OpenTTD Source: src/network/network.cpp File Reference

OpenTTD Source 14.0-beta1

Data Structures | Functions | Variables
network.cpp File Reference
`#include "../stdafx.h"`
`#include "../strings_func.h"`
`#include "../command_func.h"`
`#include "../timer/timer_game_tick.h"`
`#include "../timer/timer_game_economy.h"`
`#include "network_admin.h"`
`#include "network_client.h"`
`#include "network_query.h"`
`#include "network_server.h"`
`#include "network_content.h"`
`#include "network_udp.h"`
`#include "network_gamelist.h"`
`#include "network_base.h"`
`#include "network_coordinator.h"`
`#include "core/udp.h"`
`#include "core/host.h"`
`#include "network_gui.h"`
`#include "../console_func.h"`
`#include "../3rdparty/md5/md5.h"`
`#include "../core/random_func.hpp"`
`#include "../window_func.h"`
`#include "../company_func.h"`
`#include "../company_base.h"`
`#include "../landscape_type.h"`
`#include "../rev.h"`
`#include "../core/pool_func.hpp"`
`#include "../gfx_func.h"`
`#include "../error.h"`
`#include "../misc_cmd.h"`
`#include <charconv>`
`#include <sstream>`
`#include <iomanip>`
`#include "../safeguards.h"`

Go to the source code of this file.

## Data Structures
class | TCPQueryConnecter
| Non blocking connection to query servers for their game info. More...
class | TCPClientConnecter
| Non blocking connection create to actually connect to servers. More...

## Functions
std::string | GenerateUid (std::string_view subject)
| Generate an unique ID. More...
bool | HasClients ()
| Return whether there is any client connected or trying to connect at all. More...
byte | NetworkSpectatorCount ()
std::string | NetworkChangeCompanyPassword (CompanyID company_id, std::string password)
| Change the company password of a given company. More...
std::string | GenerateCompanyPasswordHash (const std::string &password, const std::string &password_server_id, uint32_t password_game_seed)
| Hash the given password using server ID and game seed. More...
bool | NetworkCompanyIsPassworded (CompanyID company_id)
| Check if the company we want to join requires a password. More...
void | NetworkTextMessage (NetworkAction action, TextColour colour, bool self_send, const std::string &name, const std::string &str, int64_t data, const std::string &data_str)
uint | NetworkCalculateLag (const NetworkClientSocket *cs)
void | ShowNetworkError (StringID error_string)
StringID | GetNetworkErrorMsg (NetworkErrorCode err)
| Retrieve the string id of an internal error number. More...
void | NetworkHandlePauseChange (PauseMode prev_mode, PauseMode changed_mode)
| Handle the pause mode change so we send the right messages to the chat. More...
static void | CheckPauseHelper (bool pause, PauseMode pm)
| Helper function for the pause checkers. More...
static uint | NetworkCountActiveClients ()
| Counts the number of active clients connected. More...
static void | CheckMinActiveClients ()
| Check if the minimum number of active clients has been reached and pause or unpause the game as appropriate.
static bool | NetworkHasJoiningClient ()
| Checks whether there is a joining client. More...
static void | CheckPauseOnJoin ()
| Check whether we should pause on join.
std::string_view | ParseCompanyFromConnectionString (const std::string &connection_string, CompanyID *company_id)
| Parse the company part ("#company" postfix) of a connecting string. More...
std::string_view | ParseFullConnectionString (const std::string &connection_string, uint16_t &port, CompanyID *company_id)
| Converts a string to ip/port/company Format: IP:port::company. More...
std::string | NormalizeConnectionString (const std::string &connection_string, uint16_t default_port)
| Normalize a connection string. More...
NetworkAddress | ParseConnectionString (const std::string &connection_string, uint16_t default_port)
| Convert a string containing either "hostname" or "hostname:ip" to a NetworkAddress. More...
static void | InitializeNetworkPools (bool close_admins=true)
| Resets the pools used for network clients, and the admin pool if needed. More...
void | NetworkClose (bool close_admins)
| Close current connections. More...
static void | NetworkInitialize (bool close_admins=true)
void | NetworkQueryServer (const std::string &connection_string)
| Query a server to fetch the game-info. More...
NetworkGameList * | NetworkAddServer (const std::string &connection_string, bool manually, bool never_expire)
| Validates an address entered as a string and adds the server to the list. More...
void | GetBindAddresses (NetworkAddressList *addresses, uint16_t port)
| Get the addresses to bind to. More...
void | NetworkRebuildHostList ()
bool | NetworkClientConnectGame (const std::string &connection_string, CompanyID default_company, const std::string &join_server_password, const std::string &join_company_password)
| Join a client to the server at with the given connection string. More...
void | NetworkClientJoinGame ()
| Actually perform the joining to the server. More...
static void | NetworkInitGameInfo ()
bool | NetworkValidateServerName (std::string &server_name)
| Trim the given server name in place, i.e. More...
static void | CheckClientAndServerName ()
| Check whether the client and server name are set, for a dedicated server and if not set them to some default value and tell the user to change this as soon as possible. More...
bool | NetworkServerStart ()
void | NetworkReboot ()
void | NetworkDisconnect (bool close_admins)
| We want to disconnect from the host/clients. More...
void | NetworkUpdateServerGameType ()
| The setting server_game_type was updated; possibly we need to take some action.
static bool | NetworkReceive ()
| Receives something from the network. More...
static void | NetworkSend ()
void | NetworkBackgroundLoop ()
| We have to do some (simple) background stuff that runs normally, even when we are not in multiplayer. More...
void | NetworkGameLoop ()
static void | NetworkGenerateServerId ()
void | NetworkStartUp ()
| This tries to launch the network for a given OS.
void | NetworkShutDown ()
| This shuts the network down.

