network_server.cpp

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

Generated on Sun May 15 19:20:10 2011 for OpenTTD by  doxygen 1.6.1