network_client.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00012 #ifdef ENABLE_NETWORK
00013 
00014 #include "../stdafx.h"
00015 #include "network_gui.h"
00016 #include "../saveload/saveload.h"
00017 #include "../saveload/saveload_filter.h"
00018 #include "../command_func.h"
00019 #include "../console_func.h"
00020 #include "../strings_func.h"
00021 #include "../window_func.h"
00022 #include "../company_func.h"
00023 #include "../company_base.h"
00024 #include "../company_gui.h"
00025 #include "../core/random_func.hpp"
00026 #include "../date_func.h"
00027 #include "../gfx_func.h"
00028 #include "../error.h"
00029 #include "../rev.h"
00030 #include "network.h"
00031 #include "network_base.h"
00032 #include "network_client.h"
00033 #include "../core/backup_type.hpp"
00034 #include "../viewport_func.h"
00035 
00036 #include "table/strings.h"
00037 
00038 /* This file handles all the client-commands */
00039 
00040 
00042 struct PacketReader : LoadFilter {
00043   static const size_t CHUNK = 32 * 1024;  
00044 
00045   AutoFreeSmallVector<byte *, 16> blocks; 
00046   byte *buf;                              
00047   byte *bufe;                             
00048   byte **block;                           
00049   size_t written_bytes;                   
00050   size_t read_bytes;                      
00051 
00053   PacketReader() : LoadFilter(NULL), buf(NULL), bufe(NULL), block(NULL), written_bytes(0), read_bytes(0)
00054   {
00055   }
00056 
00061   void AddPacket(const Packet *p)
00062   {
00063     assert(this->read_bytes == 0);
00064 
00065     size_t in_packet = p->size - p->pos;
00066     size_t to_write  = min((size_t)(this->bufe - this->buf), in_packet);
00067     const byte *pbuf = p->buffer + p->pos;
00068 
00069     this->written_bytes += in_packet;
00070     if (to_write != 0) {
00071       memcpy(this->buf, pbuf, to_write);
00072       this->buf += to_write;
00073     }
00074 
00075     /* Did everything fit in the current chunk, then we're done. */
00076     if (to_write == in_packet) return;
00077 
00078     /* Allocate a new chunk and add the remaining data. */
00079     pbuf += to_write;
00080     to_write   = in_packet - to_write;
00081     this->buf  = *this->blocks.Append() = CallocT<byte>(CHUNK);
00082     this->bufe = this->buf + CHUNK;
00083 
00084     memcpy(this->buf, pbuf, to_write);
00085     this->buf += to_write;
00086   }
00087 
00088   /* virtual */ size_t Read(byte *rbuf, size_t size)
00089   {
00090     /* Limit the amount to read to whatever we still have. */
00091     size_t ret_size = size = min(this->written_bytes - this->read_bytes, size);
00092     this->read_bytes += ret_size;
00093     const byte *rbufe = rbuf + ret_size;
00094 
00095     while (rbuf != rbufe) {
00096       if (this->buf == this->bufe) {
00097         this->buf = *this->block++;
00098         this->bufe = this->buf + CHUNK;
00099       }
00100 
00101       size_t to_write = min(this->bufe - this->buf, rbufe - rbuf);
00102       memcpy(rbuf, this->buf, to_write);
00103       rbuf += to_write;
00104       this->buf += to_write;
00105     }
00106 
00107     return ret_size;
00108   }
00109 
00110   /* virtual */ void Reset()
00111   {
00112     this->read_bytes = 0;
00113 
00114     this->block = this->blocks.Begin();
00115     this->buf   = *this->block++;
00116     this->bufe  = this->buf + CHUNK;
00117   }
00118 };
00119 
00120 
00125 ClientNetworkGameSocketHandler::ClientNetworkGameSocketHandler(SOCKET s) : NetworkGameSocketHandler(s), savegame(NULL), status(STATUS_INACTIVE)
00126 {
00127   assert(ClientNetworkGameSocketHandler::my_client == NULL);
00128   ClientNetworkGameSocketHandler::my_client = this;
00129 }
00130 
00132 ClientNetworkGameSocketHandler::~ClientNetworkGameSocketHandler()
00133 {
00134   assert(ClientNetworkGameSocketHandler::my_client == this);
00135   ClientNetworkGameSocketHandler::my_client = NULL;
00136 
00137   delete this->savegame;
00138 }
00139 
00140 NetworkRecvStatus ClientNetworkGameSocketHandler::CloseConnection(NetworkRecvStatus status)
00141 {
00142   assert(status != NETWORK_RECV_STATUS_OKAY);
00143   /*
00144    * Sending a message just before leaving the game calls cs->SendPackets.
00145    * This might invoke this function, which means that when we close the
00146    * connection after cs->SendPackets we will close an already closed
00147    * connection. This handles that case gracefully without having to make
00148    * that code any more complex or more aware of the validity of the socket.
00149    */
00150   if (this->sock == INVALID_SOCKET) return status;
00151 
00152   DEBUG(net, 1, "Closed client connection %d", this->client_id);
00153 
00154   this->SendPackets(true);
00155 
00156   /* Wait a number of ticks so our leave message can reach the server.
00157    * This is especially needed for Windows servers as they seem to get
00158    * the "socket is closed" message before receiving our leave message,
00159    * which would trigger the server to close the connection as well. */
00160   CSleep(3 * MILLISECONDS_PER_TICK);
00161 
00162   delete this->GetInfo();
00163   delete this;
00164 
00165   return status;
00166 }
00167 
00172 void ClientNetworkGameSocketHandler::ClientError(NetworkRecvStatus res)
00173 {
00174   /* First, send a CLIENT_ERROR to the server, so he knows we are
00175    *  disconnection (and why!) */
00176   NetworkErrorCode errorno;
00177 
00178   /* We just want to close the connection.. */
00179   if (res == NETWORK_RECV_STATUS_CLOSE_QUERY) {
00180     this->NetworkSocketHandler::CloseConnection();
00181     this->CloseConnection(res);
00182     _networking = false;
00183 
00184     DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
00185     return;
00186   }
00187 
00188   switch (res) {
00189     case NETWORK_RECV_STATUS_DESYNC:          errorno = NETWORK_ERROR_DESYNC; break;
00190     case NETWORK_RECV_STATUS_SAVEGAME:        errorno = NETWORK_ERROR_SAVEGAME_FAILED; break;
00191     case NETWORK_RECV_STATUS_NEWGRF_MISMATCH: errorno = NETWORK_ERROR_NEWGRF_MISMATCH; break;
00192     default:                                  errorno = NETWORK_ERROR_GENERAL; break;
00193   }
00194 
00195   /* This means we fucked up and the server closed the connection */
00196   if (res != NETWORK_RECV_STATUS_SERVER_ERROR && res != NETWORK_RECV_STATUS_SERVER_FULL &&
00197       res != NETWORK_RECV_STATUS_SERVER_BANNED) {
00198     SendError(errorno);
00199   }
00200 
00201   _switch_mode = SM_MENU;
00202   this->CloseConnection(res);
00203   _networking = false;
00204 }
00205 
00206 
00212 /*static */ bool ClientNetworkGameSocketHandler::Receive()
00213 {
00214   if (my_client->CanSendReceive()) {
00215     NetworkRecvStatus res = my_client->ReceivePackets();
00216     if (res != NETWORK_RECV_STATUS_OKAY) {
00217       /* The client made an error of which we can not recover.
00218        * Close the connection and drop back to the main menu. */
00219       my_client->ClientError(res);
00220       return false;
00221     }
00222   }
00223   return _networking;
00224 }
00225 
00227 /*static */ void ClientNetworkGameSocketHandler::Send()
00228 {
00229   my_client->SendPackets();
00230   my_client->CheckConnection();
00231 }
00232 
00237 /* static */ bool ClientNetworkGameSocketHandler::GameLoop()
00238 {
00239   _frame_counter++;
00240 
00241   NetworkExecuteLocalCommandQueue();
00242 
00243   extern void StateGameLoop();
00244   StateGameLoop();
00245 
00246   /* Check if we are in sync! */
00247   if (_sync_frame != 0) {
00248     if (_sync_frame == _frame_counter) {
00249 #ifdef NETWORK_SEND_DOUBLE_SEED
00250       if (_sync_seed_1 != _random.state[0] || _sync_seed_2 != _random.state[1]) {
00251 #else
00252       if (_sync_seed_1 != _random.state[0]) {
00253 #endif
00254         NetworkError(STR_NETWORK_ERROR_DESYNC);
00255         DEBUG(desync, 1, "sync_err: %08x; %02x", _date, _date_fract);
00256         DEBUG(net, 0, "Sync error detected!");
00257         my_client->ClientError(NETWORK_RECV_STATUS_DESYNC);
00258         return false;
00259       }
00260 
00261       /* If this is the first time we have a sync-frame, we
00262        *   need to let the server know that we are ready and at the same
00263        *   frame as he is.. so we can start playing! */
00264       if (_network_first_time) {
00265         _network_first_time = false;
00266         SendAck();
00267       }
00268 
00269       _sync_frame = 0;
00270     } else if (_sync_frame < _frame_counter) {
00271       DEBUG(net, 1, "Missed frame for sync-test (%d / %d)", _sync_frame, _frame_counter);
00272       _sync_frame = 0;
00273     }
00274   }
00275 
00276   return true;
00277 }
00278 
00279 
00281 ClientNetworkGameSocketHandler * ClientNetworkGameSocketHandler::my_client = NULL;
00282 
00284 static uint32 last_ack_frame;
00285 
00287 static uint32 _password_game_seed;
00289 static char _password_server_id[NETWORK_SERVER_ID_LENGTH];
00290 
00292 static uint8 _network_server_max_companies;
00294 static uint8 _network_server_max_spectators;
00295 
00297 CompanyID _network_join_as;
00298 
00300 const char *_network_join_server_password = NULL;
00302 const char *_network_join_company_password = NULL;
00303 
00305 assert_compile(NETWORK_SERVER_ID_LENGTH == 16 * 2 + 1);
00306 
00307 /***********
00308  * Sending functions
00309  *   DEF_CLIENT_SEND_COMMAND has no parameters
00310  ************/
00311 
00313 NetworkRecvStatus ClientNetworkGameSocketHandler::SendCompanyInformationQuery()
00314 {
00315   my_client->status = STATUS_COMPANY_INFO;
00316   _network_join_status = NETWORK_JOIN_STATUS_GETTING_COMPANY_INFO;
00317   SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
00318 
00319   Packet *p = new Packet(PACKET_CLIENT_COMPANY_INFO);
00320   my_client->SendPacket(p);
00321   return NETWORK_RECV_STATUS_OKAY;
00322 }
00323 
00325 NetworkRecvStatus ClientNetworkGameSocketHandler::SendJoin()
00326 {
00327   my_client->status = STATUS_JOIN;
00328   _network_join_status = NETWORK_JOIN_STATUS_AUTHORIZING;
00329   SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
00330 
00331   Packet *p = new Packet(PACKET_CLIENT_JOIN);
00332   p->Send_string(_openttd_revision);
00333   p->Send_uint32(_openttd_newgrf_version);
00334   p->Send_string(_settings_client.network.client_name); // Client name
00335   p->Send_uint8 (_network_join_as);     // PlayAs
00336   p->Send_uint8 (NETLANG_ANY);          // Language
00337   my_client->SendPacket(p);
00338   return NETWORK_RECV_STATUS_OKAY;
00339 }
00340 
00342 NetworkRecvStatus ClientNetworkGameSocketHandler::SendNewGRFsOk()
00343 {
00344   Packet *p = new Packet(PACKET_CLIENT_NEWGRFS_CHECKED);
00345   my_client->SendPacket(p);
00346   return NETWORK_RECV_STATUS_OKAY;
00347 }
00348 
00353 NetworkRecvStatus ClientNetworkGameSocketHandler::SendGamePassword(const char *password)
00354 {
00355   Packet *p = new Packet(PACKET_CLIENT_GAME_PASSWORD);
00356   p->Send_string(password);
00357   my_client->SendPacket(p);
00358   return NETWORK_RECV_STATUS_OKAY;
00359 }
00360 
00365 NetworkRecvStatus ClientNetworkGameSocketHandler::SendCompanyPassword(const char *password)
00366 {
00367   Packet *p = new Packet(PACKET_CLIENT_COMPANY_PASSWORD);
00368   p->Send_string(GenerateCompanyPasswordHash(password, _password_server_id, _password_game_seed));
00369   my_client->SendPacket(p);
00370   return NETWORK_RECV_STATUS_OKAY;
00371 }
00372 
00374 NetworkRecvStatus ClientNetworkGameSocketHandler::SendGetMap()
00375 {
00376   my_client->status = STATUS_MAP_WAIT;
00377 
00378   Packet *p = new Packet(PACKET_CLIENT_GETMAP);
00379   my_client->SendPacket(p);
00380   return NETWORK_RECV_STATUS_OKAY;
00381 }
00382 
00384 NetworkRecvStatus ClientNetworkGameSocketHandler::SendMapOk()
00385 {
00386   my_client->status = STATUS_ACTIVE;
00387 
00388   Packet *p = new Packet(PACKET_CLIENT_MAP_OK);
00389   my_client->SendPacket(p);
00390   return NETWORK_RECV_STATUS_OKAY;
00391 }
00392 
00394 NetworkRecvStatus ClientNetworkGameSocketHandler::SendAck()
00395 {
00396   Packet *p = new Packet(PACKET_CLIENT_ACK);
00397 
00398   p->Send_uint32(_frame_counter);
00399   p->Send_uint8 (my_client->token);
00400   my_client->SendPacket(p);
00401   return NETWORK_RECV_STATUS_OKAY;
00402 }
00403 
00408 NetworkRecvStatus ClientNetworkGameSocketHandler::SendCommand(const CommandPacket *cp)
00409 {
00410   Packet *p = new Packet(PACKET_CLIENT_COMMAND);
00411   my_client->NetworkGameSocketHandler::SendCommand(p, cp);
00412 
00413   my_client->SendPacket(p);
00414   return NETWORK_RECV_STATUS_OKAY;
00415 }
00416 
00418 NetworkRecvStatus ClientNetworkGameSocketHandler::SendChat(NetworkAction action, DestType type, int dest, const char *msg, int64 data)
00419 {
00420   Packet *p = new Packet(PACKET_CLIENT_CHAT);
00421 
00422   p->Send_uint8 (action);
00423   p->Send_uint8 (type);
00424   p->Send_uint32(dest);
00425   p->Send_string(msg);
00426   p->Send_uint64(data);
00427 
00428   my_client->SendPacket(p);
00429   return NETWORK_RECV_STATUS_OKAY;
00430 }
00431 
00433 NetworkRecvStatus ClientNetworkGameSocketHandler::SendError(NetworkErrorCode errorno)
00434 {
00435   Packet *p = new Packet(PACKET_CLIENT_ERROR);
00436 
00437   p->Send_uint8(errorno);
00438   my_client->SendPacket(p);
00439   return NETWORK_RECV_STATUS_OKAY;
00440 }
00441 
00446 NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetPassword(const char *password)
00447 {
00448   Packet *p = new Packet(PACKET_CLIENT_SET_PASSWORD);
00449 
00450   p->Send_string(GenerateCompanyPasswordHash(password, _password_server_id, _password_game_seed));
00451   my_client->SendPacket(p);
00452   return NETWORK_RECV_STATUS_OKAY;
00453 }
00454 
00459 NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetName(const char *name)
00460 {
00461   Packet *p = new Packet(PACKET_CLIENT_SET_NAME);
00462 
00463   p->Send_string(name);
00464   my_client->SendPacket(p);
00465   return NETWORK_RECV_STATUS_OKAY;
00466 }
00467 
00471 NetworkRecvStatus ClientNetworkGameSocketHandler::SendQuit()
00472 {
00473   Packet *p = new Packet(PACKET_CLIENT_QUIT);
00474 
00475   my_client->SendPacket(p);
00476   return NETWORK_RECV_STATUS_OKAY;
00477 }
00478 
00484 NetworkRecvStatus ClientNetworkGameSocketHandler::SendRCon(const char *pass, const char *command)
00485 {
00486   Packet *p = new Packet(PACKET_CLIENT_RCON);
00487   p->Send_string(pass);
00488   p->Send_string(command);
00489   my_client->SendPacket(p);
00490   return NETWORK_RECV_STATUS_OKAY;
00491 }
00492 
00498 NetworkRecvStatus ClientNetworkGameSocketHandler::SendMove(CompanyID company, const char *password)
00499 {
00500   Packet *p = new Packet(PACKET_CLIENT_MOVE);
00501   p->Send_uint8(company);
00502   p->Send_string(GenerateCompanyPasswordHash(password, _password_server_id, _password_game_seed));
00503   my_client->SendPacket(p);
00504   return NETWORK_RECV_STATUS_OKAY;
00505 }
00506 
00511 bool ClientNetworkGameSocketHandler::IsConnected()
00512 {
00513   return my_client != NULL && my_client->status == STATUS_ACTIVE;
00514 }
00515 
00516 
00517 /***********
00518  * Receiving functions
00519  *   DEF_CLIENT_RECEIVE_COMMAND has parameter: Packet *p
00520  ************/
00521 
00522 extern bool SafeLoad(const char *filename, int mode, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL);
00523 
00524 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_FULL(Packet *p)
00525 {
00526   /* We try to join a server which is full */
00527   ShowErrorMessage(STR_NETWORK_ERROR_SERVER_FULL, INVALID_STRING_ID, WL_CRITICAL);
00528   DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
00529 
00530   return NETWORK_RECV_STATUS_SERVER_FULL;
00531 }
00532 
00533 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_BANNED(Packet *p)
00534 {
00535   /* We try to join a server where we are banned */
00536   ShowErrorMessage(STR_NETWORK_ERROR_SERVER_BANNED, INVALID_STRING_ID, WL_CRITICAL);
00537   DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
00538 
00539   return NETWORK_RECV_STATUS_SERVER_BANNED;
00540 }
00541 
00542 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_COMPANY_INFO(Packet *p)
00543 {
00544   if (this->status != STATUS_COMPANY_INFO) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00545 
00546   byte company_info_version = p->Recv_uint8();
00547 
00548   if (!this->HasClientQuit() && company_info_version == NETWORK_COMPANY_INFO_VERSION) {
00549     /* We have received all data... (there are no more packets coming) */
00550     if (!p->Recv_bool()) return NETWORK_RECV_STATUS_CLOSE_QUERY;
00551 
00552     CompanyID current = (Owner)p->Recv_uint8();
00553     if (current >= MAX_COMPANIES) return NETWORK_RECV_STATUS_CLOSE_QUERY;
00554 
00555     NetworkCompanyInfo *company_info = GetLobbyCompanyInfo(current);
00556     if (company_info == NULL) return NETWORK_RECV_STATUS_CLOSE_QUERY;
00557 
00558     p->Recv_string(company_info->company_name, sizeof(company_info->company_name));
00559     company_info->inaugurated_year = p->Recv_uint32();
00560     company_info->company_value    = p->Recv_uint64();
00561     company_info->money            = p->Recv_uint64();
00562     company_info->income           = p->Recv_uint64();
00563     company_info->performance      = p->Recv_uint16();
00564     company_info->use_password     = p->Recv_bool();
00565     for (uint i = 0; i < NETWORK_VEH_END; i++) {
00566       company_info->num_vehicle[i] = p->Recv_uint16();
00567     }
00568     for (uint i = 0; i < NETWORK_VEH_END; i++) {
00569       company_info->num_station[i] = p->Recv_uint16();
00570     }
00571     company_info->ai               = p->Recv_bool();
00572 
00573     p->Recv_string(company_info->clients, sizeof(company_info->clients));
00574 
00575     SetWindowDirty(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_LOBBY);
00576 
00577     return NETWORK_RECV_STATUS_OKAY;
00578   }
00579 
00580   return NETWORK_RECV_STATUS_CLOSE_QUERY;
00581 }
00582 
00583 /* This packet contains info about the client (playas and name)
00584  *  as client we save this in NetworkClientInfo, linked via 'client_id'
00585  *  which is always an unique number on a server. */
00586 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CLIENT_INFO(Packet *p)
00587 {
00588   NetworkClientInfo *ci;
00589   ClientID client_id = (ClientID)p->Recv_uint32();
00590   CompanyID playas = (CompanyID)p->Recv_uint8();
00591   char name[NETWORK_NAME_LENGTH];
00592 
00593   p->Recv_string(name, sizeof(name));
00594 
00595   if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00596   if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
00597 
00598   ci = NetworkClientInfo::GetByClientID(client_id);
00599   if (ci != NULL) {
00600     if (playas == ci->client_playas && strcmp(name, ci->client_name) != 0) {
00601       /* Client name changed, display the change */
00602       NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, name);
00603     } else if (playas != ci->client_playas) {
00604       /* The client changed from client-player..
00605        * Do not display that for now */
00606     }
00607 
00608     /* Make sure we're in the company the server tells us to be in,
00609      * for the rare case that we get moved while joining. */
00610     if (client_id == _network_own_client_id) SetLocalCompany(!Company::IsValidID(playas) ? COMPANY_SPECTATOR : playas);
00611 
00612     ci->client_playas = playas;
00613     strecpy(ci->client_name, name, lastof(ci->client_name));
00614 
00615     SetWindowDirty(WC_CLIENT_LIST, 0);
00616 
00617     return NETWORK_RECV_STATUS_OKAY;
00618   }
00619 
00620   /* There are at most as many ClientInfo as ClientSocket objects in a
00621    * server. Having more Infos than a server can have means something
00622    * has gone wrong somewhere, i.e. the server has more Infos than it
00623    * has actual clients. That means the server is feeding us an invalid
00624    * state. So, bail out! This server is broken. */
00625   if (!NetworkClientInfo::CanAllocateItem()) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00626 
00627   /* We don't have this client_id yet, find an empty client_id, and put the data there */
00628   ci = new NetworkClientInfo(client_id);
00629   ci->client_playas = playas;
00630   if (client_id == _network_own_client_id) this->SetInfo(ci);
00631 
00632   strecpy(ci->client_name, name, lastof(ci->client_name));
00633 
00634   SetWindowDirty(WC_CLIENT_LIST, 0);
00635 
00636   return NETWORK_RECV_STATUS_OKAY;
00637 }
00638 
00639 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR(Packet *p)
00640 {
00641   static const StringID network_error_strings[] = {
00642     STR_NETWORK_ERROR_LOSTCONNECTION,    // NETWORK_ERROR_GENERAL
00643     STR_NETWORK_ERROR_LOSTCONNECTION,    // NETWORK_ERROR_DESYNC
00644     STR_NETWORK_ERROR_LOSTCONNECTION,    // NETWORK_ERROR_SAVEGAME_FAILED
00645     STR_NETWORK_ERROR_LOSTCONNECTION,    // NETWORK_ERROR_CONNECTION_LOST
00646     STR_NETWORK_ERROR_LOSTCONNECTION,    // NETWORK_ERROR_ILLEGAL_PACKET
00647     STR_NETWORK_ERROR_LOSTCONNECTION,    // NETWORK_ERROR_NEWGRF_MISMATCH
00648     STR_NETWORK_ERROR_SERVER_ERROR,      // NETWORK_ERROR_NOT_AUTHORIZED
00649     STR_NETWORK_ERROR_SERVER_ERROR,      // NETWORK_ERROR_NOT_EXPECTED
00650     STR_NETWORK_ERROR_WRONG_REVISION,    // NETWORK_ERROR_WRONG_REVISION
00651     STR_NETWORK_ERROR_LOSTCONNECTION,    // NETWORK_ERROR_NAME_IN_USE
00652     STR_NETWORK_ERROR_WRONG_PASSWORD,    // NETWORK_ERROR_WRONG_PASSWORD
00653     STR_NETWORK_ERROR_SERVER_ERROR,      // NETWORK_ERROR_COMPANY_MISMATCH
00654     STR_NETWORK_ERROR_KICKED,            // NETWORK_ERROR_KICKED
00655     STR_NETWORK_ERROR_CHEATER,           // NETWORK_ERROR_CHEATER
00656     STR_NETWORK_ERROR_SERVER_FULL,       // NETWORK_ERROR_FULL
00657     STR_NETWORK_ERROR_TOO_MANY_COMMANDS, // NETWORK_ERROR_TOO_MANY_COMMANDS
00658     STR_NETWORK_ERROR_TIMEOUT_PASSWORD,  // NETWORK_ERROR_TIMEOUT_PASSWORD
00659     STR_NETWORK_ERROR_TIMEOUT_COMPUTER,  // NETWORK_ERROR_TIMEOUT_COMPUTER
00660     STR_NETWORK_ERROR_TIMEOUT_MAP,       // NETWORK_ERROR_TIMEOUT_MAP
00661     STR_NETWORK_ERROR_TIMEOUT_JOIN,      // NETWORK_ERROR_TIMEOUT_JOIN
00662   };
00663   assert_compile(lengthof(network_error_strings) == NETWORK_ERROR_END);
00664 
00665   NetworkErrorCode error = (NetworkErrorCode)p->Recv_uint8();
00666 
00667   StringID err = STR_NETWORK_ERROR_LOSTCONNECTION;
00668   if (error < (ptrdiff_t)lengthof(network_error_strings)) err = network_error_strings[error];
00669 
00670   ShowErrorMessage(err, INVALID_STRING_ID, WL_CRITICAL);
00671 
00672   DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
00673 
00674   return NETWORK_RECV_STATUS_SERVER_ERROR;
00675 }
00676 
00677 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHECK_NEWGRFS(Packet *p)
00678 {
00679   if (this->status != STATUS_JOIN) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00680 
00681   uint grf_count = p->Recv_uint8();
00682   NetworkRecvStatus ret = NETWORK_RECV_STATUS_OKAY;
00683 
00684   /* Check all GRFs */
00685   for (; grf_count > 0; grf_count--) {
00686     GRFIdentifier c;
00687     this->ReceiveGRFIdentifier(p, &c);
00688 
00689     /* Check whether we know this GRF */
00690     const GRFConfig *f = FindGRFConfig(c.grfid, FGCM_EXACT, c.md5sum);
00691     if (f == NULL) {
00692       /* We do not know this GRF, bail out of initialization */
00693       char buf[sizeof(c.md5sum) * 2 + 1];
00694       md5sumToString(buf, lastof(buf), c.md5sum);
00695       DEBUG(grf, 0, "NewGRF %08X not found; checksum %s", BSWAP32(c.grfid), buf);
00696       ret = NETWORK_RECV_STATUS_NEWGRF_MISMATCH;
00697     }
00698   }
00699 
00700   if (ret == NETWORK_RECV_STATUS_OKAY) {
00701     /* Start receiving the map */
00702     return SendNewGRFsOk();
00703   }
00704 
00705   /* NewGRF mismatch, bail out */
00706   ShowErrorMessage(STR_NETWORK_ERROR_NEWGRF_MISMATCH, INVALID_STRING_ID, WL_CRITICAL);
00707   return ret;
00708 }
00709 
00710 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_NEED_GAME_PASSWORD(Packet *p)
00711 {
00712   if (this->status < STATUS_JOIN || this->status >= STATUS_AUTH_GAME) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00713   this->status = STATUS_AUTH_GAME;
00714 
00715   const char *password = _network_join_server_password;
00716   if (!StrEmpty(password)) {
00717     return SendGamePassword(password);
00718   }
00719 
00720   ShowNetworkNeedPassword(NETWORK_GAME_PASSWORD);
00721 
00722   return NETWORK_RECV_STATUS_OKAY;
00723 }
00724 
00725 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_NEED_COMPANY_PASSWORD(Packet *p)
00726 {
00727   if (this->status < STATUS_JOIN || this->status >= STATUS_AUTH_COMPANY) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00728   this->status = STATUS_AUTH_COMPANY;
00729 
00730   _password_game_seed = p->Recv_uint32();
00731   p->Recv_string(_password_server_id, sizeof(_password_server_id));
00732   if (this->HasClientQuit()) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00733 
00734   const char *password = _network_join_company_password;
00735   if (!StrEmpty(password)) {
00736     return SendCompanyPassword(password);
00737   }
00738 
00739   ShowNetworkNeedPassword(NETWORK_COMPANY_PASSWORD);
00740 
00741   return NETWORK_RECV_STATUS_OKAY;
00742 }
00743 
00744 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_WELCOME(Packet *p)
00745 {
00746   if (this->status < STATUS_JOIN || this->status >= STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00747   this->status = STATUS_AUTHORIZED;
00748 
00749   _network_own_client_id = (ClientID)p->Recv_uint32();
00750 
00751   /* Initialize the password hash salting variables, even if they were previously. */
00752   _password_game_seed = p->Recv_uint32();
00753   p->Recv_string(_password_server_id, sizeof(_password_server_id));
00754 
00755   /* Start receiving the map */
00756   return SendGetMap();
00757 }
00758 
00759 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_WAIT(Packet *p)
00760 {
00761   /* We set the internal wait state when requesting the map. */
00762   if (this->status != STATUS_MAP_WAIT) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00763 
00764   /* But... only now we set the join status to waiting, instead of requesting. */
00765   _network_join_status = NETWORK_JOIN_STATUS_WAITING;
00766   _network_join_waiting = p->Recv_uint8();
00767   SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
00768 
00769   return NETWORK_RECV_STATUS_OKAY;
00770 }
00771 
00772 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_BEGIN(Packet *p)
00773 {
00774   if (this->status < STATUS_AUTHORIZED || this->status >= STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00775   this->status = STATUS_MAP;
00776 
00777   if (this->savegame != NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00778 
00779   this->savegame = new PacketReader();
00780 
00781   _frame_counter = _frame_counter_server = _frame_counter_max = p->Recv_uint32();
00782 
00783   _network_join_bytes = 0;
00784   _network_join_bytes_total = 0;
00785 
00786   _network_join_status = NETWORK_JOIN_STATUS_DOWNLOADING;
00787   SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
00788 
00789   return NETWORK_RECV_STATUS_OKAY;
00790 }
00791 
00792 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_SIZE(Packet *p)
00793 {
00794   if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00795   if (this->savegame == NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00796 
00797   _network_join_bytes_total = p->Recv_uint32();
00798   SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
00799 
00800   return NETWORK_RECV_STATUS_OKAY;
00801 }
00802 
00803 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DATA(Packet *p)
00804 {
00805   if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00806   if (this->savegame == NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00807 
00808   /* We are still receiving data, put it to the file */
00809   this->savegame->AddPacket(p);
00810 
00811   _network_join_bytes = (uint32)this->savegame->written_bytes;
00812   SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
00813 
00814   return NETWORK_RECV_STATUS_OKAY;
00815 }
00816 
00817 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DONE(Packet *p)
00818 {
00819   if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00820   if (this->savegame == NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00821 
00822   _network_join_status = NETWORK_JOIN_STATUS_PROCESSING;
00823   SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
00824 
00825   /*
00826    * Make sure everything is set for reading.
00827    *
00828    * We need the local copy and reset this->savegame because when
00829    * loading fails the network gets reset upon loading the intro
00830    * game, which would cause us to free this->savegame twice.
00831    */
00832   LoadFilter *lf = this->savegame;
00833   this->savegame = NULL;
00834   lf->Reset();
00835 
00836   /* The map is done downloading, load it */
00837   ClearErrorMessages();
00838   bool load_success = SafeLoad(NULL, SL_LOAD, GM_NORMAL, NO_DIRECTORY, lf);
00839 
00840   /* Long savegame loads shouldn't affect the lag calculation! */
00841   this->last_packet = _realtime_tick;
00842 
00843   if (!load_success) {
00844     DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
00845     ShowErrorMessage(STR_NETWORK_ERROR_SAVEGAMEERROR, INVALID_STRING_ID, WL_CRITICAL);
00846     return NETWORK_RECV_STATUS_SAVEGAME;
00847   }
00848   /* If the savegame has successfully loaded, ALL windows have been removed,
00849    * only toolbar/statusbar and gamefield are visible */
00850 
00851   /* Say we received the map and loaded it correctly! */
00852   SendMapOk();
00853 
00854   /* New company/spectator (invalid company) or company we want to join is not active
00855    * Switch local company to spectator and await the server's judgement */
00856   if (_network_join_as == COMPANY_NEW_COMPANY || !Company::IsValidID(_network_join_as)) {
00857     SetLocalCompany(COMPANY_SPECTATOR);
00858 
00859     if (_network_join_as != COMPANY_SPECTATOR) {
00860       /* We have arrived and ready to start playing; send a command to make a new company;
00861        * the server will give us a client-id and let us in */
00862       _network_join_status = NETWORK_JOIN_STATUS_REGISTERING;
00863       ShowJoinStatusWindow();
00864       NetworkSendCommand(0, 0, 0, CMD_COMPANY_CTRL, NULL, NULL, _local_company);
00865     }
00866   } else {
00867     /* take control over an existing company */
00868     SetLocalCompany(_network_join_as);
00869     Company *c = Company::Get(_network_join_as);
00870     if (c->location_of_HQ != INVALID_TILE) ScrollMainWindowToTile(c->location_of_HQ, true);
00871   }
00872 
00873   return NETWORK_RECV_STATUS_OKAY;
00874 }
00875 
00876 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_FRAME(Packet *p)
00877 {
00878   if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00879 
00880   _frame_counter_server = p->Recv_uint32();
00881   _frame_counter_max = p->Recv_uint32();
00882 #ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
00883   /* Test if the server supports this option
00884    *  and if we are at the frame the server is */
00885   if (p->pos + 1 < p->size) {
00886     _sync_frame = _frame_counter_server;
00887     _sync_seed_1 = p->Recv_uint32();
00888 #ifdef NETWORK_SEND_DOUBLE_SEED
00889     _sync_seed_2 = p->Recv_uint32();
00890 #endif
00891   }
00892 #endif
00893   /* Receive the token. */
00894   if (p->pos != p->size) this->token = p->Recv_uint8();
00895 
00896   DEBUG(net, 5, "Received FRAME %d", _frame_counter_server);
00897 
00898   /* Let the server know that we received this frame correctly
00899    *  We do this only once per day, to save some bandwidth ;) */
00900   if (!_network_first_time && last_ack_frame < _frame_counter) {
00901     last_ack_frame = _frame_counter + DAY_TICKS;
00902     DEBUG(net, 4, "Sent ACK at %d", _frame_counter);
00903     SendAck();
00904   }
00905 
00906   return NETWORK_RECV_STATUS_OKAY;
00907 }
00908 
00909 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_SYNC(Packet *p)
00910 {
00911   if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00912 
00913   _sync_frame = p->Recv_uint32();
00914   _sync_seed_1 = p->Recv_uint32();
00915 #ifdef NETWORK_SEND_DOUBLE_SEED
00916   _sync_seed_2 = p->Recv_uint32();
00917 #endif
00918 
00919   return NETWORK_RECV_STATUS_OKAY;
00920 }
00921 
00922 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_COMMAND(Packet *p)
00923 {
00924   if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00925 
00926   CommandPacket cp;
00927   const char *err = this->ReceiveCommand(p, &cp);
00928   cp.frame    = p->Recv_uint32();
00929   cp.my_cmd   = p->Recv_bool();
00930 
00931   if (err != NULL) {
00932     IConsolePrintF(CC_ERROR, "WARNING: %s from server, dropping...", err);
00933     return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00934   }
00935 
00936   this->incoming_queue.Append(&cp);
00937 
00938   return NETWORK_RECV_STATUS_OKAY;
00939 }
00940 
00941 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHAT(Packet *p)
00942 {
00943   if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00944 
00945   char name[NETWORK_NAME_LENGTH], msg[NETWORK_CHAT_LENGTH];
00946   const NetworkClientInfo *ci = NULL, *ci_to;
00947 
00948   NetworkAction action = (NetworkAction)p->Recv_uint8();
00949   ClientID client_id = (ClientID)p->Recv_uint32();
00950   bool self_send = p->Recv_bool();
00951   p->Recv_string(msg, NETWORK_CHAT_LENGTH);
00952   int64 data = p->Recv_uint64();
00953 
00954   ci_to = NetworkClientInfo::GetByClientID(client_id);
00955   if (ci_to == NULL) return NETWORK_RECV_STATUS_OKAY;
00956 
00957   /* Did we initiate the action locally? */
00958   if (self_send) {
00959     switch (action) {
00960       case NETWORK_ACTION_CHAT_CLIENT:
00961         /* For speaking to client we need the client-name */
00962         snprintf(name, sizeof(name), "%s", ci_to->client_name);
00963         ci = NetworkClientInfo::GetByClientID(_network_own_client_id);
00964         break;
00965 
00966       /* For speaking to company or giving money, we need the company-name */
00967       case NETWORK_ACTION_GIVE_MONEY:
00968         if (!Company::IsValidID(ci_to->client_playas)) return NETWORK_RECV_STATUS_OKAY;
00969         /* FALL THROUGH */
00970       case NETWORK_ACTION_CHAT_COMPANY: {
00971         StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
00972         SetDParam(0, ci_to->client_playas);
00973 
00974         GetString(name, str, lastof(name));
00975         ci = NetworkClientInfo::GetByClientID(_network_own_client_id);
00976         break;
00977       }
00978 
00979       default: return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00980     }
00981   } else {
00982     /* Display message from somebody else */
00983     snprintf(name, sizeof(name), "%s", ci_to->client_name);
00984     ci = ci_to;
00985   }
00986 
00987   if (ci != NULL) {
00988     NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), self_send, name, msg, data);
00989   }
00990   return NETWORK_RECV_STATUS_OKAY;
00991 }
00992 
00993 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR_QUIT(Packet *p)
00994 {
00995   if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00996 
00997   ClientID client_id = (ClientID)p->Recv_uint32();
00998 
00999   NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
01000   if (ci != NULL) {
01001     NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, NULL, GetNetworkErrorMsg((NetworkErrorCode)p->Recv_uint8()));
01002     delete ci;
01003   }
01004 
01005   SetWindowDirty(WC_CLIENT_LIST, 0);
01006 
01007   return NETWORK_RECV_STATUS_OKAY;
01008 }
01009 
01010 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_QUIT(Packet *p)
01011 {
01012   if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
01013 
01014   ClientID client_id = (ClientID)p->Recv_uint32();
01015 
01016   NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
01017   if (ci != NULL) {
01018     NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, NULL, STR_NETWORK_MESSAGE_CLIENT_LEAVING);
01019     delete ci;
01020   } else {
01021     DEBUG(net, 0, "Unknown client (%d) is leaving the game", client_id);
01022   }
01023 
01024   SetWindowDirty(WC_CLIENT_LIST, 0);
01025 
01026   /* If we come here it means we could not locate the client.. strange :s */
01027   return NETWORK_RECV_STATUS_OKAY;
01028 }
01029 
01030 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_JOIN(Packet *p)
01031 {
01032   if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
01033 
01034   ClientID client_id = (ClientID)p->Recv_uint32();
01035 
01036   NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
01037   if (ci != NULL) {
01038     NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, ci->client_name);
01039   }
01040 
01041   SetWindowDirty(WC_CLIENT_LIST, 0);
01042 
01043   return NETWORK_RECV_STATUS_OKAY;
01044 }
01045 
01046 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_SHUTDOWN(Packet *p)
01047 {
01048   /* Only when we're trying to join we really
01049    * care about the server shutting down. */
01050   if (this->status >= STATUS_JOIN) {
01051     ShowErrorMessage(STR_NETWORK_MESSAGE_SERVER_SHUTDOWN, INVALID_STRING_ID, WL_CRITICAL);
01052   }
01053 
01054   return NETWORK_RECV_STATUS_SERVER_ERROR;
01055 }
01056 
01057 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_NEWGAME(Packet *p)
01058 {
01059   /* Only when we're trying to join we really
01060    * care about the server shutting down. */
01061   if (this->status >= STATUS_JOIN) {
01062     /* To trottle the reconnects a bit, every clients waits its
01063      * Client ID modulo 16. This way reconnects should be spread
01064      * out a bit. */
01065     _network_reconnect = _network_own_client_id % 16;
01066     ShowErrorMessage(STR_NETWORK_MESSAGE_SERVER_REBOOT, INVALID_STRING_ID, WL_CRITICAL);
01067   }
01068 
01069   return NETWORK_RECV_STATUS_SERVER_ERROR;
01070 }
01071 
01072 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_RCON(Packet *p)
01073 {
01074   if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
01075 
01076   TextColour colour_code = (TextColour)p->Recv_uint16();
01077   if (!IsValidConsoleColour(colour_code)) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
01078 
01079   char rcon_out[NETWORK_RCONCOMMAND_LENGTH];
01080   p->Recv_string(rcon_out, sizeof(rcon_out));
01081 
01082   IConsolePrint(colour_code, rcon_out);
01083 
01084   return NETWORK_RECV_STATUS_OKAY;
01085 }
01086 
01087 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MOVE(Packet *p)
01088 {
01089   if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
01090 
01091   /* Nothing more in this packet... */
01092   ClientID client_id   = (ClientID)p->Recv_uint32();
01093   CompanyID company_id = (CompanyID)p->Recv_uint8();
01094 
01095   if (client_id == 0) {
01096     /* definitely an invalid client id, debug message and do nothing. */
01097     DEBUG(net, 0, "[move] received invalid client index = 0");
01098     return NETWORK_RECV_STATUS_MALFORMED_PACKET;
01099   }
01100 
01101   const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
01102   /* Just make sure we do not try to use a client_index that does not exist */
01103   if (ci == NULL) return NETWORK_RECV_STATUS_OKAY;
01104 
01105   /* if not valid player, force spectator, else check player exists */
01106   if (!Company::IsValidID(company_id)) company_id = COMPANY_SPECTATOR;
01107 
01108   if (client_id == _network_own_client_id) {
01109     SetLocalCompany(company_id);
01110     if (company_id != COMPANY_SPECTATOR) {
01111       Company *c = Company::Get(company_id);
01112       if (c->location_of_HQ != INVALID_TILE) ScrollMainWindowToTile(c->location_of_HQ, true);
01113     }
01114   }
01115 
01116   return NETWORK_RECV_STATUS_OKAY;
01117 }
01118 
01119 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CONFIG_UPDATE(Packet *p)
01120 {
01121   if (this->status < STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
01122 
01123   _network_server_max_companies = p->Recv_uint8();
01124   _network_server_max_spectators = p->Recv_uint8();
01125 
01126   return NETWORK_RECV_STATUS_OKAY;
01127 }
01128 
01129 NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_COMPANY_UPDATE(Packet *p)
01130 {
01131   if (this->status < STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
01132 
01133   _network_company_passworded = p->Recv_uint16();
01134   SetWindowClassesDirty(WC_COMPANY);
01135 
01136   return NETWORK_RECV_STATUS_OKAY;
01137 }
01138 
01142 void ClientNetworkGameSocketHandler::CheckConnection()
01143 {
01144   /* Only once we're authorized we can expect a steady stream of packets. */
01145   if (this->status < STATUS_AUTHORIZED) return;
01146 
01147   /* It might... sometimes occur that the realtime ticker overflows. */
01148   if (_realtime_tick < this->last_packet) this->last_packet = _realtime_tick;
01149 
01150   /* Lag is in milliseconds; 5 seconds are roughly twice the
01151    * server's "you're slow" threshold (1 game day). */
01152   uint lag = (_realtime_tick - this->last_packet) / 1000;
01153   if (lag < 5) return;
01154 
01155   /* 20 seconds are (way) more than 4 game days after which
01156    * the server will forcefully disconnect you. */
01157   if (lag > 20) {
01158     this->NetworkGameSocketHandler::CloseConnection();
01159     ShowErrorMessage(STR_NETWORK_ERROR_LOSTCONNECTION, INVALID_STRING_ID, WL_CRITICAL);
01160     return;
01161   }
01162 
01163   /* Prevent showing the lag message every tick; just update it when needed. */
01164   static uint last_lag = 0;
01165   if (last_lag == lag) return;
01166 
01167   last_lag = lag;
01168   SetDParam(0, lag);
01169   ShowErrorMessage(STR_NETWORK_ERROR_CLIENT_GUI_LOST_CONNECTION_CAPTION, STR_NETWORK_ERROR_CLIENT_GUI_LOST_CONNECTION, WL_INFO);
01170 }
01171 
01172 
01174 void NetworkClient_Connected()
01175 {
01176   /* Set the frame-counter to 0 so nothing happens till we are ready */
01177   _frame_counter = 0;
01178   _frame_counter_server = 0;
01179   last_ack_frame = 0;
01180   /* Request the game-info */
01181   MyClient::SendJoin();
01182 }
01183 
01189 void NetworkClientSendRcon(const char *password, const char *command)
01190 {
01191   MyClient::SendRCon(password, command);
01192 }
01193 
01200 void NetworkClientRequestMove(CompanyID company_id, const char *pass)
01201 {
01202   MyClient::SendMove(company_id, pass);
01203 }
01204 
01209 void NetworkClientsToSpectators(CompanyID cid)
01210 {
01211   Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
01212   /* If our company is changing owner, go to spectators */
01213   if (cid == _local_company) SetLocalCompany(COMPANY_SPECTATOR);
01214 
01215   NetworkClientInfo *ci;
01216   FOR_ALL_CLIENT_INFOS(ci) {
01217     if (ci->client_playas != cid) continue;
01218     NetworkTextMessage(NETWORK_ACTION_COMPANY_SPECTATOR, CC_DEFAULT, false, ci->client_name);
01219     ci->client_playas = COMPANY_SPECTATOR;
01220   }
01221 
01222   cur_company.Restore();
01223 }
01224 
01228 void NetworkUpdateClientName()
01229 {
01230   NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(_network_own_client_id);
01231 
01232   if (ci == NULL) return;
01233 
01234   /* Don't change the name if it is the same as the old name */
01235   if (strcmp(ci->client_name, _settings_client.network.client_name) != 0) {
01236     if (!_network_server) {
01237       MyClient::SendSetName(_settings_client.network.client_name);
01238     } else {
01239       if (NetworkFindName(_settings_client.network.client_name)) {
01240         NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, _settings_client.network.client_name);
01241         strecpy(ci->client_name, _settings_client.network.client_name, lastof(ci->client_name));
01242         NetworkUpdateClientInfo(CLIENT_ID_SERVER);
01243       }
01244     }
01245   }
01246 }
01247 
01256 void NetworkClientSendChat(NetworkAction action, DestType type, int dest, const char *msg, int64 data)
01257 {
01258   MyClient::SendChat(action, type, dest, msg, data);
01259 }
01260 
01265 void NetworkClientSetCompanyPassword(const char *password)
01266 {
01267   MyClient::SendSetPassword(password);
01268 }
01269 
01275 bool NetworkClientPreferTeamChat(const NetworkClientInfo *cio)
01276 {
01277   /* Only companies actually playing can speak to team. Eg spectators cannot */
01278   if (!_settings_client.gui.prefer_teamchat || !Company::IsValidID(cio->client_playas)) return false;
01279 
01280   const NetworkClientInfo *ci;
01281   FOR_ALL_CLIENT_INFOS(ci) {
01282     if (ci->client_playas == cio->client_playas && ci != cio) return true;
01283   }
01284 
01285   return false;
01286 }
01287 
01292 bool NetworkMaxCompaniesReached()
01293 {
01294   return Company::GetNumItems() >= (_network_server ? _settings_client.network.max_companies : _network_server_max_companies);
01295 }
01296 
01301 bool NetworkMaxSpectatorsReached()
01302 {
01303   return NetworkSpectatorCount() >= (_network_server ? _settings_client.network.max_spectators : _network_server_max_spectators);
01304 }
01305 
01306 #endif /* ENABLE_NETWORK */