# network_server.cpp

Go to the documentation of this file.

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