network.cpp

Go to the documentation of this file.
00001 /* $Id$ */
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 "table/strings.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   extern StringID _switch_mode_errorstr;
00291   _switch_mode_errorstr = error_string;
00292 }
00293 
00299 StringID GetNetworkErrorMsg(NetworkErrorCode err)
00300 {
00301   /* List of possible network errors, used by
00302    * PACKET_SERVER_ERROR and PACKET_CLIENT_ERROR */
00303   static const StringID network_error_strings[] = {
00304     STR_NETWORK_ERROR_CLIENT_GENERAL,
00305     STR_NETWORK_ERROR_CLIENT_DESYNC,
00306     STR_NETWORK_ERROR_CLIENT_SAVEGAME,
00307     STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST,
00308     STR_NETWORK_ERROR_CLIENT_PROTOCOL_ERROR,
00309     STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH,
00310     STR_NETWORK_ERROR_CLIENT_NOT_AUTHORIZED,
00311     STR_NETWORK_ERROR_CLIENT_NOT_EXPECTED,
00312     STR_NETWORK_ERROR_CLIENT_WRONG_REVISION,
00313     STR_NETWORK_ERROR_CLIENT_NAME_IN_USE,
00314     STR_NETWORK_ERROR_CLIENT_WRONG_PASSWORD,
00315     STR_NETWORK_ERROR_CLIENT_COMPANY_MISMATCH,
00316     STR_NETWORK_ERROR_CLIENT_KICKED,
00317     STR_NETWORK_ERROR_CLIENT_CHEATER,
00318     STR_NETWORK_ERROR_CLIENT_SERVER_FULL,
00319     STR_NETWORK_ERROR_CLIENT_TOO_MANY_COMMANDS
00320   };
00321 
00322   if (err >= (ptrdiff_t)lengthof(network_error_strings)) err = NETWORK_ERROR_GENERAL;
00323 
00324   return network_error_strings[err];
00325 }
00326 
00332 void NetworkHandlePauseChange(PauseMode prev_mode, PauseMode changed_mode)
00333 {
00334   if (!_networking) return;
00335 
00336   switch (changed_mode) {
00337     case PM_PAUSED_NORMAL:
00338     case PM_PAUSED_JOIN:
00339     case PM_PAUSED_ACTIVE_CLIENTS: {
00340       bool changed = ((_pause_mode == PM_UNPAUSED) != (prev_mode == PM_UNPAUSED));
00341       bool paused = (_pause_mode != PM_UNPAUSED);
00342       if (!paused && !changed) return;
00343 
00344       StringID str;
00345       if (!changed) {
00346         int i = -1;
00347         if ((_pause_mode & PM_PAUSED_NORMAL) != PM_UNPAUSED)         SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_MANUAL);
00348         if ((_pause_mode & PM_PAUSED_JOIN) != PM_UNPAUSED)           SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_CONNECTING_CLIENTS);
00349         if ((_pause_mode & PM_PAUSED_ACTIVE_CLIENTS) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_NOT_ENOUGH_PLAYERS);
00350         str = STR_NETWORK_SERVER_MESSAGE_GAME_STILL_PAUSED_1 + i;
00351       } else {
00352         switch (changed_mode) {
00353           case PM_PAUSED_NORMAL:         SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_MANUAL); break;
00354           case PM_PAUSED_JOIN:           SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_CONNECTING_CLIENTS); break;
00355           case PM_PAUSED_ACTIVE_CLIENTS: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_NOT_ENOUGH_PLAYERS); break;
00356           default: NOT_REACHED();
00357         }
00358         str = paused ? STR_NETWORK_SERVER_MESSAGE_GAME_PAUSED : STR_NETWORK_SERVER_MESSAGE_GAME_UNPAUSED;
00359       }
00360 
00361       char buffer[DRAW_STRING_BUFFER];
00362       GetString(buffer, str, lastof(buffer));
00363       NetworkTextMessage(NETWORK_ACTION_SERVER_MESSAGE, CC_DEFAULT, false, NULL, buffer);
00364       break;
00365     }
00366 
00367     default:
00368       return;
00369   }
00370 }
00371 
00372 
00381 static void CheckPauseHelper(bool pause, PauseMode pm)
00382 {
00383   if (pause == ((_pause_mode & pm) != PM_UNPAUSED)) return;
00384 
00385   DoCommandP(0, pm, pause ? 1 : 0, CMD_PAUSE);
00386 }
00387 
00393 static uint NetworkCountActiveClients()
00394 {
00395   const NetworkClientSocket *cs;
00396   uint count = 0;
00397 
00398   FOR_ALL_CLIENT_SOCKETS(cs) {
00399     if (cs->status != NetworkClientSocket::STATUS_ACTIVE) continue;
00400     if (!Company::IsValidID(cs->GetInfo()->client_playas)) continue;
00401     count++;
00402   }
00403 
00404   return count;
00405 }
00406 
00410 static void CheckMinActiveClients()
00411 {
00412   if ((_pause_mode & PM_PAUSED_ERROR) != PM_UNPAUSED ||
00413       !_network_dedicated ||
00414       (_settings_client.network.min_active_clients == 0 && (_pause_mode & PM_PAUSED_ACTIVE_CLIENTS) == PM_UNPAUSED)) {
00415     return;
00416   }
00417   CheckPauseHelper(NetworkCountActiveClients() < _settings_client.network.min_active_clients, PM_PAUSED_ACTIVE_CLIENTS);
00418 }
00419 
00424 static bool NetworkHasJoiningClient()
00425 {
00426   const NetworkClientSocket *cs;
00427   FOR_ALL_CLIENT_SOCKETS(cs) {
00428     if (cs->status >= NetworkClientSocket::STATUS_AUTHORIZED && cs->status < NetworkClientSocket::STATUS_ACTIVE) return true;
00429   }
00430 
00431   return false;
00432 }
00433 
00437 static void CheckPauseOnJoin()
00438 {
00439   if ((_pause_mode & PM_PAUSED_ERROR) != PM_UNPAUSED ||
00440       (!_settings_client.network.pause_on_join && (_pause_mode & PM_PAUSED_JOIN) == PM_UNPAUSED)) {
00441     return;
00442   }
00443   CheckPauseHelper(NetworkHasJoiningClient(), PM_PAUSED_JOIN);
00444 }
00445 
00454 void ParseConnectionString(const char **company, const char **port, char *connection_string)
00455 {
00456   bool ipv6 = (strchr(connection_string, ':') != strrchr(connection_string, ':'));
00457   char *p;
00458   for (p = connection_string; *p != '\0'; p++) {
00459     switch (*p) {
00460       case '[':
00461         ipv6 = true;
00462         break;
00463 
00464       case ']':
00465         ipv6 = false;
00466         break;
00467 
00468       case '#':
00469         *company = p + 1;
00470         *p = '\0';
00471         break;
00472 
00473       case ':':
00474         if (ipv6) break;
00475         *port = p + 1;
00476         *p = '\0';
00477         break;
00478     }
00479   }
00480 }
00481 
00487 /* static */ void ServerNetworkGameSocketHandler::AcceptConnection(SOCKET s, const NetworkAddress &address)
00488 {
00489   /* Register the login */
00490   _network_clients_connected++;
00491 
00492   SetWindowDirty(WC_CLIENT_LIST, 0);
00493   ServerNetworkGameSocketHandler *cs = new ServerNetworkGameSocketHandler(s);
00494   cs->client_address = address; // Save the IP of the client
00495 }
00496 
00501 static void InitializeNetworkPools(bool close_admins = true)
00502 {
00503   PoolBase::Clean(PT_NCLIENT | (close_admins ? PT_NADMIN : PT_NONE));
00504 }
00505 
00510 void NetworkClose(bool close_admins)
00511 {
00512   if (_network_server) {
00513     if (close_admins) {
00514       ServerNetworkAdminSocketHandler *as;
00515       FOR_ALL_ADMIN_SOCKETS(as) {
00516         as->CloseConnection(true);
00517       }
00518     }
00519 
00520     NetworkClientSocket *cs;
00521     FOR_ALL_CLIENT_SOCKETS(cs) {
00522       cs->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
00523     }
00524     ServerNetworkGameSocketHandler::CloseListeners();
00525     ServerNetworkAdminSocketHandler::CloseListeners();
00526   } else if (MyClient::my_client != NULL) {
00527     MyClient::SendQuit();
00528     MyClient::my_client->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
00529   }
00530 
00531   TCPConnecter::KillAll();
00532 
00533   _networking = false;
00534   _network_server = false;
00535 
00536   NetworkFreeLocalCommandQueue();
00537 
00538   free(_network_company_states);
00539   _network_company_states = NULL;
00540 
00541   InitializeNetworkPools(close_admins);
00542 }
00543 
00544 /* Inits the network (cleans sockets and stuff) */
00545 static void NetworkInitialize(bool close_admins = true)
00546 {
00547   InitializeNetworkPools(close_admins);
00548   NetworkUDPInitialize();
00549 
00550   _sync_frame = 0;
00551   _network_first_time = true;
00552 
00553   _network_reconnect = 0;
00554 }
00555 
00557 class TCPQueryConnecter : TCPConnecter {
00558 public:
00559   TCPQueryConnecter(const NetworkAddress &address) : TCPConnecter(address) {}
00560 
00561   virtual void OnFailure()
00562   {
00563     NetworkDisconnect();
00564   }
00565 
00566   virtual void OnConnect(SOCKET s)
00567   {
00568     _networking = true;
00569     new ClientNetworkGameSocketHandler(s);
00570     MyClient::SendCompanyInformationQuery();
00571   }
00572 };
00573 
00574 /* Query a server to fetch his game-info
00575  *  If game_info is true, only the gameinfo is fetched,
00576  *   else only the client_info is fetched */
00577 void NetworkTCPQueryServer(NetworkAddress address)
00578 {
00579   if (!_network_available) return;
00580 
00581   NetworkDisconnect();
00582   NetworkInitialize();
00583 
00584   new TCPQueryConnecter(address);
00585 }
00586 
00587 /* Validates an address entered as a string and adds the server to
00588  * the list. If you use this function, the games will be marked
00589  * as manually added. */
00590 void NetworkAddServer(const char *b)
00591 {
00592   if (*b != '\0') {
00593     const char *port = NULL;
00594     const char *company = NULL;
00595     char host[NETWORK_HOSTNAME_LENGTH];
00596     uint16 rport;
00597 
00598     strecpy(host, b, lastof(host));
00599 
00600     strecpy(_settings_client.network.connect_to_ip, b, lastof(_settings_client.network.connect_to_ip));
00601     rport = NETWORK_DEFAULT_PORT;
00602 
00603     ParseConnectionString(&company, &port, host);
00604     if (port != NULL) rport = atoi(port);
00605 
00606     NetworkUDPQueryServer(NetworkAddress(host, rport), true);
00607   }
00608 }
00609 
00615 void GetBindAddresses(NetworkAddressList *addresses, uint16 port)
00616 {
00617   for (char **iter = _network_bind_list.Begin(); iter != _network_bind_list.End(); iter++) {
00618     *addresses->Append() = NetworkAddress(*iter, port);
00619   }
00620 
00621   /* No address, so bind to everything. */
00622   if (addresses->Length() == 0) {
00623     *addresses->Append() = NetworkAddress("", port);
00624   }
00625 }
00626 
00627 /* Generates the list of manually added hosts from NetworkGameList and
00628  * dumps them into the array _network_host_list. This array is needed
00629  * by the function that generates the config file. */
00630 void NetworkRebuildHostList()
00631 {
00632   _network_host_list.Clear();
00633 
00634   for (NetworkGameList *item = _network_game_list; item != NULL; item = item->next) {
00635     if (item->manually) *_network_host_list.Append() = strdup(item->address.GetAddressAsString(false));
00636   }
00637 }
00638 
00640 class TCPClientConnecter : TCPConnecter {
00641 public:
00642   TCPClientConnecter(const NetworkAddress &address) : TCPConnecter(address) {}
00643 
00644   virtual void OnFailure()
00645   {
00646     NetworkError(STR_NETWORK_ERROR_NOCONNECTION);
00647   }
00648 
00649   virtual void OnConnect(SOCKET s)
00650   {
00651     _networking = true;
00652     new ClientNetworkGameSocketHandler(s);
00653     IConsoleCmdExec("exec scripts/on_client.scr 0");
00654     NetworkClient_Connected();
00655   }
00656 };
00657 
00658 
00659 /* Used by clients, to connect to a server */
00660 void NetworkClientConnectGame(NetworkAddress address, CompanyID join_as, const char *join_server_password, const char *join_company_password)
00661 {
00662   if (!_network_available) return;
00663 
00664   if (address.GetPort() == 0) return;
00665 
00666   strecpy(_settings_client.network.last_host, address.GetHostname(), lastof(_settings_client.network.last_host));
00667   _settings_client.network.last_port = address.GetPort();
00668   _network_join_as = join_as;
00669   _network_join_server_password = join_server_password;
00670   _network_join_company_password = join_company_password;
00671 
00672   NetworkDisconnect();
00673   NetworkInitialize();
00674 
00675   _network_join_status = NETWORK_JOIN_STATUS_CONNECTING;
00676   ShowJoinStatusWindow();
00677 
00678   new TCPClientConnecter(address);
00679 }
00680 
00681 static void NetworkInitGameInfo()
00682 {
00683   if (StrEmpty(_settings_client.network.server_name)) {
00684     snprintf(_settings_client.network.server_name, sizeof(_settings_client.network.server_name), "Unnamed Server");
00685   }
00686 
00687   /* The server is a client too */
00688   _network_game_info.clients_on = _network_dedicated ? 0 : 1;
00689 
00690   /* There should be always space for the server. */
00691   assert(NetworkClientInfo::CanAllocateItem());
00692   NetworkClientInfo *ci = new NetworkClientInfo(CLIENT_ID_SERVER);
00693   ci->client_playas = _network_dedicated ? COMPANY_SPECTATOR : _local_company;
00694 
00695   strecpy(ci->client_name, _settings_client.network.client_name, lastof(ci->client_name));
00696 }
00697 
00698 bool NetworkServerStart()
00699 {
00700   if (!_network_available) return false;
00701 
00702   /* Call the pre-scripts */
00703   IConsoleCmdExec("exec scripts/pre_server.scr 0");
00704   if (_network_dedicated) IConsoleCmdExec("exec scripts/pre_dedicated.scr 0");
00705 
00706   NetworkDisconnect(false, false);
00707   NetworkInitialize(false);
00708   if (!ServerNetworkGameSocketHandler::Listen(_settings_client.network.server_port)) return false;
00709 
00710   /* Only listen for admins when the password isn't empty. */
00711   if (!StrEmpty(_settings_client.network.admin_password) && !ServerNetworkAdminSocketHandler::Listen(_settings_client.network.server_admin_port)) return false;
00712 
00713   /* Try to start UDP-server */
00714   _network_udp_server = _udp_server_socket->Listen();
00715 
00716   _network_company_states = CallocT<NetworkCompanyState>(MAX_COMPANIES);
00717   _network_server = true;
00718   _networking = true;
00719   _frame_counter = 0;
00720   _frame_counter_server = 0;
00721   _frame_counter_max = 0;
00722   _last_sync_frame = 0;
00723   _network_own_client_id = CLIENT_ID_SERVER;
00724 
00725   _network_clients_connected = 0;
00726   _network_company_passworded = 0;
00727 
00728   NetworkInitGameInfo();
00729 
00730   /* execute server initialization script */
00731   IConsoleCmdExec("exec scripts/on_server.scr 0");
00732   /* if the server is dedicated ... add some other script */
00733   if (_network_dedicated) IConsoleCmdExec("exec scripts/on_dedicated.scr 0");
00734 
00735   /* Try to register us to the master server */
00736   _network_last_advertise_frame = 0;
00737   _network_need_advertise = true;
00738   NetworkUDPAdvertise();
00739 
00740   /* welcome possibly still connected admins - this can only happen on a dedicated server. */
00741   if (_network_dedicated) ServerNetworkAdminSocketHandler::WelcomeAll();
00742 
00743   return true;
00744 }
00745 
00746 /* The server is rebooting...
00747  * The only difference with NetworkDisconnect, is the packets that is sent */
00748 void NetworkReboot()
00749 {
00750   if (_network_server) {
00751     NetworkClientSocket *cs;
00752     FOR_ALL_CLIENT_SOCKETS(cs) {
00753       cs->SendNewGame();
00754       cs->SendPackets();
00755     }
00756 
00757     ServerNetworkAdminSocketHandler *as;
00758     FOR_ALL_ACTIVE_ADMIN_SOCKETS(as) {
00759       as->SendNewGame();
00760       as->SendPackets();
00761     }
00762   }
00763 
00764   /* For non-dedicated servers we have to kick the admins as we are not
00765    * certain that we will end up in a new network game. */
00766   NetworkClose(!_network_dedicated);
00767 }
00768 
00774 void NetworkDisconnect(bool blocking, bool close_admins)
00775 {
00776   if (_network_server) {
00777     NetworkClientSocket *cs;
00778     FOR_ALL_CLIENT_SOCKETS(cs) {
00779       cs->SendShutdown();
00780       cs->SendPackets();
00781     }
00782 
00783     if (close_admins) {
00784       ServerNetworkAdminSocketHandler *as;
00785       FOR_ALL_ACTIVE_ADMIN_SOCKETS(as) {
00786         as->SendShutdown();
00787         as->SendPackets();
00788       }
00789     }
00790   }
00791 
00792   if (_settings_client.network.server_advertise) NetworkUDPRemoveAdvertise(blocking);
00793 
00794   DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
00795 
00796   NetworkClose(close_admins);
00797 
00798   /* Reinitialize the UDP stack, i.e. close all existing connections. */
00799   NetworkUDPInitialize();
00800 }
00801 
00806 static bool NetworkReceive()
00807 {
00808   if (_network_server) {
00809     ServerNetworkAdminSocketHandler::Receive();
00810     return ServerNetworkGameSocketHandler::Receive();
00811   } else {
00812     return ClientNetworkGameSocketHandler::Receive();
00813   }
00814 }
00815 
00816 /* This sends all buffered commands (if possible) */
00817 static void NetworkSend()
00818 {
00819   if (_network_server) {
00820     ServerNetworkAdminSocketHandler::Send();
00821     ServerNetworkGameSocketHandler::Send();
00822   } else {
00823     ClientNetworkGameSocketHandler::Send();
00824   }
00825 }
00826 
00827 /* We have to do some UDP checking */
00828 void NetworkUDPGameLoop()
00829 {
00830   _network_content_client.SendReceive();
00831   TCPConnecter::CheckCallbacks();
00832   NetworkHTTPSocketHandler::HTTPReceive();
00833 
00834   if (_network_udp_server) {
00835     _udp_server_socket->ReceivePackets();
00836     _udp_master_socket->ReceivePackets();
00837   } else {
00838     _udp_client_socket->ReceivePackets();
00839     if (_network_udp_broadcast > 0) _network_udp_broadcast--;
00840   }
00841 }
00842 
00843 /* The main loop called from ttd.c
00844  *  Here we also have to do StateGameLoop if needed! */
00845 void NetworkGameLoop()
00846 {
00847   if (!_networking) return;
00848 
00849   if (!NetworkReceive()) return;
00850 
00851   if (_network_server) {
00852     /* Log the sync state to check for in-syncedness of replays. */
00853     if (_date_fract == 0) {
00854       /* We don't want to log multiple times if paused. */
00855       static Date last_log;
00856       if (last_log != _date) {
00857         DEBUG(desync, 1, "sync: %08x; %02x; %08x; %08x", _date, _date_fract, _random.state[0], _random.state[1]);
00858         last_log = _date;
00859       }
00860     }
00861 
00862 #ifdef DEBUG_DUMP_COMMANDS
00863     /* Loading of the debug commands from -ddesync>=1 */
00864     static FILE *f = FioFOpenFile("commands.log", "rb", SAVE_DIR);
00865     static Date next_date = 0;
00866     static uint32 next_date_fract;
00867     static CommandPacket *cp = NULL;
00868     static bool check_sync_state = false;
00869     static uint32 sync_state[2];
00870     if (f == NULL && next_date == 0) {
00871       DEBUG(net, 0, "Cannot open commands.log");
00872       next_date = 1;
00873     }
00874 
00875     while (f != NULL && !feof(f)) {
00876       if (_date == next_date && _date_fract == next_date_fract) {
00877         if (cp != NULL) {
00878           NetworkSendCommand(cp->tile, cp->p1, cp->p2, cp->cmd & ~CMD_FLAGS_MASK, NULL, cp->text, cp->company);
00879           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));
00880           free(cp);
00881           cp = NULL;
00882         }
00883         if (check_sync_state) {
00884           if (sync_state[0] == _random.state[0] && sync_state[1] == _random.state[1]) {
00885             DEBUG(net, 0, "sync check: %08x; %02x; match", _date, _date_fract);
00886           } else {
00887             DEBUG(net, 0, "sync check: %08x; %02x; mismatch expected {%08x, %08x}, got {%08x, %08x}",
00888                   _date, _date_fract, sync_state[0], sync_state[1], _random.state[0], _random.state[1]);
00889             NOT_REACHED();
00890           }
00891           check_sync_state = false;
00892         }
00893       }
00894 
00895       if (cp != NULL || check_sync_state) break;
00896 
00897       char buff[4096];
00898       if (fgets(buff, lengthof(buff), f) == NULL) break;
00899 
00900       char *p = buff;
00901       /* Ignore the "[date time] " part of the message */
00902       if (*p == '[') {
00903         p = strchr(p, ']');
00904         if (p == NULL) break;
00905         p += 2;
00906       }
00907 
00908       if (strncmp(p, "cmd: ", 5) == 0) {
00909         cp = CallocT<CommandPacket>(1);
00910         int company;
00911         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);
00912         /* There are 8 pieces of data to read, however the last is a
00913          * string that might or might not exist. Ignore it if that
00914          * string misses because in 99% of the time it's not used. */
00915         assert(ret == 8 || ret == 7);
00916         cp->company = (CompanyID)company;
00917       } else if (strncmp(p, "join: ", 6) == 0) {
00918         /* Manually insert a pause when joining; this way the client can join at the exact right time. */
00919         int ret = sscanf(p + 6, "%x; %x", &next_date, &next_date_fract);
00920         assert(ret == 2);
00921         DEBUG(net, 0, "injecting pause for join at %08x:%02x; please join when paused", next_date, next_date_fract);
00922         cp = CallocT<CommandPacket>(1);
00923         cp->company = COMPANY_SPECTATOR;
00924         cp->cmd = CMD_PAUSE;
00925         cp->p1 = PM_PAUSED_NORMAL;
00926         cp->p2 = 1;
00927         _ddc_fastforward = false;
00928       } else if (strncmp(p, "sync: ", 6) == 0) {
00929         int ret = sscanf(p + 6, "%x; %x; %x; %x", &next_date, &next_date_fract, &sync_state[0], &sync_state[1]);
00930         assert(ret == 4);
00931         check_sync_state = true;
00932       } else if (strncmp(p, "msg: ", 5) == 0 || strncmp(p, "client: ", 8) == 0 ||
00933             strncmp(p, "load: ", 6) == 0 || strncmp(p, "save: ", 6) == 0) {
00934         /* A message that is not very important to the log playback, but part of the log. */
00935       } else {
00936         /* Can't parse a line; what's wrong here? */
00937         DEBUG(net, 0, "trying to parse: %s", p);
00938         NOT_REACHED();
00939       }
00940     }
00941     if (f != NULL && feof(f)) {
00942       DEBUG(net, 0, "End of commands.log");
00943       fclose(f);
00944       f = NULL;
00945     }
00946 #endif /* DEBUG_DUMP_COMMANDS */
00947     if (_frame_counter >= _frame_counter_max) {
00948       /* Only check for active clients just before we're going to send out
00949        * the commands so we don't send multiple pause/unpause commands when
00950        * the frame_freq is more than 1 tick. Same with distributing commands. */
00951       CheckPauseOnJoin();
00952       CheckMinActiveClients();
00953       NetworkDistributeCommands();
00954     }
00955 
00956     bool send_frame = false;
00957 
00958     /* We first increase the _frame_counter */
00959     _frame_counter++;
00960     /* Update max-frame-counter */
00961     if (_frame_counter > _frame_counter_max) {
00962       _frame_counter_max = _frame_counter + _settings_client.network.frame_freq;
00963       send_frame = true;
00964     }
00965 
00966     NetworkExecuteLocalCommandQueue();
00967 
00968     /* Then we make the frame */
00969     StateGameLoop();
00970 
00971     _sync_seed_1 = _random.state[0];
00972 #ifdef NETWORK_SEND_DOUBLE_SEED
00973     _sync_seed_2 = _random.state[1];
00974 #endif
00975 
00976     NetworkServer_Tick(send_frame);
00977   } else {
00978     /* Client */
00979 
00980     /* Make sure we are at the frame were the server is (quick-frames) */
00981     if (_frame_counter_server > _frame_counter) {
00982       /* Run a number of frames; when things go bad, get out. */
00983       while (_frame_counter_server > _frame_counter) {
00984         if (!ClientNetworkGameSocketHandler::GameLoop()) return;
00985       }
00986     } else {
00987       /* Else, keep on going till _frame_counter_max */
00988       if (_frame_counter_max > _frame_counter) {
00989         /* Run one frame; if things went bad, get out. */
00990         if (!ClientNetworkGameSocketHandler::GameLoop()) return;
00991       }
00992     }
00993   }
00994 
00995   NetworkSend();
00996 }
00997 
00998 static void NetworkGenerateServerId()
00999 {
01000   Md5 checksum;
01001   uint8 digest[16];
01002   char hex_output[16 * 2 + 1];
01003   char coding_string[NETWORK_NAME_LENGTH];
01004   int di;
01005 
01006   snprintf(coding_string, sizeof(coding_string), "%d%s", (uint)Random(), "OpenTTD Server ID");
01007 
01008   /* Generate the MD5 hash */
01009   checksum.Append((const uint8*)coding_string, strlen(coding_string));
01010   checksum.Finish(digest);
01011 
01012   for (di = 0; di < 16; ++di) {
01013     sprintf(hex_output + di * 2, "%02x", digest[di]);
01014   }
01015 
01016   /* _settings_client.network.network_id is our id */
01017   snprintf(_settings_client.network.network_id, sizeof(_settings_client.network.network_id), "%s", hex_output);
01018 }
01019 
01020 void NetworkStartDebugLog(NetworkAddress address)
01021 {
01022   extern SOCKET _debug_socket;  // Comes from debug.c
01023 
01024   DEBUG(net, 0, "Redirecting DEBUG() to %s:%d", address.GetHostname(), address.GetPort());
01025 
01026   SOCKET s = address.Connect();
01027   if (s == INVALID_SOCKET) {
01028     DEBUG(net, 0, "Failed to open socket for redirection DEBUG()");
01029     return;
01030   }
01031 
01032   _debug_socket = s;
01033 
01034   DEBUG(net, 0, "DEBUG() is now redirected");
01035 }
01036 
01038 void NetworkStartUp()
01039 {
01040   DEBUG(net, 3, "[core] starting network...");
01041 
01042   /* Network is available */
01043   _network_available = NetworkCoreInitialize();
01044   _network_dedicated = false;
01045   _network_last_advertise_frame = 0;
01046   _network_need_advertise = true;
01047   _network_advertise_retries = 0;
01048 
01049   /* Generate an server id when there is none yet */
01050   if (StrEmpty(_settings_client.network.network_id)) NetworkGenerateServerId();
01051 
01052   memset(&_network_game_info, 0, sizeof(_network_game_info));
01053 
01054   NetworkInitialize();
01055   DEBUG(net, 3, "[core] network online, multiplayer available");
01056   NetworkFindBroadcastIPs(&_broadcast_list);
01057 }
01058 
01060 void NetworkShutDown()
01061 {
01062   NetworkDisconnect(true);
01063   NetworkUDPClose();
01064 
01065   DEBUG(net, 3, "[core] shutting down network");
01066 
01067   _network_available = false;
01068 
01069   NetworkCoreShutdown();
01070 }
01071 
01076 bool IsNetworkCompatibleVersion(const char *other)
01077 {
01078   return strncmp(_openttd_revision, other, NETWORK_REVISION_LENGTH - 1) == 0;
01079 }
01080 
01081 #endif /* ENABLE_NETWORK */