OpenTTD Source  14.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 "../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 #ifdef DEBUG_DUMP_COMMANDS
41 # include "../fileio_func.h"
42 #endif
43 #include <charconv>
44 #include <sstream>
45 #include <iomanip>
46 
47 #include "../safeguards.h"
48 
49 #ifdef DEBUG_DUMP_COMMANDS
50 
55 bool _ddc_fastforward = true;
56 #endif /* DEBUG_DUMP_COMMANDS */
57 
60 
64 
79 uint32_t _frame_counter;
80 uint32_t _last_sync_frame;
82 uint32_t _sync_seed_1;
83 #ifdef NETWORK_SEND_DOUBLE_SEED
84 uint32_t _sync_seed_2;
85 #endif
86 uint32_t _sync_frame;
89 
91 
94 
95 extern std::string GenerateUid(std::string_view subject);
96 
102 {
103  return !NetworkClientSocket::Iterate().empty();
104 }
105 
110 {
111  /* Delete the chat window, if you were chatting with this client. */
113 }
114 
121 {
123  if (ci->client_id == client_id) return ci;
124  }
125 
126  return nullptr;
127 }
128 
135 {
136  for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
137  if (cs->client_id == client_id) return cs;
138  }
139 
140  return nullptr;
141 }
142 
143 byte NetworkSpectatorCount()
144 {
145  byte count = 0;
146 
147  for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
148  if (ci->client_playas == COMPANY_SPECTATOR) count++;
149  }
150 
151  /* Don't count a dedicated server as spectator */
152  if (_network_dedicated) count--;
153 
154  return count;
155 }
156 
163 std::string NetworkChangeCompanyPassword(CompanyID company_id, std::string password)
164 {
165  if (password.compare("*") == 0) password = "";
166 
167  if (_network_server) {
168  NetworkServerSetCompanyPassword(company_id, password, false);
169  } else {
171  }
172 
173  return password;
174 }
175 
183 std::string GenerateCompanyPasswordHash(const std::string &password, const std::string &password_server_id, uint32_t password_game_seed)
184 {
185  if (password.empty()) return password;
186 
187  size_t password_length = password.size();
188  size_t password_server_id_length = password_server_id.size();
189 
190  std::ostringstream salted_password;
191  /* Add the password with the server's ID and game seed as the salt. */
192  for (uint i = 0; i < NETWORK_SERVER_ID_LENGTH - 1; i++) {
193  char password_char = (i < password_length ? password[i] : 0);
194  char server_id_char = (i < password_server_id_length ? password_server_id[i] : 0);
195  char seed_char = password_game_seed >> (i % 32);
196  salted_password << (char)(password_char ^ server_id_char ^ seed_char); // Cast needed, otherwise interpreted as integer to format
197  }
198 
199  Md5 checksum;
200  MD5Hash digest;
201 
202  /* Generate the MD5 hash */
203  std::string salted_password_string = salted_password.str();
204  checksum.Append(salted_password_string.data(), salted_password_string.size());
205  checksum.Finish(digest);
206 
207  return FormatArrayAsHex(digest);
208 }
209 
216 {
217  return HasBit(_network_company_passworded, company_id);
218 }
219 
220 /* This puts a text-message to the console, or in the future, the chat-box,
221  * (to keep it all a bit more general)
222  * If 'self_send' is true, this is the client who is sending the message */
223 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)
224 {
225  StringID strid;
226  switch (action) {
227  case NETWORK_ACTION_SERVER_MESSAGE:
228  /* Ignore invalid messages */
229  strid = STR_NETWORK_SERVER_MESSAGE;
230  colour = CC_DEFAULT;
231  break;
232  case NETWORK_ACTION_COMPANY_SPECTATOR:
233  colour = CC_DEFAULT;
234  strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_SPECTATE;
235  break;
236  case NETWORK_ACTION_COMPANY_JOIN:
237  colour = CC_DEFAULT;
238  strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_JOIN;
239  break;
240  case NETWORK_ACTION_COMPANY_NEW:
241  colour = CC_DEFAULT;
242  strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_NEW;
243  break;
244  case NETWORK_ACTION_JOIN:
245  /* Show the Client ID for the server but not for the client. */
246  strid = _network_server ? STR_NETWORK_MESSAGE_CLIENT_JOINED_ID : STR_NETWORK_MESSAGE_CLIENT_JOINED;
247  break;
248  case NETWORK_ACTION_LEAVE: strid = STR_NETWORK_MESSAGE_CLIENT_LEFT; break;
249  case NETWORK_ACTION_NAME_CHANGE: strid = STR_NETWORK_MESSAGE_NAME_CHANGE; break;
250  case NETWORK_ACTION_GIVE_MONEY: strid = STR_NETWORK_MESSAGE_GIVE_MONEY; break;
251  case NETWORK_ACTION_CHAT_COMPANY: strid = self_send ? STR_NETWORK_CHAT_TO_COMPANY : STR_NETWORK_CHAT_COMPANY; break;
252  case NETWORK_ACTION_CHAT_CLIENT: strid = self_send ? STR_NETWORK_CHAT_TO_CLIENT : STR_NETWORK_CHAT_CLIENT; break;
253  case NETWORK_ACTION_KICKED: strid = STR_NETWORK_MESSAGE_KICKED; break;
254  case NETWORK_ACTION_EXTERNAL_CHAT: strid = STR_NETWORK_CHAT_EXTERNAL; break;
255  default: strid = STR_NETWORK_CHAT_ALL; break;
256  }
257 
258  SetDParamStr(0, name);
259  SetDParamStr(1, str);
260  SetDParam(2, data);
261  SetDParamStr(3, data_str);
262 
263  /* All of these strings start with "***". These characters are interpreted as both left-to-right and
264  * right-to-left characters depending on the context. As the next text might be an user's name, the
265  * user name's characters will influence the direction of the "***" instead of the language setting
266  * of the game. Manually set the direction of the "***" by inserting a text-direction marker. */
267  std::ostringstream stream;
268  std::ostreambuf_iterator<char> iterator(stream);
270  std::string message = stream.str() + GetString(strid);
271 
272  Debug(desync, 1, "msg: {:08x}; {:02x}; {}", TimerGameEconomy::date, TimerGameEconomy::date_fract, message);
273  IConsolePrint(colour, message);
275 }
276 
277 /* Calculate the frame-lag of a client */
278 uint NetworkCalculateLag(const NetworkClientSocket *cs)
279 {
280  int lag = cs->last_frame_server - cs->last_frame;
281  /* This client has missed their ACK packet after 1 DAY_TICKS..
282  * so we increase their lag for every frame that passes!
283  * The packet can be out by a max of _net_frame_freq */
284  if (cs->last_frame_server + Ticks::DAY_TICKS + _settings_client.network.frame_freq < _frame_counter) {
285  lag += _frame_counter - (cs->last_frame_server + Ticks::DAY_TICKS + _settings_client.network.frame_freq);
286  }
287  return lag;
288 }
289 
290 
291 /* There was a non-recoverable error, drop back to the main menu with a nice
292  * error */
293 void ShowNetworkError(StringID error_string)
294 {
297 }
298 
305 {
306  /* List of possible network errors, used by
307  * PACKET_SERVER_ERROR and PACKET_CLIENT_ERROR */
308  static const StringID network_error_strings[] = {
309  STR_NETWORK_ERROR_CLIENT_GENERAL,
310  STR_NETWORK_ERROR_CLIENT_DESYNC,
311  STR_NETWORK_ERROR_CLIENT_SAVEGAME,
312  STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST,
313  STR_NETWORK_ERROR_CLIENT_PROTOCOL_ERROR,
314  STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH,
315  STR_NETWORK_ERROR_CLIENT_NOT_AUTHORIZED,
316  STR_NETWORK_ERROR_CLIENT_NOT_EXPECTED,
317  STR_NETWORK_ERROR_CLIENT_WRONG_REVISION,
318  STR_NETWORK_ERROR_CLIENT_NAME_IN_USE,
319  STR_NETWORK_ERROR_CLIENT_WRONG_PASSWORD,
320  STR_NETWORK_ERROR_CLIENT_COMPANY_MISMATCH,
321  STR_NETWORK_ERROR_CLIENT_KICKED,
322  STR_NETWORK_ERROR_CLIENT_CHEATER,
323  STR_NETWORK_ERROR_CLIENT_SERVER_FULL,
324  STR_NETWORK_ERROR_CLIENT_TOO_MANY_COMMANDS,
325  STR_NETWORK_ERROR_CLIENT_TIMEOUT_PASSWORD,
326  STR_NETWORK_ERROR_CLIENT_TIMEOUT_COMPUTER,
327  STR_NETWORK_ERROR_CLIENT_TIMEOUT_MAP,
328  STR_NETWORK_ERROR_CLIENT_TIMEOUT_JOIN,
329  STR_NETWORK_ERROR_CLIENT_INVALID_CLIENT_NAME,
330  };
331  static_assert(lengthof(network_error_strings) == NETWORK_ERROR_END);
332 
333  if (err >= (ptrdiff_t)lengthof(network_error_strings)) err = NETWORK_ERROR_GENERAL;
334 
335  return network_error_strings[err];
336 }
337 
343 void NetworkHandlePauseChange(PauseMode prev_mode, PauseMode changed_mode)
344 {
345  if (!_networking) return;
346 
347  switch (changed_mode) {
348  case PM_PAUSED_NORMAL:
349  case PM_PAUSED_JOIN:
352  case PM_PAUSED_LINK_GRAPH: {
353  bool changed = ((_pause_mode == PM_UNPAUSED) != (prev_mode == PM_UNPAUSED));
354  bool paused = (_pause_mode != PM_UNPAUSED);
355  if (!paused && !changed) return;
356 
357  StringID str;
358  if (!changed) {
359  int i = -1;
360 
361  if ((_pause_mode & PM_PAUSED_NORMAL) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_MANUAL);
362  if ((_pause_mode & PM_PAUSED_JOIN) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_CONNECTING_CLIENTS);
363  if ((_pause_mode & PM_PAUSED_GAME_SCRIPT) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_GAME_SCRIPT);
364  if ((_pause_mode & PM_PAUSED_ACTIVE_CLIENTS) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_NOT_ENOUGH_PLAYERS);
365  if ((_pause_mode & PM_PAUSED_LINK_GRAPH) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_LINK_GRAPH);
366  str = STR_NETWORK_SERVER_MESSAGE_GAME_STILL_PAUSED_1 + i;
367  } else {
368  switch (changed_mode) {
369  case PM_PAUSED_NORMAL: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_MANUAL); break;
370  case PM_PAUSED_JOIN: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_CONNECTING_CLIENTS); break;
371  case PM_PAUSED_GAME_SCRIPT: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_GAME_SCRIPT); break;
372  case PM_PAUSED_ACTIVE_CLIENTS: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_NOT_ENOUGH_PLAYERS); break;
373  case PM_PAUSED_LINK_GRAPH: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_LINK_GRAPH); break;
374  default: NOT_REACHED();
375  }
376  str = paused ? STR_NETWORK_SERVER_MESSAGE_GAME_PAUSED : STR_NETWORK_SERVER_MESSAGE_GAME_UNPAUSED;
377  }
378 
379  NetworkTextMessage(NETWORK_ACTION_SERVER_MESSAGE, CC_DEFAULT, false, "", GetString(str));
380  break;
381  }
382 
383  default:
384  return;
385  }
386 }
387 
388 
397 static void CheckPauseHelper(bool pause, PauseMode pm)
398 {
399  if (pause == ((_pause_mode & pm) != PM_UNPAUSED)) return;
400 
401  Command<CMD_PAUSE>::Post(pm, pause);
402 }
403 
410 {
411  uint count = 0;
412 
413  for (const NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
414  if (cs->status != NetworkClientSocket::STATUS_ACTIVE) continue;
415  if (!Company::IsValidID(cs->GetInfo()->client_playas)) continue;
416  count++;
417  }
418 
419  return count;
420 }
421 
426 {
430  return;
431  }
433 }
434 
440 {
441  for (const NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
442  if (cs->status >= NetworkClientSocket::STATUS_AUTHORIZED && cs->status < NetworkClientSocket::STATUS_ACTIVE) return true;
443  }
444 
445  return false;
446 }
447 
451 static void CheckPauseOnJoin()
452 {
455  return;
456  }
458 }
459 
466 std::string_view ParseCompanyFromConnectionString(const std::string &connection_string, CompanyID *company_id)
467 {
468  std::string_view ip = connection_string;
469  if (company_id == nullptr) return ip;
470 
471  size_t offset = ip.find_last_of('#');
472  if (offset != std::string::npos) {
473  std::string_view company_string = ip.substr(offset + 1);
474  ip = ip.substr(0, offset);
475 
476  uint8_t company_value;
477  auto [_, err] = std::from_chars(company_string.data(), company_string.data() + company_string.size(), company_value);
478  if (err == std::errc()) {
479  if (company_value != COMPANY_NEW_COMPANY && company_value != COMPANY_SPECTATOR) {
480  if (company_value > MAX_COMPANIES || company_value == 0) {
481  *company_id = COMPANY_SPECTATOR;
482  } else {
483  /* "#1" means the first company, which has index 0. */
484  *company_id = (CompanyID)(company_value - 1);
485  }
486  } else {
487  *company_id = (CompanyID)company_value;
488  }
489  }
490  }
491 
492  return ip;
493 }
494 
510 std::string_view ParseFullConnectionString(const std::string &connection_string, uint16_t &port, CompanyID *company_id)
511 {
512  std::string_view ip = ParseCompanyFromConnectionString(connection_string, company_id);
513 
514  size_t port_offset = ip.find_last_of(':');
515  size_t ipv6_close = ip.find_last_of(']');
516  if (port_offset != std::string::npos && (ipv6_close == std::string::npos || ipv6_close < port_offset)) {
517  std::string_view port_string = ip.substr(port_offset + 1);
518  ip = ip.substr(0, port_offset);
519  std::from_chars(port_string.data(), port_string.data() + port_string.size(), port);
520  }
521  return ip;
522 }
523 
530 std::string NormalizeConnectionString(const std::string &connection_string, uint16_t default_port)
531 {
532  uint16_t port = default_port;
533  std::string_view ip = ParseFullConnectionString(connection_string, port);
534  return std::string(ip) + ":" + std::to_string(port);
535 }
536 
545 NetworkAddress ParseConnectionString(const std::string &connection_string, uint16_t default_port)
546 {
547  uint16_t port = default_port;
548  std::string_view ip = ParseFullConnectionString(connection_string, port);
549  return NetworkAddress(ip, port);
550 }
551 
557 /* static */ void ServerNetworkGameSocketHandler::AcceptConnection(SOCKET s, const NetworkAddress &address)
558 {
559  /* Register the login */
561 
563  cs->client_address = address; // Save the IP of the client
564 
566 }
567 
572 static void InitializeNetworkPools(bool close_admins = true)
573 {
574  PoolBase::Clean(PT_NCLIENT | (close_admins ? PT_NADMIN : PT_NONE));
575 }
576 
581 void NetworkClose(bool close_admins)
582 {
583  if (_network_server) {
584  if (close_admins) {
586  as->CloseConnection(true);
587  }
588  }
589 
590  for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
591  cs->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT);
592  }
595 
597  } else {
598  if (MyClient::my_client != nullptr) {
601  }
602 
604  }
605  NetworkGameSocketHandler::ProcessDeferredDeletions();
606 
608 
609  _networking = false;
610  _network_server = false;
611 
613 
614  delete[] _network_company_states;
615  _network_company_states = nullptr;
617 
618  InitializeNetworkPools(close_admins);
619 }
620 
621 /* Initializes the network (cleans sockets and stuff) */
622 static void NetworkInitialize(bool close_admins = true)
623 {
624  InitializeNetworkPools(close_admins);
625 
626  _sync_frame = 0;
627  _network_first_time = true;
628 
629  _network_reconnect = 0;
630 }
631 
634 private:
635  std::string connection_string;
636 
637 public:
638  TCPQueryConnecter(const std::string &connection_string) : TCPServerConnecter(connection_string, NETWORK_DEFAULT_PORT), connection_string(connection_string) {}
639 
640  void OnFailure() override
641  {
642  Debug(net, 9, "Query::OnFailure(): connection_string={}", this->connection_string);
643 
644  NetworkGameList *item = NetworkGameListAddItem(connection_string);
645  item->status = NGLS_OFFLINE;
646  item->refreshing = false;
647 
649  }
650 
651  void OnConnect(SOCKET s) override
652  {
653  Debug(net, 9, "Query::OnConnect(): connection_string={}", this->connection_string);
654 
655  QueryNetworkGameSocketHandler::QueryServer(s, this->connection_string);
656  }
657 };
658 
663 void NetworkQueryServer(const std::string &connection_string)
664 {
665  if (!_network_available) return;
666 
667  Debug(net, 9, "NetworkQueryServer(): connection_string={}", connection_string);
668 
669  /* Mark the entry as refreshing, so the GUI can show the refresh is pending. */
670  NetworkGameList *item = NetworkGameListAddItem(connection_string);
671  item->refreshing = true;
672 
673  TCPConnecter::Create<TCPQueryConnecter>(connection_string);
674 }
675 
685 NetworkGameList *NetworkAddServer(const std::string &connection_string, bool manually, bool never_expire)
686 {
687  if (connection_string.empty()) return nullptr;
688 
689  /* Ensure the item already exists in the list */
690  NetworkGameList *item = NetworkGameListAddItem(connection_string);
691  if (item->info.server_name.empty()) {
693  item->info.server_name = connection_string;
694 
696 
697  NetworkQueryServer(connection_string);
698  }
699 
700  if (manually) item->manually = true;
701  if (never_expire) item->version = INT32_MAX;
702 
703  return item;
704 }
705 
711 void GetBindAddresses(NetworkAddressList *addresses, uint16_t port)
712 {
713  for (const auto &iter : _network_bind_list) {
714  addresses->emplace_back(iter.c_str(), port);
715  }
716 
717  /* No address, so bind to everything. */
718  if (addresses->empty()) {
719  addresses->emplace_back("", port);
720  }
721 }
722 
723 /* Generates the list of manually added hosts from NetworkGameList and
724  * dumps them into the array _network_host_list. This array is needed
725  * by the function that generates the config file. */
726 void NetworkRebuildHostList()
727 {
728  _network_host_list.clear();
729 
730  for (NetworkGameList *item = _network_game_list; item != nullptr; item = item->next) {
731  if (item->manually) _network_host_list.emplace_back(item->connection_string);
732  }
733 }
734 
737 private:
738  std::string connection_string;
739 
740 public:
741  TCPClientConnecter(const std::string &connection_string) : TCPServerConnecter(connection_string, NETWORK_DEFAULT_PORT), connection_string(connection_string) {}
742 
743  void OnFailure() override
744  {
745  Debug(net, 9, "Client::OnFailure(): connection_string={}", this->connection_string);
746 
747  ShowNetworkError(STR_NETWORK_ERROR_NOCONNECTION);
748  }
749 
750  void OnConnect(SOCKET s) override
751  {
752  Debug(net, 9, "Client::OnConnect(): connection_string={}", this->connection_string);
753 
754  _networking = true;
756  new ClientNetworkGameSocketHandler(s, this->connection_string);
757  IConsoleCmdExec("exec scripts/on_client.scr 0");
759  }
760 };
761 
779 bool NetworkClientConnectGame(const std::string &connection_string, CompanyID default_company, const std::string &join_server_password, const std::string &join_company_password)
780 {
781  Debug(net, 9, "NetworkClientConnectGame(): connection_string={}", connection_string);
782 
783  CompanyID join_as = default_company;
784  std::string resolved_connection_string = ServerAddress::Parse(connection_string, NETWORK_DEFAULT_PORT, &join_as).connection_string;
785 
786  if (!_network_available) return false;
787  if (!NetworkValidateOurClientName()) return false;
788 
789  _network_join.connection_string = resolved_connection_string;
790  _network_join.company = join_as;
791  _network_join.server_password = join_server_password;
792  _network_join.company_password = join_company_password;
793 
794  if (_game_mode == GM_MENU) {
795  /* From the menu we can immediately continue with the actual join. */
797  } else {
798  /* When already playing a game, first go back to the main menu. This
799  * disconnects the user from the current game, meaning we can safely
800  * load in the new. After all, there is little point in continueing to
801  * play on a server if we are connecting to another one.
802  */
804  }
805  return true;
806 }
807 
814 {
816  NetworkInitialize();
817 
819  Debug(net, 9, "status = CONNECTING");
820  _network_join_status = NETWORK_JOIN_STATUS_CONNECTING;
821  ShowJoinStatusWindow();
822 
823  TCPConnecter::Create<TCPClientConnecter>(_network_join.connection_string);
824 }
825 
826 static void NetworkInitGameInfo()
827 {
828  FillStaticNetworkServerGameInfo();
829  /* The server is a client too */
830  _network_game_info.clients_on = _network_dedicated ? 0 : 1;
831 
832  /* There should be always space for the server. */
836 
838 }
839 
850 bool NetworkValidateServerName(std::string &server_name)
851 {
852  StrTrimInPlace(server_name);
853  if (!server_name.empty()) return true;
854 
855  ShowErrorMessage(STR_NETWORK_ERROR_BAD_SERVER_NAME, INVALID_STRING_ID, WL_ERROR);
856  return false;
857 }
858 
866 {
867  static const std::string fallback_client_name = "Unnamed Client";
869  if (_settings_client.network.client_name.empty() || _settings_client.network.client_name.compare(fallback_client_name) == 0) {
870  Debug(net, 1, "No \"client_name\" has been set, using \"{}\" instead. Please set this now using the \"name <new name>\" command", fallback_client_name);
871  _settings_client.network.client_name = fallback_client_name;
872  }
873 
874  static const std::string fallback_server_name = "Unnamed Server";
876  if (_settings_client.network.server_name.empty() || _settings_client.network.server_name.compare(fallback_server_name) == 0) {
877  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);
878  _settings_client.network.server_name = fallback_server_name;
879  }
880 }
881 
882 bool NetworkServerStart()
883 {
884  if (!_network_available) return false;
885 
886  /* Call the pre-scripts */
887  IConsoleCmdExec("exec scripts/pre_server.scr 0");
888  if (_network_dedicated) IConsoleCmdExec("exec scripts/pre_dedicated.scr 0");
889 
890  /* Check for the client and server names to be set, but only after the scripts had a chance to set them.*/
892 
893  NetworkDisconnect(false);
894  NetworkInitialize(false);
896  Debug(net, 5, "Starting listeners for clients");
898 
899  /* Only listen for admins when the password isn't empty. */
900  if (!_settings_client.network.admin_password.empty()) {
901  Debug(net, 5, "Starting listeners for admins");
903  }
904 
905  /* Try to start UDP-server */
906  Debug(net, 5, "Starting listeners for incoming server queries");
908 
910  _network_server = true;
911  _networking = true;
912  _frame_counter = 0;
914  _frame_counter_max = 0;
915  _last_sync_frame = 0;
917 
920 
921  NetworkInitGameInfo();
922 
923  if (_settings_client.network.server_game_type != SERVER_GAME_TYPE_LOCAL) {
925  }
926 
927  /* execute server initialization script */
928  IConsoleCmdExec("exec scripts/on_server.scr 0");
929  /* if the server is dedicated ... add some other script */
930  if (_network_dedicated) IConsoleCmdExec("exec scripts/on_dedicated.scr 0");
931 
932  /* welcome possibly still connected admins - this can only happen on a dedicated server. */
934 
935  return true;
936 }
937 
938 /* The server is rebooting...
939  * The only difference with NetworkDisconnect, is the packets that is sent */
940 void NetworkReboot()
941 {
942  if (_network_server) {
943  for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
944  cs->SendNewGame();
945  cs->SendPackets();
946  }
947 
949  as->SendNewGame();
950  as->SendPackets();
951  }
952  }
953 
954  /* For non-dedicated servers we have to kick the admins as we are not
955  * certain that we will end up in a new network game. */
957 }
958 
963 void NetworkDisconnect(bool close_admins)
964 {
965  if (_network_server) {
966  for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
967  cs->SendShutdown();
968  cs->SendPackets();
969  }
970 
971  if (close_admins) {
973  as->SendShutdown();
974  as->SendPackets();
975  }
976  }
977  }
978 
980 
981  NetworkClose(close_admins);
982 
983  /* Reinitialize the UDP stack, i.e. close all existing connections. */
985 }
986 
992 {
993  if (!_networking) return;
994 
996  case SERVER_GAME_TYPE_LOCAL:
998  break;
999 
1000  case SERVER_GAME_TYPE_INVITE_ONLY:
1001  case SERVER_GAME_TYPE_PUBLIC:
1003  break;
1004 
1005  default:
1006  NOT_REACHED();
1007  }
1008 }
1009 
1014 static bool NetworkReceive()
1015 {
1016  bool result;
1017  if (_network_server) {
1020  } else {
1022  }
1023  NetworkGameSocketHandler::ProcessDeferredDeletions();
1024  return result;
1025 }
1026 
1027 /* This sends all buffered commands (if possible) */
1028 static void NetworkSend()
1029 {
1030  if (_network_server) {
1033  } else {
1035  }
1036  NetworkGameSocketHandler::ProcessDeferredDeletions();
1037 }
1038 
1045 {
1051  NetworkGameSocketHandler::ProcessDeferredDeletions();
1052 
1054 }
1055 
1056 /* The main loop called from ttd.c
1057  * Here we also have to do StateGameLoop if needed! */
1058 void NetworkGameLoop()
1059 {
1060  if (!_networking) return;
1061 
1062  if (!NetworkReceive()) return;
1063 
1064  if (_network_server) {
1065  /* Log the sync state to check for in-syncedness of replays. */
1066  if (TimerGameEconomy::date_fract == 0) {
1067  /* We don't want to log multiple times if paused. */
1068  static TimerGameEconomy::Date last_log;
1069  if (last_log != TimerGameEconomy::date) {
1070  Debug(desync, 1, "sync: {:08x}; {:02x}; {:08x}; {:08x}", TimerGameEconomy::date, TimerGameEconomy::date_fract, _random.state[0], _random.state[1]);
1071  last_log = TimerGameEconomy::date;
1072  }
1073  }
1074 
1075 #ifdef DEBUG_DUMP_COMMANDS
1076  /* Loading of the debug commands from -ddesync>=1 */
1077  static FILE *f = FioFOpenFile("commands.log", "rb", SAVE_DIR);
1078  static TimerGameEconomy::Date next_date(0);
1079  static uint32_t next_date_fract;
1080  static CommandPacket *cp = nullptr;
1081  static bool check_sync_state = false;
1082  static uint32_t sync_state[2];
1083  if (f == nullptr && next_date == 0) {
1084  Debug(desync, 0, "Cannot open commands.log");
1085  next_date = TimerGameEconomy::Date(1);
1086  }
1087 
1088  while (f != nullptr && !feof(f)) {
1089  if (TimerGameEconomy::date == next_date && TimerGameEconomy::date_fract == next_date_fract) {
1090  if (cp != nullptr) {
1091  NetworkSendCommand(cp->cmd, cp->err_msg, nullptr, cp->company, cp->data);
1092  Debug(desync, 0, "Injecting: {:08x}; {:02x}; {:02x}; {:08x}; {} ({})", TimerGameEconomy::date, TimerGameEconomy::date_fract, (int)_current_company, cp->cmd, FormatArrayAsHex(cp->data), GetCommandName(cp->cmd));
1093  delete cp;
1094  cp = nullptr;
1095  }
1096  if (check_sync_state) {
1097  if (sync_state[0] == _random.state[0] && sync_state[1] == _random.state[1]) {
1098  Debug(desync, 0, "Sync check: {:08x}; {:02x}; match", TimerGameEconomy::date, TimerGameEconomy::date_fract);
1099  } else {
1100  Debug(desync, 0, "Sync check: {:08x}; {:02x}; mismatch expected {{{:08x}, {:08x}}}, got {{{:08x}, {:08x}}}",
1101  TimerGameEconomy::date, TimerGameEconomy::date_fract, sync_state[0], sync_state[1], _random.state[0], _random.state[1]);
1102  NOT_REACHED();
1103  }
1104  check_sync_state = false;
1105  }
1106  }
1107 
1108  /* Skip all entries in the command-log till we caught up with the current game again. */
1109  if (TimerGameEconomy::date > next_date || (TimerGameEconomy::date == next_date && TimerGameEconomy::date_fract > next_date_fract)) {
1110  Debug(desync, 0, "Skipping to next command at {:08x}:{:02x}", next_date, next_date_fract);
1111  if (cp != nullptr) {
1112  delete cp;
1113  cp = nullptr;
1114  }
1115  check_sync_state = false;
1116  }
1117 
1118  if (cp != nullptr || check_sync_state) break;
1119 
1120  char buff[4096];
1121  if (fgets(buff, lengthof(buff), f) == nullptr) break;
1122 
1123  char *p = buff;
1124  /* Ignore the "[date time] " part of the message */
1125  if (*p == '[') {
1126  p = strchr(p, ']');
1127  if (p == nullptr) break;
1128  p += 2;
1129  }
1130 
1131  if (strncmp(p, "cmd: ", 5) == 0
1132 #ifdef DEBUG_FAILED_DUMP_COMMANDS
1133  || strncmp(p, "cmdf: ", 6) == 0
1134 #endif
1135  ) {
1136  p += 5;
1137  if (*p == ' ') p++;
1138  cp = new CommandPacket();
1139  int company;
1140  uint cmd;
1141  char buffer[256];
1142  uint32_t next_date_raw;
1143  int ret = sscanf(p, "%x; %x; %x; %x; %x; %255s", &next_date_raw, &next_date_fract, &company, &cmd, &cp->err_msg, buffer);
1144  assert(ret == 6);
1145  next_date = TimerGameEconomy::Date((int32_t)next_date_raw);
1146  cp->company = (CompanyID)company;
1147  cp->cmd = (Commands)cmd;
1148 
1149  /* Parse command data. */
1150  std::vector<byte> args;
1151  size_t arg_len = strlen(buffer);
1152  for (size_t i = 0; i + 1 < arg_len; i += 2) {
1153  byte e = 0;
1154  std::from_chars(buffer + i, buffer + i + 2, e, 16);
1155  args.emplace_back(e);
1156  }
1157  cp->data = args;
1158  } else if (strncmp(p, "join: ", 6) == 0) {
1159  /* Manually insert a pause when joining; this way the client can join at the exact right time. */
1160  uint32_t next_date_raw;
1161  int ret = sscanf(p + 6, "%x; %x", &next_date_raw, &next_date_fract);
1162  next_date = TimerGameEconomy::Date((int32_t)next_date_raw);
1163  assert(ret == 2);
1164  Debug(desync, 0, "Injecting pause for join at {:08x}:{:02x}; please join when paused", next_date, next_date_fract);
1165  cp = new CommandPacket();
1166  cp->company = COMPANY_SPECTATOR;
1167  cp->cmd = CMD_PAUSE;
1169  _ddc_fastforward = false;
1170  } else if (strncmp(p, "sync: ", 6) == 0) {
1171  uint32_t next_date_raw;
1172  int ret = sscanf(p + 6, "%x; %x; %x; %x", &next_date_raw, &next_date_fract, &sync_state[0], &sync_state[1]);
1173  next_date = TimerGameEconomy::Date((int32_t)next_date_raw);
1174  assert(ret == 4);
1175  check_sync_state = true;
1176  } else if (strncmp(p, "msg: ", 5) == 0 || strncmp(p, "client: ", 8) == 0 ||
1177  strncmp(p, "load: ", 6) == 0 || strncmp(p, "save: ", 6) == 0 ||
1178  strncmp(p, "warning: ", 9) == 0) {
1179  /* A message that is not very important to the log playback, but part of the log. */
1180 #ifndef DEBUG_FAILED_DUMP_COMMANDS
1181  } else if (strncmp(p, "cmdf: ", 6) == 0) {
1182  Debug(desync, 0, "Skipping replay of failed command: {}", p + 6);
1183 #endif
1184  } else {
1185  /* Can't parse a line; what's wrong here? */
1186  Debug(desync, 0, "Trying to parse: {}", p);
1187  NOT_REACHED();
1188  }
1189  }
1190  if (f != nullptr && feof(f)) {
1191  Debug(desync, 0, "End of commands.log");
1192  fclose(f);
1193  f = nullptr;
1194  }
1195 #endif /* DEBUG_DUMP_COMMANDS */
1197  /* Only check for active clients just before we're going to send out
1198  * the commands so we don't send multiple pause/unpause commands when
1199  * the frame_freq is more than 1 tick. Same with distributing commands. */
1200  CheckPauseOnJoin();
1203  }
1204 
1205  bool send_frame = false;
1206 
1207  /* We first increase the _frame_counter */
1208  _frame_counter++;
1209  /* Update max-frame-counter */
1212  send_frame = true;
1213  }
1214 
1216 
1217  /* Then we make the frame */
1218  StateGameLoop();
1219 
1220  _sync_seed_1 = _random.state[0];
1221 #ifdef NETWORK_SEND_DOUBLE_SEED
1222  _sync_seed_2 = _random.state[1];
1223 #endif
1224 
1225  NetworkServer_Tick(send_frame);
1226  } else {
1227  /* Client */
1228 
1229  /* Make sure we are at the frame were the server is (quick-frames) */
1231  /* Run a number of frames; when things go bad, get out. */
1234  }
1235  } else {
1236  /* Else, keep on going till _frame_counter_max */
1238  /* Run one frame; if things went bad, get out. */
1240  }
1241  }
1242  }
1243 
1244  NetworkSend();
1245 }
1246 
1247 static void NetworkGenerateServerId()
1248 {
1249  _settings_client.network.network_id = GenerateUid("OpenTTD Server ID");
1250 }
1251 
1254 {
1255  Debug(net, 3, "Starting network");
1256 
1257  /* Network is available */
1259  _network_dedicated = false;
1260 
1261  /* Generate an server id when there is none yet */
1262  if (_settings_client.network.network_id.empty()) NetworkGenerateServerId();
1263 
1264  _network_game_info = {};
1265 
1266  NetworkInitialize();
1268  Debug(net, 3, "Network online, multiplayer available");
1271 }
1272 
1275 {
1278  NetworkUDPClose();
1279 
1280  Debug(net, 3, "Shutting down network");
1281 
1282  _network_available = false;
1283 
1285 }
1286 
1287 #ifdef __EMSCRIPTEN__
1288 extern "C" {
1289 
1290 void CDECL em_openttd_add_server(const char *connection_string)
1291 {
1292  NetworkAddServer(connection_string, false, true);
1293 }
1294 
1295 }
1296 #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:850
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:3204
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:823
NetworkValidateOurClientName
bool NetworkValidateOurClientName()
Convenience method for NetworkValidateClientName on _settings_client.network.client_name.
Definition: network_client.cpp:1346
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:685
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:530
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:711
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:66
_network_company_passworded
CompanyMask _network_company_passworded
Bitmask of the password status of all companies.
Definition: network.cpp:88
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:973
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:268
TCPQueryConnecter::OnFailure
void OnFailure() override
Callback for when the connection attempt failed.
Definition: network.cpp:640
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:439
CommandPacket::err_msg
StringID err_msg
string ID of error message to use.
Definition: network_internal.h:103
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:343
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:74
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:1044
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:304
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:72
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:161
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:87
NetworkServer_Tick
void NetworkServer_Tick(bool send_frame)
This is called every tick if this is a _network_server.
Definition: network_server.cpp:1711
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:109
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:163
NetworkQueryServer
void NetworkQueryServer(const std::string &connection_string)
Query a server to fetch the game-info.
Definition: network.cpp:663
PM_UNPAUSED
@ PM_UNPAUSED
A normal unpaused game.
Definition: openttd.h:69
HasClients
bool HasClients()
Return whether there is any client connected or trying to connect at all.
Definition: network.cpp:101
network_coordinator.h
_sync_seed_1
uint32_t _sync_seed_1
Seed to compare during sync checks.
Definition: network.cpp:82
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:120
NetworkClientJoinGame
void NetworkClientJoinGame()
Actually perform the joining to the server.
Definition: network.cpp:813
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:98
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:545
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:301
CommandPacket
Everything we need to know about a command to be able to execute it.
Definition: network_internal.h:96
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:264
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:80
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:49
NetworkClient_Connected
void NetworkClient_Connected()
Is called after a client is connected to the server.
Definition: network_client.cpp:1248
TCPClientConnecter::OnFailure
void OnFailure() override
Callback for when the connection attempt failed.
Definition: network.cpp:743
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:736
NetworkSettings::client_name
std::string client_name
name of the player (as client)
Definition: settings_type.h:318
lengthof
#define lengthof(array)
Return the length of an fixed size array.
Definition: stdafx.h:303
InitializeNetworkPools
static void InitializeNetworkPools(bool close_admins=true)
Resets the pools used for network clients, and the admin pool if needed.
Definition: network.cpp:572
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:1274
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:70
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:65
CheckPauseHelper
static void CheckPauseHelper(bool pause, PauseMode pm)
Helper function for the pause checkers.
Definition: network.cpp:397
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:865
ServerNetworkGameSocketHandler::GetByClientID
static ServerNetworkGameSocketHandler * GetByClientID(ClientID client_id)
Return the client state given it's client-identifier.
Definition: network.cpp:134
network_client.h
PauseMode
PauseMode
Modes of pausing we've got.
Definition: openttd.h:68
network_server.h
_network_dedicated
bool _network_dedicated
are we a dedicated server?
Definition: network.cpp:68
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:75
ServerNetworkGameSocketHandler::AcceptConnection
static void AcceptConnection(SOCKET s, const NetworkAddress &address)
Handle the accepting of a connection to the server.
Definition: network.cpp:557
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:466
NetworkCompanyIsPassworded
bool NetworkCompanyIsPassworded(CompanyID company_id)
Check if the company we want to join requires a password.
Definition: network.cpp:215
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:963
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:71
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:243
_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:74
_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:77
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:51
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:388
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:196
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:1393
_frame_counter
uint32_t _frame_counter
The current frame.
Definition: network.cpp:79
CommandPacket::data
CommandDataBuffer data
command parameters.
Definition: network_internal.h:105
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:451
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:93
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:70
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:309
NetworkCountActiveClients
static uint NetworkCountActiveClients()
Counts the number of active clients connected.
Definition: network.cpp:409
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:76
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:237
PM_PAUSED_JOIN
@ PM_PAUSED_JOIN
A game paused for 'pause_on_join'.
Definition: openttd.h:72
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:425
NetworkGameSocketHandler::client_id
ClientID client_id
Client identifier.
Definition: tcp_game.h:496
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:779
NGLS_OFFLINE
@ NGLS_OFFLINE
Server is offline (or cannot be queried).
Definition: network_gamelist.h:19
_network_ban_list
StringList _network_ban_list
The banned clients.
Definition: network.cpp:76
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:636
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:581
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:510
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:86
ServerNetworkGameSocketHandler::ServerNetworkGameSocketHandler
ServerNetworkGameSocketHandler(SOCKET s)
Create a new socket for the server side of the game connection.
Definition: network_server.cpp:188
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:991
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:183
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:245
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:511
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:75
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:328
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:1434
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:1253
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:75
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:67
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:1014
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:1684
PM_PAUSED_ERROR
@ PM_PAUSED_ERROR
A game paused because a (critical) error.
Definition: openttd.h:73
NetworkFreeLocalCommandQueue
void NetworkFreeLocalCommandQueue()
Free the local command queues.
Definition: network_command.cpp:279
_network_join
NetworkJoinInfo _network_join
Information about the game to join to.
Definition: network_client.cpp:327
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:81
ClientNetworkGameSocketHandler::Send
static void Send()
Send the packets of this socket handler.
Definition: network_client.cpp:258
TCPQueryConnecter
Non blocking connection to query servers for their game info.
Definition: network.cpp:633
_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:69
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:67
_frame_counter_max
uint32_t _frame_counter_max
To where we may go with our clients.
Definition: network.cpp:78
_network_reconnect
uint8_t _network_reconnect
Reconnect timeout.
Definition: network.cpp:73
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:635
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:346
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:102
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