Maintain a circular buffer of recent commands, add to crashlog.
[openttd-joker.git] / src / network / network_udp.cpp
blob6128c459ce899d809458adbe140eb62a30f6064c
1 /* $Id: network_udp.cpp 24900 2013-01-08 22:46:42Z planetmaker $ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /**
11 * @file network_udp.cpp This file handles the UDP related communication.
13 * This is the GameServer <-> MasterServer and GameServer <-> GameClient
14 * communication before the game is being joined.
17 #ifdef ENABLE_NETWORK
19 #include "../stdafx.h"
20 #include "../date_func.h"
21 #include "../map_func.h"
22 #include "../debug.h"
23 #include "network_gamelist.h"
24 #include "network_internal.h"
25 #include "network_udp.h"
26 #include "network.h"
27 #include "../core/endian_func.hpp"
28 #include "../company_base.h"
29 #include "../thread/thread.h"
30 #include "../rev.h"
31 #include "../newgrf_text.h"
32 #include "../strings_func.h"
33 #include "table/strings.h"
35 #include "core/udp.h"
37 #include "../safeguards.h"
39 /** Mutex for all out threaded udp resolution and such. */
40 static ThreadMutex *_network_udp_mutex = ThreadMutex::New();
42 /** Session key to register ourselves to the master server */
43 static uint64 _session_key = 0;
45 static const uint32 ADVERTISE_NORMAL_INTERVAL = 15 * 60 * 1000; ///< interval between advertising in ms (15 minutes)
46 static const uint32 ADVERTISE_RETRY_INTERVAL = 10 * 1000; ///< re-advertise when no response after this many ms (10 seconds)
47 static const uint32 ADVERTISE_RETRY_TIMES = 3; ///< give up re-advertising after this much failed retries
49 NetworkUDPSocketHandler *_udp_client_socket = NULL; ///< udp client socket
50 NetworkUDPSocketHandler *_udp_server_socket = NULL; ///< udp server socket
51 NetworkUDPSocketHandler *_udp_master_socket = NULL; ///< udp master socket
53 /** Simpler wrapper struct for NetworkUDPQueryServerThread */
54 struct NetworkUDPQueryServerInfo : NetworkAddress {
55 bool manually; ///< Did we connect manually or not?
57 /**
58 * Create the structure.
59 * @param address The address of the server to query.
60 * @param manually Whether the address was entered manually.
62 NetworkUDPQueryServerInfo(const NetworkAddress &address, bool manually) :
63 NetworkAddress(address),
64 manually(manually)
69 /**
70 * Helper function doing the actual work for querying the server.
71 * @param address The address of the server.
72 * @param needs_mutex Whether we need to acquire locks when sending the packet or not.
73 * @param manually Whether the address was entered manually.
75 static void NetworkUDPQueryServer(NetworkAddress *address, bool needs_mutex, bool manually)
77 /* Clear item in gamelist */
78 NetworkGameList *item = CallocT<NetworkGameList>(1);
79 address->GetAddressAsString(item->info.server_name, lastof(item->info.server_name));
80 strecpy(item->info.hostname, address->GetHostname(), lastof(item->info.hostname));
81 item->address = *address;
82 item->manually = manually;
83 NetworkGameListAddItemDelayed(item);
85 if (needs_mutex) _network_udp_mutex->BeginCritical();
86 /* Init the packet */
87 Packet p(PACKET_UDP_CLIENT_FIND_SERVER);
88 if (_udp_client_socket != NULL) _udp_client_socket->SendPacket(&p, address);
89 if (needs_mutex) _network_udp_mutex->EndCritical();
92 /**
93 * Threaded part for resolving the IP of a server and querying it.
94 * @param pntr the NetworkUDPQueryServerInfo.
96 static void NetworkUDPQueryServerThread(void *pntr)
98 NetworkUDPQueryServerInfo *info = (NetworkUDPQueryServerInfo*)pntr;
99 NetworkUDPQueryServer(info, true, info->manually);
101 delete info;
105 * Query a specific server.
106 * @param address The address of the server.
107 * @param manually Whether the address was entered manually.
109 void NetworkUDPQueryServer(NetworkAddress address, bool manually)
111 NetworkUDPQueryServerInfo *info = new NetworkUDPQueryServerInfo(address, manually);
112 if (address.IsResolved() || !ThreadObject::New(NetworkUDPQueryServerThread, info, NULL, "ottd:udp-query")) {
113 NetworkUDPQueryServerThread(info);
117 ///*** Communication with the masterserver ***/
119 /** Helper class for connecting to the master server. */
120 class MasterNetworkUDPSocketHandler : public NetworkUDPSocketHandler {
121 protected:
122 virtual void Receive_MASTER_ACK_REGISTER(Packet *p, NetworkAddress *client_addr);
123 virtual void Receive_MASTER_SESSION_KEY(Packet *p, NetworkAddress *client_addr);
124 public:
126 * Create the socket.
127 * @param addresses The addresses to bind on.
129 MasterNetworkUDPSocketHandler(NetworkAddressList *addresses) : NetworkUDPSocketHandler(addresses) {}
130 virtual ~MasterNetworkUDPSocketHandler() {}
133 void MasterNetworkUDPSocketHandler::Receive_MASTER_ACK_REGISTER(Packet *p, NetworkAddress *client_addr)
135 _network_advertise_retries = 0;
136 DEBUG(net, 2, "[udp] advertising on master server successful (%s)", NetworkAddress::AddressFamilyAsString(client_addr->GetAddress()->ss_family));
138 /* We are advertised, but we don't want to! */
139 if (!_settings_client.network.server_advertise) NetworkUDPRemoveAdvertise(false);
142 void MasterNetworkUDPSocketHandler::Receive_MASTER_SESSION_KEY(Packet *p, NetworkAddress *client_addr)
144 _session_key = p->Recv_uint64();
145 DEBUG(net, 2, "[udp] received new session key from master server (%s)", NetworkAddress::AddressFamilyAsString(client_addr->GetAddress()->ss_family));
148 ///*** Communication with clients (we are server) ***/
150 /** Helper class for handling all server side communication. */
151 class ServerNetworkUDPSocketHandler : public NetworkUDPSocketHandler {
152 protected:
153 virtual void Receive_CLIENT_FIND_SERVER(Packet *p, NetworkAddress *client_addr);
154 virtual void Receive_CLIENT_DETAIL_INFO(Packet *p, NetworkAddress *client_addr);
155 virtual void Receive_CLIENT_GET_NEWGRFS(Packet *p, NetworkAddress *client_addr);
156 public:
158 * Create the socket.
159 * @param addresses The addresses to bind on.
161 ServerNetworkUDPSocketHandler(NetworkAddressList *addresses) : NetworkUDPSocketHandler(addresses) {}
162 virtual ~ServerNetworkUDPSocketHandler() {}
165 void ServerNetworkUDPSocketHandler::Receive_CLIENT_FIND_SERVER(Packet *p, NetworkAddress *client_addr)
167 /* Just a fail-safe.. should never happen */
168 if (!_network_udp_server) {
169 return;
172 NetworkGameInfo ngi;
174 /* Update some game_info */
175 ngi.clients_on = _network_game_info.clients_on;
176 ngi.start_date = ConvertYMDToDate(_settings_game.game_creation.starting_year, 0, 1);
178 ngi.server_lang = _settings_client.network.server_lang;
179 ngi.use_password = !StrEmpty(_settings_client.network.server_password);
180 ngi.clients_max = _settings_client.network.max_clients;
181 ngi.companies_on = (byte)Company::GetNumItems();
182 ngi.companies_max = _settings_client.network.max_companies;
183 ngi.spectators_on = NetworkSpectatorCount();
184 ngi.spectators_max = _settings_client.network.max_spectators;
185 ngi.game_date = _date;
186 ngi.map_width = MapSizeX();
187 ngi.map_height = MapSizeY();
188 ngi.map_set = _settings_game.game_creation.landscape;
189 ngi.dedicated = _network_dedicated;
190 ngi.grfconfig = _grfconfig;
192 strecpy(ngi.map_name, _network_game_info.map_name, lastof(ngi.map_name));
193 strecpy(ngi.server_name, _settings_client.network.server_name, lastof(ngi.server_name));
194 strecpy(ngi.server_revision, _openttd_revision, lastof(ngi.server_revision));
196 Packet packet(PACKET_UDP_SERVER_RESPONSE);
197 this->SendNetworkGameInfo(&packet, &ngi);
199 /* Let the client know that we are here */
200 this->SendPacket(&packet, client_addr);
202 DEBUG(net, 2, "[udp] queried from %s", client_addr->GetHostname());
205 void ServerNetworkUDPSocketHandler::Receive_CLIENT_DETAIL_INFO(Packet *p, NetworkAddress *client_addr)
207 /* Just a fail-safe.. should never happen */
208 if (!_network_udp_server) return;
210 Packet packet(PACKET_UDP_SERVER_DETAIL_INFO);
212 /* Send the amount of active companies */
213 packet.Send_uint8 (NETWORK_COMPANY_INFO_VERSION);
214 packet.Send_uint8 ((uint8)Company::GetNumItems());
216 /* Fetch the latest version of the stats */
217 NetworkCompanyStats company_stats[MAX_COMPANIES];
218 NetworkPopulateCompanyStats(company_stats);
220 /* The minimum company information "blob" size. */
221 static const uint MIN_CI_SIZE = 54;
222 uint max_cname_length = NETWORK_COMPANY_NAME_LENGTH;
224 if (Company::GetNumItems() * (MIN_CI_SIZE + NETWORK_COMPANY_NAME_LENGTH) >= (uint)SEND_MTU - packet.size) {
225 /* Assume we can at least put the company information in the packets. */
226 assert(Company::GetNumItems() * MIN_CI_SIZE < (uint)SEND_MTU - packet.size);
228 /* At this moment the company names might not fit in the
229 * packet. Check whether that is really the case. */
231 for (;;) {
232 int free = SEND_MTU - packet.size;
233 Company *company;
234 FOR_ALL_COMPANIES(company) {
235 char company_name[NETWORK_COMPANY_NAME_LENGTH];
236 SetDParam(0, company->index);
237 GetString(company_name, STR_COMPANY_NAME, company_name + max_cname_length - 1);
238 free -= MIN_CI_SIZE;
239 free -= (int)strlen(company_name);
241 if (free >= 0) break;
243 /* Try again, with slightly shorter strings. */
244 assert(max_cname_length > 0);
245 max_cname_length--;
249 Company *company;
250 /* Go through all the companies */
251 FOR_ALL_COMPANIES(company) {
252 /* Send the information */
253 this->SendCompanyInformation(&packet, company, &company_stats[company->index], max_cname_length);
256 this->SendPacket(&packet, client_addr);
260 * A client has requested the names of some NewGRFs.
262 * Replying this can be tricky as we have a limit of SEND_MTU bytes
263 * in the reply packet and we can send up to 100 bytes per NewGRF
264 * (GRF ID, MD5sum and NETWORK_GRF_NAME_LENGTH bytes for the name).
265 * As SEND_MTU is _much_ less than 100 * NETWORK_MAX_GRF_COUNT, it
266 * could be that a packet overflows. To stop this we only reply
267 * with the first N NewGRFs so that if the first N + 1 NewGRFs
268 * would be sent, the packet overflows.
269 * in_reply and in_reply_count are used to keep a list of GRFs to
270 * send in the reply.
272 void ServerNetworkUDPSocketHandler::Receive_CLIENT_GET_NEWGRFS(Packet *p, NetworkAddress *client_addr)
274 uint8 num_grfs;
275 uint i;
277 const GRFConfig *in_reply[NETWORK_MAX_GRF_COUNT];
278 uint8 in_reply_count = 0;
279 size_t packet_len = 0;
281 DEBUG(net, 6, "[udp] newgrf data request from %s", client_addr->GetAddressAsString());
283 num_grfs = p->Recv_uint8 ();
284 if (num_grfs > NETWORK_MAX_GRF_COUNT) return;
286 for (i = 0; i < num_grfs; i++) {
287 GRFIdentifier c;
288 const GRFConfig *f;
290 this->ReceiveGRFIdentifier(p, &c);
292 /* Find the matching GRF file */
293 f = FindGRFConfig(c.grfid, FGCM_EXACT, c.md5sum);
294 if (f == NULL) continue; // The GRF is unknown to this server
296 /* If the reply might exceed the size of the packet, only reply
297 * the current list and do not send the other data.
298 * The name could be an empty string, if so take the filename. */
299 packet_len += sizeof(c.grfid) + sizeof(c.md5sum) +
300 min(strlen(f->GetName()) + 1, (size_t)NETWORK_GRF_NAME_LENGTH);
301 if (packet_len > SEND_MTU - 4) { // 4 is 3 byte header + grf count in reply
302 break;
304 in_reply[in_reply_count] = f;
305 in_reply_count++;
308 if (in_reply_count == 0) return;
310 Packet packet(PACKET_UDP_SERVER_NEWGRFS);
311 packet.Send_uint8(in_reply_count);
312 for (i = 0; i < in_reply_count; i++) {
313 char name[NETWORK_GRF_NAME_LENGTH];
315 /* The name could be an empty string, if so take the filename */
316 strecpy(name, in_reply[i]->GetName(), lastof(name));
317 this->SendGRFIdentifier(&packet, &in_reply[i]->ident);
318 packet.Send_string(name);
321 this->SendPacket(&packet, client_addr);
324 ///*** Communication with servers (we are client) ***/
326 /** Helper class for handling all client side communication. */
327 class ClientNetworkUDPSocketHandler : public NetworkUDPSocketHandler {
328 protected:
329 virtual void Receive_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr);
330 virtual void Receive_MASTER_RESPONSE_LIST(Packet *p, NetworkAddress *client_addr);
331 virtual void Receive_SERVER_NEWGRFS(Packet *p, NetworkAddress *client_addr);
332 virtual void HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config);
333 public:
334 virtual ~ClientNetworkUDPSocketHandler() {}
337 void ClientNetworkUDPSocketHandler::Receive_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr)
339 NetworkGameList *item;
341 /* Just a fail-safe.. should never happen */
342 if (_network_udp_server) return;
344 DEBUG(net, 4, "[udp] server response from %s", client_addr->GetAddressAsString());
346 /* Find next item */
347 item = NetworkGameListAddItem(*client_addr);
349 ClearGRFConfigList(&item->info.grfconfig);
350 this->ReceiveNetworkGameInfo(p, &item->info);
352 item->info.compatible = true;
354 /* Checks whether there needs to be a request for names of GRFs and makes
355 * the request if necessary. GRFs that need to be requested are the GRFs
356 * that do not exist on the clients system and we do not have the name
357 * resolved of, i.e. the name is still UNKNOWN_GRF_NAME_PLACEHOLDER.
358 * The in_request array and in_request_count are used so there is no need
359 * to do a second loop over the GRF list, which can be relatively expensive
360 * due to the string comparisons. */
361 const GRFConfig *in_request[NETWORK_MAX_GRF_COUNT];
362 const GRFConfig *c;
363 uint in_request_count = 0;
365 for (c = item->info.grfconfig; c != NULL; c = c->next) {
366 if (c->status == GCS_NOT_FOUND) item->info.compatible = false;
367 if (c->status != GCS_NOT_FOUND || strcmp(c->GetName(), UNKNOWN_GRF_NAME_PLACEHOLDER) != 0) continue;
368 in_request[in_request_count] = c;
369 in_request_count++;
372 if (in_request_count > 0) {
373 /* There are 'unknown' GRFs, now send a request for them */
374 uint i;
375 Packet packet(PACKET_UDP_CLIENT_GET_NEWGRFS);
377 packet.Send_uint8(in_request_count);
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') {
387 seprintf(item->info.hostname, lastof(item->info.hostname), "%s", client_addr->GetHostname());
390 if (client_addr->GetAddress()->ss_family == AF_INET6) {
391 strecat(item->info.server_name, " (IPv6)", lastof(item->info.server_name));
394 /* Check if we are allowed on this server based on the revision-match */
395 item->info.version_compatible = IsNetworkCompatibleVersion(item->info.server_revision);
396 item->info.compatible &= item->info.version_compatible; // Already contains match for GRFs
398 item->online = true;
400 UpdateNetworkGameWindow();
403 void ClientNetworkUDPSocketHandler::Receive_MASTER_RESPONSE_LIST(Packet *p, NetworkAddress *client_addr)
405 /* packet begins with the protocol version (uint8)
406 * then an uint16 which indicates how many
407 * ip:port pairs are in this packet, after that
408 * an uint32 (ip) and an uint16 (port) for each pair.
411 ServerListType type = (ServerListType)(p->Recv_uint8() - 1);
413 if (type < SLT_END) {
414 for (int i = p->Recv_uint16(); i != 0 ; i--) {
415 sockaddr_storage addr_storage;
416 memset(&addr_storage, 0, sizeof(addr_storage));
418 if (type == SLT_IPv4) {
419 addr_storage.ss_family = AF_INET;
420 ((sockaddr_in*)&addr_storage)->sin_addr.s_addr = TO_LE32(p->Recv_uint32());
421 } else {
422 assert(type == SLT_IPv6);
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();
427 NetworkAddress addr(addr_storage, type == SLT_IPv4 ? sizeof(sockaddr_in) : sizeof(sockaddr_in6));
428 addr.SetPort(p->Recv_uint16());
430 /* Somehow we reached the end of the packet */
431 if (this->HasClientQuit()) return;
433 NetworkUDPQueryServer(&addr, false, false);
438 /** The return of the client's request of the names of some NewGRFs */
439 void ClientNetworkUDPSocketHandler::Receive_SERVER_NEWGRFS(Packet *p, NetworkAddress *client_addr)
441 uint8 num_grfs;
442 uint i;
444 DEBUG(net, 6, "[udp] newgrf data reply from %s", client_addr->GetAddressAsString());
446 num_grfs = p->Recv_uint8 ();
447 if (num_grfs > NETWORK_MAX_GRF_COUNT) return;
449 for (i = 0; i < num_grfs; i++) {
450 char name[NETWORK_GRF_NAME_LENGTH];
451 GRFIdentifier c;
453 this->ReceiveGRFIdentifier(p, &c);
454 p->Recv_string(name, sizeof(name));
456 /* An empty name is not possible under normal circumstances
457 * and causes problems when showing the NewGRF list. */
458 if (StrEmpty(name)) continue;
460 /* Try to find the GRFTextWrapper for the name of this GRF ID and MD5sum tuple.
461 * If it exists and not resolved yet, then name of the fake GRF is
462 * overwritten with the name from the reply. */
463 GRFTextWrapper *unknown_name = FindUnknownGRFName(c.grfid, c.md5sum, false);
464 if (unknown_name != NULL && strcmp(GetGRFStringFromGRFText(unknown_name->text), UNKNOWN_GRF_NAME_PLACEHOLDER) == 0) {
465 AddGRFTextToList(&unknown_name->text, name);
470 void ClientNetworkUDPSocketHandler::HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config)
472 /* Find the matching GRF file */
473 const GRFConfig *f = FindGRFConfig(config->ident.grfid, FGCM_EXACT, config->ident.md5sum);
474 if (f == NULL) {
475 /* Don't know the GRF, so mark game incompatible and the (possibly)
476 * already resolved name for this GRF (another server has sent the
477 * name of the GRF already */
478 config->name->Release();
479 config->name = FindUnknownGRFName(config->ident.grfid, config->ident.md5sum, true);
480 config->name->AddRef();
481 config->status = GCS_NOT_FOUND;
482 } else {
483 config->filename = f->filename;
484 config->name->Release();
485 config->name = f->name;
486 config->name->AddRef();
487 config->info->Release();
488 config->info = f->info;
489 config->info->AddRef();
490 config->url->Release();
491 config->url = f->url;
492 config->url->AddRef();
494 SetBit(config->flags, GCF_COPY);
497 /** Broadcast to all ips */
498 static void NetworkUDPBroadCast(NetworkUDPSocketHandler *socket)
500 for (NetworkAddress *addr = _broadcast_list.Begin(); addr != _broadcast_list.End(); addr++) {
501 Packet p(PACKET_UDP_CLIENT_FIND_SERVER);
503 DEBUG(net, 4, "[udp] broadcasting to %s", addr->GetHostname());
505 socket->SendPacket(&p, addr, true, true);
510 /** Request the the server-list from the master server */
511 void NetworkUDPQueryMasterServer()
513 Packet p(PACKET_UDP_CLIENT_GET_LIST);
514 NetworkAddress out_addr(NETWORK_MASTER_SERVER_HOST, NETWORK_MASTER_SERVER_PORT);
516 /* packet only contains protocol version */
517 p.Send_uint8(NETWORK_MASTER_SERVER_VERSION);
518 p.Send_uint8(SLT_AUTODETECT);
520 _udp_client_socket->SendPacket(&p, &out_addr, true);
522 DEBUG(net, 2, "[udp] master server queried at %s", out_addr.GetAddressAsString());
525 /** Find all servers */
526 void NetworkUDPSearchGame()
528 /* We are still searching.. */
529 if (_network_udp_broadcast > 0) return;
531 DEBUG(net, 0, "[udp] searching server");
533 NetworkUDPBroadCast(_udp_client_socket);
534 _network_udp_broadcast = 300; // Stay searching for 300 ticks
538 * Thread entry point for de-advertising.
539 * @param pntr unused.
541 static void NetworkUDPRemoveAdvertiseThread(void *pntr)
543 DEBUG(net, 1, "[udp] removing advertise from master server");
545 /* Find somewhere to send */
546 NetworkAddress out_addr(NETWORK_MASTER_SERVER_HOST, NETWORK_MASTER_SERVER_PORT);
548 /* Send the packet */
549 Packet p(PACKET_UDP_SERVER_UNREGISTER);
550 /* Packet is: Version, server_port */
551 p.Send_uint8 (NETWORK_MASTER_SERVER_VERSION);
552 p.Send_uint16(_settings_client.network.server_port);
554 _network_udp_mutex->BeginCritical();
555 if (_udp_master_socket != NULL) _udp_master_socket->SendPacket(&p, &out_addr, true);
556 _network_udp_mutex->EndCritical();
560 * Remove our advertise from the master-server.
561 * @param blocking whether to wait until the removal has finished.
563 void NetworkUDPRemoveAdvertise(bool blocking)
565 /* Check if we are advertising */
566 if (!_networking || !_network_server || !_network_udp_server) return;
568 if (blocking || !ThreadObject::New(NetworkUDPRemoveAdvertiseThread, NULL, NULL, "ottd:udp-advert")) {
569 NetworkUDPRemoveAdvertiseThread(NULL);
574 * Thread entry point for advertising.
575 * @param pntr unused.
577 static void NetworkUDPAdvertiseThread(void *pntr)
579 /* Find somewhere to send */
580 NetworkAddress out_addr(NETWORK_MASTER_SERVER_HOST, NETWORK_MASTER_SERVER_PORT);
582 DEBUG(net, 1, "[udp] advertising to master server");
584 /* Add a bit more messaging when we cannot get a session key */
585 static byte session_key_retries = 0;
586 if (_session_key == 0 && session_key_retries++ == 2) {
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));
592 if (_session_key != 0 && _network_advertise_retries == 0) {
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");
596 DEBUG(net, 0, "[udp] please allow udp and tcp packets to port %u to be delivered", _settings_client.network.server_port);
597 DEBUG(net, 0, "[udp] please allow udp and tcp packets from port %u to be delivered", _settings_client.network.server_port);
600 /* Send the packet */
601 Packet p(PACKET_UDP_SERVER_REGISTER);
602 /* Packet is: WELCOME_MESSAGE, Version, server_port */
603 p.Send_string(NETWORK_MASTER_SERVER_WELCOME_MESSAGE);
604 p.Send_uint8 (NETWORK_MASTER_SERVER_VERSION);
605 p.Send_uint16(_settings_client.network.server_port);
606 p.Send_uint64(_session_key);
608 _network_udp_mutex->BeginCritical();
609 if (_udp_master_socket != NULL) _udp_master_socket->SendPacket(&p, &out_addr, true);
610 _network_udp_mutex->EndCritical();
614 * Register us to the master server
615 * This function checks if it needs to send an advertise
617 void NetworkUDPAdvertise()
619 static uint32 _last_advertisement = 0; ///< The time of the last advertisement (used to check for wrapping of time)
620 static uint32 _next_advertisement = 0; ///< The next time we should perform a normal advertisement.
621 static uint32 _next_retry = 0; ///< The next time we should perform a retry of an advertisement.
623 /* Check if we should send an advertise */
624 if (!_networking || !_network_server || !_network_udp_server || !_settings_client.network.server_advertise) return;
626 if (_network_need_advertise || _realtime_tick < _last_advertisement) {
627 /* Forced advertisement, or a wrapping of time in which case we determine the advertisement/retry times again. */
628 _network_need_advertise = false;
629 _network_advertise_retries = ADVERTISE_RETRY_TIMES;
630 } else {
631 /* Only send once every ADVERTISE_NORMAL_INTERVAL ticks */
632 if (_network_advertise_retries == 0) {
633 if (_realtime_tick <= _next_advertisement) return;
635 _network_advertise_retries = ADVERTISE_RETRY_TIMES;
636 } else {
637 /* An actual retry. */
638 if (_realtime_tick <= _next_retry) return;
642 _network_advertise_retries--;
643 _last_advertisement = _realtime_tick;
644 _next_advertisement = _realtime_tick + ADVERTISE_NORMAL_INTERVAL;
645 _next_retry = _realtime_tick + ADVERTISE_RETRY_INTERVAL;
647 /* Make sure we do not have an overflow when checking these; when time wraps, we simply force an advertisement. */
648 if (_next_advertisement < _last_advertisement) _next_advertisement = UINT32_MAX;
649 if (_next_retry < _last_advertisement) _next_retry = UINT32_MAX;
651 if (!ThreadObject::New(NetworkUDPAdvertiseThread, NULL, NULL, "ottd:udp-advert")) {
652 NetworkUDPAdvertiseThread(NULL);
656 /** Initialize the whole UDP bit. */
657 void NetworkUDPInitialize()
659 /* If not closed, then do it. */
660 if (_udp_server_socket != NULL) NetworkUDPClose();
662 DEBUG(net, 1, "[udp] initializing listeners");
663 assert(_udp_client_socket == NULL && _udp_server_socket == NULL && _udp_master_socket == NULL);
665 _network_udp_mutex->BeginCritical();
667 _udp_client_socket = new ClientNetworkUDPSocketHandler();
669 NetworkAddressList server;
670 GetBindAddresses(&server, _settings_client.network.server_port);
671 _udp_server_socket = new ServerNetworkUDPSocketHandler(&server);
673 server.Clear();
674 GetBindAddresses(&server, 0);
675 _udp_master_socket = new MasterNetworkUDPSocketHandler(&server);
677 _network_udp_server = false;
678 _network_udp_broadcast = 0;
679 _network_udp_mutex->EndCritical();
682 /** Close all UDP related stuff. */
683 void NetworkUDPClose()
685 _network_udp_mutex->BeginCritical();
686 _udp_server_socket->Close();
687 _udp_master_socket->Close();
688 _udp_client_socket->Close();
689 delete _udp_client_socket;
690 delete _udp_server_socket;
691 delete _udp_master_socket;
692 _udp_client_socket = NULL;
693 _udp_server_socket = NULL;
694 _udp_master_socket = NULL;
695 _network_udp_mutex->EndCritical();
697 _network_udp_server = false;
698 _network_udp_broadcast = 0;
699 DEBUG(net, 1, "[udp] closed listeners");
702 /** Receive the UDP packets. */
703 void NetworkBackgroundUDPLoop()
705 _network_udp_mutex->BeginCritical();
707 if (_network_udp_server) {
708 _udp_server_socket->ReceivePackets();
709 _udp_master_socket->ReceivePackets();
710 } else {
711 _udp_client_socket->ReceivePackets();
712 if (_network_udp_broadcast > 0) _network_udp_broadcast--;
715 _network_udp_mutex->EndCritical();
718 #endif /* ENABLE_NETWORK */