Update to 12.0-beta1
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
add_files(
|
||||
address.cpp
|
||||
address.h
|
||||
config.cpp
|
||||
config.h
|
||||
core.cpp
|
||||
core.h
|
||||
@@ -20,11 +21,17 @@ 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
|
||||
tcp_turn.cpp
|
||||
tcp_turn.h
|
||||
udp.cpp
|
||||
udp.h
|
||||
)
|
||||
|
||||
+112
-110
@@ -10,6 +10,7 @@
|
||||
#include "../../stdafx.h"
|
||||
|
||||
#include "address.h"
|
||||
#include "../network_internal.h"
|
||||
#include "../../debug.h"
|
||||
|
||||
#include "../../safeguards.h"
|
||||
@@ -19,11 +20,13 @@
|
||||
* IPv4 dotted representation is given.
|
||||
* @return the hostname
|
||||
*/
|
||||
const char *NetworkAddress::GetHostname()
|
||||
const std::string &NetworkAddress::GetHostname()
|
||||
{
|
||||
if (StrEmpty(this->hostname) && this->address.ss_family != AF_UNSPEC) {
|
||||
if (this->hostname.empty() && this->address.ss_family != AF_UNSPEC) {
|
||||
assert(this->address_length != 0);
|
||||
getnameinfo((struct sockaddr *)&this->address, this->address_length, this->hostname, sizeof(this->hostname), nullptr, 0, NI_NUMERICHOST);
|
||||
char buffer[NETWORK_HOSTNAME_LENGTH];
|
||||
getnameinfo((struct sockaddr *)&this->address, this->address_length, buffer, sizeof(buffer), nullptr, 0, NI_NUMERICHOST);
|
||||
this->hostname = buffer;
|
||||
}
|
||||
return this->hostname;
|
||||
}
|
||||
@@ -69,26 +72,17 @@ void NetworkAddress::SetPort(uint16 port)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the address as a string, e.g. 127.0.0.1:12345.
|
||||
* @param buffer the buffer to write to
|
||||
* @param last the last element in the buffer
|
||||
* @param with_family whether to add the family (e.g. IPvX).
|
||||
* Helper to get the formatting string of an address for a given family.
|
||||
* @param family The family to get the address format for.
|
||||
* @param with_family Whether to add the familty to the address (e.g. IPv4).
|
||||
* @return The format string for the address.
|
||||
*/
|
||||
void NetworkAddress::GetAddressAsString(char *buffer, const char *last, bool with_family)
|
||||
static const char *GetAddressFormatString(uint16 family, bool with_family)
|
||||
{
|
||||
if (this->GetAddress()->ss_family == AF_INET6) buffer = strecpy(buffer, "[", last);
|
||||
buffer = strecpy(buffer, this->GetHostname(), last);
|
||||
if (this->GetAddress()->ss_family == AF_INET6) buffer = strecpy(buffer, "]", last);
|
||||
buffer += seprintf(buffer, last, ":%d", this->GetPort());
|
||||
|
||||
if (with_family) {
|
||||
char family;
|
||||
switch (this->address.ss_family) {
|
||||
case AF_INET: family = '4'; break;
|
||||
case AF_INET6: family = '6'; break;
|
||||
default: family = '?'; break;
|
||||
}
|
||||
seprintf(buffer, last, " (IPv%c)", family);
|
||||
switch (family) {
|
||||
case AF_INET: return with_family ? "{}:{} (IPv4)" : "{}:{}";
|
||||
case AF_INET6: return with_family ? "[{}]:{} (IPv6)" : "[{}]:{}";
|
||||
default: return with_family ? "{}:{} (IPv?)" : "{}:{}";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,10 +93,7 @@ void NetworkAddress::GetAddressAsString(char *buffer, const char *last, bool wit
|
||||
*/
|
||||
std::string NetworkAddress::GetAddressAsString(bool with_family)
|
||||
{
|
||||
/* 6 = for the : and 5 for the decimal port number */
|
||||
char buf[NETWORK_HOSTNAME_LENGTH + 6 + 7];
|
||||
this->GetAddressAsString(buf, lastof(buf), with_family);
|
||||
return buf;
|
||||
return fmt::format(GetAddressFormatString(this->GetAddress()->ss_family, with_family), this->GetHostname(), this->GetPort());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -153,7 +144,7 @@ bool NetworkAddress::IsFamily(int family)
|
||||
* @note netmask without /n assumes all bits need to match.
|
||||
* @return true if this IP is within the netmask.
|
||||
*/
|
||||
bool NetworkAddress::IsInNetmask(const char *netmask)
|
||||
bool NetworkAddress::IsInNetmask(const std::string &netmask)
|
||||
{
|
||||
/* Resolve it if we didn't do it already */
|
||||
if (!this->IsResolved()) this->GetAddress();
|
||||
@@ -163,16 +154,15 @@ bool NetworkAddress::IsInNetmask(const char *netmask)
|
||||
NetworkAddress mask_address;
|
||||
|
||||
/* Check for CIDR separator */
|
||||
const char *chr_cidr = strchr(netmask, '/');
|
||||
if (chr_cidr != nullptr) {
|
||||
int tmp_cidr = atoi(chr_cidr + 1);
|
||||
auto cidr_separator_location = netmask.find('/');
|
||||
if (cidr_separator_location != std::string::npos) {
|
||||
int tmp_cidr = atoi(netmask.substr(cidr_separator_location + 1).c_str());
|
||||
|
||||
/* Invalid CIDR, treat as single host */
|
||||
if (tmp_cidr > 0 || tmp_cidr < cidr) cidr = tmp_cidr;
|
||||
if (tmp_cidr > 0 && tmp_cidr < cidr) cidr = tmp_cidr;
|
||||
|
||||
/* Remove the / so that NetworkAddress works on the IP portion */
|
||||
std::string ip_str(netmask, chr_cidr - netmask);
|
||||
mask_address = NetworkAddress(ip_str.c_str(), 0, this->address.ss_family);
|
||||
mask_address = NetworkAddress(netmask.substr(0, cidr_separator_location), 0, this->address.ss_family);
|
||||
} else {
|
||||
mask_address = NetworkAddress(netmask, 0, this->address.ss_family);
|
||||
}
|
||||
@@ -232,31 +222,31 @@ SOCKET NetworkAddress::Resolve(int family, int socktype, int flags, SocketList *
|
||||
/* Setting both hostname to nullptr and port to 0 is not allowed.
|
||||
* As port 0 means bind to any port, the other must mean that
|
||||
* we want to bind to 'all' IPs. */
|
||||
if (StrEmpty(this->hostname) && this->address_length == 0 && this->GetPort() == 0) {
|
||||
if (this->hostname.empty() && this->address_length == 0 && this->GetPort() == 0) {
|
||||
reset_hostname = true;
|
||||
int fam = this->address.ss_family;
|
||||
if (fam == AF_UNSPEC) fam = family;
|
||||
strecpy(this->hostname, fam == AF_INET ? "0.0.0.0" : "::", lastof(this->hostname));
|
||||
this->hostname = fam == AF_INET ? "0.0.0.0" : "::";
|
||||
}
|
||||
|
||||
static bool _resolve_timeout_error_message_shown = false;
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
int e = getaddrinfo(StrEmpty(this->hostname) ? nullptr : this->hostname, port_name, &hints, &ai);
|
||||
int e = getaddrinfo(this->hostname.empty() ? nullptr : this->hostname.c_str(), port_name, &hints, &ai);
|
||||
auto end = std::chrono::steady_clock::now();
|
||||
std::chrono::seconds duration = std::chrono::duration_cast<std::chrono::seconds>(end - start);
|
||||
if (!_resolve_timeout_error_message_shown && duration >= std::chrono::seconds(5)) {
|
||||
DEBUG(net, 0, "getaddrinfo for hostname \"%s\", port %s, address family %s and socket type %s took %i seconds",
|
||||
this->hostname, port_name, AddressFamilyAsString(family), SocketTypeAsString(socktype), (int)duration.count());
|
||||
DEBUG(net, 0, " this is likely an issue in the DNS name resolver's configuration causing it to time out");
|
||||
Debug(net, 0, "getaddrinfo for hostname \"{}\", port {}, address family {} and socket type {} took {} seconds",
|
||||
this->hostname, port_name, AddressFamilyAsString(family), SocketTypeAsString(socktype), duration.count());
|
||||
Debug(net, 0, " this is likely an issue in the DNS name resolver's configuration causing it to time out");
|
||||
_resolve_timeout_error_message_shown = true;
|
||||
}
|
||||
|
||||
|
||||
if (reset_hostname) strecpy(this->hostname, "", lastof(this->hostname));
|
||||
if (reset_hostname) this->hostname.clear();
|
||||
|
||||
if (e != 0) {
|
||||
if (func != ResolveLoopProc) {
|
||||
DEBUG(net, 0, "getaddrinfo for hostname \"%s\", port %s, address family %s and socket type %s failed: %s",
|
||||
Debug(net, 0, "getaddrinfo for hostname \"{}\", port {}, address family {} and socket type {} failed: {}",
|
||||
this->hostname, port_name, AddressFamilyAsString(family), SocketTypeAsString(socktype), FS2OTTD(gai_strerror(e)));
|
||||
}
|
||||
return INVALID_SOCKET;
|
||||
@@ -302,59 +292,6 @@ SOCKET NetworkAddress::Resolve(int family, int socktype, int flags, SocketList *
|
||||
return sock;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to resolve a connected socket.
|
||||
* @param runp information about the socket to try not
|
||||
* @return the opened socket or INVALID_SOCKET
|
||||
*/
|
||||
static SOCKET ConnectLoopProc(addrinfo *runp)
|
||||
{
|
||||
const char *type = NetworkAddress::SocketTypeAsString(runp->ai_socktype);
|
||||
const char *family = NetworkAddress::AddressFamilyAsString(runp->ai_family);
|
||||
char address[NETWORK_HOSTNAME_LENGTH + 6 + 7];
|
||||
NetworkAddress(runp->ai_addr, (int)runp->ai_addrlen).GetAddressAsString(address, lastof(address));
|
||||
|
||||
SOCKET sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
|
||||
if (sock == INVALID_SOCKET) {
|
||||
DEBUG(net, 1, "[%s] could not create %s socket: %s", type, family, NetworkError::GetLast().AsString());
|
||||
return INVALID_SOCKET;
|
||||
}
|
||||
|
||||
if (!SetNoDelay(sock)) DEBUG(net, 1, "[%s] setting TCP_NODELAY failed", type);
|
||||
|
||||
int err = connect(sock, runp->ai_addr, (int)runp->ai_addrlen);
|
||||
#ifdef __EMSCRIPTEN__
|
||||
/* Emscripten is asynchronous, and as such a connect() is still in
|
||||
* progress by the time the call returns. */
|
||||
if (err != 0 && !NetworkError::GetLast().IsConnectInProgress())
|
||||
#else
|
||||
if (err != 0)
|
||||
#endif
|
||||
{
|
||||
DEBUG(net, 1, "[%s] could not connect %s socket: %s", type, family, NetworkError::GetLast().AsString());
|
||||
closesocket(sock);
|
||||
return INVALID_SOCKET;
|
||||
}
|
||||
|
||||
/* Connection succeeded */
|
||||
if (!SetNonBlocking(sock)) DEBUG(net, 0, "[%s] setting non-blocking mode failed", type);
|
||||
|
||||
DEBUG(net, 1, "[%s] connected to %s", type, address);
|
||||
|
||||
return sock;
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to the given address.
|
||||
* @return the connected socket or INVALID_SOCKET.
|
||||
*/
|
||||
SOCKET NetworkAddress::Connect()
|
||||
{
|
||||
DEBUG(net, 1, "Connecting to %s", this->GetAddressAsString().c_str());
|
||||
|
||||
return this->Resolve(AF_UNSPEC, SOCK_STREAM, AI_ADDRCONFIG, nullptr, ConnectLoopProc);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to resolve a listening.
|
||||
* @param runp information about the socket to try not
|
||||
@@ -362,50 +299,51 @@ SOCKET NetworkAddress::Connect()
|
||||
*/
|
||||
static SOCKET ListenLoopProc(addrinfo *runp)
|
||||
{
|
||||
const char *type = NetworkAddress::SocketTypeAsString(runp->ai_socktype);
|
||||
const char *family = NetworkAddress::AddressFamilyAsString(runp->ai_family);
|
||||
char address[NETWORK_HOSTNAME_LENGTH + 6 + 7];
|
||||
NetworkAddress(runp->ai_addr, (int)runp->ai_addrlen).GetAddressAsString(address, lastof(address));
|
||||
std::string address = NetworkAddress(runp->ai_addr, (int)runp->ai_addrlen).GetAddressAsString();
|
||||
|
||||
SOCKET sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
|
||||
if (sock == INVALID_SOCKET) {
|
||||
DEBUG(net, 0, "[%s] could not create %s socket on port %s: %s", type, family, address, NetworkError::GetLast().AsString());
|
||||
const char *type = NetworkAddress::SocketTypeAsString(runp->ai_socktype);
|
||||
const char *family = NetworkAddress::AddressFamilyAsString(runp->ai_family);
|
||||
Debug(net, 0, "Could not create {} {} socket: {}", type, family, NetworkError::GetLast().AsString());
|
||||
return INVALID_SOCKET;
|
||||
}
|
||||
|
||||
if (runp->ai_socktype == SOCK_STREAM && !SetNoDelay(sock)) {
|
||||
DEBUG(net, 3, "[%s] setting TCP_NODELAY failed for port %s", type, address);
|
||||
Debug(net, 1, "Setting no-delay mode failed: {}", 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) {
|
||||
DEBUG(net, 3, "[%s] could not set reusable %s sockets for port %s: %s", type, family, address, NetworkError::GetLast().AsString());
|
||||
if (!SetReusePort(sock)) {
|
||||
Debug(net, 0, "Setting reuse-address mode failed: {}", 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, "[%s] could not disable IPv4 over IPv6 on port %s: %s", type, address, NetworkError::GetLast().AsString());
|
||||
Debug(net, 3, "Could not disable IPv4 over IPv6: {}", NetworkError::GetLast().AsString());
|
||||
}
|
||||
#endif
|
||||
|
||||
if (bind(sock, runp->ai_addr, (int)runp->ai_addrlen) != 0) {
|
||||
DEBUG(net, 1, "[%s] could not bind on %s port %s: %s", type, family, address, NetworkError::GetLast().AsString());
|
||||
Debug(net, 0, "Could not bind socket on {}: {}", address, NetworkError::GetLast().AsString());
|
||||
closesocket(sock);
|
||||
return INVALID_SOCKET;
|
||||
}
|
||||
|
||||
if (runp->ai_socktype != SOCK_DGRAM && listen(sock, 1) != 0) {
|
||||
DEBUG(net, 1, "[%s] could not listen at %s port %s: %s", type, family, address, NetworkError::GetLast().AsString());
|
||||
Debug(net, 0, "Could not listen on socket: {}", NetworkError::GetLast().AsString());
|
||||
closesocket(sock);
|
||||
return INVALID_SOCKET;
|
||||
}
|
||||
|
||||
/* Connection succeeded */
|
||||
if (!SetNonBlocking(sock)) DEBUG(net, 0, "[%s] setting non-blocking mode failed for %s port %s", type, family, address);
|
||||
|
||||
DEBUG(net, 1, "[%s] listening on %s port %s", type, family, address);
|
||||
if (!SetNonBlocking(sock)) {
|
||||
Debug(net, 0, "Setting non-blocking mode failed: {}", NetworkError::GetLast().AsString());
|
||||
}
|
||||
|
||||
Debug(net, 3, "Listening on {}", address);
|
||||
return sock;
|
||||
}
|
||||
|
||||
@@ -418,11 +356,11 @@ void NetworkAddress::Listen(int socktype, SocketList *sockets)
|
||||
{
|
||||
assert(sockets != nullptr);
|
||||
|
||||
/* Setting both hostname to nullptr and port to 0 is not allowed.
|
||||
/* Setting both hostname to "" and port to 0 is not allowed.
|
||||
* As port 0 means bind to any port, the other must mean that
|
||||
* we want to bind to 'all' IPs. */
|
||||
if (this->address_length == 0 && this->address.ss_family == AF_UNSPEC &&
|
||||
StrEmpty(this->hostname) && this->GetPort() == 0) {
|
||||
this->hostname.empty() && this->GetPort() == 0) {
|
||||
this->Resolve(AF_INET, socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
|
||||
this->Resolve(AF_INET6, socktype, AI_ADDRCONFIG | AI_PASSIVE, sockets, ListenLoopProc);
|
||||
} else {
|
||||
@@ -460,3 +398,67 @@ void NetworkAddress::Listen(int socktype, SocketList *sockets)
|
||||
default: return "unsupported";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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: {}", 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: {}", 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.
|
||||
* @return The string representation of the peer name.
|
||||
*/
|
||||
/* static */ const std::string NetworkAddress::GetPeerName(SOCKET sock)
|
||||
{
|
||||
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));
|
||||
}
|
||||
|
||||
+50
-17
@@ -12,6 +12,7 @@
|
||||
|
||||
#include "os_abstraction.h"
|
||||
#include "config.h"
|
||||
#include "../../company_type.h"
|
||||
#include "../../string_func.h"
|
||||
#include "../../core/smallmap_type.hpp"
|
||||
|
||||
@@ -28,10 +29,10 @@ typedef SmallMap<NetworkAddress, SOCKET> SocketList; ///< Type for a mapping
|
||||
*/
|
||||
class NetworkAddress {
|
||||
private:
|
||||
char hostname[NETWORK_HOSTNAME_LENGTH]; ///< The hostname
|
||||
int address_length; ///< The length of the resolved address
|
||||
sockaddr_storage address; ///< The resolved address
|
||||
bool resolved; ///< Whether the address has been (tried to be) resolved
|
||||
std::string hostname; ///< The hostname
|
||||
int address_length; ///< The length of the resolved address
|
||||
sockaddr_storage address; ///< The resolved address
|
||||
bool resolved; ///< Whether the address has been (tried to be) resolved
|
||||
|
||||
/**
|
||||
* Helper function to resolve something to a socket.
|
||||
@@ -52,7 +53,6 @@ public:
|
||||
address(address),
|
||||
resolved(address_length != 0)
|
||||
{
|
||||
*this->hostname = '\0';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -64,7 +64,6 @@ public:
|
||||
address_length(address_length),
|
||||
resolved(address_length != 0)
|
||||
{
|
||||
*this->hostname = '\0';
|
||||
memset(&this->address, 0, sizeof(this->address));
|
||||
memcpy(&this->address, address, address_length);
|
||||
}
|
||||
@@ -75,24 +74,22 @@ public:
|
||||
* @param port the port
|
||||
* @param family the address family
|
||||
*/
|
||||
NetworkAddress(const char *hostname = "", uint16 port = 0, int family = AF_UNSPEC) :
|
||||
NetworkAddress(std::string_view hostname = "", uint16 port = 0, int family = AF_UNSPEC) :
|
||||
address_length(0),
|
||||
resolved(false)
|
||||
{
|
||||
/* Also handle IPv6 bracket enclosed hostnames */
|
||||
if (StrEmpty(hostname)) hostname = "";
|
||||
if (*hostname == '[') hostname++;
|
||||
strecpy(this->hostname, StrEmpty(hostname) ? "" : hostname, lastof(this->hostname));
|
||||
char *tmp = strrchr(this->hostname, ']');
|
||||
if (tmp != nullptr) *tmp = '\0';
|
||||
if (!hostname.empty() && hostname.front() == '[' && hostname.back() == ']') {
|
||||
hostname.remove_prefix(1);
|
||||
hostname.remove_suffix(1);
|
||||
}
|
||||
this->hostname = hostname;
|
||||
|
||||
memset(&this->address, 0, sizeof(this->address));
|
||||
this->address.ss_family = family;
|
||||
this->SetPort(port);
|
||||
}
|
||||
|
||||
const char *GetHostname();
|
||||
void GetAddressAsString(char *buffer, const char *last, bool with_family = true);
|
||||
const std::string &GetHostname();
|
||||
std::string GetAddressAsString(bool with_family = true);
|
||||
const sockaddr_storage *GetAddress();
|
||||
|
||||
@@ -120,7 +117,7 @@ public:
|
||||
}
|
||||
|
||||
bool IsFamily(int family);
|
||||
bool IsInNetmask(const char *netmask);
|
||||
bool IsInNetmask(const std::string &netmask);
|
||||
|
||||
/**
|
||||
* Compare the address of this class with the address of another.
|
||||
@@ -174,11 +171,47 @@ public:
|
||||
return this->CompareTo(address) < 0;
|
||||
}
|
||||
|
||||
SOCKET Connect();
|
||||
void Listen(int socktype, SocketList *sockets);
|
||||
|
||||
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);
|
||||
};
|
||||
|
||||
/**
|
||||
* 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 */
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
+70
-45
@@ -12,61 +12,86 @@
|
||||
#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_TURN_SERVER_PORT = 3974; ///< The default port of the TURN 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 SEND_MTU = 1460; ///< Number of bytes we can pack in a single packet
|
||||
static const uint16 UDP_MTU = 1460; ///< Number of bytes we can pack in a single UDP packet
|
||||
/*
|
||||
* 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.
|
||||
*
|
||||
* Packets up to 32 KiB have the high bit not set:
|
||||
* 00000000 00000000 0bbbbbbb aaaaaaaa -> aaaaaaaa 0bbbbbbb
|
||||
* Send_uint16(GB(size, 0, 15)
|
||||
*
|
||||
* Packets up to 1 GiB, first uint16 has high bit set so it knows to read a
|
||||
* next uint16 for the remaining bits of the size.
|
||||
* 00dddddd cccccccc bbbbbbbb aaaaaaaa -> cccccccc 10dddddd aaaaaaaa bbbbbbbb
|
||||
* 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 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 = 6; ///< 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 = 5; ///< 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_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_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 = SEND_MTU - 3; ///< The maximum length of a gamescript json string, in bytes including '\0'. Must not be longer than SEND_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_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_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 = 32; ///< 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 SEND_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_NUM_LANGUAGES = 36; ///< Number of known languages (to the network protocol) + 1 for 'any'.
|
||||
|
||||
/**
|
||||
* The number of landscapes in OpenTTD.
|
||||
* This number must be equal to NUM_LANDSCAPE, but as this number is used
|
||||
* within the network code and that the network code is shared with the
|
||||
* masterserver/updater, it has to be declared in here too. In network.cpp
|
||||
* 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_MAX_GRF_COUNT = 255;
|
||||
|
||||
#endif /* NETWORK_CORE_CONFIG_H */
|
||||
|
||||
@@ -27,9 +27,9 @@ bool NetworkCoreInitialize()
|
||||
#ifdef _WIN32
|
||||
{
|
||||
WSADATA wsa;
|
||||
DEBUG(net, 3, "[core] loading windows socket library");
|
||||
Debug(net, 5, "Loading windows socket library");
|
||||
if (WSAStartup(MAKEWORD(2, 0), &wsa) != 0) {
|
||||
DEBUG(net, 0, "[core] WSAStartup failed, network unavailable");
|
||||
Debug(net, 0, "WSAStartup failed, network unavailable");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
+20
-21
@@ -20,16 +20,17 @@ void NetworkCoreShutdown();
|
||||
|
||||
/** Status of a network client; reasons why a client has quit */
|
||||
enum NetworkRecvStatus {
|
||||
NETWORK_RECV_STATUS_OKAY, ///< Everything is okay
|
||||
NETWORK_RECV_STATUS_DESYNC, ///< A desync did occur
|
||||
NETWORK_RECV_STATUS_NEWGRF_MISMATCH, ///< We did not have the required NewGRFs
|
||||
NETWORK_RECV_STATUS_SAVEGAME, ///< Something went wrong (down)loading the savegame
|
||||
NETWORK_RECV_STATUS_CONN_LOST, ///< The connection is 'just' lost
|
||||
NETWORK_RECV_STATUS_MALFORMED_PACKET, ///< We apparently send a malformed packet
|
||||
NETWORK_RECV_STATUS_SERVER_ERROR, ///< The server told us we made an error
|
||||
NETWORK_RECV_STATUS_SERVER_FULL, ///< The server is full
|
||||
NETWORK_RECV_STATUS_SERVER_BANNED, ///< The server has banned us
|
||||
NETWORK_RECV_STATUS_CLOSE_QUERY, ///< Done querying the server
|
||||
NETWORK_RECV_STATUS_OKAY, ///< Everything is okay.
|
||||
NETWORK_RECV_STATUS_DESYNC, ///< A desync did occur.
|
||||
NETWORK_RECV_STATUS_NEWGRF_MISMATCH, ///< We did not have the required NewGRFs.
|
||||
NETWORK_RECV_STATUS_SAVEGAME, ///< Something went wrong (down)loading the savegame.
|
||||
NETWORK_RECV_STATUS_CLIENT_QUIT, ///< The connection is lost gracefully. Other clients are already informed of this leaving client.
|
||||
NETWORK_RECV_STATUS_MALFORMED_PACKET, ///< We apparently send a malformed packet.
|
||||
NETWORK_RECV_STATUS_SERVER_ERROR, ///< The server told us we made an error.
|
||||
NETWORK_RECV_STATUS_SERVER_FULL, ///< The server is full.
|
||||
NETWORK_RECV_STATUS_SERVER_BANNED, ///< The server has banned us.
|
||||
NETWORK_RECV_STATUS_CLOSE_QUERY, ///< Done querying the server.
|
||||
NETWORK_RECV_STATUS_CONNECTION_LOST, ///< The connection is lost unexpectedly.
|
||||
};
|
||||
|
||||
/** Forward declaration due to circular dependencies */
|
||||
@@ -39,24 +40,24 @@ struct Packet;
|
||||
* SocketHandler for all network sockets in OpenTTD.
|
||||
*/
|
||||
class NetworkSocketHandler {
|
||||
private:
|
||||
bool has_quit; ///< Whether the current client has quit/send a bad packet
|
||||
|
||||
public:
|
||||
/** Create a new unbound socket */
|
||||
NetworkSocketHandler() { this->has_quit = false; }
|
||||
|
||||
/** Close the socket when destructing the socket handler */
|
||||
virtual ~NetworkSocketHandler() { this->Close(); }
|
||||
|
||||
/** Really close the socket */
|
||||
virtual void Close() {}
|
||||
virtual ~NetworkSocketHandler() {}
|
||||
|
||||
/**
|
||||
* Close the current connection; for TCP this will be mostly equivalent
|
||||
* to Close(), but for UDP it just means the packet has to be dropped.
|
||||
* @param error Whether we quit under an error condition or not.
|
||||
* @return new status of the connection.
|
||||
* Mark the connection as closed.
|
||||
*
|
||||
* This doesn't mean the actual connection is closed, but just that we
|
||||
* act like it is. This is useful for UDP, which doesn't normally close
|
||||
* a socket, but its handler might need to pretend it does.
|
||||
*/
|
||||
virtual NetworkRecvStatus CloseConnection(bool error = true) { this->has_quit = true; return NETWORK_RECV_STATUS_OKAY; }
|
||||
void MarkClosed() { this->has_quit = true; }
|
||||
|
||||
/**
|
||||
* Whether the current client connected to the socket has quit.
|
||||
@@ -70,8 +71,6 @@ public:
|
||||
* Reopen the socket so we can send/receive stuff again.
|
||||
*/
|
||||
void Reopen() { this->has_quit = false; }
|
||||
|
||||
void SendCompanyInformation(Packet *p, const struct Company *c, const struct NetworkCompanyStats *stats, uint max_len = NETWORK_COMPANY_NAME_LENGTH);
|
||||
};
|
||||
|
||||
#endif /* NETWORK_CORE_CORE_H */
|
||||
|
||||
+155
-86
@@ -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"
|
||||
@@ -36,42 +38,33 @@ NetworkServerGameInfo _network_game_info; ///< Information about our game.
|
||||
|
||||
/**
|
||||
* Get the network version string used by this build.
|
||||
* The returned string is guaranteed to be at most NETWORK_REVISON_LENGTH bytes.
|
||||
* The returned string is guaranteed to be at most NETWORK_REVISON_LENGTH bytes including '\0' terminator.
|
||||
*/
|
||||
const char *GetNetworkRevisionString()
|
||||
std::string_view GetNetworkRevisionString()
|
||||
{
|
||||
/* This will be allocated on heap and never free'd, but only once so not a "real" leak. */
|
||||
static char *network_revision = nullptr;
|
||||
static std::string network_revision;
|
||||
|
||||
if (!network_revision) {
|
||||
/* Start by taking a chance on the full revision string. */
|
||||
network_revision = stredup(_openttd_revision);
|
||||
/* Ensure it's not longer than the packet buffer length. */
|
||||
if (strlen(network_revision) >= NETWORK_REVISION_LENGTH) network_revision[NETWORK_REVISION_LENGTH - 1] = '\0';
|
||||
|
||||
/* Tag names are not mangled further. */
|
||||
if (network_revision.empty()) {
|
||||
network_revision = _openttd_revision;
|
||||
if (_openttd_revision_tagged) {
|
||||
DEBUG(net, 1, "Network revision name is '%s'", network_revision);
|
||||
return network_revision;
|
||||
}
|
||||
/* Tagged; do not mangle further, though ensure it's not too long. */
|
||||
if (network_revision.size() >= NETWORK_REVISION_LENGTH) network_revision.resize(NETWORK_REVISION_LENGTH - 1);
|
||||
} else {
|
||||
/* Not tagged; add the githash suffix while ensuring the string does not become too long. */
|
||||
assert(_openttd_revision_modified < 3);
|
||||
std::string githash_suffix = fmt::format("-{}{}", "gum"[_openttd_revision_modified], _openttd_revision_hash);
|
||||
if (githash_suffix.size() > GITHASH_SUFFIX_LEN) githash_suffix.resize(GITHASH_SUFFIX_LEN);
|
||||
|
||||
/* Prepare a prefix of the git hash.
|
||||
* Size is length + 1 for terminator, +2 for -g prefix. */
|
||||
assert(_openttd_revision_modified < 3);
|
||||
char githash_suffix[GITHASH_SUFFIX_LEN + 1] = "-";
|
||||
githash_suffix[1] = "gum"[_openttd_revision_modified];
|
||||
for (uint i = 2; i < GITHASH_SUFFIX_LEN; i++) {
|
||||
githash_suffix[i] = _openttd_revision_hash[i-2];
|
||||
}
|
||||
/* Where did the hash start in the original string? Overwrite from that position, unless that would create a too long string. */
|
||||
size_t hash_end = network_revision.find_last_of('-');
|
||||
if (hash_end == std::string::npos) hash_end = network_revision.size();
|
||||
if (hash_end + githash_suffix.size() >= NETWORK_REVISION_LENGTH) hash_end = NETWORK_REVISION_LENGTH - githash_suffix.size() - 1;
|
||||
|
||||
/* Where did the hash start in the original string?
|
||||
* Overwrite from that position, unless that would go past end of packet buffer length. */
|
||||
ptrdiff_t hashofs = strrchr(_openttd_revision, '-') - _openttd_revision;
|
||||
if (hashofs + strlen(githash_suffix) + 1 > NETWORK_REVISION_LENGTH) hashofs = strlen(network_revision) - strlen(githash_suffix);
|
||||
/* Replace the git hash in revision string. */
|
||||
strecpy(network_revision + hashofs, githash_suffix, network_revision + NETWORK_REVISION_LENGTH);
|
||||
assert(strlen(network_revision) < NETWORK_REVISION_LENGTH); // strlen does not include terminator, constant does, hence strictly less than
|
||||
DEBUG(net, 1, "Network revision name is '%s'", network_revision);
|
||||
/* Replace the git hash in revision string. */
|
||||
network_revision.replace(hash_end, std::string::npos, githash_suffix);
|
||||
}
|
||||
assert(network_revision.size() < NETWORK_REVISION_LENGTH); // size does not include terminator, constant does, hence strictly less than
|
||||
Debug(net, 3, "Network revision name: {}", network_revision);
|
||||
}
|
||||
|
||||
return network_revision;
|
||||
@@ -79,12 +72,14 @@ const char *GetNetworkRevisionString()
|
||||
|
||||
/**
|
||||
* Extract the git hash from the revision string.
|
||||
* @param revstr The revision string (formatted as DATE-BRANCH-GITHASH).
|
||||
* @param revision_string The revision string (formatted as DATE-BRANCH-GITHASH).
|
||||
* @return The git has part of the revision.
|
||||
*/
|
||||
static const char *ExtractNetworkRevisionHash(const char *revstr)
|
||||
static std::string_view ExtractNetworkRevisionHash(std::string_view revision_string)
|
||||
{
|
||||
return strrchr(revstr, '-');
|
||||
size_t index = revision_string.find_last_of('-');
|
||||
if (index == std::string::npos) return {};
|
||||
return revision_string.substr(index);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -92,47 +87,70 @@ static const char *ExtractNetworkRevisionHash(const char *revstr)
|
||||
* First tries to match the full string, if that fails, attempts to compare just git hashes.
|
||||
* @param other the version string to compare to
|
||||
*/
|
||||
bool IsNetworkCompatibleVersion(const char *other)
|
||||
bool IsNetworkCompatibleVersion(std::string_view other)
|
||||
{
|
||||
if (strncmp(GetNetworkRevisionString(), other, NETWORK_REVISION_LENGTH - 1) == 0) return true;
|
||||
if (GetNetworkRevisionString() == other) return true;
|
||||
|
||||
/* If this version is tagged, then the revision string must be a complete match,
|
||||
* since there is no git hash suffix in it.
|
||||
* This is needed to avoid situations like "1.9.0-beta1" comparing equal to "2.0.0-beta1". */
|
||||
if (_openttd_revision_tagged) return false;
|
||||
|
||||
const char *hash1 = ExtractNetworkRevisionHash(GetNetworkRevisionString());
|
||||
const char *hash2 = ExtractNetworkRevisionHash(other);
|
||||
return hash1 != nullptr && hash2 != nullptr && strncmp(hash1, hash2, GITHASH_SUFFIX_LEN) == 0;
|
||||
std::string_view hash1 = ExtractNetworkRevisionHash(GetNetworkRevisionString());
|
||||
std::string_view hash2 = ExtractNetworkRevisionHash(other);
|
||||
return hash1 == hash2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fill a NetworkGameInfo structure with the latest information of the server.
|
||||
* @param ngi the NetworkGameInfo struct to fill with data.
|
||||
* Check if an game entry is compatible with our client.
|
||||
*/
|
||||
void FillNetworkGameInfo(NetworkGameInfo &ngi)
|
||||
void CheckGameCompatibility(NetworkGameInfo &ngi)
|
||||
{
|
||||
/* Update some game_info */
|
||||
ngi.clients_on = _network_game_info.clients_on;
|
||||
ngi.start_date = ConvertYMDToDate(_settings_game.game_creation.starting_year, 0, 1);
|
||||
/* Check if we are allowed on this server based on the revision-check. */
|
||||
ngi.version_compatible = IsNetworkCompatibleVersion(ngi.server_revision);
|
||||
ngi.compatible = ngi.version_compatible;
|
||||
|
||||
ngi.server_lang = _settings_client.network.server_lang;
|
||||
ngi.use_password = !StrEmpty(_settings_client.network.server_password);
|
||||
ngi.clients_max = _settings_client.network.max_clients;
|
||||
ngi.companies_on = (byte)Company::GetNumItems();
|
||||
ngi.companies_max = _settings_client.network.max_companies;
|
||||
ngi.spectators_on = NetworkSpectatorCount();
|
||||
ngi.spectators_max = _settings_client.network.max_spectators;
|
||||
ngi.game_date = _date;
|
||||
ngi.map_width = MapSizeX();
|
||||
ngi.map_height = MapSizeY();
|
||||
ngi.map_set = _settings_game.game_creation.landscape;
|
||||
ngi.dedicated = _network_dedicated;
|
||||
ngi.grfconfig = _grfconfig;
|
||||
/* Check if we have all the GRFs on the client-system too. */
|
||||
for (const GRFConfig *c = ngi.grfconfig; c != nullptr; c = c->next) {
|
||||
if (c->status == GCS_NOT_FOUND) ngi.compatible = false;
|
||||
}
|
||||
}
|
||||
|
||||
strecpy(ngi.map_name, _network_game_info.map_name, lastof(ngi.map_name));
|
||||
strecpy(ngi.server_name, _settings_client.network.server_name, lastof(ngi.server_name));
|
||||
strecpy(ngi.server_revision, GetNetworkRevisionString(), lastof(ngi.server_revision));
|
||||
/**
|
||||
* Fill a NetworkServerGameInfo structure with the static content, or things
|
||||
* that are so static they can be updated on request from a settings change.
|
||||
*/
|
||||
void FillStaticNetworkServerGameInfo()
|
||||
{
|
||||
_network_game_info.use_password = !_settings_client.network.server_password.empty();
|
||||
_network_game_info.start_date = ConvertYMDToDate(_settings_game.game_creation.starting_year, 0, 1);
|
||||
_network_game_info.clients_max = _settings_client.network.max_clients;
|
||||
_network_game_info.companies_max = _settings_client.network.max_companies;
|
||||
_network_game_info.map_width = MapSizeX();
|
||||
_network_game_info.map_height = MapSizeY();
|
||||
_network_game_info.landscape = _settings_game.game_creation.landscape;
|
||||
_network_game_info.dedicated = _network_dedicated;
|
||||
_network_game_info.grfconfig = _grfconfig;
|
||||
|
||||
_network_game_info.server_name = _settings_client.network.server_name;
|
||||
_network_game_info.server_revision = GetNetworkRevisionString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the NetworkServerGameInfo structure with the latest information of the server.
|
||||
* @return The current NetworkServerGameInfo.
|
||||
*/
|
||||
const NetworkServerGameInfo *GetCurrentNetworkServerGameInfo()
|
||||
{
|
||||
/* 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;
|
||||
return &_network_game_info;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -140,17 +158,15 @@ void FillNetworkGameInfo(NetworkGameInfo &ngi)
|
||||
* a NetworkGameInfo. Only grfid and md5sum are set, the rest is zero. This
|
||||
* function must set all appropriate fields. This GRF is later appended to
|
||||
* the grfconfig list of the NetworkGameInfo.
|
||||
* @param config the GRF to handle.
|
||||
* @param config The GRF to handle.
|
||||
* @param name The name of the NewGRF, empty when unknown.
|
||||
*/
|
||||
static void HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config)
|
||||
static void HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config, std::string name)
|
||||
{
|
||||
/* Find the matching GRF file */
|
||||
const GRFConfig *f = FindGRFConfig(config->ident.grfid, FGCM_EXACT, config->ident.md5sum);
|
||||
if (f == nullptr) {
|
||||
/* Don't know the GRF, so mark game incompatible and the (possibly)
|
||||
* already resolved name for this GRF (another server has sent the
|
||||
* name of the GRF already */
|
||||
config->name = FindUnknownGRFName(config->ident.grfid, config->ident.md5sum, true);
|
||||
AddGRFTextToList(config->name, name.empty() ? GetString(STR_CONFIG_ERROR_INVALID_GRF_UNKNOWN) : name);
|
||||
config->status = GCS_NOT_FOUND;
|
||||
} else {
|
||||
config->filename = f->filename;
|
||||
@@ -166,7 +182,7 @@ static void HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config)
|
||||
* @param p the packet to write the data to.
|
||||
* @param info the NetworkGameInfo struct to serialize from.
|
||||
*/
|
||||
void SerializeNetworkGameInfo(Packet *p, const NetworkGameInfo *info)
|
||||
void SerializeNetworkGameInfo(Packet *p, const NetworkServerGameInfo *info, bool send_newgrf_names)
|
||||
{
|
||||
p->Send_uint8 (NETWORK_GAME_INFO_VERSION);
|
||||
|
||||
@@ -178,6 +194,14 @@ void SerializeNetworkGameInfo(Packet *p, const NetworkGameInfo *info)
|
||||
/* Update the documentation in game_info.h on changes
|
||||
* to the NetworkGameInfo wire-protocol! */
|
||||
|
||||
/* NETWORK_GAME_INFO_VERSION = 6 */
|
||||
p->Send_uint8(send_newgrf_names ? NST_GRFID_MD5_NAME : NST_GRFID_MD5);
|
||||
|
||||
/* 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
|
||||
@@ -195,7 +219,10 @@ void SerializeNetworkGameInfo(Packet *p, const NetworkGameInfo *info)
|
||||
|
||||
/* Send actual GRF Identifications */
|
||||
for (c = info->grfconfig; c != nullptr; c = c->next) {
|
||||
if (!HasBit(c->flags, GCF_STATIC)) SerializeGRFIdentifier(p, &c->ident);
|
||||
if (HasBit(c->flags, GCF_STATIC)) continue;
|
||||
|
||||
SerializeGRFIdentifier(p, &c->ident);
|
||||
if (send_newgrf_names) p->Send_string(c->GetName());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,20 +233,18 @@ void SerializeNetworkGameInfo(Packet *p, const NetworkGameInfo *info)
|
||||
/* NETWORK_GAME_INFO_VERSION = 2 */
|
||||
p->Send_uint8 (info->companies_max);
|
||||
p->Send_uint8 (info->companies_on);
|
||||
p->Send_uint8 (info->spectators_max);
|
||||
p->Send_uint8 (info->clients_max); // Used to be max-spectators
|
||||
|
||||
/* NETWORK_GAME_INFO_VERSION = 1 */
|
||||
p->Send_string(info->server_name);
|
||||
p->Send_string(info->server_revision);
|
||||
p->Send_uint8 (info->server_lang);
|
||||
p->Send_bool (info->use_password);
|
||||
p->Send_uint8 (info->clients_max);
|
||||
p->Send_uint8 (info->clients_on);
|
||||
p->Send_uint8 (info->spectators_on);
|
||||
p->Send_string(info->map_name);
|
||||
p->Send_uint16(info->map_width);
|
||||
p->Send_uint16(info->map_height);
|
||||
p->Send_uint8 (info->map_set);
|
||||
p->Send_uint8 (info->landscape);
|
||||
p->Send_bool (info->dedicated);
|
||||
}
|
||||
|
||||
@@ -228,11 +253,12 @@ void SerializeNetworkGameInfo(Packet *p, const NetworkGameInfo *info)
|
||||
* @param p the packet to read the data from.
|
||||
* @param info the NetworkGameInfo to deserialize into.
|
||||
*/
|
||||
void DeserializeNetworkGameInfo(Packet *p, NetworkGameInfo *info)
|
||||
void DeserializeNetworkGameInfo(Packet *p, NetworkGameInfo *info, const GameInfoNewGRFLookupTable *newgrf_lookup_table)
|
||||
{
|
||||
static const Date MAX_DATE = ConvertYMDToDate(MAX_YEAR, 11, 31); // December is month 11
|
||||
|
||||
info->game_info_version = p->Recv_uint8();
|
||||
byte game_info_version = p->Recv_uint8();
|
||||
NewGRFSerializationType newgrf_serialisation = NST_GRFID_MD5;
|
||||
|
||||
/*
|
||||
* Please observe the order.
|
||||
@@ -242,7 +268,18 @@ void DeserializeNetworkGameInfo(Packet *p, NetworkGameInfo *info)
|
||||
/* Update the documentation in game_info.h on changes
|
||||
* to the NetworkGameInfo wire-protocol! */
|
||||
|
||||
switch (info->game_info_version) {
|
||||
switch (game_info_version) {
|
||||
case 6:
|
||||
newgrf_serialisation = (NewGRFSerializationType)p->Recv_uint8();
|
||||
if (newgrf_serialisation >= NST_END) return;
|
||||
FALLTHROUGH;
|
||||
|
||||
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;
|
||||
@@ -252,9 +289,31 @@ void DeserializeNetworkGameInfo(Packet *p, NetworkGameInfo *info)
|
||||
if (num_grfs > NETWORK_MAX_GRF_COUNT) return;
|
||||
|
||||
for (i = 0; i < num_grfs; i++) {
|
||||
NamedGRFIdentifier grf;
|
||||
switch (newgrf_serialisation) {
|
||||
case NST_GRFID_MD5:
|
||||
DeserializeGRFIdentifier(p, &grf.ident);
|
||||
break;
|
||||
|
||||
case NST_GRFID_MD5_NAME:
|
||||
DeserializeGRFIdentifierWithName(p, &grf);
|
||||
break;
|
||||
|
||||
case NST_LOOKUP_ID: {
|
||||
if (newgrf_lookup_table == nullptr) return;
|
||||
auto it = newgrf_lookup_table->find(p->Recv_uint32());
|
||||
if (it == newgrf_lookup_table->end()) return;
|
||||
grf = it->second;
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
NOT_REACHED();
|
||||
}
|
||||
|
||||
GRFConfig *c = new GRFConfig();
|
||||
DeserializeGRFIdentifier(p, &c->ident);
|
||||
HandleIncomingNetworkGameInfoGRFConfig(c);
|
||||
c->ident = grf.ident;
|
||||
HandleIncomingNetworkGameInfoGRFConfig(c, grf.name);
|
||||
|
||||
/* Append GRFConfig to the list */
|
||||
*dst = c;
|
||||
@@ -271,29 +330,28 @@ void DeserializeNetworkGameInfo(Packet *p, NetworkGameInfo *info)
|
||||
case 2:
|
||||
info->companies_max = p->Recv_uint8 ();
|
||||
info->companies_on = p->Recv_uint8 ();
|
||||
info->spectators_max = p->Recv_uint8 ();
|
||||
p->Recv_uint8(); // Used to contain max-spectators.
|
||||
FALLTHROUGH;
|
||||
|
||||
case 1:
|
||||
p->Recv_string(info->server_name, sizeof(info->server_name));
|
||||
p->Recv_string(info->server_revision, sizeof(info->server_revision));
|
||||
info->server_lang = p->Recv_uint8 ();
|
||||
info->server_name = p->Recv_string(NETWORK_NAME_LENGTH);
|
||||
info->server_revision = p->Recv_string(NETWORK_REVISION_LENGTH);
|
||||
if (game_info_version < 6) p->Recv_uint8 (); // Used to contain server-lang.
|
||||
info->use_password = p->Recv_bool ();
|
||||
info->clients_max = p->Recv_uint8 ();
|
||||
info->clients_on = p->Recv_uint8 ();
|
||||
info->spectators_on = p->Recv_uint8 ();
|
||||
if (info->game_info_version < 3) { // 16 bits dates got scrapped and are read earlier
|
||||
if (game_info_version < 3) { // 16 bits dates got scrapped and are read earlier
|
||||
info->game_date = p->Recv_uint16() + DAYS_TILL_ORIGINAL_BASE_YEAR;
|
||||
info->start_date = p->Recv_uint16() + DAYS_TILL_ORIGINAL_BASE_YEAR;
|
||||
}
|
||||
p->Recv_string(info->map_name, sizeof(info->map_name));
|
||||
if (game_info_version < 6) while (p->Recv_uint8() != 0) {} // Used to contain the map-name.
|
||||
info->map_width = p->Recv_uint16();
|
||||
info->map_height = p->Recv_uint16();
|
||||
info->map_set = p->Recv_uint8 ();
|
||||
info->landscape = p->Recv_uint8 ();
|
||||
info->dedicated = p->Recv_bool ();
|
||||
|
||||
if (info->server_lang >= NETWORK_NUM_LANGUAGES) info->server_lang = 0;
|
||||
if (info->map_set >= NETWORK_NUM_LANDSCAPES) info->map_set = 0;
|
||||
if (info->landscape >= NUM_LANDSCAPE) info->landscape = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -324,3 +382,14 @@ void DeserializeGRFIdentifier(Packet *p, GRFIdentifier *grf)
|
||||
grf->md5sum[j] = p->Recv_uint8();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserializes the NamedGRFIdentifier (GRF ID, MD5 checksum and name) from the packet
|
||||
* @param p the packet to read the data from.
|
||||
* @param grf the NamedGRFIdentifier to deserialize.
|
||||
*/
|
||||
void DeserializeGRFIdentifierWithName(Packet *p, NamedGRFIdentifier *grf)
|
||||
{
|
||||
DeserializeGRFIdentifier(p, &grf->ident);
|
||||
grf->name = p->Recv_string(NETWORK_GRF_NAME_LENGTH);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,8 @@
|
||||
#include "../../newgrf_config.h"
|
||||
#include "../../date_type.h"
|
||||
|
||||
#include <unordered_map>
|
||||
|
||||
/*
|
||||
* NetworkGameInfo has several revisions which we still need to support on the
|
||||
* wire. The table below shows the version and size for each field of the
|
||||
@@ -25,11 +27,32 @@
|
||||
* Version: Bytes: Description:
|
||||
* all 1 the version of this packet's structure
|
||||
*
|
||||
* 4+ 1 number of GRFs attached (n)
|
||||
* 4+ n * 20 unique identifier for GRF files. Consists of:
|
||||
* - one 4 byte variable with the GRF ID
|
||||
* - 16 bytes (sent sequentially) for the MD5 checksum
|
||||
* of the GRF
|
||||
* 6+ 1 type of storage for the NewGRFs below:
|
||||
* 0 = NewGRF ID and MD5 checksum.
|
||||
* Used as default for version 5 and below, and for
|
||||
* later game updates to the Game Coordinator.
|
||||
* 1 = NewGRF ID, MD5 checksum and name.
|
||||
* Used for direct requests and the first game
|
||||
* update to Game Coordinator.
|
||||
* 2 = Index in NewGRF lookup table.
|
||||
* Used for sending server listing from the Game
|
||||
* Coordinator to the clients.
|
||||
*
|
||||
* 5+ 4 version number of the Game Script (-1 is case none is selected).
|
||||
* 5+ var string with the name of the Game Script.
|
||||
*
|
||||
* 4+ 1 number of GRFs attached (n).
|
||||
* 4+ n * var identifiers for GRF files. Consists of:
|
||||
* Note: the 'vN' refers to packet version and 'type'
|
||||
* refers to the v6+ type of storage for the NewGRFs.
|
||||
* - 4 byte variable with the GRF ID.
|
||||
* For v4, v5, and v6+ in case of type 0 and/or type 1.
|
||||
* - 16 bytes with the MD5 checksum of the GRF.
|
||||
* For v4, v5, and v6+ in case of type 0 and/or type 1.
|
||||
* - string with name of NewGRF.
|
||||
* For v6+ in case of type 1.
|
||||
* - 4 byte lookup table index.
|
||||
* For v6+ in case of type 2.
|
||||
*
|
||||
* 3+ 4 current game date in days since 1-1-0 (DMY)
|
||||
* 3+ 4 game introduction date in days since 1-1-0 (DMY)
|
||||
@@ -40,7 +63,7 @@
|
||||
*
|
||||
* 1+ var string with the name of the server
|
||||
* 1+ var string with the revision of the server
|
||||
* 1+ 1 the language run on the server
|
||||
* 1 - 5 1 the language run on the server
|
||||
* (0 = any, 1 = English, 2 = German, 3 = French)
|
||||
* 1+ 1 whether the server uses a password (0 = no, 1 = yes)
|
||||
* 1+ 1 maximum number of clients allowed on the server
|
||||
@@ -48,7 +71,7 @@
|
||||
* 1+ 1 number of spectators on the server
|
||||
* 1 & 2 2 current game date in days since 1-1-1920 (DMY)
|
||||
* 1 & 2 2 game introduction date in days since 1-1-1920 (DMY)
|
||||
* 1+ var string with the name of the map
|
||||
* 1 - 5 var string with the name of the map
|
||||
* 1+ 2 width of the map in tiles
|
||||
* 1+ 2 height of the map in tiles
|
||||
* 1+ 1 type of map:
|
||||
@@ -56,52 +79,71 @@
|
||||
* 1+ 1 whether the server is dedicated (0 = no, 1 = yes)
|
||||
*/
|
||||
|
||||
/**
|
||||
* The game information that is not generated on-the-fly and has to
|
||||
* be sent to the clients.
|
||||
*/
|
||||
struct NetworkServerGameInfo {
|
||||
char map_name[NETWORK_NAME_LENGTH]; ///< Map which is played ["random" for a randomized map]
|
||||
byte clients_on; ///< Current count of clients on server
|
||||
/** The different types/ways a NewGRF can be serialized in the GameInfo since version 6. */
|
||||
enum NewGRFSerializationType {
|
||||
NST_GRFID_MD5 = 0, ///< Unique GRF ID and MD5 checksum.
|
||||
NST_GRFID_MD5_NAME = 1, ///< Unique GRF ID, MD5 checksum and name.
|
||||
NST_LOOKUP_ID = 2, ///< Unique ID into a lookup table that is sent before.
|
||||
NST_END ///< The end of the list (period).
|
||||
};
|
||||
|
||||
/**
|
||||
* The game information that is sent from the server to the clients.
|
||||
* The game information that is sent from the server to the client.
|
||||
*/
|
||||
struct NetworkServerGameInfo {
|
||||
GRFConfig *grfconfig; ///< List of NewGRF files used
|
||||
Date start_date; ///< When the game started
|
||||
Date game_date; ///< Current date
|
||||
uint16 map_width; ///< Map width
|
||||
uint16 map_height; ///< Map height
|
||||
std::string server_name; ///< Server name
|
||||
std::string server_revision; ///< The version number the server is using (e.g.: 'r304' or 0.5.0)
|
||||
bool dedicated; ///< Is this a dedicated server?
|
||||
bool use_password; ///< Is this server passworded?
|
||||
byte clients_on; ///< Current count of clients on server
|
||||
byte clients_max; ///< Max clients allowed on server
|
||||
byte companies_on; ///< How many started companies do we have
|
||||
byte companies_max; ///< Max companies allowed on server
|
||||
byte spectators_on; ///< How many spectators do we have?
|
||||
byte landscape; ///< The used landscape
|
||||
int gamescript_version; ///< Version of the gamescript.
|
||||
std::string gamescript_name; ///< Name of the gamescript.
|
||||
};
|
||||
|
||||
/**
|
||||
* The game information that is sent from the server to the clients
|
||||
* with extra information only required at the client side.
|
||||
*/
|
||||
struct NetworkGameInfo : NetworkServerGameInfo {
|
||||
GRFConfig *grfconfig; ///< List of NewGRF files used
|
||||
Date start_date; ///< When the game started
|
||||
Date game_date; ///< Current date
|
||||
uint16 map_width; ///< Map width
|
||||
uint16 map_height; ///< Map height
|
||||
char server_name[NETWORK_NAME_LENGTH]; ///< Server name
|
||||
char hostname[NETWORK_HOSTNAME_LENGTH]; ///< Hostname of the server (if any)
|
||||
char server_revision[NETWORK_REVISION_LENGTH]; ///< The version number the server is using (e.g.: 'r304' or 0.5.0)
|
||||
bool dedicated; ///< Is this a dedicated server?
|
||||
bool version_compatible; ///< Can we connect to this server or not? (based on server_revision)
|
||||
bool compatible; ///< Can we connect to this server or not? (based on server_revision _and_ grf_match
|
||||
bool use_password; ///< Is this server passworded?
|
||||
byte game_info_version; ///< Version of the game info
|
||||
byte server_lang; ///< Language of the server (we should make a nice table for this)
|
||||
byte clients_max; ///< Max clients allowed on server
|
||||
byte companies_on; ///< How many started companies do we have
|
||||
byte companies_max; ///< Max companies allowed on server
|
||||
byte spectators_on; ///< How many spectators do we have?
|
||||
byte spectators_max; ///< Max spectators allowed on server
|
||||
byte map_set; ///< Graphical set
|
||||
};
|
||||
|
||||
/**
|
||||
* Container to hold the GRF identifier (GRF ID + MD5 checksum) and the name
|
||||
* associated with that NewGRF.
|
||||
*/
|
||||
struct NamedGRFIdentifier {
|
||||
GRFIdentifier ident; ///< The unique identifier of the NewGRF.
|
||||
std::string name; ///< The name of the NewGRF.
|
||||
};
|
||||
/** Lookup table for the GameInfo in case of #NST_LOOKUP_ID. */
|
||||
typedef std::unordered_map<uint32, NamedGRFIdentifier> GameInfoNewGRFLookupTable;
|
||||
|
||||
extern NetworkServerGameInfo _network_game_info;
|
||||
|
||||
const char *GetNetworkRevisionString();
|
||||
bool IsNetworkCompatibleVersion(const char *other);
|
||||
std::string_view GetNetworkRevisionString();
|
||||
bool IsNetworkCompatibleVersion(std::string_view other);
|
||||
void CheckGameCompatibility(NetworkGameInfo &ngi);
|
||||
|
||||
void FillNetworkGameInfo(NetworkGameInfo &ngi);
|
||||
void FillStaticNetworkServerGameInfo();
|
||||
const NetworkServerGameInfo *GetCurrentNetworkServerGameInfo();
|
||||
|
||||
void DeserializeGRFIdentifier(Packet *p, GRFIdentifier *grf);
|
||||
void DeserializeGRFIdentifierWithName(Packet *p, NamedGRFIdentifier *grf);
|
||||
void SerializeGRFIdentifier(Packet *p, const GRFIdentifier *grf);
|
||||
|
||||
void DeserializeNetworkGameInfo(Packet *p, NetworkGameInfo *info);
|
||||
void SerializeNetworkGameInfo(Packet *p, const NetworkGameInfo *info);
|
||||
void DeserializeNetworkGameInfo(Packet *p, NetworkGameInfo *info, const GameInfoNewGRFLookupTable *newgrf_lookup_table = nullptr);
|
||||
void SerializeNetworkGameInfo(Packet *p, const NetworkServerGameInfo *info, bool send_newgrf_names = true);
|
||||
|
||||
#endif /* NETWORK_CORE_GAME_INFO_H */
|
||||
|
||||
@@ -20,72 +20,7 @@
|
||||
*/
|
||||
static void NetworkFindBroadcastIPsInternal(NetworkAddressList *broadcast);
|
||||
|
||||
#if defined(__HAIKU__) /* doesn't have neither getifaddrs or net/if.h */
|
||||
/* Based on Andrew Bachmann's netstat+.c. Big thanks to him! */
|
||||
extern "C" int _netstat(int fd, char **output, int verbose);
|
||||
|
||||
int seek_past_header(char **pos, const char *header)
|
||||
{
|
||||
char *new_pos = strstr(*pos, header);
|
||||
if (new_pos == 0) {
|
||||
return B_ERROR;
|
||||
}
|
||||
*pos += strlen(header) + new_pos - *pos + 1;
|
||||
return B_OK;
|
||||
}
|
||||
|
||||
static void NetworkFindBroadcastIPsInternal(NetworkAddressList *broadcast) // BEOS implementation
|
||||
{
|
||||
int sock = socket(AF_INET, SOCK_DGRAM, 0);
|
||||
|
||||
if (sock < 0) {
|
||||
DEBUG(net, 0, "[core] error creating socket");
|
||||
return;
|
||||
}
|
||||
|
||||
char *output_pointer = nullptr;
|
||||
int output_length = _netstat(sock, &output_pointer, 1);
|
||||
if (output_length < 0) {
|
||||
DEBUG(net, 0, "[core] error running _netstat");
|
||||
return;
|
||||
}
|
||||
|
||||
char **output = &output_pointer;
|
||||
if (seek_past_header(output, "IP Interfaces:") == B_OK) {
|
||||
for (;;) {
|
||||
uint32 n;
|
||||
int fields, read;
|
||||
uint8 i1, i2, i3, i4, j1, j2, j3, j4;
|
||||
uint32 ip;
|
||||
uint32 netmask;
|
||||
|
||||
fields = sscanf(*output, "%u: %hhu.%hhu.%hhu.%hhu, netmask %hhu.%hhu.%hhu.%hhu%n",
|
||||
&n, &i1, &i2, &i3, &i4, &j1, &j2, &j3, &j4, &read);
|
||||
read += 1;
|
||||
if (fields != 9) {
|
||||
break;
|
||||
}
|
||||
|
||||
ip = (uint32)i1 << 24 | (uint32)i2 << 16 | (uint32)i3 << 8 | (uint32)i4;
|
||||
netmask = (uint32)j1 << 24 | (uint32)j2 << 16 | (uint32)j3 << 8 | (uint32)j4;
|
||||
|
||||
if (ip != INADDR_LOOPBACK && ip != INADDR_ANY) {
|
||||
sockaddr_storage address;
|
||||
memset(&address, 0, sizeof(address));
|
||||
((sockaddr_in*)&address)->sin_addr.s_addr = htonl(ip | ~netmask);
|
||||
NetworkAddress addr(address, sizeof(sockaddr));
|
||||
if (std::none_of(broadcast->begin(), broadcast->end(), [&addr](NetworkAddress const& elem) -> bool { return elem == addr; })) broadcast->push_back(addr);
|
||||
}
|
||||
if (read < 0) {
|
||||
break;
|
||||
}
|
||||
*output += read;
|
||||
}
|
||||
closesocket(sock);
|
||||
}
|
||||
}
|
||||
|
||||
#elif defined(HAVE_GETIFADDRS)
|
||||
#if defined(HAVE_GETIFADDRS)
|
||||
static void NetworkFindBroadcastIPsInternal(NetworkAddressList *broadcast) // GETIFADDRS implementation
|
||||
{
|
||||
struct ifaddrs *ifap, *ifa;
|
||||
@@ -196,10 +131,10 @@ void NetworkFindBroadcastIPs(NetworkAddressList *broadcast)
|
||||
NetworkFindBroadcastIPsInternal(broadcast);
|
||||
|
||||
/* Now display to the debug all the detected ips */
|
||||
DEBUG(net, 3, "Detected broadcast addresses:");
|
||||
Debug(net, 3, "Detected broadcast addresses:");
|
||||
int i = 0;
|
||||
for (NetworkAddress &addr : *broadcast) {
|
||||
addr.SetPort(NETWORK_DEFAULT_PORT);
|
||||
DEBUG(net, 3, "%d) %s", i++, addr.GetHostname());
|
||||
Debug(net, 3, " {}) {}", i++, addr.GetHostname());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,7 +76,7 @@ bool NetworkError::IsConnectInProgress() const
|
||||
* Get the string representation of the error message.
|
||||
* @return The string representation that will get overwritten by next calls.
|
||||
*/
|
||||
const char *NetworkError::AsString() const
|
||||
const std::string &NetworkError::AsString() const
|
||||
{
|
||||
if (this->message.empty()) {
|
||||
#if defined(_WIN32)
|
||||
@@ -97,7 +97,7 @@ const char *NetworkError::AsString() const
|
||||
this->message.assign(strerror(this->error));
|
||||
#endif
|
||||
}
|
||||
return this->message.c_str();
|
||||
return this->message;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -159,6 +159,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
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the error from a socket, if any.
|
||||
* @param d The socket to get the error from.
|
||||
|
||||
@@ -14,8 +14,6 @@
|
||||
#ifndef NETWORK_CORE_OS_ABSTRACTION_H
|
||||
#define NETWORK_CORE_OS_ABSTRACTION_H
|
||||
|
||||
#include <string>
|
||||
|
||||
/**
|
||||
* Abstraction of a network error where all implementation details of the
|
||||
* error codes are encapsulated in this class and the abstraction layer.
|
||||
@@ -31,7 +29,7 @@ public:
|
||||
bool WouldBlock() const;
|
||||
bool IsConnectionReset() const;
|
||||
bool IsConnectInProgress() const;
|
||||
const char *AsString() const;
|
||||
const std::string &AsString() const;
|
||||
|
||||
static NetworkError GetLast();
|
||||
};
|
||||
@@ -110,6 +108,13 @@ typedef unsigned long in_addr_t;
|
||||
# undef FD_SETSIZE
|
||||
# define FD_SETSIZE 64
|
||||
# endif
|
||||
|
||||
/* Haiku says it supports FD_SETSIZE fds, but it really only supports 512. */
|
||||
# if defined(__HAIKU__)
|
||||
# undef FD_SETSIZE
|
||||
# define FD_SETSIZE 512
|
||||
# endif
|
||||
|
||||
#endif /* UNIX */
|
||||
|
||||
/* OS/2 stuff */
|
||||
@@ -191,6 +196,7 @@ static inline socklen_t FixAddrLenForEmscripten(struct sockaddr_storage &address
|
||||
|
||||
bool SetNonBlocking(SOCKET d);
|
||||
bool SetNoDelay(SOCKET d);
|
||||
bool SetReusePort(SOCKET d);
|
||||
NetworkError GetSocketError(SOCKET d);
|
||||
|
||||
/* Make sure these structures have the size we expect them to be */
|
||||
|
||||
+179
-82
@@ -17,44 +17,66 @@
|
||||
#include "../../safeguards.h"
|
||||
|
||||
/**
|
||||
* Create a packet that is used to read from a network socket
|
||||
* @param cs the socket handler associated with the socket we are reading from
|
||||
* Create a packet that is used to read from a network socket.
|
||||
* @param cs The socket handler associated with the socket we are reading from.
|
||||
* @param limit The maximum size of packets to accept.
|
||||
* @param initial_read_size The initial amount of data to transfer from the socket into the
|
||||
* packet. This defaults to just the required bytes to determine the
|
||||
* packet's size. That default is the wanted for streams such as TCP
|
||||
* as you do not want to read data of the next packet yet. For UDP
|
||||
* you need to read the whole packet at once otherwise you might
|
||||
* loose some the data of the packet, so there you pass the maximum
|
||||
* size for the packet you expect from the network.
|
||||
*/
|
||||
Packet::Packet(NetworkSocketHandler *cs)
|
||||
Packet::Packet(NetworkSocketHandler *cs, size_t limit, size_t initial_read_size) : next(nullptr), pos(0), limit(limit)
|
||||
{
|
||||
assert(cs != nullptr);
|
||||
|
||||
this->cs = cs;
|
||||
this->next = nullptr;
|
||||
this->pos = 0; // We start reading from here
|
||||
this->size = 0;
|
||||
this->buffer = MallocT<byte>(SEND_MTU);
|
||||
this->cs = cs;
|
||||
this->buffer.resize(initial_read_size);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a packet to send
|
||||
* @param type of the packet to send
|
||||
* @param type The type of the packet to send
|
||||
* @param limit The maximum number of bytes the packet may have. Default is COMPAT_MTU.
|
||||
* Be careful of compatibility with older clients/servers when changing
|
||||
* the limit as it might break things if the other side is not expecting
|
||||
* much larger packets than what they support.
|
||||
*/
|
||||
Packet::Packet(PacketType type)
|
||||
Packet::Packet(PacketType type, size_t limit) : next(nullptr), pos(0), limit(limit), cs(nullptr)
|
||||
{
|
||||
this->cs = nullptr;
|
||||
this->next = nullptr;
|
||||
|
||||
/* Skip the size so we can write that in before sending the packet */
|
||||
this->pos = 0;
|
||||
this->size = sizeof(PacketSize);
|
||||
this->buffer = MallocT<byte>(SEND_MTU);
|
||||
this->buffer[this->size++] = type;
|
||||
/* Allocate space for the the size so we can write that in just before sending the packet. */
|
||||
this->Send_uint16(0);
|
||||
this->Send_uint8(type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Free the buffer of this packet.
|
||||
* Add the given Packet to the end of the queue of packets.
|
||||
* @param queue The pointer to the begin of the queue.
|
||||
* @param packet The packet to append to the queue.
|
||||
*/
|
||||
Packet::~Packet()
|
||||
/* static */ void Packet::AddToQueue(Packet **queue, Packet *packet)
|
||||
{
|
||||
free(this->buffer);
|
||||
while (*queue != nullptr) queue = &(*queue)->next;
|
||||
*queue = packet;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pop the packet from the begin of the queue and set the
|
||||
* begin of the queue to the second element in the queue.
|
||||
* @param queue The pointer to the begin of the queue.
|
||||
* @return The Packet that used to be a the begin of the queue.
|
||||
*/
|
||||
/* static */ Packet *Packet::PopFromQueue(Packet **queue)
|
||||
{
|
||||
Packet *p = *queue;
|
||||
*queue = p->next;
|
||||
p->next = nullptr;
|
||||
return p;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Writes the packet size from the raw packet from packet->size
|
||||
*/
|
||||
@@ -62,10 +84,21 @@ void Packet::PrepareToSend()
|
||||
{
|
||||
assert(this->cs == nullptr && this->next == nullptr);
|
||||
|
||||
this->buffer[0] = GB(this->size, 0, 8);
|
||||
this->buffer[1] = GB(this->size, 8, 8);
|
||||
this->buffer[0] = GB(this->Size(), 0, 8);
|
||||
this->buffer[1] = GB(this->Size(), 8, 8);
|
||||
|
||||
this->pos = 0; // We start reading from here
|
||||
this->buffer.shrink_to_fit();
|
||||
}
|
||||
|
||||
/**
|
||||
* Is it safe to write to the packet, i.e. didn't we run over the buffer?
|
||||
* @param bytes_to_write The amount of bytes we want to try to write.
|
||||
* @return True iff the given amount of bytes can be written to the packet.
|
||||
*/
|
||||
bool Packet::CanWriteToPacket(size_t bytes_to_write)
|
||||
{
|
||||
return this->Size() + bytes_to_write <= this->limit;
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -95,8 +128,8 @@ void Packet::Send_bool(bool data)
|
||||
*/
|
||||
void Packet::Send_uint8(uint8 data)
|
||||
{
|
||||
assert(this->size < SEND_MTU - sizeof(data));
|
||||
this->buffer[this->size++] = data;
|
||||
assert(this->CanWriteToPacket(sizeof(data)));
|
||||
this->buffer.emplace_back(data);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -105,9 +138,9 @@ void Packet::Send_uint8(uint8 data)
|
||||
*/
|
||||
void Packet::Send_uint16(uint16 data)
|
||||
{
|
||||
assert(this->size < SEND_MTU - sizeof(data));
|
||||
this->buffer[this->size++] = GB(data, 0, 8);
|
||||
this->buffer[this->size++] = GB(data, 8, 8);
|
||||
assert(this->CanWriteToPacket(sizeof(data)));
|
||||
this->buffer.emplace_back(GB(data, 0, 8));
|
||||
this->buffer.emplace_back(GB(data, 8, 8));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -116,11 +149,11 @@ void Packet::Send_uint16(uint16 data)
|
||||
*/
|
||||
void Packet::Send_uint32(uint32 data)
|
||||
{
|
||||
assert(this->size < SEND_MTU - sizeof(data));
|
||||
this->buffer[this->size++] = GB(data, 0, 8);
|
||||
this->buffer[this->size++] = GB(data, 8, 8);
|
||||
this->buffer[this->size++] = GB(data, 16, 8);
|
||||
this->buffer[this->size++] = GB(data, 24, 8);
|
||||
assert(this->CanWriteToPacket(sizeof(data)));
|
||||
this->buffer.emplace_back(GB(data, 0, 8));
|
||||
this->buffer.emplace_back(GB(data, 8, 8));
|
||||
this->buffer.emplace_back(GB(data, 16, 8));
|
||||
this->buffer.emplace_back(GB(data, 24, 8));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -129,15 +162,15 @@ void Packet::Send_uint32(uint32 data)
|
||||
*/
|
||||
void Packet::Send_uint64(uint64 data)
|
||||
{
|
||||
assert(this->size < SEND_MTU - sizeof(data));
|
||||
this->buffer[this->size++] = GB(data, 0, 8);
|
||||
this->buffer[this->size++] = GB(data, 8, 8);
|
||||
this->buffer[this->size++] = GB(data, 16, 8);
|
||||
this->buffer[this->size++] = GB(data, 24, 8);
|
||||
this->buffer[this->size++] = GB(data, 32, 8);
|
||||
this->buffer[this->size++] = GB(data, 40, 8);
|
||||
this->buffer[this->size++] = GB(data, 48, 8);
|
||||
this->buffer[this->size++] = GB(data, 56, 8);
|
||||
assert(this->CanWriteToPacket(sizeof(data)));
|
||||
this->buffer.emplace_back(GB(data, 0, 8));
|
||||
this->buffer.emplace_back(GB(data, 8, 8));
|
||||
this->buffer.emplace_back(GB(data, 16, 8));
|
||||
this->buffer.emplace_back(GB(data, 24, 8));
|
||||
this->buffer.emplace_back(GB(data, 32, 8));
|
||||
this->buffer.emplace_back(GB(data, 40, 8));
|
||||
this->buffer.emplace_back(GB(data, 48, 8));
|
||||
this->buffer.emplace_back(GB(data, 56, 8));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -145,14 +178,27 @@ void Packet::Send_uint64(uint64 data)
|
||||
* the string + '\0'. No size-byte or something.
|
||||
* @param data The string to send
|
||||
*/
|
||||
void Packet::Send_string(const char *data)
|
||||
void Packet::Send_string(const std::string_view data)
|
||||
{
|
||||
assert(data != nullptr);
|
||||
/* The <= *is* valid due to the fact that we are comparing sizes and not the index. */
|
||||
assert(this->size + strlen(data) + 1 <= SEND_MTU);
|
||||
while ((this->buffer[this->size++] = *data++) != '\0') {}
|
||||
assert(this->CanWriteToPacket(data.size() + 1));
|
||||
this->buffer.insert(this->buffer.end(), data.begin(), data.end());
|
||||
this->buffer.emplace_back('\0');
|
||||
}
|
||||
|
||||
/**
|
||||
* Send as many of the bytes as possible in the packet. This can mean
|
||||
* that it is possible that not all bytes are sent. To cope with this
|
||||
* the function returns the amount of bytes that were actually sent.
|
||||
* @param begin The begin of the buffer to send.
|
||||
* @param end The end of the buffer to send.
|
||||
* @return The number of bytes that were added to this packet.
|
||||
*/
|
||||
size_t Packet::Send_bytes(const byte *begin, const byte *end)
|
||||
{
|
||||
size_t amount = std::min<size_t>(end - begin, this->limit - this->Size());
|
||||
this->buffer.insert(this->buffer.end(), begin, begin + amount);
|
||||
return amount;
|
||||
}
|
||||
|
||||
/*
|
||||
* Receiving commands
|
||||
@@ -162,18 +208,21 @@ void Packet::Send_string(const char *data)
|
||||
|
||||
|
||||
/**
|
||||
* Is it safe to read from the packet, i.e. didn't we run over the buffer ?
|
||||
* @param bytes_to_read The amount of bytes we want to try to read.
|
||||
* Is it safe to read from the packet, i.e. didn't we run over the buffer?
|
||||
* In case \c close_connection is true, the connection will be closed when one would
|
||||
* overrun the buffer. When it is false, the connection remains untouched.
|
||||
* @param bytes_to_read The amount of bytes we want to try to read.
|
||||
* @param close_connection Whether to close the connection if one cannot read that amount.
|
||||
* @return True if that is safe, otherwise false.
|
||||
*/
|
||||
bool Packet::CanReadFromPacket(uint bytes_to_read)
|
||||
bool Packet::CanReadFromPacket(size_t bytes_to_read, bool close_connection)
|
||||
{
|
||||
/* Don't allow reading from a quit client/client who send bad data */
|
||||
if (this->cs->HasClientQuit()) return false;
|
||||
|
||||
/* Check if variable is within packet-size */
|
||||
if (this->pos + bytes_to_read > this->size) {
|
||||
this->cs->NetworkSocketHandler::CloseConnection();
|
||||
if (this->pos + bytes_to_read > this->Size()) {
|
||||
if (close_connection) this->cs->NetworkSocketHandler::MarkClosed();
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -181,13 +230,45 @@ bool Packet::CanReadFromPacket(uint bytes_to_read)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the packet size from the raw packet and stores it in the packet->size
|
||||
* Check whether the packet, given the position of the "write" pointer, has read
|
||||
* enough of the packet to contain its size.
|
||||
* @return True iff there is enough data in the packet to contain the packet's size.
|
||||
*/
|
||||
void Packet::ReadRawPacketSize()
|
||||
bool Packet::HasPacketSizeData() const
|
||||
{
|
||||
return this->pos >= sizeof(PacketSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of bytes in the packet.
|
||||
* When sending a packet this is the size of the data up to that moment.
|
||||
* When receiving a packet (before PrepareToRead) this is the allocated size for the data to be read.
|
||||
* When reading a packet (after PrepareToRead) this is the full size of the packet.
|
||||
* @return The packet's size.
|
||||
*/
|
||||
size_t Packet::Size() const
|
||||
{
|
||||
return this->buffer.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the packet size from the raw packet and stores it in the packet->size
|
||||
* @return True iff the packet size seems plausible.
|
||||
*/
|
||||
bool Packet::ParsePacketSize()
|
||||
{
|
||||
assert(this->cs != nullptr && this->next == nullptr);
|
||||
this->size = (PacketSize)this->buffer[0];
|
||||
this->size += (PacketSize)this->buffer[1] << 8;
|
||||
size_t size = (size_t)this->buffer[0];
|
||||
size += (size_t)this->buffer[1] << 8;
|
||||
|
||||
/* If the size of the packet is less than the bytes required for the size and type of
|
||||
* the packet, or more than the allowed limit, then something is wrong with the packet.
|
||||
* In those cases the packet can generally be regarded as containing garbage data. */
|
||||
if (size < sizeof(PacketSize) + sizeof(PacketType) || size > this->limit) return false;
|
||||
|
||||
this->buffer.resize(size);
|
||||
this->pos = sizeof(PacketSize);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -195,12 +276,20 @@ void Packet::ReadRawPacketSize()
|
||||
*/
|
||||
void Packet::PrepareToRead()
|
||||
{
|
||||
this->ReadRawPacketSize();
|
||||
|
||||
/* Put the position on the right place */
|
||||
this->pos = sizeof(PacketSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the \c PacketType from this packet.
|
||||
* @return The packet type.
|
||||
*/
|
||||
PacketType Packet::GetPacketType() const
|
||||
{
|
||||
assert(this->Size() >= sizeof(PacketSize) + sizeof(PacketType));
|
||||
return static_cast<PacketType>(buffer[sizeof(PacketSize)]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a boolean from the packet.
|
||||
* @return The read data.
|
||||
@@ -218,7 +307,7 @@ uint8 Packet::Recv_uint8()
|
||||
{
|
||||
uint8 n;
|
||||
|
||||
if (!this->CanReadFromPacket(sizeof(n))) return 0;
|
||||
if (!this->CanReadFromPacket(sizeof(n), true)) return 0;
|
||||
|
||||
n = this->buffer[this->pos++];
|
||||
return n;
|
||||
@@ -232,7 +321,7 @@ uint16 Packet::Recv_uint16()
|
||||
{
|
||||
uint16 n;
|
||||
|
||||
if (!this->CanReadFromPacket(sizeof(n))) return 0;
|
||||
if (!this->CanReadFromPacket(sizeof(n), true)) return 0;
|
||||
|
||||
n = (uint16)this->buffer[this->pos++];
|
||||
n += (uint16)this->buffer[this->pos++] << 8;
|
||||
@@ -247,7 +336,7 @@ uint32 Packet::Recv_uint32()
|
||||
{
|
||||
uint32 n;
|
||||
|
||||
if (!this->CanReadFromPacket(sizeof(n))) return 0;
|
||||
if (!this->CanReadFromPacket(sizeof(n), true)) return 0;
|
||||
|
||||
n = (uint32)this->buffer[this->pos++];
|
||||
n += (uint32)this->buffer[this->pos++] << 8;
|
||||
@@ -264,7 +353,7 @@ uint64 Packet::Recv_uint64()
|
||||
{
|
||||
uint64 n;
|
||||
|
||||
if (!this->CanReadFromPacket(sizeof(n))) return 0;
|
||||
if (!this->CanReadFromPacket(sizeof(n), true)) return 0;
|
||||
|
||||
n = (uint64)this->buffer[this->pos++];
|
||||
n += (uint64)this->buffer[this->pos++] << 8;
|
||||
@@ -278,31 +367,39 @@ uint64 Packet::Recv_uint64()
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a string till it finds a '\0' in the stream.
|
||||
* @param buffer The buffer to put the data into.
|
||||
* @param size The size of the buffer.
|
||||
* Reads characters (bytes) from the packet until it finds a '\0', or reaches a
|
||||
* maximum of \c length characters.
|
||||
* When the '\0' has not been reached in the first \c length read characters,
|
||||
* more characters are read from the packet until '\0' has been reached. However,
|
||||
* these characters will not end up in the returned string.
|
||||
* The length of the returned string will be at most \c length - 1 characters.
|
||||
* @param length The maximum length of the string including '\0'.
|
||||
* @param settings The string validation settings.
|
||||
* @return The validated string.
|
||||
*/
|
||||
void Packet::Recv_string(char *buffer, size_t size, StringValidationSettings settings)
|
||||
std::string Packet::Recv_string(size_t length, StringValidationSettings settings)
|
||||
{
|
||||
PacketSize pos;
|
||||
char *bufp = buffer;
|
||||
const char *last = buffer + size - 1;
|
||||
assert(length > 1);
|
||||
|
||||
/* Don't allow reading from a closed socket */
|
||||
if (cs->HasClientQuit()) return;
|
||||
/* Both loops with Recv_uint8 terminate when reading past the end of the
|
||||
* packet as Recv_uint8 then closes the connection and returns 0. */
|
||||
std::string str;
|
||||
char character;
|
||||
while (--length > 0 && (character = this->Recv_uint8()) != '\0') str.push_back(character);
|
||||
|
||||
pos = this->pos;
|
||||
while (--size > 0 && pos < this->size && (*buffer++ = this->buffer[pos++]) != '\0') {}
|
||||
|
||||
if (size == 0 || pos == this->size) {
|
||||
*buffer = '\0';
|
||||
/* If size was sooner to zero then the string in the stream
|
||||
* skip till the \0, so than packet can be read out correctly for the rest */
|
||||
while (pos < this->size && this->buffer[pos] != '\0') pos++;
|
||||
pos++;
|
||||
if (length == 0) {
|
||||
/* The string in the packet was longer. Read until the termination. */
|
||||
while (this->Recv_uint8() != '\0') {}
|
||||
}
|
||||
this->pos = pos;
|
||||
|
||||
str_validate(bufp, last, settings);
|
||||
return StrMakeValid(str, settings);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the amount of bytes that are still available for the Transfer functions.
|
||||
* @return The number of bytes that still have to be transfered.
|
||||
*/
|
||||
size_t Packet::RemainingBytesToTransfer() const
|
||||
{
|
||||
return this->Size() - this->pos;
|
||||
}
|
||||
|
||||
+130
-25
@@ -12,9 +12,12 @@
|
||||
#ifndef NETWORK_CORE_PACKET_H
|
||||
#define NETWORK_CORE_PACKET_H
|
||||
|
||||
#include "os_abstraction.h"
|
||||
#include "config.h"
|
||||
#include "core.h"
|
||||
#include "../../string_type.h"
|
||||
#include <functional>
|
||||
#include <limits>
|
||||
|
||||
typedef uint16 PacketSize; ///< Size of the whole packet.
|
||||
typedef uint8 PacketType; ///< Identifier for the packet
|
||||
@@ -23,10 +26,11 @@ typedef uint8 PacketType; ///< Identifier for the packet
|
||||
* Internal entity of a packet. As everything is sent as a packet,
|
||||
* all network communication will need to call the functions that
|
||||
* populate the packet.
|
||||
* Every packet can be at most SEND_MTU bytes. Overflowing this
|
||||
* limit will give an assertion when sending (i.e. writing) the
|
||||
* packet. Reading past the size of the packet when receiving
|
||||
* will return all 0 values and "" in case of the string.
|
||||
* Every packet can be at most a limited number bytes set in the
|
||||
* constructor. Overflowing this limit will give an assertion when
|
||||
* sending (i.e. writing) the packet. Reading past the size of the
|
||||
* packet when receiving will return all 0 values and "" in case of
|
||||
* the string.
|
||||
*
|
||||
* --- Points of attention ---
|
||||
* - all > 1 byte integral values are written in little endian,
|
||||
@@ -38,49 +42,150 @@ typedef uint8 PacketType; ///< Identifier for the packet
|
||||
* (year % 4 == 0) and ((year % 100 != 0) or (year % 400 == 0))
|
||||
*/
|
||||
struct Packet {
|
||||
private:
|
||||
/** The next packet. Used for queueing packets before sending. */
|
||||
Packet *next;
|
||||
/**
|
||||
* The size of the whole packet for received packets. For packets
|
||||
* that will be sent, the value is filled in just before the
|
||||
* actual transmission.
|
||||
*/
|
||||
PacketSize size;
|
||||
/** The current read/write position in the packet */
|
||||
PacketSize pos;
|
||||
/** The buffer of this packet, of basically variable length up to SEND_MTU. */
|
||||
byte *buffer;
|
||||
/** The buffer of this packet. */
|
||||
std::vector<byte> buffer;
|
||||
/** The limit for the packet size. */
|
||||
size_t limit;
|
||||
|
||||
private:
|
||||
/** Socket we're associated with. */
|
||||
NetworkSocketHandler *cs;
|
||||
|
||||
public:
|
||||
Packet(NetworkSocketHandler *cs);
|
||||
Packet(PacketType type);
|
||||
~Packet();
|
||||
Packet(NetworkSocketHandler *cs, size_t limit, size_t initial_read_size = sizeof(PacketSize));
|
||||
Packet(PacketType type, size_t limit = COMPAT_MTU);
|
||||
|
||||
static void AddToQueue(Packet **queue, Packet *packet);
|
||||
static Packet *PopFromQueue(Packet **queue);
|
||||
|
||||
/* Sending/writing of packets */
|
||||
void PrepareToSend();
|
||||
|
||||
void Send_bool (bool data);
|
||||
void Send_uint8 (uint8 data);
|
||||
void Send_uint16(uint16 data);
|
||||
void Send_uint32(uint32 data);
|
||||
void Send_uint64(uint64 data);
|
||||
void Send_string(const char *data);
|
||||
bool CanWriteToPacket(size_t bytes_to_write);
|
||||
void Send_bool (bool data);
|
||||
void Send_uint8 (uint8 data);
|
||||
void Send_uint16(uint16 data);
|
||||
void Send_uint32(uint32 data);
|
||||
void Send_uint64(uint64 data);
|
||||
void Send_string(const std::string_view data);
|
||||
size_t Send_bytes (const byte *begin, const byte *end);
|
||||
|
||||
/* Reading/receiving of packets */
|
||||
void ReadRawPacketSize();
|
||||
bool HasPacketSizeData() const;
|
||||
bool ParsePacketSize();
|
||||
size_t Size() const;
|
||||
void PrepareToRead();
|
||||
PacketType GetPacketType() const;
|
||||
|
||||
bool CanReadFromPacket (uint bytes_to_read);
|
||||
bool CanReadFromPacket(size_t bytes_to_read, bool close_connection = false);
|
||||
bool Recv_bool ();
|
||||
uint8 Recv_uint8 ();
|
||||
uint16 Recv_uint16();
|
||||
uint32 Recv_uint32();
|
||||
uint64 Recv_uint64();
|
||||
void Recv_string(char *buffer, size_t size, StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK);
|
||||
std::string Recv_string(size_t length, StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK);
|
||||
|
||||
size_t RemainingBytesToTransfer() const;
|
||||
|
||||
/**
|
||||
* Transfer data from the packet to the given function. It starts reading at the
|
||||
* position the last transfer stopped.
|
||||
* See Packet::TransferIn for more information about transferring data to functions.
|
||||
* @param transfer_function The function to pass the buffer as second parameter and the
|
||||
* amount to write as third parameter. It returns the amount that
|
||||
* was written or -1 upon errors.
|
||||
* @param limit The maximum amount of bytes to transfer.
|
||||
* @param destination The first parameter of the transfer function.
|
||||
* @param args The fourth and further parameters to the transfer function, if any.
|
||||
* @return The return value of the transfer_function.
|
||||
*/
|
||||
template <
|
||||
typename A = size_t, ///< The type for the amount to be passed, so it can be cast to the right type.
|
||||
typename F, ///< The type of the function.
|
||||
typename D, ///< The type of the destination.
|
||||
typename ... Args> ///< The types of the remaining arguments to the function.
|
||||
ssize_t TransferOutWithLimit(F transfer_function, size_t limit, D destination, Args&& ... args)
|
||||
{
|
||||
size_t amount = std::min(this->RemainingBytesToTransfer(), limit);
|
||||
if (amount == 0) return 0;
|
||||
|
||||
assert(this->pos < this->buffer.size());
|
||||
assert(this->pos + amount <= this->buffer.size());
|
||||
/* Making buffer a char means casting a lot in the Recv/Send functions. */
|
||||
const char *output_buffer = reinterpret_cast<const char*>(this->buffer.data() + this->pos);
|
||||
ssize_t bytes = transfer_function(destination, output_buffer, static_cast<A>(amount), std::forward<Args>(args)...);
|
||||
if (bytes > 0) this->pos += bytes;
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transfer data from the packet to the given function. It starts reading at the
|
||||
* position the last transfer stopped.
|
||||
* See Packet::TransferIn for more information about transferring data to functions.
|
||||
* @param transfer_function The function to pass the buffer as second parameter and the
|
||||
* amount to write as third parameter. It returns the amount that
|
||||
* was written or -1 upon errors.
|
||||
* @param destination The first parameter of the transfer function.
|
||||
* @param args The fourth and further parameters to the transfer function, if any.
|
||||
* @tparam A The type for the amount to be passed, so it can be cast to the right type.
|
||||
* @tparam F The type of the transfer_function.
|
||||
* @tparam D The type of the destination.
|
||||
* @tparam Args The types of the remaining arguments to the function.
|
||||
* @return The return value of the transfer_function.
|
||||
*/
|
||||
template <typename A = size_t, typename F, typename D, typename ... Args>
|
||||
ssize_t TransferOut(F transfer_function, D destination, Args&& ... args)
|
||||
{
|
||||
return TransferOutWithLimit<A>(transfer_function, std::numeric_limits<size_t>::max(), destination, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
/**
|
||||
* Transfer data from the given function into the packet. It starts writing at the
|
||||
* position the last transfer stopped.
|
||||
*
|
||||
* Examples of functions that can be used to transfer data into a packet are TCP's
|
||||
* recv and UDP's recvfrom functions. They will directly write their data into the
|
||||
* packet without an intermediate buffer.
|
||||
* Examples of functions that can be used to transfer data from a packet are TCP's
|
||||
* send and UDP's sendto functions. They will directly read the data from the packet's
|
||||
* buffer without an intermediate buffer.
|
||||
* These are functions are special in a sense as even though the packet can send or
|
||||
* receive an amount of data, those functions can say they only processed a smaller
|
||||
* amount, so special handling is required to keep the position pointers correct.
|
||||
* Most of these transfer functions are in the form function(source, buffer, amount, ...),
|
||||
* so the template of this function will assume that as the base parameter order.
|
||||
*
|
||||
* This will attempt to write all the remaining bytes into the packet. It updates the
|
||||
* position based on how many bytes were actually written by the called transfer_function.
|
||||
* @param transfer_function The function to pass the buffer as second parameter and the
|
||||
* amount to read as third parameter. It returns the amount that
|
||||
* was read or -1 upon errors.
|
||||
* @param source The first parameter of the transfer function.
|
||||
* @param args The fourth and further parameters to the transfer function, if any.
|
||||
* @tparam A The type for the amount to be passed, so it can be cast to the right type.
|
||||
* @tparam F The type of the transfer_function.
|
||||
* @tparam S The type of the source.
|
||||
* @tparam Args The types of the remaining arguments to the function.
|
||||
* @return The return value of the transfer_function.
|
||||
*/
|
||||
template <typename A = size_t, typename F, typename S, typename ... Args>
|
||||
ssize_t TransferIn(F transfer_function, S source, Args&& ... args)
|
||||
{
|
||||
size_t amount = this->RemainingBytesToTransfer();
|
||||
if (amount == 0) return 0;
|
||||
|
||||
assert(this->pos < this->buffer.size());
|
||||
assert(this->pos + amount <= this->buffer.size());
|
||||
/* Making buffer a char means casting a lot in the Recv/Send functions. */
|
||||
char *input_buffer = reinterpret_cast<char*>(this->buffer.data() + this->pos);
|
||||
ssize_t bytes = transfer_function(source, input_buffer, static_cast<A>(amount), std::forward<Args>(args)...);
|
||||
if (bytes > 0) this->pos += bytes;
|
||||
return bytes;
|
||||
}
|
||||
};
|
||||
|
||||
#endif /* NETWORK_CORE_PACKET_H */
|
||||
|
||||
+46
-53
@@ -29,25 +29,45 @@ NetworkTCPSocketHandler::NetworkTCPSocketHandler(SOCKET s) :
|
||||
|
||||
NetworkTCPSocketHandler::~NetworkTCPSocketHandler()
|
||||
{
|
||||
this->CloseConnection();
|
||||
this->EmptyPacketQueue();
|
||||
this->CloseSocket();
|
||||
}
|
||||
|
||||
/**
|
||||
* Free all pending and partially received packets.
|
||||
*/
|
||||
void NetworkTCPSocketHandler::EmptyPacketQueue()
|
||||
{
|
||||
while (this->packet_queue != nullptr) {
|
||||
delete Packet::PopFromQueue(&this->packet_queue);
|
||||
}
|
||||
delete this->packet_recv;
|
||||
this->packet_recv = nullptr;
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the actual socket of the connection.
|
||||
* Please make sure CloseConnection is called before CloseSocket, as
|
||||
* otherwise not all resources might be released.
|
||||
*/
|
||||
void NetworkTCPSocketHandler::CloseSocket()
|
||||
{
|
||||
if (this->sock != INVALID_SOCKET) closesocket(this->sock);
|
||||
this->sock = INVALID_SOCKET;
|
||||
}
|
||||
|
||||
/**
|
||||
* This will put this socket handler in a close state. It will not
|
||||
* actually close the OS socket; use CloseSocket for this.
|
||||
* @param error Whether we quit under an error condition or not.
|
||||
* @return new status of the connection.
|
||||
*/
|
||||
NetworkRecvStatus NetworkTCPSocketHandler::CloseConnection(bool error)
|
||||
{
|
||||
this->MarkClosed();
|
||||
this->writable = false;
|
||||
NetworkSocketHandler::CloseConnection(error);
|
||||
|
||||
/* Free all pending and partially received packets */
|
||||
while (this->packet_queue != nullptr) {
|
||||
Packet *p = this->packet_queue->next;
|
||||
delete this->packet_queue;
|
||||
this->packet_queue = p;
|
||||
}
|
||||
delete this->packet_recv;
|
||||
this->packet_recv = nullptr;
|
||||
this->EmptyPacketQueue();
|
||||
|
||||
return NETWORK_RECV_STATUS_OKAY;
|
||||
}
|
||||
@@ -60,26 +80,10 @@ NetworkRecvStatus NetworkTCPSocketHandler::CloseConnection(bool error)
|
||||
*/
|
||||
void NetworkTCPSocketHandler::SendPacket(Packet *packet)
|
||||
{
|
||||
Packet *p;
|
||||
assert(packet != nullptr);
|
||||
|
||||
packet->PrepareToSend();
|
||||
|
||||
/* Reallocate the packet as in 99+% of the times we send at most 25 bytes and
|
||||
* keeping the other 1400+ bytes wastes memory, especially when someone tries
|
||||
* to do a denial of service attack! */
|
||||
packet->buffer = ReallocT(packet->buffer, packet->size);
|
||||
|
||||
/* Locate last packet buffered for the client */
|
||||
p = this->packet_queue;
|
||||
if (p == nullptr) {
|
||||
/* No packets yet */
|
||||
this->packet_queue = packet;
|
||||
} else {
|
||||
/* Skip to the last packet */
|
||||
while (p->next != nullptr) p = p->next;
|
||||
p->next = packet;
|
||||
}
|
||||
Packet::AddToQueue(&this->packet_queue, packet);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -101,15 +105,14 @@ SendPacketsState NetworkTCPSocketHandler::SendPackets(bool closing_down)
|
||||
if (!this->writable) return SPS_NONE_SENT;
|
||||
if (!this->IsConnected()) return SPS_CLOSED;
|
||||
|
||||
p = this->packet_queue;
|
||||
while (p != nullptr) {
|
||||
res = send(this->sock, (const char*)p->buffer + p->pos, p->size - p->pos, 0);
|
||||
while ((p = this->packet_queue) != nullptr) {
|
||||
res = p->TransferOut<int>(send, this->sock, 0);
|
||||
if (res == -1) {
|
||||
NetworkError err = NetworkError::GetLast();
|
||||
if (!err.WouldBlock()) {
|
||||
/* Something went wrong.. close client! */
|
||||
if (!closing_down) {
|
||||
DEBUG(net, 0, "send failed with error %s", err.AsString());
|
||||
Debug(net, 0, "Send failed: {}", err.AsString());
|
||||
this->CloseConnection();
|
||||
}
|
||||
return SPS_CLOSED;
|
||||
@@ -122,14 +125,10 @@ SendPacketsState NetworkTCPSocketHandler::SendPackets(bool closing_down)
|
||||
return SPS_CLOSED;
|
||||
}
|
||||
|
||||
p->pos += res;
|
||||
|
||||
/* Is this packet sent? */
|
||||
if (p->pos == p->size) {
|
||||
if (p->RemainingBytesToTransfer() == 0) {
|
||||
/* Go to the next packet */
|
||||
this->packet_queue = p->next;
|
||||
delete p;
|
||||
p = this->packet_queue;
|
||||
delete Packet::PopFromQueue(&this->packet_queue);
|
||||
} else {
|
||||
return SPS_PARTLY_SENT;
|
||||
}
|
||||
@@ -149,21 +148,20 @@ Packet *NetworkTCPSocketHandler::ReceivePacket()
|
||||
if (!this->IsConnected()) return nullptr;
|
||||
|
||||
if (this->packet_recv == nullptr) {
|
||||
this->packet_recv = new Packet(this);
|
||||
this->packet_recv = new Packet(this, TCP_MTU);
|
||||
}
|
||||
|
||||
Packet *p = this->packet_recv;
|
||||
|
||||
/* Read packet size */
|
||||
if (p->pos < sizeof(PacketSize)) {
|
||||
while (p->pos < sizeof(PacketSize)) {
|
||||
/* Read the size of the packet */
|
||||
res = recv(this->sock, (char*)p->buffer + p->pos, sizeof(PacketSize) - p->pos, 0);
|
||||
if (!p->HasPacketSizeData()) {
|
||||
while (p->RemainingBytesToTransfer() != 0) {
|
||||
res = p->TransferIn<int>(recv, this->sock, 0);
|
||||
if (res == -1) {
|
||||
NetworkError err = NetworkError::GetLast();
|
||||
if (!err.WouldBlock()) {
|
||||
/* Something went wrong... */
|
||||
if (!err.IsConnectionReset()) DEBUG(net, 0, "recv failed with error %s", err.AsString());
|
||||
if (!err.IsConnectionReset()) Debug(net, 0, "Recv failed: {}", err.AsString());
|
||||
this->CloseConnection();
|
||||
return nullptr;
|
||||
}
|
||||
@@ -175,26 +173,23 @@ Packet *NetworkTCPSocketHandler::ReceivePacket()
|
||||
this->CloseConnection();
|
||||
return nullptr;
|
||||
}
|
||||
p->pos += res;
|
||||
}
|
||||
|
||||
/* Read the packet size from the received packet */
|
||||
p->ReadRawPacketSize();
|
||||
|
||||
if (p->size > SEND_MTU) {
|
||||
/* Parse the size in the received packet and if not valid, close the connection. */
|
||||
if (!p->ParsePacketSize()) {
|
||||
this->CloseConnection();
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
/* Read rest of packet */
|
||||
while (p->pos < p->size) {
|
||||
res = recv(this->sock, (char*)p->buffer + p->pos, p->size - p->pos, 0);
|
||||
while (p->RemainingBytesToTransfer() != 0) {
|
||||
res = p->TransferIn<int>(recv, this->sock, 0);
|
||||
if (res == -1) {
|
||||
NetworkError err = NetworkError::GetLast();
|
||||
if (!err.WouldBlock()) {
|
||||
/* Something went wrong... */
|
||||
if (!err.IsConnectionReset()) DEBUG(net, 0, "recv failed with error %s", err.AsString());
|
||||
if (!err.IsConnectionReset()) Debug(net, 0, "Recv failed: {}", err.AsString());
|
||||
this->CloseConnection();
|
||||
return nullptr;
|
||||
}
|
||||
@@ -206,8 +201,6 @@ Packet *NetworkTCPSocketHandler::ReceivePacket()
|
||||
this->CloseConnection();
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
p->pos += res;
|
||||
}
|
||||
|
||||
/* Prepare for receiving a new packet */
|
||||
|
||||
+67
-13
@@ -16,6 +16,9 @@
|
||||
#include "packet.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <map>
|
||||
#include <thread>
|
||||
|
||||
/** The states of sending the packets. */
|
||||
enum SendPacketsState {
|
||||
@@ -30,6 +33,8 @@ class NetworkTCPSocketHandler : public NetworkSocketHandler {
|
||||
private:
|
||||
Packet *packet_queue; ///< Packets that are awaiting delivery
|
||||
Packet *packet_recv; ///< Partially received packet
|
||||
|
||||
void EmptyPacketQueue();
|
||||
public:
|
||||
SOCKET sock; ///< The socket currently connected to
|
||||
bool writable; ///< Can we write to this socket?
|
||||
@@ -40,7 +45,9 @@ public:
|
||||
*/
|
||||
bool IsConnected() const { return this->sock != INVALID_SOCKET; }
|
||||
|
||||
NetworkRecvStatus CloseConnection(bool error = true) override;
|
||||
virtual NetworkRecvStatus CloseConnection(bool error = true);
|
||||
void CloseSocket();
|
||||
|
||||
virtual void SendPacket(Packet *packet);
|
||||
SendPacketsState SendPackets(bool closing_down = false);
|
||||
|
||||
@@ -63,23 +70,53 @@ public:
|
||||
*/
|
||||
class TCPConnecter {
|
||||
private:
|
||||
std::atomic<bool> connected;///< Whether we succeeded in making the connection
|
||||
std::atomic<bool> aborted; ///< Whether we bailed out (i.e. connection making failed)
|
||||
bool killed; ///< Whether we got killed
|
||||
SOCKET sock; ///< The socket we're connecting with
|
||||
/**
|
||||
* The current status of the connecter.
|
||||
*
|
||||
* We track the status like this to ensure everything is executed from the
|
||||
* game-thread, and not at another random time where we might not have the
|
||||
* lock on the game-state.
|
||||
*/
|
||||
enum class Status {
|
||||
INIT, ///< TCPConnecter is created but resolving hasn't started.
|
||||
RESOLVING, ///< The hostname is being resolved (threaded).
|
||||
FAILURE, ///< Resolving failed.
|
||||
CONNECTING, ///< We are currently connecting.
|
||||
CONNECTED, ///< The connection is established.
|
||||
};
|
||||
|
||||
void Connect();
|
||||
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.
|
||||
|
||||
static void ThreadEntry(TCPConnecter *param);
|
||||
addrinfo *ai = nullptr; ///< getaddrinfo() allocated linked-list of resolved addresses.
|
||||
std::vector<addrinfo *> addresses; ///< Addresses we can connect to.
|
||||
std::map<SOCKET, NetworkAddress> sock_to_address; ///< Mapping of a socket to the real address it is connecting to. USed for DEBUG statements.
|
||||
size_t current_address = 0; ///< Current index in addresses we are trying.
|
||||
|
||||
protected:
|
||||
/** Address we're connecting to */
|
||||
NetworkAddress address;
|
||||
std::vector<SOCKET> sockets; ///< Pending connect() attempts.
|
||||
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);
|
||||
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 NetworkAddress &address);
|
||||
/** Silence the warnings */
|
||||
virtual ~TCPConnecter() {}
|
||||
TCPConnecter() {};
|
||||
TCPConnecter(const std::string &connection_string, uint16 default_port, NetworkAddress bind_address = {}, int family = AF_UNSPEC);
|
||||
virtual ~TCPConnecter();
|
||||
|
||||
/**
|
||||
* Callback when the connection succeeded.
|
||||
@@ -92,8 +129,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 */
|
||||
|
||||
@@ -30,18 +30,12 @@ static_assert((int)CRR_END == (int)ADMIN_CRR_END);
|
||||
NetworkAdminSocketHandler::NetworkAdminSocketHandler(SOCKET s) : status(ADMIN_STATUS_INACTIVE)
|
||||
{
|
||||
this->sock = s;
|
||||
this->admin_name[0] = '\0';
|
||||
this->admin_version[0] = '\0';
|
||||
}
|
||||
|
||||
NetworkAdminSocketHandler::~NetworkAdminSocketHandler()
|
||||
{
|
||||
}
|
||||
|
||||
NetworkRecvStatus NetworkAdminSocketHandler::CloseConnection(bool error)
|
||||
{
|
||||
delete this;
|
||||
return NETWORK_RECV_STATUS_CONN_LOST;
|
||||
return NETWORK_RECV_STATUS_CLIENT_QUIT;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -93,9 +87,9 @@ NetworkRecvStatus NetworkAdminSocketHandler::HandlePacket(Packet *p)
|
||||
|
||||
default:
|
||||
if (this->HasClientQuit()) {
|
||||
DEBUG(net, 0, "[tcp/admin] received invalid packet type %d from '%s' (%s)", type, this->admin_name, this->admin_version);
|
||||
Debug(net, 0, "[tcp/admin] Received invalid packet type {} from '{}' ({})", type, this->admin_name, this->admin_version);
|
||||
} else {
|
||||
DEBUG(net, 0, "[tcp/admin] received illegal packet from '%s' (%s)", this->admin_name, this->admin_version);
|
||||
Debug(net, 0, "[tcp/admin] Received illegal packet from '{}' ({})", this->admin_name, this->admin_version);
|
||||
}
|
||||
|
||||
this->CloseConnection();
|
||||
@@ -129,7 +123,7 @@ NetworkRecvStatus NetworkAdminSocketHandler::ReceivePackets()
|
||||
*/
|
||||
NetworkRecvStatus NetworkAdminSocketHandler::ReceiveInvalidPacket(PacketAdminType type)
|
||||
{
|
||||
DEBUG(net, 0, "[tcp/admin] received illegal packet type %d from admin %s (%s)", type, this->admin_name, this->admin_version);
|
||||
Debug(net, 0, "[tcp/admin] Received illegal packet type {} from admin {} ({})", type, this->admin_name, this->admin_version);
|
||||
return NETWORK_RECV_STATUS_MALFORMED_PACKET;
|
||||
}
|
||||
|
||||
|
||||
@@ -109,9 +109,9 @@ enum AdminCompanyRemoveReason {
|
||||
/** Main socket handler for admin related connections. */
|
||||
class NetworkAdminSocketHandler : public NetworkTCPSocketHandler {
|
||||
protected:
|
||||
char admin_name[NETWORK_CLIENT_NAME_LENGTH]; ///< Name of the admin.
|
||||
char admin_version[NETWORK_REVISION_LENGTH]; ///< Version string of the admin.
|
||||
AdminStatus status; ///< Status of this admin.
|
||||
std::string admin_name; ///< Name of the admin.
|
||||
std::string admin_version; ///< Version string of the admin.
|
||||
AdminStatus status; ///< Status of this admin.
|
||||
|
||||
NetworkRecvStatus ReceiveInvalidPacket(PacketAdminType type);
|
||||
|
||||
@@ -222,7 +222,7 @@ protected:
|
||||
|
||||
/**
|
||||
* Welcome a connected admin to the game:
|
||||
* string Name of the Server (e.g. as advertised to master server).
|
||||
* string Name of the Server.
|
||||
* string OpenTTD version string.
|
||||
* bool Server is dedicated.
|
||||
* string Name of the Map.
|
||||
@@ -482,7 +482,6 @@ public:
|
||||
NetworkRecvStatus CloseConnection(bool error = true) override;
|
||||
|
||||
NetworkAdminSocketHandler(SOCKET s);
|
||||
~NetworkAdminSocketHandler();
|
||||
|
||||
NetworkRecvStatus ReceivePackets();
|
||||
|
||||
|
||||
@@ -13,6 +13,10 @@
|
||||
#include "../../thread.h"
|
||||
|
||||
#include "tcp.h"
|
||||
#include "../network_coordinator.h"
|
||||
#include "../network_internal.h"
|
||||
|
||||
#include <deque>
|
||||
|
||||
#include "../../safeguards.h"
|
||||
|
||||
@@ -20,40 +24,439 @@
|
||||
static std::vector<TCPConnecter *> _tcp_connecters;
|
||||
|
||||
/**
|
||||
* Create a new connecter for the given address
|
||||
* @param address the (un)resolved 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 NetworkAddress &address) :
|
||||
connected(false),
|
||||
aborted(false),
|
||||
killed(false),
|
||||
sock(INVALID_SOCKET),
|
||||
address(address)
|
||||
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);
|
||||
if (!StartNewThread(nullptr, "ottd:tcp", &TCPConnecter::ThreadEntry, this)) {
|
||||
this->Connect();
|
||||
}
|
||||
}
|
||||
|
||||
/** The actual connection function */
|
||||
void TCPConnecter::Connect()
|
||||
/**
|
||||
* 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))
|
||||
{
|
||||
this->sock = this->address.Connect();
|
||||
if (this->sock == INVALID_SOCKET) {
|
||||
this->aborted = true;
|
||||
} else {
|
||||
this->connected = true;
|
||||
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()) {
|
||||
this->resolve_thread.join();
|
||||
}
|
||||
|
||||
for (const auto &socket : this->sockets) {
|
||||
closesocket(socket);
|
||||
}
|
||||
this->sockets.clear();
|
||||
this->sock_to_address.clear();
|
||||
|
||||
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.
|
||||
*/
|
||||
void TCPConnecter::Connect(addrinfo *address)
|
||||
{
|
||||
SOCKET sock = socket(address->ai_family, address->ai_socktype, address->ai_protocol);
|
||||
if (sock == INVALID_SOCKET) {
|
||||
Debug(net, 0, "Could not create {} {} socket: {}", NetworkAddress::SocketTypeAsString(address->ai_socktype), NetworkAddress::AddressFamilyAsString(address->ai_family), NetworkError::GetLast().AsString());
|
||||
return;
|
||||
}
|
||||
|
||||
if (!SetReusePort(sock)) {
|
||||
Debug(net, 0, "Setting reuse-port mode failed: {}", 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 {}: {}", this->bind_address.GetAddressAsString(), NetworkError::GetLast().AsString());
|
||||
closesocket(sock);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!SetNoDelay(sock)) {
|
||||
Debug(net, 1, "Setting TCP_NODELAY failed: {}", NetworkError::GetLast().AsString());
|
||||
}
|
||||
if (!SetNonBlocking(sock)) {
|
||||
Debug(net, 0, "Setting non-blocking mode failed: {}", NetworkError::GetLast().AsString());
|
||||
}
|
||||
|
||||
NetworkAddress network_address = NetworkAddress(address->ai_addr, (int)address->ai_addrlen);
|
||||
Debug(net, 5, "Attempting to connect to {}", network_address.GetAddressAsString());
|
||||
|
||||
int err = connect(sock, address->ai_addr, (int)address->ai_addrlen);
|
||||
if (err != 0 && !NetworkError::GetLast().IsConnectInProgress()) {
|
||||
closesocket(sock);
|
||||
|
||||
Debug(net, 1, "Could not connect to {}: {}", network_address.GetAddressAsString(), NetworkError::GetLast().AsString());
|
||||
return;
|
||||
}
|
||||
|
||||
this->sock_to_address[sock] = network_address;
|
||||
this->sockets.push_back(sock);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the connect() for the next address in the list.
|
||||
* @return True iff a new connect() is attempted.
|
||||
*/
|
||||
bool TCPConnecter::TryNextAddress()
|
||||
{
|
||||
if (this->current_address >= this->addresses.size()) return false;
|
||||
|
||||
this->last_attempt = std::chrono::steady_clock::now();
|
||||
this->Connect(this->addresses[this->current_address++]);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback when resolving is done.
|
||||
* @param ai A linked-list of address information.
|
||||
*/
|
||||
void TCPConnecter::OnResolved(addrinfo *ai)
|
||||
{
|
||||
std::deque<addrinfo *> addresses_ipv4, addresses_ipv6;
|
||||
|
||||
/* Apply "Happy Eyeballs" if it is likely IPv6 is functional. */
|
||||
|
||||
/* Detect if IPv6 is likely to succeed or not. */
|
||||
bool seen_ipv6 = false;
|
||||
bool resort = true;
|
||||
for (addrinfo *runp = ai; runp != nullptr; runp = runp->ai_next) {
|
||||
if (runp->ai_family == AF_INET6) {
|
||||
seen_ipv6 = true;
|
||||
} else if (!seen_ipv6) {
|
||||
/* We see an IPv4 before an IPv6; this most likely means there is
|
||||
* no IPv6 available on the system, so keep the order of this
|
||||
* list. */
|
||||
resort = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/* 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);
|
||||
} else {
|
||||
addresses_ipv4.emplace_back(runp);
|
||||
}
|
||||
} else {
|
||||
this->addresses.emplace_back(runp);
|
||||
}
|
||||
}
|
||||
|
||||
/* If we want to resort, make the list like IPv6 / IPv4 / IPv6 / IPv4 / ..
|
||||
* for how ever many (round-robin) DNS entries we have. */
|
||||
if (resort) {
|
||||
while (!addresses_ipv4.empty() || !addresses_ipv6.empty()) {
|
||||
if (!addresses_ipv6.empty()) {
|
||||
this->addresses.push_back(addresses_ipv6.front());
|
||||
addresses_ipv6.pop_front();
|
||||
}
|
||||
if (!addresses_ipv4.empty()) {
|
||||
this->addresses.push_back(addresses_ipv4.front());
|
||||
addresses_ipv4.pop_front();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (_debug_net_level >= 6) {
|
||||
Debug(net, 6, "{} resolved in:", this->connection_string);
|
||||
for (const auto &address : this->addresses) {
|
||||
Debug(net, 6, "- {}", NetworkAddress(address->ai_addr, (int)address->ai_addrlen).GetAddressAsString());
|
||||
}
|
||||
}
|
||||
|
||||
this->current_address = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start resolving the hostname.
|
||||
*
|
||||
* This function must change "status" to either Status::FAILURE
|
||||
* or Status::CONNECTING before returning.
|
||||
*/
|
||||
void TCPConnecter::Resolve()
|
||||
{
|
||||
/* Port is already guaranteed part of the connection_string. */
|
||||
NetworkAddress address = ParseConnectionString(this->connection_string, 0);
|
||||
|
||||
addrinfo hints;
|
||||
memset(&hints, 0, sizeof(hints));
|
||||
hints.ai_family = AF_UNSPEC;
|
||||
hints.ai_flags = AI_ADDRCONFIG;
|
||||
hints.ai_socktype = SOCK_STREAM;
|
||||
|
||||
char port_name[6];
|
||||
seprintf(port_name, lastof(port_name), "%u", address.GetPort());
|
||||
|
||||
static bool getaddrinfo_timeout_error_shown = false;
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
|
||||
addrinfo *ai;
|
||||
int error = getaddrinfo(address.GetHostname().c_str(), port_name, &hints, &ai);
|
||||
|
||||
auto end = std::chrono::steady_clock::now();
|
||||
auto duration = std::chrono::duration_cast<std::chrono::seconds>(end - start);
|
||||
if (!getaddrinfo_timeout_error_shown && duration >= std::chrono::seconds(5)) {
|
||||
Debug(net, 0, "getaddrinfo() for address \"{}\" took {} seconds", this->connection_string, duration.count());
|
||||
Debug(net, 0, " This is likely an issue in the DNS name resolver's configuration causing it to time out");
|
||||
getaddrinfo_timeout_error_shown = true;
|
||||
}
|
||||
|
||||
if (error != 0) {
|
||||
Debug(net, 0, "Failed to resolve DNS for {}", this->connection_string);
|
||||
this->status = Status::FAILURE;
|
||||
return;
|
||||
}
|
||||
|
||||
this->ai = ai;
|
||||
this->OnResolved(ai);
|
||||
|
||||
this->status = Status::CONNECTING;
|
||||
}
|
||||
|
||||
/**
|
||||
* Thunk to start Resolve() on the right instance.
|
||||
*/
|
||||
/* static */ void TCPConnecter::ResolveThunk(TCPConnecter *connecter)
|
||||
{
|
||||
connecter->Resolve();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if there was activity for this connecter.
|
||||
* @return True iff the TCPConnecter is done and can be cleaned up.
|
||||
*/
|
||||
bool TCPConnecter::CheckActivity()
|
||||
{
|
||||
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). */
|
||||
if (StartNewThread(&this->resolve_thread, "ottd:resolve", &TCPConnecter::ResolveThunk, this)) {
|
||||
this->status = Status::RESOLVING;
|
||||
return false;
|
||||
}
|
||||
|
||||
/* No threads, do a blocking resolve. */
|
||||
this->Resolve();
|
||||
|
||||
/* Continue as we are either failed or can start the first
|
||||
* connection. The rest of this function handles exactly that. */
|
||||
break;
|
||||
|
||||
case Status::RESOLVING:
|
||||
/* Wait till Resolve() comes back with an answer (in case it runs threaded). */
|
||||
return false;
|
||||
|
||||
case Status::FAILURE:
|
||||
/* Ensure the OnFailure() is called from the game-thread instead of the
|
||||
* resolve-thread, as otherwise we can get into some threading issues. */
|
||||
this->OnFailure();
|
||||
return true;
|
||||
|
||||
case Status::CONNECTING:
|
||||
case Status::CONNECTED:
|
||||
break;
|
||||
}
|
||||
|
||||
/* If there are no attempts pending, connect to the next. */
|
||||
if (this->sockets.empty()) {
|
||||
if (!this->TryNextAddress()) {
|
||||
/* There were no more addresses to try, so we failed. */
|
||||
this->OnFailure();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
fd_set write_fd;
|
||||
FD_ZERO(&write_fd);
|
||||
for (const auto &socket : this->sockets) {
|
||||
FD_SET(socket, &write_fd);
|
||||
}
|
||||
|
||||
timeval tv;
|
||||
tv.tv_usec = 0;
|
||||
tv.tv_sec = 0;
|
||||
int n = select(FD_SETSIZE, nullptr, &write_fd, nullptr, &tv);
|
||||
/* select() failed; hopefully next try it doesn't. */
|
||||
if (n < 0) {
|
||||
/* select() normally never fails; so hopefully it works next try! */
|
||||
Debug(net, 1, "select() failed: {}", NetworkError::GetLast().AsString());
|
||||
return false;
|
||||
}
|
||||
|
||||
/* No socket updates. */
|
||||
if (n == 0) {
|
||||
/* Wait 250ms between attempting another address. */
|
||||
if (std::chrono::steady_clock::now() < this->last_attempt + std::chrono::milliseconds(250)) return false;
|
||||
|
||||
/* Try the next address in the list. */
|
||||
if (this->TryNextAddress()) return false;
|
||||
|
||||
/* Wait up to 3 seconds since the last connection we started. */
|
||||
if (std::chrono::steady_clock::now() < this->last_attempt + std::chrono::milliseconds(3000)) return false;
|
||||
|
||||
/* More than 3 seconds no socket reported activity, and there are no
|
||||
* more address to try. Timeout the attempt. */
|
||||
Debug(net, 0, "Timeout while connecting to {}", this->connection_string);
|
||||
|
||||
for (const auto &socket : this->sockets) {
|
||||
closesocket(socket);
|
||||
}
|
||||
this->sockets.clear();
|
||||
this->sock_to_address.clear();
|
||||
|
||||
this->OnFailure();
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Check for errors on any of the sockets. */
|
||||
for (auto it = this->sockets.begin(); it != this->sockets.end(); /* nothing */) {
|
||||
NetworkError socket_error = GetSocketError(*it);
|
||||
if (socket_error.HasError()) {
|
||||
Debug(net, 1, "Could not connect to {}: {}", this->sock_to_address[*it].GetAddressAsString(), socket_error.AsString());
|
||||
closesocket(*it);
|
||||
this->sock_to_address.erase(*it);
|
||||
it = this->sockets.erase(it);
|
||||
} else {
|
||||
it++;
|
||||
}
|
||||
}
|
||||
|
||||
/* In case all sockets had an error, queue a new one. */
|
||||
if (this->sockets.empty()) {
|
||||
if (!this->TryNextAddress()) {
|
||||
/* There were no more addresses to try, so we failed. */
|
||||
this->OnFailure();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* At least one socket is connected. The first one that does is the one
|
||||
* we will be using, and we close all other sockets. */
|
||||
SOCKET connected_socket = INVALID_SOCKET;
|
||||
for (auto it = this->sockets.begin(); it != this->sockets.end(); /* nothing */) {
|
||||
if (connected_socket == INVALID_SOCKET && FD_ISSET(*it, &write_fd)) {
|
||||
connected_socket = *it;
|
||||
} else {
|
||||
closesocket(*it);
|
||||
}
|
||||
this->sock_to_address.erase(*it);
|
||||
it = this->sockets.erase(it);
|
||||
}
|
||||
assert(connected_socket != INVALID_SOCKET);
|
||||
|
||||
Debug(net, 3, "Connected to {}", this->connection_string);
|
||||
if (_debug_net_level >= 5) {
|
||||
Debug(net, 5, "- using {}", NetworkAddress::GetPeerName(connected_socket));
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Entry point for the new threads.
|
||||
* @param param the TCPConnecter instance to call Connect on.
|
||||
* 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.
|
||||
*/
|
||||
/* static */ void TCPConnecter::ThreadEntry(TCPConnecter *param)
|
||||
void TCPServerConnecter::SetConnected(SOCKET sock)
|
||||
{
|
||||
param->Connect();
|
||||
this->socket = sock;
|
||||
this->status = Status::CONNECTED;
|
||||
}
|
||||
|
||||
/**
|
||||
* The connection couldn't be established.
|
||||
*/
|
||||
void TCPServerConnecter::SetFailure()
|
||||
{
|
||||
this->status = Status::FAILURE;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -66,32 +469,22 @@ void TCPConnecter::Connect()
|
||||
{
|
||||
for (auto iter = _tcp_connecters.begin(); iter < _tcp_connecters.end(); /* nothing */) {
|
||||
TCPConnecter *cur = *iter;
|
||||
const bool connected = cur->connected.load();
|
||||
const bool aborted = cur->aborted.load();
|
||||
if ((connected || aborted) && cur->killed) {
|
||||
|
||||
if (cur->CheckActivity()) {
|
||||
iter = _tcp_connecters.erase(iter);
|
||||
if (cur->sock != INVALID_SOCKET) closesocket(cur->sock);
|
||||
delete cur;
|
||||
continue;
|
||||
} else {
|
||||
iter++;
|
||||
}
|
||||
if (connected) {
|
||||
iter = _tcp_connecters.erase(iter);
|
||||
cur->OnConnect(cur->sock);
|
||||
delete cur;
|
||||
continue;
|
||||
}
|
||||
if (aborted) {
|
||||
iter = _tcp_connecters.erase(iter);
|
||||
cur->OnFailure();
|
||||
delete cur;
|
||||
continue;
|
||||
}
|
||||
iter++;
|
||||
}
|
||||
}
|
||||
|
||||
/** Kill all connection attempts. */
|
||||
/* static */ void TCPConnecter::KillAll()
|
||||
{
|
||||
for (TCPConnecter *conn : _tcp_connecters) conn->killed = true;
|
||||
for (auto iter = _tcp_connecters.begin(); iter < _tcp_connecters.end(); /* nothing */) {
|
||||
TCPConnecter *cur = *iter;
|
||||
iter = _tcp_connecters.erase(iter);
|
||||
delete cur;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,62 +10,16 @@
|
||||
*/
|
||||
|
||||
#include "../../stdafx.h"
|
||||
#ifndef OPENTTD_MSU
|
||||
#include "../../textfile_gui.h"
|
||||
#include "../../newgrf_config.h"
|
||||
#include "../../base_media_base.h"
|
||||
#include "../../ai/ai.hpp"
|
||||
#include "../../game/game.hpp"
|
||||
#include "../../fios.h"
|
||||
#endif /* OPENTTD_MSU */
|
||||
#include "tcp_content.h"
|
||||
|
||||
#include "../../safeguards.h"
|
||||
|
||||
/** Clear everything in the struct */
|
||||
ContentInfo::ContentInfo()
|
||||
{
|
||||
memset(this, 0, sizeof(*this));
|
||||
}
|
||||
|
||||
/** Free everything allocated */
|
||||
ContentInfo::~ContentInfo()
|
||||
{
|
||||
free(this->dependencies);
|
||||
free(this->tags);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy data from other #ContentInfo and take ownership of allocated stuff.
|
||||
* @param other Source to copy from. #dependencies and #tags will be NULLed.
|
||||
*/
|
||||
void ContentInfo::TransferFrom(ContentInfo *other)
|
||||
{
|
||||
if (other != this) {
|
||||
free(this->dependencies);
|
||||
free(this->tags);
|
||||
memcpy(this, other, sizeof(ContentInfo));
|
||||
other->dependencies = nullptr;
|
||||
other->tags = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the size of the data as send over the network.
|
||||
* @return the size.
|
||||
*/
|
||||
size_t ContentInfo::Size() const
|
||||
{
|
||||
size_t len = 0;
|
||||
for (uint i = 0; i < this->tag_count; i++) len += strlen(this->tags[i]) + 1;
|
||||
|
||||
/* The size is never larger than the content info size plus the size of the
|
||||
* tags and dependencies */
|
||||
return sizeof(*this) +
|
||||
sizeof(this->dependency_count) +
|
||||
sizeof(*this->dependencies) * this->dependency_count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the state either selected or autoselected?
|
||||
* @return true iff that's the case
|
||||
@@ -92,7 +46,6 @@ bool ContentInfo::IsValid() const
|
||||
return this->state < ContentInfo::INVALID && this->type >= CONTENT_TYPE_BEGIN && this->type < CONTENT_TYPE_END;
|
||||
}
|
||||
|
||||
#ifndef OPENTTD_MSU
|
||||
/**
|
||||
* Search a textfile file next to this file in the content list.
|
||||
* @param type The type of the textfile to search for.
|
||||
@@ -139,16 +92,6 @@ const char *ContentInfo::GetTextfile(TextfileType type) const
|
||||
if (tmp == nullptr) return nullptr;
|
||||
return ::GetTextfile(type, GetContentInfoSubDir(this->type), tmp);
|
||||
}
|
||||
#endif /* OPENTTD_MSU */
|
||||
|
||||
void NetworkContentSocketHandler::Close()
|
||||
{
|
||||
CloseConnection();
|
||||
if (this->sock == INVALID_SOCKET) return;
|
||||
|
||||
closesocket(this->sock);
|
||||
this->sock = INVALID_SOCKET;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the given packet, i.e. pass it to the right
|
||||
@@ -171,9 +114,9 @@ bool NetworkContentSocketHandler::HandlePacket(Packet *p)
|
||||
|
||||
default:
|
||||
if (this->HasClientQuit()) {
|
||||
DEBUG(net, 0, "[tcp/content] received invalid packet type %d from %s", type, this->client_addr.GetAddressAsString().c_str());
|
||||
Debug(net, 0, "[tcp/content] Received invalid packet type {}", type);
|
||||
} else {
|
||||
DEBUG(net, 0, "[tcp/content] received illegal packet from %s", this->client_addr.GetAddressAsString().c_str());
|
||||
Debug(net, 0, "[tcp/content] Received illegal packet");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -224,7 +167,7 @@ bool NetworkContentSocketHandler::ReceivePackets()
|
||||
*/
|
||||
bool NetworkContentSocketHandler::ReceiveInvalidPacket(PacketContentType type)
|
||||
{
|
||||
DEBUG(net, 0, "[tcp/content] received illegal packet type %d from %s", type, this->client_addr.GetAddressAsString().c_str());
|
||||
Debug(net, 0, "[tcp/content] Received illegal packet type {}", type);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -236,7 +179,6 @@ bool NetworkContentSocketHandler::Receive_SERVER_INFO(Packet *p) { return this->
|
||||
bool NetworkContentSocketHandler::Receive_CLIENT_CONTENT(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CONTENT_CLIENT_CONTENT); }
|
||||
bool NetworkContentSocketHandler::Receive_SERVER_CONTENT(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CONTENT_SERVER_CONTENT); }
|
||||
|
||||
#ifndef OPENTTD_MSU
|
||||
/**
|
||||
* Helper to get the subdirectory a #ContentInfo is located in.
|
||||
* @param type The type of content.
|
||||
@@ -261,4 +203,3 @@ Subdirectory GetContentInfoSubDir(ContentType type)
|
||||
case CONTENT_TYPE_HEIGHTMAP: return HEIGHTMAP_DIR;
|
||||
}
|
||||
}
|
||||
#endif /* OPENTTD_MSU */
|
||||
|
||||
@@ -21,9 +21,6 @@
|
||||
/** Base socket handler for all Content TCP sockets */
|
||||
class NetworkContentSocketHandler : public NetworkTCPSocketHandler {
|
||||
protected:
|
||||
NetworkAddress client_addr; ///< The address we're connected to.
|
||||
void Close() override;
|
||||
|
||||
bool ReceiveInvalidPacket(PacketContentType type);
|
||||
|
||||
/**
|
||||
@@ -119,20 +116,21 @@ public:
|
||||
* @param s the socket we are connected with
|
||||
* @param address IP etc. of the client
|
||||
*/
|
||||
NetworkContentSocketHandler(SOCKET s = INVALID_SOCKET, const NetworkAddress &address = NetworkAddress()) :
|
||||
NetworkTCPSocketHandler(s),
|
||||
client_addr(address)
|
||||
NetworkContentSocketHandler(SOCKET s = INVALID_SOCKET) :
|
||||
NetworkTCPSocketHandler(s)
|
||||
{
|
||||
}
|
||||
|
||||
/** On destructing of this class, the socket needs to be closed */
|
||||
virtual ~NetworkContentSocketHandler() { this->Close(); }
|
||||
virtual ~NetworkContentSocketHandler()
|
||||
{
|
||||
/* Virtual functions get called statically in destructors, so make it explicit to remove any confusion. */
|
||||
this->CloseSocket();
|
||||
}
|
||||
|
||||
bool ReceivePackets();
|
||||
};
|
||||
|
||||
#ifndef OPENTTD_MSU
|
||||
Subdirectory GetContentInfoSubDir(ContentType type);
|
||||
#endif /* OPENTTD_MSU */
|
||||
|
||||
#endif /* NETWORK_CORE_TCP_CONTENT_H */
|
||||
|
||||
@@ -26,6 +26,7 @@ enum ContentType {
|
||||
CONTENT_TYPE_GAME = 9, ///< The content consists of a game script
|
||||
CONTENT_TYPE_GAME_LIBRARY = 10, ///< The content consists of a GS library
|
||||
CONTENT_TYPE_END, ///< Helper to mark the end of the types
|
||||
INVALID_CONTENT_TYPE = 0xFF, ///< Invalid/uninitialized content
|
||||
};
|
||||
|
||||
/** Enum with all types of TCP content packets. The order MUST not be changed **/
|
||||
@@ -57,34 +58,24 @@ struct ContentInfo {
|
||||
INVALID, ///< The content's invalid
|
||||
};
|
||||
|
||||
ContentType type; ///< Type of content
|
||||
ContentID id; ///< Unique (server side) ID for the content
|
||||
uint32 filesize; ///< Size of the file
|
||||
char filename[48]; ///< Filename (for the .tar.gz; only valid on download)
|
||||
char name[32]; ///< Name of the content
|
||||
char version[16]; ///< Version of the content
|
||||
char url[96]; ///< URL related to the content
|
||||
char description[512]; ///< Description of the content
|
||||
uint32 unique_id; ///< Unique ID; either GRF ID or shortname
|
||||
byte md5sum[16]; ///< The MD5 checksum
|
||||
uint8 dependency_count; ///< Number of dependencies
|
||||
ContentID *dependencies; ///< Malloced array of dependencies (unique server side ids)
|
||||
uint8 tag_count; ///< Number of tags
|
||||
char (*tags)[32]; ///< Malloced array of tags (strings)
|
||||
State state; ///< Whether the content info is selected (for download)
|
||||
bool upgrade; ///< This item is an upgrade
|
||||
ContentType type = INVALID_CONTENT_TYPE; ///< Type of content
|
||||
ContentID id = INVALID_CONTENT_ID; ///< Unique (server side) ID for the content
|
||||
uint32 filesize = 0; ///< Size of the file
|
||||
std::string filename; ///< Filename (for the .tar.gz; only valid on download)
|
||||
std::string name; ///< Name of the content
|
||||
std::string version; ///< Version of the content
|
||||
std::string url; ///< URL related to the content
|
||||
std::string description; ///< Description of the content
|
||||
uint32 unique_id = 0; ///< Unique ID; either GRF ID or shortname
|
||||
byte md5sum[16] = {0}; ///< The MD5 checksum
|
||||
std::vector<ContentID> dependencies; ///< The dependencies (unique server side ids)
|
||||
StringList tags; ///< Tags associated with the content
|
||||
State state = State::UNSELECTED; ///< Whether the content info is selected (for download)
|
||||
bool upgrade = false; ///< This item is an upgrade
|
||||
|
||||
ContentInfo();
|
||||
~ContentInfo();
|
||||
|
||||
void TransferFrom(ContentInfo *other);
|
||||
|
||||
size_t Size() const;
|
||||
bool IsSelected() const;
|
||||
bool IsValid() const;
|
||||
#ifndef OPENTTD_MSU
|
||||
const char *GetTextfile(TextfileType type) const;
|
||||
#endif /* OPENTTD_MSU */
|
||||
};
|
||||
|
||||
#endif /* NETWORK_CORE_TCP_CONTENT_TYPE_H */
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
* 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);
|
||||
case PACKET_COORDINATOR_GC_NEWGRF_LOOKUP: return this->Receive_GC_NEWGRF_LOOKUP(p);
|
||||
case PACKET_COORDINATOR_GC_TURN_CONNECT: return this->Receive_GC_TURN_CONNECT(p);
|
||||
|
||||
default:
|
||||
Debug(net, 0, "[tcp/coordinator] Received invalid packet type {}", 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.
|
||||
*/
|
||||
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);
|
||||
delete p;
|
||||
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 {}", 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); }
|
||||
bool NetworkCoordinatorSocketHandler::Receive_GC_NEWGRF_LOOKUP(Packet *p) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_NEWGRF_LOOKUP); }
|
||||
bool NetworkCoordinatorSocketHandler::Receive_GC_TURN_CONNECT(Packet *p) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_TURN_CONNECT); }
|
||||
@@ -0,0 +1,318 @@
|
||||
/*
|
||||
* 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_GC_NEWGRF_LOOKUP, ///< Game Coordinator informs client about NewGRF lookup table updates needed for GC_LISTING.
|
||||
PACKET_COORDINATOR_GC_TURN_CONNECT, ///< Game Coordinator tells client/server to connect to a specific TURN server.
|
||||
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.
|
||||
CONNECTION_TYPE_TURN, ///< The Game Coordinator needs you to connect to a relay.
|
||||
};
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* uint32 (Game Coordinator protocol >= 4) Cursor as received from GC_NEWGRF_LOOKUP, or zero.
|
||||
*
|
||||
* @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);
|
||||
|
||||
/**
|
||||
* Game Coordinator informs the client of updates for the NewGRFs lookup table
|
||||
* as used by the NewGRF deserialization in GC_LISTING.
|
||||
* This packet is sent after a CLIENT_LISTING request, but before GC_LISTING.
|
||||
*
|
||||
* uint32 Lookup table cursor.
|
||||
* uint16 Number of NewGRFs in the packet, with for each of the NewGRFs:
|
||||
* uint32 Lookup table index for the NewGRF.
|
||||
* uint32 Unique NewGRF ID.
|
||||
* byte[16] MD5 checksum of the NewGRF
|
||||
* string Name of the NewGRF.
|
||||
*
|
||||
* The lookup table built using these packets are used by the deserialisation
|
||||
* of the NewGRFs for servers in the GC_LISTING. These updates are additive,
|
||||
* i.e. each update will add NewGRFs but never remove them. However, this
|
||||
* lookup table is specific to the connection with the Game Coordinator, and
|
||||
* should be considered invalid after disconnecting from the Game Coordinator.
|
||||
*
|
||||
* @param p The packet that was just received.
|
||||
* @return True upon success, otherwise false.
|
||||
*/
|
||||
virtual bool Receive_GC_NEWGRF_LOOKUP(Packet *p);
|
||||
|
||||
/**
|
||||
* Game Coordinator requests that we make a connection to the indicated
|
||||
* peer, which is a TURN server.
|
||||
*
|
||||
* string Token to track the current connect request.
|
||||
* uint8 Tracking number to track current connect request.
|
||||
* string Ticket to hand over to the TURN server.
|
||||
* string Connection string of the TURN server.
|
||||
*
|
||||
* @param p The packet that was just received.
|
||||
* @return True upon success, otherwise false.
|
||||
*/
|
||||
virtual bool Receive_GC_TURN_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 */
|
||||
@@ -48,10 +48,10 @@ NetworkRecvStatus NetworkGameSocketHandler::CloseConnection(bool error)
|
||||
_networking = false;
|
||||
ShowErrorMessage(STR_NETWORK_ERROR_LOSTCONNECTION, INVALID_STRING_ID, WL_CRITICAL);
|
||||
|
||||
return NETWORK_RECV_STATUS_CONN_LOST;
|
||||
return this->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT);
|
||||
}
|
||||
|
||||
return this->CloseConnection(error ? NETWORK_RECV_STATUS_SERVER_ERROR : NETWORK_RECV_STATUS_CONN_LOST);
|
||||
return this->CloseConnection(NETWORK_RECV_STATUS_CONNECTION_LOST);
|
||||
}
|
||||
|
||||
|
||||
@@ -73,8 +73,6 @@ NetworkRecvStatus NetworkGameSocketHandler::HandlePacket(Packet *p)
|
||||
case PACKET_SERVER_ERROR: return this->Receive_SERVER_ERROR(p);
|
||||
case PACKET_CLIENT_GAME_INFO: return this->Receive_CLIENT_GAME_INFO(p);
|
||||
case PACKET_SERVER_GAME_INFO: return this->Receive_SERVER_GAME_INFO(p);
|
||||
case PACKET_CLIENT_COMPANY_INFO: return this->Receive_CLIENT_COMPANY_INFO(p);
|
||||
case PACKET_SERVER_COMPANY_INFO: return this->Receive_SERVER_COMPANY_INFO(p);
|
||||
case PACKET_SERVER_CLIENT_INFO: return this->Receive_SERVER_CLIENT_INFO(p);
|
||||
case PACKET_SERVER_NEED_GAME_PASSWORD: return this->Receive_SERVER_NEED_GAME_PASSWORD(p);
|
||||
case PACKET_SERVER_NEED_COMPANY_PASSWORD: return this->Receive_SERVER_NEED_COMPANY_PASSWORD(p);
|
||||
@@ -117,9 +115,9 @@ NetworkRecvStatus NetworkGameSocketHandler::HandlePacket(Packet *p)
|
||||
this->CloseConnection();
|
||||
|
||||
if (this->HasClientQuit()) {
|
||||
DEBUG(net, 0, "[tcp/game] received invalid packet type %d from client %d", type, this->client_id);
|
||||
Debug(net, 0, "[tcp/game] Received invalid packet type {} from client {}", type, this->client_id);
|
||||
} else {
|
||||
DEBUG(net, 0, "[tcp/game] received illegal packet from client %d", this->client_id);
|
||||
Debug(net, 0, "[tcp/game] Received illegal packet from client {}", this->client_id);
|
||||
}
|
||||
return NETWORK_RECV_STATUS_MALFORMED_PACKET;
|
||||
}
|
||||
@@ -151,7 +149,7 @@ NetworkRecvStatus NetworkGameSocketHandler::ReceivePackets()
|
||||
*/
|
||||
NetworkRecvStatus NetworkGameSocketHandler::ReceiveInvalidPacket(PacketGameType type)
|
||||
{
|
||||
DEBUG(net, 0, "[tcp/game] received illegal packet type %d from client %d", type, this->client_id);
|
||||
Debug(net, 0, "[tcp/game] Received illegal packet type {} from client {}", type, this->client_id);
|
||||
return NETWORK_RECV_STATUS_MALFORMED_PACKET;
|
||||
}
|
||||
|
||||
@@ -161,8 +159,6 @@ NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet *p) { ret
|
||||
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_ERROR(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_ERROR); }
|
||||
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_GAME_INFO(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_GAME_INFO); }
|
||||
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_GAME_INFO(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_GAME_INFO); }
|
||||
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_COMPANY_INFO(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_COMPANY_INFO); }
|
||||
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_COMPANY_INFO(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_COMPANY_INFO); }
|
||||
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_CLIENT_INFO(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_CLIENT_INFO); }
|
||||
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_NEED_GAME_PASSWORD(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_NEED_GAME_PASSWORD); }
|
||||
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_NEED_COMPANY_PASSWORD(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_NEED_COMPANY_PASSWORD); }
|
||||
|
||||
@@ -38,9 +38,9 @@ enum PacketGameType {
|
||||
PACKET_CLIENT_JOIN, ///< The client telling the server it wants to join.
|
||||
PACKET_SERVER_ERROR, ///< Server sending an error message to the client.
|
||||
|
||||
/* Packets used for the pre-game lobby. */
|
||||
PACKET_CLIENT_COMPANY_INFO, ///< Request information about all companies.
|
||||
PACKET_SERVER_COMPANY_INFO, ///< Information about a single company.
|
||||
/* Unused packet types, formerly used for the pre-game lobby. */
|
||||
PACKET_CLIENT_UNUSED, ///< Unused.
|
||||
PACKET_SERVER_UNUSED, ///< Unused.
|
||||
|
||||
/* Packets used to get the game info. */
|
||||
PACKET_SERVER_GAME_INFO, ///< Information about the server.
|
||||
@@ -200,40 +200,6 @@ protected:
|
||||
*/
|
||||
virtual NetworkRecvStatus Receive_SERVER_GAME_INFO(Packet *p);
|
||||
|
||||
/**
|
||||
* Request company information (in detail).
|
||||
* @param p The packet that was just received.
|
||||
*/
|
||||
virtual NetworkRecvStatus Receive_CLIENT_COMPANY_INFO(Packet *p);
|
||||
|
||||
/**
|
||||
* Sends information about the companies (one packet per company):
|
||||
* uint8 Version of the structure of this packet (NETWORK_COMPANY_INFO_VERSION).
|
||||
* bool Contains data (false marks the end of updates).
|
||||
* 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.
|
||||
* string Client names (comma separated list)
|
||||
* @param p The packet that was just received.
|
||||
*/
|
||||
virtual NetworkRecvStatus Receive_SERVER_COMPANY_INFO(Packet *p);
|
||||
|
||||
/**
|
||||
* Send information about a client:
|
||||
* uint32 ID of the client (always unique on a server. 1 = server, 0 is invalid).
|
||||
@@ -274,7 +240,7 @@ protected:
|
||||
virtual NetworkRecvStatus Receive_CLIENT_COMPANY_PASSWORD(Packet *p);
|
||||
|
||||
/**
|
||||
* The client is joined and ready to receive his map:
|
||||
* The client is joined and ready to receive their map:
|
||||
* uint32 Own client ID.
|
||||
* uint32 Generation seed.
|
||||
* string Network ID of the server.
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
#include "../../stdafx.h"
|
||||
#include "../../debug.h"
|
||||
#include "../../rev.h"
|
||||
#include "../network_func.h"
|
||||
#include "../network_internal.h"
|
||||
#include "game_info.h"
|
||||
|
||||
#include "tcp_http.h"
|
||||
@@ -32,7 +32,7 @@ static std::vector<NetworkHTTPSocketHandler *> _http_connections;
|
||||
* @param depth the depth (redirect recursion) of the queries
|
||||
*/
|
||||
NetworkHTTPSocketHandler::NetworkHTTPSocketHandler(SOCKET s,
|
||||
HTTPCallback *callback, const char *host, const char *url,
|
||||
HTTPCallback *callback, const std::string &host, const char *url,
|
||||
const char *data, int depth) :
|
||||
NetworkSocketHandler(),
|
||||
recv_pos(0),
|
||||
@@ -42,19 +42,16 @@ NetworkHTTPSocketHandler::NetworkHTTPSocketHandler(SOCKET s,
|
||||
redirect_depth(depth),
|
||||
sock(s)
|
||||
{
|
||||
size_t bufferSize = strlen(url) + strlen(host) + strlen(GetNetworkRevisionString()) + (data == nullptr ? 0 : strlen(data)) + 128;
|
||||
char *buffer = AllocaM(char, bufferSize);
|
||||
|
||||
DEBUG(net, 7, "[tcp/http] requesting %s%s", host, url);
|
||||
Debug(net, 5, "[tcp/http] Requesting {}{}", host, url);
|
||||
std::string request;
|
||||
if (data != nullptr) {
|
||||
seprintf(buffer, buffer + bufferSize - 1, "POST %s HTTP/1.0\r\nHost: %s\r\nUser-Agent: OpenTTD/%s\r\nContent-Type: text/plain\r\nContent-Length: %d\r\n\r\n%s\r\n", url, host, GetNetworkRevisionString(), (int)strlen(data), data);
|
||||
request = fmt::format("POST {} HTTP/1.0\r\nHost: {}\r\nUser-Agent: OpenTTD/{}\r\nContent-Type: text/plain\r\nContent-Length: {}\r\n\r\n{}\r\n", url, host, GetNetworkRevisionString(), strlen(data), data);
|
||||
} else {
|
||||
seprintf(buffer, buffer + bufferSize - 1, "GET %s HTTP/1.0\r\nHost: %s\r\nUser-Agent: OpenTTD/%s\r\n\r\n", url, host, GetNetworkRevisionString());
|
||||
request = fmt::format("GET {} HTTP/1.0\r\nHost: {}\r\nUser-Agent: OpenTTD/{}\r\n\r\n", url, host, GetNetworkRevisionString());
|
||||
}
|
||||
|
||||
ssize_t size = strlen(buffer);
|
||||
ssize_t res = send(this->sock, (const char*)buffer, size, 0);
|
||||
if (res != size) {
|
||||
ssize_t res = send(this->sock, request.data(), (int)request.size(), 0);
|
||||
if (res != (ssize_t)request.size()) {
|
||||
/* Sending all data failed. Socket can't handle this little bit
|
||||
* of information? Just fall back to the old system! */
|
||||
this->callback->OnFailure();
|
||||
@@ -68,24 +65,25 @@ NetworkHTTPSocketHandler::NetworkHTTPSocketHandler(SOCKET s,
|
||||
/** Free whatever needs to be freed. */
|
||||
NetworkHTTPSocketHandler::~NetworkHTTPSocketHandler()
|
||||
{
|
||||
this->CloseConnection();
|
||||
this->CloseSocket();
|
||||
|
||||
if (this->sock != INVALID_SOCKET) closesocket(this->sock);
|
||||
this->sock = INVALID_SOCKET;
|
||||
free(this->data);
|
||||
}
|
||||
|
||||
NetworkRecvStatus NetworkHTTPSocketHandler::CloseConnection(bool error)
|
||||
/**
|
||||
* Close the actual socket of the connection.
|
||||
*/
|
||||
void NetworkHTTPSocketHandler::CloseSocket()
|
||||
{
|
||||
NetworkSocketHandler::CloseConnection(error);
|
||||
return NETWORK_RECV_STATUS_OKAY;
|
||||
if (this->sock != INVALID_SOCKET) closesocket(this->sock);
|
||||
this->sock = INVALID_SOCKET;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to simplify the error handling.
|
||||
* @param msg the error message to show.
|
||||
*/
|
||||
#define return_error(msg) { DEBUG(net, 0, msg); return -1; }
|
||||
#define return_error(msg) { Debug(net, 1, msg); return -1; }
|
||||
|
||||
static const char * const NEWLINE = "\r\n"; ///< End of line marker
|
||||
static const char * const END_OF_HEADER = "\r\n\r\n"; ///< End of header marker
|
||||
@@ -112,7 +110,7 @@ int NetworkHTTPSocketHandler::HandleHeader()
|
||||
/* We expect a HTTP/1.[01] reply */
|
||||
if (strncmp(this->recv_buffer, HTTP_1_0, strlen(HTTP_1_0)) != 0 &&
|
||||
strncmp(this->recv_buffer, HTTP_1_1, strlen(HTTP_1_1)) != 0) {
|
||||
return_error("[tcp/http] received invalid HTTP reply");
|
||||
return_error("[tcp/http] Received invalid HTTP reply");
|
||||
}
|
||||
|
||||
char *status = this->recv_buffer + strlen(HTTP_1_0);
|
||||
@@ -121,7 +119,7 @@ int NetworkHTTPSocketHandler::HandleHeader()
|
||||
|
||||
/* Get the length of the document to receive */
|
||||
char *length = strcasestr(this->recv_buffer, CONTENT_LENGTH);
|
||||
if (length == nullptr) return_error("[tcp/http] missing 'content-length' header");
|
||||
if (length == nullptr) return_error("[tcp/http] Missing 'content-length' header");
|
||||
|
||||
/* Skip the header */
|
||||
length += strlen(CONTENT_LENGTH);
|
||||
@@ -139,9 +137,9 @@ int NetworkHTTPSocketHandler::HandleHeader()
|
||||
/* Make sure we're going to download at least something;
|
||||
* zero sized files are, for OpenTTD's purposes, always
|
||||
* wrong. You can't have gzips of 0 bytes! */
|
||||
if (len == 0) return_error("[tcp/http] refusing to download 0 bytes");
|
||||
if (len == 0) return_error("[tcp/http] Refusing to download 0 bytes");
|
||||
|
||||
DEBUG(net, 7, "[tcp/http] downloading %i bytes", len);
|
||||
Debug(net, 7, "[tcp/http] Downloading {} bytes", len);
|
||||
return len;
|
||||
}
|
||||
|
||||
@@ -154,15 +152,15 @@ int NetworkHTTPSocketHandler::HandleHeader()
|
||||
/* Search the end of the line. This is safe because the header will
|
||||
* always end with two newlines. */
|
||||
*strstr(status, NEWLINE) = '\0';
|
||||
DEBUG(net, 0, "[tcp/http] unhandled status reply %s", status);
|
||||
Debug(net, 1, "[tcp/http] Unhandled status reply {}", status);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (this->redirect_depth == 5) return_error("[tcp/http] too many redirects, looping redirects?");
|
||||
if (this->redirect_depth == 5) return_error("[tcp/http] Too many redirects, looping redirects?");
|
||||
|
||||
/* Redirect to other URL */
|
||||
char *uri = strcasestr(this->recv_buffer, LOCATION);
|
||||
if (uri == nullptr) return_error("[tcp/http] missing 'location' header for redirect");
|
||||
if (uri == nullptr) return_error("[tcp/http] Missing 'location' header for redirect");
|
||||
|
||||
uri += strlen(LOCATION);
|
||||
|
||||
@@ -171,7 +169,7 @@ int NetworkHTTPSocketHandler::HandleHeader()
|
||||
char *end_of_line = strstr(uri, NEWLINE);
|
||||
*end_of_line = '\0';
|
||||
|
||||
DEBUG(net, 6, "[tcp/http] redirecting to %s", uri);
|
||||
Debug(net, 7, "[tcp/http] Redirecting to {}", uri);
|
||||
|
||||
int ret = NetworkHTTPSocketHandler::Connect(uri, this->callback, this->data, this->redirect_depth + 1);
|
||||
if (ret != 0) return ret;
|
||||
@@ -194,26 +192,20 @@ int NetworkHTTPSocketHandler::HandleHeader()
|
||||
/* static */ int NetworkHTTPSocketHandler::Connect(char *uri, HTTPCallback *callback, const char *data, int depth)
|
||||
{
|
||||
char *hname = strstr(uri, "://");
|
||||
if (hname == nullptr) return_error("[tcp/http] invalid location");
|
||||
if (hname == nullptr) return_error("[tcp/http] Invalid location");
|
||||
|
||||
hname += 3;
|
||||
|
||||
char *url = strchr(hname, '/');
|
||||
if (url == nullptr) return_error("[tcp/http] invalid location");
|
||||
if (url == nullptr) return_error("[tcp/http] Invalid location");
|
||||
|
||||
*url = '\0';
|
||||
|
||||
/* Fetch the hostname, and possible port number. */
|
||||
const char *company = nullptr;
|
||||
const char *port = nullptr;
|
||||
ParseConnectionString(&company, &port, hname);
|
||||
if (company != nullptr) return_error("[tcp/http] invalid hostname");
|
||||
|
||||
NetworkAddress address(hname, port == nullptr ? 80 : atoi(port));
|
||||
std::string hostname = std::string(hname);
|
||||
|
||||
/* Restore the URL. */
|
||||
*url = '/';
|
||||
new NetworkHTTPContentConnecter(address, callback, url, data, depth);
|
||||
new NetworkHTTPContentConnecter(hostname, callback, url, data, depth);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -234,7 +226,7 @@ int NetworkHTTPSocketHandler::Receive()
|
||||
NetworkError err = NetworkError::GetLast();
|
||||
if (!err.WouldBlock()) {
|
||||
/* Something went wrong... */
|
||||
if (!err.IsConnectionReset()) DEBUG(net, 0, "recv failed with error %s", err.AsString());
|
||||
if (!err.IsConnectionReset()) Debug(net, 0, "Recv failed: {}", err.AsString());
|
||||
return -1;
|
||||
}
|
||||
/* Connection would block, so stop for now */
|
||||
@@ -262,7 +254,7 @@ int NetworkHTTPSocketHandler::Receive()
|
||||
|
||||
if (end_of_header == nullptr) {
|
||||
if (read == lengthof(this->recv_buffer)) {
|
||||
DEBUG(net, 0, "[tcp/http] header too big");
|
||||
Debug(net, 1, "[tcp/http] Header too big");
|
||||
return -1;
|
||||
}
|
||||
this->recv_pos = read;
|
||||
@@ -319,7 +311,7 @@ int NetworkHTTPSocketHandler::Receive()
|
||||
if (ret < 0) cur->callback->OnFailure();
|
||||
if (ret <= 0) {
|
||||
/* Then... the connection can be closed */
|
||||
cur->CloseConnection();
|
||||
cur->CloseSocket();
|
||||
iter = _http_connections.erase(iter);
|
||||
delete cur;
|
||||
continue;
|
||||
|
||||
+12
-12
@@ -58,10 +58,10 @@ public:
|
||||
return this->sock != INVALID_SOCKET;
|
||||
}
|
||||
|
||||
NetworkRecvStatus CloseConnection(bool error = true) override;
|
||||
void CloseSocket();
|
||||
|
||||
NetworkHTTPSocketHandler(SOCKET sock, HTTPCallback *callback,
|
||||
const char *host, const char *url, const char *data, int depth);
|
||||
const std::string &host, const char *url, const char *data, int depth);
|
||||
|
||||
~NetworkHTTPSocketHandler();
|
||||
|
||||
@@ -73,6 +73,7 @@ public:
|
||||
|
||||
/** Connect with a HTTP server and do ONE query. */
|
||||
class NetworkHTTPContentConnecter : TCPConnecter {
|
||||
std::string hostname; ///< Hostname we are connecting to.
|
||||
HTTPCallback *callback; ///< Callback to tell that we received some data (or won't).
|
||||
const char *url; ///< The URL we want to get at the server.
|
||||
const char *data; ///< The data to send
|
||||
@@ -81,16 +82,15 @@ class NetworkHTTPContentConnecter : TCPConnecter {
|
||||
public:
|
||||
/**
|
||||
* Start the connecting.
|
||||
* @param address the address to connect to
|
||||
* @param callback the callback for HTTP retrieval
|
||||
* @param url the url at the server
|
||||
* @param data the data to send
|
||||
* @param depth the depth (redirect recursion) of the queries
|
||||
* @param hostname The hostname to connect to.
|
||||
* @param callback The callback for HTTP retrieval.
|
||||
* @param url The url at the server.
|
||||
* @param data The data to send.
|
||||
* @param depth The depth (redirect recursion) of the queries.
|
||||
*/
|
||||
NetworkHTTPContentConnecter(const NetworkAddress &address,
|
||||
HTTPCallback *callback, const char *url,
|
||||
const char *data = nullptr, int depth = 0) :
|
||||
TCPConnecter(address),
|
||||
NetworkHTTPContentConnecter(const std::string &hostname, HTTPCallback *callback, const char *url, const char *data = nullptr, int depth = 0) :
|
||||
TCPConnecter(hostname, 80),
|
||||
hostname(hostname),
|
||||
callback(callback),
|
||||
url(stredup(url)),
|
||||
data(data),
|
||||
@@ -112,7 +112,7 @@ public:
|
||||
|
||||
void OnConnect(SOCKET s) override
|
||||
{
|
||||
new NetworkHTTPSocketHandler(s, this->callback, this->address.GetHostname(), this->url, this->data, this->depth);
|
||||
new NetworkHTTPSocketHandler(s, this->callback, this->hostname, this->url, this->data, this->depth);
|
||||
/* We've relinquished control of data now. */
|
||||
this->data = nullptr;
|
||||
}
|
||||
|
||||
@@ -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)) {
|
||||
Packet p(Tban_packet);
|
||||
p.PrepareToSend();
|
||||
|
||||
Debug(net, 2, "[{}] Banned ip tried to join ({}), refused", Tsocket::GetName(), entry);
|
||||
|
||||
if (p.TransferOut<int>(send, s, 0) < 0) {
|
||||
Debug(net, 0, "[{}] send failed: {}", 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, "[{}] send failed: {}", Tsocket::GetName(), NetworkError::GetLast().AsString());
|
||||
}
|
||||
closesocket(s);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts clients from the sockets.
|
||||
* @param ls Socket to accept clients from.
|
||||
@@ -49,45 +85,11 @@ public:
|
||||
SetNonBlocking(s); // XXX error handling?
|
||||
|
||||
NetworkAddress address(sin, sin_len);
|
||||
DEBUG(net, 1, "[%s] Client connected from %s on frame %d", Tsocket::GetName(), address.GetHostname(), _frame_counter);
|
||||
Debug(net, 3, "[{}] Client connected from {} on frame {}", Tsocket::GetName(), address.GetHostname(), _frame_counter);
|
||||
|
||||
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, 1, "[%s] Banned ip tried to join (%s), refused", Tsocket::GetName(), entry.c_str());
|
||||
|
||||
if (send(s, (const char*)p.buffer, p.size, 0) < 0) {
|
||||
DEBUG(net, 0, "send failed with error %s", 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 (send(s, (const char*)p.buffer, p.size, 0) < 0) {
|
||||
DEBUG(net, 0, "send failed with error %s", NetworkError::GetLast().AsString());
|
||||
}
|
||||
closesocket(s);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!Tsocket::ValidateClient(s, address)) continue;
|
||||
Tsocket::AcceptConnection(s, address);
|
||||
}
|
||||
}
|
||||
@@ -150,7 +152,7 @@ public:
|
||||
}
|
||||
|
||||
if (sockets.size() == 0) {
|
||||
DEBUG(net, 0, "[server] could not start network: could not create listening socket");
|
||||
Debug(net, 0, "Could not start network: could not create listening socket");
|
||||
ShowNetworkError(STR_NETWORK_ERROR_SERVER_START);
|
||||
return false;
|
||||
}
|
||||
@@ -165,7 +167,7 @@ public:
|
||||
closesocket(s.second);
|
||||
}
|
||||
sockets.clear();
|
||||
DEBUG(net, 1, "[%s] closed listeners", Tsocket::GetName());
|
||||
Debug(net, 5, "[{}] Closed listeners", Tsocket::GetName());
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -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 {}", type);
|
||||
return false;
|
||||
}
|
||||
|
||||
bool NetworkStunSocketHandler::Receive_SERCLI_STUN(Packet *p) { return this->ReceiveInvalidPacket(PACKET_STUN_SERCLI_STUN); }
|
||||
@@ -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 */
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* 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_turn.cpp Basic functions to receive and send TURN packets.
|
||||
*/
|
||||
|
||||
#include "../../stdafx.h"
|
||||
#include "../../date_func.h"
|
||||
#include "../../debug.h"
|
||||
#include "tcp_turn.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 if we should immediately handle further packets, false otherwise
|
||||
*/
|
||||
bool NetworkTurnSocketHandler::HandlePacket(Packet *p)
|
||||
{
|
||||
PacketTurnType type = (PacketTurnType)p->Recv_uint8();
|
||||
|
||||
switch (type) {
|
||||
case PACKET_TURN_TURN_ERROR: return this->Receive_TURN_ERROR(p);
|
||||
case PACKET_TURN_SERCLI_CONNECT: return this->Receive_SERCLI_CONNECT(p);
|
||||
case PACKET_TURN_TURN_CONNECTED: return this->Receive_TURN_CONNECTED(p);
|
||||
|
||||
default:
|
||||
Debug(net, 0, "[tcp/turn] Received invalid packet type {}", type);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Receive a packet at TCP level
|
||||
* @return Whether at least one packet was received.
|
||||
*/
|
||||
bool NetworkTurnSocketHandler::ReceivePackets()
|
||||
{
|
||||
Packet *p;
|
||||
static const int MAX_PACKETS_TO_RECEIVE = 4;
|
||||
int i = MAX_PACKETS_TO_RECEIVE;
|
||||
while (--i != 0 && (p = this->ReceivePacket()) != nullptr) {
|
||||
bool cont = this->HandlePacket(p);
|
||||
delete p;
|
||||
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 NetworkTurnSocketHandler::ReceiveInvalidPacket(PacketTurnType type)
|
||||
{
|
||||
Debug(net, 0, "[tcp/turn] Received illegal packet type {}", type);
|
||||
return false;
|
||||
}
|
||||
|
||||
bool NetworkTurnSocketHandler::Receive_TURN_ERROR(Packet *p) { return this->ReceiveInvalidPacket(PACKET_TURN_TURN_ERROR); }
|
||||
bool NetworkTurnSocketHandler::Receive_SERCLI_CONNECT(Packet *p) { return this->ReceiveInvalidPacket(PACKET_TURN_SERCLI_CONNECT); }
|
||||
bool NetworkTurnSocketHandler::Receive_TURN_CONNECTED(Packet *p) { return this->ReceiveInvalidPacket(PACKET_TURN_TURN_CONNECTED); }
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* 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_turn.h Basic functions to receive and send TCP packets to/from the TURN server.
|
||||
*/
|
||||
|
||||
#ifndef NETWORK_CORE_TCP_TURN_H
|
||||
#define NETWORK_CORE_TCP_TURN_H
|
||||
|
||||
#include "os_abstraction.h"
|
||||
#include "tcp.h"
|
||||
#include "packet.h"
|
||||
#include "game_info.h"
|
||||
|
||||
/** Enum with all types of TCP TURN packets. The order MUST not be changed. **/
|
||||
enum PacketTurnType {
|
||||
PACKET_TURN_TURN_ERROR, ///< TURN server is unable to relay.
|
||||
PACKET_TURN_SERCLI_CONNECT, ///< Client or server is connecting to the TURN server.
|
||||
PACKET_TURN_TURN_CONNECTED, ///< TURN server indicates the socket is now being relayed.
|
||||
PACKET_TURN_END, ///< Must ALWAYS be on the end of this list!! (period)
|
||||
};
|
||||
|
||||
/** Base socket handler for all TURN TCP sockets. */
|
||||
class NetworkTurnSocketHandler : public NetworkTCPSocketHandler {
|
||||
protected:
|
||||
bool ReceiveInvalidPacket(PacketTurnType type);
|
||||
|
||||
/**
|
||||
* TURN server was unable to connect the client or server based on the
|
||||
* token. Most likely cause is an invalid token or the other side that
|
||||
* hasn't connected in a reasonable amount of time.
|
||||
*
|
||||
* @param p The packet that was just received.
|
||||
* @return True upon success, otherwise false.
|
||||
*/
|
||||
virtual bool Receive_TURN_ERROR(Packet *p);
|
||||
|
||||
/**
|
||||
* Client or servers wants to connect to the TURN server (on request by
|
||||
* the Game Coordinator).
|
||||
*
|
||||
* uint8 Game Coordinator protocol version.
|
||||
* string Token to track the current TURN request.
|
||||
*
|
||||
* @param p The packet that was just received.
|
||||
* @return True upon success, otherwise false.
|
||||
*/
|
||||
virtual bool Receive_SERCLI_CONNECT(Packet *p);
|
||||
|
||||
/**
|
||||
* TURN server has connected client and server together and will now relay
|
||||
* all packets to each other. No further TURN packets should be send over
|
||||
* this socket, and the socket should be handed over to the game protocol.
|
||||
*
|
||||
* string Hostname of the peer. This can be used to check if a client is not banned etc.
|
||||
*
|
||||
* @param p The packet that was just received.
|
||||
* @return True upon success, otherwise false.
|
||||
*/
|
||||
virtual bool Receive_TURN_CONNECTED(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.
|
||||
* @param address IP etc. of the client.
|
||||
*/
|
||||
NetworkTurnSocketHandler(SOCKET s = INVALID_SOCKET) : NetworkTCPSocketHandler(s) {}
|
||||
|
||||
bool ReceivePackets();
|
||||
};
|
||||
|
||||
#endif /* NETWORK_CORE_TCP_TURN_H */
|
||||
+19
-44
@@ -28,11 +28,11 @@ NetworkUDPSocketHandler::NetworkUDPSocketHandler(NetworkAddressList *bind)
|
||||
this->bind.push_back(addr);
|
||||
}
|
||||
} else {
|
||||
/* As hostname nullptr and port 0/nullptr don't go well when
|
||||
/* As an empty hostname and port 0 don't go well when
|
||||
* resolving it we need to add an address for each of
|
||||
* the address families we support. */
|
||||
this->bind.emplace_back(nullptr, 0, AF_INET);
|
||||
this->bind.emplace_back(nullptr, 0, AF_INET6);
|
||||
this->bind.emplace_back("", 0, AF_INET);
|
||||
this->bind.emplace_back("", 0, AF_INET6);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ NetworkUDPSocketHandler::NetworkUDPSocketHandler(NetworkAddressList *bind)
|
||||
bool NetworkUDPSocketHandler::Listen()
|
||||
{
|
||||
/* Make sure socket is closed */
|
||||
this->Close();
|
||||
this->CloseSocket();
|
||||
|
||||
for (NetworkAddress &addr : this->bind) {
|
||||
addr.Listen(SOCK_DGRAM, &this->sockets);
|
||||
@@ -54,9 +54,9 @@ bool NetworkUDPSocketHandler::Listen()
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the given UDP socket
|
||||
* Close the actual UDP socket.
|
||||
*/
|
||||
void NetworkUDPSocketHandler::Close()
|
||||
void NetworkUDPSocketHandler::CloseSocket()
|
||||
{
|
||||
for (auto &s : this->sockets) {
|
||||
closesocket(s.second);
|
||||
@@ -64,12 +64,6 @@ void NetworkUDPSocketHandler::Close()
|
||||
this->sockets.clear();
|
||||
}
|
||||
|
||||
NetworkRecvStatus NetworkUDPSocketHandler::CloseConnection(bool error)
|
||||
{
|
||||
NetworkSocketHandler::CloseConnection(error);
|
||||
return NETWORK_RECV_STATUS_OKAY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a packet over UDP
|
||||
* @param p the packet to send
|
||||
@@ -95,16 +89,16 @@ void NetworkUDPSocketHandler::SendPacket(Packet *p, NetworkAddress *recv, bool a
|
||||
/* Enable broadcast */
|
||||
unsigned long val = 1;
|
||||
if (setsockopt(s.second, SOL_SOCKET, SO_BROADCAST, (char *) &val, sizeof(val)) < 0) {
|
||||
DEBUG(net, 1, "[udp] setting broadcast failed with: %s", NetworkError::GetLast().AsString());
|
||||
Debug(net, 1, "Setting broadcast mode failed: {}", NetworkError::GetLast().AsString());
|
||||
}
|
||||
}
|
||||
|
||||
/* Send the buffer */
|
||||
int res = sendto(s.second, (const char*)p->buffer, p->size, 0, (const struct sockaddr *)send.GetAddress(), send.GetAddressLength());
|
||||
DEBUG(net, 7, "[udp] sendto(%s)", send.GetAddressAsString().c_str());
|
||||
ssize_t res = p->TransferOut<int>(sendto, s.second, 0, (const struct sockaddr *)send.GetAddress(), send.GetAddressLength());
|
||||
Debug(net, 7, "sendto({})", send.GetAddressAsString());
|
||||
|
||||
/* Check for any errors, but ignore it otherwise */
|
||||
if (res == -1) DEBUG(net, 1, "[udp] sendto(%s) failed with: %s", send.GetAddressAsString().c_str(), NetworkError::GetLast().AsString());
|
||||
if (res == -1) Debug(net, 1, "sendto({}) failed: {}", send.GetAddressAsString(), NetworkError::GetLast().AsString());
|
||||
|
||||
if (!all) break;
|
||||
}
|
||||
@@ -120,12 +114,13 @@ void NetworkUDPSocketHandler::ReceivePackets()
|
||||
struct sockaddr_storage client_addr;
|
||||
memset(&client_addr, 0, sizeof(client_addr));
|
||||
|
||||
Packet p(this);
|
||||
/* The limit is UDP_MTU, but also allocate that much as we need to read the whole packet in one go. */
|
||||
Packet p(this, UDP_MTU, UDP_MTU);
|
||||
socklen_t client_len = sizeof(client_addr);
|
||||
|
||||
/* Try to receive anything */
|
||||
SetNonBlocking(s.second); // Some OSes seem to lose the non-blocking status of the socket
|
||||
int nbytes = recvfrom(s.second, (char*)p.buffer, SEND_MTU, 0, (struct sockaddr *)&client_addr, &client_len);
|
||||
ssize_t nbytes = p.TransferIn<int>(recvfrom, s.second, 0, (struct sockaddr *)&client_addr, &client_len);
|
||||
|
||||
/* Did we get the bytes for the base header of the packet? */
|
||||
if (nbytes <= 0) break; // No data, i.e. no packet
|
||||
@@ -135,14 +130,14 @@ void NetworkUDPSocketHandler::ReceivePackets()
|
||||
#endif
|
||||
|
||||
NetworkAddress address(client_addr, client_len);
|
||||
p.PrepareToRead();
|
||||
|
||||
/* If the size does not match the packet must be corrupted.
|
||||
* Otherwise it will be marked as corrupted later on. */
|
||||
if (nbytes != p.size) {
|
||||
DEBUG(net, 1, "received a packet with mismatching size from %s", address.GetAddressAsString().c_str());
|
||||
if (!p.ParsePacketSize() || (size_t)nbytes != p.Size()) {
|
||||
Debug(net, 1, "Received a packet with mismatching size from {}", address.GetAddressAsString());
|
||||
continue;
|
||||
}
|
||||
p.PrepareToRead();
|
||||
|
||||
/* Handle the packet */
|
||||
this->HandleUDPPacket(&p, &address);
|
||||
@@ -167,22 +162,12 @@ 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;
|
||||
|
||||
default:
|
||||
if (this->HasClientQuit()) {
|
||||
DEBUG(net, 0, "[udp] received invalid packet type %d from %s", type, client_addr->GetAddressAsString().c_str());
|
||||
Debug(net, 0, "[udp] Received invalid packet type {} from {}", type, client_addr->GetAddressAsString());
|
||||
} else {
|
||||
DEBUG(net, 0, "[udp] received illegal packet from %s", client_addr->GetAddressAsString().c_str());
|
||||
Debug(net, 0, "[udp] Received illegal packet from {}", client_addr->GetAddressAsString());
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -195,18 +180,8 @@ void NetworkUDPSocketHandler::HandleUDPPacket(Packet *p, NetworkAddress *client_
|
||||
*/
|
||||
void NetworkUDPSocketHandler::ReceiveInvalidPacket(PacketUDPType type, NetworkAddress *client_addr)
|
||||
{
|
||||
DEBUG(net, 0, "[udp] received packet type %d on wrong port from %s", type, client_addr->GetAddressAsString().c_str());
|
||||
Debug(net, 0, "[udp] Received packet type {} on wrong port from {}", type, client_addr->GetAddressAsString());
|
||||
}
|
||||
|
||||
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_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); }
|
||||
|
||||
+3
-139
@@ -19,28 +19,9 @@
|
||||
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 on the end of this list!! (period)
|
||||
};
|
||||
|
||||
/** 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:
|
||||
@@ -49,8 +30,6 @@ protected:
|
||||
/** The opened sockets. */
|
||||
SocketList sockets;
|
||||
|
||||
NetworkRecvStatus CloseConnection(bool error = true) override;
|
||||
|
||||
void ReceiveInvalidPacket(PacketUDPType, NetworkAddress *client_addr);
|
||||
|
||||
/**
|
||||
@@ -61,136 +40,21 @@ 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.
|
||||
*/
|
||||
virtual void Receive_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);
|
||||
public:
|
||||
NetworkUDPSocketHandler(NetworkAddressList *bind = nullptr);
|
||||
|
||||
/** On destructing of this class, the socket needs to be closed */
|
||||
virtual ~NetworkUDPSocketHandler() { this->Close(); }
|
||||
virtual ~NetworkUDPSocketHandler() { this->CloseSocket(); }
|
||||
|
||||
bool Listen();
|
||||
void Close() override;
|
||||
void CloseSocket();
|
||||
|
||||
void SendPacket(Packet *p, NetworkAddress *recv, bool all = false, bool broadcast = false);
|
||||
void ReceivePackets();
|
||||
|
||||
Reference in New Issue
Block a user