10 #include "../stdafx.h" 12 #include "../strings_func.h" 13 #include "../command_func.h" 14 #include "../date_func.h" 25 #include "../console_func.h" 26 #include "../3rdparty/md5/md5.h" 27 #include "../core/random_func.hpp" 28 #include "../window_func.h" 29 #include "../company_func.h" 30 #include "../company_base.h" 31 #include "../landscape_type.h" 33 #include "../core/pool_func.hpp" 34 #include "../gfx_func.h" 37 #include "../safeguards.h" 39 #ifdef DEBUG_DUMP_COMMANDS 40 #include "../fileio_func.h" 72 #ifdef NETWORK_SEND_DOUBLE_SEED 102 return !NetworkClientSocket::Iterate().empty();
122 if (ci->client_id == client_id)
return ci;
135 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
136 if (cs->client_id == client_id)
return cs;
142 byte NetworkSpectatorCount()
151 if (_network_dedicated) count--;
164 if (strcmp(password,
"*") == 0) password =
"";
166 if (_network_server) {
184 if (
StrEmpty(password))
return password;
188 memset(salted_password, 0,
sizeof(salted_password));
189 seprintf(salted_password,
lastof(salted_password),
"%s", password);
192 salted_password[i] ^= password_server_id[i] ^ (password_game_seed >> (i % 32));
200 checksum.Append(salted_password,
sizeof(salted_password) - 1);
201 checksum.Finish(digest);
203 for (
int di = 0; di < 16; di++)
seprintf(hashed_password + di * 2,
lastof(hashed_password),
"%02x", digest[di]);
205 return hashed_password;
215 return HasBit(_network_company_passworded, company_id);
221 void NetworkTextMessage(
NetworkAction action,
TextColour colour,
bool self_send,
const char *name,
const char *str, int64 data)
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 = self_send ? STR_NETWORK_MESSAGE_GAVE_MONEY_AWAY : 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 default: strid = STR_NETWORK_CHAT_ALL;
break;
264 GetString(msg_ptr, strid,
lastof(message));
272 uint NetworkCalculateLag(
const NetworkClientSocket *cs)
274 int lag = cs->last_frame_server - cs->last_frame;
287 void NetworkError(
StringID error_string)
302 static const StringID network_error_strings[] = {
303 STR_NETWORK_ERROR_CLIENT_GENERAL,
304 STR_NETWORK_ERROR_CLIENT_DESYNC,
305 STR_NETWORK_ERROR_CLIENT_SAVEGAME,
306 STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST,
307 STR_NETWORK_ERROR_CLIENT_PROTOCOL_ERROR,
308 STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH,
309 STR_NETWORK_ERROR_CLIENT_NOT_AUTHORIZED,
310 STR_NETWORK_ERROR_CLIENT_NOT_EXPECTED,
311 STR_NETWORK_ERROR_CLIENT_WRONG_REVISION,
312 STR_NETWORK_ERROR_CLIENT_NAME_IN_USE,
313 STR_NETWORK_ERROR_CLIENT_WRONG_PASSWORD,
314 STR_NETWORK_ERROR_CLIENT_COMPANY_MISMATCH,
315 STR_NETWORK_ERROR_CLIENT_KICKED,
316 STR_NETWORK_ERROR_CLIENT_CHEATER,
317 STR_NETWORK_ERROR_CLIENT_SERVER_FULL,
318 STR_NETWORK_ERROR_CLIENT_TOO_MANY_COMMANDS,
319 STR_NETWORK_ERROR_CLIENT_TIMEOUT_PASSWORD,
320 STR_NETWORK_ERROR_CLIENT_TIMEOUT_COMPUTER,
321 STR_NETWORK_ERROR_CLIENT_TIMEOUT_MAP,
322 STR_NETWORK_ERROR_CLIENT_TIMEOUT_JOIN,
326 if (err >= (ptrdiff_t)
lengthof(network_error_strings)) err = NETWORK_ERROR_GENERAL;
328 return network_error_strings[err];
338 if (!_networking)
return;
340 switch (changed_mode) {
347 if (!paused && !changed)
return;
357 str = STR_NETWORK_SERVER_MESSAGE_GAME_STILL_PAUSED_1 + i;
359 switch (changed_mode) {
364 default: NOT_REACHED();
366 str = paused ? STR_NETWORK_SERVER_MESSAGE_GAME_PAUSED : STR_NETWORK_SERVER_MESSAGE_GAME_UNPAUSED;
370 GetString(buffer, str,
lastof(buffer));
371 NetworkTextMessage(NETWORK_ACTION_SERVER_MESSAGE,
CC_DEFAULT,
false,
nullptr, buffer);
405 for (
const NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
406 if (cs->status != NetworkClientSocket::STATUS_ACTIVE)
continue;
420 !_network_dedicated ||
433 for (
const NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
434 if (cs->status >= NetworkClientSocket::STATUS_AUTHORIZED && cs->status < NetworkClientSocket::STATUS_ACTIVE)
return true;
462 bool ipv6 = (strchr(connection_string,
':') != strrchr(connection_string,
':'));
464 for (p = connection_string; *p !=
'\0'; p++) {
496 _network_clients_connected++;
518 if (_network_server) {
521 as->CloseConnection(
true);
525 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
538 _network_server =
false;
549 static void NetworkInitialize(
bool close_admins =
true)
555 _network_first_time =
true;
557 _network_reconnect = 0;
583 if (!_network_available)
return;
594 void NetworkAddServer(
const char *b)
597 const char *port =
nullptr;
598 const char *company =
nullptr;
608 if (port !=
nullptr) rport = atoi(port);
621 for (
const auto &iter : _network_bind_list) {
622 addresses->emplace_back(iter.c_str(), port);
626 if (addresses->size() == 0) {
627 addresses->emplace_back(
"", port);
634 void NetworkRebuildHostList()
636 _network_host_list.clear();
639 if (item->manually) _network_host_list.emplace_back(item->address.GetAddressAsString(
false));
650 NetworkError(STR_NETWORK_ERROR_NOCONNECTION);
664 void NetworkClientConnectGame(
NetworkAddress address,
CompanyID join_as,
const char *join_server_password,
const char *join_company_password)
666 if (!_network_available)
return;
668 if (address.
GetPort() == 0)
return;
680 ShowJoinStatusWindow();
685 static void NetworkInitGameInfo()
692 _network_game_info.
clients_on = _network_dedicated ? 0 : 1;
702 bool NetworkServerStart()
704 if (!_network_available)
return false;
708 if (_network_dedicated)
IConsoleCmdExec(
"exec scripts/pre_dedicated.scr 0");
711 NetworkInitialize(
false);
712 DEBUG(net, 1,
"starting listeners for clients");
717 DEBUG(net, 1,
"starting listeners for admins");
722 DEBUG(net, 1,
"starting listeners for incoming server queries");
723 _network_udp_server = _udp_server_socket->
Listen();
726 _network_server =
true;
729 _frame_counter_server = 0;
730 _frame_counter_max = 0;
731 _last_sync_frame = 0;
734 _network_clients_connected = 0;
735 _network_company_passworded = 0;
737 NetworkInitGameInfo();
742 if (_network_dedicated)
IConsoleCmdExec(
"exec scripts/on_dedicated.scr 0");
745 _network_need_advertise =
true;
758 if (_network_server) {
759 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
782 if (_network_server) {
783 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
812 if (_network_server) {
821 static void NetworkSend()
823 if (_network_server) {
847 void NetworkGameLoop()
849 if (!_networking)
return;
853 if (_network_server) {
857 static Date last_log;
858 if (last_log !=
_date) {
864 #ifdef DEBUG_DUMP_COMMANDS 867 static Date next_date = 0;
868 static uint32 next_date_fract;
870 static bool check_sync_state =
false;
871 static uint32 sync_state[2];
872 if (f ==
nullptr && next_date == 0) {
873 DEBUG(net, 0,
"Cannot open commands.log");
877 while (f !=
nullptr && !feof(f)) {
881 DEBUG(net, 0,
"injecting: %08x; %02x; %02x; %06x; %08x; %08x; %08x; \"%s\" (%s)",
_date,
_date_fract, (
int)
_current_company, cp->
tile, cp->
p1, cp->
p2, cp->
cmd, cp->
text,
GetCommandName(cp->
cmd));
885 if (check_sync_state) {
889 DEBUG(net, 0,
"sync check: %08x; %02x; mismatch expected {%08x, %08x}, got {%08x, %08x}",
893 check_sync_state =
false;
897 if (cp !=
nullptr || check_sync_state)
break;
900 if (fgets(buff,
lengthof(buff), f) ==
nullptr)
break;
906 if (p ==
nullptr)
break;
910 if (strncmp(p,
"cmd: ", 5) == 0
911 #ifdef DEBUG_FAILED_DUMP_COMMANDS
912 || strncmp(p,
"cmdf: ", 6) == 0
917 cp = CallocT<CommandPacket>(1);
919 int ret = sscanf(p,
"%x; %x; %x; %x; %x; %x; %x; \"%[^\"]\"", &next_date, &next_date_fract, &company, &cp->
tile, &cp->
p1, &cp->
p2, &cp->
cmd, cp->
text);
923 assert(ret == 8 || ret == 7);
925 }
else if (strncmp(p,
"join: ", 6) == 0) {
927 int ret = sscanf(p + 6,
"%x; %x", &next_date, &next_date_fract);
929 DEBUG(net, 0,
"injecting pause for join at %08x:%02x; please join when paused", next_date, next_date_fract);
930 cp = CallocT<CommandPacket>(1);
936 }
else if (strncmp(p,
"sync: ", 6) == 0) {
937 int ret = sscanf(p + 6,
"%x; %x; %x; %x", &next_date, &next_date_fract, &sync_state[0], &sync_state[1]);
939 check_sync_state =
true;
940 }
else if (strncmp(p,
"msg: ", 5) == 0 || strncmp(p,
"client: ", 8) == 0 ||
941 strncmp(p,
"load: ", 6) == 0 || strncmp(p,
"save: ", 6) == 0) {
943 #ifndef DEBUG_FAILED_DUMP_COMMANDS 944 }
else if (strncmp(p,
"cmdf: ", 6) == 0) {
945 DEBUG(net, 0,
"Skipping replay of failed command: %s", p + 6);
949 DEBUG(net, 0,
"trying to parse: %s", p);
953 if (f !=
nullptr && feof(f)) {
954 DEBUG(net, 0,
"End of commands.log");
959 if (_frame_counter >= _frame_counter_max) {
968 bool send_frame =
false;
973 if (_frame_counter > _frame_counter_max) {
984 #ifdef NETWORK_SEND_DOUBLE_SEED 993 if (_frame_counter_server > _frame_counter) {
995 while (_frame_counter_server > _frame_counter) {
1000 if (_frame_counter_max > _frame_counter) {
1010 static void NetworkGenerateServerId()
1014 char hex_output[16 * 2 + 1];
1018 seprintf(coding_string,
lastof(coding_string),
"%d%s", (uint)Random(),
"OpenTTD Server ID");
1021 checksum.Append((
const uint8*)coding_string, strlen(coding_string));
1022 checksum.Finish(digest);
1024 for (di = 0; di < 16; ++di) {
1025 seprintf(hex_output + di * 2,
lastof(hex_output),
"%02x", digest[di]);
1034 extern SOCKET _debug_socket;
1039 if (s == INVALID_SOCKET) {
1040 DEBUG(net, 0,
"Failed to open socket for redirection DEBUG()");
1046 DEBUG(net, 0,
"DEBUG() is now redirected");
1052 DEBUG(net, 3,
"[core] starting network...");
1056 _network_dedicated =
false;
1057 _network_need_advertise =
true;
1058 _network_advertise_retries = 0;
1063 memset(&_network_game_info, 0,
sizeof(_network_game_info));
1065 NetworkInitialize();
1066 DEBUG(net, 3,
"[core] network online, multiplayer available");
1076 DEBUG(net, 3,
"[core] shutting down network");
1078 _network_available =
false;
1096 static char *network_revision =
nullptr;
1098 if (!network_revision) {
1100 network_revision =
stredup(_openttd_revision);
1105 if (_openttd_revision_tagged) {
1106 DEBUG(net, 1,
"Network revision name is '%s'", network_revision);
1107 return network_revision;
1112 assert(_openttd_revision_modified < 3);
1113 char githash_suffix[GITHASH_SUFFIX_LEN + 1] =
"-";
1114 githash_suffix[1] =
"gum"[_openttd_revision_modified];
1116 githash_suffix[i] = _openttd_revision_hash[i-2];
1121 ptrdiff_t hashofs = strrchr(_openttd_revision,
'-') - _openttd_revision;
1122 if (hashofs + strlen(githash_suffix) + 1 >
NETWORK_REVISION_LENGTH) hashofs = strlen(network_revision) - strlen(githash_suffix);
1126 DEBUG(net, 1,
"Network revision name is '%s'", network_revision);
1129 return network_revision;
1132 static const char *ExtractNetworkRevisionHash(
const char *revstr)
1134 return strrchr(revstr,
'-');
1149 if (_openttd_revision_tagged)
return false;
1152 const char *hash2 = ExtractNetworkRevisionHash(other);
1153 return hash1 && hash2 && (strncmp(hash1, hash2, GITHASH_SUFFIX_LEN) == 0);
Owner
Enum for all companies/owners.
void NetworkServer_Tick(bool send_frame)
This is called every tick if this is a _network_server.
A game paused for 'min_active_clients'.
void OnFailure() override
Callback for when the connection attempt failed.
static bool NetworkReceive()
Receives something from the network.
void ParseConnectionString(const char **company, const char **port, char *connection_string)
Converts a string to ip/port/company Format: IP:port::company.
bool _networking
are we in networking mode?
static const WChar CHAR_TD_LRM
The next character acts like a left-to-right character.
void NetworkSendCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback, const char *text, CompanyID company)
Prepare a DoCommand to be send over the network.
const char * GetCommandName(uint32 cmd)
bool IsNetworkCompatibleVersion(const char *other)
Checks whether the given version string is compatible with our version.
Container for all information known about a client.
uint32 _sync_seed_1
Seed to compare during sync checks.
bool server_advertise
advertise the server to the masterserver
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
static void WelcomeAll()
Send a Welcome packet to all connected admins.
static bool Receive()
Check whether we received/can send some data from/to the server and when that's the case handle it ap...
void GetBindAddresses(NetworkAddressList *addresses, uint16 port)
Get the addresses to bind to.
static void KillAll()
Kill all connection attempts.
uint16 last_port
port of the last joined server
Client list; Window numbers:
bool NetworkCoreInitialize()
Initializes the network core (as that is needed for some platforms.
"Helper" class for creating TCP connections in a non-blocking manner
char server_name[NETWORK_NAME_LENGTH]
name of the server
NetworkUDPSocketHandler * _udp_client_socket
udp client socket
const char * _network_join_server_password
Login password from -p argument.
The game information that is not generated on-the-fly and has to be sent to the clients.
Switch to game intro menu.
const char * _network_join_company_password
Company password from -P argument.
NetworkGameList * next
Next pointer to make a linked game list.
~NetworkClientInfo()
Basically a client is leaving us right now.
GUIs related to networking.
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
void NetworkExecuteLocalCommandQueue()
Execute all commands on the local command queue that ought to be executed this frame.
NetworkErrorCode
The error codes we send around in the protocols.
NetworkRecvStatus CloseConnection(NetworkRecvStatus status) override
Close the network connection due to the given status.
ClientID client_id
Client identifier (same as ClientState->client_id)
NetworkJoinStatus _network_join_status
The status of joining.
uint16 _network_udp_broadcast
Timeout for the UDP broadcasts.
Sending and receiving UDP messages.
Client part of the network protocol.
static void Send()
Send the packets for the server sockets.
void SendReceive()
Check whether we received/can send some data from/to the content server and when that's the case hand...
#define _ddc_fastforward
Helper variable to make the dedicated server go fast until the (first) join.
Wrapper for (un)resolved network addresses; there's no reason to transform a numeric IP to a string a...
ClientID _redirect_console_to_client
If not invalid, redirect the console output to a client.
static void Clean(PoolType)
Clean all pools of given type.
void NetworkStartUp()
This tries to launch the network for a given OS.
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.
static const int DAY_TICKS
1 day is 74 ticks; _date_fract used to be uint16 and incremented by 885.
static const int DRAW_STRING_BUFFER
Size of the buffer used for drawing strings.
void NetworkFindBroadcastIPs(NetworkAddressList *broadcast)
Find the IPv4 broadcast addresses; IPv6 uses a completely different strategy for broadcasting.
Send message/notice to only a certain client (Private)
Base socket handler for all UDP sockets.
#define lastof(x)
Get the last element of an fixed size array.
static const TextColour CC_DEFAULT
Default colour of the console.
bool NetworkCompanyIsPassworded(CompanyID company_id)
Check if the company we want to join requires a password.
Base core network types and some helper functions to access them.
Structure with information shown in the game list (GUI)
void NetworkUDPQueryServer(NetworkAddress address, bool manually)
Query a specific server.
Class for handling the client side of the game connection.
ClientID
'Unique' identifier to be given to clients
static void HTTPReceive()
Do the receiving for all HTTP connections.
NetworkClientInfoPool _networkclientinfo_pool("NetworkClientInfo")
The pool with client information.
uint32 _sync_frame
The frame to perform the sync check.
void NetworkHandlePauseChange(PauseMode prev_mode, PauseMode changed_mode)
Handle the pause mode change so we send the right messages to the chat.
char text[32 *MAX_CHAR_LENGTH]
possible text sent for name changes etc, in bytes including '\0'.
bool _network_udp_server
Is the UDP server started?
void OnConnect(SOCKET s) override
Callback when the connection succeeded.
Class for handling the server side of the game connection.
void NetworkUDPAdvertise()
Register us to the master server This function checks if it needs to send an advertise.
StringID GetNetworkErrorMsg(NetworkErrorCode err)
Retrieve the string id of an internal error number.
bool _network_available
is network mode available?
bool _network_dedicated
are we a dedicated server?
assert_compile(NetworkClientInfoPool::MAX_SIZE==NetworkClientSocketPool::MAX_SIZE)
Make sure both pools have the same size.
static const size_t MAX_SIZE
Make template parameter accessible from outside.
std::vector< NetworkAddress > NetworkAddressList
Type for a list of addresses.
Critical errors, the MessageBox is shown in all cases.
NetworkAddressList _broadcast_list
List of broadcast addresses.
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
void StateGameLoop()
State controlling game loop.
NetworkSettings network
settings related to the network
static const int MAX_CHAR_LENGTH
Max. length of UTF-8 encoded unicode character.
bool _is_network_server
Does this client wants to be a network-server?
CompanyID client_playas
As which company is this client playing (CompanyID)
mask for all command flags
DateFract _date_fract
Fractional part of the day.
NetworkAddress client_address
IP-address of the client (so he can be banned)
The client is spectating.
static uint NetworkCountActiveClients()
Counts the number of active clients connected.
char client_name[NETWORK_CLIENT_NAME_LENGTH]
Name of the client.
static Pool::IterateWrapper< ServerNetworkAdminSocketHandler > IterateActive(size_t from=0)
Returns an iterable ensemble of all active admin sockets.
Server part of the network protocol.
bool _network_need_advertise
Whether we need to advertise.
static ServerNetworkGameSocketHandler * GetByClientID(ClientID client_id)
Return the client state given it's client-identifier.
void IConsoleCmdExec(const char *cmdstr)
Execute a given command passed to us.
static void CheckCallbacks()
Check whether we need to call the callback, i.e.
Non blocking connection create to query servers.
static bool Receive()
Handle the receiving of packets.
ClientSettings _settings_client
The current settings for this game.
ClientID _network_own_client_id
Our client identifier.
FILE * FioFOpenFile(const char *filename, const char *mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
void CDECL IConsolePrintF(TextColour colour_code, const char *format,...)
Handle the printing of text entered into the console or redirected there by any other means...
void NetworkCoreShutdown()
Shuts down the network core (as that is needed for some platforms.
void NetworkServerSetCompanyPassword(CompanyID company_id, const char *password, bool already_hashed)
Set/Reset a company password on the server end.
Resolving of hostnames/IPs.
static const uint MAX_LENGTH_COMPANY_NAME_CHARS
The maximum length of a company name in characters including '\0'.
static void InitializeNetworkPools(bool close_admins=true)
Resets the pools used for network clients, and the admin pool if needed.
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
char connect_to_ip[NETWORK_HOSTNAME_LENGTH]
default for the "Add server" query
static void AcceptConnection(SOCKET s, const NetworkAddress &address)
Handle the accepting of a connection to the server.
NetworkCompanyState * _network_company_states
Statistics about some companies.
uint16 server_admin_port
port the server listens on for the admin network
const char * GetNetworkRevisionString()
Get the network version string used by this build.
uint8 _network_reconnect
Reconnect timeout.
static void CheckPauseHelper(bool pause, PauseMode pm)
Helper function for the pause checkers.
static ClientNetworkGameSocketHandler * my_client
This is us!
Base directory for all savegames.
void OnConnect(SOCKET s) override
Callback when the connection succeeded.
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
const char * GetHostname()
Get the hostname; in case it wasn't given the IPv4 dotted representation is given.
byte clients_on
Current count of clients on server.
NetworkGameList * _network_game_list
Game list of this client.
static void CheckPauseOnJoin()
Check whether we should pause on join.
Part of the network protocol handling content distribution.
void NetworkShutDown()
This shuts the network down.
bool DoCommandP(const CommandContainer *container, bool my_cmd)
Shortcut for the long DoCommandP when having a container with the data.
CompanyID company
company that is executing the command
#define lengthof(x)
Return the length of an fixed size array.
NetworkServerGameInfo _network_game_info
Information about our game.
PauseMode _pause_mode
The current pause mode.
static const uint NETWORK_HOSTNAME_LENGTH
The maximum length of the host name, in bytes including '\0'.
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Text is written left-to-right by default.
PauseMode
Modes of pausing we've got.
bool Listen()
Start listening on the given host and port.
void NetworkClient_Connected()
Is called after a client is connected to the server.
static bool NetworkHasJoiningClient()
Checks whether there is a joining client.
void OnFailure() override
Callback for when the connection attempt failed.
Base class for all pools.
The connection is 'just' lost.
#define DEBUG(name, level,...)
Output a line of debugging information.
void NetworkUDPInitialize()
Initialize the whole UDP bit.
Network status window; Window numbers:
void NetworkFreeLocalCommandQueue()
Free the local command queues.
StringList _network_host_list
The servers we know.
uint16 server_port
port the server listens on
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
Delete a window by its class and window number (if it is open).
uint16 network_chat_timeout
timeout of chat messages in seconds
static NetworkRecvStatus SendCompanyInformationQuery()
Query the server for company information.
bool HasClients()
Return whether there is any client connected or trying to connect at all.
bool pause_on_join
pause the game when people join
SOCKET Connect()
Connect to the given address.
byte _network_clients_connected
The amount of clients connected.
static const uint16 NETWORK_DEFAULT_PORT
The default port of the game server (TCP & UDP)
char client_name[NETWORK_CLIENT_NAME_LENGTH]
name of the player (as client)
GUISettings gui
settings related to the GUI
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
uint32 _frame_counter
The current frame.
Non blocking connection create to actually connect to servers.
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Randomizer _random
Random used in the game state calculations.
Handling of the list of games.
char network_id[NETWORK_SERVER_ID_LENGTH]
network ID for servers
First company, same as owner.
TextDirection _current_text_dir
Text direction of the currently selected language.
CompanyID _network_join_as
Who would we like to join as.
CompanyMask _network_company_passworded
Bitmask of the password status of all companies.
void NetworkClientSetCompanyPassword(const char *password)
Set/Reset company password on the client side.
void NetworkBackgroundUDPLoop()
Receive the UDP packets.
uint8 frame_freq
how often do we send commands to the clients
std::vector< std::string > StringList
Type for a list of strings.
static const uint NETWORK_COMPANY_NAME_LENGTH
The maximum length of the company name, in bytes including '\0'.
NetworkClientInfo(ClientID client_id=INVALID_CLIENT_ID)
Create a new client.
void NetworkClose(bool close_admins)
Close current connections.
uint32 _frame_counter_server
The frame_counter of the server, if in network-mode.
static const WChar CHAR_TD_RLM
The next character acts like a right-to-left character.
static const uint NETWORK_SERVER_ID_LENGTH
The maximum length of the network id of the servers, in bytes including '\0'.
Class for handling the server side of the game connection.
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Maximum number of companies.
StringList _network_ban_list
The banned clients.
void CDECL NetworkAddChatMessage(TextColour colour, uint duration, const char *message,...)
Add a text message to the 'chat window' to be shown.
SwitchMode _switch_mode
The next mainloop command.
const char * GenerateCompanyPasswordHash(const char *password, const char *password_server_id, uint32 password_game_seed)
Hash the given password using server ID and game seed.
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function() ...
char admin_password[NETWORK_PASSWORD_LENGTH]
password for the admin network
bool _network_server
network-server is active
static NetworkRecvStatus SendQuit()
Tell the server we would like to quit.
CompanyID _current_company
Company currently doing an action.
void NetworkUDPRemoveAdvertise(bool blocking)
Remove our advertise from the master-server.
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
void NetworkBackgroundLoop()
We have to do some (simple) background stuff that runs normally, even when we are not in multiplayer...
TileIndex tile
tile command being executed on.
uint32 _last_sync_frame
Used in the server to store the last time a sync packet was sent to clients.
uint16 GetPort() const
Get the port.
void NetworkDisconnect(bool blocking, bool close_admins)
We want to disconnect from the host/clients.
Everything we need to know about a command to be able to execute it.
static void Send()
Send the packets of this socket handler.
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
size_t Utf8Encode(char *buf, WChar c)
Encode a unicode character and place it in the buffer.
int32 Date
The type to store our dates in.
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
char last_host[NETWORK_HOSTNAME_LENGTH]
IP address of the last joined server.
static void CloseListeners()
Close the sockets we're listening on.
static const uint NETWORK_NAME_LENGTH
The maximum length of the server name and map name, in bytes including '\0'.
uint8 _network_advertise_retries
The number of advertisement retries we did.
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Servers always have this ID.
A game paused by a game script.
Some state information of a company, especially for servers.
StringList _network_bind_list
The addresses to bind on.
static const uint NETWORK_NUM_LANDSCAPES
The number of landscapes in OpenTTD.
NetworkUDPSocketHandler * _udp_master_socket
udp master socket
static NetworkClientInfo * GetByClientID(ClientID client_id)
Return the CI given it's client-identifier.
uint32 state[2]
The state of the randomizer.
static void CheckMinActiveClients()
Check if the minimum number of active clients has been reached and pause or unpause the game as appro...
const char * NetworkChangeCompanyPassword(CompanyID company_id, const char *password)
Change the company password of a given company.
static const uint NETWORK_REVISION_LENGTH
The maximum length of the revision, in bytes including '\0'.
NetworkUDPSocketHandler * _udp_server_socket
udp server socket
static bool Listen(uint16 port)
Listen on a particular port.
void NetworkUDPClose()
Close all UDP related stuff.
Date _date
Current date in days (day counter)
A game paused for 'pause_on_join'.
void NetworkDistributeCommands()
Distribute the commands of ourself and the clients.
uint32 _frame_counter_max
To where we may go with our clients.
static bool GameLoop()
Actual game loop for the client.
bool _network_first_time
Whether we have finished joining or not.
static void Send()
Send the packets for the server sockets.
uint32 cmd
command being executed.
Basic functions to receive and send UDP packets.
A game paused because a (critical) error.
NetworkAction
Actions that can be used for NetworkTextMessage.
static const uint GITHASH_SUFFIX_LEN
How many hex digits of the git hash to include in network revision string.
ClientNetworkContentSocketHandler _network_content_client
The client we use to connect to the server.
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-...
Server part of the admin network protocol.
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
uint8 min_active_clients
minimum amount of active clients to unpause the game