network_server.cpp

Go to the documentation of this file.
00001 /* $Id: network_server.cpp 26020 2013-11-17 11:24:39Z 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 "../strings_func.h"
00016 #include "../date_func.h"
00017 #include "network_admin.h"
00018 #include "network_server.h"
00019 #include "network_udp.h"
00020 #include "network_base.h"
00021 #include "../console_func.h"
00022 #include "../company_base.h"
00023 #include "../command_func.h"
00024 #include "../saveload/saveload.h"
00025 #include "../saveload/saveload_filter.h"
00026 #include "../station_base.h"
00027 #include "../genworld.h"
00028 #include "../company_func.h"
00029 #include "../company_gui.h"
00030 #include "../roadveh.h"
00031 #include "../order_backup.h"
00032 #include "../core/pool_func.hpp"
00033 #include "../core/random_func.hpp"
00034 #include "../rev.h"
00035 
00036 
00037 /* This file handles all the server-commands */
00038 
00039 DECLARE_POSTFIX_INCREMENT(ClientID)
00041 static ClientID _network_client_id = CLIENT_ID_FIRST;
00042 
00044 assert_compile(MAX_CLIENT_SLOTS > MAX_CLIENTS);
00046 assert_compile(NetworkClientSocketPool::MAX_SIZE == MAX_CLIENT_SLOTS);
00047 
00049 NetworkClientSocketPool _networkclientsocket_pool("NetworkClientSocket");
00050 INSTANTIATE_POOL_METHODS(NetworkClientSocket)
00051 
00053 template SocketList TCPListenHandler<ServerNetworkGameSocketHandler, PACKET_SERVER_FULL, PACKET_SERVER_BANNED>::sockets;
00054 
00056 struct PacketWriter : SaveFilter {
00057   ServerNetworkGameSocketHandler *cs; 
00058   Packet *current;                    
00059   size_t total_size;                  
00060   Packet *packets;                    
00061   ThreadMutex *mutex;                 
00062 
00067   PacketWriter(ServerNetworkGameSocketHandler *cs) : SaveFilter(NULL), cs(cs), current(NULL), total_size(0), packets(NULL)
00068   {
00069     this->mutex = ThreadMutex::New();
00070   }
00071 
00073   ~PacketWriter()
00074   {
00075     if (this->mutex != NULL) this->mutex->BeginCritical();
00076 
00077     if (this->cs != NULL && this->mutex != NULL) {
00078       this->mutex->WaitForSignal();
00079     }
00080 
00081     /* This must all wait until the Destroy function is called. */
00082 
00083     while (this->packets != NULL) {
00084       Packet *p = this->packets->next;
00085       delete this->packets;
00086       this->packets = p;
00087     }
00088 
00089     delete this->current;
00090 
00091     if (this->mutex != NULL) this->mutex->EndCritical();
00092 
00093     delete this->mutex;
00094     this->mutex = NULL;
00095   }
00096 
00107   void Destroy()
00108   {
00109     if (this->mutex != NULL) this->mutex->BeginCritical();
00110 
00111     this->cs = NULL;
00112 
00113     if (this->mutex != NULL) this->mutex->SendSignal();
00114 
00115     if (this->mutex != NULL) this->mutex->EndCritical();
00116   }
00117 
00125   bool HasPackets()
00126   {
00127     return this->packets != NULL;
00128   }
00129 
00133   Packet *PopPacket()
00134   {
00135     if (this->mutex != NULL) this->mutex->BeginCritical();
00136 
00137     Packet *p = this->packets;
00138     this->packets = p->next;
00139     p->next = NULL;
00140 
00141     if (this->mutex != NULL) this->mutex->EndCritical();
00142 
00143     return p;
00144   }
00145 
00147   void AppendQueue()
00148   {
00149     if (this->current == NULL) return;
00150 
00151     Packet **p = &this->packets;
00152     while (*p != NULL) {
00153       p = &(*p)->next;
00154     }
00155     *p = this->current;
00156 
00157     this->current = NULL;
00158   }
00159 
00160   /* virtual */ void Write(byte *buf, size_t size)
00161   {
00162     /* We want to abort the saving when the socket is closed. */
00163     if (this->cs == NULL) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
00164 
00165     if (this->current == NULL) this->current = new Packet(PACKET_SERVER_MAP_DATA);
00166 
00167     if (this->mutex != NULL) this->mutex->BeginCritical();
00168 
00169     byte *bufe = buf + size;
00170     while (buf != bufe) {
00171       size_t to_write = min(SEND_MTU - this->current->size, bufe - buf);
00172       memcpy(this->current->buffer + this->current->size, buf, to_write);
00173       this->current->size += (PacketSize)to_write;
00174       buf += to_write;
00175 
00176       if (this->current->size == SEND_MTU) {
00177         this->AppendQueue();
00178         if (buf != bufe) this->current = new Packet(PACKET_SERVER_MAP_DATA);
00179       }
00180     }
00181 
00182     if (this->mutex != NULL) this->mutex->EndCritical();
00183 
00184     this->total_size += size;
00185   }
00186 
00187   /* virtual */ void Finish()
00188   {
00189     /* We want to abort the saving when the socket is closed. */
00190     if (this->cs == NULL) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
00191 
00192     if (this->mutex != NULL) this->mutex->BeginCritical();
00193 
00194     /* Make sure the last packet is flushed. */
00195     this->AppendQueue();
00196 
00197     /* Add a packet stating that this is the end to the queue. */
00198     this->current = new Packet(PACKET_SERVER_MAP_DONE);
00199     this->AppendQueue();
00200 
00201     /* Fast-track the size to the client. */
00202     Packet *p = new Packet(PACKET_SERVER_MAP_SIZE);
00203     p->Send_uint32((uint32)this->total_size);
00204     this->cs->NetworkTCPSocketHandler::SendPacket(p);
00205 
00206     if (this->mutex != NULL) this->mutex->EndCritical();
00207   }
00208 };
00209 
00210 
00215 ServerNetworkGameSocketHandler::ServerNetworkGameSocketHandler(SOCKET s) : NetworkGameSocketHandler(s)
00216 {
00217   this->status = STATUS_INACTIVE;
00218   this->client_id = _network_client_id++;
00219   this->receive_limit = _settings_client.network.bytes_per_frame_burst;
00220 
00221   /* The Socket and Info pools need to be the same in size. After all,
00222    * each Socket will be associated with at most one Info object. As
00223    * such if the Socket was allocated the Info object can as well. */
00224   assert_compile(NetworkClientSocketPool::MAX_SIZE == NetworkClientInfoPool::MAX_SIZE);
00225 }
00226 
00230 ServerNetworkGameSocketHandler::~ServerNetworkGameSocketHandler()
00231 {
00232   if (_redirect_console_to_client == this->client_id) _redirect_console_to_client = INVALID_CLIENT_ID;
00233   OrderBackup::ResetUser(this->client_id);
00234 
00235   if (this->savegame != NULL) {
00236     this->savegame->Destroy();
00237     this->savegame = NULL;
00238   }
00239 
00240   /* Make sure the saving is completely cancelled.
00241    * Yes, we need to handle the save finish as well
00242    * as the next connection in this "loop" might
00243    * just be requesting the map and such. */
00244   WaitTillSaved();
00245   ProcessAsyncSaveFinish();
00246 }
00247 
00248 Packet *ServerNetworkGameSocketHandler::ReceivePacket()
00249 {
00250   /* Only allow receiving when we have some buffer free; this value
00251    * can go negative, but eventually it will become positive again. */
00252   if (this->receive_limit <= 0) return NULL;
00253 
00254   /* We can receive a packet, so try that and if needed account for
00255    * the amount of received data. */
00256   Packet *p = this->NetworkTCPSocketHandler::ReceivePacket();
00257   if (p != NULL) this->receive_limit -= p->size;
00258   return p;
00259 }
00260 
00261 NetworkRecvStatus ServerNetworkGameSocketHandler::CloseConnection(NetworkRecvStatus status)
00262 {
00263   assert(status != NETWORK_RECV_STATUS_OKAY);
00264   /*
00265    * Sending a message just before leaving the game calls cs->SendPackets.
00266    * This might invoke this function, which means that when we close the
00267    * connection after cs->SendPackets we will close an already closed
00268    * connection. This handles that case gracefully without having to make
00269    * that code any more complex or more aware of the validity of the socket.
00270    */
00271   if (this->sock == INVALID_SOCKET) return status;
00272 
00273   if (status != NETWORK_RECV_STATUS_CONN_LOST && !this->HasClientQuit() && this->status >= STATUS_AUTHORIZED) {
00274     /* We did not receive a leave message from this client... */
00275     char client_name[NETWORK_CLIENT_NAME_LENGTH];
00276     NetworkClientSocket *new_cs;
00277 
00278     this->GetClientName(client_name, sizeof(client_name));
00279 
00280     NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST);
00281 
00282     /* Inform other clients of this... strange leaving ;) */
00283     FOR_ALL_CLIENT_SOCKETS(new_cs) {
00284       if (new_cs->status > STATUS_AUTHORIZED && this != new_cs) {
00285         new_cs->SendErrorQuit(this->client_id, NETWORK_ERROR_CONNECTION_LOST);
00286       }
00287     }
00288   }
00289 
00290   NetworkAdminClientError(this->client_id, NETWORK_ERROR_CONNECTION_LOST);
00291   DEBUG(net, 1, "Closed client connection %d", this->client_id);
00292 
00293   /* We just lost one client :( */
00294   if (this->status >= STATUS_AUTHORIZED) _network_game_info.clients_on--;
00295   extern byte _network_clients_connected;
00296   _network_clients_connected--;
00297 
00298   DeleteWindowById(WC_CLIENT_LIST_POPUP, this->client_id);
00299   SetWindowDirty(WC_CLIENT_LIST, 0);
00300 
00301   this->SendPackets(true);
00302 
00303   delete this->GetInfo();
00304   delete this;
00305 
00306   return status;
00307 }
00308 
00313 /* static */ bool ServerNetworkGameSocketHandler::AllowConnection()
00314 {
00315   extern byte _network_clients_connected;
00316   bool accept = _network_clients_connected < MAX_CLIENTS && _network_game_info.clients_on < _settings_client.network.max_clients;
00317 
00318   /* We can't go over the MAX_CLIENTS limit here. However, the
00319    * pool must have place for all clients and ourself. */
00320   assert_compile(NetworkClientSocketPool::MAX_SIZE == MAX_CLIENTS + 1);
00321   assert(!accept || ServerNetworkGameSocketHandler::CanAllocateItem());
00322   return accept;
00323 }
00324 
00326 /* static */ void ServerNetworkGameSocketHandler::Send()
00327 {
00328   NetworkClientSocket *cs;
00329   FOR_ALL_CLIENT_SOCKETS(cs) {
00330     if (cs->writable) {
00331       if (cs->SendPackets() != SPS_CLOSED && cs->status == STATUS_MAP) {
00332         /* This client is in the middle of a map-send, call the function for that */
00333         cs->SendMap();
00334       }
00335     }
00336   }
00337 }
00338 
00339 static void NetworkHandleCommandQueue(NetworkClientSocket *cs);
00340 
00341 /***********
00342  * Sending functions
00343  *   DEF_SERVER_SEND_COMMAND has parameter: NetworkClientSocket *cs
00344  ************/
00345 
00350 NetworkRecvStatus ServerNetworkGameSocketHandler::SendClientInfo(NetworkClientInfo *ci)
00351 {
00352   if (ci->client_id != INVALID_CLIENT_ID) {
00353     Packet *p = new Packet(PACKET_SERVER_CLIENT_INFO);
00354     p->Send_uint32(ci->client_id);
00355     p->Send_uint8 (ci->client_playas);
00356     p->Send_string(ci->client_name);
00357 
00358     this->SendPacket(p);
00359   }
00360   return NETWORK_RECV_STATUS_OKAY;
00361 }
00362 
00364 NetworkRecvStatus ServerNetworkGameSocketHandler::SendCompanyInfo()
00365 {
00366   /* Fetch the latest version of the stats */
00367   NetworkCompanyStats company_stats[MAX_COMPANIES];
00368   NetworkPopulateCompanyStats(company_stats);
00369 
00370   /* Make a list of all clients per company */
00371   char clients[MAX_COMPANIES][NETWORK_CLIENTS_LENGTH];
00372   NetworkClientSocket *csi;
00373   memset(clients, 0, sizeof(clients));
00374 
00375   /* Add the local player (if not dedicated) */
00376   const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
00377   if (ci != NULL && Company::IsValidID(ci->client_playas)) {
00378     strecpy(clients[ci->client_playas], ci->client_name, lastof(clients[ci->client_playas]));
00379   }
00380 
00381   FOR_ALL_CLIENT_SOCKETS(csi) {
00382     char client_name[NETWORK_CLIENT_NAME_LENGTH];
00383 
00384     ((ServerNetworkGameSocketHandler*)csi)->GetClientName(client_name, sizeof(client_name));
00385 
00386     ci = csi->GetInfo();
00387     if (ci != NULL && Company::IsValidID(ci->client_playas)) {
00388       if (!StrEmpty(clients[ci->client_playas])) {
00389         strecat(clients[ci->client_playas], ", ", lastof(clients[ci->client_playas]));
00390       }
00391 
00392       strecat(clients[ci->client_playas], client_name, lastof(clients[ci->client_playas]));
00393     }
00394   }
00395 
00396   /* Now send the data */
00397 
00398   Company *company;
00399   Packet *p;
00400 
00401   FOR_ALL_COMPANIES(company) {
00402     p = new Packet(PACKET_SERVER_COMPANY_INFO);
00403 
00404     p->Send_uint8 (NETWORK_COMPANY_INFO_VERSION);
00405     p->Send_bool  (true);
00406     this->SendCompanyInformation(p, company, &company_stats[company->index]);
00407 
00408     if (StrEmpty(clients[company->index])) {
00409       p->Send_string("<none>");
00410     } else {
00411       p->Send_string(clients[company->index]);
00412     }
00413 
00414     this->SendPacket(p);
00415   }
00416 
00417   p = new Packet(PACKET_SERVER_COMPANY_INFO);
00418 
00419   p->Send_uint8 (NETWORK_COMPANY_INFO_VERSION);
00420   p->Send_bool  (false);
00421 
00422   this->SendPacket(p);
00423   return NETWORK_RECV_STATUS_OKAY;
00424 }
00425 
00430 NetworkRecvStatus ServerNetworkGameSocketHandler::SendError(NetworkErrorCode error)
00431 {
00432   char str[100];
00433   Packet *p = new Packet(PACKET_SERVER_ERROR);
00434 
00435   p->Send_uint8(error);
00436   this->SendPacket(p);
00437 
00438   StringID strid = GetNetworkErrorMsg(error);
00439   GetString(str, strid, lastof(str));
00440 
00441   /* Only send when the current client was in game */
00442   if (this->status > STATUS_AUTHORIZED) {
00443     NetworkClientSocket *new_cs;
00444     char client_name[NETWORK_CLIENT_NAME_LENGTH];
00445 
00446     this->GetClientName(client_name, sizeof(client_name));
00447 
00448     DEBUG(net, 1, "'%s' made an error and has been disconnected. Reason: '%s'", client_name, str);
00449 
00450     NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, strid);
00451 
00452     FOR_ALL_CLIENT_SOCKETS(new_cs) {
00453       if (new_cs->status > STATUS_AUTHORIZED && new_cs != this) {
00454         /* Some errors we filter to a more general error. Clients don't have to know the real
00455          *  reason a joining failed. */
00456         if (error == NETWORK_ERROR_NOT_AUTHORIZED || error == NETWORK_ERROR_NOT_EXPECTED || error == NETWORK_ERROR_WRONG_REVISION) {
00457           error = NETWORK_ERROR_ILLEGAL_PACKET;
00458         }
00459         new_cs->SendErrorQuit(this->client_id, error);
00460       }
00461     }
00462 
00463     NetworkAdminClientError(this->client_id, error);
00464   } else {
00465     DEBUG(net, 1, "Client %d made an error and has been disconnected. Reason: '%s'", this->client_id, str);
00466   }
00467 
00468   /* The client made a mistake, so drop his connection now! */
00469   return this->CloseConnection(NETWORK_RECV_STATUS_SERVER_ERROR);
00470 }
00471 
00473 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGRFCheck()
00474 {
00475   Packet *p = new Packet(PACKET_SERVER_CHECK_NEWGRFS);
00476   const GRFConfig *c;
00477   uint grf_count = 0;
00478 
00479   for (c = _grfconfig; c != NULL; c = c->next) {
00480     if (!HasBit(c->flags, GCF_STATIC)) grf_count++;
00481   }
00482 
00483   p->Send_uint8 (grf_count);
00484   for (c = _grfconfig; c != NULL; c = c->next) {
00485     if (!HasBit(c->flags, GCF_STATIC)) this->SendGRFIdentifier(p, &c->ident);
00486   }
00487 
00488   this->SendPacket(p);
00489   return NETWORK_RECV_STATUS_OKAY;
00490 }
00491 
00493 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNeedGamePassword()
00494 {
00495   /* Invalid packet when status is STATUS_AUTH_GAME or higher */
00496   if (this->status >= STATUS_AUTH_GAME) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
00497 
00498   this->status = STATUS_AUTH_GAME;
00499   /* Reset 'lag' counters */
00500   this->last_frame = this->last_frame_server = _frame_counter;
00501 
00502   Packet *p = new Packet(PACKET_SERVER_NEED_GAME_PASSWORD);
00503   this->SendPacket(p);
00504   return NETWORK_RECV_STATUS_OKAY;
00505 }
00506 
00508 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNeedCompanyPassword()
00509 {
00510   /* Invalid packet when status is STATUS_AUTH_COMPANY or higher */
00511   if (this->status >= STATUS_AUTH_COMPANY) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
00512 
00513   this->status = STATUS_AUTH_COMPANY;
00514   /* Reset 'lag' counters */
00515   this->last_frame = this->last_frame_server = _frame_counter;
00516 
00517   Packet *p = new Packet(PACKET_SERVER_NEED_COMPANY_PASSWORD);
00518   p->Send_uint32(_settings_game.game_creation.generation_seed);
00519   p->Send_string(_settings_client.network.network_id);
00520   this->SendPacket(p);
00521   return NETWORK_RECV_STATUS_OKAY;
00522 }
00523 
00525 NetworkRecvStatus ServerNetworkGameSocketHandler::SendWelcome()
00526 {
00527   Packet *p;
00528   NetworkClientSocket *new_cs;
00529 
00530   /* Invalid packet when status is AUTH or higher */
00531   if (this->status >= STATUS_AUTHORIZED) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
00532 
00533   this->status = STATUS_AUTHORIZED;
00534   /* Reset 'lag' counters */
00535   this->last_frame = this->last_frame_server = _frame_counter;
00536 
00537   _network_game_info.clients_on++;
00538 
00539   p = new Packet(PACKET_SERVER_WELCOME);
00540   p->Send_uint32(this->client_id);
00541   p->Send_uint32(_settings_game.game_creation.generation_seed);
00542   p->Send_string(_settings_client.network.network_id);
00543   this->SendPacket(p);
00544 
00545   /* Transmit info about all the active clients */
00546   FOR_ALL_CLIENT_SOCKETS(new_cs) {
00547     if (new_cs != this && new_cs->status > STATUS_AUTHORIZED) {
00548       this->SendClientInfo(new_cs->GetInfo());
00549     }
00550   }
00551   /* Also send the info of the server */
00552   return this->SendClientInfo(NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER));
00553 }
00554 
00556 NetworkRecvStatus ServerNetworkGameSocketHandler::SendWait()
00557 {
00558   int waiting = 0;
00559   NetworkClientSocket *new_cs;
00560   Packet *p;
00561 
00562   /* Count how many clients are waiting in the queue, in front of you! */
00563   FOR_ALL_CLIENT_SOCKETS(new_cs) {
00564     if (new_cs->status != STATUS_MAP_WAIT) continue;
00565     if (new_cs->GetInfo()->join_date < this->GetInfo()->join_date || (new_cs->GetInfo()->join_date == this->GetInfo()->join_date && new_cs->client_id < this->client_id)) waiting++;
00566   }
00567 
00568   p = new Packet(PACKET_SERVER_WAIT);
00569   p->Send_uint8(waiting);
00570   this->SendPacket(p);
00571   return NETWORK_RECV_STATUS_OKAY;
00572 }
00573 
00575 NetworkRecvStatus ServerNetworkGameSocketHandler::SendMap()
00576 {
00577   static uint sent_packets; // How many packets we did send successfully last time
00578 
00579   if (this->status < STATUS_AUTHORIZED) {
00580     /* Illegal call, return error and ignore the packet */
00581     return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
00582   }
00583 
00584   if (this->status == STATUS_AUTHORIZED) {
00585     this->savegame = new PacketWriter(this);
00586 
00587     /* Now send the _frame_counter and how many packets are coming */
00588     Packet *p = new Packet(PACKET_SERVER_MAP_BEGIN);
00589     p->Send_uint32(_frame_counter);
00590     this->SendPacket(p);
00591 
00592     NetworkSyncCommandQueue(this);
00593     this->status = STATUS_MAP;
00594     /* Mark the start of download */
00595     this->last_frame = _frame_counter;
00596     this->last_frame_server = _frame_counter;
00597 
00598     sent_packets = 4; // We start with trying 4 packets
00599 
00600     /* Make a dump of the current game */
00601     if (SaveWithFilter(this->savegame, true) != SL_OK) usererror("network savedump failed");
00602   }
00603 
00604   if (this->status == STATUS_MAP) {
00605     bool last_packet = false;
00606     bool has_packets = false;
00607 
00608     for (uint i = 0; (has_packets = this->savegame->HasPackets()) && i < sent_packets; i++) {
00609       Packet *p = this->savegame->PopPacket();
00610       last_packet = p->buffer[2] == PACKET_SERVER_MAP_DONE;
00611 
00612       this->SendPacket(p);
00613 
00614       if (last_packet) {
00615         /* There is no more data, so break the for */
00616         break;
00617       }
00618     }
00619 
00620     if (last_packet) {
00621       /* Done reading, make sure saving is done as well */
00622       this->savegame->Destroy();
00623       this->savegame = NULL;
00624 
00625       WaitTillSaved();
00626 
00627       /* Set the status to DONE_MAP, no we will wait for the client
00628        *  to send it is ready (maybe that happens like never ;)) */
00629       this->status = STATUS_DONE_MAP;
00630 
00631       /* Find the best candidate for joining, i.e. the first joiner. */
00632       NetworkClientSocket *new_cs;
00633       NetworkClientSocket *best = NULL;
00634       FOR_ALL_CLIENT_SOCKETS(new_cs) {
00635         if (new_cs->status == STATUS_MAP_WAIT) {
00636           if (best == NULL || best->GetInfo()->join_date > new_cs->GetInfo()->join_date || (best->GetInfo()->join_date == new_cs->GetInfo()->join_date && best->client_id > new_cs->client_id)) {
00637             best = new_cs;
00638           }
00639         }
00640       }
00641 
00642       /* Is there someone else to join? */
00643       if (best != NULL) {
00644         /* Let the first start joining. */
00645         best->status = STATUS_AUTHORIZED;
00646         best->SendMap();
00647 
00648         /* And update the rest. */
00649         FOR_ALL_CLIENT_SOCKETS(new_cs) {
00650           if (new_cs->status == STATUS_MAP_WAIT) new_cs->SendWait();
00651         }
00652       }
00653     }
00654 
00655     switch (this->SendPackets()) {
00656       case SPS_CLOSED:
00657         return NETWORK_RECV_STATUS_CONN_LOST;
00658 
00659       case SPS_ALL_SENT:
00660         /* All are sent, increase the sent_packets */
00661         if (has_packets) sent_packets *= 2;
00662         break;
00663 
00664       case SPS_PARTLY_SENT:
00665         /* Only a part is sent; leave the transmission state. */
00666         break;
00667 
00668       case SPS_NONE_SENT:
00669         /* Not everything is sent, decrease the sent_packets */
00670         if (sent_packets > 1) sent_packets /= 2;
00671         break;
00672     }
00673   }
00674   return NETWORK_RECV_STATUS_OKAY;
00675 }
00676 
00681 NetworkRecvStatus ServerNetworkGameSocketHandler::SendJoin(ClientID client_id)
00682 {
00683   Packet *p = new Packet(PACKET_SERVER_JOIN);
00684 
00685   p->Send_uint32(client_id);
00686 
00687   this->SendPacket(p);
00688   return NETWORK_RECV_STATUS_OKAY;
00689 }
00690 
00692 NetworkRecvStatus ServerNetworkGameSocketHandler::SendFrame()
00693 {
00694   Packet *p = new Packet(PACKET_SERVER_FRAME);
00695   p->Send_uint32(_frame_counter);
00696   p->Send_uint32(_frame_counter_max);
00697 #ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
00698   p->Send_uint32(_sync_seed_1);
00699 #ifdef NETWORK_SEND_DOUBLE_SEED
00700   p->Send_uint32(_sync_seed_2);
00701 #endif
00702 #endif
00703 
00704   /* If token equals 0, we need to make a new token and send that. */
00705   if (this->last_token == 0) {
00706     this->last_token = InteractiveRandomRange(UINT8_MAX - 1) + 1;
00707     p->Send_uint8(this->last_token);
00708   }
00709 
00710   this->SendPacket(p);
00711   return NETWORK_RECV_STATUS_OKAY;
00712 }
00713 
00715 NetworkRecvStatus ServerNetworkGameSocketHandler::SendSync()
00716 {
00717   Packet *p = new Packet(PACKET_SERVER_SYNC);
00718   p->Send_uint32(_frame_counter);
00719   p->Send_uint32(_sync_seed_1);
00720 
00721 #ifdef NETWORK_SEND_DOUBLE_SEED
00722   p->Send_uint32(_sync_seed_2);
00723 #endif
00724   this->SendPacket(p);
00725   return NETWORK_RECV_STATUS_OKAY;
00726 }
00727 
00732 NetworkRecvStatus ServerNetworkGameSocketHandler::SendCommand(const CommandPacket *cp)
00733 {
00734   Packet *p = new Packet(PACKET_SERVER_COMMAND);
00735 
00736   this->NetworkGameSocketHandler::SendCommand(p, cp);
00737   p->Send_uint32(cp->frame);
00738   p->Send_bool  (cp->my_cmd);
00739 
00740   this->SendPacket(p);
00741   return NETWORK_RECV_STATUS_OKAY;
00742 }
00743 
00752 NetworkRecvStatus ServerNetworkGameSocketHandler::SendChat(NetworkAction action, ClientID client_id, bool self_send, const char *msg, int64 data)
00753 {
00754   if (this->status < STATUS_PRE_ACTIVE) return NETWORK_RECV_STATUS_OKAY;
00755 
00756   Packet *p = new Packet(PACKET_SERVER_CHAT);
00757 
00758   p->Send_uint8 (action);
00759   p->Send_uint32(client_id);
00760   p->Send_bool  (self_send);
00761   p->Send_string(msg);
00762   p->Send_uint64(data);
00763 
00764   this->SendPacket(p);
00765   return NETWORK_RECV_STATUS_OKAY;
00766 }
00767 
00773 NetworkRecvStatus ServerNetworkGameSocketHandler::SendErrorQuit(ClientID client_id, NetworkErrorCode errorno)
00774 {
00775   Packet *p = new Packet(PACKET_SERVER_ERROR_QUIT);
00776 
00777   p->Send_uint32(client_id);
00778   p->Send_uint8 (errorno);
00779 
00780   this->SendPacket(p);
00781   return NETWORK_RECV_STATUS_OKAY;
00782 }
00783 
00788 NetworkRecvStatus ServerNetworkGameSocketHandler::SendQuit(ClientID client_id)
00789 {
00790   Packet *p = new Packet(PACKET_SERVER_QUIT);
00791 
00792   p->Send_uint32(client_id);
00793 
00794   this->SendPacket(p);
00795   return NETWORK_RECV_STATUS_OKAY;
00796 }
00797 
00799 NetworkRecvStatus ServerNetworkGameSocketHandler::SendShutdown()
00800 {
00801   Packet *p = new Packet(PACKET_SERVER_SHUTDOWN);
00802   this->SendPacket(p);
00803   return NETWORK_RECV_STATUS_OKAY;
00804 }
00805 
00807 NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGame()
00808 {
00809   Packet *p = new Packet(PACKET_SERVER_NEWGAME);
00810   this->SendPacket(p);
00811   return NETWORK_RECV_STATUS_OKAY;
00812 }
00813 
00819 NetworkRecvStatus ServerNetworkGameSocketHandler::SendRConResult(uint16 colour, const char *command)
00820 {
00821   Packet *p = new Packet(PACKET_SERVER_RCON);
00822 
00823   p->Send_uint16(colour);
00824   p->Send_string(command);
00825   this->SendPacket(p);
00826   return NETWORK_RECV_STATUS_OKAY;
00827 }
00828 
00834 NetworkRecvStatus ServerNetworkGameSocketHandler::SendMove(ClientID client_id, CompanyID company_id)
00835 {
00836   Packet *p = new Packet(PACKET_SERVER_MOVE);
00837 
00838   p->Send_uint32(client_id);
00839   p->Send_uint8(company_id);
00840   this->SendPacket(p);
00841   return NETWORK_RECV_STATUS_OKAY;
00842 }
00843 
00845 NetworkRecvStatus ServerNetworkGameSocketHandler::SendCompanyUpdate()
00846 {
00847   Packet *p = new Packet(PACKET_SERVER_COMPANY_UPDATE);
00848 
00849   p->Send_uint16(_network_company_passworded);
00850   this->SendPacket(p);
00851   return NETWORK_RECV_STATUS_OKAY;
00852 }
00853 
00855 NetworkRecvStatus ServerNetworkGameSocketHandler::SendConfigUpdate()
00856 {
00857   Packet *p = new Packet(PACKET_SERVER_CONFIG_UPDATE);
00858 
00859   p->Send_uint8(_settings_client.network.max_companies);
00860   p->Send_uint8(_settings_client.network.max_spectators);
00861   this->SendPacket(p);
00862   return NETWORK_RECV_STATUS_OKAY;
00863 }
00864 
00865 /***********
00866  * Receiving functions
00867  *   DEF_SERVER_RECEIVE_COMMAND has parameter: NetworkClientSocket *cs, Packet *p
00868  ************/
00869 
00870 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMPANY_INFO(Packet *p)
00871 {
00872   return this->SendCompanyInfo();
00873 }
00874 
00875 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_NEWGRFS_CHECKED(Packet *p)
00876 {
00877   if (this->status != STATUS_NEWGRFS_CHECK) {
00878     /* Illegal call, return error and ignore the packet */
00879     return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
00880   }
00881 
00882   NetworkClientInfo *ci = this->GetInfo();
00883 
00884   /* We now want a password from the client else we do not allow him in! */
00885   if (!StrEmpty(_settings_client.network.server_password)) {
00886     return this->SendNeedGamePassword();
00887   }
00888 
00889   if (Company::IsValidID(ci->client_playas) && !StrEmpty(_network_company_states[ci->client_playas].password)) {
00890     return this->SendNeedCompanyPassword();
00891   }
00892 
00893   return this->SendWelcome();
00894 }
00895 
00896 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet *p)
00897 {
00898   if (this->status != STATUS_INACTIVE) {
00899     /* Illegal call, return error and ignore the packet */
00900     return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
00901   }
00902 
00903   char name[NETWORK_CLIENT_NAME_LENGTH];
00904   CompanyID playas;
00905   NetworkLanguage client_lang;
00906   char client_revision[NETWORK_REVISION_LENGTH];
00907 
00908   p->Recv_string(client_revision, sizeof(client_revision));
00909   uint32 newgrf_version = p->Recv_uint32();
00910 
00911   /* Check if the client has revision control enabled */
00912   if (!IsNetworkCompatibleVersion(client_revision) || _openttd_newgrf_version != newgrf_version) {
00913     /* Different revisions!! */
00914     return this->SendError(NETWORK_ERROR_WRONG_REVISION);
00915   }
00916 
00917   p->Recv_string(name, sizeof(name));
00918   playas = (Owner)p->Recv_uint8();
00919   client_lang = (NetworkLanguage)p->Recv_uint8();
00920 
00921   if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
00922 
00923   /* join another company does not affect these values */
00924   switch (playas) {
00925     case COMPANY_NEW_COMPANY: // New company
00926       if (Company::GetNumItems() >= _settings_client.network.max_companies) {
00927         return this->SendError(NETWORK_ERROR_FULL);
00928       }
00929       break;
00930     case COMPANY_SPECTATOR: // Spectator
00931       if (NetworkSpectatorCount() >= _settings_client.network.max_spectators) {
00932         return this->SendError(NETWORK_ERROR_FULL);
00933       }
00934       break;
00935     default: // Join another company (companies 1-8 (index 0-7))
00936       if (!Company::IsValidHumanID(playas)) {
00937         return this->SendError(NETWORK_ERROR_COMPANY_MISMATCH);
00938       }
00939       break;
00940   }
00941 
00942   /* We need a valid name.. make it Player */
00943   if (StrEmpty(name)) strecpy(name, "Player", lastof(name));
00944 
00945   if (!NetworkFindName(name)) { // Change name if duplicate
00946     /* We could not create a name for this client */
00947     return this->SendError(NETWORK_ERROR_NAME_IN_USE);
00948   }
00949 
00950   assert(NetworkClientInfo::CanAllocateItem());
00951   NetworkClientInfo *ci = new NetworkClientInfo(this->client_id);
00952   this->SetInfo(ci);
00953   ci->join_date = _date;
00954   strecpy(ci->client_name, name, lastof(ci->client_name));
00955   ci->client_playas = playas;
00956   ci->client_lang = client_lang;
00957   DEBUG(desync, 1, "client: %08x; %02x; %02x; %04x", _date, _date_fract, (int)ci->client_playas, ci->index);
00958 
00959   /* Make sure companies to which people try to join are not autocleaned */
00960   if (Company::IsValidID(playas)) _network_company_states[playas].months_empty = 0;
00961 
00962   this->status = STATUS_NEWGRFS_CHECK;
00963 
00964   if (_grfconfig == NULL) {
00965     /* Behave as if we received PACKET_CLIENT_NEWGRFS_CHECKED */
00966     return this->Receive_CLIENT_NEWGRFS_CHECKED(NULL);
00967   }
00968 
00969   return this->SendNewGRFCheck();
00970 }
00971 
00972 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GAME_PASSWORD(Packet *p)
00973 {
00974   if (this->status != STATUS_AUTH_GAME) {
00975     return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
00976   }
00977 
00978   char password[NETWORK_PASSWORD_LENGTH];
00979   p->Recv_string(password, sizeof(password));
00980 
00981   /* Check game password. Allow joining if we cleared the password meanwhile */
00982   if (!StrEmpty(_settings_client.network.server_password) &&
00983       strcmp(password, _settings_client.network.server_password) != 0) {
00984     /* Password is invalid */
00985     return this->SendError(NETWORK_ERROR_WRONG_PASSWORD);
00986   }
00987 
00988   const NetworkClientInfo *ci = this->GetInfo();
00989   if (Company::IsValidID(ci->client_playas) && !StrEmpty(_network_company_states[ci->client_playas].password)) {
00990     return this->SendNeedCompanyPassword();
00991   }
00992 
00993   /* Valid password, allow user */
00994   return this->SendWelcome();
00995 }
00996 
00997 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMPANY_PASSWORD(Packet *p)
00998 {
00999   if (this->status != STATUS_AUTH_COMPANY) {
01000     return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
01001   }
01002 
01003   char password[NETWORK_PASSWORD_LENGTH];
01004   p->Recv_string(password, sizeof(password));
01005 
01006   /* Check company password. Allow joining if we cleared the password meanwhile.
01007    * Also, check the company is still valid - client could be moved to spectators
01008    * in the middle of the authorization process */
01009   CompanyID playas = this->GetInfo()->client_playas;
01010   if (Company::IsValidID(playas) && !StrEmpty(_network_company_states[playas].password) &&
01011       strcmp(password, _network_company_states[playas].password) != 0) {
01012     /* Password is invalid */
01013     return this->SendError(NETWORK_ERROR_WRONG_PASSWORD);
01014   }
01015 
01016   return this->SendWelcome();
01017 }
01018 
01019 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GETMAP(Packet *p)
01020 {
01021   NetworkClientSocket *new_cs;
01022   /* The client was never joined.. so this is impossible, right?
01023    *  Ignore the packet, give the client a warning, and close his connection */
01024   if (this->status < STATUS_AUTHORIZED || this->HasClientQuit()) {
01025     return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
01026   }
01027 
01028   /* Check if someone else is receiving the map */
01029   FOR_ALL_CLIENT_SOCKETS(new_cs) {
01030     if (new_cs->status == STATUS_MAP) {
01031       /* Tell the new client to wait */
01032       this->status = STATUS_MAP_WAIT;
01033       return this->SendWait();
01034     }
01035   }
01036 
01037   /* We receive a request to upload the map.. give it to the client! */
01038   return this->SendMap();
01039 }
01040 
01041 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MAP_OK(Packet *p)
01042 {
01043   /* Client has the map, now start syncing */
01044   if (this->status == STATUS_DONE_MAP && !this->HasClientQuit()) {
01045     char client_name[NETWORK_CLIENT_NAME_LENGTH];
01046     NetworkClientSocket *new_cs;
01047 
01048     this->GetClientName(client_name, sizeof(client_name));
01049 
01050     NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, client_name, NULL, this->client_id);
01051 
01052     /* Mark the client as pre-active, and wait for an ACK
01053      *  so we know he is done loading and in sync with us */
01054     this->status = STATUS_PRE_ACTIVE;
01055     NetworkHandleCommandQueue(this);
01056     this->SendFrame();
01057     this->SendSync();
01058 
01059     /* This is the frame the client receives
01060      *  we need it later on to make sure the client is not too slow */
01061     this->last_frame = _frame_counter;
01062     this->last_frame_server = _frame_counter;
01063 
01064     FOR_ALL_CLIENT_SOCKETS(new_cs) {
01065       if (new_cs->status > STATUS_AUTHORIZED) {
01066         new_cs->SendClientInfo(this->GetInfo());
01067         new_cs->SendJoin(this->client_id);
01068       }
01069     }
01070 
01071     NetworkAdminClientInfo(this, true);
01072 
01073     /* also update the new client with our max values */
01074     this->SendConfigUpdate();
01075 
01076     /* quickly update the syncing client with company details */
01077     return this->SendCompanyUpdate();
01078   }
01079 
01080   /* Wrong status for this packet, give a warning to client, and close connection */
01081   return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
01082 }
01083 
01088 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMMAND(Packet *p)
01089 {
01090   /* The client was never joined.. so this is impossible, right?
01091    *  Ignore the packet, give the client a warning, and close his connection */
01092   if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
01093     return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
01094   }
01095 
01096   if (this->incoming_queue.Count() >= _settings_client.network.max_commands_in_queue) {
01097     return this->SendError(NETWORK_ERROR_TOO_MANY_COMMANDS);
01098   }
01099 
01100   CommandPacket cp;
01101   const char *err = this->ReceiveCommand(p, &cp);
01102 
01103   if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
01104 
01105   NetworkClientInfo *ci = this->GetInfo();
01106 
01107   if (err != NULL) {
01108     IConsolePrintF(CC_ERROR, "WARNING: %s from client %d (IP: %s).", err, ci->client_id, this->GetClientIP());
01109     return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
01110   }
01111 
01112 
01113   if ((GetCommandFlags(cp.cmd) & CMD_SERVER) && ci->client_id != CLIENT_ID_SERVER) {
01114     IConsolePrintF(CC_ERROR, "WARNING: server only command from: client %d (IP: %s), kicking...", ci->client_id, this->GetClientIP());
01115     return this->SendError(NETWORK_ERROR_KICKED);
01116   }
01117 
01118   if ((GetCommandFlags(cp.cmd) & CMD_SPECTATOR) == 0 && !Company::IsValidID(cp.company) && ci->client_id != CLIENT_ID_SERVER) {
01119     IConsolePrintF(CC_ERROR, "WARNING: spectator issueing command from client %d (IP: %s), kicking...", ci->client_id, this->GetClientIP());
01120     return this->SendError(NETWORK_ERROR_KICKED);
01121   }
01122 
01128   if (!(cp.cmd == CMD_COMPANY_CTRL && cp.p1 == 0 && ci->client_playas == COMPANY_NEW_COMPANY) && ci->client_playas != cp.company) {
01129     IConsolePrintF(CC_ERROR, "WARNING: client %d (IP: %s) tried to execute a command as company %d, kicking...",
01130                    ci->client_playas + 1, this->GetClientIP(), cp.company + 1);
01131     return this->SendError(NETWORK_ERROR_COMPANY_MISMATCH);
01132   }
01133 
01134   if (cp.cmd == CMD_COMPANY_CTRL) {
01135     if (cp.p1 != 0 || cp.company != COMPANY_SPECTATOR) {
01136       return this->SendError(NETWORK_ERROR_CHEATER);
01137     }
01138 
01139     /* 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! */
01140     if (Company::GetNumItems() >= _settings_client.network.max_companies) {
01141       NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_CLIENT, ci->client_id, "cannot create new company, server full", CLIENT_ID_SERVER);
01142       return NETWORK_RECV_STATUS_OKAY;
01143     }
01144   }
01145 
01146   if (GetCommandFlags(cp.cmd) & CMD_CLIENT_ID) cp.p2 = this->client_id;
01147 
01148   this->incoming_queue.Append(&cp);
01149   return NETWORK_RECV_STATUS_OKAY;
01150 }
01151 
01152 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ERROR(Packet *p)
01153 {
01154   /* This packets means a client noticed an error and is reporting this
01155    *  to us. Display the error and report it to the other clients */
01156   NetworkClientSocket *new_cs;
01157   char str[100];
01158   char client_name[NETWORK_CLIENT_NAME_LENGTH];
01159   NetworkErrorCode errorno = (NetworkErrorCode)p->Recv_uint8();
01160 
01161   /* The client was never joined.. thank the client for the packet, but ignore it */
01162   if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
01163     return this->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
01164   }
01165 
01166   this->GetClientName(client_name, sizeof(client_name));
01167 
01168   StringID strid = GetNetworkErrorMsg(errorno);
01169   GetString(str, strid, lastof(str));
01170 
01171   DEBUG(net, 2, "'%s' reported an error and is closing its connection (%s)", client_name, str);
01172 
01173   NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, strid);
01174 
01175   FOR_ALL_CLIENT_SOCKETS(new_cs) {
01176     if (new_cs->status > STATUS_AUTHORIZED) {
01177       new_cs->SendErrorQuit(this->client_id, errorno);
01178     }
01179   }
01180 
01181   NetworkAdminClientError(this->client_id, errorno);
01182 
01183   return this->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
01184 }
01185 
01186 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_QUIT(Packet *p)
01187 {
01188   /* The client wants to leave. Display this and report it to the other
01189    *  clients. */
01190   NetworkClientSocket *new_cs;
01191   char client_name[NETWORK_CLIENT_NAME_LENGTH];
01192 
01193   /* The client was never joined.. thank the client for the packet, but ignore it */
01194   if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
01195     return this->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
01196   }
01197 
01198   this->GetClientName(client_name, sizeof(client_name));
01199 
01200   NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, STR_NETWORK_MESSAGE_CLIENT_LEAVING);
01201 
01202   FOR_ALL_CLIENT_SOCKETS(new_cs) {
01203     if (new_cs->status > STATUS_AUTHORIZED && new_cs != this) {
01204       new_cs->SendQuit(this->client_id);
01205     }
01206   }
01207 
01208   NetworkAdminClientQuit(this->client_id);
01209 
01210   return this->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
01211 }
01212 
01213 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ACK(Packet *p)
01214 {
01215   if (this->status < STATUS_AUTHORIZED) {
01216     /* Illegal call, return error and ignore the packet */
01217     return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
01218   }
01219 
01220   uint32 frame = p->Recv_uint32();
01221 
01222   /* The client is trying to catch up with the server */
01223   if (this->status == STATUS_PRE_ACTIVE) {
01224     /* The client is not yet catched up? */
01225     if (frame + DAY_TICKS < _frame_counter) return NETWORK_RECV_STATUS_OKAY;
01226 
01227     /* Now he is! Unpause the game */
01228     this->status = STATUS_ACTIVE;
01229     this->last_token_frame = _frame_counter;
01230 
01231     /* Execute script for, e.g. MOTD */
01232     IConsoleCmdExec("exec scripts/on_server_connect.scr 0");
01233   }
01234 
01235   /* Get, and validate the token. */
01236   uint8 token = p->Recv_uint8();
01237   if (token == this->last_token) {
01238     /* We differentiate between last_token_frame and last_frame so the lag
01239      * test uses the actual lag of the client instead of the lag for getting
01240      * the token back and forth; after all, the token is only sent every
01241      * time we receive a PACKET_CLIENT_ACK, after which we will send a new
01242      * token to the client. If the lag would be one day, then we would not
01243      * be sending the new token soon enough for the new daily scheduled
01244      * PACKET_CLIENT_ACK. This would then register the lag of the client as
01245      * two days, even when it's only a single day. */
01246     this->last_token_frame = _frame_counter;
01247     /* Request a new token. */
01248     this->last_token = 0;
01249   }
01250 
01251   /* The client received the frame, make note of it */
01252   this->last_frame = frame;
01253   /* With those 2 values we can calculate the lag realtime */
01254   this->last_frame_server = _frame_counter;
01255   return NETWORK_RECV_STATUS_OKAY;
01256 }
01257 
01258 
01269 void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, const char *msg, ClientID from_id, int64 data, bool from_admin)
01270 {
01271   NetworkClientSocket *cs;
01272   const NetworkClientInfo *ci, *ci_own, *ci_to;
01273 
01274   switch (desttype) {
01275     case DESTTYPE_CLIENT:
01276       /* Are we sending to the server? */
01277       if ((ClientID)dest == CLIENT_ID_SERVER) {
01278         ci = NetworkClientInfo::GetByClientID(from_id);
01279         /* Display the text locally, and that is it */
01280         if (ci != NULL) {
01281           NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
01282 
01283           if (_settings_client.network.server_admin_chat) {
01284             NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
01285           }
01286         }
01287       } else {
01288         /* Else find the client to send the message to */
01289         FOR_ALL_CLIENT_SOCKETS(cs) {
01290           if (cs->client_id == (ClientID)dest) {
01291             cs->SendChat(action, from_id, false, msg, data);
01292             break;
01293           }
01294         }
01295       }
01296 
01297       /* Display the message locally (so you know you have sent it) */
01298       if (from_id != (ClientID)dest) {
01299         if (from_id == CLIENT_ID_SERVER) {
01300           ci = NetworkClientInfo::GetByClientID(from_id);
01301           ci_to = NetworkClientInfo::GetByClientID((ClientID)dest);
01302           if (ci != NULL && ci_to != NULL) {
01303             NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), true, ci_to->client_name, msg, data);
01304           }
01305         } else {
01306           FOR_ALL_CLIENT_SOCKETS(cs) {
01307             if (cs->client_id == from_id) {
01308               cs->SendChat(action, (ClientID)dest, true, msg, data);
01309               break;
01310             }
01311           }
01312         }
01313       }
01314       break;
01315     case DESTTYPE_TEAM: {
01316       /* If this is false, the message is already displayed on the client who sent it. */
01317       bool show_local = true;
01318       /* Find all clients that belong to this company */
01319       ci_to = NULL;
01320       FOR_ALL_CLIENT_SOCKETS(cs) {
01321         ci = cs->GetInfo();
01322         if (ci != NULL && ci->client_playas == (CompanyID)dest) {
01323           cs->SendChat(action, from_id, false, msg, data);
01324           if (cs->client_id == from_id) show_local = false;
01325           ci_to = ci; // Remember a client that is in the company for company-name
01326         }
01327       }
01328 
01329       /* if the server can read it, let the admin network read it, too. */
01330       if (_local_company == (CompanyID)dest && _settings_client.network.server_admin_chat) {
01331         NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
01332       }
01333 
01334       ci = NetworkClientInfo::GetByClientID(from_id);
01335       ci_own = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
01336       if (ci != NULL && ci_own != NULL && ci_own->client_playas == dest) {
01337         NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
01338         if (from_id == CLIENT_ID_SERVER) show_local = false;
01339         ci_to = ci_own;
01340       }
01341 
01342       /* There is no such client */
01343       if (ci_to == NULL) break;
01344 
01345       /* Display the message locally (so you know you have sent it) */
01346       if (ci != NULL && show_local) {
01347         if (from_id == CLIENT_ID_SERVER) {
01348           char name[NETWORK_NAME_LENGTH];
01349           StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
01350           SetDParam(0, ci_to->client_playas);
01351           GetString(name, str, lastof(name));
01352           NetworkTextMessage(action, GetDrawStringCompanyColour(ci_own->client_playas), true, name, msg, data);
01353         } else {
01354           FOR_ALL_CLIENT_SOCKETS(cs) {
01355             if (cs->client_id == from_id) {
01356               cs->SendChat(action, ci_to->client_id, true, msg, data);
01357             }
01358           }
01359         }
01360       }
01361       break;
01362     }
01363     default:
01364       DEBUG(net, 0, "[server] received unknown chat destination type %d. Doing broadcast instead", desttype);
01365       /* FALL THROUGH */
01366     case DESTTYPE_BROADCAST:
01367       FOR_ALL_CLIENT_SOCKETS(cs) {
01368         cs->SendChat(action, from_id, false, msg, data);
01369       }
01370 
01371       NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
01372 
01373       ci = NetworkClientInfo::GetByClientID(from_id);
01374       if (ci != NULL) {
01375         NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
01376       }
01377       break;
01378   }
01379 }
01380 
01381 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_CHAT(Packet *p)
01382 {
01383   if (this->status < STATUS_PRE_ACTIVE) {
01384     /* Illegal call, return error and ignore the packet */
01385     return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
01386   }
01387 
01388   NetworkAction action = (NetworkAction)p->Recv_uint8();
01389   DestType desttype = (DestType)p->Recv_uint8();
01390   int dest = p->Recv_uint32();
01391   char msg[NETWORK_CHAT_LENGTH];
01392 
01393   p->Recv_string(msg, NETWORK_CHAT_LENGTH);
01394   int64 data = p->Recv_uint64();
01395 
01396   NetworkClientInfo *ci = this->GetInfo();
01397   switch (action) {
01398     case NETWORK_ACTION_GIVE_MONEY:
01399       if (!Company::IsValidID(ci->client_playas)) break;
01400       /* FALL THROUGH */
01401     case NETWORK_ACTION_CHAT:
01402     case NETWORK_ACTION_CHAT_CLIENT:
01403     case NETWORK_ACTION_CHAT_COMPANY:
01404       NetworkServerSendChat(action, desttype, dest, msg, this->client_id, data);
01405       break;
01406     default:
01407       IConsolePrintF(CC_ERROR, "WARNING: invalid chat action from client %d (IP: %s).", ci->client_id, this->GetClientIP());
01408       return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
01409   }
01410   return NETWORK_RECV_STATUS_OKAY;
01411 }
01412 
01413 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_PASSWORD(Packet *p)
01414 {
01415   if (this->status != STATUS_ACTIVE) {
01416     /* Illegal call, return error and ignore the packet */
01417     return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
01418   }
01419 
01420   char password[NETWORK_PASSWORD_LENGTH];
01421   const NetworkClientInfo *ci;
01422 
01423   p->Recv_string(password, sizeof(password));
01424   ci = this->GetInfo();
01425 
01426   NetworkServerSetCompanyPassword(ci->client_playas, password);
01427   return NETWORK_RECV_STATUS_OKAY;
01428 }
01429 
01430 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_NAME(Packet *p)
01431 {
01432   if (this->status != STATUS_ACTIVE) {
01433     /* Illegal call, return error and ignore the packet */
01434     return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
01435   }
01436 
01437   char client_name[NETWORK_CLIENT_NAME_LENGTH];
01438   NetworkClientInfo *ci;
01439 
01440   p->Recv_string(client_name, sizeof(client_name));
01441   ci = this->GetInfo();
01442 
01443   if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
01444 
01445   if (ci != NULL) {
01446     /* Display change */
01447     if (NetworkFindName(client_name)) {
01448       NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, client_name);
01449       strecpy(ci->client_name, client_name, lastof(ci->client_name));
01450       NetworkUpdateClientInfo(ci->client_id);
01451     }
01452   }
01453   return NETWORK_RECV_STATUS_OKAY;
01454 }
01455 
01456 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_RCON(Packet *p)
01457 {
01458   if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
01459 
01460   char pass[NETWORK_PASSWORD_LENGTH];
01461   char command[NETWORK_RCONCOMMAND_LENGTH];
01462 
01463   if (StrEmpty(_settings_client.network.rcon_password)) return NETWORK_RECV_STATUS_OKAY;
01464 
01465   p->Recv_string(pass, sizeof(pass));
01466   p->Recv_string(command, sizeof(command));
01467 
01468   if (strcmp(pass, _settings_client.network.rcon_password) != 0) {
01469     DEBUG(net, 0, "[rcon] wrong password from client-id %d", this->client_id);
01470     return NETWORK_RECV_STATUS_OKAY;
01471   }
01472 
01473   DEBUG(net, 0, "[rcon] client-id %d executed: '%s'", this->client_id, command);
01474 
01475   _redirect_console_to_client = this->client_id;
01476   IConsoleCmdExec(command);
01477   _redirect_console_to_client = INVALID_CLIENT_ID;
01478   return NETWORK_RECV_STATUS_OKAY;
01479 }
01480 
01481 NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MOVE(Packet *p)
01482 {
01483   if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
01484 
01485   CompanyID company_id = (Owner)p->Recv_uint8();
01486 
01487   /* Check if the company is valid, we don't allow moving to AI companies */
01488   if (company_id != COMPANY_SPECTATOR && !Company::IsValidHumanID(company_id)) return NETWORK_RECV_STATUS_OKAY;
01489 
01490   /* Check if we require a password for this company */
01491   if (company_id != COMPANY_SPECTATOR && !StrEmpty(_network_company_states[company_id].password)) {
01492     /* we need a password from the client - should be in this packet */
01493     char password[NETWORK_PASSWORD_LENGTH];
01494     p->Recv_string(password, sizeof(password));
01495 
01496     /* Incorrect password sent, return! */
01497     if (strcmp(password, _network_company_states[company_id].password) != 0) {
01498       DEBUG(net, 2, "[move] wrong password from client-id #%d for company #%d", this->client_id, company_id + 1);
01499       return NETWORK_RECV_STATUS_OKAY;
01500     }
01501   }
01502 
01503   /* if we get here we can move the client */
01504   NetworkServerDoMove(this->client_id, company_id);
01505   return NETWORK_RECV_STATUS_OKAY;
01506 }
01507 
01515 void NetworkSocketHandler::SendCompanyInformation(Packet *p, const Company *c, const NetworkCompanyStats *stats, uint max_len)
01516 {
01517   /* Grab the company name */
01518   char company_name[NETWORK_COMPANY_NAME_LENGTH];
01519   SetDParam(0, c->index);
01520 
01521   assert(max_len <= lengthof(company_name));
01522   GetString(company_name, STR_COMPANY_NAME, company_name + max_len - 1);
01523 
01524   /* Get the income */
01525   Money income = 0;
01526   if (_cur_year - 1 == c->inaugurated_year) {
01527     /* The company is here just 1 year, so display [2], else display[1] */
01528     for (uint i = 0; i < lengthof(c->yearly_expenses[2]); i++) {
01529       income -= c->yearly_expenses[2][i];
01530     }
01531   } else {
01532     for (uint i = 0; i < lengthof(c->yearly_expenses[1]); i++) {
01533       income -= c->yearly_expenses[1][i];
01534     }
01535   }
01536 
01537   /* Send the information */
01538   p->Send_uint8 (c->index);
01539   p->Send_string(company_name);
01540   p->Send_uint32(c->inaugurated_year);
01541   p->Send_uint64(c->old_economy[0].company_value);
01542   p->Send_uint64(c->money);
01543   p->Send_uint64(income);
01544   p->Send_uint16(c->old_economy[0].performance_history);
01545 
01546   /* Send 1 if there is a password for the company else send 0 */
01547   p->Send_bool  (!StrEmpty(_network_company_states[c->index].password));
01548 
01549   for (uint i = 0; i < NETWORK_VEH_END; i++) {
01550     p->Send_uint16(stats->num_vehicle[i]);
01551   }
01552 
01553   for (uint i = 0; i < NETWORK_VEH_END; i++) {
01554     p->Send_uint16(stats->num_station[i]);
01555   }
01556 
01557   p->Send_bool(c->is_ai);
01558 }
01559 
01564 void NetworkPopulateCompanyStats(NetworkCompanyStats *stats)
01565 {
01566   const Vehicle *v;
01567   const Station *s;
01568 
01569   memset(stats, 0, sizeof(*stats) * MAX_COMPANIES);
01570 
01571   /* Go through all vehicles and count the type of vehicles */
01572   FOR_ALL_VEHICLES(v) {
01573     if (!Company::IsValidID(v->owner) || !v->IsPrimaryVehicle()) continue;
01574     byte type = 0;
01575     switch (v->type) {
01576       case VEH_TRAIN: type = NETWORK_VEH_TRAIN; break;
01577       case VEH_ROAD: type = RoadVehicle::From(v)->IsBus() ? NETWORK_VEH_BUS : NETWORK_VEH_LORRY; break;
01578       case VEH_AIRCRAFT: type = NETWORK_VEH_PLANE; break;
01579       case VEH_SHIP: type = NETWORK_VEH_SHIP; break;
01580       default: continue;
01581     }
01582     stats[v->owner].num_vehicle[type]++;
01583   }
01584 
01585   /* Go through all stations and count the types of stations */
01586   FOR_ALL_STATIONS(s) {
01587     if (Company::IsValidID(s->owner)) {
01588       NetworkCompanyStats *npi = &stats[s->owner];
01589 
01590       if (s->facilities & FACIL_TRAIN)      npi->num_station[NETWORK_VEH_TRAIN]++;
01591       if (s->facilities & FACIL_TRUCK_STOP) npi->num_station[NETWORK_VEH_LORRY]++;
01592       if (s->facilities & FACIL_BUS_STOP)   npi->num_station[NETWORK_VEH_BUS]++;
01593       if (s->facilities & FACIL_AIRPORT)    npi->num_station[NETWORK_VEH_PLANE]++;
01594       if (s->facilities & FACIL_DOCK)       npi->num_station[NETWORK_VEH_SHIP]++;
01595     }
01596   }
01597 }
01598 
01603 void NetworkUpdateClientInfo(ClientID client_id)
01604 {
01605   NetworkClientSocket *cs;
01606   NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
01607 
01608   if (ci == NULL) return;
01609 
01610   DEBUG(desync, 1, "client: %08x; %02x; %02x; %04x", _date, _date_fract, (int)ci->client_playas, client_id);
01611 
01612   FOR_ALL_CLIENT_SOCKETS(cs) {
01613     cs->SendClientInfo(ci);
01614   }
01615 
01616   NetworkAdminClientUpdate(ci);
01617 }
01618 
01620 static void NetworkCheckRestartMap()
01621 {
01622   if (_settings_client.network.restart_game_year != 0 && _cur_year >= _settings_client.network.restart_game_year) {
01623     DEBUG(net, 0, "Auto-restarting map. Year %d reached", _cur_year);
01624 
01625     StartNewGameWithoutGUI(GENERATE_NEW_SEED);
01626   }
01627 }
01628 
01635 static void NetworkAutoCleanCompanies()
01636 {
01637   const NetworkClientInfo *ci;
01638   const Company *c;
01639   bool clients_in_company[MAX_COMPANIES];
01640   int vehicles_in_company[MAX_COMPANIES];
01641 
01642   if (!_settings_client.network.autoclean_companies) return;
01643 
01644   memset(clients_in_company, 0, sizeof(clients_in_company));
01645 
01646   /* Detect the active companies */
01647   FOR_ALL_CLIENT_INFOS(ci) {
01648     if (Company::IsValidID(ci->client_playas)) clients_in_company[ci->client_playas] = true;
01649   }
01650 
01651   if (!_network_dedicated) {
01652     ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
01653     if (Company::IsValidID(ci->client_playas)) clients_in_company[ci->client_playas] = true;
01654   }
01655 
01656   if (_settings_client.network.autoclean_novehicles != 0) {
01657     memset(vehicles_in_company, 0, sizeof(vehicles_in_company));
01658 
01659     const Vehicle *v;
01660     FOR_ALL_VEHICLES(v) {
01661       if (!Company::IsValidID(v->owner) || !v->IsPrimaryVehicle()) continue;
01662       vehicles_in_company[v->owner]++;
01663     }
01664   }
01665 
01666   /* Go through all the companies */
01667   FOR_ALL_COMPANIES(c) {
01668     /* Skip the non-active once */
01669     if (c->is_ai) continue;
01670 
01671     if (!clients_in_company[c->index]) {
01672       /* The company is empty for one month more */
01673       _network_company_states[c->index].months_empty++;
01674 
01675       /* Is the company empty for autoclean_unprotected-months, and is there no protection? */
01676       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)) {
01677         /* Shut the company down */
01678         DoCommandP(0, 2 | c->index << 16, CRR_AUTOCLEAN, CMD_COMPANY_CTRL);
01679         IConsolePrintF(CC_DEFAULT, "Auto-cleaned company #%d with no password", c->index + 1);
01680       }
01681       /* Is the company empty for autoclean_protected-months, and there is a protection? */
01682       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)) {
01683         /* Unprotect the company */
01684         _network_company_states[c->index].password[0] = '\0';
01685         IConsolePrintF(CC_DEFAULT, "Auto-removed protection from company #%d", c->index + 1);
01686         _network_company_states[c->index].months_empty = 0;
01687         NetworkServerUpdateCompanyPassworded(c->index, false);
01688       }
01689       /* Is the company empty for autoclean_novehicles-months, and has no vehicles? */
01690       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) {
01691         /* Shut the company down */
01692         DoCommandP(0, 2 | c->index << 16, CRR_AUTOCLEAN, CMD_COMPANY_CTRL);
01693         IConsolePrintF(CC_DEFAULT, "Auto-cleaned company #%d with no vehicles", c->index + 1);
01694       }
01695     } else {
01696       /* It is not empty, reset the date */
01697       _network_company_states[c->index].months_empty = 0;
01698     }
01699   }
01700 }
01701 
01707 bool NetworkFindName(char new_name[NETWORK_CLIENT_NAME_LENGTH])
01708 {
01709   bool found_name = false;
01710   uint number = 0;
01711   char original_name[NETWORK_CLIENT_NAME_LENGTH];
01712 
01713   /* We use NETWORK_CLIENT_NAME_LENGTH in here, because new_name is really a pointer */
01714   ttd_strlcpy(original_name, new_name, NETWORK_CLIENT_NAME_LENGTH);
01715 
01716   while (!found_name) {
01717     const NetworkClientInfo *ci;
01718 
01719     found_name = true;
01720     FOR_ALL_CLIENT_INFOS(ci) {
01721       if (strcmp(ci->client_name, new_name) == 0) {
01722         /* Name already in use */
01723         found_name = false;
01724         break;
01725       }
01726     }
01727     /* Check if it is the same as the server-name */
01728     ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
01729     if (ci != NULL) {
01730       if (strcmp(ci->client_name, new_name) == 0) found_name = false; // name already in use
01731     }
01732 
01733     if (!found_name) {
01734       /* Try a new name (<name> #1, <name> #2, and so on) */
01735 
01736       /* Something's really wrong when there're more names than clients */
01737       if (number++ > MAX_CLIENTS) break;
01738       snprintf(new_name, NETWORK_CLIENT_NAME_LENGTH, "%s #%d", original_name, number);
01739     }
01740   }
01741 
01742   return found_name;
01743 }
01744 
01751 bool NetworkServerChangeClientName(ClientID client_id, const char *new_name)
01752 {
01753   NetworkClientInfo *ci;
01754   /* Check if the name's already in use */
01755   FOR_ALL_CLIENT_INFOS(ci) {
01756     if (strcmp(ci->client_name, new_name) == 0) return false;
01757   }
01758 
01759   ci = NetworkClientInfo::GetByClientID(client_id);
01760   if (ci == NULL) return false;
01761 
01762   NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, true, ci->client_name, new_name);
01763 
01764   strecpy(ci->client_name, new_name, lastof(ci->client_name));
01765 
01766   NetworkUpdateClientInfo(client_id);
01767   return true;
01768 }
01769 
01776 void NetworkServerSetCompanyPassword(CompanyID company_id, const char *password, bool already_hashed)
01777 {
01778   if (!Company::IsValidHumanID(company_id)) return;
01779 
01780   if (!already_hashed) {
01781     password = GenerateCompanyPasswordHash(password, _settings_client.network.network_id, _settings_game.game_creation.generation_seed);
01782   }
01783 
01784   strecpy(_network_company_states[company_id].password, password, lastof(_network_company_states[company_id].password));
01785   NetworkServerUpdateCompanyPassworded(company_id, !StrEmpty(_network_company_states[company_id].password));
01786 }
01787 
01792 static void NetworkHandleCommandQueue(NetworkClientSocket *cs)
01793 {
01794   CommandPacket *cp;
01795   while ((cp = cs->outgoing_queue.Pop()) != NULL) {
01796     cs->SendCommand(cp);
01797     free(cp);
01798   }
01799 }
01800 
01805 void NetworkServer_Tick(bool send_frame)
01806 {
01807   NetworkClientSocket *cs;
01808 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
01809   bool send_sync = false;
01810 #endif
01811 
01812 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
01813   if (_frame_counter >= _last_sync_frame + _settings_client.network.sync_freq) {
01814     _last_sync_frame = _frame_counter;
01815     send_sync = true;
01816   }
01817 #endif
01818 
01819   /* Now we are done with the frame, inform the clients that they can
01820    *  do their frame! */
01821   FOR_ALL_CLIENT_SOCKETS(cs) {
01822     /* We allow a number of bytes per frame, but only to the burst amount
01823      * to be available for packet receiving at any particular time. */
01824     cs->receive_limit = min(cs->receive_limit + _settings_client.network.bytes_per_frame,
01825         _settings_client.network.bytes_per_frame_burst);
01826 
01827     /* Check if the speed of the client is what we can expect from a client */
01828     uint lag = NetworkCalculateLag(cs);
01829     switch (cs->status) {
01830       case NetworkClientSocket::STATUS_ACTIVE:
01831         if (lag > _settings_client.network.max_lag_time) {
01832           /* Client did still not report in within the specified limit. */
01833           IConsolePrintF(CC_ERROR, cs->last_packet + lag * MILLISECONDS_PER_TICK > _realtime_tick ?
01834               /* A packet was received in the last three game days, so the client is likely lagging behind. */
01835                 "Client #%d is dropped because the client's game state is more than %d ticks behind" :
01836               /* No packet was received in the last three game days; sounds like a lost connection. */
01837                 "Client #%d is dropped because the client did not respond for more than %d ticks",
01838               cs->client_id, lag);
01839           cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
01840           continue;
01841         }
01842 
01843         /* Report once per time we detect the lag, and only when we
01844          * received a packet in the last 2000 milliseconds. If we
01845          * did not receive a packet, then the client is not just
01846          * slow, but the connection is likely severed. Mentioning
01847          * frame_freq is not useful in this case. */
01848         if (lag > (uint)DAY_TICKS && cs->lag_test == 0 && cs->last_packet + 2000 > _realtime_tick) {
01849           IConsolePrintF(CC_WARNING, "[%d] Client #%d is slow, try increasing [network.]frame_freq to a higher value!", _frame_counter, cs->client_id);
01850           cs->lag_test = 1;
01851         }
01852 
01853         if (cs->last_frame_server - cs->last_token_frame >= _settings_client.network.max_lag_time) {
01854           /* This is a bad client! It didn't send the right token back within time. */
01855           IConsolePrintF(CC_ERROR, "Client #%d is dropped because it fails to send valid acks", cs->client_id);
01856           cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
01857           continue;
01858         }
01859         break;
01860 
01861       case NetworkClientSocket::STATUS_INACTIVE:
01862       case NetworkClientSocket::STATUS_NEWGRFS_CHECK:
01863       case NetworkClientSocket::STATUS_AUTHORIZED:
01864         /* NewGRF check and authorized states should be handled almost instantly.
01865          * So give them some lee-way, likewise for the query with inactive. */
01866         if (lag > _settings_client.network.max_init_time) {
01867           IConsolePrintF(CC_ERROR, "Client #%d is dropped because it took longer than %d ticks to start the joining process", cs->client_id, _settings_client.network.max_init_time);
01868           cs->SendError(NETWORK_ERROR_TIMEOUT_COMPUTER);
01869           continue;
01870         }
01871         break;
01872 
01873       case NetworkClientSocket::STATUS_MAP:
01874         /* Downloading the map... this is the amount of time since starting the saving. */
01875         if (lag > _settings_client.network.max_download_time) {
01876           IConsolePrintF(CC_ERROR, "Client #%d is dropped because it took longer than %d ticks to download the map", cs->client_id, _settings_client.network.max_download_time);
01877           cs->SendError(NETWORK_ERROR_TIMEOUT_MAP);
01878           continue;
01879         }
01880         break;
01881 
01882       case NetworkClientSocket::STATUS_DONE_MAP:
01883       case NetworkClientSocket::STATUS_PRE_ACTIVE:
01884         /* The map has been sent, so this is for loading the map and syncing up. */
01885         if (lag > _settings_client.network.max_join_time) {
01886           IConsolePrintF(CC_ERROR, "Client #%d is dropped because it took longer than %d ticks to join", cs->client_id, _settings_client.network.max_join_time);
01887           cs->SendError(NETWORK_ERROR_TIMEOUT_JOIN);
01888           continue;
01889         }
01890         break;
01891 
01892       case NetworkClientSocket::STATUS_AUTH_GAME:
01893       case NetworkClientSocket::STATUS_AUTH_COMPANY:
01894         /* These don't block? */
01895         if (lag > _settings_client.network.max_password_time) {
01896           IConsolePrintF(CC_ERROR, "Client #%d is dropped because it took longer than %d ticks to enter the password", cs->client_id, _settings_client.network.max_password_time);
01897           cs->SendError(NETWORK_ERROR_TIMEOUT_PASSWORD);
01898           continue;
01899         }
01900         break;
01901 
01902       case NetworkClientSocket::STATUS_MAP_WAIT:
01903         /* This is an internal state where we do not wait
01904          * on the client to move to a different state. */
01905         break;
01906 
01907       case NetworkClientSocket::STATUS_END:
01908         /* Bad server/code. */
01909         NOT_REACHED();
01910     }
01911 
01912     if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) {
01913       /* Check if we can send command, and if we have anything in the queue */
01914       NetworkHandleCommandQueue(cs);
01915 
01916       /* Send an updated _frame_counter_max to the client */
01917       if (send_frame) cs->SendFrame();
01918 
01919 #ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
01920       /* Send a sync-check packet */
01921       if (send_sync) cs->SendSync();
01922 #endif
01923     }
01924   }
01925 
01926   /* See if we need to advertise */
01927   NetworkUDPAdvertise();
01928 }
01929 
01931 void NetworkServerYearlyLoop()
01932 {
01933   NetworkCheckRestartMap();
01934   NetworkAdminUpdate(ADMIN_FREQUENCY_ANUALLY);
01935 }
01936 
01938 void NetworkServerMonthlyLoop()
01939 {
01940   NetworkAutoCleanCompanies();
01941   NetworkAdminUpdate(ADMIN_FREQUENCY_MONTHLY);
01942   if ((_cur_month % 3) == 0) NetworkAdminUpdate(ADMIN_FREQUENCY_QUARTERLY);
01943 }
01944 
01946 void NetworkServerDailyLoop()
01947 {
01948   NetworkAdminUpdate(ADMIN_FREQUENCY_DAILY);
01949   if ((_date % 7) == 3) NetworkAdminUpdate(ADMIN_FREQUENCY_WEEKLY);
01950 }
01951 
01956 const char *ServerNetworkGameSocketHandler::GetClientIP()
01957 {
01958   return this->client_address.GetHostname();
01959 }
01960 
01962 void NetworkServerShowStatusToConsole()
01963 {
01964   static const char * const stat_str[] = {
01965     "inactive",
01966     "checking NewGRFs",
01967     "authorizing (server password)",
01968     "authorizing (company password)",
01969     "authorized",
01970     "waiting",
01971     "loading map",
01972     "map done",
01973     "ready",
01974     "active"
01975   };
01976   assert_compile(lengthof(stat_str) == NetworkClientSocket::STATUS_END);
01977 
01978   NetworkClientSocket *cs;
01979   FOR_ALL_CLIENT_SOCKETS(cs) {
01980     NetworkClientInfo *ci = cs->GetInfo();
01981     if (ci == NULL) continue;
01982     uint lag = NetworkCalculateLag(cs);
01983     const char *status;
01984 
01985     status = (cs->status < (ptrdiff_t)lengthof(stat_str) ? stat_str[cs->status] : "unknown");
01986     IConsolePrintF(CC_INFO, "Client #%1d  name: '%s'  status: '%s'  frame-lag: %3d  company: %1d  IP: %s",
01987       cs->client_id, ci->client_name, status, lag,
01988       ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0),
01989       cs->GetClientIP());
01990   }
01991 }
01992 
01996 void NetworkServerSendConfigUpdate()
01997 {
01998   NetworkClientSocket *cs;
01999 
02000   FOR_ALL_CLIENT_SOCKETS(cs) {
02001     if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) cs->SendConfigUpdate();
02002   }
02003 }
02004 
02010 void NetworkServerUpdateCompanyPassworded(CompanyID company_id, bool passworded)
02011 {
02012   if (NetworkCompanyIsPassworded(company_id) == passworded) return;
02013 
02014   SB(_network_company_passworded, company_id, 1, !!passworded);
02015   SetWindowClassesDirty(WC_COMPANY);
02016 
02017   NetworkClientSocket *cs;
02018   FOR_ALL_CLIENT_SOCKETS(cs) {
02019     if (cs->status >= NetworkClientSocket::STATUS_PRE_ACTIVE) cs->SendCompanyUpdate();
02020   }
02021 
02022   NetworkAdminCompanyUpdate(Company::GetIfValid(company_id));
02023 }
02024 
02031 void NetworkServerDoMove(ClientID client_id, CompanyID company_id)
02032 {
02033   /* Only allow non-dedicated servers and normal clients to be moved */
02034   if (client_id == CLIENT_ID_SERVER && _network_dedicated) return;
02035 
02036   NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
02037 
02038   /* No need to waste network resources if the client is in the company already! */
02039   if (ci->client_playas == company_id) return;
02040 
02041   ci->client_playas = company_id;
02042 
02043   if (client_id == CLIENT_ID_SERVER) {
02044     SetLocalCompany(company_id);
02045   } else {
02046     NetworkClientSocket *cs = NetworkClientSocket::GetByClientID(client_id);
02047     /* When the company isn't authorized we can't move them yet. */
02048     if (cs->status < NetworkClientSocket::STATUS_AUTHORIZED) return;
02049     cs->SendMove(client_id, company_id);
02050   }
02051 
02052   /* announce the client's move */
02053   NetworkUpdateClientInfo(client_id);
02054 
02055   NetworkAction action = (company_id == COMPANY_SPECTATOR) ? NETWORK_ACTION_COMPANY_SPECTATOR : NETWORK_ACTION_COMPANY_JOIN;
02056   NetworkServerSendChat(action, DESTTYPE_BROADCAST, 0, "", client_id, company_id + 1);
02057 }
02058 
02065 void NetworkServerSendRcon(ClientID client_id, TextColour colour_code, const char *string)
02066 {
02067   NetworkClientSocket::GetByClientID(client_id)->SendRConResult(colour_code, string);
02068 }
02069 
02074 void NetworkServerKickClient(ClientID client_id)
02075 {
02076   if (client_id == CLIENT_ID_SERVER) return;
02077   NetworkClientSocket::GetByClientID(client_id)->SendError(NETWORK_ERROR_KICKED);
02078 }
02079 
02085 uint NetworkServerKickOrBanIP(ClientID client_id, bool ban)
02086 {
02087   return NetworkServerKickOrBanIP(NetworkClientSocket::GetByClientID(client_id)->GetClientIP(), ban);
02088 }
02089 
02095 uint NetworkServerKickOrBanIP(const char *ip, bool ban)
02096 {
02097   /* Add address to ban-list */
02098   if (ban) {
02099     bool contains = false;
02100     for (char **iter = _network_ban_list.Begin(); iter != _network_ban_list.End(); iter++) {
02101       if (strcmp(*iter, ip) == 0) {
02102         contains = true;
02103         break;
02104       }
02105     }
02106     if (!contains) *_network_ban_list.Append() = strdup(ip);
02107   }
02108 
02109   uint n = 0;
02110 
02111   /* There can be multiple clients with the same IP, kick them all */
02112   NetworkClientSocket *cs;
02113   FOR_ALL_CLIENT_SOCKETS(cs) {
02114     if (cs->client_id == CLIENT_ID_SERVER) continue;
02115     if (cs->client_address.IsInNetmask(const_cast<char *>(ip))) {
02116       NetworkServerKickClient(cs->client_id);
02117       n++;
02118     }
02119   }
02120 
02121   return n;
02122 }
02123 
02129 bool NetworkCompanyHasClients(CompanyID company)
02130 {
02131   const NetworkClientInfo *ci;
02132   FOR_ALL_CLIENT_INFOS(ci) {
02133     if (ci->client_playas == company) return true;
02134   }
02135   return false;
02136 }
02137 
02138 
02144 void ServerNetworkGameSocketHandler::GetClientName(char *client_name, size_t size) const
02145 {
02146   const NetworkClientInfo *ci = this->GetInfo();
02147 
02148   if (ci == NULL || StrEmpty(ci->client_name)) {
02149     snprintf(client_name, size, "Client #%4d", this->client_id);
02150   } else {
02151     ttd_strlcpy(client_name, ci->client_name, size);
02152   }
02153 }
02154 
02158 void NetworkPrintClients()
02159 {
02160   NetworkClientInfo *ci;
02161   FOR_ALL_CLIENT_INFOS(ci) {
02162     if (_network_server) {
02163       IConsolePrintF(CC_INFO, "Client #%1d  name: '%s'  company: %1d  IP: %s",
02164           ci->client_id,
02165           ci->client_name,
02166           ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0),
02167           ci->client_id == CLIENT_ID_SERVER ? "server" : NetworkClientSocket::GetByClientID(ci->client_id)->GetClientIP());
02168     } else {
02169       IConsolePrintF(CC_INFO, "Client #%1d  name: '%s'  company: %1d",
02170           ci->client_id,
02171           ci->client_name,
02172           ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0));
02173     }
02174   }
02175 }
02176 
02177 #endif /* ENABLE_NETWORK */