## Variables
NetworkClientInfoPool | _networkclientinfo_pool ("NetworkClientInfo")
| Make sure both pools have the same size. More...
bool | _networking
| are we in networking mode?
bool | _network_server
| network-server is active
bool | _network_available
| is network mode available?
bool | _network_dedicated
| are we a dedicated server?
bool | _is_network_server
| Does this client wants to be a network-server?
NetworkCompanyState * | _network_company_states = nullptr
| Statistics about some companies. More...
ClientID | _network_own_client_id
| Our client identifier.
ClientID | _redirect_console_to_client
| If not invalid, redirect the console output to a client.
uint8_t | _network_reconnect
| Reconnect timeout.
StringList | _network_bind_list
| The addresses to bind on.
StringList | _network_host_list
| The servers we know.
StringList | _network_ban_list
| The banned clients.
uint32_t | _frame_counter_server
| The frame_counter of the server, if in network-mode.
uint32_t | _frame_counter_max
| To where we may go with our clients.
uint32_t | _frame_counter
| The current frame.
uint32_t | _last_sync_frame
| Used in the server to store the last time a sync packet was sent to clients.
NetworkAddressList | _broadcast_list
| List of broadcast addresses.
uint32_t | _sync_seed_1
| Seed to compare during sync checks.
uint32_t | _sync_frame
| The frame to perform the sync check.
bool | _network_first_time
| Whether we have finished joining or not.
CompanyMask | _network_company_passworded
| Bitmask of the password status of all companies.
byte | _network_clients_connected = 0
| The amount of clients connected.

## Detailed Description

Base functions for networking support.

Definition in file network.cpp.

## Function Documentation

## ◆ CheckClientAndServerName()

static void CheckClientAndServerName | ( |  | ) |
| static

Check whether the client and server name are set, for a dedicated server and if not set them to some default value and tell the user to change this as soon as possible.

If the saved name is the default value, then the user is told to override this value too. This is only meant dedicated servers, as for the other servers the GUI ensures a name has been entered.

Definition at line 858 of file network.cpp.

References _settings_client, NetworkSettings::client_name, Debug, ClientSettings::network, NetworkSettings::server_name, and StrTrimInPlace().

## ◆ CheckPauseHelper()

static void CheckPauseHelper | ( | bool | pause,
|  | PauseMode | pm
| ) |  |
| static

Helper function for the pause checkers.

If pause is true and the current pause mode isn't set the game will be paused, if it it false and the pause mode is set the game will be unpaused. In the other cases nothing happens to the pause state.

Parameters

  pause | whether we'd like to pause
  pm | the mode which we would like to pause with

Definition at line 391 of file network.cpp.

References _pause_mode, and PM_UNPAUSED.

Referenced by CheckMinActiveClients(), and CheckPauseOnJoin().

## ◆ GenerateCompanyPasswordHash()

std::string GenerateCompanyPasswordHash | ( | const std::string & | password,
|  | const std::string & | password_server_id,
|  | uint32_t | password_game_seed
| ) |  |

Hash the given password using server ID and game seed.

Parameters

  password | Password to hash.
  password_server_id | Server ID.
  password_game_seed | Game seed.

Returns
  The hashed password.

Definition at line 177 of file network.cpp.

References FormatArrayAsHex(), and NETWORK_SERVER_ID_LENGTH.

