Changeset - r5624:8f8d1f8d3a74
[Not reviewed]
master
0 17 0
rubidium - 18 years ago 2007-01-12 20:19:49
rubidium@openttd.org
(svn r8083) -Codechange: make a NetworkSocketHandler as base for all sockets and move a little of NetworkClientState functionality to the NetworkSocketHandler. Move the rest of the NetworkClientState to the new NetworkTCPSocketHandler class/struct, which is not yet implemented in an object oriented manner. The UDP socket handler now extends the NetworkSocketHandler instead of having a reference to a NetworkClientState.
17 files changed with 306 insertions and 270 deletions:
0 comments (0 inline, 0 general)
src/console_cmds.cpp
Show inline comments
 
@@ -547,13 +547,13 @@ DEF_CONSOLE_CMD(ConStatus)
 
		"loading map",
 
		"map done",
 
		"ready",
 
		"active"
 
	};
 

	
 
	const NetworkClientState *cs;
 
	NetworkTCPSocketHandler *cs;
 

	
 
	if (argc == 0) {
 
		IConsoleHelp("List the status of all clients connected to the server. Usage 'status'");
 
		return true;
 
	}
 

	
 
@@ -669,13 +669,13 @@ DEF_CONSOLE_CMD(ConKick)
 
	return true;
 
}
 

	
 
DEF_CONSOLE_CMD(ConResetCompany)
 
