Fix old map array tunnel head conversion
[openttd/fttd.git] / src / network / network.cpp
blob551d10b1c83da294d85b6b12c0f9603aba8eadbb
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file network.cpp Base functions for networking support. */
12 #include "../stdafx.h"
14 #ifdef ENABLE_NETWORK
16 #include "../string.h"
17 #include "../strings_func.h"
18 #include "../command_func.h"
19 #include "../date_func.h"
20 #include "network_admin.h"
21 #include "network_client.h"
22 #include "network_server.h"
23 #include "network_content.h"
24 #include "network_udp.h"
25 #include "network_gamelist.h"
26 #include "network_base.h"
27 #include "core/udp.h"
28 #include "core/host.h"
29 #include "network_gui.h"
30 #include "../console_func.h"
31 #include "../3rdparty/md5/md5.h"
32 #include "../core/random_func.hpp"
33 #include "../window_func.h"
34 #include "../company_func.h"
35 #include "../company_base.h"
36 #include "../landscape_type.h"
37 #include "../rev.h"
38 #include "../core/pool_func.hpp"
39 #include "../gfx_func.h"
40 #include "../error.h"
42 #ifdef DEBUG_DUMP_COMMANDS
43 #include "../fileio_func.h"
44 /** When running the server till the wait point, run as fast as we can! */
45 bool _ddc_fastforward = true;
46 #endif /* DEBUG_DUMP_COMMANDS */
48 /** Make sure both pools have the same size. */
49 assert_compile(NetworkClientInfo::Pool::MAX_SIZE == NetworkClientSocket::Pool::MAX_SIZE);
51 /** The pool with client information. */
52 template<> NetworkClientInfo::Pool NetworkClientInfo::PoolItem::pool ("NetworkClientInfo");
53 INSTANTIATE_POOL_METHODS(NetworkClientInfo)
55 bool _networking; ///< are we in networking mode?
56 bool _network_server; ///< network-server is active
57 bool _network_available; ///< is network mode available?
58 bool _network_dedicated; ///< are we a dedicated server?
59 bool _is_network_server; ///< Does this client wants to be a network-server?
60 NetworkServerGameInfo _network_game_info; ///< Information about our game.
61 NetworkCompanyState *_network_company_states = NULL; ///< Statistics about some companies.
62 ClientID _network_own_client_id; ///< Our client identifier.
63 ClientID _redirect_console_to_client; ///< If not invalid, redirect the console output to a client.
64 bool _network_need_advertise; ///< Whether we need to advertise.
65 uint8 _network_reconnect; ///< Reconnect timeout
66 StringList _network_bind_list; ///< The addresses to bind on.
67 StringList _network_host_list; ///< The servers we know.
68 StringList _network_ban_list; ///< The banned clients.
69 uint32 _frame_counter_server; ///< The frame_counter of the server, if in network-mode
70 uint32 _frame_counter_max; ///< To where we may go with our clients
71 uint32 _frame_counter; ///< The current frame.
72 uint32 _last_sync_frame; ///< Used in the server to store the last time a sync packet was sent to clients.
73 NetworkAddressList _broadcast_list; ///< List of broadcast addresses.
74 uint32 _sync_seed_1; ///< Seed to compare during sync checks.
75 #ifdef NETWORK_SEND_DOUBLE_SEED
76 uint32 _sync_seed_2; ///< Second part of the seed.
77 #endif
78 uint32 _sync_frame; ///< The frame to perform the sync check.
79 bool _network_first_time; ///< Whether we have finished joining or not.
80 bool _network_udp_server; ///< Is the UDP server started?
81 uint16 _network_udp_broadcast; ///< Timeout for the UDP broadcasts.
82 uint8 _network_advertise_retries; ///< The number of advertisement retries we did.
83 CompanyMask _network_company_passworded; ///< Bitmask of the password status of all companies.
85 /* Check whether NETWORK_NUM_LANDSCAPES is still in sync with NUM_LANDSCAPE */
86 assert_compile((int)NETWORK_NUM_LANDSCAPES == (int)NUM_LANDSCAPE);
87 assert_compile((int)NETWORK_COMPANY_NAME_LENGTH == MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH);
89 extern NetworkUDPSocketHandler *_udp_client_socket; ///< udp client socket
90 extern NetworkUDPSocketHandler *_udp_server_socket; ///< udp server socket
91 extern NetworkUDPSocketHandler *_udp_master_socket; ///< udp master socket
93 /** The amount of clients connected */
94 byte _network_clients_connected = 0;
96 /* Some externs / forwards */
97 extern void StateGameLoop();
99 /**
100 * Return whether there is any client connected or trying to connect at all.
101 * @return whether we have any client activity
103 bool HasClients()
105 NetworkClientSocket *cs;
106 FOR_ALL_CLIENT_SOCKETS(cs) return true;
108 return false;
112 * Basically a client is leaving us right now.
114 NetworkClientInfo::~NetworkClientInfo()
116 /* Delete the chat window, if you were chatting with this client. */
117 InvalidateWindowData(WC_SEND_NETWORK_MSG, DESTTYPE_CLIENT, this->client_id);
121 * Return the CI given it's client-identifier
122 * @param client_id the ClientID to search for
123 * @return return a pointer to the corresponding NetworkClientInfo struct or NULL when not found
125 /* static */ NetworkClientInfo *NetworkClientInfo::GetByClientID(ClientID client_id)
127 NetworkClientInfo *ci;
129 FOR_ALL_CLIENT_INFOS(ci) {
130 if (ci->client_id == client_id) return ci;
133 return NULL;
137 * Return the client state given it's client-identifier
138 * @param client_id the ClientID to search for
139 * @return return a pointer to the corresponding NetworkClientSocket struct or NULL when not found
141 /* static */ ServerNetworkGameSocketHandler *ServerNetworkGameSocketHandler::GetByClientID(ClientID client_id)
143 NetworkClientSocket *cs;
145 FOR_ALL_CLIENT_SOCKETS(cs) {
146 if (cs->client_id == client_id) return cs;
149 return NULL;
152 byte NetworkSpectatorCount()
154 const NetworkClientInfo *ci;
155 byte count = 0;
157 FOR_ALL_CLIENT_INFOS(ci) {
158 if (ci->client_playas == COMPANY_SPECTATOR) count++;
161 /* Don't count a dedicated server as spectator */
162 if (_network_dedicated) count--;
164 return count;
168 * Change the company password of a given company.
169 * @param company_id ID of the company the password should be changed for.
170 * @param password The unhashed password we like to set ('*' or '' resets the password)
171 * @return The password.
173 const char *NetworkChangeCompanyPassword(CompanyID company_id, const char *password)
175 if (strcmp(password, "*") == 0) password = "";
177 if (_network_server) {
178 NetworkServerSetCompanyPassword(company_id, password, false);
179 } else {
180 NetworkClientSetCompanyPassword(password);
183 return password;
187 * Hash the given password using server ID and game seed.
188 * @param password Password to hash.
189 * @param password_server_id Server ID.
190 * @param password_game_seed Game seed.
191 * @return The hashed password.
193 const char *GenerateCompanyPasswordHash(const char *password, const char *password_server_id, uint32 password_game_seed)
195 if (StrEmpty(password)) return password;
197 char salted_password[NETWORK_SERVER_ID_LENGTH];
199 memset(salted_password, 0, sizeof(salted_password));
200 snprintf(salted_password, sizeof(salted_password), "%s", password);
201 /* Add the game seed and the server's ID as the salt. */
202 for (uint i = 0; i < NETWORK_SERVER_ID_LENGTH - 1; i++) {
203 salted_password[i] ^= password_server_id[i] ^ (password_game_seed >> (i % 32));
206 Md5 checksum;
207 uint8 digest[16];
208 static char hashed_password[NETWORK_SERVER_ID_LENGTH];
210 /* Generate the MD5 hash */
211 checksum.Append(salted_password, sizeof(salted_password) - 1);
212 checksum.Finish(digest);
214 for (int di = 0; di < 16; di++) sprintf(hashed_password + di * 2, "%02x", digest[di]);
215 hashed_password[lengthof(hashed_password) - 1] = '\0';
217 return hashed_password;
221 * Check if the company we want to join requires a password.
222 * @param company_id id of the company we want to check the 'passworded' flag for.
223 * @return true if the company requires a password.
225 bool NetworkCompanyIsPassworded(CompanyID company_id)
227 return HasBit(_network_company_passworded, company_id);
230 /* This puts a text-message to the console, or in the future, the chat-box,
231 * (to keep it all a bit more general)
232 * If 'self_send' is true, this is the client who is sending the message */
233 void NetworkTextMessage(NetworkAction action, TextColour colour, bool self_send, const char *name, const char *str, int64 data)
235 StringID strid;
236 switch (action) {
237 case NETWORK_ACTION_SERVER_MESSAGE:
238 /* Ignore invalid messages */
239 strid = STR_NETWORK_SERVER_MESSAGE;
240 colour = CC_DEFAULT;
241 break;
242 case NETWORK_ACTION_COMPANY_SPECTATOR:
243 colour = CC_DEFAULT;
244 strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_SPECTATE;
245 break;
246 case NETWORK_ACTION_COMPANY_JOIN:
247 colour = CC_DEFAULT;
248 strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_JOIN;
249 break;
250 case NETWORK_ACTION_COMPANY_NEW:
251 colour = CC_DEFAULT;
252 strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_NEW;
253 break;
254 case NETWORK_ACTION_JOIN:
255 /* Show the Client ID for the server but not for the client. */
256 strid = _network_server ? STR_NETWORK_MESSAGE_CLIENT_JOINED_ID : STR_NETWORK_MESSAGE_CLIENT_JOINED;
257 break;
258 case NETWORK_ACTION_LEAVE: strid = STR_NETWORK_MESSAGE_CLIENT_LEFT; break;
259 case NETWORK_ACTION_NAME_CHANGE: strid = STR_NETWORK_MESSAGE_NAME_CHANGE; break;
260 case NETWORK_ACTION_GIVE_MONEY: strid = self_send ? STR_NETWORK_MESSAGE_GAVE_MONEY_AWAY : STR_NETWORK_MESSAGE_GIVE_MONEY; break;
261 case NETWORK_ACTION_CHAT_COMPANY: strid = self_send ? STR_NETWORK_CHAT_TO_COMPANY : STR_NETWORK_CHAT_COMPANY; break;
262 case NETWORK_ACTION_CHAT_CLIENT: strid = self_send ? STR_NETWORK_CHAT_TO_CLIENT : STR_NETWORK_CHAT_CLIENT; break;
263 default: strid = STR_NETWORK_CHAT_ALL; break;
266 sstring<1024> message;
267 SetDParamStr(0, name);
268 SetDParamStr(1, str);
269 SetDParam(2, data);
271 /* All of these strings start with "***". These characters are interpreted as both left-to-right and
272 * right-to-left characters depending on the context. As the next text might be an user's name, the
273 * user name's characters will influence the direction of the "***" instead of the language setting
274 * of the game. Manually set the direction of the "***" by inserting a text-direction marker. */
275 message.append_utf8 (_current_text_dir == TD_LTR ? CHAR_TD_LRM : CHAR_TD_RLM);
276 AppendString (&message, strid);
278 DEBUG (desync, 1, "msg: %08x.%02x %s", _date, _date_fract, message.c_str());
279 IConsolePrintF(colour, "%s", message.c_str());
280 NetworkAddChatMessage((TextColour)colour, _settings_client.gui.network_chat_timeout, "%s", message.c_str());
283 /* Calculate the frame-lag of a client */
284 uint NetworkCalculateLag(const NetworkClientSocket *cs)
286 int lag = cs->last_frame_server - cs->last_frame;
287 /* This client has missed his ACK packet after 1 DAY_TICKS..
288 * so we increase his lag for every frame that passes!
289 * The packet can be out by a max of _net_frame_freq */
290 if (cs->last_frame_server + DAY_TICKS + _settings_client.network.frame_freq < _frame_counter) {
291 lag += _frame_counter - (cs->last_frame_server + DAY_TICKS + _settings_client.network.frame_freq);
293 return lag;
297 /* There was a non-recoverable error, drop back to the main menu with a nice
298 * error */
299 void NetworkError(StringID error_string)
301 _switch_mode = SM_MENU;
302 ShowErrorMessage(error_string, INVALID_STRING_ID, WL_CRITICAL);
306 * Retrieve the string id of an internal error number
307 * @param err NetworkErrorCode
308 * @return the StringID
310 StringID GetNetworkErrorMsg(NetworkErrorCode err)
312 /* List of possible network errors, used by
313 * PACKET_SERVER_ERROR and PACKET_CLIENT_ERROR */
314 static const StringID network_error_strings[] = {
315 STR_NETWORK_ERROR_CLIENT_GENERAL,
316 STR_NETWORK_ERROR_CLIENT_DESYNC,
317 STR_NETWORK_ERROR_CLIENT_SAVEGAME,
318 STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST,
319 STR_NETWORK_ERROR_CLIENT_PROTOCOL_ERROR,
320 STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH,
321 STR_NETWORK_ERROR_CLIENT_NOT_AUTHORIZED,
322 STR_NETWORK_ERROR_CLIENT_NOT_EXPECTED,
323 STR_NETWORK_ERROR_CLIENT_WRONG_REVISION,
324 STR_NETWORK_ERROR_CLIENT_NAME_IN_USE,
325 STR_NETWORK_ERROR_CLIENT_WRONG_PASSWORD,
326 STR_NETWORK_ERROR_CLIENT_COMPANY_MISMATCH,
327 STR_NETWORK_ERROR_CLIENT_KICKED,
328 STR_NETWORK_ERROR_CLIENT_CHEATER,
329 STR_NETWORK_ERROR_CLIENT_SERVER_FULL,
330 STR_NETWORK_ERROR_CLIENT_TOO_MANY_COMMANDS,
331 STR_NETWORK_ERROR_CLIENT_TIMEOUT_PASSWORD,
332 STR_NETWORK_ERROR_CLIENT_TIMEOUT_COMPUTER,
333 STR_NETWORK_ERROR_CLIENT_TIMEOUT_MAP,
334 STR_NETWORK_ERROR_CLIENT_TIMEOUT_JOIN,
336 assert_compile(lengthof(network_error_strings) == NETWORK_ERROR_END);
338 if (err >= (ptrdiff_t)lengthof(network_error_strings)) err = NETWORK_ERROR_GENERAL;
340 return network_error_strings[err];
344 * Handle the pause mode change so we send the right messages to the chat.
345 * @param prev_mode The previous pause mode.
346 * @param changed_mode The pause mode that got changed.
348 void NetworkHandlePauseChange(PauseMode prev_mode, PauseMode changed_mode)
350 if (!_networking) return;
352 switch (changed_mode) {
353 case PM_PAUSED_NORMAL:
354 case PM_PAUSED_JOIN:
355 case PM_PAUSED_GAME_SCRIPT:
356 case PM_PAUSED_ACTIVE_CLIENTS: {
357 bool changed = ((_pause_mode == PM_UNPAUSED) != (prev_mode == PM_UNPAUSED));
358 bool paused = (_pause_mode != PM_UNPAUSED);
359 if (!paused && !changed) return;
361 StringID str;
362 if (!changed) {
363 int i = -1;
365 if ((_pause_mode & PM_PAUSED_NORMAL) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_MANUAL);
366 if ((_pause_mode & PM_PAUSED_JOIN) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_CONNECTING_CLIENTS);
367 if ((_pause_mode & PM_PAUSED_GAME_SCRIPT) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_GAME_SCRIPT);
368 if ((_pause_mode & PM_PAUSED_ACTIVE_CLIENTS) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_NOT_ENOUGH_PLAYERS);
369 str = STR_NETWORK_SERVER_MESSAGE_GAME_STILL_PAUSED_1 + i;
370 } else {
371 switch (changed_mode) {
372 case PM_PAUSED_NORMAL: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_MANUAL); break;
373 case PM_PAUSED_JOIN: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_CONNECTING_CLIENTS); break;
374 case PM_PAUSED_GAME_SCRIPT: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_GAME_SCRIPT); break;
375 case PM_PAUSED_ACTIVE_CLIENTS: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_NOT_ENOUGH_PLAYERS); break;
376 default: NOT_REACHED();
378 str = paused ? STR_NETWORK_SERVER_MESSAGE_GAME_PAUSED : STR_NETWORK_SERVER_MESSAGE_GAME_UNPAUSED;
381 char buffer[DRAW_STRING_BUFFER];
382 GetString (buffer, str);
383 NetworkTextMessage(NETWORK_ACTION_SERVER_MESSAGE, CC_DEFAULT, false, NULL, buffer);
384 break;
387 default:
388 return;
394 * Helper function for the pause checkers. If pause is true and the
395 * current pause mode isn't set the game will be paused, if it it false
396 * and the pause mode is set the game will be unpaused. In the other
397 * cases nothing happens to the pause state.
398 * @param pause whether we'd like to pause
399 * @param pm the mode which we would like to pause with
401 static void CheckPauseHelper(bool pause, PauseMode pm)
403 if (pause == ((_pause_mode & pm) != PM_UNPAUSED)) return;
405 DoCommandP(0, pm, pause ? 1 : 0, CMD_PAUSE);
409 * Counts the number of active clients connected.
410 * It has to be in STATUS_ACTIVE and not a spectator
411 * @return number of active clients
413 static uint NetworkCountActiveClients()
415 const NetworkClientSocket *cs;
416 uint count = 0;
418 FOR_ALL_CLIENT_SOCKETS(cs) {
419 if (cs->status != NetworkClientSocket::STATUS_ACTIVE) continue;
420 if (!Company::IsValidID(cs->GetInfo()->client_playas)) continue;
421 count++;
424 return count;
428 * Check if the minimum number of active clients has been reached and pause or unpause the game as appropriate
430 static void CheckMinActiveClients()
432 if ((_pause_mode & PM_PAUSED_ERROR) != PM_UNPAUSED ||
433 !_network_dedicated ||
434 (_settings_client.network.min_active_clients == 0 && (_pause_mode & PM_PAUSED_ACTIVE_CLIENTS) == PM_UNPAUSED)) {
435 return;
437 CheckPauseHelper(NetworkCountActiveClients() < _settings_client.network.min_active_clients, PM_PAUSED_ACTIVE_CLIENTS);
441 * Checks whether there is a joining client
442 * @return true iff one client is joining (but not authorizing)
444 static bool NetworkHasJoiningClient()
446 const NetworkClientSocket *cs;
447 FOR_ALL_CLIENT_SOCKETS(cs) {
448 if (cs->status >= NetworkClientSocket::STATUS_AUTHORIZED && cs->status < NetworkClientSocket::STATUS_ACTIVE) return true;
451 return false;
455 * Check whether we should pause on join
457 static void CheckPauseOnJoin()
459 if ((_pause_mode & PM_PAUSED_ERROR) != PM_UNPAUSED ||
460 (!_settings_client.network.pause_on_join && (_pause_mode & PM_PAUSED_JOIN) == PM_UNPAUSED)) {
461 return;
463 CheckPauseHelper(NetworkHasJoiningClient(), PM_PAUSED_JOIN);
467 * Converts a string to ip/port/company
468 * Format: IP:port#company
470 * connection_string will be re-terminated to separate out the hostname, and company and port will
471 * be set to the company and port strings given by the user, inside the memory area originally
472 * occupied by connection_string.
474 void ParseConnectionString(const char **company, const char **port, char *connection_string)
476 bool ipv6 = (strchr(connection_string, ':') != strrchr(connection_string, ':'));
477 char *p;
478 for (p = connection_string; *p != '\0'; p++) {
479 switch (*p) {
480 case '[':
481 ipv6 = true;
482 break;
484 case ']':
485 ipv6 = false;
486 break;
488 case '#':
489 *company = p + 1;
490 *p = '\0';
491 break;
493 case ':':
494 if (ipv6) break;
495 *port = p + 1;
496 *p = '\0';
497 break;
503 * Handle the accepting of a connection to the server.
504 * @param s The socket of the new connection.
505 * @param address The address of the peer.
507 /* static */ void ServerNetworkGameSocketHandler::AcceptConnection(SOCKET s, const NetworkAddress &address)
509 /* Register the login */
510 _network_clients_connected++;
512 SetWindowDirty(WC_CLIENT_LIST, 0);
513 ServerNetworkGameSocketHandler *cs = new ServerNetworkGameSocketHandler(s);
514 cs->client_address = address; // Save the IP of the client
518 * Resets the pools used for network clients, and the admin pool if needed.
519 * @param close_admins Whether the admin pool has to be cleared as well.
521 static void InitializeNetworkPools(bool close_admins = true)
523 PoolBase::Clean(PT_NCLIENT | (close_admins ? PT_NADMIN : PT_NONE));
527 * Close current connections.
528 * @param close_admins Whether the admin connections have to be closed as well.
530 void NetworkClose(bool close_admins)
532 if (_network_server) {
533 if (close_admins) {
534 ServerNetworkAdminSocketHandler *as;
535 FOR_ALL_ADMIN_SOCKETS(as) {
536 as->CloseConnection(true);
540 NetworkClientSocket *cs;
541 FOR_ALL_CLIENT_SOCKETS(cs) {
542 cs->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
544 ServerNetworkGameSocketHandler::CloseListeners();
545 ServerNetworkAdminSocketHandler::CloseListeners();
546 } else if (MyClient::my_client != NULL) {
547 MyClient::SendQuit();
548 MyClient::my_client->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
551 TCPConnecter::KillAll();
553 _networking = false;
554 _network_server = false;
556 NetworkFreeLocalCommandQueue();
558 free(_network_company_states);
559 _network_company_states = NULL;
561 InitializeNetworkPools(close_admins);
564 /* Initializes the network (cleans sockets and stuff) */
565 static void NetworkInitialize(bool close_admins = true)
567 InitializeNetworkPools(close_admins);
568 NetworkUDPInitialize();
570 _sync_frame = 0;
571 _network_first_time = true;
573 _network_reconnect = 0;
576 /** Non blocking connection create to query servers */
577 class TCPQueryConnecter : TCPConnecter {
578 public:
579 TCPQueryConnecter(const NetworkAddress &address) : TCPConnecter(address) {}
581 virtual void OnFailure()
583 NetworkDisconnect();
586 virtual void OnConnect(SOCKET s)
588 _networking = true;
589 new ClientNetworkGameSocketHandler(s);
590 MyClient::SendCompanyInformationQuery();
594 /* Query a server to fetch his game-info
595 * If game_info is true, only the gameinfo is fetched,
596 * else only the client_info is fetched */
597 void NetworkTCPQueryServer(NetworkAddress address)
599 if (!_network_available) return;
601 NetworkDisconnect();
602 NetworkInitialize();
604 new TCPQueryConnecter(address);
607 /* Validates an address entered as a string and adds the server to
608 * the list. If you use this function, the games will be marked
609 * as manually added. */
610 void NetworkAddServer(const char *b)
612 if (*b != '\0') {
613 const char *port = NULL;
614 const char *company = NULL;
615 char host[NETWORK_HOSTNAME_LENGTH];
616 uint16 rport;
618 bstrcpy (host, b);
620 bstrcpy (_settings_client.network.connect_to_ip, b);
621 rport = NETWORK_DEFAULT_PORT;
623 ParseConnectionString(&company, &port, host);
624 if (port != NULL) rport = atoi(port);
626 NetworkUDPQueryServer(NetworkAddress(host, rport), true);
631 * Get the addresses to bind to.
632 * @param addresses the list to write to.
633 * @param port the port to bind to.
635 void GetBindAddresses(NetworkAddressList *addresses, uint16 port)
637 for (char **iter = _network_bind_list.Begin(); iter != _network_bind_list.End(); iter++) {
638 *addresses->Append() = NetworkAddress(*iter, port);
641 /* No address, so bind to everything. */
642 if (addresses->Length() == 0) {
643 *addresses->Append() = NetworkAddress("", port);
647 /* Generates the list of manually added hosts from NetworkGameList and
648 * dumps them into the array _network_host_list. This array is needed
649 * by the function that generates the config file. */
650 void NetworkRebuildHostList()
652 _network_host_list.Clear();
654 for (NetworkGameList *item = _network_game_list; item != NULL; item = item->next) {
655 if (item->manually) *_network_host_list.Append() = xstrdup(item->address.GetAddressAsString(false));
659 /** Non blocking connection create to actually connect to servers */
660 class TCPClientConnecter : TCPConnecter {
661 public:
662 TCPClientConnecter(const NetworkAddress &address) : TCPConnecter(address) {}
664 virtual void OnFailure()
666 NetworkError(STR_NETWORK_ERROR_NOCONNECTION);
669 virtual void OnConnect(SOCKET s)
671 _networking = true;
672 new ClientNetworkGameSocketHandler(s);
673 IConsoleCmdExec("exec scripts/on_client.scr 0");
674 NetworkClient_Connected();
679 /* Used by clients, to connect to a server */
680 void NetworkClientConnectGame(NetworkAddress address, CompanyID join_as, const char *join_server_password, const char *join_company_password)
682 if (!_network_available) return;
684 if (address.GetPort() == 0) return;
686 bstrcpy (_settings_client.network.last_host, address.GetHostname());
687 _settings_client.network.last_port = address.GetPort();
688 _network_join_as = join_as;
689 _network_join_server_password = join_server_password;
690 _network_join_company_password = join_company_password;
692 NetworkDisconnect();
693 NetworkInitialize();
695 _network_join_status = NETWORK_JOIN_STATUS_CONNECTING;
696 ShowJoinStatusWindow();
698 new TCPClientConnecter(address);
701 static void NetworkInitGameInfo()
703 if (StrEmpty(_settings_client.network.server_name)) {
704 bstrcpy (_settings_client.network.server_name, "Unnamed Server");
707 /* The server is a client too */
708 _network_game_info.clients_on = _network_dedicated ? 0 : 1;
710 /* There should be always space for the server. */
711 assert(NetworkClientInfo::CanAllocateItem());
712 NetworkClientInfo *ci = new NetworkClientInfo(CLIENT_ID_SERVER);
713 ci->client_playas = _network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST;
715 bstrcpy (ci->client_name, _settings_client.network.client_name);
718 bool NetworkServerStart()
720 if (!_network_available) return false;
722 /* Call the pre-scripts */
723 IConsoleCmdExec("exec scripts/pre_server.scr 0");
724 if (_network_dedicated) IConsoleCmdExec("exec scripts/pre_dedicated.scr 0");
726 NetworkDisconnect(false, false);
727 NetworkInitialize(false);
728 DEBUG(net, 1, "starting listeners for clients");
729 if (!ServerNetworkGameSocketHandler::Listen(_settings_client.network.server_port)) return false;
731 /* Only listen for admins when the password isn't empty. */
732 if (!StrEmpty(_settings_client.network.admin_password)) {
733 DEBUG(net, 1, "starting listeners for admins");
734 if (!ServerNetworkAdminSocketHandler::Listen(_settings_client.network.server_admin_port)) return false;
737 /* Try to start UDP-server */
738 DEBUG(net, 1, "starting listeners for incoming server queries");
739 _network_udp_server = _udp_server_socket->Listen();
741 _network_company_states = xcalloct<NetworkCompanyState>(MAX_COMPANIES);
742 _network_server = true;
743 _networking = true;
744 _frame_counter = 0;
745 _frame_counter_server = 0;
746 _frame_counter_max = 0;
747 _last_sync_frame = 0;
748 _network_own_client_id = CLIENT_ID_SERVER;
750 _network_clients_connected = 0;
751 _network_company_passworded = 0;
753 NetworkInitGameInfo();
755 /* execute server initialization script */
756 IConsoleCmdExec("exec scripts/on_server.scr 0");
757 /* if the server is dedicated ... add some other script */
758 if (_network_dedicated) IConsoleCmdExec("exec scripts/on_dedicated.scr 0");
760 /* Try to register us to the master server */
761 _network_need_advertise = true;
762 NetworkUDPAdvertise();
764 /* welcome possibly still connected admins - this can only happen on a dedicated server. */
765 if (_network_dedicated) ServerNetworkAdminSocketHandler::WelcomeAll();
767 return true;
770 /* The server is rebooting...
771 * The only difference with NetworkDisconnect, is the packets that is sent */
772 void NetworkReboot()
774 if (_network_server) {
775 NetworkClientSocket *cs;
776 FOR_ALL_CLIENT_SOCKETS(cs) {
777 cs->SendNewGame();
778 cs->SendPackets();
781 ServerNetworkAdminSocketHandler *as;
782 FOR_ALL_ACTIVE_ADMIN_SOCKETS(as) {
783 as->SendNewGame();
784 as->SendPackets();
788 /* For non-dedicated servers we have to kick the admins as we are not
789 * certain that we will end up in a new network game. */
790 NetworkClose(!_network_dedicated);
794 * We want to disconnect from the host/clients.
795 * @param blocking whether to wait till everything has been closed.
796 * @param close_admins Whether the admin sockets need to be closed as well.
798 void NetworkDisconnect(bool blocking, bool close_admins)
800 if (_network_server) {
801 NetworkClientSocket *cs;
802 FOR_ALL_CLIENT_SOCKETS(cs) {
803 cs->SendShutdown();
804 cs->SendPackets();
807 if (close_admins) {
808 ServerNetworkAdminSocketHandler *as;
809 FOR_ALL_ACTIVE_ADMIN_SOCKETS(as) {
810 as->SendShutdown();
811 as->SendPackets();
816 if (_settings_client.network.server_advertise) NetworkUDPRemoveAdvertise(blocking);
818 DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
820 NetworkClose(close_admins);
822 /* Reinitialize the UDP stack, i.e. close all existing connections. */
823 NetworkUDPInitialize();
827 * Receives something from the network.
828 * @return true if everything went fine, false when the connection got closed.
830 static bool NetworkReceive()
832 if (_network_server) {
833 ServerNetworkAdminSocketHandler::Receive();
834 return ServerNetworkGameSocketHandler::Receive();
835 } else {
836 return ClientNetworkGameSocketHandler::Receive();
840 /* This sends all buffered commands (if possible) */
841 static void NetworkSend()
843 if (_network_server) {
844 ServerNetworkAdminSocketHandler::Send();
845 ServerNetworkGameSocketHandler::Send();
846 } else {
847 ClientNetworkGameSocketHandler::Send();
852 * We have to do some (simple) background stuff that runs normally,
853 * even when we are not in multiplayer. For example stuff needed
854 * for finding servers or downloading content.
856 void NetworkBackgroundLoop()
858 _network_content_client.SendReceive();
859 TCPConnecter::CheckCallbacks();
860 NetworkHTTPSocketHandler::HTTPReceive();
862 NetworkBackgroundUDPLoop();
865 /** Inject commands from the log if debugging. */
866 static void InjectDebugDumpCommands (void)
868 #ifdef DEBUG_DUMP_COMMANDS
869 /* Loading of the debug commands from -ddesync>=1 */
870 static FILE *f = FioFOpenFile ("commands.log", "rb", SAVE_DIR);
871 static Date next_date = 0;
872 static uint32 next_date_fract;
873 static CommandPacket *cp = NULL;
874 static bool check_sync_state = false;
875 static uint32 sync_state[2];
877 if (f == NULL) {
878 if (next_date == 0) {
879 DEBUG(net, 0, "Cannot open commands.log");
880 next_date = 1;
882 return;
885 while (!feof(f)) {
886 if (_date == next_date && _date_fract == next_date_fract) {
887 if (cp != NULL) {
888 NetworkSendCommand (cp, cp->company, CMDSRC_OTHER);
889 DEBUG (net, 0, "injecting: %08x.%02x %02x %06x %08x %08x %02x \"%s\" (%s)",
890 _date, _date_fract, (int)_current_company,
891 cp->tile, cp->p1, cp->p2, cp->cmd, cp->text, GetCommandName(cp->cmd));
892 delete cp;
893 cp = NULL;
895 if (check_sync_state) {
896 if (sync_state[0] == _random.state[0] && sync_state[1] == _random.state[1]) {
897 DEBUG (net, 0, "sync check: %08x.%02x match", _date, _date_fract);
898 } else {
899 DEBUG (net, 0, "sync check: %08x.%02x mismatch expected {%08x, %08x}, got {%08x, %08x}",
900 _date, _date_fract, sync_state[0], sync_state[1], _random.state[0], _random.state[1]);
901 NOT_REACHED();
903 check_sync_state = false;
907 if (cp != NULL || check_sync_state) break;
909 char buff [4096];
910 if (fgets (buff, lengthof(buff), f) == NULL) break;
912 char *p = buff;
913 /* Ignore the "[date time] " part of the message */
914 if (*p == '[') {
915 p = strchr (p, ']');
916 if (p == NULL) break;
917 p += 2;
920 if (strncmp (p, "cmd: ", 5) == 0
921 #ifdef DEBUG_FAILED_DUMP_COMMANDS
922 || strncmp (p, "cmdf: ", 6) == 0
923 #endif
925 p += 5;
926 if (*p == ' ') p++;
927 cp = new CommandPacket;
928 int company, cmd;
929 int ret = sscanf (p, "%x.%x %x %x %x %x %x \"%[^\"]\"",
930 &next_date, &next_date_fract, &company,
931 &cp->tile, &cp->p1, &cp->p2, &cmd, cp->textdata);
932 /* There are 8 pieces of data to read, however the last is a
933 * string that might or might not exist. Ignore it if that
934 * string misses because in 99% of the time it's not used. */
935 assert (ret == 8 || ret == 7);
936 cp->company = (CompanyID)company;
937 cp->cmd = (CommandID)cmd;
938 } else if (strncmp (p, "join: ", 6) == 0) {
939 /* Manually insert a pause when joining; this way the client can join at the exact right time. */
940 int ret = sscanf (p + 6, "%x.%x", &next_date, &next_date_fract);
941 assert (ret == 2);
942 DEBUG (net, 0, "injecting pause for join at %08x.%02x; please join when paused",
943 next_date, next_date_fract);
944 cp = new CommandPacket;
945 cp->company = COMPANY_SPECTATOR;
946 cp->cmd = CMD_PAUSE;
947 cp->p1 = PM_PAUSED_NORMAL;
948 cp->p2 = 1;
949 _ddc_fastforward = false;
950 } else if (strncmp (p, "sync: ", 6) == 0) {
951 int ret = sscanf (p + 6, "%x.%x %x %x", &next_date, &next_date_fract, &sync_state[0], &sync_state[1]);
952 assert (ret == 4);
953 check_sync_state = true;
954 } else if (strncmp (p, "msg: ", 5) == 0 ||
955 strncmp (p, "client: ", 8) == 0 ||
956 strncmp (p, "new_map: ", 9) == 0 ||
957 strncmp (p, "load: ", 6) == 0 ||
958 strncmp (p, "save: ", 6) == 0) {
959 /* A message that is not very important to the log playback, but part of the log. */
960 #ifndef DEBUG_FAILED_DUMP_COMMANDS
961 } else if (strncmp (p, "cmdf: ", 6) == 0) {
962 DEBUG (net, 0, "Skipping replay of failed command: %s", p + 6);
963 #endif
964 } else {
965 /* Can't parse a line; what's wrong here? */
966 DEBUG (net, 0, "trying to parse: %s", p);
967 NOT_REACHED();
971 if (feof(f)) {
972 DEBUG (net, 0, "End of commands.log");
973 fclose (f);
974 f = NULL;
976 #endif /* DEBUG_DUMP_COMMANDS */
979 /* The main loop called from ttd.c
980 * Here we also have to do StateGameLoop if needed! */
981 void NetworkGameLoop()
983 if (!_networking) return;
985 if (!NetworkReceive()) return;
987 if (_network_server) {
988 /* Log the sync state to check for in-syncedness of replays. */
989 if (_date_fract == 0) {
990 /* We don't want to log multiple times if paused. */
991 static Date last_log;
992 if (last_log != _date) {
993 DEBUG (desync, 1, "sync: %08x.%02x %08x %08x", _date, _date_fract, _random.state[0], _random.state[1]);
994 last_log = _date;
998 InjectDebugDumpCommands();
1000 if (_frame_counter >= _frame_counter_max) {
1001 /* Only check for active clients just before we're going to send out
1002 * the commands so we don't send multiple pause/unpause commands when
1003 * the frame_freq is more than 1 tick. Same with distributing commands. */
1004 CheckPauseOnJoin();
1005 CheckMinActiveClients();
1006 NetworkDistributeCommands();
1009 bool send_frame = false;
1011 /* We first increase the _frame_counter */
1012 _frame_counter++;
1013 /* Update max-frame-counter */
1014 if (_frame_counter > _frame_counter_max) {
1015 _frame_counter_max = _frame_counter + _settings_client.network.frame_freq;
1016 send_frame = true;
1019 NetworkExecuteLocalCommandQueue();
1021 /* Then we make the frame */
1022 StateGameLoop();
1024 _sync_seed_1 = _random.state[0];
1025 #ifdef NETWORK_SEND_DOUBLE_SEED
1026 _sync_seed_2 = _random.state[1];
1027 #endif
1029 NetworkServer_Tick(send_frame);
1030 } else {
1031 /* Client */
1033 /* Make sure we are at the frame were the server is (quick-frames) */
1034 if (_frame_counter_server > _frame_counter) {
1035 /* Run a number of frames; when things go bad, get out. */
1036 while (_frame_counter_server > _frame_counter) {
1037 if (!ClientNetworkGameSocketHandler::GameLoop()) return;
1039 } else {
1040 /* Else, keep on going till _frame_counter_max */
1041 if (_frame_counter_max > _frame_counter) {
1042 /* Run one frame; if things went bad, get out. */
1043 if (!ClientNetworkGameSocketHandler::GameLoop()) return;
1048 NetworkSend();
1051 static void NetworkGenerateServerId()
1053 Md5 checksum;
1054 uint8 digest[16];
1055 char hex_output[16 * 2 + 1];
1056 char coding_string[NETWORK_NAME_LENGTH];
1057 int di;
1059 bstrfmt (coding_string, "%d%s", (uint)Random(), "OpenTTD Server ID");
1061 /* Generate the MD5 hash */
1062 checksum.Append((const uint8*)coding_string, strlen(coding_string));
1063 checksum.Finish(digest);
1065 for (di = 0; di < 16; ++di) {
1066 sprintf(hex_output + di * 2, "%02x", digest[di]);
1069 /* _settings_client.network.network_id is our id */
1070 bstrcpy (_settings_client.network.network_id, hex_output);
1073 void NetworkStartDebugLog(NetworkAddress address)
1075 extern SOCKET _debug_socket; // Comes from debug.c
1077 DEBUG(net, 0, "Redirecting DEBUG() to %s:%d", address.GetHostname(), address.GetPort());
1079 SOCKET s = address.Connect();
1080 if (s == INVALID_SOCKET) {
1081 DEBUG(net, 0, "Failed to open socket for redirection DEBUG()");
1082 return;
1085 _debug_socket = s;
1087 DEBUG(net, 0, "DEBUG() is now redirected");
1090 /** This tries to launch the network for a given OS */
1091 void NetworkStartUp()
1093 DEBUG(net, 3, "[core] starting network...");
1095 /* Network is available */
1096 _network_available = NetworkCoreInitialize();
1097 _network_dedicated = false;
1098 _network_need_advertise = true;
1099 _network_advertise_retries = 0;
1101 /* Generate an server id when there is none yet */
1102 if (StrEmpty(_settings_client.network.network_id)) NetworkGenerateServerId();
1104 memset(&_network_game_info, 0, sizeof(_network_game_info));
1106 NetworkInitialize();
1107 DEBUG(net, 3, "[core] network online, multiplayer available");
1108 NetworkFindBroadcastIPs(&_broadcast_list);
1111 /** This shuts the network down */
1112 void NetworkShutDown()
1114 NetworkDisconnect(true);
1115 NetworkUDPClose();
1117 DEBUG(net, 3, "[core] shutting down network");
1119 _network_available = false;
1121 NetworkCoreShutdown();
1125 * Checks whether the given version string is compatible with our version.
1126 * @param other the version string to compare to
1128 bool IsNetworkCompatibleVersion(const char *other)
1130 return strncmp(_openttd_revision, other, NETWORK_REVISION_LENGTH - 1) == 0;
1133 #endif /* ENABLE_NETWORK */