OpenTTD Source 20250524-master-gc366e6a48e
network_client.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 <http://www.gnu.org/licenses/>.
6 */
7
10#include "../stdafx.h"
11#include "network_gui.h"
12#include "../core/string_consumer.hpp"
13#include "../saveload/saveload.h"
14#include "../saveload/saveload_filter.h"
15#include "../command_func.h"
16#include "../console_func.h"
17#include "../strings_func.h"
18#include "../window_func.h"
19#include "../company_func.h"
20#include "../company_base.h"
21#include "../company_gui.h"
22#include "../company_cmd.h"
23#include "../core/random_func.hpp"
24#include "../timer/timer_game_tick.h"
25#include "../timer/timer_game_calendar.h"
26#include "../gfx_func.h"
27#include "../error.h"
28#include "../rev.h"
29#include "network.h"
30#include "network_base.h"
31#include "network_client.h"
32#include "network_gamelist.h"
33#include "../core/backup_type.hpp"
34#include "../thread.h"
35#include "../social_integration.h"
36
37#include "table/strings.h"
38
39#include "../safeguards.h"
40
41/* This file handles all the client-commands */
42
45 using Buffer = std::deque<uint8_t>;
46
48 Buffer::const_iterator iterator;
49 size_t read_bytes = 0;
50
53 {
54 }
55
61 {
62 assert(this->read_bytes == 0);
63 p.TransferOut([this](std::span<const uint8_t> source) {
64 std::ranges::copy(source, std::back_inserter(this->buffer));
65 return source.size();
66 });
67 }
68
69 size_t Read(uint8_t *rbuf, size_t size) override
70 {
71 /* Limit the amount to read to whatever we still have. */
72 size_t read_size = std::min(this->buffer.size() - this->read_bytes, size);
73
74 std::copy_n(this->iterator, read_size, rbuf);
75 std::advance(this->iterator, read_size);
76 this->read_bytes += read_size;
77
78 return read_size;
79 }
80
81 void Reset() override
82 {
83 this->read_bytes = 0;
84 this->iterator = this->buffer.cbegin();
85 }
86};
87
88
93{
94 static FiosNumberedSaveName _netsave_ctr("netsave");
95 DoAutoOrNetsave(_netsave_ctr);
96}
97
98
103ClientNetworkGameSocketHandler::ClientNetworkGameSocketHandler(SOCKET s, std::string_view connection_string) : NetworkGameSocketHandler(s), connection_string(connection_string)
104{
107}
108
117
119{
121 if (this->IsPendingDeletion()) return status;
122
123 assert(this->sock != INVALID_SOCKET);
124
125 if (!this->HasClientQuit()) {
126 Debug(net, 3, "Closed client connection {}", this->client_id);
127
128 this->SendPackets(true);
129
130 /* Wait a number of ticks so our leave message can reach the server.
131 * This is especially needed for Windows servers as they seem to get
132 * the "socket is closed" message before receiving our leave message,
133 * which would trigger the server to close the connection as well. */
135 }
136
137 this->DeferDeletion();
138
139 return status;
140}
141
147{
148 if (this->IsPendingDeletion()) return;
149
150 /* First, send a CLIENT_ERROR to the server, so it knows we are
151 * disconnected (and why!) */
152 NetworkErrorCode errorno;
153
154 /* We just want to close the connection.. */
157 this->CloseConnection(res);
158 _networking = false;
159
161 return;
162 }
163
164 switch (res) {
165 case NETWORK_RECV_STATUS_DESYNC: errorno = NETWORK_ERROR_DESYNC; break;
166 case NETWORK_RECV_STATUS_SAVEGAME: errorno = NETWORK_ERROR_SAVEGAME_FAILED; break;
167 case NETWORK_RECV_STATUS_NEWGRF_MISMATCH: errorno = NETWORK_ERROR_NEWGRF_MISMATCH; break;
168 default: errorno = NETWORK_ERROR_GENERAL; break;
169 }
170
173 /* This means the server closed the connection. Emergency save is
174 * already created if this was appropriate during handling of the
175 * disconnect. */
176 this->CloseConnection(res);
177 } else {
178 /* This means we as client made a boo-boo. */
179 SendError(errorno);
180
181 /* Close connection before we make an emergency save, as the save can
182 * take a bit of time; better that the server doesn't stall while we
183 * are doing the save, and already disconnects us. */
184 this->CloseConnection(res);
186 }
187
189
190 if (_game_mode != GM_MENU) _switch_mode = SM_MENU;
191 _networking = false;
192}
193
194
201{
202 if (my_client->CanSendReceive()) {
204 if (res != NETWORK_RECV_STATUS_OKAY) {
205 /* The client made an error of which we can not recover.
206 * Close the connection and drop back to the main menu. */
208 return false;
209 }
210 }
211 return _networking;
212}
213
216{
218 if (my_client != nullptr) my_client->CheckConnection();
219}
220
226{
228
230
232
233 /* Check if we are in sync! */
234 if (_sync_frame != 0) {
236#ifdef NETWORK_SEND_DOUBLE_SEED
237 if (_sync_seed_1 != _random.state[0] || _sync_seed_2 != _random.state[1]) {
238#else
239 if (_sync_seed_1 != _random.state[0]) {
240#endif
241 ShowNetworkError(STR_NETWORK_ERROR_DESYNC);
242 Debug(desync, 1, "sync_err: {:08x}; {:02x}", TimerGameEconomy::date, TimerGameEconomy::date_fract);
243 Debug(net, 0, "Sync error detected");
245 return false;
246 }
247
248 /* If this is the first time we have a sync-frame, we
249 * need to let the server know that we are ready and at the same
250 * frame as it is.. so we can start playing! */
252 _network_first_time = false;
253 SendAck();
254 }
255
256 _sync_frame = 0;
257 } else if (_sync_frame < _frame_counter) {
258 Debug(net, 1, "Missed frame for sync-test: {} / {}", _sync_frame, _frame_counter);
259 _sync_frame = 0;
260 }
261 }
262
263 return true;
264}
265
266
269
271static uint32_t last_ack_frame;
272
277
280
281/***********
282 * Sending functions
283 ************/
284
287{
288 Debug(net, 9, "Client::SendJoin()");
289
290 Debug(net, 9, "Client::status = JOIN");
292 Debug(net, 9, "Client::join_status = AUTHORIZING");
293 _network_join_status = NETWORK_JOIN_STATUS_AUTHORIZING;
295
296 auto p = std::make_unique<Packet>(my_client, PACKET_CLIENT_JOIN);
297 p->Send_string(GetNetworkRevisionString());
298 p->Send_uint32(_openttd_newgrf_version);
299 my_client->SendPacket(std::move(p));
300
302}
303
304NetworkRecvStatus ClientNetworkGameSocketHandler::SendIdentify()
305{
306 Debug(net, 9, "Client::SendIdentify()");
307
308 auto p = std::make_unique<Packet>(my_client, PACKET_CLIENT_IDENTIFY);
309 p->Send_string(_settings_client.network.client_name); // Client name
310 p->Send_uint8(_network_join.company); // PlayAs
311 my_client->SendPacket(std::move(p));
313}
314
317{
318 Debug(net, 9, "Client::SendNewGRFsOk()");
319
320 auto p = std::make_unique<Packet>(my_client, PACKET_CLIENT_NEWGRFS_CHECKED);
321 my_client->SendPacket(std::move(p));
323}
324
330{
331 Debug(net, 9, "Client::SendAuthResponse()");
332
333 auto p = std::make_unique<Packet>(my_client, PACKET_CLIENT_AUTH_RESPONSE);
334 my_client->authentication_handler->SendResponse(*p);
335 my_client->SendPacket(std::move(p));
336
338}
339
342{
343 Debug(net, 9, "Client::SendGetMap()");
344
345 Debug(net, 9, "Client::status = MAP_WAIT");
347
348 auto p = std::make_unique<Packet>(my_client, PACKET_CLIENT_GETMAP);
349 my_client->SendPacket(std::move(p));
351}
352
355{
356 Debug(net, 9, "Client::SendMapOk()");
357
358 Debug(net, 9, "Client::status = ACTIVE");
360
361 auto p = std::make_unique<Packet>(my_client, PACKET_CLIENT_MAP_OK);
362 my_client->SendPacket(std::move(p));
364}
365
368{
369 Debug(net, 9, "Client::SendAck()");
370
371 auto p = std::make_unique<Packet>(my_client, PACKET_CLIENT_ACK);
372
373 p->Send_uint32(_frame_counter);
374 p->Send_uint8 (my_client->token);
375 my_client->SendPacket(std::move(p));
377}
378
384{
385 Debug(net, 9, "Client::SendCommand(): cmd={}", cp.cmd);
386
387 auto p = std::make_unique<Packet>(my_client, PACKET_CLIENT_COMMAND);
388 my_client->NetworkGameSocketHandler::SendCommand(*p, cp);
389
390 my_client->SendPacket(std::move(p));
392}
393
395NetworkRecvStatus ClientNetworkGameSocketHandler::SendChat(NetworkAction action, DestType type, int dest, std::string_view msg, int64_t data)
396{
397 Debug(net, 9, "Client::SendChat(): action={}, type={}, dest={}", action, type, dest);
398
399 auto p = std::make_unique<Packet>(my_client, PACKET_CLIENT_CHAT);
400
401 p->Send_uint8 (action);
402 p->Send_uint8 (type);
403 p->Send_uint32(dest);
404 p->Send_string(msg);
405 p->Send_uint64(data);
406
407 my_client->SendPacket(std::move(p));
409}
410
413{
414 Debug(net, 9, "Client::SendError(): errorno={}", errorno);
415
416 auto p = std::make_unique<Packet>(my_client, PACKET_CLIENT_ERROR);
417
418 p->Send_uint8(errorno);
419 my_client->SendPacket(std::move(p));
421}
422
428{
429 Debug(net, 9, "Client::SendSetName()");
430
431 auto p = std::make_unique<Packet>(my_client, PACKET_CLIENT_SET_NAME);
432
433 p->Send_string(name);
434 my_client->SendPacket(std::move(p));
436}
437
442{
443 Debug(net, 9, "Client::SendQuit()");
444
445 auto p = std::make_unique<Packet>(my_client, PACKET_CLIENT_QUIT);
446
447 my_client->SendPacket(std::move(p));
449}
450
456NetworkRecvStatus ClientNetworkGameSocketHandler::SendRCon(std::string_view pass, std::string_view command)
457{
458 Debug(net, 9, "Client::SendRCon()");
459
460 auto p = std::make_unique<Packet>(my_client, PACKET_CLIENT_RCON);
461 p->Send_string(pass);
462 p->Send_string(command);
463 my_client->SendPacket(std::move(p));
465}
466
472{
473 Debug(net, 9, "Client::SendMove(): company={}", company);
474
475 auto p = std::make_unique<Packet>(my_client, PACKET_CLIENT_MOVE);
476 p->Send_uint8(company);
477 my_client->SendPacket(std::move(p));
479}
480
489
490
491/***********
492 * Receiving functions
493 ************/
494
495extern bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, std::shared_ptr<struct LoadFilter> lf);
496
498{
499 Debug(net, 9, "Client::Receive_SERVER_FULL()");
500
501 /* We try to join a server which is full */
502 ShowErrorMessage(GetEncodedString(STR_NETWORK_ERROR_SERVER_FULL), {}, WL_CRITICAL);
503
505}
506
508{
509 Debug(net, 9, "Client::Receive_SERVER_BANNED()");
510
511 /* We try to join a server where we are banned */
512 ShowErrorMessage(GetEncodedString(STR_NETWORK_ERROR_SERVER_BANNED), {}, WL_CRITICAL);
513
515}
516
517/* This packet contains info about the client (playas and name)
518 * as client we save this in NetworkClientInfo, linked via 'client_id'
519 * which is always an unique number on a server. */
521{
524 CompanyID playas = (CompanyID)p.Recv_uint8();
525
526 Debug(net, 9, "Client::Receive_SERVER_CLIENT_INFO(): client_id={}, playas={}", client_id, playas);
527
528 std::string name = p.Recv_string(NETWORK_NAME_LENGTH);
529 std::string public_key = p.Recv_string(NETWORK_PUBLIC_KEY_LENGTH);
530
533 /* The server validates the name when receiving it from clients, so when it is wrong
534 * here something went really wrong. In the best case the packet got malformed on its
535 * way too us, in the worst case the server is broken or compromised. */
537
539 if (ci != nullptr) {
540 if (playas == ci->client_playas && name.compare(ci->client_name) != 0) {
541 /* Client name changed, display the change */
542 NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, name);
543 } else if (playas != ci->client_playas) {
544 /* The client changed from client-player..
545 * Do not display that for now */
546 }
547
548 /* Make sure we're in the company the server tells us to be in,
549 * for the rare case that we get moved while joining. */
551
552 ci->client_playas = playas;
553 ci->client_name = std::move(name);
554 ci->public_key = std::move(public_key);
555
557
559 }
560
561 /* There are at most as many ClientInfo as ClientSocket objects in a
562 * server. Having more info than a server can have means something
563 * has gone wrong somewhere, i.e. the server has more info than it
564 * has actual clients. That means the server is feeding us an invalid
565 * state. So, bail out! This server is broken. */
567
568 /* We don't have this client_id yet, find an empty client_id, and put the data there */
570 ci->client_playas = playas;
571 if (client_id == _network_own_client_id) this->SetInfo(ci);
572
573 ci->client_name = std::move(name);
574 ci->public_key = std::move(public_key);
575
577
579}
580
582{
583 static const StringID network_error_strings[] = {
584 STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_GENERAL
585 STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_DESYNC
586 STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_SAVEGAME_FAILED
587 STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_CONNECTION_LOST
588 STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_ILLEGAL_PACKET
589 STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_NEWGRF_MISMATCH
590 STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_NOT_AUTHORIZED
591 STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_NOT_EXPECTED
592 STR_NETWORK_ERROR_WRONG_REVISION, // NETWORK_ERROR_WRONG_REVISION
593 STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_NAME_IN_USE
594 STR_NETWORK_ERROR_WRONG_PASSWORD, // NETWORK_ERROR_WRONG_PASSWORD
595 STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_COMPANY_MISMATCH
596 STR_NETWORK_ERROR_KICKED, // NETWORK_ERROR_KICKED
597 STR_NETWORK_ERROR_CHEATER, // NETWORK_ERROR_CHEATER
598 STR_NETWORK_ERROR_SERVER_FULL, // NETWORK_ERROR_FULL
599 STR_NETWORK_ERROR_TOO_MANY_COMMANDS, // NETWORK_ERROR_TOO_MANY_COMMANDS
600 STR_NETWORK_ERROR_TIMEOUT_PASSWORD, // NETWORK_ERROR_TIMEOUT_PASSWORD
601 STR_NETWORK_ERROR_TIMEOUT_COMPUTER, // NETWORK_ERROR_TIMEOUT_COMPUTER
602 STR_NETWORK_ERROR_TIMEOUT_MAP, // NETWORK_ERROR_TIMEOUT_MAP
603 STR_NETWORK_ERROR_TIMEOUT_JOIN, // NETWORK_ERROR_TIMEOUT_JOIN
604 STR_NETWORK_ERROR_INVALID_CLIENT_NAME, // NETWORK_ERROR_INVALID_CLIENT_NAME
605 STR_NETWORK_ERROR_NOT_ON_ALLOW_LIST, // NETWORK_ERROR_NOT_ON_ALLOW_LIST
606 STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_NO_AUTHENTICATION_METHOD_AVAILABLE
607 };
608 static_assert(lengthof(network_error_strings) == NETWORK_ERROR_END);
609
611
612 Debug(net, 9, "Client::Receive_SERVER_ERROR(): error={}", error);
613
614 StringID err = STR_NETWORK_ERROR_LOSTCONNECTION;
615 if (error < (ptrdiff_t)lengthof(network_error_strings)) err = network_error_strings[error];
616 /* In case of kicking a client, we assume there is a kick message in the packet if we can read one byte */
617 if (error == NETWORK_ERROR_KICKED && p.CanReadFromPacket(1)) {
619 GetEncodedString(STR_NETWORK_ERROR_KICK_MESSAGE, p.Recv_string(NETWORK_CHAT_LENGTH)),
621 } else {
623 }
624
625 /* Perform an emergency save if we had already entered the game */
627
629}
630
632{
634
635 uint grf_count = p.Recv_uint8();
637
638 Debug(net, 9, "Client::Receive_SERVER_CHECK_NEWGRFS(): grf_count={}", grf_count);
639
640 /* Check all GRFs */
641 for (; grf_count > 0; grf_count--) {
643 DeserializeGRFIdentifier(p, c);
644
645 /* Check whether we know this GRF */
646 const GRFConfig *f = FindGRFConfig(c.grfid, FGCM_EXACT, &c.md5sum);
647 if (f == nullptr) {
648 /* We do not know this GRF, bail out of initialization */
649 Debug(grf, 0, "NewGRF {:08X} not found; checksum {}", std::byteswap(c.grfid), FormatArrayAsHex(c.md5sum));
651 }
652 }
653
654 if (ret == NETWORK_RECV_STATUS_OKAY) {
655 /* Start receiving the map */
656 return SendNewGRFsOk();
657 }
658
659 /* NewGRF mismatch, bail out */
660 ShowErrorMessage(GetEncodedString(STR_NETWORK_ERROR_NEWGRF_MISMATCH), {}, WL_CRITICAL);
661 return ret;
662}
663
665 virtual void SendResponse() override { MyClient::SendAuthResponse(); }
666 virtual void AskUserForPassword(std::shared_ptr<NetworkAuthenticationPasswordRequest> request) override
667 {
668 if (!_network_join.server_password.empty()) {
669 request->Reply(_network_join.server_password);
670 } else {
671 ShowNetworkNeedPassword(std::move(request));
672 }
673 }
674};
675
677{
679 Debug(net, 9, "Client::status = AUTH_GAME");
680 this->status = STATUS_AUTH_GAME;
681
682 Debug(net, 9, "Client::Receive_SERVER_AUTH_REQUEST()");
683
684 if (this->authentication_handler == nullptr) {
685 this->authentication_handler = NetworkAuthenticationClientHandler::Create(std::make_shared<ClientGamePasswordRequestHandler>(),
687 }
688 switch (this->authentication_handler->ReceiveRequest(p)) {
690 return SendAuthResponse();
691
694
696 default:
698 }
699}
700
702{
704
705 Debug(net, 9, "Client::Receive_SERVER_ENABLE_ENCRYPTION()");
706
707 if (!this->authentication_handler->ReceiveEnableEncryption(p)) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
708
709 this->receive_encryption_handler = this->authentication_handler->CreateServerToClientEncryptionHandler();
710 this->send_encryption_handler = this->authentication_handler->CreateClientToServerEncryptionHandler();
711 this->authentication_handler = nullptr;
712
713 Debug(net, 9, "Client::status = ENCRYPTED");
714 this->status = STATUS_ENCRYPTED;
715
716 return this->SendIdentify();
717}
718
720{
721 if (this->status < STATUS_ENCRYPTED || this->status >= STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
722 Debug(net, 9, "Client::status = AUTHORIZED");
724
726
727 Debug(net, 9, "Client::Receive_SERVER_WELCOME(): client_id={}", _network_own_client_id);
728
729 /* Start receiving the map */
730 return SendGetMap();
731}
732
734{
735 /* We set the internal wait state when requesting the map. */
737
738 Debug(net, 9, "Client::Receive_SERVER_WAIT()");
739
740 /* But... only now we set the join status to waiting, instead of requesting. */
741 Debug(net, 9, "Client::join_status = WAITING");
742 _network_join_status = NETWORK_JOIN_STATUS_WAITING;
745
747}
748
750{
751 if (this->status < STATUS_AUTHORIZED || this->status >= STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
752 Debug(net, 9, "Client::status = MAP");
753 this->status = STATUS_MAP;
754
755 if (this->savegame != nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
756
757 this->savegame = std::make_shared<PacketReader>();
758
760
761 Debug(net, 9, "Client::Receive_SERVER_MAP_BEGIN(): frame_counter={}", _frame_counter);
762
765
766 Debug(net, 9, "Client::join_status = DOWNLOADING");
767 _network_join_status = NETWORK_JOIN_STATUS_DOWNLOADING;
769
771}
772
785
787{
789 if (this->savegame == nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
790
791 /* We are still receiving data, put it to the file */
792 this->savegame->AddPacket(p);
793
794 _network_join_bytes = static_cast<uint32_t>(this->savegame->buffer.size());
796
798}
799
801{
803 if (this->savegame == nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
804
805 Debug(net, 9, "Client::Receive_SERVER_MAP_DONE()");
806
807 Debug(net, 9, "Client::join_status = PROCESSING");
808 _network_join_status = NETWORK_JOIN_STATUS_PROCESSING;
810
811 this->savegame->Reset();
812
813 /* The map is done downloading, load it */
815
816 /* Set the abstract filetype. This is read during savegame load. */
817 _file_to_saveload.SetMode(FIOS_TYPE_FILE, SLO_LOAD);
818
819 bool load_success = SafeLoad({}, SLO_LOAD, DFT_GAME_FILE, GM_NORMAL, NO_DIRECTORY, this->savegame);
820 this->savegame = nullptr;
821
822 /* Long savegame loads shouldn't affect the lag calculation! */
823 this->last_packet = std::chrono::steady_clock::now();
824
825 if (!load_success) {
826 ShowErrorMessage(GetEncodedString(STR_NETWORK_ERROR_SAVEGAMEERROR), {}, WL_CRITICAL);
828 }
829 /* If the savegame has successfully loaded, ALL windows have been removed,
830 * only toolbar/statusbar and gamefield are visible */
831
832 /* Say we received the map and loaded it correctly! */
833 SendMapOk();
834
835 /* As we skipped switch-mode, update the time we "switched". */
836 _game_session_stats.start_time = std::chrono::steady_clock::now();
837 _game_session_stats.savegame_size = std::nullopt;
838
839 ShowClientList();
840
841 /* New company/spectator (invalid company) or company we want to join is not active
842 * Switch local company to spectator and await the server's judgement */
845
847 /* We have arrived and ready to start playing; send a command to make a new company;
848 * the server will give us a client-id and let us in */
849 Debug(net, 9, "Client::join_status = REGISTERING");
850 _network_join_status = NETWORK_JOIN_STATUS_REGISTERING;
851 ShowJoinStatusWindow();
853 }
854 } else {
855 /* take control over an existing company */
857 }
858
860
862}
863
865{
867
870#ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
871 /* Test if the server supports this option
872 * and if we are at the frame the server is */
873#ifdef NETWORK_SEND_DOUBLE_SEED
874 if (p.CanReadFromPacket(sizeof(uint32_t) + sizeof(uint32_t))) {
875#else
876 if (p.CanReadFromPacket(sizeof(uint32_t))) {
877#endif
880#ifdef NETWORK_SEND_DOUBLE_SEED
881 _sync_seed_2 = p.Recv_uint32();
882#endif
883 }
884#endif
885 /* Receive the token. */
886 if (p.CanReadFromPacket(sizeof(uint8_t))) this->token = p.Recv_uint8();
887
888 /* Let the server know that we received this frame correctly
889 * We do this only once per day, to save some bandwidth ;) */
892 Debug(net, 7, "Sent ACK at {}", _frame_counter);
893 SendAck();
894 }
895
897}
898
900{
902
905#ifdef NETWORK_SEND_DOUBLE_SEED
906 _sync_seed_2 = p.Recv_uint32();
907#endif
908
909 Debug(net, 9, "Client::Receive_SERVER_SYNC(): sync_frame={}, sync_seed_1={}", _sync_frame, _sync_seed_1);
910
912}
913
915{
917
918 CommandPacket cp;
919 auto err = this->ReceiveCommand(p, cp);
920 cp.frame = p.Recv_uint32();
921 cp.my_cmd = p.Recv_bool();
922
923 Debug(net, 9, "Client::Receive_SERVER_COMMAND(): cmd={}, frame={}", cp.cmd, cp.frame);
924
925 if (err.has_value()) {
926 IConsolePrint(CC_WARNING, "Dropping server connection due to {}.", *err);
928 }
929
930 this->incoming_queue.push_back(std::move(cp));
931
933}
934
936{
938
939 std::string name;
940 const NetworkClientInfo *ci = nullptr, *ci_to;
941
944 bool self_send = p.Recv_bool();
945 std::string msg = p.Recv_string(NETWORK_CHAT_LENGTH);
946 int64_t data = p.Recv_uint64();
947
948 Debug(net, 9, "Client::Receive_SERVER_CHAT(): action={}, client_id={}, self_send={}", action, client_id, self_send);
949
951 if (ci_to == nullptr) return NETWORK_RECV_STATUS_OKAY;
952
953 /* Did we initiate the action locally? */
954 if (self_send) {
955 switch (action) {
956 case NETWORK_ACTION_CHAT_CLIENT:
957 /* For speaking to client we need the client-name */
958 name = ci_to->client_name;
960 break;
961
962 /* For speaking to company, we need the company-name */
963 case NETWORK_ACTION_CHAT_COMPANY: {
964 StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
965
966 name = GetString(str, ci_to->client_playas);
968 break;
969 }
970
972 }
973 } else {
974 /* Display message from somebody else */
975 name = ci_to->client_name;
976 ci = ci_to;
977 }
978
979 if (ci != nullptr) {
980 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), self_send, name, msg, data);
981 }
983}
984
986{
988
989 std::string source = p.Recv_string(NETWORK_CHAT_LENGTH);
990 TextColour colour = (TextColour)p.Recv_uint16();
991 std::string user = p.Recv_string(NETWORK_CHAT_LENGTH);
992 std::string msg = p.Recv_string(NETWORK_CHAT_LENGTH);
993
994 Debug(net, 9, "Client::Receive_SERVER_EXTERNAL_CHAT(): source={}", source);
995
997
998 NetworkTextMessage(NETWORK_ACTION_EXTERNAL_CHAT, colour, false, user, msg, source);
999
1001}
1002
1004{
1006
1008
1009 Debug(net, 9, "Client::Receive_SERVER_ERROR_QUIT(): client_id={}", client_id);
1010
1012 if (ci != nullptr) {
1013 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, "", GetNetworkErrorMsg((NetworkErrorCode)p.Recv_uint8()));
1014 delete ci;
1015 }
1016
1018
1020}
1021
1023{
1025
1027
1028 Debug(net, 9, "Client::Receive_SERVER_QUIT(): client_id={}", client_id);
1029
1031 if (ci != nullptr) {
1032 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, "", STR_NETWORK_MESSAGE_CLIENT_LEAVING);
1033 delete ci;
1034 } else {
1035 Debug(net, 1, "Unknown client ({}) is leaving the game", client_id);
1036 }
1037
1039
1040 /* If we come here it means we could not locate the client.. strange :s */
1042}
1043
1045{
1047
1049
1050 Debug(net, 9, "Client::Receive_SERVER_JOIN(): client_id={}", client_id);
1051
1053 if (ci != nullptr) {
1054 NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, ci->client_name);
1055 }
1056
1058
1060}
1061
1063{
1064 Debug(net, 9, "Client::Receive_SERVER_SHUTDOWN()");
1065
1066 /* Only when we're trying to join we really
1067 * care about the server shutting down. */
1068 if (this->status >= STATUS_JOIN) {
1069 ShowErrorMessage(GetEncodedString(STR_NETWORK_MESSAGE_SERVER_SHUTDOWN), {}, WL_CRITICAL);
1070 }
1071
1073
1075}
1076
1078{
1079 Debug(net, 9, "Client::Receive_SERVER_NEWGAME()");
1080
1081 /* Only when we're trying to join we really
1082 * care about the server shutting down. */
1083 if (this->status >= STATUS_JOIN) {
1084 /* To throttle the reconnects a bit, every clients waits its
1085 * Client ID modulo 16 + 1 (value 0 means no reconnect).
1086 * This way reconnects should be spread out a bit. */
1088 ShowErrorMessage(GetEncodedString(STR_NETWORK_MESSAGE_SERVER_REBOOT), {}, WL_CRITICAL);
1089 }
1090
1092
1094}
1095
1097{
1099
1100 Debug(net, 9, "Client::Receive_SERVER_RCON()");
1101
1102 TextColour colour_code = (TextColour)p.Recv_uint16();
1104
1105 std::string rcon_out = p.Recv_string(NETWORK_RCONCOMMAND_LENGTH);
1106
1107 IConsolePrint(colour_code, rcon_out);
1108
1110}
1111
1113{
1115
1116 /* Nothing more in this packet... */
1118 CompanyID company_id = (CompanyID)p.Recv_uint8();
1119
1120 Debug(net, 9, "Client::Receive_SERVER_MOVE(): client_id={}, comapny_id={}", client_id, company_id);
1121
1122 if (client_id == 0) {
1123 /* definitely an invalid client id, debug message and do nothing. */
1124 Debug(net, 1, "Received invalid client index = 0");
1126 }
1127
1129 /* Just make sure we do not try to use a client_index that does not exist */
1130 if (ci == nullptr) return NETWORK_RECV_STATUS_OKAY;
1131
1132 /* if not valid player, force spectator, else check player exists */
1133 if (!Company::IsValidID(company_id)) company_id = COMPANY_SPECTATOR;
1134
1136 SetLocalCompany(company_id);
1137 }
1138
1140}
1141
1143{
1145
1146 _network_server_max_companies = p.Recv_uint8();
1148
1150
1151 Debug(net, 9, "Client::Receive_SERVER_CONFIG_UPDATE(): max_companies={}", _network_server_max_companies);
1152
1154}
1155
1160{
1161 /* Only once we're authorized we can expect a steady stream of packets. */
1162 if (this->status < STATUS_AUTHORIZED) return;
1163
1164 /* 5 seconds are roughly twice the server's "you're slow" threshold (1 game day). */
1165 std::chrono::steady_clock::duration lag = std::chrono::steady_clock::now() - this->last_packet;
1166 if (lag < std::chrono::seconds(5)) return;
1167
1168 /* 20 seconds are (way) more than 4 game days after which
1169 * the server will forcefully disconnect you. */
1170 if (lag > std::chrono::seconds(20)) {
1172 return;
1173 }
1174
1175 /* Prevent showing the lag message every tick; just update it when needed. */
1176 static std::chrono::steady_clock::duration last_lag = {};
1177 if (std::chrono::duration_cast<std::chrono::seconds>(last_lag) == std::chrono::duration_cast<std::chrono::seconds>(lag)) return;
1178
1179 last_lag = lag;
1181 GetEncodedString(STR_NETWORK_ERROR_CLIENT_GUI_LOST_CONNECTION_CAPTION),
1182 GetEncodedString(STR_NETWORK_ERROR_CLIENT_GUI_LOST_CONNECTION, std::chrono::duration_cast<std::chrono::seconds>(lag).count()),
1183 WL_INFO);
1184}
1185
1186
1189{
1190 /* Set the frame-counter to 0 so nothing happens till we are ready */
1191 _frame_counter = 0;
1193 last_ack_frame = 0;
1194
1195 Debug(net, 9, "Client::NetworkClient_Connected()");
1196
1197 /* Request the game-info */
1199}
1200
1206void NetworkClientSendRcon(std::string_view password, std::string_view command)
1207{
1208 MyClient::SendRCon(password, command);
1209}
1210
1216{
1217 MyClient::SendMove(company_id);
1218}
1219
1225{
1227 /* If our company is changing owner, go to spectators */
1229
1231 if (ci->client_playas != cid) continue;
1232 NetworkTextMessage(NETWORK_ACTION_COMPANY_SPECTATOR, CC_DEFAULT, false, ci->client_name);
1233 ci->client_playas = COMPANY_SPECTATOR;
1234 }
1235
1236 cur_company.Restore();
1237}
1238
1246bool NetworkIsValidClientName(std::string_view client_name)
1247{
1248 if (client_name.empty()) return false;
1249 if (client_name[0] == ' ') return false;
1250 return true;
1251}
1252
1268bool NetworkValidateClientName(std::string &client_name)
1269{
1270 StrTrimInPlace(client_name);
1271 if (NetworkIsValidClientName(client_name)) return true;
1272
1273 ShowErrorMessage(GetEncodedString(STR_NETWORK_ERROR_BAD_PLAYER_NAME), {}, WL_ERROR);
1274 return false;
1275}
1276
1288
1293void NetworkUpdateClientName(const std::string &client_name)
1294{
1296 if (ci == nullptr) return;
1297
1298 /* Don't change the name if it is the same as the old name */
1299 if (client_name.compare(ci->client_name) != 0) {
1300 if (!_network_server) {
1301 MyClient::SendSetName(client_name);
1302 } else {
1303 /* Copy to a temporary buffer so no #n gets added after our name in the settings when there are duplicate names. */
1304 std::string temporary_name = client_name;
1305 if (NetworkMakeClientNameUnique(temporary_name)) {
1306 NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, temporary_name);
1307 ci->client_name = std::move(temporary_name);
1309 }
1310 }
1311 }
1312}
1313
1322void NetworkClientSendChat(NetworkAction action, DestType type, int dest, std::string_view msg, int64_t data)
1323{
1324 MyClient::SendChat(action, type, dest, msg, data);
1325}
1326
1333{
1334 /* Only companies actually playing can speak to team. Eg spectators cannot */
1336
1337 for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1338 if (ci->client_playas == cio->client_playas && ci != cio) return true;
1339 }
1340
1341 return false;
1342}
1343
1352
virtual void AskUserForPassword(std::shared_ptr< NetworkAuthenticationPasswordRequest > request) override
Callback to trigger asking the user for the password.
virtual void SendResponse() override
Callback to trigger sending the response for the password request.
Class for handling the client side of the game connection.
NetworkRecvStatus Receive_SERVER_QUIT(Packet &p) override
Notification that a client left the game: uint32_t ID of the client.
static NetworkRecvStatus SendChat(NetworkAction action, DestType type, int dest, std::string_view msg, int64_t data)
Send a chat-packet over the network.
static ClientNetworkGameSocketHandler * my_client
This is us!
static NetworkRecvStatus SendQuit()
Tell the server we would like to quit.
NetworkRecvStatus Receive_SERVER_SYNC(Packet &p) override
Sends a sync-check to the client: uint32_t Frame counter.
NetworkRecvStatus Receive_SERVER_ENABLE_ENCRYPTION(Packet &p) override
Indication to the client that authentication is complete and encryption has to be used from here on f...
NetworkRecvStatus Receive_SERVER_MAP_SIZE(Packet &p) override
Sends the size of the map to the client.
static bool Receive()
Check whether we received/can send some data from/to the server and when that's the case handle it ap...
NetworkRecvStatus Receive_SERVER_MAP_DONE(Packet &p) override
Sends that all data of the map are sent to the client:
NetworkRecvStatus Receive_SERVER_CLIENT_INFO(Packet &p) override
Send information about a client: uint32_t ID of the client (always unique on a server.
~ClientNetworkGameSocketHandler()
Clear whatever we assigned.
ServerStatus status
Status of the connection with the server.
NetworkRecvStatus Receive_SERVER_CHECK_NEWGRFS(Packet &p) override
Sends information about all used GRFs to the client: uint8_t Amount of GRFs (the following data is re...
static NetworkRecvStatus SendMove(CompanyID company)
Ask the server to move us.
NetworkRecvStatus Receive_SERVER_WAIT(Packet &p) override
Notification that another client is currently receiving the map: uint8_t Number of clients waiting in...
std::unique_ptr< class NetworkAuthenticationClientHandler > authentication_handler
The handler for the authentication.
std::shared_ptr< struct PacketReader > savegame
Packet reader for reading the savegame.
static bool IsConnected()
Check whether the client is actually connected (and in the game).
NetworkRecvStatus Receive_SERVER_EXTERNAL_CHAT(Packet &p) override
Sends a chat-packet for external source to the client: string Name of the source this message came fr...
uint8_t token
The token we need to send back to the server to prove we're the right client.
static NetworkRecvStatus SendSetName(const std::string &name)
Tell the server that we like to change the name of the client.
friend void NetworkExecuteLocalCommandQueue()
Execute all commands on the local command queue that ought to be executed this frame.
NetworkRecvStatus Receive_SERVER_ERROR_QUIT(Packet &p) override
Inform all clients that one client made an error and thus has quit/been disconnected: uint32_t ID of ...
static NetworkRecvStatus SendNewGRFsOk()
Tell the server we got all the NewGRFs.
static NetworkRecvStatus SendMapOk()
Tell the server we received the complete map.
void CheckConnection()
Check the connection's state, i.e.
ClientNetworkGameSocketHandler(SOCKET s, std::string_view connection_string)
Create a new socket for the client side of the game connection.
NetworkRecvStatus Receive_SERVER_RCON(Packet &p) override
Send the result of an issues RCon command back to the client: uint16_t Colour code.
NetworkRecvStatus Receive_SERVER_BANNED(Packet &p) override
Notification that the client trying to join is banned.
NetworkRecvStatus Receive_SERVER_CONFIG_UPDATE(Packet &p) override
Update the clients knowledge of the max settings: uint8_t Maximum number of companies allowed.
void ClientError(NetworkRecvStatus res)
Handle an error coming from the client side.
NetworkRecvStatus Receive_SERVER_WELCOME(Packet &p) override
The client is joined and ready to receive their map: uint32_t Own client ID.
static NetworkRecvStatus SendAck()
Send an acknowledgement from the server's ticks.
NetworkRecvStatus Receive_SERVER_MAP_BEGIN(Packet &p) override
Sends that the server will begin with sending the map to the client: uint32_t Current frame.
NetworkRecvStatus Receive_SERVER_JOIN(Packet &p) override
A client joined (PACKET_CLIENT_MAP_OK), what usually directly follows is a PACKET_SERVER_CLIENT_INFO:...
static NetworkRecvStatus SendAuthResponse()
Set the game password as requested.
static bool GameLoop()
Actual game loop for the client.
static void Send()
Send the packets of this socket handler.
@ STATUS_JOIN
We are trying to join a server.
@ STATUS_ENCRYPTED
The game authentication has completed and from here on the connection to the server is encrypted.
@ STATUS_MAP
The client is downloading the map.
@ STATUS_AUTH_GAME
Last action was requesting game (server) password.
@ STATUS_ACTIVE
The client is active within in the game.
@ STATUS_MAP_WAIT
The client is waiting as someone else is downloading the map.
@ STATUS_AUTHORIZED
The client is authorized at the server.
static NetworkRecvStatus SendRCon(std::string_view password, std::string_view command)
Send a console command.
NetworkRecvStatus Receive_SERVER_CHAT(Packet &p) override
Sends a chat-packet to the client: uint8_t ID of the action (see NetworkAction).
NetworkRecvStatus Receive_SERVER_MOVE(Packet &p) override
Move a client from one company into another: uint32_t ID of the client.
static NetworkRecvStatus SendCommand(const CommandPacket &cp)
Send a command to the server.
NetworkRecvStatus Receive_SERVER_FRAME(Packet &p) override
Sends the current frame counter to the client: uint32_t Frame counter uint32_t Frame counter max (how...
NetworkRecvStatus Receive_SERVER_COMMAND(Packet &p) override
Sends a DoCommand to the client: uint8_t ID of the company (0..MAX_COMPANIES-1).
NetworkRecvStatus Receive_SERVER_NEWGAME(Packet &p) override
Let the clients know that the server is loading a new map.
NetworkRecvStatus CloseConnection(NetworkRecvStatus status) override
Close the network connection due to the given status.
static NetworkRecvStatus SendGetMap()
Request the map from the server.
NetworkRecvStatus Receive_SERVER_AUTH_REQUEST(Packet &p) override
Indication to the client that it needs to authenticate: uint8_t The NetworkAuthenticationMethod to us...
NetworkRecvStatus Receive_SERVER_MAP_DATA(Packet &p) override
Sends the data of the map to the client: Contains a part of the map (until max size of packet).
NetworkRecvStatus Receive_SERVER_ERROR(Packet &p) override
The client made an error: uint8_t Error code caused (see NetworkErrorCode).
static NetworkRecvStatus SendError(NetworkErrorCode errorno)
Send an error-packet over the network.
NetworkRecvStatus Receive_SERVER_SHUTDOWN(Packet &p) override
Let the clients know that the server is closing.
static NetworkRecvStatus SendJoin()
Tell the server we would like to join.
NetworkRecvStatus Receive_SERVER_FULL(Packet &p) override
Notification that the server is full.
@ AwaitUserInput
We have requested some user input, but must wait on that.
@ Invalid
We have received an invalid request.
@ ReadyForResponse
We do not have to wait for user input, and can immediately respond to the server.
static std::unique_ptr< NetworkAuthenticationClientHandler > Create(std::shared_ptr< NetworkAuthenticationPasswordRequestHandler > password_handler, std::string &secret_key, std::string &public_key)
Create a NetworkAuthenticationClientHandler.
Callback interface for client implementations to provide the handling of the password requests.
Base socket handler for all TCP sockets.
Definition tcp_game.h:141
NetworkRecvStatus ReceivePackets()
Do the actual receiving of packets.
Definition tcp_game.cpp:131
NetworkClientInfo * GetInfo() const
Gets the client info of this socket handler.
Definition tcp_game.h:515
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:486
CommandQueue incoming_queue
The command-queue awaiting handling.
Definition tcp_game.h:489
std::chrono::steady_clock::time_point last_packet
Time we received the last frame.
Definition tcp_game.h:490
void SetInfo(NetworkClientInfo *info)
Sets the client info for this socket handler.
Definition tcp_game.h:505
NetworkRecvStatus CloseConnection(bool error=true) override
Functions to help ReceivePacket/SendPacket a bit A socket can make errors.
Definition tcp_game.cpp:40
void MarkClosed()
Mark the connection as closed.
Definition core.h:66
bool HasClientQuit() const
Whether the current client connected to the socket has quit.
Definition core.h:74
std::unique_ptr< class NetworkEncryptionHandler > send_encryption_handler
The handler for encrypting sent packets.
Definition core.h:50
std::unique_ptr< class NetworkEncryptionHandler > receive_encryption_handler
The handler for decrypting received packets.
Definition core.h:49
SOCKET sock
The socket currently connected to.
Definition tcp.h:38
virtual void SendPacket(std::unique_ptr< Packet > &&packet)
This function puts the packet in the send-queue and it is send as soon as possible.
Definition tcp.cpp:58
SendPacketsState SendPackets(bool closing_down=false)
Sends all the buffered packets out for this client.
Definition tcp.cpp:76
bool CanSendReceive()
Check whether this socket can send or receive something.
Definition tcp.cpp:194
static void EventEnterMultiplayer(uint map_width, uint map_height)
Event: user entered a multiplayer game.
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static Date date
Current date in days (day counter).
static DateFract date_fract
Fractional part of the day.
TextColour GetDrawStringCompanyColour(CompanyID company)
Get the colour for DrawString-subroutines which matches the colour of the company.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
void SetLocalCompany(CompanyID new_company)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
CompanyID _current_company
Company currently doing an action.
@ CCA_NEW
Create a new company.
static constexpr CompanyID COMPANY_SPECTATOR
The client is spectating.
static constexpr CompanyID COMPANY_NEW_COMPANY
The client wants a new company.
@ CRR_NONE
Dummy reason for actions that don't need one.
static const uint NETWORK_CHAT_LENGTH
The maximum length of a chat message, in bytes including '\0'.
Definition config.h:61
static const uint NETWORK_NAME_LENGTH
The maximum length of the server name and map name, in bytes including '\0'.
Definition config.h:53
static const uint NETWORK_PUBLIC_KEY_LENGTH
The maximum length of the hexadecimal encoded public keys, in bytes including '\0'.
Definition config.h:101
static const uint NETWORK_RCONCOMMAND_LENGTH
The maximum length of a rconsole command, in bytes including '\0'.
Definition config.h:59
void IConsolePrint(TextColour colour_code, const std::string &string)
Handle the printing of text entered into the console or redirected there by any other means.
Definition console.cpp:90
bool IsValidConsoleColour(TextColour c)
Check whether the given TextColour is valid for console usage.
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:23
@ NETWORK_RECV_STATUS_DESYNC
A desync did occur.
Definition core.h:25
@ NETWORK_RECV_STATUS_CLIENT_QUIT
The connection is lost gracefully. Other clients are already informed of this leaving client.
Definition core.h:28
@ NETWORK_RECV_STATUS_SERVER_ERROR
The server told us we made an error.
Definition core.h:30
@ NETWORK_RECV_STATUS_SAVEGAME
Something went wrong (down)loading the savegame.
Definition core.h:27
@ NETWORK_RECV_STATUS_CLOSE_QUERY
Done querying the server.
Definition core.h:33
@ NETWORK_RECV_STATUS_OKAY
Everything is okay.
Definition core.h:24
@ NETWORK_RECV_STATUS_NEWGRF_MISMATCH
We did not have the required NewGRFs.
Definition core.h:26
@ NETWORK_RECV_STATUS_SERVER_FULL
The server is full.
Definition core.h:31
@ NETWORK_RECV_STATUS_MALFORMED_PACKET
We apparently send a malformed packet.
Definition core.h:29
@ NETWORK_RECV_STATUS_SERVER_BANNED
The server has banned us.
Definition core.h:32
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
void ClearErrorMessages()
Clear all errors from the queue.
@ WL_ERROR
Errors (eg. saving/loading failed)
Definition error.h:26
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition error.h:27
@ WL_INFO
Used for DoCommand-like (and some non-fatal AI GUI) errors/information.
Definition error.h:24
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
SaveLoadOperation
Operation performed on the file.
Definition fileio_type.h:51
@ SLO_LOAD
File is being loaded.
Definition fileio_type.h:53
DetailedFileType
Kinds of files in each AbstractFileType.
Definition fileio_type.h:27
@ DFT_GAME_FILE
Save game or scenario file.
Definition fileio_type.h:30
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition fileio_type.h:87
@ NO_DIRECTORY
A path without any base directory.
GameSessionStats _game_session_stats
Statistics about the current session.
Definition gfx.cpp:51
SwitchMode _switch_mode
The next mainloop command.
Definition gfx.cpp:49
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
Definition gfx_type.h:302
static const uint MILLISECONDS_PER_TICK
The number of milliseconds per game tick.
Definition gfx_type.h:365
StringID GetNetworkErrorMsg(NetworkErrorCode err)
Retrieve the string id of an internal error number.
Definition network.cpp:311
uint32_t _frame_counter_server
The frame_counter of the server, if in network-mode.
Definition network.cpp:78
uint32_t _frame_counter
The current frame.
Definition network.cpp:80
uint8_t _network_reconnect
Reconnect timeout.
Definition network.cpp:74
bool _networking
are we in networking mode?
Definition network.cpp:67
bool _network_server
network-server is active
Definition network.cpp:68
uint32_t _sync_seed_1
Seed to compare during sync checks.
Definition network.cpp:83
uint32_t _sync_frame
The frame to perform the sync check.
Definition network.cpp:87
ClientID _network_own_client_id
Our client identifier.
Definition network.cpp:72
bool _network_first_time
Whether we have finished joining or not.
Definition network.cpp:88
uint32_t _frame_counter_max
To where we may go with our clients.
Definition network.cpp:79
Basic functions/variables used all over the place.
Base core network types and some helper functions to access them.
void NetworkUpdateClientName(const std::string &client_name)
Send the server our name as callback from the setting.
NetworkJoinInfo _network_join
Information about the game to join to.
bool NetworkValidateOurClientName()
Convenience method for NetworkValidateClientName on _settings_client.network.client_name.
void ClientNetworkEmergencySave()
Create an emergency savegame when the network connection is lost.
static uint32_t last_ack_frame
Last frame we performed an ack.
bool NetworkMaxCompaniesReached()
Check if max_companies has been reached on the server (local check only).
void NetworkClientSendRcon(std::string_view password, std::string_view command)
Send a remote console command.
uint NetworkMaxCompaniesAllowed()
Get the maximum number of companies that are allowed by the server.
void NetworkClientsToSpectators(CompanyID cid)
Move the clients of a company to the spectators.
static uint8_t _network_server_max_companies
Maximum number of companies of the currently joined server.
bool NetworkClientPreferTeamChat(const NetworkClientInfo *cio)
Tell whether the client has team members who they can chat to.
void NetworkClientSendChat(NetworkAction action, DestType type, int dest, std::string_view msg, int64_t data)
Send a chat message.
std::string _network_server_name
The current name of the server you are on.
void NetworkClientRequestMove(CompanyID company_id)
Notify the server of this client wanting to be moved to another company.
bool NetworkValidateClientName(std::string &client_name)
Trim the given client name in place, i.e.
bool NetworkIsValidClientName(std::string_view client_name)
Check whether the given client name is deemed valid for use in network games.
Client part of the network protocol.
NetworkJoinInfo _network_join
Information about the game to join to.
void NetworkClient_Connected()
Is called after a client is connected to the server.
void NetworkUpdateClientInfo(ClientID client_id)
Send updated client info of a particular client.
Handling of the list of games.
NetworkJoinStatus _network_join_status
The status of joining.
uint8_t _network_join_waiting
The number of clients waiting in front of us.
uint32_t _network_join_bytes_total
The total number of bytes to download.
uint32_t _network_join_bytes
The number of bytes we already downloaded.
GUIs related to networking.
bool NetworkMakeClientNameUnique(std::string &new_name)
Check whether a name is unique, and otherwise try to make it unique.
DestType
Destination of our chat messages.
NetworkErrorCode
The error codes we send around in the protocols.
NetworkAction
Actions that can be used for NetworkTextMessage.
ClientID
'Unique' identifier to be given to clients
@ CLIENT_ID_SERVER
Servers always have this ID.
const GRFConfig * FindGRFConfig(uint32_t grfid, FindGRFConfigMode mode, const MD5Hash *md5sum, uint32_t desired_version)
Find a NewGRF in the scanned list.
@ FGCM_EXACT
Only find Grfs matching md5sum.
void StateGameLoop()
State controlling game loop.
Definition openttd.cpp:1211
GameMode
Mode which defines the state of the game.
Definition openttd.h:18
@ SM_MENU
Switch to game intro menu.
Definition openttd.h:33
Randomizer _random
Random used in the game state calculations.
void DoAutoOrNetsave(FiosNumberedSaveName &counter)
Create an autosave or netsave.
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Definition saveload.cpp:66
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:59
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:271
std::string FormatArrayAsHex(std::span< const uint8_t > data)
Format a byte array into a continuous hex string.
Definition string.cpp:75
void StrTrimInPlace(std::string &str)
Trim the spaces from given string in place, i.e.
Definition string.cpp:226
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:91
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:415
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Class to backup a specific variable and restore it later.
void Restore()
Restore the variable.
NetworkSettings network
settings related to the network
GUISettings gui
settings related to the GUI
Everything we need to know about a command to be able to execute it.
uint32_t frame
the frame in which this packet is executed
bool my_cmd
did the command originate from "me"
Commands cmd
command being executed.
void SetMode(const FiosType &ft, SaveLoadOperation fop=SLO_LOAD)
Set the mode and file type of the file to save or load.
A savegame name automatically numbered.
Definition fios.h:129
Information about GRF, used in the game and (part of it) in savegames.
Basic data to distinguish a GRF.
uint32_t grfid
GRF ID (defined by Action 0x08)
MD5Hash md5sum
MD5 checksum of file to distinguish files with the same GRF ID (eg. newer version of GRF)
bool prefer_teamchat
choose the chat message target with <ENTER>, true=all clients, false=your team
std::chrono::steady_clock::time_point start_time
Time when the current game was started.
Definition openttd.h:56
std::optional< size_t > savegame_size
Size of the last saved savegame in bytes, or std::nullopt if not saved yet.
Definition openttd.h:58
Interface for filtering a savegame till it is loaded.
static uint SizeY()
Get the size of the map along the Y.
Definition map_func.h:278
static debug_inline uint SizeX()
Get the size of the map along the X.
Definition map_func.h:269
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:118
CompanyID client_playas
As which company is this client playing (CompanyID)
std::string client_name
Name of the client.
std::string public_key
The public key of the client.
Information required to join a server.
std::string server_password
The password of the server to join.
CompanyID company
The company to join.
std::string client_secret_key
The secret key of the client for authorized key logins.
uint8_t max_companies
maximum amount of companies
std::string client_name
name of the player (as client)
std::string client_public_key
The public key of the client for authorized key logins.
Read some packets, and when do use that data as initial load filter.
size_t Read(uint8_t *rbuf, size_t size) override
Read a given number of bytes from the savegame.
std::deque< uint8_t > Buffer
The underlying buffer type that's being use.
PacketReader()
Initialise everything.
size_t read_bytes
The total number of read bytes.
void AddPacket(Packet &p)
Add a packet to this buffer.
Buffer::const_iterator iterator
Buffer we're going to write to/read from.
void Reset() override
Reset this filter to read from the beginning of the file.
Buffer buffer
Buffer with the raw save game data.
Internal entity of a packet.
Definition packet.h:43
uint16_t Recv_uint16()
Read a 16 bits integer from the packet.
Definition packet.cpp:332
uint64_t Recv_uint64()
Read a 64 bits integer from the packet.
Definition packet.cpp:364
bool Recv_bool()
Read a boolean from the packet.
Definition packet.cpp:309
uint32_t Recv_uint32()
Read a 32 bits integer from the packet.
Definition packet.cpp:347
std::string Recv_string(size_t length, StringValidationSettings settings=StringValidationSetting::ReplaceWithQuestionMark)
Reads characters (bytes) from the packet until it finds a '\0', or reaches a maximum of length charac...
Definition packet.cpp:425
uint8_t Recv_uint8()
Read a 8 bits integer from the packet.
Definition packet.cpp:318
bool CanReadFromPacket(size_t bytes_to_read, bool close_connection=false)
Is it safe to read from the packet, i.e.
Definition packet.cpp:219
ssize_t TransferOut(F transfer_function)
Transfer data from the packet to the given function.
Definition packet.h:128
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
static size_t GetNumItems()
Returns number of valid items in the pool.
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
static bool IsValidID(auto index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
uint32_t state[2]
The state of the randomizer.
@ PACKET_CLIENT_IDENTIFY
Client telling the server the client's name and requested company.
Definition tcp_game.h:68
@ PACKET_CLIENT_GETMAP
Client requests the actual map.
Definition tcp_game.h:79
@ PACKET_CLIENT_ERROR
A client reports an error to the server.
Definition tcp_game.h:124
@ PACKET_CLIENT_JOIN
The client telling the server it wants to join.
Definition tcp_game.h:37
@ PACKET_CLIENT_AUTH_RESPONSE
The client responds to the authentication request.
Definition tcp_game.h:64
@ PACKET_CLIENT_NEWGRFS_CHECKED
Client acknowledges that it has all required NewGRFs.
Definition tcp_game.h:72
@ PACKET_CLIENT_COMMAND
Client executed a command and sends it to the server.
Definition tcp_game.h:101
@ PACKET_CLIENT_SET_NAME
A client changes its name.
Definition tcp_game.h:118
@ PACKET_CLIENT_ACK
The client tells the server which frame it has executed.
Definition tcp_game.h:97
@ PACKET_CLIENT_RCON
Client asks the server to execute some command.
Definition tcp_game.h:110
@ PACKET_CLIENT_MAP_OK
Client tells the server that it received the whole map.
Definition tcp_game.h:85
@ PACKET_CLIENT_QUIT
A client tells the server it is going to quit.
Definition tcp_game.h:122
@ PACKET_CLIENT_MOVE
A client would like to be moved to another company.
Definition tcp_game.h:114
@ PACKET_CLIENT_CHAT
Client said something that should be distributed.
Definition tcp_game.h:105
void CSleep(int milliseconds)
Sleep on the current thread for a defined time.
Definition thread.h:24
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Definition window.cpp:1182
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:3265
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition window.cpp:3147
@ WN_NETWORK_STATUS_WINDOW_JOIN
Network join status.
Definition window_type.h:41
@ WC_CLIENT_LIST
Client list; Window numbers:
@ WC_NETWORK_STATUS_WINDOW
Network status window; Window numbers: