network_server.cpp

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