OpenTTD Source: src/network/network_server.cpp Source File

OpenTTD Source 15.3

network_server.cpp
Go to the documentation of this file.
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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
10#include "../stdafx.h"
11#include "../strings_func.h"
12#include "core/network_game_info.h"
13#include "network_admin.h"
14#include "network_server.h"
15#include "network_udp.h"
16#include "network_base.h"
17#include "../console_func.h"
18#include "../company_base.h"
19#include "../command_func.h"
20#include "../saveload/saveload.h"
21#include "../saveload/saveload_filter.h"
22#include "../station_base.h"
23#include "../genworld.h"
24#include "../company_func.h"
25#include "../company_gui.h"
26#include "../company_cmd.h"
27#include "../roadveh.h"
28#include "../order_backup.h"
29#include "../core/pool_func.hpp"
30#include "../core/random_func.hpp"
31#include "../company_cmd.h"
32#include "../rev.h"
33#include "../timer/timer.h"
34#include "../timer/timer_game_calendar.h"
35#include "../timer/timer_game_economy.h"
36#include "../timer/timer_game_realtime.h"
37#include <mutex>
38#include <condition_variable>
39
40#include "table/strings.h"
41
42#include "../safeguards.h"
43
44
45/* This file handles all the server-commands */
46
47 DECLARE_INCREMENT_DECREMENT_OPERATORS(ClientID)
49static ClientID _network_client_id = CLIENT_ID_FIRST;
50
52static_assert(NetworkClientSocketPool::MAX_SIZE > MAX_CLIENTS);
53
55 NetworkClientSocketPool _networkclientsocket_pool("NetworkClientSocket");
56 INSTANTIATE_POOL_METHODS(NetworkClientSocket)
57
59template SocketList TCPListenHandler<ServerNetworkGameSocketHandler, PACKET_SERVER_FULL, PACKET_SERVER_BANNED>::sockets;
60
61static NetworkAuthenticationDefaultPasswordProvider _password_provider(_settings_client.network.server_password);
62static NetworkAuthenticationDefaultAuthorizedKeyHandler _authorized_key_handler(_settings_client.network.server_authorized_keys);
63static NetworkAuthenticationDefaultAuthorizedKeyHandler _rcon_authorized_key_handler(_settings_client.network.rcon_authorized_keys);
64
65
67struct PacketWriter : SaveFilter {
68 ServerNetworkGameSocketHandler *cs;
69 std::unique_ptr<Packet> current;
70 size_t total_size;
71 std::deque<std::unique_ptr<Packet>> packets;
72 std::mutex mutex;
73 std::condition_variable exit_sig;
74
79 PacketWriter(ServerNetworkGameSocketHandler *cs) : SaveFilter(nullptr), cs(cs), total_size(0)
80 {
81 }
82
84 ~PacketWriter()
85 {
86 std::unique_lock<std::mutex> lock(this->mutex);
87
88 while (this->cs != nullptr) this->exit_sig.wait(lock);
89
90 /* This must all wait until the Destroy function is called. */
91
92 this->packets.clear();
93 this->current = nullptr;
94 }
95
106 void Destroy()
107 {
108 std::unique_lock<std::mutex> lock(this->mutex);
109
110 this->cs = nullptr;
111
112 this->exit_sig.notify_all();
113 lock.unlock();
114
115 /* Make sure the saving is completely cancelled. Yes,
116 * we need to handle the save finish as well as the
117 * next connection might just be requesting a map. */
118 WaitTillSaved();
119 }
120
126 bool TransferToNetworkQueue()
127 {
128 /* Unsafe check for the queue being empty or not. */
129 if (this->packets.empty()) return false;
130
131 std::lock_guard<std::mutex> lock(this->mutex);
132
133 while (!this->packets.empty()) {
134 bool last_packet = this->packets.front()->GetPacketType() == PACKET_SERVER_MAP_DONE;
135 this->cs->SendPacket(std::move(this->packets.front()));
136 this->packets.pop_front();
137
138 if (last_packet) return true;
139 }
140
141 return false;
142 }
143
144 void Write(uint8_t *buf, size_t size) override
145 {
146 std::lock_guard<std::mutex> lock(this->mutex);
147
148 /* We want to abort the saving when the socket is closed. */
149 if (this->cs == nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
150
151 if (this->current == nullptr) this->current = std::make_unique<Packet>(this->cs, PACKET_SERVER_MAP_DATA, TCP_MTU);
152
153 std::span<const uint8_t> to_write(buf, size);
154 while (!to_write.empty()) {
155 to_write = this->current->Send_bytes(to_write);
156
157 if (!this->current->CanWriteToPacket(1)) {
158 this->packets.push_back(std::move(this->current));
159 if (!to_write.empty()) this->current = std::make_unique<Packet>(this->cs, PACKET_SERVER_MAP_DATA, TCP_MTU);
160 }
161 }
162
163 this->total_size += size;
164 }
165
166 void Finish() override
167 {
168 std::lock_guard<std::mutex> lock(this->mutex);
169
170 /* We want to abort the saving when the socket is closed. */
171 if (this->cs == nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
172
173 /* Make sure the last packet is flushed. */
174 if (this->current != nullptr) this->packets.push_back(std::move(this->current));
175
176 /* Add a packet stating that this is the end to the queue. */
177 this->packets.push_back(std::make_unique<Packet>(this->cs, PACKET_SERVER_MAP_DONE));
178
179 /* Fast-track the size to the client. */
180 auto p = std::make_unique<Packet>(this->cs, PACKET_SERVER_MAP_SIZE);
181 p->Send_uint32((uint32_t)this->total_size);
182 this->packets.push_front(std::move(p));
183 }
184};
185
186
191ServerNetworkGameSocketHandler::ServerNetworkGameSocketHandler(SOCKET s) : NetworkGameSocketHandler(s)
192{
193 this->client_id = _network_client_id++;
194 this->receive_limit = _settings_client.network.bytes_per_frame_burst;
195
196 Debug(net, 9, "client[{}] status = INACTIVE", this->client_id);
197
198 /* The Socket and Info pools need to be the same in size. After all,
199 * each Socket will be associated with at most one Info object. As
200 * such if the Socket was allocated the Info object can as well. */
201 static_assert(NetworkClientSocketPool::MAX_SIZE == NetworkClientInfoPool::MAX_SIZE);
202}
203
207ServerNetworkGameSocketHandler::~ServerNetworkGameSocketHandler()
208{
209 delete this->GetInfo();
210
211 if (_redirect_console_to_client == this->client_id) _redirect_console_to_client = INVALID_CLIENT_ID;
212 OrderBackup::ResetUser(this->client_id);
213
214 if (this->savegame != nullptr) {
215 this->savegame->Destroy();
216 this->savegame = nullptr;
217 }
218
219 InvalidateWindowData(WC_CLIENT_LIST, 0);
220}
221
222std::unique_ptr<Packet> ServerNetworkGameSocketHandler::ReceivePacket()
223{
224 /* Only allow receiving when we have some buffer free; this value
225 * can go negative, but eventually it will become positive again. */
226 if (this->receive_limit <= 0) return nullptr;
227
228 /* We can receive a packet, so try that and if needed account for
229 * the amount of received data. */
230 std::unique_ptr<Packet> p = this->NetworkTCPSocketHandler::ReceivePacket();
231 if (p != nullptr) this->receive_limit -= p->Size();
232 return p;
233}
234
235 NetworkRecvStatus ServerNetworkGameSocketHandler::CloseConnection(NetworkRecvStatus status)
236{
237 assert(status != NETWORK_RECV_STATUS_OKAY);
238 /*
239 * Sending a message just before leaving the game calls cs->SendPackets.
240 * This might invoke this function, which means that when we close the
241 * connection after cs->SendPackets we will close an already closed
242 * connection. This handles that case gracefully without having to make
243 * that code any more complex or more aware of the validity of the socket.
244 */
245 if (this->IsPendingDeletion() || this->sock == INVALID_SOCKET) return status;
246
247 if (status != NETWORK_RECV_STATUS_CLIENT_QUIT && status != NETWORK_RECV_STATUS_SERVER_ERROR && !this->HasClientQuit() && this->status >= STATUS_AUTHORIZED) {
248 /* We did not receive a leave message from this client... */
249 std::string client_name = this->GetClientName();
250
251 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, "", STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST);
252
253 /* Inform other clients of this... strange leaving ;) */
254 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
255 if (new_cs->status >= STATUS_AUTHORIZED && this != new_cs) {
256 new_cs->SendErrorQuit(this->client_id, NETWORK_ERROR_CONNECTION_LOST);
257 }
258 }
259 }
260
261 /* If we were transferring a map to this client, stop the savegame creation
262 * process and queue the next client to receive the map. */
263 if (this->status == STATUS_MAP) {
264 /* Ensure the saving of the game is stopped too. */
265 this->savegame->Destroy();
266 this->savegame = nullptr;
267
268 this->CheckNextClientToSendMap(this);
269 }
270
271 NetworkAdminClientError(this->client_id, NETWORK_ERROR_CONNECTION_LOST);
272 Debug(net, 3, "[{}] Client #{} closed connection", ServerNetworkGameSocketHandler::GetName(), this->client_id);
273
274 /* We just lost one client :( */
275 if (this->status >= STATUS_AUTHORIZED) _network_game_info.clients_on--;
276 extern uint8_t _network_clients_connected;
277 _network_clients_connected--;
278
279 this->SendPackets(true);
280
281 this->DeferDeletion();
282
283 return status;
284}
285
290/* static */ bool ServerNetworkGameSocketHandler::AllowConnection()
291{
292 extern uint8_t _network_clients_connected;
293 bool accept = _network_clients_connected < MAX_CLIENTS;
294
295 /* We can't go over the MAX_CLIENTS limit here. However, the
296 * pool must have place for all clients and ourself. */
297 static_assert(NetworkClientSocketPool::MAX_SIZE == MAX_CLIENTS + 1);
298 assert(!accept || ServerNetworkGameSocketHandler::CanAllocateItem());
299 return accept;
300}
301
303/* static */ void ServerNetworkGameSocketHandler::Send()
304{
305 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
306 if (cs->writable) {
307 if (cs->SendPackets() != SPS_CLOSED && cs->status == STATUS_MAP) {
308 /* This client is in the middle of a map-send, call the function for that */
309 cs->SendMap();
310 }
311 }
312 }
313}
314
315static void NetworkHandleCommandQueue(NetworkClientSocket *cs);
316
317/***********
318 * Sending functions
319 ************/
320
325 NetworkRecvStatus ServerNetworkGameSocketHandler::SendClientInfo(NetworkClientInfo *ci)
326{
327 Debug(net, 9, "client[{}] SendClientInfo(): client_id={}", this->client_id, ci->client_id);
328
329 if (ci->client_id != INVALID_CLIENT_ID) {
330 auto p = std::make_unique<Packet>(this, PACKET_SERVER_CLIENT_INFO);
331 p->Send_uint32(ci->client_id);
332 p->Send_uint8 (ci->client_playas);
333 p->Send_string(ci->client_name);
334 p->Send_string(ci->public_key);
335
336 this->SendPacket(std::move(p));
337 }
338 return NETWORK_RECV_STATUS_OKAY;
339}
340
342 NetworkRecvStatus ServerNetworkGameSocketHandler::SendGameInfo()
343{
344 Debug(net, 9, "client[{}] SendGameInfo()", this->client_id);
345
346 auto p = std::make_unique<Packet>(this, PACKET_SERVER_GAME_INFO, TCP_MTU);
347 SerializeNetworkGameInfo(*p, GetCurrentNetworkServerGameInfo());
348
349 this->SendPacket(std::move(p));
350
351 return NETWORK_RECV_STATUS_OKAY;
352}
353
359 NetworkRecvStatus ServerNetworkGameSocketHandler::SendError(NetworkErrorCode error, std::string_view reason)
360{
361 Debug(net, 9, "client[{}] SendError(): error={}", this->client_id, error);
362
363 auto p = std::make_unique<Packet>(this, PACKET_SERVER_ERROR);
364
365 p->Send_uint8(error);
366 if (!reason.empty()) p->Send_string(reason);
367 this->SendPacket(std::move(p));
368
369 StringID strid = GetNetworkErrorMsg(error);
370
371 /* Only send when the current client was in game */
372 if (this->status >= STATUS_AUTHORIZED) {
373 std::string client_name = this->GetClientName();
374
375 Debug(net, 1, "'{}' made an error and has been disconnected: {}", client_name, GetString(strid));
376
377 if (error == NETWORK_ERROR_KICKED && !reason.empty()) {
378 NetworkTextMessage(NETWORK_ACTION_KICKED, CC_DEFAULT, false, client_name, reason, strid);
379 } else {
380 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, "", strid);
381 }
382
383 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
384 if (new_cs->status >= STATUS_AUTHORIZED && new_cs != this) {
385 /* Some errors we filter to a more general error. Clients don't have to know the real
386 * reason a joining failed. */
387 if (error == NETWORK_ERROR_NOT_AUTHORIZED || error == NETWORK_ERROR_NOT_EXPECTED || error == NETWORK_ERROR_WRONG_REVISION) {
388 error = NETWORK_ERROR_ILLEGAL_PACKET;
389 }
390 new_cs->SendErrorQuit(this->client_id, error);
391 }
392 }
393
394 NetworkAdminClientError(this->client_id, error);
395 } else {
396 Debug(net, 1, "Client {} made an error and has been disconnected: {}", this->client_id, GetString(strid));
397 }
398
399 /* The client made a mistake, so drop the connection now! */
400 return this->CloseConnection(NETWORK_RECV_STATUS_SERVER_ERROR);
401}
402
404 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGRFCheck()
405{
406 Debug(net, 9, "client[{}] SendNewGRFCheck()", this->client_id);
407
408 /* Invalid packet when status is anything but STATUS_IDENTIFY. */
409 if (this->status != STATUS_IDENTIFY) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
410
411 Debug(net, 9, "client[{}] status = NEWGRFS_CHECK", this->client_id);
412 this->status = STATUS_NEWGRFS_CHECK;
413
414 if (_grfconfig.empty()) {
415 /* There are no NewGRFs, so they're welcome. */
416 return this->SendWelcome();
417 }
418
419 auto p = std::make_unique<Packet>(this, PACKET_SERVER_CHECK_NEWGRFS, TCP_MTU);
420
421 uint grf_count = std::ranges::count_if(_grfconfig, [](const auto &c){ return !c->flags.Test(GRFConfigFlag::Static); });
422 p->Send_uint8 (grf_count);
423
424 for (const auto &c : _grfconfig) {
425 if (!c->flags.Test(GRFConfigFlag::Static)) SerializeGRFIdentifier(*p, c->ident);
426 }
427
428 this->SendPacket(std::move(p));
429 return NETWORK_RECV_STATUS_OKAY;
430}
431
433 NetworkRecvStatus ServerNetworkGameSocketHandler::SendAuthRequest()
434{
435 Debug(net, 9, "client[{}] SendAuthRequest()", this->client_id);
436
437 /* Invalid packet when status is anything but STATUS_INACTIVE or STATUS_AUTH_GAME. */
438 if (this->status != STATUS_INACTIVE && status != STATUS_AUTH_GAME) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
439
440 Debug(net, 9, "client[{}] status = AUTH_GAME", this->client_id);
441 this->status = STATUS_AUTH_GAME;
442
443 /* Reset 'lag' counters */
444 this->last_frame = this->last_frame_server = _frame_counter;
445
446 if (this->authentication_handler == nullptr) {
447 this->authentication_handler = NetworkAuthenticationServerHandler::Create(&_password_provider, &_authorized_key_handler);
448 }
449
450 auto p = std::make_unique<Packet>(this, PACKET_SERVER_AUTH_REQUEST);
451 this->authentication_handler->SendRequest(*p);
452
453 this->SendPacket(std::move(p));
454 return NETWORK_RECV_STATUS_OKAY;
455}
456
458 NetworkRecvStatus ServerNetworkGameSocketHandler::SendEnableEncryption()
459{
460 Debug(net, 9, "client[{}] SendEnableEncryption()", this->client_id);
461
462 /* Invalid packet when status is anything but STATUS_AUTH_GAME. */
463 if (this->status != STATUS_AUTH_GAME) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
464
465 auto p = std::make_unique<Packet>(this, PACKET_SERVER_ENABLE_ENCRYPTION);
466 this->authentication_handler->SendEnableEncryption(*p);
467 this->SendPacket(std::move(p));
468 return NETWORK_RECV_STATUS_OKAY;
469}
470
472 NetworkRecvStatus ServerNetworkGameSocketHandler::SendWelcome()
473{
474 Debug(net, 9, "client[{}] SendWelcome()", this->client_id);
475
476 /* Invalid packet when status is anything but STATUS_NEWGRFS_CHECK. */
477 if (this->status != STATUS_NEWGRFS_CHECK) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
478
479 Debug(net, 9, "client[{}] status = AUTHORIZED", this->client_id);
480 this->status = STATUS_AUTHORIZED;
481
482 /* Reset 'lag' counters */
483 this->last_frame = this->last_frame_server = _frame_counter;
484
485 _network_game_info.clients_on++;
486
487 auto p = std::make_unique<Packet>(this, PACKET_SERVER_WELCOME);
488 p->Send_uint32(this->client_id);
489 this->SendPacket(std::move(p));
490
491 /* Transmit info about all the active clients */
492 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
493 if (new_cs != this && new_cs->status >= STATUS_AUTHORIZED) {
494 this->SendClientInfo(new_cs->GetInfo());
495 }
496 }
497 /* Also send the info of the server */
498 return this->SendClientInfo(NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER));
499}
500
502 NetworkRecvStatus ServerNetworkGameSocketHandler::SendWait()
503{
504 Debug(net, 9, "client[{}] SendWait()", this->client_id);
505
506 int waiting = 1; // current player getting the map counts as 1
507
508 /* Count how many clients are waiting in the queue, in front of you! */
509 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
510 if (new_cs->status != STATUS_MAP_WAIT) continue;
511 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++;
512 }
513
514 auto p = std::make_unique<Packet>(this, PACKET_SERVER_WAIT);
515 p->Send_uint8(waiting);
516 this->SendPacket(std::move(p));
517 return NETWORK_RECV_STATUS_OKAY;
518}
519
520void ServerNetworkGameSocketHandler::CheckNextClientToSendMap(NetworkClientSocket *ignore_cs)
521{
522 Debug(net, 9, "client[{}] CheckNextClientToSendMap()", this->client_id);
523
524 /* Find the best candidate for joining, i.e. the first joiner. */
525 NetworkClientSocket *best = nullptr;
526 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
527 if (ignore_cs == new_cs) continue;
528
529 if (new_cs->status == STATUS_MAP_WAIT) {
530 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)) {
531 best = new_cs;
532 }
533 }
534 }
535
536 /* Is there someone else to join? */
537 if (best != nullptr) {
538 /* Let the first start joining. */
539 best->status = STATUS_AUTHORIZED;
540 best->SendMap();
541
542 /* And update the rest. */
543 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
544 if (new_cs->status == STATUS_MAP_WAIT) new_cs->SendWait();
545 }
546 }
547}
548
550 NetworkRecvStatus ServerNetworkGameSocketHandler::SendMap()
551{
552 if (this->status < STATUS_AUTHORIZED) {
553 /* Illegal call, return error and ignore the packet */
554 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
555 }
556
557 if (this->status == STATUS_AUTHORIZED) {
558 Debug(net, 9, "client[{}] SendMap(): first_packet", this->client_id);
559
560 WaitTillSaved();
561 this->savegame = std::make_shared<PacketWriter>(this);
562
563 /* Now send the _frame_counter and how many packets are coming */
564 auto p = std::make_unique<Packet>(this, PACKET_SERVER_MAP_BEGIN);
565 p->Send_uint32(_frame_counter);
566 this->SendPacket(std::move(p));
567
568 NetworkSyncCommandQueue(this);
569 Debug(net, 9, "client[{}] status = MAP", this->client_id);
570 this->status = STATUS_MAP;
571 /* Mark the start of download */
572 this->last_frame = _frame_counter;
573 this->last_frame_server = _frame_counter;
574
575 /* Make a dump of the current game */
576 if (SaveWithFilter(this->savegame, true) != SL_OK) UserError("network savedump failed");
577 }
578
579 if (this->status == STATUS_MAP) {
580 bool last_packet = this->savegame->TransferToNetworkQueue();
581 if (last_packet) {
582 Debug(net, 9, "client[{}] SendMap(): last_packet", this->client_id);
583
584 /* Done reading, make sure saving is done as well */
585 this->savegame->Destroy();
586 this->savegame = nullptr;
587
588 /* Set the status to DONE_MAP, no we will wait for the client
589 * to send it is ready (maybe that happens like never ;)) */
590 Debug(net, 9, "client[{}] status = DONE_MAP", this->client_id);
591 this->status = STATUS_DONE_MAP;
592
593 this->CheckNextClientToSendMap();
594 }
595 }
596 return NETWORK_RECV_STATUS_OKAY;
597}
598
603 NetworkRecvStatus ServerNetworkGameSocketHandler::SendJoin(ClientID client_id)
604{
605 Debug(net, 9, "client[{}] SendJoin(): client_id={}", this->client_id, client_id);
606
607 auto p = std::make_unique<Packet>(this, PACKET_SERVER_JOIN);
608
609 p->Send_uint32(client_id);
610
611 this->SendPacket(std::move(p));
612 return NETWORK_RECV_STATUS_OKAY;
613}
614
616 NetworkRecvStatus ServerNetworkGameSocketHandler::SendFrame()
617{
618 auto p = std::make_unique<Packet>(this, PACKET_SERVER_FRAME);
619 p->Send_uint32(_frame_counter);
620 p->Send_uint32(_frame_counter_max);
621#ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
622 p->Send_uint32(_sync_seed_1);
623#ifdef NETWORK_SEND_DOUBLE_SEED
624 p->Send_uint32(_sync_seed_2);
625#endif
626#endif
627
628 /* If token equals 0, we need to make a new token and send that. */
629 if (this->last_token == 0) {
630 this->last_token = InteractiveRandomRange(UINT8_MAX - 1) + 1;
631 p->Send_uint8(this->last_token);
632 }
633
634 this->SendPacket(std::move(p));
635 return NETWORK_RECV_STATUS_OKAY;
636}
637
639 NetworkRecvStatus ServerNetworkGameSocketHandler::SendSync()
640{
641 Debug(net, 9, "client[{}] SendSync(), frame_counter={}, sync_seed_1={}", this->client_id, _frame_counter, _sync_seed_1);
642
643 auto p = std::make_unique<Packet>(this, PACKET_SERVER_SYNC);
644 p->Send_uint32(_frame_counter);
645 p->Send_uint32(_sync_seed_1);
646
647#ifdef NETWORK_SEND_DOUBLE_SEED
648 p->Send_uint32(_sync_seed_2);
649#endif
650 this->SendPacket(std::move(p));
651 return NETWORK_RECV_STATUS_OKAY;
652}
653
658 NetworkRecvStatus ServerNetworkGameSocketHandler::SendCommand(const CommandPacket &cp)
659{
660 Debug(net, 9, "client[{}] SendCommand(): cmd={}", this->client_id, cp.cmd);
661
662 auto p = std::make_unique<Packet>(this, PACKET_SERVER_COMMAND);
663
664 this->NetworkGameSocketHandler::SendCommand(*p, cp);
665 p->Send_uint32(cp.frame);
666 p->Send_bool (cp.my_cmd);
667
668 this->SendPacket(std::move(p));
669 return NETWORK_RECV_STATUS_OKAY;
670}
671
680 NetworkRecvStatus ServerNetworkGameSocketHandler::SendChat(NetworkAction action, ClientID client_id, bool self_send, std::string_view msg, int64_t data)
681{
682 Debug(net, 9, "client[{}] SendChat(): action={}, client_id={}, self_send={}", this->client_id, action, client_id, self_send);
683
684 if (this->status < STATUS_PRE_ACTIVE) return NETWORK_RECV_STATUS_OKAY;
685
686 auto p = std::make_unique<Packet>(this, PACKET_SERVER_CHAT);
687
688 p->Send_uint8 (action);
689 p->Send_uint32(client_id);
690 p->Send_bool (self_send);
691 p->Send_string(msg);
692 p->Send_uint64(data);
693
694 this->SendPacket(std::move(p));
695 return NETWORK_RECV_STATUS_OKAY;
696}
697
705 NetworkRecvStatus ServerNetworkGameSocketHandler::SendExternalChat(std::string_view source, TextColour colour, std::string_view user, std::string_view msg)
706{
707 Debug(net, 9, "client[{}] SendExternalChat(): source={}", this->client_id, source);
708
709 if (this->status < STATUS_PRE_ACTIVE) return NETWORK_RECV_STATUS_OKAY;
710
711 auto p = std::make_unique<Packet>(this, PACKET_SERVER_EXTERNAL_CHAT);
712
713 p->Send_string(source);
714 p->Send_uint16(colour);
715 p->Send_string(user);
716 p->Send_string(msg);
717
718 this->SendPacket(std::move(p));
719 return NETWORK_RECV_STATUS_OKAY;
720}
721
727 NetworkRecvStatus ServerNetworkGameSocketHandler::SendErrorQuit(ClientID client_id, NetworkErrorCode errorno)
728{
729 Debug(net, 9, "client[{}] SendErrorQuit(): client_id={}, errorno={}", this->client_id, client_id, errorno);
730
731 auto p = std::make_unique<Packet>(this, PACKET_SERVER_ERROR_QUIT);
732
733 p->Send_uint32(client_id);
734 p->Send_uint8 (errorno);
735
736 this->SendPacket(std::move(p));
737 return NETWORK_RECV_STATUS_OKAY;
738}
739
744 NetworkRecvStatus ServerNetworkGameSocketHandler::SendQuit(ClientID client_id)
745{
746 Debug(net, 9, "client[{}] SendQuit(): client_id={}", this->client_id, client_id);
747
748 auto p = std::make_unique<Packet>(this, PACKET_SERVER_QUIT);
749
750 p->Send_uint32(client_id);
751
752 this->SendPacket(std::move(p));
753 return NETWORK_RECV_STATUS_OKAY;
754}
755
757 NetworkRecvStatus ServerNetworkGameSocketHandler::SendShutdown()
758{
759 Debug(net, 9, "client[{}] SendShutdown()", this->client_id);
760
761 auto p = std::make_unique<Packet>(this, PACKET_SERVER_SHUTDOWN);
762 this->SendPacket(std::move(p));
763 return NETWORK_RECV_STATUS_OKAY;
764}
765
767 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGame()
768{
769 Debug(net, 9, "client[{}] SendNewGame()", this->client_id);
770
771 auto p = std::make_unique<Packet>(this, PACKET_SERVER_NEWGAME);
772 this->SendPacket(std::move(p));
773 return NETWORK_RECV_STATUS_OKAY;
774}
775
781 NetworkRecvStatus ServerNetworkGameSocketHandler::SendRConResult(uint16_t colour, std::string_view command)
782{
783 Debug(net, 9, "client[{}] SendRConResult()", this->client_id);
784
785 auto p = std::make_unique<Packet>(this, PACKET_SERVER_RCON);
786
787 p->Send_uint16(colour);
788 p->Send_string(command);
789 this->SendPacket(std::move(p));
790 return NETWORK_RECV_STATUS_OKAY;
791}
792
798 NetworkRecvStatus ServerNetworkGameSocketHandler::SendMove(ClientID client_id, CompanyID company_id)
799{
800 Debug(net, 9, "client[{}] SendMove(): client_id={}", this->client_id, client_id);
801
802 auto p = std::make_unique<Packet>(this, PACKET_SERVER_MOVE);
803
804 p->Send_uint32(client_id);
805 p->Send_uint8(company_id);
806 this->SendPacket(std::move(p));
807 return NETWORK_RECV_STATUS_OKAY;
808}
809
811 NetworkRecvStatus ServerNetworkGameSocketHandler::SendConfigUpdate()
812{
813 Debug(net, 9, "client[{}] SendConfigUpdate()", this->client_id);
814
815 auto p = std::make_unique<Packet>(this, PACKET_SERVER_CONFIG_UPDATE);
816
817 p->Send_uint8(_settings_client.network.max_companies);
818 p->Send_string(_settings_client.network.server_name);
819 this->SendPacket(std::move(p));
820 return NETWORK_RECV_STATUS_OKAY;
821}
822
823/***********
824 * Receiving functions
825 ************/
826
827 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GAME_INFO(Packet &)
828{
829 Debug(net, 9, "client[{}] Receive_CLIENT_GAME_INFO()", this->client_id);
830
831 return this->SendGameInfo();
832}
833
834 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_NEWGRFS_CHECKED(Packet &)
835{
836 if (this->status != STATUS_NEWGRFS_CHECK) {
837 /* Illegal call, return error and ignore the packet */
838 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
839 }
840
841 Debug(net, 9, "client[{}] Receive_CLIENT_NEWGRFS_CHECKED()", this->client_id);
842
843 return this->SendWelcome();
844}
845
846 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet &p)
847{
848 if (this->status != STATUS_INACTIVE) {
849 /* Illegal call, return error and ignore the packet */
850 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
851 }
852
853 if (_network_game_info.clients_on >= _settings_client.network.max_clients) {
854 /* Turns out we are full. Inform the user about this. */
855 return this->SendError(NETWORK_ERROR_FULL);
856 }
857
858 std::string client_revision = p.Recv_string(NETWORK_REVISION_LENGTH);
859 uint32_t newgrf_version = p.Recv_uint32();
860
861 Debug(net, 9, "client[{}] Receive_CLIENT_JOIN(): client_revision={}, newgrf_version={}", this->client_id, client_revision, newgrf_version);
862
863 /* Check if the client has revision control enabled */
864 if (!IsNetworkCompatibleVersion(client_revision) || _openttd_newgrf_version != newgrf_version) {
865 /* Different revisions!! */
866 return this->SendError(NETWORK_ERROR_WRONG_REVISION);
867 }
868
869 return this->SendAuthRequest();
870}
871
872 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_IDENTIFY(Packet &p)
873{
874 if (this->status != STATUS_IDENTIFY) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
875
876 Debug(net, 9, "client[{}] Receive_CLIENT_IDENTIFY()", this->client_id);
877
878 std::string client_name = p.Recv_string(NETWORK_CLIENT_NAME_LENGTH);
879 CompanyID playas = (Owner)p.Recv_uint8();
880
881 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT;
882
883 /* join another company does not affect these values */
884 switch (playas.base()) {
885 case COMPANY_NEW_COMPANY.base(): // New company
886 if (Company::GetNumItems() >= _settings_client.network.max_companies) {
887 return this->SendError(NETWORK_ERROR_FULL);
888 }
889 break;
890 case COMPANY_SPECTATOR.base(): // Spectator
891 break;
892 default: // Join another company (companies 1..MAX_COMPANIES (index 0..(MAX_COMPANIES-1)))
893 if (!Company::IsValidHumanID(playas)) {
894 return this->SendError(NETWORK_ERROR_COMPANY_MISMATCH);
895 }
896
897 if (!Company::Get(playas)->allow_list.Contains(this->peer_public_key)) {
898 /* When we're not authorized, just bump us to a spectator. */
899 playas = COMPANY_SPECTATOR;
900 }
901 break;
902 }
903
904 if (!NetworkIsValidClientName(client_name)) {
905 /* An invalid client name was given. However, the client ensures the name
906 * is valid before it is sent over the network, so something went horribly
907 * wrong. This is probably someone trying to troll us. */
908 return this->SendError(NETWORK_ERROR_INVALID_CLIENT_NAME);
909 }
910
911 if (!NetworkMakeClientNameUnique(client_name)) { // Change name if duplicate
912 /* We could not create a name for this client */
913 return this->SendError(NETWORK_ERROR_NAME_IN_USE);
914 }
915
916 assert(NetworkClientInfo::CanAllocateItem());
917 NetworkClientInfo *ci = new NetworkClientInfo(this->client_id);
918 this->SetInfo(ci);
919 ci->join_date = TimerGameEconomy::date;
920 ci->client_name = std::move(client_name);
921 ci->client_playas = playas;
922 ci->public_key = this->peer_public_key;
923 Debug(desync, 1, "client: {:08x}; {:02x}; {:02x}; {:02x}", TimerGameEconomy::date, TimerGameEconomy::date_fract, ci->client_playas, ci->index);
924
925 /* Make sure companies to which people try to join are not autocleaned */
926 Company *c = Company::GetIfValid(playas);
927 if (c != nullptr) c->months_empty = 0;
928
929 return this->SendNewGRFCheck();
930}
931
932static NetworkErrorCode GetErrorForAuthenticationMethod(NetworkAuthenticationMethod method)
933{
934 switch (method) {
935 case NetworkAuthenticationMethod::X25519_PAKE:
936 return NETWORK_ERROR_WRONG_PASSWORD;
937 case NetworkAuthenticationMethod::X25519_AuthorizedKey:
938 return NETWORK_ERROR_NOT_ON_ALLOW_LIST;
939
940 default:
941 NOT_REACHED();
942 }
943}
944
945 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_AUTH_RESPONSE(Packet &p)
946{
947 if (this->status != STATUS_AUTH_GAME) {
948 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
949 }
950
951 Debug(net, 9, "client[{}] Receive_CLIENT_AUTH_RESPONSE()", this->client_id);
952
953 auto authentication_method = this->authentication_handler->GetAuthenticationMethod();
954 switch (this->authentication_handler->ReceiveResponse(p)) {
955 case NetworkAuthenticationServerHandler::ResponseResult::Authenticated:
956 break;
957
958 case NetworkAuthenticationServerHandler::ResponseResult::RetryNextMethod:
959 return this->SendAuthRequest();
960
961 case NetworkAuthenticationServerHandler::ResponseResult::NotAuthenticated:
962 default:
963 return this->SendError(GetErrorForAuthenticationMethod(authentication_method));
964 }
965
966 NetworkRecvStatus status = this->SendEnableEncryption();
967 if (status != NETWORK_RECV_STATUS_OKAY) return status;
968
969 this->peer_public_key = this->authentication_handler->GetPeerPublicKey();
970 this->receive_encryption_handler = this->authentication_handler->CreateClientToServerEncryptionHandler();
971 this->send_encryption_handler = this->authentication_handler->CreateServerToClientEncryptionHandler();
972 this->authentication_handler = nullptr;
973
974 Debug(net, 9, "client[{}] status = IDENTIFY", this->client_id);
975 this->status = STATUS_IDENTIFY;
976
977 /* Reset 'lag' counters */
978 this->last_frame = this->last_frame_server = _frame_counter;
979
980 return NETWORK_RECV_STATUS_OKAY;
981}
982
983 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GETMAP(Packet &)
984{
985 /* The client was never joined.. so this is impossible, right?
986 * Ignore the packet, give the client a warning, and close the connection */
987 if (this->status < STATUS_AUTHORIZED || this->HasClientQuit()) {
988 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
989 }
990
991 Debug(net, 9, "client[{}] Receive_CLIENT_GETMAP()", this->client_id);
992
993 /* Check if someone else is receiving the map */
994 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
995 if (new_cs->status == STATUS_MAP) {
996 /* Tell the new client to wait */
997 Debug(net, 9, "client[{}] status = MAP_WAIT", this->client_id);
998 this->status = STATUS_MAP_WAIT;
999 return this->SendWait();
1000 }
1001 }
1002
1003 /* We receive a request to upload the map.. give it to the client! */
1004 return this->SendMap();
1005}
1006
1007 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MAP_OK(Packet &)
1008{
1009 /* Client has the map, now start syncing */
1010 if (this->status == STATUS_DONE_MAP && !this->HasClientQuit()) {
1011 Debug(net, 9, "client[{}] Receive_CLIENT_MAP_OK()", this->client_id);
1012
1013 std::string client_name = this->GetClientName();
1014
1015 NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, client_name, "", this->client_id);
1016 InvalidateWindowData(WC_CLIENT_LIST, 0);
1017
1018 Debug(net, 3, "[{}] Client #{} ({}) joined as {}", ServerNetworkGameSocketHandler::GetName(), this->client_id, this->GetClientIP(), client_name);
1019
1020 /* Mark the client as pre-active, and wait for an ACK
1021 * so we know it is done loading and in sync with us */
1022 Debug(net, 9, "client[{}] status = PRE_ACTIVE", this->client_id);
1023 this->status = STATUS_PRE_ACTIVE;
1024 NetworkHandleCommandQueue(this);
1025 this->SendFrame();
1026 this->SendSync();
1027
1028 /* This is the frame the client receives
1029 * we need it later on to make sure the client is not too slow */
1030 this->last_frame = _frame_counter;
1031 this->last_frame_server = _frame_counter;
1032
1033 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
1034 if (new_cs->status >= STATUS_AUTHORIZED) {
1035 new_cs->SendClientInfo(this->GetInfo());
1036 new_cs->SendJoin(this->client_id);
1037 }
1038 }
1039
1040 NetworkAdminClientInfo(this, true);
1041
1042 /* also update the new client with our max values */
1043 return this->SendConfigUpdate();
1044 }
1045
1046 /* Wrong status for this packet, give a warning to client, and close connection */
1047 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1048}
1049
1054 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMMAND(Packet &p)
1055{
1056 /* The client was never joined.. so this is impossible, right?
1057 * Ignore the packet, give the client a warning, and close the connection */
1058 if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
1059 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1060 }
1061
1062 if (this->incoming_queue.size() >= _settings_client.network.max_commands_in_queue) {
1063 return this->SendError(NETWORK_ERROR_TOO_MANY_COMMANDS);
1064 }
1065
1066 Debug(net, 9, "client[{}] Receive_CLIENT_COMMAND()", this->client_id);
1067
1068 CommandPacket cp;
1069 auto err = this->ReceiveCommand(p, cp);
1070
1071 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT;
1072
1073 NetworkClientInfo *ci = this->GetInfo();
1074
1075 if (err.has_value()) {
1076 IConsolePrint(CC_WARNING, "Dropping client #{} (IP: {}) due to {}.", ci->client_id, this->GetClientIP(), *err);
1077 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1078 }
1079
1080 if (GetCommandFlags(cp.cmd).Test(CommandFlag::Server) && ci->client_id != CLIENT_ID_SERVER) {
1081 IConsolePrint(CC_WARNING, "Kicking client #{} (IP: {}) due to calling a server only command {}.", ci->client_id, this->GetClientIP(), cp.cmd);
1082 return this->SendError(NETWORK_ERROR_KICKED);
1083 }
1084
1085 if (!GetCommandFlags(cp.cmd).Test(CommandFlag::Spectator) && !Company::IsValidID(cp.company) && ci->client_id != CLIENT_ID_SERVER) {
1086 IConsolePrint(CC_WARNING, "Kicking client #{} (IP: {}) due to calling a non-spectator command {}.", ci->client_id, this->GetClientIP(), cp.cmd);
1087 return this->SendError(NETWORK_ERROR_KICKED);
1088 }
1089
1095 CompanyCtrlAction cca = cp.cmd == CMD_COMPANY_CTRL ? std::get<0>(EndianBufferReader::ToValue<CommandTraits<CMD_COMPANY_CTRL>::Args>(cp.data)) : CCA_NEW;
1096 if (!(cp.cmd == CMD_COMPANY_CTRL && cca == CCA_NEW && ci->client_playas == COMPANY_NEW_COMPANY) && ci->client_playas != cp.company) {
1097 IConsolePrint(CC_WARNING, "Kicking client #{} (IP: {}) due to calling a command as another company {}.",
1098 ci->client_playas + 1, this->GetClientIP(), cp.company + 1);
1099 return this->SendError(NETWORK_ERROR_COMPANY_MISMATCH);
1100 }
1101
1102 if (cp.cmd == CMD_COMPANY_CTRL) {
1103 if (cca != CCA_NEW || cp.company != COMPANY_SPECTATOR) {
1104 return this->SendError(NETWORK_ERROR_CHEATER);
1105 }
1106
1107 /* 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! */
1108 if (Company::GetNumItems() >= _settings_client.network.max_companies) {
1109 NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_CLIENT, ci->client_id, "cannot create new company, server full", CLIENT_ID_SERVER);
1110 return NETWORK_RECV_STATUS_OKAY;
1111 }
1112 }
1113
1114 if (cp.cmd == CMD_COMPANY_ALLOW_LIST_CTRL) {
1115 /* Maybe the client just got moved before allowing? */
1116 if (ci->client_id != CLIENT_ID_SERVER && ci->client_playas != cp.company) return NETWORK_RECV_STATUS_OKAY;
1117
1118 /* Only allow clients to add/remove currently joined clients. The server owner does not go via this method, so is allowed to do more. */
1119 std::string public_key = std::get<1>(EndianBufferReader::ToValue<CommandTraits<CMD_COMPANY_ALLOW_LIST_CTRL>::Args>(cp.data));
1120 bool found = false;
1121 for (const NetworkClientInfo *info : NetworkClientInfo::Iterate()) {
1122 if (info->public_key == public_key) {
1123 found = true;
1124 break;
1125 }
1126 }
1127
1128 /* Maybe the client just left? */
1129 if (!found) return NETWORK_RECV_STATUS_OKAY;
1130 }
1131
1132 if (GetCommandFlags(cp.cmd).Test(CommandFlag::ClientID)) NetworkReplaceCommandClientId(cp, this->client_id);
1133
1134 this->incoming_queue.push_back(std::move(cp));
1135 return NETWORK_RECV_STATUS_OKAY;
1136}
1137
1138 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ERROR(Packet &p)
1139{
1140 /* This packets means a client noticed an error and is reporting this
1141 * to us. Display the error and report it to the other clients */
1142 NetworkErrorCode errorno = (NetworkErrorCode)p.Recv_uint8();
1143
1144 Debug(net, 9, "client[{}] Receive_CLIENT_ERROR(): errorno={}", this->client_id, errorno);
1145
1146 /* The client was never joined.. thank the client for the packet, but ignore it */
1147 if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
1148 return this->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT);
1149 }
1150
1151 std::string client_name = this->GetClientName();
1152 StringID strid = GetNetworkErrorMsg(errorno);
1153
1154 Debug(net, 1, "'{}' reported an error and is closing its connection: {}", client_name, GetString(strid));
1155
1156 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, "", strid);
1157
1158 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
1159 if (new_cs->status >= STATUS_AUTHORIZED) {
1160 new_cs->SendErrorQuit(this->client_id, errorno);
1161 }
1162 }
1163
1164 NetworkAdminClientError(this->client_id, errorno);
1165
1166 return this->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT);
1167}
1168
1169 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_QUIT(Packet &)
1170{
1171 /* The client was never joined.. thank the client for the packet, but ignore it */
1172 if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
1173 return this->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT);
1174 }
1175
1176 Debug(net, 9, "client[{}] Receive_CLIENT_QUIT()", this->client_id);
1177
1178 /* The client wants to leave. Display this and report it to the other clients. */
1179 std::string client_name = this->GetClientName();
1180 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, "", STR_NETWORK_MESSAGE_CLIENT_LEAVING);
1181
1182 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
1183 if (new_cs->status >= STATUS_AUTHORIZED && new_cs != this) {
1184 new_cs->SendQuit(this->client_id);
1185 }
1186 }
1187
1188 NetworkAdminClientQuit(this->client_id);
1189
1190 return this->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT);
1191}
1192
1193 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ACK(Packet &p)
1194{
1195 if (this->status < STATUS_AUTHORIZED) {
1196 /* Illegal call, return error and ignore the packet */
1197 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
1198 }
1199
1200 uint32_t frame = p.Recv_uint32();
1201
1202 Debug(net, 9, "client[{}] Receive_CLIENT_ACK(): frame={}", this->client_id, frame);
1203
1204 /* The client is trying to catch up with the server */
1205 if (this->status == STATUS_PRE_ACTIVE) {
1206 /* The client is not yet caught up? */
1207 if (frame + Ticks::DAY_TICKS < _frame_counter) return NETWORK_RECV_STATUS_OKAY;
1208
1209 /* Now it is! Unpause the game */
1210 Debug(net, 9, "client[{}] status = ACTIVE", this->client_id);
1211 this->status = STATUS_ACTIVE;
1212 this->last_token_frame = _frame_counter;
1213
1214 /* Execute script for, e.g. MOTD */
1215 IConsoleCmdExec("exec scripts/on_server_connect.scr 0");
1216 }
1217
1218 /* Get, and validate the token. */
1219 uint8_t token = p.Recv_uint8();
1220 if (token == this->last_token) {
1221 /* We differentiate between last_token_frame and last_frame so the lag
1222 * test uses the actual lag of the client instead of the lag for getting
1223 * the token back and forth; after all, the token is only sent every
1224 * time we receive a PACKET_CLIENT_ACK, after which we will send a new
1225 * token to the client. If the lag would be one day, then we would not
1226 * be sending the new token soon enough for the new daily scheduled
1227 * PACKET_CLIENT_ACK. This would then register the lag of the client as
1228 * two days, even when it's only a single day. */
1229 this->last_token_frame = _frame_counter;
1230 /* Request a new token. */
1231 this->last_token = 0;
1232 }
1233
1234 /* The client received the frame, make note of it */
1235 this->last_frame = frame;
1236 /* With those 2 values we can calculate the lag realtime */
1237 this->last_frame_server = _frame_counter;
1238 return NETWORK_RECV_STATUS_OKAY;
1239}
1240
1241
1252 void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, std::string_view msg, ClientID from_id, int64_t data, bool from_admin)
1253{
1254 const NetworkClientInfo *ci, *ci_own, *ci_to;
1255
1256 switch (desttype) {
1257 case DESTTYPE_CLIENT:
1258 /* Are we sending to the server? */
1259 if ((ClientID)dest == CLIENT_ID_SERVER) {
1260 ci = NetworkClientInfo::GetByClientID(from_id);
1261 /* Display the text locally, and that is it */
1262 if (ci != nullptr) {
1263 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
1264
1265 if (_settings_client.network.server_admin_chat) {
1266 NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
1267 }
1268 }
1269 } else {
1270 /* Else find the client to send the message to */
1271 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1272 if (cs->client_id == (ClientID)dest && cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) {
1273 cs->SendChat(action, from_id, false, msg, data);
1274 break;
1275 }
1276 }
1277 }
1278
1279 /* Display the message locally (so you know you have sent it) */
1280 if (from_id != (ClientID)dest) {
1281 if (from_id == CLIENT_ID_SERVER) {
1282 ci = NetworkClientInfo::GetByClientID(from_id);
1283 ci_to = NetworkClientInfo::GetByClientID((ClientID)dest);
1284 if (ci != nullptr && ci_to != nullptr) {
1285 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), true, ci_to->client_name, msg, data);
1286 }
1287 } else {
1288 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1289 if (cs->client_id == from_id && cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) {
1290 cs->SendChat(action, (ClientID)dest, true, msg, data);
1291 break;
1292 }
1293 }
1294 }
1295 }
1296 break;
1297 case DESTTYPE_TEAM: {
1298 /* If this is false, the message is already displayed on the client who sent it. */
1299 bool show_local = true;
1300 /* Find all clients that belong to this company */
1301 ci_to = nullptr;
1302 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1303 ci = cs->GetInfo();
1304 if (ci != nullptr && ci->client_playas == (CompanyID)dest && cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) {
1305 cs->SendChat(action, from_id, false, msg, data);
1306 if (cs->client_id == from_id) show_local = false;
1307 ci_to = ci; // Remember a client that is in the company for company-name
1308 }
1309 }
1310
1311 /* if the server can read it, let the admin network read it, too. */
1312 if (_local_company == (CompanyID)dest && _settings_client.network.server_admin_chat) {
1313 NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
1314 }
1315
1316 ci = NetworkClientInfo::GetByClientID(from_id);
1317 ci_own = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
1318 if (ci != nullptr && ci_own != nullptr && ci_own->client_playas == dest) {
1319 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
1320 if (from_id == CLIENT_ID_SERVER) show_local = false;
1321 ci_to = ci_own;
1322 }
1323
1324 /* There is no such client */
1325 if (ci_to == nullptr) break;
1326
1327 /* Display the message locally (so you know you have sent it) */
1328 if (ci != nullptr && show_local) {
1329 if (from_id == CLIENT_ID_SERVER) {
1330 StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
1331 std::string name = GetString(str, ci_to->client_playas);
1332 NetworkTextMessage(action, GetDrawStringCompanyColour(ci_own->client_playas), true, name, msg, data);
1333 } else {
1334 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1335 if (cs->client_id == from_id && cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) {
1336 cs->SendChat(action, ci_to->client_id, true, msg, data);
1337 }
1338 }
1339 }
1340 }
1341 break;
1342 }
1343 default:
1344 Debug(net, 1, "Received unknown chat destination type {}; doing broadcast instead", desttype);
1345 [[fallthrough]];
1346
1347 case DESTTYPE_BROADCAST:
1348 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1349 if (cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) cs->SendChat(action, from_id, false, msg, data);
1350 }
1351
1352 NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
1353
1354 ci = NetworkClientInfo::GetByClientID(from_id);
1355 if (ci != nullptr) {
1356 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
1357 }
1358 break;
1359 }
1360}
1361
1369 void NetworkServerSendExternalChat(std::string_view source, TextColour colour, std::string_view user, std::string_view msg)
1370{
1371 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1372 if (cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) cs->SendExternalChat(source, colour, user, msg);
1373 }
1374 NetworkTextMessage(NETWORK_ACTION_EXTERNAL_CHAT, colour, false, user, msg, source);
1375}
1376
1377 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_CHAT(Packet &p)
1378{
1379 if (this->status < STATUS_PRE_ACTIVE) {
1380 /* Illegal call, return error and ignore the packet */
1381 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
1382 }
1383
1384 NetworkAction action = (NetworkAction)p.Recv_uint8();
1385 DestType desttype = (DestType)p.Recv_uint8();
1386 int dest = p.Recv_uint32();
1387
1388 Debug(net, 9, "client[{}] Receive_CLIENT_CHAT(): action={}, desttype={}, dest={}", this->client_id, action, desttype, dest);
1389
1390 std::string msg = p.Recv_string(NETWORK_CHAT_LENGTH);
1391 int64_t data = p.Recv_uint64();
1392
1393 NetworkClientInfo *ci = this->GetInfo();
1394 switch (action) {
1395 case NETWORK_ACTION_CHAT:
1396 case NETWORK_ACTION_CHAT_CLIENT:
1397 case NETWORK_ACTION_CHAT_COMPANY:
1398 NetworkServerSendChat(action, desttype, dest, msg, this->client_id, data);
1399 break;
1400 default:
1401 IConsolePrint(CC_WARNING, "Kicking client #{} (IP: {}) due to unknown chact action.", ci->client_id, this->GetClientIP());
1402 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1403 }
1404 return NETWORK_RECV_STATUS_OKAY;
1405}
1406
1407 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_NAME(Packet &p)
1408{
1409 if (this->status != STATUS_ACTIVE) {
1410 /* Illegal call, return error and ignore the packet */
1411 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1412 }
1413
1414 Debug(net, 9, "client[{}] Receive_CLIENT_SET_NAME()", this->client_id);
1415
1416 NetworkClientInfo *ci;
1417
1418 std::string client_name = p.Recv_string(NETWORK_CLIENT_NAME_LENGTH);
1419 ci = this->GetInfo();
1420
1421 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT;
1422
1423 if (ci != nullptr) {
1424 if (!NetworkIsValidClientName(client_name)) {
1425 /* An invalid client name was given. However, the client ensures the name
1426 * is valid before it is sent over the network, so something went horribly
1427 * wrong. This is probably someone trying to troll us. */
1428 return this->SendError(NETWORK_ERROR_INVALID_CLIENT_NAME);
1429 }
1430
1431 /* Display change */
1432 if (NetworkMakeClientNameUnique(client_name)) {
1433 NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, client_name);
1434 ci->client_name = std::move(client_name);
1435 NetworkUpdateClientInfo(ci->client_id);
1436 }
1437 }
1438 return NETWORK_RECV_STATUS_OKAY;
1439}
1440
1441 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_RCON(Packet &p)
1442{
1443 if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1444
1445 Debug(net, 9, "client[{}] Receive_CLIENT_RCON()", this->client_id);
1446
1447 std::string password = p.Recv_string(NETWORK_PASSWORD_LENGTH);
1448 std::string command = p.Recv_string(NETWORK_RCONCOMMAND_LENGTH);
1449
1450 if (_rcon_authorized_key_handler.IsAllowed(this->peer_public_key)) {
1451 /* We are allowed, nothing more to validate. */
1452 } else if (_settings_client.network.rcon_password.empty()) {
1453 return NETWORK_RECV_STATUS_OKAY;
1454 } else if (_settings_client.network.rcon_password != password) {
1455 Debug(net, 1, "[rcon] Wrong password from client-id {}", this->client_id);
1456 return NETWORK_RECV_STATUS_OKAY;
1457 }
1458
1459 Debug(net, 3, "[rcon] Client-id {} executed: {}", this->client_id, command);
1460
1461 _redirect_console_to_client = this->client_id;
1462 IConsoleCmdExec(command);
1463 _redirect_console_to_client = INVALID_CLIENT_ID;
1464 return NETWORK_RECV_STATUS_OKAY;
1465}
1466
1467 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MOVE(Packet &p)
1468{
1469 if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1470
1471 CompanyID company_id = (Owner)p.Recv_uint8();
1472
1473 Debug(net, 9, "client[{}] Receive_CLIENT_MOVE(): company_id={}", this->client_id, company_id);
1474
1475 /* Check if the company is valid, we don't allow moving to AI companies */
1476 if (company_id != COMPANY_SPECTATOR && !Company::IsValidHumanID(company_id)) return NETWORK_RECV_STATUS_OKAY;
1477
1478 if (company_id != COMPANY_SPECTATOR && !Company::Get(company_id)->allow_list.Contains(this->peer_public_key)) {
1479 Debug(net, 2, "Wrong public key from client-id #{} for company #{}", this->client_id, company_id + 1);
1480 return NETWORK_RECV_STATUS_OKAY;
1481 }
1482
1483 /* if we get here we can move the client */
1484 NetworkServerDoMove(this->client_id, company_id);
1485 return NETWORK_RECV_STATUS_OKAY;
1486}
1487
1491 NetworkCompanyStatsArray NetworkGetCompanyStats()
1492{
1493 NetworkCompanyStatsArray stats = {};
1494
1495 /* Go through all vehicles and count the type of vehicles */
1496 for (const Vehicle *v : Vehicle::Iterate()) {
1497 if (!Company::IsValidID(v->owner) || !v->IsPrimaryVehicle()) continue;
1498 uint8_t type = 0;
1499 switch (v->type) {
1500 case VEH_TRAIN: type = NETWORK_VEH_TRAIN; break;
1501 case VEH_ROAD: type = RoadVehicle::From(v)->IsBus() ? NETWORK_VEH_BUS : NETWORK_VEH_LORRY; break;
1502 case VEH_AIRCRAFT: type = NETWORK_VEH_PLANE; break;
1503 case VEH_SHIP: type = NETWORK_VEH_SHIP; break;
1504 default: continue;
1505 }
1506 stats[v->owner].num_vehicle[type]++;
1507 }
1508
1509 /* Go through all stations and count the types of stations */
1510 for (const Station *s : Station::Iterate()) {
1511 if (Company::IsValidID(s->owner)) {
1512 NetworkCompanyStats *npi = &stats[s->owner];
1513
1514 if (s->facilities.Test(StationFacility::Train)) npi->num_station[NETWORK_VEH_TRAIN]++;
1515 if (s->facilities.Test(StationFacility::TruckStop)) npi->num_station[NETWORK_VEH_LORRY]++;
1516 if (s->facilities.Test(StationFacility::BusStop)) npi->num_station[NETWORK_VEH_BUS]++;
1517 if (s->facilities.Test(StationFacility::Airport)) npi->num_station[NETWORK_VEH_PLANE]++;
1518 if (s->facilities.Test(StationFacility::Dock)) npi->num_station[NETWORK_VEH_SHIP]++;
1519 }
1520 }
1521
1522 return stats;
1523}
1524
1529 void NetworkUpdateClientInfo(ClientID client_id)
1530{
1531 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1532
1533 if (ci == nullptr) return;
1534
1535 Debug(desync, 1, "client: {:08x}; {:02x}; {:02x}; {:04x}", TimerGameEconomy::date, TimerGameEconomy::date_fract, ci->client_playas, client_id);
1536
1537 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1538 if (cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) {
1539 cs->SendClientInfo(ci);
1540 }
1541 }
1542
1543 NetworkAdminClientUpdate(ci);
1544}
1545
1551 static void NetworkAutoCleanCompanies()
1552{
1553 CompanyMask has_clients{};
1554 CompanyMask has_vehicles{};
1555
1556 if (!_settings_client.network.autoclean_companies) return;
1557
1558 /* Detect the active companies */
1559 for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1560 if (Company::IsValidID(ci->client_playas)) has_clients.Set(ci->client_playas);
1561 }
1562
1563 if (!_network_dedicated) {
1564 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
1565 assert(ci != nullptr);
1566 if (Company::IsValidID(ci->client_playas)) has_clients.Set(ci->client_playas);
1567 }
1568
1569 if (_settings_client.network.autoclean_novehicles != 0) {
1570 for (const Company *c : Company::Iterate()) {
1571 if (std::any_of(std::begin(c->group_all), std::end(c->group_all), [](const GroupStatistics &gs) { return gs.num_vehicle != 0; })) has_vehicles.Set(c->index);
1572 }
1573 }
1574
1575 /* Go through all the companies */
1576 for (Company *c : Company::Iterate()) {
1577 /* Skip the non-active once */
1578 if (c->is_ai) continue;
1579
1580 if (!has_clients.Test(c->index)) {
1581 /* The company is empty for one month more */
1582 if (c->months_empty != std::numeric_limits<decltype(c->months_empty)>::max()) c->months_empty++;
1583
1584 /* Is the company empty for autoclean_protected-months? */
1585 if (_settings_client.network.autoclean_protected != 0 && c->months_empty > _settings_client.network.autoclean_protected) {
1586 /* Shut the company down */
1587 Command<CMD_COMPANY_CTRL>::Post(CCA_DELETE, c->index, CRR_AUTOCLEAN, INVALID_CLIENT_ID);
1588 IConsolePrint(CC_INFO, "Auto-cleaned company #{}.", c->index + 1);
1589 }
1590 /* Is the company empty for autoclean_novehicles-months, and has no vehicles? */
1591 if (_settings_client.network.autoclean_novehicles != 0 && c->months_empty > _settings_client.network.autoclean_novehicles && !has_vehicles.Test(c->index)) {
1592 /* Shut the company down */
1593 Command<CMD_COMPANY_CTRL>::Post(CCA_DELETE, c->index, CRR_AUTOCLEAN, INVALID_CLIENT_ID);
1594 IConsolePrint(CC_INFO, "Auto-cleaned company #{} with no vehicles.", c->index + 1);
1595 }
1596 } else {
1597 /* It is not empty, reset the date */
1598 c->months_empty = 0;
1599 }
1600 }
1601}
1602
1608 bool NetworkMakeClientNameUnique(std::string &name)
1609{
1610 bool is_name_unique = false;
1611 std::string original_name = name;
1612
1613 for (uint number = 1; !is_name_unique && number <= MAX_CLIENTS; number++) { // Something's really wrong when there're more names than clients
1614 is_name_unique = true;
1615 for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1616 if (ci->client_name == name) {
1617 /* Name already in use */
1618 is_name_unique = false;
1619 break;
1620 }
1621 }
1622 /* Check if it is the same as the server-name */
1623 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
1624 if (ci != nullptr) {
1625 if (ci->client_name == name) is_name_unique = false; // name already in use
1626 }
1627
1628 if (!is_name_unique) {
1629 /* Try a new name (<name> #1, <name> #2, and so on) */
1630 name = fmt::format("{} #{}", original_name, number);
1631
1632 /* The constructed client name is larger than the limit,
1633 * so... bail out as no valid name can be created. */
1634 if (name.size() >= NETWORK_CLIENT_NAME_LENGTH) return false;
1635 }
1636 }
1637
1638 return is_name_unique;
1639}
1640
1647 bool NetworkServerChangeClientName(ClientID client_id, const std::string &new_name)
1648{
1649 /* Check if the name's already in use */
1650 for (NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1651 if (ci->client_name == new_name) return false;
1652 }
1653
1654 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1655 if (ci == nullptr) return false;
1656
1657 NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, true, ci->client_name, new_name);
1658
1659 ci->client_name = new_name;
1660
1661 NetworkUpdateClientInfo(client_id);
1662 return true;
1663}
1664
1669 static void NetworkHandleCommandQueue(NetworkClientSocket *cs)
1670{
1671 for (auto &cp : cs->outgoing_queue) cs->SendCommand(cp);
1672 cs->outgoing_queue.clear();
1673}
1674
1679 void NetworkServer_Tick(bool send_frame)
1680{
1681#ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1682 bool send_sync = false;
1683#endif
1684
1685#ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1686 if (_frame_counter >= _last_sync_frame + _settings_client.network.sync_freq) {
1687 _last_sync_frame = _frame_counter;
1688 send_sync = true;
1689 }
1690#endif
1691
1692 /* Now we are done with the frame, inform the clients that they can
1693 * do their frame! */
1694 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1695 /* We allow a number of bytes per frame, but only to the burst amount
1696 * to be available for packet receiving at any particular time. */
1697 cs->receive_limit = std::min<size_t>(cs->receive_limit + _settings_client.network.bytes_per_frame,
1698 _settings_client.network.bytes_per_frame_burst);
1699
1700 /* Check if the speed of the client is what we can expect from a client */
1701 uint lag = NetworkCalculateLag(cs);
1702 switch (cs->status) {
1703 case NetworkClientSocket::STATUS_ACTIVE:
1704 if (lag > _settings_client.network.max_lag_time) {
1705 /* Client did still not report in within the specified limit. */
1706
1707 if (cs->last_packet + std::chrono::milliseconds(lag * MILLISECONDS_PER_TICK) > std::chrono::steady_clock::now()) {
1708 /* A packet was received in the last three game days, so the client is likely lagging behind. */
1709 IConsolePrint(CC_WARNING, "Client #{} (IP: {}) is dropped because the client's game state is more than {} ticks behind.", cs->client_id, cs->GetClientIP(), lag);
1710 } else {
1711 /* No packet was received in the last three game days; sounds like a lost connection. */
1712 IConsolePrint(CC_WARNING, "Client #{} (IP: {}) is dropped because the client did not respond for more than {} ticks.", cs->client_id, cs->GetClientIP(), lag);
1713 }
1714 cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
1715 continue;
1716 }
1717
1718 /* Report once per time we detect the lag, and only when we
1719 * received a packet in the last 2 seconds. If we
1720 * did not receive a packet, then the client is not just
1721 * slow, but the connection is likely severed. Mentioning
1722 * frame_freq is not useful in this case. */
1723 if (lag > (uint)Ticks::DAY_TICKS && cs->lag_test == 0 && cs->last_packet + std::chrono::seconds(2) > std::chrono::steady_clock::now()) {
1724 IConsolePrint(CC_WARNING, "[{}] Client #{} is slow, try increasing [network.]frame_freq to a higher value!", _frame_counter, cs->client_id);
1725 cs->lag_test = 1;
1726 }
1727
1728 if (cs->last_frame_server - cs->last_token_frame >= _settings_client.network.max_lag_time) {
1729 /* This is a bad client! It didn't send the right token back within time. */
1730 IConsolePrint(CC_WARNING, "Client #{} (IP: {}) is dropped because it fails to send valid acks.", cs->client_id, cs->GetClientIP());
1731 cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
1732 continue;
1733 }
1734 break;
1735
1736 case NetworkClientSocket::STATUS_INACTIVE:
1737 case NetworkClientSocket::STATUS_IDENTIFY:
1738 case NetworkClientSocket::STATUS_NEWGRFS_CHECK:
1739 case NetworkClientSocket::STATUS_AUTHORIZED:
1740 /* NewGRF check and authorized states should be handled almost instantly.
1741 * So give them some lee-way, likewise for the query with inactive. */
1742 if (lag > _settings_client.network.max_init_time) {
1743 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);
1744 cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
1745 continue;
1746 }
1747 break;
1748
1749 case NetworkClientSocket::STATUS_MAP_WAIT:
1750 /* Send every two seconds a packet to the client, to make sure
1751 * it knows the server is still there; just someone else is
1752 * still receiving the map. */
1753 if (std::chrono::steady_clock::now() > cs->last_packet + std::chrono::seconds(2)) {
1754 cs->SendWait();
1755 /* We need to reset the timer, as otherwise we will be
1756 * spamming the client. Strictly speaking this variable
1757 * tracks when we last received a packet from the client,
1758 * but as it is waiting, it will not send us any till we
1759 * start sending them data. */
1760 cs->last_packet = std::chrono::steady_clock::now();
1761 }
1762 break;
1763
1764 case NetworkClientSocket::STATUS_MAP:
1765 /* Downloading the map... this is the amount of time since starting the saving. */
1766 if (lag > _settings_client.network.max_download_time) {
1767 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);
1768 cs->SendError(NETWORK_ERROR_TIMEOUT_MAP);
1769 continue;
1770 }
1771 break;
1772
1773 case NetworkClientSocket::STATUS_DONE_MAP:
1774 case NetworkClientSocket::STATUS_PRE_ACTIVE:
1775 /* The map has been sent, so this is for loading the map and syncing up. */
1776 if (lag > _settings_client.network.max_join_time) {
1777 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);
1778 cs->SendError(NETWORK_ERROR_TIMEOUT_JOIN);
1779 continue;
1780 }
1781 break;
1782
1783 case NetworkClientSocket::STATUS_AUTH_GAME:
1784 /* These don't block? */
1785 if (lag > _settings_client.network.max_password_time) {
1786 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);
1787 cs->SendError(NETWORK_ERROR_TIMEOUT_PASSWORD);
1788 continue;
1789 }
1790 break;
1791
1792 case NetworkClientSocket::STATUS_END:
1793 /* Bad server/code. */
1794 NOT_REACHED();
1795 }
1796
1797 if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) {
1798 /* Check if we can send command, and if we have anything in the queue */
1799 NetworkHandleCommandQueue(cs);
1800
1801 /* Send an updated _frame_counter_max to the client */
1802 if (send_frame) cs->SendFrame();
1803
1804#ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1805 /* Send a sync-check packet */
1806 if (send_sync) cs->SendSync();
1807#endif
1808 }
1809 }
1810}
1811
1813 static void NetworkRestartMap()
1814{
1815 _settings_newgame.game_creation.generation_seed = GENERATE_NEW_SEED;
1816 switch (_file_to_saveload.ftype.abstract) {
1817 case FT_SAVEGAME:
1818 case FT_SCENARIO:
1819 _switch_mode = SM_LOAD_GAME;
1820 break;
1821
1822 case FT_HEIGHTMAP:
1823 _switch_mode = SM_START_HEIGHTMAP;
1824 break;
1825
1826 default:
1827 _switch_mode = SM_NEWGAME;
1828 }
1829}
1830
1832 static IntervalTimer<TimerGameRealtime> _network_restart_map_timer({std::chrono::hours::zero(), TimerGameRealtime::UNPAUSED}, [](auto)
1833{
1834 if (!_network_server) return;
1835
1836 /* If setting is 0, this feature is disabled. */
1837 if (_settings_client.network.restart_hours == 0) return;
1838
1839 Debug(net, 3, "Auto-restarting map: {} hours played", _settings_client.network.restart_hours);
1840 NetworkRestartMap();
1841});
1842
1847 void ChangeNetworkRestartTime(bool reset)
1848{
1849 if (!_network_server) return;
1850
1851 _network_restart_map_timer.SetInterval({ std::chrono::hours(_settings_client.network.restart_hours), TimerGameRealtime::UNPAUSED }, reset);
1852}
1853
1855 static void NetworkCheckRestartMapYear()
1856{
1857 /* If setting is 0, this feature is disabled. */
1858 if (_settings_client.network.restart_game_year == 0) return;
1859
1860 if (TimerGameCalendar::year >= _settings_client.network.restart_game_year) {
1861 Debug(net, 3, "Auto-restarting map: year {} reached", TimerGameCalendar::year);
1862 NetworkRestartMap();
1863 }
1864}
1865
1867 static const IntervalTimer<TimerGameCalendar> _calendar_network_yearly({ TimerGameCalendar::YEAR, TimerGameCalendar::Priority::NONE }, [](auto) {
1868 if (!_network_server) return;
1869
1870 NetworkCheckRestartMapYear();
1871});
1872
1874 static const IntervalTimer<TimerGameEconomy> _economy_network_yearly({TimerGameEconomy::YEAR, TimerGameEconomy::Priority::NONE}, [](auto)
1875{
1876 if (!_network_server) return;
1877
1878 NetworkAdminUpdate(AdminUpdateFrequency::Annually);
1879});
1880
1882 static const IntervalTimer<TimerGameEconomy> _network_quarterly({TimerGameEconomy::QUARTER, TimerGameEconomy::Priority::NONE}, [](auto)
1883{
1884 if (!_network_server) return;
1885
1886 NetworkAutoCleanCompanies();
1887 NetworkAdminUpdate(AdminUpdateFrequency::Quarterly);
1888});
1889
1891 static const IntervalTimer<TimerGameEconomy> _network_monthly({TimerGameEconomy::MONTH, TimerGameEconomy::Priority::NONE}, [](auto)
1892{
1893 if (!_network_server) return;
1894
1895 NetworkAutoCleanCompanies();
1896 NetworkAdminUpdate(AdminUpdateFrequency::Monthly);
1897});
1898
1900 static const IntervalTimer<TimerGameEconomy> _network_weekly({TimerGameEconomy::WEEK, TimerGameEconomy::Priority::NONE}, [](auto)
1901{
1902 if (!_network_server) return;
1903
1904 NetworkAdminUpdate(AdminUpdateFrequency::Weekly);
1905});
1906
1908 static const IntervalTimer<TimerGameEconomy> _economy_network_daily({TimerGameEconomy::DAY, TimerGameEconomy::Priority::NONE}, [](auto)
1909{
1910 if (!_network_server) return;
1911
1912 NetworkAdminUpdate(AdminUpdateFrequency::Daily);
1913});
1914
1919std::string_view ServerNetworkGameSocketHandler::GetClientIP()
1920{
1921 return this->client_address.GetHostname();
1922}
1923
1925 void NetworkServerShowStatusToConsole()
1926{
1927 static const std::string_view stat_str[] = {
1928 "inactive",
1929 "authorizing",
1930 "identifying client",
1931 "checking NewGRFs",
1932 "authorized",
1933 "waiting",
1934 "loading map",
1935 "map done",
1936 "ready",
1937 "active"
1938 };
1939 static_assert(lengthof(stat_str) == NetworkClientSocket::STATUS_END);
1940
1941 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1942 NetworkClientInfo *ci = cs->GetInfo();
1943 if (ci == nullptr) continue;
1944 uint lag = NetworkCalculateLag(cs);
1945
1946 std::string_view status = (cs->status < (ptrdiff_t)lengthof(stat_str) ? stat_str[cs->status] : "unknown");
1947 IConsolePrint(CC_INFO, "Client #{} name: '{}' status: '{}' frame-lag: {} company: {} IP: {}",
1948 cs->client_id, ci->client_name, status, lag,
1949 ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0),
1950 cs->GetClientIP());
1951 }
1952}
1953
1957 void NetworkServerSendConfigUpdate()
1958{
1959 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1960 if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) cs->SendConfigUpdate();
1961 }
1962}
1963
1965 void NetworkServerUpdateGameInfo()
1966{
1967 if (_network_server) FillStaticNetworkServerGameInfo();
1968}
1969
1976 void NetworkServerDoMove(ClientID client_id, CompanyID company_id)
1977{
1978 /* Only allow non-dedicated servers and normal clients to be moved */
1979 if (client_id == CLIENT_ID_SERVER && _network_dedicated) return;
1980
1981 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1982 assert(ci != nullptr);
1983
1984 /* No need to waste network resources if the client is in the company already! */
1985 if (ci->client_playas == company_id) return;
1986
1987 ci->client_playas = company_id;
1988
1989 if (client_id == CLIENT_ID_SERVER) {
1990 SetLocalCompany(company_id);
1991 } else {
1992 NetworkClientSocket *cs = NetworkClientSocket::GetByClientID(client_id);
1993 /* When the company isn't authorized we can't move them yet. */
1994 if (cs->status < NetworkClientSocket::STATUS_AUTHORIZED) return;
1995 cs->SendMove(client_id, company_id);
1996 }
1997
1998 /* Announce the client's move. */
1999 NetworkUpdateClientInfo(client_id);
2000
2001 if (company_id == COMPANY_SPECTATOR) {
2002 /* The client has joined spectators. */
2003 NetworkServerSendChat(NETWORK_ACTION_COMPANY_SPECTATOR, DESTTYPE_BROADCAST, 0, "", client_id);
2004 } else {
2005 /* The client has joined another company. */
2006 std::string company_name = GetString(STR_COMPANY_NAME, company_id);
2007 NetworkServerSendChat(NETWORK_ACTION_COMPANY_JOIN, DESTTYPE_BROADCAST, 0, company_name, client_id);
2008 }
2009
2010 InvalidateWindowData(WC_CLIENT_LIST, 0);
2011}
2012
2019 void NetworkServerSendRcon(ClientID client_id, TextColour colour_code, std::string_view string)
2020{
2021 NetworkClientSocket::GetByClientID(client_id)->SendRConResult(colour_code, string);
2022}
2023
2029 void NetworkServerKickClient(ClientID client_id, std::string_view reason)
2030{
2031 if (client_id == CLIENT_ID_SERVER) return;
2032 NetworkClientSocket::GetByClientID(client_id)->SendError(NETWORK_ERROR_KICKED, reason);
2033}
2034
2041uint NetworkServerKickOrBanIP(ClientID client_id, bool ban, std::string_view reason)
2042{
2043 return NetworkServerKickOrBanIP(NetworkClientSocket::GetByClientID(client_id)->GetClientIP(), ban, reason);
2044}
2045
2052uint NetworkServerKickOrBanIP(std::string_view ip, bool ban, std::string_view reason)
2053{
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;
2061 }
2062 }
2063 if (!contains) _network_ban_list.emplace_back(ip);
2064 }
2065
2066 uint n = 0;
2067
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++;
2079 }
2080 }
2081
2082 return n;
2083}
2084
2090 bool NetworkCompanyHasClients(CompanyID company)
2091{
2092 for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
2093 if (ci->client_playas == company) return true;
2094 }
2095 return false;
2096}
2097
2098
2104std::string ServerNetworkGameSocketHandler::GetClientName() const
2105{
2106 const NetworkClientInfo *ci = this->GetInfo();
2107 if (ci != nullptr && !ci->client_name.empty()) return ci->client_name;
2108
2109 return fmt::format("Client #{}", this->client_id);
2110}
2111
2115 void NetworkPrintClients()
2116{
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));
2129 }
2130 }
2131}
2132
2138std::string_view NetworkGetPublicKeyOfClient(ClientID client_id)
2139{
2140 auto socket = NetworkClientSocket::GetByClientID(client_id);
2141 return socket == nullptr ? "" : socket->GetPeerPublicKey();
2142}
2143
2144
2150 void NetworkServerNewCompany(const Company *c, NetworkClientInfo *ci)
2151{
2152 assert(c != nullptr);
2153
2154 if (!_network_server) return;
2155
2156 if (ci != nullptr) {
2157 /* ci is nullptr when replaying, or for AIs. In neither case there is a client. */
2158 ci->client_playas = c->index;
2159 NetworkUpdateClientInfo(ci->client_id);
2160
2161 /*
2162 * This function is called from a command, but is only called for the server.
2163 * The client information is managed out-of-band from the commands, so to not have a
2164 * different state/president/company name in the different clients, we need to
2165 * circumvent the normal ::Post logic and go directly to sending the command.
2166 */
2167 Command<CMD_COMPANY_ALLOW_LIST_CTRL>::SendNet(STR_NULL, c->index, CALCA_ADD, ci->public_key);
2168 Command<CMD_RENAME_PRESIDENT>::SendNet(STR_NULL, c->index, ci->client_name);
2169
2170 NetworkServerSendChat(NETWORK_ACTION_COMPANY_NEW, DESTTYPE_BROADCAST, 0, "", ci->client_id, c->index + 1);
2171 }
2172}
SocketList
std::map< SOCKET, NetworkAddress > SocketList
Type for a mapping between address and socket.
Definition address.h:21
BaseBitSet::Test
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
Definition base_bitset_type.hpp:141
BaseBitSet::Set
constexpr Timpl & Set()
Set all bits.
Definition base_bitset_type.hpp:40
CompanyMask
Definition company_type.h:43
IntervalTimer
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition timer.h:76
IntervalTimer::SetInterval
void SetInterval(const TPeriod interval, bool reset=true)
Set a new interval for the timer.
Definition timer.h:99
NetworkAddress::GetHostname
const std::string & GetHostname()
Get the hostname; in case it wasn't given the IPv4 dotted representation is given.
Definition address.cpp:24
NetworkAuthenticationDefaultAuthorizedKeyHandler
Default implementation for the authorized key handler.
Definition network_crypto.h:161
NetworkAuthenticationDefaultAuthorizedKeyHandler::IsAllowed
bool IsAllowed(std::string_view peer_public_key) const override
Check whether the given public key of the peer is allowed in.
Definition network_crypto.h:172
NetworkAuthenticationDefaultPasswordProvider
Default implementation of the password provider.
Definition network_crypto.h:123
NetworkAuthenticationServerHandler::Create
static std::unique_ptr< NetworkAuthenticationServerHandler > Create(const NetworkAuthenticationPasswordProvider *password_provider, const NetworkAuthenticationAuthorizedKeyHandler *authorized_key_handler, NetworkAuthenticationMethodMask client_supported_method_mask={NetworkAuthenticationMethod::X25519_KeyExchangeOnly, NetworkAuthenticationMethod::X25519_PAKE, NetworkAuthenticationMethod::X25519_AuthorizedKey})
Create a NetworkAuthenticationServerHandler.
Definition network_crypto.cpp:478
NetworkAuthenticationServerHandler::ResponseResult::RetryNextMethod
@ RetryNextMethod
The client failed to authenticate, but there is another method to try.
NetworkAuthenticationServerHandler::ResponseResult::NotAuthenticated
@ NotAuthenticated
All authentications for this handler have been exhausted.
NetworkAuthenticationServerHandler::ResponseResult::Authenticated
@ Authenticated
The client was authenticated successfully.
NetworkGameSocketHandler
Base socket handler for all TCP sockets.
Definition tcp_game.h:140
NetworkGameSocketHandler::last_frame
uint32_t last_frame
Last frame we have executed.
Definition tcp_game.h:486
NetworkGameSocketHandler::GetInfo
NetworkClientInfo * GetInfo() const
Gets the client info of this socket handler.
Definition tcp_game.h:514
NetworkGameSocketHandler::ReceiveCommand
std::optional< std::string_view > ReceiveCommand(Packet &p, CommandPacket &cp)
Receives a command from the network.
Definition network_command.cpp:374
NetworkGameSocketHandler::client_id
ClientID client_id
Client identifier.
Definition tcp_game.h:485
NetworkGameSocketHandler::incoming_queue
CommandQueue incoming_queue
The command-queue awaiting handling.
Definition tcp_game.h:488
NetworkGameSocketHandler::last_packet
std::chrono::steady_clock::time_point last_packet
Time we received the last frame.
Definition tcp_game.h:489
NetworkGameSocketHandler::SetInfo
void SetInfo(NetworkClientInfo *info)
Sets the client info for this socket handler.
Definition tcp_game.h:504
NetworkGameSocketHandler::last_frame_server
uint32_t last_frame_server
Last frame the server has executed.
Definition tcp_game.h:487
NetworkGameSocketHandler::info
NetworkClientInfo * info
Client info related to this socket.
Definition tcp_game.h:143
NetworkGameSocketHandler::SendCommand
void SendCommand(Packet &p, const CommandPacket &cp)
Sends a command over the network.
Definition network_command.cpp:395
NetworkSocketHandler::HasClientQuit
bool HasClientQuit() const
Whether the current client connected to the socket has quit.
Definition core.h:74
NetworkSocketHandler::send_encryption_handler
std::unique_ptr< class NetworkEncryptionHandler > send_encryption_handler
The handler for encrypting sent packets.
Definition core.h:50
NetworkSocketHandler::receive_encryption_handler
std::unique_ptr< class NetworkEncryptionHandler > receive_encryption_handler
The handler for decrypting received packets.
Definition core.h:49
NetworkTCPSocketHandler::ReceivePacket
virtual std::unique_ptr< Packet > ReceivePacket()
Receives a packet for the given client.
Definition tcp.cpp:119
NetworkTCPSocketHandler::sock
SOCKET sock
The socket currently connected to.
Definition tcp.h:38
NetworkTCPSocketHandler::SendPacket
virtual void SendPacket(std::unique_ptr< Packet > &&packet)
This function puts the packet in the send-queue and it is send as soon as possible.
Definition tcp.cpp:58
NetworkTCPSocketHandler::SendPackets
SendPacketsState SendPackets(bool closing_down=false)
Sends all the buffered packets out for this client.
Definition tcp.cpp:76
ServerNetworkGameSocketHandler
Class for handling the server side of the game connection.
Definition network_server.h:24
ServerNetworkGameSocketHandler::Receive_CLIENT_SET_NAME
NetworkRecvStatus Receive_CLIENT_SET_NAME(Packet &p) override
Gives the client a new name: string New name of the client.
Definition network_server.cpp:1407
ServerNetworkGameSocketHandler::GetName
static std::string_view GetName()
Get the name used by the listener.
Definition network_server.h:113
ServerNetworkGameSocketHandler::receive_limit
size_t receive_limit
Amount of bytes that we can receive at this moment.
Definition network_server.h:72
ServerNetworkGameSocketHandler::savegame
std::shared_ptr< struct PacketWriter > savegame
Writer used to write the savegame.
Definition network_server.h:74
ServerNetworkGameSocketHandler::Send
static void Send()
Send the packets for the server sockets.
Definition network_server.cpp:303
ServerNetworkGameSocketHandler::Receive_CLIENT_MOVE
NetworkRecvStatus Receive_CLIENT_MOVE(Packet &p) override
Request the server to move this client into another company: uint8_t ID of the company the client wan...
Definition network_server.cpp:1467
ServerNetworkGameSocketHandler::SendQuit
NetworkRecvStatus SendQuit(ClientID client_id)
Tell the client another client quit.
Definition network_server.cpp:744
ServerNetworkGameSocketHandler::Receive_CLIENT_ACK
NetworkRecvStatus Receive_CLIENT_ACK(Packet &p) override
Tell the server we are done with this frame: uint32_t Current frame counter of the client.
Definition network_server.cpp:1193
ServerNetworkGameSocketHandler::Receive_CLIENT_AUTH_RESPONSE
NetworkRecvStatus Receive_CLIENT_AUTH_RESPONSE(Packet &p) override
Send the response to the authentication request: 32 * uint8_t Public key of the client.
Definition network_server.cpp:945
ServerNetworkGameSocketHandler::ReceivePacket
std::unique_ptr< Packet > ReceivePacket() override
Receives a packet for the given client.
Definition network_server.cpp:222
ServerNetworkGameSocketHandler::STATUS_PRE_ACTIVE
@ STATUS_PRE_ACTIVE
The client is catching up the delayed frames.
Definition network_server.h:62
ServerNetworkGameSocketHandler::STATUS_IDENTIFY
@ STATUS_IDENTIFY
The client is identifying itself.
Definition network_server.h:56
ServerNetworkGameSocketHandler::STATUS_AUTH_GAME
@ STATUS_AUTH_GAME
The client is authorizing with game (server) password.
Definition network_server.h:55
ServerNetworkGameSocketHandler::STATUS_NEWGRFS_CHECK
@ STATUS_NEWGRFS_CHECK
The client is checking NewGRFs.
Definition network_server.h:57
ServerNetworkGameSocketHandler::STATUS_AUTHORIZED
@ STATUS_AUTHORIZED
The client is authorized.
Definition network_server.h:58
ServerNetworkGameSocketHandler::STATUS_INACTIVE
@ STATUS_INACTIVE
The client is not connected nor active.
Definition network_server.h:54
ServerNetworkGameSocketHandler::STATUS_MAP
@ STATUS_MAP
The client is downloading the map.
Definition network_server.h:60
ServerNetworkGameSocketHandler::STATUS_DONE_MAP
@ STATUS_DONE_MAP
The client has downloaded the map.
Definition network_server.h:61
ServerNetworkGameSocketHandler::STATUS_ACTIVE
@ STATUS_ACTIVE
The client is active within in the game.
Definition network_server.h:63
ServerNetworkGameSocketHandler::STATUS_MAP_WAIT
@ STATUS_MAP_WAIT
The client is waiting as someone else is downloading the map.
Definition network_server.h:59
ServerNetworkGameSocketHandler::Receive_CLIENT_COMMAND
NetworkRecvStatus Receive_CLIENT_COMMAND(Packet &p) override
The client has done a command and wants us to handle it.
Definition network_server.cpp:1054
ServerNetworkGameSocketHandler::SendRConResult
NetworkRecvStatus SendRConResult(uint16_t colour, std::string_view command)
Send the result of a console action.
Definition network_server.cpp:781
ServerNetworkGameSocketHandler::Receive_CLIENT_QUIT
NetworkRecvStatus Receive_CLIENT_QUIT(Packet &p) override
The client is quitting the game.
Definition network_server.cpp:1169
ServerNetworkGameSocketHandler::SendChat
NetworkRecvStatus SendChat(NetworkAction action, ClientID client_id, bool self_send, std::string_view msg, int64_t data)
Send a chat message.
Definition network_server.cpp:680
ServerNetworkGameSocketHandler::SendWelcome
NetworkRecvStatus SendWelcome()
Send the client a welcome message with some basic information.
Definition network_server.cpp:472
ServerNetworkGameSocketHandler::SendAuthRequest
NetworkRecvStatus SendAuthRequest()
Request the game password.
Definition network_server.cpp:433
ServerNetworkGameSocketHandler::~ServerNetworkGameSocketHandler
~ServerNetworkGameSocketHandler()
Clear everything related to this client.
Definition network_server.cpp:207
ServerNetworkGameSocketHandler::GetClientName
std::string GetClientName() const
Get the name of the client, if the user did not send it yet, Client ID is used.
Definition network_server.cpp:2104
ServerNetworkGameSocketHandler::last_token
uint8_t last_token
The last random token we did send to verify the client is listening.
Definition network_server.h:68
ServerNetworkGameSocketHandler::SendFrame
NetworkRecvStatus SendFrame()
Tell the client that they may run to a particular frame.
Definition network_server.cpp:616
ServerNetworkGameSocketHandler::Receive_CLIENT_ERROR
NetworkRecvStatus Receive_CLIENT_ERROR(Packet &p) override
The client made an error and is quitting the game.
Definition network_server.cpp:1138
ServerNetworkGameSocketHandler::SendGameInfo
NetworkRecvStatus SendGameInfo()
Send the client information about the server.
Definition network_server.cpp:342
ServerNetworkGameSocketHandler::SendJoin
NetworkRecvStatus SendJoin(ClientID client_id)
Tell that a client joined.
Definition network_server.cpp:603
ServerNetworkGameSocketHandler::peer_public_key
std::string peer_public_key
The public key of our client.
Definition network_server.h:27
ServerNetworkGameSocketHandler::Receive_CLIENT_CHAT
NetworkRecvStatus Receive_CLIENT_CHAT(Packet &p) override
Sends a chat-packet to the server: uint8_t ID of the action (see NetworkAction).
Definition network_server.cpp:1377
ServerNetworkGameSocketHandler::SendClientInfo
NetworkRecvStatus SendClientInfo(NetworkClientInfo *ci)
Send the client information about a client.
Definition network_server.cpp:325
ServerNetworkGameSocketHandler::AllowConnection
static bool AllowConnection()
Whether an connection is allowed or not at this moment.
Definition network_server.cpp:290
ServerNetworkGameSocketHandler::SendEnableEncryption
NetworkRecvStatus SendEnableEncryption()
Notify the client that the authentication has completed and tell that for the remainder of this socke...
Definition network_server.cpp:458
ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN
NetworkRecvStatus Receive_CLIENT_JOIN(Packet &p) override
Try to join the server: string OpenTTD revision (norev0000 if no revision).
Definition network_server.cpp:846
ServerNetworkGameSocketHandler::Receive_CLIENT_GAME_INFO
NetworkRecvStatus Receive_CLIENT_GAME_INFO(Packet &p) override
Request game information.
Definition network_server.cpp:827
ServerNetworkGameSocketHandler::SendExternalChat
NetworkRecvStatus SendExternalChat(std::string_view source, TextColour colour, std::string_view user, std::string_view msg)
Send a chat message from external source.
Definition network_server.cpp:705
ServerNetworkGameSocketHandler::SendErrorQuit
NetworkRecvStatus SendErrorQuit(ClientID client_id, NetworkErrorCode errorno)
Tell the client another client quit with an error.
Definition network_server.cpp:727
ServerNetworkGameSocketHandler::client_address
NetworkAddress client_address
IP-address of the client (so they can be banned)
Definition network_server.h:75
ServerNetworkGameSocketHandler::SendNewGame
NetworkRecvStatus SendNewGame()
Tell the client we're starting a new game.
Definition network_server.cpp:767
ServerNetworkGameSocketHandler::Receive_CLIENT_GETMAP
NetworkRecvStatus Receive_CLIENT_GETMAP(Packet &p) override
Request the map from the server.
Definition network_server.cpp:983
ServerNetworkGameSocketHandler::SendSync
NetworkRecvStatus SendSync()
Request the client to sync.
Definition network_server.cpp:639
ServerNetworkGameSocketHandler::authentication_handler
std::unique_ptr< class NetworkAuthenticationServerHandler > authentication_handler
The handler for the authentication.
Definition network_server.h:26
ServerNetworkGameSocketHandler::SendMove
NetworkRecvStatus SendMove(ClientID client_id, CompanyID company_id)
Tell that a client moved to another company.
Definition network_server.cpp:798
ServerNetworkGameSocketHandler::Receive_CLIENT_RCON
NetworkRecvStatus Receive_CLIENT_RCON(Packet &p) override
Send an RCon command to the server: string RCon password.
Definition network_server.cpp:1441
ServerNetworkGameSocketHandler::SendError
NetworkRecvStatus SendError(NetworkErrorCode error, std::string_view reason={})
Send an error to the client, and close its connection.
Definition network_server.cpp:359
ServerNetworkGameSocketHandler::ServerNetworkGameSocketHandler
ServerNetworkGameSocketHandler(SOCKET s)
Create a new socket for the server side of the game connection.
Definition network_server.cpp:191
ServerNetworkGameSocketHandler::Receive_CLIENT_IDENTIFY
NetworkRecvStatus Receive_CLIENT_IDENTIFY(Packet &p) override
The client tells the server about the identity of the client: string Name of the client (max NETWORK_...
Definition network_server.cpp:872
ServerNetworkGameSocketHandler::CloseConnection
NetworkRecvStatus CloseConnection(NetworkRecvStatus status) override
Close the network connection due to the given status.
Definition network_server.cpp:235
ServerNetworkGameSocketHandler::SendMap
NetworkRecvStatus SendMap()
This sends the map to the client.
Definition network_server.cpp:550
ServerNetworkGameSocketHandler::Receive_CLIENT_NEWGRFS_CHECKED
NetworkRecvStatus Receive_CLIENT_NEWGRFS_CHECKED(Packet &p) override
Tell the server that we have the required GRFs.
Definition network_server.cpp:834
ServerNetworkGameSocketHandler::last_token_frame
uint32_t last_token_frame
The last frame we received the right token.
Definition network_server.h:69
ServerNetworkGameSocketHandler::Receive_CLIENT_MAP_OK
NetworkRecvStatus Receive_CLIENT_MAP_OK(Packet &p) override
Tell the server that we are done receiving/loading the map.
Definition network_server.cpp:1007
ServerNetworkGameSocketHandler::SendShutdown
NetworkRecvStatus SendShutdown()
Tell the client we're shutting down.
Definition network_server.cpp:757
ServerNetworkGameSocketHandler::status
ClientStatus status
Status of this client.
Definition network_server.h:70
ServerNetworkGameSocketHandler::SendNewGRFCheck
NetworkRecvStatus SendNewGRFCheck()
Send the check for the NewGRFs.
Definition network_server.cpp:404
ServerNetworkGameSocketHandler::GetClientIP
std::string_view GetClientIP()
Get the IP address/hostname of the connected client.
Definition network_server.cpp:1919
ServerNetworkGameSocketHandler::SendConfigUpdate
NetworkRecvStatus SendConfigUpdate()
Send an update about the max company/spectator counts.
Definition network_server.cpp:811
ServerNetworkGameSocketHandler::SendWait
NetworkRecvStatus SendWait()
Tell the client that its put in a waiting queue.
Definition network_server.cpp:502
ServerNetworkGameSocketHandler::SendCommand
NetworkRecvStatus SendCommand(const CommandPacket &cp)
Send a command to the client to execute.
Definition network_server.cpp:658
TCPListenHandler
Template for TCP listeners.
Definition tcp_listen.h:30
Ticks::DAY_TICKS
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
Definition timer_game_tick.h:75
TimerGameCalendar::year
static Year year
Current year, starting at 0.
Definition timer_game_calendar.h:31
TimerGameEconomy::date
static Date date
Current date in days (day counter).
Definition timer_game_economy.h:38
TimerGameEconomy::date_fract
static DateFract date_fract
Fractional part of the day.
Definition timer_game_economy.h:39
TimerGameRealtime::UNPAUSED
@ UNPAUSED
Only run when not paused.
Definition timer_game_realtime.h:32
TypedIndexContainer
A sort-of mixin that implements 'at(pos)' and 'operator[](pos)' only for a specific type.
Definition convertible_through_base.hpp:38
GetCommandFlags
CommandFlags GetCommandFlags(Commands cmd)
This function mask the parameter with CMD_ID_MASK and returns the flags which belongs to the given co...
Definition command.cpp:118
CommandFlag::Spectator
@ Spectator
the command may be initiated by a spectator
CommandFlag::Server
@ Server
the command can only be initiated by the server
CommandFlag::ClientID
@ ClientID
set p2 with the ClientID of the sending client.
CMD_COMPANY_CTRL
@ CMD_COMPANY_CTRL
used in multiplayer to create a new companies etc.
Definition command_type.h:312
CMD_COMPANY_ALLOW_LIST_CTRL
@ CMD_COMPANY_ALLOW_LIST_CTRL
Used in multiplayer to add/remove a client's public key to/from the company's allow list.
Definition command_type.h:313
GetDrawStringCompanyColour
TextColour GetDrawStringCompanyColour(CompanyID company)
Get the colour for DrawString-subroutines which matches the colour of the company.
Definition company_cmd.cpp:153
_local_company
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition company_cmd.cpp:55
SetLocalCompany
void SetLocalCompany(CompanyID new_company)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
Definition company_cmd.cpp:119
CompanyCtrlAction
CompanyCtrlAction
The action to do with CMD_COMPANY_CTRL.
Definition company_type.h:71
CCA_DELETE
@ CCA_DELETE
Delete a company.
Definition company_type.h:74
CCA_NEW
@ CCA_NEW
Create a new company.
Definition company_type.h:72
COMPANY_SPECTATOR
static constexpr CompanyID COMPANY_SPECTATOR
The client is spectating.
Definition company_type.h:21
CALCA_ADD
@ CALCA_ADD
Create a public key.
Definition company_type.h:81
COMPANY_NEW_COMPANY
static constexpr CompanyID COMPANY_NEW_COMPANY
The client wants a new company.
Definition company_type.h:20
CRR_AUTOCLEAN
@ CRR_AUTOCLEAN
The company is removed due to autoclean.
Definition company_type.h:62
TCP_MTU
static const size_t TCP_MTU
Number of bytes we can pack in a single TCP packet.
Definition config.h:45
NETWORK_CLIENT_NAME_LENGTH
static const uint NETWORK_CLIENT_NAME_LENGTH
The maximum length of a client's name, in bytes including '\0'.
Definition config.h:58
NETWORK_CHAT_LENGTH
static const uint NETWORK_CHAT_LENGTH
The maximum length of a chat message, in bytes including '\0'.
Definition config.h:61
NETWORK_REVISION_LENGTH
static const uint NETWORK_REVISION_LENGTH
The maximum length of the revision, in bytes including '\0'.
Definition config.h:56
NETWORK_RCONCOMMAND_LENGTH
static const uint NETWORK_RCONCOMMAND_LENGTH
The maximum length of a rconsole command, in bytes including '\0'.
Definition config.h:59
NETWORK_PASSWORD_LENGTH
static const uint NETWORK_PASSWORD_LENGTH
The maximum length of the password, in bytes including '\0'.
Definition config.h:57
IConsoleCmdExec
void IConsoleCmdExec(std::string_view command_string, const uint recurse_count)
Execute a given command passed to us.
Definition console.cpp:269
IConsolePrint
void IConsolePrint(TextColour colour_code, const std::string &string)
Handle the printing of text entered into the console or redirected there by any other means.
Definition console.cpp:90
CC_INFO
static const TextColour CC_INFO
Colour for information lines.
Definition console_type.h:27
CC_WARNING
static const TextColour CC_WARNING
Colour for warning lines.
Definition console_type.h:25
CC_DEFAULT
static const TextColour CC_DEFAULT
Default colour of the console.
Definition console_type.h:23
NetworkRecvStatus
NetworkRecvStatus
Status of a network client; reasons why a client has quit.
Definition core.h:23
NETWORK_RECV_STATUS_CLIENT_QUIT
@ NETWORK_RECV_STATUS_CLIENT_QUIT
The connection is lost gracefully. Other clients are already informed of this leaving client.
Definition core.h:28
NETWORK_RECV_STATUS_SERVER_ERROR
@ NETWORK_RECV_STATUS_SERVER_ERROR
The server told us we made an error.
Definition core.h:30
NETWORK_RECV_STATUS_OKAY
@ NETWORK_RECV_STATUS_OKAY
Everything is okay.
Definition core.h:24
NETWORK_RECV_STATUS_MALFORMED_PACKET
@ NETWORK_RECV_STATUS_MALFORMED_PACKET
We apparently send a malformed packet.
Definition core.h:29
Debug
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
DECLARE_INCREMENT_DECREMENT_OPERATORS
#define DECLARE_INCREMENT_DECREMENT_OPERATORS(enum_type)
For some enums it is useful to have pre/post increment/decrement operators.
Definition enum_type.hpp:63
FT_SCENARIO
@ FT_SCENARIO
old or new scenario
Definition fileio_type.h:20
FT_HEIGHTMAP
@ FT_HEIGHTMAP
heightmap file
Definition fileio_type.h:21
FT_SAVEGAME
@ FT_SAVEGAME
old or new savegame
Definition fileio_type.h:19
GENERATE_NEW_SEED
static const uint32_t GENERATE_NEW_SEED
Create a new random seed.
Definition genworld.h:25
_switch_mode
SwitchMode _switch_mode
The next mainloop command.
Definition gfx.cpp:49
TextColour
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
Definition gfx_type.h:307
MILLISECONDS_PER_TICK
static const uint MILLISECONDS_PER_TICK
The number of milliseconds per game tick.
Definition gfx_type.h:370
_last_sync_frame
uint32_t _last_sync_frame
Used in the server to store the last time a sync packet was sent to clients.
Definition network.cpp:81
GetNetworkErrorMsg
StringID GetNetworkErrorMsg(NetworkErrorCode err)
Retrieve the string id of an internal error number.
Definition network.cpp:311
_redirect_console_to_client
ClientID _redirect_console_to_client
If not invalid, redirect the console output to a client.
Definition network.cpp:73
_frame_counter
uint32_t _frame_counter
The current frame.
Definition network.cpp:80
_network_ban_list
StringList _network_ban_list
The banned clients.
Definition network.cpp:77
_network_dedicated
bool _network_dedicated
are we a dedicated server?
Definition network.cpp:70
_network_server
bool _network_server
network-server is active
Definition network.cpp:68
_sync_seed_1
uint32_t _sync_seed_1
Seed to compare during sync checks.
Definition network.cpp:83
_network_clients_connected
uint8_t _network_clients_connected
The amount of clients connected.
Definition network.cpp:91
_frame_counter_max
uint32_t _frame_counter_max
To where we may go with our clients.
Definition network.cpp:79
NetworkAdminClientUpdate
void NetworkAdminClientUpdate(const NetworkClientInfo *ci)
Notify the admin network of a client update (if they did opt in for the respective update).
Definition network_admin.cpp:896
NetworkAdminClientQuit
void NetworkAdminClientQuit(ClientID client_id)
Notify the admin network that a client quit (if they have opt in for the respective update).
Definition network_admin.cpp:909
NetworkAdminChat
void NetworkAdminChat(NetworkAction action, DestType desttype, ClientID client_id, std::string_view msg, int64_t data, bool from_admin)
Send chat to the admin network (if they did opt in for the respective update).
Definition network_admin.cpp:982
NetworkAdminUpdate
void NetworkAdminUpdate(AdminUpdateFrequency freq)
Send (push) updates to the admin network as they have registered for these updates.
Definition network_admin.cpp:1061
NetworkAdminClientInfo
void NetworkAdminClientInfo(const NetworkClientSocket *cs, bool new_client)
Notify the admin network of a new client (if they did opt in for the respective update).
Definition network_admin.cpp:880
NetworkAdminClientError
void NetworkAdminClientError(ClientID client_id, NetworkErrorCode error_code)
Notify the admin network of a client error (if they have opt in for the respective update).
Definition network_admin.cpp:923
network_admin.h
Server part of the admin network protocol.
network_base.h
Base core network types and some helper functions to access them.
NetworkIsValidClientName
bool NetworkIsValidClientName(std::string_view client_name)
Check whether the given client name is deemed valid for use in network games.
Definition network_client.cpp:1245
NetworkSyncCommandQueue
void NetworkSyncCommandQueue(NetworkClientSocket *cs)
Sync our local command queue to the command queue of the given socket.
Definition network_command.cpp:245
NetworkReplaceCommandClientId
void NetworkReplaceCommandClientId(CommandPacket &cp, ClientID client_id)
Insert a client ID into the command data in a command packet.
Definition network_command.cpp:444
NetworkAuthenticationMethod
NetworkAuthenticationMethod
The authentication method that can be used.
Definition network_crypto.h:177
NetworkAuthenticationMethod::X25519_PAKE
@ X25519_PAKE
Authentication using x25519 password-authenticated key agreement.
NetworkAuthenticationMethod::X25519_AuthorizedKey
@ X25519_AuthorizedKey
Authentication using x22519 key exchange and authorized keys.
NetworkUpdateClientInfo
void NetworkUpdateClientInfo(ClientID client_id)
Send updated client info of a particular client.
Definition network_server.cpp:1529
NetworkServerDoMove
void NetworkServerDoMove(ClientID client_id, CompanyID company_id)
Handle the tid-bits of moving a client from one company to another.
Definition network_server.cpp:1976
NetworkServerSendChat
void NetworkServerSendChat(NetworkAction action, DestType type, int dest, std::string_view msg, ClientID from_id, int64_t data=0, bool from_admin=false)
Send an actual chat message.
Definition network_server.cpp:1252
NetworkMakeClientNameUnique
bool NetworkMakeClientNameUnique(std::string &new_name)
Check whether a name is unique, and otherwise try to make it unique.
Definition network_server.cpp:1608
NetworkServerChangeClientName
bool NetworkServerChangeClientName(ClientID client_id, const std::string &new_name)
Change the client name of the given client.
Definition network_server.cpp:1647
NetworkServerSendExternalChat
void NetworkServerSendExternalChat(std::string_view source, TextColour colour, std::string_view user, std::string_view msg)
Send a chat message from external source.
Definition network_server.cpp:1369
NetworkPrintClients
void NetworkPrintClients()
Print all the clients to the console.
Definition network_server.cpp:2115
NetworkServerUpdateGameInfo
void NetworkServerUpdateGameInfo()
Update the server's NetworkServerGameInfo due to changes in settings.
Definition network_server.cpp:1965
NetworkGetCompanyStats
NetworkCompanyStatsArray NetworkGetCompanyStats()
Get the company stats.
Definition network_server.cpp:1491
NetworkUpdateClientInfo
void NetworkUpdateClientInfo(ClientID client_id)
Send updated client info of a particular client.
Definition network_server.cpp:1529
NetworkServerSendChat
void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, std::string_view msg, ClientID from_id, int64_t data, bool from_admin)
Send an actual chat message.
Definition network_server.cpp:1252
_rcon_authorized_key_handler
static NetworkAuthenticationDefaultAuthorizedKeyHandler _rcon_authorized_key_handler(_settings_client.network.rcon_authorized_keys)
Provides the authorized key validation for rcon.
_password_provider
static NetworkAuthenticationDefaultPasswordProvider _password_provider(_settings_client.network.server_password)
Provides the password validation for the game's password.
NetworkServerSendConfigUpdate
void NetworkServerSendConfigUpdate()
Send Config Update.
Definition network_server.cpp:1957
_network_weekly
static const IntervalTimer< TimerGameEconomy > _network_weekly({TimerGameEconomy::WEEK, TimerGameEconomy::Priority::NONE}, [](auto) { if(!_network_server) return;NetworkAdminUpdate(AdminUpdateFrequency::Weekly);})
Economy weekly "callback".
NetworkServerDoMove
void NetworkServerDoMove(ClientID client_id, CompanyID company_id)
Handle the tid-bits of moving a client from one company to another.
Definition network_server.cpp:1976
ChangeNetworkRestartTime
void ChangeNetworkRestartTime(bool reset)
Reset the automatic network restart time interval.
Definition network_server.cpp:1847
NetworkCompanyHasClients
bool NetworkCompanyHasClients(CompanyID company)
Check whether a particular company has clients.
Definition network_server.cpp:2090
NetworkRestartMap
static void NetworkRestartMap()
Helper function to restart the map.
Definition network_server.cpp:1813
NetworkServerKickClient
void NetworkServerKickClient(ClientID client_id, std::string_view reason)
Kick a single client.
Definition network_server.cpp:2029
NetworkCheckRestartMapYear
static void NetworkCheckRestartMapYear()
Check if we want to restart the map based on the year.
Definition network_server.cpp:1855
NetworkMakeClientNameUnique
bool NetworkMakeClientNameUnique(std::string &name)
Check whether a name is unique, and otherwise try to make it unique.
Definition network_server.cpp:1608
_network_client_id
static ClientID _network_client_id
The identifier counter for new clients (is never decreased)
Definition network_server.cpp:49
NetworkGetPublicKeyOfClient
std::string_view NetworkGetPublicKeyOfClient(ClientID client_id)
Get the public key of the client with the given id.
Definition network_server.cpp:2138
_authorized_key_handler
static NetworkAuthenticationDefaultAuthorizedKeyHandler _authorized_key_handler(_settings_client.network.server_authorized_keys)
Provides the authorized key handling for the game authentication.
_economy_network_daily
static const IntervalTimer< TimerGameEconomy > _economy_network_daily({TimerGameEconomy::DAY, TimerGameEconomy::Priority::NONE}, [](auto) { if(!_network_server) return;NetworkAdminUpdate(AdminUpdateFrequency::Daily);})
Daily "callback".
NetworkHandleCommandQueue
static void NetworkHandleCommandQueue(NetworkClientSocket *cs)
Handle the command-queue of a socket.
Definition network_server.cpp:1669
_calendar_network_yearly
static const IntervalTimer< TimerGameCalendar > _calendar_network_yearly({ TimerGameCalendar::YEAR, TimerGameCalendar::Priority::NONE }, [](auto) { if(!_network_server) return;NetworkCheckRestartMapYear();})
Calendar yearly "callback".
_network_quarterly
static const IntervalTimer< TimerGameEconomy > _network_quarterly({TimerGameEconomy::QUARTER, TimerGameEconomy::Priority::NONE}, [](auto) { if(!_network_server) return;NetworkAutoCleanCompanies();NetworkAdminUpdate(AdminUpdateFrequency::Quarterly);})
Quarterly "callback".
NetworkServerShowStatusToConsole
void NetworkServerShowStatusToConsole()
Show the status message of all clients on the console.
Definition network_server.cpp:1925
NetworkServerNewCompany
void NetworkServerNewCompany(const Company *c, NetworkClientInfo *ci)
Perform all the server specific administration of a new company.
Definition network_server.cpp:2150
NetworkServerSendRcon
void NetworkServerSendRcon(ClientID client_id, TextColour colour_code, std::string_view string)
Send an rcon reply to the client.
Definition network_server.cpp:2019
NetworkServerKickOrBanIP
uint NetworkServerKickOrBanIP(ClientID client_id, bool ban, std::string_view reason)
Ban, or kick, everyone joined from the given client's IP.
Definition network_server.cpp:2041
NetworkServer_Tick
void NetworkServer_Tick(bool send_frame)
This is called every tick if this is a _network_server.
Definition network_server.cpp:1679
_networkclientsocket_pool
NetworkClientSocketPool _networkclientsocket_pool("NetworkClientSocket")
Make very sure the preconditions given in network_type.h are actually followed.
_network_restart_map_timer
static IntervalTimer< TimerGameRealtime > _network_restart_map_timer({std::chrono::hours::zero(), TimerGameRealtime::UNPAUSED}, [](auto) { if(!_network_server) return;if(_settings_client.network.restart_hours==0) return;Debug(net, 3, "Auto-restarting map: {} hours played", _settings_client.network.restart_hours);NetworkRestartMap();})
Timer to restart a network server automatically based on real-time hours played.
_network_monthly
static const IntervalTimer< TimerGameEconomy > _network_monthly({TimerGameEconomy::MONTH, TimerGameEconomy::Priority::NONE}, [](auto) { if(!_network_server) return;NetworkAutoCleanCompanies();NetworkAdminUpdate(AdminUpdateFrequency::Monthly);})
Economy monthly "callback".
NetworkAutoCleanCompanies
static void NetworkAutoCleanCompanies()
Remove companies that have not been used depending on the autoclean_companies setting and values for ...
Definition network_server.cpp:1551
_economy_network_yearly
static const IntervalTimer< TimerGameEconomy > _economy_network_yearly({TimerGameEconomy::YEAR, TimerGameEconomy::Priority::NONE}, [](auto) { if(!_network_server) return;NetworkAdminUpdate(AdminUpdateFrequency::Annually);})
Economy yearly "callback".
network_server.h
Server part of the network protocol.
DestType
DestType
Destination of our chat messages.
Definition network_type.h:68
DESTTYPE_CLIENT
@ DESTTYPE_CLIENT
Send message/notice to only a certain client (Private)
Definition network_type.h:71
DESTTYPE_TEAM
@ DESTTYPE_TEAM
Send message/notice to everyone playing the same company (Team)
Definition network_type.h:70
DESTTYPE_BROADCAST
@ DESTTYPE_BROADCAST
Send message/notice to all clients (All)
Definition network_type.h:69
NetworkErrorCode
NetworkErrorCode
The error codes we send around in the protocols.
Definition network_type.h:99
NetworkAction
NetworkAction
Actions that can be used for NetworkTextMessage.
Definition network_type.h:79
MAX_CLIENTS
static const uint MAX_CLIENTS
How many clients can we have.
Definition network_type.h:17
ClientID
ClientID
'Unique' identifier to be given to clients
Definition network_type.h:43
INVALID_CLIENT_ID
@ INVALID_CLIENT_ID
Client is not part of anything.
Definition network_type.h:44
CLIENT_ID_SERVER
@ CLIENT_ID_SERVER
Servers always have this ID.
Definition network_type.h:45
CLIENT_ID_FIRST
@ CLIENT_ID_FIRST
The first client ID.
Definition network_type.h:46
network_udp.h
Sending and receiving UDP messages.
_grfconfig
GRFConfigList _grfconfig
First item in list of current GRF set up.
Definition newgrf_config.cpp:154
Static
@ Static
GRF file is used statically (can be used in any MP game)
Definition newgrf_config.h:23
SM_START_HEIGHTMAP
@ SM_START_HEIGHTMAP
Load a heightmap and start a new game from it.
Definition openttd.h:38
SM_LOAD_GAME
@ SM_LOAD_GAME
Load game, Play Scenario.
Definition openttd.h:32
SM_NEWGAME
@ SM_NEWGAME
New Game --> 'Random game'.
Definition openttd.h:28
INSTANTIATE_POOL_METHODS
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
Definition pool_func.hpp:210
SlError
void SlError(StringID string, const std::string &extra_msg)
Error handler.
Definition saveload.cpp:339
SaveWithFilter
SaveOrLoadResult SaveWithFilter(std::shared_ptr< SaveFilter > writer, bool threaded)
Save the game using a (writer) filter.
Definition saveload.cpp:3078
_file_to_saveload
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Definition saveload.cpp:78
SL_OK
@ SL_OK
completed successfully
Definition saveload.h:421
_settings_newgame
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
Definition settings.cpp:62
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
StationFacility::Dock
@ Dock
Station with a dock.
StationFacility::TruckStop
@ TruckStop
Station with truck stops.
StationFacility::Train
@ Train
Station with train station.
StationFacility::Airport
@ Airport
Station with an airport.
StationFacility::BusStop
@ BusStop
Station with bus stops.
lengthof
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:271
GetString
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:424
StringID
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Definition strings_type.h:19
ClientSettings::network
NetworkSettings network
settings related to the network
Definition settings_type.h:651
CommandHelper
Definition command_func.h:84
CommandPacket
Everything we need to know about a command to be able to execute it.
Definition network_internal.h:95
CommandPacket::data
CommandDataBuffer data
command parameters.
Definition network_internal.h:103
CommandPacket::frame
uint32_t frame
the frame in which this packet is executed
Definition network_internal.h:97
CommandPacket::company
CompanyID company
company that is executing the command
Definition network_internal.h:96
CommandPacket::my_cmd
bool my_cmd
did the command originate from "me"
Definition network_internal.h:98
CommandPacket::cmd
Commands cmd
command being executed.
Definition network_internal.h:100
CommandTraits
Defines the traits of a command.
Definition command_type.h:464
CompanyProperties::months_empty
uint8_t months_empty
NOSAVE: Number of months this company has not had a client in multiplayer.
Definition company_base.h:99
Company
Definition company_base.h:127
Company::IsValidHumanID
static bool IsValidHumanID(auto index)
Is this company a valid company, not controlled by a NoAI program?
Definition company_base.h:165
FileToSaveLoad::ftype
FiosType ftype
File type.
Definition saveload.h:429
FiosType::abstract
AbstractFileType abstract
Abstract file type.
Definition fileio_type.h:64
GameCreationSettings::generation_seed
uint32_t generation_seed
noise seed for world generation
Definition settings_type.h:379
GameSettings::game_creation
GameCreationSettings game_creation
settings used during the creation of a game (map)
Definition settings_type.h:634
GroupStatistics
Statistics and caches on the vehicles in a group.
Definition group.h:25
NetworkClientInfo
Container for all information known about a client.
Definition network_base.h:24
NetworkClientInfo::GetByClientID
static NetworkClientInfo * GetByClientID(ClientID client_id)
Return the CI given it's client-identifier.
Definition network.cpp:118
NetworkClientInfo::join_date
TimerGameEconomy::Date join_date
Gamedate the client has joined.
Definition network_base.h:29
NetworkClientInfo::client_playas
CompanyID client_playas
As which company is this client playing (CompanyID)
Definition network_base.h:28
NetworkClientInfo::client_id
ClientID client_id
Client identifier (same as ClientState->client_id)
Definition network_base.h:25
NetworkClientInfo::client_name
std::string client_name
Name of the client.
Definition network_base.h:26
NetworkClientInfo::public_key
std::string public_key
The public key of the client.
Definition network_base.h:27
NetworkCompanyStats
Simple calculated statistics of a company.
Definition network_type.h:56
NetworkCompanyStats::num_station
uint16_t num_station[NETWORK_VEH_END]
How many stations are there of this type?
Definition network_type.h:58
NetworkServerGameInfo::clients_on
uint8_t clients_on
Current count of clients on server.
Definition network_game_info.h:108
NetworkSettings::max_clients
uint8_t max_clients
maximum amount of clients
Definition settings_type.h:365
NetworkSettings::bytes_per_frame_burst
uint16_t bytes_per_frame_burst
how many bytes may, over a short period, be received?
Definition settings_type.h:336
NetworkSettings::autoclean_companies
bool autoclean_companies
automatically remove companies that are not in use
Definition settings_type.h:361
NetworkSettings::server_admin_chat
bool server_admin_chat
allow private chat for the server to be distributed to the admin network
Definition settings_type.h:345
NetworkSettings::restart_game_year
TimerGameCalendar::Year restart_game_year
year the server restarts
Definition settings_type.h:366
NetworkSettings::max_companies
uint8_t max_companies
maximum amount of companies
Definition settings_type.h:364
NetworkSettings::autoclean_protected
uint8_t autoclean_protected
Remove companies after this many months.
Definition settings_type.h:362
NetworkSettings::max_password_time
uint16_t max_password_time
maximum amount of time, in game ticks, a client may take to enter the password
Definition settings_type.h:340
NetworkSettings::max_join_time
uint16_t max_join_time
maximum amount of time, in game ticks, a client may take to sync up during joining
Definition settings_type.h:338
NetworkSettings::bytes_per_frame
uint16_t bytes_per_frame
how many bytes may, over a long period, be received per frame?
Definition settings_type.h:335
NetworkSettings::max_init_time
uint16_t max_init_time
maximum amount of time, in game ticks, a client may take to initiate joining
Definition settings_type.h:337
NetworkSettings::max_lag_time
uint16_t max_lag_time
maximum amount of time, in game ticks, a client may be lagging behind the server
Definition settings_type.h:341
NetworkSettings::autoclean_novehicles
uint8_t autoclean_novehicles
remove companies with no vehicles after this many months
Definition settings_type.h:363
NetworkSettings::max_commands_in_queue
uint16_t max_commands_in_queue
how many commands may there be in the incoming queue before dropping the connection?
Definition settings_type.h:334
NetworkSettings::server_name
std::string server_name
name of the server
Definition settings_type.h:349
NetworkSettings::restart_hours
uint16_t restart_hours
number of hours to run the server before automatic restart
Definition settings_type.h:367
NetworkSettings::max_download_time
uint16_t max_download_time
maximum amount of time, in game ticks, a client may take to download the map
Definition settings_type.h:339
NetworkSettings::sync_freq
uint16_t sync_freq
how often do we check whether we are still in-sync
Definition settings_type.h:330
NetworkSettings::rcon_password
std::string rcon_password
password for rconsole (server side)
Definition settings_type.h:352
OrderBackup::ResetUser
static void ResetUser(uint32_t user)
Reset an user's OrderBackup if needed.
Definition order_backup.cpp:146
PacketWriter
Writing a savegame directly to a number of packets.
Definition network_server.cpp:67
PacketWriter::Write
void Write(uint8_t *buf, size_t size) override
Write a given number of bytes into the savegame.
Definition network_server.cpp:144
PacketWriter::current
std::unique_ptr< Packet > current
The packet we're currently writing to.
Definition network_server.cpp:69
PacketWriter::PacketWriter
PacketWriter(ServerNetworkGameSocketHandler *cs)
Create the packet writer.
Definition network_server.cpp:79
PacketWriter::total_size
size_t total_size
Total size of the compressed savegame.
Definition network_server.cpp:70
PacketWriter::exit_sig
std::condition_variable exit_sig
Signal for threaded destruction of this packet writer.
Definition network_server.cpp:73
PacketWriter::Finish
void Finish() override
Prepare everything to finish writing the savegame.
Definition network_server.cpp:166
PacketWriter::cs
ServerNetworkGameSocketHandler * cs
Socket we are associated with.
Definition network_server.cpp:68
PacketWriter::mutex
std::mutex mutex
Mutex for making threaded saving safe.
Definition network_server.cpp:72
PacketWriter::Destroy
void Destroy()
Begin the destruction of this packet writer.
Definition network_server.cpp:106
PacketWriter::TransferToNetworkQueue
bool TransferToNetworkQueue()
Transfer all packets from here to the network's queue while holding the lock on our mutex.
Definition network_server.cpp:126
PacketWriter::~PacketWriter
~PacketWriter()
Make sure everything is cleaned up.
Definition network_server.cpp:84
PacketWriter::packets
std::deque< std::unique_ptr< Packet > > packets
Packet queue of the savegame; send these "slowly" to the client. Cannot be a std::queue as we want to...
Definition network_server.cpp:71
Packet
Internal entity of a packet.
Definition packet.h:43
Packet::Recv_uint64
uint64_t Recv_uint64()
Read a 64 bits integer from the packet.
Definition packet.cpp:364
Packet::Recv_uint32
uint32_t Recv_uint32()
Read a 32 bits integer from the packet.
Definition packet.cpp:347
Packet::Recv_string
std::string Recv_string(size_t length, StringValidationSettings settings=StringValidationSetting::ReplaceWithQuestionMark)
Reads characters (bytes) from the packet until it finds a '\0', or reaches a maximum of length charac...
Definition packet.cpp:425
Packet::Recv_uint8
uint8_t Recv_uint8()
Read a 8 bits integer from the packet.
Definition packet.cpp:318
PoolID< uint8_t, struct CompanyIDTag, 0xF, 0xFF >
Pool::PoolItem<&_networkclientsocket_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition pool_type.hpp:436
Pool::PoolItem<&_company_pool >::Get
static Titem * Get(auto index)
Returns Titem with given index.
Definition pool_type.hpp:387
Pool::PoolItem<&_company_pool >::GetNumItems
static size_t GetNumItems()
Returns number of valid items in the pool.
Definition pool_type.hpp:417
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition pool_type.hpp:286
Pool::PoolItem<&_networkclientsocket_pool >::CanAllocateItem
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
Definition pool_type.hpp:357
Pool::PoolItem<&_company_pool >::IsValidID
static bool IsValidID(auto index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition pool_type.hpp:376
Pool::PoolItem<&_company_pool >::GetIfValid
static Titem * GetIfValid(auto index)
Returns Titem with given index.
Definition pool_type.hpp:398
Pool
Base class for all pools.
Definition pool_type.hpp:133
Pool::MAX_SIZE
static constexpr size_t MAX_SIZE
Make template parameter accessible from outside.
Definition pool_type.hpp:135
SaveFilter
Interface for filtering a savegame till it is written.
Definition saveload_filter.h:57
SpecializedStation< Station, false >::Iterate
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
Definition base_station_base.h:299
SpecializedVehicle::From
static T * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Definition vehicle_base.h:1134
Station
Station data structure.
Definition station_base.h:520
Vehicle
Vehicle data structure.
Definition vehicle_base.h:205
SPS_CLOSED
@ SPS_CLOSED
The connection got closed.
Definition tcp.h:24
AdminUpdateFrequency::Annually
@ Annually
The admin gets information about this on a yearly basis.
AdminUpdateFrequency::Weekly
@ Weekly
The admin gets information about this on a weekly basis.
AdminUpdateFrequency::Monthly
@ Monthly
The admin gets information about this on a monthly basis.
AdminUpdateFrequency::Quarterly
@ Quarterly
The admin gets information about this on a quarterly basis.
AdminUpdateFrequency::Daily
@ Daily
The admin gets information about this on a daily basis.
PACKET_SERVER_JOIN
@ PACKET_SERVER_JOIN
Tells clients that a new client has joined.
Definition tcp_game.h:86
PACKET_SERVER_MAP_SIZE
@ PACKET_SERVER_MAP_SIZE
Server tells the client what the (compressed) size of the map is.
Definition tcp_game.h:81
PACKET_SERVER_RCON
@ PACKET_SERVER_RCON
Response of the executed command on the server.
Definition tcp_game.h:110
PACKET_SERVER_MAP_BEGIN
@ PACKET_SERVER_MAP_BEGIN
Server tells the client that it is beginning to send the map.
Definition tcp_game.h:80
PACKET_SERVER_SYNC
@ PACKET_SERVER_SYNC
Server tells the client what the random state should be.
Definition tcp_game.h:97
PACKET_SERVER_WAIT
@ PACKET_SERVER_WAIT
Server tells the client there are some people waiting for the map as well.
Definition tcp_game.h:79
PACKET_SERVER_CONFIG_UPDATE
@ PACKET_SERVER_CONFIG_UPDATE
Some network configuration important to the client changed.
Definition tcp_game.h:118
PACKET_SERVER_ENABLE_ENCRYPTION
@ PACKET_SERVER_ENABLE_ENCRYPTION
The server tells that authentication has completed and requests to enable encryption with the keys of...
Definition tcp_game.h:64
PACKET_SERVER_GAME_INFO
@ PACKET_SERVER_GAME_INFO
Information about the server.
Definition tcp_game.h:44
PACKET_SERVER_ERROR_QUIT
@ PACKET_SERVER_ERROR_QUIT
A server tells that a client has hit an error and did quit.
Definition tcp_game.h:124
PACKET_SERVER_CLIENT_INFO
@ PACKET_SERVER_CLIENT_INFO
Server sends you information about a client.
Definition tcp_game.h:75
PACKET_SERVER_WELCOME
@ PACKET_SERVER_WELCOME
Server welcomes you and gives you your ClientID.
Definition tcp_game.h:74
PACKET_SERVER_BANNED
@ PACKET_SERVER_BANNED
The server has banned you.
Definition tcp_game.h:33
PACKET_SERVER_FRAME
@ PACKET_SERVER_FRAME
Server tells the client what frame it is in, and thus to where the client may progress.
Definition tcp_game.h:95
PACKET_SERVER_EXTERNAL_CHAT
@ PACKET_SERVER_EXTERNAL_CHAT
Server distributing the message from external source.
Definition tcp_game.h:106
PACKET_SERVER_CHAT
@ PACKET_SERVER_CHAT
Server distributing the message of a client (or itself).
Definition tcp_game.h:105
PACKET_SERVER_COMMAND
@ PACKET_SERVER_COMMAND
Server distributes a command to (all) the clients.
Definition tcp_game.h:101
PACKET_SERVER_SHUTDOWN
@ PACKET_SERVER_SHUTDOWN
The server is shutting down.
Definition tcp_game.h:49
PACKET_SERVER_AUTH_REQUEST
@ PACKET_SERVER_AUTH_REQUEST
The server requests the client to authenticate using a number of methods.
Definition tcp_game.h:62
PACKET_SERVER_NEWGAME
@ PACKET_SERVER_NEWGAME
The server is preparing to start a new game.
Definition tcp_game.h:48
PACKET_SERVER_MOVE
@ PACKET_SERVER_MOVE
Server tells everyone that someone is moved to another company.
Definition tcp_game.h:114
PACKET_SERVER_MAP_DATA
@ PACKET_SERVER_MAP_DATA
Server sends bits of the map to the client.
Definition tcp_game.h:82
PACKET_SERVER_FULL
@ PACKET_SERVER_FULL
The server is full and has no place for you.
Definition tcp_game.h:32
PACKET_SERVER_QUIT
@ PACKET_SERVER_QUIT
A server tells that a client has quit.
Definition tcp_game.h:122
PACKET_SERVER_ERROR
@ PACKET_SERVER_ERROR
Server sending an error message to the client.
Definition tcp_game.h:37
PACKET_SERVER_CHECK_NEWGRFS
@ PACKET_SERVER_CHECK_NEWGRFS
Server sends NewGRF IDs and MD5 checksums for the client to check.
Definition tcp_game.h:70
PACKET_SERVER_MAP_DONE
@ PACKET_SERVER_MAP_DONE
Server tells it has just sent the last bits of the map to the client.
Definition tcp_game.h:83
VEH_ROAD
@ VEH_ROAD
Road vehicle type.
Definition vehicle_type.h:26
VEH_AIRCRAFT
@ VEH_AIRCRAFT
Aircraft vehicle type.
Definition vehicle_type.h:28
VEH_SHIP
@ VEH_SHIP
Ship vehicle type.
Definition vehicle_type.h:27
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition vehicle_type.h:25
lock
std::mutex lock
synchronization for playback status fields
Definition win32_m.cpp:35
InvalidateWindowData
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition window.cpp:3297
WC_CLIENT_LIST
@ WC_CLIENT_LIST
Client list; Window numbers:
Definition window_type.h:489