Update to 1.10.0-beta1

This commit is contained in:
dP
2019-10-31 22:24:28 +03:00
parent b84a475e14
commit 599ccf0c2b
1470 changed files with 354219 additions and 16795 deletions
+17 -22
View File
@@ -11,8 +11,6 @@
#include "../../stdafx.h"
#ifdef ENABLE_NETWORK
#include "address.h"
#include "../../debug.h"
@@ -27,7 +25,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 +131,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 +145,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 +156,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 +166,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 +232,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 +242,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 +255,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 +323,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 +386,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 +430,3 @@ void NetworkAddress::Listen(int socktype, SocketList *sockets)
default: return "unsupported";
}
}
#endif /* ENABLE_NETWORK */
+4 -16
View File
@@ -17,11 +17,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 +84,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 +120,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 +181,4 @@ public:
static const char *AddressFamilyAsString(int family);
};
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_ADDRESS_H */
-51
View File
@@ -11,8 +11,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 +19,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 +45,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 +78,3 @@ void NetworkSocketHandler::ReceiveGRFIdentifier(Packet *p, GRFIdentifier *grf)
grf->md5sum[j] = p->Recv_uint8();
}
}
#endif /* ENABLE_NETWORK */
-4
View File
@@ -17,8 +17,6 @@
#include "../../newgrf_config.h"
#include "config.h"
#ifdef ENABLE_NETWORK
bool NetworkCoreInitialize();
void NetworkCoreShutdown();
@@ -80,6 +78,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 */
-4
View File
@@ -19,8 +19,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 +56,4 @@ struct NetworkGameInfo : NetworkServerGameInfo {
const char * GetNetworkRevisionString();
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_GAME_H */
+12 -16
View File
@@ -9,8 +9,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 +22,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 +45,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 +76,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 +94,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 +116,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 +136,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 +174,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 +200,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 */
+22 -86
View File
@@ -18,8 +18,6 @@
/* Include standard stuff per OS */
#ifdef ENABLE_NETWORK
/* Windows stuff */
#if defined(_WIN32)
#include <errno.h>
@@ -33,6 +31,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 +51,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)
# if !defined(__sgi__) && !defined(SUNOS) && !defined(__INNOTEK_LIBC__) \
&& !(defined(__GLIBC__) && (__GLIBC__ <= 2) && (__GLIBC_MINOR__ <= 2)) && !defined(__dietlibc__) && !defined(HPUX)
/* 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 +87,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 +143,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 +155,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 +166,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 -11
View File
@@ -11,8 +11,6 @@
* @file packet.cpp Basic functions to create, fill and read packets.
*/
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#include "../../string_func.h"
@@ -26,10 +24,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 +39,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 +62,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 +149,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 +187,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 +308,3 @@ void Packet::Recv_string(char *buffer, size_t size, StringValidationSettings set
str_validate(bufp, last, settings);
}
#endif /* ENABLE_NETWORK */
-4
View File
@@ -18,8 +18,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 +85,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 -27
View File
@@ -11,8 +11,6 @@
* @file tcp.cpp Basic functions to receive and send TCP packets.
*/
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#include "../../debug.h"
@@ -26,7 +24,7 @@
*/
NetworkTCPSocketHandler::NetworkTCPSocketHandler(SOCKET s) :
NetworkSocketHandler(),
packet_queue(NULL), packet_recv(NULL),
packet_queue(nullptr), packet_recv(nullptr),
sock(s), writable(false)
{
}
@@ -45,13 +43,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 +63,7 @@ NetworkRecvStatus NetworkTCPSocketHandler::CloseConnection(bool error)
void NetworkTCPSocketHandler::SendPacket(Packet *packet)
{
Packet *p;
assert(packet != NULL);
assert(packet != nullptr);
packet->PrepareToSend();
@@ -76,12 +74,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 +104,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 +142,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 +167,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 +185,7 @@ Packet *NetworkTCPSocketHandler::ReceivePacket()
if (p->size > SEND_MTU) {
this->CloseConnection();
return NULL;
return nullptr;
}
}
@@ -200,22 +198,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 +236,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 -8
View File
@@ -17,8 +17,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 +40,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 +52,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 +63,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 +70,7 @@ private:
void Connect();
static void ThreadEntry(void *param);
static void ThreadEntry(TCPConnecter *param);
protected:
/** Address we're connecting to */
@@ -99,6 +96,4 @@ public:
static void KillAll();
};
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_TCP_H */
+1 -5
View File
@@ -11,8 +11,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 +115,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 +170,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 -5
View File
@@ -19,8 +19,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 +481,7 @@ protected:
NetworkRecvStatus HandlePacket(Packet *p);
public:
NetworkRecvStatus CloseConnection(bool error = true);
NetworkRecvStatus CloseConnection(bool error = true) override;
NetworkAdminSocketHandler(SOCKET s);
~NetworkAdminSocketHandler();
@@ -500,6 +498,4 @@ public:
}
};
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_TCP_ADMIN_H */
+11 -15
View File
@@ -11,17 +11,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 +32,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 +53,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 +66,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 +93,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 -11
View File
@@ -11,8 +11,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 +47,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 +98,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 +120,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 +138,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 +209,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 +264,3 @@ Subdirectory GetContentInfoSubDir(ContentType type)
}
}
#endif /* OPENTTD_MSU */
#endif /* ENABLE_NETWORK */
+1 -5
View File
@@ -19,8 +19,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 +98,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 +211,4 @@ public:
Subdirectory GetContentInfoSubDir(ContentType type);
#endif /* OPENTTD_MSU */
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_TCP_CONTENT_H */
+2 -6
View File
@@ -11,8 +11,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 +26,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 +134,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 +197,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 -8
View File
@@ -19,8 +19,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 +130,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 +522,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 +537,7 @@ public:
*/
inline void SetInfo(NetworkClientInfo *info)
{
assert(info != NULL && this->info == NULL);
assert(info != nullptr && this->info == nullptr);
this->info = info;
}
@@ -558,6 +556,4 @@ public:
void SendCommand(Packet *p, const CommandPacket *cp);
};
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_TCP_GAME_H */
+22 -30
View File
@@ -11,8 +11,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 +21,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 +43,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 +63,7 @@ NetworkHTTPSocketHandler::NetworkHTTPSocketHandler(SOCKET s,
return;
}
*_http_connections.Append() = this;
_http_connections.push_back(this);
}
/** Free whatever needs to be freed. */
@@ -110,7 +108,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 +122,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 +163,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 +178,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 +195,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 +246,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 +261,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 +297,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 +321,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 +329,3 @@ int NetworkHTTPSocketHandler::Receive()
iter++;
}
}
#endif /* ENABLE_NETWORK */
+8 -12
View File
@@ -16,8 +16,6 @@
#include "tcp.h"
#ifdef ENABLE_NETWORK
/** Callback for when the HTTP handler has something to tell us. */
struct HTTPCallback {
/**
@@ -28,9 +26,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 +60,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 +68,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 +91,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 +106,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 */
+15 -23
View File
@@ -20,8 +20,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 +54,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());
@@ -113,20 +111,16 @@ public:
}
/* 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 */
@@ -146,16 +140,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 +161,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 -28
View File
@@ -11,8 +11,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 +24,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 +47,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 +59,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 +80,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 +116,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 +125,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 +176,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 +345,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 -7
View File
@@ -18,8 +18,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 +52,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 +229,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 +244,4 @@ public:
void ReceiveNetworkGameInfo(Packet *p, NetworkGameInfo *info);
};
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_UDP_H */
+33 -37
View File
@@ -11,8 +11,6 @@
#include "../stdafx.h"
#ifdef ENABLE_NETWORK
#include "../strings_func.h"
#include "../command_func.h"
#include "../date_func.h"
@@ -59,7 +57,7 @@ bool _network_available; ///< is network mode available?
bool _network_dedicated; ///< are we a dedicated server?
bool _is_network_server; ///< Does this client wants to be a network-server?
NetworkServerGameInfo _network_game_info; ///< Information about our game.
NetworkCompanyState *_network_company_states = NULL; ///< Statistics about some companies.
NetworkCompanyState *_network_company_states = nullptr; ///< Statistics about some companies.
ClientID _network_own_client_id; ///< Our client identifier.
ClientID _redirect_console_to_client; ///< If not invalid, redirect the console output to a client.
bool _network_need_advertise; ///< Whether we need to advertise.
@@ -121,7 +119,7 @@ NetworkClientInfo::~NetworkClientInfo()
/**
* Return the CI given it's client-identifier
* @param client_id the ClientID to search for
* @return return a pointer to the corresponding NetworkClientInfo struct or NULL when not found
* @return return a pointer to the corresponding NetworkClientInfo struct or nullptr when not found
*/
/* static */ NetworkClientInfo *NetworkClientInfo::GetByClientID(ClientID client_id)
{
@@ -131,13 +129,13 @@ NetworkClientInfo::~NetworkClientInfo()
if (ci->client_id == client_id) return ci;
}
return NULL;
return nullptr;
}
/**
* Return the client state given it's client-identifier
* @param client_id the ClientID to search for
* @return return a pointer to the corresponding NetworkClientSocket struct or NULL when not found
* @return return a pointer to the corresponding NetworkClientSocket struct or nullptr when not found
*/
/* static */ ServerNetworkGameSocketHandler *ServerNetworkGameSocketHandler::GetByClientID(ClientID client_id)
{
@@ -147,7 +145,7 @@ NetworkClientInfo::~NetworkClientInfo()
if (cs->client_id == client_id) return cs;
}
return NULL;
return nullptr;
}
byte NetworkSpectatorCount()
@@ -380,7 +378,7 @@ void NetworkHandlePauseChange(PauseMode prev_mode, PauseMode changed_mode)
char buffer[DRAW_STRING_BUFFER];
GetString(buffer, str, lastof(buffer));
NetworkTextMessage(NETWORK_ACTION_SERVER_MESSAGE, CC_DEFAULT, false, NULL, buffer);
NetworkTextMessage(NETWORK_ACTION_SERVER_MESSAGE, CC_DEFAULT, false, nullptr, buffer);
break;
}
@@ -543,7 +541,7 @@ void NetworkClose(bool close_admins)
}
ServerNetworkGameSocketHandler::CloseListeners();
ServerNetworkAdminSocketHandler::CloseListeners();
} else if (MyClient::my_client != NULL) {
} else if (MyClient::my_client != nullptr) {
MyClient::SendQuit();
MyClient::my_client->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
}
@@ -556,7 +554,7 @@ void NetworkClose(bool close_admins)
NetworkFreeLocalCommandQueue();
free(_network_company_states);
_network_company_states = NULL;
_network_company_states = nullptr;
InitializeNetworkPools(close_admins);
}
@@ -578,12 +576,12 @@ class TCPQueryConnecter : TCPConnecter {
public:
TCPQueryConnecter(const NetworkAddress &address) : TCPConnecter(address) {}
virtual void OnFailure()
void OnFailure() override
{
NetworkDisconnect();
}
virtual void OnConnect(SOCKET s)
void OnConnect(SOCKET s) override
{
_networking = true;
new ClientNetworkGameSocketHandler(s);
@@ -610,8 +608,8 @@ void NetworkTCPQueryServer(NetworkAddress address)
void NetworkAddServer(const char *b)
{
if (*b != '\0') {
const char *port = NULL;
const char *company = NULL;
const char *port = nullptr;
const char *company = nullptr;
char host[NETWORK_HOSTNAME_LENGTH];
uint16 rport;
@@ -621,7 +619,7 @@ void NetworkAddServer(const char *b)
rport = NETWORK_DEFAULT_PORT;
ParseConnectionString(&company, &port, host);
if (port != NULL) rport = atoi(port);
if (port != nullptr) rport = atoi(port);
NetworkUDPQueryServer(NetworkAddress(host, rport), true);
}
@@ -634,13 +632,13 @@ void NetworkAddServer(const char *b)
*/
void GetBindAddresses(NetworkAddressList *addresses, uint16 port)
{
for (char **iter = _network_bind_list.Begin(); iter != _network_bind_list.End(); iter++) {
*addresses->Append() = NetworkAddress(*iter, port);
for (const auto &iter : _network_bind_list) {
addresses->emplace_back(iter.c_str(), port);
}
/* No address, so bind to everything. */
if (addresses->Length() == 0) {
*addresses->Append() = NetworkAddress("", port);
if (addresses->size() == 0) {
addresses->emplace_back("", port);
}
}
@@ -649,10 +647,10 @@ void GetBindAddresses(NetworkAddressList *addresses, uint16 port)
* by the function that generates the config file. */
void NetworkRebuildHostList()
{
_network_host_list.Clear();
_network_host_list.clear();
for (NetworkGameList *item = _network_game_list; item != NULL; item = item->next) {
if (item->manually) *_network_host_list.Append() = stredup(item->address.GetAddressAsString(false));
for (NetworkGameList *item = _network_game_list; item != nullptr; item = item->next) {
if (item->manually) _network_host_list.emplace_back(item->address.GetAddressAsString(false));
}
}
@@ -661,12 +659,12 @@ class TCPClientConnecter : TCPConnecter {
public:
TCPClientConnecter(const NetworkAddress &address) : TCPConnecter(address) {}
virtual void OnFailure()
void OnFailure() override
{
NetworkError(STR_NETWORK_ERROR_NOCONNECTION);
}
virtual void OnConnect(SOCKET s)
void OnConnect(SOCKET s) override
{
_networking = true;
new ClientNetworkGameSocketHandler(s);
@@ -886,21 +884,21 @@ void NetworkGameLoop()
static FILE *f = FioFOpenFile("commands.log", "rb", SAVE_DIR);
static Date next_date = 0;
static uint32 next_date_fract;
static CommandPacket *cp = NULL;
static CommandPacket *cp = nullptr;
static bool check_sync_state = false;
static uint32 sync_state[2];
if (f == NULL && next_date == 0) {
if (f == nullptr && next_date == 0) {
DEBUG(net, 0, "Cannot open commands.log");
next_date = 1;
}
while (f != NULL && !feof(f)) {
while (f != nullptr && !feof(f)) {
if (_date == next_date && _date_fract == next_date_fract) {
if (cp != NULL) {
NetworkSendCommand(cp->tile, cp->p1, cp->p2, cp->cmd & ~CMD_FLAGS_MASK, NULL, cp->text, cp->company);
if (cp != nullptr) {
NetworkSendCommand(cp->tile, cp->p1, cp->p2, cp->cmd & ~CMD_FLAGS_MASK, nullptr, cp->text, cp->company);
DEBUG(net, 0, "injecting: %08x; %02x; %02x; %06x; %08x; %08x; %08x; \"%s\" (%s)", _date, _date_fract, (int)_current_company, cp->tile, cp->p1, cp->p2, cp->cmd, cp->text, GetCommandName(cp->cmd));
free(cp);
cp = NULL;
cp = nullptr;
}
if (check_sync_state) {
if (sync_state[0] == _random.state[0] && sync_state[1] == _random.state[1]) {
@@ -914,16 +912,16 @@ void NetworkGameLoop()
}
}
if (cp != NULL || check_sync_state) break;
if (cp != nullptr || check_sync_state) break;
char buff[4096];
if (fgets(buff, lengthof(buff), f) == NULL) break;
if (fgets(buff, lengthof(buff), f) == nullptr) break;
char *p = buff;
/* Ignore the "[date time] " part of the message */
if (*p == '[') {
p = strchr(p, ']');
if (p == NULL) break;
if (p == nullptr) break;
p += 2;
}
@@ -970,10 +968,10 @@ void NetworkGameLoop()
NOT_REACHED();
}
}
if (f != NULL && feof(f)) {
if (f != nullptr && feof(f)) {
DEBUG(net, 0, "End of commands.log");
fclose(f);
f = NULL;
f = nullptr;
}
#endif /* DEBUG_DUMP_COMMANDS */
if (_frame_counter >= _frame_counter_max) {
@@ -1172,5 +1170,3 @@ bool IsNetworkCompatibleVersion(const char *other)
const char *hash2 = ExtractNetworkRevisionHash(other);
return hash1 && hash2 && (strncmp(hash1, hash2, GITHASH_SUFFIX_LEN) == 0);
}
#endif /* ENABLE_NETWORK */
-18
View File
@@ -12,9 +12,6 @@
#ifndef NETWORK_H
#define NETWORK_H
#ifdef ENABLE_NETWORK
void NetworkStartUp();
void NetworkShutDown();
void NetworkDrawChatMessage();
@@ -26,19 +23,4 @@ extern bool _network_available; ///< is network mode available?
extern bool _network_dedicated; ///< are we a dedicated server?
extern bool _is_network_server; ///< Does this client wants to be a network-server?
#else /* ENABLE_NETWORK */
/* Network function stubs when networking is disabled */
static inline void NetworkStartUp() {}
static inline void NetworkShutDown() {}
static inline void NetworkDrawChatMessage() {}
static inline bool HasClients() { return false; }
#define _networking 0
#define _network_server 0
#define _network_available 0
#define _network_dedicated 0
#define _is_network_server 0
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_H */
+9 -13
View File
@@ -9,8 +9,6 @@
/** @file network_admin.cpp Server part of the admin network protocol. */
#ifdef ENABLE_NETWORK
#include "../stdafx.h"
#include "../strings_func.h"
#include "../date_func.h"
@@ -236,12 +234,12 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendClientJoin(ClientID clien
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendClientInfo(const NetworkClientSocket *cs, const NetworkClientInfo *ci)
{
/* Only send data when we're a proper client, not just someone trying to query the server. */
if (ci == NULL) return NETWORK_RECV_STATUS_OKAY;
if (ci == nullptr) return NETWORK_RECV_STATUS_OKAY;
Packet *p = new Packet(ADMIN_PACKET_SERVER_CLIENT_INFO);
p->Send_uint32(ci->client_id);
p->Send_string(cs == NULL ? "" : const_cast<NetworkAddress &>(cs->client_address).GetHostname());
p->Send_string(cs == nullptr ? "" : const_cast<NetworkAddress &>(cs->client_address).GetHostname());
p->Send_string(ci->client_name);
p->Send_uint8 (ci->client_lang);
p->Send_uint32(ci->join_date);
@@ -736,16 +734,16 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_POLL(Packet *p)
/* The admin is requesting client info. */
const NetworkClientSocket *cs;
if (d1 == UINT32_MAX) {
this->SendClientInfo(NULL, NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER));
this->SendClientInfo(nullptr, NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER));
FOR_ALL_CLIENT_SOCKETS(cs) {
this->SendClientInfo(cs, cs->GetInfo());
}
} else {
if (d1 == CLIENT_ID_SERVER) {
this->SendClientInfo(NULL, NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER));
this->SendClientInfo(nullptr, NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER));
} else {
cs = NetworkClientSocket::GetByClientID((ClientID)d1);
if (cs != NULL) this->SendClientInfo(cs, cs->GetInfo());
if (cs != nullptr) this->SendClientInfo(cs, cs->GetInfo());
}
}
break;
@@ -759,7 +757,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_POLL(Packet *p)
}
} else {
company = Company::GetIfValid(d1);
if (company != NULL) this->SendCompanyInfo(company);
if (company != nullptr) this->SendCompanyInfo(company);
}
break;
@@ -886,7 +884,7 @@ void NetworkAdminClientError(ClientID client_id, NetworkErrorCode error_code)
*/
void NetworkAdminCompanyInfo(const Company *company, bool new_company)
{
if (company == NULL) {
if (company == nullptr) {
DEBUG(net, 1, "[admin] Empty company given for update");
return;
}
@@ -908,7 +906,7 @@ void NetworkAdminCompanyInfo(const Company *company, bool new_company)
*/
void NetworkAdminCompanyUpdate(const Company *company)
{
if (company == NULL) return;
if (company == nullptr) return;
ServerNetworkAdminSocketHandler *as;
FOR_ALL_ACTIVE_ADMIN_SOCKETS(as) {
@@ -994,7 +992,7 @@ void NetworkAdminGameScript(const char *json)
*/
void NetworkAdminCmdLogging(const NetworkClientSocket *owner, const CommandPacket *cp)
{
ClientID client_id = owner == NULL ? _network_own_client_id : owner->client_id;
ClientID client_id = owner == nullptr ? _network_own_client_id : owner->client_id;
ServerNetworkAdminSocketHandler *as;
FOR_ALL_ACTIVE_ADMIN_SOCKETS(as) {
@@ -1045,5 +1043,3 @@ void NetworkAdminUpdate(AdminUpdateFrequency freq)
}
}
}
#endif /* ENABLE_NETWORK */
+8 -11
View File
@@ -12,8 +12,6 @@
#ifndef NETWORK_ADMIN_H
#define NETWORK_ADMIN_H
#ifdef ENABLE_NETWORK
#include "network_internal.h"
#include "core/tcp_listen.h"
#include "core/tcp_admin.h"
@@ -28,14 +26,14 @@ extern NetworkAdminSocketPool _networkadminsocket_pool;
/** Class for handling the server side of the game connection. */
class ServerNetworkAdminSocketHandler : public NetworkAdminSocketPool::PoolItem<&_networkadminsocket_pool>, public NetworkAdminSocketHandler, public TCPListenHandler<ServerNetworkAdminSocketHandler, ADMIN_PACKET_SERVER_FULL, ADMIN_PACKET_SERVER_BANNED> {
protected:
virtual NetworkRecvStatus Receive_ADMIN_JOIN(Packet *p);
virtual NetworkRecvStatus Receive_ADMIN_QUIT(Packet *p);
virtual NetworkRecvStatus Receive_ADMIN_UPDATE_FREQUENCY(Packet *p);
virtual NetworkRecvStatus Receive_ADMIN_POLL(Packet *p);
virtual NetworkRecvStatus Receive_ADMIN_CHAT(Packet *p);
virtual NetworkRecvStatus Receive_ADMIN_RCON(Packet *p);
virtual NetworkRecvStatus Receive_ADMIN_GAMESCRIPT(Packet *p);
virtual NetworkRecvStatus Receive_ADMIN_PING(Packet *p);
NetworkRecvStatus Receive_ADMIN_JOIN(Packet *p) override;
NetworkRecvStatus Receive_ADMIN_QUIT(Packet *p) override;
NetworkRecvStatus Receive_ADMIN_UPDATE_FREQUENCY(Packet *p) override;
NetworkRecvStatus Receive_ADMIN_POLL(Packet *p) override;
NetworkRecvStatus Receive_ADMIN_CHAT(Packet *p) override;
NetworkRecvStatus Receive_ADMIN_RCON(Packet *p) override;
NetworkRecvStatus Receive_ADMIN_GAMESCRIPT(Packet *p) override;
NetworkRecvStatus Receive_ADMIN_PING(Packet *p) override;
NetworkRecvStatus SendProtocol();
NetworkRecvStatus SendPong(uint32 d1);
@@ -124,5 +122,4 @@ void NetworkAdminConsole(const char *origin, const char *string);
void NetworkAdminGameScript(const char *json);
void NetworkAdminCmdLogging(const NetworkClientSocket *owner, const CommandPacket *cp);
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_ADMIN_H */
-3
View File
@@ -12,8 +12,6 @@
#ifndef NETWORK_BASE_H
#define NETWORK_BASE_H
#ifdef ENABLE_NETWORK
#include "network_type.h"
#include "core/address.h"
#include "../core/pool_type.hpp"
@@ -54,5 +52,4 @@ struct NetworkClientInfo : NetworkClientInfoPool::PoolItem<&_networkclientinfo_p
*/
#define FOR_ALL_CLIENT_INFOS(var) FOR_ALL_CLIENT_INFOS_FROM(var, 0)
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_BASE_H */
+14 -18
View File
@@ -11,8 +11,6 @@
#include <stdarg.h> /* va_list */
#ifdef ENABLE_NETWORK
#include "../stdafx.h"
#include "../strings_func.h"
#include "../blitter/factory.hpp"
@@ -48,7 +46,7 @@ struct ChatMessage {
};
/* used for chat window */
static ChatMessage *_chatmsg_list = NULL; ///< The actual chat message list.
static ChatMessage *_chatmsg_list = nullptr; ///< The actual chat message list.
static bool _chatmessage_dirty = false; ///< Does the chat message need repainting?
static bool _chatmessage_visible = false; ///< Is a chat message visible.
static bool _chat_tab_completion_active; ///< Whether tab completion is active.
@@ -59,7 +57,7 @@ static uint MAX_CHAT_MESSAGES = 0; ///< The limit of chat messages to sho
* the left and pixels from the bottom. The height is the maximum height.
*/
static PointDimension _chatmsg_box;
static uint8 *_chatmessage_backup = NULL; ///< Backup in case text is moved.
static uint8 *_chatmessage_backup = nullptr; ///< Backup in case text is moved.
/**
* Count the chat messages.
@@ -322,7 +320,7 @@ struct NetworkChatWindow : public Window {
InvalidateWindowData(WC_NEWS_WINDOW, 0, 0);
}
virtual void FindWindowPlacementAndResize(int def_width, int def_height)
void FindWindowPlacementAndResize(int def_width, int def_height) override
{
Window::FindWindowPlacementAndResize(_toolbar_width, def_height);
}
@@ -362,7 +360,7 @@ struct NetworkChatWindow : public Window {
}
}
return NULL;
return nullptr;
}
/**
@@ -373,7 +371,7 @@ struct NetworkChatWindow : public Window {
static char *ChatTabCompletionFindText(char *buf)
{
char *p = strrchr(buf, ' ');
if (p == NULL) return buf;
if (p == nullptr) return buf;
*p = '\0';
return p + 1;
@@ -402,7 +400,7 @@ struct NetworkChatWindow : public Window {
tb_buf = ChatTabCompletionFindText(pre_buf);
tb_len = strlen(tb_buf);
while ((cur_name = ChatTabCompletionNextItem(&item)) != NULL) {
while ((cur_name = ChatTabCompletionNextItem(&item)) != nullptr) {
item++;
if (_chat_tab_completion_active) {
@@ -460,13 +458,13 @@ struct NetworkChatWindow : public Window {
free(pre_buf);
}
virtual Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number)
Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number) override
{
Point pt = { 0, _screen.height - sm_height - FindWindowById(WC_STATUS_BAR, 0)->height };
return pt;
}
virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
{
if (widget != WID_NC_DESTINATION) return;
@@ -479,7 +477,7 @@ struct NetworkChatWindow : public Window {
*size = maxdim(*size, d);
}
virtual void DrawWidget(const Rect &r, int widget) const
void DrawWidget(const Rect &r, int widget) const override
{
if (widget != WID_NC_DESTINATION) return;
@@ -489,7 +487,7 @@ struct NetworkChatWindow : public Window {
DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, this->dest_string, TC_BLACK, SA_RIGHT);
}
virtual void OnClick(Point pt, int widget, int click_count)
void OnClick(Point pt, int widget, int click_count) override
{
switch (widget) {
case WID_NC_SENDBUTTON: /* Send */
@@ -502,7 +500,7 @@ struct NetworkChatWindow : public Window {
}
}
virtual EventState OnKeyPress(WChar key, uint16 keycode)
EventState OnKeyPress(WChar key, uint16 keycode) override
{
EventState state = ES_NOT_HANDLED;
if (keycode == WKC_TAB) {
@@ -512,7 +510,7 @@ struct NetworkChatWindow : public Window {
return state;
}
virtual void OnEditboxChanged(int wid)
void OnEditboxChanged(int wid) override
{
_chat_tab_completion_active = false;
}
@@ -522,7 +520,7 @@ struct NetworkChatWindow : public Window {
* @param data Information about the changed data.
* @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
*/
virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
void OnInvalidateData(int data = 0, bool gui_scope = true) override
{
if (data == this->dest) delete this;
}
@@ -545,7 +543,7 @@ static const NWidgetPart _nested_chat_window_widgets[] = {
/** The description of the chat window. */
static WindowDesc _chat_window_desc(
WDP_MANUAL, NULL, 0, 0,
WDP_MANUAL, nullptr, 0, 0,
WC_SEND_NETWORK_MSG, WC_NONE,
0,
_nested_chat_window_widgets, lengthof(_nested_chat_window_widgets)
@@ -562,5 +560,3 @@ void ShowNetworkChatQueryWindow(DestType type, int dest)
DeleteWindowByClass(WC_SEND_NETWORK_MSG);
new NetworkChatWindow(&_chat_window_desc, type, dest);
}
#endif /* ENABLE_NETWORK */
+44 -40
View File
@@ -9,8 +9,6 @@
/** @file network_client.cpp Client part of the network protocol. */
#ifdef ENABLE_NETWORK
#include "../stdafx.h"
#include "network_gui.h"
#include "../saveload/saveload.h"
@@ -31,6 +29,7 @@
#include "network_base.h"
#include "network_client.h"
#include "../core/backup_type.hpp"
#include "../thread.h"
#include "table/strings.h"
@@ -43,7 +42,7 @@
struct PacketReader : LoadFilter {
static const size_t CHUNK = 32 * 1024; ///< 32 KiB chunks of memory.
AutoFreeSmallVector<byte *, 16> blocks; ///< Buffer with blocks of allocated memory.
std::vector<byte *> blocks; ///< Buffer with blocks of allocated memory.
byte *buf; ///< Buffer we're going to write to/read from.
byte *bufe; ///< End of the buffer we write to/read from.
byte **block; ///< The block we're reading from/writing to.
@@ -51,10 +50,17 @@ struct PacketReader : LoadFilter {
size_t read_bytes; ///< The total number of read bytes.
/** Initialise everything. */
PacketReader() : LoadFilter(NULL), buf(NULL), bufe(NULL), block(NULL), written_bytes(0), read_bytes(0)
PacketReader() : LoadFilter(nullptr), buf(nullptr), bufe(nullptr), block(nullptr), written_bytes(0), read_bytes(0)
{
}
~PacketReader() override
{
for (auto p : this->blocks) {
free(p);
}
}
/**
* Add a packet to this buffer.
* @param p The packet to add.
@@ -79,14 +85,14 @@ struct PacketReader : LoadFilter {
/* Allocate a new chunk and add the remaining data. */
pbuf += to_write;
to_write = in_packet - to_write;
this->buf = *this->blocks.Append() = CallocT<byte>(CHUNK);
this->blocks.push_back(this->buf = CallocT<byte>(CHUNK));
this->bufe = this->buf + CHUNK;
memcpy(this->buf, pbuf, to_write);
this->buf += to_write;
}
/* virtual */ size_t Read(byte *rbuf, size_t size)
size_t Read(byte *rbuf, size_t size) override
{
/* Limit the amount to read to whatever we still have. */
size_t ret_size = size = min(this->written_bytes - this->read_bytes, size);
@@ -108,11 +114,11 @@ struct PacketReader : LoadFilter {
return ret_size;
}
/* virtual */ void Reset()
void Reset() override
{
this->read_bytes = 0;
this->block = this->blocks.Begin();
this->block = this->blocks.data();
this->buf = *this->block++;
this->bufe = this->buf + CHUNK;
}
@@ -137,9 +143,9 @@ void ClientNetworkEmergencySave()
* Create a new socket for the client side of the game connection.
* @param s The socket to connect with.
*/
ClientNetworkGameSocketHandler::ClientNetworkGameSocketHandler(SOCKET s) : NetworkGameSocketHandler(s), savegame(NULL), status(STATUS_INACTIVE)
ClientNetworkGameSocketHandler::ClientNetworkGameSocketHandler(SOCKET s) : NetworkGameSocketHandler(s), savegame(nullptr), status(STATUS_INACTIVE)
{
assert(ClientNetworkGameSocketHandler::my_client == NULL);
assert(ClientNetworkGameSocketHandler::my_client == nullptr);
ClientNetworkGameSocketHandler::my_client = this;
}
@@ -147,7 +153,7 @@ ClientNetworkGameSocketHandler::ClientNetworkGameSocketHandler(SOCKET s) : Netwo
ClientNetworkGameSocketHandler::~ClientNetworkGameSocketHandler()
{
assert(ClientNetworkGameSocketHandler::my_client == this);
ClientNetworkGameSocketHandler::my_client = NULL;
ClientNetworkGameSocketHandler::my_client = nullptr;
delete this->savegame;
}
@@ -295,7 +301,7 @@ void ClientNetworkGameSocketHandler::ClientError(NetworkRecvStatus res)
/** Our client's connection. */
ClientNetworkGameSocketHandler * ClientNetworkGameSocketHandler::my_client = NULL;
ClientNetworkGameSocketHandler * ClientNetworkGameSocketHandler::my_client = nullptr;
/** Last frame we performed an ack. */
static uint32 last_ack_frame;
@@ -314,9 +320,9 @@ static uint8 _network_server_max_spectators;
CompanyID _network_join_as;
/** Login password from -p argument */
const char *_network_join_server_password = NULL;
const char *_network_join_server_password = nullptr;
/** Company password from -P argument */
const char *_network_join_company_password = NULL;
const char *_network_join_company_password = nullptr;
/** Make sure the server ID length is the same as a md5 hash. */
assert_compile(NETWORK_SERVER_ID_LENGTH == 16 * 2 + 1);
@@ -527,7 +533,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendMove(CompanyID company, co
*/
bool ClientNetworkGameSocketHandler::IsConnected()
{
return my_client != NULL && my_client->status == STATUS_ACTIVE;
return my_client != nullptr && my_client->status == STATUS_ACTIVE;
}
@@ -536,7 +542,7 @@ bool ClientNetworkGameSocketHandler::IsConnected()
* DEF_CLIENT_RECEIVE_COMMAND has parameter: Packet *p
************/
extern bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL);
extern bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = nullptr);
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_FULL(Packet *p)
{
@@ -570,7 +576,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_COMPANY_INFO(Pa
if (current >= MAX_COMPANIES) return NETWORK_RECV_STATUS_CLOSE_QUERY;
NetworkCompanyInfo *company_info = GetLobbyCompanyInfo(current);
if (company_info == NULL) return NETWORK_RECV_STATUS_CLOSE_QUERY;
if (company_info == nullptr) return NETWORK_RECV_STATUS_CLOSE_QUERY;
p->Recv_string(company_info->company_name, sizeof(company_info->company_name));
company_info->inaugurated_year = p->Recv_uint32();
@@ -613,7 +619,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CLIENT_INFO(Pac
if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
ci = NetworkClientInfo::GetByClientID(client_id);
if (ci != NULL) {
if (ci != nullptr) {
if (playas == ci->client_playas && strcmp(name, ci->client_name) != 0) {
/* Client name changed, display the change */
NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, name);
@@ -708,7 +714,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHECK_NEWGRFS(P
/* Check whether we know this GRF */
const GRFConfig *f = FindGRFConfig(c.grfid, FGCM_EXACT, c.md5sum);
if (f == NULL) {
if (f == nullptr) {
/* We do not know this GRF, bail out of initialization */
char buf[sizeof(c.md5sum) * 2 + 1];
md5sumToString(buf, lastof(buf), c.md5sum);
@@ -794,7 +800,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_BEGIN(Packe
if (this->status < STATUS_AUTHORIZED || this->status >= STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
this->status = STATUS_MAP;
if (this->savegame != NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
if (this->savegame != nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
this->savegame = new PacketReader();
@@ -812,7 +818,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_BEGIN(Packe
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_SIZE(Packet *p)
{
if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
if (this->savegame == NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
if (this->savegame == nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
_network_join_bytes_total = p->Recv_uint32();
SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
@@ -823,7 +829,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_SIZE(Packet
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DATA(Packet *p)
{
if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
if (this->savegame == NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
if (this->savegame == nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
/* We are still receiving data, put it to the file */
this->savegame->AddPacket(p);
@@ -837,7 +843,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DATA(Packet
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DONE(Packet *p)
{
if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
if (this->savegame == NULL) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
if (this->savegame == nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
_network_join_status = NETWORK_JOIN_STATUS_PROCESSING;
SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
@@ -850,12 +856,12 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DONE(Packet
* game, which would cause us to free this->savegame twice.
*/
LoadFilter *lf = this->savegame;
this->savegame = NULL;
this->savegame = nullptr;
lf->Reset();
/* The map is done downloading, load it */
ClearErrorMessages();
bool load_success = SafeLoad(NULL, SLO_LOAD, DFT_GAME_FILE, GM_NORMAL, NO_DIRECTORY, lf);
bool load_success = SafeLoad(nullptr, SLO_LOAD, DFT_GAME_FILE, GM_NORMAL, NO_DIRECTORY, lf);
/* Long savegame loads shouldn't affect the lag calculation! */
this->last_packet = _realtime_tick;
@@ -881,7 +887,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DONE(Packet
* the server will give us a client-id and let us in */
_network_join_status = NETWORK_JOIN_STATUS_REGISTERING;
ShowJoinStatusWindow();
NetworkSendCommand(0, CCA_NEW, 0, CMD_COMPANY_CTRL, NULL, NULL, _local_company);
NetworkSendCommand(0, CCA_NEW, 0, CMD_COMPANY_CTRL, nullptr, nullptr, _local_company);
}
} else {
/* take control over an existing company */
@@ -946,7 +952,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_COMMAND(Packet
cp.frame = p->Recv_uint32();
cp.my_cmd = p->Recv_bool();
if (err != NULL) {
if (err != nullptr) {
IConsolePrintF(CC_ERROR, "WARNING: %s from server, dropping...", err);
return NETWORK_RECV_STATUS_MALFORMED_PACKET;
}
@@ -961,7 +967,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHAT(Packet *p)
if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
char name[NETWORK_NAME_LENGTH], msg[NETWORK_CHAT_LENGTH];
const NetworkClientInfo *ci = NULL, *ci_to;
const NetworkClientInfo *ci = nullptr, *ci_to;
NetworkAction action = (NetworkAction)p->Recv_uint8();
ClientID client_id = (ClientID)p->Recv_uint32();
@@ -970,7 +976,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHAT(Packet *p)
int64 data = p->Recv_uint64();
ci_to = NetworkClientInfo::GetByClientID(client_id);
if (ci_to == NULL) return NETWORK_RECV_STATUS_OKAY;
if (ci_to == nullptr) return NETWORK_RECV_STATUS_OKAY;
/* Did we initiate the action locally? */
if (self_send) {
@@ -1003,7 +1009,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHAT(Packet *p)
ci = ci_to;
}
if (ci != NULL) {
if (ci != nullptr) {
NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), self_send, name, msg, data);
}
return NETWORK_RECV_STATUS_OKAY;
@@ -1016,8 +1022,8 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR_QUIT(Pack
ClientID client_id = (ClientID)p->Recv_uint32();
NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
if (ci != NULL) {
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, NULL, GetNetworkErrorMsg((NetworkErrorCode)p->Recv_uint8()));
if (ci != nullptr) {
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, nullptr, GetNetworkErrorMsg((NetworkErrorCode)p->Recv_uint8()));
delete ci;
}
@@ -1033,8 +1039,8 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_QUIT(Packet *p)
ClientID client_id = (ClientID)p->Recv_uint32();
NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
if (ci != NULL) {
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, NULL, STR_NETWORK_MESSAGE_CLIENT_LEAVING);
if (ci != nullptr) {
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, nullptr, STR_NETWORK_MESSAGE_CLIENT_LEAVING);
delete ci;
} else {
DEBUG(net, 0, "Unknown client (%d) is leaving the game", client_id);
@@ -1053,7 +1059,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_JOIN(Packet *p)
ClientID client_id = (ClientID)p->Recv_uint32();
NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
if (ci != NULL) {
if (ci != nullptr) {
NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, ci->client_name);
}
@@ -1123,7 +1129,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MOVE(Packet *p)
const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
/* Just make sure we do not try to use a client_index that does not exist */
if (ci == NULL) return NETWORK_RECV_STATUS_OKAY;
if (ci == nullptr) return NETWORK_RECV_STATUS_OKAY;
/* if not valid player, force spectator, else check player exists */
if (!Company::IsValidID(company_id)) company_id = COMPANY_SPECTATOR;
@@ -1226,7 +1232,7 @@ void NetworkClientRequestMove(CompanyID company_id, const char *pass)
*/
void NetworkClientsToSpectators(CompanyID cid)
{
Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
Backup<CompanyID> cur_company(_current_company, FILE_LINE);
/* If our company is changing owner, go to spectators */
if (cid == _local_company) SetLocalCompany(COMPANY_SPECTATOR);
@@ -1247,7 +1253,7 @@ void NetworkUpdateClientName()
{
NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(_network_own_client_id);
if (ci == NULL) return;
if (ci == nullptr) return;
/* Don't change the name if it is the same as the old name */
if (strcmp(ci->client_name, _settings_client.network.client_name) != 0) {
@@ -1320,5 +1326,3 @@ bool NetworkMaxSpectatorsReached()
{
return NetworkSpectatorCount() >= (_network_server ? _settings_client.network.max_spectators : _network_server_max_spectators);
}
#endif /* ENABLE_NETWORK */
+28 -32
View File
@@ -12,8 +12,6 @@
#ifndef NETWORK_CLIENT_H
#define NETWORK_CLIENT_H
#ifdef ENABLE_NETWORK
#include "network_internal.h"
/** Class for handling the client side of the game connection. */
@@ -44,33 +42,33 @@ protected:
friend void NetworkClose(bool close_admins);
static ClientNetworkGameSocketHandler *my_client; ///< This is us!
virtual NetworkRecvStatus Receive_SERVER_FULL(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_BANNED(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_ERROR(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_COMPANY_INFO(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_CLIENT_INFO(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_NEED_GAME_PASSWORD(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_NEED_COMPANY_PASSWORD(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_WELCOME(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_WAIT(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_MAP_BEGIN(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_MAP_SIZE(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_MAP_DATA(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_MAP_DONE(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_JOIN(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_FRAME(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_SYNC(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_COMMAND(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_CHAT(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_QUIT(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_ERROR_QUIT(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_SHUTDOWN(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_NEWGAME(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_RCON(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_CHECK_NEWGRFS(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_MOVE(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_COMPANY_UPDATE(Packet *p);
virtual NetworkRecvStatus Receive_SERVER_CONFIG_UPDATE(Packet *p);
NetworkRecvStatus Receive_SERVER_FULL(Packet *p) override;
NetworkRecvStatus Receive_SERVER_BANNED(Packet *p) override;
NetworkRecvStatus Receive_SERVER_ERROR(Packet *p) override;
NetworkRecvStatus Receive_SERVER_COMPANY_INFO(Packet *p) override;
NetworkRecvStatus Receive_SERVER_CLIENT_INFO(Packet *p) override;
NetworkRecvStatus Receive_SERVER_NEED_GAME_PASSWORD(Packet *p) override;
NetworkRecvStatus Receive_SERVER_NEED_COMPANY_PASSWORD(Packet *p) override;
NetworkRecvStatus Receive_SERVER_WELCOME(Packet *p) override;
NetworkRecvStatus Receive_SERVER_WAIT(Packet *p) override;
NetworkRecvStatus Receive_SERVER_MAP_BEGIN(Packet *p) override;
NetworkRecvStatus Receive_SERVER_MAP_SIZE(Packet *p) override;
NetworkRecvStatus Receive_SERVER_MAP_DATA(Packet *p) override;
NetworkRecvStatus Receive_SERVER_MAP_DONE(Packet *p) override;
NetworkRecvStatus Receive_SERVER_JOIN(Packet *p) override;
NetworkRecvStatus Receive_SERVER_FRAME(Packet *p) override;
NetworkRecvStatus Receive_SERVER_SYNC(Packet *p) override;
NetworkRecvStatus Receive_SERVER_COMMAND(Packet *p) override;
NetworkRecvStatus Receive_SERVER_CHAT(Packet *p) override;
NetworkRecvStatus Receive_SERVER_QUIT(Packet *p) override;
NetworkRecvStatus Receive_SERVER_ERROR_QUIT(Packet *p) override;
NetworkRecvStatus Receive_SERVER_SHUTDOWN(Packet *p) override;
NetworkRecvStatus Receive_SERVER_NEWGAME(Packet *p) override;
NetworkRecvStatus Receive_SERVER_RCON(Packet *p) override;
NetworkRecvStatus Receive_SERVER_CHECK_NEWGRFS(Packet *p) override;
NetworkRecvStatus Receive_SERVER_MOVE(Packet *p) override;
NetworkRecvStatus Receive_SERVER_COMPANY_UPDATE(Packet *p) override;
NetworkRecvStatus Receive_SERVER_CONFIG_UPDATE(Packet *p) override;
static NetworkRecvStatus SendNewGRFsOk();
static NetworkRecvStatus SendGetMap();
@@ -80,7 +78,7 @@ public:
ClientNetworkGameSocketHandler(SOCKET s);
~ClientNetworkGameSocketHandler();
NetworkRecvStatus CloseConnection(NetworkRecvStatus status);
NetworkRecvStatus CloseConnection(NetworkRecvStatus status) override;
void ClientError(NetworkRecvStatus res);
static NetworkRecvStatus SendCompanyInformationQuery();
@@ -118,6 +116,4 @@ extern CompanyID _network_join_as;
extern const char *_network_join_server_password;
extern const char *_network_join_company_password;
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CLIENT_H */
+19 -23
View File
@@ -9,8 +9,6 @@
/** @file network_command.cpp Command handling over network connections. */
#ifdef ENABLE_NETWORK
#include "../stdafx.h"
#include "network_admin.h"
#include "network_client.h"
@@ -23,7 +21,7 @@
/** Table with all the callbacks we'll use for conversion*/
static CommandCallback * const _callback_table[] = {
/* 0x00 */ NULL,
/* 0x00 */ nullptr,
/* 0x01 */ CcBuildPrimaryVehicle,
/* 0x02 */ CcBuildAirport,
/* 0x03 */ CcBuildBridge,
@@ -62,8 +60,8 @@ void CommandQueue::Append(CommandPacket *p)
{
CommandPacket *add = MallocT<CommandPacket>(1);
*add = *p;
add->next = NULL;
if (this->first == NULL) {
add->next = nullptr;
if (this->first == nullptr) {
this->first = add;
} else {
this->last->next = add;
@@ -81,15 +79,15 @@ CommandPacket *CommandQueue::Pop(bool ignore_paused)
{
CommandPacket **prev = &this->first;
CommandPacket *ret = this->first;
CommandPacket *prev_item = NULL;
CommandPacket *prev_item = nullptr;
if (ignore_paused && _pause_mode != PM_UNPAUSED) {
while (ret != NULL && !IsCommandAllowedWhilePaused(ret->cmd)) {
while (ret != nullptr && !IsCommandAllowedWhilePaused(ret->cmd)) {
prev_item = ret;
prev = &ret->next;
ret = ret->next;
}
}
if (ret != NULL) {
if (ret != nullptr) {
if (ret == this->last) this->last = prev_item;
*prev = ret->next;
this->count--;
@@ -106,17 +104,17 @@ CommandPacket *CommandQueue::Peek(bool ignore_paused)
{
if (!ignore_paused || _pause_mode == PM_UNPAUSED) return this->first;
for (CommandPacket *p = this->first; p != NULL; p = p->next) {
for (CommandPacket *p = this->first; p != nullptr; p = p->next) {
if (IsCommandAllowedWhilePaused(p->cmd)) return p;
}
return NULL;
return nullptr;
}
/** Free everything that is in the queue. */
void CommandQueue::Free()
{
CommandPacket *cp;
while ((cp = this->Pop()) != NULL) {
while ((cp = this->Pop()) != nullptr) {
free(cp);
}
assert(this->count == 0);
@@ -149,7 +147,7 @@ void NetworkSendCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, Comman
c.cmd = cmd;
c.callback = callback;
strecpy(c.text, (text != NULL) ? text : "", lastof(c.text));
strecpy(c.text, (text != nullptr) ? text : "", lastof(c.text));
if (_network_server) {
/* If we are the server, we queue the command in our 'special' queue.
@@ -182,7 +180,7 @@ void NetworkSendCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, Comman
*/
void NetworkSyncCommandQueue(NetworkClientSocket *cs)
{
for (CommandPacket *p = _local_execution_queue.Peek(); p != NULL; p = p->next) {
for (CommandPacket *p = _local_execution_queue.Peek(); p != nullptr; p = p->next) {
CommandPacket c = *p;
c.callback = 0;
cs->outgoing_queue.Append(&c);
@@ -199,7 +197,7 @@ void NetworkExecuteLocalCommandQueue()
CommandQueue &queue = (_network_server ? _local_execution_queue : ClientNetworkGameSocketHandler::my_client->incoming_queue);
CommandPacket *cp;
while ((cp = queue.Peek()) != NULL) {
while ((cp = queue.Peek()) != nullptr) {
/* The queue is always in order, which means
* that the first element will be executed first. */
if (_frame_counter < cp->frame) break;
@@ -247,13 +245,13 @@ static void DistributeCommandPacket(CommandPacket &cp, const NetworkClientSocket
if (cs->status >= NetworkClientSocket::STATUS_MAP) {
/* Callbacks are only send back to the client who sent them in the
* first place. This filters that out. */
cp.callback = (cs != owner) ? NULL : callback;
cp.callback = (cs != owner) ? nullptr : callback;
cp.my_cmd = (cs == owner);
cs->outgoing_queue.Append(&cp);
}
}
cp.callback = (cs != owner) ? NULL : callback;
cp.callback = (cs != owner) ? nullptr : callback;
cp.my_cmd = (cs == owner);
_local_execution_queue.Append(&cp);
}
@@ -273,7 +271,7 @@ static void DistributeQueue(CommandQueue *queue, const NetworkClientSocket *owne
#endif
CommandPacket *cp;
while (--to_go >= 0 && (cp = queue->Pop(true)) != NULL) {
while (--to_go >= 0 && (cp = queue->Pop(true)) != nullptr) {
DistributeCommandPacket(*cp, owner);
NetworkAdminCmdLogging(owner, cp);
free(cp);
@@ -284,7 +282,7 @@ static void DistributeQueue(CommandQueue *queue, const NetworkClientSocket *owne
void NetworkDistributeCommands()
{
/* First send the server's commands. */
DistributeQueue(&_local_wait_queue, NULL);
DistributeQueue(&_local_wait_queue, nullptr);
/* Then send the queues of the others. */
NetworkClientSocket *cs;
@@ -297,7 +295,7 @@ void NetworkDistributeCommands()
* Receives a command from the network.
* @param p the packet to read from.
* @param cp the struct to write the data to.
* @return an error message. When NULL there has been no error.
* @return an error message. When nullptr there has been no error.
*/
const char *NetworkGameSocketHandler::ReceiveCommand(Packet *p, CommandPacket *cp)
{
@@ -316,7 +314,7 @@ const char *NetworkGameSocketHandler::ReceiveCommand(Packet *p, CommandPacket *c
if (callback >= lengthof(_callback_table)) return "invalid callback";
cp->callback = _callback_table[callback];
return NULL;
return nullptr;
}
/**
@@ -340,9 +338,7 @@ void NetworkGameSocketHandler::SendCommand(Packet *p, const CommandPacket *cp)
if (callback == lengthof(_callback_table)) {
DEBUG(net, 0, "Unknown callback. (Pointer: %p) No callback sent", cp->callback);
callback = 0; // _callback_table[0] == NULL
callback = 0; // _callback_table[0] == nullptr
}
p->Send_uint8 (callback);
}
#endif /* ENABLE_NETWORK */
+107 -120
View File
@@ -9,8 +9,6 @@
/** @file network_content.cpp Content sending/receiving part of the network protocol. */
#if defined(ENABLE_NETWORK)
#include "../stdafx.h"
#include "../rev.h"
#include "../ai/ai.hpp"
@@ -37,7 +35,7 @@ ClientNetworkContentSocketHandler _network_content_client;
/** Wrapper function for the HasProc */
static bool HasGRFConfig(const ContentInfo *ci, bool md5sum)
{
return FindGRFConfig(BSWAP32(ci->unique_id), md5sum ? FGCM_EXACT : FGCM_ANY, md5sum ? ci->md5sum : NULL) != NULL;
return FindGRFConfig(BSWAP32(ci->unique_id), md5sum ? FGCM_EXACT : FGCM_ANY, md5sum ? ci->md5sum : nullptr) != nullptr;
}
/**
@@ -81,7 +79,7 @@ bool ClientNetworkContentSocketHandler::Receive_SERVER_INFO(Packet *p)
}
/* Find the appropriate check function */
HasProc proc = NULL;
HasProc proc = nullptr;
switch (ci->type) {
case CONTENT_TYPE_NEWGRF:
proc = HasGRFConfig;
@@ -124,7 +122,7 @@ bool ClientNetworkContentSocketHandler::Receive_SERVER_INFO(Packet *p)
break;
}
if (proc != NULL) {
if (proc != nullptr) {
if (proc(ci, true)) {
ci->state = ContentInfo::ALREADY_HERE;
} else {
@@ -135,12 +133,11 @@ bool ClientNetworkContentSocketHandler::Receive_SERVER_INFO(Packet *p)
ci->state = ContentInfo::UNSELECTED;
}
/* Something we don't have and has filesize 0 does not exist in te system */
/* Something we don't have and has filesize 0 does not exist in the system */
if (ci->state == ContentInfo::UNSELECTED && ci->filesize == 0) ci->state = ContentInfo::DOES_NOT_EXIST;
/* Do we already have a stub for this? */
for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) {
ContentInfo *ici = *iter;
for (ContentInfo *ici : this->infos) {
if (ici->type == ci->type && ici->unique_id == ci->unique_id &&
memcmp(ci->md5sum, ici->md5sum, sizeof(ci->md5sum)) == 0) {
/* Preserve the name if possible */
@@ -167,11 +164,11 @@ bool ClientNetworkContentSocketHandler::Receive_SERVER_INFO(Packet *p)
return true;
}
*this->infos.Append() = ci;
this->infos.push_back(ci);
/* Incoming data means that we might need to reconsider dependencies */
for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) {
this->CheckDependencyState(*iter);
for (ContentInfo *ici : this->infos) {
this->CheckDependencyState(ici);
}
this->OnReceiveContentInfo(ci);
@@ -244,19 +241,18 @@ void ClientNetworkContentSocketHandler::RequestContentList(uint count, const Con
*/
void ClientNetworkContentSocketHandler::RequestContentList(ContentVector *cv, bool send_md5sum)
{
if (cv == NULL) return;
if (cv == nullptr) return;
this->Connect();
assert(cv->Length() < 255);
assert(cv->Length() < (SEND_MTU - sizeof(PacketSize) - sizeof(byte) - sizeof(uint8)) /
assert(cv->size() < 255);
assert(cv->size() < (SEND_MTU - sizeof(PacketSize) - sizeof(byte) - sizeof(uint8)) /
(sizeof(uint8) + sizeof(uint32) + (send_md5sum ? /*sizeof(ContentInfo::md5sum)*/16 : 0)));
Packet *p = new Packet(send_md5sum ? PACKET_CONTENT_CLIENT_INFO_EXTID_MD5 : PACKET_CONTENT_CLIENT_INFO_EXTID);
p->Send_uint8(cv->Length());
p->Send_uint8((uint8)cv->size());
for (ContentIterator iter = cv->Begin(); iter != cv->End(); iter++) {
const ContentInfo *ci = *iter;
for (const ContentInfo *ci : *cv) {
p->Send_uint8((byte)ci->type);
p->Send_uint32(ci->unique_id);
if (!send_md5sum) continue;
@@ -268,11 +264,9 @@ void ClientNetworkContentSocketHandler::RequestContentList(ContentVector *cv, bo
this->SendPacket(p);
for (ContentIterator iter = cv->Begin(); iter != cv->End(); iter++) {
ContentInfo *ci = *iter;
for (ContentInfo *ci : *cv) {
bool found = false;
for (ContentIterator iter2 = this->infos.Begin(); iter2 != this->infos.End(); iter2++) {
ContentInfo *ci2 = *iter2;
for (ContentInfo *ci2 : this->infos) {
if (ci->type == ci2->type && ci->unique_id == ci2->unique_id &&
(!send_md5sum || memcmp(ci->md5sum, ci2->md5sum, sizeof(ci->md5sum)) == 0)) {
found = true;
@@ -280,7 +274,7 @@ void ClientNetworkContentSocketHandler::RequestContentList(ContentVector *cv, bo
}
}
if (!found) {
*this->infos.Append() = ci;
this->infos.push_back(ci);
} else {
delete ci;
}
@@ -298,15 +292,14 @@ void ClientNetworkContentSocketHandler::DownloadSelectedContent(uint &files, uin
bytes = 0;
ContentIDList content;
for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) {
const ContentInfo *ci = *iter;
for (const ContentInfo *ci : this->infos) {
if (!ci->IsSelected() || ci->state == ContentInfo::ALREADY_HERE) continue;
*content.Append() = ci->id;
content.push_back(ci->id);
bytes += ci->filesize;
}
files = content.Length();
files = (uint)content.size();
/* If there's nothing to download, do nothing. */
if (files == 0) return;
@@ -324,7 +317,7 @@ void ClientNetworkContentSocketHandler::DownloadSelectedContent(uint &files, uin
*/
void ClientNetworkContentSocketHandler::DownloadSelectedContentHTTP(const ContentIDList &content)
{
uint count = content.Length();
uint count = (uint)content.size();
/* Allocate memory for the whole request.
* Requests are "id\nid\n..." (as strings), so assume the maximum ID,
@@ -335,8 +328,8 @@ void ClientNetworkContentSocketHandler::DownloadSelectedContentHTTP(const Conten
const char *lastof = content_request + bytes - 1;
char *p = content_request;
for (const ContentID *id = content.Begin(); id != content.End(); id++) {
p += seprintf(p, lastof, "%d\n", *id);
for (const ContentID &id : content) {
p += seprintf(p, lastof, "%d\n", id);
}
this->http_response_index = -1;
@@ -352,8 +345,8 @@ void ClientNetworkContentSocketHandler::DownloadSelectedContentHTTP(const Conten
*/
void ClientNetworkContentSocketHandler::DownloadSelectedContentFallback(const ContentIDList &content)
{
uint count = content.Length();
const ContentID *content_ids = content.Begin();
uint count = (uint)content.size();
const ContentID *content_ids = content.data();
this->Connect();
while (count > 0) {
@@ -381,12 +374,12 @@ void ClientNetworkContentSocketHandler::DownloadSelectedContentFallback(const Co
* @param ci the information to get the filename from
* @param compressed should the filename end with .gz?
* @return a statically allocated buffer with the filename or
* NULL when no filename could be made.
* nullptr when no filename could be made.
*/
static char *GetFullFilename(const ContentInfo *ci, bool compressed)
{
Subdirectory dir = GetContentInfoSubDir(ci->type);
if (dir == NO_DIRECTORY) return NULL;
if (dir == NO_DIRECTORY) return nullptr;
static char buf[MAX_PATH];
FioGetFullPath(buf, lastof(buf), SP_AUTODOWNLOAD_DIR, dir, ci->filename);
@@ -407,14 +400,14 @@ static bool GunzipFile(const ContentInfo *ci)
/* Need to open the file with fopen() to support non-ASCII on Windows. */
FILE *ftmp = fopen(GetFullFilename(ci, true), "rb");
if (ftmp == NULL) return false;
if (ftmp == nullptr) return false;
/* Duplicate the handle, and close the FILE*, to avoid double-closing the handle later. */
gzFile fin = gzdopen(dup(fileno(ftmp)), "rb");
fclose(ftmp);
FILE *fout = fopen(GetFullFilename(ci, false), "wb");
if (fin == NULL || fout == NULL) {
if (fin == nullptr || fout == nullptr) {
ret = false;
} else {
byte buff[8192];
@@ -448,8 +441,8 @@ static bool GunzipFile(const ContentInfo *ci)
}
}
if (fin != NULL) gzclose(fin);
if (fout != NULL) fclose(fout);
if (fin != nullptr) gzclose(fin);
if (fout != nullptr) fclose(fout);
return ret;
#else
@@ -459,7 +452,7 @@ static bool GunzipFile(const ContentInfo *ci)
bool ClientNetworkContentSocketHandler::Receive_SERVER_CONTENT(Packet *p)
{
if (this->curFile == NULL) {
if (this->curFile == nullptr) {
delete this->curInfo;
/* When we haven't opened a file this must be our first packet with metadata. */
this->curInfo = new ContentInfo;
@@ -480,7 +473,7 @@ bool ClientNetworkContentSocketHandler::Receive_SERVER_CONTENT(Packet *p)
ShowErrorMessage(STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD, STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD_FILE_NOT_WRITABLE, WL_ERROR);
this->Close();
fclose(this->curFile);
this->curFile = NULL;
this->curFile = nullptr;
return false;
}
@@ -501,14 +494,14 @@ bool ClientNetworkContentSocketHandler::BeforeDownload()
{
if (!this->curInfo->IsValid()) {
delete this->curInfo;
this->curInfo = NULL;
this->curInfo = nullptr;
return false;
}
if (this->curInfo->filesize != 0) {
/* The filesize is > 0, so we are going to download it */
const char *filename = GetFullFilename(this->curInfo, true);
if (filename == NULL || (this->curFile = fopen(filename, "wb")) == NULL) {
if (filename == nullptr || (this->curFile = fopen(filename, "wb")) == nullptr) {
/* Unless that fails of course... */
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_CONTENT_DOWNLOAD);
ShowErrorMessage(STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD, STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD_FILE_NOT_WRITABLE, WL_ERROR);
@@ -527,7 +520,7 @@ void ClientNetworkContentSocketHandler::AfterDownload()
/* We read nothing; that's our marker for end-of-stream.
* Now gunzip the tar and make it known. */
fclose(this->curFile);
this->curFile = NULL;
this->curFile = nullptr;
if (GunzipFile(this->curInfo)) {
unlink(GetFullFilename(this->curInfo, true));
@@ -557,41 +550,42 @@ void ClientNetworkContentSocketHandler::OnFailure()
uint files, bytes;
this->DownloadSelectedContent(files, bytes, true);
this->http_response.Reset();
this->http_response.clear();
this->http_response.shrink_to_fit();
this->http_response_index = -2;
if (this->curFile != NULL) {
if (this->curFile != nullptr) {
/* Revert the download progress when we are going for the old system. */
long size = ftell(this->curFile);
if (size > 0) this->OnDownloadProgress(this->curInfo, (int)-size);
fclose(this->curFile);
this->curFile = NULL;
this->curFile = nullptr;
}
}
void ClientNetworkContentSocketHandler::OnReceiveData(const char *data, size_t length)
{
assert(data == NULL || length != 0);
assert(data == nullptr || length != 0);
/* Ignore any latent data coming from a connection we closed. */
if (this->http_response_index == -2) return;
if (this->http_response_index == -1) {
if (data != NULL) {
if (data != nullptr) {
/* Append the rest of the response. */
memcpy(this->http_response.Append((uint)length), data, length);
this->http_response.insert(this->http_response.end(), data, data + length);
return;
} else {
/* Make sure the response is properly terminated. */
*this->http_response.Append() = '\0';
this->http_response.push_back('\0');
/* And prepare for receiving the rest of the data. */
this->http_response_index = 0;
}
}
if (data != NULL) {
if (data != nullptr) {
/* We have data, so write it to the file. */
if (fwrite(data, 1, length, this->curFile) != length) {
/* Writing failed somehow, let try via the old method. */
@@ -604,12 +598,12 @@ void ClientNetworkContentSocketHandler::OnReceiveData(const char *data, size_t l
return;
}
if (this->curFile != NULL) {
if (this->curFile != nullptr) {
/* We've finished downloading a file. */
this->AfterDownload();
}
if ((uint)this->http_response_index >= this->http_response.Length()) {
if ((uint)this->http_response_index >= this->http_response.size()) {
/* It's not a real failure, but if there's
* nothing more to download it helps with
* cleaning up the stuff we allocated. */
@@ -622,12 +616,12 @@ void ClientNetworkContentSocketHandler::OnReceiveData(const char *data, size_t l
this->curInfo = new ContentInfo;
/** Check p for not being null and return calling OnFailure if that's not the case. */
#define check_not_null(p) { if ((p) == NULL) { this->OnFailure(); return; } }
#define check_not_null(p) { if ((p) == nullptr) { this->OnFailure(); return; } }
/** Check p for not being null and then terminate, or return calling OnFailure. */
#define check_and_terminate(p) { check_not_null(p); *(p) = '\0'; }
for (;;) {
char *str = this->http_response.Begin() + this->http_response_index;
char *str = this->http_response.data() + this->http_response_index;
char *p = strchr(str, '\n');
check_and_terminate(p);
@@ -655,7 +649,7 @@ void ClientNetworkContentSocketHandler::OnReceiveData(const char *data, size_t l
str = p + 1;
/* Is it a fallback URL? If so, just continue with the next one. */
if (strncmp(str, "ottd", 4) == 0) {
if ((uint)this->http_response_index >= this->http_response.Length()) {
if ((uint)this->http_response_index >= this->http_response.size()) {
/* Have we gone through all lines? */
this->OnFailure();
return;
@@ -701,8 +695,8 @@ void ClientNetworkContentSocketHandler::OnReceiveData(const char *data, size_t l
ClientNetworkContentSocketHandler::ClientNetworkContentSocketHandler() :
NetworkContentSocketHandler(),
http_response_index(-2),
curFile(NULL),
curInfo(NULL),
curFile(nullptr),
curInfo(nullptr),
isConnecting(false),
lastActivity(_realtime_tick)
{
@@ -712,9 +706,9 @@ ClientNetworkContentSocketHandler::ClientNetworkContentSocketHandler() :
ClientNetworkContentSocketHandler::~ClientNetworkContentSocketHandler()
{
delete this->curInfo;
if (this->curFile != NULL) fclose(this->curFile);
if (this->curFile != nullptr) fclose(this->curFile);
for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) delete *iter;
for (ContentInfo *ci : this->infos) delete ci;
}
/** Connect to the content server. */
@@ -726,13 +720,13 @@ public:
*/
NetworkContentConnecter(const NetworkAddress &address) : TCPConnecter(address) {}
virtual void OnFailure()
void OnFailure() override
{
_network_content_client.isConnecting = false;
_network_content_client.OnConnect(false);
}
virtual void OnConnect(SOCKET s)
void OnConnect(SOCKET s) override
{
assert(_network_content_client.sock == INVALID_SOCKET);
_network_content_client.isConnecting = false;
@@ -780,7 +774,7 @@ void ClientNetworkContentSocketHandler::SendReceive()
if (this->CanSendReceive()) {
if (this->ReceivePackets()) {
/* Only update activity once a packet is received, instead of everytime we try it. */
/* Only update activity once a packet is received, instead of every time we try it. */
this->lastActivity = _realtime_tick;
}
}
@@ -795,25 +789,23 @@ void ClientNetworkContentSocketHandler::SendReceive()
void ClientNetworkContentSocketHandler::DownloadContentInfo(ContentID cid)
{
/* When we tried to download it already, don't try again */
if (this->requested.Contains(cid)) return;
if (std::find(this->requested.begin(), this->requested.end(), cid) != this->requested.end()) return;
*this->requested.Append() = cid;
assert(this->requested.Contains(cid));
this->requested.push_back(cid);
this->RequestContentList(1, &cid);
}
/**
* Get the content info based on a ContentID
* @param cid the ContentID to search for
* @return the ContentInfo or NULL if not found
* @return the ContentInfo or nullptr if not found
*/
ContentInfo *ClientNetworkContentSocketHandler::GetContent(ContentID cid)
{
for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) {
ContentInfo *ci = *iter;
for (ContentInfo *ci : this->infos) {
if (ci->id == cid) return ci;
}
return NULL;
return nullptr;
}
@@ -824,7 +816,7 @@ ContentInfo *ClientNetworkContentSocketHandler::GetContent(ContentID cid)
void ClientNetworkContentSocketHandler::Select(ContentID cid)
{
ContentInfo *ci = this->GetContent(cid);
if (ci == NULL || ci->state != ContentInfo::UNSELECTED) return;
if (ci == nullptr || ci->state != ContentInfo::UNSELECTED) return;
ci->state = ContentInfo::SELECTED;
this->CheckDependencyState(ci);
@@ -837,7 +829,7 @@ void ClientNetworkContentSocketHandler::Select(ContentID cid)
void ClientNetworkContentSocketHandler::Unselect(ContentID cid)
{
ContentInfo *ci = this->GetContent(cid);
if (ci == NULL || !ci->IsSelected()) return;
if (ci == nullptr || !ci->IsSelected()) return;
ci->state = ContentInfo::UNSELECTED;
this->CheckDependencyState(ci);
@@ -846,8 +838,7 @@ void ClientNetworkContentSocketHandler::Unselect(ContentID cid)
/** Select everything we can select */
void ClientNetworkContentSocketHandler::SelectAll()
{
for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) {
ContentInfo *ci = *iter;
for (ContentInfo *ci : this->infos) {
if (ci->state == ContentInfo::UNSELECTED) {
ci->state = ContentInfo::SELECTED;
this->CheckDependencyState(ci);
@@ -858,8 +849,7 @@ void ClientNetworkContentSocketHandler::SelectAll()
/** Select everything that's an update for something we've got */
void ClientNetworkContentSocketHandler::SelectUpgrade()
{
for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) {
ContentInfo *ci = *iter;
for (ContentInfo *ci : this->infos) {
if (ci->state == ContentInfo::UNSELECTED && ci->upgrade) {
ci->state = ContentInfo::SELECTED;
this->CheckDependencyState(ci);
@@ -870,8 +860,7 @@ void ClientNetworkContentSocketHandler::SelectUpgrade()
/** Unselect everything that we've not downloaded so far. */
void ClientNetworkContentSocketHandler::UnselectAll()
{
for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) {
ContentInfo *ci = *iter;
for (ContentInfo *ci : this->infos) {
if (ci->IsSelected() && ci->state != ContentInfo::ALREADY_HERE) ci->state = ContentInfo::UNSELECTED;
}
}
@@ -901,13 +890,12 @@ void ClientNetworkContentSocketHandler::ToggleSelectedState(const ContentInfo *c
*/
void ClientNetworkContentSocketHandler::ReverseLookupDependency(ConstContentVector &parents, const ContentInfo *child) const
{
for (ConstContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) {
const ContentInfo *ci = *iter;
for (const ContentInfo * const &ci : this->infos) {
if (ci == child) continue;
for (uint i = 0; i < ci->dependency_count; i++) {
if (ci->dependencies[i] == child->id) {
*parents.Append() = ci;
parents.push_back(ci);
break;
}
}
@@ -921,18 +909,18 @@ void ClientNetworkContentSocketHandler::ReverseLookupDependency(ConstContentVect
*/
void ClientNetworkContentSocketHandler::ReverseLookupTreeDependency(ConstContentVector &tree, const ContentInfo *child) const
{
*tree.Append() = child;
tree.push_back(child);
/* First find all direct parents. We can't use the "normal" iterator as
* we are including stuff into the vector and as such the vector's data
* store can be reallocated (and thus move), which means out iterating
* pointer gets invalid. So fall back to the indices. */
for (uint i = 0; i < tree.Length(); i++) {
for (uint i = 0; i < tree.size(); i++) {
ConstContentVector parents;
this->ReverseLookupDependency(parents, tree[i]);
for (ConstContentIterator piter = parents.Begin(); piter != parents.End(); piter++) {
tree.Include(*piter);
for (const ContentInfo *ci : parents) {
include(tree, ci);
}
}
}
@@ -949,7 +937,7 @@ void ClientNetworkContentSocketHandler::CheckDependencyState(ContentInfo *ci)
* selected and thus can unselect when a dependency is removed. */
for (uint i = 0; i < ci->dependency_count; i++) {
ContentInfo *c = this->GetContent(ci->dependencies[i]);
if (c == NULL) {
if (c == nullptr) {
this->DownloadContentInfo(ci->dependencies[i]);
} else if (c->state == ContentInfo::UNSELECTED) {
c->state = ContentInfo::AUTOSELECTED;
@@ -967,8 +955,7 @@ void ClientNetworkContentSocketHandler::CheckDependencyState(ContentInfo *ci)
* we automatically selected them. */
ConstContentVector parents;
this->ReverseLookupDependency(parents, ci);
for (ConstContentIterator iter = parents.Begin(); iter != parents.End(); iter++) {
const ContentInfo *c = *iter;
for (const ContentInfo *c : parents) {
if (!c->IsSelected()) continue;
this->Unselect(c->id);
@@ -976,22 +963,22 @@ void ClientNetworkContentSocketHandler::CheckDependencyState(ContentInfo *ci)
for (uint i = 0; i < ci->dependency_count; i++) {
const ContentInfo *c = this->GetContent(ci->dependencies[i]);
if (c == NULL) {
if (c == nullptr) {
DownloadContentInfo(ci->dependencies[i]);
continue;
}
if (c->state != ContentInfo::AUTOSELECTED) continue;
/* Only unselect when WE are the only parent. */
parents.Clear();
parents.clear();
this->ReverseLookupDependency(parents, c);
/* First check whether anything depends on us */
int sel_count = 0;
bool force_selection = false;
for (ConstContentIterator iter = parents.Begin(); iter != parents.End(); iter++) {
if ((*iter)->IsSelected()) sel_count++;
if ((*iter)->state == ContentInfo::SELECTED) force_selection = true;
for (const ContentInfo *ci : parents) {
if (ci->IsSelected()) sel_count++;
if (ci->state == ContentInfo::SELECTED) force_selection = true;
}
if (sel_count == 0) {
/* Nothing depends on us */
@@ -1002,12 +989,12 @@ void ClientNetworkContentSocketHandler::CheckDependencyState(ContentInfo *ci)
if (force_selection) continue;
/* "Flood" search to find all items in the dependency graph*/
parents.Clear();
parents.clear();
this->ReverseLookupTreeDependency(parents, c);
/* Is there anything that is "force" selected?, if so... we're done. */
for (ConstContentIterator iter = parents.Begin(); iter != parents.End(); iter++) {
if ((*iter)->state != ContentInfo::SELECTED) continue;
for (const ContentInfo *ci : parents) {
if (ci->state != ContentInfo::SELECTED) continue;
force_selection = true;
break;
@@ -1020,12 +1007,11 @@ void ClientNetworkContentSocketHandler::CheckDependencyState(ContentInfo *ci)
* After that's done run over them once again to test their children
* to unselect. Don't do it immediately because it'll do exactly what
* we're doing now. */
for (ConstContentIterator iter = parents.Begin(); iter != parents.End(); iter++) {
const ContentInfo *c = *iter;
for (const ContentInfo *c : parents) {
if (c->state == ContentInfo::AUTOSELECTED) this->Unselect(c->id);
}
for (ConstContentIterator iter = parents.Begin(); iter != parents.End(); iter++) {
this->CheckDependencyState(this->GetContent((*iter)->id));
for (const ContentInfo *c : parents) {
this->CheckDependencyState(this->GetContent(c->id));
}
}
}
@@ -1033,62 +1019,63 @@ void ClientNetworkContentSocketHandler::CheckDependencyState(ContentInfo *ci)
/** Clear all downloaded content information. */
void ClientNetworkContentSocketHandler::Clear()
{
for (ContentIterator iter = this->infos.Begin(); iter != this->infos.End(); iter++) delete *iter;
for (ContentInfo *c : this->infos) delete c;
this->infos.Clear();
this->requested.Clear();
this->infos.clear();
this->requested.clear();
}
/*** CALLBACK ***/
void ClientNetworkContentSocketHandler::OnConnect(bool success)
{
for (ContentCallback **iter = this->callbacks.Begin(); iter != this->callbacks.End(); /* nothing */) {
ContentCallback *cb = *iter;
for (size_t i = 0; i < this->callbacks.size(); /* nothing */) {
ContentCallback *cb = this->callbacks[i];
/* the callback may remove itself from this->callbacks */
cb->OnConnect(success);
if (iter != this->callbacks.End() && *iter == cb) iter++;
if (i != this->callbacks.size() && this->callbacks[i] == cb) i++;
}
}
void ClientNetworkContentSocketHandler::OnDisconnect()
{
for (ContentCallback **iter = this->callbacks.Begin(); iter != this->callbacks.End(); /* nothing */) {
ContentCallback *cb = *iter;
for (size_t i = 0; i < this->callbacks.size(); /* nothing */) {
ContentCallback *cb = this->callbacks[i];
cb->OnDisconnect();
if (iter != this->callbacks.End() && *iter == cb) iter++;
if (i != this->callbacks.size() && this->callbacks[i] == cb) i++;
}
}
void ClientNetworkContentSocketHandler::OnReceiveContentInfo(const ContentInfo *ci)
{
for (ContentCallback **iter = this->callbacks.Begin(); iter != this->callbacks.End(); /* nothing */) {
ContentCallback *cb = *iter;
for (size_t i = 0; i < this->callbacks.size(); /* nothing */) {
ContentCallback *cb = this->callbacks[i];
/* the callback may add items and/or remove itself from this->callbacks */
cb->OnReceiveContentInfo(ci);
if (iter != this->callbacks.End() && *iter == cb) iter++;
if (i != this->callbacks.size() && this->callbacks[i] == cb) i++;
}
}
void ClientNetworkContentSocketHandler::OnDownloadProgress(const ContentInfo *ci, int bytes)
{
for (ContentCallback **iter = this->callbacks.Begin(); iter != this->callbacks.End(); /* nothing */) {
ContentCallback *cb = *iter;
for (size_t i = 0; i < this->callbacks.size(); /* nothing */) {
ContentCallback *cb = this->callbacks[i];
cb->OnDownloadProgress(ci, bytes);
if (iter != this->callbacks.End() && *iter == cb) iter++;
if (i != this->callbacks.size() && this->callbacks[i] == cb) i++;
}
}
void ClientNetworkContentSocketHandler::OnDownloadComplete(ContentID cid)
{
ContentInfo *ci = this->GetContent(cid);
if (ci != NULL) {
if (ci != nullptr) {
ci->state = ContentInfo::ALREADY_HERE;
}
for (ContentCallback **iter = this->callbacks.Begin(); iter != this->callbacks.End(); /* nothing */) {
ContentCallback *cb = *iter;
for (size_t i = 0; i < this->callbacks.size(); /* nothing */) {
ContentCallback *cb = this->callbacks[i];
/* the callback may remove itself from this->callbacks */
cb->OnDownloadComplete(cid);
if (iter != this->callbacks.End() && *iter == cb) iter++;
if (i != this->callbacks.size() && this->callbacks[i] == cb) i++;
}
}
#endif /* ENABLE_NETWORK */
+25 -31
View File
@@ -15,12 +15,10 @@
#include "core/tcp_content.h"
#include "core/tcp_http.h"
#if defined(ENABLE_NETWORK)
/** Vector with content info */
typedef SmallVector<ContentInfo *, 16> ContentVector;
typedef std::vector<ContentInfo *> ContentVector;
/** Vector with constant content info */
typedef SmallVector<const ContentInfo *, 16> ConstContentVector;
typedef std::vector<const ContentInfo *> ConstContentVector;
/** Iterator for the content vector */
typedef ContentInfo **ContentIterator;
@@ -68,12 +66,12 @@ struct ContentCallback {
*/
class ClientNetworkContentSocketHandler : public NetworkContentSocketHandler, ContentCallback, HTTPCallback {
protected:
typedef SmallVector<ContentID, 4> ContentIDList; ///< List of content IDs to (possibly) select.
SmallVector<ContentCallback *, 2> callbacks; ///< Callbacks to notify "the world"
ContentIDList requested; ///< ContentIDs we already requested (so we don't do it again)
ContentVector infos; ///< All content info we received
SmallVector<char, 1024> http_response; ///< The HTTP response to the requests we've been doing
int http_response_index; ///< Where we are, in the response, with handling it
typedef std::vector<ContentID> ContentIDList; ///< List of content IDs to (possibly) select.
std::vector<ContentCallback *> callbacks; ///< Callbacks to notify "the world"
ContentIDList requested; ///< ContentIDs we already requested (so we don't do it again)
ContentVector infos; ///< All content info we received
std::vector<char> http_response; ///< The HTTP response to the requests we've been doing
int http_response_index; ///< Where we are, in the response, with handling it
FILE *curFile; ///< Currently downloaded file
ContentInfo *curInfo; ///< Information about the currently downloaded file
@@ -82,20 +80,20 @@ protected:
friend class NetworkContentConnecter;
virtual bool Receive_SERVER_INFO(Packet *p);
virtual bool Receive_SERVER_CONTENT(Packet *p);
bool Receive_SERVER_INFO(Packet *p) override;
bool Receive_SERVER_CONTENT(Packet *p) override;
ContentInfo *GetContent(ContentID cid);
void DownloadContentInfo(ContentID cid);
void OnConnect(bool success);
void OnDisconnect();
void OnReceiveContentInfo(const ContentInfo *ci);
void OnDownloadProgress(const ContentInfo *ci, int bytes);
void OnDownloadComplete(ContentID cid);
void OnConnect(bool success) override;
void OnDisconnect() override;
void OnReceiveContentInfo(const ContentInfo *ci) override;
void OnDownloadProgress(const ContentInfo *ci, int bytes) override;
void OnDownloadComplete(ContentID cid) override;
void OnFailure();
void OnReceiveData(const char *data, size_t length);
void OnFailure() override;
void OnReceiveData(const char *data, size_t length) override;
bool BeforeDownload();
void AfterDownload();
@@ -111,7 +109,7 @@ public:
void Connect();
void SendReceive();
void Close();
void Close() override;
void RequestContentList(ContentType type);
void RequestContentList(uint count, const ContentID *content_ids);
@@ -131,30 +129,26 @@ public:
void CheckDependencyState(ContentInfo *ci);
/** Get the number of content items we know locally. */
uint Length() const { return this->infos.Length(); }
uint Length() const { return (uint)this->infos.size(); }
/** Get the begin of the content inf iterator. */
ConstContentIterator Begin() const { return this->infos.Begin(); }
ConstContentIterator Begin() const { return this->infos.data(); }
/** Get the nth position of the content inf iterator. */
ConstContentIterator Get(uint32 index) const { return this->infos.Get(index); }
ConstContentIterator Get(uint32 index) const { return this->infos.data() + index; }
/** Get the end of the content inf iterator. */
ConstContentIterator End() const { return this->infos.End(); }
ConstContentIterator End() const { return this->Begin() + this->Length(); }
void Clear();
/** Add a callback to this class */
void AddCallback(ContentCallback *cb) { this->callbacks.Include(cb); }
void AddCallback(ContentCallback *cb) { include(this->callbacks, cb); }
/** Remove a callback */
void RemoveCallback(ContentCallback *cb) { this->callbacks.Erase(this->callbacks.Find(cb)); }
void RemoveCallback(ContentCallback *cb) { this->callbacks.erase(std::find(this->callbacks.begin(), this->callbacks.end(), cb)); }
};
extern ClientNetworkContentSocketHandler _network_content_client;
void ShowNetworkContentListWindow(ContentVector *cv = NULL, ContentType type1 = CONTENT_TYPE_END, ContentType type2 = CONTENT_TYPE_END);
void ShowNetworkContentListWindow(ContentVector *cv = nullptr, ContentType type1 = CONTENT_TYPE_END, ContentType type2 = CONTENT_TYPE_END);
void ShowMissingContentWindow(const struct GRFConfig *list);
#else
static inline void ShowNetworkContentListWindow() {}
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CONTENT_H */
+79 -86
View File
@@ -9,7 +9,6 @@
/** @file network_content_gui.cpp Implementation of the Network Content related GUIs. */
#if defined(ENABLE_NETWORK)
#include "../stdafx.h"
#include "../strings_func.h"
#include "../gfx_func.h"
@@ -65,7 +64,7 @@ struct ContentTextfileWindow : public TextfileWindow {
}
}
/* virtual */ void SetStringParameters(int widget) const
void SetStringParameters(int widget) const override
{
if (widget == WID_TF_CAPTION) {
SetDParam(0, this->GetTypeString());
@@ -96,7 +95,7 @@ static const NWidgetPart _nested_network_content_download_status_window_widgets[
/** Window description for the download window */
static WindowDesc _network_content_download_status_window_desc(
WDP_CENTER, NULL, 0, 0,
WDP_CENTER, nullptr, 0, 0,
WC_NETWORK_STATUS_WINDOW, WC_NONE,
WDF_MODAL,
_nested_network_content_download_status_window_widgets, lengthof(_nested_network_content_download_status_window_widgets)
@@ -116,7 +115,7 @@ BaseNetworkContentDownloadStatusWindow::~BaseNetworkContentDownloadStatusWindow(
_network_content_client.RemoveCallback(this);
}
/* virtual */ void BaseNetworkContentDownloadStatusWindow::DrawWidget(const Rect &r, int widget) const
void BaseNetworkContentDownloadStatusWindow::DrawWidget(const Rect &r, int widget) const
{
if (widget != WID_NCDS_BACKGROUND) return;
@@ -145,7 +144,7 @@ BaseNetworkContentDownloadStatusWindow::~BaseNetworkContentDownloadStatusWindow(
DrawStringMultiLine(r.left + 2, r.right - 2, y, y + FONT_HEIGHT_NORMAL * 2, str, TC_FROMSTRING, SA_CENTER);
}
/* virtual */ void BaseNetworkContentDownloadStatusWindow::OnDownloadProgress(const ContentInfo *ci, int bytes)
void BaseNetworkContentDownloadStatusWindow::OnDownloadProgress(const ContentInfo *ci, int bytes)
{
if (ci->id != this->cur_id) {
strecpy(this->name, ci->filename, lastof(this->name));
@@ -161,7 +160,7 @@ BaseNetworkContentDownloadStatusWindow::~BaseNetworkContentDownloadStatusWindow(
/** Window for showing the download status of content */
struct NetworkContentDownloadStatusWindow : public BaseNetworkContentDownloadStatusWindow {
private:
SmallVector<ContentType, 4> receivedTypes; ///< Types we received so we can update their cache
std::vector<ContentType> receivedTypes; ///< Types we received so we can update their cache
public:
/**
@@ -177,8 +176,8 @@ public:
~NetworkContentDownloadStatusWindow()
{
TarScanner::Mode mode = TarScanner::NONE;
for (ContentType *iter = this->receivedTypes.Begin(); iter != this->receivedTypes.End(); iter++) {
switch (*iter) {
for (auto ctype : this->receivedTypes) {
switch (ctype) {
case CONTENT_TYPE_AI:
case CONTENT_TYPE_AI_LIBRARY:
/* AI::Rescan calls the scanner. */
@@ -211,8 +210,8 @@ public:
TarScanner::DoScan(mode);
/* Tell all the backends about what we've downloaded */
for (ContentType *iter = this->receivedTypes.Begin(); iter != this->receivedTypes.End(); iter++) {
switch (*iter) {
for (auto ctype : this->receivedTypes) {
switch (ctype) {
case CONTENT_TYPE_AI:
case CONTENT_TYPE_AI_LIBRARY:
AI::Rescan();
@@ -239,7 +238,7 @@ public:
break;
case CONTENT_TYPE_NEWGRF:
ScanNewGRFFiles(NULL);
ScanNewGRFFiles(nullptr);
break;
case CONTENT_TYPE_SCENARIO:
@@ -258,7 +257,7 @@ public:
InvalidateWindowData(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_CONTENT_LIST, 2);
}
virtual void OnClick(Point pt, int widget, int click_count)
void OnClick(Point pt, int widget, int click_count) override
{
if (widget == WID_NCDS_CANCELOK) {
if (this->downloaded_bytes != this->total_bytes) {
@@ -272,10 +271,10 @@ public:
}
}
virtual void OnDownloadProgress(const ContentInfo *ci, int bytes)
void OnDownloadProgress(const ContentInfo *ci, int bytes) override
{
BaseNetworkContentDownloadStatusWindow::OnDownloadProgress(ci, bytes);
this->receivedTypes.Include(ci->type);
include(this->receivedTypes, ci->type);
/* When downloading is finished change cancel in ok */
if (this->downloaded_bytes == this->total_bytes) {
@@ -290,7 +289,7 @@ struct ContentListFilterData {
std::bitset<CONTENT_TYPE_END> types; ///< Content types displayed
};
/** Filter criterias for NetworkContentListWindow. */
/** Filter criteria for NetworkContentListWindow. */
enum ContentListFilterCriteria {
CONTENT_FILTER_TEXT = 0, ///< Filter by query sting
CONTENT_FILTER_TYPE_OR_SELECTED,///< Filter by being of displayed type or selected for download
@@ -334,8 +333,7 @@ class NetworkContentListWindow : public Window, ContentCallback {
pos = strecpy(pos, "do=searchgrfid&q=", last);
bool first = true;
for (ConstContentIterator iter = this->content.Begin(); iter != this->content.End(); iter++) {
const ContentInfo *ci = *iter;
for (const ContentInfo *ci : this->content) {
if (ci->state != ContentInfo::DOES_NOT_EXIST) continue;
if (!first) pos = strecpy(pos, ",", last);
@@ -386,49 +384,49 @@ class NetworkContentListWindow : public Window, ContentCallback {
if (!this->content.NeedRebuild()) return;
/* Create temporary array of games to use for listing */
this->content.Clear();
this->content.clear();
bool all_available = true;
for (ConstContentIterator iter = _network_content_client.Begin(); iter != _network_content_client.End(); iter++) {
if ((*iter)->state == ContentInfo::DOES_NOT_EXIST) all_available = false;
*this->content.Append() = *iter;
this->content.push_back(*iter);
}
this->SetWidgetDisabledState(WID_NCL_SEARCH_EXTERNAL, this->auto_select && all_available);
this->FilterContentList();
this->content.Compact();
this->content.shrink_to_fit();
this->content.RebuildDone();
this->SortContentList();
this->vscroll->SetCount(this->content.Length()); // Update the scrollbar
this->vscroll->SetCount((int)this->content.size()); // Update the scrollbar
this->ScrollToSelected();
}
/** Sort content by name. */
static int CDECL NameSorter(const ContentInfo * const *a, const ContentInfo * const *b)
static bool NameSorter(const ContentInfo * const &a, const ContentInfo * const &b)
{
return strnatcmp((*a)->name, (*b)->name, true); // Sort by name (natural sorting).
return strnatcmp(a->name, b->name, true) < 0; // Sort by name (natural sorting).
}
/** Sort content by type. */
static int CDECL TypeSorter(const ContentInfo * const *a, const ContentInfo * const *b)
static bool TypeSorter(const ContentInfo * const &a, const ContentInfo * const &b)
{
int r = 0;
if ((*a)->type != (*b)->type) {
r = strnatcmp(content_type_strs[(*a)->type], content_type_strs[(*b)->type]);
if (a->type != b->type) {
r = strnatcmp(content_type_strs[a->type], content_type_strs[b->type]);
}
if (r == 0) r = NameSorter(a, b);
return r;
if (r == 0) return NameSorter(a, b);
return r < 0;
}
/** Sort content by state. */
static int CDECL StateSorter(const ContentInfo * const *a, const ContentInfo * const *b)
static bool StateSorter(const ContentInfo * const &a, const ContentInfo * const &b)
{
int r = (*a)->state - (*b)->state;
if (r == 0) r = TypeSorter(a, b);
return r;
int r = a->state - b->state;
if (r == 0) return TypeSorter(a, b);
return r < 0;
}
/** Sort the content list */
@@ -436,12 +434,8 @@ class NetworkContentListWindow : public Window, ContentCallback {
{
if (!this->content.Sort()) return;
for (ConstContentIterator iter = this->content.Begin(); iter != this->content.End(); iter++) {
if (*iter == this->selected) {
this->list_pos = iter - this->content.Begin();
break;
}
}
int idx = find_index(this->content, this->selected);
if (idx >= 0) this->list_pos = idx;
}
/** Filter content by tags/name */
@@ -479,15 +473,14 @@ class NetworkContentListWindow : public Window, ContentCallback {
if (!changed) return;
/* update list position */
for (ConstContentIterator iter = this->content.Begin(); iter != this->content.End(); iter++) {
if (*iter == this->selected) {
this->list_pos = iter - this->content.Begin();
return;
}
int idx = find_index(this->content, this->selected);
if (idx >= 0) {
this->list_pos = idx;
return;
}
/* previously selected item not in list anymore */
this->selected = NULL;
this->selected = nullptr;
this->list_pos = 0;
}
@@ -508,7 +501,7 @@ class NetworkContentListWindow : public Window, ContentCallback {
/** Make sure that the currently selected content info is within the visible part of the matrix */
void ScrollToSelected()
{
if (this->selected == NULL) return;
if (this->selected == nullptr) return;
this->vscroll->ScrollTowards(this->list_pos);
}
@@ -528,7 +521,7 @@ public:
Window(desc),
auto_select(select_all),
filter_editbox(EDITBOX_MAX_SIZE),
selected(NULL),
selected(nullptr),
list_pos(0)
{
this->checkbox_size = maxdim(maxdim(GetSpriteSize(SPR_BOX_EMPTY), GetSpriteSize(SPR_BOX_CHECKED)), GetSpriteSize(SPR_BLOT));
@@ -563,7 +556,7 @@ public:
_network_content_client.RemoveCallback(this);
}
virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
{
switch (widget) {
case WID_NCL_FILTER_CAPT:
@@ -591,7 +584,7 @@ public:
}
virtual void DrawWidget(const Rect &r, int widget) const
void DrawWidget(const Rect &r, int widget) const override
{
switch (widget) {
case WID_NCL_FILTER_CAPT:
@@ -608,7 +601,7 @@ public:
}
}
virtual void OnPaint()
void OnPaint() override
{
const SortButtonState arrow = this->content.IsDescSortOrder() ? SBS_DOWN : SBS_UP;
@@ -641,8 +634,12 @@ public:
int sprite_y_offset = WD_MATRIX_TOP + (line_height - this->checkbox_size.height) / 2 - 1;
int text_y_offset = WD_MATRIX_TOP + (line_height - FONT_HEIGHT_NORMAL) / 2;
uint y = r.top;
int cnt = 0;
for (ConstContentIterator iter = this->content.Get(this->vscroll->GetPosition()); iter != this->content.End() && cnt < this->vscroll->GetCapacity(); iter++, cnt++) {
auto iter = this->content.begin() + this->vscroll->GetPosition();
size_t last = this->vscroll->GetPosition() + this->vscroll->GetCapacity();
auto end = (last < this->content.size()) ? this->content.begin() + last : this->content.end();
for (/**/; iter != end; iter++) {
const ContentInfo *ci = *iter;
if (ci == this->selected) GfxFillRect(r.left + 1, y + 1, r.right - 1, y + this->resize.step_height - 1, PC_GREY);
@@ -688,7 +685,7 @@ public:
SetDParam(0, this->filesize_sum);
DrawString(r.left + DETAIL_LEFT, r.right - DETAIL_RIGHT, r.bottom - FONT_HEIGHT_NORMAL - WD_PAR_VSEP_NORMAL, STR_CONTENT_TOTAL_DOWNLOAD_SIZE);
if (this->selected == NULL) return;
if (this->selected == nullptr) return;
/* And fill the rest of the details when there's information to place there */
DrawStringMultiLine(r.left + WD_INSET_LEFT, r.right - WD_INSET_RIGHT, r.top + DETAIL_TITLE_HEIGHT / 2, r.top + DETAIL_TITLE_HEIGHT, STR_CONTENT_DETAIL_SUBTITLE_UNSELECTED + this->selected->state, TC_FROMSTRING, SA_CENTER);
@@ -767,8 +764,7 @@ public:
char buf[DRAW_STRING_BUFFER] = "";
char *p = buf;
for (ConstContentIterator iter = tree.Begin(); iter != tree.End(); iter++) {
const ContentInfo *ci = *iter;
for (const ContentInfo *ci : tree) {
if (ci == this->selected || ci->state != ContentInfo::SELECTED) continue;
p += seprintf(p, lastof(buf), buf == p ? "%s" : ", %s", ci->name);
@@ -780,10 +776,10 @@ public:
}
}
virtual void OnClick(Point pt, int widget, int click_count)
void OnClick(Point pt, int widget, int click_count) override
{
if (widget >= WID_NCL_TEXTFILE && widget < WID_NCL_TEXTFILE + TFT_END) {
if (this->selected == NULL || this->selected->state != ContentInfo::ALREADY_HERE) return;
if (this->selected == nullptr || this->selected->state != ContentInfo::ALREADY_HERE) return;
ShowContentTextfileWindow((TextfileType)(widget - WID_NCL_TEXTFILE), this->selected);
return;
@@ -792,9 +788,9 @@ public:
switch (widget) {
case WID_NCL_MATRIX: {
uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NCL_MATRIX);
if (id_v >= this->content.Length()) return; // click out of bounds
if (id_v >= this->content.size()) return; // click out of bounds
this->selected = *this->content.Get(id_v);
this->selected = this->content[id_v];
this->list_pos = id_v;
const NWidgetBase *checkbox = this->GetWidget<NWidgetBase>(WID_NCL_CHECKBOX);
@@ -816,7 +812,7 @@ public:
case WID_NCL_NAME:
if (this->content.SortType() == widget - WID_NCL_CHECKBOX) {
this->content.ToggleSortOrder();
if (this->content.Length() > 0) this->list_pos = this->content.Length() - this->list_pos - 1;
if (this->content.size() > 0) this->list_pos = (int)this->content.size() - this->list_pos - 1;
} else {
this->content.SetSortType(widget - WID_NCL_CHECKBOX);
this->content.ForceResort();
@@ -846,14 +842,14 @@ public:
break;
case WID_NCL_OPEN_URL:
if (this->selected != NULL) {
if (this->selected != nullptr) {
extern void OpenBrowser(const char *url);
OpenBrowser(this->selected->url);
}
break;
case WID_NCL_DOWNLOAD:
if (BringWindowToFrontById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_CONTENT_DOWNLOAD) == NULL) new NetworkContentDownloadStatusWindow();
if (BringWindowToFrontById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_CONTENT_DOWNLOAD) == nullptr) new NetworkContentDownloadStatusWindow();
break;
case WID_NCL_SEARCH_EXTERNAL:
@@ -866,7 +862,7 @@ public:
}
}
virtual EventState OnKeyPress(WChar key, uint16 keycode)
EventState OnKeyPress(WChar key, uint16 keycode) override
{
switch (keycode) {
case WKC_UP:
@@ -875,7 +871,7 @@ public:
break;
case WKC_DOWN:
/* scroll down by one */
if (this->list_pos < (int)this->content.Length() - 1) this->list_pos++;
if (this->list_pos < (int)this->content.size() - 1) this->list_pos++;
break;
case WKC_PAGEUP:
/* scroll up a page */
@@ -883,7 +879,7 @@ public:
break;
case WKC_PAGEDOWN:
/* scroll down a page */
this->list_pos = min(this->list_pos + this->vscroll->GetCapacity(), (int)this->content.Length() - 1);
this->list_pos = min(this->list_pos + this->vscroll->GetCapacity(), (int)this->content.size() - 1);
break;
case WKC_HOME:
/* jump to beginning */
@@ -891,13 +887,13 @@ public:
break;
case WKC_END:
/* jump to end */
this->list_pos = this->content.Length() - 1;
this->list_pos = (int)this->content.size() - 1;
break;
case WKC_SPACE:
case WKC_RETURN:
if (keycode == WKC_RETURN || !IsWidgetFocused(WID_NCL_FILTER)) {
if (this->selected != NULL) {
if (this->selected != nullptr) {
_network_content_client.ToggleSelectedState(this->selected);
this->content.ForceResort();
this->InvalidateData();
@@ -915,7 +911,7 @@ public:
return ES_NOT_HANDLED;
}
if (this->content.Length() == 0) {
if (this->content.size() == 0) {
this->list_pos = 0; // above stuff may result in "-1".
if (this->UpdateFilterState()) {
this->content.ForceRebuild();
@@ -924,7 +920,7 @@ public:
return ES_HANDLED;
}
this->selected = *this->content.Get(this->list_pos);
this->selected = this->content[this->list_pos];
if (this->UpdateFilterState()) {
this->content.ForceRebuild();
@@ -938,7 +934,7 @@ public:
return ES_HANDLED;
}
virtual void OnEditboxChanged(int wid)
void OnEditboxChanged(int wid) override
{
if (wid == WID_NCL_FILTER) {
this->filter_data.string_filter.SetFilterTerm(this->filter_editbox.text.buf);
@@ -948,25 +944,25 @@ public:
}
}
virtual void OnResize()
void OnResize() override
{
this->vscroll->SetCapacityFromWidget(this, WID_NCL_MATRIX);
}
virtual void OnReceiveContentInfo(const ContentInfo *rci)
void OnReceiveContentInfo(const ContentInfo *rci) override
{
if (this->auto_select && !rci->IsSelected()) _network_content_client.ToggleSelectedState(rci);
this->content.ForceRebuild();
this->InvalidateData();
}
virtual void OnDownloadComplete(ContentID cid)
void OnDownloadComplete(ContentID cid) override
{
this->content.ForceResort();
this->InvalidateData();
}
virtual void OnConnect(bool success)
void OnConnect(bool success) override
{
if (!success) {
ShowErrorMessage(STR_CONTENT_ERROR_COULD_NOT_CONNECT, INVALID_STRING_ID, WL_ERROR);
@@ -982,7 +978,7 @@ public:
* @param data Information about the changed data.
* @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
*/
virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
void OnInvalidateData(int data = 0, bool gui_scope = true) override
{
if (!gui_scope) return;
if (this->content.NeedRebuild()) this->BuildContentList();
@@ -991,8 +987,7 @@ public:
this->filesize_sum = 0;
bool show_select_all = false;
bool show_select_upgrade = false;
for (ConstContentIterator iter = this->content.Begin(); iter != this->content.End(); iter++) {
const ContentInfo *ci = *iter;
for (const ContentInfo *ci : this->content) {
switch (ci->state) {
case ContentInfo::SELECTED:
case ContentInfo::AUTOSELECTED:
@@ -1010,13 +1005,13 @@ public:
}
/* If data == 2 then the status window caused this OnInvalidate */
this->SetWidgetDisabledState(WID_NCL_DOWNLOAD, this->filesize_sum == 0 || (FindWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_CONTENT_DOWNLOAD) != NULL && data != 2));
this->SetWidgetDisabledState(WID_NCL_DOWNLOAD, this->filesize_sum == 0 || (FindWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_CONTENT_DOWNLOAD) != nullptr && data != 2));
this->SetWidgetDisabledState(WID_NCL_UNSELECT, this->filesize_sum == 0);
this->SetWidgetDisabledState(WID_NCL_SELECT_ALL, !show_select_all);
this->SetWidgetDisabledState(WID_NCL_SELECT_UPDATE, !show_select_upgrade);
this->SetWidgetDisabledState(WID_NCL_OPEN_URL, this->selected == NULL || StrEmpty(this->selected->url));
this->SetWidgetDisabledState(WID_NCL_OPEN_URL, this->selected == nullptr || StrEmpty(this->selected->url));
for (TextfileType tft = TFT_BEGIN; tft < TFT_END; tft++) {
this->SetWidgetDisabledState(WID_NCL_TEXTFILE + tft, this->selected == NULL || this->selected->state != ContentInfo::ALREADY_HERE || this->selected->GetTextfile(tft) == NULL);
this->SetWidgetDisabledState(WID_NCL_TEXTFILE + tft, this->selected == nullptr || this->selected->state != ContentInfo::ALREADY_HERE || this->selected->GetTextfile(tft) == nullptr);
}
this->GetWidget<NWidgetCore>(WID_NCL_CANCEL)->widget_data = this->filesize_sum == 0 ? STR_AI_SETTINGS_CLOSE : STR_AI_LIST_CANCEL;
@@ -1136,7 +1131,7 @@ static WindowDesc _network_content_list_desc(
/**
* Show the content list window with a given set of content
* @param cv the content to show, or NULL when it has to search for itself
* @param cv the content to show, or nullptr when it has to search for itself
* @param type1 the first type to (only) show or #CONTENT_TYPE_END to show all.
* @param type2 the second type to (only) show in addition to type1. If type2 is != #CONTENT_TYPE_END, then also type1 should be != #CONTENT_TYPE_END.
* If type2 != #CONTENT_TYPE_END, then type1 != type2 must be true.
@@ -1146,7 +1141,7 @@ void ShowNetworkContentListWindow(ContentVector *cv, ContentType type1, ContentT
#if defined(WITH_ZLIB)
std::bitset<CONTENT_TYPE_END> types;
_network_content_client.Clear();
if (cv == NULL) {
if (cv == nullptr) {
assert(type1 != CONTENT_TYPE_END || type2 == CONTENT_TYPE_END);
assert(type1 == CONTENT_TYPE_END || type1 != type2);
_network_content_client.RequestContentList(type1);
@@ -1159,14 +1154,12 @@ void ShowNetworkContentListWindow(ContentVector *cv, ContentType type1, ContentT
}
DeleteWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_CONTENT_LIST);
new NetworkContentListWindow(&_network_content_list_desc, cv != NULL, types);
new NetworkContentListWindow(&_network_content_list_desc, cv != nullptr, types);
#else
ShowErrorMessage(STR_CONTENT_NO_ZLIB, STR_CONTENT_NO_ZLIB_SUB, WL_ERROR);
/* Connection failed... clean up the mess */
if (cv != NULL) {
for (ContentIterator iter = cv->Begin(); iter != cv->End(); iter++) delete *iter;
if (cv != nullptr) {
for (ContentInfo *ci : *cv) delete ci;
}
#endif /* WITH_ZLIB */
}
#endif /* ENABLE_NETWORK */
+2 -2
View File
@@ -39,8 +39,8 @@ public:
*/
~BaseNetworkContentDownloadStatusWindow();
virtual void DrawWidget(const Rect &r, int widget) const;
virtual void OnDownloadProgress(const ContentInfo *ci, int bytes);
void DrawWidget(const Rect &r, int widget) const override;
void OnDownloadProgress(const ContentInfo *ci, int bytes) override;
};
void BuildContentTypeStringList();
+1 -4
View File
@@ -26,8 +26,6 @@
#include "../openttd.h"
#include "../company_type.h"
#ifdef ENABLE_NETWORK
extern NetworkServerGameInfo _network_game_info;
extern NetworkCompanyState *_network_company_states;
@@ -53,7 +51,7 @@ void NetworkPopulateCompanyStats(NetworkCompanyStats *stats);
void NetworkUpdateClientInfo(ClientID client_id);
void NetworkClientsToSpectators(CompanyID cid);
void NetworkClientConnectGame(NetworkAddress address, CompanyID join_as, const char *join_server_password = NULL, const char *join_company_password = NULL);
void NetworkClientConnectGame(NetworkAddress address, CompanyID join_as, const char *join_server_password = nullptr, const char *join_company_password = nullptr);
void NetworkClientRequestMove(CompanyID company, const char *pass = "");
void NetworkClientSendRcon(const char *password, const char *command);
void NetworkClientSendChat(NetworkAction action, DestType type, int dest, const char *msg, int64 data = 0);
@@ -90,5 +88,4 @@ void NetworkChatMessageLoop();
void NetworkAfterNewGRFScan();
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_FUNC_H */
+23 -32
View File
@@ -12,24 +12,20 @@
* Also, it handles the request to a server for data about the server
*/
#ifdef ENABLE_NETWORK
#include "../stdafx.h"
#include "../debug.h"
#include "../window_func.h"
#include "../thread/thread.h"
#include "network_internal.h"
#include "network_udp.h"
#include "network_gamelist.h"
#include <atomic>
#include "../safeguards.h"
NetworkGameList *_network_game_list = NULL;
NetworkGameList *_network_game_list = nullptr;
/** Mutex for handling delayed insertion/querying of servers. */
static ThreadMutex *_network_game_list_mutex = ThreadMutex::New();
/** The games to insert when the GUI thread has time for us. */
static NetworkGameList *_network_game_delayed_insertion_list = NULL;
static std::atomic<NetworkGameList *> _network_game_delayed_insertion_list(nullptr);
/**
* Add a new item to the linked gamelist, but do it delayed in the next tick
@@ -38,23 +34,21 @@ static NetworkGameList *_network_game_delayed_insertion_list = NULL;
*/
void NetworkGameListAddItemDelayed(NetworkGameList *item)
{
_network_game_list_mutex->BeginCritical();
item->next = _network_game_delayed_insertion_list;
_network_game_delayed_insertion_list = item;
_network_game_list_mutex->EndCritical();
item->next = _network_game_delayed_insertion_list.load(std::memory_order_relaxed);
while (!_network_game_delayed_insertion_list.compare_exchange_weak(item->next, item, std::memory_order_acq_rel)) {}
}
/** Perform the delayed (thread safe) insertion into the game list */
static void NetworkGameListHandleDelayedInsert()
{
_network_game_list_mutex->BeginCritical();
while (_network_game_delayed_insertion_list != NULL) {
NetworkGameList *ins_item = _network_game_delayed_insertion_list;
_network_game_delayed_insertion_list = ins_item->next;
while (true) {
NetworkGameList *ins_item = _network_game_delayed_insertion_list.load(std::memory_order_relaxed);
while (ins_item != nullptr && !_network_game_delayed_insertion_list.compare_exchange_weak(ins_item, ins_item->next, std::memory_order_acq_rel)) {}
if (ins_item == nullptr) break; // No item left.
NetworkGameList *item = NetworkGameListAddItem(ins_item->address);
if (item != NULL) {
if (item != nullptr) {
if (StrEmpty(item->info.server_name)) {
ClearGRFConfigList(&item->info.grfconfig);
memset(&item->info, 0, sizeof(item->info));
@@ -68,7 +62,6 @@ static void NetworkGameListHandleDelayedInsert()
}
free(ins_item);
}
_network_game_list_mutex->EndCritical();
}
/**
@@ -85,22 +78,22 @@ NetworkGameList *NetworkGameListAddItem(NetworkAddress address)
if (StrEmpty(hostname) ||
strcmp(hostname, "0.0.0.0") == 0 ||
strcmp(hostname, "::") == 0) {
return NULL;
return nullptr;
}
NetworkGameList *item, *prev_item;
prev_item = NULL;
for (item = _network_game_list; item != NULL; item = item->next) {
prev_item = nullptr;
for (item = _network_game_list; item != nullptr; item = item->next) {
if (item->address == address) return item;
prev_item = item;
}
item = CallocT<NetworkGameList>(1);
item->next = NULL;
item->next = nullptr;
item->address = address;
if (prev_item == NULL) {
if (prev_item == nullptr) {
_network_game_list = item;
} else {
prev_item->next = item;
@@ -118,10 +111,10 @@ NetworkGameList *NetworkGameListAddItem(NetworkAddress address)
*/
void NetworkGameListRemoveItem(NetworkGameList *remove)
{
NetworkGameList *prev_item = NULL;
for (NetworkGameList *item = _network_game_list; item != NULL; item = item->next) {
NetworkGameList *prev_item = nullptr;
for (NetworkGameList *item = _network_game_list; item != nullptr; item = item->next) {
if (remove == item) {
if (prev_item == NULL) {
if (prev_item == nullptr) {
_network_game_list = remove->next;
} else {
prev_item->next = remove->next;
@@ -130,7 +123,7 @@ void NetworkGameListRemoveItem(NetworkGameList *remove)
/* Remove GRFConfig information */
ClearGRFConfigList(&remove->info.grfconfig);
free(remove);
remove = NULL;
remove = nullptr;
DEBUG(net, 4, "[gamelist] removed server from list");
NetworkRebuildHostList();
@@ -155,7 +148,7 @@ void NetworkGameListRequery()
if (++requery_cnt < REQUERY_EVERY_X_GAMELOOPS) return;
requery_cnt = 0;
for (NetworkGameList *item = _network_game_list; item != NULL; item = item->next) {
for (NetworkGameList *item = _network_game_list; item != nullptr; item = item->next) {
item->retries++;
if (item->retries < REFRESH_GAMEINFO_X_REQUERIES && (item->online || item->retries >= MAX_GAME_LIST_REQUERY_COUNT)) continue;
@@ -172,15 +165,15 @@ void NetworkGameListRequery()
*/
void NetworkAfterNewGRFScan()
{
for (NetworkGameList *item = _network_game_list; item != NULL; item = item->next) {
for (NetworkGameList *item = _network_game_list; item != nullptr; item = item->next) {
/* Reset compatibility state */
item->info.compatible = item->info.version_compatible;
for (GRFConfig *c = item->info.grfconfig; c != NULL; c = c->next) {
for (GRFConfig *c = item->info.grfconfig; c != nullptr; c = c->next) {
assert(HasBit(c->flags, GCF_COPY));
const GRFConfig *f = FindGRFConfig(c->ident.grfid, FGCM_EXACT, c->ident.md5sum);
if (f == NULL) {
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. */
@@ -206,5 +199,3 @@ void NetworkAfterNewGRFScan()
InvalidateWindowClassesData(WC_NETWORK_WINDOW);
}
#endif /* ENABLE_NETWORK */
+170 -145
View File
@@ -9,7 +9,6 @@
/** @file network_gui.cpp Implementation of the Network related GUIs. */
#ifdef ENABLE_NETWORK
#include "../stdafx.h"
#include "../strings_func.h"
#include "../date_func.h"
@@ -64,18 +63,18 @@ static const StringID _lan_internet_types_dropdown[] = {
INVALID_STRING_ID
};
static StringID _language_dropdown[NETLANG_COUNT + 1] = {STR_NULL};
static std::vector<StringID> _language_dropdown;
void SortNetworkLanguages()
{
/* Init the strings */
if (_language_dropdown[0] == STR_NULL) {
for (int i = 0; i < NETLANG_COUNT; i++) _language_dropdown[i] = STR_NETWORK_LANG_ANY + i;
_language_dropdown[NETLANG_COUNT] = INVALID_STRING_ID;
if (_language_dropdown.empty()) {
for (int i = 0; i < NETLANG_COUNT; i++) _language_dropdown.emplace_back(STR_NETWORK_LANG_ANY + i);
_language_dropdown.emplace_back(INVALID_STRING_ID);
}
/* Sort the strings (we don't move 'any' and the 'invalid' one) */
QSortT(_language_dropdown + 1, NETLANG_COUNT - 1, &StringIDSorter);
std::sort(_language_dropdown.begin() + 1, _language_dropdown.end() - 1, StringIDSorter);
}
/**
@@ -118,7 +117,7 @@ public:
*lastof(this->visible) = true;
}
void SetupSmallestSize(Window *w, bool init_array)
void SetupSmallestSize(Window *w, bool init_array) override
{
/* Oh yeah, we ought to be findable! */
w->nested_array[WID_NG_HEADER] = this;
@@ -130,13 +129,13 @@ public:
this->resize_y = 0; // We never resize in this direction
/* First initialise some variables... */
for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
child_wid->SetupSmallestSize(w, init_array);
this->smallest_y = max(this->smallest_y, child_wid->smallest_y + child_wid->padding_top + child_wid->padding_bottom);
}
/* ... then in a second pass make sure the 'current' sizes are set. Won't change for most widgets. */
for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
child_wid->current_x = child_wid->smallest_x;
child_wid->current_y = this->smallest_y;
}
@@ -144,7 +143,7 @@ public:
this->smallest_x = this->head->smallest_x + this->tail->smallest_x; // First and last are always shown, rest not
}
void AssignSizePosition(SizingType sizing, uint x, uint y, uint given_width, uint given_height, bool rtl)
void AssignSizePosition(SizingType sizing, uint x, uint y, uint given_width, uint given_height, bool rtl) override
{
assert(given_width >= this->smallest_x && given_height >= this->smallest_y);
@@ -173,7 +172,7 @@ public:
uint position = 0; // Place to put next child relative to origin of the container.
uint i = rtl ? lengthof(this->visible) - 1 : 0;
child_wid = rtl ? this->tail : this->head;
while (child_wid != NULL) {
while (child_wid != nullptr) {
if (this->visible[i]) {
child_wid->AssignSizePosition(sizing, x + position, y, child_wid->current_x, this->current_y, rtl);
position += child_wid->current_x;
@@ -184,27 +183,27 @@ public:
}
}
/* virtual */ void Draw(const Window *w)
void Draw(const Window *w) override
{
int i = 0;
for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
if (!this->visible[i++]) continue;
child_wid->Draw(w);
}
}
/* virtual */ NWidgetCore *GetWidgetFromPos(int x, int y)
NWidgetCore *GetWidgetFromPos(int x, int y) override
{
if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return NULL;
if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return nullptr;
int i = 0;
for (NWidgetBase *child_wid = this->head; child_wid != NULL; child_wid = child_wid->next) {
for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
if (!this->visible[i++]) continue;
NWidgetCore *nwid = child_wid->GetWidgetFromPos(x, y);
if (nwid != NULL) return nwid;
if (nwid != nullptr) return nwid;
}
return NULL;
return nullptr;
}
/**
@@ -239,7 +238,7 @@ protected:
int lock_offset; ///< Left offset for lock icon.
int blot_offset; ///< Left offset for green/yellow/red compatibility icon.
int flag_offset; ///< Left offset for langauge flag icon.
int flag_offset; ///< Left offset for language flag icon.
/**
* (Re)build the GUI network game list (a.k.a. this->servers) as some
@@ -251,10 +250,10 @@ protected:
if (!this->servers.NeedRebuild()) return;
/* Create temporary array of games to use for listing */
this->servers.Clear();
this->servers.clear();
for (NetworkGameList *ngl = _network_game_list; ngl != NULL; ngl = ngl->next) {
*this->servers.Append() = ngl;
for (NetworkGameList *ngl = _network_game_list; ngl != nullptr; ngl = ngl->next) {
this->servers.push_back(ngl);
}
/* Apply the filter condition immediately, if a search string has been provided. */
@@ -268,9 +267,9 @@ protected:
this->servers.SetFilterState(false);
}
this->servers.Compact();
this->servers.shrink_to_fit();
this->servers.RebuildDone();
this->vscroll->SetCount(this->servers.Length());
this->vscroll->SetCount((int)this->servers.size());
/* Sort the list of network games as requested. */
this->servers.Sort();
@@ -278,10 +277,10 @@ protected:
}
/** Sort servers by name. */
static int CDECL NGameNameSorter(NetworkGameList * const *a, NetworkGameList * const *b)
static bool NGameNameSorter(NetworkGameList * const &a, NetworkGameList * const &b)
{
int r = strnatcmp((*a)->info.server_name, (*b)->info.server_name, true); // Sort by name (natural sorting).
return r == 0 ? (*a)->address.CompareTo((*b)->address) : r;
int r = strnatcmp(a->info.server_name, b->info.server_name, true); // Sort by name (natural sorting).
return r == 0 ? a->address.CompareTo(b->address) < 0: r < 0;
}
/**
@@ -289,60 +288,60 @@ protected:
* server. If the two servers have the same amount, the one with the
* higher maximum is preferred.
*/
static int CDECL NGameClientSorter(NetworkGameList * const *a, NetworkGameList * const *b)
static bool NGameClientSorter(NetworkGameList * const &a, NetworkGameList * const &b)
{
/* Reverse as per default we are interested in most-clients first */
int r = (*a)->info.clients_on - (*b)->info.clients_on;
int r = a->info.clients_on - b->info.clients_on;
if (r == 0) r = (*a)->info.clients_max - (*b)->info.clients_max;
if (r == 0) r = NGameNameSorter(a, b);
if (r == 0) r = a->info.clients_max - b->info.clients_max;
if (r == 0) return NGameNameSorter(a, b);
return r;
return r < 0;
}
/** Sort servers by map size */
static int CDECL NGameMapSizeSorter(NetworkGameList * const *a, NetworkGameList * const *b)
static bool NGameMapSizeSorter(NetworkGameList * const &a, NetworkGameList * const &b)
{
/* Sort by the area of the map. */
int r = ((*a)->info.map_height) * ((*a)->info.map_width) - ((*b)->info.map_height) * ((*b)->info.map_width);
int r = (a->info.map_height) * (a->info.map_width) - (b->info.map_height) * (b->info.map_width);
if (r == 0) r = (*a)->info.map_width - (*b)->info.map_width;
return (r != 0) ? r : NGameClientSorter(a, b);
if (r == 0) r = a->info.map_width - b->info.map_width;
return (r != 0) ? r < 0 : NGameClientSorter(a, b);
}
/** Sort servers by current date */
static int CDECL NGameDateSorter(NetworkGameList * const *a, NetworkGameList * const *b)
static bool NGameDateSorter(NetworkGameList * const &a, NetworkGameList * const &b)
{
int r = (*a)->info.game_date - (*b)->info.game_date;
return (r != 0) ? r : NGameClientSorter(a, b);
int r = a->info.game_date - b->info.game_date;
return (r != 0) ? r < 0 : NGameClientSorter(a, b);
}
/** Sort servers by the number of days the game is running */
static int CDECL NGameYearsSorter(NetworkGameList * const *a, NetworkGameList * const *b)
static bool NGameYearsSorter(NetworkGameList * const &a, NetworkGameList * const &b)
{
int r = (*a)->info.game_date - (*a)->info.start_date - (*b)->info.game_date + (*b)->info.start_date;
return (r != 0) ? r : NGameDateSorter(a, b);
int r = a->info.game_date - a->info.start_date - b->info.game_date + b->info.start_date;
return (r != 0) ? r < 0: NGameDateSorter(a, b);
}
/**
* Sort servers by joinability. If both servers are the
* same, prefer the non-passworded server first.
*/
static int CDECL NGameAllowedSorter(NetworkGameList * const *a, NetworkGameList * const *b)
static bool NGameAllowedSorter(NetworkGameList * const &a, NetworkGameList * const &b)
{
/* The servers we do not know anything about (the ones that did not reply) should be at the bottom) */
int r = StrEmpty((*a)->info.server_revision) - StrEmpty((*b)->info.server_revision);
int r = StrEmpty(a->info.server_revision) - StrEmpty(b->info.server_revision);
/* Reverse default as we are interested in version-compatible clients first */
if (r == 0) r = (*b)->info.version_compatible - (*a)->info.version_compatible;
if (r == 0) r = b->info.version_compatible - a->info.version_compatible;
/* The version-compatible ones are then sorted with NewGRF compatible first, incompatible last */
if (r == 0) r = (*b)->info.compatible - (*a)->info.compatible;
if (r == 0) r = b->info.compatible - a->info.compatible;
/* Passworded servers should be below unpassworded servers */
if (r == 0) r = (*a)->info.use_password - (*b)->info.use_password;
if (r == 0) r = a->info.use_password - b->info.use_password;
/* Finally sort on the number of clients of the server */
if (r == 0) r = -NGameClientSorter(a, b);
if (r == 0) return NGameClientSorter(a, b);
return r;
return r < 0;
}
/** Sort the server list */
@@ -355,7 +354,7 @@ protected:
void UpdateListPos()
{
this->list_pos = SLP_INVALID;
for (uint i = 0; i != this->servers.Length(); i++) {
for (uint i = 0; i != this->servers.size(); i++) {
if (this->servers[i] == this->server) {
this->list_pos = i;
break;
@@ -365,8 +364,8 @@ protected:
static bool CDECL NGameSearchFilter(NetworkGameList * const *item, StringFilter &sf)
{
assert(item != NULL);
assert((*item) != NULL);
assert(item != nullptr);
assert((*item) != nullptr);
sf.ResetState();
sf.AddLine((*item)->info.server_name);
@@ -461,7 +460,7 @@ public:
NetworkGameWindow(WindowDesc *desc) : Window(desc), name_editbox(NETWORK_CLIENT_NAME_LENGTH), filter_editbox(120)
{
this->list_pos = SLP_INVALID;
this->server = NULL;
this->server = nullptr;
this->lock_offset = 5;
this->blot_offset = this->lock_offset + 3 + GetSpriteSize(SPR_LOCK).width;
@@ -480,7 +479,7 @@ public:
this->last_joined = NetworkGameListAddItem(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port));
this->server = this->last_joined;
if (this->last_joined != NULL) NetworkUDPQueryServer(this->last_joined->address);
if (this->last_joined != nullptr) NetworkUDPQueryServer(this->last_joined->address);
this->requery_timer.SetInterval(MILLISECONDS_PER_TICK);
@@ -495,7 +494,7 @@ public:
this->last_sorting = this->servers.GetListing();
}
virtual void SetStringParameters(int widget) const
void SetStringParameters(int widget) const override
{
switch (widget) {
case WID_NG_CONN_BTN:
@@ -504,7 +503,7 @@ public:
}
}
virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
{
switch (widget) {
case WID_NG_CONN_BTN:
@@ -559,13 +558,13 @@ public:
}
}
virtual void DrawWidget(const Rect &r, int widget) const
void DrawWidget(const Rect &r, int widget) const override
{
switch (widget) {
case WID_NG_MATRIX: {
uint16 y = r.top;
const int max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), (int)this->servers.Length());
const int max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), (int)this->servers.size());
for (int i = this->vscroll->GetPosition(); i < max; ++i) {
const NetworkGameList *ngl = this->servers[i];
@@ -577,7 +576,7 @@ public:
case WID_NG_LASTJOINED:
/* Draw the last joined server, if any */
if (this->last_joined != NULL) this->DrawServerLine(this->last_joined, r.top, this->last_joined == this->server);
if (this->last_joined != nullptr) this->DrawServerLine(this->last_joined, r.top, this->last_joined == this->server);
break;
case WID_NG_DETAILS:
@@ -596,7 +595,7 @@ public:
}
virtual void OnPaint()
void OnPaint() override
{
if (this->servers.NeedRebuild()) {
this->BuildGUINetworkGameList();
@@ -607,16 +606,16 @@ public:
NetworkGameList *sel = this->server;
/* 'Refresh' button invisible if no server selected */
this->SetWidgetDisabledState(WID_NG_REFRESH, sel == NULL);
this->SetWidgetDisabledState(WID_NG_REFRESH, sel == nullptr);
/* 'Join' button disabling conditions */
this->SetWidgetDisabledState(WID_NG_JOIN, sel == NULL || // no Selected Server
this->SetWidgetDisabledState(WID_NG_JOIN, sel == nullptr || // no Selected Server
!sel->online || // Server offline
sel->info.clients_on >= sel->info.clients_max || // Server full
!sel->info.compatible); // Revision mismatch
/* 'NewGRF Settings' button invisible if no NewGRF is used */
this->GetWidget<NWidgetStacked>(WID_NG_NEWGRF_SEL)->SetDisplayedPlane(sel == NULL || !sel->online || sel->info.grfconfig == NULL);
this->GetWidget<NWidgetStacked>(WID_NG_NEWGRF_MISSING_SEL)->SetDisplayedPlane(sel == NULL || !sel->online || sel->info.grfconfig == NULL || !sel->info.version_compatible || sel->info.compatible);
this->GetWidget<NWidgetStacked>(WID_NG_NEWGRF_SEL)->SetDisplayedPlane(sel == nullptr || !sel->online || sel->info.grfconfig == nullptr);
this->GetWidget<NWidgetStacked>(WID_NG_NEWGRF_MISSING_SEL)->SetDisplayedPlane(sel == nullptr || !sel->online || sel->info.grfconfig == nullptr || !sel->info.version_compatible || sel->info.compatible);
this->DrawWidgets();
}
@@ -629,7 +628,7 @@ public:
/* Draw the right menu */
GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.top + detail_height - 1, PC_DARK_BLUE);
if (sel == NULL) {
if (sel == nullptr) {
DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + 6 + 4 + FONT_HEIGHT_NORMAL, STR_NETWORK_SERVER_LIST_GAME_INFO, TC_FROMSTRING, SA_HOR_CENTER);
} else if (!sel->online) {
DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + 6 + 4 + FONT_HEIGHT_NORMAL, sel->info.server_name, TC_ORANGE, SA_HOR_CENTER); // game name
@@ -692,7 +691,7 @@ public:
}
}
virtual void OnClick(Point pt, int widget, int click_count)
void OnClick(Point pt, int widget, int click_count) override
{
switch (widget) {
case WID_NG_CANCEL: // Cancel button
@@ -711,7 +710,7 @@ public:
case WID_NG_INFO: // Connectivity (green dot)
if (this->servers.SortType() == widget - WID_NG_NAME) {
this->servers.ToggleSortOrder();
if (this->list_pos != SLP_INVALID) this->list_pos = this->servers.Length() - this->list_pos - 1;
if (this->list_pos != SLP_INVALID) this->list_pos = (ServerListPosition)this->servers.size() - this->list_pos - 1;
} else {
this->servers.SetSortType(widget - WID_NG_NAME);
this->servers.ForceResort();
@@ -723,8 +722,8 @@ public:
case WID_NG_MATRIX: { // Show available network games
uint id_v = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NG_MATRIX);
this->server = (id_v < this->servers.Length()) ? this->servers[id_v] : NULL;
this->list_pos = (server == NULL) ? SLP_INVALID : id_v;
this->server = (id_v < this->servers.size()) ? this->servers[id_v] : nullptr;
this->list_pos = (server == nullptr) ? SLP_INVALID : id_v;
this->SetDirty();
/* FIXME the disabling should go into some InvalidateData, which is called instead of the SetDirty */
@@ -733,7 +732,7 @@ public:
}
case WID_NG_LASTJOINED: {
if (this->last_joined != NULL) {
if (this->last_joined != nullptr) {
this->server = this->last_joined;
/* search the position of the newly selected server */
@@ -768,7 +767,7 @@ public:
break;
case WID_NG_JOIN: // Join Game
if (this->server != NULL) {
if (this->server != nullptr) {
seprintf(_settings_client.network.last_host, lastof(_settings_client.network.last_host), "%s", this->server->address.GetHostname());
_settings_client.network.last_port = this->server->address.GetPort();
ShowNetworkLobbyWindow(this->server);
@@ -776,20 +775,20 @@ public:
break;
case WID_NG_REFRESH: // Refresh
if (this->server != NULL) NetworkUDPQueryServer(this->server->address);
if (this->server != nullptr) NetworkUDPQueryServer(this->server->address);
break;
case WID_NG_NEWGRF: // NewGRF Settings
if (this->server != NULL) ShowNewGRFSettings(false, false, false, &this->server->info.grfconfig);
if (this->server != nullptr) ShowNewGRFSettings(false, false, false, &this->server->info.grfconfig);
break;
case WID_NG_NEWGRF_MISSING: // Find missing content online
if (this->server != NULL) ShowMissingContentWindow(this->server->info.grfconfig);
if (this->server != nullptr) ShowMissingContentWindow(this->server->info.grfconfig);
break;
}
}
virtual void OnDropdownSelect(int widget, int index)
void OnDropdownSelect(int widget, int index) override
{
switch (widget) {
case WID_NG_CONN_BTN:
@@ -808,19 +807,19 @@ public:
* @param data Information about the changed data.
* @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
*/
virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
void OnInvalidateData(int data = 0, bool gui_scope = true) override
{
this->servers.ForceRebuild();
this->SetDirty();
}
virtual EventState OnKeyPress(WChar key, uint16 keycode)
EventState OnKeyPress(WChar key, uint16 keycode) override
{
EventState state = ES_NOT_HANDLED;
/* handle up, down, pageup, pagedown, home and end */
if (keycode == WKC_UP || keycode == WKC_DOWN || keycode == WKC_PAGEUP || keycode == WKC_PAGEDOWN || keycode == WKC_HOME || keycode == WKC_END) {
if (this->servers.Length() == 0) return ES_HANDLED;
if (this->servers.size() == 0) return ES_HANDLED;
switch (keycode) {
case WKC_UP:
/* scroll up by one */
@@ -830,7 +829,7 @@ public:
case WKC_DOWN:
/* scroll down by one */
if (this->list_pos == SLP_INVALID) return ES_HANDLED;
if (this->list_pos < this->servers.Length() - 1) this->list_pos++;
if (this->list_pos < this->servers.size() - 1) this->list_pos++;
break;
case WKC_PAGEUP:
/* scroll up a page */
@@ -840,7 +839,7 @@ public:
case WKC_PAGEDOWN:
/* scroll down a page */
if (this->list_pos == SLP_INVALID) return ES_HANDLED;
this->list_pos = min(this->list_pos + this->vscroll->GetCapacity(), (int)this->servers.Length() - 1);
this->list_pos = min(this->list_pos + this->vscroll->GetCapacity(), (int)this->servers.size() - 1);
break;
case WKC_HOME:
/* jump to beginning */
@@ -848,7 +847,7 @@ public:
break;
case WKC_END:
/* jump to end */
this->list_pos = this->servers.Length() - 1;
this->list_pos = (ServerListPosition)this->servers.size() - 1;
break;
default: NOT_REACHED();
}
@@ -863,11 +862,11 @@ public:
return ES_HANDLED;
}
if (this->server != NULL) {
if (this->server != nullptr) {
if (keycode == WKC_DELETE) { // Press 'delete' to remove servers
NetworkGameListRemoveItem(this->server);
if (this->server == this->last_joined) this->last_joined = NULL;
this->server = NULL;
if (this->server == this->last_joined) this->last_joined = nullptr;
this->server = nullptr;
this->list_pos = SLP_INVALID;
}
}
@@ -875,7 +874,7 @@ public:
return state;
}
virtual void OnEditboxChanged(int wid)
void OnEditboxChanged(int wid) override
{
switch (wid) {
case WID_NG_FILTER: {
@@ -897,17 +896,17 @@ public:
}
}
virtual void OnQueryTextFinished(char *str)
void OnQueryTextFinished(char *str) override
{
if (!StrEmpty(str)) NetworkAddServer(str);
}
virtual void OnResize()
void OnResize() override
{
this->vscroll->SetCapacityFromWidget(this, WID_NG_MATRIX);
}
virtual void OnRealtimeTick(uint delta_ms)
void OnRealtimeTick(uint delta_ms) override
{
if (!this->requery_timer.Elapsed(delta_ms)) return;
this->requery_timer.SetInterval(MILLISECONDS_PER_TICK);
@@ -1046,8 +1045,8 @@ void ShowNetworkGameWindow()
if (first) {
first = false;
/* Add all servers from the config file to our list. */
for (char **iter = _network_host_list.Begin(); iter != _network_host_list.End(); iter++) {
NetworkAddServer(*iter);
for (const auto &iter : _network_host_list) {
NetworkAddServer(iter.c_str());
}
}
@@ -1068,7 +1067,7 @@ struct NetworkStartServerWindow : public Window {
this->SetFocusedWidget(WID_NSS_GAMENAME);
}
virtual void SetStringParameters(int widget) const
void SetStringParameters(int widget) const override
{
switch (widget) {
case WID_NSS_CONNTYPE_BTN:
@@ -1093,7 +1092,7 @@ struct NetworkStartServerWindow : public Window {
}
}
virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
{
switch (widget) {
case WID_NSS_CONNTYPE_BTN:
@@ -1104,7 +1103,7 @@ struct NetworkStartServerWindow : public Window {
}
}
virtual void DrawWidget(const Rect &r, int widget) const
void DrawWidget(const Rect &r, int widget) const override
{
switch (widget) {
case WID_NSS_SETPWD:
@@ -1113,7 +1112,7 @@ struct NetworkStartServerWindow : public Window {
}
}
virtual void OnClick(Point pt, int widget, int click_count)
void OnClick(Point pt, int widget, int click_count) override
{
switch (widget) {
case WID_NSS_CANCEL: // Cancel button
@@ -1173,13 +1172,13 @@ struct NetworkStartServerWindow : public Window {
case WID_NSS_LANGUAGE_BTN: { // Language
uint sel = 0;
for (uint i = 0; i < lengthof(_language_dropdown) - 1; i++) {
for (uint i = 0; i < _language_dropdown.size() - 1; i++) {
if (_language_dropdown[i] == STR_NETWORK_LANG_ANY + _settings_client.network.server_lang) {
sel = i;
break;
}
}
ShowDropDownMenu(this, _language_dropdown, sel, WID_NSS_LANGUAGE_BTN, 0, 0);
ShowDropDownMenu(this, _language_dropdown.data(), sel, WID_NSS_LANGUAGE_BTN, 0, 0);
break;
}
@@ -1209,7 +1208,7 @@ struct NetworkStartServerWindow : public Window {
}
}
virtual void OnDropdownSelect(int widget, int index)
void OnDropdownSelect(int widget, int index) override
{
switch (widget) {
case WID_NSS_CONNTYPE_BTN:
@@ -1225,14 +1224,14 @@ struct NetworkStartServerWindow : public Window {
this->SetDirty();
}
virtual void OnEditboxChanged(int wid)
void OnEditboxChanged(int wid) override
{
if (wid == WID_NSS_GAMENAME) {
strecpy(_settings_client.network.server_name, this->name_editbox.text.buf, lastof(_settings_client.network.server_name));
}
}
virtual void OnTimeout()
void OnTimeout() override
{
static const int raise_widgets[] = {WID_NSS_CLIENTS_BTND, WID_NSS_CLIENTS_BTNU, WID_NSS_COMPANIES_BTND, WID_NSS_COMPANIES_BTNU, WID_NSS_SPECTATORS_BTND, WID_NSS_SPECTATORS_BTNU, WIDGET_LIST_END};
for (const int *widget = raise_widgets; *widget != WIDGET_LIST_END; widget++) {
@@ -1243,9 +1242,9 @@ struct NetworkStartServerWindow : public Window {
}
}
virtual void OnQueryTextFinished(char *str)
void OnQueryTextFinished(char *str) override
{
if (str == NULL) return;
if (str == nullptr) return;
if (this->widget_id == WID_NSS_SETPWD) {
strecpy(_settings_client.network.server_password, str, lastof(_settings_client.network.server_password));
@@ -1345,7 +1344,7 @@ static const NWidgetPart _nested_network_start_server_window_widgets[] = {
};
static WindowDesc _network_start_server_window_desc(
WDP_CENTER, NULL, 0, 0,
WDP_CENTER, nullptr, 0, 0,
WC_NETWORK_WINDOW, WC_NONE,
0,
_nested_network_start_server_window_widgets, lengthof(_nested_network_start_server_window_widgets)
@@ -1385,7 +1384,7 @@ struct NetworkLobbyWindow : public Window {
return COMPANY_FIRST;
}
virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
{
switch (widget) {
case WID_NL_HEADER:
@@ -1403,7 +1402,7 @@ struct NetworkLobbyWindow : public Window {
}
}
virtual void SetStringParameters(int widget) const
void SetStringParameters(int widget) const override
{
switch (widget) {
case WID_NL_TEXT:
@@ -1412,7 +1411,7 @@ struct NetworkLobbyWindow : public Window {
}
}
virtual void DrawWidget(const Rect &r, int widget) const
void DrawWidget(const Rect &r, int widget) const override
{
switch (widget) {
case WID_NL_DETAILS:
@@ -1425,7 +1424,7 @@ struct NetworkLobbyWindow : public Window {
}
}
virtual void OnPaint()
void OnPaint() override
{
const NetworkGameInfo *gi = &this->server->info;
@@ -1547,7 +1546,7 @@ struct NetworkLobbyWindow : public Window {
DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_NETWORK_GAME_LOBBY_PLAYERS); // players
}
virtual void OnClick(Point pt, int widget, int click_count)
void OnClick(Point pt, int widget, int click_count) override
{
switch (widget) {
case WID_NL_CANCEL: // Cancel button
@@ -1586,7 +1585,7 @@ struct NetworkLobbyWindow : public Window {
}
}
virtual void OnResize()
void OnResize() override
{
this->vscroll->SetCapacityFromWidget(this, WID_NL_MATRIX);
}
@@ -1632,7 +1631,7 @@ static const NWidgetPart _nested_network_lobby_window_widgets[] = {
};
static WindowDesc _network_lobby_window_desc(
WDP_CENTER, NULL, 0, 0,
WDP_CENTER, nullptr, 0, 0,
WC_NETWORK_WINDOW, WC_NONE,
0,
_nested_network_lobby_window_widgets, lengthof(_nested_network_lobby_window_widgets)
@@ -1661,7 +1660,7 @@ static void ShowNetworkLobbyWindow(NetworkGameList *ngl)
NetworkCompanyInfo *GetLobbyCompanyInfo(CompanyID company)
{
NetworkLobbyWindow *lobby = dynamic_cast<NetworkLobbyWindow*>(FindWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_LOBBY));
return (lobby != NULL && company < MAX_COMPANIES) ? &lobby->company_info[company] : NULL;
return (lobby != nullptr && company < MAX_COMPANIES) ? &lobby->company_info[company] : nullptr;
}
/* The window below gives information about the connected clients
@@ -1681,7 +1680,7 @@ static const NWidgetPart _nested_client_list_popup_widgets[] = {
};
static WindowDesc _client_list_popup_desc(
WDP_AUTO, NULL, 0, 0,
WDP_AUTO, nullptr, 0, 0,
WC_CLIENT_LIST_POPUP, WC_CLIENT_LIST,
0,
_nested_client_list_popup_widgets, lengthof(_nested_client_list_popup_widgets)
@@ -1729,7 +1728,7 @@ struct NetworkClientListPopupWindow : Window {
uint sel_index;
ClientID client_id;
Point desired_location;
SmallVector<ClientListAction, 2> actions; ///< Actions to execute
std::vector<ClientListAction> actions; ///< Actions to execute
/**
* Add an action to the list of actions to execute.
@@ -1738,9 +1737,7 @@ struct NetworkClientListPopupWindow : Window {
*/
inline void AddAction(StringID name, ClientList_Action_Proc *proc)
{
ClientListAction *action = this->actions.Append();
action->name = name;
action->proc = proc;
this->actions.push_back({name, proc});
}
NetworkClientListPopupWindow(WindowDesc *desc, int x, int y, ClientID client_id) :
@@ -1778,30 +1775,30 @@ struct NetworkClientListPopupWindow : Window {
CLRBITS(this->flags, WF_WHITE_BORDER);
}
virtual Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number)
Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number) override
{
return this->desired_location;
}
virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
{
Dimension d = *size;
for (const ClientListAction *action = this->actions.Begin(); action != this->actions.End(); action++) {
d = maxdim(GetStringBoundingBox(action->name), d);
for (const ClientListAction &action : this->actions) {
d = maxdim(GetStringBoundingBox(action.name), d);
}
d.height *= this->actions.Length();
d.height *= (uint)this->actions.size();
d.width += WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
d.height += WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
*size = d;
}
virtual void DrawWidget(const Rect &r, int widget) const
void DrawWidget(const Rect &r, int widget) const override
{
/* Draw the actions */
int sel = this->sel_index;
int y = r.top + WD_FRAMERECT_TOP;
for (const ClientListAction *action = this->actions.Begin(); action != this->actions.End(); action++, y += FONT_HEIGHT_NORMAL) {
for (const ClientListAction &action : this->actions) {
TextColour colour;
if (sel-- == 0) { // Selected item, highlight it
GfxFillRect(r.left + 1, y, r.right - 1, y + FONT_HEIGHT_NORMAL - 1, PC_BLACK);
@@ -1810,24 +1807,25 @@ struct NetworkClientListPopupWindow : Window {
colour = TC_BLACK;
}
DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, action->name, colour);
DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, action.name, colour);
y += FONT_HEIGHT_NORMAL;
}
}
virtual void OnMouseLoop()
void OnMouseLoop() override
{
/* We selected an action */
uint index = (_cursor.pos.y - this->top - WD_FRAMERECT_TOP) / FONT_HEIGHT_NORMAL;
if (_left_button_down) {
if (index == this->sel_index || index >= this->actions.Length()) return;
if (index == this->sel_index || index >= this->actions.size()) return;
this->sel_index = index;
this->SetDirty();
} else {
if (index < this->actions.Length() && _cursor.pos.y >= this->top) {
if (index < this->actions.size() && _cursor.pos.y >= this->top) {
const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(this->client_id);
if (ci != NULL) this->actions[index].proc(ci);
if (ci != nullptr) this->actions[index].proc(ci);
}
DeleteWindowByClass(WC_CLIENT_LIST_POPUP);
@@ -1842,7 +1840,7 @@ static void PopupClientList(ClientID client_id, int x, int y)
{
DeleteWindowByClass(WC_CLIENT_LIST_POPUP);
if (NetworkClientInfo::GetByClientID(client_id) == NULL) return;
if (NetworkClientInfo::GetByClientID(client_id) == nullptr) return;
new NetworkClientListPopupWindow(&_client_list_popup_desc, x, y, client_id);
}
@@ -1905,7 +1903,7 @@ struct NetworkClientListWindow : Window {
return true;
}
virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
{
if (widget != WID_CL_PANEL) return;
@@ -1922,7 +1920,7 @@ struct NetworkClientListWindow : Window {
size->width = WD_FRAMERECT_LEFT + this->server_client_width + this->icon_size.width + WD_FRAMERECT_LEFT + width + WD_FRAMERECT_RIGHT;
}
virtual void OnPaint()
void OnPaint() override
{
/* Check if we need to reset the height */
if (!this->CheckClientListHeight()) return;
@@ -1930,7 +1928,7 @@ struct NetworkClientListWindow : Window {
this->DrawWidgets();
}
virtual void DrawWidget(const Rect &r, int widget) const
void DrawWidget(const Rect &r, int widget) const override
{
if (widget != WID_CL_PANEL) return;
@@ -1976,7 +1974,7 @@ struct NetworkClientListWindow : Window {
}
}
virtual void OnClick(Point pt, int widget, int click_count)
void OnClick(Point pt, int widget, int click_count) override
{
/* Show the popup with option */
if (this->selected_item != -1) {
@@ -1988,11 +1986,11 @@ struct NetworkClientListWindow : Window {
client_no--;
}
if (ci != NULL) PopupClientList(ci->client_id, pt.x + this->left, pt.y + this->top);
if (ci != nullptr) PopupClientList(ci->client_id, pt.x + this->left, pt.y + this->top);
}
}
virtual void OnMouseOver(Point pt, int widget)
void OnMouseOver(Point pt, int widget) override
{
/* -1 means we left the current window */
if (pt.y == -1) {
@@ -2036,7 +2034,7 @@ struct NetworkJoinStatusWindow : Window {
this->InitNested(WN_NETWORK_STATUS_WINDOW_JOIN);
}
virtual void DrawWidget(const Rect &r, int widget) const
void DrawWidget(const Rect &r, int widget) const override
{
if (widget != WID_NJS_BACKGROUND) return;
@@ -2070,7 +2068,7 @@ struct NetworkJoinStatusWindow : Window {
DrawFrameRect(r.left + 20, r.top + 5, (int)((this->width - 20) * progress / 100), r.top + 15, COLOUR_MAUVE, FR_NONE);
}
virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
{
if (widget != WID_NJS_BACKGROUND) return;
@@ -2096,7 +2094,7 @@ struct NetworkJoinStatusWindow : Window {
size->width = width + WD_FRAMERECT_LEFT + WD_FRAMERECT_BOTTOM + 10;
}
virtual void OnClick(Point pt, int widget, int click_count)
void OnClick(Point pt, int widget, int click_count) override
{
if (widget == WID_NJS_CANCELOK) { // Disconnect button
NetworkDisconnect();
@@ -2105,7 +2103,7 @@ struct NetworkJoinStatusWindow : Window {
}
}
virtual void OnQueryTextFinished(char *str)
void OnQueryTextFinished(char *str) override
{
if (StrEmpty(str)) {
NetworkDisconnect();
@@ -2135,7 +2133,7 @@ static const NWidgetPart _nested_network_join_status_window_widgets[] = {
};
static WindowDesc _network_join_status_window_desc(
WDP_CENTER, NULL, 0, 0,
WDP_CENTER, nullptr, 0, 0,
WC_NETWORK_STATUS_WINDOW, WC_NONE,
WDF_MODAL,
_nested_network_join_status_window_widgets, lengthof(_nested_network_join_status_window_widgets)
@@ -2150,7 +2148,7 @@ void ShowJoinStatusWindow()
void ShowNetworkNeedPassword(NetworkPasswordType npt)
{
NetworkJoinStatusWindow *w = (NetworkJoinStatusWindow *)FindWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
if (w == NULL) return;
if (w == nullptr) return;
w->password_type = npt;
StringID caption;
@@ -2159,15 +2157,17 @@ void ShowNetworkNeedPassword(NetworkPasswordType npt)
case NETWORK_GAME_PASSWORD: caption = STR_NETWORK_NEED_GAME_PASSWORD_CAPTION; break;
case NETWORK_COMPANY_PASSWORD: caption = STR_NETWORK_NEED_COMPANY_PASSWORD_CAPTION; break;
}
ShowQueryString(STR_EMPTY, caption, NETWORK_PASSWORD_LENGTH, w, CS_ALPHANUMERAL, QSF_NONE);
ShowQueryString(STR_EMPTY, caption, NETWORK_PASSWORD_LENGTH, w, CS_ALPHANUMERAL, QSF_PASSWORD);
}
struct NetworkCompanyPasswordWindow : public Window {
QueryString password_editbox; ///< Password editbox.
Dimension warning_size; ///< How much space to use for the warning text
NetworkCompanyPasswordWindow(WindowDesc *desc, Window *parent) : Window(desc), password_editbox(lengthof(_settings_client.network.default_company_pass))
{
this->InitNested(0);
this->UpdateWarningStringSize();
this->parent = parent;
this->querystrings[WID_NCP_PASSWORD] = &this->password_editbox;
@@ -2176,6 +2176,32 @@ struct NetworkCompanyPasswordWindow : public Window {
this->SetFocusedWidget(WID_NCP_PASSWORD);
}
void UpdateWarningStringSize()
{
assert(this->nested_root->smallest_x > 0);
this->warning_size.width = this->nested_root->current_x - (WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT);
this->warning_size.height = GetStringHeight(STR_WARNING_PASSWORD_SECURITY, this->warning_size.width);
this->warning_size.height += WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
this->ReInit();
}
void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
{
if (widget == WID_NCP_WARNING) {
*size = this->warning_size;
}
}
void DrawWidget(const Rect &r, int widget) const override
{
if (widget != WID_NCP_WARNING) return;
DrawStringMultiLine(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT,
r.top + WD_FRAMERECT_TOP, r.bottom - WD_FRAMERECT_BOTTOM,
STR_WARNING_PASSWORD_SECURITY, TC_FROMSTRING, SA_CENTER);
}
void OnOk()
{
if (this->IsWidgetLowered(WID_NCP_SAVE_AS_DEFAULT_PASSWORD)) {
@@ -2185,7 +2211,7 @@ struct NetworkCompanyPasswordWindow : public Window {
NetworkChangeCompanyPassword(_local_company, this->password_editbox.text.buf);
}
virtual void OnClick(Point pt, int widget, int click_count)
void OnClick(Point pt, int widget, int click_count) override
{
switch (widget) {
case WID_NCP_OK:
@@ -2222,6 +2248,7 @@ static const NWidgetPart _nested_network_company_password_window_widgets[] = {
EndContainer(),
EndContainer(),
EndContainer(),
NWidget(WWT_PANEL, COLOUR_GREY, WID_NCP_WARNING), EndContainer(),
NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_NCP_CANCEL), SetFill(1, 0), SetDataTip(STR_BUTTON_CANCEL, STR_COMPANY_PASSWORD_CANCEL),
NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_NCP_OK), SetFill(1, 0), SetDataTip(STR_BUTTON_OK, STR_COMPANY_PASSWORD_OK),
@@ -2229,7 +2256,7 @@ static const NWidgetPart _nested_network_company_password_window_widgets[] = {
};
static WindowDesc _network_company_password_window_desc(
WDP_AUTO, NULL, 0, 0,
WDP_AUTO, nullptr, 0, 0,
WC_COMPANY_PASSWORD_WINDOW, WC_NONE,
0,
_nested_network_company_password_window_widgets, lengthof(_nested_network_company_password_window_widgets)
@@ -2241,5 +2268,3 @@ void ShowNetworkCompanyPasswordWindow(Window *parent)
new NetworkCompanyPasswordWindow(&_network_company_password_window_desc, parent);
}
#endif /* ENABLE_NETWORK */
-12
View File
@@ -17,8 +17,6 @@
#include "../window_type.h"
#include "network_type.h"
#ifdef ENABLE_NETWORK
void ShowNetworkNeedPassword(NetworkPasswordType npt);
void ShowNetworkGiveMoneyWindow(CompanyID company);
void ShowNetworkChatQueryWindow(DestType type, int dest);
@@ -42,14 +40,4 @@ struct NetworkCompanyInfo : NetworkCompanyStats {
NetworkCompanyInfo *GetLobbyCompanyInfo(CompanyID company);
#else /* ENABLE_NETWORK */
/* Network function stubs when networking is disabled */
static inline void ShowNetworkChatQueryWindow(byte desttype, int dest) {}
static inline void ShowClientList() {}
static inline void ShowNetworkGameWindow() {}
static inline void ShowNetworkCompanyPasswordWindow(Window *parent) {}
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_GUI_H */
+2 -5
View File
@@ -17,8 +17,6 @@
#include "../command_type.h"
#ifdef ENABLE_NETWORK
#ifdef RANDOM_DEBUG
/**
* If this line is enable, every frame will have a sync test
@@ -151,8 +149,8 @@ bool IsNetworkCompatibleVersion(const char *version);
* Everything we need to know about a command to be able to execute it.
*/
struct CommandPacket : CommandContainer {
/** Make sure the pointer is NULL. */
CommandPacket() : next(NULL), company(INVALID_COMPANY), frame(0), my_cmd(false) {}
/** Make sure the pointer is nullptr. */
CommandPacket() : next(nullptr), company(INVALID_COMPANY), frame(0), my_cmd(false) {}
CommandPacket *next; ///< the next command packet (if in queue)
CompanyID company; ///< company that is executing the command
uint32 frame; ///< the frame in which this packet is executed
@@ -171,5 +169,4 @@ StringID GetNetworkErrorMsg(NetworkErrorCode err);
bool NetworkFindName(char *new_name, const char *last);
const char *GenerateCompanyPasswordHash(const char *password, const char *password_server_id, uint32 password_game_seed);
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_INTERNAL_H */
+74 -90
View File
@@ -9,8 +9,6 @@
/** @file network_server.cpp Server part of the network protocol. */
#ifdef ENABLE_NETWORK
#include "../stdafx.h"
#include "../strings_func.h"
#include "../date_func.h"
@@ -32,6 +30,8 @@
#include "../core/pool_func.hpp"
#include "../core/random_func.hpp"
#include "../rev.h"
#include <mutex>
#include <condition_variable>
#include "../safeguards.h"
@@ -60,47 +60,40 @@ struct PacketWriter : SaveFilter {
Packet *current; ///< The packet we're currently writing to.
size_t total_size; ///< Total size of the compressed savegame.
Packet *packets; ///< Packet queue of the savegame; send these "slowly" to the client.
ThreadMutex *mutex; ///< Mutex for making threaded saving safe.
std::mutex mutex; ///< Mutex for making threaded saving safe.
std::condition_variable exit_sig; ///< Signal for threaded destruction of this packet writer.
/**
* Create the packet writer.
* @param cs The socket handler we're making the packets for.
*/
PacketWriter(ServerNetworkGameSocketHandler *cs) : SaveFilter(NULL), cs(cs), current(NULL), total_size(0), packets(NULL)
PacketWriter(ServerNetworkGameSocketHandler *cs) : SaveFilter(nullptr), cs(cs), current(nullptr), total_size(0), packets(nullptr)
{
this->mutex = ThreadMutex::New();
}
/** Make sure everything is cleaned up. */
~PacketWriter()
{
if (this->mutex != NULL) this->mutex->BeginCritical();
std::unique_lock<std::mutex> lock(this->mutex);
if (this->cs != NULL && this->mutex != NULL) {
this->mutex->WaitForSignal();
}
if (this->cs != nullptr) this->exit_sig.wait(lock);
/* This must all wait until the Destroy function is called. */
while (this->packets != NULL) {
while (this->packets != nullptr) {
Packet *p = this->packets->next;
delete this->packets;
this->packets = p;
}
delete this->current;
if (this->mutex != NULL) this->mutex->EndCritical();
delete this->mutex;
this->mutex = NULL;
}
/**
* Begin the destruction of this packet writer. It can happen in two ways:
* in the first case the client disconnected while saving the map. In this
* case the saving has not finished and killed this PacketWriter. In that
* case we simply set cs to NULL, triggering the appending to fail due to
* case we simply set cs to nullptr, triggering the appending to fail due to
* the connection problem and eventually triggering the destructor. In the
* second case the destructor is already called, and it is waiting for our
* signal which we will send. Only then the packets will be removed by the
@@ -108,13 +101,12 @@ struct PacketWriter : SaveFilter {
*/
void Destroy()
{
if (this->mutex != NULL) this->mutex->BeginCritical();
std::unique_lock<std::mutex> lock(this->mutex);
this->cs = NULL;
this->cs = nullptr;
if (this->mutex != NULL) this->mutex->SendSignal();
if (this->mutex != NULL) this->mutex->EndCritical();
this->exit_sig.notify_all();
lock.unlock();
/* Make sure the saving is completely cancelled. Yes,
* we need to handle the save finish as well as the
@@ -132,7 +124,7 @@ struct PacketWriter : SaveFilter {
*/
bool HasPackets()
{
return this->packets != NULL;
return this->packets != nullptr;
}
/**
@@ -140,13 +132,11 @@ struct PacketWriter : SaveFilter {
*/
Packet *PopPacket()
{
if (this->mutex != NULL) this->mutex->BeginCritical();
std::lock_guard<std::mutex> lock(this->mutex);
Packet *p = this->packets;
this->packets = p->next;
p->next = NULL;
if (this->mutex != NULL) this->mutex->EndCritical();
p->next = nullptr;
return p;
}
@@ -154,25 +144,25 @@ struct PacketWriter : SaveFilter {
/** Append the current packet to the queue. */
void AppendQueue()
{
if (this->current == NULL) return;
if (this->current == nullptr) return;
Packet **p = &this->packets;
while (*p != NULL) {
while (*p != nullptr) {
p = &(*p)->next;
}
*p = this->current;
this->current = NULL;
this->current = nullptr;
}
/* virtual */ void Write(byte *buf, size_t size)
void Write(byte *buf, size_t size) override
{
/* We want to abort the saving when the socket is closed. */
if (this->cs == NULL) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
if (this->cs == nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
if (this->current == NULL) this->current = new Packet(PACKET_SERVER_MAP_DATA);
if (this->current == nullptr) this->current = new Packet(PACKET_SERVER_MAP_DATA);
if (this->mutex != NULL) this->mutex->BeginCritical();
std::lock_guard<std::mutex> lock(this->mutex);
byte *bufe = buf + size;
while (buf != bufe) {
@@ -187,17 +177,15 @@ struct PacketWriter : SaveFilter {
}
}
if (this->mutex != NULL) this->mutex->EndCritical();
this->total_size += size;
}
/* virtual */ void Finish()
void Finish() override
{
/* We want to abort the saving when the socket is closed. */
if (this->cs == NULL) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
if (this->cs == nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
if (this->mutex != NULL) this->mutex->BeginCritical();
std::lock_guard<std::mutex> lock(this->mutex);
/* Make sure the last packet is flushed. */
this->AppendQueue();
@@ -210,8 +198,6 @@ struct PacketWriter : SaveFilter {
Packet *p = new Packet(PACKET_SERVER_MAP_SIZE);
p->Send_uint32((uint32)this->total_size);
this->cs->NetworkTCPSocketHandler::SendPacket(p);
if (this->mutex != NULL) this->mutex->EndCritical();
}
};
@@ -240,9 +226,9 @@ ServerNetworkGameSocketHandler::~ServerNetworkGameSocketHandler()
if (_redirect_console_to_client == this->client_id) _redirect_console_to_client = INVALID_CLIENT_ID;
OrderBackup::ResetUser(this->client_id);
if (this->savegame != NULL) {
if (this->savegame != nullptr) {
this->savegame->Destroy();
this->savegame = NULL;
this->savegame = nullptr;
}
}
@@ -250,12 +236,12 @@ Packet *ServerNetworkGameSocketHandler::ReceivePacket()
{
/* Only allow receiving when we have some buffer free; this value
* can go negative, but eventually it will become positive again. */
if (this->receive_limit <= 0) return NULL;
if (this->receive_limit <= 0) return nullptr;
/* We can receive a packet, so try that and if needed account for
* the amount of received data. */
Packet *p = this->NetworkTCPSocketHandler::ReceivePacket();
if (p != NULL) this->receive_limit -= p->size;
if (p != nullptr) this->receive_limit -= p->size;
return p;
}
@@ -278,7 +264,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::CloseConnection(NetworkRecvSta
this->GetClientName(client_name, lastof(client_name));
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST);
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, nullptr, STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST);
/* Inform other clients of this... strange leaving ;) */
FOR_ALL_CLIENT_SOCKETS(new_cs) {
@@ -375,7 +361,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendCompanyInfo()
/* Add the local player (if not dedicated) */
const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
if (ci != NULL && Company::IsValidID(ci->client_playas)) {
if (ci != nullptr && Company::IsValidID(ci->client_playas)) {
strecpy(clients[ci->client_playas], ci->client_name, lastof(clients[ci->client_playas]));
}
@@ -385,7 +371,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendCompanyInfo()
((ServerNetworkGameSocketHandler*)csi)->GetClientName(client_name, lastof(client_name));
ci = csi->GetInfo();
if (ci != NULL && Company::IsValidID(ci->client_playas)) {
if (ci != nullptr && Company::IsValidID(ci->client_playas)) {
if (!StrEmpty(clients[ci->client_playas])) {
strecat(clients[ci->client_playas], ", ", lastof(clients[ci->client_playas]));
}
@@ -448,7 +434,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendError(NetworkErrorCode err
DEBUG(net, 1, "'%s' made an error and has been disconnected. Reason: '%s'", client_name, str);
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, strid);
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, nullptr, strid);
FOR_ALL_CLIENT_SOCKETS(new_cs) {
if (new_cs->status > STATUS_AUTHORIZED && new_cs != this) {
@@ -477,12 +463,12 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGRFCheck()
const GRFConfig *c;
uint grf_count = 0;
for (c = _grfconfig; c != NULL; c = c->next) {
for (c = _grfconfig; c != nullptr; c = c->next) {
if (!HasBit(c->flags, GCF_STATIC)) grf_count++;
}
p->Send_uint8 (grf_count);
for (c = _grfconfig; c != NULL; c = c->next) {
for (c = _grfconfig; c != nullptr; c = c->next) {
if (!HasBit(c->flags, GCF_STATIC)) this->SendGRFIdentifier(p, &c->ident);
}
@@ -621,7 +607,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendMap()
if (last_packet) {
/* Done reading, make sure saving is done as well */
this->savegame->Destroy();
this->savegame = NULL;
this->savegame = nullptr;
/* Set the status to DONE_MAP, no we will wait for the client
* to send it is ready (maybe that happens like never ;)) */
@@ -629,17 +615,17 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendMap()
/* Find the best candidate for joining, i.e. the first joiner. */
NetworkClientSocket *new_cs;
NetworkClientSocket *best = NULL;
NetworkClientSocket *best = nullptr;
FOR_ALL_CLIENT_SOCKETS(new_cs) {
if (new_cs->status == STATUS_MAP_WAIT) {
if (best == NULL || best->GetInfo()->join_date > new_cs->GetInfo()->join_date || (best->GetInfo()->join_date == new_cs->GetInfo()->join_date && best->client_id > new_cs->client_id)) {
if (best == nullptr || best->GetInfo()->join_date > new_cs->GetInfo()->join_date || (best->GetInfo()->join_date == new_cs->GetInfo()->join_date && best->client_id > new_cs->client_id)) {
best = new_cs;
}
}
}
/* Is there someone else to join? */
if (best != NULL) {
if (best != nullptr) {
/* Let the first start joining. */
best->status = STATUS_AUTHORIZED;
best->SendMap();
@@ -960,9 +946,9 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet *p)
this->status = STATUS_NEWGRFS_CHECK;
if (_grfconfig == NULL) {
if (_grfconfig == nullptr) {
/* Behave as if we received PACKET_CLIENT_NEWGRFS_CHECKED */
return this->Receive_CLIENT_NEWGRFS_CHECKED(NULL);
return this->Receive_CLIENT_NEWGRFS_CHECKED(nullptr);
}
return this->SendNewGRFCheck();
@@ -1046,7 +1032,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MAP_OK(Packet *
this->GetClientName(client_name, lastof(client_name));
NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, client_name, NULL, this->client_id);
NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, client_name, nullptr, this->client_id);
/* Mark the client as pre-active, and wait for an ACK
* so we know he is done loading and in sync with us */
@@ -1103,7 +1089,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMMAND(Packet
NetworkClientInfo *ci = this->GetInfo();
if (err != NULL) {
if (err != nullptr) {
IConsolePrintF(CC_ERROR, "WARNING: %s from client %d (IP: %s).", err, ci->client_id, this->GetClientIP());
return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
}
@@ -1169,7 +1155,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ERROR(Packet *p
DEBUG(net, 2, "'%s' reported an error and is closing its connection (%s)", client_name, str);
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, strid);
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, nullptr, strid);
FOR_ALL_CLIENT_SOCKETS(new_cs) {
if (new_cs->status > STATUS_AUTHORIZED) {
@@ -1196,7 +1182,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_QUIT(Packet *p)
this->GetClientName(client_name, lastof(client_name));
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, STR_NETWORK_MESSAGE_CLIENT_LEAVING);
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, nullptr, STR_NETWORK_MESSAGE_CLIENT_LEAVING);
FOR_ALL_CLIENT_SOCKETS(new_cs) {
if (new_cs->status > STATUS_AUTHORIZED && new_cs != this) {
@@ -1220,7 +1206,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ACK(Packet *p)
/* The client is trying to catch up with the server */
if (this->status == STATUS_PRE_ACTIVE) {
/* The client is not yet catched up? */
/* The client is not yet caught up? */
if (frame + DAY_TICKS < _frame_counter) return NETWORK_RECV_STATUS_OKAY;
/* Now he is! Unpause the game */
@@ -1276,7 +1262,7 @@ void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, co
if ((ClientID)dest == CLIENT_ID_SERVER) {
ci = NetworkClientInfo::GetByClientID(from_id);
/* Display the text locally, and that is it */
if (ci != NULL) {
if (ci != nullptr) {
NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
if (_settings_client.network.server_admin_chat) {
@@ -1298,7 +1284,7 @@ void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, co
if (from_id == CLIENT_ID_SERVER) {
ci = NetworkClientInfo::GetByClientID(from_id);
ci_to = NetworkClientInfo::GetByClientID((ClientID)dest);
if (ci != NULL && ci_to != NULL) {
if (ci != nullptr && ci_to != nullptr) {
NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), true, ci_to->client_name, msg, data);
}
} else {
@@ -1315,10 +1301,10 @@ void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, co
/* If this is false, the message is already displayed on the client who sent it. */
bool show_local = true;
/* Find all clients that belong to this company */
ci_to = NULL;
ci_to = nullptr;
FOR_ALL_CLIENT_SOCKETS(cs) {
ci = cs->GetInfo();
if (ci != NULL && ci->client_playas == (CompanyID)dest) {
if (ci != nullptr && ci->client_playas == (CompanyID)dest) {
cs->SendChat(action, from_id, false, msg, data);
if (cs->client_id == from_id) show_local = false;
ci_to = ci; // Remember a client that is in the company for company-name
@@ -1332,17 +1318,17 @@ void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, co
ci = NetworkClientInfo::GetByClientID(from_id);
ci_own = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
if (ci != NULL && ci_own != NULL && ci_own->client_playas == dest) {
if (ci != nullptr && ci_own != nullptr && ci_own->client_playas == dest) {
NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
if (from_id == CLIENT_ID_SERVER) show_local = false;
ci_to = ci_own;
}
/* There is no such client */
if (ci_to == NULL) break;
if (ci_to == nullptr) break;
/* Display the message locally (so you know you have sent it) */
if (ci != NULL && show_local) {
if (ci != nullptr && show_local) {
if (from_id == CLIENT_ID_SERVER) {
char name[NETWORK_NAME_LENGTH];
StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
@@ -1371,7 +1357,7 @@ void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, co
NetworkAdminChat(action, desttype, from_id, msg, data, from_admin);
ci = NetworkClientInfo::GetByClientID(from_id);
if (ci != NULL) {
if (ci != nullptr) {
NetworkTextMessage(action, GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
}
break;
@@ -1442,7 +1428,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_NAME(Packet
if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
if (ci != NULL) {
if (ci != nullptr) {
/* Display change */
if (NetworkFindName(client_name, lastof(client_name))) {
NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, client_name);
@@ -1605,7 +1591,7 @@ void NetworkUpdateClientInfo(ClientID client_id)
NetworkClientSocket *cs;
NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
if (ci == NULL) return;
if (ci == nullptr) return;
DEBUG(desync, 1, "client: %08x; %02x; %02x; %04x", _date, _date_fract, (int)ci->client_playas, client_id);
@@ -1726,7 +1712,7 @@ bool NetworkFindName(char *new_name, const char *last)
}
/* Check if it is the same as the server-name */
ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
if (ci != NULL) {
if (ci != nullptr) {
if (strcmp(ci->client_name, new_name) == 0) found_name = false; // name already in use
}
@@ -1757,7 +1743,7 @@ bool NetworkServerChangeClientName(ClientID client_id, const char *new_name)
}
ci = NetworkClientInfo::GetByClientID(client_id);
if (ci == NULL) return false;
if (ci == nullptr) return false;
NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, true, ci->client_name, new_name);
@@ -1792,7 +1778,7 @@ void NetworkServerSetCompanyPassword(CompanyID company_id, const char *password,
static void NetworkHandleCommandQueue(NetworkClientSocket *cs)
{
CommandPacket *cp;
while ((cp = cs->outgoing_queue.Pop()) != NULL) {
while ((cp = cs->outgoing_queue.Pop()) != nullptr) {
cs->SendCommand(cp);
free(cp);
}
@@ -1978,7 +1964,7 @@ void NetworkServerShowStatusToConsole()
NetworkClientSocket *cs;
FOR_ALL_CLIENT_SOCKETS(cs) {
NetworkClientInfo *ci = cs->GetInfo();
if (ci == NULL) continue;
if (ci == nullptr) continue;
uint lag = NetworkCalculateLag(cs);
const char *status;
@@ -2097,13 +2083,13 @@ uint NetworkServerKickOrBanIP(const char *ip, bool ban)
/* Add address to ban-list */
if (ban) {
bool contains = false;
for (char **iter = _network_ban_list.Begin(); iter != _network_ban_list.End(); iter++) {
if (strcmp(*iter, ip) == 0) {
for (const auto &iter : _network_ban_list) {
if (iter == ip) {
contains = true;
break;
}
}
if (!contains) *_network_ban_list.Append() = stredup(ip);
if (!contains) _network_ban_list.emplace_back(ip);
}
uint n = 0;
@@ -2112,7 +2098,7 @@ uint NetworkServerKickOrBanIP(const char *ip, bool ban)
NetworkClientSocket *cs;
FOR_ALL_CLIENT_SOCKETS(cs) {
if (cs->client_id == CLIENT_ID_SERVER) continue;
if (cs->client_address.IsInNetmask(const_cast<char *>(ip))) {
if (cs->client_address.IsInNetmask(ip)) {
NetworkServerKickClient(cs->client_id);
n++;
}
@@ -2145,7 +2131,7 @@ void ServerNetworkGameSocketHandler::GetClientName(char *client_name, const char
{
const NetworkClientInfo *ci = this->GetInfo();
if (ci == NULL || StrEmpty(ci->client_name)) {
if (ci == nullptr || StrEmpty(ci->client_name)) {
seprintf(client_name, last, "Client #%4d", this->client_id);
} else {
strecpy(client_name, ci->client_name, last);
@@ -2176,12 +2162,12 @@ void NetworkPrintClients()
/**
* Perform all the server specific administration of a new company.
* @param c The newly created company; can't be NULL.
* @param ci The client information of the client that made the company; can be NULL.
* @param c The newly created company; can't be nullptr.
* @param ci The client information of the client that made the company; can be nullptr.
*/
void NetworkServerNewCompany(const Company *c, NetworkClientInfo *ci)
{
assert(c != NULL);
assert(c != nullptr);
if (!_network_server) return;
@@ -2189,22 +2175,20 @@ void NetworkServerNewCompany(const Company *c, NetworkClientInfo *ci)
_network_company_states[c->index].password[0] = '\0';
NetworkServerUpdateCompanyPassworded(c->index, false);
if (ci != NULL) {
/* ci is NULL when replaying, or for AIs. In neither case there is a client. */
if (ci != nullptr) {
/* ci is nullptr when replaying, or for AIs. In neither case there is a client. */
ci->client_playas = c->index;
NetworkUpdateClientInfo(ci->client_id);
NetworkSendCommand(0, 0, 0, CMD_RENAME_PRESIDENT, NULL, ci->client_name, c->index);
NetworkSendCommand(0, 0, 0, CMD_RENAME_PRESIDENT, nullptr, ci->client_name, c->index);
}
/* Announce new company on network. */
NetworkAdminCompanyInfo(c, true);
if (ci != NULL) {
/* ci is NULL when replaying, or for AIs. In neither case there is a client.
if (ci != nullptr) {
/* ci is nullptr when replaying, or for AIs. In neither case there is a client.
We need to send Admin port update here so that they first know about the new company
and then learn about a possibly joining client (see FS#6025) */
NetworkServerSendChat(NETWORK_ACTION_COMPANY_NEW, DESTTYPE_BROADCAST, 0, "", ci->client_id, c->index + 1);
}
}
#endif /* ENABLE_NETWORK */
+18 -29
View File
@@ -12,11 +12,8 @@
#ifndef NETWORK_SERVER_H
#define NETWORK_SERVER_H
#ifdef ENABLE_NETWORK
#include "network_internal.h"
#include "core/tcp_listen.h"
#include "../thread/thread.h"
class ServerNetworkGameSocketHandler;
/** Make the code look slightly nicer/simpler. */
@@ -28,22 +25,22 @@ extern NetworkClientSocketPool _networkclientsocket_pool;
/** Class for handling the server side of the game connection. */
class ServerNetworkGameSocketHandler : public NetworkClientSocketPool::PoolItem<&_networkclientsocket_pool>, public NetworkGameSocketHandler, public TCPListenHandler<ServerNetworkGameSocketHandler, PACKET_SERVER_FULL, PACKET_SERVER_BANNED> {
protected:
virtual NetworkRecvStatus Receive_CLIENT_JOIN(Packet *p);
virtual NetworkRecvStatus Receive_CLIENT_COMPANY_INFO(Packet *p);
virtual NetworkRecvStatus Receive_CLIENT_GAME_PASSWORD(Packet *p);
virtual NetworkRecvStatus Receive_CLIENT_COMPANY_PASSWORD(Packet *p);
virtual NetworkRecvStatus Receive_CLIENT_GETMAP(Packet *p);
virtual NetworkRecvStatus Receive_CLIENT_MAP_OK(Packet *p);
virtual NetworkRecvStatus Receive_CLIENT_ACK(Packet *p);
virtual NetworkRecvStatus Receive_CLIENT_COMMAND(Packet *p);
virtual NetworkRecvStatus Receive_CLIENT_CHAT(Packet *p);
virtual NetworkRecvStatus Receive_CLIENT_SET_PASSWORD(Packet *p);
virtual NetworkRecvStatus Receive_CLIENT_SET_NAME(Packet *p);
virtual NetworkRecvStatus Receive_CLIENT_QUIT(Packet *p);
virtual NetworkRecvStatus Receive_CLIENT_ERROR(Packet *p);
virtual NetworkRecvStatus Receive_CLIENT_RCON(Packet *p);
virtual NetworkRecvStatus Receive_CLIENT_NEWGRFS_CHECKED(Packet *p);
virtual NetworkRecvStatus Receive_CLIENT_MOVE(Packet *p);
NetworkRecvStatus Receive_CLIENT_JOIN(Packet *p) override;
NetworkRecvStatus Receive_CLIENT_COMPANY_INFO(Packet *p) override;
NetworkRecvStatus Receive_CLIENT_GAME_PASSWORD(Packet *p) override;
NetworkRecvStatus Receive_CLIENT_COMPANY_PASSWORD(Packet *p) override;
NetworkRecvStatus Receive_CLIENT_GETMAP(Packet *p) override;
NetworkRecvStatus Receive_CLIENT_MAP_OK(Packet *p) override;
NetworkRecvStatus Receive_CLIENT_ACK(Packet *p) override;
NetworkRecvStatus Receive_CLIENT_COMMAND(Packet *p) override;
NetworkRecvStatus Receive_CLIENT_CHAT(Packet *p) override;
NetworkRecvStatus Receive_CLIENT_SET_PASSWORD(Packet *p) override;
NetworkRecvStatus Receive_CLIENT_SET_NAME(Packet *p) override;
NetworkRecvStatus Receive_CLIENT_QUIT(Packet *p) override;
NetworkRecvStatus Receive_CLIENT_ERROR(Packet *p) override;
NetworkRecvStatus Receive_CLIENT_RCON(Packet *p) override;
NetworkRecvStatus Receive_CLIENT_NEWGRFS_CHECKED(Packet *p) override;
NetworkRecvStatus Receive_CLIENT_MOVE(Packet *p) override;
NetworkRecvStatus SendCompanyInfo();
NetworkRecvStatus SendNewGRFCheck();
@@ -81,8 +78,8 @@ public:
ServerNetworkGameSocketHandler(SOCKET s);
~ServerNetworkGameSocketHandler();
virtual Packet *ReceivePacket();
NetworkRecvStatus CloseConnection(NetworkRecvStatus status);
virtual Packet *ReceivePacket() override;
NetworkRecvStatus CloseConnection(NetworkRecvStatus status) override;
void GetClientName(char *client_name, const char *last) const;
NetworkRecvStatus SendMap();
@@ -138,12 +135,4 @@ void NetworkServerUpdateCompanyPassworded(CompanyID company_id, bool passworded)
*/
#define FOR_ALL_CLIENT_SOCKETS(var) FOR_ALL_CLIENT_SOCKETS_FROM(var, 0)
#else /* ENABLE_NETWORK */
/* Network function stubs when networking is disabled */
static inline void NetworkServerMonthlyLoop() {}
static inline void NetworkServerYearlyLoop() {}
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_SERVER_H */
+1 -4
View File
@@ -14,8 +14,6 @@
#include "core/game.h"
#ifdef ENABLE_NETWORK
/** How many clients can we have */
static const uint MAX_CLIENTS = 255;
@@ -40,7 +38,7 @@ enum NetworkVehicleType {
};
/** 'Unique' identifier to be given to clients */
enum ClientID {
enum ClientID : uint32 {
INVALID_CLIENT_ID = 0, ///< Client is not part of anything
CLIENT_ID_SERVER = 1, ///< Servers always have this ID
CLIENT_ID_FIRST = 2, ///< The first client ID
@@ -130,5 +128,4 @@ enum NetworkErrorCode {
NETWORK_ERROR_END,
};
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_TYPE_H */
+51 -91
View File
@@ -14,8 +14,6 @@
* communication before the game is being joined.
*/
#ifdef ENABLE_NETWORK
#include "../stdafx.h"
#include "../date_func.h"
#include "../map_func.h"
@@ -26,18 +24,19 @@
#include "network.h"
#include "../core/endian_func.hpp"
#include "../company_base.h"
#include "../thread/thread.h"
#include "../thread.h"
#include "../rev.h"
#include "../newgrf_text.h"
#include "../strings_func.h"
#include "table/strings.h"
#include <mutex>
#include "core/udp.h"
#include "../safeguards.h"
/** Mutex for all out threaded udp resolution and such. */
static ThreadMutex *_network_udp_mutex = ThreadMutex::New();
static std::mutex _network_udp_mutex;
/** Session key to register ourselves to the master server */
static uint64 _session_key = 0;
@@ -46,25 +45,9 @@ static const uint32 ADVERTISE_NORMAL_INTERVAL = 15 * 60 * 1000; ///< interval be
static const uint32 ADVERTISE_RETRY_INTERVAL = 10 * 1000; ///< re-advertise when no response after this many ms (10 seconds)
static const uint32 ADVERTISE_RETRY_TIMES = 3; ///< give up re-advertising after this much failed retries
NetworkUDPSocketHandler *_udp_client_socket = NULL; ///< udp client socket
NetworkUDPSocketHandler *_udp_server_socket = NULL; ///< udp server socket
NetworkUDPSocketHandler *_udp_master_socket = NULL; ///< udp master socket
/** Simpler wrapper struct for NetworkUDPQueryServerThread */
struct NetworkUDPQueryServerInfo : NetworkAddress {
bool manually; ///< Did we connect manually or not?
/**
* Create the structure.
* @param address The address of the server to query.
* @param manually Whether the address was entered manually.
*/
NetworkUDPQueryServerInfo(const NetworkAddress &address, bool manually) :
NetworkAddress(address),
manually(manually)
{
}
};
NetworkUDPSocketHandler *_udp_client_socket = nullptr; ///< udp client socket
NetworkUDPSocketHandler *_udp_server_socket = nullptr; ///< udp server socket
NetworkUDPSocketHandler *_udp_master_socket = nullptr; ///< udp master socket
/**
* Helper function doing the actual work for querying the server.
@@ -72,33 +55,21 @@ struct NetworkUDPQueryServerInfo : NetworkAddress {
* @param needs_mutex Whether we need to acquire locks when sending the packet or not.
* @param manually Whether the address was entered manually.
*/
static void NetworkUDPQueryServer(NetworkAddress *address, bool needs_mutex, bool manually)
static void DoNetworkUDPQueryServer(NetworkAddress &address, bool needs_mutex, bool manually)
{
/* Clear item in gamelist */
NetworkGameList *item = CallocT<NetworkGameList>(1);
address->GetAddressAsString(item->info.server_name, lastof(item->info.server_name));
strecpy(item->info.hostname, address->GetHostname(), lastof(item->info.hostname));
item->address = *address;
address.GetAddressAsString(item->info.server_name, lastof(item->info.server_name));
strecpy(item->info.hostname, address.GetHostname(), lastof(item->info.hostname));
item->address = address;
item->manually = manually;
NetworkGameListAddItemDelayed(item);
if (needs_mutex) _network_udp_mutex->BeginCritical();
std::unique_lock<std::mutex> lock(_network_udp_mutex, std::defer_lock);
if (needs_mutex) lock.lock();
/* Init the packet */
Packet p(PACKET_UDP_CLIENT_FIND_SERVER);
if (_udp_client_socket != NULL) _udp_client_socket->SendPacket(&p, address);
if (needs_mutex) _network_udp_mutex->EndCritical();
}
/**
* Threaded part for resolving the IP of a server and querying it.
* @param pntr the NetworkUDPQueryServerInfo.
*/
static void NetworkUDPQueryServerThread(void *pntr)
{
NetworkUDPQueryServerInfo *info = (NetworkUDPQueryServerInfo*)pntr;
NetworkUDPQueryServer(info, true, info->manually);
delete info;
if (_udp_client_socket != nullptr) _udp_client_socket->SendPacket(&p, &address);
}
/**
@@ -108,9 +79,8 @@ static void NetworkUDPQueryServerThread(void *pntr)
*/
void NetworkUDPQueryServer(NetworkAddress address, bool manually)
{
NetworkUDPQueryServerInfo *info = new NetworkUDPQueryServerInfo(address, manually);
if (address.IsResolved() || !ThreadObject::New(NetworkUDPQueryServerThread, info, NULL, "ottd:udp-query")) {
NetworkUDPQueryServerThread(info);
if (address.IsResolved() || !StartNewThread(nullptr, "ottd:udp-query", &DoNetworkUDPQueryServer, std::move(address), true, std::move(manually))) {
DoNetworkUDPQueryServer(address, true, manually);
}
}
@@ -119,8 +89,8 @@ void NetworkUDPQueryServer(NetworkAddress address, bool manually)
/** Helper class for connecting to the master server. */
class MasterNetworkUDPSocketHandler : public NetworkUDPSocketHandler {
protected:
virtual void Receive_MASTER_ACK_REGISTER(Packet *p, NetworkAddress *client_addr);
virtual void Receive_MASTER_SESSION_KEY(Packet *p, NetworkAddress *client_addr);
void Receive_MASTER_ACK_REGISTER(Packet *p, NetworkAddress *client_addr) override;
void Receive_MASTER_SESSION_KEY(Packet *p, NetworkAddress *client_addr) override;
public:
/**
* Create the socket.
@@ -150,9 +120,9 @@ void MasterNetworkUDPSocketHandler::Receive_MASTER_SESSION_KEY(Packet *p, Networ
/** Helper class for handling all server side communication. */
class ServerNetworkUDPSocketHandler : public NetworkUDPSocketHandler {
protected:
virtual void Receive_CLIENT_FIND_SERVER(Packet *p, NetworkAddress *client_addr);
virtual void Receive_CLIENT_DETAIL_INFO(Packet *p, NetworkAddress *client_addr);
virtual void Receive_CLIENT_GET_NEWGRFS(Packet *p, NetworkAddress *client_addr);
void Receive_CLIENT_FIND_SERVER(Packet *p, NetworkAddress *client_addr) override;
void Receive_CLIENT_DETAIL_INFO(Packet *p, NetworkAddress *client_addr) override;
void Receive_CLIENT_GET_NEWGRFS(Packet *p, NetworkAddress *client_addr) override;
public:
/**
* Create the socket.
@@ -291,7 +261,7 @@ void ServerNetworkUDPSocketHandler::Receive_CLIENT_GET_NEWGRFS(Packet *p, Networ
/* Find the matching GRF file */
f = FindGRFConfig(c.grfid, FGCM_EXACT, c.md5sum);
if (f == NULL) continue; // The GRF is unknown to this server
if (f == nullptr) continue; // The GRF is unknown to this server
/* If the reply might exceed the size of the packet, only reply
* the current list and do not send the other data.
@@ -326,10 +296,10 @@ void ServerNetworkUDPSocketHandler::Receive_CLIENT_GET_NEWGRFS(Packet *p, Networ
/** Helper class for handling all client side communication. */
class ClientNetworkUDPSocketHandler : public NetworkUDPSocketHandler {
protected:
virtual void Receive_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr);
virtual void Receive_MASTER_RESPONSE_LIST(Packet *p, NetworkAddress *client_addr);
virtual void Receive_SERVER_NEWGRFS(Packet *p, NetworkAddress *client_addr);
virtual void HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config);
void Receive_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr) override;
void Receive_MASTER_RESPONSE_LIST(Packet *p, NetworkAddress *client_addr) override;
void Receive_SERVER_NEWGRFS(Packet *p, NetworkAddress *client_addr) override;
void HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config) override;
public:
virtual ~ClientNetworkUDPSocketHandler() {}
};
@@ -362,7 +332,7 @@ void ClientNetworkUDPSocketHandler::Receive_SERVER_RESPONSE(Packet *p, NetworkAd
const GRFConfig *c;
uint in_request_count = 0;
for (c = item->info.grfconfig; c != NULL; c = c->next) {
for (c = item->info.grfconfig; c != nullptr; c = c->next) {
if (c->status == GCS_NOT_FOUND) item->info.compatible = false;
if (c->status != GCS_NOT_FOUND || strcmp(c->GetName(), UNKNOWN_GRF_NAME_PLACEHOLDER) != 0) continue;
in_request[in_request_count] = c;
@@ -430,7 +400,7 @@ void ClientNetworkUDPSocketHandler::Receive_MASTER_RESPONSE_LIST(Packet *p, Netw
/* Somehow we reached the end of the packet */
if (this->HasClientQuit()) return;
NetworkUDPQueryServer(&addr, false, false);
DoNetworkUDPQueryServer(addr, false, false);
}
}
}
@@ -461,7 +431,7 @@ void ClientNetworkUDPSocketHandler::Receive_SERVER_NEWGRFS(Packet *p, NetworkAdd
* If it exists and not resolved yet, then name of the fake GRF is
* overwritten with the name from the reply. */
GRFTextWrapper *unknown_name = FindUnknownGRFName(c.grfid, c.md5sum, false);
if (unknown_name != NULL && strcmp(GetGRFStringFromGRFText(unknown_name->text), UNKNOWN_GRF_NAME_PLACEHOLDER) == 0) {
if (unknown_name != nullptr && strcmp(GetGRFStringFromGRFText(unknown_name->text), UNKNOWN_GRF_NAME_PLACEHOLDER) == 0) {
AddGRFTextToList(&unknown_name->text, name);
}
}
@@ -471,7 +441,7 @@ void ClientNetworkUDPSocketHandler::HandleIncomingNetworkGameInfoGRFConfig(GRFCo
{
/* Find the matching GRF file */
const GRFConfig *f = FindGRFConfig(config->ident.grfid, FGCM_EXACT, config->ident.md5sum);
if (f == NULL) {
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 */
@@ -497,12 +467,12 @@ void ClientNetworkUDPSocketHandler::HandleIncomingNetworkGameInfoGRFConfig(GRFCo
/** Broadcast to all ips */
static void NetworkUDPBroadCast(NetworkUDPSocketHandler *socket)
{
for (NetworkAddress *addr = _broadcast_list.Begin(); addr != _broadcast_list.End(); addr++) {
for (NetworkAddress &addr : _broadcast_list) {
Packet p(PACKET_UDP_CLIENT_FIND_SERVER);
DEBUG(net, 4, "[udp] broadcasting to %s", addr->GetHostname());
DEBUG(net, 4, "[udp] broadcasting to %s", addr.GetHostname());
socket->SendPacket(&p, addr, true, true);
socket->SendPacket(&p, &addr, true, true);
}
}
@@ -536,9 +506,8 @@ void NetworkUDPSearchGame()
/**
* Thread entry point for de-advertising.
* @param pntr unused.
*/
static void NetworkUDPRemoveAdvertiseThread(void *pntr)
static void NetworkUDPRemoveAdvertiseThread()
{
DEBUG(net, 1, "[udp] removing advertise from master server");
@@ -551,9 +520,8 @@ static void NetworkUDPRemoveAdvertiseThread(void *pntr)
p.Send_uint8 (NETWORK_MASTER_SERVER_VERSION);
p.Send_uint16(_settings_client.network.server_port);
_network_udp_mutex->BeginCritical();
if (_udp_master_socket != NULL) _udp_master_socket->SendPacket(&p, &out_addr, true);
_network_udp_mutex->EndCritical();
std::lock_guard<std::mutex> lock(_network_udp_mutex);
if (_udp_master_socket != nullptr) _udp_master_socket->SendPacket(&p, &out_addr, true);
}
/**
@@ -565,16 +533,15 @@ void NetworkUDPRemoveAdvertise(bool blocking)
/* Check if we are advertising */
if (!_networking || !_network_server || !_network_udp_server) return;
if (blocking || !ThreadObject::New(NetworkUDPRemoveAdvertiseThread, NULL, NULL, "ottd:udp-advert")) {
NetworkUDPRemoveAdvertiseThread(NULL);
if (blocking || !StartNewThread(nullptr, "ottd:udp-advert", &NetworkUDPRemoveAdvertiseThread)) {
NetworkUDPRemoveAdvertiseThread();
}
}
/**
* Thread entry point for advertising.
* @param pntr unused.
*/
static void NetworkUDPAdvertiseThread(void *pntr)
static void NetworkUDPAdvertiseThread()
{
/* Find somewhere to send */
NetworkAddress out_addr(NETWORK_MASTER_SERVER_HOST, NETWORK_MASTER_SERVER_PORT);
@@ -605,9 +572,8 @@ static void NetworkUDPAdvertiseThread(void *pntr)
p.Send_uint16(_settings_client.network.server_port);
p.Send_uint64(_session_key);
_network_udp_mutex->BeginCritical();
if (_udp_master_socket != NULL) _udp_master_socket->SendPacket(&p, &out_addr, true);
_network_udp_mutex->EndCritical();
std::lock_guard<std::mutex> lock(_network_udp_mutex);
if (_udp_master_socket != nullptr) _udp_master_socket->SendPacket(&p, &out_addr, true);
}
/**
@@ -648,8 +614,8 @@ void NetworkUDPAdvertise()
if (_next_advertisement < _last_advertisement) _next_advertisement = UINT32_MAX;
if (_next_retry < _last_advertisement) _next_retry = UINT32_MAX;
if (!ThreadObject::New(NetworkUDPAdvertiseThread, NULL, NULL, "ottd:udp-advert")) {
NetworkUDPAdvertiseThread(NULL);
if (!StartNewThread(nullptr, "ottd:udp-advert", &NetworkUDPAdvertiseThread)) {
NetworkUDPAdvertiseThread();
}
}
@@ -657,12 +623,12 @@ void NetworkUDPAdvertise()
void NetworkUDPInitialize()
{
/* If not closed, then do it. */
if (_udp_server_socket != NULL) NetworkUDPClose();
if (_udp_server_socket != nullptr) NetworkUDPClose();
DEBUG(net, 1, "[udp] initializing listeners");
assert(_udp_client_socket == NULL && _udp_server_socket == NULL && _udp_master_socket == NULL);
assert(_udp_client_socket == nullptr && _udp_server_socket == nullptr && _udp_master_socket == nullptr);
_network_udp_mutex->BeginCritical();
std::lock_guard<std::mutex> lock(_network_udp_mutex);
_udp_client_socket = new ClientNetworkUDPSocketHandler();
@@ -670,29 +636,27 @@ void NetworkUDPInitialize()
GetBindAddresses(&server, _settings_client.network.server_port);
_udp_server_socket = new ServerNetworkUDPSocketHandler(&server);
server.Clear();
server.clear();
GetBindAddresses(&server, 0);
_udp_master_socket = new MasterNetworkUDPSocketHandler(&server);
_network_udp_server = false;
_network_udp_broadcast = 0;
_network_udp_mutex->EndCritical();
}
/** Close all UDP related stuff. */
void NetworkUDPClose()
{
_network_udp_mutex->BeginCritical();
std::lock_guard<std::mutex> lock(_network_udp_mutex);
_udp_server_socket->Close();
_udp_master_socket->Close();
_udp_client_socket->Close();
delete _udp_client_socket;
delete _udp_server_socket;
delete _udp_master_socket;
_udp_client_socket = NULL;
_udp_server_socket = NULL;
_udp_master_socket = NULL;
_network_udp_mutex->EndCritical();
_udp_client_socket = nullptr;
_udp_server_socket = nullptr;
_udp_master_socket = nullptr;
_network_udp_server = false;
_network_udp_broadcast = 0;
@@ -702,7 +666,7 @@ void NetworkUDPClose()
/** Receive the UDP packets. */
void NetworkBackgroundUDPLoop()
{
_network_udp_mutex->BeginCritical();
std::lock_guard<std::mutex> lock(_network_udp_mutex);
if (_network_udp_server) {
_udp_server_socket->ReceivePackets();
@@ -711,8 +675,4 @@ void NetworkBackgroundUDPLoop()
_udp_client_socket->ReceivePackets();
if (_network_udp_broadcast > 0) _network_udp_broadcast--;
}
_network_udp_mutex->EndCritical();
}
#endif /* ENABLE_NETWORK */
-4
View File
@@ -12,8 +12,6 @@
#ifndef NETWORK_UDP_H
#define NETWORK_UDP_H
#ifdef ENABLE_NETWORK
#include "core/address.h"
void NetworkUDPInitialize();
@@ -25,6 +23,4 @@ void NetworkUDPRemoveAdvertise(bool blocking);
void NetworkUDPClose();
void NetworkBackgroundUDPLoop();
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_UDP_H */