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/>.
10 /** @file network.cpp Base functions for networking support. */
12 #include "../stdafx.h"
16 #include "../strings_func.h"
17 #include "../command_func.h"
18 #include "../date_func.h"
19 #include "network_admin.h"
20 #include "network_client.h"
21 #include "network_server.h"
22 #include "network_content.h"
23 #include "network_udp.h"
24 #include "network_gamelist.h"
25 #include "network_base.h"
27 #include "core/host.h"
28 #include "network_gui.h"
29 #include "../console_func.h"
30 #include "../3rdparty/md5/md5.h"
31 #include "../core/random_func.hpp"
32 #include "../window_func.h"
33 #include "../company_func.h"
34 #include "../company_base.h"
35 #include "../landscape_type.h"
37 #include "../core/pool_func.hpp"
38 #include "../gfx_func.h"
41 #ifdef DEBUG_DUMP_COMMANDS
42 #include "../fileio_func.h"
43 /** When running the server till the wait point, run as fast as we can! */
44 bool _ddc_fastforward
= true;
45 #endif /* DEBUG_DUMP_COMMANDS */
47 /** Make sure both pools have the same size. */
48 assert_compile(NetworkClientInfoPool::MAX_SIZE
== NetworkClientSocketPool::MAX_SIZE
);
50 /** The pool with client information. */
51 NetworkClientInfoPool
_networkclientinfo_pool("NetworkClientInfo");
52 INSTANTIATE_POOL_METHODS(NetworkClientInfo
)
54 bool _networking
; ///< are we in networking mode?
55 bool _network_server
; ///< network-server is active
56 bool _network_available
; ///< is network mode available?
57 bool _network_dedicated
; ///< are we a dedicated server?
58 bool _is_network_server
; ///< Does this client wants to be a network-server?
59 NetworkServerGameInfo _network_game_info
; ///< Information about our game.
60 NetworkCompanyState
*_network_company_states
= NULL
; ///< Statistics about some companies.
61 ClientID _network_own_client_id
; ///< Our client identifier.
62 ClientID _redirect_console_to_client
; ///< If not invalid, redirect the console output to a client.
63 bool _network_need_advertise
; ///< Whether we need to advertise.
64 uint32 _network_last_advertise_frame
; ///< Last time we did 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.
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();
100 * Basically a client is leaving us right now.
102 NetworkClientInfo::~NetworkClientInfo()
104 /* Delete the chat window, if you were chatting with this client. */
105 InvalidateWindowData(WC_SEND_NETWORK_MSG
, DESTTYPE_CLIENT
, this->client_id
);
109 * Return the CI given it's client-identifier
110 * @param client_id the ClientID to search for
111 * @return return a pointer to the corresponding NetworkClientInfo struct or NULL when not found
113 /* static */ NetworkClientInfo
*NetworkClientInfo::GetByClientID(ClientID client_id
)
115 NetworkClientInfo
*ci
;
117 FOR_ALL_CLIENT_INFOS(ci
) {
118 if (ci
->client_id
== client_id
) return ci
;
125 * Return the client state given it's client-identifier
126 * @param client_id the ClientID to search for
127 * @return return a pointer to the corresponding NetworkClientSocket struct or NULL when not found
129 /* static */ ServerNetworkGameSocketHandler
*ServerNetworkGameSocketHandler::GetByClientID(ClientID client_id
)
131 NetworkClientSocket
*cs
;
133 FOR_ALL_CLIENT_SOCKETS(cs
) {
134 if (cs
->client_id
== client_id
) return cs
;
140 byte
NetworkSpectatorCount()
142 const NetworkClientInfo
*ci
;
145 FOR_ALL_CLIENT_INFOS(ci
) {
146 if (ci
->client_playas
== COMPANY_SPECTATOR
) count
++;
149 /* Don't count a dedicated server as spectator */
150 if (_network_dedicated
) count
--;
156 * Change the company password of a given company.
157 * @param company_id ID of the company the password should be changed for.
158 * @param password The unhashed password we like to set ('*' or '' resets the password)
159 * @return The password.
161 const char *NetworkChangeCompanyPassword(CompanyID company_id
, const char *password
)
163 if (strcmp(password
, "*") == 0) password
= "";
165 if (_network_server
) {
166 NetworkServerSetCompanyPassword(company_id
, password
, false);
168 NetworkClientSetCompanyPassword(password
);
175 * Hash the given password using server ID and game seed.
176 * @param password Password to hash.
177 * @param password_server_id Server ID.
178 * @param password_game_seed Game seed.
179 * @return The hashed password.
181 const char *GenerateCompanyPasswordHash(const char *password
, const char *password_server_id
, uint32 password_game_seed
)
183 if (StrEmpty(password
)) return password
;
185 char salted_password
[NETWORK_SERVER_ID_LENGTH
];
187 memset(salted_password
, 0, sizeof(salted_password
));
188 snprintf(salted_password
, sizeof(salted_password
), "%s", password
);
189 /* Add the game seed and the server's ID as the salt. */
190 for (uint i
= 0; i
< NETWORK_SERVER_ID_LENGTH
- 1; i
++) {
191 salted_password
[i
] ^= password_server_id
[i
] ^ (password_game_seed
>> (i
% 32));
196 static char hashed_password
[NETWORK_SERVER_ID_LENGTH
];
198 /* Generate the MD5 hash */
199 checksum
.Append(salted_password
, sizeof(salted_password
) - 1);
200 checksum
.Finish(digest
);
202 for (int di
= 0; di
< 16; di
++) sprintf(hashed_password
+ di
* 2, "%02x", digest
[di
]);
203 hashed_password
[lengthof(hashed_password
) - 1] = '\0';
205 return hashed_password
;
209 * Check if the company we want to join requires a password.
210 * @param company_id id of the company we want to check the 'passworded' flag for.
211 * @return true if the company requires a password.
213 bool NetworkCompanyIsPassworded(CompanyID company_id
)
215 return HasBit(_network_company_passworded
, company_id
);
218 /* This puts a text-message to the console, or in the future, the chat-box,
219 * (to keep it all a bit more general)
220 * If 'self_send' is true, this is the client who is sending the message */
221 void NetworkTextMessage(NetworkAction action
, TextColour colour
, bool self_send
, const char *name
, const char *str
, int64 data
)
225 case NETWORK_ACTION_SERVER_MESSAGE
:
226 /* Ignore invalid messages */
227 strid
= STR_NETWORK_SERVER_MESSAGE
;
230 case NETWORK_ACTION_COMPANY_SPECTATOR
:
232 strid
= STR_NETWORK_MESSAGE_CLIENT_COMPANY_SPECTATE
;
234 case NETWORK_ACTION_COMPANY_JOIN
:
236 strid
= STR_NETWORK_MESSAGE_CLIENT_COMPANY_JOIN
;
238 case NETWORK_ACTION_COMPANY_NEW
:
240 strid
= STR_NETWORK_MESSAGE_CLIENT_COMPANY_NEW
;
242 case NETWORK_ACTION_JOIN
:
243 /* Show the Client ID for the server but not for the client. */
244 strid
= _network_server
? STR_NETWORK_MESSAGE_CLIENT_JOINED_ID
: STR_NETWORK_MESSAGE_CLIENT_JOINED
;
246 case NETWORK_ACTION_LEAVE
: strid
= STR_NETWORK_MESSAGE_CLIENT_LEFT
; break;
247 case NETWORK_ACTION_NAME_CHANGE
: strid
= STR_NETWORK_MESSAGE_NAME_CHANGE
; break;
248 case NETWORK_ACTION_GIVE_MONEY
: strid
= self_send
? STR_NETWORK_MESSAGE_GAVE_MONEY_AWAY
: STR_NETWORK_MESSAGE_GIVE_MONEY
; break;
249 case NETWORK_ACTION_CHAT_COMPANY
: strid
= self_send
? STR_NETWORK_CHAT_TO_COMPANY
: STR_NETWORK_CHAT_COMPANY
; break;
250 case NETWORK_ACTION_CHAT_CLIENT
: strid
= self_send
? STR_NETWORK_CHAT_TO_CLIENT
: STR_NETWORK_CHAT_CLIENT
; break;
251 default: strid
= STR_NETWORK_CHAT_ALL
; break;
255 SetDParamStr(0, name
);
256 SetDParamStr(1, str
);
259 /* All of these strings start with "***". These characters are interpreted as both left-to-right and
260 * right-to-left characters depending on the context. As the next text might be an user's name, the
261 * user name's characters will influence the direction of the "***" instead of the language setting
262 * of the game. Manually set the direction of the "***" by inserting a text-direction marker. */
263 char *msg_ptr
= message
+ Utf8Encode(message
, _current_text_dir
== TD_LTR
? CHAR_TD_LRM
: CHAR_TD_RLM
);
264 GetString(msg_ptr
, strid
, lastof(message
));
266 DEBUG(desync
, 1, "msg: %08x; %02x; %s", _date
, _date_fract
, message
);
267 IConsolePrintF(colour
, "%s", message
);
268 NetworkAddChatMessage((TextColour
)colour
, _settings_client
.gui
.network_chat_timeout
, "%s", message
);
271 /* Calculate the frame-lag of a client */
272 uint
NetworkCalculateLag(const NetworkClientSocket
*cs
)
274 int lag
= cs
->last_frame_server
- cs
->last_frame
;
275 /* This client has missed his ACK packet after 1 DAY_TICKS..
276 * so we increase his lag for every frame that passes!
277 * The packet can be out by a max of _net_frame_freq */
278 if (cs
->last_frame_server
+ DAY_TICKS
+ _settings_client
.network
.frame_freq
< _frame_counter
) {
279 lag
+= _frame_counter
- (cs
->last_frame_server
+ DAY_TICKS
+ _settings_client
.network
.frame_freq
);
285 /* There was a non-recoverable error, drop back to the main menu with a nice
287 void NetworkError(StringID error_string
)
289 _switch_mode
= SM_MENU
;
290 ShowErrorMessage(error_string
, INVALID_STRING_ID
, WL_CRITICAL
);
294 * Retrieve the string id of an internal error number
295 * @param err NetworkErrorCode
296 * @return the StringID
298 StringID
GetNetworkErrorMsg(NetworkErrorCode err
)
300 /* List of possible network errors, used by
301 * PACKET_SERVER_ERROR and PACKET_CLIENT_ERROR */
302 static const StringID network_error_strings
[] = {
303 STR_NETWORK_ERROR_CLIENT_GENERAL
,
304 STR_NETWORK_ERROR_CLIENT_DESYNC
,
305 STR_NETWORK_ERROR_CLIENT_SAVEGAME
,
306 STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST
,
307 STR_NETWORK_ERROR_CLIENT_PROTOCOL_ERROR
,
308 STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH
,
309 STR_NETWORK_ERROR_CLIENT_NOT_AUTHORIZED
,
310 STR_NETWORK_ERROR_CLIENT_NOT_EXPECTED
,
311 STR_NETWORK_ERROR_CLIENT_WRONG_REVISION
,
312 STR_NETWORK_ERROR_CLIENT_NAME_IN_USE
,
313 STR_NETWORK_ERROR_CLIENT_WRONG_PASSWORD
,
314 STR_NETWORK_ERROR_CLIENT_COMPANY_MISMATCH
,
315 STR_NETWORK_ERROR_CLIENT_KICKED
,
316 STR_NETWORK_ERROR_CLIENT_CHEATER
,
317 STR_NETWORK_ERROR_CLIENT_SERVER_FULL
,
318 STR_NETWORK_ERROR_CLIENT_TOO_MANY_COMMANDS
,
319 STR_NETWORK_ERROR_CLIENT_TIMEOUT_PASSWORD
,
320 STR_NETWORK_ERROR_CLIENT_TIMEOUT_COMPUTER
,
321 STR_NETWORK_ERROR_CLIENT_TIMEOUT_MAP
,
322 STR_NETWORK_ERROR_CLIENT_TIMEOUT_JOIN
,
324 assert_compile(lengthof(network_error_strings
) == NETWORK_ERROR_END
);
326 if (err
>= (ptrdiff_t)lengthof(network_error_strings
)) err
= NETWORK_ERROR_GENERAL
;
328 return network_error_strings
[err
];
332 * Handle the pause mode change so we send the right messages to the chat.
333 * @param prev_mode The previous pause mode.
334 * @param changed_mode The pause mode that got changed.
336 void NetworkHandlePauseChange(PauseMode prev_mode
, PauseMode changed_mode
)
338 if (!_networking
) return;
340 switch (changed_mode
) {
341 case PM_PAUSED_NORMAL
:
343 case PM_PAUSED_GAME_SCRIPT
:
344 case PM_PAUSED_ACTIVE_CLIENTS
: {
345 bool changed
= ((_pause_mode
== PM_UNPAUSED
) != (prev_mode
== PM_UNPAUSED
));
346 bool paused
= (_pause_mode
!= PM_UNPAUSED
);
347 if (!paused
&& !changed
) return;
353 if ((_pause_mode
& PM_PAUSED_NORMAL
) != PM_UNPAUSED
) SetDParam(++i
, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_MANUAL
);
354 if ((_pause_mode
& PM_PAUSED_JOIN
) != PM_UNPAUSED
) SetDParam(++i
, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_CONNECTING_CLIENTS
);
355 if ((_pause_mode
& PM_PAUSED_GAME_SCRIPT
) != PM_UNPAUSED
) SetDParam(++i
, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_GAME_SCRIPT
);
356 if ((_pause_mode
& PM_PAUSED_ACTIVE_CLIENTS
) != PM_UNPAUSED
) SetDParam(++i
, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_NOT_ENOUGH_PLAYERS
);
357 str
= STR_NETWORK_SERVER_MESSAGE_GAME_STILL_PAUSED_1
+ i
;
359 switch (changed_mode
) {
360 case PM_PAUSED_NORMAL
: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_MANUAL
); break;
361 case PM_PAUSED_JOIN
: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_CONNECTING_CLIENTS
); break;
362 case PM_PAUSED_GAME_SCRIPT
: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_GAME_SCRIPT
); break;
363 case PM_PAUSED_ACTIVE_CLIENTS
: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_NOT_ENOUGH_PLAYERS
); break;
364 default: NOT_REACHED();
366 str
= paused
? STR_NETWORK_SERVER_MESSAGE_GAME_PAUSED
: STR_NETWORK_SERVER_MESSAGE_GAME_UNPAUSED
;
369 char buffer
[DRAW_STRING_BUFFER
];
370 GetString(buffer
, str
, lastof(buffer
));
371 NetworkTextMessage(NETWORK_ACTION_SERVER_MESSAGE
, CC_DEFAULT
, false, NULL
, buffer
);
382 * Helper function for the pause checkers. If pause is true and the
383 * current pause mode isn't set the game will be paused, if it it false
384 * and the pause mode is set the game will be unpaused. In the other
385 * cases nothing happens to the pause state.
386 * @param pause whether we'd like to pause
387 * @param pm the mode which we would like to pause with
389 static void CheckPauseHelper(bool pause
, PauseMode pm
)
391 if (pause
== ((_pause_mode
& pm
) != PM_UNPAUSED
)) return;
393 DoCommandP(0, pm
, pause
? 1 : 0, CMD_PAUSE
);
397 * Counts the number of active clients connected.
398 * It has to be in STATUS_ACTIVE and not a spectator
399 * @return number of active clients
401 static uint
NetworkCountActiveClients()
403 const NetworkClientSocket
*cs
;
406 FOR_ALL_CLIENT_SOCKETS(cs
) {
407 if (cs
->status
!= NetworkClientSocket::STATUS_ACTIVE
) continue;
408 if (!Company::IsValidID(cs
->GetInfo()->client_playas
)) continue;
416 * Check if the minimum number of active clients has been reached and pause or unpause the game as appropriate
418 static void CheckMinActiveClients()
420 if ((_pause_mode
& PM_PAUSED_ERROR
) != PM_UNPAUSED
||
421 !_network_dedicated
||
422 (_settings_client
.network
.min_active_clients
== 0 && (_pause_mode
& PM_PAUSED_ACTIVE_CLIENTS
) == PM_UNPAUSED
)) {
425 CheckPauseHelper(NetworkCountActiveClients() < _settings_client
.network
.min_active_clients
, PM_PAUSED_ACTIVE_CLIENTS
);
429 * Checks whether there is a joining client
430 * @return true iff one client is joining (but not authorizing)
432 static bool NetworkHasJoiningClient()
434 const NetworkClientSocket
*cs
;
435 FOR_ALL_CLIENT_SOCKETS(cs
) {
436 if (cs
->status
>= NetworkClientSocket::STATUS_AUTHORIZED
&& cs
->status
< NetworkClientSocket::STATUS_ACTIVE
) return true;
443 * Check whether we should pause on join
445 static void CheckPauseOnJoin()
447 if ((_pause_mode
& PM_PAUSED_ERROR
) != PM_UNPAUSED
||
448 (!_settings_client
.network
.pause_on_join
&& (_pause_mode
& PM_PAUSED_JOIN
) == PM_UNPAUSED
)) {
451 CheckPauseHelper(NetworkHasJoiningClient(), PM_PAUSED_JOIN
);
455 * Converts a string to ip/port/company
456 * Format: IP:port#company
458 * connection_string will be re-terminated to separate out the hostname, and company and port will
459 * be set to the company and port strings given by the user, inside the memory area originally
460 * occupied by connection_string.
462 void ParseConnectionString(const char **company
, const char **port
, char *connection_string
)
464 bool ipv6
= (strchr(connection_string
, ':') != strrchr(connection_string
, ':'));
466 for (p
= connection_string
; *p
!= '\0'; p
++) {
491 * Handle the accepting of a connection to the server.
492 * @param s The socket of the new connection.
493 * @param address The address of the peer.
495 /* static */ void ServerNetworkGameSocketHandler::AcceptConnection(SOCKET s
, const NetworkAddress
&address
)
497 /* Register the login */
498 _network_clients_connected
++;
500 SetWindowDirty(WC_CLIENT_LIST
, 0);
501 ServerNetworkGameSocketHandler
*cs
= new ServerNetworkGameSocketHandler(s
);
502 cs
->client_address
= address
; // Save the IP of the client
506 * Resets the pools used for network clients, and the admin pool if needed.
507 * @param close_admins Whether the admin pool has to be cleared as well.
509 static void InitializeNetworkPools(bool close_admins
= true)
511 PoolBase::Clean(PT_NCLIENT
| (close_admins
? PT_NADMIN
: PT_NONE
));
515 * Close current connections.
516 * @param close_admins Whether the admin connections have to be closed as well.
518 void NetworkClose(bool close_admins
)
520 if (_network_server
) {
522 ServerNetworkAdminSocketHandler
*as
;
523 FOR_ALL_ADMIN_SOCKETS(as
) {
524 as
->CloseConnection(true);
528 NetworkClientSocket
*cs
;
529 FOR_ALL_CLIENT_SOCKETS(cs
) {
530 cs
->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST
);
532 ServerNetworkGameSocketHandler::CloseListeners();
533 ServerNetworkAdminSocketHandler::CloseListeners();
534 } else if (MyClient::my_client
!= NULL
) {
535 MyClient::SendQuit();
536 MyClient::my_client
->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST
);
539 TCPConnecter::KillAll();
542 _network_server
= false;
544 NetworkFreeLocalCommandQueue();
546 free(_network_company_states
);
547 _network_company_states
= NULL
;
549 InitializeNetworkPools(close_admins
);
552 /* Initializes the network (cleans sockets and stuff) */
553 static void NetworkInitialize(bool close_admins
= true)
555 InitializeNetworkPools(close_admins
);
556 NetworkUDPInitialize();
559 _network_first_time
= true;
561 _network_reconnect
= 0;
564 /** Non blocking connection create to query servers */
565 class TCPQueryConnecter
: TCPConnecter
{
567 TCPQueryConnecter(const NetworkAddress
&address
) : TCPConnecter(address
) {}
569 virtual void OnFailure()
574 virtual void OnConnect(SOCKET s
)
577 new ClientNetworkGameSocketHandler(s
);
578 MyClient::SendCompanyInformationQuery();
582 /* Query a server to fetch his game-info
583 * If game_info is true, only the gameinfo is fetched,
584 * else only the client_info is fetched */
585 void NetworkTCPQueryServer(NetworkAddress address
)
587 if (!_network_available
) return;
592 new TCPQueryConnecter(address
);
595 /* Validates an address entered as a string and adds the server to
596 * the list. If you use this function, the games will be marked
597 * as manually added. */
598 void NetworkAddServer(const char *b
)
601 const char *port
= NULL
;
602 const char *company
= NULL
;
603 char host
[NETWORK_HOSTNAME_LENGTH
];
606 strecpy(host
, b
, lastof(host
));
608 strecpy(_settings_client
.network
.connect_to_ip
, b
, lastof(_settings_client
.network
.connect_to_ip
));
609 rport
= NETWORK_DEFAULT_PORT
;
611 ParseConnectionString(&company
, &port
, host
);
612 if (port
!= NULL
) rport
= atoi(port
);
614 NetworkUDPQueryServer(NetworkAddress(host
, rport
), true);
619 * Get the addresses to bind to.
620 * @param addresses the list to write to.
621 * @param port the port to bind to.
623 void GetBindAddresses(NetworkAddressList
*addresses
, uint16 port
)
625 for (char **iter
= _network_bind_list
.Begin(); iter
!= _network_bind_list
.End(); iter
++) {
626 *addresses
->Append() = NetworkAddress(*iter
, port
);
629 /* No address, so bind to everything. */
630 if (addresses
->Length() == 0) {
631 *addresses
->Append() = NetworkAddress("", port
);
635 /* Generates the list of manually added hosts from NetworkGameList and
636 * dumps them into the array _network_host_list. This array is needed
637 * by the function that generates the config file. */
638 void NetworkRebuildHostList()
640 _network_host_list
.Clear();
642 for (NetworkGameList
*item
= _network_game_list
; item
!= NULL
; item
= item
->next
) {
643 if (item
->manually
) *_network_host_list
.Append() = strdup(item
->address
.GetAddressAsString(false));
647 /** Non blocking connection create to actually connect to servers */
648 class TCPClientConnecter
: TCPConnecter
{
650 TCPClientConnecter(const NetworkAddress
&address
) : TCPConnecter(address
) {}
652 virtual void OnFailure()
654 NetworkError(STR_NETWORK_ERROR_NOCONNECTION
);
657 virtual void OnConnect(SOCKET s
)
660 new ClientNetworkGameSocketHandler(s
);
661 IConsoleCmdExec("exec scripts/on_client.scr 0");
662 NetworkClient_Connected();
667 /* Used by clients, to connect to a server */
668 void NetworkClientConnectGame(NetworkAddress address
, CompanyID join_as
, const char *join_server_password
, const char *join_company_password
)
670 if (!_network_available
) return;
672 if (address
.GetPort() == 0) return;
674 strecpy(_settings_client
.network
.last_host
, address
.GetHostname(), lastof(_settings_client
.network
.last_host
));
675 _settings_client
.network
.last_port
= address
.GetPort();
676 _network_join_as
= join_as
;
677 _network_join_server_password
= join_server_password
;
678 _network_join_company_password
= join_company_password
;
683 _network_join_status
= NETWORK_JOIN_STATUS_CONNECTING
;
684 ShowJoinStatusWindow();
686 new TCPClientConnecter(address
);
689 static void NetworkInitGameInfo()
691 if (StrEmpty(_settings_client
.network
.server_name
)) {
692 snprintf(_settings_client
.network
.server_name
, sizeof(_settings_client
.network
.server_name
), "Unnamed Server");
695 /* The server is a client too */
696 _network_game_info
.clients_on
= _network_dedicated
? 0 : 1;
698 /* There should be always space for the server. */
699 assert(NetworkClientInfo::CanAllocateItem());
700 NetworkClientInfo
*ci
= new NetworkClientInfo(CLIENT_ID_SERVER
);
701 ci
->client_playas
= _network_dedicated
? COMPANY_SPECTATOR
: _local_company
;
703 strecpy(ci
->client_name
, _settings_client
.network
.client_name
, lastof(ci
->client_name
));
706 bool NetworkServerStart()
708 if (!_network_available
) return false;
710 /* Call the pre-scripts */
711 IConsoleCmdExec("exec scripts/pre_server.scr 0");
712 if (_network_dedicated
) IConsoleCmdExec("exec scripts/pre_dedicated.scr 0");
714 NetworkDisconnect(false, false);
715 NetworkInitialize(false);
716 if (!ServerNetworkGameSocketHandler::Listen(_settings_client
.network
.server_port
)) return false;
718 /* Only listen for admins when the password isn't empty. */
719 if (!StrEmpty(_settings_client
.network
.admin_password
) && !ServerNetworkAdminSocketHandler::Listen(_settings_client
.network
.server_admin_port
)) return false;
721 /* Try to start UDP-server */
722 _network_udp_server
= _udp_server_socket
->Listen();
724 _network_company_states
= CallocT
<NetworkCompanyState
>(MAX_COMPANIES
);
725 _network_server
= true;
728 _frame_counter_server
= 0;
729 _frame_counter_max
= 0;
730 _last_sync_frame
= 0;
731 _network_own_client_id
= CLIENT_ID_SERVER
;
733 _network_clients_connected
= 0;
734 _network_company_passworded
= 0;
736 NetworkInitGameInfo();
738 /* execute server initialization script */
739 IConsoleCmdExec("exec scripts/on_server.scr 0");
740 /* if the server is dedicated ... add some other script */
741 if (_network_dedicated
) IConsoleCmdExec("exec scripts/on_dedicated.scr 0");
743 /* Try to register us to the master server */
744 _network_last_advertise_frame
= 0;
745 _network_need_advertise
= true;
746 NetworkUDPAdvertise();
748 /* welcome possibly still connected admins - this can only happen on a dedicated server. */
749 if (_network_dedicated
) ServerNetworkAdminSocketHandler::WelcomeAll();
754 /* The server is rebooting...
755 * The only difference with NetworkDisconnect, is the packets that is sent */
758 if (_network_server
) {
759 NetworkClientSocket
*cs
;
760 FOR_ALL_CLIENT_SOCKETS(cs
) {
765 ServerNetworkAdminSocketHandler
*as
;
766 FOR_ALL_ACTIVE_ADMIN_SOCKETS(as
) {
772 /* For non-dedicated servers we have to kick the admins as we are not
773 * certain that we will end up in a new network game. */
774 NetworkClose(!_network_dedicated
);
778 * We want to disconnect from the host/clients.
779 * @param blocking whether to wait till everything has been closed.
780 * @param close_admins Whether the admin sockets need to be closed as well.
782 void NetworkDisconnect(bool blocking
, bool close_admins
)
784 if (_network_server
) {
785 NetworkClientSocket
*cs
;
786 FOR_ALL_CLIENT_SOCKETS(cs
) {
792 ServerNetworkAdminSocketHandler
*as
;
793 FOR_ALL_ACTIVE_ADMIN_SOCKETS(as
) {
800 if (_settings_client
.network
.server_advertise
) NetworkUDPRemoveAdvertise(blocking
);
802 DeleteWindowById(WC_NETWORK_STATUS_WINDOW
, WN_NETWORK_STATUS_WINDOW_JOIN
);
804 NetworkClose(close_admins
);
806 /* Reinitialize the UDP stack, i.e. close all existing connections. */
807 NetworkUDPInitialize();
811 * Receives something from the network.
812 * @return true if everything went fine, false when the connection got closed.
814 static bool NetworkReceive()
816 if (_network_server
) {
817 ServerNetworkAdminSocketHandler::Receive();
818 return ServerNetworkGameSocketHandler::Receive();
820 return ClientNetworkGameSocketHandler::Receive();
824 /* This sends all buffered commands (if possible) */
825 static void NetworkSend()
827 if (_network_server
) {
828 ServerNetworkAdminSocketHandler::Send();
829 ServerNetworkGameSocketHandler::Send();
831 ClientNetworkGameSocketHandler::Send();
836 * We have to do some (simple) background stuff that runs normally,
837 * even when we are not in multiplayer. For example stuff needed
838 * for finding servers or downloading content.
840 void NetworkBackgroundLoop()
842 _network_content_client
.SendReceive();
843 TCPConnecter::CheckCallbacks();
844 NetworkHTTPSocketHandler::HTTPReceive();
846 NetworkBackgroundUDPLoop();
849 /* The main loop called from ttd.c
850 * Here we also have to do StateGameLoop if needed! */
851 void NetworkGameLoop()
853 if (!_networking
) return;
855 if (!NetworkReceive()) return;
857 if (_network_server
) {
858 /* Log the sync state to check for in-syncedness of replays. */
859 if (_date_fract
== 0) {
860 /* We don't want to log multiple times if paused. */
861 static Date last_log
;
862 if (last_log
!= _date
) {
863 DEBUG(desync
, 1, "sync: %08x; %02x; %08x; %08x", _date
, _date_fract
, _random
.state
[0], _random
.state
[1]);
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];
876 if (f
== NULL
&& next_date
== 0) {
877 DEBUG(net
, 0, "Cannot open commands.log");
881 while (f
!= NULL
&& !feof(f
)) {
882 if (_date
== next_date
&& _date_fract
== next_date_fract
) {
884 NetworkSendCommand(cp
->tile
, cp
->p1
, cp
->p2
, cp
->cmd
& ~CMD_FLAGS_MASK
, NULL
, cp
->text
, cp
->company
);
885 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
));
889 if (check_sync_state
) {
890 if (sync_state
[0] == _random
.state
[0] && sync_state
[1] == _random
.state
[1]) {
891 DEBUG(net
, 0, "sync check: %08x; %02x; match", _date
, _date_fract
);
893 DEBUG(net
, 0, "sync check: %08x; %02x; mismatch expected {%08x, %08x}, got {%08x, %08x}",
894 _date
, _date_fract
, sync_state
[0], sync_state
[1], _random
.state
[0], _random
.state
[1]);
897 check_sync_state
= false;
901 if (cp
!= NULL
|| check_sync_state
) break;
904 if (fgets(buff
, lengthof(buff
), f
) == NULL
) break;
907 /* Ignore the "[date time] " part of the message */
910 if (p
== NULL
) break;
914 if (strncmp(p
, "cmd: ", 5) == 0) {
915 cp
= CallocT
<CommandPacket
>(1);
917 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
);
918 /* There are 8 pieces of data to read, however the last is a
919 * string that might or might not exist. Ignore it if that
920 * string misses because in 99% of the time it's not used. */
921 assert(ret
== 8 || ret
== 7);
922 cp
->company
= (CompanyID
)company
;
923 } else if (strncmp(p
, "join: ", 6) == 0) {
924 /* Manually insert a pause when joining; this way the client can join at the exact right time. */
925 int ret
= sscanf(p
+ 6, "%x; %x", &next_date
, &next_date_fract
);
927 DEBUG(net
, 0, "injecting pause for join at %08x:%02x; please join when paused", next_date
, next_date_fract
);
928 cp
= CallocT
<CommandPacket
>(1);
929 cp
->company
= COMPANY_SPECTATOR
;
931 cp
->p1
= PM_PAUSED_NORMAL
;
933 _ddc_fastforward
= false;
934 } else if (strncmp(p
, "sync: ", 6) == 0) {
935 int ret
= sscanf(p
+ 6, "%x; %x; %x; %x", &next_date
, &next_date_fract
, &sync_state
[0], &sync_state
[1]);
937 check_sync_state
= true;
938 } else if (strncmp(p
, "msg: ", 5) == 0 || strncmp(p
, "client: ", 8) == 0 ||
939 strncmp(p
, "load: ", 6) == 0 || strncmp(p
, "save: ", 6) == 0) {
940 /* A message that is not very important to the log playback, but part of the log. */
942 /* Can't parse a line; what's wrong here? */
943 DEBUG(net
, 0, "trying to parse: %s", p
);
947 if (f
!= NULL
&& feof(f
)) {
948 DEBUG(net
, 0, "End of commands.log");
952 #endif /* DEBUG_DUMP_COMMANDS */
953 if (_frame_counter
>= _frame_counter_max
) {
954 /* Only check for active clients just before we're going to send out
955 * the commands so we don't send multiple pause/unpause commands when
956 * the frame_freq is more than 1 tick. Same with distributing commands. */
958 CheckMinActiveClients();
959 NetworkDistributeCommands();
962 bool send_frame
= false;
964 /* We first increase the _frame_counter */
966 /* Update max-frame-counter */
967 if (_frame_counter
> _frame_counter_max
) {
968 _frame_counter_max
= _frame_counter
+ _settings_client
.network
.frame_freq
;
972 NetworkExecuteLocalCommandQueue();
974 /* Then we make the frame */
977 _sync_seed_1
= _random
.state
[0];
978 #ifdef NETWORK_SEND_DOUBLE_SEED
979 _sync_seed_2
= _random
.state
[1];
982 NetworkServer_Tick(send_frame
);
986 /* Make sure we are at the frame were the server is (quick-frames) */
987 if (_frame_counter_server
> _frame_counter
) {
988 /* Run a number of frames; when things go bad, get out. */
989 while (_frame_counter_server
> _frame_counter
) {
990 if (!ClientNetworkGameSocketHandler::GameLoop()) return;
993 /* Else, keep on going till _frame_counter_max */
994 if (_frame_counter_max
> _frame_counter
) {
995 /* Run one frame; if things went bad, get out. */
996 if (!ClientNetworkGameSocketHandler::GameLoop()) return;
1004 static void NetworkGenerateServerId()
1008 char hex_output
[16 * 2 + 1];
1009 char coding_string
[NETWORK_NAME_LENGTH
];
1012 snprintf(coding_string
, sizeof(coding_string
), "%d%s", (uint
)Random(), "OpenTTD Server ID");
1014 /* Generate the MD5 hash */
1015 checksum
.Append((const uint8
*)coding_string
, strlen(coding_string
));
1016 checksum
.Finish(digest
);
1018 for (di
= 0; di
< 16; ++di
) {
1019 sprintf(hex_output
+ di
* 2, "%02x", digest
[di
]);
1022 /* _settings_client.network.network_id is our id */
1023 snprintf(_settings_client
.network
.network_id
, sizeof(_settings_client
.network
.network_id
), "%s", hex_output
);
1026 void NetworkStartDebugLog(NetworkAddress address
)
1028 extern SOCKET _debug_socket
; // Comes from debug.c
1030 DEBUG(net
, 0, "Redirecting DEBUG() to %s:%d", address
.GetHostname(), address
.GetPort());
1032 SOCKET s
= address
.Connect();
1033 if (s
== INVALID_SOCKET
) {
1034 DEBUG(net
, 0, "Failed to open socket for redirection DEBUG()");
1040 DEBUG(net
, 0, "DEBUG() is now redirected");
1043 /** This tries to launch the network for a given OS */
1044 void NetworkStartUp()
1046 DEBUG(net
, 3, "[core] starting network...");
1048 /* Network is available */
1049 _network_available
= NetworkCoreInitialize();
1050 _network_dedicated
= false;
1051 _network_last_advertise_frame
= 0;
1052 _network_need_advertise
= true;
1053 _network_advertise_retries
= 0;
1055 /* Generate an server id when there is none yet */
1056 if (StrEmpty(_settings_client
.network
.network_id
)) NetworkGenerateServerId();
1058 memset(&_network_game_info
, 0, sizeof(_network_game_info
));
1060 NetworkInitialize();
1061 DEBUG(net
, 3, "[core] network online, multiplayer available");
1062 NetworkFindBroadcastIPs(&_broadcast_list
);
1065 /** This shuts the network down */
1066 void NetworkShutDown()
1068 NetworkDisconnect(true);
1071 DEBUG(net
, 3, "[core] shutting down network");
1073 _network_available
= false;
1075 NetworkCoreShutdown();
1079 * Checks whether the given version string is compatible with our version.
1080 * @param other the version string to compare to
1082 bool IsNetworkCompatibleVersion(const char *other
)
1084 return strncmp(_openttd_revision
, other
, NETWORK_REVISION_LENGTH
- 1) == 0;
1087 #endif /* ENABLE_NETWORK */