Update to 12.0-beta1

This commit is contained in:
dP
2021-08-15 14:57:29 +03:00
parent ac7d3eba75
commit 9df4f2c4fc
666 changed files with 61302 additions and 20466 deletions

View File

@@ -27,6 +27,7 @@
#include "network.h"
#include "network_base.h"
#include "network_client.h"
#include "network_gamelist.h"
#include "../core/backup_type.hpp"
#include "../thread.h"
@@ -36,7 +37,6 @@
/* This file handles all the client-commands */
/** Read some packets, and when do use that data as initial load filter. */
struct PacketReader : LoadFilter {
static const size_t CHUNK = 32 * 1024; ///< 32 KiB chunks of memory.
@@ -60,35 +60,38 @@ struct PacketReader : LoadFilter {
}
}
/**
* Simple wrapper around fwrite to be able to pass it to Packet's TransferOut.
* @param destination The reader to add the data to.
* @param source The buffer to read data from.
* @param amount The number of bytes to copy.
* @return The number of bytes that were copied.
*/
static inline ssize_t TransferOutMemCopy(PacketReader *destination, const char *source, size_t amount)
{
memcpy(destination->buf, source, amount);
destination->buf += amount;
destination->written_bytes += amount;
return amount;
}
/**
* Add a packet to this buffer.
* @param p The packet to add.
*/
void AddPacket(const Packet *p)
void AddPacket(Packet *p)
{
assert(this->read_bytes == 0);
size_t in_packet = p->size - p->pos;
size_t to_write = std::min<size_t>(this->bufe - this->buf, in_packet);
const byte *pbuf = p->buffer + p->pos;
this->written_bytes += in_packet;
if (to_write != 0) {
memcpy(this->buf, pbuf, to_write);
this->buf += to_write;
}
p->TransferOutWithLimit(TransferOutMemCopy, this->bufe - this->buf, this);
/* Did everything fit in the current chunk, then we're done. */
if (to_write == in_packet) return;
if (p->RemainingBytesToTransfer() == 0) return;
/* Allocate a new chunk and add the remaining data. */
pbuf += to_write;
to_write = in_packet - to_write;
this->blocks.push_back(this->buf = CallocT<byte>(CHUNK));
this->bufe = this->buf + CHUNK;
memcpy(this->buf, pbuf, to_write);
this->buf += to_write;
p->TransferOutWithLimit(TransferOutMemCopy, this->bufe - this->buf, this);
}
size_t Read(byte *rbuf, size_t size) override
@@ -129,12 +132,8 @@ struct PacketReader : LoadFilter {
*/
void ClientNetworkEmergencySave()
{
if (!_settings_client.gui.autosave_on_network_disconnect) return;
if (!_networking) return;
const char *filename = "netsave.sav";
DEBUG(net, 0, "Client: Performing emergency save (%s)", filename);
SaveOrLoad(filename, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR, false);
static FiosNumberedSaveName _netsave_ctr("netsave");
DoAutoOrNetsave(_netsave_ctr);
}
@@ -142,7 +141,7 @@ void ClientNetworkEmergencySave()
* Create a new socket for the client side of the game connection.
* @param s The socket to connect with.
*/
ClientNetworkGameSocketHandler::ClientNetworkGameSocketHandler(SOCKET s) : NetworkGameSocketHandler(s), savegame(nullptr), status(STATUS_INACTIVE)
ClientNetworkGameSocketHandler::ClientNetworkGameSocketHandler(SOCKET s, const std::string &connection_string) : NetworkGameSocketHandler(s), connection_string(connection_string), savegame(nullptr), status(STATUS_INACTIVE)
{
assert(ClientNetworkGameSocketHandler::my_client == nullptr);
ClientNetworkGameSocketHandler::my_client = this;
@@ -155,31 +154,26 @@ ClientNetworkGameSocketHandler::~ClientNetworkGameSocketHandler()
ClientNetworkGameSocketHandler::my_client = nullptr;
delete this->savegame;
delete this->GetInfo();
}
NetworkRecvStatus ClientNetworkGameSocketHandler::CloseConnection(NetworkRecvStatus status)
{
assert(status != NETWORK_RECV_STATUS_OKAY);
/*
* Sending a message just before leaving the game calls cs->SendPackets.
* This might invoke this function, which means that when we close the
* connection after cs->SendPackets we will close an already closed
* connection. This handles that case gracefully without having to make
* that code any more complex or more aware of the validity of the socket.
*/
if (this->sock == INVALID_SOCKET) return status;
assert(this->sock != INVALID_SOCKET);
DEBUG(net, 1, "Closed client connection %d", this->client_id);
if (!this->HasClientQuit()) {
Debug(net, 3, "Closed client connection {}", this->client_id);
this->SendPackets(true);
this->SendPackets(true);
/* Wait a number of ticks so our leave message can reach the server.
* This is especially needed for Windows servers as they seem to get
* the "socket is closed" message before receiving our leave message,
* which would trigger the server to close the connection as well. */
CSleep(3 * MILLISECONDS_PER_TICK);
/* Wait a number of ticks so our leave message can reach the server.
* This is especially needed for Windows servers as they seem to get
* the "socket is closed" message before receiving our leave message,
* which would trigger the server to close the connection as well. */
CSleep(3 * MILLISECONDS_PER_TICK);
}
delete this->GetInfo();
delete this;
return status;
@@ -191,17 +185,17 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::CloseConnection(NetworkRecvSta
*/
void ClientNetworkGameSocketHandler::ClientError(NetworkRecvStatus res)
{
/* First, send a CLIENT_ERROR to the server, so he knows we are
* disconnection (and why!) */
/* First, send a CLIENT_ERROR to the server, so it knows we are
* disconnected (and why!) */
NetworkErrorCode errorno;
/* We just want to close the connection.. */
if (res == NETWORK_RECV_STATUS_CLOSE_QUERY) {
this->NetworkSocketHandler::CloseConnection();
this->NetworkSocketHandler::MarkClosed();
this->CloseConnection(res);
_networking = false;
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
return;
}
@@ -257,7 +251,7 @@ void ClientNetworkGameSocketHandler::ClientError(NetworkRecvStatus res)
/* static */ void ClientNetworkGameSocketHandler::Send()
{
my_client->SendPackets();
my_client->CheckConnection();
if (my_client != nullptr) my_client->CheckConnection();
}
/**
@@ -282,15 +276,15 @@ void ClientNetworkGameSocketHandler::ClientError(NetworkRecvStatus res)
if (_sync_seed_1 != _random.state[0]) {
#endif
ShowNetworkError(STR_NETWORK_ERROR_DESYNC);
DEBUG(desync, 1, "sync_err: %08x; %02x", _date, _date_fract);
DEBUG(net, 0, "Sync error detected!");
Debug(desync, 1, "sync_err: {:08x}; {:02x}", _date, _date_fract);
Debug(net, 0, "Sync error detected");
my_client->ClientError(NETWORK_RECV_STATUS_DESYNC);
return false;
}
/* If this is the first time we have a sync-frame, we
* need to let the server know that we are ready and at the same
* frame as he is.. so we can start playing! */
* frame as it is.. so we can start playing! */
if (_network_first_time) {
_network_first_time = false;
SendAck();
@@ -298,7 +292,7 @@ void ClientNetworkGameSocketHandler::ClientError(NetworkRecvStatus res)
_sync_frame = 0;
} else if (_sync_frame < _frame_counter) {
DEBUG(net, 1, "Missed frame for sync-test (%d / %d)", _sync_frame, _frame_counter);
Debug(net, 1, "Missed frame for sync-test: {} / {}", _sync_frame, _frame_counter);
_sync_frame = 0;
}
}
@@ -316,20 +310,15 @@ static uint32 last_ack_frame;
/** One bit of 'entropy' used to generate a salt for the company passwords. */
static uint32 _password_game_seed;
/** The other bit of 'entropy' used to generate a salt for the company passwords. */
static char _password_server_id[NETWORK_SERVER_ID_LENGTH];
static std::string _password_server_id;
/** Maximum number of companies of the currently joined server. */
static uint8 _network_server_max_companies;
/** Maximum number of spectators of the currently joined server. */
static uint8 _network_server_max_spectators;
/** The current name of the server you are on. */
std::string _network_server_name;
/** Who would we like to join as. */
CompanyID _network_join_as;
/** Login password from -p argument */
const char *_network_join_server_password = nullptr;
/** Company password from -P argument */
const char *_network_join_company_password = nullptr;
/** Information about the game to join to. */
NetworkJoinInfo _network_join;
/** Make sure the server ID length is the same as a md5 hash. */
static_assert(NETWORK_SERVER_ID_LENGTH == 16 * 2 + 1);
@@ -339,15 +328,14 @@ static_assert(NETWORK_SERVER_ID_LENGTH == 16 * 2 + 1);
* DEF_CLIENT_SEND_COMMAND has no parameters
************/
/** Query the server for company information. */
NetworkRecvStatus ClientNetworkGameSocketHandler::SendCompanyInformationQuery()
/**
* Query the server for server information.
*/
NetworkRecvStatus ClientNetworkGameSocketHandler::SendInformationQuery()
{
my_client->status = STATUS_COMPANY_INFO;
_network_join_status = NETWORK_JOIN_STATUS_GETTING_COMPANY_INFO;
SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
my_client->status = STATUS_GAME_INFO;
my_client->SendPacket(new Packet(PACKET_CLIENT_GAME_INFO));
Packet *p = new Packet(PACKET_CLIENT_COMPANY_INFO);
my_client->SendPacket(p);
return NETWORK_RECV_STATUS_OKAY;
}
@@ -362,8 +350,8 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendJoin()
p->Send_string(GetNetworkRevisionString());
p->Send_uint32(_openttd_newgrf_version);
p->Send_string(_settings_client.network.client_name); // Client name
p->Send_uint8 (_network_join_as); // PlayAs
p->Send_uint8 (NETLANG_ANY); // Language
p->Send_uint8 (_network_join.company); // PlayAs
p->Send_uint8 (0); // Used to be language
my_client->SendPacket(p);
return NETWORK_RECV_STATUS_OKAY;
}
@@ -380,7 +368,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendNewGRFsOk()
* Set the game password as requested.
* @param password The game password.
*/
NetworkRecvStatus ClientNetworkGameSocketHandler::SendGamePassword(const char *password)
NetworkRecvStatus ClientNetworkGameSocketHandler::SendGamePassword(const std::string &password)
{
Packet *p = new Packet(PACKET_CLIENT_GAME_PASSWORD);
p->Send_string(password);
@@ -392,7 +380,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendGamePassword(const char *p
* Set the company password as requested.
* @param password The company password.
*/
NetworkRecvStatus ClientNetworkGameSocketHandler::SendCompanyPassword(const char *password)
NetworkRecvStatus ClientNetworkGameSocketHandler::SendCompanyPassword(const std::string &password)
{
Packet *p = new Packet(PACKET_CLIENT_COMPANY_PASSWORD);
p->Send_string(GenerateCompanyPasswordHash(password, _password_server_id, _password_game_seed));
@@ -445,7 +433,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendCommand(const CommandPacke
}
/** Send a chat-packet over the network */
NetworkRecvStatus ClientNetworkGameSocketHandler::SendChat(NetworkAction action, DestType type, int dest, const char *msg, int64 data)
NetworkRecvStatus ClientNetworkGameSocketHandler::SendChat(NetworkAction action, DestType type, int dest, const std::string &msg, int64 data)
{
Packet *p = new Packet(PACKET_CLIENT_CHAT);
@@ -473,7 +461,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendError(NetworkErrorCode err
* Tell the server that we like to change the password of the company.
* @param password The new password.
*/
NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetPassword(const char *password)
NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetPassword(const std::string &password)
{
Packet *p = new Packet(PACKET_CLIENT_SET_PASSWORD);
@@ -486,7 +474,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetPassword(const char *pa
* Tell the server that we like to change the name of the client.
* @param name The new name.
*/
NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetName(const char *name)
NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetName(const std::string &name)
{
Packet *p = new Packet(PACKET_CLIENT_SET_NAME);
@@ -511,7 +499,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendQuit()
* @param pass The password for the remote command.
* @param command The actual command.
*/
NetworkRecvStatus ClientNetworkGameSocketHandler::SendRCon(const char *pass, const char *command)
NetworkRecvStatus ClientNetworkGameSocketHandler::SendRCon(const std::string &pass, const std::string &command)
{
Packet *p = new Packet(PACKET_CLIENT_RCON);
p->Send_string(pass);
@@ -525,7 +513,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendRCon(const char *pass, con
* @param company The company to move to.
* @param password The password of the company to move to.
*/
NetworkRecvStatus ClientNetworkGameSocketHandler::SendMove(CompanyID company, const char *password)
NetworkRecvStatus ClientNetworkGameSocketHandler::SendMove(CompanyID company, const std::string &password)
{
Packet *p = new Packet(PACKET_CLIENT_MOVE);
p->Send_uint8(company);
@@ -555,7 +543,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_FULL(Packet *p)
{
/* We try to join a server which is full */
ShowErrorMessage(STR_NETWORK_ERROR_SERVER_FULL, INVALID_STRING_ID, WL_CRITICAL);
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
return NETWORK_RECV_STATUS_SERVER_FULL;
}
@@ -564,48 +552,27 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_BANNED(Packet *
{
/* We try to join a server where we are banned */
ShowErrorMessage(STR_NETWORK_ERROR_SERVER_BANNED, INVALID_STRING_ID, WL_CRITICAL);
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
return NETWORK_RECV_STATUS_SERVER_BANNED;
}
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_COMPANY_INFO(Packet *p)
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_GAME_INFO(Packet *p)
{
if (this->status != STATUS_COMPANY_INFO) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
if (this->status != STATUS_GAME_INFO) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
byte company_info_version = p->Recv_uint8();
NetworkGameList *item = NetworkGameListAddItem(this->connection_string);
if (!this->HasClientQuit() && company_info_version == NETWORK_COMPANY_INFO_VERSION) {
/* We have received all data... (there are no more packets coming) */
if (!p->Recv_bool()) return NETWORK_RECV_STATUS_CLOSE_QUERY;
/* Clear any existing GRFConfig chain. */
ClearGRFConfigList(&item->info.grfconfig);
/* Retrieve the NetworkGameInfo from the packet. */
DeserializeNetworkGameInfo(p, &item->info);
/* Check for compatability with the client. */
CheckGameCompatibility(item->info);
/* Ensure we consider the server online. */
item->online = true;
CompanyID current = (Owner)p->Recv_uint8();
if (current >= MAX_COMPANIES) return NETWORK_RECV_STATUS_CLOSE_QUERY;
NetworkCompanyInfo *company_info = GetLobbyCompanyInfo(current);
if (company_info == nullptr) return NETWORK_RECV_STATUS_CLOSE_QUERY;
p->Recv_string(company_info->company_name, sizeof(company_info->company_name));
company_info->inaugurated_year = p->Recv_uint32();
company_info->company_value = p->Recv_uint64();
company_info->money = p->Recv_uint64();
company_info->income = p->Recv_uint64();
company_info->performance = p->Recv_uint16();
company_info->use_password = p->Recv_bool();
for (uint i = 0; i < NETWORK_VEH_END; i++) {
company_info->num_vehicle[i] = p->Recv_uint16();
}
for (uint i = 0; i < NETWORK_VEH_END; i++) {
company_info->num_station[i] = p->Recv_uint16();
}
company_info->ai = p->Recv_bool();
p->Recv_string(company_info->clients, sizeof(company_info->clients));
SetWindowDirty(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_LOBBY);
return NETWORK_RECV_STATUS_OKAY;
}
UpdateNetworkGameWindow();
return NETWORK_RECV_STATUS_CLOSE_QUERY;
}
@@ -618,16 +585,19 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CLIENT_INFO(Pac
NetworkClientInfo *ci;
ClientID client_id = (ClientID)p->Recv_uint32();
CompanyID playas = (CompanyID)p->Recv_uint8();
char name[NETWORK_NAME_LENGTH];
p->Recv_string(name, sizeof(name));
std::string name = p->Recv_string(NETWORK_NAME_LENGTH);
if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CONN_LOST;
if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT;
/* The server validates the name when receiving it from clients, so when it is wrong
* here something went really wrong. In the best case the packet got malformed on its
* way too us, in the worst case the server is broken or compromised. */
if (!NetworkIsValidClientName(name)) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
ci = NetworkClientInfo::GetByClientID(client_id);
if (ci != nullptr) {
if (playas == ci->client_playas && strcmp(name, ci->client_name) != 0) {
if (playas == ci->client_playas && name.compare(ci->client_name) != 0) {
/* Client name changed, display the change */
NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, name);
} else if (playas != ci->client_playas) {
@@ -640,9 +610,9 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CLIENT_INFO(Pac
if (client_id == _network_own_client_id) SetLocalCompany(!Company::IsValidID(playas) ? COMPANY_SPECTATOR : playas);
ci->client_playas = playas;
strecpy(ci->client_name, name, lastof(ci->client_name));
ci->client_name = name;
SetWindowDirty(WC_CLIENT_LIST, 0);
InvalidateWindowData(WC_CLIENT_LIST, 0);
return NETWORK_RECV_STATUS_OKAY;
}
@@ -659,9 +629,9 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CLIENT_INFO(Pac
ci->client_playas = playas;
if (client_id == _network_own_client_id) this->SetInfo(ci);
strecpy(ci->client_name, name, lastof(ci->client_name));
ci->client_name = name;
SetWindowDirty(WC_CLIENT_LIST, 0);
InvalidateWindowData(WC_CLIENT_LIST, 0);
return NETWORK_RECV_STATUS_OKAY;
}
@@ -669,37 +639,46 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CLIENT_INFO(Pac
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR(Packet *p)
{
static const StringID network_error_strings[] = {
STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_GENERAL
STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_DESYNC
STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_SAVEGAME_FAILED
STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_CONNECTION_LOST
STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_ILLEGAL_PACKET
STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_NEWGRF_MISMATCH
STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_NOT_AUTHORIZED
STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_NOT_EXPECTED
STR_NETWORK_ERROR_WRONG_REVISION, // NETWORK_ERROR_WRONG_REVISION
STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_NAME_IN_USE
STR_NETWORK_ERROR_WRONG_PASSWORD, // NETWORK_ERROR_WRONG_PASSWORD
STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_COMPANY_MISMATCH
STR_NETWORK_ERROR_KICKED, // NETWORK_ERROR_KICKED
STR_NETWORK_ERROR_CHEATER, // NETWORK_ERROR_CHEATER
STR_NETWORK_ERROR_SERVER_FULL, // NETWORK_ERROR_FULL
STR_NETWORK_ERROR_TOO_MANY_COMMANDS, // NETWORK_ERROR_TOO_MANY_COMMANDS
STR_NETWORK_ERROR_TIMEOUT_PASSWORD, // NETWORK_ERROR_TIMEOUT_PASSWORD
STR_NETWORK_ERROR_TIMEOUT_COMPUTER, // NETWORK_ERROR_TIMEOUT_COMPUTER
STR_NETWORK_ERROR_TIMEOUT_MAP, // NETWORK_ERROR_TIMEOUT_MAP
STR_NETWORK_ERROR_TIMEOUT_JOIN, // NETWORK_ERROR_TIMEOUT_JOIN
STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_GENERAL
STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_DESYNC
STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_SAVEGAME_FAILED
STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_CONNECTION_LOST
STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_ILLEGAL_PACKET
STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_NEWGRF_MISMATCH
STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_NOT_AUTHORIZED
STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_NOT_EXPECTED
STR_NETWORK_ERROR_WRONG_REVISION, // NETWORK_ERROR_WRONG_REVISION
STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_NAME_IN_USE
STR_NETWORK_ERROR_WRONG_PASSWORD, // NETWORK_ERROR_WRONG_PASSWORD
STR_NETWORK_ERROR_SERVER_ERROR, // NETWORK_ERROR_COMPANY_MISMATCH
STR_NETWORK_ERROR_KICKED, // NETWORK_ERROR_KICKED
STR_NETWORK_ERROR_CHEATER, // NETWORK_ERROR_CHEATER
STR_NETWORK_ERROR_SERVER_FULL, // NETWORK_ERROR_FULL
STR_NETWORK_ERROR_TOO_MANY_COMMANDS, // NETWORK_ERROR_TOO_MANY_COMMANDS
STR_NETWORK_ERROR_TIMEOUT_PASSWORD, // NETWORK_ERROR_TIMEOUT_PASSWORD
STR_NETWORK_ERROR_TIMEOUT_COMPUTER, // NETWORK_ERROR_TIMEOUT_COMPUTER
STR_NETWORK_ERROR_TIMEOUT_MAP, // NETWORK_ERROR_TIMEOUT_MAP
STR_NETWORK_ERROR_TIMEOUT_JOIN, // NETWORK_ERROR_TIMEOUT_JOIN
STR_NETWORK_ERROR_INVALID_CLIENT_NAME, // NETWORK_ERROR_INVALID_CLIENT_NAME
};
static_assert(lengthof(network_error_strings) == NETWORK_ERROR_END);
NetworkErrorCode error = (NetworkErrorCode)p->Recv_uint8();
/* If we query a server that is 1.11.1 or older, we get an
* NETWORK_ERROR_NOT_EXPECTED on requesting the game info. Show a special
* error popup in that case.
*/
if (error == NETWORK_ERROR_NOT_EXPECTED && this->status == STATUS_GAME_INFO) {
ShowErrorMessage(STR_NETWORK_ERROR_SERVER_TOO_OLD, INVALID_STRING_ID, WL_CRITICAL);
return NETWORK_RECV_STATUS_CLOSE_QUERY;
}
StringID err = STR_NETWORK_ERROR_LOSTCONNECTION;
if (error < (ptrdiff_t)lengthof(network_error_strings)) err = network_error_strings[error];
/* In case of kicking a client, we assume there is a kick message in the packet if we can read one byte */
if (error == NETWORK_ERROR_KICKED && p->CanReadFromPacket(1)) {
char kick_msg[255];
p->Recv_string(kick_msg, sizeof(kick_msg));
std::string kick_msg = p->Recv_string(NETWORK_CHAT_LENGTH);
SetDParamStr(0, kick_msg);
ShowErrorMessage(err, STR_NETWORK_ERROR_KICK_MESSAGE, WL_CRITICAL);
} else {
@@ -709,7 +688,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR(Packet *p
/* Perform an emergency save if we had already entered the game */
if (this->status == STATUS_ACTIVE) ClientNetworkEmergencySave();
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
return NETWORK_RECV_STATUS_SERVER_ERROR;
}
@@ -732,7 +711,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHECK_NEWGRFS(P
/* We do not know this GRF, bail out of initialization */
char buf[sizeof(c.md5sum) * 2 + 1];
md5sumToString(buf, lastof(buf), c.md5sum);
DEBUG(grf, 0, "NewGRF %08X not found; checksum %s", BSWAP32(c.grfid), buf);
Debug(grf, 0, "NewGRF {:08X} not found; checksum {}", BSWAP32(c.grfid), buf);
ret = NETWORK_RECV_STATUS_NEWGRF_MISMATCH;
}
}
@@ -752,9 +731,8 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_NEED_GAME_PASSW
if (this->status < STATUS_JOIN || this->status >= STATUS_AUTH_GAME) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
this->status = STATUS_AUTH_GAME;
const char *password = _network_join_server_password;
if (!StrEmpty(password)) {
return SendGamePassword(password);
if (!_network_join.server_password.empty()) {
return SendGamePassword(_network_join.server_password);
}
ShowNetworkNeedPassword(NETWORK_GAME_PASSWORD);
@@ -768,12 +746,11 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_NEED_COMPANY_PA
this->status = STATUS_AUTH_COMPANY;
_password_game_seed = p->Recv_uint32();
p->Recv_string(_password_server_id, sizeof(_password_server_id));
_password_server_id = p->Recv_string(NETWORK_SERVER_ID_LENGTH);
if (this->HasClientQuit()) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
const char *password = _network_join_company_password;
if (!StrEmpty(password)) {
return SendCompanyPassword(password);
if (!_network_join.company_password.empty()) {
return SendCompanyPassword(_network_join.company_password);
}
ShowNetworkNeedPassword(NETWORK_COMPANY_PASSWORD);
@@ -790,7 +767,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_WELCOME(Packet
/* Initialize the password hash salting variables, even if they were previously. */
_password_game_seed = p->Recv_uint32();
p->Recv_string(_password_server_id, sizeof(_password_server_id));
_password_server_id = p->Recv_string(NETWORK_SERVER_ID_LENGTH);
/* Start receiving the map */
return SendGetMap();
@@ -881,7 +858,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DONE(Packet
this->last_packet = std::chrono::steady_clock::now();
if (!load_success) {
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
ShowErrorMessage(STR_NETWORK_ERROR_SAVEGAMEERROR, INVALID_STRING_ID, WL_CRITICAL);
return NETWORK_RECV_STATUS_SAVEGAME;
}
@@ -891,21 +868,23 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DONE(Packet
/* Say we received the map and loaded it correctly! */
SendMapOk();
ShowClientList();
/* New company/spectator (invalid company) or company we want to join is not active
* Switch local company to spectator and await the server's judgement */
if (_network_join_as == COMPANY_NEW_COMPANY || !Company::IsValidID(_network_join_as)) {
if (_network_join.company == COMPANY_NEW_COMPANY || !Company::IsValidID(_network_join.company)) {
SetLocalCompany(COMPANY_SPECTATOR);
if (_network_join_as != COMPANY_SPECTATOR) {
if (_network_join.company != COMPANY_SPECTATOR) {
/* We have arrived and ready to start playing; send a command to make a new company;
* the server will give us a client-id and let us in */
_network_join_status = NETWORK_JOIN_STATUS_REGISTERING;
ShowJoinStatusWindow();
NetworkSendCommand(0, CCA_NEW, 0, CMD_COMPANY_CTRL, nullptr, nullptr, _local_company);
NetworkSendCommand(0, CCA_NEW, 0, CMD_COMPANY_CTRL, nullptr, {}, _local_company);
}
} else {
/* take control over an existing company */
SetLocalCompany(_network_join_as);
SetLocalCompany(_network_join.company);
}
return NETWORK_RECV_STATUS_OKAY;
@@ -929,15 +908,15 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_FRAME(Packet *p
}
#endif
/* Receive the token. */
if (p->pos != p->size) this->token = p->Recv_uint8();
if (p->CanReadFromPacket(sizeof(uint8))) this->token = p->Recv_uint8();
DEBUG(net, 5, "Received FRAME %d", _frame_counter_server);
Debug(net, 7, "Received FRAME {}", _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);
Debug(net, 7, "Sent ACK at {}", _frame_counter);
SendAck();
}
@@ -967,7 +946,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_COMMAND(Packet
cp.my_cmd = p->Recv_bool();
if (err != nullptr) {
IConsolePrintF(CC_ERROR, "WARNING: %s from server, dropping...", err);
IConsolePrint(CC_WARNING, "Dropping server connection due to {}.", err);
return NETWORK_RECV_STATUS_MALFORMED_PACKET;
}
@@ -980,13 +959,13 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHAT(Packet *p)
{
if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
char name[NETWORK_NAME_LENGTH], msg[NETWORK_CHAT_LENGTH];
std::string name;
const NetworkClientInfo *ci = nullptr, *ci_to;
NetworkAction action = (NetworkAction)p->Recv_uint8();
ClientID client_id = (ClientID)p->Recv_uint32();
bool self_send = p->Recv_bool();
p->Recv_string(msg, NETWORK_CHAT_LENGTH);
std::string msg = p->Recv_string(NETWORK_CHAT_LENGTH);
int64 data = p->Recv_uint64();
ci_to = NetworkClientInfo::GetByClientID(client_id);
@@ -997,7 +976,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHAT(Packet *p)
switch (action) {
case NETWORK_ACTION_CHAT_CLIENT:
/* For speaking to client we need the client-name */
seprintf(name, lastof(name), "%s", ci_to->client_name);
name = ci_to->client_name;
ci = NetworkClientInfo::GetByClientID(_network_own_client_id);
break;
@@ -1006,7 +985,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHAT(Packet *p)
StringID str = Company::IsValidID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
SetDParam(0, ci_to->client_playas);
GetString(name, str, lastof(name));
name = GetString(str);
ci = NetworkClientInfo::GetByClientID(_network_own_client_id);
break;
}
@@ -1015,7 +994,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHAT(Packet *p)
}
} else {
/* Display message from somebody else */
seprintf(name, lastof(name), "%s", ci_to->client_name);
name = ci_to->client_name;
ci = ci_to;
}
@@ -1033,11 +1012,11 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR_QUIT(Pack
NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
if (ci != nullptr) {
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, nullptr, GetNetworkErrorMsg((NetworkErrorCode)p->Recv_uint8()));
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, "", GetNetworkErrorMsg((NetworkErrorCode)p->Recv_uint8()));
delete ci;
}
SetWindowDirty(WC_CLIENT_LIST, 0);
InvalidateWindowData(WC_CLIENT_LIST, 0);
return NETWORK_RECV_STATUS_OKAY;
}
@@ -1050,13 +1029,13 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_QUIT(Packet *p)
NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
if (ci != nullptr) {
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, nullptr, STR_NETWORK_MESSAGE_CLIENT_LEAVING);
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, "", STR_NETWORK_MESSAGE_CLIENT_LEAVING);
delete ci;
} else {
DEBUG(net, 0, "Unknown client (%d) is leaving the game", client_id);
Debug(net, 1, "Unknown client ({}) is leaving the game", client_id);
}
SetWindowDirty(WC_CLIENT_LIST, 0);
InvalidateWindowData(WC_CLIENT_LIST, 0);
/* If we come here it means we could not locate the client.. strange :s */
return NETWORK_RECV_STATUS_OKAY;
@@ -1073,7 +1052,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_JOIN(Packet *p)
NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, ci->client_name);
}
SetWindowDirty(WC_CLIENT_LIST, 0);
InvalidateWindowData(WC_CLIENT_LIST, 0);
return NETWORK_RECV_STATUS_OKAY;
}
@@ -1115,8 +1094,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_RCON(Packet *p)
TextColour colour_code = (TextColour)p->Recv_uint16();
if (!IsValidConsoleColour(colour_code)) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
char rcon_out[NETWORK_RCONCOMMAND_LENGTH];
p->Recv_string(rcon_out, sizeof(rcon_out));
std::string rcon_out = p->Recv_string(NETWORK_RCONCOMMAND_LENGTH);
IConsolePrint(colour_code, rcon_out);
@@ -1133,7 +1111,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MOVE(Packet *p)
if (client_id == 0) {
/* definitely an invalid client id, debug message and do nothing. */
DEBUG(net, 0, "[move] received invalid client index = 0");
Debug(net, 1, "Received invalid client index = 0");
return NETWORK_RECV_STATUS_MALFORMED_PACKET;
}
@@ -1156,7 +1134,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CONFIG_UPDATE(P
if (this->status < STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
_network_server_max_companies = p->Recv_uint8();
_network_server_max_spectators = p->Recv_uint8();
_network_server_name = p->Recv_string(NETWORK_NAME_LENGTH);
return NETWORK_RECV_STATUS_OKAY;
}
@@ -1216,7 +1194,7 @@ void NetworkClient_Connected()
* @param password The password.
* @param command The command to execute.
*/
void NetworkClientSendRcon(const char *password, const char *command)
void NetworkClientSendRcon(const std::string &password, const std::string &command)
{
MyClient::SendRCon(password, command);
}
@@ -1227,7 +1205,7 @@ void NetworkClientSendRcon(const char *password, const char *command)
* @param pass the password, is only checked on the server end if a password is needed.
* @return void
*/
void NetworkClientRequestMove(CompanyID company_id, const char *pass)
void NetworkClientRequestMove(CompanyID company_id, const std::string &pass)
{
MyClient::SendMove(company_id, pass);
}
@@ -1252,22 +1230,74 @@ void NetworkClientsToSpectators(CompanyID cid)
}
/**
* Send the server our name.
* Check whether the given client name is deemed valid for use in network games.
* An empty name (null or '') is not valid as that is essentially no name at all.
* A name starting with white space is not valid for tab completion purposes.
* @param client_name The client name to check for validity.
* @return True iff the name is valid.
*/
void NetworkUpdateClientName()
bool NetworkIsValidClientName(const std::string_view client_name)
{
if (client_name.empty()) return false;
if (client_name[0] == ' ') return false;
return true;
}
/**
* Trim the given client name in place, i.e. remove leading and trailing spaces.
* After the trim check whether the client name is valid. A client name is valid
* whenever the name is not empty and does not start with spaces. This check is
* done via \c NetworkIsValidClientName.
* When the client name is valid, this function returns true.
* When the client name is not valid a GUI error message is shown telling the
* user to set the client name and this function returns false.
*
* This function is not suitable for ensuring a valid client name at the server
* as the error message will then be shown to the host instead of the client.
* @param client_name The client name to validate. It will be trimmed of leading
* and trailing spaces.
* @return True iff the client name is valid.
*/
bool NetworkValidateClientName(std::string &client_name)
{
StrTrimInPlace(client_name);
if (NetworkIsValidClientName(client_name)) return true;
ShowErrorMessage(STR_NETWORK_ERROR_BAD_PLAYER_NAME, INVALID_STRING_ID, WL_ERROR);
return false;
}
/**
* Convenience method for NetworkValidateClientName on _settings_client.network.client_name.
* It trims the client name and checks whether it is empty. When it is empty
* an error message is shown to the GUI user.
* See \c NetworkValidateClientName(char*) for details about the functionality.
* @return True iff the client name is valid.
*/
bool NetworkValidateOurClientName()
{
return NetworkValidateClientName(_settings_client.network.client_name);
}
/**
* Send the server our name as callback from the setting.
* @param newname The new client name.
*/
void NetworkUpdateClientName(const std::string &client_name)
{
NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(_network_own_client_id);
if (ci == nullptr) return;
/* Don't change the name if it is the same as the old name */
if (strcmp(ci->client_name, _settings_client.network.client_name) != 0) {
if (client_name.compare(ci->client_name) != 0) {
if (!_network_server) {
MyClient::SendSetName(_settings_client.network.client_name);
MyClient::SendSetName(client_name);
} else {
if (NetworkFindName(_settings_client.network.client_name, lastof(_settings_client.network.client_name))) {
NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, _settings_client.network.client_name);
strecpy(ci->client_name, _settings_client.network.client_name, lastof(ci->client_name));
/* Copy to a temporary buffer so no #n gets added after our name in the settings when there are duplicate names. */
std::string temporary_name = client_name;
if (NetworkMakeClientNameUnique(temporary_name)) {
NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, temporary_name);
ci->client_name = temporary_name;
NetworkUpdateClientInfo(CLIENT_ID_SERVER);
}
}
@@ -1282,7 +1312,7 @@ void NetworkUpdateClientName()
* @param msg The actual message.
* @param data Arbitrary extra data.
*/
void NetworkClientSendChat(NetworkAction action, DestType type, int dest, const char *msg, int64 data)
void NetworkClientSendChat(NetworkAction action, DestType type, int dest, const std::string &msg, int64 data)
{
MyClient::SendChat(action, type, dest, msg, data);
}
@@ -1291,13 +1321,13 @@ void NetworkClientSendChat(NetworkAction action, DestType type, int dest, const
* Set/Reset company password on the client side.
* @param password Password to be set.
*/
void NetworkClientSetCompanyPassword(const char *password)
void NetworkClientSetCompanyPassword(const std::string &password)
{
MyClient::SendSetPassword(password);
}
/**
* Tell whether the client has team members where he/she can chat to.
* Tell whether the client has team members who they can chat to.
* @param cio client to check members of.
* @return true if there is at least one team member.
*/
@@ -1321,12 +1351,3 @@ bool NetworkMaxCompaniesReached()
{
return Company::GetNumItems() >= (_network_server ? _settings_client.network.max_companies : _network_server_max_companies);
}
/**
* Check if max_spectatos has been reached on the server (local check only).
* @return true if the max value has been reached or exceeded, false otherwise.
*/
bool NetworkMaxSpectatorsReached()
{
return NetworkSpectatorCount() >= (_network_server ? _settings_client.network.max_spectators : _network_server_max_spectators);
}