network_client.cpp

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