OpenTTD Source  1.11.1
network.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 
10 #include "../stdafx.h"
11 
12 #include "../strings_func.h"
13 #include "../command_func.h"
14 #include "../date_func.h"
15 #include "network_admin.h"
16 #include "network_client.h"
17 #include "network_server.h"
18 #include "network_content.h"
19 #include "network_udp.h"
20 #include "network_gamelist.h"
21 #include "network_base.h"
22 #include "core/udp.h"
23 #include "core/host.h"
24 #include "network_gui.h"
25 #include "../console_func.h"
26 #include "../3rdparty/md5/md5.h"
27 #include "../core/random_func.hpp"
28 #include "../window_func.h"
29 #include "../company_func.h"
30 #include "../company_base.h"
31 #include "../landscape_type.h"
32 #include "../rev.h"
33 #include "../core/pool_func.hpp"
34 #include "../gfx_func.h"
35 #include "../error.h"
36 
37 #include "../safeguards.h"
38 
39 #ifdef DEBUG_DUMP_COMMANDS
40 #include "../fileio_func.h"
42 bool _ddc_fastforward = true;
43 #endif /* DEBUG_DUMP_COMMANDS */
44 
47 
51 
71 uint32 _sync_seed_1;
72 #ifdef NETWORK_SEND_DOUBLE_SEED
73 uint32 _sync_seed_2;
74 #endif
75 uint32 _sync_frame;
78 
79 /* Check whether NETWORK_NUM_LANDSCAPES is still in sync with NUM_LANDSCAPE */
80 static_assert((int)NETWORK_NUM_LANDSCAPES == (int)NUM_LANDSCAPE);
82 
85 
86 /* Some externs / forwards */
87 extern void StateGameLoop();
88 
93 bool HasClients()
94 {
95  return !NetworkClientSocket::Iterate().empty();
96 }
97 
102 {
103  /* Delete the chat window, if you were chatting with this client. */
105 }
106 
113 {
115  if (ci->client_id == client_id) return ci;
116  }
117 
118  return nullptr;
119 }
120 
127 {
128  for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
129  if (cs->client_id == client_id) return cs;
130  }
131 
132  return nullptr;
133 }
134 
135 byte NetworkSpectatorCount()
136 {
137  byte count = 0;
138 
139  for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
140  if (ci->client_playas == COMPANY_SPECTATOR) count++;
141  }
142 
143  /* Don't count a dedicated server as spectator */
144  if (_network_dedicated) count--;
145 
146  return count;
147 }
148 
155 const char *NetworkChangeCompanyPassword(CompanyID company_id, const char *password)
156 {
157  if (strcmp(password, "*") == 0) password = "";
158 
159  if (_network_server) {
160  NetworkServerSetCompanyPassword(company_id, password, false);
161  } else {
163  }
164 
165  return password;
166 }
167 
175 const char *GenerateCompanyPasswordHash(const char *password, const char *password_server_id, uint32 password_game_seed)
176 {
177  if (StrEmpty(password)) return password;
178 
179  char salted_password[NETWORK_SERVER_ID_LENGTH];
180 
181  memset(salted_password, 0, sizeof(salted_password));
182  seprintf(salted_password, lastof(salted_password), "%s", password);
183  /* Add the game seed and the server's ID as the salt. */
184  for (uint i = 0; i < NETWORK_SERVER_ID_LENGTH - 1; i++) {
185  salted_password[i] ^= password_server_id[i] ^ (password_game_seed >> (i % 32));
186  }
187 
188  Md5 checksum;
189  uint8 digest[16];
190  static char hashed_password[NETWORK_SERVER_ID_LENGTH];
191 
192  /* Generate the MD5 hash */
193  checksum.Append(salted_password, sizeof(salted_password) - 1);
194  checksum.Finish(digest);
195 
196  for (int di = 0; di < 16; di++) seprintf(hashed_password + di * 2, lastof(hashed_password), "%02x", digest[di]);
197 
198  return hashed_password;
199 }
200 
207 {
208  return HasBit(_network_company_passworded, company_id);
209 }
210 
211 /* This puts a text-message to the console, or in the future, the chat-box,
212  * (to keep it all a bit more general)
213  * If 'self_send' is true, this is the client who is sending the message */
214 void NetworkTextMessage(NetworkAction action, TextColour colour, bool self_send, const char *name, const char *str, int64 data)
215 {
216  StringID strid;
217  switch (action) {
218  case NETWORK_ACTION_SERVER_MESSAGE:
219  /* Ignore invalid messages */
220  strid = STR_NETWORK_SERVER_MESSAGE;
221  colour = CC_DEFAULT;
222  break;
223  case NETWORK_ACTION_COMPANY_SPECTATOR:
224  colour = CC_DEFAULT;
225  strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_SPECTATE;
226  break;
227  case NETWORK_ACTION_COMPANY_JOIN:
228  colour = CC_DEFAULT;
229  strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_JOIN;
230  break;
231  case NETWORK_ACTION_COMPANY_NEW:
232  colour = CC_DEFAULT;
233  strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_NEW;
234  break;
235  case NETWORK_ACTION_JOIN:
236  /* Show the Client ID for the server but not for the client. */
237  strid = _network_server ? STR_NETWORK_MESSAGE_CLIENT_JOINED_ID : STR_NETWORK_MESSAGE_CLIENT_JOINED;
238  break;
239  case NETWORK_ACTION_LEAVE: strid = STR_NETWORK_MESSAGE_CLIENT_LEFT; break;
240  case NETWORK_ACTION_NAME_CHANGE: strid = STR_NETWORK_MESSAGE_NAME_CHANGE; break;
241  case NETWORK_ACTION_GIVE_MONEY: strid = STR_NETWORK_MESSAGE_GIVE_MONEY; break;
242  case NETWORK_ACTION_CHAT_COMPANY: strid = self_send ? STR_NETWORK_CHAT_TO_COMPANY : STR_NETWORK_CHAT_COMPANY; break;
243  case NETWORK_ACTION_CHAT_CLIENT: strid = self_send ? STR_NETWORK_CHAT_TO_CLIENT : STR_NETWORK_CHAT_CLIENT; break;
244  case NETWORK_ACTION_KICKED: strid = STR_NETWORK_MESSAGE_KICKED; break;
245  default: strid = STR_NETWORK_CHAT_ALL; break;
246  }
247 
248  char message[1024];
249  SetDParamStr(0, name);
250  SetDParamStr(1, str);
251  SetDParam(2, data);
252 
253  /* All of these strings start with "***". These characters are interpreted as both left-to-right and
254  * right-to-left characters depending on the context. As the next text might be an user's name, the
255  * user name's characters will influence the direction of the "***" instead of the language setting
256  * of the game. Manually set the direction of the "***" by inserting a text-direction marker. */
257  char *msg_ptr = message + Utf8Encode(message, _current_text_dir == TD_LTR ? CHAR_TD_LRM : CHAR_TD_RLM);
258  GetString(msg_ptr, strid, lastof(message));
259 
260  DEBUG(desync, 1, "msg: %08x; %02x; %s", _date, _date_fract, message);
261  IConsolePrintF(colour, "%s", message);
263 }
264 
265 /* Calculate the frame-lag of a client */
266 uint NetworkCalculateLag(const NetworkClientSocket *cs)
267 {
268  int lag = cs->last_frame_server - cs->last_frame;
269  /* This client has missed his ACK packet after 1 DAY_TICKS..
270  * so we increase his lag for every frame that passes!
271  * The packet can be out by a max of _net_frame_freq */
272  if (cs->last_frame_server + DAY_TICKS + _settings_client.network.frame_freq < _frame_counter) {
273  lag += _frame_counter - (cs->last_frame_server + DAY_TICKS + _settings_client.network.frame_freq);
274  }
275  return lag;
276 }
277 
278 
279 /* There was a non-recoverable error, drop back to the main menu with a nice
280  * error */
281 void NetworkError(StringID error_string)
282 {
285 }
286 
293 {
294  /* List of possible network errors, used by
295  * PACKET_SERVER_ERROR and PACKET_CLIENT_ERROR */
296  static const StringID network_error_strings[] = {
297  STR_NETWORK_ERROR_CLIENT_GENERAL,
298  STR_NETWORK_ERROR_CLIENT_DESYNC,
299  STR_NETWORK_ERROR_CLIENT_SAVEGAME,
300  STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST,
301  STR_NETWORK_ERROR_CLIENT_PROTOCOL_ERROR,
302  STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH,
303  STR_NETWORK_ERROR_CLIENT_NOT_AUTHORIZED,
304  STR_NETWORK_ERROR_CLIENT_NOT_EXPECTED,
305  STR_NETWORK_ERROR_CLIENT_WRONG_REVISION,
306  STR_NETWORK_ERROR_CLIENT_NAME_IN_USE,
307  STR_NETWORK_ERROR_CLIENT_WRONG_PASSWORD,
308  STR_NETWORK_ERROR_CLIENT_COMPANY_MISMATCH,
309  STR_NETWORK_ERROR_CLIENT_KICKED,
310  STR_NETWORK_ERROR_CLIENT_CHEATER,
311  STR_NETWORK_ERROR_CLIENT_SERVER_FULL,
312  STR_NETWORK_ERROR_CLIENT_TOO_MANY_COMMANDS,
313  STR_NETWORK_ERROR_CLIENT_TIMEOUT_PASSWORD,
314  STR_NETWORK_ERROR_CLIENT_TIMEOUT_COMPUTER,
315  STR_NETWORK_ERROR_CLIENT_TIMEOUT_MAP,
316  STR_NETWORK_ERROR_CLIENT_TIMEOUT_JOIN,
317  };
318  static_assert(lengthof(network_error_strings) == NETWORK_ERROR_END);
319 
320  if (err >= (ptrdiff_t)lengthof(network_error_strings)) err = NETWORK_ERROR_GENERAL;
321 
322  return network_error_strings[err];
323 }
324 
330 void NetworkHandlePauseChange(PauseMode prev_mode, PauseMode changed_mode)
331 {
332  if (!_networking) return;
333 
334  switch (changed_mode) {
335  case PM_PAUSED_NORMAL:
336  case PM_PAUSED_JOIN:
339  case PM_PAUSED_LINK_GRAPH: {
340  bool changed = ((_pause_mode == PM_UNPAUSED) != (prev_mode == PM_UNPAUSED));
341  bool paused = (_pause_mode != PM_UNPAUSED);
342  if (!paused && !changed) return;
343 
344  StringID str;
345  if (!changed) {
346  int i = -1;
347 
348  if ((_pause_mode & PM_PAUSED_NORMAL) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_MANUAL);
349  if ((_pause_mode & PM_PAUSED_JOIN) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_CONNECTING_CLIENTS);
350  if ((_pause_mode & PM_PAUSED_GAME_SCRIPT) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_GAME_SCRIPT);
351  if ((_pause_mode & PM_PAUSED_ACTIVE_CLIENTS) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_NOT_ENOUGH_PLAYERS);
352  if ((_pause_mode & PM_PAUSED_LINK_GRAPH) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_LINK_GRAPH);
353  str = STR_NETWORK_SERVER_MESSAGE_GAME_STILL_PAUSED_1 + i;
354  } else {
355  switch (changed_mode) {
356  case PM_PAUSED_NORMAL: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_MANUAL); break;
357  case PM_PAUSED_JOIN: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_CONNECTING_CLIENTS); break;
358  case PM_PAUSED_GAME_SCRIPT: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_GAME_SCRIPT); break;
359  case PM_PAUSED_ACTIVE_CLIENTS: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_NOT_ENOUGH_PLAYERS); break;
360  case PM_PAUSED_LINK_GRAPH: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_LINK_GRAPH); break;
361  default: NOT_REACHED();
362  }
363  str = paused ? STR_NETWORK_SERVER_MESSAGE_GAME_PAUSED : STR_NETWORK_SERVER_MESSAGE_GAME_UNPAUSED;
364  }
365 
366  char buffer[DRAW_STRING_BUFFER];
367  GetString(buffer, str, lastof(buffer));
368  NetworkTextMessage(NETWORK_ACTION_SERVER_MESSAGE, CC_DEFAULT, false, nullptr, buffer);
369  break;
370  }
371 
372  default:
373  return;
374  }
375 }
376 
377 
386 static void CheckPauseHelper(bool pause, PauseMode pm)
387 {
388  if (pause == ((_pause_mode & pm) != PM_UNPAUSED)) return;
389 
390  DoCommandP(0, pm, pause ? 1 : 0, CMD_PAUSE);
391 }
392 
399 {
400  uint count = 0;
401 
402  for (const NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
403  if (cs->status != NetworkClientSocket::STATUS_ACTIVE) continue;
404  if (!Company::IsValidID(cs->GetInfo()->client_playas)) continue;
405  count++;
406  }
407 
408  return count;
409 }
410 
415 {
419  return;
420  }
422 }
423 
429 {
430  for (const NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
431  if (cs->status >= NetworkClientSocket::STATUS_AUTHORIZED && cs->status < NetworkClientSocket::STATUS_ACTIVE) return true;
432  }
433 
434  return false;
435 }
436 
440 static void CheckPauseOnJoin()
441 {
444  return;
445  }
447 }
448 
457 void ParseConnectionString(const char **company, const char **port, char *connection_string)
458 {
459  bool ipv6 = (strchr(connection_string, ':') != strrchr(connection_string, ':'));
460  char *p;
461  for (p = connection_string; *p != '\0'; p++) {
462  switch (*p) {
463  case '[':
464  ipv6 = true;
465  break;
466 
467  case ']':
468  ipv6 = false;
469  break;
470 
471  case '#':
472  *company = p + 1;
473  *p = '\0';
474  break;
475 
476  case ':':
477  if (ipv6) break;
478  *port = p + 1;
479  *p = '\0';
480  break;
481  }
482  }
483 }
484 
490 /* static */ void ServerNetworkGameSocketHandler::AcceptConnection(SOCKET s, const NetworkAddress &address)
491 {
492  /* Register the login */
494 
497  cs->client_address = address; // Save the IP of the client
498 }
499 
504 static void InitializeNetworkPools(bool close_admins = true)
505 {
506  PoolBase::Clean(PT_NCLIENT | (close_admins ? PT_NADMIN : PT_NONE));
507 }
508 
513 void NetworkClose(bool close_admins)
514 {
515  if (_network_server) {
516  if (close_admins) {
518  as->CloseConnection(true);
519  }
520  }
521 
522  for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
523  cs->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
524  }
527  } else if (MyClient::my_client != nullptr) {
530  }
531 
533 
534  _networking = false;
535  _network_server = false;
536 
538 
540  _network_company_states = nullptr;
541 
542  InitializeNetworkPools(close_admins);
543 }
544 
545 /* Initializes the network (cleans sockets and stuff) */
546 static void NetworkInitialize(bool close_admins = true)
547 {
548  InitializeNetworkPools(close_admins);
550 
551  _sync_frame = 0;
552  _network_first_time = true;
553 
554  _network_reconnect = 0;
555 }
556 
559 public:
561 
562  void OnFailure() override
563  {
565  }
566 
567  void OnConnect(SOCKET s) override
568  {
569  _networking = true;
572  }
573 };
574 
575 /* Query a server to fetch his game-info
576  * If game_info is true, only the gameinfo is fetched,
577  * else only the client_info is fetched */
578 void NetworkTCPQueryServer(NetworkAddress address)
579 {
580  if (!_network_available) return;
581 
583  NetworkInitialize();
584 
585  new TCPQueryConnecter(address);
586 }
587 
588 /* Validates an address entered as a string and adds the server to
589  * the list. If you use this function, the games will be marked
590  * as manually added. */
591 void NetworkAddServer(const char *b)
592 {
593  if (*b != '\0') {
594  const char *port = nullptr;
595  const char *company = nullptr;
596  char host[NETWORK_HOSTNAME_LENGTH];
597  uint16 rport;
598 
599  strecpy(host, b, lastof(host));
600 
602  rport = NETWORK_DEFAULT_PORT;
603 
604  ParseConnectionString(&company, &port, host);
605  if (port != nullptr) rport = atoi(port);
606 
607  NetworkUDPQueryServer(NetworkAddress(host, rport), true);
608  }
609 }
610 
616 void GetBindAddresses(NetworkAddressList *addresses, uint16 port)
617 {
618  for (const auto &iter : _network_bind_list) {
619  addresses->emplace_back(iter.c_str(), port);
620  }
621 
622  /* No address, so bind to everything. */
623  if (addresses->size() == 0) {
624  addresses->emplace_back("", port);
625  }
626 }
627 
628 /* Generates the list of manually added hosts from NetworkGameList and
629  * dumps them into the array _network_host_list. This array is needed
630  * by the function that generates the config file. */
631 void NetworkRebuildHostList()
632 {
633  _network_host_list.clear();
634 
635  for (NetworkGameList *item = _network_game_list; item != nullptr; item = item->next) {
636  if (item->manually) _network_host_list.emplace_back(item->address.GetAddressAsString(false));
637  }
638 }
639 
642 public:
644 
645  void OnFailure() override
646  {
647  NetworkError(STR_NETWORK_ERROR_NOCONNECTION);
648  }
649 
650  void OnConnect(SOCKET s) override
651  {
652  _networking = true;
654  IConsoleCmdExec("exec scripts/on_client.scr 0");
656  }
657 };
658 
659 
660 /* Used by clients, to connect to a server */
661 void NetworkClientConnectGame(NetworkAddress address, CompanyID join_as, const char *join_server_password, const char *join_company_password)
662 {
663  if (!_network_available) return;
664 
665  if (address.GetPort() == 0) return;
666 
669  _network_join_as = join_as;
670  _network_join_server_password = join_server_password;
671  _network_join_company_password = join_company_password;
672 
674  NetworkInitialize();
675 
676  _network_join_status = NETWORK_JOIN_STATUS_CONNECTING;
677  ShowJoinStatusWindow();
678 
679  new TCPClientConnecter(address);
680 }
681 
682 static void NetworkInitGameInfo()
683 {
686  }
687 
688  /* The server is a client too */
690 
691  /* There should be always space for the server. */
695 
697 }
698 
699 bool NetworkServerStart()
700 {
701  if (!_network_available) return false;
702 
703  /* Call the pre-scripts */
704  IConsoleCmdExec("exec scripts/pre_server.scr 0");
705  if (_network_dedicated) IConsoleCmdExec("exec scripts/pre_dedicated.scr 0");
706 
707  NetworkDisconnect(false, false);
708  NetworkInitialize(false);
709  DEBUG(net, 1, "starting listeners for clients");
711 
712  /* Only listen for admins when the password isn't empty. */
714  DEBUG(net, 1, "starting listeners for admins");
716  }
717 
718  /* Try to start UDP-server */
719  DEBUG(net, 1, "starting listeners for incoming server queries");
721 
722  _network_company_states = CallocT<NetworkCompanyState>(MAX_COMPANIES);
723  _network_server = true;
724  _networking = true;
725  _frame_counter = 0;
727  _frame_counter_max = 0;
728  _last_sync_frame = 0;
730 
733 
734  NetworkInitGameInfo();
735 
736  /* execute server initialization script */
737  IConsoleCmdExec("exec scripts/on_server.scr 0");
738  /* if the server is dedicated ... add some other script */
739  if (_network_dedicated) IConsoleCmdExec("exec scripts/on_dedicated.scr 0");
740 
741  /* Try to register us to the master server */
744 
745  /* welcome possibly still connected admins - this can only happen on a dedicated server. */
747 
748  return true;
749 }
750 
751 /* The server is rebooting...
752  * The only difference with NetworkDisconnect, is the packets that is sent */
753 void NetworkReboot()
754 {
755  if (_network_server) {
756  for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
757  cs->SendNewGame();
758  cs->SendPackets();
759  }
760 
762  as->SendNewGame();
763  as->SendPackets();
764  }
765  }
766 
767  /* For non-dedicated servers we have to kick the admins as we are not
768  * certain that we will end up in a new network game. */
770 }
771 
777 void NetworkDisconnect(bool blocking, bool close_admins)
778 {
779  if (_network_server) {
780  for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
781  cs->SendShutdown();
782  cs->SendPackets();
783  }
784 
785  if (close_admins) {
787  as->SendShutdown();
788  as->SendPackets();
789  }
790  }
791  }
792 
794 
796 
797  NetworkClose(close_admins);
798 
799  /* Reinitialize the UDP stack, i.e. close all existing connections. */
801 }
802 
807 static bool NetworkReceive()
808 {
809  if (_network_server) {
812  } else {
814  }
815 }
816 
817 /* This sends all buffered commands (if possible) */
818 static void NetworkSend()
819 {
820  if (_network_server) {
823  } else {
825  }
826 }
827 
834 {
838 
840 }
841 
842 /* The main loop called from ttd.c
843  * Here we also have to do StateGameLoop if needed! */
844 void NetworkGameLoop()
845 {
846  if (!_networking) return;
847 
848  if (!NetworkReceive()) return;
849 
850  if (_network_server) {
851  /* Log the sync state to check for in-syncedness of replays. */
852  if (_date_fract == 0) {
853  /* We don't want to log multiple times if paused. */
854  static Date last_log;
855  if (last_log != _date) {
856  DEBUG(desync, 1, "sync: %08x; %02x; %08x; %08x", _date, _date_fract, _random.state[0], _random.state[1]);
857  last_log = _date;
858  }
859  }
860 
861 #ifdef DEBUG_DUMP_COMMANDS
862  /* Loading of the debug commands from -ddesync>=1 */
863  static FILE *f = FioFOpenFile("commands.log", "rb", SAVE_DIR);
864  static Date next_date = 0;
865  static uint32 next_date_fract;
866  static CommandPacket *cp = nullptr;
867  static bool check_sync_state = false;
868  static uint32 sync_state[2];
869  if (f == nullptr && next_date == 0) {
870  DEBUG(net, 0, "Cannot open commands.log");
871  next_date = 1;
872  }
873 
874  while (f != nullptr && !feof(f)) {
875  if (_date == next_date && _date_fract == next_date_fract) {
876  if (cp != nullptr) {
877  NetworkSendCommand(cp->tile, cp->p1, cp->p2, cp->cmd & ~CMD_FLAGS_MASK, nullptr, cp->text, cp->company);
878  DEBUG(net, 0, "injecting: %08x; %02x; %02x; %06x; %08x; %08x; %08x; \"%s\" (%s)", _date, _date_fract, (int)_current_company, cp->tile, cp->p1, cp->p2, cp->cmd, cp->text, GetCommandName(cp->cmd));
879  free(cp);
880  cp = nullptr;
881  }
882  if (check_sync_state) {
883  if (sync_state[0] == _random.state[0] && sync_state[1] == _random.state[1]) {
884  DEBUG(net, 0, "sync check: %08x; %02x; match", _date, _date_fract);
885  } else {
886  DEBUG(net, 0, "sync check: %08x; %02x; mismatch expected {%08x, %08x}, got {%08x, %08x}",
887  _date, _date_fract, sync_state[0], sync_state[1], _random.state[0], _random.state[1]);
888  NOT_REACHED();
889  }
890  check_sync_state = false;
891  }
892  }
893 
894  if (cp != nullptr || check_sync_state) break;
895 
896  char buff[4096];
897  if (fgets(buff, lengthof(buff), f) == nullptr) break;
898 
899  char *p = buff;
900  /* Ignore the "[date time] " part of the message */
901  if (*p == '[') {
902  p = strchr(p, ']');
903  if (p == nullptr) break;
904  p += 2;
905  }
906 
907  if (strncmp(p, "cmd: ", 5) == 0
908 #ifdef DEBUG_FAILED_DUMP_COMMANDS
909  || strncmp(p, "cmdf: ", 6) == 0
910 #endif
911  ) {
912  p += 5;
913  if (*p == ' ') p++;
914  cp = CallocT<CommandPacket>(1);
915  int company;
916  static_assert(sizeof(cp->text) == 128);
917  int ret = sscanf(p, "%x; %x; %x; %x; %x; %x; %x; \"%127[^\"]\"", &next_date, &next_date_fract, &company, &cp->tile, &cp->p1, &cp->p2, &cp->cmd, cp->text);
918  /* There are 8 pieces of data to read, however the last is a
919  * string that might or might not exist. Ignore it if that
920  * string misses because in 99% of the time it's not used. */
921  assert(ret == 8 || ret == 7);
922  cp->company = (CompanyID)company;
923  } else if (strncmp(p, "join: ", 6) == 0) {
924  /* Manually insert a pause when joining; this way the client can join at the exact right time. */
925  int ret = sscanf(p + 6, "%x; %x", &next_date, &next_date_fract);
926  assert(ret == 2);
927  DEBUG(net, 0, "injecting pause for join at %08x:%02x; please join when paused", next_date, next_date_fract);
928  cp = CallocT<CommandPacket>(1);
930  cp->cmd = CMD_PAUSE;
931  cp->p1 = PM_PAUSED_NORMAL;
932  cp->p2 = 1;
933  _ddc_fastforward = false;
934  } else if (strncmp(p, "sync: ", 6) == 0) {
935  int ret = sscanf(p + 6, "%x; %x; %x; %x", &next_date, &next_date_fract, &sync_state[0], &sync_state[1]);
936  assert(ret == 4);
937  check_sync_state = true;
938  } else if (strncmp(p, "msg: ", 5) == 0 || strncmp(p, "client: ", 8) == 0 ||
939  strncmp(p, "load: ", 6) == 0 || strncmp(p, "save: ", 6) == 0) {
940  /* A message that is not very important to the log playback, but part of the log. */
941 #ifndef DEBUG_FAILED_DUMP_COMMANDS
942  } else if (strncmp(p, "cmdf: ", 6) == 0) {
943  DEBUG(net, 0, "Skipping replay of failed command: %s", p + 6);
944 #endif
945  } else {
946  /* Can't parse a line; what's wrong here? */
947  DEBUG(net, 0, "trying to parse: %s", p);
948  NOT_REACHED();
949  }
950  }
951  if (f != nullptr && feof(f)) {
952  DEBUG(net, 0, "End of commands.log");
953  fclose(f);
954  f = nullptr;
955  }
956 #endif /* DEBUG_DUMP_COMMANDS */
958  /* Only check for active clients just before we're going to send out
959  * the commands so we don't send multiple pause/unpause commands when
960  * the frame_freq is more than 1 tick. Same with distributing commands. */
964  }
965 
966  bool send_frame = false;
967 
968  /* We first increase the _frame_counter */
969  _frame_counter++;
970  /* Update max-frame-counter */
973  send_frame = true;
974  }
975 
977 
978  /* Then we make the frame */
979  StateGameLoop();
980 
982 #ifdef NETWORK_SEND_DOUBLE_SEED
983  _sync_seed_2 = _random.state[1];
984 #endif
985 
986  NetworkServer_Tick(send_frame);
987  } else {
988  /* Client */
989 
990  /* Make sure we are at the frame were the server is (quick-frames) */
992  /* Run a number of frames; when things go bad, get out. */
995  }
996  } else {
997  /* Else, keep on going till _frame_counter_max */
999  /* Run one frame; if things went bad, get out. */
1001  }
1002  }
1003  }
1004 
1005  NetworkSend();
1006 }
1007 
1008 static void NetworkGenerateServerId()
1009 {
1010  Md5 checksum;
1011  uint8 digest[16];
1012  char hex_output[16 * 2 + 1];
1013  char coding_string[NETWORK_NAME_LENGTH];
1014  int di;
1015 
1016  seprintf(coding_string, lastof(coding_string), "%d%s", (uint)Random(), "OpenTTD Server ID");
1017 
1018  /* Generate the MD5 hash */
1019  checksum.Append((const uint8*)coding_string, strlen(coding_string));
1020  checksum.Finish(digest);
1021 
1022  for (di = 0; di < 16; ++di) {
1023  seprintf(hex_output + di * 2, lastof(hex_output), "%02x", digest[di]);
1024  }
1025 
1026  /* _settings_client.network.network_id is our id */
1028 }
1029 
1030 void NetworkStartDebugLog(NetworkAddress address)
1031 {
1032  extern SOCKET _debug_socket; // Comes from debug.c
1033 
1034  DEBUG(net, 0, "Redirecting DEBUG() to %s:%d", address.GetHostname(), address.GetPort());
1035 
1036  SOCKET s = address.Connect();
1037  if (s == INVALID_SOCKET) {
1038  DEBUG(net, 0, "Failed to open socket for redirection DEBUG()");
1039  return;
1040  }
1041 
1042  _debug_socket = s;
1043 
1044  DEBUG(net, 0, "DEBUG() is now redirected");
1045 }
1046 
1049 {
1050  DEBUG(net, 3, "[core] starting network...");
1051 
1052  /* Network is available */
1054  _network_dedicated = false;
1055  _network_need_advertise = true;
1056 
1057  /* Generate an server id when there is none yet */
1058  if (StrEmpty(_settings_client.network.network_id)) NetworkGenerateServerId();
1059 
1060  memset(&_network_game_info, 0, sizeof(_network_game_info));
1061 
1062  NetworkInitialize();
1063  DEBUG(net, 3, "[core] network online, multiplayer available");
1065 }
1066 
1069 {
1070  NetworkDisconnect(true);
1071  NetworkUDPClose();
1072 
1073  DEBUG(net, 3, "[core] shutting down network");
1074 
1075  _network_available = false;
1076 
1078 }
1079 
1084 static const uint GITHASH_SUFFIX_LEN = 12;
1085 
1091 {
1092  /* This will be allocated on heap and never free'd, but only once so not a "real" leak. */
1093  static char *network_revision = nullptr;
1094 
1095  if (!network_revision) {
1096  /* Start by taking a chance on the full revision string. */
1097  network_revision = stredup(_openttd_revision);
1098  /* Ensure it's not longer than the packet buffer length. */
1099  if (strlen(network_revision) >= NETWORK_REVISION_LENGTH) network_revision[NETWORK_REVISION_LENGTH - 1] = '\0';
1100 
1101  /* Tag names are not mangled further. */
1102  if (_openttd_revision_tagged) {
1103  DEBUG(net, 1, "Network revision name is '%s'", network_revision);
1104  return network_revision;
1105  }
1106 
1107  /* Prepare a prefix of the git hash.
1108  * Size is length + 1 for terminator, +2 for -g prefix. */
1109  assert(_openttd_revision_modified < 3);
1110  char githash_suffix[GITHASH_SUFFIX_LEN + 1] = "-";
1111  githash_suffix[1] = "gum"[_openttd_revision_modified];
1112  for (uint i = 2; i < GITHASH_SUFFIX_LEN; i++) {
1113  githash_suffix[i] = _openttd_revision_hash[i-2];
1114  }
1115 
1116  /* Where did the hash start in the original string?
1117  * Overwrite from that position, unless that would go past end of packet buffer length. */
1118  ptrdiff_t hashofs = strrchr(_openttd_revision, '-') - _openttd_revision;
1119  if (hashofs + strlen(githash_suffix) + 1 > NETWORK_REVISION_LENGTH) hashofs = strlen(network_revision) - strlen(githash_suffix);
1120  /* Replace the git hash in revision string. */
1121  strecpy(network_revision + hashofs, githash_suffix, network_revision + NETWORK_REVISION_LENGTH);
1122  assert(strlen(network_revision) < NETWORK_REVISION_LENGTH); // strlen does not include terminator, constant does, hence strictly less than
1123  DEBUG(net, 1, "Network revision name is '%s'", network_revision);
1124  }
1125 
1126  return network_revision;
1127 }
1128 
1129 static const char *ExtractNetworkRevisionHash(const char *revstr)
1130 {
1131  return strrchr(revstr, '-');
1132 }
1133 
1139 bool IsNetworkCompatibleVersion(const char *other)
1140 {
1141  if (strncmp(GetNetworkRevisionString(), other, NETWORK_REVISION_LENGTH - 1) == 0) return true;
1142 
1143  /* If this version is tagged, then the revision string must be a complete match,
1144  * since there is no git hash suffix in it.
1145  * This is needed to avoid situations like "1.9.0-beta1" comparing equal to "2.0.0-beta1". */
1146  if (_openttd_revision_tagged) return false;
1147 
1148  const char *hash1 = ExtractNetworkRevisionHash(GetNetworkRevisionString());
1149  const char *hash2 = ExtractNetworkRevisionHash(other);
1150  return hash1 && hash2 && (strncmp(hash1, hash2, GITHASH_SUFFIX_LEN) == 0);
1151 }
1152 
1153 #ifdef __EMSCRIPTEN__
1154 extern "C" {
1155 
1156 void CDECL em_openttd_add_server(const char *host, int port)
1157 {
1158  NetworkUDPQueryServer(NetworkAddress(host, port), true);
1159 }
1160 
1161 }
1162 #endif
network_content.h
TCPConnecter::CheckCallbacks
static void CheckCallbacks()
Check whether we need to call the callback, i.e.
Definition: tcp_connect.cpp:65
TCPConnecter::TCPConnecter
TCPConnecter(const NetworkAddress &address)
Create a new connecter for the given address.
Definition: tcp_connect.cpp:26
host.h
NetworkAddress::Connect
SOCKET Connect()
Connect to the given address.
Definition: address.cpp:351
CommandContainer::cmd
uint32 cmd
command being executed.
Definition: command_type.h:483
NetworkSettings::client_name
char client_name[NETWORK_CLIENT_NAME_LENGTH]
name of the player (as client)
Definition: settings_type.h:270
InvalidateWindowData
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition: window.cpp:3321
_frame_counter
uint32 _frame_counter
The current frame.
Definition: network.cpp:68
NETWORK_DEFAULT_PORT
static const uint16 NETWORK_DEFAULT_PORT
The default port of the game server (TCP & UDP)
Definition: config.h:29
NetworkClientSetCompanyPassword
void NetworkClientSetCompanyPassword(const char *password)
Set/Reset company password on the client side.
Definition: network_client.cpp:1293
SAVE_DIR
@ SAVE_DIR
Base directory for all savegames.
Definition: fileio_type.h:110
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3220
ClientNetworkContentSocketHandler::SendReceive
void SendReceive()
Check whether we received/can send some data from/to the content server and when that's the case hand...
Definition: network_content.cpp:779
NetworkServerSetCompanyPassword
void NetworkServerSetCompanyPassword(CompanyID company_id, const char *password, bool already_hashed)
Set/Reset a company password on the server end.
Definition: network_server.cpp:1782
_network_game_info
NetworkServerGameInfo _network_game_info
Information about our game.
Definition: network.cpp:57
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
NetworkSettings::frame_freq
uint8 frame_freq
how often do we send commands to the clients
Definition: settings_type.h:251
NetworkSettings::server_port
uint16 server_port
port the server listens on
Definition: settings_type.h:262
TCPConnecter
"Helper" class for creating TCP connections in a non-blocking manner
Definition: tcp.h:64
NETWORK_NAME_LENGTH
static const uint NETWORK_NAME_LENGTH
The maximum length of the server name and map name, in bytes including '\0'.
Definition: config.h:40
NetworkClientInfo::client_playas
CompanyID client_playas
As which company is this client playing (CompanyID)
Definition: network_base.h:27
TD_LTR
@ TD_LTR
Text is written left-to-right by default.
Definition: strings_type.h:23
NetworkSettings::connect_to_ip
char connect_to_ip[NETWORK_HOSTNAME_LENGTH]
default for the "Add server" query
Definition: settings_type.h:272
_network_join_as
CompanyID _network_join_as
Who would we like to join as.
Definition: network_client.cpp:326
_date_fract
DateFract _date_fract
Fractional part of the day.
Definition: date.cpp:29
NetworkCompanyState
Some state information of a company, especially for servers.
Definition: network_type.h:64
_network_server
bool _network_server
network-server is active
Definition: network.cpp:53
_network_company_passworded
CompanyMask _network_company_passworded
Bitmask of the password status of all companies.
Definition: network.cpp:77
GetCommandName
const char * GetCommandName(uint32 cmd)
Definition: command.cpp:407
NetworkAction
NetworkAction
Actions that can be used for NetworkTextMessage.
Definition: network_type.h:91
NetworkClientInfo::client_name
char client_name[NETWORK_CLIENT_NAME_LENGTH]
Name of the client.
Definition: network_base.h:25
NETWORK_NUM_LANDSCAPES
static const uint NETWORK_NUM_LANDSCAPES
The number of landscapes in OpenTTD.
Definition: config.h:70
GetNetworkRevisionString
const char * GetNetworkRevisionString()
Get the network version string used by this build.
Definition: network.cpp:1090
WC_CLIENT_LIST
@ WC_CLIENT_LIST
Client list; Window numbers:
Definition: window_type.h:472
ServerNetworkAdminSocketHandler::WelcomeAll
static void WelcomeAll()
Send a Welcome packet to all connected admins.
Definition: network_admin.cpp:989
NetworkSettings::network_id
char network_id[NETWORK_SERVER_ID_LENGTH]
network ID for servers
Definition: settings_type.h:273
ClientNetworkGameSocketHandler::GameLoop
static bool GameLoop()
Actual game loop for the client.
Definition: network_client.cpp:266
TCPQueryConnecter::OnFailure
void OnFailure() override
Callback for when the connection attempt failed.
Definition: network.cpp:562
HasBit
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103
NetworkHasJoiningClient
static bool NetworkHasJoiningClient()
Checks whether there is a joining client.
Definition: network.cpp:428
Utf8Encode
size_t Utf8Encode(T buf, WChar c)
Encode a unicode character and place it in the buffer.
Definition: string.cpp:523
_networkclientinfo_pool
NetworkClientInfoPool _networkclientinfo_pool("NetworkClientInfo")
Make sure both pools have the same size.
NetworkSettings::pause_on_join
bool pause_on_join
pause the game when people join
Definition: settings_type.h:261
NetworkServerGameInfo
The game information that is not generated on-the-fly and has to be sent to the clients.
Definition: game.h:24
TextColour
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
Definition: gfx_type.h:250
CommandContainer::p2
uint32 p2
parameter p2.
Definition: command_type.h:482
NetworkHandlePauseChange
void NetworkHandlePauseChange(PauseMode prev_mode, PauseMode changed_mode)
Handle the pause mode change so we send the right messages to the chat.
Definition: network.cpp:330
ServerNetworkAdminSocketHandler::IterateActive
static Pool::IterateWrapperFiltered< ServerNetworkAdminSocketHandler, ServerNetworkAdminSocketHandlerFilter > IterateActive(size_t from=0)
Returns an iterable ensemble of all active admin sockets.
Definition: network_admin.h:95
_random
Randomizer _random
Random used in the game state calculations.
Definition: random_func.cpp:25
CommandContainer::text
char text[32 *MAX_CHAR_LENGTH]
possible text sent for name changes etc, in bytes including '\0'.
Definition: command_type.h:485
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:79
_network_bind_list
StringList _network_bind_list
The addresses to bind on.
Definition: network.cpp:63
NetworkUDPAdvertise
void NetworkUDPAdvertise()
Register us to the master server This function checks if it needs to send an advertise.
Definition: network_udp.cpp:605
NetworkBackgroundLoop
void NetworkBackgroundLoop()
We have to do some (simple) background stuff that runs normally, even when we are not in multiplayer.
Definition: network.cpp:833
network_gui.h
_network_join_status
NetworkJoinStatus _network_join_status
The status of joining.
Definition: network_gui.cpp:1977
GetNetworkErrorMsg
StringID GetNetworkErrorMsg(NetworkErrorCode err)
Retrieve the string id of an internal error number.
Definition: network.cpp:292
ClientNetworkGameSocketHandler::my_client
static ClientNetworkGameSocketHandler * my_client
This is us!
Definition: network_client.h:41
_network_join_company_password
const char * _network_join_company_password
Company password from -P argument.
Definition: network_client.cpp:331
NetworkSettings::admin_password
char admin_password[NETWORK_PASSWORD_LENGTH]
password for the admin network
Definition: settings_type.h:268
_redirect_console_to_client
ClientID _redirect_console_to_client
If not invalid, redirect the console output to a client.
Definition: network.cpp:60
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
ClientNetworkGameSocketHandler::CloseConnection
NetworkRecvStatus CloseConnection(NetworkRecvStatus status) override
Close the network connection due to the given status.
Definition: network_client.cpp:159
GenerateCompanyPasswordHash
const char * GenerateCompanyPasswordHash(const char *password, const char *password_server_id, uint32 password_game_seed)
Hash the given password using server ID and game seed.
Definition: network.cpp:175
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
CC_DEFAULT
static const TextColour CC_DEFAULT
Default colour of the console.
Definition: console_type.h:23
_frame_counter_max
uint32 _frame_counter_max
To where we may go with our clients.
Definition: network.cpp:67
_network_first_time
bool _network_first_time
Whether we have finished joining or not.
Definition: network.cpp:76
NetworkServer_Tick
void NetworkServer_Tick(bool send_frame)
This is called every tick if this is a _network_server.
Definition: network_server.cpp:1811
ServerNetworkAdminSocketHandler::Send
static void Send()
Send the packets for the server sockets.
Definition: network_admin.cpp:95
network_base.h
ShowErrorMessage
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=nullptr, uint textref_stack_size=0, const uint32 *textref_stack=nullptr)
Display an error message in a window.
Definition: error_gui.cpp:372
MAX_CHAR_LENGTH
static const int MAX_CHAR_LENGTH
Max. length of UTF-8 encoded unicode character.
Definition: strings_type.h:18
_network_game_list
NetworkGameList * _network_game_list
Game list of this client.
Definition: network_gamelist.cpp:23
MAX_LENGTH_COMPANY_NAME_CHARS
static const uint MAX_LENGTH_COMPANY_NAME_CHARS
The maximum length of a company name in characters including '\0'.
Definition: company_type.h:40
NetworkClientInfo::~NetworkClientInfo
~NetworkClientInfo()
Basically a client is leaving us right now.
Definition: network.cpp:101
PM_UNPAUSED
@ PM_UNPAUSED
A normal unpaused game.
Definition: openttd.h:59
HasClients
bool HasClients()
Return whether there is any client connected or trying to connect at all.
Definition: network.cpp:93
NetworkUDPQueryServer
void NetworkUDPQueryServer(NetworkAddress address, bool manually)
Query a specific server.
Definition: network_udp.cpp:111
Pool::MAX_SIZE
static constexpr size_t MAX_SIZE
Make template parameter accessible from outside.
Definition: pool_type.hpp:85
COMPANY_FIRST
@ COMPANY_FIRST
First company, same as owner.
Definition: company_type.h:22
NetworkClientInfo::GetByClientID
static NetworkClientInfo * GetByClientID(ClientID client_id)
Return the CI given it's client-identifier.
Definition: network.cpp:112
TCPQueryConnecter::OnConnect
void OnConnect(SOCKET s) override
Callback when the connection succeeded.
Definition: network.cpp:567
_frame_counter_server
uint32 _frame_counter_server
The frame_counter of the server, if in network-mode.
Definition: network.cpp:66
CommandPacket::company
CompanyID company
company that is executing the command
Definition: network_internal.h:148
CommandContainer::p1
uint32 p1
parameter p1.
Definition: command_type.h:481
ServerNetworkGameSocketHandler::Send
static void Send()
Send the packets for the server sockets.
Definition: network_server.cpp:330
_network_join_server_password
const char * _network_join_server_password
Login password from -p argument.
Definition: network_client.cpp:329
NETWORK_RECV_STATUS_CONN_LOST
@ NETWORK_RECV_STATUS_CONN_LOST
The connection is 'just' lost.
Definition: core.h:27
DRAW_STRING_BUFFER
static const int DRAW_STRING_BUFFER
Size of the buffer used for drawing strings.
Definition: gfx_func.h:85
CommandPacket
Everything we need to know about a command to be able to execute it.
Definition: network_internal.h:144
_date
Date _date
Current date in days (day counter)
Definition: date.cpp:28
DoCommandP
bool DoCommandP(const CommandContainer *container, bool my_cmd)
Shortcut for the long DoCommandP when having a container with the data.
Definition: command.cpp:541
NetworkSettings::last_host
char last_host[NETWORK_HOSTNAME_LENGTH]
IP address of the last joined server.
Definition: settings_type.h:285
NetworkAddressList
std::vector< NetworkAddress > NetworkAddressList
Type for a list of addresses.
Definition: address.h:20
CMD_PAUSE
@ CMD_PAUSE
pause the game
Definition: command_type.h:256
DEBUG
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:35
TCPListenHandler< ServerNetworkAdminSocketHandler, ADMIN_PACKET_SERVER_FULL, ADMIN_PACKET_SERVER_BANNED >::Receive
static bool Receive()
Handle the receiving of packets.
Definition: tcp_listen.h:99
FioFOpenFile
FILE * FioFOpenFile(const std::string &filename, const char *mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
Definition: fileio.cpp:406
NetworkAddress::GetHostname
const char * GetHostname()
Get the hostname; in case it wasn't given the IPv4 dotted representation is given.
Definition: address.cpp:22
ClientID
ClientID
'Unique' identifier to be given to clients
Definition: network_type.h:39
Date
int32 Date
The type to store our dates in.
Definition: date_type.h:14
NetworkSettings::min_active_clients
uint8 min_active_clients
minimum amount of active clients to unpause the game
Definition: settings_type.h:282
ParseConnectionString
void ParseConnectionString(const char **company, const char **port, char *connection_string)
Converts a string to ip/port/company Format: IP:port::company.
Definition: network.cpp:457
_pause_mode
PauseMode _pause_mode
The current pause mode.
Definition: gfx.cpp:47
NetworkClient_Connected
void NetworkClient_Connected()
Is called after a client is connected to the server.
Definition: network_client.cpp:1203
IsNetworkCompatibleVersion
bool IsNetworkCompatibleVersion(const char *other)
Checks whether the given version string is compatible with our version.
Definition: network.cpp:1139
TCPClientConnecter::OnFailure
void OnFailure() override
Callback for when the connection attempt failed.
Definition: network.cpp:645
_sync_seed_1
uint32 _sync_seed_1
Seed to compare during sync checks.
Definition: network.cpp:71
NetworkAddress::GetPort
uint16 GetPort() const
Get the port.
Definition: address.cpp:35
MAX_COMPANIES
@ MAX_COMPANIES
Maximum number of companies.
Definition: company_type.h:23
StringList
std::vector< std::string > StringList
Type for a list of strings.
Definition: string_type.h:58
TCPClientConnecter
Non blocking connection create to actually connect to servers.
Definition: network.cpp:641
NetworkDisconnect
void NetworkDisconnect(bool blocking, bool close_admins)
We want to disconnect from the host/clients.
Definition: network.cpp:777
CHAR_TD_RLM
static const WChar CHAR_TD_RLM
The next character acts like a right-to-left character.
Definition: string_type.h:40
InitializeNetworkPools
static void InitializeNetworkPools(bool close_admins=true)
Resets the pools used for network clients, and the admin pool if needed.
Definition: network.cpp:504
PoolBase::Clean
static void Clean(PoolType)
Clean all pools of given type.
Definition: pool_func.cpp:30
NetworkShutDown
void NetworkShutDown()
This shuts the network down.
Definition: network.cpp:1068
CLIENT_ID_SERVER
@ CLIENT_ID_SERVER
Servers always have this ID.
Definition: network_type.h:41
PT_NADMIN
@ PT_NADMIN
Network admin pool.
Definition: pool_type.hpp:21
_network_company_states
NetworkCompanyState * _network_company_states
Statistics about some companies.
Definition: network.cpp:58
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
NETWORK_SERVER_ID_LENGTH
static const uint NETWORK_SERVER_ID_LENGTH
The maximum length of the network id of the servers, in bytes including '\0'.
Definition: config.h:43
_networking
bool _networking
are we in networking mode?
Definition: network.cpp:52
NetworkSettings::last_port
uint16 last_port
port of the last joined server
Definition: settings_type.h:286
CheckPauseHelper
static void CheckPauseHelper(bool pause, PauseMode pm)
Helper function for the pause checkers.
Definition: network.cpp:386
PT_NONE
@ PT_NONE
No pool is selected.
Definition: pool_type.hpp:18
ServerNetworkGameSocketHandler::GetByClientID
static ServerNetworkGameSocketHandler * GetByClientID(ClientID client_id)
Return the client state given it's client-identifier.
Definition: network.cpp:126
network_client.h
CMD_FLAGS_MASK
@ CMD_FLAGS_MASK
mask for all command flags
Definition: command_type.h:381
NetworkSettings::server_name
char server_name[NETWORK_NAME_LENGTH]
name of the server
Definition: settings_type.h:265
PauseMode
PauseMode
Modes of pausing we've got.
Definition: openttd.h:58
_network_reconnect
uint8 _network_reconnect
Reconnect timeout.
Definition: network.cpp:62
network_server.h
_network_dedicated
bool _network_dedicated
are we a dedicated server?
Definition: network.cpp:55
TCPConnecter::KillAll
static void KillAll()
Kill all connection attempts.
Definition: tcp_connect.cpp:94
TCPConnecter::address
NetworkAddress address
Address we're connecting to.
Definition: tcp.h:77
PM_PAUSED_GAME_SCRIPT
@ PM_PAUSED_GAME_SCRIPT
A game paused by a game script.
Definition: openttd.h:65
Randomizer::state
uint32 state[2]
The state of the randomizer.
Definition: random_func.hpp:23
NETWORK_REVISION_LENGTH
static const uint NETWORK_REVISION_LENGTH
The maximum length of the revision, in bytes including '\0'.
Definition: config.h:44
ServerNetworkGameSocketHandler::AcceptConnection
static void AcceptConnection(SOCKET s, const NetworkAddress &address)
Handle the accepting of a connection to the server.
Definition: network.cpp:490
PT_NCLIENT
@ PT_NCLIENT
Network client pools.
Definition: pool_type.hpp:20
NetworkCompanyIsPassworded
bool NetworkCompanyIsPassworded(CompanyID company_id)
Check if the company we want to join requires a password.
Definition: network.cpp:206
NetworkClientInfo::client_id
ClientID client_id
Client identifier (same as ClientState->client_id)
Definition: network_base.h:24
StateGameLoop
void StateGameLoop()
State controlling game loop.
Definition: openttd.cpp:1344
_network_own_client_id
ClientID _network_own_client_id
Our client identifier.
Definition: network.cpp:59
ClientNetworkGameSocketHandler::SendCompanyInformationQuery
static NetworkRecvStatus SendCompanyInformationQuery()
Make sure the server ID length is the same as a md5 hash.
Definition: network_client.cpp:342
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
NetworkCoreShutdown
void NetworkCoreShutdown()
Shuts down the network core (as that is needed for some platforms.
Definition: core.cpp:44
ClientNetworkGameSocketHandler::Receive
static bool Receive()
Check whether we received/can send some data from/to the server and when that's the case handle it ap...
Definition: network_client.cpp:241
_network_content_client
ClientNetworkContentSocketHandler _network_content_client
The client we use to connect to the server.
Definition: network_content.cpp:35
ServerNetworkGameSocketHandler
Class for handling the server side of the game connection.
Definition: network_server.h:24
PM_PAUSED_ACTIVE_CLIENTS
@ PM_PAUSED_ACTIVE_CLIENTS
A game paused for 'min_active_clients'.
Definition: openttd.h:64
_switch_mode
SwitchMode _switch_mode
The next mainloop command.
Definition: gfx.cpp:46
StringID
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
_ddc_fastforward
#define _ddc_fastforward
Helper variable to make the dedicated server go fast until the (first) join.
Definition: network_internal.h:47
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
NetworkAddress
Wrapper for (un)resolved network addresses; there's no reason to transform a numeric IP to a string a...
Definition: address.h:29
Pool::PoolItem<&_networkclientinfo_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:378
Pool
Base class for all pools.
Definition: pool_type.hpp:81
DeleteWindowById
void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
Delete a window by its class and window number (if it is open).
Definition: window.cpp:1165
network_udp.h
NetworkSendCommand
void NetworkSendCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback, const char *text, CompanyID company)
Prepare a DoCommand to be send over the network.
Definition: network_command.cpp:136
COMPANY_SPECTATOR
@ COMPANY_SPECTATOR
The client is spectating.
Definition: company_type.h:35
ServerNetworkAdminSocketHandler
Class for handling the server side of the game connection.
Definition: network_admin.h:25
CheckPauseOnJoin
static void CheckPauseOnJoin()
Check whether we should pause on join.
Definition: network.cpp:440
_network_clients_connected
byte _network_clients_connected
The amount of clients connected.
Definition: network.cpp:84
WC_NETWORK_STATUS_WINDOW
@ WC_NETWORK_STATUS_WINDOW
Network status window; Window numbers:
Definition: window_type.h:485
NetworkUDPInitialize
void NetworkUDPInitialize()
Initialize the whole UDP bit.
Definition: network_udp.cpp:637
PM_PAUSED_NORMAL
@ PM_PAUSED_NORMAL
A game normally paused.
Definition: openttd.h:60
NetworkHTTPSocketHandler::HTTPReceive
static void HTTPReceive()
Do the receiving for all HTTP connections.
Definition: tcp_http.cpp:295
Pool::PoolItem<&_networkclientinfo_pool >::CanAllocateItem
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
Definition: pool_type.hpp:299
NetworkCountActiveClients
static uint NetworkCountActiveClients()
Counts the number of active clients connected.
Definition: network.cpp:398
seprintf
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:442
udp.h
_network_need_advertise
bool _network_need_advertise
Whether we need to advertise.
Definition: network.cpp:61
SM_MENU
@ SM_MENU
Switch to game intro menu.
Definition: openttd.h:31
ClientNetworkGameSocketHandler
Class for handling the client side of the game connection.
Definition: network_client.h:16
PM_PAUSED_LINK_GRAPH
@ PM_PAUSED_LINK_GRAPH
A game paused due to the link graph schedule lagging.
Definition: openttd.h:66
NetworkFindBroadcastIPs
void NetworkFindBroadcastIPs(NetworkAddressList *broadcast)
Find the IPv4 broadcast addresses; IPv6 uses a completely different strategy for broadcasting.
Definition: host.cpp:194
INSTANTIATE_POOL_METHODS
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
Definition: pool_func.hpp:224
stredup
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
Definition: string.cpp:137
PM_PAUSED_JOIN
@ PM_PAUSED_JOIN
A game paused for 'pause_on_join'.
Definition: openttd.h:62
_sync_frame
uint32 _sync_frame
The frame to perform the sync check.
Definition: network.cpp:75
NetworkGameList
Structure with information shown in the game list (GUI)
Definition: network_gamelist.h:17
CheckMinActiveClients
static void CheckMinActiveClients()
Check if the minimum number of active clients has been reached and pause or unpause the game as appro...
Definition: network.cpp:414
NetworkChangeCompanyPassword
const char * NetworkChangeCompanyPassword(CompanyID company_id, const char *password)
Change the company password of a given company.
Definition: network.cpp:155
NetworkGameSocketHandler::client_id
ClientID client_id
Client identifier.
Definition: tcp_game.h:518
WC_SEND_NETWORK_MSG
@ WC_SEND_NETWORK_MSG
Chatbox; Window numbers:
Definition: window_type.h:491
CHAR_TD_LRM
static const WChar CHAR_TD_LRM
The next character acts like a left-to-right character.
Definition: string_type.h:39
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:363
_network_ban_list
StringList _network_ban_list
The banned clients.
Definition: network.cpp:65
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
NetworkClose
void NetworkClose(bool close_admins)
Close current connections.
Definition: network.cpp:513
ServerNetworkGameSocketHandler::ServerNetworkGameSocketHandler
ServerNetworkGameSocketHandler(SOCKET s)
Create a new socket for the server side of the game connection.
Definition: network_server.cpp:217
ServerNetworkGameSocketHandler::client_address
NetworkAddress client_address
IP-address of the client (so he can be banned)
Definition: network_server.h:73
NETWORK_HOSTNAME_LENGTH
static const uint NETWORK_HOSTNAME_LENGTH
The maximum length of the host name, in bytes including '\0'.
Definition: config.h:42
NetworkCoreInitialize
bool NetworkCoreInitialize()
Initializes the network core (as that is needed for some platforms.
Definition: core.cpp:24
IConsoleCmdExec
void IConsoleCmdExec(const char *cmdstr, const uint recurse_count)
Execute a given command passed to us.
Definition: console.cpp:407
NetworkGameList::next
NetworkGameList * next
Next pointer to make a linked game list.
Definition: network_gamelist.h:23
network_gamelist.h
DESTTYPE_CLIENT
@ DESTTYPE_CLIENT
Send message/notice to only a certain client (Private)
Definition: network_type.h:84
NetworkExecuteLocalCommandQueue
void NetworkExecuteLocalCommandQueue()
Execute all commands on the local command queue that ought to be executed this frame.
Definition: network_command.cpp:191
ClientNetworkGameSocketHandler::SendQuit
static NetworkRecvStatus SendQuit()
Tell the server we would like to quit.
Definition: network_client.cpp:500
Pool::PoolItem<&_company_pool >::IsValidID
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition: pool_type.hpp:318
TCPListenHandler< ServerNetworkGameSocketHandler, PACKET_SERVER_FULL, PACKET_SERVER_BANNED >::CloseListeners
static void CloseListeners()
Close the sockets we're listening on.
Definition: tcp_listen.h:162
NetworkStartUp
void NetworkStartUp()
This tries to launch the network for a given OS.
Definition: network.cpp:1048
_network_host_list
StringList _network_host_list
The servers we know.
Definition: network.cpp:64
network_admin.h
CommandContainer::tile
TileIndex tile
tile command being executed on.
Definition: command_type.h:480
NetworkServerGameInfo::clients_on
byte clients_on
Current count of clients on server.
Definition: game.h:26
_network_available
bool _network_available
is network mode available?
Definition: network.cpp:54
strecpy
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: string.cpp:112
WN_NETWORK_STATUS_WINDOW_JOIN
@ WN_NETWORK_STATUS_WINDOW_JOIN
Network join status.
Definition: window_type.h:32
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:450
NetworkReceive
static bool NetworkReceive()
Receives something from the network.
Definition: network.cpp:807
PM_PAUSED_ERROR
@ PM_PAUSED_ERROR
A game paused because a (critical) error.
Definition: openttd.h:63
NetworkFreeLocalCommandQueue
void NetworkFreeLocalCommandQueue()
Free the local command queues.
Definition: network_command.cpp:225
GITHASH_SUFFIX_LEN
static const uint GITHASH_SUFFIX_LEN
How many hex digits of the git hash to include in network revision string.
Definition: network.cpp:1084
GUISettings::network_chat_timeout
uint16 network_chat_timeout
timeout of chat messages in seconds
Definition: settings_type.h:171
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
ClientNetworkGameSocketHandler::Send
static void Send()
Send the packets of this socket handler.
Definition: network_client.cpp:256
NetworkSettings::server_admin_port
uint16 server_admin_port
port the server listens on for the admin network
Definition: settings_type.h:263
TCPQueryConnecter
Non blocking connection create to query servers.
Definition: network.cpp:558
DAY_TICKS
static const int DAY_TICKS
1 day is 74 ticks; _date_fract used to be uint16 and incremented by 885.
Definition: date_type.h:28
_current_text_dir
TextDirection _current_text_dir
Text direction of the currently selected language.
Definition: strings.cpp:48
_last_sync_frame
uint32 _last_sync_frame
Used in the server to store the last time a sync packet was sent to clients.
Definition: network.cpp:69
_is_network_server
bool _is_network_server
Does this client wants to be a network-server?
Definition: network.cpp:56
NetworkErrorCode
NetworkErrorCode
The error codes we send around in the protocols.
Definition: network_type.h:110
NetworkClientInfo
Container for all information known about a client.
Definition: network_base.h:23
TCPListenHandler< ServerNetworkGameSocketHandler, PACKET_SERVER_FULL, PACKET_SERVER_BANNED >::Listen
static bool Listen(uint16 port)
Listen on a particular port.
Definition: tcp_listen.h:141
IConsolePrintF
void CDECL IConsolePrintF(TextColour colour_code, const char *format,...)
Handle the printing of text entered into the console or redirected there by any other means.
Definition: console.cpp:125
SetDParamStr
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Definition: strings.cpp:286
TCPClientConnecter::OnConnect
void OnConnect(SOCKET s) override
Callback when the connection succeeded.
Definition: network.cpp:650
INVALID_STRING_ID
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Definition: strings_type.h:17
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition: settings_type.h:581
WL_CRITICAL
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:25
NetworkAddChatMessage
void CDECL NetworkAddChatMessage(TextColour colour, uint duration, const char *message,...)
Add a text message to the 'chat window' to be shown.
Definition: network_chat_gui.cpp:80
NetworkDistributeCommands
void NetworkDistributeCommands()
Distribute the commands of ourself and the clients.
Definition: network_command.cpp:279
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