Merge branch 'master' into jgrpp-beta

# Conflicts:
#	src/console_cmds.cpp
#	src/debug.cpp
#	src/lang/vietnamese.txt
#	src/network/core/address.cpp
#	src/network/core/address.h
#	src/network/core/config.h
#	src/network/core/os_abstraction.cpp
#	src/network/core/os_abstraction.h
#	src/network/core/tcp_listen.h
#	src/network/core/udp.cpp
#	src/network/core/udp.h
#	src/network/network.cpp
#	src/network/network_client.cpp
#	src/network/network_gamelist.cpp
#	src/network/network_server.cpp
#	src/network/network_udp.cpp
#	src/newgrf.cpp
#	src/openttd.cpp
#	src/saveload/saveload.h
#	src/settings.cpp
#	src/settings_table.cpp
#	src/settings_type.h
#	src/table/settings/network_settings.ini
This commit is contained in:
Jonathan G Rennison
2021-11-02 00:51:54 +00:00
124 changed files with 3050 additions and 1274 deletions

View File

@@ -1,6 +1,7 @@
add_files(
address.cpp
address.h
config.cpp
config.h
core.cpp
core.h
@@ -20,11 +21,15 @@ add_files(
tcp_content.cpp
tcp_content.h
tcp_content_type.h
tcp_coordinator.cpp
tcp_coordinator.h
tcp_game.cpp
tcp_game.h
tcp_http.cpp
tcp_http.h
tcp_listen.h
tcp_stun.cpp
tcp_stun.h
udp.cpp
udp.h
)

View File

@@ -10,6 +10,7 @@
#include "../../stdafx.h"
#include "address.h"
#include "../network_internal.h"
#include "../../debug.h"
#include "../../safeguards.h"
@@ -335,13 +336,12 @@ static SOCKET ListenLoopProc(addrinfo *runp)
DEBUG(net, 1, "Setting no-delay mode failed: %s", NetworkError::GetLast().AsString());
}
int on = 1;
/* The (const char*) cast is needed for windows!! */
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on)) == -1) {
if (!SetReusePort(sock)) {
DEBUG(net, 0, "Setting reuse-address mode failed: %s", NetworkError::GetLast().AsString());
}
#ifndef __OS2__
int on = 1;
if (runp->ai_family == AF_INET6 &&
setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&on, sizeof(on)) == -1) {
DEBUG(net, 3, "Could not disable IPv4 over IPv6: %s", NetworkError::GetLast().AsString());
@@ -422,6 +422,38 @@ void NetworkAddress::Listen(int socktype, SocketList *sockets)
}
}
/**
* Get the peer address of a socket as NetworkAddress.
* @param sock The socket to get the peer address of.
* @return The NetworkAddress of the peer address.
*/
/* static */ NetworkAddress NetworkAddress::GetPeerAddress(SOCKET sock)
{
sockaddr_storage addr = {};
socklen_t addr_len = sizeof(addr);
if (getpeername(sock, (sockaddr *)&addr, &addr_len) != 0) {
DEBUG(net, 0, "Failed to get address of the peer: %s", NetworkError::GetLast().AsString());
return NetworkAddress();
}
return NetworkAddress(addr, addr_len);
}
/**
* Get the local address of a socket as NetworkAddress.
* @param sock The socket to get the local address of.
* @return The NetworkAddress of the local address.
*/
/* static */ NetworkAddress NetworkAddress::GetSockAddress(SOCKET sock)
{
sockaddr_storage addr = {};
socklen_t addr_len = sizeof(addr);
if (getsockname(sock, (sockaddr *)&addr, &addr_len) != 0) {
DEBUG(net, 0, "Failed to get address of the socket: %s", NetworkError::GetLast().AsString());
return NetworkAddress();
}
return NetworkAddress(addr, addr_len);
}
/**
* Get the peer name of a socket in string format.
* @param sock The socket to get the peer name of.
@@ -429,8 +461,27 @@ void NetworkAddress::Listen(int socktype, SocketList *sockets)
*/
/* static */ const std::string NetworkAddress::GetPeerName(SOCKET sock)
{
sockaddr_storage addr;
socklen_t addr_len = sizeof(addr);
getpeername(sock, (sockaddr *)&addr, &addr_len);
return NetworkAddress(addr, addr_len).GetAddressAsString();
return NetworkAddress::GetPeerAddress(sock).GetAddressAsString();
}
/**
* Convert a string containing either "hostname", "hostname:port" or invite code
* to a ServerAddress, where the string can be postfixed with "#company" to
* indicate the requested company.
*
* @param connection_string The string to parse.
* @param default_port The default port to set port to if not in connection_string.
* @param company Pointer to the company variable to set iff indicated.
* @return A valid ServerAddress of the parsed information.
*/
/* static */ ServerAddress ServerAddress::Parse(const std::string &connection_string, uint16 default_port, CompanyID *company_id)
{
if (StrStartsWith(connection_string, "+")) {
std::string_view invite_code = ParseCompanyFromConnectionString(connection_string, company_id);
return ServerAddress(SERVER_ADDRESS_INVITE_CODE, std::string(invite_code));
}
uint16 port = default_port;
std::string_view ip = ParseFullConnectionString(connection_string, port, company_id);
return ServerAddress(SERVER_ADDRESS_DIRECT, std::string(ip) + ":" + std::to_string(port));
}

View File

@@ -12,6 +12,7 @@
#include "os_abstraction.h"
#include "config.h"
#include "../../company_type.h"
#include "../../string_func.h"
#include "../../core/smallmap_type.hpp"
@@ -175,6 +176,8 @@ public:
static const char *SocketTypeAsString(int socktype);
static const char *AddressFamilyAsString(int family);
static NetworkAddress GetPeerAddress(SOCKET sock);
static NetworkAddress GetSockAddress(SOCKET sock);
static const std::string GetPeerName(SOCKET sock);
};
@@ -191,4 +194,38 @@ private:
char buf[NETWORK_HOSTNAME_PORT_LENGTH + 7];
};
/**
* Types of server addresses we know.
*
* Sorting will prefer entries at the top of this list above ones at the bottom.
*/
enum ServerAddressType {
SERVER_ADDRESS_DIRECT, ///< Server-address is based on an hostname:port.
SERVER_ADDRESS_INVITE_CODE, ///< Server-address is based on an invite code.
};
/**
* Address to a game server.
*
* This generalises addresses which are based on different identifiers.
*/
class ServerAddress {
private:
/**
* Create a new ServerAddress object.
*
* Please use ServerAddress::Parse() instead of calling this directly.
*
* @param type The type of the ServerAdress.
* @param connection_string The connection_string that belongs to this ServerAddress type.
*/
ServerAddress(ServerAddressType type, const std::string &connection_string) : type(type), connection_string(connection_string) {}
public:
ServerAddressType type; ///< The type of this ServerAddress.
std::string connection_string; ///< The connection string for this ServerAddress.
static ServerAddress Parse(const std::string &connection_string, uint16 default_port, CompanyID *company_id = nullptr);
};
#endif /* NETWORK_CORE_ADDRESS_H */

View File

@@ -0,0 +1,69 @@
/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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/>.
*/
/**
* @file config.cpp Configuration of the connection strings for network stuff using environment variables.
*/
#include "../../stdafx.h"
#include <cstdlib>
#include "../../string_func.h"
#include "../../safeguards.h"
/**
* Get the environment variable using std::getenv and when it is an empty string (or nullptr), return a fallback value instead.
* @param variable The environment variable to read from.
* @param fallback The fallback in case the environment variable is not set.
* @return The environment value, or when that does not exist the given fallback value.
*/
static const char *GetEnv(const char *variable, const char *fallback)
{
const char *value = std::getenv(variable);
return StrEmpty(value) ? fallback : value;
}
/**
* Get the connection string for the game coordinator from the environment variable OTTD_COORDINATOR_CS,
* or when it has not been set a hard coded default DNS hostname of the production server.
* @return The game coordinator's connection string.
*/
const char *NetworkCoordinatorConnectionString()
{
return GetEnv("OTTD_COORDINATOR_CS", "coordinator.openttd.org");
}
/**
* Get the connection string for the STUN server from the environment variable OTTD_STUN_CS,
* or when it has not been set a hard coded default DNS hostname of the production server.
* @return The STUN server's connection string.
*/
const char *NetworkStunConnectionString()
{
return GetEnv("OTTD_STUN_CS", "stun.openttd.org");
}
/**
* Get the connection string for the content server from the environment variable OTTD_CONTENT_SERVER_CS,
* or when it has not been set a hard coded default DNS hostname of the production server.
* @return The content server's connection string.
*/
const char *NetworkContentServerConnectionString()
{
return GetEnv("OTTD_CONTENT_SERVER_CS", "content.openttd.org");
}
/**
* Get the connection string for the content mirror from the environment variable OTTD_CONTENT_MIRROR_CS,
* or when it has not been set a hard coded default DNS hostname of the production server.
* @return The content mirror's connection string.
*/
const char *NetworkContentMirrorConnectionString()
{
return GetEnv("OTTD_CONTENT_MIRROR_CS", "binaries.openttd.org");
}

