1
0
mirror of https://github.com/OpenTTD/OpenTTD.git synced 2025-08-19 20:49:11 +00:00

(svn r7759) -Merge: makefile rewrite. This merge features:

- A proper ./configure, so everything needs to be configured only once, not for every make.
 - Usage of makedepend when available. This greatly reduces the time needed for generating the dependencies.
 - A generator for all project files. There is a single file with sources, which is used to generate Makefiles and the project files for MSVC.
 - Proper support for OSX universal binaries.
 - Object files for non-MSVC compiles are also placed in separate directories, making is faster to switch between debug and release compiles and it does not touch the directory with the source files.
 - Functionality to make a bundle of all needed files for for example a nightly or distribution of a binary with all needed GRFs and language files.

Note: as this merge moves almost all files, it is recommended to make a backup of your working copy before updating your working copy.
This commit is contained in:
rubidium
2007-01-02 19:19:48 +00:00
parent ccc0a3f4db
commit 66bbf336c6
448 changed files with 8150 additions and 6127 deletions

49
src/network/core/config.h Normal file
View File

@@ -0,0 +1,49 @@
/* $Id$ */
#ifndef NETWORK_CORE_CONFIG_H
#define NETWORK_CORE_CONFIG_H
#ifdef ENABLE_NETWORK
/** DNS hostname of the masterserver */
#define NETWORK_MASTER_SERVER_HOST "master.openttd.org"
/** Message sent to the masterserver to 'identify' this client as OpenTTD */
#define NETWORK_MASTER_SERVER_WELCOME_MESSAGE "OpenTTDRegister"
enum {
NETWORK_MASTER_SERVER_PORT = 3978, ///< The default port of the master server (UDP)
NETWORK_DEFAULT_PORT = 3979, ///< The default port of the game server (TCP & UDP)
SEND_MTU = 1460, ///< Number of bytes we can pack in a single packet
NETWORK_GAME_INFO_VERSION = 4, ///< What version of game-info do we use?
NETWORK_COMPANY_INFO_VERSION = 4, ///< What version of company info is this?
NETWORK_MASTER_SERVER_VERSION = 1, ///< What version of master-server-protocol do we use?
NETWORK_NAME_LENGTH = 80, ///< The maximum length of the server name and map name, in bytes including '\0'
NETWORK_HOSTNAME_LENGTH = 80, ///< The maximum length of the host name, in bytes including '\0'
NETWORK_REVISION_LENGTH = 15, ///< The maximum length of the revision, in bytes including '\0'
NETWORK_PASSWORD_LENGTH = 20, ///< The maximum length of the password, in bytes including '\0'
NETWORK_PLAYERS_LENGTH = 200, ///< The maximum length for the list of players that controls a company, in bytes including '\0'
NETWORK_CLIENT_NAME_LENGTH = 25, ///< The maximum length of a player, in bytes including '\0'
NETWORK_RCONCOMMAND_LENGTH = 500, ///< The maximum length of a rconsole command, in bytes including '\0'
NETWORK_GRF_NAME_LENGTH = 80, ///< Maximum length of the name of a GRF
/**
* Maximum number of GRFs that can be sent.
* This value is related to number of handles (files) OpenTTD can open.
* This is currently 64 and about 10 are currently used when OpenTTD loads
* without any NewGRFs. Therefore one can only load about 55 NewGRFs, so
* this is not a limit, but rather a way to easily check whether the limit
* imposed by the handle count is reached. Secondly it isn't possible to
* send much more GRF IDs + MD5sums in the PACKET_UDP_SERVER_RESPONSE, due
* to the limited size of UDP packets.
*/
NETWORK_MAX_GRF_COUNT = 55,
NETWORK_NUM_LANGUAGES = 4, ///< Number of known languages (to the network protocol) + 1 for 'any'.
};
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_CONFIG_H */

47
src/network/core/game.h Normal file
View File

@@ -0,0 +1,47 @@
/* $Id$ */
#ifndef NETWORK_CORE_GAME_H
#define NETWORK_CORE_GAME_H
#ifdef ENABLE_NETWORK
/**
* @file game.h Information about a game that is sent between a
* game server, game client and masterserver.
*/
/**
* This is the struct used by both client and server
* some fields will be empty on the client (like game_password) by default
* and only filled with data a player enters.
*/
typedef struct NetworkGameInfo {
byte game_info_version; ///< Version of the game info
char server_name[NETWORK_NAME_LENGTH]; ///< Server name
char hostname[NETWORK_HOSTNAME_LENGTH]; ///< Hostname of the server (if any)
char server_revision[NETWORK_REVISION_LENGTH]; ///< The version number the server is using (e.g.: 'r304' or 0.5.0)
bool version_compatible; ///< Can we connect to this server or not? (based on server_revision)
bool compatible; ///< Can we connect to this server or not? (based on server_revision _and_ grf_match
byte server_lang; ///< Language of the server (we should make a nice table for this)
byte use_password; ///< Is set to != 0 if it uses a password
char server_password[NETWORK_PASSWORD_LENGTH]; ///< On the server: the game password, on the client: != "" if server has password
byte clients_max; ///< Max clients allowed on server
byte clients_on; ///< Current count of clients on server
byte companies_max; ///< Max companies allowed on server
byte companies_on; ///< How many started companies do we have
byte spectators_max; ///< Max spectators allowed on server
byte spectators_on; ///< How many spectators do we have?
Date game_date; ///< Current date
Date start_date; ///< When the game started
char map_name[NETWORK_NAME_LENGTH]; ///< Map which is played ["random" for a randomized map]
uint16 map_width; ///< Map width
uint16 map_height; ///< Map height
byte map_set; ///< Graphical set
bool dedicated; ///< Is this a dedicated server?
char rcon_password[NETWORK_PASSWORD_LENGTH]; ///< RCon password for the server. "" if rcon is disabled
struct GRFConfig *grfconfig; ///< List of NewGRF files used
} NetworkGameInfo;
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_GAME_H */

View File

@@ -0,0 +1,181 @@
/* $Id$ */
#ifndef NETWORK_CORE_OS_ABSTRACTION_H
#define NETWORK_CORE_OS_ABSTRACTION_H
/**
* @file os_abstraction.h Network stuff has many things that needs to be
* included and/or implemented by default.
* All those things are in this file.
*/
/* Include standard stuff per OS */
#ifdef ENABLE_NETWORK
/* Windows stuff */
#if defined(WIN32) || defined(WIN64)
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#if !(defined(__MINGW32__) || defined(__CYGWIN__))
/* Windows has some different names for some types */
typedef SSIZE_T ssize_t;
typedef int socklen_t;
#endif
#define GET_LAST_ERROR() WSAGetLastError()
#define EWOULDBLOCK WSAEWOULDBLOCK
/* Windows has some different names for some types */
typedef unsigned long in_addr_t;
#endif /* WIN32 */
/* UNIX stuff */
#if defined(UNIX)
# 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
/* 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>
/* According to glibc/NEWS, <ifaddrs.h> appeared in glibc-2.3. */
# if !defined(__sgi__) && !defined(SUNOS) && !defined(__MORPHOS__) && !defined(__BEOS__) && !defined(__INNOTEK_LIBC__) \
&& !(defined(__GLIBC__) && (__GLIBC__ <= 2) && (__GLIBC_MINOR__ <= 2)) && !defined(__dietlibc__)
/* 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(SUNOS) || defined(__MORPHOS__) || defined(__BEOS__)
# define INADDR_NONE 0xffffffff
# endif
# if defined(__BEOS__) && !defined(BEOS_NET_SERVER)
/* needed on Zeta */
# include <sys/sockio.h>
# endif
# endif /* BEOS_NET_SERVER */
# if !defined(__BEOS__) && defined(__GLIBC__) && (__GLIBC__ <= 2) && (__GLIBC_MINOR__ <= 1)
typedef uint32_t in_addr_t;
# endif
# include <errno.h>
# include <sys/time.h>
# include <netdb.h>
#endif // UNIX
#ifdef __BEOS__
typedef int socklen_t;
#endif
/* OS/2 stuff */
#if defined(__OS2__)
# define SOCKET int
# define INVALID_SOCKET -1
# define ioctlsocket ioctl
# define closesocket close
# define GET_LAST_ERROR() (sock_errno())
/* Includes needed for OS/2 systems */
# include <types.h>
# include <unistd.h>
# include <sys/ioctl.h>
# include <sys/socket.h>
# include <netinet/in.h>
# include <netinet/tcp.h>
# include <arpa/inet.h>
# include <net/if.h>
# include <errno.h>
# include <sys/time.h>
# include <netdb.h>
# include <nerrno.h>
# define INADDR_NONE 0xffffffff
typedef int socklen_t;
#if !defined(__INNOTEK_LIBC__)
typedef unsigned long in_addr_t;
#endif /* __INNOTEK_LIBC__ */
#endif /* OS/2 */
/* MorphOS and Amiga stuff */
#if defined(__MORPHOS__) || defined(__AMIGA__)
# include <exec/types.h>
# include <proto/exec.h> // required for Open/CloseLibrary()
# 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__
static inline bool SetNonBlocking(int d)
{
#ifdef WIN32
u_long nonblocking = 1;
#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
}
static inline bool SetNoDelay(int 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
}
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_OS_ABSTRACTION_H */

216
src/network/core/packet.c Normal file
View File

@@ -0,0 +1,216 @@
/* $Id$ */
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#include "../../macros.h"
#include "../../string.h"
#include "os_abstraction.h"
#include "config.h"
#include "packet.h"
/**
* @file packet.h Basic functions to create, fill and read packets.
*/
/* Do not want to include functions.h and all required headers */
extern void NORETURN CDECL error(const char *str, ...);
/**
* Create a packet for sending
* @param type the of packet
* @return the newly created packet
*/
Packet *NetworkSend_Init(PacketType type)
{
Packet *packet = malloc(sizeof(Packet));
/* An error is inplace here, because it simply means we ran out of memory. */
if (packet == NULL) error("Failed to allocate Packet");
/* Skip the size so we can write that in before sending the packet */
packet->size = sizeof(packet->size);
packet->buffer[packet->size++] = type;
packet->pos = 0;
return packet;
}
/**
* Writes the packet size from the raw packet from packet->size
* @param packet the packet to write the size of
*/
void NetworkSend_FillPacketSize(Packet *packet)
{
packet->buffer[0] = GB(packet->size, 0, 8);
packet->buffer[1] = GB(packet->size, 8, 8);
}
/**
* The next couple of functions make sure we can send
* uint8, uint16, uint32 and uint64 endian-safe
* over the network. The least significant bytes are
* sent first.
*
* So 0x01234567 would be sent as 67 45 23 01.
*/
void NetworkSend_uint8(Packet *packet, uint8 data)
{
assert(packet->size < sizeof(packet->buffer) - sizeof(data));
packet->buffer[packet->size++] = data;
}
void NetworkSend_uint16(Packet *packet, uint16 data)
{
assert(packet->size < sizeof(packet->buffer) - sizeof(data));
packet->buffer[packet->size++] = GB(data, 0, 8);
packet->buffer[packet->size++] = GB(data, 8, 8);
}
void NetworkSend_uint32(Packet *packet, uint32 data)
{
assert(packet->size < sizeof(packet->buffer) - sizeof(data));
packet->buffer[packet->size++] = GB(data, 0, 8);
packet->buffer[packet->size++] = GB(data, 8, 8);
packet->buffer[packet->size++] = GB(data, 16, 8);
packet->buffer[packet->size++] = GB(data, 24, 8);
}
void NetworkSend_uint64(Packet *packet, uint64 data)
{
assert(packet->size < sizeof(packet->buffer) - sizeof(data));
packet->buffer[packet->size++] = GB(data, 0, 8);
packet->buffer[packet->size++] = GB(data, 8, 8);
packet->buffer[packet->size++] = GB(data, 16, 8);
packet->buffer[packet->size++] = GB(data, 24, 8);
packet->buffer[packet->size++] = GB(data, 32, 8);
packet->buffer[packet->size++] = GB(data, 40, 8);
packet->buffer[packet->size++] = GB(data, 48, 8);
packet->buffer[packet->size++] = GB(data, 56, 8);
}
/**
* Sends a string over the network. It sends out
* the string + '\0'. No size-byte or something.
*/
void NetworkSend_string(Packet *packet, const char* data)
{
assert(data != NULL);
assert(packet->size < sizeof(packet->buffer) - strlen(data) - 1);
while ((packet->buffer[packet->size++] = *data++) != '\0') {}
}
/**
* Receiving commands
* Again, the next couple of functions are endian-safe
* see the comment before NetworkSend_uint8 for more info.
*/
extern uint 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, Packet *packet, uint bytes_to_read)
{
/* Don't allow reading from a closed socket */
if (HasClientQuit(cs)) return false;
/* Check if variable is within packet-size */
if (packet->pos + bytes_to_read > packet->size) {
CloseConnection(cs);
return false;
}
return true;
}
/**
* Reads the packet size from the raw packet and stores it in the packet->size
* @param packet the packet to read the size of
*/
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 n;
if (!CanReadFromPacket(cs, packet, sizeof(n))) return 0;
n = packet->buffer[packet->pos++];
return n;
}
uint16 NetworkRecv_uint16(NetworkClientState *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 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 n;
if (!CanReadFromPacket(cs, packet, sizeof(n))) return 0;
n = (uint64)packet->buffer[packet->pos++];
n += (uint64)packet->buffer[packet->pos++] << 8;
n += (uint64)packet->buffer[packet->pos++] << 16;
n += (uint64)packet->buffer[packet->pos++] << 24;
n += (uint64)packet->buffer[packet->pos++] << 32;
n += (uint64)packet->buffer[packet->pos++] << 40;
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)
{
PacketSize pos;
char *bufp = buffer;
/* Don't allow reading from a closed socket */
if (HasClientQuit(cs)) return;
pos = p->pos;
while (--size > 0 && pos < p->size && (*buffer++ = p->buffer[pos++]) != '\0') {}
if (size == 0 || pos == p->size) {
*buffer = '\0';
/* If size was sooner to zero then the string in the stream
* skip till the \0, so than packet can be read out correctly for the rest */
while (pos < p->size && p->buffer[pos] != '\0') pos++;
pos++;
}
p->pos = pos;
str_validate(bufp);
}
#endif /* ENABLE_NETWORK */

