Merge branch 'origin/master' commit 'a499e9acdd385b57dd43caf88af3a6f7f53716ba'

This commit is contained in:
pelya
2020-03-20 00:10:46 +02:00
1448 changed files with 32573 additions and 27146 deletions
+17 -24
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -11,8 +9,6 @@
#include "../../stdafx.h"
#ifdef ENABLE_NETWORK
#include "address.h"
#include "../../debug.h"
@@ -27,7 +23,7 @@ const char *NetworkAddress::GetHostname()
{
if (StrEmpty(this->hostname) && this->address.ss_family != AF_UNSPEC) {
assert(this->address_length != 0);
getnameinfo((struct sockaddr *)&this->address, this->address_length, this->hostname, sizeof(this->hostname), NULL, 0, NI_NUMERICHOST);
getnameinfo((struct sockaddr *)&this->address, this->address_length, this->hostname, sizeof(this->hostname), nullptr, 0, NI_NUMERICHOST);
}
return this->hostname;
}
@@ -133,7 +129,7 @@ const sockaddr_storage *NetworkAddress::GetAddress()
* bothered to implement the specifications and allow '0' as value
* that means "don't care whether it is SOCK_STREAM or SOCK_DGRAM".
*/
this->Resolve(this->address.ss_family, SOCK_STREAM, AI_ADDRCONFIG, NULL, ResolveLoopProc);
this->Resolve(this->address.ss_family, SOCK_STREAM, AI_ADDRCONFIG, nullptr, ResolveLoopProc);
this->resolved = true;
}
return &this->address;
@@ -147,7 +143,7 @@ const sockaddr_storage *NetworkAddress::GetAddress()
bool NetworkAddress::IsFamily(int family)
{
if (!this->IsResolved()) {
this->Resolve(family, SOCK_STREAM, AI_ADDRCONFIG, NULL, ResolveLoopProc);
this->Resolve(family, SOCK_STREAM, AI_ADDRCONFIG, nullptr, ResolveLoopProc);
}
return this->address.ss_family == family;
}
@@ -158,7 +154,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(char *netmask)
bool NetworkAddress::IsInNetmask(const char *netmask)
{
/* Resolve it if we didn't do it already */
if (!this->IsResolved()) this->GetAddress();
@@ -168,17 +164,16 @@ bool NetworkAddress::IsInNetmask(char *netmask)
NetworkAddress mask_address;
/* Check for CIDR separator */
char *chr_cidr = strchr(netmask, '/');
if (chr_cidr != NULL) {
const char *chr_cidr = strchr(netmask, '/');
if (chr_cidr != nullptr) {
int tmp_cidr = atoi(chr_cidr + 1);
/* Invalid CIDR, treat as single host */
if (tmp_cidr > 0 || tmp_cidr < cidr) cidr = tmp_cidr;
/* Remove and then replace the / so that NetworkAddress works on the IP portion */
*chr_cidr = '\0';
mask_address = NetworkAddress(netmask, 0, this->address.ss_family);
*chr_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);
} else {
mask_address = NetworkAddress(netmask, 0, this->address.ss_family);
}
@@ -235,7 +230,7 @@ SOCKET NetworkAddress::Resolve(int family, int socktype, int flags, SocketList *
seprintf(port_name, lastof(port_name), "%u", this->GetPort());
bool reset_hostname = false;
/* Setting both hostname to NULL and port to 0 is not allowed.
/* 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) {
@@ -245,7 +240,7 @@ SOCKET NetworkAddress::Resolve(int family, int socktype, int flags, SocketList *
strecpy(this->hostname, fam == AF_INET ? "0.0.0.0" : "::", lastof(this->hostname));
}
int e = getaddrinfo(StrEmpty(this->hostname) ? NULL : this->hostname, port_name, &hints, &ai);
int e = getaddrinfo(StrEmpty(this->hostname) ? nullptr : this->hostname, port_name, &hints, &ai);
if (reset_hostname) strecpy(this->hostname, "", lastof(this->hostname));
@@ -258,18 +253,18 @@ SOCKET NetworkAddress::Resolve(int family, int socktype, int flags, SocketList *
}
SOCKET sock = INVALID_SOCKET;
for (struct addrinfo *runp = ai; runp != NULL; runp = runp->ai_next) {
for (struct addrinfo *runp = ai; runp != nullptr; runp = runp->ai_next) {
/* When we are binding to multiple sockets, make sure we do not
* connect to one with exactly the same address twice. That's
* of course totally unneeded ;) */
if (sockets != NULL) {
if (sockets != nullptr) {
NetworkAddress address(runp->ai_addr, (int)runp->ai_addrlen);
if (sockets->Contains(address)) continue;
}
sock = func(runp);
if (sock == INVALID_SOCKET) continue;
if (sockets == NULL) {
if (sockets == nullptr) {
this->address_length = (int)runp->ai_addrlen;
assert(sizeof(this->address) >= runp->ai_addrlen);
memcpy(&this->address, runp->ai_addr, runp->ai_addrlen);
@@ -326,7 +321,7 @@ SOCKET NetworkAddress::Connect()
{
DEBUG(net, 1, "Connecting to %s", this->GetAddressAsString());
return this->Resolve(AF_UNSPEC, SOCK_STREAM, AI_ADDRCONFIG, NULL, ConnectLoopProc);
return this->Resolve(AF_UNSPEC, SOCK_STREAM, AI_ADDRCONFIG, nullptr, ConnectLoopProc);
}
/**
@@ -389,9 +384,9 @@ static SOCKET ListenLoopProc(addrinfo *runp)
*/
void NetworkAddress::Listen(int socktype, SocketList *sockets)
{
assert(sockets != NULL);
assert(sockets != nullptr);
/* Setting both hostname to NULL and port to 0 is not allowed.
/* 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 (this->address_length == 0 && this->address.ss_family == AF_UNSPEC &&
@@ -433,5 +428,3 @@ void NetworkAddress::Listen(int socktype, SocketList *sockets)
default: return "unsupported";
}
}
#endif /* ENABLE_NETWORK */
+4 -18
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -17,11 +15,9 @@
#include "../../string_func.h"
#include "../../core/smallmap_type.hpp"
#ifdef ENABLE_NETWORK
class NetworkAddress;
typedef SmallVector<NetworkAddress, 4> NetworkAddressList; ///< Type for a list of addresses.
typedef SmallMap<NetworkAddress, SOCKET, 4> SocketList; ///< Type for a mapping between address and socket.
typedef std::vector<NetworkAddress> NetworkAddressList; ///< Type for a list of addresses.
typedef SmallMap<NetworkAddress, SOCKET> SocketList; ///< Type for a mapping between address and socket.
/**
* Wrapper for (un)resolved network addresses; there's no reason to transform
@@ -86,22 +82,13 @@ public:
if (*hostname == '[') hostname++;
strecpy(this->hostname, StrEmpty(hostname) ? "" : hostname, lastof(this->hostname));
char *tmp = strrchr(this->hostname, ']');
if (tmp != NULL) *tmp = '\0';
if (tmp != nullptr) *tmp = '\0';
memset(&this->address, 0, sizeof(this->address));
this->address.ss_family = family;
this->SetPort(port);
}
/**
* Make a clone of another address
* @param address the address to clone
*/
NetworkAddress(const NetworkAddress &address)
{
memcpy(this, &address, sizeof(*this));
}
const char *GetHostname();
void GetAddressAsString(char *buffer, const char *last, bool with_family = true);
const char *GetAddressAsString(bool with_family = true);
@@ -131,7 +118,7 @@ public:
}
bool IsFamily(int family);
bool IsInNetmask(char *netmask);
bool IsInNetmask(const char *netmask);
/**
* Compare the address of this class with the address of another.
@@ -192,5 +179,4 @@ public:
static const char *AddressFamilyAsString(int family);
};
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_ADDRESS_H */
-2
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
-53
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -11,8 +9,6 @@
* @file core.cpp Functions used to initialize/shut down the core network
*/
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#include "../../debug.h"
#include "os_abstraction.h"
@@ -21,48 +17,12 @@
#include "../../safeguards.h"
#ifdef __MORPHOS__
/* the library base is required here */
struct Library *SocketBase = NULL;
#endif
/**
* Initializes the network core (as that is needed for some platforms
* @return true if the core has been initialized, false otherwise
*/
bool NetworkCoreInitialize()
{
#if defined(__MORPHOS__) || defined(__AMIGA__)
/*
* IMPORTANT NOTE: SocketBase needs to be initialized before we use _any_
* network related function, else: crash.
*/
DEBUG(net, 3, "[core] loading bsd socket library");
SocketBase = OpenLibrary("bsdsocket.library", 4);
if (SocketBase == NULL) {
DEBUG(net, 0, "[core] can't open bsdsocket.library version 4, network unavailable");
return false;
}
#if defined(__AMIGA__)
/* for usleep() implementation (only required for legacy AmigaOS builds) */
TimerPort = CreateMsgPort();
if (TimerPort != NULL) {
TimerRequest = (struct timerequest*)CreateIORequest(TimerPort, sizeof(struct timerequest);
if (TimerRequest != NULL) {
if (OpenDevice("timer.device", UNIT_MICROHZ, (struct IORequest*)TimerRequest, 0) == 0) {
TimerBase = TimerRequest->tr_node.io_Device;
if (TimerBase == NULL) {
/* free resources... */
DEBUG(net, 0, "[core] can't initialize timer, network unavailable");
return false;
}
}
}
}
#endif /* __AMIGA__ */
#endif /* __MORPHOS__ / __AMIGA__ */
/* Let's load the network in windows */
#ifdef _WIN32
{
@@ -83,17 +43,6 @@ bool NetworkCoreInitialize()
*/
void NetworkCoreShutdown()
{
#if defined(__MORPHOS__) || defined(__AMIGA__)
/* free allocated resources */
#if defined(__AMIGA__)
if (TimerBase != NULL) CloseDevice((struct IORequest*)TimerRequest); // XXX This smells wrong
if (TimerRequest != NULL) DeleteIORequest(TimerRequest);
if (TimerPort != NULL) DeleteMsgPort(TimerPort);
#endif
if (SocketBase != NULL) CloseLibrary(SocketBase);
#endif
#if defined(_WIN32)
WSACleanup();
#endif
@@ -127,5 +76,3 @@ void NetworkSocketHandler::ReceiveGRFIdentifier(Packet *p, GRFIdentifier *grf)
grf->md5sum[j] = p->Recv_uint8();
}
}
#endif /* ENABLE_NETWORK */
-6
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -17,8 +15,6 @@
#include "../../newgrf_config.h"
#include "config.h"
#ifdef ENABLE_NETWORK
bool NetworkCoreInitialize();
void NetworkCoreShutdown();
@@ -80,6 +76,4 @@ public:
void SendCompanyInformation(Packet *p, const struct Company *c, const struct NetworkCompanyStats *stats, uint max_len = NETWORK_COMPANY_NAME_LENGTH);
};
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_CORE_H */
-6
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -19,8 +17,6 @@
#include "../../newgrf_config.h"
#include "../../date_type.h"
#ifdef ENABLE_NETWORK
/**
* The game information that is not generated on-the-fly and has to
* be sent to the clients.
@@ -58,6 +54,4 @@ struct NetworkGameInfo : NetworkServerGameInfo {
const char * GetNetworkRevisionString();
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_GAME_H */
+12 -18
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -9,8 +7,6 @@
/** @file host.cpp Functions related to getting host specific data (IPs). */
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#include "../../debug.h"
#include "address.h"
@@ -24,7 +20,7 @@
*/
static void NetworkFindBroadcastIPsInternal(NetworkAddressList *broadcast);
#if defined(BEOS_NET_SERVER) || defined(__HAIKU__) /* doesn't have neither getifaddrs or net/if.h */
#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);
@@ -47,7 +43,7 @@ static void NetworkFindBroadcastIPsInternal(NetworkAddressList *broadcast) // BE
return;
}
char *output_pointer = NULL;
char *output_pointer = nullptr;
int output_length = _netstat(sock, &output_pointer, 1);
if (output_length < 0) {
DEBUG(net, 0, "[core] error running _netstat");
@@ -78,7 +74,7 @@ static void NetworkFindBroadcastIPsInternal(NetworkAddressList *broadcast) // BE
memset(&address, 0, sizeof(address));
((sockaddr_in*)&address)->sin_addr.s_addr = htonl(ip | ~netmask);
NetworkAddress addr(address, sizeof(sockaddr));
if (!broadcast->Contains(addr)) *broadcast->Append() = addr;
if (std::none_of(broadcast->begin(), broadcast->end(), [&addr](NetworkAddress const& elem) -> bool { return elem == addr; })) broadcast->push_back(addr);
}
if (read < 0) {
break;
@@ -96,13 +92,13 @@ static void NetworkFindBroadcastIPsInternal(NetworkAddressList *broadcast) // GE
if (getifaddrs(&ifap) != 0) return;
for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
for (ifa = ifap; ifa != nullptr; ifa = ifa->ifa_next) {
if (!(ifa->ifa_flags & IFF_BROADCAST)) continue;
if (ifa->ifa_broadaddr == NULL) continue;
if (ifa->ifa_broadaddr == nullptr) continue;
if (ifa->ifa_broadaddr->sa_family != AF_INET) continue;
NetworkAddress addr(ifa->ifa_broadaddr, sizeof(sockaddr));
if (!broadcast->Contains(addr)) *broadcast->Append() = addr;
if (std::none_of(broadcast->begin(), broadcast->end(), [&addr](NetworkAddress const& elem) -> bool { return elem == addr; })) broadcast->push_back(addr);
}
freeifaddrs(ifap);
}
@@ -118,7 +114,7 @@ static void NetworkFindBroadcastIPsInternal(NetworkAddressList *broadcast) // Wi
INTERFACE_INFO *ifo = CallocT<INTERFACE_INFO>(num);
for (;;) {
if (WSAIoctl(sock, SIO_GET_INTERFACE_LIST, NULL, 0, ifo, num * sizeof(*ifo), &len, NULL, NULL) == 0) break;
if (WSAIoctl(sock, SIO_GET_INTERFACE_LIST, nullptr, 0, ifo, num * sizeof(*ifo), &len, nullptr, nullptr) == 0) break;
free(ifo);
if (WSAGetLastError() != WSAEFAULT) {
closesocket(sock);
@@ -138,7 +134,7 @@ static void NetworkFindBroadcastIPsInternal(NetworkAddressList *broadcast) // Wi
memcpy(&address, &ifo[j].iiAddress.Address, sizeof(sockaddr));
((sockaddr_in*)&address)->sin_addr.s_addr = ifo[j].iiAddress.AddressIn.sin_addr.s_addr | ~ifo[j].iiNetmask.AddressIn.sin_addr.s_addr;
NetworkAddress addr(address, sizeof(sockaddr));
if (!broadcast->Contains(addr)) *broadcast->Append() = addr;
if (std::none_of(broadcast->begin(), broadcast->end(), [&addr](NetworkAddress const& elem) -> bool { return elem == addr; })) broadcast->push_back(addr);
}
free(ifo);
@@ -176,7 +172,7 @@ static void NetworkFindBroadcastIPsInternal(NetworkAddressList *broadcast) // !G
(r.ifr_flags & IFF_BROADCAST) &&
ioctl(sock, SIOCGIFBRDADDR, &r) != -1) {
NetworkAddress addr(&r.ifr_broadaddr, sizeof(sockaddr));
if (!broadcast->Contains(addr)) *broadcast->Append() = addr;
if (std::none_of(broadcast->begin(), broadcast->end(), [&addr](NetworkAddress const& elem) -> bool { return elem == addr; })) broadcast->push_back(addr);
}
}
@@ -202,10 +198,8 @@ void NetworkFindBroadcastIPs(NetworkAddressList *broadcast)
/* Now display to the debug all the detected ips */
DEBUG(net, 3, "Detected broadcast addresses:");
int i = 0;
for (NetworkAddress *addr = broadcast->Begin(); addr != broadcast->End(); addr++) {
addr->SetPort(NETWORK_DEFAULT_PORT);
DEBUG(net, 3, "%d) %s", i++, addr->GetHostname());
for (NetworkAddress &addr : *broadcast) {
addr.SetPort(NETWORK_DEFAULT_PORT);
DEBUG(net, 3, "%d) %s", i++, addr.GetHostname());
}
}
#endif /* ENABLE_NETWORK */
-2
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
+22 -88
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -18,8 +16,6 @@
/* Include standard stuff per OS */
#ifdef ENABLE_NETWORK
/* Windows stuff */
#if defined(_WIN32)
#include <errno.h>
@@ -33,6 +29,11 @@
/* Windows has some different names for some types */
typedef unsigned long in_addr_t;
/* Handle cross-compilation with --build=*-*-cygwin --host=*-*-mingw32 */
#if defined(__MINGW32__) && !defined(AI_ADDRCONFIG)
# define AI_ADDRCONFIG 0x00000400
#endif
#if !(defined(__MINGW32__) || defined(__CYGWIN__))
/* Windows has some different names for some types */
typedef SSIZE_T ssize_t;
@@ -48,50 +49,34 @@ typedef unsigned long in_addr_t;
# endif
# define SOCKET int
# define INVALID_SOCKET -1
# if !defined(__MORPHOS__) && !defined(__AMIGA__)
# define ioctlsocket ioctl
# if !defined(BEOS_NET_SERVER)
# define closesocket close
# endif
# define GET_LAST_ERROR() (errno)
# endif
# define ioctlsocket ioctl
# define closesocket close
# define GET_LAST_ERROR() (errno)
/* Need this for FIONREAD on solaris */
# define BSD_COMP
/* Includes needed for UNIX-like systems */
# include <unistd.h>
# include <sys/ioctl.h>
# if defined(__BEOS__) && defined(BEOS_NET_SERVER)
# include <be/net/socket.h>
# include <be/kernel/OS.h> /* snooze() */
# include <be/net/netdb.h>
typedef unsigned long in_addr_t;
# define INADDR_NONE INADDR_BROADCAST
# else
# include <sys/socket.h>
# include <netinet/in.h>
# include <netinet/tcp.h>
# include <arpa/inet.h>
# include <net/if.h>
# include <sys/socket.h>
# include <netinet/in.h>
# include <netinet/tcp.h>
# include <arpa/inet.h>
# include <net/if.h>
/* According to glibc/NEWS, <ifaddrs.h> appeared in glibc-2.3. */
# if !defined(__sgi__) && !defined(SUNOS) && !defined(__MORPHOS__) && !defined(__BEOS__) && !defined(__HAIKU__) && !defined(__INNOTEK_LIBC__) \
&& !(defined(__GLIBC__) && (__GLIBC__ <= 2) && (__GLIBC_MINOR__ <= 2)) && !defined(__dietlibc__) && !defined(HPUX) && !defined(__ANDROID__)
# if !defined(__sgi__) && !defined(SUNOS) && !defined(__INNOTEK_LIBC__) \
&& !(defined(__GLIBC__) && (__GLIBC__ <= 2) && (__GLIBC_MINOR__ <= 2)) && !defined(__dietlibc__) && !defined(HPUX) && !defined(__ANDROID__)
/* If for any reason ifaddrs.h does not exist on your system, comment out
* the following two lines and an alternative way will be used to fetch
* the list of IPs from the system. */
# include <ifaddrs.h>
# define HAVE_GETIFADDRS
# endif
# if !defined(INADDR_NONE)
# define INADDR_NONE 0xffffffff
# endif
# if defined(__BEOS__) && !defined(BEOS_NET_SERVER)
/* needed on Zeta */
# include <sys/sockio.h>
# endif
# endif /* BEOS_NET_SERVER */
# include <ifaddrs.h>
# define HAVE_GETIFADDRS
# endif
# if !defined(INADDR_NONE)
# define INADDR_NONE 0xffffffff
# endif
# if !defined(__BEOS__) && defined(__GLIBC__) && (__GLIBC__ <= 2) && (__GLIBC_MINOR__ <= 1)
# if defined(__GLIBC__) && (__GLIBC__ <= 2) && (__GLIBC_MINOR__ <= 1)
typedef uint32_t in_addr_t;
# endif
@@ -100,14 +85,6 @@ typedef unsigned long in_addr_t;
# include <netdb.h>
#endif /* UNIX */
#ifdef __BEOS__
typedef int socklen_t;
#endif
#ifdef __HAIKU__
#define IPV6_V6ONLY 27
#endif
/* OS/2 stuff */
#if defined(__OS2__)
# define SOCKET int
@@ -164,39 +141,6 @@ typedef unsigned long in_addr_t;
#endif /* OS/2 */
/* MorphOS and Amiga stuff */
#if defined(__MORPHOS__) || defined(__AMIGA__)
# include <exec/types.h>
# include <proto/exec.h> /* required for Open/CloseLibrary() */
/* MorphOS defines his network functions with UBYTE arrays while we
* use char arrays. This gives tons of unneeded warnings */
# define UBYTE char
# if defined(__MORPHOS__)
# include <sys/filio.h> /* FIO* defines */
# include <sys/sockio.h> /* SIO* defines */
# include <netinet/in.h>
# else /* __AMIGA__ */
# include <proto/socket.h>
# endif
/* Make the names compatible */
# define closesocket(s) CloseSocket(s)
# define GET_LAST_ERROR() Errno()
# define ioctlsocket(s, request, status) IoctlSocket((LONG)s, (ULONG)request, (char*)status)
# define ioctl ioctlsocket
typedef unsigned int in_addr_t;
typedef long socklen_t;
extern struct Library *SocketBase;
# ifdef __AMIGA__
/* for usleep() implementation */
extern struct Device *TimerBase;
extern struct MsgPort *TimerPort;
extern struct timerequest *TimerRequest;
# endif
#endif /* __MORPHOS__ || __AMIGA__ */
/**
* Try to set the socket into non-blocking mode.
* @param d The socket to set the non-blocking more for.
@@ -209,11 +153,7 @@ static inline bool SetNonBlocking(SOCKET d)
#else
int nonblocking = 1;
#endif
#if (defined(__BEOS__) && defined(BEOS_NET_SERVER))
return setsockopt(d, SOL_SOCKET, SO_NONBLOCK, &nonblocking, sizeof(nonblocking)) == 0;
#else
return ioctlsocket(d, FIONBIO, &nonblocking) == 0;
#endif
}
/**
@@ -224,19 +164,13 @@ static inline bool SetNonBlocking(SOCKET d)
static inline bool SetNoDelay(SOCKET d)
{
/* XXX should this be done at all? */
#if !defined(BEOS_NET_SERVER) /* not implemented on BeOS net_server */
int b = 1;
/* The (const char*) cast is needed for windows */
return setsockopt(d, IPPROTO_TCP, TCP_NODELAY, (const char*)&b, sizeof(b)) == 0;
#else
return true;
#endif
}
/* Make sure these structures have the size we expect them to be */
assert_compile(sizeof(in_addr) == 4); ///< IPv4 addresses should be 4 bytes.
assert_compile(sizeof(in6_addr) == 16); ///< IPv6 addresses should be 16 bytes.
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_OS_ABSTRACTION_H */
+7 -13
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -11,8 +9,6 @@
* @file packet.cpp Basic functions to create, fill and read packets.
*/
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#include "../../string_func.h"
@@ -26,10 +22,10 @@
*/
Packet::Packet(NetworkSocketHandler *cs)
{
assert(cs != NULL);
assert(cs != nullptr);
this->cs = cs;
this->next = NULL;
this->next = nullptr;
this->pos = 0; // We start reading from here
this->size = 0;
this->buffer = MallocT<byte>(SEND_MTU);
@@ -41,8 +37,8 @@ Packet::Packet(NetworkSocketHandler *cs)
*/
Packet::Packet(PacketType type)
{
this->cs = NULL;
this->next = NULL;
this->cs = nullptr;
this->next = nullptr;
/* Skip the size so we can write that in before sending the packet */
this->pos = 0;
@@ -64,7 +60,7 @@ Packet::~Packet()
*/
void Packet::PrepareToSend()
{
assert(this->cs == NULL && this->next == NULL);
assert(this->cs == nullptr && this->next == nullptr);
this->buffer[0] = GB(this->size, 0, 8);
this->buffer[1] = GB(this->size, 8, 8);
@@ -151,7 +147,7 @@ void Packet::Send_uint64(uint64 data)
*/
void Packet::Send_string(const char *data)
{
assert(data != NULL);
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') {}
@@ -189,7 +185,7 @@ bool Packet::CanReadFromPacket(uint bytes_to_read)
*/
void Packet::ReadRawPacketSize()
{
assert(this->cs != NULL && this->next == NULL);
assert(this->cs != nullptr && this->next == nullptr);
this->size = (PacketSize)this->buffer[0];
this->size += (PacketSize)this->buffer[1] << 8;
}
@@ -310,5 +306,3 @@ void Packet::Recv_string(char *buffer, size_t size, StringValidationSettings set
str_validate(bufp, last, settings);
}
#endif /* ENABLE_NETWORK */
-6
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -18,8 +16,6 @@
#include "core.h"
#include "../../string_type.h"
#ifdef ENABLE_NETWORK
typedef uint16 PacketSize; ///< Size of the whole packet.
typedef uint8 PacketType; ///< Identifier for the packet
@@ -87,6 +83,4 @@ public:
void Recv_string(char *buffer, size_t size, StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK);
};
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_PACKET_H */
+19 -29
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -11,8 +9,6 @@
* @file tcp.cpp Basic functions to receive and send TCP packets.
*/
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#include "../../debug.h"
@@ -26,7 +22,7 @@
*/
NetworkTCPSocketHandler::NetworkTCPSocketHandler(SOCKET s) :
NetworkSocketHandler(),
packet_queue(NULL), packet_recv(NULL),
packet_queue(nullptr), packet_recv(nullptr),
sock(s), writable(false)
{
}
@@ -45,13 +41,13 @@ NetworkRecvStatus NetworkTCPSocketHandler::CloseConnection(bool error)
NetworkSocketHandler::CloseConnection(error);
/* Free all pending and partially received packets */
while (this->packet_queue != NULL) {
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 = NULL;
this->packet_recv = nullptr;
return NETWORK_RECV_STATUS_OKAY;
}
@@ -65,7 +61,7 @@ NetworkRecvStatus NetworkTCPSocketHandler::CloseConnection(bool error)
void NetworkTCPSocketHandler::SendPacket(Packet *packet)
{
Packet *p;
assert(packet != NULL);
assert(packet != nullptr);
packet->PrepareToSend();
@@ -76,12 +72,12 @@ void NetworkTCPSocketHandler::SendPacket(Packet *packet)
/* Locate last packet buffered for the client */
p = this->packet_queue;
if (p == NULL) {
if (p == nullptr) {
/* No packets yet */
this->packet_queue = packet;
} else {
/* Skip to the last packet */
while (p->next != NULL) p = p->next;
while (p->next != nullptr) p = p->next;
p->next = packet;
}
}
@@ -106,7 +102,7 @@ SendPacketsState NetworkTCPSocketHandler::SendPackets(bool closing_down)
if (!this->IsConnected()) return SPS_CLOSED;
p = this->packet_queue;
while (p != NULL) {
while (p != nullptr) {
res = send(this->sock, (const char*)p->buffer + p->pos, p->size - p->pos, 0);
if (res == -1) {
int err = GET_LAST_ERROR();
@@ -144,15 +140,15 @@ SendPacketsState NetworkTCPSocketHandler::SendPackets(bool closing_down)
/**
* Receives a packet for the given client
* @return The received packet (or NULL when it didn't receive one)
* @return The received packet (or nullptr when it didn't receive one)
*/
Packet *NetworkTCPSocketHandler::ReceivePacket()
{
ssize_t res;
if (!this->IsConnected()) return NULL;
if (!this->IsConnected()) return nullptr;
if (this->packet_recv == NULL) {
if (this->packet_recv == nullptr) {
this->packet_recv = new Packet(this);
}
@@ -169,15 +165,15 @@ Packet *NetworkTCPSocketHandler::ReceivePacket()
/* Something went wrong... (104 is connection reset by peer) */
if (err != 104) DEBUG(net, 0, "recv failed with error %d", err);
this->CloseConnection();
return NULL;
return nullptr;
}
/* Connection would block, so stop for now */
return NULL;
return nullptr;
}
if (res == 0) {
/* Client/server has left */
this->CloseConnection();
return NULL;
return nullptr;
}
p->pos += res;
}
@@ -187,7 +183,7 @@ Packet *NetworkTCPSocketHandler::ReceivePacket()
if (p->size > SEND_MTU) {
this->CloseConnection();
return NULL;
return nullptr;
}
}
@@ -200,22 +196,22 @@ Packet *NetworkTCPSocketHandler::ReceivePacket()
/* Something went wrong... (104 is connection reset by peer) */
if (err != 104) DEBUG(net, 0, "recv failed with error %d", err);
this->CloseConnection();
return NULL;
return nullptr;
}
/* Connection would block */
return NULL;
return nullptr;
}
if (res == 0) {
/* Client/server has left */
this->CloseConnection();
return NULL;
return nullptr;
}
p->pos += res;
}
/* Prepare for receiving a new packet */
this->packet_recv = NULL;
this->packet_recv = nullptr;
p->PrepareToRead();
return p;
@@ -238,14 +234,8 @@ bool NetworkTCPSocketHandler::CanSendReceive()
FD_SET(this->sock, &write_fd);
tv.tv_sec = tv.tv_usec = 0; // don't block at all.
#if !defined(__MORPHOS__) && !defined(__AMIGA__)
if (select(FD_SETSIZE, &read_fd, &write_fd, NULL, &tv) < 0) return false;
#else
if (WaitSelect(FD_SETSIZE, &read_fd, &write_fd, NULL, &tv, NULL) < 0) return false;
#endif
if (select(FD_SETSIZE, &read_fd, &write_fd, nullptr, &tv) < 0) return false;
this->writable = !!FD_ISSET(this->sock, &write_fd);
return FD_ISSET(this->sock, &read_fd) != 0;
}
#endif /* ENABLE_NETWORK */
+3 -10
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -17,8 +15,6 @@
#include "address.h"
#include "packet.h"
#ifdef ENABLE_NETWORK
/** The states of sending the packets. */
enum SendPacketsState {
SPS_CLOSED, ///< The connection got closed.
@@ -42,7 +38,7 @@ public:
*/
bool IsConnected() const { return this->sock != INVALID_SOCKET; }
virtual NetworkRecvStatus CloseConnection(bool error = true);
NetworkRecvStatus CloseConnection(bool error = true) override;
virtual void SendPacket(Packet *packet);
SendPacketsState SendPackets(bool closing_down = false);
@@ -54,7 +50,7 @@ public:
* Whether there is something pending in the send queue.
* @return true when something is pending in the send queue.
*/
bool HasSendQueue() { return this->packet_queue != NULL; }
bool HasSendQueue() { return this->packet_queue != nullptr; }
NetworkTCPSocketHandler(SOCKET s = INVALID_SOCKET);
~NetworkTCPSocketHandler();
@@ -65,7 +61,6 @@ public:
*/
class TCPConnecter {
private:
class ThreadObject *thread; ///< Thread used to create the TCP connection
bool connected; ///< Whether we succeeded in making the connection
bool aborted; ///< Whether we bailed out (i.e. connection making failed)
bool killed; ///< Whether we got killed
@@ -73,7 +68,7 @@ private:
void Connect();
static void ThreadEntry(void *param);
static void ThreadEntry(TCPConnecter *param);
protected:
/** Address we're connecting to */
@@ -99,6 +94,4 @@ public:
static void KillAll();
};
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_TCP_H */
+1 -7
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -11,8 +9,6 @@
* @file tcp_admin.cpp Basic functions to receive and send TCP packets to and from the admin network.
*/
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#include "../network_internal.h"
@@ -117,7 +113,7 @@ NetworkRecvStatus NetworkAdminSocketHandler::HandlePacket(Packet *p)
NetworkRecvStatus NetworkAdminSocketHandler::ReceivePackets()
{
Packet *p;
while ((p = this->ReceivePacket()) != NULL) {
while ((p = this->ReceivePacket()) != nullptr) {
NetworkRecvStatus res = this->HandlePacket(p);
if (res != NETWORK_RECV_STATUS_OKAY) return res;
}
@@ -172,5 +168,3 @@ NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_CMD_NAMES(Packet *p)
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_CMD_LOGGING(Packet *p) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_CMD_LOGGING); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_RCON_END(Packet *p) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_RCON_END); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_PONG(Packet *p) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_PONG); }
#endif /* ENABLE_NETWORK */
+1 -7
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -19,8 +17,6 @@
#include "../network_type.h"
#include "../../core/pool_type.hpp"
#ifdef ENABLE_NETWORK
/**
* Enum with types of TCP packets specific to the admin network.
* This protocol may only be extended to ensure stability.
@@ -483,7 +479,7 @@ protected:
NetworkRecvStatus HandlePacket(Packet *p);
public:
NetworkRecvStatus CloseConnection(bool error = true);
NetworkRecvStatus CloseConnection(bool error = true) override;
NetworkAdminSocketHandler(SOCKET s);
~NetworkAdminSocketHandler();
@@ -500,6 +496,4 @@ public:
}
};
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_TCP_ADMIN_H */
+11 -17
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -11,17 +9,15 @@
* @file tcp_connect.cpp Basic functions to create connections without blocking.
*/
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#include "../../thread/thread.h"
#include "../../thread.h"
#include "tcp.h"
#include "../../safeguards.h"
/** List of connections that are currently being created */
static SmallVector<TCPConnecter *, 1> _tcp_connecters;
static std::vector<TCPConnecter *> _tcp_connecters;
/**
* Create a new connecter for the given address
@@ -34,8 +30,8 @@ TCPConnecter::TCPConnecter(const NetworkAddress &address) :
sock(INVALID_SOCKET),
address(address)
{
*_tcp_connecters.Append() = this;
if (!ThreadObject::New(TCPConnecter::ThreadEntry, this, &this->thread, "ottd:tcp")) {
_tcp_connecters.push_back(this);
if (!StartNewThread(nullptr, "ottd:tcp", &TCPConnecter::ThreadEntry, this)) {
this->Connect();
}
}
@@ -55,9 +51,9 @@ void TCPConnecter::Connect()
* Entry point for the new threads.
* @param param the TCPConnecter instance to call Connect on.
*/
/* static */ void TCPConnecter::ThreadEntry(void *param)
/* static */ void TCPConnecter::ThreadEntry(TCPConnecter *param)
{
static_cast<TCPConnecter*>(param)->Connect();
param->Connect();
}
/**
@@ -68,22 +64,22 @@ void TCPConnecter::Connect()
*/
/* static */ void TCPConnecter::CheckCallbacks()
{
for (TCPConnecter **iter = _tcp_connecters.Begin(); iter < _tcp_connecters.End(); /* nothing */) {
for (auto iter = _tcp_connecters.begin(); iter < _tcp_connecters.end(); /* nothing */) {
TCPConnecter *cur = *iter;
if ((cur->connected || cur->aborted) && cur->killed) {
_tcp_connecters.Erase(iter);
iter = _tcp_connecters.erase(iter);
if (cur->sock != INVALID_SOCKET) closesocket(cur->sock);
delete cur;
continue;
}
if (cur->connected) {
_tcp_connecters.Erase(iter);
iter = _tcp_connecters.erase(iter);
cur->OnConnect(cur->sock);
delete cur;
continue;
}
if (cur->aborted) {
_tcp_connecters.Erase(iter);
iter = _tcp_connecters.erase(iter);
cur->OnFailure();
delete cur;
continue;
@@ -95,7 +91,5 @@ void TCPConnecter::Connect()
/** Kill all connection attempts. */
/* static */ void TCPConnecter::KillAll()
{
for (TCPConnecter **iter = _tcp_connecters.Begin(); iter != _tcp_connecters.End(); iter++) (*iter)->killed = true;
for (TCPConnecter *conn : _tcp_connecters) conn->killed = true;
}
#endif /* ENABLE_NETWORK */
+7 -13
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -11,8 +9,6 @@
* @file tcp_content.cpp Basic functions to receive and send Content packets.
*/
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#ifndef OPENTTD_MSU
#include "../../textfile_gui.h"
@@ -49,8 +45,8 @@ void ContentInfo::TransferFrom(ContentInfo *other)
free(this->dependencies);
free(this->tags);
memcpy(this, other, sizeof(ContentInfo));
other->dependencies = NULL;
other->tags = NULL;
other->dependencies = nullptr;
other->tags = nullptr;
}
}
@@ -100,11 +96,11 @@ bool ContentInfo::IsValid() const
/**
* Search a textfile file next to this file in the content list.
* @param type The type of the textfile to search for.
* @return The filename for the textfile, \c NULL otherwise.
* @return The filename for the textfile, \c nullptr otherwise.
*/
const char *ContentInfo::GetTextfile(TextfileType type) const
{
if (this->state == INVALID) return NULL;
if (this->state == INVALID) return nullptr;
const char *tmp;
switch (this->type) {
default: NOT_REACHED();
@@ -122,7 +118,7 @@ const char *ContentInfo::GetTextfile(TextfileType type) const
break;
case CONTENT_TYPE_NEWGRF: {
const GRFConfig *gc = FindGRFConfig(BSWAP32(this->unique_id), FGCM_EXACT, this->md5sum);
tmp = gc != NULL ? gc->filename : NULL;
tmp = gc != nullptr ? gc->filename : nullptr;
break;
}
case CONTENT_TYPE_BASE_GRAPHICS:
@@ -140,7 +136,7 @@ const char *ContentInfo::GetTextfile(TextfileType type) const
tmp = FindScenario(this, true);
break;
}
if (tmp == NULL) return NULL;
if (tmp == nullptr) return nullptr;
return ::GetTextfile(type, GetContentInfoSubDir(this->type), tmp);
}
#endif /* OPENTTD_MSU */
@@ -211,7 +207,7 @@ bool NetworkContentSocketHandler::ReceivePackets()
Packet *p;
static const int MAX_PACKETS_TO_RECEIVE = 42;
int i = MAX_PACKETS_TO_RECEIVE;
while (--i != 0 && (p = this->ReceivePacket()) != NULL) {
while (--i != 0 && (p = this->ReceivePacket()) != nullptr) {
bool cont = this->HandlePacket(p);
delete p;
if (!cont) return true;
@@ -266,5 +262,3 @@ Subdirectory GetContentInfoSubDir(ContentType type)
}
}
#endif /* OPENTTD_MSU */
#endif /* ENABLE_NETWORK */
+1 -7
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -19,8 +17,6 @@
#include "packet.h"
#include "../../debug.h"
#ifdef ENABLE_NETWORK
/** The values in the enum are important; they are used as database 'keys' */
enum ContentType {
CONTENT_TYPE_BEGIN = 1, ///< Helper to mark the begin of the types
@@ -100,7 +96,7 @@ struct ContentInfo {
class NetworkContentSocketHandler : public NetworkTCPSocketHandler {
protected:
NetworkAddress client_addr; ///< The address we're connected to.
virtual void Close();
void Close() override;
bool ReceiveInvalidPacket(PacketContentType type);
@@ -213,6 +209,4 @@ public:
Subdirectory GetContentInfoSubDir(ContentType type);
#endif /* OPENTTD_MSU */
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_TCP_CONTENT_H */
+2 -8
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -11,8 +9,6 @@
* @file tcp_game.cpp Basic functions to receive and send TCP packets for game purposes.
*/
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#include "../network.h"
@@ -28,7 +24,7 @@
* Create a new socket for the game connection.
* @param s The socket to connect with.
*/
NetworkGameSocketHandler::NetworkGameSocketHandler(SOCKET s) : info(NULL), client_id(INVALID_CLIENT_ID),
NetworkGameSocketHandler::NetworkGameSocketHandler(SOCKET s) : info(nullptr), client_id(INVALID_CLIENT_ID),
last_frame(_frame_counter), last_frame_server(_frame_counter), last_packet(_realtime_tick)
{
this->sock = s;
@@ -136,7 +132,7 @@ NetworkRecvStatus NetworkGameSocketHandler::HandlePacket(Packet *p)
NetworkRecvStatus NetworkGameSocketHandler::ReceivePackets()
{
Packet *p;
while ((p = this->ReceivePacket()) != NULL) {
while ((p = this->ReceivePacket()) != nullptr) {
NetworkRecvStatus res = HandlePacket(p);
delete p;
if (res != NETWORK_RECV_STATUS_OKAY) return res;
@@ -199,5 +195,3 @@ NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_MOVE(Packet *p) { ret
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_MOVE(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_MOVE); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_COMPANY_UPDATE(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_COMPANY_UPDATE); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_CONFIG_UPDATE(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_CONFIG_UPDATE); }
#endif /* ENABLE_NETWORK */
+4 -10
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -19,8 +17,6 @@
#include "../network_type.h"
#include "../../core/pool_type.hpp"
#ifdef ENABLE_NETWORK
/**
* Enum with all types of TCP packets.
* For the exact meaning, look at #NetworkGameSocketHandler.
@@ -132,12 +128,12 @@ struct CommandPacket;
/** A queue of CommandPackets. */
class CommandQueue {
CommandPacket *first; ///< The first packet in the queue.
CommandPacket *last; ///< The last packet in the queue; only valid when first != NULL.
CommandPacket *last; ///< The last packet in the queue; only valid when first != nullptr.
uint count; ///< The number of items in the queue.
public:
/** Initialise the command queue. */
CommandQueue() : first(NULL), last(NULL), count(0) {}
CommandQueue() : first(nullptr), last(nullptr), count(0) {}
/** Clear the command queue. */
~CommandQueue() { this->Free(); }
void Append(CommandPacket *p);
@@ -524,7 +520,7 @@ public:
CommandQueue incoming_queue; ///< The command-queue awaiting handling
uint last_packet; ///< Time we received the last frame.
NetworkRecvStatus CloseConnection(bool error = true);
NetworkRecvStatus CloseConnection(bool error = true) override;
/**
* Close the network connection due to the given status.
@@ -539,7 +535,7 @@ public:
*/
inline void SetInfo(NetworkClientInfo *info)
{
assert(info != NULL && this->info == NULL);
assert(info != nullptr && this->info == nullptr);
this->info = info;
}
@@ -558,6 +554,4 @@ public:
void SendCommand(Packet *p, const CommandPacket *cp);
};
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_TCP_GAME_H */
+22 -32
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -11,8 +9,6 @@
* @file tcp_http.cpp Basic functions to receive and send HTTP TCP packets.
*/
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#include "../../debug.h"
#include "../../rev.h"
@@ -23,7 +19,7 @@
#include "../../safeguards.h"
/** List of open HTTP connections. */
static SmallVector<NetworkHTTPSocketHandler *, 1> _http_connections;
static std::vector<NetworkHTTPSocketHandler *> _http_connections;
/**
* Start the querying
@@ -45,11 +41,11 @@ NetworkHTTPSocketHandler::NetworkHTTPSocketHandler(SOCKET s,
redirect_depth(depth),
sock(s)
{
size_t bufferSize = strlen(url) + strlen(host) + strlen(GetNetworkRevisionString()) + (data == NULL ? 0 : strlen(data)) + 128;
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);
if (data != NULL) {
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);
} 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());
@@ -65,7 +61,7 @@ NetworkHTTPSocketHandler::NetworkHTTPSocketHandler(SOCKET s,
return;
}
*_http_connections.Append() = this;
_http_connections.push_back(this);
}
/** Free whatever needs to be freed. */
@@ -110,7 +106,7 @@ static const char * const LOCATION = "Location: "; ///< Header for l
int NetworkHTTPSocketHandler::HandleHeader()
{
assert(strlen(HTTP_1_0) == strlen(HTTP_1_1));
assert(strstr(this->recv_buffer, END_OF_HEADER) != NULL);
assert(strstr(this->recv_buffer, END_OF_HEADER) != nullptr);
/* We expect a HTTP/1.[01] reply */
if (strncmp(this->recv_buffer, HTTP_1_0, strlen(HTTP_1_0)) != 0 &&
@@ -124,7 +120,7 @@ int NetworkHTTPSocketHandler::HandleHeader()
/* Get the length of the document to receive */
char *length = strcasestr(this->recv_buffer, CONTENT_LENGTH);
if (length == NULL) 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);
@@ -165,7 +161,7 @@ int NetworkHTTPSocketHandler::HandleHeader()
/* Redirect to other URL */
char *uri = strcasestr(this->recv_buffer, LOCATION);
if (uri == NULL) return_error("[tcp/http] missing 'location' header for redirect");
if (uri == nullptr) return_error("[tcp/http] missing 'location' header for redirect");
uri += strlen(LOCATION);
@@ -180,7 +176,7 @@ int NetworkHTTPSocketHandler::HandleHeader()
if (ret != 0) return ret;
/* We've relinquished control of data now. */
this->data = NULL;
this->data = nullptr;
/* Restore the header. */
*end_of_line = '\r';
@@ -197,22 +193,22 @@ int NetworkHTTPSocketHandler::HandleHeader()
/* static */ int NetworkHTTPSocketHandler::Connect(char *uri, HTTPCallback *callback, const char *data, int depth)
{
char *hname = strstr(uri, "://");
if (hname == NULL) return_error("[tcp/http] invalid location");
if (hname == nullptr) return_error("[tcp/http] invalid location");
hname += 3;
char *url = strchr(hname, '/');
if (url == NULL) 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 = NULL;
const char *port = NULL;
const char *company = nullptr;
const char *port = nullptr;
ParseConnectionString(&company, &port, hname);
if (company != NULL) return_error("[tcp/http] invalid hostname");
if (company != nullptr) return_error("[tcp/http] invalid hostname");
NetworkAddress address(hname, port == NULL ? 80 : atoi(port));
NetworkAddress address(hname, port == nullptr ? 80 : atoi(port));
/* Restore the URL. */
*url = '/';
@@ -248,7 +244,7 @@ int NetworkHTTPSocketHandler::Receive()
if (res == 0) {
if (this->recv_length != 0) return -1;
this->callback->OnReceiveData(NULL, 0);
this->callback->OnReceiveData(nullptr, 0);
return 0;
}
@@ -263,7 +259,7 @@ int NetworkHTTPSocketHandler::Receive()
char *end_of_header = strstr(this->recv_buffer, END_OF_HEADER);
this->recv_buffer[end] = prev;
if (end_of_header == NULL) {
if (end_of_header == nullptr) {
if (read == lengthof(this->recv_buffer)) {
DEBUG(net, 0, "[tcp/http] header too big");
return -1;
@@ -299,25 +295,21 @@ int NetworkHTTPSocketHandler::Receive()
/* static */ void NetworkHTTPSocketHandler::HTTPReceive()
{
/* No connections, just bail out. */
if (_http_connections.Length() == 0) return;
if (_http_connections.size() == 0) return;
fd_set read_fd;
struct timeval tv;
FD_ZERO(&read_fd);
for (NetworkHTTPSocketHandler **iter = _http_connections.Begin(); iter < _http_connections.End(); iter++) {
FD_SET((*iter)->sock, &read_fd);
for (NetworkHTTPSocketHandler *handler : _http_connections) {
FD_SET(handler->sock, &read_fd);
}
tv.tv_sec = tv.tv_usec = 0; // don't block at all.
#if !defined(__MORPHOS__) && !defined(__AMIGA__)
int n = select(FD_SETSIZE, &read_fd, NULL, NULL, &tv);
#else
int n = WaitSelect(FD_SETSIZE, &read_fd, NULL, NULL, &tv, NULL);
#endif
int n = select(FD_SETSIZE, &read_fd, nullptr, nullptr, &tv);
if (n == -1) return;
for (NetworkHTTPSocketHandler **iter = _http_connections.Begin(); iter < _http_connections.End(); /* nothing */) {
for (auto iter = _http_connections.begin(); iter < _http_connections.end(); /* nothing */) {
NetworkHTTPSocketHandler *cur = *iter;
if (FD_ISSET(cur->sock, &read_fd)) {
@@ -327,7 +319,7 @@ int NetworkHTTPSocketHandler::Receive()
if (ret <= 0) {
/* Then... the connection can be closed */
cur->CloseConnection();
_http_connections.Erase(iter);
iter = _http_connections.erase(iter);
delete cur;
continue;
}
@@ -335,5 +327,3 @@ int NetworkHTTPSocketHandler::Receive()
iter++;
}
}
#endif /* ENABLE_NETWORK */
+8 -14
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -16,8 +14,6 @@
#include "tcp.h"
#ifdef ENABLE_NETWORK
/** Callback for when the HTTP handler has something to tell us. */
struct HTTPCallback {
/**
@@ -28,9 +24,9 @@ struct HTTPCallback {
/**
* We're receiving data.
* @param data the received data, NULL when all data has been received.
* @param data the received data, nullptr when all data has been received.
* @param length the amount of received data, 0 when all data has been received.
* @note When NULL is sent the HTTP socket handler is closed/freed.
* @note When nullptr is sent the HTTP socket handler is closed/freed.
*/
virtual void OnReceiveData(const char *data, size_t length) = 0;
@@ -62,7 +58,7 @@ public:
return this->sock != INVALID_SOCKET;
}
virtual NetworkRecvStatus CloseConnection(bool error = true);
NetworkRecvStatus CloseConnection(bool error = true) override;
NetworkHTTPSocketHandler(SOCKET sock, HTTPCallback *callback,
const char *host, const char *url, const char *data, int depth);
@@ -70,7 +66,7 @@ public:
~NetworkHTTPSocketHandler();
static int Connect(char *uri, HTTPCallback *callback,
const char *data = NULL, int depth = 0);
const char *data = nullptr, int depth = 0);
static void HTTPReceive();
};
@@ -93,7 +89,7 @@ public:
*/
NetworkHTTPContentConnecter(const NetworkAddress &address,
HTTPCallback *callback, const char *url,
const char *data = NULL, int depth = 0) :
const char *data = nullptr, int depth = 0) :
TCPConnecter(address),
callback(callback),
url(stredup(url)),
@@ -108,20 +104,18 @@ public:
free(this->url);
}
virtual void OnFailure()
void OnFailure() override
{
this->callback->OnFailure();
free(this->data);
}
virtual void OnConnect(SOCKET s)
void OnConnect(SOCKET s) override
{
new NetworkHTTPSocketHandler(s, this->callback, this->address.GetHostname(), this->url, this->data, this->depth);
/* We've relinquished control of data now. */
this->data = NULL;
this->data = nullptr;
}
};
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_TCP_HTTP_H */
+17 -28
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -20,8 +18,6 @@
#include "../../debug.h"
#include "table/strings.h"
#ifdef ENABLE_NETWORK
/**
* Template for TCP listeners.
* @param Tsocket The class we create sockets for.
@@ -56,13 +52,13 @@ public:
/* Check if the client is banned */
bool banned = false;
for (char **iter = _network_ban_list.Begin(); iter != _network_ban_list.End(); iter++) {
banned = address.IsInNetmask(*iter);
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(), *iter);
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 %d", GET_LAST_ERROR());
@@ -106,31 +102,26 @@ public:
FD_ZERO(&write_fd);
Tsocket *cs;
FOR_ALL_ITEMS_FROM(Tsocket, idx, cs, 0) {
for (Tsocket *cs : Tsocket::Iterate()) {
FD_SET(cs->sock, &read_fd);
FD_SET(cs->sock, &write_fd);
}
/* take care of listener port */
for (SocketList::iterator s = sockets.Begin(); s != sockets.End(); s++) {
FD_SET(s->second, &read_fd);
for (auto &s : sockets) {
FD_SET(s.second, &read_fd);
}
tv.tv_sec = tv.tv_usec = 0; // don't block at all.
#if !defined(__MORPHOS__) && !defined(__AMIGA__)
if (select(FD_SETSIZE, &read_fd, &write_fd, NULL, &tv) < 0) return false;
#else
if (WaitSelect(FD_SETSIZE, &read_fd, &write_fd, NULL, &tv, NULL) < 0) return false;
#endif
if (select(FD_SETSIZE, &read_fd, &write_fd, nullptr, &tv) < 0) return false;
/* accept clients.. */
for (SocketList::iterator s = sockets.Begin(); s != sockets.End(); s++) {
if (FD_ISSET(s->second, &read_fd)) AcceptClient(s->second);
for (auto &s : sockets) {
if (FD_ISSET(s.second, &read_fd)) AcceptClient(s.second);
}
/* read stuff from clients */
FOR_ALL_ITEMS_FROM(Tsocket, idx, cs, 0) {
for (Tsocket *cs : Tsocket::Iterate()) {
cs->writable = !!FD_ISSET(cs->sock, &write_fd);
if (FD_ISSET(cs->sock, &read_fd)) {
cs->ReceivePackets();
@@ -146,16 +137,16 @@ public:
*/
static bool Listen(uint16 port)
{
assert(sockets.Length() == 0);
assert(sockets.size() == 0);
NetworkAddressList addresses;
GetBindAddresses(&addresses, port);
for (NetworkAddress *address = addresses.Begin(); address != addresses.End(); address++) {
address->Listen(SOCK_STREAM, &sockets);
for (NetworkAddress &address : addresses) {
address.Listen(SOCK_STREAM, &sockets);
}
if (sockets.Length() == 0) {
if (sockets.size() == 0) {
DEBUG(net, 0, "[server] could not start network: could not create listening socket");
NetworkError(STR_NETWORK_ERROR_SERVER_START);
return false;
@@ -167,16 +158,14 @@ public:
/** Close the sockets we're listening on. */
static void CloseListeners()
{
for (SocketList::iterator s = sockets.Begin(); s != sockets.End(); s++) {
closesocket(s->second);
for (auto &s : sockets) {
closesocket(s.second);
}
sockets.Clear();
sockets.clear();
DEBUG(net, 1, "[%s] closed listeners", Tsocket::GetName());
}
};
template <class Tsocket, PacketType Tfull_packet, PacketType Tban_packet> SocketList TCPListenHandler<Tsocket, Tfull_packet, Tban_packet>::sockets;
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_TCP_LISTEN_H */
+22 -30
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -11,8 +9,6 @@
* @file core/udp.cpp Basic functions to receive and send UDP packets.
*/
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#include "../../date_func.h"
#include "../../debug.h"
@@ -26,16 +22,16 @@
*/
NetworkUDPSocketHandler::NetworkUDPSocketHandler(NetworkAddressList *bind)
{
if (bind != NULL) {
for (NetworkAddress *addr = bind->Begin(); addr != bind->End(); addr++) {
*this->bind.Append() = *addr;
if (bind != nullptr) {
for (NetworkAddress &addr : *bind) {
this->bind.push_back(addr);
}
} else {
/* As hostname NULL and port 0/NULL don't go well when
/* As hostname nullptr and port 0/nullptr don't go well when
* resolving it we need to add an address for each of
* the address families we support. */
*this->bind.Append() = NetworkAddress(NULL, 0, AF_INET);
*this->bind.Append() = NetworkAddress(NULL, 0, AF_INET6);
this->bind.emplace_back(nullptr, 0, AF_INET);
this->bind.emplace_back(nullptr, 0, AF_INET6);
}
}
@@ -49,11 +45,11 @@ bool NetworkUDPSocketHandler::Listen()
/* Make sure socket is closed */
this->Close();
for (NetworkAddress *addr = this->bind.Begin(); addr != this->bind.End(); addr++) {
addr->Listen(SOCK_DGRAM, &this->sockets);
for (NetworkAddress &addr : this->bind) {
addr.Listen(SOCK_DGRAM, &this->sockets);
}
return this->sockets.Length() != 0;
return this->sockets.size() != 0;
}
/**
@@ -61,10 +57,10 @@ bool NetworkUDPSocketHandler::Listen()
*/
void NetworkUDPSocketHandler::Close()
{
for (SocketList::iterator s = this->sockets.Begin(); s != this->sockets.End(); s++) {
closesocket(s->second);
for (auto &s : this->sockets) {
closesocket(s.second);
}
this->sockets.Clear();
this->sockets.clear();
}
NetworkRecvStatus NetworkUDPSocketHandler::CloseConnection(bool error)
@@ -82,30 +78,28 @@ NetworkRecvStatus NetworkUDPSocketHandler::CloseConnection(bool error)
*/
void NetworkUDPSocketHandler::SendPacket(Packet *p, NetworkAddress *recv, bool all, bool broadcast)
{
if (this->sockets.Length() == 0) this->Listen();
if (this->sockets.size() == 0) this->Listen();
for (SocketList::iterator s = this->sockets.Begin(); s != this->sockets.End(); s++) {
for (auto &s : this->sockets) {
/* Make a local copy because if we resolve it we cannot
* easily unresolve it so we can resolve it later again. */
NetworkAddress send(*recv);
/* Not the same type */
if (!send.IsFamily(s->first.GetAddress()->ss_family)) continue;
if (!send.IsFamily(s.first.GetAddress()->ss_family)) continue;
p->PrepareToSend();
#ifndef BEOS_NET_SERVER /* will work around this, some day; maybe. */
if (broadcast) {
/* Enable broadcast */
unsigned long val = 1;
if (setsockopt(s->second, SOL_SOCKET, SO_BROADCAST, (char *) &val, sizeof(val)) < 0) {
if (setsockopt(s.second, SOL_SOCKET, SO_BROADCAST, (char *) &val, sizeof(val)) < 0) {
DEBUG(net, 1, "[udp] setting broadcast failed with: %i", GET_LAST_ERROR());
}
}
#endif
/* Send the buffer */
int res = sendto(s->second, (const char*)p->buffer, p->size, 0, (const struct sockaddr *)send.GetAddress(), send.GetAddressLength());
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());
/* Check for any errors, but ignore it otherwise */
@@ -120,7 +114,7 @@ void NetworkUDPSocketHandler::SendPacket(Packet *p, NetworkAddress *recv, bool a
*/
void NetworkUDPSocketHandler::ReceivePackets()
{
for (SocketList::iterator s = this->sockets.Begin(); s != this->sockets.End(); s++) {
for (auto &s : this->sockets) {
for (int i = 0; i < 1000; i++) { // Do not infinitely loop when DoSing with UDP
struct sockaddr_storage client_addr;
memset(&client_addr, 0, sizeof(client_addr));
@@ -129,8 +123,8 @@ void NetworkUDPSocketHandler::ReceivePackets()
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);
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);
/* Did we get the bytes for the base header of the packet? */
if (nbytes <= 0) break; // No data, i.e. no packet
@@ -180,13 +174,13 @@ void NetworkUDPSocketHandler::SendNetworkGameInfo(Packet *p, const NetworkGameIn
uint count = 0;
/* Count number of GRFs to send information about */
for (c = info->grfconfig; c != NULL; c = c->next) {
for (c = info->grfconfig; c != nullptr; c = c->next) {
if (!HasBit(c->flags, GCF_STATIC)) count++;
}
p->Send_uint8 (count); // Send number of GRFs
/* Send actual GRF Identifications */
for (c = info->grfconfig; c != NULL; c = c->next) {
for (c = info->grfconfig; c != nullptr; c = c->next) {
if (!HasBit(c->flags, GCF_STATIC)) this->SendGRFIdentifier(p, &c->ident);
}
}
@@ -349,5 +343,3 @@ void NetworkUDPSocketHandler::Receive_SERVER_UNREGISTER(Packet *p, NetworkAddres
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); }
#endif /* ENABLE_NETWORK */
+3 -9
View File
@@ -1,5 +1,3 @@
/* $Id$ */
/*
* 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.
@@ -18,8 +16,6 @@
#include "game.h"
#include "packet.h"
#ifdef ENABLE_NETWORK
/** Enum with all types of UDP packets. The order MUST not be changed **/
enum PacketUDPType {
PACKET_UDP_CLIENT_FIND_SERVER, ///< Queries a game server for game information
@@ -54,7 +50,7 @@ protected:
/** The opened sockets. */
SocketList sockets;
NetworkRecvStatus CloseConnection(bool error = true);
NetworkRecvStatus CloseConnection(bool error = true) override;
void ReceiveInvalidPacket(PacketUDPType, NetworkAddress *client_addr);
@@ -231,13 +227,13 @@ protected:
*/
virtual void HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config) { NOT_REACHED(); }
public:
NetworkUDPSocketHandler(NetworkAddressList *bind = NULL);
NetworkUDPSocketHandler(NetworkAddressList *bind = nullptr);
/** On destructing of this class, the socket needs to be closed */
virtual ~NetworkUDPSocketHandler() { this->Close(); }
bool Listen();
void Close();
void Close() override;
void SendPacket(Packet *p, NetworkAddress *recv, bool all = false, bool broadcast = false);
void ReceivePackets();
@@ -246,6 +242,4 @@ public:
void ReceiveNetworkGameInfo(Packet *p, NetworkGameInfo *info);
};
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_UDP_H */