View File

@@ -12,26 +12,24 @@
#ifndef NETWORK_CORE_CONFIG_H
#define NETWORK_CORE_CONFIG_H
/** DNS hostname of the masterserver */
static const char * const NETWORK_MASTER_SERVER_HOST = "master.openttd.org";
/** DNS hostname of the content server */
static const char * const NETWORK_CONTENT_SERVER_HOST = "content.openttd.org";
/** DNS hostname of the HTTP-content mirror server */
static const char * const NETWORK_CONTENT_MIRROR_HOST = "binaries.openttd.org";
const char *NetworkCoordinatorConnectionString();
const char *NetworkStunConnectionString();
const char *NetworkContentServerConnectionString();
const char *NetworkContentMirrorConnectionString();
/** URL of the HTTP mirror system */
static const char * const NETWORK_CONTENT_MIRROR_URL = "/bananas";
/** Message sent to the masterserver to 'identify' this client as OpenTTD */
static const char * const NETWORK_MASTER_SERVER_WELCOME_MESSAGE = "OpenTTDRegister";
static const uint16 NETWORK_MASTER_SERVER_PORT = 3978; ///< The default port of the master server (UDP)
static const uint16 NETWORK_CONTENT_SERVER_PORT = 3978; ///< The default port of the content server (TCP)
static const uint16 NETWORK_CONTENT_MIRROR_PORT = 80; ///< The default port of the content mirror (TCP)
static const uint16 NETWORK_DEFAULT_PORT = 3979; ///< The default port of the game server (TCP & UDP)
static const uint16 NETWORK_ADMIN_PORT = 3977; ///< The default port for admin network
static const uint16 NETWORK_DEFAULT_DEBUGLOG_PORT = 3982; ///< The default port debug-log is sent to (TCP)
static const uint16 NETWORK_COORDINATOR_SERVER_PORT = 3976; ///< The default port of the Game Coordinator server (TCP)
static const uint16 NETWORK_STUN_SERVER_PORT = 3975; ///< The default port of the STUN server (TCP)
static const uint16 NETWORK_CONTENT_SERVER_PORT = 3978; ///< The default port of the content server (TCP)
static const uint16 NETWORK_CONTENT_MIRROR_PORT = 80; ///< The default port of the content mirror (TCP)
static const uint16 NETWORK_DEFAULT_PORT = 3979; ///< The default port of the game server (TCP & UDP)
static const uint16 NETWORK_ADMIN_PORT = 3977; ///< The default port for admin network
static const uint16 NETWORK_DEFAULT_DEBUGLOG_PORT = 3982; ///< The default port debug-log is sent to (TCP)
static const uint16 UDP_MTU = 1460; ///< Number of bytes we can pack in a single UDP packet
static const uint16 UDP_MTU_SHORT = 1400; ///< Number of bytes we can pack in a single UDP packet (conservative)
static const uint16 UDP_MTU = 1460; ///< Number of bytes we can pack in a single UDP packet
static const uint16 UDP_MTU_SHORT = 1400; ///< Number of bytes we can pack in a single UDP packet (conservative)
/*
* Technically a TCP packet could become 64kiB, however the high bit is kept so it becomes possible in the future
* to go to (significantly) larger packets if needed. This would entail a strategy such as employed for UTF-8.
@@ -46,42 +44,56 @@ static const uint16 UDP_MTU_SHORT = 1400; ///< Number of
* Send_uint16(GB(size, 16, 14) | 0b10 << 14)
* Send_uint16(GB(size, 0, 16))
*/
static const uint16 TCP_MTU = 32767; ///< Number of bytes we can pack in a single TCP packet
static const uint16 COMPAT_MTU = 1460; ///< Number of bytes we can pack in a single packet for backward compatibility
static const uint16 TCP_MTU = 32767; ///< Number of bytes we can pack in a single TCP packet
static const uint16 COMPAT_MTU = 1460; ///< Number of bytes we can pack in a single packet for backward compatibility
static const byte NETWORK_GAME_ADMIN_VERSION = 1; ///< What version of the admin network do we use?
static const byte NETWORK_GAME_INFO_VERSION = 4; ///< What version of game-info do we use?
static const byte NETWORK_COMPANY_INFO_VERSION = 6; ///< What version of company info is this?
static const byte NETWORK_MASTER_SERVER_VERSION = 2; ///< What version of master-server-protocol do we use?
static const byte NETWORK_GAME_ADMIN_VERSION = 1; ///< What version of the admin network do we use?
static const byte NETWORK_GAME_INFO_VERSION = 5; ///< What version of game-info do we use?
static const byte NETWORK_COMPANY_INFO_VERSION = 6; ///< What version of company info is this?
static const byte NETWORK_COORDINATOR_VERSION = 3; ///< What version of game-coordinator-protocol do we use?
static const uint NETWORK_NAME_LENGTH = 80; ///< The maximum length of the server name and map name, in bytes including '\0'
static const uint NETWORK_COMPANY_NAME_LENGTH = 128; ///< The maximum length of the company name, in bytes including '\0'
static const uint NETWORK_HOSTNAME_LENGTH = 80; ///< The maximum length of the host name, in bytes including '\0'
static const uint NETWORK_HOSTNAME_PORT_LENGTH = 80 + 6; ///< The maximum length of the host name + port, in bytes including '\0'. The extra six is ":" + port number (with a max of 65536)
static const uint NETWORK_SERVER_ID_LENGTH = 33; ///< The maximum length of the network id of the servers, in bytes including '\0'
static const uint NETWORK_REVISION_LENGTH = 33; ///< The maximum length of the revision, in bytes including '\0'
static const uint NETWORK_LONG_REVISION_LENGTH = 64; ///< The maximum length of the revision, in bytes including '\0'
static const uint NETWORK_PASSWORD_LENGTH = 33; ///< The maximum length of the password, in bytes including '\0' (must be >= NETWORK_SERVER_ID_LENGTH)
static const uint NETWORK_CLIENTS_LENGTH = 200; ///< The maximum length for the list of clients that controls a company, in bytes including '\0'
static const uint NETWORK_CLIENT_NAME_LENGTH = 25; ///< The maximum length of a client's name, in bytes including '\0'
static const uint NETWORK_RCONCOMMAND_LENGTH = 500; ///< The maximum length of a rconsole command, in bytes including '\0'
static const uint NETWORK_GAMESCRIPT_JSON_LENGTH = COMPAT_MTU-3; ///< The maximum length of a gamescript json string, in bytes including '\0'. Must not be longer than COMPAT_MTU including header (3 bytes)
static const uint NETWORK_CHAT_LENGTH = 900; ///< The maximum length of a chat message, in bytes including '\0'
static const uint NETWORK_CONTENT_FILENAME_LENGTH = 48; ///< The maximum length of a content's filename, in bytes including '\0'.
static const uint NETWORK_CONTENT_NAME_LENGTH = 64; ///< The maximum length of a content's name, in bytes including '\0'.
static const uint NETWORK_CONTENT_VERSION_LENGTH = 16; ///< The maximum length of a content's version, in bytes including '\0'.
static const uint NETWORK_CONTENT_URL_LENGTH = 96; ///< The maximum length of a content's url, in bytes including '\0'.
static const uint NETWORK_CONTENT_DESC_LENGTH = 512; ///< The maximum length of a content's description, in bytes including '\0'.
static const uint NETWORK_CONTENT_TAG_LENGTH = 32; ///< The maximum length of a content's tag, in bytes including '\0'.
static const uint NETWORK_NAME_LENGTH = 80; ///< The maximum length of the server name and map name, in bytes including '\0'
static const uint NETWORK_COMPANY_NAME_LENGTH = 128; ///< The maximum length of the company name, in bytes including '\0'
static const uint NETWORK_HOSTNAME_LENGTH = 80; ///< The maximum length of the host name, in bytes including '\0'
static const uint NETWORK_HOSTNAME_PORT_LENGTH = 80 + 6; ///< The maximum length of the host name + port, in bytes including '\0'. The extra six is ":" + port number (with a max of 65536)
static const uint NETWORK_SERVER_ID_LENGTH = 33; ///< The maximum length of the network id of the servers, in bytes including '\0'
static const uint NETWORK_REVISION_LENGTH = 33; ///< The maximum length of the revision, in bytes including '\0'
static const uint NETWORK_LONG_REVISION_LENGTH = 64; ///< The maximum length of the revision, in bytes including '\0'
static const uint NETWORK_PASSWORD_LENGTH = 33; ///< The maximum length of the password, in bytes including '\0' (must be >= NETWORK_SERVER_ID_LENGTH)
static const uint NETWORK_CLIENTS_LENGTH = 200; ///< The maximum length for the list of clients that controls a company, in bytes including '\0'
static const uint NETWORK_CLIENT_NAME_LENGTH = 25; ///< The maximum length of a client's name, in bytes including '\0'
static const uint NETWORK_RCONCOMMAND_LENGTH = 500; ///< The maximum length of a rconsole command, in bytes including '\0'
static const uint NETWORK_GAMESCRIPT_JSON_LENGTH = COMPAT_MTU - 3; ///< The maximum length of a gamescript json string, in bytes including '\0'. Must not be longer than COMPAT_MTU including header (3 bytes)
static const uint NETWORK_CHAT_LENGTH = 900; ///< The maximum length of a chat message, in bytes including '\0'
static const uint NETWORK_CONTENT_FILENAME_LENGTH = 48; ///< The maximum length of a content's filename, in bytes including '\0'.
static const uint NETWORK_CONTENT_NAME_LENGTH = 64; ///< The maximum length of a content's name, in bytes including '\0'.
static const uint NETWORK_CONTENT_VERSION_LENGTH = 16; ///< The maximum length of a content's version, in bytes including '\0'.
static const uint NETWORK_CONTENT_URL_LENGTH = 96; ///< The maximum length of a content's url, in bytes including '\0'.
static const uint NETWORK_CONTENT_DESC_LENGTH = 512; ///< The maximum length of a content's description, in bytes including '\0'.
static const uint NETWORK_CONTENT_TAG_LENGTH = 32; ///< The maximum length of a content's tag, in bytes including '\0'.
static const uint NETWORK_ERROR_DETAIL_LENGTH = 100; ///< The maximum length of the error detail, in bytes including '\0'.
static const uint NETWORK_INVITE_CODE_LENGTH = 64; ///< The maximum length of the invite code, in bytes including '\0'.
static const uint NETWORK_INVITE_CODE_SECRET_LENGTH = 80; ///< The maximum length of the invite code secret, in bytes including '\0'.
static const uint NETWORK_TOKEN_LENGTH = 64; ///< The maximum length of a token, in bytes including '\0'.
static const uint NETWORK_GRF_NAME_LENGTH = 80; ///< Maximum length of the name of a GRF
static const uint NETWORK_GRF_NAME_LENGTH = 80; ///< Maximum length of the name of a GRF
/**
* Maximum number of GRFs that can be sent.
* This limit is reached when PACKET_UDP_SERVER_RESPONSE reaches the maximum size of UDP_MTU bytes.
*
* This limit exists to avoid that the SERVER_INFO packet exceeding the
* maximum MTU. At the time of writing this limit is 32767 (TCP_MTU).
*
* In the SERVER_INFO packet is the NetworkGameInfo struct, which is
* 142 bytes + 100 per NewGRF (under the assumption strings are used to
* their max). This brings us to roughly 326 possible NewGRFs. Round it
* down so people don't freak out because they see a weird value, and you
* get the limit: 255.
*
* PS: in case you ever want to raise this number, please be mindful that
* "amount of NewGRFs" in NetworkGameInfo is currently an uint8.
*/
static const uint NETWORK_MAX_GRF_COUNT = 62;
static const uint NETWORK_MAX_GRF_COUNT_SHORT = 59;
static const uint NETWORK_MAX_GRF_COUNT = 255;
/**
* The number of landscapes in OpenTTD.
@@ -91,6 +103,6 @@ static const uint NETWORK_MAX_GRF_COUNT_SHORT = 59;
* there is a compile assertion to check that this NUM_LANDSCAPE is equal
* to NETWORK_NUM_LANDSCAPES.
*/
static const uint NETWORK_NUM_LANDSCAPES = 4;
static const uint NETWORK_NUM_LANDSCAPES = 4;
#endif /* NETWORK_CORE_CONFIG_H */