67
src/network/core/packet.h Normal file
View File

@@ -0,0 +1,67 @@
/* $Id$ */
#ifndef NETWORK_CORE_PACKET_H
#define NETWORK_CORE_PACKET_H
#ifdef ENABLE_NETWORK
/**
* @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(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
* populate the packet.
* Every packet can be at most SEND_MTU bytes. Overflowing this
* limit will give an assertion when sending (i.e. writing) the
* packet. Reading past the size of the packet when receiving
* will return all 0 values and "" in case of the string.
*/
typedef struct Packet {
/** The next packet. Used for queueing packets before sending. */
struct Packet *next;
/** The size of the whole packet for received packets. For packets
* that will be sent, the value is filled in just before the
* actual transmission. */
PacketSize size;
/** The current read/write position in the packet */
PacketSize pos;
/** The buffer of this packet */
byte buffer[SEND_MTU];
} Packet;
Packet *NetworkSend_Init(PacketType type);
void NetworkSend_FillPacketSize(Packet *packet);
void NetworkSend_uint8 (Packet *packet, uint8 data);
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);
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_PACKET_H */

227
src/network/core/tcp.c Normal file
View File

@@ -0,0 +1,227 @@
/* $Id$ */
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#include "../../debug.h"
#include "../../openttd.h"
#include "../../variables.h"
#include "table/strings.h"
#include "../../functions.h"
#include "os_abstraction.h"
#include "config.h"
#include "packet.h"
#include "../network_data.h"
#include "tcp.h"
/**
* @file tcp.c Basic functions to receive and send TCP packets.
*/
/**
* 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
*/
NetworkRecvStatus CloseConnection(NetworkClientState *cs)
{
NetworkCloseClient(cs);
/* Clients drop back to the main menu */
if (!_network_server && _networking) {
_switch_mode = SM_MENU;
_networking = false;
_switch_mode_errorstr = STR_NETWORK_ERR_LOSTCONNECTION;
return NETWORK_RECV_STATUS_CONN_LOST;
}
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(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)
{
Packet *p;
assert(packet != NULL);
packet->pos = 0;
packet->next = NULL;
NetworkSend_FillPacketSize(packet);
/* Locate last packet buffered for the client */
p = cs->packet_queue;
if (p == NULL) {
/* No packets yet */
cs->packet_queue = packet;
} else {
/* Skip to the last packet */
while (p->next != NULL) p = p->next;
p->next = packet;
}
}
/**
* Sends all the buffered packets out for this client. It stops when:
* 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)
{
ssize_t res;
Packet *p;
/* We can not write to this socket!! */
if (!cs->writable) return false;
if (cs->socket == INVALID_SOCKET) return false;
p = cs->packet_queue;
while (p != NULL) {
res = send(cs->socket, 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);
return false;
}
return true;
}
if (res == 0) {
/* Client/server has left us :( */
CloseConnection(cs);
return false;
}
p->pos += res;
/* Is this packet sent? */
if (p->pos == p->size) {
/* Go to the next packet */
cs->packet_queue = p->next;
free(p);
p = cs->packet_queue;
} else {
return true;
}
}
return true;
}
/**
* 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)
{
ssize_t res;
Packet *p;
*status = NETWORK_RECV_STATUS_OKAY;
if (cs->socket == INVALID_SOCKET) return NULL;
if (cs->packet_recv == NULL) {
cs->packet_recv = malloc(sizeof(Packet));
if (cs->packet_recv == NULL) error("Failed to allocate packet");
/* Set pos to zero! */
cs->packet_recv->pos = 0;
cs->packet_recv->size = 0; // Can be ommited, just for safety reasons
}
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, 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);
return NULL;
}
/* Connection would block, so stop for now */
return NULL;
}
if (res == 0) {
/* Client/server has left */
*status = CloseConnection(cs);
return NULL;
}
p->pos += res;
}
NetworkRecv_ReadPacketSize(p);
if (p->size > SEND_MTU) {
*status = CloseConnection(cs);
return NULL;
}
}
/* Read rest of packet */
while (p->pos < p->size) {
res = recv(cs->socket, 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);
return NULL;
}
/* Connection would block */
return NULL;
}
if (res == 0) {
/* Client/server has left */
*status = CloseConnection(cs);
return NULL;
}
p->pos += res;
}
/* We have a complete packet, return it! */
p->pos = 2;
p->next = NULL; // Should not be needed, but who knows...
/* Prepare for receiving a new packet */
cs->packet_recv = NULL;
return p;
}
#endif /* ENABLE_NETWORK */

60
src/network/core/tcp.h Normal file
View File

@@ -0,0 +1,60 @@
/* $Id$ */
#ifndef NETWORK_CORE_TCP_H
#define NETWORK_CORE_TCP_H
#ifdef ENABLE_NETWORK
/**
* @file tcp.h Basic functions to receive and send TCP packets.
*/
/**
* Enum with all types of UDP packets.
* The order of the first 4 packets MUST not be changed, as
* it protects old clients from joining newer servers
* (because SERVER_ERROR is the respond to a wrong revision)
*/
enum {
PACKET_SERVER_FULL,
PACKET_SERVER_BANNED,
PACKET_CLIENT_JOIN,
PACKET_SERVER_ERROR,
PACKET_CLIENT_COMPANY_INFO,
PACKET_SERVER_COMPANY_INFO,
PACKET_SERVER_CLIENT_INFO,
PACKET_SERVER_NEED_PASSWORD,
PACKET_CLIENT_PASSWORD,
PACKET_SERVER_WELCOME,
PACKET_CLIENT_GETMAP,
PACKET_SERVER_WAIT,
PACKET_SERVER_MAP,
PACKET_CLIENT_MAP_OK,
PACKET_SERVER_JOIN,
PACKET_SERVER_FRAME,
PACKET_SERVER_SYNC,
PACKET_CLIENT_ACK,
PACKET_CLIENT_COMMAND,
PACKET_SERVER_COMMAND,
PACKET_CLIENT_CHAT,
PACKET_SERVER_CHAT,
PACKET_CLIENT_SET_PASSWORD,
PACKET_CLIENT_SET_NAME,
PACKET_CLIENT_QUIT,
PACKET_CLIENT_ERROR,
PACKET_SERVER_QUIT,
PACKET_SERVER_ERROR_QUIT,
PACKET_SERVER_SHUTDOWN,
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);
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_TCP_H */

277
src/network/core/udp.c Normal file
View File

