|
OpenTTD Source
14.0-beta1
|
Go to the documentation of this file.
10 #include "../stdafx.h"
12 #include "../saveload/saveload.h"
13 #include "../saveload/saveload_filter.h"
14 #include "../command_func.h"
15 #include "../console_func.h"
16 #include "../strings_func.h"
17 #include "../window_func.h"
18 #include "../company_func.h"
19 #include "../company_base.h"
20 #include "../company_gui.h"
21 #include "../company_cmd.h"
22 #include "../core/random_func.hpp"
23 #include "../timer/timer_game_tick.h"
24 #include "../timer/timer_game_calendar.h"
25 #include "../gfx_func.h"
32 #include "../core/backup_type.hpp"
33 #include "../thread.h"
34 #include "../social_integration.h"
36 #include "table/strings.h"
38 #include "../safeguards.h"
44 static const size_t CHUNK = 32 * 1024;
60 for (
auto p : this->blocks) {
74 memcpy(destination->
buf, source, amount);
75 destination->
buf += amount;
86 assert(this->read_bytes == 0);
93 this->blocks.push_back(this->buf = CallocT<byte>(
CHUNK));
94 this->bufe = this->buf +
CHUNK;
99 size_t Read(
byte *rbuf,
size_t size)
override
102 size_t ret_size = size = std::min(this->written_bytes - this->read_bytes, size);
103 this->read_bytes += ret_size;
104 const byte *rbufe = rbuf + ret_size;
106 while (rbuf != rbufe) {
107 if (this->buf == this->bufe) {
108 this->buf = *this->block++;
109 this->bufe = this->buf +
CHUNK;
112 size_t to_write = std::min(this->bufe - this->buf, rbufe - rbuf);
113 memcpy(rbuf, this->buf, to_write);
115 this->buf += to_write;
123 this->read_bytes = 0;
125 this->block = this->blocks.data();
126 this->buf = *this->block++;
127 this->bufe = this->buf +
CHUNK;
165 if (this->IsPendingDeletion())
return status;
167 assert(this->
sock != INVALID_SOCKET);
181 this->DeferDeletion();
192 if (this->IsPendingDeletion())
return;
212 default: errorno = NETWORK_ERROR_GENERAL;
break;
280 #ifdef NETWORK_SEND_DOUBLE_SEED
285 ShowNetworkError(STR_NETWORK_ERROR_DESYNC);
287 Debug(net, 0,
"Sync error detected");
341 Debug(net, 9,
"Client::SendJoin()");
343 Debug(net, 9,
"Client::status = JOIN");
345 Debug(net, 9,
"Client::join_status = AUTHORIZING");
362 Debug(net, 9,
"Client::SendNewGRFsOk()");
375 Debug(net, 9,
"Client::SendGamePassword()");
389 Debug(net, 9,
"Client::SendCompanyPassword()");
400 Debug(net, 9,
"Client::SendGetMap()");
402 Debug(net, 9,
"Client::status = MAP_WAIT");
413 Debug(net, 9,
"Client::SendMapOk()");
415 Debug(net, 9,
"Client::status = ACTIVE");
426 Debug(net, 9,
"Client::SendAck()");
442 Debug(net, 9,
"Client::SendCommand(): cmd={}", cp->
cmd);
445 my_client->NetworkGameSocketHandler::SendCommand(p, cp);
454 Debug(net, 9,
"Client::SendChat(): action={}, type={}, dest={}", action, type, dest);
471 Debug(net, 9,
"Client::SendError(): errorno={}", errorno);
486 Debug(net, 9,
"Client::SendSetPassword()");
501 Debug(net, 9,
"Client::SendSetName()");
515 Debug(net, 9,
"Client::SendSetName()");
530 Debug(net, 9,
"Client::SendRCon()");
546 Debug(net, 9,
"Client::SendMove(): company={}", company);
574 Debug(net, 9,
"Client::Receive_SERVER_FULL()");
584 Debug(net, 9,
"Client::Receive_SERVER_BANNED()");
601 Debug(net, 9,
"Client::Receive_SERVER_CLIENT_INFO(): client_id={}, playas={}",
client_id, playas);
655 static const StringID network_error_strings[] = {
656 STR_NETWORK_ERROR_LOSTCONNECTION,
657 STR_NETWORK_ERROR_LOSTCONNECTION,
658 STR_NETWORK_ERROR_LOSTCONNECTION,
659 STR_NETWORK_ERROR_LOSTCONNECTION,
660 STR_NETWORK_ERROR_LOSTCONNECTION,
661 STR_NETWORK_ERROR_LOSTCONNECTION,
662 STR_NETWORK_ERROR_SERVER_ERROR,
663 STR_NETWORK_ERROR_SERVER_ERROR,
664 STR_NETWORK_ERROR_WRONG_REVISION,
665 STR_NETWORK_ERROR_LOSTCONNECTION,
666 STR_NETWORK_ERROR_WRONG_PASSWORD,
667 STR_NETWORK_ERROR_SERVER_ERROR,
668 STR_NETWORK_ERROR_KICKED,
669 STR_NETWORK_ERROR_CHEATER,
670 STR_NETWORK_ERROR_SERVER_FULL,
671 STR_NETWORK_ERROR_TOO_MANY_COMMANDS,
672 STR_NETWORK_ERROR_TIMEOUT_PASSWORD,
673 STR_NETWORK_ERROR_TIMEOUT_COMPUTER,
674 STR_NETWORK_ERROR_TIMEOUT_MAP,
675 STR_NETWORK_ERROR_TIMEOUT_JOIN,
676 STR_NETWORK_ERROR_INVALID_CLIENT_NAME,
678 static_assert(
lengthof(network_error_strings) == NETWORK_ERROR_END);
682 Debug(net, 9,
"Client::Receive_SERVER_ERROR(): error={}", error);
684 StringID err = STR_NETWORK_ERROR_LOSTCONNECTION;
685 if (error < (ptrdiff_t)
lengthof(network_error_strings)) err = network_error_strings[error];
707 Debug(net, 9,
"Client::Receive_SERVER_CHECK_NEWGRFS(): grf_count={}", grf_count);
710 for (; grf_count > 0; grf_count--) {
712 DeserializeGRFIdentifier(p, &c);
736 Debug(net, 9,
"Client::status = AUTH_GAME");
739 Debug(net, 9,
"Client::Receive_SERVER_NEED_GAME_PASSWORD()");
753 Debug(net, 9,
"Client::status = AUTH_COMPANY");
756 Debug(net, 9,
"Client::Receive_SERVER_NEED_COMPANY_PASSWORD()");
774 Debug(net, 9,
"Client::status = AUTHORIZED");
794 Debug(net, 9,
"Client::Receive_SERVER_WAIT()");
797 Debug(net, 9,
"Client::join_status = WAITING");
808 Debug(net, 9,
"Client::status = MAP");
822 Debug(net, 9,
"Client::join_status = DOWNLOADING");
861 Debug(net, 9,
"Client::Receive_SERVER_MAP_DONE()");
863 Debug(net, 9,
"Client::join_status = PROCESSING");
883 this->
last_packet = std::chrono::steady_clock::now();
905 Debug(net, 9,
"Client::join_status = REGISTERING");
907 ShowJoinStatusWindow();
926 #ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
929 #ifdef NETWORK_SEND_DOUBLE_SEED
936 #ifdef NETWORK_SEND_DOUBLE_SEED
961 #ifdef NETWORK_SEND_DOUBLE_SEED
979 Debug(net, 9,
"Client::Receive_SERVER_COMMAND(): cmd={}, frame={}", cp.
cmd, cp.
frame);
981 if (err !=
nullptr) {
1004 Debug(net, 9,
"Client::Receive_SERVER_CHAT(): action={}, client_id={}, self_send={}", action,
client_id, self_send);
1012 case NETWORK_ACTION_CHAT_CLIENT:
1014 name = ci_to->client_name;
1019 case NETWORK_ACTION_CHAT_COMPANY: {
1032 name = ci_to->client_name;
1036 if (ci !=
nullptr) {
1051 Debug(net, 9,
"Client::Receive_SERVER_EXTERNAL_CHAT(): source={}", source);
1055 NetworkTextMessage(NETWORK_ACTION_EXTERNAL_CHAT, colour,
false, user, msg, 0, source);
1066 Debug(net, 9,
"Client::Receive_SERVER_ERROR_QUIT(): client_id={}",
client_id);
1069 if (ci !=
nullptr) {
1085 Debug(net, 9,
"Client::Receive_SERVER_QUIT(): client_id={}",
client_id);
1088 if (ci !=
nullptr) {
1089 NetworkTextMessage(NETWORK_ACTION_LEAVE,
CC_DEFAULT,
false, ci->
client_name,
"", STR_NETWORK_MESSAGE_CLIENT_LEAVING);
1092 Debug(net, 1,
"Unknown client ({}) is leaving the game",
client_id);
1107 Debug(net, 9,
"Client::Receive_SERVER_JOIN(): client_id={}",
client_id);
1110 if (ci !=
nullptr) {
1121 Debug(net, 9,
"Client::Receive_SERVER_SHUTDOWN()");
1136 Debug(net, 9,
"Client::Receive_SERVER_NEWGAME()");
1157 Debug(net, 9,
"Client::Receive_SERVER_RCON()");
1177 Debug(net, 9,
"Client::Receive_SERVER_MOVE(): client_id={}, comapny_id={}",
client_id, company_id);
1181 Debug(net, 1,
"Received invalid client index = 0");
1203 _network_server_max_companies = p->
Recv_uint8();
1220 Debug(net, 9,
"Client::Receive_SERVER_COMPANY_UPDATE()");
1234 std::chrono::steady_clock::duration lag = std::chrono::steady_clock::now() - this->
last_packet;
1235 if (lag < std::chrono::seconds(5))
return;
1239 if (lag > std::chrono::seconds(20)) {
1245 static std::chrono::steady_clock::duration last_lag = {};
1246 if (std::chrono::duration_cast<std::chrono::seconds>(last_lag) == std::chrono::duration_cast<std::chrono::seconds>(lag))
return;
1249 SetDParam(0, std::chrono::duration_cast<std::chrono::seconds>(lag).count());
1250 ShowErrorMessage(STR_NETWORK_ERROR_CLIENT_GUI_LOST_CONNECTION_CAPTION, STR_NETWORK_ERROR_CLIENT_GUI_LOST_CONNECTION,
WL_INFO);
1262 Debug(net, 9,
"Client::NetworkClient_Connected()");
1300 if (ci->client_playas != cid)
continue;
1301 NetworkTextMessage(NETWORK_ACTION_COMPANY_SPECTATOR,
CC_DEFAULT,
false, ci->client_name);
1317 if (client_name.empty())
return false;
1318 if (client_name[0] ==
' ')
return false;
1365 if (ci ==
nullptr)
return;
1373 std::string temporary_name = client_name;
1416 if (ci->client_playas == cio->
client_playas && ci != cio)
return true;
uint64_t Recv_uint64()
Read a 64 bits integer from the packet.
void NetworkClientSendRcon(const std::string &password, const std::string &command)
Send a remote console command.
NetworkRecvStatus Receive_SERVER_FRAME(Packet *p) override
Sends the current frame counter to the client: uint32_t Frame counter uint32_t Frame counter max (how...
void AddPacket(Packet *p)
Add a packet to this buffer.
static NetworkRecvStatus SendNewGRFsOk()
Tell the server we got all the NewGRFs.
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-...
NetworkRecvStatus Receive_SERVER_CHAT(Packet *p) override
Sends a chat-packet to the client: uint8_t ID of the action (see NetworkAction).
@ NETWORK_RECV_STATUS_CLIENT_QUIT
The connection is lost gracefully. Other clients are already informed of this leaving client.
void Send_uint64(uint64_t data)
Package a 64 bits integer in the packet.
std::string FormatArrayAsHex(std::span< const byte > data)
Format a byte array into a continuous hex string.
@ PACKET_CLIENT_ERROR
A client reports an error to the server.
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
bool NetworkValidateOurClientName()
Convenience method for NetworkValidateClientName on _settings_client.network.client_name.
NetworkRecvStatus ReceivePackets()
Do the actual receiving of packets.
void CSleep(int milliseconds)
Sleep on the current thread for a defined time.
bool NetworkValidateClientName(std::string &client_name)
Trim the given client name in place, i.e.
@ NETWORK_RECV_STATUS_DESYNC
A desync did occur.
void ShowErrorMessage(StringID summary_msg, int x, int y, CommandCost cc)
Display an error message in a window.
@ STATUS_AUTH_COMPANY
Last action was requesting company password.
std::string client_name
Name of the client.
std::string company_password
The password of the company to join.
Class to backup a specific variable and restore it later.
NetworkRecvStatus Receive_SERVER_BANNED(Packet *p) override
Notification that the client trying to join is banned.
uint32_t frame
the frame in which this packet is executed
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)
void ClientNetworkEmergencySave()
Create an emergency savegame when the network connection is lost.
void NetworkClientRequestMove(CompanyID company_id, const std::string &pass)
Notify the server of this client wanting to be moved to another company.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
bool _network_server
network-server is active
SaveLoadOperation
Operation performed on the file.
ClientNetworkGameSocketHandler(SOCKET s, const std::string &connection_string)
Create a new socket for the client side of the game connection.
CompanyMask _network_company_passworded
Bitmask of the password status of all companies.
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
NetworkAction
Actions that can be used for NetworkTextMessage.
bool NetworkClientPreferTeamChat(const NetworkClientInfo *cio)
Tell whether the client has team members who they can chat to.
std::chrono::steady_clock::time_point last_packet
Time we received the last frame.
@ WC_CLIENT_LIST
Client list; Window numbers:
NetworkRecvStatus Receive_SERVER_COMPANY_UPDATE(Packet *p) override
Update the clients knowledge of which company is password protected: uint16_t Bitwise representation ...
void CheckConnection()
Check the connection's state, i.e.
std::string server_password
The password of the server to join.
void SetInfo(NetworkClientInfo *info)
Sets the client info for this socket handler.
void NetworkUpdateClientInfo(ClientID client_id)
Send updated client info of a particular client.
static bool GameLoop()
Actual game loop for the client.
byte ** block
The block we're reading from/writing to.
static const uint NETWORK_CHAT_LENGTH
The maximum length of a chat message, in bytes including '\0'.
static NetworkRecvStatus SendChat(NetworkAction action, DestType type, int dest, const std::string &msg, int64_t data)
Send a chat-packet over the network.
@ PACKET_CLIENT_COMMAND
Client executed a command and sends it to the server.
void SetLocalCompany(CompanyID new_company)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
@ DFT_GAME_FILE
Save game or scenario file.
SOCKET sock
The socket currently connected to.
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
size_t written_bytes
The total number of bytes we've written.
Randomizer _random
Random used in the game state calculations.
static DateFract date_fract
Fractional part of the day.
ClientSettings _settings_client
The current settings for this game.
@ PACKET_CLIENT_QUIT
A client tells the server it is going to quit.
NetworkJoinStatus _network_join_status
The status of joining.
@ PACKET_CLIENT_GETMAP
Client requests the actual map.
NetworkRecvStatus Receive_SERVER_ERROR(Packet *p) override
The client made an error: uint8_t Error code caused (see NetworkErrorCode).
@ WC_COMPANY
Company view; Window numbers:
StringID GetNetworkErrorMsg(NetworkErrorCode err)
Retrieve the string id of an internal error number.
std::string _network_server_name
The current name of the server you are on.
static ClientNetworkGameSocketHandler * my_client
This is us!
NetworkRecvStatus Receive_SERVER_MAP_BEGIN(Packet *p) override
Sends that the server will begin with sending the map to the client: uint32_t Current frame.
Owner
Enum for all companies/owners.
NetworkRecvStatus CloseConnection(NetworkRecvStatus status) override
Close the network connection due to the given status.
Base socket handler for all TCP sockets.
virtual void Reset()
Reset this filter to read from the beginning of the file.
size_t Read(byte *rbuf, size_t size) override
Read a given number of bytes from the savegame.
NetworkRecvStatus Receive_SERVER_CLIENT_INFO(Packet *p) override
Send information about a client: uint32_t ID of the client (always unique on a server.
static const TextColour CC_DEFAULT
Default colour of the console.
Read some packets, and when do use that data as initial load filter.
bool _network_first_time
Whether we have finished joining or not.
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
@ PACKET_CLIENT_CHAT
Client said something that should be distributed.
NetworkRecvStatus Receive_SERVER_NEWGAME(Packet *p) override
Let the clients know that the server is loading a new map.
size_t read_bytes
The total number of read bytes.
@ PACKET_CLIENT_JOIN
The client telling the server it wants to join.
bool CanReadFromPacket(size_t bytes_to_read, bool close_connection=false)
Is it safe to read from the packet, i.e.
std::string Recv_string(size_t length, StringValidationSettings settings=SVS_REPLACE_WITH_QUESTION_MARK)
Reads characters (bytes) from the packet until it finds a '\0', or reaches a maximum of length charac...
NetworkRecvStatus Receive_SERVER_NEED_COMPANY_PASSWORD(Packet *p) override
Indication to the client that the server needs a company password: uint32_t Generation seed.
void Append(CommandPacket *p)
Append a CommandPacket at the end of the queue.
NetworkRecvStatus Receive_SERVER_NEED_GAME_PASSWORD(Packet *p) override
Indication to the client that the server needs a game password.
static NetworkRecvStatus SendJoin()
Make sure the server ID length is the same as a md5 hash.
uint32_t _sync_seed_1
Seed to compare during sync checks.
static uint32_t _password_game_seed
One bit of 'entropy' used to generate a salt for the company passwords.
static NetworkClientInfo * GetByClientID(ClientID client_id)
Return the CI given it's client-identifier.
CompanyID company
The company to join.
Basic data to distinguish a GRF.
ssize_t TransferOutWithLimit(F transfer_function, size_t limit, D destination, Args &&... args)
Transfer data from the packet to the given function.
static NetworkRecvStatus SendMove(CompanyID company, const std::string &password)
Ask the server to move us.
@ STATUS_MAP
The client is downloading the map.
static NetworkRecvStatus SendCompanyPassword(const std::string &password)
Set the company password as requested.
void ClearErrorMessages()
Clear all errors from the queue.
NetworkRecvStatus Receive_SERVER_MAP_DATA(Packet *p) override
Sends the data of the map to the client: Contains a part of the map (until max size of packet).
@ COMPANY_NEW_COMPANY
The client wants a new company.
void Send_uint32(uint32_t data)
Package a 32 bits integer in the packet.
@ SLO_LOAD
File is being loaded.
NetworkRecvStatus Receive_SERVER_FULL(Packet *p) override
Notification that the server is full.
static const size_t CHUNK
32 KiB chunks of memory.
static NetworkRecvStatus SendSetName(const std::string &name)
Tell the server that we like to change the name of the client.
void Send_uint8(uint8_t data)
Package a 8 bits integer in the packet.
static uint32_t BSWAP32(uint32_t x)
Perform a 32 bits endianness bitswap on x.
Everything we need to know about a command to be able to execute it.
NetworkRecvStatus Receive_SERVER_CHECK_NEWGRFS(Packet *p) override
Sends information about all used GRFs to the client: uint8_t Amount of GRFs (the following data is re...
Information about GRF, used in the game and (part of it) in savegames.
std::vector< byte * > blocks
Buffer with blocks of allocated memory.
@ NETWORK_RECV_STATUS_NEWGRF_MISMATCH
We did not have the required NewGRFs.
bool NetworkMaxCompaniesReached()
Check if max_companies has been reached on the server (local check only).
@ NETWORK_RECV_STATUS_SERVER_FULL
The server is full.
uint32_t Recv_uint32()
Read a 32 bits integer from the packet.
static bool IsConnected()
Check whether the client is actually connected (and in the game).
void free(const void *ptr)
Version of the standard free that accepts const pointers.
void StrTrimInPlace(std::string &str)
Trim the spaces from given string in place, i.e.
@ NETWORK_RECV_STATUS_SERVER_ERROR
The server told us we made an error.
MD5Hash md5sum
MD5 checksum of file to distinguish files with the same GRF ID (eg. newer version of GRF)
NetworkRecvStatus Receive_SERVER_WELCOME(Packet *p) override
The client is joined and ready to receive their map: uint32_t Own client ID.
NetworkRecvStatus Receive_SERVER_JOIN(Packet *p) override
A client joined (PACKET_CLIENT_MAP_OK), what usually directly follows is a PACKET_SERVER_CLIENT_INFO:...
static std::string _password_server_id
The other bit of 'entropy' used to generate a salt for the company passwords.
@ NETWORK_RECV_STATUS_SERVER_BANNED
The server has banned us.
static uint32_t last_ack_frame
Last frame we performed an ack.
void NetworkUpdateClientName(const std::string &client_name)
Send the server our name as callback from the setting.
void NetworkClient_Connected()
Is called after a client is connected to the server.
@ PACKET_CLIENT_NEWGRFS_CHECKED
Client acknowledges that it has all required NewGRFs.
void Reset() override
Reset this filter to read from the beginning of the file.
void NetworkClientsToSpectators(CompanyID cid)
Move the clients of a company to the spectators.
@ WL_INFO
Used for DoCommand-like (and some non-fatal AI GUI) errors/information.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
@ STATUS_JOIN
We are trying to join a server.
void MarkClosed()
Mark the connection as closed.
@ NETWORK_COMPANY_PASSWORD
The password of the company.
std::string client_name
name of the player (as client)
bool IsValidConsoleColour(TextColour c)
Check whether the given TextColour is valid for console usage.
@ NETWORK_RECV_STATUS_CLOSE_QUERY
Done querying the server.
virtual void SendPacket(Packet *packet)
This function puts the packet in the send-queue and it is send as soon as possible.
static NetworkRecvStatus SendRCon(const std::string &password, const std::string &command)
Send a console command.
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?
@ STATUS_MAP_WAIT
The client is waiting as someone else is downloading the map.
bool my_cmd
did the command originate from "me"
void DoAutoOrNetsave(FiosNumberedSaveName &counter)
Create an autosave or netsave.
@ PACKET_CLIENT_MAP_OK
Client tells the server that it received the whole map.
Internal entity of a packet.
NetworkRecvStatus Receive_SERVER_EXTERNAL_CHAT(Packet *p) override
Sends a chat-packet for external source to the client: string Name of the source this message came fr...
GameMode
Mode which defines the state of the game.
const char * ReceiveCommand(Packet *p, CommandPacket *cp)
Receives a command from the network.
byte * buf
Buffer we're going to write to/read from.
static void EventEnterMultiplayer(uint map_width, uint map_height)
Event: user entered a multiplayer game.
bool prefer_teamchat
choose the chat message target with <ENTER>, true=all clients, false=your team
ClientID _network_own_client_id
Our client identifier.
static debug_inline uint SizeX()
Get the size of the map along the X.
@ PACKET_CLIENT_SET_NAME
A client changes its name.
static bool Receive()
Check whether we received/can send some data from/to the server and when that's the case handle it ap...
@ CCA_NEW
Create a new company.
NetworkClientInfo * GetInfo() const
Gets the client info of this socket handler.
NetworkRecvStatus Receive_SERVER_CONFIG_UPDATE(Packet *p) override
Update the clients knowledge of the max settings: uint8_t Maximum number of companies allowed.
SwitchMode _switch_mode
The next mainloop command.
bool HasClientQuit() const
Whether the current client connected to the socket has quit.
uint32_t _frame_counter_server
The frame_counter of the server, if in network-mode.
SendPacketsState SendPackets(bool closing_down=false)
Sends all the buffered packets out for this client.
CompanyID _current_company
Company currently doing an action.
static const uint NETWORK_RCONCOMMAND_LENGTH
The maximum length of a rconsole command, in bytes including '\0'.
bool CanSendReceive()
Check whether this socket can send or receive something.
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
A savegame name automatically numbered.
DetailedFileType
Kinds of files in each AbstractFileType.
ClientID
'Unique' identifier to be given to clients
static size_t GetNumItems()
Returns number of valid items in the pool.
static NetworkRecvStatus SendCommand(const CommandPacket *cp)
Send a command to the server.
static ssize_t TransferOutMemCopy(PacketReader *destination, const char *source, size_t amount)
Simple wrapper around fwrite to be able to pass it to Packet's TransferOut.
void Restore()
Restore the variable.
bool Recv_bool()
Read a boolean from the packet.
NetworkRecvStatus Receive_SERVER_ERROR_QUIT(Packet *p) override
Inform all clients that one client made an error and thus has quit/been disconnected: uint32_t ID of ...
TextColour GetDrawStringCompanyColour(CompanyID company)
Get the colour for DrawString-subroutines which matches the colour of the company.
void NetworkClientSetCompanyPassword(const std::string &password)
Set/Reset company password on the client side.
uint32_t _frame_counter
The current frame.
@ CRR_NONE
Dummy reason for actions that don't need one.
DestType
Destination of our chat messages.
@ NO_DIRECTORY
A path without any base directory.
@ STATUS_AUTHORIZED
The client is authorized at the server.
void SetDParam(size_t n, uint64_t v)
Set a string parameter v at index n in the global string parameter array.
@ COMPANY_SPECTATOR
The client is spectating.
@ PACKET_CLIENT_GAME_PASSWORD
Clients sends the (hashed) game password.
uint8_t _network_join_waiting
The number of clients waiting in front of us.
Information required to join a server.
NetworkRecvStatus
Status of a network client; reasons why a client has quit.
static NetworkRecvStatus SendError(NetworkErrorCode errorno)
Send an error-packet over the network.
@ WC_NETWORK_STATUS_WINDOW
Network status window; Window numbers:
NetworkRecvStatus Receive_SERVER_SYNC(Packet *p) override
Sends a sync-check to the client: uint32_t Frame counter.
void ClientError(NetworkRecvStatus res)
Handle an error coming from the client side.
byte token
The token we need to send back to the server to prove we're the right client.
uint32_t _network_join_bytes_total
The total number of bytes to download.
std::string GetString(StringID string)
Resolve the given StringID into a std::string with all the associated DParam lookups and formatting.
uint8_t max_companies
maximum amount of companies
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
@ STATUS_AUTH_GAME
Last action was requesting game (server) password.
byte * bufe
End of the buffer we write to/read from.
Subdirectory
The different kinds of subdirectories OpenTTD uses.
void SetDParamStr(size_t n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
friend void NetworkExecuteLocalCommandQueue()
Execute all commands on the local command queue that ought to be executed this frame.
@ PACKET_CLIENT_RCON
Client asks the server to execute some command.
@ INVALID_CLIENT_ID
Client is not part of anything.
~ClientNetworkGameSocketHandler()
Clear whatever we assigned.
@ WL_ERROR
Errors (eg. saving/loading failed)
NetworkRecvStatus Receive_SERVER_COMMAND(Packet *p) override
Sends a DoCommand to the client: uint8_t ID of the company (0..MAX_COMPANIES-1).
uint NetworkMaxCompaniesAllowed()
Get the maximum number of companies that are allowed by the server.
@ SM_MENU
Switch to game intro menu.
Class for handling the client side of the game connection.
NetworkRecvStatus Receive_SERVER_SHUTDOWN(Packet *p) override
Let the clients know that the server is closing.
CommandQueue incoming_queue
The command-queue awaiting handling.
ClientID client_id
Client identifier.
void Send_string(const std::string_view data)
Sends a string over the network.
static const uint MILLISECONDS_PER_TICK
The number of milliseconds per game tick.
static NetworkRecvStatus SendGetMap()
Request the map from the server.
Interface for filtering a savegame till it is loaded.
#define lengthof(x)
Return the length of an fixed size array.
NetworkRecvStatus Receive_SERVER_RCON(Packet *p) override
Send the result of an issues RCon command back to the client: uint16_t Colour code.
NetworkSettings network
settings related to the network
uint32_t grfid
GRF ID (defined by Action 0x08)
uint32_t state[2]
The state of the randomizer.
static NetworkRecvStatus SendMapOk()
Tell the server we received the complete map.
uint32_t _sync_frame
The frame to perform the sync check.
NetworkRecvStatus CloseConnection(bool error=true) override
Functions to help ReceivePacket/SendPacket a bit A socket can make errors.
@ PACKET_CLIENT_ACK
The client tells the server which frame it has executed.
@ PACKET_CLIENT_MOVE
A client would like to be moved to another company.
@ INVALID_COMPANY
An invalid company.
std::string GenerateCompanyPasswordHash(const std::string &password, const std::string &password_server_id, uint32_t password_game_seed)
Hash the given password using server ID and game seed.
struct PacketReader * savegame
Packet reader for reading the savegame.
static NetworkRecvStatus SendAck()
Send an acknowledgement from the server's ticks.
@ NETWORK_RECV_STATUS_OKAY
Everything is okay.
void NetworkClientSendChat(NetworkAction action, DestType type, int dest, const std::string &msg, int64_t data)
Send a chat message.
bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf=nullptr)
Load the specified savegame but on error do different things.
NetworkRecvStatus Receive_SERVER_MAP_DONE(Packet *p) override
Sends that all data of the map are sent to the client:
PacketReader()
Initialise everything.
static NetworkRecvStatus SendQuit()
Tell the server we would like to quit.
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
@ STATUS_ACTIVE
The client is active within in the game.
ServerStatus status
Status of the connection with the server.
void StateGameLoop()
State controlling game loop.
@ FGCM_EXACT
Only find Grfs matching md5sum.
uint16_t Recv_uint16()
Read a 16 bits integer from the packet.
@ NETWORK_RECV_STATUS_SAVEGAME
Something went wrong (down)loading the savegame.
static NetworkRecvStatus SendGamePassword(const std::string &password)
Set the game password as requested.
static uint8_t _network_server_max_companies
Maximum number of companies of the currently joined server.
NetworkRecvStatus Receive_SERVER_MAP_SIZE(Packet *p) override
Sends the size of the map to the client.
@ WN_NETWORK_STATUS_WINDOW_JOIN
Network join status.
static const TextColour CC_WARNING
Colour for warning lines.
bool NetworkMakeClientNameUnique(std::string &new_name)
Check whether a name is unique, and otherwise try to make it unique.
NetworkRecvStatus Receive_SERVER_QUIT(Packet *p) override
Notification that a client left the game: uint32_t ID of the client.
size_t RemainingBytesToTransfer() const
Get the amount of bytes that are still available for the Transfer functions.
NetworkJoinInfo _network_join
Information about the game to join to.
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
const GRFConfig * FindGRFConfig(uint32_t grfid, FindGRFConfigMode mode, const MD5Hash *md5sum, uint32_t desired_version)
Find a NewGRF in the scanned list.
uint32_t _network_join_bytes
The number of bytes we already downloaded.
NetworkRecvStatus Receive_SERVER_MOVE(Packet *p) override
Move a client from one company into another: uint32_t ID of the client.
@ CLIENT_ID_SERVER
Servers always have this ID.
static NetworkRecvStatus SendSetPassword(const std::string &password)
Tell the server that we like to change the password of the company.
static void Send()
Send the packets of this socket handler.
NetworkErrorCode
The error codes we send around in the protocols.
Container for all information known about a client.
bool NetworkIsValidClientName(const std::string_view client_name)
Check whether the given client name is deemed valid for use in network games.
uint32_t _frame_counter_max
To where we may go with our clients.
@ PACKET_CLIENT_SET_PASSWORD
A client (re)sets its company's password.
uint8_t _network_reconnect
Reconnect timeout.
uint8_t Recv_uint8()
Read a 8 bits integer from the packet.
@ PACKET_CLIENT_COMPANY_PASSWORD
Client sends the (hashed) company password.
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
static uint SizeY()
Get the size of the map along the Y.
GUISettings gui
settings related to the GUI
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
@ NETWORK_GAME_PASSWORD
The password of the game.
NetworkRecvStatus Receive_SERVER_WAIT(Packet *p) override
Notification that another client is currently receiving the map: uint8_t Number of clients waiting in...
@ NETWORK_RECV_STATUS_MALFORMED_PACKET
We apparently send a malformed packet.
Commands cmd
command being executed.
static Date date
Current date in days (day counter).
void IConsolePrint(TextColour colour_code, const std::string &string)
Handle the printing of text entered into the console or redirected there by any other means.