Referenced by NetworkServerSetCompanyPassword(), ClientNetworkGameSocketHandler::SendCompanyPassword(), ClientNetworkGameSocketHandler::SendMove(), and ClientNetworkGameSocketHandler::SendSetPassword().

## ◆ GenerateUid()

std::string GenerateUid | ( | std::string_view | subject | ) |

Generate an unique ID.

It isn't as much of an unique ID but more a hashed digest of a random string and a time. It is very likely to be unique, but it does not follow any UUID standard.

Definition at line 69 of file misc.cpp.

References FormatArrayAsHex(), and RandomBytesWithFallback().

Referenced by GenerateSavegameId().

## ◆ GetBindAddresses()

void GetBindAddresses | ( | NetworkAddressList * | addresses,
|  | uint16_t | port
| ) |  |

Get the addresses to bind to.

Parameters

  addresses | the list to write to.
  port | the port to bind to.

Definition at line 705 of file network.cpp.

Referenced by NetworkUDPInitialize().

## ◆ GetNetworkErrorMsg()

StringID GetNetworkErrorMsg | ( | NetworkErrorCode | err | ) |

Retrieve the string id of an internal error number.

Parameters

  err | NetworkErrorCode

Returns
  the StringID

Definition at line 298 of file network.cpp.

References lengthof.

Referenced by ServerNetworkGameSocketHandler::Receive_CLIENT_ERROR(), ServerNetworkAdminSocketHandler::SendError(), and ServerNetworkGameSocketHandler::SendError().

## ◆ HasClients()

bool HasClients | ( |  | ) |

Return whether there is any client connected or trying to connect at all.

Returns
  whether we have any client activity

Definition at line 95 of file network.cpp.

## ◆ InitializeNetworkPools()

static void InitializeNetworkPools | ( | bool | close_admins = `true` | ) |
| static

Resets the pools used for network clients, and the admin pool if needed.

Parameters

  close_admins | Whether the admin pool has to be cleared as well.

Definition at line 566 of file network.cpp.

References PoolBase::Clean(), PT_NADMIN, PT_NCLIENT, and PT_NONE.

Referenced by NetworkClose().

## ◆ NetworkAddServer()

NetworkGameList* NetworkAddServer | ( | const std::string & | connection_string,
|  | bool | manually,
|  | bool | never_expire
| ) |  |

Validates an address entered as a string and adds the server to the list.

If you use this function, the games will be marked as manually added.

Parameters

  connection_string | The IP:port of the server to add.
  manually | Whether the enter should be marked as manual added.
  never_expire | Whether the entry can expire (removed when no longer found in the public listing).

Returns
  The entry on the game list.

Definition at line 679 of file network.cpp.

References ClearGRFConfigList(), NetworkServerGameInfo::grfconfig, NetworkGameList::info, NetworkGameList::manually, NetworkGameListAddItem(), NetworkQueryServer(), NetworkServerGameInfo::server_name, UpdateNetworkGameWindow(), and NetworkGameList::version.

Referenced by ClientNetworkUDPSocketHandler::Receive_SERVER_RESPONSE().

## ◆ NetworkBackgroundLoop()

void NetworkBackgroundLoop | ( |  | ) |

We have to do some (simple) background stuff that runs normally, even when we are not in multiplayer.

For example stuff needed for finding servers or downloading content.

Definition at line 1037 of file network.cpp.

References _network_content_client, _network_coordinator_client, TCPConnecter::CheckCallbacks(), NetworkHTTPSocketHandler::HTTPReceive(), NetworkBackgroundUDPLoop(), QueryNetworkGameSocketHandler::SendReceive(), ClientNetworkCoordinatorSocketHandler::SendReceive(), and ClientNetworkContentSocketHandler::SendReceive().

## ◆ NetworkChangeCompanyPassword()

std::string NetworkChangeCompanyPassword | ( | CompanyID | company_id,
|  | std::string | password
| ) |  |

Change the company password of a given company.

Parameters

  company_id | ID of the company the password should be changed for.
  password | The unhashed password we like to set ('*' or '' resets the password)

Returns
  The password.

Definition at line 157 of file network.cpp.

References _network_server, NetworkClientSetCompanyPassword(), and NetworkServerSetCompanyPassword().

Referenced by CmdCompanyCtrl().

## ◆ NetworkClientConnectGame()

bool NetworkClientConnectGame | ( | const std::string & | connection_string,
|  | CompanyID | default_company,
|  | const std::string & | join_server_password,
|  | const std::string & | join_company_password
| ) |  |