@@ -0,0 +1,277 @@
/* $Id$ */
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#include "../../date.h"
#include "../../debug.h"
#include "../../macros.h"
#include "../../newgrf_config.h"
#include "os_abstraction.h"
#include "config.h"
#include "game.h"
#include "packet.h"
#include "udp.h"
/**
* @file udp.c Basic functions to receive and send UDP packets.
*/
/**
* 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
*/
void NetworkSendUDP_Packet(SOCKET udp, Packet *p, struct sockaddr_in *recv)
{
int res;
NetworkSend_FillPacketSize(p);
/* Send the buffer */
res = sendto(udp, 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());
}
/**
* 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
* @return true if the listening succeeded
*/
bool NetworkUDPListen(SOCKET *udp, uint32 host, uint16 port, bool broadcast)
{
struct sockaddr_in sin;
/* Make sure socket is closed */
closesocket(*udp);
*udp = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (*udp == INVALID_SOCKET) {
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(*udp, FIONBIO, &blocking);
#else
setsockopt(*udp, 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(*udp, (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(*udp, 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;
}
/**
* Receive a packet at UDP level
* @param udp the socket to receive the packet on
*/
void NetworkUDPReceive(SOCKET udp)
{
struct sockaddr_in client_addr;
socklen_t client_len;
int nbytes;
Packet p;
int packet_len;
packet_len = sizeof(p.buffer);
client_len = sizeof(client_addr);
/* Try to receive anything */
nbytes = recvfrom(udp, p.buffer, packet_len, 0, (struct sockaddr *)&client_addr, &client_len);
/* We got some bytes for the base header of the packet.
* Assume we received the whole packet. */
if (nbytes > 2) {
NetworkRecv_ReadPacketSize(&p);
/* Put the position on the right place */
p.pos = 2;
p.next = NULL;
/* Handle the packet */
NetworkHandleUDPPacket(&p, &client_addr);
}
}
/**
* Serializes the GRFIdentifier (GRF ID and MD5 checksum) to the packet
* @param p the packet to write the data to
* @param c the configuration to write the GRF ID and MD5 checksum from
*/
void NetworkSend_GRFIdentifier(Packet *p, const GRFConfig *c)
{
uint j;
NetworkSend_uint32(p, c->grfid);
for (j = 0; j < sizeof(c->md5sum); j++) {
NetworkSend_uint8 (p, c->md5sum[j]);
}
}
/**
* Deserializes the GRFIdentifier (GRF ID and MD5 checksum) from the packet
* @param cs the client state (for closing connect on out-of-bounds reading etc)
* @param p the packet to read the data from
* @param c the configuration to write the GRF ID and MD5 checksum to
*/
void NetworkRecv_GRFIdentifier(NetworkClientState *cs, Packet *p, GRFConfig *c)
{
uint j;
c->grfid = NetworkRecv_uint32(cs, p);
for (j = 0; j < sizeof(c->md5sum); j++) {
c->md5sum[j] = NetworkRecv_uint8(cs, p);
}
}
/**
* Serializes the NetworkGameInfo struct to the packet
* @param p the packet to write the data to
* @param info the NetworkGameInfo struct to serialize
*/
void NetworkSend_NetworkGameInfo(Packet *p, const NetworkGameInfo *info)
{
NetworkSend_uint8 (p, NETWORK_GAME_INFO_VERSION);
/*
* Please observe the order.
* The parts must be read in the same order as they are sent!
*/
/* NETWORK_GAME_INFO_VERSION = 4 */
{
/* Only send the GRF Identification (GRF_ID and MD5 checksum) of
* the GRFs that are needed, i.e. the ones that the server has
* selected in the NewGRF GUI and not the ones that are used due
* to the fact that they are in [newgrf-static] in openttd.cfg */
const GRFConfig *c;
uint count = 0;
/* Count number of GRFs to send information about */
for (c = info->grfconfig; c != NULL; c = c->next) {
if (!HASBIT(c->flags, GCF_STATIC)) count++;
}
NetworkSend_uint8 (p, count); // Send number of GRFs
/* Send actual GRF Identifications */
for (c = info->grfconfig; c != NULL; c = c->next) {
if (!HASBIT(c->flags, GCF_STATIC)) NetworkSend_GRFIdentifier(p, c);
}
}
/* NETWORK_GAME_INFO_VERSION = 3 */
NetworkSend_uint32(p, info->game_date);
NetworkSend_uint32(p, info->start_date);
/* NETWORK_GAME_INFO_VERSION = 2 */
NetworkSend_uint8 (p, info->companies_max);
NetworkSend_uint8 (p, info->companies_on);
NetworkSend_uint8 (p, info->spectators_max);
/* NETWORK_GAME_INFO_VERSION = 1 */
NetworkSend_string(p, info->server_name);
NetworkSend_string(p, info->server_revision);
NetworkSend_uint8 (p, info->server_lang);
NetworkSend_uint8 (p, info->use_password);
NetworkSend_uint8 (p, info->clients_max);
NetworkSend_uint8 (p, info->clients_on);
NetworkSend_uint8 (p, info->spectators_on);
NetworkSend_string(p, info->map_name);
NetworkSend_uint16(p, info->map_width);
NetworkSend_uint16(p, info->map_height);
NetworkSend_uint8 (p, info->map_set);
NetworkSend_uint8 (p, info->dedicated);
}
/**
* Deserializes the NetworkGameInfo struct from the packet
* @param cs the client state (for closing connect on out-of-bounds reading etc)
* @param p the packet to read the data from
* @param info the NetworkGameInfo to deserialize into
*/
void NetworkRecv_NetworkGameInfo(NetworkClientState *cs, Packet *p, NetworkGameInfo *info)
{
info->game_info_version = NetworkRecv_uint8(cs, p);
/*
* Please observe the order.
* The parts must be read in the same order as they are sent!
*/
switch (info->game_info_version) {
case 4: {
GRFConfig *c, **dst = &info->grfconfig;
uint i;
uint num_grfs = NetworkRecv_uint8(cs, p);
for (i = 0; i < num_grfs; i++) {
c = calloc(1, sizeof(*c));
NetworkRecv_GRFIdentifier(cs, p, c);
HandleIncomingNetworkGameInfoGRFConfig(c);
/* Append GRFConfig to the list */
*dst = c;
dst = &c->next;
}
} /* Fallthrough */
case 3:
info->game_date = NetworkRecv_uint32(cs, p);
info->start_date = NetworkRecv_uint32(cs, p);
/* Fallthrough */
case 2:
info->companies_max = NetworkRecv_uint8 (cs, p);
info->companies_on = NetworkRecv_uint8 (cs, p);
info->spectators_max = NetworkRecv_uint8 (cs, p);
/* Fallthrough */
case 1:
NetworkRecv_string(cs, p, info->server_name, sizeof(info->server_name));
NetworkRecv_string(cs, p, info->server_revision, sizeof(info->server_revision));
info->server_lang = NetworkRecv_uint8 (cs, p);
info->use_password = NetworkRecv_uint8 (cs, p);
info->clients_max = NetworkRecv_uint8 (cs, p);
info->clients_on = NetworkRecv_uint8 (cs, p);
info->spectators_on = NetworkRecv_uint8 (cs, p);
if (info->game_info_version < 3) { // 16 bits dates got scrapped and are read earlier
info->game_date = NetworkRecv_uint16(cs, p) + DAYS_TILL_ORIGINAL_BASE_YEAR;
info->start_date = NetworkRecv_uint16(cs, p) + DAYS_TILL_ORIGINAL_BASE_YEAR;
}
NetworkRecv_string(cs, p, info->map_name, sizeof(info->map_name));
info->map_width = NetworkRecv_uint16(cs, p);
info->map_height = NetworkRecv_uint16(cs, p);
info->map_set = NetworkRecv_uint8 (cs, p);
info->dedicated = NetworkRecv_uint8 (cs, p);
}
}
#endif /* ENABLE_NETWORK */

62
src/network/core/udp.h Normal file
View File

@@ -0,0 +1,62 @@
/* $Id$ */
#ifndef NETWORK_CORE_UDP_H
#define NETWORK_CORE_UDP_H
#ifdef ENABLE_NETWORK
/**
* @file udp.h Basic functions to receive and send UDP packets.
*/
///** Sending/receiving of UDP packets **////
void NetworkSendUDP_Packet(SOCKET udp, Packet *p, struct sockaddr_in *recv);
bool NetworkUDPListen(SOCKET *udp, uint32 host, uint16 port, bool broadcast);
void NetworkUDPReceive(SOCKET udp);
/**
* Function that is called for every received UDP packet.
* @param packet the received packet
* @param client_addr the address of the sender of the packet
*/
void NetworkHandleUDPPacket(Packet *p, struct sockaddr_in *client_addr);
///** Sending/receiving of (large) chuncks of UDP packets **////
/** Enum with all types of UDP packets. The order MUST not be changed **/
enum {
PACKET_UDP_CLIENT_FIND_SERVER, ///< Queries a game server for game information
PACKET_UDP_SERVER_RESPONSE, ///< Reply of the game server with game information
PACKET_UDP_CLIENT_DETAIL_INFO, ///< Queries a game server about details of the game, such as companies
PACKET_UDP_SERVER_DETAIL_INFO, ///< Reply of the game server about details of the game, such as companies
PACKET_UDP_SERVER_REGISTER, ///< Packet to register itself to the master server
PACKET_UDP_MASTER_ACK_REGISTER, ///< Packet indicating registration has succedeed
PACKET_UDP_CLIENT_GET_LIST, ///< Request for serverlist from master server
PACKET_UDP_MASTER_RESPONSE_LIST, ///< Response from master server with server ip's + port's
PACKET_UDP_SERVER_UNREGISTER, ///< Request to be removed from the server-list
PACKET_UDP_CLIENT_GET_NEWGRFS, ///< Requests the name for a list of GRFs (GRF_ID and MD5)
PACKET_UDP_SERVER_NEWGRFS, ///< Sends the list of NewGRF's requested.
PACKET_UDP_END ///< Must ALWAYS be on the end of this list!! (period)
};
void NetworkSend_GRFIdentifier(Packet *p, const GRFConfig *c);
void NetworkSend_NetworkGameInfo(Packet *p, const NetworkGameInfo *info);
void NetworkRecv_GRFIdentifier(NetworkClientState *cs, Packet *p, GRFConfig *c);
void NetworkRecv_NetworkGameInfo(NetworkClientState *cs, Packet *p, NetworkGameInfo *info);
/**
* Function that is called for every GRFConfig that is read when receiving
* a NetworkGameInfo. Only grfid and md5sum are set, the rest is zero. This
* function must set all appropriate fields. This GRF is later appended to
* the grfconfig list of the NetworkGameInfo.
* @param config the GRF to handle
*/
void HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config);
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CORE_UDP_H */

1451
src/network/network.c Normal file

File diff suppressed because it is too large Load Diff

212
src/network/network.h Normal file
View File

@@ -0,0 +1,212 @@
/* $Id$ */
#ifndef NETWORK_H
#define NETWORK_H
#define NOREV_STRING "norev000"
#ifdef ENABLE_NETWORK
#include "../player.h"
#include "core/config.h"
#include "core/game.h"
// If this line is enable, every frame will have a sync test
// this is not needed in normal games. Normal is like 1 sync in 100
// frames. You can enable this if you have a lot of desyncs on a certain
// game.
// Remember: both client and server have to be compiled with this
// option enabled to make it to work. If one of the two has it disabled
// nothing will happen.
//#define ENABLE_NETWORK_SYNC_EVERY_FRAME
// In theory sending 1 of the 2 seeds is enough to check for desyncs
// so in theory, this next define can be left off.
//#define NETWORK_SEND_DOUBLE_SEED
// How many clients can we have? Like.. MAX_PLAYERS - 1 is the amount of
// players that can really play.. so.. a max of 4 spectators.. gives us..
// MAX_PLAYERS + 3
#define MAX_CLIENTS (MAX_PLAYERS + 3)
// Do not change this next line. It should _ALWAYS_ be MAX_CLIENTS + 1
#define MAX_CLIENT_INFO (MAX_CLIENTS + 1)
#define MAX_INTERFACES 9
// How many vehicle/station types we put over the network
#define NETWORK_VEHICLE_TYPES 5
#define NETWORK_STATION_TYPES 5
typedef struct NetworkPlayerInfo {
char company_name[NETWORK_NAME_LENGTH]; // Company name
char password[NETWORK_PASSWORD_LENGTH]; // The password for the player
Year inaugurated_year; // What year the company started in
int64 company_value; // The company value
int64 money; // The amount of money the company has
int64 income; // How much did the company earned last year
uint16 performance; // What was his performance last month?
byte use_password; // 0: No password 1: There is a password
uint16 num_vehicle[NETWORK_VEHICLE_TYPES]; // How many vehicles are there of this type?
uint16 num_station[NETWORK_STATION_TYPES]; // How many stations are there of this type?
char players[NETWORK_PLAYERS_LENGTH]; // The players that control this company (Name1, name2, ..)
uint16 months_empty; // How many months the company is empty
} NetworkPlayerInfo;
typedef struct NetworkClientInfo {
uint16 client_index; // Index of the client (same as ClientState->index)
char client_name[NETWORK_CLIENT_NAME_LENGTH]; // Name of the client
byte client_lang; // The language of the client
byte client_playas; // As which player is this client playing (PlayerID)
uint32 client_ip; // IP-address of the client (so he can be banned)
Date join_date; // Gamedate the player has joined
char unique_id[NETWORK_NAME_LENGTH]; // Every play sends an unique id so we can indentify him
} NetworkClientInfo;
typedef struct NetworkGameList {
NetworkGameInfo info;
uint32 ip;
uint16 port;
bool online; // False if the server did not respond (default status)
bool manually; // True if the server was added manually
struct NetworkGameList *next;
} NetworkGameList;
typedef enum {
NETWORK_JOIN_STATUS_CONNECTING,
NETWORK_JOIN_STATUS_AUTHORIZING,
NETWORK_JOIN_STATUS_WAITING,
NETWORK_JOIN_STATUS_DOWNLOADING,
NETWORK_JOIN_STATUS_PROCESSING,
NETWORK_JOIN_STATUS_REGISTERING,
NETWORK_JOIN_STATUS_GETTING_COMPANY_INFO,
} NetworkJoinStatus;
// language ids for server_lang and client_lang
typedef enum {
NETLANG_ANY = 0,
NETLANG_ENGLISH = 1,
NETLANG_GERMAN = 2,
NETLANG_FRENCH = 3,
} NetworkLanguage;
VARDEF NetworkGameList *_network_game_list;
VARDEF NetworkGameInfo _network_game_info;
VARDEF NetworkPlayerInfo _network_player_info[MAX_PLAYERS];
VARDEF NetworkClientInfo _network_client_info[MAX_CLIENT_INFO];
VARDEF char _network_player_name[NETWORK_CLIENT_NAME_LENGTH];
VARDEF char _network_default_ip[NETWORK_HOSTNAME_LENGTH];
VARDEF uint16 _network_own_client_index;
VARDEF char _network_unique_id[NETWORK_NAME_LENGTH]; // Our own unique ID
VARDEF uint32 _frame_counter_server; // The frame_counter of the server, if in network-mode
VARDEF uint32 _frame_counter_max; // To where we may go with our clients
VARDEF uint32 _last_sync_frame; // Used in the server to store the last time a sync packet was sent to clients.
// networking settings
VARDEF uint32 _broadcast_list[MAX_INTERFACES + 1];
VARDEF uint16 _network_server_port;
/* We use bind_ip and bind_ip_host, where bind_ip_host is the readable form of
bind_ip_host, and bind_ip the numeric value, because we want a nice number
in the openttd.cfg, but we wants to use the uint32 internally.. */
VARDEF uint32 _network_server_bind_ip;
VARDEF char _network_server_bind_ip_host[NETWORK_HOSTNAME_LENGTH];
VARDEF bool _is_network_server; // Does this client wants to be a network-server?
VARDEF char _network_server_name[NETWORK_NAME_LENGTH];
VARDEF char _network_server_password[NETWORK_PASSWORD_LENGTH];
VARDEF char _network_rcon_password[NETWORK_PASSWORD_LENGTH];
VARDEF uint16 _network_max_join_time; ///< Time a client can max take to join
VARDEF bool _network_pause_on_join; ///< Pause the game when a client tries to join (more chance of succeeding join)
VARDEF uint16 _redirect_console_to_client;
VARDEF uint16 _network_sync_freq;
VARDEF uint8 _network_frame_freq;
VARDEF uint32 _sync_seed_1, _sync_seed_2;
VARDEF uint32 _sync_frame;
VARDEF bool _network_first_time;
// Vars needed for the join-GUI
VARDEF NetworkJoinStatus _network_join_status;
VARDEF uint8 _network_join_waiting;
VARDEF uint16 _network_join_kbytes;
VARDEF uint16 _network_join_kbytes_total;
VARDEF char _network_last_host[NETWORK_HOSTNAME_LENGTH];
VARDEF short _network_last_port;
VARDEF uint32 _network_last_host_ip;
VARDEF uint8 _network_reconnect;
VARDEF bool _network_udp_server;
VARDEF uint16 _network_udp_broadcast;
VARDEF byte _network_lan_internet;
VARDEF bool _network_need_advertise;
VARDEF uint32 _network_last_advertise_frame;
VARDEF uint8 _network_advertise_retries;
VARDEF bool _network_autoclean_companies;
VARDEF uint8 _network_autoclean_unprotected; // Remove a company after X months
VARDEF uint8 _network_autoclean_protected; // Unprotect a company after X months
VARDEF Year _network_restart_game_year; // If this year is reached, the server automaticly restarts
VARDEF uint8 _network_min_players; // Minimum number of players for game to unpause
NetworkGameList *NetworkQueryServer(const char* host, unsigned short port, bool game_info);
byte NetworkSpectatorCount(void);
VARDEF char *_network_host_list[10];
VARDEF char *_network_ban_list[25];
void ParseConnectionString(const char **player, const char **port, char *connection_string);
void NetworkUpdateClientInfo(uint16 client_index);
void NetworkAddServer(const char *b);
void NetworkRebuildHostList(void);
bool NetworkChangeCompanyPassword(byte argc, char *argv[]);
void NetworkPopulateCompanyInfo(void);
void UpdateNetworkGameWindow(bool unselect);
void CheckMinPlayers(void);
void NetworkStartUp(void);
void NetworkUDPClose(void);
void NetworkShutDown(void);
void NetworkGameLoop(void);
void NetworkUDPGameLoop(void);
bool NetworkServerStart(void);
bool NetworkClientConnectGame(const char *host, uint16 port);
void NetworkReboot(void);
void NetworkDisconnect(void);
VARDEF bool _networking; ///< are we in networking mode?
VARDEF bool _network_server; ///< network-server is active
VARDEF bool _network_available; ///< is network mode available?
#else /* ENABLE_NETWORK */
/* Network function stubs when networking is disabled */
static inline void NetworkStartUp(void) {}
static inline void NetworkShutDown(void) {}
#define _networking 0
#define _network_server 0
#define _network_available 0
#endif /* ENABLE_NETWORK */
/* These variables must always be registered! */
VARDEF bool _network_dedicated; ///< are we a dedicated server?
VARDEF bool _network_advertise; ///< is the server advertising to the master server?
VARDEF PlayerID _network_playas; ///< an id to play as.. (see players.h:Players)
#endif /* NETWORK_H */

View File

@@ -0,0 +1,819 @@
/* $Id$ */
#ifdef ENABLE_NETWORK
#include "../stdafx.h"
#include "../debug.h"
#include "../string.h"
#include "../strings.h"
#include "network_data.h"
#include "core/tcp.h"
#include "../date.h"
#include "table/strings.h"
#include "../functions.h"
#include "network_client.h"
#include "network_gamelist.h"
#include "network_gui.h"
#include "../saveload.h"
#include "../command.h"
#include "../window.h"
#include "../console.h"
#include "../variables.h"
#include "../ai/ai.h"
// This file handles all the client-commands
// So we don't make too much typos ;)
#define MY_CLIENT DEREF_CLIENT(0)
static uint32 last_ack_frame;
// **********
// Sending functions
// DEF_CLIENT_SEND_COMMAND has no parameters
// **********
DEF_CLIENT_SEND_COMMAND(PACKET_CLIENT_COMPANY_INFO)
{
//
// Packet: CLIENT_COMPANY_INFO
// Function: Request company-info (in detail)
// Data:
// <none>
//
Packet *p;
_network_join_status = NETWORK_JOIN_STATUS_GETTING_COMPANY_INFO;
InvalidateWindow(WC_NETWORK_STATUS_WINDOW, 0);
p = NetworkSend_Init(PACKET_CLIENT_COMPANY_INFO);
NetworkSend_Packet(p, MY_CLIENT);
}
DEF_CLIENT_SEND_COMMAND(PACKET_CLIENT_JOIN)
{
//
// Packet: CLIENT_JOIN
// Function: Try to join the server
// Data:
// String: OpenTTD Revision (norev000 if no revision)
// String: Player Name (max NETWORK_NAME_LENGTH)
// uint8: Play as Player id (1..MAX_PLAYERS)
// uint8: Language ID
// String: Unique id to find the player back in server-listing
//
extern const char _openttd_revision[];
Packet *p;
_network_join_status = NETWORK_JOIN_STATUS_AUTHORIZING;
InvalidateWindow(WC_NETWORK_STATUS_WINDOW, 0);
p = NetworkSend_Init(PACKET_CLIENT_JOIN);
NetworkSend_string(p, _openttd_revision);
NetworkSend_string(p, _network_player_name); // Player name
NetworkSend_uint8(p, _network_playas); // PlayAs
NetworkSend_uint8(p, NETLANG_ANY); // Language
NetworkSend_string(p, _network_unique_id);
NetworkSend_Packet(p, MY_CLIENT);
}
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_PASSWORD)(NetworkPasswordType type, const char *password)
{
//
// Packet: CLIENT_PASSWORD
// Function: Send a password to the server to authorize
// Data:
// uint8: NetworkPasswordType
// String: Password
//
Packet *p = NetworkSend_Init(PACKET_CLIENT_PASSWORD);
NetworkSend_uint8(p, type);
NetworkSend_string(p, password);
NetworkSend_Packet(p, MY_CLIENT);
}
DEF_CLIENT_SEND_COMMAND(PACKET_CLIENT_GETMAP)
{
//
// Packet: CLIENT_GETMAP
// Function: Request the map from the server
// Data:
// <none>
//
Packet *p = NetworkSend_Init(PACKET_CLIENT_GETMAP);
NetworkSend_Packet(p, MY_CLIENT);
}
DEF_CLIENT_SEND_COMMAND(PACKET_CLIENT_MAP_OK)
{
//
// Packet: CLIENT_MAP_OK
// Function: Tell the server that we are done receiving/loading the map
// Data:
// <none>
//
Packet *p = NetworkSend_Init(PACKET_CLIENT_MAP_OK);
NetworkSend_Packet(p, MY_CLIENT);
}
DEF_CLIENT_SEND_COMMAND(PACKET_CLIENT_ACK)
{
//
// Packet: CLIENT_ACK
// Function: Tell the server we are done with this frame
// Data:
// uint32: current FrameCounter of the client
//
Packet *p = NetworkSend_Init(PACKET_CLIENT_ACK);
NetworkSend_uint32(p, _frame_counter);
NetworkSend_Packet(p, MY_CLIENT);
}
// Send a command packet to the server
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_COMMAND)(CommandPacket *cp)
{
//
// Packet: CLIENT_COMMAND
// Function: Send a DoCommand to the Server
// Data:
// uint8: PlayerID (0..MAX_PLAYERS-1)
// uint32: CommandID (see command.h)
// uint32: P1 (free variables used in DoCommand)
// uint32: P2
// uint32: Tile
// string: text
// uint8: CallBackID (see callback_table.c)
//
Packet *p = NetworkSend_Init(PACKET_CLIENT_COMMAND);
NetworkSend_uint8(p, cp->player);
NetworkSend_uint32(p, cp->cmd);
NetworkSend_uint32(p, cp->p1);
NetworkSend_uint32(p, cp->p2);
NetworkSend_uint32(p, (uint32)cp->tile);
NetworkSend_string(p, cp->text);
NetworkSend_uint8(p, cp->callback);
NetworkSend_Packet(p, MY_CLIENT);
}
// Send a chat-packet over the network
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_CHAT)(NetworkAction action, DestType type, int dest, const char *msg)
{
//
// Packet: CLIENT_CHAT
// Function: Send a chat-packet to the serve
// Data:
// uint8: ActionID (see network_data.h, NetworkAction)
// uint8: Destination Type (see network_data.h, DestType);
// uint8: Destination Player (1..MAX_PLAYERS)
// String: Message (max MAX_TEXT_MSG_LEN)
//
Packet *p = NetworkSend_Init(PACKET_CLIENT_CHAT);
NetworkSend_uint8(p, action);
NetworkSend_uint8(p, type);
NetworkSend_uint8(p, dest);
NetworkSend_string(p, msg);
NetworkSend_Packet(p, MY_CLIENT);
}
// Send an error-packet over the network
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_ERROR)(NetworkErrorCode errorno)
{
//
// Packet: CLIENT_ERROR
// Function: The client made an error and is quiting the game
// Data:
// uint8: ErrorID (see network_data.h, NetworkErrorCode)
//
Packet *p = NetworkSend_Init(PACKET_CLIENT_ERROR);
NetworkSend_uint8(p, errorno);
NetworkSend_Packet(p, MY_CLIENT);
}
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_SET_PASSWORD)(const char *password)
{
//
// Packet: PACKET_CLIENT_SET_PASSWORD
// Function: Set the password for the clients current company
// Data:
// String: Password
//
Packet *p = NetworkSend_Init(PACKET_CLIENT_SET_PASSWORD);
NetworkSend_string(p, password);
NetworkSend_Packet(p, MY_CLIENT);
}
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_SET_NAME)(const char *name)
{
//
// Packet: PACKET_CLIENT_SET_NAME
// Function: Gives the player a new name
// Data:
// String: Name
//
Packet *p = NetworkSend_Init(PACKET_CLIENT_SET_NAME);
NetworkSend_string(p, name);
NetworkSend_Packet(p, MY_CLIENT);
}
// Send an quit-packet over the network
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_QUIT)(const char *leavemsg)
{
//
// Packet: CLIENT_QUIT
// Function: The client is quiting the game
// Data:
// String: leave-message
//
Packet *p = NetworkSend_Init(PACKET_CLIENT_QUIT);
NetworkSend_string(p, leavemsg);
NetworkSend_Packet(p, MY_CLIENT);
}
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_RCON)(const char *pass, const char *command)
{
Packet *p = NetworkSend_Init(PACKET_CLIENT_RCON);
NetworkSend_string(p, pass);
NetworkSend_string(p, command);
NetworkSend_Packet(p, MY_CLIENT);
}
// **********
// Receiving functions
// DEF_CLIENT_RECEIVE_COMMAND has parameter: Packet *p
// **********
extern bool SafeSaveOrLoad(const char *filename, int mode, int newgm);
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_FULL)
{
// We try to join a server which is full
_switch_mode_errorstr = STR_NETWORK_ERR_SERVER_FULL;
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
return NETWORK_RECV_STATUS_SERVER_FULL;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_BANNED)
{
// We try to join a server where we are banned
_switch_mode_errorstr = STR_NETWORK_ERR_SERVER_BANNED;
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
return NETWORK_RECV_STATUS_SERVER_BANNED;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_COMPANY_INFO)
{
byte company_info_version;
int i;
company_info_version = NetworkRecv_uint8(MY_CLIENT, p);
if (!MY_CLIENT->has_quit && company_info_version == NETWORK_COMPANY_INFO_VERSION) {
byte total;
byte current;
total = NetworkRecv_uint8(MY_CLIENT, p);
// There is no data at all..
if (total == 0) return NETWORK_RECV_STATUS_CLOSE_QUERY;
current = NetworkRecv_uint8(MY_CLIENT, p);
if (!IsValidPlayer(current)) return NETWORK_RECV_STATUS_CLOSE_QUERY;
NetworkRecv_string(MY_CLIENT, p, _network_player_info[current].company_name, sizeof(_network_player_info[current].company_name));
_network_player_info[current].inaugurated_year = NetworkRecv_uint32(MY_CLIENT, p);
_network_player_info[current].company_value = NetworkRecv_uint64(MY_CLIENT, p);
_network_player_info[current].money = NetworkRecv_uint64(MY_CLIENT, p);
_network_player_info[current].income = NetworkRecv_uint64(MY_CLIENT, p);
_network_player_info[current].performance = NetworkRecv_uint16(MY_CLIENT, p);
_network_player_info[current].use_password = NetworkRecv_uint8(MY_CLIENT, p);
for (i = 0; i < NETWORK_VEHICLE_TYPES; i++)
_network_player_info[current].num_vehicle[i] = NetworkRecv_uint16(MY_CLIENT, p);
for (i = 0; i < NETWORK_STATION_TYPES; i++)
_network_player_info[current].num_station[i] = NetworkRecv_uint16(MY_CLIENT, p);
NetworkRecv_string(MY_CLIENT, p, _network_player_info[current].players, sizeof(_network_player_info[current].players));
InvalidateWindow(WC_NETWORK_WINDOW, 0);
return NETWORK_RECV_STATUS_OKAY;
}
return NETWORK_RECV_STATUS_CLOSE_QUERY;
}
// This packet contains info about the client (playas and name)
// as client we save this in NetworkClientInfo, linked via 'index'
// which is always an unique number on a server.
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_CLIENT_INFO)
{
NetworkClientInfo *ci;
uint16 index = NetworkRecv_uint16(MY_CLIENT, p);
PlayerID playas = NetworkRecv_uint8(MY_CLIENT, p);
char name[NETWORK_NAME_LENGTH];
char unique_id[NETWORK_NAME_LENGTH];
NetworkRecv_string(MY_CLIENT, p, name, sizeof(name));
NetworkRecv_string(MY_CLIENT, p, unique_id, sizeof(unique_id));
if (MY_CLIENT->has_quit) return NETWORK_RECV_STATUS_CONN_LOST;
/* Do we receive a change of data? Most likely we changed playas */
if (index == _network_own_client_index) _network_playas = playas;
ci = NetworkFindClientInfoFromIndex(index);
if (ci != NULL) {
if (playas == ci->client_playas && strcmp(name, ci->client_name) != 0) {
// Client name changed, display the change
NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, 1, false, ci->client_name, "%s", name);
} else if (playas != ci->client_playas) {
// The player changed from client-player..
// Do not display that for now
}
ci->client_playas = playas;
ttd_strlcpy(ci->client_name, name, sizeof(ci->client_name));
InvalidateWindow(WC_CLIENT_LIST, 0);
return NETWORK_RECV_STATUS_OKAY;
}
// We don't have this index yet, find an empty index, and put the data there
ci = NetworkFindClientInfoFromIndex(NETWORK_EMPTY_INDEX);
if (ci != NULL) {
ci->client_index = index;
ci->client_playas = playas;
ttd_strlcpy(ci->client_name, name, sizeof(ci->client_name));
ttd_strlcpy(ci->unique_id, unique_id, sizeof(ci->unique_id));
InvalidateWindow(WC_CLIENT_LIST, 0);
return NETWORK_RECV_STATUS_OKAY;
}
// Here the program should never ever come.....
return NETWORK_RECV_STATUS_MALFORMED_PACKET;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_ERROR)
{
NetworkErrorCode error = NetworkRecv_uint8(MY_CLIENT, p);
switch (error) {
/* We made an error in the protocol, and our connection is closed.... */
case NETWORK_ERROR_NOT_AUTHORIZED:
case NETWORK_ERROR_NOT_EXPECTED:
case NETWORK_ERROR_PLAYER_MISMATCH:
_switch_mode_errorstr = STR_NETWORK_ERR_SERVER_ERROR;
break;
case NETWORK_ERROR_FULL:
_switch_mode_errorstr = STR_NETWORK_ERR_SERVER_FULL;
break;
case NETWORK_ERROR_WRONG_REVISION:
_switch_mode_errorstr = STR_NETWORK_ERR_WRONG_REVISION;
break;
case NETWORK_ERROR_WRONG_PASSWORD:
_switch_mode_errorstr = STR_NETWORK_ERR_WRONG_PASSWORD;
break;
case NETWORK_ERROR_KICKED:
_switch_mode_errorstr = STR_NETWORK_ERR_KICKED;
break;
case NETWORK_ERROR_CHEATER:
_switch_mode_errorstr = STR_NETWORK_ERR_CHEATER;
break;
default:
_switch_mode_errorstr = STR_NETWORK_ERR_LOSTCONNECTION;
}
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
return NETWORK_RECV_STATUS_SERVER_ERROR;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_NEED_PASSWORD)
{
NetworkPasswordType type = NetworkRecv_uint8(MY_CLIENT, p);
switch (type) {
case NETWORK_GAME_PASSWORD:
case NETWORK_COMPANY_PASSWORD:
ShowNetworkNeedPassword(type);
return NETWORK_RECV_STATUS_OKAY;
default: return NETWORK_RECV_STATUS_MALFORMED_PACKET;
}
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_WELCOME)
{
_network_own_client_index = NetworkRecv_uint16(MY_CLIENT, p);
// Start receiving the map
SEND_COMMAND(PACKET_CLIENT_GETMAP)();
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_WAIT)
{
_network_join_status = NETWORK_JOIN_STATUS_WAITING;
_network_join_waiting = NetworkRecv_uint8(MY_CLIENT, p);
InvalidateWindow(WC_NETWORK_STATUS_WINDOW, 0);
// We are put on hold for receiving the map.. we need GUI for this ;)
DEBUG(net, 1, "The server is currently busy sending the map to someone else, please wait..." );
DEBUG(net, 1, "There are %d clients in front of you", _network_join_waiting);
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_MAP)
{
static char filename[256];
static FILE *file_pointer;
byte maptype;
maptype = NetworkRecv_uint8(MY_CLIENT, p);
if (MY_CLIENT->has_quit) return NETWORK_RECV_STATUS_CONN_LOST;
// First packet, init some stuff
if (maptype == MAP_PACKET_START) {
// The name for the temp-map
snprintf(filename, lengthof(filename), "%s%snetwork_client.tmp", _paths.autosave_dir, PATHSEP);
file_pointer = fopen(filename, "wb");
if (file_pointer == NULL) {
_switch_mode_errorstr = STR_NETWORK_ERR_SAVEGAMEERROR;
return NETWORK_RECV_STATUS_SAVEGAME;
}
_frame_counter = _frame_counter_server = _frame_counter_max = NetworkRecv_uint32(MY_CLIENT, p);
_network_join_status = NETWORK_JOIN_STATUS_DOWNLOADING;
_network_join_kbytes = 0;
_network_join_kbytes_total = NetworkRecv_uint32(MY_CLIENT, p) / 1024;
InvalidateWindow(WC_NETWORK_STATUS_WINDOW, 0);
// The first packet does not contain any more data
return NETWORK_RECV_STATUS_OKAY;
}
if (maptype == MAP_PACKET_NORMAL) {
// We are still receiving data, put it to the file
fwrite(p->buffer + p->pos, 1, p->size - p->pos, file_pointer);
_network_join_kbytes = ftell(file_pointer) / 1024;
InvalidateWindow(WC_NETWORK_STATUS_WINDOW, 0);
}
// Check if this was the last packet
if (maptype == MAP_PACKET_END) {
fclose(file_pointer);
_network_join_status = NETWORK_JOIN_STATUS_PROCESSING;
InvalidateWindow(WC_NETWORK_STATUS_WINDOW, 0);
/* The map is done downloading, load it */
if (!SafeSaveOrLoad(filename, SL_LOAD, GM_NORMAL)) {
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
_switch_mode_errorstr = STR_NETWORK_ERR_SAVEGAMEERROR;
return NETWORK_RECV_STATUS_SAVEGAME;
}
/* If the savegame has successfully loaded, ALL windows have been removed,
* only toolbar/statusbar and gamefield are visible */
_opt_ptr = &_opt; // during a network game you are always in-game
// Say we received the map and loaded it correctly!
SEND_COMMAND(PACKET_CLIENT_MAP_OK)();
/* New company/spectator (invalid player) or company we want to join is not active
* Switch local player to spectator and await the server's judgement */
if (_network_playas == PLAYER_NEW_COMPANY || !IsValidPlayer(_network_playas) ||
!GetPlayer(_network_playas)->is_active) {
SetLocalPlayer(PLAYER_SPECTATOR);
if (_network_playas != PLAYER_SPECTATOR) {
/* We have arrived and ready to start playing; send a command to make a new player;
* the server will give us a client-id and let us in */
_network_join_status = NETWORK_JOIN_STATUS_REGISTERING;
ShowJoinStatusWindow();
NetworkSend_Command(0, 0, 0, CMD_PLAYER_CTRL, NULL);
}
} else {
// take control over an existing company
SetLocalPlayer(_network_playas);
}
}
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_FRAME)
{
_frame_counter_server = NetworkRecv_uint32(MY_CLIENT, p);
_frame_counter_max = NetworkRecv_uint32(MY_CLIENT, p);
#ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
// Test if the server supports this option
// and if we are at the frame the server is
if (p->pos < p->size) {
_sync_frame = _frame_counter_server;
_sync_seed_1 = NetworkRecv_uint32(MY_CLIENT, p);
#ifdef NETWORK_SEND_DOUBLE_SEED
_sync_seed_2 = NetworkRecv_uint32(MY_CLIENT, p);
#endif
}
#endif
DEBUG(net, 5, "Received FRAME %d", _frame_counter_server);
// Let the server know that we received this frame correctly
// We do this only once per day, to save some bandwidth ;)
if (!_network_first_time && last_ack_frame < _frame_counter) {
last_ack_frame = _frame_counter + DAY_TICKS;
DEBUG(net, 4, "Sent ACK at %d", _frame_counter);
SEND_COMMAND(PACKET_CLIENT_ACK)();
}
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_SYNC)
{
_sync_frame = NetworkRecv_uint32(MY_CLIENT, p);
_sync_seed_1 = NetworkRecv_uint32(MY_CLIENT, p);
#ifdef NETWORK_SEND_DOUBLE_SEED
_sync_seed_2 = NetworkRecv_uint32(MY_CLIENT, p);
#endif
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_COMMAND)
{
CommandPacket *cp = malloc(sizeof(CommandPacket));
cp->player = NetworkRecv_uint8(MY_CLIENT, p);
cp->cmd = NetworkRecv_uint32(MY_CLIENT, p);
cp->p1 = NetworkRecv_uint32(MY_CLIENT, p);
cp->p2 = NetworkRecv_uint32(MY_CLIENT, p);
cp->tile = NetworkRecv_uint32(MY_CLIENT, p);
NetworkRecv_string(MY_CLIENT, p, cp->text, sizeof(cp->text));
cp->callback = NetworkRecv_uint8(MY_CLIENT, p);
cp->frame = NetworkRecv_uint32(MY_CLIENT, p);
cp->next = NULL;
// The server did send us this command..
// queue it in our own queue, so we can handle it in the upcoming frame!
if (_local_command_queue == NULL) {
_local_command_queue = cp;
} else {
// Find last packet
CommandPacket *c = _local_command_queue;
while (c->next != NULL) c = c->next;
c->next = cp;
}
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_CHAT)
{
char name[NETWORK_NAME_LENGTH], msg[MAX_TEXT_MSG_LEN];
const NetworkClientInfo *ci = NULL, *ci_to;
NetworkAction action = NetworkRecv_uint8(MY_CLIENT, p);
uint16 index = NetworkRecv_uint16(MY_CLIENT, p);
bool self_send = NetworkRecv_uint8(MY_CLIENT, p);
NetworkRecv_string(MY_CLIENT, p, msg, MAX_TEXT_MSG_LEN);
ci_to = NetworkFindClientInfoFromIndex(index);
if (ci_to == NULL) return NETWORK_RECV_STATUS_OKAY;
/* Did we initiate the action locally? */
if (self_send) {
switch (action) {
case NETWORK_ACTION_CHAT_CLIENT:
/* For speaking to client we need the client-name */
snprintf(name, sizeof(name), "%s", ci_to->client_name);
ci = NetworkFindClientInfoFromIndex(_network_own_client_index);
break;
/* For speaking to company or giving money, we need the player-name */
case NETWORK_ACTION_GIVE_MONEY:
if (!IsValidPlayer(ci_to->client_playas)) return NETWORK_RECV_STATUS_OKAY;
/* fallthrough */
case NETWORK_ACTION_CHAT_COMPANY: {
StringID str = IsValidPlayer(ci_to->client_playas) ? GetPlayer(ci_to->client_playas)->name_1 : STR_NETWORK_SPECTATORS;
GetString(name, str, lastof(name));
ci = NetworkFindClientInfoFromIndex(_network_own_client_index);
} break;
default: NOT_REACHED(); break;
}
} else {
/* Display message from somebody else */
snprintf(name, sizeof(name), "%s", ci_to->client_name);
ci = ci_to;
}
if (ci != NULL)
NetworkTextMessage(action, GetDrawStringPlayerColor(ci->client_playas), self_send, name, "%s", msg);
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_ERROR_QUIT)
{
char str[100];
uint16 index;
NetworkClientInfo *ci;
index = NetworkRecv_uint16(MY_CLIENT, p);
GetNetworkErrorMsg(str, NetworkRecv_uint8(MY_CLIENT, p), lastof(str));
ci = NetworkFindClientInfoFromIndex(index);
if (ci != NULL) {
NetworkTextMessage(NETWORK_ACTION_LEAVE, 1, false, ci->client_name, "%s", str);
// The client is gone, give the NetworkClientInfo free
ci->client_index = NETWORK_EMPTY_INDEX;
}
InvalidateWindow(WC_CLIENT_LIST, 0);
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_QUIT)
{
char str[100];
uint16 index;
NetworkClientInfo *ci;
index = NetworkRecv_uint16(MY_CLIENT, p);
NetworkRecv_string(MY_CLIENT, p, str, lengthof(str));
ci = NetworkFindClientInfoFromIndex(index);
if (ci != NULL) {
NetworkTextMessage(NETWORK_ACTION_LEAVE, 1, false, ci->client_name, "%s", str);
// The client is gone, give the NetworkClientInfo free
ci->client_index = NETWORK_EMPTY_INDEX;
} else {
DEBUG(net, 0, "Unknown client (%d) is leaving the game", index);
}
InvalidateWindow(WC_CLIENT_LIST, 0);
// If we come here it means we could not locate the client.. strange :s
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_JOIN)
{
uint16 index;
NetworkClientInfo *ci;
index = NetworkRecv_uint16(MY_CLIENT, p);
ci = NetworkFindClientInfoFromIndex(index);
if (ci != NULL)
NetworkTextMessage(NETWORK_ACTION_JOIN, 1, false, ci->client_name, "");
InvalidateWindow(WC_CLIENT_LIST, 0);
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_SHUTDOWN)
{
_switch_mode_errorstr = STR_NETWORK_SERVER_SHUTDOWN;
return NETWORK_RECV_STATUS_SERVER_ERROR;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_NEWGAME)
{
// To trottle the reconnects a bit, every clients waits
// his _local_player value before reconnecting
// PLAYER_SPECTATOR is currently 255, so to avoid long wait periods
// set the max to 10.
_network_reconnect = min(_local_player + 1, 10);
_switch_mode_errorstr = STR_NETWORK_SERVER_REBOOT;
return NETWORK_RECV_STATUS_SERVER_ERROR;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_RCON)
{
char rcon_out[NETWORK_RCONCOMMAND_LENGTH];
uint16 color_code;
color_code = NetworkRecv_uint16(MY_CLIENT, p);
NetworkRecv_string(MY_CLIENT, p, rcon_out, sizeof(rcon_out));
IConsolePrint(color_code, rcon_out);
return NETWORK_RECV_STATUS_OKAY;
}
// The layout for the receive-functions by the client
typedef NetworkRecvStatus NetworkClientPacket(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.
static NetworkClientPacket* const _network_client_packet[] = {
RECEIVE_COMMAND(PACKET_SERVER_FULL),
RECEIVE_COMMAND(PACKET_SERVER_BANNED),
NULL, /*PACKET_CLIENT_JOIN,*/
RECEIVE_COMMAND(PACKET_SERVER_ERROR),
NULL, /*PACKET_CLIENT_COMPANY_INFO,*/
RECEIVE_COMMAND(PACKET_SERVER_COMPANY_INFO),
RECEIVE_COMMAND(PACKET_SERVER_CLIENT_INFO),
RECEIVE_COMMAND(PACKET_SERVER_NEED_PASSWORD),
NULL, /*PACKET_CLIENT_PASSWORD,*/
RECEIVE_COMMAND(PACKET_SERVER_WELCOME),
NULL, /*PACKET_CLIENT_GETMAP,*/
RECEIVE_COMMAND(PACKET_SERVER_WAIT),
RECEIVE_COMMAND(PACKET_SERVER_MAP),
NULL, /*PACKET_CLIENT_MAP_OK,*/
RECEIVE_COMMAND(PACKET_SERVER_JOIN),
RECEIVE_COMMAND(PACKET_SERVER_FRAME),
RECEIVE_COMMAND(PACKET_SERVER_SYNC),
NULL, /*PACKET_CLIENT_ACK,*/
NULL, /*PACKET_CLIENT_COMMAND,*/
RECEIVE_COMMAND(PACKET_SERVER_COMMAND),
NULL, /*PACKET_CLIENT_CHAT,*/
RECEIVE_COMMAND(PACKET_SERVER_CHAT),
NULL, /*PACKET_CLIENT_SET_PASSWORD,*/
NULL, /*PACKET_CLIENT_SET_NAME,*/
NULL, /*PACKET_CLIENT_QUIT,*/
NULL, /*PACKET_CLIENT_ERROR,*/
RECEIVE_COMMAND(PACKET_SERVER_QUIT),
RECEIVE_COMMAND(PACKET_SERVER_ERROR_QUIT),
RECEIVE_COMMAND(PACKET_SERVER_SHUTDOWN),
RECEIVE_COMMAND(PACKET_SERVER_NEWGAME),
RECEIVE_COMMAND(PACKET_SERVER_RCON),
NULL, /*PACKET_CLIENT_RCON,*/
};
// If this fails, check the array above with network_data.h
assert_compile(lengthof(_network_client_packet) == PACKET_END);
// Is called after a client is connected to the server
void NetworkClient_Connected(void)
{
// Set the frame-counter to 0 so nothing happens till we are ready
_frame_counter = 0;
_frame_counter_server = 0;
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)
{
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);
if (type < PACKET_END && _network_client_packet[type] != NULL && !MY_CLIENT->has_quit) {
res = _network_client_packet[type](p);
} else {
res = NETWORK_RECV_STATUS_MALFORMED_PACKET;
DEBUG(net, 0, "[client] received invalid packet type %d", type);
}
free(p);
}
return res;
}
#endif /* ENABLE_NETWORK */

