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