network_client.cpp

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