Go to the documentation of this file.
10 #include "../stdafx.h"
12 #include "../strings_func.h"
13 #include "../command_func.h"
14 #include "../date_func.h"
27 #include "../console_func.h"
28 #include "../3rdparty/md5/md5.h"
29 #include "../core/random_func.hpp"
30 #include "../window_func.h"
31 #include "../company_func.h"
32 #include "../company_base.h"
33 #include "../landscape_type.h"
35 #include "../core/pool_func.hpp"
36 #include "../gfx_func.h"
38 #include "../misc_cmd.h"
43 #include "../safeguards.h"
45 #ifdef DEBUG_DUMP_COMMANDS
46 #include "../fileio_func.h"
76 #ifdef NETWORK_SEND_DOUBLE_SEED
97 return !NetworkClientSocket::Iterate().empty();
117 if (ci->client_id ==
client_id)
return ci;
130 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
131 if (cs->client_id ==
client_id)
return cs;
137 byte NetworkSpectatorCount()
159 if (password.compare(
"*") == 0) password =
"";
179 if (password.empty())
return password;
181 size_t password_length = password.size();
182 size_t password_server_id_length = password_server_id.size();
184 std::ostringstream salted_password;
187 char password_char = (i < password_length ? password[i] : 0);
188 char server_id_char = (i < password_server_id_length ? password_server_id[i] : 0);
189 char seed_char = password_game_seed >> (i % 32);
190 salted_password << (char)(password_char ^ server_id_char ^ seed_char);
197 std::string salted_password_string = salted_password.str();
198 checksum.Append(salted_password_string.data(), salted_password_string.size());
199 checksum.Finish(digest);
201 std::ostringstream hashed_password;
202 hashed_password << std::hex << std::setfill(
'0');
203 for (
int di = 0; di < 16; di++) hashed_password << std::setw(2) << (int)digest[di];
205 return hashed_password.str();
221 void NetworkTextMessage(
NetworkAction action,
TextColour colour,
bool self_send,
const std::string &name,
const std::string &str, int64 data,
const std::string &data_str)
225 case NETWORK_ACTION_SERVER_MESSAGE:
227 strid = STR_NETWORK_SERVER_MESSAGE;
230 case NETWORK_ACTION_COMPANY_SPECTATOR:
232 strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_SPECTATE;
234 case NETWORK_ACTION_COMPANY_JOIN:
236 strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_JOIN;
238 case NETWORK_ACTION_COMPANY_NEW:
240 strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_NEW;
242 case NETWORK_ACTION_JOIN:
244 strid =
_network_server ? STR_NETWORK_MESSAGE_CLIENT_JOINED_ID : STR_NETWORK_MESSAGE_CLIENT_JOINED;
246 case NETWORK_ACTION_LEAVE: strid = STR_NETWORK_MESSAGE_CLIENT_LEFT;
break;
247 case NETWORK_ACTION_NAME_CHANGE: strid = STR_NETWORK_MESSAGE_NAME_CHANGE;
break;
248 case NETWORK_ACTION_GIVE_MONEY: strid = STR_NETWORK_MESSAGE_GIVE_MONEY;
break;
249 case NETWORK_ACTION_CHAT_COMPANY: strid = self_send ? STR_NETWORK_CHAT_TO_COMPANY : STR_NETWORK_CHAT_COMPANY;
break;
250 case NETWORK_ACTION_CHAT_CLIENT: strid = self_send ? STR_NETWORK_CHAT_TO_CLIENT : STR_NETWORK_CHAT_CLIENT;
break;
251 case NETWORK_ACTION_KICKED: strid = STR_NETWORK_MESSAGE_KICKED;
break;
252 case NETWORK_ACTION_EXTERNAL_CHAT: strid = STR_NETWORK_CHAT_EXTERNAL;
break;
253 default: strid = STR_NETWORK_CHAT_ALL;
break;
267 GetString(msg_ptr, strid,
lastof(message));
275 uint NetworkCalculateLag(
const NetworkClientSocket *cs)
277 int lag = cs->last_frame_server - cs->last_frame;
290 void ShowNetworkError(
StringID error_string)
305 static const StringID network_error_strings[] = {
306 STR_NETWORK_ERROR_CLIENT_GENERAL,
307 STR_NETWORK_ERROR_CLIENT_DESYNC,
308 STR_NETWORK_ERROR_CLIENT_SAVEGAME,
309 STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST,
310 STR_NETWORK_ERROR_CLIENT_PROTOCOL_ERROR,
311 STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH,
312 STR_NETWORK_ERROR_CLIENT_NOT_AUTHORIZED,
313 STR_NETWORK_ERROR_CLIENT_NOT_EXPECTED,
314 STR_NETWORK_ERROR_CLIENT_WRONG_REVISION,
315 STR_NETWORK_ERROR_CLIENT_NAME_IN_USE,
316 STR_NETWORK_ERROR_CLIENT_WRONG_PASSWORD,
317 STR_NETWORK_ERROR_CLIENT_COMPANY_MISMATCH,
318 STR_NETWORK_ERROR_CLIENT_KICKED,
319 STR_NETWORK_ERROR_CLIENT_CHEATER,
320 STR_NETWORK_ERROR_CLIENT_SERVER_FULL,
321 STR_NETWORK_ERROR_CLIENT_TOO_MANY_COMMANDS,
322 STR_NETWORK_ERROR_CLIENT_TIMEOUT_PASSWORD,
323 STR_NETWORK_ERROR_CLIENT_TIMEOUT_COMPUTER,
324 STR_NETWORK_ERROR_CLIENT_TIMEOUT_MAP,
325 STR_NETWORK_ERROR_CLIENT_TIMEOUT_JOIN,
326 STR_NETWORK_ERROR_CLIENT_INVALID_CLIENT_NAME,
328 static_assert(
lengthof(network_error_strings) == NETWORK_ERROR_END);
330 if (err >= (ptrdiff_t)
lengthof(network_error_strings)) err = NETWORK_ERROR_GENERAL;
332 return network_error_strings[err];
344 switch (changed_mode) {
352 if (!paused && !changed)
return;
363 str = STR_NETWORK_SERVER_MESSAGE_GAME_STILL_PAUSED_1 + i;
365 switch (changed_mode) {
371 default: NOT_REACHED();
373 str = paused ? STR_NETWORK_SERVER_MESSAGE_GAME_PAUSED : STR_NETWORK_SERVER_MESSAGE_GAME_UNPAUSED;
376 NetworkTextMessage(NETWORK_ACTION_SERVER_MESSAGE,
CC_DEFAULT,
false,
"", GetString(str));
410 for (
const NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
411 if (cs->status != NetworkClientSocket::STATUS_ACTIVE)
continue;
438 for (
const NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
439 if (cs->status >= NetworkClientSocket::STATUS_AUTHORIZED && cs->status < NetworkClientSocket::STATUS_ACTIVE)
return true;
465 std::string_view ip = connection_string;
466 if (company_id ==
nullptr)
return ip;
468 size_t offset = ip.find_last_of(
'#');
469 if (offset != std::string::npos) {
470 std::string_view company_string = ip.substr(offset + 1);
471 ip = ip.substr(0, offset);
474 auto [_, err] = std::from_chars(company_string.data(), company_string.data() + company_string.size(), company_value);
475 if (err == std::errc()) {
481 *company_id = (
CompanyID)(company_value - 1);
511 size_t port_offset = ip.find_last_of(
':');
512 size_t ipv6_close = ip.find_last_of(
']');
513 if (port_offset != std::string::npos && (ipv6_close == std::string::npos || ipv6_close < port_offset)) {
514 std::string_view port_string = ip.substr(port_offset + 1);
515 ip = ip.substr(0, port_offset);
516 std::from_chars(port_string.data(), port_string.data() + port_string.size(), port);
529 uint16 port = default_port;
531 return std::string(ip) +
":" + std::to_string(port);
544 uint16 port = default_port;
583 as->CloseConnection(
true);
587 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
618 static void NetworkInitialize(
bool close_admins =
true)
631 std::string connection_string;
677 if (connection_string.empty())
return nullptr;
690 if (manually) item->
manually =
true;
691 if (never_expire) item->
version = INT32_MAX;
704 addresses->emplace_back(iter.c_str(), port);
708 if (addresses->size() == 0) {
709 addresses->emplace_back(
"", port);
716 void NetworkRebuildHostList()
728 std::string connection_string;
735 ShowNetworkError(STR_NETWORK_ERROR_NOCONNECTION);
764 bool NetworkClientConnectGame(
const std::string &connection_string,
CompanyID default_company,
const std::string &join_server_password,
const std::string &join_company_password)
777 if (_game_mode == GM_MENU) {
803 ShowJoinStatusWindow();
808 static void NetworkInitGameInfo()
835 if (!server_name.empty())
return true;
849 static const std::string fallback_client_name =
"Unnamed Client";
852 Debug(net, 1,
"No \"client_name\" has been set, using \"{}\" instead. Please set this now using the \"name <new name>\" command", fallback_client_name);
856 static const std::string fallback_server_name =
"Unnamed Server";
859 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);
864 bool NetworkServerStart()
876 NetworkInitialize(
false);
878 Debug(net, 5,
"Starting listeners for clients");
883 Debug(net, 5,
"Starting listeners for admins");
888 Debug(net, 5,
"Starting listeners for incoming server queries");
903 NetworkInitGameInfo();
925 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
949 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
979 case SERVER_GAME_TYPE_LOCAL:
983 case SERVER_GAME_TYPE_INVITE_ONLY:
984 case SERVER_GAME_TYPE_PUBLIC:
1008 static void NetworkSend()
1036 void NetworkGameLoop()
1046 static Date last_log;
1047 if (last_log !=
_date) {
1053 #ifdef DEBUG_DUMP_COMMANDS
1056 static Date next_date = 0;
1057 static uint32 next_date_fract;
1059 static bool check_sync_state =
false;
1060 static uint32 sync_state[2];
1061 if (f ==
nullptr && next_date == 0) {
1062 Debug(desync, 0,
"Cannot open commands.log");
1066 while (f !=
nullptr && !feof(f)) {
1068 if (cp !=
nullptr) {
1074 if (check_sync_state) {
1078 Debug(desync, 0,
"Sync check: {:08x}; {:02x}; mismatch expected {{{:08x}, {:08x}}}, got {{{:08x}, {:08x}}}",
1082 check_sync_state =
false;
1086 if (cp !=
nullptr || check_sync_state)
break;
1089 if (fgets(buff,
lengthof(buff), f) ==
nullptr)
break;
1095 if (p ==
nullptr)
break;
1099 if (strncmp(p,
"cmd: ", 5) == 0
1100 #ifdef DEBUG_FAILED_DUMP_COMMANDS
1101 || strncmp(p,
"cmdf: ", 6) == 0
1110 int ret = sscanf(p,
"%x; %x; %x; %x; %x; %x; %255s", &next_date, &next_date_fract, &company, &cmd, &cp->
err_msg, &cp->tile, buffer);
1116 std::vector<byte> args;
1117 size_t arg_len = strlen(buffer);
1118 for (
size_t i = 0; i + 1 < arg_len; i += 2) {
1120 std::from_chars(buffer + i, buffer + i + 1, e, 16);
1121 args.emplace_back(e);
1124 }
else if (strncmp(p,
"join: ", 6) == 0) {
1126 int ret = sscanf(p + 6,
"%x; %x", &next_date, &next_date_fract);
1128 Debug(desync, 0,
"Injecting pause for join at {:08x}:{:02x}; please join when paused", next_date, next_date_fract);
1134 }
else if (strncmp(p,
"sync: ", 6) == 0) {
1135 int ret = sscanf(p + 6,
"%x; %x; %x; %x", &next_date, &next_date_fract, &sync_state[0], &sync_state[1]);
1137 check_sync_state =
true;
1138 }
else if (strncmp(p,
"msg: ", 5) == 0 || strncmp(p,
"client: ", 8) == 0 ||
1139 strncmp(p,
"load: ", 6) == 0 || strncmp(p,
"save: ", 6) == 0) {
1141 #ifndef DEBUG_FAILED_DUMP_COMMANDS
1142 }
else if (strncmp(p,
"cmdf: ", 6) == 0) {
1143 Debug(desync, 0,
"Skipping replay of failed command: {}", p + 6);
1147 Debug(desync, 0,
"Trying to parse: {}", p);
1151 if (f !=
nullptr && feof(f)) {
1152 Debug(desync, 0,
"End of commands.log");
1166 bool send_frame =
false;
1182 #ifdef NETWORK_SEND_DOUBLE_SEED
1208 static void NetworkGenerateServerId()
1212 char hex_output[16 * 2 + 1];
1216 seprintf(coding_string,
lastof(coding_string),
"%d%s", (uint)Random(),
"OpenTTD Server ID");
1219 checksum.Append((
const uint8*)coding_string, strlen(coding_string));
1220 checksum.Finish(digest);
1222 for (di = 0; di < 16; ++di) {
1223 seprintf(hex_output + di * 2,
lastof(hex_output),
"%02x", digest[di]);
1232 std::string connection_string;
1239 Debug(net, 0,
"Failed to open connection to {} for redirecting Debug()", this->connection_string);
1244 Debug(net, 3,
"Redirecting Debug() to {}", this->connection_string);
1246 extern SOCKET _debug_socket;
1251 void NetworkStartDebugLog(
const std::string &connection_string)
1259 Debug(net, 3,
"Starting network");
1270 NetworkInitialize();
1272 Debug(net, 3,
"Network online, multiplayer available");
1282 Debug(net, 3,
"Shutting down network");
1289 #ifdef __EMSCRIPTEN__
1292 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.
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.
uint32 _frame_counter
The current frame.
static const uint16 NETWORK_DEFAULT_PORT
The default port of the game server (TCP & UDP)
@ 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...
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.
std::string client_name
Name of the client.
Commands
List of commands.
void ClearGRFConfigList(GRFConfig **config)
Clear a GRF Config list, freeing all nodes.
void NetworkUDPServerListen()
Start the listening of the UDP server component.
void GetBindAddresses(NetworkAddressList *addresses, uint16 port)
Get the addresses to bind to.
std::string company_password
The password of the company to join.
uint8 frame_freq
how often do we send commands to the clients
uint16 server_port
port the server listens on
"Helper" class for creating TCP connections in a non-blocking manner
static const uint NETWORK_NAME_LENGTH
The maximum length of the server name and map name, in bytes including '\0'.
CompanyID client_playas
As which company is this client playing (CompanyID)
@ TD_LTR
Text is written left-to-right by default.
DateFract _date_fract
Fractional part of the day.
Some state information of a company, especially for servers.
bool _network_server
network-server is active
CompanyMask _network_company_passworded
Bitmask of the password status of all companies.
NetworkAction
Actions that can be used for NetworkTextMessage.
@ WC_CLIENT_LIST
Client list; Window numbers:
static void WelcomeAll()
Send a Welcome packet to all connected admins.
std::string server_password
The password of the server to join.
NetworkAddress ParseConnectionString(const std::string &connection_string, uint16 default_port)
Convert a string containing either "hostname" or "hostname:ip" to a NetworkAddress.
static bool GameLoop()
Actual game loop for the client.
void OnFailure() override
Callback for when the connection attempt failed.
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
static bool NetworkHasJoiningClient()
Checks whether there is a joining client.
size_t Utf8Encode(T buf, WChar c)
Encode a unicode character and place it in the buffer.
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...
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.
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!
NetworkServerGameInfo _network_game_info
Information about our game.
ClientID _redirect_console_to_client
If not invalid, redirect the console output to a client.
Owner
Enum for all companies/owners.
NetworkRecvStatus CloseConnection(NetworkRecvStatus status) override
Close the network connection due to the given status.
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
static ServerAddress Parse(const std::string &connection_string, uint16 default_port, CompanyID *company_id=nullptr)
Convert a string containing either "hostname", "hostname:port" or invite code to a ServerAddress,...
Defines the traits of a command.
static const TextColour CC_DEFAULT
Default colour of the console.
uint32 _frame_counter_max
To where we may go with our clients.
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.
static void Send()
Send the packets for the server sockets.
void FillStaticNetworkServerGameInfo()
Fill a NetworkServerGameInfo structure with the static content, or things that are so static they can...
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=nullptr, uint textref_stack_size=0, const uint32 *textref_stack=nullptr)
Display an error message in a window.
void OnFailure() override
Callback for when the connection attempt failed.
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.
std::string NetworkChangeCompanyPassword(CompanyID company_id, std::string password)
Change the company password of a given company.
void NetworkQueryServer(const std::string &connection_string)
Query a server to fetch the game-info.
@ PM_UNPAUSED
A normal unpaused game.
bool HasClients()
Return whether there is any client connected or trying to connect at all.
std::string FormatArrayAsHex(span< const byte > data)
Format a byte array into a continuous hex string.
static constexpr size_t MAX_SIZE
Make template parameter accessible from outside.
@ COMPANY_FIRST
First company, same as owner.
static NetworkClientInfo * GetByClientID(ClientID client_id)
Return the CI given it's client-identifier.
void OnConnect(SOCKET s) override
Callback when the connection succeeded.
uint32 _frame_counter_server
The frame_counter of the server, if in network-mode.
void NetworkClientJoinGame()
Actually perform the joining to the server.
CompanyID company
The company to join.
CompanyID company
company that is executing the command
@ COMPANY_NEW_COMPANY
The client wants a new company.
static void Send()
Send the packets for the server sockets.
Everything we need to know about a command to be able to execute it.
Date _date
Current date in days (day counter)
std::string last_joined
Last joined server.
std::vector< NetworkAddress > NetworkAddressList
Type for a list of addresses.
std::string NormalizeConnectionString(const std::string &connection_string, uint16 default_port)
Normalize a connection string.
static bool Receive()
Handle the receiving of packets.
FILE * FioFOpenFile(const std::string &filename, const char *mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
void StrTrimInPlace(std::string &str)
Trim the spaces from given string in place, i.e.
std::string GenerateCompanyPasswordHash(const std::string &password, const std::string &password_server_id, uint32 password_game_seed)
Hash the given password using server ID and game seed.
ClientID
'Unique' identifier to be given to clients
int32 Date
The type to store our dates in.
uint8 min_active_clients
minimum amount of active clients to unpause the game
bool manually
True if the server was added manually.
std::string admin_password
password for the admin network
PauseMode _pause_mode
The current pause mode.
void NetworkClient_Connected()
Is called after a client is connected to the server.
void OnFailure() override
Callback for when the connection attempt failed.
uint32 _sync_seed_1
Seed to compare during sync checks.
NetworkRecvStatus CloseConnection(bool error=true) override
This will put this socket handler in a close state.
@ MAX_COMPANIES
Maximum number of companies.
std::vector< std::string > StringList
Type for a list of strings.
Non blocking connection create to actually connect to servers.
void NetworkDisconnect(bool blocking, bool close_admins)
We want to disconnect from the host/clients.
std::string client_name
name of the player (as client)
static const WChar CHAR_TD_RLM
The next character acts like a right-to-left character.
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.
@ CLIENT_ID_SERVER
Servers always have this ID.
@ PT_NADMIN
Network admin pool.
NetworkCompanyState * _network_company_states
Statistics about some companies.
static const uint NETWORK_SERVER_ID_LENGTH
The maximum length of the network id of the servers, in bytes including '\0'.
int version
Used to see which servers are no longer available on the Game Coordinator and can be removed.
std::string_view ParseFullConnectionString(const std::string &connection_string, uint16 &port, CompanyID *company_id)
Converts a string to ip/port/company Format: IP:port::company.
bool _networking
are we in networking mode?
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 ServerNetworkGameSocketHandler * GetByClientID(ClientID client_id)
Return the client state given it's client-identifier.
PauseMode
Modes of pausing we've got.
uint8 _network_reconnect
Reconnect timeout.
bool _network_dedicated
are we a dedicated server?
void Register()
Register our server to receive our invite code.
static void KillAll()
Kill all connection attempts.
static void QueryServer(SOCKET s, const std::string &connection_string)
Start to query a server based on an open socket.
@ PM_PAUSED_GAME_SCRIPT
A game paused by a game script.
uint32 state[2]
The state of the randomizer.
@ CMD_PAUSE
pause the game
static void AcceptConnection(SOCKET s, const NetworkAddress &address)
Handle the accepting of a connection to the server.
@ PT_NCLIENT
Network client pools.
std::string_view ParseCompanyFromConnectionString(const std::string &connection_string, CompanyID *company_id)
Parse the company part ("#company" postfix) of a connecting string.
bool NetworkCompanyIsPassworded(CompanyID company_id)
Check if the company we want to join requires a password.
ClientID client_id
Client identifier (same as ClientState->client_id)
void StateGameLoop()
State controlling game loop.
ClientID _network_own_client_id
Our client identifier.
void NetworkBackgroundUDPLoop()
Receive the UDP packets.
void OnConnect(SOCKET s) override
Callback when the connection succeeded.
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.
@ PM_PAUSED_ACTIVE_CLIENTS
A game paused for 'min_active_clients'.
SwitchMode _switch_mode
The next mainloop command.
uint32 StringID
Numeric value that represents a string, independent of the selected language.
ServerGameType server_game_type
Server type: local / public / invite-only.
#define _ddc_fastforward
Helper variable to make the dedicated server go fast until the (first) join.
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.
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.
void NetworkClientSetCompanyPassword(const std::string &password)
Set/Reset company password on the client side.
CommandDataBuffer data
command parameters.
@ COMPANY_SPECTATOR
The client is spectating.
Class for handling the server side of the game connection.
static void CheckPauseOnJoin()
Check whether we should pause on join.
byte _network_clients_connected
The amount of clients connected.
@ WC_NETWORK_STATUS_WINDOW
Network status window; Window numbers:
void NetworkUDPInitialize()
Initialize the whole UDP bit.
static const uint16 NETWORK_DEFAULT_DEBUGLOG_PORT
The default port debug-log is sent to (TCP)
ClientNetworkCoordinatorSocketHandler _network_coordinator_client
The connection to the Game Coordinator.
@ PM_PAUSED_NORMAL
A game normally paused.
static void HTTPReceive()
Do the receiving for all HTTP connections.
const char * GetCommandName(Commands cmd)
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.
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
@ WL_ERROR
Errors (eg. saving/loading failed)
@ SM_MENU
Switch to game intro menu.
Class for handling the client side of the game connection.
@ PM_PAUSED_LINK_GRAPH
A game paused due to the link graph schedule lagging.
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.
@ PM_PAUSED_JOIN
A game paused for 'pause_on_join'.
uint32 _sync_frame
The frame to perform the sync check.
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:
static const WChar CHAR_TD_LRM
The next character acts like a left-to-right character.
bool NetworkClientConnectGame(const std::string &connection_string, CompanyID default_company, const std::string &join_server_password, const std::string &join_company_password)
Join a client to the server at with the given connection string.
#define Debug(name, level, format_string,...)
Ouptut a line of debugging information.
@ NGLS_OFFLINE
Server is offline (or cannot be queried).
#define lengthof(x)
Return the length of an fixed size array.
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.
void NetworkClose(bool close_admins)
Close current connections.
void CloseWindowById(WindowClass cls, WindowNumber number, bool force)
Close a window by its class and window number (if it is open).
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 IConsoleCmdExec(const char *cmdstr, const uint recurse_count)
Execute a given command passed to us.
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.
@ DESTTYPE_CLIENT
Send message/notice to only a certain client (Private)
void NetworkExecuteLocalCommandQueue()
Execute all commands on the local command queue that ought to be executed this frame.
static NetworkRecvStatus SendQuit()
Tell the server we would like to quit.
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 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.
byte clients_on
Current count of clients on server.
bool _network_available
is network mode available?
@ WN_NETWORK_STATUS_WINDOW_JOIN
Network join status.
static bool NetworkReceive()
Receives something from the network.
void NetworkServerSetCompanyPassword(CompanyID company_id, const std::string &password, bool already_hashed)
Set/Reset a company password on the server end.
@ PM_PAUSED_ERROR
A game paused because a (critical) error.
void NetworkFreeLocalCommandQueue()
Free the local command queues.
NetworkJoinInfo _network_join
Information about the game to join to.
@ SM_JOIN_GAME
Join a network game.
uint16 network_chat_timeout
timeout of chat messages in seconds
std::string connection_string
The connection string for this ServerAddress.
#define lastof(x)
Get the last element of an fixed size array.
GRFConfig * grfconfig
List of NewGRF files used.
NetworkAddressList _broadcast_list
List of broadcast addresses.
static void Send()
Send the packets of this socket handler.
uint16 server_admin_port
port the server listens on for the admin network
Non blocking connection to query servers for their game info.
static const int DAY_TICKS
1 day is 74 ticks; _date_fract used to be uint16 and incremented by 885.
TextDirection _current_text_dir
Text direction of the currently selected language.
uint32 _last_sync_frame
Used in the server to store the last time a sync packet was sent to clients.
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.
static bool Listen(uint16 port)
Listen on a particular port.
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
void OnConnect(SOCKET s) override
Callback when the connection succeeded.
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.
std::string network_id
network ID for servers
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.
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.