# network_server.cpp

Go to the documentation of this file.

    00001 /* $Id: network_server.cpp 19741 2010-04-30 21:01:21Z 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_INACTIVE) {
    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   if (_grfconfig == NULL) {
    00747     return RECEIVE_COMMAND(PACKET_CLIENT_NEWGRFS_CHECKED)(cs, NULL);
    00748   }
    00749
    00750   return SEND_COMMAND(PACKET_SERVER_CHECK_NEWGRFS)(cs);
    00751 }
    00752
    00753 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_GAME_PASSWORD)
    00754 {
    00755   if (cs->status != STATUS_AUTH_GAME) {
    00756     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    00757   }
    00758
    00759   char password[NETWORK_PASSWORD_LENGTH];
    00760   p->Recv_string(password, sizeof(password));
    00761
    00762   /* Check game password. Allow joining if we cleared the password meanwhile */
    00763   if (!StrEmpty(_settings_client.network.server_password) &&
    00764       strcmp(password, _settings_client.network.server_password) != 0) {
    00765     /* Password is invalid */
    00766     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_WRONG_PASSWORD);
    00767   }
    00768
    00769   const NetworkClientInfo *ci = cs->GetInfo();
    00770   if (Company::IsValidID(ci->client_playas) && !StrEmpty(_network_company_states[ci->client_playas].password)) {
    00771     return SEND_COMMAND(PACKET_SERVER_NEED_COMPANY_PASSWORD)(cs);
    00772   }
    00773
    00774   /* Valid password, allow user */
    00775   return SEND_COMMAND(PACKET_SERVER_WELCOME)(cs);
    00776 }
    00777
    00778 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_COMPANY_PASSWORD)
    00779 {
    00780   if (cs->status != STATUS_AUTH_COMPANY) {
    00781     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    00782   }
    00783
    00784   char password[NETWORK_PASSWORD_LENGTH];
    00785   p->Recv_string(password, sizeof(password));
    00786
    00787   /* Check company password. Allow joining if we cleared the password meanwhile.
    00788    * Also, check the company is still valid - client could be moved to spectators
    00789    * in the middle of the authorization process */
    00790   CompanyID playas = cs->GetInfo()->client_playas;
    00791   if (Company::IsValidID(playas) && !StrEmpty(_network_company_states[playas].password) &&
    00792       strcmp(password, _network_company_states[playas].password) != 0) {
    00793     /* Password is invalid */
    00794     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_WRONG_PASSWORD);
    00795   }
    00796
    00797   return SEND_COMMAND(PACKET_SERVER_WELCOME)(cs);
    00798 }
    00799
    00800 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_GETMAP)
    00801 {
    00802   NetworkClientSocket *new_cs;
    00803
    00804   /* Do an extra version match. We told the client our version already,
    00805    * lets confirm that the client isn't lieing to us.
    00806    * But only do it for stable releases because of those we are sure
    00807    * that everybody has the same NewGRF version. For trunk and the
    00808    * branches we make tarballs of the OpenTTDs compiled from tarball
    00809    * will have the lower bits set to 0. As such they would become
    00810    * incompatible, which we would like to prevent by this. */
    00811   if (HasBit(_openttd_newgrf_version, 19)) {
    00812     if (_openttd_newgrf_version != p->Recv_uint32()) {
    00813       /* The version we get from the client differs, it must have the
    00814        * wrong version. The client must be wrong. */
    00815       return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    00816     }
    00817   } else if (p->size != 3) {
    00818     /* We received a packet from a version that claims to be stable.
    00819      * That shouldn't happen. The client must be wrong. */
    00820     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    00821   }
    00822
    00823   /* The client was never joined.. so this is impossible, right?
    00824    *  Ignore the packet, give the client a warning, and close his connection */
    00825   if (cs->status < STATUS_AUTHORIZED || cs->HasClientQuit()) {
    00826     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_AUTHORIZED);
    00827   }
    00828
    00829   /* Check if someone else is receiving the map */
    00830   FOR_ALL_CLIENT_SOCKETS(new_cs) {
    00831     if (new_cs->status == STATUS_MAP) {
    00832       /* Tell the new client to wait */
    00833       cs->status = STATUS_MAP_WAIT;
    00834       return SEND_COMMAND(PACKET_SERVER_WAIT)(cs);
    00835     }
    00836   }
    00837
    00838   /* We receive a request to upload the map.. give it to the client! */
    00839   return SEND_COMMAND(PACKET_SERVER_MAP)(cs);
    00840 }
    00841
    00842 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_MAP_OK)
    00843 {
    00844   /* Client has the map, now start syncing */
    00845   if (cs->status == STATUS_DONE_MAP && !cs->HasClientQuit()) {
    00846     char client_name[NETWORK_CLIENT_NAME_LENGTH];
    00847     NetworkClientSocket *new_cs;
    00848
    00849     NetworkGetClientName(client_name, sizeof(client_name), cs);
    00850
    00851     NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, client_name, NULL, cs->client_id);
    00852
    00853     /* Mark the client as pre-active, and wait for an ACK
    00854      *  so we know he is done loading and in sync with us */
    00855     cs->status = STATUS_PRE_ACTIVE;
    00856     NetworkHandleCommandQueue(cs);
    00857     SEND_COMMAND(PACKET_SERVER_FRAME)(cs);
    00858     SEND_COMMAND(PACKET_SERVER_SYNC)(cs);
    00859
    00860     /* This is the frame the client receives
    00861      *  we need it later on to make sure the client is not too slow */
    00862     cs->last_frame = _frame_counter;
    00863     cs->last_frame_server = _frame_counter;
    00864
    00865     FOR_ALL_CLIENT_SOCKETS(new_cs) {
    00866       if (new_cs->status > STATUS_AUTHORIZED) {
    00867         SEND_COMMAND(PACKET_SERVER_CLIENT_INFO)(new_cs, cs->GetInfo());
    00868         SEND_COMMAND(PACKET_SERVER_JOIN)(new_cs, cs->client_id);
    00869       }
    00870     }
    00871
    00872     /* also update the new client with our max values */
    00873     SEND_COMMAND(PACKET_SERVER_CONFIG_UPDATE)(cs);
    00874
    00875     /* quickly update the syncing client with company details */
    00876     return SEND_COMMAND(PACKET_SERVER_COMPANY_UPDATE)(cs);
    00877   }
    00878
    00879   /* Wrong status for this packet, give a warning to client, and close connection */
    00880   return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    00881 }
    00882
    00887 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_COMMAND)
    00888 {
    00889   NetworkClientSocket *new_cs;
    00890
    00891   /* The client was never joined.. so this is impossible, right?
    00892    *  Ignore the packet, give the client a warning, and close his connection */
    00893   if (cs->status < STATUS_DONE_MAP || cs->HasClientQuit()) {
    00894     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    00895   }
    00896
    00897   CommandPacket cp;
    00898   const char *err = cs->Recv_Command(p, &cp);
    00899
    00900   if (cs->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
    00901
    00902   NetworkClientInfo *ci = cs->GetInfo();
    00903
    00904   if (err != NULL) {
    00905     IConsolePrintF(CC_ERROR, "WARNING: %s from client %d (IP: %s).", err, ci->client_id, GetClientIP(ci));
    00906     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    00907   }
    00908
    00909
    00910   if ((GetCommandFlags(cp.cmd) & CMD_SERVER) && ci->client_id != CLIENT_ID_SERVER) {
    00911     IConsolePrintF(CC_ERROR, "WARNING: server only command from: client %d (IP: %s), kicking...", ci->client_id, GetClientIP(ci));
    00912     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_KICKED);
    00913   }
    00914
    00915   if ((GetCommandFlags(cp.cmd) & CMD_SPECTATOR) == 0 && !Company::IsValidID(cp.company) && ci->client_id != CLIENT_ID_SERVER) {
    00916     IConsolePrintF(CC_ERROR, "WARNING: spectator issueing command from client %d (IP: %s), kicking...", ci->client_id, GetClientIP(ci));
    00917     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_KICKED);
    00918   }
    00919
    00924   if (!(cp.cmd == CMD_COMPANY_CTRL && cp.p1 == 0 && ci->client_playas == COMPANY_NEW_COMPANY) && ci->client_playas != cp.company) {
    00925     IConsolePrintF(CC_ERROR, "WARNING: client %d (IP: %s) tried to execute a command as company %d, kicking...",
    00926                    ci->client_playas + 1, GetClientIP(ci), cp.company + 1);
    00927     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_COMPANY_MISMATCH);
    00928   }
    00929
    00935   if (cp.cmd == CMD_COMPANY_CTRL) {
    00936     if (cp.p1 != 0 || cp.company != COMPANY_SPECTATOR) {
    00937       return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_CHEATER);
    00938     }
    00939
    00940     /* 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! */
    00941     if (Company::GetNumItems() >= _settings_client.network.max_companies) {
    00942       NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_CLIENT, ci->client_id, "cannot create new company, server full", CLIENT_ID_SERVER);
    00943       return NETWORK_RECV_STATUS_OKAY;
    00944     }
    00945
    00946     cp.p2 = cs->client_id;
    00947   }
    00948
    00949   /* The frame can be executed in the same frame as the next frame-packet
    00950    *  That frame just before that frame is saved in _frame_counter_max */
    00951   cp.frame = _frame_counter_max + 1;
    00952   cp.next  = NULL;
    00953
    00954   CommandCallback *callback = cp.callback;
    00955
    00956   /* Queue the command for the clients (are send at the end of the frame
    00957    *   if they can handle it ;)) */
    00958   FOR_ALL_CLIENT_SOCKETS(new_cs) {
    00959     if (new_cs->status >= STATUS_MAP) {
    00960       /* Callbacks are only send back to the client who sent them in the
    00961        *  first place. This filters that out. */
    00962       cp.callback = (new_cs != cs) ? NULL : callback;
    00963       cp.my_cmd = (new_cs == cs);
    00964       NetworkAddCommandQueue(cp, new_cs);
    00965     }
    00966   }
    00967
    00968   cp.callback = NULL;
    00969   cp.my_cmd = false;
    00970   NetworkAddCommandQueue(cp);
    00971   return NETWORK_RECV_STATUS_OKAY;
    00972 }
    00973
    00974 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_ERROR)
    00975 {
    00976   /* This packets means a client noticed an error and is reporting this
    00977    *  to us. Display the error and report it to the other clients */
    00978   NetworkClientSocket *new_cs;
    00979   char str[100];
    00980   char client_name[NETWORK_CLIENT_NAME_LENGTH];
    00981   NetworkErrorCode errorno = (NetworkErrorCode)p->Recv_uint8();
    00982
    00983   /* The client was never joined.. thank the client for the packet, but ignore it */
    00984   if (cs->status < STATUS_DONE_MAP || cs->HasClientQuit()) {
    00985     cs->CloseConnection();
    00986     return NETWORK_RECV_STATUS_CONN_LOST;
    00987   }
    00988
    00989   NetworkGetClientName(client_name, sizeof(client_name), cs);
    00990
    00991   StringID strid = GetNetworkErrorMsg(errorno);
    00992   GetString(str, strid, lastof(str));
    00993
    00994   DEBUG(net, 2, "'%s' reported an error and is closing its connection (%s)", client_name, str);
    00995
    00996   NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, strid);
    00997
    00998   FOR_ALL_CLIENT_SOCKETS(new_cs) {
    00999     if (new_cs->status > STATUS_AUTHORIZED) {
    01000       SEND_COMMAND(PACKET_SERVER_ERROR_QUIT)(new_cs, cs->client_id, errorno);
    01001     }
    01002   }
    01003
    01004   cs->CloseConnection(false);
    01005   return NETWORK_RECV_STATUS_CONN_LOST;
    01006 }
    01007
    01008 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_QUIT)
    01009 {
    01010   /* The client wants to leave. Display this and report it to the other
    01011    *  clients. */
    01012   NetworkClientSocket *new_cs;
    01013   char client_name[NETWORK_CLIENT_NAME_LENGTH];
    01014
    01015   /* The client was never joined.. thank the client for the packet, but ignore it */
    01016   if (cs->status < STATUS_DONE_MAP || cs->HasClientQuit()) {
    01017     cs->CloseConnection();
    01018     return NETWORK_RECV_STATUS_CONN_LOST;
    01019   }
    01020
    01021   NetworkGetClientName(client_name, sizeof(client_name), cs);
    01022
    01023   NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, STR_NETWORK_MESSAGE_CLIENT_LEAVING);
    01024
    01025   FOR_ALL_CLIENT_SOCKETS(new_cs) {
    01026     if (new_cs->status > STATUS_AUTHORIZED) {
    01027       SEND_COMMAND(PACKET_SERVER_QUIT)(new_cs, cs->client_id);
    01028     }
    01029   }
    01030
    01031   cs->CloseConnection(false);
    01032   return NETWORK_RECV_STATUS_CONN_LOST;
    01033 }
    01034
    01035 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_ACK)
    01036 {
    01037   if (cs->status < STATUS_AUTHORIZED) {
    01038     /* Illegal call, return error and ignore the packet */
    01039     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_AUTHORIZED);
    01040   }
    01041
    01042   uint32 frame = p->Recv_uint32();
    01043
    01044   /* The client is trying to catch up with the server */
    01045   if (cs->status == STATUS_PRE_ACTIVE) {
    01046     /* The client is not yet catched up? */
    01047     if (frame + DAY_TICKS < _frame_counter) return NETWORK_RECV_STATUS_OKAY;
    01048
    01049     /* Now he is! Unpause the game */
    01050     cs->status = STATUS_ACTIVE;
    01051
    01052     /* Execute script for, e.g. MOTD */
    01053     IConsoleCmdExec("exec scripts/on_server_connect.scr 0");
    01054   }
    01055
    01056   /* The client received the frame, make note of it */
    01057   cs->last_frame = frame;
    01058   /* With those 2 values we can calculate the lag realtime */
    01059   cs->last_frame_server = _frame_counter;
    01060   return NETWORK_RECV_STATUS_OKAY;
    01061 }
    01062
    01063
    01064
    01065 void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, const char *msg, ClientID from_id, int64 data)
    01066 {
    01067   NetworkClientSocket *cs;
    01068   const NetworkClientInfo *ci, *ci_own, *ci_to;
    01069
    01070   switch (desttype) {
    01071   case DESTTYPE_CLIENT:
    01072     /* Are we sending to the server? */
    01073     if ((ClientID)dest == CLIENT_ID_SERVER) {
    01074       ci = NetworkFindClientInfoFromClientID(from_id);
    01075       /* Display the text locally, and that is it */
    01076       if (ci != NULL)
    01077         NetworkTextMessage(action, (ConsoleColour)GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
    01078     } else {
    01079       /* Else find the client to send the message to */
    01080       FOR_ALL_CLIENT_SOCKETS(cs) {
    01081         if (cs->client_id == (ClientID)dest) {
    01082           SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, from_id, false, msg, data);
    01083           break;
    01084         }
    01085       }
    01086     }
    01087
    01088     /* Display the message locally (so you know you have sent it) */
    01089     if (from_id != (ClientID)dest) {
    01090       if (from_id == CLIENT_ID_SERVER) {
    01091         ci = NetworkFindClientInfoFromClientID(from_id);
    01092         ci_to = NetworkFindClientInfoFromClientID((ClientID)dest);
    01093         if (ci != NULL && ci_to != NULL)
    01094           NetworkTextMessage(action, (ConsoleColour)GetDrawStringCompanyColour(ci->client_playas), true, ci_to->client_name, msg, data);
    01095       } else {
    01096         FOR_ALL_CLIENT_SOCKETS(cs) {
    01097           if (cs->client_id == from_id) {
    01098             SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, (ClientID)dest, true, msg, data);
    01099             break;
    01100           }
    01101         }
    01102       }
    01103     }
    01104     break;
    01105   case DESTTYPE_TEAM: {
    01106     /* If this is false, the message is already displayed on the client who sent it. */
    01107     bool show_local = true;
    01108     /* Find all clients that belong to this company */
    01109     ci_to = NULL;
    01110     FOR_ALL_CLIENT_SOCKETS(cs) {
    01111       ci = cs->GetInfo();
    01112       if (ci->client_playas == (CompanyID)dest) {
    01113         SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, from_id, false, msg, data);
    01114         if (cs->client_id == from_id) show_local = false;
    01115         ci_to = ci; // Remember a client that is in the company for company-name
    01116       }
    01117     }
    01118
    01119     ci = NetworkFindClientInfoFromClientID(from_id);
    01120     ci_own = NetworkFindClientInfoFromClientID(CLIENT_ID_SERVER);
    01121     if (ci != NULL && ci_own != NULL && ci_own->client_playas == dest) {
    01122       NetworkTextMessage(action, (ConsoleColour)GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
    01123       if (from_id == CLIENT_ID_SERVER) show_local = false;
    01124       ci_to = ci_own;
    01125     }
    01126
    01127     /* There is no such client */
    01128     if (ci_to == NULL) break;
    01129
    01130     /* Display the message locally (so you know you have sent it) */
    01131     if (ci != NULL && show_local) {
    01132       if (from_id == CLIENT_ID_SERVER) {
    01133         char name[NETWORK_NAME_LENGTH];
    01134         StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
    01135         SetDParam(0, ci_to->client_playas);
    01136         GetString(name, str, lastof(name));
    01137         NetworkTextMessage(action, (ConsoleColour)GetDrawStringCompanyColour(ci_own->client_playas), true, name, msg, data);
    01138       } else {
    01139         FOR_ALL_CLIENT_SOCKETS(cs) {
    01140           if (cs->client_id == from_id) {
    01141             SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, ci_to->client_id, true, msg, data);
    01142           }
    01143         }
    01144       }
    01145     }
    01146     }
    01147     break;
    01148   default:
    01149     DEBUG(net, 0, "[server] received unknown chat destination type %d. Doing broadcast instead", desttype);
    01150     /* fall-through to next case */
    01151   case DESTTYPE_BROADCAST:
    01152     FOR_ALL_CLIENT_SOCKETS(cs) {
    01153       SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, from_id, false, msg, data);
    01154     }
    01155     ci = NetworkFindClientInfoFromClientID(from_id);
    01156     if (ci != NULL)
    01157       NetworkTextMessage(action, (ConsoleColour)GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
    01158     break;
    01159   }
    01160 }
    01161
    01162 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_CHAT)
    01163 {
    01164   if (cs->status < STATUS_AUTHORIZED) {
    01165     /* Illegal call, return error and ignore the packet */
    01166     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_AUTHORIZED);
    01167   }
    01168
    01169   NetworkAction action = (NetworkAction)p->Recv_uint8();
    01170   DestType desttype = (DestType)p->Recv_uint8();
    01171   int dest = p->Recv_uint32();
    01172   char msg[NETWORK_CHAT_LENGTH];
    01173
    01174   p->Recv_string(msg, NETWORK_CHAT_LENGTH);
    01175   int64 data = p->Recv_uint64();
    01176
    01177   NetworkClientInfo *ci = cs->GetInfo();
    01178   switch (action) {
    01179     case NETWORK_ACTION_GIVE_MONEY:
    01180       if (!Company::IsValidID(ci->client_playas)) break;
    01181       /* Fall-through */
    01182     case NETWORK_ACTION_CHAT:
    01183     case NETWORK_ACTION_CHAT_CLIENT:
    01184     case NETWORK_ACTION_CHAT_COMPANY:
    01185       NetworkServerSendChat(action, desttype, dest, msg, cs->client_id, data);
    01186       break;
    01187     default:
    01188       IConsolePrintF(CC_ERROR, "WARNING: invalid chat action from client %d (IP: %s).", ci->client_id, GetClientIP(ci));
    01189       return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    01190       break;
    01191   }
    01192   return NETWORK_RECV_STATUS_OKAY;
    01193 }
    01194
    01195 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_SET_PASSWORD)
    01196 {
    01197   if (cs->status != STATUS_ACTIVE) {
    01198     /* Illegal call, return error and ignore the packet */
    01199     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    01200   }
    01201
    01202   char password[NETWORK_PASSWORD_LENGTH];
    01203   const NetworkClientInfo *ci;
    01204
    01205   p->Recv_string(password, sizeof(password));
    01206   ci = cs->GetInfo();
    01207
    01208   if (Company::IsValidID(ci->client_playas)) {
    01209     strecpy(_network_company_states[ci->client_playas].password, password, lastof(_network_company_states[ci->client_playas].password));
    01210     NetworkServerUpdateCompanyPassworded(ci->client_playas, !StrEmpty(_network_company_states[ci->client_playas].password));
    01211   }
    01212   return NETWORK_RECV_STATUS_OKAY;
    01213 }
    01214
    01215 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_SET_NAME)
    01216 {
    01217   if (cs->status != STATUS_ACTIVE) {
    01218     /* Illegal call, return error and ignore the packet */
    01219     return SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
    01220   }
    01221
    01222   char client_name[NETWORK_CLIENT_NAME_LENGTH];
    01223   NetworkClientInfo *ci;
    01224
    01225   p->Recv_string(client_name, sizeof(client_name));
    01226   ci = cs->GetInfo();
    01227
    01228   if (cs->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
    01229
    01230   if (ci != NULL) {
    01231     /* Display change */
    01232     if (NetworkFindName(client_name)) {
    01233       NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, client_name);
    01234       strecpy(ci->client_name, client_name, lastof(ci->client_name));
    01235       NetworkUpdateClientInfo(ci->client_id);
    01236     }
    01237   }
    01238   return NETWORK_RECV_STATUS_OKAY;
    01239 }
    01240
    01241 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_RCON)
    01242 {
    01243   char pass[NETWORK_PASSWORD_LENGTH];
    01244   char command[NETWORK_RCONCOMMAND_LENGTH];
    01245
    01246   if (StrEmpty(_settings_client.network.rcon_password)) return NETWORK_RECV_STATUS_OKAY;
    01247
    01248   p->Recv_string(pass, sizeof(pass));
    01249   p->Recv_string(command, sizeof(command));
    01250
    01251   if (strcmp(pass, _settings_client.network.rcon_password) != 0) {
    01252     DEBUG(net, 0, "[rcon] wrong password from client-id %d", cs->client_id);
    01253     return NETWORK_RECV_STATUS_OKAY;
    01254   }
    01255
    01256   DEBUG(net, 0, "[rcon] client-id %d executed: '%s'", cs->client_id, command);
    01257
    01258   _redirect_console_to_client = cs->client_id;
    01259   IConsoleCmdExec(command);
    01260   _redirect_console_to_client = INVALID_CLIENT_ID;
    01261   return NETWORK_RECV_STATUS_OKAY;
    01262 }
    01263
    01264 DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_MOVE)
    01265 {
    01266   CompanyID company_id = (Owner)p->Recv_uint8();
    01267
    01268   /* Check if the company is valid, we don't allow moving to AI companies */
    01269   if (company_id != COMPANY_SPECTATOR && !Company::IsValidHumanID(company_id)) return NETWORK_RECV_STATUS_OKAY;
    01270
    01271   /* Check if we require a password for this company */
    01272   if (company_id != COMPANY_SPECTATOR && !StrEmpty(_network_company_states[company_id].password)) {
    01273     /* we need a password from the client - should be in this packet */
    01274     char password[NETWORK_PASSWORD_LENGTH];
    01275     p->Recv_string(password, sizeof(password));
    01276
    01277     /* Incorrect password sent, return! */
    01278     if (strcmp(password, _network_company_states[company_id].password) != 0) {
    01279       DEBUG(net, 2, "[move] wrong password from client-id #%d for company #%d", cs->client_id, company_id + 1);
    01280       return NETWORK_RECV_STATUS_OKAY;
    01281     }
    01282   }
    01283
    01284   /* if we get here we can move the client */
    01285   NetworkServerDoMove(cs->client_id, company_id);
    01286   return NETWORK_RECV_STATUS_OKAY;
    01287 }
    01288
    01289 /* The layout for the receive-functions by the server */
    01290 typedef NetworkRecvStatus NetworkServerPacket(NetworkClientSocket *cs, Packet *p);
    01291
    01292
    01293 /* This array matches PacketType. At an incoming
    01294  *  packet it is matches against this array
    01295  *  and that way the right function to handle that
    01296  *  packet is found. */
    01297 static NetworkServerPacket * const _network_server_packet[] = {
    01298   NULL, // PACKET_SERVER_FULL,
    01299   NULL, // PACKET_SERVER_BANNED,
    01300   RECEIVE_COMMAND(PACKET_CLIENT_JOIN),
    01301   NULL, // PACKET_SERVER_ERROR,
    01302   RECEIVE_COMMAND(PACKET_CLIENT_COMPANY_INFO),
    01303   NULL, // PACKET_SERVER_COMPANY_INFO,
    01304   NULL, // PACKET_SERVER_CLIENT_INFO,
    01305   NULL, // PACKET_SERVER_NEED_GAME_PASSWORD,
    01306   NULL, // PACKET_SERVER_NEED_COMPANY_PASSWORD,
    01307   RECEIVE_COMMAND(PACKET_CLIENT_GAME_PASSWORD),
    01308   RECEIVE_COMMAND(PACKET_CLIENT_COMPANY_PASSWORD),
    01309   NULL, // PACKET_SERVER_WELCOME,
    01310   RECEIVE_COMMAND(PACKET_CLIENT_GETMAP),
    01311   NULL, // PACKET_SERVER_WAIT,
    01312   NULL, // PACKET_SERVER_MAP,
    01313   RECEIVE_COMMAND(PACKET_CLIENT_MAP_OK),
    01314   NULL, // PACKET_SERVER_JOIN,
    01315   NULL, // PACKET_SERVER_FRAME,
    01316   NULL, // PACKET_SERVER_SYNC,
    01317   RECEIVE_COMMAND(PACKET_CLIENT_ACK),
    01318   RECEIVE_COMMAND(PACKET_CLIENT_COMMAND),
    01319   NULL, // PACKET_SERVER_COMMAND,
    01320   RECEIVE_COMMAND(PACKET_CLIENT_CHAT),
    01321   NULL, // PACKET_SERVER_CHAT,
    01322   RECEIVE_COMMAND(PACKET_CLIENT_SET_PASSWORD),
    01323   RECEIVE_COMMAND(PACKET_CLIENT_SET_NAME),
    01324   RECEIVE_COMMAND(PACKET_CLIENT_QUIT),
    01325   RECEIVE_COMMAND(PACKET_CLIENT_ERROR),
    01326   NULL, // PACKET_SERVER_QUIT,
    01327   NULL, // PACKET_SERVER_ERROR_QUIT,
    01328   NULL, // PACKET_SERVER_SHUTDOWN,
    01329   NULL, // PACKET_SERVER_NEWGAME,
    01330   NULL, // PACKET_SERVER_RCON,
    01331   RECEIVE_COMMAND(PACKET_CLIENT_RCON),
    01332   NULL, // PACKET_CLIENT_CHECK_NEWGRFS,
    01333   RECEIVE_COMMAND(PACKET_CLIENT_NEWGRFS_CHECKED),
    01334   NULL, // PACKET_SERVER_MOVE,
    01335   RECEIVE_COMMAND(PACKET_CLIENT_MOVE),
    01336   NULL, // PACKET_SERVER_COMPANY_UPDATE,
    01337   NULL, // PACKET_SERVER_CONFIG_UPDATE,
    01338 };
    01339
    01340 /* If this fails, check the array above with network_data.h */
    01341 assert_compile(lengthof(_network_server_packet) == PACKET_END);
    01342
    01343 void NetworkSocketHandler::Send_CompanyInformation(Packet *p, const Company *c, const NetworkCompanyStats *stats)
    01344 {
    01345   /* Grab the company name */
    01346   char company_name[NETWORK_COMPANY_NAME_LENGTH];
    01347   SetDParam(0, c->index);
    01348   GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
    01349
    01350   /* Get the income */
    01351   Money income = 0;
    01352   if (_cur_year - 1 == c->inaugurated_year) {
    01353     /* The company is here just 1 year, so display [2], else display[1] */
    01354     for (uint i = 0; i < lengthof(c->yearly_expenses[2]); i++) {
    01355       income -= c->yearly_expenses[2][i];
    01356     }
    01357   } else {
    01358     for (uint i = 0; i < lengthof(c->yearly_expenses[1]); i++) {
    01359       income -= c->yearly_expenses[1][i];
    01360     }
    01361   }
    01362
    01363   /* Send the information */
    01364   p->Send_uint8 (c->index);
    01365   p->Send_string(company_name);
    01366   p->Send_uint32(c->inaugurated_year);
    01367   p->Send_uint64(c->old_economy[0].company_value);
    01368   p->Send_uint64(c->money);
    01369   p->Send_uint64(income);
    01370   p->Send_uint16(c->old_economy[0].performance_history);
    01371
    01372   /* Send 1 if there is a passord for the company else send 0 */
    01373   p->Send_bool  (!StrEmpty(_network_company_states[c->index].password));
    01374
    01375   for (int i = 0; i < NETWORK_VEHICLE_TYPES; i++) {
    01376     p->Send_uint16(stats->num_vehicle[i]);
    01377   }
    01378
    01379   for (int i = 0; i < NETWORK_STATION_TYPES; i++) {
    01380     p->Send_uint16(stats->num_station[i]);
    01381   }
    01382
    01383   p->Send_bool(c->is_ai);
    01384 }
    01385
    01390 void NetworkPopulateCompanyStats(NetworkCompanyStats *stats)
    01391 {
    01392   const Vehicle *v;
    01393   const Station *s;
    01394
    01395   memset(stats, 0, sizeof(*stats) * MAX_COMPANIES);
    01396
    01397   /* Go through all vehicles and count the type of vehicles */
    01398   FOR_ALL_VEHICLES(v) {
    01399     if (!Company::IsValidID(v->owner) || !v->IsPrimaryVehicle()) continue;
    01400     byte type = 0;
    01401     switch (v->type) {
    01402       case VEH_TRAIN: type = 0; break;
    01403       case VEH_ROAD: type = RoadVehicle::From(v)->IsBus() ? 2 : 1; break;
    01404       case VEH_AIRCRAFT: type = 3; break;
    01405       case VEH_SHIP: type = 4; break;
    01406       default: continue;
    01407     }
    01408     stats[v->owner].num_vehicle[type]++;
    01409   }
    01410
    01411   /* Go through all stations and count the types of stations */
    01412   FOR_ALL_STATIONS(s) {
    01413     if (Company::IsValidID(s->owner)) {
    01414       NetworkCompanyStats *npi = &stats[s->owner];
    01415
    01416       if (s->facilities & FACIL_TRAIN)      npi->num_station[0]++;
    01417       if (s->facilities & FACIL_TRUCK_STOP) npi->num_station[1]++;
    01418       if (s->facilities & FACIL_BUS_STOP)   npi->num_station[2]++;
    01419       if (s->facilities & FACIL_AIRPORT)    npi->num_station[3]++;
    01420       if (s->facilities & FACIL_DOCK)       npi->num_station[4]++;
    01421     }
    01422   }
    01423 }
    01424
    01425 /* Send a packet to all clients with updated info about this client_id */
    01426 void NetworkUpdateClientInfo(ClientID client_id)
    01427 {
    01428   NetworkClientSocket *cs;
    01429   NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(client_id);
    01430
    01431   if (ci == NULL) return;
    01432
    01433   DEBUG(desync, 1, "client: %08x; %02x; %02x; %04x", _date, _date_fract, (int)ci->client_playas, client_id);
    01434
    01435   FOR_ALL_CLIENT_SOCKETS(cs) {
    01436     SEND_COMMAND(PACKET_SERVER_CLIENT_INFO)(cs, ci);
    01437   }
    01438 }
    01439
    01440 /* Check if we want to restart the map */
    01441 static void NetworkCheckRestartMap()
    01442 {
    01443   if (_settings_client.network.restart_game_year != 0 && _cur_year >= _settings_client.network.restart_game_year) {
    01444     DEBUG(net, 0, "Auto-restarting map. Year %d reached", _cur_year);
    01445
    01446     StartNewGameWithoutGUI(GENERATE_NEW_SEED);
    01447   }
    01448 }
    01449
    01450 /* Check if the server has autoclean_companies activated
    01451     Two things happen:
    01452       1) If a company is not protected, it is closed after 1 year (for example)
    01453       2) If a company is protected, protection is disabled after 3 years (for example)
    01454            (and item 1. happens a year later) */
    01455 static void NetworkAutoCleanCompanies()
    01456 {
    01457   const NetworkClientInfo *ci;
    01458   const Company *c;
    01459   bool clients_in_company[MAX_COMPANIES];
    01460   int vehicles_in_company[MAX_COMPANIES];
    01461
    01462   if (!_settings_client.network.autoclean_companies) return;
    01463
    01464   memset(clients_in_company, 0, sizeof(clients_in_company));
    01465
    01466   /* Detect the active companies */
    01467   FOR_ALL_CLIENT_INFOS(ci) {
    01468     if (Company::IsValidID(ci->client_playas)) clients_in_company[ci->client_playas] = true;
    01469   }
    01470
    01471   if (!_network_dedicated) {
    01472     ci = NetworkFindClientInfoFromClientID(CLIENT_ID_SERVER);
    01473     if (Company::IsValidID(ci->client_playas)) clients_in_company[ci->client_playas] = true;
    01474   }
    01475
    01476   if (_settings_client.network.autoclean_novehicles != 0) {
    01477     memset(vehicles_in_company, 0, sizeof(vehicles_in_company));
    01478
    01479     const Vehicle *v;
    01480     FOR_ALL_VEHICLES(v) {
    01481       if (!Company::IsValidID(v->owner) || !v->IsPrimaryVehicle()) continue;
    01482       vehicles_in_company[v->owner]++;
    01483     }
    01484   }
    01485
    01486   /* Go through all the comapnies */
    01487   FOR_ALL_COMPANIES(c) {
    01488     /* Skip the non-active once */
    01489     if (c->is_ai) continue;
    01490
    01491     if (!clients_in_company[c->index]) {
    01492       /* The company is empty for one month more */
    01493       _network_company_states[c->index].months_empty++;
    01494
    01495       /* Is the company empty for autoclean_unprotected-months, and is there no protection? */
    01496       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)) {
    01497         /* Shut the company down */
    01498         DoCommandP(0, 2, c->index, CMD_COMPANY_CTRL);
    01499         IConsolePrintF(CC_DEFAULT, "Auto-cleaned company #%d with no password", c->index + 1);
    01500       }
    01501       /* Is the company empty for autoclean_protected-months, and there is a protection? */
    01502       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)) {
    01503         /* Unprotect the company */
    01504         _network_company_states[c->index].password[0] = '\0';
    01505         IConsolePrintF(CC_DEFAULT, "Auto-removed protection from company #%d", c->index + 1);
    01506         _network_company_states[c->index].months_empty = 0;
    01507         NetworkServerUpdateCompanyPassworded(c->index, false);
    01508       }
    01509       /* Is the company empty for autoclean_novehicles-months, and has no vehicles? */
    01510       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) {
    01511         /* Shut the company down */
    01512         DoCommandP(0, 2, c->index, CMD_COMPANY_CTRL);
    01513         IConsolePrintF(CC_DEFAULT, "Auto-cleaned company #%d with no vehicles", c->index + 1);
    01514       }
    01515     } else {
    01516       /* It is not empty, reset the date */
    01517       _network_company_states[c->index].months_empty = 0;
    01518     }
    01519   }
    01520 }
    01521
    01522 /* This function changes new_name to a name that is unique (by adding #1 ...)
    01523  *  and it returns true if that succeeded. */
    01524 bool NetworkFindName(char new_name[NETWORK_CLIENT_NAME_LENGTH])
    01525 {
    01526   bool found_name = false;
    01527   uint number = 0;
    01528   char original_name[NETWORK_CLIENT_NAME_LENGTH];
    01529
    01530   /* We use NETWORK_CLIENT_NAME_LENGTH in here, because new_name is really a pointer */
    01531   ttd_strlcpy(original_name, new_name, NETWORK_CLIENT_NAME_LENGTH);
    01532
    01533   while (!found_name) {
    01534     const NetworkClientInfo *ci;
    01535
    01536     found_name = true;
    01537     FOR_ALL_CLIENT_INFOS(ci) {
    01538       if (strcmp(ci->client_name, new_name) == 0) {
    01539         /* Name already in use */
    01540         found_name = false;
    01541         break;
    01542       }
    01543     }
    01544     /* Check if it is the same as the server-name */
    01545     ci = NetworkFindClientInfoFromClientID(CLIENT_ID_SERVER);
    01546     if (ci != NULL) {
    01547       if (strcmp(ci->client_name, new_name) == 0) found_name = false; // name already in use
    01548     }
    01549
    01550     if (!found_name) {
    01551       /* Try a new name (<name> #1, <name> #2, and so on) */
    01552
    01553       /* Something's really wrong when there're more names than clients */
    01554       if (number++ > MAX_CLIENTS) break;
    01555       snprintf(new_name, NETWORK_CLIENT_NAME_LENGTH, "%s #%d", original_name, number);
    01556     }
    01557   }
    01558
    01559   return found_name;
    01560 }
    01561
    01568 bool NetworkServerChangeClientName(ClientID client_id, const char *new_name)
    01569 {
    01570   NetworkClientInfo *ci;
    01571   /* Check if the name's already in use */
    01572   FOR_ALL_CLIENT_INFOS(ci) {
    01573     if (strcmp(ci->client_name, new_name) == 0) return false;
    01574   }
    01575
    01576   ci = NetworkFindClientInfoFromClientID(client_id);
    01577   if (ci == NULL) return false;
    01578
    01579   NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, true, ci->client_name, new_name);
    01580
    01581   strecpy(ci->client_name, new_name, lastof(ci->client_name));
    01582
    01583   NetworkUpdateClientInfo(client_id);
    01584   return true;
    01585 }
    01586
    01587 /* Reads a packet from the stream */
    01588 void NetworkServer_ReadPackets(NetworkClientSocket *cs)
    01589 {
    01590   Packet *p;
    01591   NetworkRecvStatus res = NETWORK_RECV_STATUS_OKAY;
    01592
    01593   while (res == NETWORK_RECV_STATUS_OKAY && (p = cs->Recv_Packet()) != NULL) {
    01594     byte type = p->Recv_uint8();
    01595     if (type < PACKET_END && _network_server_packet[type] != NULL && !cs->HasClientQuit()) {
    01596       res = _network_server_packet[type](cs, p);
    01597     } else {
    01598       cs->CloseConnection();
    01599       res = NETWORK_RECV_STATUS_MALFORMED_PACKET;
    01600       DEBUG(net, 0, "[server] received invalid packet type %d", type);
    01601     }
    01602
    01603     delete p;
    01604   }
    01605 }
    01606
    01607 /* Handle the local command-queue */
    01608 static void NetworkHandleCommandQueue(NetworkClientSocket *cs)
    01609 {
    01610   CommandPacket *cp;
    01611
    01612   while ( (cp = cs->command_queue) != NULL) {
    01613     SEND_COMMAND(PACKET_SERVER_COMMAND)(cs, cp);
    01614
    01615     cs->command_queue = cp->next;
    01616     free(cp);
    01617   }
    01618 }
    01619
    01620 /* This is called every tick if this is a _network_server */
    01621 void NetworkServer_Tick(bool send_frame)
    01622 {
    01623   NetworkClientSocket *cs;
    01624 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
    01625   bool send_sync = false;
    01626 #endif
    01627
    01628 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
    01629   if (_frame_counter >= _last_sync_frame + _settings_client.network.sync_freq) {
    01630     _last_sync_frame = _frame_counter;
    01631     send_sync = true;
    01632   }
    01633 #endif
    01634
    01635   /* Now we are done with the frame, inform the clients that they can
    01636    *  do their frame! */
    01637   FOR_ALL_CLIENT_SOCKETS(cs) {
    01638     /* Check if the speed of the client is what we can expect from a client */
    01639     if (cs->status == STATUS_ACTIVE) {
    01640       /* 1 lag-point per day */
    01641       int lag = NetworkCalculateLag(cs) / DAY_TICKS;
    01642       if (lag > 0) {
    01643         if (lag > 3) {
    01644           /* Client did still not report in after 4 game-day, drop him
    01645            *  (that is, the 3 of above, + 1 before any lag is counted) */
    01646           IConsolePrintF(CC_ERROR,"Client #%d is dropped because the client did not respond for more than 4 game-days", cs->client_id);
    01647           NetworkCloseClient(cs, NETWORK_RECV_STATUS_SERVER_ERROR);
    01648           continue;
    01649         }
    01650
    01651         /* Report once per time we detect the lag */
    01652         if (cs->lag_test == 0) {
    01653           IConsolePrintF(CC_WARNING,"[%d] Client #%d is slow, try increasing *net_frame_freq to a higher value!", _frame_counter, cs->client_id);
    01654           cs->lag_test = 1;
    01655         }
    01656       } else {
    01657         cs->lag_test = 0;
    01658       }
    01659     } else if (cs->status == STATUS_PRE_ACTIVE) {
    01660       int lag = NetworkCalculateLag(cs);
    01661       if (lag > _settings_client.network.max_join_time) {
    01662         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);
    01663         NetworkCloseClient(cs, NETWORK_RECV_STATUS_SERVER_ERROR);
    01664       }
    01665     } else if (cs->status == STATUS_INACTIVE) {
    01666       int lag = NetworkCalculateLag(cs);
    01667       if (lag > 4 * DAY_TICKS) {
    01668         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);
    01669         NetworkCloseClient(cs, NETWORK_RECV_STATUS_SERVER_ERROR);
    01670       }
    01671     }
    01672
    01673     if (cs->status >= STATUS_PRE_ACTIVE) {
    01674       /* Check if we can send command, and if we have anything in the queue */
    01675       NetworkHandleCommandQueue(cs);
    01676
    01677       /* Send an updated _frame_counter_max to the client */
    01678       if (send_frame) SEND_COMMAND(PACKET_SERVER_FRAME)(cs);
    01679
    01680 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
    01681       /* Send a sync-check packet */
    01682       if (send_sync) SEND_COMMAND(PACKET_SERVER_SYNC)(cs);
    01683 #endif
    01684     }
    01685   }
    01686
    01687   /* See if we need to advertise */
    01688   NetworkUDPAdvertise();
    01689 }
    01690
    01691 void NetworkServerYearlyLoop()
    01692 {
    01693   NetworkCheckRestartMap();
    01694 }
    01695
    01696 void NetworkServerMonthlyLoop()
    01697 {
    01698   NetworkAutoCleanCompanies();
    01699 }
    01700
    01701 const char *GetClientIP(NetworkClientInfo *ci)
    01702 {
    01703   return ci->client_address.GetHostname();
    01704 }
    01705
    01706 void NetworkServerShowStatusToConsole()
    01707 {
    01708   static const char * const stat_str[] = {
    01709     "inactive",
    01710     "authorizing (server password)",
    01711     "authorizing (company password)",
    01712     "authorized",
    01713     "waiting",
    01714     "loading map",
    01715     "map done",
    01716     "ready",
    01717     "active"
    01718   };
    01719   assert_compile(lengthof(stat_str) == STATUS_END);
    01720
    01721   NetworkClientSocket *cs;
    01722   FOR_ALL_CLIENT_SOCKETS(cs) {
    01723     int lag = NetworkCalculateLag(cs);
    01724     NetworkClientInfo *ci = cs->GetInfo();
    01725     const char *status;
    01726
    01727     status = (cs->status < (ptrdiff_t)lengthof(stat_str) ? stat_str[cs->status] : "unknown");
    01728     IConsolePrintF(CC_INFO, "Client #%1d  name: '%s'  status: '%s'  frame-lag: %3d  company: %1d  IP: %s",
    01729       cs->client_id, ci->client_name, status, lag,
    01730       ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0),
    01731       GetClientIP(ci));
    01732   }
    01733 }
    01734
    01738 void NetworkServerSendConfigUpdate()
    01739 {
    01740   NetworkClientSocket *cs;
    01741
    01742   FOR_ALL_CLIENT_SOCKETS(cs) {
    01743     SEND_COMMAND(PACKET_SERVER_CONFIG_UPDATE)(cs);
    01744   }
    01745 }
    01746
    01747 void NetworkServerUpdateCompanyPassworded(CompanyID company_id, bool passworded)
    01748 {
    01749   if (NetworkCompanyIsPassworded(company_id) == passworded) return;
    01750
    01751   SB(_network_company_passworded, company_id, 1, !!passworded);
    01752   SetWindowClassesDirty(WC_COMPANY);
    01753
    01754   NetworkClientSocket *cs;
    01755   FOR_ALL_CLIENT_SOCKETS(cs) {
    01756     SEND_COMMAND(PACKET_SERVER_COMPANY_UPDATE)(cs);
    01757   }
    01758 }
    01759
    01766 void NetworkServerDoMove(ClientID client_id, CompanyID company_id)
    01767 {
    01768   /* Only allow non-dedicated servers and normal clients to be moved */
    01769   if (client_id == CLIENT_ID_SERVER && _network_dedicated) return;
    01770
    01771   NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(client_id);
    01772
    01773   /* No need to waste network resources if the client is in the company already! */
    01774   if (ci->client_playas == company_id) return;
    01775
    01776   ci->client_playas = company_id;
    01777
    01778   if (client_id == CLIENT_ID_SERVER) {
    01779     SetLocalCompany(company_id);
    01780   } else {
    01781     SEND_COMMAND(PACKET_SERVER_MOVE)(NetworkFindClientStateFromClientID(client_id), client_id, company_id);
    01782   }
    01783
    01784   /* announce the client's move */
    01785   NetworkUpdateClientInfo(client_id);
    01786
    01787   NetworkAction action = (company_id == COMPANY_SPECTATOR) ? NETWORK_ACTION_COMPANY_SPECTATOR : NETWORK_ACTION_COMPANY_JOIN;
    01788   NetworkServerSendChat(action, DESTTYPE_BROADCAST, 0, "", client_id, company_id + 1);
    01789 }
    01790
    01791 void NetworkServerSendRcon(ClientID client_id, ConsoleColour colour_code, const char *string)
    01792 {
    01793   SEND_COMMAND(PACKET_SERVER_RCON)(NetworkFindClientStateFromClientID(client_id), colour_code, string);
    01794 }
    01795
    01796 void NetworkServerSendError(ClientID client_id, NetworkErrorCode error)
    01797 {
    01798   SEND_COMMAND(PACKET_SERVER_ERROR)(NetworkFindClientStateFromClientID(client_id), error);
    01799 }
    01800
    01801 void NetworkServerKickClient(ClientID client_id)
    01802 {
    01803   if (client_id == CLIENT_ID_SERVER) return;
    01804   NetworkServerSendError(client_id, NETWORK_ERROR_KICKED);
    01805 }
    01806
    01807 void NetworkServerBanIP(const char *banip)
    01808 {
    01809   NetworkClientInfo *ci;
    01810
    01811   /* There can be multiple clients with the same IP, kick them all */
    01812   FOR_ALL_CLIENT_INFOS(ci) {
    01813     if (ci->client_address.IsInNetmask(const_cast<char *>(banip))) {
    01814       NetworkServerKickClient(ci->client_id);
    01815     }
    01816   }
    01817
    01818   /* Add user to ban-list */
    01819   *_network_ban_list.Append() = strdup(banip);
    01820 }
    01821
    01822 bool NetworkCompanyHasClients(CompanyID company)
    01823 {
    01824   const NetworkClientInfo *ci;
    01825   FOR_ALL_CLIENT_INFOS(ci) {
    01826     if (ci->client_playas == company) return true;
    01827   }
    01828   return false;
    01829 }
    01830
    01831 #endif /* ENABLE_NETWORK */