network_client.cpp

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

Generated on Sun Jan 9 16:01:56 2011 for OpenTTD by  doxygen 1.6.1