1 /* $Id: network_server.cpp 26043 2013-11-21 18:35:31Z rubidium $ */
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
10 /** @file network_server.cpp Server part of the network protocol. */
14 #include "../stdafx.h"
15 #include "../strings_func.h"
16 #include "../date_func.h"
17 #include "network_admin.h"
18 #include "network_server.h"
19 #include "network_udp.h"
20 #include "network_base.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"
39 /* This file handles all the server-commands */
41 DECLARE_POSTFIX_INCREMENT(ClientID
)
42 /** The identifier counter for new clients (is never decreased) */
43 static ClientID _network_client_id
= CLIENT_ID_FIRST
;
45 /** Make very sure the preconditions given in network_type.h are actually followed */
46 assert_compile(MAX_CLIENT_SLOTS
> MAX_CLIENTS
);
48 assert_compile(NetworkClientSocketPool::MAX_SIZE
== MAX_CLIENT_SLOTS
);
50 /** The pool with clients. */
51 NetworkClientSocketPool
_networkclientsocket_pool("NetworkClientSocket");
52 INSTANTIATE_POOL_METHODS(NetworkClientSocket
)
54 /** Instantiate the listen sockets. */
55 template SocketList TCPListenHandler
<ServerNetworkGameSocketHandler
, PACKET_SERVER_FULL
, PACKET_SERVER_BANNED
>::sockets
;
57 /** Writing a savegame directly to a number of packets. */
58 struct PacketWriter
: SaveFilter
{
59 ServerNetworkGameSocketHandler
*cs
; ///< Socket we are associated with.
60 Packet
*current
; ///< The packet we're currently writing to.
61 size_t total_size
; ///< Total size of the compressed savegame.
62 Packet
*packets
; ///< Packet queue of the savegame; send these "slowly" to the client.
63 ThreadMutex
*mutex
; ///< Mutex for making threaded saving safe.
66 * Create the packet writer.
67 * @param cs The socket handler we're making the packets for.
69 PacketWriter(ServerNetworkGameSocketHandler
*cs
) : SaveFilter(nullptr), cs(cs
), current(nullptr), total_size(0), packets(nullptr)
71 this->mutex
= ThreadMutex::New();
74 /** Make sure everything is cleaned up. */
77 if (this->mutex
!= nullptr) this->mutex
->BeginCritical();
79 if (this->cs
!= nullptr && this->mutex
!= nullptr) {
80 this->mutex
->WaitForSignal();
83 /* This must all wait until the Destroy function is called. */
85 while (this->packets
!= nullptr) {
86 Packet
*p
= this->packets
->next
;
93 if (this->mutex
!= nullptr) this->mutex
->EndCritical();
96 this->mutex
= nullptr;
100 * Begin the destruction of this packet writer. It can happen in two ways:
101 * in the first case the client disconnected while saving the map. In this
102 * case the saving has not finished and killed this PacketWriter. In that
103 * case we simply set cs to nullptr, triggering the appending to fail due to
104 * the connection problem and eventually triggering the destructor. In the
105 * second case the destructor is already called, and it is waiting for our
106 * signal which we will send. Only then the packets will be removed by the
111 if (this->mutex
!= nullptr) this->mutex
->BeginCritical();
115 if (this->mutex
!= nullptr) this->mutex
->SendSignal();
117 if (this->mutex
!= nullptr) this->mutex
->EndCritical();
119 /* Make sure the saving is completely cancelled. Yes,
120 * we need to handle the save finish as well as the
121 * next connection might just be requesting a map. */
123 ProcessAsyncSaveFinish();
127 * Checks whether there are packets.
128 * It's not 100% threading safe, but this is only asked for when checking
129 * whether there still is something to send. Then another call will be made
130 * to actually get the Packet, which will be the only one popping packets
131 * and thus eventually setting this on false.
135 return this->packets
!= nullptr;
139 * Pop a single created packet from the queue with packets.
143 if (this->mutex
!= nullptr) this->mutex
->BeginCritical();
145 Packet
*p
= this->packets
;
146 this->packets
= p
->next
;
149 if (this->mutex
!= nullptr) this->mutex
->EndCritical();
154 /** Append the current packet to the queue. */
157 if (this->current
== nullptr) return;
159 Packet
**p
= &this->packets
;
160 while (*p
!= nullptr) {
165 this->current
= nullptr;
168 /* virtual */ void Write(byte
*buf
, size_t size
)
170 /* We want to abort the saving when the socket is closed. */
171 if (this->cs
== nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION
);
173 if (this->current
== nullptr) this->current
= new Packet(PACKET_SERVER_MAP_DATA
);
175 if (this->mutex
!= nullptr) this->mutex
->BeginCritical();
177 byte
*bufe
= buf
+ size
;
178 while (buf
!= bufe
) {
179 size_t to_write
= min(SEND_MTU
- this->current
->size
, bufe
- buf
);
180 memcpy(this->current
->buffer
+ this->current
->size
, buf
, to_write
);
181 this->current
->size
+= (PacketSize
)to_write
;
184 if (this->current
->size
== SEND_MTU
) {
186 if (buf
!= bufe
) this->current
= new Packet(PACKET_SERVER_MAP_DATA
);
190 if (this->mutex
!= nullptr) this->mutex
->EndCritical();
192 this->total_size
+= size
;
195 /* virtual */ void Finish()
197 /* We want to abort the saving when the socket is closed. */
198 if (this->cs
== nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION
);
200 if (this->mutex
!= nullptr) this->mutex
->BeginCritical();
202 /* Make sure the last packet is flushed. */
205 /* Add a packet stating that this is the end to the queue. */
206 this->current
= new Packet(PACKET_SERVER_MAP_DONE
);
209 /* Fast-track the size to the client. */
210 Packet
*p
= new Packet(PACKET_SERVER_MAP_SIZE
);
211 p
->Send_uint32((uint32
)this->total_size
);
212 this->cs
->NetworkTCPSocketHandler::SendPacket(p
);
214 if (this->mutex
!= nullptr) this->mutex
->EndCritical();
220 * Create a new socket for the server side of the game connection.
221 * @param s The socket to connect with.
223 ServerNetworkGameSocketHandler::ServerNetworkGameSocketHandler(SOCKET s
) : NetworkGameSocketHandler(s
)
225 this->status
= STATUS_INACTIVE
;
226 this->client_id
= _network_client_id
++;
227 this->receive_limit
= _settings_client
.network
.bytes_per_frame_burst
;
229 /* The Socket and Info pools need to be the same in size. After all,
230 * each Socket will be associated with at most one Info object. As
231 * such if the Socket was allocated the Info object can as well. */
232 assert_compile(NetworkClientSocketPool::MAX_SIZE
== NetworkClientInfoPool::MAX_SIZE
);
236 * Clear everything related to this client.
238 ServerNetworkGameSocketHandler::~ServerNetworkGameSocketHandler()
240 if (_redirect_console_to_client
== this->client_id
) _redirect_console_to_client
= INVALID_CLIENT_ID
;
241 OrderBackup::ResetUser(this->client_id
);
243 if (this->savegame
!= nullptr) {
244 this->savegame
->Destroy();
245 this->savegame
= nullptr;
249 Packet
*ServerNetworkGameSocketHandler::ReceivePacket()
251 /* Only allow receiving when we have some buffer free; this value
252 * can go negative, but eventually it will become positive again. */
253 if (this->receive_limit
<= 0) return nullptr;
255 /* We can receive a packet, so try that and if needed account for
256 * the amount of received data. */
257 Packet
*p
= this->NetworkTCPSocketHandler::ReceivePacket();
258 if (p
!= nullptr) this->receive_limit
-= p
->size
;
262 NetworkRecvStatus
ServerNetworkGameSocketHandler::CloseConnection(NetworkRecvStatus status
)
264 assert(status
!= NETWORK_RECV_STATUS_OKAY
);
266 * Sending a message just before leaving the game calls cs->SendPackets.
267 * This might invoke this function, which means that when we close the
268 * connection after cs->SendPackets we will close an already closed
269 * connection. This handles that case gracefully without having to make
270 * that code any more complex or more aware of the validity of the socket.
272 if (this->sock
== INVALID_SOCKET
) return status
;
274 if (status
!= NETWORK_RECV_STATUS_CONN_LOST
&& !this->HasClientQuit() && this->status
>= STATUS_AUTHORIZED
) {
275 /* We did not receive a leave message from this client... */
276 char client_name
[NETWORK_CLIENT_NAME_LENGTH
];
277 NetworkClientSocket
*new_cs
;
279 this->GetClientName(client_name
, lastof(client_name
));
281 NetworkTextMessage(NETWORK_ACTION_LEAVE
, CC_DEFAULT
, false, client_name
, nullptr, STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST
);
283 /* Inform other clients of this... strange leaving ;) */
284 FOR_ALL_CLIENT_SOCKETS(new_cs
) {
285 if (new_cs
->status
> STATUS_AUTHORIZED
&& this != new_cs
) {
286 new_cs
->SendErrorQuit(this->client_id
, NETWORK_ERROR_CONNECTION_LOST
);
291 NetworkAdminClientError(this->client_id
, NETWORK_ERROR_CONNECTION_LOST
);
292 DEBUG(net
, 1, "Closed client connection %d", this->client_id
);
294 /* We just lost one client :( */
295 if (this->status
>= STATUS_AUTHORIZED
) _network_game_info
.clients_on
--;
296 extern byte _network_clients_connected
;
297 _network_clients_connected
--;
299 DeleteWindowById(WC_CLIENT_LIST_POPUP
, this->client_id
);
300 SetWindowDirty(WC_CLIENT_LIST
, 0);
302 this->SendPackets(true);
304 delete this->GetInfo();
311 * Whether an connection is allowed or not at this moment.
312 * @return true if the connection is allowed.
314 /* static */ bool ServerNetworkGameSocketHandler::AllowConnection()
316 extern byte _network_clients_connected
;
317 bool accept
= _network_clients_connected
< MAX_CLIENTS
&& _network_game_info
.clients_on
< _settings_client
.network
.max_clients
;
319 /* We can't go over the MAX_CLIENTS limit here. However, the
320 * pool must have place for all clients and ourself. */
321 assert_compile(NetworkClientSocketPool::MAX_SIZE
== MAX_CLIENTS
+ 1);
322 assert(!accept
|| ServerNetworkGameSocketHandler::CanAllocateItem());
326 /** Send the packets for the server sockets. */
327 /* static */ void ServerNetworkGameSocketHandler::Send()
329 NetworkClientSocket
*cs
;
330 FOR_ALL_CLIENT_SOCKETS(cs
) {
332 if (cs
->SendPackets() != SPS_CLOSED
&& cs
->status
== STATUS_MAP
) {
333 /* This client is in the middle of a map-send, call the function for that */
340 static void NetworkHandleCommandQueue(NetworkClientSocket
*cs
);
344 * DEF_SERVER_SEND_COMMAND has parameter: NetworkClientSocket *cs
348 * Send the client information about a client.
349 * @param ci The client to send information about.
351 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendClientInfo(NetworkClientInfo
*ci
)
353 if (ci
->client_id
!= INVALID_CLIENT_ID
) {
354 Packet
*p
= new Packet(PACKET_SERVER_CLIENT_INFO
);
355 p
->Send_uint32(ci
->client_id
);
356 p
->Send_uint8 (ci
->client_playas
);
357 p
->Send_string(ci
->client_name
);
361 return NETWORK_RECV_STATUS_OKAY
;
364 /** Send the client information about the companies. */
365 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendCompanyInfo()
367 /* Fetch the latest version of the stats */
368 NetworkCompanyStats company_stats
[MAX_COMPANIES
];
369 NetworkPopulateCompanyStats(company_stats
);
371 /* Make a list of all clients per company */
372 char clients
[MAX_COMPANIES
][NETWORK_CLIENTS_LENGTH
];
373 NetworkClientSocket
*csi
;
374 memset(clients
, 0, sizeof(clients
));
376 /* Add the local player (if not dedicated) */
377 const NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER
);
378 if (ci
!= nullptr && Company::IsValidID(ci
->client_playas
)) {
379 strecpy(clients
[ci
->client_playas
], ci
->client_name
, lastof(clients
[ci
->client_playas
]));
382 FOR_ALL_CLIENT_SOCKETS(csi
) {
383 char client_name
[NETWORK_CLIENT_NAME_LENGTH
];
385 ((ServerNetworkGameSocketHandler
*)csi
)->GetClientName(client_name
, lastof(client_name
));
388 if (ci
!= nullptr && Company::IsValidID(ci
->client_playas
)) {
389 if (!StrEmpty(clients
[ci
->client_playas
])) {
390 strecat(clients
[ci
->client_playas
], ", ", lastof(clients
[ci
->client_playas
]));
393 strecat(clients
[ci
->client_playas
], client_name
, lastof(clients
[ci
->client_playas
]));
397 /* Now send the data */
402 FOR_ALL_COMPANIES(company
) {
403 p
= new Packet(PACKET_SERVER_COMPANY_INFO
);
405 p
->Send_uint8 (NETWORK_COMPANY_INFO_VERSION
);
407 this->SendCompanyInformation(p
, company
, &company_stats
[company
->index
]);
409 if (StrEmpty(clients
[company
->index
])) {
410 p
->Send_string("<none>");
412 p
->Send_string(clients
[company
->index
]);
418 p
= new Packet(PACKET_SERVER_COMPANY_INFO
);
420 p
->Send_uint8 (NETWORK_COMPANY_INFO_VERSION
);
421 p
->Send_bool (false);
424 return NETWORK_RECV_STATUS_OKAY
;
428 * Send an error to the client, and close its connection.
429 * @param error The error to disconnect for.
431 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendError(NetworkErrorCode error
)
434 Packet
*p
= new Packet(PACKET_SERVER_ERROR
);
436 p
->Send_uint8(error
);
439 StringID strid
= GetNetworkErrorMsg(error
);
440 GetString(str
, strid
, lastof(str
));
442 /* Only send when the current client was in game */
443 if (this->status
> STATUS_AUTHORIZED
) {
444 NetworkClientSocket
*new_cs
;
445 char client_name
[NETWORK_CLIENT_NAME_LENGTH
];
447 this->GetClientName(client_name
, lastof(client_name
));
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
, nullptr, strid
);
453 FOR_ALL_CLIENT_SOCKETS(new_cs
) {
454 if (new_cs
->status
> STATUS_AUTHORIZED
&& new_cs
!= this) {
455 /* Some errors we filter to a more general error. Clients don't have to know the real
456 * reason a joining failed. */
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
);
464 NetworkAdminClientError(this->client_id
, error
);
466 DEBUG(net
, 1, "Client %d made an error and has been disconnected. Reason: '%s'", this->client_id
, str
);
469 /* The client made a mistake, so drop his connection now! */
470 return this->CloseConnection(NETWORK_RECV_STATUS_SERVER_ERROR
);
473 /** Send the check for the NewGRFs. */
474 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendNewGRFCheck()
476 std::vector
<std::list
<GRFIdentifier
>> grf_identifier_lists
;
479 // Collect all the identifiers and split them up, so we can send them with multiple packets.
480 for (auto config
= _grfconfig
; config
!= nullptr; config
= config
->next
) {
481 if (HasBit(config
->flags
, GCF_STATIC
)) continue;
483 if ((grf_count
% NETWORK_MAX_GRF_COUNT
) == 0) {
484 grf_identifier_lists
.push_back(std::list
<GRFIdentifier
>());
487 grf_identifier_lists
.back().push_back(config
->ident
);
492 // Send all the packets.
493 for (size_t i
= 0; i
< grf_identifier_lists
.size(); ++i
) {
494 Packet
*p
= new Packet(PACKET_SERVER_CHECK_NEWGRFS
);
495 auto grf_ident_list
= grf_identifier_lists
[i
];
497 // The number of newGRF identifiers in the packet.
498 p
->Send_uint8((uint8
)grf_ident_list
.size());
499 // Whether this is the final packet.
500 bool is_last_packet
= (i
== (grf_identifier_lists
.size() - 1));
501 p
->Send_bool(is_last_packet
);
503 // The actual identifier list.
504 for (auto ident
: grf_ident_list
) {
505 this->SendGRFIdentifier(p
, &ident
);
511 return NETWORK_RECV_STATUS_OKAY
;
514 /** Request the game password. */
515 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendNeedGamePassword()
517 /* Invalid packet when status is STATUS_AUTH_GAME or higher */
518 if (this->status
>= STATUS_AUTH_GAME
) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET
);
520 this->status
= STATUS_AUTH_GAME
;
521 /* Reset 'lag' counters */
522 this->last_frame
= this->last_frame_server
= _frame_counter
;
524 Packet
*p
= new Packet(PACKET_SERVER_NEED_GAME_PASSWORD
);
526 return NETWORK_RECV_STATUS_OKAY
;
529 /** Request the company password. */
530 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendNeedCompanyPassword()
532 /* Invalid packet when status is STATUS_AUTH_COMPANY or higher */
533 if (this->status
>= STATUS_AUTH_COMPANY
) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET
);
535 this->status
= STATUS_AUTH_COMPANY
;
536 /* Reset 'lag' counters */
537 this->last_frame
= this->last_frame_server
= _frame_counter
;
539 Packet
*p
= new Packet(PACKET_SERVER_NEED_COMPANY_PASSWORD
);
540 p
->Send_uint32(_settings_game
.game_creation
.generation_seed
);
541 p
->Send_string(_settings_client
.network
.network_id
);
543 return NETWORK_RECV_STATUS_OKAY
;
546 /** Send the client a welcome message with some basic information. */
547 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendWelcome()
550 NetworkClientSocket
*new_cs
;
552 /* Invalid packet when status is AUTH or higher */
553 if (this->status
>= STATUS_AUTHORIZED
) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET
);
555 this->status
= STATUS_AUTHORIZED
;
556 /* Reset 'lag' counters */
557 this->last_frame
= this->last_frame_server
= _frame_counter
;
559 _network_game_info
.clients_on
++;
561 p
= new Packet(PACKET_SERVER_WELCOME
);
562 p
->Send_uint32(this->client_id
);
563 p
->Send_uint32(_settings_game
.game_creation
.generation_seed
);
564 p
->Send_string(_settings_client
.network
.network_id
);
567 /* Transmit info about all the active clients */
568 FOR_ALL_CLIENT_SOCKETS(new_cs
) {
569 if (new_cs
!= this && new_cs
->status
> STATUS_AUTHORIZED
) {
570 this->SendClientInfo(new_cs
->GetInfo());
573 /* Also send the info of the server */
574 return this->SendClientInfo(NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER
));
577 /** Tell the client that its put in a waiting queue. */
578 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendWait()
581 NetworkClientSocket
*new_cs
;
584 /* Count how many clients are waiting in the queue, in front of you! */
585 FOR_ALL_CLIENT_SOCKETS(new_cs
) {
586 if (new_cs
->status
!= STATUS_MAP_WAIT
) continue;
587 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
++;
590 p
= new Packet(PACKET_SERVER_WAIT
);
591 p
->Send_uint8(waiting
);
593 return NETWORK_RECV_STATUS_OKAY
;
596 /** This sends the map to the client */
597 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendMap()
599 static uint sent_packets
; // How many packets we did send successfully last time
601 if (this->status
< STATUS_AUTHORIZED
) {
602 /* Illegal call, return error and ignore the packet */
603 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED
);
606 if (this->status
== STATUS_AUTHORIZED
) {
607 this->savegame
= new PacketWriter(this);
609 /* Now send the _frame_counter and how many packets are coming */
610 Packet
*p
= new Packet(PACKET_SERVER_MAP_BEGIN
);
611 p
->Send_uint32(_frame_counter
);
614 NetworkSyncCommandQueue(this);
615 this->status
= STATUS_MAP
;
616 /* Mark the start of download */
617 this->last_frame
= _frame_counter
;
618 this->last_frame_server
= _frame_counter
;
620 sent_packets
= 4; // We start with trying 4 packets
622 /* Make a dump of the current game */
623 if (SaveWithFilter(this->savegame
, true) != SL_OK
) usererror("network savedump failed");
626 if (this->status
== STATUS_MAP
) {
627 bool last_packet
= false;
628 bool has_packets
= false;
630 for (uint i
= 0; (has_packets
= this->savegame
->HasPackets()) && i
< sent_packets
; i
++) {
631 Packet
*p
= this->savegame
->PopPacket();
632 last_packet
= p
->buffer
[2] == PACKET_SERVER_MAP_DONE
;
637 /* There is no more data, so break the for */
643 /* Done reading, make sure saving is done as well */
644 this->savegame
->Destroy();
645 this->savegame
= nullptr;
647 /* Set the status to DONE_MAP, no we will wait for the client
648 * to send it is ready (maybe that happens like never ;)) */
649 this->status
= STATUS_DONE_MAP
;
651 /* Find the best candidate for joining, i.e. the first joiner. */
652 NetworkClientSocket
*new_cs
;
653 NetworkClientSocket
*best
= nullptr;
654 FOR_ALL_CLIENT_SOCKETS(new_cs
) {
655 if (new_cs
->status
== STATUS_MAP_WAIT
) {
656 if (best
== nullptr || 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
)) {
662 /* Is there someone else to join? */
663 if (best
!= nullptr) {
664 /* Let the first start joining. */
665 best
->status
= STATUS_AUTHORIZED
;
668 /* And update the rest. */
669 FOR_ALL_CLIENT_SOCKETS(new_cs
) {
670 if (new_cs
->status
== STATUS_MAP_WAIT
) new_cs
->SendWait();
675 switch (this->SendPackets()) {
677 return NETWORK_RECV_STATUS_CONN_LOST
;
680 /* All are sent, increase the sent_packets */
681 if (has_packets
) sent_packets
*= 2;
684 case SPS_PARTLY_SENT
:
685 /* Only a part is sent; leave the transmission state. */
689 /* Not everything is sent, decrease the sent_packets */
690 if (sent_packets
> 1) sent_packets
/= 2;
694 return NETWORK_RECV_STATUS_OKAY
;
698 * Tell that a client joined.
699 * @param client_id The client that joined.
701 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendJoin(ClientID client_id
)
703 Packet
*p
= new Packet(PACKET_SERVER_JOIN
);
705 p
->Send_uint32(client_id
);
708 return NETWORK_RECV_STATUS_OKAY
;
711 /** Tell the client that they may run to a particular frame. */
712 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendFrame()
714 Packet
*p
= new Packet(PACKET_SERVER_FRAME
);
715 p
->Send_uint32(_frame_counter
);
716 p
->Send_uint32(_frame_counter_max
);
717 #ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
718 p
->Send_uint32(_sync_seed_1
);
719 #ifdef NETWORK_SEND_DOUBLE_SEED
720 p
->Send_uint32(_sync_seed_2
);
724 /* If token equals 0, we need to make a new token and send that. */
725 if (this->last_token
== 0) {
726 this->last_token
= InteractiveRandomRange(UINT8_MAX
- 1) + 1;
727 p
->Send_uint8(this->last_token
);
731 return NETWORK_RECV_STATUS_OKAY
;
734 /** Request the client to sync. */
735 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendSync()
737 Packet
*p
= new Packet(PACKET_SERVER_SYNC
);
738 p
->Send_uint32(_frame_counter
);
739 p
->Send_uint32(_sync_seed_1
);
741 #ifdef NETWORK_SEND_DOUBLE_SEED
742 p
->Send_uint32(_sync_seed_2
);
745 return NETWORK_RECV_STATUS_OKAY
;
749 * Send a command to the client to execute.
750 * @param cp The command to send.
752 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendCommand(const CommandPacket
*cp
)
754 Packet
*p
= new Packet(PACKET_SERVER_COMMAND
);
756 this->NetworkGameSocketHandler::SendCommand(p
, cp
);
757 p
->Send_uint32(cp
->frame
);
758 p
->Send_bool (cp
->my_cmd
);
761 return NETWORK_RECV_STATUS_OKAY
;
765 * Send a chat message.
766 * @param action The action associated with the message.
767 * @param client_id The origin of the chat message.
768 * @param self_send Whether we did send the message.
769 * @param msg The actual message.
770 * @param data Arbitrary extra data.
772 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendChat(NetworkAction action
, ClientID client_id
, bool self_send
, const char *msg
, NetworkTextMessageData data
)
774 if (this->status
< STATUS_PRE_ACTIVE
) return NETWORK_RECV_STATUS_OKAY
;
776 Packet
*p
= new Packet(PACKET_SERVER_CHAT
);
778 p
->Send_uint8 (action
);
779 p
->Send_uint32(client_id
);
780 p
->Send_bool (self_send
);
785 return NETWORK_RECV_STATUS_OKAY
;
789 * Tell the client another client quit with an error.
790 * @param client_id The client that quit.
791 * @param errorno The reason the client quit.
793 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendErrorQuit(ClientID client_id
, NetworkErrorCode errorno
)
795 Packet
*p
= new Packet(PACKET_SERVER_ERROR_QUIT
);
797 p
->Send_uint32(client_id
);
798 p
->Send_uint8 (errorno
);
801 return NETWORK_RECV_STATUS_OKAY
;
805 * Tell the client another client quit.
806 * @param client_id The client that quit.
808 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendQuit(ClientID client_id
)
810 Packet
*p
= new Packet(PACKET_SERVER_QUIT
);
812 p
->Send_uint32(client_id
);
815 return NETWORK_RECV_STATUS_OKAY
;
818 /** Tell the client we're shutting down. */
819 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendShutdown()
821 Packet
*p
= new Packet(PACKET_SERVER_SHUTDOWN
);
823 return NETWORK_RECV_STATUS_OKAY
;
826 /** Tell the client we're starting a new game. */
827 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendNewGame()
829 Packet
*p
= new Packet(PACKET_SERVER_NEWGAME
);
831 return NETWORK_RECV_STATUS_OKAY
;
835 * Send the result of a console action.
836 * @param colour The colour of the result.
837 * @param command The command that was executed.
839 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendRConResult(uint16 colour
, const char *command
)
841 Packet
*p
= new Packet(PACKET_SERVER_RCON
);
843 p
->Send_uint16(colour
);
844 p
->Send_string(command
);
846 return NETWORK_RECV_STATUS_OKAY
;
850 * Tell that a client moved to another company.
851 * @param client_id The client that moved.
852 * @param company_id The company the client moved to.
854 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendMove(ClientID client_id
, CompanyID company_id
)
856 Packet
*p
= new Packet(PACKET_SERVER_MOVE
);
858 p
->Send_uint32(client_id
);
859 p
->Send_uint8(company_id
);
861 return NETWORK_RECV_STATUS_OKAY
;
864 /** Send an update about the company password states. */
865 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendCompanyUpdate()
867 Packet
*p
= new Packet(PACKET_SERVER_COMPANY_UPDATE
);
869 p
->Send_uint16(_network_company_passworded
);
871 return NETWORK_RECV_STATUS_OKAY
;
874 /** Send an update about the max company/spectator counts. */
875 NetworkRecvStatus
ServerNetworkGameSocketHandler::SendConfigUpdate()
877 Packet
*p
= new Packet(PACKET_SERVER_CONFIG_UPDATE
);
879 p
->Send_uint8(_settings_client
.network
.max_companies
);
880 p
->Send_uint8(_settings_client
.network
.max_spectators
);
882 return NETWORK_RECV_STATUS_OKAY
;
886 * Receiving functions
887 * DEF_SERVER_RECEIVE_COMMAND has parameter: NetworkClientSocket *cs, Packet *p
890 NetworkRecvStatus
ServerNetworkGameSocketHandler::Receive_CLIENT_COMPANY_INFO(Packet
*p
)
892 return this->SendCompanyInfo();
895 NetworkRecvStatus
ServerNetworkGameSocketHandler::Receive_CLIENT_NEWGRFS_CHECKED(Packet
*p
)
897 if (this->status
!= STATUS_NEWGRFS_CHECK
) {
898 /* Illegal call, return error and ignore the packet */
899 return this->SendError(NETWORK_ERROR_NOT_EXPECTED
);
902 NetworkClientInfo
*ci
= this->GetInfo();
904 /* We now want a password from the client else we do not allow him in! */
905 if (!StrEmpty(_settings_client
.network
.server_password
)) {
906 return this->SendNeedGamePassword();
909 if (Company::IsValidID(ci
->client_playas
) && !StrEmpty(_network_company_states
[ci
->client_playas
].password
)) {
910 return this->SendNeedCompanyPassword();
913 return this->SendWelcome();
916 NetworkRecvStatus
ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet
*p
)
918 if (this->status
!= STATUS_INACTIVE
) {
919 /* Illegal call, return error and ignore the packet */
920 return this->SendError(NETWORK_ERROR_NOT_EXPECTED
);
923 char name
[NETWORK_CLIENT_NAME_LENGTH
];
925 NetworkLanguage client_lang
;
926 char client_revision
[NETWORK_REVISION_LENGTH
];
928 p
->Recv_string(client_revision
, sizeof(client_revision
));
929 uint32 newgrf_version
= p
->Recv_uint32();
931 /* Check if the client has revision control enabled */
932 if (!IsNetworkCompatibleVersion(client_revision
) || _openttd_newgrf_version
!= newgrf_version
) {
933 /* Different revisions!! */
934 return this->SendError(NETWORK_ERROR_WRONG_REVISION
);
937 p
->Recv_string(name
, sizeof(name
));
938 playas
= (Owner
)p
->Recv_uint8();
939 client_lang
= (NetworkLanguage
)p
->Recv_uint8();
941 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST
;
943 /* join another company does not affect these values */
945 case COMPANY_NEW_COMPANY
: // New company
946 if (Company::GetNumItems() >= _settings_client
.network
.max_companies
) {
947 return this->SendError(NETWORK_ERROR_FULL
);
950 case COMPANY_SPECTATOR
: // Spectator
951 if (NetworkSpectatorCount() >= _settings_client
.network
.max_spectators
) {
952 return this->SendError(NETWORK_ERROR_FULL
);
955 default: // Join another company (companies 1-8 (index 0-7))
956 if (!Company::IsValidHumanID(playas
)) {
957 return this->SendError(NETWORK_ERROR_COMPANY_MISMATCH
);
962 /* We need a valid name.. make it Player */
963 if (StrEmpty(name
)) strecpy(name
, "Player", lastof(name
));
965 if (!NetworkFindName(name
, lastof(name
))) { // Change name if duplicate
966 /* We could not create a name for this client */
967 return this->SendError(NETWORK_ERROR_NAME_IN_USE
);
970 assert(NetworkClientInfo::CanAllocateItem());
971 NetworkClientInfo
*ci
= new NetworkClientInfo(this->client_id
);
973 ci
->join_date
= _date
;
974 strecpy(ci
->client_name
, name
, lastof(ci
->client_name
));
975 ci
->client_playas
= playas
;
976 ci
->client_lang
= client_lang
;
977 DEBUG(desync
, 1, "client: %08x; %02x; %02x; %02x", _date
, _date_fract
, (int)ci
->client_playas
, (int)ci
->index
);
979 /* Make sure companies to which people try to join are not autocleaned */
980 if (Company::IsValidID(playas
)) _network_company_states
[playas
].months_empty
= 0;
982 this->status
= STATUS_NEWGRFS_CHECK
;
984 if (_grfconfig
== nullptr) {
985 /* Behave as if we received PACKET_CLIENT_NEWGRFS_CHECKED */
986 return this->Receive_CLIENT_NEWGRFS_CHECKED(nullptr);
989 return this->SendNewGRFCheck();
992 NetworkRecvStatus
ServerNetworkGameSocketHandler::Receive_CLIENT_GAME_PASSWORD(Packet
*p
)
994 if (this->status
!= STATUS_AUTH_GAME
) {
995 return this->SendError(NETWORK_ERROR_NOT_EXPECTED
);
998 char password
[NETWORK_PASSWORD_LENGTH
];
999 p
->Recv_string(password
, sizeof(password
));
1001 /* Check game password. Allow joining if we cleared the password meanwhile */
1002 if (!StrEmpty(_settings_client
.network
.server_password
) &&
1003 strcmp(password
, _settings_client
.network
.server_password
) != 0) {
1004 /* Password is invalid */
1005 return this->SendError(NETWORK_ERROR_WRONG_PASSWORD
);
1008 const NetworkClientInfo
*ci
= this->GetInfo();
1009 if (Company::IsValidID(ci
->client_playas
) && !StrEmpty(_network_company_states
[ci
->client_playas
].password
)) {
1010 return this->SendNeedCompanyPassword();
1013 /* Valid password, allow user */
1014 return this->SendWelcome();
1017 NetworkRecvStatus
ServerNetworkGameSocketHandler::Receive_CLIENT_COMPANY_PASSWORD(Packet
*p
)
1019 if (this->status
!= STATUS_AUTH_COMPANY
) {
1020 return this->SendError(NETWORK_ERROR_NOT_EXPECTED
);
1023 char password
[NETWORK_PASSWORD_LENGTH
];
1024 p
->Recv_string(password
, sizeof(password
));
1026 /* Check company password. Allow joining if we cleared the password meanwhile.
1027 * Also, check the company is still valid - client could be moved to spectators
1028 * in the middle of the authorization process */
1029 CompanyID playas
= this->GetInfo()->client_playas
;
1030 if (Company::IsValidID(playas
) && !StrEmpty(_network_company_states
[playas
].password
) &&
1031 strcmp(password
, _network_company_states
[playas
].password
) != 0) {
1032 /* Password is invalid */
1033 return this->SendError(NETWORK_ERROR_WRONG_PASSWORD
);
1036 return this->SendWelcome();
1039 NetworkRecvStatus
ServerNetworkGameSocketHandler::Receive_CLIENT_GETMAP(Packet
*p
)
1041 NetworkClientSocket
*new_cs
;
1042 /* The client was never joined.. so this is impossible, right?
1043 * Ignore the packet, give the client a warning, and close his connection */
1044 if (this->status
< STATUS_AUTHORIZED
|| this->HasClientQuit()) {
1045 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED
);
1048 /* Check if someone else is receiving the map */
1049 FOR_ALL_CLIENT_SOCKETS(new_cs
) {
1050 if (new_cs
->status
== STATUS_MAP
) {
1051 /* Tell the new client to wait */
1052 this->status
= STATUS_MAP_WAIT
;
1053 return this->SendWait();
1057 /* We receive a request to upload the map.. give it to the client! */
1058 return this->SendMap();
1061 NetworkRecvStatus
ServerNetworkGameSocketHandler::Receive_CLIENT_MAP_OK(Packet
*p
)
1063 /* Client has the map, now start syncing */
1064 if (this->status
== STATUS_DONE_MAP
&& !this->HasClientQuit()) {
1065 char client_name
[NETWORK_CLIENT_NAME_LENGTH
];
1066 NetworkClientSocket
*new_cs
;
1068 this->GetClientName(client_name
, lastof(client_name
));
1070 NetworkTextMessage(NETWORK_ACTION_JOIN
, CC_DEFAULT
, false, client_name
, nullptr, this->client_id
);
1072 /* Mark the client as pre-active, and wait for an ACK
1073 * so we know he is done loading and in sync with us */
1074 this->status
= STATUS_PRE_ACTIVE
;
1075 NetworkHandleCommandQueue(this);
1079 /* This is the frame the client receives
1080 * we need it later on to make sure the client is not too slow */
1081 this->last_frame
= _frame_counter
;
1082 this->last_frame_server
= _frame_counter
;
1084 FOR_ALL_CLIENT_SOCKETS(new_cs
) {
1085 if (new_cs
->status
> STATUS_AUTHORIZED
) {
1086 new_cs
->SendClientInfo(this->GetInfo());
1087 new_cs
->SendJoin(this->client_id
);
1091 NetworkAdminClientInfo(this, true);
1093 /* also update the new client with our max values */
1094 this->SendConfigUpdate();
1096 /* quickly update the syncing client with company details */
1097 return this->SendCompanyUpdate();
1100 /* Wrong status for this packet, give a warning to client, and close connection */
1101 return this->SendError(NETWORK_ERROR_NOT_EXPECTED
);
1105 * The client has done a command and wants us to handle it
1106 * @param p the packet in which the command was sent
1108 NetworkRecvStatus
ServerNetworkGameSocketHandler::Receive_CLIENT_COMMAND(Packet
*p
)
1110 /* The client was never joined.. so this is impossible, right?
1111 * Ignore the packet, give the client a warning, and close his connection */
1112 if (this->status
< STATUS_DONE_MAP
|| this->HasClientQuit()) {
1113 return this->SendError(NETWORK_ERROR_NOT_EXPECTED
);
1116 if (this->incoming_queue
.Count() >= _settings_client
.network
.max_commands_in_queue
) {
1117 return this->SendError(NETWORK_ERROR_TOO_MANY_COMMANDS
);
1121 const char *err
= this->ReceiveCommand(p
, &cp
);
1123 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST
;
1125 NetworkClientInfo
*ci
= this->GetInfo();
1127 if (err
!= nullptr) {
1128 IConsolePrintF(CC_ERROR
, "WARNING: %s from client %d (IP: %s).", err
, ci
->client_id
, this->GetClientIP());
1129 return this->SendError(NETWORK_ERROR_NOT_EXPECTED
);
1133 if ((GetCommandFlags(cp
.cmd
) & CMD_SERVER
) && ci
->client_id
!= CLIENT_ID_SERVER
) {
1134 IConsolePrintF(CC_ERROR
, "WARNING: server only command from: client %d (IP: %s), kicking...", ci
->client_id
, this->GetClientIP());
1135 return this->SendError(NETWORK_ERROR_KICKED
);
1138 if ((GetCommandFlags(cp
.cmd
) & CMD_SPECTATOR
) == 0 && !Company::IsValidID(cp
.company
) && ci
->client_id
!= CLIENT_ID_SERVER
) {
1139 IConsolePrintF(CC_ERROR
, "WARNING: spectator issueing command from client %d (IP: %s), kicking...", ci
->client_id
, this->GetClientIP());
1140 return this->SendError(NETWORK_ERROR_KICKED
);
1144 * Only CMD_COMPANY_CTRL is always allowed, for the rest, playas needs
1145 * to match the company in the packet. If it doesn't, the client has done
1146 * something pretty naughty (or a bug), and will be kicked
1148 if (!(cp
.cmd
== CMD_COMPANY_CTRL
&& cp
.p1
== 0 && ci
->client_playas
== COMPANY_NEW_COMPANY
) && ci
->client_playas
!= cp
.company
) {
1149 IConsolePrintF(CC_ERROR
, "WARNING: client %d (IP: %s) tried to execute a command as company %d, kicking...",
1150 ci
->client_playas
+ 1, this->GetClientIP(), cp
.company
+ 1);
1151 return this->SendError(NETWORK_ERROR_COMPANY_MISMATCH
);
1154 if (cp
.cmd
== CMD_COMPANY_CTRL
) {
1155 if (cp
.p1
!= 0 || cp
.company
!= COMPANY_SPECTATOR
) {
1156 return this->SendError(NETWORK_ERROR_CHEATER
);
1159 /* Check if we are full - else it's possible for spectators to send a CMD_COMPANY_CTRL and the company is created regardless of max_companies! */
1160 if (Company::GetNumItems() >= _settings_client
.network
.max_companies
) {
1161 NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE
, DESTTYPE_CLIENT
, ci
->client_id
, "cannot create new company, server full", CLIENT_ID_SERVER
);
1162 return NETWORK_RECV_STATUS_OKAY
;
1166 if (GetCommandFlags(cp
.cmd
) & CMD_CLIENT_ID
) cp
.p2
= this->client_id
;
1168 this->incoming_queue
.Append(&cp
);
1169 return NETWORK_RECV_STATUS_OKAY
;
1172 NetworkRecvStatus
ServerNetworkGameSocketHandler::Receive_CLIENT_ERROR(Packet
*p
)
1174 /* This packets means a client noticed an error and is reporting this
1175 * to us. Display the error and report it to the other clients */
1176 NetworkClientSocket
*new_cs
;
1178 char client_name
[NETWORK_CLIENT_NAME_LENGTH
];
1179 NetworkErrorCode errorno
= (NetworkErrorCode
)p
->Recv_uint8();
1181 /* The client was never joined.. thank the client for the packet, but ignore it */
1182 if (this->status
< STATUS_DONE_MAP
|| this->HasClientQuit()) {
1183 return this->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST
);
1186 this->GetClientName(client_name
, lastof(client_name
));
1188 StringID strid
= GetNetworkErrorMsg(errorno
);
1189 GetString(str
, strid
, lastof(str
));
1191 DEBUG(net
, 2, "'%s' reported an error and is closing its connection (%s)", client_name
, str
);
1193 NetworkTextMessage(NETWORK_ACTION_LEAVE
, CC_DEFAULT
, false, client_name
, nullptr, strid
);
1195 FOR_ALL_CLIENT_SOCKETS(new_cs
) {
1196 if (new_cs
->status
> STATUS_AUTHORIZED
) {
1197 new_cs
->SendErrorQuit(this->client_id
, errorno
);
1201 NetworkAdminClientError(this->client_id
, errorno
);
1203 if (errorno
== NETWORK_ERROR_DESYNC
) {
1204 // have the server and all clients run some sanity checks
1205 NetworkSendCommand(0, 0, 0, CMD_DESYNC_CHECK
, nullptr, nullptr, _local_company
, 0);
1208 return this->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST
);
1211 NetworkRecvStatus
ServerNetworkGameSocketHandler::Receive_CLIENT_QUIT(Packet
*p
)
1213 /* The client wants to leave. Display this and report it to the other
1215 NetworkClientSocket
*new_cs
;
1216 char client_name
[NETWORK_CLIENT_NAME_LENGTH
];
1218 /* The client was never joined.. thank the client for the packet, but ignore it */
1219 if (this->status
< STATUS_DONE_MAP
|| this->HasClientQuit()) {
1220 return this->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST
);
1223 this->GetClientName(client_name
, lastof(client_name
));
1225 NetworkTextMessage(NETWORK_ACTION_LEAVE
, CC_DEFAULT
, false, client_name
, nullptr, STR_NETWORK_MESSAGE_CLIENT_LEAVING
);
1227 FOR_ALL_CLIENT_SOCKETS(new_cs
) {
1228 if (new_cs
->status
> STATUS_AUTHORIZED
&& new_cs
!= this) {
1229 new_cs
->SendQuit(this->client_id
);
1233 NetworkAdminClientQuit(this->client_id
);
1235 return this->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST
);
1238 NetworkRecvStatus
ServerNetworkGameSocketHandler::Receive_CLIENT_ACK(Packet
*p
)
1240 if (this->status
< STATUS_AUTHORIZED
) {
1241 /* Illegal call, return error and ignore the packet */
1242 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED
);
1245 uint32 frame
= p
->Recv_uint32();
1247 /* The client is trying to catch up with the server */
1248 if (this->status
== STATUS_PRE_ACTIVE
) {
1249 /* The client is not yet catched up? */
1250 if (frame
+ DAY_TICKS
< _frame_counter
) return NETWORK_RECV_STATUS_OKAY
;
1252 /* Now he is! Unpause the game */
1253 this->status
= STATUS_ACTIVE
;
1254 this->last_token_frame
= _frame_counter
;
1256 /* Execute script for, e.g. MOTD */
1257 IConsoleCmdExec("exec scripts/on_server_connect.scr 0");
1260 /* Get, and validate the token. */
1261 uint8 token
= p
->Recv_uint8();
1262 if (token
== this->last_token
) {
1263 /* We differentiate between last_token_frame and last_frame so the lag
1264 * test uses the actual lag of the client instead of the lag for getting
1265 * the token back and forth; after all, the token is only sent every
1266 * time we receive a PACKET_CLIENT_ACK, after which we will send a new
1267 * token to the client. If the lag would be one day, then we would not
1268 * be sending the new token soon enough for the new daily scheduled
1269 * PACKET_CLIENT_ACK. This would then register the lag of the client as
1270 * two days, even when it's only a single day. */
1271 this->last_token_frame
= _frame_counter
;
1272 /* Request a new token. */
1273 this->last_token
= 0;
1276 /* The client received the frame, make note of it */
1277 this->last_frame
= frame
;
1278 /* With those 2 values we can calculate the lag realtime */
1279 this->last_frame_server
= _frame_counter
;
1280 return NETWORK_RECV_STATUS_OKAY
;
1285 * Send an actual chat message.
1286 * @param action The action that's performed.
1287 * @param desttype The type of destination.
1288 * @param dest The actual destination index.
1289 * @param msg The actual message.
1290 * @param from_id The origin of the message.
1291 * @param data Arbitrary data.
1292 * @param from_admin Whether the origin is an admin or not.
1294 void NetworkServerSendChat(NetworkAction action
, DestType desttype
, int dest
, const char *msg
, ClientID from_id
, NetworkTextMessageData data
, bool from_admin
)
1296 NetworkClientSocket
*cs
;
1297 const NetworkClientInfo
*ci
, *ci_own
, *ci_to
;
1300 case DESTTYPE_CLIENT
:
1301 /* Are we sending to the server? */
1302 if ((ClientID
)dest
== CLIENT_ID_SERVER
) {
1303 ci
= NetworkClientInfo::GetByClientID(from_id
);
1304 /* Display the text locally, and that is it */
1305 if (ci
!= nullptr) {
1306 NetworkTextMessage(action
, GetDrawStringCompanyColour(ci
->client_playas
), false, ci
->client_name
, msg
, data
);
1308 if (_settings_client
.network
.server_admin_chat
) {
1309 NetworkAdminChat(action
, desttype
, from_id
, msg
, data
, from_admin
);
1313 /* Else find the client to send the message to */
1314 FOR_ALL_CLIENT_SOCKETS(cs
) {
1315 if (cs
->client_id
== (ClientID
)dest
) {
1316 cs
->SendChat(action
, from_id
, false, msg
, data
);
1322 /* Display the message locally (so you know you have sent it) */
1323 if (from_id
!= (ClientID
)dest
) {
1324 if (from_id
== CLIENT_ID_SERVER
) {
1325 ci
= NetworkClientInfo::GetByClientID(from_id
);
1326 ci_to
= NetworkClientInfo::GetByClientID((ClientID
)dest
);
1327 if (ci
!= nullptr && ci_to
!= nullptr) {
1328 NetworkTextMessage(action
, GetDrawStringCompanyColour(ci
->client_playas
), true, ci_to
->client_name
, msg
, data
);
1331 FOR_ALL_CLIENT_SOCKETS(cs
) {
1332 if (cs
->client_id
== from_id
) {
1333 cs
->SendChat(action
, (ClientID
)dest
, true, msg
, data
);
1340 case DESTTYPE_TEAM
: {
1341 /* If this is false, the message is already displayed on the client who sent it. */
1342 bool show_local
= true;
1343 /* Find all clients that belong to this company */
1345 FOR_ALL_CLIENT_SOCKETS(cs
) {
1347 if (ci
!= nullptr && ci
->client_playas
== (CompanyID
)dest
) {
1348 cs
->SendChat(action
, from_id
, false, msg
, data
);
1349 if (cs
->client_id
== from_id
) show_local
= false;
1350 ci_to
= ci
; // Remember a client that is in the company for company-name
1354 /* if the server can read it, let the admin network read it, too. */
1355 if (_local_company
== (CompanyID
)dest
&& _settings_client
.network
.server_admin_chat
) {
1356 NetworkAdminChat(action
, desttype
, from_id
, msg
, data
, from_admin
);
1359 ci
= NetworkClientInfo::GetByClientID(from_id
);
1360 ci_own
= NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER
);
1361 if (ci
!= nullptr && ci_own
!= nullptr && ci_own
->client_playas
== dest
) {
1362 NetworkTextMessage(action
, GetDrawStringCompanyColour(ci
->client_playas
), false, ci
->client_name
, msg
, data
);
1363 if (from_id
== CLIENT_ID_SERVER
) show_local
= false;
1367 /* There is no such client */
1368 if (ci_to
== nullptr) break;
1370 /* Display the message locally (so you know you have sent it) */
1371 if (ci
!= nullptr && show_local
) {
1372 if (from_id
== CLIENT_ID_SERVER
) {
1373 char name
[NETWORK_NAME_LENGTH
];
1374 StringID str
= Company::IsValidID(ci_to
->client_playas
) ? STR_COMPANY_NAME
: STR_NETWORK_SPECTATORS
;
1375 SetDParam(0, ci_to
->client_playas
);
1376 GetString(name
, str
, lastof(name
));
1377 NetworkTextMessage(action
, GetDrawStringCompanyColour(ci_own
->client_playas
), true, name
, msg
, data
);
1379 FOR_ALL_CLIENT_SOCKETS(cs
) {
1380 if (cs
->client_id
== from_id
) {
1381 cs
->SendChat(action
, ci_to
->client_id
, true, msg
, data
);
1389 DEBUG(net
, 0, "[server] received unknown chat destination type %d. Doing broadcast instead", desttype
);
1392 case DESTTYPE_BROADCAST
:
1393 case DESTTYPE_BROADCAST_SS
:
1394 FOR_ALL_CLIENT_SOCKETS(cs
) {
1395 cs
->SendChat(action
, from_id
, (desttype
== DESTTYPE_BROADCAST_SS
&& from_id
== cs
->client_id
), msg
, data
);
1398 NetworkAdminChat(action
, desttype
, from_id
, msg
, data
, from_admin
);
1400 ci
= NetworkClientInfo::GetByClientID(from_id
);
1401 if (ci
!= nullptr) {
1402 NetworkTextMessage(action
, GetDrawStringCompanyColour(ci
->client_playas
),
1403 (desttype
== DESTTYPE_BROADCAST_SS
&& from_id
== CLIENT_ID_SERVER
), ci
->client_name
, msg
, data
);
1409 NetworkRecvStatus
ServerNetworkGameSocketHandler::Receive_CLIENT_CHAT(Packet
*p
)
1411 if (this->status
< STATUS_PRE_ACTIVE
) {
1412 /* Illegal call, return error and ignore the packet */
1413 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED
);
1416 NetworkAction action
= (NetworkAction
)p
->Recv_uint8();
1417 DestType desttype
= (DestType
)p
->Recv_uint8();
1418 int dest
= p
->Recv_uint32();
1419 char msg
[NETWORK_CHAT_LENGTH
];
1421 p
->Recv_string(msg
, NETWORK_CHAT_LENGTH
);
1422 NetworkTextMessageData data
;
1425 NetworkClientInfo
*ci
= this->GetInfo();
1427 case NETWORK_ACTION_GIVE_MONEY
:
1428 if (!Company::IsValidID(ci
->client_playas
)) break;
1430 case NETWORK_ACTION_CHAT
:
1431 case NETWORK_ACTION_CHAT_CLIENT
:
1432 case NETWORK_ACTION_CHAT_COMPANY
:
1433 NetworkServerSendChat(action
, desttype
, dest
, msg
, this->client_id
, data
);
1436 IConsolePrintF(CC_ERROR
, "WARNING: invalid chat action from client %d (IP: %s).", ci
->client_id
, this->GetClientIP());
1437 return this->SendError(NETWORK_ERROR_NOT_EXPECTED
);
1439 return NETWORK_RECV_STATUS_OKAY
;
1442 NetworkRecvStatus
ServerNetworkGameSocketHandler::Receive_CLIENT_SET_PASSWORD(Packet
*p
)
1444 if (this->status
!= STATUS_ACTIVE
) {
1445 /* Illegal call, return error and ignore the packet */
1446 return this->SendError(NETWORK_ERROR_NOT_EXPECTED
);
1449 char password
[NETWORK_PASSWORD_LENGTH
];
1450 const NetworkClientInfo
*ci
;
1452 p
->Recv_string(password
, sizeof(password
));
1453 ci
= this->GetInfo();
1455 NetworkServerSetCompanyPassword(ci
->client_playas
, password
);
1456 return NETWORK_RECV_STATUS_OKAY
;
1459 NetworkRecvStatus
ServerNetworkGameSocketHandler::Receive_CLIENT_SET_NAME(Packet
*p
)
1461 if (this->status
!= STATUS_ACTIVE
) {
1462 /* Illegal call, return error and ignore the packet */
1463 return this->SendError(NETWORK_ERROR_NOT_EXPECTED
);
1466 char client_name
[NETWORK_CLIENT_NAME_LENGTH
];
1467 NetworkClientInfo
*ci
;
1469 p
->Recv_string(client_name
, sizeof(client_name
));
1470 ci
= this->GetInfo();
1472 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST
;
1474 if (ci
!= nullptr) {
1475 /* Display change */
1476 if (NetworkFindName(client_name
, lastof(client_name
))) {
1477 NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE
, CC_DEFAULT
, false, ci
->client_name
, client_name
);
1478 strecpy(ci
->client_name
, client_name
, lastof(ci
->client_name
));
1479 NetworkUpdateClientInfo(ci
->client_id
);
1482 return NETWORK_RECV_STATUS_OKAY
;
1485 NetworkRecvStatus
ServerNetworkGameSocketHandler::Receive_CLIENT_RCON(Packet
*p
)
1487 if (this->status
!= STATUS_ACTIVE
) return this->SendError(NETWORK_ERROR_NOT_EXPECTED
);
1489 char pass
[NETWORK_PASSWORD_LENGTH
];
1490 char command
[NETWORK_RCONCOMMAND_LENGTH
];
1492 if (StrEmpty(_settings_client
.network
.rcon_password
)) return NETWORK_RECV_STATUS_OKAY
;
1494 p
->Recv_string(pass
, sizeof(pass
));
1495 p
->Recv_string(command
, sizeof(command
));
1497 if (strcmp(pass
, _settings_client
.network
.rcon_password
) != 0) {
1498 DEBUG(net
, 0, "[rcon] wrong password from client-id %d", this->client_id
);
1499 return NETWORK_RECV_STATUS_OKAY
;
1502 DEBUG(net
, 0, "[rcon] client-id %d executed: '%s'", this->client_id
, command
);
1504 _redirect_console_to_client
= this->client_id
;
1505 IConsoleCmdExec(command
);
1506 _redirect_console_to_client
= INVALID_CLIENT_ID
;
1507 return NETWORK_RECV_STATUS_OKAY
;
1510 NetworkRecvStatus
ServerNetworkGameSocketHandler::Receive_CLIENT_MOVE(Packet
*p
)
1512 if (this->status
!= STATUS_ACTIVE
) return this->SendError(NETWORK_ERROR_NOT_EXPECTED
);
1514 CompanyID company_id
= (Owner
)p
->Recv_uint8();
1516 /* Check if the company is valid, we don't allow moving to AI companies */
1517 if (company_id
!= COMPANY_SPECTATOR
&& !Company::IsValidHumanID(company_id
)) return NETWORK_RECV_STATUS_OKAY
;
1519 /* Check if we require a password for this company */
1520 if (company_id
!= COMPANY_SPECTATOR
&& !StrEmpty(_network_company_states
[company_id
].password
)) {
1521 /* we need a password from the client - should be in this packet */
1522 char password
[NETWORK_PASSWORD_LENGTH
];
1523 p
->Recv_string(password
, sizeof(password
));
1525 /* Incorrect password sent, return! */
1526 if (strcmp(password
, _network_company_states
[company_id
].password
) != 0) {
1527 DEBUG(net
, 2, "[move] wrong password from client-id #%d for company #%d", this->client_id
, company_id
+ 1);
1528 return NETWORK_RECV_STATUS_OKAY
;
1532 /* if we get here we can move the client */
1533 NetworkServerDoMove(this->client_id
, company_id
);
1534 return NETWORK_RECV_STATUS_OKAY
;
1538 * Package some generic company information into a packet.
1539 * @param p The packet that will contain the data.
1540 * @param c The company to put the of into the packet.
1541 * @param stats The statistics to put in the packet.
1542 * @param max_len The maximum length of the company name.
1544 void NetworkSocketHandler::SendCompanyInformation(Packet
*p
, const Company
*c
, const NetworkCompanyStats
*stats
, uint max_len
)
1546 /* Grab the company name */
1547 char company_name
[NETWORK_COMPANY_NAME_LENGTH
];
1548 SetDParam(0, c
->index
);
1550 assert(max_len
<= lengthof(company_name
));
1551 GetString(company_name
, STR_COMPANY_NAME
, company_name
+ max_len
- 1);
1553 /* Get the income */
1555 if (_cur_year
- 1 == c
->inaugurated_year
) {
1556 /* The company is here just 1 year, so display [2], else display[1] */
1557 for (uint i
= 0; i
< lengthof(c
->yearly_expenses
[2]); i
++) {
1558 income
-= c
->yearly_expenses
[2][i
];
1561 for (uint i
= 0; i
< lengthof(c
->yearly_expenses
[1]); i
++) {
1562 income
-= c
->yearly_expenses
[1][i
];
1566 /* Send the information */
1567 p
->Send_uint8 (c
->index
);
1568 p
->Send_string(company_name
);
1569 p
->Send_uint32(c
->inaugurated_year
);
1570 p
->Send_uint64(c
->old_economy
[0].company_value
);
1571 p
->Send_uint64(c
->money
);
1572 p
->Send_uint64(income
);
1573 p
->Send_uint16(c
->old_economy
[0].performance_history
);
1575 /* Send 1 if there is a password for the company else send 0 */
1576 p
->Send_bool (!StrEmpty(_network_company_states
[c
->index
].password
));
1578 for (uint i
= 0; i
< NETWORK_VEH_END
; i
++) {
1579 p
->Send_uint16(stats
->num_vehicle
[i
]);
1582 for (uint i
= 0; i
< NETWORK_VEH_END
; i
++) {
1583 p
->Send_uint16(stats
->num_station
[i
]);
1586 p
->Send_bool(c
->is_ai
);
1590 * Populate the company stats.
1591 * @param stats the stats to update
1593 void NetworkPopulateCompanyStats(NetworkCompanyStats
*stats
)
1598 memset(stats
, 0, sizeof(*stats
) * MAX_COMPANIES
);
1600 /* Go through all vehicles and count the type of vehicles */
1601 FOR_ALL_VEHICLES(v
) {
1602 if (!Company::IsValidID(v
->owner
) || !v
->IsPrimaryVehicle()) continue;
1605 case VEH_TRAIN
: type
= NETWORK_VEH_TRAIN
; break;
1606 case VEH_ROAD
: type
= RoadVehicle::From(v
)->IsBus() ? NETWORK_VEH_BUS
: NETWORK_VEH_LORRY
; break;
1607 case VEH_AIRCRAFT
: type
= NETWORK_VEH_PLANE
; break;
1608 case VEH_SHIP
: type
= NETWORK_VEH_SHIP
; break;
1611 stats
[v
->owner
].num_vehicle
[type
]++;
1614 /* Go through all stations and count the types of stations */
1615 FOR_ALL_STATIONS(s
) {
1616 if (Company::IsValidID(s
->owner
)) {
1617 NetworkCompanyStats
*npi
= &stats
[s
->owner
];
1619 if (s
->facilities
& FACIL_TRAIN
) npi
->num_station
[NETWORK_VEH_TRAIN
]++;
1620 if (s
->facilities
& FACIL_TRUCK_STOP
) npi
->num_station
[NETWORK_VEH_LORRY
]++;
1621 if (s
->facilities
& FACIL_BUS_STOP
) npi
->num_station
[NETWORK_VEH_BUS
]++;
1622 if (s
->facilities
& FACIL_AIRPORT
) npi
->num_station
[NETWORK_VEH_PLANE
]++;
1623 if (s
->facilities
& FACIL_DOCK
) npi
->num_station
[NETWORK_VEH_SHIP
]++;
1629 * Send updated client info of a particular client.
1630 * @param client_id The client to send it for.
1632 void NetworkUpdateClientInfo(ClientID client_id
)
1634 NetworkClientSocket
*cs
;
1635 NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID(client_id
);
1637 if (ci
== nullptr) return;
1639 DEBUG(desync
, 1, "client: %08x; %02x; %02x; %04x", _date
, _date_fract
, (int)ci
->client_playas
, client_id
);
1641 FOR_ALL_CLIENT_SOCKETS(cs
) {
1642 cs
->SendClientInfo(ci
);
1645 NetworkAdminClientUpdate(ci
);
1648 /** Check if we want to restart the map */
1649 static void NetworkCheckRestartMap()
1651 if (_settings_client
.network
.restart_game_year
!= 0 && _cur_year
>= _settings_client
.network
.restart_game_year
) {
1652 DEBUG(net
, 0, "Auto-restarting map. Year %d reached", _cur_year
);
1654 StartNewGameWithoutGUI(GENERATE_NEW_SEED
);
1658 /** Check if the server has autoclean_companies activated
1659 * Two things happen:
1660 * 1) If a company is not protected, it is closed after 1 year (for example)
1661 * 2) If a company is protected, protection is disabled after 3 years (for example)
1662 * (and item 1. happens a year later)
1664 static void NetworkAutoCleanCompanies()
1666 const NetworkClientInfo
*ci
;
1668 bool clients_in_company
[MAX_COMPANIES
];
1669 int vehicles_in_company
[MAX_COMPANIES
];
1671 if (!_settings_client
.network
.autoclean_companies
) return;
1673 memset(clients_in_company
, 0, sizeof(clients_in_company
));
1675 /* Detect the active companies */
1676 FOR_ALL_CLIENT_INFOS(ci
) {
1677 if (Company::IsValidID(ci
->client_playas
)) clients_in_company
[ci
->client_playas
] = true;
1680 if (!_network_dedicated
) {
1681 ci
= NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER
);
1682 if (Company::IsValidID(ci
->client_playas
)) clients_in_company
[ci
->client_playas
] = true;
1685 if (_settings_client
.network
.autoclean_novehicles
!= 0) {
1686 memset(vehicles_in_company
, 0, sizeof(vehicles_in_company
));
1689 FOR_ALL_VEHICLES(v
) {
1690 if (!Company::IsValidID(v
->owner
) || !v
->IsPrimaryVehicle()) continue;
1691 vehicles_in_company
[v
->owner
]++;
1695 /* Go through all the companies */
1696 FOR_ALL_COMPANIES(c
) {
1697 /* Skip the non-active once */
1698 if (c
->is_ai
) continue;
1700 if (!clients_in_company
[c
->index
]) {
1701 /* The company is empty for one month more */
1702 _network_company_states
[c
->index
].months_empty
++;
1704 /* Is the company empty for autoclean_unprotected-months, and is there no protection? */
1705 if (_settings_client
.network
.autoclean_unprotected
!= 0 && _network_company_states
[c
->index
].months_empty
> _settings_client
.network
.autoclean_unprotected
&& StrEmpty(_network_company_states
[c
->index
].password
)) {
1706 /* Shut the company down */
1707 DoCommandP(0, 2 | c
->index
<< 16, CRR_AUTOCLEAN
, CMD_COMPANY_CTRL
);
1708 IConsolePrintF(CC_DEFAULT
, "Auto-cleaned company #%d with no password", c
->index
+ 1);
1710 /* Is the company empty for autoclean_protected-months, and there is a protection? */
1711 if (_settings_client
.network
.autoclean_protected
!= 0 && _network_company_states
[c
->index
].months_empty
> _settings_client
.network
.autoclean_protected
&& !StrEmpty(_network_company_states
[c
->index
].password
)) {
1712 /* Unprotect the company */
1713 _network_company_states
[c
->index
].password
[0] = '\0';
1714 IConsolePrintF(CC_DEFAULT
, "Auto-removed protection from company #%d", c
->index
+ 1);
1715 _network_company_states
[c
->index
].months_empty
= 0;
1716 NetworkServerUpdateCompanyPassworded(c
->index
, false);
1718 /* Is the company empty for autoclean_novehicles-months, and has no vehicles? */
1719 if (_settings_client
.network
.autoclean_novehicles
!= 0 && _network_company_states
[c
->index
].months_empty
> _settings_client
.network
.autoclean_novehicles
&& vehicles_in_company
[c
->index
] == 0) {
1720 /* Shut the company down */
1721 DoCommandP(0, 2 | c
->index
<< 16, CRR_AUTOCLEAN
, CMD_COMPANY_CTRL
);
1722 IConsolePrintF(CC_DEFAULT
, "Auto-cleaned company #%d with no vehicles", c
->index
+ 1);
1725 /* It is not empty, reset the date */
1726 _network_company_states
[c
->index
].months_empty
= 0;
1732 * Check whether a name is unique, and otherwise try to make it unique.
1733 * @param new_name The name to check/modify.
1734 * @param last The last writeable element of the buffer.
1735 * @return True if an unique name was achieved.
1737 bool NetworkFindName(char *new_name
, const char *last
)
1739 bool found_name
= false;
1741 char original_name
[NETWORK_CLIENT_NAME_LENGTH
];
1743 strecpy(original_name
, new_name
, lastof(original_name
));
1745 while (!found_name
) {
1746 const NetworkClientInfo
*ci
;
1749 FOR_ALL_CLIENT_INFOS(ci
) {
1750 if (strcmp(ci
->client_name
, new_name
) == 0) {
1751 /* Name already in use */
1756 /* Check if it is the same as the server-name */
1757 ci
= NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER
);
1758 if (ci
!= nullptr) {
1759 if (strcmp(ci
->client_name
, new_name
) == 0) found_name
= false; // name already in use
1763 /* Try a new name (<name> #1, <name> #2, and so on) */
1765 /* Something's really wrong when there're more names than clients */
1766 if (number
++ > MAX_CLIENTS
) break;
1767 seprintf(new_name
, last
, "%s #%d", original_name
, number
);
1775 * Change the client name of the given client
1776 * @param client_id the client to change the name of
1777 * @param new_name the new name for the client
1778 * @return true iff the name was changed
1780 bool NetworkServerChangeClientName(ClientID client_id
, const char *new_name
)
1782 NetworkClientInfo
*ci
;
1783 /* Check if the name's already in use */
1784 FOR_ALL_CLIENT_INFOS(ci
) {
1785 if (strcmp(ci
->client_name
, new_name
) == 0) return false;
1788 ci
= NetworkClientInfo::GetByClientID(client_id
);
1789 if (ci
== nullptr) return false;
1791 NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE
, CC_DEFAULT
, true, ci
->client_name
, new_name
);
1793 strecpy(ci
->client_name
, new_name
, lastof(ci
->client_name
));
1795 NetworkUpdateClientInfo(client_id
);
1800 * Set/Reset a company password on the server end.
1801 * @param company_id ID of the company the password should be changed for.
1802 * @param password The new password.
1803 * @param already_hashed Is the given password already hashed?
1805 void NetworkServerSetCompanyPassword(CompanyID company_id
, const char *password
, bool already_hashed
)
1807 if (!Company::IsValidHumanID(company_id
)) return;
1809 if (!already_hashed
) {
1810 password
= GenerateCompanyPasswordHash(password
, _settings_client
.network
.network_id
, _settings_game
.game_creation
.generation_seed
);
1813 strecpy(_network_company_states
[company_id
].password
, password
, lastof(_network_company_states
[company_id
].password
));
1814 NetworkServerUpdateCompanyPassworded(company_id
, !StrEmpty(_network_company_states
[company_id
].password
));
1818 * Handle the command-queue of a socket.
1819 * @param cs The socket to handle the queue for.
1821 static void NetworkHandleCommandQueue(NetworkClientSocket
*cs
)
1824 while ((cp
= cs
->outgoing_queue
.Pop()) != nullptr) {
1825 cs
->SendCommand(cp
);
1831 * This is called every tick if this is a _network_server
1832 * @param send_frame Whether to send the frame to the clients.
1834 void NetworkServer_Tick(bool send_frame
)
1836 NetworkClientSocket
*cs
;
1837 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1838 bool send_sync
= false;
1841 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1842 if (_frame_counter
>= _last_sync_frame
+ _settings_client
.network
.sync_freq
) {
1843 _last_sync_frame
= _frame_counter
;
1848 /* Now we are done with the frame, inform the clients that they can
1849 * do their frame! */
1850 FOR_ALL_CLIENT_SOCKETS(cs
) {
1851 /* We allow a number of bytes per frame, but only to the burst amount
1852 * to be available for packet receiving at any particular time. */
1853 cs
->receive_limit
= min(cs
->receive_limit
+ _settings_client
.network
.bytes_per_frame
,
1854 _settings_client
.network
.bytes_per_frame_burst
);
1856 /* Check if the speed of the client is what we can expect from a client */
1857 uint lag
= NetworkCalculateLag(cs
);
1858 switch (cs
->status
) {
1859 case NetworkClientSocket::STATUS_ACTIVE
:
1860 if (lag
> _settings_client
.network
.max_lag_time
) {
1861 /* Client did still not report in within the specified limit. */
1862 IConsolePrintF(CC_ERROR
, cs
->last_packet
+ lag
* MILLISECONDS_PER_TICK
> _realtime_tick
?
1863 /* A packet was received in the last three game days, so the client is likely lagging behind. */
1864 "Client #%d is dropped because the client's game state is more than %d ticks behind" :
1865 /* No packet was received in the last three game days; sounds like a lost connection. */
1866 "Client #%d is dropped because the client did not respond for more than %d ticks",
1867 cs
->client_id
, lag
);
1868 cs
->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER
);
1872 /* Report once per time we detect the lag, and only when we
1873 * received a packet in the last 2000 milliseconds. If we
1874 * did not receive a packet, then the client is not just
1875 * slow, but the connection is likely severed. Mentioning
1876 * frame_freq is not useful in this case. */
1877 if (lag
> (uint
)DAY_TICKS
&& cs
->lag_test
== 0 && cs
->last_packet
+ 2000 > _realtime_tick
) {
1878 IConsolePrintF(CC_WARNING
, "[%d] Client #%d is slow, try increasing [network.]frame_freq to a higher value!", _frame_counter
, cs
->client_id
);
1882 if (cs
->last_frame_server
- cs
->last_token_frame
>= _settings_client
.network
.max_lag_time
) {
1883 /* This is a bad client! It didn't send the right token back within time. */
1884 IConsolePrintF(CC_ERROR
, "Client #%d is dropped because it fails to send valid acks", cs
->client_id
);
1885 cs
->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER
);
1890 case NetworkClientSocket::STATUS_INACTIVE
:
1891 case NetworkClientSocket::STATUS_NEWGRFS_CHECK
:
1892 case NetworkClientSocket::STATUS_AUTHORIZED
:
1893 /* NewGRF check and authorized states should be handled almost instantly.
1894 * So give them some lee-way, likewise for the query with inactive. */
1895 if (lag
> _settings_client
.network
.max_init_time
) {
1896 IConsolePrintF(CC_ERROR
, "Client #%d is dropped because it took longer than %d ticks to start the joining process", cs
->client_id
, _settings_client
.network
.max_init_time
);
1897 cs
->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER
);
1902 case NetworkClientSocket::STATUS_MAP
:
1903 /* Downloading the map... this is the amount of time since starting the saving. */
1904 if (lag
> _settings_client
.network
.max_download_time
) {
1905 IConsolePrintF(CC_ERROR
, "Client #%d is dropped because it took longer than %d ticks to download the map", cs
->client_id
, _settings_client
.network
.max_download_time
);
1906 cs
->SendError(NETWORK_ERROR_TIMEOUT_MAP
);
1911 case NetworkClientSocket::STATUS_DONE_MAP
:
1912 case NetworkClientSocket::STATUS_PRE_ACTIVE
:
1913 /* The map has been sent, so this is for loading the map and syncing up. */
1914 if (lag
> _settings_client
.network
.max_join_time
) {
1915 IConsolePrintF(CC_ERROR
, "Client #%d is dropped because it took longer than %d ticks to join", cs
->client_id
, _settings_client
.network
.max_join_time
);
1916 cs
->SendError(NETWORK_ERROR_TIMEOUT_JOIN
);
1921 case NetworkClientSocket::STATUS_AUTH_GAME
:
1922 case NetworkClientSocket::STATUS_AUTH_COMPANY
:
1923 /* These don't block? */
1924 if (lag
> _settings_client
.network
.max_password_time
) {
1925 IConsolePrintF(CC_ERROR
, "Client #%d is dropped because it took longer than %d ticks to enter the password", cs
->client_id
, _settings_client
.network
.max_password_time
);
1926 cs
->SendError(NETWORK_ERROR_TIMEOUT_PASSWORD
);
1931 case NetworkClientSocket::STATUS_MAP_WAIT
:
1932 /* This is an internal state where we do not wait
1933 * on the client to move to a different state. */
1936 case NetworkClientSocket::STATUS_END
:
1937 /* Bad server/code. */
1941 if (cs
->status
>= NetworkClientSocket::STATUS_PRE_ACTIVE
) {
1942 /* Check if we can send command, and if we have anything in the queue */
1943 NetworkHandleCommandQueue(cs
);
1945 /* Send an updated _frame_counter_max to the client */
1946 if (send_frame
) cs
->SendFrame();
1948 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1949 /* Send a sync-check packet */
1950 if (send_sync
) cs
->SendSync();
1955 /* See if we need to advertise */
1956 NetworkUDPAdvertise();
1959 /** Yearly "callback". Called whenever the year changes. */
1960 void NetworkServerYearlyLoop()
1962 NetworkCheckRestartMap();
1963 NetworkAdminUpdate(ADMIN_FREQUENCY_ANUALLY
);
1966 /** Monthly "callback". Called whenever the month changes. */
1967 void NetworkServerMonthlyLoop()
1969 NetworkAutoCleanCompanies();
1970 NetworkAdminUpdate(ADMIN_FREQUENCY_MONTHLY
);
1971 if ((_cur_month
% 3) == 0) NetworkAdminUpdate(ADMIN_FREQUENCY_QUARTERLY
);
1974 /** Daily "callback". Called whenever the date changes. */
1975 void NetworkServerDailyLoop()
1977 NetworkAdminUpdate(ADMIN_FREQUENCY_DAILY
);
1978 if ((_date
% 7) == 3) NetworkAdminUpdate(ADMIN_FREQUENCY_WEEKLY
);
1982 * Get the IP address/hostname of the connected client.
1983 * @return The IP address.
1985 const char *ServerNetworkGameSocketHandler::GetClientIP()
1987 return this->client_address
.GetHostname();
1990 /** Show the status message of all clients on the console. */
1991 void NetworkServerShowStatusToConsole()
1993 static const char * const stat_str
[] = {
1996 "authorizing (server password)",
1997 "authorizing (company password)",
2005 assert_compile(lengthof(stat_str
) == NetworkClientSocket::STATUS_END
);
2007 NetworkClientSocket
*cs
;
2008 FOR_ALL_CLIENT_SOCKETS(cs
) {
2009 NetworkClientInfo
*ci
= cs
->GetInfo();
2010 if (ci
== nullptr) continue;
2011 uint lag
= NetworkCalculateLag(cs
);
2014 status
= (cs
->status
< (ptrdiff_t)lengthof(stat_str
) ? stat_str
[cs
->status
] : "unknown");
2015 IConsolePrintF(CC_INFO
, "Client #%1d name: '%s' status: '%s' frame-lag: %3d company: %1d IP: %s",
2016 cs
->client_id
, ci
->client_name
, status
, lag
,
2017 ci
->client_playas
+ (Company::IsValidID(ci
->client_playas
) ? 1 : 0),
2023 * Send Config Update
2025 void NetworkServerSendConfigUpdate()
2027 NetworkClientSocket
*cs
;
2029 FOR_ALL_CLIENT_SOCKETS(cs
) {
2030 if (cs
->status
>= NetworkClientSocket::STATUS_PRE_ACTIVE
) cs
->SendConfigUpdate();
2035 * Tell that a particular company is (not) passworded.
2036 * @param company_id The company that got/removed the password.
2037 * @param passworded Whether the password was received or removed.
2039 void NetworkServerUpdateCompanyPassworded(CompanyID company_id
, bool passworded
)
2041 if (NetworkCompanyIsPassworded(company_id
) == passworded
) return;
2043 SB(_network_company_passworded
, company_id
, 1, !!passworded
);
2044 SetWindowClassesDirty(WC_COMPANY
);
2046 NetworkClientSocket
*cs
;
2047 FOR_ALL_CLIENT_SOCKETS(cs
) {
2048 if (cs
->status
>= NetworkClientSocket::STATUS_PRE_ACTIVE
) cs
->SendCompanyUpdate();
2051 NetworkAdminCompanyUpdate(Company::GetIfValid(company_id
));
2055 * Handle the tid-bits of moving a client from one company to another.
2056 * @param client_id id of the client we want to move.
2057 * @param company_id id of the company we want to move the client to.
2060 void NetworkServerDoMove(ClientID client_id
, CompanyID company_id
)
2062 /* Only allow non-dedicated servers and normal clients to be moved */
2063 if (client_id
== CLIENT_ID_SERVER
&& _network_dedicated
) return;
2065 NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID(client_id
);
2067 /* No need to waste network resources if the client is in the company already! */
2068 if (ci
->client_playas
== company_id
) return;
2070 ci
->client_playas
= company_id
;
2072 if (client_id
== CLIENT_ID_SERVER
) {
2073 SetLocalCompany(company_id
);
2075 NetworkClientSocket
*cs
= NetworkClientSocket::GetByClientID(client_id
);
2076 /* When the company isn't authorized we can't move them yet. */
2077 if (cs
->status
< NetworkClientSocket::STATUS_AUTHORIZED
) return;
2078 cs
->SendMove(client_id
, company_id
);
2081 /* announce the client's move */
2082 NetworkUpdateClientInfo(client_id
);
2084 NetworkAction action
= (company_id
== COMPANY_SPECTATOR
) ? NETWORK_ACTION_COMPANY_SPECTATOR
: NETWORK_ACTION_COMPANY_JOIN
;
2085 NetworkServerSendChat(action
, DESTTYPE_BROADCAST
, 0, "", client_id
, company_id
+ 1);
2089 * Send an rcon reply to the client.
2090 * @param client_id The identifier of the client.
2091 * @param colour_code The colour of the text.
2092 * @param string The actual reply.
2094 void NetworkServerSendRcon(ClientID client_id
, TextColour colour_code
, const char *string
)
2096 NetworkClientSocket::GetByClientID(client_id
)->SendRConResult(colour_code
, string
);
2100 * Kick a single client.
2101 * @param client_id The client to kick.
2103 void NetworkServerKickClient(ClientID client_id
)
2105 if (client_id
== CLIENT_ID_SERVER
) return;
2106 NetworkClientSocket::GetByClientID(client_id
)->SendError(NETWORK_ERROR_KICKED
);
2110 * Ban, or kick, everyone joined from the given client's IP.
2111 * @param client_id The client to check for.
2112 * @param ban Whether to ban or kick.
2114 uint
NetworkServerKickOrBanIP(ClientID client_id
, bool ban
)
2116 return NetworkServerKickOrBanIP(NetworkClientSocket::GetByClientID(client_id
)->GetClientIP(), ban
);
2120 * Kick or ban someone based on an IP address.
2121 * @param ip The IP address/range to ban/kick.
2122 * @param ban Whether to ban or just kick.
2124 uint
NetworkServerKickOrBanIP(const char *ip
, bool ban
)
2126 /* Add address to ban-list */
2128 bool contains
= false;
2129 for (char **iter
= _network_ban_list
.Begin(); iter
!= _network_ban_list
.End(); iter
++) {
2130 if (strcmp(*iter
, ip
) == 0) {
2135 if (!contains
) *_network_ban_list
.Append() = stredup(ip
);
2140 /* There can be multiple clients with the same IP, kick them all */
2141 NetworkClientSocket
*cs
;
2142 FOR_ALL_CLIENT_SOCKETS(cs
) {
2143 if (cs
->client_id
== CLIENT_ID_SERVER
) continue;
2144 if (cs
->client_address
.IsInNetmask(const_cast<char *>(ip
))) {
2145 NetworkServerKickClient(cs
->client_id
);
2154 * Check whether a particular company has clients.
2155 * @param company The company to check.
2156 * @return True if at least one client is joined to the company.
2158 bool NetworkCompanyHasClients(CompanyID company
)
2160 const NetworkClientInfo
*ci
;
2161 FOR_ALL_CLIENT_INFOS(ci
) {
2162 if (ci
->client_playas
== company
) return true;
2169 * Get the name of the client, if the user did not send it yet, Client #<no> is used.
2170 * @param client_name The variable to write the name to.
2171 * @param last The pointer to the last element of the destination buffer
2173 void ServerNetworkGameSocketHandler::GetClientName(char *client_name
, const char *last
) const
2175 const NetworkClientInfo
*ci
= this->GetInfo();
2177 if (ci
== nullptr || StrEmpty(ci
->client_name
)) {
2178 seprintf(client_name
, last
, "Client #%4d", this->client_id
);
2180 strecpy(client_name
, ci
->client_name
, last
);
2185 * Print all the clients to the console
2187 void NetworkPrintClients()
2189 NetworkClientInfo
*ci
;
2190 FOR_ALL_CLIENT_INFOS(ci
) {
2191 if (_network_server
) {
2192 IConsolePrintF(CC_INFO
, "Client #%1d name: '%s' company: %1d IP: %s",
2195 ci
->client_playas
+ (Company::IsValidID(ci
->client_playas
) ? 1 : 0),
2196 ci
->client_id
== CLIENT_ID_SERVER
? "server" : NetworkClientSocket::GetByClientID(ci
->client_id
)->GetClientIP());
2198 IConsolePrintF(CC_INFO
, "Client #%1d name: '%s' company: %1d",
2201 ci
->client_playas
+ (Company::IsValidID(ci
->client_playas
) ? 1 : 0));
2207 * Perform all the server specific administration of a new company.
2208 * @param c The newly created company; can't be nullptr.
2209 * @param ci The client information of the client that made the company; can be nullptr.
2211 void NetworkServerNewCompany(const Company
*c
, NetworkClientInfo
*ci
)
2213 assert(c
!= nullptr);
2215 if (!_network_server
) return;
2217 _network_company_states
[c
->index
].months_empty
= 0;
2218 _network_company_states
[c
->index
].password
[0] = '\0';
2219 NetworkServerUpdateCompanyPassworded(c
->index
, false);
2221 if (ci
!= nullptr) {
2222 /* ci is nullptr when replaying, or for AIs. In neither case there is a client. */
2223 ci
->client_playas
= c
->index
;
2224 NetworkUpdateClientInfo(ci
->client_id
);
2225 NetworkSendCommand(0, 0, 0, CMD_RENAME_PRESIDENT
, nullptr, ci
->client_name
, c
->index
, 0);
2228 /* Announce new company on network. */
2229 NetworkAdminCompanyInfo(c
, true);
2231 if (ci
!= nullptr) {
2232 /* ci is nullptr when replaying, or for AIs. In neither case there is a client.
2233 We need to send Admin port update here so that they first know about the new company
2234 and then learn about a possibly joining client (see FS#6025) */
2235 NetworkServerSendChat(NETWORK_ACTION_COMPANY_NEW
, DESTTYPE_BROADCAST
, 0, "", ci
->client_id
, c
->index
+ 1);
2239 #endif /* ENABLE_NETWORK */