network_client.cpp

Go to the documentation of this file.
00001 /* $Id: network_client.cpp 23795 2012-01-13 21:54:59Z rubidium $ */
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 "../debug.h"
00016 #include "network_gui.h"
00017 #include "../saveload/saveload.h"
00018 #include "../saveload/saveload_filter.h"
00019 #include "../command_func.h"
00020 #include "../console_func.h"
00021 #include "../strings_func.h"
00022 #include "../window_func.h"
00023 #include "../company_func.h"
00024 #include "../company_base.h"
00025 #include "../company_gui.h"
00026 #include "../core/random_func.hpp"
00027 #include "../date_func.h"
00028 #include "../gfx_func.h"
00029 #include "../gui.h"
00030 #include "../rev.h"
00031 #include "network.h"
00032 #include "network_base.h"
00033 #include "network_client.h"
00034 #include "../core/backup_type.hpp"
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, 0);
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 
00283 static uint32 last_ack_frame;
00284 
00286 static uint32 _password_game_seed;
00288 static char _password_server_id[NETWORK_SERVER_ID_LENGTH];
00289 
00291 static uint8 _network_server_max_companies;
00293 static uint8 _network_server_max_spectators;
00294 
00296 CompanyID _network_join_as;
00297 
00299 const char *_network_join_server_password = NULL;
00301 const char *_network_join_company_password = NULL;
00302 
00304 assert_compile(NETWORK_SERVER_ID_LENGTH == 16 * 2 + 1);
00305 
00306 /***********
00307  * Sending functions
00308  *   DEF_CLIENT_SEND_COMMAND has no parameters
00309  ************/
00310 
00311 NetworkRecvStatus ClientNetworkGameSocketHandler::SendCompanyInformationQuery()
00312 {
00313   my_client->status = STATUS_COMPANY_INFO;
00314   _network_join_status = NETWORK_JOIN_STATUS_GETTING_COMPANY_INFO;
00315   SetWindowDirty(WC_NETWORK_STATUS_WINDOW, 0);
00316 
00317   Packet *p = new Packet(PACKET_CLIENT_COMPANY_INFO);
00318   my_client->SendPacket(p);
00319   return NETWORK_RECV_STATUS_OKAY;
00320 }
00321 
00322 NetworkRecvStatus ClientNetworkGameSocketHandler::SendJoin()
00323 {
00324   my_client->status = STATUS_JOIN;
00325   _network_join_status = NETWORK_JOIN_STATUS_AUTHORIZING;
00326   SetWindowDirty(WC_NETWORK_STATUS_WINDOW, 0);
00327 
00328   Packet *p = new Packet(PACKET_CLIENT_JOIN);
00329   p->Send_string(_openttd_revision);
00330   p->Send_string(_settings_client.network.client_name); // Client name
00331   p->Send_uint8 (_network_join_as);     // PlayAs
00332   p->Send_uint8 (NETLANG_ANY);          // Language
00333   my_client->SendPacket(p);
00334   return NETWORK_RECV_STATUS_OKAY;
00335 }
00336 
00337 NetworkRecvStatus ClientNetworkGameSocketHandler::SendNewGRFsOk()
00338 {
00339   Packet *p = new Packet(PACKET_CLIENT_NEWGRFS_CHECKED);
00340   my_client->SendPacket(p);
00341   return NETWORK_RECV_STATUS_OKAY;
00342 }
00343 
00344 NetworkRecvStatus ClientNetworkGameSocketHandler::SendGamePassword(const char *password)
00345 {
00346   Packet *p = new Packet(PACKET_CLIENT_GAME_PASSWORD);
00347   p->Send_string(password);
00348   my_client->SendPacket(p);
00349   return NETWORK_RECV_STATUS_OKAY;
00350 }
00351 
00352 NetworkRecvStatus ClientNetworkGameSocketHandler::SendCompanyPassword(const char *password)
00353 {
00354   Packet *p = new Packet(PACKET_CLIENT_COMPANY_PASSWORD);
00355   p->Send_string(GenerateCompanyPasswordHash(password, _password_server_id, _password_game_seed));
00356   my_client->SendPacket(p);
00357   return NETWORK_RECV_STATUS_OKAY;
00358 }
00359 
00360 NetworkRecvStatus ClientNetworkGameSocketHandler::SendGetMap()
00361 {
00362   my_client->status = STATUS_MAP_WAIT;
00363 
00364   Packet *p = new Packet(PACKET_CLIENT_GETMAP);
00365   /* Send the OpenTTD version to the server, let it validate it too.
00366    * But only do it for stable releases because of those we are sure
00367    * that everybody has the same NewGRF version. For trunk and the
00368    * branches we make tarballs of the OpenTTDs compiled from tarball
00369    * will have the lower bits set to 0. As such they would become
00370    * incompatible, which we would like to prevent by this. */
00371   if (HasBit(_openttd_newgrf_version, 19)) p->Send_uint32(_openttd_newgrf_version);
00372   my_client->SendPacket(p);
00373   return NETWORK_RECV_STATUS_OKAY;
00374 }
00375 
00376 NetworkRecvStatus ClientNetworkGameSocketHandler::SendMapOk()
00377 {
00378   my_client->status = STATUS_ACTIVE;
00379 
00380   Packet *p = new Packet(PACKET_CLIENT_MAP_OK);
00381   my_client->SendPacket(p);
00382   return NETWORK_RECV_STATUS_OKAY;
00383 }
00384 
00385 NetworkRecvStatus ClientNetworkGameSocketHandler::SendAck()
00386 {
00387   Packet *p = new Packet(PACKET_CLIENT_ACK);
00388 
00389   p->Send_uint32(_frame_counter);
00390   p->Send_uint8 (my_client->token);
00391   my_client->SendPacket(p);
00392   return NETWORK_RECV_STATUS_OKAY;
00393 }
00394 
00395 /* Send a command packet to the server */
00396 NetworkRecvStatus ClientNetworkGameSocketHandler::SendCommand(const CommandPacket *cp)
00397 {
00398   Packet *p = new Packet(PACKET_CLIENT_COMMAND);
00399   my_client->NetworkGameSocketHandler::SendCommand(p, cp);
00400 
00401   my_client->SendPacket(p);
00402   return NETWORK_RECV_STATUS_OKAY;
00403 }
00404 
00405 /* Send a chat-packet over the network */
00406 NetworkRecvStatus ClientNetworkGameSocketHandler::SendChat(NetworkAction action, DestType type, int dest, const char *msg, int64 data)
00407 {
00408   Packet *p = new Packet(PACKET_CLIENT_CHAT);
00409 
00410   p->Send_uint8 (action);
00411   p->Send_uint8 (type);
00412   p->Send_uint32(dest);
00413   p->Send_string(msg);
00414   p->Send_uint64(data);
00415 
00416   my_client->SendPacket(p);
00417   return NETWORK_RECV_STATUS_OKAY;
00418 }
00419 
00420 /* Send an error-packet over the network */
00421 NetworkRecvStatus ClientNetworkGameSocketHandler::SendError(NetworkErrorCode errorno)
00422 {
00423   Packet *p = new Packet(PACKET_CLIENT_ERROR);
00424 
00425   p->Send_uint8(errorno);
00426   my_client->SendPacket(p);
00427   return NETWORK_RECV_STATUS_OKAY;
00428 }
00429 
00430 NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetPassword(const char *password)
00431 {
00432   Packet *p = new Packet(PACKET_CLIENT_SET_PASSWORD);
00433 
00434   p->Send_string(GenerateCompanyPasswordHash(password, _password_server_id, _password_game_seed));
00435   my_client->SendPacket(p);
00436   return NETWORK_RECV_STATUS_OKAY;
00437 }
00438 
00439 NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetName(const char *name)
00440 {
00441   Packet *p = new Packet(PACKET_CLIENT_SET_NAME);
00442 
00443   p->Send_string(name);
00444   my_client->SendPacket(p);
00445   return NETWORK_RECV_STATUS_OKAY;
00446 }
00447 
00448 NetworkRecvStatus ClientNetworkGameSocketHandler::SendQuit()
00449 {
00450   Packet *p = new Packet(PACKET_CLIENT_QUIT);
00451 
00452   my_client->SendPacket(p);
00453   return NETWORK_RECV_STATUS_OKAY;
00454 }
00455 
00456 NetworkRecvStatus ClientNetworkGameSocketHandler::SendRCon(const char *pass, const char *command)
00457 {
00458   Packet *p = new Packet(PACKET_CLIENT_RCON);
00459   p->Send_string(pass);
00460   p->Send_string(command);
00461   my_client->SendPacket(p);
00462   return NETWORK_RECV_STATUS_OKAY;
00463 }
00464 
00465 NetworkRecvStatus ClientNetworkGameSocketHandler::SendMove(CompanyID company, const char *password)
00466 {
00467   Packet *p = new Packet(PACKET_CLIENT_MOVE);
00468   p->Send_uint8(company);
00469   p->Send_string(GenerateCompanyPasswordHash(password, _password_server_id, _password_game_seed));
00470   my_client->SendPacket(p);
00471   return NETWORK_RECV_STATUS_OKAY;
00472 }
00473 
00478 bool ClientNetworkGameSocketHandler::IsConnected()
00479 {
00480   return my_client != NULL && my_client->status == STATUS_ACTIVE;
00481 }
00482 
00483 
00484 /***********
00485  * Receiving functions
00486  *   DEF_CLIENT_RECEIVE_COMMAND has parameter: Packet *p
00487  ************/
00488 
00489 extern bool SafeLoad(const char *filename, int mode, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL);
00490 extern StringID _switch_mode_errorstr;
00491 
00492 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_FULL)
00493 {
00494   /* We try to join a server which is full */
00495   _switch_mode_errorstr = STR_NETWORK_ERROR_SERVER_FULL;
00496   DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
00497 
00498   return NETWORK_RECV_STATUS_SERVER_FULL;
00499 }
00500 
00501 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_BANNED)
00502 {
00503   /* We try to join a server where we are banned */
00504   _switch_mode_errorstr = STR_NETWORK_ERROR_SERVER_BANNED;
00505   DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
00506 
00507   return NETWORK_RECV_STATUS_SERVER_BANNED;
00508 }
00509 
00510 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_COMPANY_INFO)
00511 {
00512   if (this->status != STATUS_COMPANY_INFO) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00513 
00514   byte company_info_version = p->Recv_uint8();
00515 
00516   if (!this->HasClientQuit() && company_info_version == NETWORK_COMPANY_INFO_VERSION) {
00517     /* We have received all data... (there are no more packets coming) */
00518     if (!p->Recv_bool()) return NETWORK_RECV_STATUS_CLOSE_QUERY;
00519 
00520     CompanyID current = (Owner)p->Recv_uint8();
00521     if (current >= MAX_COMPANIES) return NETWORK_RECV_STATUS_CLOSE_QUERY;
00522 
00523     NetworkCompanyInfo *company_info = GetLobbyCompanyInfo(current);
00524     if (company_info == NULL) return NETWORK_RECV_STATUS_CLOSE_QUERY;
00525 
00526     p->Recv_string(company_info->company_name, sizeof(company_info->company_name));
00527     company_info->inaugurated_year = p->Recv_uint32();
00528     company_info->company_value    = p->Recv_uint64();
00529     company_info->money            = p->Recv_uint64();
00530     company_info->income           = p->Recv_uint64();
00531     company_info->performance      = p->Recv_uint16();
00532     company_info->use_password     = p->Recv_bool();
00533     for (uint i = 0; i < NETWORK_VEH_END; i++) {
00534       company_info->num_vehicle[i] = p->Recv_uint16();
00535     }
00536     for (uint i = 0; i < NETWORK_VEH_END; i++) {
00537       company_info->num_station[i] = p->Recv_uint16();
00538     }
00539     company_info->ai               = p->Recv_bool();
00540 
00541     p->Recv_string(company_info->clients, sizeof(company_info->clients));
00542 
00543     SetWindowDirty(WC_NETWORK_WINDOW, 0);
00544 
00545     return NETWORK_RECV_STATUS_OKAY;
00546   }
00547 
00548   return NETWORK_RECV_STATUS_CLOSE_QUERY;
00549 }
00550 
00551 /* This packet contains info about the client (playas and name)
00552  *  as client we save this in NetworkClientInfo, linked via 'client_id'
00553  *  which is always an unique number on a server. */
00554 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_CLIENT_INFO)
00555 {
00556   NetworkClientInfo *ci;
00557   ClientID client_id = (ClientID)p->Recv_uint32();
00558   CompanyID playas = (CompanyID)p->Recv_uint8();
00559   char name[NETWORK_NAME_LENGTH];
00560 
00561   p->Recv_string(name, sizeof(name));
00562 
00563   if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00564   if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
00565 
00566   ci = NetworkClientInfo::GetByClientID(client_id);
00567   if (ci != NULL) {
00568     if (playas == ci->client_playas && strcmp(name, ci->client_name) != 0) {
00569       /* Client name changed, display the change */
00570       NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, name);
00571     } else if (playas != ci->client_playas) {
00572       /* The client changed from client-player..
00573        * Do not display that for now */
00574     }
00575 
00576     /* Make sure we're in the company the server tells us to be in,
00577      * for the rare case that we get moved while joining. */
00578     if (client_id == _network_own_client_id) SetLocalCompany(!Company::IsValidID(playas) ? COMPANY_SPECTATOR : playas);
00579 
00580     ci->client_playas = playas;
00581     strecpy(ci->client_name, name, lastof(ci->client_name));
00582 
00583     SetWindowDirty(WC_CLIENT_LIST, 0);
00584 
00585     return NETWORK_RECV_STATUS_OKAY;
00586   }
00587 
00588   /* There are at most as many ClientInfo as ClientSocket objects in a
00589    * server. Having more Infos than a server can have means something
00590    * has gone wrong somewhere, i.e. the server has more Infos than it
00591    * has actual clients. That means the server is feeding us an invalid
00592    * state. So, bail out! This server is broken. */
00593   if (!NetworkClientInfo::CanAllocateItem()) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00594 
00595   /* We don't have this client_id yet, find an empty client_id, and put the data there */
00596   ci = new NetworkClientInfo(client_id);
00597   ci->client_playas = playas;
00598   if (client_id == _network_own_client_id) this->SetInfo(ci);
00599 
00600   strecpy(ci->client_name, name, lastof(ci->client_name));
00601 
00602   SetWindowDirty(WC_CLIENT_LIST, 0);
00603 
00604   return NETWORK_RECV_STATUS_OKAY;
00605 }
00606 
00607 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_ERROR)
00608 {
00609   NetworkErrorCode error = (NetworkErrorCode)p->Recv_uint8();
00610 
00611   switch (error) {
00612     /* We made an error in the protocol, and our connection is closed.... */
00613     case NETWORK_ERROR_NOT_AUTHORIZED:
00614     case NETWORK_ERROR_NOT_EXPECTED:
00615     case NETWORK_ERROR_COMPANY_MISMATCH:
00616       _switch_mode_errorstr = STR_NETWORK_ERROR_SERVER_ERROR;
00617       break;
00618     case NETWORK_ERROR_FULL:
00619       _switch_mode_errorstr = STR_NETWORK_ERROR_SERVER_FULL;
00620       break;
00621     case NETWORK_ERROR_WRONG_REVISION:
00622       _switch_mode_errorstr = STR_NETWORK_ERROR_WRONG_REVISION;
00623       break;
00624     case NETWORK_ERROR_WRONG_PASSWORD:
00625       _switch_mode_errorstr = STR_NETWORK_ERROR_WRONG_PASSWORD;
00626       break;
00627     case NETWORK_ERROR_KICKED:
00628       _switch_mode_errorstr = STR_NETWORK_ERROR_KICKED;
00629       break;
00630     case NETWORK_ERROR_CHEATER:
00631       _switch_mode_errorstr = STR_NETWORK_ERROR_CHEATER;
00632       break;
00633     case NETWORK_ERROR_TOO_MANY_COMMANDS:
00634       _switch_mode_errorstr = STR_NETWORK_ERROR_TOO_MANY_COMMANDS;
00635       break;
00636     case NETWORK_ERROR_TIMEOUT_PASSWORD:
00637       ShowErrorMessage(STR_NETWORK_ERROR_TIMEOUT_PASSWORD, INVALID_STRING_ID, WL_CRITICAL);
00638       break;
00639     case NETWORK_ERROR_TIMEOUT_COMPUTER:
00640       ShowErrorMessage(STR_NETWORK_ERROR_TIMEOUT_COMPUTER, INVALID_STRING_ID, WL_CRITICAL);
00641       break;
00642     default:
00643       _switch_mode_errorstr = STR_NETWORK_ERROR_LOSTCONNECTION;
00644   }
00645 
00646   DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
00647 
00648   return NETWORK_RECV_STATUS_SERVER_ERROR;
00649 }
00650 
00651 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_CHECK_NEWGRFS)
00652 {
00653   if (this->status != STATUS_JOIN) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00654 
00655   uint grf_count = p->Recv_uint8();
00656   NetworkRecvStatus ret = NETWORK_RECV_STATUS_OKAY;
00657 
00658   /* Check all GRFs */
00659   for (; grf_count > 0; grf_count--) {
00660     GRFIdentifier c;
00661     this->ReceiveGRFIdentifier(p, &c);
00662 
00663     /* Check whether we know this GRF */
00664     const GRFConfig *f = FindGRFConfig(c.grfid, FGCM_EXACT, c.md5sum);
00665     if (f == NULL) {
00666       /* We do not know this GRF, bail out of initialization */
00667       char buf[sizeof(c.md5sum) * 2 + 1];
00668       md5sumToString(buf, lastof(buf), c.md5sum);
00669       DEBUG(grf, 0, "NewGRF %08X not found; checksum %s", BSWAP32(c.grfid), buf);
00670       ret = NETWORK_RECV_STATUS_NEWGRF_MISMATCH;
00671     }
00672   }
00673 
00674   if (ret == NETWORK_RECV_STATUS_OKAY) {
00675     /* Start receiving the map */
00676     return SendNewGRFsOk();
00677   }
00678 
00679   /* NewGRF mismatch, bail out */
00680   _switch_mode_errorstr = STR_NETWORK_ERROR_NEWGRF_MISMATCH;
00681   return ret;
00682 }
00683 
00684 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_NEED_GAME_PASSWORD)
00685 {
00686   if (this->status < STATUS_JOIN || this->status >= STATUS_AUTH_GAME) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00687   this->status = STATUS_AUTH_GAME;
00688 
00689   const char *password = _network_join_server_password;
00690   if (!StrEmpty(password)) {
00691     return SendGamePassword(password);
00692   }
00693 
00694   ShowNetworkNeedPassword(NETWORK_GAME_PASSWORD);
00695 
00696   return NETWORK_RECV_STATUS_OKAY;
00697 }
00698 
00699 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_NEED_COMPANY_PASSWORD)
00700 {
00701   if (this->status < STATUS_JOIN || this->status >= STATUS_AUTH_COMPANY) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00702   this->status = STATUS_AUTH_COMPANY;
00703 
00704   _password_game_seed = p->Recv_uint32();
00705   p->Recv_string(_password_server_id, sizeof(_password_server_id));
00706   if (this->HasClientQuit()) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00707 
00708   const char *password = _network_join_company_password;
00709   if (!StrEmpty(password)) {
00710     return SendCompanyPassword(password);
00711   }
00712 
00713   ShowNetworkNeedPassword(NETWORK_COMPANY_PASSWORD);
00714 
00715   return NETWORK_RECV_STATUS_OKAY;
00716 }
00717 
00718 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_WELCOME)
00719 {
00720   if (this->status < STATUS_JOIN || this->status >= STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00721   this->status = STATUS_AUTHORIZED;
00722 
00723   _network_own_client_id = (ClientID)p->Recv_uint32();
00724 
00725   /* Initialize the password hash salting variables, even if they were previously. */
00726   _password_game_seed = p->Recv_uint32();
00727   p->Recv_string(_password_server_id, sizeof(_password_server_id));
00728 
00729   /* Start receiving the map */
00730   return SendGetMap();
00731 }
00732 
00733 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_WAIT)
00734 {
00735   /* We set the internal wait state when requesting the map. */
00736   if (this->status != STATUS_MAP_WAIT) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00737 
00738   /* But... only now we set the join status to waiting, instead of requesting. */
00739   _network_join_status = NETWORK_JOIN_STATUS_WAITING;
00740   _network_join_waiting = p->Recv_uint8();
00741   SetWindowDirty(WC_NETWORK_STATUS_WINDOW, 0);
00742 
00743   return NETWORK_RECV_STATUS_OKAY;
00744 }
00745 
00746 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_MAP_BEGIN)
00747 {
00748   if (this->status < STATUS_AUTHORIZED || this->status >= STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00749   this->status = STATUS_MAP;
00750 
00751   if (this->savegame != NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00752 
00753   this->savegame = new PacketReader();
00754 
00755   _frame_counter = _frame_counter_server = _frame_counter_max = p->Recv_uint32();
00756 
00757   _network_join_bytes = 0;
00758   _network_join_bytes_total = 0;
00759 
00760   _network_join_status = NETWORK_JOIN_STATUS_DOWNLOADING;
00761   SetWindowDirty(WC_NETWORK_STATUS_WINDOW, 0);
00762 
00763   return NETWORK_RECV_STATUS_OKAY;
00764 }
00765 
00766 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_MAP_SIZE)
00767 {
00768   if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00769   if (this->savegame == NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00770 
00771   _network_join_bytes_total = p->Recv_uint32();
00772   SetWindowDirty(WC_NETWORK_STATUS_WINDOW, 0);
00773 
00774   return NETWORK_RECV_STATUS_OKAY;
00775 }
00776 
00777 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_MAP_DATA)
00778 {
00779   if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00780   if (this->savegame == NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00781 
00782   /* We are still receiving data, put it to the file */
00783   this->savegame->AddPacket(p);
00784 
00785   _network_join_bytes = (uint32)this->savegame->written_bytes;
00786   SetWindowDirty(WC_NETWORK_STATUS_WINDOW, 0);
00787 
00788   return NETWORK_RECV_STATUS_OKAY;
00789 }
00790 
00791 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_MAP_DONE)
00792 {
00793   if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00794   if (this->savegame == NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00795 
00796   _network_join_status = NETWORK_JOIN_STATUS_PROCESSING;
00797   SetWindowDirty(WC_NETWORK_STATUS_WINDOW, 0);
00798 
00799   /*
00800    * Make sure everything is set for reading.
00801    *
00802    * We need the local copy and reset this->savegame because when
00803    * loading fails the network gets reset upon loading the intro
00804    * game, which would cause us to free this->savegame twice.
00805    */
00806   LoadFilter *lf = this->savegame;
00807   this->savegame = NULL;
00808   lf->Reset();
00809 
00810   /* The map is done downloading, load it */
00811   bool load_success = SafeLoad(NULL, SL_LOAD, GM_NORMAL, NO_DIRECTORY, lf);
00812 
00813   /* Long savegame loads shouldn't affect the lag calculation! */
00814   this->last_packet = _realtime_tick;
00815 
00816   if (!load_success) {
00817     DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
00818     _switch_mode_errorstr = STR_NETWORK_ERROR_SAVEGAMEERROR;
00819     return NETWORK_RECV_STATUS_SAVEGAME;
00820   }
00821   /* If the savegame has successfully loaded, ALL windows have been removed,
00822    * only toolbar/statusbar and gamefield are visible */
00823 
00824   /* Say we received the map and loaded it correctly! */
00825   SendMapOk();
00826 
00827   /* New company/spectator (invalid company) or company we want to join is not active
00828    * Switch local company to spectator and await the server's judgement */
00829   if (_network_join_as == COMPANY_NEW_COMPANY || !Company::IsValidID(_network_join_as)) {
00830     SetLocalCompany(COMPANY_SPECTATOR);
00831 
00832     if (_network_join_as != COMPANY_SPECTATOR) {
00833       /* We have arrived and ready to start playing; send a command to make a new company;
00834        * the server will give us a client-id and let us in */
00835       _network_join_status = NETWORK_JOIN_STATUS_REGISTERING;
00836       ShowJoinStatusWindow();
00837       NetworkSendCommand(0, 0, 0, CMD_COMPANY_CTRL, NULL, NULL, _local_company);
00838     }
00839   } else {
00840     /* take control over an existing company */
00841     SetLocalCompany(_network_join_as);
00842   }
00843 
00844   return NETWORK_RECV_STATUS_OKAY;
00845 }
00846 
00847 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_FRAME)
00848 {
00849   if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00850 
00851   _frame_counter_server = p->Recv_uint32();
00852   _frame_counter_max = p->Recv_uint32();
00853 #ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
00854   /* Test if the server supports this option
00855    *  and if we are at the frame the server is */
00856   if (p->pos + 1 < p->size) {
00857     _sync_frame = _frame_counter_server;
00858     _sync_seed_1 = p->Recv_uint32();
00859 #ifdef NETWORK_SEND_DOUBLE_SEED
00860     _sync_seed_2 = p->Recv_uint32();
00861 #endif
00862   }
00863 #endif
00864   /* Receive the token. */
00865   if (p->pos != p->size) this->token = p->Recv_uint8();
00866 
00867   DEBUG(net, 5, "Received FRAME %d", _frame_counter_server);
00868 
00869   /* Let the server know that we received this frame correctly
00870    *  We do this only once per day, to save some bandwidth ;) */
00871   if (!_network_first_time && last_ack_frame < _frame_counter) {
00872     last_ack_frame = _frame_counter + DAY_TICKS;
00873     DEBUG(net, 4, "Sent ACK at %d", _frame_counter);
00874     SendAck();
00875   }
00876 
00877   return NETWORK_RECV_STATUS_OKAY;
00878 }
00879 
00880 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_SYNC)
00881 {
00882   if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00883 
00884   _sync_frame = p->Recv_uint32();
00885   _sync_seed_1 = p->Recv_uint32();
00886 #ifdef NETWORK_SEND_DOUBLE_SEED
00887   _sync_seed_2 = p->Recv_uint32();
00888 #endif
00889 
00890   return NETWORK_RECV_STATUS_OKAY;
00891 }
00892 
00893 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_COMMAND)
00894 {
00895   if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00896 
00897   CommandPacket cp;
00898   const char *err = this->ReceiveCommand(p, &cp);
00899   cp.frame    = p->Recv_uint32();
00900   cp.my_cmd   = p->Recv_bool();
00901 
00902   if (err != NULL) {
00903     IConsolePrintF(CC_ERROR, "WARNING: %s from server, dropping...", err);
00904     return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00905   }
00906 
00907   this->incoming_queue.Append(&cp);
00908 
00909   return NETWORK_RECV_STATUS_OKAY;
00910 }
00911 
00912 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_CHAT)
00913 {
00914   if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00915 
00916   char name[NETWORK_NAME_LENGTH], msg[NETWORK_CHAT_LENGTH];
00917   const NetworkClientInfo *ci = NULL, *ci_to;
00918 
00919   NetworkAction action = (NetworkAction)p->Recv_uint8();
00920   ClientID client_id = (ClientID)p->Recv_uint32();
00921   bool self_send = p->Recv_bool();
00922   p->Recv_string(msg, NETWORK_CHAT_LENGTH);
00923   int64 data = p->Recv_uint64();
00924 
00925   ci_to = NetworkClientInfo::GetByClientID(client_id);
00926   if (ci_to == NULL) return NETWORK_RECV_STATUS_OKAY;
00927 
00928   /* Did we initiate the action locally? */
00929   if (self_send) {
00930     switch (action) {
00931       case NETWORK_ACTION_CHAT_CLIENT:
00932         /* For speaking to client we need the client-name */
00933         snprintf(name, sizeof(name), "%s", ci_to->client_name);
00934         ci = NetworkClientInfo::GetByClientID(_network_own_client_id);
00935         break;
00936 
00937       /* For speaking to company or giving money, we need the company-name */
00938       case NETWORK_ACTION_GIVE_MONEY:
00939         if (!Company::IsValidID(ci_to->client_playas)) return NETWORK_RECV_STATUS_OKAY;
00940         /* FALL THROUGH */
00941       case NETWORK_ACTION_CHAT_COMPANY: {
00942         StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
00943         SetDParam(0, ci_to->client_playas);
00944 
00945         GetString(name, str, lastof(name));
00946         ci = NetworkClientInfo::GetByClientID(_network_own_client_id);
00947         break;
00948       }
00949 
00950       default: return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00951     }
00952   } else {
00953     /* Display message from somebody else */
00954     snprintf(name, sizeof(name), "%s", ci_to->client_name);
00955     ci = ci_to;
00956   }
00957 
00958   if (ci != NULL) {
00959     NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), self_send, name, msg, data);
00960   }
00961   return NETWORK_RECV_STATUS_OKAY;
00962 }
00963 
00964 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_ERROR_QUIT)
00965 {
00966   if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00967 
00968   ClientID client_id = (ClientID)p->Recv_uint32();
00969 
00970   NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
00971   if (ci != NULL) {
00972     NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, NULL, GetNetworkErrorMsg((NetworkErrorCode)p->Recv_uint8()));
00973     delete ci;
00974   }
00975 
00976   SetWindowDirty(WC_CLIENT_LIST, 0);
00977 
00978   return NETWORK_RECV_STATUS_OKAY;
00979 }
00980 
00981 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_QUIT)
00982 {
00983   if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00984 
00985   ClientID client_id = (ClientID)p->Recv_uint32();
00986 
00987   NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
00988   if (ci != NULL) {
00989     NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, NULL, STR_NETWORK_MESSAGE_CLIENT_LEAVING);
00990     delete ci;
00991   } else {
00992     DEBUG(net, 0, "Unknown client (%d) is leaving the game", client_id);
00993   }
00994 
00995   SetWindowDirty(WC_CLIENT_LIST, 0);
00996 
00997   /* If we come here it means we could not locate the client.. strange :s */
00998   return NETWORK_RECV_STATUS_OKAY;
00999 }
01000 
01001 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_JOIN)
01002 {
01003   if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
01004 
01005   ClientID client_id = (ClientID)p->Recv_uint32();
01006 
01007   NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
01008   if (ci != NULL) {
01009     NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, ci->client_name);
01010   }
01011 
01012   SetWindowDirty(WC_CLIENT_LIST, 0);
01013 
01014   return NETWORK_RECV_STATUS_OKAY;
01015 }
01016 
01017 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_SHUTDOWN)
01018 {
01019   /* Only when we're trying to join we really
01020    * care about the server shutting down. */
01021   if (this->status >= STATUS_JOIN) {
01022     _switch_mode_errorstr = STR_NETWORK_MESSAGE_SERVER_SHUTDOWN;
01023   }
01024 
01025   return NETWORK_RECV_STATUS_SERVER_ERROR;
01026 }
01027 
01028 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_NEWGAME)
01029 {
01030   /* Only when we're trying to join we really
01031    * care about the server shutting down. */
01032   if (this->status >= STATUS_JOIN) {
01033     /* To trottle the reconnects a bit, every clients waits its
01034      * Client ID modulo 16. This way reconnects should be spread
01035      * out a bit. */
01036     _network_reconnect = _network_own_client_id % 16;
01037     _switch_mode_errorstr = STR_NETWORK_MESSAGE_SERVER_REBOOT;
01038   }
01039 
01040   return NETWORK_RECV_STATUS_SERVER_ERROR;
01041 }
01042 
01043 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_RCON)
01044 {
01045   if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
01046 
01047   TextColour colour_code = (TextColour)p->Recv_uint16();
01048   if (!IsValidConsoleColour(colour_code)) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
01049 
01050   char rcon_out[NETWORK_RCONCOMMAND_LENGTH];
01051   p->Recv_string(rcon_out, sizeof(rcon_out));
01052 
01053   IConsolePrint(colour_code, rcon_out);
01054 
01055   return NETWORK_RECV_STATUS_OKAY;
01056 }
01057 
01058 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_MOVE)
01059 {
01060   if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
01061 
01062   /* Nothing more in this packet... */
01063   ClientID client_id   = (ClientID)p->Recv_uint32();
01064   CompanyID company_id = (CompanyID)p->Recv_uint8();
01065 
01066   if (client_id == 0) {
01067     /* definitely an invalid client id, debug message and do nothing. */
01068     DEBUG(net, 0, "[move] received invalid client index = 0");
01069     return NETWORK_RECV_STATUS_MALFORMED_PACKET;
01070   }
01071 
01072   const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
01073   /* Just make sure we do not try to use a client_index that does not exist */
01074   if (ci == NULL) return NETWORK_RECV_STATUS_OKAY;
01075 
01076   /* if not valid player, force spectator, else check player exists */
01077   if (!Company::IsValidID(company_id)) company_id = COMPANY_SPECTATOR;
01078 
01079   if (client_id == _network_own_client_id) {
01080     SetLocalCompany(company_id);
01081   }
01082 
01083   return NETWORK_RECV_STATUS_OKAY;
01084 }
01085 
01086 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_CONFIG_UPDATE)
01087 {
01088   if (this->status < STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
01089 
01090   _network_server_max_companies = p->Recv_uint8();
01091   _network_server_max_spectators = p->Recv_uint8();
01092 
01093   return NETWORK_RECV_STATUS_OKAY;
01094 }
01095 
01096 DEF_GAME_RECEIVE_COMMAND(Client, PACKET_SERVER_COMPANY_UPDATE)
01097 {
01098   if (this->status < STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
01099 
01100   _network_company_passworded = p->Recv_uint16();
01101   SetWindowClassesDirty(WC_COMPANY);
01102 
01103   return NETWORK_RECV_STATUS_OKAY;
01104 }
01105 
01109 void ClientNetworkGameSocketHandler::CheckConnection()
01110 {
01111   /* Only once we're authorized we can expect a steady stream of packets. */
01112   if (this->status < STATUS_AUTHORIZED) return;
01113 
01114   /* It might... sometimes occur that the realtime ticker overflows. */
01115   if (_realtime_tick < this->last_packet) this->last_packet = _realtime_tick;
01116 
01117   /* Lag is in milliseconds; 5 seconds are roughly twice the
01118    * server's "you're slow" threshold (1 game day). */
01119   uint lag = (_realtime_tick - this->last_packet) / 1000;
01120   if (lag < 5) return;
01121 
01122   /* 20 seconds are (way) more than 4 game days after which
01123    * the server will forcefully disconnect you. */
01124   if (lag > 20) {
01125     this->NetworkGameSocketHandler::CloseConnection();
01126     _switch_mode_errorstr = STR_NETWORK_ERROR_LOSTCONNECTION;
01127     return;
01128   }
01129 
01130   /* Prevent showing the lag message every tick; just update it when needed. */
01131   static uint last_lag = 0;
01132   if (last_lag == lag) return;
01133 
01134   last_lag = lag;
01135   SetDParam(0, lag);
01136   ShowErrorMessage(STR_NETWORK_ERROR_CLIENT_GUI_LOST_CONNECTION_CAPTION, STR_NETWORK_ERROR_CLIENT_GUI_LOST_CONNECTION, WL_INFO);
01137 }
01138 
01139 
01140 /* Is called after a client is connected to the server */
01141 void NetworkClient_Connected()
01142 {
01143   /* Set the frame-counter to 0 so nothing happens till we are ready */
01144   _frame_counter = 0;
01145   _frame_counter_server = 0;
01146   last_ack_frame = 0;
01147   /* Request the game-info */
01148   MyClient::SendJoin();
01149 }
01150 
01151 void NetworkClientSendRcon(const char *password, const char *command)
01152 {
01153   MyClient::SendRCon(password, command);
01154 }
01155 
01162 void NetworkClientRequestMove(CompanyID company_id, const char *pass)
01163 {
01164   MyClient::SendMove(company_id, pass);
01165 }
01166 
01167 void NetworkClientsToSpectators(CompanyID cid)
01168 {
01169   Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
01170   /* If our company is changing owner, go to spectators */
01171   if (cid == _local_company) SetLocalCompany(COMPANY_SPECTATOR);
01172 
01173   NetworkClientInfo *ci;
01174   FOR_ALL_CLIENT_INFOS(ci) {
01175     if (ci->client_playas != cid) continue;
01176     NetworkTextMessage(NETWORK_ACTION_COMPANY_SPECTATOR, CC_DEFAULT, false, ci->client_name);
01177     ci->client_playas = COMPANY_SPECTATOR;
01178   }
01179 
01180   cur_company.Restore();
01181 }
01182 
01183 void NetworkUpdateClientName()
01184 {
01185   NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(_network_own_client_id);
01186 
01187   if (ci == NULL) return;
01188 
01189   /* Don't change the name if it is the same as the old name */
01190   if (strcmp(ci->client_name, _settings_client.network.client_name) != 0) {
01191     if (!_network_server) {
01192       MyClient::SendSetName(_settings_client.network.client_name);
01193     } else {
01194       if (NetworkFindName(_settings_client.network.client_name)) {
01195         NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, _settings_client.network.client_name);
01196         strecpy(ci->client_name, _settings_client.network.client_name, lastof(ci->client_name));
01197         NetworkUpdateClientInfo(CLIENT_ID_SERVER);
01198       }
01199     }
01200   }
01201 }
01202 
01203 void NetworkClientSendChat(NetworkAction action, DestType type, int dest, const char *msg, int64 data)
01204 {
01205   MyClient::SendChat(action, type, dest, msg, data);
01206 }
01207 
01212 void NetworkClientSetCompanyPassword(const char *password)
01213 {
01214   MyClient::SendSetPassword(password);
01215 }
01216 
01222 bool NetworkClientPreferTeamChat(const NetworkClientInfo *cio)
01223 {
01224   /* Only companies actually playing can speak to team. Eg spectators cannot */
01225   if (!_settings_client.gui.prefer_teamchat || !Company::IsValidID(cio->client_playas)) return false;
01226 
01227   const NetworkClientInfo *ci;
01228   FOR_ALL_CLIENT_INFOS(ci) {
01229     if (ci->client_playas == cio->client_playas && ci != cio) return true;
01230   }
01231 
01232   return false;
01233 }
01234 
01239 bool NetworkMaxCompaniesReached()
01240 {
01241   return Company::GetNumItems() >= (_network_server ? _settings_client.network.max_companies : _network_server_max_companies);
01242 }
01243 
01248 bool NetworkMaxSpectatorsReached()
01249 {
01250   return NetworkSpectatorCount() >= (_network_server ? _settings_client.network.max_spectators : _network_server_max_spectators);
01251 }
01252 
01253 #endif /* ENABLE_NETWORK */