OpenTTD Source  14.0-beta1
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 "../timer/timer_game_tick.h"
15 #include "../timer/timer_game_economy.h"
16 #include "network_admin.h"
17 #include "network_client.h"
18 #include "network_query.h"
19 #include "network_server.h"
20 #include "network_content.h"
21 #include "network_udp.h"
22 #include "network_gamelist.h"
23 #include "network_base.h"
24 #include "network_coordinator.h"
25 #include "core/udp.h"
26 #include "core/host.h"
27 #include "network_gui.h"
28 #include "../console_func.h"
29 #include "../3rdparty/md5/md5.h"
30 #include "../core/random_func.hpp"
31 #include "../window_func.h"
32 #include "../company_func.h"
33 #include "../company_base.h"
34 #include "../landscape_type.h"
35 #include "../rev.h"
36 #include "../core/pool_func.hpp"
37 #include "../gfx_func.h"
38 #include "../error.h"
39 #include "../misc_cmd.h"
40 #include <charconv>
41 #include <sstream>
42 #include <iomanip>
43 
44 #include "../safeguards.h"
45 
46 #ifdef DEBUG_DUMP_COMMANDS
47 #include "../fileio_func.h"
49 bool _ddc_fastforward = true;
50 #endif /* DEBUG_DUMP_COMMANDS */
51 
54 
58 
73 uint32_t _frame_counter;
74 uint32_t _last_sync_frame;
76 uint32_t _sync_seed_1;
77 #ifdef NETWORK_SEND_DOUBLE_SEED
78 uint32_t _sync_seed_2;
79 #endif
80 uint32_t _sync_frame;
83 
85 
88 
89 extern std::string GenerateUid(std::string_view subject);
90 
95 bool HasClients()
96 {
97  return !NetworkClientSocket::Iterate().empty();
98 }
99 
104 {
105  /* Delete the chat window, if you were chatting with this client. */
107 }
108 
115 {
117  if (ci->client_id == client_id) return ci;
118  }
119 
120  return nullptr;
121 }
122 
129 {
130  for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
131  if (cs->client_id == client_id) return cs;
132  }
133 
134  return nullptr;
135 }
136 
137 byte NetworkSpectatorCount()
138 {
139  byte count = 0;
140 
141  for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
142  if (ci->client_playas == COMPANY_SPECTATOR) count++;
143  }
144 
145  /* Don't count a dedicated server as spectator */
146  if (_network_dedicated) count--;
147 
148  return count;
149 }
150 
157 std::string NetworkChangeCompanyPassword(CompanyID company_id, std::string password)
158 {
159  if (password.compare("*") == 0) password = "";
160 
161  if (_network_server) {
162  NetworkServerSetCompanyPassword(company_id, password, false);
163  } else {
165  }
166 
167  return password;
168 }
169 
177 std::string GenerateCompanyPasswordHash(const std::string &password, const std::string &password_server_id, uint32_t password_game_seed)
178 {
179  if (password.empty()) return password;
180 
181  size_t password_length = password.size();
182  size_t password_server_id_length = password_server_id.size();
183 
184  std::ostringstream salted_password;
185  /* Add the password with the server's ID and game seed as the salt. */
186  for (uint i = 0; i < NETWORK_SERVER_ID_LENGTH - 1; i++) {
187  char password_char = (i < password_length ? password[i] : 0);
188  char server_id_char = (i < password_server_id_length ? password_server_id[i] : 0);
189  char seed_char = password_game_seed >> (i % 32);
190  salted_password << (char)(password_char ^ server_id_char ^ seed_char); // Cast needed, otherwise interpreted as integer to format
191  }
192 
193  Md5 checksum;
194  MD5Hash digest;
195 
196  /* Generate the MD5 hash */
197  std::string salted_password_string = salted_password.str();
198  checksum.Append(salted_password_string.data(), salted_password_string.size());
199  checksum.Finish(digest);
200 
201  return FormatArrayAsHex(digest);
202 }
203 
210 {
211  return HasBit(_network_company_passworded, company_id);
212 }
213 
214 /* This puts a text-message to the console, or in the future, the chat-box,
215  * (to keep it all a bit more general)
216  * If 'self_send' is true, this is the client who is sending the message */
217 void NetworkTextMessage(NetworkAction action, TextColour colour, bool self_send, const std::string &name, const std::string &str, int64_t data, const std::string &data_str)
218 {
219  StringID strid;
220  switch (action) {
221  case NETWORK_ACTION_SERVER_MESSAGE:
222  /* Ignore invalid messages */
223  strid = STR_NETWORK_SERVER_MESSAGE;
224  colour = CC_DEFAULT;
225  break;
226  case NETWORK_ACTION_COMPANY_SPECTATOR:
227  colour = CC_DEFAULT;
228  strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_SPECTATE;
229  break;
230  case NETWORK_ACTION_COMPANY_JOIN:
231  colour = CC_DEFAULT;
232  strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_JOIN;
233  break;
234  case NETWORK_ACTION_COMPANY_NEW:
235  colour = CC_DEFAULT;
236  strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_NEW;
237  break;
238  case NETWORK_ACTION_JOIN:
239  /* Show the Client ID for the server but not for the client. */
240  strid = _network_server ? STR_NETWORK_MESSAGE_CLIENT_JOINED_ID : STR_NETWORK_MESSAGE_CLIENT_JOINED;
241  break;
242  case NETWORK_ACTION_LEAVE: strid = STR_NETWORK_MESSAGE_CLIENT_LEFT; break;
243  case NETWORK_ACTION_NAME_CHANGE: strid = STR_NETWORK_MESSAGE_NAME_CHANGE; break;
244  case NETWORK_ACTION_GIVE_MONEY: strid = STR_NETWORK_MESSAGE_GIVE_MONEY; break;
245  case NETWORK_ACTION_CHAT_COMPANY: strid = self_send ? STR_NETWORK_CHAT_TO_COMPANY : STR_NETWORK_CHAT_COMPANY; break;
246  case NETWORK_ACTION_CHAT_CLIENT: strid = self_send ? STR_NETWORK_CHAT_TO_CLIENT : STR_NETWORK_CHAT_CLIENT; break;
247  case NETWORK_ACTION_KICKED: strid = STR_NETWORK_MESSAGE_KICKED; break;
248  case NETWORK_ACTION_EXTERNAL_CHAT: strid = STR_NETWORK_CHAT_EXTERNAL; break;
249  default: strid = STR_NETWORK_CHAT_ALL; break;
250  }
251 
252  SetDParamStr(0, name);
253  SetDParamStr(1, str);
254  SetDParam(2, data);
255  SetDParamStr(3, data_str);
256 
257  /* All of these strings start with "***". These characters are interpreted as both left-to-right and
258  * right-to-left characters depending on the context. As the next text might be an user's name, the
259  * user name's characters will influence the direction of the "***" instead of the language setting
260  * of the game. Manually set the direction of the "***" by inserting a text-direction marker. */
261  std::ostringstream stream;
262  std::ostreambuf_iterator<char> iterator(stream);
264  std::string message = stream.str() + GetString(strid);
265 
266  Debug(desync, 1, "msg: {:08x}; {:02x}; {}", TimerGameEconomy::date, TimerGameEconomy::date_fract, message);
267  IConsolePrint(colour, message);
269 }
270 
271 /* Calculate the frame-lag of a client */
272 uint NetworkCalculateLag(const NetworkClientSocket *cs)
273 {
274  int lag = cs->last_frame_server - cs->last_frame;
275  /* This client has missed their ACK packet after 1 DAY_TICKS..
276  * so we increase their lag for every frame that passes!
277  * The packet can be out by a max of _net_frame_freq */
278  if (cs->last_frame_server + Ticks::DAY_TICKS + _settings_client.network.frame_freq < _frame_counter) {
279  lag += _frame_counter - (cs->last_frame_server + Ticks::DAY_TICKS + _settings_client.network.frame_freq);
280  }
281  return lag;
282 }
283 
284 
285 /* There was a non-recoverable error, drop back to the main menu with a nice
286  * error */
287 void ShowNetworkError(StringID error_string)
288 {
291 }
292 
299 {
300  /* List of possible network errors, used by
301  * PACKET_SERVER_ERROR and PACKET_CLIENT_ERROR */
302  static const StringID network_error_strings[] = {
303  STR_NETWORK_ERROR_CLIENT_GENERAL,
304  STR_NETWORK_ERROR_CLIENT_DESYNC,
305  STR_NETWORK_ERROR_CLIENT_SAVEGAME,
306  STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST,
307  STR_NETWORK_ERROR_CLIENT_PROTOCOL_ERROR,
308  STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH,
309  STR_NETWORK_ERROR_CLIENT_NOT_AUTHORIZED,
310  STR_NETWORK_ERROR_CLIENT_NOT_EXPECTED,
311  STR_NETWORK_ERROR_CLIENT_WRONG_REVISION,
312  STR_NETWORK_ERROR_CLIENT_NAME_IN_USE,
313  STR_NETWORK_ERROR_CLIENT_WRONG_PASSWORD,
314  STR_NETWORK_ERROR_CLIENT_COMPANY_MISMATCH,
315  STR_NETWORK_ERROR_CLIENT_KICKED,
316  STR_NETWORK_ERROR_CLIENT_CHEATER,
317  STR_NETWORK_ERROR_CLIENT_SERVER_FULL,
318  STR_NETWORK_ERROR_CLIENT_TOO_MANY_COMMANDS,
319  STR_NETWORK_ERROR_CLIENT_TIMEOUT_PASSWORD,
320  STR_NETWORK_ERROR_CLIENT_TIMEOUT_COMPUTER,
321  STR_NETWORK_ERROR_CLIENT_TIMEOUT_MAP,
322  STR_NETWORK_ERROR_CLIENT_TIMEOUT_JOIN,
323  STR_NETWORK_ERROR_CLIENT_INVALID_CLIENT_NAME,
324  };
325  static_assert(lengthof(network_error_strings) == NETWORK_ERROR_END);
326 
327  if (err >= (ptrdiff_t)lengthof(network_error_strings)) err = NETWORK_ERROR_GENERAL;
328 
329  return network_error_strings[err];
330 }
331 
337 void NetworkHandlePauseChange(PauseMode prev_mode, PauseMode changed_mode)
338 {
339  if (!_networking) return;
340 
341  switch (changed_mode) {
342  case PM_PAUSED_NORMAL:
343  case PM_PAUSED_JOIN:
346  case PM_PAUSED_LINK_GRAPH: {
347  bool changed = ((_pause_mode == PM_UNPAUSED) != (prev_mode == PM_UNPAUSED));
348  bool paused = (_pause_mode != PM_UNPAUSED);
349  if (!paused && !changed) return;
350 
351  StringID str;
352  if (!changed) {
353  int i = -1;
354 
355  if ((_pause_mode & PM_PAUSED_NORMAL) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_MANUAL);
356  if ((_pause_mode & PM_PAUSED_JOIN) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_CONNECTING_CLIENTS);
357  if ((_pause_mode & PM_PAUSED_GAME_SCRIPT) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_GAME_SCRIPT);
358  if ((_pause_mode & PM_PAUSED_ACTIVE_CLIENTS) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_NOT_ENOUGH_PLAYERS);
359  if ((_pause_mode & PM_PAUSED_LINK_GRAPH) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_LINK_GRAPH);
360  str = STR_NETWORK_SERVER_MESSAGE_GAME_STILL_PAUSED_1 + i;
361  } else {
362  switch (changed_mode) {
363  case PM_PAUSED_NORMAL: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_MANUAL); break;
364  case PM_PAUSED_JOIN: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_CONNECTING_CLIENTS); break;
365  case PM_PAUSED_GAME_SCRIPT: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_GAME_SCRIPT); break;
366  case PM_PAUSED_ACTIVE_CLIENTS: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_NOT_ENOUGH_PLAYERS); break;
367  case PM_PAUSED_LINK_GRAPH: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_LINK_GRAPH); break;
368  default: NOT_REACHED();
369  }
370  str = paused ? STR_NETWORK_SERVER_MESSAGE_GAME_PAUSED : STR_NETWORK_SERVER_MESSAGE_GAME_UNPAUSED;
371  }
372 
373  NetworkTextMessage(NETWORK_ACTION_SERVER_MESSAGE, CC_DEFAULT, false, "", GetString(str));
374  break;
375  }
376 
377  default:
378  return;
379  }
380 }
381 
382 
391 static void CheckPauseHelper(bool pause, PauseMode pm)
392 {
393  if (pause == ((_pause_mode & pm) != PM_UNPAUSED)) return;
394 
395  Command<CMD_PAUSE>::Post(pm, pause);
396 }
397 
404 {
405  uint count = 0;
406 
407  for (const NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
408  if (cs->status != NetworkClientSocket::STATUS_ACTIVE) continue;
409  if (!Company::IsValidID(cs->GetInfo()->client_playas)) continue;
410  count++;
411  }
412 
413  return count;
414 }
415 
420 {
424  return;
425  }
427 }
428 
434 {
435  for (const NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
436  if (cs->status >= NetworkClientSocket::STATUS_AUTHORIZED && cs->status < NetworkClientSocket::STATUS_ACTIVE) return true;
437  }
438 
439  return false;
440 }
441 
445 static void CheckPauseOnJoin()
446 {
449  return;
450  }
452 }
453 
460 std::string_view ParseCompanyFromConnectionString(const std::string &connection_string, CompanyID *company_id)
461 {
462  std::string_view ip = connection_string;
463  if (company_id == nullptr) return ip;
464 
465  size_t offset = ip.find_last_of('#');
466  if (offset != std::string::npos) {
467  std::string_view company_string = ip.substr(offset + 1);
468  ip = ip.substr(0, offset);
469 
470  uint8_t company_value;
471  auto [_, err] = std::from_chars(company_string.data(), company_string.data() + company_string.size(), company_value);
472  if (err == std::errc()) {
473  if (company_value != COMPANY_NEW_COMPANY && company_value != COMPANY_SPECTATOR) {
474  if (company_value > MAX_COMPANIES || company_value == 0) {
475  *company_id = COMPANY_SPECTATOR;
476  } else {
477  /* "#1" means the first company, which has index 0. */
478  *company_id = (CompanyID)(company_value - 1);
479  }
480  } else {
481  *company_id = (CompanyID)company_value;
482  }
483  }
484  }
485 
486  return ip;
487 }
488 
504 std::string_view ParseFullConnectionString(const std::string &connection_string, uint16_t &port, CompanyID *company_id)
505 {
506  std::string_view ip = ParseCompanyFromConnectionString(connection_string, company_id);
507 
508  size_t port_offset = ip.find_last_of(':');
509  size_t ipv6_close = ip.find_last_of(']');
510  if (port_offset != std::string::npos && (ipv6_close == std::string::npos || ipv6_close < port_offset)) {
511  std::string_view port_string = ip.substr(port_offset + 1);
512  ip = ip.substr(0, port_offset);
513  std::from_chars(port_string.data(), port_string.data() + port_string.size(), port);
514  }
515  return ip;
516 }
517 
524 std::string NormalizeConnectionString(const std::string &connection_string, uint16_t default_port)
525 {
526  uint16_t port = default_port;
527  std::string_view ip = ParseFullConnectionString(connection_string, port);
528  return std::string(ip) + ":" + std::to_string(port);
529 }
530 
539 NetworkAddress ParseConnectionString(const std::string &connection_string, uint16_t default_port)
540 {
541  uint16_t port = default_port;
542  std::string_view ip = ParseFullConnectionString(connection_string, port);
543  return NetworkAddress(ip, port);
544 }
545 
551 /* static */ void ServerNetworkGameSocketHandler::AcceptConnection(SOCKET s, const NetworkAddress &address)
552 {
553  /* Register the login */
555 
557  cs->client_address = address; // Save the IP of the client
558 
560 }
561 
566 static void InitializeNetworkPools(bool close_admins = true)
567 {
568  PoolBase::Clean(PT_NCLIENT | (close_admins ? PT_NADMIN : PT_NONE));
569 }
570 
575 void NetworkClose(bool close_admins)
576 {
577  if (_network_server) {
578  if (close_admins) {
580  as->CloseConnection(true);
581  }
582  }
583 
584  for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
585  cs->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT);
586  }
589 
591  } else {
592  if (MyClient::my_client != nullptr) {
595  }
596 
598  }
599  NetworkGameSocketHandler::ProcessDeferredDeletions();
600 
602 
603  _networking = false;
604  _network_server = false;
605 
607 
608  delete[] _network_company_states;
609  _network_company_states = nullptr;
611 
612  InitializeNetworkPools(close_admins);
613 }
614 
615 /* Initializes the network (cleans sockets and stuff) */
616 static void NetworkInitialize(bool close_admins = true)
617 {
618  InitializeNetworkPools(close_admins);
619 
620  _sync_frame = 0;
621  _network_first_time = true;
622 
623  _network_reconnect = 0;
624 }
625 
628 private:
629  std::string connection_string;
630 
631 public:
632  TCPQueryConnecter(const std::string &connection_string) : TCPServerConnecter(connection_string, NETWORK_DEFAULT_PORT), connection_string(connection_string) {}
633 
634  void OnFailure() override
635  {
636  Debug(net, 9, "Query::OnFailure(): connection_string={}", this->connection_string);
637 
638  NetworkGameList *item = NetworkGameListAddItem(connection_string);
639  item->status = NGLS_OFFLINE;
640  item->refreshing = false;
641 
643  }
644 
645  void OnConnect(SOCKET s) override
646  {
647  Debug(net, 9, "Query::OnConnect(): connection_string={}", this->connection_string);
648 
649  QueryNetworkGameSocketHandler::QueryServer(s, this->connection_string);
650  }
651 };
652 
657 void NetworkQueryServer(const std::string &connection_string)
658 {
659  if (!_network_available) return;
660 
661  Debug(net, 9, "NetworkQueryServer(): connection_string={}", connection_string);
662 
663  /* Mark the entry as refreshing, so the GUI can show the refresh is pending. */
664  NetworkGameList *item = NetworkGameListAddItem(connection_string);
665  item->refreshing = true;
666 
667  TCPConnecter::Create<TCPQueryConnecter>(connection_string);
668 }
669 
679 NetworkGameList *NetworkAddServer(const std::string &connection_string, bool manually, bool never_expire)
680 {
681  if (connection_string.empty()) return nullptr;
682 
683  /* Ensure the item already exists in the list */
684  NetworkGameList *item = NetworkGameListAddItem(connection_string);
685  if (item->info.server_name.empty()) {
687  item->info.server_name = connection_string;
688 
690 
691  NetworkQueryServer(connection_string);
692  }
693 
694  if (manually) item->manually = true;
695  if (never_expire) item->version = INT32_MAX;
696 
697  return item;
698 }
699 
705 void GetBindAddresses(NetworkAddressList *addresses, uint16_t port)
706 {
707  for (const auto &iter : _network_bind_list) {
708  addresses->emplace_back(iter.c_str(), port);
709  }
710 
711  /* No address, so bind to everything. */
712  if (addresses->empty()) {
713  addresses->emplace_back("", port);
714  }
715 }
716 
717 /* Generates the list of manually added hosts from NetworkGameList and
718  * dumps them into the array _network_host_list. This array is needed
719  * by the function that generates the config file. */
720 void NetworkRebuildHostList()
721 {
722  _network_host_list.clear();
723 
724  for (NetworkGameList *item = _network_game_list; item != nullptr; item = item->next) {
725  if (item->manually) _network_host_list.emplace_back(item->connection_string);
726  }
727 }
728 
731 private:
732  std::string connection_string;
733 
734 public:
735  TCPClientConnecter(const std::string &connection_string) : TCPServerConnecter(connection_string, NETWORK_DEFAULT_PORT), connection_string(connection_string) {}
736 
737  void OnFailure() override
738  {
739  Debug(net, 9, "Client::OnFailure(): connection_string={}", this->connection_string);
740 
741  ShowNetworkError(STR_NETWORK_ERROR_NOCONNECTION);
742  }
743 
744  void OnConnect(SOCKET s) override
745  {
746  Debug(net, 9, "Client::OnConnect(): connection_string={}", this->connection_string);
747 
748  _networking = true;
749  new ClientNetworkGameSocketHandler(s, this->connection_string);
750  IConsoleCmdExec("exec scripts/on_client.scr 0");
752  }
753 };
754 
772 bool NetworkClientConnectGame(const std::string &connection_string, CompanyID default_company, const std::string &join_server_password, const std::string &join_company_password)
773 {
774  Debug(net, 9, "NetworkClientConnectGame(): connection_string={}", connection_string);
775 
776  CompanyID join_as = default_company;
777  std::string resolved_connection_string = ServerAddress::Parse(connection_string, NETWORK_DEFAULT_PORT, &join_as).connection_string;
778 
779  if (!_network_available) return false;
780  if (!NetworkValidateOurClientName()) return false;
781 
782  _network_join.connection_string = resolved_connection_string;
783  _network_join.company = join_as;
784  _network_join.server_password = join_server_password;
785  _network_join.company_password = join_company_password;
786 
787  if (_game_mode == GM_MENU) {
788  /* From the menu we can immediately continue with the actual join. */
790  } else {
791  /* When already playing a game, first go back to the main menu. This
792  * disconnects the user from the current game, meaning we can safely
793  * load in the new. After all, there is little point in continueing to
794  * play on a server if we are connecting to another one.
795  */
797  }
798  return true;
799 }
800 
807 {
809  NetworkInitialize();
810 
812  Debug(net, 9, "status = CONNECTING");
813  _network_join_status = NETWORK_JOIN_STATUS_CONNECTING;
814  ShowJoinStatusWindow();
815 
816  TCPConnecter::Create<TCPClientConnecter>(_network_join.connection_string);
817 }
818 
819 static void NetworkInitGameInfo()
820 {
821  FillStaticNetworkServerGameInfo();
822  /* The server is a client too */
823  _network_game_info.clients_on = _network_dedicated ? 0 : 1;
824 
825  /* There should be always space for the server. */
829 
831 }
832 
843 bool NetworkValidateServerName(std::string &server_name)
844 {
845  StrTrimInPlace(server_name);
846  if (!server_name.empty()) return true;
847 
848  ShowErrorMessage(STR_NETWORK_ERROR_BAD_SERVER_NAME, INVALID_STRING_ID, WL_ERROR);
849  return false;
850 }
851 
859 {
860  static const std::string fallback_client_name = "Unnamed Client";
862  if (_settings_client.network.client_name.empty() || _settings_client.network.client_name.compare(fallback_client_name) == 0) {
863  Debug(net, 1, "No \"client_name\" has been set, using \"{}\" instead. Please set this now using the \"name <new name>\" command", fallback_client_name);
864  _settings_client.network.client_name = fallback_client_name;
865  }
866 
867  static const std::string fallback_server_name = "Unnamed Server";
869  if (_settings_client.network.server_name.empty() || _settings_client.network.server_name.compare(fallback_server_name) == 0) {
870  Debug(net, 1, "No \"server_name\" has been set, using \"{}\" instead. Please set this now using the \"server_name <new name>\" command", fallback_server_name);
871  _settings_client.network.server_name = fallback_server_name;
872  }
873 }
874 
875 bool NetworkServerStart()
876 {
877  if (!_network_available) return false;
878 
879  /* Call the pre-scripts */
880  IConsoleCmdExec("exec scripts/pre_server.scr 0");
881  if (_network_dedicated) IConsoleCmdExec("exec scripts/pre_dedicated.scr 0");
882 
883  /* Check for the client and server names to be set, but only after the scripts had a chance to set them.*/
885 
886  NetworkDisconnect(false);
887  NetworkInitialize(false);
889  Debug(net, 5, "Starting listeners for clients");
891 
892  /* Only listen for admins when the password isn't empty. */
893  if (!_settings_client.network.admin_password.empty()) {
894  Debug(net, 5, "Starting listeners for admins");
896  }
897 
898  /* Try to start UDP-server */
899  Debug(net, 5, "Starting listeners for incoming server queries");
901 
903  _network_server = true;
904  _networking = true;
905  _frame_counter = 0;
907  _frame_counter_max = 0;
908  _last_sync_frame = 0;
910 
913 
914  NetworkInitGameInfo();
915 
916  if (_settings_client.network.server_game_type != SERVER_GAME_TYPE_LOCAL) {
918  }
919 
920  /* execute server initialization script */
921  IConsoleCmdExec("exec scripts/on_server.scr 0");
922  /* if the server is dedicated ... add some other script */
923  if (_network_dedicated) IConsoleCmdExec("exec scripts/on_dedicated.scr 0");
924 
925  /* welcome possibly still connected admins - this can only happen on a dedicated server. */
927 
928  return true;
929 }
930 
931 /* The server is rebooting...
932  * The only difference with NetworkDisconnect, is the packets that is sent */
933 void NetworkReboot()
934 {
935  if (_network_server) {
936  for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
937  cs->SendNewGame();
938  cs->SendPackets();
939  }
940 
942  as->SendNewGame();
943  as->SendPackets();
944  }
945  }
946 
947  /* For non-dedicated servers we have to kick the admins as we are not
948  * certain that we will end up in a new network game. */
950 }
951 
956 void NetworkDisconnect(bool close_admins)
957 {
958  if (_network_server) {
959  for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
960  cs->SendShutdown();
961  cs->SendPackets();
962  }
963 
964  if (close_admins) {
966  as->SendShutdown();
967  as->SendPackets();
968  }
969  }
970  }
971 
973 
974  NetworkClose(close_admins);
975 
976  /* Reinitialize the UDP stack, i.e. close all existing connections. */
978 }
979 
985 {
986  if (!_networking) return;
987 
989  case SERVER_GAME_TYPE_LOCAL:
991  break;
992 
993  case SERVER_GAME_TYPE_INVITE_ONLY:
994  case SERVER_GAME_TYPE_PUBLIC:
996  break;
997 
998  default:
999  NOT_REACHED();
1000  }
1001 }
1002 
1007 static bool NetworkReceive()
1008 {
1009  bool result;
1010  if (_network_server) {
1013  } else {
1015  }
1016  NetworkGameSocketHandler::ProcessDeferredDeletions();
1017  return result;
1018 }
1019 
1020 /* This sends all buffered commands (if possible) */
1021 static void NetworkSend()
1022 {
1023  if (_network_server) {
1026  } else {
1028  }
1029  NetworkGameSocketHandler::ProcessDeferredDeletions();
1030 }
1031 
1038 {
1044  NetworkGameSocketHandler::ProcessDeferredDeletions();
1045 
1047 }
1048 
1049 /* The main loop called from ttd.c
1050  * Here we also have to do StateGameLoop if needed! */
1051 void NetworkGameLoop()
1052 {
1053  if (!_networking) return;
1054 
1055  if (!NetworkReceive()) return;
1056 
1057  if (_network_server) {
1058  /* Log the sync state to check for in-syncedness of replays. */
1059  if (TimerGameEconomy::date_fract == 0) {
1060  /* We don't want to log multiple times if paused. */
1061  static TimerGameEconomy::Date last_log;
1062  if (last_log != TimerGameEconomy::date) {
1063  Debug(desync, 1, "sync: {:08x}; {:02x}; {:08x}; {:08x}", TimerGameEconomy::date, TimerGameEconomy::date_fract, _random.state[0], _random.state[1]);
1064  last_log = TimerGameEconomy::date;
1065  }
1066  }
1067 
1068 #ifdef DEBUG_DUMP_COMMANDS
1069  /* Loading of the debug commands from -ddesync>=1 */
1070  static FILE *f = FioFOpenFile("commands.log", "rb", SAVE_DIR);
1071  static TimerGameEconomy::Date next_date(0);
1072  static uint32_t next_date_fract;
1073  static CommandPacket *cp = nullptr;
1074  static bool check_sync_state = false;
1075  static uint32_t sync_state[2];
1076  if (f == nullptr && next_date == 0) {
1077  Debug(desync, 0, "Cannot open commands.log");
1078  next_date = TimerGameEconomy::Date(1);
1079  }
1080 
1081  while (f != nullptr && !feof(f)) {
1082  if (TimerGameEconomy::date == next_date && TimerGameEconomy::date_fract == next_date_fract) {
1083  if (cp != nullptr) {
1084  NetworkSendCommand(cp->cmd, cp->err_msg, nullptr, cp->company, cp->data);
1085  Debug(desync, 0, "Injecting: {:08x}; {:02x}; {:02x}; {:08x}; {} ({})", TimerGameEconomy::date, TimerGameEconomy::date_fract, (int)_current_company, cp->cmd, FormatArrayAsHex(cp->data), GetCommandName(cp->cmd));
1086  delete cp;
1087  cp = nullptr;
1088  }
1089  if (check_sync_state) {
1090  if (sync_state[0] == _random.state[0] && sync_state[1] == _random.state[1]) {
1091  Debug(desync, 0, "Sync check: {:08x}; {:02x}; match", TimerGameEconomy::date, TimerGameEconomy::date_fract);
1092  } else {
1093  Debug(desync, 0, "Sync check: {:08x}; {:02x}; mismatch expected {{{:08x}, {:08x}}}, got {{{:08x}, {:08x}}}",
1094  TimerGameEconomy::date, TimerGameEconomy::date_fract, sync_state[0], sync_state[1], _random.state[0], _random.state[1]);
1095  NOT_REACHED();
1096  }
1097  check_sync_state = false;
1098  }
1099  }
1100 
1101  if (cp != nullptr || check_sync_state) break;
1102 
1103  char buff[4096];
1104  if (fgets(buff, lengthof(buff), f) == nullptr) break;
1105 
1106  char *p = buff;
1107  /* Ignore the "[date time] " part of the message */
1108  if (*p == '[') {
1109  p = strchr(p, ']');
1110  if (p == nullptr) break;
1111  p += 2;
1112  }
1113 
1114  if (strncmp(p, "cmd: ", 5) == 0
1115 #ifdef DEBUG_FAILED_DUMP_COMMANDS
1116  || strncmp(p, "cmdf: ", 6) == 0
1117 #endif
1118  ) {
1119  p += 5;
1120  if (*p == ' ') p++;
1121  cp = new CommandPacket();
1122  int company;
1123  uint cmd;
1124  char buffer[256];
1125  uint32_t next_date_raw;
1126  int ret = sscanf(p, "%x; %x; %x; %x; %x; %255s", &next_date_raw, &next_date_fract, &company, &cmd, &cp->err_msg, buffer);
1127  assert(ret == 6);
1128  next_date = TimerGameEconomy::Date((int32_t)next_date_raw);
1129  cp->company = (CompanyID)company;
1130  cp->cmd = (Commands)cmd;
1131 
1132  /* Parse command data. */
1133  std::vector<byte> args;
1134  size_t arg_len = strlen(buffer);
1135  for (size_t i = 0; i + 1 < arg_len; i += 2) {
1136  byte e = 0;
1137  std::from_chars(buffer + i, buffer + i + 2, e, 16);
1138  args.emplace_back(e);
1139  }
1140  cp->data = args;
1141  } else if (strncmp(p, "join: ", 6) == 0) {
1142  /* Manually insert a pause when joining; this way the client can join at the exact right time. */
1143  uint32_t next_date_raw;
1144  int ret = sscanf(p + 6, "%x; %x", &next_date_raw, &next_date_fract);
1145  next_date = TimerGameEconomy::Date((int32_t)next_date_raw);
1146  assert(ret == 2);
1147  Debug(desync, 0, "Injecting pause for join at {:08x}:{:02x}; please join when paused", next_date, next_date_fract);
1148  cp = new CommandPacket();
1149  cp->company = COMPANY_SPECTATOR;
1150  cp->cmd = CMD_PAUSE;
1152  _ddc_fastforward = false;
1153  } else if (strncmp(p, "sync: ", 6) == 0) {
1154  uint32_t next_date_raw;
1155  int ret = sscanf(p + 6, "%x; %x; %x; %x", &next_date_raw, &next_date_fract, &sync_state[0], &sync_state[1]);
1156  next_date = TimerGameEconomy::Date((int32_t)next_date_raw);
1157  assert(ret == 4);
1158  check_sync_state = true;
1159  } else if (strncmp(p, "msg: ", 5) == 0 || strncmp(p, "client: ", 8) == 0 ||
1160  strncmp(p, "load: ", 6) == 0 || strncmp(p, "save: ", 6) == 0) {
1161  /* A message that is not very important to the log playback, but part of the log. */
1162 #ifndef DEBUG_FAILED_DUMP_COMMANDS
1163  } else if (strncmp(p, "cmdf: ", 6) == 0) {
1164  Debug(desync, 0, "Skipping replay of failed command: {}", p + 6);
1165 #endif
1166  } else {
1167  /* Can't parse a line; what's wrong here? */
1168  Debug(desync, 0, "Trying to parse: {}", p);
1169  NOT_REACHED();
1170  }
1171  }
1172  if (f != nullptr && feof(f)) {
1173  Debug(desync, 0, "End of commands.log");
1174  fclose(f);
1175  f = nullptr;
1176  }
1177 #endif /* DEBUG_DUMP_COMMANDS */
1179  /* Only check for active clients just before we're going to send out
1180  * the commands so we don't send multiple pause/unpause commands when
1181  * the frame_freq is more than 1 tick. Same with distributing commands. */
1182  CheckPauseOnJoin();
1185  }
1186 
1187  bool send_frame = false;
1188 
1189  /* We first increase the _frame_counter */
1190  _frame_counter++;
1191  /* Update max-frame-counter */
1194  send_frame = true;
1195  }
1196 
1198 
1199  /* Then we make the frame */
1200  StateGameLoop();
1201 
1202  _sync_seed_1 = _random.state[0];
1203 #ifdef NETWORK_SEND_DOUBLE_SEED
1204  _sync_seed_2 = _random.state[1];
1205 #endif
1206 
1207  NetworkServer_Tick(send_frame);
1208  } else {
1209  /* Client */
1210 
1211  /* Make sure we are at the frame were the server is (quick-frames) */
1213  /* Run a number of frames; when things go bad, get out. */
1216  }
1217  } else {
1218  /* Else, keep on going till _frame_counter_max */
1220  /* Run one frame; if things went bad, get out. */
1222  }
1223  }
1224  }
1225 
1226  NetworkSend();
1227 }
1228 
1229 static void NetworkGenerateServerId()
1230 {
1231  _settings_client.network.network_id = GenerateUid("OpenTTD Server ID");
1232 }
1233 
1236 {
1237  Debug(net, 3, "Starting network");
1238 
1239  /* Network is available */
1241  _network_dedicated = false;
1242 
1243  /* Generate an server id when there is none yet */
1244  if (_settings_client.network.network_id.empty()) NetworkGenerateServerId();
1245 
1246  _network_game_info = {};
1247 
1248  NetworkInitialize();
1250  Debug(net, 3, "Network online, multiplayer available");
1253 }
1254 
1257 {
1260  NetworkUDPClose();
1261 
1262  Debug(net, 3, "Shutting down network");
1263 
1264  _network_available = false;
1265 
1267 }
1268 
1269 #ifdef __EMSCRIPTEN__
1270 extern "C" {
1271 
1272 void CDECL em_openttd_add_server(const char *connection_string)
1273 {
1274  NetworkAddServer(connection_string, false, true);
1275 }
1276 
1277 }
1278 #endif
network_content.h
TCPConnecter::CheckCallbacks
static void CheckCallbacks()
Check whether we need to call the callback, i.e.
Definition: tcp_connect.cpp:463
NetworkValidateServerName
bool NetworkValidateServerName(std::string &server_name)
Trim the given server name in place, i.e.
Definition: network.cpp:843
host.h
NetworkSettings::frame_freq
uint8_t frame_freq
how often do we send commands to the clients
Definition: settings_type.h:296
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:3200
NETWORK_RECV_STATUS_CLIENT_QUIT
@ NETWORK_RECV_STATUS_CLIENT_QUIT
The connection is lost gracefully. Other clients are already informed of this leaving client.
Definition: core.h:27
FormatArrayAsHex
std::string FormatArrayAsHex(std::span< const byte > data)
Format a byte array into a continuous hex string.
Definition: string.cpp:88
SAVE_DIR
@ SAVE_DIR
Base directory for all savegames.
Definition: fileio_type.h:110
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:817
NetworkValidateOurClientName
bool NetworkValidateOurClientName()
Convenience method for NetworkValidateClientName on _settings_client.network.client_name.
Definition: network_client.cpp:1353
NetworkAddServer
NetworkGameList * NetworkAddServer(const std::string &connection_string, bool manually, bool never_expire)
Validates an address entered as a string and adds the server to the list.
Definition: network.cpp:679
ShowErrorMessage
void ShowErrorMessage(StringID summary_msg, int x, int y, CommandCost cc)
Display an error message in a window.
Definition: error_gui.cpp:367
NormalizeConnectionString
std::string NormalizeConnectionString(const std::string &connection_string, uint16_t default_port)
Normalize a connection string.
Definition: network.cpp:524
NetworkClientInfo::client_name
std::string client_name
Name of the client.
Definition: network_base.h:26
ClearGRFConfigList
void ClearGRFConfigList(GRFConfig **config)
Clear a GRF Config list, freeing all nodes.
Definition: newgrf_config.cpp:356
NetworkUDPServerListen
void NetworkUDPServerListen()
Start the listening of the UDP server component.
Definition: network_udp.cpp:144
NetworkJoinInfo::company_password
std::string company_password
The password of the company to join.
Definition: network_client.h:116
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
GetBindAddresses
void GetBindAddresses(NetworkAddressList *addresses, uint16_t port)
Get the addresses to bind to.
Definition: network.cpp:705
StringID
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
NetworkCompanyState
Some state information of a company, especially for servers.
Definition: network_type.h:74
_network_server
bool _network_server
network-server is active
Definition: network.cpp:60
_network_company_passworded
CompanyMask _network_company_passworded
Bitmask of the password status of all companies.
Definition: network.cpp:82
CloseWindowById
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Definition: window.cpp:1141
NetworkAction
NetworkAction
Actions that can be used for NetworkTextMessage.
Definition: network_type.h:102
WC_CLIENT_LIST
@ WC_CLIENT_LIST
Client list; Window numbers:
Definition: window_type.h:478
ServerNetworkAdminSocketHandler::WelcomeAll
static void WelcomeAll()
Send a Welcome packet to all connected admins.
Definition: network_admin.cpp:976
NetworkJoinInfo::server_password
std::string server_password
The password of the server to join.
Definition: network_client.h:115
ClientNetworkGameSocketHandler::GameLoop
static bool GameLoop()
Actual game loop for the client.
Definition: network_client.cpp:269
TCPQueryConnecter::OnFailure
void OnFailure() override
Callback for when the connection attempt failed.
Definition: network.cpp:634
TCPListenHandler< ServerNetworkGameSocketHandler, PACKET_SERVER_FULL, PACKET_SERVER_BANNED >::Listen
static bool Listen(uint16_t port)
Listen on a particular port.
Definition: tcp_listen.h:143
NetworkHasJoiningClient
static bool NetworkHasJoiningClient()
Checks whether there is a joining client.
Definition: network.cpp:433
CommandPacket::err_msg
StringID err_msg
string ID of error message to use.
Definition: network_internal.h:118
NetworkJoinInfo::connection_string
std::string connection_string
The address of the server to join.
Definition: network_client.h:113
_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:307
TextColour
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
Definition: gfx_type.h:253
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:337
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:96
_random
Randomizer _random
Random used in the game state calculations.
Definition: random_func.cpp:37
ServerAddress::Parse
static ServerAddress Parse(const std::string &connection_string, uint16_t default_port, CompanyID *company_id=nullptr)
Convert a string containing either "hostname", "hostname:port" or invite code to a ServerAddress,...
Definition: address.cpp:450
TimerGameEconomy::date_fract
static DateFract date_fract
Fractional part of the day.
Definition: timer_game_economy.h:38
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:54
_network_bind_list
StringList _network_bind_list
The addresses to bind on.
Definition: network.cpp:68
UpdateNetworkGameWindow
void UpdateNetworkGameWindow()
Update the network new window because a new server is found on the network.
Definition: network_gui.cpp:66
NetworkGameListAddItem
NetworkGameList * NetworkGameListAddItem(const std::string &connection_string)
Add a new item to the linked gamelist.
Definition: network_gamelist.cpp:32
NetworkBackgroundLoop
void NetworkBackgroundLoop()
We have to do some (simple) background stuff that runs normally, even when we are not in multiplayer.
Definition: network.cpp:1037
network_gui.h
_network_join_status
NetworkJoinStatus _network_join_status
The status of joining.
Definition: network_gui.cpp:2101
GetNetworkErrorMsg
StringID GetNetworkErrorMsg(NetworkErrorCode err)
Retrieve the string id of an internal error number.
Definition: network.cpp:298
ClientNetworkGameSocketHandler::my_client
static ClientNetworkGameSocketHandler * my_client
This is us!
Definition: network_client.h:41
_redirect_console_to_client
ClientID _redirect_console_to_client
If not invalid, redirect the console output to a client.
Definition: network.cpp:66
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:162
GUISettings::network_chat_timeout
uint16_t network_chat_timeout
timeout of chat messages in seconds
Definition: settings_type.h:212
CommandTraits
Defines the traits of a command.
Definition: command_type.h:448
CC_DEFAULT
static const TextColour CC_DEFAULT
Default colour of the console.
Definition: console_type.h:23
_network_first_time
bool _network_first_time
Whether we have finished joining or not.
Definition: network.cpp:81
NetworkServer_Tick
void NetworkServer_Tick(bool send_frame)
This is called every tick if this is a _network_server.
Definition: network_server.cpp:1750
Debug
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
ServerNetworkAdminSocketHandler::Send
static void Send()
Send the packets for the server sockets.
Definition: network_admin.cpp:102
network_base.h
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:41
NetworkClientInfo::~NetworkClientInfo
~NetworkClientInfo()
Basically a client is leaving us right now.
Definition: network.cpp:103
ClientNetworkCoordinatorSocketHandler::CloseAllConnections
void CloseAllConnections()
Close all pending connection tokens.
Definition: network_coordinator.cpp:685
NetworkChangeCompanyPassword
std::string NetworkChangeCompanyPassword(CompanyID company_id, std::string password)
Change the company password of a given company.
Definition: network.cpp:157
NetworkQueryServer
void NetworkQueryServer(const std::string &connection_string)
Query a server to fetch the game-info.
Definition: network.cpp:657
PM_UNPAUSED
@ PM_UNPAUSED
A normal unpaused game.
Definition: openttd.h:63
HasClients
bool HasClients()
Return whether there is any client connected or trying to connect at all.
Definition: network.cpp:95
network_coordinator.h
_sync_seed_1
uint32_t _sync_seed_1
Seed to compare during sync checks.
Definition: network.cpp:76
Pool::MAX_SIZE
static constexpr size_t MAX_SIZE
Make template parameter accessible from outside.
Definition: pool_type.hpp:84
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:114
NetworkClientJoinGame
void NetworkClientJoinGame()
Actually perform the joining to the server.
Definition: network.cpp:806
NetworkJoinInfo::company
CompanyID company
The company to join.
Definition: network_client.h:114
CommandPacket::company
CompanyID company
company that is executing the command
Definition: network_internal.h:113
ParseConnectionString
NetworkAddress ParseConnectionString(const std::string &connection_string, uint16_t default_port)
Convert a string containing either "hostname" or "hostname:ip" to a NetworkAddress.
Definition: network.cpp:539
COMPANY_NEW_COMPANY
@ COMPANY_NEW_COMPANY
The client wants a new company.
Definition: company_type.h:34
ServerNetworkGameSocketHandler::Send
static void Send()
Send the packets for the server sockets.
Definition: network_server.cpp:325
CommandPacket
Everything we need to know about a command to be able to execute it.
Definition: network_internal.h:109
NetworkSettings::last_joined
std::string last_joined
Last joined server.
Definition: settings_type.h:332
NetworkAddressList
std::vector< NetworkAddress > NetworkAddressList
Type for a list of addresses.
Definition: address.h:19
TCPListenHandler< ServerNetworkAdminSocketHandler, ADMIN_PACKET_SERVER_FULL, ADMIN_PACKET_SERVER_BANNED >::Receive
static bool Receive()
Handle the receiving of packets.
Definition: tcp_listen.h:101
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:263
StrTrimInPlace
void StrTrimInPlace(std::string &str)
Trim the spaces from given string in place, i.e.
Definition: string.cpp:288
IConsoleCmdExec
void IConsoleCmdExec(const std::string &command_string, const uint recurse_count)
Execute a given command passed to us.
Definition: console.cpp:293
_last_sync_frame
uint32_t _last_sync_frame
Used in the server to store the last time a sync packet was sent to clients.
Definition: network.cpp:74
NetworkGameList::manually
bool manually
True if the server was added manually.
Definition: network_gamelist.h:33
NetworkSettings::admin_password
std::string admin_password
password for the admin network
Definition: settings_type.h:317
_pause_mode
PauseMode _pause_mode
The current pause mode.
Definition: gfx.cpp:50
NetworkClient_Connected
void NetworkClient_Connected()
Is called after a client is connected to the server.
Definition: network_client.cpp:1255
TCPClientConnecter::OnFailure
void OnFailure() override
Callback for when the connection attempt failed.
Definition: network.cpp:737
ClientNetworkCoordinatorSocketHandler::CloseConnection
NetworkRecvStatus CloseConnection(bool error=true) override
This will put this socket handler in a close state.
Definition: network_coordinator.cpp:432
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:60
TCPClientConnecter
Non blocking connection create to actually connect to servers.
Definition: network.cpp:730
NetworkSettings::client_name
std::string client_name
name of the player (as client)
Definition: settings_type.h:318
InitializeNetworkPools
static void InitializeNetworkPools(bool close_admins=true)
Resets the pools used for network clients, and the admin pool if needed.
Definition: network.cpp:566
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:1256
PT_NADMIN
@ PT_NADMIN
Network admin pool.
Definition: pool_type.hpp:20
_network_company_states
NetworkCompanyState * _network_company_states
Statistics about some companies.
Definition: network.cpp:64
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:57
NetworkGameList::version
int version
Used to see which servers are no longer available on the Game Coordinator and can be removed.
Definition: network_gamelist.h:35
_networking
bool _networking
are we in networking mode?
Definition: network.cpp:59
CheckPauseHelper
static void CheckPauseHelper(bool pause, PauseMode pm)
Helper function for the pause checkers.
Definition: network.cpp:391
PT_NONE
@ PT_NONE
No pool is selected.
Definition: pool_type.hpp:17
CheckClientAndServerName
static void CheckClientAndServerName()
Check whether the client and server name are set, for a dedicated server and if not set them to some ...
Definition: network.cpp:858
ServerNetworkGameSocketHandler::GetByClientID
static ServerNetworkGameSocketHandler * GetByClientID(ClientID client_id)
Return the client state given it's client-identifier.
Definition: network.cpp:128
network_client.h
PauseMode
PauseMode
Modes of pausing we've got.
Definition: openttd.h:62
network_server.h
_network_dedicated
bool _network_dedicated
are we a dedicated server?
Definition: network.cpp:62
CMD_PAUSE
@ CMD_PAUSE
pause the game
Definition: command_type.h:273
ClientNetworkCoordinatorSocketHandler::Register
void Register()
Register our server to receive our invite code.
Definition: network_coordinator.cpp:452
TCPConnecter::KillAll
static void KillAll()
Kill all connection attempts.
Definition: tcp_connect.cpp:472
QueryNetworkGameSocketHandler::QueryServer
static void QueryServer(SOCKET s, const std::string &connection_string)
Start to query a server based on an open socket.
Definition: network_query.h:46
PM_PAUSED_GAME_SCRIPT
@ PM_PAUSED_GAME_SCRIPT
A game paused by a game script.
Definition: openttd.h:69
ServerNetworkGameSocketHandler::AcceptConnection
static void AcceptConnection(SOCKET s, const NetworkAddress &address)
Handle the accepting of a connection to the server.
Definition: network.cpp:551
PT_NCLIENT
@ PT_NCLIENT
Network client pools.
Definition: pool_type.hpp:19
NETWORK_DEFAULT_PORT
static const uint16_t NETWORK_DEFAULT_PORT
The default port of the game server (TCP & UDP)
Definition: config.h:25
ParseCompanyFromConnectionString
std::string_view ParseCompanyFromConnectionString(const std::string &connection_string, CompanyID *company_id)
Parse the company part ("#company" postfix) of a connecting string.
Definition: network.cpp:460
NetworkCompanyIsPassworded
bool NetworkCompanyIsPassworded(CompanyID company_id)
Check if the company we want to join requires a password.
Definition: network.cpp:209
NetworkClientInfo::client_id
ClientID client_id
Client identifier (same as ClientState->client_id)
Definition: network_base.h:25
NetworkDisconnect
void NetworkDisconnect(bool close_admins)
We want to disconnect from the host/clients.
Definition: network.cpp:956
NetworkHTTPUninitialize
void NetworkHTTPUninitialize()
Uninitialize the HTTP socket handler.
Definition: http_curl.cpp:277
NetworkSettings::server_port
uint16_t server_port
port the server listens on
Definition: settings_type.h:308
network_query.h
_network_own_client_id
ClientID _network_own_client_id
Our client identifier.
Definition: network.cpp:65
NetworkBackgroundUDPLoop
void NetworkBackgroundUDPLoop()
Receive the UDP packets.
Definition: network_udp.cpp:161
NetworkSettings::server_name
std::string server_name
name of the server
Definition: settings_type.h:314
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:244
_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:68
_switch_mode
SwitchMode _switch_mode
The next mainloop command.
Definition: gfx.cpp:48
NetworkSettings::server_game_type
ServerGameType server_game_type
Server type: local / public / invite-only.
Definition: settings_type.h:311
_frame_counter_server
uint32_t _frame_counter_server
The frame_counter of the server, if in network-mode.
Definition: network.cpp:71
_ddc_fastforward
#define _ddc_fastforward
Helper variable to make the dedicated server go fast until the (first) join.
Definition: network_internal.h:50
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:50
NetworkAddress
Wrapper for (un)resolved network addresses; there's no reason to transform a numeric IP to a string a...
Definition: address.h:28
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:384
Pool
Base class for all pools.
Definition: pool_type.hpp:80
ClientID
ClientID
'Unique' identifier to be given to clients
Definition: network_type.h:49
ClientNetworkCoordinatorSocketHandler::SendReceive
void SendReceive()
Check whether we received/can send some data from/to the Game Coordinator server and when that's the ...
Definition: network_coordinator.cpp:717
NetworkSendCommand
void NetworkSendCommand(Commands cmd, StringID err_message, CommandCallback *callback, CompanyID company, const CommandDataBuffer &cmd_data)
Prepare a DoCommand to be send over the network.
Definition: network_command.cpp:266
network_udp.h
NetworkAddChatMessage
void CDECL NetworkAddChatMessage(TextColour colour, uint duration, const std::string &message)
Add a text message to the 'chat window' to be shown.
Definition: network_chat_gui.cpp:86
NetworkClientSetCompanyPassword
void NetworkClientSetCompanyPassword(const std::string &password)
Set/Reset company password on the client side.
Definition: network_client.cpp:1400
_frame_counter
uint32_t _frame_counter
The current frame.
Definition: network.cpp:73
CommandPacket::data
CommandDataBuffer data
command parameters.
Definition: network_internal.h:120
SetDParam
void SetDParam(size_t n, uint64_t v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings.cpp:104
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:445
NetworkSettings::server_admin_port
uint16_t server_admin_port
port the server listens on for the admin network
Definition: settings_type.h:309
_network_clients_connected
byte _network_clients_connected
The amount of clients connected.
Definition: network.cpp:87
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:125
_network_coordinator_client
ClientNetworkCoordinatorSocketHandler _network_coordinator_client
The connection to the Game Coordinator.
Definition: network_coordinator.cpp:30
PM_PAUSED_NORMAL
@ PM_PAUSED_NORMAL
A game normally paused.
Definition: openttd.h:64
NetworkHTTPSocketHandler::HTTPReceive
static void HTTPReceive()
Do the receiving for all HTTP connections.
Definition: http_curl.cpp:107
GetString
std::string GetString(StringID string)
Resolve the given StringID into a std::string with all the associated DParam lookups and formatting.
Definition: strings.cpp:327
GetCommandName
const char * GetCommandName(Commands cmd)
This function mask the parameter with CMD_ID_MASK and returns the name which belongs to the given com...
Definition: command.cpp:132
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:305
NetworkCountActiveClients
static uint NetworkCountActiveClients()
Counts the number of active clients connected.
Definition: network.cpp:403
DESTTYPE_CLIENT
@ DESTTYPE_CLIENT
Send message/notice to only a certain client (Private)
Definition: network_type.h:94
udp.h
SetDParamStr
void SetDParamStr(size_t n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Definition: strings.cpp:352
WL_ERROR
@ WL_ERROR
Errors (eg. saving/loading failed)
Definition: error.h:26
TCPServerConnecter
Definition: tcp.h:151
SM_MENU
@ SM_MENU
Switch to game intro menu.
Definition: openttd.h:33
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:70
NetworkFindBroadcastIPs
void NetworkFindBroadcastIPs(NetworkAddressList *broadcast)
Find the IPv4 broadcast addresses; IPv6 uses a completely different strategy for broadcasting.
Definition: host.cpp:86
INSTANTIATE_POOL_METHODS
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
Definition: pool_func.hpp:225
PM_PAUSED_JOIN
@ PM_PAUSED_JOIN
A game paused for 'pause_on_join'.
Definition: openttd.h:66
NetworkGameList
Structure with information shown in the game list (GUI)
Definition: network_gamelist.h:27
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:419
NetworkGameSocketHandler::client_id
ClientID client_id
Client identifier.
Definition: tcp_game.h:509
CommandHelper
Definition: command_func.h:93
WC_SEND_NETWORK_MSG
@ WC_SEND_NETWORK_MSG
Chatbox; Window numbers:
Definition: window_type.h:503
NetworkClientConnectGame
bool NetworkClientConnectGame(const std::string &connection_string, CompanyID default_company, const std::string &join_server_password, const std::string &join_company_password)
Join a client to the server at with the given connection string.
Definition: network.cpp:772
NGLS_OFFLINE
@ NGLS_OFFLINE
Server is offline (or cannot be queried).
Definition: network_gamelist.h:19
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:300
_network_ban_list
StringList _network_ban_list
The banned clients.
Definition: network.cpp:70
NetworkUDPClose
void NetworkUDPClose()
Close all UDP related stuff.
Definition: network_udp.cpp:150
ClientSettings::network
NetworkSettings network
settings related to the network
Definition: settings_type.h:637
QueryNetworkGameSocketHandler::SendReceive
static void SendReceive()
Check if any query needs to send or receive.
Definition: network_query.cpp:164
Randomizer::state
uint32_t state[2]
The state of the randomizer.
Definition: random_func.hpp:23
NetworkClose
void NetworkClose(bool close_admins)
Close current connections.
Definition: network.cpp:575
ParseFullConnectionString
std::string_view ParseFullConnectionString(const std::string &connection_string, uint16_t &port, CompanyID *company_id)
Converts a string to ip/port/company Format: IP:port::company.
Definition: network.cpp:504
NetworkHTTPInitialize
void NetworkHTTPInitialize()
Initialize the HTTP socket handler.
Definition: http_curl.cpp:242
CHAR_TD_RLM
static const char32_t CHAR_TD_RLM
The next character acts like a right-to-left character.
Definition: string_type.h:36
_sync_frame
uint32_t _sync_frame
The frame to perform the sync check.
Definition: network.cpp:80
ServerNetworkGameSocketHandler::ServerNetworkGameSocketHandler
ServerNetworkGameSocketHandler(SOCKET s)
Create a new socket for the server side of the game connection.
Definition: network_server.cpp:212
ServerNetworkGameSocketHandler::client_address
NetworkAddress client_address
IP-address of the client (so they can be banned)
Definition: network_server.h:73
NetworkCoreInitialize
bool NetworkCoreInitialize()
Initializes the network core (as that is needed for some platforms.
Definition: core.cpp:24
NetworkUpdateServerGameType
void NetworkUpdateServerGameType()
The setting server_game_type was updated; possibly we need to take some action.
Definition: network.cpp:984
GenerateCompanyPasswordHash
std::string GenerateCompanyPasswordHash(const std::string &password, const std::string &password_server_id, uint32_t password_game_seed)
Hash the given password using server ID and game seed.
Definition: network.cpp:177
EndianBufferWriter
Endian-aware buffer adapter that always writes values in little endian order.
Definition: endian_buffer.hpp:26
NetworkGameList::next
NetworkGameList * next
Next pointer to make a linked game list.
Definition: network_gamelist.h:36
network_gamelist.h
Utf8Encode
size_t Utf8Encode(T buf, char32_t c)
Encode a unicode character and place it in the buffer.
Definition: string.cpp:479
NetworkExecuteLocalCommandQueue
void NetworkExecuteLocalCommandQueue()
Execute all commands on the local command queue that ought to be executed this frame.
Definition: network_command.cpp:316
Commands
Commands
List of commands.
Definition: command_type.h:187
ClientNetworkGameSocketHandler::SendQuit
static NetworkRecvStatus SendQuit()
Tell the server we would like to quit.
Definition: network_client.cpp:513
Ticks::DAY_TICKS
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
Definition: timer_game_tick.h:48
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:324
TCPListenHandler< ServerNetworkGameSocketHandler, PACKET_SERVER_FULL, PACKET_SERVER_BANNED >::CloseListeners
static void CloseListeners()
Close the sockets we're listening on.
Definition: tcp_listen.h:164
NetworkServerGameInfo::server_name
std::string server_name
Server name.
Definition: network_game_info.h:103
StateGameLoop
void StateGameLoop()
State controlling game loop.
Definition: openttd.cpp:1427
NetworkSettings::min_active_clients
uint8_t min_active_clients
minimum amount of active clients to unpause the game
Definition: settings_type.h:330
NetworkStartUp
void NetworkStartUp()
This tries to launch the network for a given OS.
Definition: network.cpp:1235
NetworkGameList::refreshing
bool refreshing
Whether this server is being queried.
Definition: network_gamelist.h:34
_network_host_list
StringList _network_host_list
The servers we know.
Definition: network.cpp:69
network_admin.h
NetworkGameList::info
NetworkGameInfo info
The game information of this server.
Definition: network_gamelist.h:30
NetworkServerGameInfo::clients_on
byte clients_on
Current count of clients on server.
Definition: network_game_info.h:107
_network_available
bool _network_available
is network mode available?
Definition: network.cpp:61
WN_NETWORK_STATUS_WINDOW_JOIN
@ WN_NETWORK_STATUS_WINDOW_JOIN
Network join status.
Definition: window_type.h:39
NetworkReceive
static bool NetworkReceive()
Receives something from the network.
Definition: network.cpp:1007
NetworkServerSetCompanyPassword
void NetworkServerSetCompanyPassword(CompanyID company_id, const std::string &password, bool already_hashed)
Set/Reset a company password on the server end.
Definition: network_server.cpp:1720
PM_PAUSED_ERROR
@ PM_PAUSED_ERROR
A game paused because a (critical) error.
Definition: openttd.h:67
NetworkFreeLocalCommandQueue
void NetworkFreeLocalCommandQueue()
Free the local command queues.
Definition: network_command.cpp:352
_network_join
NetworkJoinInfo _network_join
Information about the game to join to.
Definition: network_client.cpp:328
SM_JOIN_GAME
@ SM_JOIN_GAME
Join a network game.
Definition: openttd.h:41
ServerAddress::connection_string
std::string connection_string
The connection string for this ServerAddress.
Definition: address.h:210
NetworkServerGameInfo::grfconfig
GRFConfig * grfconfig
List of NewGRF files used.
Definition: network_game_info.h:97
CLIENT_ID_SERVER
@ CLIENT_ID_SERVER
Servers always have this ID.
Definition: network_type.h:51
_broadcast_list
NetworkAddressList _broadcast_list
List of broadcast addresses.
Definition: network.cpp:75
ClientNetworkGameSocketHandler::Send
static void Send()
Send the packets of this socket handler.
Definition: network_client.cpp:259
TCPQueryConnecter
Non blocking connection to query servers for their game info.
Definition: network.cpp:627
_current_text_dir
TextDirection _current_text_dir
Text direction of the currently selected language.
Definition: strings.cpp:56
_is_network_server
bool _is_network_server
Does this client wants to be a network-server?
Definition: network.cpp:63
NetworkErrorCode
NetworkErrorCode
The error codes we send around in the protocols.
Definition: network_type.h:122
NetworkClientInfo
Container for all information known about a client.
Definition: network_base.h:24
GenerateUid
std::string GenerateUid(std::string_view subject)
Generate an unique ID.
Definition: misc.cpp:69
_frame_counter_max
uint32_t _frame_counter_max
To where we may go with our clients.
Definition: network.cpp:72
_network_reconnect
uint8_t _network_reconnect
Reconnect timeout.
Definition: network.cpp:67
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:636
WL_CRITICAL
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:27
NetworkDistributeCommands
void NetworkDistributeCommands()
Distribute the commands of ourself and the clients.
Definition: network_command.cpp:410
NetworkSettings::network_id
std::string network_id
network ID for servers
Definition: settings_type.h:321
NetworkGameList::status
NetworkGameListStatus status
Stats of the server.
Definition: network_gamelist.h:32
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:54
CommandPacket::cmd
Commands cmd
command being executed.
Definition: network_internal.h:117
TimerGameEconomy::date
static Date date
Current date in days (day counter).
Definition: timer_game_economy.h:37
CHAR_TD_LRM
static const char32_t CHAR_TD_LRM
The next character acts like a left-to-right character.
Definition: string_type.h:35
IConsolePrint
void IConsolePrint(TextColour colour_code, const std::string &string)
Handle the printing of text entered into the console or redirected there by any other means.
Definition: console.cpp:91
HasBit
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103