View File

@@ -16,6 +16,8 @@
#include "../../date_func.h"
#include "../../debug.h"
#include "../../map_func.h"
#include "../../game/game.hpp"
#include "../../game/game_info.hpp"
#include "../../settings_type.h"
#include "../../string_func.h"
#include "../../rev.h"
@@ -149,7 +151,11 @@ void FillStaticNetworkServerGameInfo()
*/
const NetworkServerGameInfo *GetCurrentNetworkServerGameInfo()
{
/* Client_on is used as global variable to keep track on the number of clients. */
/* These variables are updated inside _network_game_info as if they are global variables:
* - clients_on
* - invite_code
* These don't need to be updated manually here.
*/
_network_game_info.companies_on = (byte)Company::GetNumItems();
_network_game_info.spectators_on = NetworkSpectatorCount();
_network_game_info.game_date = _date;
@@ -199,6 +205,11 @@ void SerializeNetworkGameInfo(Packet *p, const NetworkServerGameInfo *info)
/* Update the documentation in game_info.h on changes
* to the NetworkGameInfo wire-protocol! */
/* NETWORK_GAME_INFO_VERSION = 5 */
GameInfo *game_info = Game::GetInfo();
p->Send_uint32(game_info == nullptr ? -1 : (uint32)game_info->GetVersion());
p->Send_string(game_info == nullptr ? "" : game_info->GetName());
/* NETWORK_GAME_INFO_VERSION = 4 */
{
/* Only send the GRF Identification (GRF_ID and MD5 checksum) of
@@ -218,12 +229,7 @@ void SerializeNetworkGameInfo(Packet *p, const NetworkServerGameInfo *info)
uint index = 0;
for (c = info->grfconfig; c != nullptr; c = c->next) {
if (!HasBit(c->flags, GCF_STATIC)) {
if (index == NETWORK_MAX_GRF_COUNT - 1 && count > NETWORK_MAX_GRF_COUNT) {
/* Send fake GRF ID */
p->Send_uint32(0x56D2B000);
p->Send_binary((const char*) _out_of_band_grf_md5, 16);
} else if (index >= NETWORK_MAX_GRF_COUNT) {
if (index >= NETWORK_MAX_GRF_COUNT) {
break;
} else {
SerializeGRFIdentifier(p, &c->ident);
@@ -327,6 +333,12 @@ void DeserializeNetworkGameInfo(Packet *p, NetworkGameInfo *info)
* to the NetworkGameInfo wire-protocol! */
switch (game_info_version) {
case 5: {
info->gamescript_version = (int)p->Recv_uint32();
info->gamescript_name = p->Recv_string(NETWORK_NAME_LENGTH);
FALLTHROUGH;
}
case 4: {
GRFConfig **dst = &info->grfconfig;
uint i;

View File

@@ -76,6 +76,8 @@ struct NetworkServerGameInfo {
byte spectators_on; ///< How many spectators do we have?
byte spectators_max; ///< Max spectators allowed on server
byte landscape; ///< The used landscape
int gamescript_version; ///< Version of the gamescript.
std::string gamescript_name; ///< Name of the gamescript.
};
/**

View File

@@ -180,6 +180,23 @@ bool SetNoDelay(SOCKET d)
#endif
}
/**
* Try to set the socket to reuse ports.
* @param d The socket to reuse ports on.
* @return True if disabling the delaying succeeded, otherwise false.
*/
bool SetReusePort(SOCKET d)
{
#ifdef _WIN32
/* Windows has no SO_REUSEPORT, but for our usecases SO_REUSEADDR does the same job. */
int reuse_port = 1;
return setsockopt(d, SOL_SOCKET, SO_REUSEADDR, (const char *)&reuse_port, sizeof(reuse_port)) == 0;
#else
int reuse_port = 1;
return setsockopt(d, SOL_SOCKET, SO_REUSEPORT, &reuse_port, sizeof(reuse_port)) == 0;
#endif
}
/**
* Try to shutdown the socket in one or both directions.
* @param d The socket to disable the delaying for.

View File

@@ -215,6 +215,7 @@ static inline socklen_t FixAddrLenForEmscripten(struct sockaddr_storage &address
bool SetNonBlocking(SOCKET d);
bool SetBlocking(SOCKET d);
bool SetNoDelay(SOCKET d);
bool SetReusePort(SOCKET d);
bool ShutdownSocket(SOCKET d, bool read, bool write, uint linger_timeout);
NetworkError GetSocketError(SOCKET d);

View File

@@ -95,10 +95,12 @@ private:
RESOLVING, ///< The hostname is being resolved (threaded).
FAILURE, ///< Resolving failed.
CONNECTING, ///< We are currently connecting.
CONNECTED, ///< The connection is established.
};
std::thread resolve_thread; ///< Thread used during resolving.
std::atomic<Status> status = Status::INIT; ///< The current status of the connecter.
std::atomic<bool> killed = false; ///< Whether this connecter is marked as killed.
addrinfo *ai = nullptr; ///< getaddrinfo() allocated linked-list of resolved addresses.
std::vector<addrinfo *> addresses; ///< Addresses we can connect to.
@@ -109,17 +111,24 @@ private:
std::chrono::steady_clock::time_point last_attempt; ///< Time we last tried to connect.
std::string connection_string; ///< Current address we are connecting to (before resolving).
NetworkAddress bind_address; ///< Address we're binding to, if any.
int family = AF_UNSPEC; ///< Family we are using to connect with.
void Resolve();
void OnResolved(addrinfo *ai);
bool TryNextAddress();
void Connect(addrinfo *address);
bool CheckActivity();
virtual bool CheckActivity();
/* We do not want any other derived classes from this class being able to
* access these private members, but it is okay for TCPServerConnecter. */
friend class TCPServerConnecter;
static void ResolveThunk(TCPConnecter *connecter);
public:
TCPConnecter(const std::string &connection_string, uint16 default_port);
TCPConnecter() {};
TCPConnecter(const std::string &connection_string, uint16 default_port, NetworkAddress bind_address = {}, int family = AF_UNSPEC);
virtual ~TCPConnecter();
/**
@@ -133,8 +142,25 @@ public:
*/
virtual void OnFailure() {}
void Kill();
static void CheckCallbacks();
static void KillAll();
};
class TCPServerConnecter : public TCPConnecter {
private:
SOCKET socket = INVALID_SOCKET; ///< The socket when a connection is established.
bool CheckActivity() override;
public:
ServerAddress server_address; ///< Address we are connecting to.
TCPServerConnecter(const std::string &connection_string, uint16 default_port);
void SetConnected(SOCKET sock);
void SetFailure();
};
#endif /* NETWORK_CORE_TCP_H */

View File

@@ -13,6 +13,7 @@
#include "../../thread.h"
#include "tcp.h"
#include "../network_coordinator.h"
#include "../network_internal.h"
#include <deque>
@@ -23,16 +24,45 @@
static std::vector<TCPConnecter *> _tcp_connecters;
/**
* Create a new connecter for the given address
* @param connection_string the address to connect to
* Create a new connecter for the given address.
* @param connection_string The address to connect to.
* @param default_port If not indicated in connection_string, what port to use.
* @param bind_address The local bind address to use. Defaults to letting the OS find one.
*/
TCPConnecter::TCPConnecter(const std::string &connection_string, uint16 default_port)
TCPConnecter::TCPConnecter(const std::string &connection_string, uint16 default_port, NetworkAddress bind_address, int family) :
bind_address(bind_address),
family(family)
{
this->connection_string = NormalizeConnectionString(connection_string, default_port);
_tcp_connecters.push_back(this);
}
/**
* Create a new connecter for the server.
* @param connection_string The address to connect to.
* @param default_port If not indicated in connection_string, what port to use.
*/
TCPServerConnecter::TCPServerConnecter(const std::string &connection_string, uint16 default_port) :
server_address(ServerAddress::Parse(connection_string, default_port))
{
switch (this->server_address.type) {
case SERVER_ADDRESS_DIRECT:
this->connection_string = this->server_address.connection_string;
break;
case SERVER_ADDRESS_INVITE_CODE:
this->status = Status::CONNECTING;
_network_coordinator_client.ConnectToServer(this->server_address.connection_string, this);
break;
default:
NOT_REACHED();
}
_tcp_connecters.push_back(this);
}
TCPConnecter::~TCPConnecter()
{
if (this->resolve_thread.joinable()) {
@@ -48,6 +78,16 @@ TCPConnecter::~TCPConnecter()
if (this->ai != nullptr) freeaddrinfo(this->ai);
}
/**
* Kill this connecter.
* It will abort as soon as it can and not call any of the callbacks.
*/
void TCPConnecter::Kill()
{
/* Delay the removing of the socket till the next CheckActivity(). */
this->killed = true;
}
/**
* Start a connection to the indicated address.
* @param address The address to connection to.
@@ -60,6 +100,18 @@ void TCPConnecter::Connect(addrinfo *address)
return;
}
if (!SetReusePort(sock)) {
DEBUG(net, 0, "Setting reuse-port mode failed: %s", NetworkError::GetLast().AsString());
}
if (this->bind_address.GetPort() > 0) {
if (bind(sock, (const sockaddr *)this->bind_address.GetAddress(), this->bind_address.GetAddressLength()) != 0) {
DEBUG(net, 1, "Could not bind socket on %s: %s", NetworkAddressDumper().GetAddressAsString(&(this->bind_address)), NetworkError::GetLast().AsString());
closesocket(sock);
return;
}
}
if (!SetNoDelay(sock)) {
DEBUG(net, 1, "Setting TCP_NODELAY failed: %s", NetworkError::GetLast().AsString());
}
@@ -123,6 +175,9 @@ void TCPConnecter::OnResolved(addrinfo *ai)
/* Convert the addrinfo into NetworkAddresses. */
for (addrinfo *runp = ai; runp != nullptr; runp = runp->ai_next) {
/* Skip entries if the family is set and it is not matching. */
if (this->family != AF_UNSPEC && this->family != runp->ai_family) continue;
if (resort) {
if (runp->ai_family == AF_INET6) {
addresses_ipv6.emplace_back(runp);
@@ -219,7 +274,9 @@ void TCPConnecter::Resolve()
*/
bool TCPConnecter::CheckActivity()
{
switch (this->status.load()) {
if (this->killed) return true;
switch (this->status) {
case Status::INIT:
/* Start the thread delayed, so the vtable is loaded. This allows classes
* to overload functions used by Resolve() (in case threading is disabled). */
@@ -246,6 +303,7 @@ bool TCPConnecter::CheckActivity()
return true;
case Status::CONNECTING:
case Status::CONNECTED:
break;
}
@@ -344,9 +402,63 @@ bool TCPConnecter::CheckActivity()
}
this->OnConnect(connected_socket);
this->status = Status::CONNECTED;
return true;
}
/**
* Check if there was activity for this connecter.
* @return True iff the TCPConnecter is done and can be cleaned up.
*/
bool TCPServerConnecter::CheckActivity()
{
if (this->killed) return true;
switch (this->server_address.type) {
case SERVER_ADDRESS_DIRECT:
return TCPConnecter::CheckActivity();
case SERVER_ADDRESS_INVITE_CODE:
/* Check if a result has come in. */
switch (this->status) {
case Status::FAILURE:
this->OnFailure();
return true;
case Status::CONNECTED:
this->OnConnect(this->socket);
return true;
default:
break;
}
return false;
default:
NOT_REACHED();
}
}
/**
* The connection was successfully established.
* This socket is fully setup and ready to send/recv game protocol packets.
* @param sock The socket of the established connection.
*/
void TCPServerConnecter::SetConnected(SOCKET sock)
{
this->socket = sock;
this->status = Status::CONNECTED;
}
/**
* The connection couldn't be established.
*/
void TCPServerConnecter::SetFailure()
{
this->status = Status::FAILURE;
}
/**
* Check whether we need to call the callback, i.e. whether we
* have connected or aborted and call the appropriate callback

View File

@@ -0,0 +1,101 @@
/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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/>.
*/
/**
* @file tcp_coordinator.cpp Basic functions to receive and send Game Coordinator packets.
*/
#include "../../stdafx.h"
#include "../../date_func.h"
#include "../../debug.h"
#include "tcp_coordinator.h"
#include "../../safeguards.h"
/**
* Handle the given packet, i.e. pass it to the right.
* parser receive command.
* @param p The packet to handle.
* @return True iff we should immediately handle further packets.
*/
bool NetworkCoordinatorSocketHandler::HandlePacket(Packet *p)
{
PacketCoordinatorType type = (PacketCoordinatorType)p->Recv_uint8();
switch (type) {
case PACKET_COORDINATOR_GC_ERROR: return this->Receive_GC_ERROR(p);
case PACKET_COORDINATOR_SERVER_REGISTER: return this->Receive_SERVER_REGISTER(p);
case PACKET_COORDINATOR_GC_REGISTER_ACK: return this->Receive_GC_REGISTER_ACK(p);
case PACKET_COORDINATOR_SERVER_UPDATE: return this->Receive_SERVER_UPDATE(p);
case PACKET_COORDINATOR_CLIENT_LISTING: return this->Receive_CLIENT_LISTING(p);
case PACKET_COORDINATOR_GC_LISTING: return this->Receive_GC_LISTING(p);
case PACKET_COORDINATOR_CLIENT_CONNECT: return this->Receive_CLIENT_CONNECT(p);
case PACKET_COORDINATOR_GC_CONNECTING: return this->Receive_GC_CONNECTING(p);
case PACKET_COORDINATOR_SERCLI_CONNECT_FAILED: return this->Receive_SERCLI_CONNECT_FAILED(p);
case PACKET_COORDINATOR_GC_CONNECT_FAILED: return this->Receive_GC_CONNECT_FAILED(p);
case PACKET_COORDINATOR_CLIENT_CONNECTED: return this->Receive_CLIENT_CONNECTED(p);
case PACKET_COORDINATOR_GC_DIRECT_CONNECT: return this->Receive_GC_DIRECT_CONNECT(p);
case PACKET_COORDINATOR_GC_STUN_REQUEST: return this->Receive_GC_STUN_REQUEST(p);
case PACKET_COORDINATOR_SERCLI_STUN_RESULT: return this->Receive_SERCLI_STUN_RESULT(p);
case PACKET_COORDINATOR_GC_STUN_CONNECT: return this->Receive_GC_STUN_CONNECT(p);
default:
DEBUG(net, 0, "[tcp/coordinator] Received invalid packet type %u", type);
return false;
}
}
/**
* Receive a packet at TCP level.
* @return Whether at least one packet was received.
*/
bool NetworkCoordinatorSocketHandler::ReceivePackets()
{
/*
* We read only a few of the packets. This allows the GUI to update when
* a large set of servers is being received. Otherwise the interface
* "hangs" while the game is updating the server-list.
*
* What arbitrary number to choose is the ultimate question though.
*/
std::unique_ptr<Packet> p;
static const int MAX_PACKETS_TO_RECEIVE = 42;
int i = MAX_PACKETS_TO_RECEIVE;
while (--i != 0 && (p = this->ReceivePacket()) != nullptr) {
bool cont = this->HandlePacket(p.get());
if (!cont) return true;
}
return i != MAX_PACKETS_TO_RECEIVE - 1;
}
/**
* Helper for logging receiving invalid packets.
* @param type The received packet type.
* @return Always false, as it's an error.
*/
bool NetworkCoordinatorSocketHandler::ReceiveInvalidPacket(PacketCoordinatorType type)
{
DEBUG(net, 0, "[tcp/coordinator] Received illegal packet type %u", type);
return false;
}
bool NetworkCoordinatorSocketHandler::Receive_GC_ERROR(Packet *p) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_ERROR); }
bool NetworkCoordinatorSocketHandler::Receive_SERVER_REGISTER(Packet *p) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_SERVER_REGISTER); }
bool NetworkCoordinatorSocketHandler::Receive_GC_REGISTER_ACK(Packet *p) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_REGISTER_ACK); }
bool NetworkCoordinatorSocketHandler::Receive_SERVER_UPDATE(Packet *p) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_SERVER_UPDATE); }
bool NetworkCoordinatorSocketHandler::Receive_CLIENT_LISTING(Packet *p) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_CLIENT_LISTING); }
bool NetworkCoordinatorSocketHandler::Receive_GC_LISTING(Packet *p) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_LISTING); }
bool NetworkCoordinatorSocketHandler::Receive_CLIENT_CONNECT(Packet *p) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_CLIENT_CONNECT); }
bool NetworkCoordinatorSocketHandler::Receive_GC_CONNECTING(Packet *p) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_CONNECTING); }
bool NetworkCoordinatorSocketHandler::Receive_SERCLI_CONNECT_FAILED(Packet *p) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_SERCLI_CONNECT_FAILED); }
bool NetworkCoordinatorSocketHandler::Receive_GC_CONNECT_FAILED(Packet *p) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_CONNECT_FAILED); }
bool NetworkCoordinatorSocketHandler::Receive_CLIENT_CONNECTED(Packet *p) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_CLIENT_CONNECTED); }
bool NetworkCoordinatorSocketHandler::Receive_GC_DIRECT_CONNECT(Packet *p) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_DIRECT_CONNECT); }
bool NetworkCoordinatorSocketHandler::Receive_GC_STUN_REQUEST(Packet *p) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_STUN_REQUEST); }
bool NetworkCoordinatorSocketHandler::Receive_SERCLI_STUN_RESULT(Packet *p) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_SERCLI_STUN_RESULT); }
bool NetworkCoordinatorSocketHandler::Receive_GC_STUN_CONNECT(Packet *p) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_STUN_CONNECT); }

