Fix #8316: Make sort industries by production and transported with a cargo filter...
[openttd-github.git] / src / network / network_server.cpp
blobe4e1de906b8e489edd66727d0c8207beb28ce60d
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 "../date_func.h"
13 #include "core/game_info.h"
14 #include "network_admin.h"
15 #include "network_server.h"
16 #include "network_udp.h"
17 #include "network_base.h"
18 #include "../console_func.h"
19 #include "../company_base.h"
20 #include "../command_func.h"
21 #include "../saveload/saveload.h"
22 #include "../saveload/saveload_filter.h"
23 #include "../station_base.h"
24 #include "../genworld.h"
25 #include "../company_func.h"
26 #include "../company_gui.h"
27 #include "../roadveh.h"
28 #include "../order_backup.h"
29 #include "../core/pool_func.hpp"
30 #include "../core/random_func.hpp"
31 #include "../rev.h"
32 #include <mutex>
33 #include <condition_variable>
35 #include "../safeguards.h"
38 /* This file handles all the server-commands */
40 DECLARE_POSTFIX_INCREMENT(ClientID)
41 /** The identifier counter for new clients (is never decreased) */
42 static ClientID _network_client_id = CLIENT_ID_FIRST;
44 /** Make very sure the preconditions given in network_type.h are actually followed */
45 static_assert(MAX_CLIENT_SLOTS > MAX_CLIENTS);
46 /** Yes... */
47 static_assert(NetworkClientSocketPool::MAX_SIZE == MAX_CLIENT_SLOTS);
49 /** The pool with clients. */
50 NetworkClientSocketPool _networkclientsocket_pool("NetworkClientSocket");
51 INSTANTIATE_POOL_METHODS(NetworkClientSocket)
53 /** Instantiate the listen sockets. */
54 template SocketList TCPListenHandler<ServerNetworkGameSocketHandler, PACKET_SERVER_FULL, PACKET_SERVER_BANNED>::sockets;
56 /** Writing a savegame directly to a number of packets. */
57 struct PacketWriter : SaveFilter {
58 ServerNetworkGameSocketHandler *cs; ///< Socket we are associated with.
59 Packet *current; ///< The packet we're currently writing to.
60 size_t total_size; ///< Total size of the compressed savegame.
61 Packet *packets; ///< Packet queue of the savegame; send these "slowly" to the client.
62 std::mutex mutex; ///< Mutex for making threaded saving safe.
63 std::condition_variable exit_sig; ///< Signal for threaded destruction of this packet writer.
65 /**
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)
73 /** Make sure everything is cleaned up. */
74 ~PacketWriter()
76 std::unique_lock<std::mutex> lock(this->mutex);
78 if (this->cs != nullptr) this->exit_sig.wait(lock);
80 /* This must all wait until the Destroy function is called. */
82 while (this->packets != nullptr) {
83 delete Packet::PopFromQueue(&this->packets);
86 delete this->current;
89 /**
90 * Begin the destruction of this packet writer. It can happen in two ways:
91 * in the first case the client disconnected while saving the map. In this
92 * case the saving has not finished and killed this PacketWriter. In that
93 * case we simply set cs to nullptr, triggering the appending to fail due to
94 * the connection problem and eventually triggering the destructor. In the
95 * second case the destructor is already called, and it is waiting for our
96 * signal which we will send. Only then the packets will be removed by the
97 * destructor.
99 void Destroy()
101 std::unique_lock<std::mutex> lock(this->mutex);
103 this->cs = nullptr;
105 this->exit_sig.notify_all();
106 lock.unlock();
108 /* Make sure the saving is completely cancelled. Yes,
109 * we need to handle the save finish as well as the
110 * next connection might just be requesting a map. */
111 WaitTillSaved();
112 ProcessAsyncSaveFinish();
116 * Transfer all packets from here to the network's queue while holding
117 * the lock on our mutex.
118 * @param socket The network socket to write to.
119 * @return True iff the last packet of the map has been sent.
121 bool TransferToNetworkQueue(ServerNetworkGameSocketHandler *socket)
123 /* Unsafe check for the queue being empty or not. */
124 if (this->packets == nullptr) return false;
126 std::lock_guard<std::mutex> lock(this->mutex);
128 while (this->packets != nullptr) {
129 Packet *p = Packet::PopFromQueue(&this->packets);
130 bool last_packet = p->GetPacketType() == PACKET_SERVER_MAP_DONE;
131 socket->SendPacket(p);
133 if (last_packet) return true;
136 return false;
139 /** Append the current packet to the queue. */
140 void AppendQueue()
142 if (this->current == nullptr) return;
144 Packet::AddToQueue(&this->packets, this->current);
145 this->current = nullptr;
148 /** Prepend the current packet to the queue. */
149 void PrependQueue()
151 if (this->current == nullptr) return;
153 /* Reversed from AppendQueue so the queue gets added to the current one. */
154 Packet::AddToQueue(&this->current, this->packets);
155 this->packets = this->current;
156 this->current = nullptr;
159 void Write(byte *buf, size_t size) override
161 /* We want to abort the saving when the socket is closed. */
162 if (this->cs == nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
164 if (this->current == nullptr) this->current = new Packet(PACKET_SERVER_MAP_DATA, TCP_MTU);
166 std::lock_guard<std::mutex> lock(this->mutex);
168 byte *bufe = buf + size;
169 while (buf != bufe) {
170 size_t written = this->current->Send_bytes(buf, bufe);
171 buf += written;
173 if (!this->current->CanWriteToPacket(1)) {
174 this->AppendQueue();
175 if (buf != bufe) this->current = new Packet(PACKET_SERVER_MAP_DATA, TCP_MTU);
179 this->total_size += size;
182 void Finish() override
184 /* We want to abort the saving when the socket is closed. */
185 if (this->cs == nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
187 std::lock_guard<std::mutex> lock(this->mutex);
189 /* Make sure the last packet is flushed. */
190 this->AppendQueue();
192 /* Add a packet stating that this is the end to the queue. */
193 this->current = new Packet(PACKET_SERVER_MAP_DONE);
194 this->AppendQueue();
196 /* Fast-track the size to the client. */
197 this->current = new Packet(PACKET_SERVER_MAP_SIZE);
198 this->current->Send_uint32((uint32)this->total_size);
199 this->PrependQueue();
205 * Create a new socket for the server side of the game connection.
206 * @param s The socket to connect with.
208 ServerNetworkGameSocketHandler::ServerNetworkGameSocketHandler(SOCKET s) : NetworkGameSocketHandler(s)
210 this->status = STATUS_INACTIVE;
211 this->client_id = _network_client_id++;
212 this->receive_limit = _settings_client.network.bytes_per_frame_burst;
214 /* The Socket and Info pools need to be the same in size. After all,
215 * each Socket will be associated with at most one Info object. As
216 * such if the Socket was allocated the Info object can as well. */
217 static_assert(NetworkClientSocketPool::MAX_SIZE == NetworkClientInfoPool::MAX_SIZE);
221 * Clear everything related to this client.
223 ServerNetworkGameSocketHandler::~ServerNetworkGameSocketHandler()
225 if (_redirect_console_to_client == this->client_id) _redirect_console_to_client = INVALID_CLIENT_ID;
226 OrderBackup::ResetUser(this->client_id);
228 if (this->savegame != nullptr) {
229 this->savegame->Destroy();
230 this->savegame = nullptr;
234 Packet *ServerNetworkGameSocketHandler::ReceivePacket()
236 /* Only allow receiving when we have some buffer free; this value
237 * can go negative, but eventually it will become positive again. */
238 if (this->receive_limit <= 0) return nullptr;
240 /* We can receive a packet, so try that and if needed account for
241 * the amount of received data. */
242 Packet *p = this->NetworkTCPSocketHandler::ReceivePacket();
243 if (p != nullptr) this->receive_limit -= p->Size();
244 return p;
247 NetworkRecvStatus ServerNetworkGameSocketHandler::CloseConnection(NetworkRecvStatus status)
249 assert(status != NETWORK_RECV_STATUS_OKAY);
251 * Sending a message just before leaving the game calls cs->SendPackets.
252 * This might invoke this function, which means that when we close the
253 * connection after cs->SendPackets we will close an already closed
254 * connection. This handles that case gracefully without having to make
255 * that code any more complex or more aware of the validity of the socket.
257 if (this->sock == INVALID_SOCKET) return status;
259 if (status != NETWORK_RECV_STATUS_CLIENT_QUIT && status != NETWORK_RECV_STATUS_SERVER_ERROR && !this->HasClientQuit() && this->status >= STATUS_AUTHORIZED) {
260 /* We did not receive a leave message from this client... */
261 std::string client_name = this->GetClientName();
263 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, "", STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST);
265 /* Inform other clients of this... strange leaving ;) */
266 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
267 if (new_cs->status > STATUS_AUTHORIZED && this != new_cs) {
268 new_cs->SendErrorQuit(this->client_id, NETWORK_ERROR_CONNECTION_LOST);
273 /* If we were transfering a map to this client, stop the savegame creation
274 * process and queue the next client to receive the map. */
275 if (this->status == STATUS_MAP) {
276 /* Ensure the saving of the game is stopped too. */
277 this->savegame->Destroy();
278 this->savegame = nullptr;
280 this->CheckNextClientToSendMap(this);
283 NetworkAdminClientError(this->client_id, NETWORK_ERROR_CONNECTION_LOST);
284 Debug(net, 3, "Closed client connection {}", this->client_id);
286 /* We just lost one client :( */
287 if (this->status >= STATUS_AUTHORIZED) _network_game_info.clients_on--;
288 extern byte _network_clients_connected;
289 _network_clients_connected--;
291 this->SendPackets(true);
293 delete this->GetInfo();
294 delete this;
296 InvalidateWindowData(WC_CLIENT_LIST, 0);
298 return status;
302 * Whether an connection is allowed or not at this moment.
303 * @return true if the connection is allowed.
305 /* static */ bool ServerNetworkGameSocketHandler::AllowConnection()
307 extern byte _network_clients_connected;
308 bool accept = _network_clients_connected < MAX_CLIENTS && _network_game_info.clients_on < _settings_client.network.max_clients;
310 /* We can't go over the MAX_CLIENTS limit here. However, the
311 * pool must have place for all clients and ourself. */
312 static_assert(NetworkClientSocketPool::MAX_SIZE == MAX_CLIENTS + 1);
313 assert(!accept || ServerNetworkGameSocketHandler::CanAllocateItem());
314 return accept;
317 /** Send the packets for the server sockets. */
318 /* static */ void ServerNetworkGameSocketHandler::Send()
320 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
321 if (cs->writable) {
322 if (cs->SendPackets() != SPS_CLOSED && cs->status == STATUS_MAP) {
323 /* This client is in the middle of a map-send, call the function for that */
324 cs->SendMap();
330 static void NetworkHandleCommandQueue(NetworkClientSocket *cs);
332 /***********
333 * Sending functions
334 * DEF_SERVER_SEND_COMMAND has parameter: NetworkClientSocket *cs
335 ************/
338 * Send the client information about a client.
339 * @param ci The client to send information about.
341 NetworkRecvStatus ServerNetworkGameSocketHandler::SendClientInfo(NetworkClientInfo *ci)
343 if (ci->client_id != INVALID_CLIENT_ID) {
344 Packet *p = new Packet(PACKET_SERVER_CLIENT_INFO);
345 p->Send_uint32(ci->client_id);
346 p->Send_uint8 (ci->client_playas);
347 p->Send_string(ci->client_name);
349 this->SendPacket(p);
351 return NETWORK_RECV_STATUS_OKAY;
354 /** Send the client information about the server. */
355 NetworkRecvStatus ServerNetworkGameSocketHandler::SendGameInfo()
357 Packet *p = new Packet(PACKET_SERVER_GAME_INFO, TCP_MTU);
358 SerializeNetworkGameInfo(p, GetCurrentNetworkServerGameInfo());
360 this->SendPacket(p);
362 return NETWORK_RECV_STATUS_OKAY;
365 /** Send the client information about the companies. */
366 NetworkRecvStatus ServerNetworkGameSocketHandler::SendCompanyInfo()
368 /* Fetch the latest version of the stats */
369 NetworkCompanyStats company_stats[MAX_COMPANIES];
370 NetworkPopulateCompanyStats(company_stats);
372 /* Make a list of all clients per company */
373 std::string clients[MAX_COMPANIES];
375 /* Add the local player (if not dedicated) */
376 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
377 if (ci != nullptr && Company::IsValidID(ci->client_playas)) {
378 clients[ci->client_playas] = ci->client_name;
381 for (NetworkClientSocket *csi : NetworkClientSocket::Iterate()) {
382 std::string client_name = static_cast<ServerNetworkGameSocketHandler*>(csi)->GetClientName();
384 ci = csi->GetInfo();
385 if (ci != nullptr && Company::IsValidID(ci->client_playas)) {
386 if (!clients[ci->client_playas].empty()) {
387 clients[ci->client_playas] += ", ";
390 clients[ci->client_playas] += client_name;
394 /* Now send the data */
396 Packet *p;
398 for (const Company *company : Company::Iterate()) {
399 p = new Packet(PACKET_SERVER_COMPANY_INFO);
401 p->Send_uint8 (NETWORK_COMPANY_INFO_VERSION);
402 p->Send_bool (true);
403 this->SendCompanyInformation(p, company, &company_stats[company->index]);
405 if (clients[company->index].empty()) {
406 p->Send_string("<none>");
407 } else {
408 p->Send_string(clients[company->index]);
411 this->SendPacket(p);
414 p = new Packet(PACKET_SERVER_COMPANY_INFO);
416 p->Send_uint8 (NETWORK_COMPANY_INFO_VERSION);
417 p->Send_bool (false);
419 this->SendPacket(p);
420 return NETWORK_RECV_STATUS_OKAY;
424 * Send an error to the client, and close its connection.
425 * @param error The error to disconnect for.
426 * @param reason In case of kicking a client, specifies the reason for kicking the client.
428 NetworkRecvStatus ServerNetworkGameSocketHandler::SendError(NetworkErrorCode error, const std::string &reason)
430 Packet *p = new Packet(PACKET_SERVER_ERROR);
432 p->Send_uint8(error);
433 if (!reason.empty()) p->Send_string(reason);
434 this->SendPacket(p);
436 StringID strid = GetNetworkErrorMsg(error);
438 /* Only send when the current client was in game */
439 if (this->status > STATUS_AUTHORIZED) {
440 std::string client_name = this->GetClientName();
442 Debug(net, 1, "'{}' made an error and has been disconnected: {}", client_name, GetString(strid));
444 if (error == NETWORK_ERROR_KICKED && !reason.empty()) {
445 NetworkTextMessage(NETWORK_ACTION_KICKED, CC_DEFAULT, false, client_name, reason, strid);
446 } else {
447 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, "", strid);
450 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
451 if (new_cs->status >= STATUS_AUTHORIZED && new_cs != this) {
452 /* Some errors we filter to a more general error. Clients don't have to know the real
453 * reason a joining failed. */
454 if (error == NETWORK_ERROR_NOT_AUTHORIZED || error == NETWORK_ERROR_NOT_EXPECTED || error == NETWORK_ERROR_WRONG_REVISION) {
455 error = NETWORK_ERROR_ILLEGAL_PACKET;
457 new_cs->SendErrorQuit(this->client_id, error);
461 NetworkAdminClientError(this->client_id, error);
462 } else {
463 Debug(net, 1, "Client {} made an error and has been disconnected: {}", this->client_id, GetString(strid));
466 /* The client made a mistake, so drop the connection now! */
467 return this->CloseConnection(NETWORK_RECV_STATUS_SERVER_ERROR);
470 /** Send the check for the NewGRFs. */
471 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGRFCheck()
473 Packet *p = new Packet(PACKET_SERVER_CHECK_NEWGRFS, TCP_MTU);
474 const GRFConfig *c;
475 uint grf_count = 0;
477 for (c = _grfconfig; c != nullptr; c = c->next) {
478 if (!HasBit(c->flags, GCF_STATIC)) grf_count++;
481 p->Send_uint8 (grf_count);
482 for (c = _grfconfig; c != nullptr; c = c->next) {
483 if (!HasBit(c->flags, GCF_STATIC)) SerializeGRFIdentifier(p, &c->ident);
486 this->SendPacket(p);
487 return NETWORK_RECV_STATUS_OKAY;
490 /** Request the game password. */
491 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNeedGamePassword()
493 /* Invalid packet when status is STATUS_AUTH_GAME or higher */
494 if (this->status >= STATUS_AUTH_GAME) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
496 this->status = STATUS_AUTH_GAME;
497 /* Reset 'lag' counters */
498 this->last_frame = this->last_frame_server = _frame_counter;
500 Packet *p = new Packet(PACKET_SERVER_NEED_GAME_PASSWORD);
501 this->SendPacket(p);
502 return NETWORK_RECV_STATUS_OKAY;
505 /** Request the company password. */
506 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNeedCompanyPassword()
508 /* Invalid packet when status is STATUS_AUTH_COMPANY or higher */
509 if (this->status >= STATUS_AUTH_COMPANY) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
511 this->status = STATUS_AUTH_COMPANY;
512 /* Reset 'lag' counters */
513 this->last_frame = this->last_frame_server = _frame_counter;
515 Packet *p = new Packet(PACKET_SERVER_NEED_COMPANY_PASSWORD);
516 p->Send_uint32(_settings_game.game_creation.generation_seed);
517 p->Send_string(_settings_client.network.network_id);
518 this->SendPacket(p);
519 return NETWORK_RECV_STATUS_OKAY;
522 /** Send the client a welcome message with some basic information. */
523 NetworkRecvStatus ServerNetworkGameSocketHandler::SendWelcome()
525 Packet *p;
527 /* Invalid packet when status is AUTH or higher */
528 if (this->status >= STATUS_AUTHORIZED) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
530 this->status = STATUS_AUTHORIZED;
531 /* Reset 'lag' counters */
532 this->last_frame = this->last_frame_server = _frame_counter;
534 _network_game_info.clients_on++;
536 p = new Packet(PACKET_SERVER_WELCOME);
537 p->Send_uint32(this->client_id);
538 p->Send_uint32(_settings_game.game_creation.generation_seed);
539 p->Send_string(_settings_client.network.network_id);
540 this->SendPacket(p);
542 /* Transmit info about all the active clients */
543 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
544 if (new_cs != this && new_cs->status >= STATUS_AUTHORIZED) {
545 this->SendClientInfo(new_cs->GetInfo());
548 /* Also send the info of the server */
549 return this->SendClientInfo(NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER));
552 /** Tell the client that its put in a waiting queue. */
553 NetworkRecvStatus ServerNetworkGameSocketHandler::SendWait()
555 int waiting = 1; // current player getting the map counts as 1
556 Packet *p;
558 /* Count how many clients are waiting in the queue, in front of you! */
559 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
560 if (new_cs->status != STATUS_MAP_WAIT) continue;
561 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++;
564 p = new Packet(PACKET_SERVER_WAIT);
565 p->Send_uint8(waiting);
566 this->SendPacket(p);
567 return NETWORK_RECV_STATUS_OKAY;
570 void ServerNetworkGameSocketHandler::CheckNextClientToSendMap(NetworkClientSocket *ignore_cs)
572 /* Find the best candidate for joining, i.e. the first joiner. */
573 NetworkClientSocket *best = nullptr;
574 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
575 if (ignore_cs == new_cs) continue;
577 if (new_cs->status == STATUS_MAP_WAIT) {
578 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)) {
579 best = new_cs;
584 /* Is there someone else to join? */
585 if (best != nullptr) {
586 /* Let the first start joining. */
587 best->status = STATUS_AUTHORIZED;
588 best->SendMap();
590 /* And update the rest. */
591 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
592 if (new_cs->status == STATUS_MAP_WAIT) new_cs->SendWait();
597 /** This sends the map to the client */
598 NetworkRecvStatus ServerNetworkGameSocketHandler::SendMap()
600 if (this->status < STATUS_AUTHORIZED) {
601 /* Illegal call, return error and ignore the packet */
602 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
605 if (this->status == STATUS_AUTHORIZED) {
606 this->savegame = new PacketWriter(this);
608 /* Now send the _frame_counter and how many packets are coming */
609 Packet *p = new Packet(PACKET_SERVER_MAP_BEGIN);
610 p->Send_uint32(_frame_counter);
611 this->SendPacket(p);
613 NetworkSyncCommandQueue(this);
614 this->status = STATUS_MAP;
615 /* Mark the start of download */
616 this->last_frame = _frame_counter;
617 this->last_frame_server = _frame_counter;
619 /* Make a dump of the current game */
620 if (SaveWithFilter(this->savegame, true) != SL_OK) usererror("network savedump failed");
623 if (this->status == STATUS_MAP) {
624 bool last_packet = this->savegame->TransferToNetworkQueue(this);
625 if (last_packet) {
626 /* Done reading, make sure saving is done as well */
627 this->savegame->Destroy();
628 this->savegame = nullptr;
630 /* Set the status to DONE_MAP, no we will wait for the client
631 * to send it is ready (maybe that happens like never ;)) */
632 this->status = STATUS_DONE_MAP;
634 this->CheckNextClientToSendMap();
637 return NETWORK_RECV_STATUS_OKAY;
641 * Tell that a client joined.
642 * @param client_id The client that joined.
644 NetworkRecvStatus ServerNetworkGameSocketHandler::SendJoin(ClientID client_id)
646 Packet *p = new Packet(PACKET_SERVER_JOIN);
648 p->Send_uint32(client_id);
650 this->SendPacket(p);
651 return NETWORK_RECV_STATUS_OKAY;
654 /** Tell the client that they may run to a particular frame. */
655 NetworkRecvStatus ServerNetworkGameSocketHandler::SendFrame()
657 Packet *p = new Packet(PACKET_SERVER_FRAME);
658 p->Send_uint32(_frame_counter);
659 p->Send_uint32(_frame_counter_max);
660 #ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
661 p->Send_uint32(_sync_seed_1);
662 #ifdef NETWORK_SEND_DOUBLE_SEED
663 p->Send_uint32(_sync_seed_2);
664 #endif
665 #endif
667 /* If token equals 0, we need to make a new token and send that. */
668 if (this->last_token == 0) {
669 this->last_token = InteractiveRandomRange(UINT8_MAX - 1) + 1;
670 p->Send_uint8(this->last_token);
673 this->SendPacket(p);
674 return NETWORK_RECV_STATUS_OKAY;
677 /** Request the client to sync. */
678 NetworkRecvStatus ServerNetworkGameSocketHandler::SendSync()
680 Packet *p = new Packet(PACKET_SERVER_SYNC);
681 p->Send_uint32(_frame_counter);
682 p->Send_uint32(_sync_seed_1);
684 #ifdef NETWORK_SEND_DOUBLE_SEED
685 p->Send_uint32(_sync_seed_2);
686 #endif
687 this->SendPacket(p);
688 return NETWORK_RECV_STATUS_OKAY;
692 * Send a command to the client to execute.
693 * @param cp The command to send.
695 NetworkRecvStatus ServerNetworkGameSocketHandler::SendCommand(const CommandPacket *cp)
697 Packet *p = new Packet(PACKET_SERVER_COMMAND);
699 this->NetworkGameSocketHandler::SendCommand(p, cp);
700 p->Send_uint32(cp->frame);
701 p->Send_bool (cp->my_cmd);
703 this->SendPacket(p);
704 return NETWORK_RECV_STATUS_OKAY;
708 * Send a chat message.
709 * @param action The action associated with the message.
710 * @param client_id The origin of the chat message.
711 * @param self_send Whether we did send the message.
712 * @param msg The actual message.
713 * @param data Arbitrary extra data.
715 NetworkRecvStatus ServerNetworkGameSocketHandler::SendChat(NetworkAction action, ClientID client_id, bool self_send, const std::string &msg, int64 data)
717 if (this->status < STATUS_PRE_ACTIVE) return NETWORK_RECV_STATUS_OKAY;
719 Packet *p = new Packet(PACKET_SERVER_CHAT);
721 p->Send_uint8 (action);
722 p->Send_uint32(client_id);
723 p->Send_bool (self_send);
724 p->Send_string(msg);
725 p->Send_uint64(data);
727 this->SendPacket(p);
728 return NETWORK_RECV_STATUS_OKAY;
732 * Tell the client another client quit with an error.
733 * @param client_id The client that quit.
734 * @param errorno The reason the client quit.
736 NetworkRecvStatus ServerNetworkGameSocketHandler::SendErrorQuit(ClientID client_id, NetworkErrorCode errorno)
738 Packet *p = new Packet(PACKET_SERVER_ERROR_QUIT);
740 p->Send_uint32(client_id);
741 p->Send_uint8 (errorno);
743 this->SendPacket(p);
744 return NETWORK_RECV_STATUS_OKAY;
748 * Tell the client another client quit.
749 * @param client_id The client that quit.
751 NetworkRecvStatus ServerNetworkGameSocketHandler::SendQuit(ClientID client_id)
753 Packet *p = new Packet(PACKET_SERVER_QUIT);
755 p->Send_uint32(client_id);
757 this->SendPacket(p);
758 return NETWORK_RECV_STATUS_OKAY;
761 /** Tell the client we're shutting down. */
762 NetworkRecvStatus ServerNetworkGameSocketHandler::SendShutdown()
764 Packet *p = new Packet(PACKET_SERVER_SHUTDOWN);
765 this->SendPacket(p);
766 return NETWORK_RECV_STATUS_OKAY;
769 /** Tell the client we're starting a new game. */
770 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGame()
772 Packet *p = new Packet(PACKET_SERVER_NEWGAME);
773 this->SendPacket(p);
774 return NETWORK_RECV_STATUS_OKAY;
778 * Send the result of a console action.
779 * @param colour The colour of the result.
780 * @param command The command that was executed.
782 NetworkRecvStatus ServerNetworkGameSocketHandler::SendRConResult(uint16 colour, const std::string &command)
784 Packet *p = new Packet(PACKET_SERVER_RCON);
786 p->Send_uint16(colour);
787 p->Send_string(command);
788 this->SendPacket(p);
789 return NETWORK_RECV_STATUS_OKAY;
793 * Tell that a client moved to another company.
794 * @param client_id The client that moved.
795 * @param company_id The company the client moved to.
797 NetworkRecvStatus ServerNetworkGameSocketHandler::SendMove(ClientID client_id, CompanyID company_id)
799 Packet *p = new Packet(PACKET_SERVER_MOVE);
801 p->Send_uint32(client_id);
802 p->Send_uint8(company_id);
803 this->SendPacket(p);
804 return NETWORK_RECV_STATUS_OKAY;
807 /** Send an update about the company password states. */
808 NetworkRecvStatus ServerNetworkGameSocketHandler::SendCompanyUpdate()
810 Packet *p = new Packet(PACKET_SERVER_COMPANY_UPDATE);
812 p->Send_uint16(_network_company_passworded);
813 this->SendPacket(p);
814 return NETWORK_RECV_STATUS_OKAY;
817 /** Send an update about the max company/spectator counts. */
818 NetworkRecvStatus ServerNetworkGameSocketHandler::SendConfigUpdate()
820 Packet *p = new Packet(PACKET_SERVER_CONFIG_UPDATE);
822 p->Send_uint8(_settings_client.network.max_companies);
823 this->SendPacket(p);
824 return NETWORK_RECV_STATUS_OKAY;
827 /***********
828 * Receiving functions
829 * DEF_SERVER_RECEIVE_COMMAND has parameter: NetworkClientSocket *cs, Packet *p
830 ************/
832 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GAME_INFO(Packet *p)
834 return this->SendGameInfo();
837 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMPANY_INFO(Packet *p)
839 return this->SendCompanyInfo();
842 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_NEWGRFS_CHECKED(Packet *p)
844 if (this->status != STATUS_NEWGRFS_CHECK) {
845 /* Illegal call, return error and ignore the packet */
846 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
849 NetworkClientInfo *ci = this->GetInfo();
851 /* We now want a password from the client else we do not allow them in! */
852 if (!_settings_client.network.server_password.empty()) {
853 return this->SendNeedGamePassword();
856 if (Company::IsValidID(ci->client_playas) && !_network_company_states[ci->client_playas].password.empty()) {
857 return this->SendNeedCompanyPassword();
860 return this->SendWelcome();
863 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet *p)
865 if (this->status != STATUS_INACTIVE) {
866 /* Illegal call, return error and ignore the packet */
867 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
870 std::string client_revision = p->Recv_string(NETWORK_REVISION_LENGTH);
871 uint32 newgrf_version = p->Recv_uint32();
873 /* Check if the client has revision control enabled */
874 if (!IsNetworkCompatibleVersion(client_revision) || _openttd_newgrf_version != newgrf_version) {
875 /* Different revisions!! */
876 return this->SendError(NETWORK_ERROR_WRONG_REVISION);
879 std::string client_name = p->Recv_string(NETWORK_CLIENT_NAME_LENGTH);
880 CompanyID playas = (Owner)p->Recv_uint8();
882 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT;
884 /* join another company does not affect these values */
885 switch (playas) {
886 case COMPANY_NEW_COMPANY: // New company
887 if (Company::GetNumItems() >= _settings_client.network.max_companies) {
888 return this->SendError(NETWORK_ERROR_FULL);
890 break;
891 case COMPANY_SPECTATOR: // Spectator
892 break;
893 default: // Join another company (companies 1-8 (index 0-7))
894 if (!Company::IsValidHumanID(playas)) {
895 return this->SendError(NETWORK_ERROR_COMPANY_MISMATCH);
897 break;
900 if (!NetworkIsValidClientName(client_name)) {
901 /* An invalid client name was given. However, the client ensures the name
902 * is valid before it is sent over the network, so something went horribly
903 * wrong. This is probably someone trying to troll us. */
904 return this->SendError(NETWORK_ERROR_INVALID_CLIENT_NAME);
907 if (!NetworkMakeClientNameUnique(client_name)) { // Change name if duplicate
908 /* We could not create a name for this client */
909 return this->SendError(NETWORK_ERROR_NAME_IN_USE);
912 assert(NetworkClientInfo::CanAllocateItem());
913 NetworkClientInfo *ci = new NetworkClientInfo(this->client_id);
914 this->SetInfo(ci);
915 ci->join_date = _date;
916 ci->client_name = client_name;
917 ci->client_playas = playas;
918 Debug(desync, 1, "client: {:08x}; {:02x}; {:02x}; {:02x}", _date, _date_fract, (int)ci->client_playas, (int)ci->index);
920 /* Make sure companies to which people try to join are not autocleaned */
921 if (Company::IsValidID(playas)) _network_company_states[playas].months_empty = 0;
923 this->status = STATUS_NEWGRFS_CHECK;
925 if (_grfconfig == nullptr) {
926 /* Behave as if we received PACKET_CLIENT_NEWGRFS_CHECKED */
927 return this->Receive_CLIENT_NEWGRFS_CHECKED(nullptr);
930 return this->SendNewGRFCheck();
933 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GAME_PASSWORD(Packet *p)
935 if (this->status != STATUS_AUTH_GAME) {
936 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
939 std::string password = p->Recv_string(NETWORK_PASSWORD_LENGTH);
941 /* Check game password. Allow joining if we cleared the password meanwhile */
942 if (!_settings_client.network.server_password.empty() &&
943 _settings_client.network.server_password.compare(password) != 0) {
944 /* Password is invalid */
945 return this->SendError(NETWORK_ERROR_WRONG_PASSWORD);
948 const NetworkClientInfo *ci = this->GetInfo();
949 if (Company::IsValidID(ci->client_playas) && !_network_company_states[ci->client_playas].password.empty()) {
950 return this->SendNeedCompanyPassword();
953 /* Valid password, allow user */
954 return this->SendWelcome();
957 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMPANY_PASSWORD(Packet *p)
959 if (this->status != STATUS_AUTH_COMPANY) {
960 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
963 std::string password = p->Recv_string(NETWORK_PASSWORD_LENGTH);
965 /* Check company password. Allow joining if we cleared the password meanwhile.
966 * Also, check the company is still valid - client could be moved to spectators
967 * in the middle of the authorization process */
968 CompanyID playas = this->GetInfo()->client_playas;
969 if (Company::IsValidID(playas) && !_network_company_states[playas].password.empty() &&
970 _network_company_states[playas].password.compare(password) != 0) {
971 /* Password is invalid */
972 return this->SendError(NETWORK_ERROR_WRONG_PASSWORD);
975 return this->SendWelcome();
978 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GETMAP(Packet *p)
980 /* The client was never joined.. so this is impossible, right?
981 * Ignore the packet, give the client a warning, and close the connection */
982 if (this->status < STATUS_AUTHORIZED || this->HasClientQuit()) {
983 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
986 /* Check if someone else is receiving the map */
987 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
988 if (new_cs->status == STATUS_MAP) {
989 /* Tell the new client to wait */
990 this->status = STATUS_MAP_WAIT;
991 return this->SendWait();
995 /* We receive a request to upload the map.. give it to the client! */
996 return this->SendMap();
999 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MAP_OK(Packet *p)
1001 /* Client has the map, now start syncing */
1002 if (this->status == STATUS_DONE_MAP && !this->HasClientQuit()) {
1003 std::string client_name = this->GetClientName();
1005 NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, client_name, "", this->client_id);
1006 InvalidateWindowData(WC_CLIENT_LIST, 0);
1008 /* Mark the client as pre-active, and wait for an ACK
1009 * so we know it is done loading and in sync with us */
1010 this->status = STATUS_PRE_ACTIVE;
1011 NetworkHandleCommandQueue(this);
1012 this->SendFrame();
1013 this->SendSync();
1015 /* This is the frame the client receives
1016 * we need it later on to make sure the client is not too slow */
1017 this->last_frame = _frame_counter;
1018 this->last_frame_server = _frame_counter;
1020 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
1021 if (new_cs->status >= STATUS_AUTHORIZED) {
1022 new_cs->SendClientInfo(this->GetInfo());
1023 new_cs->SendJoin(this->client_id);
1027 NetworkAdminClientInfo(this, true);
1029 /* also update the new client with our max values */
1030 this->SendConfigUpdate();
1032 /* quickly update the syncing client with company details */
1033 return this->SendCompanyUpdate();
1036 /* Wrong status for this packet, give a warning to client, and close connection */
1037 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1041 * The client has done a command and wants us to handle it
1042 * @param p the packet in which the command was sent
1044 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMMAND(Packet *p)
1046 /* The client was never joined.. so this is impossible, right?
1047 * Ignore the packet, give the client a warning, and close the connection */
1048 if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
1049 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1052 if (this->incoming_queue.Count() >= _settings_client.network.max_commands_in_queue) {
1053 return this->SendError(NETWORK_ERROR_TOO_MANY_COMMANDS);
1056 CommandPacket cp;
1057 const char *err = this->ReceiveCommand(p, &cp);
1059 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT;
1061 NetworkClientInfo *ci = this->GetInfo();
1063 if (err != nullptr) {
1064 IConsolePrint(CC_WARNING, "Dropping client #{} (IP: {}) due to {}.", ci->client_id, this->GetClientIP(), err);
1065 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1069 if ((GetCommandFlags(cp.cmd) & CMD_SERVER) && ci->client_id != CLIENT_ID_SERVER) {
1070 IConsolePrint(CC_WARNING, "Kicking client #{} (IP: {}) due to calling a server only command {}.", ci->client_id, this->GetClientIP(), cp.cmd & CMD_ID_MASK);
1071 return this->SendError(NETWORK_ERROR_KICKED);
1074 if ((GetCommandFlags(cp.cmd) & CMD_SPECTATOR) == 0 && !Company::IsValidID(cp.company) && ci->client_id != CLIENT_ID_SERVER) {
1075 IConsolePrint(CC_WARNING, "Kicking client #{} (IP: {}) due to calling a non-spectator command {}.", ci->client_id, this->GetClientIP(), cp.cmd & CMD_ID_MASK);
1076 return this->SendError(NETWORK_ERROR_KICKED);
1080 * Only CMD_COMPANY_CTRL is always allowed, for the rest, playas needs
1081 * to match the company in the packet. If it doesn't, the client has done
1082 * something pretty naughty (or a bug), and will be kicked
1084 if (!(cp.cmd == CMD_COMPANY_CTRL && cp.p1 == 0 && ci->client_playas == COMPANY_NEW_COMPANY) && ci->client_playas != cp.company) {
1085 IConsolePrint(CC_WARNING, "Kicking client #{} (IP: {}) due to calling a command as another company {}.",
1086 ci->client_playas + 1, this->GetClientIP(), cp.company + 1);
1087 return this->SendError(NETWORK_ERROR_COMPANY_MISMATCH);
1090 if (cp.cmd == CMD_COMPANY_CTRL) {
1091 if (cp.p1 != 0 || cp.company != COMPANY_SPECTATOR) {
1092 return this->SendError(NETWORK_ERROR_CHEATER);
1095 /* 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! */
1096 if (Company::GetNumItems() >= _settings_client.network.max_companies) {
1097 NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_CLIENT, ci->client_id, "cannot create new company, server full", CLIENT_ID_SERVER);
1098 return NETWORK_RECV_STATUS_OKAY;
1102 if (GetCommandFlags(cp.cmd) & CMD_CLIENT_ID) cp.p2 = this->client_id;
1104 this->incoming_queue.Append(&cp);
1105 return NETWORK_RECV_STATUS_OKAY;
1108 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ERROR(Packet *p)
1110 /* This packets means a client noticed an error and is reporting this
1111 * to us. Display the error and report it to the other clients */
1112 NetworkErrorCode errorno = (NetworkErrorCode)p->Recv_uint8();
1114 /* The client was never joined.. thank the client for the packet, but ignore it */
1115 if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
1116 return this->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT);
1119 std::string client_name = this->GetClientName();
1120 StringID strid = GetNetworkErrorMsg(errorno);
1122 Debug(net, 1, "'{}' reported an error and is closing its connection: {}", client_name, GetString(strid));
1124 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, "", strid);
1126 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
1127 if (new_cs->status >= STATUS_AUTHORIZED) {
1128 new_cs->SendErrorQuit(this->client_id, errorno);
1132 NetworkAdminClientError(this->client_id, errorno);
1134 return this->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT);
1137 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_QUIT(Packet *p)
1139 /* The client was never joined.. thank the client for the packet, but ignore it */
1140 if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
1141 return this->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT);
1144 /* The client wants to leave. Display this and report it to the other clients. */
1145 std::string client_name = this->GetClientName();
1146 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, "", STR_NETWORK_MESSAGE_CLIENT_LEAVING);
1148 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
1149 if (new_cs->status >= STATUS_AUTHORIZED && new_cs != this) {
1150 new_cs->SendQuit(this->client_id);
1154 NetworkAdminClientQuit(this->client_id);
1156 return this->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT);
1159 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ACK(Packet *p)
1161 if (this->status < STATUS_AUTHORIZED) {
1162 /* Illegal call, return error and ignore the packet */
1163 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
1166 uint32 frame = p->Recv_uint32();
1168 /* The client is trying to catch up with the server */
1169 if (this->status == STATUS_PRE_ACTIVE) {
1170 /* The client is not yet caught up? */
1171 if (frame + DAY_TICKS < _frame_counter) return NETWORK_RECV_STATUS_OKAY;
1173 /* Now it is! Unpause the game */
1174 this->status = STATUS_ACTIVE;
1175 this->last_token_frame = _frame_counter;
1177 /* Execute script for, e.g. MOTD */
1178 IConsoleCmdExec("exec scripts/on_server_connect.scr 0");
1181 /* Get, and validate the token. */
1182 uint8 token = p->Recv_uint8();
1183 if (token == this->last_token) {
1184 /* We differentiate between last_token_frame and last_frame so the lag
1185 * test uses the actual lag of the client instead of the lag for getting
1186 * the token back and forth; after all, the token is only sent every
1187 * time we receive a PACKET_CLIENT_ACK, after which we will send a new
1188 * token to the client. If the lag would be one day, then we would not
1189 * be sending the new token soon enough for the new daily scheduled
1190 * PACKET_CLIENT_ACK. This would then register the lag of the client as
1191 * two days, even when it's only a single day. */
1192 this->last_token_frame = _frame_counter;
1193 /* Request a new token. */
1194 this->last_token = 0;
1197 /* The client received the frame, make note of it */
1198 this->last_frame = frame;
1199 /* With those 2 values we can calculate the lag realtime */
1200 this->last_frame_server = _frame_counter;
1201 return NETWORK_RECV_STATUS_OKAY;
1206 * Send an actual chat message.
1207 * @param action The action that's performed.
1208 * @param desttype The type of destination.
1209 * @param dest The actual destination index.
1210 * @param msg The actual message.
1211 * @param from_id The origin of the message.
1212 * @param data Arbitrary data.
1213 * @param from_admin Whether the origin is an admin or not.
1215 void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, const std::string &msg, ClientID from_id, int64 data, bool from_admin)
1217 const NetworkClientInfo *ci, *ci_own, *ci_to;
1219 switch (desttype) {
1220 case DESTTYPE_CLIENT:
1221 /* Are we sending to the server? */
1222 if ((ClientID)dest == CLIENT_ID_SERVER) {
1223 ci = NetworkClientInfo::GetByClientID(from_id);
1224 /* Display the text locally, and that is it */
1225 if (ci != nullptr) {
1226 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
1228 if (_settings_client.network.server_admin_chat) {
1229 NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
1232 } else {
1233 /* Else find the client to send the message to */
1234 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1235 if (cs->client_id == (ClientID)dest) {
1236 cs->SendChat(action, from_id, false, msg, data);
1237 break;
1242 /* Display the message locally (so you know you have sent it) */
1243 if (from_id != (ClientID)dest) {
1244 if (from_id == CLIENT_ID_SERVER) {
1245 ci = NetworkClientInfo::GetByClientID(from_id);
1246 ci_to = NetworkClientInfo::GetByClientID((ClientID)dest);
1247 if (ci != nullptr && ci_to != nullptr) {
1248 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), true, ci_to->client_name, msg, data);
1250 } else {
1251 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1252 if (cs->client_id == from_id) {
1253 cs->SendChat(action, (ClientID)dest, true, msg, data);
1254 break;
1259 break;
1260 case DESTTYPE_TEAM: {
1261 /* If this is false, the message is already displayed on the client who sent it. */
1262 bool show_local = true;
1263 /* Find all clients that belong to this company */
1264 ci_to = nullptr;
1265 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1266 ci = cs->GetInfo();
1267 if (ci != nullptr && ci->client_playas == (CompanyID)dest) {
1268 cs->SendChat(action, from_id, false, msg, data);
1269 if (cs->client_id == from_id) show_local = false;
1270 ci_to = ci; // Remember a client that is in the company for company-name
1274 /* if the server can read it, let the admin network read it, too. */
1275 if (_local_company == (CompanyID)dest && _settings_client.network.server_admin_chat) {
1276 NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
1279 ci = NetworkClientInfo::GetByClientID(from_id);
1280 ci_own = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
1281 if (ci != nullptr && ci_own != nullptr && ci_own->client_playas == dest) {
1282 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
1283 if (from_id == CLIENT_ID_SERVER) show_local = false;
1284 ci_to = ci_own;
1287 /* There is no such client */
1288 if (ci_to == nullptr) break;
1290 /* Display the message locally (so you know you have sent it) */
1291 if (ci != nullptr && show_local) {
1292 if (from_id == CLIENT_ID_SERVER) {
1293 StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
1294 SetDParam(0, ci_to->client_playas);
1295 std::string name = GetString(str);
1296 NetworkTextMessage(action, GetDrawStringCompanyColour(ci_own->client_playas), true, name, msg, data);
1297 } else {
1298 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1299 if (cs->client_id == from_id) {
1300 cs->SendChat(action, ci_to->client_id, true, msg, data);
1305 break;
1307 default:
1308 Debug(net, 1, "Received unknown chat destination type {}; doing broadcast instead", desttype);
1309 FALLTHROUGH;
1311 case DESTTYPE_BROADCAST:
1312 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1313 cs->SendChat(action, from_id, false, msg, data);
1316 NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
1318 ci = NetworkClientInfo::GetByClientID(from_id);
1319 if (ci != nullptr) {
1320 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
1322 break;
1326 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_CHAT(Packet *p)
1328 if (this->status < STATUS_PRE_ACTIVE) {
1329 /* Illegal call, return error and ignore the packet */
1330 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
1333 NetworkAction action = (NetworkAction)p->Recv_uint8();
1334 DestType desttype = (DestType)p->Recv_uint8();
1335 int dest = p->Recv_uint32();
1337 std::string msg = p->Recv_string(NETWORK_CHAT_LENGTH);
1338 int64 data = p->Recv_uint64();
1340 NetworkClientInfo *ci = this->GetInfo();
1341 switch (action) {
1342 case NETWORK_ACTION_CHAT:
1343 case NETWORK_ACTION_CHAT_CLIENT:
1344 case NETWORK_ACTION_CHAT_COMPANY:
1345 NetworkServerSendChat(action, desttype, dest, msg, this->client_id, data);
1346 break;
1347 default:
1348 IConsolePrint(CC_WARNING, "Kicking client #{} (IP: {}) due to unknown chact action.", ci->client_id, this->GetClientIP());
1349 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1351 return NETWORK_RECV_STATUS_OKAY;
1354 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_PASSWORD(Packet *p)
1356 if (this->status != STATUS_ACTIVE) {
1357 /* Illegal call, return error and ignore the packet */
1358 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1361 std::string password = p->Recv_string(NETWORK_PASSWORD_LENGTH);
1362 const NetworkClientInfo *ci = this->GetInfo();
1364 NetworkServerSetCompanyPassword(ci->client_playas, password);
1365 return NETWORK_RECV_STATUS_OKAY;
1368 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_NAME(Packet *p)
1370 if (this->status != STATUS_ACTIVE) {
1371 /* Illegal call, return error and ignore the packet */
1372 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1375 NetworkClientInfo *ci;
1377 std::string client_name = p->Recv_string(NETWORK_CLIENT_NAME_LENGTH);
1378 ci = this->GetInfo();
1380 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT;
1382 if (ci != nullptr) {
1383 if (!NetworkIsValidClientName(client_name)) {
1384 /* An invalid client name was given. However, the client ensures the name
1385 * is valid before it is sent over the network, so something went horribly
1386 * wrong. This is probably someone trying to troll us. */
1387 return this->SendError(NETWORK_ERROR_INVALID_CLIENT_NAME);
1390 /* Display change */
1391 if (NetworkMakeClientNameUnique(client_name)) {
1392 NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, client_name);
1393 ci->client_name = client_name;
1394 NetworkUpdateClientInfo(ci->client_id);
1397 return NETWORK_RECV_STATUS_OKAY;
1400 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_RCON(Packet *p)
1402 if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1404 if (_settings_client.network.rcon_password.empty()) return NETWORK_RECV_STATUS_OKAY;
1406 std::string password = p->Recv_string(NETWORK_PASSWORD_LENGTH);
1407 std::string command = p->Recv_string(NETWORK_RCONCOMMAND_LENGTH);
1409 if (_settings_client.network.rcon_password.compare(password) != 0) {
1410 Debug(net, 1, "[rcon] Wrong password from client-id {}", this->client_id);
1411 return NETWORK_RECV_STATUS_OKAY;
1414 Debug(net, 3, "[rcon] Client-id {} executed: {}", this->client_id, command);
1416 _redirect_console_to_client = this->client_id;
1417 IConsoleCmdExec(command.c_str());
1418 _redirect_console_to_client = INVALID_CLIENT_ID;
1419 return NETWORK_RECV_STATUS_OKAY;
1422 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MOVE(Packet *p)
1424 if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1426 CompanyID company_id = (Owner)p->Recv_uint8();
1428 /* Check if the company is valid, we don't allow moving to AI companies */
1429 if (company_id != COMPANY_SPECTATOR && !Company::IsValidHumanID(company_id)) return NETWORK_RECV_STATUS_OKAY;
1431 /* Check if we require a password for this company */
1432 if (company_id != COMPANY_SPECTATOR && !_network_company_states[company_id].password.empty()) {
1433 /* we need a password from the client - should be in this packet */
1434 std::string password = p->Recv_string(NETWORK_PASSWORD_LENGTH);
1436 /* Incorrect password sent, return! */
1437 if (_network_company_states[company_id].password.compare(password) != 0) {
1438 Debug(net, 2, "Wrong password from client-id #{} for company #{}", this->client_id, company_id + 1);
1439 return NETWORK_RECV_STATUS_OKAY;
1443 /* if we get here we can move the client */
1444 NetworkServerDoMove(this->client_id, company_id);
1445 return NETWORK_RECV_STATUS_OKAY;
1449 * Package some generic company information into a packet.
1450 * @param p The packet that will contain the data.
1451 * @param c The company to put the of into the packet.
1452 * @param stats The statistics to put in the packet.
1453 * @param max_len The maximum length of the company name.
1455 void NetworkSocketHandler::SendCompanyInformation(Packet *p, const Company *c, const NetworkCompanyStats *stats, uint max_len)
1457 /* Grab the company name */
1458 char company_name[NETWORK_COMPANY_NAME_LENGTH];
1459 SetDParam(0, c->index);
1461 assert(max_len <= lengthof(company_name));
1462 GetString(company_name, STR_COMPANY_NAME, company_name + max_len - 1);
1464 /* Get the income */
1465 Money income = 0;
1466 if (_cur_year - 1 == c->inaugurated_year) {
1467 /* The company is here just 1 year, so display [2], else display[1] */
1468 for (uint i = 0; i < lengthof(c->yearly_expenses[2]); i++) {
1469 income -= c->yearly_expenses[2][i];
1471 } else {
1472 for (uint i = 0; i < lengthof(c->yearly_expenses[1]); i++) {
1473 income -= c->yearly_expenses[1][i];
1477 /* Send the information */
1478 p->Send_uint8 (c->index);
1479 p->Send_string(company_name);
1480 p->Send_uint32(c->inaugurated_year);
1481 p->Send_uint64(c->old_economy[0].company_value);
1482 p->Send_uint64(c->money);
1483 p->Send_uint64(income);
1484 p->Send_uint16(c->old_economy[0].performance_history);
1486 /* Send 1 if there is a password for the company else send 0 */
1487 p->Send_bool (!_network_company_states[c->index].password.empty());
1489 for (uint i = 0; i < NETWORK_VEH_END; i++) {
1490 p->Send_uint16(stats->num_vehicle[i]);
1493 for (uint i = 0; i < NETWORK_VEH_END; i++) {
1494 p->Send_uint16(stats->num_station[i]);
1497 p->Send_bool(c->is_ai);
1501 * Populate the company stats.
1502 * @param stats the stats to update
1504 void NetworkPopulateCompanyStats(NetworkCompanyStats *stats)
1506 memset(stats, 0, sizeof(*stats) * MAX_COMPANIES);
1508 /* Go through all vehicles and count the type of vehicles */
1509 for (const Vehicle *v : Vehicle::Iterate()) {
1510 if (!Company::IsValidID(v->owner) || !v->IsPrimaryVehicle()) continue;
1511 byte type = 0;
1512 switch (v->type) {
1513 case VEH_TRAIN: type = NETWORK_VEH_TRAIN; break;
1514 case VEH_ROAD: type = RoadVehicle::From(v)->IsBus() ? NETWORK_VEH_BUS : NETWORK_VEH_LORRY; break;
1515 case VEH_AIRCRAFT: type = NETWORK_VEH_PLANE; break;
1516 case VEH_SHIP: type = NETWORK_VEH_SHIP; break;
1517 default: continue;
1519 stats[v->owner].num_vehicle[type]++;
1522 /* Go through all stations and count the types of stations */
1523 for (const Station *s : Station::Iterate()) {
1524 if (Company::IsValidID(s->owner)) {
1525 NetworkCompanyStats *npi = &stats[s->owner];
1527 if (s->facilities & FACIL_TRAIN) npi->num_station[NETWORK_VEH_TRAIN]++;
1528 if (s->facilities & FACIL_TRUCK_STOP) npi->num_station[NETWORK_VEH_LORRY]++;
1529 if (s->facilities & FACIL_BUS_STOP) npi->num_station[NETWORK_VEH_BUS]++;
1530 if (s->facilities & FACIL_AIRPORT) npi->num_station[NETWORK_VEH_PLANE]++;
1531 if (s->facilities & FACIL_DOCK) npi->num_station[NETWORK_VEH_SHIP]++;
1537 * Send updated client info of a particular client.
1538 * @param client_id The client to send it for.
1540 void NetworkUpdateClientInfo(ClientID client_id)
1542 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1544 if (ci == nullptr) return;
1546 Debug(desync, 1, "client: {:08x}; {:02x}; {:02x}; {:04x}", _date, _date_fract, (int)ci->client_playas, client_id);
1548 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1549 if (cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) {
1550 cs->SendClientInfo(ci);
1554 NetworkAdminClientUpdate(ci);
1557 /** Check if we want to restart the map */
1558 static void NetworkCheckRestartMap()
1560 if (_settings_client.network.restart_game_year != 0 && _cur_year >= _settings_client.network.restart_game_year) {
1561 Debug(net, 3, "Auto-restarting map: year {} reached", _cur_year);
1563 _settings_newgame.game_creation.generation_seed = GENERATE_NEW_SEED;
1564 switch(_file_to_saveload.abstract_ftype) {
1565 case FT_SAVEGAME:
1566 case FT_SCENARIO:
1567 _switch_mode = SM_LOAD_GAME;
1568 break;
1570 case FT_HEIGHTMAP:
1571 _switch_mode = SM_START_HEIGHTMAP;
1572 break;
1574 default:
1575 _switch_mode = SM_NEWGAME;
1580 /** Check if the server has autoclean_companies activated
1581 * Two things happen:
1582 * 1) If a company is not protected, it is closed after 1 year (for example)
1583 * 2) If a company is protected, protection is disabled after 3 years (for example)
1584 * (and item 1. happens a year later)
1586 static void NetworkAutoCleanCompanies()
1588 bool clients_in_company[MAX_COMPANIES];
1589 int vehicles_in_company[MAX_COMPANIES];
1591 if (!_settings_client.network.autoclean_companies) return;
1593 memset(clients_in_company, 0, sizeof(clients_in_company));
1595 /* Detect the active companies */
1596 for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1597 if (Company::IsValidID(ci->client_playas)) clients_in_company[ci->client_playas] = true;
1600 if (!_network_dedicated) {
1601 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
1602 if (Company::IsValidID(ci->client_playas)) clients_in_company[ci->client_playas] = true;
1605 if (_settings_client.network.autoclean_novehicles != 0) {
1606 memset(vehicles_in_company, 0, sizeof(vehicles_in_company));
1608 for (const Vehicle *v : Vehicle::Iterate()) {
1609 if (!Company::IsValidID(v->owner) || !v->IsPrimaryVehicle()) continue;
1610 vehicles_in_company[v->owner]++;
1614 /* Go through all the companies */
1615 for (const Company *c : Company::Iterate()) {
1616 /* Skip the non-active once */
1617 if (c->is_ai) continue;
1619 if (!clients_in_company[c->index]) {
1620 /* The company is empty for one month more */
1621 _network_company_states[c->index].months_empty++;
1623 /* Is the company empty for autoclean_unprotected-months, and is there no protection? */
1624 if (_settings_client.network.autoclean_unprotected != 0 && _network_company_states[c->index].months_empty > _settings_client.network.autoclean_unprotected && _network_company_states[c->index].password.empty()) {
1625 /* Shut the company down */
1626 DoCommandP(0, CCA_DELETE | c->index << 16 | CRR_AUTOCLEAN << 24, 0, CMD_COMPANY_CTRL);
1627 IConsolePrint(CC_INFO, "Auto-cleaned company #{} with no password.", c->index + 1);
1629 /* Is the company empty for autoclean_protected-months, and there is a protection? */
1630 if (_settings_client.network.autoclean_protected != 0 && _network_company_states[c->index].months_empty > _settings_client.network.autoclean_protected && !_network_company_states[c->index].password.empty()) {
1631 /* Unprotect the company */
1632 _network_company_states[c->index].password.clear();
1633 IConsolePrint(CC_INFO, "Auto-removed protection from company #{}.", c->index + 1);
1634 _network_company_states[c->index].months_empty = 0;
1635 NetworkServerUpdateCompanyPassworded(c->index, false);
1637 /* Is the company empty for autoclean_novehicles-months, and has no vehicles? */
1638 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) {
1639 /* Shut the company down */
1640 DoCommandP(0, CCA_DELETE | c->index << 16 | CRR_AUTOCLEAN << 24, 0, CMD_COMPANY_CTRL);
1641 IConsolePrint(CC_INFO, "Auto-cleaned company #{} with no vehicles.", c->index + 1);
1643 } else {
1644 /* It is not empty, reset the date */
1645 _network_company_states[c->index].months_empty = 0;
1651 * Check whether a name is unique, and otherwise try to make it unique.
1652 * @param new_name The name to check/modify.
1653 * @return True if an unique name was achieved.
1655 bool NetworkMakeClientNameUnique(std::string &name)
1657 bool is_name_unique = false;
1658 uint number = 0;
1659 std::string original_name = name;
1661 while (!is_name_unique) {
1662 is_name_unique = true;
1663 for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1664 if (ci->client_name.compare(name) == 0) {
1665 /* Name already in use */
1666 is_name_unique = false;
1667 break;
1670 /* Check if it is the same as the server-name */
1671 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
1672 if (ci != nullptr) {
1673 if (ci->client_name.compare(name) == 0) is_name_unique = false; // name already in use
1676 if (!is_name_unique) {
1677 /* Try a new name (<name> #1, <name> #2, and so on) */
1678 name = original_name + " #" + std::to_string(number);
1680 /* The constructed client name is larger than the limit,
1681 * so... bail out as no valid name can be created. */
1682 if (name.size() >= NETWORK_CLIENT_NAME_LENGTH) return false;
1686 return is_name_unique;
1690 * Change the client name of the given client
1691 * @param client_id the client to change the name of
1692 * @param new_name the new name for the client
1693 * @return true iff the name was changed
1695 bool NetworkServerChangeClientName(ClientID client_id, const std::string &new_name)
1697 /* Check if the name's already in use */
1698 for (NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1699 if (ci->client_name.compare(new_name) == 0) return false;
1702 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1703 if (ci == nullptr) return false;
1705 NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, true, ci->client_name, new_name);
1707 ci->client_name = new_name;
1709 NetworkUpdateClientInfo(client_id);
1710 return true;
1714 * Set/Reset a company password on the server end.
1715 * @param company_id ID of the company the password should be changed for.
1716 * @param password The new password.
1717 * @param already_hashed Is the given password already hashed?
1719 void NetworkServerSetCompanyPassword(CompanyID company_id, const std::string &password, bool already_hashed)
1721 if (!Company::IsValidHumanID(company_id)) return;
1723 if (already_hashed) {
1724 _network_company_states[company_id].password = password;
1725 } else {
1726 _network_company_states[company_id].password = GenerateCompanyPasswordHash(password, _settings_client.network.network_id, _settings_game.game_creation.generation_seed);
1729 NetworkServerUpdateCompanyPassworded(company_id, !_network_company_states[company_id].password.empty());
1733 * Handle the command-queue of a socket.
1734 * @param cs The socket to handle the queue for.
1736 static void NetworkHandleCommandQueue(NetworkClientSocket *cs)
1738 CommandPacket *cp;
1739 while ((cp = cs->outgoing_queue.Pop()) != nullptr) {
1740 cs->SendCommand(cp);
1741 delete cp;
1746 * This is called every tick if this is a _network_server
1747 * @param send_frame Whether to send the frame to the clients.
1749 void NetworkServer_Tick(bool send_frame)
1751 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1752 bool send_sync = false;
1753 #endif
1755 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1756 if (_frame_counter >= _last_sync_frame + _settings_client.network.sync_freq) {
1757 _last_sync_frame = _frame_counter;
1758 send_sync = true;
1760 #endif
1762 /* Now we are done with the frame, inform the clients that they can
1763 * do their frame! */
1764 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1765 /* We allow a number of bytes per frame, but only to the burst amount
1766 * to be available for packet receiving at any particular time. */
1767 cs->receive_limit = std::min<size_t>(cs->receive_limit + _settings_client.network.bytes_per_frame,
1768 _settings_client.network.bytes_per_frame_burst);
1770 /* Check if the speed of the client is what we can expect from a client */
1771 uint lag = NetworkCalculateLag(cs);
1772 switch (cs->status) {
1773 case NetworkClientSocket::STATUS_ACTIVE:
1774 if (lag > _settings_client.network.max_lag_time) {
1775 /* Client did still not report in within the specified limit. */
1776 IConsolePrint(CC_WARNING, cs->last_packet + std::chrono::milliseconds(lag * MILLISECONDS_PER_TICK) > std::chrono::steady_clock::now() ?
1777 /* A packet was received in the last three game days, so the client is likely lagging behind. */
1778 "Client #%u (IP: %s) is dropped because the client's game state is more than %d ticks behind." :
1779 /* No packet was received in the last three game days; sounds like a lost connection. */
1780 "Client #%u (IP: %s) is dropped because the client did not respond for more than %d ticks.",
1781 cs->client_id, cs->GetClientIP(), lag);
1782 cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
1783 continue;
1786 /* Report once per time we detect the lag, and only when we
1787 * received a packet in the last 2 seconds. If we
1788 * did not receive a packet, then the client is not just
1789 * slow, but the connection is likely severed. Mentioning
1790 * frame_freq is not useful in this case. */
1791 if (lag > (uint)DAY_TICKS && cs->lag_test == 0 && cs->last_packet + std::chrono::seconds(2) > std::chrono::steady_clock::now()) {
1792 IConsolePrint(CC_WARNING, "[{}] Client #{} is slow, try increasing [network.]frame_freq to a higher value!", _frame_counter, cs->client_id);
1793 cs->lag_test = 1;
1796 if (cs->last_frame_server - cs->last_token_frame >= _settings_client.network.max_lag_time) {
1797 /* This is a bad client! It didn't send the right token back within time. */
1798 IConsolePrint(CC_WARNING, "Client #{} (IP: {}) is dropped because it fails to send valid acks.", cs->client_id, cs->GetClientIP());
1799 cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
1800 continue;
1802 break;
1804 case NetworkClientSocket::STATUS_INACTIVE:
1805 case NetworkClientSocket::STATUS_NEWGRFS_CHECK:
1806 case NetworkClientSocket::STATUS_AUTHORIZED:
1807 /* NewGRF check and authorized states should be handled almost instantly.
1808 * So give them some lee-way, likewise for the query with inactive. */
1809 if (lag > _settings_client.network.max_init_time) {
1810 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);
1811 cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
1812 continue;
1814 break;
1816 case NetworkClientSocket::STATUS_MAP_WAIT:
1817 /* Send every two seconds a packet to the client, to make sure
1818 * it knows the server is still there; just someone else is
1819 * still receiving the map. */
1820 if (std::chrono::steady_clock::now() > cs->last_packet + std::chrono::seconds(2)) {
1821 cs->SendWait();
1822 /* We need to reset the timer, as otherwise we will be
1823 * spamming the client. Strictly speaking this variable
1824 * tracks when we last received a packet from the client,
1825 * but as it is waiting, it will not send us any till we
1826 * start sending them data. */
1827 cs->last_packet = std::chrono::steady_clock::now();
1829 break;
1831 case NetworkClientSocket::STATUS_MAP:
1832 /* Downloading the map... this is the amount of time since starting the saving. */
1833 if (lag > _settings_client.network.max_download_time) {
1834 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);
1835 cs->SendError(NETWORK_ERROR_TIMEOUT_MAP);
1836 continue;
1838 break;
1840 case NetworkClientSocket::STATUS_DONE_MAP:
1841 case NetworkClientSocket::STATUS_PRE_ACTIVE:
1842 /* The map has been sent, so this is for loading the map and syncing up. */
1843 if (lag > _settings_client.network.max_join_time) {
1844 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);
1845 cs->SendError(NETWORK_ERROR_TIMEOUT_JOIN);
1846 continue;
1848 break;
1850 case NetworkClientSocket::STATUS_AUTH_GAME:
1851 case NetworkClientSocket::STATUS_AUTH_COMPANY:
1852 /* These don't block? */
1853 if (lag > _settings_client.network.max_password_time) {
1854 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);
1855 cs->SendError(NETWORK_ERROR_TIMEOUT_PASSWORD);
1856 continue;
1858 break;
1860 case NetworkClientSocket::STATUS_END:
1861 /* Bad server/code. */
1862 NOT_REACHED();
1865 if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) {
1866 /* Check if we can send command, and if we have anything in the queue */
1867 NetworkHandleCommandQueue(cs);
1869 /* Send an updated _frame_counter_max to the client */
1870 if (send_frame) cs->SendFrame();
1872 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1873 /* Send a sync-check packet */
1874 if (send_sync) cs->SendSync();
1875 #endif
1880 /** Yearly "callback". Called whenever the year changes. */
1881 void NetworkServerYearlyLoop()
1883 NetworkCheckRestartMap();
1884 NetworkAdminUpdate(ADMIN_FREQUENCY_ANUALLY);
1887 /** Monthly "callback". Called whenever the month changes. */
1888 void NetworkServerMonthlyLoop()
1890 NetworkAutoCleanCompanies();
1891 NetworkAdminUpdate(ADMIN_FREQUENCY_MONTHLY);
1892 if ((_cur_month % 3) == 0) NetworkAdminUpdate(ADMIN_FREQUENCY_QUARTERLY);
1895 /** Daily "callback". Called whenever the date changes. */
1896 void NetworkServerDailyLoop()
1898 NetworkAdminUpdate(ADMIN_FREQUENCY_DAILY);
1899 if ((_date % 7) == 3) NetworkAdminUpdate(ADMIN_FREQUENCY_WEEKLY);
1903 * Get the IP address/hostname of the connected client.
1904 * @return The IP address.
1906 const std::string &ServerNetworkGameSocketHandler::GetClientIP()
1908 return this->client_address.GetHostname();
1911 /** Show the status message of all clients on the console. */
1912 void NetworkServerShowStatusToConsole()
1914 static const char * const stat_str[] = {
1915 "inactive",
1916 "checking NewGRFs",
1917 "authorizing (server password)",
1918 "authorizing (company password)",
1919 "authorized",
1920 "waiting",
1921 "loading map",
1922 "map done",
1923 "ready",
1924 "active"
1926 static_assert(lengthof(stat_str) == NetworkClientSocket::STATUS_END);
1928 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1929 NetworkClientInfo *ci = cs->GetInfo();
1930 if (ci == nullptr) continue;
1931 uint lag = NetworkCalculateLag(cs);
1932 const char *status;
1934 status = (cs->status < (ptrdiff_t)lengthof(stat_str) ? stat_str[cs->status] : "unknown");
1935 IConsolePrint(CC_INFO, "Client #{} name: '{}' status: '{}' frame-lag: {} company: {} IP: {}",
1936 cs->client_id, ci->client_name.c_str(), status, lag,
1937 ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0),
1938 cs->GetClientIP());
1943 * Send Config Update
1945 void NetworkServerSendConfigUpdate()
1947 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1948 if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) cs->SendConfigUpdate();
1952 /** Update the server's NetworkServerGameInfo due to changes in settings. */
1953 void NetworkServerUpdateGameInfo()
1955 if (_network_server) FillStaticNetworkServerGameInfo();
1959 * Tell that a particular company is (not) passworded.
1960 * @param company_id The company that got/removed the password.
1961 * @param passworded Whether the password was received or removed.
1963 void NetworkServerUpdateCompanyPassworded(CompanyID company_id, bool passworded)
1965 if (NetworkCompanyIsPassworded(company_id) == passworded) return;
1967 SB(_network_company_passworded, company_id, 1, !!passworded);
1968 SetWindowClassesDirty(WC_COMPANY);
1970 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1971 if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) cs->SendCompanyUpdate();
1974 NetworkAdminCompanyUpdate(Company::GetIfValid(company_id));
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);
1990 /* No need to waste network resources if the client is in the company already! */
1991 if (ci->client_playas == company_id) return;
1993 ci->client_playas = company_id;
1995 if (client_id == CLIENT_ID_SERVER) {
1996 SetLocalCompany(company_id);
1997 } else {
1998 NetworkClientSocket *cs = NetworkClientSocket::GetByClientID(client_id);
1999 /* When the company isn't authorized we can't move them yet. */
2000 if (cs->status < NetworkClientSocket::STATUS_AUTHORIZED) return;
2001 cs->SendMove(client_id, company_id);
2004 /* announce the client's move */
2005 NetworkUpdateClientInfo(client_id);
2007 NetworkAction action = (company_id == COMPANY_SPECTATOR) ? NETWORK_ACTION_COMPANY_SPECTATOR : NETWORK_ACTION_COMPANY_JOIN;
2008 NetworkServerSendChat(action, DESTTYPE_BROADCAST, 0, "", client_id, company_id + 1);
2010 InvalidateWindowData(WC_CLIENT_LIST, 0);
2014 * Send an rcon reply to the client.
2015 * @param client_id The identifier of the client.
2016 * @param colour_code The colour of the text.
2017 * @param string The actual reply.
2019 void NetworkServerSendRcon(ClientID client_id, TextColour colour_code, const std::string &string)
2021 NetworkClientSocket::GetByClientID(client_id)->SendRConResult(colour_code, string);
2025 * Kick a single client.
2026 * @param client_id The client to kick.
2027 * @param reason In case of kicking a client, specifies the reason for kicking the client.
2029 void NetworkServerKickClient(ClientID client_id, const std::string &reason)
2031 if (client_id == CLIENT_ID_SERVER) return;
2032 NetworkClientSocket::GetByClientID(client_id)->SendError(NETWORK_ERROR_KICKED, reason);
2036 * Ban, or kick, everyone joined from the given client's IP.
2037 * @param client_id The client to check for.
2038 * @param ban Whether to ban or kick.
2039 * @param reason In case of kicking a client, specifies the reason for kicking the client.
2041 uint NetworkServerKickOrBanIP(ClientID client_id, bool ban, const std::string &reason)
2043 return NetworkServerKickOrBanIP(NetworkClientSocket::GetByClientID(client_id)->GetClientIP(), ban, reason);
2047 * Kick or ban someone based on an IP address.
2048 * @param ip The IP address/range to ban/kick.
2049 * @param ban Whether to ban or just kick.
2050 * @param reason In case of kicking a client, specifies the reason for kicking the client.
2052 uint NetworkServerKickOrBanIP(const std::string &ip, bool ban, const std::string &reason)
2054 /* Add address to ban-list */
2055 if (ban) {
2056 bool contains = false;
2057 for (const auto &iter : _network_ban_list) {
2058 if (iter == ip) {
2059 contains = true;
2060 break;
2063 if (!contains) _network_ban_list.emplace_back(ip);
2066 uint n = 0;
2068 /* There can be multiple clients with the same IP, kick them all but don't kill the server,
2069 * or the client doing the rcon. The latter can't be kicked because kicking frees closes
2070 * and subsequently free the connection related instances, which we would be reading from
2071 * and writing to after returning. So we would read or write data from freed memory up till
2072 * the segfault triggers. */
2073 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
2074 if (cs->client_id == CLIENT_ID_SERVER) continue;
2075 if (cs->client_id == _redirect_console_to_client) continue;
2076 if (cs->client_address.IsInNetmask(ip)) {
2077 NetworkServerKickClient(cs->client_id, reason);
2078 n++;
2082 return n;
2086 * Check whether a particular company has clients.
2087 * @param company The company to check.
2088 * @return True if at least one client is joined to the company.
2090 bool NetworkCompanyHasClients(CompanyID company)
2092 for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
2093 if (ci->client_playas == company) return true;
2095 return false;
2100 * Get the name of the client, if the user did not send it yet, Client ID is used.
2101 * @param client_name The variable to write the name to.
2102 * @param last The pointer to the last element of the destination buffer
2104 std::string ServerNetworkGameSocketHandler::GetClientName() const
2106 const NetworkClientInfo *ci = this->GetInfo();
2107 if (ci != nullptr && !ci->client_name.empty()) return ci->client_name;
2109 return fmt::format("Client #{}", this->client_id);
2113 * Print all the clients to the console
2115 void NetworkPrintClients()
2117 for (NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
2118 if (_network_server) {
2119 IConsolePrint(CC_INFO, "Client #{} name: '{}' company: {} IP: {}",
2120 ci->client_id,
2121 ci->client_name,
2122 ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0),
2123 ci->client_id == CLIENT_ID_SERVER ? "server" : NetworkClientSocket::GetByClientID(ci->client_id)->GetClientIP());
2124 } else {
2125 IConsolePrint(CC_INFO, "Client #{} name: '{}' company: {}",
2126 ci->client_id,
2127 ci->client_name,
2128 ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0));
2134 * Perform all the server specific administration of a new company.
2135 * @param c The newly created company; can't be nullptr.
2136 * @param ci The client information of the client that made the company; can be nullptr.
2138 void NetworkServerNewCompany(const Company *c, NetworkClientInfo *ci)
2140 assert(c != nullptr);
2142 if (!_network_server) return;
2144 _network_company_states[c->index].months_empty = 0;
2145 _network_company_states[c->index].password.clear();
2146 NetworkServerUpdateCompanyPassworded(c->index, false);
2148 if (ci != nullptr) {
2149 /* ci is nullptr when replaying, or for AIs. In neither case there is a client. */
2150 ci->client_playas = c->index;
2151 NetworkUpdateClientInfo(ci->client_id);
2152 NetworkSendCommand(0, 0, 0, CMD_RENAME_PRESIDENT, nullptr, ci->client_name, c->index);
2155 /* Announce new company on network. */
2156 NetworkAdminCompanyInfo(c, true);
2158 if (ci != nullptr) {
2159 /* ci is nullptr when replaying, or for AIs. In neither case there is a client.
2160 We need to send Admin port update here so that they first know about the new company
2161 and then learn about a possibly joining client (see FS#6025) */
2162 NetworkServerSendChat(NETWORK_ACTION_COMPANY_NEW, DESTTYPE_BROADCAST, 0, "", ci->client_id, c->index + 1);