{
 
	const Player *p;
 
	const NetworkClientState *cs;
 
	NetworkTCPSocketHandler *cs;
 
	const NetworkClientInfo *ci;
 
	PlayerID index;
 

	
 
	if (argc == 0) {
 
		IConsoleHelp("Remove an idle company from the game. Usage: 'reset_company <company-id>'");
 
		IConsoleHelp("For company-id's, see the list of companies from the dropdown menu. Player 1 is 1, etc.");
src/economy.cpp
Show inline comments
 
@@ -424,13 +424,13 @@ static void PlayersCheckBankrupt(Player 
 
				}
 

	
 
#ifdef ENABLE_NETWORK
 
				/* The server has to handle all administrative issues, for example
 
				 * updating and notifying all clients of what has happened */
 
				if (_network_server) {
 
					const NetworkClientState *cs;
 
					NetworkTCPSocketHandler *cs;
 
					NetworkClientInfo *ci = NetworkFindClientInfoFromIndex(NETWORK_SERVER_INDEX);
 

	
 
					/* The server has just gone belly-up, mark it as spectator */
 
					if (owner == ci->client_playas) {
 
						ci->client_playas = PLAYER_SPECTATOR;
 
						NetworkUpdateClientInfo(NETWORK_SERVER_INDEX);
src/network/core/core.h
Show inline comments
 
@@ -2,12 +2,64 @@
 

	
 
#ifndef NETWORK_CORE_H
 
#define NETWORK_CORE_H
 

	
 
#ifdef ENABLE_NETWORK
 

	
 
#include "os_abstraction.h"
 

	
 
bool NetworkCoreInitialize(void);
 
void NetworkCoreShutdown(void);
 

	
 
typedef enum {
 
	NETWORK_RECV_STATUS_OKAY,             ///< Everything is okay
 
	NETWORK_RECV_STATUS_DESYNC,           ///< A desync did occur
 
	NETWORK_RECV_STATUS_SAVEGAME,         ///< Something went wrong (down)loading the savegame
 
	NETWORK_RECV_STATUS_CONN_LOST,        ///< The conection is 'just' lost
 
	NETWORK_RECV_STATUS_MALFORMED_PACKET, ///< We apparently send a malformed packet
 
	NETWORK_RECV_STATUS_SERVER_ERROR,     ///< The server told us we made an error
 
	NETWORK_RECV_STATUS_SERVER_FULL,      ///< The server is full
 
	NETWORK_RECV_STATUS_SERVER_BANNED,    ///< The server has banned us
 
	NETWORK_RECV_STATUS_CLOSE_QUERY,      ///< Done quering the server
 
} NetworkRecvStatus;
 

	
 
/**
 
 * SocketHandler for all network sockets in OpenTTD.
 
 */
 
class NetworkSocketHandler {
 
public:
 
	/* TODO: make socket & has_quit protected once the TCP stuff
 
	 *is in a real class too */
 
	bool has_quit; ///< Whether the current client has quit/send a bad packet
 
	SOCKET sock;   ///< The socket currently connected to
 
public:
 
	NetworkSocketHandler() { this->sock = INVALID_SOCKET; this->has_quit = false; }
 
	virtual ~NetworkSocketHandler() { this->Close(); }
 

	
 
	/** Really close the socket */
 
	virtual void Close() {}
 

	
 
	/**
 
	 * Close the current connection; for TCP this will be mostly equivalent
 
	 * to Close(), but for UDP it just means the packet has to be dropped.
 
	 * @return new status of the connection.
 
	 */
 
	virtual NetworkRecvStatus CloseConnection() { this->has_quit = true; return NETWORK_RECV_STATUS_OKAY; }
 

	
 
	/**
 
	 * Whether this socket is currently bound to a socket.
 
	 * @return true when the socket is bound, false otherwise
 
	 */
 
	bool IsConnected() { return this->sock != INVALID_SOCKET; }
 

	
 
	/**
 
	 * Whether the current client connected to the socket has quit.
 
	 * In the case of UDP, for example, once a client quits (send bad
 
	 * data), the socket in not closed; only the packet is dropped.
 
	 * @return true when the current client has quit, false otherwise
 
	 */
 
	bool HasClientQuit() { return this->has_quit; }
 
};
 

	
 
#endif /* ENABLE_NETWORK */
 

	
 
#endif /* NETWORK_CORE_H */
src/network/core/packet.cpp
Show inline comments
 
@@ -3,13 +3,12 @@
 
#ifdef ENABLE_NETWORK
 

	
 
#include "../../stdafx.h"
 
#include "../../macros.h"
 
#include "../../string.h"
 
#include "../../helpers.hpp"
 
#include "../network_data.h"
 

	
 
#include "packet.h"
 

	
 
/**
 
 * @file packet.h Basic functions to create, fill and read packets.
 
 */
 
@@ -108,23 +107,21 @@ void NetworkSend_string(Packet *packet, 
 
 * Receiving commands
 
 * Again, the next couple of functions are endian-safe
 
 *  see the comment before NetworkSend_uint8 for more info.
 
 */
 

	
 

	
 
extern NetworkRecvStatus CloseConnection(NetworkClientState *cs);
 

	
 
/** Is it safe to read from the packet, i.e. didn't we run over the buffer ? */
 
static inline bool CanReadFromPacket(NetworkClientState *cs, const Packet *packet, const uint bytes_to_read)
 
static inline bool CanReadFromPacket(NetworkSocketHandler *cs, const Packet *packet, const uint bytes_to_read)
 
{
 
	/* Don't allow reading from a closed socket */
 
	if (HasClientQuit(cs)) return false;
 
	/* Don't allow reading from a quit client/client who send bad data */
 
	if (cs->HasClientQuit()) return false;
 

	
 
	/* Check if variable is within packet-size */
 
	if (packet->pos + bytes_to_read > packet->size) {
 
		CloseConnection(cs);
 
		cs->CloseConnection();
 
		return false;
 
	}
 

	
 
	return true;
 
}
 

	
 
@@ -135,47 +132,47 @@ static inline bool CanReadFromPacket(Net
 
void NetworkRecv_ReadPacketSize(Packet *packet)
 
{
 
	packet->size  = (uint16)packet->buffer[0];
 
	packet->size += (uint16)packet->buffer[1] << 8;
 
}
 

	
 
uint8 NetworkRecv_uint8(NetworkClientState *cs, Packet *packet)
 
uint8 NetworkRecv_uint8(NetworkSocketHandler *cs, Packet *packet)
 
{
 
	uint8 n;
 

	
 
	if (!CanReadFromPacket(cs, packet, sizeof(n))) return 0;
 

	
 
	n = packet->buffer[packet->pos++];
 
	return n;
 
}
 

	
 
uint16 NetworkRecv_uint16(NetworkClientState *cs, Packet *packet)
 
uint16 NetworkRecv_uint16(NetworkSocketHandler *cs, Packet *packet)
 
{
 
	uint16 n;
 

	
 
	if (!CanReadFromPacket(cs, packet, sizeof(n))) return 0;
 

	
 
	n  = (uint16)packet->buffer[packet->pos++];
 
	n += (uint16)packet->buffer[packet->pos++] << 8;
 
	return n;
 
}
 

	
 
uint32 NetworkRecv_uint32(NetworkClientState *cs, Packet *packet)
 
uint32 NetworkRecv_uint32(NetworkSocketHandler *cs, Packet *packet)
 
{
 
	uint32 n;
 

	
 
	if (!CanReadFromPacket(cs, packet, sizeof(n))) return 0;
 

	
 
	n  = (uint32)packet->buffer[packet->pos++];
 
	n += (uint32)packet->buffer[packet->pos++] << 8;
 
	n += (uint32)packet->buffer[packet->pos++] << 16;
 
	n += (uint32)packet->buffer[packet->pos++] << 24;
 
	return n;
 
}
 

	
 
uint64 NetworkRecv_uint64(NetworkClientState *cs, Packet *packet)
 
uint64 NetworkRecv_uint64(NetworkSocketHandler *cs, Packet *packet)
 
{
 
	uint64 n;
 

	
 
	if (!CanReadFromPacket(cs, packet, sizeof(n))) return 0;
 

	
 
	n  = (uint64)packet->buffer[packet->pos++];
 
@@ -187,19 +184,19 @@ uint64 NetworkRecv_uint64(NetworkClientS
 
	n += (uint64)packet->buffer[packet->pos++] << 48;
 
	n += (uint64)packet->buffer[packet->pos++] << 56;
 
	return n;
 
}
 

	
 
/** Reads a string till it finds a '\0' in the stream */
 
void NetworkRecv_string(NetworkClientState *cs, Packet *p, char *buffer, size_t size)
 
void NetworkRecv_string(NetworkSocketHandler *cs, Packet *p, char *buffer, size_t size)
 
{
 
	PacketSize pos;
 
	char *bufp = buffer;
 

	
 
	/* Don't allow reading from a closed socket */
 
	if (HasClientQuit(cs)) return;
 
	if (cs->HasClientQuit()) return;
 

	
 
	pos = p->pos;
 
	while (--size > 0 && pos < p->size && (*buffer++ = p->buffer[pos++]) != '\0') {}
 

	
 
	if (size == 0 || pos == p->size) {
 
		*buffer = '\0';
src/network/core/packet.h
Show inline comments
 
@@ -3,29 +3,18 @@
 
#ifndef NETWORK_CORE_PACKET_H
 
#define NETWORK_CORE_PACKET_H
 

	
 
#ifdef ENABLE_NETWORK
 

	
 
#include "config.h"
 
#include "core.h"
 

	
 
/**
 
 * @file packet.h Basic functions to create, fill and read packets.
 
 */
 

	
 
typedef struct NetworkClientState NetworkClientState;
 

	
 
/**
 
 * Queries the network client state struct to determine whether
 
 * the client has quit. It indirectly also queries whether the
 
 * packet is corrupt as the connection will be closed if it is
 
 * reading beyond the boundary of the received packet.
 
 * @param cs the state to query
 
 * @param true if the connection should be considered dropped
 
 */
 
bool HasClientQuit(const NetworkClientState *cs);
 

	
 
typedef uint16 PacketSize; ///< Size of the whole packet.
 
typedef uint8  PacketType; ///< Identifier for the packet
 

	
 
/**
 
 * Internal entity of a packet. As everything is sent as a packet,
 
 * all network communication will need to call the functions that
 
@@ -55,15 +44,15 @@ void NetworkSend_uint8 (Packet *packet, 
 
void NetworkSend_uint16(Packet *packet, uint16 data);
 
void NetworkSend_uint32(Packet *packet, uint32 data);
 
void NetworkSend_uint64(Packet *packet, uint64 data);
 
void NetworkSend_string(Packet *packet, const char* data);
 

	
 
void NetworkRecv_ReadPacketSize(Packet *packet);
 
uint8  NetworkRecv_uint8 (NetworkClientState *cs, Packet *packet);
 
uint16 NetworkRecv_uint16(NetworkClientState *cs, Packet *packet);
 
uint32 NetworkRecv_uint32(NetworkClientState *cs, Packet *packet);
 
uint64 NetworkRecv_uint64(NetworkClientState *cs, Packet *packet);
 
void   NetworkRecv_string(NetworkClientState *cs, Packet *packet, char* buffer, size_t size);
 
uint8  NetworkRecv_uint8 (NetworkSocketHandler *cs, Packet *packet);
 
uint16 NetworkRecv_uint16(NetworkSocketHandler *cs, Packet *packet);
 
uint32 NetworkRecv_uint32(NetworkSocketHandler *cs, Packet *packet);
 
uint64 NetworkRecv_uint64(NetworkSocketHandler *cs, Packet *packet);
 
void   NetworkRecv_string(NetworkSocketHandler *cs, Packet *packet, char* buffer, size_t size);
 

	
 
#endif /* ENABLE_NETWORK */
 

	
 
#endif /* NETWORK_CORE_PACKET_H */
src/network/core/tcp.cpp
Show inline comments
 
@@ -15,23 +15,44 @@
 
#include "../../helpers.hpp"
 

	
 
/**
 
 * @file tcp.c Basic functions to receive and send TCP packets.
 
 */
 

	
 
/** Very ugly temporary hack !!! */
 
void NetworkTCPSocketHandler::Initialize()
 
{
 
	this->sock              = INVALID_SOCKET;
 

	
 
	this->index             = 0;
 
	this->last_frame        = 0;
 
	this->last_frame_server = 0;
 
	this->lag_test          = 0;
 

	
 
	this->status            = STATUS_INACTIVE;
 
	this->has_quit          = false;
 
	this->writable          = false;
 

	
 
	this->packet_queue      = NULL;
 
	this->packet_recv       = NULL;
 

	
 
	this->command_queue     = NULL;
 
}
 

	
 
/**
 
 * Functions to help NetworkRecv_Packet/NetworkSend_Packet a bit
 
 *  A socket can make errors. When that happens this handles what to do.
 
 * For clients: close connection and drop back to main-menu
 
 * For servers: close connection and that is it
 
 * @param cs the client to close the connection of
 
 * @return the new status
 
 * TODO: needs to be splitted when using client and server socket packets
 
 */
 
NetworkRecvStatus CloseConnection(NetworkClientState *cs)
 
NetworkRecvStatus NetworkTCPSocketHandler::CloseConnection()
 
{
 
	NetworkCloseClient(cs);
 
	NetworkCloseClient(this);
 

	
 
	/* Clients drop back to the main menu */
 
	if (!_network_server && _networking) {
 
		_switch_mode = SM_MENU;
 
		_networking = false;
 
		_switch_mode_errorstr = STR_NETWORK_ERR_LOSTCONNECTION;
 
@@ -40,29 +61,19 @@ NetworkRecvStatus CloseConnection(Networ
 
	}
 

	
 
	return NETWORK_RECV_STATUS_OKAY;
 
}
 

	
 
/**
 
 * Whether the client has quit or not (used in packet.c)
 
 * @param cs the client to check
 
 * @return true if the client has quit
 
 */
 
bool HasClientQuit(const NetworkClientState *cs)
 
{
 
	return cs->has_quit;
 
}
 

	
 
/**
 
 * This function puts the packet in the send-queue and it is send as
 
 * soon as possible. This is the next tick, or maybe one tick later
 
 * if the OS-network-buffer is full)
 
 * @param packet the packet to send
 
 * @param cs     the client to send to
 
 */
 
void NetworkSend_Packet(Packet *packet, NetworkClientState *cs)
 
void NetworkSend_Packet(Packet *packet, NetworkTCPSocketHandler *cs)
 
{
 
	Packet *p;
 
	assert(packet != NULL);
 

	
 
	packet->pos = 0;
 
	packet->next = NULL;
 
@@ -86,37 +97,37 @@ void NetworkSend_Packet(Packet *packet, 
 
 *   1) all packets are send (queue is empty)
 
 *   2) the OS reports back that it can not send any more
 
 *      data right now (full network-buffer, it happens ;))
 
 *   3) sending took too long
 
 * @param cs the client to send the packets for
 
 */
 
bool NetworkSend_Packets(NetworkClientState *cs)
 
bool NetworkSend_Packets(NetworkTCPSocketHandler *cs)
 
{
 
	ssize_t res;
 
	Packet *p;
 

	
 
	/* We can not write to this socket!! */
 
	if (!cs->writable) return false;
 
	if (cs->socket == INVALID_SOCKET) return false;
 
	if (!cs->IsConnected()) return false;
 

	
 
	p = cs->packet_queue;
 
	while (p != NULL) {
 
		res = send(cs->socket, (const char*)p->buffer + p->pos, p->size - p->pos, 0);
 
		res = send(cs->sock, (const char*)p->buffer + p->pos, p->size - p->pos, 0);
 
		if (res == -1) {
 
			int err = GET_LAST_ERROR();
 
			if (err != EWOULDBLOCK) {
 
				/* Something went wrong.. close client! */
 
				DEBUG(net, 0, "send failed with error %d", err);
 
				CloseConnection(cs);
 
				cs->CloseConnection();
 
				return false;
 
			}
 
			return true;
 
		}
 
		if (res == 0) {
 
			/* Client/server has left us :( */
 
			CloseConnection(cs);
 
			cs->CloseConnection();
 
			return false;
 
		}
 

	
 
		p->pos += res;
 

	
 
		/* Is this packet sent? */
 
@@ -136,20 +147,20 @@ bool NetworkSend_Packets(NetworkClientSt
 
/**
 
 * Receives a packet for the given client
 
 * @param cs     the client to (try to) receive a packet for
 
 * @param status the variable to store the status into
 
 * @return the received packet (or NULL when it didn't receive one)
 
 */
 
Packet *NetworkRecv_Packet(NetworkClientState *cs, NetworkRecvStatus *status)
 
Packet *NetworkRecv_Packet(NetworkTCPSocketHandler *cs, NetworkRecvStatus *status)
 
{
 
	ssize_t res;
 
	Packet *p;
 

	
 
	*status = NETWORK_RECV_STATUS_OKAY;
 

	
 
	if (cs->socket == INVALID_SOCKET) return NULL;
 
	if (!cs->IsConnected()) return NULL;
 

	
 
	if (cs->packet_recv == NULL) {
 
		cs->packet_recv = MallocT<Packet>(1);
 
		if (cs->packet_recv == NULL) error("Failed to allocate packet");
 
		/* Set pos to zero! */
 
		cs->packet_recv->pos = 0;
 
@@ -158,58 +169,58 @@ Packet *NetworkRecv_Packet(NetworkClient
 

	
 
	p = cs->packet_recv;
 

	
 
	/* Read packet size */
 
	if (p->pos < sizeof(PacketSize)) {
 
		while (p->pos < sizeof(PacketSize)) {
 
			/* Read the size of the packet */
 
			res = recv(cs->socket, (char*)p->buffer + p->pos, sizeof(PacketSize) - p->pos, 0);
 
		/* Read the size of the packet */
 
			res = recv(cs->sock, (char*)p->buffer + p->pos, sizeof(PacketSize) - p->pos, 0);
 
			if (res == -1) {
 
				int err = GET_LAST_ERROR();
 
				if (err != EWOULDBLOCK) {
 
					/* Something went wrong... (104 is connection reset by peer) */
 
					if (err != 104) DEBUG(net, 0, "recv failed with error %d", err);
 
					*status = CloseConnection(cs);
 
					*status = cs->CloseConnection();
 
					return NULL;
 
				}
 
				/* Connection would block, so stop for now */
 
				return NULL;
 
			}
 
			if (res == 0) {
 
				/* Client/server has left */
 
				*status = CloseConnection(cs);
 
				*status = cs->CloseConnection();
 
				return NULL;
 
			}
 
			p->pos += res;
 
		}
 

	
 
		NetworkRecv_ReadPacketSize(p);
 

	
 
		if (p->size > SEND_MTU) {
 
			*status = CloseConnection(cs);
 
			*status = cs->CloseConnection();
 
			return NULL;
 
		}
 
	}
 

	
 
	/* Read rest of packet */
 
	while (p->pos < p->size) {
 
		res = recv(cs->socket, (char*)p->buffer + p->pos, p->size - p->pos, 0);
 
		res = recv(cs->sock, (char*)p->buffer + p->pos, p->size - p->pos, 0);
 
		if (res == -1) {
 
			int err = GET_LAST_ERROR();
 
			if (err != EWOULDBLOCK) {
 
				/* Something went wrong... (104 is connection reset by peer) */
 
				if (err != 104) DEBUG(net, 0, "recv failed with error %d", err);
 
				*status = CloseConnection(cs);
 
				*status = cs->CloseConnection();
 
				return NULL;
 
			}
 
			/* Connection would block */
 
			return NULL;
 
		}
 
		if (res == 0) {
 
			/* Client/server has left */
 
			*status = CloseConnection(cs);
 
			*status = cs->CloseConnection();
 
			return NULL;
 
		}
 

	
 
		p->pos += res;
 
	}
 

	
src/network/core/tcp.h
Show inline comments
 
@@ -3,12 +3,13 @@
 
#ifndef NETWORK_CORE_TCP_H
 
#define NETWORK_CORE_TCP_H
 

	
 
#ifdef ENABLE_NETWORK
 

	
 
#include "os_abstraction.h"
 
#include "core.h"
 
#include "packet.h"
 

	
 
/**
 
 * @file tcp.h Basic functions to receive and send TCP packets.
 
 */
 

	
 
@@ -51,13 +52,58 @@ enum {
 
	PACKET_SERVER_NEWGAME,
 
	PACKET_SERVER_RCON,
 
	PACKET_CLIENT_RCON,
 
	PACKET_END                   ///< Must ALWAYS be on the end of this list!! (period)
 
};
 

	
 
void NetworkSend_Packet(Packet *packet, NetworkClientState *cs);
 
Packet *NetworkRecv_Packet(NetworkClientState *cs, NetworkRecvStatus *status);
 
bool NetworkSend_Packets(NetworkClientState *cs);
 
typedef struct CommandPacket {
 
	struct CommandPacket *next;
 
	PlayerByte player; ///< player that is executing the command
 
	uint32 cmd;        ///< command being executed
 
	uint32 p1;         ///< parameter p1
 
	uint32 p2;         ///< parameter p2
 
	TileIndex tile;    ///< tile command being executed on
 
	char text[80];
 
	uint32 frame;      ///< the frame in which this packet is executed
 
	byte callback;     ///< any callback function executed upon successful completion of the command
 
} CommandPacket;
 

	
 
typedef enum {
 
	STATUS_INACTIVE,   ///< The client is not connected nor active
 
	STATUS_AUTH,       ///< The client is authorized
 
	STATUS_MAP_WAIT,   ///< The client is waiting as someone else is downloading the map
 
	STATUS_MAP,        ///< The client is downloading the map
 
	STATUS_DONE_MAP,   ///< The client has downloaded the map
 
	STATUS_PRE_ACTIVE, ///< The client is catching up the delayed frames
 
	STATUS_ACTIVE,     ///< The client is an active player in the game
 
} ClientStatus;
 

	
 
/** Base socket handler for all TCP sockets */
 
class NetworkTCPSocketHandler : public NetworkSocketHandler {
 
/* TODO: rewrite into a proper class */
 
public:
 
	uint16 index;
 
	uint32 last_frame;
 
	uint32 last_frame_server;
 
	byte lag_test; // This byte is used for lag-testing the client
 

	
 
	ClientStatus status;
 
	bool writable; // is client ready to write to?
 

	
 
	Packet *packet_queue; // Packets that are awaiting delivery
 
	Packet *packet_recv; // Partially received packet
 

	
 
	CommandPacket *command_queue; // The command-queue awaiting delivery
 

	
 
	NetworkRecvStatus CloseConnection();
 
	void Initialize();
 
};
 

	
 

	
 

	
 
void NetworkSend_Packet(Packet *packet, NetworkTCPSocketHandler *cs);
 
Packet *NetworkRecv_Packet(NetworkTCPSocketHandler *cs, NetworkRecvStatus *status);
 
bool NetworkSend_Packets(NetworkTCPSocketHandler *cs);
 

	
 
#endif /* ENABLE_NETWORK */
 

	
 
#endif /* NETWORK_CORE_TCP_H */
src/network/core/udp.cpp
Show inline comments
 
@@ -10,18 +10,12 @@
 
#include "udp.h"
 

	
 
/**
 
 * @file udp.c Basic functions to receive and send UDP packets.
 
 */
 

	
 
/** Initialize the sockets with an INVALID_SOCKET */
 
NetworkUDPSocketHandler::NetworkUDPSocketHandler()
 
{
 
	this->udp = INVALID_SOCKET;
 
}
 

	
 
/**
 
 * Start listening on the given host and port.
 
 * @param udp       the place where the (references to the) UDP are stored
 
 * @param host      the host (ip) to listen on
 
 * @param port      the port to listen on
 
 * @param broadcast whether to allow broadcast sending/receiving
 
@@ -31,43 +25,43 @@ bool NetworkUDPSocketHandler::Listen(con
 
{
 
	struct sockaddr_in sin;
 

	
 
	/* Make sure socket is closed */
 
	this->Close();
 

	
 
	this->udp = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
 
	if (this->udp == INVALID_SOCKET) {
 
	this->sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
 
	if (!this->IsConnected()) {
 
		DEBUG(net, 0, "[udp] failed to start UDP listener");
 
		return false;
 
	}
 

	
 
	/* set nonblocking mode for socket */
 
	{
 
		unsigned long blocking = 1;
 
#ifndef BEOS_NET_SERVER
 
		ioctlsocket(this->udp, FIONBIO, &blocking);
 
		ioctlsocket(this->sock, FIONBIO, &blocking);
 
#else
 
		setsockopt(this->udp, SOL_SOCKET, SO_NONBLOCK, &blocking, NULL);
 
		setsockopt(this->sock, SOL_SOCKET, SO_NONBLOCK, &blocking, NULL);
 
#endif
 
	}
 

	
 
	sin.sin_family = AF_INET;
 
	/* Listen on all IPs */
 
	sin.sin_addr.s_addr = host;
 
	sin.sin_port = htons(port);
 

	
 
	if (bind(this->udp, (struct sockaddr*)&sin, sizeof(sin)) != 0) {
 
	if (bind(this->sock, (struct sockaddr*)&sin, sizeof(sin)) != 0) {
 
		DEBUG(net, 0, "[udp] bind failed on %s:%i", inet_ntoa(*(struct in_addr *)&host), port);
 
		return false;
 
	}
 

	
 
	if (broadcast) {
 
		/* Enable broadcast */
 
		unsigned long val = 1;
 
#ifndef BEOS_NET_SERVER // will work around this, some day; maybe.
 
		setsockopt(this->udp, SOL_SOCKET, SO_BROADCAST, (char *) &val , sizeof(val));
 
		setsockopt(this->sock, SOL_SOCKET, SO_BROADCAST, (char *) &val , sizeof(val));
 
#endif
 
	}
 

	
 
	DEBUG(net, 1, "[udp] listening on port %s:%d", inet_ntoa(*(struct in_addr *)&host), port);
 

	
 
	return true;
 
@@ -76,18 +70,23 @@ bool NetworkUDPSocketHandler::Listen(con
 
/**
 
 * Close the given UDP socket
 
 * @param udp the socket to close
 
 */
 
void NetworkUDPSocketHandler::Close()
 
{
 
	if (this->udp == INVALID_SOCKET) return;
 
	if (!this->IsConnected()) return;
 

	
 
	closesocket(this->udp);
 
	this->udp = INVALID_SOCKET;
 
	closesocket(this->sock);
 
	this->sock = INVALID_SOCKET;
 
}
 

	
 
NetworkRecvStatus NetworkUDPSocketHandler::CloseConnection()
 
{
 
	this->has_quit = true;
 
	return NETWORK_RECV_STATUS_OKAY;
 
}
 

	
 
/**
 
 * Send a packet over UDP
 
 * @param udp  the socket to send over
 
 * @param p    the packet to send
 
 * @param recv the receiver (target) of the packet
 
@@ -96,13 +95,13 @@ void NetworkUDPSocketHandler::SendPacket
 
{
 
	int res;
 

	
 
	NetworkSend_FillPacketSize(p);
 

	
 
	/* Send the buffer */
 
	res = sendto(this->udp, (const char*)p->buffer, p->size, 0, (struct sockaddr *)recv, sizeof(*recv));
 
	res = sendto(this->sock, (const char*)p->buffer, p->size, 0, (struct sockaddr *)recv, sizeof(*recv));
 

	
 
	/* Check for any errors, but ignore it otherwise */
 
	if (res == -1) DEBUG(net, 1, "[udp] sendto failed with: %i", GET_LAST_ERROR());
 
}
 

	
 
/**
 
@@ -114,19 +113,19 @@ void NetworkUDPSocketHandler::ReceivePac
 
	struct sockaddr_in client_addr;
 
	socklen_t client_len;
 
	int nbytes;
 
	Packet p;
 
	int packet_len;
 

	
 
	if (this->udp == INVALID_SOCKET) return;
 
	if (!this->IsConnected()) return;
 

	
 
	packet_len = sizeof(p.buffer);
 
	client_len = sizeof(client_addr);
 

	
 
	/* Try to receive anything */
 
	nbytes = recvfrom(this->udp, (char*)p.buffer, packet_len, 0, (struct sockaddr *)&client_addr, &client_len);
 
	nbytes = recvfrom(this->sock, (char*)p.buffer, packet_len, 0, (struct sockaddr *)&client_addr, &client_len);
 

	
 
	/* We got some bytes for the base header of the packet. */
 
	if (nbytes > 2) {
 
		NetworkRecv_ReadPacketSize(&p);
 

	
 
		/* If the size does not match the packet must be corrupted.
 
@@ -167,15 +166,15 @@ void NetworkUDPSocketHandler::Send_GRFId
 
 * @param p  the packet to read the data from
 
 * @param c  the configuration to write the GRF ID and MD5 checksum to
 
 */
 
void NetworkUDPSocketHandler::Recv_GRFIdentifier(Packet *p, GRFConfig *c)
 
{
 
	uint j;
 
	c->grfid = NetworkRecv_uint32(&this->cs, p);
 
	c->grfid = NetworkRecv_uint32(this, p);
 
	for (j = 0; j < sizeof(c->md5sum); j++) {
 
		c->md5sum[j] = NetworkRecv_uint8(&this->cs, p);
 
		c->md5sum[j] = NetworkRecv_uint8(this, p);
 
	}
 
}
 

	
 

	
 
/**
 
 * Serializes the NetworkGameInfo struct to the packet
 
@@ -243,13 +242,13 @@ void NetworkUDPSocketHandler::Send_Netwo
 
 * Deserializes the NetworkGameInfo struct from the packet
 
 * @param p    the packet to read the data from
 
 * @param info the NetworkGameInfo to deserialize into
 
 */
 
void NetworkUDPSocketHandler::Recv_NetworkGameInfo(Packet *p, NetworkGameInfo *info)
 
{
 
	info->game_info_version = NetworkRecv_uint8(&this->cs, p);
 
	info->game_info_version = NetworkRecv_uint8(this, p);
 

	
 
	/*
 
	 *              Please observe the order.
 
	 * The parts must be read in the same order as they are sent!
 
	 */
 

	
 
@@ -257,50 +256,50 @@ void NetworkUDPSocketHandler::Recv_Netwo
 
	 * to the NetworkGameInfo wire-protocol! */
 

	
 
	switch (info->game_info_version) {
 
		case 4: {
 
			GRFConfig **dst = &info->grfconfig;
 
			uint i;
 
			uint num_grfs = NetworkRecv_uint8(&this->cs, p);
 
			uint num_grfs = NetworkRecv_uint8(this, p);
 

	
 
			for (i = 0; i < num_grfs; i++) {
 
				GRFConfig *c = CallocT<GRFConfig>(1);
 
				this->Recv_GRFIdentifier(p, c);
 
				this->HandleIncomingNetworkGameInfoGRFConfig(c);
 

	
 
				/* Append GRFConfig to the list */
 
				*dst = c;
 
				dst = &c->next;
 
			}
 
		} /* Fallthrough */
 
		case 3:
 
			info->game_date      = NetworkRecv_uint32(&this->cs, p);
 
			info->start_date     = NetworkRecv_uint32(&this->cs, p);
 
			info->game_date      = NetworkRecv_uint32(this, p);
 
			info->start_date     = NetworkRecv_uint32(this, p);
 
			/* Fallthrough */
 
		case 2:
 
			info->companies_max  = NetworkRecv_uint8 (&this->cs, p);
 
			info->companies_on   = NetworkRecv_uint8 (&this->cs, p);
 
			info->spectators_max = NetworkRecv_uint8 (&this->cs, p);
 
			info->companies_max  = NetworkRecv_uint8 (this, p);
 
			info->companies_on   = NetworkRecv_uint8 (this, p);
 
			info->spectators_max = NetworkRecv_uint8 (this, p);
 
			/* Fallthrough */
 
		case 1:
 
			NetworkRecv_string(&this->cs, p, info->server_name,     sizeof(info->server_name));
 
			NetworkRecv_string(&this->cs, p, info->server_revision, sizeof(info->server_revision));
 
			info->server_lang    = NetworkRecv_uint8 (&this->cs, p);
 
			info->use_password   = NetworkRecv_uint8 (&this->cs, p);
 
			info->clients_max    = NetworkRecv_uint8 (&this->cs, p);
 
			info->clients_on     = NetworkRecv_uint8 (&this->cs, p);
 
			info->spectators_on  = NetworkRecv_uint8 (&this->cs, p);
 
			NetworkRecv_string(this, p, info->server_name,     sizeof(info->server_name));
 
			NetworkRecv_string(this, p, info->server_revision, sizeof(info->server_revision));
 
			info->server_lang    = NetworkRecv_uint8 (this, p);
 
			info->use_password   = NetworkRecv_uint8 (this, p);
 
			info->clients_max    = NetworkRecv_uint8 (this, p);
 
			info->clients_on     = NetworkRecv_uint8 (this, p);
 
			info->spectators_on  = NetworkRecv_uint8 (this, p);
 
			if (info->game_info_version < 3) { // 16 bits dates got scrapped and are read earlier
 
				info->game_date    = NetworkRecv_uint16(&this->cs, p) + DAYS_TILL_ORIGINAL_BASE_YEAR;
 
				info->start_date   = NetworkRecv_uint16(&this->cs, p) + DAYS_TILL_ORIGINAL_BASE_YEAR;
 
				info->game_date    = NetworkRecv_uint16(this, p) + DAYS_TILL_ORIGINAL_BASE_YEAR;
 
				info->start_date   = NetworkRecv_uint16(this, p) + DAYS_TILL_ORIGINAL_BASE_YEAR;
 
			}
 
			NetworkRecv_string(&this->cs, p, info->map_name, sizeof(info->map_name));
 
			info->map_width      = NetworkRecv_uint16(&this->cs, p);
 
			info->map_height     = NetworkRecv_uint16(&this->cs, p);
 
			info->map_set        = NetworkRecv_uint8 (&this->cs, p);
 
			info->dedicated      = (NetworkRecv_uint8(&this->cs, p) != 0);
 
			NetworkRecv_string(this, p, info->map_name, sizeof(info->map_name));
 
			info->map_width      = NetworkRecv_uint16(this, p);
 
			info->map_height     = NetworkRecv_uint16(this, p);
 
			info->map_set        = NetworkRecv_uint8 (this, p);
 
			info->dedicated      = (NetworkRecv_uint8(this, p) != 0);
 
	}
 
}
 

	
 
/* Defines a simple (switch) case for each network packet */
 
#define UDP_COMMAND(type) case type: this->NetworkPacketReceive_ ## type ## _command(p, client_addr); break;
 

	
 
@@ -310,19 +309,18 @@ void NetworkUDPSocketHandler::Recv_Netwo
 
 * @param client_addr the sender of the packet
 
 */
 
void NetworkUDPSocketHandler::HandleUDPPacket(Packet *p, const struct sockaddr_in *client_addr)
 
{
 
	PacketUDPType type;
 

	
 
	/* Fake a client, so we can see when there is an illegal packet */
 
	this->cs.socket = INVALID_SOCKET;
 
	this->cs.has_quit = false;
 
	/* New packet == new client, which has not quit yet */
 
	this->has_quit = false;
 

	
 
	type = (PacketUDPType)NetworkRecv_uint8(&this->cs, p);
 
	type = (PacketUDPType)NetworkRecv_uint8(this, p);
 

	
 
	switch (this->cs.has_quit ? PACKET_UDP_END : type) {
 
	switch (this->HasClientQuit() ? PACKET_UDP_END : type) {
 
		UDP_COMMAND(PACKET_UDP_CLIENT_FIND_SERVER);
 
		UDP_COMMAND(PACKET_UDP_SERVER_RESPONSE);
 
		UDP_COMMAND(PACKET_UDP_CLIENT_DETAIL_INFO);
 
		UDP_COMMAND(PACKET_UDP_SERVER_DETAIL_INFO);
 
		UDP_COMMAND(PACKET_UDP_SERVER_REGISTER);
 
		UDP_COMMAND(PACKET_UDP_MASTER_ACK_REGISTER);
 
@@ -330,13 +328,13 @@ void NetworkUDPSocketHandler::HandleUDPP
 
		UDP_COMMAND(PACKET_UDP_MASTER_RESPONSE_LIST);
 
		UDP_COMMAND(PACKET_UDP_SERVER_UNREGISTER);
 
		UDP_COMMAND(PACKET_UDP_CLIENT_GET_NEWGRFS);
 
		UDP_COMMAND(PACKET_UDP_SERVER_NEWGRFS);
 

	
 
		default:
 
			if (!this->cs.has_quit) {
 
			if (this->HasClientQuit()) {
 
				DEBUG(net, 0, "[udp] received invalid packet type %d from %s:%d", type,  inet_ntoa(client_addr->sin_addr), ntohs(client_addr->sin_port));
 
			} else {
 
				DEBUG(net, 0, "[udp] received illegal packet from %s:%d", inet_ntoa(client_addr->sin_addr), ntohs(client_addr->sin_port));
 
			}
 
			break;
 
	}
 
@@ -348,14 +346,14 @@ void NetworkUDPSocketHandler::HandleUDPP
 
 * socket where the packet came from.
 
 */
 

	
 
#define DEFINE_UNAVAILABLE_UDP_RECEIVE_COMMAND(type) \
 
void NetworkUDPSocketHandler::NetworkPacketReceive_## type ##_command(\
 
		Packet *p, const struct sockaddr_in *client_addr) { \
 
	DEBUG(net, 0, "[udp] received packet on wrong port from %s:%d", \
 
			inet_ntoa(client_addr->sin_addr), ntohs(client_addr->sin_port)); \
 
	DEBUG(net, 0, "[udp] received packet type %d on wrong port from %s:%d", \
 
			type, inet_ntoa(client_addr->sin_addr), ntohs(client_addr->sin_port)); \
 
}
 

	
 
DEFINE_UNAVAILABLE_UDP_RECEIVE_COMMAND(PACKET_UDP_CLIENT_FIND_SERVER);
 
DEFINE_UNAVAILABLE_UDP_RECEIVE_COMMAND(PACKET_UDP_SERVER_RESPONSE);
 
DEFINE_UNAVAILABLE_UDP_RECEIVE_COMMAND(PACKET_UDP_CLIENT_DETAIL_INFO);
 
DEFINE_UNAVAILABLE_UDP_RECEIVE_COMMAND(PACKET_UDP_SERVER_DETAIL_INFO);
src/network/core/udp.h
Show inline comments
 
@@ -3,17 +3,17 @@
 
#ifndef NETWORK_CORE_UDP_H
 
#define NETWORK_CORE_UDP_H
 

	
 
#ifdef ENABLE_NETWORK
 

	
 
#include "os_abstraction.h"
 
#include "core.h"
 
#include "game.h"
 
#include "packet.h"
 
#include "../../newgrf_config.h"
 
#include "../../debug.h"
 
#include "../network_data.h"
 

	
 
/**
 
 * @file udp.h Basic functions to receive and send UDP packets.
 
 *
 
 *
 
 * *** Requesting game information from a server ***
 
@@ -88,17 +88,17 @@ enum PacketUDPType {
 
	PACKET_UDP_SERVER_NEWGRFS,       ///< Sends the list of NewGRF's requested.
 
	PACKET_UDP_END                   ///< Must ALWAYS be on the end of this list!! (period)
 
};
 

	
 
#define DECLARE_UDP_RECEIVE_COMMAND(type) virtual void NetworkPacketReceive_## type ##_command(Packet *p, const struct sockaddr_in *)
 

	
 
class NetworkUDPSocketHandler {
 
private:
 
	SOCKET udp;
 
/** Base socket handler for all UDP sockets */
 
class NetworkUDPSocketHandler : public NetworkSocketHandler {
 
protected:
 
	NetworkClientState cs;
 
	NetworkRecvStatus CloseConnection();
 

	
 
	/* Declare all possible packets here. If it can be received by the
 
	 * a specific handler, it has to be implemented. */
 
	DECLARE_UDP_RECEIVE_COMMAND(PACKET_UDP_CLIENT_FIND_SERVER);
 
	DECLARE_UDP_RECEIVE_COMMAND(PACKET_UDP_SERVER_RESPONSE);
 
	DECLARE_UDP_RECEIVE_COMMAND(PACKET_UDP_CLIENT_DETAIL_INFO);
 
	DECLARE_UDP_RECEIVE_COMMAND(PACKET_UDP_SERVER_DETAIL_INFO);
 
@@ -118,16 +118,14 @@ protected:
 
	 * function must set all appropriate fields. This GRF is later appended to
 
	 * the grfconfig list of the NetworkGameInfo.
 
	 * @param config the GRF to handle
 
	 */
 
	virtual void HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config) { NOT_REACHED(); }
 
public:
 
	NetworkUDPSocketHandler();
 
	virtual ~NetworkUDPSocketHandler() { this->Close(); }
 

	
 
	bool IsListening() { return this->udp != INVALID_SOCKET; }
 
	bool Listen(uint32 host, uint16 port, bool broadcast);
 
	void Close();
 

	
 
	void SendPacket(Packet *p, const struct sockaddr_in *recv);
 
	void ReceivePackets();
 

	
src/network/network.cpp
Show inline comments
 
@@ -44,13 +44,13 @@ CommandPacket *_local_command_queue;
 
extern NetworkUDPSocketHandler *_udp_client_socket; ///< udp client socket
 
extern NetworkUDPSocketHandler *_udp_server_socket; ///< udp server socket
 
extern NetworkUDPSocketHandler *_udp_master_socket; ///< udp master socket
 

	
 
// Here we keep track of the clients
 
//  (and the client uses [0] for his own communication)
 
NetworkClientState _clients[MAX_CLIENTS];
 
NetworkTCPSocketHandler _clients[MAX_CLIENTS];
 

	
 

	
 

	
 
// The listen socket for the server
 
static SOCKET _listensocket;
 

	
 
@@ -87,39 +87,39 @@ NetworkClientInfo *NetworkFindClientInfo
 
	}
 

	
 
	return NULL;
 
}
 

	
 
// Function that looks up the CS for a given client-index
 
NetworkClientState *NetworkFindClientStateFromIndex(uint16 client_index)
 
NetworkTCPSocketHandler *NetworkFindClientStateFromIndex(uint16 client_index)
 
{
 
	NetworkClientState *cs;
 
	NetworkTCPSocketHandler *cs;
 

	
 
	for (cs = _clients; cs != endof(_clients); cs++) {
 
		if (cs->index == client_index) return cs;
 
	}
 

	
 
	return NULL;
 
}
 

	
 
// NetworkGetClientName is a server-safe function to get the name of the client
 
//  if the user did not send it yet, Client #<no> is used.
 
void NetworkGetClientName(char *client_name, size_t size, const NetworkClientState *cs)
 
void NetworkGetClientName(char *client_name, size_t size, const NetworkTCPSocketHandler *cs)
 
{
 
	const NetworkClientInfo *ci = DEREF_CLIENT_INFO(cs);
 

	
 
	if (ci->client_name[0] == '\0') {
 
		snprintf(client_name, size, "Client #%4d", cs->index);
 
	} else {
 
		ttd_strlcpy(client_name, ci->client_name, size);
 
	}
 
}
 

	
 
byte NetworkSpectatorCount(void)
 
{
 
	const NetworkClientState *cs;
 
	NetworkTCPSocketHandler *cs;
 
	byte count = 0;
 

	
 
	FOR_ALL_CLIENTS(cs) {
 
		if (DEREF_CLIENT_INFO(cs)->client_playas == PLAYER_SPECTATOR) count++;
 
	}
 

	
 
@@ -194,13 +194,13 @@ void CDECL NetworkTextMessage(NetworkAct
 

	
 
	IConsolePrintF(color, "%s", message);
 
	AddTextMessage(color, duration, "%s", message);
 
}
 

	
 
// Calculate the frame-lag of a client
 
uint NetworkCalculateLag(const NetworkClientState *cs)
 
uint NetworkCalculateLag(const NetworkTCPSocketHandler *cs)
 
{
 
	int lag = cs->last_frame_server - cs->last_frame;
 
	// This client has missed his ACK packet after 1 DAY_TICKS..
 
	//  so we increase his lag for every frame that passes!
 
	// The packet can be out by a max of _net_frame_freq
 
	if (cs->last_frame_server + DAY_TICKS + _network_frame_freq < _frame_counter)
 
@@ -227,13 +227,13 @@ static void ClientStartError(const char 
 
static void ServerStartError(const char *error)
 
{
 
	DEBUG(net, 0, "[server] could not start network: %s",error);
 
	NetworkError(STR_NETWORK_ERR_SERVER_START);
 
}
 

	
 
static void NetworkClientError(NetworkRecvStatus res, NetworkClientState* cs)
 
static void NetworkClientError(NetworkRecvStatus res, NetworkTCPSocketHandler* cs)
 
{
 
	// First, send a CLIENT_ERROR to the server, so he knows we are
 
	//  disconnection (and why!)
 
	NetworkErrorCode errorno;
 

	
 
	// We just want to close the connection..
 
@@ -295,13 +295,13 @@ char* GetNetworkErrorMsg(char* buf, Netw
 
	return GetString(buf, network_error_strings[err], last);
 
}
 

	
 
/* Count the number of active clients connected */
 
static uint NetworkCountPlayers(void)
 
{
 
	const NetworkClientState *cs;
 
	NetworkTCPSocketHandler *cs;
 
	uint count = 0;
 

	
 
	FOR_ALL_CLIENTS(cs) {
 
		const NetworkClientInfo *ci = DEREF_CLIENT_INFO(cs);
 
		if (IsValidPlayer(ci->client_playas)) count++;
 
	}
 
@@ -546,32 +546,29 @@ void ParseConnectionString(const char **
 
		}
 
	}
 
}
 

	
 
// Creates a new client from a socket
 
//   Used both by the server and the client
 
static NetworkClientState *NetworkAllocClient(SOCKET s)
 
static NetworkTCPSocketHandler *NetworkAllocClient(SOCKET s)
 
{
 
	NetworkClientState *cs;
 
	NetworkTCPSocketHandler *cs;
 
	byte client_no = 0;
 

	
 
	if (_network_server) {
 
		// Can we handle a new client?
 
		if (_network_clients_connected >= MAX_CLIENTS) return NULL;
 
		if (_network_game_info.clients_on >= _network_game_info.clients_max) return NULL;
 

	
 
		// Register the login
 
		client_no = _network_clients_connected++;
 
	}
 

	
 
	cs = DEREF_CLIENT(client_no);
 
	memset(cs, 0, sizeof(*cs));
 
	cs->socket = s;
 
	cs->last_frame = 0;
 
	cs->has_quit = false;
 

	
 
	cs->Initialize();
 
	cs->sock = s;
 
	cs->last_frame = _frame_counter;
 
	cs->last_frame_server = _frame_counter;
 

	
 
	if (_network_server) {
 
		NetworkClientInfo *ci = DEREF_CLIENT_INFO(cs);
 
		memset(ci, 0, sizeof(*ci));
 
@@ -585,29 +582,29 @@ static NetworkClientState *NetworkAllocC
 
	}
 

	
 
	return cs;
 
}
 

	
 
// Close a connection
 
void NetworkCloseClient(NetworkClientState *cs)
 
void NetworkCloseClient(NetworkTCPSocketHandler *cs)
 
{
 
	NetworkClientInfo *ci;
 
	// Socket is already dead
 
	if (cs->socket == INVALID_SOCKET) {
 
	if (cs->sock == INVALID_SOCKET) {
 
		cs->has_quit = true;
 
		return;
 
	}
 

	
 
	DEBUG(net, 1, "Closed client connection %d", cs->index);
 

	
 
	if (!cs->has_quit && _network_server && cs->status > STATUS_INACTIVE) {
 
		// We did not receive a leave message from this client...
 
		NetworkErrorCode errorno = NETWORK_ERROR_CONNECTION_LOST;
 
		char str[100];
 
		char client_name[NETWORK_CLIENT_NAME_LENGTH];
 
		NetworkClientState *new_cs;
 
		NetworkTCPSocketHandler *new_cs;
 

	
 
		NetworkGetClientName(client_name, sizeof(client_name), cs);
 

	
 
		GetNetworkErrorMsg(str, errorno, lastof(str));
 

	
 
		NetworkTextMessage(NETWORK_ACTION_LEAVE, 1, false, client_name, "%s", str);
 
@@ -623,13 +620,13 @@ void NetworkCloseClient(NetworkClientSta
 
	/* When the client was PRE_ACTIVE, the server was in pause mode, so unpause */
 
	if (cs->status == STATUS_PRE_ACTIVE && _network_pause_on_join) {
 
		DoCommandP(0, 0, 0, NULL, CMD_PAUSE);
 
		NetworkServer_HandleChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_BROADCAST, 0, "Game unpaused", NETWORK_SERVER_INDEX);
 
	}
 

	
 
	closesocket(cs->socket);
 
	closesocket(cs->sock);
 
	cs->writable = false;
 
	cs->has_quit = true;
 

	
 
	// Free all pending and partially received packets
 
	while (cs->packet_queue != NULL) {
 
		Packet *p = cs->packet_queue->next;
 
@@ -650,24 +647,24 @@ void NetworkCloseClient(NetworkClientSta
 

	
 
	if (_network_server) {
 
		// We just lost one client :(
 
		if (cs->status > STATUS_INACTIVE) _network_game_info.clients_on--;
 
		_network_clients_connected--;
 

	
 
		while ((cs + 1) != DEREF_CLIENT(MAX_CLIENTS) && (cs + 1)->socket != INVALID_SOCKET) {
 
		while ((cs + 1) != DEREF_CLIENT(MAX_CLIENTS) && (cs + 1)->sock != INVALID_SOCKET) {
 
			*cs = *(cs + 1);
 
			*ci = *(ci + 1);
 
			cs++;
 
			ci++;
 
		}
 

	
 
		InvalidateWindow(WC_CLIENT_LIST, 0);
 
	}
 

	
 
	// Reset the status of the last socket
 
	cs->socket = INVALID_SOCKET;
 
	cs->sock = INVALID_SOCKET;
 
	cs->status = STATUS_INACTIVE;
 
	cs->index = NETWORK_EMPTY_INDEX;
 
	ci->client_index = NETWORK_EMPTY_INDEX;
 

	
 
	CheckMinPlayers();
 
}
 
@@ -708,13 +705,13 @@ static bool NetworkConnect(const char *h
 
}
 

	
 
// For the server, to accept new clients
 
static void NetworkAcceptClients(void)
 
{
 
	struct sockaddr_in sin;
 
	NetworkClientState *cs;
 
	NetworkTCPSocketHandler *cs;
 
	uint i;
 
	bool banned;
 

	
 
	// Should never ever happen.. is it possible??
 
	assert(_listensocket != INVALID_SOCKET);
 

	
 
@@ -824,13 +821,13 @@ static bool NetworkListen(void)
 
	return true;
 
}
 

	
 
// Close all current connections
 
static void NetworkClose(void)
 
{
 
	NetworkClientState *cs;
 
	NetworkTCPSocketHandler *cs;
 

	
 
	FOR_ALL_CLIENTS(cs) {
 
		if (!_network_server) {
 
			SEND_COMMAND(PACKET_CLIENT_QUIT)("leaving");
 
			NetworkSend_Packets(cs);
 
		}
 
@@ -846,22 +843,19 @@ static void NetworkClose(void)
 
	}
 
}
 

	
 
// Inits the network (cleans sockets and stuff)
 
static void NetworkInitialize(void)
 
{
 
	NetworkClientState *cs;
 
	NetworkTCPSocketHandler *cs;
 

	
 
	_local_command_queue = NULL;
 

	
 
	// Clean all client-sockets
 
	memset(_clients, 0, sizeof(_clients));
 
	for (cs = _clients; cs != &_clients[MAX_CLIENTS]; cs++) {
 
		cs->socket = INVALID_SOCKET;
 
		cs->status = STATUS_INACTIVE;
 
		cs->command_queue = NULL;
 
		cs->Initialize();
 
	}
 

	
 
	// Clean the client_info memory
 
	memset(&_network_client_info, 0, sizeof(_network_client_info));
 
	memset(&_network_player_info, 0, sizeof(_network_player_info));
 

	
 
@@ -1068,13 +1062,13 @@ bool NetworkServerStart(void)
 

	
 
// The server is rebooting...
 
// The only difference with NetworkDisconnect, is the packets that is sent
 
void NetworkReboot(void)
 
{
 
	if (_network_server) {
 
		NetworkClientState *cs;
 
		NetworkTCPSocketHandler *cs;
 
		FOR_ALL_CLIENTS(cs) {
 
			SEND_COMMAND(PACKET_SERVER_NEWGAME)(cs);
 
			NetworkSend_Packets(cs);
 
		}
 
	}
 

	
 
@@ -1092,13 +1086,13 @@ void NetworkReboot(void)
 
}
 

	
 
// We want to disconnect from the host/clients
 
void NetworkDisconnect(void)
 
{
 
	if (_network_server) {
 
		NetworkClientState *cs;
 
		NetworkTCPSocketHandler *cs;
 
		FOR_ALL_CLIENTS(cs) {
 
			SEND_COMMAND(PACKET_SERVER_SHUTDOWN)(cs);
 
			NetworkSend_Packets(cs);
 
		}
 
	}
 

	
 
@@ -1119,23 +1113,23 @@ void NetworkDisconnect(void)
 
	_network_server = false;
 
}
 

	
 
// Receives something from the network
 
static bool NetworkReceive(void)
 
{
 
	NetworkClientState *cs;
 
	NetworkTCPSocketHandler *cs;
 
	int n;
 
	fd_set read_fd, write_fd;
 
	struct timeval tv;
 

	
 
	FD_ZERO(&read_fd);
 
	FD_ZERO(&write_fd);
 

	
 
	FOR_ALL_CLIENTS(cs) {
 
		FD_SET(cs->socket, &read_fd);
 
		FD_SET(cs->socket, &write_fd);
 
		FD_SET(cs->sock, &read_fd);
 
		FD_SET(cs->sock, &write_fd);
 
	}
 

	
 
	// take care of listener port
 
	if (_network_server) FD_SET(_listensocket, &read_fd);
 

	
 
	tv.tv_sec = tv.tv_usec = 0; // don't block at all.
 
@@ -1148,14 +1142,14 @@ static bool NetworkReceive(void)
 

	
 
	// accept clients..
 
	if (_network_server && FD_ISSET(_listensocket, &read_fd)) NetworkAcceptClients();
 

	
 
	// read stuff from clients
 
	FOR_ALL_CLIENTS(cs) {
 
		cs->writable = !!FD_ISSET(cs->socket, &write_fd);
 
		if (FD_ISSET(cs->socket, &read_fd)) {
 
		cs->writable = !!FD_ISSET(cs->sock, &write_fd);
 
		if (FD_ISSET(cs->sock, &read_fd)) {
 
			if (_network_server) {
 
				NetworkServer_ReadPackets(cs);
 
			} else {
 
				NetworkRecvStatus res;
 

	
 
				// The client already was quiting!
 
@@ -1174,13 +1168,13 @@ static bool NetworkReceive(void)
 
	return true;
 
}
 

	
 
// This sends all buffered commands (if possible)
 
static void NetworkSend(void)
 
{
 
	NetworkClientState *cs;
 
	NetworkTCPSocketHandler *cs;
 
	FOR_ALL_CLIENTS(cs) {
 
		if (cs->writable) {
 
			NetworkSend_Packets(cs);
 

	
 
			if (cs->status == STATUS_MAP) {
 
				// This client is in the middle of a map-send, call the function for that
src/network/network_client.cpp
Show inline comments
 
@@ -793,13 +793,13 @@ void NetworkClient_Connected(void)
 
	last_ack_frame = 0;
 
	// Request the game-info
 
	SEND_COMMAND(PACKET_CLIENT_JOIN)();
 
}
 

	
 
// Reads the packets from the socket-stream, if available
 
NetworkRecvStatus NetworkClient_ReadPackets(NetworkClientState *cs)
 
NetworkRecvStatus NetworkClient_ReadPackets(NetworkTCPSocketHandler *cs)
 
{
 
	Packet *p;
 
	NetworkRecvStatus res = NETWORK_RECV_STATUS_OKAY;
 

	
 
	while (res == NETWORK_RECV_STATUS_OKAY && (p = NetworkRecv_Packet(cs, &res)) != NULL) {
 
		byte type = NetworkRecv_uint8(MY_CLIENT, p);
src/network/network_client.h
Show inline comments
 
@@ -14,12 +14,12 @@ DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLI
 
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_PASSWORD)(NetworkPasswordType type, const char *password);
 
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_SET_PASSWORD)(const char *password);
 
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_SET_NAME)(const char *name);
 
DEF_CLIENT_SEND_COMMAND(PACKET_CLIENT_ACK);
 
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_RCON)(const char *pass, const char *command);
 

	
 
NetworkRecvStatus NetworkClient_ReadPackets(NetworkClientState *cs);
 
NetworkRecvStatus NetworkClient_ReadPackets(NetworkTCPSocketHandler *cs);
 
void NetworkClient_Connected(void);
 

	
 
#endif /* ENABLE_NETWORK */
 

	
 
#endif /* NETWORK_CLIENT_H */
src/network/network_data.cpp
Show inline comments
 
@@ -9,13 +9,13 @@
 
#include "network_client.h"
 
#include "../command.h"
 
#include "../callback_table.h"
 
#include "../helpers.hpp"
 

	
 
// Add a command to the local command queue
 
void NetworkAddCommandQueue(NetworkClientState *cs, CommandPacket *cp)
 
void NetworkAddCommandQueue(NetworkTCPSocketHandler *cs, CommandPacket *cp)
 
{
 
	CommandPacket* new_cp = MallocT<CommandPacket>(1);
 

	
 
	*new_cp = *cp;
 

	
 
	if (cs->command_queue == NULL) {
 
@@ -62,13 +62,13 @@ void NetworkSend_Command(TileIndex tile,
 
	if (_network_server) {
 
		// If we are the server, we queue the command in our 'special' queue.
 
		//   In theory, we could execute the command right away, but then the
 
		//   client on the server can do everything 1 tick faster than others.
 
		//   So to keep the game fair, we delay the command with 1 tick
 
		//   which gives about the same speed as most clients.
 
		NetworkClientState *cs;
 
		NetworkTCPSocketHandler *cs;
 

	
 
		// And we queue it for delivery to the clients
 
		FOR_ALL_CLIENTS(cs) {
 
			if (cs->status > STATUS_AUTH) NetworkAddCommandQueue(cs, c);
 
		}
 

	
src/network/network_data.h
Show inline comments
 
@@ -6,62 +6,30 @@
 
// Is the network enabled?
 
#ifdef ENABLE_NETWORK
 

	
 
#include "../openttd.h"
 
#include "network.h"
 
#include "core/os_abstraction.h"
 
#include "core/core.h"
 
#include "core/config.h"
 
#include "core/packet.h"
 
#include "core/tcp.h"
 

	
 
#define MAX_TEXT_MSG_LEN 1024 /* long long long long sentences :-) */
 

	
 
// The client-info-server-index is always 1
 
#define NETWORK_SERVER_INDEX 1
 
#define NETWORK_EMPTY_INDEX 0
 

	
 
typedef struct CommandPacket {
 
	struct CommandPacket *next;
 
	PlayerByte player; /// player that is executing the command
 
	uint32 cmd;    /// command being executed
 
	uint32 p1;     /// parameter p1
 
	uint32 p2;     /// parameter p2
 
	TileIndex tile; /// tile command being executed on
 
	char text[80];
 
	uint32 frame;  /// the frame in which this packet is executed
 
	byte callback; /// any callback function executed upon successful completion of the command
 
} CommandPacket;
 

	
 
typedef enum {
 
	STATUS_INACTIVE,
 
	STATUS_AUTH, // This means that the client is authorized
 
	STATUS_MAP_WAIT, // This means that the client is put on hold because someone else is getting the map
 
	STATUS_MAP,
 
	STATUS_DONE_MAP,
 
	STATUS_PRE_ACTIVE,
 
	STATUS_ACTIVE,
 
} ClientStatus;
 

	
 
typedef enum {
 
	MAP_PACKET_START,
 
	MAP_PACKET_NORMAL,
 
	MAP_PACKET_END,
 
} MapPacket;
 

	
 
typedef enum {
 
	NETWORK_RECV_STATUS_OKAY,
 
	NETWORK_RECV_STATUS_DESYNC,
 
	NETWORK_RECV_STATUS_SAVEGAME,
 
	NETWORK_RECV_STATUS_CONN_LOST,
 
	NETWORK_RECV_STATUS_MALFORMED_PACKET,
 
	NETWORK_RECV_STATUS_SERVER_ERROR, // The server told us we made an error
 
	NETWORK_RECV_STATUS_SERVER_FULL,
 
	NETWORK_RECV_STATUS_SERVER_BANNED,
 
	NETWORK_RECV_STATUS_CLOSE_QUERY, // Done quering the server
 
} NetworkRecvStatus;
 

	
 
typedef enum {
 
	NETWORK_ERROR_GENERAL, // Try to use thisone like never
 

	
 
	// Signals from clients
 
	NETWORK_ERROR_DESYNC,
 
	NETWORK_ERROR_SAVEGAME_FAILED,
 
	NETWORK_ERROR_CONNECTION_LOST,
 
@@ -93,73 +61,55 @@ typedef enum {
 

	
 
typedef enum {
 
	NETWORK_GAME_PASSWORD,
 
	NETWORK_COMPANY_PASSWORD,
 
} NetworkPasswordType;
 

	
 
// To keep the clients all together
 
struct NetworkClientState { // Typedeffed in network_core/packet.h
 
	SOCKET socket;
 
	uint16 index;
 
	uint32 last_frame;
 
	uint32 last_frame_server;
 
	byte lag_test; // This byte is used for lag-testing the client
 

	
 
	ClientStatus status;
 
	bool writable; // is client ready to write to?
 
	bool has_quit;
 

	
 
	Packet *packet_queue; // Packets that are awaiting delivery
 
	Packet *packet_recv; // Partially received packet
 

	
 
	CommandPacket *command_queue; // The command-queue awaiting delivery
 
};
 

	
 
typedef enum {
 
	DESTTYPE_BROADCAST, ///< Send message/notice to all players (All)
 
	DESTTYPE_TEAM,    ///< Send message/notice to everyone playing the same company (Team)
 
	DESTTYPE_CLIENT,    ///< Send message/notice to only a certain player (Private)
 
} DestType;
 

	
 
// following externs are instantiated at network.cpp
 
extern CommandPacket *_local_command_queue;
 

	
 
// Here we keep track of the clients
 
//  (and the client uses [0] for his own communication)
 
extern NetworkClientState _clients[MAX_CLIENTS];
 
extern NetworkTCPSocketHandler _clients[MAX_CLIENTS];
 

	
 
#define DEREF_CLIENT(i) (&_clients[i])
 
// This returns the NetworkClientInfo from a NetworkClientState
 
#define DEREF_CLIENT_INFO(cs) (&_network_client_info[cs - _clients])
 

	
 
// Macros to make life a bit more easier
 
#define DEF_CLIENT_RECEIVE_COMMAND(type) NetworkRecvStatus NetworkPacketReceive_ ## type ## _command(Packet *p)
 
#define DEF_CLIENT_SEND_COMMAND(type) void NetworkPacketSend_ ## type ## _command(void)
 
#define DEF_CLIENT_SEND_COMMAND_PARAM(type) void NetworkPacketSend_ ## type ## _command
 
#define DEF_SERVER_RECEIVE_COMMAND(type) void NetworkPacketReceive_ ## type ## _command(NetworkClientState *cs, Packet *p)
 
#define DEF_SERVER_SEND_COMMAND(type) void NetworkPacketSend_ ## type ## _command(NetworkClientState *cs)
 
#define DEF_SERVER_RECEIVE_COMMAND(type) void NetworkPacketReceive_ ## type ## _command(NetworkTCPSocketHandler *cs, Packet *p)
 
#define DEF_SERVER_SEND_COMMAND(type) void NetworkPacketSend_ ## type ## _command(NetworkTCPSocketHandler *cs)
 
#define DEF_SERVER_SEND_COMMAND_PARAM(type) void NetworkPacketSend_ ## type ## _command
 

	
 
#define SEND_COMMAND(type) NetworkPacketSend_ ## type ## _command
 
#define RECEIVE_COMMAND(type) NetworkPacketReceive_ ## type ## _command
 

	
 
#define FOR_ALL_CLIENTS(cs) for (cs = _clients; cs != endof(_clients) && cs->socket != INVALID_SOCKET; cs++)
 
#define FOR_ALL_CLIENTS(cs) for (cs = _clients; cs != endof(_clients) && cs->IsConnected(); cs++)
 
#define FOR_ALL_ACTIVE_CLIENT_INFOS(ci) for (ci = _network_client_info; ci != endof(_network_client_info); ci++) if (ci->client_index != NETWORK_EMPTY_INDEX)
 

	
 
void NetworkExecuteCommand(CommandPacket *cp);
 
void NetworkAddCommandQueue(NetworkClientState *cs, CommandPacket *cp);
 
void NetworkAddCommandQueue(NetworkTCPSocketHandler *cs, CommandPacket *cp);
 

	
 
// from network.c
 
void NetworkCloseClient(NetworkClientState *cs);
 
void NetworkCloseClient(NetworkTCPSocketHandler *cs);
 
void CDECL NetworkTextMessage(NetworkAction action, uint16 color, bool self_send, const char *name, const char *str, ...);
 
void NetworkGetClientName(char *clientname, size_t size, const NetworkClientState *cs);
 
uint NetworkCalculateLag(const NetworkClientState *cs);
 
void NetworkGetClientName(char *clientname, size_t size, const NetworkTCPSocketHandler *cs);
 
uint NetworkCalculateLag(const NetworkTCPSocketHandler *cs);
 
byte NetworkGetCurrentLanguageIndex(void);
 
NetworkClientInfo *NetworkFindClientInfoFromIndex(uint16 client_index);
 
NetworkClientInfo *NetworkFindClientInfoFromIP(const char *ip);
 
NetworkClientState *NetworkFindClientStateFromIndex(uint16 client_index);
 
NetworkTCPSocketHandler *NetworkFindClientStateFromIndex(uint16 client_index);
 
unsigned long NetworkResolveHost(const char *hostname);
 
char* GetNetworkErrorMsg(char* buf, NetworkErrorCode err, const char* last);
 

	
 
#endif /* ENABLE_NETWORK */
 

	
 
#endif /* NETWORK_DATA_H */
src/network/network_server.cpp
Show inline comments
 
@@ -23,20 +23,20 @@
 
#include "../variables.h"
 
#include "../genworld.h"
 
#include "../helpers.hpp"
 

	
 
// This file handles all the server-commands
 

	
 
static void NetworkHandleCommandQueue(NetworkClientState* cs);
 
static void NetworkHandleCommandQueue(NetworkTCPSocketHandler* cs);
 

	
 
// **********
 
// Sending functions
 
//   DEF_SERVER_SEND_COMMAND has parameter: NetworkClientState *cs
 
//   DEF_SERVER_SEND_COMMAND has parameter: NetworkTCPSocketHandler *cs
 
// **********
 

	
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_CLIENT_INFO)(NetworkClientState *cs, NetworkClientInfo *ci)
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_CLIENT_INFO)(NetworkTCPSocketHandler *cs, NetworkClientInfo *ci)
 
{
 
	//
 
	// Packet: SERVER_CLIENT_INFO
 
	// Function: Sends info about a client
 
	// Data:
 
	//    uint16:  The index of the client (always unique on a server. 1 = server)
 
@@ -128,13 +128,13 @@ DEF_SERVER_SEND_COMMAND(PACKET_SERVER_CO
 
	NetworkSend_uint8 (p, NETWORK_COMPANY_INFO_VERSION);
 
	NetworkSend_uint8 (p, 0);
 

	
 
	NetworkSend_Packet(p, cs);
 
}
 

	
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_ERROR)(NetworkClientState *cs, NetworkErrorCode error)
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_ERROR)(NetworkTCPSocketHandler *cs, NetworkErrorCode error)
 
{
 
	//
 
	// Packet: SERVER_ERROR
 
	// Function: The client made an error
 
	// Data:
 
	//    uint8:  ErrorID (see network_data.h, NetworkErrorCode)
 
@@ -147,13 +147,13 @@ DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SER
 
	NetworkSend_Packet(p, cs);
 

	
 
	GetNetworkErrorMsg(str, error, lastof(str));
 

	
 
	// Only send when the current client was in game
 
	if (cs->status > STATUS_AUTH) {
 
		NetworkClientState *new_cs;
 
		NetworkTCPSocketHandler *new_cs;
 
		char client_name[NETWORK_CLIENT_NAME_LENGTH];
 

	
 
		NetworkGetClientName(client_name, sizeof(client_name), cs);
 

	
 
		DEBUG(net, 1, "'%s' made an error and has been disconnected. Reason: '%s'", client_name, str);
 

	
 
@@ -179,13 +179,13 @@ DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SER
 
	NetworkSend_Packets(cs);
 

	
 
	// The client made a mistake, so drop his connection now!
 
	NetworkCloseClient(cs);
 
}
 

	
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_NEED_PASSWORD)(NetworkClientState *cs, NetworkPasswordType type)
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_NEED_PASSWORD)(NetworkTCPSocketHandler *cs, NetworkPasswordType type)
 
{
 
	//
 
	// Packet: SERVER_NEED_PASSWORD
 
	// Function: Indication to the client that the server needs a password
 
	// Data:
 
	//    uint8:  Type of password
 
@@ -203,13 +203,13 @@ DEF_SERVER_SEND_COMMAND(PACKET_SERVER_WE
 
	// Function: The client is joined and ready to receive his map
 
	// Data:
 
	//    uint16:  Own ClientID
 
	//
 

	
 
	Packet *p;
 
	const NetworkClientState *new_cs;
 
	NetworkTCPSocketHandler *new_cs;
 

	
 
	// Invalid packet when status is AUTH or higher
 
	if (cs->status >= STATUS_AUTH) return;
 

	
 
	cs->status = STATUS_AUTH;
 
	_network_game_info.clients_on++;
 
@@ -234,13 +234,13 @@ DEF_SERVER_SEND_COMMAND(PACKET_SERVER_WA
 
	// Function: The client can not receive the map at the moment because
 
	//             someone else is already receiving the map
 
	// Data:
 
	//    uint8:  Clients awaiting map
 
	//
 
	int waiting = 0;
 
	NetworkClientState *new_cs;
 
	NetworkTCPSocketHandler *new_cs;
 
	Packet *p;
 

	
 
	// Count how many players are waiting in the queue
 
	FOR_ALL_CLIENTS(new_cs) {
 
		if (new_cs->status == STATUS_MAP_WAIT) waiting++;
 
	}
 
@@ -327,13 +327,13 @@ DEF_SERVER_SEND_COMMAND(PACKET_SERVER_MA
 
				// Set the status to DONE_MAP, no we will wait for the client
 
				//  to send it is ready (maybe that happens like never ;))
 
				cs->status = STATUS_DONE_MAP;
 
				fclose(file_pointer);
 

	
 
				{
 
					NetworkClientState *new_cs;
 
					NetworkTCPSocketHandler *new_cs;
 
					bool new_map_client = false;
 
					// Check if there is a client waiting for receiving the map
 
					//  and start sending him the map
 
					FOR_ALL_CLIENTS(new_cs) {
 
						if (new_cs->status == STATUS_MAP_WAIT) {
 
							// Check if we already have a new client to send the map to
 
@@ -364,13 +364,13 @@ DEF_SERVER_SEND_COMMAND(PACKET_SERVER_MA
 
			// Not everything is sent, decrease the sent_packets
 
			if (sent_packets > 1) sent_packets /= 2;
 
		}
 
	}
 
}
 

	
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_JOIN)(NetworkClientState *cs, uint16 client_index)
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_JOIN)(NetworkTCPSocketHandler *cs, uint16 client_index)
 
{
 
	//
 
	// Packet: SERVER_JOIN
 
	// Function: A client is joined (all active clients receive this after a
 
	//     PACKET_CLIENT_MAP_OK) Mostly what directly follows is a
 
	//     PACKET_SERVER_CLIENT_INFO
 
@@ -430,13 +430,13 @@ DEF_SERVER_SEND_COMMAND(PACKET_SERVER_SY
 
#ifdef NETWORK_SEND_DOUBLE_SEED
 
	NetworkSend_uint32(p, _sync_seed_2);
 
#endif
 
	NetworkSend_Packet(p, cs);
 
}
 

	
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_COMMAND)(NetworkClientState *cs, CommandPacket *cp)
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_COMMAND)(NetworkTCPSocketHandler *cs, CommandPacket *cp)
 
{
 
	//
 
	// Packet: SERVER_COMMAND
 
	// Function: Sends a DoCommand to the client
 
	// Data:
 
	//    uint8:  PlayerID (0..MAX_PLAYERS-1)
 
@@ -460,13 +460,13 @@ DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SER
 
	NetworkSend_uint8(p, cp->callback);
 
	NetworkSend_uint32(p, cp->frame);
 

	
 
	NetworkSend_Packet(p, cs);
 
}
 

	
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_CHAT)(NetworkClientState *cs, NetworkAction action, uint16 client_index, bool self_send, const char *msg)
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_CHAT)(NetworkTCPSocketHandler *cs, NetworkAction action, uint16 client_index, bool self_send, const char *msg)
 
{
 
	//
 
	// Packet: SERVER_CHAT
 
	// Function: Sends a chat-packet to the client
 
	// Data:
 
	//    uint8:  ActionID (see network_data.h, NetworkAction)
 
@@ -481,13 +481,13 @@ DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SER
 
	NetworkSend_uint8(p, self_send);
 
	NetworkSend_string(p, msg);
 

	
 
	NetworkSend_Packet(p, cs);
 
}
 

	
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_ERROR_QUIT)(NetworkClientState *cs, uint16 client_index, NetworkErrorCode errorno)
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_ERROR_QUIT)(NetworkTCPSocketHandler *cs, uint16 client_index, NetworkErrorCode errorno)
 
{
 
	//
 
	// Packet: SERVER_ERROR_QUIT
 
	// Function: One of the clients made an error and is quiting the game
 
	//      This packet informs the other clients of that.
 
	// Data:
 
@@ -500,13 +500,13 @@ DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SER
 
	NetworkSend_uint16(p, client_index);
 
	NetworkSend_uint8(p, errorno);
 

	
 
	NetworkSend_Packet(p, cs);
 
}
 

	
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_QUIT)(NetworkClientState *cs, uint16 client_index, const char *leavemsg)
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_QUIT)(NetworkTCPSocketHandler *cs, uint16 client_index, const char *leavemsg)
 
{
 
	//
 
	// Packet: SERVER_ERROR_QUIT
 
	// Function: A client left the game, and this packets informs the other clients
 
	//      of that.
 
	// Data:
 
@@ -545,24 +545,24 @@ DEF_SERVER_SEND_COMMAND(PACKET_SERVER_NE
 
	//
 

	
 
	Packet *p = NetworkSend_Init(PACKET_SERVER_NEWGAME);
 
	NetworkSend_Packet(p, cs);
 
}
 

	
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_RCON)(NetworkClientState *cs, uint16 color, const char *command)
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_RCON)(NetworkTCPSocketHandler *cs, uint16 color, const char *command)
 
{
 
	Packet *p = NetworkSend_Init(PACKET_SERVER_RCON);
 

	
 
	NetworkSend_uint16(p, color);
 
	NetworkSend_string(p, command);
 
	NetworkSend_Packet(p, cs);
 
}
 

	
 
// **********
 
// Receiving functions
 
//   DEF_SERVER_RECEIVE_COMMAND has parameter: NetworkClientState *cs, Packet *p
 
//   DEF_SERVER_RECEIVE_COMMAND has parameter: NetworkTCPSocketHandler *cs, Packet *p
 
// **********
 

	
 
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_COMPANY_INFO)
 
{
 
	SEND_COMMAND(PACKET_SERVER_COMPANY_INFO)(cs);
 
}
 
@@ -693,13 +693,13 @@ DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT
 
	SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
 
	return;
 
}
 

	
 
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_GETMAP)
 
{
 
	const NetworkClientState *new_cs;
 
	NetworkTCPSocketHandler *new_cs;
 

	
 
	// The client was never joined.. so this is impossible, right?
 
	//  Ignore the packet, give the client a warning, and close his connection
 
	if (cs->status < STATUS_AUTH || cs->has_quit) {
 
		SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_AUTHORIZED);
 
		return;
 
@@ -721,13 +721,13 @@ DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT
 

	
 
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_MAP_OK)
 
{
 
	// Client has the map, now start syncing
 
	if (cs->status == STATUS_DONE_MAP && !cs->has_quit) {
 
		char client_name[NETWORK_CLIENT_NAME_LENGTH];
 
		NetworkClientState *new_cs;
 
		NetworkTCPSocketHandler *new_cs;
 

	
 
		NetworkGetClientName(client_name, sizeof(client_name), cs);
 

	
 
		NetworkTextMessage(NETWORK_ACTION_JOIN, 1, false, client_name, "");
 

	
 
		// Mark the client as pre-active, and wait for an ACK
 
@@ -786,13 +786,13 @@ static bool CheckCommandFlags(const Comm
 
/** The client has done a command and wants us to handle it
 
 * @param *cs the connected client that has sent the command
 
 * @param *p the packet in which the command was sent
 
 */
 
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_COMMAND)
 
{
 
	NetworkClientState *new_cs;
 
	NetworkTCPSocketHandler *new_cs;
 
	const NetworkClientInfo *ci;
 
	byte callback;
 

	
 
	CommandPacket *cp = MallocT<CommandPacket>(1);
 

	
 
	// The client was never joined.. so this is impossible, right?
 
@@ -885,13 +885,13 @@ DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT
 
}
 

	
 
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_ERROR)
 
{
 
	// This packets means a client noticed an error and is reporting this
 
	//  to us. Display the error and report it to the other clients
 
	NetworkClientState *new_cs;
 
	NetworkTCPSocketHandler *new_cs;
 
	char str[100];
 
	char client_name[NETWORK_CLIENT_NAME_LENGTH];
 
	NetworkErrorCode errorno = (NetworkErrorCode)NetworkRecv_uint8(cs, p);
 

	
 
	// The client was never joined.. thank the client for the packet, but ignore it
 
	if (cs->status < STATUS_DONE_MAP || cs->has_quit) {
 
@@ -917,13 +917,13 @@ DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT
 
}
 

	
 
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_QUIT)
 
{
 
	// The client wants to leave. Display this and report it to the other
 
	//  clients.
 
	NetworkClientState *new_cs;
 
	NetworkTCPSocketHandler *new_cs;
 
	char str[100];
 
	char client_name[NETWORK_CLIENT_NAME_LENGTH];
 

	
 
	// The client was never joined.. thank the client for the packet, but ignore it
 
	if (cs->status < STATUS_DONE_MAP || cs->has_quit) {
 
		cs->has_quit = true;
 
@@ -975,13 +975,13 @@ DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT
 
}
 

	
 

	
 

	
 
void NetworkServer_HandleChat(NetworkAction action, DestType desttype, int dest, const char *msg, uint16 from_index)
 
{
 
	NetworkClientState *cs;
 
	NetworkTCPSocketHandler *cs;
 
	const NetworkClientInfo *ci, *ci_own, *ci_to;
 

	
 
	switch (desttype) {
 
	case DESTTYPE_CLIENT:
 
		/* Are we sending to the server? */
 
		if (dest == NETWORK_SERVER_INDEX) {
 
@@ -1138,13 +1138,13 @@ DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT
 
	IConsoleCmdExec(command);
 
	_redirect_console_to_client = 0;
 
	return;
 
}
 

	
 
// The layout for the receive-functions by the server
 
typedef void NetworkServerPacket(NetworkClientState *cs, Packet *p);
 
typedef void NetworkServerPacket(NetworkTCPSocketHandler *cs, Packet *p);
 

	
 

	
 
// This array matches PacketType. At an incoming
 
//  packet it is matches against this array
 
//  and that way the right function to handle that
 
//  packet is found.
 
@@ -1190,13 +1190,13 @@ assert_compile(lengthof(_network_server_
 
void NetworkPopulateCompanyInfo(void)
 
{
 
	char password[NETWORK_PASSWORD_LENGTH];
 
	const Player *p;
 
	const Vehicle *v;
 
	const Station *s;
 
	const NetworkClientState *cs;
 
	NetworkTCPSocketHandler *cs;
 
	const NetworkClientInfo *ci;
 
	uint i;
 
	uint16 months_empty;
 

	
 
	FOR_ALL_PLAYERS(p) {
 
		if (!p->is_active) {
 
@@ -1299,13 +1299,13 @@ void NetworkPopulateCompanyInfo(void)
 
	}
 
}
 

	
 
// Send a packet to all clients with updated info about this client_index
 
void NetworkUpdateClientInfo(uint16 client_index)
 
{
 
	NetworkClientState *cs;
 
	NetworkTCPSocketHandler *cs;
 
	NetworkClientInfo *ci = NetworkFindClientInfoFromIndex(client_index);
 

	
 
	if (ci == NULL) return;
 

	
 
	FOR_ALL_CLIENTS(cs) {
 
		SEND_COMMAND(PACKET_SERVER_CLIENT_INFO)(cs, ci);
 
@@ -1326,13 +1326,13 @@ static void NetworkCheckRestartMap(void)
 
    Two things happen:
 
      1) If a company is not protected, it is closed after 1 year (for example)
 
      2) If a company is protected, protection is disabled after 3 years (for example)
 
           (and item 1. happens a year later) */
 
static void NetworkAutoCleanCompanies(void)
 
{
 
	const NetworkClientState *cs;
 
	NetworkTCPSocketHandler *cs;
 
	const NetworkClientInfo *ci;
 
	const Player *p;
 
	bool clients_in_company[MAX_PLAYERS];
 

	
 
	if (!_network_autoclean_companies) return;
 

	
 
@@ -1379,13 +1379,13 @@ static void NetworkAutoCleanCompanies(vo
 
}
 

	
 
// This function changes new_name to a name that is unique (by adding #1 ...)
 
//  and it returns true if that succeeded.
 
bool NetworkFindName(char new_name[NETWORK_CLIENT_NAME_LENGTH])
 
{
 
	NetworkClientState *new_cs;
 
	NetworkTCPSocketHandler *new_cs;
 
	bool found_name = false;
 
	byte number = 0;
 
	char original_name[NETWORK_CLIENT_NAME_LENGTH];
 

	
 
	// We use NETWORK_CLIENT_NAME_LENGTH in here, because new_name is really a pointer
 
	ttd_strlcpy(original_name, new_name, NETWORK_CLIENT_NAME_LENGTH);
 
@@ -1418,13 +1418,13 @@ bool NetworkFindName(char new_name[NETWO
 
	}
 

	
 
	return found_name;
 
}
 

	
 
// Reads a packet from the stream
 
bool NetworkServer_ReadPackets(NetworkClientState *cs)
 
bool NetworkServer_ReadPackets(NetworkTCPSocketHandler *cs)
 
{
 
	Packet *p;
 
	NetworkRecvStatus res;
 
	while ((p = NetworkRecv_Packet(cs, &res)) != NULL) {
 
		byte type = NetworkRecv_uint8(cs, p);
 
		if (type < PACKET_END && _network_server_packet[type] != NULL && !cs->has_quit) {
 
@@ -1436,13 +1436,13 @@ bool NetworkServer_ReadPackets(NetworkCl
 
	}
 

	
 
	return true;
 
}
 

	
 
// Handle the local command-queue
 
static void NetworkHandleCommandQueue(NetworkClientState* cs)
 
static void NetworkHandleCommandQueue(NetworkTCPSocketHandler* cs)
 
{
 
	CommandPacket *cp;
 

	
 
	while ( (cp = cs->command_queue) != NULL) {
 
		SEND_COMMAND(PACKET_SERVER_COMMAND)(cs, cp);
 

	
 
@@ -1451,13 +1451,13 @@ static void NetworkHandleCommandQueue(Ne
 
	}
 
}
 

	
 
// This is called every tick if this is a _network_server
 
void NetworkServer_Tick(bool send_frame)
 
{
 
	NetworkClientState *cs;
 
	NetworkTCPSocketHandler *cs;
 
#ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
 
	bool send_sync = false;
 
#endif
 

	
 
#ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
 
	if (_frame_counter >= _last_sync_frame + _network_sync_freq) {
src/network/network_server.h
Show inline comments
 
@@ -3,22 +3,22 @@
 
#ifndef NETWORK_SERVER_H
 
#define NETWORK_SERVER_H
 

	
 
#ifdef ENABLE_NETWORK
 

	
 
DEF_SERVER_SEND_COMMAND(PACKET_SERVER_MAP);
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_ERROR_QUIT)(NetworkClientState *cs, uint16 client_index, NetworkErrorCode errorno);
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_ERROR)(NetworkClientState *cs, NetworkErrorCode error);
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_ERROR_QUIT)(NetworkTCPSocketHandler *cs, uint16 client_index, NetworkErrorCode errorno);
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_ERROR)(NetworkTCPSocketHandler *cs, NetworkErrorCode error);
 
DEF_SERVER_SEND_COMMAND(PACKET_SERVER_SHUTDOWN);
 
DEF_SERVER_SEND_COMMAND(PACKET_SERVER_NEWGAME);
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_RCON)(NetworkClientState *cs, uint16 color, const char *command);
 
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_RCON)(NetworkTCPSocketHandler *cs, uint16 color, const char *command);
 

	
 
bool NetworkFindName(char new_name[NETWORK_CLIENT_NAME_LENGTH]);
 
void NetworkServer_HandleChat(NetworkAction action, DestType type, int dest, const char *msg, uint16 from_index);
 

	
 
bool NetworkServer_ReadPackets(NetworkClientState *cs);
 
bool NetworkServer_ReadPackets(NetworkTCPSocketHandler *cs);
 
void NetworkServer_Tick(bool send_frame);
 
void NetworkServerMonthlyLoop(void);
 
void NetworkServerYearlyLoop(void);
 

	
 
static inline const char* GetPlayerIP(const NetworkClientInfo* ci)
 
{
src/network/network_udp.cpp
Show inline comments
 
@@ -90,13 +90,13 @@ DEF_UDP_RECEIVE_COMMAND(Server, PACKET_U
 

	
 
	DEBUG(net, 2, "[udp] queried from '%s'", inet_ntoa(client_addr->sin_addr));
 
}
 

	
 
DEF_UDP_RECEIVE_COMMAND(Server, PACKET_UDP_CLIENT_DETAIL_INFO)
 
{
 
	NetworkClientState *cs;
 
	NetworkTCPSocketHandler *cs;
 
	NetworkClientInfo *ci;
 
	Packet *packet;
 
	Player *player;
 
	byte current = 0;
 
	int i;
 

	
 
@@ -218,13 +218,13 @@ DEF_UDP_RECEIVE_COMMAND(Server, PACKET_U
 
	Packet *packet;
 
	uint8 in_reply_count = 0;
 
	uint packet_len = 0;
 

	
 
	DEBUG(net, 6, "[udp] newgrf data request from %s:%d", inet_ntoa(client_addr->sin_addr), ntohs(client_addr->sin_port));
 

	
 
	num_grfs = NetworkRecv_uint8 (&this->cs, p);
 
	num_grfs = NetworkRecv_uint8 (this, p);
 
	if (num_grfs > NETWORK_MAX_GRF_COUNT) return;
 

	
 
	for (i = 0; i < num_grfs; i++) {
 
		GRFConfig c;
 
		const GRFConfig *f;
 

	
 
@@ -357,20 +357,21 @@ DEF_UDP_RECEIVE_COMMAND(Client, PACKET_U
 
	/* packet begins with the protocol version (uint8)
 
	 * then an uint16 which indicates how many
 
	 * ip:port pairs are in this packet, after that
 
	 * an uint32 (ip) and an uint16 (port) for each pair
 
	 */
 

	
 
	ver = NetworkRecv_uint8(&this->cs, p);
 

	
 
	if (this->cs.has_quit) return;
 
	ver = NetworkRecv_uint8(this, p);
 

	
 
	if (ver == 1) {
 
		for (i = NetworkRecv_uint16(&this->cs, p); i != 0 ; i--) {
 
			ip.s_addr = TO_LE32(NetworkRecv_uint32(&this->cs, p));
 
			port = NetworkRecv_uint16(&this->cs, p);
 
		for (i = NetworkRecv_uint16(this, p); i != 0 ; i--) {
 
			ip.s_addr = TO_LE32(NetworkRecv_uint32(this, p));
 
			port = NetworkRecv_uint16(this, p);
 

	
 
			/* Somehow we reached the end of the packet */
 
			if (this->HasClientQuit()) return;
 
			NetworkUDPQueryServer(inet_ntoa(ip), port);
 
		}
 
	}
 
}
 

	
 
/** The return of the client's request of the names of some NewGRFs */
 
@@ -378,22 +379,22 @@ DEF_UDP_RECEIVE_COMMAND(Client, PACKET_U
 
{
 
	uint8 num_grfs;
 
	uint i;
 

	
 
	DEBUG(net, 6, "[udp] newgrf data reply from %s:%d", inet_ntoa(client_addr->sin_addr), ntohs(client_addr->sin_port));
 

	
 
	num_grfs = NetworkRecv_uint8 (&this->cs, p);
 
	num_grfs = NetworkRecv_uint8 (this, p);
 
	if (num_grfs > NETWORK_MAX_GRF_COUNT) return;
 

	
 
	for (i = 0; i < num_grfs; i++) {
 
		char *unknown_name;
 
		char name[NETWORK_GRF_NAME_LENGTH];
 
		GRFConfig c;
 

	
 
		this->Recv_GRFIdentifier(p, &c);
 
		NetworkRecv_string(&this->cs, p, name, sizeof(name));
 
		NetworkRecv_string(this, p, name, sizeof(name));
 

	
 
		/* An empty name is not possible under normal circumstances
 
		 * and causes problems when showing the NewGRF list. */
 
		if (strlen(name) == 0) continue;
 

	
 
		/* Finds the fake GRFConfig for the just read GRF ID and MD5sum tuple.
 
@@ -462,13 +463,13 @@ static void NetworkUDPBroadCast(NetworkU
 
// Request the the server-list from the master server
 
void NetworkUDPQueryMasterServer(void)
 
{
 
	struct sockaddr_in out_addr;
 
	Packet *p;
 

	
 
	if (!_udp_client_socket->IsListening()) {
 
	if (!_udp_client_socket->IsConnected()) {
 
		if (!_udp_client_socket->Listen(0, 0, true)) return;
 
	}
 

	
 
	p = NetworkSend_Init(PACKET_UDP_CLIENT_GET_LIST);
 

	
 
	out_addr.sin_family = AF_INET;
 
@@ -489,13 +490,13 @@ void NetworkUDPQueryMasterServer(void)
 
void NetworkUDPSearchGame(void)
 
{
 
	// We are still searching..
 
	if (_network_udp_broadcast > 0) return;
 

	
 
	// No UDP-socket yet..
 
	if (!_udp_client_socket->IsListening()) {
 
	if (!_udp_client_socket->IsConnected()) {
 
		if (!_udp_client_socket->Listen(0, 0, true)) return;
 
	}
 

	
 
	DEBUG(net, 0, "[udp] searching server");
 

	
 
	NetworkUDPBroadCast(_udp_client_socket);
 
@@ -506,13 +507,13 @@ NetworkGameList *NetworkUDPQueryServer(c
 
{
 
	struct sockaddr_in out_addr;
 
	Packet *p;
 
	NetworkGameList *item;
 

	
 
	// No UDP-socket yet..
 
	if (!_udp_client_socket->IsListening()) {
 
	if (!_udp_client_socket->IsConnected()) {
 
		if (!_udp_client_socket->Listen(0, 0, true)) return NULL;
 
	}
 

	
 
	out_addr.sin_family = AF_INET;
 
	out_addr.sin_port = htons(port);
 
	out_addr.sin_addr.s_addr = NetworkResolveHost(host);
 
@@ -542,13 +543,13 @@ void NetworkUDPRemoveAdvertise(void)
 
	Packet *p;
 

	
 
	/* Check if we are advertising */
 
	if (!_networking || !_network_server || !_network_udp_server) return;
 

	
 
	/* check for socket */
 
	if (!_udp_master_socket->IsListening()) {
 
	if (!_udp_master_socket->IsConnected()) {
 
		if (!_udp_master_socket->Listen(0, 0, false)) return;
 
	}
 

	
 
	DEBUG(net, 1, "[udp] removing advertise from master server");
 

	
 
	/* Find somewhere to send */
 
@@ -575,13 +576,13 @@ void NetworkUDPAdvertise(void)
 

	
 
	/* Check if we should send an advertise */
 
	if (!_networking || !_network_server || !_network_udp_server || !_network_advertise)
 
		return;
 

	
 
	/* check for socket */
 
	if (!_udp_master_socket->IsListening()) {
 
	if (!_udp_master_socket->IsConnected()) {
 
		if (!_udp_master_socket->Listen(0, 0, false)) return;
 
	}
 

	
 
	if (_network_need_advertise) {
 
		_network_need_advertise = false;
 
		_network_advertise_retries = ADVERTISE_RETRY_TIMES;
0 comments (0 inline, 0 general)