# network_client.cpp

Go to the documentation of this file.

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