OpenTTD Source  1.11.2
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 "core/game_info.h"
20 #include "network_gamelist.h"
21 #include "network_internal.h"
22 #include "network_udp.h"
23 #include "network.h"
24 #include "../core/endian_func.hpp"
25 #include "../company_base.h"
26 #include "../thread.h"
27 #include "../rev.h"
28 #include "../newgrf_text.h"
29 #include "../strings_func.h"
30 #include "table/strings.h"
31 #include <mutex>
32 
33 #include "core/udp.h"
34 
35 #include "../safeguards.h"
36 
38 static uint64 _session_key = 0;
39 
40 static const std::chrono::minutes ADVERTISE_NORMAL_INTERVAL(15);
41 static const std::chrono::seconds ADVERTISE_RETRY_INTERVAL(10);
42 static const uint32 ADVERTISE_RETRY_TIMES = 3;
43 
44 static bool _network_udp_server;
45 static uint16 _network_udp_broadcast;
47 
49 struct UDPSocket {
50  const std::string name;
51  std::mutex mutex;
53  std::atomic<int> receive_iterations_locked;
54 
55  UDPSocket(const std::string &name_) : name(name_), socket(nullptr) {}
56 
57  void Close()
58  {
59  std::lock_guard<std::mutex> lock(mutex);
60  socket->Close();
61  delete socket;
62  socket = nullptr;
63  }
64 
65  void ReceivePackets()
66  {
67  std::unique_lock<std::mutex> lock(mutex, std::defer_lock);
68  if (!lock.try_lock()) {
69  if (++receive_iterations_locked % 32 == 0) {
70  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());
71  }
72  return;
73  }
74 
77  }
78 };
79 
80 static UDPSocket _udp_client("Client");
81 static UDPSocket _udp_server("Server");
82 static UDPSocket _udp_master("Master");
83 
90 static void DoNetworkUDPQueryServer(NetworkAddress &address, bool needs_mutex, bool manually)
91 {
92  /* Clear item in gamelist */
93  NetworkGameList *item = CallocT<NetworkGameList>(1);
95  strecpy(item->info.hostname, address.GetHostname(), lastof(item->info.hostname));
96  item->address = address;
97  item->manually = manually;
99 
100  std::unique_lock<std::mutex> lock(_udp_client.mutex, std::defer_lock);
101  if (needs_mutex) lock.lock();
102  /* Init the packet */
104  if (_udp_client.socket != nullptr) _udp_client.socket->SendPacket(&p, &address);
105 }
106 
112 void NetworkUDPQueryServer(NetworkAddress address, bool manually)
113 {
114  if (address.IsResolved() || !StartNewThread(nullptr, "ottd:udp-query", &DoNetworkUDPQueryServer, std::move(address), true, std::move(manually))) {
115  DoNetworkUDPQueryServer(address, true, manually);
116  }
117 }
118 
120 
123 protected:
124  void Receive_MASTER_ACK_REGISTER(Packet *p, NetworkAddress *client_addr) override;
125  void Receive_MASTER_SESSION_KEY(Packet *p, NetworkAddress *client_addr) override;
126 public:
132  virtual ~MasterNetworkUDPSocketHandler() {}
133 };
134 
136 {
138  DEBUG(net, 2, "[udp] advertising on master server successful (%s)", NetworkAddress::AddressFamilyAsString(client_addr->GetAddress()->ss_family));
139 
140  /* We are advertised, but we don't want to! */
142 }
143 
145 {
146  _session_key = p->Recv_uint64();
147  DEBUG(net, 2, "[udp] received new session key from master server (%s)", NetworkAddress::AddressFamilyAsString(client_addr->GetAddress()->ss_family));
148 }
149 
151 
154 protected:
155  void Receive_CLIENT_FIND_SERVER(Packet *p, NetworkAddress *client_addr) override;
156  void Receive_CLIENT_DETAIL_INFO(Packet *p, NetworkAddress *client_addr) override;
157  void Receive_CLIENT_GET_NEWGRFS(Packet *p, NetworkAddress *client_addr) override;
158 public:
164  virtual ~ServerNetworkUDPSocketHandler() {}
165 };
166 
168 {
169  /* Just a fail-safe.. should never happen */
170  if (!_network_udp_server) {
171  return;
172  }
173 
174  NetworkGameInfo ngi;
175  FillNetworkGameInfo(ngi);
176 
178  SerializeNetworkGameInfo(&packet, &ngi);
179 
180  /* Let the client know that we are here */
181  this->SendPacket(&packet, client_addr);
182 
183  DEBUG(net, 2, "[udp] queried from %s", client_addr->GetHostname());
184 }
185 
187 {
188  /* Just a fail-safe.. should never happen */
189  if (!_network_udp_server) return;
190 
192 
193  /* Send the amount of active companies */
195  packet.Send_uint8 ((uint8)Company::GetNumItems());
196 
197  /* Fetch the latest version of the stats */
198  NetworkCompanyStats company_stats[MAX_COMPANIES];
199  NetworkPopulateCompanyStats(company_stats);
200 
201  /* The minimum company information "blob" size. */
202  static const uint MIN_CI_SIZE = 54;
203  uint max_cname_length = NETWORK_COMPANY_NAME_LENGTH;
204 
205  if (Company::GetNumItems() * (MIN_CI_SIZE + NETWORK_COMPANY_NAME_LENGTH) >= (uint)SEND_MTU - packet.size) {
206  /* Assume we can at least put the company information in the packets. */
207  assert(Company::GetNumItems() * MIN_CI_SIZE < (uint)SEND_MTU - packet.size);
208 
209  /* At this moment the company names might not fit in the
210  * packet. Check whether that is really the case. */
211 
212  for (;;) {
213  int free = SEND_MTU - packet.size;
214  for (const Company *company : Company::Iterate()) {
215  char company_name[NETWORK_COMPANY_NAME_LENGTH];
216  SetDParam(0, company->index);
217  GetString(company_name, STR_COMPANY_NAME, company_name + max_cname_length - 1);
218  free -= MIN_CI_SIZE;
219  free -= (int)strlen(company_name);
220  }
221  if (free >= 0) break;
222 
223  /* Try again, with slightly shorter strings. */
224  assert(max_cname_length > 0);
225  max_cname_length--;
226  }
227  }
228 
229  /* Go through all the companies */
230  for (const Company *company : Company::Iterate()) {
231  /* Send the information */
232  this->SendCompanyInformation(&packet, company, &company_stats[company->index], max_cname_length);
233  }
234 
235  this->SendPacket(&packet, client_addr);
236 }
237 
252 {
253  uint8 num_grfs;
254  uint i;
255 
256  const GRFConfig *in_reply[NETWORK_MAX_GRF_COUNT];
257  uint8 in_reply_count = 0;
258  size_t packet_len = 0;
259 
260  DEBUG(net, 6, "[udp] newgrf data request from %s", client_addr->GetAddressAsString().c_str());
261 
262  num_grfs = p->Recv_uint8 ();
263  if (num_grfs > NETWORK_MAX_GRF_COUNT) return;
264 
265  for (i = 0; i < num_grfs; i++) {
266  GRFIdentifier c;
267  const GRFConfig *f;
268 
270 
271  /* Find the matching GRF file */
273  if (f == nullptr) continue; // The GRF is unknown to this server
274 
275  /* If the reply might exceed the size of the packet, only reply
276  * the current list and do not send the other data.
277  * The name could be an empty string, if so take the filename. */
278  packet_len += sizeof(c.grfid) + sizeof(c.md5sum) +
279  std::min(strlen(f->GetName()) + 1, (size_t)NETWORK_GRF_NAME_LENGTH);
280  if (packet_len > SEND_MTU - 4) { // 4 is 3 byte header + grf count in reply
281  break;
282  }
283  in_reply[in_reply_count] = f;
284  in_reply_count++;
285  }
286 
287  if (in_reply_count == 0) return;
288 
290  packet.Send_uint8(in_reply_count);
291  for (i = 0; i < in_reply_count; i++) {
292  char name[NETWORK_GRF_NAME_LENGTH];
293 
294  /* The name could be an empty string, if so take the filename */
295  strecpy(name, in_reply[i]->GetName(), lastof(name));
296  SerializeGRFIdentifier(&packet, &in_reply[i]->ident);
297  packet.Send_string(name);
298  }
299 
300  this->SendPacket(&packet, client_addr);
301 }
302 
304 
307 protected:
308  void Receive_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr) override;
309  void Receive_MASTER_RESPONSE_LIST(Packet *p, NetworkAddress *client_addr) override;
310  void Receive_SERVER_NEWGRFS(Packet *p, NetworkAddress *client_addr) override;
311 public:
312  virtual ~ClientNetworkUDPSocketHandler() {}
313 };
314 
316 {
317  NetworkGameList *item;
318 
319  /* Just a fail-safe.. should never happen */
320  if (_network_udp_server) return;
321 
322  DEBUG(net, 4, "[udp] server response from %s", client_addr->GetAddressAsString().c_str());
323 
324  /* Find next item */
325  item = NetworkGameListAddItem(*client_addr);
326 
328  DeserializeNetworkGameInfo(p, &item->info);
329 
330  item->info.compatible = true;
331  {
332  /* Checks whether there needs to be a request for names of GRFs and makes
333  * the request if necessary. GRFs that need to be requested are the GRFs
334  * that do not exist on the clients system and we do not have the name
335  * resolved of, i.e. the name is still UNKNOWN_GRF_NAME_PLACEHOLDER.
336  * The in_request array and in_request_count are used so there is no need
337  * to do a second loop over the GRF list, which can be relatively expensive
338  * due to the string comparisons. */
339  const GRFConfig *in_request[NETWORK_MAX_GRF_COUNT];
340  const GRFConfig *c;
341  uint in_request_count = 0;
342 
343  for (c = item->info.grfconfig; c != nullptr; c = c->next) {
344  if (c->status == GCS_NOT_FOUND) item->info.compatible = false;
345  if (c->status != GCS_NOT_FOUND || strcmp(c->GetName(), UNKNOWN_GRF_NAME_PLACEHOLDER) != 0) continue;
346  in_request[in_request_count] = c;
347  in_request_count++;
348  }
349 
350  if (in_request_count > 0) {
351  /* There are 'unknown' GRFs, now send a request for them */
352  uint i;
354 
355  packet.Send_uint8(in_request_count);
356  for (i = 0; i < in_request_count; i++) {
357  SerializeGRFIdentifier(&packet, &in_request[i]->ident);
358  }
359 
360  this->SendPacket(&packet, &item->address);
361  }
362  }
363 
364  if (item->info.hostname[0] == '\0') {
365  seprintf(item->info.hostname, lastof(item->info.hostname), "%s", client_addr->GetHostname());
366  }
367 
368  if (client_addr->GetAddress()->ss_family == AF_INET6) {
369  strecat(item->info.server_name, " (IPv6)", lastof(item->info.server_name));
370  }
371 
372  /* Check if we are allowed on this server based on the revision-match */
374  item->info.compatible &= item->info.version_compatible; // Already contains match for GRFs
375 
376  item->online = true;
377 
379 }
380 
382 {
383  /* packet begins with the protocol version (uint8)
384  * then an uint16 which indicates how many
385  * ip:port pairs are in this packet, after that
386  * an uint32 (ip) and an uint16 (port) for each pair.
387  */
388 
389  ServerListType type = (ServerListType)(p->Recv_uint8() - 1);
390 
391  if (type < SLT_END) {
392  for (int i = p->Recv_uint16(); i != 0 ; i--) {
393  sockaddr_storage addr_storage;
394  memset(&addr_storage, 0, sizeof(addr_storage));
395 
396  if (type == SLT_IPv4) {
397  addr_storage.ss_family = AF_INET;
398  ((sockaddr_in*)&addr_storage)->sin_addr.s_addr = TO_LE32(p->Recv_uint32());
399  } else {
400  assert(type == SLT_IPv6);
401  addr_storage.ss_family = AF_INET6;
402  byte *addr = (byte*)&((sockaddr_in6*)&addr_storage)->sin6_addr;
403  for (uint i = 0; i < sizeof(in6_addr); i++) *addr++ = p->Recv_uint8();
404  }
405  NetworkAddress addr(addr_storage, type == SLT_IPv4 ? sizeof(sockaddr_in) : sizeof(sockaddr_in6));
406  addr.SetPort(p->Recv_uint16());
407 
408  /* Somehow we reached the end of the packet */
409  if (this->HasClientQuit()) return;
410 
411  DoNetworkUDPQueryServer(addr, false, false);
412  }
413  }
414 }
415 
418 {
419  uint8 num_grfs;
420  uint i;
421 
422  DEBUG(net, 6, "[udp] newgrf data reply from %s", client_addr->GetAddressAsString().c_str());
423 
424  num_grfs = p->Recv_uint8 ();
425  if (num_grfs > NETWORK_MAX_GRF_COUNT) return;
426 
427  for (i = 0; i < num_grfs; i++) {
428  char name[NETWORK_GRF_NAME_LENGTH];
429  GRFIdentifier c;
430 
432  p->Recv_string(name, sizeof(name));
433 
434  /* An empty name is not possible under normal circumstances
435  * and causes problems when showing the NewGRF list. */
436  if (StrEmpty(name)) continue;
437 
438  /* Try to find the GRFTextWrapper for the name of this GRF ID and MD5sum tuple.
439  * If it exists and not resolved yet, then name of the fake GRF is
440  * overwritten with the name from the reply. */
441  GRFTextWrapper unknown_name = FindUnknownGRFName(c.grfid, c.md5sum, false);
442  if (unknown_name && strcmp(GetGRFStringFromGRFText(unknown_name), UNKNOWN_GRF_NAME_PLACEHOLDER) == 0) {
443  AddGRFTextToList(unknown_name, name);
444  }
445  }
446 }
447 
450 {
451  for (NetworkAddress &addr : _broadcast_list) {
453 
454  DEBUG(net, 4, "[udp] broadcasting to %s", addr.GetHostname());
455 
456  socket->SendPacket(&p, &addr, true, true);
457  }
458 }
459 
460 
463 {
466 
467  /* packet only contains protocol version */
470 
471  std::lock_guard<std::mutex> lock(_udp_client.mutex);
472  _udp_client.socket->SendPacket(&p, &out_addr, true);
473 
474  DEBUG(net, 2, "[udp] master server queried at %s", out_addr.GetAddressAsString().c_str());
475 }
476 
479 {
480  /* We are still searching.. */
481  if (_network_udp_broadcast > 0) return;
482 
483  DEBUG(net, 0, "[udp] searching server");
484 
486  _network_udp_broadcast = 300; // Stay searching for 300 ticks
487 }
488 
493 {
494  DEBUG(net, 1, "[udp] removing advertise from master server");
495 
496  /* Find somewhere to send */
498 
499  /* Send the packet */
501  /* Packet is: Version, server_port */
504 
505  std::lock_guard<std::mutex> lock(_udp_master.mutex);
506  if (_udp_master.socket != nullptr) _udp_master.socket->SendPacket(&p, &out_addr, true);
507 }
508 
513 void NetworkUDPRemoveAdvertise(bool blocking)
514 {
515  /* Check if we are advertising */
516  if (!_networking || !_network_server || !_network_udp_server) return;
517 
518  if (blocking || !StartNewThread(nullptr, "ottd:udp-advert", &NetworkUDPRemoveAdvertiseThread)) {
520  }
521 }
522 
527 {
528  /* Find somewhere to send */
530 
531  DEBUG(net, 1, "[udp] advertising to master server");
532 
533  /* Add a bit more messaging when we cannot get a session key */
534  static byte session_key_retries = 0;
535  if (_session_key == 0 && session_key_retries++ == 2) {
536  DEBUG(net, 0, "[udp] advertising to the master server is failing");
537  DEBUG(net, 0, "[udp] we are not receiving the session key from the server");
538  DEBUG(net, 0, "[udp] please allow udp packets from %s to you to be delivered", out_addr.GetAddressAsString(false).c_str());
539  DEBUG(net, 0, "[udp] please allow udp packets from you to %s to be delivered", out_addr.GetAddressAsString(false).c_str());
540  }
541  if (_session_key != 0 && _network_advertise_retries == 0) {
542  DEBUG(net, 0, "[udp] advertising to the master server is failing");
543  DEBUG(net, 0, "[udp] we are not receiving the acknowledgement from the server");
544  DEBUG(net, 0, "[udp] this usually means that the master server cannot reach us");
545  DEBUG(net, 0, "[udp] please allow udp and tcp packets to port %u to be delivered", _settings_client.network.server_port);
546  DEBUG(net, 0, "[udp] please allow udp and tcp packets from port %u to be delivered", _settings_client.network.server_port);
547  }
548 
549  /* Send the packet */
551  /* Packet is: WELCOME_MESSAGE, Version, server_port */
556 
557  std::lock_guard<std::mutex> lock(_udp_master.mutex);
558  if (_udp_master.socket != nullptr) _udp_master.socket->SendPacket(&p, &out_addr, true);
559 }
560 
566 {
567  static std::chrono::steady_clock::time_point _last_advertisement = {};
568 
569  /* Check if we should send an advertise */
571 
573  /* Forced advertisement. */
574  _network_need_advertise = false;
576  } else {
577  /* Only send once every ADVERTISE_NORMAL_INTERVAL ticks */
578  if (_network_advertise_retries == 0) {
579  if (std::chrono::steady_clock::now() <= _last_advertisement + ADVERTISE_NORMAL_INTERVAL) return;
580 
582  } else {
583  /* An actual retry. */
584  if (std::chrono::steady_clock::now() <= _last_advertisement + ADVERTISE_RETRY_INTERVAL) return;
585  }
586  }
587 
589  _last_advertisement = std::chrono::steady_clock::now();
590 
591  if (!StartNewThread(nullptr, "ottd:udp-advert", &NetworkUDPAdvertiseThread)) {
593  }
594 }
595 
598 {
599  /* If not closed, then do it. */
600  if (_udp_server.socket != nullptr) NetworkUDPClose();
601 
602  DEBUG(net, 1, "[udp] initializing listeners");
603  assert(_udp_client.socket == nullptr && _udp_server.socket == nullptr && _udp_master.socket == nullptr);
604 
606 
608 
609  NetworkAddressList server;
612 
613  server.clear();
614  GetBindAddresses(&server, 0);
616 
617  _network_udp_server = false;
620 }
621 
624 {
625  std::lock_guard<std::mutex> lock(_udp_server.mutex);
627 }
628 
631 {
632  _udp_client.Close();
633  _udp_server.Close();
634  _udp_master.Close();
635 
636  _network_udp_server = false;
638  DEBUG(net, 1, "[udp] closed listeners");
639 }
640 
643 {
644  if (_network_udp_server) {
645  _udp_server.ReceivePackets();
646  _udp_master.ReceivePackets();
647  } else {
648  _udp_client.ReceivePackets();
650  }
651 }
NetworkGameInfo
The game information that is sent from the server to the clients.
Definition: game_info.h:71
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:26
NetworkUDPSocketHandler
Base socket handler for all UDP sockets.
Definition: udp.h:45
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
SerializeGRFIdentifier
void SerializeGRFIdentifier(Packet *p, const GRFIdentifier *grf)
Serializes the GRFIdentifier (GRF ID and MD5 checksum) to the packet.
Definition: game_info.cpp:305
UDPSocket::name
const std::string name
The name of the socket.
Definition: network_udp.cpp:50
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:738
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:29
DeserializeNetworkGameInfo
void DeserializeNetworkGameInfo(Packet *p, NetworkGameInfo *info)
Deserializes the NetworkGameInfo struct from the packet.
Definition: game_info.cpp:231
ClearGRFConfigList
void ClearGRFConfigList(GRFConfig **config)
Clear a GRF Config list, freeing all nodes.
Definition: newgrf_config.cpp:402
_network_advertise_retries
static uint8 _network_advertise_retries
The number of advertisement retries we did.
Definition: network_udp.cpp:46
NetworkUDPServerListen
void NetworkUDPServerListen()
Start the listening of the UDP server component.
Definition: network_udp.cpp:623
GetBindAddresses
void GetBindAddresses(NetworkAddressList *addresses, uint16 port)
Get the addresses to bind to.
Definition: network.cpp:619
ServerListType
ServerListType
The types of server lists we can get.
Definition: udp.h:36
NetworkSettings::server_port
uint16 server_port
port the server listens on
Definition: settings_type.h:262
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:20
NetworkPopulateCompanyStats
void NetworkPopulateCompanyStats(NetworkCompanyStats *stats)
Populate the company stats.
Definition: network_server.cpp:1587
DeserializeGRFIdentifier
void DeserializeGRFIdentifier(Packet *p, GRFIdentifier *grf)
Deserializes the GRFIdentifier (GRF ID and MD5 checksum) from the packet.
Definition: game_info.cpp:319
NetworkUDPAdvertiseThread
static void NetworkUDPAdvertiseThread()
Thread entry point for advertising.
Definition: network_udp.cpp:526
PACKET_UDP_SERVER_UNREGISTER
@ PACKET_UDP_SERVER_UNREGISTER
Request to be removed from the server-list.
Definition: udp.h:28
_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:24
_udp_server
static UDPSocket _udp_server("Server")
udp server socket
NetworkUDPBroadCast
static void NetworkUDPBroadCast(NetworkUDPSocketHandler *socket)
Broadcast to all ips.
Definition: network_udp.cpp:449
NetworkUDPSocketHandler::Close
void Close() override
Close the given UDP socket.
Definition: udp.cpp:59
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:144
NetworkGameInfo::hostname
char hostname[NETWORK_HOSTNAME_LENGTH]
Hostname of the server (if any)
Definition: game_info.h:78
GCS_NOT_FOUND
@ GCS_NOT_FOUND
GRF file was not found in the local cache.
Definition: newgrf_config.h:37
_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:565
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:478
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:49
ADVERTISE_RETRY_INTERVAL
static const std::chrono::seconds ADVERTISE_RETRY_INTERVAL(10)
re-advertise when no response after this amount of time.
SLT_IPv6
@ SLT_IPv6
Get the IPv6 addresses.
Definition: udp.h:38
NetworkGameList::address
NetworkAddress address
The connection info of the game server.
Definition: network_gamelist.h:20
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_info.h:81
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
ADVERTISE_RETRY_TIMES
static const uint32 ADVERTISE_RETRY_TIMES
give up re-advertising after this much failed retries
Definition: network_udp.cpp:42
NetworkUDPQueryServer
void NetworkUDPQueryServer(NetworkAddress address, bool manually)
Query a specific server.
Definition: network_udp.cpp:112
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
FillNetworkGameInfo
void FillNetworkGameInfo(NetworkGameInfo &ngi)
Fill a NetworkGameInfo structure with the latest information of the server.
Definition: game_info.cpp:113
UDPSocket::receive_iterations_locked
std::atomic< int > receive_iterations_locked
The number of receive iterations the mutex was locked.
Definition: network_udp.cpp:53
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:417
Packet::Recv_uint32
uint32 Recv_uint32()
Read a 32 bits integer from the packet.
Definition: packet.cpp:246
NetworkUDPQueryMasterServer
void NetworkUDPQueryMasterServer()
Request the the server-list from the master server.
Definition: network_udp.cpp:462
IsNetworkCompatibleVersion
bool IsNetworkCompatibleVersion(const char *other)
Checks whether the given version string is compatible with our version.
Definition: game_info.cpp:95
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:135
DEBUG
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:35
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
UDPSocket::mutex
std::mutex mutex
Mutex for everything that (indirectly) touches the sockets within the handler.
Definition: network_udp.cpp:51
UDPSocket::socket
NetworkUDPSocketHandler * socket
The actual socket, which may be nullptr when not initialized yet.
Definition: network_udp.cpp:52
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:22
StartNewThread
bool StartNewThread(std::thread *thr, const char *name, TFn &&_Fx, TArgs &&... _Ax)
Start a new thread.
Definition: thread.h:45
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:513
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:23
_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:45
SLT_END
@ SLT_END
End of 'arrays' marker.
Definition: udp.h:41
SLT_IPv4
@ SLT_IPv4
Get the IPv4 addresses.
Definition: udp.h:37
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_info.h:77
ClientNetworkUDPSocketHandler
‍*** Communication with servers (we are client) ***‍/
Definition: network_udp.cpp:306
PACKET_UDP_SERVER_NEWGRFS
@ PACKET_UDP_SERVER_NEWGRFS
Sends the list of NewGRF's requested.
Definition: udp.h:30
PACKET_UDP_SERVER_RESPONSE
@ PACKET_UDP_SERVER_RESPONSE
Reply of the game server with game information.
Definition: udp.h:21
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:167
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:642
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:153
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:44
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:90
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:315
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:251
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:122
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:597
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:186
network_internal.h
NetworkUDPSocketHandler::Listen
bool Listen()
Start listening on the given host and port.
Definition: udp.cpp:44
SLT_AUTODETECT
@ SLT_AUTODETECT
Autodetect the type based on the connection.
Definition: udp.h:39
seprintf
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:460
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:381
game_info.h
udp.h
_network_need_advertise
bool _network_need_advertise
Whether we need to advertise.
Definition: network.cpp:60
Packet::Recv_uint8
uint8 Recv_uint8()
Read a 8 bits integer from the packet.
Definition: packet.cpp:217
SerializeNetworkGameInfo
void SerializeNetworkGameInfo(Packet *p, const NetworkGameInfo *info)
Serializes the NetworkGameInfo struct to the packet.
Definition: game_info.cpp:169
NetworkGameList
Structure with information shown in the game list (GUI)
Definition: network_gamelist.h:18
network.h
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_info.h:79
NetworkUDPClose
void NetworkUDPClose()
Close all UDP related stuff.
Definition: network_udp.cpp:630
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:1538
NetworkUDPSocketHandler::ReceivePackets
void ReceivePackets()
Receive a packet at UDP level.
Definition: udp.cpp:116
network_gamelist.h
MasterNetworkUDPSocketHandler::MasterNetworkUDPSocketHandler
MasterNetworkUDPSocketHandler(NetworkAddressList *addresses)
Create the socket.
Definition: network_udp.cpp:131
NetworkUDPRemoveAdvertiseThread
static void NetworkUDPRemoveAdvertiseThread()
Thread entry point for de-advertising.
Definition: network_udp.cpp:492
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:163
GRFTextWrapper
std::shared_ptr< GRFTextList > GRFTextWrapper
Reference counted wrapper around a GRFText pointer.
Definition: newgrf_text.h:33
NetworkGameList::info
NetworkGameInfo info
The game information of this server.
Definition: network_gamelist.h:19
_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:785
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:456
strecat
char * strecat(char *dst, const char *src, const char *last)
Appends characters from one string to another.
Definition: string.cpp:84
NetworkGameInfo::grfconfig
GRFConfig * grfconfig
List of NewGRF files used.
Definition: game_info.h:72
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:21
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:385
_broadcast_list
NetworkAddressList _broadcast_list
List of broadcast addresses.
Definition: network.cpp:69
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_info.h:82
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:80
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
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:105
_session_key
static uint64 _session_key
Session key to register ourselves to the master server.
Definition: network_udp.cpp:38
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