Fix: Data races on cursor state in OpenGL backends
[openttd-github.git] / src / network / network_server.cpp
blob86885d59805474a05c060c66056db0cc4e276c16
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 "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 "../roadveh.h"
27 #include "../order_backup.h"
28 #include "../core/pool_func.hpp"
29 #include "../core/random_func.hpp"
30 #include "../rev.h"
31 #include <mutex>
32 #include <condition_variable>
34 #include "../safeguards.h"
37 /* This file handles all the server-commands */
39 DECLARE_POSTFIX_INCREMENT(ClientID)
40 /** The identifier counter for new clients (is never decreased) */
41 static ClientID _network_client_id = CLIENT_ID_FIRST;
43 /** Make very sure the preconditions given in network_type.h are actually followed */
44 static_assert(MAX_CLIENT_SLOTS > MAX_CLIENTS);
45 /** Yes... */
46 static_assert(NetworkClientSocketPool::MAX_SIZE == MAX_CLIENT_SLOTS);
48 /** The pool with clients. */
49 NetworkClientSocketPool _networkclientsocket_pool("NetworkClientSocket");
50 INSTANTIATE_POOL_METHODS(NetworkClientSocket)
52 /** Instantiate the listen sockets. */
53 template SocketList TCPListenHandler<ServerNetworkGameSocketHandler, PACKET_SERVER_FULL, PACKET_SERVER_BANNED>::sockets;
55 /** Writing a savegame directly to a number of packets. */
56 struct PacketWriter : SaveFilter {
57 ServerNetworkGameSocketHandler *cs; ///< Socket we are associated with.
58 Packet *current; ///< The packet we're currently writing to.
59 size_t total_size; ///< Total size of the compressed savegame.
60 Packet *packets; ///< Packet queue of the savegame; send these "slowly" to the client.
61 std::mutex mutex; ///< Mutex for making threaded saving safe.
62 std::condition_variable exit_sig; ///< Signal for threaded destruction of this packet writer.
64 /**
65 * Create the packet writer.
66 * @param cs The socket handler we're making the packets for.
68 PacketWriter(ServerNetworkGameSocketHandler *cs) : SaveFilter(nullptr), cs(cs), current(nullptr), total_size(0), packets(nullptr)
72 /** Make sure everything is cleaned up. */
73 ~PacketWriter()
75 std::unique_lock<std::mutex> lock(this->mutex);
77 if (this->cs != nullptr) this->exit_sig.wait(lock);
79 /* This must all wait until the Destroy function is called. */
81 while (this->packets != nullptr) {
82 Packet *p = this->packets->next;
83 delete this->packets;
84 this->packets = p;
87 delete this->current;
90 /**
91 * Begin the destruction of this packet writer. It can happen in two ways:
92 * in the first case the client disconnected while saving the map. In this
93 * case the saving has not finished and killed this PacketWriter. In that
94 * case we simply set cs to nullptr, triggering the appending to fail due to
95 * the connection problem and eventually triggering the destructor. In the
96 * second case the destructor is already called, and it is waiting for our
97 * signal which we will send. Only then the packets will be removed by the
98 * destructor.
100 void Destroy()
102 std::unique_lock<std::mutex> lock(this->mutex);
104 this->cs = nullptr;
106 this->exit_sig.notify_all();
107 lock.unlock();
109 /* Make sure the saving is completely cancelled. Yes,
110 * we need to handle the save finish as well as the
111 * next connection might just be requesting a map. */
112 WaitTillSaved();
113 ProcessAsyncSaveFinish();
117 * Checks whether there are packets.
118 * It's not 100% threading safe, but this is only asked for when checking
119 * whether there still is something to send. Then another call will be made
120 * to actually get the Packet, which will be the only one popping packets
121 * and thus eventually setting this on false.
123 bool HasPackets()
125 return this->packets != nullptr;
129 * Pop a single created packet from the queue with packets.
131 Packet *PopPacket()
133 std::lock_guard<std::mutex> lock(this->mutex);
135 Packet *p = this->packets;
136 this->packets = p->next;
137 p->next = nullptr;
139 return p;
142 /** Append the current packet to the queue. */
143 void AppendQueue()
145 if (this->current == nullptr) return;
147 Packet **p = &this->packets;
148 while (*p != nullptr) {
149 p = &(*p)->next;
151 *p = this->current;
153 this->current = nullptr;
156 /** Prepend the current packet to the queue. */
157 void PrependQueue()
159 if (this->current == nullptr) return;
161 this->current->next = this->packets;
162 this->packets = this->current;
163 this->current = nullptr;
166 void Write(byte *buf, size_t size) override
168 /* We want to abort the saving when the socket is closed. */
169 if (this->cs == nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
171 if (this->current == nullptr) this->current = new Packet(PACKET_SERVER_MAP_DATA);
173 std::lock_guard<std::mutex> lock(this->mutex);
175 byte *bufe = buf + size;
176 while (buf != bufe) {
177 size_t to_write = std::min<size_t>(SEND_MTU - this->current->size, bufe - buf);
178 memcpy(this->current->buffer + this->current->size, buf, to_write);
179 this->current->size += (PacketSize)to_write;
180 buf += to_write;
182 if (this->current->size == SEND_MTU) {
183 this->AppendQueue();
184 if (buf != bufe) this->current = new Packet(PACKET_SERVER_MAP_DATA);
188 this->total_size += size;
191 void Finish() override
193 /* We want to abort the saving when the socket is closed. */
194 if (this->cs == nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
196 std::lock_guard<std::mutex> lock(this->mutex);
198 /* Make sure the last packet is flushed. */
199 this->AppendQueue();
201 /* Add a packet stating that this is the end to the queue. */
202 this->current = new Packet(PACKET_SERVER_MAP_DONE);
203 this->AppendQueue();
205 /* Fast-track the size to the client. */
206 this->current = new Packet(PACKET_SERVER_MAP_SIZE);
207 this->current->Send_uint32((uint32)this->total_size);
208 this->PrependQueue();
214 * Create a new socket for the server side of the game connection.
215 * @param s The socket to connect with.
217 ServerNetworkGameSocketHandler::ServerNetworkGameSocketHandler(SOCKET s) : NetworkGameSocketHandler(s)
219 this->status = STATUS_INACTIVE;
220 this->client_id = _network_client_id++;
221 this->receive_limit = _settings_client.network.bytes_per_frame_burst;
223 /* The Socket and Info pools need to be the same in size. After all,
224 * each Socket will be associated with at most one Info object. As
225 * such if the Socket was allocated the Info object can as well. */
226 static_assert(NetworkClientSocketPool::MAX_SIZE == NetworkClientInfoPool::MAX_SIZE);
230 * Clear everything related to this client.
232 ServerNetworkGameSocketHandler::~ServerNetworkGameSocketHandler()
234 if (_redirect_console_to_client == this->client_id) _redirect_console_to_client = INVALID_CLIENT_ID;
235 OrderBackup::ResetUser(this->client_id);
237 if (this->savegame != nullptr) {
238 this->savegame->Destroy();
239 this->savegame = nullptr;
243 Packet *ServerNetworkGameSocketHandler::ReceivePacket()
245 /* Only allow receiving when we have some buffer free; this value
246 * can go negative, but eventually it will become positive again. */
247 if (this->receive_limit <= 0) return nullptr;
249 /* We can receive a packet, so try that and if needed account for
250 * the amount of received data. */
251 Packet *p = this->NetworkTCPSocketHandler::ReceivePacket();
252 if (p != nullptr) this->receive_limit -= p->size;
253 return p;
256 NetworkRecvStatus ServerNetworkGameSocketHandler::CloseConnection(NetworkRecvStatus status)
258 assert(status != NETWORK_RECV_STATUS_OKAY);
260 * Sending a message just before leaving the game calls cs->SendPackets.
261 * This might invoke this function, which means that when we close the
262 * connection after cs->SendPackets we will close an already closed
263 * connection. This handles that case gracefully without having to make
264 * that code any more complex or more aware of the validity of the socket.
266 if (this->sock == INVALID_SOCKET) return status;
268 if (status != NETWORK_RECV_STATUS_CONN_LOST && status != NETWORK_RECV_STATUS_SERVER_ERROR && !this->HasClientQuit() && this->status >= STATUS_AUTHORIZED) {
269 /* We did not receive a leave message from this client... */
270 char client_name[NETWORK_CLIENT_NAME_LENGTH];
272 this->GetClientName(client_name, lastof(client_name));
274 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, nullptr, STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST);
276 /* Inform other clients of this... strange leaving ;) */
277 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
278 if (new_cs->status > STATUS_AUTHORIZED && this != new_cs) {
279 new_cs->SendErrorQuit(this->client_id, NETWORK_ERROR_CONNECTION_LOST);
284 /* If we were transfering a map to this client, stop the savegame creation
285 * process and queue the next client to receive the map. */
286 if (this->status == STATUS_MAP) {
287 /* Ensure the saving of the game is stopped too. */
288 this->savegame->Destroy();
289 this->savegame = nullptr;
291 this->CheckNextClientToSendMap(this);
294 NetworkAdminClientError(this->client_id, NETWORK_ERROR_CONNECTION_LOST);
295 DEBUG(net, 1, "Closed client connection %d", this->client_id);
297 /* We just lost one client :( */
298 if (this->status >= STATUS_AUTHORIZED) _network_game_info.clients_on--;
299 extern byte _network_clients_connected;
300 _network_clients_connected--;
302 DeleteWindowById(WC_CLIENT_LIST_POPUP, this->client_id);
303 SetWindowDirty(WC_CLIENT_LIST, 0);
305 this->SendPackets(true);
307 delete this->GetInfo();
308 delete this;
310 return status;
314 * Whether an connection is allowed or not at this moment.
315 * @return true if the connection is allowed.
317 /* static */ bool ServerNetworkGameSocketHandler::AllowConnection()
319 extern byte _network_clients_connected;
320 bool accept = _network_clients_connected < MAX_CLIENTS && _network_game_info.clients_on < _settings_client.network.max_clients;
322 /* We can't go over the MAX_CLIENTS limit here. However, the
323 * pool must have place for all clients and ourself. */
324 static_assert(NetworkClientSocketPool::MAX_SIZE == MAX_CLIENTS + 1);
325 assert(!accept || ServerNetworkGameSocketHandler::CanAllocateItem());
326 return accept;
329 /** Send the packets for the server sockets. */
330 /* static */ void ServerNetworkGameSocketHandler::Send()
332 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
333 if (cs->writable) {
334 if (cs->SendPackets() != SPS_CLOSED && cs->status == STATUS_MAP) {
335 /* This client is in the middle of a map-send, call the function for that */
336 cs->SendMap();
342 static void NetworkHandleCommandQueue(NetworkClientSocket *cs);
344 /***********
345 * Sending functions
346 * DEF_SERVER_SEND_COMMAND has parameter: NetworkClientSocket *cs
347 ************/
350 * Send the client information about a client.
351 * @param ci The client to send information about.
353 NetworkRecvStatus ServerNetworkGameSocketHandler::SendClientInfo(NetworkClientInfo *ci)
355 if (ci->client_id != INVALID_CLIENT_ID) {
356 Packet *p = new Packet(PACKET_SERVER_CLIENT_INFO);
357 p->Send_uint32(ci->client_id);
358 p->Send_uint8 (ci->client_playas);
359 p->Send_string(ci->client_name);
361 this->SendPacket(p);
363 return NETWORK_RECV_STATUS_OKAY;
366 /** Send the client information about the companies. */
367 NetworkRecvStatus ServerNetworkGameSocketHandler::SendCompanyInfo()
369 /* Fetch the latest version of the stats */
370 NetworkCompanyStats company_stats[MAX_COMPANIES];
371 NetworkPopulateCompanyStats(company_stats);
373 /* Make a list of all clients per company */
374 char clients[MAX_COMPANIES][NETWORK_CLIENTS_LENGTH];
375 memset(clients, 0, sizeof(clients));
377 /* Add the local player (if not dedicated) */
378 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
379 if (ci != nullptr && Company::IsValidID(ci->client_playas)) {
380 strecpy(clients[ci->client_playas], ci->client_name, lastof(clients[ci->client_playas]));
383 for (NetworkClientSocket *csi : NetworkClientSocket::Iterate()) {
384 char client_name[NETWORK_CLIENT_NAME_LENGTH];
386 ((ServerNetworkGameSocketHandler*)csi)->GetClientName(client_name, lastof(client_name));
388 ci = csi->GetInfo();
389 if (ci != nullptr && Company::IsValidID(ci->client_playas)) {
390 if (!StrEmpty(clients[ci->client_playas])) {
391 strecat(clients[ci->client_playas], ", ", lastof(clients[ci->client_playas]));
394 strecat(clients[ci->client_playas], client_name, lastof(clients[ci->client_playas]));
398 /* Now send the data */
400 Packet *p;
402 for (const Company *company : Company::Iterate()) {
403 p = new Packet(PACKET_SERVER_COMPANY_INFO);
405 p->Send_uint8 (NETWORK_COMPANY_INFO_VERSION);
406 p->Send_bool (true);
407 this->SendCompanyInformation(p, company, &company_stats[company->index]);
409 if (StrEmpty(clients[company->index])) {
410 p->Send_string("<none>");
411 } else {
412 p->Send_string(clients[company->index]);
415 this->SendPacket(p);
418 p = new Packet(PACKET_SERVER_COMPANY_INFO);
420 p->Send_uint8 (NETWORK_COMPANY_INFO_VERSION);
421 p->Send_bool (false);
423 this->SendPacket(p);
424 return NETWORK_RECV_STATUS_OKAY;
428 * Send an error to the client, and close its connection.
429 * @param error The error to disconnect for.
430 * @param reason In case of kicking a client, specifies the reason for kicking the client.
432 NetworkRecvStatus ServerNetworkGameSocketHandler::SendError(NetworkErrorCode error, const char *reason)
434 char str[100];
435 Packet *p = new Packet(PACKET_SERVER_ERROR);
437 p->Send_uint8(error);
438 if (reason != nullptr) p->Send_string(reason);
439 this->SendPacket(p);
441 StringID strid = GetNetworkErrorMsg(error);
442 GetString(str, strid, lastof(str));
444 /* Only send when the current client was in game */
445 if (this->status > STATUS_AUTHORIZED) {
446 char client_name[NETWORK_CLIENT_NAME_LENGTH];
448 this->GetClientName(client_name, lastof(client_name));
450 DEBUG(net, 1, "'%s' made an error and has been disconnected. Reason: '%s'", client_name, str);
452 if (error == NETWORK_ERROR_KICKED && reason != nullptr) {
453 NetworkTextMessage(NETWORK_ACTION_KICKED, CC_DEFAULT, false, client_name, reason, strid);
454 } else {
455 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, nullptr, strid);
458 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
459 if (new_cs->status >= STATUS_AUTHORIZED && new_cs != this) {
460 /* Some errors we filter to a more general error. Clients don't have to know the real
461 * reason a joining failed. */
462 if (error == NETWORK_ERROR_NOT_AUTHORIZED || error == NETWORK_ERROR_NOT_EXPECTED || error == NETWORK_ERROR_WRONG_REVISION) {
463 error = NETWORK_ERROR_ILLEGAL_PACKET;
465 new_cs->SendErrorQuit(this->client_id, error);
469 NetworkAdminClientError(this->client_id, error);
470 } else {
471 DEBUG(net, 1, "Client %d made an error and has been disconnected. Reason: '%s'", this->client_id, str);
474 /* The client made a mistake, so drop his connection now! */
475 return this->CloseConnection(NETWORK_RECV_STATUS_SERVER_ERROR);
478 /** Send the check for the NewGRFs. */
479 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGRFCheck()
481 Packet *p = new Packet(PACKET_SERVER_CHECK_NEWGRFS);
482 const GRFConfig *c;
483 uint grf_count = 0;
485 for (c = _grfconfig; c != nullptr; c = c->next) {
486 if (!HasBit(c->flags, GCF_STATIC)) grf_count++;
489 p->Send_uint8 (grf_count);
490 for (c = _grfconfig; c != nullptr; c = c->next) {
491 if (!HasBit(c->flags, GCF_STATIC)) this->SendGRFIdentifier(p, &c->ident);
494 this->SendPacket(p);
495 return NETWORK_RECV_STATUS_OKAY;
498 /** Request the game password. */
499 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNeedGamePassword()
501 /* Invalid packet when status is STATUS_AUTH_GAME or higher */
502 if (this->status >= STATUS_AUTH_GAME) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
504 this->status = STATUS_AUTH_GAME;
505 /* Reset 'lag' counters */
506 this->last_frame = this->last_frame_server = _frame_counter;
508 Packet *p = new Packet(PACKET_SERVER_NEED_GAME_PASSWORD);
509 this->SendPacket(p);
510 return NETWORK_RECV_STATUS_OKAY;
513 /** Request the company password. */
514 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNeedCompanyPassword()
516 /* Invalid packet when status is STATUS_AUTH_COMPANY or higher */
517 if (this->status >= STATUS_AUTH_COMPANY) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
519 this->status = STATUS_AUTH_COMPANY;
520 /* Reset 'lag' counters */
521 this->last_frame = this->last_frame_server = _frame_counter;
523 Packet *p = new Packet(PACKET_SERVER_NEED_COMPANY_PASSWORD);
524 p->Send_uint32(_settings_game.game_creation.generation_seed);
525 p->Send_string(_settings_client.network.network_id);
526 this->SendPacket(p);
527 return NETWORK_RECV_STATUS_OKAY;
530 /** Send the client a welcome message with some basic information. */
531 NetworkRecvStatus ServerNetworkGameSocketHandler::SendWelcome()
533 Packet *p;
535 /* Invalid packet when status is AUTH or higher */
536 if (this->status >= STATUS_AUTHORIZED) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
538 this->status = STATUS_AUTHORIZED;
539 /* Reset 'lag' counters */
540 this->last_frame = this->last_frame_server = _frame_counter;
542 _network_game_info.clients_on++;
544 p = new Packet(PACKET_SERVER_WELCOME);
545 p->Send_uint32(this->client_id);
546 p->Send_uint32(_settings_game.game_creation.generation_seed);
547 p->Send_string(_settings_client.network.network_id);
548 this->SendPacket(p);
550 /* Transmit info about all the active clients */
551 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
552 if (new_cs != this && new_cs->status >= STATUS_AUTHORIZED) {
553 this->SendClientInfo(new_cs->GetInfo());
556 /* Also send the info of the server */
557 return this->SendClientInfo(NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER));
560 /** Tell the client that its put in a waiting queue. */
561 NetworkRecvStatus ServerNetworkGameSocketHandler::SendWait()
563 int waiting = 1; // current player getting the map counts as 1
564 Packet *p;
566 /* Count how many clients are waiting in the queue, in front of you! */
567 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
568 if (new_cs->status != STATUS_MAP_WAIT) continue;
569 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++;
572 p = new Packet(PACKET_SERVER_WAIT);
573 p->Send_uint8(waiting);
574 this->SendPacket(p);
575 return NETWORK_RECV_STATUS_OKAY;
578 void ServerNetworkGameSocketHandler::CheckNextClientToSendMap(NetworkClientSocket *ignore_cs)
580 /* Find the best candidate for joining, i.e. the first joiner. */
581 NetworkClientSocket *best = nullptr;
582 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
583 if (ignore_cs == new_cs) continue;
585 if (new_cs->status == STATUS_MAP_WAIT) {
586 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)) {
587 best = new_cs;
592 /* Is there someone else to join? */
593 if (best != nullptr) {
594 /* Let the first start joining. */
595 best->status = STATUS_AUTHORIZED;
596 best->SendMap();
598 /* And update the rest. */
599 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
600 if (new_cs->status == STATUS_MAP_WAIT) new_cs->SendWait();
605 /** This sends the map to the client */
606 NetworkRecvStatus ServerNetworkGameSocketHandler::SendMap()
608 static uint sent_packets; // How many packets we did send successfully last time
610 if (this->status < STATUS_AUTHORIZED) {
611 /* Illegal call, return error and ignore the packet */
612 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
615 if (this->status == STATUS_AUTHORIZED) {
616 this->savegame = new PacketWriter(this);
618 /* Now send the _frame_counter and how many packets are coming */
619 Packet *p = new Packet(PACKET_SERVER_MAP_BEGIN);
620 p->Send_uint32(_frame_counter);
621 this->SendPacket(p);
623 NetworkSyncCommandQueue(this);
624 this->status = STATUS_MAP;
625 /* Mark the start of download */
626 this->last_frame = _frame_counter;
627 this->last_frame_server = _frame_counter;
629 sent_packets = 4; // We start with trying 4 packets
631 /* Make a dump of the current game */
632 if (SaveWithFilter(this->savegame, true) != SL_OK) usererror("network savedump failed");
635 if (this->status == STATUS_MAP) {
636 bool last_packet = false;
637 bool has_packets = false;
639 for (uint i = 0; (has_packets = this->savegame->HasPackets()) && i < sent_packets; i++) {
640 Packet *p = this->savegame->PopPacket();
641 last_packet = p->buffer[2] == PACKET_SERVER_MAP_DONE;
643 this->SendPacket(p);
645 if (last_packet) {
646 /* There is no more data, so break the for */
647 break;
651 if (last_packet) {
652 /* Done reading, make sure saving is done as well */
653 this->savegame->Destroy();
654 this->savegame = nullptr;
656 /* Set the status to DONE_MAP, no we will wait for the client
657 * to send it is ready (maybe that happens like never ;)) */
658 this->status = STATUS_DONE_MAP;
660 this->CheckNextClientToSendMap();
663 switch (this->SendPackets()) {
664 case SPS_CLOSED:
665 return NETWORK_RECV_STATUS_CONN_LOST;
667 case SPS_ALL_SENT:
668 /* All are sent, increase the sent_packets */
669 if (has_packets) sent_packets *= 2;
670 break;
672 case SPS_PARTLY_SENT:
673 /* Only a part is sent; leave the transmission state. */
674 break;
676 case SPS_NONE_SENT:
677 /* Not everything is sent, decrease the sent_packets */
678 if (sent_packets > 1) sent_packets /= 2;
679 break;
682 return NETWORK_RECV_STATUS_OKAY;
686 * Tell that a client joined.
687 * @param client_id The client that joined.
689 NetworkRecvStatus ServerNetworkGameSocketHandler::SendJoin(ClientID client_id)
691 Packet *p = new Packet(PACKET_SERVER_JOIN);
693 p->Send_uint32(client_id);
695 this->SendPacket(p);
696 return NETWORK_RECV_STATUS_OKAY;
699 /** Tell the client that they may run to a particular frame. */
700 NetworkRecvStatus ServerNetworkGameSocketHandler::SendFrame()
702 Packet *p = new Packet(PACKET_SERVER_FRAME);
703 p->Send_uint32(_frame_counter);
704 p->Send_uint32(_frame_counter_max);
705 #ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
706 p->Send_uint32(_sync_seed_1);
707 #ifdef NETWORK_SEND_DOUBLE_SEED
708 p->Send_uint32(_sync_seed_2);
709 #endif
710 #endif
712 /* If token equals 0, we need to make a new token and send that. */
713 if (this->last_token == 0) {
714 this->last_token = InteractiveRandomRange(UINT8_MAX - 1) + 1;
715 p->Send_uint8(this->last_token);
718 this->SendPacket(p);
719 return NETWORK_RECV_STATUS_OKAY;
722 /** Request the client to sync. */
723 NetworkRecvStatus ServerNetworkGameSocketHandler::SendSync()
725 Packet *p = new Packet(PACKET_SERVER_SYNC);
726 p->Send_uint32(_frame_counter);
727 p->Send_uint32(_sync_seed_1);
729 #ifdef NETWORK_SEND_DOUBLE_SEED
730 p->Send_uint32(_sync_seed_2);
731 #endif
732 this->SendPacket(p);
733 return NETWORK_RECV_STATUS_OKAY;
737 * Send a command to the client to execute.
738 * @param cp The command to send.
740 NetworkRecvStatus ServerNetworkGameSocketHandler::SendCommand(const CommandPacket *cp)
742 Packet *p = new Packet(PACKET_SERVER_COMMAND);
744 this->NetworkGameSocketHandler::SendCommand(p, cp);
745 p->Send_uint32(cp->frame);
746 p->Send_bool (cp->my_cmd);
748 this->SendPacket(p);
749 return NETWORK_RECV_STATUS_OKAY;
753 * Send a chat message.
754 * @param action The action associated with the message.
755 * @param client_id The origin of the chat message.
756 * @param self_send Whether we did send the message.
757 * @param msg The actual message.
758 * @param data Arbitrary extra data.
760 NetworkRecvStatus ServerNetworkGameSocketHandler::SendChat(NetworkAction action, ClientID client_id, bool self_send, const char *msg, int64 data)
762 if (this->status < STATUS_PRE_ACTIVE) return NETWORK_RECV_STATUS_OKAY;
764 Packet *p = new Packet(PACKET_SERVER_CHAT);
766 p->Send_uint8 (action);
767 p->Send_uint32(client_id);
768 p->Send_bool (self_send);
769 p->Send_string(msg);
770 p->Send_uint64(data);
772 this->SendPacket(p);
773 return NETWORK_RECV_STATUS_OKAY;
777 * Tell the client another client quit with an error.
778 * @param client_id The client that quit.
779 * @param errorno The reason the client quit.
781 NetworkRecvStatus ServerNetworkGameSocketHandler::SendErrorQuit(ClientID client_id, NetworkErrorCode errorno)
783 Packet *p = new Packet(PACKET_SERVER_ERROR_QUIT);
785 p->Send_uint32(client_id);
786 p->Send_uint8 (errorno);
788 this->SendPacket(p);
789 return NETWORK_RECV_STATUS_OKAY;
793 * Tell the client another client quit.
794 * @param client_id The client that quit.
796 NetworkRecvStatus ServerNetworkGameSocketHandler::SendQuit(ClientID client_id)
798 Packet *p = new Packet(PACKET_SERVER_QUIT);
800 p->Send_uint32(client_id);
802 this->SendPacket(p);
803 return NETWORK_RECV_STATUS_OKAY;
806 /** Tell the client we're shutting down. */
807 NetworkRecvStatus ServerNetworkGameSocketHandler::SendShutdown()
809 Packet *p = new Packet(PACKET_SERVER_SHUTDOWN);
810 this->SendPacket(p);
811 return NETWORK_RECV_STATUS_OKAY;
814 /** Tell the client we're starting a new game. */
815 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGame()
817 Packet *p = new Packet(PACKET_SERVER_NEWGAME);
818 this->SendPacket(p);
819 return NETWORK_RECV_STATUS_OKAY;
823 * Send the result of a console action.
824 * @param colour The colour of the result.
825 * @param command The command that was executed.
827 NetworkRecvStatus ServerNetworkGameSocketHandler::SendRConResult(uint16 colour, const char *command)
829 Packet *p = new Packet(PACKET_SERVER_RCON);
831 p->Send_uint16(colour);
832 p->Send_string(command);
833 this->SendPacket(p);
834 return NETWORK_RECV_STATUS_OKAY;
838 * Tell that a client moved to another company.
839 * @param client_id The client that moved.
840 * @param company_id The company the client moved to.
842 NetworkRecvStatus ServerNetworkGameSocketHandler::SendMove(ClientID client_id, CompanyID company_id)
844 Packet *p = new Packet(PACKET_SERVER_MOVE);
846 p->Send_uint32(client_id);
847 p->Send_uint8(company_id);
848 this->SendPacket(p);
849 return NETWORK_RECV_STATUS_OKAY;
852 /** Send an update about the company password states. */
853 NetworkRecvStatus ServerNetworkGameSocketHandler::SendCompanyUpdate()
855 Packet *p = new Packet(PACKET_SERVER_COMPANY_UPDATE);
857 p->Send_uint16(_network_company_passworded);
858 this->SendPacket(p);
859 return NETWORK_RECV_STATUS_OKAY;
862 /** Send an update about the max company/spectator counts. */
863 NetworkRecvStatus ServerNetworkGameSocketHandler::SendConfigUpdate()
865 Packet *p = new Packet(PACKET_SERVER_CONFIG_UPDATE);
867 p->Send_uint8(_settings_client.network.max_companies);
868 p->Send_uint8(_settings_client.network.max_spectators);
869 this->SendPacket(p);
870 return NETWORK_RECV_STATUS_OKAY;
873 /***********
874 * Receiving functions
875 * DEF_SERVER_RECEIVE_COMMAND has parameter: NetworkClientSocket *cs, Packet *p
876 ************/
878 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMPANY_INFO(Packet *p)
880 return this->SendCompanyInfo();
883 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_NEWGRFS_CHECKED(Packet *p)
885 if (this->status != STATUS_NEWGRFS_CHECK) {
886 /* Illegal call, return error and ignore the packet */
887 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
890 NetworkClientInfo *ci = this->GetInfo();
892 /* We now want a password from the client else we do not allow him in! */
893 if (!StrEmpty(_settings_client.network.server_password)) {
894 return this->SendNeedGamePassword();
897 if (Company::IsValidID(ci->client_playas) && !StrEmpty(_network_company_states[ci->client_playas].password)) {
898 return this->SendNeedCompanyPassword();
901 return this->SendWelcome();
904 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet *p)
906 if (this->status != STATUS_INACTIVE) {
907 /* Illegal call, return error and ignore the packet */
908 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
911 char name[NETWORK_CLIENT_NAME_LENGTH];
912 CompanyID playas;
913 NetworkLanguage client_lang;
914 char client_revision[NETWORK_REVISION_LENGTH];
916 p->Recv_string(client_revision, sizeof(client_revision));
917 uint32 newgrf_version = p->Recv_uint32();
919 /* Check if the client has revision control enabled */
920 if (!IsNetworkCompatibleVersion(client_revision) || _openttd_newgrf_version != newgrf_version) {
921 /* Different revisions!! */
922 return this->SendError(NETWORK_ERROR_WRONG_REVISION);
925 p->Recv_string(name, sizeof(name));
926 playas = (Owner)p->Recv_uint8();
927 client_lang = (NetworkLanguage)p->Recv_uint8();
929 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
931 /* join another company does not affect these values */
932 switch (playas) {
933 case COMPANY_NEW_COMPANY: // New company
934 if (Company::GetNumItems() >= _settings_client.network.max_companies) {
935 return this->SendError(NETWORK_ERROR_FULL);
937 break;
938 case COMPANY_SPECTATOR: // Spectator
939 if (NetworkSpectatorCount() >= _settings_client.network.max_spectators) {
940 return this->SendError(NETWORK_ERROR_FULL);
942 break;
943 default: // Join another company (companies 1-8 (index 0-7))
944 if (!Company::IsValidHumanID(playas)) {
945 return this->SendError(NETWORK_ERROR_COMPANY_MISMATCH);
947 break;
950 /* We need a valid name.. make it Player */
951 if (StrEmpty(name)) strecpy(name, "Player", lastof(name));
953 if (!NetworkFindName(name, lastof(name))) { // Change name if duplicate
954 /* We could not create a name for this client */
955 return this->SendError(NETWORK_ERROR_NAME_IN_USE);
958 assert(NetworkClientInfo::CanAllocateItem());
959 NetworkClientInfo *ci = new NetworkClientInfo(this->client_id);
960 this->SetInfo(ci);
961 ci->join_date = _date;
962 strecpy(ci->client_name, name, lastof(ci->client_name));
963 ci->client_playas = playas;
964 ci->client_lang = client_lang;
965 DEBUG(desync, 1, "client: %08x; %02x; %02x; %02x", _date, _date_fract, (int)ci->client_playas, (int)ci->index);
967 /* Make sure companies to which people try to join are not autocleaned */
968 if (Company::IsValidID(playas)) _network_company_states[playas].months_empty = 0;
970 this->status = STATUS_NEWGRFS_CHECK;
972 if (_grfconfig == nullptr) {
973 /* Behave as if we received PACKET_CLIENT_NEWGRFS_CHECKED */
974 return this->Receive_CLIENT_NEWGRFS_CHECKED(nullptr);
977 return this->SendNewGRFCheck();
980 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GAME_PASSWORD(Packet *p)
982 if (this->status != STATUS_AUTH_GAME) {
983 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
986 char password[NETWORK_PASSWORD_LENGTH];
987 p->Recv_string(password, sizeof(password));
989 /* Check game password. Allow joining if we cleared the password meanwhile */
990 if (!StrEmpty(_settings_client.network.server_password) &&
991 strcmp(password, _settings_client.network.server_password) != 0) {
992 /* Password is invalid */
993 return this->SendError(NETWORK_ERROR_WRONG_PASSWORD);
996 const NetworkClientInfo *ci = this->GetInfo();
997 if (Company::IsValidID(ci->client_playas) && !StrEmpty(_network_company_states[ci->client_playas].password)) {
998 return this->SendNeedCompanyPassword();
1001 /* Valid password, allow user */
1002 return this->SendWelcome();
1005 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMPANY_PASSWORD(Packet *p)
1007 if (this->status != STATUS_AUTH_COMPANY) {
1008 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1011 char password[NETWORK_PASSWORD_LENGTH];
1012 p->Recv_string(password, sizeof(password));
1014 /* Check company password. Allow joining if we cleared the password meanwhile.
1015 * Also, check the company is still valid - client could be moved to spectators
1016 * in the middle of the authorization process */
1017 CompanyID playas = this->GetInfo()->client_playas;
1018 if (Company::IsValidID(playas) && !StrEmpty(_network_company_states[playas].password) &&
1019 strcmp(password, _network_company_states[playas].password) != 0) {
1020 /* Password is invalid */
1021 return this->SendError(NETWORK_ERROR_WRONG_PASSWORD);
1024 return this->SendWelcome();
1027 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GETMAP(Packet *p)
1029 /* The client was never joined.. so this is impossible, right?
1030 * Ignore the packet, give the client a warning, and close his connection */
1031 if (this->status < STATUS_AUTHORIZED || this->HasClientQuit()) {
1032 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
1035 /* Check if someone else is receiving the map */
1036 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
1037 if (new_cs->status == STATUS_MAP) {
1038 /* Tell the new client to wait */
1039 this->status = STATUS_MAP_WAIT;
1040 return this->SendWait();
1044 /* We receive a request to upload the map.. give it to the client! */
1045 return this->SendMap();
1048 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MAP_OK(Packet *p)
1050 /* Client has the map, now start syncing */
1051 if (this->status == STATUS_DONE_MAP && !this->HasClientQuit()) {
1052 char client_name[NETWORK_CLIENT_NAME_LENGTH];
1054 this->GetClientName(client_name, lastof(client_name));
1056 NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, client_name, nullptr, this->client_id);
1058 /* Mark the client as pre-active, and wait for an ACK
1059 * so we know he is done loading and in sync with us */
1060 this->status = STATUS_PRE_ACTIVE;
1061 NetworkHandleCommandQueue(this);
1062 this->SendFrame();
1063 this->SendSync();
1065 /* This is the frame the client receives
1066 * we need it later on to make sure the client is not too slow */
1067 this->last_frame = _frame_counter;
1068 this->last_frame_server = _frame_counter;
1070 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
1071 if (new_cs->status >= STATUS_AUTHORIZED) {
1072 new_cs->SendClientInfo(this->GetInfo());
1073 new_cs->SendJoin(this->client_id);
1077 NetworkAdminClientInfo(this, true);
1079 /* also update the new client with our max values */
1080 this->SendConfigUpdate();
1082 /* quickly update the syncing client with company details */
1083 return this->SendCompanyUpdate();
1086 /* Wrong status for this packet, give a warning to client, and close connection */
1087 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1091 * The client has done a command and wants us to handle it
1092 * @param p the packet in which the command was sent
1094 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMMAND(Packet *p)
1096 /* The client was never joined.. so this is impossible, right?
1097 * Ignore the packet, give the client a warning, and close his connection */
1098 if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
1099 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1102 if (this->incoming_queue.Count() >= _settings_client.network.max_commands_in_queue) {
1103 return this->SendError(NETWORK_ERROR_TOO_MANY_COMMANDS);
1106 CommandPacket cp;
1107 const char *err = this->ReceiveCommand(p, &cp);
1109 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
1111 NetworkClientInfo *ci = this->GetInfo();
1113 if (err != nullptr) {
1114 IConsolePrintF(CC_ERROR, "WARNING: %s from client %d (IP: %s).", err, ci->client_id, this->GetClientIP());
1115 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1119 if ((GetCommandFlags(cp.cmd) & CMD_SERVER) && ci->client_id != CLIENT_ID_SERVER) {
1120 IConsolePrintF(CC_ERROR, "WARNING: server only command %u from client %u (IP: %s), kicking...", cp.cmd & CMD_ID_MASK, ci->client_id, this->GetClientIP());
1121 return this->SendError(NETWORK_ERROR_KICKED);
1124 if ((GetCommandFlags(cp.cmd) & CMD_SPECTATOR) == 0 && !Company::IsValidID(cp.company) && ci->client_id != CLIENT_ID_SERVER) {
1125 IConsolePrintF(CC_ERROR, "WARNING: spectator (client: %u, IP: %s) issued non-spectator command %u, kicking...", ci->client_id, this->GetClientIP(), cp.cmd & CMD_ID_MASK);
1126 return this->SendError(NETWORK_ERROR_KICKED);
1130 * Only CMD_COMPANY_CTRL is always allowed, for the rest, playas needs
1131 * to match the company in the packet. If it doesn't, the client has done
1132 * something pretty naughty (or a bug), and will be kicked
1134 if (!(cp.cmd == CMD_COMPANY_CTRL && cp.p1 == 0 && ci->client_playas == COMPANY_NEW_COMPANY) && ci->client_playas != cp.company) {
1135 IConsolePrintF(CC_ERROR, "WARNING: client %d (IP: %s) tried to execute a command as company %d, kicking...",
1136 ci->client_playas + 1, this->GetClientIP(), cp.company + 1);
1137 return this->SendError(NETWORK_ERROR_COMPANY_MISMATCH);
1140 if (cp.cmd == CMD_COMPANY_CTRL) {
1141 if (cp.p1 != 0 || cp.company != COMPANY_SPECTATOR) {
1142 return this->SendError(NETWORK_ERROR_CHEATER);
1145 /* 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! */
1146 if (Company::GetNumItems() >= _settings_client.network.max_companies) {
1147 NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_CLIENT, ci->client_id, "cannot create new company, server full", CLIENT_ID_SERVER);
1148 return NETWORK_RECV_STATUS_OKAY;
1152 if (GetCommandFlags(cp.cmd) & CMD_CLIENT_ID) cp.p2 = this->client_id;
1154 this->incoming_queue.Append(&cp);
1155 return NETWORK_RECV_STATUS_OKAY;
1158 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ERROR(Packet *p)
1160 /* This packets means a client noticed an error and is reporting this
1161 * to us. Display the error and report it to the other clients */
1162 char str[100];
1163 char client_name[NETWORK_CLIENT_NAME_LENGTH];
1164 NetworkErrorCode errorno = (NetworkErrorCode)p->Recv_uint8();
1166 /* The client was never joined.. thank the client for the packet, but ignore it */
1167 if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
1168 return this->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
1171 this->GetClientName(client_name, lastof(client_name));
1173 StringID strid = GetNetworkErrorMsg(errorno);
1174 GetString(str, strid, lastof(str));
1176 DEBUG(net, 2, "'%s' reported an error and is closing its connection (%s)", client_name, str);
1178 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, nullptr, strid);
1180 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
1181 if (new_cs->status >= STATUS_AUTHORIZED) {
1182 new_cs->SendErrorQuit(this->client_id, errorno);
1186 NetworkAdminClientError(this->client_id, errorno);
1188 return this->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
1191 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_QUIT(Packet *p)
1193 /* The client wants to leave. Display this and report it to the other
1194 * clients. */
1195 char client_name[NETWORK_CLIENT_NAME_LENGTH];
1197 /* The client was never joined.. thank the client for the packet, but ignore it */
1198 if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
1199 return this->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
1202 this->GetClientName(client_name, lastof(client_name));
1204 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, nullptr, STR_NETWORK_MESSAGE_CLIENT_LEAVING);
1206 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
1207 if (new_cs->status >= STATUS_AUTHORIZED && new_cs != this) {
1208 new_cs->SendQuit(this->client_id);
1212 NetworkAdminClientQuit(this->client_id);
1214 return this->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
1217 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ACK(Packet *p)
1219 if (this->status < STATUS_AUTHORIZED) {
1220 /* Illegal call, return error and ignore the packet */
1221 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
1224 uint32 frame = p->Recv_uint32();
1226 /* The client is trying to catch up with the server */
1227 if (this->status == STATUS_PRE_ACTIVE) {
1228 /* The client is not yet caught up? */
1229 if (frame + DAY_TICKS < _frame_counter) return NETWORK_RECV_STATUS_OKAY;
1231 /* Now he is! Unpause the game */
1232 this->status = STATUS_ACTIVE;
1233 this->last_token_frame = _frame_counter;
1235 /* Execute script for, e.g. MOTD */
1236 IConsoleCmdExec("exec scripts/on_server_connect.scr 0");
1239 /* Get, and validate the token. */
1240 uint8 token = p->Recv_uint8();
1241 if (token == this->last_token) {
1242 /* We differentiate between last_token_frame and last_frame so the lag
1243 * test uses the actual lag of the client instead of the lag for getting
1244 * the token back and forth; after all, the token is only sent every
1245 * time we receive a PACKET_CLIENT_ACK, after which we will send a new
1246 * token to the client. If the lag would be one day, then we would not
1247 * be sending the new token soon enough for the new daily scheduled
1248 * PACKET_CLIENT_ACK. This would then register the lag of the client as
1249 * two days, even when it's only a single day. */
1250 this->last_token_frame = _frame_counter;
1251 /* Request a new token. */
1252 this->last_token = 0;
1255 /* The client received the frame, make note of it */
1256 this->last_frame = frame;
1257 /* With those 2 values we can calculate the lag realtime */
1258 this->last_frame_server = _frame_counter;
1259 return NETWORK_RECV_STATUS_OKAY;
1264 * Send an actual chat message.
1265 * @param action The action that's performed.
1266 * @param desttype The type of destination.
1267 * @param dest The actual destination index.
1268 * @param msg The actual message.
1269 * @param from_id The origin of the message.
1270 * @param data Arbitrary data.
1271 * @param from_admin Whether the origin is an admin or not.
1273 void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, const char *msg, ClientID from_id, int64 data, bool from_admin)
1275 const NetworkClientInfo *ci, *ci_own, *ci_to;
1277 switch (desttype) {
1278 case DESTTYPE_CLIENT:
1279 /* Are we sending to the server? */
1280 if ((ClientID)dest == CLIENT_ID_SERVER) {
1281 ci = NetworkClientInfo::GetByClientID(from_id);
1282 /* Display the text locally, and that is it */
1283 if (ci != nullptr) {
1284 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
1286 if (_settings_client.network.server_admin_chat) {
1287 NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
1290 } else {
1291 /* Else find the client to send the message to */
1292 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1293 if (cs->client_id == (ClientID)dest) {
1294 cs->SendChat(action, from_id, false, msg, data);
1295 break;
1300 /* Display the message locally (so you know you have sent it) */
1301 if (from_id != (ClientID)dest) {
1302 if (from_id == CLIENT_ID_SERVER) {
1303 ci = NetworkClientInfo::GetByClientID(from_id);
1304 ci_to = NetworkClientInfo::GetByClientID((ClientID)dest);
1305 if (ci != nullptr && ci_to != nullptr) {
1306 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), true, ci_to->client_name, msg, data);
1308 } else {
1309 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1310 if (cs->client_id == from_id) {
1311 cs->SendChat(action, (ClientID)dest, true, msg, data);
1312 break;
1317 break;
1318 case DESTTYPE_TEAM: {
1319 /* If this is false, the message is already displayed on the client who sent it. */
1320 bool show_local = true;
1321 /* Find all clients that belong to this company */
1322 ci_to = nullptr;
1323 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1324 ci = cs->GetInfo();
1325 if (ci != nullptr && ci->client_playas == (CompanyID)dest) {
1326 cs->SendChat(action, from_id, false, msg, data);
1327 if (cs->client_id == from_id) show_local = false;
1328 ci_to = ci; // Remember a client that is in the company for company-name
1332 /* if the server can read it, let the admin network read it, too. */
1333 if (_local_company == (CompanyID)dest && _settings_client.network.server_admin_chat) {
1334 NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
1337 ci = NetworkClientInfo::GetByClientID(from_id);
1338 ci_own = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
1339 if (ci != nullptr && ci_own != nullptr && ci_own->client_playas == dest) {
1340 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
1341 if (from_id == CLIENT_ID_SERVER) show_local = false;
1342 ci_to = ci_own;
1345 /* There is no such client */
1346 if (ci_to == nullptr) break;
1348 /* Display the message locally (so you know you have sent it) */
1349 if (ci != nullptr && show_local) {
1350 if (from_id == CLIENT_ID_SERVER) {
1351 char name[NETWORK_NAME_LENGTH];
1352 StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
1353 SetDParam(0, ci_to->client_playas);
1354 GetString(name, str, lastof(name));
1355 NetworkTextMessage(action, GetDrawStringCompanyColour(ci_own->client_playas), true, name, msg, data);
1356 } else {
1357 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1358 if (cs->client_id == from_id) {
1359 cs->SendChat(action, ci_to->client_id, true, msg, data);
1364 break;
1366 default:
1367 DEBUG(net, 0, "[server] received unknown chat destination type %d. Doing broadcast instead", desttype);
1368 FALLTHROUGH;
1370 case DESTTYPE_BROADCAST:
1371 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1372 cs->SendChat(action, from_id, false, msg, data);
1375 NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
1377 ci = NetworkClientInfo::GetByClientID(from_id);
1378 if (ci != nullptr) {
1379 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
1381 break;
1385 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_CHAT(Packet *p)
1387 if (this->status < STATUS_PRE_ACTIVE) {
1388 /* Illegal call, return error and ignore the packet */
1389 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
1392 NetworkAction action = (NetworkAction)p->Recv_uint8();
1393 DestType desttype = (DestType)p->Recv_uint8();
1394 int dest = p->Recv_uint32();
1395 char msg[NETWORK_CHAT_LENGTH];
1397 p->Recv_string(msg, NETWORK_CHAT_LENGTH);
1398 int64 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 IConsolePrintF(CC_ERROR, "WARNING: invalid chat action from client %d (IP: %s).", 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_PASSWORD(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 char password[NETWORK_PASSWORD_LENGTH];
1422 const NetworkClientInfo *ci;
1424 p->Recv_string(password, sizeof(password));
1425 ci = this->GetInfo();
1427 NetworkServerSetCompanyPassword(ci->client_playas, password);
1428 return NETWORK_RECV_STATUS_OKAY;
1431 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_NAME(Packet *p)
1433 if (this->status != STATUS_ACTIVE) {
1434 /* Illegal call, return error and ignore the packet */
1435 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1438 char client_name[NETWORK_CLIENT_NAME_LENGTH];
1439 NetworkClientInfo *ci;
1441 p->Recv_string(client_name, sizeof(client_name));
1442 ci = this->GetInfo();
1444 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
1446 if (ci != nullptr) {
1447 /* Display change */
1448 if (NetworkFindName(client_name, lastof(client_name))) {
1449 NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, client_name);
1450 strecpy(ci->client_name, client_name, lastof(ci->client_name));
1451 NetworkUpdateClientInfo(ci->client_id);
1454 return NETWORK_RECV_STATUS_OKAY;
1457 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_RCON(Packet *p)
1459 if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1461 char pass[NETWORK_PASSWORD_LENGTH];
1462 char command[NETWORK_RCONCOMMAND_LENGTH];
1464 if (StrEmpty(_settings_client.network.rcon_password)) return NETWORK_RECV_STATUS_OKAY;
1466 p->Recv_string(pass, sizeof(pass));
1467 p->Recv_string(command, sizeof(command));
1469 if (strcmp(pass, _settings_client.network.rcon_password) != 0) {
1470 DEBUG(net, 0, "[rcon] wrong password from client-id %d", this->client_id);
1471 return NETWORK_RECV_STATUS_OKAY;
1474 DEBUG(net, 0, "[rcon] client-id %d executed: '%s'", this->client_id, command);
1476 _redirect_console_to_client = this->client_id;
1477 IConsoleCmdExec(command);
1478 _redirect_console_to_client = INVALID_CLIENT_ID;
1479 return NETWORK_RECV_STATUS_OKAY;
1482 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MOVE(Packet *p)
1484 if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1486 CompanyID company_id = (Owner)p->Recv_uint8();
1488 /* Check if the company is valid, we don't allow moving to AI companies */
1489 if (company_id != COMPANY_SPECTATOR && !Company::IsValidHumanID(company_id)) return NETWORK_RECV_STATUS_OKAY;
1491 /* Check if we require a password for this company */
1492 if (company_id != COMPANY_SPECTATOR && !StrEmpty(_network_company_states[company_id].password)) {
1493 /* we need a password from the client - should be in this packet */
1494 char password[NETWORK_PASSWORD_LENGTH];
1495 p->Recv_string(password, sizeof(password));
1497 /* Incorrect password sent, return! */
1498 if (strcmp(password, _network_company_states[company_id].password) != 0) {
1499 DEBUG(net, 2, "[move] wrong password from client-id #%d for company #%d", this->client_id, company_id + 1);
1500 return NETWORK_RECV_STATUS_OKAY;
1504 /* if we get here we can move the client */
1505 NetworkServerDoMove(this->client_id, company_id);
1506 return NETWORK_RECV_STATUS_OKAY;
1510 * Package some generic company information into a packet.
1511 * @param p The packet that will contain the data.
1512 * @param c The company to put the of into the packet.
1513 * @param stats The statistics to put in the packet.
1514 * @param max_len The maximum length of the company name.
1516 void NetworkSocketHandler::SendCompanyInformation(Packet *p, const Company *c, const NetworkCompanyStats *stats, uint max_len)
1518 /* Grab the company name */
1519 char company_name[NETWORK_COMPANY_NAME_LENGTH];
1520 SetDParam(0, c->index);
1522 assert(max_len <= lengthof(company_name));
1523 GetString(company_name, STR_COMPANY_NAME, company_name + max_len - 1);
1525 /* Get the income */
1526 Money income = 0;
1527 if (_cur_year - 1 == c->inaugurated_year) {
1528 /* The company is here just 1 year, so display [2], else display[1] */
1529 for (uint i = 0; i < lengthof(c->yearly_expenses[2]); i++) {
1530 income -= c->yearly_expenses[2][i];
1532 } else {
1533 for (uint i = 0; i < lengthof(c->yearly_expenses[1]); i++) {
1534 income -= c->yearly_expenses[1][i];
1538 /* Send the information */
1539 p->Send_uint8 (c->index);
1540 p->Send_string(company_name);
1541 p->Send_uint32(c->inaugurated_year);
1542 p->Send_uint64(c->old_economy[0].company_value);
1543 p->Send_uint64(c->money);
1544 p->Send_uint64(income);
1545 p->Send_uint16(c->old_economy[0].performance_history);
1547 /* Send 1 if there is a password for the company else send 0 */
1548 p->Send_bool (!StrEmpty(_network_company_states[c->index].password));
1550 for (uint i = 0; i < NETWORK_VEH_END; i++) {
1551 p->Send_uint16(stats->num_vehicle[i]);
1554 for (uint i = 0; i < NETWORK_VEH_END; i++) {
1555 p->Send_uint16(stats->num_station[i]);
1558 p->Send_bool(c->is_ai);
1562 * Populate the company stats.
1563 * @param stats the stats to update
1565 void NetworkPopulateCompanyStats(NetworkCompanyStats *stats)
1567 memset(stats, 0, sizeof(*stats) * MAX_COMPANIES);
1569 /* Go through all vehicles and count the type of vehicles */
1570 for (const Vehicle *v : Vehicle::Iterate()) {
1571 if (!Company::IsValidID(v->owner) || !v->IsPrimaryVehicle()) continue;
1572 byte type = 0;
1573 switch (v->type) {
1574 case VEH_TRAIN: type = NETWORK_VEH_TRAIN; break;
1575 case VEH_ROAD: type = RoadVehicle::From(v)->IsBus() ? NETWORK_VEH_BUS : NETWORK_VEH_LORRY; break;
1576 case VEH_AIRCRAFT: type = NETWORK_VEH_PLANE; break;
1577 case VEH_SHIP: type = NETWORK_VEH_SHIP; break;
1578 default: continue;
1580 stats[v->owner].num_vehicle[type]++;
1583 /* Go through all stations and count the types of stations */
1584 for (const Station *s : Station::Iterate()) {
1585 if (Company::IsValidID(s->owner)) {
1586 NetworkCompanyStats *npi = &stats[s->owner];
1588 if (s->facilities & FACIL_TRAIN) npi->num_station[NETWORK_VEH_TRAIN]++;
1589 if (s->facilities & FACIL_TRUCK_STOP) npi->num_station[NETWORK_VEH_LORRY]++;
1590 if (s->facilities & FACIL_BUS_STOP) npi->num_station[NETWORK_VEH_BUS]++;
1591 if (s->facilities & FACIL_AIRPORT) npi->num_station[NETWORK_VEH_PLANE]++;
1592 if (s->facilities & FACIL_DOCK) npi->num_station[NETWORK_VEH_SHIP]++;
1598 * Send updated client info of a particular client.
1599 * @param client_id The client to send it for.
1601 void NetworkUpdateClientInfo(ClientID client_id)
1603 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1605 if (ci == nullptr) return;
1607 DEBUG(desync, 1, "client: %08x; %02x; %02x; %04x", _date, _date_fract, (int)ci->client_playas, client_id);
1609 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1610 if (cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) {
1611 cs->SendClientInfo(ci);
1615 NetworkAdminClientUpdate(ci);
1618 /** Check if we want to restart the map */
1619 static void NetworkCheckRestartMap()
1621 if (_settings_client.network.restart_game_year != 0 && _cur_year >= _settings_client.network.restart_game_year) {
1622 DEBUG(net, 0, "Auto-restarting map. Year %d reached", _cur_year);
1624 _settings_newgame.game_creation.generation_seed = GENERATE_NEW_SEED;
1625 switch(_file_to_saveload.abstract_ftype) {
1626 case FT_SAVEGAME:
1627 case FT_SCENARIO:
1628 _switch_mode = SM_LOAD_GAME;
1629 break;
1631 case FT_HEIGHTMAP:
1632 _switch_mode = SM_START_HEIGHTMAP;
1633 break;
1635 default:
1636 _switch_mode = SM_NEWGAME;
1641 /** Check if the server has autoclean_companies activated
1642 * Two things happen:
1643 * 1) If a company is not protected, it is closed after 1 year (for example)
1644 * 2) If a company is protected, protection is disabled after 3 years (for example)
1645 * (and item 1. happens a year later)
1647 static void NetworkAutoCleanCompanies()
1649 bool clients_in_company[MAX_COMPANIES];
1650 int vehicles_in_company[MAX_COMPANIES];
1652 if (!_settings_client.network.autoclean_companies) return;
1654 memset(clients_in_company, 0, sizeof(clients_in_company));
1656 /* Detect the active companies */
1657 for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1658 if (Company::IsValidID(ci->client_playas)) clients_in_company[ci->client_playas] = true;
1661 if (!_network_dedicated) {
1662 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
1663 if (Company::IsValidID(ci->client_playas)) clients_in_company[ci->client_playas] = true;
1666 if (_settings_client.network.autoclean_novehicles != 0) {
1667 memset(vehicles_in_company, 0, sizeof(vehicles_in_company));
1669 for (const Vehicle *v : Vehicle::Iterate()) {
1670 if (!Company::IsValidID(v->owner) || !v->IsPrimaryVehicle()) continue;
1671 vehicles_in_company[v->owner]++;
1675 /* Go through all the companies */
1676 for (const Company *c : Company::Iterate()) {
1677 /* Skip the non-active once */
1678 if (c->is_ai) continue;
1680 if (!clients_in_company[c->index]) {
1681 /* The company is empty for one month more */
1682 _network_company_states[c->index].months_empty++;
1684 /* Is the company empty for autoclean_unprotected-months, and is there no protection? */
1685 if (_settings_client.network.autoclean_unprotected != 0 && _network_company_states[c->index].months_empty > _settings_client.network.autoclean_unprotected && StrEmpty(_network_company_states[c->index].password)) {
1686 /* Shut the company down */
1687 DoCommandP(0, CCA_DELETE | c->index << 16 | CRR_AUTOCLEAN << 24, 0, CMD_COMPANY_CTRL);
1688 IConsolePrintF(CC_DEFAULT, "Auto-cleaned company #%d with no password", c->index + 1);
1690 /* Is the company empty for autoclean_protected-months, and there is a protection? */
1691 if (_settings_client.network.autoclean_protected != 0 && _network_company_states[c->index].months_empty > _settings_client.network.autoclean_protected && !StrEmpty(_network_company_states[c->index].password)) {
1692 /* Unprotect the company */
1693 _network_company_states[c->index].password[0] = '\0';
1694 IConsolePrintF(CC_DEFAULT, "Auto-removed protection from company #%d", c->index + 1);
1695 _network_company_states[c->index].months_empty = 0;
1696 NetworkServerUpdateCompanyPassworded(c->index, false);
1698 /* Is the company empty for autoclean_novehicles-months, and has no vehicles? */
1699 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) {
1700 /* Shut the company down */
1701 DoCommandP(0, CCA_DELETE | c->index << 16 | CRR_AUTOCLEAN << 24, 0, CMD_COMPANY_CTRL);
1702 IConsolePrintF(CC_DEFAULT, "Auto-cleaned company #%d with no vehicles", c->index + 1);
1704 } else {
1705 /* It is not empty, reset the date */
1706 _network_company_states[c->index].months_empty = 0;
1712 * Check whether a name is unique, and otherwise try to make it unique.
1713 * @param new_name The name to check/modify.
1714 * @param last The last writeable element of the buffer.
1715 * @return True if an unique name was achieved.
1717 bool NetworkFindName(char *new_name, const char *last)
1719 bool found_name = false;
1720 uint number = 0;
1721 char original_name[NETWORK_CLIENT_NAME_LENGTH];
1723 strecpy(original_name, new_name, lastof(original_name));
1725 while (!found_name) {
1726 found_name = true;
1727 for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1728 if (strcmp(ci->client_name, new_name) == 0) {
1729 /* Name already in use */
1730 found_name = false;
1731 break;
1734 /* Check if it is the same as the server-name */
1735 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
1736 if (ci != nullptr) {
1737 if (strcmp(ci->client_name, new_name) == 0) found_name = false; // name already in use
1740 if (!found_name) {
1741 /* Try a new name (<name> #1, <name> #2, and so on) */
1743 /* Something's really wrong when there're more names than clients */
1744 if (number++ > MAX_CLIENTS) break;
1745 seprintf(new_name, last, "%s #%d", original_name, number);
1749 return found_name;
1753 * Change the client name of the given client
1754 * @param client_id the client to change the name of
1755 * @param new_name the new name for the client
1756 * @return true iff the name was changed
1758 bool NetworkServerChangeClientName(ClientID client_id, const char *new_name)
1760 /* Check if the name's already in use */
1761 for (NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1762 if (strcmp(ci->client_name, new_name) == 0) return false;
1765 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1766 if (ci == nullptr) return false;
1768 NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, true, ci->client_name, new_name);
1770 strecpy(ci->client_name, new_name, lastof(ci->client_name));
1772 NetworkUpdateClientInfo(client_id);
1773 return true;
1777 * Set/Reset a company password on the server end.
1778 * @param company_id ID of the company the password should be changed for.
1779 * @param password The new password.
1780 * @param already_hashed Is the given password already hashed?
1782 void NetworkServerSetCompanyPassword(CompanyID company_id, const char *password, bool already_hashed)
1784 if (!Company::IsValidHumanID(company_id)) return;
1786 if (!already_hashed) {
1787 password = GenerateCompanyPasswordHash(password, _settings_client.network.network_id, _settings_game.game_creation.generation_seed);
1790 strecpy(_network_company_states[company_id].password, password, lastof(_network_company_states[company_id].password));
1791 NetworkServerUpdateCompanyPassworded(company_id, !StrEmpty(_network_company_states[company_id].password));
1795 * Handle the command-queue of a socket.
1796 * @param cs The socket to handle the queue for.
1798 static void NetworkHandleCommandQueue(NetworkClientSocket *cs)
1800 CommandPacket *cp;
1801 while ((cp = cs->outgoing_queue.Pop()) != nullptr) {
1802 cs->SendCommand(cp);
1803 free(cp);
1808 * This is called every tick if this is a _network_server
1809 * @param send_frame Whether to send the frame to the clients.
1811 void NetworkServer_Tick(bool send_frame)
1813 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1814 bool send_sync = false;
1815 #endif
1817 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1818 if (_frame_counter >= _last_sync_frame + _settings_client.network.sync_freq) {
1819 _last_sync_frame = _frame_counter;
1820 send_sync = true;
1822 #endif
1824 /* Now we are done with the frame, inform the clients that they can
1825 * do their frame! */
1826 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1827 /* We allow a number of bytes per frame, but only to the burst amount
1828 * to be available for packet receiving at any particular time. */
1829 cs->receive_limit = std::min<int>(cs->receive_limit + _settings_client.network.bytes_per_frame,
1830 _settings_client.network.bytes_per_frame_burst);
1832 /* Check if the speed of the client is what we can expect from a client */
1833 uint lag = NetworkCalculateLag(cs);
1834 switch (cs->status) {
1835 case NetworkClientSocket::STATUS_ACTIVE:
1836 if (lag > _settings_client.network.max_lag_time) {
1837 /* Client did still not report in within the specified limit. */
1838 IConsolePrintF(CC_ERROR, cs->last_packet + std::chrono::milliseconds(lag * MILLISECONDS_PER_TICK) > std::chrono::steady_clock::now() ?
1839 /* A packet was received in the last three game days, so the client is likely lagging behind. */
1840 "Client #%d is dropped because the client's game state is more than %d ticks behind" :
1841 /* No packet was received in the last three game days; sounds like a lost connection. */
1842 "Client #%d is dropped because the client did not respond for more than %d ticks",
1843 cs->client_id, lag);
1844 cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
1845 continue;
1848 /* Report once per time we detect the lag, and only when we
1849 * received a packet in the last 2 seconds. If we
1850 * did not receive a packet, then the client is not just
1851 * slow, but the connection is likely severed. Mentioning
1852 * frame_freq is not useful in this case. */
1853 if (lag > (uint)DAY_TICKS && cs->lag_test == 0 && cs->last_packet + std::chrono::seconds(2) > std::chrono::steady_clock::now()) {
1854 IConsolePrintF(CC_WARNING, "[%d] Client #%d is slow, try increasing [network.]frame_freq to a higher value!", _frame_counter, cs->client_id);
1855 cs->lag_test = 1;
1858 if (cs->last_frame_server - cs->last_token_frame >= _settings_client.network.max_lag_time) {
1859 /* This is a bad client! It didn't send the right token back within time. */
1860 IConsolePrintF(CC_ERROR, "Client #%d is dropped because it fails to send valid acks", cs->client_id);
1861 cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
1862 continue;
1864 break;
1866 case NetworkClientSocket::STATUS_INACTIVE:
1867 case NetworkClientSocket::STATUS_NEWGRFS_CHECK:
1868 case NetworkClientSocket::STATUS_AUTHORIZED:
1869 /* NewGRF check and authorized states should be handled almost instantly.
1870 * So give them some lee-way, likewise for the query with inactive. */
1871 if (lag > _settings_client.network.max_init_time) {
1872 IConsolePrintF(CC_ERROR, "Client #%d is dropped because it took longer than %d ticks to start the joining process", cs->client_id, _settings_client.network.max_init_time);
1873 cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
1874 continue;
1876 break;
1878 case NetworkClientSocket::STATUS_MAP_WAIT:
1879 /* Send every two seconds a packet to the client, to make sure
1880 * he knows the server is still there; just someone else is
1881 * still receiving the map. */
1882 if (std::chrono::steady_clock::now() > cs->last_packet + std::chrono::seconds(2)) {
1883 cs->SendWait();
1884 /* We need to reset the timer, as otherwise we will be
1885 * spamming the client. Strictly speaking this variable
1886 * tracks when we last received a packet from the client,
1887 * but as he is waiting, he will not send us any till we
1888 * start sending him data. */
1889 cs->last_packet = std::chrono::steady_clock::now();
1891 break;
1893 case NetworkClientSocket::STATUS_MAP:
1894 /* Downloading the map... this is the amount of time since starting the saving. */
1895 if (lag > _settings_client.network.max_download_time) {
1896 IConsolePrintF(CC_ERROR, "Client #%d is dropped because it took longer than %d ticks to download the map", cs->client_id, _settings_client.network.max_download_time);
1897 cs->SendError(NETWORK_ERROR_TIMEOUT_MAP);
1898 continue;
1900 break;
1902 case NetworkClientSocket::STATUS_DONE_MAP:
1903 case NetworkClientSocket::STATUS_PRE_ACTIVE:
1904 /* The map has been sent, so this is for loading the map and syncing up. */
1905 if (lag > _settings_client.network.max_join_time) {
1906 IConsolePrintF(CC_ERROR, "Client #%d is dropped because it took longer than %d ticks to join", cs->client_id, _settings_client.network.max_join_time);
1907 cs->SendError(NETWORK_ERROR_TIMEOUT_JOIN);
1908 continue;
1910 break;
1912 case NetworkClientSocket::STATUS_AUTH_GAME:
1913 case NetworkClientSocket::STATUS_AUTH_COMPANY:
1914 /* These don't block? */
1915 if (lag > _settings_client.network.max_password_time) {
1916 IConsolePrintF(CC_ERROR, "Client #%d is dropped because it took longer than %d ticks to enter the password", cs->client_id, _settings_client.network.max_password_time);
1917 cs->SendError(NETWORK_ERROR_TIMEOUT_PASSWORD);
1918 continue;
1920 break;
1922 case NetworkClientSocket::STATUS_END:
1923 /* Bad server/code. */
1924 NOT_REACHED();
1927 if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) {
1928 /* Check if we can send command, and if we have anything in the queue */
1929 NetworkHandleCommandQueue(cs);
1931 /* Send an updated _frame_counter_max to the client */
1932 if (send_frame) cs->SendFrame();
1934 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1935 /* Send a sync-check packet */
1936 if (send_sync) cs->SendSync();
1937 #endif
1941 /* See if we need to advertise */
1942 NetworkUDPAdvertise();
1945 /** Yearly "callback". Called whenever the year changes. */
1946 void NetworkServerYearlyLoop()
1948 NetworkCheckRestartMap();
1949 NetworkAdminUpdate(ADMIN_FREQUENCY_ANUALLY);
1952 /** Monthly "callback". Called whenever the month changes. */
1953 void NetworkServerMonthlyLoop()
1955 NetworkAutoCleanCompanies();
1956 NetworkAdminUpdate(ADMIN_FREQUENCY_MONTHLY);
1957 if ((_cur_month % 3) == 0) NetworkAdminUpdate(ADMIN_FREQUENCY_QUARTERLY);
1960 /** Daily "callback". Called whenever the date changes. */
1961 void NetworkServerDailyLoop()
1963 NetworkAdminUpdate(ADMIN_FREQUENCY_DAILY);
1964 if ((_date % 7) == 3) NetworkAdminUpdate(ADMIN_FREQUENCY_WEEKLY);
1968 * Get the IP address/hostname of the connected client.
1969 * @return The IP address.
1971 const char *ServerNetworkGameSocketHandler::GetClientIP()
1973 return this->client_address.GetHostname();
1976 /** Show the status message of all clients on the console. */
1977 void NetworkServerShowStatusToConsole()
1979 static const char * const stat_str[] = {
1980 "inactive",
1981 "checking NewGRFs",
1982 "authorizing (server password)",
1983 "authorizing (company password)",
1984 "authorized",
1985 "waiting",
1986 "loading map",
1987 "map done",
1988 "ready",
1989 "active"
1991 static_assert(lengthof(stat_str) == NetworkClientSocket::STATUS_END);
1993 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1994 NetworkClientInfo *ci = cs->GetInfo();
1995 if (ci == nullptr) continue;
1996 uint lag = NetworkCalculateLag(cs);
1997 const char *status;
1999 status = (cs->status < (ptrdiff_t)lengthof(stat_str) ? stat_str[cs->status] : "unknown");
2000 IConsolePrintF(CC_INFO, "Client #%1d name: '%s' status: '%s' frame-lag: %3d company: %1d IP: %s",
2001 cs->client_id, ci->client_name, status, lag,
2002 ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0),
2003 cs->GetClientIP());
2008 * Send Config Update
2010 void NetworkServerSendConfigUpdate()
2012 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
2013 if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) cs->SendConfigUpdate();
2018 * Tell that a particular company is (not) passworded.
2019 * @param company_id The company that got/removed the password.
2020 * @param passworded Whether the password was received or removed.
2022 void NetworkServerUpdateCompanyPassworded(CompanyID company_id, bool passworded)
2024 if (NetworkCompanyIsPassworded(company_id) == passworded) return;
2026 SB(_network_company_passworded, company_id, 1, !!passworded);
2027 SetWindowClassesDirty(WC_COMPANY);
2029 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
2030 if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) cs->SendCompanyUpdate();
2033 NetworkAdminCompanyUpdate(Company::GetIfValid(company_id));
2037 * Handle the tid-bits of moving a client from one company to another.
2038 * @param client_id id of the client we want to move.
2039 * @param company_id id of the company we want to move the client to.
2040 * @return void
2042 void NetworkServerDoMove(ClientID client_id, CompanyID company_id)
2044 /* Only allow non-dedicated servers and normal clients to be moved */
2045 if (client_id == CLIENT_ID_SERVER && _network_dedicated) return;
2047 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
2049 /* No need to waste network resources if the client is in the company already! */
2050 if (ci->client_playas == company_id) return;
2052 ci->client_playas = company_id;
2054 if (client_id == CLIENT_ID_SERVER) {
2055 SetLocalCompany(company_id);
2056 } else {
2057 NetworkClientSocket *cs = NetworkClientSocket::GetByClientID(client_id);
2058 /* When the company isn't authorized we can't move them yet. */
2059 if (cs->status < NetworkClientSocket::STATUS_AUTHORIZED) return;
2060 cs->SendMove(client_id, company_id);
2063 /* announce the client's move */
2064 NetworkUpdateClientInfo(client_id);
2066 NetworkAction action = (company_id == COMPANY_SPECTATOR) ? NETWORK_ACTION_COMPANY_SPECTATOR : NETWORK_ACTION_COMPANY_JOIN;
2067 NetworkServerSendChat(action, DESTTYPE_BROADCAST, 0, "", client_id, company_id + 1);
2071 * Send an rcon reply to the client.
2072 * @param client_id The identifier of the client.
2073 * @param colour_code The colour of the text.
2074 * @param string The actual reply.
2076 void NetworkServerSendRcon(ClientID client_id, TextColour colour_code, const char *string)
2078 NetworkClientSocket::GetByClientID(client_id)->SendRConResult(colour_code, string);
2082 * Kick a single client.
2083 * @param client_id The client to kick.
2084 * @param reason In case of kicking a client, specifies the reason for kicking the client.
2086 void NetworkServerKickClient(ClientID client_id, const char *reason)
2088 if (client_id == CLIENT_ID_SERVER) return;
2089 NetworkClientSocket::GetByClientID(client_id)->SendError(NETWORK_ERROR_KICKED, reason);
2093 * Ban, or kick, everyone joined from the given client's IP.
2094 * @param client_id The client to check for.
2095 * @param ban Whether to ban or kick.
2096 * @param reason In case of kicking a client, specifies the reason for kicking the client.
2098 uint NetworkServerKickOrBanIP(ClientID client_id, bool ban, const char *reason)
2100 return NetworkServerKickOrBanIP(NetworkClientSocket::GetByClientID(client_id)->GetClientIP(), ban, reason);
2104 * Kick or ban someone based on an IP address.
2105 * @param ip The IP address/range to ban/kick.
2106 * @param ban Whether to ban or just kick.
2107 * @param reason In case of kicking a client, specifies the reason for kicking the client.
2109 uint NetworkServerKickOrBanIP(const char *ip, bool ban, const char *reason)
2111 /* Add address to ban-list */
2112 if (ban) {
2113 bool contains = false;
2114 for (const auto &iter : _network_ban_list) {
2115 if (iter == ip) {
2116 contains = true;
2117 break;
2120 if (!contains) _network_ban_list.emplace_back(ip);
2123 uint n = 0;
2125 /* There can be multiple clients with the same IP, kick them all but don't kill the server,
2126 * or the client doing the rcon. The latter can't be kicked because kicking frees closes
2127 * and subsequently free the connection related instances, which we would be reading from
2128 * and writing to after returning. So we would read or write data from freed memory up till
2129 * the segfault triggers. */
2130 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
2131 if (cs->client_id == CLIENT_ID_SERVER) continue;
2132 if (cs->client_id == _redirect_console_to_client) continue;
2133 if (cs->client_address.IsInNetmask(ip)) {
2134 NetworkServerKickClient(cs->client_id, reason);
2135 n++;
2139 return n;
2143 * Check whether a particular company has clients.
2144 * @param company The company to check.
2145 * @return True if at least one client is joined to the company.
2147 bool NetworkCompanyHasClients(CompanyID company)
2149 for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
2150 if (ci->client_playas == company) return true;
2152 return false;
2157 * Get the name of the client, if the user did not send it yet, Client ID is used.
2158 * @param client_name The variable to write the name to.
2159 * @param last The pointer to the last element of the destination buffer
2161 void ServerNetworkGameSocketHandler::GetClientName(char *client_name, const char *last) const
2163 const NetworkClientInfo *ci = this->GetInfo();
2165 if (ci == nullptr || StrEmpty(ci->client_name)) {
2166 seprintf(client_name, last, "Client #%4d", this->client_id);
2167 } else {
2168 strecpy(client_name, ci->client_name, last);
2173 * Print all the clients to the console
2175 void NetworkPrintClients()
2177 for (NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
2178 if (_network_server) {
2179 IConsolePrintF(CC_INFO, "Client #%1d name: '%s' company: %1d IP: %s",
2180 ci->client_id,
2181 ci->client_name,
2182 ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0),
2183 ci->client_id == CLIENT_ID_SERVER ? "server" : NetworkClientSocket::GetByClientID(ci->client_id)->GetClientIP());
2184 } else {
2185 IConsolePrintF(CC_INFO, "Client #%1d name: '%s' company: %1d",
2186 ci->client_id,
2187 ci->client_name,
2188 ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0));
2194 * Perform all the server specific administration of a new company.
2195 * @param c The newly created company; can't be nullptr.
2196 * @param ci The client information of the client that made the company; can be nullptr.
2198 void NetworkServerNewCompany(const Company *c, NetworkClientInfo *ci)
2200 assert(c != nullptr);
2202 if (!_network_server) return;
2204 _network_company_states[c->index].months_empty = 0;
2205 _network_company_states[c->index].password[0] = '\0';
2206 NetworkServerUpdateCompanyPassworded(c->index, false);
2208 if (ci != nullptr) {
2209 /* ci is nullptr when replaying, or for AIs. In neither case there is a client. */
2210 ci->client_playas = c->index;
2211 NetworkUpdateClientInfo(ci->client_id);
2212 NetworkSendCommand(0, 0, 0, CMD_RENAME_PRESIDENT, nullptr, ci->client_name, c->index);
2215 /* Announce new company on network. */
2216 NetworkAdminCompanyInfo(c, true);
2218 if (ci != nullptr) {
2219 /* ci is nullptr when replaying, or for AIs. In neither case there is a client.
2220 We need to send Admin port update here so that they first know about the new company
2221 and then learn about a possibly joining client (see FS#6025) */
2222 NetworkServerSendChat(NETWORK_ACTION_COMPANY_NEW, DESTTYPE_BROADCAST, 0, "", ci->client_id, c->index + 1);