View File

@@ -0,0 +1,277 @@
/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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/>.
*/
/**
* @file tcp_coordinator.h Basic functions to receive and send TCP packets to/from the Game Coordinator server.
*/
#ifndef NETWORK_CORE_TCP_COORDINATOR_H
#define NETWORK_CORE_TCP_COORDINATOR_H
#include "os_abstraction.h"
#include "tcp.h"
#include "packet.h"
#include "game_info.h"
/**
* Enum with all types of TCP Game Coordinator packets. The order MUST not be changed.
*
* GC -> packets from Game Coordinator to either Client or Server.
* SERVER -> packets from Server to Game Coordinator.
* CLIENT -> packets from Client to Game Coordinator.
* SERCLI -> packets from either the Server or Client to Game Coordinator.
**/
enum PacketCoordinatorType {
PACKET_COORDINATOR_GC_ERROR, ///< Game Coordinator indicates there was an error.
PACKET_COORDINATOR_SERVER_REGISTER, ///< Server registration.
PACKET_COORDINATOR_GC_REGISTER_ACK, ///< Game Coordinator accepts the registration.
PACKET_COORDINATOR_SERVER_UPDATE, ///< Server sends an set intervals an update of the server.
PACKET_COORDINATOR_CLIENT_LISTING, ///< Client is requesting a listing of all public servers.
PACKET_COORDINATOR_GC_LISTING, ///< Game Coordinator returns a listing of all public servers.
PACKET_COORDINATOR_CLIENT_CONNECT, ///< Client wants to connect to a server based on an invite code.
PACKET_COORDINATOR_GC_CONNECTING, ///< Game Coordinator informs the client of the token assigned to the connection attempt.
PACKET_COORDINATOR_SERCLI_CONNECT_FAILED, ///< Client/server tells the Game Coordinator the current connection attempt failed.
PACKET_COORDINATOR_GC_CONNECT_FAILED, ///< Game Coordinator informs client/server it has given up on the connection attempt.
PACKET_COORDINATOR_CLIENT_CONNECTED, ///< Client informs the Game Coordinator the connection with the server is established.
PACKET_COORDINATOR_GC_DIRECT_CONNECT, ///< Game Coordinator tells client to directly connect to the hostname:port of the server.
PACKET_COORDINATOR_GC_STUN_REQUEST, ///< Game Coordinator tells client/server to initiate a STUN request.
PACKET_COORDINATOR_SERCLI_STUN_RESULT, ///< Client/server informs the Game Coordinator of the result of the STUN request.
PACKET_COORDINATOR_GC_STUN_CONNECT, ///< Game Coordinator tells client/server to connect() reusing the STUN local address.
PACKET_COORDINATOR_END, ///< Must ALWAYS be on the end of this list!! (period)
};
/**
* The type of connection the Game Coordinator can detect we have.
*/
enum ConnectionType {
CONNECTION_TYPE_UNKNOWN, ///< The Game Coordinator hasn't informed us yet what type of connection we have.
CONNECTION_TYPE_ISOLATED, ///< The Game Coordinator failed to find a way to connect to your server. Nobody will be able to join.
CONNECTION_TYPE_DIRECT, ///< The Game Coordinator can directly connect to your server.
CONNECTION_TYPE_STUN, ///< The Game Coordinator can connect to your server via a STUN request.
};
/**
* The type of error from the Game Coordinator.
*/
enum NetworkCoordinatorErrorType {
NETWORK_COORDINATOR_ERROR_UNKNOWN, ///< There was an unknown error.
NETWORK_COORDINATOR_ERROR_REGISTRATION_FAILED, ///< Your request for registration failed.
NETWORK_COORDINATOR_ERROR_INVALID_INVITE_CODE, ///< The invite code given is invalid.
};
/** Base socket handler for all Game Coordinator TCP sockets. */
class NetworkCoordinatorSocketHandler : public NetworkTCPSocketHandler {
protected:
bool ReceiveInvalidPacket(PacketCoordinatorType type);
/**
* Game Coordinator indicates there was an error. This can either be a
* permanent error causing the connection to be dropped, or in response
* to a request that is invalid.
*
* uint8 Type of error (see NetworkCoordinatorErrorType).
* string Details of the error.
*
* @param p The packet that was just received.
* @return True upon success, otherwise false.
*/
virtual bool Receive_GC_ERROR(Packet *p);
/**
* Server is starting a multiplayer game and wants to let the
* Game Coordinator know.
*
* uint8 Game Coordinator protocol version.
* uint8 Type of game (see ServerGameType).
* uint16 Local port of the server.
* string Invite code the server wants to use (can be empty; coordinator will assign a new invite code).
* string Secret that belongs to the invite code (empty if invite code is empty).
*
* @param p The packet that was just received.
* @return True upon success, otherwise false.
*/
virtual bool Receive_SERVER_REGISTER(Packet *p);
/**
* Game Coordinator acknowledges the registration.
*
* string Invite code that can be used to join this server.
* string Secret that belongs to the invite code (only needed if reusing the invite code on next SERVER_REGISTER).
* uint8 Type of connection was detected (see ConnectionType).
*
* @param p The packet that was just received.
* @return True upon success, otherwise false.
*/
virtual bool Receive_GC_REGISTER_ACK(Packet *p);
/**
* Send an update of the current state of the server to the Game Coordinator.
*
* uint8 Game Coordinator protocol version.
* Serialized NetworkGameInfo. See game_info.hpp for details.
*
* @param p The packet that was just received.
* @return True upon success, otherwise false.
*/
virtual bool Receive_SERVER_UPDATE(Packet *p);
/**
* Client requests a list of all public servers.
*
* uint8 Game Coordinator protocol version.
* uint8 Game-info version used by this client.
* string Revision of the client.
*
* @param p The packet that was just received.
* @return True upon success, otherwise false.
*/
virtual bool Receive_CLIENT_LISTING(Packet *p);
/**
* Game Coordinator replies with a list of all public servers. Multiple
* of these packets are received after a request till all servers are
* sent over. Last packet will have server count of 0.
*
* uint16 Amount of public servers in this packet.
* For each server:
* string Connection string for this server.
* Serialized NetworkGameInfo. See game_info.hpp for details.
*
* @param p The packet that was just received.
* @return True upon success, otherwise false.
*/
virtual bool Receive_GC_LISTING(Packet *p);
/**
* Client wants to connect to a Server.
*
* uint8 Game Coordinator protocol version.
* string Invite code of the Server to join.
*
* @param p The packet that was just received.
* @return True upon success, otherwise false.
*/
virtual bool Receive_CLIENT_CONNECT(Packet *p);
/**
* Game Coordinator informs the Client under what token it will start the
* attempt to connect the Server and Client together.
*
* string Token to track the current connect request.
* string Invite code of the Server to join.
*
* @param p The packet that was just received.
* @return True upon success, otherwise false.
*/
virtual bool Receive_GC_CONNECTING(Packet *p);
/**
* Client or Server failed to connect to the remote side.
*
* uint8 Game Coordinator protocol version.
* string Token to track the current connect request.
* uint8 Tracking number to track current connect request.
*
* @param p The packet that was just received.
* @return True upon success, otherwise false.
*/
virtual bool Receive_SERCLI_CONNECT_FAILED(Packet *p);
/**
* Game Coordinator informs the Client that it failed to find a way to
* connect the Client to the Server. Any open connections for this token
* should be closed now.
*
* string Token to track the current connect request.
*
* @param p The packet that was just received.
* @return True upon success, otherwise false.
*/
virtual bool Receive_GC_CONNECT_FAILED(Packet *p);
/**
* Client informs the Game Coordinator the connection with the Server is
* established. The Client will disconnect from the Game Coordinator next.
*
* uint8 Game Coordinator protocol version.
* string Token to track the current connect request.
*
* @param p The packet that was just received.
* @return True upon success, otherwise false.
*/
virtual bool Receive_CLIENT_CONNECTED(Packet *p);
/**
* Game Coordinator requests that the Client makes a direct connection to
* the indicated peer, which is a Server.
*
* string Token to track the current connect request.
* uint8 Tracking number to track current connect request.
* string Hostname of the peer.
* uint16 Port of the peer.
*
* @param p The packet that was just received.
* @return True upon success, otherwise false.
*/
virtual bool Receive_GC_DIRECT_CONNECT(Packet *p);
/**
* Game Coordinator requests the client/server to do a STUN request to the
* STUN server. Important is to remember the local port these STUN requests
* are sent from, as this will be needed for later conenctions too.
* The client/server should do multiple STUN requests for every available
* interface that connects to the Internet (e.g., once for IPv4 and once
* for IPv6).
*
* string Token to track the current connect request.
*
* @param p The packet that was just received.
* @return True upon success, otherwise false.
*/
virtual bool Receive_GC_STUN_REQUEST(Packet *p);
/**
* Client/server informs the Game Coordinator the result of a STUN request.
*
* uint8 Game Coordinator protocol version.
* string Token to track the current connect request.
* uint8 Interface number, as given during STUN request.
* bool Whether the STUN connection was successful.
*
* @param p The packet that was just received.
* @return True upon success, otherwise false.
*/
virtual bool Receive_SERCLI_STUN_RESULT(Packet *p);
/**
* Game Coordinator informs the client/server of its STUN peer (the host:ip
* of the other side). It should start a connect() to this peer ASAP with
* the local address as used with the STUN request.
*
* string Token to track the current connect request.
* uint8 Tracking number to track current connect request.
* uint8 Interface number, as given during STUN request.
* string Host of the peer.
* uint16 Port of the peer.
*
* @param p The packet that was just received.
* @return True upon success, otherwise false.
*/
virtual bool Receive_GC_STUN_CONNECT(Packet *p);
bool HandlePacket(Packet *p);
public:
/**
* Create a new cs socket handler for a given cs.
* @param s The socket we are connected with.
*/
NetworkCoordinatorSocketHandler(SOCKET s = INVALID_SOCKET) : NetworkTCPSocketHandler(s) {}
bool ReceivePackets();
};
#endif /* NETWORK_CORE_TCP_COORDINATOR_H */

