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

OpenTTD Source 14.0-beta3

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