OpenTTD Source
20240917-master-g9ab0a47812
|
Go to the documentation of this file.
10 #include "../stdafx.h"
12 #include "../strings_func.h"
13 #include "../command_func.h"
14 #include "../timer/timer_game_tick.h"
15 #include "../timer/timer_game_economy.h"
28 #include "../console_func.h"
29 #include "../3rdparty/md5/md5.h"
30 #include "../core/random_func.hpp"
31 #include "../window_func.h"
32 #include "../company_func.h"
33 #include "../company_base.h"
34 #include "../landscape_type.h"
36 #include "../core/pool_func.hpp"
37 #include "../gfx_func.h"
39 #include "../misc_cmd.h"
40 #ifdef DEBUG_DUMP_COMMANDS
41 # include "../fileio_func.h"
47 #include "../safeguards.h"
49 #ifdef DEBUG_DUMP_COMMANDS
55 bool _ddc_fastforward =
true;
82 #ifdef NETWORK_SEND_DOUBLE_SEED
83 uint32_t _sync_seed_2;
93 extern std::string
GenerateUid(std::string_view subject);
101 return !NetworkClientSocket::Iterate().empty();
121 if (ci->client_id ==
client_id)
return ci;
156 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
157 if (cs->client_id ==
client_id)
return cs;
170 static auto FindKey(
auto *authorized_keys, std::string_view authorized_key)
172 return std::find_if(authorized_keys->begin(), authorized_keys->end(), [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;
216 uint8_t NetworkSpectatorCount()
234 void NetworkTextMessage(
NetworkAction action,
TextColour colour,
bool self_send,
const std::string &name,
const std::string &str, int64_t data,
const std::string &data_str)
238 case NETWORK_ACTION_SERVER_MESSAGE:
240 strid = STR_NETWORK_SERVER_MESSAGE;
243 case NETWORK_ACTION_COMPANY_SPECTATOR:
245 strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_SPECTATE;
247 case NETWORK_ACTION_COMPANY_JOIN:
249 strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_JOIN;
251 case NETWORK_ACTION_COMPANY_NEW:
253 strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_NEW;
255 case NETWORK_ACTION_JOIN:
257 strid =
_network_server ? STR_NETWORK_MESSAGE_CLIENT_JOINED_ID : STR_NETWORK_MESSAGE_CLIENT_JOINED;
259 case NETWORK_ACTION_LEAVE: strid = STR_NETWORK_MESSAGE_CLIENT_LEFT;
break;
260 case NETWORK_ACTION_NAME_CHANGE: strid = STR_NETWORK_MESSAGE_NAME_CHANGE;
break;
261 case NETWORK_ACTION_GIVE_MONEY: strid = STR_NETWORK_MESSAGE_GIVE_MONEY;
break;
262 case NETWORK_ACTION_CHAT_COMPANY: strid = self_send ? STR_NETWORK_CHAT_TO_COMPANY : STR_NETWORK_CHAT_COMPANY;
break;
263 case NETWORK_ACTION_CHAT_CLIENT: strid = self_send ? STR_NETWORK_CHAT_TO_CLIENT : STR_NETWORK_CHAT_CLIENT;
break;
264 case NETWORK_ACTION_KICKED: strid = STR_NETWORK_MESSAGE_KICKED;
break;
265 case NETWORK_ACTION_EXTERNAL_CHAT: strid = STR_NETWORK_CHAT_EXTERNAL;
break;
266 default: strid = STR_NETWORK_CHAT_ALL;
break;
278 std::ostringstream stream;
279 std::ostreambuf_iterator<char> iterator(stream);
281 std::string message = stream.str() +
GetString(strid);
289 uint NetworkCalculateLag(
const NetworkClientSocket *cs)
291 int lag = cs->last_frame_server - cs->last_frame;
304 void ShowNetworkError(
StringID error_string)
319 static const StringID network_error_strings[] = {
320 STR_NETWORK_ERROR_CLIENT_GENERAL,
321 STR_NETWORK_ERROR_CLIENT_DESYNC,
322 STR_NETWORK_ERROR_CLIENT_SAVEGAME,
323 STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST,
324 STR_NETWORK_ERROR_CLIENT_PROTOCOL_ERROR,
325 STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH,
326 STR_NETWORK_ERROR_CLIENT_NOT_AUTHORIZED,
327 STR_NETWORK_ERROR_CLIENT_NOT_EXPECTED,
328 STR_NETWORK_ERROR_CLIENT_WRONG_REVISION,
329 STR_NETWORK_ERROR_CLIENT_NAME_IN_USE,
330 STR_NETWORK_ERROR_CLIENT_WRONG_PASSWORD,
331 STR_NETWORK_ERROR_CLIENT_COMPANY_MISMATCH,
332 STR_NETWORK_ERROR_CLIENT_KICKED,
333 STR_NETWORK_ERROR_CLIENT_CHEATER,
334 STR_NETWORK_ERROR_CLIENT_SERVER_FULL,
335 STR_NETWORK_ERROR_CLIENT_TOO_MANY_COMMANDS,
336 STR_NETWORK_ERROR_CLIENT_TIMEOUT_PASSWORD,
337 STR_NETWORK_ERROR_CLIENT_TIMEOUT_COMPUTER,
338 STR_NETWORK_ERROR_CLIENT_TIMEOUT_MAP,
339 STR_NETWORK_ERROR_CLIENT_TIMEOUT_JOIN,
340 STR_NETWORK_ERROR_CLIENT_INVALID_CLIENT_NAME,
341 STR_NETWORK_ERROR_CLIENT_NOT_ON_ALLOW_LIST,
342 STR_NETWORK_ERROR_CLIENT_NO_AUTHENTICATION_METHOD_AVAILABLE,
344 static_assert(
lengthof(network_error_strings) == NETWORK_ERROR_END);
346 if (err >= (ptrdiff_t)
lengthof(network_error_strings)) err = NETWORK_ERROR_GENERAL;
348 return network_error_strings[err];
360 switch (changed_mode) {
368 if (!paused && !changed)
return;
379 str = STR_NETWORK_SERVER_MESSAGE_GAME_STILL_PAUSED_1 + i;
381 switch (changed_mode) {
387 default: NOT_REACHED();
389 str = paused ? STR_NETWORK_SERVER_MESSAGE_GAME_PAUSED : STR_NETWORK_SERVER_MESSAGE_GAME_UNPAUSED;
426 for (
const NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
427 if (cs->status != NetworkClientSocket::STATUS_ACTIVE)
continue;
454 for (
const NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
455 if (cs->status >= NetworkClientSocket::STATUS_AUTHORIZED && cs->status < NetworkClientSocket::STATUS_ACTIVE)
return true;
481 std::string_view ip = connection_string;
482 if (company_id ==
nullptr)
return ip;
484 size_t offset = ip.find_last_of(
'#');
485 if (offset != std::string::npos) {
486 std::string_view company_string = ip.substr(offset + 1);
487 ip = ip.substr(0, offset);
489 uint8_t company_value;
490 auto [_, err] = std::from_chars(company_string.data(), company_string.data() + company_string.size(), company_value);
491 if (err == std::errc()) {
497 *company_id = (
CompanyID)(company_value - 1);
527 size_t port_offset = ip.find_last_of(
':');
528 size_t ipv6_close = ip.find_last_of(
']');
529 if (port_offset != std::string::npos && (ipv6_close == std::string::npos || ipv6_close < port_offset)) {
530 std::string_view port_string = ip.substr(port_offset + 1);
531 ip = ip.substr(0, port_offset);
532 std::from_chars(port_string.data(), port_string.data() + port_string.size(), port);
545 uint16_t port = default_port;
547 return std::string(ip) +
":" + std::to_string(port);
560 uint16_t port = default_port;
599 as->CloseConnection(
true);
603 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
618 NetworkGameSocketHandler::ProcessDeferredDeletions();
631 static void NetworkInitialize(
bool close_admins =
true)
644 std::string connection_string;
651 Debug(net, 9,
"Query::OnFailure(): connection_string={}", this->connection_string);
660 void OnConnect(SOCKET s)
override
662 Debug(net, 9,
"Query::OnConnect(): connection_string={}", this->connection_string);
676 Debug(net, 9,
"NetworkQueryServer(): connection_string={}", connection_string);
682 TCPConnecter::Create<TCPQueryConnecter>(connection_string);
696 if (connection_string.empty())
return nullptr;
709 if (manually) item->
manually =
true;
710 if (never_expire) item->
version = INT32_MAX;
723 addresses->emplace_back(iter.c_str(), port);
727 if (addresses->empty()) {
728 addresses->emplace_back(
"", port);
735 void NetworkRebuildHostList()
747 std::string connection_string;
754 Debug(net, 9,
"Client::OnFailure(): connection_string={}", this->connection_string);
756 ShowNetworkError(STR_NETWORK_ERROR_NOCONNECTION);
759 void OnConnect(SOCKET s)
override
761 Debug(net, 9,
"Client::OnConnect(): connection_string={}", this->connection_string);
789 Debug(net, 9,
"NetworkClientConnectGame(): connection_string={}", connection_string);
801 if (_game_mode == GM_MENU) {
826 Debug(net, 9,
"status = CONNECTING");
828 ShowJoinStatusWindow();
833 static void NetworkInitGameInfo()
835 FillStaticNetworkServerGameInfo();
863 if (!server_name.empty())
return true;
877 static const std::string fallback_client_name =
"Unnamed Client";
880 Debug(net, 1,
"No \"client_name\" has been set, using \"{}\" instead. Please set this now using the \"name <new name>\" command", fallback_client_name);
884 static const std::string fallback_server_name =
"Unnamed Server";
887 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);
892 bool NetworkServerStart()
904 NetworkInitialize(
false);
906 Debug(net, 5,
"Starting listeners for clients");
911 Debug(net, 5,
"Starting listeners for admins");
916 Debug(net, 5,
"Starting listeners for incoming server queries");
929 NetworkInitGameInfo();
959 if (c !=
nullptr && ci !=
nullptr) {
981 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1004 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1034 case SERVER_GAME_TYPE_LOCAL:
1038 case SERVER_GAME_TYPE_INVITE_ONLY:
1039 case SERVER_GAME_TYPE_PUBLIC:
1061 NetworkGameSocketHandler::ProcessDeferredDeletions();
1066 static void NetworkSend()
1074 NetworkGameSocketHandler::ProcessDeferredDeletions();
1089 NetworkGameSocketHandler::ProcessDeferredDeletions();
1096 void NetworkGameLoop()
1106 static TimerGameEconomy::Date last_log;
1113 #ifdef DEBUG_DUMP_COMMANDS
1116 static TimerGameEconomy::Date next_date(0);
1117 static uint32_t next_date_fract;
1119 static bool check_sync_state =
false;
1120 static uint32_t sync_state[2];
1121 if (!f.has_value() && next_date == 0) {
1122 Debug(desync, 0,
"Cannot open commands.log");
1123 next_date = TimerGameEconomy::Date(1);
1126 while (f.has_value() && !feof(*f)) {
1128 if (cp !=
nullptr) {
1134 if (check_sync_state) {
1138 Debug(desync, 0,
"Sync check: {:08x}; {:02x}; mismatch expected {{{:08x}, {:08x}}}, got {{{:08x}, {:08x}}}",
1142 check_sync_state =
false;
1148 Debug(desync, 0,
"Skipping to next command at {:08x}:{:02x}", next_date, next_date_fract);
1149 if (cp !=
nullptr) {
1153 check_sync_state =
false;
1156 if (cp !=
nullptr || check_sync_state)
break;
1159 if (fgets(buff,
lengthof(buff), *f) ==
nullptr)
break;
1165 if (p ==
nullptr)
break;
1169 if (strncmp(p,
"cmd: ", 5) == 0
1170 #ifdef DEBUG_FAILED_DUMP_COMMANDS
1171 || strncmp(p,
"cmdf: ", 6) == 0
1180 uint32_t next_date_raw;
1181 int ret = sscanf(p,
"%x; %x; %x; %x; %x; %255s", &next_date_raw, &next_date_fract, &company, &cmd, &cp->
err_msg, buffer);
1183 next_date = TimerGameEconomy::Date((int32_t)next_date_raw);
1188 std::vector<uint8_t> args;
1189 size_t arg_len = strlen(buffer);
1190 for (
size_t i = 0; i + 1 < arg_len; i += 2) {
1192 std::from_chars(buffer + i, buffer + i + 2, e, 16);
1193 args.emplace_back(e);
1196 }
else if (strncmp(p,
"join: ", 6) == 0) {
1198 uint32_t next_date_raw;
1199 int ret = sscanf(p + 6,
"%x; %x", &next_date_raw, &next_date_fract);
1200 next_date = TimerGameEconomy::Date((int32_t)next_date_raw);
1202 Debug(desync, 0,
"Injecting pause for join at {:08x}:{:02x}; please join when paused", next_date, next_date_fract);
1207 _ddc_fastforward =
false;
1208 }
else if (strncmp(p,
"sync: ", 6) == 0) {
1209 uint32_t next_date_raw;
1210 int ret = sscanf(p + 6,
"%x; %x; %x; %x", &next_date_raw, &next_date_fract, &sync_state[0], &sync_state[1]);
1211 next_date = TimerGameEconomy::Date((int32_t)next_date_raw);
1213 check_sync_state =
true;
1214 }
else if (strncmp(p,
"msg: ", 5) == 0 || strncmp(p,
"client: ", 8) == 0 ||
1215 strncmp(p,
"load: ", 6) == 0 || strncmp(p,
"save: ", 6) == 0 ||
1216 strncmp(p,
"warning: ", 9) == 0) {
1218 #ifndef DEBUG_FAILED_DUMP_COMMANDS
1219 }
else if (strncmp(p,
"cmdf: ", 6) == 0) {
1220 Debug(desync, 0,
"Skipping replay of failed command: {}", p + 6);
1224 Debug(desync, 0,
"Trying to parse: {}", p);
1228 if (f.has_value() && feof(*f)) {
1229 Debug(desync, 0,
"End of commands.log");
1242 bool send_frame =
false;
1258 #ifdef NETWORK_SEND_DOUBLE_SEED
1287 Debug(net, 3,
"Starting network");
1293 _network_game_info = {};
1295 NetworkInitialize();
1297 Debug(net, 3,
"Network online, multiplayer available");
1309 Debug(net, 3,
"Shutting down network");
1316 #ifdef __EMSCRIPTEN__
1319 void CDECL em_openttd_add_server(
const char *connection_string)
static void CheckCallbacks()
Check whether we need to call the callback, i.e.
bool NetworkValidateServerName(std::string &server_name)
Trim the given server name in place, i.e.
uint8_t frame_freq
how often do we send commands to the clients
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-...
@ NETWORK_RECV_STATUS_CLIENT_QUIT
The connection is lost gracefully. Other clients are already informed of this leaving client.
@ SAVE_DIR
Base directory for all savegames.
void SendReceive()
Check whether we received/can send some data from/to the content server and when that's the case hand...
uint8_t _network_clients_connected
The amount of clients connected.
bool NetworkValidateOurClientName()
Convenience method for NetworkValidateClientName on _settings_client.network.client_name.
NetworkGameList * NetworkAddServer(const std::string &connection_string, bool manually, bool never_expire)
Validates an address entered as a string and adds the server to the list.
void ShowErrorMessage(StringID summary_msg, int x, int y, CommandCost cc)
Display an error message in a window.
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
std::string NormalizeConnectionString(const std::string &connection_string, uint16_t default_port)
Normalize a connection string.
std::string client_name
Name of the client.
void ClearGRFConfigList(GRFConfig **config)
Clear a GRF Config list, freeing all nodes.
void NetworkUDPServerListen()
Start the listening of the UDP server component.
@ PM_PAUSED_ERROR
A game paused because a (critical) error.
CompanyID client_playas
As which company is this client playing (CompanyID)
@ TD_LTR
Text is written left-to-right by default.
void GetBindAddresses(NetworkAddressList *addresses, uint16_t port)
Get the addresses to bind to.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
bool _network_server
network-server is active
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
NetworkAction
Actions that can be used for NetworkTextMessage.
@ WC_CLIENT_LIST
Client list; Window numbers:
@ COMPANY_NEW_COMPANY
The client wants a new company.
Owner
Enum for all companies/owners.
Tindex index
Index of this pool item.
static void WelcomeAll()
Send a Welcome packet to all connected admins.
std::string server_password
The password of the server to join.
static bool GameLoop()
Actual game loop for the client.
void OnFailure() override
Callback for when the connection attempt failed.
void ChangeNetworkRestartTime(bool reset)
Reset the automatic network restart time interval.
static bool Listen(uint16_t port)
Listen on a particular port.
static bool NetworkHasJoiningClient()
Checks whether there is a joining client.
StringID err_msg
string ID of error message to use.
std::string connection_string
The address of the server to join.
NetworkClientInfoPool _networkclientinfo_pool("NetworkClientInfo")
Make sure both pools have the same size.
bool pause_on_join
pause the game when people join
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
std::string name
Name of the company if the user changed it.
void NetworkHandlePauseChange(PauseMode prev_mode, PauseMode changed_mode)
Handle the pause mode change so we send the right messages to the chat.
static Pool::IterateWrapperFiltered< ServerNetworkAdminSocketHandler, ServerNetworkAdminSocketHandlerFilter > IterateActive(size_t from=0)
Returns an iterable ensemble of all active admin sockets.
Randomizer _random
Random used in the game state calculations.
static ServerAddress Parse(const std::string &connection_string, uint16_t default_port, CompanyID *company_id=nullptr)
Convert a string containing either "hostname", "hostname:port" or invite code to a ServerAddress,...
static DateFract date_fract
Fractional part of the day.
ClientSettings _settings_client
The current settings for this game.
StringList _network_bind_list
The addresses to bind on.
void UpdateNetworkGameWindow()
Update the network new window because a new server is found on the network.
NetworkGameList * NetworkGameListAddItem(const std::string &connection_string)
Add a new item to the linked gamelist.
void NetworkBackgroundLoop()
We have to do some (simple) background stuff that runs normally, even when we are not in multiplayer.
NetworkJoinStatus _network_join_status
The status of joining.
StringID GetNetworkErrorMsg(NetworkErrorCode err)
Retrieve the string id of an internal error number.
static ClientNetworkGameSocketHandler * my_client
This is us!
ClientID _redirect_console_to_client
If not invalid, redirect the console output to a client.
NetworkRecvStatus CloseConnection(NetworkRecvStatus status) override
Close the network connection due to the given status.
uint16_t network_chat_timeout
timeout of chat messages in seconds
Defines the traits of a command.
static const TextColour CC_DEFAULT
Default colour of the console.
bool _network_first_time
Whether we have finished joining or not.
void NetworkServer_Tick(bool send_frame)
This is called every tick if this is a _network_server.
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
static void Send()
Send the packets for the server sockets.
@ DESTTYPE_CLIENT
Send message/notice to only a certain client (Private)
bool Add(std::string_view key)
Add the given key to the authorized keys, when it is not already contained.
static const int MAX_CHAR_LENGTH
Max. length of UTF-8 encoded unicode character.
NetworkGameList * _network_game_list
Game list of this client.
static const uint MAX_LENGTH_COMPANY_NAME_CHARS
The maximum length of a company name in characters including '\0'.
~NetworkClientInfo()
Basically a client is leaving us right now.
void CloseAllConnections()
Close all pending connection tokens.
void NetworkQueryServer(const std::string &connection_string)
Query a server to fetch the game-info.
bool HasClients()
Return whether there is any client connected or trying to connect at all.
bool Remove(std::string_view key)
Remove the given key from the authorized keys, when it is exists.
uint32_t _sync_seed_1
Seed to compare during sync checks.
static constexpr size_t MAX_SIZE
Make template parameter accessible from outside.
static NetworkClientInfo * GetByClientID(ClientID client_id)
Return the CI given it's client-identifier.
void NetworkClientJoinGame()
Actually perform the joining to the server.
CompanyID company
The company to join.
CompanyID company
company that is executing the command
NetworkAddress ParseConnectionString(const std::string &connection_string, uint16_t default_port)
Convert a string containing either "hostname" or "hostname:ip" to a NetworkAddress.
static void Send()
Send the packets for the server sockets.
Everything we need to know about a command to be able to execute it.
std::string last_joined
Last joined server.
std::vector< NetworkAddress > NetworkAddressList
Type for a list of addresses.
std::string FormatArrayAsHex(std::span< const uint8_t > data)
Format a byte array into a continuous hex string.
static bool Receive()
Handle the receiving of packets.
@ PM_PAUSED_ACTIVE_CLIENTS
A game paused for 'min_active_clients'.
void StrTrimInPlace(std::string &str)
Trim the spaces from given string in place, i.e.
void IConsoleCmdExec(const std::string &command_string, const uint recurse_count)
Execute a given command passed to us.
uint32_t _last_sync_frame
Used in the server to store the last time a sync packet was sent to clients.
bool manually
True if the server was added manually.
PauseMode _pause_mode
The current pause mode.
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.
void NetworkClient_Connected()
Is called after a client is connected to the server.
void OnFailure() override
Callback for when the connection attempt failed.
NetworkRecvStatus CloseConnection(bool error=true) override
This will put this socket handler in a close state.
std::vector< std::string > StringList
Type for a list of strings.
Non blocking connection create to actually connect to servers.
std::string client_name
name of the player (as client)
#define lengthof(array)
Return the length of an fixed size array.
static void InitializeNetworkPools(bool close_admins=true)
Resets the pools used for network clients, and the admin pool if needed.
static void Clean(PoolType)
Clean all pools of given type.
void NetworkShutDown()
This shuts the network down.
@ PT_NADMIN
Network admin pool.
int version
Used to see which servers are no longer available on the Game Coordinator and can be removed.
bool _networking
are we in networking mode?
bool CanJoinCompany(CompanyID company_id) const
Returns whether the given company can be joined by this client.
static void CheckPauseHelper(bool pause, PauseMode pm)
Helper function for the pause checkers.
@ PT_NONE
No pool is selected.
static void CheckClientAndServerName()
Check whether the client and server name are set, for a dedicated server and if not set them to some ...
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.
static ServerNetworkGameSocketHandler * GetByClientID(ClientID client_id)
Return the client state given it's client-identifier.
std::string public_key
The public key of the client.
PauseMode
Modes of pausing we've got.
bool _network_dedicated
are we a dedicated server?
@ CMD_PAUSE
pause the game
void Register()
Register our server to receive our invite code.
static void KillAll()
Kill all connection attempts.
@ PM_PAUSED_LINK_GRAPH
A game paused due to the link graph schedule lagging.
static void QueryServer(SOCKET s, const std::string &connection_string)
Start to query a server based on an open socket.
static void AcceptConnection(SOCKET s, const NetworkAddress &address)
Handle the accepting of a connection to the server.
@ PT_NCLIENT
Network client pools.
static const uint16_t NETWORK_DEFAULT_PORT
The default port of the game server (TCP & UDP)
std::string_view ParseCompanyFromConnectionString(const std::string &connection_string, CompanyID *company_id)
Parse the company part ("#company" postfix) of a connecting string.
uint8_t clients_on
Current count of clients on server.
ClientID client_id
Client identifier (same as ClientState->client_id)
void NetworkDisconnect(bool close_admins)
We want to disconnect from the host/clients.
void NetworkHTTPUninitialize()
Uninitialize the HTTP socket handler.
uint16_t server_port
port the server listens on
ClientID _network_own_client_id
Our client identifier.
void NetworkBackgroundUDPLoop()
Receive the UDP packets.
std::string server_name
name of the server
void NetworkCoreShutdown()
Shuts down the network core (as that is needed for some platforms.
static bool Receive()
Check whether we received/can send some data from/to the server and when that's the case handle it ap...
ClientNetworkContentSocketHandler _network_content_client
The client we use to connect to the server.
Class for handling the server side of the game connection.
SwitchMode _switch_mode
The next mainloop command.
ServerGameType server_game_type
Server type: local / public / invite-only.
uint32_t _frame_counter_server
The frame_counter of the server, if in network-mode.
CompanyID _current_company
Company currently doing an action.
Wrapper for (un)resolved network addresses; there's no reason to transform a numeric IP to a string a...
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Base class for all pools.
ClientID
'Unique' identifier to be given to clients
void SendReceive()
Check whether we received/can send some data from/to the Game Coordinator server and when that's the ...
void NetworkSendCommand(Commands cmd, StringID err_message, CommandCallback *callback, CompanyID company, const CommandDataBuffer &cmd_data)
Prepare a DoCommand to be send over the network.
void CDECL NetworkAddChatMessage(TextColour colour, uint duration, const std::string &message)
Add a text message to the 'chat window' to be shown.
uint32_t _frame_counter
The current frame.
CommandDataBuffer data
command parameters.
void SetDParam(size_t n, uint64_t v)
Set a string parameter v at index n in the global string parameter array.
Class for handling the server side of the game connection.
static void CheckPauseOnJoin()
Check whether we should pause on join.
void NetworkServerNewCompany(const Company *company, NetworkClientInfo *ci)
Perform all the server specific administration of a new company.
uint16_t server_admin_port
port the server listens on for the admin network
@ WC_NETWORK_STATUS_WINDOW
Network status window; Window numbers:
void NetworkUDPInitialize()
Initialize the whole UDP bit.
ClientNetworkCoordinatorSocketHandler _network_coordinator_client
The connection to the Game Coordinator.
static void HTTPReceive()
Do the receiving for all HTTP connections.
std::string GetString(StringID string)
Resolve the given StringID into a std::string with all the associated DParam lookups and formatting.
const char * GetCommandName(Commands cmd)
This function mask the parameter with CMD_ID_MASK and returns the name which belongs to the given com...
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
static uint NetworkCountActiveClients()
Counts the number of active clients connected.
CompanyID GetFirstPlayableCompanyID()
Get the index of the first available company.
void SetDParamStr(size_t n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
@ PM_PAUSED_JOIN
A game paused for 'pause_on_join'.
std::optional< FileHandle > FioFOpenFile(const std::string &filename, const char *mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
@ WL_ERROR
Errors (eg. saving/loading failed)
@ SM_MENU
Switch to game intro menu.
Class for handling the client side of the game connection.
void NetworkFindBroadcastIPs(NetworkAddressList *broadcast)
Find the IPv4 broadcast addresses; IPv6 uses a completely different strategy for broadcasting.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
NetworkAuthorizedKeys allow_list
Public keys of clients that are allowed to join this company.
Structure with information shown in the game list (GUI)
static void CheckMinActiveClients()
Check if the minimum number of active clients has been reached and pause or unpause the game as appro...
ClientID client_id
Client identifier.
@ WC_SEND_NETWORK_MSG
Chatbox; Window numbers:
@ NGLS_OFFLINE
Server is offline (or cannot be queried).
StringList _network_ban_list
The banned clients.
void NetworkUDPClose()
Close all UDP related stuff.
NetworkSettings network
settings related to the network
static void SendReceive()
Check if any query needs to send or receive.
uint32_t state[2]
The state of the randomizer.
@ COMPANY_SPECTATOR
The client is spectating.
void NetworkClose(bool close_admins)
Close current connections.
std::string_view ParseFullConnectionString(const std::string &connection_string, uint16_t &port, CompanyID *company_id)
Converts a string to ip/port/company Format: IP:port::company.
std::string client_secret_key
The secret key of the client for authorized key logins.
void NetworkHTTPInitialize()
Initialize the HTTP socket handler.
static const char32_t CHAR_TD_RLM
The next character acts like a right-to-left character.
uint32_t _sync_frame
The frame to perform the sync check.
ServerNetworkGameSocketHandler(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)
bool NetworkCoreInitialize()
Initializes the network core (as that is needed for some platforms.
void NetworkUpdateServerGameType()
The setting server_game_type was updated; possibly we need to take some action.
Endian-aware buffer adapter that always writes values in little endian order.
NetworkGameList * next
Next pointer to make a linked game list.
bool NetworkCanJoinCompany(CompanyID company_id)
Returns whether the given company can be joined by this client.
size_t Utf8Encode(T buf, char32_t c)
Encode a unicode character and place it in the buffer.
void NetworkExecuteLocalCommandQueue()
Execute all commands on the local command queue that ought to be executed this frame.
Commands
List of commands.
static NetworkRecvStatus SendQuit()
Tell the server we would like to quit.
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
@ MAX_COMPANIES
Maximum number of companies.
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
static void CloseListeners()
Close the sockets we're listening on.
std::string server_name
Server name.
void StateGameLoop()
State controlling game loop.
uint8_t min_active_clients
minimum amount of active clients to unpause the game
void NetworkStartUp()
This tries to launch the network for a given OS.
bool refreshing
Whether this server is being queried.
StringList _network_host_list
The servers we know.
NetworkGameInfo info
The game information of this server.
@ PM_UNPAUSED
A normal unpaused game.
bool _network_available
is network mode available?
@ WN_NETWORK_STATUS_WINDOW_JOIN
Network join status.
bool Contains(std::string_view key) const
Check whether the given key is contains in these authorized keys.
static bool NetworkReceive()
Receives something from the network.
std::string client_public_key
The public key of the client for authorized key logins.
void NetworkFreeLocalCommandQueue()
Free the local command queues.
NetworkJoinInfo _network_join
Information about the game to join to.
@ SM_JOIN_GAME
Join a network game.
void NetworkOnGameStart()
Perform tasks when the server is started.
std::string connection_string
The connection string for this ServerAddress.
@ PM_PAUSED_NORMAL
A game normally paused.
GRFConfig * grfconfig
List of NewGRF files used.
void NetworkServerUpdateGameInfo()
Update the server's NetworkServerGameInfo due to changes in settings.
@ CLIENT_ID_SERVER
Servers always have this ID.
NetworkAddressList _broadcast_list
List of broadcast addresses.
static void Send()
Send the packets of this socket handler.
Non blocking connection to query servers for their game info.
TextDirection _current_text_dir
Text direction of the currently selected language.
bool _is_network_server
Does this client wants to be a network-server?
NetworkErrorCode
The error codes we send around in the protocols.
Container for all information known about a client.
std::string GenerateUid(std::string_view subject)
Generate an unique ID.
uint32_t _frame_counter_max
To where we may go with our clients.
uint8_t _network_reconnect
Reconnect timeout.
bool NetworkClientConnectGame(const std::string &connection_string, CompanyID default_company, const std::string &join_server_password)
Join a client to the server at with the given connection string.
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
GUISettings gui
settings related to the GUI
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
void NetworkDistributeCommands()
Distribute the commands of ourself and the clients.
@ PM_PAUSED_GAME_SCRIPT
A game paused by a game script.
StringID name_1
Name of the company if the user did not change it.
NetworkGameListStatus status
Stats of the server.
static const uint NETWORK_COMPANY_NAME_LENGTH
The maximum length of the company name, in bytes including '\0'.
Commands cmd
command being executed.
static Date date
Current date in days (day counter).
static const char32_t CHAR_TD_LRM
The next character acts like a left-to-right character.
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.