View File

@@ -30,6 +30,42 @@ class TCPListenHandler {
static SocketList sockets;
public:
static bool ValidateClient(SOCKET s, NetworkAddress &address)
{
/* Check if the client is banned. */
for (const auto &entry : _network_ban_list) {
if (address.IsInNetmask(entry.c_str())) {
Packet p(Tban_packet);
p.PrepareToSend();
DEBUG(net, 2, "[%s] Banned ip tried to join (%s), refused", Tsocket::GetName(), entry.c_str());
if (p.TransferOut<int>(send, s, 0) < 0) {
DEBUG(net, 0, "[%s] send failed: %s", Tsocket::GetName(), NetworkError::GetLast().AsString());
}
closesocket(s);
return false;
}
}
/* Can we handle a new client? */
if (!Tsocket::AllowConnection()) {
/* No more clients allowed?
* Send to the client that we are full! */
Packet p(Tfull_packet);
p.PrepareToSend();
if (p.TransferOut<int>(send, s, 0) < 0) {
DEBUG(net, 0, "[%s] send failed: %s", Tsocket::GetName(), NetworkError::GetLast().AsString());
}
closesocket(s);
return false;
}
return true;
}
/**
* Accepts clients from the sockets.
* @param ls Socket to accept clients from.
@@ -53,41 +89,7 @@ public:
SetNoDelay(s); // XXX error handling?
/* Check if the client is banned */
bool banned = false;
for (const auto &entry : _network_ban_list) {
banned = address.IsInNetmask(entry.c_str());
if (banned) {
Packet p(Tban_packet);
p.PrepareToSend();
DEBUG(net, 2, "[%s] Banned ip tried to join (%s), refused", Tsocket::GetName(), entry.c_str());
if (p.TransferOut<int>(send, s, 0) < 0) {
DEBUG(net, 0, "[%s] send failed: %s", Tsocket::GetName(), NetworkError::GetLast().AsString());
}
closesocket(s);
break;
}
}
/* If this client is banned, continue with next client */
if (banned) continue;
/* Can we handle a new client? */
if (!Tsocket::AllowConnection()) {
/* no more clients allowed?
* Send to the client that we are full! */
Packet p(Tfull_packet);
p.PrepareToSend();
if (p.TransferOut<int>(send, s, 0) < 0) {
DEBUG(net, 0, "[%s] send failed: %s", Tsocket::GetName(), NetworkError::GetLast().AsString());
}
closesocket(s);
continue;
}
if (!Tsocket::ValidateClient(s, address)) continue;
Tsocket::AcceptConnection(s, address);
}
}