Join a client to the server at with the given connection string.

The default for the passwords is `nullptr`. When the server or company needs a password and none is given, the user is asked to enter the password in the GUI. This function will return false whenever some information required to join is not correct such as the company number or the client's name, or when there is not networking avalabile at all. If the function returns false the connection with the existing server is not disconnected. It will return true when it starts the actual join process, i.e. when it actually shows the join status window.

Parameters

  connection_string | The IP address, port and company number to join as.
  default_company | The company number to join as when none is given.
  join_server_password | The password for the server.
  join_company_password | The password for the company.

Returns
  Whether the join has started.

Definition at line 772 of file network.cpp.

References _network_available, _network_join, NetworkJoinInfo::company, NetworkJoinInfo::company_password, NetworkJoinInfo::connection_string, ServerAddress::connection_string, Debug, NETWORK_DEFAULT_PORT, NetworkValidateOurClientName(), ServerAddress::Parse(), and NetworkJoinInfo::server_password.

## ◆ NetworkClientJoinGame()

void NetworkClientJoinGame | ( |  | ) |

Actually perform the joining to the server.

Use NetworkClientConnectGame when you want to connect to a specific server/company. This function assumes _network_join is already fully set up.

Definition at line 806 of file network.cpp.

References NetworkDisconnect().

## ◆ NetworkClose()

void NetworkClose | ( | bool | close_admins | ) |

Close current connections.

Parameters

  close_admins | Whether the admin connections have to be closed as well.

Definition at line 575 of file network.cpp.

