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

OpenTTD Source 1.11.0-RC1

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 "../date_func.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 "../roadveh.h"
27 #include "../order_backup.h"
28 #include "../core/pool_func.hpp"
29 #include "../core/random_func.hpp"
30 #include "../rev.h"
31 #include <mutex>
32 #include <condition_variable>
33
34 #include "../safeguards.h"
35
36
37 /* This file handles all the server-commands */
38
39 DECLARE_POSTFIX_INCREMENT(ClientID)
41 static ClientID _network_client_id = CLIENT_ID_FIRST;
42
44 static_assert(MAX_CLIENT_SLOTS > MAX_CLIENTS);
46 static_assert(NetworkClientSocketPool::MAX_SIZE == MAX_CLIENT_SLOTS);
47
49 NetworkClientSocketPool _networkclientsocket_pool("NetworkClientSocket");
50 INSTANTIATE_POOL_METHODS(NetworkClientSocket)
51
53 template SocketList TCPListenHandler<ServerNetworkGameSocketHandler, PACKET_SERVER_FULL, PACKET_SERVER_BANNED>::sockets;
54
56 struct PacketWriter : SaveFilter {
57 ServerNetworkGameSocketHandler *cs;
58 Packet *current;
59 size_t total_size;
60 Packet *packets;
61 std::mutex mutex;
62 std::condition_variable exit_sig;
63
68 PacketWriter(ServerNetworkGameSocketHandler *cs) : SaveFilter(nullptr), cs(cs), current(nullptr), total_size(0), packets(nullptr)
69 {
70 }
71
73 ~PacketWriter()
74 {
75 std::unique_lock<std::mutex> lock(this->mutex);
76
77 if (this->cs != nullptr) this->exit_sig.wait(lock);
78
79 /* This must all wait until the Destroy function is called. */
80
81 while (this->packets != nullptr) {
82 Packet *p = this->packets->next;
83 delete this->packets;
84 this->packets = p;
85 }
86
87 delete this->current;
88 }
89
100 void Destroy()
101 {
102 std::unique_lock<std::mutex> lock(this->mutex);
103
104 this->cs = nullptr;
105
106 this->exit_sig.notify_all();
107 lock.unlock();
108
109 /* Make sure the saving is completely cancelled. Yes,
110 * we need to handle the save finish as well as the
111 * next connection might just be requesting a map. */
112 WaitTillSaved();
113 ProcessAsyncSaveFinish();
114 }
115
123 bool HasPackets()
124 {
125 return this->packets != nullptr;
126 }
127
131 Packet *PopPacket()
132 {
133 std::lock_guard<std::mutex> lock(this->mutex);
134
135 Packet *p = this->packets;
136 this->packets = p->next;
137 p->next = nullptr;
138
139 return p;
140 }
141
143 void AppendQueue()
144 {
145 if (this->current == nullptr) return;
146
147 Packet **p = &this->packets;
148 while (*p != nullptr) {
149 p = &(*p)->next;
150 }
151 *p = this->current;
152
153 this->current = nullptr;
154 }
155
157 void PrependQueue()
158 {
159 if (this->current == nullptr) return;
160
161 this->current->next = this->packets;
162 this->packets = this->current;
163 this->current = nullptr;
164 }
165
166 void Write(byte *buf, size_t size) override
167 {
168 /* We want to abort the saving when the socket is closed. */
169 if (this->cs == nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
170
171 if (this->current == nullptr) this->current = new Packet(PACKET_SERVER_MAP_DATA);
172
173 std::lock_guard<std::mutex> lock(this->mutex);
174
175 byte *bufe = buf + size;
176 while (buf != bufe) {
177 size_t to_write = std::min<size_t>(SEND_MTU - this->current->size, bufe - buf);
178 memcpy(this->current->buffer + this->current->size, buf, to_write);
179 this->current->size += (PacketSize)to_write;
180 buf += to_write;
181
182 if (this->current->size == SEND_MTU) {
183 this->AppendQueue();
184 if (buf != bufe) this->current = new Packet(PACKET_SERVER_MAP_DATA);
185 }
186 }
187
188 this->total_size += size;
189 }
190
191 void Finish() override
192 {
193 /* We want to abort the saving when the socket is closed. */
194 if (this->cs == nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
195
196 std::lock_guard<std::mutex> lock(this->mutex);
197
198 /* Make sure the last packet is flushed. */
199 this->AppendQueue();
200
201 /* Add a packet stating that this is the end to the queue. */
202 this->current = new Packet(PACKET_SERVER_MAP_DONE);
203 this->AppendQueue();
204
205 /* Fast-track the size to the client. */
206 this->current = new Packet(PACKET_SERVER_MAP_SIZE);
207 this->current->Send_uint32((uint32)this->total_size);
208 this->PrependQueue();
209 }
210 };
211
212
217 ServerNetworkGameSocketHandler::ServerNetworkGameSocketHandler(SOCKET s) : NetworkGameSocketHandler(s)
218 {
219 this->status = STATUS_INACTIVE;
220 this->client_id = _network_client_id++;
221 this->receive_limit = _settings_client.network.bytes_per_frame_burst;
222
223 /* The Socket and Info pools need to be the same in size. After all,
224 * each Socket will be associated with at most one Info object. As
225 * such if the Socket was allocated the Info object can as well. */
226 static_assert(NetworkClientSocketPool::MAX_SIZE == NetworkClientInfoPool::MAX_SIZE);
227 }
228
232 ServerNetworkGameSocketHandler::~ServerNetworkGameSocketHandler()
233 {
234 if (_redirect_console_to_client == this->client_id) _redirect_console_to_client = INVALID_CLIENT_ID;
235 OrderBackup::ResetUser(this->client_id);
236
237 if (this->savegame != nullptr) {
238 this->savegame->Destroy();
239 this->savegame = nullptr;
240 }
241 }
242
243 Packet *ServerNetworkGameSocketHandler::ReceivePacket()
244 {
245 /* Only allow receiving when we have some buffer free; this value
246 * can go negative, but eventually it will become positive again. */
247 if (this->receive_limit <= 0) return nullptr;
248
249 /* We can receive a packet, so try that and if needed account for
250 * the amount of received data. */
251 Packet *p = this->NetworkTCPSocketHandler::ReceivePacket();
252 if (p != nullptr) this->receive_limit -= p->size;
253 return p;
254 }
255
256 NetworkRecvStatus ServerNetworkGameSocketHandler::CloseConnection(NetworkRecvStatus status)
257 {
258 assert(status != NETWORK_RECV_STATUS_OKAY);
259 /*
260 * Sending a message just before leaving the game calls cs->SendPackets.
261 * This might invoke this function, which means that when we close the
262 * connection after cs->SendPackets we will close an already closed
263 * connection. This handles that case gracefully without having to make
264 * that code any more complex or more aware of the validity of the socket.
265 */
266 if (this->sock == INVALID_SOCKET) return status;
267
268 if (status != NETWORK_RECV_STATUS_CONN_LOST && status != NETWORK_RECV_STATUS_SERVER_ERROR && !this->HasClientQuit() && this->status >= STATUS_AUTHORIZED) {
269 /* We did not receive a leave message from this client... */
270 char client_name[NETWORK_CLIENT_NAME_LENGTH];
271
272 this->GetClientName(client_name, lastof(client_name));
273
274 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, nullptr, STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST);
275
276 /* Inform other clients of this... strange leaving ;) */
277 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
278 if (new_cs->status > STATUS_AUTHORIZED && this != new_cs) {
279 new_cs->SendErrorQuit(this->client_id, NETWORK_ERROR_CONNECTION_LOST);
280 }
281 }
282 }
283
284 /* If we were transfering a map to this client, stop the savegame creation
285 * process and queue the next client to receive the map. */
286 if (this->status == STATUS_MAP) {
287 /* Ensure the saving of the game is stopped too. */
288 this->savegame->Destroy();
289 this->savegame = nullptr;
290
291 this->CheckNextClientToSendMap(this);
292 }
293
294 NetworkAdminClientError(this->client_id, NETWORK_ERROR_CONNECTION_LOST);
295 DEBUG(net, 1, "Closed client connection %d", this->client_id);
296
297 /* We just lost one client :( */
298 if (this->status >= STATUS_AUTHORIZED) _network_game_info.clients_on--;
299 extern byte _network_clients_connected;
300 _network_clients_connected--;
301
302 DeleteWindowById(WC_CLIENT_LIST_POPUP, this->client_id);
303 SetWindowDirty(WC_CLIENT_LIST, 0);
304
305 this->SendPackets(true);
306
307 delete this->GetInfo();
308 delete this;
309
310 return status;
311 }
312
317 /* static */ bool ServerNetworkGameSocketHandler::AllowConnection()
318 {
319 extern byte _network_clients_connected;
320 bool accept = _network_clients_connected < MAX_CLIENTS && _network_game_info.clients_on < _settings_client.network.max_clients;
321
322 /* We can't go over the MAX_CLIENTS limit here. However, the
323 * pool must have place for all clients and ourself. */
324 static_assert(NetworkClientSocketPool::MAX_SIZE == MAX_CLIENTS + 1);
325 assert(!accept || ServerNetworkGameSocketHandler::CanAllocateItem());
326 return accept;
327 }
328
330 /* static */ void ServerNetworkGameSocketHandler::Send()
331 {
332 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
333 if (cs->writable) {
334 if (cs->SendPackets() != SPS_CLOSED && cs->status == STATUS_MAP) {
335 /* This client is in the middle of a map-send, call the function for that */
336 cs->SendMap();
337 }
338 }
339 }
340 }
341
342 static void NetworkHandleCommandQueue(NetworkClientSocket *cs);
343
344 /***********
345 * Sending functions
346 * DEF_SERVER_SEND_COMMAND has parameter: NetworkClientSocket *cs
347 ************/
348
353 NetworkRecvStatus ServerNetworkGameSocketHandler::SendClientInfo(NetworkClientInfo *ci)
354 {
355 if (ci->client_id != INVALID_CLIENT_ID) {
356 Packet *p = new Packet(PACKET_SERVER_CLIENT_INFO);
357 p->Send_uint32(ci->client_id);
358 p->Send_uint8 (ci->client_playas);
359 p->Send_string(ci->client_name);
360
361 this->SendPacket(p);
362 }
363 return NETWORK_RECV_STATUS_OKAY;
364 }
365
367 NetworkRecvStatus ServerNetworkGameSocketHandler::SendCompanyInfo()
368 {
369 /* Fetch the latest version of the stats */
370 NetworkCompanyStats company_stats[MAX_COMPANIES];
371 NetworkPopulateCompanyStats(company_stats);
372
373 /* Make a list of all clients per company */
374 char clients[MAX_COMPANIES][NETWORK_CLIENTS_LENGTH];
375 memset(clients, 0, sizeof(clients));
376
377 /* Add the local player (if not dedicated) */
378 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
379 if (ci != nullptr && Company::IsValidID(ci->client_playas)) {
380 strecpy(clients[ci->client_playas], ci->client_name, lastof(clients[ci->client_playas]));
381 }
382
383 for (NetworkClientSocket *csi : NetworkClientSocket::Iterate()) {
384 char client_name[NETWORK_CLIENT_NAME_LENGTH];
385
386 ((ServerNetworkGameSocketHandler*)csi)->GetClientName(client_name, lastof(client_name));
387
388 ci = csi->GetInfo();
389 if (ci != nullptr && Company::IsValidID(ci->client_playas)) {
390 if (!StrEmpty(clients[ci->client_playas])) {
391 strecat(clients[ci->client_playas], ", ", lastof(clients[ci->client_playas]));
392 }
393
394 strecat(clients[ci->client_playas], client_name, lastof(clients[ci->client_playas]));
395 }
396 }
397
398 /* Now send the data */
399
400 Packet *p;
401
402 for (const Company *company : Company::Iterate()) {
403 p = new Packet(PACKET_SERVER_COMPANY_INFO);
404
405 p->Send_uint8 (NETWORK_COMPANY_INFO_VERSION);
406 p->Send_bool (true);
407 this->SendCompanyInformation(p, company, &company_stats[company->index]);
408
409 if (StrEmpty(clients[company->index])) {
410 p->Send_string("<none>");
411 } else {
412 p->Send_string(clients[company->index]);
413 }
414
415 this->SendPacket(p);
416 }
417
418 p = new Packet(PACKET_SERVER_COMPANY_INFO);
419
420 p->Send_uint8 (NETWORK_COMPANY_INFO_VERSION);
421 p->Send_bool (false);
422
423 this->SendPacket(p);
424 return NETWORK_RECV_STATUS_OKAY;
425 }
426
432 NetworkRecvStatus ServerNetworkGameSocketHandler::SendError(NetworkErrorCode error, const char *reason)
433 {
434 char str[100];
435 Packet *p = new Packet(PACKET_SERVER_ERROR);
436
437 p->Send_uint8(error);
438 if (reason != nullptr) p->Send_string(reason);
439 this->SendPacket(p);
440
441 StringID strid = GetNetworkErrorMsg(error);
442 GetString(str, strid, lastof(str));
443
444 /* Only send when the current client was in game */
445 if (this->status > STATUS_AUTHORIZED) {
446 char client_name[NETWORK_CLIENT_NAME_LENGTH];
447
448 this->GetClientName(client_name, lastof(client_name));
449
450 DEBUG(net, 1, "'%s' made an error and has been disconnected. Reason: '%s'", client_name, str);
451
452 if (error == NETWORK_ERROR_KICKED && reason != nullptr) {
453 NetworkTextMessage(NETWORK_ACTION_KICKED, CC_DEFAULT, false, client_name, reason, strid);
454 } else {
455 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, nullptr, strid);
456 }
457
458 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
459 if (new_cs->status > STATUS_AUTHORIZED && new_cs != this) {
460 /* Some errors we filter to a more general error. Clients don't have to know the real
461 * reason a joining failed. */
462 if (error == NETWORK_ERROR_NOT_AUTHORIZED || error == NETWORK_ERROR_NOT_EXPECTED || error == NETWORK_ERROR_WRONG_REVISION) {
463 error = NETWORK_ERROR_ILLEGAL_PACKET;
464 }
465 new_cs->SendErrorQuit(this->client_id, error);
466 }
467 }
468
469 NetworkAdminClientError(this->client_id, error);
470 } else {
471 DEBUG(net, 1, "Client %d made an error and has been disconnected. Reason: '%s'", this->client_id, str);
472 }
473
474 /* The client made a mistake, so drop his connection now! */
475 return this->CloseConnection(NETWORK_RECV_STATUS_SERVER_ERROR);
476 }
477
479 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGRFCheck()
480 {
481 Packet *p = new Packet(PACKET_SERVER_CHECK_NEWGRFS);
482 const GRFConfig *c;
483 uint grf_count = 0;
484
485 for (c = _grfconfig; c != nullptr; c = c->next) {
486 if (!HasBit(c->flags, GCF_STATIC)) grf_count++;
487 }
488
489 p->Send_uint8 (grf_count);
490 for (c = _grfconfig; c != nullptr; c = c->next) {
491 if (!HasBit(c->flags, GCF_STATIC)) this->SendGRFIdentifier(p, &c->ident);
492 }
493
494 this->SendPacket(p);
495 return NETWORK_RECV_STATUS_OKAY;
496 }
497
499 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNeedGamePassword()
500 {
501 /* Invalid packet when status is STATUS_AUTH_GAME or higher */
502 if (this->status >= STATUS_AUTH_GAME) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
503
504 this->status = STATUS_AUTH_GAME;
505 /* Reset 'lag' counters */
506 this->last_frame = this->last_frame_server = _frame_counter;
507
508 Packet *p = new Packet(PACKET_SERVER_NEED_GAME_PASSWORD);
509 this->SendPacket(p);
510 return NETWORK_RECV_STATUS_OKAY;
511 }
512
514 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNeedCompanyPassword()
515 {
516 /* Invalid packet when status is STATUS_AUTH_COMPANY or higher */
517 if (this->status >= STATUS_AUTH_COMPANY) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
518
519 this->status = STATUS_AUTH_COMPANY;
520 /* Reset 'lag' counters */
521 this->last_frame = this->last_frame_server = _frame_counter;
522
523 Packet *p = new Packet(PACKET_SERVER_NEED_COMPANY_PASSWORD);
524 p->Send_uint32(_settings_game.game_creation.generation_seed);
525 p->Send_string(_settings_client.network.network_id);
526 this->SendPacket(p);
527 return NETWORK_RECV_STATUS_OKAY;
528 }
529
531 NetworkRecvStatus ServerNetworkGameSocketHandler::SendWelcome()
532 {
533 Packet *p;
534
535 /* Invalid packet when status is AUTH or higher */
536 if (this->status >= STATUS_AUTHORIZED) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
537
538 this->status = STATUS_AUTHORIZED;
539 /* Reset 'lag' counters */
540 this->last_frame = this->last_frame_server = _frame_counter;
541
542 _network_game_info.clients_on++;
543
544 p = new Packet(PACKET_SERVER_WELCOME);
545 p->Send_uint32(this->client_id);
546 p->Send_uint32(_settings_game.game_creation.generation_seed);
547 p->Send_string(_settings_client.network.network_id);
548 this->SendPacket(p);
549
550 /* Transmit info about all the active clients */
551 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
552 if (new_cs != this && new_cs->status > STATUS_AUTHORIZED) {
553 this->SendClientInfo(new_cs->GetInfo());
554 }
555 }
556 /* Also send the info of the server */
557 return this->SendClientInfo(NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER));
558 }
559
561 NetworkRecvStatus ServerNetworkGameSocketHandler::SendWait()
562 {
563 int waiting = 1; // current player getting the map counts as 1
564 Packet *p;
565
566 /* Count how many clients are waiting in the queue, in front of you! */
567 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
568 if (new_cs->status != STATUS_MAP_WAIT) continue;
569 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++;
570 }
571
572 p = new Packet(PACKET_SERVER_WAIT);
573 p->Send_uint8(waiting);
574 this->SendPacket(p);
575 return NETWORK_RECV_STATUS_OKAY;
576 }
577
578 void ServerNetworkGameSocketHandler::CheckNextClientToSendMap(NetworkClientSocket *ignore_cs)
579 {
580 /* Find the best candidate for joining, i.e. the first joiner. */
581 NetworkClientSocket *best = nullptr;
582 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
583 if (ignore_cs == new_cs) continue;
584
585 if (new_cs->status == STATUS_MAP_WAIT) {
586 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)) {
587 best = new_cs;
588 }
589 }
590 }
591
592 /* Is there someone else to join? */
593 if (best != nullptr) {
594 /* Let the first start joining. */
595 best->status = STATUS_AUTHORIZED;
596 best->SendMap();
597
598 /* And update the rest. */
599 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
600 if (new_cs->status == STATUS_MAP_WAIT) new_cs->SendWait();
601 }
602 }
603 }
604
606 NetworkRecvStatus ServerNetworkGameSocketHandler::SendMap()
607 {
608 static uint sent_packets; // How many packets we did send successfully last time
609
610 if (this->status < STATUS_AUTHORIZED) {
611 /* Illegal call, return error and ignore the packet */
612 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
613 }
614
615 if (this->status == STATUS_AUTHORIZED) {
616 this->savegame = new PacketWriter(this);
617
618 /* Now send the _frame_counter and how many packets are coming */
619 Packet *p = new Packet(PACKET_SERVER_MAP_BEGIN);
620 p->Send_uint32(_frame_counter);
621 this->SendPacket(p);
622
623 NetworkSyncCommandQueue(this);
624 this->status = STATUS_MAP;
625 /* Mark the start of download */
626 this->last_frame = _frame_counter;
627 this->last_frame_server = _frame_counter;
628
629 sent_packets = 4; // We start with trying 4 packets
630
631 /* Make a dump of the current game */
632 if (SaveWithFilter(this->savegame, true) != SL_OK) usererror("network savedump failed");
633 }
634
635 if (this->status == STATUS_MAP) {
636 bool last_packet = false;
637 bool has_packets = false;
638
639 for (uint i = 0; (has_packets = this->savegame->HasPackets()) && i < sent_packets; i++) {
640 Packet *p = this->savegame->PopPacket();
641 last_packet = p->buffer[2] == PACKET_SERVER_MAP_DONE;
642
643 this->SendPacket(p);
644
645 if (last_packet) {
646 /* There is no more data, so break the for */
647 break;
648 }
649 }
650
651 if (last_packet) {
652 /* Done reading, make sure saving is done as well */
653 this->savegame->Destroy();
654 this->savegame = nullptr;
655
656 /* Set the status to DONE_MAP, no we will wait for the client
657 * to send it is ready (maybe that happens like never ;)) */
658 this->status = STATUS_DONE_MAP;
659
660 this->CheckNextClientToSendMap();
661 }
662
663 switch (this->SendPackets()) {
664 case SPS_CLOSED:
665 return NETWORK_RECV_STATUS_CONN_LOST;
666
667 case SPS_ALL_SENT:
668 /* All are sent, increase the sent_packets */
669 if (has_packets) sent_packets *= 2;
670 break;
671
672 case SPS_PARTLY_SENT:
673 /* Only a part is sent; leave the transmission state. */
674 break;
675
676 case SPS_NONE_SENT:
677 /* Not everything is sent, decrease the sent_packets */
678 if (sent_packets > 1) sent_packets /= 2;
679 break;
680 }
681 }
682 return NETWORK_RECV_STATUS_OKAY;
683 }
684
689 NetworkRecvStatus ServerNetworkGameSocketHandler::SendJoin(ClientID client_id)
690 {
691 Packet *p = new Packet(PACKET_SERVER_JOIN);
692
693 p->Send_uint32(client_id);
694
695 this->SendPacket(p);
696 return NETWORK_RECV_STATUS_OKAY;
697 }
698
700 NetworkRecvStatus ServerNetworkGameSocketHandler::SendFrame()
701 {
702 Packet *p = new Packet(PACKET_SERVER_FRAME);
703 p->Send_uint32(_frame_counter);
704 p->Send_uint32(_frame_counter_max);
705 #ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
706 p->Send_uint32(_sync_seed_1);
707 #ifdef NETWORK_SEND_DOUBLE_SEED
708 p->Send_uint32(_sync_seed_2);
709 #endif
710 #endif
711
712 /* If token equals 0, we need to make a new token and send that. */
713 if (this->last_token == 0) {
714 this->last_token = InteractiveRandomRange(UINT8_MAX - 1) + 1;
715 p->Send_uint8(this->last_token);
716 }
717
718 this->SendPacket(p);
719 return NETWORK_RECV_STATUS_OKAY;
720 }
721
723 NetworkRecvStatus ServerNetworkGameSocketHandler::SendSync()
724 {
725 Packet *p = new Packet(PACKET_SERVER_SYNC);
726 p->Send_uint32(_frame_counter);
727 p->Send_uint32(_sync_seed_1);
728
729 #ifdef NETWORK_SEND_DOUBLE_SEED
730 p->Send_uint32(_sync_seed_2);
731 #endif
732 this->SendPacket(p);
733 return NETWORK_RECV_STATUS_OKAY;
734 }
735
740 NetworkRecvStatus ServerNetworkGameSocketHandler::SendCommand(const CommandPacket *cp)
741 {
742 Packet *p = new Packet(PACKET_SERVER_COMMAND);
743
744 this->NetworkGameSocketHandler::SendCommand(p, cp);
745 p->Send_uint32(cp->frame);
746 p->Send_bool (cp->my_cmd);
747
748 this->SendPacket(p);
749 return NETWORK_RECV_STATUS_OKAY;
750 }
751
760 NetworkRecvStatus ServerNetworkGameSocketHandler::SendChat(NetworkAction action, ClientID client_id, bool self_send, const char *msg, int64 data)
761 {
762 if (this->status < STATUS_PRE_ACTIVE) return NETWORK_RECV_STATUS_OKAY;
763
764 Packet *p = new Packet(PACKET_SERVER_CHAT);
765
766 p->Send_uint8 (action);
767 p->Send_uint32(client_id);
768 p->Send_bool (self_send);
769 p->Send_string(msg);
770 p->Send_uint64(data);
771
772 this->SendPacket(p);
773 return NETWORK_RECV_STATUS_OKAY;
774 }
775
781 NetworkRecvStatus ServerNetworkGameSocketHandler::SendErrorQuit(ClientID client_id, NetworkErrorCode errorno)
782 {
783 Packet *p = new Packet(PACKET_SERVER_ERROR_QUIT);
784
785 p->Send_uint32(client_id);
786 p->Send_uint8 (errorno);
787
788 this->SendPacket(p);
789 return NETWORK_RECV_STATUS_OKAY;
790 }
791
796 NetworkRecvStatus ServerNetworkGameSocketHandler::SendQuit(ClientID client_id)
797 {
798 Packet *p = new Packet(PACKET_SERVER_QUIT);
799
800 p->Send_uint32(client_id);
801
802 this->SendPacket(p);
803 return NETWORK_RECV_STATUS_OKAY;
804 }
805
807 NetworkRecvStatus ServerNetworkGameSocketHandler::SendShutdown()
808 {
809 Packet *p = new Packet(PACKET_SERVER_SHUTDOWN);
810 this->SendPacket(p);
811 return NETWORK_RECV_STATUS_OKAY;
812 }
813
815 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGame()
816 {
817 Packet *p = new Packet(PACKET_SERVER_NEWGAME);
818 this->SendPacket(p);
819 return NETWORK_RECV_STATUS_OKAY;
820 }
821
827 NetworkRecvStatus ServerNetworkGameSocketHandler::SendRConResult(uint16 colour, const char *command)
828 {
829 Packet *p = new Packet(PACKET_SERVER_RCON);
830
831 p->Send_uint16(colour);
832 p->Send_string(command);
833 this->SendPacket(p);
834 return NETWORK_RECV_STATUS_OKAY;
835 }
836
842 NetworkRecvStatus ServerNetworkGameSocketHandler::SendMove(ClientID client_id, CompanyID company_id)
843 {
844 Packet *p = new Packet(PACKET_SERVER_MOVE);
845
846 p->Send_uint32(client_id);
847 p->Send_uint8(company_id);
848 this->SendPacket(p);
849 return NETWORK_RECV_STATUS_OKAY;
850 }
851
853 NetworkRecvStatus ServerNetworkGameSocketHandler::SendCompanyUpdate()
854 {
855 Packet *p = new Packet(PACKET_SERVER_COMPANY_UPDATE);
856
857 p->Send_uint16(_network_company_passworded);
858 this->SendPacket(p);
859 return NETWORK_RECV_STATUS_OKAY;
860 }
861
863 NetworkRecvStatus ServerNetworkGameSocketHandler::SendConfigUpdate()
864 {
865 Packet *p = new Packet(PACKET_SERVER_CONFIG_UPDATE);
866
867 p->Send_uint8(_settings_client.network.max_companies);
868 p->Send_uint8(_settings_client.network.max_spectators);
869 this->SendPacket(p);
870 return NETWORK_RECV_STATUS_OKAY;
871 }
872
873 /***********
874 * Receiving functions
875 * DEF_SERVER_RECEIVE_COMMAND has parameter: NetworkClientSocket *cs, Packet *p
876 ************/
877
878 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMPANY_INFO(Packet *p)
879 {
880 return this->SendCompanyInfo();
881 }
882
883 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_NEWGRFS_CHECKED(Packet *p)
884 {
885 if (this->status != STATUS_NEWGRFS_CHECK) {
886 /* Illegal call, return error and ignore the packet */
887 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
888 }
889
890 NetworkClientInfo *ci = this->GetInfo();
891
892 /* We now want a password from the client else we do not allow him in! */
893 if (!StrEmpty(_settings_client.network.server_password)) {
894 return this->SendNeedGamePassword();
895 }
896
897 if (Company::IsValidID(ci->client_playas) && !StrEmpty(_network_company_states[ci->client_playas].password)) {
898 return this->SendNeedCompanyPassword();
899 }
900
901 return this->SendWelcome();
902 }
903
904 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet *p)
905 {
906 if (this->status != STATUS_INACTIVE) {
907 /* Illegal call, return error and ignore the packet */
908 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
909 }
910
911 char name[NETWORK_CLIENT_NAME_LENGTH];
912 CompanyID playas;
913 NetworkLanguage client_lang;
914 char client_revision[NETWORK_REVISION_LENGTH];
915
916 p->Recv_string(client_revision, sizeof(client_revision));
917 uint32 newgrf_version = p->Recv_uint32();
918
919 /* Check if the client has revision control enabled */
920 if (!IsNetworkCompatibleVersion(client_revision) || _openttd_newgrf_version != newgrf_version) {
921 /* Different revisions!! */
922 return this->SendError(NETWORK_ERROR_WRONG_REVISION);
923 }
924
925 p->Recv_string(name, sizeof(name));
926 playas = (Owner)p->Recv_uint8();
927 client_lang = (NetworkLanguage)p->Recv_uint8();
928
929 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
930
931 /* join another company does not affect these values */
932 switch (playas) {
933 case COMPANY_NEW_COMPANY: // New company
934 if (Company::GetNumItems() >= _settings_client.network.max_companies) {
935 return this->SendError(NETWORK_ERROR_FULL);
936 }
937 break;
938 case COMPANY_SPECTATOR: // Spectator
939 if (NetworkSpectatorCount() >= _settings_client.network.max_spectators) {
940 return this->SendError(NETWORK_ERROR_FULL);
941 }
942 break;
943 default: // Join another company (companies 1-8 (index 0-7))
944 if (!Company::IsValidHumanID(playas)) {
945 return this->SendError(NETWORK_ERROR_COMPANY_MISMATCH);
946 }
947 break;
948 }
949
950 /* We need a valid name.. make it Player */
951 if (StrEmpty(name)) strecpy(name, "Player", lastof(name));
952
953 if (!NetworkFindName(name, lastof(name))) { // Change name if duplicate
954 /* We could not create a name for this client */
955 return this->SendError(NETWORK_ERROR_NAME_IN_USE);
956 }
957
958 assert(NetworkClientInfo::CanAllocateItem());
959 NetworkClientInfo *ci = new NetworkClientInfo(this->client_id);
960 this->SetInfo(ci);
961 ci->join_date = _date;
962 strecpy(ci->client_name, name, lastof(ci->client_name));
963 ci->client_playas = playas;
964 ci->client_lang = client_lang;
965 DEBUG(desync, 1, "client: %08x; %02x; %02x; %02x", _date, _date_fract, (int)ci->client_playas, (int)ci->index);
966
967 /* Make sure companies to which people try to join are not autocleaned */
968 if (Company::IsValidID(playas)) _network_company_states[playas].months_empty = 0;
969
970 this->status = STATUS_NEWGRFS_CHECK;
971
972 if (_grfconfig == nullptr) {
973 /* Behave as if we received PACKET_CLIENT_NEWGRFS_CHECKED */
974 return this->Receive_CLIENT_NEWGRFS_CHECKED(nullptr);
975 }
976
977 return this->SendNewGRFCheck();
978 }
979
980 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GAME_PASSWORD(Packet *p)
981 {
982 if (this->status != STATUS_AUTH_GAME) {
983 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
984 }
985
986 char password[NETWORK_PASSWORD_LENGTH];
987 p->Recv_string(password, sizeof(password));
988
989 /* Check game password. Allow joining if we cleared the password meanwhile */
990 if (!StrEmpty(_settings_client.network.server_password) &&
991 strcmp(password, _settings_client.network.server_password) != 0) {
992 /* Password is invalid */
993 return this->SendError(NETWORK_ERROR_WRONG_PASSWORD);
994 }
995
996 const NetworkClientInfo *ci = this->GetInfo();
997 if (Company::IsValidID(ci->client_playas) && !StrEmpty(_network_company_states[ci->client_playas].password)) {
998 return this->SendNeedCompanyPassword();
999 }
1000
1001 /* Valid password, allow user */
1002 return this->SendWelcome();
1003 }
1004
1005 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMPANY_PASSWORD(Packet *p)
1006 {
1007 if (this->status != STATUS_AUTH_COMPANY) {
1008 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1009 }
1010
1011 char password[NETWORK_PASSWORD_LENGTH];
1012 p->Recv_string(password, sizeof(password));
1013
1014 /* Check company password. Allow joining if we cleared the password meanwhile.
1015 * Also, check the company is still valid - client could be moved to spectators
1016 * in the middle of the authorization process */
1017 CompanyID playas = this->GetInfo()->client_playas;
1018 if (Company::IsValidID(playas) && !StrEmpty(_network_company_states[playas].password) &&
1019 strcmp(password, _network_company_states[playas].password) != 0) {
1020 /* Password is invalid */
1021 return this->SendError(NETWORK_ERROR_WRONG_PASSWORD);
1022 }
1023
1024 return this->SendWelcome();
1025 }
1026
1027 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GETMAP(Packet *p)
1028 {
1029 /* The client was never joined.. so this is impossible, right?
1030 * Ignore the packet, give the client a warning, and close his connection */
1031 if (this->status < STATUS_AUTHORIZED || this->HasClientQuit()) {
1032 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
1033 }
1034
1035 /* Check if someone else is receiving the map */
1036 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
1037 if (new_cs->status == STATUS_MAP) {
1038 /* Tell the new client to wait */
1039 this->status = STATUS_MAP_WAIT;
1040 return this->SendWait();
1041 }
1042 }
1043
1044 /* We receive a request to upload the map.. give it to the client! */
1045 return this->SendMap();
1046 }
1047
1048 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MAP_OK(Packet *p)
1049 {
1050 /* Client has the map, now start syncing */
1051 if (this->status == STATUS_DONE_MAP && !this->HasClientQuit()) {
1052 char client_name[NETWORK_CLIENT_NAME_LENGTH];
1053
1054 this->GetClientName(client_name, lastof(client_name));
1055
1056 NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, client_name, nullptr, this->client_id);
1057
1058 /* Mark the client as pre-active, and wait for an ACK
1059 * so we know he is done loading and in sync with us */
1060 this->status = STATUS_PRE_ACTIVE;
1061 NetworkHandleCommandQueue(this);
1062 this->SendFrame();
1063 this->SendSync();
1064
1065 /* This is the frame the client receives
1066 * we need it later on to make sure the client is not too slow */
1067 this->last_frame = _frame_counter;
1068 this->last_frame_server = _frame_counter;
1069
1070 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
1071 if (new_cs->status > STATUS_AUTHORIZED) {
1072 new_cs->SendClientInfo(this->GetInfo());
1073 new_cs->SendJoin(this->client_id);
1074 }
1075 }
1076
1077 NetworkAdminClientInfo(this, true);
1078
1079 /* also update the new client with our max values */
1080 this->SendConfigUpdate();
1081
1082 /* quickly update the syncing client with company details */
1083 return this->SendCompanyUpdate();
1084 }
1085
1086 /* Wrong status for this packet, give a warning to client, and close connection */
1087 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1088 }
1089
1094 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMMAND(Packet *p)
1095 {
1096 /* The client was never joined.. so this is impossible, right?
1097 * Ignore the packet, give the client a warning, and close his connection */
1098 if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
1099 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1100 }
1101
1102 if (this->incoming_queue.Count() >= _settings_client.network.max_commands_in_queue) {
1103 return this->SendError(NETWORK_ERROR_TOO_MANY_COMMANDS);
1104 }
1105
1106 CommandPacket cp;
1107 const char *err = this->ReceiveCommand(p, &cp);
1108
1109 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
1110
1111 NetworkClientInfo *ci = this->GetInfo();
1112
1113 if (err != nullptr) {
1114 IConsolePrintF(CC_ERROR, "WARNING: %s from client %d (IP: %s).", err, ci->client_id, this->GetClientIP());
1115 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1116 }
1117
1118
1119 if ((GetCommandFlags(cp.cmd) & CMD_SERVER) && ci->client_id != CLIENT_ID_SERVER) {
1120 IConsolePrintF(CC_ERROR, "WARNING: server only command %u from client %u (IP: %s), kicking...", cp.cmd & CMD_ID_MASK, ci->client_id, this->GetClientIP());
1121 return this->SendError(NETWORK_ERROR_KICKED);
1122 }
1123
1124 if ((GetCommandFlags(cp.cmd) & CMD_SPECTATOR) == 0 && !Company::IsValidID(cp.company) && ci->client_id != CLIENT_ID_SERVER) {
1125 IConsolePrintF(CC_ERROR, "WARNING: spectator (client: %u, IP: %s) issued non-spectator command %u, kicking...", ci->client_id, this->GetClientIP(), cp.cmd & CMD_ID_MASK);
1126 return this->SendError(NETWORK_ERROR_KICKED);
1127 }
1128
1134 if (!(cp.cmd == CMD_COMPANY_CTRL && cp.p1 == 0 && ci->client_playas == COMPANY_NEW_COMPANY) && ci->client_playas != cp.company) {
1135 IConsolePrintF(CC_ERROR, "WARNING: client %d (IP: %s) tried to execute a command as company %d, kicking...",
1136 ci->client_playas + 1, this->GetClientIP(), cp.company + 1);
1137 return this->SendError(NETWORK_ERROR_COMPANY_MISMATCH);
1138 }
1139
1140 if (cp.cmd == CMD_COMPANY_CTRL) {
1141 if (cp.p1 != 0 || cp.company != COMPANY_SPECTATOR) {
1142 return this->SendError(NETWORK_ERROR_CHEATER);
1143 }
1144
1145 /* 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! */
1146 if (Company::GetNumItems() >= _settings_client.network.max_companies) {
1147 NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_CLIENT, ci->client_id, "cannot create new company, server full", CLIENT_ID_SERVER);
1148 return NETWORK_RECV_STATUS_OKAY;
1149 }
1150 }
1151
1152 if (GetCommandFlags(cp.cmd) & CMD_CLIENT_ID) cp.p2 = this->client_id;
1153
1154 this->incoming_queue.Append(&cp);
1155 return NETWORK_RECV_STATUS_OKAY;
1156 }
1157
1158 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ERROR(Packet *p)
1159 {
1160 /* This packets means a client noticed an error and is reporting this
1161 * to us. Display the error and report it to the other clients */
1162 char str[100];
1163 char client_name[NETWORK_CLIENT_NAME_LENGTH];
1164 NetworkErrorCode errorno = (NetworkErrorCode)p->Recv_uint8();
1165
1166 /* The client was never joined.. thank the client for the packet, but ignore it */
1167 if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
1168 return this->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
1169 }
1170
1171 this->GetClientName(client_name, lastof(client_name));
1172
1173 StringID strid = GetNetworkErrorMsg(errorno);
1174 GetString(str, strid, lastof(str));
1175
1176 DEBUG(net, 2, "'%s' reported an error and is closing its connection (%s)", client_name, str);
1177
1178 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, nullptr, strid);
1179
1180 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
1181 if (new_cs->status > STATUS_AUTHORIZED) {
1182 new_cs->SendErrorQuit(this->client_id, errorno);
1183 }
1184 }
1185
1186 NetworkAdminClientError(this->client_id, errorno);
1187
1188 return this->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
1189 }
1190
1191 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_QUIT(Packet *p)
1192 {
1193 /* The client wants to leave. Display this and report it to the other
1194 * clients. */
1195 char client_name[NETWORK_CLIENT_NAME_LENGTH];
1196
1197 /* The client was never joined.. thank the client for the packet, but ignore it */
1198 if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
1199 return this->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
1200 }
1201
1202 this->GetClientName(client_name, lastof(client_name));
1203
1204 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, nullptr, STR_NETWORK_MESSAGE_CLIENT_LEAVING);
1205
1206 for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
1207 if (new_cs->status > STATUS_AUTHORIZED && new_cs != this) {
1208 new_cs->SendQuit(this->client_id);
1209 }
1210 }
1211
1212 NetworkAdminClientQuit(this->client_id);
1213
1214 return this->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
1215 }
1216
1217 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ACK(Packet *p)
1218 {
1219 if (this->status < STATUS_AUTHORIZED) {
1220 /* Illegal call, return error and ignore the packet */
1221 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
1222 }
1223
1224 uint32 frame = p->Recv_uint32();
1225
1226 /* The client is trying to catch up with the server */
1227 if (this->status == STATUS_PRE_ACTIVE) {
1228 /* The client is not yet caught up? */
1229 if (frame + DAY_TICKS < _frame_counter) return NETWORK_RECV_STATUS_OKAY;
1230
1231 /* Now he is! Unpause the game */
1232 this->status = STATUS_ACTIVE;
1233 this->last_token_frame = _frame_counter;
1234
1235 /* Execute script for, e.g. MOTD */
1236 IConsoleCmdExec("exec scripts/on_server_connect.scr 0");
1237 }
1238
1239 /* Get, and validate the token. */
1240 uint8 token = p->Recv_uint8();
1241 if (token == this->last_token) {
1242 /* We differentiate between last_token_frame and last_frame so the lag
1243 * test uses the actual lag of the client instead of the lag for getting
1244 * the token back and forth; after all, the token is only sent every
1245 * time we receive a PACKET_CLIENT_ACK, after which we will send a new
1246 * token to the client. If the lag would be one day, then we would not
1247 * be sending the new token soon enough for the new daily scheduled
1248 * PACKET_CLIENT_ACK. This would then register the lag of the client as
1249 * two days, even when it's only a single day. */
1250 this->last_token_frame = _frame_counter;
1251 /* Request a new token. */
1252 this->last_token = 0;
1253 }
1254
1255 /* The client received the frame, make note of it */
1256 this->last_frame = frame;
1257 /* With those 2 values we can calculate the lag realtime */
1258 this->last_frame_server = _frame_counter;
1259 return NETWORK_RECV_STATUS_OKAY;
1260 }
1261
1262
1273 void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, const char *msg, ClientID from_id, int64 data, bool from_admin)
1274 {
1275 const NetworkClientInfo *ci, *ci_own, *ci_to;
1276
1277 switch (desttype) {
1278 case DESTTYPE_CLIENT:
1279 /* Are we sending to the server? */
1280 if ((ClientID)dest == CLIENT_ID_SERVER) {
1281 ci = NetworkClientInfo::GetByClientID(from_id);
1282 /* Display the text locally, and that is it */
1283 if (ci != nullptr) {
1284 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
1285
1286 if (_settings_client.network.server_admin_chat) {
1287 NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
1288 }
1289 }
1290 } else {
1291 /* Else find the client to send the message to */
1292 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1293 if (cs->client_id == (ClientID)dest) {
1294 cs->SendChat(action, from_id, false, msg, data);
1295 break;
1296 }
1297 }
1298 }
1299
1300 /* Display the message locally (so you know you have sent it) */
1301 if (from_id != (ClientID)dest) {
1302 if (from_id == CLIENT_ID_SERVER) {
1303 ci = NetworkClientInfo::GetByClientID(from_id);
1304 ci_to = NetworkClientInfo::GetByClientID((ClientID)dest);
1305 if (ci != nullptr && ci_to != nullptr) {
1306 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), true, ci_to->client_name, msg, data);
1307 }
1308 } else {
1309 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1310 if (cs->client_id == from_id) {
1311 cs->SendChat(action, (ClientID)dest, true, msg, data);
1312 break;
1313 }
1314 }
1315 }
1316 }
1317 break;
1318 case DESTTYPE_TEAM: {
1319 /* If this is false, the message is already displayed on the client who sent it. */
1320 bool show_local = true;
1321 /* Find all clients that belong to this company */
1322 ci_to = nullptr;
1323 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1324 ci = cs->GetInfo();
1325 if (ci != nullptr && ci->client_playas == (CompanyID)dest) {
1326 cs->SendChat(action, from_id, false, msg, data);
1327 if (cs->client_id == from_id) show_local = false;
1328 ci_to = ci; // Remember a client that is in the company for company-name
1329 }
1330 }
1331
1332 /* if the server can read it, let the admin network read it, too. */
1333 if (_local_company == (CompanyID)dest && _settings_client.network.server_admin_chat) {
1334 NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
1335 }
1336
1337 ci = NetworkClientInfo::GetByClientID(from_id);
1338 ci_own = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
1339 if (ci != nullptr && ci_own != nullptr && ci_own->client_playas == dest) {
1340 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
1341 if (from_id == CLIENT_ID_SERVER) show_local = false;
1342 ci_to = ci_own;
1343 }
1344
1345 /* There is no such client */
1346 if (ci_to == nullptr) break;
1347
1348 /* Display the message locally (so you know you have sent it) */
1349 if (ci != nullptr && show_local) {
1350 if (from_id == CLIENT_ID_SERVER) {
1351 char name[NETWORK_NAME_LENGTH];
1352 StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
1353 SetDParam(0, ci_to->client_playas);
1354 GetString(name, str, lastof(name));
1355 NetworkTextMessage(action, GetDrawStringCompanyColour(ci_own->client_playas), true, name, msg, data);
1356 } else {
1357 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1358 if (cs->client_id == from_id) {
1359 cs->SendChat(action, ci_to->client_id, true, msg, data);
1360 }
1361 }
1362 }
1363 }
1364 break;
1365 }
1366 default:
1367 DEBUG(net, 0, "[server] received unknown chat destination type %d. Doing broadcast instead", desttype);
1368 FALLTHROUGH;
1369
1370 case DESTTYPE_BROADCAST:
1371 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1372 cs->SendChat(action, from_id, false, msg, data);
1373 }
1374
1375 NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
1376
1377 ci = NetworkClientInfo::GetByClientID(from_id);
1378 if (ci != nullptr) {
1379 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
1380 }
1381 break;
1382 }
1383 }
1384
1385 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_CHAT(Packet *p)
1386 {
1387 if (this->status < STATUS_PRE_ACTIVE) {
1388 /* Illegal call, return error and ignore the packet */
1389 return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
1390 }
1391
1392 NetworkAction action = (NetworkAction)p->Recv_uint8();
1393 DestType desttype = (DestType)p->Recv_uint8();
1394 int dest = p->Recv_uint32();
1395 char msg[NETWORK_CHAT_LENGTH];
1396
1397 p->Recv_string(msg, NETWORK_CHAT_LENGTH);
1398 int64 data = p->Recv_uint64();
1399
1400 NetworkClientInfo *ci = this->GetInfo();
1401 switch (action) {
1402 case NETWORK_ACTION_CHAT:
1403 case NETWORK_ACTION_CHAT_CLIENT:
1404 case NETWORK_ACTION_CHAT_COMPANY:
1405 NetworkServerSendChat(action, desttype, dest, msg, this->client_id, data);
1406 break;
1407 default:
1408 IConsolePrintF(CC_ERROR, "WARNING: invalid chat action from client %d (IP: %s).", ci->client_id, this->GetClientIP());
1409 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1410 }
1411 return NETWORK_RECV_STATUS_OKAY;
1412 }
1413
1414 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_PASSWORD(Packet *p)
1415 {
1416 if (this->status != STATUS_ACTIVE) {
1417 /* Illegal call, return error and ignore the packet */
1418 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1419 }
1420
1421 char password[NETWORK_PASSWORD_LENGTH];
1422 const NetworkClientInfo *ci;
1423
1424 p->Recv_string(password, sizeof(password));
1425 ci = this->GetInfo();
1426
1427 NetworkServerSetCompanyPassword(ci->client_playas, password);
1428 return NETWORK_RECV_STATUS_OKAY;
1429 }
1430
1431 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_NAME(Packet *p)
1432 {
1433 if (this->status != STATUS_ACTIVE) {
1434 /* Illegal call, return error and ignore the packet */
1435 return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1436 }
1437
1438 char client_name[NETWORK_CLIENT_NAME_LENGTH];
1439 NetworkClientInfo *ci;
1440
1441 p->Recv_string(client_name, sizeof(client_name));
1442 ci = this->GetInfo();
1443
1444 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
1445
1446 if (ci != nullptr) {
1447 /* Display change */
1448 if (NetworkFindName(client_name, lastof(client_name))) {
1449 NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, client_name);
1450 strecpy(ci->client_name, client_name, lastof(ci->client_name));
1451 NetworkUpdateClientInfo(ci->client_id);
1452 }
1453 }
1454 return NETWORK_RECV_STATUS_OKAY;
1455 }
1456
1457 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_RCON(Packet *p)
1458 {
1459 if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1460
1461 char pass[NETWORK_PASSWORD_LENGTH];
1462 char command[NETWORK_RCONCOMMAND_LENGTH];
1463
1464 if (StrEmpty(_settings_client.network.rcon_password)) return NETWORK_RECV_STATUS_OKAY;
1465
1466 p->Recv_string(pass, sizeof(pass));
1467 p->Recv_string(command, sizeof(command));
1468
1469 if (strcmp(pass, _settings_client.network.rcon_password) != 0) {
1470 DEBUG(net, 0, "[rcon] wrong password from client-id %d", this->client_id);
1471 return NETWORK_RECV_STATUS_OKAY;
1472 }
1473
1474 DEBUG(net, 0, "[rcon] client-id %d executed: '%s'", this->client_id, command);
1475
1476 _redirect_console_to_client = this->client_id;
1477 IConsoleCmdExec(command);
1478 _redirect_console_to_client = INVALID_CLIENT_ID;
1479 return NETWORK_RECV_STATUS_OKAY;
1480 }
1481
1482 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MOVE(Packet *p)
1483 {
1484 if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1485
1486 CompanyID company_id = (Owner)p->Recv_uint8();
1487
1488 /* Check if the company is valid, we don't allow moving to AI companies */
1489 if (company_id != COMPANY_SPECTATOR && !Company::IsValidHumanID(company_id)) return NETWORK_RECV_STATUS_OKAY;
1490
1491 /* Check if we require a password for this company */
1492 if (company_id != COMPANY_SPECTATOR && !StrEmpty(_network_company_states[company_id].password)) {
1493 /* we need a password from the client - should be in this packet */
1494 char password[NETWORK_PASSWORD_LENGTH];
1495 p->Recv_string(password, sizeof(password));
1496
1497 /* Incorrect password sent, return! */
1498 if (strcmp(password, _network_company_states[company_id].password) != 0) {
1499 DEBUG(net, 2, "[move] wrong password from client-id #%d for company #%d", this->client_id, company_id + 1);
1500 return NETWORK_RECV_STATUS_OKAY;
1501 }
1502 }
1503
1504 /* if we get here we can move the client */
1505 NetworkServerDoMove(this->client_id, company_id);
1506 return NETWORK_RECV_STATUS_OKAY;
1507 }
1508
1516 void NetworkSocketHandler::SendCompanyInformation(Packet *p, const Company *c, const NetworkCompanyStats *stats, uint max_len)
1517 {
1518 /* Grab the company name */
1519 char company_name[NETWORK_COMPANY_NAME_LENGTH];
1520 SetDParam(0, c->index);
1521
1522 assert(max_len <= lengthof(company_name));
1523 GetString(company_name, STR_COMPANY_NAME, company_name + max_len - 1);
1524
1525 /* Get the income */
1526 Money income = 0;
1527 if (_cur_year - 1 == c->inaugurated_year) {
1528 /* The company is here just 1 year, so display [2], else display[1] */
1529 for (uint i = 0; i < lengthof(c->yearly_expenses[2]); i++) {
1530 income -= c->yearly_expenses[2][i];
1531 }
1532 } else {
1533 for (uint i = 0; i < lengthof(c->yearly_expenses[1]); i++) {
1534 income -= c->yearly_expenses[1][i];
1535 }
1536 }
1537
1538 /* Send the information */
1539 p->Send_uint8 (c->index);
1540 p->Send_string(company_name);
1541 p->Send_uint32(c->inaugurated_year);
1542 p->Send_uint64(c->old_economy[0].company_value);
1543 p->Send_uint64(c->money);
1544 p->Send_uint64(income);
1545 p->Send_uint16(c->old_economy[0].performance_history);
1546
1547 /* Send 1 if there is a password for the company else send 0 */
1548 p->Send_bool (!StrEmpty(_network_company_states[c->index].password));
1549
1550 for (uint i = 0; i < NETWORK_VEH_END; i++) {
1551 p->Send_uint16(stats->num_vehicle[i]);
1552 }
1553
1554 for (uint i = 0; i < NETWORK_VEH_END; i++) {
1555 p->Send_uint16(stats->num_station[i]);
1556 }
1557
1558 p->Send_bool(c->is_ai);
1559 }
1560
1565 void NetworkPopulateCompanyStats(NetworkCompanyStats *stats)
1566 {
1567 memset(stats, 0, sizeof(*stats) * MAX_COMPANIES);
1568
1569 /* Go through all vehicles and count the type of vehicles */
1570 for (const Vehicle *v : Vehicle::Iterate()) {
1571 if (!Company::IsValidID(v->owner) || !v->IsPrimaryVehicle()) continue;
1572 byte type = 0;
1573 switch (v->type) {
1574 case VEH_TRAIN: type = NETWORK_VEH_TRAIN; break;
1575 case VEH_ROAD: type = RoadVehicle::From(v)->IsBus() ? NETWORK_VEH_BUS : NETWORK_VEH_LORRY; break;
1576 case VEH_AIRCRAFT: type = NETWORK_VEH_PLANE; break;
1577 case VEH_SHIP: type = NETWORK_VEH_SHIP; break;
1578 default: continue;
1579 }
1580 stats[v->owner].num_vehicle[type]++;
1581 }
1582
1583 /* Go through all stations and count the types of stations */
1584 for (const Station *s : Station::Iterate()) {
1585 if (Company::IsValidID(s->owner)) {
1586 NetworkCompanyStats *npi = &stats[s->owner];
1587
1588 if (s->facilities & FACIL_TRAIN) npi->num_station[NETWORK_VEH_TRAIN]++;
1589 if (s->facilities & FACIL_TRUCK_STOP) npi->num_station[NETWORK_VEH_LORRY]++;
1590 if (s->facilities & FACIL_BUS_STOP) npi->num_station[NETWORK_VEH_BUS]++;
1591 if (s->facilities & FACIL_AIRPORT) npi->num_station[NETWORK_VEH_PLANE]++;
1592 if (s->facilities & FACIL_DOCK) npi->num_station[NETWORK_VEH_SHIP]++;
1593 }
1594 }
1595 }
1596
1601 void NetworkUpdateClientInfo(ClientID client_id)
1602 {
1603 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1604
1605 if (ci == nullptr) return;
1606
1607 DEBUG(desync, 1, "client: %08x; %02x; %02x; %04x", _date, _date_fract, (int)ci->client_playas, client_id);
1608
1609 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1610 cs->SendClientInfo(ci);
1611 }
1612
1613 NetworkAdminClientUpdate(ci);
1614 }
1615
1617 static void NetworkCheckRestartMap()
1618 {
1619 if (_settings_client.network.restart_game_year != 0 && _cur_year >= _settings_client.network.restart_game_year) {
1620 DEBUG(net, 0, "Auto-restarting map. Year %d reached", _cur_year);
1621
1622 _settings_newgame.game_creation.generation_seed = GENERATE_NEW_SEED;
1623 switch(_file_to_saveload.abstract_ftype) {
1624 case FT_SAVEGAME:
1625 case FT_SCENARIO:
1626 _switch_mode = SM_LOAD_GAME;
1627 break;
1628
1629 case FT_HEIGHTMAP:
1630 _switch_mode = SM_START_HEIGHTMAP;
1631 break;
1632
1633 default:
1634 _switch_mode = SM_NEWGAME;
1635 }
1636 }
1637 }
1638
1645 static void NetworkAutoCleanCompanies()
1646 {
1647 bool clients_in_company[MAX_COMPANIES];
1648 int vehicles_in_company[MAX_COMPANIES];
1649
1650 if (!_settings_client.network.autoclean_companies) return;
1651
1652 memset(clients_in_company, 0, sizeof(clients_in_company));
1653
1654 /* Detect the active companies */
1655 for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1656 if (Company::IsValidID(ci->client_playas)) clients_in_company[ci->client_playas] = true;
1657 }
1658
1659 if (!_network_dedicated) {
1660 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
1661 if (Company::IsValidID(ci->client_playas)) clients_in_company[ci->client_playas] = true;
1662 }
1663
1664 if (_settings_client.network.autoclean_novehicles != 0) {
1665 memset(vehicles_in_company, 0, sizeof(vehicles_in_company));
1666
1667 for (const Vehicle *v : Vehicle::Iterate()) {
1668 if (!Company::IsValidID(v->owner) || !v->IsPrimaryVehicle()) continue;
1669 vehicles_in_company[v->owner]++;
1670 }
1671 }
1672
1673 /* Go through all the companies */
1674 for (const Company *c : Company::Iterate()) {
1675 /* Skip the non-active once */
1676 if (c->is_ai) continue;
1677
1678 if (!clients_in_company[c->index]) {
1679 /* The company is empty for one month more */
1680 _network_company_states[c->index].months_empty++;
1681
1682 /* Is the company empty for autoclean_unprotected-months, and is there no protection? */
1683 if (_settings_client.network.autoclean_unprotected != 0 && _network_company_states[c->index].months_empty > _settings_client.network.autoclean_unprotected && StrEmpty(_network_company_states[c->index].password)) {
1684 /* Shut the company down */
1685 DoCommandP(0, CCA_DELETE | c->index << 16 | CRR_AUTOCLEAN << 24, 0, CMD_COMPANY_CTRL);
1686 IConsolePrintF(CC_DEFAULT, "Auto-cleaned company #%d with no password", c->index + 1);
1687 }
1688 /* Is the company empty for autoclean_protected-months, and there is a protection? */
1689 if (_settings_client.network.autoclean_protected != 0 && _network_company_states[c->index].months_empty > _settings_client.network.autoclean_protected && !StrEmpty(_network_company_states[c->index].password)) {
1690 /* Unprotect the company */
1691 _network_company_states[c->index].password[0] = '\0';
1692 IConsolePrintF(CC_DEFAULT, "Auto-removed protection from company #%d", c->index + 1);
1693 _network_company_states[c->index].months_empty = 0;
1694 NetworkServerUpdateCompanyPassworded(c->index, false);
1695 }
1696 /* Is the company empty for autoclean_novehicles-months, and has no vehicles? */
1697 if (_settings_client.network.autoclean_novehicles != 0 && _network_company_states[c->index].months_empty > _settings_client.network.autoclean_novehicles && vehicles_in_company[c->index] == 0) {
1698 /* Shut the company down */
1699 DoCommandP(0, CCA_DELETE | c->index << 16 | CRR_AUTOCLEAN << 24, 0, CMD_COMPANY_CTRL);
1700 IConsolePrintF(CC_DEFAULT, "Auto-cleaned company #%d with no vehicles", c->index + 1);
1701 }
1702 } else {
1703 /* It is not empty, reset the date */
1704 _network_company_states[c->index].months_empty = 0;
1705 }
1706 }
1707 }
1708
1715 bool NetworkFindName(char *new_name, const char *last)
1716 {
1717 bool found_name = false;
1718 uint number = 0;
1719 char original_name[NETWORK_CLIENT_NAME_LENGTH];
1720
1721 strecpy(original_name, new_name, lastof(original_name));
1722
1723 while (!found_name) {
1724 found_name = true;
1725 for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1726 if (strcmp(ci->client_name, new_name) == 0) {
1727 /* Name already in use */
1728 found_name = false;
1729 break;
1730 }
1731 }
1732 /* Check if it is the same as the server-name */
1733 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
1734 if (ci != nullptr) {
1735 if (strcmp(ci->client_name, new_name) == 0) found_name = false; // name already in use
1736 }
1737
1738 if (!found_name) {
1739 /* Try a new name (<name> #1, <name> #2, and so on) */
1740
1741 /* Something's really wrong when there're more names than clients */
1742 if (number++ > MAX_CLIENTS) break;
1743 seprintf(new_name, last, "%s #%d", original_name, number);
1744 }
1745 }
1746
1747 return found_name;
1748 }
1749
1756 bool NetworkServerChangeClientName(ClientID client_id, const char *new_name)
1757 {
1758 /* Check if the name's already in use */
1759 for (NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1760 if (strcmp(ci->client_name, new_name) == 0) return false;
1761 }
1762
1763 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1764 if (ci == nullptr) return false;
1765
1766 NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, true, ci->client_name, new_name);
1767
1768 strecpy(ci->client_name, new_name, lastof(ci->client_name));
1769
1770 NetworkUpdateClientInfo(client_id);
1771 return true;
1772 }
1773
1780 void NetworkServerSetCompanyPassword(CompanyID company_id, const char *password, bool already_hashed)
1781 {
1782 if (!Company::IsValidHumanID(company_id)) return;
1783
1784 if (!already_hashed) {
1785 password = GenerateCompanyPasswordHash(password, _settings_client.network.network_id, _settings_game.game_creation.generation_seed);
1786 }
1787
1788 strecpy(_network_company_states[company_id].password, password, lastof(_network_company_states[company_id].password));
1789 NetworkServerUpdateCompanyPassworded(company_id, !StrEmpty(_network_company_states[company_id].password));
1790 }
1791
1796 static void NetworkHandleCommandQueue(NetworkClientSocket *cs)
1797 {
1798 CommandPacket *cp;
1799 while ((cp = cs->outgoing_queue.Pop()) != nullptr) {
1800 cs->SendCommand(cp);
1801 free(cp);
1802 }
1803 }
1804
1809 void NetworkServer_Tick(bool send_frame)
1810 {
1811 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1812 bool send_sync = false;
1813 #endif
1814
1815 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1816 if (_frame_counter >= _last_sync_frame + _settings_client.network.sync_freq) {
1817 _last_sync_frame = _frame_counter;
1818 send_sync = true;
1819 }
1820 #endif
1821
1822 /* Now we are done with the frame, inform the clients that they can
1823 * do their frame! */
1824 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1825 /* We allow a number of bytes per frame, but only to the burst amount
1826 * to be available for packet receiving at any particular time. */
1827 cs->receive_limit = std::min<int>(cs->receive_limit + _settings_client.network.bytes_per_frame,
1828 _settings_client.network.bytes_per_frame_burst);
1829
1830 /* Check if the speed of the client is what we can expect from a client */
1831 uint lag = NetworkCalculateLag(cs);
1832 switch (cs->status) {
1833 case NetworkClientSocket::STATUS_ACTIVE:
1834 if (lag > _settings_client.network.max_lag_time) {
1835 /* Client did still not report in within the specified limit. */
1836 IConsolePrintF(CC_ERROR, cs->last_packet + std::chrono::milliseconds(lag * MILLISECONDS_PER_TICK) > std::chrono::steady_clock::now() ?
1837 /* A packet was received in the last three game days, so the client is likely lagging behind. */
1838 "Client #%d is dropped because the client's game state is more than %d ticks behind" :
1839 /* No packet was received in the last three game days; sounds like a lost connection. */
1840 "Client #%d is dropped because the client did not respond for more than %d ticks",
1841 cs->client_id, lag);
1842 cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
1843 continue;
1844 }
1845
1846 /* Report once per time we detect the lag, and only when we
1847 * received a packet in the last 2 seconds. If we
1848 * did not receive a packet, then the client is not just
1849 * slow, but the connection is likely severed. Mentioning
1850 * frame_freq is not useful in this case. */
1851 if (lag > (uint)DAY_TICKS && cs->lag_test == 0 && cs->last_packet + std::chrono::seconds(2) > std::chrono::steady_clock::now()) {
1852 IConsolePrintF(CC_WARNING, "[%d] Client #%d is slow, try increasing [network.]frame_freq to a higher value!", _frame_counter, cs->client_id);
1853 cs->lag_test = 1;
1854 }
1855
1856 if (cs->last_frame_server - cs->last_token_frame >= _settings_client.network.max_lag_time) {
1857 /* This is a bad client! It didn't send the right token back within time. */
1858 IConsolePrintF(CC_ERROR, "Client #%d is dropped because it fails to send valid acks", cs->client_id);
1859 cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
1860 continue;
1861 }
1862 break;
1863
1864 case NetworkClientSocket::STATUS_INACTIVE:
1865 case NetworkClientSocket::STATUS_NEWGRFS_CHECK:
1866 case NetworkClientSocket::STATUS_AUTHORIZED:
1867 /* NewGRF check and authorized states should be handled almost instantly.
1868 * So give them some lee-way, likewise for the query with inactive. */
1869 if (lag > _settings_client.network.max_init_time) {
1870 IConsolePrintF(CC_ERROR, "Client #%d is dropped because it took longer than %d ticks to start the joining process", cs->client_id, _settings_client.network.max_init_time);
1871 cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
1872 continue;
1873 }
1874 break;
1875
1876 case NetworkClientSocket::STATUS_MAP_WAIT:
1877 /* Send every two seconds a packet to the client, to make sure
1878 * he knows the server is still there; just someone else is
1879 * still receiving the map. */
1880 if (std::chrono::steady_clock::now() > cs->last_packet + std::chrono::seconds(2)) {
1881 cs->SendWait();
1882 /* We need to reset the timer, as otherwise we will be
1883 * spamming the client. Strictly speaking this variable
1884 * tracks when we last received a packet from the client,
1885 * but as he is waiting, he will not send us any till we
1886 * start sending him data. */
1887 cs->last_packet = std::chrono::steady_clock::now();
1888 }
1889 break;
1890
1891 case NetworkClientSocket::STATUS_MAP:
1892 /* Downloading the map... this is the amount of time since starting the saving. */
1893 if (lag > _settings_client.network.max_download_time) {
1894 IConsolePrintF(CC_ERROR, "Client #%d is dropped because it took longer than %d ticks to download the map", cs->client_id, _settings_client.network.max_download_time);
1895 cs->SendError(NETWORK_ERROR_TIMEOUT_MAP);
1896 continue;
1897 }
1898 break;
1899
1900 case NetworkClientSocket::STATUS_DONE_MAP:
1901 case NetworkClientSocket::STATUS_PRE_ACTIVE:
1902 /* The map has been sent, so this is for loading the map and syncing up. */
1903 if (lag > _settings_client.network.max_join_time) {
1904 IConsolePrintF(CC_ERROR, "Client #%d is dropped because it took longer than %d ticks to join", cs->client_id, _settings_client.network.max_join_time);
1905 cs->SendError(NETWORK_ERROR_TIMEOUT_JOIN);
1906 continue;
1907 }
1908 break;
1909
1910 case NetworkClientSocket::STATUS_AUTH_GAME:
1911 case NetworkClientSocket::STATUS_AUTH_COMPANY:
1912 /* These don't block? */
1913 if (lag > _settings_client.network.max_password_time) {
1914 IConsolePrintF(CC_ERROR, "Client #%d is dropped because it took longer than %d ticks to enter the password", cs->client_id, _settings_client.network.max_password_time);
1915 cs->SendError(NETWORK_ERROR_TIMEOUT_PASSWORD);
1916 continue;
1917 }
1918 break;
1919
1920 case NetworkClientSocket::STATUS_END:
1921 /* Bad server/code. */
1922 NOT_REACHED();
1923 }
1924
1925 if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) {
1926 /* Check if we can send command, and if we have anything in the queue */
1927 NetworkHandleCommandQueue(cs);
1928
1929 /* Send an updated _frame_counter_max to the client */
1930 if (send_frame) cs->SendFrame();
1931
1932 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1933 /* Send a sync-check packet */
1934 if (send_sync) cs->SendSync();
1935 #endif
1936 }
1937 }
1938
1939 /* See if we need to advertise */
1940 NetworkUDPAdvertise();
1941 }
1942
1944 void NetworkServerYearlyLoop()
1945 {
1946 NetworkCheckRestartMap();
1947 NetworkAdminUpdate(ADMIN_FREQUENCY_ANUALLY);
1948 }
1949
1951 void NetworkServerMonthlyLoop()
1952 {
1953 NetworkAutoCleanCompanies();
1954 NetworkAdminUpdate(ADMIN_FREQUENCY_MONTHLY);
1955 if ((_cur_month % 3) == 0) NetworkAdminUpdate(ADMIN_FREQUENCY_QUARTERLY);
1956 }
1957
1959 void NetworkServerDailyLoop()
1960 {
1961 NetworkAdminUpdate(ADMIN_FREQUENCY_DAILY);
1962 if ((_date % 7) == 3) NetworkAdminUpdate(ADMIN_FREQUENCY_WEEKLY);
1963 }
1964
1969 const char *ServerNetworkGameSocketHandler::GetClientIP()
1970 {
1971 return this->client_address.GetHostname();
1972 }
1973
1975 void NetworkServerShowStatusToConsole()
1976 {
1977 static const char * const stat_str[] = {
1978 "inactive",
1979 "checking NewGRFs",
1980 "authorizing (server password)",
1981 "authorizing (company password)",
1982 "authorized",
1983 "waiting",
1984 "loading map",
1985 "map done",
1986 "ready",
1987 "active"
1988 };
1989 static_assert(lengthof(stat_str) == NetworkClientSocket::STATUS_END);
1990
1991 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1992 NetworkClientInfo *ci = cs->GetInfo();
1993 if (ci == nullptr) continue;
1994 uint lag = NetworkCalculateLag(cs);
1995 const char *status;
1996
1997 status = (cs->status < (ptrdiff_t)lengthof(stat_str) ? stat_str[cs->status] : "unknown");
1998 IConsolePrintF(CC_INFO, "Client #%1d name: '%s' status: '%s' frame-lag: %3d company: %1d IP: %s",
1999 cs->client_id, ci->client_name, status, lag,
2000 ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0),
2001 cs->GetClientIP());
2002 }
2003 }
2004
2008 void NetworkServerSendConfigUpdate()
2009 {
2010 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
2011 if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) cs->SendConfigUpdate();
2012 }
2013 }
2014
2020 void NetworkServerUpdateCompanyPassworded(CompanyID company_id, bool passworded)
2021 {
2022 if (NetworkCompanyIsPassworded(company_id) == passworded) return;
2023
2024 SB(_network_company_passworded, company_id, 1, !!passworded);
2025 SetWindowClassesDirty(WC_COMPANY);
2026
2027 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
2028 if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) cs->SendCompanyUpdate();
2029 }
2030
2031 NetworkAdminCompanyUpdate(Company::GetIfValid(company_id));
2032 }
2033
2040 void NetworkServerDoMove(ClientID client_id, CompanyID company_id)
2041 {
2042 /* Only allow non-dedicated servers and normal clients to be moved */
2043 if (client_id == CLIENT_ID_SERVER && _network_dedicated) return;
2044
2045 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
2046
2047 /* No need to waste network resources if the client is in the company already! */
2048 if (ci->client_playas == company_id) return;
2049
2050 ci->client_playas = company_id;
2051
2052 if (client_id == CLIENT_ID_SERVER) {
2053 SetLocalCompany(company_id);
2054 } else {
2055 NetworkClientSocket *cs = NetworkClientSocket::GetByClientID(client_id);
2056 /* When the company isn't authorized we can't move them yet. */
2057 if (cs->status < NetworkClientSocket::STATUS_AUTHORIZED) return;
2058 cs->SendMove(client_id, company_id);
2059 }
2060
2061 /* announce the client's move */
2062 NetworkUpdateClientInfo(client_id);
2063
2064 NetworkAction action = (company_id == COMPANY_SPECTATOR) ? NETWORK_ACTION_COMPANY_SPECTATOR : NETWORK_ACTION_COMPANY_JOIN;
2065 NetworkServerSendChat(action, DESTTYPE_BROADCAST, 0, "", client_id, company_id + 1);
2066 }
2067
2074 void NetworkServerSendRcon(ClientID client_id, TextColour colour_code, const char *string)
2075 {
2076 NetworkClientSocket::GetByClientID(client_id)->SendRConResult(colour_code, string);
2077 }
2078
2084 void NetworkServerKickClient(ClientID client_id, const char *reason)
2085 {
2086 if (client_id == CLIENT_ID_SERVER) return;
2087 NetworkClientSocket::GetByClientID(client_id)->SendError(NETWORK_ERROR_KICKED, reason);
2088 }
2089
2096 uint NetworkServerKickOrBanIP(ClientID client_id, bool ban, const char *reason)
2097 {
2098 return NetworkServerKickOrBanIP(NetworkClientSocket::GetByClientID(client_id)->GetClientIP(), ban, reason);
2099 }
2100
2107 uint NetworkServerKickOrBanIP(const char *ip, bool ban, const char *reason)
2108 {
2109 /* Add address to ban-list */
2110 if (ban) {
2111 bool contains = false;
2112 for (const auto &iter : _network_ban_list) {
2113 if (iter == ip) {
2114 contains = true;
2115 break;
2116 }
2117 }
2118 if (!contains) _network_ban_list.emplace_back(ip);
2119 }
2120
2121 uint n = 0;
2122
2123 /* There can be multiple clients with the same IP, kick them all but don't kill the server,
2124 * or the client doing the rcon. The latter can't be kicked because kicking frees closes
2125 * and subsequently free the connection related instances, which we would be reading from
2126 * and writing to after returning. So we would read or write data from freed memory up till
2127 * the segfault triggers. */
2128 for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
2129 if (cs->client_id == CLIENT_ID_SERVER) continue;
2130 if (cs->client_id == _redirect_console_to_client) continue;
2131 if (cs->client_address.IsInNetmask(ip)) {
2132 NetworkServerKickClient(cs->client_id, reason);
2133 n++;
2134 }
2135 }
2136
2137 return n;
2138 }
2139
2145 bool NetworkCompanyHasClients(CompanyID company)
2146 {
2147 for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
2148 if (ci->client_playas == company) return true;
2149 }
2150 return false;
2151 }
2152
2153
2159 void ServerNetworkGameSocketHandler::GetClientName(char *client_name, const char *last) const
2160 {
2161 const NetworkClientInfo *ci = this->GetInfo();
2162
2163 if (ci == nullptr || StrEmpty(ci->client_name)) {
2164 seprintf(client_name, last, "Client #%4d", this->client_id);
2165 } else {
2166 strecpy(client_name, ci->client_name, last);
2167 }
2168 }
2169
2173 void NetworkPrintClients()
2174 {
2175 for (NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
2176 if (_network_server) {
2177 IConsolePrintF(CC_INFO, "Client #%1d name: '%s' company: %1d IP: %s",
2178 ci->client_id,
2179 ci->client_name,
2180 ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0),
2181 ci->client_id == CLIENT_ID_SERVER ? "server" : NetworkClientSocket::GetByClientID(ci->client_id)->GetClientIP());
2182 } else {
2183 IConsolePrintF(CC_INFO, "Client #%1d name: '%s' company: %1d",
2184 ci->client_id,
2185 ci->client_name,
2186 ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0));
2187 }
2188 }
2189 }
2190
2196 void NetworkServerNewCompany(const Company *c, NetworkClientInfo *ci)
2197 {
2198 assert(c != nullptr);
2199
2200 if (!_network_server) return;
2201
2202 _network_company_states[c->index].months_empty = 0;
2203 _network_company_states[c->index].password[0] = '\0';
2204 NetworkServerUpdateCompanyPassworded(c->index, false);
2205
2206 if (ci != nullptr) {
2207 /* ci is nullptr when replaying, or for AIs. In neither case there is a client. */
2208 ci->client_playas = c->index;
2209 NetworkUpdateClientInfo(ci->client_id);
2210 NetworkSendCommand(0, 0, 0, CMD_RENAME_PRESIDENT, nullptr, ci->client_name, c->index);
2211 }
2212
2213 /* Announce new company on network. */
2214 NetworkAdminCompanyInfo(c, true);
2215
2216 if (ci != nullptr) {
2217 /* ci is nullptr when replaying, or for AIs. In neither case there is a client.
2218 We need to send Admin port update here so that they first know about the new company
2219 and then learn about a possibly joining client (see FS#6025) */
2220 NetworkServerSendChat(NETWORK_ACTION_COMPANY_NEW, DESTTYPE_BROADCAST, 0, "", ci->client_id, c->index + 1);
2221 }
2222 }
ServerNetworkGameSocketHandler::Receive_CLIENT_QUIT
NetworkRecvStatus Receive_CLIENT_QUIT(Packet *p) override
The client is quitting the game.
Definition: network_server.cpp:1191
VEH_AIRCRAFT
@ VEH_AIRCRAFT
Aircraft vehicle type.
Definition: vehicle_type.h:27
NetworkSettings::rcon_password
char rcon_password[NETWORK_PASSWORD_LENGTH]
password for rconsole (server side)
Definition: settings_type.h:267
NetworkCompanyStats::num_station
uint16 num_station[NETWORK_VEH_END]
How many stations are there of this type?
Definition: network_type.h:59
CompanyProperties::is_ai
bool is_ai
If true, the company is (also) controlled by the computer (a NoAI program).
Definition: company_base.h:94
NetworkCompanyStats
Simple calculated statistics of a company.
Definition: network_type.h:57
CommandContainer::cmd
uint32 cmd
command being executed.
Definition: command_type.h:483
DestType
DestType
Destination of our chat messages.
Definition: network_type.h:81
CC_INFO
static const TextColour CC_INFO
Colour for information lines.
Definition: console_type.h:26
NetworkSettings::max_password_time
uint16 max_password_time
maximum amount of time, in game ticks, a client may take to enter the password
Definition: settings_type.h:259
_frame_counter
uint32 _frame_counter
The current frame.
Definition: network.cpp:68
NetworkServerKickOrBanIP
uint NetworkServerKickOrBanIP(ClientID client_id, bool ban, const char *reason)
Ban, or kick, everyone joined from the given client's IP.
Definition: network_server.cpp:2096
GameCreationSettings::generation_seed
uint32 generation_seed
noise seed for world generation
Definition: settings_type.h:292
CompanyEconomyEntry::company_value
Money company_value
The value of the company.
Definition: company_base.h:27
FT_SCENARIO
@ FT_SCENARIO
old or new scenario
Definition: fileio_type.h:19
PACKET_SERVER_ERROR
@ PACKET_SERVER_ERROR
Server sending an error message to the client.
Definition: tcp_game.h:39
NetworkServerSendConfigUpdate
void NetworkServerSendConfigUpdate()
Send Config Update.
Definition: network_server.cpp:2008
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3220
NetworkAdminUpdate
void NetworkAdminUpdate(AdminUpdateFrequency freq)
Send (push) updates to the admin network as they have registered for these updates.
Definition: network_admin.cpp:1000
Packet::Recv_string
void Recv_string(char *buffer, size_t size, StringValidationSettings settings=SVS_REPLACE_WITH_QUESTION_MARK)
Reads a string till it finds a '\0' in the stream.
Definition: packet.cpp:286
INVALID_CLIENT_ID
@ INVALID_CLIENT_ID
Client is not part of anything.
Definition: network_type.h:40
NetworkSettings::max_spectators
uint8 max_spectators
maximum amount of spectators
Definition: settings_type.h:280
SM_START_HEIGHTMAP
@ SM_START_HEIGHTMAP
Load a heightmap and start a new game from it.
Definition: openttd.h:36
usererror
void CDECL usererror(const char *s,...)
Error handling for fatal user errors.
Definition: openttd.cpp:102
NetworkFindName
bool NetworkFindName(char *new_name, const char *last)
Check whether a name is unique, and otherwise try to make it unique.
Definition: network_server.cpp:1715
NetworkServerSetCompanyPassword
void NetworkServerSetCompanyPassword(CompanyID company_id, const char *password, bool already_hashed)
Set/Reset a company password on the server end.
Definition: network_server.cpp:1780
SM_LOAD_GAME
@ SM_LOAD_GAME
Load game, Play Scenario.
Definition: openttd.h:30
_network_game_info
NetworkServerGameInfo _network_game_info
Information about our game.
Definition: network.cpp:57
NetworkServerSendChat
void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, const char *msg, ClientID from_id, int64 data, bool from_admin)
Send an actual chat message.
Definition: network_server.cpp:1273
NetworkSettings::autoclean_unprotected
uint8 autoclean_unprotected
remove passwordless companies after this many months
Definition: settings_type.h:275
Pool::PoolItem<&_company_pool >::GetIfValid
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:340
NetworkServerShowStatusToConsole
void NetworkServerShowStatusToConsole()
Show the status message of all clients on the console.
Definition: network_server.cpp:1975
NetworkCheckRestartMap
static void NetworkCheckRestartMap()
Check if we want to restart the map.
Definition: network_server.cpp:1617
Packet::buffer
byte * buffer
The buffer of this packet, of basically variable length up to SEND_MTU.
Definition: packet.h:52
PacketWriter::cs
ServerNetworkGameSocketHandler * cs
Socket we are associated with.
Definition: network_server.cpp:57
NetworkSettings::max_clients
uint8 max_clients
maximum amount of clients
Definition: settings_type.h:279
PacketWriter::HasPackets
bool HasPackets()
Checks whether there are packets.
Definition: network_server.cpp:123
_cur_year
Year _cur_year
Current year, starting at 0.
Definition: date.cpp:26
NETWORK_NAME_LENGTH
static const uint NETWORK_NAME_LENGTH
The maximum length of the server name and map name, in bytes including '\0'.
Definition: config.h:40
lock
std::mutex lock
synchronization for playback status fields
Definition: win32_m.cpp:34
NetworkClientInfo::client_playas
CompanyID client_playas
As which company is this client playing (CompanyID)
Definition: network_base.h:27
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
CompanyProperties::inaugurated_year
Year inaugurated_year
Year of starting the company.
Definition: company_base.h:79
Station
Station data structure.
Definition: station_base.h:450
CommandQueue::Count
uint Count() const
Get the number of items in the queue.
Definition: tcp_game.h:145
_date_fract
DateFract _date_fract
Fractional part of the day.
Definition: date.cpp:29
PACKET_SERVER_CONFIG_UPDATE
@ PACKET_SERVER_CONFIG_UPDATE
Some network configuration important to the client changed.
Definition: tcp_game.h:111
_network_server
bool _network_server
network-server is active
Definition: network.cpp:53
_network_company_passworded
CompanyMask _network_company_passworded
Bitmask of the password status of all companies.
Definition: network.cpp:80
CRR_AUTOCLEAN
@ CRR_AUTOCLEAN
The company is removed due to autoclean.
Definition: company_type.h:57
NetworkAction
NetworkAction
Actions that can be used for NetworkTextMessage.
Definition: network_type.h:91
NetworkClientInfo::client_name
char client_name[NETWORK_CLIENT_NAME_LENGTH]
Name of the client.
Definition: network_base.h:25
CommandPacket::frame
uint32 frame
the frame in which this packet is executed
Definition: network_internal.h:154
SPS_CLOSED
@ SPS_CLOSED
The connection got closed.
Definition: tcp.h:22
NetworkGameSocketHandler::last_packet
std::chrono::steady_clock::time_point last_packet
Time we received the last frame.
Definition: tcp_game.h:522
WC_CLIENT_LIST
@ WC_CLIENT_LIST
Client list; Window numbers:
Definition: window_type.h:472
NetworkAdminChat
void NetworkAdminChat(NetworkAction action, DestType desttype, ClientID client_id, const char *msg, int64 data, bool from_admin)
Send chat to the admin network (if they did opt in for the respective update).
Definition: network_admin.cpp:921
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:227
ServerNetworkGameSocketHandler::Receive_CLIENT_COMPANY_INFO
NetworkRecvStatus Receive_CLIENT_COMPANY_INFO(Packet *p) override
Request company information (in detail).
Definition: network_server.cpp:878
NetworkGameSocketHandler::SetInfo
void SetInfo(NetworkClientInfo *info)
Sets the client info for this socket handler.
Definition: tcp_game.h:537
NetworkSettings::network_id
char network_id[NETWORK_SERVER_ID_LENGTH]
network ID for servers
Definition: settings_type.h:273
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:1414
NETWORK_CHAT_LENGTH
static const uint NETWORK_CHAT_LENGTH
The maximum length of a chat message, in bytes including '\0'.
Definition: config.h:50
WC_CLIENT_LIST_POPUP
@ WC_CLIENT_LIST_POPUP
Popup for the client list; Window numbers:
Definition: window_type.h:478
HasBit
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103
NetworkClientInfo::join_date
Date join_date
Gamedate the client has joined.
Definition: network_base.h:28
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:1645
ADMIN_FREQUENCY_DAILY
@ ADMIN_FREQUENCY_DAILY
The admin gets information about this on a daily basis.
Definition: tcp_admin.h:91
PACKET_SERVER_NEWGAME
@ PACKET_SERVER_NEWGAME
The server is preparing to start a new game.
Definition: tcp_game.h:114
NetworkCompanyState::password
char password[NETWORK_PASSWORD_LENGTH]
The password for the company.
Definition: network_type.h:65
NetworkPrintClients
void NetworkPrintClients()
Print all the clients to the console.
Definition: network_server.cpp:2173
SetLocalCompany
void SetLocalCompany(CompanyID new_company)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
Definition: company_cmd.cpp:102
NetworkTCPSocketHandler::sock
SOCKET sock
The socket currently connected to.
Definition: tcp.h:34
PacketWriter::Write
void Write(byte *buf, size_t size) override
Write a given number of bytes into the savegame.
Definition: network_server.cpp:166
ServerNetworkGameSocketHandler::last_token_frame
uint32 last_token_frame
The last frame we received the right token.
Definition: network_server.h:67
MAX_CLIENTS
static const uint MAX_CLIENTS
How many clients can we have.
Definition: network_type.h:16
TextColour
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
Definition: gfx_type.h:250
CommandContainer::p2
uint32 p2
parameter p2.
Definition: command_type.h:482
ServerNetworkGameSocketHandler::ReceivePacket
virtual Packet * ReceivePacket() override
Receives a packet for the given client.
Definition: network_server.cpp:243
NetworkGameSocketHandler::last_frame_server
uint32 last_frame_server
Last frame the server has executed.
Definition: tcp_game.h:520
DESTTYPE_TEAM
@ DESTTYPE_TEAM
Send message/notice to everyone playing the same company (Team)
Definition: network_type.h:83
GRFConfig::ident
GRFIdentifier ident
grfid and md5sum to uniquely identify newgrfs
Definition: newgrf_config.h:157
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:79
NetworkUDPAdvertise
void NetworkUDPAdvertise()
Register us to the master server This function checks if it needs to send an advertise.
Definition: network_udp.cpp:571
PACKET_SERVER_WAIT
@ PACKET_SERVER_WAIT
Server tells the client there are some people waiting for the map as well.
Definition: tcp_game.h:71
ServerNetworkGameSocketHandler::STATUS_MAP
@ STATUS_MAP
The client is downloading the map.
Definition: network_server.h:58
PACKET_SERVER_JOIN
@ PACKET_SERVER_JOIN
Tells clients that a new client has joined.
Definition: tcp_game.h:78
Company::IsValidHumanID
static bool IsValidHumanID(size_t index)
Is this company a valid company, not controlled by a NoAI program?
Definition: company_base.h:145
NetworkSyncCommandQueue
void NetworkSyncCommandQueue(NetworkClientSocket *cs)
Sync our local command queue to the command queue of the given socket.
Definition: network_command.cpp:179
ADMIN_FREQUENCY_MONTHLY
@ ADMIN_FREQUENCY_MONTHLY
The admin gets information about this on a monthly basis.
Definition: tcp_admin.h:93
ServerNetworkGameSocketHandler::STATUS_MAP_WAIT
@ STATUS_MAP_WAIT
The client is waiting as someone else is downloading the map.
Definition: network_server.h:57
NetworkServerMonthlyLoop
void NetworkServerMonthlyLoop()
Monthly "callback".
Definition: network_server.cpp:1951
NetworkSettings::autoclean_protected
uint8 autoclean_protected
remove the password from passworded companies after this many months
Definition: settings_type.h:276
ServerNetworkGameSocketHandler::receive_limit
int receive_limit
Amount of bytes that we can receive at this moment.
Definition: network_server.h:70
WC_COMPANY
@ WC_COMPANY
Company view; Window numbers:
Definition: window_type.h:362
GetNetworkErrorMsg
StringID GetNetworkErrorMsg(NetworkErrorCode err)
Retrieve the string id of an internal error number.
Definition: network.cpp:299
VEH_ROAD
@ VEH_ROAD
Road vehicle type.
Definition: vehicle_type.h:25
Vehicle
Vehicle data structure.
Definition: vehicle_base.h:222
NetworkCompanyState::months_empty
uint16 months_empty
How many months the company is empty.
Definition: network_type.h:66
_redirect_console_to_client
ClientID _redirect_console_to_client
If not invalid, redirect the console output to a client.
Definition: network.cpp:60
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:47
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
NetworkGameSocketHandler
Base socket handler for all TCP sockets.
Definition: tcp_game.h:149
GenerateCompanyPasswordHash
const char * GenerateCompanyPasswordHash(const char *password, const char *password_server_id, uint32 password_game_seed)
Hash the given password using server ID and game seed.
Definition: network.cpp:182
Packet::Send_uint8
void Send_uint8(uint8 data)
Package a 8 bits integer in the packet.
Definition: packet.cpp:96
NetworkLanguage
NetworkLanguage
Language ids for server_lang and client_lang.
Definition: network_internal.h:66
SetDParam
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings_func.h:199
SPS_ALL_SENT
@ SPS_ALL_SENT
All packets in the queue are sent.
Definition: tcp.h:25
GENERATE_NEW_SEED
static const uint32 GENERATE_NEW_SEED
Create a new random seed.
Definition: genworld.h:24
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:1048
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:845
CC_DEFAULT
static const TextColour CC_DEFAULT
Default colour of the console.
Definition: console_type.h:23
_frame_counter_max
uint32 _frame_counter_max
To where we may go with our clients.
Definition: network.cpp:67
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:1809
ServerNetworkGameSocketHandler::SendCommand
NetworkRecvStatus SendCommand(const CommandPacket *cp)
Send a command to the client to execute.
Definition: network_server.cpp:740
network_base.h
SmallMap< NetworkAddress, SOCKET >
PACKET_SERVER_MAP_SIZE
@ PACKET_SERVER_MAP_SIZE
Server tells the client what the (compressed) size of the map is.
Definition: tcp_game.h:73
ServerNetworkGameSocketHandler::SendRConResult
NetworkRecvStatus SendRConResult(uint16 colour, const char *command)
Send the result of a console action.
Definition: network_server.cpp:827
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:816
GameSettings::game_creation
GameCreationSettings game_creation
settings used during the creation of a game (map)
Definition: settings_type.h:560
PacketWriter::Finish
void Finish() override
Prepare everything to finish writing the savegame.
Definition: network_server.cpp:191
Packet::Send_uint32
void Send_uint32(uint32 data)
Package a 32 bits integer in the packet.
Definition: packet.cpp:117
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:75
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:270
NetworkTCPSocketHandler::ReceivePacket
virtual Packet * ReceivePacket()
Receives a packet for the given client.
Definition: tcp.cpp:145
NetworkSettings::max_download_time
uint16 max_download_time
maximum amount of time, in game ticks, a client may take to download the map
Definition: settings_type.h:258
CommandQueue::Append
void Append(CommandPacket *p)
Append a CommandPacket at the end of the queue.
Definition: network_command.cpp:57
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:119
ADMIN_FREQUENCY_QUARTERLY
@ ADMIN_FREQUENCY_QUARTERLY
The admin gets information about this on a quarterly basis.
Definition: tcp_admin.h:94
ServerNetworkGameSocketHandler::Receive_CLIENT_COMPANY_PASSWORD
NetworkRecvStatus Receive_CLIENT_COMPANY_PASSWORD(Packet *p) override
Send a password to the server to authorize uint8 Password type (see NetworkPasswordType).
Definition: network_server.cpp:1005
PacketWriter::PrependQueue
void PrependQueue()
Prepend the current packet to the queue.
Definition: network_server.cpp:157
CommandPacket::company
CompanyID company
company that is executing the command
Definition: network_internal.h:153
FileToSaveLoad::abstract_ftype
AbstractFileType abstract_ftype
Abstract type of file (scenario, heightmap, etc).
Definition: saveload.h:342
NetworkClientInfo::client_lang
byte client_lang
The language of the client.
Definition: network_base.h:26
FACIL_BUS_STOP
@ FACIL_BUS_STOP
Station with bus stops.
Definition: station_type.h:54
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:883
TCPListenHandler
Template for TCP listeners.
Definition: tcp_listen.h:28
ServerNetworkGameSocketHandler::~ServerNetworkGameSocketHandler
~ServerNetworkGameSocketHandler()
Clear everything related to this client.
Definition: network_server.cpp:232
CommandContainer::p1
uint32 p1
parameter p1.
Definition: command_type.h:481
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:264
ServerNetworkGameSocketHandler::STATUS_INACTIVE
@ STATUS_INACTIVE
The client is not connected nor active.
Definition: network_server.h:52
ServerNetworkGameSocketHandler::Send
static void Send()
Send the packets for the server sockets.
Definition: network_server.cpp:330
NetworkCompanyStats::num_vehicle
uint16 num_vehicle[NETWORK_VEH_END]
How many vehicles are there of this type?
Definition: network_type.h:58
Packet::Recv_uint32
uint32 Recv_uint32()
Read a 32 bits integer from the packet.
Definition: packet.cpp:246
NetworkSettings::server_password
char server_password[NETWORK_PASSWORD_LENGTH]
password for joining this server
Definition: settings_type.h:266
NETWORK_RECV_STATUS_CONN_LOST
@ NETWORK_RECV_STATUS_CONN_LOST
The connection is 'just' lost.
Definition: core.h:27
PACKET_SERVER_NEED_GAME_PASSWORD
@ PACKET_SERVER_NEED_GAME_PASSWORD
Server requests the (hashed) game password.
Definition: tcp_game.h:60
NETWORK_CLIENTS_LENGTH
static const uint NETWORK_CLIENTS_LENGTH
The maximum length for the list of clients that controls a company, in bytes including '\0'.
Definition: config.h:46
PacketWriter
Writing a savegame directly to a number of packets.
Definition: network_server.cpp:56
NetworkServerUpdateCompanyPassworded
void NetworkServerUpdateCompanyPassworded(CompanyID company_id, bool passworded)
Tell that a particular company is (not) passworded.
Definition: network_server.cpp:2020
CompanyEconomyEntry::performance_history
int32 performance_history
Company score (scale 0-1000)
Definition: company_base.h:26
CommandPacket
Everything we need to know about a command to be able to execute it.
Definition: network_internal.h:149
_date
Date _date
Current date in days (day counter)
Definition: date.cpp:28
ServerNetworkGameSocketHandler::SendSync
NetworkRecvStatus SendSync()
Request the client to sync.
Definition: network_server.cpp:723
GRFConfig
Information about GRF, used in the game and (part of it) in savegames.
Definition: newgrf_config.h:152
PACKET_SERVER_SHUTDOWN
@ PACKET_SERVER_SHUTDOWN
The server is shutting down.
Definition: tcp_game.h:115
DoCommandP
bool DoCommandP(const CommandContainer *container, bool my_cmd)
Shortcut for the long DoCommandP when having a container with the data.
Definition: command.cpp:541
PACKET_SERVER_NEED_COMPANY_PASSWORD
@ PACKET_SERVER_NEED_COMPANY_PASSWORD
Server requests the (hashed) company password.
Definition: tcp_game.h:62
ServerNetworkGameSocketHandler::SendConfigUpdate
NetworkRecvStatus SendConfigUpdate()
Send an update about the max company/spectator counts.
Definition: network_server.cpp:863
SM_NEWGAME
@ SM_NEWGAME
New Game --> 'Random game'.
Definition: openttd.h:26
Pool::MAX_SIZE
static const size_t MAX_SIZE
Make template parameter accessible from outside.
Definition: pool_type.hpp:85
DEBUG
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:35
NetworkHandleCommandQueue
static void NetworkHandleCommandQueue(NetworkClientSocket *cs)
Handle the command-queue of a socket.
Definition: network_server.cpp:1796
NetworkSettings::bytes_per_frame
uint16 bytes_per_frame
how many bytes may, over a long period, be received per frame?
Definition: settings_type.h:254
Packet::Send_string
void Send_string(const char *data)
Sends a string over the network.
Definition: packet.cpp:148
NetworkAddress::GetHostname
const char * GetHostname()
Get the hostname; in case it wasn't given the IPv4 dotted representation is given.
Definition: address.cpp:22
NETWORK_RECV_STATUS_SERVER_ERROR
@ NETWORK_RECV_STATUS_SERVER_ERROR
The server told us we made an error.
Definition: core.h:29
PACKET_SERVER_COMPANY_UPDATE
@ PACKET_SERVER_COMPANY_UPDATE
Information (password) of a company changed.
Definition: tcp_game.h:110
GRFConfig::flags
uint8 flags
NOSAVE: GCF_Flags, bitset.
Definition: newgrf_config.h:167
NetworkSettings::restart_game_year
Year restart_game_year
year the server restarts
Definition: settings_type.h:281
SB
static T SB(T &x, const uint8 s, const uint8 n, const U d)
Set n bits in x starting at bit s to d.
Definition: bitmath_func.hpp:58
ClientID
ClientID
'Unique' identifier to be given to clients
Definition: network_type.h:39
CompanyProperties::money
Money money
Money owned by the company.
Definition: company_base.h:66
NetworkSocketHandler::SendGRFIdentifier
void SendGRFIdentifier(Packet *p, const GRFIdentifier *grf)
Serializes the GRFIdentifier (GRF ID and MD5 checksum) to the packet.
Definition: core.cpp:57
Packet::size
PacketSize size
The size of the whole packet for received packets.
Definition: packet.h:48
PACKET_SERVER_BANNED
@ PACKET_SERVER_BANNED
The server has banned you.
Definition: tcp_game.h:35
SEND_MTU
static const uint16 SEND_MTU
Number of bytes we can pack in a single packet.
Definition: config.h:33
ServerNetworkGameSocketHandler::SendMove
NetworkRecvStatus SendMove(ClientID client_id, CompanyID company_id)
Tell that a client moved to another company.
Definition: network_server.cpp:842
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:904
ServerNetworkGameSocketHandler::SendJoin
NetworkRecvStatus SendJoin(ClientID client_id)
Tell that a client joined.
Definition: network_server.cpp:689
IsNetworkCompatibleVersion
bool IsNetworkCompatibleVersion(const char *other)
Checks whether the given version string is compatible with our version.
Definition: network.cpp:1147
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:80
_sync_seed_1
uint32 _sync_seed_1
Seed to compare during sync checks.
Definition: network.cpp:71
ServerNetworkGameSocketHandler::SendFrame
NetworkRecvStatus SendFrame()
Tell the client that they may run to a particular frame.
Definition: network_server.cpp:700
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:46
PacketWriter::PopPacket
Packet * PopPacket()
Pop a single created packet from the queue with packets.
Definition: network_server.cpp:131
NetworkServerSendRcon
void NetworkServerSendRcon(ClientID client_id, TextColour colour_code, const char *string)
Send an rcon reply to the client.
Definition: network_server.cpp:2074
CMD_CLIENT_ID
@ CMD_CLIENT_ID
set p2 with the ClientID of the sending client.
Definition: command_type.h:398
PacketWriter::total_size
size_t total_size
Total size of the compressed savegame.
Definition: network_server.cpp:59
Packet::Send_uint16
void Send_uint16(uint16 data)
Package a 16 bits integer in the packet.
Definition: packet.cpp:106
NetworkTCPSocketHandler::SendPacket
virtual void SendPacket(Packet *packet)
This function puts the packet in the send-queue and it is send as soon as possible.
Definition: tcp.cpp:61
CLIENT_ID_SERVER
@ CLIENT_ID_SERVER
Servers always have this ID.
Definition: network_type.h:41
_network_company_states
NetworkCompanyState * _network_company_states
Statistics about some companies.
Definition: network.cpp:58
StrEmpty
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:60
ServerNetworkGameSocketHandler::SendCompanyUpdate
NetworkRecvStatus SendCompanyUpdate()
Send an update about the company password states.
Definition: network_server.cpp:853
ServerNetworkGameSocketHandler::SendWelcome
NetworkRecvStatus SendWelcome()
Send the client a welcome message with some basic information.
Definition: network_server.cpp:531
_network_client_id
static ClientID _network_client_id
The identifier counter for new clients (is never decreased)
Definition: network_server.cpp:41
ServerNetworkGameSocketHandler::Receive_CLIENT_MOVE
NetworkRecvStatus Receive_CLIENT_MOVE(Packet *p) override
Request the server to move this client into another company: uint8 ID of the company the client wants...
Definition: network_server.cpp:1482
Packet::next
Packet * next
The next packet.
Definition: packet.h:42
CommandPacket::my_cmd
bool my_cmd
did the command originate from "me"
Definition: network_internal.h:155
CompanyProperties::yearly_expenses
Money yearly_expenses[3][EXPENSES_END]
Expenses of the company for the last three years, in every ExpensesType category.
Definition: company_base.h:96
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:1565
FACIL_DOCK
@ FACIL_DOCK
Station with a dock.
Definition: station_type.h:56
network_server.h
_network_dedicated
bool _network_dedicated
are we a dedicated server?
Definition: network.cpp:55
ServerNetworkGameSocketHandler::savegame
struct PacketWriter * savegame
Writer used to write the savegame.
Definition: network_server.h:72
Packet
Internal entity of a packet.
Definition: packet.h:40
NetworkSettings::max_join_time
uint16 max_join_time
maximum amount of time, in game ticks, a client may take to sync up during joining
Definition: settings_type.h:257
NETWORK_COMPANY_INFO_VERSION
static const byte NETWORK_COMPANY_INFO_VERSION
What version of company info is this?
Definition: config.h:37
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:353
NetworkGameSocketHandler::ReceiveCommand
const char * ReceiveCommand(Packet *p, CommandPacket *cp)
Receives a command from the network.
Definition: network_command.cpp:296
GetCommandFlags
CommandFlags GetCommandFlags(uint32 cmd)
Definition: command.cpp:393
ADMIN_FREQUENCY_ANUALLY
@ ADMIN_FREQUENCY_ANUALLY
The admin gets information about this on a yearly basis.
Definition: tcp_admin.h:95
NETWORK_REVISION_LENGTH
static const uint NETWORK_REVISION_LENGTH
The maximum length of the revision, in bytes including '\0'.
Definition: config.h:44
PACKET_SERVER_COMPANY_INFO
@ PACKET_SERVER_COMPANY_INFO
Information about a single company.
Definition: tcp_game.h:43
ServerNetworkGameSocketHandler::STATUS_DONE_MAP
@ STATUS_DONE_MAP
The client has downloaded the map.
Definition: network_server.h:59
ServerNetworkGameSocketHandler::GetClientIP
const char * GetClientIP()
Get the IP address/hostname of the connected client.
Definition: network_server.cpp:1969
NetworkCompanyIsPassworded
bool NetworkCompanyIsPassworded(CompanyID company_id)
Check if the company we want to join requires a password.
Definition: network.cpp:213
ServerNetworkGameSocketHandler::SendQuit
NetworkRecvStatus SendQuit(ClientID client_id)
Tell the client another client quit.
Definition: network_server.cpp:796
NetworkClientInfo::client_id
ClientID client_id
Client identifier (same as ClientState->client_id)
Definition: network_base.h:24
PACKET_SERVER_MOVE
@ PACKET_SERVER_MOVE
Server tells everyone that someone is moved to another company.
Definition: tcp_game.h:105
NetworkServerDailyLoop
void NetworkServerDailyLoop()
Daily "callback".
Definition: network_server.cpp:1959
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:45
PACKET_SERVER_FULL
@ PACKET_SERVER_FULL
The server is full and has no place for you.
Definition: tcp_game.h:34
NetworkServerChangeClientName
bool NetworkServerChangeClientName(ClientID client_id, const char *new_name)
Change the client name of the given client.
Definition: network_server.cpp:1756
Packet::Send_bool
void Send_bool(bool data)
Package a boolean in the packet.
Definition: packet.cpp:87
SlError
void NORETURN SlError(StringID string, const char *extra_msg)
Error handler.
Definition: saveload.cpp:326
NetworkAdminCompanyUpdate
void NetworkAdminCompanyUpdate(const Company *company)
Notify the admin network of company updates.
Definition: network_admin.cpp:894
SPS_NONE_SENT
@ SPS_NONE_SENT
The buffer is still full, so no (parts of) packets could be sent.
Definition: tcp.h:23
ServerNetworkGameSocketHandler::SendErrorQuit
NetworkRecvStatus SendErrorQuit(ClientID client_id, NetworkErrorCode errorno)
Tell the client another client quit with an error.
Definition: network_server.cpp:781
NetworkServerNewCompany
void NetworkServerNewCompany(const Company *c, NetworkClientInfo *ci)
Perform all the server specific administration of a new company.
Definition: network_server.cpp:2196
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:547
_switch_mode
SwitchMode _switch_mode
The next mainloop command.
Definition: gfx.cpp:46
StringID
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
PacketWriter::AppendQueue
void AppendQueue()
Append the current packet to the queue.
Definition: network_server.cpp:143
NetworkSocketHandler::HasClientQuit
bool HasClientQuit() const
Whether the current client connected to the socket has quit.
Definition: core.h:67
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:1094
NetworkTCPSocketHandler::SendPackets
SendPacketsState SendPackets(bool closing_down=false)
Sends all the buffered packets out for this client.
Definition: tcp.cpp:95
NETWORK_RCONCOMMAND_LENGTH
static const uint NETWORK_RCONCOMMAND_LENGTH
The maximum length of a rconsole command, in bytes including '\0'.
Definition: config.h:48
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:2040
Pool::PoolItem<&_company_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:378
Pool
Base class for all pools.
Definition: pool_type.hpp:81
DeleteWindowById
void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
Delete a window by its class and window number (if it is open).
Definition: window.cpp:1165
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:1431
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:121
Pool::PoolItem<&_company_pool >::GetNumItems
static size_t GetNumItems()
Returns number of valid items in the pool.
Definition: pool_type.hpp:359
ServerNetworkGameSocketHandler::SendNewGame
NetworkRecvStatus SendNewGame()
Tell the client we're starting a new game.
Definition: network_server.cpp:815
FACIL_TRAIN
@ FACIL_TRAIN
Station with train station.
Definition: station_type.h:52
CMD_ID_MASK
@ CMD_ID_MASK
mask for the command ID
Definition: command_type.h:382
network_udp.h
PacketWriter::~PacketWriter
~PacketWriter()
Make sure everything is cleaned up.
Definition: network_server.cpp:73
PacketSize
uint16 PacketSize
Size of the whole packet.
Definition: packet.h:19
SpecializedVehicle< RoadVehicle, Type >::From
static RoadVehicle * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Definition: vehicle_base.h:1162
Packet::Send_uint64
void Send_uint64(uint64 data)
Package a 64 bits integer in the packet.
Definition: packet.cpp:130
NetworkSendCommand
void NetworkSendCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback, const char *text, CompanyID company)
Prepare a DoCommand to be send over the network.
Definition: network_command.cpp:136
SaveFilter
Interface for filtering a savegame till it is written.
Definition: saveload_filter.h:60
GetDrawStringCompanyColour
TextColour GetDrawStringCompanyColour(CompanyID company)
Get the colour for DrawString-subroutines which matches the colour of the company.
Definition: company_cmd.cpp:131
NetworkSettings::bytes_per_frame_burst
uint16 bytes_per_frame_burst
how many bytes may, over a short period, be received?
Definition: settings_type.h:255
COMPANY_SPECTATOR
@ COMPANY_SPECTATOR
The client is spectating.
Definition: company_type.h:35
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:91
_file_to_saveload
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Definition: saveload.cpp:62
GRFConfig::next
struct GRFConfig * next
NOSAVE: Next item in the linked list.
Definition: newgrf_config.h:177
ServerNetworkGameSocketHandler::SendChat
NetworkRecvStatus SendChat(NetworkAction action, ClientID client_id, bool self_send, const char *msg, int64 data)
Send a chat message.
Definition: network_server.cpp:760
ServerNetworkGameSocketHandler::STATUS_NEWGRFS_CHECK
@ STATUS_NEWGRFS_CHECK
The client is checking NewGRFs.
Definition: network_server.h:53
SaveWithFilter
SaveOrLoadResult SaveWithFilter(SaveFilter *writer, bool threaded)
Save the game using a (writer) filter.
Definition: saveload.cpp:2586
ServerNetworkGameSocketHandler::AllowConnection
static bool AllowConnection()
Whether an connection is allowed or not at this moment.
Definition: network_server.cpp:317
ServerNetworkGameSocketHandler::Receive_CLIENT_GETMAP
NetworkRecvStatus Receive_CLIENT_GETMAP(Packet *p) override
Request the map from the server.
Definition: network_server.cpp:1027
NetworkSettings::max_init_time
uint16 max_init_time
maximum amount of time, in game ticks, a client may take to initiate joining
Definition: settings_type.h:256
PACKET_SERVER_SYNC
@ PACKET_SERVER_SYNC
Server tells the client what the random state should be.
Definition: tcp_game.h:89
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:299
ServerNetworkGameSocketHandler::SendMap
NetworkRecvStatus SendMap()
This sends the map to the client.
Definition: network_server.cpp:606
seprintf
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:442
FT_HEIGHTMAP
@ FT_HEIGHTMAP
heightmap file
Definition: fileio_type.h:20
PACKET_SERVER_MAP_BEGIN
@ PACKET_SERVER_MAP_BEGIN
Server tells the client that it is beginning to send the map.
Definition: tcp_game.h:72
Packet::Recv_uint8
uint8 Recv_uint8()
Read a 8 bits integer from the packet.
Definition: packet.cpp:217
ServerNetworkGameSocketHandler::SendNewGRFCheck
NetworkRecvStatus SendNewGRFCheck()
Send the check for the NewGRFs.
Definition: network_server.cpp:479
CC_ERROR
static const TextColour CC_ERROR
Colour for error lines.
Definition: console_type.h:24
ServerNetworkGameSocketHandler::STATUS_AUTH_COMPANY
@ STATUS_AUTH_COMPANY
The client is authorizing with company password.
Definition: network_server.h:55
CMD_COMPANY_CTRL
@ CMD_COMPANY_CTRL
used in multiplayer to create a new companies etc.
Definition: command_type.h:281
PACKET_SERVER_CHAT
@ PACKET_SERVER_CHAT
Server distributing the message of a client (or itself).
Definition: tcp_game.h:97
INSTANTIATE_POOL_METHODS
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
Definition: pool_func.hpp:224
PACKET_SERVER_RCON
@ PACKET_SERVER_RCON
Response of the executed command on the server.
Definition: tcp_game.h:101
PACKET_SERVER_QUIT
@ PACKET_SERVER_QUIT
A server tells that a client has quit.
Definition: tcp_game.h:119
ServerNetworkGameSocketHandler::SendNeedGamePassword
NetworkRecvStatus SendNeedGamePassword()
Request the game password.
Definition: network_server.cpp:499
NetworkGameSocketHandler::incoming_queue
CommandQueue incoming_queue
The command-queue awaiting handling.
Definition: tcp_game.h:521
error
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
Definition: openttd.cpp:131
NetworkGameSocketHandler::client_id
ClientID client_id
Client identifier.
Definition: tcp_game.h:518
_grfconfig
GRFConfig * _grfconfig
First item in list of current GRF set up.
Definition: newgrf_config.cpp:170
PacketWriter::PacketWriter
PacketWriter(ServerNetworkGameSocketHandler *cs)
Create the packet writer.
Definition: network_server.cpp:68
MILLISECONDS_PER_TICK
static const uint MILLISECONDS_PER_TICK
The number of milliseconds per game tick.
Definition: gfx_type.h:310
PACKET_SERVER_COMMAND
@ PACKET_SERVER_COMMAND
Server distributes a command to (all) the clients.
Definition: tcp_game.h:93
ServerNetworkGameSocketHandler::Receive_CLIENT_ACK
NetworkRecvStatus Receive_CLIENT_ACK(Packet *p) override
Tell the server we are done with this frame: uint32 Current frame counter of the client.
Definition: network_server.cpp:1217
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:832
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:87
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:367
_network_ban_list
StringList _network_ban_list
The banned clients.
Definition: network.cpp:65
ClientSettings::network
NetworkSettings network
settings related to the network
Definition: settings_type.h:578
SPS_PARTLY_SENT
@ SPS_PARTLY_SENT
The packets are partly sent; there are more packets to be sent in the queue.
Definition: tcp.h:24
Packet::Recv_uint64
uint64 Recv_uint64()
Read a 64 bits integer from the packet.
Definition: packet.cpp:263
OrderBackup::ResetUser
static void ResetUser(uint32 user)
Reset an user's OrderBackup if needed.
Definition: order_backup.cpp:164
NetworkSocketHandler::SendCompanyInformation
void SendCompanyInformation(Packet *p, const struct Company *c, const struct NetworkCompanyStats *stats, uint max_len=NETWORK_COMPANY_NAME_LENGTH)
Package some generic company information into a packet.
Definition: network_server.cpp:1516
NetworkSettings::autoclean_novehicles
uint8 autoclean_novehicles
remove companies with no vehicles after this many months
Definition: settings_type.h:277
OverflowSafeInt< int64, INT64_MAX, INT64_MIN >
DESTTYPE_BROADCAST
@ DESTTYPE_BROADCAST
Send message/notice to all clients (All)
Definition: network_type.h:82
PacketWriter::mutex
std::mutex mutex
Mutex for making threaded saving safe.
Definition: network_server.cpp:61
ServerNetworkGameSocketHandler::ServerNetworkGameSocketHandler
ServerNetworkGameSocketHandler(SOCKET s)
Create a new socket for the server side of the game connection.
Definition: network_server.cpp:217
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:1457
RoadVehicle::IsBus
bool IsBus() const
Check whether a roadvehicle is a bus.
Definition: roadveh_cmd.cpp:79
ServerNetworkGameSocketHandler::client_address
NetworkAddress client_address
IP-address of the client (so he can be banned)
Definition: network_server.h:73
IConsoleCmdExec
void IConsoleCmdExec(const char *cmdstr, const uint recurse_count)
Execute a given command passed to us.
Definition: console.cpp:407
ProcessAsyncSaveFinish
void ProcessAsyncSaveFinish()
Handle async save finishes.
Definition: saveload.cpp:402
PacketWriter::Destroy
void Destroy()
Begin the destruction of this packet writer.
Definition: network_server.cpp:100
NetworkSettings::max_lag_time
uint16 max_lag_time
maximum amount of time, in game ticks, a client may be lagging behind the server
Definition: settings_type.h:260
ServerNetworkGameSocketHandler::Receive_CLIENT_CHAT
NetworkRecvStatus Receive_CLIENT_CHAT(Packet *p) override
Sends a chat-packet to the server: uint8 ID of the action (see NetworkAction).
Definition: network_server.cpp:1385
PACKET_SERVER_CLIENT_INFO
@ PACKET_SERVER_CLIENT_INFO
Server sends you information about a client.
Definition: tcp_game.h:67
NETWORK_RECV_STATUS_OKAY
@ NETWORK_RECV_STATUS_OKAY
Everything is okay.
Definition: core.h:23
NetworkGameSocketHandler::SendCommand
void SendCommand(Packet *p, const CommandPacket *cp)
Sends a command over the network.
Definition: network_command.cpp:321
CCA_DELETE
@ CCA_DELETE
Delete a company.
Definition: company_type.h:67
ServerNetworkGameSocketHandler::Receive_CLIENT_GAME_PASSWORD
NetworkRecvStatus Receive_CLIENT_GAME_PASSWORD(Packet *p) override
Send a password to the server to authorize: uint8 Password type (see NetworkPasswordType).
Definition: network_server.cpp:980
ADMIN_FREQUENCY_WEEKLY
@ ADMIN_FREQUENCY_WEEKLY
The admin gets information about this on a weekly basis.
Definition: tcp_admin.h:92
DESTTYPE_CLIENT
@ DESTTYPE_CLIENT
Send message/notice to only a certain client (Private)
Definition: network_type.h:84
PACKET_SERVER_WELCOME
@ PACKET_SERVER_WELCOME
Server welcomes you and gives you your ClientID.
Definition: tcp_game.h:66
ServerNetworkGameSocketHandler::SendShutdown
NetworkRecvStatus SendShutdown()
Tell the client we're shutting down.
Definition: network_server.cpp:807
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition: vehicle_type.h:24
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:318
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:391
CMD_SPECTATOR
@ CMD_SPECTATOR
the command may be initiated by a spectator
Definition: command_type.h:392
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:62
ServerNetworkGameSocketHandler::SendError
NetworkRecvStatus SendError(NetworkErrorCode error, const char *reason=nullptr)
Send an error to the client, and close its connection.
Definition: network_server.cpp:432
network_admin.h
NetworkServerGameInfo::clients_on
byte clients_on
Current count of clients on server.
Definition: game.h:26
strecpy
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: string.cpp:112
NetworkSettings::max_commands_in_queue
uint16 max_commands_in_queue
how many commands may there be in the incoming queue before dropping the connection?
Definition: settings_type.h:253
CC_WARNING
static const TextColour CC_WARNING
Colour for warning lines.
Definition: console_type.h:25
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:454
ServerNetworkGameSocketHandler::SendCompanyInfo
NetworkRecvStatus SendCompanyInfo()
Send the client information about the companies.
Definition: network_server.cpp:367
strecat
char * strecat(char *dst, const char *src, const char *last)
Appends characters from one string to another.
Definition: string.cpp:84
NetworkServerKickClient
void NetworkServerKickClient(ClientID client_id, const char *reason)
Kick a single client.
Definition: network_server.cpp:2084
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
VEH_SHIP
@ VEH_SHIP
Ship vehicle type.
Definition: vehicle_type.h:26
Company
Definition: company_base.h:110
_cur_month
Month _cur_month
Current month (0..11)
Definition: date.cpp:27
ServerNetworkGameSocketHandler::SendNeedCompanyPassword
NetworkRecvStatus SendNeedCompanyPassword()
Request the company password.
Definition: network_server.cpp:514
PACKET_SERVER_CHECK_NEWGRFS
@ PACKET_SERVER_CHECK_NEWGRFS
Server sends NewGRF IDs and MD5 checksums for the client to check.
Definition: tcp_game.h:56
NetworkServerYearlyLoop
void NetworkServerYearlyLoop()
Yearly "callback".
Definition: network_server.cpp:1944
SetWindowClassesDirty
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3248
CMD_RENAME_PRESIDENT
@ CMD_RENAME_PRESIDENT
change the president name
Definition: command_type.h:247
CompanyProperties::old_economy
CompanyEconomyEntry old_economy[MAX_HISTORY_QUARTERS]
Economic data of the company of the last MAX_HISTORY_QUARTERS quarters.
Definition: company_base.h:98
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:383
SL_OK
@ SL_OK
completed successfully
Definition: saveload.h:333
NetworkGameSocketHandler::last_frame
uint32 last_frame
Last frame we have executed.
Definition: tcp_game.h:519
_networkclientsocket_pool
NetworkClientSocketPool _networkclientsocket_pool("NetworkClientSocket")
Make very sure the preconditions given in network_type.h are actually followed.
DAY_TICKS
static const int DAY_TICKS
1 day is 74 ticks; _date_fract used to be uint16 and incremented by 885.
Definition: date_type.h:28
PacketWriter::current
Packet * current
The packet we're currently writing to.
Definition: network_server.cpp:58
ServerNetworkGameSocketHandler::GetClientName
void GetClientName(char *client_name, const char *last) const
Get the name of the client, if the user did not send it yet, Client ID is used.
Definition: network_server.cpp:2159
_last_sync_frame
uint32 _last_sync_frame
Used in the server to store the last time a sync packet was sent to clients.
Definition: network.cpp:69
NetworkAdminCompanyInfo
void NetworkAdminCompanyInfo(const Company *company, bool new_company)
Notify the admin network of company details.
Definition: network_admin.cpp:873
NetworkErrorCode
NetworkErrorCode
The error codes we send around in the protocols.
Definition: network_type.h:110
NetworkClientInfo
Container for all information known about a client.
Definition: network_base.h:23
ServerNetworkGameSocketHandler::CloseConnection
NetworkRecvStatus CloseConnection(NetworkRecvStatus status) override
Close the network connection due to the given status.
Definition: network_server.cpp:256
IConsolePrintF
void CDECL IConsolePrintF(TextColour colour_code, const char *format,...)
Handle the printing of text entered into the console or redirected there by any other means.
Definition: console.cpp:125
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:2145
PacketWriter::packets
Packet * packets
Packet queue of the savegame; send these "slowly" to the client.
Definition: network_server.cpp:60
_settings_newgame
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
Definition: settings.cpp:81
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:859
GCF_STATIC
@ GCF_STATIC
GRF file is used statically (can be used in any MP game)
Definition: newgrf_config.h:25
NetworkSettings::sync_freq
uint16 sync_freq
how often do we check whether we are still in-sync
Definition: settings_type.h:250
ServerNetworkGameSocketHandler::SendWait
NetworkRecvStatus SendWait()
Tell the client that its put in a waiting queue.
Definition: network_server.cpp:561
NetworkSettings::autoclean_companies
bool autoclean_companies
automatically remove companies that are not in use
Definition: settings_type.h:274
PACKET_SERVER_MAP_DATA
@ PACKET_SERVER_MAP_DATA
Server sends bits of the map to the client.
Definition: tcp_game.h:74
NetworkSettings::max_companies
uint8 max_companies
maximum amount of companies
Definition: settings_type.h:278
ServerNetworkGameSocketHandler::STATUS_AUTHORIZED
@ STATUS_AUTHORIZED
The client is authorized.
Definition: network_server.h:56
CLIENT_ID_FIRST
@ CLIENT_ID_FIRST
The first client ID.
Definition: network_type.h:42
NETWORK_RECV_STATUS_MALFORMED_PACKET
@ NETWORK_RECV_STATUS_MALFORMED_PACKET
We apparently send a malformed packet.
Definition: core.h:28
NETWORK_COMPANY_NAME_LENGTH
static const uint NETWORK_COMPANY_NAME_LENGTH
The maximum length of the company name, in bytes including '\0'.
Definition: config.h:41
NetworkUpdateClientInfo
void NetworkUpdateClientInfo(ClientID client_id)
Send updated client info of a particular client.
Definition: network_server.cpp:1601
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:1158