29#include "../3rdparty/md5/md5.h"
41#ifdef DEBUG_DUMP_COMMANDS
47#include "table/strings.h"
51#ifdef DEBUG_DUMP_COMMANDS
57bool _ddc_fastforward =
true;
84#ifdef NETWORK_SEND_DOUBLE_SEED
93extern std::string
GenerateUid(std::string_view subject);
101 return !NetworkClientSocket::Iterate().empty();
121 if (ci->client_id ==
client_id)
return ci;
157 if (cs->client_id ==
client_id)
return cs;
170static auto FindKey(
auto *authorized_keys, std::string_view authorized_key)
172 return std::ranges::find_if(*authorized_keys, [authorized_key](
auto &value) {
return StrEqualsIgnoreCase(value, authorized_key); });
182 return FindKey(
this, key) != this->end();
192 if (key.empty())
return false;
194 auto iter =
FindKey(
this, key);
195 if (iter != this->end())
return false;
197 this->emplace_back(key);
208 auto iter =
FindKey(
this, key);
209 if (iter == this->end())
return false;
216uint8_t NetworkSpectatorCount()
246 case NETWORK_ACTION_SERVER_MESSAGE:
248 builder +=
GetString(STR_NETWORK_SERVER_MESSAGE, str);
251 case NETWORK_ACTION_COMPANY_SPECTATOR:
253 builder +=
GetString(STR_NETWORK_MESSAGE_CLIENT_COMPANY_SPECTATE, name);
255 case NETWORK_ACTION_COMPANY_JOIN:
257 builder +=
GetString(STR_NETWORK_MESSAGE_CLIENT_COMPANY_JOIN, name, str);
259 case NETWORK_ACTION_COMPANY_NEW:
261 builder +=
GetString(STR_NETWORK_MESSAGE_CLIENT_COMPANY_NEW, name, std::move(data));
263 case NETWORK_ACTION_JOIN:
266 GetString(STR_NETWORK_MESSAGE_CLIENT_JOINED_ID, name, std::move(data)) :
267 GetString(STR_NETWORK_MESSAGE_CLIENT_JOINED, name);
269 case NETWORK_ACTION_LEAVE: builder +=
GetString(STR_NETWORK_MESSAGE_CLIENT_LEFT, name, std::move(data));
break;
270 case NETWORK_ACTION_NAME_CHANGE: builder +=
GetString(STR_NETWORK_MESSAGE_NAME_CHANGE, name, str);
break;
271 case NETWORK_ACTION_GIVE_MONEY: builder +=
GetString(STR_NETWORK_MESSAGE_GIVE_MONEY, name, std::move(data), str);
break;
272 case NETWORK_ACTION_KICKED: builder +=
GetString(STR_NETWORK_MESSAGE_KICKED, name, str);
break;
273 case NETWORK_ACTION_CHAT_COMPANY: builder +=
GetString(self_send ? STR_NETWORK_CHAT_TO_COMPANY : STR_NETWORK_CHAT_COMPANY, name, str);
break;
274 case NETWORK_ACTION_CHAT_CLIENT: builder +=
GetString(self_send ? STR_NETWORK_CHAT_TO_CLIENT : STR_NETWORK_CHAT_CLIENT, name, str);
break;
275 case NETWORK_ACTION_EXTERNAL_CHAT: builder +=
GetString(STR_NETWORK_CHAT_EXTERNAL, std::move(data), name, str);
break;
276 default: builder +=
GetString(STR_NETWORK_CHAT_ALL, name, str);
break;
285uint NetworkCalculateLag(
const NetworkClientSocket *cs)
287 int lag = cs->last_frame_server - cs->last_frame;
300void ShowNetworkError(
StringID error_string)
351 switch (changed_mode) {
359 if (!paused && !changed)
return;
363 std::array<StringParameter, 5> params{};
364 auto it = params.begin();
370 str =
GetStringWithArgs(STR_NETWORK_SERVER_MESSAGE_GAME_STILL_PAUSED_1 + std::distance(params.begin(), it) - 1, {params.begin(), it});
373 switch (changed_mode) {
374 case PauseMode::Normal: reason = STR_NETWORK_SERVER_MESSAGE_GAME_REASON_MANUAL;
break;
375 case PauseMode::Join: reason = STR_NETWORK_SERVER_MESSAGE_GAME_REASON_CONNECTING_CLIENTS;
break;
379 default: NOT_REACHED();
381 str =
GetString(paused ? STR_NETWORK_SERVER_MESSAGE_GAME_PAUSED : STR_NETWORK_SERVER_MESSAGE_GAME_UNPAUSED, reason);
384 NetworkTextMessage(NETWORK_ACTION_SERVER_MESSAGE,
CC_DEFAULT,
false,
"", str);
406 Command<Commands::Pause>::Post(pm, pause);
418 for (
const NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
419 if (cs->status != NetworkClientSocket::STATUS_ACTIVE)
continue;
446 for (
const NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
447 if (cs->status >= NetworkClientSocket::STATUS_AUTHORIZED && cs->status < NetworkClientSocket::STATUS_ACTIVE)
return true;
473 std::string_view ip = connection_string;
474 if (company_id ==
nullptr)
return ip;
476 size_t offset = ip.find_last_of(
'#');
477 if (offset != std::string::npos) {
478 std::string_view company_string = ip.substr(offset + 1);
479 ip = ip.substr(0, offset);
481 uint8_t company_value;
482 auto [_, err] = std::from_chars(company_string.data(), company_string.data() + company_string.size(), company_value);
483 if (err == std::errc()) {
485 if (company_value > MAX_COMPANIES || company_value == 0) {
489 *company_id = (CompanyID)(company_value - 1);
492 *company_id = (CompanyID)company_value;
519 size_t port_offset = ip.find_last_of(
':');
520 size_t ipv6_close = ip.find_last_of(
']');
521 if (port_offset != std::string::npos && (ipv6_close == std::string::npos || ipv6_close < port_offset)) {
522 std::string_view port_string = ip.substr(port_offset + 1);
523 ip = ip.substr(0, port_offset);
524 std::from_chars(port_string.data(), port_string.data() + port_string.size(), port);
537 uint16_t port = default_port;
539 return fmt::format(
"{}:{}", ip, port);
552 uint16_t port = default_port;
593 as->CloseConnection(
true);
597 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
625static void NetworkInitialize(
bool close_admins =
true)
638 std::string connection_string;
645 Debug(net, 9,
"Query::OnFailure(): connection_string={}", this->connection_string);
656 Debug(net, 9,
"Query::OnConnect(): connection_string={}", this->connection_string);
670 Debug(net, 9,
"NetworkQueryServer(): connection_string={}", connection_string);
690 if (connection_string.empty())
return nullptr;
703 if (manually) item->
manually =
true;
704 if (never_expire) item->
version = INT32_MAX;
717 addresses->emplace_back(iter, port);
721 if (addresses->empty()) {
722 addresses->emplace_back(
"", port);
742 std::string connection_string;
749 Debug(net, 9,
"Client::OnFailure(): connection_string={}", this->connection_string);
751 ShowNetworkError(STR_NETWORK_ERROR_NOCONNECTION);
756 Debug(net, 9,
"Client::OnConnect(): connection_string={}", this->connection_string);
782bool NetworkClientConnectGame(std::string_view connection_string, CompanyID default_company,
const std::string &join_server_password)
784 Debug(net, 9,
"NetworkClientConnectGame(): connection_string={}", connection_string);
786 CompanyID join_as = default_company;
792 _network_join.connection_string = std::move(resolved_connection_string);
796 if (_game_mode == GM_MENU) {
821 Debug(net, 9,
"status = Connecting");
823 ShowJoinStatusWindow();
828static void NetworkInitGameInfo()
858 if (!server_name.empty())
return true;
872 static const std::string fallback_client_name =
"Unnamed Client";
875 Debug(net, 1,
"No \"client_name\" has been set, using \"{}\" instead. Please set this now using the \"name <new name>\" command", fallback_client_name);
879 static const std::string fallback_server_name =
"Unnamed Server";
882 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);
887bool NetworkServerStart()
899 NetworkInitialize(
false);
901 Debug(net, 5,
"Starting listeners for clients");
906 Debug(net, 5,
"Starting listeners for admins");
911 Debug(net, 5,
"Starting listeners for incoming server queries");
924 NetworkInitGameInfo();
954 if (c !=
nullptr && ci !=
nullptr) {
978 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1001 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1105 static TimerGameEconomy::Date last_log;
1112#ifdef DEBUG_DUMP_COMMANDS
1115 static TimerGameEconomy::Date next_date(0);
1116 static uint32_t next_date_fract;
1118 static bool check_sync_state =
false;
1119 static uint32_t sync_state[2];
1120 if (!f.has_value() && next_date == 0) {
1121 Debug(desync, 0,
"Cannot open commands.log");
1122 next_date = TimerGameEconomy::Date(1);
1125 while (f.has_value() && !feof(*f)) {
1127 if (cp !=
nullptr) {
1133 if (check_sync_state) {
1134 if (sync_state[0] ==
_random.state[0] && sync_state[1] ==
_random.state[1]) {
1137 Debug(desync, 0,
"Sync check: {:08x}; {:02x}; mismatch expected {{{:08x}, {:08x}}}, got {{{:08x}, {:08x}}}",
1141 check_sync_state =
false;
1147 Debug(desync, 0,
"Skipping to next command at {:08x}:{:02x}", next_date, next_date_fract);
1148 if (cp !=
nullptr) {
1152 check_sync_state =
false;
1155 if (cp !=
nullptr || check_sync_state)
break;
1158 if (fgets(buff,
lengthof(buff), *f) ==
nullptr)
break;
1167 if (consumer.
ReadIf(
"cmd: ")
1168#ifdef DEBUG_FAILED_DUMP_COMMANDS
1169 || consumer.
ReadIf(
"cmdf: ")
1173 next_date = TimerGameEconomy::Date(consumer.
ReadIntegerBase<uint32_t>(16));
1174 bool valid = consumer.
ReadIf(
"; ");
1176 valid &= consumer.
ReadIf(
"; ");
1178 valid &= consumer.
ReadIf(
"; ");
1180 valid &= consumer.
ReadIf(
"; ");
1182 valid &= consumer.
ReadIf(
"; ");
1188 for (
size_t i = 0; i + 1 < args.size(); i += 2) {
1190 std::from_chars(args.data() + i, args.data() + i + 2, e, 16);
1191 cp->
data.push_back(e);
1193 }
else if (consumer.
ReadIf(
"join: ")) {
1195 next_date = TimerGameEconomy::Date(consumer.
ReadIntegerBase<uint32_t>(16));
1196 bool valid = consumer.
ReadIf(
"; ");
1199 Debug(desync, 0,
"Injecting pause for join at {:08x}:{:02x}; please join when paused", next_date, next_date_fract);
1204 _ddc_fastforward =
false;
1205 }
else if (consumer.
ReadIf(
"sync: ")) {
1206 next_date = TimerGameEconomy::Date(consumer.
ReadIntegerBase<uint32_t>(16));
1207 bool valid = consumer.
ReadIf(
"; ");
1209 valid &= consumer.
ReadIf(
"; ");
1211 valid &= consumer.
ReadIf(
"; ");
1214 check_sync_state =
true;
1215 }
else if (consumer.
ReadIf(
"msg: ") || consumer.
ReadIf(
"client: ") ||
1216 consumer.
ReadIf(
"load: ") || consumer.
ReadIf(
"save: ") ||
1217 consumer.
ReadIf(
"warning: ")) {
1219#ifndef DEBUG_FAILED_DUMP_COMMANDS
1220 }
else if (consumer.
ReadIf(
"cmdf: ")) {
1229 if (f.has_value() && feof(*f)) {
1230 Debug(desync, 0,
"End of commands.log");
1243 bool send_frame =
false;
1259#ifdef NETWORK_SEND_DOUBLE_SEED
1260 _sync_seed_2 =
_random.state[1];
1288 Debug(net, 3,
"Starting network");
1296 NetworkInitialize();
1298 Debug(net, 3,
"Network online, multiplayer available");
1310 Debug(net, 3,
"Shutting down network");
1317#ifdef __EMSCRIPTEN__
1320void CDECL em_openttd_add_server(
const char *connection_string)
std::vector< NetworkAddress > NetworkAddressList
Type for a list of addresses.
constexpr bool None() const
Test if none of the values are set.
constexpr Timpl & Set()
Set all bits.
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...
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.
bool Add(std::string_view key)
Add the given key to the authorized keys, when it is not already contained.
bool Remove(std::string_view key)
Remove the given key from the authorized keys, when it is exists.
static void ProcessDeferredDeletions()
Actually delete the socket handlers that were marked for deletion.
ClientID client_id
Client identifier.
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.
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,...
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.
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.
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.
void OnFailure() override
Callback for when the connection attempt failed.
std::string connection_string
Current address we are connecting to (before resolving).
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...
static void KillAll()
Kill all connection attempts.
static bool Listen(uint16_t port)
static void CloseListeners()
void OnConnect(SOCKET s) override
Callback when the connection succeeded.
void OnFailure() override
Callback for when the connection attempt failed.
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.
std::string_view GetCommandName(Commands cmd)
Get the name of the given command.
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.
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).
void IConsoleCmdExec(std::string_view command_string, const uint recurse_count)
Execute a given command passed to us.
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.
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.
bool NetworkCoreInitialize()
Initializes the network core (as that is needed for some platforms.
@ NETWORK_RECV_STATUS_CLIENT_QUIT
The connection is lost gracefully. Other clients are already informed of this leaving client.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Functions related to errors.
@ WL_ERROR
Errors (eg. saving/loading failed).
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
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.
Functions for standard in/out file operations.
@ SAVE_DIR
Base directory for all savegames.
PauseModes _pause_mode
The current pause mode.
SwitchMode _switch_mode
The next mainloop command.
Functions related to the gfx engine.
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
void NetworkFindBroadcastIPs(NetworkAddressList *broadcast)
Find the IPv4 broadcast addresses; IPv6 uses a completely different strategy for broadcasting.
Resolving of hostnames/IPs.
void NetworkHTTPInitialize()
Initialize the HTTP socket handler.
void NetworkHTTPUninitialize()
Uninitialize the HTTP socket handler.
Types related to the landscape.
Miscellaneous command definitions.
uint32_t _last_sync_frame
Used in the server to store the last time a sync packet was sent to clients.
NetworkAddress ParseConnectionString(std::string_view connection_string, uint16_t default_port)
Convert a string containing either "hostname" or "hostname:ip" to a NetworkAddress.
void NetworkStartUp()
This tries to launch the network for a given OS.
bool _is_network_server
Does this client wants to be a network-server?
NetworkClientInfoPool _networkclientinfo_pool("NetworkClientInfo")
Make sure both pools have the same size.
void NetworkHandlePauseChange(PauseModes prev_mode, PauseMode changed_mode)
Handle the pause mode change so we send the right messages to the chat.
static uint NetworkCountActiveClients()
Counts the number of active clients connected.
StringList _network_host_list
The servers we know.
StringID GetNetworkErrorMsg(NetworkErrorCode err)
Retrieve a short translateable string of the error code.
uint32_t _frame_counter_server
The frame_counter of the server, if in network-mode.
static void CheckPauseOnJoin()
Check whether we should pause on join.
NetworkAddressList _broadcast_list
List of broadcast addresses.
void NetworkClientJoinGame()
Actually perform the joining to the server.
static bool NetworkHasJoiningClient()
Checks whether there is a joining client.
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.
ClientID _redirect_console_to_client
If not invalid, redirect the console output to a client.
static void CheckClientAndServerName()
Check whether the client and server name are set, for a dedicated server and if not set them to some ...
void NetworkOnGameStart()
Perform tasks when the server is started.
uint32_t _frame_counter
The current frame.
bool _network_available
is network mode available?
uint8_t _network_reconnect
Reconnect timeout.
bool _networking
are we in networking mode?
void NetworkQueryServer(std::string_view connection_string)
Query a server to fetch the game-info.
static void InitializeNetworkPools(bool close_admins=true)
Resets the pools used for network clients, and the admin pool if needed.
StringList _network_ban_list
The banned clients.
static void NetworkSend()
This sends all buffered commands (if possible).
bool _network_dedicated
are we a dedicated server?
bool HasClients()
Return whether there is any client connected or trying to connect at all.
static bool NetworkReceive()
Receives something from the network.
void NetworkGameLoop()
The main loop called from ttd.c.
void NetworkReboot()
The server is rebooting... The only difference with NetworkDisconnect, is the packets that is sent.
void NetworkDisconnect(bool close_admins)
We want to disconnect from the host/clients.
bool _network_server
network-server is active
std::string GenerateUid(std::string_view subject)
Generate an unique ID.
uint32_t _sync_seed_1
Seed to compare during sync checks.
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.
uint32_t _sync_frame
The frame to perform the sync check.
void NetworkBackgroundLoop()
We have to do some (simple) background stuff that runs normally, even when we are not in multiplayer.
StringList _network_bind_list
The addresses to bind on.
std::string NormalizeConnectionString(std::string_view connection_string, uint16_t default_port)
Normalize a connection string.
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.
static void CheckMinActiveClients()
Check if the minimum number of active clients has been reached and pause or unpause the game as appro...
void NetworkRebuildHostList()
Generates the list of manually added hosts from NetworkGame and dumps them into the array _network_ho...
ClientID _network_own_client_id
Our client identifier.
std::string_view ParseCompanyFromConnectionString(std::string_view connection_string, CompanyID *company_id)
Parse the company part ("#company" postfix) of a connecting string.
static void CheckPauseHelper(bool pause, PauseMode pm)
Helper function for the pause checkers.
bool _network_first_time
Whether we have finished joining or not.
void NetworkShutDown()
This shuts the network down.
uint8_t _network_clients_connected
The amount of clients connected.
void GetBindAddresses(NetworkAddressList *addresses, uint16_t port)
Get the addresses to bind to.
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.
void NetworkUpdateServerGameType()
The setting server_game_type was updated; possibly we need to take some action.
bool NetworkCanJoinCompany(CompanyID company_id)
Returns whether the given company can be joined by this client.
void NetworkClose(bool close_admins)
Close current connections.
uint32_t _frame_counter_max
To where we may go with our clients.
bool NetworkValidateServerName(std::string &server_name)
Trim the given server name in place, i.e.
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(TextColour 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.
@ NGLS_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.
GUIs related to networking.
@ Connecting
Opening the connection to the server.
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.
@ DESTTYPE_CLIENT
Send message/notice to only a certain client (Private).
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.
ClientID
'Unique' identifier to be given to clients
@ CLIENT_ID_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.
PauseMode
Modes of pausing we've got.
@ LinkGraph
A game paused due to the link graph schedule lagging.
@ Error
A game paused because a (critical) error.
@ GameScript
A game paused by a game script.
@ ActiveClients
A game paused for 'min_active_clients'.
@ Normal
A game normally paused.
@ Join
A game paused for 'pause_on_join'.
@ SM_JOIN_GAME
Join a network game.
@ SM_MENU
Switch to game intro menu.
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.
@ NetworkAdmin
Network admin pool.
Randomizer _random
Random used in the game state calculations.
Pseudo random number generator.
Declaration of OTTD revision dependent variables.
A number of safeguards to prevent using unsafe methods.
ClientSettings _settings_client
The current settings for this game.
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
std::string FormatArrayAsHex(std::span< const uint8_t > data)
Format a byte array into a continuous hex string.
bool StrEqualsIgnoreCase(std::string_view str1, std::string_view str2)
Compares two string( view)s for equality, while ignoring the case of the characters.
void StrTrimInPlace(std::string &str)
Trim the spaces from given string in place, i.e.
Compose strings from textual and binary data.
static const char32_t CHAR_TD_LRM
The next character acts like a left-to-right character.
static const char32_t CHAR_TD_RLM
The next character acts like a right-to-left character.
std::vector< std::string > StringList
Type for a list of strings.
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.
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
TextDirection _current_text_dir
Text direction of the currently selected language.
Functions related to OTTD's strings.
uint32_t 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 all information known about a client.
static NetworkClientInfo * GetByClientID(ClientID client_id)
Return the CI given it's client-identifier.
~NetworkClientInfo()
Basically a client is leaving us right now.
bool CanJoinCompany(CompanyID company_id) const
Returns whether the given company can be joined by this client.
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=INVALID_CLIENT_ID)
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.
static Pool::IterateWrapper< NetworkClientInfo > Iterate(size_t from=0)
static bool CanAllocateItem(size_t n=1)
static bool IsValidID(auto index)
static T * Create(Targs &&... args)
static Company * GetIfValid(auto index)
static constexpr size_t MAX_SIZE
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.
Basic functions to receive and send UDP packets.
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
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-...
Window functions not directly related to making/drawing windows.
@ WN_NETWORK_STATUS_WINDOW_JOIN
Network join status.
@ WC_SEND_NETWORK_MSG
Chatbox; Window numbers:
@ WC_CLIENT_LIST
Client list; Window numbers:
@ WC_NETWORK_STATUS_WINDOW
Network status window; Window numbers: