4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
10 /** @file network_client.cpp Client part of the network protocol. */
14 #include "../stdafx.h"
15 #include "network_gui.h"
16 #include "../saveload/saveload.h"
17 #include "../saveload/saveload_filter.h"
18 #include "../command_func.h"
19 #include "../console_func.h"
20 #include "../strings_func.h"
21 #include "../window_func.h"
22 #include "../company_func.h"
23 #include "../company_base.h"
24 #include "../company_gui.h"
25 #include "../core/random_func.hpp"
26 #include "../date_func.h"
27 #include "../gfx_func.h"
31 #include "network_base.h"
32 #include "network_client.h"
33 #include "../core/backup_type.hpp"
35 #include "table/strings.h"
37 #include "../safeguards.h"
39 /* This file handles all the client-commands */
42 /** Read some packets, and when do use that data as initial load filter. */
43 struct PacketReader
: LoadFilter
{
44 static const size_t CHUNK
= 32 * 1024; ///< 32 KiB chunks of memory.
46 AutoFreeSmallVector
<byte
*, 16> blocks
; ///< Buffer with blocks of allocated memory.
47 byte
*buf
; ///< Buffer we're going to write to/read from.
48 byte
*bufe
; ///< End of the buffer we write to/read from.
49 byte
**block
; ///< The block we're reading from/writing to.
50 size_t written_bytes
; ///< The total number of bytes we've written.
51 size_t read_bytes
; ///< The total number of read bytes.
53 /** Initialise everything. */
54 PacketReader() : LoadFilter(NULL
), buf(NULL
), bufe(NULL
), block(NULL
), written_bytes(0), read_bytes(0)
59 * Add a packet to this buffer.
60 * @param p The packet to add.
62 void AddPacket(const Packet
*p
)
64 assert(this->read_bytes
== 0);
66 size_t in_packet
= p
->size
- p
->pos
;
67 size_t to_write
= min((size_t)(this->bufe
- this->buf
), in_packet
);
68 const byte
*pbuf
= p
->buffer
+ p
->pos
;
70 this->written_bytes
+= in_packet
;
72 memcpy(this->buf
, pbuf
, to_write
);
73 this->buf
+= to_write
;
76 /* Did everything fit in the current chunk, then we're done. */
77 if (to_write
== in_packet
) return;
79 /* Allocate a new chunk and add the remaining data. */
81 to_write
= in_packet
- to_write
;
82 this->buf
= *this->blocks
.Append() = CallocT
<byte
>(CHUNK
);
83 this->bufe
= this->buf
+ CHUNK
;
85 memcpy(this->buf
, pbuf
, to_write
);
86 this->buf
+= to_write
;
89 /* virtual */ size_t Read(byte
*rbuf
, size_t size
)
91 /* Limit the amount to read to whatever we still have. */
92 size_t ret_size
= size
= min(this->written_bytes
- this->read_bytes
, size
);
93 this->read_bytes
+= ret_size
;
94 const byte
*rbufe
= rbuf
+ ret_size
;
96 while (rbuf
!= rbufe
) {
97 if (this->buf
== this->bufe
) {
98 this->buf
= *this->block
++;
99 this->bufe
= this->buf
+ CHUNK
;
102 size_t to_write
= min(this->bufe
- this->buf
, rbufe
- rbuf
);
103 memcpy(rbuf
, this->buf
, to_write
);
105 this->buf
+= to_write
;
111 /* virtual */ void Reset()
113 this->read_bytes
= 0;
115 this->block
= this->blocks
.Begin();
116 this->buf
= *this->block
++;
117 this->bufe
= this->buf
+ CHUNK
;
123 * Create a new socket for the client side of the game connection.
124 * @param s The socket to connect with.
126 ClientNetworkGameSocketHandler::ClientNetworkGameSocketHandler(SOCKET s
)
127 : NetworkGameSocketHandler(s
),
128 savegame(NULL
), token(0), status(STATUS_INACTIVE
)
130 assert(ClientNetworkGameSocketHandler::my_client
== NULL
);
131 ClientNetworkGameSocketHandler::my_client
= this;
134 /** Clear whatever we assigned. */
135 ClientNetworkGameSocketHandler::~ClientNetworkGameSocketHandler()
137 assert(ClientNetworkGameSocketHandler::my_client
== this);
138 ClientNetworkGameSocketHandler::my_client
= NULL
;
140 delete this->savegame
;
143 NetworkRecvStatus
ClientNetworkGameSocketHandler::CloseConnection(NetworkRecvStatus status
)
145 assert(status
!= NETWORK_RECV_STATUS_OKAY
);
147 * Sending a message just before leaving the game calls cs->SendPackets.
148 * This might invoke this function, which means that when we close the
149 * connection after cs->SendPackets we will close an already closed
150 * connection. This handles that case gracefully without having to make
151 * that code any more complex or more aware of the validity of the socket.
153 if (this->sock
== INVALID_SOCKET
) return status
;
155 DEBUG(net
, 1, "Closed client connection %d", this->client_id
);
157 this->SendPackets(true);
159 /* Wait a number of ticks so our leave message can reach the server.
160 * This is especially needed for Windows servers as they seem to get
161 * the "socket is closed" message before receiving our leave message,
162 * which would trigger the server to close the connection as well. */
163 CSleep(3 * MILLISECONDS_PER_TICK
);
165 delete this->GetInfo();
172 * Handle an error coming from the client side.
173 * @param res The "error" that happened.
175 void ClientNetworkGameSocketHandler::ClientError(NetworkRecvStatus res
)
177 /* First, send a CLIENT_ERROR to the server, so he knows we are
178 * disconnection (and why!) */
179 NetworkErrorCode errorno
;
181 /* We just want to close the connection.. */
182 if (res
== NETWORK_RECV_STATUS_CLOSE_QUERY
) {
183 this->NetworkSocketHandler::CloseConnection();
184 this->CloseConnection(res
);
187 DeleteWindowById(WC_NETWORK_STATUS_WINDOW
, WN_NETWORK_STATUS_WINDOW_JOIN
);
192 case NETWORK_RECV_STATUS_DESYNC
: errorno
= NETWORK_ERROR_DESYNC
; break;
193 case NETWORK_RECV_STATUS_SAVEGAME
: errorno
= NETWORK_ERROR_SAVEGAME_FAILED
; break;
194 case NETWORK_RECV_STATUS_NEWGRF_MISMATCH
: errorno
= NETWORK_ERROR_NEWGRF_MISMATCH
; break;
195 default: errorno
= NETWORK_ERROR_GENERAL
; break;
198 /* This means we fucked up and the server closed the connection */
199 if (res
!= NETWORK_RECV_STATUS_SERVER_ERROR
&& res
!= NETWORK_RECV_STATUS_SERVER_FULL
&&
200 res
!= NETWORK_RECV_STATUS_SERVER_BANNED
) {
204 _switch_mode
= SM_MENU
;
205 this->CloseConnection(res
);
211 * Check whether we received/can send some data from/to the server and
212 * when that's the case handle it appropriately.
213 * @return true when everything went okay.
215 /* static */ bool ClientNetworkGameSocketHandler::Receive()
217 if (my_client
->CanSendReceive()) {
218 NetworkRecvStatus res
= my_client
->ReceivePackets();
219 if (res
!= NETWORK_RECV_STATUS_OKAY
) {
220 /* The client made an error of which we can not recover.
221 * Close the connection and drop back to the main menu. */
222 my_client
->ClientError(res
);
229 /** Send the packets of this socket handler. */
230 /* static */ void ClientNetworkGameSocketHandler::Send()
232 my_client
->SendPackets();
233 my_client
->CheckConnection();
237 * Actual game loop for the client.
238 * @return Whether everything went okay, or not.
240 /* static */ bool ClientNetworkGameSocketHandler::GameLoop()
244 NetworkExecuteLocalCommandQueue();
246 extern void StateGameLoop();
249 /* Check if we are in sync! */
250 if (_sync_frame
!= 0) {
251 if (_sync_frame
== _frame_counter
) {
252 #ifdef NETWORK_SEND_DOUBLE_SEED
253 if (_sync_seed_1
!= _random
.state
[0] || _sync_seed_2
!= _random
.state
[1]) {
255 if (_sync_seed_1
!= _random
.state
[0]) {
257 NetworkError(STR_NETWORK_ERROR_DESYNC
);
258 DEBUG(desync
, 1, "sync_err: %08x; %02x", _date
, _date_fract
);
259 DEBUG(net
, 0, "Sync error detected!");
260 my_client
->ClientError(NETWORK_RECV_STATUS_DESYNC
);
262 extern void CheckCaches(bool force_check
);
267 /* If this is the first time we have a sync-frame, we
268 * need to let the server know that we are ready and at the same
269 * frame as he is.. so we can start playing! */
270 if (_network_first_time
) {
271 _network_first_time
= false;
276 } else if (_sync_frame
< _frame_counter
) {
277 DEBUG(net
, 1, "Missed frame for sync-test (%d / %d)", _sync_frame
, _frame_counter
);
286 /** Our client's connection. */
287 ClientNetworkGameSocketHandler
* ClientNetworkGameSocketHandler::my_client
= NULL
;
289 /** Last frame we performed an ack. */
290 static uint32 last_ack_frame
;
292 /** One bit of 'entropy' used to generate a salt for the company passwords. */
293 static uint32 _password_game_seed
;
294 /** The other bit of 'entropy' used to generate a salt for the company passwords. */
295 static char _password_server_id
[NETWORK_SERVER_ID_LENGTH
];
297 /** Maximum number of companies of the currently joined server. */
298 static uint8 _network_server_max_companies
;
299 /** Maximum number of spectators of the currently joined server. */
300 static uint8 _network_server_max_spectators
;
302 /** Who would we like to join as. */
303 CompanyID _network_join_as
;
305 /** Login password from -p argument */
306 const char *_network_join_server_password
= NULL
;
307 /** Company password from -P argument */
308 const char *_network_join_company_password
= NULL
;
310 /** Make sure the server ID length is the same as a md5 hash. */
311 assert_compile(NETWORK_SERVER_ID_LENGTH
== 16 * 2 + 1);
315 * DEF_CLIENT_SEND_COMMAND has no parameters
318 /** Query the server for company information. */
319 NetworkRecvStatus
ClientNetworkGameSocketHandler::SendCompanyInformationQuery()
321 my_client
->status
= STATUS_COMPANY_INFO
;
322 _network_join_status
= NETWORK_JOIN_STATUS_GETTING_COMPANY_INFO
;
323 SetWindowDirty(WC_NETWORK_STATUS_WINDOW
, WN_NETWORK_STATUS_WINDOW_JOIN
);
325 Packet
*p
= new Packet(PACKET_CLIENT_COMPANY_INFO
);
326 my_client
->SendPacket(p
);
327 return NETWORK_RECV_STATUS_OKAY
;
330 /** Tell the server we would like to join. */
331 NetworkRecvStatus
ClientNetworkGameSocketHandler::SendJoin()
333 my_client
->status
= STATUS_JOIN
;
334 _network_join_status
= NETWORK_JOIN_STATUS_AUTHORIZING
;
335 SetWindowDirty(WC_NETWORK_STATUS_WINDOW
, WN_NETWORK_STATUS_WINDOW_JOIN
);
337 Packet
*p
= new Packet(PACKET_CLIENT_JOIN
);
338 p
->Send_string(_openttd_revision
);
339 p
->Send_uint32(_openttd_newgrf_version
);
340 p
->Send_string(_settings_client
.network
.client_name
); // Client name
341 p
->Send_uint8 (_network_join_as
); // PlayAs
342 p
->Send_uint8 (NETLANG_ANY
); // Language
343 my_client
->SendPacket(p
);
344 return NETWORK_RECV_STATUS_OKAY
;
347 /** Tell the server we got all the NewGRFs. */
348 NetworkRecvStatus
ClientNetworkGameSocketHandler::SendNewGRFsOk()
350 Packet
*p
= new Packet(PACKET_CLIENT_NEWGRFS_CHECKED
);
351 my_client
->SendPacket(p
);
352 return NETWORK_RECV_STATUS_OKAY
;
356 * Set the game password as requested.
357 * @param password The game password.
359 NetworkRecvStatus
ClientNetworkGameSocketHandler::SendGamePassword(const char *password
)
361 Packet
*p
= new Packet(PACKET_CLIENT_GAME_PASSWORD
);
362 p
->Send_string(password
);
363 my_client
->SendPacket(p
);
364 return NETWORK_RECV_STATUS_OKAY
;
368 * Set the company password as requested.
369 * @param password The company password.
371 NetworkRecvStatus
ClientNetworkGameSocketHandler::SendCompanyPassword(const char *password
)
373 Packet
*p
= new Packet(PACKET_CLIENT_COMPANY_PASSWORD
);
374 p
->Send_string(GenerateCompanyPasswordHash(password
, _password_server_id
, _password_game_seed
));
375 my_client
->SendPacket(p
);
376 return NETWORK_RECV_STATUS_OKAY
;
379 /** Request the map from the server. */
380 NetworkRecvStatus
ClientNetworkGameSocketHandler::SendGetMap()
382 my_client
->status
= STATUS_MAP_WAIT
;
384 Packet
*p
= new Packet(PACKET_CLIENT_GETMAP
);
385 my_client
->SendPacket(p
);
386 return NETWORK_RECV_STATUS_OKAY
;
389 /** Tell the server we received the complete map. */
390 NetworkRecvStatus
ClientNetworkGameSocketHandler::SendMapOk()
392 my_client
->status
= STATUS_ACTIVE
;
394 Packet
*p
= new Packet(PACKET_CLIENT_MAP_OK
);
395 my_client
->SendPacket(p
);
396 return NETWORK_RECV_STATUS_OKAY
;
399 /** Send an acknowledgement from the server's ticks. */
400 NetworkRecvStatus
ClientNetworkGameSocketHandler::SendAck()
402 Packet
*p
= new Packet(PACKET_CLIENT_ACK
);
404 p
->Send_uint32(_frame_counter
);
405 p
->Send_uint8 (my_client
->token
);
406 my_client
->SendPacket(p
);
407 return NETWORK_RECV_STATUS_OKAY
;
411 * Send a command to the server.
412 * @param cp The command to send.
414 NetworkRecvStatus
ClientNetworkGameSocketHandler::SendCommand(const CommandPacket
*cp
)
416 Packet
*p
= new Packet(PACKET_CLIENT_COMMAND
);
417 my_client
->NetworkGameSocketHandler::SendCommand(p
, cp
);
419 my_client
->SendPacket(p
);
420 return NETWORK_RECV_STATUS_OKAY
;
423 /** Send a chat-packet over the network */
424 NetworkRecvStatus
ClientNetworkGameSocketHandler::SendChat(NetworkAction action
, DestType type
, int dest
, const char *msg
, NetworkTextMessageData data
)
426 Packet
*p
= new Packet(PACKET_CLIENT_CHAT
);
428 p
->Send_uint8 (action
);
429 p
->Send_uint8 (type
);
430 p
->Send_uint32(dest
);
434 my_client
->SendPacket(p
);
435 return NETWORK_RECV_STATUS_OKAY
;
438 /** Send an error-packet over the network */
439 NetworkRecvStatus
ClientNetworkGameSocketHandler::SendError(NetworkErrorCode errorno
)
441 Packet
*p
= new Packet(PACKET_CLIENT_ERROR
);
443 p
->Send_uint8(errorno
);
444 my_client
->SendPacket(p
);
445 return NETWORK_RECV_STATUS_OKAY
;
449 * Tell the server that we like to change the password of the company.
450 * @param password The new password.
452 NetworkRecvStatus
ClientNetworkGameSocketHandler::SendSetPassword(const char *password
)
454 Packet
*p
= new Packet(PACKET_CLIENT_SET_PASSWORD
);
456 p
->Send_string(GenerateCompanyPasswordHash(password
, _password_server_id
, _password_game_seed
));
457 my_client
->SendPacket(p
);
458 return NETWORK_RECV_STATUS_OKAY
;
462 * Tell the server that we like to change the name of the client.
463 * @param name The new name.
465 NetworkRecvStatus
ClientNetworkGameSocketHandler::SendSetName(const char *name
)
467 Packet
*p
= new Packet(PACKET_CLIENT_SET_NAME
);
469 p
->Send_string(name
);
470 my_client
->SendPacket(p
);
471 return NETWORK_RECV_STATUS_OKAY
;
475 * Tell the server we would like to quit.
477 NetworkRecvStatus
ClientNetworkGameSocketHandler::SendQuit()
479 Packet
*p
= new Packet(PACKET_CLIENT_QUIT
);
481 my_client
->SendPacket(p
);
482 return NETWORK_RECV_STATUS_OKAY
;
486 * Send a console command.
487 * @param pass The password for the remote command.
488 * @param command The actual command.
490 NetworkRecvStatus
ClientNetworkGameSocketHandler::SendRCon(const char *pass
, const char *command
)
492 Packet
*p
= new Packet(PACKET_CLIENT_RCON
);
493 p
->Send_string(pass
);
494 p
->Send_string(command
);
495 my_client
->SendPacket(p
);
496 return NETWORK_RECV_STATUS_OKAY
;
500 * Ask the server to move us.
501 * @param company The company to move to.
502 * @param password The password of the company to move to.
504 NetworkRecvStatus
ClientNetworkGameSocketHandler::SendMove(CompanyID company
, const char *password
)
506 Packet
*p
= new Packet(PACKET_CLIENT_MOVE
);
507 p
->Send_uint8(company
);
508 p
->Send_string(GenerateCompanyPasswordHash(password
, _password_server_id
, _password_game_seed
));
509 my_client
->SendPacket(p
);
510 return NETWORK_RECV_STATUS_OKAY
;
514 * Check whether the client is actually connected (and in the game).
515 * @return True when the client is connected.
517 bool ClientNetworkGameSocketHandler::IsConnected()
519 return my_client
!= NULL
&& my_client
->status
== STATUS_ACTIVE
;
524 * Receiving functions
525 * DEF_CLIENT_RECEIVE_COMMAND has parameter: Packet *p
528 extern bool SafeLoad(const char *filename
, SaveLoadOperation fop
, DetailedFileType dft
, GameMode newgm
, Subdirectory subdir
, struct LoadFilter
*lf
= NULL
);
530 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_FULL(Packet
*p
)
532 /* We try to join a server which is full */
533 ShowErrorMessage(STR_NETWORK_ERROR_SERVER_FULL
, INVALID_STRING_ID
, WL_CRITICAL
);
534 DeleteWindowById(WC_NETWORK_STATUS_WINDOW
, WN_NETWORK_STATUS_WINDOW_JOIN
);
536 return NETWORK_RECV_STATUS_SERVER_FULL
;
539 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_BANNED(Packet
*p
)
541 /* We try to join a server where we are banned */
542 ShowErrorMessage(STR_NETWORK_ERROR_SERVER_BANNED
, INVALID_STRING_ID
, WL_CRITICAL
);
543 DeleteWindowById(WC_NETWORK_STATUS_WINDOW
, WN_NETWORK_STATUS_WINDOW_JOIN
);
545 return NETWORK_RECV_STATUS_SERVER_BANNED
;
548 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_COMPANY_INFO(Packet
*p
)
550 if (this->status
!= STATUS_COMPANY_INFO
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
552 byte company_info_version
= p
->Recv_uint8();
554 if (!this->HasClientQuit() && company_info_version
== NETWORK_COMPANY_INFO_VERSION
) {
555 /* We have received all data... (there are no more packets coming) */
556 if (!p
->Recv_bool()) return NETWORK_RECV_STATUS_CLOSE_QUERY
;
558 CompanyID current
= (Owner
)p
->Recv_uint8();
559 if (current
>= MAX_COMPANIES
) return NETWORK_RECV_STATUS_CLOSE_QUERY
;
561 NetworkCompanyInfo
*company_info
= GetLobbyCompanyInfo(current
);
562 if (company_info
== NULL
) return NETWORK_RECV_STATUS_CLOSE_QUERY
;
564 p
->Recv_string(company_info
->company_name
, sizeof(company_info
->company_name
));
565 company_info
->inaugurated_year
= p
->Recv_uint32();
566 company_info
->company_value
= p
->Recv_uint64();
567 company_info
->money
= p
->Recv_uint64();
568 company_info
->income
= p
->Recv_uint64();
569 company_info
->performance
= p
->Recv_uint16();
570 company_info
->use_password
= p
->Recv_bool();
571 for (uint i
= 0; i
< NETWORK_VEH_END
; i
++) {
572 company_info
->num_vehicle
[i
] = p
->Recv_uint16();
574 for (uint i
= 0; i
< NETWORK_VEH_END
; i
++) {
575 company_info
->num_station
[i
] = p
->Recv_uint16();
577 company_info
->ai
= p
->Recv_bool();
579 p
->Recv_string(company_info
->clients
, sizeof(company_info
->clients
));
581 SetWindowDirty(WC_NETWORK_WINDOW
, WN_NETWORK_WINDOW_LOBBY
);
583 return NETWORK_RECV_STATUS_OKAY
;
586 return NETWORK_RECV_STATUS_CLOSE_QUERY
;
589 /* This packet contains info about the client (playas and name)
590 * as client we save this in NetworkClientInfo, linked via 'client_id'
591 * which is always an unique number on a server. */
592 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_CLIENT_INFO(Packet
*p
)
594 NetworkClientInfo
*ci
;
595 ClientID client_id
= (ClientID
)p
->Recv_uint32();
596 CompanyID playas
= (CompanyID
)p
->Recv_uint8();
597 char name
[NETWORK_NAME_LENGTH
];
599 p
->Recv_string(name
, sizeof(name
));
601 if (this->status
< STATUS_AUTHORIZED
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
602 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST
;
604 ci
= NetworkClientInfo::GetByClientID(client_id
);
606 if (playas
== ci
->client_playas
&& strcmp(name
, ci
->client_name
) != 0) {
607 /* Client name changed, display the change */
608 NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE
, CC_DEFAULT
, false, ci
->client_name
, name
);
609 } else if (playas
!= ci
->client_playas
) {
610 /* The client changed from client-player..
611 * Do not display that for now */
614 /* Make sure we're in the company the server tells us to be in,
615 * for the rare case that we get moved while joining. */
616 if (client_id
== _network_own_client_id
) SetLocalCompany(!Company::IsValidID(playas
) ? COMPANY_SPECTATOR
: playas
);
618 ci
->client_playas
= playas
;
619 strecpy(ci
->client_name
, name
, lastof(ci
->client_name
));
621 SetWindowDirty(WC_CLIENT_LIST
, 0);
623 return NETWORK_RECV_STATUS_OKAY
;
626 /* There are at most as many ClientInfo as ClientSocket objects in a
627 * server. Having more info than a server can have means something
628 * has gone wrong somewhere, i.e. the server has more info than it
629 * has actual clients. That means the server is feeding us an invalid
630 * state. So, bail out! This server is broken. */
631 if (!NetworkClientInfo::CanAllocateItem()) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
633 /* We don't have this client_id yet, find an empty client_id, and put the data there */
634 ci
= new NetworkClientInfo(client_id
);
635 ci
->client_playas
= playas
;
636 if (client_id
== _network_own_client_id
) this->SetInfo(ci
);
638 strecpy(ci
->client_name
, name
, lastof(ci
->client_name
));
640 SetWindowDirty(WC_CLIENT_LIST
, 0);
642 return NETWORK_RECV_STATUS_OKAY
;
645 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_ERROR(Packet
*p
)
647 static const StringID network_error_strings
[] = {
648 STR_NETWORK_ERROR_LOSTCONNECTION
, // NETWORK_ERROR_GENERAL
649 STR_NETWORK_ERROR_LOSTCONNECTION
, // NETWORK_ERROR_DESYNC
650 STR_NETWORK_ERROR_LOSTCONNECTION
, // NETWORK_ERROR_SAVEGAME_FAILED
651 STR_NETWORK_ERROR_LOSTCONNECTION
, // NETWORK_ERROR_CONNECTION_LOST
652 STR_NETWORK_ERROR_LOSTCONNECTION
, // NETWORK_ERROR_ILLEGAL_PACKET
653 STR_NETWORK_ERROR_LOSTCONNECTION
, // NETWORK_ERROR_NEWGRF_MISMATCH
654 STR_NETWORK_ERROR_SERVER_ERROR
, // NETWORK_ERROR_NOT_AUTHORIZED
655 STR_NETWORK_ERROR_SERVER_ERROR
, // NETWORK_ERROR_NOT_EXPECTED
656 STR_NETWORK_ERROR_WRONG_REVISION
, // NETWORK_ERROR_WRONG_REVISION
657 STR_NETWORK_ERROR_LOSTCONNECTION
, // NETWORK_ERROR_NAME_IN_USE
658 STR_NETWORK_ERROR_WRONG_PASSWORD
, // NETWORK_ERROR_WRONG_PASSWORD
659 STR_NETWORK_ERROR_SERVER_ERROR
, // NETWORK_ERROR_COMPANY_MISMATCH
660 STR_NETWORK_ERROR_KICKED
, // NETWORK_ERROR_KICKED
661 STR_NETWORK_ERROR_CHEATER
, // NETWORK_ERROR_CHEATER
662 STR_NETWORK_ERROR_SERVER_FULL
, // NETWORK_ERROR_FULL
663 STR_NETWORK_ERROR_TOO_MANY_COMMANDS
, // NETWORK_ERROR_TOO_MANY_COMMANDS
664 STR_NETWORK_ERROR_TIMEOUT_PASSWORD
, // NETWORK_ERROR_TIMEOUT_PASSWORD
665 STR_NETWORK_ERROR_TIMEOUT_COMPUTER
, // NETWORK_ERROR_TIMEOUT_COMPUTER
666 STR_NETWORK_ERROR_TIMEOUT_MAP
, // NETWORK_ERROR_TIMEOUT_MAP
667 STR_NETWORK_ERROR_TIMEOUT_JOIN
, // NETWORK_ERROR_TIMEOUT_JOIN
669 assert_compile(lengthof(network_error_strings
) == NETWORK_ERROR_END
);
671 NetworkErrorCode error
= (NetworkErrorCode
)p
->Recv_uint8();
673 StringID err
= STR_NETWORK_ERROR_LOSTCONNECTION
;
674 if (error
< (ptrdiff_t)lengthof(network_error_strings
)) err
= network_error_strings
[error
];
676 ShowErrorMessage(err
, INVALID_STRING_ID
, WL_CRITICAL
);
678 DeleteWindowById(WC_NETWORK_STATUS_WINDOW
, WN_NETWORK_STATUS_WINDOW_JOIN
);
680 return NETWORK_RECV_STATUS_SERVER_ERROR
;
683 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_CHECK_NEWGRFS(Packet
*p
)
685 if (this->status
!= STATUS_JOIN
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
687 uint grf_count
= p
->Recv_uint8();
688 bool is_last_packet
= p
->Recv_bool();
690 NetworkRecvStatus ret
= NETWORK_RECV_STATUS_OKAY
;
693 for (; grf_count
> 0; grf_count
--) {
695 this->ReceiveGRFIdentifier(p
, &c
);
697 /* Check whether we know this GRF */
698 const GRFConfig
*f
= FindGRFConfig(c
.grfid
, FGCM_EXACT
, c
.md5sum
);
700 /* We do not know this GRF, bail out of initialization */
701 char buf
[sizeof(c
.md5sum
) * 2 + 1];
702 md5sumToString(buf
, lastof(buf
), c
.md5sum
);
703 DEBUG(grf
, 0, "NewGRF %08X not found; checksum %s", BSWAP32(c
.grfid
), buf
);
704 ret
= NETWORK_RECV_STATUS_NEWGRF_MISMATCH
;
708 if (ret
== NETWORK_RECV_STATUS_OKAY
&& is_last_packet
) {
709 /* Start receiving the map */
710 return SendNewGRFsOk();
713 if (ret
!= NETWORK_RECV_STATUS_OKAY
) {
714 /* NewGRF mismatch, bail out */
715 ShowErrorMessage(STR_NETWORK_ERROR_NEWGRF_MISMATCH
, INVALID_STRING_ID
, WL_CRITICAL
);
721 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_NEED_GAME_PASSWORD(Packet
*p
)
723 if (this->status
< STATUS_JOIN
|| this->status
>= STATUS_AUTH_GAME
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
724 this->status
= STATUS_AUTH_GAME
;
726 const char *password
= _network_join_server_password
;
727 if (!StrEmpty(password
)) {
728 return SendGamePassword(password
);
731 ShowNetworkNeedPassword(NETWORK_GAME_PASSWORD
);
733 return NETWORK_RECV_STATUS_OKAY
;
736 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_NEED_COMPANY_PASSWORD(Packet
*p
)
738 if (this->status
< STATUS_JOIN
|| this->status
>= STATUS_AUTH_COMPANY
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
739 this->status
= STATUS_AUTH_COMPANY
;
741 _password_game_seed
= p
->Recv_uint32();
742 p
->Recv_string(_password_server_id
, sizeof(_password_server_id
));
743 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
745 const char *password
= _network_join_company_password
;
746 if (!StrEmpty(password
)) {
747 return SendCompanyPassword(password
);
750 ShowNetworkNeedPassword(NETWORK_COMPANY_PASSWORD
);
752 return NETWORK_RECV_STATUS_OKAY
;
755 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_WELCOME(Packet
*p
)
757 if (this->status
< STATUS_JOIN
|| this->status
>= STATUS_AUTHORIZED
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
758 this->status
= STATUS_AUTHORIZED
;
760 _network_own_client_id
= (ClientID
)p
->Recv_uint32();
762 /* Initialize the password hash salting variables, even if they were previously. */
763 _password_game_seed
= p
->Recv_uint32();
764 p
->Recv_string(_password_server_id
, sizeof(_password_server_id
));
766 /* Start receiving the map */
770 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_WAIT(Packet
*p
)
772 /* We set the internal wait state when requesting the map. */
773 if (this->status
!= STATUS_MAP_WAIT
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
775 /* But... only now we set the join status to waiting, instead of requesting. */
776 _network_join_status
= NETWORK_JOIN_STATUS_WAITING
;
777 _network_join_waiting
= p
->Recv_uint8();
778 SetWindowDirty(WC_NETWORK_STATUS_WINDOW
, WN_NETWORK_STATUS_WINDOW_JOIN
);
780 return NETWORK_RECV_STATUS_OKAY
;
783 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_MAP_BEGIN(Packet
*p
)
785 if (this->status
< STATUS_AUTHORIZED
|| this->status
>= STATUS_MAP
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
786 this->status
= STATUS_MAP
;
788 if (this->savegame
!= NULL
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
790 this->savegame
= new PacketReader();
792 _frame_counter
= _frame_counter_server
= _frame_counter_max
= p
->Recv_uint32();
794 _network_join_bytes
= 0;
795 _network_join_bytes_total
= 0;
797 _network_join_status
= NETWORK_JOIN_STATUS_DOWNLOADING
;
798 SetWindowDirty(WC_NETWORK_STATUS_WINDOW
, WN_NETWORK_STATUS_WINDOW_JOIN
);
800 return NETWORK_RECV_STATUS_OKAY
;
803 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_MAP_SIZE(Packet
*p
)
805 if (this->status
!= STATUS_MAP
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
806 if (this->savegame
== NULL
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
808 _network_join_bytes_total
= p
->Recv_uint32();
809 SetWindowDirty(WC_NETWORK_STATUS_WINDOW
, WN_NETWORK_STATUS_WINDOW_JOIN
);
811 return NETWORK_RECV_STATUS_OKAY
;
814 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DATA(Packet
*p
)
816 if (this->status
!= STATUS_MAP
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
817 if (this->savegame
== NULL
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
819 /* We are still receiving data, put it to the file */
820 this->savegame
->AddPacket(p
);
822 _network_join_bytes
= (uint32
)this->savegame
->written_bytes
;
823 SetWindowDirty(WC_NETWORK_STATUS_WINDOW
, WN_NETWORK_STATUS_WINDOW_JOIN
);
825 return NETWORK_RECV_STATUS_OKAY
;
828 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DONE(Packet
*p
)
830 if (this->status
!= STATUS_MAP
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
831 if (this->savegame
== NULL
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
833 _network_join_status
= NETWORK_JOIN_STATUS_PROCESSING
;
834 SetWindowDirty(WC_NETWORK_STATUS_WINDOW
, WN_NETWORK_STATUS_WINDOW_JOIN
);
837 * Make sure everything is set for reading.
839 * We need the local copy and reset this->savegame because when
840 * loading fails the network gets reset upon loading the intro
841 * game, which would cause us to free this->savegame twice.
843 LoadFilter
*lf
= this->savegame
;
844 this->savegame
= NULL
;
847 /* The map is done downloading, load it */
848 ClearErrorMessages();
849 bool load_success
= SafeLoad(NULL
, SLO_LOAD
, DFT_GAME_FILE
, GM_NORMAL
, NO_DIRECTORY
, lf
);
851 /* Long savegame loads shouldn't affect the lag calculation! */
852 this->last_packet
= _realtime_tick
;
855 DeleteWindowById(WC_NETWORK_STATUS_WINDOW
, WN_NETWORK_STATUS_WINDOW_JOIN
);
856 ShowErrorMessage(STR_NETWORK_ERROR_SAVEGAMEERROR
, INVALID_STRING_ID
, WL_CRITICAL
);
857 return NETWORK_RECV_STATUS_SAVEGAME
;
859 /* If the savegame has successfully loaded, ALL windows have been removed,
860 * only toolbar/statusbar and gamefield are visible */
862 /* Say we received the map and loaded it correctly! */
865 /* New company/spectator (invalid company) or company we want to join is not active
866 * Switch local company to spectator and await the server's judgement */
867 if (_network_join_as
== COMPANY_NEW_COMPANY
|| !Company::IsValidID(_network_join_as
)) {
868 SetLocalCompany(COMPANY_SPECTATOR
);
870 if (_network_join_as
!= COMPANY_SPECTATOR
) {
871 /* We have arrived and ready to start playing; send a command to make a new company;
872 * the server will give us a client-id and let us in */
873 _network_join_status
= NETWORK_JOIN_STATUS_REGISTERING
;
874 ShowJoinStatusWindow();
875 NetworkSendCommand(0, 0, 0, CMD_COMPANY_CTRL
, NULL
, NULL
, _local_company
, 0);
878 /* take control over an existing company */
879 SetLocalCompany(_network_join_as
);
882 return NETWORK_RECV_STATUS_OKAY
;
885 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_FRAME(Packet
*p
)
887 if (this->status
!= STATUS_ACTIVE
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
889 _frame_counter_server
= p
->Recv_uint32();
890 _frame_counter_max
= p
->Recv_uint32();
891 #ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
892 /* Test if the server supports this option
893 * and if we are at the frame the server is */
894 if (p
->pos
+ 1 < p
->size
) {
895 _sync_frame
= _frame_counter_server
;
896 _sync_seed_1
= p
->Recv_uint32();
897 #ifdef NETWORK_SEND_DOUBLE_SEED
898 _sync_seed_2
= p
->Recv_uint32();
902 /* Receive the token. */
903 if (p
->pos
!= p
->size
) this->token
= p
->Recv_uint8();
905 DEBUG(net
, 5, "Received FRAME %d", _frame_counter_server
);
907 /* Let the server know that we received this frame correctly
908 * We do this only once per day, to save some bandwidth ;) */
909 if (!_network_first_time
&& last_ack_frame
< _frame_counter
) {
910 last_ack_frame
= _frame_counter
+ DAY_TICKS
;
911 DEBUG(net
, 4, "Sent ACK at %d", _frame_counter
);
915 return NETWORK_RECV_STATUS_OKAY
;
918 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_SYNC(Packet
*p
)
920 if (this->status
!= STATUS_ACTIVE
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
922 _sync_frame
= p
->Recv_uint32();
923 _sync_seed_1
= p
->Recv_uint32();
924 #ifdef NETWORK_SEND_DOUBLE_SEED
925 _sync_seed_2
= p
->Recv_uint32();
928 return NETWORK_RECV_STATUS_OKAY
;
931 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_COMMAND(Packet
*p
)
933 if (this->status
!= STATUS_ACTIVE
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
936 const char *err
= this->ReceiveCommand(p
, &cp
);
937 cp
.frame
= p
->Recv_uint32();
938 cp
.my_cmd
= p
->Recv_bool();
941 IConsolePrintF(CC_ERROR
, "WARNING: %s from server, dropping...", err
);
942 return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
945 this->incoming_queue
.Append(&cp
);
947 return NETWORK_RECV_STATUS_OKAY
;
950 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_CHAT(Packet
*p
)
952 if (this->status
!= STATUS_ACTIVE
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
954 char name
[NETWORK_NAME_LENGTH
], msg
[NETWORK_CHAT_LENGTH
];
955 const NetworkClientInfo
*ci
= NULL
, *ci_to
;
957 NetworkAction action
= (NetworkAction
)p
->Recv_uint8();
958 ClientID client_id
= (ClientID
)p
->Recv_uint32();
959 bool self_send
= p
->Recv_bool();
960 p
->Recv_string(msg
, NETWORK_CHAT_LENGTH
);
961 NetworkTextMessageData data
;
964 ci_to
= NetworkClientInfo::GetByClientID(client_id
);
965 if (ci_to
== NULL
) return NETWORK_RECV_STATUS_OKAY
;
967 /* Did we initiate the action locally? */
970 case NETWORK_ACTION_CHAT_CLIENT
:
971 /* For speaking to client we need the client-name */
972 seprintf(name
, lastof(name
), "%s", ci_to
->client_name
);
973 ci
= NetworkClientInfo::GetByClientID(_network_own_client_id
);
976 /* For speaking to company or giving money, we need the company-name */
977 case NETWORK_ACTION_GIVE_MONEY
:
978 if (!Company::IsValidID(ci_to
->client_playas
)) return NETWORK_RECV_STATUS_OKAY
;
981 case NETWORK_ACTION_CHAT_COMPANY
: {
982 StringID str
= Company::IsValidID(ci_to
->client_playas
) ? STR_COMPANY_NAME
: STR_NETWORK_SPECTATORS
;
983 SetDParam(0, ci_to
->client_playas
);
985 GetString(name
, str
, lastof(name
));
986 ci
= NetworkClientInfo::GetByClientID(_network_own_client_id
);
990 default: return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
993 /* Display message from somebody else */
994 seprintf(name
, lastof(name
), "%s", ci_to
->client_name
);
999 NetworkTextMessage(action
, GetDrawStringCompanyColour(ci
->client_playas
), self_send
, name
, msg
, data
);
1001 return NETWORK_RECV_STATUS_OKAY
;
1004 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_ERROR_QUIT(Packet
*p
)
1006 if (this->status
< STATUS_AUTHORIZED
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
1008 ClientID client_id
= (ClientID
)p
->Recv_uint32();
1010 NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID(client_id
);
1012 NetworkTextMessage(NETWORK_ACTION_LEAVE
, CC_DEFAULT
, false, ci
->client_name
, NULL
, GetNetworkErrorMsg((NetworkErrorCode
)p
->Recv_uint8()));
1016 SetWindowDirty(WC_CLIENT_LIST
, 0);
1018 return NETWORK_RECV_STATUS_OKAY
;
1021 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_QUIT(Packet
*p
)
1023 if (this->status
< STATUS_AUTHORIZED
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
1025 ClientID client_id
= (ClientID
)p
->Recv_uint32();
1027 NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID(client_id
);
1029 NetworkTextMessage(NETWORK_ACTION_LEAVE
, CC_DEFAULT
, false, ci
->client_name
, NULL
, STR_NETWORK_MESSAGE_CLIENT_LEAVING
);
1032 DEBUG(net
, 0, "Unknown client (%d) is leaving the game", client_id
);
1035 SetWindowDirty(WC_CLIENT_LIST
, 0);
1037 /* If we come here it means we could not locate the client.. strange :s */
1038 return NETWORK_RECV_STATUS_OKAY
;
1041 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_JOIN(Packet
*p
)
1043 if (this->status
< STATUS_AUTHORIZED
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
1045 ClientID client_id
= (ClientID
)p
->Recv_uint32();
1047 NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID(client_id
);
1049 NetworkTextMessage(NETWORK_ACTION_JOIN
, CC_DEFAULT
, false, ci
->client_name
);
1052 SetWindowDirty(WC_CLIENT_LIST
, 0);
1054 return NETWORK_RECV_STATUS_OKAY
;
1057 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_SHUTDOWN(Packet
*p
)
1059 /* Only when we're trying to join we really
1060 * care about the server shutting down. */
1061 if (this->status
>= STATUS_JOIN
) {
1062 ShowErrorMessage(STR_NETWORK_MESSAGE_SERVER_SHUTDOWN
, INVALID_STRING_ID
, WL_CRITICAL
);
1065 return NETWORK_RECV_STATUS_SERVER_ERROR
;
1068 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_NEWGAME(Packet
*p
)
1070 /* Only when we're trying to join we really
1071 * care about the server shutting down. */
1072 if (this->status
>= STATUS_JOIN
) {
1073 /* To throttle the reconnects a bit, every clients waits its
1074 * Client ID modulo 16. This way reconnects should be spread
1076 _network_reconnect
= _network_own_client_id
% 16;
1077 ShowErrorMessage(STR_NETWORK_MESSAGE_SERVER_REBOOT
, INVALID_STRING_ID
, WL_CRITICAL
);
1080 return NETWORK_RECV_STATUS_SERVER_ERROR
;
1083 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_RCON(Packet
*p
)
1085 if (this->status
< STATUS_AUTHORIZED
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
1087 TextColour colour_code
= (TextColour
)p
->Recv_uint16();
1088 if (!IsValidConsoleColour(colour_code
)) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
1090 char rcon_out
[NETWORK_RCONCOMMAND_LENGTH
];
1091 p
->Recv_string(rcon_out
, sizeof(rcon_out
));
1093 IConsolePrint(colour_code
, rcon_out
);
1095 return NETWORK_RECV_STATUS_OKAY
;
1098 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_MOVE(Packet
*p
)
1100 if (this->status
< STATUS_AUTHORIZED
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
1102 /* Nothing more in this packet... */
1103 ClientID client_id
= (ClientID
)p
->Recv_uint32();
1104 CompanyID company_id
= (CompanyID
)p
->Recv_uint8();
1106 if (client_id
== 0) {
1107 /* definitely an invalid client id, debug message and do nothing. */
1108 DEBUG(net
, 0, "[move] received invalid client index = 0");
1109 return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
1112 const NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID(client_id
);
1113 /* Just make sure we do not try to use a client_index that does not exist */
1114 if (ci
== NULL
) return NETWORK_RECV_STATUS_OKAY
;
1116 /* if not valid player, force spectator, else check player exists */
1117 if (!Company::IsValidID(company_id
)) company_id
= COMPANY_SPECTATOR
;
1119 if (client_id
== _network_own_client_id
) {
1120 SetLocalCompany(company_id
);
1123 return NETWORK_RECV_STATUS_OKAY
;
1126 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_CONFIG_UPDATE(Packet
*p
)
1128 if (this->status
< STATUS_ACTIVE
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
1130 _network_server_max_companies
= p
->Recv_uint8();
1131 _network_server_max_spectators
= p
->Recv_uint8();
1133 return NETWORK_RECV_STATUS_OKAY
;
1136 NetworkRecvStatus
ClientNetworkGameSocketHandler::Receive_SERVER_COMPANY_UPDATE(Packet
*p
)
1138 if (this->status
< STATUS_ACTIVE
) return NETWORK_RECV_STATUS_MALFORMED_PACKET
;
1140 _network_company_passworded
= p
->Recv_uint16();
1141 SetWindowClassesDirty(WC_COMPANY
);
1143 return NETWORK_RECV_STATUS_OKAY
;
1147 * Check the connection's state, i.e. is the connection still up?
1149 void ClientNetworkGameSocketHandler::CheckConnection()
1151 /* Only once we're authorized we can expect a steady stream of packets. */
1152 if (this->status
< STATUS_AUTHORIZED
) return;
1154 /* It might... sometimes occur that the realtime ticker overflows. */
1155 if (_realtime_tick
< this->last_packet
) this->last_packet
= _realtime_tick
;
1157 /* Lag is in milliseconds; 5 seconds are roughly twice the
1158 * server's "you're slow" threshold (1 game day). */
1159 uint lag
= (_realtime_tick
- this->last_packet
) / 1000;
1160 if (lag
< 5) return;
1162 /* 20 seconds are (way) more than 4 game days after which
1163 * the server will forcefully disconnect you. */
1165 this->NetworkGameSocketHandler::CloseConnection();
1166 ShowErrorMessage(STR_NETWORK_ERROR_LOSTCONNECTION
, INVALID_STRING_ID
, WL_CRITICAL
);
1170 /* Prevent showing the lag message every tick; just update it when needed. */
1171 static uint last_lag
= 0;
1172 if (last_lag
== lag
) return;
1176 ShowErrorMessage(STR_NETWORK_ERROR_CLIENT_GUI_LOST_CONNECTION_CAPTION
, STR_NETWORK_ERROR_CLIENT_GUI_LOST_CONNECTION
, WL_INFO
);
1180 /** Is called after a client is connected to the server */
1181 void NetworkClient_Connected()
1183 /* Set the frame-counter to 0 so nothing happens till we are ready */
1185 _frame_counter_server
= 0;
1187 /* Request the game-info */
1188 MyClient::SendJoin();
1192 * Send a remote console command.
1193 * @param password The password.
1194 * @param command The command to execute.
1196 void NetworkClientSendRcon(const char *password
, const char *command
)
1198 MyClient::SendRCon(password
, command
);
1202 * Notify the server of this client wanting to be moved to another company.
1203 * @param company_id id of the company the client wishes to be moved to.
1204 * @param pass the password, is only checked on the server end if a password is needed.
1207 void NetworkClientRequestMove(CompanyID company_id
, const char *pass
)
1209 MyClient::SendMove(company_id
, pass
);
1213 * Move the clients of a company to the spectators.
1214 * @param cid The company to move the clients of.
1216 void NetworkClientsToSpectators(CompanyID cid
)
1218 Backup
<CompanyByte
> cur_company(_current_company
, FILE_LINE
);
1219 /* If our company is changing owner, go to spectators */
1220 if (cid
== _local_company
) SetLocalCompany(COMPANY_SPECTATOR
);
1222 NetworkClientInfo
*ci
;
1223 FOR_ALL_CLIENT_INFOS(ci
) {
1224 if (ci
->client_playas
!= cid
) continue;
1225 NetworkTextMessage(NETWORK_ACTION_COMPANY_SPECTATOR
, CC_DEFAULT
, false, ci
->client_name
);
1226 ci
->client_playas
= COMPANY_SPECTATOR
;
1229 cur_company
.Restore();
1233 * Send the server our name.
1235 void NetworkUpdateClientName()
1237 NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID(_network_own_client_id
);
1239 if (ci
== NULL
) return;
1241 /* Don't change the name if it is the same as the old name */
1242 if (strcmp(ci
->client_name
, _settings_client
.network
.client_name
) != 0) {
1243 if (!_network_server
) {
1244 MyClient::SendSetName(_settings_client
.network
.client_name
);
1246 if (NetworkFindName(_settings_client
.network
.client_name
, lastof(_settings_client
.network
.client_name
))) {
1247 NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE
, CC_DEFAULT
, false, ci
->client_name
, _settings_client
.network
.client_name
);
1248 strecpy(ci
->client_name
, _settings_client
.network
.client_name
, lastof(ci
->client_name
));
1249 NetworkUpdateClientInfo(CLIENT_ID_SERVER
);
1256 * Send a chat message.
1257 * @param action The action associated with the message.
1258 * @param type The destination type.
1259 * @param dest The destination index, be it a company index or client id.
1260 * @param msg The actual message.
1261 * @param data Arbitrary extra data.
1263 void NetworkClientSendChat(NetworkAction action
, DestType type
, int dest
, const char *msg
, NetworkTextMessageData data
)
1265 MyClient::SendChat(action
, type
, dest
, msg
, data
);
1269 * Set/Reset company password on the client side.
1270 * @param password Password to be set.
1272 void NetworkClientSetCompanyPassword(const char *password
)
1274 MyClient::SendSetPassword(password
);
1278 * Tell whether the client has team members where he/she can chat to.
1279 * @param cio client to check members of.
1280 * @return true if there is at least one team member.
1282 bool NetworkClientPreferTeamChat(const NetworkClientInfo
*cio
)
1284 /* Only companies actually playing can speak to team. Eg spectators cannot */
1285 if (!_settings_client
.gui
.prefer_teamchat
|| !Company::IsValidID(cio
->client_playas
)) return false;
1287 const NetworkClientInfo
*ci
;
1288 FOR_ALL_CLIENT_INFOS(ci
) {
1289 if (ci
->client_playas
== cio
->client_playas
&& ci
!= cio
) return true;
1296 * Check if max_companies has been reached on the server (local check only).
1297 * @return true if the max value has been reached or exceeded, false otherwise.
1299 bool NetworkMaxCompaniesReached()
1301 return Company::GetNumItems() >= (_network_server
? _settings_client
.network
.max_companies
: _network_server_max_companies
);
1305 * Check if max_spectatos has been reached on the server (local check only).
1306 * @return true if the max value has been reached or exceeded, false otherwise.
1308 bool NetworkMaxSpectatorsReached()
1310 return NetworkSpectatorCount() >= (_network_server
? _settings_client
.network
.max_spectators
: _network_server_max_spectators
);
1313 #endif /* ENABLE_NETWORK */