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 
8 /** @file network_server.cpp Server part of the network protocol. */
9 
10 #include "../stdafx.h"
11 #include "../strings_func.h"
12 #include "../date_func.h"
13 #include "core/game_info.h"
14 #include "network_admin.h"
15 #include "network_server.h"
16 #include "network_udp.h"
17 #include "network_base.h"
18 #include "../console_func.h"
19 #include "../company_base.h"
20 #include "../command_func.h"
21 #include "../saveload/saveload.h"
22 #include "../saveload/saveload_filter.h"
23 #include "../station_base.h"
24 #include "../genworld.h"
25 #include "../company_func.h"
26 #include "../company_gui.h"
27 #include "../roadveh.h"
28 #include "../order_backup.h"
29 #include "../core/pool_func.hpp"
30 #include "../core/random_func.hpp"
31 #include "../rev.h"
32 #include <mutex>
33 #include <condition_variable>
34 
35 #include "../safeguards.h"
36 
37 
38 /* This file handles all the server-commands */
39 
40 DECLARE_POSTFIX_INCREMENT(ClientID)
41 /** The identifier counter for new clients (is never decreased) */
42 static ClientID _network_client_id = CLIENT_ID_FIRST;
43 
44 /** Make very sure the preconditions given in network_type.h are actually followed */
45 static_assert(MAX_CLIENT_SLOTS > MAX_CLIENTS);
46 /** Yes... */
47 static_assert(NetworkClientSocketPool::MAX_SIZE == MAX_CLIENT_SLOTS);
48 
49 /** The pool with clients. */
50 NetworkClientSocketPool _networkclientsocket_pool("NetworkClientSocket");
51 INSTANTIATE_POOL_METHODS(NetworkClientSocket)
52 
53 /** Instantiate the listen sockets. */
54 template SocketList TCPListenHandler<ServerNetworkGameSocketHandler, PACKET_SERVER_FULL, PACKET_SERVER_BANNED>::sockets;
55 
56 /** Writing a savegame directly to a number of packets. */
57 struct PacketWriter : SaveFilter {
58 	ServerNetworkGameSocketHandler *cs; ///< Socket we are associated with.
59 	Packet *current;                    ///< The packet we're currently writing to.
60 	size_t total_size;                  ///< Total size of the compressed savegame.
61 	Packet *packets;                    ///< Packet queue of the savegame; send these "slowly" to the client.
62 	std::mutex mutex;                   ///< Mutex for making threaded saving safe.
63 	std::condition_variable exit_sig;   ///< Signal for threaded destruction of this packet writer.
64 
65 	/**
66 	 * Create the packet writer.
67 	 * @param cs The socket handler we're making the packets for.
68 	 */
PacketWriterPacketWriter69 	PacketWriter(ServerNetworkGameSocketHandler *cs) : SaveFilter(nullptr), cs(cs), current(nullptr), total_size(0), packets(nullptr)
70 	{
71 	}
72 
73 	/** Make sure everything is cleaned up. */
~PacketWriterPacketWriter74 	~PacketWriter()
75 	{
76 		std::unique_lock<std::mutex> lock(this->mutex);
77 
78 		if (this->cs != nullptr) this->exit_sig.wait(lock);
79 
80 		/* This must all wait until the Destroy function is called. */
81 
82 		while (this->packets != nullptr) {
83 			delete Packet::PopFromQueue(&this->packets);
84 		}
85 
86 		delete this->current;
87 	}
88 
89 	/**
90 	 * Begin the destruction of this packet writer. It can happen in two ways:
91 	 * in the first case the client disconnected while saving the map. In this
92 	 * case the saving has not finished and killed this PacketWriter. In that
93 	 * case we simply set cs to nullptr, triggering the appending to fail due to
94 	 * the connection problem and eventually triggering the destructor. In the
95 	 * second case the destructor is already called, and it is waiting for our
96 	 * signal which we will send. Only then the packets will be removed by the
97 	 * destructor.
98 	 */
DestroyPacketWriter99 	void Destroy()
100 	{
101 		std::unique_lock<std::mutex> lock(this->mutex);
102 
103 		this->cs = nullptr;
104 
105 		this->exit_sig.notify_all();
106 		lock.unlock();
107 
108 		/* Make sure the saving is completely cancelled. Yes,
109 		 * we need to handle the save finish as well as the
110 		 * next connection might just be requesting a map. */
111 		WaitTillSaved();
112 		ProcessAsyncSaveFinish();
113 	}
114 
115 	/**
116 	 * Transfer all packets from here to the network's queue while holding
117 	 * the lock on our mutex.
118 	 * @param socket The network socket to write to.
119 	 * @return True iff the last packet of the map has been sent.
120 	 */
TransferToNetworkQueuePacketWriter121 	bool TransferToNetworkQueue(ServerNetworkGameSocketHandler *socket)
122 	{
123 		/* Unsafe check for the queue being empty or not. */
124 		if (this->packets == nullptr) return false;
125 
126 		std::lock_guard<std::mutex> lock(this->mutex);
127 
128 		while (this->packets != nullptr) {
129 			Packet *p = Packet::PopFromQueue(&this->packets);
130 			bool last_packet = p->GetPacketType() == PACKET_SERVER_MAP_DONE;
131 			socket->SendPacket(p);
132 
133 			if (last_packet) return true;
134 		}
135 
136 		return false;
137 	}
138 
139 	/** Append the current packet to the queue. */
AppendQueuePacketWriter140 	void AppendQueue()
141 	{
142 		if (this->current == nullptr) return;
143 
144 		Packet::AddToQueue(&this->packets, this->current);
145 		this->current = nullptr;
146 	}
147 
148 	/** Prepend the current packet to the queue. */
PrependQueuePacketWriter149 	void PrependQueue()
150 	{
151 		if (this->current == nullptr) return;
152 
153 		/* Reversed from AppendQueue so the queue gets added to the current one. */
154 		Packet::AddToQueue(&this->current, this->packets);
155 		this->packets = this->current;
156 		this->current = nullptr;
157 	}
158 
WritePacketWriter159 	void Write(byte *buf, size_t size) override
160 	{
161 		/* We want to abort the saving when the socket is closed. */
162 		if (this->cs == nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
163 
164 		if (this->current == nullptr) this->current = new Packet(PACKET_SERVER_MAP_DATA, TCP_MTU);
165 
166 		std::lock_guard<std::mutex> lock(this->mutex);
167 
168 		byte *bufe = buf + size;
169 		while (buf != bufe) {
170 			size_t written = this->current->Send_bytes(buf, bufe);
171 			buf += written;
172 
173 			if (!this->current->CanWriteToPacket(1)) {
174 				this->AppendQueue();
175 				if (buf != bufe) this->current = new Packet(PACKET_SERVER_MAP_DATA, TCP_MTU);
176 			}
177 		}
178 
179 		this->total_size += size;
180 	}
181 
FinishPacketWriter182 	void Finish() override
183 	{
184 		/* We want to abort the saving when the socket is closed. */
185 		if (this->cs == nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
186 
187 		std::lock_guard<std::mutex> lock(this->mutex);
188 
189 		/* Make sure the last packet is flushed. */
190 		this->AppendQueue();
191 
192 		/* Add a packet stating that this is the end to the queue. */
193 		this->current = new Packet(PACKET_SERVER_MAP_DONE);
194 		this->AppendQueue();
195 
196 		/* Fast-track the size to the client. */
197 		this->current = new Packet(PACKET_SERVER_MAP_SIZE);
198 		this->current->Send_uint32((uint32)this->total_size);
199 		this->PrependQueue();
200 	}
201 };
202 
203 
204 /**
205  * Create a new socket for the server side of the game connection.
206  * @param s The socket to connect with.
207  */
ServerNetworkGameSocketHandler(SOCKET s)208 ServerNetworkGameSocketHandler::ServerNetworkGameSocketHandler(SOCKET s) : NetworkGameSocketHandler(s)
209 {
210 	this->status = STATUS_INACTIVE;
211 	this->client_id = _network_client_id++;
212 	this->receive_limit = _settings_client.network.bytes_per_frame_burst;
213 
214 	/* The Socket and Info pools need to be the same in size. After all,
215 	 * each Socket will be associated with at most one Info object. As
216 	 * such if the Socket was allocated the Info object can as well. */
217 	static_assert(NetworkClientSocketPool::MAX_SIZE == NetworkClientInfoPool::MAX_SIZE);
218 }
219 
220 /**
221  * Clear everything related to this client.
222  */
~ServerNetworkGameSocketHandler()223 ServerNetworkGameSocketHandler::~ServerNetworkGameSocketHandler()
224 {
225 	if (_redirect_console_to_client == this->client_id) _redirect_console_to_client = INVALID_CLIENT_ID;
226 	OrderBackup::ResetUser(this->client_id);
227 
228 	if (this->savegame != nullptr) {
229 		this->savegame->Destroy();
230 		this->savegame = nullptr;
231 	}
232 }
233 
ReceivePacket()234 Packet *ServerNetworkGameSocketHandler::ReceivePacket()
235 {
236 	/* Only allow receiving when we have some buffer free; this value
237 	 * can go negative, but eventually it will become positive again. */
238 	if (this->receive_limit <= 0) return nullptr;
239 
240 	/* We can receive a packet, so try that and if needed account for
241 	 * the amount of received data. */
242 	Packet *p = this->NetworkTCPSocketHandler::ReceivePacket();
243 	if (p != nullptr) this->receive_limit -= p->Size();
244 	return p;
245 }
246 
CloseConnection(NetworkRecvStatus status)247 NetworkRecvStatus ServerNetworkGameSocketHandler::CloseConnection(NetworkRecvStatus status)
248 {
249 	assert(status != NETWORK_RECV_STATUS_OKAY);
250 	/*
251 	 * Sending a message just before leaving the game calls cs->SendPackets.
252 	 * This might invoke this function, which means that when we close the
253 	 * connection after cs->SendPackets we will close an already closed
254 	 * connection. This handles that case gracefully without having to make
255 	 * that code any more complex or more aware of the validity of the socket.
256 	 */
257 	if (this->sock == INVALID_SOCKET) return status;
258 
259 	if (status != NETWORK_RECV_STATUS_CLIENT_QUIT && status != NETWORK_RECV_STATUS_SERVER_ERROR && !this->HasClientQuit() && this->status >= STATUS_AUTHORIZED) {
260 		/* We did not receive a leave message from this client... */
261 		std::string client_name = this->GetClientName();
262 
263 		NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, "", STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST);
264 
265 		/* Inform other clients of this... strange leaving ;) */
266 		for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
267 			if (new_cs->status > STATUS_AUTHORIZED && this != new_cs) {
268 				new_cs->SendErrorQuit(this->client_id, NETWORK_ERROR_CONNECTION_LOST);
269 			}
270 		}
271 	}
272 
273 	/* If we were transfering a map to this client, stop the savegame creation
274 	 * process and queue the next client to receive the map. */
275 	if (this->status == STATUS_MAP) {
276 		/* Ensure the saving of the game is stopped too. */
277 		this->savegame->Destroy();
278 		this->savegame = nullptr;
279 
280 		this->CheckNextClientToSendMap(this);
281 	}
282 
283 	NetworkAdminClientError(this->client_id, NETWORK_ERROR_CONNECTION_LOST);
284 	Debug(net, 3, "[{}] Client #{} closed connection", ServerNetworkGameSocketHandler::GetName(), this->client_id);
285 
286 	/* We just lost one client :( */
287 	if (this->status >= STATUS_AUTHORIZED) _network_game_info.clients_on--;
288 	extern byte _network_clients_connected;
289 	_network_clients_connected--;
290 
291 	this->SendPackets(true);
292 
293 	delete this->GetInfo();
294 	delete this;
295 
296 	InvalidateWindowData(WC_CLIENT_LIST, 0);
297 
298 	return status;
299 }
300 
301 /**
302  * Whether an connection is allowed or not at this moment.
303  * @return true if the connection is allowed.
304  */
AllowConnection()305 /* static */ bool ServerNetworkGameSocketHandler::AllowConnection()
306 {
307 	extern byte _network_clients_connected;
308 	bool accept = _network_clients_connected < MAX_CLIENTS;
309 
310 	/* We can't go over the MAX_CLIENTS limit here. However, the
311 	 * pool must have place for all clients and ourself. */
312 	static_assert(NetworkClientSocketPool::MAX_SIZE == MAX_CLIENTS + 1);
313 	assert(!accept || ServerNetworkGameSocketHandler::CanAllocateItem());
314 	return accept;
315 }
316 
317 /** Send the packets for the server sockets. */
Send()318 /* static */ void ServerNetworkGameSocketHandler::Send()
319 {
320 	for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
321 		if (cs->writable) {
322 			if (cs->SendPackets() != SPS_CLOSED && cs->status == STATUS_MAP) {
323 				/* This client is in the middle of a map-send, call the function for that */
324 				cs->SendMap();
325 			}
326 		}
327 	}
328 }
329 
330 static void NetworkHandleCommandQueue(NetworkClientSocket *cs);
331 
332 /***********
333  * Sending functions
334  *   DEF_SERVER_SEND_COMMAND has parameter: NetworkClientSocket *cs
335  ************/
336 
337 /**
338  * Send the client information about a client.
339  * @param ci The client to send information about.
340  */
SendClientInfo(NetworkClientInfo * ci)341 NetworkRecvStatus ServerNetworkGameSocketHandler::SendClientInfo(NetworkClientInfo *ci)
342 {
343 	if (ci->client_id != INVALID_CLIENT_ID) {
344 		Packet *p = new Packet(PACKET_SERVER_CLIENT_INFO);
345 		p->Send_uint32(ci->client_id);
346 		p->Send_uint8 (ci->client_playas);
347 		p->Send_string(ci->client_name);
348 
349 		this->SendPacket(p);
350 	}
351 	return NETWORK_RECV_STATUS_OKAY;
352 }
353 
354 /** Send the client information about the server. */
SendGameInfo()355 NetworkRecvStatus ServerNetworkGameSocketHandler::SendGameInfo()
356 {
357 	Packet *p = new Packet(PACKET_SERVER_GAME_INFO, TCP_MTU);
358 	SerializeNetworkGameInfo(p, GetCurrentNetworkServerGameInfo());
359 
360 	this->SendPacket(p);
361 
362 	return NETWORK_RECV_STATUS_OKAY;
363 }
364 
365 /**
366  * Send an error to the client, and close its connection.
367  * @param error The error to disconnect for.
368  * @param reason In case of kicking a client, specifies the reason for kicking the client.
369  */
SendError(NetworkErrorCode error,const std::string & reason)370 NetworkRecvStatus ServerNetworkGameSocketHandler::SendError(NetworkErrorCode error, const std::string &reason)
371 {
372 	Packet *p = new Packet(PACKET_SERVER_ERROR);
373 
374 	p->Send_uint8(error);
375 	if (!reason.empty()) p->Send_string(reason);
376 	this->SendPacket(p);
377 
378 	StringID strid = GetNetworkErrorMsg(error);
379 
380 	/* Only send when the current client was in game */
381 	if (this->status > STATUS_AUTHORIZED) {
382 		std::string client_name = this->GetClientName();
383 
384 		Debug(net, 1, "'{}' made an error and has been disconnected: {}", client_name, GetString(strid));
385 
386 		if (error == NETWORK_ERROR_KICKED && !reason.empty()) {
387 			NetworkTextMessage(NETWORK_ACTION_KICKED, CC_DEFAULT, false, client_name, reason, strid);
388 		} else {
389 			NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, "", strid);
390 		}
391 
392 		for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
393 			if (new_cs->status >= STATUS_AUTHORIZED && new_cs != this) {
394 				/* Some errors we filter to a more general error. Clients don't have to know the real
395 				 *  reason a joining failed. */
396 				if (error == NETWORK_ERROR_NOT_AUTHORIZED || error == NETWORK_ERROR_NOT_EXPECTED || error == NETWORK_ERROR_WRONG_REVISION) {
397 					error = NETWORK_ERROR_ILLEGAL_PACKET;
398 				}
399 				new_cs->SendErrorQuit(this->client_id, error);
400 			}
401 		}
402 
403 		NetworkAdminClientError(this->client_id, error);
404 	} else {
405 		Debug(net, 1, "Client {} made an error and has been disconnected: {}", this->client_id, GetString(strid));
406 	}
407 
408 	/* The client made a mistake, so drop the connection now! */
409 	return this->CloseConnection(NETWORK_RECV_STATUS_SERVER_ERROR);
410 }
411 
412 /** Send the check for the NewGRFs. */
SendNewGRFCheck()413 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGRFCheck()
414 {
415 	Packet *p = new Packet(PACKET_SERVER_CHECK_NEWGRFS, TCP_MTU);
416 	const GRFConfig *c;
417 	uint grf_count = 0;
418 
419 	for (c = _grfconfig; c != nullptr; c = c->next) {
420 		if (!HasBit(c->flags, GCF_STATIC)) grf_count++;
421 	}
422 
423 	p->Send_uint8 (grf_count);
424 	for (c = _grfconfig; c != nullptr; c = c->next) {
425 		if (!HasBit(c->flags, GCF_STATIC)) SerializeGRFIdentifier(p, &c->ident);
426 	}
427 
428 	this->SendPacket(p);
429 	return NETWORK_RECV_STATUS_OKAY;
430 }
431 
432 /** Request the game password. */
SendNeedGamePassword()433 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNeedGamePassword()
434 {
435 	/* Invalid packet when status is STATUS_AUTH_GAME or higher */
436 	if (this->status >= STATUS_AUTH_GAME) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
437 
438 	this->status = STATUS_AUTH_GAME;
439 	/* Reset 'lag' counters */
440 	this->last_frame = this->last_frame_server = _frame_counter;
441 
442 	Packet *p = new Packet(PACKET_SERVER_NEED_GAME_PASSWORD);
443 	this->SendPacket(p);
444 	return NETWORK_RECV_STATUS_OKAY;
445 }
446 
447 /** Request the company password. */
SendNeedCompanyPassword()448 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNeedCompanyPassword()
449 {
450 	/* Invalid packet when status is STATUS_AUTH_COMPANY or higher */
451 	if (this->status >= STATUS_AUTH_COMPANY) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
452 
453 	this->status = STATUS_AUTH_COMPANY;
454 	/* Reset 'lag' counters */
455 	this->last_frame = this->last_frame_server = _frame_counter;
456 
457 	Packet *p = new Packet(PACKET_SERVER_NEED_COMPANY_PASSWORD);
458 	p->Send_uint32(_settings_game.game_creation.generation_seed);
459 	p->Send_string(_settings_client.network.network_id);
460 	this->SendPacket(p);
461 	return NETWORK_RECV_STATUS_OKAY;
462 }
463 
464 /** Send the client a welcome message with some basic information. */
SendWelcome()465 NetworkRecvStatus ServerNetworkGameSocketHandler::SendWelcome()
466 {
467 	Packet *p;
468 
469 	/* Invalid packet when status is AUTH or higher */
470 	if (this->status >= STATUS_AUTHORIZED) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
471 
472 	this->status = STATUS_AUTHORIZED;
473 	/* Reset 'lag' counters */
474 	this->last_frame = this->last_frame_server = _frame_counter;
475 
476 	_network_game_info.clients_on++;
477 
478 	p = new Packet(PACKET_SERVER_WELCOME);
479 	p->Send_uint32(this->client_id);
480 	p->Send_uint32(_settings_game.game_creation.generation_seed);
481 	p->Send_string(_settings_client.network.network_id);
482 	this->SendPacket(p);
483 
484 	/* Transmit info about all the active clients */
485 	for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
486 		if (new_cs != this && new_cs->status >= STATUS_AUTHORIZED) {
487 			this->SendClientInfo(new_cs->GetInfo());
488 		}
489 	}
490 	/* Also send the info of the server */
491 	return this->SendClientInfo(NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER));
492 }
493 
494 /** Tell the client that its put in a waiting queue. */
SendWait()495 NetworkRecvStatus ServerNetworkGameSocketHandler::SendWait()
496 {
497 	int waiting = 1; // current player getting the map counts as 1
498 	Packet *p;
499 
500 	/* Count how many clients are waiting in the queue, in front of you! */
501 	for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
502 		if (new_cs->status != STATUS_MAP_WAIT) continue;
503 		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++;
504 	}
505 
506 	p = new Packet(PACKET_SERVER_WAIT);
507 	p->Send_uint8(waiting);
508 	this->SendPacket(p);
509 	return NETWORK_RECV_STATUS_OKAY;
510 }
511 
CheckNextClientToSendMap(NetworkClientSocket * ignore_cs)512 void ServerNetworkGameSocketHandler::CheckNextClientToSendMap(NetworkClientSocket *ignore_cs)
513 {
514 	/* Find the best candidate for joining, i.e. the first joiner. */
515 	NetworkClientSocket *best = nullptr;
516 	for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
517 		if (ignore_cs == new_cs) continue;
518 
519 		if (new_cs->status == STATUS_MAP_WAIT) {
520 			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)) {
521 				best = new_cs;
522 			}
523 		}
524 	}
525 
526 	/* Is there someone else to join? */
527 	if (best != nullptr) {
528 		/* Let the first start joining. */
529 		best->status = STATUS_AUTHORIZED;
530 		best->SendMap();
531 
532 		/* And update the rest. */
533 		for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
534 			if (new_cs->status == STATUS_MAP_WAIT) new_cs->SendWait();
535 		}
536 	}
537 }
538 
539 /** This sends the map to the client */
SendMap()540 NetworkRecvStatus ServerNetworkGameSocketHandler::SendMap()
541 {
542 	if (this->status < STATUS_AUTHORIZED) {
543 		/* Illegal call, return error and ignore the packet */
544 		return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
545 	}
546 
547 	if (this->status == STATUS_AUTHORIZED) {
548 		this->savegame = new PacketWriter(this);
549 
550 		/* Now send the _frame_counter and how many packets are coming */
551 		Packet *p = new Packet(PACKET_SERVER_MAP_BEGIN);
552 		p->Send_uint32(_frame_counter);
553 		this->SendPacket(p);
554 
555 		NetworkSyncCommandQueue(this);
556 		this->status = STATUS_MAP;
557 		/* Mark the start of download */
558 		this->last_frame = _frame_counter;
559 		this->last_frame_server = _frame_counter;
560 
561 		/* Make a dump of the current game */
562 		if (SaveWithFilter(this->savegame, true) != SL_OK) usererror("network savedump failed");
563 	}
564 
565 	if (this->status == STATUS_MAP) {
566 		bool last_packet = this->savegame->TransferToNetworkQueue(this);
567 		if (last_packet) {
568 			/* Done reading, make sure saving is done as well */
569 			this->savegame->Destroy();
570 			this->savegame = nullptr;
571 
572 			/* Set the status to DONE_MAP, no we will wait for the client
573 			 *  to send it is ready (maybe that happens like never ;)) */
574 			this->status = STATUS_DONE_MAP;
575 
576 			this->CheckNextClientToSendMap();
577 		}
578 	}
579 	return NETWORK_RECV_STATUS_OKAY;
580 }
581 
582 /**
583  * Tell that a client joined.
584  * @param client_id The client that joined.
585  */
SendJoin(ClientID client_id)586 NetworkRecvStatus ServerNetworkGameSocketHandler::SendJoin(ClientID client_id)
587 {
588 	Packet *p = new Packet(PACKET_SERVER_JOIN);
589 
590 	p->Send_uint32(client_id);
591 
592 	this->SendPacket(p);
593 	return NETWORK_RECV_STATUS_OKAY;
594 }
595 
596 /** Tell the client that they may run to a particular frame. */
SendFrame()597 NetworkRecvStatus ServerNetworkGameSocketHandler::SendFrame()
598 {
599 	Packet *p = new Packet(PACKET_SERVER_FRAME);
600 	p->Send_uint32(_frame_counter);
601 	p->Send_uint32(_frame_counter_max);
602 #ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
603 	p->Send_uint32(_sync_seed_1);
604 #ifdef NETWORK_SEND_DOUBLE_SEED
605 	p->Send_uint32(_sync_seed_2);
606 #endif
607 #endif
608 
609 	/* If token equals 0, we need to make a new token and send that. */
610 	if (this->last_token == 0) {
611 		this->last_token = InteractiveRandomRange(UINT8_MAX - 1) + 1;
612 		p->Send_uint8(this->last_token);
613 	}
614 
615 	this->SendPacket(p);
616 	return NETWORK_RECV_STATUS_OKAY;
617 }
618 
619 /** Request the client to sync. */
SendSync()620 NetworkRecvStatus ServerNetworkGameSocketHandler::SendSync()
621 {
622 	Packet *p = new Packet(PACKET_SERVER_SYNC);
623 	p->Send_uint32(_frame_counter);
624 	p->Send_uint32(_sync_seed_1);
625 
626 #ifdef NETWORK_SEND_DOUBLE_SEED
627 	p->Send_uint32(_sync_seed_2);
628 #endif
629 	this->SendPacket(p);
630 	return NETWORK_RECV_STATUS_OKAY;
631 }
632 
633 /**
634  * Send a command to the client to execute.
635  * @param cp The command to send.
636  */
SendCommand(const CommandPacket * cp)637 NetworkRecvStatus ServerNetworkGameSocketHandler::SendCommand(const CommandPacket *cp)
638 {
639 	Packet *p = new Packet(PACKET_SERVER_COMMAND);
640 
641 	this->NetworkGameSocketHandler::SendCommand(p, cp);
642 	p->Send_uint32(cp->frame);
643 	p->Send_bool  (cp->my_cmd);
644 
645 	this->SendPacket(p);
646 	return NETWORK_RECV_STATUS_OKAY;
647 }
648 
649 /**
650  * Send a chat message.
651  * @param action The action associated with the message.
652  * @param client_id The origin of the chat message.
653  * @param self_send Whether we did send the message.
654  * @param msg The actual message.
655  * @param data Arbitrary extra data.
656  */
SendChat(NetworkAction action,ClientID client_id,bool self_send,const std::string & msg,int64 data)657 NetworkRecvStatus ServerNetworkGameSocketHandler::SendChat(NetworkAction action, ClientID client_id, bool self_send, const std::string &msg, int64 data)
658 {
659 	if (this->status < STATUS_PRE_ACTIVE) return NETWORK_RECV_STATUS_OKAY;
660 
661 	Packet *p = new Packet(PACKET_SERVER_CHAT);
662 
663 	p->Send_uint8 (action);
664 	p->Send_uint32(client_id);
665 	p->Send_bool  (self_send);
666 	p->Send_string(msg);
667 	p->Send_uint64(data);
668 
669 	this->SendPacket(p);
670 	return NETWORK_RECV_STATUS_OKAY;
671 }
672 
673 /**
674  * Send a chat message from external source.
675  * @param source Name of the source this message came from.
676  * @param colour TextColour to use for the message.
677  * @param user Name of the user who sent the messsage.
678  * @param msg The actual message.
679  */
SendExternalChat(const std::string & source,TextColour colour,const std::string & user,const std::string & msg)680 NetworkRecvStatus ServerNetworkGameSocketHandler::SendExternalChat(const std::string &source, TextColour colour, const std::string &user, const std::string &msg)
681 {
682 	if (this->status < STATUS_PRE_ACTIVE) return NETWORK_RECV_STATUS_OKAY;
683 
684 	Packet *p = new Packet(PACKET_SERVER_EXTERNAL_CHAT);
685 
686 	p->Send_string(source);
687 	p->Send_uint16(colour);
688 	p->Send_string(user);
689 	p->Send_string(msg);
690 
691 	this->SendPacket(p);
692 	return NETWORK_RECV_STATUS_OKAY;
693 }
694 
695 /**
696  * Tell the client another client quit with an error.
697  * @param client_id The client that quit.
698  * @param errorno The reason the client quit.
699  */
SendErrorQuit(ClientID client_id,NetworkErrorCode errorno)700 NetworkRecvStatus ServerNetworkGameSocketHandler::SendErrorQuit(ClientID client_id, NetworkErrorCode errorno)
701 {
702 	Packet *p = new Packet(PACKET_SERVER_ERROR_QUIT);
703 
704 	p->Send_uint32(client_id);
705 	p->Send_uint8 (errorno);
706 
707 	this->SendPacket(p);
708 	return NETWORK_RECV_STATUS_OKAY;
709 }
710 
711 /**
712  * Tell the client another client quit.
713  * @param client_id The client that quit.
714  */
SendQuit(ClientID client_id)715 NetworkRecvStatus ServerNetworkGameSocketHandler::SendQuit(ClientID client_id)
716 {
717 	Packet *p = new Packet(PACKET_SERVER_QUIT);
718 
719 	p->Send_uint32(client_id);
720 
721 	this->SendPacket(p);
722 	return NETWORK_RECV_STATUS_OKAY;
723 }
724 
725 /** Tell the client we're shutting down. */
SendShutdown()726 NetworkRecvStatus ServerNetworkGameSocketHandler::SendShutdown()
727 {
728 	Packet *p = new Packet(PACKET_SERVER_SHUTDOWN);
729 	this->SendPacket(p);
730 	return NETWORK_RECV_STATUS_OKAY;
731 }
732 
733 /** Tell the client we're starting a new game. */
SendNewGame()734 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGame()
735 {
736 	Packet *p = new Packet(PACKET_SERVER_NEWGAME);
737 	this->SendPacket(p);
738 	return NETWORK_RECV_STATUS_OKAY;
739 }
740 
741 /**
742  * Send the result of a console action.
743  * @param colour The colour of the result.
744  * @param command The command that was executed.
745  */
SendRConResult(uint16 colour,const std::string & command)746 NetworkRecvStatus ServerNetworkGameSocketHandler::SendRConResult(uint16 colour, const std::string &command)
747 {
748 	Packet *p = new Packet(PACKET_SERVER_RCON);
749 
750 	p->Send_uint16(colour);
751 	p->Send_string(command);
752 	this->SendPacket(p);
753 	return NETWORK_RECV_STATUS_OKAY;
754 }
755 
756 /**
757  * Tell that a client moved to another company.
758  * @param client_id The client that moved.
759  * @param company_id The company the client moved to.
760  */
SendMove(ClientID client_id,CompanyID company_id)761 NetworkRecvStatus ServerNetworkGameSocketHandler::SendMove(ClientID client_id, CompanyID company_id)
762 {
763 	Packet *p = new Packet(PACKET_SERVER_MOVE);
764 
765 	p->Send_uint32(client_id);
766 	p->Send_uint8(company_id);
767 	this->SendPacket(p);
768 	return NETWORK_RECV_STATUS_OKAY;
769 }
770 
771 /** Send an update about the company password states. */
SendCompanyUpdate()772 NetworkRecvStatus ServerNetworkGameSocketHandler::SendCompanyUpdate()
773 {
774 	Packet *p = new Packet(PACKET_SERVER_COMPANY_UPDATE);
775 
776 	p->Send_uint16(_network_company_passworded);
777 	this->SendPacket(p);
778 	return NETWORK_RECV_STATUS_OKAY;
779 }
780 
781 /** Send an update about the max company/spectator counts. */
SendConfigUpdate()782 NetworkRecvStatus ServerNetworkGameSocketHandler::SendConfigUpdate()
783 {
784 	Packet *p = new Packet(PACKET_SERVER_CONFIG_UPDATE);
785 
786 	p->Send_uint8(_settings_client.network.max_companies);
787 	p->Send_string(_settings_client.network.server_name);
788 	this->SendPacket(p);
789 	return NETWORK_RECV_STATUS_OKAY;
790 }
791 
792 /***********
793  * Receiving functions
794  *   DEF_SERVER_RECEIVE_COMMAND has parameter: NetworkClientSocket *cs, Packet *p
795  ************/
796 
Receive_CLIENT_GAME_INFO(Packet * p)797 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GAME_INFO(Packet *p)
798 {
799 	return this->SendGameInfo();
800 }
801 
Receive_CLIENT_NEWGRFS_CHECKED(Packet * p)802 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_NEWGRFS_CHECKED(Packet *p)
803 {
804 	if (this->status != STATUS_NEWGRFS_CHECK) {
805 		/* Illegal call, return error and ignore the packet */
806 		return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
807 	}
808 
809 	NetworkClientInfo *ci = this->GetInfo();
810 
811 	/* We now want a password from the client else we do not allow them in! */
812 	if (!_settings_client.network.server_password.empty()) {
813 		return this->SendNeedGamePassword();
814 	}
815 
816 	if (Company::IsValidID(ci->client_playas) && !_network_company_states[ci->client_playas].password.empty()) {
817 		return this->SendNeedCompanyPassword();
818 	}
819 
820 	return this->SendWelcome();
821 }
822 
Receive_CLIENT_JOIN(Packet * p)823 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet *p)
824 {
825 	if (this->status != STATUS_INACTIVE) {
826 		/* Illegal call, return error and ignore the packet */
827 		return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
828 	}
829 
830 	if (_network_game_info.clients_on >= _settings_client.network.max_clients) {
831 		/* Turns out we are full. Inform the user about this. */
832 		return this->SendError(NETWORK_ERROR_FULL);
833 	}
834 
835 	std::string client_revision = p->Recv_string(NETWORK_REVISION_LENGTH);
836 	uint32 newgrf_version = p->Recv_uint32();
837 
838 	/* Check if the client has revision control enabled */
839 	if (!IsNetworkCompatibleVersion(client_revision) || _openttd_newgrf_version != newgrf_version) {
840 		/* Different revisions!! */
841 		return this->SendError(NETWORK_ERROR_WRONG_REVISION);
842 	}
843 
844 	std::string client_name = p->Recv_string(NETWORK_CLIENT_NAME_LENGTH);
845 	CompanyID playas = (Owner)p->Recv_uint8();
846 
847 	if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT;
848 
849 	/* join another company does not affect these values */
850 	switch (playas) {
851 		case COMPANY_NEW_COMPANY: // New company
852 			if (Company::GetNumItems() >= _settings_client.network.max_companies) {
853 				return this->SendError(NETWORK_ERROR_FULL);
854 			}
855 			break;
856 		case COMPANY_SPECTATOR: // Spectator
857 			break;
858 		default: // Join another company (companies 1-8 (index 0-7))
859 			if (!Company::IsValidHumanID(playas)) {
860 				return this->SendError(NETWORK_ERROR_COMPANY_MISMATCH);
861 			}
862 			break;
863 	}
864 
865 	if (!NetworkIsValidClientName(client_name)) {
866 		/* An invalid client name was given. However, the client ensures the name
867 		 * is valid before it is sent over the network, so something went horribly
868 		 * wrong. This is probably someone trying to troll us. */
869 		return this->SendError(NETWORK_ERROR_INVALID_CLIENT_NAME);
870 	}
871 
872 	if (!NetworkMakeClientNameUnique(client_name)) { // Change name if duplicate
873 		/* We could not create a name for this client */
874 		return this->SendError(NETWORK_ERROR_NAME_IN_USE);
875 	}
876 
877 	assert(NetworkClientInfo::CanAllocateItem());
878 	NetworkClientInfo *ci = new NetworkClientInfo(this->client_id);
879 	this->SetInfo(ci);
880 	ci->join_date = _date;
881 	ci->client_name = client_name;
882 	ci->client_playas = playas;
883 	Debug(desync, 1, "client: {:08x}; {:02x}; {:02x}; {:02x}", _date, _date_fract, (int)ci->client_playas, (int)ci->index);
884 
885 	/* Make sure companies to which people try to join are not autocleaned */
886 	if (Company::IsValidID(playas)) _network_company_states[playas].months_empty = 0;
887 
888 	this->status = STATUS_NEWGRFS_CHECK;
889 
890 	if (_grfconfig == nullptr) {
891 		/* Behave as if we received PACKET_CLIENT_NEWGRFS_CHECKED */
892 		return this->Receive_CLIENT_NEWGRFS_CHECKED(nullptr);
893 	}
894 
895 	return this->SendNewGRFCheck();
896 }
897 
Receive_CLIENT_GAME_PASSWORD(Packet * p)898 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GAME_PASSWORD(Packet *p)
899 {
900 	if (this->status != STATUS_AUTH_GAME) {
901 		return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
902 	}
903 
904 	std::string password = p->Recv_string(NETWORK_PASSWORD_LENGTH);
905 
906 	/* Check game password. Allow joining if we cleared the password meanwhile */
907 	if (!_settings_client.network.server_password.empty() &&
908 			_settings_client.network.server_password.compare(password) != 0) {
909 		/* Password is invalid */
910 		return this->SendError(NETWORK_ERROR_WRONG_PASSWORD);
911 	}
912 
913 	const NetworkClientInfo *ci = this->GetInfo();
914 	if (Company::IsValidID(ci->client_playas) && !_network_company_states[ci->client_playas].password.empty()) {
915 		return this->SendNeedCompanyPassword();
916 	}
917 
918 	/* Valid password, allow user */
919 	return this->SendWelcome();
920 }
921 
Receive_CLIENT_COMPANY_PASSWORD(Packet * p)922 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMPANY_PASSWORD(Packet *p)
923 {
924 	if (this->status != STATUS_AUTH_COMPANY) {
925 		return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
926 	}
927 
928 	std::string password = p->Recv_string(NETWORK_PASSWORD_LENGTH);
929 
930 	/* Check company password. Allow joining if we cleared the password meanwhile.
931 	 * Also, check the company is still valid - client could be moved to spectators
932 	 * in the middle of the authorization process */
933 	CompanyID playas = this->GetInfo()->client_playas;
934 	if (Company::IsValidID(playas) && !_network_company_states[playas].password.empty() &&
935 			_network_company_states[playas].password.compare(password) != 0) {
936 		/* Password is invalid */
937 		return this->SendError(NETWORK_ERROR_WRONG_PASSWORD);
938 	}
939 
940 	return this->SendWelcome();
941 }
942 
Receive_CLIENT_GETMAP(Packet * p)943 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GETMAP(Packet *p)
944 {
945 	/* The client was never joined.. so this is impossible, right?
946 	 *  Ignore the packet, give the client a warning, and close the connection */
947 	if (this->status < STATUS_AUTHORIZED || this->HasClientQuit()) {
948 		return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
949 	}
950 
951 	/* Check if someone else is receiving the map */
952 	for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
953 		if (new_cs->status == STATUS_MAP) {
954 			/* Tell the new client to wait */
955 			this->status = STATUS_MAP_WAIT;
956 			return this->SendWait();
957 		}
958 	}
959 
960 	/* We receive a request to upload the map.. give it to the client! */
961 	return this->SendMap();
962 }
963 
Receive_CLIENT_MAP_OK(Packet * p)964 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MAP_OK(Packet *p)
965 {
966 	/* Client has the map, now start syncing */
967 	if (this->status == STATUS_DONE_MAP && !this->HasClientQuit()) {
968 		std::string client_name = this->GetClientName();
969 
970 		NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, client_name, "", this->client_id);
971 		InvalidateWindowData(WC_CLIENT_LIST, 0);
972 
973 		Debug(net, 3, "[{}] Client #{} ({}) joined as {}", ServerNetworkGameSocketHandler::GetName(), this->client_id, this->GetClientIP(), client_name);
974 
975 		/* Mark the client as pre-active, and wait for an ACK
976 		 *  so we know it is done loading and in sync with us */
977 		this->status = STATUS_PRE_ACTIVE;
978 		NetworkHandleCommandQueue(this);
979 		this->SendFrame();
980 		this->SendSync();
981 
982 		/* This is the frame the client receives
983 		 *  we need it later on to make sure the client is not too slow */
984 		this->last_frame = _frame_counter;
985 		this->last_frame_server = _frame_counter;
986 
987 		for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
988 			if (new_cs->status >= STATUS_AUTHORIZED) {
989 				new_cs->SendClientInfo(this->GetInfo());
990 				new_cs->SendJoin(this->client_id);
991 			}
992 		}
993 
994 		NetworkAdminClientInfo(this, true);
995 
996 		/* also update the new client with our max values */
997 		this->SendConfigUpdate();
998 
999 		/* quickly update the syncing client with company details */
1000 		return this->SendCompanyUpdate();
1001 	}
1002 
1003 	/* Wrong status for this packet, give a warning to client, and close connection */
1004 	return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1005 }
1006 
1007 /**
1008  * The client has done a command and wants us to handle it
1009  * @param p the packet in which the command was sent
1010  */
Receive_CLIENT_COMMAND(Packet * p)1011 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMMAND(Packet *p)
1012 {
1013 	/* The client was never joined.. so this is impossible, right?
1014 	 *  Ignore the packet, give the client a warning, and close the connection */
1015 	if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
1016 		return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1017 	}
1018 
1019 	if (this->incoming_queue.Count() >= _settings_client.network.max_commands_in_queue) {
1020 		return this->SendError(NETWORK_ERROR_TOO_MANY_COMMANDS);
1021 	}
1022 
1023 	CommandPacket cp;
1024 	const char *err = this->ReceiveCommand(p, &cp);
1025 
1026 	if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT;
1027 
1028 	NetworkClientInfo *ci = this->GetInfo();
1029 
1030 	if (err != nullptr) {
1031 		IConsolePrint(CC_WARNING, "Dropping client #{} (IP: {}) due to {}.", ci->client_id, this->GetClientIP(), err);
1032 		return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1033 	}
1034 
1035 
1036 	if ((GetCommandFlags(cp.cmd) & CMD_SERVER) && ci->client_id != CLIENT_ID_SERVER) {
1037 		IConsolePrint(CC_WARNING, "Kicking client #{} (IP: {}) due to calling a server only command {}.", ci->client_id, this->GetClientIP(), cp.cmd & CMD_ID_MASK);
1038 		return this->SendError(NETWORK_ERROR_KICKED);
1039 	}
1040 
1041 	if ((GetCommandFlags(cp.cmd) & CMD_SPECTATOR) == 0 && !Company::IsValidID(cp.company) && ci->client_id != CLIENT_ID_SERVER) {
1042 		IConsolePrint(CC_WARNING, "Kicking client #{} (IP: {}) due to calling a non-spectator command {}.", ci->client_id, this->GetClientIP(), cp.cmd & CMD_ID_MASK);
1043 		return this->SendError(NETWORK_ERROR_KICKED);
1044 	}
1045 
1046 	/**
1047 	 * Only CMD_COMPANY_CTRL is always allowed, for the rest, playas needs
1048 	 * to match the company in the packet. If it doesn't, the client has done
1049 	 * something pretty naughty (or a bug), and will be kicked
1050 	 */
1051 	if (!(cp.cmd == CMD_COMPANY_CTRL && cp.p1 == 0 && ci->client_playas == COMPANY_NEW_COMPANY) && ci->client_playas != cp.company) {
1052 		IConsolePrint(CC_WARNING, "Kicking client #{} (IP: {}) due to calling a command as another company {}.",
1053 		               ci->client_playas + 1, this->GetClientIP(), cp.company + 1);
1054 		return this->SendError(NETWORK_ERROR_COMPANY_MISMATCH);
1055 	}
1056 
1057 	if (cp.cmd == CMD_COMPANY_CTRL) {
1058 		if (cp.p1 != 0 || cp.company != COMPANY_SPECTATOR) {
1059 			return this->SendError(NETWORK_ERROR_CHEATER);
1060 		}
1061 
1062 		/* 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! */
1063 		if (Company::GetNumItems() >= _settings_client.network.max_companies) {
1064 			NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_CLIENT, ci->client_id, "cannot create new company, server full", CLIENT_ID_SERVER);
1065 			return NETWORK_RECV_STATUS_OKAY;
1066 		}
1067 	}
1068 
1069 	if (GetCommandFlags(cp.cmd) & CMD_CLIENT_ID) cp.p2 = this->client_id;
1070 
1071 	this->incoming_queue.Append(&cp);
1072 	return NETWORK_RECV_STATUS_OKAY;
1073 }
1074 
Receive_CLIENT_ERROR(Packet * p)1075 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ERROR(Packet *p)
1076 {
1077 	/* This packets means a client noticed an error and is reporting this
1078 	 *  to us. Display the error and report it to the other clients */
1079 	NetworkErrorCode errorno = (NetworkErrorCode)p->Recv_uint8();
1080 
1081 	/* The client was never joined.. thank the client for the packet, but ignore it */
1082 	if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
1083 		return this->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT);
1084 	}
1085 
1086 	std::string client_name = this->GetClientName();
1087 	StringID strid = GetNetworkErrorMsg(errorno);
1088 
1089 	Debug(net, 1, "'{}' reported an error and is closing its connection: {}", client_name, GetString(strid));
1090 
1091 	NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, "", strid);
1092 
1093 	for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
1094 		if (new_cs->status >= STATUS_AUTHORIZED) {
1095 			new_cs->SendErrorQuit(this->client_id, errorno);
1096 		}
1097 	}
1098 
1099 	NetworkAdminClientError(this->client_id, errorno);
1100 
1101 	return this->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT);
1102 }
1103 
Receive_CLIENT_QUIT(Packet * p)1104 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_QUIT(Packet *p)
1105 {
1106 	/* The client was never joined.. thank the client for the packet, but ignore it */
1107 	if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
1108 		return this->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT);
1109 	}
1110 
1111 	/* The client wants to leave. Display this and report it to the other clients. */
1112 	std::string client_name = this->GetClientName();
1113 	NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, "", STR_NETWORK_MESSAGE_CLIENT_LEAVING);
1114 
1115 	for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
1116 		if (new_cs->status >= STATUS_AUTHORIZED && new_cs != this) {
1117 			new_cs->SendQuit(this->client_id);
1118 		}
1119 	}
1120 
1121 	NetworkAdminClientQuit(this->client_id);
1122 
1123 	return this->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT);
1124 }
1125 
Receive_CLIENT_ACK(Packet * p)1126 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ACK(Packet *p)
1127 {
1128 	if (this->status < STATUS_AUTHORIZED) {
1129 		/* Illegal call, return error and ignore the packet */
1130 		return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
1131 	}
1132 
1133 	uint32 frame = p->Recv_uint32();
1134 
1135 	/* The client is trying to catch up with the server */
1136 	if (this->status == STATUS_PRE_ACTIVE) {
1137 		/* The client is not yet caught up? */
1138 		if (frame + DAY_TICKS < _frame_counter) return NETWORK_RECV_STATUS_OKAY;
1139 
1140 		/* Now it is! Unpause the game */
1141 		this->status = STATUS_ACTIVE;
1142 		this->last_token_frame = _frame_counter;
1143 
1144 		/* Execute script for, e.g. MOTD */
1145 		IConsoleCmdExec("exec scripts/on_server_connect.scr 0");
1146 	}
1147 
1148 	/* Get, and validate the token. */
1149 	uint8 token = p->Recv_uint8();
1150 	if (token == this->last_token) {
1151 		/* We differentiate between last_token_frame and last_frame so the lag
1152 		 * test uses the actual lag of the client instead of the lag for getting
1153 		 * the token back and forth; after all, the token is only sent every
1154 		 * time we receive a PACKET_CLIENT_ACK, after which we will send a new
1155 		 * token to the client. If the lag would be one day, then we would not
1156 		 * be sending the new token soon enough for the new daily scheduled
1157 		 * PACKET_CLIENT_ACK. This would then register the lag of the client as
1158 		 * two days, even when it's only a single day. */
1159 		this->last_token_frame = _frame_counter;
1160 		/* Request a new token. */
1161 		this->last_token = 0;
1162 	}
1163 
1164 	/* The client received the frame, make note of it */
1165 	this->last_frame = frame;
1166 	/* With those 2 values we can calculate the lag realtime */
1167 	this->last_frame_server = _frame_counter;
1168 	return NETWORK_RECV_STATUS_OKAY;
1169 }
1170 
1171 
1172 /**
1173  * Send an actual chat message.
1174  * @param action The action that's performed.
1175  * @param desttype The type of destination.
1176  * @param dest The actual destination index.
1177  * @param msg The actual message.
1178  * @param from_id The origin of the message.
1179  * @param data Arbitrary data.
1180  * @param from_admin Whether the origin is an admin or not.
1181  */
NetworkServerSendChat(NetworkAction action,DestType desttype,int dest,const std::string & msg,ClientID from_id,int64 data,bool from_admin)1182 void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, const std::string &msg, ClientID from_id, int64 data, bool from_admin)
1183 {
1184 	const NetworkClientInfo *ci, *ci_own, *ci_to;
1185 
1186 	switch (desttype) {
1187 		case DESTTYPE_CLIENT:
1188 			/* Are we sending to the server? */
1189 			if ((ClientID)dest == CLIENT_ID_SERVER) {
1190 				ci = NetworkClientInfo::GetByClientID(from_id);
1191 				/* Display the text locally, and that is it */
1192 				if (ci != nullptr) {
1193 					NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
1194 
1195 					if (_settings_client.network.server_admin_chat) {
1196 						NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
1197 					}
1198 				}
1199 			} else {
1200 				/* Else find the client to send the message to */
1201 				for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1202 					if (cs->client_id == (ClientID)dest) {
1203 						cs->SendChat(action, from_id, false, msg, data);
1204 						break;
1205 					}
1206 				}
1207 			}
1208 
1209 			/* Display the message locally (so you know you have sent it) */
1210 			if (from_id != (ClientID)dest) {
1211 				if (from_id == CLIENT_ID_SERVER) {
1212 					ci = NetworkClientInfo::GetByClientID(from_id);
1213 					ci_to = NetworkClientInfo::GetByClientID((ClientID)dest);
1214 					if (ci != nullptr && ci_to != nullptr) {
1215 						NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), true, ci_to->client_name, msg, data);
1216 					}
1217 				} else {
1218 					for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1219 						if (cs->client_id == from_id) {
1220 							cs->SendChat(action, (ClientID)dest, true, msg, data);
1221 							break;
1222 						}
1223 					}
1224 				}
1225 			}
1226 			break;
1227 		case DESTTYPE_TEAM: {
1228 			/* If this is false, the message is already displayed on the client who sent it. */
1229 			bool show_local = true;
1230 			/* Find all clients that belong to this company */
1231 			ci_to = nullptr;
1232 			for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1233 				ci = cs->GetInfo();
1234 				if (ci != nullptr && ci->client_playas == (CompanyID)dest) {
1235 					cs->SendChat(action, from_id, false, msg, data);
1236 					if (cs->client_id == from_id) show_local = false;
1237 					ci_to = ci; // Remember a client that is in the company for company-name
1238 				}
1239 			}
1240 
1241 			/* if the server can read it, let the admin network read it, too. */
1242 			if (_local_company == (CompanyID)dest && _settings_client.network.server_admin_chat) {
1243 				NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
1244 			}
1245 
1246 			ci = NetworkClientInfo::GetByClientID(from_id);
1247 			ci_own = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
1248 			if (ci != nullptr && ci_own != nullptr && ci_own->client_playas == dest) {
1249 				NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
1250 				if (from_id == CLIENT_ID_SERVER) show_local = false;
1251 				ci_to = ci_own;
1252 			}
1253 
1254 			/* There is no such client */
1255 			if (ci_to == nullptr) break;
1256 
1257 			/* Display the message locally (so you know you have sent it) */
1258 			if (ci != nullptr && show_local) {
1259 				if (from_id == CLIENT_ID_SERVER) {
1260 					StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
1261 					SetDParam(0, ci_to->client_playas);
1262 					std::string name = GetString(str);
1263 					NetworkTextMessage(action, GetDrawStringCompanyColour(ci_own->client_playas), true, name, msg, data);
1264 				} else {
1265 					for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1266 						if (cs->client_id == from_id) {
1267 							cs->SendChat(action, ci_to->client_id, true, msg, data);
1268 						}
1269 					}
1270 				}
1271 			}
1272 			break;
1273 		}
1274 		default:
1275 			Debug(net, 1, "Received unknown chat destination type {}; doing broadcast instead", desttype);
1276 			FALLTHROUGH;
1277 
1278 		case DESTTYPE_BROADCAST:
1279 			for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1280 				cs->SendChat(action, from_id, false, msg, data);
1281 			}
1282 
1283 			NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
1284 
1285 			ci = NetworkClientInfo::GetByClientID(from_id);
1286 			if (ci != nullptr) {
1287 				NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data, "");
1288 			}
1289 			break;
1290 	}
1291 }
1292 
1293 /**
1294  * Send a chat message from external source.
1295  * @param source Name of the source this message came from.
1296  * @param colour TextColour to use for the message.
1297  * @param user Name of the user who sent the messsage.
1298  * @param msg The actual message.
1299  */
NetworkServerSendExternalChat(const std::string & source,TextColour colour,const std::string & user,const std::string & msg)1300 void NetworkServerSendExternalChat(const std::string &source, TextColour colour, const std::string &user, const std::string &msg)
1301 {
1302 	for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1303 		cs->SendExternalChat(source, colour, user, msg);
1304 	}
1305 	NetworkTextMessage(NETWORK_ACTION_EXTERNAL_CHAT, colour, false, user, msg, 0, source);
1306 }
1307 
Receive_CLIENT_CHAT(Packet * p)1308 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_CHAT(Packet *p)
1309 {
1310 	if (this->status < STATUS_PRE_ACTIVE) {
1311 		/* Illegal call, return error and ignore the packet */
1312 		return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
1313 	}
1314 
1315 	NetworkAction action = (NetworkAction)p->Recv_uint8();
1316 	DestType desttype = (DestType)p->Recv_uint8();
1317 	int dest = p->Recv_uint32();
1318 
1319 	std::string msg = p->Recv_string(NETWORK_CHAT_LENGTH);
1320 	int64 data = p->Recv_uint64();
1321 
1322 	NetworkClientInfo *ci = this->GetInfo();
1323 	switch (action) {
1324 		case NETWORK_ACTION_CHAT:
1325 		case NETWORK_ACTION_CHAT_CLIENT:
1326 		case NETWORK_ACTION_CHAT_COMPANY:
1327 			NetworkServerSendChat(action, desttype, dest, msg, this->client_id, data);
1328 			break;
1329 		default:
1330 			IConsolePrint(CC_WARNING, "Kicking client #{} (IP: {}) due to unknown chact action.", ci->client_id, this->GetClientIP());
1331 			return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1332 	}
1333 	return NETWORK_RECV_STATUS_OKAY;
1334 }
1335 
Receive_CLIENT_SET_PASSWORD(Packet * p)1336 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_PASSWORD(Packet *p)
1337 {
1338 	if (this->status != STATUS_ACTIVE) {
1339 		/* Illegal call, return error and ignore the packet */
1340 		return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1341 	}
1342 
1343 	std::string password = p->Recv_string(NETWORK_PASSWORD_LENGTH);
1344 	const NetworkClientInfo *ci = this->GetInfo();
1345 
1346 	NetworkServerSetCompanyPassword(ci->client_playas, password);
1347 	return NETWORK_RECV_STATUS_OKAY;
1348 }
1349 
Receive_CLIENT_SET_NAME(Packet * p)1350 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_NAME(Packet *p)
1351 {
1352 	if (this->status != STATUS_ACTIVE) {
1353 		/* Illegal call, return error and ignore the packet */
1354 		return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1355 	}
1356 
1357 	NetworkClientInfo *ci;
1358 
1359 	std::string client_name = p->Recv_string(NETWORK_CLIENT_NAME_LENGTH);
1360 	ci = this->GetInfo();
1361 
1362 	if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT;
1363 
1364 	if (ci != nullptr) {
1365 		if (!NetworkIsValidClientName(client_name)) {
1366 			/* An invalid client name was given. However, the client ensures the name
1367 			 * is valid before it is sent over the network, so something went horribly
1368 			 * wrong. This is probably someone trying to troll us. */
1369 			return this->SendError(NETWORK_ERROR_INVALID_CLIENT_NAME);
1370 		}
1371 
1372 		/* Display change */
1373 		if (NetworkMakeClientNameUnique(client_name)) {
1374 			NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, client_name);
1375 			ci->client_name = client_name;
1376 			NetworkUpdateClientInfo(ci->client_id);
1377 		}
1378 	}
1379 	return NETWORK_RECV_STATUS_OKAY;
1380 }
1381 
Receive_CLIENT_RCON(Packet * p)1382 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_RCON(Packet *p)
1383 {
1384 	if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1385 
1386 	if (_settings_client.network.rcon_password.empty()) return NETWORK_RECV_STATUS_OKAY;
1387 
1388 	std::string password = p->Recv_string(NETWORK_PASSWORD_LENGTH);
1389 	std::string command = p->Recv_string(NETWORK_RCONCOMMAND_LENGTH);
1390 
1391 	if (_settings_client.network.rcon_password.compare(password) != 0) {
1392 		Debug(net, 1, "[rcon] Wrong password from client-id {}", this->client_id);
1393 		return NETWORK_RECV_STATUS_OKAY;
1394 	}
1395 
1396 	Debug(net, 3, "[rcon] Client-id {} executed: {}", this->client_id, command);
1397 
1398 	_redirect_console_to_client = this->client_id;
1399 	IConsoleCmdExec(command.c_str());
1400 	_redirect_console_to_client = INVALID_CLIENT_ID;
1401 	return NETWORK_RECV_STATUS_OKAY;
1402 }
1403 
Receive_CLIENT_MOVE(Packet * p)1404 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MOVE(Packet *p)
1405 {
1406 	if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
1407 
1408 	CompanyID company_id = (Owner)p->Recv_uint8();
1409 
1410 	/* Check if the company is valid, we don't allow moving to AI companies */
1411 	if (company_id != COMPANY_SPECTATOR && !Company::IsValidHumanID(company_id)) return NETWORK_RECV_STATUS_OKAY;
1412 
1413 	/* Check if we require a password for this company */
1414 	if (company_id != COMPANY_SPECTATOR && !_network_company_states[company_id].password.empty()) {
1415 		/* we need a password from the client - should be in this packet */
1416 		std::string password = p->Recv_string(NETWORK_PASSWORD_LENGTH);
1417 
1418 		/* Incorrect password sent, return! */
1419 		if (_network_company_states[company_id].password.compare(password) != 0) {
1420 			Debug(net, 2, "Wrong password from client-id #{} for company #{}", this->client_id, company_id + 1);
1421 			return NETWORK_RECV_STATUS_OKAY;
1422 		}
1423 	}
1424 
1425 	/* if we get here we can move the client */
1426 	NetworkServerDoMove(this->client_id, company_id);
1427 	return NETWORK_RECV_STATUS_OKAY;
1428 }
1429 
1430 /**
1431  * Populate the company stats.
1432  * @param stats the stats to update
1433  */
NetworkPopulateCompanyStats(NetworkCompanyStats * stats)1434 void NetworkPopulateCompanyStats(NetworkCompanyStats *stats)
1435 {
1436 	memset(stats, 0, sizeof(*stats) * MAX_COMPANIES);
1437 
1438 	/* Go through all vehicles and count the type of vehicles */
1439 	for (const Vehicle *v : Vehicle::Iterate()) {
1440 		if (!Company::IsValidID(v->owner) || !v->IsPrimaryVehicle()) continue;
1441 		byte type = 0;
1442 		switch (v->type) {
1443 			case VEH_TRAIN: type = NETWORK_VEH_TRAIN; break;
1444 			case VEH_ROAD: type = RoadVehicle::From(v)->IsBus() ? NETWORK_VEH_BUS : NETWORK_VEH_LORRY; break;
1445 			case VEH_AIRCRAFT: type = NETWORK_VEH_PLANE; break;
1446 			case VEH_SHIP: type = NETWORK_VEH_SHIP; break;
1447 			default: continue;
1448 		}
1449 		stats[v->owner].num_vehicle[type]++;
1450 	}
1451 
1452 	/* Go through all stations and count the types of stations */
1453 	for (const Station *s : Station::Iterate()) {
1454 		if (Company::IsValidID(s->owner)) {
1455 			NetworkCompanyStats *npi = &stats[s->owner];
1456 
1457 			if (s->facilities & FACIL_TRAIN)      npi->num_station[NETWORK_VEH_TRAIN]++;
1458 			if (s->facilities & FACIL_TRUCK_STOP) npi->num_station[NETWORK_VEH_LORRY]++;
1459 			if (s->facilities & FACIL_BUS_STOP)   npi->num_station[NETWORK_VEH_BUS]++;
1460 			if (s->facilities & FACIL_AIRPORT)    npi->num_station[NETWORK_VEH_PLANE]++;
1461 			if (s->facilities & FACIL_DOCK)       npi->num_station[NETWORK_VEH_SHIP]++;
1462 		}
1463 	}
1464 }
1465 
1466 /**
1467  * Send updated client info of a particular client.
1468  * @param client_id The client to send it for.
1469  */
NetworkUpdateClientInfo(ClientID client_id)1470 void NetworkUpdateClientInfo(ClientID client_id)
1471 {
1472 	NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1473 
1474 	if (ci == nullptr) return;
1475 
1476 	Debug(desync, 1, "client: {:08x}; {:02x}; {:02x}; {:04x}", _date, _date_fract, (int)ci->client_playas, client_id);
1477 
1478 	for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1479 		if (cs->status >= ServerNetworkGameSocketHandler::STATUS_AUTHORIZED) {
1480 			cs->SendClientInfo(ci);
1481 		}
1482 	}
1483 
1484 	NetworkAdminClientUpdate(ci);
1485 }
1486 
1487 /** Check if we want to restart the map */
NetworkCheckRestartMap()1488 static void NetworkCheckRestartMap()
1489 {
1490 	if (_settings_client.network.restart_game_year != 0 && _cur_year >= _settings_client.network.restart_game_year) {
1491 		Debug(net, 3, "Auto-restarting map: year {} reached", _cur_year);
1492 
1493 		_settings_newgame.game_creation.generation_seed = GENERATE_NEW_SEED;
1494 		switch(_file_to_saveload.abstract_ftype) {
1495 			case FT_SAVEGAME:
1496 			case FT_SCENARIO:
1497 				_switch_mode = SM_LOAD_GAME;
1498 				break;
1499 
1500 			case FT_HEIGHTMAP:
1501 				_switch_mode = SM_START_HEIGHTMAP;
1502 				break;
1503 
1504 			default:
1505 				_switch_mode = SM_NEWGAME;
1506 		}
1507 	}
1508 }
1509 
1510 /** Check if the server has autoclean_companies activated
1511  * Two things happen:
1512  *     1) If a company is not protected, it is closed after 1 year (for example)
1513  *     2) If a company is protected, protection is disabled after 3 years (for example)
1514  *          (and item 1. happens a year later)
1515  */
NetworkAutoCleanCompanies()1516 static void NetworkAutoCleanCompanies()
1517 {
1518 	bool clients_in_company[MAX_COMPANIES];
1519 	int vehicles_in_company[MAX_COMPANIES];
1520 
1521 	if (!_settings_client.network.autoclean_companies) return;
1522 
1523 	memset(clients_in_company, 0, sizeof(clients_in_company));
1524 
1525 	/* Detect the active companies */
1526 	for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1527 		if (Company::IsValidID(ci->client_playas)) clients_in_company[ci->client_playas] = true;
1528 	}
1529 
1530 	if (!_network_dedicated) {
1531 		const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
1532 		if (Company::IsValidID(ci->client_playas)) clients_in_company[ci->client_playas] = true;
1533 	}
1534 
1535 	if (_settings_client.network.autoclean_novehicles != 0) {
1536 		memset(vehicles_in_company, 0, sizeof(vehicles_in_company));
1537 
1538 		for (const Vehicle *v : Vehicle::Iterate()) {
1539 			if (!Company::IsValidID(v->owner) || !v->IsPrimaryVehicle()) continue;
1540 			vehicles_in_company[v->owner]++;
1541 		}
1542 	}
1543 
1544 	/* Go through all the companies */
1545 	for (const Company *c : Company::Iterate()) {
1546 		/* Skip the non-active once */
1547 		if (c->is_ai) continue;
1548 
1549 		if (!clients_in_company[c->index]) {
1550 			/* The company is empty for one month more */
1551 			_network_company_states[c->index].months_empty++;
1552 
1553 			/* Is the company empty for autoclean_unprotected-months, and is there no protection? */
1554 			if (_settings_client.network.autoclean_unprotected != 0 && _network_company_states[c->index].months_empty > _settings_client.network.autoclean_unprotected && _network_company_states[c->index].password.empty()) {
1555 				/* Shut the company down */
1556 				DoCommandP(0, CCA_DELETE | c->index << 16 | CRR_AUTOCLEAN << 24, 0, CMD_COMPANY_CTRL);
1557 				IConsolePrint(CC_INFO, "Auto-cleaned company #{} with no password.", c->index + 1);
1558 			}
1559 			/* Is the company empty for autoclean_protected-months, and there is a protection? */
1560 			if (_settings_client.network.autoclean_protected != 0 && _network_company_states[c->index].months_empty > _settings_client.network.autoclean_protected && !_network_company_states[c->index].password.empty()) {
1561 				/* Unprotect the company */
1562 				_network_company_states[c->index].password.clear();
1563 				IConsolePrint(CC_INFO, "Auto-removed protection from company #{}.", c->index + 1);
1564 				_network_company_states[c->index].months_empty = 0;
1565 				NetworkServerUpdateCompanyPassworded(c->index, false);
1566 			}
1567 			/* Is the company empty for autoclean_novehicles-months, and has no vehicles? */
1568 			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) {
1569 				/* Shut the company down */
1570 				DoCommandP(0, CCA_DELETE | c->index << 16 | CRR_AUTOCLEAN << 24, 0, CMD_COMPANY_CTRL);
1571 				IConsolePrint(CC_INFO, "Auto-cleaned company #{} with no vehicles.", c->index + 1);
1572 			}
1573 		} else {
1574 			/* It is not empty, reset the date */
1575 			_network_company_states[c->index].months_empty = 0;
1576 		}
1577 	}
1578 }
1579 
1580 /**
1581  * Check whether a name is unique, and otherwise try to make it unique.
1582  * @param new_name The name to check/modify.
1583  * @return True if an unique name was achieved.
1584  */
NetworkMakeClientNameUnique(std::string & name)1585 bool NetworkMakeClientNameUnique(std::string &name)
1586 {
1587 	bool is_name_unique = false;
1588 	std::string original_name = name;
1589 
1590 	for (uint number = 1; !is_name_unique && number <= MAX_CLIENTS; number++) {  // Something's really wrong when there're more names than clients
1591 		is_name_unique = true;
1592 		for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1593 			if (ci->client_name == name) {
1594 				/* Name already in use */
1595 				is_name_unique = false;
1596 				break;
1597 			}
1598 		}
1599 		/* Check if it is the same as the server-name */
1600 		const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
1601 		if (ci != nullptr) {
1602 			if (ci->client_name == name) is_name_unique = false; // name already in use
1603 		}
1604 
1605 		if (!is_name_unique) {
1606 			/* Try a new name (<name> #1, <name> #2, and so on) */
1607 			name = original_name + " #" + std::to_string(number);
1608 
1609 			/* The constructed client name is larger than the limit,
1610 			 * so... bail out as no valid name can be created. */
1611 			if (name.size() >= NETWORK_CLIENT_NAME_LENGTH) return false;
1612 		}
1613 	}
1614 
1615 	return is_name_unique;
1616 }
1617 
1618 /**
1619  * Change the client name of the given client
1620  * @param client_id the client to change the name of
1621  * @param new_name the new name for the client
1622  * @return true iff the name was changed
1623  */
NetworkServerChangeClientName(ClientID client_id,const std::string & new_name)1624 bool NetworkServerChangeClientName(ClientID client_id, const std::string &new_name)
1625 {
1626 	/* Check if the name's already in use */
1627 	for (NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
1628 		if (ci->client_name.compare(new_name) == 0) return false;
1629 	}
1630 
1631 	NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1632 	if (ci == nullptr) return false;
1633 
1634 	NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, true, ci->client_name, new_name);
1635 
1636 	ci->client_name = new_name;
1637 
1638 	NetworkUpdateClientInfo(client_id);
1639 	return true;
1640 }
1641 
1642 /**
1643  * Set/Reset a company password on the server end.
1644  * @param company_id ID of the company the password should be changed for.
1645  * @param password The new password.
1646  * @param already_hashed Is the given password already hashed?
1647  */
NetworkServerSetCompanyPassword(CompanyID company_id,const std::string & password,bool already_hashed)1648 void NetworkServerSetCompanyPassword(CompanyID company_id, const std::string &password, bool already_hashed)
1649 {
1650 	if (!Company::IsValidHumanID(company_id)) return;
1651 
1652 	if (already_hashed) {
1653 		_network_company_states[company_id].password = password;
1654 	} else {
1655 		_network_company_states[company_id].password = GenerateCompanyPasswordHash(password, _settings_client.network.network_id, _settings_game.game_creation.generation_seed);
1656 	}
1657 
1658 	NetworkServerUpdateCompanyPassworded(company_id, !_network_company_states[company_id].password.empty());
1659 }
1660 
1661 /**
1662  * Handle the command-queue of a socket.
1663  * @param cs The socket to handle the queue for.
1664  */
NetworkHandleCommandQueue(NetworkClientSocket * cs)1665 static void NetworkHandleCommandQueue(NetworkClientSocket *cs)
1666 {
1667 	CommandPacket *cp;
1668 	while ((cp = cs->outgoing_queue.Pop()) != nullptr) {
1669 		cs->SendCommand(cp);
1670 		delete cp;
1671 	}
1672 }
1673 
1674 /**
1675  * This is called every tick if this is a _network_server
1676  * @param send_frame Whether to send the frame to the clients.
1677  */
NetworkServer_Tick(bool send_frame)1678 void NetworkServer_Tick(bool send_frame)
1679 {
1680 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1681 	bool send_sync = false;
1682 #endif
1683 
1684 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1685 	if (_frame_counter >= _last_sync_frame + _settings_client.network.sync_freq) {
1686 		_last_sync_frame = _frame_counter;
1687 		send_sync = true;
1688 	}
1689 #endif
1690 
1691 	/* Now we are done with the frame, inform the clients that they can
1692 	 *  do their frame! */
1693 	for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1694 		/* We allow a number of bytes per frame, but only to the burst amount
1695 		 * to be available for packet receiving at any particular time. */
1696 		cs->receive_limit = std::min<size_t>(cs->receive_limit + _settings_client.network.bytes_per_frame,
1697 				_settings_client.network.bytes_per_frame_burst);
1698 
1699 		/* Check if the speed of the client is what we can expect from a client */
1700 		uint lag = NetworkCalculateLag(cs);
1701 		switch (cs->status) {
1702 			case NetworkClientSocket::STATUS_ACTIVE:
1703 				if (lag > _settings_client.network.max_lag_time) {
1704 					/* Client did still not report in within the specified limit. */
1705 					IConsolePrint(CC_WARNING, cs->last_packet + std::chrono::milliseconds(lag * MILLISECONDS_PER_TICK) > std::chrono::steady_clock::now() ?
1706 							/* A packet was received in the last three game days, so the client is likely lagging behind. */
1707 								"Client #{} (IP: {}) is dropped because the client's game state is more than {} ticks behind." :
1708 							/* No packet was received in the last three game days; sounds like a lost connection. */
1709 								"Client #{} (IP: {}) is dropped because the client did not respond for more than {} ticks.",
1710 							cs->client_id, cs->GetClientIP(), lag);
1711 					cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
1712 					continue;
1713 				}
1714 
1715 				/* Report once per time we detect the lag, and only when we
1716 				 * received a packet in the last 2 seconds. If we
1717 				 * did not receive a packet, then the client is not just
1718 				 * slow, but the connection is likely severed. Mentioning
1719 				 * frame_freq is not useful in this case. */
1720 				if (lag > (uint)DAY_TICKS && cs->lag_test == 0 && cs->last_packet + std::chrono::seconds(2) > std::chrono::steady_clock::now()) {
1721 					IConsolePrint(CC_WARNING, "[{}] Client #{} is slow, try increasing [network.]frame_freq to a higher value!", _frame_counter, cs->client_id);
1722 					cs->lag_test = 1;
1723 				}
1724 
1725 				if (cs->last_frame_server - cs->last_token_frame >= _settings_client.network.max_lag_time) {
1726 					/* This is a bad client! It didn't send the right token back within time. */
1727 					IConsolePrint(CC_WARNING, "Client #{} (IP: {}) is dropped because it fails to send valid acks.", cs->client_id, cs->GetClientIP());
1728 					cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
1729 					continue;
1730 				}
1731 				break;
1732 
1733 			case NetworkClientSocket::STATUS_INACTIVE:
1734 			case NetworkClientSocket::STATUS_NEWGRFS_CHECK:
1735 			case NetworkClientSocket::STATUS_AUTHORIZED:
1736 				/* NewGRF check and authorized states should be handled almost instantly.
1737 				 * So give them some lee-way, likewise for the query with inactive. */
1738 				if (lag > _settings_client.network.max_init_time) {
1739 					IConsolePrint(CC_WARNING, "Client #{} (IP: {}) is dropped because it took longer than {} ticks to start the joining process.", cs->client_id, cs->GetClientIP(), _settings_client.network.max_init_time);
1740 					cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
1741 					continue;
1742 				}
1743 				break;
1744 
1745 			case NetworkClientSocket::STATUS_MAP_WAIT:
1746 				/* Send every two seconds a packet to the client, to make sure
1747 				 * it knows the server is still there; just someone else is
1748 				 * still receiving the map. */
1749 				if (std::chrono::steady_clock::now() > cs->last_packet + std::chrono::seconds(2)) {
1750 					cs->SendWait();
1751 					/* We need to reset the timer, as otherwise we will be
1752 					 * spamming the client. Strictly speaking this variable
1753 					 * tracks when we last received a packet from the client,
1754 					 * but as it is waiting, it will not send us any till we
1755 					 * start sending them data. */
1756 					cs->last_packet = std::chrono::steady_clock::now();
1757 				}
1758 				break;
1759 
1760 			case NetworkClientSocket::STATUS_MAP:
1761 				/* Downloading the map... this is the amount of time since starting the saving. */
1762 				if (lag > _settings_client.network.max_download_time) {
1763 					IConsolePrint(CC_WARNING, "Client #{} (IP: {}) is dropped because it took longer than {} ticks to download the map.", cs->client_id, cs->GetClientIP(), _settings_client.network.max_download_time);
1764 					cs->SendError(NETWORK_ERROR_TIMEOUT_MAP);
1765 					continue;
1766 				}
1767 				break;
1768 
1769 			case NetworkClientSocket::STATUS_DONE_MAP:
1770 			case NetworkClientSocket::STATUS_PRE_ACTIVE:
1771 				/* The map has been sent, so this is for loading the map and syncing up. */
1772 				if (lag > _settings_client.network.max_join_time) {
1773 					IConsolePrint(CC_WARNING, "Client #{} (IP: {}) is dropped because it took longer than {} ticks to join.", cs->client_id, cs->GetClientIP(), _settings_client.network.max_join_time);
1774 					cs->SendError(NETWORK_ERROR_TIMEOUT_JOIN);
1775 					continue;
1776 				}
1777 				break;
1778 
1779 			case NetworkClientSocket::STATUS_AUTH_GAME:
1780 			case NetworkClientSocket::STATUS_AUTH_COMPANY:
1781 				/* These don't block? */
1782 				if (lag > _settings_client.network.max_password_time) {
1783 					IConsolePrint(CC_WARNING, "Client #{} (IP: {}) is dropped because it took longer than {} ticks to enter the password.", cs->client_id, cs->GetClientIP(), _settings_client.network.max_password_time);
1784 					cs->SendError(NETWORK_ERROR_TIMEOUT_PASSWORD);
1785 					continue;
1786 				}
1787 				break;
1788 
1789 			case NetworkClientSocket::STATUS_END:
1790 				/* Bad server/code. */
1791 				NOT_REACHED();
1792 		}
1793 
1794 		if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) {
1795 			/* Check if we can send command, and if we have anything in the queue */
1796 			NetworkHandleCommandQueue(cs);
1797 
1798 			/* Send an updated _frame_counter_max to the client */
1799 			if (send_frame) cs->SendFrame();
1800 
1801 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
1802 			/* Send a sync-check packet */
1803 			if (send_sync) cs->SendSync();
1804 #endif
1805 		}
1806 	}
1807 }
1808 
1809 /** Yearly "callback". Called whenever the year changes. */
NetworkServerYearlyLoop()1810 void NetworkServerYearlyLoop()
1811 {
1812 	NetworkCheckRestartMap();
1813 	NetworkAdminUpdate(ADMIN_FREQUENCY_ANUALLY);
1814 }
1815 
1816 /** Monthly "callback". Called whenever the month changes. */
NetworkServerMonthlyLoop()1817 void NetworkServerMonthlyLoop()
1818 {
1819 	NetworkAutoCleanCompanies();
1820 	NetworkAdminUpdate(ADMIN_FREQUENCY_MONTHLY);
1821 	if ((_cur_month % 3) == 0) NetworkAdminUpdate(ADMIN_FREQUENCY_QUARTERLY);
1822 }
1823 
1824 /** Daily "callback". Called whenever the date changes. */
NetworkServerDailyLoop()1825 void NetworkServerDailyLoop()
1826 {
1827 	NetworkAdminUpdate(ADMIN_FREQUENCY_DAILY);
1828 	if ((_date % 7) == 3) NetworkAdminUpdate(ADMIN_FREQUENCY_WEEKLY);
1829 }
1830 
1831 /**
1832  * Get the IP address/hostname of the connected client.
1833  * @return The IP address.
1834  */
GetClientIP()1835 const std::string &ServerNetworkGameSocketHandler::GetClientIP()
1836 {
1837 	return this->client_address.GetHostname();
1838 }
1839 
1840 /** Show the status message of all clients on the console. */
NetworkServerShowStatusToConsole()1841 void NetworkServerShowStatusToConsole()
1842 {
1843 	static const char * const stat_str[] = {
1844 		"inactive",
1845 		"checking NewGRFs",
1846 		"authorizing (server password)",
1847 		"authorizing (company password)",
1848 		"authorized",
1849 		"waiting",
1850 		"loading map",
1851 		"map done",
1852 		"ready",
1853 		"active"
1854 	};
1855 	static_assert(lengthof(stat_str) == NetworkClientSocket::STATUS_END);
1856 
1857 	for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1858 		NetworkClientInfo *ci = cs->GetInfo();
1859 		if (ci == nullptr) continue;
1860 		uint lag = NetworkCalculateLag(cs);
1861 		const char *status;
1862 
1863 		status = (cs->status < (ptrdiff_t)lengthof(stat_str) ? stat_str[cs->status] : "unknown");
1864 		IConsolePrint(CC_INFO, "Client #{}  name: '{}'  status: '{}'  frame-lag: {}  company: {}  IP: {}",
1865 			cs->client_id, ci->client_name.c_str(), status, lag,
1866 			ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0),
1867 			cs->GetClientIP());
1868 	}
1869 }
1870 
1871 /**
1872  * Send Config Update
1873  */
NetworkServerSendConfigUpdate()1874 void NetworkServerSendConfigUpdate()
1875 {
1876 	for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1877 		if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) cs->SendConfigUpdate();
1878 	}
1879 }
1880 
1881 /** Update the server's NetworkServerGameInfo due to changes in settings. */
NetworkServerUpdateGameInfo()1882 void NetworkServerUpdateGameInfo()
1883 {
1884 	if (_network_server) FillStaticNetworkServerGameInfo();
1885 }
1886 
1887 /**
1888  * Tell that a particular company is (not) passworded.
1889  * @param company_id The company that got/removed the password.
1890  * @param passworded Whether the password was received or removed.
1891  */
NetworkServerUpdateCompanyPassworded(CompanyID company_id,bool passworded)1892 void NetworkServerUpdateCompanyPassworded(CompanyID company_id, bool passworded)
1893 {
1894 	if (NetworkCompanyIsPassworded(company_id) == passworded) return;
1895 
1896 	SB(_network_company_passworded, company_id, 1, !!passworded);
1897 	SetWindowClassesDirty(WC_COMPANY);
1898 
1899 	for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
1900 		if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) cs->SendCompanyUpdate();
1901 	}
1902 
1903 	NetworkAdminCompanyUpdate(Company::GetIfValid(company_id));
1904 }
1905 
1906 /**
1907  * Handle the tid-bits of moving a client from one company to another.
1908  * @param client_id id of the client we want to move.
1909  * @param company_id id of the company we want to move the client to.
1910  * @return void
1911  */
NetworkServerDoMove(ClientID client_id,CompanyID company_id)1912 void NetworkServerDoMove(ClientID client_id, CompanyID company_id)
1913 {
1914 	/* Only allow non-dedicated servers and normal clients to be moved */
1915 	if (client_id == CLIENT_ID_SERVER && _network_dedicated) return;
1916 
1917 	NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1918 
1919 	/* No need to waste network resources if the client is in the company already! */
1920 	if (ci->client_playas == company_id) return;
1921 
1922 	ci->client_playas = company_id;
1923 
1924 	if (client_id == CLIENT_ID_SERVER) {
1925 		SetLocalCompany(company_id);
1926 	} else {
1927 		NetworkClientSocket *cs = NetworkClientSocket::GetByClientID(client_id);
1928 		/* When the company isn't authorized we can't move them yet. */
1929 		if (cs->status < NetworkClientSocket::STATUS_AUTHORIZED) return;
1930 		cs->SendMove(client_id, company_id);
1931 	}
1932 
1933 	/* announce the client's move */
1934 	NetworkUpdateClientInfo(client_id);
1935 
1936 	NetworkAction action = (company_id == COMPANY_SPECTATOR) ? NETWORK_ACTION_COMPANY_SPECTATOR : NETWORK_ACTION_COMPANY_JOIN;
1937 	NetworkServerSendChat(action, DESTTYPE_BROADCAST, 0, "", client_id, company_id + 1);
1938 
1939 	InvalidateWindowData(WC_CLIENT_LIST, 0);
1940 }
1941 
1942 /**
1943  * Send an rcon reply to the client.
1944  * @param client_id The identifier of the client.
1945  * @param colour_code The colour of the text.
1946  * @param string The actual reply.
1947  */
NetworkServerSendRcon(ClientID client_id,TextColour colour_code,const std::string & string)1948 void NetworkServerSendRcon(ClientID client_id, TextColour colour_code, const std::string &string)
1949 {
1950 	NetworkClientSocket::GetByClientID(client_id)->SendRConResult(colour_code, string);
1951 }
1952 
1953 /**
1954  * Kick a single client.
1955  * @param client_id The client to kick.
1956  * @param reason In case of kicking a client, specifies the reason for kicking the client.
1957  */
NetworkServerKickClient(ClientID client_id,const std::string & reason)1958 void NetworkServerKickClient(ClientID client_id, const std::string &reason)
1959 {
1960 	if (client_id == CLIENT_ID_SERVER) return;
1961 	NetworkClientSocket::GetByClientID(client_id)->SendError(NETWORK_ERROR_KICKED, reason);
1962 }
1963 
1964 /**
1965  * Ban, or kick, everyone joined from the given client's IP.
1966  * @param client_id The client to check for.
1967  * @param ban Whether to ban or kick.
1968  * @param reason In case of kicking a client, specifies the reason for kicking the client.
1969  */
NetworkServerKickOrBanIP(ClientID client_id,bool ban,const std::string & reason)1970 uint NetworkServerKickOrBanIP(ClientID client_id, bool ban, const std::string &reason)
1971 {
1972 	return NetworkServerKickOrBanIP(NetworkClientSocket::GetByClientID(client_id)->GetClientIP(), ban, reason);
1973 }
1974 
1975 /**
1976  * Kick or ban someone based on an IP address.
1977  * @param ip The IP address/range to ban/kick.
1978  * @param ban Whether to ban or just kick.
1979  * @param reason In case of kicking a client, specifies the reason for kicking the client.
1980  */
NetworkServerKickOrBanIP(const std::string & ip,bool ban,const std::string & reason)1981 uint NetworkServerKickOrBanIP(const std::string &ip, bool ban, const std::string &reason)
1982 {
1983 	/* Add address to ban-list */
1984 	if (ban) {
1985 		bool contains = false;
1986 		for (const auto &iter : _network_ban_list) {
1987 			if (iter == ip) {
1988 				contains = true;
1989 				break;
1990 			}
1991 		}
1992 		if (!contains) _network_ban_list.emplace_back(ip);
1993 	}
1994 
1995 	uint n = 0;
1996 
1997 	/* There can be multiple clients with the same IP, kick them all but don't kill the server,
1998 	 * or the client doing the rcon. The latter can't be kicked because kicking frees closes
1999 	 * and subsequently free the connection related instances, which we would be reading from
2000 	 * and writing to after returning. So we would read or write data from freed memory up till
2001 	 * the segfault triggers. */
2002 	for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
2003 		if (cs->client_id == CLIENT_ID_SERVER) continue;
2004 		if (cs->client_id == _redirect_console_to_client) continue;
2005 		if (cs->client_address.IsInNetmask(ip)) {
2006 			NetworkServerKickClient(cs->client_id, reason);
2007 			n++;
2008 		}
2009 	}
2010 
2011 	return n;
2012 }
2013 
2014 /**
2015  * Check whether a particular company has clients.
2016  * @param company The company to check.
2017  * @return True if at least one client is joined to the company.
2018  */
NetworkCompanyHasClients(CompanyID company)2019 bool NetworkCompanyHasClients(CompanyID company)
2020 {
2021 	for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
2022 		if (ci->client_playas == company) return true;
2023 	}
2024 	return false;
2025 }
2026 
2027 
2028 /**
2029  * Get the name of the client, if the user did not send it yet, Client ID is used.
2030  * @param client_name The variable to write the name to.
2031  * @param last        The pointer to the last element of the destination buffer
2032  */
GetClientName() const2033 std::string ServerNetworkGameSocketHandler::GetClientName() const
2034 {
2035 	const NetworkClientInfo *ci = this->GetInfo();
2036 	if (ci != nullptr && !ci->client_name.empty()) return ci->client_name;
2037 
2038 	return fmt::format("Client #{}", this->client_id);
2039 }
2040 
2041 /**
2042  * Print all the clients to the console
2043  */
NetworkPrintClients()2044 void NetworkPrintClients()
2045 {
2046 	for (NetworkClientInfo *ci : NetworkClientInfo::Iterate()) {
2047 		if (_network_server) {
2048 			IConsolePrint(CC_INFO, "Client #{}  name: '{}'  company: {}  IP: {}",
2049 					ci->client_id,
2050 					ci->client_name,
2051 					ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0),
2052 					ci->client_id == CLIENT_ID_SERVER ? "server" : NetworkClientSocket::GetByClientID(ci->client_id)->GetClientIP());
2053 		} else {
2054 			IConsolePrint(CC_INFO, "Client #{}  name: '{}'  company: {}",
2055 					ci->client_id,
2056 					ci->client_name,
2057 					ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0));
2058 		}
2059 	}
2060 }
2061 
2062 /**
2063  * Perform all the server specific administration of a new company.
2064  * @param c  The newly created company; can't be nullptr.
2065  * @param ci The client information of the client that made the company; can be nullptr.
2066  */
NetworkServerNewCompany(const Company * c,NetworkClientInfo * ci)2067 void NetworkServerNewCompany(const Company *c, NetworkClientInfo *ci)
2068 {
2069 	assert(c != nullptr);
2070 
2071 	if (!_network_server) return;
2072 
2073 	_network_company_states[c->index].months_empty = 0;
2074 	_network_company_states[c->index].password.clear();
2075 	NetworkServerUpdateCompanyPassworded(c->index, false);
2076 
2077 	if (ci != nullptr) {
2078 		/* ci is nullptr when replaying, or for AIs. In neither case there is a client. */
2079 		ci->client_playas = c->index;
2080 		NetworkUpdateClientInfo(ci->client_id);
2081 		NetworkSendCommand(0, 0, 0, CMD_RENAME_PRESIDENT, nullptr, ci->client_name, c->index);
2082 	}
2083 
2084 	/* Announce new company on network. */
2085 	NetworkAdminCompanyInfo(c, true);
2086 
2087 	if (ci != nullptr) {
2088 		/* ci is nullptr when replaying, or for AIs. In neither case there is a client.
2089 		   We need to send Admin port update here so that they first know about the new company
2090 		   and then learn about a possibly joining client (see FS#6025) */
2091 		NetworkServerSendChat(NETWORK_ACTION_COMPANY_NEW, DESTTYPE_BROADCAST, 0, "", ci->client_id, c->index + 1);
2092 	}
2093 }
2094