Update: Translations from eints
[openttd-github.git] / src / network / network_server.cpp
blobbe04e39a99e4e65cf3b2daf5358f7299f5df55f0
1 /*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
8 /** @file network_server.cpp Server part of the network protocol. */
10 #include "../stdafx.h"
11 #include "../strings_func.h"
12 #include "core/network_game_info.h"
13 #include "network_admin.h"
14 #include "network_server.h"
15 #include "network_udp.h"
16 #include "network_base.h"
17 #include "../console_func.h"
18 #include "../company_base.h"
19 #include "../command_func.h"
20 #include "../saveload/saveload.h"
21 #include "../saveload/saveload_filter.h"
22 #include "../station_base.h"
23 #include "../genworld.h"
24 #include "../company_func.h"
25 #include "../company_gui.h"
26 #include "../company_cmd.h"
27 #include "../roadveh.h"
28 #include "../order_backup.h"
29 #include "../core/pool_func.hpp"
30 #include "../core/random_func.hpp"
31 #include "../company_cmd.h"
32 #include "../rev.h"
33 #include "../timer/timer.h"
34 #include "../timer/timer_game_calendar.h"
35 #include "../timer/timer_game_economy.h"
36 #include "../timer/timer_game_realtime.h"
37 #include <mutex>
38 #include <condition_variable>
40 #include "../safeguards.h"
43 /* This file handles all the server-commands */
45 DECLARE_POSTFIX_INCREMENT(ClientID)
46 /** The identifier counter for new clients (is never decreased) */
47 static ClientID _network_client_id = CLIENT_ID_FIRST;
49 /** Make very sure the preconditions given in network_type.h are actually followed */
50 static_assert(MAX_CLIENT_SLOTS > MAX_CLIENTS);
51 /** Yes... */
52 static_assert(NetworkClientSocketPool::MAX_SIZE == MAX_CLIENT_SLOTS);
54 /** The pool with clients. */
55 NetworkClientSocketPool _networkclientsocket_pool("NetworkClientSocket");
56 INSTANTIATE_POOL_METHODS(NetworkClientSocket)
58 /** Instantiate the listen sockets. */
59 template SocketList TCPListenHandler<ServerNetworkGameSocketHandler, PACKET_SERVER_FULL, PACKET_SERVER_BANNED>::sockets;
61 static NetworkAuthenticationDefaultPasswordProvider _password_provider(_settings_client.network.server_password); ///< Provides the password validation for the game's password.
62 static NetworkAuthenticationDefaultAuthorizedKeyHandler _authorized_key_handler(_settings_client.network.server_authorized_keys); ///< Provides the authorized key handling for the game authentication.
63 static NetworkAuthenticationDefaultAuthorizedKeyHandler _rcon_authorized_key_handler(_settings_client.network.rcon_authorized_keys); ///< Provides the authorized key validation for rcon.
66 /** Writing a savegame directly to a number of packets. */
67 struct PacketWriter : SaveFilter {
68 ServerNetworkGameSocketHandler *cs; ///< Socket we are associated with.
69 std::unique_ptr<Packet> current; ///< The packet we're currently writing to.
70 size_t total_size; ///< Total size of the compressed savegame.
71 std::deque<std::unique_ptr<Packet>> packets; ///< Packet queue of the savegame; send these "slowly" to the client. Cannot be a std::queue as we want to push the map size packet in front of the data packets.
72 std::mutex mutex; ///< Mutex for making threaded saving safe.
73 std::condition_variable exit_sig; ///< Signal for threaded destruction of this packet writer.
75 /**
76 * Create the packet writer.
77 * @param cs The socket handler we're making the packets for.
79 PacketWriter(ServerNetworkGameSocketHandler *cs) : SaveFilter(nullptr), cs(cs), total_size(0)
83 /** Make sure everything is cleaned up. */
84 ~PacketWriter()
86 std::unique_lock<std::mutex> lock(this->mutex);
88 if (this->cs != nullptr) this->exit_sig.wait(lock);
90 /* This must all wait until the Destroy function is called. */
92 this->packets.clear();
93 this->current = nullptr;
96 /**
97 * Begin the destruction of this packet writer. It can happen in two ways:
98 * in the first case the client disconnected while saving the map. In this
99 * case the saving has not finished and killed this PacketWriter. In that
100 * case we simply set cs to nullptr, triggering the appending to fail due to
101 * the connection problem and eventually triggering the destructor. In the
102 * second case the destructor is already called, and it is waiting for our
103 * signal which we will send. Only then the packets will be removed by the
104 * destructor.
106 void Destroy()
108 std::unique_lock<std::mutex> lock(this->mutex);
110 this->cs = nullptr;
112 this->exit_sig.notify_all();
113 lock.unlock();
115 /* Make sure the saving is completely cancelled. Yes,
116 * we need to handle the save finish as well as the
117 * next connection might just be requesting a map. */
118 WaitTillSaved();
122 * Transfer all packets from here to the network's queue while holding
123 * the lock on our mutex.
124 * @return True iff the last packet of the map has been sent.
126 bool TransferToNetworkQueue()
128 /* Unsafe check for the queue being empty or not. */
129 if (this->packets.empty()) return false;
131 std::lock_guard<std::mutex> lock(this->mutex);
133 while (!this->packets.empty()) {
134 bool last_packet = this->packets.front()->GetPacketType() == PACKET_SERVER_MAP_DONE;
135 this->cs->SendPacket(std::move(this->packets.front()));
136 this->packets.pop_front();
138 if (last_packet) return true;
141 return false;
144 void Write(uint8_t *buf, size_t size) override
146 std::lock_guard<std::mutex> lock(this->mutex);
148 /* We want to abort the saving when the socket is closed. */
149 if (this->cs == nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
151 if (this->current == nullptr) this->current = std::make_unique<Packet>(this->cs, PACKET_SERVER_MAP_DATA, TCP_MTU);
153 std::span<const uint8_t> to_write(buf, size);
154 while (!to_write.empty()) {
155 to_write = this->current->Send_bytes(to_write);
157 if (!this->current->CanWriteToPacket(1)) {
158 this->packets.push_back(std::move(this->current));
159 if (!to_write.empty()) this->current = std::make_unique<Packet>(this->cs, PACKET_SERVER_MAP_DATA, TCP_MTU);
163 this->total_size += size;
166 void Finish() override
168 std::lock_guard<std::mutex> lock(this->mutex);
170 /* We want to abort the saving when the socket is closed. */
171 if (this->cs == nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
173 /* Make sure the last packet is flushed. */
174 if (this->current != nullptr) this->packets.push_back(std::move(this->current));
176 /* Add a packet stating that this is the end to the queue. */
177 this->packets.push_back(std::make_unique<Packet>(this->cs, PACKET_SERVER_MAP_DONE));
179 /* Fast-track the size to the client. */
180 auto p = std::make_unique<Packet>(this->cs, PACKET_SERVER_MAP_SIZE);
181 p->Send_uint32((uint32_t)this->total_size);
182 this->packets.push_front(std::move(p));
188 * Create a new socket for the server side of the game connection.
189 * @param s The socket to connect with.
191 ServerNetworkGameSocketHandler::ServerNetworkGameSocketHandler(SOCKET s) : NetworkGameSocketHandler(s)
193 this->status = STATUS_INACTIVE;
194 this->client_id = _network_client_id++;
195 this->receive_limit = _settings_client.network.bytes_per_frame_burst;
197 Debug(net, 9, "client[{}] status = INACTIVE", this->client_id);
199 /* The Socket and Info pools need to be the same in size. After all,
200 * each Socket will be associated with at most one Info object. As
201 * such if the Socket was allocated the Info object can as well. */
202 static_assert(NetworkClientSocketPool::MAX_SIZE == NetworkClientInfoPool::MAX_SIZE);
206 * Clear everything related to this client.
208 ServerNetworkGameSocketHandler::~ServerNetworkGameSocketHandler()
210 delete this->GetInfo();
212 if (_redirect_console_to_client == this->client_id) _redirect_console_to_client = INVALID_CLIENT_ID;
213 OrderBackup::ResetUser(this->client_id);
215 if (this->savegame != nullptr) {
216 this->savegame->Destroy();
217 this->savegame = nullptr;
220 InvalidateWindowData(WC_CLIENT_LIST, 0);
223 std::unique_ptr<Packet> ServerNetworkGameSocketHandler::ReceivePacket()
225 /* Only allow receiving when we have some buffer free; this value
226 * can go negative, but eventually it will become positive again. */
227 if (this->receive_limit <= 0) return nullptr;
229 /* We can receive a packet, so try that and if needed account for
230 * the amount of received data. */
231 std::unique_ptr<Packet> p = this->NetworkTCPSocketHandler::ReceivePacket();
232 if (p != nullptr) this->receive_limit -= p->Size();
233 return p;
236 NetworkRecvStatus ServerNetworkGameSocketHandler::CloseConnection(NetworkRecvStatus status)
238 assert(status != NETWORK_RECV_STATUS_OKAY);
240 * Sending a message just before leaving the game calls cs->SendPackets.
241 * This might invoke this function, which means that when we close the
242 * connection after cs->SendPackets we will close an already closed
243 * connection. This handles that case gracefully without having to make
244 * that code any more complex or more aware of the validity of the socket.
246 if (this->IsPendingDeletion() || this->sock == INVALID_SOCKET) return status;
248 if (status != NETWORK_RECV_STATUS_CLIENT_QUIT && status != NETWORK_RECV_STATUS_SERVER_ERROR && !this->HasClientQuit() && this->status >= STATUS_AUTHORIZED) {
249 /* We did not receive a leave message from this client... */
250 std::string client_name = this->GetClientName();
252 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, "", STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST);
254 /* Inform other clients of this... strange leaving ;) */
255 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
256 if (new_cs->status >= STATUS_AUTHORIZED && this != new_cs) {
257 new_cs->SendErrorQuit(this->client_id, NETWORK_ERROR_CONNECTION_LOST);
262 /* If we were transfering a map to this client, stop the savegame creation
263 * process and queue the next client to receive the map. */
264 if (this->status == STATUS_MAP) {
265 /* Ensure the saving of the game is stopped too. */
266 this->savegame->Destroy();
267 this->savegame = nullptr;
269 this->CheckNextClientToSendMap(this);
272 NetworkAdminClientError(this->client_id, NETWORK_ERROR_CONNECTION_LOST);
273 Debug(net, 3, "[{}] Client #{} closed connection", ServerNetworkGameSocketHandler::GetName(), this->client_id);
275 /* We just lost one client :( */
276 if (this->status >= STATUS_AUTHORIZED) _network_game_info.clients_on--;
277 extern uint8_t _network_clients_connected;
278 _network_clients_connected--;
280 this->SendPackets(true);
282 this->DeferDeletion();
284 return status;
288 * Whether an connection is allowed or not at this moment.
289 * @return true if the connection is allowed.
291 /* static */ bool ServerNetworkGameSocketHandler::AllowConnection()
293 extern uint8_t _network_clients_connected;
294 bool accept = _network_clients_connected < MAX_CLIENTS;
296 /* We can't go over the MAX_CLIENTS limit here. However, the
297 * pool must have place for all clients and ourself. */
298 static_assert(NetworkClientSocketPool::MAX_SIZE == MAX_CLIENTS + 1);
299 assert(!accept || ServerNetworkGameSocketHandler::CanAllocateItem());
300 return accept;
303 /** Send the packets for the server sockets. */
304 /* static */ void ServerNetworkGameSocketHandler::Send()
306 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
307 if (cs->writable) {
308 if (cs->SendPackets() != SPS_CLOSED && cs->status == STATUS_MAP) {
309 /* This client is in the middle of a map-send, call the function for that */
310 cs->SendMap();
316 static void NetworkHandleCommandQueue(NetworkClientSocket *cs);
318 /***********
319 * Sending functions
320 ************/
323 * Send the client information about a client.
324 * @param ci The client to send information about.
326 NetworkRecvStatus ServerNetworkGameSocketHandler::SendClientInfo(NetworkClientInfo *ci)
328 Debug(net, 9, "client[{}] SendClientInfo(): client_id={}", this->client_id, ci->client_id);
330 if (ci->client_id != INVALID_CLIENT_ID) {
331 auto p = std::make_unique<Packet>(this, PACKET_SERVER_CLIENT_INFO);
332 p->Send_uint32(ci->client_id);
333 p->Send_uint8 (ci->client_playas);
334 p->Send_string(ci->client_name);
335 p->Send_string(ci->public_key);
337 this->SendPacket(std::move(p));
339 return NETWORK_RECV_STATUS_OKAY;
342 /** Send the client information about the server. */
343 NetworkRecvStatus ServerNetworkGameSocketHandler::SendGameInfo()
345 Debug(net, 9, "client[{}] SendGameInfo()", this->client_id);
347 auto p = std::make_unique<Packet>(this, PACKET_SERVER_GAME_INFO, TCP_MTU);
348 SerializeNetworkGameInfo(*p, GetCurrentNetworkServerGameInfo());
350 this->SendPacket(std::move(p));
352 return NETWORK_RECV_STATUS_OKAY;
356 * Send an error to the client, and close its connection.
357 * @param error The error to disconnect for.
358 * @param reason In case of kicking a client, specifies the reason for kicking the client.
360 NetworkRecvStatus ServerNetworkGameSocketHandler::SendError(NetworkErrorCode error, const std::string &reason)
362 Debug(net, 9, "client[{}] SendError(): error={}", this->client_id, error);
364 auto p = std::make_unique<Packet>(this, PACKET_SERVER_ERROR);
366 p->Send_uint8(error);
367 if (!reason.empty()) p->Send_string(reason);
368 this->SendPacket(std::move(p));
370 StringID strid = GetNetworkErrorMsg(error);
372 /* Only send when the current client was in game */
373 if (this->status >= STATUS_AUTHORIZED) {
374 std::string client_name = this->GetClientName();
376 Debug(net, 1, "'{}' made an error and has been disconnected: {}", client_name, GetString(strid));
378 if (error == NETWORK_ERROR_KICKED && !reason.empty()) {
379 NetworkTextMessage(NETWORK_ACTION_KICKED, CC_DEFAULT, false, client_name, reason, strid);
380 } else {
381 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, "", strid);
384 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
385 if (new_cs->status >= STATUS_AUTHORIZED && new_cs != this) {
386 /* Some errors we filter to a more general error. Clients don't have to know the real
387 * reason a joining failed. */
388 if (error == NETWORK_ERROR_NOT_AUTHORIZED || error == NETWORK_ERROR_NOT_EXPECTED || error == NETWORK_ERROR_WRONG_REVISION) {
389 error = NETWORK_ERROR_ILLEGAL_PACKET;
391 new_cs->SendErrorQuit(this->client_id, error);
395 NetworkAdminClientError(this->client_id, error);
396 } else {
397 Debug(net, 1, "Client {} made an error and has been disconnected: {}", this->client_id, GetString(strid));
400 /* The client made a mistake, so drop the connection now! */
401 return this->CloseConnection(NETWORK_RECV_STATUS_SERVER_ERROR);
404 /** Send the check for the NewGRFs. */
405 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGRFCheck()
407 Debug(net, 9, "client[{}] SendNewGRFCheck()", this->client_id);
409 /* Invalid packet when status is anything but STATUS_IDENTIFY. */
410 if (this->status != STATUS_IDENTIFY) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
412 Debug(net, 9, "client[{}] status = NEWGRFS_CHECK", this->client_id);
413 this->status = STATUS_NEWGRFS_CHECK;
415 if (_grfconfig == nullptr) {
416 /* There are no NewGRFs, so they're welcome. */
417 return this->SendWelcome();
420 auto p = std::make_unique<Packet>(this, PACKET_SERVER_CHECK_NEWGRFS, TCP_MTU);
421 const GRFConfig *c;
422 uint grf_count = 0;
424 for (c = _grfconfig; c != nullptr; c = c->next) {
425 if (!HasBit(c->flags, GCF_STATIC)) grf_count++;
428 p->Send_uint8 (grf_count);
429 for (c = _grfconfig; c != nullptr; c = c->next) {
430 if (!HasBit(c->flags, GCF_STATIC)) SerializeGRFIdentifier(*p, c->ident);
433 this->SendPacket(std::move(p));
434 return NETWORK_RECV_STATUS_OKAY;
437 /** Request the game password. */
438 NetworkRecvStatus ServerNetworkGameSocketHandler::SendAuthRequest()
440 Debug(net, 9, "client[{}] SendAuthRequest()", this->client_id);
442 /* Invalid packet when status is anything but STATUS_INACTIVE or STATUS_AUTH_GAME. */
443 if (this->status != STATUS_INACTIVE && status != STATUS_AUTH_GAME) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
445 Debug(net, 9, "client[{}] status = AUTH_GAME", this->client_id);
446 this->status = STATUS_AUTH_GAME;
448 /* Reset 'lag' counters */
449 this->last_frame = this->last_frame_server = _frame_counter;
451 if (this->authentication_handler == nullptr) {
452 this->authentication_handler = NetworkAuthenticationServerHandler::Create(&_password_provider, &_authorized_key_handler);
455 auto p = std::make_unique<Packet>(this, PACKET_SERVER_AUTH_REQUEST);
456 this->authentication_handler->SendRequest(*p);
458 this->SendPacket(std::move(p));
459 return NETWORK_RECV_STATUS_OKAY;
462 /** Notify the client that the authentication has completed and tell that for the remainder of this socket encryption is enabled. */
463 NetworkRecvStatus ServerNetworkGameSocketHandler::SendEnableEncryption()
465 Debug(net, 9, "client[{}] SendEnableEncryption()", this->client_id);
467 /* Invalid packet when status is anything but STATUS_AUTH_GAME. */
468 if (this->status != STATUS_AUTH_GAME) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
470 auto p = std::make_unique<Packet>(this, PACKET_SERVER_ENABLE_ENCRYPTION);
471 this->authentication_handler->SendEnableEncryption(*p);
472 this->SendPacket(std::move(p));
473 return NETWORK_RECV_STATUS_OKAY;
476 /** Send the client a welcome message with some basic information. */
477 NetworkRecvStatus ServerNetworkGameSocketHandler::SendWelcome()
479 Debug(net, 9, "client[{}] SendWelcome()", this->client_id);
481 /* Invalid packet when status is anything but STATUS_NEWGRFS_CHECK. */
482 if (this->status != STATUS_NEWGRFS_CHECK) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
484 Debug(net, 9, "client[{}] status = AUTHORIZED", this->client_id);
485 this->status = STATUS_AUTHORIZED;
487 /* Reset 'lag' counters */
488 this->last_frame = this->last_frame_server = _frame_counter;
490 _network_game_info.clients_on++;
492 auto p = std::make_unique<Packet>(this, PACKET_SERVER_WELCOME);
493 p->Send_uint32(this->client_id);
494 this->SendPacket(std::move(p));
496 /* Transmit info about all the active clients */
497 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
498 if (new_cs != this && new_cs->status >= STATUS_AUTHORIZED) {
499 this->SendClientInfo(new_cs->GetInfo());
502 /* Also send the info of the server */
503 return this->SendClientInfo(NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER));
506 /** Tell the client that its put in a waiting queue. */
507 NetworkRecvStatus ServerNetworkGameSocketHandler::SendWait()
509 Debug(net, 9, "client[{}] SendWait()", this->client_id);
511 int waiting = 1; // current player getting the map counts as 1
513 /* Count how many clients are waiting in the queue, in front of you! */
514 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
515 if (new_cs->status != STATUS_MAP_WAIT) continue;
516 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++;
519 auto p = std::make_unique<Packet>(this, PACKET_SERVER_WAIT);
520 p->Send_uint8(waiting);
521 this->SendPacket(std::move(p));
522 return NETWORK_RECV_STATUS_OKAY;
525 void ServerNetworkGameSocketHandler::CheckNextClientToSendMap(NetworkClientSocket *ignore_cs)
527 Debug(net, 9, "client[{}] CheckNextClientToSendMap()", this->client_id);
529 /* Find the best candidate for joining, i.e. the first joiner. */
530 NetworkClientSocket *best = nullptr;
531 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
532 if (ignore_cs == new_cs) continue;
534 if (new_cs->status == STATUS_MAP_WAIT) {
535 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)) {
536 best = new_cs;
541 /* Is there someone else to join? */
542 if (best != nullptr) {
543 /* Let the first start joining. */
544 best->status = STATUS_AUTHORIZED;
545 best->SendMap();
547 /* And update the rest. */
548 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
549 if (new_cs->status == STATUS_MAP_WAIT) new_cs->SendWait();
554 /** This sends the map to the client */
555 NetworkRecvStatus ServerNetworkGameSocketHandler::SendMap()
557 if (this->status < STATUS_AUTHORIZED) {
558 /* Illegal call, return error and ignore the packet */
559 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
562 if (this->status == STATUS_AUTHORIZED) {
563 Debug(net, 9, "client[{}] SendMap(): first_packet", this->client_id);
565 WaitTillSaved();
566 this->savegame = std::make_shared<PacketWriter>(this);
568 /* Now send the _frame_counter and how many packets are coming */
569 auto p = std::make_unique<Packet>(this, PACKET_SERVER_MAP_BEGIN);
570 p->Send_uint32(_frame_counter);
571 this->SendPacket(std::move(p));
573 NetworkSyncCommandQueue(this);
574 Debug(net, 9, "client[{}] status = MAP", this->client_id);
575 this->status = STATUS_MAP;
576 /* Mark the start of download */
577 this->last_frame = _frame_counter;
578 this->last_frame_server = _frame_counter;
580 /* Make a dump of the current game */
581 if (SaveWithFilter(this->savegame, true) != SL_OK) UserError("network savedump failed");
584 if (this->status == STATUS_MAP) {
585 bool last_packet = this->savegame->TransferToNetworkQueue();
586 if (last_packet) {
587 Debug(net, 9, "client[{}] SendMap(): last_packet", this->client_id);
589 /* Done reading, make sure saving is done as well */
590 this->savegame->Destroy();
591 this->savegame = nullptr;
593 /* Set the status to DONE_MAP, no we will wait for the client
594 * to send it is ready (maybe that happens like never ;)) */
595 Debug(net, 9, "client[{}] status = DONE_MAP", this->client_id);
596 this->status = STATUS_DONE_MAP;
598 this->CheckNextClientToSendMap();
601 return NETWORK_RECV_STATUS_OKAY;
605 * Tell that a client joined.
606 * @param client_id The client that joined.
608 NetworkRecvStatus ServerNetworkGameSocketHandler::SendJoin(ClientID client_id)
610 Debug(net, 9, "client[{}] SendJoin(): client_id={}", this->client_id, client_id);
612 auto p = std::make_unique<Packet>(this, PACKET_SERVER_JOIN);
614 p->Send_uint32(client_id);
616 this->SendPacket(std::move(p));
617 return NETWORK_RECV_STATUS_OKAY;
620 /** Tell the client that they may run to a particular frame. */
621 NetworkRecvStatus ServerNetworkGameSocketHandler::SendFrame()
623 auto p = std::make_unique<Packet>(this, PACKET_SERVER_FRAME);
624 p->Send_uint32(_frame_counter);
625 p->Send_uint32(_frame_counter_max);
626 #ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
627 p->Send_uint32(_sync_seed_1);
628 #ifdef NETWORK_SEND_DOUBLE_SEED
629 p->Send_uint32(_sync_seed_2);
630 #endif
631 #endif
633 /* If token equals 0, we need to make a new token and send that. */
634 if (this->last_token == 0) {
635 this->last_token = InteractiveRandomRange(UINT8_MAX - 1) + 1;
636 p->Send_uint8(this->last_token);
639 this->SendPacket(std::move(p));
640 return NETWORK_RECV_STATUS_OKAY;
643 /** Request the client to sync. */
644 NetworkRecvStatus ServerNetworkGameSocketHandler::SendSync()
646 Debug(net, 9, "client[{}] SendSync(), frame_counter={}, sync_seed_1={}", this->client_id, _frame_counter, _sync_seed_1);
648 auto p = std::make_unique<Packet>(this, PACKET_SERVER_SYNC);
649 p->Send_uint32(_frame_counter);
650 p->Send_uint32(_sync_seed_1);
652 #ifdef NETWORK_SEND_DOUBLE_SEED
653 p->Send_uint32(_sync_seed_2);
654 #endif
655 this->SendPacket(std::move(p));
656 return NETWORK_RECV_STATUS_OKAY;
660 * Send a command to the client to execute.
661 * @param cp The command to send.
663 NetworkRecvStatus ServerNetworkGameSocketHandler::SendCommand(const CommandPacket &cp)
665 Debug(net, 9, "client[{}] SendCommand(): cmd={}", this->client_id, cp.cmd);
667 auto p = std::make_unique<Packet>(this, PACKET_SERVER_COMMAND);
669 this->NetworkGameSocketHandler::SendCommand(*p, cp);
670 p->Send_uint32(cp.frame);
671 p->Send_bool (cp.my_cmd);
673 this->SendPacket(std::move(p));
674 return NETWORK_RECV_STATUS_OKAY;
678 * Send a chat message.
679 * @param action The action associated with the message.
680 * @param client_id The origin of the chat message.
681 * @param self_send Whether we did send the message.
682 * @param msg The actual message.
683 * @param data Arbitrary extra data.
685 NetworkRecvStatus ServerNetworkGameSocketHandler::SendChat(NetworkAction action, ClientID client_id, bool self_send, const std::string &msg, int64_t data)
687 Debug(net, 9, "client[{}] SendChat(): action={}, client_id={}, self_send={}", this->client_id, action, client_id, self_send);
689 if (this->status < STATUS_PRE_ACTIVE) return NETWORK_RECV_STATUS_OKAY;
691 auto p = std::make_unique<Packet>(this, PACKET_SERVER_CHAT);
693 p->Send_uint8 (action);
694 p->Send_uint32(client_id);
695 p->Send_bool (self_send);
696 p->Send_string(msg);
697 p->Send_uint64(data);
699 this->SendPacket(std::move(p));
700 return NETWORK_RECV_STATUS_OKAY;
704 * Send a chat message from external source.
705 * @param source Name of the source this message came from.
706 * @param colour TextColour to use for the message.
707 * @param user Name of the user who sent the messsage.
708 * @param msg The actual message.
710 NetworkRecvStatus ServerNetworkGameSocketHandler::SendExternalChat(const std::string &source, TextColour colour, const std::string &user, const std::string &msg)
712 Debug(net, 9, "client[{}] SendExternalChat(): source={}", this->client_id, source);
714 if (this->status < STATUS_PRE_ACTIVE) return NETWORK_RECV_STATUS_OKAY;
716 auto p = std::make_unique<Packet>(this, PACKET_SERVER_EXTERNAL_CHAT);
718 p->Send_string(source);
719 p->Send_uint16(colour);
720 p->Send_string(user);
721 p->Send_string(msg);
723 this->SendPacket(std::move(p));
724 return NETWORK_RECV_STATUS_OKAY;
728 * Tell the client another client quit with an error.
729 * @param client_id The client that quit.
730 * @param errorno The reason the client quit.
732 NetworkRecvStatus ServerNetworkGameSocketHandler::SendErrorQuit(ClientID client_id, NetworkErrorCode errorno)
734 Debug(net, 9, "client[{}] SendErrorQuit(): client_id={}, errorno={}", this->client_id, client_id, errorno);
736 auto p = std::make_unique<Packet>(this, PACKET_SERVER_ERROR_QUIT);
738 p->Send_uint32(client_id);
739 p->Send_uint8 (errorno);
741 this->SendPacket(std::move(p));
742 return NETWORK_RECV_STATUS_OKAY;
746 * Tell the client another client quit.
747 * @param client_id The client that quit.
749 NetworkRecvStatus ServerNetworkGameSocketHandler::SendQuit(ClientID client_id)
751 Debug(net, 9, "client[{}] SendQuit(): client_id={}", this->client_id, client_id);
753 auto p = std::make_unique<Packet>(this, PACKET_SERVER_QUIT);
755 p->Send_uint32(client_id);
757 this->SendPacket(std::move(p));
758 return NETWORK_RECV_STATUS_OKAY;
761 /** Tell the client we're shutting down. */
762 NetworkRecvStatus ServerNetworkGameSocketHandler::SendShutdown()
764 Debug(net, 9, "client[{}] SendShutdown()", this->client_id);
766 auto p = std::make_unique<Packet>(this, PACKET_SERVER_SHUTDOWN);
767 this->SendPacket(std::move(p));
768 return NETWORK_RECV_STATUS_OKAY;
771 /** Tell the client we're starting a new game. */
772 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGame()
774 Debug(net, 9, "client[{}] SendNewGame()", this->client_id);
776 auto p = std::make_unique<Packet>(this, PACKET_SERVER_NEWGAME);
777 this->SendPacket(std::move(p));
778 return NETWORK_RECV_STATUS_OKAY;
782 * Send the result of a console action.
783 * @param colour The colour of the result.
784 * @param command The command that was executed.
786 NetworkRecvStatus ServerNetworkGameSocketHandler::SendRConResult(uint16_t colour, const std::string &command)
788 Debug(net, 9, "client[{}] SendRConResult()", this->client_id);
790 auto p = std::make_unique<Packet>(this, PACKET_SERVER_RCON);
792 p->Send_uint16(colour);
793 p->Send_string(command);
794 this->SendPacket(std::move(p));
795 return NETWORK_RECV_STATUS_OKAY;
799 * Tell that a client moved to another company.
800 * @param client_id The client that moved.
801 * @param company_id The company the client moved to.
803 NetworkRecvStatus ServerNetworkGameSocketHandler::SendMove(ClientID client_id, CompanyID company_id)
805 Debug(net, 9, "client[{}] SendMove(): client_id={}", this->client_id, client_id);
807 auto p = std::make_unique<Packet>(this, PACKET_SERVER_MOVE);
809 p->Send_uint32(client_id);
810 p->Send_uint8(company_id);
811 this->SendPacket(std::move(p));
812 return NETWORK_RECV_STATUS_OKAY;
815 /** Send an update about the max company/spectator counts. */
816 NetworkRecvStatus ServerNetworkGameSocketHandler::SendConfigUpdate()
818 Debug(net, 9, "client[{}] SendConfigUpdate()", this->client_id);
820 auto p = std::make_unique<Packet>(this, PACKET_SERVER_CONFIG_UPDATE);
822 p->Send_uint8(_settings_client.network.max_companies);
823 p->Send_string(_settings_client.network.server_name);
824 this->SendPacket(std::move(p));
825 return NETWORK_RECV_STATUS_OKAY;
828 /***********
829 * Receiving functions
830 ************/
832 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GAME_INFO(Packet &)
834 Debug(net, 9, "client[{}] Receive_CLIENT_GAME_INFO()", this->client_id);
836 return this->SendGameInfo();
839 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_NEWGRFS_CHECKED(Packet &)
841 if (this->status != STATUS_NEWGRFS_CHECK) {
842 /* Illegal call, return error and ignore the packet */
843 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
846 Debug(net, 9, "client[{}] Receive_CLIENT_NEWGRFS_CHECKED()", this->client_id);
848 return this->SendWelcome();
851 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet &p)
853 if (this->status != STATUS_INACTIVE) {
854 /* Illegal call, return error and ignore the packet */
855 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
858 if (_network_game_info.clients_on >= _settings_client.network.max_clients) {
859 /* Turns out we are full. Inform the user about this. */
860 return this->SendError(NETWORK_ERROR_FULL);
863 std::string client_revision = p.Recv_string(NETWORK_REVISION_LENGTH);
864 uint32_t newgrf_version = p.Recv_uint32();
866 Debug(net, 9, "client[{}] Receive_CLIENT_JOIN(): client_revision={}, newgrf_version={}", this->client_id, client_revision, newgrf_version);
868 /* Check if the client has revision control enabled */
869 if (!IsNetworkCompatibleVersion(client_revision) || _openttd_newgrf_version != newgrf_version) {
870 /* Different revisions!! */
871 return this->SendError(NETWORK_ERROR_WRONG_REVISION);
874 return this->SendAuthRequest();
877 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_IDENTIFY(Packet &p)
879 if (this->status != STATUS_IDENTIFY) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
881 Debug(net, 9, "client[{}] Receive_CLIENT_IDENTIFY()", this->client_id);
883 std::string client_name = p.Recv_string(NETWORK_CLIENT_NAME_LENGTH);
884 CompanyID playas = (Owner)p.Recv_uint8();
886 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT;
888 /* join another company does not affect these values */
889 switch (playas) {
890 case COMPANY_NEW_COMPANY: // New company
891 if (Company::GetNumItems() >= _settings_client.network.max_companies) {
892 return this->SendError(NETWORK_ERROR_FULL);
894 break;
895 case COMPANY_SPECTATOR: // Spectator
896 break;
897 default: // Join another company (companies 1..MAX_COMPANIES (index 0..(MAX_COMPANIES-1)))
898 if (!Company::IsValidHumanID(playas)) {
899 return this->SendError(NETWORK_ERROR_COMPANY_MISMATCH);
902 if (!Company::Get(playas)->allow_list.Contains(this->peer_public_key)) {
903 /* When we're not authorized, just bump us to a spectator. */
904 playas = COMPANY_SPECTATOR;
906 break;
909 if (!NetworkIsValidClientName(client_name)) {
910 /* An invalid client name was given. However, the client ensures the name
911 * is valid before it is sent over the network, so something went horribly
912 * wrong. This is probably someone trying to troll us. */
913 return this->SendError(NETWORK_ERROR_INVALID_CLIENT_NAME);
916 if (!NetworkMakeClientNameUnique(client_name)) { // Change name if duplicate
917 /* We could not create a name for this client */
918 return this->SendError(NETWORK_ERROR_NAME_IN_USE);
921 assert(NetworkClientInfo::CanAllocateItem());
922 NetworkClientInfo *ci = new NetworkClientInfo(this->client_id);
923 this->SetInfo(ci);
924 ci->join_date = TimerGameEconomy::date;
925 ci->client_name = client_name;
926 ci->client_playas = playas;
927 ci->public_key = this->peer_public_key;
928 Debug(desync, 1, "client: {:08x}; {:02x}; {:02x}; {:02x}", TimerGameEconomy::date, TimerGameEconomy::date_fract, (int)ci->client_playas, (int)ci->index);
930 /* Make sure companies to which people try to join are not autocleaned */
931 Company *c = Company::GetIfValid(playas);
932 if (c != nullptr) c->months_empty = 0;
934 return this->SendNewGRFCheck();
937 static NetworkErrorCode GetErrorForAuthenticationMethod(NetworkAuthenticationMethod method)
939 switch (method) {
940 case NETWORK_AUTH_METHOD_X25519_PAKE:
941 return NETWORK_ERROR_WRONG_PASSWORD;
942 case NETWORK_AUTH_METHOD_X25519_AUTHORIZED_KEY:
943 return NETWORK_ERROR_NOT_ON_ALLOW_LIST;
945 default:
946 NOT_REACHED();
950 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_AUTH_RESPONSE(Packet &p)
952 if (this->status != STATUS_AUTH_GAME) {
953 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
956 Debug(net, 9, "client[{}] Receive_CLIENT_AUTH_RESPONSE()", this->client_id);
958 auto authentication_method = this->authentication_handler->GetAuthenticationMethod();
959 switch (this->authentication_handler->ReceiveResponse(p)) {
960 case NetworkAuthenticationServerHandler::AUTHENTICATED:
961 break;
963 case NetworkAuthenticationServerHandler::RETRY_NEXT_METHOD:
964 return this->SendAuthRequest();
966 case NetworkAuthenticationServerHandler::NOT_AUTHENTICATED:
967 default:
968 return this->SendError(GetErrorForAuthenticationMethod(authentication_method));
971 NetworkRecvStatus status = this->SendEnableEncryption();
972 if (status != NETWORK_RECV_STATUS_OKAY) return status;
974 this->peer_public_key = this->authentication_handler->GetPeerPublicKey();
975 this->receive_encryption_handler = this->authentication_handler->CreateClientToServerEncryptionHandler();
976 this->send_encryption_handler = this->authentication_handler->CreateServerToClientEncryptionHandler();
977 this->authentication_handler = nullptr;
979 Debug(net, 9, "client[{}] status = IDENTIFY", this->client_id);
980 this->status = STATUS_IDENTIFY;
982 /* Reset 'lag' counters */
983 this->last_frame = this->last_frame_server = _frame_counter;
985 return NETWORK_RECV_STATUS_OKAY;
988 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GETMAP(Packet &)
990 /* The client was never joined.. so this is impossible, right?
991 * Ignore the packet, give the client a warning, and close the connection */
992 if (this->status < STATUS_AUTHORIZED || this->HasClientQuit()) {
993 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
996 Debug(net, 9, "client[{}] Receive_CLIENT_GETMAP()", this->client_id);
998 /* Check if someone else is receiving the map */
999 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
1000 if (new_cs->status == STATUS_MAP) {
1001 /* Tell the new client to wait */
1002 Debug(net, 9, "client[{}] status = MAP_WAIT", this->client_id);
1003 this->status = STATUS_MAP_WAIT;
1004 return this->SendWait();
1008 /* We receive a request to upload the map.. give it to the client! */
1009 return this->SendMap();
1012 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MAP_OK(Packet &)
1014 /* Client has the map, now start syncing */
1015 if (this->status == STATUS_DONE_MAP && !this->HasClientQuit()) {
1016 Debug(net, 9, "client[{}] Receive_CLIENT_MAP_OK()", this->client_id);
1018 std::string client_name = this->GetClientName();
1020 NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, client_name, "", this->client_id);
1021 InvalidateWindowData(WC_CLIENT_LIST, 0);
1023 Debug(net, 3, "[{}] Client #{} ({}) joined as {}", ServerNetworkGameSocketHandler::GetName(), this->client_id, this->GetClientIP(), client_name);
1025 /* Mark the client as pre-active, and wait for an ACK
1026 * so we know it is done loading and in sync with us */
1027 Debug(net, 9, "client[{}] status = PRE_ACTIVE", this->client_id);
1028 this->status = STATUS_PRE_ACTIVE;
1029 NetworkHandleCommandQueue(this);
1030 this->SendFrame();
1031 this->SendSync();
1033 /* This is the frame the client receives
1034 * we need it later on to make sure the client is not too slow */
1035 this->last_frame = _frame_counter;
1036 this->last_frame_server = _frame_counter;
1038 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
1039 if (new_cs->status >= STATUS_AUTHORIZED) {
1040 new_cs->SendClientInfo(this->GetInfo());
1041 new_cs->SendJoin(this->client_id);
1045 NetworkAdminClientInfo(this, true);
1047 /* also update the new client with our max values */
1048 return this->SendConfigUpdate();
1051 /* Wrong status for this packet, give a warning to client, and close connection */
1052 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1056 * The client has done a command and wants us to handle it
1057 * @param p the packet in which the command was sent
1059 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMMAND(Packet &p)
1061 /* The client was never joined.. so this is impossible, right?
1062 * Ignore the packet, give the client a warning, and close the connection */
1063 if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
1064 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1067 if (this->incoming_queue.size() >= _settings_client.network.max_commands_in_queue) {
1068 return this->SendError(NETWORK_ERROR_TOO_MANY_COMMANDS);
1071 Debug(net, 9, "client[{}] Receive_CLIENT_COMMAND()", this->client_id);
1073 CommandPacket cp;
1074 const char *err = this->ReceiveCommand(p, cp);
1076 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT;
1078 NetworkClientInfo *ci = this->GetInfo();
1080 if (err != nullptr) {
1081 IConsolePrint(CC_WARNING, "Dropping client #{} (IP: {}) due to {}.", ci->client_id, this->GetClientIP(), err);
1082 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1086 if ((GetCommandFlags(cp.cmd) & CMD_SERVER) && ci->client_id != CLIENT_ID_SERVER) {
1087 IConsolePrint(CC_WARNING, "Kicking client #{} (IP: {}) due to calling a server only command {}.", ci->client_id, this->GetClientIP(), cp.cmd);
1088 return this->SendError(NETWORK_ERROR_KICKED);
1091 if ((GetCommandFlags(cp.cmd) & CMD_SPECTATOR) == 0 && !Company::IsValidID(cp.company) && ci->client_id != CLIENT_ID_SERVER) {
1092 IConsolePrint(CC_WARNING, "Kicking client #{} (IP: {}) due to calling a non-spectator command {}.", ci->client_id, this->GetClientIP(), cp.cmd);
1093 return this->SendError(NETWORK_ERROR_KICKED);
1097 * Only CMD_COMPANY_CTRL is always allowed, for the rest, playas needs
1098 * to match the company in the packet. If it doesn't, the client has done
1099 * something pretty naughty (or a bug), and will be kicked
1101 CompanyCtrlAction cca = cp.cmd == CMD_COMPANY_CTRL ? std::get<0>(EndianBufferReader::ToValue<CommandTraits<CMD_COMPANY_CTRL>::Args>(cp.data)) : CCA_NEW;
1102 if (!(cp.cmd == CMD_COMPANY_CTRL && cca == CCA_NEW && ci->client_playas == COMPANY_NEW_COMPANY) && ci->client_playas != cp.company) {
1103 IConsolePrint(CC_WARNING, "Kicking client #{} (IP: {}) due to calling a command as another company {}.",
1104 ci->client_playas + 1, this->GetClientIP(), cp.company + 1);
1105 return this->SendError(NETWORK_ERROR_COMPANY_MISMATCH);
1108 if (cp.cmd == CMD_COMPANY_CTRL) {
1109 if (cca != CCA_NEW || cp.company != COMPANY_SPECTATOR) {
1110 return this->SendError(NETWORK_ERROR_CHEATER);
1113 /* 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! */
1114 if (Company::GetNumItems() >= _settings_client.network.max_companies) {
1115 NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_CLIENT, ci->client_id, "cannot create new company, server full", CLIENT_ID_SERVER);
1116 return NETWORK_RECV_STATUS_OKAY;
1120 if (cp.cmd == CMD_COMPANY_ALLOW_LIST_CTRL) {
1121 /* Maybe the client just got moved before allowing? */
1122 if (ci->client_id != CLIENT_ID_SERVER && ci->client_playas != cp.company) return NETWORK_RECV_STATUS_OKAY;
1124 /* Only allow clients to add/remove currently joined clients. The server owner does not go via this method, so is allowed to do more. */
1125 std::string public_key = std::get<1>(EndianBufferReader::ToValue<CommandTraits<CMD_COMPANY_ALLOW_LIST_CTRL>::Args>(cp.data));
1126 bool found = false;
1127 for (const NetworkClientInfo *info : NetworkClientInfo::Iterate()) {
1128 if (info->public_key == public_key) {
1129 found = true;
1130 break;
1134 /* Maybe the client just left? */
1135 if (!found) return NETWORK_RECV_STATUS_OKAY;
1138 if (GetCommandFlags(cp.cmd) & CMD_CLIENT_ID) NetworkReplaceCommandClientId(cp, this->client_id);
1140 this->incoming_queue.push_back(cp);
1141 return NETWORK_RECV_STATUS_OKAY;
1144 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ERROR(Packet &p)
1146 /* This packets means a client noticed an error and is reporting this
1147 * to us. Display the error and report it to the other clients */
1148 NetworkErrorCode errorno = (NetworkErrorCode)p.Recv_uint8();
1150 Debug(net, 9, "client[{}] Receive_CLIENT_ERROR(): errorno={}", this->client_id, errorno);
1152 /* The client was never joined.. thank the client for the packet, but ignore it */
1153 if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
1154 return this->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT);
1157 std::string client_name = this->GetClientName();
1158 StringID strid = GetNetworkErrorMsg(errorno);
1160 Debug(net, 1, "'{}' reported an error and is closing its connection: {}", client_name, GetString(strid));
1162 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, "", strid);
1164 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
1165 if (new_cs->status >= STATUS_AUTHORIZED) {
1166 new_cs->SendErrorQuit(this->client_id, errorno);
1170 NetworkAdminClientError(this->client_id, errorno);
1172 return this->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT);
1175 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_QUIT(Packet &)
1177 /* The client was never joined.. thank the client for the packet, but ignore it */
1178 if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
1179 return this->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT);
1182 Debug(net, 9, "client[{}] Receive_CLIENT_QUIT()", this->client_id);
1184 /* The client wants to leave. Display this and report it to the other clients. */
1185 std::string client_name = this->GetClientName();
1186 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, "", STR_NETWORK_MESSAGE_CLIENT_LEAVING);
1188 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
1189 if (new_cs->status >= STATUS_AUTHORIZED && new_cs != this) {
1190 new_cs->SendQuit(this->client_id);
1194 NetworkAdminClientQuit(this->client_id);
1196 return this->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT);
1199 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ACK(Packet &p)
1201 if (this->status < STATUS_AUTHORIZED) {
1202 /* Illegal call, return error and ignore the packet */
1203 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
1206 uint32_t frame = p.Recv_uint32();
1208 Debug(net, 9, "client[{}] Receive_CLIENT_ACK(): frame={}", this->client_id, frame);
1210 /* The client is trying to catch up with the server */
1211 if (this->status == STATUS_PRE_ACTIVE) {
1212 /* The client is not yet caught up? */
1213 if (frame + Ticks::DAY_TICKS < _frame_counter) return NETWORK_RECV_STATUS_OKAY;
1215 /* Now it is! Unpause the game */
1216 Debug(net, 9, "client[{}] status = ACTIVE", this->client_id);
1217 this->status = STATUS_ACTIVE;
1218 this->last_token_frame = _frame_counter;
1220 /* Execute script for, e.g. MOTD */
1221 IConsoleCmdExec("exec scripts/on_server_connect.scr 0");
1224 /* Get, and validate the token. */
1225 uint8_t token = p.Recv_uint8();
1226 if (token == this->last_token) {
1227 /* We differentiate between last_token_frame and last_frame so the lag
1228 * test uses the actual lag of the client instead of the lag for getting
1229 * the token back and forth; after all, the token is only sent every
1230 * time we receive a PACKET_CLIENT_ACK, after which we will send a new
1231 * token to the client. If the lag would be one day, then we would not
1232 * be sending the new token soon enough for the new daily scheduled
1233 * PACKET_CLIENT_ACK. This would then register the lag of the client as
1234 * two days, even when it's only a single day. */
1235 this->last_token_frame = _frame_counter;
1236 /* Request a new token. */
1237 this->last_token = 0;
1240 /* The client received the frame, make note of it */
1241 this->last_frame = frame;
1242 /* With those 2 values we can calculate the lag realtime */
1243 this->last_frame_server = _frame_counter;
1244 return NETWORK_RECV_STATUS_OKAY;
1249 * Send an actual chat message.
1250 * @param action The action that's performed.
1251 * @param desttype The type of destination.
1252 * @param dest The actual destination index.
1253 * @param msg The actual message.
1254 * @param from_id The origin of the message.
1255 * @param data Arbitrary data.
1256 * @param from_admin Whether the origin is an admin or not.
1258 void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, const std::string &msg, ClientID from_id, int64_t data, bool from_admin)
1260 const NetworkClientInfo *ci, *ci_own, *ci_to;
1262 switch (desttype) {
1263 case DESTTYPE_CLIENT:
1264 /* Are we sending to the server? */
1265 if ((ClientID)dest == CLIENT_ID_SERVER) {
1266 ci = NetworkClientInfo::GetByClientID(from_id);
1267 /* Display the text locally, and that is it */
1268 if (ci != nullptr) {
1269 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
1271 if (_settings_client.network.server_admin_chat) {
1272 NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
1275 } else {
1276 /* Else find the client to send the message to */
1277 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1278 if (cs->client_id == (ClientID)dest && cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) {
1279 cs->SendChat(action, from_id, false, msg, data);
1280 break;
1285 /* Display the message locally (so you know you have sent it) */
1286 if (from_id != (ClientID)dest) {
1287 if (from_id == CLIENT_ID_SERVER) {
1288 ci = NetworkClientInfo::GetByClientID(from_id);
1289 ci_to = NetworkClientInfo::GetByClientID((ClientID)dest);
1290 if (ci != nullptr && ci_to != nullptr) {
1291 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), true, ci_to->client_name, msg, data);
1293 } else {
1294 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1295 if (cs->client_id == from_id && cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) {
1296 cs->SendChat(action, (ClientID)dest, true, msg, data);
1297 break;
1302 break;
1303 case DESTTYPE_TEAM: {
1304 /* If this is false, the message is already displayed on the client who sent it. */
1305 bool show_local = true;
1306 /* Find all clients that belong to this company */
1307 ci_to = nullptr;
1308 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1309 ci = cs->GetInfo();
1310 if (ci != nullptr && ci->client_playas == (CompanyID)dest && cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) {
1311 cs->SendChat(action, from_id, false, msg, data);
1312 if (cs->client_id == from_id) show_local = false;
1313 ci_to = ci; // Remember a client that is in the company for company-name
1317 /* if the server can read it, let the admin network read it, too. */
1318 if (_local_company == (CompanyID)dest && _settings_client.network.server_admin_chat) {
1319 NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
1322 ci = NetworkClientInfo::GetByClientID(from_id);
1323 ci_own = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
1324 if (ci != nullptr && ci_own != nullptr && ci_own->client_playas == dest) {
1325 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
1326 if (from_id == CLIENT_ID_SERVER) show_local = false;
1327 ci_to = ci_own;
1330 /* There is no such client */
1331 if (ci_to == nullptr) break;
1333 /* Display the message locally (so you know you have sent it) */
1334 if (ci != nullptr && show_local) {
1335 if (from_id == CLIENT_ID_SERVER) {
1336 StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
1337 SetDParam(0, ci_to->client_playas);
1338 std::string name = GetString(str);
1339 NetworkTextMessage(action, GetDrawStringCompanyColour(ci_own->client_playas), true, name, msg, data);
1340 } else {
1341 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1342 if (cs->client_id == from_id && cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) {
1343 cs->SendChat(action, ci_to->client_id, true, msg, data);
1348 break;
1350 default:
1351 Debug(net, 1, "Received unknown chat destination type {}; doing broadcast instead", desttype);
1352 [[fallthrough]];
1354 case DESTTYPE_BROADCAST:
1355 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1356 if (cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) cs->SendChat(action, from_id, false, msg, data);
1359 NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
1361 ci = NetworkClientInfo::GetByClientID(from_id);
1362 if (ci != nullptr) {
1363 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data, "");
1365 break;
1370 * Send a chat message from external source.
1371 * @param source Name of the source this message came from.
1372 * @param colour TextColour to use for the message.
1373 * @param user Name of the user who sent the messsage.
1374 * @param msg The actual message.
1376 void NetworkServerSendExternalChat(const std::string &source, TextColour colour, const std::string &user, const std::string &msg)
1378 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1379 if (cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) cs->SendExternalChat(source, colour, user, msg);
1381 NetworkTextMessage(NETWORK_ACTION_EXTERNAL_CHAT, colour, false, user, msg, 0, source);
1384 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_CHAT(Packet &p)
1386 if (this->status < STATUS_PRE_ACTIVE) {
1387 /* Illegal call, return error and ignore the packet */
1388 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
1391 NetworkAction action = (NetworkAction)p.Recv_uint8();
1392 DestType desttype = (DestType)p.Recv_uint8();
1393 int dest = p.Recv_uint32();
1395 Debug(net, 9, "client[{}] Receive_CLIENT_CHAT(): action={}, desttype={}, dest={}", this->client_id, action, desttype, dest);
1397 std::string msg = p.Recv_string(NETWORK_CHAT_LENGTH);
1398 int64_t data = p.Recv_uint64();
1400 NetworkClientInfo *ci = this->GetInfo();
1401 switch (action) {
1402 case NETWORK_ACTION_CHAT:
1403 case NETWORK_ACTION_CHAT_CLIENT:
1404 case NETWORK_ACTION_CHAT_COMPANY:
1405 NetworkServerSendChat(action, desttype, dest, msg, this->client_id, data);
1406 break;
1407 default:
1408 IConsolePrint(CC_WARNING, "Kicking client #{} (IP: {}) due to unknown chact action.", ci->client_id, this->GetClientIP());
1409 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1411 return NETWORK_RECV_STATUS_OKAY;
1414 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_NAME(Packet &p)
1416 if (this->status != STATUS_ACTIVE) {
1417 /* Illegal call, return error and ignore the packet */
1418 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1421 Debug(net, 9, "client[{}] Receive_CLIENT_SET_NAME()", this->client_id);
1423 NetworkClientInfo *ci;
1425 std::string client_name = p.Recv_string(NETWORK_CLIENT_NAME_LENGTH);
1426 ci = this->GetInfo();
1428 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT;
1430 if (ci != nullptr) {
1431 if (!NetworkIsValidClientName(client_name)) {
1432 /* An invalid client name was given. However, the client ensures the name
1433 * is valid before it is sent over the network, so something went horribly
1434 * wrong. This is probably someone trying to troll us. */
1435 return this->SendError(NETWORK_ERROR_INVALID_CLIENT_NAME);
1438 /* Display change */
1439 if (NetworkMakeClientNameUnique(client_name)) {
1440 NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, client_name);
1441 ci->client_name = client_name;
1442 NetworkUpdateClientInfo(ci->client_id);
1445 return NETWORK_RECV_STATUS_OKAY;
1448 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_RCON(Packet &p)
1450 if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1452 Debug(net, 9, "client[{}] Receive_CLIENT_RCON()", this->client_id);
1454 std::string password = p.Recv_string(NETWORK_PASSWORD_LENGTH);
1455 std::string command = p.Recv_string(NETWORK_RCONCOMMAND_LENGTH);
1457 if (_rcon_authorized_key_handler.IsAllowed(this->peer_public_key)) {
1458 /* We are allowed, nothing more to validate. */
1459 } else if (_settings_client.network.rcon_password.empty()) {
1460 return NETWORK_RECV_STATUS_OKAY;
1461 } else if (_settings_client.network.rcon_password.compare(password) != 0) {
1462 Debug(net, 1, "[rcon] Wrong password from client-id {}", this->client_id);
1463 return NETWORK_RECV_STATUS_OKAY;
1466 Debug(net, 3, "[rcon] Client-id {} executed: {}", this->client_id, command);
1468 _redirect_console_to_client = this->client_id;
1469 IConsoleCmdExec(command);
1470 _redirect_console_to_client = INVALID_CLIENT_ID;
1471 return NETWORK_RECV_STATUS_OKAY;
1474 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MOVE(Packet &p)
1476 if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1478 CompanyID company_id = (Owner)p.Recv_uint8();
1480 Debug(net, 9, "client[{}] Receive_CLIENT_MOVE(): company_id={}", this->client_id, company_id);
1482 /* Check if the company is valid, we don't allow moving to AI companies */
1483 if (company_id != COMPANY_SPECTATOR && !Company::IsValidHumanID(company_id)) return NETWORK_RECV_STATUS_OKAY;
1485 if (company_id != COMPANY_SPECTATOR && !Company::Get(company_id)->allow_list.Contains(this->peer_public_key)) {
1486 Debug(net, 2, "Wrong public key from client-id #{} for company #{}", this->client_id, company_id + 1);
1487 return NETWORK_RECV_STATUS_OKAY;
1490 /* if we get here we can move the client */
1491 NetworkServerDoMove(this->client_id, company_id);
1492 return NETWORK_RECV_STATUS_OKAY;
1496 * Populate the company stats.
1497 * @param stats the stats to update
1499 void NetworkPopulateCompanyStats(NetworkCompanyStats *stats)
1501 memset(stats, 0, sizeof(*stats) * MAX_COMPANIES);
1503 /* Go through all vehicles and count the type of vehicles */
1504 for (const Vehicle *v : Vehicle::Iterate()) {
1505 if (!Company::IsValidID(v->owner) || !v->IsPrimaryVehicle()) continue;
1506 uint8_t type = 0;
1507 switch (v->type) {
1508 case VEH_TRAIN: type = NETWORK_VEH_TRAIN; break;
1509 case VEH_ROAD: type = RoadVehicle::From(v)->IsBus() ? NETWORK_VEH_BUS : NETWORK_VEH_LORRY; break;
1510 case VEH_AIRCRAFT: type = NETWORK_VEH_PLANE; break;
1511 case VEH_SHIP: type = NETWORK_VEH_SHIP; break;
1512 default: continue;
1514 stats[v->owner].num_vehicle[type]++;
1517 /* Go through all stations and count the types of stations */
1518 for (const Station *s : Station::Iterate()) {
1519 if (Company::IsValidID(s->owner)) {
1520 NetworkCompanyStats *npi = &stats[s->owner];
1522 if (s->facilities & FACIL_TRAIN) npi->num_station[NETWORK_VEH_TRAIN]++;
1523 if (s->facilities & FACIL_TRUCK_STOP) npi->num_station[NETWORK_VEH_LORRY]++;
1524 if (s->facilities & FACIL_BUS_STOP) npi->num_station[NETWORK_VEH_BUS]++;
1525 if (s->facilities & FACIL_AIRPORT) npi->num_station[NETWORK_VEH_PLANE]++;
1526 if (s->facilities & FACIL_DOCK) npi->num_station[NETWORK_VEH_SHIP]++;
1532 * Send updated client info of a particular client.
1533 * @param client_id The client to send it for.
1535 void NetworkUpdateClientInfo(ClientID client_id)
1537 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1539 if (ci == nullptr) return;
1541 Debug(desync, 1, "client: {:08x}; {:02x}; {:02x}; {:04x}", TimerGameEconomy::date, TimerGameEconomy::date_fract, (int)ci->client_playas, client_id);
1543 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1544 if (cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) {
1545 cs->SendClientInfo(ci);
1549 NetworkAdminClientUpdate(ci);
1553 * Remove companies that have not been used depending on the \c autoclean_companies setting
1554 * and values for \c autoclean_protected, which removes any company, and
1555 * \c autoclean_novehicles, which removes companies without vehicles.
1557 static void NetworkAutoCleanCompanies()
1559 CompanyMask has_clients = 0;
1560 CompanyMask has_vehicles = 0;
1562 if (!_settings_client.network.autoclean_companies) return;
1564 /* Detect the active companies */
1565 for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1566 if (Company::IsValidID(ci->client_playas)) SetBit(has_clients, ci->client_playas);
1569 if (!_network_dedicated) {
1570 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
1571 assert(ci != nullptr);
1572 if (Company::IsValidID(ci->client_playas)) SetBit(has_clients, ci->client_playas);
1575 if (_settings_client.network.autoclean_novehicles != 0) {
1576 for (const Company *c : Company::Iterate()) {
1577 if (std::any_of(std::begin(c->group_all), std::end(c->group_all), [](const GroupStatistics &gs) { return gs.num_vehicle != 0; })) SetBit(has_vehicles, c->index);
1581 /* Go through all the companies */
1582 for (Company *c : Company::Iterate()) {
1583 /* Skip the non-active once */
1584 if (c->is_ai) continue;
1586 if (!HasBit(has_clients, c->index)) {
1587 /* The company is empty for one month more */
1588 if (c->months_empty != std::numeric_limits<decltype(c->months_empty)>::max()) c->months_empty++;
1590 /* Is the company empty for autoclean_protected-months? */
1591 if (_settings_client.network.autoclean_protected != 0 && c->months_empty > _settings_client.network.autoclean_protected) {
1592 /* Shut the company down */
1593 Command<CMD_COMPANY_CTRL>::Post(CCA_DELETE, c->index, CRR_AUTOCLEAN, INVALID_CLIENT_ID);
1594 IConsolePrint(CC_INFO, "Auto-cleaned company #{}.", c->index + 1);
1596 /* Is the company empty for autoclean_novehicles-months, and has no vehicles? */
1597 if (_settings_client.network.autoclean_novehicles != 0 && c->months_empty > _settings_client.network.autoclean_novehicles && !HasBit(has_vehicles, c->index)) {
1598 /* Shut the company down */
1599 Command<CMD_COMPANY_CTRL>::Post(CCA_DELETE, c->index, CRR_AUTOCLEAN, INVALID_CLIENT_ID);
1600 IConsolePrint(CC_INFO, "Auto-cleaned company #{} with no vehicles.", c->index + 1);
1602 } else {
1603 /* It is not empty, reset the date */
1604 c->months_empty = 0;
1610 * Check whether a name is unique, and otherwise try to make it unique.
1611 * @param new_name The name to check/modify.
1612 * @return True if an unique name was achieved.
1614 bool NetworkMakeClientNameUnique(std::string &name)
1616 bool is_name_unique = false;
1617 std::string original_name = name;
1619 for (uint number = 1; !is_name_unique && number <= MAX_CLIENTS; number++) { // Something's really wrong when there're more names than clients
1620 is_name_unique = true;
1621 for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1622 if (ci->client_name == name) {
1623 /* Name already in use */
1624 is_name_unique = false;
1625 break;
1628 /* Check if it is the same as the server-name */
1629 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
1630 if (ci != nullptr) {
1631 if (ci->client_name == name) is_name_unique = false; // name already in use
1634 if (!is_name_unique) {
1635 /* Try a new name (<name> #1, <name> #2, and so on) */
1636 name = original_name + " #" + std::to_string(number);
1638 /* The constructed client name is larger than the limit,
1639 * so... bail out as no valid name can be created. */
1640 if (name.size() >= NETWORK_CLIENT_NAME_LENGTH) return false;
1644 return is_name_unique;
1648 * Change the client name of the given client
1649 * @param client_id the client to change the name of
1650 * @param new_name the new name for the client
1651 * @return true iff the name was changed
1653 bool NetworkServerChangeClientName(ClientID client_id, const std::string &new_name)
1655 /* Check if the name's already in use */
1656 for (NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1657 if (ci->client_name.compare(new_name) == 0) return false;
1660 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1661 if (ci == nullptr) return false;
1663 NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, true, ci->client_name, new_name);
1665 ci->client_name = new_name;
1667 NetworkUpdateClientInfo(client_id);
1668 return true;
1672 * Handle the command-queue of a socket.
1673 * @param cs The socket to handle the queue for.
1675 static void NetworkHandleCommandQueue(NetworkClientSocket *cs)
1677 for (auto &cp : cs->outgoing_queue) cs->SendCommand(cp);
1678 cs->outgoing_queue.clear();
1682 * This is called every tick if this is a _network_server
1683 * @param send_frame Whether to send the frame to the clients.
1685 void NetworkServer_Tick(bool send_frame)
1687 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1688 bool send_sync = false;
1689 #endif
1691 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1692 if (_frame_counter >= _last_sync_frame + _settings_client.network.sync_freq) {
1693 _last_sync_frame = _frame_counter;
1694 send_sync = true;
1696 #endif
1698 /* Now we are done with the frame, inform the clients that they can
1699 * do their frame! */
1700 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1701 /* We allow a number of bytes per frame, but only to the burst amount
1702 * to be available for packet receiving at any particular time. */
1703 cs->receive_limit = std::min<size_t>(cs->receive_limit + _settings_client.network.bytes_per_frame,
1704 _settings_client.network.bytes_per_frame_burst);
1706 /* Check if the speed of the client is what we can expect from a client */
1707 uint lag = NetworkCalculateLag(cs);
1708 switch (cs->status) {
1709 case NetworkClientSocket::STATUS_ACTIVE:
1710 if (lag > _settings_client.network.max_lag_time) {
1711 /* Client did still not report in within the specified limit. */
1713 if (cs->last_packet + std::chrono::milliseconds(lag * MILLISECONDS_PER_TICK) > std::chrono::steady_clock::now()) {
1714 /* A packet was received in the last three game days, so the client is likely lagging behind. */
1715 IConsolePrint(CC_WARNING, "Client #{} (IP: {}) is dropped because the client's game state is more than {} ticks behind.", cs->client_id, cs->GetClientIP(), lag);
1716 } else {
1717 /* No packet was received in the last three game days; sounds like a lost connection. */
1718 IConsolePrint(CC_WARNING, "Client #{} (IP: {}) is dropped because the client did not respond for more than {} ticks.", cs->client_id, cs->GetClientIP(), lag);
1720 cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
1721 continue;
1724 /* Report once per time we detect the lag, and only when we
1725 * received a packet in the last 2 seconds. If we
1726 * did not receive a packet, then the client is not just
1727 * slow, but the connection is likely severed. Mentioning
1728 * frame_freq is not useful in this case. */
1729 if (lag > (uint)Ticks::DAY_TICKS && cs->lag_test == 0 && cs->last_packet + std::chrono::seconds(2) > std::chrono::steady_clock::now()) {
1730 IConsolePrint(CC_WARNING, "[{}] Client #{} is slow, try increasing [network.]frame_freq to a higher value!", _frame_counter, cs->client_id);
1731 cs->lag_test = 1;
1734 if (cs->last_frame_server - cs->last_token_frame >= _settings_client.network.max_lag_time) {
1735 /* This is a bad client! It didn't send the right token back within time. */
1736 IConsolePrint(CC_WARNING, "Client #{} (IP: {}) is dropped because it fails to send valid acks.", cs->client_id, cs->GetClientIP());
1737 cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
1738 continue;
1740 break;
1742 case NetworkClientSocket::STATUS_INACTIVE:
1743 case NetworkClientSocket::STATUS_IDENTIFY:
1744 case NetworkClientSocket::STATUS_NEWGRFS_CHECK:
1745 case NetworkClientSocket::STATUS_AUTHORIZED:
1746 /* NewGRF check and authorized states should be handled almost instantly.
1747 * So give them some lee-way, likewise for the query with inactive. */
1748 if (lag > _settings_client.network.max_init_time) {
1749 IConsolePrint(CC_WARNING, "Client #{} (IP: {}) is dropped because it took longer than {} ticks to start the joining process.", cs->client_id, cs->GetClientIP(), _settings_client.network.max_init_time);
1750 cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
1751 continue;
1753 break;
1755 case NetworkClientSocket::STATUS_MAP_WAIT:
1756 /* Send every two seconds a packet to the client, to make sure
1757 * it knows the server is still there; just someone else is
1758 * still receiving the map. */
1759 if (std::chrono::steady_clock::now() > cs->last_packet + std::chrono::seconds(2)) {
1760 cs->SendWait();
1761 /* We need to reset the timer, as otherwise we will be
1762 * spamming the client. Strictly speaking this variable
1763 * tracks when we last received a packet from the client,
1764 * but as it is waiting, it will not send us any till we
1765 * start sending them data. */
1766 cs->last_packet = std::chrono::steady_clock::now();
1768 break;
1770 case NetworkClientSocket::STATUS_MAP:
1771 /* Downloading the map... this is the amount of time since starting the saving. */
1772 if (lag > _settings_client.network.max_download_time) {
1773 IConsolePrint(CC_WARNING, "Client #{} (IP: {}) is dropped because it took longer than {} ticks to download the map.", cs->client_id, cs->GetClientIP(), _settings_client.network.max_download_time);
1774 cs->SendError(NETWORK_ERROR_TIMEOUT_MAP);
1775 continue;
1777 break;
1779 case NetworkClientSocket::STATUS_DONE_MAP:
1780 case NetworkClientSocket::STATUS_PRE_ACTIVE:
1781 /* The map has been sent, so this is for loading the map and syncing up. */
1782 if (lag > _settings_client.network.max_join_time) {
1783 IConsolePrint(CC_WARNING, "Client #{} (IP: {}) is dropped because it took longer than {} ticks to join.", cs->client_id, cs->GetClientIP(), _settings_client.network.max_join_time);
1784 cs->SendError(NETWORK_ERROR_TIMEOUT_JOIN);
1785 continue;
1787 break;
1789 case NetworkClientSocket::STATUS_AUTH_GAME:
1790 /* These don't block? */
1791 if (lag > _settings_client.network.max_password_time) {
1792 IConsolePrint(CC_WARNING, "Client #{} (IP: {}) is dropped because it took longer than {} ticks to enter the password.", cs->client_id, cs->GetClientIP(), _settings_client.network.max_password_time);
1793 cs->SendError(NETWORK_ERROR_TIMEOUT_PASSWORD);
1794 continue;
1796 break;
1798 case NetworkClientSocket::STATUS_END:
1799 /* Bad server/code. */
1800 NOT_REACHED();
1803 if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) {
1804 /* Check if we can send command, and if we have anything in the queue */
1805 NetworkHandleCommandQueue(cs);
1807 /* Send an updated _frame_counter_max to the client */
1808 if (send_frame) cs->SendFrame();
1810 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1811 /* Send a sync-check packet */
1812 if (send_sync) cs->SendSync();
1813 #endif
1818 /** Helper function to restart the map. */
1819 static void NetworkRestartMap()
1821 _settings_newgame.game_creation.generation_seed = GENERATE_NEW_SEED;
1822 switch (_file_to_saveload.abstract_ftype) {
1823 case FT_SAVEGAME:
1824 case FT_SCENARIO:
1825 _switch_mode = SM_LOAD_GAME;
1826 break;
1828 case FT_HEIGHTMAP:
1829 _switch_mode = SM_START_HEIGHTMAP;
1830 break;
1832 default:
1833 _switch_mode = SM_NEWGAME;
1837 /** Timer to restart a network server automatically based on real-time hours played. Initialized at zero to disable until settings are loaded. */
1838 static IntervalTimer<TimerGameRealtime> _network_restart_map_timer({std::chrono::hours::zero(), TimerGameRealtime::UNPAUSED}, [](auto)
1840 if (!_network_server) return;
1842 /* If setting is 0, this feature is disabled. */
1843 if (_settings_client.network.restart_hours == 0) return;
1845 Debug(net, 3, "Auto-restarting map: {} hours played", _settings_client.network.restart_hours);
1846 NetworkRestartMap();
1850 * Reset the automatic network restart time interval.
1851 * @param reset Whether to reset the timer to zero.
1853 void ChangeNetworkRestartTime(bool reset)
1855 if (!_network_server) return;
1857 _network_restart_map_timer.SetInterval({ std::chrono::hours(_settings_client.network.restart_hours), TimerGameRealtime::UNPAUSED }, reset);
1860 /** Check if we want to restart the map based on the year. */
1861 static void NetworkCheckRestartMapYear()
1863 /* If setting is 0, this feature is disabled. */
1864 if (_settings_client.network.restart_game_year == 0) return;
1866 if (TimerGameCalendar::year >= _settings_client.network.restart_game_year) {
1867 Debug(net, 3, "Auto-restarting map: year {} reached", TimerGameCalendar::year);
1868 NetworkRestartMap();
1872 /** Calendar yearly "callback". Called whenever the calendar year changes. */
1873 static IntervalTimer<TimerGameCalendar> _calendar_network_yearly({ TimerGameCalendar::YEAR, TimerGameCalendar::Priority::NONE }, [](auto) {
1874 if (!_network_server) return;
1876 NetworkCheckRestartMapYear();
1879 /** Economy yearly "callback". Called whenever the economy year changes. */
1880 static IntervalTimer<TimerGameEconomy> _economy_network_yearly({TimerGameEconomy::YEAR, TimerGameEconomy::Priority::NONE}, [](auto)
1882 if (!_network_server) return;
1884 NetworkAdminUpdate(ADMIN_FREQUENCY_ANUALLY);
1887 /** Quarterly "callback". Called whenever the economy quarter changes. */
1888 static IntervalTimer<TimerGameEconomy> _network_quarterly({TimerGameEconomy::QUARTER, TimerGameEconomy::Priority::NONE}, [](auto)
1890 if (!_network_server) return;
1892 NetworkAutoCleanCompanies();
1893 NetworkAdminUpdate(ADMIN_FREQUENCY_QUARTERLY);
1896 /** Economy monthly "callback". Called whenever the economy month changes. */
1897 static IntervalTimer<TimerGameEconomy> _network_monthly({TimerGameEconomy::MONTH, TimerGameEconomy::Priority::NONE}, [](auto)
1899 if (!_network_server) return;
1901 NetworkAutoCleanCompanies();
1902 NetworkAdminUpdate(ADMIN_FREQUENCY_MONTHLY);
1905 /** Economy weekly "callback". Called whenever the economy week changes. */
1906 static IntervalTimer<TimerGameEconomy> _network_weekly({TimerGameEconomy::WEEK, TimerGameEconomy::Priority::NONE}, [](auto)
1908 if (!_network_server) return;
1910 NetworkAdminUpdate(ADMIN_FREQUENCY_WEEKLY);
1913 /** Daily "callback". Called whenever the economy date changes. */
1914 static IntervalTimer<TimerGameEconomy> _economy_network_daily({TimerGameEconomy::DAY, TimerGameEconomy::Priority::NONE}, [](auto)
1916 if (!_network_server) return;
1918 NetworkAdminUpdate(ADMIN_FREQUENCY_DAILY);
1922 * Get the IP address/hostname of the connected client.
1923 * @return The IP address.
1925 const std::string &ServerNetworkGameSocketHandler::GetClientIP()
1927 return this->client_address.GetHostname();
1930 /** Show the status message of all clients on the console. */
1931 void NetworkServerShowStatusToConsole()
1933 static const char * const stat_str[] = {
1934 "inactive",
1935 "authorizing",
1936 "identifing client",
1937 "checking NewGRFs",
1938 "authorized",
1939 "waiting",
1940 "loading map",
1941 "map done",
1942 "ready",
1943 "active"
1945 static_assert(lengthof(stat_str) == NetworkClientSocket::STATUS_END);
1947 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1948 NetworkClientInfo *ci = cs->GetInfo();
1949 if (ci == nullptr) continue;
1950 uint lag = NetworkCalculateLag(cs);
1951 const char *status;
1953 status = (cs->status < (ptrdiff_t)lengthof(stat_str) ? stat_str[cs->status] : "unknown");
1954 IConsolePrint(CC_INFO, "Client #{} name: '{}' status: '{}' frame-lag: {} company: {} IP: {}",
1955 cs->client_id, ci->client_name, status, lag,
1956 ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0),
1957 cs->GetClientIP());
1962 * Send Config Update
1964 void NetworkServerSendConfigUpdate()
1966 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1967 if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) cs->SendConfigUpdate();
1971 /** Update the server's NetworkServerGameInfo due to changes in settings. */
1972 void NetworkServerUpdateGameInfo()
1974 if (_network_server) FillStaticNetworkServerGameInfo();
1978 * Handle the tid-bits of moving a client from one company to another.
1979 * @param client_id id of the client we want to move.
1980 * @param company_id id of the company we want to move the client to.
1981 * @return void
1983 void NetworkServerDoMove(ClientID client_id, CompanyID company_id)
1985 /* Only allow non-dedicated servers and normal clients to be moved */
1986 if (client_id == CLIENT_ID_SERVER && _network_dedicated) return;
1988 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1989 assert(ci != nullptr);
1991 /* No need to waste network resources if the client is in the company already! */
1992 if (ci->client_playas == company_id) return;
1994 ci->client_playas = company_id;
1996 if (client_id == CLIENT_ID_SERVER) {
1997 SetLocalCompany(company_id);
1998 } else {
1999 NetworkClientSocket *cs = NetworkClientSocket::GetByClientID(client_id);
2000 /* When the company isn't authorized we can't move them yet. */
2001 if (cs->status < NetworkClientSocket::STATUS_AUTHORIZED) return;
2002 cs->SendMove(client_id, company_id);
2005 /* announce the client's move */
2006 NetworkUpdateClientInfo(client_id);
2008 NetworkAction action = (company_id == COMPANY_SPECTATOR) ? NETWORK_ACTION_COMPANY_SPECTATOR : NETWORK_ACTION_COMPANY_JOIN;
2009 NetworkServerSendChat(action, DESTTYPE_BROADCAST, 0, "", client_id, company_id + 1);
2011 InvalidateWindowData(WC_CLIENT_LIST, 0);
2015 * Send an rcon reply to the client.
2016 * @param client_id The identifier of the client.
2017 * @param colour_code The colour of the text.
2018 * @param string The actual reply.
2020 void NetworkServerSendRcon(ClientID client_id, TextColour colour_code, const std::string &string)
2022 NetworkClientSocket::GetByClientID(client_id)->SendRConResult(colour_code, string);
2026 * Kick a single client.
2027 * @param client_id The client to kick.
2028 * @param reason In case of kicking a client, specifies the reason for kicking the client.
2030 void NetworkServerKickClient(ClientID client_id, const std::string &reason)
2032 if (client_id == CLIENT_ID_SERVER) return;
2033 NetworkClientSocket::GetByClientID(client_id)->SendError(NETWORK_ERROR_KICKED, reason);
2037 * Ban, or kick, everyone joined from the given client's IP.
2038 * @param client_id The client to check for.
2039 * @param ban Whether to ban or kick.
2040 * @param reason In case of kicking a client, specifies the reason for kicking the client.
2042 uint NetworkServerKickOrBanIP(ClientID client_id, bool ban, const std::string &reason)
2044 return NetworkServerKickOrBanIP(NetworkClientSocket::GetByClientID(client_id)->GetClientIP(), ban, reason);
2048 * Kick or ban someone based on an IP address.
2049 * @param ip The IP address/range to ban/kick.
2050 * @param ban Whether to ban or just kick.
2051 * @param reason In case of kicking a client, specifies the reason for kicking the client.
2053 uint NetworkServerKickOrBanIP(const std::string &ip, bool ban, const std::string &reason)
2055 /* Add address to ban-list */
2056 if (ban) {
2057 bool contains = false;
2058 for (const auto &iter : _network_ban_list) {
2059 if (iter == ip) {
2060 contains = true;
2061 break;
2064 if (!contains) _network_ban_list.emplace_back(ip);
2067 uint n = 0;
2069 /* There can be multiple clients with the same IP, kick them all but don't kill the server,
2070 * or the client doing the rcon. The latter can't be kicked because kicking frees closes
2071 * and subsequently free the connection related instances, which we would be reading from
2072 * and writing to after returning. So we would read or write data from freed memory up till
2073 * the segfault triggers. */
2074 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
2075 if (cs->client_id == CLIENT_ID_SERVER) continue;
2076 if (cs->client_id == _redirect_console_to_client) continue;
2077 if (cs->client_address.IsInNetmask(ip)) {
2078 NetworkServerKickClient(cs->client_id, reason);
2079 n++;
2083 return n;
2087 * Check whether a particular company has clients.
2088 * @param company The company to check.
2089 * @return True if at least one client is joined to the company.
2091 bool NetworkCompanyHasClients(CompanyID company)
2093 for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
2094 if (ci->client_playas == company) return true;
2096 return false;
2101 * Get the name of the client, if the user did not send it yet, Client ID is used.
2102 * @param client_name The variable to write the name to.
2103 * @param last The pointer to the last element of the destination buffer
2105 std::string ServerNetworkGameSocketHandler::GetClientName() const
2107 const NetworkClientInfo *ci = this->GetInfo();
2108 if (ci != nullptr && !ci->client_name.empty()) return ci->client_name;
2110 return fmt::format("Client #{}", this->client_id);
2114 * Print all the clients to the console
2116 void NetworkPrintClients()
2118 for (NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
2119 if (_network_server) {
2120 IConsolePrint(CC_INFO, "Client #{} name: '{}' company: {} IP: {}",
2121 ci->client_id,
2122 ci->client_name,
2123 ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0),
2124 ci->client_id == CLIENT_ID_SERVER ? "server" : NetworkClientSocket::GetByClientID(ci->client_id)->GetClientIP());
2125 } else {
2126 IConsolePrint(CC_INFO, "Client #{} name: '{}' company: {}",
2127 ci->client_id,
2128 ci->client_name,
2129 ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0));
2135 * Get the public key of the client with the given id.
2136 * @param client_id The id of the client.
2137 * @return View of the public key, which is empty when the client does not exist.
2139 std::string_view NetworkGetPublicKeyOfClient(ClientID client_id)
2141 auto socket = NetworkClientSocket::GetByClientID(client_id);
2142 return socket == nullptr ? "" : socket->GetPeerPublicKey();
2147 * Perform all the server specific administration of a new company.
2148 * @param c The newly created company; can't be nullptr.
2149 * @param ci The client information of the client that made the company; can be nullptr.
2151 void NetworkServerNewCompany(const Company *c, NetworkClientInfo *ci)
2153 assert(c != nullptr);
2155 if (!_network_server) return;
2157 if (ci != nullptr) {
2158 /* ci is nullptr when replaying, or for AIs. In neither case there is a client. */
2159 ci->client_playas = c->index;
2160 NetworkUpdateClientInfo(ci->client_id);
2163 * This function is called from a command, but is only called for the server.
2164 * The client information is managed out-of-band from the commands, so to not have a
2165 * different state/president/company name in the different clients, we need to
2166 * circumvent the normal ::Post logic and go directly to sending the command.
2168 Command<CMD_COMPANY_ALLOW_LIST_CTRL>::SendNet(STR_NULL, c->index, CALCA_ADD, ci->public_key);
2169 Command<CMD_RENAME_PRESIDENT>::SendNet(STR_NULL, c->index, ci->client_name);
2171 NetworkServerSendChat(NETWORK_ACTION_COMPANY_NEW, DESTTYPE_BROADCAST, 0, "", ci->client_id, c->index + 1);