# network_server.cpp

Go to the documentation of this file.

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