network_client.cpp

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

Generated on Thu Feb 4 17:20:25 2010 for OpenTTD by  doxygen 1.5.6