network_client.cpp

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

Generated on Fri Dec 31 17:15:33 2010 for OpenTTD by  doxygen 1.6.1