View File

@@ -0,0 +1,29 @@
/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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/>.
*/
/**
* @file tcp_stun.cpp Basic functions to receive and send STUN packets.
*/
#include "../../stdafx.h"
#include "../../debug.h"
#include "tcp_stun.h"
#include "../../safeguards.h"
/**
* Helper for logging receiving invalid packets.
* @param type The received packet type.
* @return Always false, as it's an error.
*/
bool NetworkStunSocketHandler::ReceiveInvalidPacket(PacketStunType type)
{
DEBUG(net, 0, "[tcp/stun] Received illegal packet type %u", type);
return false;
}
bool NetworkStunSocketHandler::Receive_SERCLI_STUN(Packet *p) { return this->ReceiveInvalidPacket(PACKET_STUN_SERCLI_STUN); }

View File

@@ -0,0 +1,53 @@
/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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/>.
*/
/**
* @file tcp_stun.h Basic functions to receive and send TCP packets to/from the STUN server.
*/
#ifndef NETWORK_CORE_TCP_STUN_H
#define NETWORK_CORE_TCP_STUN_H
#include "os_abstraction.h"
#include "tcp.h"
#include "packet.h"
/** Enum with all types of TCP STUN packets. The order MUST not be changed. **/
enum PacketStunType {
PACKET_STUN_SERCLI_STUN, ///< Send a STUN request to the STUN server.
PACKET_STUN_END, ///< Must ALWAYS be on the end of this list!! (period)
};
/** Base socket handler for all STUN TCP sockets. */
class NetworkStunSocketHandler : public NetworkTCPSocketHandler {
protected:
bool ReceiveInvalidPacket(PacketStunType type);
/**
* Send a STUN request to the STUN server letting the Game Coordinator know
* what our actually public IP:port is.
*
* uint8 Game Coordinator protocol version.
* string Token to track the current STUN request.
* uint8 Which interface number this is (for example, IPv4 or IPv6).
* The Game Coordinator relays this number back in later packets.
*
* @param p The packet that was just received.
* @return True upon success, otherwise false.
*/
virtual bool Receive_SERCLI_STUN(Packet *p);
public:
/**
* Create a new cs socket handler for a given cs.
* @param s the socket we are connected with.
* @param address IP etc. of the client.
*/
NetworkStunSocketHandler(SOCKET s = INVALID_SOCKET) : NetworkTCPSocketHandler(s) {}
};
#endif /* NETWORK_CORE_TCP_STUN_H */

