OpenTTD
network_udp.cpp
Go to the documentation of this file.
1 /* $Id$ */
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 #include "../stdafx.h"
18 #include "../date_func.h"
19 #include "../map_func.h"
20 #include "../debug.h"
21 #include "network_gamelist.h"
22 #include "network_internal.h"
23 #include "network_udp.h"
24 #include "network.h"
25 #include "../core/endian_func.hpp"
26 #include "../company_base.h"
27 #include "../thread.h"
28 #include "../rev.h"
29 #include "../newgrf_text.h"
30 #include "../strings_func.h"
31 #include "table/strings.h"
32 #include <mutex>
33 
34 #include "core/udp.h"
35 
36 #include "../safeguards.h"
37 
39 static std::mutex _network_udp_mutex;
40 
42 static uint64 _session_key = 0;
43 
44 static const uint32 ADVERTISE_NORMAL_INTERVAL = 15 * 60 * 1000;
45 static const uint32 ADVERTISE_RETRY_INTERVAL = 10 * 1000;
46 static const uint32 ADVERTISE_RETRY_TIMES = 3;
47 
51 
58 static void DoNetworkUDPQueryServer(NetworkAddress &address, bool needs_mutex, bool manually)
59 {
60  /* Clear item in gamelist */
61  NetworkGameList *item = CallocT<NetworkGameList>(1);
63  strecpy(item->info.hostname, address.GetHostname(), lastof(item->info.hostname));
64  item->address = address;
65  item->manually = manually;
67 
68  std::unique_lock<std::mutex> lock(_network_udp_mutex, std::defer_lock);
69  if (needs_mutex) lock.lock();
70  /* Init the packet */
72  if (_udp_client_socket != nullptr) _udp_client_socket->SendPacket(&p, &address);
73 }
74 
80 void NetworkUDPQueryServer(NetworkAddress address, bool manually)
81 {
82  if (address.IsResolved() || !StartNewThread(nullptr, "ottd:udp-query", &DoNetworkUDPQueryServer, std::move(address), true, std::move(manually))) {
83  DoNetworkUDPQueryServer(address, true, manually);
84  }
85 }
86 
88 
91 protected:
92  void Receive_MASTER_ACK_REGISTER(Packet *p, NetworkAddress *client_addr) override;
93  void Receive_MASTER_SESSION_KEY(Packet *p, NetworkAddress *client_addr) override;
94 public:
100  virtual ~MasterNetworkUDPSocketHandler() {}
101 };
102 
104 {
106  DEBUG(net, 2, "[udp] advertising on master server successful (%s)", NetworkAddress::AddressFamilyAsString(client_addr->GetAddress()->ss_family));
107 
108  /* We are advertised, but we don't want to! */
110 }
111 
113 {
114  _session_key = p->Recv_uint64();
115  DEBUG(net, 2, "[udp] received new session key from master server (%s)", NetworkAddress::AddressFamilyAsString(client_addr->GetAddress()->ss_family));
116 }
117 
119 
122 protected:
123  void Receive_CLIENT_FIND_SERVER(Packet *p, NetworkAddress *client_addr) override;
124  void Receive_CLIENT_DETAIL_INFO(Packet *p, NetworkAddress *client_addr) override;
125  void Receive_CLIENT_GET_NEWGRFS(Packet *p, NetworkAddress *client_addr) override;
126 public:
132  virtual ~ServerNetworkUDPSocketHandler() {}
133 };
134 
136 {
137  /* Just a fail-safe.. should never happen */
138  if (!_network_udp_server) {
139  return;
140  }
141 
142  NetworkGameInfo ngi;
143 
144  /* Update some game_info */
147 
151  ngi.companies_on = (byte)Company::GetNumItems();
153  ngi.spectators_on = NetworkSpectatorCount();
155  ngi.game_date = _date;
156  ngi.map_width = MapSizeX();
157  ngi.map_height = MapSizeY();
160  ngi.grfconfig = _grfconfig;
161 
165 
167  this->SendNetworkGameInfo(&packet, &ngi);
168 
169  /* Let the client know that we are here */
170  this->SendPacket(&packet, client_addr);
171 
172  DEBUG(net, 2, "[udp] queried from %s", client_addr->GetHostname());
173 }
174 
176 {
177  /* Just a fail-safe.. should never happen */
178  if (!_network_udp_server) return;
179 
181 
182  /* Send the amount of active companies */
184  packet.Send_uint8 ((uint8)Company::GetNumItems());
185 
186  /* Fetch the latest version of the stats */
187  NetworkCompanyStats company_stats[MAX_COMPANIES];
188  NetworkPopulateCompanyStats(company_stats);
189 
190  /* The minimum company information "blob" size. */
191  static const uint MIN_CI_SIZE = 54;
192  uint max_cname_length = NETWORK_COMPANY_NAME_LENGTH;
193 
194  if (Company::GetNumItems() * (MIN_CI_SIZE + NETWORK_COMPANY_NAME_LENGTH) >= (uint)SEND_MTU - packet.size) {
195  /* Assume we can at least put the company information in the packets. */
196  assert(Company::GetNumItems() * MIN_CI_SIZE < (uint)SEND_MTU - packet.size);
197 
198  /* At this moment the company names might not fit in the
199  * packet. Check whether that is really the case. */
200 
201  for (;;) {
202  int free = SEND_MTU - packet.size;
203  Company *company;
204  FOR_ALL_COMPANIES(company) {
205  char company_name[NETWORK_COMPANY_NAME_LENGTH];
206  SetDParam(0, company->index);
207  GetString(company_name, STR_COMPANY_NAME, company_name + max_cname_length - 1);
208  free -= MIN_CI_SIZE;
209  free -= (int)strlen(company_name);
210  }
211  if (free >= 0) break;
212 
213  /* Try again, with slightly shorter strings. */
214  assert(max_cname_length > 0);
215  max_cname_length--;
216  }
217  }
218 
219  Company *company;
220  /* Go through all the companies */
221  FOR_ALL_COMPANIES(company) {
222  /* Send the information */
223  this->SendCompanyInformation(&packet, company, &company_stats[company->index], max_cname_length);
224  }
225 
226  this->SendPacket(&packet, client_addr);
227 }
228 
243 {
244  uint8 num_grfs;
245  uint i;
246 
247  const GRFConfig *in_reply[NETWORK_MAX_GRF_COUNT];
248  uint8 in_reply_count = 0;
249  size_t packet_len = 0;
250 
251  DEBUG(net, 6, "[udp] newgrf data request from %s", client_addr->GetAddressAsString());
252 
253  num_grfs = p->Recv_uint8 ();
254  if (num_grfs > NETWORK_MAX_GRF_COUNT) return;
255 
256  for (i = 0; i < num_grfs; i++) {
257  GRFIdentifier c;
258  const GRFConfig *f;
259 
260  this->ReceiveGRFIdentifier(p, &c);
261 
262  /* Find the matching GRF file */
264  if (f == nullptr) continue; // The GRF is unknown to this server
265 
266  /* If the reply might exceed the size of the packet, only reply
267  * the current list and do not send the other data.
268  * The name could be an empty string, if so take the filename. */
269  packet_len += sizeof(c.grfid) + sizeof(c.md5sum) +
270  min(strlen(f->GetName()) + 1, (size_t)NETWORK_GRF_NAME_LENGTH);
271  if (packet_len > SEND_MTU - 4) { // 4 is 3 byte header + grf count in reply
272  break;
273  }
274  in_reply[in_reply_count] = f;
275  in_reply_count++;
276  }
277 
278  if (in_reply_count == 0) return;
279 
281  packet.Send_uint8(in_reply_count);
282  for (i = 0; i < in_reply_count; i++) {
283  char name[NETWORK_GRF_NAME_LENGTH];
284 
285  /* The name could be an empty string, if so take the filename */
286  strecpy(name, in_reply[i]->GetName(), lastof(name));
287  this->SendGRFIdentifier(&packet, &in_reply[i]->ident);
288  packet.Send_string(name);
289  }
290 
291  this->SendPacket(&packet, client_addr);
292 }
293 
295 
298 protected:
299  void Receive_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr) override;
300  void Receive_MASTER_RESPONSE_LIST(Packet *p, NetworkAddress *client_addr) override;
301  void Receive_SERVER_NEWGRFS(Packet *p, NetworkAddress *client_addr) override;
302  void HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config) override;
303 public:
304  virtual ~ClientNetworkUDPSocketHandler() {}
305 };
306 
308 {
309  NetworkGameList *item;
310 
311  /* Just a fail-safe.. should never happen */
312  if (_network_udp_server) return;
313 
314  DEBUG(net, 4, "[udp] server response from %s", client_addr->GetAddressAsString());
315 
316  /* Find next item */
317  item = NetworkGameListAddItem(*client_addr);
318 
319  ClearGRFConfigList(&item->info.grfconfig);
320  this->ReceiveNetworkGameInfo(p, &item->info);
321 
322  item->info.compatible = true;
323  {
324  /* Checks whether there needs to be a request for names of GRFs and makes
325  * the request if necessary. GRFs that need to be requested are the GRFs
326  * that do not exist on the clients system and we do not have the name
327  * resolved of, i.e. the name is still UNKNOWN_GRF_NAME_PLACEHOLDER.
328  * The in_request array and in_request_count are used so there is no need
329  * to do a second loop over the GRF list, which can be relatively expensive
330  * due to the string comparisons. */
331  const GRFConfig *in_request[NETWORK_MAX_GRF_COUNT];
332  const GRFConfig *c;
333  uint in_request_count = 0;
334 
335  for (c = item->info.grfconfig; c != nullptr; c = c->next) {
336  if (c->status == GCS_NOT_FOUND) item->info.compatible = false;
337  if (c->status != GCS_NOT_FOUND || strcmp(c->GetName(), UNKNOWN_GRF_NAME_PLACEHOLDER) != 0) continue;
338  in_request[in_request_count] = c;
339  in_request_count++;
340  }
341 
342  if (in_request_count > 0) {
343  /* There are 'unknown' GRFs, now send a request for them */
344  uint i;
346 
347  packet.Send_uint8(in_request_count);
348  for (i = 0; i < in_request_count; i++) {
349  this->SendGRFIdentifier(&packet, &in_request[i]->ident);
350  }
351 
352  this->SendPacket(&packet, &item->address);
353  }
354  }
355 
356  if (item->info.hostname[0] == '\0') {
357  seprintf(item->info.hostname, lastof(item->info.hostname), "%s", client_addr->GetHostname());
358  }
359 
360  if (client_addr->GetAddress()->ss_family == AF_INET6) {
361  strecat(item->info.server_name, " (IPv6)", lastof(item->info.server_name));
362  }
363 
364  /* Check if we are allowed on this server based on the revision-match */
365  item->info.version_compatible = IsNetworkCompatibleVersion(item->info.server_revision);
366  item->info.compatible &= item->info.version_compatible; // Already contains match for GRFs
367 
368  item->online = true;
369 
371 }
372 
374 {
375  /* packet begins with the protocol version (uint8)
376  * then an uint16 which indicates how many
377  * ip:port pairs are in this packet, after that
378  * an uint32 (ip) and an uint16 (port) for each pair.
379  */
380 
381  ServerListType type = (ServerListType)(p->Recv_uint8() - 1);
382 
383  if (type < SLT_END) {
384  for (int i = p->Recv_uint16(); i != 0 ; i--) {
385  sockaddr_storage addr_storage;
386  memset(&addr_storage, 0, sizeof(addr_storage));
387 
388  if (type == SLT_IPv4) {
389  addr_storage.ss_family = AF_INET;
390  ((sockaddr_in*)&addr_storage)->sin_addr.s_addr = TO_LE32(p->Recv_uint32());
391  } else {
392  assert(type == SLT_IPv6);
393  addr_storage.ss_family = AF_INET6;
394  byte *addr = (byte*)&((sockaddr_in6*)&addr_storage)->sin6_addr;
395  for (uint i = 0; i < sizeof(in6_addr); i++) *addr++ = p->Recv_uint8();
396  }
397  NetworkAddress addr(addr_storage, type == SLT_IPv4 ? sizeof(sockaddr_in) : sizeof(sockaddr_in6));
398  addr.SetPort(p->Recv_uint16());
399 
400  /* Somehow we reached the end of the packet */
401  if (this->HasClientQuit()) return;
402 
403  DoNetworkUDPQueryServer(addr, false, false);
404  }
405  }
406 }
407 
410 {
411  uint8 num_grfs;
412  uint i;
413 
414  DEBUG(net, 6, "[udp] newgrf data reply from %s", client_addr->GetAddressAsString());
415 
416  num_grfs = p->Recv_uint8 ();
417  if (num_grfs > NETWORK_MAX_GRF_COUNT) return;
418 
419  for (i = 0; i < num_grfs; i++) {
420  char name[NETWORK_GRF_NAME_LENGTH];
421  GRFIdentifier c;
422 
423  this->ReceiveGRFIdentifier(p, &c);
424  p->Recv_string(name, sizeof(name));
425 
426  /* An empty name is not possible under normal circumstances
427  * and causes problems when showing the NewGRF list. */
428  if (StrEmpty(name)) continue;
429 
430  /* Try to find the GRFTextWrapper for the name of this GRF ID and MD5sum tuple.
431  * If it exists and not resolved yet, then name of the fake GRF is
432  * overwritten with the name from the reply. */
433  GRFTextWrapper *unknown_name = FindUnknownGRFName(c.grfid, c.md5sum, false);
434  if (unknown_name != nullptr && strcmp(GetGRFStringFromGRFText(unknown_name->text), UNKNOWN_GRF_NAME_PLACEHOLDER) == 0) {
435  AddGRFTextToList(&unknown_name->text, name);
436  }
437  }
438 }
439 
441 {
442  /* Find the matching GRF file */
443  const GRFConfig *f = FindGRFConfig(config->ident.grfid, FGCM_EXACT, config->ident.md5sum);
444  if (f == nullptr) {
445  /* Don't know the GRF, so mark game incompatible and the (possibly)
446  * already resolved name for this GRF (another server has sent the
447  * name of the GRF already */
448  config->name->Release();
449  config->name = FindUnknownGRFName(config->ident.grfid, config->ident.md5sum, true);
450  config->name->AddRef();
451  config->status = GCS_NOT_FOUND;
452  } else {
453  config->filename = f->filename;
454  config->name->Release();
455  config->name = f->name;
456  config->name->AddRef();
457  config->info->Release();
458  config->info = f->info;
459  config->info->AddRef();
460  config->url->Release();
461  config->url = f->url;
462  config->url->AddRef();
463  }
464  SetBit(config->flags, GCF_COPY);
465 }
466 
469 {
470  for (NetworkAddress &addr : _broadcast_list) {
472 
473  DEBUG(net, 4, "[udp] broadcasting to %s", addr.GetHostname());
474 
475  socket->SendPacket(&p, &addr, true, true);
476  }
477 }
478 
479 
482 {
485 
486  /* packet only contains protocol version */
489 
490  _udp_client_socket->SendPacket(&p, &out_addr, true);
491 
492  DEBUG(net, 2, "[udp] master server queried at %s", out_addr.GetAddressAsString());
493 }
494 
497 {
498  /* We are still searching.. */
499  if (_network_udp_broadcast > 0) return;
500 
501  DEBUG(net, 0, "[udp] searching server");
502 
503  NetworkUDPBroadCast(_udp_client_socket);
504  _network_udp_broadcast = 300; // Stay searching for 300 ticks
505 }
506 
511 {
512  DEBUG(net, 1, "[udp] removing advertise from master server");
513 
514  /* Find somewhere to send */
516 
517  /* Send the packet */
519  /* Packet is: Version, server_port */
522 
523  std::lock_guard<std::mutex> lock(_network_udp_mutex);
524  if (_udp_master_socket != nullptr) _udp_master_socket->SendPacket(&p, &out_addr, true);
525 }
526 
531 void NetworkUDPRemoveAdvertise(bool blocking)
532 {
533  /* Check if we are advertising */
534  if (!_networking || !_network_server || !_network_udp_server) return;
535 
536  if (blocking || !StartNewThread(nullptr, "ottd:udp-advert", &NetworkUDPRemoveAdvertiseThread)) {
538  }
539 }
540 
545 {
546  /* Find somewhere to send */
548 
549  DEBUG(net, 1, "[udp] advertising to master server");
550 
551  /* Add a bit more messaging when we cannot get a session key */
552  static byte session_key_retries = 0;
553  if (_session_key == 0 && session_key_retries++ == 2) {
554  DEBUG(net, 0, "[udp] advertising to the master server is failing");
555  DEBUG(net, 0, "[udp] we are not receiving the session key from the server");
556  DEBUG(net, 0, "[udp] please allow udp packets from %s to you to be delivered", out_addr.GetAddressAsString(false));
557  DEBUG(net, 0, "[udp] please allow udp packets from you to %s to be delivered", out_addr.GetAddressAsString(false));
558  }
559  if (_session_key != 0 && _network_advertise_retries == 0) {
560  DEBUG(net, 0, "[udp] advertising to the master server is failing");
561  DEBUG(net, 0, "[udp] we are not receiving the acknowledgement from the server");
562  DEBUG(net, 0, "[udp] this usually means that the master server cannot reach us");
563  DEBUG(net, 0, "[udp] please allow udp and tcp packets to port %u to be delivered", _settings_client.network.server_port);
564  DEBUG(net, 0, "[udp] please allow udp and tcp packets from port %u to be delivered", _settings_client.network.server_port);
565  }
566 
567  /* Send the packet */
569  /* Packet is: WELCOME_MESSAGE, Version, server_port */
574 
575  std::lock_guard<std::mutex> lock(_network_udp_mutex);
576  if (_udp_master_socket != nullptr) _udp_master_socket->SendPacket(&p, &out_addr, true);
577 }
578 
584 {
585  static uint32 _last_advertisement = 0;
586  static uint32 _next_advertisement = 0;
587  static uint32 _next_retry = 0;
588 
589  /* Check if we should send an advertise */
591 
592  if (_network_need_advertise || _realtime_tick < _last_advertisement) {
593  /* Forced advertisement, or a wrapping of time in which case we determine the advertisement/retry times again. */
594  _network_need_advertise = false;
596  } else {
597  /* Only send once every ADVERTISE_NORMAL_INTERVAL ticks */
598  if (_network_advertise_retries == 0) {
599  if (_realtime_tick <= _next_advertisement) return;
600 
602  } else {
603  /* An actual retry. */
604  if (_realtime_tick <= _next_retry) return;
605  }
606  }
607 
609  _last_advertisement = _realtime_tick;
610  _next_advertisement = _realtime_tick + ADVERTISE_NORMAL_INTERVAL;
612 
613  /* Make sure we do not have an overflow when checking these; when time wraps, we simply force an advertisement. */
614  if (_next_advertisement < _last_advertisement) _next_advertisement = UINT32_MAX;
615  if (_next_retry < _last_advertisement) _next_retry = UINT32_MAX;
616 
617  if (!StartNewThread(nullptr, "ottd:udp-advert", &NetworkUDPAdvertiseThread)) {
619  }
620 }
621 
624 {
625  /* If not closed, then do it. */
626  if (_udp_server_socket != nullptr) NetworkUDPClose();
627 
628  DEBUG(net, 1, "[udp] initializing listeners");
629  assert(_udp_client_socket == nullptr && _udp_server_socket == nullptr && _udp_master_socket == nullptr);
630 
631  std::lock_guard<std::mutex> lock(_network_udp_mutex);
632 
633  _udp_client_socket = new ClientNetworkUDPSocketHandler();
634 
635  NetworkAddressList server;
637  _udp_server_socket = new ServerNetworkUDPSocketHandler(&server);
638 
639  server.clear();
640  GetBindAddresses(&server, 0);
641  _udp_master_socket = new MasterNetworkUDPSocketHandler(&server);
642 
643  _network_udp_server = false;
645 }
646 
649 {
650  std::lock_guard<std::mutex> lock(_network_udp_mutex);
651  _udp_server_socket->Close();
652  _udp_master_socket->Close();
653  _udp_client_socket->Close();
654  delete _udp_client_socket;
655  delete _udp_server_socket;
656  delete _udp_master_socket;
657  _udp_client_socket = nullptr;
658  _udp_server_socket = nullptr;
659  _udp_master_socket = nullptr;
660 
661  _network_udp_server = false;
663  DEBUG(net, 1, "[udp] closed listeners");
664 }
665 
668 {
669  std::lock_guard<std::mutex> lock(_network_udp_mutex);
670 
671  if (_network_udp_server) {
672  _udp_server_socket->ReceivePackets();
673  _udp_master_socket->ReceivePackets();
674  } else {
675  _udp_client_socket->ReceivePackets();
677  }
678 }
Date start_date
When the game started.
Definition: game.h:36
byte spectators_max
Max spectators allowed on server.
Definition: game.h:53
uint16 map_height
Map height.
Definition: game.h:39
Autodetect the type based on the connection.
Definition: udp.h:42
static uint MapSizeX()
Get the size of the map along the X.
Definition: map_func.h:74
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:81
bool _networking
are we in networking mode?
Definition: network.cpp:54
bool IsNetworkCompatibleVersion(const char *other)
Checks whether the given version string is compatible with our version.
Definition: network.cpp:1160
static uint MapSizeY()
Get the size of the map along the Y.
Definition: map_func.h:84
bool HasClientQuit() const
Whether the current client connected to the socket has quit.
Definition: core.h:69
virtual void Receive_CLIENT_GET_NEWGRFS(Packet *p, NetworkAddress *client_addr)
The client requests information about some NewGRFs.
Definition: udp.cpp:345
uint32 _realtime_tick
The real time in the game.
Definition: debug.cpp:50
Internal entity of a packet.
Definition: packet.h:42
bool server_advertise
advertise the server to the masterserver
GRFConfig * _grfconfig
First item in list of current GRF set up.
byte landscape
the landscape we&#39;re currently in
static char * strecat(char *dst, const char *src, const char *last)
Appends characters from one string to another.
Definition: depend.cpp:99
void GetBindAddresses(NetworkAddressList *addresses, uint16 port)
Get the addresses to bind to.
Definition: network.cpp:633
uint32 Recv_uint32()
Read a 32 bits integer from the packet.
Definition: packet.cpp:248
void Receive_SERVER_NEWGRFS(Packet *p, NetworkAddress *client_addr) override
The return of the client&#39;s request of the names of some NewGRFs.
Queries a game server for game information.
Definition: udp.h:23
*** Communication with servers (we are client) ***/
char server_name[NETWORK_NAME_LENGTH]
name of the server
Requests the name for a list of GRFs (GRF_ID and MD5)
Definition: udp.h:32
static void NetworkUDPAdvertiseThread()
Thread entry point for advertising.
void ReceivePackets()
Receive a packet at UDP level.
Definition: udp.cpp:117
void ClearGRFConfigList(GRFConfig **config)
Clear a GRF Config list, freeing all nodes.
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:409
byte server_lang
Language of the server (we should make a nice table for this)
Definition: game.h:48
void Send_string(const char *data)
Sends a string over the network.
Definition: packet.cpp:150
virtual void Receive_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr)
Return of server information to the client.
Definition: udp.cpp:337
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
NetworkUDPSocketHandler * _udp_master_socket
udp master socket
Definition: network_udp.cpp:50
void NetworkPopulateCompanyStats(NetworkCompanyStats *stats)
Populate the company stats.
void Receive_MASTER_SESSION_KEY(Packet *p, NetworkAddress *client_addr) override
The master server sends us a session key.
Request for serverlist from master server.
Definition: udp.h:29
Get the IPv4 addresses.
Definition: udp.h:40
void SendNetworkGameInfo(Packet *p, const NetworkGameInfo *info)
Serializes the NetworkGameInfo struct to the packet.
Definition: udp.cpp:157
void Send_uint8(uint8 data)
Package a 8 bits integer in the packet.
Definition: packet.cpp:98
uint16 _network_udp_broadcast
Timeout for the UDP broadcasts.
Definition: network.cpp:80
Get the IPv6 addresses.
Definition: udp.h:41
GRFStatus status
NOSAVE: GRFStatus, enum.
struct GRFText * text
The actual text.
static uint64 _session_key
Session key to register ourselves to the master server.
Definition: network_udp.cpp:42
Sending and receiving UDP messages.
static const uint32 ADVERTISE_RETRY_TIMES
give up re-advertising after this much failed retries
Definition: network_udp.cpp:46
void HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config) override
Function that is called for every GRFConfig that is read when receiving a NetworkGameInfo.
Wrapper for (un)resolved network addresses; there&#39;s no reason to transform a numeric IP to a string a...
Definition: address.h:29
Tindex index
Index of this pool item.
Definition: pool_type.hpp:147
uint16 map_width
Map width.
Definition: game.h:38
Base socket handler for all UDP sockets.
Definition: udp.h:48
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:50
void Receive_MASTER_ACK_REGISTER(Packet *p, NetworkAddress *client_addr) override
The master server acknowledges the registration.
*** Communication with clients (we are server) ***/
GRF file was not found in the local cache.
Definition: newgrf_config.h:38
Structure with information shown in the game list (GUI)
const char * GetNetworkRevisionString()
Get the network version string used by this build.
Definition: network.cpp:1111
void NetworkUDPQueryServer(NetworkAddress address, bool manually)
Query a specific server.
Definition: network_udp.cpp:80
const GRFConfig * FindGRFConfig(uint32 grfid, FindGRFConfigMode mode, const uint8 *md5sum, uint32 desired_version)
Find a NewGRF in the scanned list.
Request to be removed from the server-list.
Definition: udp.h:31
GRFIdentifier ident
grfid and md5sum to uniquely identify newgrfs
NetworkUDPSocketHandler * _udp_server_socket
udp server socket
Definition: network_udp.cpp:49
Basic data to distinguish a GRF.
Definition: newgrf_config.h:84
bool _network_udp_server
Is the UDP server started?
Definition: network.cpp:79
struct GRFConfig * next
NOSAVE: Next item in the linked list.
char server_name[NETWORK_NAME_LENGTH]
Server name.
Definition: game.h:40
void NetworkUDPAdvertise()
Register us to the master server This function checks if it needs to send an advertise.
void UpdateNetworkGameWindow()
Update the network new window because a new server is found on the network.
Definition: network_gui.cpp:84
bool _network_dedicated
are we a dedicated server?
Definition: network.cpp:57
The game information that is sent from the server to the clients.
Definition: game.h:34
byte companies_max
Max companies allowed on server.
Definition: game.h:51
std::vector< NetworkAddress > NetworkAddressList
Type for a list of addresses.
Definition: address.h:20
bool StartNewThread(std::thread *thr, const char *name, TFn &&_Fx, TArgs &&... _Ax)
Start a new thread.
Definition: thread.h:50
virtual void Receive_CLIENT_FIND_SERVER(Packet *p, NetworkAddress *client_addr)
Queries to the server for information about the game.
Definition: udp.cpp:336
static const uint NETWORK_GRF_NAME_LENGTH
Maximum length of the name of a GRF.
Definition: config.h:54
NetworkAddressList _broadcast_list
List of broadcast addresses.
Definition: network.cpp:72
virtual void HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config)
Function that is called for every GRFConfig that is read when receiving a NetworkGameInfo.
Definition: udp.h:230
void Receive_CLIENT_FIND_SERVER(Packet *p, NetworkAddress *client_addr) override
Queries to the server for information about the game.
static const byte NETWORK_MASTER_SERVER_VERSION
What version of master-server-protocol do we use?
Definition: config.h:40
NetworkSettings network
settings related to the network
NetworkGameList * NetworkGameListAddItem(NetworkAddress address)
Add a new item to the linked gamelist.
GRFTextWrapper * FindUnknownGRFName(uint32 grfid, uint8 *md5sum, bool create)
Finds the name of a NewGRF in the list of names for unknown GRFs.
byte companies_on
How many started companies do we have.
Definition: game.h:50
void NetworkUDPSearchGame()
Find all servers.
void Send_uint64(uint64 data)
Package a 64 bits integer in the packet.
Definition: packet.cpp:132
*** Communication with the masterserver ***/
Definition: network_udp.cpp:90
Information about GRF, used in the game and (part of it) in savegames.
void SendCompanyInformation(Packet *p, const struct Company *c, const struct NetworkCompanyStats *stats, uint max_len=NETWORK_COMPANY_NAME_LENGTH)
Package some generic company information into a packet.
void AddGRFTextToList(GRFText **list, GRFText *text_to_add)
Add a GRFText to a GRFText list.
uint8 max_spectators
maximum amount of spectators
void Send_uint16(uint16 data)
Package a 16 bits integer in the packet.
Definition: packet.cpp:108
bool _network_need_advertise
Whether we need to advertise.
Definition: network.cpp:63
byte clients_max
Max clients allowed on server.
Definition: game.h:49
static const char *const NETWORK_MASTER_SERVER_HOST
DNS hostname of the masterserver.
Definition: config.h:18
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:80
Packet to register itself to the master server.
Definition: udp.h:27
std::mutex lock
synchronization for playback status fields
Definition: win32_m.cpp:36
void NetworkUDPQueryMasterServer()
Request the the server-list from the master server.
The data is copied from a grf in _all_grfs.
Definition: newgrf_config.h:28
static void NetworkUDPBroadCast(NetworkUDPSocketHandler *socket)
Broadcast to all ips.
bool use_password
Is this server passworded?
Definition: game.h:46
virtual void Receive_SERVER_NEWGRFS(Packet *p, NetworkAddress *client_addr)
The server returns information about some NewGRFs.
Definition: udp.cpp:346
void Close() override
Close the given UDP socket.
Definition: udp.cpp:60
static std::mutex _network_udp_mutex
Mutex for all out threaded udp resolution and such.
Definition: network_udp.cpp:39
Reply of the game server about details of the game, such as companies.
Definition: udp.h:26
uint8 flags
NOSAVE: GCF_Flags, bitset.
ServerListType
The types of server lists we can get.
Definition: udp.h:39
NetworkAddress address
The connection info of the game server.
const char * GetHostname()
Get the hostname; in case it wasn&#39;t given the IPv4 dotted representation is given.
Definition: address.cpp:24
byte clients_on
Current count of clients on server.
Definition: game.h:28
NetworkGameInfo info
The game information of this server.
char server_revision[NETWORK_REVISION_LENGTH]
The version number the server is using (e.g.: &#39;r304&#39; or 0.5.0)
Definition: game.h:42
void Receive_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr) override
Return of server information to the client.
Basic functions/variables used all over the place.
PacketSize size
The size of the whole packet for received packets.
Definition: packet.h:50
static const char *const NETWORK_MASTER_SERVER_WELCOME_MESSAGE
Message sent to the masterserver to &#39;identify&#39; this client as OpenTTD.
Definition: config.h:26
void Receive_CLIENT_DETAIL_INFO(Packet *p, NetworkAddress *client_addr) override
Query for detailed information about companies.
virtual void Receive_CLIENT_DETAIL_INFO(Packet *p, NetworkAddress *client_addr)
Query for detailed information about companies.
Definition: udp.cpp:338
NetworkServerGameInfo _network_game_info
Information about our game.
Definition: network.cpp:59
static T min(const T a, const T b)
Returns the minimum of two values.
Definition: math_func.hpp:42
uint8 server_lang
language of the server
Reference counted wrapper around a GRFText pointer.
bool dedicated
Is this a dedicated server?
Definition: game.h:43
void SendPacket(Packet *p, NetworkAddress *recv, bool all=false, bool broadcast=false)
Send a packet over UDP.
Definition: udp.cpp:81
ServerNetworkUDPSocketHandler(NetworkAddressList *addresses)
Create the socket.
uint8 max_companies
maximum amount of companies
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:37
void SetPort(uint16 port)
Set the port.
Definition: address.cpp:56
Sends the list of NewGRF&#39;s requested.
Definition: udp.h:33
void NetworkUDPInitialize()
Initialize the whole UDP bit.
GRFTextWrapper * url
NOSAVE: URL belonging to this GRF.
char map_name[NETWORK_NAME_LENGTH]
Map which is played ["random" for a randomized map].
Definition: game.h:27
uint16 server_port
port the server listens on
byte map_set
Graphical set.
Definition: game.h:54
NetworkUDPSocketHandler * _udp_client_socket
udp client socket
Definition: network_udp.cpp:48
Date game_date
Current date.
Definition: game.h:37
const char * GetGRFStringFromGRFText(const GRFText *text)
Get a C-string from a GRFText-list.
uint8 Recv_uint8()
Read a 8 bits integer from the packet.
Definition: packet.cpp:219
uint64 Recv_uint64()
Read a 64 bits integer from the packet.
Definition: packet.cpp:265
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:59
Variables and function used internally.
static void NetworkUDPRemoveAdvertiseThread()
Thread entry point for de-advertising.
static size_t GetNumItems()
Returns number of valid items in the pool.
Definition: pool_type.hpp:276
#define UNKNOWN_GRF_NAME_PLACEHOLDER
For communication about GRFs over the network.
Handling of the list of games.
static const uint32 ADVERTISE_NORMAL_INTERVAL
interval between advertising in ms (15 minutes)
Definition: network_udp.cpp:44
void NetworkBackgroundUDPLoop()
Receive the UDP packets.
void NetworkGameListAddItemDelayed(NetworkGameList *item)
Add a new item to the linked gamelist, but do it delayed in the next tick or so to prevent race condi...
static void DoNetworkUDPQueryServer(NetworkAddress &address, bool needs_mutex, bool manually)
Helper function doing the actual work for querying the server.
Definition: network_udp.cpp:58
uint8 max_clients
maximum amount of clients
static const uint NETWORK_COMPANY_NAME_LENGTH
The maximum length of the company name, in bytes including &#39;\0&#39;.
Definition: config.h:43
static const uint32 ADVERTISE_RETRY_INTERVAL
re-advertise when no response after this many ms (10 seconds)
Definition: network_udp.cpp:45
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: depend.cpp:68
char * filename
Filename - either with or without full path.
Maximum number of companies.
Definition: company_type.h:25
static const char * AddressFamilyAsString(int family)
Convert the address family into a string.
Definition: address.cpp:424
static const uint16 SEND_MTU
Number of bytes we can pack in a single packet.
Definition: config.h:35
GRFTextWrapper * name
NOSAVE: GRF name (Action 0x08)
MasterNetworkUDPSocketHandler(NetworkAddressList *addresses)
Create the socket.
Definition: network_udp.cpp:99
bool _network_server
network-server is active
Definition: network.cpp:55
bool manually
True if the server was added manually.
void NetworkUDPRemoveAdvertise(bool blocking)
Remove our advertise from the master-server.
void ReceiveNetworkGameInfo(Packet *p, NetworkGameInfo *info)
Deserializes the NetworkGameInfo struct from the packet.
Definition: udp.cpp:219
void Receive_CLIENT_GET_NEWGRFS(Packet *p, NetworkAddress *client_addr) override
A client has requested the names of some NewGRFs.
const char * GetName() const
Get the name of this grf.
uint32 grfid
GRF ID (defined by Action 0x08)
Definition: newgrf_config.h:85
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: depend.cpp:131
Reply of the game server with game information.
Definition: udp.h:24
virtual void Receive_MASTER_RESPONSE_LIST(Packet *p, NetworkAddress *client_addr)
The server sends a list of servers.
Definition: udp.cpp:343
void Receive_MASTER_RESPONSE_LIST(Packet *p, NetworkAddress *client_addr) override
The server sends a list of servers.
Simple calculated statistics of a company.
Definition: network_type.h:59
uint8 _network_advertise_retries
The number of advertisement retries we did.
Definition: network.cpp:81
char hostname[NETWORK_HOSTNAME_LENGTH]
Hostname of the server (if any)
Definition: game.h:41
End of &#39;arrays&#39; marker.
Definition: udp.h:44
GameCreationSettings game_creation
settings used during the creation of a game (map)
void ReceiveGRFIdentifier(Packet *p, GRFIdentifier *grf)
Deserializes the GRFIdentifier (GRF ID and MD5 checksum) from the packet.
Definition: core.cpp:73
Date ConvertYMDToDate(Year year, Month month, Day day)
Converts a tuple of Year, Month and Day to a Date.
Definition: date.cpp:149
uint16 Recv_uint16()
Read a 16 bits integer from the packet.
Definition: packet.cpp:233
uint8 md5sum[16]
MD5 checksum of file to distinguish files with the same GRF ID (eg. newer version of GRF) ...
Definition: newgrf_config.h:86
Only find Grfs matching md5sum.
static const byte NETWORK_COMPANY_INFO_VERSION
What version of company info is this?
Definition: config.h:39
char server_password[NETWORK_PASSWORD_LENGTH]
password for joining this server
void NetworkUDPClose()
Close all UDP related stuff.
Date _date
Current date in days (day counter)
Definition: date.cpp:28
GRFConfig * grfconfig
List of NewGRF files used.
Definition: game.h:35
void SendGRFIdentifier(Packet *p, const GRFIdentifier *grf)
Serializes the GRFIdentifier (GRF ID and MD5 checksum) to the packet.
Definition: core.cpp:59
Year starting_year
starting date
Basic functions to receive and send UDP packets.
static const uint16 NETWORK_MASTER_SERVER_PORT
The default port of the master server (UDP)
Definition: config.h:28
const sockaddr_storage * GetAddress()
Get the address in its internal representation.
Definition: address.cpp:126
void GetAddressAsString(char *buffer, const char *last, bool with_family=true)
Get the address as a string, e.g.
Definition: address.cpp:79
byte spectators_on
How many spectators do we have?
Definition: game.h:52
static const uint NETWORK_MAX_GRF_COUNT
Maximum number of GRFs that can be sent.
Definition: config.h:60
void Recv_string(char *buffer, size_t size, StringValidationSettings settings=SVS_REPLACE_WITH_QUESTION_MARK)
Reads a string till it finds a &#39;\0&#39; in the stream.
Definition: packet.cpp:288
bool IsResolved() const
Check whether the IP address has been resolved already.
Definition: address.h:117
GRFTextWrapper * info
NOSAVE: GRF info (author, copyright, ...) (Action 0x08)
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings_func.h:201