network_server.cpp

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

Generated on Wed Mar 17 23:50:12 2010 for OpenTTD by  doxygen 1.6.1