# network.cpp

Go to the documentation of this file.

    00001 /* $Id: network.cpp 15775 2009-03-19 23:50:54Z 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
    00333 /* Count the number of active clients connected */
    00334 static uint NetworkCountActiveClients()
    00335 {
    00336   const NetworkClientInfo *ci;
    00337   uint count = 0;
    00338
    00339   FOR_ALL_CLIENT_INFOS(ci) {
    00340     if (IsValidCompanyID(ci->client_playas)) count++;
    00341   }
    00342
    00343   return count;
    00344 }
    00345
    00346 static bool _min_active_clients_paused = false;
    00347
    00348 /* Check if the minimum number of active clients has been reached and pause or unpause the game as appropriate */
    00349 static void CheckMinActiveClients()
    00350 {
    00351   if (!_network_dedicated) return;
    00352
    00353   if (NetworkCountActiveClients() < _settings_client.network.min_active_clients) {
    00354     if (_min_active_clients_paused) return;
    00355
    00356     _min_active_clients_paused = true;
    00357     DoCommandP(0, 1, 0, CMD_PAUSE);
    00358     NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_BROADCAST, 0, "", CLIENT_ID_SERVER, NETWORK_SERVER_MESSAGE_GAME_PAUSED_PLAYERS);
    00359   } else {
    00360     if (!_min_active_clients_paused) return;
    00361
    00362     _min_active_clients_paused = false;
    00363     DoCommandP(0, 0, 0, CMD_PAUSE);
    00364     NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_BROADCAST, 0, "", CLIENT_ID_SERVER, NETWORK_SERVER_MESSAGE_GAME_UNPAUSED_PLAYERS);
    00365   }
    00366 }
    00367
    00374 void ParseConnectionString(const char **company, const char **port, char *connection_string)
    00375 {
    00376   char *p;
    00377   for (p = connection_string; *p != '\0'; p++) {
    00378     switch (*p) {
    00379       case '#':
    00380         *company = p + 1;
    00381         *p = '\0';
    00382         break;
    00383       case ':':
    00384         *port = p + 1;
    00385         *p = '\0';
    00386         break;
    00387     }
    00388   }
    00389 }
    00390
    00391 /* Creates a new client from a socket
    00392  *   Used both by the server and the client */
    00393 static NetworkClientSocket *NetworkAllocClient(SOCKET s)
    00394 {
    00395   if (_network_server) {
    00396     /* Can we handle a new client? */
    00397     if (_network_clients_connected >= MAX_CLIENTS) return NULL;
    00398     if (_network_game_info.clients_on >= _settings_client.network.max_clients) return NULL;
    00399
    00400     /* Register the login */
    00401     _network_clients_connected++;
    00402   }
    00403
    00404   NetworkClientSocket *cs = new NetworkClientSocket(INVALID_CLIENT_ID);
    00405   cs->sock = s;
    00406   cs->last_frame = _frame_counter;
    00407   cs->last_frame_server = _frame_counter;
    00408
    00409   if (_network_server) {
    00410     cs->client_id = _network_client_id++;
    00411     NetworkClientInfo *ci = new NetworkClientInfo(cs->client_id);
    00412     cs->SetInfo(ci);
    00413     ci->client_playas = COMPANY_INACTIVE_CLIENT;
    00414     ci->join_date = _date;
    00415
    00416     InvalidateWindow(WC_CLIENT_LIST, 0);
    00417   }
    00418
    00419   return cs;
    00420 }
    00421
    00422 /* Close a connection */
    00423 void NetworkCloseClient(NetworkClientSocket *cs)
    00424 {
    00425   /*
    00426    * Sending a message just before leaving the game calls cs->Send_Packets.
    00427    * This might invoke this function, which means that when we close the
    00428    * connection after cs->Send_Packets we will close an already closed
    00429    * connection. This handles that case gracefully without having to make
    00430    * that code any more complex or more aware of the validity of the socket.
    00431    */
    00432   if (cs->sock == INVALID_SOCKET) return;
    00433
    00434   DEBUG(net, 1, "Closed client connection %d", cs->client_id);
    00435
    00436   if (!cs->has_quit && _network_server && cs->status > STATUS_INACTIVE) {
    00437     /* We did not receive a leave message from this client... */
    00438     char client_name[NETWORK_CLIENT_NAME_LENGTH];
    00439     NetworkClientSocket *new_cs;
    00440
    00441     NetworkGetClientName(client_name, sizeof(client_name), cs);
    00442
    00443     NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, STR_NETWORK_ERR_CLIENT_CONNECTION_LOST);
    00444
    00445     /* Inform other clients of this... strange leaving ;) */
    00446     FOR_ALL_CLIENT_SOCKETS(new_cs) {
    00447       if (new_cs->status > STATUS_AUTH && cs != new_cs) {
    00448         SEND_COMMAND(PACKET_SERVER_ERROR_QUIT)(new_cs, cs->client_id, NETWORK_ERROR_CONNECTION_LOST);
    00449       }
    00450     }
    00451   }
    00452
    00453   /* When the client was PRE_ACTIVE, the server was in pause mode, so unpause */
    00454   if (cs->status == STATUS_PRE_ACTIVE && _settings_client.network.pause_on_join) {
    00455     DoCommandP(0, 0, 0, CMD_PAUSE);
    00456     NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_BROADCAST, 0, "", CLIENT_ID_SERVER, NETWORK_SERVER_MESSAGE_GAME_UNPAUSED_CONNECT_FAIL);
    00457   }
    00458
    00459   if (_network_server) {
    00460     /* We just lost one client :( */
    00461     if (cs->status >= STATUS_AUTH) _network_game_info.clients_on--;
    00462     _network_clients_connected--;
    00463
    00464     InvalidateWindow(WC_CLIENT_LIST, 0);
    00465   }
    00466
    00467   delete cs->GetInfo();
    00468   delete cs;
    00469 }
    00470
    00471 /* For the server, to accept new clients */
    00472 static void NetworkAcceptClients()
    00473 {
    00474   struct sockaddr_in sin;
    00475   NetworkClientSocket *cs;
    00476   uint i;
    00477   bool banned;
    00478
    00479   /* Should never ever happen.. is it possible?? */
    00480   assert(_listensocket != INVALID_SOCKET);
    00481
    00482   for (;;) {
    00483     socklen_t sin_len = sizeof(sin);
    00484     SOCKET s = accept(_listensocket, (struct sockaddr*)&sin, &sin_len);
    00485     if (s == INVALID_SOCKET) return;
    00486
    00487     SetNonBlocking(s); // XXX error handling?
    00488
    00489     DEBUG(net, 1, "Client connected from %s on frame %d", inet_ntoa(sin.sin_addr), _frame_counter);
    00490
    00491     SetNoDelay(s); // XXX error handling?
    00492
    00493     /* Check if the client is banned */
    00494     banned = false;
    00495     for (i = 0; i < lengthof(_network_ban_list); i++) {
    00496       if (_network_ban_list[i] == NULL) continue;
    00497
    00498       /* Check for CIDR separator */
    00499       char *chr_cidr = strchr(_network_ban_list[i], '/');
    00500       if (chr_cidr != NULL) {
    00501         int cidr = atoi(chr_cidr + 1);
    00502
    00503         /* Invalid CIDR, treat as single host */
    00504         if (cidr <= 0 || cidr > 32) cidr = 32;
    00505
    00506         /* Remove and then replace the / so that inet_addr() works on the IP portion */
    00507         *chr_cidr = '\0';
    00508         uint32 ban_ip = inet_addr(_network_ban_list[i]);
    00509         *chr_cidr = '/';
    00510
    00511         /* Convert CIDR to mask in network format */
    00512         uint32 mask = htonl(-(1 << (32 - cidr)));
    00513         if ((sin.sin_addr.s_addr & mask) == (ban_ip & mask)) banned = true;
    00514       } else {
    00515         /* No CIDR used, so just perform a simple IP test */
    00516         if (sin.sin_addr.s_addr == inet_addr(_network_ban_list[i])) banned = true;
    00517       }
    00518
    00519       if (banned) {
    00520         Packet p(PACKET_SERVER_BANNED);
    00521         p.PrepareToSend();
    00522
    00523         DEBUG(net, 1, "Banned ip tried to join (%s), refused", _network_ban_list[i]);
    00524
    00525         send(s, (const char*)p.buffer, p.size, 0);
    00526         closesocket(s);
    00527         break;
    00528       }
    00529     }
    00530     /* If this client is banned, continue with next client */
    00531     if (banned) continue;
    00532
    00533     cs = NetworkAllocClient(s);
    00534     if (cs == NULL) {
    00535       /* no more clients allowed?
    00536        * Send to the client that we are full! */
    00537       Packet p(PACKET_SERVER_FULL);
    00538       p.PrepareToSend();
    00539
    00540       send(s, (const char*)p.buffer, p.size, 0);
    00541       closesocket(s);
    00542
    00543       continue;
    00544     }
    00545
    00546     /* a new client has connected. We set him at inactive for now
    00547      *  maybe he is only requesting server-info. Till he has sent a PACKET_CLIENT_MAP_OK
    00548      *  the client stays inactive */
    00549     cs->status = STATUS_INACTIVE;
    00550
    00551     cs->GetInfo()->client_ip = sin.sin_addr.s_addr; // Save the IP of the client
    00552   }
    00553 }
    00554
    00555 /* Set up the listen socket for the server */
    00556 static bool NetworkListen()
    00557 {
    00558   SOCKET ls;
    00559   struct sockaddr_in sin;
    00560
    00561   DEBUG(net, 1, "Listening on %s:%d", _settings_client.network.server_bind_ip, _settings_client.network.server_port);
    00562
    00563   ls = socket(AF_INET, SOCK_STREAM, 0);
    00564   if (ls == INVALID_SOCKET) {
    00565     ServerStartError("socket() on listen socket failed");
    00566     return false;
    00567   }
    00568
    00569   { // reuse the socket
    00570     int reuse = 1;
    00571     /* The (const char*) cast is needed for windows!! */
    00572     if (setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) == -1) {
    00573       ServerStartError("setsockopt() on listen socket failed");
    00574       return false;
    00575     }
    00576   }
    00577
    00578   if (!SetNonBlocking(ls)) DEBUG(net, 0, "Setting non-blocking mode failed"); // XXX should this be an error?
    00579
    00580   sin.sin_family = AF_INET;
    00581   sin.sin_addr.s_addr = _network_server_bind_ip;
    00582   sin.sin_port = htons(_settings_client.network.server_port);
    00583
    00584   if (bind(ls, (struct sockaddr*)&sin, sizeof(sin)) != 0) {
    00585     ServerStartError("bind() failed");
    00586     return false;
    00587   }
    00588
    00589   if (listen(ls, 1) != 0) {
    00590     ServerStartError("listen() failed");
    00591     return false;
    00592   }
    00593
    00594   _listensocket = ls;
    00595
    00596   return true;
    00597 }
    00598
    00600 static void InitializeNetworkPools()
    00601 {
    00602   _NetworkClientSocket_pool.CleanPool();
    00603   _NetworkClientSocket_pool.AddBlockToPool();
    00604   _NetworkClientInfo_pool.CleanPool();
    00605   _NetworkClientInfo_pool.AddBlockToPool();
    00606 }
    00607
    00608 /* Close all current connections */
    00609 static void NetworkClose()
    00610 {
    00611   NetworkClientSocket *cs;
    00612
    00613   FOR_ALL_CLIENT_SOCKETS(cs) {
    00614     if (!_network_server) {
    00615       SEND_COMMAND(PACKET_CLIENT_QUIT)();
    00616       cs->Send_Packets();
    00617     }
    00618     NetworkCloseClient(cs);
    00619   }
    00620
    00621   if (_network_server) {
    00622     /* We are a server, also close the listensocket */
    00623     closesocket(_listensocket);
    00624     _listensocket = INVALID_SOCKET;
    00625     DEBUG(net, 1, "Closed listener");
    00626   }
    00627   NetworkUDPCloseAll();
    00628
    00629   TCPConnecter::KillAll();
    00630
    00631   _networking = false;
    00632   _network_server = false;
    00633
    00634   NetworkFreeLocalCommandQueue();
    00635
    00636   free(_network_company_states);
    00637   _network_company_states = NULL;
    00638
    00639   InitializeNetworkPools();
    00640 }
    00641
    00642 /* Inits the network (cleans sockets and stuff) */
    00643 static void NetworkInitialize()
    00644 {
    00645   InitializeNetworkPools();
    00646
    00647   _sync_frame = 0;
    00648   _network_first_time = true;
    00649
    00650   _network_reconnect = 0;
    00651 }
    00652
    00654 class TCPQueryConnecter : TCPConnecter {
    00655 public:
    00656   TCPQueryConnecter(const NetworkAddress &address) : TCPConnecter(address) {}
    00657
    00658   virtual void OnFailure()
    00659   {
    00660     NetworkDisconnect();
    00661   }
    00662
    00663   virtual void OnConnect(SOCKET s)
    00664   {
    00665     _networking = true;
    00666     NetworkAllocClient(s);
    00667     SEND_COMMAND(PACKET_CLIENT_COMPANY_INFO)();
    00668   }
    00669 };
    00670
    00671 /* Query a server to fetch his game-info
    00672  *  If game_info is true, only the gameinfo is fetched,
    00673  *   else only the client_info is fetched */
    00674 void NetworkTCPQueryServer(NetworkAddress address)
    00675 {
    00676   if (!_network_available) return;
    00677
    00678   NetworkDisconnect();
    00679   NetworkInitialize();
    00680
    00681   new TCPQueryConnecter(address);
    00682 }
    00683
    00684 /* Validates an address entered as a string and adds the server to
    00685  * the list. If you use this function, the games will be marked
    00686  * as manually added. */
    00687 void NetworkAddServer(const char *b)
    00688 {
    00689   if (*b != '\0') {
    00690     const char *port = NULL;
    00691     const char *company = NULL;
    00692     char host[NETWORK_HOSTNAME_LENGTH];
    00693     uint16 rport;
    00694
    00695     strecpy(host, b, lastof(host));
    00696
    00697     strecpy(_settings_client.network.connect_to_ip, b, lastof(_settings_client.network.connect_to_ip));
    00698     rport = NETWORK_DEFAULT_PORT;
    00699
    00700     ParseConnectionString(&company, &port, host);
    00701     if (port != NULL) rport = atoi(port);
    00702
    00703     NetworkUDPQueryServer(NetworkAddress(host, rport), true);
    00704   }
    00705 }
    00706
    00707 /* Generates the list of manually added hosts from NetworkGameList and
    00708  * dumps them into the array _network_host_list. This array is needed
    00709  * by the function that generates the config file. */
    00710 void NetworkRebuildHostList()
    00711 {
    00712   uint i = 0;
    00713   const NetworkGameList *item = _network_game_list;
    00714   while (item != NULL && i != lengthof(_network_host_list)) {
    00715     if (item->manually) {
    00716       free(_network_host_list[i]);
    00717       _network_host_list[i++] = str_fmt("%s:%i", item->info.hostname, item->port);
    00718     }
    00719     item = item->next;
    00720   }
    00721
    00722   for (; i < lengthof(_network_host_list); i++) {
    00723     free(_network_host_list[i]);
    00724     _network_host_list[i] = NULL;
    00725   }
    00726 }
    00727
    00729 class TCPClientConnecter : TCPConnecter {
    00730 public:
    00731   TCPClientConnecter(const NetworkAddress &address) : TCPConnecter(address) {}
    00732
    00733   virtual void OnFailure()
    00734   {
    00735     NetworkError(STR_NETWORK_ERR_NOCONNECTION);
    00736   }
    00737
    00738   virtual void OnConnect(SOCKET s)
    00739   {
    00740     _networking = true;
    00741     NetworkAllocClient(s);
    00742     IConsoleCmdExec("exec scripts/on_client.scr 0");
    00743     NetworkClient_Connected();
    00744   }
    00745 };
    00746
    00747
    00748 /* Used by clients, to connect to a server */
    00749 void NetworkClientConnectGame(NetworkAddress address)
    00750 {
    00751   if (!_network_available) return;
    00752
    00753   if (address.GetPort() == 0) return;
    00754
    00755   strecpy(_settings_client.network.last_host, address.GetHostname(), lastof(_settings_client.network.last_host));
    00756   _settings_client.network.last_port = address.GetPort();
    00757
    00758   NetworkDisconnect();
    00759   NetworkInitialize();
    00760
    00761   _network_join_status = NETWORK_JOIN_STATUS_CONNECTING;
    00762   ShowJoinStatusWindow();
    00763
    00764   new TCPClientConnecter(address);
    00765 }
    00766
    00767 static void NetworkInitGameInfo()
    00768 {
    00769   if (StrEmpty(_settings_client.network.server_name)) {
    00770     snprintf(_settings_client.network.server_name, sizeof(_settings_client.network.server_name), "Unnamed Server");
    00771   }
    00772
    00773   /* The server is a client too */
    00774   _network_game_info.clients_on = _network_dedicated ? 0 : 1;
    00775   _network_game_info.start_date = ConvertYMDToDate(_settings_game.game_creation.starting_year, 0, 1);
    00776
    00777   NetworkClientInfo *ci = new NetworkClientInfo(CLIENT_ID_SERVER);
    00778   ci->client_playas = _network_dedicated ? COMPANY_SPECTATOR : _local_company;
    00779
    00780   strecpy(ci->client_name, _settings_client.network.client_name, lastof(ci->client_name));
    00781   strecpy(ci->unique_id, _settings_client.network.network_id, lastof(ci->unique_id));
    00782 }
    00783
    00784 bool NetworkServerStart()
    00785 {
    00786   if (!_network_available) return false;
    00787
    00788   /* Call the pre-scripts */
    00789   IConsoleCmdExec("exec scripts/pre_server.scr 0");
    00790   if (_network_dedicated) IConsoleCmdExec("exec scripts/pre_dedicated.scr 0");
    00791
    00792   NetworkInitialize();
    00793   if (!NetworkListen()) return false;
    00794
    00795   /* Try to start UDP-server */
    00796   _network_udp_server = true;
    00797   _network_udp_server = _udp_server_socket->Listen(_network_server_bind_ip, _settings_client.network.server_port, false);
    00798
    00799   _network_company_states = CallocT<NetworkCompanyState>(MAX_COMPANIES);
    00800   _network_server = true;
    00801   _networking = true;
    00802   _frame_counter = 0;
    00803   _frame_counter_server = 0;
    00804   _frame_counter_max = 0;
    00805   _last_sync_frame = 0;
    00806   _network_own_client_id = CLIENT_ID_SERVER;
    00807
    00808   /* Non-dedicated server will always be company #1 */
    00809   if (!_network_dedicated) _network_playas = COMPANY_FIRST;
    00810
    00811   _network_clients_connected = 0;
    00812
    00813   NetworkInitGameInfo();
    00814
    00815   /* execute server initialization script */
    00816   IConsoleCmdExec("exec scripts/on_server.scr 0");
    00817   /* if the server is dedicated ... add some other script */
    00818   if (_network_dedicated) IConsoleCmdExec("exec scripts/on_dedicated.scr 0");
    00819
    00820   _min_active_clients_paused = false;
    00821
    00822   /* Try to register us to the master server */
    00823   _network_last_advertise_frame = 0;
    00824   _network_need_advertise = true;
    00825   NetworkUDPAdvertise();
    00826   return true;
    00827 }
    00828
    00829 /* The server is rebooting...
    00830  * The only difference with NetworkDisconnect, is the packets that is sent */
    00831 void NetworkReboot()
    00832 {
    00833   if (_network_server) {
    00834     NetworkClientSocket *cs;
    00835     FOR_ALL_CLIENT_SOCKETS(cs) {
    00836       SEND_COMMAND(PACKET_SERVER_NEWGAME)(cs);
    00837       cs->Send_Packets();
    00838     }
    00839   }
    00840
    00841   NetworkClose();
    00842 }
    00843
    00844 /* We want to disconnect from the host/clients */
    00845 void NetworkDisconnect()
    00846 {
    00847   if (_network_server) {
    00848     NetworkClientSocket *cs;
    00849     FOR_ALL_CLIENT_SOCKETS(cs) {
    00850       SEND_COMMAND(PACKET_SERVER_SHUTDOWN)(cs);
    00851       cs->Send_Packets();
    00852     }
    00853   }
    00854
    00855   if (_settings_client.network.server_advertise) NetworkUDPRemoveAdvertise();
    00856
    00857   DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
    00858
    00859   NetworkClose();
    00860 }
    00861
    00862 /* Receives something from the network */
    00863 static bool NetworkReceive()
    00864 {
    00865   NetworkClientSocket *cs;
    00866   int n;
    00867   fd_set read_fd, write_fd;
    00868   struct timeval tv;
    00869
    00870   FD_ZERO(&read_fd);
    00871   FD_ZERO(&write_fd);
    00872
    00873   FOR_ALL_CLIENT_SOCKETS(cs) {
    00874     FD_SET(cs->sock, &read_fd);
    00875     FD_SET(cs->sock, &write_fd);
    00876   }
    00877
    00878   /* take care of listener port */
    00879   if (_network_server) FD_SET(_listensocket, &read_fd);
    00880
    00881   tv.tv_sec = tv.tv_usec = 0; // don't block at all.
    00882 #if !defined(__MORPHOS__) && !defined(__AMIGA__)
    00883   n = select(FD_SETSIZE, &read_fd, &write_fd, NULL, &tv);
    00884 #else
    00885   n = WaitSelect(FD_SETSIZE, &read_fd, &write_fd, NULL, &tv, NULL);
    00886 #endif
    00887   if (n == -1 && !_network_server) NetworkError(STR_NETWORK_ERR_LOSTCONNECTION);
    00888
    00889   /* accept clients.. */
    00890   if (_network_server && FD_ISSET(_listensocket, &read_fd)) NetworkAcceptClients();
    00891
    00892   /* read stuff from clients */
    00893   FOR_ALL_CLIENT_SOCKETS(cs) {
    00894     cs->writable = !!FD_ISSET(cs->sock, &write_fd);
    00895     if (FD_ISSET(cs->sock, &read_fd)) {
    00896       if (_network_server) {
    00897         NetworkServer_ReadPackets(cs);
    00898       } else {
    00899         NetworkRecvStatus res;
    00900
    00901         /* The client already was quiting! */
    00902         if (cs->has_quit) return false;
    00903
    00904         res = NetworkClient_ReadPackets(cs);
    00905         if (res != NETWORK_RECV_STATUS_OKAY) {
    00906           /* The client made an error of which we can not recover
    00907            *   close the client and drop back to main menu */
    00908           NetworkClientError(res, cs);
    00909           return false;
    00910         }
    00911       }
    00912     }
    00913   }
    00914   return true;
    00915 }
    00916
    00917 /* This sends all buffered commands (if possible) */
    00918 static void NetworkSend()
    00919 {
    00920   NetworkClientSocket *cs;
    00921   FOR_ALL_CLIENT_SOCKETS(cs) {
    00922     if (cs->writable) {
    00923       cs->Send_Packets();
    00924
    00925       if (cs->status == STATUS_MAP) {
    00926         /* This client is in the middle of a map-send, call the function for that */
    00927         SEND_COMMAND(PACKET_SERVER_MAP)(cs);
    00928       }
    00929     }
    00930   }
    00931 }
    00932
    00933 static bool NetworkDoClientLoop()
    00934 {
    00935   _frame_counter++;
    00936
    00937   NetworkExecuteLocalCommandQueue();
    00938
    00939   StateGameLoop();
    00940
    00941   /* Check if we are in sync! */
    00942   if (_sync_frame != 0) {
    00943     if (_sync_frame == _frame_counter) {
    00944 #ifdef NETWORK_SEND_DOUBLE_SEED
    00945       if (_sync_seed_1 != _random.state[0] || _sync_seed_2 != _random.state[1]) {
    00946 #else
    00947       if (_sync_seed_1 != _random.state[0]) {
    00948 #endif
    00949         NetworkError(STR_NETWORK_ERR_DESYNC);
    00950         DEBUG(desync, 1, "sync_err: %d; %d\n", _date, _date_fract);
    00951         DEBUG(net, 0, "Sync error detected!");
    00952         NetworkClientError(NETWORK_RECV_STATUS_DESYNC, GetNetworkClientSocket(0));
    00953         return false;
    00954       }
    00955
    00956       /* If this is the first time we have a sync-frame, we
    00957        *   need to let the server know that we are ready and at the same
    00958        *   frame as he is.. so we can start playing! */
    00959       if (_network_first_time) {
    00960         _network_first_time = false;
    00961         SEND_COMMAND(PACKET_CLIENT_ACK)();
    00962       }
    00963
    00964       _sync_frame = 0;
    00965     } else if (_sync_frame < _frame_counter) {
    00966       DEBUG(net, 1, "Missed frame for sync-test (%d / %d)", _sync_frame, _frame_counter);
    00967       _sync_frame = 0;
    00968     }
    00969   }
    00970
    00971   return true;
    00972 }
    00973
    00974 /* We have to do some UDP checking */
    00975 void NetworkUDPGameLoop()
    00976 {
    00977   _network_content_client.SendReceive();
    00978   TCPConnecter::CheckCallbacks();
    00979
    00980   if (_network_udp_server) {
    00981     _udp_server_socket->ReceivePackets();
    00982     _udp_master_socket->ReceivePackets();
    00983   } else {
    00984     _udp_client_socket->ReceivePackets();
    00985     if (_network_udp_broadcast > 0) _network_udp_broadcast--;
    00986     NetworkGameListRequery();
    00987   }
    00988 }
    00989
    00990 /* The main loop called from ttd.c
    00991  *  Here we also have to do StateGameLoop if needed! */
    00992 void NetworkGameLoop()
    00993 {
    00994   if (!_networking) return;
    00995
    00996   if (!NetworkReceive()) return;
    00997
    00998   if (_network_server) {
    00999 #ifdef DEBUG_DUMP_COMMANDS
    01000     static FILE *f = FioFOpenFile("commands.log", "rb", SAVE_DIR);
    01001     static Date next_date = 0;
    01002     static uint32 next_date_fract;
    01003     static CommandPacket *cp = NULL;
    01004     if (f == NULL && next_date == 0) {
    01005       printf("Cannot open commands.log\n");
    01006       next_date = 1;
    01007     }
    01008
    01009     while (f != NULL && !feof(f)) {
    01010       if (cp != NULL && _date == next_date && _date_fract == next_date_fract) {
    01011         _current_company = cp->company;
    01012         DoCommandP(cp->tile, cp->p1, cp->p2, cp->cmd, NULL, cp->text);
    01013         free(cp);
    01014         cp = NULL;
    01015       }
    01016
    01017       if (cp != NULL) break;
    01018
    01019       char buff[4096];
    01020       if (fgets(buff, lengthof(buff), f) == NULL) break;
    01021       if (strncmp(buff, "cmd: ", 8) != 0) continue;
    01022       cp = MallocT<CommandPacket>(1);
    01023       int company;
    01024       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);
    01025       cp->company = (CompanyID)company;
    01026     }
    01027 #endif /* DEBUG_DUMP_COMMANDS */
    01028     CheckMinActiveClients();
    01029
    01030     bool send_frame = false;
    01031
    01032     /* We first increase the _frame_counter */
    01033     _frame_counter++;
    01034     /* Update max-frame-counter */
    01035     if (_frame_counter > _frame_counter_max) {
    01036       _frame_counter_max = _frame_counter + _settings_client.network.frame_freq;
    01037       send_frame = true;
    01038     }
    01039
    01040     NetworkExecuteLocalCommandQueue();
    01041
    01042     /* Then we make the frame */
    01043     StateGameLoop();
    01044
    01045     _sync_seed_1 = _random.state[0];
    01046 #ifdef NETWORK_SEND_DOUBLE_SEED
    01047     _sync_seed_2 = _random.state[1];
    01048 #endif
    01049
    01050     NetworkServer_Tick(send_frame);
    01051   } else {
    01052     /* Client */
    01053
    01054     /* Make sure we are at the frame were the server is (quick-frames) */
    01055     if (_frame_counter_server > _frame_counter) {
    01056       while (_frame_counter_server > _frame_counter) {
    01057         if (!NetworkDoClientLoop()) break;
    01058       }
    01059     } else {
    01060       /* Else, keep on going till _frame_counter_max */
    01061       if (_frame_counter_max > _frame_counter) NetworkDoClientLoop();
    01062     }
    01063   }
    01064
    01065   NetworkSend();
    01066 }
    01067
    01068 static void NetworkGenerateUniqueId()
    01069 {
    01070   Md5 checksum;
    01071   uint8 digest[16];
    01072   char hex_output[16 * 2 + 1];
    01073   char coding_string[NETWORK_NAME_LENGTH];
    01074   int di;
    01075
    01076   snprintf(coding_string, sizeof(coding_string), "%d%s", (uint)Random(), "OpenTTD Unique ID");
    01077
    01078   /* Generate the MD5 hash */
    01079   checksum.Append((const uint8*)coding_string, strlen(coding_string));
    01080   checksum.Finish(digest);
    01081
    01082   for (di = 0; di < 16; ++di)
    01083     sprintf(hex_output + di * 2, "%02x", digest[di]);
    01084
    01085   /* _network_unique_id is our id */
    01086   snprintf(_settings_client.network.network_id, sizeof(_settings_client.network.network_id), "%s", hex_output);
    01087 }
    01088
    01089 void NetworkStartDebugLog(NetworkAddress address)
    01090 {
    01091   extern SOCKET _debug_socket;  // Comes from debug.c
    01092   SOCKET s;
    01093   struct sockaddr_in sin;
    01094
    01095   DEBUG(net, 0, "Redirecting DEBUG() to %s:%d", address.GetHostname(), address.GetPort());
    01096
    01097   s = socket(AF_INET, SOCK_STREAM, 0);
    01098   if (s == INVALID_SOCKET) {
    01099     DEBUG(net, 0, "Failed to open socket for redirection DEBUG()");
    01100     return;
    01101   }
    01102
    01103   if (!SetNoDelay(s)) DEBUG(net, 1, "Setting TCP_NODELAY failed");
    01104
    01105   sin.sin_family = AF_INET;
    01106   sin.sin_addr.s_addr = address.GetIP();
    01107   sin.sin_port = htons(address.GetPort());
    01108
    01109   if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) != 0) {
    01110     DEBUG(net, 0, "Failed to redirection DEBUG() to %s:%d", address.GetHostname(), address.GetPort());
    01111     return;
    01112   }
    01113
    01114   if (!SetNonBlocking(s)) DEBUG(net, 0, "Setting non-blocking mode failed");
    01115   _debug_socket = s;
    01116
    01117   DEBUG(net, 0, "DEBUG() is now redirected");
    01118 }
    01119
    01121 void NetworkStartUp()
    01122 {
    01123   DEBUG(net, 3, "[core] starting network...");
    01124
    01125   /* Network is available */
    01126   _network_available = NetworkCoreInitialize();;
    01127   _network_dedicated = false;
    01128   _network_last_advertise_frame = 0;
    01129   _network_need_advertise = true;
    01130   _network_advertise_retries = 0;
    01131
    01132   /* Load the ip from the openttd.cfg */
    01133   _network_server_bind_ip = inet_addr(_settings_client.network.server_bind_ip);
    01134   /* And put the data back in it in case it was an invalid ip */
    01135   snprintf(_settings_client.network.server_bind_ip, sizeof(_settings_client.network.server_bind_ip), "%s", inet_ntoa(*(struct in_addr *)&_network_server_bind_ip));
    01136
    01137   /* Generate an unique id when there is none yet */
    01138   if (StrEmpty(_settings_client.network.network_id)) NetworkGenerateUniqueId();
    01139
    01140   memset(&_network_game_info, 0, sizeof(_network_game_info));
    01141
    01142   NetworkUDPInitialize();
    01143   NetworkInitialize();
    01144   DEBUG(net, 3, "[core] network online, multiplayer available");
    01145   NetworkFindBroadcastIPs(_broadcast_list, MAX_INTERFACES);
    01146 }
    01147
    01149 void NetworkShutDown()
    01150 {
    01151   NetworkDisconnect();
    01152   NetworkUDPShutdown();
    01153
    01154   DEBUG(net, 3, "[core] shutting down network");
    01155
    01156   _network_available = false;
    01157
    01158   NetworkCoreShutdown();
    01159 }
    01160
    01165 bool IsNetworkCompatibleVersion(const char *other)
    01166 {
    01167   return strncmp(_openttd_revision, other, NETWORK_REVISION_LENGTH - 1) == 0;
    01168 }
    01169
    01170 #endif /* ENABLE_NETWORK */
    01171
    01172 /* NOTE: this variable needs to be always available */
    01173 CompanyID _network_playas;