# network_server.cpp

Go to the documentation of this file.

    00001 /* $Id: network_server.cpp 21184 2010-11-14 12:42:29Z 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 "../strings_func.h"
    00017 #include "../date_func.h"
    00018 #include "network_server.h"
    00019 #include "network_udp.h"
    00020 #include "network.h"
    00021 #include "network_base.h"
    00022 #include "../console_func.h"
    00023 #include "../company_base.h"
    00024 #include "../command_func.h"
    00025 #include "../saveload/saveload.h"
    00026 #include "../station_base.h"
    00027 #include "../genworld.h"
    00028 #include "../fileio_func.h"
    00029 #include "../company_func.h"
    00030 #include "../company_gui.h"
    00031 #include "../window_func.h"
    00032 #include "../roadveh.h"
    00033 #include "../rev.h"
    00034
    00035 #include "table/strings.h"
    00036
    00037 /* This file handles all the server-commands */
    00038
    00039 static void NetworkHandleCommandQueue(NetworkClientSocket *cs);
    00040
    00041 /***********
    00042  * Sending functions
    00043  *   DEF_SERVER_SEND_COMMAND has parameter: NetworkClientSocket *cs
    00044  ************/
    00045
    00046 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_CLIENT_INFO)(NetworkClientSocket *cs, NetworkClientInfo *ci)
    00047 {
    00048   /*
    00049    * Packet: SERVER_CLIENT_INFO
    00050    * Function: Sends info about a client
    00051    * Data:
    00052    *    uint32:  The identifier of the client (always unique on a server. 1 = server, 0 is invalid)
    00053    *    uint8:  As which company the client is playing
    00054    *    String: The name of the client
    00055    */
    00056
    00057   if (ci->client_id != INVALID_CLIENT_ID) {
    00058     Packet *p = new Packet(PACKET_SERVER_CLIENT_INFO);
    00059     p->Send_uint32(ci->client_id);
    00060     p->Send_uint8 (ci->client_playas);
    00061     p->Send_string(ci->client_name);
    00062
    00063     cs->Send_Packet(p);
    00064   }
    00065   return NETWORK_RECV_STATUS_OKAY;
    00066 }
    00067
    00068 DEF_SERVER_SEND_COMMAND(PACKET_SERVER_COMPANY_INFO)
    00069 {
    00070   /*
    00071    * Packet: SERVER_COMPANY_INFO
    00072    * Function: Sends info about the companies
    00073    * Data:
    00074    */
    00075
    00076   /* Fetch the latest version of the stats */
    00077   NetworkCompanyStats company_stats[MAX_COMPANIES];
    00078   NetworkPopulateCompanyStats(company_stats);
    00079
    00080   /* Make a list of all clients per company */
    00081   char clients[MAX_COMPANIES][NETWORK_CLIENTS_LENGTH];
    00082   NetworkClientSocket *csi;
    00083   memset(clients, 0, sizeof(clients));
    00084
    00085   /* Add the local player (if not dedicated) */
    00086   const NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(CLIENT_ID_SERVER);
    00087   if (ci != NULL && Company::IsValidID(ci->client_playas)) {
    00088     strecpy(clients[ci->client_playas], ci->client_name, lastof(clients[ci->client_playas]));
    00089   }
    00090
    00091   FOR_ALL_CLIENT_SOCKETS(csi) {
    00092     char client_name[NETWORK_CLIENT_NAME_LENGTH];
    00093
    00094     NetworkGetClientName(client_name, sizeof(client_name), csi);
    00095
    00096     ci = csi->GetInfo();
    00097     if (ci != NULL && Company::IsValidID(ci->client_playas)) {
    00098       if (!StrEmpty(clients[ci->client_playas])) {
    00099         strecat(clients[ci->client_playas], ", ", lastof(clients[ci->client_playas]));
    00100       }
    00101
    00102       strecat(clients[ci->client_playas], client_name, lastof(clients[ci->client_playas]));
    00103     }
    00104   }
    00105
    00106   /* Now send the data */
    00107
    00108   Company *company;
    00109   Packet *p;
    00110
    00111   FOR_ALL_COMPANIES(company) {
    00112     p = new Packet(PACKET_SERVER_COMPANY_INFO);
    00113
    00114     p->Send_uint8 (NETWORK_COMPANY_INFO_VERSION);
    00115     p->Send_bool  (true);
    00116     cs->Send_CompanyInformation(p, company, &company_stats[company->index]);
    00117
    00118     if (StrEmpty(clients[company->index])) {
    00119       p->Send_string("<none>");
    00120     } else {
    00121       p->Send_string(clients[company->index]);
    00122     }
    00123
    00124     cs->Send_Packet(p);
    00125   }
    00126
    00127   p = new Packet(PACKET_SERVER_COMPANY_INFO);
    00128
    00129   p->Send_uint8 (NETWORK_COMPANY_INFO_VERSION);
    00130   p->Send_bool  (false);
    00131
    00132   cs->Send_Packet(p);
    00133   return NETWORK_RECV_STATUS_OKAY;
    00134 }
    00135
    00136 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_ERROR)(NetworkClientSocket *cs, NetworkErrorCode error)
    00137 {
    00138   /*
    00139    * Packet: SERVER_ERROR
    00140    * Function: The client made an error
    00141    * Data:
    00142    *    uint8:  ErrorID (see network_data.h, NetworkErrorCode)
    00143    */
    00144
    00145   char str[100];
    00146   Packet *p = new Packet(PACKET_SERVER_ERROR);
    00147
    00148   p->Send_uint8(error);
    00149   cs->Send_Packet(p);
    00150
    00151   StringID strid = GetNetworkErrorMsg(error);
    00152   GetString(str, strid, lastof(str));
    00153
    00154   /* Only send when the current client was in game */
    00155   if (cs->status > STATUS_AUTHORIZED) {
    00156     NetworkClientSocket *new_cs;
    00157     char client_name[NETWORK_CLIENT_NAME_LENGTH];
    00158
    00159     NetworkGetClientName(client_name, sizeof(client_name), cs);
    00160
    00161     DEBUG(net, 1, "'%s' made an error and has been disconnected. Reason: '%s'", client_name, str);
    00162
    00163     NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, strid);
    00164
    00165     FOR_ALL_CLIENT_SOCKETS(new_cs) {
    00166       if (new_cs->status > STATUS_AUTHORIZED && new_cs != cs) {
    00167         /* Some errors we filter to a more general error. Clients don't have to know the real
    00168          *  reason a joining failed. */
    00169         if (error == NETWORK_ERROR_NOT_AUTHORIZED || error == NETWORK_ERROR_NOT_EXPECTED || error == NETWORK_ERROR_WRONG_REVISION)
    00170           error = NETWORK_ERROR_ILLEGAL_PACKET;
    00171
    00172         SEND_COMMAND(PACKET_SERVER_ERROR_QUIT)(new_cs, cs->client_id, error);
    00173       }
    00174     }
    00175   } else {
    00176     DEBUG(net, 1, "Client %d made an error and has been disconnected. Reason: '%s'", cs->client_id, str);
    00177   }
    00178
    00179   /* The client made a mistake, so drop his connection now! */
    00180   return NetworkCloseClient(cs, NETWORK_RECV_STATUS_SERVER_ERROR);
    00181 }
    00182
    00183 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_CHECK_NEWGRFS)(NetworkClientSocket *cs)
    00184 {
    00185   /*
    00186    * Packet: PACKET_SERVER_CHECK_NEWGRFS
    00187    * Function: Sends info about the used GRFs to the client
    00188    * Data:
    00189    *      uint8:  Amount of GRFs
    00190    *    And then for each GRF:
    00191    *      uint32: GRF ID
    00192    * 16 * uint8:  MD5 checksum of the GRF
    00193    */
    00194
    00195   Packet *p = new Packet(PACKET_SERVER_CHECK_NEWGRFS);
    00196   const GRFConfig *c;
    00197   uint grf_count = 0;
    00198
    00199   for (c = _grfconfig; c != NULL; c = c->next) {
    00200     if (!HasBit(c->flags, GCF_STATIC)) grf_count++;
    00201   }
    00202
    00203   p->Send_uint8 (grf_count);
    00204   for (c = _grfconfig; c != NULL; c = c->next) {
    00205     if (!HasBit(c->flags, GCF_STATIC)) cs->Send_GRFIdentifier(p, c);
    00206   }
    00207
    00208   cs->Send_Packet(p);
    00209   return NETWORK_RECV_STATUS_OKAY;
    00210 }
    00211
    00212 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_NEED_GAME_PASSWORD)(NetworkClientSocket *cs)
    00213 {
    00214   /*
    00215    * Packet: PACKET_SERVER_NEED_GAME_PASSWORD
    00216    * Function: Indication to the client that the server needs a game password
    00217    */
    00218
    00219   /* Invalid packet when status is STATUS_AUTH_GAME or higher */
    00220   if (cs->status >= STATUS_AUTH_GAME) return NetworkCloseClient(cs, NETWORK_RECV_STATUS_MALFORMED_PACKET);
    00221
    00222   cs->status = STATUS_AUTH_GAME;
    00223
    00224   Packet *p = new Packet(PACKET_SERVER_NEED_GAME_PASSWORD);
    00225   cs->Send_Packet(p);
    00226   return NETWORK_RECV_STATUS_OKAY;
    00227 }
    00228
    00229 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_NEED_COMPANY_PASSWORD)(NetworkClientSocket *cs)
    00230 {
    00231   /*
    00232    * Packet: PACKET_SERVER_NEED_COMPANY_PASSWORD
    00233    * Function: Indication to the client that the server needs a company password
    00234    * Data:
    00235    *    uint32:  Generation seed
    00236    *    string:  Network ID of the server
    00237    */
    00238
    00239   /* Invalid packet when status is STATUS_AUTH_COMPANY or higher */
    00240   if (cs->status >= STATUS_AUTH_COMPANY) return NetworkCloseClient(cs, NETWORK_RECV_STATUS_MALFORMED_PACKET);
    00241
    00242   cs->status = STATUS_AUTH_COMPANY;
    00243
    00244   Packet *p = new Packet(PACKET_SERVER_NEED_COMPANY_PASSWORD);
    00245   p->Send_uint32(_settings_game.game_creation.generation_seed);
    00246   p->Send_string(_settings_client.network.network_id);
    00247   cs->Send_Packet(p);
    00248   return NETWORK_RECV_STATUS_OKAY;
    00249 }
    00250
    00251 DEF_SERVER_SEND_COMMAND(PACKET_SERVER_WELCOME)
    00252 {
    00253   /*
    00254    * Packet: SERVER_WELCOME
    00255    * Function: The client is joined and ready to receive his map
    00256    * Data:
    00257    *    uint32:  Own Client identifier
    00258    */
    00259
    00260   Packet *p;
    00261   NetworkClientSocket *new_cs;
    00262
    00263   /* Invalid packet when status is AUTH or higher */
    00264   if (cs->status >= STATUS_AUTHORIZED) return NetworkCloseClient(cs, NETWORK_RECV_STATUS_MALFORMED_PACKET);
    00265
    00266   cs->status = STATUS_AUTHORIZED;
    00267   _network_game_info.clients_on++;
    00268
    00269   p = new Packet(PACKET_SERVER_WELCOME);
    00270   p->Send_uint32(cs->client_id);
    00271   p->Send_uint32(_settings_game.game_creation.generation_seed);
    00272   p->Send_string(_settings_client.network.network_id);
    00273   cs->Send_Packet(p);
    00274
    00275     /* Transmit info about all the active clients */
    00276   FOR_ALL_CLIENT_SOCKETS(new_cs) {
    00277     if (new_cs != cs && new_cs->status > STATUS_AUTHORIZED)
    00278       SEND_COMMAND(PACKET_SERVER_CLIENT_INFO)(cs, new_cs->GetInfo());
    00279   }
    00280   /* Also send the info of the server */
    00281   return SEND_COMMAND(PACKET_SERVER_CLIENT_INFO)(cs, NetworkFindClientInfoFromClientID(CLIENT_ID_SERVER));
    00282 }
    00283
    00284 DEF_SERVER_SEND_COMMAND(PACKET_SERVER_WAIT)
    00285 {
    00286   /*
    00287    * Packet: PACKET_SERVER_WAIT
    00288    * Function: The client can not receive the map at the moment because
    00289    *             someone else is already receiving the map
    00290    * Data:
    00291    *    uint8:  Clients awaiting map
    00292    */
    00293   int waiting = 0;
    00294   NetworkClientSocket *new_cs;
    00295   Packet *p;
    00296
    00297   /* Count how many clients are waiting in the queue */
    00298   FOR_ALL_CLIENT_SOCKETS(new_cs) {
    00299     if (new_cs->status == STATUS_MAP_WAIT) waiting++;
    00300   }
    00301
    00302   p = new Packet(PACKET_SERVER_WAIT);
    00303   p->Send_uint8(waiting);
    00304   cs->Send_Packet(p);
    00305   return NETWORK_RECV_STATUS_OKAY;
    00306 }
    00307
    00308 /* This sends the map to the client */
    00309 DEF_SERVER_SEND_COMMAND(PACKET_SERVER_MAP)
    00310 {
    00311   /*
    00312    * Packet: SERVER_MAP
    00313    * Function: Sends the map to the client, or a part of it (it is splitted in
    00314    *   a lot of multiple packets)
    00315    * Data:
    00316    *    uint8:  packet-type (MAP_PACKET_START, MAP_PACKET_NORMAL and MAP_PACKET_END)
    00317    *  if MAP_PACKET_START:
    00318    *    uint32: The current FrameCounter
    00319    *  if MAP_PACKET_NORMAL:
    00320    *    piece of the map (till max-size of packet)
    00321    *  if MAP_PACKET_END:
    00322    *    nothing
    00323    */
    00324
    00325   static FILE *file_pointer = NULL;
    00326   static uint sent_packets; // How many packets we did send succecfully last time
    00327
    00328   if (cs->status < STATUS_AUTHORIZED) {
    00329     /* Illegal call, return error and ignore the packet */
    00330     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_AUTHORIZED);
    00331   }
    00332
    00333   if (cs->status == STATUS_AUTHORIZED) {
    00334     const char *filename = "network_server.tmp";
    00335     Packet *p;
    00336
    00337     /* Make a dump of the current game */
    00338     if (SaveOrLoad(filename, SL_SAVE, AUTOSAVE_DIR) != SL_OK) usererror("network savedump failed");
    00339
    00340     if (file_pointer != NULL) fclose(file_pointer);
    00341
    00342     file_pointer = FioFOpenFile(filename, "rb", AUTOSAVE_DIR);
    00343     if (file_pointer == NULL) usererror("network savedump failed - could not open just saved dump");
    00344
    00345     fseek(file_pointer, 0, SEEK_END);
    00346     if (ftell(file_pointer) == 0) usererror("network savedump failed - zero sized savegame?");
    00347
    00348     /* Now send the _frame_counter and how many packets are coming */
    00349     p = new Packet(PACKET_SERVER_MAP);
    00350     p->Send_uint8 (MAP_PACKET_START);
    00351     p->Send_uint32(_frame_counter);
    00352     p->Send_uint32(ftell(file_pointer));
    00353     cs->Send_Packet(p);
    00354
    00355     fseek(file_pointer, 0, SEEK_SET);
    00356
    00357     sent_packets = 4; // We start with trying 4 packets
    00358
    00359     NetworkSyncCommandQueue(cs);
    00360     cs->status = STATUS_MAP;
    00361     /* Mark the start of download */
    00362     cs->last_frame = _frame_counter;
    00363     cs->last_frame_server = _frame_counter;
    00364   }
    00365
    00366   if (cs->status == STATUS_MAP) {
    00367     uint i;
    00368     int res;
    00369     for (i = 0; i < sent_packets; i++) {
    00370       Packet *p = new Packet(PACKET_SERVER_MAP);
    00371       p->Send_uint8(MAP_PACKET_NORMAL);
    00372       res = (int)fread(p->buffer + p->size, 1, SEND_MTU - p->size, file_pointer);
    00373
    00374       if (ferror(file_pointer)) usererror("Error reading temporary network savegame!");
    00375
    00376       p->size += res;
    00377       cs->Send_Packet(p);
    00378       if (feof(file_pointer)) {
    00379         /* Done reading! */
    00380         Packet *p = new Packet(PACKET_SERVER_MAP);
    00381         p->Send_uint8(MAP_PACKET_END);
    00382         cs->Send_Packet(p);
    00383
    00384         /* Set the status to DONE_MAP, no we will wait for the client
    00385          *  to send it is ready (maybe that happens like never ;)) */
    00386         cs->status = STATUS_DONE_MAP;
    00387         fclose(file_pointer);
    00388         file_pointer = NULL;
    00389
    00390         NetworkClientSocket *new_cs;
    00391         bool new_map_client = false;
    00392         /* Check if there is a client waiting for receiving the map
    00393          *  and start sending him the map */
    00394         FOR_ALL_CLIENT_SOCKETS(new_cs) {
    00395           if (new_cs->status == STATUS_MAP_WAIT) {
    00396             /* Check if we already have a new client to send the map to */
    00397             if (!new_map_client) {
    00398               /* If not, this client will get the map */
    00399               new_cs->status = STATUS_AUTHORIZED;
    00400               new_map_client = true;
    00401               SEND_COMMAND(PACKET_SERVER_MAP)(new_cs);
    00402             } else {
    00403               /* Else, send the other clients how many clients are in front of them */
    00404               SEND_COMMAND(PACKET_SERVER_WAIT)(new_cs);
    00405             }
    00406           }
    00407         }
    00408
    00409         /* There is no more data, so break the for */
    00410         break;
    00411       }
    00412     }
    00413
    00414     /* Send all packets (forced) and check if we have send it all */
    00415     if (cs->Send_Packets() && cs->IsPacketQueueEmpty()) {
    00416       /* All are sent, increase the sent_packets */
    00417       sent_packets *= 2;
    00418     } else {
    00419       /* Not everything is sent, decrease the sent_packets */
    00420       if (sent_packets > 1) sent_packets /= 2;
    00421     }
    00422   }
    00423   return NETWORK_RECV_STATUS_OKAY;
    00424 }
    00425
    00426 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_JOIN)(NetworkClientSocket *cs, ClientID client_id)
    00427 {
    00428   /*
    00429    * Packet: SERVER_JOIN
    00430    * Function: A client is joined (all active clients receive this after a
    00431    *     PACKET_CLIENT_MAP_OK) Mostly what directly follows is a
    00432    *     PACKET_SERVER_CLIENT_INFO
    00433    * Data:
    00434    *    uint32:  Client-identifier
    00435    */
    00436
    00437   Packet *p = new Packet(PACKET_SERVER_JOIN);
    00438
    00439   p->Send_uint32(client_id);
    00440
    00441   cs->Send_Packet(p);
    00442   return NETWORK_RECV_STATUS_OKAY;
    00443 }
    00444
    00445
    00446 DEF_SERVER_SEND_COMMAND(PACKET_SERVER_FRAME)
    00447 {
    00448   /*
    00449    * Packet: SERVER_FRAME
    00450    * Function: Sends the current frame-counter to the client
    00451    * Data:
    00452    *    uint32: Frame Counter
    00453    *    uint32: Frame Counter Max (how far may the client walk before the server?)
    00454    *    [uint32: general-seed-1]
    00455    *    [uint32: general-seed-2]
    00456    *      (last two depends on compile-settings, and are not default settings)
    00457    */
    00458
    00459   Packet *p = new Packet(PACKET_SERVER_FRAME);
    00460   p->Send_uint32(_frame_counter);
    00461   p->Send_uint32(_frame_counter_max);
    00462 #ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
    00463   p->Send_uint32(_sync_seed_1);
    00464 #ifdef NETWORK_SEND_DOUBLE_SEED
    00465   p->Send_uint32(_sync_seed_2);
    00466 #endif
    00467 #endif
    00468   cs->Send_Packet(p);
    00469   return NETWORK_RECV_STATUS_OKAY;
    00470 }
    00471
    00472 DEF_SERVER_SEND_COMMAND(PACKET_SERVER_SYNC)
    00473 {
    00474   /*
    00475    * Packet: SERVER_SYNC
    00476    * Function: Sends a sync-check to the client
    00477    * Data:
    00478    *    uint32: Frame Counter
    00479    *    uint32: General-seed-1
    00480    *    [uint32: general-seed-2]
    00481    *      (last one depends on compile-settings, and are not default settings)
    00482    */
    00483
    00484   Packet *p = new Packet(PACKET_SERVER_SYNC);
    00485   p->Send_uint32(_frame_counter);
    00486   p->Send_uint32(_sync_seed_1);
    00487
    00488 #ifdef NETWORK_SEND_DOUBLE_SEED
    00489   p->Send_uint32(_sync_seed_2);
    00490 #endif
    00491   cs->Send_Packet(p);
    00492   return NETWORK_RECV_STATUS_OKAY;
    00493 }
    00494
    00495 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_COMMAND)(NetworkClientSocket *cs, const CommandPacket *cp)
    00496 {
    00497   /*
    00498    * Packet: SERVER_COMMAND
    00499    * Function: Sends a DoCommand to the client
    00500    * Data:
    00501    *    uint8:  CompanyID (0..MAX_COMPANIES-1)
    00502    *    uint32: CommandID (see command.h)
    00503    *    uint32: P1 (free variables used in DoCommand)
    00504    *    uint32: P2
    00505    *    uint32: Tile
    00506    *    string: text
    00507    *    uint8:  CallBackID
    00508    *    uint32: Frame of execution
    00509    */
    00510
    00511   Packet *p = new Packet(PACKET_SERVER_COMMAND);
    00512
    00513   cs->Send_Command(p, cp);
    00514   p->Send_uint32(cp->frame);
    00515   p->Send_bool  (cp->my_cmd);
    00516
    00517   cs->Send_Packet(p);
    00518   return NETWORK_RECV_STATUS_OKAY;
    00519 }
    00520
    00521 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_CHAT)(NetworkClientSocket *cs, NetworkAction action, ClientID client_id, bool self_send, const char *msg, int64 data)
    00522 {
    00523   /*
    00524    * Packet: SERVER_CHAT
    00525    * Function: Sends a chat-packet to the client
    00526    * Data:
    00527    *    uint8:  ActionID (see network_data.h, NetworkAction)
    00528    *    uint32: Client-identifier
    00529    *    String: Message (max NETWORK_CHAT_LENGTH)
    00530    *    uint64: Arbitrary data
    00531    */
    00532
    00533   Packet *p = new Packet(PACKET_SERVER_CHAT);
    00534
    00535   p->Send_uint8 (action);
    00536   p->Send_uint32(client_id);
    00537   p->Send_bool  (self_send);
    00538   p->Send_string(msg);
    00539   p->Send_uint64(data);
    00540
    00541   cs->Send_Packet(p);
    00542   return NETWORK_RECV_STATUS_OKAY;
    00543 }
    00544
    00545 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_ERROR_QUIT)(NetworkClientSocket *cs, ClientID client_id, NetworkErrorCode errorno)
    00546 {
    00547   /*
    00548    * Packet: SERVER_ERROR_QUIT
    00549    * Function: One of the clients made an error and is quiting the game
    00550    *      This packet informs the other clients of that.
    00551    * Data:
    00552    *    uint32:  Client-identifier
    00553    *    uint8:  ErrorID (see network_data.h, NetworkErrorCode)
    00554    */
    00555
    00556   Packet *p = new Packet(PACKET_SERVER_ERROR_QUIT);
    00557
    00558   p->Send_uint32(client_id);
    00559   p->Send_uint8 (errorno);
    00560
    00561   cs->Send_Packet(p);
    00562   return NETWORK_RECV_STATUS_OKAY;
    00563 }
    00564
    00565 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_QUIT)(NetworkClientSocket *cs, ClientID client_id)
    00566 {
    00567   /*
    00568    * Packet: SERVER_ERROR_QUIT
    00569    * Function: A client left the game, and this packets informs the other clients
    00570    *      of that.
    00571    * Data:
    00572    *    uint32:  Client-identifier
    00573    */
    00574
    00575   Packet *p = new Packet(PACKET_SERVER_QUIT);
    00576
    00577   p->Send_uint32(client_id);
    00578
    00579   cs->Send_Packet(p);
    00580   return NETWORK_RECV_STATUS_OKAY;
    00581 }
    00582
    00583 DEF_SERVER_SEND_COMMAND(PACKET_SERVER_SHUTDOWN)
    00584 {
    00585   /*
    00586    * Packet: SERVER_SHUTDOWN
    00587    * Function: Let the clients know that the server is closing
    00588    * Data:
    00589    *     <none>
    00590    */
    00591
    00592   Packet *p = new Packet(PACKET_SERVER_SHUTDOWN);
    00593   cs->Send_Packet(p);
    00594   return NETWORK_RECV_STATUS_OKAY;
    00595 }
    00596
    00597 DEF_SERVER_SEND_COMMAND(PACKET_SERVER_NEWGAME)
    00598 {
    00599   /*
    00600    * Packet: PACKET_SERVER_NEWGAME
    00601    * Function: Let the clients know that the server is loading a new map
    00602    * Data:
    00603    *     <none>
    00604    */
    00605
    00606   Packet *p = new Packet(PACKET_SERVER_NEWGAME);
    00607   cs->Send_Packet(p);
    00608   return NETWORK_RECV_STATUS_OKAY;
    00609 }
    00610
    00611 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_RCON)(NetworkClientSocket *cs, uint16 colour, const char *command)
    00612 {
    00613   Packet *p = new Packet(PACKET_SERVER_RCON);
    00614
    00615   p->Send_uint16(colour);
    00616   p->Send_string(command);
    00617   cs->Send_Packet(p);
    00618   return NETWORK_RECV_STATUS_OKAY;
    00619 }
    00620
    00621 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_MOVE)(NetworkClientSocket *cs, ClientID client_id, CompanyID company_id)
    00622 {
    00623   Packet *p = new Packet(PACKET_SERVER_MOVE);
    00624
    00625   p->Send_uint32(client_id);
    00626   p->Send_uint8(company_id);
    00627   cs->Send_Packet(p);
    00628   return NETWORK_RECV_STATUS_OKAY;
    00629 }
    00630
    00631 DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_COMPANY_UPDATE)(NetworkClientSocket *cs)
    00632 {
    00633   Packet *p = new Packet(PACKET_SERVER_COMPANY_UPDATE);
    00634
    00635   p->Send_uint16(_network_company_passworded);
    00636   cs->Send_Packet(p);
    00637   return NETWORK_RECV_STATUS_OKAY;
    00638 }
    00639
    00640 DEF_SERVER_SEND_COMMAND(PACKET_SERVER_CONFIG_UPDATE)
    00641 {
    00642   Packet *p = new Packet(PACKET_SERVER_CONFIG_UPDATE);
    00643
    00644   p->Send_uint8(_settings_client.network.max_companies);
    00645   p->Send_uint8(_settings_client.network.max_spectators);
    00646   cs->Send_Packet(p);
    00647   return NETWORK_RECV_STATUS_OKAY;
    00648 }
    00649
    00650 /***********
    00651  * Receiving functions
    00652  *   DEF_SERVER_RECEIVE_COMMAND has parameter: NetworkClientSocket *cs, Packet *p
    00653  ************/
    00654
    00655 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_COMPANY_INFO)
    00656 {
    00657   return SEND_COMMAND(PACKET_SERVER_COMPANY_INFO)(cs);
    00658 }
    00659
    00660 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_NEWGRFS_CHECKED)
    00661 {
    00662   if (cs->status != STATUS_NEWGRFS_CHECK) {
    00663     /* Illegal call, return error and ignore the packet */
    00664     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    00665   }
    00666
    00667   NetworkClientInfo *ci = cs->GetInfo();
    00668
    00669   /* We now want a password from the client else we do not allow him in! */
    00670   if (!StrEmpty(_settings_client.network.server_password)) {
    00671     return SEND_COMMAND(PACKET_SERVER_NEED_GAME_PASSWORD)(cs);
    00672   }
    00673
    00674   if (Company::IsValidID(ci->client_playas) && !StrEmpty(_network_company_states[ci->client_playas].password)) {
    00675     return SEND_COMMAND(PACKET_SERVER_NEED_COMPANY_PASSWORD)(cs);
    00676   }
    00677
    00678   return SEND_COMMAND(PACKET_SERVER_WELCOME)(cs);
    00679 }
    00680
    00681 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_JOIN)
    00682 {
    00683   if (cs->status != STATUS_INACTIVE) {
    00684     /* Illegal call, return error and ignore the packet */
    00685     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    00686   }
    00687
    00688   char name[NETWORK_CLIENT_NAME_LENGTH];
    00689   NetworkClientInfo *ci;
    00690   CompanyID playas;
    00691   NetworkLanguage client_lang;
    00692   char client_revision[NETWORK_REVISION_LENGTH];
    00693
    00694   p->Recv_string(client_revision, sizeof(client_revision));
    00695
    00696   /* Check if the client has revision control enabled */
    00697   if (!IsNetworkCompatibleVersion(client_revision)) {
    00698     /* Different revisions!! */
    00699     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_WRONG_REVISION);
    00700   }
    00701
    00702   p->Recv_string(name, sizeof(name));
    00703   playas = (Owner)p->Recv_uint8();
    00704   client_lang = (NetworkLanguage)p->Recv_uint8();
    00705
    00706   if (cs->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
    00707
    00708   /* join another company does not affect these values */
    00709   switch (playas) {
    00710     case COMPANY_NEW_COMPANY: // New company
    00711       if (Company::GetNumItems() >= _settings_client.network.max_companies) {
    00712         return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_FULL);
    00713       }
    00714       break;
    00715     case COMPANY_SPECTATOR: // Spectator
    00716       if (NetworkSpectatorCount() >= _settings_client.network.max_spectators) {
    00717         return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_FULL);
    00718       }
    00719       break;
    00720     default: // Join another company (companies 1-8 (index 0-7))
    00721       if (!Company::IsValidHumanID(playas)) {
    00722         return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_COMPANY_MISMATCH);
    00723       }
    00724       break;
    00725   }
    00726
    00727   /* We need a valid name.. make it Player */
    00728   if (StrEmpty(name)) strecpy(name, "Player", lastof(name));
    00729
    00730   if (!NetworkFindName(name)) { // Change name if duplicate
    00731     /* We could not create a name for this client */
    00732     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NAME_IN_USE);
    00733   }
    00734
    00735   ci = cs->GetInfo();
    00736
    00737   strecpy(ci->client_name, name, lastof(ci->client_name));
    00738   ci->client_playas = playas;
    00739   ci->client_lang = client_lang;
    00740   DEBUG(desync, 1, "client: %08x; %02x; %02x; %04x", _date, _date_fract, (int)ci->client_playas, ci->index);
    00741
    00742   /* Make sure companies to which people try to join are not autocleaned */
    00743   if (Company::IsValidID(playas)) _network_company_states[playas].months_empty = 0;
    00744
    00745   cs->status = STATUS_NEWGRFS_CHECK;
    00746
    00747   if (_grfconfig == NULL) {
    00748     /* Behave as if we received PACKET_CLIENT_NEWGRFS_CHECKED */
    00749     return RECEIVE_COMMAND(PACKET_CLIENT_NEWGRFS_CHECKED)(cs, NULL);
    00750   }
    00751
    00752   return SEND_COMMAND(PACKET_SERVER_CHECK_NEWGRFS)(cs);
    00753 }
    00754
    00755 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_GAME_PASSWORD)
    00756 {
    00757   if (cs->status != STATUS_AUTH_GAME) {
    00758     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    00759   }
    00760
    00761   char password[NETWORK_PASSWORD_LENGTH];
    00762   p->Recv_string(password, sizeof(password));
    00763
    00764   /* Check game password. Allow joining if we cleared the password meanwhile */
    00765   if (!StrEmpty(_settings_client.network.server_password) &&
    00766       strcmp(password, _settings_client.network.server_password) != 0) {
    00767     /* Password is invalid */
    00768     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_WRONG_PASSWORD);
    00769   }
    00770
    00771   const NetworkClientInfo *ci = cs->GetInfo();
    00772   if (Company::IsValidID(ci->client_playas) && !StrEmpty(_network_company_states[ci->client_playas].password)) {
    00773     return SEND_COMMAND(PACKET_SERVER_NEED_COMPANY_PASSWORD)(cs);
    00774   }
    00775
    00776   /* Valid password, allow user */
    00777   return SEND_COMMAND(PACKET_SERVER_WELCOME)(cs);
    00778 }
    00779
    00780 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_COMPANY_PASSWORD)
    00781 {
    00782   if (cs->status != STATUS_AUTH_COMPANY) {
    00783     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    00784   }
    00785
    00786   char password[NETWORK_PASSWORD_LENGTH];
    00787   p->Recv_string(password, sizeof(password));
    00788
    00789   /* Check company password. Allow joining if we cleared the password meanwhile.
    00790    * Also, check the company is still valid - client could be moved to spectators
    00791    * in the middle of the authorization process */
    00792   CompanyID playas = cs->GetInfo()->client_playas;
    00793   if (Company::IsValidID(playas) && !StrEmpty(_network_company_states[playas].password) &&
    00794       strcmp(password, _network_company_states[playas].password) != 0) {
    00795     /* Password is invalid */
    00796     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_WRONG_PASSWORD);
    00797   }
    00798
    00799   return SEND_COMMAND(PACKET_SERVER_WELCOME)(cs);
    00800 }
    00801
    00802 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_GETMAP)
    00803 {
    00804   NetworkClientSocket *new_cs;
    00805
    00806   /* Do an extra version match. We told the client our version already,
    00807    * lets confirm that the client isn't lieing to us.
    00808    * But only do it for stable releases because of those we are sure
    00809    * that everybody has the same NewGRF version. For trunk and the
    00810    * branches we make tarballs of the OpenTTDs compiled from tarball
    00811    * will have the lower bits set to 0. As such they would become
    00812    * incompatible, which we would like to prevent by this. */
    00813   if (HasBit(_openttd_newgrf_version, 19)) {
    00814     if (_openttd_newgrf_version != p->Recv_uint32()) {
    00815       /* The version we get from the client differs, it must have the
    00816        * wrong version. The client must be wrong. */
    00817       return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    00818     }
    00819   } else if (p->size != 3) {
    00820     /* We received a packet from a version that claims to be stable.
    00821      * That shouldn't happen. The client must be wrong. */
    00822     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    00823   }
    00824
    00825   /* The client was never joined.. so this is impossible, right?
    00826    *  Ignore the packet, give the client a warning, and close his connection */
    00827   if (cs->status < STATUS_AUTHORIZED || cs->HasClientQuit()) {
    00828     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_AUTHORIZED);
    00829   }
    00830
    00831   /* Check if someone else is receiving the map */
    00832   FOR_ALL_CLIENT_SOCKETS(new_cs) {
    00833     if (new_cs->status == STATUS_MAP) {
    00834       /* Tell the new client to wait */
    00835       cs->status = STATUS_MAP_WAIT;
    00836       return SEND_COMMAND(PACKET_SERVER_WAIT)(cs);
    00837     }
    00838   }
    00839
    00840   /* We receive a request to upload the map.. give it to the client! */
    00841   return SEND_COMMAND(PACKET_SERVER_MAP)(cs);
    00842 }
    00843
    00844 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_MAP_OK)
    00845 {
    00846   /* Client has the map, now start syncing */
    00847   if (cs->status == STATUS_DONE_MAP && !cs->HasClientQuit()) {
    00848     char client_name[NETWORK_CLIENT_NAME_LENGTH];
    00849     NetworkClientSocket *new_cs;
    00850
    00851     NetworkGetClientName(client_name, sizeof(client_name), cs);
    00852
    00853     NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, client_name, NULL, cs->client_id);
    00854
    00855     /* Mark the client as pre-active, and wait for an ACK
    00856      *  so we know he is done loading and in sync with us */
    00857     cs->status = STATUS_PRE_ACTIVE;
    00858     NetworkHandleCommandQueue(cs);
    00859     SEND_COMMAND(PACKET_SERVER_FRAME)(cs);
    00860     SEND_COMMAND(PACKET_SERVER_SYNC)(cs);
    00861
    00862     /* This is the frame the client receives
    00863      *  we need it later on to make sure the client is not too slow */
    00864     cs->last_frame = _frame_counter;
    00865     cs->last_frame_server = _frame_counter;
    00866
    00867     FOR_ALL_CLIENT_SOCKETS(new_cs) {
    00868       if (new_cs->status > STATUS_AUTHORIZED) {
    00869         SEND_COMMAND(PACKET_SERVER_CLIENT_INFO)(new_cs, cs->GetInfo());
    00870         SEND_COMMAND(PACKET_SERVER_JOIN)(new_cs, cs->client_id);
    00871       }
    00872     }
    00873
    00874     /* also update the new client with our max values */
    00875     SEND_COMMAND(PACKET_SERVER_CONFIG_UPDATE)(cs);
    00876
    00877     /* quickly update the syncing client with company details */
    00878     return SEND_COMMAND(PACKET_SERVER_COMPANY_UPDATE)(cs);
    00879   }
    00880
    00881   /* Wrong status for this packet, give a warning to client, and close connection */
    00882   return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    00883 }
    00884
    00889 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_COMMAND)
    00890 {
    00891   NetworkClientSocket *new_cs;
    00892
    00893   /* The client was never joined.. so this is impossible, right?
    00894    *  Ignore the packet, give the client a warning, and close his connection */
    00895   if (cs->status < STATUS_DONE_MAP || cs->HasClientQuit()) {
    00896     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    00897   }
    00898
    00899   CommandPacket cp;
    00900   const char *err = cs->Recv_Command(p, &cp);
    00901
    00902   if (cs->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
    00903
    00904   NetworkClientInfo *ci = cs->GetInfo();
    00905
    00906   if (err != NULL) {
    00907     IConsolePrintF(CC_ERROR, "WARNING: %s from client %d (IP: %s).", err, ci->client_id, GetClientIP(ci));
    00908     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    00909   }
    00910
    00911
    00912   if ((GetCommandFlags(cp.cmd) & CMD_SERVER) && ci->client_id != CLIENT_ID_SERVER) {
    00913     IConsolePrintF(CC_ERROR, "WARNING: server only command from: client %d (IP: %s), kicking...", ci->client_id, GetClientIP(ci));
    00914     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_KICKED);
    00915   }
    00916
    00917   if ((GetCommandFlags(cp.cmd) & CMD_SPECTATOR) == 0 && !Company::IsValidID(cp.company) && ci->client_id != CLIENT_ID_SERVER) {
    00918     IConsolePrintF(CC_ERROR, "WARNING: spectator issueing command from client %d (IP: %s), kicking...", ci->client_id, GetClientIP(ci));
    00919     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_KICKED);
    00920   }
    00921
    00926   if (!(cp.cmd == CMD_COMPANY_CTRL && cp.p1 == 0 && ci->client_playas == COMPANY_NEW_COMPANY) && ci->client_playas != cp.company) {
    00927     IConsolePrintF(CC_ERROR, "WARNING: client %d (IP: %s) tried to execute a command as company %d, kicking...",
    00928                    ci->client_playas + 1, GetClientIP(ci), cp.company + 1);
    00929     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_COMPANY_MISMATCH);
    00930   }
    00931
    00937   if (cp.cmd == CMD_COMPANY_CTRL) {
    00938     if (cp.p1 != 0 || cp.company != COMPANY_SPECTATOR) {
    00939       return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_CHEATER);
    00940     }
    00941
    00942     /* Check if we are full - else it's possible for spectators to send a CMD_COMPANY_CTRL and the company is created regardless of max_companies! */
    00943     if (Company::GetNumItems() >= _settings_client.network.max_companies) {
    00944       NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_CLIENT, ci->client_id, "cannot create new company, server full", CLIENT_ID_SERVER);
    00945       return NETWORK_RECV_STATUS_OKAY;
    00946     }
    00947
    00948     cp.p2 = cs->client_id;
    00949   }
    00950
    00951   /* The frame can be executed in the same frame as the next frame-packet
    00952    *  That frame just before that frame is saved in _frame_counter_max */
    00953   cp.frame = _frame_counter_max + 1;
    00954   cp.next  = NULL;
    00955
    00956   CommandCallback *callback = cp.callback;
    00957
    00958   /* Queue the command for the clients (are send at the end of the frame
    00959    *   if they can handle it ;)) */
    00960   FOR_ALL_CLIENT_SOCKETS(new_cs) {
    00961     if (new_cs->status >= STATUS_MAP) {
    00962       /* Callbacks are only send back to the client who sent them in the
    00963        *  first place. This filters that out. */
    00964       cp.callback = (new_cs != cs) ? NULL : callback;
    00965       cp.my_cmd = (new_cs == cs);
    00966       NetworkAddCommandQueue(cp, new_cs);
    00967     }
    00968   }
    00969
    00970   cp.callback = NULL;
    00971   cp.my_cmd = false;
    00972   NetworkAddCommandQueue(cp);
    00973   return NETWORK_RECV_STATUS_OKAY;
    00974 }
    00975
    00976 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_ERROR)
    00977 {
    00978   /* This packets means a client noticed an error and is reporting this
    00979    *  to us. Display the error and report it to the other clients */
    00980   NetworkClientSocket *new_cs;
    00981   char str[100];
    00982   char client_name[NETWORK_CLIENT_NAME_LENGTH];
    00983   NetworkErrorCode errorno = (NetworkErrorCode)p->Recv_uint8();
    00984
    00985   /* The client was never joined.. thank the client for the packet, but ignore it */
    00986   if (cs->status < STATUS_DONE_MAP || cs->HasClientQuit()) {
    00987     cs->CloseConnection();
    00988     return NETWORK_RECV_STATUS_CONN_LOST;
    00989   }
    00990
    00991   NetworkGetClientName(client_name, sizeof(client_name), cs);
    00992
    00993   StringID strid = GetNetworkErrorMsg(errorno);
    00994   GetString(str, strid, lastof(str));
    00995
    00996   DEBUG(net, 2, "'%s' reported an error and is closing its connection (%s)", client_name, str);
    00997
    00998   NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, strid);
    00999
    01000   FOR_ALL_CLIENT_SOCKETS(new_cs) {
    01001     if (new_cs->status > STATUS_AUTHORIZED) {
    01002       SEND_COMMAND(PACKET_SERVER_ERROR_QUIT)(new_cs, cs->client_id, errorno);
    01003     }
    01004   }
    01005
    01006   cs->CloseConnection(false);
    01007   return NETWORK_RECV_STATUS_CONN_LOST;
    01008 }
    01009
    01010 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_QUIT)
    01011 {
    01012   /* The client wants to leave. Display this and report it to the other
    01013    *  clients. */
    01014   NetworkClientSocket *new_cs;
    01015   char client_name[NETWORK_CLIENT_NAME_LENGTH];
    01016
    01017   /* The client was never joined.. thank the client for the packet, but ignore it */
    01018   if (cs->status < STATUS_DONE_MAP || cs->HasClientQuit()) {
    01019     cs->CloseConnection();
    01020     return NETWORK_RECV_STATUS_CONN_LOST;
    01021   }
    01022
    01023   NetworkGetClientName(client_name, sizeof(client_name), cs);
    01024
    01025   NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, STR_NETWORK_MESSAGE_CLIENT_LEAVING);
    01026
    01027   FOR_ALL_CLIENT_SOCKETS(new_cs) {
    01028     if (new_cs->status > STATUS_AUTHORIZED) {
    01029       SEND_COMMAND(PACKET_SERVER_QUIT)(new_cs, cs->client_id);
    01030     }
    01031   }
    01032
    01033   cs->CloseConnection(false);
    01034   return NETWORK_RECV_STATUS_CONN_LOST;
    01035 }
    01036
    01037 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_ACK)
    01038 {
    01039   if (cs->status < STATUS_AUTHORIZED) {
    01040     /* Illegal call, return error and ignore the packet */
    01041     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_AUTHORIZED);
    01042   }
    01043
    01044   uint32 frame = p->Recv_uint32();
    01045
    01046   /* The client is trying to catch up with the server */
    01047   if (cs->status == STATUS_PRE_ACTIVE) {
    01048     /* The client is not yet catched up? */
    01049     if (frame + DAY_TICKS < _frame_counter) return NETWORK_RECV_STATUS_OKAY;
    01050
    01051     /* Now he is! Unpause the game */
    01052     cs->status = STATUS_ACTIVE;
    01053
    01054     /* Execute script for, e.g. MOTD */
    01055     IConsoleCmdExec("exec scripts/on_server_connect.scr 0");
    01056   }
    01057
    01058   /* The client received the frame, make note of it */
    01059   cs->last_frame = frame;
    01060   /* With those 2 values we can calculate the lag realtime */
    01061   cs->last_frame_server = _frame_counter;
    01062   return NETWORK_RECV_STATUS_OKAY;
    01063 }
    01064
    01065
    01066
    01067 void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, const char *msg, ClientID from_id, int64 data)
    01068 {
    01069   NetworkClientSocket *cs;
    01070   const NetworkClientInfo *ci, *ci_own, *ci_to;
    01071
    01072   switch (desttype) {
    01073   case DESTTYPE_CLIENT:
    01074     /* Are we sending to the server? */
    01075     if ((ClientID)dest == CLIENT_ID_SERVER) {
    01076       ci = NetworkFindClientInfoFromClientID(from_id);
    01077       /* Display the text locally, and that is it */
    01078       if (ci != NULL)
    01079         NetworkTextMessage(action, (ConsoleColour)GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
    01080     } else {
    01081       /* Else find the client to send the message to */
    01082       FOR_ALL_CLIENT_SOCKETS(cs) {
    01083         if (cs->client_id == (ClientID)dest) {
    01084           SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, from_id, false, msg, data);
    01085           break;
    01086         }
    01087       }
    01088     }
    01089
    01090     /* Display the message locally (so you know you have sent it) */
    01091     if (from_id != (ClientID)dest) {
    01092       if (from_id == CLIENT_ID_SERVER) {
    01093         ci = NetworkFindClientInfoFromClientID(from_id);
    01094         ci_to = NetworkFindClientInfoFromClientID((ClientID)dest);
    01095         if (ci != NULL && ci_to != NULL)
    01096           NetworkTextMessage(action, (ConsoleColour)GetDrawStringCompanyColour(ci->client_playas), true, ci_to->client_name, msg, data);
    01097       } else {
    01098         FOR_ALL_CLIENT_SOCKETS(cs) {
    01099           if (cs->client_id == from_id) {
    01100             SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, (ClientID)dest, true, msg, data);
    01101             break;
    01102           }
    01103         }
    01104       }
    01105     }
    01106     break;
    01107   case DESTTYPE_TEAM: {
    01108     /* If this is false, the message is already displayed on the client who sent it. */
    01109     bool show_local = true;
    01110     /* Find all clients that belong to this company */
    01111     ci_to = NULL;
    01112     FOR_ALL_CLIENT_SOCKETS(cs) {
    01113       ci = cs->GetInfo();
    01114       if (ci->client_playas == (CompanyID)dest) {
    01115         SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, from_id, false, msg, data);
    01116         if (cs->client_id == from_id) show_local = false;
    01117         ci_to = ci; // Remember a client that is in the company for company-name
    01118       }
    01119     }
    01120
    01121     ci = NetworkFindClientInfoFromClientID(from_id);
    01122     ci_own = NetworkFindClientInfoFromClientID(CLIENT_ID_SERVER);
    01123     if (ci != NULL && ci_own != NULL && ci_own->client_playas == dest) {
    01124       NetworkTextMessage(action, (ConsoleColour)GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
    01125       if (from_id == CLIENT_ID_SERVER) show_local = false;
    01126       ci_to = ci_own;
    01127     }
    01128
    01129     /* There is no such client */
    01130     if (ci_to == NULL) break;
    01131
    01132     /* Display the message locally (so you know you have sent it) */
    01133     if (ci != NULL && show_local) {
    01134       if (from_id == CLIENT_ID_SERVER) {
    01135         char name[NETWORK_NAME_LENGTH];
    01136         StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
    01137         SetDParam(0, ci_to->client_playas);
    01138         GetString(name, str, lastof(name));
    01139         NetworkTextMessage(action, (ConsoleColour)GetDrawStringCompanyColour(ci_own->client_playas), true, name, msg, data);
    01140       } else {
    01141         FOR_ALL_CLIENT_SOCKETS(cs) {
    01142           if (cs->client_id == from_id) {
    01143             SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, ci_to->client_id, true, msg, data);
    01144           }
    01145         }
    01146       }
    01147     }
    01148     }
    01149     break;
    01150   default:
    01151     DEBUG(net, 0, "[server] received unknown chat destination type %d. Doing broadcast instead", desttype);
    01152     /* fall-through to next case */
    01153   case DESTTYPE_BROADCAST:
    01154     FOR_ALL_CLIENT_SOCKETS(cs) {
    01155       SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, from_id, false, msg, data);
    01156     }
    01157     ci = NetworkFindClientInfoFromClientID(from_id);
    01158     if (ci != NULL)
    01159       NetworkTextMessage(action, (ConsoleColour)GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
    01160     break;
    01161   }
    01162 }
    01163
    01164 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_CHAT)
    01165 {
    01166   if (cs->status < STATUS_AUTHORIZED) {
    01167     /* Illegal call, return error and ignore the packet */
    01168     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_AUTHORIZED);
    01169   }
    01170
    01171   NetworkAction action = (NetworkAction)p->Recv_uint8();
    01172   DestType desttype = (DestType)p->Recv_uint8();
    01173   int dest = p->Recv_uint32();
    01174   char msg[NETWORK_CHAT_LENGTH];
    01175
    01176   p->Recv_string(msg, NETWORK_CHAT_LENGTH);
    01177   int64 data = p->Recv_uint64();
    01178
    01179   NetworkClientInfo *ci = cs->GetInfo();
    01180   switch (action) {
    01181     case NETWORK_ACTION_GIVE_MONEY:
    01182       if (!Company::IsValidID(ci->client_playas)) break;
    01183       /* Fall-through */
    01184     case NETWORK_ACTION_CHAT:
    01185     case NETWORK_ACTION_CHAT_CLIENT:
    01186     case NETWORK_ACTION_CHAT_COMPANY:
    01187       NetworkServerSendChat(action, desttype, dest, msg, cs->client_id, data);
    01188       break;
    01189     default:
    01190       IConsolePrintF(CC_ERROR, "WARNING: invalid chat action from client %d (IP: %s).", ci->client_id, GetClientIP(ci));
    01191       return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    01192       break;
    01193   }
    01194   return NETWORK_RECV_STATUS_OKAY;
    01195 }
    01196
    01197 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_SET_PASSWORD)
    01198 {
    01199   if (cs->status != STATUS_ACTIVE) {
    01200     /* Illegal call, return error and ignore the packet */
    01201     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    01202   }
    01203
    01204   char password[NETWORK_PASSWORD_LENGTH];
    01205   const NetworkClientInfo *ci;
    01206
    01207   p->Recv_string(password, sizeof(password));
    01208   ci = cs->GetInfo();
    01209
    01210   if (Company::IsValidID(ci->client_playas)) {
    01211     strecpy(_network_company_states[ci->client_playas].password, password, lastof(_network_company_states[ci->client_playas].password));
    01212     NetworkServerUpdateCompanyPassworded(ci->client_playas, !StrEmpty(_network_company_states[ci->client_playas].password));
    01213   }
    01214   return NETWORK_RECV_STATUS_OKAY;
    01215 }
    01216
    01217 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_SET_NAME)
    01218 {
    01219   if (cs->status != STATUS_ACTIVE) {
    01220     /* Illegal call, return error and ignore the packet */
    01221     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    01222   }
    01223
    01224   char client_name[NETWORK_CLIENT_NAME_LENGTH];
    01225   NetworkClientInfo *ci;
    01226
    01227   p->Recv_string(client_name, sizeof(client_name));
    01228   ci = cs->GetInfo();
    01229
    01230   if (cs->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
    01231
    01232   if (ci != NULL) {
    01233     /* Display change */
    01234     if (NetworkFindName(client_name)) {
    01235       NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, client_name);
    01236       strecpy(ci->client_name, client_name, lastof(ci->client_name));
    01237       NetworkUpdateClientInfo(ci->client_id);
    01238     }
    01239   }
    01240   return NETWORK_RECV_STATUS_OKAY;
    01241 }
    01242
    01243 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_RCON)
    01244 {
    01245   char pass[NETWORK_PASSWORD_LENGTH];
    01246   char command[NETWORK_RCONCOMMAND_LENGTH];
    01247
    01248   if (StrEmpty(_settings_client.network.rcon_password)) return NETWORK_RECV_STATUS_OKAY;
    01249
    01250   p->Recv_string(pass, sizeof(pass));
    01251   p->Recv_string(command, sizeof(command));
    01252
    01253   if (strcmp(pass, _settings_client.network.rcon_password) != 0) {
    01254     DEBUG(net, 0, "[rcon] wrong password from client-id %d", cs->client_id);
    01255     return NETWORK_RECV_STATUS_OKAY;
    01256   }
    01257
    01258   DEBUG(net, 0, "[rcon] client-id %d executed: '%s'", cs->client_id, command);
    01259
    01260   _redirect_console_to_client = cs->client_id;
    01261   IConsoleCmdExec(command);
    01262   _redirect_console_to_client = INVALID_CLIENT_ID;
    01263   return NETWORK_RECV_STATUS_OKAY;
    01264 }
    01265
    01266 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_MOVE)
    01267 {
    01268   CompanyID company_id = (Owner)p->Recv_uint8();
    01269
    01270   /* Check if the company is valid, we don't allow moving to AI companies */
    01271   if (company_id != COMPANY_SPECTATOR && !Company::IsValidHumanID(company_id)) return NETWORK_RECV_STATUS_OKAY;
    01272
    01273   /* Check if we require a password for this company */
    01274   if (company_id != COMPANY_SPECTATOR && !StrEmpty(_network_company_states[company_id].password)) {
    01275     /* we need a password from the client - should be in this packet */
    01276     char password[NETWORK_PASSWORD_LENGTH];
    01277     p->Recv_string(password, sizeof(password));
    01278
    01279     /* Incorrect password sent, return! */
    01280     if (strcmp(password, _network_company_states[company_id].password) != 0) {
    01281       DEBUG(net, 2, "[move] wrong password from client-id #%d for company #%d", cs->client_id, company_id + 1);
    01282       return NETWORK_RECV_STATUS_OKAY;
    01283     }
    01284   }
    01285
    01286   /* if we get here we can move the client */
    01287   NetworkServerDoMove(cs->client_id, company_id);
    01288   return NETWORK_RECV_STATUS_OKAY;
    01289 }
    01290
    01291 /* The layout for the receive-functions by the server */
    01292 typedef NetworkRecvStatus NetworkServerPacket(NetworkClientSocket *cs, Packet *p);
    01293
    01294
    01295 /* This array matches PacketType. At an incoming
    01296  *  packet it is matches against this array
    01297  *  and that way the right function to handle that
    01298  *  packet is found. */
    01299 static NetworkServerPacket * const _network_server_packet[] = {
    01300   NULL, // PACKET_SERVER_FULL,
    01301   NULL, // PACKET_SERVER_BANNED,
    01302   RECEIVE_COMMAND(PACKET_CLIENT_JOIN),
    01303   NULL, // PACKET_SERVER_ERROR,
    01304   RECEIVE_COMMAND(PACKET_CLIENT_COMPANY_INFO),
    01305   NULL, // PACKET_SERVER_COMPANY_INFO,
    01306   NULL, // PACKET_SERVER_CLIENT_INFO,
    01307   NULL, // PACKET_SERVER_NEED_GAME_PASSWORD,
    01308   NULL, // PACKET_SERVER_NEED_COMPANY_PASSWORD,
    01309   RECEIVE_COMMAND(PACKET_CLIENT_GAME_PASSWORD),
    01310   RECEIVE_COMMAND(PACKET_CLIENT_COMPANY_PASSWORD),
    01311   NULL, // PACKET_SERVER_WELCOME,
    01312   RECEIVE_COMMAND(PACKET_CLIENT_GETMAP),
    01313   NULL, // PACKET_SERVER_WAIT,
    01314   NULL, // PACKET_SERVER_MAP,
    01315   RECEIVE_COMMAND(PACKET_CLIENT_MAP_OK),
    01316   NULL, // PACKET_SERVER_JOIN,
    01317   NULL, // PACKET_SERVER_FRAME,
    01318   NULL, // PACKET_SERVER_SYNC,
    01319   RECEIVE_COMMAND(PACKET_CLIENT_ACK),
    01320   RECEIVE_COMMAND(PACKET_CLIENT_COMMAND),
    01321   NULL, // PACKET_SERVER_COMMAND,
    01322   RECEIVE_COMMAND(PACKET_CLIENT_CHAT),
    01323   NULL, // PACKET_SERVER_CHAT,
    01324   RECEIVE_COMMAND(PACKET_CLIENT_SET_PASSWORD),
    01325   RECEIVE_COMMAND(PACKET_CLIENT_SET_NAME),
    01326   RECEIVE_COMMAND(PACKET_CLIENT_QUIT),
    01327   RECEIVE_COMMAND(PACKET_CLIENT_ERROR),
    01328   NULL, // PACKET_SERVER_QUIT,
    01329   NULL, // PACKET_SERVER_ERROR_QUIT,
    01330   NULL, // PACKET_SERVER_SHUTDOWN,
    01331   NULL, // PACKET_SERVER_NEWGAME,
    01332   NULL, // PACKET_SERVER_RCON,
    01333   RECEIVE_COMMAND(PACKET_CLIENT_RCON),
    01334   NULL, // PACKET_CLIENT_CHECK_NEWGRFS,
    01335   RECEIVE_COMMAND(PACKET_CLIENT_NEWGRFS_CHECKED),
    01336   NULL, // PACKET_SERVER_MOVE,
    01337   RECEIVE_COMMAND(PACKET_CLIENT_MOVE),
    01338   NULL, // PACKET_SERVER_COMPANY_UPDATE,
    01339   NULL, // PACKET_SERVER_CONFIG_UPDATE,
    01340 };
    01341
    01342 /* If this fails, check the array above with network_data.h */
    01343 assert_compile(lengthof(_network_server_packet) == PACKET_END);
    01344
    01345 void NetworkSocketHandler::Send_CompanyInformation(Packet *p, const Company *c, const NetworkCompanyStats *stats)
    01346 {
    01347   /* Grab the company name */
    01348   char company_name[NETWORK_COMPANY_NAME_LENGTH];
    01349   SetDParam(0, c->index);
    01350   GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
    01351
    01352   /* Get the income */
    01353   Money income = 0;
    01354   if (_cur_year - 1 == c->inaugurated_year) {
    01355     /* The company is here just 1 year, so display [2], else display[1] */
    01356     for (uint i = 0; i < lengthof(c->yearly_expenses[2]); i++) {
    01357       income -= c->yearly_expenses[2][i];
    01358     }
    01359   } else {
    01360     for (uint i = 0; i < lengthof(c->yearly_expenses[1]); i++) {
    01361       income -= c->yearly_expenses[1][i];
    01362     }
    01363   }
    01364
    01365   /* Send the information */
    01366   p->Send_uint8 (c->index);
    01367   p->Send_string(company_name);
    01368   p->Send_uint32(c->inaugurated_year);
    01369   p->Send_uint64(c->old_economy[0].company_value);
    01370   p->Send_uint64(c->money);
    01371   p->Send_uint64(income);
    01372   p->Send_uint16(c->old_economy[0].performance_history);
    01373
    01374   /* Send 1 if there is a passord for the company else send 0 */
    01375   p->Send_bool  (!StrEmpty(_network_company_states[c->index].password));
    01376
    01377   for (int i = 0; i < NETWORK_VEHICLE_TYPES; i++) {
    01378     p->Send_uint16(stats->num_vehicle[i]);
    01379   }
    01380
    01381   for (int i = 0; i < NETWORK_STATION_TYPES; i++) {
    01382     p->Send_uint16(stats->num_station[i]);
    01383   }
    01384
    01385   p->Send_bool(c->is_ai);
    01386 }
    01387
    01392 void NetworkPopulateCompanyStats(NetworkCompanyStats *stats)
    01393 {
    01394   const Vehicle *v;
    01395   const Station *s;
    01396
    01397   memset(stats, 0, sizeof(*stats) * MAX_COMPANIES);
    01398
    01399   /* Go through all vehicles and count the type of vehicles */
    01400   FOR_ALL_VEHICLES(v) {
    01401     if (!Company::IsValidID(v->owner) || !v->IsPrimaryVehicle()) continue;
    01402     byte type = 0;
    01403     switch (v->type) {
    01404       case VEH_TRAIN: type = 0; break;
    01405       case VEH_ROAD: type = RoadVehicle::From(v)->IsBus() ? 2 : 1; break;
    01406       case VEH_AIRCRAFT: type = 3; break;
    01407       case VEH_SHIP: type = 4; break;
    01408       default: continue;
    01409     }
    01410     stats[v->owner].num_vehicle[type]++;
    01411   }
    01412
    01413   /* Go through all stations and count the types of stations */
    01414   FOR_ALL_STATIONS(s) {
    01415     if (Company::IsValidID(s->owner)) {
    01416       NetworkCompanyStats *npi = &stats[s->owner];
    01417
    01418       if (s->facilities & FACIL_TRAIN)      npi->num_station[0]++;
    01419       if (s->facilities & FACIL_TRUCK_STOP) npi->num_station[1]++;
    01420       if (s->facilities & FACIL_BUS_STOP)   npi->num_station[2]++;
    01421       if (s->facilities & FACIL_AIRPORT)    npi->num_station[3]++;
    01422       if (s->facilities & FACIL_DOCK)       npi->num_station[4]++;
    01423     }
    01424   }
    01425 }
    01426
    01427 /* Send a packet to all clients with updated info about this client_id */
    01428 void NetworkUpdateClientInfo(ClientID client_id)
    01429 {
    01430   NetworkClientSocket *cs;
    01431   NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(client_id);
    01432
    01433   if (ci == NULL) return;
    01434
    01435   DEBUG(desync, 1, "client: %08x; %02x; %02x; %04x", _date, _date_fract, (int)ci->client_playas, client_id);
    01436
    01437   FOR_ALL_CLIENT_SOCKETS(cs) {
    01438     SEND_COMMAND(PACKET_SERVER_CLIENT_INFO)(cs, ci);
    01439   }
    01440 }
    01441
    01442 /* Check if we want to restart the map */
    01443 static void NetworkCheckRestartMap()
    01444 {
    01445   if (_settings_client.network.restart_game_year != 0 && _cur_year >= _settings_client.network.restart_game_year) {
    01446     DEBUG(net, 0, "Auto-restarting map. Year %d reached", _cur_year);
    01447
    01448     StartNewGameWithoutGUI(GENERATE_NEW_SEED);
    01449   }
    01450 }
    01451
    01452 /* Check if the server has autoclean_companies activated
    01453     Two things happen:
    01454       1) If a company is not protected, it is closed after 1 year (for example)
    01455       2) If a company is protected, protection is disabled after 3 years (for example)
    01456            (and item 1. happens a year later) */
    01457 static void NetworkAutoCleanCompanies()
    01458 {
    01459   const NetworkClientInfo *ci;
    01460   const Company *c;
    01461   bool clients_in_company[MAX_COMPANIES];
    01462   int vehicles_in_company[MAX_COMPANIES];
    01463
    01464   if (!_settings_client.network.autoclean_companies) return;
    01465
    01466   memset(clients_in_company, 0, sizeof(clients_in_company));
    01467
    01468   /* Detect the active companies */
    01469   FOR_ALL_CLIENT_INFOS(ci) {
    01470     if (Company::IsValidID(ci->client_playas)) clients_in_company[ci->client_playas] = true;
    01471   }
    01472
    01473   if (!_network_dedicated) {
    01474     ci = NetworkFindClientInfoFromClientID(CLIENT_ID_SERVER);
    01475     if (Company::IsValidID(ci->client_playas)) clients_in_company[ci->client_playas] = true;
    01476   }
    01477
    01478   if (_settings_client.network.autoclean_novehicles != 0) {
    01479     memset(vehicles_in_company, 0, sizeof(vehicles_in_company));
    01480
    01481     const Vehicle *v;
    01482     FOR_ALL_VEHICLES(v) {
    01483       if (!Company::IsValidID(v->owner) || !v->IsPrimaryVehicle()) continue;
    01484       vehicles_in_company[v->owner]++;
    01485     }
    01486   }
    01487
    01488   /* Go through all the comapnies */
    01489   FOR_ALL_COMPANIES(c) {
    01490     /* Skip the non-active once */
    01491     if (c->is_ai) continue;
    01492
    01493     if (!clients_in_company[c->index]) {
    01494       /* The company is empty for one month more */
    01495       _network_company_states[c->index].months_empty++;
    01496
    01497       /* Is the company empty for autoclean_unprotected-months, and is there no protection? */
    01498       if (_settings_client.network.autoclean_unprotected != 0 && _network_company_states[c->index].months_empty > _settings_client.network.autoclean_unprotected && StrEmpty(_network_company_states[c->index].password)) {
    01499         /* Shut the company down */
    01500         DoCommandP(0, 2, c->index, CMD_COMPANY_CTRL);
    01501         IConsolePrintF(CC_DEFAULT, "Auto-cleaned company #%d with no password", c->index + 1);
    01502       }
    01503       /* Is the company empty for autoclean_protected-months, and there is a protection? */
    01504       if (_settings_client.network.autoclean_protected != 0 && _network_company_states[c->index].months_empty > _settings_client.network.autoclean_protected && !StrEmpty(_network_company_states[c->index].password)) {
    01505         /* Unprotect the company */
    01506         _network_company_states[c->index].password[0] = '\0';
    01507         IConsolePrintF(CC_DEFAULT, "Auto-removed protection from company #%d", c->index + 1);
    01508         _network_company_states[c->index].months_empty = 0;
    01509         NetworkServerUpdateCompanyPassworded(c->index, false);
    01510       }
    01511       /* Is the company empty for autoclean_novehicles-months, and has no vehicles? */
    01512       if (_settings_client.network.autoclean_novehicles != 0 && _network_company_states[c->index].months_empty > _settings_client.network.autoclean_novehicles && vehicles_in_company[c->index] == 0) {
    01513         /* Shut the company down */
    01514         DoCommandP(0, 2, c->index, CMD_COMPANY_CTRL);
    01515         IConsolePrintF(CC_DEFAULT, "Auto-cleaned company #%d with no vehicles", c->index + 1);
    01516       }
    01517     } else {
    01518       /* It is not empty, reset the date */
    01519       _network_company_states[c->index].months_empty = 0;
    01520     }
    01521   }
    01522 }
    01523
    01524 /* This function changes new_name to a name that is unique (by adding #1 ...)
    01525  *  and it returns true if that succeeded. */
    01526 bool NetworkFindName(char new_name[NETWORK_CLIENT_NAME_LENGTH])
    01527 {
    01528   bool found_name = false;
    01529   uint number = 0;
    01530   char original_name[NETWORK_CLIENT_NAME_LENGTH];
    01531
    01532   /* We use NETWORK_CLIENT_NAME_LENGTH in here, because new_name is really a pointer */
    01533   ttd_strlcpy(original_name, new_name, NETWORK_CLIENT_NAME_LENGTH);
    01534
    01535   while (!found_name) {
    01536     const NetworkClientInfo *ci;
    01537
    01538     found_name = true;
    01539     FOR_ALL_CLIENT_INFOS(ci) {
    01540       if (strcmp(ci->client_name, new_name) == 0) {
    01541         /* Name already in use */
    01542         found_name = false;
    01543         break;
    01544       }
    01545     }
    01546     /* Check if it is the same as the server-name */
    01547     ci = NetworkFindClientInfoFromClientID(CLIENT_ID_SERVER);
    01548     if (ci != NULL) {
    01549       if (strcmp(ci->client_name, new_name) == 0) found_name = false; // name already in use
    01550     }
    01551
    01552     if (!found_name) {
    01553       /* Try a new name (<name> #1, <name> #2, and so on) */
    01554
    01555       /* Something's really wrong when there're more names than clients */
    01556       if (number++ > MAX_CLIENTS) break;
    01557       snprintf(new_name, NETWORK_CLIENT_NAME_LENGTH, "%s #%d", original_name, number);
    01558     }
    01559   }
    01560
    01561   return found_name;
    01562 }
    01563
    01570 bool NetworkServerChangeClientName(ClientID client_id, const char *new_name)
    01571 {
    01572   NetworkClientInfo *ci;
    01573   /* Check if the name's already in use */
    01574   FOR_ALL_CLIENT_INFOS(ci) {
    01575     if (strcmp(ci->client_name, new_name) == 0) return false;
    01576   }
    01577
    01578   ci = NetworkFindClientInfoFromClientID(client_id);
    01579   if (ci == NULL) return false;
    01580
    01581   NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, true, ci->client_name, new_name);
    01582
    01583   strecpy(ci->client_name, new_name, lastof(ci->client_name));
    01584
    01585   NetworkUpdateClientInfo(client_id);
    01586   return true;
    01587 }
    01588
    01589 /* Reads a packet from the stream */
    01590 void NetworkServer_ReadPackets(NetworkClientSocket *cs)
    01591 {
    01592   Packet *p;
    01593   NetworkRecvStatus res = NETWORK_RECV_STATUS_OKAY;
    01594
    01595   while (res == NETWORK_RECV_STATUS_OKAY && (p = cs->Recv_Packet()) != NULL) {
    01596     byte type = p->Recv_uint8();
    01597     if (type < PACKET_END && _network_server_packet[type] != NULL && !cs->HasClientQuit()) {
    01598       res = _network_server_packet[type](cs, p);
    01599     } else {
    01600       cs->CloseConnection();
    01601       res = NETWORK_RECV_STATUS_MALFORMED_PACKET;
    01602       DEBUG(net, 0, "[server] received invalid packet type %d", type);
    01603     }
    01604
    01605     delete p;
    01606   }
    01607 }
    01608
    01609 /* Handle the local command-queue */
    01610 static void NetworkHandleCommandQueue(NetworkClientSocket *cs)
    01611 {
    01612   CommandPacket *cp;
    01613
    01614   while ( (cp = cs->command_queue) != NULL) {
    01615     SEND_COMMAND(PACKET_SERVER_COMMAND)(cs, cp);
    01616
    01617     cs->command_queue = cp->next;
    01618     free(cp);
    01619   }
    01620 }
    01621
    01622 /* This is called every tick if this is a _network_server */
    01623 void NetworkServer_Tick(bool send_frame)
    01624 {
    01625   NetworkClientSocket *cs;
    01626 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
    01627   bool send_sync = false;
    01628 #endif
    01629
    01630 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
    01631   if (_frame_counter >= _last_sync_frame + _settings_client.network.sync_freq) {
    01632     _last_sync_frame = _frame_counter;
    01633     send_sync = true;
    01634   }
    01635 #endif
    01636
    01637   /* Now we are done with the frame, inform the clients that they can
    01638    *  do their frame! */
    01639   FOR_ALL_CLIENT_SOCKETS(cs) {
    01640     /* Check if the speed of the client is what we can expect from a client */
    01641     if (cs->status == STATUS_ACTIVE) {
    01642       /* 1 lag-point per day */
    01643       int lag = NetworkCalculateLag(cs) / DAY_TICKS;
    01644       if (lag > 0) {
    01645         if (lag > 3) {
    01646           /* Client did still not report in after 4 game-day, drop him
    01647            *  (that is, the 3 of above, + 1 before any lag is counted) */
    01648           IConsolePrintF(CC_ERROR,"Client #%d is dropped because the client did not respond for more than 4 game-days", cs->client_id);
    01649           NetworkCloseClient(cs, NETWORK_RECV_STATUS_SERVER_ERROR);
    01650           continue;
    01651         }
    01652
    01653         /* Report once per time we detect the lag */
    01654         if (cs->lag_test == 0) {
    01655           IConsolePrintF(CC_WARNING,"[%d] Client #%d is slow, try increasing *net_frame_freq to a higher value!", _frame_counter, cs->client_id);
    01656           cs->lag_test = 1;
    01657         }
    01658       } else {
    01659         cs->lag_test = 0;
    01660       }
    01661     } else if (cs->status == STATUS_PRE_ACTIVE) {
    01662       int lag = NetworkCalculateLag(cs);
    01663       if (lag > _settings_client.network.max_join_time) {
    01664         IConsolePrintF(CC_ERROR,"Client #%d is dropped because it took longer than %d ticks for him to join", cs->client_id, _settings_client.network.max_join_time);
    01665         NetworkCloseClient(cs, NETWORK_RECV_STATUS_SERVER_ERROR);
    01666       }
    01667     } else if (cs->status == STATUS_INACTIVE) {
    01668       int lag = NetworkCalculateLag(cs);
    01669       if (lag > 4 * DAY_TICKS) {
    01670         IConsolePrintF(CC_ERROR,"Client #%d is dropped because it took longer than %d ticks to start the joining process", cs->client_id, 4 * DAY_TICKS);
    01671         NetworkCloseClient(cs, NETWORK_RECV_STATUS_SERVER_ERROR);
    01672       }
    01673     }
    01674
    01675     if (cs->status >= STATUS_PRE_ACTIVE) {
    01676       /* Check if we can send command, and if we have anything in the queue */
    01677       NetworkHandleCommandQueue(cs);
    01678
    01679       /* Send an updated _frame_counter_max to the client */
    01680       if (send_frame) SEND_COMMAND(PACKET_SERVER_FRAME)(cs);
    01681
    01682 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
    01683       /* Send a sync-check packet */
    01684       if (send_sync) SEND_COMMAND(PACKET_SERVER_SYNC)(cs);
    01685 #endif
    01686     }
    01687   }
    01688
    01689   /* See if we need to advertise */
    01690   NetworkUDPAdvertise();
    01691 }
    01692
    01693 void NetworkServerYearlyLoop()
    01694 {
    01695   NetworkCheckRestartMap();
    01696 }
    01697
    01698 void NetworkServerMonthlyLoop()
    01699 {
    01700   NetworkAutoCleanCompanies();
    01701 }
    01702
    01703 const char *GetClientIP(NetworkClientInfo *ci)
    01704 {
    01705   return ci->client_address.GetHostname();
    01706 }
    01707
    01708 void NetworkServerShowStatusToConsole()
    01709 {
    01710   static const char * const stat_str[] = {
    01711     "inactive",
    01712     "checking NewGRFs",
    01713     "authorizing (server password)",
    01714     "authorizing (company password)",
    01715     "authorized",
    01716     "waiting",
    01717     "loading map",
    01718     "map done",
    01719     "ready",
    01720     "active"
    01721   };
    01722   assert_compile(lengthof(stat_str) == STATUS_END);
    01723
    01724   NetworkClientSocket *cs;
    01725   FOR_ALL_CLIENT_SOCKETS(cs) {
    01726     int lag = NetworkCalculateLag(cs);
    01727     NetworkClientInfo *ci = cs->GetInfo();
    01728     const char *status;
    01729
    01730     status = (cs->status < (ptrdiff_t)lengthof(stat_str) ? stat_str[cs->status] : "unknown");
    01731     IConsolePrintF(CC_INFO, "Client #%1d  name: '%s'  status: '%s'  frame-lag: %3d  company: %1d  IP: %s",
    01732       cs->client_id, ci->client_name, status, lag,
    01733       ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0),
    01734       GetClientIP(ci));
    01735   }
    01736 }
    01737
    01741 void NetworkServerSendConfigUpdate()
    01742 {
    01743   NetworkClientSocket *cs;
    01744
    01745   FOR_ALL_CLIENT_SOCKETS(cs) {
    01746     SEND_COMMAND(PACKET_SERVER_CONFIG_UPDATE)(cs);
    01747   }
    01748 }
    01749
    01750 void NetworkServerUpdateCompanyPassworded(CompanyID company_id, bool passworded)
    01751 {
    01752   if (NetworkCompanyIsPassworded(company_id) == passworded) return;
    01753
    01754   SB(_network_company_passworded, company_id, 1, !!passworded);
    01755   SetWindowClassesDirty(WC_COMPANY);
    01756
    01757   NetworkClientSocket *cs;
    01758   FOR_ALL_CLIENT_SOCKETS(cs) {
    01759     SEND_COMMAND(PACKET_SERVER_COMPANY_UPDATE)(cs);
    01760   }
    01761 }
    01762
    01769 void NetworkServerDoMove(ClientID client_id, CompanyID company_id)
    01770 {
    01771   /* Only allow non-dedicated servers and normal clients to be moved */
    01772   if (client_id == CLIENT_ID_SERVER && _network_dedicated) return;
    01773
    01774   NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(client_id);
    01775
    01776   /* No need to waste network resources if the client is in the company already! */
    01777   if (ci->client_playas == company_id) return;
    01778
    01779   ci->client_playas = company_id;
    01780
    01781   if (client_id == CLIENT_ID_SERVER) {
    01782     SetLocalCompany(company_id);
    01783   } else {
    01784     SEND_COMMAND(PACKET_SERVER_MOVE)(NetworkFindClientStateFromClientID(client_id), client_id, company_id);
    01785   }
    01786
    01787   /* announce the client's move */
    01788   NetworkUpdateClientInfo(client_id);
    01789
    01790   NetworkAction action = (company_id == COMPANY_SPECTATOR) ? NETWORK_ACTION_COMPANY_SPECTATOR : NETWORK_ACTION_COMPANY_JOIN;
    01791   NetworkServerSendChat(action, DESTTYPE_BROADCAST, 0, "", client_id, company_id + 1);
    01792 }
    01793
    01794 void NetworkServerSendRcon(ClientID client_id, ConsoleColour colour_code, const char *string)
    01795 {
    01796   SEND_COMMAND(PACKET_SERVER_RCON)(NetworkFindClientStateFromClientID(client_id), colour_code, string);
    01797 }
    01798
    01799 void NetworkServerSendError(ClientID client_id, NetworkErrorCode error)
    01800 {
    01801   SEND_COMMAND(PACKET_SERVER_ERROR)(NetworkFindClientStateFromClientID(client_id), error);
    01802 }
    01803
    01804 void NetworkServerKickClient(ClientID client_id)
    01805 {
    01806   if (client_id == CLIENT_ID_SERVER) return;
    01807   NetworkServerSendError(client_id, NETWORK_ERROR_KICKED);
    01808 }
    01809
    01810 uint NetworkServerKickOrBanIP(const char *ip, bool ban)
    01811 {
    01812   /* Add address to ban-list */
    01813   if (ban) *_network_ban_list.Append() = strdup(ip);
    01814
    01815   uint n = 0;
    01816
    01817   /* There can be multiple clients with the same IP, kick them all */
    01818   NetworkClientInfo *ci;
    01819   FOR_ALL_CLIENT_INFOS(ci) {
    01820     if (ci->client_id == CLIENT_ID_SERVER) continue;
    01821     if (ci->client_address.IsInNetmask(const_cast<char *>(ip))) {
    01822       NetworkServerKickClient(ci->client_id);
    01823       n++;
    01824     }
    01825   }
    01826
    01827   return n;
    01828 }
    01829
    01830 bool NetworkCompanyHasClients(CompanyID company)
    01831 {
    01832   const NetworkClientInfo *ci;
    01833   FOR_ALL_CLIENT_INFOS(ci) {
    01834     if (ci->client_playas == company) return true;
    01835   }
    01836   return false;
    01837 }
    01838
    01839 #endif /* ENABLE_NETWORK */