15 #include "../stdafx.h" 16 #include "../date_func.h" 17 #include "../map_func.h" 23 #include "../core/endian_func.hpp" 24 #include "../company_base.h" 25 #include "../thread.h" 27 #include "../newgrf_text.h" 28 #include "../strings_func.h" 29 #include "table/strings.h" 34 #include "../safeguards.h" 67 if (needs_mutex) lock.lock();
70 if (_udp_client_socket !=
nullptr) _udp_client_socket->
SendPacket(&p, &address);
189 static const uint MIN_CI_SIZE = 54;
204 GetString(company_name, STR_COMPANY_NAME, company_name + max_cname_length - 1);
206 free -= (int)strlen(company_name);
208 if (free >= 0)
break;
211 assert(max_cname_length > 0);
244 uint8 in_reply_count = 0;
245 size_t packet_len = 0;
252 for (i = 0; i < num_grfs; i++) {
260 if (f ==
nullptr)
continue;
270 in_reply[in_reply_count] = f;
274 if (in_reply_count == 0)
return;
278 for (i = 0; i < in_reply_count; i++) {
318 item->info.compatible =
true;
329 uint in_request_count = 0;
331 for (c = item->
info.grfconfig; c !=
nullptr; c = c->
next) {
334 in_request[in_request_count] = c;
338 if (in_request_count > 0) {
344 for (i = 0; i < in_request_count; i++) {
352 if (item->info.hostname[0] ==
'\0') {
356 if (client_addr->
GetAddress()->ss_family == AF_INET6) {
357 strecat(item->info.server_name,
" (IPv6)",
lastof(item->info.server_name));
362 item->info.compatible &= item->info.version_compatible;
381 sockaddr_storage addr_storage;
382 memset(&addr_storage, 0,
sizeof(addr_storage));
385 addr_storage.ss_family = AF_INET;
386 ((sockaddr_in*)&addr_storage)->sin_addr.s_addr = TO_LE32(p->
Recv_uint32());
389 addr_storage.ss_family = AF_INET6;
390 byte *addr = (byte*)&((sockaddr_in6*)&addr_storage)->sin6_addr;
391 for (uint i = 0; i <
sizeof(in6_addr); i++) *addr++ = p->
Recv_uint8();
415 for (i = 0; i < num_grfs; i++) {
444 config->
name->Release();
446 config->
name->AddRef();
450 config->
name->Release();
452 config->
name->AddRef();
453 config->
info->Release();
455 config->
info->AddRef();
456 config->
url->Release();
458 config->
url->AddRef();
469 DEBUG(net, 4,
"[udp] broadcasting to %s", addr.GetHostname());
486 _udp_client_socket->
SendPacket(&p, &out_addr,
true);
497 DEBUG(net, 0,
"[udp] searching server");
508 DEBUG(net, 1,
"[udp] removing advertise from master server");
520 if (_udp_master_socket !=
nullptr) _udp_master_socket->
SendPacket(&p, &out_addr,
true);
545 DEBUG(net, 1,
"[udp] advertising to master server");
548 static byte session_key_retries = 0;
550 DEBUG(net, 0,
"[udp] advertising to the master server is failing");
551 DEBUG(net, 0,
"[udp] we are not receiving the session key from the server");
552 DEBUG(net, 0,
"[udp] please allow udp packets from %s to you to be delivered", out_addr.
GetAddressAsString(
false));
553 DEBUG(net, 0,
"[udp] please allow udp packets from you to %s to be delivered", out_addr.
GetAddressAsString(
false));
556 DEBUG(net, 0,
"[udp] advertising to the master server is failing");
557 DEBUG(net, 0,
"[udp] we are not receiving the acknowledgement from the server");
558 DEBUG(net, 0,
"[udp] this usually means that the master server cannot reach us");
572 if (_udp_master_socket !=
nullptr) _udp_master_socket->
SendPacket(&p, &out_addr,
true);
581 static uint32 _last_advertisement = 0;
582 static uint32 _next_advertisement = 0;
583 static uint32 _next_retry = 0;
610 if (_next_advertisement < _last_advertisement) _next_advertisement = UINT32_MAX;
611 if (_next_retry < _last_advertisement) _next_retry = UINT32_MAX;
624 DEBUG(net, 1,
"[udp] initializing listeners");
625 assert(_udp_client_socket ==
nullptr && _udp_server_socket ==
nullptr && _udp_master_socket ==
nullptr);
647 _udp_server_socket->
Close();
648 _udp_master_socket->
Close();
649 _udp_client_socket->
Close();
653 _udp_client_socket =
nullptr;
654 _udp_server_socket =
nullptr;
655 _udp_master_socket =
nullptr;
659 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?
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.
bool HasClientQuit() const
Whether the current client connected to the socket has quit.
virtual void Receive_CLIENT_GET_NEWGRFS(Packet *p, NetworkAddress *client_addr)
The client requests information about some NewGRFs.
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.
void Receive_SERVER_NEWGRFS(Packet *p, NetworkAddress *client_addr) override
The return of the client's request of the names of some NewGRFs.
Queries a game server for game information.
*** Communication with servers (we are client) ***/
char server_name[NETWORK_NAME_LENGTH]
name of the server
Requests the name for a list of GRFs (GRF_ID and MD5)
static void NetworkUDPAdvertiseThread()
Thread entry point for advertising.
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.
NetworkUDPSocketHandler * _udp_master_socket
udp master socket
void NetworkPopulateCompanyStats(NetworkCompanyStats *stats)
Populate the company stats.
void Receive_MASTER_SESSION_KEY(Packet *p, NetworkAddress *client_addr) override
The master server sends us a session key.
Request for serverlist from master server.
void SendNetworkGameInfo(Packet *p, const NetworkGameInfo *info)
Serializes the NetworkGameInfo struct to the packet.
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.
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 HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config) override
Function that is called for every GRFConfig that is read when receiving a NetworkGameInfo.
Wrapper for (un)resolved network addresses; there's no reason to transform a numeric IP to a string a...
uint16 map_width
Map width.
Base socket handler for all UDP sockets.
#define lastof(x)
Get the last element of an fixed size array.
void Receive_MASTER_ACK_REGISTER(Packet *p, NetworkAddress *client_addr) override
The master server acknowledges the registration.
*** 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 char * GetNetworkRevisionString()
Get the network version string used by this build.
void NetworkUDPQueryServer(NetworkAddress address, bool manually)
Query a specific server.
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
Basic data to distinguish a GRF.
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.
std::vector< NetworkAddress > NetworkAddressList
Type for a list of addresses.
bool StartNewThread(std::thread *thr, const char *name, TFn &&_Fx, TArgs &&... _Ax)
Start a new thread.
virtual void Receive_CLIENT_FIND_SERVER(Packet *p, NetworkAddress *client_addr)
Queries to the server for information about the game.
static const uint NETWORK_GRF_NAME_LENGTH
Maximum length of the name of a GRF.
NetworkAddressList _broadcast_list
List of broadcast addresses.
virtual void HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config)
Function that is called for every GRFConfig that is read when receiving a NetworkGameInfo.
void Receive_CLIENT_FIND_SERVER(Packet *p, NetworkAddress *client_addr) override
Queries to the server for information about the game.
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.
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 SendCompanyInformation(Packet *p, const struct Company *c, const struct NetworkCompanyStats *stats, uint max_len=NETWORK_COMPANY_NAME_LENGTH)
Package some generic company information into a packet.
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 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.
std::mutex lock
synchronization for playback status fields
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?
virtual void Receive_SERVER_NEWGRFS(Packet *p, NetworkAddress *client_addr)
The server returns information about some NewGRFs.
void Close() override
Close the given UDP socket.
static std::mutex _network_udp_mutex
Mutex for all out threaded udp resolution and such.
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)
void Receive_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr) override
Return of server information to the client.
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.
void Receive_CLIENT_DETAIL_INFO(Packet *p, NetworkAddress *client_addr) override
Query for detailed information about companies.
virtual void Receive_CLIENT_DETAIL_INFO(Packet *p, NetworkAddress *client_addr)
Query for detailed information about companies.
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?
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.
const char * GetGRFStringFromGRFText(const GRFText *text)
Get a C-string from a GRFText-list.
uint8 Recv_uint8()
Read a 8 bits integer from the packet.
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
uint64 Recv_uint64()
Read a 64 bits integer from the packet.
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Variables and function used internally.
static void NetworkUDPRemoveAdvertiseThread()
Thread entry point for de-advertising.
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...
static void DoNetworkUDPQueryServer(NetworkAddress &address, bool needs_mutex, bool manually)
Helper function doing the actual work for querying the server.
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.
Maximum number of companies.
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.
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.
void ReceiveNetworkGameInfo(Packet *p, NetworkGameInfo *info)
Deserializes the NetworkGameInfo struct from the packet.
void Receive_CLIENT_GET_NEWGRFS(Packet *p, NetworkAddress *client_addr) override
A client has requested the names of some NewGRFs.
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.
virtual void Receive_MASTER_RESPONSE_LIST(Packet *p, NetworkAddress *client_addr)
The server sends a list of servers.
void Receive_MASTER_RESPONSE_LIST(Packet *p, NetworkAddress *client_addr) override
The server sends a list of servers.
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)
void ReceiveGRFIdentifier(Packet *p, GRFIdentifier *grf)
Deserializes the GRFIdentifier (GRF ID and MD5 checksum) from the packet.
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.
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.
void SendGRFIdentifier(Packet *p, const GRFIdentifier *grf)
Serializes the GRFIdentifier (GRF ID and MD5 checksum) to the packet.
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.