# network.cpp

Go to the documentation of this file.

    00001 /* $Id: network.cpp 18046 2009-11-11 21:45:50Z rubidium $ */
    00002
    00005 #include "../stdafx.h"
    00006 #include "../company_type.h"
    00007
    00008 #ifdef ENABLE_NETWORK
    00009
    00010 #include "../openttd.h"
    00011 #include "../strings_func.h"
    00012 #include "../command_func.h"
    00013 #include "../variables.h"
    00014 #include "../date_func.h"
    00015 #include "network_internal.h"
    00016 #include "network_client.h"
    00017 #include "network_server.h"
    00018 #include "network_content.h"
    00019 #include "network_udp.h"
    00020 #include "network_gamelist.h"
    00021 #include "core/udp.h"
    00022 #include "core/host.h"
    00023 #include "network_gui.h"
    00024 #include "../console_func.h"
    00025 #include "../md5.h"
    00026 #include "../core/random_func.hpp"
    00027 #include "../window_func.h"
    00028 #include "../string_func.h"
    00029 #include "../company_func.h"
    00030 #include "../company_base.h"
    00031 #include "../settings_type.h"
    00032 #include "../landscape_type.h"
    00033 #include "../rev.h"
    00034 #include "../core/alloc_func.hpp"
    00035 #ifdef DEBUG_DUMP_COMMANDS
    00036   #include "../fileio_func.h"
    00037 #endif /* DEBUG_DUMP_COMMANDS */
    00038 #include "table/strings.h"
    00039 #include "../oldpool_func.h"
    00040
    00041 DECLARE_POSTFIX_INCREMENT(ClientID);
    00042
    00043 typedef ClientIndex NetworkClientInfoID;
    00044 DEFINE_OLD_POOL_GENERIC(NetworkClientInfo, NetworkClientInfo);
    00045
    00046 bool _networking;
    00047 bool _network_server;
    00048 bool _network_available;
    00049 bool _network_dedicated;
    00050 bool _is_network_server;
    00051 NetworkServerGameInfo _network_game_info;
    00052 NetworkCompanyState *_network_company_states = NULL;
    00053 ClientID _network_own_client_id;
    00054 ClientID _redirect_console_to_client;
    00055 bool _network_need_advertise;
    00056 uint32 _network_last_advertise_frame;
    00057 uint8 _network_reconnect;
    00058 char *_network_host_list[10];
    00059 char *_network_ban_list[25];
    00060 uint32 _frame_counter_server; // The frame_counter of the server, if in network-mode
    00061 uint32 _frame_counter_max; // To where we may go with our clients
    00062 uint32 _frame_counter;
    00063 uint32 _last_sync_frame; // Used in the server to store the last time a sync packet was sent to clients.
    00064 uint32 _broadcast_list[MAX_INTERFACES + 1];
    00065 uint32 _network_server_bind_ip;
    00066 uint32 _sync_seed_1, _sync_seed_2;
    00067 uint32 _sync_frame;
    00068 bool _network_first_time;
    00069 bool _network_udp_server;
    00070 uint16 _network_udp_broadcast;
    00071 uint8 _network_advertise_retries;
    00072 CompanyMask _network_company_passworded;
    00073
    00074 /* Check whether NETWORK_NUM_LANDSCAPES is still in sync with NUM_LANDSCAPE */
    00075 assert_compile((int)NETWORK_NUM_LANDSCAPES == (int)NUM_LANDSCAPE);
    00076 assert_compile((int)NETWORK_COMPANY_NAME_LENGTH == MAX_LENGTH_COMPANY_NAME_BYTES);
    00077
    00078 extern NetworkUDPSocketHandler *_udp_client_socket;
    00079 extern NetworkUDPSocketHandler *_udp_server_socket;
    00080 extern NetworkUDPSocketHandler *_udp_master_socket;
    00081
    00082 /* The listen socket for the server */
    00083 static SOCKET _listensocket;
    00084
    00085 /* The amount of clients connected */
    00086 static byte _network_clients_connected = 0;
    00087 /* The identifier counter for new clients (is never decreased) */
    00088 static ClientID _network_client_id = CLIENT_ID_FIRST;
    00089
    00090 /* Some externs / forwards */
    00091 extern void StateGameLoop();
    00092
    00098 NetworkClientInfo *NetworkFindClientInfoFromIndex(ClientIndex index)
    00099 {
    00100   return IsValidNetworkClientInfoIndex(index) ? GetNetworkClientInfo(index) : NULL;
    00101 }
    00102
    00108 NetworkClientInfo *NetworkFindClientInfoFromClientID(ClientID client_id)
    00109 {
    00110   NetworkClientInfo *ci;
    00111
    00112   FOR_ALL_CLIENT_INFOS(ci) {
    00113     if (ci->client_id == client_id) return ci;
    00114   }
    00115
    00116   return NULL;
    00117 }
    00118
    00124 NetworkClientInfo *NetworkFindClientInfoFromIP(const char *ip)
    00125 {
    00126   NetworkClientInfo *ci;
    00127   uint32 ip_number = inet_addr(ip);
    00128
    00129   FOR_ALL_CLIENT_INFOS(ci) {
    00130     if (ci->client_ip == ip_number) return ci;
    00131   }
    00132
    00133   return NULL;
    00134 }
    00135
    00141 NetworkClientSocket *NetworkFindClientStateFromClientID(ClientID client_id)
    00142 {
    00143   NetworkClientSocket *cs;
    00144
    00145   FOR_ALL_CLIENT_SOCKETS(cs) {
    00146     if (cs->client_id == client_id) return cs;
    00147   }
    00148
    00149   return NULL;
    00150 }
    00151
    00152 /* NetworkGetClientName is a server-safe function to get the name of the client
    00153  *  if the user did not send it yet, Client #<no> is used. */
    00154 void NetworkGetClientName(char *client_name, size_t size, const NetworkClientSocket *cs)
    00155 {
    00156   const NetworkClientInfo *ci = cs->GetInfo();
    00157
    00158   if (StrEmpty(ci->client_name)) {
    00159     snprintf(client_name, size, "Client #%4d", cs->client_id);
    00160   } else {
    00161     ttd_strlcpy(client_name, ci->client_name, size);
    00162   }
    00163 }
    00164
    00165 byte NetworkSpectatorCount()
    00166 {
    00167   const NetworkClientInfo *ci;
    00168   byte count = 0;
    00169
    00170   FOR_ALL_CLIENT_INFOS(ci) {
    00171     if (ci->client_playas == COMPANY_SPECTATOR) count++;
    00172   }
    00173
    00174   /* Don't count a dedicated server as spectator */
    00175   if (_network_dedicated) count--;
    00176
    00177   return count;
    00178 }
    00179
    00185 bool NetworkCompanyIsPassworded(CompanyID company_id)
    00186 {
    00187   return HasBit(_network_company_passworded, company_id);
    00188 }
    00189
    00190 /* This puts a text-message to the console, or in the future, the chat-box,
    00191  *  (to keep it all a bit more general)
    00192  * If 'self_send' is true, this is the client who is sending the message */
    00193 void NetworkTextMessage(NetworkAction action, ConsoleColour colour, bool self_send, const char *name, const char *str, int64 data)
    00194 {
    00195   const int duration = 10; // Game days the messages stay visible
    00196
    00197   StringID strid;
    00198   switch (action) {
    00199     case NETWORK_ACTION_SERVER_MESSAGE:
    00200       /* Ignore invalid messages */
    00201       if (data >= NETWORK_SERVER_MESSAGE_END) return;
    00202
    00203       strid = STR_NETWORK_SERVER_MESSAGE;
    00204       colour = CC_DEFAULT;
    00205       data = STR_NETWORK_SERVER_MESSAGE_GAME_PAUSED_PLAYERS + data;
    00206       break;
    00207     case NETWORK_ACTION_COMPANY_SPECTATOR:
    00208       colour = CC_DEFAULT;
    00209       strid = STR_NETWORK_CLIENT_COMPANY_SPECTATE;
    00210       break;
    00211     case NETWORK_ACTION_COMPANY_JOIN:
    00212       colour = CC_DEFAULT;
    00213       strid = STR_NETWORK_CLIENT_COMPANY_JOIN;
    00214       break;
    00215     case NETWORK_ACTION_COMPANY_NEW:
    00216       colour = CC_DEFAULT;
    00217       strid = STR_NETWORK_CLIENT_COMPANY_NEW;
    00218       break;
    00219     case NETWORK_ACTION_JOIN:           strid = STR_NETWORK_CLIENT_JOINED; break;
    00220     case NETWORK_ACTION_LEAVE:          strid = STR_NETWORK_CLIENT_LEFT; break;
    00221     case NETWORK_ACTION_NAME_CHANGE:    strid = STR_NETWORK_NAME_CHANGE; break;
    00222     case NETWORK_ACTION_GIVE_MONEY:     strid = self_send ? STR_NETWORK_GAVE_MONEY_AWAY : STR_NETWORK_GIVE_MONEY;   break;
    00223     case NETWORK_ACTION_CHAT_COMPANY:   strid = self_send ? STR_NETWORK_CHAT_TO_COMPANY : STR_NETWORK_CHAT_COMPANY; break;
    00224     case NETWORK_ACTION_CHAT_CLIENT:    strid = self_send ? STR_NETWORK_CHAT_TO_CLIENT  : STR_NETWORK_CHAT_CLIENT;  break;
    00225     default:                            strid = STR_NETWORK_CHAT_ALL; break;
    00226   }
    00227
    00228   char message[1024];
    00229   SetDParamStr(0, name);
    00230   SetDParamStr(1, str);
    00231   SetDParam(2, data);
    00232   GetString(message, strid, lastof(message));
    00233
    00234   DEBUG(desync, 1, "msg: %d; %d; %s\n", _date, _date_fract, message);
    00235   IConsolePrintF(colour, "%s", message);
    00236   NetworkAddChatMessage((TextColour)colour, duration, "%s", message);
    00237 }
    00238
    00239 /* Calculate the frame-lag of a client */
    00240 uint NetworkCalculateLag(const NetworkClientSocket *cs)
    00241 {
    00242   int lag = cs->last_frame_server - cs->last_frame;
    00243   /* This client has missed his ACK packet after 1 DAY_TICKS..
    00244    *  so we increase his lag for every frame that passes!
    00245    * The packet can be out by a max of _net_frame_freq */
    00246   if (cs->last_frame_server + DAY_TICKS + _settings_client.network.frame_freq < _frame_counter)
    00247     lag += _frame_counter - (cs->last_frame_server + DAY_TICKS + _settings_client.network.frame_freq);
    00248
    00249   return lag;
    00250 }
    00251
    00252
    00253 /* There was a non-recoverable error, drop back to the main menu with a nice
    00254  *  error */
    00255 static void NetworkError(StringID error_string)
    00256 {
    00257   _switch_mode = SM_MENU;
    00258   extern StringID _switch_mode_errorstr;
    00259   _switch_mode_errorstr = error_string;
    00260 }
    00261
    00262 static void ServerStartError(const char *error)
    00263 {
    00264   DEBUG(net, 0, "[server] could not start network: %s",error);
    00265   NetworkError(STR_NETWORK_ERR_SERVER_START);
    00266 }
    00267
    00268 static void NetworkClientError(NetworkRecvStatus res, NetworkClientSocket *cs)
    00269 {
    00270   /* First, send a CLIENT_ERROR to the server, so he knows we are
    00271    *  disconnection (and why!) */
    00272   NetworkErrorCode errorno;
    00273
    00274   /* We just want to close the connection.. */
    00275   if (res == NETWORK_RECV_STATUS_CLOSE_QUERY) {
    00276     cs->has_quit = true;
    00277     NetworkCloseClient(cs);
    00278     _networking = false;
    00279
    00280     DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
    00281     return;
    00282   }
    00283
    00284   switch (res) {
    00285     case NETWORK_RECV_STATUS_DESYNC:          errorno = NETWORK_ERROR_DESYNC; break;
    00286     case NETWORK_RECV_STATUS_SAVEGAME:        errorno = NETWORK_ERROR_SAVEGAME_FAILED; break;
    00287     case NETWORK_RECV_STATUS_NEWGRF_MISMATCH: errorno = NETWORK_ERROR_NEWGRF_MISMATCH; break;
    00288     default:                                  errorno = NETWORK_ERROR_GENERAL; break;
    00289   }
    00290   /* This means we fucked up and the server closed the connection */
    00291   if (res != NETWORK_RECV_STATUS_SERVER_ERROR && res != NETWORK_RECV_STATUS_SERVER_FULL &&
    00292       res != NETWORK_RECV_STATUS_SERVER_BANNED) {
    00293     SEND_COMMAND(PACKET_CLIENT_ERROR)(errorno);
    00294   }
    00295
    00296   _switch_mode = SM_MENU;
    00297   NetworkCloseClient(cs);
    00298   _networking = false;
    00299 }
    00300
    00306 StringID GetNetworkErrorMsg(NetworkErrorCode err)
    00307 {
    00308   /* List of possible network errors, used by
    00309    * PACKET_SERVER_ERROR and PACKET_CLIENT_ERROR */
    00310   static const StringID network_error_strings[] = {
    00311     STR_NETWORK_ERR_CLIENT_GENERAL,
    00312     STR_NETWORK_ERR_CLIENT_DESYNC,
    00313     STR_NETWORK_ERR_CLIENT_SAVEGAME,
    00314     STR_NETWORK_ERR_CLIENT_CONNECTION_LOST,
    00315     STR_NETWORK_ERR_CLIENT_PROTOCOL_ERROR,
    00316     STR_NETWORK_ERR_CLIENT_NEWGRF_MISMATCH,
    00317     STR_NETWORK_ERR_CLIENT_NOT_AUTHORIZED,
    00318     STR_NETWORK_ERR_CLIENT_NOT_EXPECTED,
    00319     STR_NETWORK_ERR_CLIENT_WRONG_REVISION,
    00320     STR_NETWORK_ERR_CLIENT_NAME_IN_USE,
    00321     STR_NETWORK_ERR_CLIENT_WRONG_PASSWORD,
    00322     STR_NETWORK_ERR_CLIENT_COMPANY_MISMATCH,
    00323     STR_NETWORK_ERR_CLIENT_KICKED,
    00324     STR_NETWORK_ERR_CLIENT_CHEATER,
    00325     STR_NETWORK_ERR_CLIENT_SERVER_FULL
    00326   };
    00327
    00328   if (err >= (ptrdiff_t)lengthof(network_error_strings)) err = NETWORK_ERROR_GENERAL;
    00329
    00330   return network_error_strings[err];
    00331 }
    00332
    00338 static uint NetworkCountActiveClients()
    00339 {
    00340   const NetworkClientSocket *cs;
    00341   uint count = 0;
    00342
    00343   FOR_ALL_CLIENT_SOCKETS(cs) {
    00344     if (cs->status != STATUS_ACTIVE) continue;
    00345     if (!IsValidCompanyID(cs->GetInfo()->client_playas)) continue;
    00346     count++;
    00347   }
    00348
    00349   return count;
    00350 }
    00351
    00352 static bool _min_active_clients_paused = false;
    00353
    00354 /* Check if the minimum number of active clients has been reached and pause or unpause the game as appropriate */
    00355 static void CheckMinActiveClients()
    00356 {
    00357   if (!_network_dedicated) return;
    00358
    00359   if (NetworkCountActiveClients() < _settings_client.network.min_active_clients) {
    00360     if (_min_active_clients_paused) return;
    00361
    00362     _min_active_clients_paused = true;
    00363     DoCommandP(0, 1, 0, CMD_PAUSE);
    00364     NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_BROADCAST, 0, "", CLIENT_ID_SERVER, NETWORK_SERVER_MESSAGE_GAME_PAUSED_PLAYERS);
    00365   } else {
    00366     if (!_min_active_clients_paused) return;
    00367
    00368     _min_active_clients_paused = false;
    00369     DoCommandP(0, 0, 0, CMD_PAUSE);
    00370     NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_BROADCAST, 0, "", CLIENT_ID_SERVER, NETWORK_SERVER_MESSAGE_GAME_UNPAUSED_PLAYERS);
    00371   }
    00372 }
    00373
    00380 void ParseConnectionString(const char **company, const char **port, char *connection_string)
    00381 {
    00382   char *p;
    00383   for (p = connection_string; *p != '\0'; p++) {
    00384     switch (*p) {
    00385       case '#':
    00386         *company = p + 1;
    00387         *p = '\0';
    00388         break;
    00389       case ':':
    00390         *port = p + 1;
    00391         *p = '\0';
    00392         break;
    00393     }
    00394   }
    00395 }
    00396
    00397 /* Creates a new client from a socket
    00398  *   Used both by the server and the client */
    00399 static NetworkClientSocket *NetworkAllocClient(SOCKET s)
    00400 {
    00401   if (_network_server) {
    00402     /* Can we handle a new client? */
    00403     if (_network_clients_connected >= MAX_CLIENTS) return NULL;
    00404     if (_network_game_info.clients_on >= _settings_client.network.max_clients) return NULL;
    00405
    00406     /* Register the login */
    00407     _network_clients_connected++;
    00408   }
    00409
    00410   NetworkClientSocket *cs = new NetworkClientSocket(INVALID_CLIENT_ID);
    00411   cs->sock = s;
    00412   cs->last_frame = _frame_counter;
    00413   cs->last_frame_server = _frame_counter;
    00414
    00415   if (_network_server) {
    00416     cs->client_id = _network_client_id++;
    00417     NetworkClientInfo *ci = new NetworkClientInfo(cs->client_id);
    00418     cs->SetInfo(ci);
    00419     ci->client_playas = COMPANY_INACTIVE_CLIENT;
    00420     ci->join_date = _date;
    00421
    00422     InvalidateWindow(WC_CLIENT_LIST, 0);
    00423   }
    00424
    00425   return cs;
    00426 }
    00427
    00428 /* Close a connection */
    00429 void NetworkCloseClient(NetworkClientSocket *cs)
    00430 {
    00431   /*
    00432    * Sending a message just before leaving the game calls cs->Send_Packets.
    00433    * This might invoke this function, which means that when we close the
    00434    * connection after cs->Send_Packets we will close an already closed
    00435    * connection. This handles that case gracefully without having to make
    00436    * that code any more complex or more aware of the validity of the socket.
    00437    */
    00438   if (cs->sock == INVALID_SOCKET) return;
    00439
    00440   DEBUG(net, 1, "Closed client connection %d", cs->client_id);
    00441
    00442   if (!cs->has_quit && _network_server && cs->status > STATUS_INACTIVE) {
    00443     /* We did not receive a leave message from this client... */
    00444     char client_name[NETWORK_CLIENT_NAME_LENGTH];
    00445     NetworkClientSocket *new_cs;
    00446
    00447     NetworkGetClientName(client_name, sizeof(client_name), cs);
    00448
    00449     NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, STR_NETWORK_ERR_CLIENT_CONNECTION_LOST);
    00450
    00451     /* Inform other clients of this... strange leaving ;) */
    00452     FOR_ALL_CLIENT_SOCKETS(new_cs) {
    00453       if (new_cs->status > STATUS_AUTH && cs != new_cs) {
    00454         SEND_COMMAND(PACKET_SERVER_ERROR_QUIT)(new_cs, cs->client_id, NETWORK_ERROR_CONNECTION_LOST);
    00455       }
    00456     }
    00457   }
    00458
    00459   /* When the client was PRE_ACTIVE, the server was in pause mode, so unpause */
    00460   if (cs->status == STATUS_PRE_ACTIVE && _settings_client.network.pause_on_join) {
    00461     DoCommandP(0, 0, 0, CMD_PAUSE);
    00462     NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_BROADCAST, 0, "", CLIENT_ID_SERVER, NETWORK_SERVER_MESSAGE_GAME_UNPAUSED_CONNECT_FAIL);
    00463   }
    00464
    00465   if (_network_server) {
    00466     /* We just lost one client :( */
    00467     if (cs->status >= STATUS_AUTH) _network_game_info.clients_on--;
    00468     _network_clients_connected--;
    00469
    00470     InvalidateWindow(WC_CLIENT_LIST, 0);
    00471   }
    00472
    00473   delete cs->GetInfo();
    00474   delete cs;
    00475 }
    00476
    00477 /* For the server, to accept new clients */
    00478 static void NetworkAcceptClients()
    00479 {
    00480   struct sockaddr_in sin;
    00481   NetworkClientSocket *cs;
    00482   uint i;
    00483   bool banned;
    00484
    00485   /* Should never ever happen.. is it possible?? */
    00486   assert(_listensocket != INVALID_SOCKET);
    00487
    00488   for (;;) {
    00489     socklen_t sin_len = sizeof(sin);
    00490     SOCKET s = accept(_listensocket, (struct sockaddr*)&sin, &sin_len);
    00491     if (s == INVALID_SOCKET) return;
    00492
    00493     SetNonBlocking(s); // XXX error handling?
    00494
    00495     DEBUG(net, 1, "Client connected from %s on frame %d", inet_ntoa(sin.sin_addr), _frame_counter);
    00496
    00497     SetNoDelay(s); // XXX error handling?
    00498
    00499     /* Check if the client is banned */
    00500     banned = false;
    00501     for (i = 0; i < lengthof(_network_ban_list); i++) {
    00502       if (_network_ban_list[i] == NULL) continue;
    00503
    00504       /* Check for CIDR separator */
    00505       char *chr_cidr = strchr(_network_ban_list[i], '/');
    00506       if (chr_cidr != NULL) {
    00507         int cidr = atoi(chr_cidr + 1);
    00508
    00509         /* Invalid CIDR, treat as single host */
    00510         if (cidr <= 0 || cidr > 32) cidr = 32;
    00511
    00512         /* Remove and then replace the / so that inet_addr() works on the IP portion */
    00513         *chr_cidr = '\0';
    00514         uint32 ban_ip = inet_addr(_network_ban_list[i]);
    00515         *chr_cidr = '/';
    00516
    00517         /* Convert CIDR to mask in network format */
    00518         uint32 mask = htonl(-(1 << (32 - cidr)));
    00519         if ((sin.sin_addr.s_addr & mask) == (ban_ip & mask)) banned = true;
    00520       } else {
    00521         /* No CIDR used, so just perform a simple IP test */
    00522         if (sin.sin_addr.s_addr == inet_addr(_network_ban_list[i])) banned = true;
    00523       }
    00524
    00525       if (banned) {
    00526         Packet p(PACKET_SERVER_BANNED);
    00527         p.PrepareToSend();
    00528
    00529         DEBUG(net, 1, "Banned ip tried to join (%s), refused", _network_ban_list[i]);
    00530
    00531         send(s, (const char*)p.buffer, p.size, 0);
    00532         closesocket(s);
    00533         break;
    00534       }
    00535     }
    00536     /* If this client is banned, continue with next client */
    00537     if (banned) continue;
    00538
    00539     cs = NetworkAllocClient(s);
    00540     if (cs == NULL) {
    00541       /* no more clients allowed?
    00542        * Send to the client that we are full! */
    00543       Packet p(PACKET_SERVER_FULL);
    00544       p.PrepareToSend();
    00545
    00546       send(s, (const char*)p.buffer, p.size, 0);
    00547       closesocket(s);
    00548
    00549       continue;
    00550     }
    00551
    00552     /* a new client has connected. We set him at inactive for now
    00553      *  maybe he is only requesting server-info. Till he has sent a PACKET_CLIENT_MAP_OK
    00554      *  the client stays inactive */
    00555     cs->status = STATUS_INACTIVE;
    00556
    00557     cs->GetInfo()->client_ip = sin.sin_addr.s_addr; // Save the IP of the client
    00558   }
    00559 }
    00560
    00561 /* Set up the listen socket for the server */
    00562 static bool NetworkListen()
    00563 {
    00564   SOCKET ls;
    00565   struct sockaddr_in sin;
    00566
    00567   DEBUG(net, 1, "Listening on %s:%d", _settings_client.network.server_bind_ip, _settings_client.network.server_port);
    00568
    00569   ls = socket(AF_INET, SOCK_STREAM, 0);
    00570   if (ls == INVALID_SOCKET) {
    00571     ServerStartError("socket() on listen socket failed");
    00572     return false;
    00573   }
    00574
    00575   { // reuse the socket
    00576     int reuse = 1;
    00577     /* The (const char*) cast is needed for windows!! */
    00578     if (setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) == -1) {
    00579       ServerStartError("setsockopt() on listen socket failed");
    00580       return false;
    00581     }
    00582   }
    00583
    00584   if (!SetNonBlocking(ls)) DEBUG(net, 0, "Setting non-blocking mode failed"); // XXX should this be an error?
    00585
    00586   sin.sin_family = AF_INET;
    00587   sin.sin_addr.s_addr = _network_server_bind_ip;
    00588   sin.sin_port = htons(_settings_client.network.server_port);
    00589
    00590   if (bind(ls, (struct sockaddr*)&sin, sizeof(sin)) != 0) {
    00591     ServerStartError("bind() failed");
    00592     return false;
    00593   }
    00594
    00595   if (listen(ls, 1) != 0) {
    00596     ServerStartError("listen() failed");
    00597     return false;
    00598   }
    00599
    00600   _listensocket = ls;
    00601
    00602   return true;
    00603 }
    00604
    00606 static void InitializeNetworkPools()
    00607 {
    00608   _NetworkClientSocket_pool.CleanPool();
    00609   _NetworkClientSocket_pool.AddBlockToPool();
    00610   _NetworkClientInfo_pool.CleanPool();
    00611   _NetworkClientInfo_pool.AddBlockToPool();
    00612 }
    00613
    00614 /* Close all current connections */
    00615 static void NetworkClose()
    00616 {
    00617   NetworkClientSocket *cs;
    00618
    00619   FOR_ALL_CLIENT_SOCKETS(cs) {
    00620     if (!_network_server) {
    00621       SEND_COMMAND(PACKET_CLIENT_QUIT)();
    00622       cs->Send_Packets();
    00623     }
    00624     NetworkCloseClient(cs);
    00625   }
    00626
    00627   if (_network_server) {
    00628     /* We are a server, also close the listensocket */
    00629     closesocket(_listensocket);
    00630     _listensocket = INVALID_SOCKET;
    00631     DEBUG(net, 1, "[tcp] closed listeners");
    00632   }
    00633   NetworkUDPCloseAll();
    00634
    00635   TCPConnecter::KillAll();
    00636
    00637   _networking = false;
    00638   _network_server = false;
    00639
    00640   NetworkFreeLocalCommandQueue();
    00641
    00642   free(_network_company_states);
    00643   _network_company_states = NULL;
    00644
    00645   InitializeNetworkPools();
    00646 }
    00647
    00648 /* Inits the network (cleans sockets and stuff) */
    00649 static void NetworkInitialize()
    00650 {
    00651   InitializeNetworkPools();
    00652
    00653   _sync_frame = 0;
    00654   _network_first_time = true;
    00655
    00656   _network_reconnect = 0;
    00657 }
    00658
    00660 class TCPQueryConnecter : TCPConnecter {
    00661 public:
    00662   TCPQueryConnecter(const NetworkAddress &address) : TCPConnecter(address) {}
    00663
    00664   virtual void OnFailure()
    00665   {
    00666     NetworkDisconnect();
    00667   }
    00668
    00669   virtual void OnConnect(SOCKET s)
    00670   {
    00671     _networking = true;
    00672     NetworkAllocClient(s);
    00673     SEND_COMMAND(PACKET_CLIENT_COMPANY_INFO)();
    00674   }
    00675 };
    00676
    00677 /* Query a server to fetch his game-info
    00678  *  If game_info is true, only the gameinfo is fetched,
    00679  *   else only the client_info is fetched */
    00680 void NetworkTCPQueryServer(NetworkAddress address)
    00681 {
    00682   if (!_network_available) return;
    00683
    00684   NetworkDisconnect();
    00685   NetworkInitialize();
    00686
    00687   new TCPQueryConnecter(address);
    00688 }
    00689
    00690 /* Validates an address entered as a string and adds the server to
    00691  * the list. If you use this function, the games will be marked
    00692  * as manually added. */
    00693 void NetworkAddServer(const char *b)
    00694 {
    00695   if (*b != '\0') {
    00696     const char *port = NULL;
    00697     const char *company = NULL;
    00698     char host[NETWORK_HOSTNAME_LENGTH];
    00699     uint16 rport;
    00700
    00701     strecpy(host, b, lastof(host));
    00702
    00703     strecpy(_settings_client.network.connect_to_ip, b, lastof(_settings_client.network.connect_to_ip));
    00704     rport = NETWORK_DEFAULT_PORT;
    00705
    00706     ParseConnectionString(&company, &port, host);
    00707     if (port != NULL) rport = atoi(port);
    00708
    00709     NetworkUDPQueryServer(NetworkAddress(host, rport), true);
    00710   }
    00711 }
    00712
    00713 /* Generates the list of manually added hosts from NetworkGameList and
    00714  * dumps them into the array _network_host_list. This array is needed
    00715  * by the function that generates the config file. */
    00716 void NetworkRebuildHostList()
    00717 {
    00718   uint i = 0;
    00719   const NetworkGameList *item = _network_game_list;
    00720   while (item != NULL && i != lengthof(_network_host_list)) {
    00721     if (item->manually) {
    00722       free(_network_host_list[i]);
    00723       _network_host_list[i++] = str_fmt("%s:%i", item->info.hostname, item->port);
    00724     }
    00725     item = item->next;
    00726   }
    00727
    00728   for (; i < lengthof(_network_host_list); i++) {
    00729     free(_network_host_list[i]);
    00730     _network_host_list[i] = NULL;
    00731   }
    00732 }
    00733
    00735 class TCPClientConnecter : TCPConnecter {
    00736 public:
    00737   TCPClientConnecter(const NetworkAddress &address) : TCPConnecter(address) {}
    00738
    00739   virtual void OnFailure()
    00740   {
    00741     NetworkError(STR_NETWORK_ERR_NOCONNECTION);
    00742   }
    00743
    00744   virtual void OnConnect(SOCKET s)
    00745   {
    00746     _networking = true;
    00747     NetworkAllocClient(s);
    00748     IConsoleCmdExec("exec scripts/on_client.scr 0");
    00749     NetworkClient_Connected();
    00750   }
    00751 };
    00752
    00753
    00754 /* Used by clients, to connect to a server */
    00755 void NetworkClientConnectGame(NetworkAddress address)
    00756 {
    00757   if (!_network_available) return;
    00758
    00759   if (address.GetPort() == 0) return;
    00760
    00761   strecpy(_settings_client.network.last_host, address.GetHostname(), lastof(_settings_client.network.last_host));
    00762   _settings_client.network.last_port = address.GetPort();
    00763
    00764   NetworkDisconnect();
    00765   NetworkInitialize();
    00766
    00767   _network_join_status = NETWORK_JOIN_STATUS_CONNECTING;
    00768   ShowJoinStatusWindow();
    00769
    00770   new TCPClientConnecter(address);
    00771 }
    00772
    00773 static void NetworkInitGameInfo()
    00774 {
    00775   if (StrEmpty(_settings_client.network.server_name)) {
    00776     snprintf(_settings_client.network.server_name, sizeof(_settings_client.network.server_name), "Unnamed Server");
    00777   }
    00778
    00779   /* The server is a client too */
    00780   _network_game_info.clients_on = _network_dedicated ? 0 : 1;
    00781
    00782   NetworkClientInfo *ci = new NetworkClientInfo(CLIENT_ID_SERVER);
    00783   ci->client_playas = _network_dedicated ? COMPANY_SPECTATOR : _local_company;
    00784
    00785   strecpy(ci->client_name, _settings_client.network.client_name, lastof(ci->client_name));
    00786   strecpy(ci->unique_id, _settings_client.network.network_id, lastof(ci->unique_id));
    00787 }
    00788
    00789 bool NetworkServerStart()
    00790 {
    00791   if (!_network_available) return false;
    00792
    00793   /* Call the pre-scripts */
    00794   IConsoleCmdExec("exec scripts/pre_server.scr 0");
    00795   if (_network_dedicated) IConsoleCmdExec("exec scripts/pre_dedicated.scr 0");
    00796
    00797   NetworkInitialize();
    00798   if (!NetworkListen()) return false;
    00799
    00800   /* Try to start UDP-server */
    00801   _network_udp_server = true;
    00802   _network_udp_server = _udp_server_socket->Listen(_network_server_bind_ip, _settings_client.network.server_port, false);
    00803
    00804   _network_company_states = CallocT<NetworkCompanyState>(MAX_COMPANIES);
    00805   _network_server = true;
    00806   _networking = true;
    00807   _frame_counter = 0;
    00808   _frame_counter_server = 0;
    00809   _frame_counter_max = 0;
    00810   _last_sync_frame = 0;
    00811   _network_own_client_id = CLIENT_ID_SERVER;
    00812
    00813   /* Non-dedicated server will always be company #1 */
    00814   if (!_network_dedicated) _network_playas = COMPANY_FIRST;
    00815
    00816   _network_clients_connected = 0;
    00817
    00818   NetworkInitGameInfo();
    00819
    00820   /* execute server initialization script */
    00821   IConsoleCmdExec("exec scripts/on_server.scr 0");
    00822   /* if the server is dedicated ... add some other script */
    00823   if (_network_dedicated) IConsoleCmdExec("exec scripts/on_dedicated.scr 0");
    00824
    00825   _min_active_clients_paused = false;
    00826
    00827   /* Try to register us to the master server */
    00828   _network_last_advertise_frame = 0;
    00829   _network_need_advertise = true;
    00830   NetworkUDPAdvertise();
    00831   return true;
    00832 }
    00833
    00834 /* The server is rebooting...
    00835  * The only difference with NetworkDisconnect, is the packets that is sent */
    00836 void NetworkReboot()
    00837 {
    00838   if (_network_server) {
    00839     NetworkClientSocket *cs;
    00840     FOR_ALL_CLIENT_SOCKETS(cs) {
    00841       SEND_COMMAND(PACKET_SERVER_NEWGAME)(cs);
    00842       cs->Send_Packets();
    00843     }
    00844   }
    00845
    00846   NetworkClose();
    00847 }
    00848
    00853 void NetworkDisconnect(bool blocking)
    00854 {
    00855   if (_network_server) {
    00856     NetworkClientSocket *cs;
    00857     FOR_ALL_CLIENT_SOCKETS(cs) {
    00858       SEND_COMMAND(PACKET_SERVER_SHUTDOWN)(cs);
    00859       cs->Send_Packets();
    00860     }
    00861   }
    00862
    00863   if (_settings_client.network.server_advertise) NetworkUDPRemoveAdvertise(blocking);
    00864
    00865   DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
    00866
    00867   NetworkClose();
    00868 }
    00869
    00870 /* Receives something from the network */
    00871 static bool NetworkReceive()
    00872 {
    00873   NetworkClientSocket *cs;
    00874   int n;
    00875   fd_set read_fd, write_fd;
    00876   struct timeval tv;
    00877
    00878   FD_ZERO(&read_fd);
    00879   FD_ZERO(&write_fd);
    00880
    00881   FOR_ALL_CLIENT_SOCKETS(cs) {
    00882     FD_SET(cs->sock, &read_fd);
    00883     FD_SET(cs->sock, &write_fd);
    00884   }
    00885
    00886   /* take care of listener port */
    00887   if (_network_server) FD_SET(_listensocket, &read_fd);
    00888
    00889   tv.tv_sec = tv.tv_usec = 0; // don't block at all.
    00890 #if !defined(__MORPHOS__) && !defined(__AMIGA__)
    00891   n = select(FD_SETSIZE, &read_fd, &write_fd, NULL, &tv);
    00892 #else
    00893   n = WaitSelect(FD_SETSIZE, &read_fd, &write_fd, NULL, &tv, NULL);
    00894 #endif
    00895   if (n == -1 && !_network_server) NetworkError(STR_NETWORK_ERR_LOSTCONNECTION);
    00896
    00897   /* accept clients.. */
    00898   if (_network_server && FD_ISSET(_listensocket, &read_fd)) NetworkAcceptClients();
    00899
    00900   /* read stuff from clients */
    00901   FOR_ALL_CLIENT_SOCKETS(cs) {
    00902     cs->writable = !!FD_ISSET(cs->sock, &write_fd);
    00903     if (FD_ISSET(cs->sock, &read_fd)) {
    00904       if (_network_server) {
    00905         NetworkServer_ReadPackets(cs);
    00906       } else {
    00907         NetworkRecvStatus res;
    00908
    00909         /* The client already was quiting! */
    00910         if (cs->has_quit) return false;
    00911
    00912         res = NetworkClient_ReadPackets(cs);
    00913         if (res != NETWORK_RECV_STATUS_OKAY) {
    00914           /* The client made an error of which we can not recover
    00915            *   close the client and drop back to main menu */
    00916           NetworkClientError(res, cs);
    00917           return false;
    00918         }
    00919       }
    00920     }
    00921   }
    00922   return true;
    00923 }
    00924
    00925 /* This sends all buffered commands (if possible) */
    00926 static void NetworkSend()
    00927 {
    00928   NetworkClientSocket *cs;
    00929   FOR_ALL_CLIENT_SOCKETS(cs) {
    00930     if (cs->writable) {
    00931       cs->Send_Packets();
    00932
    00933       if (cs->status == STATUS_MAP) {
    00934         /* This client is in the middle of a map-send, call the function for that */
    00935         SEND_COMMAND(PACKET_SERVER_MAP)(cs);
    00936       }
    00937     }
    00938   }
    00939 }
    00940
    00941 static bool NetworkDoClientLoop()
    00942 {
    00943   _frame_counter++;
    00944
    00945   NetworkExecuteLocalCommandQueue();
    00946
    00947   StateGameLoop();
    00948
    00949   /* Check if we are in sync! */
    00950   if (_sync_frame != 0) {
    00951     if (_sync_frame == _frame_counter) {
    00952 #ifdef NETWORK_SEND_DOUBLE_SEED
    00953       if (_sync_seed_1 != _random.state[0] || _sync_seed_2 != _random.state[1]) {
    00954 #else
    00955       if (_sync_seed_1 != _random.state[0]) {
    00956 #endif
    00957         NetworkError(STR_NETWORK_ERR_DESYNC);
    00958         DEBUG(desync, 1, "sync_err: %d; %d\n", _date, _date_fract);
    00959         DEBUG(net, 0, "Sync error detected!");
    00960         NetworkClientError(NETWORK_RECV_STATUS_DESYNC, GetNetworkClientSocket(0));
    00961         return false;
    00962       }
    00963
    00964       /* If this is the first time we have a sync-frame, we
    00965        *   need to let the server know that we are ready and at the same
    00966        *   frame as he is.. so we can start playing! */
    00967       if (_network_first_time) {
    00968         _network_first_time = false;
    00969         SEND_COMMAND(PACKET_CLIENT_ACK)();
    00970       }
    00971
    00972       _sync_frame = 0;
    00973     } else if (_sync_frame < _frame_counter) {
    00974       DEBUG(net, 1, "Missed frame for sync-test (%d / %d)", _sync_frame, _frame_counter);
    00975       _sync_frame = 0;
    00976     }
    00977   }
    00978
    00979   return true;
    00980 }
    00981
    00982 /* We have to do some UDP checking */
    00983 void NetworkUDPGameLoop()
    00984 {
    00985   _network_content_client.SendReceive();
    00986   TCPConnecter::CheckCallbacks();
    00987
    00988   if (_network_udp_server) {
    00989     _udp_server_socket->ReceivePackets();
    00990     _udp_master_socket->ReceivePackets();
    00991   } else {
    00992     _udp_client_socket->ReceivePackets();
    00993     if (_network_udp_broadcast > 0) _network_udp_broadcast--;
    00994     NetworkGameListRequery();
    00995   }
    00996 }
    00997
    00998 /* The main loop called from ttd.c
    00999  *  Here we also have to do StateGameLoop if needed! */
    01000 void NetworkGameLoop()
    01001 {
    01002   if (!_networking) return;
    01003
    01004   if (!NetworkReceive()) return;
    01005
    01006   if (_network_server) {
    01007 #ifdef DEBUG_DUMP_COMMANDS
    01008     static FILE *f = FioFOpenFile("commands.log", "rb", SAVE_DIR);
    01009     static Date next_date = 0;
    01010     static uint32 next_date_fract;
    01011     static CommandPacket *cp = NULL;
    01012     if (f == NULL && next_date == 0) {
    01013       printf("Cannot open commands.log\n");
    01014       next_date = 1;
    01015     }
    01016
    01017     while (f != NULL && !feof(f)) {
    01018       if (cp != NULL && _date == next_date && _date_fract == next_date_fract) {
    01019         _current_company = cp->company;
    01020         DoCommandP(cp->tile, cp->p1, cp->p2, cp->cmd, NULL, cp->text);
    01021         free(cp);
    01022         cp = NULL;
    01023       }
    01024
    01025       if (cp != NULL) break;
    01026
    01027       char buff[4096];
    01028       if (fgets(buff, lengthof(buff), f) == NULL) break;
    01029       if (strncmp(buff, "cmd: ", 8) != 0) continue;
    01030       cp = MallocT<CommandPacket>(1);
    01031       int company;
    01032       sscanf(&buff[8], "%d; %d; %d; %d; %d; %d; %d; %s", &next_date, &next_date_fract, &company, &cp->tile, &cp->p1, &cp->p2, &cp->cmd, cp->text);
    01033       cp->company = (CompanyID)company;
    01034     }
    01035 #endif /* DEBUG_DUMP_COMMANDS */
    01036     CheckMinActiveClients();
    01037
    01038     bool send_frame = false;
    01039
    01040     /* We first increase the _frame_counter */
    01041     _frame_counter++;
    01042     /* Update max-frame-counter */
    01043     if (_frame_counter > _frame_counter_max) {
    01044       _frame_counter_max = _frame_counter + _settings_client.network.frame_freq;
    01045       send_frame = true;
    01046     }
    01047
    01048     NetworkExecuteLocalCommandQueue();
    01049
    01050     /* Then we make the frame */
    01051     StateGameLoop();
    01052
    01053     _sync_seed_1 = _random.state[0];
    01054 #ifdef NETWORK_SEND_DOUBLE_SEED
    01055     _sync_seed_2 = _random.state[1];
    01056 #endif
    01057
    01058     NetworkServer_Tick(send_frame);
    01059   } else {
    01060     /* Client */
    01061
    01062     /* Make sure we are at the frame were the server is (quick-frames) */
    01063     if (_frame_counter_server > _frame_counter) {
    01064       while (_frame_counter_server > _frame_counter) {
    01065         if (!NetworkDoClientLoop()) break;
    01066       }
    01067     } else {
    01068       /* Else, keep on going till _frame_counter_max */
    01069       if (_frame_counter_max > _frame_counter) NetworkDoClientLoop();
    01070     }
    01071   }
    01072
    01073   NetworkSend();
    01074 }
    01075
    01076 static void NetworkGenerateUniqueId()
    01077 {
    01078   Md5 checksum;
    01079   uint8 digest[16];
    01080   char hex_output[16 * 2 + 1];
    01081   char coding_string[NETWORK_NAME_LENGTH];
    01082   int di;
    01083
    01084   snprintf(coding_string, sizeof(coding_string), "%d%s", (uint)Random(), "OpenTTD Unique ID");
    01085
    01086   /* Generate the MD5 hash */
    01087   checksum.Append((const uint8*)coding_string, strlen(coding_string));
    01088   checksum.Finish(digest);
    01089
    01090   for (di = 0; di < 16; ++di)
    01091     sprintf(hex_output + di * 2, "%02x", digest[di]);
    01092
    01093   /* _network_unique_id is our id */
    01094   snprintf(_settings_client.network.network_id, sizeof(_settings_client.network.network_id), "%s", hex_output);
    01095 }
    01096
    01097 void NetworkStartDebugLog(NetworkAddress address)
    01098 {
    01099   extern SOCKET _debug_socket;  // Comes from debug.c
    01100   SOCKET s;
    01101   struct sockaddr_in sin;
    01102
    01103   DEBUG(net, 0, "Redirecting DEBUG() to %s:%d", address.GetHostname(), address.GetPort());
    01104
    01105   s = socket(AF_INET, SOCK_STREAM, 0);
    01106   if (s == INVALID_SOCKET) {
    01107     DEBUG(net, 0, "Failed to open socket for redirection DEBUG()");
    01108     return;
    01109   }
    01110
    01111   if (!SetNoDelay(s)) DEBUG(net, 1, "Setting TCP_NODELAY failed");
    01112
    01113   sin.sin_family = AF_INET;
    01114   sin.sin_addr.s_addr = address.GetIP();
    01115   sin.sin_port = htons(address.GetPort());
    01116
    01117   if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) != 0) {
    01118     DEBUG(net, 0, "Failed to redirection DEBUG() to %s:%d", address.GetHostname(), address.GetPort());
    01119     return;
    01120   }
    01121
    01122   if (!SetNonBlocking(s)) DEBUG(net, 0, "Setting non-blocking mode failed");
    01123   _debug_socket = s;
    01124
    01125   DEBUG(net, 0, "DEBUG() is now redirected");
    01126 }
    01127
    01129 void NetworkStartUp()
    01130 {
    01131   DEBUG(net, 3, "[core] starting network...");
    01132
    01133   /* Network is available */
    01134   _network_available = NetworkCoreInitialize();;
    01135   _network_dedicated = false;
    01136   _network_last_advertise_frame = 0;
    01137   _network_need_advertise = true;
    01138   _network_advertise_retries = 0;
    01139
    01140   /* Load the ip from the openttd.cfg */
    01141   _network_server_bind_ip = inet_addr(_settings_client.network.server_bind_ip);
    01142   /* And put the data back in it in case it was an invalid ip */
    01143   snprintf(_settings_client.network.server_bind_ip, sizeof(_settings_client.network.server_bind_ip), "%s", inet_ntoa(*(struct in_addr *)&_network_server_bind_ip));
    01144
    01145   /* Generate an unique id when there is none yet */
    01146   if (StrEmpty(_settings_client.network.network_id)) NetworkGenerateUniqueId();
    01147
    01148   memset(&_network_game_info, 0, sizeof(_network_game_info));
    01149
    01150   NetworkUDPInitialize();
    01151   NetworkInitialize();
    01152   DEBUG(net, 3, "[core] network online, multiplayer available");
    01153   NetworkFindBroadcastIPs(_broadcast_list, MAX_INTERFACES);
    01154 }
    01155
    01157 void NetworkShutDown()
    01158 {
    01159   NetworkDisconnect(true);
    01160   NetworkUDPShutdown();
    01161
    01162   DEBUG(net, 3, "[core] shutting down network");
    01163
    01164   _network_available = false;
    01165
    01166   NetworkCoreShutdown();
    01167 }
    01168
    01173 bool IsNetworkCompatibleVersion(const char *other)
    01174 {
    01175   return strncmp(_openttd_revision, other, NETWORK_REVISION_LENGTH - 1) == 0;
    01176 }
    01177
    01178 #endif /* ENABLE_NETWORK */
    01179
    01180 /* NOTE: this variable needs to be always available */
    01181 CompanyID _network_playas;