View File

@@ -0,0 +1,25 @@
/* $Id$ */
#ifndef NETWORK_CLIENT_H
#define NETWORK_CLIENT_H
#ifdef ENABLE_NETWORK
DEF_CLIENT_SEND_COMMAND(PACKET_CLIENT_GAME_INFO);
DEF_CLIENT_SEND_COMMAND(PACKET_CLIENT_COMPANY_INFO);
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_COMMAND)(CommandPacket *cp);
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_ERROR)(NetworkErrorCode errorno);
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_QUIT)(const char *leavemsg);
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_CHAT)(NetworkAction action, DestType desttype, int dest, const char *msg);
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);
void NetworkClient_Connected(void);
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_CLIENT_H */

106
src/network/network_data.c Normal file
View File

@@ -0,0 +1,106 @@
/* $Id$ */
#ifdef ENABLE_NETWORK
#include "../stdafx.h"
#include "../debug.h"
#include "network_data.h"
#include "../string.h"
#include "network_client.h"
#include "../command.h"
#include "../callback_table.h"
// Add a command to the local command queue
void NetworkAddCommandQueue(NetworkClientState *cs, CommandPacket *cp)
{
CommandPacket* new_cp = malloc(sizeof(*new_cp));
*new_cp = *cp;
if (cs->command_queue == NULL) {
cs->command_queue = new_cp;
} else {
CommandPacket *c = cs->command_queue;
while (c->next != NULL) c = c->next;
c->next = new_cp;
}
}
// Prepare a DoCommand to be send over the network
void NetworkSend_Command(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback)
{
CommandPacket *c = malloc(sizeof(CommandPacket));
byte temp_callback;
c->player = _local_player;
c->next = NULL;
c->tile = tile;
c->p1 = p1;
c->p2 = p2;
c->cmd = cmd;
c->callback = 0;
temp_callback = 0;
while (temp_callback < _callback_table_count && _callback_table[temp_callback] != callback)
temp_callback++;
if (temp_callback == _callback_table_count) {
DEBUG(net, 0, "Unknown callback. (Pointer: %p) No callback sent", callback);
temp_callback = 0; /* _callback_table[0] == NULL */
}
if (_network_server) {
// We are the server, so set the command to be executed next possible frame
c->frame = _frame_counter_max + 1;
} else {
c->frame = 0; // The client can't tell which frame, so just make it 0
}
ttd_strlcpy(c->text, (_cmd_text != NULL) ? _cmd_text : "", lengthof(c->text));
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;
// And we queue it for delivery to the clients
FOR_ALL_CLIENTS(cs) {
if (cs->status > STATUS_AUTH) NetworkAddCommandQueue(cs, c);
}
// Only the server gets the callback, because clients should not get them
c->callback = temp_callback;
if (_local_command_queue == NULL) {
_local_command_queue = c;
} else {
// Find last packet
CommandPacket *cp = _local_command_queue;
while (cp->next != NULL) cp = cp->next;
cp->next = c;
}
return;
}
// Clients send their command to the server and forget all about the packet
c->callback = temp_callback;
SEND_COMMAND(PACKET_CLIENT_COMMAND)(c);
}
// Execute a DoCommand we received from the network
void NetworkExecuteCommand(CommandPacket *cp)
{
_current_player = cp->player;
_cmd_text = cp->text;
/* cp->callback is unsigned. so we don't need to do lower bounds checking. */
if (cp->callback > _callback_table_count) {
DEBUG(net, 0, "Received out-of-bounds callback (%d)", cp->callback);
cp->callback = 0;
}
DoCommandP(cp->tile, cp->p1, cp->p2, _callback_table[cp->callback], cp->cmd | CMD_NETWORK_COMMAND);
}
#endif /* ENABLE_NETWORK */

