OpenTTD Source 20261112-master-gbcbec5e63f
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
9
10#include "../stdafx.h"
11#include "../strings_func.h"
13#include "network_admin.h"
14#include "network_server.h"
15#include "network_base.h"
16#include "../console_func.h"
17#include "../company_base.h"
18#include "../command_func.h"
21#include "../station_base.h"
22#include "../genworld.h"
23#include "../company_func.h"
24#include "../company_gui.h"
25#include "../company_cmd.h"
26#include "../roadveh.h"
27#include "../order_backup.h"
28#include "../core/pool_func.hpp"
30#include "../company_cmd.h"
31#include "../rev.h"
32#include "../timer/timer.h"
36#include <mutex>
37#include <condition_variable>
38
39#include "table/strings.h"
40
41#include "../safeguards.h"
42
43
44/* This file handles all the server-commands */
45
49
51static_assert(NetworkClientSocketPool::MAX_SIZE > MAX_CLIENTS);
52
56
57
59
63
64
68 std::unique_ptr<Packet> current;
69 size_t total_size;
70 std::deque<std::unique_ptr<Packet>> packets;
71 std::mutex mutex;
72 std::condition_variable exit_sig;
73
81
83 ~PacketWriter() override
84 {
85 std::unique_lock<std::mutex> lock(this->mutex);
86
87 while (this->cs != nullptr) this->exit_sig.wait(lock);
88
89 /* This must all wait until the Destroy function is called. */
90
91 this->packets.clear();
92 this->current = nullptr;
93 }
94
105 void Destroy()
106 {
107 std::unique_lock<std::mutex> lock(this->mutex);
108
109 this->cs = nullptr;
110
111 this->exit_sig.notify_all();
112 lock.unlock();
113
114 /* Make sure the saving is completely cancelled. Yes,
115 * we need to handle the save finish as well as the
116 * next connection might just be requesting a map. */
117 WaitTillSaved();
118 }
119
126 {
127 /* Unsafe check for the queue being empty or not. */
128 if (this->packets.empty()) return false;
129
130 std::lock_guard<std::mutex> lock(this->mutex);
131
132 while (!this->packets.empty()) {
133 bool last_packet = this->packets.front()->GetPacketType() == to_underlying(PacketGameType::ServerMapDone);
134 this->cs->SendPacket(std::move(this->packets.front()));
135 this->packets.pop_front();
136
137 if (last_packet) return true;
138 }
139
140 return false;
141 }
142
143 void Write(const uint8_t *buf, size_t size) override
144 {
145 std::lock_guard<std::mutex> lock(this->mutex);
146
147 /* We want to abort the saving when the socket is closed. */
148 if (this->cs == nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
149
150 if (this->current == nullptr) this->current = std::make_unique<Packet>(this->cs, PacketGameType::ServerMapData, TCP_MTU);
151
152 std::span<const uint8_t> to_write(buf, size);
153 while (!to_write.empty()) {
154 to_write = this->current->Send_bytes(to_write);
155
156 if (!this->current->CanWriteToPacket(1)) {
157 this->packets.push_back(std::move(this->current));
158 if (!to_write.empty()) this->current = std::make_unique<Packet>(this->cs, PacketGameType::ServerMapData, TCP_MTU);
159 }
160 }
161
162 this->total_size += size;
163 }
164
165 void Finish() override
166 {
167 std::lock_guard<std::mutex> lock(this->mutex);
168
169 /* We want to abort the saving when the socket is closed. */
170 if (this->cs == nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
171
172 /* Make sure the last packet is flushed. */
173 if (this->current != nullptr) this->packets.push_back(std::move(this->current));
174
175 /* Add a packet stating that this is the end to the queue. */
176 this->packets.push_back(std::make_unique<Packet>(this->cs, PacketGameType::ServerMapDone));
177
178 /* Fast-track the size to the client. */
179 auto p = std::make_unique<Packet>(this->cs, PacketGameType::ServerMapSize);
180 p->Send_uint32((uint32_t)this->total_size);
181 this->packets.push_front(std::move(p));
182 }
183};
184
185
193{
195 this->receive_limit = _settings_client.network.bytes_per_frame_burst;
196
197 Debug(Facility::Net, Severity::Trace3, "client[{}] status = INACTIVE", this->client_id);
198
199 /* The Socket and Info pools need to be the same in size. After all,
200 * each Socket will be associated with at most one Info object. As
201 * such if the Socket was allocated the Info object can as well. */
203}
204
209{
210 delete this->GetInfo();
211
214
215 if (this->savegame != nullptr) {
216 this->savegame->Destroy();
217 this->savegame = nullptr;
218 }
219
220 InvalidateWindowData(WindowClass::NetworkClientList, 0);
221}
222
224{
225 /* Only allow receiving when we have some buffer free; this value
226 * can go negative, but eventually it will become positive again. */
227 if (this->receive_limit <= 0) return nullptr;
228
229 /* We can receive a packet, so try that and if needed account for
230 * the amount of received data. */
231 std::unique_ptr<Packet> p = this->NetworkTCPSocketHandler::ReceivePacket();
232 if (p != nullptr) this->receive_limit -= p->Size();
233 return p;
234}
235
237{
239 /*
240 * Sending a message just before leaving the game calls cs->SendPackets.
241 * This might invoke this function, which means that when we close the
242 * connection after cs->SendPackets we will close an already closed
243 * connection. This handles that case gracefully without having to make
244 * that code any more complex or more aware of the validity of the socket.
245 */
246 if (this->IsPendingDeletion() || this->sock == INVALID_SOCKET) return status;
247
249 /* We did not receive a leave message from this client... */
250 std::string client_name = this->GetClientName();
251
252 NetworkTextMessage(NetworkAction::ClientLeave, CC_DEFAULT, false, client_name, "", STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST);
253
254 /* Inform other clients of this... strange leaving ;) */
256 if (new_cs->status >= ClientStatus::Authorized && this != new_cs) {
257 new_cs->SendErrorQuit(this->client_id, NetworkErrorCode::ConnectionLost);
258 }
259 }
260 }
261
262 /* If we were transferring a map to this client, stop the savegame creation
263 * process and queue the next client to receive the map. */
264 if (this->status == ClientStatus::Map) {
265 /* Ensure the saving of the game is stopped too. */
266 this->savegame->Destroy();
267 this->savegame = nullptr;
268
269 this->CheckNextClientToSendMap(this);
270 }
271
273 Debug(Facility::Net, Severity::Notice, "[{}] Client #{} closed connection", ServerNetworkGameSocketHandler::GetName(), this->client_id);
274
275 /* We just lost one client :( */
276 if (this->status >= ClientStatus::Authorized) _network_game_info.clients_on--;
277 extern uint8_t _network_clients_connected;
279
280 this->SendPackets(true);
281
282 this->DeferDeletion();
283
284 return status;
285}
286
292{
293 extern uint8_t _network_clients_connected;
295
296 /* We can't go over the MAX_CLIENTS limit here. However, the
297 * pool must have place for all clients and ourself. */
300 return accept;
301}
302
305{
307 if (cs->writable) {
308 if (cs->SendPackets() != SendPacketsState::Closed && cs->status == ClientStatus::Map) {
309 /* This client is in the middle of a map-send, call the function for that */
310 cs->SendMap();
311 }
312 }
313 }
314}
315
317
318/***********
319 * Sending functions
320 ************/
321
328{
329 Debug(Facility::Net, Severity::Trace3, "client[{}] SendClientInfo(): client_id={}", this->client_id, ci->client_id);
330
331 if (ci->client_id != ClientID::Invalid) {
332 auto p = std::make_unique<Packet>(this, PacketGameType::ServerClientInfo);
333 p->Send_uint32(to_underlying(ci->client_id));
334 p->Send_uint8 (ci->client_playas);
335 p->Send_string(ci->client_name);
336 p->Send_string(ci->public_key);
337
338 this->SendPacket(std::move(p));
339 }
341}
342
348{
349 Debug(Facility::Net, Severity::Trace3, "client[{}] SendGameInfo()", this->client_id);
350
351 auto p = std::make_unique<Packet>(this, PacketGameType::ServerGameInfo, TCP_MTU);
353
354 this->SendPacket(std::move(p));
355
357}
358
366{
367 Debug(Facility::Net, Severity::Trace3, "client[{}] SendError(): error={}", this->client_id, error);
368
369 auto p = std::make_unique<Packet>(this, PacketGameType::ServerError);
370
371 p->Send_uint8(to_underlying(error));
372 if (!reason.empty()) p->Send_string(reason);
373 this->SendPacket(std::move(p));
374
375 StringID strid = GetNetworkErrorMsg(error);
376
377 /* Only send when the current client was in game */
378 if (this->status >= ClientStatus::Authorized) {
379 std::string client_name = this->GetClientName();
380
381 Debug(Facility::Net, Severity::Error, "'{}' made an error and has been disconnected: {}", client_name, GetString(strid));
382
383 if (error == NetworkErrorCode::Kicked && !reason.empty()) {
384 NetworkTextMessage(NetworkAction::ClientKicked, CC_DEFAULT, false, client_name, reason, strid);
385 } else {
386 NetworkTextMessage(NetworkAction::ClientLeave, CC_DEFAULT, false, client_name, "", strid);
387 }
388
390 if (new_cs->status >= ClientStatus::Authorized && new_cs != this) {
391 /* Some errors we filter to a more general error. Clients don't have to know the real
392 * reason a joining failed. */
395 }
396 new_cs->SendErrorQuit(this->client_id, error);
397 }
398 }
399
401 } else {
402 Debug(Facility::Net, Severity::Error, "Client {} made an error and has been disconnected: {}", this->client_id, GetString(strid));
403 }
404
405 /* The client made a mistake, so drop the connection now! */
407}
408
414{
415 Debug(Facility::Net, Severity::Trace3, "client[{}] SendNewGRFCheck()", this->client_id);
416
417 /* Invalid packet when status is anything but ClientStatus::Identify. */
419
420 Debug(Facility::Net, Severity::Trace3, "client[{}] status = NEWGRFS_CHECK", this->client_id);
422
423 if (_grfconfig.empty()) {
424 /* There are no NewGRFs, so they're welcome. */
425 return this->SendWelcome();
426 }
427
428 auto p = std::make_unique<Packet>(this, PacketGameType::ServerCheckNewGRFs, TCP_MTU);
429
430 uint grf_count = std::ranges::count_if(_grfconfig, [](const auto &c){ return !c->flags.Test(GRFConfigFlag::Static); });
431 p->Send_uint8 (grf_count);
432
433 for (const auto &c : _grfconfig) {
434 if (!c->flags.Test(GRFConfigFlag::Static)) SerializeGRFIdentifier(*p, c->ident);
435 }
436
437 this->SendPacket(std::move(p));
439}
440
446{
447 Debug(Facility::Net, Severity::Trace3, "client[{}] SendAuthRequest()", this->client_id);
448
449 /* Invalid packet when status is anything but ClientStatus::Inactive or ClientStatus::AuthGame. */
451
452 Debug(Facility::Net, Severity::Trace3, "client[{}] status = AUTH_GAME", this->client_id);
454
455 /* Reset 'lag' counters */
457
458 if (this->authentication_handler == nullptr) {
460 }
461
462 auto p = std::make_unique<Packet>(this, PacketGameType::ServerAuthenticationRequest);
463 this->authentication_handler->SendRequest(*p);
464
465 this->SendPacket(std::move(p));
467}
468
474{
475 Debug(Facility::Net, Severity::Trace3, "client[{}] SendEnableEncryption()", this->client_id);
476
477 /* Invalid packet when status is anything but ClientStatus::AuthGame. */
479
480 auto p = std::make_unique<Packet>(this, PacketGameType::ServerEnableEncryption);
481 this->authentication_handler->SendEnableEncryption(*p);
482 this->SendPacket(std::move(p));
484}
485
491{
492 Debug(Facility::Net, Severity::Trace3, "client[{}] SendWelcome()", this->client_id);
493
494 /* Invalid packet when status is anything but ClientStatus::NewGRFsCheck. */
496
497 Debug(Facility::Net, Severity::Trace3, "client[{}] status = AUTHORIZED", this->client_id);
499
500 /* Reset 'lag' counters */
502
503 _network_game_info.clients_on++;
504
505 auto p = std::make_unique<Packet>(this, PacketGameType::ServerWelcome);
506 p->Send_uint32(to_underlying(this->client_id));
507 this->SendPacket(std::move(p));
508
509 /* Transmit info about all the active clients */
511 if (new_cs != this && new_cs->status >= ClientStatus::Authorized) {
512 this->SendClientInfo(new_cs->GetInfo());
513 }
514 }
515 /* Also send the info of the server */
517}
518
524{
525 Debug(Facility::Net, Severity::Trace3, "client[{}] SendWait()", this->client_id);
526
527 int waiting = 1; // current player getting the map counts as 1
528
529 /* Count how many clients are waiting in the queue, in front of you! */
531 if (new_cs->status != ClientStatus::MapWait) continue;
532 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++;
533 }
534
535 auto p = std::make_unique<Packet>(this, PacketGameType::ServerWaitForMap);
536 p->Send_uint8(waiting);
537 this->SendPacket(std::move(p));
539}
540
546{
547 Debug(Facility::Net, Severity::Trace3, "client[{}] CheckNextClientToSendMap()", this->client_id);
548
549 /* Find the best candidate for joining, i.e. the first joiner. */
550 NetworkClientSocket *best = nullptr;
552 if (ignore_cs == new_cs) continue;
553
554 if (new_cs->status == ClientStatus::MapWait) {
555 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)) {
556 best = new_cs;
557 }
558 }
559 }
560
561 /* Is there someone else to join? */
562 if (best != nullptr) {
563 /* Let the first start joining. */
565 best->SendMap();
566
567 /* And update the rest. */
569 if (new_cs->status == ClientStatus::MapWait) new_cs->SendWait();
570 }
571 }
572}
573
579{
580 if (this->status < ClientStatus::Authorized) {
581 /* Illegal call, return error and ignore the packet */
583 }
584
585 if (this->status == ClientStatus::Authorized) {
586 Debug(Facility::Net, Severity::Trace3, "client[{}] SendMap(): first_packet", this->client_id);
587
588 WaitTillSaved();
589 this->savegame = std::make_shared<PacketWriter>(this);
590
591 /* Now send the _frame_counter and how many packets are coming */
592 auto p = std::make_unique<Packet>(this, PacketGameType::ServerMapBegin);
593 p->Send_uint32(_frame_counter);
594 this->SendPacket(std::move(p));
595
597 Debug(Facility::Net, Severity::Trace3, "client[{}] status = MAP", this->client_id);
599 /* Mark the start of download */
602
603 /* Make a dump of the current game */
604 if (SaveWithFilter(this->savegame, true) != SaveLoadResult::Ok) UserError("network savedump failed");
605 }
606
607 if (this->status == ClientStatus::Map) {
608 bool last_packet = this->savegame->TransferToNetworkQueue();
609 if (last_packet) {
610 Debug(Facility::Net, Severity::Trace3, "client[{}] SendMap(): last_packet", this->client_id);
611
612 /* Done reading, make sure saving is done as well */
613 this->savegame->Destroy();
614 this->savegame = nullptr;
615
616 /* Set the status to DONE_MAP, no we will wait for the client
617 * to send it is ready (maybe that happens like never ;)) */
618 Debug(Facility::Net, Severity::Trace3, "client[{}] status = DONE_MAP", this->client_id);
620
622 }
623 }
625}
626
633{
634 Debug(Facility::Net, Severity::Trace3, "client[{}] SendJoin(): client_id={}", this->client_id, client_id);
635
636 auto p = std::make_unique<Packet>(this, PacketGameType::ServerClientJoined);
637
638 p->Send_uint32(to_underlying(client_id));
639
640 this->SendPacket(std::move(p));
642}
643
649{
650 auto p = std::make_unique<Packet>(this, PacketGameType::ServerFrame);
651 p->Send_uint32(_frame_counter);
652 p->Send_uint32(_frame_counter_max);
653#ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
654 p->Send_uint32(_sync_seed_1);
655#ifdef NETWORK_SEND_DOUBLE_SEED
656 p->Send_uint32(_sync_seed_2);
657#endif
658#endif
659
660 /* If token equals 0, we need to make a new token and send that. */
661 if (this->last_token == 0) {
662 this->last_token = InteractiveRandomRange(UINT8_MAX - 1) + 1;
663 p->Send_uint8(this->last_token);
664 }
665
666 this->SendPacket(std::move(p));
668}
669
675{
676 Debug(Facility::Net, Severity::Trace3, "client[{}] SendSync(), frame_counter={}, sync_seed_1={}", this->client_id, _frame_counter, _sync_seed_1);
677
678 auto p = std::make_unique<Packet>(this, PacketGameType::ServerSync);
679 p->Send_uint32(_frame_counter);
680 p->Send_uint32(_sync_seed_1);
681
682#ifdef NETWORK_SEND_DOUBLE_SEED
683 p->Send_uint32(_sync_seed_2);
684#endif
685 this->SendPacket(std::move(p));
687}
688
695{
696 Debug(Facility::Net, Severity::Trace3, "client[{}] SendCommand(): cmd={}", this->client_id, cp.cmd);
697
698 auto p = std::make_unique<Packet>(this, PacketGameType::ServerCommand);
699
701 p->Send_uint32(cp.frame);
702 p->Send_bool (cp.my_cmd);
703
704 this->SendPacket(std::move(p));
706}
707
717NetworkRecvStatus ServerNetworkGameSocketHandler::SendChat(NetworkAction action, ClientID client_id, bool self_send, std::string_view msg, int64_t data)
718{
719 Debug(Facility::Net, Severity::Trace3, "client[{}] SendChat(): action={}, client_id={}, self_send={}", this->client_id, action, client_id, self_send);
720
722
723 auto p = std::make_unique<Packet>(this, PacketGameType::ServerChat);
724
725 p->Send_uint8(to_underlying(action));
726 p->Send_uint32(to_underlying(client_id));
727 p->Send_bool (self_send);
728 p->Send_string(msg);
729 p->Send_uint64(data);
730
731 this->SendPacket(std::move(p));
733}
734
743NetworkRecvStatus ServerNetworkGameSocketHandler::SendExternalChat(std::string_view source, ExtendedTextColour colour, std::string_view user, std::string_view msg)
744{
745 Debug(Facility::Net, Severity::Trace3, "client[{}] SendExternalChat(): source={}", this->client_id, source);
746
748
749 auto p = std::make_unique<Packet>(this, PacketGameType::ServerExternalChat);
750
751 p->Send_string(source);
752 p->Send_uint16(colour.ToNetwork());
753 p->Send_string(user);
754 p->Send_string(msg);
755
756 this->SendPacket(std::move(p));
758}
759
767{
768 Debug(Facility::Net, Severity::Trace3, "client[{}] SendErrorQuit(): client_id={}, errorno={}", this->client_id, client_id, errorno);
769
770 auto p = std::make_unique<Packet>(this, PacketGameType::ServerErrorQuit);
771
772 p->Send_uint32(to_underlying(client_id));
773 p->Send_uint8(to_underlying(errorno));
774
775 this->SendPacket(std::move(p));
777}
778
785{
786 Debug(Facility::Net, Severity::Trace3, "client[{}] SendQuit(): client_id={}", this->client_id, client_id);
787
788 auto p = std::make_unique<Packet>(this, PacketGameType::ServerQuit);
789
790 p->Send_uint32(to_underlying(client_id));
791
792 this->SendPacket(std::move(p));
794}
795
801{
802 Debug(Facility::Net, Severity::Trace3, "client[{}] SendShutdown()", this->client_id);
803
804 auto p = std::make_unique<Packet>(this, PacketGameType::ServerShutdown);
805 this->SendPacket(std::move(p));
807}
808
814{
815 Debug(Facility::Net, Severity::Trace3, "client[{}] SendNewGame()", this->client_id);
816
817 auto p = std::make_unique<Packet>(this, PacketGameType::ServerNewGame);
818 this->SendPacket(std::move(p));
820}
821
829{
830 Debug(Facility::Net, Severity::Trace3, "client[{}] SendRConResult()", this->client_id);
831
832 auto p = std::make_unique<Packet>(this, PacketGameType::ServerRemoteConsoleCommand);
833
834 p->Send_uint16(colour);
835 p->Send_string(command);
836 this->SendPacket(std::move(p));
838}
839
847{
848 Debug(Facility::Net, Severity::Trace3, "client[{}] SendMove(): client_id={}", this->client_id, client_id);
849
850 auto p = std::make_unique<Packet>(this, PacketGameType::ServerMove);
851
852 p->Send_uint32(to_underlying(client_id));
853 p->Send_uint8(company_id);
854 this->SendPacket(std::move(p));
856}
857
863{
864 Debug(Facility::Net, Severity::Trace3, "client[{}] SendConfigUpdate()", this->client_id);
865
866 auto p = std::make_unique<Packet>(this, PacketGameType::ServerConfigurationUpdate);
867
868 p->Send_uint8(_settings_client.network.max_companies);
869 p->Send_string(_settings_client.network.server_name);
870 this->SendPacket(std::move(p));
872}
873
874/***********
875 * Receiving functions
876 ************/
877
879{
880 Debug(Facility::Net, Severity::Trace3, "client[{}] ReceiveClientGameInfo()", this->client_id);
881
882 return this->SendGameInfo();
883}
884
886{
887 if (this->status != ClientStatus::NewGRFsCheck) {
888 /* Illegal call, return error and ignore the packet */
890 }
891
892 Debug(Facility::Net, Severity::Trace3, "client[{}] ReceiveClientNewGRFsChecked()", this->client_id);
893
894 return this->SendWelcome();
895}
896
898{
899 if (this->status != ClientStatus::Inactive) {
900 /* Illegal call, return error and ignore the packet */
902 }
903
904 if (_network_game_info.clients_on >= _settings_client.network.max_clients) {
905 /* Turns out we are full. Inform the user about this. */
907 }
908
909 std::string client_revision = p.Recv_string(NETWORK_REVISION_LENGTH);
910 uint32_t newgrf_version = p.Recv_uint32();
911
912 Debug(Facility::Net, Severity::Trace3, "client[{}] ReceiveClientJoin(): client_revision={}, newgrf_version={}", this->client_id, client_revision, newgrf_version);
913
914 /* Check if the client has revision control enabled */
915 if (!IsNetworkCompatibleVersion(client_revision) || _openttd_newgrf_version != newgrf_version) {
916 /* Different revisions!! */
918 }
919
920 return this->SendAuthRequest();
921}
922
924{
926
927 Debug(Facility::Net, Severity::Trace3, "client[{}] ReceiveClientIdentify()", this->client_id);
928
929 std::string client_name = p.Recv_string(NETWORK_CLIENT_NAME_LENGTH);
930 CompanyID playas = (Owner)p.Recv_uint8();
931
933
934 /* join another company does not affect these values */
935 switch (playas.base()) {
936 case COMPANY_NEW_COMPANY.base(): // New company
937 if (Company::GetNumItems() >= _settings_client.network.max_companies) {
939 }
940 break;
941 case COMPANY_SPECTATOR.base(): // Spectator
942 break;
943 default: // Join another company (companies 1..MAX_COMPANIES (index 0..(MAX_COMPANIES-1)))
944 if (!Company::IsValidHumanID(playas)) {
946 }
947
948 const Company *c = Company::Get(playas);
949 if (!c->allow_any && !c->allow_list.Contains(this->peer_public_key)) {
950 /* When we're not authorized, just bump us to a spectator. */
951 playas = COMPANY_SPECTATOR;
952 }
953 break;
954 }
955
956 if (!NetworkIsValidClientName(client_name)) {
957 /* An invalid client name was given. However, the client ensures the name
958 * is valid before it is sent over the network, so something went horribly
959 * wrong. This is probably someone trying to troll us. */
961 }
962
963 if (!NetworkMakeClientNameUnique(client_name)) { // Change name if duplicate
964 /* We could not create a name for this client */
966 }
967
970 this->SetInfo(ci);
972 ci->client_name = std::move(client_name);
973 ci->client_playas = playas;
974 ci->public_key = this->peer_public_key;
975 Debug(Facility::Desync, Severity::Error, "client: {:08x}; {:02x}; {:02x}; {:02x}", TimerGameEconomy::date, TimerGameEconomy::date_fract, ci->client_playas, ci->index);
976
977 /* Make sure companies to which people try to join are not autocleaned */
978 Company *c = Company::GetIfValid(playas);
979 if (c != nullptr) c->months_empty = 0;
980
981 return this->SendNewGRFCheck();
982}
983
1001
1003{
1004 if (this->status != ClientStatus::AuthGame) {
1006 }
1007
1008 Debug(Facility::Net, Severity::Trace3, "client[{}] ReceiveClientAuthenticationResponse()", this->client_id);
1009
1010 auto authentication_method = this->authentication_handler->GetAuthenticationMethod();
1011 switch (this->authentication_handler->ReceiveResponse(p)) {
1013 break;
1014
1016 return this->SendAuthRequest();
1017
1019 default:
1020 return this->SendError(GetErrorForAuthenticationMethod(authentication_method));
1021 }
1022
1024 if (status != NetworkRecvStatus::Okay) return status;
1025
1026 this->peer_public_key = this->authentication_handler->GetPeerPublicKey();
1027 this->receive_encryption_handler = this->authentication_handler->CreateClientToServerEncryptionHandler();
1028 this->send_encryption_handler = this->authentication_handler->CreateServerToClientEncryptionHandler();
1029 this->authentication_handler = nullptr;
1030
1031 Debug(Facility::Net, Severity::Trace3, "client[{}] status = IDENTIFY", this->client_id);
1032 this->status = ClientStatus::Identify;
1033
1034 /* Reset 'lag' counters */
1036
1038}
1039
1041{
1042 /* The client was never joined.. so this is impossible, right?
1043 * Ignore the packet, give the client a warning, and close the connection */
1046 }
1047
1048 Debug(Facility::Net, Severity::Trace3, "client[{}] ReceiveClientGetMap()", this->client_id);
1049
1050 /* Check if someone else is receiving the map */
1052 if (new_cs->status == ClientStatus::Map) {
1053 /* Tell the new client to wait */
1054 Debug(Facility::Net, Severity::Trace3, "client[{}] status = MAP_WAIT", this->client_id);
1056 return this->SendWait();
1057 }
1058 }
1059
1060 /* We receive a request to upload the map.. give it to the client! */
1061 return this->SendMap();
1062}
1063
1065{
1066 /* Client has the map, now start syncing */
1067 if (this->status == ClientStatus::DoneMap && !this->HasClientQuit()) {
1068 Debug(Facility::Net, Severity::Trace3, "client[{}] ReceiveClientMapOk()", this->client_id);
1069
1070 std::string client_name = this->GetClientName();
1071
1072 NetworkTextMessage(NetworkAction::ClientJoin, CC_DEFAULT, false, client_name, "", this->client_id);
1073 InvalidateWindowData(WindowClass::NetworkClientList, 0);
1074
1075 Debug(Facility::Net, Severity::Notice, "[{}] Client #{} ({}) joined as {}", ServerNetworkGameSocketHandler::GetName(), this->client_id, this->GetClientIP(), client_name);
1076
1077 /* Mark the client as pre-active, and wait for an ACK
1078 * so we know it is done loading and in sync with us */
1079 Debug(Facility::Net, Severity::Trace3, "client[{}] status = PRE_ACTIVE", this->client_id);
1082 this->SendFrame();
1083 this->SendSync();
1084
1085 /* This is the frame the client receives
1086 * we need it later on to make sure the client is not too slow */
1087 this->last_frame = _frame_counter;
1089
1091 if (new_cs->status >= ClientStatus::Authorized) {
1092 new_cs->SendClientInfo(this->GetInfo());
1093 new_cs->SendJoin(this->client_id);
1094 }
1095 }
1096
1097 NetworkAdminClientInfo(this, true);
1098
1099 /* also update the new client with our max values */
1100 return this->SendConfigUpdate();
1101 }
1102
1103 /* Wrong status for this packet, give a warning to client, and close connection */
1105}
1106
1108{
1109 /* The client was never joined.. so this is impossible, right?
1110 * Ignore the packet, give the client a warning, and close the connection */
1113 }
1114
1115 if (this->incoming_queue.size() >= _settings_client.network.max_commands_in_queue) {
1117 }
1118
1119 Debug(Facility::Net, Severity::Trace3, "client[{}] ReceiveClientCommand()", this->client_id);
1120
1121 CommandPacket cp;
1122 auto err = this->ReceiveCommand(p, cp);
1123
1124 if (this->HasClientQuit()) return NetworkRecvStatus::ClientQuit;
1125
1126 NetworkClientInfo *ci = this->GetInfo();
1127
1128 if (err.has_value()) {
1129 IConsolePrint(CC_WARNING, "Dropping client #{} (IP: {}) due to {}.", ci->client_id, this->GetClientIP(), *err);
1131 }
1132
1134 IConsolePrint(CC_WARNING, "Kicking client #{} (IP: {}) due to calling a server only command {}.", ci->client_id, this->GetClientIP(), cp.cmd);
1135 return this->SendError(NetworkErrorCode::Kicked);
1136 }
1137
1139 IConsolePrint(CC_WARNING, "Kicking client #{} (IP: {}) due to calling a non-spectator command {}.", ci->client_id, this->GetClientIP(), cp.cmd);
1140 return this->SendError(NetworkErrorCode::Kicked);
1141 }
1142
1150 IConsolePrint(CC_WARNING, "Kicking client #{} (IP: {}) due to calling a command as another company {}.",
1151 ci->client_playas + 1, this->GetClientIP(), cp.company + 1);
1153 }
1154
1155 if (cp.cmd == Commands::CompanyControl) {
1156 if (cca != CompanyCtrlAction::New || cp.company != COMPANY_SPECTATOR) {
1158 }
1159
1160 /* Check if we are full - else it's possible for spectators to send a Commands::CompanyControl and the company is created regardless of max_companies! */
1161 if (Company::GetNumItems() >= _settings_client.network.max_companies) {
1164 }
1165 }
1166
1168 /* Maybe the client just got moved before allowing? */
1170
1171 /* Only allow clients to add/remove currently joined clients. The server owner does not go via this method, so is allowed to do more. */
1172 std::string public_key = std::get<1>(EndianBufferReader::ToValue<CommandTraits<Commands::CompanyAllowListControl>::Args>(cp.data));
1173 if (!public_key.empty()) {
1174 bool found = false;
1176 if (info->public_key == public_key) {
1177 found = true;
1178 break;
1179 }
1180 }
1181
1182 /* Maybe the client just left? */
1183 if (!found) return NetworkRecvStatus::Okay;
1184 }
1185 }
1186
1187 if (GetCommandFlags(cp.cmd).Test(CommandFlag::ClientID)) NetworkReplaceCommandClientId(cp, this->client_id);
1188
1189 this->incoming_queue.push_back(std::move(cp));
1191}
1192
1194{
1195 /* This packets means a client noticed an error and is reporting this
1196 * to us. Display the error and report it to the other clients */
1197 NetworkErrorCode errorno = static_cast<NetworkErrorCode>(p.Recv_uint8());
1198
1199 Debug(Facility::Net, Severity::Trace3, "client[{}] ReceiveClientError(): errorno={}", this->client_id, errorno);
1200
1201 /* The client was never joined.. thank the client for the packet, but ignore it */
1204 }
1205
1206 std::string client_name = this->GetClientName();
1207 StringID strid = GetNetworkErrorMsg(errorno);
1208
1209 Debug(Facility::Net, Severity::Error, "'{}' reported an error and is closing its connection: {}", client_name, GetString(strid));
1210
1211 NetworkTextMessage(NetworkAction::ClientLeave, CC_DEFAULT, false, client_name, "", strid);
1212
1214 if (new_cs->status >= ClientStatus::Authorized) {
1215 new_cs->SendErrorQuit(this->client_id, errorno);
1216 }
1217 }
1218
1219 NetworkAdminClientError(this->client_id, errorno);
1220
1222}
1223
1225{
1226 /* The client was never joined.. thank the client for the packet, but ignore it */
1229 }
1230
1231 Debug(Facility::Net, Severity::Trace3, "client[{}] ReceiveClientQuit()", this->client_id);
1232
1233 /* The client wants to leave. Display this and report it to the other clients. */
1234 std::string client_name = this->GetClientName();
1235 NetworkTextMessage(NetworkAction::ClientLeave, CC_DEFAULT, false, client_name, "", STR_NETWORK_MESSAGE_CLIENT_LEAVING);
1236
1238 if (new_cs->status >= ClientStatus::Authorized && new_cs != this) {
1239 new_cs->SendQuit(this->client_id);
1240 }
1241 }
1242
1244
1246}
1247
1249{
1250 if (this->status < ClientStatus::Authorized) {
1251 /* Illegal call, return error and ignore the packet */
1253 }
1254
1255 uint32_t frame = p.Recv_uint32();
1256
1257 Debug(Facility::Net, Severity::Trace3, "client[{}] ReceiveClientAck(): frame={}", this->client_id, frame);
1258
1259 /* The client is trying to catch up with the server */
1260 if (this->status == ClientStatus::PreActive) {
1261 /* The client is not yet caught up? */
1263
1264 /* Now it is! Unpause the game */
1265 Debug(Facility::Net, Severity::Trace3, "client[{}] status = ACTIVE", this->client_id);
1268
1269 /* Execute script for, e.g. MOTD */
1270 IConsoleCmdExec("exec scripts/on_server_connect.scr 0");
1271 }
1272
1273 /* Get, and validate the token. */
1274 uint8_t token = p.Recv_uint8();
1275 if (token == this->last_token) {
1276 /* We differentiate between last_token_frame and last_frame so the lag
1277 * test uses the actual lag of the client instead of the lag for getting
1278 * the token back and forth; after all, the token is only sent every
1279 * time we receive a PacketGameType::ClientAck, after which we will send a new
1280 * token to the client. If the lag would be one day, then we would not
1281 * be sending the new token soon enough for the new daily scheduled
1282 * PacketGameType::ClientAck. This would then register the lag of the client as
1283 * two days, even when it's only a single day. */
1285 /* Request a new token. */
1286 this->last_token = 0;
1287 }
1288
1289 /* The client received the frame, make note of it */
1290 this->last_frame = frame;
1291 /* With those 2 values we can calculate the lag realtime */
1294}
1295
1296
1307void NetworkServerSendChat(NetworkAction action, NetworkChatDestinationType desttype, int dest, std::string_view msg, ClientID from_id, int64_t data, bool from_admin)
1308{
1309 const NetworkClientInfo *ci, *ci_own, *ci_to;
1310
1311 switch (desttype) {
1313 /* Are we sending to the server? */
1314 if ((ClientID)dest == ClientID::Server) {
1316 /* Display the text locally, and that is it */
1317 if (ci != nullptr) {
1318 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
1319
1320 if (_settings_client.network.server_admin_chat) {
1321 NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
1322 }
1323 }
1324 } else {
1325 /* Else find the client to send the message to */
1326 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1327 if (cs->client_id == (ClientID)dest && cs->status >= ServerNetworkGameSocketHandler::ClientStatus::Authorized) {
1328 cs->SendChat(action, from_id, false, msg, data);
1329 break;
1330 }
1331 }
1332 }
1333
1334 /* Display the message locally (so you know you have sent it) */
1335 if (from_id != (ClientID)dest) {
1336 if (from_id == ClientID::Server) {
1339 if (ci != nullptr && ci_to != nullptr) {
1340 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), true, ci_to->client_name, msg, data);
1341 }
1342 } else {
1343 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1344 if (cs->client_id == from_id && cs->status >= ServerNetworkGameSocketHandler::ClientStatus::Authorized) {
1345 cs->SendChat(action, (ClientID)dest, true, msg, data);
1346 break;
1347 }
1348 }
1349 }
1350 }
1351 break;
1353 /* If this is false, the message is already displayed on the client who sent it. */
1354 bool show_local = true;
1355 /* Find all clients that belong to this company */
1356 ci_to = nullptr;
1357 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1358 ci = cs->GetInfo();
1359 if (ci != nullptr && ci->client_playas == (CompanyID)dest && cs->status >= ServerNetworkGameSocketHandler::ClientStatus::Authorized) {
1360 cs->SendChat(action, from_id, false, msg, data);
1361 if (cs->client_id == from_id) show_local = false;
1362 ci_to = ci; // Remember a client that is in the company for company-name
1363 }
1364 }
1365
1366 /* if the server can read it, let the admin network read it, too. */
1367 if (_local_company == (CompanyID)dest && _settings_client.network.server_admin_chat) {
1368 NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
1369 }
1370
1373 if (ci != nullptr && ci_own != nullptr && ci_own->client_playas == dest) {
1374 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
1375 if (from_id == ClientID::Server) show_local = false;
1376 ci_to = ci_own;
1377 }
1378
1379 /* There is no such client */
1380 if (ci_to == nullptr) break;
1381
1382 /* Display the message locally (so you know you have sent it) */
1383 if (ci != nullptr && show_local) {
1384 if (from_id == ClientID::Server) {
1385 StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
1386 std::string name = GetString(str, ci_to->client_playas);
1387 NetworkTextMessage(action, GetDrawStringCompanyColour(ci_own->client_playas), true, name, msg, data);
1388 } else {
1389 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1390 if (cs->client_id == from_id && cs->status >= ServerNetworkGameSocketHandler::ClientStatus::Authorized) {
1391 cs->SendChat(action, ci_to->client_id, true, msg, data);
1392 }
1393 }
1394 }
1395 }
1396 break;
1397 }
1398 default:
1399 Debug(Facility::Net, Severity::Error, "Received unknown chat destination type {}; doing broadcast instead", desttype);
1400 [[fallthrough]];
1401
1403 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1404 if (cs->status >= ServerNetworkGameSocketHandler::ClientStatus::Authorized) cs->SendChat(action, from_id, false, msg, data);
1405 }
1406
1407 NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
1408
1410 if (ci != nullptr) {
1411 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
1412 }
1413 break;
1414 }
1415}
1416
1424void NetworkServerSendExternalChat(std::string_view source, ExtendedTextColour colour, std::string_view user, std::string_view msg)
1425{
1426 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1427 if (cs->status >= ServerNetworkGameSocketHandler::ClientStatus::Authorized) cs->SendExternalChat(source, colour, user, msg);
1428 }
1429 NetworkTextMessage(NetworkAction::ChatExternal, colour, false, user, msg, source);
1430}
1431
1433{
1434 if (this->status < ClientStatus::PreActive) {
1435 /* Illegal call, return error and ignore the packet */
1437 }
1438
1439 NetworkAction action = static_cast<NetworkAction>(p.Recv_uint8());
1441 int dest = p.Recv_uint32();
1442
1443 Debug(Facility::Net, Severity::Trace3, "client[{}] ReceiveClientChat(): action={}, desttype={}, dest={}", this->client_id, action, desttype, dest);
1444
1445 std::string msg = p.Recv_string(NETWORK_CHAT_LENGTH);
1446 int64_t data = p.Recv_uint64();
1447
1448 NetworkClientInfo *ci = this->GetInfo();
1449 switch (action) {
1453 NetworkServerSendChat(action, desttype, dest, msg, this->client_id, data);
1454 break;
1455 default:
1456 IConsolePrint(CC_WARNING, "Kicking client #{} (IP: {}) due to unknown chact action.", ci->client_id, this->GetClientIP());
1458 }
1460}
1461
1463{
1464 if (this->status != ClientStatus::Active) {
1465 /* Illegal call, return error and ignore the packet */
1467 }
1468
1469 Debug(Facility::Net, Severity::Trace3, "client[{}] ReceiveClientSetName()", this->client_id);
1470
1472
1473 std::string client_name = p.Recv_string(NETWORK_CLIENT_NAME_LENGTH);
1474 ci = this->GetInfo();
1475
1476 if (this->HasClientQuit()) return NetworkRecvStatus::ClientQuit;
1477
1478 if (ci != nullptr) {
1479 if (!NetworkIsValidClientName(client_name)) {
1480 /* An invalid client name was given. However, the client ensures the name
1481 * is valid before it is sent over the network, so something went horribly
1482 * wrong. This is probably someone trying to troll us. */
1484 }
1485
1486 /* Display change */
1487 if (NetworkMakeClientNameUnique(client_name)) {
1489 ci->client_name = std::move(client_name);
1491 InvalidateWindowData(WindowClass::NetworkClientList, 0);
1492 }
1493 }
1495}
1496
1498{
1500
1501 Debug(Facility::Net, Severity::Trace3, "client[{}] ReceiveClientRemoteConsoleCommand()", this->client_id);
1502
1503 std::string password = p.Recv_string(NETWORK_PASSWORD_LENGTH);
1504 std::string command = p.Recv_string(NETWORK_RCONCOMMAND_LENGTH);
1505
1506 if (_rcon_authorized_key_handler.IsAllowed(this->peer_public_key)) {
1507 /* We are allowed, nothing more to validate. */
1508 } else if (_settings_client.network.rcon_password.empty()) {
1510 } else if (_settings_client.network.rcon_password != password) {
1511 Debug(Facility::Net, Severity::Error, "[rcon] Wrong password from client-id {}", this->client_id);
1513 }
1514
1515 Debug(Facility::Net, Severity::Notice, "[rcon] Client-id {} executed: {}", this->client_id, command);
1516
1518 IConsoleCmdExec(command);
1521}
1522
1524{
1526
1527 CompanyID company_id = (Owner)p.Recv_uint8();
1528
1529 Debug(Facility::Net, Severity::Trace3, "client[{}] ReceiveClientMove(): company_id={}", this->client_id, company_id);
1530
1531 /* Check if the company is valid, we don't allow moving to AI companies */
1532 if (company_id != COMPANY_SPECTATOR) {
1533 if (!Company::IsValidHumanID(company_id)) return NetworkRecvStatus::Okay;
1534
1535 const Company *c = Company::Get(company_id);
1536 if (!c->allow_any && !c->allow_list.Contains(this->peer_public_key)) {
1537 Debug(Facility::Net, Severity::Warning, "Wrong public key from client-id #{} for company #{}", this->client_id, company_id + 1);
1539 }
1540 }
1541
1542 /* if we get here we can move the client */
1543 NetworkServerDoMove(this->client_id, company_id);
1545}
1546
1552{
1553 NetworkCompanyStatsArray stats = {};
1554
1555 /* Go through all vehicles and count the type of vehicles */
1556 for (const Vehicle *v : Vehicle::Iterate()) {
1557 if (!Company::IsValidID(v->owner) || !v->IsPrimaryVehicle()) continue;
1558 NetworkVehicleType type;
1559 switch (v->type) {
1563 case VehicleType::Ship: type = NetworkVehicleType::Ship; break;
1564 default: continue;
1565 }
1566 stats[v->owner].num_vehicle[type]++;
1567 }
1568
1569 /* Go through all stations and count the types of stations */
1570 for (const Station *s : Station::Iterate()) {
1571 if (Company::IsValidID(s->owner)) {
1572 NetworkCompanyStats *npi = &stats[s->owner];
1573
1574 if (s->facilities.Test(StationFacility::Train)) npi->num_station[NetworkVehicleType::Train]++;
1575 if (s->facilities.Test(StationFacility::TruckStop)) npi->num_station[NetworkVehicleType::Truck]++;
1576 if (s->facilities.Test(StationFacility::BusStop)) npi->num_station[NetworkVehicleType::Bus]++;
1577 if (s->facilities.Test(StationFacility::Airport)) npi->num_station[NetworkVehicleType::Aircraft]++;
1578 if (s->facilities.Test(StationFacility::Dock)) npi->num_station[NetworkVehicleType::Ship]++;
1579 }
1580 }
1581
1582 return stats;
1583}
1584
1590{
1592
1593 if (ci == nullptr) return;
1594
1595 Debug(Facility::Desync, Severity::Error, "client: {:08x}; {:02x}; {:02x}; {:04x}", TimerGameEconomy::date, TimerGameEconomy::date_fract, ci->client_playas, client_id);
1596
1597 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1599 cs->SendClientInfo(ci);
1600 }
1601 }
1602
1604}
1605
1612{
1613 CompanyMask has_clients{};
1614 CompanyMask has_vehicles{};
1615
1616 if (!_settings_client.network.autoclean_companies) return;
1617
1618 /* Detect the active companies */
1619 for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1620 if (Company::IsValidID(ci->client_playas)) has_clients.Set(ci->client_playas);
1621 }
1622
1623 if (!_network_dedicated) {
1625 assert(ci != nullptr);
1626 if (Company::IsValidID(ci->client_playas)) has_clients.Set(ci->client_playas);
1627 }
1628
1629 if (_settings_client.network.autoclean_novehicles != 0) {
1630 for (const Company *c : Company::Iterate()) {
1631 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);
1632 }
1633 }
1634
1635 /* Go through all the companies */
1636 for (Company *c : Company::Iterate()) {
1637 /* Skip the non-active once */
1638 if (c->is_ai) continue;
1639
1640 if (!has_clients.Test(c->index)) {
1641 /* The company is empty for one month more */
1642 if (c->months_empty != std::numeric_limits<decltype(c->months_empty)>::max()) c->months_empty++;
1643
1644 /* Is the company empty for autoclean_protected-months? */
1645 if (_settings_client.network.autoclean_protected != 0 && c->months_empty > _settings_client.network.autoclean_protected) {
1646 /* Shut the company down */
1647 Command<Commands::CompanyControl>::Post(CompanyCtrlAction::Delete, c->index, CompanyRemoveReason::Autoclean, ClientID::Invalid);
1648 IConsolePrint(CC_INFO, "Auto-cleaned company #{}.", c->index + 1);
1649 }
1650 /* Is the company empty for autoclean_novehicles-months, and has no vehicles? */
1651 if (_settings_client.network.autoclean_novehicles != 0 && c->months_empty > _settings_client.network.autoclean_novehicles && !has_vehicles.Test(c->index)) {
1652 /* Shut the company down */
1653 Command<Commands::CompanyControl>::Post(CompanyCtrlAction::Delete, c->index, CompanyRemoveReason::Autoclean, ClientID::Invalid);
1654 IConsolePrint(CC_INFO, "Auto-cleaned company #{} with no vehicles.", c->index + 1);
1655 }
1656 } else {
1657 /* It is not empty, reset the date */
1658 c->months_empty = 0;
1659 }
1660 }
1661}
1662
1668bool NetworkMakeClientNameUnique(std::string &name)
1669{
1670 bool is_name_unique = false;
1671 std::string original_name = name;
1672
1673 for (uint number = 1; !is_name_unique && number <= MAX_CLIENTS; number++) { // Something's really wrong when there're more names than clients
1674 is_name_unique = true;
1675 for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1676 if (ci->client_name == name) {
1677 /* Name already in use */
1678 is_name_unique = false;
1679 break;
1680 }
1681 }
1682 /* Check if it is the same as the server-name */
1684 if (ci != nullptr) {
1685 if (ci->client_name == name) is_name_unique = false; // name already in use
1686 }
1687
1688 if (!is_name_unique) {
1689 /* Try a new name (<name> #1, <name> #2, and so on) */
1690 name = fmt::format("{} #{}", original_name, number);
1691
1692 /* The constructed client name is larger than the limit,
1693 * so... bail out as no valid name can be created. */
1694 if (name.size() >= NETWORK_CLIENT_NAME_LENGTH) return false;
1695 }
1696 }
1697
1698 return is_name_unique;
1699}
1700
1707bool NetworkServerChangeClientName(ClientID client_id, const std::string &new_name)
1708{
1709 /* Check if the name's already in use */
1711 if (ci->client_name == new_name) return false;
1712 }
1713
1715 if (ci == nullptr) return false;
1716
1718
1719 ci->client_name = new_name;
1720
1721 NetworkUpdateClientInfo(client_id);
1722 return true;
1723}
1724
1730{
1731 for (auto &cp : cs->outgoing_queue) cs->SendCommand(cp);
1732 cs->outgoing_queue.clear();
1733}
1734
1739void NetworkServer_Tick(bool send_frame)
1740{
1741#ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1742 bool send_sync = false;
1743#endif
1744
1745#ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1746 if (_frame_counter >= _last_sync_frame + _settings_client.network.sync_freq) {
1748 send_sync = true;
1749 }
1750#endif
1751
1752 /* Now we are done with the frame, inform the clients that they can
1753 * do their frame! */
1754 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1755 /* We allow a number of bytes per frame, but only to the burst amount
1756 * to be available for packet receiving at any particular time. */
1757 cs->receive_limit = std::min<size_t>(cs->receive_limit + _settings_client.network.bytes_per_frame,
1758 _settings_client.network.bytes_per_frame_burst);
1759
1760 /* Check if the speed of the client is what we can expect from a client */
1761 uint lag = NetworkCalculateLag(cs);
1762 switch (cs->status) {
1763 case NetworkClientSocket::ClientStatus::Active:
1764 if (lag > _settings_client.network.max_lag_time) {
1765 /* Client did still not report in within the specified limit. */
1766
1767 if (cs->last_packet + std::chrono::milliseconds(lag * MILLISECONDS_PER_TICK) > std::chrono::steady_clock::now()) {
1768 /* A packet was received in the last three game days, so the client is likely lagging behind. */
1769 IConsolePrint(CC_WARNING, "Client #{} (IP: {}) is dropped because the client's game state is more than {} ticks behind.", cs->client_id, cs->GetClientIP(), lag);
1770 } else {
1771 /* No packet was received in the last three game days; sounds like a lost connection. */
1772 IConsolePrint(CC_WARNING, "Client #{} (IP: {}) is dropped because the client did not respond for more than {} ticks.", cs->client_id, cs->GetClientIP(), lag);
1773 }
1774 cs->SendError(NetworkErrorCode::TimeoutComputer);
1775 continue;
1776 }
1777
1778 /* Report once per time we detect the lag, and only when we
1779 * received a packet in the last 2 seconds. If we
1780 * did not receive a packet, then the client is not just
1781 * slow, but the connection is likely severed. Mentioning
1782 * frame_freq is not useful in this case. */
1783 if (lag > (uint)Ticks::DAY_TICKS && cs->lag_test == 0 && cs->last_packet + std::chrono::seconds(2) > std::chrono::steady_clock::now()) {
1784 IConsolePrint(CC_WARNING, "[{}] Client #{} is slow, try increasing [network.]frame_freq to a higher value!", _frame_counter, cs->client_id);
1785 cs->lag_test = 1;
1786 }
1787
1788 if (cs->last_frame_server - cs->last_token_frame >= _settings_client.network.max_lag_time) {
1789 /* This is a bad client! It didn't send the right token back within time. */
1790 IConsolePrint(CC_WARNING, "Client #{} (IP: {}) is dropped because it fails to send valid acks.", cs->client_id, cs->GetClientIP());
1791 cs->SendError(NetworkErrorCode::TimeoutComputer);
1792 continue;
1793 }
1794 break;
1795
1796 case NetworkClientSocket::ClientStatus::Inactive:
1797 case NetworkClientSocket::ClientStatus::Identify:
1798 case NetworkClientSocket::ClientStatus::NewGRFsCheck:
1799 case NetworkClientSocket::ClientStatus::Authorized:
1800 /* NewGRF check and authorized states should be handled almost instantly.
1801 * So give them some lee-way, likewise for the query with inactive. */
1802 if (lag > _settings_client.network.max_init_time) {
1803 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);
1804 cs->SendError(NetworkErrorCode::TimeoutComputer);
1805 continue;
1806 }
1807 break;
1808
1809 case NetworkClientSocket::ClientStatus::MapWait:
1810 /* Send every two seconds a packet to the client, to make sure
1811 * it knows the server is still there; just someone else is
1812 * still receiving the map. */
1813 if (std::chrono::steady_clock::now() > cs->last_packet + std::chrono::seconds(2)) {
1814 cs->SendWait();
1815 /* We need to reset the timer, as otherwise we will be
1816 * spamming the client. Strictly speaking this variable
1817 * tracks when we last received a packet from the client,
1818 * but as it is waiting, it will not send us any till we
1819 * start sending them data. */
1820 cs->last_packet = std::chrono::steady_clock::now();
1821 }
1822 break;
1823
1824 case NetworkClientSocket::ClientStatus::Map:
1825 /* Downloading the map... this is the amount of time since starting the saving. */
1826 if (lag > _settings_client.network.max_download_time) {
1827 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);
1828 cs->SendError(NetworkErrorCode::TimeoutMap);
1829 continue;
1830 }
1831 break;
1832
1833 case NetworkClientSocket::ClientStatus::DoneMap:
1834 case NetworkClientSocket::ClientStatus::PreActive:
1835 /* The map has been sent, so this is for loading the map and syncing up. */
1836 if (lag > _settings_client.network.max_join_time) {
1837 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);
1838 cs->SendError(NetworkErrorCode::TimeoutJoin);
1839 continue;
1840 }
1841 break;
1842
1843 case NetworkClientSocket::ClientStatus::AuthGame:
1844 /* These don't block? */
1845 if (lag > _settings_client.network.max_password_time) {
1846 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);
1847 cs->SendError(NetworkErrorCode::TimeoutPassword);
1848 continue;
1849 }
1850 break;
1851
1852 case NetworkClientSocket::ClientStatus::End:
1853 /* Bad server/code. */
1854 NOT_REACHED();
1855 }
1856
1857 if (cs->status >= NetworkClientSocket::ClientStatus::PreActive) {
1858 /* Check if we can send command, and if we have anything in the queue */
1860
1861 /* Send an updated _frame_counter_max to the client */
1862 if (send_frame) cs->SendFrame();
1863
1864#ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1865 /* Send a sync-check packet */
1866 if (send_sync) cs->SendSync();
1867#endif
1868 }
1869 }
1870}
1871
1874{
1875 _settings_newgame.game_creation.generation_seed = GENERATE_NEW_SEED;
1876 switch (_file_to_saveload.ftype.abstract) {
1880 break;
1881
1884 break;
1885
1886 default:
1888 }
1889}
1890
1893{
1894 if (!_network_server) return;
1895
1896 /* If setting is 0, this feature is disabled. */
1897 if (_settings_client.network.restart_hours == 0) return;
1898
1899 Debug(Facility::Net, Severity::Notice, "Auto-restarting map: {} hours played", _settings_client.network.restart_hours);
1901});
1902
1908{
1909 if (!_network_server) return;
1910
1911 _network_restart_map_timer.SetInterval({ std::chrono::hours(_settings_client.network.restart_hours), TimerGameRealtime::Trigger::Unpaused }, reset);
1912}
1913
1916{
1917 /* If setting is 0, this feature is disabled. */
1918 if (_settings_client.network.restart_game_year == 0) return;
1919
1920 if (TimerGameCalendar::year >= _settings_client.network.restart_game_year) {
1921 Debug(Facility::Net, Severity::Notice, "Auto-restarting map: year {} reached", TimerGameCalendar::year);
1923 }
1924}
1925
1927static const IntervalTimer<TimerGameCalendar> _calendar_network_yearly({ TimerGameCalendar::Trigger::Year, TimerGameCalendar::Priority::None }, [](auto) {
1928 if (!_network_server) return;
1929
1931});
1932
1934static const IntervalTimer<TimerGameEconomy> _economy_network_yearly({TimerGameEconomy::Trigger::Year, TimerGameEconomy::Priority::None}, [](auto)
1935{
1936 if (!_network_server) return;
1937
1939});
1940
1942static const IntervalTimer<TimerGameEconomy> _network_quarterly({TimerGameEconomy::Trigger::Quarter, TimerGameEconomy::Priority::None}, [](auto)
1943{
1944 if (!_network_server) return;
1945
1948});
1949
1951static const IntervalTimer<TimerGameEconomy> _network_monthly({TimerGameEconomy::Trigger::Month, TimerGameEconomy::Priority::None}, [](auto)
1952{
1953 if (!_network_server) return;
1954
1957});
1958
1960static const IntervalTimer<TimerGameEconomy> _network_weekly({TimerGameEconomy::Trigger::Week, TimerGameEconomy::Priority::None}, [](auto)
1961{
1962 if (!_network_server) return;
1963
1965});
1966
1968static const IntervalTimer<TimerGameEconomy> _economy_network_daily({TimerGameEconomy::Trigger::Day, TimerGameEconomy::Priority::None}, [](auto)
1969{
1970 if (!_network_server) return;
1971
1973});
1974
1980{
1981 return this->client_address.GetHostname();
1982}
1983
1986{
1988 "inactive",
1989 "authorizing",
1990 "identifying client",
1991 "checking NewGRFs",
1992 "authorized",
1993 "waiting",
1994 "loading map",
1995 "map done",
1996 "ready",
1997 "active"
1998 };
1999
2000 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
2001 NetworkClientInfo *ci = cs->GetInfo();
2002 if (ci == nullptr) continue;
2003 uint lag = NetworkCalculateLag(cs);
2004
2005 std::string_view status = (to_underlying(cs->status) < std::size(stat_str) ? stat_str[cs->status] : "unknown");
2006 IConsolePrint(CC_INFO, "Client #{} name: '{}' status: '{}' frame-lag: {} company: {} IP: {}",
2007 cs->client_id, ci->client_name, status, lag,
2008 ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0),
2009 cs->GetClientIP());
2010 }
2011}
2012
2017{
2018 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
2019 if (cs->status >= NetworkClientSocket::ClientStatus::PreActive) cs->SendConfigUpdate();
2020 }
2021}
2022
2028
2034void NetworkServerDoMove(ClientID client_id, CompanyID company_id)
2035{
2036 /* Only allow non-dedicated servers and normal clients to be moved */
2037 if (client_id == ClientID::Server && _network_dedicated) return;
2038
2040 assert(ci != nullptr);
2041
2042 /* No need to waste network resources if the client is in the company already! */
2043 if (ci->client_playas == company_id) return;
2044
2045 ci->client_playas = company_id;
2046
2047 if (client_id == ClientID::Server) {
2048 SetLocalCompany(company_id);
2049 } else {
2050 NetworkClientSocket *cs = NetworkClientSocket::GetByClientID(client_id);
2051 /* When the company isn't authorized we can't move them yet. */
2052 if (cs->status < NetworkClientSocket::ClientStatus::Authorized) return;
2053 cs->SendMove(client_id, company_id);
2054 }
2055
2056 /* Announce the client's move. */
2057 NetworkUpdateClientInfo(client_id);
2058
2059 if (company_id == COMPANY_SPECTATOR) {
2060 /* The client has joined spectators. */
2062 } else {
2063 /* The client has joined another company. */
2064 std::string company_name = GetString(STR_COMPANY_NAME, company_id);
2066 Company::Get(company_id)->months_empty = 0; // Reset upon joining as client might not remain the whole month.
2067 }
2068
2069 InvalidateWindowData(WindowClass::NetworkClientList, 0);
2070}
2071
2078void NetworkServerSendRcon(ClientID client_id, ExtendedTextColour colour_code, std::string_view string)
2079{
2080 NetworkClientSocket::GetByClientID(client_id)->SendRConResult(colour_code.ToNetwork(), string);
2081}
2082
2088void NetworkServerKickClient(ClientID client_id, std::string_view reason)
2089{
2090 if (client_id == ClientID::Server) return;
2091 NetworkClientSocket::GetByClientID(client_id)->SendError(NetworkErrorCode::Kicked, reason);
2092}
2093
2101uint NetworkServerKickOrBanIP(ClientID client_id, bool ban, std::string_view reason)
2102{
2103 return NetworkServerKickOrBanIP(NetworkClientSocket::GetByClientID(client_id)->GetClientIP(), ban, reason);
2104}
2105
2113uint NetworkServerKickOrBanIP(std::string_view ip, bool ban, std::string_view reason)
2114{
2115 /* Add address to ban-list */
2116 if (ban) {
2117 bool contains = false;
2118 for (const auto &iter : _network_ban_list) {
2119 if (iter == ip) {
2120 contains = true;
2121 break;
2122 }
2123 }
2124 if (!contains) _network_ban_list.emplace_back(ip);
2125 }
2126
2127 uint n = 0;
2128
2129 /* There can be multiple clients with the same IP, kick them all but don't kill the server,
2130 * or the client doing the rcon. The latter can't be kicked because kicking frees closes
2131 * and subsequently free the connection related instances, which we would be reading from
2132 * and writing to after returning. So we would read or write data from freed memory up till
2133 * the segfault triggers. */
2134 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
2135 if (cs->client_id == ClientID::Server) continue;
2136 if (cs->client_id == _redirect_console_to_client) continue;
2137 if (cs->client_address.IsInNetmask(ip)) {
2138 NetworkServerKickClient(cs->client_id, reason);
2139 n++;
2140 }
2141 }
2142
2143 return n;
2144}
2145
2151bool NetworkCompanyHasClients(CompanyID company)
2152{
2153 for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
2154 if (ci->client_playas == company) return true;
2155 }
2156 return false;
2157}
2158
2159
2165{
2166 const NetworkClientInfo *ci = this->GetInfo();
2167 if (ci != nullptr && !ci->client_name.empty()) return ci->client_name;
2168
2169 return fmt::format("Client #{}", this->client_id);
2170}
2171
2176{
2178 if (_network_server) {
2179 IConsolePrint(CC_INFO, "Client #{} name: '{}' company: {} IP: {}",
2180 ci->client_id,
2181 ci->client_name,
2182 ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0),
2183 ci->client_id == ClientID::Server ? "server" : NetworkClientSocket::GetByClientID(ci->client_id)->GetClientIP());
2184 } else {
2185 IConsolePrint(CC_INFO, "Client #{} name: '{}' company: {}",
2186 ci->client_id,
2187 ci->client_name,
2188 ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0));
2189 }
2190 }
2191}
2192
2198std::string_view NetworkGetPublicKeyOfClient(ClientID client_id)
2199{
2200 auto socket = NetworkClientSocket::GetByClientID(client_id);
2201 return socket == nullptr ? "" : socket->GetPeerPublicKey();
2202}
2203
2204
2211{
2212 assert(c != nullptr);
2213
2214 if (!_network_server) return;
2215
2216 if (ci != nullptr) {
2217 /* ci is nullptr when replaying, or for AIs. In neither case there is a client. */
2218 ci->client_playas = c->index;
2220
2221 /*
2222 * This function is called from a command, but is only called for the server.
2223 * The client information is managed out-of-band from the commands, so to not have a
2224 * different state/president/company name in the different clients, we need to
2225 * circumvent the normal ::Post logic and go directly to sending the command.
2226 */
2227 Command<Commands::CompanyAllowListControl>::SendNet(STR_NULL, c->index, CompanyAllowListCtrlAction::AddKey, ci->public_key);
2228 Command<Commands::RenamePresident>::SendNet(STR_NULL, c->index, ci->client_name);
2229
2231 }
2232}
std::map< SOCKET, NetworkAddress > SocketList
Type for a mapping between address and socket.
Definition address.h:19
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Timpl & Set()
Set all bits.
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition timer.h:76
Default implementation for the authorized key handler.
Default implementation of the password provider.
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.
@ RetryNextMethod
The client failed to authenticate, but there is another method to try.
@ NotAuthenticated
All authentications for this handler have been exhausted.
@ Authenticated
The client was authenticated successfully.
bool Contains(std::string_view key) const
Check whether the given key is contains in these authorized keys.
Definition network.cpp:176
bool IsPendingDeletion() const
Is this pending for deletion and as such should not be accessed anymore.
Definition tcp_game.h:571
NetworkGameSocketHandler(SOCKET s)
Create a new socket for the game connection.
Definition tcp_game.cpp:29
uint32_t last_frame
Last frame we have executed.
Definition tcp_game.h:528
NetworkClientInfo * GetInfo() const
Gets the client info of this socket handler.
Definition tcp_game.h:557
std::optional< std::string_view > ReceiveCommand(Packet &p, CommandPacket &cp)
Receives a command from the network.
ClientID client_id
Client identifier.
Definition tcp_game.h:527
CommandQueue incoming_queue
The command-queue awaiting handling.
Definition tcp_game.h:530
std::chrono::steady_clock::time_point last_packet
Time we received the last frame.
Definition tcp_game.h:531
void SetInfo(NetworkClientInfo *info)
Sets the client info for this socket handler.
Definition tcp_game.h:547
uint32_t last_frame_server
Last frame the server has executed.
Definition tcp_game.h:529
NetworkClientInfo * info
Client info related to this socket.
Definition tcp_game.h:143
void SendCommand(Packet &p, const CommandPacket &cp)
Sends a command over the network.
void DeferDeletion()
Mark this socket handler for deletion, once iterating the socket handlers is done.
Definition tcp_game.cpp:190
bool HasClientQuit() const
Whether the current client connected to the socket has quit.
Definition core.h:70
std::unique_ptr< class NetworkEncryptionHandler > send_encryption_handler
The handler for encrypting sent packets.
Definition core.h:46
std::unique_ptr< class NetworkEncryptionHandler > receive_encryption_handler
The handler for decrypting received packets.
Definition core.h:45
virtual std::unique_ptr< Packet > ReceivePacket()
Receives a packet for the given client.
Definition tcp.cpp:118
SOCKET sock
The socket currently connected to.
Definition tcp.h:35
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:57
SendPacketsState SendPackets(bool closing_down=false)
Sends all the buffered packets out for this client.
Definition tcp.cpp:75
Class for handling the server side of the game connection.
static std::string_view GetName()
Get the name used by the listener.
NetworkRecvStatus ReceiveClientGameInfo(Packet &p) override
Request game information.
size_t receive_limit
Amount of bytes that we can receive at this moment.
std::shared_ptr< struct PacketWriter > savegame
Writer used to write the savegame.
static void Send()
Send the packets for the server sockets.
NetworkRecvStatus SendQuit(ClientID client_id)
Tell the client another client quit.
NetworkRecvStatus ReceiveClientIdentify(Packet &p) override
The client tells the server about the identity of the client: string Name of the client (max NETWORK_...
std::unique_ptr< Packet > ReceivePacket() override
Receives a packet for the given client.
@ MapWait
The client is waiting as someone else is downloading the map.
@ PreActive
The client is catching up the delayed frames.
@ Inactive
The client is not connected nor active.
@ Map
The client is downloading the map.
@ Active
The client is active within in the game.
@ Identify
The client is identifying itself.
@ NewGRFsCheck
The client is checking NewGRFs.
@ DoneMap
The client has downloaded the map.
@ AuthGame
The client is authorizing with game (server) password.
NetworkRecvStatus SendRConResult(uint16_t colour, std::string_view command)
Send the result of a console action.
NetworkRecvStatus ReceiveClientAck(Packet &p) override
Tell the server we are done with this frame: uint32_t Current frame counter of the client.
NetworkRecvStatus SendChat(NetworkAction action, ClientID client_id, bool self_send, std::string_view msg, int64_t data)
Send a chat message.
NetworkRecvStatus SendWelcome()
Send the client a welcome message with some basic information.
NetworkRecvStatus SendAuthRequest()
Request the game password.
std::string GetClientName() const
Get the name of the client, if the user did not send it yet, Client ID is used.
NetworkRecvStatus ReceiveClientRemoteConsoleCommand(Packet &p) override
Send an RCon command to the server: string RCon password.
uint8_t last_token
The last random token we did send to verify the client is listening.
NetworkRecvStatus SendFrame()
Tell the client that they may run to a particular frame.
NetworkRecvStatus ReceiveClientSetName(Packet &p) override
Gives the client a new name: string New name of the client.
NetworkRecvStatus SendGameInfo()
Send the client information about the server.
NetworkRecvStatus SendJoin(ClientID client_id)
Tell that a client joined.
~ServerNetworkGameSocketHandler() override
Clear everything related to this client.
NetworkRecvStatus ReceiveClientChat(Packet &p) override
Sends a chat-packet to the server: uint8_t ID of the action (see NetworkAction).
NetworkRecvStatus ReceiveClientNewGRFsChecked(Packet &p) override
Tell the server that we have the required GRFs.
std::string peer_public_key
The public key of our client.
NetworkRecvStatus ReceiveClientGetMap(Packet &p) override
Request the map from the server.
NetworkRecvStatus SendClientInfo(NetworkClientInfo *ci)
Send the client information about a client.
static bool AllowConnection()
Whether an connection is allowed or not at this moment.
NetworkRecvStatus SendEnableEncryption()
Notify the client that the authentication has completed and tell that for the remainder of this socke...
ServerNetworkGameSocketHandler(ClientPoolID index, SOCKET s)
Create a new socket for the server side of the game connection.
NetworkRecvStatus SendErrorQuit(ClientID client_id, NetworkErrorCode errorno)
Tell the client another client quit with an error.
NetworkAddress client_address
IP-address of the client (so they can be banned).
NetworkRecvStatus SendNewGame()
Tell the client we're starting a new game.
NetworkRecvStatus ReceiveClientCommand(Packet &p) override
Send a DoCommand to the Server: uint8_t ID of the company (0..MAX_COMPANIES-1).
NetworkRecvStatus SendSync()
Request the client to sync.
std::unique_ptr< class NetworkAuthenticationServerHandler > authentication_handler
The handler for the authentication.
NetworkRecvStatus ReceiveClientJoin(Packet &p) override
Try to join the server: string OpenTTD revision (norev0000 if no revision).
NetworkRecvStatus ReceiveClientError(Packet &p) override
The client made an error and is quitting the game.
NetworkRecvStatus SendMove(ClientID client_id, CompanyID company_id)
Tell that a client moved to another company.
NetworkRecvStatus SendError(NetworkErrorCode error, std::string_view reason={})
Send an error to the client, and close its connection.
NetworkRecvStatus CloseConnection(NetworkRecvStatus status) override
Close the network connection due to the given status.
NetworkRecvStatus SendMap()
This sends the map to the client.
uint32_t last_token_frame
The last frame we received the right token.
NetworkRecvStatus SendExternalChat(std::string_view source, ExtendedTextColour colour, std::string_view user, std::string_view msg)
Send a chat message from external source.
NetworkRecvStatus SendShutdown()
Tell the client we're shutting down.
NetworkRecvStatus ReceiveClientMapOk(Packet &p) override
Tell the server that we are done receiving/loading the map.
NetworkRecvStatus ReceiveClientQuit(Packet &p) override
The client is quitting the game.
ClientStatus status
Status of this client.
void CheckNextClientToSendMap(NetworkClientSocket *ignore_cs=nullptr)
Find the next candidate for joining, and start the joining process for that client.
NetworkRecvStatus SendNewGRFCheck()
Send the check for the NewGRFs.
NetworkRecvStatus ReceiveClientAuthenticationResponse(Packet &p) override
Send the response to the authentication request: 32 * uint8_t Public key of the client.
std::string_view GetClientIP()
Get the IP address/hostname of the connected client.
NetworkRecvStatus SendConfigUpdate()
Send an update about the max company/spectator counts.
NetworkRecvStatus SendWait()
Tell the client that its put in a waiting queue.
NetworkRecvStatus ReceiveClientMove(Packet &p) override
Request the server to move this client into another company: uint8_t ID of the company the client wan...
NetworkRecvStatus SendCommand(const CommandPacket &cp)
Send a command to the client to execute.
Template for TCP listeners.
Definition tcp_listen.h:28
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static Year year
Current year, starting at 0.
static Date date
Current date in days (day counter).
static DateFract date_fract
Fractional part of the day.
@ Unpaused
Only run when not paused.
CommandFlags GetCommandFlags(Commands cmd)
Get the command flags associated with the given command.
Definition command.cpp:112
Functions related to commands.
@ Spectator
the command may be initiated by a spectator
@ Server
the command can only be initiated by the server
@ ClientID
set p2 with the ClientID of the sending client.
@ CompanyControl
used in multiplayer to create a new companies etc.
@ CompanyAllowListControl
Used in multiplayer to add/remove a client's public key to/from the company's allow list.
Definition of stuff that is very close to a company, like the company struct itself.
void SetLocalCompany(CompanyID new_company, bool switching_game)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
ExtendedTextColour GetDrawStringCompanyColour(CompanyID company)
Get the colour for DrawString-subroutines which matches the colour of the company.
Command definitions related to companies.
Functions related to companies.
GUI Functions related to companies.
CompanyCtrlAction
The action to do with Commands::CompanyControl.
@ New
Create a new company.
@ Delete
Delete a company.
static constexpr CompanyID COMPANY_SPECTATOR
The client is spectating.
@ AddKey
Create a public key.
static constexpr CompanyID COMPANY_NEW_COMPANY
The client wants a new company.
@ Autoclean
The company is removed due to autoclean.
static const size_t TCP_MTU
Number of bytes we can pack in a single TCP packet.
Definition config.h:43
static const uint NETWORK_CLIENT_NAME_LENGTH
The maximum length of a client's name, in bytes including '\0'.
Definition config.h:56
static const uint NETWORK_CHAT_LENGTH
The maximum length of a chat message, in bytes including '\0'.
Definition config.h:59
static const uint NETWORK_REVISION_LENGTH
The maximum length of the revision, in bytes including '\0'.
Definition config.h:54
static const uint NETWORK_RCONCOMMAND_LENGTH
The maximum length of a rconsole command, in bytes including '\0'.
Definition config.h:57
static const uint NETWORK_PASSWORD_LENGTH
The maximum length of the password, in bytes including '\0'.
Definition config.h:55
void IConsolePrint(ExtendedTextColour 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:91
void IConsoleCmdExec(std::string_view command_string, const uint recurse_count)
Execute a given command passed to us.
Definition console.cpp:272
Console functions used outside of the console code.
static const TextColour CC_INFO
Colour for information lines.
static const TextColour CC_WARNING
Colour for warning lines.
static const TextColour CC_DEFAULT
Default colour of the console.
NetworkRecvStatus
Status of a network client; reasons why a client has quit.
Definition core.h:19
@ Okay
Everything is okay.
Definition core.h:20
@ ClientQuit
The connection is lost gracefully. Other clients are already informed of this leaving client.
Definition core.h:24
@ ServerFull
The server is full.
Definition core.h:27
@ ServerBanned
The server has banned us.
Definition core.h:28
@ ServerError
The server told us we made an error.
Definition core.h:26
@ MalformedPacket
We apparently send a malformed packet.
Definition core.h:25
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Desync
Desync message facility.
Definition debug_type.h:41
@ Net
Net message facility.
Definition debug_type.h:33
@ Warning
Warning, wrong but okay if you don't know.
Definition debug_type.h:17
@ Notice
Notice.
Definition debug_type.h:18
@ Error
Error, but we are recovering.
Definition debug_type.h:16
@ Trace3
Trace information #3.
Definition debug_type.h:24
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
#define DECLARE_INCREMENT_DECREMENT_OPERATORS(enum_type)
For some enums it is useful to have pre/post increment/decrement operators.
Definition enum_type.hpp:86
EnumClassIndexContainer< std::array< T, to_underlying(N)>, Index > EnumIndexArray
A typedef for EnumClassIndexContainer using std::array as the backing container type.
@ Savegame
old or new savegame
Definition fileio_type.h:18
@ Scenario
old or new scenario
Definition fileio_type.h:19
@ Heightmap
heightmap file
Definition fileio_type.h:20
Functions related to world/map generation.
static const uint32_t GENERATE_NEW_SEED
Create a new random seed.
Definition genworld.h:23
SwitchMode _switch_mode
The next mainloop command.
Definition gfx.cpp:45
static const uint MILLISECONDS_PER_TICK
The number of milliseconds per game tick.
Definition gfx_type.h:417
uint32_t _last_sync_frame
Used in the server to store the last time a sync packet was sent to clients.
Definition network.cpp:77
StringID GetNetworkErrorMsg(NetworkErrorCode err)
Retrieve a short translateable string of the error code.
Definition network.cpp:324
ClientID _redirect_console_to_client
If not invalid, redirect the console output to a client.
Definition network.cpp:69
uint32_t _frame_counter
The current frame.
Definition network.cpp:76
StringList _network_ban_list
The banned clients.
Definition network.cpp:73
bool _network_dedicated
are we a dedicated server?
Definition network.cpp:66
bool _network_server
network-server is active
Definition network.cpp:64
uint32_t _sync_seed_1
Seed to compare during sync checks.
Definition network.cpp:79
uint NetworkCalculateLag(const NetworkClientSocket *cs)
Calculate the frame-lag of a client.
Definition network.cpp:295
void NetworkTextMessage(NetworkAction action, ExtendedTextColour colour, bool self_send, std::string_view name, std::string_view str, StringParameter &&data)
Writes a text-message to the console and the chat box.
Definition network.cpp:240
uint8_t _network_clients_connected
The amount of clients connected.
Definition network.cpp:87
uint32_t _frame_counter_max
To where we may go with our clients.
Definition network.cpp:75
void NetworkAdminClientUpdate(const NetworkClientInfo *ci)
Notify the admin network of a client update (if they did opt in for the respective update).
void NetworkAdminClientQuit(ClientID client_id)
Notify the admin network that a client quit (if they have opt in for the respective update).
void NetworkAdminUpdate(AdminUpdateFrequency freq)
Send (push) updates to the admin network as they have registered for these updates.
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).
void NetworkAdminChat(NetworkAction action, NetworkChatDestinationType 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).
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).
Server part of the admin network protocol.
Base core network types and some helper functions to access them.
bool NetworkIsValidClientName(std::string_view client_name)
Check whether the given client name is deemed valid for use in network games.
void NetworkSyncCommandQueue(NetworkClientSocket *cs)
Sync our local command queue to the command queue of the given socket.
NetworkAuthenticationMethod
The authentication method that can be used.
@ X25519_PAKE
Authentication using x25519 password-authenticated key agreement.
@ X25519_AuthorizedKey
Authentication using x22519 key exchange and authorized keys.
void NetworkUpdateClientInfo(ClientID client_id)
Send updated client info of a particular client.
void NetworkServerSendChat(NetworkAction action, NetworkChatDestinationType type, int dest, std::string_view msg, ClientID from_id, int64_t data=0, bool from_admin=false)
Send an actual chat message.
void NetworkServerDoMove(ClientID client_id, CompanyID company_id)
Handle the tid-bits of moving a client from one company to another.
TypedIndexContainer< std::array< NetworkCompanyStats, MAX_COMPANIES >, CompanyID > NetworkCompanyStatsArray
Container with statistics for all possible companies.
void SerializeNetworkGameInfo(Packet &p, const NetworkServerGameInfo &info, bool send_newgrf_names)
Serializes the NetworkGameInfo struct to the packet.
const NetworkServerGameInfo & GetCurrentNetworkServerGameInfo()
Get the NetworkServerGameInfo structure with the latest information of the server.
void SerializeGRFIdentifier(Packet &p, const GRFIdentifier &grf)
Serializes the GRFIdentifier (GRF ID and MD5 checksum) to the packet.
void FillStaticNetworkServerGameInfo()
Fill a NetworkServerGameInfo structure with the static content, or things that are so static they can...
NetworkServerGameInfo _network_game_info
Information about our game.
bool IsNetworkCompatibleVersion(std::string_view other)
Checks whether the given version string is compatible with our version.
Convert NetworkGameInfo to Packet and back.
class ServerNetworkGameSocketHandler NetworkClientSocket
Class for handling the server side of the game connection.
bool NetworkMakeClientNameUnique(std::string &new_name)
Check whether a name is unique, and otherwise try to make it unique.
static NetworkAuthenticationDefaultAuthorizedKeyHandler _authorized_key_handler
Provides the authorized key handling for the game authentication.
bool NetworkServerChangeClientName(ClientID client_id, const std::string &new_name)
Change the client name of the given client.
void NetworkPrintClients()
Print all the clients to the console.
void NetworkServerUpdateGameInfo()
Update the server's NetworkServerGameInfo due to changes in settings.
static const IntervalTimer< TimerGameEconomy > _network_monthly({TimerGameEconomy::Trigger::Month, TimerGameEconomy::Priority::None}, [](auto) { if(!_network_server) return;NetworkAutoCleanCompanies();NetworkAdminUpdate(AdminUpdateFrequency::Monthly);})
Economy monthly "callback".
NetworkCompanyStatsArray NetworkGetCompanyStats()
Get the company stats.
void NetworkUpdateClientInfo(ClientID client_id)
Send updated client info of a particular client.
void NetworkServerSendExternalChat(std::string_view source, ExtendedTextColour colour, std::string_view user, std::string_view msg)
Send a chat message from external source.
void NetworkServerSendChat(NetworkAction action, NetworkChatDestinationType desttype, int dest, std::string_view msg, ClientID from_id, int64_t data, bool from_admin)
Send an actual chat message.
NetworkClientSocketPool _networkclientsocket_pool
Make very sure the preconditions given in network_type.h are actually followed.
static IntervalTimer< TimerGameRealtime > _network_restart_map_timer({std::chrono::hours::zero(), TimerGameRealtime::Trigger::Unpaused}, [](auto) { if(!_network_server) return;if(_settings_client.network.restart_hours==0) return;Debug(Facility::Net, Severity::Notice, "Auto-restarting map: {} hours played", _settings_client.network.restart_hours);NetworkRestartMap();})
Timer to restart a network server automatically based on real-time hours played.
void NetworkServerSendConfigUpdate()
Send Config Update.
static const IntervalTimer< TimerGameEconomy > _network_quarterly({TimerGameEconomy::Trigger::Quarter, TimerGameEconomy::Priority::None}, [](auto) { if(!_network_server) return;NetworkAutoCleanCompanies();NetworkAdminUpdate(AdminUpdateFrequency::Quarterly);})
Quarterly "callback".
static NetworkErrorCode GetErrorForAuthenticationMethod(NetworkAuthenticationMethod method)
Determine the NetworkErrorCode for a failure of a given authentication method.
static const IntervalTimer< TimerGameCalendar > _calendar_network_yearly({ TimerGameCalendar::Trigger::Year, TimerGameCalendar::Priority::None }, [](auto) { if(!_network_server) return;NetworkCheckRestartMapYear();})
Calendar yearly "callback".
void NetworkServerSendRcon(ClientID client_id, ExtendedTextColour colour_code, std::string_view string)
Send an rcon reply to the client.
void NetworkServerDoMove(ClientID client_id, CompanyID company_id)
Handle the tid-bits of moving a client from one company to another.
static NetworkAuthenticationDefaultPasswordProvider _password_provider
Provides the password validation for the game's password.
static const IntervalTimer< TimerGameEconomy > _economy_network_yearly({TimerGameEconomy::Trigger::Year, TimerGameEconomy::Priority::None}, [](auto) { if(!_network_server) return;NetworkAdminUpdate(AdminUpdateFrequency::Annually);})
Economy yearly "callback".
void ChangeNetworkRestartTime(bool reset)
Reset the automatic network restart time interval.
bool NetworkCompanyHasClients(CompanyID company)
Check whether a particular company has clients.
static void NetworkRestartMap()
Helper function to restart the map.
void NetworkServerKickClient(ClientID client_id, std::string_view reason)
Kick a single client.
static void NetworkCheckRestartMapYear()
Check if we want to restart the map based on the year.
bool NetworkMakeClientNameUnique(std::string &name)
Check whether a name is unique, and otherwise try to make it unique.
static ClientID _network_client_id
The identifier counter for new clients (is never decreased).
std::string_view NetworkGetPublicKeyOfClient(ClientID client_id)
Get the public key of the client with the given id.
static void NetworkHandleCommandQueue(NetworkClientSocket *cs)
Handle the command-queue of a socket.
static const IntervalTimer< TimerGameEconomy > _economy_network_daily({TimerGameEconomy::Trigger::Day, TimerGameEconomy::Priority::None}, [](auto) { if(!_network_server) return;NetworkAdminUpdate(AdminUpdateFrequency::Daily);})
Daily "callback".
static const IntervalTimer< TimerGameEconomy > _network_weekly({TimerGameEconomy::Trigger::Week, TimerGameEconomy::Priority::None}, [](auto) { if(!_network_server) return;NetworkAdminUpdate(AdminUpdateFrequency::Weekly);})
Economy weekly "callback".
void NetworkServerShowStatusToConsole()
Show the status message of all clients on the console.
void NetworkServerNewCompany(const Company *c, NetworkClientInfo *ci)
Perform all the server specific administration of a new company.
uint NetworkServerKickOrBanIP(ClientID client_id, bool ban, std::string_view reason)
Ban, or kick, everyone joined from the given client's IP.
void NetworkServer_Tick(bool send_frame)
This is called every tick if this is a _network_server.
static void NetworkAutoCleanCompanies()
Remove companies that have not been used depending on the autoclean_companies setting and values for ...
static NetworkAuthenticationDefaultAuthorizedKeyHandler _rcon_authorized_key_handler
Provides the authorized key validation for rcon.
Server part of the network protocol.
ServerNetworkGameSocketHandler NetworkClientSocket
Make the code look slightly nicer/simpler.
NetworkClientSocketPool _networkclientsocket_pool
Make very sure the preconditions given in network_type.h are actually followed.
Pool< NetworkClientSocket, ClientPoolID, 8, PoolType::NetworkClient > NetworkClientSocketPool
Pool with all client sockets.
NetworkVehicleType
Vehicletypes in the order they are send in info packets.
@ Bus
A road vehicle that stops at bus stops.
@ Truck
A road vehicle that stops at truck stops.
@ Aircraft
An airplane or helicopter.
NetworkErrorCode
The error codes we send around in the protocols.
@ WrongRevision
The client is using the wrong revision.
@ Cheater
The client is trying control companies in a way they are not supposed to.
@ TimeoutPassword
The client has timed out providing a password.
@ TooManyCommands
The client has sent too many commands in a short time.
@ TimeoutComputer
The client has timed out because the computer could not keep up with the server.
@ TimeoutMap
The client has timed out because it took too long to download the map.
@ NotAuthorized
The client tried to do something there are not authorized to.
@ ServerFull
The server is full.
@ InvalidClientName
The client tried to set an invalid name.
@ TimeoutJoin
The client has timed out because getting up to speed with the server failed.
@ NotOnAllowList
The client is not on the allow list.
@ WrongPassword
The client entered a wrong password.
@ NotExpected
The request/packet was not expected in the current state.
@ Kicked
The client got kicked.
@ ConnectionLost
Connection to the client was lost.
@ IllegalPacket
A packet was received that has invalid content.
@ NameInUse
The client has a duplicate name (and we couldn't make it unique).
@ CompanyMismatch
The client was impersonating another company.
NetworkAction
Actions that can be used for NetworkTextMessage.
@ ChatExternal
An external application sent a message over the admin port.
@ ServerMessage
The server sent a message.
@ ClientKicked
A client got kicked.
@ ChatTeam
A chat sent to all clients of a team/company.
@ ClientNameChange
A client changed their name.
@ ClientJoin
A client joined the server.
@ CompanySpectator
A client joined the spectators.
@ ChatClient
A chat sent to a specific client.
@ ChatBroadcast
A chat broadcast to all clients.
@ ClientLeave
A client left the server.
@ CompanyNew
A client created an joined a new company.
@ CompanyJoin
A client joined an existing company.
static const uint MAX_CLIENTS
How many clients can we have.
NetworkChatDestinationType
Destination of our chat messages.
@ Client
Send message/notice to only a certain client (Private).
@ Team
Send message/notice to everyone playing the same company (Team).
@ Broadcast
Send message/notice to all clients (All).
ClientID
'Unique' identifier to be given to clients
@ Invalid
Client is not part of anything.
@ First
The first client ID.
@ Server
Servers always have this ID.
PoolID< uint16_t, struct ClientPoolIDTag, MAX_CLIENTS+1, 0xFFFF > ClientPoolID
Indices into the client related pools.
GRFConfigList _grfconfig
First item in list of current GRF set up.
@ Static
GRF file is used statically (can be used in any MP game).
@ LoadGame
Load game, Play Scenario.
Definition openttd.h:32
@ StartHeightmap
Load a heightmap and start a new game from it.
Definition openttd.h:38
@ NewGame
New Game --> 'Random game'.
Definition openttd.h:28
Functions related to order backups.
Some methods of Pool are placed here in order to reduce compilation time and binary size.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
Pseudo random number generator.
Declaration of OTTD revision dependent variables.
Road vehicle states.
A number of safeguards to prevent using unsafe methods.
void SlError(StringID string, const std::string &extra_msg)
Error handler.
Definition saveload.cpp:342
SaveLoadResult SaveWithFilter(std::shared_ptr< SaveFilter > writer, bool threaded)
Save the game using a (writer) filter.
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Definition saveload.cpp:81
Declaration of filters used for saving and loading savegames.
Functions related to saving and loading games.
@ Ok
completed successfully
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
Definition settings.cpp:62
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
Base classes/functions for stations.
@ Dock
Station with a dock.
@ TruckStop
Station with truck stops.
@ Train
Station with train station.
@ Airport
Station with an airport.
@ BusStop
Station with bus stops.
Definition of base types and functions in a cross-platform compatible way.
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:423
Functions related to OTTD's strings.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
Everything we need to know about a command to be able to execute it.
CommandDataBuffer data
command parameters.
uint32_t frame
the frame in which this packet is executed
CompanyID company
company that is executing the command
bool my_cmd
did the command originate from "me"
Commands cmd
command being executed.
Defines the traits of a command.
NetworkAuthorizedKeys allow_list
Public keys of clients that are allowed to join this company.
bool allow_any
Set if anyone is allowed to join this company.
uint8_t months_empty
NOSAVE: Number of months this company has not had a client in multiplayer.
static bool IsValidHumanID(auto index)
Is this company a valid company, not controlled by a NoAI program?
Container for the text colour and some text colour related flags for drawing.
Definition gfx_type.h:349
constexpr uint16_t ToNetwork() const
Encode this text colour for sending over the network.
Definition gfx_type.h:383
Statistics and caches on the vehicles in a group.
Definition group.h:25
Container for all information known about a client.
static NetworkClientInfo * GetByClientID(ClientID client_id)
Return the CI given it's client-identifier.
Definition network.cpp:114
TimerGameEconomy::Date join_date
Gamedate the client has joined.
CompanyID client_playas
As which company is this client playing (CompanyID).
ClientID client_id
Client identifier (same as ClientState->client_id).
std::string client_name
Name of the client.
std::string public_key
The public key of the client.
Simple calculated statistics of a company.
NetworkVehicleTypeArray num_station
How many stations are there of this type?
static void ResetUser(ClientID user)
Reset an user's OrderBackup if needed.
std::unique_ptr< Packet > current
The packet we're currently writing to.
PacketWriter(ServerNetworkGameSocketHandler *cs)
Create the packet writer.
size_t total_size
Total size of the compressed savegame.
std::condition_variable exit_sig
Signal for threaded destruction of this packet writer.
void Finish() override
Prepare everything to finish writing the savegame.
~PacketWriter() override
Make sure everything is cleaned up under lock.
void Write(const uint8_t *buf, size_t size) override
Write a given number of bytes into the savegame.
ServerNetworkGameSocketHandler * cs
Socket we are associated with.
std::mutex mutex
Mutex for making threaded saving safe.
void Destroy()
Begin the destruction of this packet writer.
bool TransferToNetworkQueue()
Transfer all packets from here to the network's queue while holding the lock on our mutex.
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...
uint64_t Recv_uint64()
Read a 64 bits integer from the packet.
Definition packet.cpp:362
uint32_t Recv_uint32()
Read a 32 bits integer from the packet.
Definition packet.cpp:345
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:423
uint8_t Recv_uint8()
Read a 8 bits integer from the packet.
Definition packet.cpp:316
static Pool::IterateWrapper< NetworkClientSocket > Iterate(size_t from=0)
static Company * Get(auto index)
static Company * GetIfValid(auto index)
bool IsBus() const
Check whether a roadvehicle is a bus.
SaveFilter(std::shared_ptr< SaveFilter > chain)
Initialise this filter.
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
static RoadVehicle * From(Vehicle *v)
Station data structure.
Vehicle data structure.
@ Closed
The connection got closed.
Definition tcp.h:22
@ Annually
The admin gets information about this on a yearly basis.
Definition tcp_admin.h:100
@ Weekly
The admin gets information about this on a weekly basis.
Definition tcp_admin.h:97
@ Monthly
The admin gets information about this on a monthly basis.
Definition tcp_admin.h:98
@ Quarterly
The admin gets information about this on a quarterly basis.
Definition tcp_admin.h:99
@ Daily
The admin gets information about this on a daily basis.
Definition tcp_admin.h:96
PacketGameType
Enum with all types of TCP packets.
Definition tcp_game.h:22
@ ServerAuthenticationRequest
The server requests the client to authenticate using a number of methods.
Definition tcp_game.h:60
@ ServerClientInfo
Server sends you information about a client.
Definition tcp_game.h:73
@ ServerShutdown
The server is shutting down.
Definition tcp_game.h:47
@ ServerMapDone
Server tells it has just sent the last bits of the map to the client.
Definition tcp_game.h:81
@ ServerMapBegin
Server tells the client that it is beginning to send the map.
Definition tcp_game.h:78
@ ServerFrame
Server tells the client what frame it is in, and thus to where the client may progress.
Definition tcp_game.h:93
@ ServerMapData
Server sends bits of the map to the client.
Definition tcp_game.h:80
@ ServerClientJoined
Tells clients that a new client has joined.
Definition tcp_game.h:84
@ ServerGameInfo
Information about the server.
Definition tcp_game.h:42
@ ServerMapSize
Server tells the client what the (compressed) size of the map is.
Definition tcp_game.h:79
@ ServerMove
Server tells everyone that someone is moved to another company.
Definition tcp_game.h:112
@ ServerQuit
A server tells that a client has quit.
Definition tcp_game.h:120
@ ServerError
Server sending an error message to the client.
Definition tcp_game.h:35
@ ServerSync
Server tells the client what the random state should be.
Definition tcp_game.h:95
@ ServerConfigurationUpdate
Some network configuration important to the client changed.
Definition tcp_game.h:116
@ ServerRemoteConsoleCommand
Response of the executed command on the server.
Definition tcp_game.h:108
@ ServerExternalChat
Server distributing the message from external source.
Definition tcp_game.h:104
@ ServerErrorQuit
A server tells that a client has hit an error and did quit.
Definition tcp_game.h:122
@ ServerWelcome
Server welcomes you and gives you your ClientID.
Definition tcp_game.h:72
@ ServerCommand
Server distributes a command to (all) the clients.
Definition tcp_game.h:99
@ ServerChat
Server distributing the message of a client (or itself).
Definition tcp_game.h:103
@ ServerCheckNewGRFs
Server sends NewGRF IDs and MD5 checksums for the client to check.
Definition tcp_game.h:68
@ ServerWaitForMap
Server tells the client there are some people waiting for the map as well.
Definition tcp_game.h:77
@ ServerEnableEncryption
The server tells that authentication has completed and requests to enable encryption with the keys of...
Definition tcp_game.h:62
@ ServerNewGame
The server is preparing to start a new game.
Definition tcp_game.h:46
SocketList TCPListenHandler< Tsocket, EnumPacketType, Tfull_packet, Tban_packet >::sockets
Instantiate the sockets.
Definition tcp_listen.h:180
Definition of Interval and OneShot timers.
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
Definition of the real time game-timer.
@ Ship
Ship vehicle type.
@ Aircraft
Aircraft vehicle type.
@ Road
Road vehicle type.
@ Train
Train vehicle type.
std::mutex lock
synchronization for playback status fields
Definition win32_m.cpp:35
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:3377