network_client.cpp

Go to the documentation of this file.
00001 /* $Id: network_client.cpp 19132 2010-02-14 16:31:35Z alberth $ */
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 "../command_func.h"
00020 #include "../console_func.h"
00021 #include "../fileio_func.h"
00022 #include "../3rdparty/md5/md5.h"
00023 #include "../strings_func.h"
00024 #include "../window_func.h"
00025 #include "../company_func.h"
00026 #include "../company_base.h"
00027 #include "../company_gui.h"
00028 #include "../rev.h"
00029 #include "network.h"
00030 #include "network_base.h"
00031 
00032 #include "table/strings.h"
00033 
00034 /* This file handles all the client-commands */
00035 
00036 
00037 /* So we don't make too much typos ;) */
00038 #define MY_CLIENT NetworkClientSocket::Get(0)
00039 
00040 static uint32 last_ack_frame;
00041 
00043 static uint32 _password_game_seed;
00045 static char _password_server_id[NETWORK_SERVER_ID_LENGTH];
00046 
00048 static uint8 _network_server_max_companies;
00050 static uint8 _network_server_max_spectators;
00051 
00053 CompanyID _network_join_as;
00054 
00056 const char *_network_join_server_password = NULL;
00058 const char *_network_join_company_password = NULL;
00059 
00061 assert_compile(NETWORK_SERVER_ID_LENGTH == 16 * 2 + 1);
00062 
00068 static const char *GenerateCompanyPasswordHash(const char *password)
00069 {
00070   if (StrEmpty(password)) return password;
00071 
00072   char salted_password[NETWORK_SERVER_ID_LENGTH];
00073 
00074   memset(salted_password, 0, sizeof(salted_password));
00075   snprintf(salted_password, sizeof(salted_password), "%s", password);
00076   /* Add the game seed and the server's ID as the salt. */
00077   for (uint i = 0; i < NETWORK_SERVER_ID_LENGTH - 1; i++) salted_password[i] ^= _password_server_id[i] ^ (_password_game_seed >> i);
00078 
00079   Md5 checksum;
00080   uint8 digest[16];
00081   static char hashed_password[NETWORK_SERVER_ID_LENGTH];
00082 
00083   /* Generate the MD5 hash */
00084   checksum.Append((const uint8*)salted_password, sizeof(salted_password) - 1);
00085   checksum.Finish(digest);
00086 
00087   for (int di = 0; di < 16; di++) sprintf(hashed_password + di * 2, "%02x", digest[di]);
00088   hashed_password[lengthof(hashed_password) - 1] = '\0';
00089 
00090   return hashed_password;
00091 }
00092 
00096 void HashCurrentCompanyPassword(const char *password)
00097 {
00098   _password_game_seed = _settings_game.game_creation.generation_seed;
00099   strecpy(_password_server_id, _settings_client.network.network_id, lastof(_password_server_id));
00100 
00101   const char *new_pw = GenerateCompanyPasswordHash(password);
00102   strecpy(_network_company_states[_local_company].password, new_pw, lastof(_network_company_states[_local_company].password));
00103 
00104   if (_network_server) {
00105     NetworkServerUpdateCompanyPassworded(_local_company, !StrEmpty(_network_company_states[_local_company].password));
00106   }
00107 }
00108 
00109 
00110 /***********
00111  * Sending functions
00112  *   DEF_CLIENT_SEND_COMMAND has no parameters
00113  ************/
00114 
00115 DEF_CLIENT_SEND_COMMAND(PACKET_CLIENT_COMPANY_INFO)
00116 {
00117   /*
00118    * Packet: CLIENT_COMPANY_INFO
00119    * Function: Request company-info (in detail)
00120    * Data:
00121    *    <none>
00122    */
00123   Packet *p;
00124   _network_join_status = NETWORK_JOIN_STATUS_GETTING_COMPANY_INFO;
00125   SetWindowDirty(WC_NETWORK_STATUS_WINDOW, 0);
00126 
00127   p = new Packet(PACKET_CLIENT_COMPANY_INFO);
00128   MY_CLIENT->Send_Packet(p);
00129   return NETWORK_RECV_STATUS_OKAY;
00130 }
00131 
00132 DEF_CLIENT_SEND_COMMAND(PACKET_CLIENT_JOIN)
00133 {
00134   /*
00135    * Packet: CLIENT_JOIN
00136    * Function: Try to join the server
00137    * Data:
00138    *    String: OpenTTD Revision (norev000 if no revision)
00139    *    String: Client Name (max NETWORK_NAME_LENGTH)
00140    *    uint8:  Play as Company id (1..MAX_COMPANIES)
00141    *    uint8:  Language ID
00142    */
00143 
00144   Packet *p;
00145   _network_join_status = NETWORK_JOIN_STATUS_AUTHORIZING;
00146   SetWindowDirty(WC_NETWORK_STATUS_WINDOW, 0);
00147 
00148   p = new Packet(PACKET_CLIENT_JOIN);
00149   p->Send_string(_openttd_revision);
00150   p->Send_string(_settings_client.network.client_name); // Client name
00151   p->Send_uint8 (_network_join_as);     // PlayAs
00152   p->Send_uint8 (NETLANG_ANY);          // Language
00153   MY_CLIENT->Send_Packet(p);
00154   return NETWORK_RECV_STATUS_OKAY;
00155 }
00156 
00157 DEF_CLIENT_SEND_COMMAND(PACKET_CLIENT_NEWGRFS_CHECKED)
00158 {
00159   /*
00160    * Packet: CLIENT_NEWGRFS_CHECKED
00161    * Function: Tell the server that we have the required GRFs
00162    * Data:
00163    */
00164 
00165   Packet *p = new Packet(PACKET_CLIENT_NEWGRFS_CHECKED);
00166   MY_CLIENT->Send_Packet(p);
00167   return NETWORK_RECV_STATUS_OKAY;
00168 }
00169 
00170 DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_PASSWORD)(NetworkPasswordType type, const char *password)
00171 {
00172   /*
00173    * Packet: CLIENT_PASSWORD
00174    * Function: Send a password to the server to authorize
00175    * Data:
00176    *    uint8:  NetworkPasswordType
00177    *    String: Password
00178    */
00179   Packet *p = new Packet(PACKET_CLIENT_PASSWORD);
00180   p->Send_uint8 (type);
00181   p->Send_string(type == NETWORK_GAME_PASSWORD ? password : GenerateCompanyPasswordHash(password));
00182   MY_CLIENT->Send_Packet(p);
00183   return NETWORK_RECV_STATUS_OKAY;
00184 }
00185 
00186 DEF_CLIENT_SEND_COMMAND(PACKET_CLIENT_GETMAP)
00187 {
00188   /*
00189    * Packet: CLIENT_GETMAP
00190    * Function: Request the map from the server
00191    * Data:
00192    *    <none>
00193    */
00194 
00195   Packet *p = new Packet(PACKET_CLIENT_GETMAP);
00196   /* Send the OpenTTD version to the server, let it validate it too.
00197    * But only do it for stable releases because of those we are sure
00198    * that everybody has the same NewGRF version. For trunk and the
00199    * branches we make tarballs of the OpenTTDs compiled from tarball
00200    * will have the lower bits set to 0. As such they would become
00201    * incompatible, which we would like to prevent by this. */
00202   if (HasBit(_openttd_newgrf_version, 19)) p->Send_uint32(_openttd_newgrf_version);
00203   MY_CLIENT->Send_Packet(p);
00204   return NETWORK_RECV_STATUS_OKAY;
00205 }
00206 
00207 DEF_CLIENT_SEND_COMMAND(PACKET_CLIENT_MAP_OK)
00208 {
00209   /*
00210    * Packet: CLIENT_MAP_OK
00211    * Function: Tell the server that we are done receiving/loading the map
00212    * Data:
00213    *    <none>
00214    */
00215 
00216   Packet *p = new Packet(PACKET_CLIENT_MAP_OK);
00217   MY_CLIENT->Send_Packet(p);
00218   return NETWORK_RECV_STATUS_OKAY;
00219 }
00220 
00221 DEF_CLIENT_SEND_COMMAND(PACKET_CLIENT_ACK)
00222 {
00223   /*
00224    * Packet: CLIENT_ACK
00225    * Function: Tell the server we are done with this frame
00226    * Data:
00227    *    uint32: current FrameCounter of the client
00228    */
00229 
00230   Packet *p = new Packet(PACKET_CLIENT_ACK);
00231 
00232   p->Send_uint32(_frame_counter);
00233   MY_CLIENT->Send_Packet(p);
00234   return NETWORK_RECV_STATUS_OKAY;
00235 }
00236 
00237 /* Send a command packet to the server */
00238 DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_COMMAND)(const CommandPacket *cp)
00239 {
00240   /*
00241    * Packet: CLIENT_COMMAND
00242    * Function: Send a DoCommand to the Server
00243    * Data:
00244    *    uint8:  CompanyID (0..MAX_COMPANIES-1)
00245    *    uint32: CommandID (see command.h)
00246    *    uint32: P1 (free variables used in DoCommand)
00247    *    uint32: P2
00248    *    uint32: Tile
00249    *    string: text
00250    *    uint8:  CallBackID
00251    */
00252 
00253   Packet *p = new Packet(PACKET_CLIENT_COMMAND);
00254   MY_CLIENT->Send_Command(p, cp);
00255 
00256   MY_CLIENT->Send_Packet(p);
00257   return NETWORK_RECV_STATUS_OKAY;
00258 }
00259 
00260 /* Send a chat-packet over the network */
00261 DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_CHAT)(NetworkAction action, DestType type, int dest, const char *msg, int64 data)
00262 {
00263   /*
00264    * Packet: CLIENT_CHAT
00265    * Function: Send a chat-packet to the serve
00266    * Data:
00267    *    uint8:  ActionID (see network_data.h, NetworkAction)
00268    *    uint8:  Destination Type (see network_data.h, DestType);
00269    *    uint32: Destination CompanyID/Client-identifier
00270    *    String: Message (max NETWORK_CHAT_LENGTH)
00271    *    uint64: Some arbitrary number
00272    */
00273 
00274   Packet *p = new Packet(PACKET_CLIENT_CHAT);
00275 
00276   p->Send_uint8 (action);
00277   p->Send_uint8 (type);
00278   p->Send_uint32(dest);
00279   p->Send_string(msg);
00280   p->Send_uint64(data);
00281 
00282   MY_CLIENT->Send_Packet(p);
00283   return NETWORK_RECV_STATUS_OKAY;
00284 }
00285 
00286 /* Send an error-packet over the network */
00287 DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_ERROR)(NetworkErrorCode errorno)
00288 {
00289   /*
00290    * Packet: CLIENT_ERROR
00291    * Function: The client made an error and is quiting the game
00292    * Data:
00293    *    uint8:  ErrorID (see network_data.h, NetworkErrorCode)
00294    */
00295   Packet *p = new Packet(PACKET_CLIENT_ERROR);
00296 
00297   p->Send_uint8(errorno);
00298   MY_CLIENT->Send_Packet(p);
00299   return NETWORK_RECV_STATUS_OKAY;
00300 }
00301 
00302 DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_SET_PASSWORD)(const char *password)
00303 {
00304   /*
00305    * Packet: PACKET_CLIENT_SET_PASSWORD
00306    * Function: Set the password for the clients current company
00307    * Data:
00308    *    String: Password
00309    */
00310   Packet *p = new Packet(PACKET_CLIENT_SET_PASSWORD);
00311 
00312   p->Send_string(GenerateCompanyPasswordHash(password));
00313   MY_CLIENT->Send_Packet(p);
00314   return NETWORK_RECV_STATUS_OKAY;
00315 }
00316 
00317 DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_SET_NAME)(const char *name)
00318 {
00319   /*
00320    * Packet: PACKET_CLIENT_SET_NAME
00321    * Function: Gives the client a new name
00322    * Data:
00323    *    String: Name
00324    */
00325   Packet *p = new Packet(PACKET_CLIENT_SET_NAME);
00326 
00327   p->Send_string(name);
00328   MY_CLIENT->Send_Packet(p);
00329   return NETWORK_RECV_STATUS_OKAY;
00330 }
00331 
00332 /* Send an quit-packet over the network */
00333 DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_QUIT)()
00334 {
00335   /*
00336    * Packet: CLIENT_QUIT
00337    * Function: The client is quiting the game
00338    * Data:
00339    */
00340   Packet *p = new Packet(PACKET_CLIENT_QUIT);
00341 
00342   MY_CLIENT->Send_Packet(p);
00343   return NETWORK_RECV_STATUS_OKAY;
00344 }
00345 
00346 DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_RCON)(const char *pass, const char *command)
00347 {
00348   Packet *p = new Packet(PACKET_CLIENT_RCON);
00349   p->Send_string(pass);
00350   p->Send_string(command);
00351   MY_CLIENT->Send_Packet(p);
00352   return NETWORK_RECV_STATUS_OKAY;
00353 }
00354 
00355 DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_MOVE)(CompanyID company, const char *pass)
00356 {
00357   Packet *p = new Packet(PACKET_CLIENT_MOVE);
00358   p->Send_uint8(company);
00359   p->Send_string(GenerateCompanyPasswordHash(pass));
00360   MY_CLIENT->Send_Packet(p);
00361   return NETWORK_RECV_STATUS_OKAY;
00362 }
00363 
00364 
00365 /***********
00366  * Receiving functions
00367  *   DEF_CLIENT_RECEIVE_COMMAND has parameter: Packet *p
00368  ************/
00369 
00370 extern bool SafeSaveOrLoad(const char *filename, int mode, GameMode newgm, Subdirectory subdir);
00371 extern StringID _switch_mode_errorstr;
00372 
00373 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_FULL)
00374 {
00375   /* We try to join a server which is full */
00376   _switch_mode_errorstr = STR_NETWORK_ERROR_SERVER_FULL;
00377   DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
00378 
00379   return NETWORK_RECV_STATUS_SERVER_FULL;
00380 }
00381 
00382 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_BANNED)
00383 {
00384   /* We try to join a server where we are banned */
00385   _switch_mode_errorstr = STR_NETWORK_ERROR_SERVER_BANNED;
00386   DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
00387 
00388   return NETWORK_RECV_STATUS_SERVER_BANNED;
00389 }
00390 
00391 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_COMPANY_INFO)
00392 {
00393   byte company_info_version = p->Recv_uint8();
00394 
00395   if (!MY_CLIENT->HasClientQuit() && company_info_version == NETWORK_COMPANY_INFO_VERSION) {
00396     /* We have received all data... (there are no more packets coming) */
00397     if (!p->Recv_bool()) return NETWORK_RECV_STATUS_CLOSE_QUERY;
00398 
00399     CompanyID current = (Owner)p->Recv_uint8();
00400     if (current >= MAX_COMPANIES) return NETWORK_RECV_STATUS_CLOSE_QUERY;
00401 
00402     NetworkCompanyInfo *company_info = GetLobbyCompanyInfo(current);
00403     if (company_info == NULL) return NETWORK_RECV_STATUS_CLOSE_QUERY;
00404 
00405     p->Recv_string(company_info->company_name, sizeof(company_info->company_name));
00406     company_info->inaugurated_year = p->Recv_uint32();
00407     company_info->company_value    = p->Recv_uint64();
00408     company_info->money            = p->Recv_uint64();
00409     company_info->income           = p->Recv_uint64();
00410     company_info->performance      = p->Recv_uint16();
00411     company_info->use_password     = p->Recv_bool();
00412     for (int i = 0; i < NETWORK_VEHICLE_TYPES; i++)
00413       company_info->num_vehicle[i] = p->Recv_uint16();
00414     for (int i = 0; i < NETWORK_STATION_TYPES; i++)
00415       company_info->num_station[i] = p->Recv_uint16();
00416     company_info->ai               = p->Recv_bool();
00417 
00418     p->Recv_string(company_info->clients, sizeof(company_info->clients));
00419 
00420     SetWindowDirty(WC_NETWORK_WINDOW, 0);
00421 
00422     return NETWORK_RECV_STATUS_OKAY;
00423   }
00424 
00425   return NETWORK_RECV_STATUS_CLOSE_QUERY;
00426 }
00427 
00428 /* This packet contains info about the client (playas and name)
00429  *  as client we save this in NetworkClientInfo, linked via 'client_id'
00430  *  which is always an unique number on a server. */
00431 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_CLIENT_INFO)
00432 {
00433   NetworkClientInfo *ci;
00434   ClientID client_id = (ClientID)p->Recv_uint32();
00435   CompanyID playas = (CompanyID)p->Recv_uint8();
00436   char name[NETWORK_NAME_LENGTH];
00437 
00438   p->Recv_string(name, sizeof(name));
00439 
00440   if (MY_CLIENT->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
00441 
00442   ci = NetworkFindClientInfoFromClientID(client_id);
00443   if (ci != NULL) {
00444     if (playas == ci->client_playas && strcmp(name, ci->client_name) != 0) {
00445       /* Client name changed, display the change */
00446       NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, name);
00447     } else if (playas != ci->client_playas) {
00448       /* The client changed from client-player..
00449        * Do not display that for now */
00450     }
00451 
00452     ci->client_playas = playas;
00453     strecpy(ci->client_name, name, lastof(ci->client_name));
00454 
00455     SetWindowDirty(WC_CLIENT_LIST, 0);
00456 
00457     return NETWORK_RECV_STATUS_OKAY;
00458   }
00459 
00460   /* We don't have this client_id yet, find an empty client_id, and put the data there */
00461   ci = new NetworkClientInfo(client_id);
00462   ci->client_playas = playas;
00463   if (client_id == _network_own_client_id) MY_CLIENT->SetInfo(ci);
00464 
00465   strecpy(ci->client_name, name, lastof(ci->client_name));
00466 
00467   SetWindowDirty(WC_CLIENT_LIST, 0);
00468 
00469   return NETWORK_RECV_STATUS_OKAY;
00470 }
00471 
00472 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_ERROR)
00473 {
00474   NetworkErrorCode error = (NetworkErrorCode)p->Recv_uint8();
00475 
00476   switch (error) {
00477     /* We made an error in the protocol, and our connection is closed.... */
00478     case NETWORK_ERROR_NOT_AUTHORIZED:
00479     case NETWORK_ERROR_NOT_EXPECTED:
00480     case NETWORK_ERROR_COMPANY_MISMATCH:
00481       _switch_mode_errorstr = STR_NETWORK_ERROR_SERVER_ERROR;
00482       break;
00483     case NETWORK_ERROR_FULL:
00484       _switch_mode_errorstr = STR_NETWORK_ERROR_SERVER_FULL;
00485       break;
00486     case NETWORK_ERROR_WRONG_REVISION:
00487       _switch_mode_errorstr = STR_NETWORK_ERROR_WRONG_REVISION;
00488       break;
00489     case NETWORK_ERROR_WRONG_PASSWORD:
00490       _switch_mode_errorstr = STR_NETWORK_ERROR_WRONG_PASSWORD;
00491       break;
00492     case NETWORK_ERROR_KICKED:
00493       _switch_mode_errorstr = STR_NETWORK_ERROR_KICKED;
00494       break;
00495     case NETWORK_ERROR_CHEATER:
00496       _switch_mode_errorstr = STR_NETWORK_ERROR_CHEATER;
00497       break;
00498     default:
00499       _switch_mode_errorstr = STR_NETWORK_ERROR_LOSTCONNECTION;
00500   }
00501 
00502   DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
00503 
00504   return NETWORK_RECV_STATUS_SERVER_ERROR;
00505 }
00506 
00507 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_CHECK_NEWGRFS)
00508 {
00509   uint grf_count = p->Recv_uint8();
00510   NetworkRecvStatus ret = NETWORK_RECV_STATUS_OKAY;
00511 
00512   /* Check all GRFs */
00513   for (; grf_count > 0; grf_count--) {
00514     GRFConfig c;
00515     MY_CLIENT->Recv_GRFIdentifier(p, &c);
00516 
00517     /* Check whether we know this GRF */
00518     const GRFConfig *f = FindGRFConfig(c.grfid, c.md5sum);
00519     if (f == NULL) {
00520       /* We do not know this GRF, bail out of initialization */
00521       char buf[sizeof(c.md5sum) * 2 + 1];
00522       md5sumToString(buf, lastof(buf), c.md5sum);
00523       DEBUG(grf, 0, "NewGRF %08X not found; checksum %s", BSWAP32(c.grfid), buf);
00524       ret = NETWORK_RECV_STATUS_NEWGRF_MISMATCH;
00525     }
00526   }
00527 
00528   if (ret == NETWORK_RECV_STATUS_OKAY) {
00529     /* Start receiving the map */
00530     return SEND_COMMAND(PACKET_CLIENT_NEWGRFS_CHECKED)();
00531   }
00532 
00533   /* NewGRF mismatch, bail out */
00534   _switch_mode_errorstr = STR_NETWORK_ERROR_NEWGRF_MISMATCH;
00535   return ret;
00536 }
00537 
00538 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_NEED_PASSWORD)
00539 {
00540   NetworkPasswordType type = (NetworkPasswordType)p->Recv_uint8();
00541 
00542   const char *password = _network_join_server_password;
00543 
00544   switch (type) {
00545     case NETWORK_COMPANY_PASSWORD:
00546       /* Initialize the password hash salting variables. */
00547       _password_game_seed = p->Recv_uint32();
00548       p->Recv_string(_password_server_id, sizeof(_password_server_id));
00549       if (MY_CLIENT->HasClientQuit()) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00550       password = _network_join_company_password;
00551       /* FALL THROUGH */
00552     case NETWORK_GAME_PASSWORD:
00553       if (StrEmpty(password)) {
00554         ShowNetworkNeedPassword(type);
00555       } else {
00556         return SEND_COMMAND(PACKET_CLIENT_PASSWORD)(type, password);
00557       }
00558       return NETWORK_RECV_STATUS_OKAY;
00559 
00560     default: return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00561   }
00562 }
00563 
00564 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_WELCOME)
00565 {
00566   _network_own_client_id = (ClientID)p->Recv_uint32();
00567 
00568   /* Initialize the password hash salting variables, even if they were previously. */
00569   _password_game_seed = p->Recv_uint32();
00570   p->Recv_string(_password_server_id, sizeof(_password_server_id));
00571 
00572   /* Start receiving the map */
00573   return SEND_COMMAND(PACKET_CLIENT_GETMAP)();
00574 }
00575 
00576 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_WAIT)
00577 {
00578   _network_join_status = NETWORK_JOIN_STATUS_WAITING;
00579   _network_join_waiting = p->Recv_uint8();
00580   SetWindowDirty(WC_NETWORK_STATUS_WINDOW, 0);
00581 
00582   /* We are put on hold for receiving the map.. we need GUI for this ;) */
00583   DEBUG(net, 1, "The server is currently busy sending the map to someone else, please wait..." );
00584   DEBUG(net, 1, "There are %d clients in front of you", _network_join_waiting);
00585 
00586   return NETWORK_RECV_STATUS_OKAY;
00587 }
00588 
00589 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_MAP)
00590 {
00591   static FILE *file_pointer;
00592 
00593   byte maptype;
00594 
00595   maptype = p->Recv_uint8();
00596 
00597   if (MY_CLIENT->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
00598 
00599   /* First packet, init some stuff */
00600   if (maptype == MAP_PACKET_START) {
00601     file_pointer = FioFOpenFile("network_client.tmp", "wb", AUTOSAVE_DIR);
00602     if (file_pointer == NULL) {
00603       _switch_mode_errorstr = STR_NETWORK_ERROR_SAVEGAMEERROR;
00604       return NETWORK_RECV_STATUS_SAVEGAME;
00605     }
00606 
00607     _frame_counter = _frame_counter_server = _frame_counter_max = p->Recv_uint32();
00608 
00609     _network_join_bytes = 0;
00610     _network_join_bytes_total = p->Recv_uint32();
00611 
00612     /* If the network connection has been closed due to loss of connection
00613      * or when _network_join_kbytes_total is 0, the join status window will
00614      * do a division by zero. When the connection is lost, we just return
00615      * that. If kbytes_total is 0, the packet must be malformed as a
00616      * savegame less than 1 kilobyte is practically impossible. */
00617     if (MY_CLIENT->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
00618     if (_network_join_bytes_total == 0) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00619 
00620     _network_join_status = NETWORK_JOIN_STATUS_DOWNLOADING;
00621     SetWindowDirty(WC_NETWORK_STATUS_WINDOW, 0);
00622 
00623     /* The first packet does not contain any more data */
00624     return NETWORK_RECV_STATUS_OKAY;
00625   }
00626 
00627   if (maptype == MAP_PACKET_NORMAL) {
00628     /* We are still receiving data, put it to the file */
00629     if (fwrite(p->buffer + p->pos, 1, p->size - p->pos, file_pointer) != (size_t)(p->size - p->pos)) {
00630       _switch_mode_errorstr = STR_NETWORK_ERROR_SAVEGAMEERROR;
00631       return NETWORK_RECV_STATUS_SAVEGAME;
00632     }
00633 
00634     _network_join_bytes = ftell(file_pointer);
00635     SetWindowDirty(WC_NETWORK_STATUS_WINDOW, 0);
00636   }
00637 
00638   /* Check if this was the last packet */
00639   if (maptype == MAP_PACKET_END) {
00640     fclose(file_pointer);
00641 
00642     _network_join_status = NETWORK_JOIN_STATUS_PROCESSING;
00643     SetWindowDirty(WC_NETWORK_STATUS_WINDOW, 0);
00644 
00645     /* The map is done downloading, load it */
00646     if (!SafeSaveOrLoad("network_client.tmp", SL_LOAD, GM_NORMAL, AUTOSAVE_DIR)) {
00647       DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
00648       _switch_mode_errorstr = STR_NETWORK_ERROR_SAVEGAMEERROR;
00649       return NETWORK_RECV_STATUS_SAVEGAME;
00650     }
00651     /* If the savegame has successfully loaded, ALL windows have been removed,
00652      * only toolbar/statusbar and gamefield are visible */
00653 
00654     /* Say we received the map and loaded it correctly! */
00655     SEND_COMMAND(PACKET_CLIENT_MAP_OK)();
00656 
00657     /* New company/spectator (invalid company) or company we want to join is not active
00658      * Switch local company to spectator and await the server's judgement */
00659     if (_network_join_as == COMPANY_NEW_COMPANY || !Company::IsValidID(_network_join_as)) {
00660       SetLocalCompany(COMPANY_SPECTATOR);
00661 
00662       if (_network_join_as != COMPANY_SPECTATOR) {
00663         /* We have arrived and ready to start playing; send a command to make a new company;
00664          * the server will give us a client-id and let us in */
00665         _network_join_status = NETWORK_JOIN_STATUS_REGISTERING;
00666         ShowJoinStatusWindow();
00667         NetworkSend_Command(0, 0, 0, CMD_COMPANY_CTRL, NULL, NULL, _local_company);
00668       }
00669     } else {
00670       /* take control over an existing company */
00671       SetLocalCompany(_network_join_as);
00672     }
00673   }
00674 
00675   return NETWORK_RECV_STATUS_OKAY;
00676 }
00677 
00678 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_FRAME)
00679 {
00680   _frame_counter_server = p->Recv_uint32();
00681   _frame_counter_max = p->Recv_uint32();
00682 #ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
00683   /* Test if the server supports this option
00684    *  and if we are at the frame the server is */
00685   if (p->pos < p->size) {
00686     _sync_frame = _frame_counter_server;
00687     _sync_seed_1 = p->Recv_uint32();
00688 #ifdef NETWORK_SEND_DOUBLE_SEED
00689     _sync_seed_2 = p->Recv_uint32();
00690 #endif
00691   }
00692 #endif
00693   DEBUG(net, 5, "Received FRAME %d", _frame_counter_server);
00694 
00695   /* Let the server know that we received this frame correctly
00696    *  We do this only once per day, to save some bandwidth ;) */
00697   if (!_network_first_time && last_ack_frame < _frame_counter) {
00698     last_ack_frame = _frame_counter + DAY_TICKS;
00699     DEBUG(net, 4, "Sent ACK at %d", _frame_counter);
00700     SEND_COMMAND(PACKET_CLIENT_ACK)();
00701   }
00702 
00703   return NETWORK_RECV_STATUS_OKAY;
00704 }
00705 
00706 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_SYNC)
00707 {
00708   _sync_frame = p->Recv_uint32();
00709   _sync_seed_1 = p->Recv_uint32();
00710 #ifdef NETWORK_SEND_DOUBLE_SEED
00711   _sync_seed_2 = p->Recv_uint32();
00712 #endif
00713 
00714   return NETWORK_RECV_STATUS_OKAY;
00715 }
00716 
00717 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_COMMAND)
00718 {
00719   CommandPacket cp;
00720   const char *err = MY_CLIENT->Recv_Command(p, &cp);
00721   cp.frame    = p->Recv_uint32();
00722   cp.my_cmd   = p->Recv_bool();
00723   cp.next     = NULL;
00724 
00725   if (err != NULL) {
00726     IConsolePrintF(CC_ERROR, "WARNING: %s from server, dropping...", err);
00727     return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00728   }
00729 
00730   /* The server did send us this command..
00731    *  queue it in our own queue, so we can handle it in the upcoming frame! */
00732   NetworkAddCommandQueue(cp);
00733 
00734   return NETWORK_RECV_STATUS_OKAY;
00735 }
00736 
00737 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_CHAT)
00738 {
00739   char name[NETWORK_NAME_LENGTH], msg[NETWORK_CHAT_LENGTH];
00740   const NetworkClientInfo *ci = NULL, *ci_to;
00741 
00742   NetworkAction action = (NetworkAction)p->Recv_uint8();
00743   ClientID client_id = (ClientID)p->Recv_uint32();
00744   bool self_send = p->Recv_bool();
00745   p->Recv_string(msg, NETWORK_CHAT_LENGTH);
00746   int64 data = p->Recv_uint64();
00747 
00748   ci_to = NetworkFindClientInfoFromClientID(client_id);
00749   if (ci_to == NULL) return NETWORK_RECV_STATUS_OKAY;
00750 
00751   /* Did we initiate the action locally? */
00752   if (self_send) {
00753     switch (action) {
00754       case NETWORK_ACTION_CHAT_CLIENT:
00755         /* For speaking to client we need the client-name */
00756         snprintf(name, sizeof(name), "%s", ci_to->client_name);
00757         ci = NetworkFindClientInfoFromClientID(_network_own_client_id);
00758         break;
00759 
00760       /* For speaking to company or giving money, we need the company-name */
00761       case NETWORK_ACTION_GIVE_MONEY:
00762         if (!Company::IsValidID(ci_to->client_playas)) return NETWORK_RECV_STATUS_OKAY;
00763         /* fallthrough */
00764       case NETWORK_ACTION_CHAT_COMPANY: {
00765         StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
00766         SetDParam(0, ci_to->client_playas);
00767 
00768         GetString(name, str, lastof(name));
00769         ci = NetworkFindClientInfoFromClientID(_network_own_client_id);
00770       } break;
00771 
00772       default: return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00773     }
00774   } else {
00775     /* Display message from somebody else */
00776     snprintf(name, sizeof(name), "%s", ci_to->client_name);
00777     ci = ci_to;
00778   }
00779 
00780   if (ci != NULL) {
00781     NetworkTextMessage(action, (ConsoleColour)GetDrawStringCompanyColour(ci->client_playas), self_send, name, msg, data);
00782   }
00783   return NETWORK_RECV_STATUS_OKAY;
00784 }
00785 
00786 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_ERROR_QUIT)
00787 {
00788   ClientID client_id = (ClientID)p->Recv_uint32();
00789 
00790   NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(client_id);
00791   if (ci != NULL) {
00792     NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, NULL, GetNetworkErrorMsg((NetworkErrorCode)p->Recv_uint8()));
00793     delete ci;
00794   }
00795 
00796   SetWindowDirty(WC_CLIENT_LIST, 0);
00797 
00798   return NETWORK_RECV_STATUS_OKAY;
00799 }
00800 
00801 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_QUIT)
00802 {
00803   NetworkClientInfo *ci;
00804 
00805   ClientID client_id = (ClientID)p->Recv_uint32();
00806 
00807   ci = NetworkFindClientInfoFromClientID(client_id);
00808   if (ci != NULL) {
00809     NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, NULL, STR_NETWORK_MESSAGE_CLIENT_LEAVING);
00810     delete ci;
00811   } else {
00812     DEBUG(net, 0, "Unknown client (%d) is leaving the game", client_id);
00813   }
00814 
00815   SetWindowDirty(WC_CLIENT_LIST, 0);
00816 
00817   /* If we come here it means we could not locate the client.. strange :s */
00818   return NETWORK_RECV_STATUS_OKAY;
00819 }
00820 
00821 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_JOIN)
00822 {
00823   ClientID client_id = (ClientID)p->Recv_uint32();
00824 
00825   NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(client_id);
00826   if (ci != NULL) {
00827     NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, ci->client_name);
00828   }
00829 
00830   SetWindowDirty(WC_CLIENT_LIST, 0);
00831 
00832   return NETWORK_RECV_STATUS_OKAY;
00833 }
00834 
00835 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_SHUTDOWN)
00836 {
00837   _switch_mode_errorstr = STR_NETWORK_MESSAGE_SERVER_SHUTDOWN;
00838 
00839   return NETWORK_RECV_STATUS_SERVER_ERROR;
00840 }
00841 
00842 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_NEWGAME)
00843 {
00844   /* To trottle the reconnects a bit, every clients waits
00845    *  his _local_company value before reconnecting
00846    * COMPANY_SPECTATOR is currently 255, so to avoid long wait periods
00847    *  set the max to 10. */
00848   _network_reconnect = min(_local_company + 1, 10);
00849   _switch_mode_errorstr = STR_NETWORK_MESSAGE_SERVER_REBOOT;
00850 
00851   return NETWORK_RECV_STATUS_SERVER_ERROR;
00852 }
00853 
00854 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_RCON)
00855 {
00856   char rcon_out[NETWORK_RCONCOMMAND_LENGTH];
00857 
00858   ConsoleColour colour_code = (ConsoleColour)p->Recv_uint16();
00859   p->Recv_string(rcon_out, sizeof(rcon_out));
00860 
00861   IConsolePrint(colour_code, rcon_out);
00862 
00863   return NETWORK_RECV_STATUS_OKAY;
00864 }
00865 
00866 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_MOVE)
00867 {
00868   /* Nothing more in this packet... */
00869   ClientID client_id   = (ClientID)p->Recv_uint32();
00870   CompanyID company_id = (CompanyID)p->Recv_uint8();
00871 
00872   if (client_id == 0) {
00873     /* definitely an invalid client id, debug message and do nothing. */
00874     DEBUG(net, 0, "[move] received invalid client index = 0");
00875     return NETWORK_RECV_STATUS_MALFORMED_PACKET;
00876   }
00877 
00878   const NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(client_id);
00879   /* Just make sure we do not try to use a client_index that does not exist */
00880   if (ci == NULL) return NETWORK_RECV_STATUS_OKAY;
00881 
00882   /* if not valid player, force spectator, else check player exists */
00883   if (!Company::IsValidID(company_id)) company_id = COMPANY_SPECTATOR;
00884 
00885   if (client_id == _network_own_client_id) {
00886     SetLocalCompany(company_id);
00887   }
00888 
00889   return NETWORK_RECV_STATUS_OKAY;
00890 }
00891 
00892 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_CONFIG_UPDATE)
00893 {
00894   _network_server_max_companies = p->Recv_uint8();
00895   _network_server_max_spectators = p->Recv_uint8();
00896 
00897   return NETWORK_RECV_STATUS_OKAY;
00898 }
00899 
00900 DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_COMPANY_UPDATE)
00901 {
00902   _network_company_passworded = p->Recv_uint16();
00903   SetWindowClassesDirty(WC_COMPANY);
00904 
00905   return NETWORK_RECV_STATUS_OKAY;
00906 }
00907 
00908 
00909 /* The layout for the receive-functions by the client */
00910 typedef NetworkRecvStatus NetworkClientPacket(Packet *p);
00911 
00912 /* This array matches PacketType. At an incoming
00913  *  packet it is matches against this array
00914  *  and that way the right function to handle that
00915  *  packet is found. */
00916 static NetworkClientPacket * const _network_client_packet[] = {
00917   RECEIVE_COMMAND(PACKET_SERVER_FULL),
00918   RECEIVE_COMMAND(PACKET_SERVER_BANNED),
00919   NULL, // PACKET_CLIENT_JOIN,
00920   RECEIVE_COMMAND(PACKET_SERVER_ERROR),
00921   NULL, // PACKET_CLIENT_COMPANY_INFO,
00922   RECEIVE_COMMAND(PACKET_SERVER_COMPANY_INFO),
00923   RECEIVE_COMMAND(PACKET_SERVER_CLIENT_INFO),
00924   RECEIVE_COMMAND(PACKET_SERVER_NEED_PASSWORD),
00925   NULL, // PACKET_CLIENT_PASSWORD,
00926   RECEIVE_COMMAND(PACKET_SERVER_WELCOME),
00927   NULL, // PACKET_CLIENT_GETMAP,
00928   RECEIVE_COMMAND(PACKET_SERVER_WAIT),
00929   RECEIVE_COMMAND(PACKET_SERVER_MAP),
00930   NULL, // PACKET_CLIENT_MAP_OK,
00931   RECEIVE_COMMAND(PACKET_SERVER_JOIN),
00932   RECEIVE_COMMAND(PACKET_SERVER_FRAME),
00933   RECEIVE_COMMAND(PACKET_SERVER_SYNC),
00934   NULL, // PACKET_CLIENT_ACK,
00935   NULL, // PACKET_CLIENT_COMMAND,
00936   RECEIVE_COMMAND(PACKET_SERVER_COMMAND),
00937   NULL, // PACKET_CLIENT_CHAT,
00938   RECEIVE_COMMAND(PACKET_SERVER_CHAT),
00939   NULL, // PACKET_CLIENT_SET_PASSWORD,
00940   NULL, // PACKET_CLIENT_SET_NAME,
00941   NULL, // PACKET_CLIENT_QUIT,
00942   NULL, // PACKET_CLIENT_ERROR,
00943   RECEIVE_COMMAND(PACKET_SERVER_QUIT),
00944   RECEIVE_COMMAND(PACKET_SERVER_ERROR_QUIT),
00945   RECEIVE_COMMAND(PACKET_SERVER_SHUTDOWN),
00946   RECEIVE_COMMAND(PACKET_SERVER_NEWGAME),
00947   RECEIVE_COMMAND(PACKET_SERVER_RCON),
00948   NULL, // PACKET_CLIENT_RCON,
00949   RECEIVE_COMMAND(PACKET_SERVER_CHECK_NEWGRFS),
00950   NULL, // PACKET_CLIENT_NEWGRFS_CHECKED,
00951   RECEIVE_COMMAND(PACKET_SERVER_MOVE),
00952   NULL, // PACKET_CLIENT_MOVE
00953   RECEIVE_COMMAND(PACKET_SERVER_COMPANY_UPDATE),
00954   RECEIVE_COMMAND(PACKET_SERVER_CONFIG_UPDATE),
00955 };
00956 
00957 /* If this fails, check the array above with network_data.h */
00958 assert_compile(lengthof(_network_client_packet) == PACKET_END);
00959 
00960 /* Is called after a client is connected to the server */
00961 void NetworkClient_Connected()
00962 {
00963   /* Set the frame-counter to 0 so nothing happens till we are ready */
00964   _frame_counter = 0;
00965   _frame_counter_server = 0;
00966   last_ack_frame = 0;
00967   /* Request the game-info */
00968   SEND_COMMAND(PACKET_CLIENT_JOIN)();
00969 }
00970 
00971 /* Reads the packets from the socket-stream, if available */
00972 NetworkRecvStatus NetworkClient_ReadPackets(NetworkClientSocket *cs)
00973 {
00974   Packet *p;
00975   NetworkRecvStatus res = NETWORK_RECV_STATUS_OKAY;
00976 
00977   while (res == NETWORK_RECV_STATUS_OKAY && (p = cs->Recv_Packet()) != NULL) {
00978     byte type = p->Recv_uint8();
00979     if (type < PACKET_END && _network_client_packet[type] != NULL && !MY_CLIENT->HasClientQuit()) {
00980       res = _network_client_packet[type](p);
00981     } else {
00982       res = NETWORK_RECV_STATUS_MALFORMED_PACKET;
00983       DEBUG(net, 0, "[client] received invalid packet type %d", type);
00984     }
00985 
00986     delete p;
00987   }
00988 
00989   return res;
00990 }
00991 
00992 void NetworkClientSendRcon(const char *password, const char *command)
00993 {
00994   SEND_COMMAND(PACKET_CLIENT_RCON)(password, command);
00995 }
00996 
01003 void NetworkClientRequestMove(CompanyID company_id, const char *pass)
01004 {
01005   SEND_COMMAND(PACKET_CLIENT_MOVE)(company_id, pass);
01006 }
01007 
01008 void NetworkUpdateClientName()
01009 {
01010   NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(_network_own_client_id);
01011 
01012   if (ci == NULL) return;
01013 
01014   /* Don't change the name if it is the same as the old name */
01015   if (strcmp(ci->client_name, _settings_client.network.client_name) != 0) {
01016     if (!_network_server) {
01017       SEND_COMMAND(PACKET_CLIENT_SET_NAME)(_settings_client.network.client_name);
01018     } else {
01019       if (NetworkFindName(_settings_client.network.client_name)) {
01020         NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, _settings_client.network.client_name);
01021         strecpy(ci->client_name, _settings_client.network.client_name, lastof(ci->client_name));
01022         NetworkUpdateClientInfo(CLIENT_ID_SERVER);
01023       }
01024     }
01025   }
01026 }
01027 
01028 void NetworkClientSendChat(NetworkAction action, DestType type, int dest, const char *msg, int64 data)
01029 {
01030   SEND_COMMAND(PACKET_CLIENT_CHAT)(action, type, dest, msg, data);
01031 }
01032 
01033 static void NetworkClientSetPassword(const char *password)
01034 {
01035   SEND_COMMAND(PACKET_CLIENT_SET_PASSWORD)(password);
01036 }
01037 
01043 bool NetworkClientPreferTeamChat(const NetworkClientInfo *cio)
01044 {
01045   /* Only companies actually playing can speak to team. Eg spectators cannot */
01046   if (!_settings_client.gui.prefer_teamchat || !Company::IsValidID(cio->client_playas)) return false;
01047 
01048   const NetworkClientInfo *ci;
01049   FOR_ALL_CLIENT_INFOS(ci) {
01050     if (ci->client_playas == cio->client_playas && ci != cio) return true;
01051   }
01052 
01053   return false;
01054 }
01055 
01061 const char *NetworkChangeCompanyPassword(const char *password)
01062 {
01063   if (strcmp(password, "*") == 0) password = "";
01064 
01065   if (!_network_server) {
01066     NetworkClientSetPassword(password);
01067   } else {
01068     HashCurrentCompanyPassword(password);
01069   }
01070 
01071   return password;
01072 }
01073 
01078 bool NetworkMaxCompaniesReached()
01079 {
01080   return Company::GetNumItems() >= (_network_server ? _settings_client.network.max_companies : _network_server_max_companies);
01081 }
01082 
01087 bool NetworkMaxSpectatorsReached()
01088 {
01089   return NetworkSpectatorCount() >= (_network_server ? _settings_client.network.max_spectators : _network_server_max_spectators);
01090 }
01091 
01095 void NetworkPrintClients()
01096 {
01097   NetworkClientInfo *ci;
01098   FOR_ALL_CLIENT_INFOS(ci) {
01099     IConsolePrintF(CC_INFO, "Client #%1d  name: '%s'  company: %1d  IP: %s",
01100         ci->client_id,
01101         ci->client_name,
01102         ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0),
01103         GetClientIP(ci));
01104   }
01105 }
01106 
01107 #endif /* ENABLE_NETWORK */

Generated on Wed Mar 31 22:43:24 2010 for OpenTTD by  doxygen 1.6.1