167
src/network/network_data.h Normal file
View File

@@ -0,0 +1,167 @@
/* $Id$ */
#ifndef NETWORK_DATA_H
#define NETWORK_DATA_H
// Is the network enabled?
#ifdef ENABLE_NETWORK
#include "../openttd.h"
#include "network.h"
#include "core/os_abstraction.h"
#include "core/config.h"
#include "core/packet.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;
PlayerID 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,
NETWORK_ERROR_ILLEGAL_PACKET,
// Signals from servers
NETWORK_ERROR_NOT_AUTHORIZED,
NETWORK_ERROR_NOT_EXPECTED,
NETWORK_ERROR_WRONG_REVISION,
NETWORK_ERROR_NAME_IN_USE,
NETWORK_ERROR_WRONG_PASSWORD,
NETWORK_ERROR_PLAYER_MISMATCH, // Happens in CLIENT_COMMAND
NETWORK_ERROR_KICKED,
NETWORK_ERROR_CHEATER,
NETWORK_ERROR_FULL,
} NetworkErrorCode;
// Actions that can be used for NetworkTextMessage
typedef enum {
NETWORK_ACTION_JOIN,
NETWORK_ACTION_LEAVE,
NETWORK_ACTION_SERVER_MESSAGE,
NETWORK_ACTION_CHAT,
NETWORK_ACTION_CHAT_COMPANY,
NETWORK_ACTION_CHAT_CLIENT,
NETWORK_ACTION_GIVE_MONEY,
NETWORK_ACTION_NAME_CHANGE,
} NetworkAction;
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;
CommandPacket *_local_command_queue;
SOCKET _udp_client_socket; // udp client socket
SOCKET _udp_server_socket; // udp server socket
SOCKET _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];
#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_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_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);
// from network.c
void NetworkCloseClient(NetworkClientState *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);
byte NetworkGetCurrentLanguageIndex(void);
NetworkClientInfo *NetworkFindClientInfoFromIndex(uint16 client_index);
NetworkClientInfo *NetworkFindClientInfoFromIP(const char *ip);
NetworkClientState *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 */

