# network_udp.cpp

Go to the documentation of this file.

    00001 /* $Id$ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * 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.
    00006  * 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.
    00007  * 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/>.
    00008  */
    00009
    00017 #ifdef ENABLE_NETWORK
    00018
    00019 #include "../stdafx.h"
    00020 #include "../date_func.h"
    00021 #include "../map_func.h"
    00022 #include "../debug.h"
    00023 #include "network_gamelist.h"
    00024 #include "network_internal.h"
    00025 #include "network_udp.h"
    00026 #include "network.h"
    00027 #include "../core/endian_func.hpp"
    00028 #include "../company_base.h"
    00029 #include "../thread/thread.h"
    00030 #include "../rev.h"
    00031 #include "../newgrf_text.h"
    00032 #include "../strings_func.h"
    00033 #include "table/strings.h"
    00034
    00035 #include "core/udp.h"
    00036
    00038 static ThreadMutex *_network_udp_mutex = ThreadMutex::New();
    00039
    00041 static uint64 _session_key = 0;
    00042
    00043 static const uint ADVERTISE_NORMAL_INTERVAL = 30000;
    00044 static const uint ADVERTISE_RETRY_INTERVAL  =   300;
    00045 static const uint ADVERTISE_RETRY_TIMES     =     3;
    00046
    00047 NetworkUDPSocketHandler *_udp_client_socket = NULL;
    00048 NetworkUDPSocketHandler *_udp_server_socket = NULL;
    00049 NetworkUDPSocketHandler *_udp_master_socket = NULL;
    00050
    00052 struct NetworkUDPQueryServerInfo : NetworkAddress {
    00053   bool manually;
    00054
    00060   NetworkUDPQueryServerInfo(const NetworkAddress &address, bool manually) :
    00061     NetworkAddress(address),
    00062     manually(manually)
    00063   {
    00064   }
    00065 };
    00066
    00073 static void NetworkUDPQueryServer(NetworkAddress *address, bool needs_mutex, bool manually)
    00074 {
    00075   /* Clear item in gamelist */
    00076   NetworkGameList *item = CallocT<NetworkGameList>(1);
    00077   address->GetAddressAsString(item->info.server_name, lastof(item->info.server_name));
    00078   strecpy(item->info.hostname, address->GetHostname(), lastof(item->info.hostname));
    00079   item->address = *address;
    00080   item->manually = manually;
    00081   NetworkGameListAddItemDelayed(item);
    00082
    00083   if (needs_mutex) _network_udp_mutex->BeginCritical();
    00084   /* Init the packet */
    00085   Packet p(PACKET_UDP_CLIENT_FIND_SERVER);
    00086   if (_udp_client_socket != NULL) _udp_client_socket->SendPacket(&p, address);
    00087   if (needs_mutex) _network_udp_mutex->EndCritical();
    00088 }
    00089
    00094 static void NetworkUDPQueryServerThread(void *pntr)
    00095 {
    00096   NetworkUDPQueryServerInfo *info = (NetworkUDPQueryServerInfo*)pntr;
    00097   NetworkUDPQueryServer(info, true, info->manually);
    00098
    00099   delete info;
    00100 }
    00101
    00107 void NetworkUDPQueryServer(NetworkAddress address, bool manually)
    00108 {
    00109   NetworkUDPQueryServerInfo *info = new NetworkUDPQueryServerInfo(address, manually);
    00110   if (address.IsResolved() || !ThreadObject::New(NetworkUDPQueryServerThread, info)) {
    00111     NetworkUDPQueryServerThread(info);
    00112   }
    00113 }
    00114
    00116
    00118 class MasterNetworkUDPSocketHandler : public NetworkUDPSocketHandler {
    00119 protected:
    00120   virtual void Receive_MASTER_ACK_REGISTER(Packet *p, NetworkAddress *client_addr);
    00121   virtual void Receive_MASTER_SESSION_KEY(Packet *p, NetworkAddress *client_addr);
    00122 public:
    00127   MasterNetworkUDPSocketHandler(NetworkAddressList *addresses) : NetworkUDPSocketHandler(addresses) {}
    00128   virtual ~MasterNetworkUDPSocketHandler() {}
    00129 };
    00130
    00131 void MasterNetworkUDPSocketHandler::Receive_MASTER_ACK_REGISTER(Packet *p, NetworkAddress *client_addr)
    00132 {
    00133   _network_advertise_retries = 0;
    00134   DEBUG(net, 2, "[udp] advertising on master server successful (%s)", NetworkAddress::AddressFamilyAsString(client_addr->GetAddress()->ss_family));
    00135
    00136   /* We are advertised, but we don't want to! */
    00137   if (!_settings_client.network.server_advertise) NetworkUDPRemoveAdvertise(false);
    00138 }
    00139
    00140 void MasterNetworkUDPSocketHandler::Receive_MASTER_SESSION_KEY(Packet *p, NetworkAddress *client_addr)
    00141 {
    00142   _session_key = p->Recv_uint64();
    00143   DEBUG(net, 2, "[udp] received new session key from master server (%s)", NetworkAddress::AddressFamilyAsString(client_addr->GetAddress()->ss_family));
    00144 }
    00145
    00147
    00149 class ServerNetworkUDPSocketHandler : public NetworkUDPSocketHandler {
    00150 protected:
    00151   virtual void Receive_CLIENT_FIND_SERVER(Packet *p, NetworkAddress *client_addr);
    00152   virtual void Receive_CLIENT_DETAIL_INFO(Packet *p, NetworkAddress *client_addr);
    00153   virtual void Receive_CLIENT_GET_NEWGRFS(Packet *p, NetworkAddress *client_addr);
    00154 public:
    00159   ServerNetworkUDPSocketHandler(NetworkAddressList *addresses) : NetworkUDPSocketHandler(addresses) {}
    00160   virtual ~ServerNetworkUDPSocketHandler() {}
    00161 };
    00162
    00163 void ServerNetworkUDPSocketHandler::Receive_CLIENT_FIND_SERVER(Packet *p, NetworkAddress *client_addr)
    00164 {
    00165   /* Just a fail-safe.. should never happen */
    00166   if (!_network_udp_server) {
    00167     return;
    00168   }
    00169
    00170   NetworkGameInfo ngi;
    00171
    00172   /* Update some game_info */
    00173   ngi.clients_on     = _network_game_info.clients_on;
    00174   ngi.start_date     = ConvertYMDToDate(_settings_game.game_creation.starting_year, 0, 1);
    00175
    00176   ngi.server_lang    = _settings_client.network.server_lang;
    00177   ngi.use_password   = !StrEmpty(_settings_client.network.server_password);
    00178   ngi.clients_max    = _settings_client.network.max_clients;
    00179   ngi.companies_on   = (byte)Company::GetNumItems();
    00180   ngi.companies_max  = _settings_client.network.max_companies;
    00181   ngi.spectators_on  = NetworkSpectatorCount();
    00182   ngi.spectators_max = _settings_client.network.max_spectators;
    00183   ngi.game_date      = _date;
    00184   ngi.map_width      = MapSizeX();
    00185   ngi.map_height     = MapSizeY();
    00186   ngi.map_set        = _settings_game.game_creation.landscape;
    00187   ngi.dedicated      = _network_dedicated;
    00188   ngi.grfconfig      = _grfconfig;
    00189
    00190   strecpy(ngi.map_name, _network_game_info.map_name, lastof(ngi.map_name));
    00191   strecpy(ngi.server_name, _settings_client.network.server_name, lastof(ngi.server_name));
    00192   strecpy(ngi.server_revision, _openttd_revision, lastof(ngi.server_revision));
    00193
    00194   Packet packet(PACKET_UDP_SERVER_RESPONSE);
    00195   this->SendNetworkGameInfo(&packet, &ngi);
    00196
    00197   /* Let the client know that we are here */
    00198   this->SendPacket(&packet, client_addr);
    00199
    00200   DEBUG(net, 2, "[udp] queried from %s", client_addr->GetHostname());
    00201 }
    00202
    00203 void ServerNetworkUDPSocketHandler::Receive_CLIENT_DETAIL_INFO(Packet *p, NetworkAddress *client_addr)
    00204 {
    00205   /* Just a fail-safe.. should never happen */
    00206   if (!_network_udp_server) return;
    00207
    00208   Packet packet(PACKET_UDP_SERVER_DETAIL_INFO);
    00209
    00210   /* Send the amount of active companies */
    00211   packet.Send_uint8 (NETWORK_COMPANY_INFO_VERSION);
    00212   packet.Send_uint8 ((uint8)Company::GetNumItems());
    00213
    00214   /* Fetch the latest version of the stats */
    00215   NetworkCompanyStats company_stats[MAX_COMPANIES];
    00216   NetworkPopulateCompanyStats(company_stats);
    00217
    00218   /* The minimum company information "blob" size. */
    00219   static const uint MIN_CI_SIZE = 54;
    00220   uint max_cname_length = NETWORK_COMPANY_NAME_LENGTH;
    00221
    00222   if (Company::GetNumItems() * (MIN_CI_SIZE + NETWORK_COMPANY_NAME_LENGTH) >= (uint)SEND_MTU - packet.size) {
    00223     /* Assume we can at least put the company information in the packets. */
    00224     assert(Company::GetNumItems() * MIN_CI_SIZE < (uint)SEND_MTU - packet.size);
    00225
    00226     /* At this moment the company names might not fit in the
    00227      * packet. Check whether that is really the case. */
    00228
    00229     for (;;) {
    00230       int free = SEND_MTU - packet.size;
    00231       Company *company;
    00232       FOR_ALL_COMPANIES(company) {
    00233         char company_name[NETWORK_COMPANY_NAME_LENGTH];
    00234         SetDParam(0, company->index);
    00235         GetString(company_name, STR_COMPANY_NAME, company_name + max_cname_length - 1);
    00236         free -= MIN_CI_SIZE;
    00237         free -= (int)strlen(company_name);
    00238       }
    00239       if (free >= 0) break;
    00240
    00241       /* Try again, with slightly shorter strings. */
    00242       assert(max_cname_length > 0);
    00243       max_cname_length--;
    00244     }
    00245   }
    00246
    00247   Company *company;
    00248   /* Go through all the companies */
    00249   FOR_ALL_COMPANIES(company) {
    00250     /* Send the information */
    00251     this->SendCompanyInformation(&packet, company, &company_stats[company->index], max_cname_length);
    00252   }
    00253
    00254   this->SendPacket(&packet, client_addr);
    00255 }
    00256
    00270 void ServerNetworkUDPSocketHandler::Receive_CLIENT_GET_NEWGRFS(Packet *p, NetworkAddress *client_addr)
    00271 {
    00272   uint8 num_grfs;
    00273   uint i;
    00274
    00275   const GRFConfig *in_reply[NETWORK_MAX_GRF_COUNT];
    00276   uint8 in_reply_count = 0;
    00277   size_t packet_len = 0;
    00278
    00279   DEBUG(net, 6, "[udp] newgrf data request from %s", client_addr->GetAddressAsString());
    00280
    00281   num_grfs = p->Recv_uint8 ();
    00282   if (num_grfs > NETWORK_MAX_GRF_COUNT) return;
    00283
    00284   for (i = 0; i < num_grfs; i++) {
    00285     GRFIdentifier c;
    00286     const GRFConfig *f;
    00287
    00288     this->ReceiveGRFIdentifier(p, &c);
    00289
    00290     /* Find the matching GRF file */
    00291     f = FindGRFConfig(c.grfid, FGCM_EXACT, c.md5sum);
    00292     if (f == NULL) continue; // The GRF is unknown to this server
    00293
    00294     /* If the reply might exceed the size of the packet, only reply
    00295      * the current list and do not send the other data.
    00296      * The name could be an empty string, if so take the filename. */
    00297     packet_len += sizeof(c.grfid) + sizeof(c.md5sum) +
    00298         min(strlen(f->GetName()) + 1, (size_t)NETWORK_GRF_NAME_LENGTH);
    00299     if (packet_len > SEND_MTU - 4) { // 4 is 3 byte header + grf count in reply
    00300       break;
    00301     }
    00302     in_reply[in_reply_count] = f;
    00303     in_reply_count++;
    00304   }
    00305
    00306   if (in_reply_count == 0) return;
    00307
    00308   Packet packet(PACKET_UDP_SERVER_NEWGRFS);
    00309   packet.Send_uint8(in_reply_count);
    00310   for (i = 0; i < in_reply_count; i++) {
    00311     char name[NETWORK_GRF_NAME_LENGTH];
    00312
    00313     /* The name could be an empty string, if so take the filename */
    00314     strecpy(name, in_reply[i]->GetName(), lastof(name));
    00315     this->SendGRFIdentifier(&packet, &in_reply[i]->ident);
    00316     packet.Send_string(name);
    00317   }
    00318
    00319   this->SendPacket(&packet, client_addr);
    00320 }
    00321
    00323
    00325 class ClientNetworkUDPSocketHandler : public NetworkUDPSocketHandler {
    00326 protected:
    00327   virtual void Receive_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr);
    00328   virtual void Receive_MASTER_RESPONSE_LIST(Packet *p, NetworkAddress *client_addr);
    00329   virtual void Receive_SERVER_NEWGRFS(Packet *p, NetworkAddress *client_addr);
    00330   virtual void HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config);
    00331 public:
    00332   virtual ~ClientNetworkUDPSocketHandler() {}
    00333 };
    00334
    00335 void ClientNetworkUDPSocketHandler::Receive_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr)
    00336 {
    00337   NetworkGameList *item;
    00338
    00339   /* Just a fail-safe.. should never happen */
    00340   if (_network_udp_server) return;
    00341
    00342   DEBUG(net, 4, "[udp] server response from %s", client_addr->GetAddressAsString());
    00343
    00344   /* Find next item */
    00345   item = NetworkGameListAddItem(*client_addr);
    00346
    00347   ClearGRFConfigList(&item->info.grfconfig);
    00348   this->ReceiveNetworkGameInfo(p, &item->info);
    00349
    00350   item->info.compatible = true;
    00351   {
    00352     /* Checks whether there needs to be a request for names of GRFs and makes
    00353      * the request if necessary. GRFs that need to be requested are the GRFs
    00354      * that do not exist on the clients system and we do not have the name
    00355      * resolved of, i.e. the name is still UNKNOWN_GRF_NAME_PLACEHOLDER.
    00356      * The in_request array and in_request_count are used so there is no need
    00357      * to do a second loop over the GRF list, which can be relatively expensive
    00358      * due to the string comparisons. */
    00359     const GRFConfig *in_request[NETWORK_MAX_GRF_COUNT];
    00360     const GRFConfig *c;
    00361     uint in_request_count = 0;
    00362
    00363     for (c = item->info.grfconfig; c != NULL; c = c->next) {
    00364       if (c->status == GCS_NOT_FOUND) item->info.compatible = false;
    00365       if (c->status != GCS_NOT_FOUND || strcmp(c->GetName(), UNKNOWN_GRF_NAME_PLACEHOLDER) != 0) continue;
    00366       in_request[in_request_count] = c;
    00367       in_request_count++;
    00368     }
    00369
    00370     if (in_request_count > 0) {
    00371       /* There are 'unknown' GRFs, now send a request for them */
    00372       uint i;
    00373       Packet packet(PACKET_UDP_CLIENT_GET_NEWGRFS);
    00374
    00375       packet.Send_uint8(in_request_count);
    00376       for (i = 0; i < in_request_count; i++) {
    00377         this->SendGRFIdentifier(&packet, &in_request[i]->ident);
    00378       }
    00379
    00380       this->SendPacket(&packet, &item->address);
    00381     }
    00382   }
    00383
    00384   if (item->info.hostname[0] == '\0') {
    00385     snprintf(item->info.hostname, sizeof(item->info.hostname), "%s", client_addr->GetHostname());
    00386   }
    00387
    00388   if (client_addr->GetAddress()->ss_family == AF_INET6) {
    00389     strecat(item->info.server_name, " (IPv6)", lastof(item->info.server_name));
    00390   }
    00391
    00392   /* Check if we are allowed on this server based on the revision-match */
    00393   item->info.version_compatible = IsNetworkCompatibleVersion(item->info.server_revision);
    00394   item->info.compatible &= item->info.version_compatible; // Already contains match for GRFs
    00395
    00396   item->online = true;
    00397
    00398   UpdateNetworkGameWindow();
    00399 }
    00400
    00401 void ClientNetworkUDPSocketHandler::Receive_MASTER_RESPONSE_LIST(Packet *p, NetworkAddress *client_addr)
    00402 {
    00403   /* packet begins with the protocol version (uint8)
    00404    * then an uint16 which indicates how many
    00405    * ip:port pairs are in this packet, after that
    00406    * an uint32 (ip) and an uint16 (port) for each pair.
    00407    */
    00408
    00409   ServerListType type = (ServerListType)(p->Recv_uint8() - 1);
    00410
    00411   if (type < SLT_END) {
    00412     for (int i = p->Recv_uint16(); i != 0 ; i--) {
    00413       sockaddr_storage addr_storage;
    00414       memset(&addr_storage, 0, sizeof(addr_storage));
    00415
    00416       if (type == SLT_IPv4) {
    00417         addr_storage.ss_family = AF_INET;
    00418         ((sockaddr_in*)&addr_storage)->sin_addr.s_addr = TO_LE32(p->Recv_uint32());
    00419       } else {
    00420         assert(type == SLT_IPv6);
    00421         addr_storage.ss_family = AF_INET6;
    00422         byte *addr = (byte*)&((sockaddr_in6*)&addr_storage)->sin6_addr;
    00423         for (uint i = 0; i < sizeof(in6_addr); i++) *addr++ = p->Recv_uint8();
    00424       }
    00425       NetworkAddress addr(addr_storage, type == SLT_IPv4 ? sizeof(sockaddr_in) : sizeof(sockaddr_in6));
    00426       addr.SetPort(p->Recv_uint16());
    00427
    00428       /* Somehow we reached the end of the packet */
    00429       if (this->HasClientQuit()) return;
    00430
    00431       NetworkUDPQueryServer(&addr, false, false);
    00432     }
    00433   }
    00434 }
    00435
    00437 void ClientNetworkUDPSocketHandler::Receive_SERVER_NEWGRFS(Packet *p, NetworkAddress *client_addr)
    00438 {
    00439   uint8 num_grfs;
    00440   uint i;
    00441
    00442   DEBUG(net, 6, "[udp] newgrf data reply from %s", client_addr->GetAddressAsString());
    00443
    00444   num_grfs = p->Recv_uint8 ();
    00445   if (num_grfs > NETWORK_MAX_GRF_COUNT) return;
    00446
    00447   for (i = 0; i < num_grfs; i++) {
    00448     char name[NETWORK_GRF_NAME_LENGTH];
    00449     GRFIdentifier c;
    00450
    00451     this->ReceiveGRFIdentifier(p, &c);
    00452     p->Recv_string(name, sizeof(name));
    00453
    00454     /* An empty name is not possible under normal circumstances
    00455      * and causes problems when showing the NewGRF list. */
    00456     if (StrEmpty(name)) continue;
    00457
    00458     /* Try to find the GRFTextWrapper for the name of this GRF ID and MD5sum tuple.
    00459      * If it exists and not resolved yet, then name of the fake GRF is
    00460      * overwritten with the name from the reply. */
    00461     GRFTextWrapper *unknown_name = FindUnknownGRFName(c.grfid, c.md5sum, false);
    00462     if (unknown_name != NULL && strcmp(GetGRFStringFromGRFText(unknown_name->text), UNKNOWN_GRF_NAME_PLACEHOLDER) == 0) {
    00463       AddGRFTextToList(&unknown_name->text, name);
    00464     }
    00465   }
    00466 }
    00467
    00468 void ClientNetworkUDPSocketHandler::HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config)
    00469 {
    00470   /* Find the matching GRF file */
    00471   const GRFConfig *f = FindGRFConfig(config->ident.grfid, FGCM_EXACT, config->ident.md5sum);
    00472   if (f == NULL) {
    00473     /* Don't know the GRF, so mark game incompatible and the (possibly)
    00474      * already resolved name for this GRF (another server has sent the
    00475      * name of the GRF already */
    00476     config->name->Release();
    00477     config->name = FindUnknownGRFName(config->ident.grfid, config->ident.md5sum, true);
    00478     config->name->AddRef();
    00479     config->status = GCS_NOT_FOUND;
    00480   } else {
    00481     config->filename = f->filename;
    00482     config->name->Release();
    00483     config->name = f->name;
    00484     config->name->AddRef();
    00485     config->info->Release();
    00486     config->info = f->info;
    00487     config->info->AddRef();
    00488     config->url->Release();
    00489     config->url = f->url;
    00490     config->url->AddRef();
    00491   }
    00492   SetBit(config->flags, GCF_COPY);
    00493 }
    00494
    00496 static void NetworkUDPBroadCast(NetworkUDPSocketHandler *socket)
    00497 {
    00498   for (NetworkAddress *addr = _broadcast_list.Begin(); addr != _broadcast_list.End(); addr++) {
    00499     Packet p(PACKET_UDP_CLIENT_FIND_SERVER);
    00500
    00501     DEBUG(net, 4, "[udp] broadcasting to %s", addr->GetHostname());
    00502
    00503     socket->SendPacket(&p, addr, true, true);
    00504   }
    00505 }
    00506
    00507
    00509 void NetworkUDPQueryMasterServer()
    00510 {
    00511   Packet p(PACKET_UDP_CLIENT_GET_LIST);
    00512   NetworkAddress out_addr(NETWORK_MASTER_SERVER_HOST, NETWORK_MASTER_SERVER_PORT);
    00513
    00514   /* packet only contains protocol version */
    00515   p.Send_uint8(NETWORK_MASTER_SERVER_VERSION);
    00516   p.Send_uint8(SLT_AUTODETECT);
    00517
    00518   _udp_client_socket->SendPacket(&p, &out_addr, true);
    00519
    00520   DEBUG(net, 2, "[udp] master server queried at %s", out_addr.GetAddressAsString());
    00521 }
    00522
    00524 void NetworkUDPSearchGame()
    00525 {
    00526   /* We are still searching.. */
    00527   if (_network_udp_broadcast > 0) return;
    00528
    00529   DEBUG(net, 0, "[udp] searching server");
    00530
    00531   NetworkUDPBroadCast(_udp_client_socket);
    00532   _network_udp_broadcast = 300; // Stay searching for 300 ticks
    00533 }
    00534
    00539 static void NetworkUDPRemoveAdvertiseThread(void *pntr)
    00540 {
    00541   DEBUG(net, 1, "[udp] removing advertise from master server");
    00542
    00543   /* Find somewhere to send */
    00544   NetworkAddress out_addr(NETWORK_MASTER_SERVER_HOST, NETWORK_MASTER_SERVER_PORT);
    00545
    00546   /* Send the packet */
    00547   Packet p(PACKET_UDP_SERVER_UNREGISTER);
    00548   /* Packet is: Version, server_port */
    00549   p.Send_uint8 (NETWORK_MASTER_SERVER_VERSION);
    00550   p.Send_uint16(_settings_client.network.server_port);
    00551
    00552   _network_udp_mutex->BeginCritical();
    00553   if (_udp_master_socket != NULL) _udp_master_socket->SendPacket(&p, &out_addr, true);
    00554   _network_udp_mutex->EndCritical();
    00555 }
    00556
    00561 void NetworkUDPRemoveAdvertise(bool blocking)
    00562 {
    00563   /* Check if we are advertising */
    00564   if (!_networking || !_network_server || !_network_udp_server) return;
    00565
    00566   if (blocking || !ThreadObject::New(NetworkUDPRemoveAdvertiseThread, NULL)) {
    00567     NetworkUDPRemoveAdvertiseThread(NULL);
    00568   }
    00569 }
    00570
    00575 static void NetworkUDPAdvertiseThread(void *pntr)
    00576 {
    00577   /* Find somewhere to send */
    00578   NetworkAddress out_addr(NETWORK_MASTER_SERVER_HOST, NETWORK_MASTER_SERVER_PORT);
    00579
    00580   DEBUG(net, 1, "[udp] advertising to master server");
    00581
    00582   /* Add a bit more messaging when we cannot get a session key */
    00583   static byte session_key_retries = 0;
    00584   if (_session_key == 0 && session_key_retries++ == 2) {
    00585     DEBUG(net, 0, "[udp] advertising to the master server is failing");
    00586     DEBUG(net, 0, "[udp]   we are not receiving the session key from the server");
    00587     DEBUG(net, 0, "[udp]   please allow udp packets from %s to you to be delivered", out_addr.GetAddressAsString(false));
    00588     DEBUG(net, 0, "[udp]   please allow udp packets from you to %s to be delivered", out_addr.GetAddressAsString(false));
    00589   }
    00590   if (_session_key != 0 && _network_advertise_retries == 0) {
    00591     DEBUG(net, 0, "[udp] advertising to the master server is failing");
    00592     DEBUG(net, 0, "[udp]   we are not receiving the acknowledgement from the server");
    00593     DEBUG(net, 0, "[udp]   this usually means that the master server cannot reach us");
    00594     DEBUG(net, 0, "[udp]   please allow udp and tcp packets to port %u to be delivered", _settings_client.network.server_port);
    00595     DEBUG(net, 0, "[udp]   please allow udp and tcp packets from port %u to be delivered", _settings_client.network.server_port);
    00596   }
    00597
    00598   /* Send the packet */
    00599   Packet p(PACKET_UDP_SERVER_REGISTER);
    00600   /* Packet is: WELCOME_MESSAGE, Version, server_port */
    00601   p.Send_string(NETWORK_MASTER_SERVER_WELCOME_MESSAGE);
    00602   p.Send_uint8 (NETWORK_MASTER_SERVER_VERSION);
    00603   p.Send_uint16(_settings_client.network.server_port);
    00604   p.Send_uint64(_session_key);
    00605
    00606   _network_udp_mutex->BeginCritical();
    00607   if (_udp_master_socket != NULL) _udp_master_socket->SendPacket(&p, &out_addr, true);
    00608   _network_udp_mutex->EndCritical();
    00609 }
    00610
    00615 void NetworkUDPAdvertise()
    00616 {
    00617   /* Check if we should send an advertise */
    00618   if (!_networking || !_network_server || !_network_udp_server || !_settings_client.network.server_advertise) return;
    00619
    00620   if (_network_need_advertise) {
    00621     _network_need_advertise = false;
    00622     _network_advertise_retries = ADVERTISE_RETRY_TIMES;
    00623   } else {
    00624     /* Only send once every ADVERTISE_NORMAL_INTERVAL ticks */
    00625     if (_network_advertise_retries == 0) {
    00626       if ((_network_last_advertise_frame + ADVERTISE_NORMAL_INTERVAL) > _frame_counter) return;
    00627
    00628       _network_advertise_retries = ADVERTISE_RETRY_TIMES;
    00629     }
    00630
    00631     if ((_network_last_advertise_frame + ADVERTISE_RETRY_INTERVAL) > _frame_counter) return;
    00632   }
    00633
    00634   _network_advertise_retries--;
    00635   _network_last_advertise_frame = _frame_counter;
    00636
    00637   if (!ThreadObject::New(NetworkUDPAdvertiseThread, NULL)) {
    00638     NetworkUDPAdvertiseThread(NULL);
    00639   }
    00640 }
    00641
    00643 void NetworkUDPInitialize()
    00644 {
    00645   /* If not closed, then do it. */
    00646   if (_udp_server_socket != NULL) NetworkUDPClose();
    00647
    00648   DEBUG(net, 1, "[udp] initializing listeners");
    00649   assert(_udp_client_socket == NULL && _udp_server_socket == NULL && _udp_master_socket == NULL);
    00650
    00651   _network_udp_mutex->BeginCritical();
    00652
    00653   _udp_client_socket = new ClientNetworkUDPSocketHandler();
    00654
    00655   NetworkAddressList server;
    00656   GetBindAddresses(&server, _settings_client.network.server_port);
    00657   _udp_server_socket = new ServerNetworkUDPSocketHandler(&server);
    00658
    00659   server.Clear();
    00660   GetBindAddresses(&server, 0);
    00661   _udp_master_socket = new MasterNetworkUDPSocketHandler(&server);
    00662
    00663   _network_udp_server = false;
    00664   _network_udp_broadcast = 0;
    00665   _network_udp_mutex->EndCritical();
    00666 }
    00667
    00669 void NetworkUDPClose()
    00670 {
    00671   _network_udp_mutex->BeginCritical();
    00672   _udp_server_socket->Close();
    00673   _udp_master_socket->Close();
    00674   _udp_client_socket->Close();
    00675   delete _udp_client_socket;
    00676   delete _udp_server_socket;
    00677   delete _udp_master_socket;
    00678   _udp_client_socket = NULL;
    00679   _udp_server_socket = NULL;
    00680   _udp_master_socket = NULL;
    00681   _network_udp_mutex->EndCritical();
    00682
    00683   _network_udp_server = false;
    00684   _network_udp_broadcast = 0;
    00685   DEBUG(net, 1, "[udp] closed listeners");
    00686 }
    00687
    00689 void NetworkBackgroundUDPLoop()
    00690 {
    00691   _network_udp_mutex->BeginCritical();
    00692
    00693   if (_network_udp_server) {
    00694     _udp_server_socket->ReceivePackets();
    00695     _udp_master_socket->ReceivePackets();
    00696   } else {
    00697     _udp_client_socket->ReceivePackets();
    00698     if (_network_udp_broadcast > 0) _network_udp_broadcast--;
    00699   }
    00700
    00701   _network_udp_mutex->EndCritical();
    00702 }
    00703
    00704 #endif /* ENABLE_NETWORK */