OpenTTD Source 20261112-master-gbcbec5e63f
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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "../stdafx.h"
11
12#include "../command_func.h"
13#include "../string_func.h"
14#include "../strings_func.h"
17#include "network_admin.h"
18#include "network_client.h"
19#include "network_query.h"
20#include "network_server.h"
21#include "network_content.h"
22#include "network_udp.h"
23#include "network_gamelist.h"
24#include "network_base.h"
25#include "network_coordinator.h"
26#include "core/host.h"
27#include "network_gui.h"
28#include "../console_func.h"
30#include "../window_func.h"
31#include "../company_func.h"
32#include "../company_base.h"
33#include "../core/pool_func.hpp"
34#include "../error.h"
35#include "../misc_cmd.h"
37#ifdef DEBUG_DUMP_COMMANDS
38# include "../fileio_func.h"
40#endif
41#include <charconv>
42
43#include "table/strings.h"
44
45#include "../safeguards.h"
46
47#ifdef DEBUG_DUMP_COMMANDS
53bool _ddc_fastforward = true;
54#endif /* DEBUG_DUMP_COMMANDS */
55
58
62
79uint32_t _sync_seed_1;
80#ifdef NETWORK_SEND_DOUBLE_SEED
81uint32_t _sync_seed_2;
82#endif
83uint32_t _sync_frame;
85
88
89extern std::string GenerateUid(std::string_view subject);
90
96{
97 return !NetworkClientSocket::Iterate().empty();
98}
99
104{
105 /* Delete the chat window, if you were chatting with this client. */
106 InvalidateWindowData(WindowClass::NetworkChat, NetworkChatDestinationType::Client, this->client_id);
107}
108
115{
117 if (ci->client_id == client_id) return ci;
118 }
119
120 return nullptr;
121}
122
128bool NetworkClientInfo::CanJoinCompany(CompanyID company_id) const
129{
130 Company *c = Company::GetIfValid(company_id);
131 return c != nullptr && (c->allow_any || this->client_id == ClientID::Server || c->allow_list.Contains(this->public_key));
132}
133
139bool NetworkCanJoinCompany(CompanyID company_id)
140{
142 return info != nullptr && info->CanJoinCompany(company_id);
143}
144
151{
153 if (cs->client_id == client_id) return cs;
154 }
155
156 return nullptr;
157}
158
159
166static auto FindKey(auto *authorized_keys, std::string_view authorized_key)
167{
168 return std::ranges::find_if(*authorized_keys, [authorized_key](auto &value) { return StrEqualsIgnoreCase(value, authorized_key); });
169}
170
176bool NetworkAuthorizedKeys::Contains(std::string_view key) const
177{
178 return FindKey(this, key) != this->end();
179}
180
186bool NetworkAuthorizedKeys::Add(std::string_view key)
187{
188 if (key.empty()) return false;
189
190 auto iter = FindKey(this, key);
191 if (iter != this->end()) return false;
192
193 this->emplace_back(key);
194 return true;
195}
196
202bool NetworkAuthorizedKeys::Remove(std::string_view key)
203{
204 auto iter = FindKey(this, key);
205 if (iter == this->end()) return false;
206
207 this->erase(iter);
208 return true;
209}
210
211
217{
218 uint8_t count = 0;
219
221 if (ci->client_playas == COMPANY_SPECTATOR) count++;
222 }
223
224 /* Don't count a dedicated server as spectator */
225 if (_network_dedicated) count--;
226
227 return count;
228}
229
230
240void NetworkTextMessage(NetworkAction action, ExtendedTextColour colour, bool self_send, std::string_view name, std::string_view str, StringParameter &&data)
241{
242 std::string message;
243 StringBuilder builder(message);
244
245 /* All of these strings start with "***". These characters are interpreted as both left-to-right and
246 * right-to-left characters depending on the context. As the next text might be an user's name, the
247 * user name's characters will influence the direction of the "***" instead of the language setting
248 * of the game. Manually set the direction of the "***" by inserting a text-direction marker. */
250
251 switch (action) {
253 /* Ignore invalid messages */
254 builder += GetString(STR_NETWORK_SERVER_MESSAGE, str);
255 colour = CC_DEFAULT;
256 break;
258 colour = CC_DEFAULT;
259 builder += GetString(STR_NETWORK_MESSAGE_CLIENT_COMPANY_SPECTATE, name);
260 break;
262 colour = CC_DEFAULT;
263 builder += GetString(STR_NETWORK_MESSAGE_CLIENT_COMPANY_JOIN, name, str);
264 break;
266 colour = CC_DEFAULT;
267 builder += GetString(STR_NETWORK_MESSAGE_CLIENT_COMPANY_NEW, name, std::move(data));
268 break;
270 /* Show the Client ID for the server but not for the client. */
271 builder += _network_server ?
272 GetString(STR_NETWORK_MESSAGE_CLIENT_JOINED_ID, name, std::move(data)) :
273 GetString(STR_NETWORK_MESSAGE_CLIENT_JOINED, name);
274 break;
275 case NetworkAction::ClientLeave: builder += GetString(STR_NETWORK_MESSAGE_CLIENT_LEFT, name, std::move(data)); break;
276 case NetworkAction::ClientNameChange:builder += GetString(STR_NETWORK_MESSAGE_NAME_CHANGE, name, str); break;
277 case NetworkAction::GiveMoney: builder += GetString(STR_NETWORK_MESSAGE_GIVE_MONEY, name, std::move(data), str); break;
278 case NetworkAction::ClientKicked: builder += GetString(STR_NETWORK_MESSAGE_KICKED, name, str); break;
279 case NetworkAction::ChatTeam: builder += GetString(self_send ? STR_NETWORK_CHAT_TO_COMPANY : STR_NETWORK_CHAT_COMPANY, name, str); break;
280 case NetworkAction::ChatClient: builder += GetString(self_send ? STR_NETWORK_CHAT_TO_CLIENT : STR_NETWORK_CHAT_CLIENT, name, str); break;
281 case NetworkAction::ChatExternal: builder += GetString(STR_NETWORK_CHAT_EXTERNAL, std::move(data), name, str); break;
282 default: builder += GetString(STR_NETWORK_CHAT_ALL, name, str); break;
283 }
284
286 IConsolePrint(colour, message);
287 NetworkAddChatMessage(colour, _settings_client.gui.network_chat_timeout, message);
288}
289
296{
297 int lag = cs->last_frame_server - cs->last_frame;
298 /* This client has missed their ACK packet after 1 DAY_TICKS..
299 * so we increase their lag for every frame that passes!
300 * The packet can be out by a max of _net_frame_freq */
301 if (cs->last_frame_server + Ticks::DAY_TICKS + _settings_client.network.frame_freq < _frame_counter) {
302 lag += _frame_counter - (cs->last_frame_server + Ticks::DAY_TICKS + _settings_client.network.frame_freq);
303 }
304 return lag;
305}
306
307
317
325{
326 switch (err) {
327 default:
328 case NetworkErrorCode::General: return STR_NETWORK_ERROR_CLIENT_GENERAL;
329 case NetworkErrorCode::Desync: return STR_NETWORK_ERROR_CLIENT_DESYNC;
330 case NetworkErrorCode::SavegameFailed: return STR_NETWORK_ERROR_CLIENT_SAVEGAME;
331 case NetworkErrorCode::ConnectionLost: return STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST;
332 case NetworkErrorCode::IllegalPacket: return STR_NETWORK_ERROR_CLIENT_PROTOCOL_ERROR;
333 case NetworkErrorCode::NewGRFMismatch: return STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH;
334 case NetworkErrorCode::NotAuthorized: return STR_NETWORK_ERROR_CLIENT_NOT_AUTHORIZED;
335 case NetworkErrorCode::NotExpected: return STR_NETWORK_ERROR_CLIENT_NOT_EXPECTED;
336 case NetworkErrorCode::WrongRevision: return STR_NETWORK_ERROR_CLIENT_WRONG_REVISION;
337 case NetworkErrorCode::NameInUse: return STR_NETWORK_ERROR_CLIENT_NAME_IN_USE;
338 case NetworkErrorCode::WrongPassword: return STR_NETWORK_ERROR_CLIENT_WRONG_PASSWORD;
339 case NetworkErrorCode::CompanyMismatch: return STR_NETWORK_ERROR_CLIENT_COMPANY_MISMATCH;
340 case NetworkErrorCode::Kicked: return STR_NETWORK_ERROR_CLIENT_KICKED;
341 case NetworkErrorCode::Cheater: return STR_NETWORK_ERROR_CLIENT_CHEATER;
342 case NetworkErrorCode::ServerFull: return STR_NETWORK_ERROR_CLIENT_SERVER_FULL;
343 case NetworkErrorCode::TooManyCommands: return STR_NETWORK_ERROR_CLIENT_TOO_MANY_COMMANDS;
344 case NetworkErrorCode::TimeoutPassword: return STR_NETWORK_ERROR_CLIENT_TIMEOUT_PASSWORD;
345 case NetworkErrorCode::TimeoutComputer: return STR_NETWORK_ERROR_CLIENT_TIMEOUT_COMPUTER;
346 case NetworkErrorCode::TimeoutMap: return STR_NETWORK_ERROR_CLIENT_TIMEOUT_MAP;
347 case NetworkErrorCode::TimeoutJoin: return STR_NETWORK_ERROR_CLIENT_TIMEOUT_JOIN;
348 case NetworkErrorCode::InvalidClientName: return STR_NETWORK_ERROR_CLIENT_INVALID_CLIENT_NAME;
349 case NetworkErrorCode::NotOnAllowList: return STR_NETWORK_ERROR_CLIENT_NOT_ON_ALLOW_LIST;
350 case NetworkErrorCode::NoAuthenticationMethodAvailable: return STR_NETWORK_ERROR_CLIENT_NO_AUTHENTICATION_METHOD_AVAILABLE;
351 };
352}
353
359void NetworkHandlePauseChange(PauseModes prev_mode, PauseMode changed_mode)
360{
361 if (!_networking) return;
362
363 switch (changed_mode) {
365 case PauseMode::Join:
369 bool changed = _pause_mode.None() != prev_mode.None();
370 bool paused = _pause_mode.Any();
371 if (!paused && !changed) return;
372
373 std::string str;
374 if (!changed) {
375 std::array<StringParameter, 5> params{};
376 auto it = params.begin();
377 if (_pause_mode.Test(PauseMode::Normal)) *it++ = STR_NETWORK_SERVER_MESSAGE_GAME_REASON_MANUAL;
378 if (_pause_mode.Test(PauseMode::Join)) *it++ = STR_NETWORK_SERVER_MESSAGE_GAME_REASON_CONNECTING_CLIENTS;
379 if (_pause_mode.Test(PauseMode::GameScript)) *it++ = STR_NETWORK_SERVER_MESSAGE_GAME_REASON_GAME_SCRIPT;
380 if (_pause_mode.Test(PauseMode::ActiveClients)) *it++ = STR_NETWORK_SERVER_MESSAGE_GAME_REASON_NOT_ENOUGH_PLAYERS;
381 if (_pause_mode.Test(PauseMode::LinkGraph)) *it++ = STR_NETWORK_SERVER_MESSAGE_GAME_REASON_LINK_GRAPH;
382 str = GetStringWithArgs(STR_NETWORK_SERVER_MESSAGE_GAME_STILL_PAUSED_1 + std::distance(params.begin(), it) - 1, {params.begin(), it});
383 } else {
384 StringID reason;
385 switch (changed_mode) {
386 case PauseMode::Normal: reason = STR_NETWORK_SERVER_MESSAGE_GAME_REASON_MANUAL; break;
387 case PauseMode::Join: reason = STR_NETWORK_SERVER_MESSAGE_GAME_REASON_CONNECTING_CLIENTS; break;
388 case PauseMode::GameScript: reason = STR_NETWORK_SERVER_MESSAGE_GAME_REASON_GAME_SCRIPT; break;
389 case PauseMode::ActiveClients: reason = STR_NETWORK_SERVER_MESSAGE_GAME_REASON_NOT_ENOUGH_PLAYERS; break;
390 case PauseMode::LinkGraph: reason = STR_NETWORK_SERVER_MESSAGE_GAME_REASON_LINK_GRAPH; break;
391 default: NOT_REACHED();
392 }
393 str = GetString(paused ? STR_NETWORK_SERVER_MESSAGE_GAME_PAUSED : STR_NETWORK_SERVER_MESSAGE_GAME_UNPAUSED, reason);
394 }
395
397 break;
398 }
399
400 default:
401 return;
402 }
403}
404
405
414static void CheckPauseHelper(bool pause, PauseMode pm)
415{
416 if (pause == _pause_mode.Test(pm)) return;
417
418 Command<Commands::Pause>::Post(pm, pause);
419}
420
427{
428 uint count = 0;
429
430 for (const NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
431 if (cs->status != NetworkClientSocket::ClientStatus::Active) continue;
432 if (!Company::IsValidID(cs->GetInfo()->client_playas)) continue;
433 count++;
434 }
435
436 return count;
437}
438
443{
444 if (_pause_mode.Test(PauseMode::Error) ||
446 (_settings_client.network.min_active_clients == 0 && !_pause_mode.Test(PauseMode::ActiveClients))) {
447 return;
448 }
450}
451
457{
458 for (const NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
459 if (cs->status >= NetworkClientSocket::ClientStatus::Authorized && cs->status < NetworkClientSocket::ClientStatus::Active) return true;
460 }
461
462 return false;
463}
464
468static void CheckPauseOnJoin()
469{
470 if (_pause_mode.Test(PauseMode::Error) ||
471 (!_settings_client.network.pause_on_join && !_pause_mode.Test(PauseMode::Join))) {
472 return;
473 }
475}
476
483std::string_view ParseCompanyFromConnectionString(std::string_view connection_string, CompanyID *company_id)
484{
485 std::string_view ip = connection_string;
486 if (company_id == nullptr) return ip;
487
488 size_t offset = ip.find_last_of('#');
489 if (offset != std::string::npos) {
490 std::string_view company_string = ip.substr(offset + 1);
491 ip = ip.substr(0, offset);
492
493 uint8_t company_value;
494 auto [_, err] = std::from_chars(company_string.data(), company_string.data() + company_string.size(), company_value);
495 if (err == std::errc()) {
496 if (company_value != COMPANY_NEW_COMPANY && company_value != COMPANY_SPECTATOR) {
497 if (company_value > MAX_COMPANIES || company_value == 0) {
498 *company_id = COMPANY_SPECTATOR;
499 } else {
500 /* "#1" means the first company, which has index 0. */
501 *company_id = (CompanyID)(company_value - 1);
502 }
503 } else {
504 *company_id = (CompanyID)company_value;
505 }
506 }
507 }
508
509 return ip;
510}
511
527std::string_view ParseFullConnectionString(std::string_view connection_string, uint16_t &port, CompanyID *company_id)
528{
529 std::string_view ip = ParseCompanyFromConnectionString(connection_string, company_id);
530
531 size_t port_offset = ip.find_last_of(':');
532 size_t ipv6_close = ip.find_last_of(']');
533 if (port_offset != std::string::npos && (ipv6_close == std::string::npos || ipv6_close < port_offset)) {
534 std::string_view port_string = ip.substr(port_offset + 1);
535 ip = ip.substr(0, port_offset);
536 std::from_chars(port_string.data(), port_string.data() + port_string.size(), port);
537 }
538 return ip;
539}
540
547std::string NormalizeConnectionString(std::string_view connection_string, uint16_t default_port)
548{
549 uint16_t port = default_port;
550 std::string_view ip = ParseFullConnectionString(connection_string, port);
551 return fmt::format("{}:{}", ip, port);
552}
553
562NetworkAddress ParseConnectionString(std::string_view connection_string, uint16_t default_port)
563{
564 uint16_t port = default_port;
565 std::string_view ip = ParseFullConnectionString(connection_string, port);
566 return NetworkAddress(ip, port);
567}
568
574/* static */ void ServerNetworkGameSocketHandler::AcceptConnection(SOCKET s, const NetworkAddress &address)
575{
576 /* Register the login */
578
580 cs->client_address = address; // Save the IP of the client
581
582 InvalidateWindowData(WindowClass::NetworkClientList, 0);
583}
584
589static void InitializeNetworkPools(bool close_admins = true)
590{
592 if (close_admins) to_clean.Set(PoolType::NetworkAdmin);
593 PoolBase::Clean(to_clean);
594}
595
600void NetworkClose(bool close_admins)
601{
602 if (_network_server) {
603 if (close_admins) {
605 as->CloseConnection(true);
606 }
607 }
608
609 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
610 cs->CloseConnection(NetworkRecvStatus::ClientQuit);
611 }
614
615 _network_coordinator_client.CloseConnection();
616 } else {
617 if (MyClient::my_client != nullptr) {
620 }
621
622 _network_coordinator_client.CloseAllConnections();
623 }
625
627
628 _networking = false;
629 _network_server = false;
630
632
633 InitializeNetworkPools(close_admins);
634}
635
640static void NetworkInitialize(bool close_admins = true)
641{
642 InitializeNetworkPools(close_admins);
643
644 _sync_frame = 0;
645 _network_first_time = true;
646
648}
649
652private:
653 std::string connection_string;
654
655public:
661
662 void OnFailure() override
663 {
664 Debug(Facility::Net, Severity::Trace3, "Query::OnFailure(): connection_string={}", this->connection_string);
665
668 item->refreshing = false;
669
671 }
672
673 void OnConnect(SOCKET s) override
674 {
675 Debug(Facility::Net, Severity::Trace3, "Query::OnConnect(): connection_string={}", this->connection_string);
676
677 QueryNetworkGameSocketHandler::QueryServer(s, this->connection_string);
678 }
679};
680
685void NetworkQueryServer(std::string_view connection_string)
686{
687 if (!_network_available) return;
688
689 Debug(Facility::Net, Severity::Trace3, "NetworkQueryServer(): connection_string={}", connection_string);
690
691 /* Mark the entry as refreshing, so the GUI can show the refresh is pending. */
692 NetworkGame *item = NetworkGameListAddItem(connection_string);
693 item->refreshing = true;
694
696}
697
707NetworkGame *NetworkAddServer(std::string_view connection_string, bool manually, bool never_expire)
708{
709 if (connection_string.empty()) return nullptr;
710
711 /* Ensure the item already exists in the list */
712 NetworkGame *item = NetworkGameListAddItem(connection_string);
713 if (item->info.server_name.empty()) {
715 item->info.server_name = connection_string;
716
718
719 NetworkQueryServer(connection_string);
720 }
721
722 if (manually) item->manually = true;
723 if (never_expire) item->version = INT32_MAX;
724
725 return item;
726}
727
733void GetBindAddresses(NetworkAddressList *addresses, uint16_t port)
734{
735 for (const auto &iter : _network_bind_list) {
736 addresses->emplace_back(iter, port);
737 }
738
739 /* No address, so bind to everything. */
740 if (addresses->empty()) {
741 addresses->emplace_back("", port);
742 }
743}
744
750{
751 _network_host_list.clear();
752
753 for (const auto &item : _network_game_list) {
754 if (item->manually) _network_host_list.emplace_back(item->connection_string);
755 }
756}
757
760private:
761 std::string connection_string;
762
763public:
769
770 void OnFailure() override
771 {
772 Debug(Facility::Net, Severity::Trace3, "Client::OnFailure(): connection_string={}", this->connection_string);
773
774 ShowNetworkError(STR_NETWORK_ERROR_NOCONNECTION);
775 }
776
777 void OnConnect(SOCKET s) override
778 {
779 Debug(Facility::Net, Severity::Trace3, "Client::OnConnect(): connection_string={}", this->connection_string);
780
781 _networking = true;
783 new ClientNetworkGameSocketHandler(s, this->connection_string);
784 IConsoleCmdExec("exec scripts/on_client.scr 0");
786 }
787};
788
805bool NetworkClientConnectGame(std::string_view connection_string, CompanyID default_company, const std::string &join_server_password)
806{
807 Debug(Facility::Net, Severity::Trace3, "NetworkClientConnectGame(): connection_string={}", connection_string);
808
809 CompanyID join_as = default_company;
810 std::string resolved_connection_string = ServerAddress::Parse(connection_string, NETWORK_DEFAULT_PORT, &join_as).connection_string;
811
812 if (!_network_available) return false;
813 if (!NetworkValidateOurClientName()) return false;
814
815 _network_join.connection_string = std::move(resolved_connection_string);
816 _network_join.company = join_as;
817 _network_join.server_password = join_server_password;
818
819 if (_game_mode == GameMode::Menu) {
820 /* From the menu we can immediately continue with the actual join. */
822 } else {
823 /* When already playing a game, first go back to the main menu. This
824 * disconnects the user from the current game, meaning we can safely
825 * load in the new. After all, there is little point in continuing to
826 * play on a server if we are connecting to another one.
827 */
829 }
830 return true;
831}
832
839{
842
843 _settings_client.network.last_joined = _network_join.connection_string;
844 Debug(Facility::Net, Severity::Trace3, "status = Connecting");
847
849}
850
853{
855 /* The server is a client too */
856 _network_game_info.clients_on = _network_dedicated ? 0 : 1;
857}
858
861{
862 /* There should be always space for the server. */
866
867 ci->client_name = _settings_client.network.client_name;
868
870 ci->public_key = _settings_client.network.client_public_key;
871}
872
883bool NetworkValidateServerName(std::string &server_name)
884{
885 StrTrimInPlace(server_name);
886 if (!server_name.empty()) return true;
887
888 ShowErrorMessage(GetEncodedString(STR_NETWORK_ERROR_BAD_SERVER_NAME), {}, WarningLevel::Error);
889 return false;
890}
891
899{
900 static const std::string fallback_client_name = "Unnamed Client";
901 StrTrimInPlace(_settings_client.network.client_name);
902 if (_settings_client.network.client_name.empty() || _settings_client.network.client_name == fallback_client_name) {
903 Debug(Facility::Net, Severity::Error, "No \"client_name\" has been set, using \"{}\" instead. Please set this now using the \"name <new name>\" command", fallback_client_name);
904 _settings_client.network.client_name = fallback_client_name;
905 }
906
907 static const std::string fallback_server_name = "Unnamed Server";
908 StrTrimInPlace(_settings_client.network.server_name);
909 if (_settings_client.network.server_name.empty() || _settings_client.network.server_name == fallback_server_name) {
910 Debug(Facility::Net, Severity::Error, "No \"server_name\" has been set, using \"{}\" instead. Please set this now using the \"server_name <new name>\" command", fallback_server_name);
911 _settings_client.network.server_name = fallback_server_name;
912 }
913}
914
920{
921 if (!_network_available) return false;
922
923 /* Call the pre-scripts */
924 IConsoleCmdExec("exec scripts/pre_server.scr 0");
925 if (_network_dedicated) IConsoleCmdExec("exec scripts/pre_dedicated.scr 0");
926
927 /* Check for the client and server names to be set, but only after the scripts had a chance to set them.*/
929
930 NetworkDisconnect(false);
931 NetworkInitialize(false);
933 Debug(Facility::Net, Severity::Debug1, "Starting listeners for clients");
934 if (!ServerNetworkGameSocketHandler::Listen(_settings_client.network.server_port)) return false;
935
936 /* Only listen for admins when the authentication is configured. */
937 if (_settings_client.network.AdminAuthenticationConfigured()) {
938 Debug(Facility::Net, Severity::Debug1, "Starting listeners for admins");
939 if (!ServerNetworkAdminSocketHandler::Listen(_settings_client.network.server_admin_port)) return false;
940 }
941
942 /* Try to start UDP-server */
943 Debug(Facility::Net, Severity::Debug1, "Starting listeners for incoming server queries");
945
946 _network_server = true;
947 _networking = true;
948 _frame_counter = 0;
953
955
958
959 if (_settings_client.network.server_game_type != ServerGameType::Local) {
961 }
962
963 /* execute server initialization script */
964 IConsoleCmdExec("exec scripts/on_server.scr 0");
965 /* if the server is dedicated ... add some other script */
966 if (_network_dedicated) IConsoleCmdExec("exec scripts/on_dedicated.scr 0");
967
968 return true;
969}
970
976{
977 if (!_network_server) return;
978
979 /* Update the static game info to set the values from the new game. */
981
983
984 if (!_network_dedicated) {
987 if (c != nullptr && ci != nullptr) {
988 ci->client_playas = c->index;
989
990 /*
991 * If the company has not been named yet, the company was just started.
992 * Otherwise it would have gotten a name already, so announce it as a new company.
993 */
994 if (c->name_1 == STR_SV_UNNAMED && c->name.empty()) NetworkServerNewCompany(c, ci);
995 }
996
998 } else {
999 /* welcome possibly still connected admins - this can only happen on a dedicated server. */
1001 }
1002}
1003
1009{
1010 if (_network_server) {
1011 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1012 cs->SendNewGame();
1013 cs->SendPackets();
1014 }
1015
1017 as->SendNewGame();
1018 as->SendPackets();
1019 }
1020 }
1021
1022 /* For non-dedicated servers we have to kick the admins as we are not
1023 * certain that we will end up in a new network game. */
1025}
1026
1031void NetworkDisconnect(bool close_admins)
1032{
1033 if (_network_server) {
1034 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1035 cs->SendShutdown();
1036 cs->SendPackets();
1037 }
1038
1039 if (close_admins) {
1041 as->SendShutdown();
1042 as->SendPackets();
1043 }
1044 }
1045 }
1046
1047 CloseWindowById(WindowClass::NetworkStatus, NetworkStatusWindowNumber::Join);
1048
1049 NetworkClose(close_admins);
1050
1051 /* Reinitialize the UDP stack, i.e. close all existing connections. */
1053}
1054
1060{
1061 if (!_networking) return;
1062
1063 switch (_settings_client.network.server_game_type) {
1065 _network_coordinator_client.CloseConnection();
1066 break;
1067
1070 _network_coordinator_client.Register();
1071 break;
1072
1073 default:
1074 NOT_REACHED();
1075 }
1076}
1077
1082static bool NetworkReceive()
1083{
1084 bool result;
1085 if (_network_server) {
1088 } else {
1090 }
1092 return result;
1093}
1094
1106
1123
1129{
1130 if (!_networking) return;
1131
1132 if (!NetworkReceive()) return;
1133
1134 if (_network_server) {
1135 /* Log the sync state to check for in-syncedness of replays. */
1137 /* We don't want to log multiple times if paused. */
1138 static TimerGameEconomy::Date last_log;
1139 if (last_log != TimerGameEconomy::date) {
1140 Debug(Facility::Desync, Severity::Error, "sync: {:08x}; {:02x}; {:08x}; {:08x}", TimerGameEconomy::date, TimerGameEconomy::date_fract, _random.state[0], _random.state[1]);
1141 last_log = TimerGameEconomy::date;
1142 }
1143 }
1144
1145#ifdef DEBUG_DUMP_COMMANDS
1146 /* Loading of the debug commands from -ddesync>=1 */
1147 static auto f = FioFOpenFile("commands.log", "rb", Subdirectory::Save);
1148 static TimerGameEconomy::Date next_date(0);
1149 static uint32_t next_date_fract;
1150 static CommandPacket *cp = nullptr;
1151 static bool check_sync_state = false;
1152 static uint32_t sync_state[2];
1153 if (!f.has_value() && next_date == 0) {
1154 Debug(Facility::Desync, Severity::Critical, "Cannot open commands.log");
1155 next_date = TimerGameEconomy::Date(1);
1156 }
1157
1158 while (f.has_value() && !feof(*f)) {
1159 if (TimerGameEconomy::date == next_date && TimerGameEconomy::date_fract == next_date_fract) {
1160 if (cp != nullptr) {
1161 NetworkSendCommand(cp->cmd, cp->err_msg, nullptr, cp->company, cp->data);
1162 Debug(Facility::Desync, Severity::Critical, "Injecting: {:08x}; {:02x}; {:02x}; {:08x}; {} ({})", TimerGameEconomy::date, TimerGameEconomy::date_fract, _current_company.base(), cp->cmd, FormatArrayAsHex(cp->data), GetCommandName(cp->cmd));
1163 delete cp;
1164 cp = nullptr;
1165 }
1166 if (check_sync_state) {
1167 if (sync_state[0] == _random.state[0] && sync_state[1] == _random.state[1]) {
1169 } else {
1170 Debug(Facility::Desync, Severity::Critical, "Sync check: {:08x}; {:02x}; mismatch expected {{{:08x}, {:08x}}}, got {{{:08x}, {:08x}}}",
1171 TimerGameEconomy::date, TimerGameEconomy::date_fract, sync_state[0], sync_state[1], _random.state[0], _random.state[1]);
1172 NOT_REACHED();
1173 }
1174 check_sync_state = false;
1175 }
1176 }
1177
1178 /* Skip all entries in the command-log till we caught up with the current game again. */
1179 if (TimerGameEconomy::date > next_date || (TimerGameEconomy::date == next_date && TimerGameEconomy::date_fract > next_date_fract)) {
1180 Debug(Facility::Desync, Severity::Critical, "Skipping to next command at {:08x}:{:02x}", next_date, next_date_fract);
1181 if (cp != nullptr) {
1182 delete cp;
1183 cp = nullptr;
1184 }
1185 check_sync_state = false;
1186 }
1187
1188 if (cp != nullptr || check_sync_state) break;
1189
1190 char buff[4096];
1191 if (fgets(buff, lengthof(buff), *f) == nullptr) break;
1192
1193 StringConsumer consumer{std::string_view{buff}};
1194 /* Ignore the "[date time] " part of the message */
1195 if (consumer.ReadCharIf('[')) {
1197 consumer.SkipCharIf(' ');
1198 }
1199
1200 if (consumer.ReadIf("cmd: ")
1201#ifdef DEBUG_FAILED_DUMP_COMMANDS
1202 || consumer.ReadIf("cmdf: ")
1203#endif
1204 ) {
1205 cp = new CommandPacket();
1206 next_date = TimerGameEconomy::Date(consumer.ReadIntegerBase<uint32_t>(16));
1207 bool valid = consumer.ReadIf("; ");
1208 next_date_fract = consumer.ReadIntegerBase<uint32_t>(16);
1209 valid &= consumer.ReadIf("; ");
1210 cp->company = static_cast<CompanyID>(consumer.ReadIntegerBase<uint16_t>(16));
1211 valid &= consumer.ReadIf("; ");
1212 cp->cmd = static_cast<Commands>(consumer.ReadIntegerBase<uint32_t>(16));
1213 valid &= consumer.ReadIf("; ");
1214 cp->err_msg = consumer.ReadIntegerBase<uint32_t>(16);
1215 valid &= consumer.ReadIf("; ");
1216 auto args = consumer.ReadUntilChar(' ', StringConsumer::SKIP_ONE_SEPARATOR);
1217 assert(valid);
1218
1219 /* Parse command data. */
1220 cp->data.clear();
1221 for (size_t i = 0; i + 1 < args.size(); i += 2) {
1222 uint8_t e = 0;
1223 std::from_chars(args.data() + i, args.data() + i + 2, e, 16);
1224 cp->data.push_back(e);
1225 }
1226 } else if (consumer.ReadIf("join: ")) {
1227 /* Manually insert a pause when joining; this way the client can join at the exact right time. */
1228 next_date = TimerGameEconomy::Date(consumer.ReadIntegerBase<uint32_t>(16));
1229 bool valid = consumer.ReadIf("; ");
1230 next_date_fract = consumer.ReadIntegerBase<uint32_t>(16);
1231 assert(valid);
1232 Debug(Facility::Desync, Severity::Critical, "Injecting pause for join at {:08x}:{:02x}; please join when paused", next_date, next_date_fract);
1233 cp = new CommandPacket();
1235 cp->cmd = Commands::Pause;
1236 cp->data = EndianBufferWriter<>::FromValue(CommandTraits<Commands::Pause>::Args{ PauseMode::Normal, true });
1237 _ddc_fastforward = false;
1238 } else if (consumer.ReadIf("sync: ")) {
1239 next_date = TimerGameEconomy::Date(consumer.ReadIntegerBase<uint32_t>(16));
1240 bool valid = consumer.ReadIf("; ");
1241 next_date_fract = consumer.ReadIntegerBase<uint32_t>(16);
1242 valid &= consumer.ReadIf("; ");
1243 sync_state[0] = consumer.ReadIntegerBase<uint32_t>(16);
1244 valid &= consumer.ReadIf("; ");
1245 sync_state[1] = consumer.ReadIntegerBase<uint32_t>(16);
1246 assert(valid);
1247 check_sync_state = true;
1248 } else if (consumer.ReadIf("msg: ") || consumer.ReadIf("client: ") ||
1249 consumer.ReadIf("load: ") || consumer.ReadIf("save: ") ||
1250 consumer.ReadIf("warning: ")) {
1251 /* A message that is not very important to the log playback, but part of the log. */
1252#ifndef DEBUG_FAILED_DUMP_COMMANDS
1253 } else if (consumer.ReadIf("cmdf: ")) {
1254 Debug(Facility::Desync, Severity::Critical, "Skipping replay of failed command: {}", consumer.Read(StringConsumer::npos));
1255#endif
1256 } else {
1257 /* Can't parse a line; what's wrong here? */
1258 Debug(Facility::Desync, Severity::Critical, "Trying to parse: {}", consumer.Read(StringConsumer::npos));
1259 NOT_REACHED();
1260 }
1261 }
1262 if (f.has_value() && feof(*f)) {
1263 Debug(Facility::Desync, Severity::Critical, "End of commands.log");
1264 f.reset();
1265 }
1266#endif /* DEBUG_DUMP_COMMANDS */
1268 /* Only check for active clients just before we're going to send out
1269 * the commands so we don't send multiple pause/unpause commands when
1270 * the frame_freq is more than 1 tick. Same with distributing commands. */
1274 }
1275
1276 bool send_frame = false;
1277
1278 /* We first increase the _frame_counter */
1280 /* Update max-frame-counter */
1282 _frame_counter_max = _frame_counter + _settings_client.network.frame_freq;
1283 send_frame = true;
1284 }
1285
1287
1288 /* Then we make the frame */
1289 StateGameLoop();
1290
1291 _sync_seed_1 = _random.state[0];
1292#ifdef NETWORK_SEND_DOUBLE_SEED
1293 _sync_seed_2 = _random.state[1];
1294#endif
1295
1296 NetworkServer_Tick(send_frame);
1297 } else {
1298 /* Client */
1299
1300 /* Make sure we are at the frame were the server is (quick-frames) */
1302 /* Run a number of frames; when things go bad, get out. */
1305 }
1306 } else {
1307 /* Else, keep on going till _frame_counter_max */
1309 /* Run one frame; if things went bad, get out. */
1311 }
1312 }
1313 }
1314
1315 NetworkSend();
1316}
1317
1320{
1321 Debug(Facility::Net, Severity::Notice, "Starting network");
1322
1323 /* Network is available */
1325 _network_dedicated = false;
1326
1327 _network_game_info = {};
1328
1331 Debug(Facility::Net, Severity::Notice, "Network online, multiplayer available");
1334}
1335
1338{
1342
1343 Debug(Facility::Net, Severity::Notice, "Shutting down network");
1344
1345 _network_available = false;
1346
1348}
1349
1350#ifdef __EMSCRIPTEN__
1351extern "C" {
1352
1353void CDECL em_openttd_add_server(const char *connection_string)
1354{
1355 NetworkAddServer(connection_string, false, true);
1356}
1357
1358}
1359#endif
std::vector< NetworkAddress > NetworkAddressList
Type for a list of addresses.
Definition address.h:18
constexpr bool None() const
Test if none of the values are set.
constexpr Timpl & Set()
Set all bits.
void PutUtf8(char32_t c)
Append UTF-8 char.
Class for handling the client side of the game connection.
static ClientNetworkGameSocketHandler * my_client
This is us!
static NetworkRecvStatus SendQuit()
Tell the server we would like to quit.
static bool Receive()
Check whether we received/can send some data from/to the server and when that's the case handle it ap...
static bool GameLoop()
Actual game loop for the client.
static void Send()
Send the packets of this socket handler.
Wrapper for (un)resolved network addresses; there's no reason to transform a numeric IP to a string a...
Definition address.h:26
static void EnsureValidSecretKeyAndUpdatePublicKey(std::string &secret_key, std::string &public_key)
Ensures that the given secret key is valid, and when not overwrite it with a valid secret key.
bool Contains(std::string_view key) const
Check whether the given key is contains in these authorized keys.
Definition network.cpp:176
bool Add(std::string_view key)
Add the given key to the authorized keys, when it is not already contained.
Definition network.cpp:186
bool Remove(std::string_view key)
Remove the given key from the authorized keys, when it is exists.
Definition network.cpp:202
static void ProcessDeferredDeletions()
Actually delete the socket handlers that were marked for deletion.
Definition tcp_game.cpp:197
ClientID client_id
Client identifier.
Definition tcp_game.h:527
static void HTTPReceive()
Do the receiving for all HTTP connections.
static void SendReceive()
Check if any query needs to send or receive.
static void QueryServer(SOCKET s, std::string_view connection_string)
Start to query a server based on an open socket.
std::string connection_string
The connection string for this ServerAddress.
Definition address.h:197
static ServerAddress Parse(std::string_view 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:445
Class for handling the server side of the game connection.
static void Send()
Send the packets for the server sockets.
static void WelcomeAll()
Send a Welcome packet to all connected admins.
static Pool::IterateWrapperFiltered< ServerNetworkAdminSocketHandler, ServerNetworkAdminSocketHandlerFilter > IterateActive(size_t from=0)
Returns an iterable ensemble of all active admin sockets.
static ServerNetworkGameSocketHandler * GetByClientID(ClientID client_id)
Return the client state given it's client-identifier.
Definition network.cpp:150
static void Send()
Send the packets for the server sockets.
static void AcceptConnection(SOCKET s, const NetworkAddress &address)
Handle the accepting of a connection to the server.
Definition network.cpp:574
ServerNetworkGameSocketHandler(ClientPoolID index, SOCKET s)
Create a new socket for the server side of the game connection.
NetworkAddress client_address
IP-address of the client (so they can be banned).
Compose data into a growing std::string.
Parse data from a string / buffer.
bool ReadCharIf(char c)
Check whether the next 8-bit char matches 'c', and skip it.
void SkipCharIf(char c)
If the next data matches the 8-bit char 'c', then skip it.
std::string_view ReadUntilChar(char c, SeparatorUsage sep)
Read data until the first occurrence of 8-bit char 'c', and advance reader.
void SkipUntilChar(char c, SeparatorUsage sep)
Skip data until the first occurrence of 8-bit char 'c'.
@ SKIP_ONE_SEPARATOR
Read and discard one separator, do not include it in the result.
bool ReadIf(std::string_view str)
Check whether the next data matches 'str', and skip it.
T ReadIntegerBase(int base, T def=0, bool clamp=false)
Read and parse an integer in number 'base', and advance the reader.
std::string_view Read(size_type len)
Read the next 'len' bytes, and advance reader.
static constexpr size_type npos
Special value for "end of data".
void OnConnect(SOCKET s) override
Callback when the connection succeeded.
Definition network.cpp:777
void OnFailure() override
Callback for when the connection attempt failed.
Definition network.cpp:770
std::string connection_string
The address that this connecter is trying to connect to.
Definition network.cpp:761
TCPClientConnecter(std::string_view connection_string)
Create the connecter.
Definition network.cpp:768
static void CheckCallbacks()
Check whether we need to call the callback, i.e.
static std::shared_ptr< TCPConnecter > Create(Args &&... args)
Create the connecter, and initiate connecting by putting it in the collection of TCP connections to m...
Definition tcp.h:146
static void KillAll()
Kill all connection attempts.
TCPQueryConnecter(std::string_view connection_string)
Create the connecter.
Definition network.cpp:660
void OnConnect(SOCKET s) override
Callback when the connection succeeded.
Definition network.cpp:673
std::string connection_string
The address that this connecter is trying to query.
Definition network.cpp:653
void OnFailure() override
Callback for when the connection attempt failed.
Definition network.cpp:662
TCPServerConnecter(std::string_view connection_string, uint16_t default_port)
Create a new connecter for the server.
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static Date date
Current date in days (day counter).
static DateFract date_fract
Fractional part of the day.
StrongType::Typedef< int32_t, DateTag< struct Economy >, StrongType::Compare, StrongType::Integer > Date
std::string_view GetCommandName(Commands cmd)
Get the name of the given command.
Definition command.cpp:124
Functions related to commands.
void NetworkSendCommand(Commands cmd, StringID err_message, CommandCallback *callback, CompanyID company, const CommandDataBuffer &cmd_data)
Prepare a DoCommand to be send over the network.
Commands
List of commands.
@ Pause
pause the game
Definition of stuff that is very close to a company, like the company struct itself.
CompanyID GetFirstPlayableCompanyID()
Get the index of the first available company.
CompanyID _current_company
Company currently doing an action.
Functions related to companies.
static constexpr CompanyID COMPANY_SPECTATOR
The client is spectating.
static constexpr CompanyID COMPANY_NEW_COMPANY
The client wants a new company.
static const uint16_t NETWORK_DEFAULT_PORT
The default port of the game server (TCP & UDP).
Definition config.h:23
void IConsolePrint(ExtendedTextColour 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
void IConsoleCmdExec(std::string_view command_string, const uint recurse_count)
Execute a given command passed to us.
Definition console.cpp:272
Console functions used outside of the console code.
static const TextColour CC_DEFAULT
Default colour of the console.
void NetworkCoreShutdown()
Shuts down the network core (as that is needed for some platforms.
Definition core.cpp:41
bool NetworkCoreInitialize()
Initializes the network core (as that is needed for some platforms.
Definition core.cpp:21
@ ClientQuit
The connection is lost gracefully. Other clients are already informed of this leaving client.
Definition core.h:24
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Desync
Desync message facility.
Definition debug_type.h:41
@ Net
Net message facility.
Definition debug_type.h:33
@ Debug1
Debug #1 - High level debug messages.
Definition debug_type.h:20
@ Notice
Notice.
Definition debug_type.h:18
@ Critical
Critical, user should know about this.
Definition debug_type.h:15
@ Error
Error, but we are recovering.
Definition debug_type.h:16
@ Trace3
Trace information #3.
Definition debug_type.h:24
Functions related to errors.
@ Critical
Critical errors, the MessageBox is shown in all cases.
Definition error.h:25
@ Error
Errors (eg. saving/loading failed).
Definition error.h:24
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
std::optional< FileHandle > FioFOpenFile(std::string_view filename, std::string_view mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
Definition fileio.cpp:248
Functions for standard in/out file operations.
@ Save
Base directory for all savegames.
Definition fileio_type.h:89
PauseModes _pause_mode
The current pause mode.
Definition gfx.cpp:46
SwitchMode _switch_mode
The next mainloop command.
Definition gfx.cpp:45
void NetworkFindBroadcastIPs(NetworkAddressList *broadcast)
Find the IPv4 broadcast addresses; IPv6 uses a completely different strategy for broadcasting.
Definition host.cpp:85
Resolving of hostnames/IPs.
void NetworkHTTPInitialize()
Initialize the HTTP socket handler.
void NetworkHTTPUninitialize()
Uninitialize the HTTP socket handler.
Miscellaneous command definitions.
uint32_t _last_sync_frame
Used in the server to store the last time a sync packet was sent to clients.
Definition network.cpp:77
NetworkAddress ParseConnectionString(std::string_view connection_string, uint16_t default_port)
Convert a string containing either "hostname" or "hostname:ip" to a NetworkAddress.
Definition network.cpp:562
void NetworkStartUp()
This tries to launch the network for a given OS.
Definition network.cpp:1319
bool _is_network_server
Does this client wants to be a network-server?
Definition network.cpp:67
void NetworkHandlePauseChange(PauseModes prev_mode, PauseMode changed_mode)
Handle the pause mode change so we send the right messages to the chat.
Definition network.cpp:359
static uint NetworkCountActiveClients()
Counts the number of active clients connected.
Definition network.cpp:426
StringList _network_host_list
The servers we know.
Definition network.cpp:72
StringID GetNetworkErrorMsg(NetworkErrorCode err)
Retrieve a short translateable string of the error code.
Definition network.cpp:324
uint32_t _frame_counter_server
The frame_counter of the server, if in network-mode.
Definition network.cpp:74
static void CheckPauseOnJoin()
Check whether we should pause on join.
Definition network.cpp:468
NetworkAddressList _broadcast_list
List of broadcast addresses.
Definition network.cpp:78
void NetworkClientJoinGame()
Actually perform the joining to the server.
Definition network.cpp:838
static bool NetworkHasJoiningClient()
Checks whether there is a joining client.
Definition network.cpp:456
static auto FindKey(auto *authorized_keys, std::string_view authorized_key)
Simple helper to find the location of the given authorized key in the authorized keys.
Definition network.cpp:166
ClientID _redirect_console_to_client
If not invalid, redirect the console output to a client.
Definition network.cpp:69
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:898
uint8_t NetworkSpectatorCount()
Get the number of clients that are playing as a spectator.
Definition network.cpp:216
void NetworkOnGameStart()
Perform tasks when the server is started.
Definition network.cpp:975
uint32_t _frame_counter
The current frame.
Definition network.cpp:76
bool _network_available
is network mode available?
Definition network.cpp:65
bool NetworkServerStart()
Run everything related to the network when starting a server.
Definition network.cpp:919
uint8_t _network_reconnect
Reconnect timeout.
Definition network.cpp:70
bool _networking
are we in networking mode?
Definition network.cpp:63
static void NetworkInitialize(bool close_admins=true)
Initializes the network (cleans sockets and stuff).
Definition network.cpp:640
void NetworkQueryServer(std::string_view connection_string)
Query a server to fetch the game-info.
Definition network.cpp:685
static void InitializeNetworkPools(bool close_admins=true)
Resets the pools used for network clients, and the admin pool if needed.
Definition network.cpp:589
StringList _network_ban_list
The banned clients.
Definition network.cpp:73
static void NetworkSend()
This sends all buffered commands (if possible).
Definition network.cpp:1096
bool _network_dedicated
are we a dedicated server?
Definition network.cpp:66
bool HasClients()
Return whether there is any client connected or trying to connect at all.
Definition network.cpp:95
static bool NetworkReceive()
Receives something from the network.
Definition network.cpp:1082
void NetworkGameLoop()
The main loop called from ttd.c.
Definition network.cpp:1128
void NetworkReboot()
The server is rebooting... The only difference with NetworkDisconnect, is the packets that is sent.
Definition network.cpp:1008
void NetworkDisconnect(bool close_admins)
We want to disconnect from the host/clients.
Definition network.cpp:1031
bool _network_server
network-server is active
Definition network.cpp:64
std::string GenerateUid(std::string_view subject)
Generate an unique ID.
Definition misc.cpp:66
uint32_t _sync_seed_1
Seed to compare during sync checks.
Definition network.cpp:79
NetworkGame * NetworkAddServer(std::string_view connection_string, bool manually, bool never_expire)
Validates an address entered as a string and adds the server to the list.
Definition network.cpp:707
uint32_t _sync_frame
The frame to perform the sync check.
Definition network.cpp:83
void NetworkBackgroundLoop()
We have to do some (simple) background stuff that runs normally, even when we are not in multiplayer.
Definition network.cpp:1112
StringList _network_bind_list
The addresses to bind on.
Definition network.cpp:71
void ShowNetworkError(StringID error_string)
There was a non-recoverable error, drop back to the main menu with a nice error.
Definition network.cpp:312
std::string NormalizeConnectionString(std::string_view connection_string, uint16_t default_port)
Normalize a connection string.
Definition network.cpp:547
uint NetworkCalculateLag(const NetworkClientSocket *cs)
Calculate the frame-lag of a client.
Definition network.cpp:295
bool NetworkClientConnectGame(std::string_view connection_string, CompanyID default_company, const std::string &join_server_password)
Join a client to the server at with the given connection string.
Definition network.cpp:805
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:442
void NetworkRebuildHostList()
Generates the list of manually added hosts from NetworkGame and dumps them into the array _network_ho...
Definition network.cpp:749
ClientID _network_own_client_id
Our client identifier.
Definition network.cpp:68
std::string_view ParseCompanyFromConnectionString(std::string_view connection_string, CompanyID *company_id)
Parse the company part ("#company" postfix) of a connecting string.
Definition network.cpp:483
static void CheckPauseHelper(bool pause, PauseMode pm)
Helper function for the pause checkers.
Definition network.cpp:414
bool _network_first_time
Whether we have finished joining or not.
Definition network.cpp:84
NetworkClientInfoPool _networkclientinfo_pool
Make sure both pools have the same size.
Definition network.cpp:60
void NetworkTextMessage(NetworkAction action, ExtendedTextColour colour, bool self_send, std::string_view name, std::string_view str, StringParameter &&data)
Writes a text-message to the console and the chat box.
Definition network.cpp:240
void NetworkShutDown()
This shuts the network down.
Definition network.cpp:1337
uint8_t _network_clients_connected
The amount of clients connected.
Definition network.cpp:87
static void NetworkInitGameInfo()
Initialise/fill the server's game info.
Definition network.cpp:852
static void NetworkInitServerClientInfo()
Initialise the server's client info.
Definition network.cpp:860
void GetBindAddresses(NetworkAddressList *addresses, uint16_t port)
Get the addresses to bind to.
Definition network.cpp:733
std::string_view ParseFullConnectionString(std::string_view connection_string, uint16_t &port, CompanyID *company_id)
Converts a string to ip/port/company Format: IP:port::company.
Definition network.cpp:527
void NetworkUpdateServerGameType()
The setting server_game_type was updated; possibly we need to take some action.
Definition network.cpp:1059
bool NetworkCanJoinCompany(CompanyID company_id)
Returns whether the given company can be joined by this client.
Definition network.cpp:139
void NetworkClose(bool close_admins)
Close current connections.
Definition network.cpp:600
uint32_t _frame_counter_max
To where we may go with our clients.
Definition network.cpp:75
bool NetworkValidateServerName(std::string &server_name)
Trim the given server name in place, i.e.
Definition network.cpp:883
Server part of the admin network protocol.
Base core network types and some helper functions to access them.
Pool< NetworkClientInfo, ClientPoolID, 8, PoolType::NetworkClient > NetworkClientInfoPool
Type for the pool with client information.
void NetworkAddChatMessage(ExtendedTextColour colour, uint duration, const std::string &message)
Add a text message to the 'chat window' to be shown.
NetworkJoinInfo _network_join
Information about the game to join to.
bool NetworkValidateOurClientName()
Convenience method for NetworkValidateClientName on _settings_client.network.client_name.
void NetworkClient_Connected()
Is called after a client is connected to the server.
Client part of the network protocol.
void NetworkFreeLocalCommandQueue()
Free the local command queues.
void NetworkExecuteLocalCommandQueue()
Execute all commands on the local command queue that ought to be executed this frame.
void NetworkDistributeCommands()
Distribute the commands of ourself and the clients.
ClientNetworkContentSocketHandler _network_content_client
The client we use to connect to the server.
Part of the network protocol handling content distribution.
ClientNetworkCoordinatorSocketHandler _network_coordinator_client
The connection to the Game Coordinator.
Part of the network protocol handling Game Coordinator requests.
void NetworkServerNewCompany(const Company *company, NetworkClientInfo *ci)
Perform all the server specific administration of a new company.
void NetworkServerUpdateGameInfo()
Update the server's NetworkServerGameInfo due to changes in settings.
void FillStaticNetworkServerGameInfo()
Fill a NetworkServerGameInfo structure with the static content, or things that are so static they can...
NetworkServerGameInfo _network_game_info
Information about our game.
NetworkGame * NetworkGameListAddItem(std::string_view connection_string)
Add a new item to the linked gamelist.
std::vector< std::unique_ptr< NetworkGame > > _network_game_list
Game list of this client.
Handling of the list of games.
@ Offline
Server is offline (or cannot be queried).
NetworkJoinStatus _network_join_status
The status of joining.
void UpdateNetworkGameWindow()
Update the network new window because a new server is found on the network.
void ShowJoinStatusWindow()
Open the window showing the status of joining the server.
void ShowClientList()
Open the client list window.
GUIs related to networking.
@ Connecting
Opening the connection to the server.
class ServerNetworkGameSocketHandler NetworkClientSocket
Class for handling the server side of the game connection.
Query part of the network protocol.
void ChangeNetworkRestartTime(bool reset)
Reset the automatic network restart time interval.
void NetworkServer_Tick(bool send_frame)
This is called every tick if this is a _network_server.
Server part of the network protocol.
ServerNetworkGameSocketHandler NetworkClientSocket
Make the code look slightly nicer/simpler.
NetworkErrorCode
The error codes we send around in the protocols.
@ WrongRevision
The client is using the wrong revision.
@ General
Fallback error code in case nothing matches.
@ Desync
Client tells that they desynced.
@ SavegameFailed
Client tells they could not load the savegame.
@ Cheater
The client is trying control companies in a way they are not supposed to.
@ TimeoutPassword
The client has timed out providing a password.
@ TooManyCommands
The client has sent too many commands in a short time.
@ TimeoutComputer
The client has timed out because the computer could not keep up with the server.
@ TimeoutMap
The client has timed out because it took too long to download the map.
@ NotAuthorized
The client tried to do something there are not authorized to.
@ ServerFull
The server is full.
@ InvalidClientName
The client tried to set an invalid name.
@ TimeoutJoin
The client has timed out because getting up to speed with the server failed.
@ NotOnAllowList
The client is not on the allow list.
@ WrongPassword
The client entered a wrong password.
@ NotExpected
The request/packet was not expected in the current state.
@ Kicked
The client got kicked.
@ ConnectionLost
Connection to the client was lost.
@ IllegalPacket
A packet was received that has invalid content.
@ NameInUse
The client has a duplicate name (and we couldn't make it unique).
@ NoAuthenticationMethodAvailable
The client and server could not find a common authentication method.
@ CompanyMismatch
The client was impersonating another company.
@ NewGRFMismatch
Client does not have the right NewGRFs.
NetworkAction
Actions that can be used for NetworkTextMessage.
@ ChatExternal
An external application sent a message over the admin port.
@ ServerMessage
The server sent a message.
@ ClientKicked
A client got kicked.
@ ChatTeam
A chat sent to all clients of a team/company.
@ ClientNameChange
A client changed their name.
@ ClientJoin
A client joined the server.
@ CompanySpectator
A client joined the spectators.
@ ChatClient
A chat sent to a specific client.
@ ClientLeave
A client left the server.
@ CompanyNew
A client created an joined a new company.
@ CompanyJoin
A client joined an existing company.
@ GiveMoney
A company was given money.
@ Client
Send message/notice to only a certain client (Private).
ClientID
'Unique' identifier to be given to clients
@ Server
Servers always have this ID.
@ Public
The game is publicly accessible.
@ Local
Do not communicate with the game coordinator.
@ InviteOnly
The game can be accessed if you know the invite code.
void NetworkUDPClose()
Close all UDP related stuff.
void NetworkUDPInitialize()
Initialize the whole UDP bit.
void NetworkUDPServerListen()
Start the listening of the UDP server component.
void NetworkBackgroundUDPLoop()
Receive the UDP packets.
Sending and receiving UDP messages.
void ClearGRFConfigList(GRFConfigList &config)
Clear a GRF Config list, freeing all nodes.
void StateGameLoop()
State controlling game loop.
Definition openttd.cpp:1197
PauseMode
Modes of pausing we've got.
Definition openttd.h:71
@ LinkGraph
A game paused due to the link graph schedule lagging.
Definition openttd.h:78
@ Error
A game paused because a (critical) error.
Definition openttd.h:75
@ GameScript
A game paused by a game script.
Definition openttd.h:77
@ ActiveClients
A game paused for 'min_active_clients'.
Definition openttd.h:76
@ Normal
A game normally paused.
Definition openttd.h:72
@ Join
A game paused for 'pause_on_join'.
Definition openttd.h:74
@ Menu
In the main menu.
Definition openttd.h:19
@ JoinGame
Join a network game.
Definition openttd.h:41
@ Menu
Switch to game intro menu.
Definition openttd.h:33
EnumBitSet< PauseMode, uint8_t > PauseModes
Bitset of PauseMode elements.
Definition openttd.h:83
Some methods of Pool are placed here in order to reduce compilation time and binary size.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
@ NetworkClient
Network client pools.
Definition pool_type.hpp:18
@ NetworkAdmin
Network admin pool.
Definition pool_type.hpp:19
EnumBitSet< PoolType, uint8_t > PoolTypes
Bitset of PoolType elements.
Definition pool_type.hpp:24
Randomizer _random
Random used in the game state calculations.
Pseudo random number generator.
A number of safeguards to prevent using unsafe methods.
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:261
std::string FormatArrayAsHex(std::span< const uint8_t > data)
Format a byte array into a continuous hex string.
Definition string.cpp:76
bool StrEqualsIgnoreCase(std::string_view str1, std::string_view str2)
Compares two string( view)s for equality, while ignoring the case of the characters.
Definition string.cpp:324
void StrTrimInPlace(std::string &str)
Trim the spaces from given string in place, i.e.
Definition string.cpp:229
Compose strings from textual and binary data.
Parse strings.
Functions related to low-level strings.
static const char32_t CHAR_TD_LRM
The next character acts like a left-to-right character.
Definition string_type.h:35
static const char32_t CHAR_TD_RLM
The next character acts like a right-to-left character.
Definition string_type.h:36
std::vector< std::string > StringList
Type for a list of strings.
Definition string_type.h:61
void GetStringWithArgs(StringBuilder &builder, StringID string, StringParameters &args, uint case_index, bool game_script)
Get a parsed string with most special stringcodes replaced by the string parameters.
Definition strings.cpp:335
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:423
TextDirection _current_text_dir
Text direction of the currently selected language.
Definition strings.cpp:55
Functions related to OTTD's strings.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
@ TD_LTR
Text is written left-to-right by default.
Everything we need to know about a command to be able to execute it.
StringID err_msg
string ID of error message to use.
CommandDataBuffer data
command parameters.
CompanyID company
company that is executing the command
Commands cmd
command being executed.
Defines the traits of a command.
NetworkAuthorizedKeys allow_list
Public keys of clients that are allowed to join this company.
bool allow_any
Set if anyone is allowed to join this company.
StringID name_1
Name of the company if the user did not change it.
std::string name
Name of the company if the user changed it.
Container for the text colour and some text colour related flags for drawing.
Definition gfx_type.h:349
Container for all information known about a client.
static NetworkClientInfo * GetByClientID(ClientID client_id)
Return the CI given it's client-identifier.
Definition network.cpp:114
~NetworkClientInfo()
Basically a client is leaving us right now.
Definition network.cpp:103
bool CanJoinCompany(CompanyID company_id) const
Returns whether the given company can be joined by this client.
Definition network.cpp:128
CompanyID client_playas
As which company is this client playing (CompanyID).
ClientID client_id
Client identifier (same as ClientState->client_id).
NetworkClientInfo(ClientPoolID index, ClientID client_id=ClientID::Invalid)
Create a new client.
std::string client_name
Name of the client.
std::string public_key
The public key of the client.
Structure with information shown in the game list (GUI).
bool refreshing
Whether this server is being queried.
int version
Used to see which servers are no longer available on the Game Coordinator and can be removed.
NetworkGameInfo info
The game information of this server.
bool manually
True if the server was added manually.
NetworkGameStatus status
Stats of the server.
GRFConfigList grfconfig
List of NewGRF files used.
std::string server_name
Server name.
static void Clean(PoolTypes)
Clean all pools of given type.
Definition pool_func.cpp:30
static Pool::IterateWrapper< NetworkClientInfo > Iterate(size_t from=0)
static Company * GetIfValid(auto index)
The data required to format and validate a single parameter of a string.
Definition of the game-economy-timer.
Definition of the tick-based game-timer.
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:1242
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:3377
Window functions not directly related to making/drawing windows.
@ Join
Network join status.
Definition window_type.h:56