OpenRCT2/src/network/network.cpp

535 lines
15 KiB
C++
Raw Normal View History

2015-02-12 03:01:02 +01:00
/*****************************************************************************
* Copyright (c) 2014 Ted John
* OpenRCT2, an open source clone of Roller Coaster Tycoon 2.
*
* This file is part of OpenRCT2.
*
* OpenRCT2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
#ifndef DISABLE_NETWORK
2015-07-07 16:09:21 +02:00
#include <math.h>
2015-07-09 04:19:12 +02:00
#include <set>
#include "network.h"
2015-07-07 16:09:21 +02:00
extern "C" {
2015-02-12 17:23:49 +01:00
#include "../addresses.h"
2015-02-12 12:30:57 +01:00
#include "../game.h"
2015-02-12 17:23:49 +01:00
#include "../localisation/date.h"
#include "../localisation/localisation.h"
#include "../management/news_item.h"
2015-07-05 17:19:01 +02:00
#include "../scenario.h"
2015-07-07 16:09:21 +02:00
}
2015-02-12 03:01:02 +01:00
#pragma comment(lib, "Ws2_32.lib")
2015-02-12 12:30:57 +01:00
int gNetworkStart = NETWORK_NONE;
char gNetworkStartHost[128];
int gNetworkStartPort = NETWORK_DEFAULT_PORT;
int gNetworkStatus = NETWORK_NONE;
2015-07-05 17:19:01 +02:00
uint32 gNetworkServerTick = 0;
2015-02-12 12:30:57 +01:00
2015-07-09 04:19:12 +02:00
struct GameCommand
{
GameCommand(uint32 args[8]) { tick = args[0], eax = args[1], ebx = args[2], ecx = args[3], edx = args[4], esi = args[5], edi = args[6], ebp = args[7]; };
uint32 tick;
uint32 eax, ebx, ecx, edx, esi, edi, ebp;
bool operator<(const GameCommand& comp) const {
return tick < comp.tick;
}
};
2015-02-12 03:01:02 +01:00
static int _wsaInitialised = 0;
static WSADATA _wsaData;
2015-07-08 03:21:05 +02:00
static SOCKET _listeningSocket = INVALID_SOCKET;
static SOCKET _serverSocket = INVALID_SOCKET;
static SOCKET _clientSocket = INVALID_SOCKET;
2015-07-07 16:09:21 +02:00
static std::vector<uint8> _chunkBuffer;
static NetworkConnection _serverConnection;
2015-07-08 03:21:05 +02:00
static std::list<std::unique_ptr<NetworkConnection>> _clientConnectionList;
2015-07-09 04:19:12 +02:00
static std::multiset<GameCommand> _gameCommandQueue;
2015-02-12 03:01:02 +01:00
2015-07-07 16:09:21 +02:00
static void network_process_packet(NetworkPacket& packet);
2015-02-12 12:30:57 +01:00
2015-07-07 16:09:21 +02:00
NetworkPacket::NetworkPacket()
{
read = 0;
size = 0;
data = std::make_shared<std::vector<uint8>>();
}
2015-07-08 03:21:05 +02:00
std::unique_ptr<NetworkPacket> NetworkPacket::AllocatePacket()
{
return std::move(std::unique_ptr<NetworkPacket>(new NetworkPacket)); // change to make_unique in c++14
2015-07-08 03:21:05 +02:00
}
std::unique_ptr<NetworkPacket> NetworkPacket::DuplicatePacket(NetworkPacket& packet)
{
return std::move(std::unique_ptr<NetworkPacket>(new NetworkPacket(packet))); // change to make_unique in c++14
2015-07-08 03:21:05 +02:00
}
2015-07-07 16:09:21 +02:00
uint8* NetworkPacket::GetData()
{
return &(*data)[0];
}
2015-07-09 04:19:12 +02:00
void NetworkPacket::Clear()
{
read = 0;
data->clear();
}
2015-07-07 16:09:21 +02:00
int NetworkConnection::ReadPacket()
{
if (inboundpacket.read < sizeof(inboundpacket.size)) {
// read packet size
int readBytes = recv(socket, &((char*)&inboundpacket.size)[inboundpacket.read], sizeof(inboundpacket.size) - inboundpacket.read, 0);
if (readBytes == SOCKET_ERROR || readBytes == 0) {
if (WSAGetLastError() != WSAEWOULDBLOCK) {
return NETWORK_DISCONNECTED;
} else {
return NETWORK_NO_DATA;
}
}
inboundpacket.read += readBytes;
if (inboundpacket.read == sizeof(inboundpacket.size)) {
inboundpacket.size = ntohs(inboundpacket.size);
inboundpacket.data->resize(inboundpacket.size);
}
} else {
// read packet data
if (inboundpacket.data->capacity() > 0) {
int readBytes = recv(socket, (char*)&inboundpacket.GetData()[inboundpacket.read - sizeof(inboundpacket.size)], sizeof(inboundpacket.size) + inboundpacket.size - inboundpacket.read, 0);
if (readBytes == SOCKET_ERROR || readBytes == 0) {
if (WSAGetLastError() != WSAEWOULDBLOCK) {
return NETWORK_DISCONNECTED;
} else {
return NETWORK_NO_DATA;
}
}
inboundpacket.read += readBytes;
}
if (inboundpacket.read == sizeof(inboundpacket.size) + inboundpacket.size) {
return NETWORK_SUCCESS;
}
}
return NETWORK_MORE_DATA;
}
int NetworkConnection::SendPacket(NetworkPacket& packet)
{
if (gNetworkStatus == NETWORK_NONE) {
return 0;
}
while (1) {
if (packet.read < sizeof(packet.size)) {
// send packet size
uint16 size = htons(packet.size);
int sentBytes = send(socket, &((char*)&size)[packet.read], sizeof(size) - packet.read, 0);
if (sentBytes == SOCKET_ERROR) {
return 0;
}
packet.read += sentBytes;
} else {
// send packet data
int sentBytes = send(socket, (const char*)&packet.GetData()[packet.read - sizeof(packet.size)], packet.data->size(), 0);
if (sentBytes == SOCKET_ERROR) {
return 0;
}
packet.read += sentBytes;
if (packet.read == sizeof(packet.size) + packet.data->size()) {
return 1;
}
}
}
return 0;
}
void NetworkConnection::QueuePacket(std::unique_ptr<NetworkPacket> packet)
{
packet->size = packet->data->size();
outboundpackets.push_back(std::move(packet));
}
void NetworkConnection::SendQueuedPackets()
{
while (outboundpackets.size() > 0 && SendPacket(*(outboundpackets.front()).get())) {
outboundpackets.remove(outboundpackets.front());
}
}
2015-02-12 03:01:02 +01:00
int network_init()
{
if (!_wsaInitialised) {
log_verbose("Initialising WSA");
if (WSAStartup(MAKEWORD(2, 2), &_wsaData) != 0) {
log_error("Unable to initialise winsock.");
return 0;
}
_wsaInitialised = 1;
}
return 1;
}
void network_close()
{
2015-02-12 12:30:57 +01:00
if (!_wsaInitialised)
return;
if (gNetworkStatus == NETWORK_CLIENT)
network_end_client();
else if (gNetworkStatus == NETWORK_SERVER)
network_end_server();
2015-02-12 03:01:02 +01:00
log_verbose("Closing WSA");
WSACleanup();
_wsaInitialised = 0;
}
2015-02-12 12:30:57 +01:00
int network_begin_client(const char *host, int port)
{
SOCKADDR_IN serverAddress;
u_long iMode;
if (!network_init())
return 0;
_serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (_serverSocket == INVALID_SOCKET) {
log_error("Unable to create socket.");
return 0;
}
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.S_un.S_addr = inet_addr(host);
serverAddress.sin_port = htons(port);
if (connect(_serverSocket, (SOCKADDR*)&serverAddress, sizeof(SOCKADDR_IN)) != 0) {
log_error("Unable to connect to host.");
return 0;
2015-07-05 17:19:01 +02:00
} else {
printf("Connected to server!\n");
2015-02-12 12:30:57 +01:00
}
iMode = 1;
if (ioctlsocket(_serverSocket, FIONBIO, &iMode) != NO_ERROR) {
closesocket(_serverSocket);
log_error("Failed to set non-blocking mode.");
}
2015-07-07 16:09:21 +02:00
_serverConnection.socket = _serverSocket;
2015-02-12 12:30:57 +01:00
gNetworkStatus = NETWORK_CLIENT;
return 1;
}
void network_end_client()
{
gNetworkStatus = NETWORK_NONE;
closesocket(_serverSocket);
}
2015-02-12 03:01:02 +01:00
int network_begin_server(int port)
{
SOCKADDR_IN localAddress;
2015-02-12 12:30:57 +01:00
u_long iMode;
2015-02-12 03:01:02 +01:00
if (!network_init())
return 0;
log_verbose("Begin listening for clients");
2015-07-08 03:21:05 +02:00
_listeningSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (_listeningSocket == INVALID_SOCKET) {
2015-02-12 03:01:02 +01:00
log_error("Unable to create socket.");
return 0;
}
2015-07-08 03:21:05 +02:00
2015-02-12 03:01:02 +01:00
localAddress.sin_family = AF_INET;
2015-02-12 12:30:57 +01:00
localAddress.sin_addr.S_un.S_addr = INADDR_ANY;
2015-02-12 03:01:02 +01:00
localAddress.sin_port = htons(port);
2015-07-08 03:21:05 +02:00
if (bind(_listeningSocket, (SOCKADDR*)&localAddress, sizeof(SOCKADDR_IN)) != 0) {
closesocket(_listeningSocket);
2015-02-12 03:01:02 +01:00
log_error("Unable to bind to socket.");
return 0;
}
2015-07-08 03:21:05 +02:00
if (listen(_listeningSocket, SOMAXCONN) != 0) {
closesocket(_listeningSocket);
2015-02-12 03:01:02 +01:00
log_error("Unable to listen on socket.");
return 0;
}
2015-02-12 12:30:57 +01:00
iMode = 1;
2015-07-08 03:21:05 +02:00
if (ioctlsocket(_listeningSocket, FIONBIO, &iMode) != NO_ERROR) {
closesocket(_listeningSocket);
2015-02-12 12:30:57 +01:00
log_error("Failed to set non-blocking mode.");
2015-07-08 03:21:05 +02:00
return 0;
2015-02-12 12:30:57 +01:00
}
2015-07-07 16:09:21 +02:00
2015-07-08 03:21:05 +02:00
printf("Ready for clients...\n");
2015-07-07 16:09:21 +02:00
2015-02-12 12:30:57 +01:00
gNetworkStatus = NETWORK_SERVER;
2015-02-12 03:01:02 +01:00
return 1;
}
void network_end_server()
{
2015-02-12 12:30:57 +01:00
gNetworkStatus = NETWORK_NONE;
2015-02-12 03:01:02 +01:00
closesocket(_clientSocket);
}
2015-07-08 03:21:05 +02:00
void network_add_client(SOCKET socket)
2015-02-12 12:30:57 +01:00
{
2015-07-08 03:21:05 +02:00
printf("New client connection\n");
auto networkconnection = std::unique_ptr<NetworkConnection>(new NetworkConnection); // change to make_unique in c++14
2015-07-08 03:21:05 +02:00
networkconnection->socket = socket;
_clientConnectionList.push_back(std::move(networkconnection));
}
2015-02-12 12:30:57 +01:00
2015-07-08 03:21:05 +02:00
void network_remove_client(std::unique_ptr<NetworkConnection>& networkconnection)
{
printf("Client removed\n");
_clientConnectionList.remove(networkconnection);
}
2015-02-12 12:30:57 +01:00
2015-07-08 03:21:05 +02:00
int network_process_connection(NetworkConnection& networkconnection)
{
int packetStatus;
2015-02-12 12:30:57 +01:00
do {
2015-07-07 16:09:21 +02:00
packetStatus = networkconnection.ReadPacket();
2015-07-05 17:19:01 +02:00
switch(packetStatus) {
case NETWORK_DISCONNECTED:
2015-02-12 12:30:57 +01:00
network_print_error();
if (gNetworkStatus == NETWORK_CLIENT) {
network_end_client();
printf("Server disconnected...\n");
2015-07-08 03:21:05 +02:00
return 0;
2015-02-12 12:30:57 +01:00
} else if (gNetworkStatus == NETWORK_SERVER) {
2015-07-07 16:09:21 +02:00
printf("Client disconnected...\n");
2015-07-08 03:21:05 +02:00
return 0;
2015-02-12 12:30:57 +01:00
}
2015-07-05 17:19:01 +02:00
break;
case NETWORK_SUCCESS:
// done reading in packet
2015-07-07 16:09:21 +02:00
network_process_packet(networkconnection.inboundpacket);
2015-07-05 17:19:01 +02:00
break;
case NETWORK_MORE_DATA:
// more data required to be read
break;
case NETWORK_NO_DATA:
break;
}
} while (packetStatus == NETWORK_MORE_DATA || packetStatus == NETWORK_SUCCESS);
2015-07-08 03:21:05 +02:00
networkconnection.SendQueuedPackets();
return 1;
}
2015-07-05 17:19:01 +02:00
2015-07-09 04:19:12 +02:00
void network_process_gamecmdqueue()
{
while (_gameCommandQueue.begin() != _gameCommandQueue.end() && _gameCommandQueue.begin()->tick < RCT2_GLOBAL(RCT2_ADDRESS_CURRENT_TICKS, uint32)) {
_gameCommandQueue.erase(_gameCommandQueue.begin());
}
while (_gameCommandQueue.begin() != _gameCommandQueue.end() && _gameCommandQueue.begin()->tick == RCT2_GLOBAL(RCT2_ADDRESS_CURRENT_TICKS, uint32)) {
const GameCommand& gc = (*_gameCommandQueue.begin());
game_do_command(gc.eax, gc.ebx, gc.ecx, gc.edx, gc.esi, gc.edi, gc.ebp);
_gameCommandQueue.erase(_gameCommandQueue.begin());
}
}
2015-07-08 03:21:05 +02:00
void network_update()
{
static uint32 lastTickUpdate = 0;
u_long iMode;
if (gNetworkStatus == NETWORK_NONE)
return;
if (gNetworkStatus == NETWORK_CLIENT) {
network_process_connection(_serverConnection);
2015-07-09 04:19:12 +02:00
network_process_gamecmdqueue();
2015-07-08 03:21:05 +02:00
} else {
2015-07-09 04:19:12 +02:00
auto it = _clientConnectionList.begin();
while(it != _clientConnectionList.end()) {
2015-07-08 03:21:05 +02:00
if (!network_process_connection(*(*it))) {
network_remove_client((*it));
it = _clientConnectionList.begin();
2015-07-09 04:19:12 +02:00
} else {
it++;
2015-07-08 03:21:05 +02:00
}
}
2015-07-09 04:19:12 +02:00
if (SDL_GetTicks() - lastTickUpdate >= 25) {
2015-07-05 17:19:01 +02:00
lastTickUpdate = SDL_GetTicks();
network_send_tick();
2015-02-12 12:30:57 +01:00
}
2015-07-08 03:21:05 +02:00
SOCKET socket = accept(_listeningSocket, NULL, NULL);
if (socket == INVALID_SOCKET) {
if (WSAGetLastError() != WSAEWOULDBLOCK) {
network_print_error();
closesocket(_listeningSocket);
log_error("Failed to accept client.");
}
} else {
iMode = 1;
if (ioctlsocket(socket, FIONBIO, &iMode) != NO_ERROR) {
closesocket(socket);
log_error("Failed to set non-blocking mode.");
} else {
network_add_client(socket);
}
}
2015-07-05 17:19:01 +02:00
}
2015-02-12 12:30:57 +01:00
}
2015-07-07 16:09:21 +02:00
static void network_process_packet(NetworkPacket& packet)
2015-02-12 12:30:57 +01:00
{
uint32 *args;
int command;
2015-02-12 17:23:49 +01:00
rct_news_item newsItem;
2015-02-12 12:30:57 +01:00
2015-07-07 16:09:21 +02:00
args = (uint32*)packet.GetData();
2015-02-12 12:30:57 +01:00
command = args[0];
2015-02-12 17:23:49 +01:00
switch (command) {
2015-07-05 17:19:01 +02:00
case NETWORK_COMMAND_AUTH:{
}break;
case NETWORK_COMMAND_MAP:{
uint32 size = args[1];
uint32 offset = args[2];
2015-07-07 16:09:21 +02:00
if (offset > 0x600000) {
// too big
} else {
int chunksize = packet.size - 4 - 4 - 4;
if (offset + chunksize > _chunkBuffer.size()) {
_chunkBuffer.resize(offset + chunksize);
2015-07-05 17:19:01 +02:00
}
2015-07-07 16:09:21 +02:00
memcpy(&_chunkBuffer[offset], (void*)&packet.GetData()[4 + 4 + 4], chunksize);
2015-07-05 17:19:01 +02:00
if (offset + chunksize == size) {
2015-07-07 16:09:21 +02:00
printf("Loading new map from network...\n");
SDL_RWops* rw = SDL_RWFromMem(&_chunkBuffer[0], size);
2015-07-05 17:19:01 +02:00
if (game_load_sv6(rw)) {
game_load_init();
}
SDL_RWclose(rw);
}
}
}break;
case NETWORK_COMMAND_CHAT:{
newsItem.type = NEWS_ITEM_BLANK;
newsItem.flags = 1;
newsItem.assoc = 0;
newsItem.ticks = 0;
newsItem.month_year = RCT2_GLOBAL(RCT2_ADDRESS_CURRENT_MONTH_YEAR, uint16);
newsItem.day = ((days_in_month[(newsItem.month_year & 7)] * RCT2_GLOBAL(RCT2_ADDRESS_CURRENT_MONTH_TICKS, uint16)) >> 16) + 1;
newsItem.colour = FORMAT_TOPAZ;
2015-07-07 16:09:21 +02:00
strcpy(newsItem.text, (char*)&packet.GetData()[4]);
2015-07-05 17:19:01 +02:00
news_item_add_to_queue_custom(&newsItem);
}break;
case NETWORK_COMMAND_GAMECMD:{
2015-07-09 04:19:12 +02:00
if (gNetworkStatus == NETWORK_SERVER) {
network_send_gamecmd(args[2], args[3], args[4], args[5], args[6], args[7], args[8]);
game_do_command(args[2], args[3], args[4], args[5], args[6], args[7], args[8]);
} else {
GameCommand gc = GameCommand(&args[1]);
_gameCommandQueue.insert(gc);
}
2015-07-05 17:19:01 +02:00
}break;
case NETWORK_COMMAND_TICK:{
gNetworkServerTick = args[1];
}break;
2015-02-12 17:23:49 +01:00
}
2015-07-09 04:19:12 +02:00
packet.Clear();
2015-07-05 17:19:01 +02:00
}
void network_send_tick()
{
2015-07-08 03:21:05 +02:00
std::unique_ptr<NetworkPacket> packet = NetworkPacket::AllocatePacket();
2015-07-07 16:09:21 +02:00
packet->Write((uint32)NETWORK_COMMAND_TICK);
packet->Write((uint32)RCT2_GLOBAL(RCT2_ADDRESS_CURRENT_TICKS, uint32));
2015-07-08 03:21:05 +02:00
for(auto it = _clientConnectionList.begin(); it != _clientConnectionList.end(); it++) {
(*it)->QueuePacket(NetworkPacket::DuplicatePacket(*packet));
}
2015-07-05 17:19:01 +02:00
}
void network_send_map()
{
2015-07-08 03:21:05 +02:00
if (gNetworkStatus == NETWORK_SERVER) {
int buffersize = 0x600000;
std::vector<uint8> buffer(buffersize);
SDL_RWops* rw = SDL_RWFromMem(&buffer[0], buffersize);
scenario_save(rw, 0);
int size = (int)SDL_RWtell(rw);
int chunksize = 1000;
for (int i = 0; i < size; i += chunksize) {
int datasize = min(chunksize, size - i);
std::unique_ptr<NetworkPacket> packet = NetworkPacket::AllocatePacket();
packet->Write((uint32)NETWORK_COMMAND_MAP);
packet->Write((uint32)size);
packet->Write((uint32)i);
packet->Write(&buffer[i], datasize);
for(auto it = _clientConnectionList.begin(); it != _clientConnectionList.end(); it++) {
(*it)->QueuePacket(NetworkPacket::DuplicatePacket(*packet));
}
}
SDL_RWclose(rw);
2015-07-05 17:19:01 +02:00
}
2015-07-07 16:09:21 +02:00
}
2015-07-07 22:52:41 +02:00
void network_send_chat(const char* text)
{
2015-07-08 03:21:05 +02:00
std::unique_ptr<NetworkPacket> packet = NetworkPacket::AllocatePacket();
2015-07-07 22:52:41 +02:00
packet->Write((uint32)NETWORK_COMMAND_CHAT);
packet->Write((uint8*)text, strlen(text) + 1);
2015-07-08 03:21:05 +02:00
if (gNetworkStatus == NETWORK_SERVER) {
for(auto it = _clientConnectionList.begin(); it != _clientConnectionList.end(); it++) {
(*it)->QueuePacket(NetworkPacket::DuplicatePacket(*packet));
}
} else {
_serverConnection.QueuePacket(std::move(packet));
}
2015-07-07 22:52:41 +02:00
}
2015-07-09 04:19:12 +02:00
void network_send_gamecmd(uint32 eax, uint32 ebx, uint32 ecx, uint32 edx, uint32 esi, uint32 edi, uint32 ebp)
2015-07-07 16:09:21 +02:00
{
2015-07-08 03:21:05 +02:00
std::unique_ptr<NetworkPacket> packet = NetworkPacket::AllocatePacket();
2015-07-07 16:09:21 +02:00
packet->Write((uint32)NETWORK_COMMAND_GAMECMD);
2015-07-09 04:19:12 +02:00
packet->Write((uint32)RCT2_GLOBAL(RCT2_ADDRESS_CURRENT_TICKS, uint32));
2015-07-07 16:09:21 +02:00
packet->Write((uint32)eax);
2015-07-09 04:19:12 +02:00
packet->Write((uint32)ebx | (1 << 31));
2015-07-07 16:09:21 +02:00
packet->Write((uint32)ecx);
packet->Write((uint32)edx);
packet->Write((uint32)esi);
packet->Write((uint32)edi);
packet->Write((uint32)ebp);
2015-07-08 03:21:05 +02:00
if (gNetworkStatus == NETWORK_SERVER) {
for(auto it = _clientConnectionList.begin(); it != _clientConnectionList.end(); it++) {
(*it)->QueuePacket(NetworkPacket::DuplicatePacket(*packet));
}
} else {
_serverConnection.QueuePacket(std::move(packet));
}
2015-02-12 03:01:02 +01:00
}
2015-02-12 12:30:57 +01:00
void network_print_error()
2015-02-12 03:01:02 +01:00
{
2015-02-12 12:30:57 +01:00
wchar_t *s = NULL;
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, WSAGetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&s, 0, NULL);
fprintf(stderr, "%S\n", s);
LocalFree(s);
2015-02-12 03:01:02 +01:00
}
#endif /* DISABLE_NETWORK */