OpenTTD
network_udp.cpp
Go to the documentation of this file.
1 /* $Id: network_udp.cpp 27670 2016-10-30 17:29:33Z frosch $ */
2 
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  */
9 
17 #ifdef ENABLE_NETWORK
18 
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"
34 
35 #include "core/udp.h"
36 
37 #include "../safeguards.h"
38 
41 
43 static uint64 _session_key = 0;
44 
45 static const uint32 ADVERTISE_NORMAL_INTERVAL = 15 * 60 * 1000;
46 static const uint32 ADVERTISE_RETRY_INTERVAL = 10 * 1000;
47 static const uint32 ADVERTISE_RETRY_TIMES = 3;
48 
52 
55  bool manually;
56 
63  NetworkAddress(address),
64  manually(manually)
65  {
66  }
67 };
68 
75 static void NetworkUDPQueryServer(NetworkAddress *address, bool needs_mutex, bool manually)
76 {
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;
84 
85  if (needs_mutex) _network_udp_mutex->BeginCritical();
86  /* Init the packet */
88  if (_udp_client_socket != NULL) _udp_client_socket->SendPacket(&p, address);
89  if (needs_mutex) _network_udp_mutex->EndCritical();
90 }
91 
96 static void NetworkUDPQueryServerThread(void *pntr)
97 {
99  NetworkUDPQueryServer(info, true, info->manually);
100 
101  delete info;
102 }
103 
109 void NetworkUDPQueryServer(NetworkAddress address, bool manually)
110 {
111  NetworkUDPQueryServerInfo *info = new NetworkUDPQueryServerInfo(address, manually);
112  if (address.IsResolved() || !ThreadObject::New(NetworkUDPQueryServerThread, info, NULL, "ottd:udp-query")) {
114  }
115 }
116 
118 
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:
130  virtual ~MasterNetworkUDPSocketHandler() {}
131 };
132 
134 {
136  DEBUG(net, 2, "[udp] advertising on master server successful (%s)", NetworkAddress::AddressFamilyAsString(client_addr->GetAddress()->ss_family));
137 
138  /* We are advertised, but we don't want to! */
140 }
141 
143 {
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));
146 }
147 
149 
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:
162  virtual ~ServerNetworkUDPSocketHandler() {}
163 };
164 
166 {
167  /* Just a fail-safe.. should never happen */
168  if (!_network_udp_server) {
169  return;
170  }
171 
172  NetworkGameInfo ngi;
173 
174  /* Update some game_info */
177 
181  ngi.companies_on = (byte)Company::GetNumItems();
183  ngi.spectators_on = NetworkSpectatorCount();
185  ngi.game_date = _date;
186  ngi.map_width = MapSizeX();
187  ngi.map_height = MapSizeY();
190  ngi.grfconfig = _grfconfig;
191 
194  strecpy(ngi.server_revision, _openttd_revision, lastof(ngi.server_revision));
195 
197  this->SendNetworkGameInfo(&packet, &ngi);
198 
199  /* Let the client know that we are here */
200  this->SendPacket(&packet, client_addr);
201 
202  DEBUG(net, 2, "[udp] queried from %s", client_addr->GetHostname());
203 }
204 
206 {
207  /* Just a fail-safe.. should never happen */
208  if (!_network_udp_server) return;
209 
211 
212  /* Send the amount of active companies */
214  packet.Send_uint8 ((uint8)Company::GetNumItems());
215 
216  /* Fetch the latest version of the stats */
217  NetworkCompanyStats company_stats[MAX_COMPANIES];
218  NetworkPopulateCompanyStats(company_stats);
219 
220  /* The minimum company information "blob" size. */
221  static const uint MIN_CI_SIZE = 54;
222  uint max_cname_length = NETWORK_COMPANY_NAME_LENGTH;
223 
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);
227 
228  /* At this moment the company names might not fit in the
229  * packet. Check whether that is really the case. */
230 
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);
240  }
241  if (free >= 0) break;
242 
243  /* Try again, with slightly shorter strings. */
244  assert(max_cname_length > 0);
245  max_cname_length--;
246  }
247  }
248 
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);
254  }
255 
256  this->SendPacket(&packet, client_addr);
257 }
258 
273 {
274  uint8 num_grfs;
275  uint i;
276 
277  const GRFConfig *in_reply[NETWORK_MAX_GRF_COUNT];
278  uint8 in_reply_count = 0;
279  size_t packet_len = 0;
280 
281  DEBUG(net, 6, "[udp] newgrf data request from %s", client_addr->GetAddressAsString());
282 
283  num_grfs = p->Recv_uint8 ();
284  if (num_grfs > NETWORK_MAX_GRF_COUNT) return;
285 
286  for (i = 0; i < num_grfs; i++) {
287  GRFIdentifier c;
288  const GRFConfig *f;
289 
290  this->ReceiveGRFIdentifier(p, &c);
291 
292  /* Find the matching GRF file */
294  if (f == NULL) continue; // The GRF is unknown to this server
295 
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;
303  }
304  in_reply[in_reply_count] = f;
305  in_reply_count++;
306  }
307 
308  if (in_reply_count == 0) return;
309 
311  packet.Send_uint8(in_reply_count);
312  for (i = 0; i < in_reply_count; i++) {
313  char name[NETWORK_GRF_NAME_LENGTH];
314 
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);
319  }
320 
321  this->SendPacket(&packet, client_addr);
322 }
323 
325 
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);
333 public:
334  virtual ~ClientNetworkUDPSocketHandler() {}
335 };
336 
338 {
339  NetworkGameList *item;
340 
341  /* Just a fail-safe.. should never happen */
342  if (_network_udp_server) return;
343 
344  DEBUG(net, 4, "[udp] server response from %s", client_addr->GetAddressAsString());
345 
346  /* Find next item */
347  item = NetworkGameListAddItem(*client_addr);
348 
349  ClearGRFConfigList(&item->info.grfconfig);
350  this->ReceiveNetworkGameInfo(p, &item->info);
351 
352  item->info.compatible = true;
353  {
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;
364 
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++;
370  }
371 
372  if (in_request_count > 0) {
373  /* There are 'unknown' GRFs, now send a request for them */
374  uint i;
376 
377  packet.Send_uint8(in_request_count);
378  for (i = 0; i < in_request_count; i++) {
379  this->SendGRFIdentifier(&packet, &in_request[i]->ident);
380  }
381 
382  this->SendPacket(&packet, &item->address);
383  }
384  }
385 
386  if (item->info.hostname[0] == '\0') {
387  seprintf(item->info.hostname, lastof(item->info.hostname), "%s", client_addr->GetHostname());
388  }
389 
390  if (client_addr->GetAddress()->ss_family == AF_INET6) {
391  strecat(item->info.server_name, " (IPv6)", lastof(item->info.server_name));
392  }
393 
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
397 
398  item->online = true;
399 
401 }
402 
404 {
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.
409  */
410 
411  ServerListType type = (ServerListType)(p->Recv_uint8() - 1);
412 
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));
417 
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();
426  }
427  NetworkAddress addr(addr_storage, type == SLT_IPv4 ? sizeof(sockaddr_in) : sizeof(sockaddr_in6));
428  addr.SetPort(p->Recv_uint16());
429 
430  /* Somehow we reached the end of the packet */
431  if (this->HasClientQuit()) return;
432 
433  NetworkUDPQueryServer(&addr, false, false);
434  }
435  }
436 }
437 
440 {
441  uint8 num_grfs;
442  uint i;
443 
444  DEBUG(net, 6, "[udp] newgrf data reply from %s", client_addr->GetAddressAsString());
445 
446  num_grfs = p->Recv_uint8 ();
447  if (num_grfs > NETWORK_MAX_GRF_COUNT) return;
448 
449  for (i = 0; i < num_grfs; i++) {
450  char name[NETWORK_GRF_NAME_LENGTH];
451  GRFIdentifier c;
452 
453  this->ReceiveGRFIdentifier(p, &c);
454  p->Recv_string(name, sizeof(name));
455 
456  /* An empty name is not possible under normal circumstances
457  * and causes problems when showing the NewGRF list. */
458  if (StrEmpty(name)) continue;
459 
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);
466  }
467  }
468 }
469 
471 {
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();
493  }
494  SetBit(config->flags, GCF_COPY);
495 }
496 
499 {
500  for (NetworkAddress *addr = _broadcast_list.Begin(); addr != _broadcast_list.End(); addr++) {
502 
503  DEBUG(net, 4, "[udp] broadcasting to %s", addr->GetHostname());
504 
505  socket->SendPacket(&p, addr, true, true);
506  }
507 }
508 
509 
512 {
515 
516  /* packet only contains protocol version */
519 
520  _udp_client_socket->SendPacket(&p, &out_addr, true);
521 
522  DEBUG(net, 2, "[udp] master server queried at %s", out_addr.GetAddressAsString());
523 }
524 
527 {
528  /* We are still searching.. */
529  if (_network_udp_broadcast > 0) return;
530 
531  DEBUG(net, 0, "[udp] searching server");
532 
533  NetworkUDPBroadCast(_udp_client_socket);
534  _network_udp_broadcast = 300; // Stay searching for 300 ticks
535 }
536 
541 static void NetworkUDPRemoveAdvertiseThread(void *pntr)
542 {
543  DEBUG(net, 1, "[udp] removing advertise from master server");
544 
545  /* Find somewhere to send */
547 
548  /* Send the packet */
550  /* Packet is: Version, server_port */
553 
554  _network_udp_mutex->BeginCritical();
555  if (_udp_master_socket != NULL) _udp_master_socket->SendPacket(&p, &out_addr, true);
556  _network_udp_mutex->EndCritical();
557 }
558 
563 void NetworkUDPRemoveAdvertise(bool blocking)
564 {
565  /* Check if we are advertising */
566  if (!_networking || !_network_server || !_network_udp_server) return;
567 
568  if (blocking || !ThreadObject::New(NetworkUDPRemoveAdvertiseThread, NULL, NULL, "ottd:udp-advert")) {
570  }
571 }
572 
577 static void NetworkUDPAdvertiseThread(void *pntr)
578 {
579  /* Find somewhere to send */
581 
582  DEBUG(net, 1, "[udp] advertising to master server");
583 
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));
591  }
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);
598  }
599 
600  /* Send the packet */
602  /* Packet is: WELCOME_MESSAGE, Version, server_port */
607 
608  _network_udp_mutex->BeginCritical();
609  if (_udp_master_socket != NULL) _udp_master_socket->SendPacket(&p, &out_addr, true);
610  _network_udp_mutex->EndCritical();
611 }
612 
618 {
619  static uint32 _last_advertisement = 0;
620  static uint32 _next_advertisement = 0;
621  static uint32 _next_retry = 0;
622 
623  /* Check if we should send an advertise */
625 
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;
630  } else {
631  /* Only send once every ADVERTISE_NORMAL_INTERVAL ticks */
632  if (_network_advertise_retries == 0) {
633  if (_realtime_tick <= _next_advertisement) return;
634 
636  } else {
637  /* An actual retry. */
638  if (_realtime_tick <= _next_retry) return;
639  }
640  }
641 
643  _last_advertisement = _realtime_tick;
644  _next_advertisement = _realtime_tick + ADVERTISE_NORMAL_INTERVAL;
646 
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;
650 
651  if (!ThreadObject::New(NetworkUDPAdvertiseThread, NULL, NULL, "ottd:udp-advert")) {
653  }
654 }
655 
658 {
659  /* If not closed, then do it. */
660  if (_udp_server_socket != NULL) NetworkUDPClose();
661 
662  DEBUG(net, 1, "[udp] initializing listeners");
663  assert(_udp_client_socket == NULL && _udp_server_socket == NULL && _udp_master_socket == NULL);
664 
665  _network_udp_mutex->BeginCritical();
666 
667  _udp_client_socket = new ClientNetworkUDPSocketHandler();
668 
669  NetworkAddressList server;
671  _udp_server_socket = new ServerNetworkUDPSocketHandler(&server);
672 
673  server.Clear();
674  GetBindAddresses(&server, 0);
675  _udp_master_socket = new MasterNetworkUDPSocketHandler(&server);
676 
677  _network_udp_server = false;
679  _network_udp_mutex->EndCritical();
680 }
681 
684 {
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();
696 
697  _network_udp_server = false;
699  DEBUG(net, 1, "[udp] closed listeners");
700 }
701 
704 {
705  _network_udp_mutex->BeginCritical();
706 
707  if (_network_udp_server) {
708  _udp_server_socket->ReceivePackets();
709  _udp_master_socket->ReceivePackets();
710  } else {
711  _udp_client_socket->ReceivePackets();
713  }
714 
715  _network_udp_mutex->EndCritical();
716 }
717 
718 #endif /* ENABLE_NETWORK */