19 #include "../stdafx.h" 20 #include "../date_func.h" 21 #include "../map_func.h" 27 #include "../core/endian_func.hpp" 28 #include "../company_base.h" 29 #include "../thread/thread.h" 31 #include "../newgrf_text.h" 32 #include "../strings_func.h" 33 #include "table/strings.h" 37 #include "../safeguards.h" 88 if (_udp_client_socket != NULL) _udp_client_socket->
SendPacket(&p, address);
197 this->SendNetworkGameInfo(&packet, &ngi);
200 this->SendPacket(&packet, client_addr);
221 static const uint MIN_CI_SIZE = 54;
234 FOR_ALL_COMPANIES(company) {
237 GetString(company_name, STR_COMPANY_NAME, company_name + max_cname_length - 1);
239 free -= (int)strlen(company_name);
241 if (free >= 0)
break;
244 assert(max_cname_length > 0);
251 FOR_ALL_COMPANIES(company) {
253 this->SendCompanyInformation(&packet, company, &company_stats[company->
index], max_cname_length);
256 this->SendPacket(&packet, client_addr);
278 uint8 in_reply_count = 0;
279 size_t packet_len = 0;
286 for (i = 0; i < num_grfs; i++) {
290 this->ReceiveGRFIdentifier(p, &c);
294 if (f == NULL)
continue;
304 in_reply[in_reply_count] = f;
308 if (in_reply_count == 0)
return;
312 for (i = 0; i < in_reply_count; i++) {
317 this->SendGRFIdentifier(&packet, &in_reply[i]->ident);
321 this->SendPacket(&packet, client_addr);
332 virtual void HandleIncomingNetworkGameInfoGRFConfig(
GRFConfig *config);
350 this->ReceiveNetworkGameInfo(p, &item->info);
352 item->info.compatible =
true;
363 uint in_request_count = 0;
365 for (c = item->
info.grfconfig; c != NULL; c = c->
next) {
368 in_request[in_request_count] = c;
372 if (in_request_count > 0) {
378 for (i = 0; i < in_request_count; i++) {
379 this->SendGRFIdentifier(&packet, &in_request[i]->ident);
382 this->SendPacket(&packet, &item->address);
386 if (item->info.hostname[0] ==
'\0') {
390 if (client_addr->
GetAddress()->ss_family == AF_INET6) {
391 strecat(item->info.server_name,
" (IPv6)",
lastof(item->info.server_name));
396 item->info.compatible &= item->info.version_compatible;
415 sockaddr_storage addr_storage;
416 memset(&addr_storage, 0,
sizeof(addr_storage));
419 addr_storage.ss_family = AF_INET;
420 ((sockaddr_in*)&addr_storage)->sin_addr.s_addr = TO_LE32(p->
Recv_uint32());
423 addr_storage.ss_family = AF_INET6;
424 byte *addr = (byte*)&((sockaddr_in6*)&addr_storage)->sin6_addr;
425 for (uint i = 0; i <
sizeof(in6_addr); i++) *addr++ = p->
Recv_uint8();
431 if (this->HasClientQuit())
return;
449 for (i = 0; i < num_grfs; i++) {
453 this->ReceiveGRFIdentifier(p, &c);
478 config->
name->Release();
480 config->
name->AddRef();
484 config->
name->Release();
486 config->
name->AddRef();
487 config->
info->Release();
489 config->
info->AddRef();
490 config->
url->Release();
492 config->
url->AddRef();
503 DEBUG(net, 4,
"[udp] broadcasting to %s", addr->GetHostname());
520 _udp_client_socket->
SendPacket(&p, &out_addr,
true);
531 DEBUG(net, 0,
"[udp] searching server");
543 DEBUG(net, 1,
"[udp] removing advertise from master server");
555 if (_udp_master_socket != NULL) _udp_master_socket->
SendPacket(&p, &out_addr,
true);
582 DEBUG(net, 1,
"[udp] advertising to master server");
585 static byte session_key_retries = 0;
587 DEBUG(net, 0,
"[udp] advertising to the master server is failing");
588 DEBUG(net, 0,
"[udp] we are not receiving the session key from the server");
589 DEBUG(net, 0,
"[udp] please allow udp packets from %s to you to be delivered", out_addr.
GetAddressAsString(
false));
590 DEBUG(net, 0,
"[udp] please allow udp packets from you to %s to be delivered", out_addr.
GetAddressAsString(
false));
593 DEBUG(net, 0,
"[udp] advertising to the master server is failing");
594 DEBUG(net, 0,
"[udp] we are not receiving the acknowledgement from the server");
595 DEBUG(net, 0,
"[udp] this usually means that the master server cannot reach us");
609 if (_udp_master_socket != NULL) _udp_master_socket->
SendPacket(&p, &out_addr,
true);
619 static uint32 _last_advertisement = 0;
620 static uint32 _next_advertisement = 0;
621 static uint32 _next_retry = 0;
648 if (_next_advertisement < _last_advertisement) _next_advertisement = UINT32_MAX;
649 if (_next_retry < _last_advertisement) _next_retry = UINT32_MAX;
662 DEBUG(net, 1,
"[udp] initializing listeners");
663 assert(_udp_client_socket == NULL && _udp_server_socket == NULL && _udp_master_socket == NULL);
686 _udp_server_socket->
Close();
687 _udp_master_socket->
Close();
688 _udp_client_socket->
Close();
692 _udp_client_socket = NULL;
693 _udp_server_socket = NULL;
694 _udp_master_socket = NULL;
699 DEBUG(net, 1,
"[udp] closed listeners");
Date start_date
When the game started.
byte spectators_max
Max spectators allowed on server.
uint16 map_height
Map height.
Autodetect the type based on the connection.
static uint MapSizeX()
Get the size of the map along the X.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
bool _networking
are we in networking mode?
Simpler wrapper struct for NetworkUDPQueryServerThread.
bool IsNetworkCompatibleVersion(const char *other)
Checks whether the given version string is compatible with our version.
static uint MapSizeY()
Get the size of the map along the Y.
uint32 _realtime_tick
The real time in the game.
Internal entity of a packet.
bool server_advertise
advertise the server to the masterserver
GRFConfig * _grfconfig
First item in list of current GRF set up.
byte landscape
the landscape we're currently in
static char * strecat(char *dst, const char *src, const char *last)
Appends characters from one string to another.
void GetBindAddresses(NetworkAddressList *addresses, uint16 port)
Get the addresses to bind to.
uint32 Recv_uint32()
Read a 32 bits integer from the packet.
Queries a game server for game information.
*** Communication with servers (we are client) ***/
virtual void Receive_MASTER_RESPONSE_LIST(Packet *p, NetworkAddress *client_addr)
The server sends a list of servers.
char server_name[NETWORK_NAME_LENGTH]
name of the server
sockaddr_storage address
The resolved address.
Requests the name for a list of GRFs (GRF_ID and MD5)
void ReceivePackets()
Receive a packet at UDP level.
void ClearGRFConfigList(GRFConfig **config)
Clear a GRF Config list, freeing all nodes.
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
byte server_lang
Language of the server (we should make a nice table for this)
void Send_string(const char *data)
Sends a string over the network.
virtual void Receive_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr)
Return of server information to the client.
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
static void NetworkUDPQueryServerThread(void *pntr)
Threaded part for resolving the IP of a server and querying it.
NetworkUDPSocketHandler * _udp_master_socket
udp master socket
void NetworkPopulateCompanyStats(NetworkCompanyStats *stats)
Populate the company stats.
Request for serverlist from master server.
void Send_uint8(uint8 data)
Package a 8 bits integer in the packet.
uint16 _network_udp_broadcast
Timeout for the UDP broadcasts.
GRFStatus status
NOSAVE: GRFStatus, enum.
struct GRFText * text
The actual text.
virtual void Receive_CLIENT_FIND_SERVER(Packet *p, NetworkAddress *client_addr)
Queries to the server for information about the game.
static uint64 _session_key
Session key to register ourselves to the master server.
Sending and receiving UDP messages.
static const uint32 ADVERTISE_RETRY_TIMES
give up re-advertising after this much failed retries
void Clear()
Remove all items from the list.
Wrapper for (un)resolved network addresses; there's no reason to transform a numeric IP to a string a...
const T * Begin() const
Get the pointer to the first item (const)
bool manually
Did we connect manually or not?
Tindex index
Index of this pool item.
uint16 map_width
Map width.
static ThreadMutex * _network_udp_mutex
Mutex for all out threaded udp resolution and such.
Base socket handler for all UDP sockets.
#define lastof(x)
Get the last element of an fixed size array.
*** Communication with clients (we are server) ***/
GRF file was not found in the local cache.
Structure with information shown in the game list (GUI)
const GRFConfig * FindGRFConfig(uint32 grfid, FindGRFConfigMode mode, const uint8 *md5sum, uint32 desired_version)
Find a NewGRF in the scanned list.
Request to be removed from the server-list.
GRFIdentifier ident
grfid and md5sum to uniquely identify newgrfs
NetworkUDPSocketHandler * _udp_server_socket
udp server socket
virtual void EndCritical(bool allow_recursive=false)=0
End of the critical section.
virtual void Receive_SERVER_NEWGRFS(Packet *p, NetworkAddress *client_addr)
The return of the client's request of the names of some NewGRFs.
Basic data to distinguish a GRF.
const T * End() const
Get the pointer behind the last valid item (const)
bool _network_udp_server
Is the UDP server started?
struct GRFConfig * next
NOSAVE: Next item in the linked list.
char server_name[NETWORK_NAME_LENGTH]
Server name.
void NetworkUDPAdvertise()
Register us to the master server This function checks if it needs to send an advertise.
void UpdateNetworkGameWindow()
Update the network new window because a new server is found on the network.
bool _network_dedicated
are we a dedicated server?
The game information that is sent from the server to the clients.
byte companies_max
Max companies allowed on server.
static const uint NETWORK_GRF_NAME_LENGTH
Maximum length of the name of a GRF.
static void NetworkUDPAdvertiseThread(void *pntr)
Thread entry point for advertising.
NetworkAddressList _broadcast_list
List of broadcast addresses.
static const byte NETWORK_MASTER_SERVER_VERSION
What version of master-server-protocol do we use?
NetworkSettings network
settings related to the network
NetworkGameList * NetworkGameListAddItem(NetworkAddress address)
Add a new item to the linked gamelist.
GRFTextWrapper * FindUnknownGRFName(uint32 grfid, uint8 *md5sum, bool create)
Finds the name of a NewGRF in the list of names for unknown GRFs.
virtual void HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config)
Function that is called for every GRFConfig that is read when receiving a NetworkGameInfo.
byte companies_on
How many started companies do we have.
void NetworkUDPSearchGame()
Find all servers.
void Send_uint64(uint64 data)
Package a 64 bits integer in the packet.
*** Communication with the masterserver ***/
Information about GRF, used in the game and (part of it) in savegames.
void AddGRFTextToList(GRFText **list, GRFText *text_to_add)
Add a GRFText to a GRFText list.
uint8 max_spectators
maximum amount of spectators
void Send_uint16(uint16 data)
Package a 16 bits integer in the packet.
bool _network_need_advertise
Whether we need to advertise.
byte clients_max
Max clients allowed on server.
static void NetworkUDPRemoveAdvertiseThread(void *pntr)
Thread entry point for de-advertising.
static const char *const NETWORK_MASTER_SERVER_HOST
DNS hostname of the masterserver.
ClientSettings _settings_client
The current settings for this game.
Packet to register itself to the master server.
void NetworkUDPQueryMasterServer()
Request the the server-list from the master server.
The data is copied from a grf in _all_grfs.
static void NetworkUDPBroadCast(NetworkUDPSocketHandler *socket)
Broadcast to all ips.
bool use_password
Is this server passworded?
NetworkUDPQueryServerInfo(const NetworkAddress &address, bool manually)
Create the structure.
virtual void Receive_CLIENT_GET_NEWGRFS(Packet *p, NetworkAddress *client_addr)
A client has requested the names of some NewGRFs.
static ThreadMutex * New()
Create a new mutex.
Reply of the game server about details of the game, such as companies.
uint8 flags
NOSAVE: GCF_Flags, bitset.
ServerListType
The types of server lists we can get.
NetworkAddress address
The connection info of the game server.
const char * GetHostname()
Get the hostname; in case it wasn't given the IPv4 dotted representation is given.
byte clients_on
Current count of clients on server.
NetworkGameInfo info
The game information of this server.
char server_revision[NETWORK_REVISION_LENGTH]
The version number the server is using (e.g.: 'r304' or 0.5.0)
Basic functions/variables used all over the place.
PacketSize size
The size of the whole packet for received packets.
static const char *const NETWORK_MASTER_SERVER_WELCOME_MESSAGE
Message sent to the masterserver to 'identify' this client as OpenTTD.
NetworkServerGameInfo _network_game_info
Information about our game.
static T min(const T a, const T b)
Returns the minimum of two values.
uint8 server_lang
language of the server
Reference counted wrapper around a GRFText pointer.
bool dedicated
Is this a dedicated server?
Maximum number of companies.
void SendPacket(Packet *p, NetworkAddress *recv, bool all=false, bool broadcast=false)
Send a packet over UDP.
ServerNetworkUDPSocketHandler(NetworkAddressList *addresses)
Create the socket.
uint8 max_companies
maximum amount of companies
#define DEBUG(name, level,...)
Output a line of debugging information.
void SetPort(uint16 port)
Set the port.
Sends the list of NewGRF's requested.
void NetworkUDPInitialize()
Initialize the whole UDP bit.
GRFTextWrapper * url
NOSAVE: URL belonging to this GRF.
char map_name[NETWORK_NAME_LENGTH]
Map which is played ["random" for a randomized map].
uint16 server_port
port the server listens on
byte map_set
Graphical set.
NetworkUDPSocketHandler * _udp_client_socket
udp client socket
Date game_date
Current date.
void Close()
Close the given UDP socket.
const char * GetGRFStringFromGRFText(const GRFText *text)
Get a C-string from a GRFText-list.
virtual void Receive_MASTER_ACK_REGISTER(Packet *p, NetworkAddress *client_addr)
The master server acknowledges the registration.
uint8 Recv_uint8()
Read a 8 bits integer from the packet.
virtual void Receive_MASTER_SESSION_KEY(Packet *p, NetworkAddress *client_addr)
The master server sends us a session key.
uint64 Recv_uint64()
Read a 64 bits integer from the packet.
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
virtual void Receive_CLIENT_DETAIL_INFO(Packet *p, NetworkAddress *client_addr)
Query for detailed information about companies.
Variables and function used internally.
static size_t GetNumItems()
Returns number of valid items in the pool.
#define UNKNOWN_GRF_NAME_PLACEHOLDER
For communication about GRFs over the network.
Handling of the list of games.
static const uint32 ADVERTISE_NORMAL_INTERVAL
interval between advertising in ms (15 minutes)
void NetworkBackgroundUDPLoop()
Receive the UDP packets.
void NetworkGameListAddItemDelayed(NetworkGameList *item)
Add a new item to the linked gamelist, but do it delayed in the next tick or so to prevent race condi...
uint8 max_clients
maximum amount of clients
static const uint NETWORK_COMPANY_NAME_LENGTH
The maximum length of the company name, in bytes including '\0'.
static const uint32 ADVERTISE_RETRY_INTERVAL
re-advertise when no response after this many ms (10 seconds)
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
char * filename
Filename - either with or without full path.
static const char * AddressFamilyAsString(int family)
Convert the address family into a string.
static const uint16 SEND_MTU
Number of bytes we can pack in a single packet.
GRFTextWrapper * name
NOSAVE: GRF name (Action 0x08)
MasterNetworkUDPSocketHandler(NetworkAddressList *addresses)
Create the socket.
static void NetworkUDPQueryServer(NetworkAddress *address, bool needs_mutex, bool manually)
Helper function doing the actual work for querying the server.
bool _network_server
network-server is active
bool manually
True if the server was added manually.
void NetworkUDPRemoveAdvertise(bool blocking)
Remove our advertise from the master-server.
const char * GetName() const
Get the name of this grf.
uint32 grfid
GRF ID (defined by Action 0x08)
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Reply of the game server with game information.
Simple calculated statistics of a company.
uint8 _network_advertise_retries
The number of advertisement retries we did.
char hostname[NETWORK_HOSTNAME_LENGTH]
Hostname of the server (if any)
End of 'arrays' marker.
GameCreationSettings game_creation
settings used during the creation of a game (map)
Date ConvertYMDToDate(Year year, Month month, Day day)
Converts a tuple of Year, Month and Day to a Date.
uint16 Recv_uint16()
Read a 16 bits integer from the packet.
virtual void BeginCritical(bool allow_recursive=false)=0
Begin the critical section.
uint8 md5sum[16]
MD5 checksum of file to distinguish files with the same GRF ID (eg. newer version of GRF) ...
Only find Grfs matching md5sum.
static const byte NETWORK_COMPANY_INFO_VERSION
What version of company info is this?
char server_password[NETWORK_PASSWORD_LENGTH]
password for joining this server
void NetworkUDPClose()
Close all UDP related stuff.
Date _date
Current date in days (day counter)
GRFConfig * grfconfig
List of NewGRF files used.
static bool New(OTTDThreadFunc proc, void *param, ThreadObject **thread=NULL, const char *name=NULL)
Create a thread; proc will be called as first function inside the thread, with optional params...
Year starting_year
starting date
Basic functions to receive and send UDP packets.
static const uint16 NETWORK_MASTER_SERVER_PORT
The default port of the master server (UDP)
const sockaddr_storage * GetAddress()
Get the address in its internal representation.
void GetAddressAsString(char *buffer, const char *last, bool with_family=true)
Get the address as a string, e.g.
byte spectators_on
How many spectators do we have?
static const uint NETWORK_MAX_GRF_COUNT
Maximum number of GRFs that can be sent.
void Recv_string(char *buffer, size_t size, StringValidationSettings settings=SVS_REPLACE_WITH_QUESTION_MARK)
Reads a string till it finds a '\0' in the stream.
bool IsResolved() const
Check whether the IP address has been resolved already.
GRFTextWrapper * info
NOSAVE: GRF info (author, copyright, ...) (Action 0x08)
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.