View File

@@ -0,0 +1,74 @@
/* $Id$ */
#ifdef ENABLE_NETWORK
#include "../stdafx.h"
#include "../debug.h"
#include "network_data.h"
#include "../newgrf_config.h"
// This file handles the GameList
// Also, it handles the request to a server for data about the server
/** Add a new item to the linked gamelist. If the IP and Port match
* return the existing item instead of adding it again
* @param ip the IP-address (inet_addr) of the to-be added item
* @param port the port the server is running on
* @return a point to the newly added or already existing item */
NetworkGameList *NetworkGameListAddItem(uint32 ip, uint16 port)
{
NetworkGameList *item, *prev_item;
prev_item = NULL;
for (item = _network_game_list; item != NULL; item = item->next) {
if (item->ip == ip && item->port == port) return item;
prev_item = item;
}
item = malloc(sizeof(*item));
memset(item, 0, sizeof(*item));
item->next = NULL;
item->ip = ip;
item->port = port;
if (prev_item == NULL) {
_network_game_list = item;
} else {
prev_item->next = item;
}
DEBUG(net, 4, "[gamelist] added server to list");
UpdateNetworkGameWindow(false);
return item;
}
/** Remove an item from the gamelist linked list
* @param remove pointer to the item to be removed */
void NetworkGameListRemoveItem(NetworkGameList *remove)
{
NetworkGameList *item, *prev_item;
prev_item = NULL;
for (item = _network_game_list; item != NULL; item = item->next) {
if (remove == item) {
if (prev_item == NULL) {
_network_game_list = remove->next;
} else {
prev_item->next = remove->next;
}
/* Remove GRFConfig information */
ClearGRFConfigList(&remove->info.grfconfig);
free(remove);
remove = NULL;
DEBUG(net, 4, "[gamelist] removed server from list");
UpdateNetworkGameWindow(false);
return;
}
prev_item = item;
}
}
#endif /* ENABLE_NETWORK */

View File

@@ -0,0 +1,11 @@
/* $Id$ */
#ifndef NETWORK_GAMELIST_H
#define NETWORK_GAMELIST_H
void NetworkGameListClear(void);
NetworkGameList *NetworkGameListAddItem(uint32 ip, uint16 port);
void NetworkGameListRemoveItem(NetworkGameList *remove);
void NetworkGameListAddQueriedItem(const NetworkGameInfo *info, bool server_online);
#endif /* NETWORK_GAMELIST_H */

