# network.cpp

Go to the documentation of this file.

    00001 /* $Id: network.cpp 24900 2013-01-08 22:46:42Z planetmaker $ */
    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 #include "../stdafx.h"
    00013
    00014 #ifdef ENABLE_NETWORK
    00015
    00016 #include "../strings_func.h"
    00017 #include "../command_func.h"
    00018 #include "../date_func.h"
    00019 #include "network_admin.h"
    00020 #include "network_client.h"
    00021 #include "network_server.h"
    00022 #include "network_content.h"
    00023 #include "network_udp.h"
    00024 #include "network_gamelist.h"
    00025 #include "network_base.h"
    00026 #include "core/udp.h"
    00027 #include "core/host.h"
    00028 #include "network_gui.h"
    00029 #include "../console_func.h"
    00030 #include "../3rdparty/md5/md5.h"
    00031 #include "../core/random_func.hpp"
    00032 #include "../window_func.h"
    00033 #include "../company_func.h"
    00034 #include "../company_base.h"
    00035 #include "../landscape_type.h"
    00036 #include "../rev.h"
    00037 #include "../core/pool_func.hpp"
    00038 #include "../gfx_func.h"
    00039 #include "../error.h"
    00040
    00041 #ifdef DEBUG_DUMP_COMMANDS
    00042 #include "../fileio_func.h"
    00044 bool _ddc_fastforward = true;
    00045 #endif /* DEBUG_DUMP_COMMANDS */
    00046
    00048 assert_compile(NetworkClientInfoPool::MAX_SIZE == NetworkClientSocketPool::MAX_SIZE);
    00049
    00051 NetworkClientInfoPool _networkclientinfo_pool("NetworkClientInfo");
    00052 INSTANTIATE_POOL_METHODS(NetworkClientInfo)
    00053
    00054 bool _networking;
    00055 bool _network_server;
    00056 bool _network_available;
    00057 bool _network_dedicated;
    00058 bool _is_network_server;
    00059 NetworkServerGameInfo _network_game_info;
    00060 NetworkCompanyState *_network_company_states = NULL;
    00061 ClientID _network_own_client_id;
    00062 ClientID _redirect_console_to_client;
    00063 bool _network_need_advertise;
    00064 uint32 _network_last_advertise_frame;
    00065 uint8 _network_reconnect;
    00066 StringList _network_bind_list;
    00067 StringList _network_host_list;
    00068 StringList _network_ban_list;
    00069 uint32 _frame_counter_server;
    00070 uint32 _frame_counter_max;
    00071 uint32 _frame_counter;
    00072 uint32 _last_sync_frame;
    00073 NetworkAddressList _broadcast_list;
    00074 uint32 _sync_seed_1;
    00075 #ifdef NETWORK_SEND_DOUBLE_SEED
    00076 uint32 _sync_seed_2;
    00077 #endif
    00078 uint32 _sync_frame;
    00079 bool _network_first_time;
    00080 bool _network_udp_server;
    00081 uint16 _network_udp_broadcast;
    00082 uint8 _network_advertise_retries;
    00083 CompanyMask _network_company_passworded;
    00084
    00085 /* Check whether NETWORK_NUM_LANDSCAPES is still in sync with NUM_LANDSCAPE */
    00086 assert_compile((int)NETWORK_NUM_LANDSCAPES == (int)NUM_LANDSCAPE);
    00087 assert_compile((int)NETWORK_COMPANY_NAME_LENGTH == MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH);
    00088
    00089 extern NetworkUDPSocketHandler *_udp_client_socket;
    00090 extern NetworkUDPSocketHandler *_udp_server_socket;
    00091 extern NetworkUDPSocketHandler *_udp_master_socket;
    00092
    00094 byte _network_clients_connected = 0;
    00095
    00096 /* Some externs / forwards */
    00097 extern void StateGameLoop();
    00098
    00102 NetworkClientInfo::~NetworkClientInfo()
    00103 {
    00104   /* Delete the chat window, if you were chatting with this client. */
    00105   InvalidateWindowData(WC_SEND_NETWORK_MSG, DESTTYPE_CLIENT, this->client_id);
    00106 }
    00107
    00113 /* static */ NetworkClientInfo *NetworkClientInfo::GetByClientID(ClientID client_id)
    00114 {
    00115   NetworkClientInfo *ci;
    00116
    00117   FOR_ALL_CLIENT_INFOS(ci) {
    00118     if (ci->client_id == client_id) return ci;
    00119   }
    00120
    00121   return NULL;
    00122 }
    00123
    00129 /* static */ ServerNetworkGameSocketHandler *ServerNetworkGameSocketHandler::GetByClientID(ClientID client_id)
    00130 {
    00131   NetworkClientSocket *cs;
    00132
    00133   FOR_ALL_CLIENT_SOCKETS(cs) {
    00134     if (cs->client_id == client_id) return cs;
    00135   }
    00136
    00137   return NULL;
    00138 }
    00139
    00140 byte NetworkSpectatorCount()
    00141 {
    00142   const NetworkClientInfo *ci;
    00143   byte count = 0;
    00144
    00145   FOR_ALL_CLIENT_INFOS(ci) {
    00146     if (ci->client_playas == COMPANY_SPECTATOR) count++;
    00147   }
    00148
    00149   /* Don't count a dedicated server as spectator */
    00150   if (_network_dedicated) count--;
    00151
    00152   return count;
    00153 }
    00154
    00161 const char *NetworkChangeCompanyPassword(CompanyID company_id, const char *password)
    00162 {
    00163   if (strcmp(password, "*") == 0) password = "";
    00164
    00165   if (_network_server) {
    00166     NetworkServerSetCompanyPassword(company_id, password, false);
    00167   } else {
    00168     NetworkClientSetCompanyPassword(password);
    00169   }
    00170
    00171   return password;
    00172 }
    00173
    00181 const char *GenerateCompanyPasswordHash(const char *password, const char *password_server_id, uint32 password_game_seed)
    00182 {
    00183   if (StrEmpty(password)) return password;
    00184
    00185   char salted_password[NETWORK_SERVER_ID_LENGTH];
    00186
    00187   memset(salted_password, 0, sizeof(salted_password));
    00188   snprintf(salted_password, sizeof(salted_password), "%s", password);
    00189   /* Add the game seed and the server's ID as the salt. */
    00190   for (uint i = 0; i < NETWORK_SERVER_ID_LENGTH - 1; i++) {
    00191     salted_password[i] ^= password_server_id[i] ^ (password_game_seed >> (i % 32));
    00192   }
    00193
    00194   Md5 checksum;
    00195   uint8 digest[16];
    00196   static char hashed_password[NETWORK_SERVER_ID_LENGTH];
    00197
    00198   /* Generate the MD5 hash */
    00199   checksum.Append(salted_password, sizeof(salted_password) - 1);
    00200   checksum.Finish(digest);
    00201
    00202   for (int di = 0; di < 16; di++) sprintf(hashed_password + di * 2, "%02x", digest[di]);
    00203   hashed_password[lengthof(hashed_password) - 1] = '\0';
    00204
    00205   return hashed_password;
    00206 }
    00207
    00213 bool NetworkCompanyIsPassworded(CompanyID company_id)
    00214 {
    00215   return HasBit(_network_company_passworded, company_id);
    00216 }
    00217
    00218 /* This puts a text-message to the console, or in the future, the chat-box,
    00219  *  (to keep it all a bit more general)
    00220  * If 'self_send' is true, this is the client who is sending the message */
    00221 void NetworkTextMessage(NetworkAction action, TextColour colour, bool self_send, const char *name, const char *str, int64 data)
    00222 {
    00223   StringID strid;
    00224   switch (action) {
    00225     case NETWORK_ACTION_SERVER_MESSAGE:
    00226       /* Ignore invalid messages */
    00227       strid = STR_NETWORK_SERVER_MESSAGE;
    00228       colour = CC_DEFAULT;
    00229       break;
    00230     case NETWORK_ACTION_COMPANY_SPECTATOR:
    00231       colour = CC_DEFAULT;
    00232       strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_SPECTATE;
    00233       break;
    00234     case NETWORK_ACTION_COMPANY_JOIN:
    00235       colour = CC_DEFAULT;
    00236       strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_JOIN;
    00237       break;
    00238     case NETWORK_ACTION_COMPANY_NEW:
    00239       colour = CC_DEFAULT;
    00240       strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_NEW;
    00241       break;
    00242     case NETWORK_ACTION_JOIN:
    00243       /* Show the Client ID for the server but not for the client. */
    00244       strid = _network_server ? STR_NETWORK_MESSAGE_CLIENT_JOINED_ID :  STR_NETWORK_MESSAGE_CLIENT_JOINED;
    00245       break;
    00246     case NETWORK_ACTION_LEAVE:          strid = STR_NETWORK_MESSAGE_CLIENT_LEFT; break;
    00247     case NETWORK_ACTION_NAME_CHANGE:    strid = STR_NETWORK_MESSAGE_NAME_CHANGE; break;
    00248     case NETWORK_ACTION_GIVE_MONEY:     strid = self_send ? STR_NETWORK_MESSAGE_GAVE_MONEY_AWAY : STR_NETWORK_MESSAGE_GIVE_MONEY;   break;
    00249     case NETWORK_ACTION_CHAT_COMPANY:   strid = self_send ? STR_NETWORK_CHAT_TO_COMPANY : STR_NETWORK_CHAT_COMPANY; break;
    00250     case NETWORK_ACTION_CHAT_CLIENT:    strid = self_send ? STR_NETWORK_CHAT_TO_CLIENT  : STR_NETWORK_CHAT_CLIENT;  break;
    00251     default:                            strid = STR_NETWORK_CHAT_ALL; break;
    00252   }
    00253
    00254   char message[1024];
    00255   SetDParamStr(0, name);
    00256   SetDParamStr(1, str);
    00257   SetDParam(2, data);
    00258
    00259   /* All of these strings start with "***". These characters are interpreted as both left-to-right and
    00260    * right-to-left characters depending on the context. As the next text might be an user's name, the
    00261    * user name's characters will influence the direction of the "***" instead of the language setting
    00262    * of the game. Manually set the direction of the "***" by inserting a text-direction marker. */
    00263   char *msg_ptr = message + Utf8Encode(message, _current_text_dir == TD_LTR ? CHAR_TD_LRM : CHAR_TD_RLM);
    00264   GetString(msg_ptr, strid, lastof(message));
    00265
    00266   DEBUG(desync, 1, "msg: %08x; %02x; %s", _date, _date_fract, message);
    00267   IConsolePrintF(colour, "%s", message);
    00268   NetworkAddChatMessage((TextColour)colour, _settings_client.gui.network_chat_timeout, "%s", message);
    00269 }
    00270
    00271 /* Calculate the frame-lag of a client */
    00272 uint NetworkCalculateLag(const NetworkClientSocket *cs)
    00273 {
    00274   int lag = cs->last_frame_server - cs->last_frame;
    00275   /* This client has missed his ACK packet after 1 DAY_TICKS..
    00276    *  so we increase his lag for every frame that passes!
    00277    * The packet can be out by a max of _net_frame_freq */
    00278   if (cs->last_frame_server + DAY_TICKS + _settings_client.network.frame_freq < _frame_counter) {
    00279     lag += _frame_counter - (cs->last_frame_server + DAY_TICKS + _settings_client.network.frame_freq);
    00280   }
    00281   return lag;
    00282 }
    00283
    00284
    00285 /* There was a non-recoverable error, drop back to the main menu with a nice
    00286  *  error */
    00287 void NetworkError(StringID error_string)
    00288 {
    00289   _switch_mode = SM_MENU;
    00290   ShowErrorMessage(error_string, INVALID_STRING_ID, WL_CRITICAL);
    00291 }
    00292
    00298 StringID GetNetworkErrorMsg(NetworkErrorCode err)
    00299 {
    00300   /* List of possible network errors, used by
    00301    * PACKET_SERVER_ERROR and PACKET_CLIENT_ERROR */
    00302   static const StringID network_error_strings[] = {
    00303     STR_NETWORK_ERROR_CLIENT_GENERAL,
    00304     STR_NETWORK_ERROR_CLIENT_DESYNC,
    00305     STR_NETWORK_ERROR_CLIENT_SAVEGAME,
    00306     STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST,
    00307     STR_NETWORK_ERROR_CLIENT_PROTOCOL_ERROR,
    00308     STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH,
    00309     STR_NETWORK_ERROR_CLIENT_NOT_AUTHORIZED,
    00310     STR_NETWORK_ERROR_CLIENT_NOT_EXPECTED,
    00311     STR_NETWORK_ERROR_CLIENT_WRONG_REVISION,
    00312     STR_NETWORK_ERROR_CLIENT_NAME_IN_USE,
    00313     STR_NETWORK_ERROR_CLIENT_WRONG_PASSWORD,
    00314     STR_NETWORK_ERROR_CLIENT_COMPANY_MISMATCH,
    00315     STR_NETWORK_ERROR_CLIENT_KICKED,
    00316     STR_NETWORK_ERROR_CLIENT_CHEATER,
    00317     STR_NETWORK_ERROR_CLIENT_SERVER_FULL,
    00318     STR_NETWORK_ERROR_CLIENT_TOO_MANY_COMMANDS,
    00319     STR_NETWORK_ERROR_CLIENT_TIMEOUT_PASSWORD,
    00320     STR_NETWORK_ERROR_CLIENT_TIMEOUT_COMPUTER,
    00321     STR_NETWORK_ERROR_CLIENT_TIMEOUT_MAP,
    00322     STR_NETWORK_ERROR_CLIENT_TIMEOUT_JOIN,
    00323   };
    00324   assert_compile(lengthof(network_error_strings) == NETWORK_ERROR_END);
    00325
    00326   if (err >= (ptrdiff_t)lengthof(network_error_strings)) err = NETWORK_ERROR_GENERAL;
    00327
    00328   return network_error_strings[err];
    00329 }
    00330
    00336 void NetworkHandlePauseChange(PauseMode prev_mode, PauseMode changed_mode)
    00337 {
    00338   if (!_networking) return;
    00339
    00340   switch (changed_mode) {
    00341     case PM_PAUSED_NORMAL:
    00342     case PM_PAUSED_JOIN:
    00343     case PM_PAUSED_GAME_SCRIPT:
    00344     case PM_PAUSED_ACTIVE_CLIENTS: {
    00345       bool changed = ((_pause_mode == PM_UNPAUSED) != (prev_mode == PM_UNPAUSED));
    00346       bool paused = (_pause_mode != PM_UNPAUSED);
    00347       if (!paused && !changed) return;
    00348
    00349       StringID str;
    00350       if (!changed) {
    00351         int i = -1;
    00352
    00353         if ((_pause_mode & PM_PAUSED_NORMAL) != PM_UNPAUSED)         SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_MANUAL);
    00354         if ((_pause_mode & PM_PAUSED_JOIN) != PM_UNPAUSED)           SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_CONNECTING_CLIENTS);
    00355         if ((_pause_mode & PM_PAUSED_GAME_SCRIPT) != PM_UNPAUSED)    SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_GAME_SCRIPT);
    00356         if ((_pause_mode & PM_PAUSED_ACTIVE_CLIENTS) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_NOT_ENOUGH_PLAYERS);
    00357         str = STR_NETWORK_SERVER_MESSAGE_GAME_STILL_PAUSED_1 + i;
    00358       } else {
    00359         switch (changed_mode) {
    00360           case PM_PAUSED_NORMAL:         SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_MANUAL); break;
    00361           case PM_PAUSED_JOIN:           SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_CONNECTING_CLIENTS); break;
    00362           case PM_PAUSED_GAME_SCRIPT:    SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_GAME_SCRIPT); break;
    00363           case PM_PAUSED_ACTIVE_CLIENTS: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_NOT_ENOUGH_PLAYERS); break;
    00364           default: NOT_REACHED();
    00365         }
    00366         str = paused ? STR_NETWORK_SERVER_MESSAGE_GAME_PAUSED : STR_NETWORK_SERVER_MESSAGE_GAME_UNPAUSED;
    00367       }
    00368
    00369       char buffer[DRAW_STRING_BUFFER];
    00370       GetString(buffer, str, lastof(buffer));
    00371       NetworkTextMessage(NETWORK_ACTION_SERVER_MESSAGE, CC_DEFAULT, false, NULL, buffer);
    00372       break;
    00373     }
    00374
    00375     default:
    00376       return;
    00377   }
    00378 }
    00379
    00380
    00389 static void CheckPauseHelper(bool pause, PauseMode pm)
    00390 {
    00391   if (pause == ((_pause_mode & pm) != PM_UNPAUSED)) return;
    00392
    00393   DoCommandP(0, pm, pause ? 1 : 0, CMD_PAUSE);
    00394 }
    00395
    00401 static uint NetworkCountActiveClients()
    00402 {
    00403   const NetworkClientSocket *cs;
    00404   uint count = 0;
    00405
    00406   FOR_ALL_CLIENT_SOCKETS(cs) {
    00407     if (cs->status != NetworkClientSocket::STATUS_ACTIVE) continue;
    00408     if (!Company::IsValidID(cs->GetInfo()->client_playas)) continue;
    00409     count++;
    00410   }
    00411
    00412   return count;
    00413 }
    00414
    00418 static void CheckMinActiveClients()
    00419 {
    00420   if ((_pause_mode & PM_PAUSED_ERROR) != PM_UNPAUSED ||
    00421       !_network_dedicated ||
    00422       (_settings_client.network.min_active_clients == 0 && (_pause_mode & PM_PAUSED_ACTIVE_CLIENTS) == PM_UNPAUSED)) {
    00423     return;
    00424   }
    00425   CheckPauseHelper(NetworkCountActiveClients() < _settings_client.network.min_active_clients, PM_PAUSED_ACTIVE_CLIENTS);
    00426 }
    00427
    00432 static bool NetworkHasJoiningClient()
    00433 {
    00434   const NetworkClientSocket *cs;
    00435   FOR_ALL_CLIENT_SOCKETS(cs) {
    00436     if (cs->status >= NetworkClientSocket::STATUS_AUTHORIZED && cs->status < NetworkClientSocket::STATUS_ACTIVE) return true;
    00437   }
    00438
    00439   return false;
    00440 }
    00441
    00445 static void CheckPauseOnJoin()
    00446 {
    00447   if ((_pause_mode & PM_PAUSED_ERROR) != PM_UNPAUSED ||
    00448       (!_settings_client.network.pause_on_join && (_pause_mode & PM_PAUSED_JOIN) == PM_UNPAUSED)) {
    00449     return;
    00450   }
    00451   CheckPauseHelper(NetworkHasJoiningClient(), PM_PAUSED_JOIN);
    00452 }
    00453
    00462 void ParseConnectionString(const char **company, const char **port, char *connection_string)
    00463 {
    00464   bool ipv6 = (strchr(connection_string, ':') != strrchr(connection_string, ':'));
    00465   char *p;
    00466   for (p = connection_string; *p != '\0'; p++) {
    00467     switch (*p) {
    00468       case '[':
    00469         ipv6 = true;
    00470         break;
    00471
    00472       case ']':
    00473         ipv6 = false;
    00474         break;
    00475
    00476       case '#':
    00477         *company = p + 1;
    00478         *p = '\0';
    00479         break;
    00480
    00481       case ':':
    00482         if (ipv6) break;
    00483         *port = p + 1;
    00484         *p = '\0';
    00485         break;
    00486     }
    00487   }
    00488 }
    00489
    00495 /* static */ void ServerNetworkGameSocketHandler::AcceptConnection(SOCKET s, const NetworkAddress &address)
    00496 {
    00497   /* Register the login */
    00498   _network_clients_connected++;
    00499
    00500   SetWindowDirty(WC_CLIENT_LIST, 0);
    00501   ServerNetworkGameSocketHandler *cs = new ServerNetworkGameSocketHandler(s);
    00502   cs->client_address = address; // Save the IP of the client
    00503 }
    00504
    00509 static void InitializeNetworkPools(bool close_admins = true)
    00510 {
    00511   PoolBase::Clean(PT_NCLIENT | (close_admins ? PT_NADMIN : PT_NONE));
    00512 }
    00513
    00518 void NetworkClose(bool close_admins)
    00519 {
    00520   if (_network_server) {
    00521     if (close_admins) {
    00522       ServerNetworkAdminSocketHandler *as;
    00523       FOR_ALL_ADMIN_SOCKETS(as) {
    00524         as->CloseConnection(true);
    00525       }
    00526     }
    00527
    00528     NetworkClientSocket *cs;
    00529     FOR_ALL_CLIENT_SOCKETS(cs) {
    00530       cs->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
    00531     }
    00532     ServerNetworkGameSocketHandler::CloseListeners();
    00533     ServerNetworkAdminSocketHandler::CloseListeners();
    00534   } else if (MyClient::my_client != NULL) {
    00535     MyClient::SendQuit();
    00536     MyClient::my_client->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
    00537   }
    00538
    00539   TCPConnecter::KillAll();
    00540
    00541   _networking = false;
    00542   _network_server = false;
    00543
    00544   NetworkFreeLocalCommandQueue();
    00545
    00546   free(_network_company_states);
    00547   _network_company_states = NULL;
    00548
    00549   InitializeNetworkPools(close_admins);
    00550 }
    00551
    00552 /* Initializes the network (cleans sockets and stuff) */
    00553 static void NetworkInitialize(bool close_admins = true)
    00554 {
    00555   InitializeNetworkPools(close_admins);
    00556   NetworkUDPInitialize();
    00557
    00558   _sync_frame = 0;
    00559   _network_first_time = true;
    00560
    00561   _network_reconnect = 0;
    00562 }
    00563
    00565 class TCPQueryConnecter : TCPConnecter {
    00566 public:
    00567   TCPQueryConnecter(const NetworkAddress &address) : TCPConnecter(address) {}
    00568
    00569   virtual void OnFailure()
    00570   {
    00571     NetworkDisconnect();
    00572   }
    00573
    00574   virtual void OnConnect(SOCKET s)
    00575   {
    00576     _networking = true;
    00577     new ClientNetworkGameSocketHandler(s);
    00578     MyClient::SendCompanyInformationQuery();
    00579   }
    00580 };
    00581
    00582 /* Query a server to fetch his game-info
    00583  *  If game_info is true, only the gameinfo is fetched,
    00584  *   else only the client_info is fetched */
    00585 void NetworkTCPQueryServer(NetworkAddress address)
    00586 {
    00587   if (!_network_available) return;
    00588
    00589   NetworkDisconnect();
    00590   NetworkInitialize();
    00591
    00592   new TCPQueryConnecter(address);
    00593 }
    00594
    00595 /* Validates an address entered as a string and adds the server to
    00596  * the list. If you use this function, the games will be marked
    00597  * as manually added. */
    00598 void NetworkAddServer(const char *b)
    00599 {
    00600   if (*b != '\0') {
    00601     const char *port = NULL;
    00602     const char *company = NULL;
    00603     char host[NETWORK_HOSTNAME_LENGTH];
    00604     uint16 rport;
    00605
    00606     strecpy(host, b, lastof(host));
    00607
    00608     strecpy(_settings_client.network.connect_to_ip, b, lastof(_settings_client.network.connect_to_ip));
    00609     rport = NETWORK_DEFAULT_PORT;
    00610
    00611     ParseConnectionString(&company, &port, host);
    00612     if (port != NULL) rport = atoi(port);
    00613
    00614     NetworkUDPQueryServer(NetworkAddress(host, rport), true);
    00615   }
    00616 }
    00617
    00623 void GetBindAddresses(NetworkAddressList *addresses, uint16 port)
    00624 {
    00625   for (char **iter = _network_bind_list.Begin(); iter != _network_bind_list.End(); iter++) {
    00626     *addresses->Append() = NetworkAddress(*iter, port);
    00627   }
    00628
    00629   /* No address, so bind to everything. */
    00630   if (addresses->Length() == 0) {
    00631     *addresses->Append() = NetworkAddress("", port);
    00632   }
    00633 }
    00634
    00635 /* Generates the list of manually added hosts from NetworkGameList and
    00636  * dumps them into the array _network_host_list. This array is needed
    00637  * by the function that generates the config file. */
    00638 void NetworkRebuildHostList()
    00639 {
    00640   _network_host_list.Clear();
    00641
    00642   for (NetworkGameList *item = _network_game_list; item != NULL; item = item->next) {
    00643     if (item->manually) *_network_host_list.Append() = strdup(item->address.GetAddressAsString(false));
    00644   }
    00645 }
    00646
    00648 class TCPClientConnecter : TCPConnecter {
    00649 public:
    00650   TCPClientConnecter(const NetworkAddress &address) : TCPConnecter(address) {}
    00651
    00652   virtual void OnFailure()
    00653   {
    00654     NetworkError(STR_NETWORK_ERROR_NOCONNECTION);
    00655   }
    00656
    00657   virtual void OnConnect(SOCKET s)
    00658   {
    00659     _networking = true;
    00660     new ClientNetworkGameSocketHandler(s);
    00661     IConsoleCmdExec("exec scripts/on_client.scr 0");
    00662     NetworkClient_Connected();
    00663   }
    00664 };
    00665
    00666
    00667 /* Used by clients, to connect to a server */
    00668 void NetworkClientConnectGame(NetworkAddress address, CompanyID join_as, const char *join_server_password, const char *join_company_password)
    00669 {
    00670   if (!_network_available) return;
    00671
    00672   if (address.GetPort() == 0) return;
    00673
    00674   strecpy(_settings_client.network.last_host, address.GetHostname(), lastof(_settings_client.network.last_host));
    00675   _settings_client.network.last_port = address.GetPort();
    00676   _network_join_as = join_as;
    00677   _network_join_server_password = join_server_password;
    00678   _network_join_company_password = join_company_password;
    00679
    00680   NetworkDisconnect();
    00681   NetworkInitialize();
    00682
    00683   _network_join_status = NETWORK_JOIN_STATUS_CONNECTING;
    00684   ShowJoinStatusWindow();
    00685
    00686   new TCPClientConnecter(address);
    00687 }
    00688
    00689 static void NetworkInitGameInfo()
    00690 {
    00691   if (StrEmpty(_settings_client.network.server_name)) {
    00692     snprintf(_settings_client.network.server_name, sizeof(_settings_client.network.server_name), "Unnamed Server");
    00693   }
    00694
    00695   /* The server is a client too */
    00696   _network_game_info.clients_on = _network_dedicated ? 0 : 1;
    00697
    00698   /* There should be always space for the server. */
    00699   assert(NetworkClientInfo::CanAllocateItem());
    00700   NetworkClientInfo *ci = new NetworkClientInfo(CLIENT_ID_SERVER);
    00701   ci->client_playas = _network_dedicated ? COMPANY_SPECTATOR : _local_company;
    00702
    00703   strecpy(ci->client_name, _settings_client.network.client_name, lastof(ci->client_name));
    00704 }
    00705
    00706 bool NetworkServerStart()
    00707 {
    00708   if (!_network_available) return false;
    00709
    00710   /* Call the pre-scripts */
    00711   IConsoleCmdExec("exec scripts/pre_server.scr 0");
    00712   if (_network_dedicated) IConsoleCmdExec("exec scripts/pre_dedicated.scr 0");
    00713
    00714   NetworkDisconnect(false, false);
    00715   NetworkInitialize(false);
    00716   if (!ServerNetworkGameSocketHandler::Listen(_settings_client.network.server_port)) return false;
    00717
    00718   /* Only listen for admins when the password isn't empty. */
    00719   if (!StrEmpty(_settings_client.network.admin_password) && !ServerNetworkAdminSocketHandler::Listen(_settings_client.network.server_admin_port)) return false;
    00720
    00721   /* Try to start UDP-server */
    00722   _network_udp_server = _udp_server_socket->Listen();
    00723
    00724   _network_company_states = CallocT<NetworkCompanyState>(MAX_COMPANIES);
    00725   _network_server = true;
    00726   _networking = true;
    00727   _frame_counter = 0;
    00728   _frame_counter_server = 0;
    00729   _frame_counter_max = 0;
    00730   _last_sync_frame = 0;
    00731   _network_own_client_id = CLIENT_ID_SERVER;
    00732
    00733   _network_clients_connected = 0;
    00734   _network_company_passworded = 0;
    00735
    00736   NetworkInitGameInfo();
    00737
    00738   /* execute server initialization script */
    00739   IConsoleCmdExec("exec scripts/on_server.scr 0");
    00740   /* if the server is dedicated ... add some other script */
    00741   if (_network_dedicated) IConsoleCmdExec("exec scripts/on_dedicated.scr 0");
    00742
    00743   /* Try to register us to the master server */
    00744   _network_last_advertise_frame = 0;
    00745   _network_need_advertise = true;
    00746   NetworkUDPAdvertise();
    00747
    00748   /* welcome possibly still connected admins - this can only happen on a dedicated server. */
    00749   if (_network_dedicated) ServerNetworkAdminSocketHandler::WelcomeAll();
    00750
    00751   return true;
    00752 }
    00753
    00754 /* The server is rebooting...
    00755  * The only difference with NetworkDisconnect, is the packets that is sent */
    00756 void NetworkReboot()
    00757 {
    00758   if (_network_server) {
    00759     NetworkClientSocket *cs;
    00760     FOR_ALL_CLIENT_SOCKETS(cs) {
    00761       cs->SendNewGame();
    00762       cs->SendPackets();
    00763     }
    00764
    00765     ServerNetworkAdminSocketHandler *as;
    00766     FOR_ALL_ACTIVE_ADMIN_SOCKETS(as) {
    00767       as->SendNewGame();
    00768       as->SendPackets();
    00769     }
    00770   }
    00771
    00772   /* For non-dedicated servers we have to kick the admins as we are not
    00773    * certain that we will end up in a new network game. */
    00774   NetworkClose(!_network_dedicated);
    00775 }
    00776
    00782 void NetworkDisconnect(bool blocking, bool close_admins)
    00783 {
    00784   if (_network_server) {
    00785     NetworkClientSocket *cs;
    00786     FOR_ALL_CLIENT_SOCKETS(cs) {
    00787       cs->SendShutdown();
    00788       cs->SendPackets();
    00789     }
    00790
    00791     if (close_admins) {
    00792       ServerNetworkAdminSocketHandler *as;
    00793       FOR_ALL_ACTIVE_ADMIN_SOCKETS(as) {
    00794         as->SendShutdown();
    00795         as->SendPackets();
    00796       }
    00797     }
    00798   }
    00799
    00800   if (_settings_client.network.server_advertise) NetworkUDPRemoveAdvertise(blocking);
    00801
    00802   DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
    00803
    00804   NetworkClose(close_admins);
    00805
    00806   /* Reinitialize the UDP stack, i.e. close all existing connections. */
    00807   NetworkUDPInitialize();
    00808 }
    00809
    00814 static bool NetworkReceive()
    00815 {
    00816   if (_network_server) {
    00817     ServerNetworkAdminSocketHandler::Receive();
    00818     return ServerNetworkGameSocketHandler::Receive();
    00819   } else {
    00820     return ClientNetworkGameSocketHandler::Receive();
    00821   }
    00822 }
    00823
    00824 /* This sends all buffered commands (if possible) */
    00825 static void NetworkSend()
    00826 {
    00827   if (_network_server) {
    00828     ServerNetworkAdminSocketHandler::Send();
    00829     ServerNetworkGameSocketHandler::Send();
    00830   } else {
    00831     ClientNetworkGameSocketHandler::Send();
    00832   }
    00833 }
    00834
    00840 void NetworkBackgroundLoop()
    00841 {
    00842   _network_content_client.SendReceive();
    00843   TCPConnecter::CheckCallbacks();
    00844   NetworkHTTPSocketHandler::HTTPReceive();
    00845
    00846   NetworkBackgroundUDPLoop();
    00847 }
    00848
    00849 /* The main loop called from ttd.c
    00850  *  Here we also have to do StateGameLoop if needed! */
    00851 void NetworkGameLoop()
    00852 {
    00853   if (!_networking) return;
    00854
    00855   if (!NetworkReceive()) return;
    00856
    00857   if (_network_server) {
    00858     /* Log the sync state to check for in-syncedness of replays. */
    00859     if (_date_fract == 0) {
    00860       /* We don't want to log multiple times if paused. */
    00861       static Date last_log;
    00862       if (last_log != _date) {
    00863         DEBUG(desync, 1, "sync: %08x; %02x; %08x; %08x", _date, _date_fract, _random.state[0], _random.state[1]);
    00864         last_log = _date;
    00865       }
    00866     }
    00867
    00868 #ifdef DEBUG_DUMP_COMMANDS
    00869     /* Loading of the debug commands from -ddesync>=1 */
    00870     static FILE *f = FioFOpenFile("commands.log", "rb", SAVE_DIR);
    00871     static Date next_date = 0;
    00872     static uint32 next_date_fract;
    00873     static CommandPacket *cp = NULL;
    00874     static bool check_sync_state = false;
    00875     static uint32 sync_state[2];
    00876     if (f == NULL && next_date == 0) {
    00877       DEBUG(net, 0, "Cannot open commands.log");
    00878       next_date = 1;
    00879     }
    00880
    00881     while (f != NULL && !feof(f)) {
    00882       if (_date == next_date && _date_fract == next_date_fract) {
    00883         if (cp != NULL) {
    00884           NetworkSendCommand(cp->tile, cp->p1, cp->p2, cp->cmd & ~CMD_FLAGS_MASK, NULL, cp->text, cp->company);
    00885           DEBUG(net, 0, "injecting: %08x; %02x; %02x; %06x; %08x; %08x; %08x; \"%s\" (%s)", _date, _date_fract, (int)_current_company, cp->tile, cp->p1, cp->p2, cp->cmd, cp->text, GetCommandName(cp->cmd));
    00886           free(cp);
    00887           cp = NULL;
    00888         }
    00889         if (check_sync_state) {
    00890           if (sync_state[0] == _random.state[0] && sync_state[1] == _random.state[1]) {
    00891             DEBUG(net, 0, "sync check: %08x; %02x; match", _date, _date_fract);
    00892           } else {
    00893             DEBUG(net, 0, "sync check: %08x; %02x; mismatch expected {%08x, %08x}, got {%08x, %08x}",
    00894                   _date, _date_fract, sync_state[0], sync_state[1], _random.state[0], _random.state[1]);
    00895             NOT_REACHED();
    00896           }
    00897           check_sync_state = false;
    00898         }
    00899       }
    00900
    00901       if (cp != NULL || check_sync_state) break;
    00902
    00903       char buff[4096];
    00904       if (fgets(buff, lengthof(buff), f) == NULL) break;
    00905
    00906       char *p = buff;
    00907       /* Ignore the "[date time] " part of the message */
    00908       if (*p == '[') {
    00909         p = strchr(p, ']');
    00910         if (p == NULL) break;
    00911         p += 2;
    00912       }
    00913
    00914       if (strncmp(p, "cmd: ", 5) == 0) {
    00915         cp = CallocT<CommandPacket>(1);
    00916         int company;
    00917         int ret = sscanf(p + 5, "%x; %x; %x; %x; %x; %x; %x; \"%[^\"]\"", &next_date, &next_date_fract, &company, &cp->tile, &cp->p1, &cp->p2, &cp->cmd, cp->text);
    00918         /* There are 8 pieces of data to read, however the last is a
    00919          * string that might or might not exist. Ignore it if that
    00920          * string misses because in 99% of the time it's not used. */
    00921         assert(ret == 8 || ret == 7);
    00922         cp->company = (CompanyID)company;
    00923       } else if (strncmp(p, "join: ", 6) == 0) {
    00924         /* Manually insert a pause when joining; this way the client can join at the exact right time. */
    00925         int ret = sscanf(p + 6, "%x; %x", &next_date, &next_date_fract);
    00926         assert(ret == 2);
    00927         DEBUG(net, 0, "injecting pause for join at %08x:%02x; please join when paused", next_date, next_date_fract);
    00928         cp = CallocT<CommandPacket>(1);
    00929         cp->company = COMPANY_SPECTATOR;
    00930         cp->cmd = CMD_PAUSE;
    00931         cp->p1 = PM_PAUSED_NORMAL;
    00932         cp->p2 = 1;
    00933         _ddc_fastforward = false;
    00934       } else if (strncmp(p, "sync: ", 6) == 0) {
    00935         int ret = sscanf(p + 6, "%x; %x; %x; %x", &next_date, &next_date_fract, &sync_state[0], &sync_state[1]);
    00936         assert(ret == 4);
    00937         check_sync_state = true;
    00938       } else if (strncmp(p, "msg: ", 5) == 0 || strncmp(p, "client: ", 8) == 0 ||
    00939             strncmp(p, "load: ", 6) == 0 || strncmp(p, "save: ", 6) == 0) {
    00940         /* A message that is not very important to the log playback, but part of the log. */
    00941       } else {
    00942         /* Can't parse a line; what's wrong here? */
    00943         DEBUG(net, 0, "trying to parse: %s", p);
    00944         NOT_REACHED();
    00945       }
    00946     }
    00947     if (f != NULL && feof(f)) {
    00948       DEBUG(net, 0, "End of commands.log");
    00949       fclose(f);
    00950       f = NULL;
    00951     }
    00952 #endif /* DEBUG_DUMP_COMMANDS */
    00953     if (_frame_counter >= _frame_counter_max) {
    00954       /* Only check for active clients just before we're going to send out
    00955        * the commands so we don't send multiple pause/unpause commands when
    00956        * the frame_freq is more than 1 tick. Same with distributing commands. */
    00957       CheckPauseOnJoin();
    00958       CheckMinActiveClients();
    00959       NetworkDistributeCommands();
    00960     }
    00961
    00962     bool send_frame = false;
    00963
    00964     /* We first increase the _frame_counter */
    00965     _frame_counter++;
    00966     /* Update max-frame-counter */
    00967     if (_frame_counter > _frame_counter_max) {
    00968       _frame_counter_max = _frame_counter + _settings_client.network.frame_freq;
    00969       send_frame = true;
    00970     }
    00971
    00972     NetworkExecuteLocalCommandQueue();
    00973
    00974     /* Then we make the frame */
    00975     StateGameLoop();
    00976
    00977     _sync_seed_1 = _random.state[0];
    00978 #ifdef NETWORK_SEND_DOUBLE_SEED
    00979     _sync_seed_2 = _random.state[1];
    00980 #endif
    00981
    00982     NetworkServer_Tick(send_frame);
    00983   } else {
    00984     /* Client */
    00985
    00986     /* Make sure we are at the frame were the server is (quick-frames) */
    00987     if (_frame_counter_server > _frame_counter) {
    00988       /* Run a number of frames; when things go bad, get out. */
    00989       while (_frame_counter_server > _frame_counter) {
    00990         if (!ClientNetworkGameSocketHandler::GameLoop()) return;
    00991       }
    00992     } else {
    00993       /* Else, keep on going till _frame_counter_max */
    00994       if (_frame_counter_max > _frame_counter) {
    00995         /* Run one frame; if things went bad, get out. */
    00996         if (!ClientNetworkGameSocketHandler::GameLoop()) return;
    00997       }
    00998     }
    00999   }
    01000
    01001   NetworkSend();
    01002 }
    01003
    01004 static void NetworkGenerateServerId()
    01005 {
    01006   Md5 checksum;
    01007   uint8 digest[16];
    01008   char hex_output[16 * 2 + 1];
    01009   char coding_string[NETWORK_NAME_LENGTH];
    01010   int di;
    01011
    01012   snprintf(coding_string, sizeof(coding_string), "%d%s", (uint)Random(), "OpenTTD Server ID");
    01013
    01014   /* Generate the MD5 hash */
    01015   checksum.Append((const uint8*)coding_string, strlen(coding_string));
    01016   checksum.Finish(digest);
    01017
    01018   for (di = 0; di < 16; ++di) {
    01019     sprintf(hex_output + di * 2, "%02x", digest[di]);
    01020   }
    01021
    01022   /* _settings_client.network.network_id is our id */
    01023   snprintf(_settings_client.network.network_id, sizeof(_settings_client.network.network_id), "%s", hex_output);
    01024 }
    01025
    01026 void NetworkStartDebugLog(NetworkAddress address)
    01027 {
    01028   extern SOCKET _debug_socket;  // Comes from debug.c
    01029
    01030   DEBUG(net, 0, "Redirecting DEBUG() to %s:%d", address.GetHostname(), address.GetPort());
    01031
    01032   SOCKET s = address.Connect();
    01033   if (s == INVALID_SOCKET) {
    01034     DEBUG(net, 0, "Failed to open socket for redirection DEBUG()");
    01035     return;
    01036   }
    01037
    01038   _debug_socket = s;
    01039
    01040   DEBUG(net, 0, "DEBUG() is now redirected");
    01041 }
    01042
    01044 void NetworkStartUp()
    01045 {
    01046   DEBUG(net, 3, "[core] starting network...");
    01047
    01048   /* Network is available */
    01049   _network_available = NetworkCoreInitialize();
    01050   _network_dedicated = false;
    01051   _network_last_advertise_frame = 0;
    01052   _network_need_advertise = true;
    01053   _network_advertise_retries = 0;
    01054
    01055   /* Generate an server id when there is none yet */
    01056   if (StrEmpty(_settings_client.network.network_id)) NetworkGenerateServerId();
    01057
    01058   memset(&_network_game_info, 0, sizeof(_network_game_info));
    01059
    01060   NetworkInitialize();
    01061   DEBUG(net, 3, "[core] network online, multiplayer available");
    01062   NetworkFindBroadcastIPs(&_broadcast_list);
    01063 }
    01064
    01066 void NetworkShutDown()
    01067 {
    01068   NetworkDisconnect(true);
    01069   NetworkUDPClose();
    01070
    01071   DEBUG(net, 3, "[core] shutting down network");
    01072
    01073   _network_available = false;
    01074
    01075   NetworkCoreShutdown();
    01076 }
    01077
    01082 bool IsNetworkCompatibleVersion(const char *other)
    01083 {
    01084   return strncmp(_openttd_revision, other, NETWORK_REVISION_LENGTH - 1) == 0;
    01085 }
    01086
    01087 #endif /* ENABLE_NETWORK */