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

OpenTTD Source 12.2

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 "../saveload/saveload.h"
13 #include "../saveload/saveload_filter.h"
14 #include "../command_func.h"
15 #include "../console_func.h"
16 #include "../strings_func.h"
17 #include "../window_func.h"
18 #include "../company_func.h"
19 #include "../company_base.h"
20 #include "../company_gui.h"
21 #include "../core/random_func.hpp"
22 #include "../date_func.h"
23 #include "../gfx_func.h"
24 #include "../error.h"
25 #include "../rev.h"
26 #include "network.h"
27 #include "network_base.h"
28 #include "network_client.h"
29 #include "network_gamelist.h"
30 #include "../core/backup_type.hpp"
31 #include "../thread.h"
32
33 #include "table/strings.h"
34
35 #include "../safeguards.h"
36
37 /* This file handles all the client-commands */
38
40 struct PacketReader : LoadFilter {
41 static const size_t CHUNK = 32 * 1024;
42
43 std::vector<byte *> blocks;
44 byte *buf;
45 byte *bufe;
46 byte **block;
47 size_t written_bytes;
48 size_t read_bytes;
49
51 PacketReader() : LoadFilter(nullptr), buf(nullptr), bufe(nullptr), block(nullptr), written_bytes(0), read_bytes(0)
52 {
53 }
54
55 ~PacketReader() override
56 {
57 for (auto p : this->blocks) {
58 free(p);
59 }
60 }
61
69 static inline ssize_t TransferOutMemCopy(PacketReader *destination, const char *source, size_t amount)
70 {
71 memcpy(destination->buf, source, amount);
72 destination->buf += amount;
73 destination->written_bytes += amount;
74 return amount;
75 }
76
81 void AddPacket(Packet *p)
82 {
83 assert(this->read_bytes == 0);
84 p->TransferOutWithLimit(TransferOutMemCopy, this->bufe - this->buf, this);
85
86 /* Did everything fit in the current chunk, then we're done. */
87 if (p->RemainingBytesToTransfer() == 0) return;
88
89 /* Allocate a new chunk and add the remaining data. */
90 this->blocks.push_back(this->buf = CallocT<byte>(CHUNK));
91 this->bufe = this->buf + CHUNK;
92
93 p->TransferOutWithLimit(TransferOutMemCopy, this->bufe - this->buf, this);
94 }
95
96 size_t Read(byte *rbuf, size_t size) override
97 {
98 /* Limit the amount to read to whatever we still have. */
99 size_t ret_size = size = std::min(this->written_bytes - this->read_bytes, size);
100 this->read_bytes += ret_size;
101 const byte *rbufe = rbuf + ret_size;
102
103 while (rbuf != rbufe) {
104 if (this->buf == this->bufe) {
105 this->buf = *this->block++;
106 this->bufe = this->buf + CHUNK;
107 }
108
109 size_t to_write = std::min(this->bufe - this->buf, rbufe - rbuf);
110 memcpy(rbuf, this->buf, to_write);
111 rbuf += to_write;
112 this->buf += to_write;
113 }
114
115 return ret_size;
116 }
117
118 void Reset() override
119 {
120 this->read_bytes = 0;
121
122 this->block = this->blocks.data();
123 this->buf = *this->block++;
124 this->bufe = this->buf + CHUNK;
125 }
126 };
127
128
132 void ClientNetworkEmergencySave()
133 {
134 static FiosNumberedSaveName _netsave_ctr("netsave");
135 DoAutoOrNetsave(_netsave_ctr);
136 }
137
138
143 ClientNetworkGameSocketHandler::ClientNetworkGameSocketHandler(SOCKET s, const std::string &connection_string) : NetworkGameSocketHandler(s), connection_string(connection_string), savegame(nullptr), status(STATUS_INACTIVE)
144 {
145 assert(ClientNetworkGameSocketHandler::my_client == nullptr);
146 ClientNetworkGameSocketHandler::my_client = this;
147 }
148
150 ClientNetworkGameSocketHandler::~ClientNetworkGameSocketHandler()
151 {
152 assert(ClientNetworkGameSocketHandler::my_client == this);
153 ClientNetworkGameSocketHandler::my_client = nullptr;
154
155 delete this->savegame;
156 delete this->GetInfo();
157 }
158
159 NetworkRecvStatus ClientNetworkGameSocketHandler::CloseConnection(NetworkRecvStatus status)
160 {
161 assert(status != NETWORK_RECV_STATUS_OKAY);
162 assert(this->sock != INVALID_SOCKET);
163
164 if (!this->HasClientQuit()) {
165 Debug(net, 3, "Closed client connection {}", this->client_id);
166
167 this->SendPackets(true);
168
169 /* Wait a number of ticks so our leave message can reach the server.
170 * This is especially needed for Windows servers as they seem to get
171 * the "socket is closed" message before receiving our leave message,
172 * which would trigger the server to close the connection as well. */
173 CSleep(3 * MILLISECONDS_PER_TICK);
174 }
175
176 delete this;
177
178 return status;
179 }
180
185 void ClientNetworkGameSocketHandler::ClientError(NetworkRecvStatus res)
186 {
187 /* First, send a CLIENT_ERROR to the server, so it knows we are
188 * disconnected (and why!) */
189 NetworkErrorCode errorno;
190
191 /* We just want to close the connection.. */
192 if (res == NETWORK_RECV_STATUS_CLOSE_QUERY) {
193 this->NetworkSocketHandler::MarkClosed();
194 this->CloseConnection(res);
195 _networking = false;
196
197 CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
198 return;
199 }
200
201 switch (res) {
202 case NETWORK_RECV_STATUS_DESYNC: errorno = NETWORK_ERROR_DESYNC; break;
203 case NETWORK_RECV_STATUS_SAVEGAME: errorno = NETWORK_ERROR_SAVEGAME_FAILED; break;
204 case NETWORK_RECV_STATUS_NEWGRF_MISMATCH: errorno = NETWORK_ERROR_NEWGRF_MISMATCH; break;
205 default: errorno = NETWORK_ERROR_GENERAL; break;
206 }
207
208 if (res == NETWORK_RECV_STATUS_SERVER_ERROR || res == NETWORK_RECV_STATUS_SERVER_FULL ||
209 res == NETWORK_RECV_STATUS_SERVER_BANNED) {
210 /* This means the server closed the connection. Emergency save is
211 * already created if this was appropriate during handling of the
212 * disconnect. */
213 this->CloseConnection(res);
214 } else {
215 /* This means we as client made a boo-boo. */
216 SendError(errorno);
217
218 /* Close connection before we make an emergency save, as the save can
219 * take a bit of time; better that the server doesn't stall while we
220 * are doing the save, and already disconnects us. */
221 this->CloseConnection(res);
222 ClientNetworkEmergencySave();
223 }
224
225 _switch_mode = SM_MENU;
226 _networking = false;
227 }
228
229
235 /* static */ bool ClientNetworkGameSocketHandler::Receive()
236 {
237 if (my_client->CanSendReceive()) {
238 NetworkRecvStatus res = my_client->ReceivePackets();
239 if (res != NETWORK_RECV_STATUS_OKAY) {
240 /* The client made an error of which we can not recover.
241 * Close the connection and drop back to the main menu. */
242 my_client->ClientError(res);
243 return false;
244 }
245 }
246 return _networking;
247 }
248
250 /* static */ void ClientNetworkGameSocketHandler::Send()
251 {
252 my_client->SendPackets();
253 if (my_client != nullptr) my_client->CheckConnection();
254 }
255
260 /* static */ bool ClientNetworkGameSocketHandler::GameLoop()
261 {
262 _frame_counter++;
263
264 NetworkExecuteLocalCommandQueue();
265
266 extern void StateGameLoop();
267 StateGameLoop();
268
269 /* Check if we are in sync! */
270 if (_sync_frame != 0) {
271 if (_sync_frame == _frame_counter) {
272 #ifdef NETWORK_SEND_DOUBLE_SEED
273 if (_sync_seed_1 != _random.state[0] || _sync_seed_2 != _random.state[1]) {
274 #else
275 if (_sync_seed_1 != _random.state[0]) {
276 #endif
277 ShowNetworkError(STR_NETWORK_ERROR_DESYNC);
278 Debug(desync, 1, "sync_err: {:08x}; {:02x}", _date, _date_fract);
279 Debug(net, 0, "Sync error detected");
280 my_client->ClientError(NETWORK_RECV_STATUS_DESYNC);
281 return false;
282 }
283
284 /* If this is the first time we have a sync-frame, we
285 * need to let the server know that we are ready and at the same
286 * frame as it is.. so we can start playing! */
287 if (_network_first_time) {
288 _network_first_time = false;
289 SendAck();
290 }
291
292 _sync_frame = 0;
293 } else if (_sync_frame < _frame_counter) {
294 Debug(net, 1, "Missed frame for sync-test: {} / {}", _sync_frame, _frame_counter);
295 _sync_frame = 0;
296 }
297 }
298
299 return true;
300 }
301
302
304 ClientNetworkGameSocketHandler * ClientNetworkGameSocketHandler::my_client = nullptr;
305
307 static uint32 last_ack_frame;
308
310 static uint32 _password_game_seed;
312 static std::string _password_server_id;
313
315 static uint8 _network_server_max_companies;
317 std::string _network_server_name;
318
320 NetworkJoinInfo _network_join;
321
323 static_assert(NETWORK_SERVER_ID_LENGTH == 16 * 2 + 1);
324
325 /***********
326 * Sending functions
327 * DEF_CLIENT_SEND_COMMAND has no parameters
328 ************/
329
331 NetworkRecvStatus ClientNetworkGameSocketHandler::SendJoin()
332 {
333 my_client->status = STATUS_JOIN;
334 _network_join_status = NETWORK_JOIN_STATUS_AUTHORIZING;
335 SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
336
337 Packet *p = new Packet(PACKET_CLIENT_JOIN);
338 p->Send_string(GetNetworkRevisionString());
339 p->Send_uint32(_openttd_newgrf_version);
340 p->Send_string(_settings_client.network.client_name); // Client name
341 p->Send_uint8 (_network_join.company); // PlayAs
342 p->Send_uint8 (0); // Used to be language
343 my_client->SendPacket(p);
344 return NETWORK_RECV_STATUS_OKAY;
345 }
346
348 NetworkRecvStatus ClientNetworkGameSocketHandler::SendNewGRFsOk()
349 {
350 Packet *p = new Packet(PACKET_CLIENT_NEWGRFS_CHECKED);
351 my_client->SendPacket(p);
352 return NETWORK_RECV_STATUS_OKAY;
353 }
354
359 NetworkRecvStatus ClientNetworkGameSocketHandler::SendGamePassword(const std::string &password)
360 {
361 Packet *p = new Packet(PACKET_CLIENT_GAME_PASSWORD);
362 p->Send_string(password);
363 my_client->SendPacket(p);
364 return NETWORK_RECV_STATUS_OKAY;
365 }
366
371 NetworkRecvStatus ClientNetworkGameSocketHandler::SendCompanyPassword(const std::string &password)
372 {
373 Packet *p = new Packet(PACKET_CLIENT_COMPANY_PASSWORD);
374 p->Send_string(GenerateCompanyPasswordHash(password, _password_server_id, _password_game_seed));
375 my_client->SendPacket(p);
376 return NETWORK_RECV_STATUS_OKAY;
377 }
378
380 NetworkRecvStatus ClientNetworkGameSocketHandler::SendGetMap()
381 {
382 my_client->status = STATUS_MAP_WAIT;
383
384 Packet *p = new Packet(PACKET_CLIENT_GETMAP);
385 my_client->SendPacket(p);
386 return NETWORK_RECV_STATUS_OKAY;
387 }
388
390 NetworkRecvStatus ClientNetworkGameSocketHandler::SendMapOk()
391 {
392 my_client->status = STATUS_ACTIVE;
393
394 Packet *p = new Packet(PACKET_CLIENT_MAP_OK);
395 my_client->SendPacket(p);
396 return NETWORK_RECV_STATUS_OKAY;
397 }
398
400 NetworkRecvStatus ClientNetworkGameSocketHandler::SendAck()
401 {
402 Packet *p = new Packet(PACKET_CLIENT_ACK);
403
404 p->Send_uint32(_frame_counter);
405 p->Send_uint8 (my_client->token);
406 my_client->SendPacket(p);
407 return NETWORK_RECV_STATUS_OKAY;
408 }
409
414 NetworkRecvStatus ClientNetworkGameSocketHandler::SendCommand(const CommandPacket *cp)
415 {
416 Packet *p = new Packet(PACKET_CLIENT_COMMAND);
417 my_client->NetworkGameSocketHandler::SendCommand(p, cp);
418
419 my_client->SendPacket(p);
420 return NETWORK_RECV_STATUS_OKAY;
421 }
422
424 NetworkRecvStatus ClientNetworkGameSocketHandler::SendChat(NetworkAction action, DestType type, int dest, const std::string &msg, int64 data)
425 {
426 Packet *p = new Packet(PACKET_CLIENT_CHAT);
427
428 p->Send_uint8 (action);
429 p->Send_uint8 (type);
430 p->Send_uint32(dest);
431 p->Send_string(msg);
432 p->Send_uint64(data);
433
434 my_client->SendPacket(p);
435 return NETWORK_RECV_STATUS_OKAY;
436 }
437
439 NetworkRecvStatus ClientNetworkGameSocketHandler::SendError(NetworkErrorCode errorno)
440 {
441 Packet *p = new Packet(PACKET_CLIENT_ERROR);
442
443 p->Send_uint8(errorno);
444 my_client->SendPacket(p);
445 return NETWORK_RECV_STATUS_OKAY;
446 }
447
452 NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetPassword(const std::string &password)
453 {
454 Packet *p = new Packet(PACKET_CLIENT_SET_PASSWORD);
455
456 p->Send_string(GenerateCompanyPasswordHash(password, _password_server_id, _password_game_seed));
457 my_client->SendPacket(p);
458 return NETWORK_RECV_STATUS_OKAY;
459 }
460
465 NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetName(const std::string &name)
466 {
467 Packet *p = new Packet(PACKET_CLIENT_SET_NAME);
468
469 p->Send_string(name);
470 my_client->SendPacket(p);
471 return NETWORK_RECV_STATUS_OKAY;
472 }
473
477 NetworkRecvStatus ClientNetworkGameSocketHandler::SendQuit()
478 {
479 Packet *p = new Packet(PACKET_CLIENT_QUIT);
480
481 my_client->SendPacket(p);
482 return NETWORK_RECV_STATUS_OKAY;
483 }
484
490 NetworkRecvStatus ClientNetworkGameSocketHandler::SendRCon(const std::string &pass, const std::string &command)
491 {
492 Packet *p = new Packet(PACKET_CLIENT_RCON);
493 p->Send_string(pass);
494 p->Send_string(command);
495 my_client->SendPacket(p);
496 return NETWORK_RECV_STATUS_OKAY;
497 }
498
504 NetworkRecvStatus ClientNetworkGameSocketHandler::SendMove(CompanyID company, const std::string &password)
505 {
506 Packet *p = new Packet(PACKET_CLIENT_MOVE);
507 p->Send_uint8(company);
508 p->Send_string(GenerateCompanyPasswordHash(password, _password_server_id, _password_game_seed));
509 my_client->SendPacket(p);
510 return NETWORK_RECV_STATUS_OKAY;
511 }
512
517 bool ClientNetworkGameSocketHandler::IsConnected()
518 {
519 return my_client != nullptr && my_client->status == STATUS_ACTIVE;
520 }
521
522
523 /***********
524 * Receiving functions
525 * DEF_CLIENT_RECEIVE_COMMAND has parameter: Packet *p
526 ************/
527
528 extern bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = nullptr);
529
530 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_FULL(Packet *p)
531 {
532 /* We try to join a server which is full */
533 ShowErrorMessage(STR_NETWORK_ERROR_SERVER_FULL, INVALID_STRING_ID, WL_CRITICAL);
534 CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
535
536 return NETWORK_RECV_STATUS_SERVER_FULL;
537 }
538
539 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_BANNED(Packet *p)
540 {
541 /* We try to join a server where we are banned */
542 ShowErrorMessage(STR_NETWORK_ERROR_SERVER_BANNED, INVALID_STRING_ID, WL_CRITICAL);
543 CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
544
545 return NETWORK_RECV_STATUS_SERVER_BANNED;
546 }
547
548 /* This packet contains info about the client (playas and name)
549 * as client we save this in NetworkClientInfo, linked via 'client_id'
550 * which is always an unique number on a server. */
551 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CLIENT_INFO(Packet *p)
552 {
553 NetworkClientInfo *ci;
554 ClientID client_id = (ClientID)p->Recv_uint32();
555 CompanyID playas = (CompanyID)p->Recv_uint8();
556
557 std::string name = p->Recv_string(NETWORK_NAME_LENGTH);
558
559 if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
560 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT;
561 /* The server validates the name when receiving it from clients, so when it is wrong
562 * here something went really wrong. In the best case the packet got malformed on its
563 * way too us, in the worst case the server is broken or compromised. */
564 if (!NetworkIsValidClientName(name)) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
565
566 ci = NetworkClientInfo::GetByClientID(client_id);
567 if (ci != nullptr) {
568 if (playas == ci->client_playas && name.compare(ci->client_name) != 0) {
569 /* Client name changed, display the change */
570 NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, name);
571 } else if (playas != ci->client_playas) {
572 /* The client changed from client-player..
573 * Do not display that for now */
574 }
575
576 /* Make sure we're in the company the server tells us to be in,
577 * for the rare case that we get moved while joining. */
578 if (client_id == _network_own_client_id) SetLocalCompany(!Company::IsValidID(playas) ? COMPANY_SPECTATOR : playas);
579
580 ci->client_playas = playas;
581 ci->client_name = name;
582
583 InvalidateWindowData(WC_CLIENT_LIST, 0);
584
585 return NETWORK_RECV_STATUS_OKAY;
586 }
587
588 /* There are at most as many ClientInfo as ClientSocket objects in a
589 * server. Having more info than a server can have means something
590 * has gone wrong somewhere, i.e. the server has more info than it
591 * has actual clients. That means the server is feeding us an invalid
592 * state. So, bail out! This server is broken. */
593 if (!NetworkClientInfo::CanAllocateItem()) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
594
595 /* We don't have this client_id yet, find an empty client_id, and put the data there */
596 ci = new NetworkClientInfo(client_id);
597 ci->client_playas = playas;
598 if (client_id == _network_own_client_id) this->SetInfo(ci);
599
600 ci->client_name = name;
601
602 InvalidateWindowData(WC_CLIENT_LIST, 0);
603
604 return NETWORK_RECV_STATUS_OKAY;
605 }
606
607 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR(Packet *p)
608 {
609 static const StringID network_error_strings[] = {
610 STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_GENERAL
611 STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_DESYNC
612 STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_SAVEGAME_FAILED
613 STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_CONNECTION_LOST
614 STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_ILLEGAL_PACKET
615 STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_NEWGRF_MISMATCH
616 STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_NOT_AUTHORIZED
617 STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_NOT_EXPECTED
618 STR_NETWORK_ERROR_WRONG_REVISION, // NETWORK_ERROR_WRONG_REVISION
619 STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_NAME_IN_USE
620 STR_NETWORK_ERROR_WRONG_PASSWORD, // NETWORK_ERROR_WRONG_PASSWORD
621 STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_COMPANY_MISMATCH
622 STR_NETWORK_ERROR_KICKED, // NETWORK_ERROR_KICKED
623 STR_NETWORK_ERROR_CHEATER, // NETWORK_ERROR_CHEATER
624 STR_NETWORK_ERROR_SERVER_FULL, // NETWORK_ERROR_FULL
625 STR_NETWORK_ERROR_TOO_MANY_COMMANDS, // NETWORK_ERROR_TOO_MANY_COMMANDS
626 STR_NETWORK_ERROR_TIMEOUT_PASSWORD, // NETWORK_ERROR_TIMEOUT_PASSWORD
627 STR_NETWORK_ERROR_TIMEOUT_COMPUTER, // NETWORK_ERROR_TIMEOUT_COMPUTER
628 STR_NETWORK_ERROR_TIMEOUT_MAP, // NETWORK_ERROR_TIMEOUT_MAP
629 STR_NETWORK_ERROR_TIMEOUT_JOIN, // NETWORK_ERROR_TIMEOUT_JOIN
630 STR_NETWORK_ERROR_INVALID_CLIENT_NAME, // NETWORK_ERROR_INVALID_CLIENT_NAME
631 };
632 static_assert(lengthof(network_error_strings) == NETWORK_ERROR_END);
633
634 NetworkErrorCode error = (NetworkErrorCode)p->Recv_uint8();
635
636 StringID err = STR_NETWORK_ERROR_LOSTCONNECTION;
637 if (error < (ptrdiff_t)lengthof(network_error_strings)) err = network_error_strings[error];
638 /* In case of kicking a client, we assume there is a kick message in the packet if we can read one byte */
639 if (error == NETWORK_ERROR_KICKED && p->CanReadFromPacket(1)) {
640 std::string kick_msg = p->Recv_string(NETWORK_CHAT_LENGTH);
641 SetDParamStr(0, kick_msg);
642 ShowErrorMessage(err, STR_NETWORK_ERROR_KICK_MESSAGE, WL_CRITICAL);
643 } else {
644 ShowErrorMessage(err, INVALID_STRING_ID, WL_CRITICAL);
645 }
646
647 /* Perform an emergency save if we had already entered the game */
648 if (this->status == STATUS_ACTIVE) ClientNetworkEmergencySave();
649
650 CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
651
652 return NETWORK_RECV_STATUS_SERVER_ERROR;
653 }
654
655 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHECK_NEWGRFS(Packet *p)
656 {
657 if (this->status != STATUS_JOIN) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
658
659 uint grf_count = p->Recv_uint8();
660 NetworkRecvStatus ret = NETWORK_RECV_STATUS_OKAY;
661
662 /* Check all GRFs */
663 for (; grf_count > 0; grf_count--) {
664 GRFIdentifier c;
665 DeserializeGRFIdentifier(p, &c);
666
667 /* Check whether we know this GRF */
668 const GRFConfig *f = FindGRFConfig(c.grfid, FGCM_EXACT, c.md5sum);
669 if (f == nullptr) {
670 /* We do not know this GRF, bail out of initialization */
671 char buf[sizeof(c.md5sum) * 2 + 1];
672 md5sumToString(buf, lastof(buf), c.md5sum);
673 Debug(grf, 0, "NewGRF {:08X} not found; checksum {}", BSWAP32(c.grfid), buf);
674 ret = NETWORK_RECV_STATUS_NEWGRF_MISMATCH;
675 }
676 }
677
678 if (ret == NETWORK_RECV_STATUS_OKAY) {
679 /* Start receiving the map */
680 return SendNewGRFsOk();
681 }
682
683 /* NewGRF mismatch, bail out */
684 ShowErrorMessage(STR_NETWORK_ERROR_NEWGRF_MISMATCH, INVALID_STRING_ID, WL_CRITICAL);
685 return ret;
686 }
687
688 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_NEED_GAME_PASSWORD(Packet *p)
689 {
690 if (this->status < STATUS_JOIN || this->status >= STATUS_AUTH_GAME) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
691 this->status = STATUS_AUTH_GAME;
692
693 if (!_network_join.server_password.empty()) {
694 return SendGamePassword(_network_join.server_password);
695 }
696
697 ShowNetworkNeedPassword(NETWORK_GAME_PASSWORD);
698
699 return NETWORK_RECV_STATUS_OKAY;
700 }
701
702 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_NEED_COMPANY_PASSWORD(Packet *p)
703 {
704 if (this->status < STATUS_JOIN || this->status >= STATUS_AUTH_COMPANY) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
705 this->status = STATUS_AUTH_COMPANY;
706
707 _password_game_seed = p->Recv_uint32();
708 _password_server_id = p->Recv_string(NETWORK_SERVER_ID_LENGTH);
709 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
710
711 if (!_network_join.company_password.empty()) {
712 return SendCompanyPassword(_network_join.company_password);
713 }
714
715 ShowNetworkNeedPassword(NETWORK_COMPANY_PASSWORD);
716
717 return NETWORK_RECV_STATUS_OKAY;
718 }
719
720 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_WELCOME(Packet *p)
721 {
722 if (this->status < STATUS_JOIN || this->status >= STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
723 this->status = STATUS_AUTHORIZED;
724
725 _network_own_client_id = (ClientID)p->Recv_uint32();
726
727 /* Initialize the password hash salting variables, even if they were previously. */
728 _password_game_seed = p->Recv_uint32();
729 _password_server_id = p->Recv_string(NETWORK_SERVER_ID_LENGTH);
730
731 /* Start receiving the map */
732 return SendGetMap();
733 }
734
735 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_WAIT(Packet *p)
736 {
737 /* We set the internal wait state when requesting the map. */
738 if (this->status != STATUS_MAP_WAIT) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
739
740 /* But... only now we set the join status to waiting, instead of requesting. */
741 _network_join_status = NETWORK_JOIN_STATUS_WAITING;
742 _network_join_waiting = p->Recv_uint8();
743 SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
744
745 return NETWORK_RECV_STATUS_OKAY;
746 }
747
748 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_BEGIN(Packet *p)
749 {
750 if (this->status < STATUS_AUTHORIZED || this->status >= STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
751 this->status = STATUS_MAP;
752
753 if (this->savegame != nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
754
755 this->savegame = new PacketReader();
756
757 _frame_counter = _frame_counter_server = _frame_counter_max = p->Recv_uint32();
758
759 _network_join_bytes = 0;
760 _network_join_bytes_total = 0;
761
762 _network_join_status = NETWORK_JOIN_STATUS_DOWNLOADING;
763 SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
764
765 return NETWORK_RECV_STATUS_OKAY;
766 }
767
768 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_SIZE(Packet *p)
769 {
770 if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
771 if (this->savegame == nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
772
773 _network_join_bytes_total = p->Recv_uint32();
774 SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
775
776 return NETWORK_RECV_STATUS_OKAY;
777 }
778
779 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DATA(Packet *p)
780 {
781 if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
782 if (this->savegame == nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
783
784 /* We are still receiving data, put it to the file */
785 this->savegame->AddPacket(p);
786
787 _network_join_bytes = (uint32)this->savegame->written_bytes;
788 SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
789
790 return NETWORK_RECV_STATUS_OKAY;
791 }
792
793 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DONE(Packet *p)
794 {
795 if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
796 if (this->savegame == nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
797
798 _network_join_status = NETWORK_JOIN_STATUS_PROCESSING;
799 SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
800
801 /*
802 * Make sure everything is set for reading.
803 *
804 * We need the local copy and reset this->savegame because when
805 * loading fails the network gets reset upon loading the intro
806 * game, which would cause us to free this->savegame twice.
807 */
808 LoadFilter *lf = this->savegame;
809 this->savegame = nullptr;
810 lf->Reset();
811
812 /* The map is done downloading, load it */
813 ClearErrorMessages();
814 bool load_success = SafeLoad({}, SLO_LOAD, DFT_GAME_FILE, GM_NORMAL, NO_DIRECTORY, lf);
815
816 /* Long savegame loads shouldn't affect the lag calculation! */
817 this->last_packet = std::chrono::steady_clock::now();
818
819 if (!load_success) {
820 CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
821 ShowErrorMessage(STR_NETWORK_ERROR_SAVEGAMEERROR, INVALID_STRING_ID, WL_CRITICAL);
822 return NETWORK_RECV_STATUS_SAVEGAME;
823 }
824 /* If the savegame has successfully loaded, ALL windows have been removed,
825 * only toolbar/statusbar and gamefield are visible */
826
827 /* Say we received the map and loaded it correctly! */
828 SendMapOk();
829
830 ShowClientList();
831
832 /* New company/spectator (invalid company) or company we want to join is not active
833 * Switch local company to spectator and await the server's judgement */
834 if (_network_join.company == COMPANY_NEW_COMPANY || !Company::IsValidID(_network_join.company)) {
835 SetLocalCompany(COMPANY_SPECTATOR);
836
837 if (_network_join.company != COMPANY_SPECTATOR) {
838 /* We have arrived and ready to start playing; send a command to make a new company;
839 * the server will give us a client-id and let us in */
840 _network_join_status = NETWORK_JOIN_STATUS_REGISTERING;
841 ShowJoinStatusWindow();
842 NetworkSendCommand(0, CCA_NEW, 0, CMD_COMPANY_CTRL, nullptr, {}, _local_company);
843 }
844 } else {
845 /* take control over an existing company */
846 SetLocalCompany(_network_join.company);
847 }
848
849 return NETWORK_RECV_STATUS_OKAY;
850 }
851
852 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_FRAME(Packet *p)
853 {
854 if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
855
856 _frame_counter_server = p->Recv_uint32();
857 _frame_counter_max = p->Recv_uint32();
858 #ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
859 /* Test if the server supports this option
860 * and if we are at the frame the server is */
861 #ifdef NETWORK_SEND_DOUBLE_SEED
862 if (p->CanReadFromPacket(sizeof(uint32) + sizeof(uint32))) {
863 #else
864 if (p->CanReadFromPacket(sizeof(uint32))) {
865 #endif
866 _sync_frame = _frame_counter_server;
867 _sync_seed_1 = p->Recv_uint32();
868 #ifdef NETWORK_SEND_DOUBLE_SEED
869 _sync_seed_2 = p->Recv_uint32();
870 #endif
871 }
872 #endif
873 /* Receive the token. */
874 if (p->CanReadFromPacket(sizeof(uint8))) this->token = p->Recv_uint8();
875
876 Debug(net, 7, "Received FRAME {}", _frame_counter_server);
877
878 /* Let the server know that we received this frame correctly
879 * We do this only once per day, to save some bandwidth ;) */
880 if (!_network_first_time && last_ack_frame < _frame_counter) {
881 last_ack_frame = _frame_counter + DAY_TICKS;
882 Debug(net, 7, "Sent ACK at {}", _frame_counter);
883 SendAck();
884 }
885
886 return NETWORK_RECV_STATUS_OKAY;
887 }
888
889 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_SYNC(Packet *p)
890 {
891 if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
892
893 _sync_frame = p->Recv_uint32();
894 _sync_seed_1 = p->Recv_uint32();
895 #ifdef NETWORK_SEND_DOUBLE_SEED
896 _sync_seed_2 = p->Recv_uint32();
897 #endif
898
899 return NETWORK_RECV_STATUS_OKAY;
900 }
901
902 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_COMMAND(Packet *p)
903 {
904 if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
905
906 CommandPacket cp;
907 const char *err = this->ReceiveCommand(p, &cp);
908 cp.frame = p->Recv_uint32();
909 cp.my_cmd = p->Recv_bool();
910
911 if (err != nullptr) {
912 IConsolePrint(CC_WARNING, "Dropping server connection due to {}.", err);
913 return NETWORK_RECV_STATUS_MALFORMED_PACKET;
914 }
915
916 this->incoming_queue.Append(&cp);
917
918 return NETWORK_RECV_STATUS_OKAY;
919 }
920
921 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHAT(Packet *p)
922 {
923 if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
924
925 std::string name;
926 const NetworkClientInfo *ci = nullptr, *ci_to;
927
928 NetworkAction action = (NetworkAction)p->Recv_uint8();
929 ClientID client_id = (ClientID)p->Recv_uint32();
930 bool self_send = p->Recv_bool();
931 std::string msg = p->Recv_string(NETWORK_CHAT_LENGTH);
932 int64 data = p->Recv_uint64();
933
934 ci_to = NetworkClientInfo::GetByClientID(client_id);
935 if (ci_to == nullptr) return NETWORK_RECV_STATUS_OKAY;
936
937 /* Did we initiate the action locally? */
938 if (self_send) {
939 switch (action) {
940 case NETWORK_ACTION_CHAT_CLIENT:
941 /* For speaking to client we need the client-name */
942 name = ci_to->client_name;
943 ci = NetworkClientInfo::GetByClientID(_network_own_client_id);
944 break;
945
946 /* For speaking to company, we need the company-name */
947 case NETWORK_ACTION_CHAT_COMPANY: {
948 StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
949 SetDParam(0, ci_to->client_playas);
950
951 name = GetString(str);
952 ci = NetworkClientInfo::GetByClientID(_network_own_client_id);
953 break;
954 }
955
956 default: return NETWORK_RECV_STATUS_MALFORMED_PACKET;
957 }
958 } else {
959 /* Display message from somebody else */
960 name = ci_to->client_name;
961 ci = ci_to;
962 }
963
964 if (ci != nullptr) {
965 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), self_send, name, msg, data);
966 }
967 return NETWORK_RECV_STATUS_OKAY;
968 }
969
970 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_EXTERNAL_CHAT(Packet *p)
971 {
972 if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
973
974 std::string source = p->Recv_string(NETWORK_CHAT_LENGTH);
975 TextColour colour = (TextColour)p->Recv_uint16();
976 std::string user = p->Recv_string(NETWORK_CHAT_LENGTH);
977 std::string msg = p->Recv_string(NETWORK_CHAT_LENGTH);
978
979 if (!IsValidConsoleColour(colour)) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
980
981 NetworkTextMessage(NETWORK_ACTION_EXTERNAL_CHAT, colour, false, user, msg, 0, source);
982
983 return NETWORK_RECV_STATUS_OKAY;
984 }
985
986 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR_QUIT(Packet *p)
987 {
988 if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
989
990 ClientID client_id = (ClientID)p->Recv_uint32();
991
992 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
993 if (ci != nullptr) {
994 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, "", GetNetworkErrorMsg((NetworkErrorCode)p->Recv_uint8()));
995 delete ci;
996 }
997
998 InvalidateWindowData(WC_CLIENT_LIST, 0);
999
1000 return NETWORK_RECV_STATUS_OKAY;
1001 }
1002
1003 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_QUIT(Packet *p)
1004 {
1005 if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
1006
1007 ClientID client_id = (ClientID)p->Recv_uint32();
1008
1009 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1010 if (ci != nullptr) {
1011 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, "", STR_NETWORK_MESSAGE_CLIENT_LEAVING);
1012 delete ci;
1013 } else {
1014 Debug(net, 1, "Unknown client ({}) is leaving the game", client_id);
1015 }
1016
1017 InvalidateWindowData(WC_CLIENT_LIST, 0);
1018
1019 /* If we come here it means we could not locate the client.. strange :s */
1020 return NETWORK_RECV_STATUS_OKAY;
1021 }
1022
1023 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_JOIN(Packet *p)
1024 {
1025 if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
1026
1027 ClientID client_id = (ClientID)p->Recv_uint32();
1028
1029 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1030 if (ci != nullptr) {
1031 NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, ci->client_name);
1032 }
1033
1034 InvalidateWindowData(WC_CLIENT_LIST, 0);
1035
1036 return NETWORK_RECV_STATUS_OKAY;
1037 }
1038
1039 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_SHUTDOWN(Packet *p)
1040 {
1041 /* Only when we're trying to join we really
1042 * care about the server shutting down. */
1043 if (this->status >= STATUS_JOIN) {
1044 ShowErrorMessage(STR_NETWORK_MESSAGE_SERVER_SHUTDOWN, INVALID_STRING_ID, WL_CRITICAL);
1045 }
1046
1047 if (this->status == STATUS_ACTIVE) ClientNetworkEmergencySave();
1048
1049 return NETWORK_RECV_STATUS_SERVER_ERROR;
1050 }
1051
1052 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_NEWGAME(Packet *p)
1053 {
1054 /* Only when we're trying to join we really
1055 * care about the server shutting down. */
1056 if (this->status >= STATUS_JOIN) {
1057 /* To throttle the reconnects a bit, every clients waits its
1058 * Client ID modulo 16 + 1 (value 0 means no reconnect).
1059 * This way reconnects should be spread out a bit. */
1060 _network_reconnect = _network_own_client_id % 16 + 1;
1061 ShowErrorMessage(STR_NETWORK_MESSAGE_SERVER_REBOOT, INVALID_STRING_ID, WL_CRITICAL);
1062 }
1063
1064 if (this->status == STATUS_ACTIVE) ClientNetworkEmergencySave();
1065
1066 return NETWORK_RECV_STATUS_SERVER_ERROR;
1067 }
1068
1069 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_RCON(Packet *p)
1070 {
1071 if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
1072
1073 TextColour colour_code = (TextColour)p->Recv_uint16();
1074 if (!IsValidConsoleColour(colour_code)) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
1075
1076 std::string rcon_out = p->Recv_string(NETWORK_RCONCOMMAND_LENGTH);
1077
1078 IConsolePrint(colour_code, rcon_out);
1079
1080 return NETWORK_RECV_STATUS_OKAY;
1081 }
1082
1083 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MOVE(Packet *p)
1084 {
1085 if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
1086
1087 /* Nothing more in this packet... */
1088 ClientID client_id = (ClientID)p->Recv_uint32();
1089 CompanyID company_id = (CompanyID)p->Recv_uint8();
1090
1091 if (client_id == 0) {
1092 /* definitely an invalid client id, debug message and do nothing. */
1093 Debug(net, 1, "Received invalid client index = 0");
1094 return NETWORK_RECV_STATUS_MALFORMED_PACKET;
1095 }
1096
1097 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1098 /* Just make sure we do not try to use a client_index that does not exist */
1099 if (ci == nullptr) return NETWORK_RECV_STATUS_OKAY;
1100
1101 /* if not valid player, force spectator, else check player exists */
1102 if (!Company::IsValidID(company_id)) company_id = COMPANY_SPECTATOR;
1103
1104 if (client_id == _network_own_client_id) {
1105 SetLocalCompany(company_id);
1106 }
1107
1108 return NETWORK_RECV_STATUS_OKAY;
1109 }
1110
1111 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CONFIG_UPDATE(Packet *p)
1112 {
1113 if (this->status < STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
1114
1115 _network_server_max_companies = p->Recv_uint8();
1116 _network_server_name = p->Recv_string(NETWORK_NAME_LENGTH);
1117
1118 return NETWORK_RECV_STATUS_OKAY;
1119 }
1120
1121 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_COMPANY_UPDATE(Packet *p)
1122 {
1123 if (this->status < STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
1124
1125 _network_company_passworded = p->Recv_uint16();
1126 SetWindowClassesDirty(WC_COMPANY);
1127
1128 return NETWORK_RECV_STATUS_OKAY;
1129 }
1130
1134 void ClientNetworkGameSocketHandler::CheckConnection()
1135 {
1136 /* Only once we're authorized we can expect a steady stream of packets. */
1137 if (this->status < STATUS_AUTHORIZED) return;
1138
1139 /* 5 seconds are roughly twice the server's "you're slow" threshold (1 game day). */
1140 std::chrono::steady_clock::duration lag = std::chrono::steady_clock::now() - this->last_packet;
1141 if (lag < std::chrono::seconds(5)) return;
1142
1143 /* 20 seconds are (way) more than 4 game days after which
1144 * the server will forcefully disconnect you. */
1145 if (lag > std::chrono::seconds(20)) {
1146 this->NetworkGameSocketHandler::CloseConnection();
1147 return;
1148 }
1149
1150 /* Prevent showing the lag message every tick; just update it when needed. */
1151 static std::chrono::steady_clock::duration last_lag = {};
1152 if (std::chrono::duration_cast<std::chrono::seconds>(last_lag) == std::chrono::duration_cast<std::chrono::seconds>(lag)) return;
1153
1154 last_lag = lag;
1155 SetDParam(0, std::chrono::duration_cast<std::chrono::seconds>(lag).count());
1156 ShowErrorMessage(STR_NETWORK_ERROR_CLIENT_GUI_LOST_CONNECTION_CAPTION, STR_NETWORK_ERROR_CLIENT_GUI_LOST_CONNECTION, WL_INFO);
1157 }
1158
1159
1161 void NetworkClient_Connected()
1162 {
1163 /* Set the frame-counter to 0 so nothing happens till we are ready */
1164 _frame_counter = 0;
1165 _frame_counter_server = 0;
1166 last_ack_frame = 0;
1167 /* Request the game-info */
1168 MyClient::SendJoin();
1169 }
1170
1176 void NetworkClientSendRcon(const std::string &password, const std::string &command)
1177 {
1178 MyClient::SendRCon(password, command);
1179 }
1180
1187 void NetworkClientRequestMove(CompanyID company_id, const std::string &pass)
1188 {
1189 MyClient::SendMove(company_id, pass);
1190 }
1191
1196 void NetworkClientsToSpectators(CompanyID cid)
1197 {
1198 Backup<CompanyID> cur_company(_current_company, FILE_LINE);
1199 /* If our company is changing owner, go to spectators */
1200 if (cid == _local_company) SetLocalCompany(COMPANY_SPECTATOR);
1201
1202 for (NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1203 if (ci->client_playas != cid) continue;
1204 NetworkTextMessage(NETWORK_ACTION_COMPANY_SPECTATOR, CC_DEFAULT, false, ci->client_name);
1205 ci->client_playas = COMPANY_SPECTATOR;
1206 }
1207
1208 cur_company.Restore();
1209 }
1210
1218 bool NetworkIsValidClientName(const std::string_view client_name)
1219 {
1220 if (client_name.empty()) return false;
1221 if (client_name[0] == ' ') return false;
1222 return true;
1223 }
1224
1240 bool NetworkValidateClientName(std::string &client_name)
1241 {
1242 StrTrimInPlace(client_name);
1243 if (NetworkIsValidClientName(client_name)) return true;
1244
1245 ShowErrorMessage(STR_NETWORK_ERROR_BAD_PLAYER_NAME, INVALID_STRING_ID, WL_ERROR);
1246 return false;
1247 }
1248
1256 bool NetworkValidateOurClientName()
1257 {
1258 return NetworkValidateClientName(_settings_client.network.client_name);
1259 }
1260
1265 void NetworkUpdateClientName(const std::string &client_name)
1266 {
1267 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(_network_own_client_id);
1268 if (ci == nullptr) return;
1269
1270 /* Don't change the name if it is the same as the old name */
1271 if (client_name.compare(ci->client_name) != 0) {
1272 if (!_network_server) {
1273 MyClient::SendSetName(client_name);
1274 } else {
1275 /* Copy to a temporary buffer so no #n gets added after our name in the settings when there are duplicate names. */
1276 std::string temporary_name = client_name;
1277 if (NetworkMakeClientNameUnique(temporary_name)) {
1278 NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, temporary_name);
1279 ci->client_name = temporary_name;
1280 NetworkUpdateClientInfo(CLIENT_ID_SERVER);
1281 }
1282 }
1283 }
1284 }
1285
1294 void NetworkClientSendChat(NetworkAction action, DestType type, int dest, const std::string &msg, int64 data)
1295 {
1296 MyClient::SendChat(action, type, dest, msg, data);
1297 }
1298
1303 void NetworkClientSetCompanyPassword(const std::string &password)
1304 {
1305 MyClient::SendSetPassword(password);
1306 }
1307
1313 bool NetworkClientPreferTeamChat(const NetworkClientInfo *cio)
1314 {
1315 /* Only companies actually playing can speak to team. Eg spectators cannot */
1316 if (!_settings_client.gui.prefer_teamchat || !Company::IsValidID(cio->client_playas)) return false;
1317
1318 for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1319 if (ci->client_playas == cio->client_playas && ci != cio) return true;
1320 }
1321
1322 return false;
1323 }
1324
1329 bool NetworkMaxCompaniesReached()
1330 {
1331 return Company::GetNumItems() >= (_network_server ? _settings_client.network.max_companies : _network_server_max_companies);
1332 }
NetworkClientSendRcon
void NetworkClientSendRcon(const std::string &password, const std::string &command)
Send a remote console command.
Definition: network_client.cpp:1176
ClientNetworkGameSocketHandler::Receive_SERVER_FRAME
NetworkRecvStatus Receive_SERVER_FRAME(Packet *p) override
Sends the current frame counter to the client: uint32 Frame counter uint32 Frame counter max (how far...
Definition: network_client.cpp:852
PacketReader::AddPacket
void AddPacket(Packet *p)
Add a packet to this buffer.
Definition: network_client.cpp:81
_network_join_bytes_total
uint32 _network_join_bytes_total
The total number of bytes to download.
Definition: network_gui.cpp:2136
DestType
DestType
Destination of our chat messages.
Definition: network_type.h:89
ClientNetworkGameSocketHandler::SendNewGRFsOk
static NetworkRecvStatus SendNewGRFsOk()
Tell the server we got all the NewGRFs.
Definition: network_client.cpp:348
InvalidateWindowData
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition: window.cpp:3234
ClientNetworkGameSocketHandler::Receive_SERVER_CHAT
NetworkRecvStatus Receive_SERVER_CHAT(Packet *p) override
Sends a chat-packet to the client: uint8 ID of the action (see NetworkAction).
Definition: network_client.cpp:921
NETWORK_RECV_STATUS_CLIENT_QUIT
@ NETWORK_RECV_STATUS_CLIENT_QUIT
The connection is lost gracefully. Other clients are already informed of this leaving client.
Definition: core.h:27
_frame_counter
uint32 _frame_counter
The current frame.
Definition: network.cpp:71
PACKET_CLIENT_ERROR
@ PACKET_CLIENT_ERROR
A client reports an error to the server.
Definition: tcp_game.h:125
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3136
NetworkValidateOurClientName
bool NetworkValidateOurClientName()
Convenience method for NetworkValidateClientName on _settings_client.network.client_name.
Definition: network_client.cpp:1256
FindGRFConfig
const GRFConfig * FindGRFConfig(uint32 grfid, FindGRFConfigMode mode, const uint8 *md5sum, uint32 desired_version)
Find a NewGRF in the scanned list.
Definition: newgrf_config.cpp:736
NetworkGameSocketHandler::ReceivePackets
NetworkRecvStatus ReceivePackets()
Do the actual receiving of packets.
Definition: tcp_game.cpp:134
CSleep
void CSleep(int milliseconds)
Sleep on the current thread for a defined time.
Definition: thread.h:23
NetworkValidateClientName
bool NetworkValidateClientName(std::string &client_name)
Trim the given client name in place, i.e.
Definition: network_client.cpp:1240
NETWORK_RECV_STATUS_DESYNC
@ NETWORK_RECV_STATUS_DESYNC
A desync did occur.
Definition: core.h:24
ClientNetworkGameSocketHandler::STATUS_AUTH_COMPANY
@ STATUS_AUTH_COMPANY
Last action was requesting company password.
Definition: network_client.h:28
NetworkClientInfo::client_name
std::string client_name
Name of the client.
Definition: network_base.h:26
_password_game_seed
static uint32 _password_game_seed
One bit of 'entropy' used to generate a salt for the company passwords.
Definition: network_client.cpp:310
_network_join_waiting
uint8 _network_join_waiting
The number of clients waiting in front of us.
Definition: network_gui.cpp:2134
NetworkJoinInfo::company_password
std::string company_password
The password of the company to join.
Definition: network_client.h:116
Backup
Class to backup a specific variable and restore it later.
Definition: backup_type.hpp:21
ClientNetworkGameSocketHandler::Receive_SERVER_BANNED
NetworkRecvStatus Receive_SERVER_BANNED(Packet *p) override
Notification that the client trying to join is banned.
Definition: network_client.cpp:539
NETWORK_NAME_LENGTH
static const uint NETWORK_NAME_LENGTH
The maximum length of the server name and map name, in bytes including '\0'.
Definition: config.h:55
NetworkClientInfo::client_playas
CompanyID client_playas
As which company is this client playing (CompanyID)
Definition: network_base.h:27
ClientNetworkEmergencySave
void ClientNetworkEmergencySave()
Create an emergency savegame when the network connection is lost.
Definition: network_client.cpp:132
_date_fract
DateFract _date_fract
Fractional part of the day.
Definition: date.cpp:29
NetworkClientRequestMove
void NetworkClientRequestMove(CompanyID company_id, const std::string &pass)
Notify the server of this client wanting to be moved to another company.
Definition: network_client.cpp:1187
_network_server
bool _network_server
network-server is active
Definition: network.cpp:58
SaveLoadOperation
SaveLoadOperation
Operation performed on the file.
Definition: fileio_type.h:47
ClientNetworkGameSocketHandler::ClientNetworkGameSocketHandler
ClientNetworkGameSocketHandler(SOCKET s, const std::string &connection_string)
Create a new socket for the client side of the game connection.
Definition: network_client.cpp:143
_network_company_passworded
CompanyMask _network_company_passworded
Bitmask of the password status of all companies.
Definition: network.cpp:80
NetworkAction
NetworkAction
Actions that can be used for NetworkTextMessage.
Definition: network_type.h:99
NetworkClientPreferTeamChat
bool NetworkClientPreferTeamChat(const NetworkClientInfo *cio)
Tell whether the client has team members who they can chat to.
Definition: network_client.cpp:1313
CommandPacket::frame
uint32 frame
the frame in which this packet is executed
Definition: network_internal.h:112
NetworkGameSocketHandler::last_packet
std::chrono::steady_clock::time_point last_packet
Time we received the last frame.
Definition: tcp_game.h:516
WC_CLIENT_LIST
@ WC_CLIENT_LIST
Client list; Window numbers:
Definition: window_type.h:470
ClientNetworkGameSocketHandler::Receive_SERVER_COMPANY_UPDATE
NetworkRecvStatus Receive_SERVER_COMPANY_UPDATE(Packet *p) override
Update the clients knowledge of which company is password protected: uint16 Bitwise representation of...
Definition: network_client.cpp:1121
ClientNetworkGameSocketHandler::CheckConnection
void CheckConnection()
Check the connection's state, i.e.
Definition: network_client.cpp:1134
NetworkJoinInfo::server_password
std::string server_password
The password of the server to join.
Definition: network_client.h:115
DeserializeGRFIdentifier
void DeserializeGRFIdentifier(Packet *p, GRFIdentifier *grf)
Deserializes the GRFIdentifier (GRF ID and MD5 checksum) from the packet.
Definition: game_info.cpp:377
NetworkGameSocketHandler::SetInfo
void SetInfo(NetworkClientInfo *info)
Sets the client info for this socket handler.
Definition: tcp_game.h:531
NetworkUpdateClientInfo
void NetworkUpdateClientInfo(ClientID client_id)
Send updated client info of a particular client.
Definition: network_server.cpp:1470
ClientNetworkGameSocketHandler::GameLoop
static bool GameLoop()
Actual game loop for the client.
Definition: network_client.cpp:260
PacketReader::block
byte ** block
The block we're reading from/writing to.
Definition: network_client.cpp:46
NETWORK_CHAT_LENGTH
static const uint NETWORK_CHAT_LENGTH
The maximum length of a chat message, in bytes including '\0'.
Definition: config.h:66
PACKET_CLIENT_COMMAND
@ PACKET_CLIENT_COMMAND
Client executed a command and sends it to the server.
Definition: tcp_game.h:96
SetLocalCompany
void SetLocalCompany(CompanyID new_company)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
Definition: company_cmd.cpp:102
DFT_GAME_FILE
@ DFT_GAME_FILE
Save game or scenario file.
Definition: fileio_type.h:31
NetworkTCPSocketHandler::sock
SOCKET sock
The socket currently connected to.
Definition: tcp.h:39
TextColour
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
Definition: gfx_type.h:250
PacketReader::written_bytes
size_t written_bytes
The total number of bytes we've written.
Definition: network_client.cpp:47
GetNetworkRevisionString
std::string_view GetNetworkRevisionString()
Get the network version string used by this build.
Definition: game_info.cpp:43
_random
Randomizer _random
Random used in the game state calculations.
Definition: random_func.cpp:25
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:52
PACKET_CLIENT_QUIT
@ PACKET_CLIENT_QUIT
A client tells the server it is going to quit.
Definition: tcp_game.h:123
network_gui.h
_network_join_status
NetworkJoinStatus _network_join_status
The status of joining.
Definition: network_gui.cpp:2133
PACKET_CLIENT_GETMAP
@ PACKET_CLIENT_GETMAP
Client requests the actual map.
Definition: tcp_game.h:74
ClientNetworkGameSocketHandler::Receive_SERVER_ERROR
NetworkRecvStatus Receive_SERVER_ERROR(Packet *p) override
The client made an error: uint8 Error code caused (see NetworkErrorCode).
Definition: network_client.cpp:607
WC_COMPANY
@ WC_COMPANY
Company view; Window numbers:
Definition: window_type.h:361
GetNetworkErrorMsg
StringID GetNetworkErrorMsg(NetworkErrorCode err)
Retrieve the string id of an internal error number.
Definition: network.cpp:300
_network_server_name
std::string _network_server_name
The current name of the server you are on.
Definition: network_client.cpp:317
ClientNetworkGameSocketHandler::my_client
static ClientNetworkGameSocketHandler * my_client
This is us!
Definition: network_client.h:41
ClientNetworkGameSocketHandler::Receive_SERVER_MAP_BEGIN
NetworkRecvStatus Receive_SERVER_MAP_BEGIN(Packet *p) override
Sends that the server will begin with sending the map to the client: uint32 Current frame.
Definition: network_client.cpp:748
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
ClientNetworkGameSocketHandler::CloseConnection
NetworkRecvStatus CloseConnection(NetworkRecvStatus status) override
Close the network connection due to the given status.
Definition: network_client.cpp:159
NetworkGameSocketHandler
Base socket handler for all TCP sockets.
Definition: tcp_game.h:154
Packet::Send_uint8
void Send_uint8(uint8 data)
Package a 8 bits integer in the packet.
Definition: packet.cpp:129
LoadFilter::Reset
virtual void Reset()
Reset this filter to read from the beginning of the file.
Definition: saveload_filter.h:43
GRFIdentifier::md5sum
uint8 md5sum[16]
MD5 checksum of file to distinguish files with the same GRF ID (eg. newer version of GRF)
Definition: newgrf_config.h:85
PacketReader::Read
size_t Read(byte *rbuf, size_t size) override
Read a given number of bytes from the savegame.
Definition: network_client.cpp:96
ClientNetworkGameSocketHandler::Receive_SERVER_CLIENT_INFO
NetworkRecvStatus Receive_SERVER_CLIENT_INFO(Packet *p) override
Send information about a client: uint32 ID of the client (always unique on a server.
Definition: network_client.cpp:551
SetDParam
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings_func.h:196
NetworkSendCommand
void NetworkSendCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback, const std::string &text, CompanyID company)
Prepare a DoCommand to be send over the network.
Definition: network_command.cpp:136
CC_DEFAULT
static const TextColour CC_DEFAULT
Default colour of the console.
Definition: console_type.h:23
_frame_counter_max
uint32 _frame_counter_max
To where we may go with our clients.
Definition: network.cpp:70
PacketReader
Read some packets, and when do use that data as initial load filter.
Definition: network_client.cpp:40
GRFIdentifier::grfid
uint32 grfid
GRF ID (defined by Action 0x08)
Definition: newgrf_config.h:84
_network_first_time
bool _network_first_time
Whether we have finished joining or not.
Definition: network.cpp:79
PACKET_CLIENT_CHAT
@ PACKET_CLIENT_CHAT
Client said something that should be distributed.
Definition: tcp_game.h:100
ClientNetworkGameSocketHandler::Receive_SERVER_NEWGAME
NetworkRecvStatus Receive_SERVER_NEWGAME(Packet *p) override
Let the clients know that the server is loading a new map.
Definition: network_client.cpp:1052
network_base.h
ShowErrorMessage
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=nullptr, uint textref_stack_size=0, const uint32 *textref_stack=nullptr)
Display an error message in a window.
Definition: error_gui.cpp:383
PacketReader::read_bytes
size_t read_bytes
The total number of read bytes.
Definition: network_client.cpp:48
Packet::Send_uint32
void Send_uint32(uint32 data)
Package a 32 bits integer in the packet.
Definition: packet.cpp:150
PACKET_CLIENT_JOIN
@ PACKET_CLIENT_JOIN
The client telling the server it wants to join.
Definition: tcp_game.h:38
ClientNetworkGameSocketHandler::SendChat
static NetworkRecvStatus SendChat(NetworkAction action, DestType type, int dest, const std::string &msg, int64 data)
Send a chat-packet over the network.
Definition: network_client.cpp:424
Packet::CanReadFromPacket
bool CanReadFromPacket(size_t bytes_to_read, bool close_connection=false)
Is it safe to read from the packet, i.e.
Definition: packet.cpp:218
Packet::Recv_string
std::string Recv_string(size_t length, StringValidationSettings settings=SVS_REPLACE_WITH_QUESTION_MARK)
Reads characters (bytes) from the packet until it finds a '\0', or reaches a maximum of length charac...
Definition: packet.cpp:380
ClientNetworkGameSocketHandler::Receive_SERVER_NEED_COMPANY_PASSWORD
NetworkRecvStatus Receive_SERVER_NEED_COMPANY_PASSWORD(Packet *p) override
Indication to the client that the server needs a company password: uint32 Generation seed.
Definition: network_client.cpp:702
CommandQueue::Append
void Append(CommandPacket *p)
Append a CommandPacket at the end of the queue.
Definition: network_command.cpp:57
ClientNetworkGameSocketHandler::Receive_SERVER_NEED_GAME_PASSWORD
NetworkRecvStatus Receive_SERVER_NEED_GAME_PASSWORD(Packet *p) override
Indication to the client that the server needs a game password.
Definition: network_client.cpp:688
ClientNetworkGameSocketHandler::SendJoin
static NetworkRecvStatus SendJoin()
Make sure the server ID length is the same as a md5 hash.
Definition: network_client.cpp:331
last_ack_frame
static uint32 last_ack_frame
Last frame we performed an ack.
Definition: network_client.cpp:307
NetworkClientInfo::GetByClientID
static NetworkClientInfo * GetByClientID(ClientID client_id)
Return the CI given it's client-identifier.
Definition: network.cpp:113
_frame_counter_server
uint32 _frame_counter_server
The frame_counter of the server, if in network-mode.
Definition: network.cpp:69
NetworkJoinInfo::company
CompanyID company
The company to join.
Definition: network_client.h:114
GRFIdentifier
Basic data to distinguish a GRF.
Definition: newgrf_config.h:83
Packet::TransferOutWithLimit
ssize_t TransferOutWithLimit(F transfer_function, size_t limit, D destination, Args &&... args)
Transfer data from the packet to the given function.
Definition: packet.h:111
ClientNetworkGameSocketHandler::SendMove
static NetworkRecvStatus SendMove(CompanyID company, const std::string &password)
Ask the server to move us.
Definition: network_client.cpp:504
ClientNetworkGameSocketHandler::STATUS_MAP
@ STATUS_MAP
The client is downloading the map.
Definition: network_client.h:31
ClientNetworkGameSocketHandler::SendCompanyPassword
static NetworkRecvStatus SendCompanyPassword(const std::string &password)
Set the company password as requested.
Definition: network_client.cpp:371
ClearErrorMessages
void ClearErrorMessages()
Clear all errors from the queue.
Definition: error_gui.cpp:341
ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DATA
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).
Definition: network_client.cpp:779
COMPANY_NEW_COMPANY
@ COMPANY_NEW_COMPANY
The client wants a new company.
Definition: company_type.h:34
SLO_LOAD
@ SLO_LOAD
File is being loaded.
Definition: fileio_type.h:49
ClientNetworkGameSocketHandler::Receive_SERVER_FULL
NetworkRecvStatus Receive_SERVER_FULL(Packet *p) override
Notification that the server is full.
Definition: network_client.cpp:530
PacketReader::CHUNK
static const size_t CHUNK
32 KiB chunks of memory.
Definition: network_client.cpp:41
Packet::Recv_uint32
uint32 Recv_uint32()
Read a 32 bits integer from the packet.
Definition: packet.cpp:335
ClientNetworkGameSocketHandler::SendSetName
static NetworkRecvStatus SendSetName(const std::string &name)
Tell the server that we like to change the name of the client.
Definition: network_client.cpp:465
CommandPacket
Everything we need to know about a command to be able to execute it.
Definition: network_internal.h:107
_date
Date _date
Current date in days (day counter)
Definition: date.cpp:28
ClientNetworkGameSocketHandler::Receive_SERVER_CHECK_NEWGRFS
NetworkRecvStatus Receive_SERVER_CHECK_NEWGRFS(Packet *p) override
Sends information about all used GRFs to the client: uint8 Amount of GRFs (the following data is repe...
Definition: network_client.cpp:655
GRFConfig
Information about GRF, used in the game and (part of it) in savegames.
Definition: newgrf_config.h:155
PacketReader::blocks
std::vector< byte * > blocks
Buffer with blocks of allocated memory.
Definition: network_client.cpp:43
NETWORK_RECV_STATUS_NEWGRF_MISMATCH
@ NETWORK_RECV_STATUS_NEWGRF_MISMATCH
We did not have the required NewGRFs.
Definition: core.h:25
NetworkMaxCompaniesReached
bool NetworkMaxCompaniesReached()
Check if max_companies has been reached on the server (local check only).
Definition: network_client.cpp:1329
NETWORK_RECV_STATUS_SERVER_FULL
@ NETWORK_RECV_STATUS_SERVER_FULL
The server is full.
Definition: core.h:30
ClientNetworkGameSocketHandler::IsConnected
static bool IsConnected()
Check whether the client is actually connected (and in the game).
Definition: network_client.cpp:517
StrTrimInPlace
void StrTrimInPlace(std::string &str)
Trim the spaces from given string in place, i.e.
Definition: string.cpp:355
NETWORK_RECV_STATUS_SERVER_ERROR
@ NETWORK_RECV_STATUS_SERVER_ERROR
The server told us we made an error.
Definition: core.h:29
GenerateCompanyPasswordHash
std::string GenerateCompanyPasswordHash(const std::string &password, const std::string &password_server_id, uint32 password_game_seed)
Hash the given password using server ID and game seed.
Definition: network.cpp:176
ClientNetworkGameSocketHandler::Receive_SERVER_WELCOME
NetworkRecvStatus Receive_SERVER_WELCOME(Packet *p) override
The client is joined and ready to receive their map: uint32 Own client ID.
Definition: network_client.cpp:720
ClientID
ClientID
'Unique' identifier to be given to clients
Definition: network_type.h:47
ClientNetworkGameSocketHandler::Receive_SERVER_JOIN
NetworkRecvStatus Receive_SERVER_JOIN(Packet *p) override
A client joined (PACKET_CLIENT_MAP_OK), what usually directly follows is a PACKET_SERVER_CLIENT_INFO:...
Definition: network_client.cpp:1023
_password_server_id
static std::string _password_server_id
The other bit of 'entropy' used to generate a salt for the company passwords.
Definition: network_client.cpp:312
NETWORK_RECV_STATUS_SERVER_BANNED
@ NETWORK_RECV_STATUS_SERVER_BANNED
The server has banned us.
Definition: core.h:31
NetworkUpdateClientName
void NetworkUpdateClientName(const std::string &client_name)
Send the server our name as callback from the setting.
Definition: network_client.cpp:1265
NetworkClient_Connected
void NetworkClient_Connected()
Is called after a client is connected to the server.
Definition: network_client.cpp:1161
PACKET_CLIENT_NEWGRFS_CHECKED
@ PACKET_CLIENT_NEWGRFS_CHECKED
Client acknowledges that it has all required NewGRFs.
Definition: tcp_game.h:61
CCA_NEW
@ CCA_NEW
Create a new company.
Definition: company_type.h:65
_sync_seed_1
uint32 _sync_seed_1
Seed to compare during sync checks.
Definition: network.cpp:74
PacketReader::Reset
void Reset() override
Reset this filter to read from the beginning of the file.
Definition: network_client.cpp:118
NetworkClientsToSpectators
void NetworkClientsToSpectators(CompanyID cid)
Move the clients of a company to the spectators.
Definition: network_client.cpp:1196
WL_INFO
@ WL_INFO
Used for DoCommand-like (and some non-fatal AI GUI) errors/information.
Definition: error.h:22
_local_company
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:46
ClientNetworkGameSocketHandler::STATUS_JOIN
@ STATUS_JOIN
We are trying to join a server.
Definition: network_client.h:25
NetworkSocketHandler::MarkClosed
void MarkClosed()
Mark the connection as closed.
Definition: core.h:60
NETWORK_COMPANY_PASSWORD
@ NETWORK_COMPANY_PASSWORD
The password of the company.
Definition: network_type.h:82
NetworkSettings::client_name
std::string client_name
name of the player (as client)
Definition: settings_type.h:285
IsValidConsoleColour
bool IsValidConsoleColour(TextColour c)
Check whether the given TextColour is valid for console usage.
Definition: console_gui.cpp:524
NETWORK_RECV_STATUS_CLOSE_QUERY
@ NETWORK_RECV_STATUS_CLOSE_QUERY
Done querying the server.
Definition: core.h:32
NetworkTCPSocketHandler::SendPacket
virtual void SendPacket(Packet *packet)
This function puts the packet in the send-queue and it is send as soon as possible.
Definition: tcp.cpp:81
CLIENT_ID_SERVER
@ CLIENT_ID_SERVER
Servers always have this ID.
Definition: network_type.h:49
ClientNetworkGameSocketHandler::SendRCon
static NetworkRecvStatus SendRCon(const std::string &password, const std::string &command)
Send a console command.
Definition: network_client.cpp:490
NETWORK_SERVER_ID_LENGTH
static const uint NETWORK_SERVER_ID_LENGTH
The maximum length of the network id of the servers, in bytes including '\0'.
Definition: config.h:59
_networking
bool _networking
are we in networking mode?
Definition: network.cpp:57
ClientNetworkGameSocketHandler::STATUS_MAP_WAIT
@ STATUS_MAP_WAIT
The client is waiting as someone else is downloading the map.
Definition: network_client.h:30
network_client.h
CommandPacket::my_cmd
bool my_cmd
did the command originate from "me"
Definition: network_internal.h:113
DoAutoOrNetsave
void DoAutoOrNetsave(FiosNumberedSaveName &counter)
Create an autosave or netsave.
Definition: saveload.cpp:3331
_network_reconnect
uint8 _network_reconnect
Reconnect timeout.
Definition: network.cpp:65
PACKET_CLIENT_MAP_OK
@ PACKET_CLIENT_MAP_OK
Client tells the server that it received the whole map.
Definition: tcp_game.h:80
Packet
Internal entity of a packet.
Definition: packet.h:44
ClientNetworkGameSocketHandler::Receive_SERVER_EXTERNAL_CHAT
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...
Definition: network_client.cpp:970
GameMode
GameMode
Mode which defines the state of the game.
Definition: openttd.h:17
NetworkGameSocketHandler::ReceiveCommand
const char * ReceiveCommand(Packet *p, CommandPacket *cp)
Receives a command from the network.
Definition: network_command.cpp:295
Randomizer::state
uint32 state[2]
The state of the randomizer.
Definition: random_func.hpp:23
PacketReader::buf
byte * buf
Buffer we're going to write to/read from.
Definition: network_client.cpp:44
BSWAP32
static uint32 BSWAP32(uint32 x)
Perform a 32 bits endianness bitswap on x.
Definition: bitmath_func.hpp:390
GUISettings::prefer_teamchat
bool prefer_teamchat
choose the chat message target with <ENTER>, true=all clients, false=your team
Definition: settings_type.h:123
_network_server_max_companies
static uint8 _network_server_max_companies
Maximum number of companies of the currently joined server.
Definition: network_client.cpp:315
StateGameLoop
void StateGameLoop()
State controlling game loop.
Definition: openttd.cpp:1316
_network_own_client_id
ClientID _network_own_client_id
Our client identifier.
Definition: network.cpp:63
NetworkClientSendChat
void NetworkClientSendChat(NetworkAction action, DestType type, int dest, const std::string &msg, int64 data)
Send a chat message.
Definition: network_client.cpp:1294
PACKET_CLIENT_SET_NAME
@ PACKET_CLIENT_SET_NAME
A client changes its name.
Definition: tcp_game.h:114
ClientNetworkGameSocketHandler::Receive
static bool Receive()
Check whether we received/can send some data from/to the server and when that's the case handle it ap...
Definition: network_client.cpp:235
NetworkGameSocketHandler::GetInfo
NetworkClientInfo * GetInfo() const
Gets the client info of this socket handler.
Definition: tcp_game.h:541
ClientNetworkGameSocketHandler::Receive_SERVER_CONFIG_UPDATE
NetworkRecvStatus Receive_SERVER_CONFIG_UPDATE(Packet *p) override
Update the clients knowledge of the max settings: uint8 Maximum number of companies allowed.
Definition: network_client.cpp:1111
_switch_mode
SwitchMode _switch_mode
The next mainloop command.
Definition: gfx.cpp:47
StringID
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
NetworkSocketHandler::HasClientQuit
bool HasClientQuit() const
Whether the current client connected to the socket has quit.
Definition: core.h:68
NetworkTCPSocketHandler::SendPackets
SendPacketsState SendPackets(bool closing_down=false)
Sends all the buffered packets out for this client.
Definition: tcp.cpp:99
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
NETWORK_RCONCOMMAND_LENGTH
static const uint NETWORK_RCONCOMMAND_LENGTH
The maximum length of a rconsole command, in bytes including '\0'.
Definition: config.h:64
NetworkTCPSocketHandler::CanSendReceive
bool CanSendReceive()
Check whether this socket can send or receive something.
Definition: tcp.cpp:218
Pool::PoolItem<&_networkclientinfo_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:386
FiosNumberedSaveName
A savegame name automatically numbered.
Definition: fios.h:131
DetailedFileType
DetailedFileType
Kinds of files in each AbstractFileType.
Definition: fileio_type.h:28
Pool::PoolItem<&_company_pool >::GetNumItems
static size_t GetNumItems()
Returns number of valid items in the pool.
Definition: pool_type.hpp:367
ClientNetworkGameSocketHandler::SendCommand
static NetworkRecvStatus SendCommand(const CommandPacket *cp)
Send a command to the server.
Definition: network_client.cpp:414
PacketReader::TransferOutMemCopy
static ssize_t TransferOutMemCopy(PacketReader *destination, const char *source, size_t amount)
Simple wrapper around fwrite to be able to pass it to Packet's TransferOut.
Definition: network_client.cpp:69
Backup::Restore
void Restore()
Restore the variable.
Definition: backup_type.hpp:112
Packet::Recv_bool
bool Recv_bool()
Read a boolean from the packet.
Definition: packet.cpp:297
Packet::Send_uint64
void Send_uint64(uint64 data)
Package a 64 bits integer in the packet.
Definition: packet.cpp:163
ClientNetworkGameSocketHandler::Receive_SERVER_ERROR_QUIT
NetworkRecvStatus Receive_SERVER_ERROR_QUIT(Packet *p) override
Inform all clients that one client made an error and thus has quit/been disconnected: uint32 ID of th...
Definition: network_client.cpp:986
GetDrawStringCompanyColour
TextColour GetDrawStringCompanyColour(CompanyID company)
Get the colour for DrawString-subroutines which matches the colour of the company.
Definition: company_cmd.cpp:131
NetworkClientSetCompanyPassword
void NetworkClientSetCompanyPassword(const std::string &password)
Set/Reset company password on the client side.
Definition: network_client.cpp:1303
NO_DIRECTORY
@ NO_DIRECTORY
A path without any base directory.
Definition: fileio_type.h:125
ClientNetworkGameSocketHandler::STATUS_AUTHORIZED
@ STATUS_AUTHORIZED
The client is authorized at the server.
Definition: network_client.h:29
COMPANY_SPECTATOR
@ COMPANY_SPECTATOR
The client is spectating.
Definition: company_type.h:35
PACKET_CLIENT_GAME_PASSWORD
@ PACKET_CLIENT_GAME_PASSWORD
Clients sends the (hashed) game password.
Definition: tcp_game.h:65
NetworkJoinInfo
Information required to join a server.
Definition: network_client.h:111
NetworkRecvStatus
NetworkRecvStatus
Status of a network client; reasons why a client has quit.
Definition: core.h:22
ClientNetworkGameSocketHandler::SendError
static NetworkRecvStatus SendError(NetworkErrorCode errorno)
Send an error-packet over the network.
Definition: network_client.cpp:439
WC_NETWORK_STATUS_WINDOW
@ WC_NETWORK_STATUS_WINDOW
Network status window; Window numbers:
Definition: window_type.h:477
ClientNetworkGameSocketHandler::Receive_SERVER_SYNC
NetworkRecvStatus Receive_SERVER_SYNC(Packet *p) override
Sends a sync-check to the client: uint32 Frame counter.
Definition: network_client.cpp:889
ClientNetworkGameSocketHandler::ClientError
void ClientError(NetworkRecvStatus res)
Handle an error coming from the client side.
Definition: network_client.cpp:185
ClientNetworkGameSocketHandler::token
byte token
The token we need to send back to the server to prove we're the right client.
Definition: network_client.h:20
Pool::PoolItem<&_networkclientinfo_pool >::CanAllocateItem
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
Definition: pool_type.hpp:307
ClientNetworkGameSocketHandler::STATUS_AUTH_GAME
@ STATUS_AUTH_GAME
Last action was requesting game (server) password.
Definition: network_client.h:27
PacketReader::bufe
byte * bufe
End of the buffer we write to/read from.
Definition: network_client.cpp:45
Subdirectory
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:108
ClientNetworkGameSocketHandler::NetworkExecuteLocalCommandQueue
friend void NetworkExecuteLocalCommandQueue()
Execute all commands on the local command queue that ought to be executed this frame.
Definition: network_command.cpp:190
PACKET_CLIENT_RCON
@ PACKET_CLIENT_RCON
Client asks the server to execute some command.
Definition: tcp_game.h:105
Packet::Recv_uint8
uint8 Recv_uint8()
Read a 8 bits integer from the packet.
Definition: packet.cpp:306
ClientNetworkGameSocketHandler::~ClientNetworkGameSocketHandler
~ClientNetworkGameSocketHandler()
Clear whatever we assigned.
Definition: network_client.cpp:150
WL_ERROR
@ WL_ERROR
Errors (eg. saving/loading failed)
Definition: error.h:24
ClientNetworkGameSocketHandler::Receive_SERVER_COMMAND
NetworkRecvStatus Receive_SERVER_COMMAND(Packet *p) override
Sends a DoCommand to the client: uint8 ID of the company (0..MAX_COMPANIES-1).
Definition: network_client.cpp:902
SM_MENU
@ SM_MENU
Switch to game intro menu.
Definition: openttd.h:32
ClientNetworkGameSocketHandler
Class for handling the client side of the game connection.
Definition: network_client.h:16
CMD_COMPANY_CTRL
@ CMD_COMPANY_CTRL
used in multiplayer to create a new companies etc.
Definition: command_type.h:281
ClientNetworkGameSocketHandler::Receive_SERVER_SHUTDOWN
NetworkRecvStatus Receive_SERVER_SHUTDOWN(Packet *p) override
Let the clients know that the server is closing.
Definition: network_client.cpp:1039
NetworkGameSocketHandler::incoming_queue
CommandQueue incoming_queue
The command-queue awaiting handling.
Definition: tcp_game.h:515
_sync_frame
uint32 _sync_frame
The frame to perform the sync check.
Definition: network.cpp:78
error
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
Definition: openttd.cpp:132
network.h
NetworkGameSocketHandler::client_id
ClientID client_id
Client identifier.
Definition: tcp_game.h:512
Packet::Send_string
void Send_string(const std::string_view data)
Sends a string over the network.
Definition: packet.cpp:181
MILLISECONDS_PER_TICK
static const uint MILLISECONDS_PER_TICK
The number of milliseconds per game tick.
Definition: gfx_type.h:310
Debug
#define Debug(name, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
ClientNetworkGameSocketHandler::SendGetMap
static NetworkRecvStatus SendGetMap()
Request the map from the server.
Definition: network_client.cpp:380
LoadFilter
Interface for filtering a savegame till it is loaded.
Definition: saveload_filter.h:14
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:378
ClientNetworkGameSocketHandler::Receive_SERVER_RCON
NetworkRecvStatus Receive_SERVER_RCON(Packet *p) override
Send the result of an issues RCon command back to the client: uint16 Colour code.
Definition: network_client.cpp:1069
ClientSettings::network
NetworkSettings network
settings related to the network
Definition: settings_type.h:595
Packet::Recv_uint64
uint64 Recv_uint64()
Read a 64 bits integer from the packet.
Definition: packet.cpp:352
CloseWindowById
void CloseWindowById(WindowClass cls, WindowNumber number, bool force)
Close a window by its class and window number (if it is open).
Definition: window.cpp:1176
ClientNetworkGameSocketHandler::SendMapOk
static NetworkRecvStatus SendMapOk()
Tell the server we received the complete map.
Definition: network_client.cpp:390
NetworkGameSocketHandler::CloseConnection
NetworkRecvStatus CloseConnection(bool error=true) override
Functions to help ReceivePacket/SendPacket a bit A socket can make errors.
Definition: tcp_game.cpp:41
PACKET_CLIENT_ACK
@ PACKET_CLIENT_ACK
The client tells the server which frame it has executed.
Definition: tcp_game.h:92
PACKET_CLIENT_MOVE
@ PACKET_CLIENT_MOVE
A client would like to be moved to another company.
Definition: tcp_game.h:109
ClientNetworkGameSocketHandler::savegame
struct PacketReader * savegame
Packet reader for reading the savegame.
Definition: network_client.h:19
ClientNetworkGameSocketHandler::SendAck
static NetworkRecvStatus SendAck()
Send an acknowledgement from the server's ticks.
Definition: network_client.cpp:400
NETWORK_RECV_STATUS_OKAY
@ NETWORK_RECV_STATUS_OKAY
Everything is okay.
Definition: core.h:23
network_gamelist.h
SafeLoad
bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf=nullptr)
Load the specified savegame but on error do different things.
Definition: openttd.cpp:933
ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DONE
NetworkRecvStatus Receive_SERVER_MAP_DONE(Packet *p) override
Sends that all data of the map are sent to the client:
Definition: network_client.cpp:793
PacketReader::PacketReader
PacketReader()
Initialise everything.
Definition: network_client.cpp:51
md5sumToString
char * md5sumToString(char *buf, const char *last, const uint8 md5sum[16])
Convert the md5sum to a hexadecimal string representation.
Definition: string.cpp:553
ClientNetworkGameSocketHandler::SendQuit
static NetworkRecvStatus SendQuit()
Tell the server we would like to quit.
Definition: network_client.cpp:477
Pool::PoolItem<&_company_pool >::IsValidID
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition: pool_type.hpp:326
ClientNetworkGameSocketHandler::STATUS_ACTIVE
@ STATUS_ACTIVE
The client is active within in the game.
Definition: network_client.h:32
ClientNetworkGameSocketHandler::status
ServerStatus status
Status of the connection with the server.
Definition: network_client.h:36
FGCM_EXACT
@ FGCM_EXACT
Only find Grfs matching md5sum.
Definition: newgrf_config.h:199
NETWORK_RECV_STATUS_SAVEGAME
@ NETWORK_RECV_STATUS_SAVEGAME
Something went wrong (down)loading the savegame.
Definition: core.h:26
ClientNetworkGameSocketHandler::SendGamePassword
static NetworkRecvStatus SendGamePassword(const std::string &password)
Set the game password as requested.
Definition: network_client.cpp:359
ClientNetworkGameSocketHandler::Receive_SERVER_MAP_SIZE
NetworkRecvStatus Receive_SERVER_MAP_SIZE(Packet *p) override
Sends the size of the map to the client.
Definition: network_client.cpp:768
WN_NETWORK_STATUS_WINDOW_JOIN
@ WN_NETWORK_STATUS_WINDOW_JOIN
Network join status.
Definition: window_type.h:31
CC_WARNING
static const TextColour CC_WARNING
Colour for warning lines.
Definition: console_type.h:25
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:460
NetworkMakeClientNameUnique
bool NetworkMakeClientNameUnique(std::string &new_name)
Check whether a name is unique, and otherwise try to make it unique.
Definition: network_server.cpp:1585
ClientNetworkGameSocketHandler::Receive_SERVER_QUIT
NetworkRecvStatus Receive_SERVER_QUIT(Packet *p) override
Notification that a client left the game: uint32 ID of the client.
Definition: network_client.cpp:1003
Packet::RemainingBytesToTransfer
size_t RemainingBytesToTransfer() const
Get the amount of bytes that are still available for the Transfer functions.
Definition: packet.cpp:402
_network_join
NetworkJoinInfo _network_join
Information about the game to join to.
Definition: network_client.cpp:320
SetWindowClassesDirty
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3162
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:394
ClientNetworkGameSocketHandler::Receive_SERVER_MOVE
NetworkRecvStatus Receive_SERVER_MOVE(Packet *p) override
Move a client from one company into another: uint32 ID of the client.
Definition: network_client.cpp:1083
ClientNetworkGameSocketHandler::SendSetPassword
static NetworkRecvStatus SendSetPassword(const std::string &password)
Tell the server that we like to change the password of the company.
Definition: network_client.cpp:452
ClientNetworkGameSocketHandler::Send
static void Send()
Send the packets of this socket handler.
Definition: network_client.cpp:250
_network_join_bytes
uint32 _network_join_bytes
The number of bytes we already downloaded.
Definition: network_gui.cpp:2135
DAY_TICKS
static const int DAY_TICKS
1 day is 74 ticks; _date_fract used to be uint16 and incremented by 885.
Definition: date_type.h:28
NetworkErrorCode
NetworkErrorCode
The error codes we send around in the protocols.
Definition: network_type.h:119
NetworkClientInfo
Container for all information known about a client.
Definition: network_base.h:24
NetworkIsValidClientName
bool NetworkIsValidClientName(const std::string_view client_name)
Check whether the given client name is deemed valid for use in network games.
Definition: network_client.cpp:1218
PACKET_CLIENT_SET_PASSWORD
@ PACKET_CLIENT_SET_PASSWORD
A client (re)sets its company's password.
Definition: tcp_game.h:113
SetDParamStr
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Definition: strings.cpp:296
PACKET_CLIENT_COMPANY_PASSWORD
@ PACKET_CLIENT_COMPANY_PASSWORD
Client sends the (hashed) company password.
Definition: tcp_game.h:67
INVALID_STRING_ID
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Definition: strings_type.h:17
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition: settings_type.h:594
WL_CRITICAL
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:25
NETWORK_GAME_PASSWORD
@ NETWORK_GAME_PASSWORD
The password of the game.
Definition: network_type.h:81
Packet::Recv_uint16
uint16 Recv_uint16()
Read a 16 bits integer from the packet.
Definition: packet.cpp:320
NetworkSettings::max_companies
uint8 max_companies
maximum amount of companies
Definition: settings_type.h:293
ClientNetworkGameSocketHandler::Receive_SERVER_WAIT
NetworkRecvStatus Receive_SERVER_WAIT(Packet *p) override
Notification that another client is currently receiving the map: uint8 Number of clients waiting in f...
Definition: network_client.cpp:735
NETWORK_RECV_STATUS_MALFORMED_PACKET
@ NETWORK_RECV_STATUS_MALFORMED_PACKET
We apparently send a malformed packet.
Definition: core.h:28
IConsolePrint
void IConsolePrint(TextColour colour_code, const std::string &string)
Handle the printing of text entered into the console or redirected there by any other means.
Definition: console.cpp:94