14 #include "../stdafx.h" 15 #include "../strings_func.h" 16 #include "../date_func.h" 21 #include "../console_func.h" 22 #include "../company_base.h" 23 #include "../command_func.h" 24 #include "../saveload/saveload.h" 25 #include "../saveload/saveload_filter.h" 26 #include "../station_base.h" 27 #include "../genworld.h" 28 #include "../company_func.h" 29 #include "../company_gui.h" 30 #include "../roadveh.h" 31 #include "../order_backup.h" 32 #include "../core/pool_func.hpp" 33 #include "../core/random_func.hpp" 36 #include "../safeguards.h" 59 ServerNetworkGameSocketHandler *
cs;
69 PacketWriter(ServerNetworkGameSocketHandler *cs) : SaveFilter(NULL), cs(cs), current(NULL), total_size(0), packets(NULL)
79 if (this->cs != NULL && this->mutex != NULL) {
85 while (this->packets != NULL) {
93 if (this->mutex != NULL) this->mutex->
EndCritical();
115 if (this->mutex != NULL) this->mutex->
SendSignal();
117 if (this->mutex != NULL) this->mutex->
EndCritical();
135 return this->packets != NULL;
145 Packet *p = this->packets;
146 this->packets = p->
next;
149 if (this->mutex != NULL) this->mutex->
EndCritical();
157 if (this->current == NULL)
return;
159 Packet **p = &this->packets;
165 this->current = NULL;
171 if (this->cs == NULL)
SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
177 byte *bufe = buf + size;
178 while (buf != bufe) {
180 memcpy(this->current->
buffer + this->current->size, buf, to_write);
190 if (this->mutex != NULL) this->mutex->
EndCritical();
192 this->total_size += size;
198 if (this->cs == NULL)
SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
212 this->cs->NetworkTCPSocketHandler::SendPacket(p);
214 if (this->mutex != NULL) this->mutex->
EndCritical();
272 if (this->
sock == INVALID_SOCKET)
return status;
277 NetworkClientSocket *new_cs;
281 NetworkTextMessage(NETWORK_ACTION_LEAVE,
CC_DEFAULT,
false, client_name, NULL, STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST);
286 new_cs->SendErrorQuit(this->
client_id, NETWORK_ERROR_CONNECTION_LOST);
297 _network_clients_connected--;
329 NetworkClientSocket *cs;
373 NetworkClientSocket *csi;
374 memset(clients, 0,
sizeof(clients));
402 FOR_ALL_COMPANIES(company) {
440 GetString(str, strid,
lastof(str));
444 NetworkClientSocket *new_cs;
449 DEBUG(net, 1,
"'%s' made an error and has been disconnected. Reason: '%s'", client_name, str);
451 NetworkTextMessage(NETWORK_ACTION_LEAVE,
CC_DEFAULT,
false, client_name, NULL, strid);
457 if (error == NETWORK_ERROR_NOT_AUTHORIZED || error == NETWORK_ERROR_NOT_EXPECTED || error == NETWORK_ERROR_WRONG_REVISION) {
458 error = NETWORK_ERROR_ILLEGAL_PACKET;
460 new_cs->SendErrorQuit(this->
client_id, error);
466 DEBUG(net, 1,
"Client %d made an error and has been disconnected. Reason: '%s'", this->
client_id, str);
529 NetworkClientSocket *new_cs;
560 NetworkClientSocket *new_cs;
578 static uint sent_packets;
582 return this->
SendError(NETWORK_ERROR_NOT_AUTHORIZED);
607 bool has_packets =
false;
609 for (uint i = 0; (has_packets = this->
savegame->
HasPackets()) && i < sent_packets; i++) {
631 NetworkClientSocket *new_cs;
632 NetworkClientSocket *best = NULL;
635 if (best == NULL || best->GetInfo()->join_date > new_cs->GetInfo()->join_date || (best->GetInfo()->join_date == new_cs->GetInfo()->join_date && best->client_id > new_cs->client_id)) {
660 if (has_packets) sent_packets *= 2;
669 if (sent_packets > 1) sent_packets /= 2;
696 #ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME 698 #ifdef NETWORK_SEND_DOUBLE_SEED 705 this->
last_token = InteractiveRandomRange(UINT8_MAX - 1) + 1;
720 #ifdef NETWORK_SEND_DOUBLE_SEED 878 return this->
SendError(NETWORK_ERROR_NOT_EXPECTED);
899 return this->
SendError(NETWORK_ERROR_NOT_EXPECTED);
907 p->
Recv_string(client_revision,
sizeof(client_revision));
913 return this->
SendError(NETWORK_ERROR_WRONG_REVISION);
926 return this->
SendError(NETWORK_ERROR_FULL);
931 return this->
SendError(NETWORK_ERROR_FULL);
936 return this->
SendError(NETWORK_ERROR_COMPANY_MISMATCH);
946 return this->
SendError(NETWORK_ERROR_NAME_IN_USE);
974 return this->
SendError(NETWORK_ERROR_NOT_EXPECTED);
984 return this->
SendError(NETWORK_ERROR_WRONG_PASSWORD);
999 return this->
SendError(NETWORK_ERROR_NOT_EXPECTED);
1012 return this->
SendError(NETWORK_ERROR_WRONG_PASSWORD);
1020 NetworkClientSocket *new_cs;
1023 if (this->status < STATUS_AUTHORIZED || this->
HasClientQuit()) {
1024 return this->
SendError(NETWORK_ERROR_NOT_AUTHORIZED);
1045 NetworkClientSocket *new_cs;
1049 NetworkTextMessage(NETWORK_ACTION_JOIN,
CC_DEFAULT,
false, client_name, NULL, this->
client_id);
1065 new_cs->SendClientInfo(this->
GetInfo());
1080 return this->
SendError(NETWORK_ERROR_NOT_EXPECTED);
1091 if (this->status < STATUS_DONE_MAP || this->
HasClientQuit()) {
1092 return this->
SendError(NETWORK_ERROR_NOT_EXPECTED);
1096 return this->
SendError(NETWORK_ERROR_TOO_MANY_COMMANDS);
1108 return this->
SendError(NETWORK_ERROR_NOT_EXPECTED);
1114 return this->
SendError(NETWORK_ERROR_KICKED);
1119 return this->
SendError(NETWORK_ERROR_KICKED);
1128 IConsolePrintF(
CC_ERROR,
"WARNING: client %d (IP: %s) tried to execute a command as company %d, kicking...",
1130 return this->
SendError(NETWORK_ERROR_COMPANY_MISMATCH);
1135 return this->
SendError(NETWORK_ERROR_CHEATER);
1155 NetworkClientSocket *new_cs;
1161 if (this->status < STATUS_DONE_MAP || this->
HasClientQuit()) {
1168 GetString(str, strid,
lastof(str));
1170 DEBUG(net, 2,
"'%s' reported an error and is closing its connection (%s)", client_name, str);
1172 NetworkTextMessage(NETWORK_ACTION_LEAVE,
CC_DEFAULT,
false, client_name, NULL, strid);
1176 new_cs->SendErrorQuit(this->
client_id, errorno);
1189 NetworkClientSocket *new_cs;
1193 if (this->status < STATUS_DONE_MAP || this->
HasClientQuit()) {
1199 NetworkTextMessage(NETWORK_ACTION_LEAVE,
CC_DEFAULT,
false, client_name, NULL, STR_NETWORK_MESSAGE_CLIENT_LEAVING);
1216 return this->
SendError(NETWORK_ERROR_NOT_AUTHORIZED);
1270 NetworkClientSocket *cs;
1289 if (cs->client_id == (
ClientID)dest) {
1290 cs->SendChat(action, from_id,
false, msg, data);
1301 if (ci != NULL && ci_to != NULL) {
1306 if (cs->client_id == from_id) {
1307 cs->SendChat(action, (
ClientID)dest,
true, msg, data);
1316 bool show_local =
true;
1322 cs->SendChat(action, from_id,
false, msg, data);
1323 if (cs->client_id == from_id) show_local =
false;
1335 if (ci != NULL && ci_own != NULL && ci_own->
client_playas == dest) {
1342 if (ci_to == NULL)
break;
1345 if (ci != NULL && show_local) {
1350 GetString(name, str,
lastof(name));
1354 if (cs->client_id == from_id) {
1355 cs->SendChat(action, ci_to->
client_id,
true, msg, data);
1363 DEBUG(net, 0,
"[server] received unknown chat destination type %d. Doing broadcast instead", desttype);
1368 cs->SendChat(action, from_id,
false, msg, data);
1385 return this->
SendError(NETWORK_ERROR_NOT_AUTHORIZED);
1398 case NETWORK_ACTION_GIVE_MONEY:
1401 case NETWORK_ACTION_CHAT:
1402 case NETWORK_ACTION_CHAT_CLIENT:
1403 case NETWORK_ACTION_CHAT_COMPANY:
1408 return this->
SendError(NETWORK_ERROR_NOT_EXPECTED);
1417 return this->
SendError(NETWORK_ERROR_NOT_EXPECTED);
1434 return this->
SendError(NETWORK_ERROR_NOT_EXPECTED);
1469 DEBUG(net, 0,
"[rcon] wrong password from client-id %d", this->
client_id);
1473 DEBUG(net, 0,
"[rcon] client-id %d executed: '%s'", this->
client_id, command);
1498 DEBUG(net, 2,
"[move] wrong password from client-id #%d for company #%d", this->
client_id, company_id + 1);
1521 assert(max_len <=
lengthof(company_name));
1522 GetString(company_name, STR_COMPANY_NAME, company_name + max_len - 1);
1549 for (uint i = 0; i < NETWORK_VEH_END; i++) {
1553 for (uint i = 0; i < NETWORK_VEH_END; i++) {
1576 case VEH_TRAIN: type = NETWORK_VEH_TRAIN;
break;
1579 case VEH_SHIP: type = NETWORK_VEH_SHIP;
break;
1586 FOR_ALL_STATIONS(s) {
1605 NetworkClientSocket *cs;
1608 if (ci == NULL)
return;
1613 cs->SendClientInfo(ci);
1623 DEBUG(net, 0,
"Auto-restarting map. Year %d reached",
_cur_year);
1644 memset(clients_in_company, 0,
sizeof(clients_in_company));
1657 memset(vehicles_in_company, 0,
sizeof(vehicles_in_company));
1662 vehicles_in_company[v->
owner]++;
1667 FOR_ALL_COMPANIES(c) {
1669 if (c->
is_ai)
continue;
1671 if (!clients_in_company[c->
index]) {
1710 bool found_name =
false;
1716 while (!found_name) {
1730 if (strcmp(ci->
client_name, new_name) == 0) found_name =
false;
1738 seprintf(new_name, last,
"%s #%d", original_name, number);
1756 if (strcmp(ci->
client_name, new_name) == 0)
return false;
1760 if (ci == NULL)
return false;
1780 if (!already_hashed) {
1795 while ((cp = cs->outgoing_queue.Pop()) != NULL) {
1796 cs->SendCommand(cp);
1807 NetworkClientSocket *cs;
1808 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME 1809 bool send_sync =
false;
1812 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME 1828 uint lag = NetworkCalculateLag(cs);
1829 switch (cs->status) {
1830 case NetworkClientSocket::STATUS_ACTIVE:
1835 "Client #%d is dropped because the client's game state is more than %d ticks behind" :
1837 "Client #%d is dropped because the client did not respond for more than %d ticks",
1838 cs->client_id, lag);
1839 cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
1856 cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
1861 case NetworkClientSocket::STATUS_INACTIVE:
1862 case NetworkClientSocket::STATUS_NEWGRFS_CHECK:
1863 case NetworkClientSocket::STATUS_AUTHORIZED:
1868 cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
1873 case NetworkClientSocket::STATUS_MAP:
1877 cs->SendError(NETWORK_ERROR_TIMEOUT_MAP);
1882 case NetworkClientSocket::STATUS_DONE_MAP:
1883 case NetworkClientSocket::STATUS_PRE_ACTIVE:
1887 cs->SendError(NETWORK_ERROR_TIMEOUT_JOIN);
1892 case NetworkClientSocket::STATUS_AUTH_GAME:
1893 case NetworkClientSocket::STATUS_AUTH_COMPANY:
1897 cs->SendError(NETWORK_ERROR_TIMEOUT_PASSWORD);
1902 case NetworkClientSocket::STATUS_MAP_WAIT:
1907 case NetworkClientSocket::STATUS_END:
1912 if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) {
1917 if (send_frame) cs->SendFrame();
1919 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME 1921 if (send_sync) cs->SendSync();
1964 static const char *
const stat_str[] = {
1967 "authorizing (server password)",
1968 "authorizing (company password)",
1978 NetworkClientSocket *cs;
1981 if (ci == NULL)
continue;
1982 uint lag = NetworkCalculateLag(cs);
1985 status = (cs->status < (ptrdiff_t)
lengthof(stat_str) ? stat_str[cs->status] :
"unknown");
1998 NetworkClientSocket *cs;
2001 if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) cs->SendConfigUpdate();
2017 NetworkClientSocket *cs;
2019 if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) cs->SendCompanyUpdate();
2046 NetworkClientSocket *cs = NetworkClientSocket::GetByClientID(client_id);
2048 if (cs->status < NetworkClientSocket::STATUS_AUTHORIZED)
return;
2049 cs->SendMove(client_id, company_id);
2067 NetworkClientSocket::GetByClientID(client_id)->SendRConResult(colour_code,
string);
2077 NetworkClientSocket::GetByClientID(client_id)->SendError(NETWORK_ERROR_KICKED);
2099 bool contains =
false;
2101 if (strcmp(*iter, ip) == 0) {
2112 NetworkClientSocket *cs;
2115 if (cs->client_address.IsInNetmask(const_cast<char *>(ip))) {
Packet * packets
Packet queue of the savegame; send these "slowly" to the client.
static const uint NETWORK_CLIENT_NAME_LENGTH
The maximum length of a client's name, in bytes including '\0'.
NetworkRecvStatus SendMap()
This sends the map to the client.
static const uint NETWORK_CLIENTS_LENGTH
The maximum length for the list of clients that controls a company, in bytes including '\0'...
void NetworkServer_Tick(bool send_frame)
This is called every tick if this is a _network_server.
Send message/notice to all clients (All)
void Write(byte *buf, size_t size)
Write a given number of bytes into the savegame.
bool server_admin_chat
allow private chat for the server to be distributed to the admin network
void NetworkAdminCompanyUpdate(const Company *company)
Notify the admin network of company updates.
virtual NetworkRecvStatus Receive_CLIENT_ACK(Packet *p)
Tell the server we are done with this frame: uint32 Current frame counter of the client.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
used in multiplayer to create a new companies etc.
The client is catching up the delayed frames.
static bool AllowConnection()
Whether an connection is allowed or not at this moment.
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, const char *msg, ClientID from_id, int64 data, bool from_admin)
Send an actual chat message.
Information about a single company.
Server tells everyone that someone is moved to another company.
NetworkRecvStatus SendNeedCompanyPassword()
Request the company password.
static void NetworkAutoCleanCompanies()
Check if the server has autoclean_companies activated Two things happen: 1) If a company is not prote...
NetworkRecvStatus SendCompanyUpdate()
Send an update about the company password states.
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.
bool IsNetworkCompatibleVersion(const char *other)
Checks whether the given version string is compatible with our version.
bool HasClientQuit() const
Whether the current client connected to the socket has quit.
Container for all information known about a client.
The client has downloaded the map.
SOCKET sock
The socket currently connected to.
NetworkRecvStatus SendJoin(ClientID client_id)
Tell that a client joined.
uint32 _sync_seed_1
Seed to compare during sync checks.
uint32 _realtime_tick
The real time in the game.
Internal entity of a packet.
ServerNetworkGameSocketHandler * cs
Socket we are associated with.
The connection got closed.
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
GRFConfig * _grfconfig
First item in list of current GRF set up.
TextColour GetDrawStringCompanyColour(CompanyID company)
Get the colour for DrawString-subroutines which matches the colour of the company.
static char * strecat(char *dst, const char *src, const char *last)
Appends characters from one string to another.
virtual NetworkRecvStatus Receive_CLIENT_RCON(Packet *p)
Send an RCon command to the server: string RCon password.
uint32 Recv_uint32()
Read a 32 bits integer from the packet.
virtual NetworkRecvStatus Receive_CLIENT_GETMAP(Packet *p)
Request the map from the server.
NetworkRecvStatus SendError(NetworkErrorCode error)
Send an error to the client, and close its connection.
Client list; Window numbers:
void NetworkServerMonthlyLoop()
Monthly "callback".
uint16 max_init_time
maximum amount of time, in game ticks, a client may take to initiate joining
byte last_token
The last random token we did send to verify the client is listening.
set p2 with the ClientID of the sending client.
A server tells that a client has hit an error and did quit.
int32 performance_history
Company score (scale 0-1000)
ServerNetworkGameSocketHandler(SOCKET s)
Create a new socket for the server side of the game connection.
void StartNewGameWithoutGUI(uint seed)
Start a normal game without the GUI.
void NetworkServerSendRcon(ClientID client_id, TextColour colour_code, const char *string)
Send an rcon reply to the client.
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
int receive_limit
Amount of bytes that we can receive at this moment.
static void ResetUser(uint32 user)
Reset an user's OrderBackup if needed.
void Send_string(const char *data)
Sends a string over the network.
Year inaugurated_year
Year of starting the company.
The server is full and has no place for you.
static ClientID _network_client_id
The identifier counter for new clients (is never decreased)
NetworkRecvStatus CloseConnection(NetworkRecvStatus status)
Close the network connection due to the given status.
NetworkErrorCode
The error codes we send around in the protocols.
NetworkRecvStatus SendCommand(const CommandPacket *cp)
Send a command to the client to execute.
ClientID client_id
Client identifier (same as ClientState->client_id)
void NORETURN SlError(StringID string, const char *extra_msg)
Error handler.
void NetworkPopulateCompanyStats(NetworkCompanyStats *stats)
Populate the company stats.
The client is downloading the map.
Popup for the client list; Window numbers:
uint8 autoclean_novehicles
remove companies with no vehicles after this many months
ClientStatus status
Status of this client.
void Send_uint8(uint8 data)
Package a 8 bits integer in the packet.
NetworkRecvStatus SendClientInfo(NetworkClientInfo *ci)
Send the client information about a client.
NetworkRecvStatus SendWait()
Tell the client that its put in a waiting queue.
Template for TCP listeners.
The client is authorizing with company password.
static const uint MAX_CLIENTS
How many clients can we have.
Sending and receiving UDP messages.
virtual NetworkRecvStatus Receive_CLIENT_QUIT(Packet *p)
The client is quitting the game.
GRF file is used statically (can be used in any MP game)
The client is active within in the game.
NetworkRecvStatus SendChat(NetworkAction action, ClientID client_id, bool self_send, const char *msg, int64 data)
Send a chat message.
const T * Begin() const
Get the pointer to the first item (const)
ClientID _redirect_console_to_client
If not invalid, redirect the console output to a client.
static const uint GENERATE_NEW_SEED
Create a new random seed.
SaveOrLoadResult SaveWithFilter(SaveFilter *writer, bool threaded)
Save the game using a (writer) filter.
Tindex index
Index of this pool item.
virtual NetworkRecvStatus Receive_CLIENT_CHAT(Packet *p)
Sends a chat-packet to the server: uint8 ID of the action (see NetworkAction).
static const int DAY_TICKS
1 day is 74 ticks; _date_fract used to be uint16 and incremented by 885.
virtual NetworkRecvStatus Receive_CLIENT_COMPANY_PASSWORD(Packet *p)
Send a password to the server to authorize uint8 Password type (see NetworkPasswordType).
bool NetworkServerChangeClientName(ClientID client_id, const char *new_name)
Change the client name of the given client.
Send message/notice to only a certain client (Private)
void Send_uint32(uint32 data)
Package a 32 bits integer in the packet.
Server distributing the message of a client (or itself).
#define lastof(x)
Get the last element of an fixed size array.
The client is spectating.
The client wants a new company.
static const TextColour CC_DEFAULT
Default colour of the console.
bool NetworkCompanyIsPassworded(CompanyID company_id)
Check if the company we want to join requires a password.
void NetworkPrintClients()
Print all the clients to the console.
Base core network types and some helper functions to access them.
uint16 bytes_per_frame_burst
how many bytes may, over a short period, be received?
bool HasPackets()
Checks whether there are packets.
void Append(CommandPacket *p)
Append a CommandPacket at the end of the queue.
Server tells the client what frame it is in, and thus to where the client may progress.
NetworkRecvStatus SendRConResult(uint16 colour, const char *command)
Send the result of a console action.
GRFIdentifier ident
grfid and md5sum to uniquely identify newgrfs
The admin gets information about this on a daily basis.
CommandFlags GetCommandFlags(uint32 cmd)
The server told us we made an error.
virtual void EndCritical(bool allow_recursive=false)=0
End of the critical section.
Year _cur_year
Current year, starting at 0.
NetworkRecvStatus SendNewGRFCheck()
Send the check for the NewGRFs.
virtual Packet * ReceivePacket()
Receives a packet for the given client.
static RoadVehicle * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
virtual NetworkRecvStatus Receive_CLIENT_NEWGRFS_CHECKED(Packet *p)
Tell the server that we have the required GRFs.
const T * End() const
Get the pointer behind the last valid item (const)
SendPacketsState SendPackets(bool closing_down=false)
Sends all the buffered packets out for this client.
Server tells the client what the random state should be.
Class for handling the server side of the game connection.
struct GRFConfig * next
NOSAVE: Next item in the linked list.
virtual NetworkRecvStatus Receive_CLIENT_GAME_PASSWORD(Packet *p)
Send a password to the server to authorize: uint8 Password type (see NetworkPasswordType).
The client is not connected nor active.
static T SB(T &x, const uint8 s, const uint8 n, const U d)
Set n bits in x starting at bit s to d.
void NetworkUDPAdvertise()
Register us to the master server This function checks if it needs to send an advertise.
StringID GetNetworkErrorMsg(NetworkErrorCode err)
Retrieve the string id of an internal error number.
Server welcomes you and gives you your ClientID.
Servers always have this ID.
virtual void SendSignal()=0
Send a signal and wake the 'thread' that was waiting for it.
static bool IsValidHumanID(size_t index)
Is this company a valid company, not controlled by a NoAI program?
The admin gets information about this on a monthly basis.
T * Append(uint to_add=1)
Append an item and return it.
bool _network_dedicated
are we a dedicated server?
Server tells the client that it is beginning to send the map.
CommandQueue incoming_queue
The command-queue awaiting handling.
assert_compile(MAX_CLIENT_SLOTS > MAX_CLIENTS)
Make very sure the preconditions given in network_type.h are actually followed.
CompanyByte _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
uint16 months_empty
How many months the company is empty.
bool autoclean_companies
automatically remove companies that are not in use
void ProcessAsyncSaveFinish()
Handle async save finishes.
Response of the executed command on the server.
uint16 num_vehicle[NETWORK_VEH_END]
How many vehicles are there of this type?
static const size_t MAX_SIZE
Make template parameter accessible from outside.
virtual NetworkRecvStatus Receive_CLIENT_JOIN(Packet *p)
Try to join the server: string OpenTTD revision (norev000 if no revision).
A server tells that a client has quit.
void NetworkServerNewCompany(const Company *c, NetworkClientInfo *ci)
Perform all the server specific administration of a new company.
Server distributes a command to (all) the clients.
The company is removed due to autoclean.
void NetworkAdminClientQuit(ClientID client_id)
Notify the admin network that a client quit (if they have opt in for the respective update)...
char password[NETWORK_PASSWORD_LENGTH]
The password for the company.
size_t total_size
Total size of the compressed savegame.
Server sends NewGRF IDs and MD5 checksums for the client to check.
void NetworkAdminUpdate(AdminUpdateFrequency freq)
Send (push) updates to the admin network as they have registered for these updates.
void GetClientName(char *client_name, const char *last) const
Get the name of the client, if the user did not send it yet, Client #<no> is used.
NetworkSettings network
settings related to the network
CompanyID client_playas
As which company is this client playing (CompanyID)
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
virtual NetworkRecvStatus Receive_CLIENT_SET_NAME(Packet *p)
Gives the client a new name: string New name of the client.
void NetworkUpdateClientInfo(ClientID client_id)
Send updated client info of a particular client.
static const uint NETWORK_RCONCOMMAND_LENGTH
The maximum length of a rconsole command, in bytes including '\0'.
uint32 last_frame
Last frame we have executed.
void Send_uint64(uint64 data)
Package a 64 bits integer in the packet.
void NetworkSyncCommandQueue(NetworkClientSocket *cs)
Sync our local command queue to the command queue of the given socket.
Server sends you information about a client.
DateFract _date_fract
Fractional part of the day.
byte * buffer
The buffer of this packet, of basically variable length up to SEND_MTU.
NetworkAddress client_address
IP-address of the client (so he can be banned)
uint16 max_lag_time
maximum amount of time, in game ticks, a client may be lagging behind the server
Information about GRF, used in the game and (part of it) in savegames.
void SendCompanyInformation(Packet *p, const struct Company *c, const struct NetworkCompanyStats *stats, uint max_len=NETWORK_COMPANY_NAME_LENGTH)
Package some generic company information into a packet.
char client_name[NETWORK_CLIENT_NAME_LENGTH]
Name of the client.
Server part of the network protocol.
uint8 max_spectators
maximum amount of spectators
void Send_uint16(uint16 data)
Package a 16 bits integer in the packet.
Server sends bits of the map to the client.
void Finish()
Prepare everything to finish writing the savegame.
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)...
void IConsoleCmdExec(const char *cmdstr)
Execute a given command passed to us.
Station with truck stops.
ClientSettings _settings_client
The current settings for this game.
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 NetworkServerSetCompanyPassword(CompanyID company_id, const char *password, bool already_hashed)
Set/Reset a company password on the server end.
The client is waiting as someone else is downloading the map.
The admin gets information about this on a quarterly basis.
static void NetworkHandleCommandQueue(NetworkClientSocket *cs)
Handle the command-queue of a socket.
void CDECL usererror(const char *s,...)
Error handling for fatal user errors.
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...
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
static void NetworkCheckRestartMap()
Check if we want to restart the map.
NetworkRecvStatus SendNeedGamePassword()
Request the game password.
NetworkCompanyState * _network_company_states
Statistics about some companies.
The client is authorizing with game (server) password.
static const uint MILLISECONDS_PER_TICK
The number of milliseconds per game tick.
static ThreadMutex * New()
Create a new mutex.
uint8 flags
NOSAVE: GCF_Flags, bitset.
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
NetworkRecvStatus
Status of a network client; reasons why a client has quit.
Writing a savegame directly to a number of packets.
#define FOR_ALL_CLIENT_INFOS(var)
Iterate over all the clients.
const char * GetHostname()
Get the hostname; in case it wasn't given the IPv4 dotted representation is given.
All packets in the queue are sent.
byte clients_on
Current count of clients on server.
static const uint NETWORK_CHAT_LENGTH
The maximum length of a chat message, in bytes including '\0'.
bool is_ai
If true, the company is (also) controlled by the computer (a NoAI program).
Money money
Money owned by the company.
uint16 max_commands_in_queue
how many commands may there be in the incoming queue before dropping the connection?
void NetworkAdminChat(NetworkAction action, DestType desttype, ClientID client_id, const char *msg, int64 data, bool from_admin)
Send chat to the admin network (if they did opt in for the respective update).
PacketSize size
The size of the whole packet for received packets.
StationFacilityByte facilities
The facilities that this station has.
NetworkLanguage
Language ids for server_lang and client_lang.
bool DoCommandP(const CommandContainer *container, bool my_cmd)
Shortcut for the long DoCommandP when having a container with the data.
CompanyID company
company that is executing the command
#define lengthof(x)
Return the length of an fixed size array.
NetworkServerGameInfo _network_game_info
Information about our game.
The buffer is still full, so no (parts of) packets could be sent.
uint last_packet
Time we received the last frame.
static T min(const T a, const T b)
Returns the minimum of two values.
char rcon_password[NETWORK_PASSWORD_LENGTH]
password for rconsole (server side)
NetworkClientInfo * GetInfo() const
Gets the client info of this socket handler.
The client is checking NewGRFs.
#define FOR_ALL_CLIENT_SOCKETS(var)
Iterate over all the sockets.
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).
uint32 frame
the frame in which this packet is executed
the command can only be initiated by the server
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Server sending an error message to the client.
NetworkRecvStatus SendFrame()
Tell the client that they may run to a particular frame.
Maximum number of companies.
uint Count() const
Get the number of items in the queue.
virtual NetworkRecvStatus Receive_CLIENT_COMMAND(Packet *p)
The client has done a command and wants us to handle it.
NetworkRecvStatus SendNewGame()
Tell the client we're starting a new game.
Packet * next
The next packet.
Date join_date
Gamedate the client has joined.
Packet * PopPacket()
Pop a single created packet from the queue with packets.
Base class for all pools.
uint8 max_companies
maximum amount of companies
uint16 sync_freq
how often do we check whether we are still in-sync
NetworkRecvStatus SendQuit(ClientID client_id)
Tell the client another client quit.
The connection is 'just' lost.
the command may be initiated by a spectator
#define DEBUG(name, level,...)
Output a line of debugging information.
uint8 autoclean_unprotected
remove passwordless companies after this many months
ClientID client_id
Client identifier.
virtual NetworkRecvStatus Receive_CLIENT_ERROR(Packet *p)
The client made an error and is quitting the game.
Month _cur_month
Current month (0..11)
OwnerByte owner
The owner of this station.
NetworkRecvStatus SendSync()
Request the client to sync.
uint32 last_frame_server
Last frame the server has executed.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
Delete a window by its class and window number (if it is open).
NetworkRecvStatus SendWelcome()
Send the client a welcome message with some basic information.
uint16 max_password_time
maximum amount of time, in game ticks, a client may take to enter the password
byte _network_clients_connected
The amount of clients connected.
bool NetworkCompanyHasClients(CompanyID company)
Check whether a particular company has clients.
bool IsBus() const
Check whether a roadvehicle is a bus.
uint8 Recv_uint8()
Read a 8 bits integer from the packet.
Tells clients that a new client has joined.
uint32 generation_seed
noise seed for world generation
Some network configuration important to the client changed.
The admin gets information about this on a yearly basis.
NetworkRecvStatus SendCompanyInfo()
Send the client information about the companies.
void SetInfo(NetworkClientInfo *info)
Sets the client info for this socket handler.
uint32 _frame_counter
The current frame.
uint64 Recv_uint64()
Read a 64 bits integer from the packet.
void Destroy()
Begin the destruction of this packet writer.
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
static size_t GetNumItems()
Returns number of valid items in the pool.
NetworkRecvStatus SendConfigUpdate()
Send an update about the max company/spectator counts.
char network_id[NETWORK_SERVER_ID_LENGTH]
network ID for servers
const char * GetClientIP()
Get the IP address/hostname of the connected client.
The admin gets information about this on a weekly basis.
CompanyMask _network_company_passworded
Bitmask of the password status of all companies.
The server is preparing to start a new game.
void NetworkServerDailyLoop()
Daily "callback".
The client is authorized.
uint8 max_clients
maximum amount of clients
Client is not part of anything.
ClientID
'Unique' identifier to be given to clients
static const uint NETWORK_COMPANY_NAME_LENGTH
The maximum length of the company name, in bytes including '\0'.
PacketWriter(ServerNetworkGameSocketHandler *cs)
Create the packet writer.
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
OwnerByte owner
Which company owns the vehicle?
void NetworkServerUpdateCompanyPassworded(CompanyID company_id, bool passworded)
Tell that a particular company is (not) passworded.
Server tells it has just sent the last bits of the map to the client.
Server tells the client what the (compressed) size of the map is.
change the president name
uint16 num_station[NETWORK_VEH_END]
How many stations are there of this type?
CompanyEconomyEntry old_economy[MAX_HISTORY_QUARTERS]
Economic data of the company of the last MAX_HISTORY_QUARTERS quarters.
Server tells the client there are some people waiting for the map as well.
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
void NetworkServerYearlyLoop()
Yearly "callback".
void AppendQueue()
Append the current packet to the queue.
virtual NetworkRecvStatus Receive_CLIENT_COMPANY_INFO(Packet *p)
Request company information (in detail).
void NetworkAdminCompanyInfo(const Company *company, bool new_company)
Notify the admin network of company details.
void NetworkServerSendConfigUpdate()
Send Config Update.
StringList _network_ban_list
The banned clients.
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.
Station with train station.
const char * ReceiveCommand(Packet *p, CommandPacket *cp)
Receives a command from the network.
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function() ...
NetworkClientSocketPool _networkclientsocket_pool("NetworkClientSocket")
The pool with clients.
bool NetworkFindName(char *new_name, const char *last)
Check whether a name is unique, and otherwise try to make it unique.
The packets are partly sent; there are more packets to be sent in the queue.
NetworkRecvStatus SendShutdown()
Tell the client we're shutting down.
static const uint16 SEND_MTU
Number of bytes we can pack in a single packet.
void NetworkServerKickClient(ClientID client_id)
Kick a single client.
uint NetworkServerKickOrBanIP(ClientID client_id, bool ban)
Ban, or kick, everyone joined from the given client's IP.
bool _network_server
network-server is active
virtual void WaitForSignal()=0
Wait for a signal to be send.
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-NULL) Titem.
~PacketWriter()
Make sure everything is cleaned up.
static const TextColour CC_ERROR
Colour for error lines.
uint32 _last_sync_frame
Used in the server to store the last time a sync packet was sent to clients.
Everything we need to know about a command to be able to execute it.
static const uint MAX_CLIENT_SLOTS
The number of slots; must be at least 1 more than MAX_CLIENTS.
Server requests the (hashed) game password.
NetworkRecvStatus SendMove(ClientID client_id, CompanyID company_id)
Tell that a client moved to another company.
NetworkRecvStatus SendErrorQuit(ClientID client_id, NetworkErrorCode errorno)
Tell the client another client quit with an error.
uint32 last_token_frame
The last frame we received the right token.
Money yearly_expenses[3][EXPENSES_END]
Expenses of the company for the last three years, in every #Expenses category.
We apparently send a malformed packet.
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Server requests the (hashed) company password.
static const uint NETWORK_NAME_LENGTH
The maximum length of the server name and map name, in bytes including '\0'.
virtual void SendPacket(Packet *packet)
This function puts the packet in the send-queue and it is send as soon as possible.
Simple calculated statistics of a company.
uint16 max_download_time
maximum amount of time, in game ticks, a client may take to download the map
static const uint NETWORK_PASSWORD_LENGTH
The maximum length of the password, in bytes including '\0' (must be >= NETWORK_SERVER_ID_LENGTH) ...
void NetworkAdminClientUpdate(const NetworkClientInfo *ci)
Notify the admin network of a client update (if they did opt in for the respective update)...
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
#define FOR_ALL_VEHICLES(var)
Iterate over all vehicles.
uint16 bytes_per_frame
how many bytes may, over a long period, be received per frame?
GameCreationSettings game_creation
settings used during the creation of a game (map)
The server has banned you.
ThreadMutex * mutex
Mutex for making threaded saving safe.
uint8 autoclean_protected
remove the password from passworded companies after this many months
virtual void BeginCritical(bool allow_recursive=false)=0
Begin the critical section.
Base socket handler for all TCP sockets.
Owner
Enum for all companies/owners.
void Send_bool(bool data)
Package a boolean in the packet.
uint16 max_join_time
maximum amount of time, in game ticks, a client may take to sync up during joining ...
Money company_value
The value of the company.
static NetworkClientInfo * GetByClientID(ClientID client_id)
Return the CI given it's client-identifier.
static const byte NETWORK_COMPANY_INFO_VERSION
What version of company info is this?
Interface for filtering a savegame till it is written.
char server_password[NETWORK_PASSWORD_LENGTH]
password for joining this server
void SendCommand(Packet *p, const CommandPacket *cp)
Sends a command over the network.
#define DECLARE_POSTFIX_INCREMENT(type)
Some enums need to have allowed incrementing (i.e.
static const uint NETWORK_REVISION_LENGTH
The maximum length of the revision, in bytes including '\0'.
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
bool my_cmd
did the command originate from "me"
~ServerNetworkGameSocketHandler()
Clear everything related to this client.
void NetworkServerDoMove(ClientID client_id, CompanyID company_id)
Handle the tid-bits of moving a client from one company to another.
Date _date
Current date in days (day counter)
The server is shutting down.
Company view; Window numbers:
uint16 PacketSize
Size of the whole packet.
void NetworkServerShowStatusToConsole()
Show the status message of all clients on the console.
static const TextColour CC_WARNING
Colour for warning lines.
void SendGRFIdentifier(Packet *p, const GRFIdentifier *grf)
Serializes the GRFIdentifier (GRF ID and MD5 checksum) to the packet.
Send message/notice to everyone playing the same company (Team)
VehicleTypeByte type
Type of vehicle.
uint32 _frame_counter_max
To where we may go with our clients.
static void Send()
Send the packets for the server sockets.
uint32 cmd
command being executed.
DestType
Destination of our chat messages.
byte client_lang
The language of the client.
virtual NetworkRecvStatus Receive_CLIENT_MOVE(Packet *p)
Request the server to move this client into another company: uint8 ID of the company the client wants...
NetworkAction
Actions that can be used for NetworkTextMessage.
Information (password) of a company changed.
static const TextColour CC_INFO
Colour for information lines.
Year restart_game_year
year the server restarts
virtual Packet * ReceivePacket()
Receives a packet for the given client.
struct PacketWriter * savegame
Writer used to write the savegame.
void Recv_string(char *buffer, size_t size, StringValidationSettings settings=SVS_REPLACE_WITH_QUESTION_MARK)
Reads a string till it finds a '\0' in the stream.
Server part of the admin network protocol.
virtual NetworkRecvStatus Receive_CLIENT_MAP_OK(Packet *p)
Tell the server that we are done receiving/loading the map.
Packet * current
The packet we're currently writing to.
virtual NetworkRecvStatus Receive_CLIENT_SET_PASSWORD(Packet *p)
Set the password for the clients current company: string The password.
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.