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"
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
95 return !NetworkClientSocket::Iterate().empty();
115 if (ci->client_id ==
client_id)
return ci;
128 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
129 if (cs->client_id ==
client_id)
return cs;
135 byte NetworkSpectatorCount()
157 if (strcmp(password,
"*") == 0) password =
"";
177 if (
StrEmpty(password))
return password;
181 memset(salted_password, 0,
sizeof(salted_password));
182 seprintf(salted_password,
lastof(salted_password),
"%s", password);
185 salted_password[i] ^= password_server_id[i] ^ (password_game_seed >> (i % 32));
193 checksum.Append(salted_password,
sizeof(salted_password) - 1);
194 checksum.Finish(digest);
196 for (
int di = 0; di < 16; di++)
seprintf(hashed_password + di * 2,
lastof(hashed_password),
"%02x", digest[di]);
198 return hashed_password;
214 void NetworkTextMessage(
NetworkAction action,
TextColour colour,
bool self_send,
const char *name,
const char *str, int64 data)
218 case NETWORK_ACTION_SERVER_MESSAGE:
220 strid = STR_NETWORK_SERVER_MESSAGE;
223 case NETWORK_ACTION_COMPANY_SPECTATOR:
225 strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_SPECTATE;
227 case NETWORK_ACTION_COMPANY_JOIN:
229 strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_JOIN;
231 case NETWORK_ACTION_COMPANY_NEW:
233 strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_NEW;
235 case NETWORK_ACTION_JOIN:
237 strid =
_network_server ? STR_NETWORK_MESSAGE_CLIENT_JOINED_ID : STR_NETWORK_MESSAGE_CLIENT_JOINED;
239 case NETWORK_ACTION_LEAVE: strid = STR_NETWORK_MESSAGE_CLIENT_LEFT;
break;
240 case NETWORK_ACTION_NAME_CHANGE: strid = STR_NETWORK_MESSAGE_NAME_CHANGE;
break;
241 case NETWORK_ACTION_GIVE_MONEY: strid = STR_NETWORK_MESSAGE_GIVE_MONEY;
break;
242 case NETWORK_ACTION_CHAT_COMPANY: strid = self_send ? STR_NETWORK_CHAT_TO_COMPANY : STR_NETWORK_CHAT_COMPANY;
break;
243 case NETWORK_ACTION_CHAT_CLIENT: strid = self_send ? STR_NETWORK_CHAT_TO_CLIENT : STR_NETWORK_CHAT_CLIENT;
break;
244 case NETWORK_ACTION_KICKED: strid = STR_NETWORK_MESSAGE_KICKED;
break;
245 default: strid = STR_NETWORK_CHAT_ALL;
break;
258 GetString(msg_ptr, strid,
lastof(message));
266 uint NetworkCalculateLag(
const NetworkClientSocket *cs)
268 int lag = cs->last_frame_server - cs->last_frame;
281 void NetworkError(
StringID error_string)
296 static const StringID network_error_strings[] = {
297 STR_NETWORK_ERROR_CLIENT_GENERAL,
298 STR_NETWORK_ERROR_CLIENT_DESYNC,
299 STR_NETWORK_ERROR_CLIENT_SAVEGAME,
300 STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST,
301 STR_NETWORK_ERROR_CLIENT_PROTOCOL_ERROR,
302 STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH,
303 STR_NETWORK_ERROR_CLIENT_NOT_AUTHORIZED,
304 STR_NETWORK_ERROR_CLIENT_NOT_EXPECTED,
305 STR_NETWORK_ERROR_CLIENT_WRONG_REVISION,
306 STR_NETWORK_ERROR_CLIENT_NAME_IN_USE,
307 STR_NETWORK_ERROR_CLIENT_WRONG_PASSWORD,
308 STR_NETWORK_ERROR_CLIENT_COMPANY_MISMATCH,
309 STR_NETWORK_ERROR_CLIENT_KICKED,
310 STR_NETWORK_ERROR_CLIENT_CHEATER,
311 STR_NETWORK_ERROR_CLIENT_SERVER_FULL,
312 STR_NETWORK_ERROR_CLIENT_TOO_MANY_COMMANDS,
313 STR_NETWORK_ERROR_CLIENT_TIMEOUT_PASSWORD,
314 STR_NETWORK_ERROR_CLIENT_TIMEOUT_COMPUTER,
315 STR_NETWORK_ERROR_CLIENT_TIMEOUT_MAP,
316 STR_NETWORK_ERROR_CLIENT_TIMEOUT_JOIN,
318 static_assert(
lengthof(network_error_strings) == NETWORK_ERROR_END);
320 if (err >= (ptrdiff_t)
lengthof(network_error_strings)) err = NETWORK_ERROR_GENERAL;
322 return network_error_strings[err];
334 switch (changed_mode) {
342 if (!paused && !changed)
return;
353 str = STR_NETWORK_SERVER_MESSAGE_GAME_STILL_PAUSED_1 + i;
355 switch (changed_mode) {
361 default: NOT_REACHED();
363 str = paused ? STR_NETWORK_SERVER_MESSAGE_GAME_PAUSED : STR_NETWORK_SERVER_MESSAGE_GAME_UNPAUSED;
367 GetString(buffer, str,
lastof(buffer));
368 NetworkTextMessage(NETWORK_ACTION_SERVER_MESSAGE,
CC_DEFAULT,
false,
nullptr, buffer);
402 for (
const NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
403 if (cs->status != NetworkClientSocket::STATUS_ACTIVE)
continue;
430 for (
const NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
431 if (cs->status >= NetworkClientSocket::STATUS_AUTHORIZED && cs->status < NetworkClientSocket::STATUS_ACTIVE)
return true;
459 bool ipv6 = (strchr(connection_string,
':') != strrchr(connection_string,
':'));
461 for (p = connection_string; *p !=
'\0'; p++) {
518 as->CloseConnection(
true);
522 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
546 static void NetworkInitialize(
bool close_admins =
true)
591 void NetworkAddServer(
const char *b)
594 const char *port =
nullptr;
595 const char *company =
nullptr;
605 if (port !=
nullptr) rport = atoi(port);
619 addresses->emplace_back(iter.c_str(), port);
623 if (addresses->size() == 0) {
624 addresses->emplace_back(
"", port);
631 void NetworkRebuildHostList()
636 if (item->manually)
_network_host_list.emplace_back(item->address.GetAddressAsString(
false));
647 NetworkError(STR_NETWORK_ERROR_NOCONNECTION);
661 void NetworkClientConnectGame(
NetworkAddress address,
CompanyID join_as,
const char *join_server_password,
const char *join_company_password)
665 if (address.
GetPort() == 0)
return;
677 ShowJoinStatusWindow();
682 static void NetworkInitGameInfo()
699 bool NetworkServerStart()
708 NetworkInitialize(
false);
709 DEBUG(net, 1,
"starting listeners for clients");
714 DEBUG(net, 1,
"starting listeners for admins");
719 DEBUG(net, 1,
"starting listeners for incoming server queries");
734 NetworkInitGameInfo();
756 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
780 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
818 static void NetworkSend()
844 void NetworkGameLoop()
854 static Date last_log;
855 if (last_log !=
_date) {
861 #ifdef DEBUG_DUMP_COMMANDS
864 static Date next_date = 0;
865 static uint32 next_date_fract;
867 static bool check_sync_state =
false;
868 static uint32 sync_state[2];
869 if (f ==
nullptr && next_date == 0) {
870 DEBUG(net, 0,
"Cannot open commands.log");
874 while (f !=
nullptr && !feof(f)) {
878 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));
882 if (check_sync_state) {
886 DEBUG(net, 0,
"sync check: %08x; %02x; mismatch expected {%08x, %08x}, got {%08x, %08x}",
890 check_sync_state =
false;
894 if (cp !=
nullptr || check_sync_state)
break;
897 if (fgets(buff,
lengthof(buff), f) ==
nullptr)
break;
903 if (p ==
nullptr)
break;
907 if (strncmp(p,
"cmd: ", 5) == 0
908 #ifdef DEBUG_FAILED_DUMP_COMMANDS
909 || strncmp(p,
"cmdf: ", 6) == 0
914 cp = CallocT<CommandPacket>(1);
916 static_assert(
sizeof(cp->
text) == 128);
917 int ret = sscanf(p,
"%x; %x; %x; %x; %x; %x; %x; \"%127[^\"]\"", &next_date, &next_date_fract, &company, &cp->
tile, &cp->
p1, &cp->
p2, &cp->
cmd, cp->
text);
921 assert(ret == 8 || ret == 7);
923 }
else if (strncmp(p,
"join: ", 6) == 0) {
925 int ret = sscanf(p + 6,
"%x; %x", &next_date, &next_date_fract);
927 DEBUG(net, 0,
"injecting pause for join at %08x:%02x; please join when paused", next_date, next_date_fract);
928 cp = CallocT<CommandPacket>(1);
934 }
else if (strncmp(p,
"sync: ", 6) == 0) {
935 int ret = sscanf(p + 6,
"%x; %x; %x; %x", &next_date, &next_date_fract, &sync_state[0], &sync_state[1]);
937 check_sync_state =
true;
938 }
else if (strncmp(p,
"msg: ", 5) == 0 || strncmp(p,
"client: ", 8) == 0 ||
939 strncmp(p,
"load: ", 6) == 0 || strncmp(p,
"save: ", 6) == 0) {
941 #ifndef DEBUG_FAILED_DUMP_COMMANDS
942 }
else if (strncmp(p,
"cmdf: ", 6) == 0) {
943 DEBUG(net, 0,
"Skipping replay of failed command: %s", p + 6);
947 DEBUG(net, 0,
"trying to parse: %s", p);
951 if (f !=
nullptr && feof(f)) {
952 DEBUG(net, 0,
"End of commands.log");
966 bool send_frame =
false;
982 #ifdef NETWORK_SEND_DOUBLE_SEED
1008 static void NetworkGenerateServerId()
1012 char hex_output[16 * 2 + 1];
1016 seprintf(coding_string,
lastof(coding_string),
"%d%s", (uint)Random(),
"OpenTTD Server ID");
1019 checksum.Append((
const uint8*)coding_string, strlen(coding_string));
1020 checksum.Finish(digest);
1022 for (di = 0; di < 16; ++di) {
1023 seprintf(hex_output + di * 2,
lastof(hex_output),
"%02x", digest[di]);
1032 extern SOCKET _debug_socket;
1037 if (s == INVALID_SOCKET) {
1038 DEBUG(net, 0,
"Failed to open socket for redirection DEBUG()");
1044 DEBUG(net, 0,
"DEBUG() is now redirected");
1050 DEBUG(net, 3,
"[core] starting network...");
1062 NetworkInitialize();
1063 DEBUG(net, 3,
"[core] network online, multiplayer available");
1073 DEBUG(net, 3,
"[core] shutting down network");
1093 static char *network_revision =
nullptr;
1095 if (!network_revision) {
1097 network_revision =
stredup(_openttd_revision);
1102 if (_openttd_revision_tagged) {
1103 DEBUG(net, 1,
"Network revision name is '%s'", network_revision);
1104 return network_revision;
1109 assert(_openttd_revision_modified < 3);
1111 githash_suffix[1] =
"gum"[_openttd_revision_modified];
1113 githash_suffix[i] = _openttd_revision_hash[i-2];
1118 ptrdiff_t hashofs = strrchr(_openttd_revision,
'-') - _openttd_revision;
1119 if (hashofs + strlen(githash_suffix) + 1 >
NETWORK_REVISION_LENGTH) hashofs = strlen(network_revision) - strlen(githash_suffix);
1123 DEBUG(net, 1,
"Network revision name is '%s'", network_revision);
1126 return network_revision;
1129 static const char *ExtractNetworkRevisionHash(
const char *revstr)
1131 return strrchr(revstr,
'-');
1146 if (_openttd_revision_tagged)
return false;
1149 const char *hash2 = ExtractNetworkRevisionHash(other);
1153 #ifdef __EMSCRIPTEN__
1156 void CDECL em_openttd_add_server(
const char *host,
int port)
static void CheckCallbacks()
Check whether we need to call the callback, i.e.
TCPConnecter(const NetworkAddress &address)
Create a new connecter for the given address.
SOCKET Connect()
Connect to the given address.
uint32 cmd
command being executed.
char client_name[NETWORK_CLIENT_NAME_LENGTH]
name of the player (as client)
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-...
uint32 _frame_counter
The current frame.
static const uint16 NETWORK_DEFAULT_PORT
The default port of the game server (TCP & UDP)
void NetworkClientSetCompanyPassword(const char *password)
Set/Reset company password on the client side.
@ SAVE_DIR
Base directory for all savegames.
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
void SendReceive()
Check whether we received/can send some data from/to the content server and when that's the case hand...
void NetworkServerSetCompanyPassword(CompanyID company_id, const char *password, bool already_hashed)
Set/Reset a company password on the server end.
NetworkServerGameInfo _network_game_info
Information about our game.
void NetworkUDPServerListen()
Start the listening of the UDP server component.
void GetBindAddresses(NetworkAddressList *addresses, uint16 port)
Get the addresses to bind to.
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.
char connect_to_ip[NETWORK_HOSTNAME_LENGTH]
default for the "Add server" query
CompanyID _network_join_as
Who would we like to join as.
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.
const char * GetCommandName(uint32 cmd)
NetworkAction
Actions that can be used for NetworkTextMessage.
char client_name[NETWORK_CLIENT_NAME_LENGTH]
Name of the client.
static const uint NETWORK_NUM_LANDSCAPES
The number of landscapes in OpenTTD.
const char * GetNetworkRevisionString()
Get the network version string used by this build.
@ WC_CLIENT_LIST
Client list; Window numbers:
static void WelcomeAll()
Send a Welcome packet to all connected admins.
char network_id[NETWORK_SERVER_ID_LENGTH]
network ID for servers
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.
NetworkClientInfoPool _networkclientinfo_pool("NetworkClientInfo")
Make sure both pools have the same size.
bool pause_on_join
pause the game when people join
The game information that is not generated on-the-fly and has to be sent to the clients.
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.
char text[32 *MAX_CHAR_LENGTH]
possible text sent for name changes etc, in bytes including '\0'.
ClientSettings _settings_client
The current settings for this game.
StringList _network_bind_list
The addresses to bind on.
void NetworkUDPAdvertise()
Register us to the master server This function checks if it needs to send an advertise.
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!
const char * _network_join_company_password
Company password from -P argument.
char admin_password[NETWORK_PASSWORD_LENGTH]
password for the admin network
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.
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 void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
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 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 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.
@ PM_UNPAUSED
A normal unpaused game.
bool HasClients()
Return whether there is any client connected or trying to connect at all.
void NetworkUDPQueryServer(NetworkAddress address, bool manually)
Query a specific server.
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.
CompanyID company
company that is executing the command
static void Send()
Send the packets for the server sockets.
const char * _network_join_server_password
Login password from -p argument.
@ NETWORK_RECV_STATUS_CONN_LOST
The connection is 'just' lost.
static const int DRAW_STRING_BUFFER
Size of the buffer used for drawing strings.
Everything we need to know about a command to be able to execute it.
Date _date
Current date in days (day counter)
bool DoCommandP(const CommandContainer *container, bool my_cmd)
Shortcut for the long DoCommandP when having a container with the data.
char last_host[NETWORK_HOSTNAME_LENGTH]
IP address of the last joined server.
std::vector< NetworkAddress > NetworkAddressList
Type for a list of addresses.
@ CMD_PAUSE
pause the game
#define DEBUG(name, level,...)
Output a line of debugging information.
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.
const char * GetHostname()
Get the hostname; in case it wasn't given the IPv4 dotted representation is given.
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
void ParseConnectionString(const char **company, const char **port, char *connection_string)
Converts a string to ip/port/company Format: IP:port::company.
PauseMode _pause_mode
The current pause mode.
void NetworkClient_Connected()
Is called after a client is connected to the server.
bool IsNetworkCompatibleVersion(const char *other)
Checks whether the given version string is compatible with our version.
void OnFailure() override
Callback for when the connection attempt failed.
uint32 _sync_seed_1
Seed to compare during sync checks.
uint16 GetPort() const
Get the port.
@ 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.
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.
void NetworkUDPRemoveAdvertise(bool blocking)
Remove our advertise from the master-server.
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
static const uint NETWORK_SERVER_ID_LENGTH
The maximum length of the network id of the servers, in bytes including '\0'.
bool _networking
are we in networking mode?
uint16 last_port
port of the last joined server
static void CheckPauseHelper(bool pause, PauseMode pm)
Helper function for the pause checkers.
@ PT_NONE
No pool is selected.
static ServerNetworkGameSocketHandler * GetByClientID(ClientID client_id)
Return the client state given it's client-identifier.
@ CMD_FLAGS_MASK
mask for all command flags
char server_name[NETWORK_NAME_LENGTH]
name of the server
PauseMode
Modes of pausing we've got.
uint8 _network_reconnect
Reconnect timeout.
bool _network_dedicated
are we a dedicated server?
static void KillAll()
Kill all connection attempts.
NetworkAddress address
Address we're connecting to.
@ PM_PAUSED_GAME_SCRIPT
A game paused by a game script.
uint32 state[2]
The state of the randomizer.
static const uint NETWORK_REVISION_LENGTH
The maximum length of the revision, in bytes including '\0'.
static void AcceptConnection(SOCKET s, const NetworkAddress &address)
Handle the accepting of a connection to the server.
@ PT_NCLIENT
Network client pools.
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.
static NetworkRecvStatus SendCompanyInformationQuery()
Make sure the server ID length is the same as a md5 hash.
bool server_advertise
advertise the server to the masterserver
void NetworkBackgroundUDPLoop()
Receive the UDP packets.
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.
#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 DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
Delete a window by its class and window number (if it is open).
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.
@ 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.
@ PM_PAUSED_NORMAL
A game normally paused.
static void HTTPReceive()
Do the receiving for all HTTP connections.
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:
bool _network_need_advertise
Whether we need to advertise.
@ 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.
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
@ 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...
const char * NetworkChangeCompanyPassword(CompanyID company_id, const char *password)
Change the company password of a given company.
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.
#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
void NetworkClose(bool close_admins)
Close current connections.
ServerNetworkGameSocketHandler(SOCKET s)
Create a new socket for the server side of the game connection.
NetworkAddress client_address
IP-address of the client (so he can be banned)
static const uint NETWORK_HOSTNAME_LENGTH
The maximum length of the host name, in bytes including '\0'.
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.
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.
void NetworkStartUp()
This tries to launch the network for a given OS.
StringList _network_host_list
The servers we know.
TileIndex tile
tile command being executed on.
byte clients_on
Current count of clients on server.
bool _network_available
is network mode available?
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
@ WN_NETWORK_STATUS_WINDOW_JOIN
Network join status.
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
static bool NetworkReceive()
Receives something from the network.
@ PM_PAUSED_ERROR
A game paused because a (critical) error.
void NetworkFreeLocalCommandQueue()
Free the local command queues.
static const uint GITHASH_SUFFIX_LEN
How many hex digits of the git hash to include in network revision string.
uint16 network_chat_timeout
timeout of chat messages in seconds
#define lastof(x)
Get the last element of an fixed size array.
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 create to query servers.
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 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 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 CDECL NetworkAddChatMessage(TextColour colour, uint duration, const char *message,...)
Add a text message to the 'chat window' to be shown.
void NetworkDistributeCommands()
Distribute the commands of ourself and the clients.
static const uint NETWORK_COMPANY_NAME_LENGTH
The maximum length of the company name, in bytes including '\0'.