1706
src/network/network_gui.c Normal file

File diff suppressed because it is too large Load Diff

26
src/network/network_gui.h Normal file
View File

@@ -0,0 +1,26 @@
/* $Id$ */
#ifndef NETWORK_GUI_H
#define NETWORK_GUI_H
#ifdef ENABLE_NETWORK
#include "network_data.h"
void ShowNetworkNeedPassword(NetworkPasswordType npt);
void ShowNetworkGiveMoneyWindow(byte player); // PlayerID
void ShowNetworkChatQueryWindow(DestType type, byte dest);
void ShowJoinStatusWindow(void);
void ShowNetworkGameWindow(void);
void ShowClientList(void);
#else /* ENABLE_NETWORK */
/* Network function stubs when networking is disabled */
static inline void ShowNetworkChatQueryWindow(byte desttype, byte dest) {}
static inline void ShowClientList(void) {}
static inline void ShowNetworkGameWindow(void) {}
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_GUI_H */

1528
src/network/network_server.c Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,39 @@
/* $Id$ */
#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(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);
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);
void NetworkServer_Tick(bool send_frame);
void NetworkServerMonthlyLoop(void);
void NetworkServerYearlyLoop(void);
static inline const char* GetPlayerIP(const NetworkClientInfo* ci)
{
struct in_addr addr;
addr.s_addr = ci->client_ip;
return inet_ntoa(addr);
}
#else /* ENABLE_NETWORK */
/* Network function stubs when networking is disabled */
static inline void NetworkServerMonthlyLoop(void) {}
static inline void NetworkServerYearlyLoop(void) {}
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_SERVER_H */

663
src/network/network_udp.c Normal file
View File

