37#include <condition_variable>
39#include "table/strings.h"
70 std::deque<std::unique_ptr<Packet>>
packets;
85 std::unique_lock<std::mutex>
lock(this->mutex);
87 while (this->cs !=
nullptr) this->exit_sig.wait(
lock);
91 this->packets.clear();
92 this->current =
nullptr;
107 std::unique_lock<std::mutex>
lock(this->mutex);
111 this->exit_sig.notify_all();
128 if (this->packets.empty())
return false;
130 std::lock_guard<std::mutex>
lock(this->mutex);
132 while (!this->packets.empty()) {
134 this->cs->
SendPacket(std::move(this->packets.front()));
135 this->packets.pop_front();
137 if (last_packet)
return true;
143 void Write(
const uint8_t *buf,
size_t size)
override
145 std::lock_guard<std::mutex>
lock(this->mutex);
148 if (this->cs ==
nullptr)
SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
152 std::span<const uint8_t> to_write(buf, size);
153 while (!to_write.empty()) {
154 to_write = this->current->Send_bytes(to_write);
156 if (!this->current->CanWriteToPacket(1)) {
157 this->packets.push_back(std::move(this->current));
162 this->total_size += size;
167 std::lock_guard<std::mutex>
lock(this->mutex);
170 if (this->cs ==
nullptr)
SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
173 if (this->current !=
nullptr) this->packets.push_back(std::move(this->current));
180 p->Send_uint32((uint32_t)this->total_size);
181 this->packets.push_front(std::move(p));
372 if (!reason.empty()) p->Send_string(reason);
396 new_cs->SendErrorQuit(this->
client_id, error);
431 p->Send_uint8 (grf_count);
532 if (new_cs->GetInfo()->join_date < this->GetInfo()->join_date || (new_cs->GetInfo()->join_date == this->GetInfo()->join_date && new_cs->client_id < this->client_id)) waiting++;
536 p->Send_uint8(waiting);
552 if (ignore_cs == new_cs)
continue;
562 if (best !=
nullptr) {
589 this->
savegame = std::make_shared<PacketWriter>(
this);
653#ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
655#ifdef NETWORK_SEND_DOUBLE_SEED
656 p->Send_uint32(_sync_seed_2);
662 this->
last_token = InteractiveRandomRange(UINT8_MAX - 1) + 1;
682#ifdef NETWORK_SEND_DOUBLE_SEED
683 p->Send_uint32(_sync_seed_2);
701 p->Send_uint32(cp.
frame);
727 p->Send_bool (self_send);
729 p->Send_uint64(data);
751 p->Send_string(source);
753 p->Send_string(user);
834 p->Send_uint16(colour);
835 p->Send_string(command);
853 p->Send_uint8(company_id);
935 switch (playas.base()) {
1092 new_cs->SendClientInfo(this->
GetInfo());
1128 if (err.has_value()) {
1173 if (!public_key.empty()) {
1176 if (
info->public_key == public_key) {
1215 new_cs->SendErrorQuit(this->
client_id, errorno);
1317 if (ci !=
nullptr) {
1328 cs->SendChat(action, from_id,
false, msg, data);
1339 if (ci !=
nullptr && ci_to !=
nullptr) {
1345 cs->SendChat(action, (
ClientID)dest,
true, msg, data);
1354 bool show_local =
true;
1360 cs->SendChat(action, from_id,
false, msg, data);
1361 if (cs->client_id == from_id) show_local =
false;
1373 if (ci !=
nullptr && ci_own !=
nullptr && ci_own->
client_playas == dest) {
1380 if (ci_to ==
nullptr)
break;
1383 if (ci !=
nullptr && show_local) {
1391 cs->SendChat(action, ci_to->
client_id,
true, msg, data);
1410 if (ci !=
nullptr) {
1478 if (ci !=
nullptr) {
1527 CompanyID company_id = (Owner)p.
Recv_uint8();
1566 stats[v->owner].num_vehicle[type]++;
1593 if (ci ==
nullptr)
return;
1599 cs->SendClientInfo(ci);
1625 assert(ci !=
nullptr);
1631 if (std::any_of(std::begin(c->group_all), std::end(c->group_all), [](
const GroupStatistics &gs) { return gs.num_vehicle != 0; })) has_vehicles.
Set(c->index);
1638 if (c->is_ai)
continue;
1640 if (!has_clients.
Test(c->index)) {
1642 if (c->months_empty != std::numeric_limits<
decltype(c->months_empty)>::max()) c->months_empty++;
1658 c->months_empty = 0;
1670 bool is_name_unique =
false;
1671 std::string original_name = name;
1673 for (uint number = 1; !is_name_unique && number <=
MAX_CLIENTS; number++) {
1674 is_name_unique =
true;
1676 if (ci->client_name == name) {
1678 is_name_unique =
false;
1684 if (ci !=
nullptr) {
1685 if (ci->
client_name == name) is_name_unique =
false;
1688 if (!is_name_unique) {
1690 name = fmt::format(
"{} #{}", original_name, number);
1698 return is_name_unique;
1711 if (ci->client_name == new_name)
return false;
1715 if (ci ==
nullptr)
return false;
1731 for (
auto &cp : cs->outgoing_queue) cs->SendCommand(cp);
1732 cs->outgoing_queue.clear();
1741#ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1742 bool send_sync =
false;
1745#ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1757 cs->receive_limit = std::min<size_t>(cs->receive_limit +
_settings_client.network.bytes_per_frame,
1762 switch (cs->status) {
1763 case NetworkClientSocket::ClientStatus::Active:
1767 if (cs->last_packet + std::chrono::milliseconds(lag *
MILLISECONDS_PER_TICK) > std::chrono::steady_clock::now()) {
1769 IConsolePrint(
CC_WARNING,
"Client #{} (IP: {}) is dropped because the client's game state is more than {} ticks behind.", cs->client_id, cs->GetClientIP(), lag);
1772 IConsolePrint(
CC_WARNING,
"Client #{} (IP: {}) is dropped because the client did not respond for more than {} ticks.", cs->client_id, cs->GetClientIP(), lag);
1783 if (lag > (uint)
Ticks::DAY_TICKS && cs->lag_test == 0 && cs->last_packet + std::chrono::seconds(2) > std::chrono::steady_clock::now()) {
1788 if (cs->last_frame_server - cs->last_token_frame >=
_settings_client.network.max_lag_time) {
1790 IConsolePrint(
CC_WARNING,
"Client #{} (IP: {}) is dropped because it fails to send valid acks.", cs->client_id, cs->GetClientIP());
1796 case NetworkClientSocket::ClientStatus::Inactive:
1797 case NetworkClientSocket::ClientStatus::Identify:
1798 case NetworkClientSocket::ClientStatus::NewGRFsCheck:
1799 case NetworkClientSocket::ClientStatus::Authorized:
1803 IConsolePrint(
CC_WARNING,
"Client #{} (IP: {}) is dropped because it took longer than {} ticks to start the joining process.", cs->client_id, cs->GetClientIP(),
_settings_client.network.max_init_time);
1809 case NetworkClientSocket::ClientStatus::MapWait:
1813 if (std::chrono::steady_clock::now() > cs->last_packet + std::chrono::seconds(2)) {
1820 cs->last_packet = std::chrono::steady_clock::now();
1824 case NetworkClientSocket::ClientStatus::Map:
1827 IConsolePrint(
CC_WARNING,
"Client #{} (IP: {}) is dropped because it took longer than {} ticks to download the map.", cs->client_id, cs->GetClientIP(),
_settings_client.network.max_download_time);
1833 case NetworkClientSocket::ClientStatus::DoneMap:
1834 case NetworkClientSocket::ClientStatus::PreActive:
1843 case NetworkClientSocket::ClientStatus::AuthGame:
1846 IConsolePrint(
CC_WARNING,
"Client #{} (IP: {}) is dropped because it took longer than {} ticks to enter the password.", cs->client_id, cs->GetClientIP(),
_settings_client.network.max_password_time);
1852 case NetworkClientSocket::ClientStatus::End:
1857 if (cs->status >= NetworkClientSocket::ClientStatus::PreActive) {
1862 if (send_frame) cs->SendFrame();
1864#ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1866 if (send_sync) cs->SendSync();
1990 "identifying client",
2002 if (ci ==
nullptr)
continue;
2005 std::string_view status = (
to_underlying(cs->status) < std::size(stat_str) ? stat_str[cs->status] :
"unknown");
2019 if (cs->status >= NetworkClientSocket::ClientStatus::PreActive) cs->SendConfigUpdate();
2040 assert(ci !=
nullptr);
2052 if (cs->status < NetworkClientSocket::ClientStatus::Authorized)
return;
2053 cs->SendMove(client_id, company_id);
2064 std::string company_name =
GetString(STR_COMPANY_NAME, company_id);
2080 NetworkClientSocket::GetByClientID(client_id)->SendRConResult(colour_code.
ToNetwork(),
string);
2117 bool contains =
false;
2137 if (cs->client_address.IsInNetmask(ip)) {
2154 if (ci->client_playas == company)
return true;
2169 return fmt::format(
"Client #{}", this->
client_id);
2183 ci->client_id ==
ClientID::Server ?
"server" : NetworkClientSocket::GetByClientID(ci->client_id)->GetClientIP());
2200 auto socket = NetworkClientSocket::GetByClientID(client_id);
2201 return socket ==
nullptr ?
"" : socket->GetPeerPublicKey();
2212 assert(c !=
nullptr);
2216 if (ci !=
nullptr) {
2228 Command<Commands::RenamePresident>::SendNet(STR_NULL, c->index, ci->
client_name);
std::map< SOCKET, NetworkAddress > SocketList
Type for a mapping between address and socket.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Timpl & Set()
Set all bits.
An interval timer will fire every interval, and will continue to fire until it is deleted.
Default implementation for the authorized key handler.
Default implementation of the password provider.
static std::unique_ptr< NetworkAuthenticationServerHandler > Create(const NetworkAuthenticationPasswordProvider *password_provider, const NetworkAuthenticationAuthorizedKeyHandler *authorized_key_handler, NetworkAuthenticationMethodMask client_supported_method_mask={NetworkAuthenticationMethod::X25519_KeyExchangeOnly, NetworkAuthenticationMethod::X25519_PAKE, NetworkAuthenticationMethod::X25519_AuthorizedKey})
Create a NetworkAuthenticationServerHandler.
@ RetryNextMethod
The client failed to authenticate, but there is another method to try.
@ NotAuthenticated
All authentications for this handler have been exhausted.
@ Authenticated
The client was authenticated successfully.
bool Contains(std::string_view key) const
Check whether the given key is contains in these authorized keys.
bool IsPendingDeletion() const
Is this pending for deletion and as such should not be accessed anymore.
NetworkGameSocketHandler(SOCKET s)
Create a new socket for the game connection.
uint32_t last_frame
Last frame we have executed.
NetworkClientInfo * GetInfo() const
Gets the client info of this socket handler.
std::optional< std::string_view > ReceiveCommand(Packet &p, CommandPacket &cp)
Receives a command from the network.
ClientID client_id
Client identifier.
CommandQueue incoming_queue
The command-queue awaiting handling.
std::chrono::steady_clock::time_point last_packet
Time we received the last frame.
void SetInfo(NetworkClientInfo *info)
Sets the client info for this socket handler.
uint32_t last_frame_server
Last frame the server has executed.
NetworkClientInfo * info
Client info related to this socket.
void SendCommand(Packet &p, const CommandPacket &cp)
Sends a command over the network.
void DeferDeletion()
Mark this socket handler for deletion, once iterating the socket handlers is done.
bool HasClientQuit() const
Whether the current client connected to the socket has quit.
std::unique_ptr< class NetworkEncryptionHandler > send_encryption_handler
The handler for encrypting sent packets.
std::unique_ptr< class NetworkEncryptionHandler > receive_encryption_handler
The handler for decrypting received packets.
virtual std::unique_ptr< Packet > ReceivePacket()
Receives a packet for the given client.
SOCKET sock
The socket currently connected to.
virtual void SendPacket(std::unique_ptr< Packet > &&packet)
This function puts the packet in the send-queue and it is send as soon as possible.
SendPacketsState SendPackets(bool closing_down=false)
Sends all the buffered packets out for this client.
Class for handling the server side of the game connection.
static std::string_view GetName()
Get the name used by the listener.
NetworkRecvStatus ReceiveClientGameInfo(Packet &p) override
Request game information.
size_t receive_limit
Amount of bytes that we can receive at this moment.
std::shared_ptr< struct PacketWriter > savegame
Writer used to write the savegame.
static void Send()
Send the packets for the server sockets.
NetworkRecvStatus SendQuit(ClientID client_id)
Tell the client another client quit.
NetworkRecvStatus ReceiveClientIdentify(Packet &p) override
The client tells the server about the identity of the client: string Name of the client (max NETWORK_...
std::unique_ptr< Packet > ReceivePacket() override
Receives a packet for the given client.
@ MapWait
The client is waiting as someone else is downloading the map.
@ PreActive
The client is catching up the delayed frames.
@ Inactive
The client is not connected nor active.
@ Map
The client is downloading the map.
@ Active
The client is active within in the game.
@ Identify
The client is identifying itself.
@ NewGRFsCheck
The client is checking NewGRFs.
@ Authorized
The client is authorized.
@ DoneMap
The client has downloaded the map.
@ AuthGame
The client is authorizing with game (server) password.
NetworkRecvStatus SendRConResult(uint16_t colour, std::string_view command)
Send the result of a console action.
NetworkRecvStatus ReceiveClientAck(Packet &p) override
Tell the server we are done with this frame: uint32_t Current frame counter of the client.
NetworkRecvStatus SendChat(NetworkAction action, ClientID client_id, bool self_send, std::string_view msg, int64_t data)
Send a chat message.
NetworkRecvStatus SendWelcome()
Send the client a welcome message with some basic information.
NetworkRecvStatus SendAuthRequest()
Request the game password.
std::string GetClientName() const
Get the name of the client, if the user did not send it yet, Client ID is used.
NetworkRecvStatus ReceiveClientRemoteConsoleCommand(Packet &p) override
Send an RCon command to the server: string RCon password.
uint8_t last_token
The last random token we did send to verify the client is listening.
NetworkRecvStatus SendFrame()
Tell the client that they may run to a particular frame.
NetworkRecvStatus ReceiveClientSetName(Packet &p) override
Gives the client a new name: string New name of the client.
NetworkRecvStatus SendGameInfo()
Send the client information about the server.
NetworkRecvStatus SendJoin(ClientID client_id)
Tell that a client joined.
~ServerNetworkGameSocketHandler() override
Clear everything related to this client.
NetworkRecvStatus ReceiveClientChat(Packet &p) override
Sends a chat-packet to the server: uint8_t ID of the action (see NetworkAction).
NetworkRecvStatus ReceiveClientNewGRFsChecked(Packet &p) override
Tell the server that we have the required GRFs.
std::string peer_public_key
The public key of our client.
NetworkRecvStatus ReceiveClientGetMap(Packet &p) override
Request the map from the server.
NetworkRecvStatus SendClientInfo(NetworkClientInfo *ci)
Send the client information about a client.
static bool AllowConnection()
Whether an connection is allowed or not at this moment.
NetworkRecvStatus SendEnableEncryption()
Notify the client that the authentication has completed and tell that for the remainder of this socke...
ServerNetworkGameSocketHandler(ClientPoolID index, SOCKET s)
Create a new socket for the server side of the game connection.
NetworkRecvStatus SendErrorQuit(ClientID client_id, NetworkErrorCode errorno)
Tell the client another client quit with an error.
NetworkAddress client_address
IP-address of the client (so they can be banned).
NetworkRecvStatus SendNewGame()
Tell the client we're starting a new game.
NetworkRecvStatus ReceiveClientCommand(Packet &p) override
Send a DoCommand to the Server: uint8_t ID of the company (0..MAX_COMPANIES-1).
NetworkRecvStatus SendSync()
Request the client to sync.
std::unique_ptr< class NetworkAuthenticationServerHandler > authentication_handler
The handler for the authentication.
NetworkRecvStatus ReceiveClientJoin(Packet &p) override
Try to join the server: string OpenTTD revision (norev0000 if no revision).
NetworkRecvStatus ReceiveClientError(Packet &p) override
The client made an error and is quitting the game.
NetworkRecvStatus SendMove(ClientID client_id, CompanyID company_id)
Tell that a client moved to another company.
NetworkRecvStatus SendError(NetworkErrorCode error, std::string_view reason={})
Send an error to the client, and close its connection.
NetworkRecvStatus CloseConnection(NetworkRecvStatus status) override
Close the network connection due to the given status.
NetworkRecvStatus SendMap()
This sends the map to the client.
uint32_t last_token_frame
The last frame we received the right token.
NetworkRecvStatus SendExternalChat(std::string_view source, ExtendedTextColour colour, std::string_view user, std::string_view msg)
Send a chat message from external source.
NetworkRecvStatus SendShutdown()
Tell the client we're shutting down.
NetworkRecvStatus ReceiveClientMapOk(Packet &p) override
Tell the server that we are done receiving/loading the map.
NetworkRecvStatus ReceiveClientQuit(Packet &p) override
The client is quitting the game.
ClientStatus status
Status of this client.
void CheckNextClientToSendMap(NetworkClientSocket *ignore_cs=nullptr)
Find the next candidate for joining, and start the joining process for that client.
NetworkRecvStatus SendNewGRFCheck()
Send the check for the NewGRFs.
NetworkRecvStatus ReceiveClientAuthenticationResponse(Packet &p) override
Send the response to the authentication request: 32 * uint8_t Public key of the client.
std::string_view GetClientIP()
Get the IP address/hostname of the connected client.
NetworkRecvStatus SendConfigUpdate()
Send an update about the max company/spectator counts.
NetworkRecvStatus SendWait()
Tell the client that its put in a waiting queue.
NetworkRecvStatus ReceiveClientMove(Packet &p) override
Request the server to move this client into another company: uint8_t ID of the company the client wan...
NetworkRecvStatus SendCommand(const CommandPacket &cp)
Send a command to the client to execute.
Template for TCP listeners.
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static Year year
Current year, starting at 0.
static Date date
Current date in days (day counter).
static DateFract date_fract
Fractional part of the day.
@ Unpaused
Only run when not paused.
CommandFlags GetCommandFlags(Commands cmd)
Get the command flags associated with the given command.
Functions related to commands.
@ Spectator
the command may be initiated by a spectator
@ Server
the command can only be initiated by the server
@ ClientID
set p2 with the ClientID of the sending client.
@ CompanyControl
used in multiplayer to create a new companies etc.
@ CompanyAllowListControl
Used in multiplayer to add/remove a client's public key to/from the company's allow list.
Definition of stuff that is very close to a company, like the company struct itself.
void SetLocalCompany(CompanyID new_company, bool switching_game)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
ExtendedTextColour GetDrawStringCompanyColour(CompanyID company)
Get the colour for DrawString-subroutines which matches the colour of the company.
Command definitions related to companies.
Functions related to companies.
GUI Functions related to companies.
CompanyCtrlAction
The action to do with Commands::CompanyControl.
@ New
Create a new company.
@ Delete
Delete a company.
static constexpr CompanyID COMPANY_SPECTATOR
The client is spectating.
@ AddKey
Create a public key.
static constexpr CompanyID COMPANY_NEW_COMPANY
The client wants a new company.
@ Autoclean
The company is removed due to autoclean.
static const size_t TCP_MTU
Number of bytes we can pack in a single TCP packet.
static const uint NETWORK_CLIENT_NAME_LENGTH
The maximum length of a client's name, in bytes including '\0'.
static const uint NETWORK_CHAT_LENGTH
The maximum length of a chat message, in bytes including '\0'.
static const uint NETWORK_REVISION_LENGTH
The maximum length of the revision, in bytes including '\0'.
static const uint NETWORK_RCONCOMMAND_LENGTH
The maximum length of a rconsole command, in bytes including '\0'.
static const uint NETWORK_PASSWORD_LENGTH
The maximum length of the password, in bytes including '\0'.
void IConsolePrint(ExtendedTextColour colour_code, const std::string &string)
Handle the printing of text entered into the console or redirected there by any other means.
void IConsoleCmdExec(std::string_view command_string, const uint recurse_count)
Execute a given command passed to us.
Console functions used outside of the console code.
static const TextColour CC_INFO
Colour for information lines.
static const TextColour CC_WARNING
Colour for warning lines.
static const TextColour CC_DEFAULT
Default colour of the console.
NetworkRecvStatus
Status of a network client; reasons why a client has quit.
@ Okay
Everything is okay.
@ ClientQuit
The connection is lost gracefully. Other clients are already informed of this leaving client.
@ ServerFull
The server is full.
@ ServerBanned
The server has banned us.
@ ServerError
The server told us we made an error.
@ MalformedPacket
We apparently send a malformed packet.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
@ Desync
Desync message facility.
@ Net
Net message facility.
@ Warning
Warning, wrong but okay if you don't know.
@ Error
Error, but we are recovering.
@ Trace3
Trace information #3.
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
#define DECLARE_INCREMENT_DECREMENT_OPERATORS(enum_type)
For some enums it is useful to have pre/post increment/decrement operators.
EnumClassIndexContainer< std::array< T, to_underlying(N)>, Index > EnumIndexArray
A typedef for EnumClassIndexContainer using std::array as the backing container type.
@ Savegame
old or new savegame
@ Scenario
old or new scenario
@ Heightmap
heightmap file
Functions related to world/map generation.
static const uint32_t GENERATE_NEW_SEED
Create a new random seed.
SwitchMode _switch_mode
The next mainloop command.
static const uint MILLISECONDS_PER_TICK
The number of milliseconds per game tick.
uint32_t _last_sync_frame
Used in the server to store the last time a sync packet was sent to clients.
StringID GetNetworkErrorMsg(NetworkErrorCode err)
Retrieve a short translateable string of the error code.
ClientID _redirect_console_to_client
If not invalid, redirect the console output to a client.
uint32_t _frame_counter
The current frame.
StringList _network_ban_list
The banned clients.
bool _network_dedicated
are we a dedicated server?
bool _network_server
network-server is active
uint32_t _sync_seed_1
Seed to compare during sync checks.
uint NetworkCalculateLag(const NetworkClientSocket *cs)
Calculate the frame-lag of a client.
void NetworkTextMessage(NetworkAction action, ExtendedTextColour colour, bool self_send, std::string_view name, std::string_view str, StringParameter &&data)
Writes a text-message to the console and the chat box.
uint8_t _network_clients_connected
The amount of clients connected.
uint32_t _frame_counter_max
To where we may go with our clients.
void NetworkAdminClientUpdate(const NetworkClientInfo *ci)
Notify the admin network of a client update (if they did opt in for the respective update).
void NetworkAdminClientQuit(ClientID client_id)
Notify the admin network that a client quit (if they have opt in for the respective update).
void NetworkAdminUpdate(AdminUpdateFrequency freq)
Send (push) updates to the admin network as they have registered for these updates.
void NetworkAdminClientInfo(const NetworkClientSocket *cs, bool new_client)
Notify the admin network of a new client (if they did opt in for the respective update).
void NetworkAdminChat(NetworkAction action, NetworkChatDestinationType desttype, ClientID client_id, std::string_view msg, int64_t data, bool from_admin)
Send chat to the admin network (if they did opt in for the respective update).
void NetworkAdminClientError(ClientID client_id, NetworkErrorCode error_code)
Notify the admin network of a client error (if they have opt in for the respective update).
Server part of the admin network protocol.
Base core network types and some helper functions to access them.
bool NetworkIsValidClientName(std::string_view client_name)
Check whether the given client name is deemed valid for use in network games.
void NetworkSyncCommandQueue(NetworkClientSocket *cs)
Sync our local command queue to the command queue of the given socket.
NetworkAuthenticationMethod
The authentication method that can be used.
@ X25519_PAKE
Authentication using x25519 password-authenticated key agreement.
@ X25519_AuthorizedKey
Authentication using x22519 key exchange and authorized keys.
void NetworkUpdateClientInfo(ClientID client_id)
Send updated client info of a particular client.
void NetworkServerSendChat(NetworkAction action, NetworkChatDestinationType type, int dest, std::string_view msg, ClientID from_id, int64_t data=0, bool from_admin=false)
Send an actual chat message.
void NetworkServerDoMove(ClientID client_id, CompanyID company_id)
Handle the tid-bits of moving a client from one company to another.
TypedIndexContainer< std::array< NetworkCompanyStats, MAX_COMPANIES >, CompanyID > NetworkCompanyStatsArray
Container with statistics for all possible companies.
void SerializeNetworkGameInfo(Packet &p, const NetworkServerGameInfo &info, bool send_newgrf_names)
Serializes the NetworkGameInfo struct to the packet.
const NetworkServerGameInfo & GetCurrentNetworkServerGameInfo()
Get the NetworkServerGameInfo structure with the latest information of the server.
void SerializeGRFIdentifier(Packet &p, const GRFIdentifier &grf)
Serializes the GRFIdentifier (GRF ID and MD5 checksum) to the packet.
void FillStaticNetworkServerGameInfo()
Fill a NetworkServerGameInfo structure with the static content, or things that are so static they can...
NetworkServerGameInfo _network_game_info
Information about our game.
bool IsNetworkCompatibleVersion(std::string_view other)
Checks whether the given version string is compatible with our version.
Convert NetworkGameInfo to Packet and back.
class ServerNetworkGameSocketHandler NetworkClientSocket
Class for handling the server side of the game connection.
bool NetworkMakeClientNameUnique(std::string &new_name)
Check whether a name is unique, and otherwise try to make it unique.
static NetworkAuthenticationDefaultAuthorizedKeyHandler _authorized_key_handler
Provides the authorized key handling for the game authentication.
bool NetworkServerChangeClientName(ClientID client_id, const std::string &new_name)
Change the client name of the given client.
void NetworkPrintClients()
Print all the clients to the console.
void NetworkServerUpdateGameInfo()
Update the server's NetworkServerGameInfo due to changes in settings.
static const IntervalTimer< TimerGameEconomy > _network_monthly({TimerGameEconomy::Trigger::Month, TimerGameEconomy::Priority::None}, [](auto) { if(!_network_server) return;NetworkAutoCleanCompanies();NetworkAdminUpdate(AdminUpdateFrequency::Monthly);})
Economy monthly "callback".
NetworkCompanyStatsArray NetworkGetCompanyStats()
Get the company stats.
void NetworkUpdateClientInfo(ClientID client_id)
Send updated client info of a particular client.
void NetworkServerSendExternalChat(std::string_view source, ExtendedTextColour colour, std::string_view user, std::string_view msg)
Send a chat message from external source.
void NetworkServerSendChat(NetworkAction action, NetworkChatDestinationType desttype, int dest, std::string_view msg, ClientID from_id, int64_t data, bool from_admin)
Send an actual chat message.
NetworkClientSocketPool _networkclientsocket_pool
Make very sure the preconditions given in network_type.h are actually followed.
static IntervalTimer< TimerGameRealtime > _network_restart_map_timer({std::chrono::hours::zero(), TimerGameRealtime::Trigger::Unpaused}, [](auto) { if(!_network_server) return;if(_settings_client.network.restart_hours==0) return;Debug(Facility::Net, Severity::Notice, "Auto-restarting map: {} hours played", _settings_client.network.restart_hours);NetworkRestartMap();})
Timer to restart a network server automatically based on real-time hours played.
void NetworkServerSendConfigUpdate()
Send Config Update.
static const IntervalTimer< TimerGameEconomy > _network_quarterly({TimerGameEconomy::Trigger::Quarter, TimerGameEconomy::Priority::None}, [](auto) { if(!_network_server) return;NetworkAutoCleanCompanies();NetworkAdminUpdate(AdminUpdateFrequency::Quarterly);})
Quarterly "callback".
static NetworkErrorCode GetErrorForAuthenticationMethod(NetworkAuthenticationMethod method)
Determine the NetworkErrorCode for a failure of a given authentication method.
static const IntervalTimer< TimerGameCalendar > _calendar_network_yearly({ TimerGameCalendar::Trigger::Year, TimerGameCalendar::Priority::None }, [](auto) { if(!_network_server) return;NetworkCheckRestartMapYear();})
Calendar yearly "callback".
void NetworkServerSendRcon(ClientID client_id, ExtendedTextColour colour_code, std::string_view string)
Send an rcon reply to the client.
void NetworkServerDoMove(ClientID client_id, CompanyID company_id)
Handle the tid-bits of moving a client from one company to another.
static NetworkAuthenticationDefaultPasswordProvider _password_provider
Provides the password validation for the game's password.
static const IntervalTimer< TimerGameEconomy > _economy_network_yearly({TimerGameEconomy::Trigger::Year, TimerGameEconomy::Priority::None}, [](auto) { if(!_network_server) return;NetworkAdminUpdate(AdminUpdateFrequency::Annually);})
Economy yearly "callback".
void ChangeNetworkRestartTime(bool reset)
Reset the automatic network restart time interval.
bool NetworkCompanyHasClients(CompanyID company)
Check whether a particular company has clients.
static void NetworkRestartMap()
Helper function to restart the map.
void NetworkServerKickClient(ClientID client_id, std::string_view reason)
Kick a single client.
static void NetworkCheckRestartMapYear()
Check if we want to restart the map based on the year.
bool NetworkMakeClientNameUnique(std::string &name)
Check whether a name is unique, and otherwise try to make it unique.
static ClientID _network_client_id
The identifier counter for new clients (is never decreased).
std::string_view NetworkGetPublicKeyOfClient(ClientID client_id)
Get the public key of the client with the given id.
static void NetworkHandleCommandQueue(NetworkClientSocket *cs)
Handle the command-queue of a socket.
static const IntervalTimer< TimerGameEconomy > _economy_network_daily({TimerGameEconomy::Trigger::Day, TimerGameEconomy::Priority::None}, [](auto) { if(!_network_server) return;NetworkAdminUpdate(AdminUpdateFrequency::Daily);})
Daily "callback".
static const IntervalTimer< TimerGameEconomy > _network_weekly({TimerGameEconomy::Trigger::Week, TimerGameEconomy::Priority::None}, [](auto) { if(!_network_server) return;NetworkAdminUpdate(AdminUpdateFrequency::Weekly);})
Economy weekly "callback".
void NetworkServerShowStatusToConsole()
Show the status message of all clients on the console.
void NetworkServerNewCompany(const Company *c, NetworkClientInfo *ci)
Perform all the server specific administration of a new company.
uint NetworkServerKickOrBanIP(ClientID client_id, bool ban, std::string_view reason)
Ban, or kick, everyone joined from the given client's IP.
void NetworkServer_Tick(bool send_frame)
This is called every tick if this is a _network_server.
static void NetworkAutoCleanCompanies()
Remove companies that have not been used depending on the autoclean_companies setting and values for ...
static NetworkAuthenticationDefaultAuthorizedKeyHandler _rcon_authorized_key_handler
Provides the authorized key validation for rcon.
Server part of the network protocol.
ServerNetworkGameSocketHandler NetworkClientSocket
Make the code look slightly nicer/simpler.
NetworkClientSocketPool _networkclientsocket_pool
Make very sure the preconditions given in network_type.h are actually followed.
Pool< NetworkClientSocket, ClientPoolID, 8, PoolType::NetworkClient > NetworkClientSocketPool
Pool with all client sockets.
NetworkVehicleType
Vehicletypes in the order they are send in info packets.
@ Bus
A road vehicle that stops at bus stops.
@ Truck
A road vehicle that stops at truck stops.
@ Aircraft
An airplane or helicopter.
NetworkErrorCode
The error codes we send around in the protocols.
@ WrongRevision
The client is using the wrong revision.
@ Cheater
The client is trying control companies in a way they are not supposed to.
@ TimeoutPassword
The client has timed out providing a password.
@ TooManyCommands
The client has sent too many commands in a short time.
@ TimeoutComputer
The client has timed out because the computer could not keep up with the server.
@ TimeoutMap
The client has timed out because it took too long to download the map.
@ NotAuthorized
The client tried to do something there are not authorized to.
@ ServerFull
The server is full.
@ InvalidClientName
The client tried to set an invalid name.
@ TimeoutJoin
The client has timed out because getting up to speed with the server failed.
@ NotOnAllowList
The client is not on the allow list.
@ WrongPassword
The client entered a wrong password.
@ NotExpected
The request/packet was not expected in the current state.
@ Kicked
The client got kicked.
@ ConnectionLost
Connection to the client was lost.
@ IllegalPacket
A packet was received that has invalid content.
@ NameInUse
The client has a duplicate name (and we couldn't make it unique).
@ CompanyMismatch
The client was impersonating another company.
NetworkAction
Actions that can be used for NetworkTextMessage.
@ ChatExternal
An external application sent a message over the admin port.
@ ServerMessage
The server sent a message.
@ ClientKicked
A client got kicked.
@ ChatTeam
A chat sent to all clients of a team/company.
@ ClientNameChange
A client changed their name.
@ ClientJoin
A client joined the server.
@ CompanySpectator
A client joined the spectators.
@ ChatClient
A chat sent to a specific client.
@ ChatBroadcast
A chat broadcast to all clients.
@ ClientLeave
A client left the server.
@ CompanyNew
A client created an joined a new company.
@ CompanyJoin
A client joined an existing company.
static const uint MAX_CLIENTS
How many clients can we have.
NetworkChatDestinationType
Destination of our chat messages.
@ Client
Send message/notice to only a certain client (Private).
@ Team
Send message/notice to everyone playing the same company (Team).
@ Broadcast
Send message/notice to all clients (All).
ClientID
'Unique' identifier to be given to clients
@ Invalid
Client is not part of anything.
@ First
The first client ID.
@ Server
Servers always have this ID.
PoolID< uint16_t, struct ClientPoolIDTag, MAX_CLIENTS+1, 0xFFFF > ClientPoolID
Indices into the client related pools.
GRFConfigList _grfconfig
First item in list of current GRF set up.
@ Static
GRF file is used statically (can be used in any MP game).
@ LoadGame
Load game, Play Scenario.
@ StartHeightmap
Load a heightmap and start a new game from it.
@ NewGame
New Game --> 'Random game'.
Functions related to order backups.
Some methods of Pool are placed here in order to reduce compilation time and binary size.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
Pseudo random number generator.
Declaration of OTTD revision dependent variables.
A number of safeguards to prevent using unsafe methods.
void SlError(StringID string, const std::string &extra_msg)
Error handler.
SaveLoadResult SaveWithFilter(std::shared_ptr< SaveFilter > writer, bool threaded)
Save the game using a (writer) filter.
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Declaration of filters used for saving and loading savegames.
Functions related to saving and loading games.
@ Ok
completed successfully
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
ClientSettings _settings_client
The current settings for this game.
Base classes/functions for stations.
@ Dock
Station with a dock.
@ TruckStop
Station with truck stops.
@ Train
Station with train station.
@ Airport
Station with an airport.
@ BusStop
Station with bus stops.
Definition of base types and functions in a cross-platform compatible way.
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Functions related to OTTD's strings.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
Everything we need to know about a command to be able to execute it.
CommandDataBuffer data
command parameters.
uint32_t frame
the frame in which this packet is executed
CompanyID company
company that is executing the command
bool my_cmd
did the command originate from "me"
Commands cmd
command being executed.
Defines the traits of a command.
NetworkAuthorizedKeys allow_list
Public keys of clients that are allowed to join this company.
bool allow_any
Set if anyone is allowed to join this company.
uint8_t months_empty
NOSAVE: Number of months this company has not had a client in multiplayer.
static bool IsValidHumanID(auto index)
Is this company a valid company, not controlled by a NoAI program?
Container for the text colour and some text colour related flags for drawing.
constexpr uint16_t ToNetwork() const
Encode this text colour for sending over the network.
Statistics and caches on the vehicles in a group.
Container for all information known about a client.
static NetworkClientInfo * GetByClientID(ClientID client_id)
Return the CI given it's client-identifier.
TimerGameEconomy::Date join_date
Gamedate the client has joined.
CompanyID client_playas
As which company is this client playing (CompanyID).
ClientID client_id
Client identifier (same as ClientState->client_id).
std::string client_name
Name of the client.
std::string public_key
The public key of the client.
Simple calculated statistics of a company.
NetworkVehicleTypeArray num_station
How many stations are there of this type?
static void ResetUser(ClientID user)
Reset an user's OrderBackup if needed.
std::unique_ptr< Packet > current
The packet we're currently writing to.
PacketWriter(ServerNetworkGameSocketHandler *cs)
Create the packet writer.
size_t total_size
Total size of the compressed savegame.
std::condition_variable exit_sig
Signal for threaded destruction of this packet writer.
void Finish() override
Prepare everything to finish writing the savegame.
~PacketWriter() override
Make sure everything is cleaned up under lock.
void Write(const uint8_t *buf, size_t size) override
Write a given number of bytes into the savegame.
ServerNetworkGameSocketHandler * cs
Socket we are associated with.
std::mutex mutex
Mutex for making threaded saving safe.
void Destroy()
Begin the destruction of this packet writer.
bool TransferToNetworkQueue()
Transfer all packets from here to the network's queue while holding the lock on our mutex.
std::deque< std::unique_ptr< Packet > > packets
Packet queue of the savegame; send these "slowly" to the client. Cannot be a std::queue as we want to...
uint64_t Recv_uint64()
Read a 64 bits integer from the packet.
uint32_t Recv_uint32()
Read a 32 bits integer from the packet.
std::string Recv_string(size_t length, StringValidationSettings settings=StringValidationSetting::ReplaceWithQuestionMark)
Reads characters (bytes) from the packet until it finds a '\0', or reaches a maximum of length charac...
uint8_t Recv_uint8()
Read a 8 bits integer from the packet.
PoolItem(ClientPoolID index)
static Pool::IterateWrapper< NetworkClientSocket > Iterate(size_t from=0)
static T * Create(Targs &&... args)
static Company * Get(auto index)
static size_t GetNumItems()
static bool CanAllocateItem(size_t n=1)
static bool IsValidID(auto index)
static Company * GetIfValid(auto index)
static constexpr size_t MAX_SIZE
bool IsBus() const
Check whether a roadvehicle is a bus.
SaveFilter(std::shared_ptr< SaveFilter > chain)
Initialise this filter.
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
static RoadVehicle * From(Vehicle *v)
@ Closed
The connection got closed.
@ Annually
The admin gets information about this on a yearly basis.
@ Weekly
The admin gets information about this on a weekly basis.
@ Monthly
The admin gets information about this on a monthly basis.
@ Quarterly
The admin gets information about this on a quarterly basis.
@ Daily
The admin gets information about this on a daily basis.
PacketGameType
Enum with all types of TCP packets.
@ ServerAuthenticationRequest
The server requests the client to authenticate using a number of methods.
@ ServerClientInfo
Server sends you information about a client.
@ ServerShutdown
The server is shutting down.
@ ServerMapDone
Server tells it has just sent the last bits of the map to the client.
@ ServerMapBegin
Server tells the client that it is beginning to send the map.
@ ServerFrame
Server tells the client what frame it is in, and thus to where the client may progress.
@ ServerMapData
Server sends bits of the map to the client.
@ ServerClientJoined
Tells clients that a new client has joined.
@ ServerGameInfo
Information about the server.
@ ServerMapSize
Server tells the client what the (compressed) size of the map is.
@ ServerMove
Server tells everyone that someone is moved to another company.
@ ServerQuit
A server tells that a client has quit.
@ ServerError
Server sending an error message to the client.
@ ServerSync
Server tells the client what the random state should be.
@ ServerConfigurationUpdate
Some network configuration important to the client changed.
@ ServerRemoteConsoleCommand
Response of the executed command on the server.
@ ServerExternalChat
Server distributing the message from external source.
@ ServerErrorQuit
A server tells that a client has hit an error and did quit.
@ ServerWelcome
Server welcomes you and gives you your ClientID.
@ ServerCommand
Server distributes a command to (all) the clients.
@ ServerChat
Server distributing the message of a client (or itself).
@ ServerCheckNewGRFs
Server sends NewGRF IDs and MD5 checksums for the client to check.
@ ServerWaitForMap
Server tells the client there are some people waiting for the map as well.
@ ServerEnableEncryption
The server tells that authentication has completed and requests to enable encryption with the keys of...
@ ServerNewGame
The server is preparing to start a new game.
SocketList TCPListenHandler< Tsocket, EnumPacketType, Tfull_packet, Tban_packet >::sockets
Instantiate the sockets.
Definition of Interval and OneShot timers.
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
Definition of the real time game-timer.
@ Aircraft
Aircraft vehicle type.
@ Train
Train vehicle type.
std::mutex lock
synchronization for playback status fields
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-...