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