@@ -0,0 +1,663 @@
/* $Id$ */
#ifdef ENABLE_NETWORK
#include "../stdafx.h"
#include "../debug.h"
#include "../string.h"
#include "network_data.h"
#include "../date.h"
#include "../map.h"
#include "network_gamelist.h"
#include "network_udp.h"
#include "../variables.h"
#include "../newgrf_config.h"
#include "core/udp.h"
/**
* @file network_udp.c This file handles the UDP related communication.
*
* This is the GameServer <-> MasterServer and GameServer <-> GameClient
* communication before the game is being joined.
*/
enum {
ADVERTISE_NORMAL_INTERVAL = 30000, // interval between advertising in ticks (15 minutes)
ADVERTISE_RETRY_INTERVAL = 300, // readvertise when no response after this many ticks (9 seconds)
ADVERTISE_RETRY_TIMES = 3 // give up readvertising after this much failed retries
};
#define DEF_UDP_RECEIVE_COMMAND(type) void NetworkPacketReceive_ ## type ## _command(Packet *p, struct sockaddr_in *client_addr)
static NetworkClientState _udp_cs;
DEF_UDP_RECEIVE_COMMAND(PACKET_UDP_CLIENT_FIND_SERVER)
{
Packet *packet;
// Just a fail-safe.. should never happen
if (!_network_udp_server)
return;
packet = NetworkSend_Init(PACKET_UDP_SERVER_RESPONSE);
// Update some game_info
_network_game_info.game_date = _date;
_network_game_info.map_width = MapSizeX();
_network_game_info.map_height = MapSizeY();
_network_game_info.map_set = _opt.landscape;
_network_game_info.companies_on = ActivePlayerCount();
_network_game_info.spectators_on = NetworkSpectatorCount();
_network_game_info.grfconfig = _grfconfig;
NetworkSend_NetworkGameInfo(p, &_network_game_info);
// Let the client know that we are here
NetworkSendUDP_Packet(_udp_server_socket, packet, client_addr);
free(packet);
DEBUG(net, 2, "[udp] queried from '%s'", inet_ntoa(client_addr->sin_addr));
}
void HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config)
{
/* Find the matching GRF file */
const GRFConfig *f = FindGRFConfig(config->grfid, config->md5sum);
if (f == NULL) {
/* Don't know the GRF, so mark game incompatible and the (possibly)
* already resolved name for this GRF (another server has sent the
* name of the GRF already */
config->name = FindUnknownGRFName(config->grfid, config->md5sum, true);
SETBIT(config->flags, GCF_NOT_FOUND);
} else {
config->filename = f->filename;
config->name = f->name;
config->info = f->info;
}
SETBIT(config->flags, GCF_COPY);
}
DEF_UDP_RECEIVE_COMMAND(PACKET_UDP_SERVER_RESPONSE)
{
extern const char _openttd_revision[];
NetworkGameList *item;
// Just a fail-safe.. should never happen
if (_network_udp_server || _udp_cs.has_quit) return;
DEBUG(net, 4, "[udp] server response from %s:%d", inet_ntoa(client_addr->sin_addr),ntohs(client_addr->sin_port));
// Find next item
item = NetworkGameListAddItem(inet_addr(inet_ntoa(client_addr->sin_addr)), ntohs(client_addr->sin_port));
NetworkRecv_NetworkGameInfo(&_udp_cs, p, &item->info);
item->info.compatible = true;
{
/* Checks whether there needs to be a request for names of GRFs and makes
* the request if necessary. GRFs that need to be requested are the GRFs
* that do not exist on the clients system and we do not have the name
* resolved of, i.e. the name is still UNKNOWN_GRF_NAME_PLACEHOLDER.
* The in_request array and in_request_count are used so there is no need
* to do a second loop over the GRF list, which can be relatively expensive
* due to the string comparisons. */
const GRFConfig *in_request[NETWORK_MAX_GRF_COUNT];
const GRFConfig *c;
uint in_request_count = 0;
struct sockaddr_in out_addr;
for (c = item->info.grfconfig; c != NULL; c = c->next) {
if (HASBIT(c->flags, GCF_NOT_FOUND)) item->info.compatible = false;
if (!HASBIT(c->flags, GCF_NOT_FOUND) || strcmp(c->name, UNKNOWN_GRF_NAME_PLACEHOLDER) != 0) continue;
in_request[in_request_count] = c;
in_request_count++;
}
if (in_request_count > 0) {
/* There are 'unknown' GRFs, now send a request for them */
uint i;
Packet *packet = NetworkSend_Init(PACKET_UDP_CLIENT_GET_NEWGRFS);
NetworkSend_uint8 (packet, in_request_count);
for (i = 0; i < in_request_count; i++) {
NetworkSend_GRFIdentifier(packet, in_request[i]);
}
out_addr.sin_family = AF_INET;
out_addr.sin_port = htons(item->port);
out_addr.sin_addr.s_addr = item->ip;
NetworkSendUDP_Packet(_udp_client_socket, packet, &out_addr);
free(packet);
}
}
if (item->info.server_lang >= NETWORK_NUM_LANGUAGES) item->info.server_lang = 0;
if (item->info.map_set >= NUM_LANDSCAPE ) item->info.map_set = 0;
if (item->info.hostname[0] == '\0')
snprintf(item->info.hostname, sizeof(item->info.hostname), "%s", inet_ntoa(client_addr->sin_addr));
/* Check if we are allowed on this server based on the revision-match */
item->info.version_compatible =
strcmp(item->info.server_revision, _openttd_revision) == 0 ||
strcmp(item->info.server_revision, NOREV_STRING) == 0;
item->info.compatible &= item->info.version_compatible; // Already contains match for GRFs
item->online = true;
UpdateNetworkGameWindow(false);
}
DEF_UDP_RECEIVE_COMMAND(PACKET_UDP_CLIENT_DETAIL_INFO)
{
NetworkClientState *cs;
NetworkClientInfo *ci;
Packet *packet;
Player *player;
byte current = 0;
int i;
// Just a fail-safe.. should never happen
if (!_network_udp_server) return;
packet = NetworkSend_Init(PACKET_UDP_SERVER_DETAIL_INFO);
/* Send the amount of active companies */
NetworkSend_uint8 (packet, NETWORK_COMPANY_INFO_VERSION);
NetworkSend_uint8 (packet, ActivePlayerCount());
/* Fetch the latest version of everything */
NetworkPopulateCompanyInfo();
/* Go through all the players */
FOR_ALL_PLAYERS(player) {
/* Skip non-active players */
if (!player->is_active) continue;
current++;
/* Send the information */
NetworkSend_uint8(packet, current);
NetworkSend_string(packet, _network_player_info[player->index].company_name);
NetworkSend_uint32(packet, _network_player_info[player->index].inaugurated_year);
NetworkSend_uint64(packet, _network_player_info[player->index].company_value);
NetworkSend_uint64(packet, _network_player_info[player->index].money);
NetworkSend_uint64(packet, _network_player_info[player->index].income);
NetworkSend_uint16(packet, _network_player_info[player->index].performance);
/* Send 1 if there is a passord for the company else send 0 */
if (_network_player_info[player->index].password[0] != '\0') {
NetworkSend_uint8(packet, 1);
} else {
NetworkSend_uint8(packet, 0);
}
for (i = 0; i < NETWORK_VEHICLE_TYPES; i++)
NetworkSend_uint16(packet, _network_player_info[player->index].num_vehicle[i]);
for (i = 0; i < NETWORK_STATION_TYPES; i++)
NetworkSend_uint16(packet, _network_player_info[player->index].num_station[i]);
/* Find the clients that are connected to this player */
FOR_ALL_CLIENTS(cs) {
ci = DEREF_CLIENT_INFO(cs);
if (ci->client_playas == player->index) {
/* The uint8 == 1 indicates that a client is following */
NetworkSend_uint8(packet, 1);
NetworkSend_string(packet, ci->client_name);
NetworkSend_string(packet, ci->unique_id);
NetworkSend_uint32(packet, ci->join_date);
}
}
/* Also check for the server itself */
ci = NetworkFindClientInfoFromIndex(NETWORK_SERVER_INDEX);
if (ci->client_playas == player->index) {
/* The uint8 == 1 indicates that a client is following */
NetworkSend_uint8(packet, 1);
NetworkSend_string(packet, ci->client_name);
NetworkSend_string(packet, ci->unique_id);
NetworkSend_uint32(packet, ci->join_date);
}
/* Indicates end of client list */
NetworkSend_uint8(packet, 0);
}
/* And check if we have any spectators */
FOR_ALL_CLIENTS(cs) {
ci = DEREF_CLIENT_INFO(cs);
if (!IsValidPlayer(ci->client_playas)) {
/* The uint8 == 1 indicates that a client is following */
NetworkSend_uint8(packet, 1);
NetworkSend_string(packet, ci->client_name);
NetworkSend_string(packet, ci->unique_id);
NetworkSend_uint32(packet, ci->join_date);
}
}
/* Also check for the server itself */
ci = NetworkFindClientInfoFromIndex(NETWORK_SERVER_INDEX);
if (!IsValidPlayer(ci->client_playas)) {
/* The uint8 == 1 indicates that a client is following */
NetworkSend_uint8(packet, 1);
NetworkSend_string(packet, ci->client_name);
NetworkSend_string(packet, ci->unique_id);
NetworkSend_uint32(packet, ci->join_date);
}
/* Indicates end of client list */
NetworkSend_uint8(packet, 0);
NetworkSendUDP_Packet(_udp_server_socket, packet, client_addr);
free(packet);
}
DEF_UDP_RECEIVE_COMMAND(PACKET_UDP_MASTER_RESPONSE_LIST)
{
int i;
struct in_addr ip;
uint16 port;
uint8 ver;
/* 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(&_udp_cs, p);
if (_udp_cs.has_quit) return;
if (ver == 1) {
for (i = NetworkRecv_uint16(&_udp_cs, p); i != 0 ; i--) {
ip.s_addr = TO_LE32(NetworkRecv_uint32(&_udp_cs, p));
port = NetworkRecv_uint16(&_udp_cs, p);
NetworkUDPQueryServer(inet_ntoa(ip), port);
}
}
}
DEF_UDP_RECEIVE_COMMAND(PACKET_UDP_MASTER_ACK_REGISTER)
{
_network_advertise_retries = 0;
DEBUG(net, 2, "[udp] advertising on master server successfull");
/* We are advertised, but we don't want to! */
if (!_network_advertise) NetworkUDPRemoveAdvertise();
}
/**
* A client has requested the names of some NewGRFs.
*
* Replying this can be tricky as we have a limit of SEND_MTU bytes
* in the reply packet and we can send up to 100 bytes per NewGRF
* (GRF ID, MD5sum and NETWORK_GRF_NAME_LENGTH bytes for the name).
* As SEND_MTU is _much_ less than 100 * NETWORK_MAX_GRF_COUNT, it
* could be that a packet overflows. To stop this we only reply
* with the first N NewGRFs so that if the first N + 1 NewGRFs
* would be sent, the packet overflows.
* in_reply and in_reply_count are used to keep a list of GRFs to
* send in the reply.
*/
DEF_UDP_RECEIVE_COMMAND(PACKET_UDP_CLIENT_GET_NEWGRFS)
{
uint8 num_grfs;
uint i;
const GRFConfig *in_reply[NETWORK_MAX_GRF_COUNT];
Packet *packet;
uint8 in_reply_count = 0;
uint packet_len = 0;
/* Just a fail-safe.. should never happen */
if (_udp_cs.has_quit) return;
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 (&_udp_cs, p);
if (num_grfs > NETWORK_MAX_GRF_COUNT) return;
for (i = 0; i < num_grfs; i++) {
GRFConfig c;
const GRFConfig *f;
NetworkRecv_GRFIdentifier(&_udp_cs, p, &c);
/* Find the matching GRF file */
f = FindGRFConfig(c.grfid, c.md5sum);
if (f == NULL) 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.
* The name could be an empty string, if so take the filename. */
packet_len += sizeof(c.grfid) + sizeof(c.md5sum) +
min(strlen((f->name != NULL && strlen(f->name) > 0) ? f->name : f->filename) + 1, NETWORK_GRF_NAME_LENGTH);
if (packet_len > SEND_MTU - 4) { // 4 is 3 byte header + grf count in reply
break;
}
in_reply[in_reply_count] = f;
in_reply_count++;
}
if (in_reply_count == 0) return;
packet = NetworkSend_Init(PACKET_UDP_SERVER_NEWGRFS);
NetworkSend_uint8 (packet, in_reply_count);
for (i = 0; i < in_reply_count; i++) {
char name[NETWORK_GRF_NAME_LENGTH];
/* The name could be an empty string, if so take the filename */
ttd_strlcpy(name, (in_reply[i]->name != NULL && strlen(in_reply[i]->name) > 0) ?
in_reply[i]->name : in_reply[i]->filename, sizeof(name));
NetworkSend_GRFIdentifier(packet, in_reply[i]);
NetworkSend_string(packet, name);
}
NetworkSendUDP_Packet(_udp_server_socket, packet, client_addr);
free(packet);
}
/** The return of the client's request of the names of some NewGRFs */
DEF_UDP_RECEIVE_COMMAND(PACKET_UDP_SERVER_NEWGRFS)
{
uint8 num_grfs;
uint i;
/* Just a fail-safe.. should never happen */
if (_udp_cs.has_quit) return;
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 (&_udp_cs, 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;
NetworkRecv_GRFIdentifier(&_udp_cs, p, &c);
NetworkRecv_string(&_udp_cs, 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.
* If it exists and not resolved yet, then name of the fake GRF is
* overwritten with the name from the reply. */
unknown_name = FindUnknownGRFName(c.grfid, c.md5sum, false);
if (unknown_name != NULL && strcmp(unknown_name, UNKNOWN_GRF_NAME_PLACEHOLDER) == 0) {
ttd_strlcpy(unknown_name, name, NETWORK_GRF_NAME_LENGTH);
}
}
}
// The layout for the receive-functions by UDP
typedef void NetworkUDPPacket(Packet *p, struct sockaddr_in *client_addr);
static NetworkUDPPacket* const _network_udp_packet[] = {
RECEIVE_COMMAND(PACKET_UDP_CLIENT_FIND_SERVER),
RECEIVE_COMMAND(PACKET_UDP_SERVER_RESPONSE),
RECEIVE_COMMAND(PACKET_UDP_CLIENT_DETAIL_INFO),
NULL,
NULL,
RECEIVE_COMMAND(PACKET_UDP_MASTER_ACK_REGISTER),
NULL,
RECEIVE_COMMAND(PACKET_UDP_MASTER_RESPONSE_LIST),
NULL,
RECEIVE_COMMAND(PACKET_UDP_CLIENT_GET_NEWGRFS),
RECEIVE_COMMAND(PACKET_UDP_SERVER_NEWGRFS),
};
// If this fails, check the array above with network_data.h
assert_compile(lengthof(_network_udp_packet) == PACKET_UDP_END);
void NetworkHandleUDPPacket(Packet *p, struct sockaddr_in *client_addr)
{
byte type;
/* Fake a client, so we can see when there is an illegal packet */
_udp_cs.socket = INVALID_SOCKET;
_udp_cs.has_quit = false;
type = NetworkRecv_uint8(&_udp_cs, p);
if (type < PACKET_UDP_END && _network_udp_packet[type] != NULL && !_udp_cs.has_quit) {
_network_udp_packet[type](p, client_addr);
} else {
if (!_udp_cs.has_quit) {
DEBUG(net, 0, "[udp] received invalid packet type %d", type);
} else {
DEBUG(net, 0, "[udp] received illegal packet");
}
}
}
// Close UDP connection
void NetworkUDPClose(void)
{
DEBUG(net, 1, "[udp] closed listeners");
if (_network_udp_server) {
if (_udp_server_socket != INVALID_SOCKET) {
closesocket(_udp_server_socket);
_udp_server_socket = INVALID_SOCKET;
}
if (_udp_master_socket != INVALID_SOCKET) {
closesocket(_udp_master_socket);
_udp_master_socket = INVALID_SOCKET;
}
_network_udp_server = false;
_network_udp_broadcast = 0;
} else {
if (_udp_client_socket != INVALID_SOCKET) {
closesocket(_udp_client_socket);
_udp_client_socket = INVALID_SOCKET;
}
_network_udp_broadcast = 0;
}
}
// Broadcast to all ips
static void NetworkUDPBroadCast(SOCKET udp)
{
Packet* p = NetworkSend_Init(PACKET_UDP_CLIENT_FIND_SERVER);
uint i;
for (i = 0; _broadcast_list[i] != 0; i++) {
struct sockaddr_in out_addr;
out_addr.sin_family = AF_INET;
out_addr.sin_port = htons(_network_server_port);
out_addr.sin_addr.s_addr = _broadcast_list[i];
DEBUG(net, 4, "[udp] broadcasting to %s", inet_ntoa(out_addr.sin_addr));
NetworkSendUDP_Packet(udp, p, &out_addr);
}
free(p);
}
// Request the the server-list from the master server
void NetworkUDPQueryMasterServer(void)
{
struct sockaddr_in out_addr;
Packet *p;
if (_udp_client_socket == INVALID_SOCKET)
if (!NetworkUDPListen(&_udp_client_socket, 0, 0, true))
return;
p = NetworkSend_Init(PACKET_UDP_CLIENT_GET_LIST);
out_addr.sin_family = AF_INET;
out_addr.sin_port = htons(NETWORK_MASTER_SERVER_PORT);
out_addr.sin_addr.s_addr = NetworkResolveHost(NETWORK_MASTER_SERVER_HOST);
// packet only contains protocol version
NetworkSend_uint8(p, NETWORK_MASTER_SERVER_VERSION);
NetworkSendUDP_Packet(_udp_client_socket, p, &out_addr);
DEBUG(net, 2, "[udp] master server queried at %s:%d", inet_ntoa(out_addr.sin_addr),ntohs(out_addr.sin_port));
free(p);
}
// Find all servers
void NetworkUDPSearchGame(void)
{
// We are still searching..
if (_network_udp_broadcast > 0) return;
// No UDP-socket yet..
if (_udp_client_socket == INVALID_SOCKET)
if (!NetworkUDPListen(&_udp_client_socket, 0, 0, true))
return;
DEBUG(net, 0, "[udp] searching server");
NetworkUDPBroadCast(_udp_client_socket);
_network_udp_broadcast = 300; // Stay searching for 300 ticks
}
NetworkGameList *NetworkUDPQueryServer(const char* host, unsigned short port)
{
struct sockaddr_in out_addr;
Packet *p;
NetworkGameList *item;
// No UDP-socket yet..
if (_udp_client_socket == INVALID_SOCKET)
if (!NetworkUDPListen(&_udp_client_socket, 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);
// Clear item in gamelist
item = NetworkGameListAddItem(inet_addr(inet_ntoa(out_addr.sin_addr)), ntohs(out_addr.sin_port));
memset(&item->info, 0, sizeof(item->info));
ttd_strlcpy(item->info.server_name, host, lengthof(item->info.server_name));
ttd_strlcpy(item->info.hostname, host, lengthof(item->info.hostname));
item->online = false;
// Init the packet
p = NetworkSend_Init(PACKET_UDP_CLIENT_FIND_SERVER);
NetworkSendUDP_Packet(_udp_client_socket, p, &out_addr);
free(p);
UpdateNetworkGameWindow(false);
return item;
}
/* Remove our advertise from the master-server */
void NetworkUDPRemoveAdvertise(void)
{
struct sockaddr_in out_addr;
Packet *p;
/* Check if we are advertising */
if (!_networking || !_network_server || !_network_udp_server) return;
/* check for socket */
if (_udp_master_socket == INVALID_SOCKET)
if (!NetworkUDPListen(&_udp_master_socket, _network_server_bind_ip, 0, false))
return;
DEBUG(net, 1, "[udp] removing advertise from master server");
/* Find somewhere to send */
out_addr.sin_family = AF_INET;
out_addr.sin_port = htons(NETWORK_MASTER_SERVER_PORT);
out_addr.sin_addr.s_addr = NetworkResolveHost(NETWORK_MASTER_SERVER_HOST);
/* Send the packet */
p = NetworkSend_Init(PACKET_UDP_SERVER_UNREGISTER);
/* Packet is: Version, server_port */
NetworkSend_uint8(p, NETWORK_MASTER_SERVER_VERSION);
NetworkSend_uint16(p, _network_server_port);
NetworkSendUDP_Packet(_udp_master_socket, p, &out_addr);
free(p);
}
/* Register us to the master server
This function checks if it needs to send an advertise */
void NetworkUDPAdvertise(void)
{
struct sockaddr_in out_addr;
Packet *p;
/* Check if we should send an advertise */
if (!_networking || !_network_server || !_network_udp_server || !_network_advertise)
return;
/* check for socket */
if (_udp_master_socket == INVALID_SOCKET)
if (!NetworkUDPListen(&_udp_master_socket, _network_server_bind_ip, 0, false))
return;
if (_network_need_advertise) {
_network_need_advertise = false;
_network_advertise_retries = ADVERTISE_RETRY_TIMES;
} else {
/* Only send once every ADVERTISE_NORMAL_INTERVAL ticks */
if (_network_advertise_retries == 0) {
if ((_network_last_advertise_frame + ADVERTISE_NORMAL_INTERVAL) > _frame_counter)
return;
_network_advertise_retries = ADVERTISE_RETRY_TIMES;
}
if ((_network_last_advertise_frame + ADVERTISE_RETRY_INTERVAL) > _frame_counter)
return;
}
_network_advertise_retries--;
_network_last_advertise_frame = _frame_counter;
/* Find somewhere to send */
out_addr.sin_family = AF_INET;
out_addr.sin_port = htons(NETWORK_MASTER_SERVER_PORT);
out_addr.sin_addr.s_addr = NetworkResolveHost(NETWORK_MASTER_SERVER_HOST);
DEBUG(net, 1, "[udp] advertising to master server");
/* Send the packet */
p = NetworkSend_Init(PACKET_UDP_SERVER_REGISTER);
/* Packet is: WELCOME_MESSAGE, Version, server_port */
NetworkSend_string(p, NETWORK_MASTER_SERVER_WELCOME_MESSAGE);
NetworkSend_uint8(p, NETWORK_MASTER_SERVER_VERSION);
NetworkSend_uint16(p, _network_server_port);
NetworkSendUDP_Packet(_udp_master_socket, p, &out_addr);
free(p);
}
void NetworkUDPInitialize(void)
{
_udp_client_socket = INVALID_SOCKET;
_udp_server_socket = INVALID_SOCKET;
_udp_master_socket = INVALID_SOCKET;
_network_udp_server = false;
_network_udp_broadcast = 0;
}
#endif /* ENABLE_NETWORK */

17
src/network/network_udp.h Normal file
View File

@@ -0,0 +1,17 @@
/* $Id$ */
#ifndef NETWORK_UDP_H
#define NETWORK_UDP_H
#ifdef ENABLE_NETWORK
void NetworkUDPInitialize(void);
void NetworkUDPSearchGame(void);
void NetworkUDPQueryMasterServer(void);
NetworkGameList *NetworkUDPQueryServer(const char* host, unsigned short port);
void NetworkUDPAdvertise(void);
void NetworkUDPRemoveAdvertise(void);
#endif /* ENABLE_NETWORK */
#endif /* NETWORK_UDP_H */