References _network_company_passworded, _network_company_states, _network_coordinator_client, _network_server, _networking, ClientNetworkCoordinatorSocketHandler::CloseAllConnections(), ClientNetworkGameSocketHandler::CloseConnection(), ClientNetworkCoordinatorSocketHandler::CloseConnection(), TCPListenHandler< ServerNetworkAdminSocketHandler, ADMIN_PACKET_SERVER_FULL, ADMIN_PACKET_SERVER_BANNED >::CloseListeners(), TCPListenHandler< ServerNetworkGameSocketHandler, PACKET_SERVER_FULL, PACKET_SERVER_BANNED >::CloseListeners(), InitializeNetworkPools(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_networkadminsocket_pool >::Iterate(), TCPConnecter::KillAll(), ClientNetworkGameSocketHandler::my_client, NETWORK_RECV_STATUS_CLIENT_QUIT, NetworkFreeLocalCommandQueue(), and ClientNetworkGameSocketHandler::SendQuit().

Referenced by NetworkDisconnect().

## ◆ NetworkCompanyIsPassworded()

bool NetworkCompanyIsPassworded | ( | CompanyID | company_id | ) |

Check if the company we want to join requires a password.

Parameters

  company_id | id of the company we want to check the 'passworded' flag for.

Returns
  true if the company requires a password.

Definition at line 209 of file network.cpp.

References _network_company_passworded, and HasBit().

Referenced by NetworkServerUpdateCompanyPassworded(), NetworkClientListWindow::OnClickCompanyJoin(), ServerNetworkAdminSocketHandler::SendCompanyInfo(), and ServerNetworkAdminSocketHandler::SendCompanyUpdate().

## ◆ NetworkCountActiveClients()

static uint NetworkCountActiveClients | ( |  | ) |
| static

Counts the number of active clients connected.

It has to be in STATUS_ACTIVE and not a spectator

Returns
  number of active clients

Definition at line 403 of file network.cpp.

References Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem<&_company_pool >::IsValidID().

Referenced by CheckMinActiveClients().

## ◆ NetworkDisconnect()

void NetworkDisconnect | ( | bool | close_admins | ) |

We want to disconnect from the host/clients.

Parameters

  close_admins | Whether the admin sockets need to be closed as well.

Definition at line 956 of file network.cpp.

References _network_server, CloseWindowById(), ServerNetworkAdminSocketHandler::IterateActive(), NetworkClose(), NetworkUDPInitialize(), WC_NETWORK_STATUS_WINDOW, and WN_NETWORK_STATUS_WINDOW_JOIN.

Referenced by NetworkClientJoinGame(), and NetworkShutDown().

## ◆ NetworkHandlePauseChange()

void NetworkHandlePauseChange | ( | PauseMode | prev_mode,
|  | PauseMode | changed_mode
| ) |  |

Handle the pause mode change so we send the right messages to the chat.

Parameters

  prev_mode | The previous pause mode.
  changed_mode | The pause mode that got changed.

Definition at line 337 of file network.cpp.

References _networking, _pause_mode, PM_PAUSED_ACTIVE_CLIENTS, PM_PAUSED_GAME_SCRIPT, PM_PAUSED_JOIN, PM_PAUSED_LINK_GRAPH, PM_PAUSED_NORMAL, PM_UNPAUSED, and SetDParam().

Referenced by CmdPause().

## ◆ NetworkHasJoiningClient()

static bool NetworkHasJoiningClient | ( |  | ) |
| static

Checks whether there is a joining client.

Returns
  true iff one client is joining (but not authorizing)

Definition at line 433 of file network.cpp.

Referenced by CheckPauseOnJoin().

## ◆ NetworkQueryServer()

void NetworkQueryServer | ( | const std::string & | connection_string | ) |

Query a server to fetch the game-info.

Parameters

  connection_string | the address to query.

Definition at line 657 of file network.cpp.

References _network_available, Debug, NetworkGameListAddItem(), and NetworkGameList::refreshing.

Referenced by NetworkAddServer().

## ◆ NetworkReceive()

static bool NetworkReceive | ( |  | ) |
| static

Receives something from the network.

Returns
  true if everything went fine, false when the connection got closed.

Definition at line 1007 of file network.cpp.

## ◆ NetworkValidateServerName()

bool NetworkValidateServerName | ( | std::string & | server_name | ) |

Trim the given server name in place, i.e.

remove leading and trailing spaces. After the trim check whether the server name is not empty. When the server name is empty a GUI error message is shown telling the user to set the servername and this function returns false.

Parameters

  server_name | The server name to validate. It will be trimmed of leading and trailing spaces.

Returns
  True iff the server name is valid.

Definition at line 843 of file network.cpp.

References INVALID_STRING_ID, ShowErrorMessage(), StrTrimInPlace(), and WL_ERROR.

## ◆ NormalizeConnectionString()

std::string NormalizeConnectionString | ( | const std::string & | connection_string,
|  | uint16_t | default_port
| ) |  |

Normalize a connection string.

That is, ensure there is a port in the string.

Parameters

  connection_string | The connection string to normalize.
  default_port | The port to use if none is given.

Returns
  The normalized connection string.

Definition at line 524 of file network.cpp.

## ◆ ParseCompanyFromConnectionString()

std::string_view ParseCompanyFromConnectionString | ( | const std::string & | connection_string,
|  | CompanyID * | company_id
| ) |  |

Parse the company part ("#company" postfix) of a connecting string.

Parameters

  connection_string | The string with the connection data.
  company_id | The company ID to set, if available.

Returns
  A std::string_view into the connection string without the company part.

Definition at line 460 of file network.cpp.

References COMPANY_NEW_COMPANY, COMPANY_SPECTATOR, and MAX_COMPANIES.

## ◆ ParseConnectionString()

NetworkAddress ParseConnectionString | ( | const std::string & | connection_string,
|  | uint16_t | default_port
| ) |  |

Convert a string containing either "hostname" or "hostname:ip" to a NetworkAddress.

Parameters

  connection_string | The string to parse.
  default_port | The default port to set port to if not in connection_string.

Returns
  A valid NetworkAddress of the parsed information.

Definition at line 539 of file network.cpp.

Referenced by TCPConnecter::Resolve().

## ◆ ParseFullConnectionString()

std::string_view ParseFullConnectionString | ( | const std::string & | connection_string,
|  | uint16_t & | port,
|  | CompanyID * | company_id
| ) |  |

Converts a string to ip/port/company Format: IP:port::company.

Returns the IP part as a string view into the passed string. This view is valid as long the passed connection string is valid. If there is no port present in the connection string, the port reference will not be touched. When there is no company ID present in the connection string or company_id is nullptr, then company ID will not be touched.

Parameters

  connection_string | The string with the connection data.
  port | The port reference to set.
  company_id | The company ID to set, if available.

Returns
  A std::string_view into the connection string with the (IP) address part.

Definition at line 504 of file network.cpp.

## Variable Documentation

## ◆ _network_company_states

NetworkCompanyState* _network_company_states = nullptr

Statistics about some companies.

Uncomment the following define to enable command replaying.

Definition at line 64 of file network.cpp.

Referenced by NetworkAutoCleanCompanies(), NetworkClose(), NetworkServerNewCompany(), and NetworkServerSetCompanyPassword().

## ◆ _networkclientinfo_pool

NetworkClientInfoPool _networkclientinfo_pool("NetworkClientInfo")

Make sure both pools have the same size.

The pool with client information.