Maintain a circular buffer of recent commands, add to crashlog.
[openttd-joker.git] / src / network / network_client.cpp
blob3599ae214a9d69db8ca3210b7e64c1b6276496fc
1 /* $Id$ */
3 /*
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/>.
8 */
10 /** @file network_client.cpp Client part of the network protocol. */
12 #ifdef ENABLE_NETWORK
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"
28 #include "../error.h"
29 #include "../rev.h"
30 #include "network.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)
58 /**
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;
71 if (to_write != 0) {
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. */
80 pbuf += to_write;
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);
104 rbuf += to_write;
105 this->buf += to_write;
108 return ret_size;
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();
166 delete this;
168 return status;
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);
185 _networking = false;
187 DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
188 return;
191 switch (res) {
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) {
201 SendError(errorno);
204 _switch_mode = SM_MENU;
205 this->CloseConnection(res);
206 _networking = false;
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);
223 return false;
226 return _networking;
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()
242 _frame_counter++;
244 NetworkExecuteLocalCommandQueue();
246 extern void StateGameLoop();
247 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]) {
254 #else
255 if (_sync_seed_1 != _random.state[0]) {
256 #endif
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);
261 return false;
264 /* If this is the first time we have a sync-frame, we
265 * need to let the server know that we are ready and at the same
266 * frame as he is.. so we can start playing! */
267 if (_network_first_time) {
268 _network_first_time = false;
269 SendAck();
272 _sync_frame = 0;
273 } else if (_sync_frame < _frame_counter) {
274 DEBUG(net, 1, "Missed frame for sync-test (%d / %d)", _sync_frame, _frame_counter);
275 _sync_frame = 0;
279 return true;
283 /** Our client's connection. */
284 ClientNetworkGameSocketHandler * ClientNetworkGameSocketHandler::my_client = NULL;
286 /** Last frame we performed an ack. */
287 static uint32 last_ack_frame;
289 /** One bit of 'entropy' used to generate a salt for the company passwords. */
290 static uint32 _password_game_seed;
291 /** The other bit of 'entropy' used to generate a salt for the company passwords. */
292 static char _password_server_id[NETWORK_SERVER_ID_LENGTH];
294 /** Maximum number of companies of the currently joined server. */
295 static uint8 _network_server_max_companies;
296 /** Maximum number of spectators of the currently joined server. */
297 static uint8 _network_server_max_spectators;
299 /** Who would we like to join as. */
300 CompanyID _network_join_as;
302 /** Login password from -p argument */
303 const char *_network_join_server_password = NULL;
304 /** Company password from -P argument */
305 const char *_network_join_company_password = NULL;
307 /** Make sure the server ID length is the same as a md5 hash. */
308 assert_compile(NETWORK_SERVER_ID_LENGTH == 16 * 2 + 1);
310 /***********
311 * Sending functions
312 * DEF_CLIENT_SEND_COMMAND has no parameters
313 ************/
315 /** Query the server for company information. */
316 NetworkRecvStatus ClientNetworkGameSocketHandler::SendCompanyInformationQuery()
318 my_client->status = STATUS_COMPANY_INFO;
319 _network_join_status = NETWORK_JOIN_STATUS_GETTING_COMPANY_INFO;
320 SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
322 Packet *p = new Packet(PACKET_CLIENT_COMPANY_INFO);
323 my_client->SendPacket(p);
324 return NETWORK_RECV_STATUS_OKAY;
327 /** Tell the server we would like to join. */
328 NetworkRecvStatus ClientNetworkGameSocketHandler::SendJoin()
330 my_client->status = STATUS_JOIN;
331 _network_join_status = NETWORK_JOIN_STATUS_AUTHORIZING;
332 SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
334 Packet *p = new Packet(PACKET_CLIENT_JOIN);
335 p->Send_string(_openttd_revision);
336 p->Send_uint32(_openttd_newgrf_version);
337 p->Send_string(_settings_client.network.client_name); // Client name
338 p->Send_uint8 (_network_join_as); // PlayAs
339 p->Send_uint8 (NETLANG_ANY); // Language
340 my_client->SendPacket(p);
341 return NETWORK_RECV_STATUS_OKAY;
344 /** Tell the server we got all the NewGRFs. */
345 NetworkRecvStatus ClientNetworkGameSocketHandler::SendNewGRFsOk()
347 Packet *p = new Packet(PACKET_CLIENT_NEWGRFS_CHECKED);
348 my_client->SendPacket(p);
349 return NETWORK_RECV_STATUS_OKAY;
353 * Set the game password as requested.
354 * @param password The game password.
356 NetworkRecvStatus ClientNetworkGameSocketHandler::SendGamePassword(const char *password)
358 Packet *p = new Packet(PACKET_CLIENT_GAME_PASSWORD);
359 p->Send_string(password);
360 my_client->SendPacket(p);
361 return NETWORK_RECV_STATUS_OKAY;
365 * Set the company password as requested.
366 * @param password The company password.
368 NetworkRecvStatus ClientNetworkGameSocketHandler::SendCompanyPassword(const char *password)
370 Packet *p = new Packet(PACKET_CLIENT_COMPANY_PASSWORD);
371 p->Send_string(GenerateCompanyPasswordHash(password, _password_server_id, _password_game_seed));
372 my_client->SendPacket(p);
373 return NETWORK_RECV_STATUS_OKAY;
376 /** Request the map from the server. */
377 NetworkRecvStatus ClientNetworkGameSocketHandler::SendGetMap()
379 my_client->status = STATUS_MAP_WAIT;
381 Packet *p = new Packet(PACKET_CLIENT_GETMAP);
382 my_client->SendPacket(p);
383 return NETWORK_RECV_STATUS_OKAY;
386 /** Tell the server we received the complete map. */
387 NetworkRecvStatus ClientNetworkGameSocketHandler::SendMapOk()
389 my_client->status = STATUS_ACTIVE;
391 Packet *p = new Packet(PACKET_CLIENT_MAP_OK);
392 my_client->SendPacket(p);
393 return NETWORK_RECV_STATUS_OKAY;
396 /** Send an acknowledgement from the server's ticks. */
397 NetworkRecvStatus ClientNetworkGameSocketHandler::SendAck()
399 Packet *p = new Packet(PACKET_CLIENT_ACK);
401 p->Send_uint32(_frame_counter);
402 p->Send_uint8 (my_client->token);
403 my_client->SendPacket(p);
404 return NETWORK_RECV_STATUS_OKAY;
408 * Send a command to the server.
409 * @param cp The command to send.
411 NetworkRecvStatus ClientNetworkGameSocketHandler::SendCommand(const CommandPacket *cp)
413 Packet *p = new Packet(PACKET_CLIENT_COMMAND);
414 my_client->NetworkGameSocketHandler::SendCommand(p, cp);
416 my_client->SendPacket(p);
417 return NETWORK_RECV_STATUS_OKAY;
420 /** Send a chat-packet over the network */
421 NetworkRecvStatus ClientNetworkGameSocketHandler::SendChat(NetworkAction action, DestType type, int dest, const char *msg, int64 data)
423 Packet *p = new Packet(PACKET_CLIENT_CHAT);
425 p->Send_uint8 (action);
426 p->Send_uint8 (type);
427 p->Send_uint32(dest);
428 p->Send_string(msg);
429 p->Send_uint64(data);
431 my_client->SendPacket(p);
432 return NETWORK_RECV_STATUS_OKAY;
435 /** Send an error-packet over the network */
436 NetworkRecvStatus ClientNetworkGameSocketHandler::SendError(NetworkErrorCode errorno)
438 Packet *p = new Packet(PACKET_CLIENT_ERROR);
440 p->Send_uint8(errorno);
441 my_client->SendPacket(p);
442 return NETWORK_RECV_STATUS_OKAY;
446 * Tell the server that we like to change the password of the company.
447 * @param password The new password.
449 NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetPassword(const char *password)
451 Packet *p = new Packet(PACKET_CLIENT_SET_PASSWORD);
453 p->Send_string(GenerateCompanyPasswordHash(password, _password_server_id, _password_game_seed));
454 my_client->SendPacket(p);
455 return NETWORK_RECV_STATUS_OKAY;
459 * Tell the server that we like to change the name of the client.
460 * @param name The new name.
462 NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetName(const char *name)
464 Packet *p = new Packet(PACKET_CLIENT_SET_NAME);
466 p->Send_string(name);
467 my_client->SendPacket(p);
468 return NETWORK_RECV_STATUS_OKAY;
472 * Tell the server we would like to quit.
474 NetworkRecvStatus ClientNetworkGameSocketHandler::SendQuit()
476 Packet *p = new Packet(PACKET_CLIENT_QUIT);
478 my_client->SendPacket(p);
479 return NETWORK_RECV_STATUS_OKAY;
483 * Send a console command.
484 * @param pass The password for the remote command.
485 * @param command The actual command.
487 NetworkRecvStatus ClientNetworkGameSocketHandler::SendRCon(const char *pass, const char *command)
489 Packet *p = new Packet(PACKET_CLIENT_RCON);
490 p->Send_string(pass);
491 p->Send_string(command);
492 my_client->SendPacket(p);
493 return NETWORK_RECV_STATUS_OKAY;
497 * Ask the server to move us.
498 * @param company The company to move to.
499 * @param password The password of the company to move to.
501 NetworkRecvStatus ClientNetworkGameSocketHandler::SendMove(CompanyID company, const char *password)
503 Packet *p = new Packet(PACKET_CLIENT_MOVE);
504 p->Send_uint8(company);
505 p->Send_string(GenerateCompanyPasswordHash(password, _password_server_id, _password_game_seed));
506 my_client->SendPacket(p);
507 return NETWORK_RECV_STATUS_OKAY;
511 * Check whether the client is actually connected (and in the game).
512 * @return True when the client is connected.
514 bool ClientNetworkGameSocketHandler::IsConnected()
516 return my_client != NULL && my_client->status == STATUS_ACTIVE;
520 /***********
521 * Receiving functions
522 * DEF_CLIENT_RECEIVE_COMMAND has parameter: Packet *p
523 ************/
525 extern bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL);
527 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_FULL(Packet *p)
529 /* We try to join a server which is full */
530 ShowErrorMessage(STR_NETWORK_ERROR_SERVER_FULL, INVALID_STRING_ID, WL_CRITICAL);
531 DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
533 return NETWORK_RECV_STATUS_SERVER_FULL;
536 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_BANNED(Packet *p)
538 /* We try to join a server where we are banned */
539 ShowErrorMessage(STR_NETWORK_ERROR_SERVER_BANNED, INVALID_STRING_ID, WL_CRITICAL);
540 DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
542 return NETWORK_RECV_STATUS_SERVER_BANNED;
545 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_COMPANY_INFO(Packet *p)
547 if (this->status != STATUS_COMPANY_INFO) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
549 byte company_info_version = p->Recv_uint8();
551 if (!this->HasClientQuit() && company_info_version == NETWORK_COMPANY_INFO_VERSION) {
552 /* We have received all data... (there are no more packets coming) */
553 if (!p->Recv_bool()) return NETWORK_RECV_STATUS_CLOSE_QUERY;
555 CompanyID current = (Owner)p->Recv_uint8();
556 if (current >= MAX_COMPANIES) return NETWORK_RECV_STATUS_CLOSE_QUERY;
558 NetworkCompanyInfo *company_info = GetLobbyCompanyInfo(current);
559 if (company_info == NULL) return NETWORK_RECV_STATUS_CLOSE_QUERY;
561 p->Recv_string(company_info->company_name, sizeof(company_info->company_name));
562 company_info->inaugurated_year = p->Recv_uint32();
563 company_info->company_value = p->Recv_uint64();
564 company_info->money = p->Recv_uint64();
565 company_info->income = p->Recv_uint64();
566 company_info->performance = p->Recv_uint16();
567 company_info->use_password = p->Recv_bool();
568 for (uint i = 0; i < NETWORK_VEH_END; i++) {
569 company_info->num_vehicle[i] = p->Recv_uint16();
571 for (uint i = 0; i < NETWORK_VEH_END; i++) {
572 company_info->num_station[i] = p->Recv_uint16();
574 company_info->ai = p->Recv_bool();
576 p->Recv_string(company_info->clients, sizeof(company_info->clients));
578 SetWindowDirty(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_LOBBY);
580 return NETWORK_RECV_STATUS_OKAY;
583 return NETWORK_RECV_STATUS_CLOSE_QUERY;
586 /* This packet contains info about the client (playas and name)
587 * as client we save this in NetworkClientInfo, linked via 'client_id'
588 * which is always an unique number on a server. */
589 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CLIENT_INFO(Packet *p)
591 NetworkClientInfo *ci;
592 ClientID client_id = (ClientID)p->Recv_uint32();
593 CompanyID playas = (CompanyID)p->Recv_uint8();
594 char name[NETWORK_NAME_LENGTH];
596 p->Recv_string(name, sizeof(name));
598 if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
599 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
601 ci = NetworkClientInfo::GetByClientID(client_id);
602 if (ci != NULL) {
603 if (playas == ci->client_playas && strcmp(name, ci->client_name) != 0) {
604 /* Client name changed, display the change */
605 NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, name);
606 } else if (playas != ci->client_playas) {
607 /* The client changed from client-player..
608 * Do not display that for now */
611 /* Make sure we're in the company the server tells us to be in,
612 * for the rare case that we get moved while joining. */
613 if (client_id == _network_own_client_id) SetLocalCompany(!Company::IsValidID(playas) ? COMPANY_SPECTATOR : playas);
615 ci->client_playas = playas;
616 strecpy(ci->client_name, name, lastof(ci->client_name));
618 SetWindowDirty(WC_CLIENT_LIST, 0);
620 return NETWORK_RECV_STATUS_OKAY;
623 /* There are at most as many ClientInfo as ClientSocket objects in a
624 * server. Having more info than a server can have means something
625 * has gone wrong somewhere, i.e. the server has more info than it
626 * has actual clients. That means the server is feeding us an invalid
627 * state. So, bail out! This server is broken. */
628 if (!NetworkClientInfo::CanAllocateItem()) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
630 /* We don't have this client_id yet, find an empty client_id, and put the data there */
631 ci = new NetworkClientInfo(client_id);
632 ci->client_playas = playas;
633 if (client_id == _network_own_client_id) this->SetInfo(ci);
635 strecpy(ci->client_name, name, lastof(ci->client_name));
637 SetWindowDirty(WC_CLIENT_LIST, 0);
639 return NETWORK_RECV_STATUS_OKAY;
642 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR(Packet *p)
644 static const StringID network_error_strings[] = {
645 STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_GENERAL
646 STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_DESYNC
647 STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_SAVEGAME_FAILED
648 STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_CONNECTION_LOST
649 STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_ILLEGAL_PACKET
650 STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_NEWGRF_MISMATCH
651 STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_NOT_AUTHORIZED
652 STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_NOT_EXPECTED
653 STR_NETWORK_ERROR_WRONG_REVISION, // NETWORK_ERROR_WRONG_REVISION
654 STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_NAME_IN_USE
655 STR_NETWORK_ERROR_WRONG_PASSWORD, // NETWORK_ERROR_WRONG_PASSWORD
656 STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_COMPANY_MISMATCH
657 STR_NETWORK_ERROR_KICKED, // NETWORK_ERROR_KICKED
658 STR_NETWORK_ERROR_CHEATER, // NETWORK_ERROR_CHEATER
659 STR_NETWORK_ERROR_SERVER_FULL, // NETWORK_ERROR_FULL
660 STR_NETWORK_ERROR_TOO_MANY_COMMANDS, // NETWORK_ERROR_TOO_MANY_COMMANDS
661 STR_NETWORK_ERROR_TIMEOUT_PASSWORD, // NETWORK_ERROR_TIMEOUT_PASSWORD
662 STR_NETWORK_ERROR_TIMEOUT_COMPUTER, // NETWORK_ERROR_TIMEOUT_COMPUTER
663 STR_NETWORK_ERROR_TIMEOUT_MAP, // NETWORK_ERROR_TIMEOUT_MAP
664 STR_NETWORK_ERROR_TIMEOUT_JOIN, // NETWORK_ERROR_TIMEOUT_JOIN
666 assert_compile(lengthof(network_error_strings) == NETWORK_ERROR_END);
668 NetworkErrorCode error = (NetworkErrorCode)p->Recv_uint8();
670 StringID err = STR_NETWORK_ERROR_LOSTCONNECTION;
671 if (error < (ptrdiff_t)lengthof(network_error_strings)) err = network_error_strings[error];
673 ShowErrorMessage(err, INVALID_STRING_ID, WL_CRITICAL);
675 DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
677 return NETWORK_RECV_STATUS_SERVER_ERROR;
680 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHECK_NEWGRFS(Packet *p)
682 if (this->status != STATUS_JOIN) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
684 uint grf_count = p->Recv_uint8();
685 NetworkRecvStatus ret = NETWORK_RECV_STATUS_OKAY;
687 /* Check all GRFs */
688 for (; grf_count > 0; grf_count--) {
689 GRFIdentifier c;
690 this->ReceiveGRFIdentifier(p, &c);
692 /* Check whether we know this GRF */
693 const GRFConfig *f = FindGRFConfig(c.grfid, FGCM_EXACT, c.md5sum);
694 if (f == NULL) {
695 /* We do not know this GRF, bail out of initialization */
696 char buf[sizeof(c.md5sum) * 2 + 1];
697 md5sumToString(buf, lastof(buf), c.md5sum);
698 DEBUG(grf, 0, "NewGRF %08X not found; checksum %s", BSWAP32(c.grfid), buf);
699 ret = NETWORK_RECV_STATUS_NEWGRF_MISMATCH;
703 if (ret == NETWORK_RECV_STATUS_OKAY) {
704 /* Start receiving the map */
705 return SendNewGRFsOk();
708 /* NewGRF mismatch, bail out */
709 ShowErrorMessage(STR_NETWORK_ERROR_NEWGRF_MISMATCH, INVALID_STRING_ID, WL_CRITICAL);
710 return ret;
713 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_NEED_GAME_PASSWORD(Packet *p)
715 if (this->status < STATUS_JOIN || this->status >= STATUS_AUTH_GAME) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
716 this->status = STATUS_AUTH_GAME;
718 const char *password = _network_join_server_password;
719 if (!StrEmpty(password)) {
720 return SendGamePassword(password);
723 ShowNetworkNeedPassword(NETWORK_GAME_PASSWORD);
725 return NETWORK_RECV_STATUS_OKAY;
728 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_NEED_COMPANY_PASSWORD(Packet *p)
730 if (this->status < STATUS_JOIN || this->status >= STATUS_AUTH_COMPANY) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
731 this->status = STATUS_AUTH_COMPANY;
733 _password_game_seed = p->Recv_uint32();
734 p->Recv_string(_password_server_id, sizeof(_password_server_id));
735 if (this->HasClientQuit()) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
737 const char *password = _network_join_company_password;
738 if (!StrEmpty(password)) {
739 return SendCompanyPassword(password);
742 ShowNetworkNeedPassword(NETWORK_COMPANY_PASSWORD);
744 return NETWORK_RECV_STATUS_OKAY;
747 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_WELCOME(Packet *p)
749 if (this->status < STATUS_JOIN || this->status >= STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
750 this->status = STATUS_AUTHORIZED;
752 _network_own_client_id = (ClientID)p->Recv_uint32();
754 /* Initialize the password hash salting variables, even if they were previously. */
755 _password_game_seed = p->Recv_uint32();
756 p->Recv_string(_password_server_id, sizeof(_password_server_id));
758 /* Start receiving the map */
759 return SendGetMap();
762 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_WAIT(Packet *p)
764 /* We set the internal wait state when requesting the map. */
765 if (this->status != STATUS_MAP_WAIT) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
767 /* But... only now we set the join status to waiting, instead of requesting. */
768 _network_join_status = NETWORK_JOIN_STATUS_WAITING;
769 _network_join_waiting = p->Recv_uint8();
770 SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
772 return NETWORK_RECV_STATUS_OKAY;
775 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_BEGIN(Packet *p)
777 if (this->status < STATUS_AUTHORIZED || this->status >= STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
778 this->status = STATUS_MAP;
780 if (this->savegame != NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
782 this->savegame = new PacketReader();
784 _frame_counter = _frame_counter_server = _frame_counter_max = p->Recv_uint32();
786 _network_join_bytes = 0;
787 _network_join_bytes_total = 0;
789 _network_join_status = NETWORK_JOIN_STATUS_DOWNLOADING;
790 SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
792 return NETWORK_RECV_STATUS_OKAY;
795 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_SIZE(Packet *p)
797 if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
798 if (this->savegame == NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
800 _network_join_bytes_total = p->Recv_uint32();
801 SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
803 return NETWORK_RECV_STATUS_OKAY;
806 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DATA(Packet *p)
808 if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
809 if (this->savegame == NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
811 /* We are still receiving data, put it to the file */
812 this->savegame->AddPacket(p);
814 _network_join_bytes = (uint32)this->savegame->written_bytes;
815 SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
817 return NETWORK_RECV_STATUS_OKAY;
820 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DONE(Packet *p)
822 if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
823 if (this->savegame == NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
825 _network_join_status = NETWORK_JOIN_STATUS_PROCESSING;
826 SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
829 * Make sure everything is set for reading.
831 * We need the local copy and reset this->savegame because when
832 * loading fails the network gets reset upon loading the intro
833 * game, which would cause us to free this->savegame twice.
835 LoadFilter *lf = this->savegame;
836 this->savegame = NULL;
837 lf->Reset();
839 /* The map is done downloading, load it */
840 ClearErrorMessages();
841 bool load_success = SafeLoad(NULL, SLO_LOAD, DFT_GAME_FILE, GM_NORMAL, NO_DIRECTORY, lf);
843 /* Long savegame loads shouldn't affect the lag calculation! */
844 this->last_packet = _realtime_tick;
846 if (!load_success) {
847 DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
848 ShowErrorMessage(STR_NETWORK_ERROR_SAVEGAMEERROR, INVALID_STRING_ID, WL_CRITICAL);
849 return NETWORK_RECV_STATUS_SAVEGAME;
851 /* If the savegame has successfully loaded, ALL windows have been removed,
852 * only toolbar/statusbar and gamefield are visible */
854 /* Say we received the map and loaded it correctly! */
855 SendMapOk();
857 /* New company/spectator (invalid company) or company we want to join is not active
858 * Switch local company to spectator and await the server's judgement */
859 if (_network_join_as == COMPANY_NEW_COMPANY || !Company::IsValidID(_network_join_as)) {
860 SetLocalCompany(COMPANY_SPECTATOR);
862 if (_network_join_as != COMPANY_SPECTATOR) {
863 /* We have arrived and ready to start playing; send a command to make a new company;
864 * the server will give us a client-id and let us in */
865 _network_join_status = NETWORK_JOIN_STATUS_REGISTERING;
866 ShowJoinStatusWindow();
867 NetworkSendCommand(0, 0, 0, CMD_COMPANY_CTRL, NULL, NULL, _local_company, 0);
869 } else {
870 /* take control over an existing company */
871 SetLocalCompany(_network_join_as);
874 return NETWORK_RECV_STATUS_OKAY;
877 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_FRAME(Packet *p)
879 if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
881 _frame_counter_server = p->Recv_uint32();
882 _frame_counter_max = p->Recv_uint32();
883 #ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
884 /* Test if the server supports this option
885 * and if we are at the frame the server is */
886 if (p->pos + 1 < p->size) {
887 _sync_frame = _frame_counter_server;
888 _sync_seed_1 = p->Recv_uint32();
889 #ifdef NETWORK_SEND_DOUBLE_SEED
890 _sync_seed_2 = p->Recv_uint32();
891 #endif
893 #endif
894 /* Receive the token. */
895 if (p->pos != p->size) this->token = p->Recv_uint8();
897 DEBUG(net, 5, "Received FRAME %d", _frame_counter_server);
899 /* Let the server know that we received this frame correctly
900 * We do this only once per day, to save some bandwidth ;) */
901 if (!_network_first_time && last_ack_frame < _frame_counter) {
902 last_ack_frame = _frame_counter + DAY_TICKS;
903 DEBUG(net, 4, "Sent ACK at %d", _frame_counter);
904 SendAck();
907 return NETWORK_RECV_STATUS_OKAY;
910 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_SYNC(Packet *p)
912 if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
914 _sync_frame = p->Recv_uint32();
915 _sync_seed_1 = p->Recv_uint32();
916 #ifdef NETWORK_SEND_DOUBLE_SEED
917 _sync_seed_2 = p->Recv_uint32();
918 #endif
920 return NETWORK_RECV_STATUS_OKAY;
923 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_COMMAND(Packet *p)
925 if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
927 CommandPacket cp;
928 const char *err = this->ReceiveCommand(p, &cp);
929 cp.frame = p->Recv_uint32();
930 cp.my_cmd = p->Recv_bool();
932 if (err != NULL) {
933 IConsolePrintF(CC_ERROR, "WARNING: %s from server, dropping...", err);
934 return NETWORK_RECV_STATUS_MALFORMED_PACKET;
937 this->incoming_queue.Append(&cp);
939 return NETWORK_RECV_STATUS_OKAY;
942 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHAT(Packet *p)
944 if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
946 char name[NETWORK_NAME_LENGTH], msg[NETWORK_CHAT_LENGTH];
947 const NetworkClientInfo *ci = NULL, *ci_to;
949 NetworkAction action = (NetworkAction)p->Recv_uint8();
950 ClientID client_id = (ClientID)p->Recv_uint32();
951 bool self_send = p->Recv_bool();
952 p->Recv_string(msg, NETWORK_CHAT_LENGTH);
953 int64 data = p->Recv_uint64();
955 ci_to = NetworkClientInfo::GetByClientID(client_id);
956 if (ci_to == NULL) return NETWORK_RECV_STATUS_OKAY;
958 /* Did we initiate the action locally? */
959 if (self_send) {
960 switch (action) {
961 case NETWORK_ACTION_CHAT_CLIENT:
962 /* For speaking to client we need the client-name */
963 seprintf(name, lastof(name), "%s", ci_to->client_name);
964 ci = NetworkClientInfo::GetByClientID(_network_own_client_id);
965 break;
967 /* For speaking to company or giving money, we need the company-name */
968 case NETWORK_ACTION_GIVE_MONEY:
969 if (!Company::IsValidID(ci_to->client_playas)) return NETWORK_RECV_STATUS_OKAY;
970 FALLTHROUGH;
972 case NETWORK_ACTION_CHAT_COMPANY: {
973 StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
974 SetDParam(0, ci_to->client_playas);
976 GetString(name, str, lastof(name));
977 ci = NetworkClientInfo::GetByClientID(_network_own_client_id);
978 break;
981 default: return NETWORK_RECV_STATUS_MALFORMED_PACKET;
983 } else {
984 /* Display message from somebody else */
985 seprintf(name, lastof(name), "%s", ci_to->client_name);
986 ci = ci_to;
989 if (ci != NULL) {
990 NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), self_send, name, msg, data);
992 return NETWORK_RECV_STATUS_OKAY;
995 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR_QUIT(Packet *p)
997 if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
999 ClientID client_id = (ClientID)p->Recv_uint32();
1001 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1002 if (ci != NULL) {
1003 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, NULL, GetNetworkErrorMsg((NetworkErrorCode)p->Recv_uint8()));
1004 delete ci;
1007 SetWindowDirty(WC_CLIENT_LIST, 0);
1009 return NETWORK_RECV_STATUS_OKAY;
1012 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_QUIT(Packet *p)
1014 if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
1016 ClientID client_id = (ClientID)p->Recv_uint32();
1018 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1019 if (ci != NULL) {
1020 NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, NULL, STR_NETWORK_MESSAGE_CLIENT_LEAVING);
1021 delete ci;
1022 } else {
1023 DEBUG(net, 0, "Unknown client (%d) is leaving the game", client_id);
1026 SetWindowDirty(WC_CLIENT_LIST, 0);
1028 /* If we come here it means we could not locate the client.. strange :s */
1029 return NETWORK_RECV_STATUS_OKAY;
1032 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_JOIN(Packet *p)
1034 if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
1036 ClientID client_id = (ClientID)p->Recv_uint32();
1038 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1039 if (ci != NULL) {
1040 NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, ci->client_name);
1043 SetWindowDirty(WC_CLIENT_LIST, 0);
1045 return NETWORK_RECV_STATUS_OKAY;
1048 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_SHUTDOWN(Packet *p)
1050 /* Only when we're trying to join we really
1051 * care about the server shutting down. */
1052 if (this->status >= STATUS_JOIN) {
1053 ShowErrorMessage(STR_NETWORK_MESSAGE_SERVER_SHUTDOWN, INVALID_STRING_ID, WL_CRITICAL);
1056 return NETWORK_RECV_STATUS_SERVER_ERROR;
1059 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_NEWGAME(Packet *p)
1061 /* Only when we're trying to join we really
1062 * care about the server shutting down. */
1063 if (this->status >= STATUS_JOIN) {
1064 /* To throttle the reconnects a bit, every clients waits its
1065 * Client ID modulo 16. This way reconnects should be spread
1066 * out a bit. */
1067 _network_reconnect = _network_own_client_id % 16;
1068 ShowErrorMessage(STR_NETWORK_MESSAGE_SERVER_REBOOT, INVALID_STRING_ID, WL_CRITICAL);
1071 return NETWORK_RECV_STATUS_SERVER_ERROR;
1074 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_RCON(Packet *p)
1076 if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
1078 TextColour colour_code = (TextColour)p->Recv_uint16();
1079 if (!IsValidConsoleColour(colour_code)) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
1081 char rcon_out[NETWORK_RCONCOMMAND_LENGTH];
1082 p->Recv_string(rcon_out, sizeof(rcon_out));
1084 IConsolePrint(colour_code, rcon_out);
1086 return NETWORK_RECV_STATUS_OKAY;
1089 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MOVE(Packet *p)
1091 if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
1093 /* Nothing more in this packet... */
1094 ClientID client_id = (ClientID)p->Recv_uint32();
1095 CompanyID company_id = (CompanyID)p->Recv_uint8();
1097 if (client_id == 0) {
1098 /* definitely an invalid client id, debug message and do nothing. */
1099 DEBUG(net, 0, "[move] received invalid client index = 0");
1100 return NETWORK_RECV_STATUS_MALFORMED_PACKET;
1103 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
1104 /* Just make sure we do not try to use a client_index that does not exist */
1105 if (ci == NULL) return NETWORK_RECV_STATUS_OKAY;
1107 /* if not valid player, force spectator, else check player exists */
1108 if (!Company::IsValidID(company_id)) company_id = COMPANY_SPECTATOR;
1110 if (client_id == _network_own_client_id) {
1111 SetLocalCompany(company_id);
1114 return NETWORK_RECV_STATUS_OKAY;
1117 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CONFIG_UPDATE(Packet *p)
1119 if (this->status < STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
1121 _network_server_max_companies = p->Recv_uint8();
1122 _network_server_max_spectators = p->Recv_uint8();
1124 return NETWORK_RECV_STATUS_OKAY;
1127 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_COMPANY_UPDATE(Packet *p)
1129 if (this->status < STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
1131 _network_company_passworded = p->Recv_uint16();
1132 SetWindowClassesDirty(WC_COMPANY);
1134 return NETWORK_RECV_STATUS_OKAY;
1138 * Check the connection's state, i.e. is the connection still up?
1140 void ClientNetworkGameSocketHandler::CheckConnection()
1142 /* Only once we're authorized we can expect a steady stream of packets. */
1143 if (this->status < STATUS_AUTHORIZED) return;
1145 /* It might... sometimes occur that the realtime ticker overflows. */
1146 if (_realtime_tick < this->last_packet) this->last_packet = _realtime_tick;
1148 /* Lag is in milliseconds; 5 seconds are roughly twice the
1149 * server's "you're slow" threshold (1 game day). */
1150 uint lag = (_realtime_tick - this->last_packet) / 1000;
1151 if (lag < 5) return;
1153 /* 20 seconds are (way) more than 4 game days after which
1154 * the server will forcefully disconnect you. */
1155 if (lag > 20) {
1156 this->NetworkGameSocketHandler::CloseConnection();
1157 ShowErrorMessage(STR_NETWORK_ERROR_LOSTCONNECTION, INVALID_STRING_ID, WL_CRITICAL);
1158 return;
1161 /* Prevent showing the lag message every tick; just update it when needed. */
1162 static uint last_lag = 0;
1163 if (last_lag == lag) return;
1165 last_lag = lag;
1166 SetDParam(0, lag);
1167 ShowErrorMessage(STR_NETWORK_ERROR_CLIENT_GUI_LOST_CONNECTION_CAPTION, STR_NETWORK_ERROR_CLIENT_GUI_LOST_CONNECTION, WL_INFO);
1171 /** Is called after a client is connected to the server */
1172 void NetworkClient_Connected()
1174 /* Set the frame-counter to 0 so nothing happens till we are ready */
1175 _frame_counter = 0;
1176 _frame_counter_server = 0;
1177 last_ack_frame = 0;
1178 /* Request the game-info */
1179 MyClient::SendJoin();
1183 * Send a remote console command.
1184 * @param password The password.
1185 * @param command The command to execute.
1187 void NetworkClientSendRcon(const char *password, const char *command)
1189 MyClient::SendRCon(password, command);
1193 * Notify the server of this client wanting to be moved to another company.
1194 * @param company_id id of the company the client wishes to be moved to.
1195 * @param pass the password, is only checked on the server end if a password is needed.
1196 * @return void
1198 void NetworkClientRequestMove(CompanyID company_id, const char *pass)
1200 MyClient::SendMove(company_id, pass);
1204 * Move the clients of a company to the spectators.
1205 * @param cid The company to move the clients of.
1207 void NetworkClientsToSpectators(CompanyID cid)
1209 Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
1210 /* If our company is changing owner, go to spectators */
1211 if (cid == _local_company) SetLocalCompany(COMPANY_SPECTATOR);
1213 NetworkClientInfo *ci;
1214 FOR_ALL_CLIENT_INFOS(ci) {
1215 if (ci->client_playas != cid) continue;
1216 NetworkTextMessage(NETWORK_ACTION_COMPANY_SPECTATOR, CC_DEFAULT, false, ci->client_name);
1217 ci->client_playas = COMPANY_SPECTATOR;
1220 cur_company.Restore();
1224 * Send the server our name.
1226 void NetworkUpdateClientName()
1228 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(_network_own_client_id);
1230 if (ci == NULL) return;
1232 /* Don't change the name if it is the same as the old name */
1233 if (strcmp(ci->client_name, _settings_client.network.client_name) != 0) {
1234 if (!_network_server) {
1235 MyClient::SendSetName(_settings_client.network.client_name);
1236 } else {
1237 if (NetworkFindName(_settings_client.network.client_name, lastof(_settings_client.network.client_name))) {
1238 NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, _settings_client.network.client_name);
1239 strecpy(ci->client_name, _settings_client.network.client_name, lastof(ci->client_name));
1240 NetworkUpdateClientInfo(CLIENT_ID_SERVER);
1247 * Send a chat message.
1248 * @param action The action associated with the message.
1249 * @param type The destination type.
1250 * @param dest The destination index, be it a company index or client id.
1251 * @param msg The actual message.
1252 * @param data Arbitrary extra data.
1254 void NetworkClientSendChat(NetworkAction action, DestType type, int dest, const char *msg, int64 data)
1256 MyClient::SendChat(action, type, dest, msg, data);
1260 * Set/Reset company password on the client side.
1261 * @param password Password to be set.
1263 void NetworkClientSetCompanyPassword(const char *password)
1265 MyClient::SendSetPassword(password);
1269 * Tell whether the client has team members where he/she can chat to.
1270 * @param cio client to check members of.
1271 * @return true if there is at least one team member.
1273 bool NetworkClientPreferTeamChat(const NetworkClientInfo *cio)
1275 /* Only companies actually playing can speak to team. Eg spectators cannot */
1276 if (!_settings_client.gui.prefer_teamchat || !Company::IsValidID(cio->client_playas)) return false;
1278 const NetworkClientInfo *ci;
1279 FOR_ALL_CLIENT_INFOS(ci) {
1280 if (ci->client_playas == cio->client_playas && ci != cio) return true;
1283 return false;
1287 * Check if max_companies has been reached on the server (local check only).
1288 * @return true if the max value has been reached or exceeded, false otherwise.
1290 bool NetworkMaxCompaniesReached()
1292 return Company::GetNumItems() >= (_network_server ? _settings_client.network.max_companies : _network_server_max_companies);
1296 * Check if max_spectatos 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 NetworkMaxSpectatorsReached()
1301 return NetworkSpectatorCount() >= (_network_server ? _settings_client.network.max_spectators : _network_server_max_spectators);
1304 #endif /* ENABLE_NETWORK */