View File

@@ -194,16 +194,6 @@ void NetworkUDPSocketHandler::HandleUDPPacket(Packet *p, NetworkAddress *client_
switch (this->HasClientQuit() ? PACKET_UDP_END : type) {
case PACKET_UDP_CLIENT_FIND_SERVER: this->Receive_CLIENT_FIND_SERVER(p, client_addr); break;
case PACKET_UDP_SERVER_RESPONSE: this->Receive_SERVER_RESPONSE(p, client_addr); break;
case PACKET_UDP_CLIENT_DETAIL_INFO: this->Receive_CLIENT_DETAIL_INFO(p, client_addr); break;
case PACKET_UDP_SERVER_DETAIL_INFO: this->Receive_SERVER_DETAIL_INFO(p, client_addr); break;
case PACKET_UDP_SERVER_REGISTER: this->Receive_SERVER_REGISTER(p, client_addr); break;
case PACKET_UDP_MASTER_ACK_REGISTER: this->Receive_MASTER_ACK_REGISTER(p, client_addr); break;
case PACKET_UDP_CLIENT_GET_LIST: this->Receive_CLIENT_GET_LIST(p, client_addr); break;
case PACKET_UDP_MASTER_RESPONSE_LIST: this->Receive_MASTER_RESPONSE_LIST(p, client_addr); break;
case PACKET_UDP_SERVER_UNREGISTER: this->Receive_SERVER_UNREGISTER(p, client_addr); break;
case PACKET_UDP_CLIENT_GET_NEWGRFS: this->Receive_CLIENT_GET_NEWGRFS(p, client_addr); break;
case PACKET_UDP_SERVER_NEWGRFS: this->Receive_SERVER_NEWGRFS(p, client_addr); break;
case PACKET_UDP_MASTER_SESSION_KEY: this->Receive_MASTER_SESSION_KEY(p, client_addr); break;
case PACKET_UDP_EX_MULTI: this->Receive_EX_MULTI(p, client_addr); break;
case PACKET_UDP_EX_SERVER_RESPONSE: this->Receive_EX_SERVER_RESPONSE(p, client_addr); break;
@@ -301,13 +291,3 @@ void NetworkUDPSocketHandler::ReceiveInvalidPacket(PacketUDPType type, NetworkAd
void NetworkUDPSocketHandler::Receive_CLIENT_FIND_SERVER(Packet *p, NetworkAddress *client_addr) { this->ReceiveInvalidPacket(PACKET_UDP_CLIENT_FIND_SERVER, client_addr); }
void NetworkUDPSocketHandler::Receive_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr) { this->ReceiveInvalidPacket(PACKET_UDP_SERVER_RESPONSE, client_addr); }
void NetworkUDPSocketHandler::Receive_EX_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr) { this->ReceiveInvalidPacket(PACKET_UDP_EX_SERVER_RESPONSE, client_addr); }
void NetworkUDPSocketHandler::Receive_CLIENT_DETAIL_INFO(Packet *p, NetworkAddress *client_addr) { this->ReceiveInvalidPacket(PACKET_UDP_CLIENT_DETAIL_INFO, client_addr); }
void NetworkUDPSocketHandler::Receive_SERVER_DETAIL_INFO(Packet *p, NetworkAddress *client_addr) { this->ReceiveInvalidPacket(PACKET_UDP_SERVER_DETAIL_INFO, client_addr); }
void NetworkUDPSocketHandler::Receive_SERVER_REGISTER(Packet *p, NetworkAddress *client_addr) { this->ReceiveInvalidPacket(PACKET_UDP_SERVER_REGISTER, client_addr); }
void NetworkUDPSocketHandler::Receive_MASTER_ACK_REGISTER(Packet *p, NetworkAddress *client_addr) { this->ReceiveInvalidPacket(PACKET_UDP_MASTER_ACK_REGISTER, client_addr); }
void NetworkUDPSocketHandler::Receive_CLIENT_GET_LIST(Packet *p, NetworkAddress *client_addr) { this->ReceiveInvalidPacket(PACKET_UDP_CLIENT_GET_LIST, client_addr); }
void NetworkUDPSocketHandler::Receive_MASTER_RESPONSE_LIST(Packet *p, NetworkAddress *client_addr) { this->ReceiveInvalidPacket(PACKET_UDP_MASTER_RESPONSE_LIST, client_addr); }
void NetworkUDPSocketHandler::Receive_SERVER_UNREGISTER(Packet *p, NetworkAddress *client_addr) { this->ReceiveInvalidPacket(PACKET_UDP_SERVER_UNREGISTER, client_addr); }
void NetworkUDPSocketHandler::Receive_CLIENT_GET_NEWGRFS(Packet *p, NetworkAddress *client_addr) { this->ReceiveInvalidPacket(PACKET_UDP_CLIENT_GET_NEWGRFS, client_addr); }
void NetworkUDPSocketHandler::Receive_SERVER_NEWGRFS(Packet *p, NetworkAddress *client_addr) { this->ReceiveInvalidPacket(PACKET_UDP_SERVER_NEWGRFS, client_addr); }
void NetworkUDPSocketHandler::Receive_MASTER_SESSION_KEY(Packet *p, NetworkAddress *client_addr) { this->ReceiveInvalidPacket(PACKET_UDP_MASTER_SESSION_KEY, client_addr); }

View File

@@ -23,31 +23,12 @@
enum PacketUDPType {
PACKET_UDP_CLIENT_FIND_SERVER, ///< Queries a game server for game information
PACKET_UDP_SERVER_RESPONSE, ///< Reply of the game server with game information
PACKET_UDP_CLIENT_DETAIL_INFO, ///< Queries a game server about details of the game, such as companies
PACKET_UDP_SERVER_DETAIL_INFO, ///< Reply of the game server about details of the game, such as companies
PACKET_UDP_SERVER_REGISTER, ///< Packet to register itself to the master server
PACKET_UDP_MASTER_ACK_REGISTER, ///< Packet indicating registration has succeeded
PACKET_UDP_CLIENT_GET_LIST, ///< Request for serverlist from master server
PACKET_UDP_MASTER_RESPONSE_LIST, ///< Response from master server with server ip's + port's
PACKET_UDP_SERVER_UNREGISTER, ///< Request to be removed from the server-list
PACKET_UDP_CLIENT_GET_NEWGRFS, ///< Requests the name for a list of GRFs (GRF_ID and MD5)
PACKET_UDP_SERVER_NEWGRFS, ///< Sends the list of NewGRF's requested.
PACKET_UDP_MASTER_SESSION_KEY, ///< Sends a fresh session key to the client
PACKET_UDP_END, ///< Must ALWAYS be the last non-extended item in the list!! (period)
PACKET_UDP_EX_MULTI = 128, ///< Extended/multi packet type
PACKET_UDP_EX_SERVER_RESPONSE, ///< Reply of the game server with extended game information
};
/** The types of server lists we can get */
enum ServerListType {
SLT_IPv4 = 0, ///< Get the IPv4 addresses
SLT_IPv6 = 1, ///< Get the IPv6 addresses
SLT_AUTODETECT, ///< Autodetect the type based on the connection
SLT_END = SLT_AUTODETECT, ///< End of 'arrays' marker
};
/** Base socket handler for all UDP sockets */
class NetworkUDPSocketHandler : public NetworkSocketHandler {
protected:
@@ -76,8 +57,7 @@ protected:
virtual void Receive_CLIENT_FIND_SERVER(Packet *p, NetworkAddress *client_addr);
/**
* Return of server information to the client.
* Serialized NetworkGameInfo. See game_info.h for details.
* Response to a query letting the client know we are here.
* @param p The received packet.
* @param client_addr The origin of the packet.
*/
@@ -85,120 +65,6 @@ protected:
virtual void Receive_EX_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr);
/**
* Query for detailed information about companies.
* @param p The received packet.
* @param client_addr The origin of the packet.
*/
virtual void Receive_CLIENT_DETAIL_INFO(Packet *p, NetworkAddress *client_addr);
/**
* Reply with detailed company information.
* uint8 Version of the packet.
* uint8 Number of companies.
* For each company:
* uint8 ID of the company.
* string Name of the company.
* uint32 Year the company was inaugurated.
* uint64 Value.
* uint64 Money.
* uint64 Income.
* uint16 Performance (last quarter).
* bool Company is password protected.
* uint16 Number of trains.
* uint16 Number of lorries.
* uint16 Number of busses.
* uint16 Number of planes.
* uint16 Number of ships.
* uint16 Number of train stations.
* uint16 Number of lorry stations.
* uint16 Number of bus stops.
* uint16 Number of airports and heliports.
* uint16 Number of harbours.
* bool Company is an AI.
* @param p The received packet.
* @param client_addr The origin of the packet.
*/
virtual void Receive_SERVER_DETAIL_INFO(Packet *p, NetworkAddress *client_addr);
/**
* Registers the server to the master server.
* string The "welcome" message to root out other binary packets.
* uint8 Version of the protocol.
* uint16 The port to unregister.
* uint64 The session key.
* @param p The received packet.
* @param client_addr The origin of the packet.
*/
virtual void Receive_SERVER_REGISTER(Packet *p, NetworkAddress *client_addr);
/**
* The master server acknowledges the registration.
* @param p The received packet.
* @param client_addr The origin of the packet.
*/
virtual void Receive_MASTER_ACK_REGISTER(Packet *p, NetworkAddress *client_addr);
/**
* The client requests a list of servers.
* uint8 The protocol version.
* uint8 The type of server to look for: IPv4, IPv6 or based on the received packet.
* @param p The received packet.
* @param client_addr The origin of the packet.
*/
virtual void Receive_CLIENT_GET_LIST(Packet *p, NetworkAddress *client_addr);
/**
* The server sends a list of servers.
* uint8 The protocol version.
* For each server:
* 4 or 16 bytes of IPv4 or IPv6 address.
* uint8 The port.
* @param p The received packet.
* @param client_addr The origin of the packet.
*/
virtual void Receive_MASTER_RESPONSE_LIST(Packet *p, NetworkAddress *client_addr);
/**
* A server unregisters itself at the master server.
* uint8 Version of the protocol.
* uint16 The port to unregister.
* @param p The received packet.
* @param client_addr The origin of the packet.
*/
virtual void Receive_SERVER_UNREGISTER(Packet *p, NetworkAddress *client_addr);
/**
* The client requests information about some NewGRFs.
* uint8 The number of NewGRFs information is requested about.
* For each NewGRF:
* uint32 The GRFID.
* 16 * uint8 MD5 checksum of the GRF.
* @param p The received packet.
* @param client_addr The origin of the packet.
*/
virtual void Receive_CLIENT_GET_NEWGRFS(Packet *p, NetworkAddress *client_addr);
/**
* The server returns information about some NewGRFs.
* uint8 The number of NewGRFs information is requested about.
* For each NewGRF:
* uint32 The GRFID.
* 16 * uint8 MD5 checksum of the GRF.
* string The name of the NewGRF.
* @param p The received packet.
* @param client_addr The origin of the packet.
*/
virtual void Receive_SERVER_NEWGRFS(Packet *p, NetworkAddress *client_addr);
/**
* The master server sends us a session key.
* uint64 The session key.
* @param p The received packet.
* @param client_addr The origin of the packet.
*/
virtual void Receive_MASTER_SESSION_KEY(Packet *p, NetworkAddress *client_addr);
void HandleUDPPacket(Packet *p, NetworkAddress *client_addr);
virtual void Receive_EX_MULTI(Packet *p, NetworkAddress *client_addr);