Merge tag '14.0-beta3' into jgrpp

# Conflicts:
#	regression/regression/result.txt
#	src/industrytype.h
#	src/network/core/config.h
#	src/network/core/network_game_info.cpp
#	src/network/core/network_game_info.h
#	src/network/core/packet.cpp
#	src/network/core/packet.h
#	src/network/core/tcp.cpp
#	src/network/core/tcp.h
#	src/network/core/tcp_admin.cpp
#	src/network/core/tcp_content.cpp
#	src/network/core/tcp_coordinator.cpp
#	src/network/core/tcp_game.cpp
#	src/network/core/tcp_game.h
#	src/network/core/tcp_turn.cpp
#	src/network/core/udp.cpp
#	src/network/core/udp.h
#	src/network/network_admin.cpp
#	src/network/network_client.cpp
#	src/network/network_client.h
#	src/network/network_command.cpp
#	src/network/network_content.cpp
#	src/network/network_internal.h
#	src/network/network_query.cpp
#	src/network/network_query.h
#	src/network/network_server.cpp
#	src/network/network_server.h
#	src/network/network_turn.cpp
#	src/network/network_udp.cpp
#	src/rail_gui.cpp
#	src/road_gui.cpp
pull/661/head
Jonathan G Rennison 3 months ago
commit 75dd135e8d

@ -1,4 +1,18 @@
14.0-beta2 (2023-02-04) 14.0-beta3 (2024-02-06)
------------------------------------------------------------------------
Add: [Script] ScriptTileList_StationCoverage to get station coverage area (#12015)
Change: Update OpenTTD TTF fonts to v0.5 (#11994)
Fix #12012: Crash when opening orders of another company (#12013)
Fix #12001: Use correct valid cargo check for old-style NewGRF town house 3rd cargo set up (#12006)
Fix #11997: Adjust economy date by 1920 when loading TTD/TTO savegames (#12007)
Fix: Focus hotkey in road/tram stop building window (#12008)
Fix: Signals were incorrectly shifted by 1 pixel when selected (#12005)
Fix: Missing default vehicles and industry acceptance/production (#12000)
Fix: [Script] Avoid overflow in scripts when infinite money is enabled (#12016)
Fix: [Script] Don't kill GS misusing GSText (#12009)
14.0-beta2 (2024-02-04)
------------------------------------------------------------------------ ------------------------------------------------------------------------
Change: [NewGRF] Improved support for redefining default cargo types (#11719) Change: [NewGRF] Improved support for redefining default cargo types (#11719)
Fix #11982: Crash when trying to place signals on things other than plain rails (#11977) Fix #11982: Crash when trying to place signals on things other than plain rails (#11977)
@ -10,7 +24,7 @@ Fix #11802: Made determining water region edge traversability more robust (#1198
Fix: Second colour vehicle-type default liveries were not being updated (#11971) Fix: Second colour vehicle-type default liveries were not being updated (#11971)
14.0-beta1 (2023-02-03) 14.0-beta1 (2024-02-03)
------------------------------------------------------------------------ ------------------------------------------------------------------------
Feature: Order option to unbunch vehicles at depot (#11945) Feature: Order option to unbunch vehicles at depot (#11945)
Feature: Infinite money mode (#11902) Feature: Infinite money mode (#11902)

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

@ -3,4 +3,4 @@
The OpenTTD TrueType font was created by Zephyris and is maintained on [Github](https://github.com/zephyris/openttd-ttf). The OpenTTD TrueType font was created by Zephyris and is maintained on [Github](https://github.com/zephyris/openttd-ttf).
It is licensed under GPL-2.0. It is licensed under GPL-2.0.
The currently included files correspond to release v0.4. The currently included files correspond to release v0.5.

@ -4,6 +4,7 @@ language = english.lng
[gui] [gui]
autosave = off autosave = off
show_date_in_logs = true
[game_creation] [game_creation]
town_name = english town_name = english

@ -1356,6 +1356,21 @@ function Regression::Station()
} }
} }
function Regression::StationList()
{
print("");
print("--StationList--");
local road_stations = AIStationList(AIStation.STATION_TRUCK_STOP);
for (local st = road_stations.Begin(); !road_stations.IsEnd(); st = road_stations.Next()) {
print(" GetName(): " + AIStation.GetName(st));
print(" TileList_StationCoverage:");
local coverage = AITileList_StationCoverage(st);
for (local i = coverage.Begin(); !coverage.IsEnd(); i = coverage.Next()) {
print(" " + i);
}
}
}
function Regression::Tile() function Regression::Tile()
{ {
print(""); print("");
@ -1987,6 +2002,7 @@ function Regression::Start()
this.Road(); this.Road();
this.Sign(); this.Sign();
this.Station(); this.Station();
this.StationList();
this.Tile(); this.Tile();
this.TileList(); this.TileList();
this.Town(); this.Town();

@ -1,3 +1,4 @@
--TestInit-- --TestInit--
Ops: 9988 Ops: 9988
TickTest: 1 TickTest: 1
@ -7759,6 +7760,153 @@ ERROR: IsEnd() is invalid as Begin() is never called
GetCargoPlannedFromVia(1000, 1000, 0, 1000): -1 GetCargoPlannedFromVia(1000, 1000, 0, 1000): -1
GetCargoPlannedFromVia(1000, 1000, 1000, 1000): -1 GetCargoPlannedFromVia(1000, 1000, 1000, 1000): -1
--StationList--
GetName(): Little Frutford Valley
TileList_StationCoverage:
34192
34191
34190
34189
34188
34187
34186
33936
33935
33934
33933
33932
33931
33930
33680
33679
33678
33677
33676
33675
33674
33424
33423
33422
33421
33420
33419
33418
33168
33167
33166
33165
33164
33163
33162
32912
32911
32910
32909
32908
32907
32906
32656
32655
32654
32653
32652
32651
32650
GetName(): Little Frutford Woods
TileList_StationCoverage:
34439
34438
34437
34436
34435
34434
34433
34432
34187
34186
34185
34184
34183
34182
34181
34180
34179
34178
34177
34176
33931
33930
33929
33928
33927
33926
33925
33924
33923
33922
33921
33920
33675
33674
33673
33672
33671
33670
33669
33668
33667
33666
33665
33664
33419
33418
33417
33416
33415
33414
33413
33412
33411
33410
33409
33408
33163
33162
33161
33160
33159
33158
33157
33156
33155
33154
33153
33152
32907
32906
32905
32904
32903
32902
32901
32900
32899
32898
32897
32896
32651
32650
32649
32648
32647
32646
32645
32644
32643
32642
32641
32640
--Tile-- --Tile--
HasTreeOnTile(): false HasTreeOnTile(): false
IsFarmTile(): true IsFarmTile(): true
@ -9587,9 +9735,9 @@ ERROR: IsEnd() is invalid as Begin() is never called
--Valuate() with excessive CPU usage-- --Valuate() with excessive CPU usage--
Your script made an error: excessive CPU usage in valuator function Your script made an error: excessive CPU usage in valuator function
*FUNCTION [unknown()] regression/main.nut line [2032] *FUNCTION [unknown()] regression/main.nut line [2048]
*FUNCTION [Valuate()] NATIVE line [-1] *FUNCTION [Valuate()] NATIVE line [-1]
*FUNCTION [Start()] regression/main.nut line [2033] *FUNCTION [Start()] regression/main.nut line [2049]
[id] 0 [id] 0
[this] TABLE [this] TABLE
@ -9598,7 +9746,7 @@ Your script made an error: excessive CPU usage in valuator function
[this] INSTANCE [this] INSTANCE
Your script made an error: excessive CPU usage in valuator function Your script made an error: excessive CPU usage in valuator function
*FUNCTION [Start()] regression/main.nut line [2033] *FUNCTION [Start()] regression/main.nut line [2049]
[Infinite] CLOSURE [Infinite] CLOSURE
[list] INSTANCE [list] INSTANCE

@ -1,3 +1,4 @@
--StationList-- --StationList--
Count(): 5 Count(): 5
Location ListDump: Location ListDump:

@ -82,6 +82,13 @@ static const CargoID CARGO_NO_REFIT = 0xFE; ///< Do not refit cargo of a vehicle
static const CargoID INVALID_CARGO = UINT8_MAX; static const CargoID INVALID_CARGO = UINT8_MAX;
/** Mixed cargo types for definitions with cargo that can vary depending on climate. */
enum MixedCargoType {
MCT_LIVESTOCK_FRUIT, ///< Cargo can be livestock or fruit.
MCT_GRAIN_WHEAT_MAIZE, ///< Cargo can be grain, wheat or maize.
MCT_VALUABLES_GOLD_DIAMONDS, ///< Cargo can be valuables, gold or diamonds.
};
/** /**
* Special cargo filter criteria. * Special cargo filter criteria.
* These are used by user interface code only and must not be assigned to any entity. Not all values are valid for every UI filter. * These are used by user interface code only and must not be assigned to any entity. Not all values are valid for every UI filter.

@ -17,6 +17,7 @@
#include "date_type.h" #include "date_type.h"
#include "sound_type.h" #include "sound_type.h"
#include "strings_type.h" #include "strings_type.h"
#include <variant>
typedef uint16_t EngineID; ///< Unique identification number of an engine. typedef uint16_t EngineID; ///< Unique identification number of an engine.
@ -149,7 +150,7 @@ struct EngineInfo {
byte load_amount; byte load_amount;
byte climates; ///< Climates supported by the engine. byte climates; ///< Climates supported by the engine.
CargoID cargo_type; CargoID cargo_type;
CargoLabel cargo_label; std::variant<CargoLabel, MixedCargoType> cargo_label;
CargoTypes refit_mask; CargoTypes refit_mask;
byte refit_cost; byte refit_cost;
byte misc_flags; ///< Miscellaneous flags. @see EngineMiscFlags byte misc_flags; ///< Miscellaneous flags. @see EngineMiscFlags

@ -10,8 +10,6 @@
#ifndef INDUSTRYTYPE_H #ifndef INDUSTRYTYPE_H
#define INDUSTRYTYPE_H #define INDUSTRYTYPE_H
#include <array>
#include <vector>
#include "map_type.h" #include "map_type.h"
#include "slope_type.h" #include "slope_type.h"
#include "industry_type.h" #include "industry_type.h"
@ -19,6 +17,9 @@
#include "cargo_type.h" #include "cargo_type.h"
#include "newgrf_animation_type.h" #include "newgrf_animation_type.h"
#include "newgrf_commons.h" #include "newgrf_commons.h"
#include <array>
#include <vector>
#include <variant>
enum IndustryCleanupType { enum IndustryCleanupType {
CLEAN_RANDOMSOUNDS, ///< Free the dynamically allocated sounds table CLEAN_RANDOMSOUNDS, ///< Free the dynamically allocated sounds table
@ -113,7 +114,7 @@ struct IndustrySpec {
IndustryType conflicting[3]; ///< Industries this industry cannot be close to IndustryType conflicting[3]; ///< Industries this industry cannot be close to
byte check_proc; ///< Index to a procedure to check for conflicting circumstances byte check_proc; ///< Index to a procedure to check for conflicting circumstances
std::array<CargoID, INDUSTRY_NUM_OUTPUTS> produced_cargo{}; std::array<CargoID, INDUSTRY_NUM_OUTPUTS> produced_cargo{};
std::array<CargoLabel, INDUSTRY_NUM_OUTPUTS> produced_cargo_label{}; std::array<std::variant<CargoLabel, MixedCargoType>, INDUSTRY_NUM_OUTPUTS> produced_cargo_label{};
std::array<byte, INDUSTRY_NUM_OUTPUTS> production_rate{}; std::array<byte, INDUSTRY_NUM_OUTPUTS> production_rate{};
/** /**
* minimum amount of cargo transported to the stations. * minimum amount of cargo transported to the stations.
@ -121,7 +122,7 @@ struct IndustrySpec {
*/ */
byte minimal_cargo; byte minimal_cargo;
std::array<CargoID, INDUSTRY_NUM_INPUTS> accepts_cargo{}; ///< 16 accepted cargoes. std::array<CargoID, INDUSTRY_NUM_INPUTS> accepts_cargo{}; ///< 16 accepted cargoes.
std::array<CargoLabel, INDUSTRY_NUM_INPUTS> accepts_cargo_label{}; std::array<std::variant<CargoLabel, MixedCargoType>, INDUSTRY_NUM_INPUTS> accepts_cargo_label{};
uint16_t input_cargo_multiplier[INDUSTRY_NUM_INPUTS][INDUSTRY_NUM_OUTPUTS]; ///< Input cargo multipliers (multiply amount of incoming cargo for the produced cargoes) uint16_t input_cargo_multiplier[INDUSTRY_NUM_INPUTS][INDUSTRY_NUM_OUTPUTS]; ///< Input cargo multipliers (multiply amount of incoming cargo for the produced cargoes)
IndustryLifeType life_type; ///< This is also known as Industry production flag, in newgrf specs IndustryLifeType life_type; ///< This is also known as Industry production flag, in newgrf specs
byte climate_availability; ///< Bitmask, giving landscape enums as bit position byte climate_availability; ///< Bitmask, giving landscape enums as bit position
@ -158,7 +159,7 @@ struct IndustrySpec {
*/ */
struct IndustryTileSpec { struct IndustryTileSpec {
std::array<CargoID, INDUSTRY_NUM_INPUTS> accepts_cargo; ///< Cargo accepted by this tile std::array<CargoID, INDUSTRY_NUM_INPUTS> accepts_cargo; ///< Cargo accepted by this tile
std::array<CargoLabel, INDUSTRY_NUM_INPUTS> accepts_cargo_label; std::array<std::variant<CargoLabel, MixedCargoType>, INDUSTRY_NUM_INPUTS> accepts_cargo_label;
std::array<int8_t, INDUSTRY_NUM_INPUTS> acceptance; ///< Level of acceptance per cargo type (signed, may be negative!) std::array<int8_t, INDUSTRY_NUM_INPUTS> acceptance; ///< Level of acceptance per cargo type (signed, may be negative!)
Slope slopes_refused; ///< slope pattern on which this tile cannot be built Slope slopes_refused; ///< slope pattern on which this tile cannot be built
byte anim_production; ///< Animation frame to start when goods are produced byte anim_production; ///< Animation frame to start when goods are produced

@ -190,6 +190,11 @@ public:
struct NetworkAddressDumper { struct NetworkAddressDumper {
const char *GetAddressAsString(NetworkAddress *addr, bool with_family = true); const char *GetAddressAsString(NetworkAddress *addr, bool with_family = true);
inline const char *GetAddressAsString(NetworkAddress &addr, bool with_family = true)
{
return this->GetAddressAsString(&addr, with_family);
}
private: private:
/* 7 extra are for with_family, which adds " (IPvX)". */ /* 7 extra are for with_family, which adds " (IPvX)". */
char buf[NETWORK_HOSTNAME_PORT_LENGTH + 7]; char buf[NETWORK_HOSTNAME_PORT_LENGTH + 7];

@ -25,8 +25,8 @@ static const uint16_t NETWORK_CONTENT_SERVER_PORT = 3978; ///< The
static const uint16_t NETWORK_DEFAULT_PORT = 3979; ///< The default port of the game server (TCP & UDP) static const uint16_t NETWORK_DEFAULT_PORT = 3979; ///< The default port of the game server (TCP & UDP)
static const uint16_t NETWORK_ADMIN_PORT = 3977; ///< The default port for admin network static const uint16_t NETWORK_ADMIN_PORT = 3977; ///< The default port for admin network
static const uint16_t UDP_MTU = 1460; ///< Number of bytes we can pack in a single UDP packet static const size_t UDP_MTU = 1460; ///< Number of bytes we can pack in a single UDP packet
static const uint16_t UDP_MTU_SHORT = 1400; ///< Number of bytes we can pack in a single UDP packet (conservative) static const size_t UDP_MTU_SHORT = 1400; ///< Number of bytes we can pack in a single UDP packet (conservative)
static const std::string NETWORK_SURVEY_DETAILS_LINK = "https://survey.openttd.org/participate"; ///< Link with more details & privacy statement of the survey. static const std::string NETWORK_SURVEY_DETAILS_LINK = "https://survey.openttd.org/participate"; ///< Link with more details & privacy statement of the survey.
/* /*
@ -43,8 +43,8 @@ static const std::string NETWORK_SURVEY_DETAILS_LINK = "https://survey.openttd.o
* Send_uint16(GB(size, 16, 14) | 0b10 << 14) * Send_uint16(GB(size, 16, 14) | 0b10 << 14)
* Send_uint16(GB(size, 0, 16)) * Send_uint16(GB(size, 0, 16))
*/ */
static const uint16_t TCP_MTU = 32767; ///< Number of bytes we can pack in a single TCP packet static const size_t TCP_MTU = 32767; ///< Number of bytes we can pack in a single TCP packet
static const uint16_t COMPAT_MTU = 1460; ///< Number of bytes we can pack in a single packet for backward compatibility static const size_t COMPAT_MTU = 1460; ///< Number of bytes we can pack in a single packet for backward compatibility
static const byte NETWORK_GAME_ADMIN_VERSION = 3; ///< What version of the admin network do we use? static const byte NETWORK_GAME_ADMIN_VERSION = 3; ///< What version of the admin network do we use?
static const byte NETWORK_GAME_INFO_VERSION = 7; ///< What version of game-info do we use? static const byte NETWORK_GAME_INFO_VERSION = 7; ///< What version of game-info do we use?

@ -148,7 +148,7 @@ void FillStaticNetworkServerGameInfo()
* Get the NetworkServerGameInfo structure with the latest information of the server. * Get the NetworkServerGameInfo structure with the latest information of the server.
* @return The current NetworkServerGameInfo. * @return The current NetworkServerGameInfo.
*/ */
const NetworkServerGameInfo *GetCurrentNetworkServerGameInfo() const NetworkServerGameInfo &GetCurrentNetworkServerGameInfo()
{ {
/* These variables are updated inside _network_game_info as if they are global variables: /* These variables are updated inside _network_game_info as if they are global variables:
* - clients_on * - clients_on
@ -159,7 +159,7 @@ const NetworkServerGameInfo *GetCurrentNetworkServerGameInfo()
_network_game_info.spectators_on = NetworkSpectatorCount(); _network_game_info.spectators_on = NetworkSpectatorCount();
_network_game_info.calendar_date = CalTime::CurDate(); _network_game_info.calendar_date = CalTime::CurDate();
_network_game_info.ticks_playing = _scaled_tick_counter; _network_game_info.ticks_playing = _scaled_tick_counter;
return &_network_game_info; return _network_game_info;
} }
/** /**
@ -191,9 +191,9 @@ static void HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config, std::strin
* @param p the packet to write the data to. * @param p the packet to write the data to.
* @param info the NetworkGameInfo struct to serialize from. * @param info the NetworkGameInfo struct to serialize from.
*/ */
void SerializeNetworkGameInfo(Packet *p, const NetworkServerGameInfo *info, bool send_newgrf_names) void SerializeNetworkGameInfo(Packet &p, const NetworkServerGameInfo &info, bool send_newgrf_names)
{ {
p->Send_uint8 (NETWORK_GAME_INFO_VERSION); p.Send_uint8 (NETWORK_GAME_INFO_VERSION);
/* /*
* Please observe the order. * Please observe the order.
@ -204,15 +204,15 @@ void SerializeNetworkGameInfo(Packet *p, const NetworkServerGameInfo *info, bool
* to the NetworkGameInfo wire-protocol! */ * to the NetworkGameInfo wire-protocol! */
/* NETWORK_GAME_INFO_VERSION = 7 */ /* NETWORK_GAME_INFO_VERSION = 7 */
p->Send_uint64(info->ticks_playing); p.Send_uint64(info.ticks_playing);
/* NETWORK_GAME_INFO_VERSION = 6 */ /* NETWORK_GAME_INFO_VERSION = 6 */
p->Send_uint8(send_newgrf_names ? NST_GRFID_MD5_NAME : NST_GRFID_MD5); p.Send_uint8(send_newgrf_names ? NST_GRFID_MD5_NAME : NST_GRFID_MD5);
/* NETWORK_GAME_INFO_VERSION = 5 */ /* NETWORK_GAME_INFO_VERSION = 5 */
GameInfo *game_info = Game::GetInfo(); GameInfo *game_info = Game::GetInfo();
p->Send_uint32(game_info == nullptr ? -1 : (uint32_t)game_info->GetVersion()); p.Send_uint32(game_info == nullptr ? -1 : (uint32_t)game_info->GetVersion());
p->Send_string(game_info == nullptr ? "" : game_info->GetName()); p.Send_string(game_info == nullptr ? "" : game_info->GetName());
/* NETWORK_GAME_INFO_VERSION = 4 */ /* NETWORK_GAME_INFO_VERSION = 4 */
{ {
@ -224,36 +224,36 @@ void SerializeNetworkGameInfo(Packet *p, const NetworkServerGameInfo *info, bool
uint count = 0; uint count = 0;
/* Count number of GRFs to send information about */ /* Count number of GRFs to send information about */
for (c = info->grfconfig; c != nullptr; c = c->next) { for (c = info.grfconfig; c != nullptr; c = c->next) {
if (!HasBit(c->flags, GCF_STATIC)) count++; if (!HasBit(c->flags, GCF_STATIC)) count++;
} }
p->Send_uint8(ClampTo<uint8_t>(std::min<uint>(count, NETWORK_MAX_GRF_COUNT))); // Send number of GRFs p.Send_uint8(ClampTo<uint8_t>(std::min<uint>(count, NETWORK_MAX_GRF_COUNT))); // Send number of GRFs
/* Send actual GRF Identifications */ /* Send actual GRF Identifications */
for (c = info->grfconfig; c != nullptr; c = c->next) { for (c = info.grfconfig; c != nullptr; c = c->next) {
if (HasBit(c->flags, GCF_STATIC)) continue; if (HasBit(c->flags, GCF_STATIC)) continue;
SerializeGRFIdentifier(p, &c->ident); SerializeGRFIdentifier(p, c->ident);
if (send_newgrf_names) p->Send_string(c->GetName()); if (send_newgrf_names) p.Send_string(c->GetName());
} }
} }
/* NETWORK_GAME_INFO_VERSION = 3 */ /* NETWORK_GAME_INFO_VERSION = 3 */
p->Send_uint32(info->calendar_date.base()); p.Send_uint32(info.calendar_date.base());
p->Send_uint32(info->calendar_start.base()); p.Send_uint32(info.calendar_start.base());
/* NETWORK_GAME_INFO_VERSION = 2 */ /* NETWORK_GAME_INFO_VERSION = 2 */
p->Send_uint8 (info->companies_max); p.Send_uint8 (info.companies_max);
p->Send_uint8 (info->companies_on); p.Send_uint8 (info.companies_on);
p->Send_uint8 (info->clients_max); // Used to be max-spectators p.Send_uint8 (info.clients_max); // Used to be max-spectators
/* NETWORK_GAME_INFO_VERSION = 1 */ /* NETWORK_GAME_INFO_VERSION = 1 */
p->Send_string(info->server_name); p.Send_string(info.server_name);
p->Send_string(info->server_revision); p.Send_string(info.server_revision);
p->Send_bool (info->use_password); p.Send_bool (info.use_password);
p->Send_uint8 (info->clients_max); p.Send_uint8 (info.clients_max);
p->Send_uint8 (info->clients_on); p.Send_uint8 (info.clients_on);
p->Send_uint8 (info->spectators_on); p.Send_uint8 (info.spectators_on);
auto encode_map_size = [&](uint32_t in) -> uint16_t { auto encode_map_size = [&](uint32_t in) -> uint16_t {
if (in < UINT16_MAX) { if (in < UINT16_MAX) {
@ -262,10 +262,10 @@ void SerializeNetworkGameInfo(Packet *p, const NetworkServerGameInfo *info, bool
return 65000 + FindFirstBit(in); return 65000 + FindFirstBit(in);
} }
}; };
p->Send_uint16(encode_map_size(info->map_width)); p.Send_uint16(encode_map_size(info.map_width));
p->Send_uint16(encode_map_size(info->map_height)); p.Send_uint16(encode_map_size(info.map_height));
p->Send_uint8 (info->landscape); p.Send_uint8 (info.landscape);
p->Send_bool (info->dedicated); p.Send_bool (info.dedicated);
} }
/** /**
@ -273,36 +273,36 @@ void SerializeNetworkGameInfo(Packet *p, const NetworkServerGameInfo *info, bool
* @param p the packet to write the data to * @param p the packet to write the data to
* @param info the NetworkGameInfo struct to serialize * @param info the NetworkGameInfo struct to serialize
*/ */
void SerializeNetworkGameInfoExtended(Packet *p, const NetworkServerGameInfo *info, uint16_t flags, uint16_t version, bool send_newgrf_names) void SerializeNetworkGameInfoExtended(Packet &p, const NetworkServerGameInfo &info, uint16_t flags, uint16_t version, bool send_newgrf_names)
{ {
version = std::max<uint16_t>(version, 1); // Version 1 is the max supported version = std::max<uint16_t>(version, 1); // Version 1 is the max supported
p->Send_uint8(version); // version num p.Send_uint8(version); // version num
p->Send_uint32(info->calendar_date.base()); p.Send_uint32(info.calendar_date.base());
p->Send_uint32(info->calendar_start.base()); p.Send_uint32(info.calendar_start.base());
p->Send_uint8 (info->companies_max); p.Send_uint8 (info.companies_max);
p->Send_uint8 (info->companies_on); p.Send_uint8 (info.companies_on);
p->Send_uint8 (info->clients_max); // Used to be max-spectators p.Send_uint8 (info.clients_max); // Used to be max-spectators
p->Send_string(info->server_name); p.Send_string(info.server_name);
p->Send_string(info->server_revision); p.Send_string(info.server_revision);
p->Send_uint8 (0); // Used to be server-lang. p.Send_uint8 (0); // Used to be server-lang.
p->Send_bool (info->use_password); p.Send_bool (info.use_password);
p->Send_uint8 (info->clients_max); p.Send_uint8 (info.clients_max);
p->Send_uint8 (info->clients_on); p.Send_uint8 (info.clients_on);
p->Send_uint8 (info->spectators_on); p.Send_uint8 (info.spectators_on);
p->Send_string(""); // Used to be map-name. p.Send_string(""); // Used to be map-name.
p->Send_uint32(info->map_width); p.Send_uint32(info.map_width);
p->Send_uint32(info->map_height); p.Send_uint32(info.map_height);
p->Send_uint8 (info->landscape); p.Send_uint8 (info.landscape);
p->Send_bool (info->dedicated); p.Send_bool (info.dedicated);
if (version >= 1) { if (version >= 1) {
GameInfo *game_info = Game::GetInfo(); GameInfo *game_info = Game::GetInfo();
p->Send_uint32(game_info == nullptr ? -1 : (uint32_t)game_info->GetVersion()); p.Send_uint32(game_info == nullptr ? -1 : (uint32_t)game_info->GetVersion());
p->Send_string(game_info == nullptr ? "" : game_info->GetName()); p.Send_string(game_info == nullptr ? "" : game_info->GetName());
p->Send_uint8(send_newgrf_names ? NST_GRFID_MD5_NAME : NST_GRFID_MD5); p.Send_uint8(send_newgrf_names ? NST_GRFID_MD5_NAME : NST_GRFID_MD5);
} }
{ {
@ -314,17 +314,17 @@ void SerializeNetworkGameInfoExtended(Packet *p, const NetworkServerGameInfo *in
uint count = 0; uint count = 0;
/* Count number of GRFs to send information about */ /* Count number of GRFs to send information about */
for (c = info->grfconfig; c != nullptr; c = c->next) { for (c = info.grfconfig; c != nullptr; c = c->next) {
if (!HasBit(c->flags, GCF_STATIC)) count++; if (!HasBit(c->flags, GCF_STATIC)) count++;
} }
p->Send_uint32(count); // Send number of GRFs p.Send_uint32(count); // Send number of GRFs
/* Send actual GRF Identifications */ /* Send actual GRF Identifications */
for (c = info->grfconfig; c != nullptr; c = c->next) { for (c = info.grfconfig; c != nullptr; c = c->next) {
if (HasBit(c->flags, GCF_STATIC)) continue; if (HasBit(c->flags, GCF_STATIC)) continue;
SerializeGRFIdentifier(p, &c->ident); SerializeGRFIdentifier(p, c->ident);
if (send_newgrf_names && version >= 1) p->Send_string(c->GetName()); if (send_newgrf_names && version >= 1) p.Send_string(c->GetName());
} }
} }
} }
@ -334,11 +334,11 @@ void SerializeNetworkGameInfoExtended(Packet *p, const NetworkServerGameInfo *in
* @param p the packet to read the data from. * @param p the packet to read the data from.
* @param info the NetworkGameInfo to deserialize into. * @param info the NetworkGameInfo to deserialize into.
*/ */
void DeserializeNetworkGameInfo(Packet *p, NetworkGameInfo *info, const GameInfoNewGRFLookupTable *newgrf_lookup_table) void DeserializeNetworkGameInfo(Packet &p, NetworkGameInfo &info, const GameInfoNewGRFLookupTable *newgrf_lookup_table)
{ {
static const CalTime::Date MAX_DATE = CalTime::ConvertYMDToDate(CalTime::MAX_YEAR, 11, 31); // December is month 11 static const CalTime::Date MAX_DATE = CalTime::ConvertYMDToDate(CalTime::MAX_YEAR, 11, 31); // December is month 11
byte game_info_version = p->Recv_uint8(); byte game_info_version = p.Recv_uint8();
NewGRFSerializationType newgrf_serialisation = NST_GRFID_MD5; NewGRFSerializationType newgrf_serialisation = NST_GRFID_MD5;
/* /*
@ -351,17 +351,17 @@ void DeserializeNetworkGameInfo(Packet *p, NetworkGameInfo *info, const GameInfo
switch (game_info_version) { switch (game_info_version) {
case 7: case 7:
info->ticks_playing = p->Recv_uint64(); info.ticks_playing = p.Recv_uint64();
[[fallthrough]]; [[fallthrough]];
case 6: case 6:
newgrf_serialisation = (NewGRFSerializationType)p->Recv_uint8(); newgrf_serialisation = (NewGRFSerializationType)p.Recv_uint8();
if (newgrf_serialisation >= NST_END) return; if (newgrf_serialisation >= NST_END) return;
[[fallthrough]]; [[fallthrough]];
case 5: { case 5: {
info->gamescript_version = (int)p->Recv_uint32(); info.gamescript_version = (int)p.Recv_uint32();
info->gamescript_name = p->Recv_string(NETWORK_NAME_LENGTH); info.gamescript_name = p.Recv_string(NETWORK_NAME_LENGTH);
[[fallthrough]]; [[fallthrough]];
} }
@ -370,23 +370,23 @@ void DeserializeNetworkGameInfo(Packet *p, NetworkGameInfo *info, const GameInfo
* protocol are matched to eachother. If that is not the case anymore a * protocol are matched to eachother. If that is not the case anymore a
* check must be added to ensure the received data is still valid. */ * check must be added to ensure the received data is still valid. */
static_assert(std::numeric_limits<uint8_t>::max() == NETWORK_MAX_GRF_COUNT); static_assert(std::numeric_limits<uint8_t>::max() == NETWORK_MAX_GRF_COUNT);
uint num_grfs = p->Recv_uint8(); uint num_grfs = p.Recv_uint8();
GRFConfig **dst = &info->grfconfig; GRFConfig **dst = &info.grfconfig;
for (uint i = 0; i < num_grfs; i++) { for (uint i = 0; i < num_grfs; i++) {
NamedGRFIdentifier grf; NamedGRFIdentifier grf;
switch (newgrf_serialisation) { switch (newgrf_serialisation) {
case NST_GRFID_MD5: case NST_GRFID_MD5:
DeserializeGRFIdentifier(p, &grf.ident); DeserializeGRFIdentifier(p, grf.ident);
break; break;
case NST_GRFID_MD5_NAME: case NST_GRFID_MD5_NAME:
DeserializeGRFIdentifierWithName(p, &grf); DeserializeGRFIdentifierWithName(p, grf);
break; break;
case NST_LOOKUP_ID: { case NST_LOOKUP_ID: {
if (newgrf_lookup_table == nullptr) return; if (newgrf_lookup_table == nullptr) return;
auto it = newgrf_lookup_table->find(p->Recv_uint32()); auto it = newgrf_lookup_table->find(p.Recv_uint32());
if (it == newgrf_lookup_table->end()) return; if (it == newgrf_lookup_table->end()) return;
grf = it->second; grf = it->second;
break; break;
@ -408,29 +408,29 @@ void DeserializeNetworkGameInfo(Packet *p, NetworkGameInfo *info, const GameInfo
} }
case 3: case 3:
info->calendar_date = Clamp(p->Recv_uint32(), 0, MAX_DATE.base()); info.calendar_date = Clamp(p.Recv_uint32(), 0, MAX_DATE.base());
info->calendar_start = Clamp(p->Recv_uint32(), 0, MAX_DATE.base()); info.calendar_start = Clamp(p.Recv_uint32(), 0, MAX_DATE.base());
[[fallthrough]]; [[fallthrough]];
case 2: case 2:
info->companies_max = p->Recv_uint8 (); info.companies_max = p.Recv_uint8 ();
info->companies_on = p->Recv_uint8 (); info.companies_on = p.Recv_uint8 ();
p->Recv_uint8(); // Used to contain max-spectators. p.Recv_uint8(); // Used to contain max-spectators.
[[fallthrough]]; [[fallthrough]];
case 1: case 1:
info->server_name = p->Recv_string(NETWORK_NAME_LENGTH); info.server_name = p.Recv_string(NETWORK_NAME_LENGTH);
info->server_revision = p->Recv_string(NETWORK_REVISION_LENGTH); info.server_revision = p.Recv_string(NETWORK_REVISION_LENGTH);
if (game_info_version < 6) p->Recv_uint8 (); // Used to contain server-lang. if (game_info_version < 6) p.Recv_uint8 (); // Used to contain server-lang.
info->use_password = p->Recv_bool (); info.use_password = p.Recv_bool ();
info->clients_max = p->Recv_uint8 (); info.clients_max = p.Recv_uint8 ();
info->clients_on = p->Recv_uint8 (); info.clients_on = p.Recv_uint8 ();
info->spectators_on = p->Recv_uint8 (); info.spectators_on = p.Recv_uint8 ();
if (game_info_version < 3) { // 16 bits dates got scrapped and are read earlier if (game_info_version < 3) { // 16 bits dates got scrapped and are read earlier
info->calendar_date = p->Recv_uint16() + CalTime::DAYS_TILL_ORIGINAL_BASE_YEAR; info.calendar_date = p.Recv_uint16() + CalTime::DAYS_TILL_ORIGINAL_BASE_YEAR;
info->calendar_start = p->Recv_uint16() + CalTime::DAYS_TILL_ORIGINAL_BASE_YEAR; info.calendar_start = p.Recv_uint16() + CalTime::DAYS_TILL_ORIGINAL_BASE_YEAR;
} }
if (game_info_version < 6) while (p->Recv_uint8() != 0) {} // Used to contain the map-name. if (game_info_version < 6) while (p.Recv_uint8() != 0) {} // Used to contain the map-name.
auto decode_map_size = [&](uint16_t in) -> uint32_t { auto decode_map_size = [&](uint16_t in) -> uint32_t {
if (in >= 65000) { if (in >= 65000) {
@ -439,13 +439,13 @@ void DeserializeNetworkGameInfo(Packet *p, NetworkGameInfo *info, const GameInfo
return in; return in;
} }
}; };
info->map_width = decode_map_size(p->Recv_uint16()); info.map_width = decode_map_size(p.Recv_uint16());
info->map_height = decode_map_size(p->Recv_uint16()); info.map_height = decode_map_size(p.Recv_uint16());
info->landscape = p->Recv_uint8 (); info.landscape = p.Recv_uint8 ();
info->dedicated = p->Recv_bool (); info.dedicated = p.Recv_bool ();
if (info->landscape >= NUM_LANDSCAPE) info->landscape = 0; if (info.landscape >= NUM_LANDSCAPE) info.landscape = 0;
} }
} }
@ -454,46 +454,46 @@ void DeserializeNetworkGameInfo(Packet *p, NetworkGameInfo *info, const GameInfo
* @param p the packet to read the data from * @param p the packet to read the data from
* @param info the NetworkGameInfo to deserialize into * @param info the NetworkGameInfo to deserialize into
*/ */
void DeserializeNetworkGameInfoExtended(Packet *p, NetworkGameInfo *info) void DeserializeNetworkGameInfoExtended(Packet &p, NetworkGameInfo &info)
{ {
static const CalTime::Date MAX_DATE = CalTime::ConvertYMDToDate(CalTime::MAX_YEAR, 11, 31); // December is month 11 static const CalTime::Date MAX_DATE = CalTime::ConvertYMDToDate(CalTime::MAX_YEAR, 11, 31); // December is month 11
const uint8_t version = p->Recv_uint8(); const uint8_t version = p.Recv_uint8();
if (version > SERVER_GAME_INFO_EXTENDED_MAX_VERSION) return; // Unknown version if (version > SERVER_GAME_INFO_EXTENDED_MAX_VERSION) return; // Unknown version
NewGRFSerializationType newgrf_serialisation = NST_GRFID_MD5; NewGRFSerializationType newgrf_serialisation = NST_GRFID_MD5;
info->calendar_date = Clamp(p->Recv_uint32(), 0, MAX_DATE.base()); info.calendar_date = Clamp(p.Recv_uint32(), 0, MAX_DATE.base());
info->calendar_start = Clamp(p->Recv_uint32(), 0, MAX_DATE.base()); info.calendar_start = Clamp(p.Recv_uint32(), 0, MAX_DATE.base());
info->companies_max = p->Recv_uint8 (); info.companies_max = p.Recv_uint8 ();
info->companies_on = p->Recv_uint8 (); info.companies_on = p.Recv_uint8 ();
p->Recv_uint8(); // Used to contain max-spectators. p.Recv_uint8(); // Used to contain max-spectators.
info->server_name = p->Recv_string(NETWORK_NAME_LENGTH); info.server_name = p.Recv_string(NETWORK_NAME_LENGTH);
info->server_revision = p->Recv_string(NETWORK_LONG_REVISION_LENGTH); info.server_revision = p.Recv_string(NETWORK_LONG_REVISION_LENGTH);
p->Recv_uint8 (); // Used to contain server-lang. p.Recv_uint8 (); // Used to contain server-lang.
info->use_password = p->Recv_bool (); info.use_password = p.Recv_bool ();
info->clients_max = p->Recv_uint8 (); info.clients_max = p.Recv_uint8 ();
info->clients_on = p->Recv_uint8 (); info.clients_on = p.Recv_uint8 ();
info->spectators_on = p->Recv_uint8 (); info.spectators_on = p.Recv_uint8 ();
while (p->Recv_uint8() != 0) {} // Used to contain the map-name. while (p.Recv_uint8() != 0) {} // Used to contain the map-name.
info->map_width = p->Recv_uint32(); info.map_width = p.Recv_uint32();
info->map_height = p->Recv_uint32(); info.map_height = p.Recv_uint32();
info->landscape = p->Recv_uint8 (); info.landscape = p.Recv_uint8 ();
if (info->landscape >= NUM_LANDSCAPE) info->landscape = 0; if (info.landscape >= NUM_LANDSCAPE) info.landscape = 0;
info->dedicated = p->Recv_bool (); info.dedicated = p.Recv_bool ();
if (version >= 1) { if (version >= 1) {
info->gamescript_version = (int)p->Recv_uint32(); info.gamescript_version = (int)p.Recv_uint32();
info->gamescript_name = p->Recv_string(NETWORK_NAME_LENGTH); info.gamescript_name = p.Recv_string(NETWORK_NAME_LENGTH);
newgrf_serialisation = (NewGRFSerializationType)p->Recv_uint8(); newgrf_serialisation = (NewGRFSerializationType)p.Recv_uint8();
if (newgrf_serialisation >= NST_END) return; if (newgrf_serialisation >= NST_END) return;
} }
{ {
GRFConfig **dst = &info->grfconfig; GRFConfig **dst = &info.grfconfig;
uint i; uint i;
uint num_grfs = p->Recv_uint32(); uint num_grfs = p.Recv_uint32();
/* Broken/bad data. It cannot have that many NewGRFs. */ /* Broken/bad data. It cannot have that many NewGRFs. */
if (num_grfs > MAX_NON_STATIC_GRF_COUNT) return; if (num_grfs > MAX_NON_STATIC_GRF_COUNT) return;
@ -502,11 +502,11 @@ void DeserializeNetworkGameInfoExtended(Packet *p, NetworkGameInfo *info)
NamedGRFIdentifier grf; NamedGRFIdentifier grf;
switch (newgrf_serialisation) { switch (newgrf_serialisation) {
case NST_GRFID_MD5: case NST_GRFID_MD5:
DeserializeGRFIdentifier(p, &grf.ident); DeserializeGRFIdentifier(p, grf.ident);
break; break;
case NST_GRFID_MD5_NAME: case NST_GRFID_MD5_NAME:
DeserializeGRFIdentifierWithName(p, &grf); DeserializeGRFIdentifierWithName(p, grf);
break; break;
case NST_LOOKUP_ID: { case NST_LOOKUP_ID: {
@ -534,11 +534,11 @@ void DeserializeNetworkGameInfoExtended(Packet *p, NetworkGameInfo *info)
* @param p the packet to write the data to. * @param p the packet to write the data to.
* @param grf the GRFIdentifier to serialize. * @param grf the GRFIdentifier to serialize.
*/ */
void SerializeGRFIdentifier(Packet *p, const GRFIdentifier *grf) void SerializeGRFIdentifier(Packet &p, const GRFIdentifier &grf)
{ {
p->Send_uint32(grf->grfid); p.Send_uint32(grf.grfid);
for (size_t j = 0; j < grf->md5sum.size(); j++) { for (size_t j = 0; j < grf.md5sum.size(); j++) {
p->Send_uint8(grf->md5sum[j]); p.Send_uint8(grf.md5sum[j]);
} }
} }
@ -547,11 +547,11 @@ void SerializeGRFIdentifier(Packet *p, const GRFIdentifier *grf)
* @param p the packet to read the data from. * @param p the packet to read the data from.
* @param grf the GRFIdentifier to deserialize. * @param grf the GRFIdentifier to deserialize.
*/ */
void DeserializeGRFIdentifier(Packet *p, GRFIdentifier *grf) void DeserializeGRFIdentifier(Packet &p, GRFIdentifier &grf)
{ {
grf->grfid = p->Recv_uint32(); grf.grfid = p.Recv_uint32();
for (size_t j = 0; j < grf->md5sum.size(); j++) { for (size_t j = 0; j < grf.md5sum.size(); j++) {
grf->md5sum[j] = p->Recv_uint8(); grf.md5sum[j] = p.Recv_uint8();
} }
} }
@ -560,8 +560,8 @@ void DeserializeGRFIdentifier(Packet *p, GRFIdentifier *grf)
* @param p the packet to read the data from. * @param p the packet to read the data from.
* @param grf the NamedGRFIdentifier to deserialize. * @param grf the NamedGRFIdentifier to deserialize.
*/ */
void DeserializeGRFIdentifierWithName(Packet *p, NamedGRFIdentifier *grf) void DeserializeGRFIdentifierWithName(Packet &p, NamedGRFIdentifier &grf)
{ {
DeserializeGRFIdentifier(p, &grf->ident); DeserializeGRFIdentifier(p, grf.ident);
grf->name = p->Recv_string(NETWORK_GRF_NAME_LENGTH); grf.name = p.Recv_string(NETWORK_GRF_NAME_LENGTH);
} }

@ -140,15 +140,15 @@ bool IsNetworkCompatibleVersion(const char *other, bool extended = false);
void CheckGameCompatibility(NetworkGameInfo &ngi, bool extended = false); void CheckGameCompatibility(NetworkGameInfo &ngi, bool extended = false);
void FillStaticNetworkServerGameInfo(); void FillStaticNetworkServerGameInfo();
const NetworkServerGameInfo *GetCurrentNetworkServerGameInfo(); const NetworkServerGameInfo &GetCurrentNetworkServerGameInfo();
void DeserializeGRFIdentifier(Packet *p, GRFIdentifier *grf); void DeserializeGRFIdentifier(Packet &p, GRFIdentifier &grf);
void DeserializeGRFIdentifierWithName(Packet *p, NamedGRFIdentifier *grf); void DeserializeGRFIdentifierWithName(Packet &p, NamedGRFIdentifier &grf);
void SerializeGRFIdentifier(Packet *p, const GRFIdentifier *grf); void SerializeGRFIdentifier(Packet &p, const GRFIdentifier &grf);
void DeserializeNetworkGameInfo(Packet *p, NetworkGameInfo *info, const GameInfoNewGRFLookupTable *newgrf_lookup_table = nullptr); void DeserializeNetworkGameInfo(Packet &p, NetworkGameInfo &info, const GameInfoNewGRFLookupTable *newgrf_lookup_table = nullptr);
void DeserializeNetworkGameInfoExtended(Packet *p, NetworkGameInfo *info); void DeserializeNetworkGameInfoExtended(Packet &p, NetworkGameInfo &info);
void SerializeNetworkGameInfo(Packet *p, const NetworkServerGameInfo *info, bool send_newgrf_names = true); void SerializeNetworkGameInfo(Packet &p, const NetworkServerGameInfo &info, bool send_newgrf_names = true);
void SerializeNetworkGameInfoExtended(Packet *p, const NetworkServerGameInfo *info, uint16_t flags, uint16_t version, bool send_newgrf_names = true); void SerializeNetworkGameInfoExtended(Packet &p, const NetworkServerGameInfo &info, uint16_t flags, uint16_t version, bool send_newgrf_names = true);
#endif /* NETWORK_CORE_GAME_INFO_H */ #endif /* NETWORK_CORE_GAME_INFO_H */

@ -198,8 +198,8 @@ struct SubPacketDeserialiser : public BufferDeserialisationHelper<SubPacketDeser
size_t size; size_t size;
PacketSize pos; PacketSize pos;
SubPacketDeserialiser(Packet *p, const byte *data, size_t size, PacketSize pos = 0) : cs(p->GetParentSocket()), data(data), size(size), pos(pos) {} SubPacketDeserialiser(Packet &p, const byte *data, size_t size, PacketSize pos = 0) : cs(p.GetParentSocket()), data(data), size(size), pos(pos) {}
SubPacketDeserialiser(Packet *p, const std::vector<byte> &buffer, PacketSize pos = 0) : cs(p->GetParentSocket()), data(buffer.data()), size(buffer.size()), pos(pos) {} SubPacketDeserialiser(Packet &p, const std::vector<byte> &buffer, PacketSize pos = 0) : cs(p.GetParentSocket()), data(buffer.data()), size(buffer.size()), pos(pos) {}
const byte *GetDeserialisationBuffer() const { return this->data; } const byte *GetDeserialisationBuffer() const { return this->data; }
size_t GetDeserialisationBufferSize() const { return this->size; } size_t GetDeserialisationBufferSize() const { return this->size; }

@ -28,19 +28,9 @@ NetworkTCPSocketHandler::NetworkTCPSocketHandler(SOCKET s) :
NetworkTCPSocketHandler::~NetworkTCPSocketHandler() NetworkTCPSocketHandler::~NetworkTCPSocketHandler()
{ {
this->EmptyPacketQueue();
this->CloseSocket(); this->CloseSocket();
} }
/**
* Free all pending and partially received packets.
*/
void NetworkTCPSocketHandler::EmptyPacketQueue()
{
this->packet_queue.clear();
this->packet_recv.reset();
}
/** /**
* Close the actual socket of the connection. * Close the actual socket of the connection.
* Please make sure CloseConnection is called before CloseSocket, as * Please make sure CloseConnection is called before CloseSocket, as
@ -63,7 +53,8 @@ NetworkRecvStatus NetworkTCPSocketHandler::CloseConnection([[maybe_unused]] bool
this->MarkClosed(); this->MarkClosed();
this->writable = false; this->writable = false;
this->EmptyPacketQueue(); this->packet_queue.clear();
this->packet_recv = nullptr;
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -134,15 +125,13 @@ void NetworkTCPSocketHandler::ShrinkToFitSendQueue()
*/ */
SendPacketsState NetworkTCPSocketHandler::SendPackets(bool closing_down) SendPacketsState NetworkTCPSocketHandler::SendPackets(bool closing_down)
{ {
ssize_t res;
/* We can not write to this socket!! */ /* We can not write to this socket!! */
if (!this->writable) return SPS_NONE_SENT; if (!this->writable) return SPS_NONE_SENT;
if (!this->IsConnected()) return SPS_CLOSED; if (!this->IsConnected()) return SPS_CLOSED;
while (!this->packet_queue.empty()) { while (!this->packet_queue.empty()) {
Packet *p = this->packet_queue.front().get(); Packet &p = *this->packet_queue.front();
res = p->TransferOut<int>(send, this->sock, 0); ssize_t res = p.TransferOut<int>(send, this->sock, 0);
if (res == -1) { if (res == -1) {
NetworkError err = NetworkError::GetLast(); NetworkError err = NetworkError::GetLast();
if (!err.WouldBlock()) { if (!err.WouldBlock()) {
@ -162,9 +151,9 @@ SendPacketsState NetworkTCPSocketHandler::SendPackets(bool closing_down)
} }
/* Is this packet sent? */ /* Is this packet sent? */
if (p->RemainingBytesToTransfer() == 0) { if (p.RemainingBytesToTransfer() == 0) {
/* Go to the next packet */ /* Go to the next packet */
if (_debug_net_level >= 5) this->LogSentPacket(*p); if (_debug_net_level >= 5) this->LogSentPacket(p);
this->packet_queue.pop_front(); this->packet_queue.pop_front();
} else { } else {
return SPS_PARTLY_SENT; return SPS_PARTLY_SENT;
@ -185,15 +174,15 @@ std::unique_ptr<Packet> NetworkTCPSocketHandler::ReceivePacket()
if (!this->IsConnected()) return nullptr; if (!this->IsConnected()) return nullptr;
if (this->packet_recv == nullptr) { if (this->packet_recv == nullptr) {
this->packet_recv.reset(new Packet(this, SHRT_MAX)); this->packet_recv = std::make_unique<Packet>(this, TCP_MTU);
} }
Packet *p = this->packet_recv.get(); Packet &p = *this->packet_recv.get();
/* Read packet size */ /* Read packet size */
if (!p->HasPacketSizeData()) { if (!p.HasPacketSizeData()) {
while (p->RemainingBytesToTransfer() != 0) { while (p.RemainingBytesToTransfer() != 0) {
res = p->TransferIn<int>(recv, this->sock, 0); res = p.TransferIn<int>(recv, this->sock, 0);
if (res == -1) { if (res == -1) {
NetworkError err = NetworkError::GetLast(); NetworkError err = NetworkError::GetLast();
if (!err.WouldBlock()) { if (!err.WouldBlock()) {
@ -213,7 +202,7 @@ std::unique_ptr<Packet> NetworkTCPSocketHandler::ReceivePacket()
} }
/* Parse the size in the received packet and if not valid, close the connection. */ /* Parse the size in the received packet and if not valid, close the connection. */
if (!p->ParsePacketSize()) { if (!p.ParsePacketSize()) {
DEBUG(net, 0, "ParsePacketSize failed, possible packet stream corruption"); DEBUG(net, 0, "ParsePacketSize failed, possible packet stream corruption");
this->CloseConnection(); this->CloseConnection();
return nullptr; return nullptr;
@ -221,8 +210,8 @@ std::unique_ptr<Packet> NetworkTCPSocketHandler::ReceivePacket()
} }
/* Read rest of packet */ /* Read rest of packet */
while (p->RemainingBytesToTransfer() != 0) { while (p.RemainingBytesToTransfer() != 0) {
res = p->TransferIn<int>(recv, this->sock, 0); res = p.TransferIn<int>(recv, this->sock, 0);
if (res == -1) { if (res == -1) {
NetworkError err = NetworkError::GetLast(); NetworkError err = NetworkError::GetLast();
if (!err.WouldBlock()) { if (!err.WouldBlock()) {
@ -242,7 +231,7 @@ std::unique_ptr<Packet> NetworkTCPSocketHandler::ReceivePacket()
} }
p->PrepareToRead(); p.PrepareToRead();
/* Prepare for receiving a new packet */ /* Prepare for receiving a new packet */
return std::move(this->packet_recv); return std::move(this->packet_recv);

@ -35,9 +35,8 @@ enum SendPacketsState {
class NetworkTCPSocketHandler : public NetworkSocketHandler { class NetworkTCPSocketHandler : public NetworkSocketHandler {
private: private:
ring_buffer<std::unique_ptr<Packet>> packet_queue; ///< Packets that are awaiting delivery ring_buffer<std::unique_ptr<Packet>> packet_queue; ///< Packets that are awaiting delivery
std::unique_ptr<Packet> packet_recv; ///< Partially received packet std::unique_ptr<Packet> packet_recv; ///< Partially received packet
void EmptyPacketQueue();
public: public:
SOCKET sock; ///< The socket currently connected to SOCKET sock; ///< The socket currently connected to
bool writable; ///< Can we write to this socket? bool writable; ///< Can we write to this socket?
@ -55,11 +54,6 @@ public:
void SendPrependPacket(std::unique_ptr<Packet> packet, int queue_after_packet_type); void SendPrependPacket(std::unique_ptr<Packet> packet, int queue_after_packet_type);
void ShrinkToFitSendQueue(); void ShrinkToFitSendQueue();
void SendPacket(Packet *packet)
{
this->SendPacket(std::unique_ptr<Packet>(packet));
}
SendPacketsState SendPackets(bool closing_down = false); SendPacketsState SendPackets(bool closing_down = false);
virtual std::unique_ptr<Packet> ReceivePacket(); virtual std::unique_ptr<Packet> ReceivePacket();

@ -43,9 +43,9 @@ NetworkRecvStatus NetworkAdminSocketHandler::CloseConnection(bool)
* @param p the packet to handle. * @param p the packet to handle.
* @return #NetworkRecvStatus of handling. * @return #NetworkRecvStatus of handling.
*/ */
NetworkRecvStatus NetworkAdminSocketHandler::HandlePacket(Packet *p) NetworkRecvStatus NetworkAdminSocketHandler::HandlePacket(Packet &p)
{ {
PacketAdminType type = (PacketAdminType)p->Recv_uint8(); PacketAdminType type = (PacketAdminType)p.Recv_uint8();
if (this->HasClientQuit()) { if (this->HasClientQuit()) {
DEBUG(net, 0, "[tcp/admin] Received invalid packet from '%s' (%s)", this->admin_name.c_str(), this->admin_version.c_str()); DEBUG(net, 0, "[tcp/admin] Received invalid packet from '%s' (%s)", this->admin_name.c_str(), this->admin_version.c_str());
@ -110,7 +110,7 @@ NetworkRecvStatus NetworkAdminSocketHandler::ReceivePackets()
{ {
std::unique_ptr<Packet> p; std::unique_ptr<Packet> p;
while ((p = this->ReceivePacket()) != nullptr) { while ((p = this->ReceivePacket()) != nullptr) {
NetworkRecvStatus res = this->HandlePacket(p.get()); NetworkRecvStatus res = this->HandlePacket(*p);
if (res != NETWORK_RECV_STATUS_OKAY) return res; if (res != NETWORK_RECV_STATUS_OKAY) return res;
} }
@ -128,40 +128,40 @@ NetworkRecvStatus NetworkAdminSocketHandler::ReceiveInvalidPacket(PacketAdminTyp
return NETWORK_RECV_STATUS_MALFORMED_PACKET; return NETWORK_RECV_STATUS_MALFORMED_PACKET;
} }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_ADMIN_JOIN(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_ADMIN_JOIN); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_ADMIN_JOIN(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_ADMIN_JOIN); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_ADMIN_QUIT(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_ADMIN_QUIT); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_ADMIN_QUIT(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_ADMIN_QUIT); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_ADMIN_UPDATE_FREQUENCY(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_ADMIN_UPDATE_FREQUENCY); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_ADMIN_UPDATE_FREQUENCY(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_ADMIN_UPDATE_FREQUENCY); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_ADMIN_POLL(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_ADMIN_POLL); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_ADMIN_POLL(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_ADMIN_POLL); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_ADMIN_CHAT(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_ADMIN_CHAT); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_ADMIN_CHAT(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_ADMIN_CHAT); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_ADMIN_EXTERNAL_CHAT(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_ADMIN_EXTERNAL_CHAT); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_ADMIN_EXTERNAL_CHAT(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_ADMIN_EXTERNAL_CHAT); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_ADMIN_RCON(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_ADMIN_RCON); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_ADMIN_RCON(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_ADMIN_RCON); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_ADMIN_GAMESCRIPT(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_ADMIN_GAMESCRIPT); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_ADMIN_GAMESCRIPT(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_ADMIN_GAMESCRIPT); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_ADMIN_PING(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_ADMIN_PING); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_ADMIN_PING(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_ADMIN_PING); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_FULL(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_FULL); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_FULL(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_FULL); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_BANNED(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_BANNED); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_BANNED(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_BANNED); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_ERROR(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_ERROR); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_ERROR(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_ERROR); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_PROTOCOL(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_PROTOCOL); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_PROTOCOL(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_PROTOCOL); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_WELCOME(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_WELCOME); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_WELCOME(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_WELCOME); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_NEWGAME(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_NEWGAME); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_NEWGAME(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_NEWGAME); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_SHUTDOWN(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_SHUTDOWN); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_SHUTDOWN(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_SHUTDOWN); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_DATE(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_DATE); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_DATE(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_DATE); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_CLIENT_JOIN(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_CLIENT_JOIN); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_CLIENT_JOIN(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_CLIENT_JOIN); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_CLIENT_INFO(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_CLIENT_INFO); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_CLIENT_INFO(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_CLIENT_INFO); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_CLIENT_UPDATE(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_CLIENT_UPDATE); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_CLIENT_UPDATE(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_CLIENT_UPDATE); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_CLIENT_QUIT(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_CLIENT_QUIT); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_CLIENT_QUIT(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_CLIENT_QUIT); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_CLIENT_ERROR(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_CLIENT_ERROR); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_CLIENT_ERROR(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_CLIENT_ERROR); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_COMPANY_NEW(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_COMPANY_NEW); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_COMPANY_NEW(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_COMPANY_NEW); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_COMPANY_INFO(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_COMPANY_INFO); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_COMPANY_INFO(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_COMPANY_INFO); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_COMPANY_UPDATE(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_COMPANY_UPDATE); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_COMPANY_UPDATE(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_COMPANY_UPDATE); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_COMPANY_REMOVE(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_COMPANY_REMOVE); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_COMPANY_REMOVE(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_COMPANY_REMOVE); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_COMPANY_ECONOMY(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_COMPANY_ECONOMY); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_COMPANY_ECONOMY(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_COMPANY_ECONOMY); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_COMPANY_STATS(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_COMPANY_STATS); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_COMPANY_STATS(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_COMPANY_STATS); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_CHAT(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_CHAT); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_CHAT(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_CHAT); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_RCON(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_RCON); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_RCON(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_RCON); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_CONSOLE(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_CONSOLE); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_CONSOLE(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_CONSOLE); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_CMD_NAMES(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_CMD_NAMES); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_CMD_NAMES(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_CMD_NAMES); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_CMD_LOGGING(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_CMD_LOGGING); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_CMD_LOGGING(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_CMD_LOGGING); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_RCON_END(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_RCON_END); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_RCON_END(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_RCON_END); }
NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_PONG(Packet *) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_PONG); } NetworkRecvStatus NetworkAdminSocketHandler::Receive_SERVER_PONG(Packet &) { return this->ReceiveInvalidPacket(ADMIN_PACKET_SERVER_PONG); }

@ -21,7 +21,7 @@
* Enum with types of TCP packets specific to the admin network. * Enum with types of TCP packets specific to the admin network.
* This protocol may only be extended to ensure stability. * This protocol may only be extended to ensure stability.
*/ */
enum PacketAdminType { enum PacketAdminType : uint8_t {
ADMIN_PACKET_ADMIN_JOIN, ///< The admin announces and authenticates itself to the server. ADMIN_PACKET_ADMIN_JOIN, ///< The admin announces and authenticates itself to the server.
ADMIN_PACKET_ADMIN_QUIT, ///< The admin tells the server that it is quitting. ADMIN_PACKET_ADMIN_QUIT, ///< The admin tells the server that it is quitting.
ADMIN_PACKET_ADMIN_UPDATE_FREQUENCY, ///< The admin tells the server the update frequency of a particular piece of information. ADMIN_PACKET_ADMIN_UPDATE_FREQUENCY, ///< The admin tells the server the update frequency of a particular piece of information.
@ -124,14 +124,14 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_ADMIN_JOIN(Packet *p); virtual NetworkRecvStatus Receive_ADMIN_JOIN(Packet &p);
/** /**
* Notification to the server that this admin is quitting. * Notification to the server that this admin is quitting.
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_ADMIN_QUIT(Packet *p); virtual NetworkRecvStatus Receive_ADMIN_QUIT(Packet &p);
/** /**
* Register updates to be sent at certain frequencies (as announced in the PROTOCOL packet): * Register updates to be sent at certain frequencies (as announced in the PROTOCOL packet):
@ -140,7 +140,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_ADMIN_UPDATE_FREQUENCY(Packet *p); virtual NetworkRecvStatus Receive_ADMIN_UPDATE_FREQUENCY(Packet &p);
/** /**
* Poll the server for certain updates, an invalid poll (e.g. not existent id) gets silently dropped: * Poll the server for certain updates, an invalid poll (e.g. not existent id) gets silently dropped:
@ -151,7 +151,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_ADMIN_POLL(Packet *p); virtual NetworkRecvStatus Receive_ADMIN_POLL(Packet &p);
/** /**
* Send chat as the server: * Send chat as the server:
@ -162,7 +162,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_ADMIN_CHAT(Packet *p); virtual NetworkRecvStatus Receive_ADMIN_CHAT(Packet &p);
/** /**
* Send chat from the external source: * Send chat from the external source:
@ -173,7 +173,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_ADMIN_EXTERNAL_CHAT(Packet *p); virtual NetworkRecvStatus Receive_ADMIN_EXTERNAL_CHAT(Packet &p);
/** /**
* Execute a command on the servers console: * Execute a command on the servers console:
@ -181,7 +181,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_ADMIN_RCON(Packet *p); virtual NetworkRecvStatus Receive_ADMIN_RCON(Packet &p);
/** /**
* Send a JSON string to the current active GameScript. * Send a JSON string to the current active GameScript.
@ -189,7 +189,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_ADMIN_GAMESCRIPT(Packet *p); virtual NetworkRecvStatus Receive_ADMIN_GAMESCRIPT(Packet &p);
/** /**
* Ping the server, requiring the server to reply with a pong packet. * Ping the server, requiring the server to reply with a pong packet.
@ -197,21 +197,21 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_ADMIN_PING(Packet *p); virtual NetworkRecvStatus Receive_ADMIN_PING(Packet &p);
/** /**
* The server is full (connection gets closed). * The server is full (connection gets closed).
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_FULL(Packet *p); virtual NetworkRecvStatus Receive_SERVER_FULL(Packet &p);
/** /**
* The source IP address is banned (connection gets closed). * The source IP address is banned (connection gets closed).
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_BANNED(Packet *p); virtual NetworkRecvStatus Receive_SERVER_BANNED(Packet &p);
/** /**
* An error was caused by this admin connection (connection gets closed). * An error was caused by this admin connection (connection gets closed).
@ -219,7 +219,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_ERROR(Packet *p); virtual NetworkRecvStatus Receive_SERVER_ERROR(Packet &p);
/** /**
* Inform a just joined admin about the protocol specifics: * Inform a just joined admin about the protocol specifics:
@ -230,7 +230,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_PROTOCOL(Packet *p); virtual NetworkRecvStatus Receive_SERVER_PROTOCOL(Packet &p);
/** /**
* Welcome a connected admin to the game: * Welcome a connected admin to the game:
@ -246,21 +246,21 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_WELCOME(Packet *p); virtual NetworkRecvStatus Receive_SERVER_WELCOME(Packet &p);
/** /**
* Notification about a newgame. * Notification about a newgame.
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_NEWGAME(Packet *p); virtual NetworkRecvStatus Receive_SERVER_NEWGAME(Packet &p);
/** /**
* Notification about the server shutting down. * Notification about the server shutting down.
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_SHUTDOWN(Packet *p); virtual NetworkRecvStatus Receive_SERVER_SHUTDOWN(Packet &p);
/** /**
* Send the current date of the game: * Send the current date of the game:
@ -268,7 +268,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_DATE(Packet *p); virtual NetworkRecvStatus Receive_SERVER_DATE(Packet &p);
/** /**
* Notification of a new client: * Notification of a new client:
@ -276,7 +276,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_CLIENT_JOIN(Packet *p); virtual NetworkRecvStatus Receive_SERVER_CLIENT_JOIN(Packet &p);
/** /**
* Client information of a specific client: * Client information of a specific client:
@ -289,7 +289,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_CLIENT_INFO(Packet *p); virtual NetworkRecvStatus Receive_SERVER_CLIENT_INFO(Packet &p);
/** /**
* Client update details on a specific client (e.g. after rename or move): * Client update details on a specific client (e.g. after rename or move):
@ -299,7 +299,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_CLIENT_UPDATE(Packet *p); virtual NetworkRecvStatus Receive_SERVER_CLIENT_UPDATE(Packet &p);
/** /**
* Notification about a client leaving the game. * Notification about a client leaving the game.
@ -307,7 +307,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_CLIENT_QUIT(Packet *p); virtual NetworkRecvStatus Receive_SERVER_CLIENT_QUIT(Packet &p);
/** /**
* Notification about a client error (and thus the clients disconnection). * Notification about a client error (and thus the clients disconnection).
@ -316,7 +316,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_CLIENT_ERROR(Packet *p); virtual NetworkRecvStatus Receive_SERVER_CLIENT_ERROR(Packet &p);
/** /**
* Notification of a new company: * Notification of a new company:
@ -324,7 +324,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_COMPANY_NEW(Packet *p); virtual NetworkRecvStatus Receive_SERVER_COMPANY_NEW(Packet &p);
/** /**
* Company information on a specific company: * Company information on a specific company:
@ -338,7 +338,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_COMPANY_INFO(Packet *p); virtual NetworkRecvStatus Receive_SERVER_COMPANY_INFO(Packet &p);
/** /**
* Company information of a specific company: * Company information of a specific company:
@ -355,7 +355,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_COMPANY_UPDATE(Packet *p); virtual NetworkRecvStatus Receive_SERVER_COMPANY_UPDATE(Packet &p);
/** /**
* Notification about a removed company (e.g. due to bankruptcy). * Notification about a removed company (e.g. due to bankruptcy).
@ -364,7 +364,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_COMPANY_REMOVE(Packet *p); virtual NetworkRecvStatus Receive_SERVER_COMPANY_REMOVE(Packet &p);
/** /**
* Economy update of a specific company: * Economy update of a specific company:
@ -382,7 +382,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_COMPANY_ECONOMY(Packet *p); virtual NetworkRecvStatus Receive_SERVER_COMPANY_ECONOMY(Packet &p);
/** /**
* Company statistics on stations and vehicles: * Company statistics on stations and vehicles:
@ -400,7 +400,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_COMPANY_STATS(Packet *p); virtual NetworkRecvStatus Receive_SERVER_COMPANY_STATS(Packet &p);
/** /**
* Send chat from the game into the admin network: * Send chat from the game into the admin network:
@ -412,7 +412,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_CHAT(Packet *p); virtual NetworkRecvStatus Receive_SERVER_CHAT(Packet &p);
/** /**
* Result of an rcon command: * Result of an rcon command:
@ -421,7 +421,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_RCON(Packet *p); virtual NetworkRecvStatus Receive_SERVER_RCON(Packet &p);
/** /**
* Send what would be printed on the server's console also into the admin network. * Send what would be printed on the server's console also into the admin network.
@ -430,7 +430,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_CONSOLE(Packet *p); virtual NetworkRecvStatus Receive_SERVER_CONSOLE(Packet &p);
/** /**
* Send DoCommand names to the bot upon request only. * Send DoCommand names to the bot upon request only.
@ -449,7 +449,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_CMD_NAMES(Packet *p); virtual NetworkRecvStatus Receive_SERVER_CMD_NAMES(Packet &p);
/** /**
* Send incoming command packets to the admin network. * Send incoming command packets to the admin network.
@ -471,7 +471,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_CMD_LOGGING(Packet *p); virtual NetworkRecvStatus Receive_SERVER_CMD_LOGGING(Packet &p);
/** /**
* Send a ping-reply (pong) to the admin that sent us the ping packet. * Send a ping-reply (pong) to the admin that sent us the ping packet.
@ -479,7 +479,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_PONG(Packet *p); virtual NetworkRecvStatus Receive_SERVER_PONG(Packet &p);
/** /**
* Notify the admin connection that the rcon command has finished. * Notify the admin connection that the rcon command has finished.
@ -487,9 +487,9 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return The state the network should have. * @return The state the network should have.
*/ */
virtual NetworkRecvStatus Receive_SERVER_RCON_END(Packet *p); virtual NetworkRecvStatus Receive_SERVER_RCON_END(Packet &p);
NetworkRecvStatus HandlePacket(Packet *p); NetworkRecvStatus HandlePacket(Packet &p);
public: public:
NetworkRecvStatus CloseConnection(bool error = true) override; NetworkRecvStatus CloseConnection(bool error = true) override;

@ -98,9 +98,9 @@ const char *ContentInfo::GetTextfile(TextfileType type) const
* @param p the packet to handle * @param p the packet to handle
* @return true if we should immediately handle further packets, false otherwise * @return true if we should immediately handle further packets, false otherwise
*/ */
bool NetworkContentSocketHandler::HandlePacket(Packet *p) bool NetworkContentSocketHandler::HandlePacket(Packet &p)
{ {
PacketContentType type = (PacketContentType)p->Recv_uint8(); PacketContentType type = (PacketContentType)p.Recv_uint8();
switch (this->HasClientQuit() ? PACKET_CONTENT_END : type) { switch (this->HasClientQuit() ? PACKET_CONTENT_END : type) {
case PACKET_CONTENT_CLIENT_INFO_LIST: return this->Receive_CLIENT_INFO_LIST(p); case PACKET_CONTENT_CLIENT_INFO_LIST: return this->Receive_CLIENT_INFO_LIST(p);
@ -150,7 +150,7 @@ bool NetworkContentSocketHandler::ReceivePackets()
static const int MAX_PACKETS_TO_RECEIVE = 42; static const int MAX_PACKETS_TO_RECEIVE = 42;
int i = MAX_PACKETS_TO_RECEIVE; int i = MAX_PACKETS_TO_RECEIVE;
while (--i != 0 && (p = this->ReceivePacket()) != nullptr) { while (--i != 0 && (p = this->ReceivePacket()) != nullptr) {
bool cont = this->HandlePacket(p.get()); bool cont = this->HandlePacket(*p);
if (!cont) return true; if (!cont) return true;
} }
@ -169,13 +169,13 @@ bool NetworkContentSocketHandler::ReceiveInvalidPacket(PacketContentType type)
return false; return false;
} }
bool NetworkContentSocketHandler::Receive_CLIENT_INFO_LIST(Packet *) { return this->ReceiveInvalidPacket(PACKET_CONTENT_CLIENT_INFO_LIST); } bool NetworkContentSocketHandler::Receive_CLIENT_INFO_LIST(Packet &) { return this->ReceiveInvalidPacket(PACKET_CONTENT_CLIENT_INFO_LIST); }
bool NetworkContentSocketHandler::Receive_CLIENT_INFO_ID(Packet *) { return this->ReceiveInvalidPacket(PACKET_CONTENT_CLIENT_INFO_ID); } bool NetworkContentSocketHandler::Receive_CLIENT_INFO_ID(Packet &) { return this->ReceiveInvalidPacket(PACKET_CONTENT_CLIENT_INFO_ID); }
bool NetworkContentSocketHandler::Receive_CLIENT_INFO_EXTID(Packet *) { return this->ReceiveInvalidPacket(PACKET_CONTENT_CLIENT_INFO_EXTID); } bool NetworkContentSocketHandler::Receive_CLIENT_INFO_EXTID(Packet &) { return this->ReceiveInvalidPacket(PACKET_CONTENT_CLIENT_INFO_EXTID); }
bool NetworkContentSocketHandler::Receive_CLIENT_INFO_EXTID_MD5(Packet *) { return this->ReceiveInvalidPacket(PACKET_CONTENT_CLIENT_INFO_EXTID_MD5); } bool NetworkContentSocketHandler::Receive_CLIENT_INFO_EXTID_MD5(Packet &) { return this->ReceiveInvalidPacket(PACKET_CONTENT_CLIENT_INFO_EXTID_MD5); }
bool NetworkContentSocketHandler::Receive_SERVER_INFO(Packet *) { return this->ReceiveInvalidPacket(PACKET_CONTENT_SERVER_INFO); } bool NetworkContentSocketHandler::Receive_SERVER_INFO(Packet &) { return this->ReceiveInvalidPacket(PACKET_CONTENT_SERVER_INFO); }
bool NetworkContentSocketHandler::Receive_CLIENT_CONTENT(Packet *) { return this->ReceiveInvalidPacket(PACKET_CONTENT_CLIENT_CONTENT); } bool NetworkContentSocketHandler::Receive_CLIENT_CONTENT(Packet &) { return this->ReceiveInvalidPacket(PACKET_CONTENT_CLIENT_CONTENT); }
bool NetworkContentSocketHandler::Receive_SERVER_CONTENT(Packet *) { return this->ReceiveInvalidPacket(PACKET_CONTENT_SERVER_CONTENT); } bool NetworkContentSocketHandler::Receive_SERVER_CONTENT(Packet &) { return this->ReceiveInvalidPacket(PACKET_CONTENT_SERVER_CONTENT); }
/** /**
* Helper to get the subdirectory a #ContentInfo is located in. * Helper to get the subdirectory a #ContentInfo is located in.

@ -34,7 +34,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_CLIENT_INFO_LIST(Packet *p); virtual bool Receive_CLIENT_INFO_LIST(Packet &p);
/** /**
* Client requesting a list of content info: * Client requesting a list of content info:
@ -43,7 +43,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_CLIENT_INFO_ID(Packet *p); virtual bool Receive_CLIENT_INFO_ID(Packet &p);
/** /**
* Client requesting a list of content info based on an external * Client requesting a list of content info based on an external
@ -57,7 +57,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_CLIENT_INFO_EXTID(Packet *p); virtual bool Receive_CLIENT_INFO_EXTID(Packet &p);
/** /**
* Client requesting a list of content info based on an external * Client requesting a list of content info based on an external
@ -72,7 +72,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_CLIENT_INFO_EXTID_MD5(Packet *p); virtual bool Receive_CLIENT_INFO_EXTID_MD5(Packet &p);
/** /**
* Server sending list of content info: * Server sending list of content info:
@ -90,7 +90,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_SERVER_INFO(Packet *p); virtual bool Receive_SERVER_INFO(Packet &p);
/** /**
* Client requesting the actual content: * Client requesting the actual content:
@ -99,7 +99,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_CLIENT_CONTENT(Packet *p); virtual bool Receive_CLIENT_CONTENT(Packet &p);
/** /**
* Server sending list of content info: * Server sending list of content info:
@ -111,9 +111,9 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_SERVER_CONTENT(Packet *p); virtual bool Receive_SERVER_CONTENT(Packet &p);
bool HandlePacket(Packet *p); bool HandlePacket(Packet &p);
public: public:
/** /**
* Create a new cs socket handler for a given cs * Create a new cs socket handler for a given cs

@ -33,7 +33,7 @@ enum ContentType {
}; };
/** Enum with all types of TCP content packets. The order MUST not be changed **/ /** Enum with all types of TCP content packets. The order MUST not be changed **/
enum PacketContentType { enum PacketContentType : uint8_t {
PACKET_CONTENT_CLIENT_INFO_LIST, ///< Queries the content server for a list of info of a given content type PACKET_CONTENT_CLIENT_INFO_LIST, ///< Queries the content server for a list of info of a given content type
PACKET_CONTENT_CLIENT_INFO_ID, ///< Queries the content server for information about a list of internal IDs PACKET_CONTENT_CLIENT_INFO_ID, ///< Queries the content server for information about a list of internal IDs
PACKET_CONTENT_CLIENT_INFO_EXTID, ///< Queries the content server for information about a list of external IDs PACKET_CONTENT_CLIENT_INFO_EXTID, ///< Queries the content server for information about a list of external IDs

@ -22,9 +22,9 @@
* @param p The packet to handle. * @param p The packet to handle.
* @return True iff we should immediately handle further packets. * @return True iff we should immediately handle further packets.
*/ */
bool NetworkCoordinatorSocketHandler::HandlePacket(Packet *p) bool NetworkCoordinatorSocketHandler::HandlePacket(Packet &p)
{ {
PacketCoordinatorType type = (PacketCoordinatorType)p->Recv_uint8(); PacketCoordinatorType type = (PacketCoordinatorType)p.Recv_uint8();
switch (type) { switch (type) {
case PACKET_COORDINATOR_GC_ERROR: return this->Receive_GC_ERROR(p); case PACKET_COORDINATOR_GC_ERROR: return this->Receive_GC_ERROR(p);
@ -68,7 +68,7 @@ bool NetworkCoordinatorSocketHandler::ReceivePackets()
static const int MAX_PACKETS_TO_RECEIVE = 42; static const int MAX_PACKETS_TO_RECEIVE = 42;
int i = MAX_PACKETS_TO_RECEIVE; int i = MAX_PACKETS_TO_RECEIVE;
while (--i != 0 && (p = this->ReceivePacket()) != nullptr) { while (--i != 0 && (p = this->ReceivePacket()) != nullptr) {
bool cont = this->HandlePacket(p.get()); bool cont = this->HandlePacket(*p);
if (!cont) return true; if (!cont) return true;
} }
@ -86,20 +86,20 @@ bool NetworkCoordinatorSocketHandler::ReceiveInvalidPacket(PacketCoordinatorType
return false; return false;
} }
bool NetworkCoordinatorSocketHandler::Receive_GC_ERROR(Packet *) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_ERROR); } bool NetworkCoordinatorSocketHandler::Receive_GC_ERROR(Packet &) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_ERROR); }
bool NetworkCoordinatorSocketHandler::Receive_SERVER_REGISTER(Packet *) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_SERVER_REGISTER); } bool NetworkCoordinatorSocketHandler::Receive_SERVER_REGISTER(Packet &) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_SERVER_REGISTER); }
bool NetworkCoordinatorSocketHandler::Receive_GC_REGISTER_ACK(Packet *) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_REGISTER_ACK); } bool NetworkCoordinatorSocketHandler::Receive_GC_REGISTER_ACK(Packet &) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_REGISTER_ACK); }
bool NetworkCoordinatorSocketHandler::Receive_SERVER_UPDATE(Packet *) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_SERVER_UPDATE); } bool NetworkCoordinatorSocketHandler::Receive_SERVER_UPDATE(Packet &) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_SERVER_UPDATE); }
bool NetworkCoordinatorSocketHandler::Receive_CLIENT_LISTING(Packet *) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_CLIENT_LISTING); } bool NetworkCoordinatorSocketHandler::Receive_CLIENT_LISTING(Packet &) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_CLIENT_LISTING); }
bool NetworkCoordinatorSocketHandler::Receive_GC_LISTING(Packet *) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_LISTING); } bool NetworkCoordinatorSocketHandler::Receive_GC_LISTING(Packet &) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_LISTING); }
bool NetworkCoordinatorSocketHandler::Receive_CLIENT_CONNECT(Packet *) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_CLIENT_CONNECT); } bool NetworkCoordinatorSocketHandler::Receive_CLIENT_CONNECT(Packet &) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_CLIENT_CONNECT); }
bool NetworkCoordinatorSocketHandler::Receive_GC_CONNECTING(Packet *) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_CONNECTING); } bool NetworkCoordinatorSocketHandler::Receive_GC_CONNECTING(Packet &) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_CONNECTING); }
bool NetworkCoordinatorSocketHandler::Receive_SERCLI_CONNECT_FAILED(Packet *) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_SERCLI_CONNECT_FAILED); } bool NetworkCoordinatorSocketHandler::Receive_SERCLI_CONNECT_FAILED(Packet &) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_SERCLI_CONNECT_FAILED); }
bool NetworkCoordinatorSocketHandler::Receive_GC_CONNECT_FAILED(Packet *) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_CONNECT_FAILED); } bool NetworkCoordinatorSocketHandler::Receive_GC_CONNECT_FAILED(Packet &) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_CONNECT_FAILED); }
bool NetworkCoordinatorSocketHandler::Receive_CLIENT_CONNECTED(Packet *) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_CLIENT_CONNECTED); } bool NetworkCoordinatorSocketHandler::Receive_CLIENT_CONNECTED(Packet &) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_CLIENT_CONNECTED); }
bool NetworkCoordinatorSocketHandler::Receive_GC_DIRECT_CONNECT(Packet *) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_DIRECT_CONNECT); } bool NetworkCoordinatorSocketHandler::Receive_GC_DIRECT_CONNECT(Packet &) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_DIRECT_CONNECT); }
bool NetworkCoordinatorSocketHandler::Receive_GC_STUN_REQUEST(Packet *) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_STUN_REQUEST); } bool NetworkCoordinatorSocketHandler::Receive_GC_STUN_REQUEST(Packet &) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_STUN_REQUEST); }
bool NetworkCoordinatorSocketHandler::Receive_SERCLI_STUN_RESULT(Packet *) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_SERCLI_STUN_RESULT); } bool NetworkCoordinatorSocketHandler::Receive_SERCLI_STUN_RESULT(Packet &) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_SERCLI_STUN_RESULT); }
bool NetworkCoordinatorSocketHandler::Receive_GC_STUN_CONNECT(Packet *) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_STUN_CONNECT); } bool NetworkCoordinatorSocketHandler::Receive_GC_STUN_CONNECT(Packet &) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_STUN_CONNECT); }
bool NetworkCoordinatorSocketHandler::Receive_GC_NEWGRF_LOOKUP(Packet *) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_NEWGRF_LOOKUP); } bool NetworkCoordinatorSocketHandler::Receive_GC_NEWGRF_LOOKUP(Packet &) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_NEWGRF_LOOKUP); }
bool NetworkCoordinatorSocketHandler::Receive_GC_TURN_CONNECT(Packet *) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_TURN_CONNECT); } bool NetworkCoordinatorSocketHandler::Receive_GC_TURN_CONNECT(Packet &) { return this->ReceiveInvalidPacket(PACKET_COORDINATOR_GC_TURN_CONNECT); }

@ -25,7 +25,7 @@
* CLIENT -> packets from Client to Game Coordinator. * CLIENT -> packets from Client to Game Coordinator.
* SERCLI -> packets from either the Server or Client to Game Coordinator. * SERCLI -> packets from either the Server or Client to Game Coordinator.
**/ **/
enum PacketCoordinatorType { enum PacketCoordinatorType : uint8_t {
PACKET_COORDINATOR_GC_ERROR, ///< Game Coordinator indicates there was an error. PACKET_COORDINATOR_GC_ERROR, ///< Game Coordinator indicates there was an error.
PACKET_COORDINATOR_SERVER_REGISTER, ///< Server registration. PACKET_COORDINATOR_SERVER_REGISTER, ///< Server registration.
PACKET_COORDINATOR_GC_REGISTER_ACK, ///< Game Coordinator accepts the registration. PACKET_COORDINATOR_GC_REGISTER_ACK, ///< Game Coordinator accepts the registration.
@ -83,7 +83,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_GC_ERROR(Packet *p); virtual bool Receive_GC_ERROR(Packet &p);
/** /**
* Server is starting a multiplayer game and wants to let the * Server is starting a multiplayer game and wants to let the
@ -98,7 +98,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_SERVER_REGISTER(Packet *p); virtual bool Receive_SERVER_REGISTER(Packet &p);
/** /**
* Game Coordinator acknowledges the registration. * Game Coordinator acknowledges the registration.
@ -110,7 +110,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_GC_REGISTER_ACK(Packet *p); virtual bool Receive_GC_REGISTER_ACK(Packet &p);
/** /**
* Send an update of the current state of the server to the Game Coordinator. * Send an update of the current state of the server to the Game Coordinator.
@ -121,7 +121,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_SERVER_UPDATE(Packet *p); virtual bool Receive_SERVER_UPDATE(Packet &p);
/** /**
* Client requests a list of all public servers. * Client requests a list of all public servers.
@ -134,7 +134,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_CLIENT_LISTING(Packet *p); virtual bool Receive_CLIENT_LISTING(Packet &p);
/** /**
* Game Coordinator replies with a list of all public servers. Multiple * Game Coordinator replies with a list of all public servers. Multiple
@ -149,7 +149,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_GC_LISTING(Packet *p); virtual bool Receive_GC_LISTING(Packet &p);
/** /**
* Client wants to connect to a Server. * Client wants to connect to a Server.
@ -160,7 +160,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_CLIENT_CONNECT(Packet *p); virtual bool Receive_CLIENT_CONNECT(Packet &p);
/** /**
* Game Coordinator informs the Client under what token it will start the * Game Coordinator informs the Client under what token it will start the
@ -172,7 +172,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_GC_CONNECTING(Packet *p); virtual bool Receive_GC_CONNECTING(Packet &p);
/** /**
* Client or Server failed to connect to the remote side. * Client or Server failed to connect to the remote side.
@ -184,7 +184,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_SERCLI_CONNECT_FAILED(Packet *p); virtual bool Receive_SERCLI_CONNECT_FAILED(Packet &p);
/** /**
* Game Coordinator informs the Client that it failed to find a way to * Game Coordinator informs the Client that it failed to find a way to
@ -196,7 +196,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_GC_CONNECT_FAILED(Packet *p); virtual bool Receive_GC_CONNECT_FAILED(Packet &p);
/** /**
* Client informs the Game Coordinator the connection with the Server is * Client informs the Game Coordinator the connection with the Server is
@ -208,7 +208,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_CLIENT_CONNECTED(Packet *p); virtual bool Receive_CLIENT_CONNECTED(Packet &p);
/** /**
* Game Coordinator requests that the Client makes a direct connection to * Game Coordinator requests that the Client makes a direct connection to
@ -222,7 +222,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_GC_DIRECT_CONNECT(Packet *p); virtual bool Receive_GC_DIRECT_CONNECT(Packet &p);
/** /**
* Game Coordinator requests the client/server to do a STUN request to the * Game Coordinator requests the client/server to do a STUN request to the
@ -237,7 +237,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_GC_STUN_REQUEST(Packet *p); virtual bool Receive_GC_STUN_REQUEST(Packet &p);
/** /**
* Client/server informs the Game Coordinator the result of a STUN request. * Client/server informs the Game Coordinator the result of a STUN request.
@ -250,7 +250,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_SERCLI_STUN_RESULT(Packet *p); virtual bool Receive_SERCLI_STUN_RESULT(Packet &p);
/** /**
* Game Coordinator informs the client/server of its STUN peer (the host:ip * Game Coordinator informs the client/server of its STUN peer (the host:ip
@ -266,7 +266,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_GC_STUN_CONNECT(Packet *p); virtual bool Receive_GC_STUN_CONNECT(Packet &p);
/** /**
* Game Coordinator informs the client of updates for the NewGRFs lookup table * Game Coordinator informs the client of updates for the NewGRFs lookup table
@ -289,7 +289,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_GC_NEWGRF_LOOKUP(Packet *p); virtual bool Receive_GC_NEWGRF_LOOKUP(Packet &p);
/** /**
* Game Coordinator requests that we make a connection to the indicated * Game Coordinator requests that we make a connection to the indicated
@ -303,9 +303,9 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_GC_TURN_CONNECT(Packet *p); virtual bool Receive_GC_TURN_CONNECT(Packet &p);
bool HandlePacket(Packet *p); bool HandlePacket(Packet &p);
public: public:
/** /**
* Create a new cs socket handler for a given cs. * Create a new cs socket handler for a given cs.

@ -129,9 +129,9 @@ NetworkRecvStatus NetworkGameSocketHandler::CloseConnection(bool)
* @param p the packet to handle * @param p the packet to handle
* @return #NetworkRecvStatus of handling. * @return #NetworkRecvStatus of handling.
*/ */
NetworkRecvStatus NetworkGameSocketHandler::HandlePacket(Packet *p) NetworkRecvStatus NetworkGameSocketHandler::HandlePacket(Packet &p)
{ {
PacketGameType type = (PacketGameType)p->Recv_uint8(); PacketGameType type = (PacketGameType)p.Recv_uint8();
if (this->HasClientQuit()) { if (this->HasClientQuit()) {
DEBUG(net, 0, "[tcp/game] Received invalid packet from client %d", this->client_id); DEBUG(net, 0, "[tcp/game] Received invalid packet from client %d", this->client_id);
@ -215,7 +215,7 @@ NetworkRecvStatus NetworkGameSocketHandler::ReceivePackets()
{ {
std::unique_ptr<Packet> p; std::unique_ptr<Packet> p;
while ((p = this->ReceivePacket()) != nullptr) { while ((p = this->ReceivePacket()) != nullptr) {
NetworkRecvStatus res = HandlePacket(p.get()); NetworkRecvStatus res = HandlePacket(*p);
if (res != NETWORK_RECV_STATUS_OKAY) return res; if (res != NETWORK_RECV_STATUS_OKAY) return res;
} }
@ -233,57 +233,57 @@ NetworkRecvStatus NetworkGameSocketHandler::ReceiveInvalidPacket(PacketGameType
return NETWORK_RECV_STATUS_MALFORMED_PACKET; return NETWORK_RECV_STATUS_MALFORMED_PACKET;
} }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_FULL(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_FULL); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_FULL(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_FULL); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_BANNED(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_BANNED); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_BANNED(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_BANNED); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_JOIN); } NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet &p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_JOIN); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_ERROR(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_ERROR); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_ERROR(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_ERROR); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_GAME_INFO(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_GAME_INFO); } NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_GAME_INFO(Packet &p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_GAME_INFO); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_GAME_INFO(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_GAME_INFO); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_GAME_INFO(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_GAME_INFO); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_GAME_INFO_EXTENDED(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_GAME_INFO_EXTENDED); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_GAME_INFO_EXTENDED(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_GAME_INFO_EXTENDED); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_CLIENT_INFO(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_CLIENT_INFO); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_CLIENT_INFO(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_CLIENT_INFO); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_NEED_GAME_PASSWORD(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_NEED_GAME_PASSWORD); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_NEED_GAME_PASSWORD(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_NEED_GAME_PASSWORD); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_NEED_COMPANY_PASSWORD(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_NEED_COMPANY_PASSWORD); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_NEED_COMPANY_PASSWORD(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_NEED_COMPANY_PASSWORD); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_GAME_PASSWORD(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_GAME_PASSWORD); } NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_GAME_PASSWORD(Packet &p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_GAME_PASSWORD); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_COMPANY_PASSWORD(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_COMPANY_PASSWORD); } NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_COMPANY_PASSWORD(Packet &p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_COMPANY_PASSWORD); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_SETTINGS_PASSWORD(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_SETTINGS_PASSWORD); } NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_SETTINGS_PASSWORD(Packet &p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_SETTINGS_PASSWORD); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_SETTINGS_ACCESS(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_SETTINGS_ACCESS); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_SETTINGS_ACCESS(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_SETTINGS_ACCESS); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_WELCOME(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_WELCOME); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_WELCOME(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_WELCOME); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_GETMAP(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_GETMAP); } NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_GETMAP(Packet &p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_GETMAP); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_WAIT(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_WAIT); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_WAIT(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_WAIT); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_MAP_BEGIN(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_MAP_BEGIN); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_MAP_BEGIN(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_MAP_BEGIN); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_MAP_SIZE(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_MAP_SIZE); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_MAP_SIZE(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_MAP_SIZE); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_MAP_DATA(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_MAP_DATA); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_MAP_DATA(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_MAP_DATA); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_MAP_DONE(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_MAP_DONE); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_MAP_DONE(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_MAP_DONE); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_MAP_OK(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_MAP_OK); } NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_MAP_OK(Packet &p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_MAP_OK); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_JOIN(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_JOIN); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_JOIN(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_JOIN); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_FRAME(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_FRAME); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_FRAME(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_FRAME); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_SYNC(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_SYNC); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_SYNC(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_SYNC); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_ACK(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_ACK); } NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_ACK(Packet &p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_ACK); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_COMMAND(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_COMMAND); } NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_COMMAND(Packet &p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_COMMAND); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_COMMAND(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_COMMAND); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_COMMAND(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_COMMAND); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_CHAT(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_CHAT); } NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_CHAT(Packet &p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_CHAT); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_CHAT(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_CHAT); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_CHAT(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_CHAT); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_EXTERNAL_CHAT(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_EXTERNAL_CHAT); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_EXTERNAL_CHAT(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_EXTERNAL_CHAT); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_SET_PASSWORD(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_SET_PASSWORD); } NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_SET_PASSWORD(Packet &p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_SET_PASSWORD); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_SET_NAME(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_SET_NAME); } NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_SET_NAME(Packet &p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_SET_NAME); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_QUIT(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_QUIT); } NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_QUIT(Packet &p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_QUIT); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_ERROR(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_ERROR); } NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_ERROR(Packet &p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_ERROR); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_DESYNC_LOG(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_DESYNC_LOG); } NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_DESYNC_LOG(Packet &p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_DESYNC_LOG); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_DESYNC_LOG(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_DESYNC_LOG); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_DESYNC_LOG(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_DESYNC_LOG); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_DESYNC_MSG(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_DESYNC_LOG); } NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_DESYNC_MSG(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_DESYNC_LOG); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_DESYNC_SYNC_DATA(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_DESYNC_SYNC_DATA); } NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_DESYNC_SYNC_DATA(Packet &p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_DESYNC_SYNC_DATA); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_QUIT(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_QUIT); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_QUIT(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_QUIT); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_ERROR_QUIT(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_ERROR_QUIT); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_ERROR_QUIT(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_ERROR_QUIT); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_SHUTDOWN(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_SHUTDOWN); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_SHUTDOWN(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_SHUTDOWN); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_NEWGAME(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_NEWGAME); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_NEWGAME(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_NEWGAME); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_RCON(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_RCON); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_RCON(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_RCON); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_RCON(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_RCON); } NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_RCON(Packet &p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_RCON); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_CHECK_NEWGRFS(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_CHECK_NEWGRFS); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_CHECK_NEWGRFS(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_CHECK_NEWGRFS); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_NEWGRFS_CHECKED(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_NEWGRFS_CHECKED); } NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_NEWGRFS_CHECKED(Packet &p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_NEWGRFS_CHECKED); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_MOVE(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_MOVE); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_MOVE(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_MOVE); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_MOVE(Packet *p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_MOVE); } NetworkRecvStatus NetworkGameSocketHandler::Receive_CLIENT_MOVE(Packet &p) { return this->ReceiveInvalidPacket(PACKET_CLIENT_MOVE); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_COMPANY_UPDATE(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_COMPANY_UPDATE); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_COMPANY_UPDATE(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_COMPANY_UPDATE); }
NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_CONFIG_UPDATE(Packet *p) { return this->ReceiveInvalidPacket(PACKET_SERVER_CONFIG_UPDATE); } NetworkRecvStatus NetworkGameSocketHandler::Receive_SERVER_CONFIG_UPDATE(Packet &p) { return this->ReceiveInvalidPacket(PACKET_SERVER_CONFIG_UPDATE); }
std::string NetworkGameSocketHandler::GetDebugInfo() const { return ""; } std::string NetworkGameSocketHandler::GetDebugInfo() const { return ""; }

@ -16,6 +16,7 @@
#include "tcp.h" #include "tcp.h"
#include "../network_type.h" #include "../network_type.h"
#include "../../core/pool_type.hpp" #include "../../core/pool_type.hpp"
#include "../../core/ring_buffer.hpp"
#include <memory> #include <memory>
#include <chrono> #include <chrono>
@ -23,7 +24,7 @@
* Enum with all types of TCP packets. * Enum with all types of TCP packets.
* For the exact meaning, look at #NetworkGameSocketHandler. * For the exact meaning, look at #NetworkGameSocketHandler.
*/ */
enum PacketGameType { enum PacketGameType : uint8_t {
/* /*
* These first four pair of packets (thus eight in * These first four pair of packets (thus eight in
* total) must remain in this order for backward * total) must remain in this order for backward
@ -142,27 +143,12 @@ const char *GetPacketTypeName(PacketGameType type);
/** Packet that wraps a command */ /** Packet that wraps a command */
struct CommandPacket; struct CommandPacket;
/** A queue of CommandPackets. */ /**
class CommandQueue { * A "queue" of CommandPackets.
CommandPacket *first; ///< The first packet in the queue. * Not a std::queue because, when paused, some commands remain on the queue.
CommandPacket *last; ///< The last packet in the queue; only valid when first != nullptr. * In other words, you do not always pop the first element from this queue.
uint count; ///< The number of items in the queue. */
using CommandQueue = ring_buffer<CommandPacket>;
void Append(CommandPacket *p, bool move);
public:
/** Initialise the command queue. */
CommandQueue() : first(nullptr), last(nullptr), count(0) {}
/** Clear the command queue. */
~CommandQueue() { this->Free(); }
void Append(CommandPacket &p) { this->Append(&p, false); }
void Append(CommandPacket &&p) { this->Append(&p, true); }
std::unique_ptr<CommandPacket> Pop(bool ignore_paused = false);
CommandPacket *Peek(bool ignore_paused = false);
void Free();
/** Get the number of items in the queue. */
uint Count() const { return this->count; }
};
/** Base socket handler for all TCP sockets */ /** Base socket handler for all TCP sockets */
class NetworkGameSocketHandler : public NetworkTCPSocketHandler { class NetworkGameSocketHandler : public NetworkTCPSocketHandler {
@ -179,13 +165,13 @@ protected:
* Notification that the server is full. * Notification that the server is full.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_FULL(Packet *p); virtual NetworkRecvStatus Receive_SERVER_FULL(Packet &p);
/** /**
* Notification that the client trying to join is banned. * Notification that the client trying to join is banned.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_BANNED(Packet *p); virtual NetworkRecvStatus Receive_SERVER_BANNED(Packet &p);
/** /**
* Try to join the server: * Try to join the server:
@ -195,34 +181,34 @@ protected:
* uint8_t ID of the clients Language. * uint8_t ID of the clients Language.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_CLIENT_JOIN(Packet *p); virtual NetworkRecvStatus Receive_CLIENT_JOIN(Packet &p);
/** /**
* The client made an error: * The client made an error:
* uint8_t Error code caused (see NetworkErrorCode). * uint8_t Error code caused (see NetworkErrorCode).
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_ERROR(Packet *p); virtual NetworkRecvStatus Receive_SERVER_ERROR(Packet &p);
/** /**
* Request game information. * Request game information.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_CLIENT_GAME_INFO(Packet *p); virtual NetworkRecvStatus Receive_CLIENT_GAME_INFO(Packet &p);
/** /**
* Sends information about the game. * Sends information about the game.
* Serialized NetworkGameInfo. See game_info.h for details. * Serialized NetworkGameInfo. See game_info.h for details.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_GAME_INFO(Packet *p); virtual NetworkRecvStatus Receive_SERVER_GAME_INFO(Packet &p);
/** /**
* Sends information about the game (extended). * Sends information about the game (extended).
* Serialized NetworkGameInfo. See game_info.h for details. * Serialized NetworkGameInfo. See game_info.h for details.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_GAME_INFO_EXTENDED(Packet *p); virtual NetworkRecvStatus Receive_SERVER_GAME_INFO_EXTENDED(Packet &p);
/** /**
* Send information about a client: * Send information about a client:
@ -231,13 +217,13 @@ protected:
* string Name of the client. * string Name of the client.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_CLIENT_INFO(Packet *p); virtual NetworkRecvStatus Receive_SERVER_CLIENT_INFO(Packet &p);
/** /**
* Indication to the client that the server needs a game password. * Indication to the client that the server needs a game password.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_NEED_GAME_PASSWORD(Packet *p); virtual NetworkRecvStatus Receive_SERVER_NEED_GAME_PASSWORD(Packet &p);
/** /**
* Indication to the client that the server needs a company password: * Indication to the client that the server needs a company password:
@ -245,7 +231,7 @@ protected:
* string Network ID of the server. * string Network ID of the server.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_NEED_COMPANY_PASSWORD(Packet *p); virtual NetworkRecvStatus Receive_SERVER_NEED_COMPANY_PASSWORD(Packet &p);
/** /**
* Send a password to the server to authorize: * Send a password to the server to authorize:
@ -253,7 +239,7 @@ protected:
* string The password. * string The password.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_CLIENT_GAME_PASSWORD(Packet *p); virtual NetworkRecvStatus Receive_CLIENT_GAME_PASSWORD(Packet &p);
/** /**
* Send a password to the server to authorize * Send a password to the server to authorize
@ -261,7 +247,7 @@ protected:
* string The password. * string The password.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_CLIENT_COMPANY_PASSWORD(Packet *p); virtual NetworkRecvStatus Receive_CLIENT_COMPANY_PASSWORD(Packet &p);
/** /**
* Send a password to the server to authorize * Send a password to the server to authorize
@ -269,14 +255,14 @@ protected:
* string The password. * string The password.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_CLIENT_SETTINGS_PASSWORD(Packet *p); virtual NetworkRecvStatus Receive_CLIENT_SETTINGS_PASSWORD(Packet &p);
/** /**
* Indication to the client that the setting access state has changed * Indication to the client that the setting access state has changed
* bool setting access state * bool setting access state
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_SETTINGS_ACCESS(Packet *p); virtual NetworkRecvStatus Receive_SERVER_SETTINGS_ACCESS(Packet &p);
/** /**
* The client is joined and ready to receive their map: * The client is joined and ready to receive their map:
@ -285,61 +271,61 @@ protected:
* string Network ID of the server. * string Network ID of the server.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_WELCOME(Packet *p); virtual NetworkRecvStatus Receive_SERVER_WELCOME(Packet &p);
/** /**
* Request the map from the server. * Request the map from the server.
* uint32_t NewGRF version (release versions of OpenTTD only). * uint32_t NewGRF version (release versions of OpenTTD only).
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_CLIENT_GETMAP(Packet *p); virtual NetworkRecvStatus Receive_CLIENT_GETMAP(Packet &p);
/** /**
* Notification that another client is currently receiving the map: * Notification that another client is currently receiving the map:
* uint8_t Number of clients waiting in front of you. * uint8_t Number of clients waiting in front of you.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_WAIT(Packet *p); virtual NetworkRecvStatus Receive_SERVER_WAIT(Packet &p);
/** /**
* Sends that the server will begin with sending the map to the client: * Sends that the server will begin with sending the map to the client:
* uint32_t Current frame. * uint32_t Current frame.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_MAP_BEGIN(Packet *p); virtual NetworkRecvStatus Receive_SERVER_MAP_BEGIN(Packet &p);
/** /**
* Sends the size of the map to the client. * Sends the size of the map to the client.
* uint32_t Size of the (compressed) map (in bytes). * uint32_t Size of the (compressed) map (in bytes).
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_MAP_SIZE(Packet *p); virtual NetworkRecvStatus Receive_SERVER_MAP_SIZE(Packet &p);
/** /**
* Sends the data of the map to the client: * Sends the data of the map to the client:
* Contains a part of the map (until max size of packet). * Contains a part of the map (until max size of packet).
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_MAP_DATA(Packet *p); virtual NetworkRecvStatus Receive_SERVER_MAP_DATA(Packet &p);
/** /**
* Sends that all data of the map are sent to the client: * Sends that all data of the map are sent to the client:
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_MAP_DONE(Packet *p); virtual NetworkRecvStatus Receive_SERVER_MAP_DONE(Packet &p);
/** /**
* Tell the server that we are done receiving/loading the map. * Tell the server that we are done receiving/loading the map.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_CLIENT_MAP_OK(Packet *p); virtual NetworkRecvStatus Receive_CLIENT_MAP_OK(Packet &p);
/** /**
* A client joined (PACKET_CLIENT_MAP_OK), what usually directly follows is a PACKET_SERVER_CLIENT_INFO: * A client joined (PACKET_CLIENT_MAP_OK), what usually directly follows is a PACKET_SERVER_CLIENT_INFO:
* uint32_t ID of the client that just joined the game. * uint32_t ID of the client that just joined the game.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_JOIN(Packet *p); virtual NetworkRecvStatus Receive_SERVER_JOIN(Packet &p);
/** /**
* Sends the current frame counter to the client: * Sends the current frame counter to the client:
@ -350,7 +336,7 @@ protected:
* uint8_t Random token to validate the client is actually listening (only occasionally present). * uint8_t Random token to validate the client is actually listening (only occasionally present).
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_FRAME(Packet *p); virtual NetworkRecvStatus Receive_SERVER_FRAME(Packet &p);
/** /**
* Sends a sync-check to the client: * Sends a sync-check to the client:
@ -359,7 +345,7 @@ protected:
* uint32_t General seed 2 (dependent on compile settings, not default). * uint32_t General seed 2 (dependent on compile settings, not default).
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_SYNC(Packet *p); virtual NetworkRecvStatus Receive_SERVER_SYNC(Packet &p);
/** /**
* Tell the server we are done with this frame: * Tell the server we are done with this frame:
@ -367,7 +353,7 @@ protected:
* uint8_t The random token that the server sent in the PACKET_SERVER_FRAME packet. * uint8_t The random token that the server sent in the PACKET_SERVER_FRAME packet.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_CLIENT_ACK(Packet *p); virtual NetworkRecvStatus Receive_CLIENT_ACK(Packet &p);
/** /**
* Send a DoCommand to the Server: * Send a DoCommand to the Server:
@ -380,7 +366,7 @@ protected:
* uint8_t ID of the callback. * uint8_t ID of the callback.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_CLIENT_COMMAND(Packet *p); virtual NetworkRecvStatus Receive_CLIENT_COMMAND(Packet &p);
/** /**
* Sends a DoCommand to the client: * Sends a DoCommand to the client:
@ -394,7 +380,7 @@ protected:
* uint32_t Frame of execution. * uint32_t Frame of execution.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_COMMAND(Packet *p); virtual NetworkRecvStatus Receive_SERVER_COMMAND(Packet &p);
/** /**
* Sends a chat-packet to the server: * Sends a chat-packet to the server:
@ -405,7 +391,7 @@ protected:
* uint64_t data (used e.g. for 'give money' actions). * uint64_t data (used e.g. for 'give money' actions).
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_CLIENT_CHAT(Packet *p); virtual NetworkRecvStatus Receive_CLIENT_CHAT(Packet &p);
/** /**
* Sends a chat-packet to the client: * Sends a chat-packet to the client:
@ -415,7 +401,7 @@ protected:
* uint64_t data (used e.g. for 'give money' actions). * uint64_t data (used e.g. for 'give money' actions).
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_CHAT(Packet *p); virtual NetworkRecvStatus Receive_SERVER_CHAT(Packet &p);
/** /**
* Sends a chat-packet for external source to the client: * Sends a chat-packet for external source to the client:
@ -425,45 +411,45 @@ protected:
* string Message (max NETWORK_CHAT_LENGTH). * string Message (max NETWORK_CHAT_LENGTH).
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_EXTERNAL_CHAT(Packet *p); virtual NetworkRecvStatus Receive_SERVER_EXTERNAL_CHAT(Packet &p);
/** /**
* Set the password for the clients current company: * Set the password for the clients current company:
* string The password. * string The password.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_CLIENT_SET_PASSWORD(Packet *p); virtual NetworkRecvStatus Receive_CLIENT_SET_PASSWORD(Packet &p);
/** /**
* Gives the client a new name: * Gives the client a new name:
* string New name of the client. * string New name of the client.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_CLIENT_SET_NAME(Packet *p); virtual NetworkRecvStatus Receive_CLIENT_SET_NAME(Packet &p);
/** /**
* The client is quitting the game. * The client is quitting the game.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_CLIENT_QUIT(Packet *p); virtual NetworkRecvStatus Receive_CLIENT_QUIT(Packet &p);
/** /**
* The client made an error and is quitting the game. * The client made an error and is quitting the game.
* uint8_t Error of the code caused (see NetworkErrorCode). * uint8_t Error of the code caused (see NetworkErrorCode).
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_CLIENT_ERROR(Packet *p); virtual NetworkRecvStatus Receive_CLIENT_ERROR(Packet &p);
virtual NetworkRecvStatus Receive_CLIENT_DESYNC_LOG(Packet *p); virtual NetworkRecvStatus Receive_CLIENT_DESYNC_LOG(Packet &p);
virtual NetworkRecvStatus Receive_SERVER_DESYNC_LOG(Packet *p); virtual NetworkRecvStatus Receive_SERVER_DESYNC_LOG(Packet &p);
virtual NetworkRecvStatus Receive_CLIENT_DESYNC_MSG(Packet *p); virtual NetworkRecvStatus Receive_CLIENT_DESYNC_MSG(Packet &p);
virtual NetworkRecvStatus Receive_CLIENT_DESYNC_SYNC_DATA(Packet *p); virtual NetworkRecvStatus Receive_CLIENT_DESYNC_SYNC_DATA(Packet &p);
/** /**
* Notification that a client left the game: * Notification that a client left the game:
* uint32_t ID of the client. * uint32_t ID of the client.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_QUIT(Packet *p); virtual NetworkRecvStatus Receive_SERVER_QUIT(Packet &p);
/** /**
* Inform all clients that one client made an error and thus has quit/been disconnected: * Inform all clients that one client made an error and thus has quit/been disconnected:
@ -471,19 +457,19 @@ protected:
* uint8_t Code of the error caused (see NetworkErrorCode). * uint8_t Code of the error caused (see NetworkErrorCode).
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_ERROR_QUIT(Packet *p); virtual NetworkRecvStatus Receive_SERVER_ERROR_QUIT(Packet &p);
/** /**
* Let the clients know that the server is closing. * Let the clients know that the server is closing.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_SHUTDOWN(Packet *p); virtual NetworkRecvStatus Receive_SERVER_SHUTDOWN(Packet &p);
/** /**
* Let the clients know that the server is loading a new map. * Let the clients know that the server is loading a new map.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_NEWGAME(Packet *p); virtual NetworkRecvStatus Receive_SERVER_NEWGAME(Packet &p);
/** /**
* Send the result of an issues RCon command back to the client: * Send the result of an issues RCon command back to the client:
@ -491,7 +477,7 @@ protected:
* string Output of the RCon command * string Output of the RCon command
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_RCON(Packet *p); virtual NetworkRecvStatus Receive_SERVER_RCON(Packet &p);
/** /**
* Send an RCon command to the server: * Send an RCon command to the server:
@ -499,7 +485,7 @@ protected:
* string Command to be executed. * string Command to be executed.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_CLIENT_RCON(Packet *p); virtual NetworkRecvStatus Receive_CLIENT_RCON(Packet &p);
/** /**
* Sends information about all used GRFs to the client: * Sends information about all used GRFs to the client:
@ -508,13 +494,13 @@ protected:
* 16 * uint8_t MD5 checksum of the GRF * 16 * uint8_t MD5 checksum of the GRF
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_CHECK_NEWGRFS(Packet *p); virtual NetworkRecvStatus Receive_SERVER_CHECK_NEWGRFS(Packet &p);
/** /**
* Tell the server that we have the required GRFs * Tell the server that we have the required GRFs
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_CLIENT_NEWGRFS_CHECKED(Packet *p); virtual NetworkRecvStatus Receive_CLIENT_NEWGRFS_CHECKED(Packet &p);
/** /**
* Move a client from one company into another: * Move a client from one company into another:
@ -522,7 +508,7 @@ protected:
* uint8_t ID of the new company. * uint8_t ID of the new company.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_MOVE(Packet *p); virtual NetworkRecvStatus Receive_SERVER_MOVE(Packet &p);
/** /**
* Request the server to move this client into another company: * Request the server to move this client into another company:
@ -530,14 +516,14 @@ protected:
* string Password, if the company is password protected. * string Password, if the company is password protected.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_CLIENT_MOVE(Packet *p); virtual NetworkRecvStatus Receive_CLIENT_MOVE(Packet &p);
/** /**
* Update the clients knowledge of which company is password protected: * Update the clients knowledge of which company is password protected:
* uint16_t Bitwise representation of each company * uint16_t Bitwise representation of each company
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_COMPANY_UPDATE(Packet *p); virtual NetworkRecvStatus Receive_SERVER_COMPANY_UPDATE(Packet &p);
/** /**
* Update the clients knowledge of the max settings: * Update the clients knowledge of the max settings:
@ -545,9 +531,9 @@ protected:
* uint8_t Maximum number of spectators allowed. * uint8_t Maximum number of spectators allowed.
* @param p The packet that was just received. * @param p The packet that was just received.
*/ */
virtual NetworkRecvStatus Receive_SERVER_CONFIG_UPDATE(Packet *p); virtual NetworkRecvStatus Receive_SERVER_CONFIG_UPDATE(Packet &p);
NetworkRecvStatus HandlePacket(Packet *p); NetworkRecvStatus HandlePacket(Packet &p);
NetworkGameSocketHandler(SOCKET s); NetworkGameSocketHandler(SOCKET s);
public: public:
@ -588,8 +574,8 @@ public:
NetworkRecvStatus ReceivePackets(); NetworkRecvStatus ReceivePackets();
const char *ReceiveCommand(Packet *p, CommandPacket *cp); const char *ReceiveCommand(Packet &p, CommandPacket &cp);
void SendCommand(Packet *p, const CommandPacket *cp); void SendCommand(Packet &p, const CommandPacket &cp);
virtual std::string GetDebugInfo() const; virtual std::string GetDebugInfo() const;
virtual void LogSentPacket(const Packet &pkt) override; virtual void LogSentPacket(const Packet &pkt) override;

@ -26,4 +26,4 @@ bool NetworkStunSocketHandler::ReceiveInvalidPacket(PacketStunType type)
return false; return false;
} }
bool NetworkStunSocketHandler::Receive_SERCLI_STUN(Packet *) { return this->ReceiveInvalidPacket(PACKET_STUN_SERCLI_STUN); } bool NetworkStunSocketHandler::Receive_SERCLI_STUN(Packet &) { return this->ReceiveInvalidPacket(PACKET_STUN_SERCLI_STUN); }

@ -17,7 +17,7 @@
#include "packet.h" #include "packet.h"
/** Enum with all types of TCP STUN packets. The order MUST not be changed. **/ /** Enum with all types of TCP STUN packets. The order MUST not be changed. **/
enum PacketStunType { enum PacketStunType : uint8_t {
PACKET_STUN_SERCLI_STUN, ///< Send a STUN request to the STUN server. PACKET_STUN_SERCLI_STUN, ///< Send a STUN request to the STUN server.
PACKET_STUN_END, ///< Must ALWAYS be on the end of this list!! (period) PACKET_STUN_END, ///< Must ALWAYS be on the end of this list!! (period)
}; };
@ -39,7 +39,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_SERCLI_STUN(Packet *p); virtual bool Receive_SERCLI_STUN(Packet &p);
public: public:
/** /**

@ -22,9 +22,9 @@
* @param p the packet to handle * @param p the packet to handle
* @return true if we should immediately handle further packets, false otherwise * @return true if we should immediately handle further packets, false otherwise
*/ */
bool NetworkTurnSocketHandler::HandlePacket(Packet *p) bool NetworkTurnSocketHandler::HandlePacket(Packet &p)
{ {
PacketTurnType type = (PacketTurnType)p->Recv_uint8(); PacketTurnType type = (PacketTurnType)p.Recv_uint8();
switch (type) { switch (type) {
case PACKET_TURN_TURN_ERROR: return this->Receive_TURN_ERROR(p); case PACKET_TURN_TURN_ERROR: return this->Receive_TURN_ERROR(p);
@ -47,7 +47,7 @@ bool NetworkTurnSocketHandler::ReceivePackets()
static const int MAX_PACKETS_TO_RECEIVE = 4; static const int MAX_PACKETS_TO_RECEIVE = 4;
int i = MAX_PACKETS_TO_RECEIVE; int i = MAX_PACKETS_TO_RECEIVE;
while (--i != 0 && (p = this->ReceivePacket()) != nullptr) { while (--i != 0 && (p = this->ReceivePacket()) != nullptr) {
bool cont = this->HandlePacket(p.get()); bool cont = this->HandlePacket(*p);
if (!cont) return true; if (!cont) return true;
} }
@ -65,6 +65,6 @@ bool NetworkTurnSocketHandler::ReceiveInvalidPacket(PacketTurnType type)
return false; return false;
} }
bool NetworkTurnSocketHandler::Receive_TURN_ERROR(Packet *) { return this->ReceiveInvalidPacket(PACKET_TURN_TURN_ERROR); } bool NetworkTurnSocketHandler::Receive_TURN_ERROR(Packet &) { return this->ReceiveInvalidPacket(PACKET_TURN_TURN_ERROR); }
bool NetworkTurnSocketHandler::Receive_SERCLI_CONNECT(Packet *) { return this->ReceiveInvalidPacket(PACKET_TURN_SERCLI_CONNECT); } bool NetworkTurnSocketHandler::Receive_SERCLI_CONNECT(Packet &) { return this->ReceiveInvalidPacket(PACKET_TURN_SERCLI_CONNECT); }
bool NetworkTurnSocketHandler::Receive_TURN_CONNECTED(Packet *) { return this->ReceiveInvalidPacket(PACKET_TURN_TURN_CONNECTED); } bool NetworkTurnSocketHandler::Receive_TURN_CONNECTED(Packet &) { return this->ReceiveInvalidPacket(PACKET_TURN_TURN_CONNECTED); }

@ -18,7 +18,7 @@
#include "network_game_info.h" #include "network_game_info.h"
/** Enum with all types of TCP TURN packets. The order MUST not be changed. **/ /** Enum with all types of TCP TURN packets. The order MUST not be changed. **/
enum PacketTurnType { enum PacketTurnType : uint8_t {
PACKET_TURN_TURN_ERROR, ///< TURN server is unable to relay. PACKET_TURN_TURN_ERROR, ///< TURN server is unable to relay.
PACKET_TURN_SERCLI_CONNECT, ///< Client or server is connecting to the TURN server. PACKET_TURN_SERCLI_CONNECT, ///< Client or server is connecting to the TURN server.
PACKET_TURN_TURN_CONNECTED, ///< TURN server indicates the socket is now being relayed. PACKET_TURN_TURN_CONNECTED, ///< TURN server indicates the socket is now being relayed.
@ -38,7 +38,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_TURN_ERROR(Packet *p); virtual bool Receive_TURN_ERROR(Packet &p);
/** /**
* Client or servers wants to connect to the TURN server (on request by * Client or servers wants to connect to the TURN server (on request by
@ -50,7 +50,7 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_SERCLI_CONNECT(Packet *p); virtual bool Receive_SERCLI_CONNECT(Packet &p);
/** /**
* TURN server has connected client and server together and will now relay * TURN server has connected client and server together and will now relay
@ -62,9 +62,9 @@ protected:
* @param p The packet that was just received. * @param p The packet that was just received.
* @return True upon success, otherwise false. * @return True upon success, otherwise false.
*/ */
virtual bool Receive_TURN_CONNECTED(Packet *p); virtual bool Receive_TURN_CONNECTED(Packet &p);
bool HandlePacket(Packet *p); bool HandlePacket(Packet &p);
public: public:
/** /**
* Create a new cs socket handler for a given cs. * Create a new cs socket handler for a given cs.

@ -73,19 +73,19 @@ void NetworkUDPSocketHandler::CloseSocket()
* @param all send the packet using all sockets that can send it * @param all send the packet using all sockets that can send it
* @param broadcast whether to send a broadcast message * @param broadcast whether to send a broadcast message
*/ */
void NetworkUDPSocketHandler::SendPacket(Packet *p, NetworkAddress *recv, bool all, bool broadcast, bool short_mtu) void NetworkUDPSocketHandler::SendPacket(Packet &p, NetworkAddress &recv, bool all, bool broadcast, bool short_mtu)
{ {
if (this->sockets.empty()) this->Listen(); if (this->sockets.empty()) this->Listen();
const uint MTU = short_mtu ? UDP_MTU_SHORT : UDP_MTU; const uint MTU = short_mtu ? UDP_MTU_SHORT : UDP_MTU;
if (p->Size() > MTU) { if (p.Size() > MTU) {
p->PrepareToSend(); p.PrepareToSend();
uint64_t token = this->fragment_token++; uint64_t token = this->fragment_token++;
const uint PAYLOAD_MTU = MTU - (1 + 2 + 8 + 1 + 1 + 2); const uint PAYLOAD_MTU = MTU - (1 + 2 + 8 + 1 + 1 + 2);
const size_t packet_size = p->Size(); const size_t packet_size = p.Size();
const uint8_t frag_count = (uint8_t)((packet_size + PAYLOAD_MTU - 1) / PAYLOAD_MTU); const uint8_t frag_count = (uint8_t)((packet_size + PAYLOAD_MTU - 1) / PAYLOAD_MTU);
Packet frag(PACKET_UDP_EX_MULTI); Packet frag(PACKET_UDP_EX_MULTI);
@ -97,10 +97,10 @@ void NetworkUDPSocketHandler::SendPacket(Packet *p, NetworkAddress *recv, bool a
frag.Send_uint8(current_frag); frag.Send_uint8(current_frag);
frag.Send_uint8(frag_count); frag.Send_uint8(frag_count);
frag.Send_uint16(payload_size); frag.Send_uint16(payload_size);
frag.Send_binary(p->GetBufferData() + offset, payload_size); frag.Send_binary(p.GetBufferData() + offset, payload_size);
current_frag++; current_frag++;
offset += payload_size; offset += payload_size;
this->SendPacket(&frag, recv, all, broadcast, short_mtu); this->SendPacket(frag, recv, all, broadcast, short_mtu);
frag.ResetState(PACKET_UDP_EX_MULTI); frag.ResetState(PACKET_UDP_EX_MULTI);
} }
assert_msg(current_frag == frag_count, "%u, %u", current_frag, frag_count); assert_msg(current_frag == frag_count, "%u, %u", current_frag, frag_count);
@ -110,12 +110,12 @@ void NetworkUDPSocketHandler::SendPacket(Packet *p, NetworkAddress *recv, bool a
for (auto &s : this->sockets) { for (auto &s : this->sockets) {
/* Make a local copy because if we resolve it we cannot /* Make a local copy because if we resolve it we cannot
* easily unresolve it so we can resolve it later again. */ * easily unresolve it so we can resolve it later again. */
NetworkAddress send(*recv); NetworkAddress send(recv);
/* Not the same type */ /* Not the same type */
if (!send.IsFamily(s.second.GetAddress()->ss_family)) continue; if (!send.IsFamily(s.second.GetAddress()->ss_family)) continue;
p->PrepareToSend(); p.PrepareToSend();
if (broadcast) { if (broadcast) {
/* Enable broadcast */ /* Enable broadcast */
@ -126,7 +126,7 @@ void NetworkUDPSocketHandler::SendPacket(Packet *p, NetworkAddress *recv, bool a
} }
/* Send the buffer */ /* Send the buffer */
ssize_t res = p->TransferOut<int>(sendto, s.first, 0, (const struct sockaddr *)send.GetAddress(), send.GetAddressLength()); ssize_t res = p.TransferOut<int>(sendto, s.first, 0, (const struct sockaddr *)send.GetAddress(), send.GetAddressLength());
DEBUG(net, 7, "sendto(%s)", NetworkAddressDumper().GetAddressAsString(&send)); DEBUG(net, 7, "sendto(%s)", NetworkAddressDumper().GetAddressAsString(&send));
/* Check for any errors, but ignore it otherwise */ /* Check for any errors, but ignore it otherwise */
@ -172,7 +172,7 @@ void NetworkUDPSocketHandler::ReceivePackets()
p.PrepareToRead(); p.PrepareToRead();
/* Handle the packet */ /* Handle the packet */
this->HandleUDPPacket(&p, &address); this->HandleUDPPacket(p, address);
} }
} }
} }
@ -182,14 +182,14 @@ void NetworkUDPSocketHandler::ReceivePackets()
* @param p the received packet * @param p the received packet
* @param client_addr the sender of the packet * @param client_addr the sender of the packet
*/ */
void NetworkUDPSocketHandler::HandleUDPPacket(Packet *p, NetworkAddress *client_addr) void NetworkUDPSocketHandler::HandleUDPPacket(Packet &p, NetworkAddress &client_addr)
{ {
PacketUDPType type; PacketUDPType type;
/* New packet == new client, which has not quit yet */ /* New packet == new client, which has not quit yet */
this->Reopen(); this->Reopen();
type = (PacketUDPType)p->Recv_uint8(); type = (PacketUDPType)p.Recv_uint8();
switch (this->HasClientQuit() ? PACKET_UDP_END : type) { switch (this->HasClientQuit() ? PACKET_UDP_END : type) {
case PACKET_UDP_CLIENT_FIND_SERVER: this->Receive_CLIENT_FIND_SERVER(p, client_addr); break; case PACKET_UDP_CLIENT_FIND_SERVER: this->Receive_CLIENT_FIND_SERVER(p, client_addr); break;
@ -208,23 +208,23 @@ void NetworkUDPSocketHandler::HandleUDPPacket(Packet *p, NetworkAddress *client_
} }
} }
void NetworkUDPSocketHandler::Receive_EX_MULTI(Packet *p, NetworkAddress *client_addr) void NetworkUDPSocketHandler::Receive_EX_MULTI(Packet &p, NetworkAddress &client_addr)
{ {
uint64_t token = p->Recv_uint64(); uint64_t token = p.Recv_uint64();
uint8_t index = p->Recv_uint8 (); uint8_t index = p.Recv_uint8 ();
uint8_t total = p->Recv_uint8 (); uint8_t total = p.Recv_uint8 ();
uint16_t payload_size = p->Recv_uint16(); uint16_t payload_size = p.Recv_uint16();
DEBUG(net, 6, "[udp] received multi-part packet from %s: " OTTD_PRINTFHEX64 ", %u/%u, %u bytes", DEBUG(net, 6, "[udp] received multi-part packet from %s: " OTTD_PRINTFHEX64 ", %u/%u, %u bytes",
NetworkAddressDumper().GetAddressAsString(client_addr), token, index, total, payload_size); NetworkAddressDumper().GetAddressAsString(client_addr), token, index, total, payload_size);
if (total == 0 || index >= total) return; if (total == 0 || index >= total) return;
if (!p->CanReadFromPacket(payload_size)) return; if (!p.CanReadFromPacket(payload_size)) return;
time_t cur_time = time(nullptr); time_t cur_time = time(nullptr);
auto add_to_fragment = [&](FragmentSet &fs) { auto add_to_fragment = [&](FragmentSet &fs) {
fs.fragments[index].assign((const char *) p->GetBufferData() + p->GetRawPos(), payload_size); fs.fragments[index].assign((const char *) p.GetBufferData() + p.GetRawPos(), payload_size);
uint total_payload = 0; uint total_payload = 0;
for (auto &frag : fs.fragments) { for (auto &frag : fs.fragments) {
@ -236,7 +236,7 @@ void NetworkUDPSocketHandler::Receive_EX_MULTI(Packet *p, NetworkAddress *client
DEBUG(net, 6, "[udp] merged multi-part packet from %s: " OTTD_PRINTFHEX64 ", %u bytes", DEBUG(net, 6, "[udp] merged multi-part packet from %s: " OTTD_PRINTFHEX64 ", %u bytes",
NetworkAddressDumper().GetAddressAsString(client_addr), token, total_payload); NetworkAddressDumper().GetAddressAsString(client_addr), token, total_payload);
Packet merged(this, SHRT_MAX, 0); Packet merged(this, TCP_MTU, 0);
merged.ReserveBuffer(total_payload); merged.ReserveBuffer(total_payload);
for (auto &frag : fs.fragments) { for (auto &frag : fs.fragments) {
merged.Send_binary((const byte *)frag.data(), frag.size()); merged.Send_binary((const byte *)frag.data(), frag.size());
@ -250,7 +250,7 @@ void NetworkUDPSocketHandler::Receive_EX_MULTI(Packet *p, NetworkAddress *client
DEBUG(net, 1, "received an extended packet with mismatching size from %s, (%u, %u)", DEBUG(net, 1, "received an extended packet with mismatching size from %s, (%u, %u)",
NetworkAddressDumper().GetAddressAsString(client_addr), (uint)total_payload, (uint)merged.ReadRawPacketSize()); NetworkAddressDumper().GetAddressAsString(client_addr), (uint)total_payload, (uint)merged.ReadRawPacketSize());
} else { } else {
this->HandleUDPPacket(&merged, client_addr); this->HandleUDPPacket(merged, client_addr);
} }
fs = this->fragments.back(); fs = this->fragments.back();
@ -266,14 +266,14 @@ void NetworkUDPSocketHandler::Receive_EX_MULTI(Packet *p, NetworkAddress *client
continue; continue;
} }
if (fs.token == token && fs.address == *client_addr && fs.fragments.size() == total) { if (fs.token == token && fs.address == client_addr && fs.fragments.size() == total) {
add_to_fragment(fs); add_to_fragment(fs);
return; return;
} }
i++; i++;
} }
this->fragments.push_back({ token, *client_addr, cur_time, {} }); this->fragments.push_back({ token, client_addr, cur_time, {} });
this->fragments.back().fragments.resize(total); this->fragments.back().fragments.resize(total);
add_to_fragment(this->fragments.back()); add_to_fragment(this->fragments.back());
} }
@ -283,11 +283,11 @@ void NetworkUDPSocketHandler::Receive_EX_MULTI(Packet *p, NetworkAddress *client
* @param type The received packet type. * @param type The received packet type.
* @param client_addr The address we received the packet from. * @param client_addr The address we received the packet from.
*/ */
void NetworkUDPSocketHandler::ReceiveInvalidPacket(PacketUDPType type, NetworkAddress *client_addr) void NetworkUDPSocketHandler::ReceiveInvalidPacket(PacketUDPType type, NetworkAddress &client_addr)
{ {
DEBUG(net, 0, "[udp] received packet type %d on wrong port from %s", type, NetworkAddressDumper().GetAddressAsString(client_addr)); DEBUG(net, 0, "[udp] received packet type %d on wrong port from %s", type, NetworkAddressDumper().GetAddressAsString(client_addr));
} }
void NetworkUDPSocketHandler::Receive_CLIENT_FIND_SERVER(Packet *p, NetworkAddress *client_addr) { this->ReceiveInvalidPacket(PACKET_UDP_CLIENT_FIND_SERVER, client_addr); } void NetworkUDPSocketHandler::Receive_CLIENT_FIND_SERVER(Packet &p, NetworkAddress &client_addr) { this->ReceiveInvalidPacket(PACKET_UDP_CLIENT_FIND_SERVER, client_addr); }
void NetworkUDPSocketHandler::Receive_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr) { this->ReceiveInvalidPacket(PACKET_UDP_SERVER_RESPONSE, client_addr); } void NetworkUDPSocketHandler::Receive_SERVER_RESPONSE(Packet &p, NetworkAddress &client_addr) { this->ReceiveInvalidPacket(PACKET_UDP_SERVER_RESPONSE, client_addr); }
void NetworkUDPSocketHandler::Receive_EX_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr) { this->ReceiveInvalidPacket(PACKET_UDP_EX_SERVER_RESPONSE, client_addr); } void NetworkUDPSocketHandler::Receive_EX_SERVER_RESPONSE(Packet &p, NetworkAddress &client_addr) { this->ReceiveInvalidPacket(PACKET_UDP_EX_SERVER_RESPONSE, client_addr); }

@ -20,7 +20,7 @@
#include <time.h> #include <time.h>
/** Enum with all types of UDP packets. The order MUST not be changed **/ /** Enum with all types of UDP packets. The order MUST not be changed **/
enum PacketUDPType { enum PacketUDPType : uint8_t {
PACKET_UDP_CLIENT_FIND_SERVER, ///< Queries a game server for game information 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_SERVER_RESPONSE, ///< Reply of the game server with game information
PACKET_UDP_END, ///< Must ALWAYS be the last non-extended item in the list!! (period) PACKET_UDP_END, ///< Must ALWAYS be the last non-extended item in the list!! (period)
@ -47,27 +47,27 @@ protected:
}; };
std::vector<FragmentSet> fragments; std::vector<FragmentSet> fragments;
void ReceiveInvalidPacket(PacketUDPType, NetworkAddress *client_addr); void ReceiveInvalidPacket(PacketUDPType, NetworkAddress &client_addr);
/** /**
* Queries to the server for information about the game. * Queries to the server for information about the game.
* @param p The received packet. * @param p The received packet.
* @param client_addr The origin of the packet. * @param client_addr The origin of the packet.
*/ */
virtual void Receive_CLIENT_FIND_SERVER(Packet *p, NetworkAddress *client_addr); virtual void Receive_CLIENT_FIND_SERVER(Packet &p, NetworkAddress &client_addr);
/** /**
* Response to a query letting the client know we are here. * Response to a query letting the client know we are here.
* @param p The received packet. * @param p The received packet.
* @param client_addr The origin of the packet. * @param client_addr The origin of the packet.
*/ */
virtual void Receive_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr); virtual void Receive_SERVER_RESPONSE(Packet &p, NetworkAddress &client_addr);
virtual void Receive_EX_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr); virtual void Receive_EX_SERVER_RESPONSE(Packet &p, NetworkAddress &client_addr);
void HandleUDPPacket(Packet *p, NetworkAddress *client_addr); void HandleUDPPacket(Packet &p, NetworkAddress &client_addr);
virtual void Receive_EX_MULTI(Packet *p, NetworkAddress *client_addr); virtual void Receive_EX_MULTI(Packet &p, NetworkAddress &client_addr);
public: public:
NetworkUDPSocketHandler(NetworkAddressList *bind = nullptr); NetworkUDPSocketHandler(NetworkAddressList *bind = nullptr);
@ -77,7 +77,7 @@ public:
bool Listen(); bool Listen();
void CloseSocket(); void CloseSocket();
void SendPacket(Packet *p, NetworkAddress *recv, bool all = false, bool broadcast = false, bool short_mtu = false); void SendPacket(Packet &p, NetworkAddress &recv, bool all = false, bool broadcast = false, bool short_mtu = false);
void ReceivePackets(); void ReceivePackets();
}; };

@ -135,10 +135,10 @@ ServerNetworkAdminSocketHandler::~ServerNetworkAdminSocketHandler()
*/ */
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendError(NetworkErrorCode error) NetworkRecvStatus ServerNetworkAdminSocketHandler::SendError(NetworkErrorCode error)
{ {
Packet *p = new Packet(ADMIN_PACKET_SERVER_ERROR); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_ERROR);
p->Send_uint8(error); p->Send_uint8(error);
this->SendPacket(p); this->SendPacket(std::move(p));
std::string error_message = GetString(GetNetworkErrorMsg(error)); std::string error_message = GetString(GetNetworkErrorMsg(error));
@ -150,7 +150,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendError(NetworkErrorCode er
/** Send the protocol version to the admin. */ /** Send the protocol version to the admin. */
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendProtocol() NetworkRecvStatus ServerNetworkAdminSocketHandler::SendProtocol()
{ {
Packet *p = new Packet(ADMIN_PACKET_SERVER_PROTOCOL); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_PROTOCOL);
/* announce the protocol version */ /* announce the protocol version */
p->Send_uint8(NETWORK_GAME_ADMIN_VERSION); p->Send_uint8(NETWORK_GAME_ADMIN_VERSION);
@ -162,7 +162,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendProtocol()
} }
p->Send_bool(false); p->Send_bool(false);
this->SendPacket(p); this->SendPacket(std::move(p));
return this->SendWelcome(); return this->SendWelcome();
} }
@ -170,7 +170,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendProtocol()
/** Send a welcome message to the admin. */ /** Send a welcome message to the admin. */
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendWelcome() NetworkRecvStatus ServerNetworkAdminSocketHandler::SendWelcome()
{ {
Packet *p = new Packet(ADMIN_PACKET_SERVER_WELCOME); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_WELCOME);
p->Send_string(_settings_client.network.server_name); p->Send_string(_settings_client.network.server_name);
p->Send_string(_openttd_revision); p->Send_string(_openttd_revision);
@ -183,7 +183,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendWelcome()
p->Send_uint16(MapSizeX()); p->Send_uint16(MapSizeX());
p->Send_uint16(MapSizeY()); p->Send_uint16(MapSizeY());
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -191,26 +191,26 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendWelcome()
/** Tell the admin we started a new game. */ /** Tell the admin we started a new game. */
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendNewGame() NetworkRecvStatus ServerNetworkAdminSocketHandler::SendNewGame()
{ {
Packet *p = new Packet(ADMIN_PACKET_SERVER_NEWGAME); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_NEWGAME);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
/** Tell the admin we're shutting down. */ /** Tell the admin we're shutting down. */
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendShutdown() NetworkRecvStatus ServerNetworkAdminSocketHandler::SendShutdown()
{ {
Packet *p = new Packet(ADMIN_PACKET_SERVER_SHUTDOWN); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_SHUTDOWN);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
/** Tell the admin the date. */ /** Tell the admin the date. */
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendDate() NetworkRecvStatus ServerNetworkAdminSocketHandler::SendDate()
{ {
Packet *p = new Packet(ADMIN_PACKET_SERVER_DATE); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_DATE);
p->Send_uint32(CalTime::CurDate().base()); p->Send_uint32(CalTime::CurDate().base());
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -221,10 +221,10 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendDate()
*/ */
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendClientJoin(ClientID client_id) NetworkRecvStatus ServerNetworkAdminSocketHandler::SendClientJoin(ClientID client_id)
{ {
Packet *p = new Packet(ADMIN_PACKET_SERVER_CLIENT_JOIN); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_CLIENT_JOIN);
p->Send_uint32(client_id); p->Send_uint32(client_id);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -239,7 +239,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendClientInfo(const NetworkC
/* Only send data when we're a proper client, not just someone trying to query the server. */ /* Only send data when we're a proper client, not just someone trying to query the server. */
if (ci == nullptr) return NETWORK_RECV_STATUS_OKAY; if (ci == nullptr) return NETWORK_RECV_STATUS_OKAY;
Packet *p = new Packet(ADMIN_PACKET_SERVER_CLIENT_INFO); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_CLIENT_INFO);
p->Send_uint32(ci->client_id); p->Send_uint32(ci->client_id);
p->Send_string(cs == nullptr ? "" : const_cast<NetworkAddress &>(cs->client_address).GetHostname()); p->Send_string(cs == nullptr ? "" : const_cast<NetworkAddress &>(cs->client_address).GetHostname());
@ -248,7 +248,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendClientInfo(const NetworkC
p->Send_uint32(ci->join_date.base()); p->Send_uint32(ci->join_date.base());
p->Send_uint8 (ci->client_playas); p->Send_uint8 (ci->client_playas);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -260,13 +260,13 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendClientInfo(const NetworkC
*/ */
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendClientUpdate(const NetworkClientInfo *ci) NetworkRecvStatus ServerNetworkAdminSocketHandler::SendClientUpdate(const NetworkClientInfo *ci)
{ {
Packet *p = new Packet(ADMIN_PACKET_SERVER_CLIENT_UPDATE); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_CLIENT_UPDATE);
p->Send_uint32(ci->client_id); p->Send_uint32(ci->client_id);
p->Send_string(ci->client_name); p->Send_string(ci->client_name);
p->Send_uint8 (ci->client_playas); p->Send_uint8 (ci->client_playas);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -277,10 +277,10 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendClientUpdate(const Networ
*/ */
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendClientQuit(ClientID client_id) NetworkRecvStatus ServerNetworkAdminSocketHandler::SendClientQuit(ClientID client_id)
{ {
Packet *p = new Packet(ADMIN_PACKET_SERVER_CLIENT_QUIT); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_CLIENT_QUIT);
p->Send_uint32(client_id); p->Send_uint32(client_id);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -292,11 +292,11 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendClientQuit(ClientID clien
*/ */
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendClientError(ClientID client_id, NetworkErrorCode error) NetworkRecvStatus ServerNetworkAdminSocketHandler::SendClientError(ClientID client_id, NetworkErrorCode error)
{ {
Packet *p = new Packet(ADMIN_PACKET_SERVER_CLIENT_ERROR); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_CLIENT_ERROR);
p->Send_uint32(client_id); p->Send_uint32(client_id);
p->Send_uint8 (error); p->Send_uint8 (error);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -307,10 +307,10 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendClientError(ClientID clie
*/ */
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCompanyNew(CompanyID company_id) NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCompanyNew(CompanyID company_id)
{ {
Packet *p = new Packet(ADMIN_PACKET_SERVER_COMPANY_NEW); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_COMPANY_NEW);
p->Send_uint8(company_id); p->Send_uint8(company_id);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -321,7 +321,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCompanyNew(CompanyID comp
*/ */
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCompanyInfo(const Company *c) NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCompanyInfo(const Company *c)
{ {
Packet *p = new Packet(ADMIN_PACKET_SERVER_COMPANY_INFO); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_COMPANY_INFO);
p->Send_uint8 (c->index); p->Send_uint8 (c->index);
SetDParam(0, c->index); SetDParam(0, c->index);
@ -334,7 +334,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCompanyInfo(const Company
p->Send_bool (c->is_ai); p->Send_bool (c->is_ai);
p->Send_uint8 (CeilDiv(c->months_of_bankruptcy, 3)); // send as quarters_of_bankruptcy p->Send_uint8 (CeilDiv(c->months_of_bankruptcy, 3)); // send as quarters_of_bankruptcy
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -346,7 +346,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCompanyInfo(const Company
*/ */
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCompanyUpdate(const Company *c) NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCompanyUpdate(const Company *c)
{ {
Packet *p = new Packet(ADMIN_PACKET_SERVER_COMPANY_UPDATE); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_COMPANY_UPDATE);
p->Send_uint8 (c->index); p->Send_uint8 (c->index);
SetDParam(0, c->index); SetDParam(0, c->index);
@ -357,7 +357,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCompanyUpdate(const Compa
p->Send_bool (NetworkCompanyIsPassworded(c->index)); p->Send_bool (NetworkCompanyIsPassworded(c->index));
p->Send_uint8 (CeilDiv(c->months_of_bankruptcy, 3)); // send as quarters_of_bankruptcy p->Send_uint8 (CeilDiv(c->months_of_bankruptcy, 3)); // send as quarters_of_bankruptcy
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -369,12 +369,12 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCompanyUpdate(const Compa
*/ */
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCompanyRemove(CompanyID company_id, AdminCompanyRemoveReason acrr) NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCompanyRemove(CompanyID company_id, AdminCompanyRemoveReason acrr)
{ {
Packet *p = new Packet(ADMIN_PACKET_SERVER_COMPANY_REMOVE); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_COMPANY_REMOVE);
p->Send_uint8(company_id); p->Send_uint8(company_id);
p->Send_uint8(acrr); p->Send_uint8(acrr);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -386,7 +386,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCompanyEconomy()
/* Get the income. */ /* Get the income. */
Money income = -std::reduce(std::begin(company->yearly_expenses[0]), std::end(company->yearly_expenses[0])); Money income = -std::reduce(std::begin(company->yearly_expenses[0]), std::end(company->yearly_expenses[0]));
Packet *p = new Packet(ADMIN_PACKET_SERVER_COMPANY_ECONOMY); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_COMPANY_ECONOMY);
p->Send_uint8(company->index); p->Send_uint8(company->index);
@ -403,7 +403,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCompanyEconomy()
p->Send_uint16(static_cast<uint16_t>(std::min<uint64_t>(UINT16_MAX, company->old_economy[i].delivered_cargo.GetSum<OverflowSafeInt64>()))); p->Send_uint16(static_cast<uint16_t>(std::min<uint64_t>(UINT16_MAX, company->old_economy[i].delivered_cargo.GetSum<OverflowSafeInt64>())));
} }
this->SendPacket(p); this->SendPacket(std::move(p));
} }
@ -419,7 +419,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCompanyStats()
/* Go through all the companies. */ /* Go through all the companies. */
for (const Company *company : Company::Iterate()) { for (const Company *company : Company::Iterate()) {
Packet *p = new Packet(ADMIN_PACKET_SERVER_COMPANY_STATS); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_COMPANY_STATS);
/* Send the information. */ /* Send the information. */
p->Send_uint8(company->index); p->Send_uint8(company->index);
@ -432,7 +432,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCompanyStats()
p->Send_uint16(company_stats[company->index].num_station[i]); p->Send_uint16(company_stats[company->index].num_station[i]);
} }
this->SendPacket(p); this->SendPacket(std::move(p));
} }
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
@ -448,15 +448,15 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCompanyStats()
*/ */
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendChat(NetworkAction action, DestType desttype, ClientID client_id, const std::string &msg, NetworkTextMessageData data) NetworkRecvStatus ServerNetworkAdminSocketHandler::SendChat(NetworkAction action, DestType desttype, ClientID client_id, const std::string &msg, NetworkTextMessageData data)
{ {
Packet *p = new Packet(ADMIN_PACKET_SERVER_CHAT); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_CHAT);
p->Send_uint8 (action); p->Send_uint8 (action);
p->Send_uint8 (desttype); p->Send_uint8 (desttype);
p->Send_uint32(client_id); p->Send_uint32(client_id);
p->Send_string(msg); p->Send_string(msg);
data.send(p); data.send(*p);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -466,10 +466,10 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendChat(NetworkAction action
*/ */
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendRconEnd(const std::string_view command) NetworkRecvStatus ServerNetworkAdminSocketHandler::SendRconEnd(const std::string_view command)
{ {
Packet *p = new Packet(ADMIN_PACKET_SERVER_RCON_END); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_RCON_END);
p->Send_string(command); p->Send_string(command);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -481,20 +481,20 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendRconEnd(const std::string
*/ */
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendRcon(uint16_t colour, const std::string_view result) NetworkRecvStatus ServerNetworkAdminSocketHandler::SendRcon(uint16_t colour, const std::string_view result)
{ {
Packet *p = new Packet(ADMIN_PACKET_SERVER_RCON); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_RCON);
p->Send_uint16(colour); p->Send_uint16(colour);
p->Send_string(result); p->Send_string(result);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_RCON(Packet *p) NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_RCON(Packet &p)
{ {
if (this->status == ADMIN_STATUS_INACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED); if (this->status == ADMIN_STATUS_INACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
std::string command = p->Recv_string(NETWORK_RCONCOMMAND_LENGTH); std::string command = p.Recv_string(NETWORK_RCONCOMMAND_LENGTH);
DEBUG(net, 3, "[admin] Rcon command from '%s' (%s): %s", this->admin_name.c_str(), this->admin_version.c_str(), command.c_str()); DEBUG(net, 3, "[admin] Rcon command from '%s' (%s): %s", this->admin_name.c_str(), this->admin_version.c_str(), command.c_str());
@ -504,11 +504,11 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_RCON(Packet *p)
return this->SendRconEnd(command); return this->SendRconEnd(command);
} }
NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_GAMESCRIPT(Packet *p) NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_GAMESCRIPT(Packet &p)
{ {
if (this->status == ADMIN_STATUS_INACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED); if (this->status == ADMIN_STATUS_INACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
std::string json = p->Recv_string(NETWORK_GAMESCRIPT_JSON_LENGTH); std::string json = p.Recv_string(NETWORK_GAMESCRIPT_JSON_LENGTH);
DEBUG(net, 6, "[admin] GameScript JSON from '%s' (%s): %s", this->admin_name.c_str(), this->admin_version.c_str(), json.c_str()); DEBUG(net, 6, "[admin] GameScript JSON from '%s' (%s): %s", this->admin_name.c_str(), this->admin_version.c_str(), json.c_str());
@ -516,11 +516,11 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_GAMESCRIPT(Pack
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_PING(Packet *p) NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_PING(Packet &p)
{ {
if (this->status == ADMIN_STATUS_INACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED); if (this->status == ADMIN_STATUS_INACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
uint32_t d1 = p->Recv_uint32(); uint32_t d1 = p.Recv_uint32();
DEBUG(net, 6, "[admin] Ping from '%s' (%s): %d", this->admin_name.c_str(), this->admin_version.c_str(), d1); DEBUG(net, 6, "[admin] Ping from '%s' (%s): %d", this->admin_name.c_str(), this->admin_version.c_str(), d1);
@ -540,11 +540,11 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendConsole(const std::string
* smaller than COMPAT_MTU. */ * smaller than COMPAT_MTU. */
if (origin.size() + string.size() + 2 + 3 >= COMPAT_MTU) return NETWORK_RECV_STATUS_OKAY; if (origin.size() + string.size() + 2 + 3 >= COMPAT_MTU) return NETWORK_RECV_STATUS_OKAY;
Packet *p = new Packet(ADMIN_PACKET_SERVER_CONSOLE); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_CONSOLE);
p->Send_string(origin); p->Send_string(origin);
p->Send_string(string); p->Send_string(string);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -555,10 +555,10 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendConsole(const std::string
*/ */
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendGameScript(const std::string_view json) NetworkRecvStatus ServerNetworkAdminSocketHandler::SendGameScript(const std::string_view json)
{ {
Packet *p = new Packet(ADMIN_PACKET_SERVER_GAMESCRIPT); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_GAMESCRIPT);
p->Send_string(json); p->Send_string(json);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -566,10 +566,10 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendGameScript(const std::str
/** Send ping-reply (pong) to admin **/ /** Send ping-reply (pong) to admin **/
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendPong(uint32_t d1) NetworkRecvStatus ServerNetworkAdminSocketHandler::SendPong(uint32_t d1)
{ {
Packet *p = new Packet(ADMIN_PACKET_SERVER_PONG); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_PONG);
p->Send_uint32(d1); p->Send_uint32(d1);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -577,7 +577,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendPong(uint32_t d1)
/** Send the names of the commands. */ /** Send the names of the commands. */
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCmdNames() NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCmdNames()
{ {
Packet *p = new Packet(ADMIN_PACKET_SERVER_CMD_NAMES); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_CMD_NAMES);
for (uint i = 0; i < CMD_END; i++) { for (uint i = 0; i < CMD_END; i++) {
const char *cmdname = GetCommandName(i); const char *cmdname = GetCommandName(i);
@ -587,9 +587,9 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCmdNames()
* byte for string '\0' termination and 1 bool "no more data" */ * byte for string '\0' termination and 1 bool "no more data" */
if (!p->CanWriteToPacket(strlen(cmdname) + 5)) { if (!p->CanWriteToPacket(strlen(cmdname) + 5)) {
p->Send_bool(false); p->Send_bool(false);
this->SendPacket(p); this->SendPacket(std::move(p));
p = new Packet(ADMIN_PACKET_SERVER_CMD_NAMES); p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_CMD_NAMES);
} }
p->Send_bool(true); p->Send_bool(true);
@ -599,7 +599,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCmdNames()
/* Marker to notify the end of the packet has been reached. */ /* Marker to notify the end of the packet has been reached. */
p->Send_bool(false); p->Send_bool(false);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -609,26 +609,26 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCmdNames()
* @param client_id The client executing the command. * @param client_id The client executing the command.
* @param cp The command that would be executed. * @param cp The command that would be executed.
*/ */
NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCmdLogging(ClientID client_id, const CommandPacket *cp) NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCmdLogging(ClientID client_id, const CommandPacket &cp)
{ {
Packet *p = new Packet(ADMIN_PACKET_SERVER_CMD_LOGGING); auto p = std::make_unique<Packet>(ADMIN_PACKET_SERVER_CMD_LOGGING);
p->Send_uint32(client_id); p->Send_uint32(client_id);
p->Send_uint8 (cp->company); p->Send_uint8 (cp.company);
p->Send_uint16(cp->cmd & CMD_ID_MASK); p->Send_uint16(cp.cmd & CMD_ID_MASK);
p->Send_uint16(4 + 4 + 8 + 4 + (uint16_t)cp->text.size() + 1); p->Send_uint16(4 + 4 + 8 + 4 + (uint16_t)cp.text.size() + 1);
{ {
p->Send_uint32(cp->p1); p->Send_uint32(cp.p1);
p->Send_uint32(cp->p2); p->Send_uint32(cp.p2);
p->Send_uint64(cp->p3); p->Send_uint64(cp.p3);
p->Send_uint32(cp->tile); p->Send_uint32(cp.tile);
p->Send_string(cp->text.c_str()); p->Send_string(cp.text.c_str());
} }
p->Send_uint32(cp->frame); p->Send_uint32(cp.frame);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -637,11 +637,11 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCmdLogging(ClientID clien
* Receiving functions * Receiving functions
************/ ************/
NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_JOIN(Packet *p) NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_JOIN(Packet &p)
{ {
if (this->status != ADMIN_STATUS_INACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED); if (this->status != ADMIN_STATUS_INACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
std::string password = p->Recv_string(NETWORK_PASSWORD_LENGTH); std::string password = p.Recv_string(NETWORK_PASSWORD_LENGTH);
if (_settings_client.network.admin_password.empty() || if (_settings_client.network.admin_password.empty() ||
_settings_client.network.admin_password.compare(password) != 0) { _settings_client.network.admin_password.compare(password) != 0) {
@ -649,8 +649,8 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_JOIN(Packet *p)
return this->SendError(NETWORK_ERROR_WRONG_PASSWORD); return this->SendError(NETWORK_ERROR_WRONG_PASSWORD);
} }
this->admin_name = p->Recv_string(NETWORK_CLIENT_NAME_LENGTH); this->admin_name = p.Recv_string(NETWORK_CLIENT_NAME_LENGTH);
this->admin_version = p->Recv_string(NETWORK_REVISION_LENGTH); this->admin_version = p.Recv_string(NETWORK_REVISION_LENGTH);
if (this->admin_name.empty() || this->admin_version.empty()) { if (this->admin_name.empty() || this->admin_version.empty()) {
/* no name or version supplied */ /* no name or version supplied */
@ -664,18 +664,18 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_JOIN(Packet *p)
return this->SendProtocol(); return this->SendProtocol();
} }
NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_QUIT(Packet *) NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_QUIT(Packet &)
{ {
/* The admin is leaving nothing else to do */ /* The admin is leaving nothing else to do */
return this->CloseConnection(); return this->CloseConnection();
} }
NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_UPDATE_FREQUENCY(Packet *p) NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_UPDATE_FREQUENCY(Packet &p)
{ {
if (this->status == ADMIN_STATUS_INACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED); if (this->status == ADMIN_STATUS_INACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
AdminUpdateType type = (AdminUpdateType)p->Recv_uint16(); AdminUpdateType type = (AdminUpdateType)p.Recv_uint16();
AdminUpdateFrequency freq = (AdminUpdateFrequency)p->Recv_uint16(); AdminUpdateFrequency freq = (AdminUpdateFrequency)p.Recv_uint16();
if (type >= ADMIN_UPDATE_END || (_admin_update_type_frequencies[type] & freq) != freq) { if (type >= ADMIN_UPDATE_END || (_admin_update_type_frequencies[type] & freq) != freq) {
/* The server does not know of this UpdateType. */ /* The server does not know of this UpdateType. */
@ -690,12 +690,12 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_UPDATE_FREQUENC
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_POLL(Packet *p) NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_POLL(Packet &p)
{ {
if (this->status == ADMIN_STATUS_INACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED); if (this->status == ADMIN_STATUS_INACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
AdminUpdateType type = (AdminUpdateType)p->Recv_uint8(); AdminUpdateType type = (AdminUpdateType)p.Recv_uint8();
uint32_t d1 = p->Recv_uint32(); uint32_t d1 = p.Recv_uint32();
switch (type) { switch (type) {
case ADMIN_UPDATE_DATE: case ADMIN_UPDATE_DATE:
@ -756,15 +756,15 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_POLL(Packet *p)
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_CHAT(Packet *p) NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_CHAT(Packet &p)
{ {
if (this->status == ADMIN_STATUS_INACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED); if (this->status == ADMIN_STATUS_INACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
NetworkAction action = (NetworkAction)p->Recv_uint8(); NetworkAction action = (NetworkAction)p.Recv_uint8();
DestType desttype = (DestType)p->Recv_uint8(); DestType desttype = (DestType)p.Recv_uint8();
int dest = p->Recv_uint32(); int dest = p.Recv_uint32();
std::string msg = p->Recv_string(NETWORK_CHAT_LENGTH); std::string msg = p.Recv_string(NETWORK_CHAT_LENGTH);
switch (action) { switch (action) {
case NETWORK_ACTION_CHAT: case NETWORK_ACTION_CHAT:
@ -782,14 +782,14 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_CHAT(Packet *p)
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_EXTERNAL_CHAT(Packet *p) NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_EXTERNAL_CHAT(Packet &p)
{ {
if (this->status == ADMIN_STATUS_INACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED); if (this->status == ADMIN_STATUS_INACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
std::string source = p->Recv_string(NETWORK_CHAT_LENGTH); std::string source = p.Recv_string(NETWORK_CHAT_LENGTH);
TextColour colour = (TextColour)p->Recv_uint16(); TextColour colour = (TextColour)p.Recv_uint16();
std::string user = p->Recv_string(NETWORK_CHAT_LENGTH); std::string user = p.Recv_string(NETWORK_CHAT_LENGTH);
std::string msg = p->Recv_string(NETWORK_CHAT_LENGTH); std::string msg = p.Recv_string(NETWORK_CHAT_LENGTH);
if (!IsValidConsoleColour(colour)) { if (!IsValidConsoleColour(colour)) {
DEBUG(net, 1, "[admin] Not supported chat colour %d (%s, %s, %s) from '%s' (%s).", DEBUG(net, 1, "[admin] Not supported chat colour %d (%s, %s, %s) from '%s' (%s).",
@ -970,7 +970,7 @@ void NetworkAdminGameScript(const std::string_view json)
* @param owner The owner of the CommandPacket (who sent us the CommandPacket). * @param owner The owner of the CommandPacket (who sent us the CommandPacket).
* @param cp The CommandPacket to be distributed. * @param cp The CommandPacket to be distributed.
*/ */
void NetworkAdminCmdLogging(const NetworkClientSocket *owner, const CommandPacket *cp) void NetworkAdminCmdLogging(const NetworkClientSocket *owner, const CommandPacket &cp)
{ {
ClientID client_id = owner == nullptr ? _network_own_client_id : owner->client_id; ClientID client_id = owner == nullptr ? _network_own_client_id : owner->client_id;

@ -24,15 +24,15 @@ extern NetworkAdminSocketPool _networkadminsocket_pool;
/** Class for handling the server side of the game connection. */ /** Class for handling the server side of the game connection. */
class ServerNetworkAdminSocketHandler : public NetworkAdminSocketPool::PoolItem<&_networkadminsocket_pool>, public NetworkAdminSocketHandler, public TCPListenHandler<ServerNetworkAdminSocketHandler, ADMIN_PACKET_SERVER_FULL, ADMIN_PACKET_SERVER_BANNED> { class ServerNetworkAdminSocketHandler : public NetworkAdminSocketPool::PoolItem<&_networkadminsocket_pool>, public NetworkAdminSocketHandler, public TCPListenHandler<ServerNetworkAdminSocketHandler, ADMIN_PACKET_SERVER_FULL, ADMIN_PACKET_SERVER_BANNED> {
protected: protected:
NetworkRecvStatus Receive_ADMIN_JOIN(Packet *p) override; NetworkRecvStatus Receive_ADMIN_JOIN(Packet &p) override;
NetworkRecvStatus Receive_ADMIN_QUIT(Packet *p) override; NetworkRecvStatus Receive_ADMIN_QUIT(Packet &p) override;
NetworkRecvStatus Receive_ADMIN_UPDATE_FREQUENCY(Packet *p) override; NetworkRecvStatus Receive_ADMIN_UPDATE_FREQUENCY(Packet &p) override;
NetworkRecvStatus Receive_ADMIN_POLL(Packet *p) override; NetworkRecvStatus Receive_ADMIN_POLL(Packet &p) override;
NetworkRecvStatus Receive_ADMIN_CHAT(Packet *p) override; NetworkRecvStatus Receive_ADMIN_CHAT(Packet &p) override;
NetworkRecvStatus Receive_ADMIN_EXTERNAL_CHAT(Packet *p) override; NetworkRecvStatus Receive_ADMIN_EXTERNAL_CHAT(Packet &p) override;
NetworkRecvStatus Receive_ADMIN_RCON(Packet *p) override; NetworkRecvStatus Receive_ADMIN_RCON(Packet &p) override;
NetworkRecvStatus Receive_ADMIN_GAMESCRIPT(Packet *p) override; NetworkRecvStatus Receive_ADMIN_GAMESCRIPT(Packet &p) override;
NetworkRecvStatus Receive_ADMIN_PING(Packet *p) override; NetworkRecvStatus Receive_ADMIN_PING(Packet &p) override;
NetworkRecvStatus SendProtocol(); NetworkRecvStatus SendProtocol();
NetworkRecvStatus SendPong(uint32_t d1); NetworkRecvStatus SendPong(uint32_t d1);
@ -67,7 +67,7 @@ public:
NetworkRecvStatus SendConsole(const std::string_view origin, const std::string_view command); NetworkRecvStatus SendConsole(const std::string_view origin, const std::string_view command);
NetworkRecvStatus SendGameScript(const std::string_view json); NetworkRecvStatus SendGameScript(const std::string_view json);
NetworkRecvStatus SendCmdNames(); NetworkRecvStatus SendCmdNames();
NetworkRecvStatus SendCmdLogging(ClientID client_id, const CommandPacket *cp); NetworkRecvStatus SendCmdLogging(ClientID client_id, const CommandPacket &cp);
NetworkRecvStatus SendRconEnd(const std::string_view command); NetworkRecvStatus SendRconEnd(const std::string_view command);
static void Send(); static void Send();
@ -112,6 +112,6 @@ void NetworkAdminUpdate(AdminUpdateFrequency freq);
void NetworkServerSendAdminRcon(AdminIndex admin_index, TextColour colour_code, const std::string_view string); void NetworkServerSendAdminRcon(AdminIndex admin_index, TextColour colour_code, const std::string_view string);
void NetworkAdminConsole(const std::string_view origin, const std::string_view string); void NetworkAdminConsole(const std::string_view origin, const std::string_view string);
void NetworkAdminGameScript(const std::string_view json); void NetworkAdminGameScript(const std::string_view json);
void NetworkAdminCmdLogging(const NetworkClientSocket *owner, const CommandPacket *cp); void NetworkAdminCmdLogging(const NetworkClientSocket *owner, const CommandPacket &cp);
#endif /* NETWORK_ADMIN_H */ #endif /* NETWORK_ADMIN_H */

@ -89,19 +89,19 @@ struct PacketReader : LoadFilter {
* Add a packet to this buffer. * Add a packet to this buffer.
* @param p The packet to add. * @param p The packet to add.
*/ */
void AddPacket(Packet *p) void AddPacket(Packet &p)
{ {
assert(this->read_bytes == 0); assert(this->read_bytes == 0);
p->TransferOutWithLimit(TransferOutMemCopy, this->bufe - this->buf, this); p.TransferOutWithLimit(TransferOutMemCopy, this->bufe - this->buf, this);
/* Did everything fit in the current chunk, then we're done. */ /* Did everything fit in the current chunk, then we're done. */
if (p->RemainingBytesToTransfer() == 0) return; if (p.RemainingBytesToTransfer() == 0) return;
/* Allocate a new chunk and add the remaining data. */ /* Allocate a new chunk and add the remaining data. */
this->blocks.push_back(this->buf = CallocT<byte>(CHUNK)); this->blocks.push_back(this->buf = CallocT<byte>(CHUNK));
this->bufe = this->buf + CHUNK; this->bufe = this->buf + CHUNK;
p->TransferOutWithLimit(TransferOutMemCopy, this->bufe - this->buf, this); p.TransferOutWithLimit(TransferOutMemCopy, this->bufe - this->buf, this);
} }
size_t Read(byte *rbuf, size_t size) override size_t Read(byte *rbuf, size_t size) override
@ -458,7 +458,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendKeyPasswordPacket(PacketTy
static_assert(std::tuple_size<decltype(ss.shared_data)>::value == 64); static_assert(std::tuple_size<decltype(ss.shared_data)>::value == 64);
crypto_aead_lock(message.data(), mac.data(), ss.shared_data.data(), nonce.data(), keys.x25519_pub_key.data(), keys.x25519_pub_key.size(), message.data(), message.size()); crypto_aead_lock(message.data(), mac.data(), ss.shared_data.data(), nonce.data(), keys.x25519_pub_key.data(), keys.x25519_pub_key.size(), message.data(), message.size());
Packet *p = new Packet(packet_type, SHRT_MAX); auto p = std::make_unique<Packet>(packet_type, TCP_MTU);
static_assert(std::tuple_size<decltype(keys.x25519_pub_key)>::value == 32); static_assert(std::tuple_size<decltype(keys.x25519_pub_key)>::value == 32);
p->Send_binary(keys.x25519_pub_key); p->Send_binary(keys.x25519_pub_key);
p->Send_binary(nonce); p->Send_binary(nonce);
@ -467,13 +467,12 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendKeyPasswordPacket(PacketTy
_next_key_message_id++; _next_key_message_id++;
my_client->SendPacket(p); my_client->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
/*********** /***********
* Sending functions * Sending functions
* DEF_CLIENT_SEND_COMMAND has no parameters
************/ ************/
/** Tell the server we would like to join. */ /** Tell the server we would like to join. */
@ -483,21 +482,21 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendJoin()
_network_join_status = NETWORK_JOIN_STATUS_AUTHORIZING; _network_join_status = NETWORK_JOIN_STATUS_AUTHORIZING;
SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN); SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
Packet *p = new Packet(PACKET_CLIENT_JOIN, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_CLIENT_JOIN);
p->Send_string(_openttd_revision); p->Send_string(_openttd_revision);
p->Send_uint32(_openttd_newgrf_version); p->Send_uint32(_openttd_newgrf_version);
p->Send_string(_settings_client.network.client_name); // Client name p->Send_string(_settings_client.network.client_name); // Client name
p->Send_uint8 (_network_join.company); // PlayAs p->Send_uint8 (_network_join.company); // PlayAs
p->Send_uint8 (0); // Used to be language p->Send_uint8 (0); // Used to be language
my_client->SendPacket(p); my_client->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
/** Tell the server we got all the NewGRFs. */ /** Tell the server we got all the NewGRFs. */
NetworkRecvStatus ClientNetworkGameSocketHandler::SendNewGRFsOk() NetworkRecvStatus ClientNetworkGameSocketHandler::SendNewGRFsOk()
{ {
Packet *p = new Packet(PACKET_CLIENT_NEWGRFS_CHECKED, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_CLIENT_NEWGRFS_CHECKED);
my_client->SendPacket(p); my_client->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -517,9 +516,9 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendGamePassword(const std::st
*/ */
NetworkRecvStatus ClientNetworkGameSocketHandler::SendCompanyPassword(const std::string &password) NetworkRecvStatus ClientNetworkGameSocketHandler::SendCompanyPassword(const std::string &password)
{ {
Packet *p = new Packet(PACKET_CLIENT_COMPANY_PASSWORD, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_CLIENT_COMPANY_PASSWORD, TCP_MTU);
p->Send_string(GenerateCompanyPasswordHash(password, _company_password_server_id, _company_password_game_seed)); p->Send_string(GenerateCompanyPasswordHash(password, _company_password_server_id, _company_password_game_seed));
my_client->SendPacket(p); my_client->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -530,8 +529,8 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendCompanyPassword(const std:
NetworkRecvStatus ClientNetworkGameSocketHandler::SendSettingsPassword(const std::string &password) NetworkRecvStatus ClientNetworkGameSocketHandler::SendSettingsPassword(const std::string &password)
{ {
if (password.empty()) { if (password.empty()) {
Packet *p = new Packet(PACKET_CLIENT_SETTINGS_PASSWORD, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_CLIENT_SETTINGS_PASSWORD, TCP_MTU);
my_client->SendPacket(p); my_client->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} else { } else {
NetworkSharedSecrets ss; NetworkSharedSecrets ss;
@ -544,13 +543,13 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendGetMap()
{ {
my_client->status = STATUS_MAP_WAIT; my_client->status = STATUS_MAP_WAIT;
Packet *p = new Packet(PACKET_CLIENT_GETMAP, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_CLIENT_GETMAP, TCP_MTU);
#if defined(WITH_ZSTD) #if defined(WITH_ZSTD)
p->Send_bool(true); p->Send_bool(true);
#else #else
p->Send_bool(false); p->Send_bool(false);
#endif #endif
my_client->SendPacket(p); my_client->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -559,19 +558,19 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendMapOk()
{ {
my_client->status = STATUS_ACTIVE; my_client->status = STATUS_ACTIVE;
Packet *p = new Packet(PACKET_CLIENT_MAP_OK, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_CLIENT_MAP_OK, TCP_MTU);
my_client->SendPacket(p); my_client->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
/** Send an acknowledgement from the server's ticks. */ /** Send an acknowledgement from the server's ticks. */
NetworkRecvStatus ClientNetworkGameSocketHandler::SendAck() NetworkRecvStatus ClientNetworkGameSocketHandler::SendAck()
{ {
Packet *p = new Packet(PACKET_CLIENT_ACK, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_CLIENT_ACK, TCP_MTU);
p->Send_uint32(_frame_counter); p->Send_uint32(_frame_counter);
p->Send_uint8 (my_client->token); p->Send_uint8 (my_client->token);
my_client->SendPacket(p); my_client->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -579,12 +578,12 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendAck()
* Send a command to the server. * Send a command to the server.
* @param cp The command to send. * @param cp The command to send.
*/ */
NetworkRecvStatus ClientNetworkGameSocketHandler::SendCommand(const CommandPacket *cp) NetworkRecvStatus ClientNetworkGameSocketHandler::SendCommand(const CommandPacket &cp)
{ {
Packet *p = new Packet(PACKET_CLIENT_COMMAND, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_CLIENT_COMMAND, TCP_MTU);
my_client->NetworkGameSocketHandler::SendCommand(p, cp); my_client->NetworkGameSocketHandler::SendCommand(*p, cp);
my_client->SendPacket(p); my_client->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -592,28 +591,28 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendCommand(const CommandPacke
NetworkRecvStatus ClientNetworkGameSocketHandler::SendChat(NetworkAction action, DestType type, int dest, const std::string &msg, NetworkTextMessageData data) NetworkRecvStatus ClientNetworkGameSocketHandler::SendChat(NetworkAction action, DestType type, int dest, const std::string &msg, NetworkTextMessageData data)
{ {
if (!my_client) return NETWORK_RECV_STATUS_CLIENT_QUIT; if (!my_client) return NETWORK_RECV_STATUS_CLIENT_QUIT;
Packet *p = new Packet(PACKET_CLIENT_CHAT, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_CLIENT_CHAT, TCP_MTU);
p->Send_uint8 (action); p->Send_uint8 (action);
p->Send_uint8 (type); p->Send_uint8 (type);
p->Send_uint32(dest); p->Send_uint32(dest);
p->Send_string(msg); p->Send_string(msg);
data.send(p); data.send(*p);
my_client->SendPacket(p); my_client->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
/** Send an error-packet over the network */ /** Send an error-packet over the network */
NetworkRecvStatus ClientNetworkGameSocketHandler::SendError(NetworkErrorCode errorno, NetworkRecvStatus recvstatus) NetworkRecvStatus ClientNetworkGameSocketHandler::SendError(NetworkErrorCode errorno, NetworkRecvStatus recvstatus)
{ {
Packet *p = new Packet(PACKET_CLIENT_ERROR, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_CLIENT_ERROR, TCP_MTU);
p->Send_uint8(errorno); p->Send_uint8(errorno);
p->Send_uint8(recvstatus); p->Send_uint8(recvstatus);
p->Send_uint8(my_client->status); p->Send_uint8(my_client->status);
p->Send_uint8(my_client->last_pkt_type); p->Send_uint8(my_client->last_pkt_type);
my_client->SendPacket(p); my_client->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -621,11 +620,11 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendError(NetworkErrorCode err
NetworkRecvStatus ClientNetworkGameSocketHandler::SendDesyncLog(const std::string &log) NetworkRecvStatus ClientNetworkGameSocketHandler::SendDesyncLog(const std::string &log)
{ {
for (size_t offset = 0; offset < log.size();) { for (size_t offset = 0; offset < log.size();) {
Packet *p = new Packet(PACKET_CLIENT_DESYNC_LOG, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_CLIENT_DESYNC_LOG, TCP_MTU);
size_t size = std::min<size_t>(log.size() - offset, SHRT_MAX - 2 - p->Size()); size_t size = std::min<size_t>(log.size() - offset, TCP_MTU - 2 - p->Size());
p->Send_uint16((uint16_t)size); p->Send_uint16((uint16_t)size);
p->Send_binary((const byte *)(log.data() + offset), size); p->Send_binary((const byte *)(log.data() + offset), size);
my_client->SendPacket(p); my_client->SendPacket(std::move(p));
offset += size; offset += size;
} }
@ -635,12 +634,12 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendDesyncLog(const std::strin
/** Send an error-packet over the network */ /** Send an error-packet over the network */
NetworkRecvStatus ClientNetworkGameSocketHandler::SendDesyncMessage(const char *msg) NetworkRecvStatus ClientNetworkGameSocketHandler::SendDesyncMessage(const char *msg)
{ {
Packet *p = new Packet(PACKET_CLIENT_DESYNC_MSG, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_CLIENT_DESYNC_MSG, TCP_MTU);
p->Send_uint32(EconTime::CurDate().base()); p->Send_uint32(EconTime::CurDate().base());
p->Send_uint16(EconTime::CurDateFract()); p->Send_uint16(EconTime::CurDateFract());
p->Send_uint8(TickSkipCounter()); p->Send_uint8(TickSkipCounter());
p->Send_string(msg); p->Send_string(msg);
my_client->SendPacket(p); my_client->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -659,7 +658,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendDesyncSyncData()
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
Packet *p = new Packet(PACKET_CLIENT_DESYNC_SYNC_DATA, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_CLIENT_DESYNC_SYNC_DATA, TCP_MTU);
p->Send_uint32((uint32_t)_network_sync_record_counts.size()); p->Send_uint32((uint32_t)_network_sync_record_counts.size());
uint32_t offset = 0; uint32_t offset = 0;
for (uint32_t count : _network_sync_record_counts) { for (uint32_t count : _network_sync_record_counts) {
@ -672,7 +671,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendDesyncSyncData()
} }
offset += count; offset += count;
} }
my_client->SendPacket(p); my_client->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -682,10 +681,10 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendDesyncSyncData()
*/ */
NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetPassword(const std::string &password) NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetPassword(const std::string &password)
{ {
Packet *p = new Packet(PACKET_CLIENT_SET_PASSWORD, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_CLIENT_SET_PASSWORD, TCP_MTU);
p->Send_string(GenerateCompanyPasswordHash(password, _company_password_server_id, _company_password_game_seed)); p->Send_string(GenerateCompanyPasswordHash(password, _company_password_server_id, _company_password_game_seed));
my_client->SendPacket(p); my_client->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -695,10 +694,10 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetPassword(const std::str
*/ */
NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetName(const std::string &name) NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetName(const std::string &name)
{ {
Packet *p = new Packet(PACKET_CLIENT_SET_NAME, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_CLIENT_SET_NAME, TCP_MTU);
p->Send_string(name); p->Send_string(name);
my_client->SendPacket(p); my_client->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -707,9 +706,9 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetName(const std::string
*/ */
NetworkRecvStatus ClientNetworkGameSocketHandler::SendQuit() NetworkRecvStatus ClientNetworkGameSocketHandler::SendQuit()
{ {
Packet *p = new Packet(PACKET_CLIENT_QUIT, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_CLIENT_QUIT, TCP_MTU);
my_client->SendPacket(p); my_client->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -730,10 +729,10 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendRCon(const std::string &pa
*/ */
NetworkRecvStatus ClientNetworkGameSocketHandler::SendMove(CompanyID company, const std::string &password) NetworkRecvStatus ClientNetworkGameSocketHandler::SendMove(CompanyID company, const std::string &password)
{ {
Packet *p = new Packet(PACKET_CLIENT_MOVE, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_CLIENT_MOVE, TCP_MTU);
p->Send_uint8(company); p->Send_uint8(company);
p->Send_string(GenerateCompanyPasswordHash(password, _company_password_server_id, _company_password_game_seed)); p->Send_string(GenerateCompanyPasswordHash(password, _company_password_server_id, _company_password_game_seed));
my_client->SendPacket(p); my_client->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -749,13 +748,12 @@ bool ClientNetworkGameSocketHandler::IsConnected()
/*********** /***********
* Receiving functions * Receiving functions
* DEF_CLIENT_RECEIVE_COMMAND has parameter: Packet *p
************/ ************/
extern bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, extern bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir,
std::shared_ptr<struct LoadFilter> lf = nullptr, std::string *error_detail = nullptr); std::shared_ptr<struct LoadFilter> lf = nullptr, std::string *error_detail = nullptr);
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_FULL(Packet *) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_FULL(Packet &)
{ {
/* We try to join a server which is full */ /* We try to join a server which is full */
ShowErrorMessage(STR_NETWORK_ERROR_SERVER_FULL, INVALID_STRING_ID, WL_CRITICAL); ShowErrorMessage(STR_NETWORK_ERROR_SERVER_FULL, INVALID_STRING_ID, WL_CRITICAL);
@ -763,7 +761,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_FULL(Packet *)
return NETWORK_RECV_STATUS_SERVER_FULL; return NETWORK_RECV_STATUS_SERVER_FULL;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_BANNED(Packet *) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_BANNED(Packet &)
{ {
/* We try to join a server where we are banned */ /* We try to join a server where we are banned */
ShowErrorMessage(STR_NETWORK_ERROR_SERVER_BANNED, INVALID_STRING_ID, WL_CRITICAL); ShowErrorMessage(STR_NETWORK_ERROR_SERVER_BANNED, INVALID_STRING_ID, WL_CRITICAL);
@ -774,13 +772,13 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_BANNED(Packet *
/* This packet contains info about the client (playas and name) /* This packet contains info about the client (playas and name)
* as client we save this in NetworkClientInfo, linked via 'client_id' * as client we save this in NetworkClientInfo, linked via 'client_id'
* which is always an unique number on a server. */ * which is always an unique number on a server. */
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CLIENT_INFO(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CLIENT_INFO(Packet &p)
{ {
NetworkClientInfo *ci; NetworkClientInfo *ci;
ClientID client_id = (ClientID)p->Recv_uint32(); ClientID client_id = (ClientID)p.Recv_uint32();
CompanyID playas = (CompanyID)p->Recv_uint8(); CompanyID playas = (CompanyID)p.Recv_uint8();
std::string name = p->Recv_string(NETWORK_NAME_LENGTH); std::string name = p.Recv_string(NETWORK_NAME_LENGTH);
if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT; if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT;
@ -830,7 +828,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CLIENT_INFO(Pac
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR(Packet &p)
{ {
static const StringID network_error_strings[] = { static const StringID network_error_strings[] = {
STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_GENERAL STR_NETWORK_ERROR_LOSTCONNECTION, // NETWORK_ERROR_GENERAL
@ -857,13 +855,13 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR(Packet *p
}; };
static_assert(lengthof(network_error_strings) == NETWORK_ERROR_END); static_assert(lengthof(network_error_strings) == NETWORK_ERROR_END);
NetworkErrorCode error = (NetworkErrorCode)p->Recv_uint8(); NetworkErrorCode error = (NetworkErrorCode)p.Recv_uint8();
StringID err = STR_NETWORK_ERROR_LOSTCONNECTION; StringID err = STR_NETWORK_ERROR_LOSTCONNECTION;
if (error < (ptrdiff_t)lengthof(network_error_strings)) err = network_error_strings[error]; 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 */ /* 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)) { if (error == NETWORK_ERROR_KICKED && p.CanReadFromPacket(1)) {
SetDParamStr(0, p->Recv_string(NETWORK_CHAT_LENGTH)); SetDParamStr(0, p.Recv_string(NETWORK_CHAT_LENGTH));
ShowErrorMessage(err, STR_NETWORK_ERROR_KICK_MESSAGE, WL_CRITICAL); ShowErrorMessage(err, STR_NETWORK_ERROR_KICK_MESSAGE, WL_CRITICAL);
} else { } else {
ShowErrorMessage(err, INVALID_STRING_ID, WL_CRITICAL); ShowErrorMessage(err, INVALID_STRING_ID, WL_CRITICAL);
@ -875,18 +873,18 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR(Packet *p
return NETWORK_RECV_STATUS_SERVER_ERROR; return NETWORK_RECV_STATUS_SERVER_ERROR;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHECK_NEWGRFS(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHECK_NEWGRFS(Packet &p)
{ {
if (this->status != STATUS_JOIN) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status != STATUS_JOIN) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
uint grf_count = p->Recv_uint32(); uint grf_count = p.Recv_uint32();
if (grf_count > MAX_NON_STATIC_GRF_COUNT) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (grf_count > MAX_NON_STATIC_GRF_COUNT) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
NetworkRecvStatus ret = NETWORK_RECV_STATUS_OKAY; NetworkRecvStatus ret = NETWORK_RECV_STATUS_OKAY;
/* Check all GRFs */ /* Check all GRFs */
for (; grf_count > 0; grf_count--) { for (; grf_count > 0; grf_count--) {
GRFIdentifier c; GRFIdentifier c;
DeserializeGRFIdentifier(p, &c); DeserializeGRFIdentifier(p, c);
/* Check whether we know this GRF */ /* Check whether we know this GRF */
const GRFConfig *f = FindGRFConfig(c.grfid, FGCM_EXACT, &c.md5sum); const GRFConfig *f = FindGRFConfig(c.grfid, FGCM_EXACT, &c.md5sum);
@ -909,14 +907,14 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHECK_NEWGRFS(P
return ret; return ret;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_NEED_GAME_PASSWORD(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_NEED_GAME_PASSWORD(Packet &p)
{ {
if (this->status < STATUS_JOIN || this->status >= STATUS_AUTH_GAME) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status < STATUS_JOIN || this->status >= STATUS_AUTH_GAME) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
this->status = STATUS_AUTH_GAME; this->status = STATUS_AUTH_GAME;
static_assert(_server_x25519_pub_key.size() == 32); static_assert(_server_x25519_pub_key.size() == 32);
p->Recv_binary(_server_x25519_pub_key); p.Recv_binary(_server_x25519_pub_key);
_password_server_id = p->Recv_string(NETWORK_SERVER_ID_LENGTH); _password_server_id = p.Recv_string(NETWORK_SERVER_ID_LENGTH);
if (this->HasClientQuit()) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->HasClientQuit()) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
if (!_network_join.server_password.empty()) { if (!_network_join.server_password.empty()) {
@ -928,13 +926,13 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_NEED_GAME_PASSW
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_NEED_COMPANY_PASSWORD(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_NEED_COMPANY_PASSWORD(Packet &p)
{ {
if (this->status < STATUS_JOIN || this->status >= STATUS_AUTH_COMPANY) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status < STATUS_JOIN || this->status >= STATUS_AUTH_COMPANY) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
this->status = STATUS_AUTH_COMPANY; this->status = STATUS_AUTH_COMPANY;
_company_password_game_seed = p->Recv_uint32(); _company_password_game_seed = p.Recv_uint32();
_company_password_server_id = p->Recv_string(NETWORK_SERVER_ID_LENGTH); _company_password_server_id = p.Recv_string(NETWORK_SERVER_ID_LENGTH);
if (this->HasClientQuit()) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->HasClientQuit()) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
if (!_network_join.company_password.empty()) { if (!_network_join.company_password.empty()) {
@ -946,38 +944,38 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_NEED_COMPANY_PA
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_WELCOME(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_WELCOME(Packet &p)
{ {
if (this->status < STATUS_JOIN || this->status >= STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status < STATUS_JOIN || this->status >= STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
this->status = STATUS_AUTHORIZED; this->status = STATUS_AUTHORIZED;
_network_own_client_id = (ClientID)p->Recv_uint32(); _network_own_client_id = (ClientID)p.Recv_uint32();
/* Initialize the password hash salting variables, even if they were previously. */ /* Initialize the password hash salting variables, even if they were previously. */
_company_password_game_seed = p->Recv_uint32(); _company_password_game_seed = p.Recv_uint32();
static_assert(_server_x25519_pub_key.size() == 32); static_assert(_server_x25519_pub_key.size() == 32);
p->Recv_binary(_server_x25519_pub_key); p.Recv_binary(_server_x25519_pub_key);
_password_server_id = p->Recv_string(NETWORK_SERVER_ID_LENGTH); _password_server_id = p.Recv_string(NETWORK_SERVER_ID_LENGTH);
_company_password_server_id = p->Recv_string(NETWORK_SERVER_ID_LENGTH); _company_password_server_id = p.Recv_string(NETWORK_SERVER_ID_LENGTH);
/* Start receiving the map */ /* Start receiving the map */
return SendGetMap(); return SendGetMap();
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_WAIT(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_WAIT(Packet &p)
{ {
/* We set the internal wait state when requesting the map. */ /* We set the internal wait state when requesting the map. */
if (this->status != STATUS_MAP_WAIT) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status != STATUS_MAP_WAIT) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
/* But... only now we set the join status to waiting, instead of requesting. */ /* But... only now we set the join status to waiting, instead of requesting. */
_network_join_status = NETWORK_JOIN_STATUS_WAITING; _network_join_status = NETWORK_JOIN_STATUS_WAITING;
_network_join_waiting = p->Recv_uint8(); _network_join_waiting = p.Recv_uint8();
SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN); SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_BEGIN(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_BEGIN(Packet &p)
{ {
if (this->status < STATUS_AUTHORIZED || this->status >= STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status < STATUS_AUTHORIZED || this->status >= STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
this->status = STATUS_MAP; this->status = STATUS_MAP;
@ -986,7 +984,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_BEGIN(Packe
this->savegame = std::make_shared<PacketReader>(); this->savegame = std::make_shared<PacketReader>();
_frame_counter = _frame_counter_server = _frame_counter_max = p->Recv_uint32(); _frame_counter = _frame_counter_server = _frame_counter_max = p.Recv_uint32();
_network_join_bytes = 0; _network_join_bytes = 0;
_network_join_bytes_total = 0; _network_join_bytes_total = 0;
@ -997,18 +995,18 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_BEGIN(Packe
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_SIZE(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_SIZE(Packet &p)
{ {
if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
if (this->savegame == nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->savegame == nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
_network_join_bytes_total = p->Recv_uint32(); _network_join_bytes_total = p.Recv_uint32();
SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN); SetWindowDirty(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN);
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DATA(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DATA(Packet &p)
{ {
if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
if (this->savegame == nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->savegame == nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
@ -1022,7 +1020,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DATA(Packet
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DONE(Packet *) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DONE(Packet &)
{ {
if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status != STATUS_MAP) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
if (this->savegame == nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->savegame == nullptr) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
@ -1080,24 +1078,24 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DONE(Packet
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_FRAME(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_FRAME(Packet &p)
{ {
if (this->status == STATUS_CLOSING) return NETWORK_RECV_STATUS_OKAY; if (this->status == STATUS_CLOSING) return NETWORK_RECV_STATUS_OKAY;
if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
_frame_counter_server = p->Recv_uint32(); _frame_counter_server = p.Recv_uint32();
_frame_counter_max = p->Recv_uint32(); _frame_counter_max = p.Recv_uint32();
#ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME #ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
/* Test if the server supports this option /* Test if the server supports this option
* and if we are at the frame the server is */ * and if we are at the frame the server is */
if (p->CanReadFromPacket(4 + 8)) { if (p.CanReadFromPacket(4 + 8)) {
_sync_frame = _frame_counter_server; _sync_frame = _frame_counter_server;
_sync_seed_1 = p->Recv_uint32(); _sync_seed_1 = p.Recv_uint32();
_sync_state_checksum = p->Recv_uint64(); _sync_state_checksum = p.Recv_uint64();
} }
#endif #endif
/* Receive the token. */ /* Receive the token. */
if (p->CanReadFromPacket(sizeof(uint8_t))) this->token = p->Recv_uint8(); if (p.CanReadFromPacket(sizeof(uint8_t))) this->token = p.Recv_uint8();
DEBUG(net, 7, "Received FRAME %d", _frame_counter_server); DEBUG(net, 7, "Received FRAME %d", _frame_counter_server);
@ -1112,39 +1110,39 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_FRAME(Packet *p
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_SYNC(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_SYNC(Packet &p)
{ {
if (this->status == STATUS_CLOSING) return NETWORK_RECV_STATUS_OKAY; if (this->status == STATUS_CLOSING) return NETWORK_RECV_STATUS_OKAY;
if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
_sync_frame = p->Recv_uint32(); _sync_frame = p.Recv_uint32();
_sync_seed_1 = p->Recv_uint32(); _sync_seed_1 = p.Recv_uint32();
_sync_state_checksum = p->Recv_uint64(); _sync_state_checksum = p.Recv_uint64();
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_COMMAND(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_COMMAND(Packet &p)
{ {
if (this->status == STATUS_CLOSING) return NETWORK_RECV_STATUS_OKAY; if (this->status == STATUS_CLOSING) return NETWORK_RECV_STATUS_OKAY;
if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
CommandPacket cp; CommandPacket cp;
const char *err = this->ReceiveCommand(p, &cp); const char *err = this->ReceiveCommand(p, cp);
cp.frame = p->Recv_uint32(); cp.frame = p.Recv_uint32();
cp.my_cmd = p->Recv_bool(); cp.my_cmd = p.Recv_bool();
if (err != nullptr) { if (err != nullptr) {
IConsolePrintF(CC_ERROR, "WARNING: %s from server, dropping...", err); IConsolePrintF(CC_ERROR, "WARNING: %s from server, dropping...", err);
return NETWORK_RECV_STATUS_MALFORMED_PACKET; return NETWORK_RECV_STATUS_MALFORMED_PACKET;
} }
this->incoming_queue.Append(std::move(cp)); this->incoming_queue.push_back(std::move(cp));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHAT(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHAT(Packet &p)
{ {
if (this->status == STATUS_CLOSING) return NETWORK_RECV_STATUS_OKAY; if (this->status == STATUS_CLOSING) return NETWORK_RECV_STATUS_OKAY;
if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
@ -1152,10 +1150,10 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHAT(Packet *p)
std::string name; std::string name;
const NetworkClientInfo *ci = nullptr, *ci_to; const NetworkClientInfo *ci = nullptr, *ci_to;
NetworkAction action = (NetworkAction)p->Recv_uint8(); NetworkAction action = (NetworkAction)p.Recv_uint8();
ClientID client_id = (ClientID)p->Recv_uint32(); ClientID client_id = (ClientID)p.Recv_uint32();
bool self_send = p->Recv_bool(); bool self_send = p.Recv_bool();
std::string msg = p->Recv_string(NETWORK_CHAT_LENGTH); std::string msg = p.Recv_string(NETWORK_CHAT_LENGTH);
NetworkTextMessageData data; NetworkTextMessageData data;
data.recv(p); data.recv(p);
@ -1199,14 +1197,14 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CHAT(Packet *p)
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_EXTERNAL_CHAT(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_EXTERNAL_CHAT(Packet &p)
{ {
if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status != STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
std::string source = p->Recv_string(NETWORK_CHAT_LENGTH); std::string source = p.Recv_string(NETWORK_CHAT_LENGTH);
TextColour colour = (TextColour)p->Recv_uint16(); TextColour colour = (TextColour)p.Recv_uint16();
std::string user = p->Recv_string(NETWORK_CHAT_LENGTH); std::string user = p.Recv_string(NETWORK_CHAT_LENGTH);
std::string msg = p->Recv_string(NETWORK_CHAT_LENGTH); std::string msg = p.Recv_string(NETWORK_CHAT_LENGTH);
if (!IsValidConsoleColour(colour)) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (!IsValidConsoleColour(colour)) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
@ -1215,16 +1213,16 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_EXTERNAL_CHAT(P
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR_QUIT(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR_QUIT(Packet &p)
{ {
if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
ClientID client_id = (ClientID)p->Recv_uint32(); ClientID client_id = (ClientID)p.Recv_uint32();
if (client_id == _network_own_client_id) return NETWORK_RECV_STATUS_OKAY; // do not try to clear our own client info if (client_id == _network_own_client_id) return NETWORK_RECV_STATUS_OKAY; // do not try to clear our own client info
NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id); NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
if (ci != nullptr) { if (ci != nullptr) {
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, "", GetNetworkErrorMsg((NetworkErrorCode)p->Recv_uint8())); NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, "", GetNetworkErrorMsg((NetworkErrorCode)p.Recv_uint8()));
delete ci; delete ci;
} }
@ -1233,20 +1231,20 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR_QUIT(Pack
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_DESYNC_LOG(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_DESYNC_LOG(Packet &p)
{ {
uint size = p->Recv_uint16(); uint size = p.Recv_uint16();
this->server_desync_log.resize(this->server_desync_log.size() + size); this->server_desync_log.resize(this->server_desync_log.size() + size);
p->Recv_binary((byte *)(this->server_desync_log.data() + this->server_desync_log.size() - size), size); p.Recv_binary((byte *)(this->server_desync_log.data() + this->server_desync_log.size() - size), size);
DEBUG(net, 2, "Received %u bytes of server desync log", size); DEBUG(net, 2, "Received %u bytes of server desync log", size);
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_QUIT(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_QUIT(Packet &p)
{ {
if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
ClientID client_id = (ClientID)p->Recv_uint32(); ClientID client_id = (ClientID)p.Recv_uint32();
NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id); NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
if (ci != nullptr) { if (ci != nullptr) {
@ -1262,11 +1260,11 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_QUIT(Packet *p)
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_JOIN(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_JOIN(Packet &p)
{ {
if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
ClientID client_id = (ClientID)p->Recv_uint32(); ClientID client_id = (ClientID)p.Recv_uint32();
NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id); NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
if (ci != nullptr) { if (ci != nullptr) {
@ -1278,7 +1276,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_JOIN(Packet *p)
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_SHUTDOWN(Packet *) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_SHUTDOWN(Packet &)
{ {
/* Only when we're trying to join we really /* Only when we're trying to join we really
* care about the server shutting down. */ * care about the server shutting down. */
@ -1291,7 +1289,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_SHUTDOWN(Packet
return NETWORK_RECV_STATUS_SERVER_ERROR; return NETWORK_RECV_STATUS_SERVER_ERROR;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_NEWGAME(Packet *) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_NEWGAME(Packet &)
{ {
/* Only when we're trying to join we really /* Only when we're trying to join we really
* care about the server shutting down. */ * care about the server shutting down. */
@ -1308,21 +1306,21 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_NEWGAME(Packet
return NETWORK_RECV_STATUS_SERVER_ERROR; return NETWORK_RECV_STATUS_SERVER_ERROR;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_RCON(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_RCON(Packet &p)
{ {
if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
if (!p->CanReadFromPacket(1)) { if (!p.CanReadFromPacket(1)) {
IConsolePrint(CC_ERROR, "Access Denied"); IConsolePrint(CC_ERROR, "Access Denied");
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
std::array<uint8_t, 24> nonce; std::array<uint8_t, 24> nonce;
std::array<uint8_t, 16> mac; std::array<uint8_t, 16> mac;
p->Recv_binary(nonce); p.Recv_binary(nonce);
p->Recv_binary(mac); p.Recv_binary(mac);
std::vector<byte> message = p->Recv_binary(p->RemainingBytesToTransfer()); std::vector<byte> message = p.Recv_binary(p.RemainingBytesToTransfer());
static_assert(std::tuple_size<decltype(NetworkSharedSecrets::shared_data)>::value == 64); static_assert(std::tuple_size<decltype(NetworkSharedSecrets::shared_data)>::value == 64);
if (crypto_aead_unlock(message.data(), mac.data(), this->last_rcon_shared_secrets.shared_data.data() + 32, nonce.data(), nullptr, 0, message.data(), message.size()) == 0) { if (crypto_aead_unlock(message.data(), mac.data(), this->last_rcon_shared_secrets.shared_data.data() + 32, nonce.data(), nullptr, 0, message.data(), message.size()) == 0) {
@ -1337,13 +1335,13 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_RCON(Packet *p)
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MOVE(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MOVE(Packet &p)
{ {
if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status < STATUS_AUTHORIZED) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
/* Nothing more in this packet... */ /* Nothing more in this packet... */
ClientID client_id = (ClientID)p->Recv_uint32(); ClientID client_id = (ClientID)p.Recv_uint32();
CompanyID company_id = (CompanyID)p->Recv_uint8(); CompanyID company_id = (CompanyID)p.Recv_uint8();
if (client_id == 0) { if (client_id == 0) {
/* definitely an invalid client id, debug message and do nothing. */ /* definitely an invalid client id, debug message and do nothing. */
@ -1365,33 +1363,33 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MOVE(Packet *p)
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CONFIG_UPDATE(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_CONFIG_UPDATE(Packet &p)
{ {
if (this->status < STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status < STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
_network_server_max_companies = p->Recv_uint8(); _network_server_max_companies = p.Recv_uint8();
_network_server_name = p->Recv_string(NETWORK_NAME_LENGTH); _network_server_name = p.Recv_string(NETWORK_NAME_LENGTH);
SetWindowClassesDirty(WC_CLIENT_LIST); SetWindowClassesDirty(WC_CLIENT_LIST);
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_COMPANY_UPDATE(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_COMPANY_UPDATE(Packet &p)
{ {
if (this->status < STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status < STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
static_assert(sizeof(_network_company_passworded) <= sizeof(uint16_t)); static_assert(sizeof(_network_company_passworded) <= sizeof(uint16_t));
_network_company_passworded = p->Recv_uint16(); _network_company_passworded = p.Recv_uint16();
SetWindowClassesDirty(WC_COMPANY); SetWindowClassesDirty(WC_COMPANY);
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_SETTINGS_ACCESS(Packet *p) NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_SETTINGS_ACCESS(Packet &p)
{ {
if (this->status < STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET; if (this->status < STATUS_ACTIVE) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
_network_settings_access = p->Recv_bool(); _network_settings_access = p.Recv_bool();
CloseWindowById(WC_CHEATS, 0); CloseWindowById(WC_CHEATS, 0);
ReInitAllWindows(false); ReInitAllWindows(false);

@ -50,35 +50,35 @@ protected:
friend void NetworkClose(bool close_admins); friend void NetworkClose(bool close_admins);
static ClientNetworkGameSocketHandler *my_client; ///< This is us! static ClientNetworkGameSocketHandler *my_client; ///< This is us!
NetworkRecvStatus Receive_SERVER_FULL(Packet *p) override; NetworkRecvStatus Receive_SERVER_FULL(Packet &p) override;
NetworkRecvStatus Receive_SERVER_BANNED(Packet *p) override; NetworkRecvStatus Receive_SERVER_BANNED(Packet &p) override;
NetworkRecvStatus Receive_SERVER_ERROR(Packet *p) override; NetworkRecvStatus Receive_SERVER_ERROR(Packet &p) override;
NetworkRecvStatus Receive_SERVER_CLIENT_INFO(Packet *p) override; NetworkRecvStatus Receive_SERVER_CLIENT_INFO(Packet &p) override;
NetworkRecvStatus Receive_SERVER_NEED_GAME_PASSWORD(Packet *p) override; NetworkRecvStatus Receive_SERVER_NEED_GAME_PASSWORD(Packet &p) override;
NetworkRecvStatus Receive_SERVER_NEED_COMPANY_PASSWORD(Packet *p) override; NetworkRecvStatus Receive_SERVER_NEED_COMPANY_PASSWORD(Packet &p) override;
NetworkRecvStatus Receive_SERVER_SETTINGS_ACCESS(Packet *p) override; NetworkRecvStatus Receive_SERVER_SETTINGS_ACCESS(Packet &p) override;
NetworkRecvStatus Receive_SERVER_WELCOME(Packet *p) override; NetworkRecvStatus Receive_SERVER_WELCOME(Packet &p) override;
NetworkRecvStatus Receive_SERVER_WAIT(Packet *p) override; NetworkRecvStatus Receive_SERVER_WAIT(Packet &p) override;
NetworkRecvStatus Receive_SERVER_MAP_BEGIN(Packet *p) override; NetworkRecvStatus Receive_SERVER_MAP_BEGIN(Packet &p) override;
NetworkRecvStatus Receive_SERVER_MAP_SIZE(Packet *p) override; NetworkRecvStatus Receive_SERVER_MAP_SIZE(Packet &p) override;
NetworkRecvStatus Receive_SERVER_MAP_DATA(Packet *p) override; NetworkRecvStatus Receive_SERVER_MAP_DATA(Packet &p) override;
NetworkRecvStatus Receive_SERVER_MAP_DONE(Packet *p) override; NetworkRecvStatus Receive_SERVER_MAP_DONE(Packet &p) override;
NetworkRecvStatus Receive_SERVER_JOIN(Packet *p) override; NetworkRecvStatus Receive_SERVER_JOIN(Packet &p) override;
NetworkRecvStatus Receive_SERVER_FRAME(Packet *p) override; NetworkRecvStatus Receive_SERVER_FRAME(Packet &p) override;
NetworkRecvStatus Receive_SERVER_SYNC(Packet *p) override; NetworkRecvStatus Receive_SERVER_SYNC(Packet &p) override;
NetworkRecvStatus Receive_SERVER_COMMAND(Packet *p) override; NetworkRecvStatus Receive_SERVER_COMMAND(Packet &p) override;
NetworkRecvStatus Receive_SERVER_CHAT(Packet *p) override; NetworkRecvStatus Receive_SERVER_CHAT(Packet &p) override;
NetworkRecvStatus Receive_SERVER_EXTERNAL_CHAT(Packet *p) override; NetworkRecvStatus Receive_SERVER_EXTERNAL_CHAT(Packet &p) override;
NetworkRecvStatus Receive_SERVER_QUIT(Packet *p) override; NetworkRecvStatus Receive_SERVER_QUIT(Packet &p) override;
NetworkRecvStatus Receive_SERVER_ERROR_QUIT(Packet *p) override; NetworkRecvStatus Receive_SERVER_ERROR_QUIT(Packet &p) override;
NetworkRecvStatus Receive_SERVER_DESYNC_LOG(Packet *p) override; NetworkRecvStatus Receive_SERVER_DESYNC_LOG(Packet &p) override;
NetworkRecvStatus Receive_SERVER_SHUTDOWN(Packet *p) override; NetworkRecvStatus Receive_SERVER_SHUTDOWN(Packet &p) override;
NetworkRecvStatus Receive_SERVER_NEWGAME(Packet *p) override; NetworkRecvStatus Receive_SERVER_NEWGAME(Packet &p) override;
NetworkRecvStatus Receive_SERVER_RCON(Packet *p) override; NetworkRecvStatus Receive_SERVER_RCON(Packet &p) override;
NetworkRecvStatus Receive_SERVER_CHECK_NEWGRFS(Packet *p) override; NetworkRecvStatus Receive_SERVER_CHECK_NEWGRFS(Packet &p) override;
NetworkRecvStatus Receive_SERVER_MOVE(Packet *p) override; NetworkRecvStatus Receive_SERVER_MOVE(Packet &p) override;
NetworkRecvStatus Receive_SERVER_COMPANY_UPDATE(Packet *p) override; NetworkRecvStatus Receive_SERVER_COMPANY_UPDATE(Packet &p) override;
NetworkRecvStatus Receive_SERVER_CONFIG_UPDATE(Packet *p) override; NetworkRecvStatus Receive_SERVER_CONFIG_UPDATE(Packet &p) override;
static NetworkRecvStatus SendNewGRFsOk(); static NetworkRecvStatus SendNewGRFsOk();
static NetworkRecvStatus SendGetMap(); static NetworkRecvStatus SendGetMap();
@ -103,7 +103,7 @@ public:
} }
static NetworkRecvStatus SendJoin(); static NetworkRecvStatus SendJoin();
static NetworkRecvStatus SendCommand(const CommandPacket *cp); static NetworkRecvStatus SendCommand(const CommandPacket &cp);
static NetworkRecvStatus SendError(NetworkErrorCode errorno, NetworkRecvStatus recvstatus = NETWORK_RECV_STATUS_OKAY); static NetworkRecvStatus SendError(NetworkErrorCode errorno, NetworkRecvStatus recvstatus = NETWORK_RECV_STATUS_OKAY);
static NetworkRecvStatus SendDesyncLog(const std::string &log); static NetworkRecvStatus SendDesyncLog(const std::string &log);
static NetworkRecvStatus SendDesyncMessage(const char *msg); static NetworkRecvStatus SendDesyncMessage(const char *msg);

@ -58,78 +58,6 @@ static CommandCallback * const _callback_table[] = {
/* 0x23 */ CcSwapSchDispatchSchedules, /* 0x23 */ CcSwapSchDispatchSchedules,
}; };
/**
* Append a CommandPacket at the end of the queue.
* @param p The packet to append to the queue.
* @note A new instance of the CommandPacket will be made.
*/
void CommandQueue::Append(CommandPacket *p, bool move)
{
CommandPacket *add = new CommandPacket();
if (move) {
*add = std::move(*p);
} else {
*add = *p;
}
add->next = nullptr;
if (this->first == nullptr) {
this->first = add;
} else {
this->last->next = add;
}
this->last = add;
this->count++;
}
/**
* Return the first item in the queue and remove it from the queue.
* @param ignore_paused Whether to ignore commands that may not be executed while paused.
* @return the first item in the queue.
*/
std::unique_ptr<CommandPacket> CommandQueue::Pop(bool ignore_paused)
{
CommandPacket **prev = &this->first;
CommandPacket *ret = this->first;
CommandPacket *prev_item = nullptr;
if (ignore_paused && _pause_mode != PM_UNPAUSED) {
while (ret != nullptr && !IsCommandAllowedWhilePaused(ret->cmd)) {
prev_item = ret;
prev = &ret->next;
ret = ret->next;
}
}
if (ret != nullptr) {
if (ret == this->last) this->last = prev_item;
*prev = ret->next;
this->count--;
}
return std::unique_ptr<CommandPacket>(ret);
}
/**
* Return the first item in the queue, but don't remove it.
* @param ignore_paused Whether to ignore commands that may not be executed while paused.
* @return the first item in the queue.
*/
CommandPacket *CommandQueue::Peek(bool ignore_paused)
{
if (!ignore_paused || _pause_mode == PM_UNPAUSED) return this->first;
for (CommandPacket *p = this->first; p != nullptr; p = p->next) {
if (IsCommandAllowedWhilePaused(p->cmd)) return p;
}
return nullptr;
}
/** Free everything that is in the queue. */
void CommandQueue::Free()
{
std::unique_ptr<CommandPacket> cp;
while ((cp = this->Pop()) != nullptr) {}
assert(this->count == 0);
}
/** Local queue of packets waiting for handling. */ /** Local queue of packets waiting for handling. */
static CommandQueue _local_wait_queue; static CommandQueue _local_wait_queue;
/** Local queue of packets waiting for execution. */ /** Local queue of packets waiting for execution. */
@ -177,14 +105,14 @@ void NetworkSendCommand(TileIndex tile, uint32_t p1, uint32_t p2, uint64_t p3, u
c.frame = _frame_counter_max + 1; c.frame = _frame_counter_max + 1;
c.my_cmd = true; c.my_cmd = true;
_local_wait_queue.Append(std::move(c)); _local_wait_queue.push_back(std::move(c));
return; return;
} }
c.frame = 0; // The client can't tell which frame, so just make it 0 c.frame = 0; // The client can't tell which frame, so just make it 0
/* Clients send their command to the server and forget all about the packet */ /* Clients send their command to the server and forget all about the packet */
MyClient::SendCommand(&c); MyClient::SendCommand(c);
} }
/** /**
@ -198,10 +126,9 @@ void NetworkSendCommand(TileIndex tile, uint32_t p1, uint32_t p2, uint64_t p3, u
*/ */
void NetworkSyncCommandQueue(NetworkClientSocket *cs) void NetworkSyncCommandQueue(NetworkClientSocket *cs)
{ {
for (CommandPacket *p = _local_execution_queue.Peek(); p != nullptr; p = p->next) { for (CommandPacket &p : _local_execution_queue) {
CommandPacket c = *p; CommandPacket &c = cs->outgoing_queue.emplace_back(p);
c.callback = nullptr; c.callback = nullptr;
cs->outgoing_queue.Append(std::move(c));
} }
} }
@ -216,8 +143,8 @@ void NetworkExecuteLocalCommandQueue()
CommandQueue &queue = (_network_server ? _local_execution_queue : ClientNetworkGameSocketHandler::my_client->incoming_queue); CommandQueue &queue = (_network_server ? _local_execution_queue : ClientNetworkGameSocketHandler::my_client->incoming_queue);
bool record_sync_event = false; bool record_sync_event = false;
CommandPacket *cp; auto cp = queue.begin();
while ((cp = queue.Peek()) != nullptr) { for (; cp != queue.end(); cp++) {
/* The queue is always in order, which means /* The queue is always in order, which means
* that the first element will be executed first. */ * that the first element will be executed first. */
if (_frame_counter < cp->frame) break; if (_frame_counter < cp->frame) break;
@ -232,12 +159,11 @@ void NetworkExecuteLocalCommandQueue()
_current_company = cp->company; _current_company = cp->company;
_cmd_client_id = cp->client_id; _cmd_client_id = cp->client_id;
cp->cmd |= CMD_NETWORK_COMMAND; cp->cmd |= CMD_NETWORK_COMMAND;
DoCommandP(cp, cp->my_cmd); DoCommandP(&(*cp), cp->my_cmd);
queue.Pop();
record_sync_event = true; record_sync_event = true;
} }
queue.erase(queue.begin(), cp);
/* Local company may have changed, so we should not restore the old value */ /* Local company may have changed, so we should not restore the old value */
_current_company = _local_company; _current_company = _local_company;
@ -251,8 +177,8 @@ void NetworkExecuteLocalCommandQueue()
*/ */
void NetworkFreeLocalCommandQueue() void NetworkFreeLocalCommandQueue()
{ {
_local_wait_queue.Free(); _local_wait_queue.clear();
_local_execution_queue.Free(); _local_execution_queue.clear();
} }
/** /**
@ -271,13 +197,13 @@ static void DistributeCommandPacket(CommandPacket &cp, const NetworkClientSocket
* first place. This filters that out. */ * first place. This filters that out. */
cp.callback = (cs != owner) ? nullptr : callback; cp.callback = (cs != owner) ? nullptr : callback;
cp.my_cmd = (cs == owner); cp.my_cmd = (cs == owner);
cs->outgoing_queue.Append(cp); cs->outgoing_queue.push_back(cp);
} }
} }
cp.callback = (nullptr != owner) ? nullptr : callback; cp.callback = (nullptr != owner) ? nullptr : callback;
cp.my_cmd = (nullptr == owner); cp.my_cmd = (nullptr == owner);
_local_execution_queue.Append(cp); _local_execution_queue.push_back(cp);
} }
/** /**
@ -285,7 +211,7 @@ static void DistributeCommandPacket(CommandPacket &cp, const NetworkClientSocket
* @param queue The queue of commands that has to be distributed. * @param queue The queue of commands that has to be distributed.
* @param owner The client that owns the commands, * @param owner The client that owns the commands,
*/ */
static void DistributeQueue(CommandQueue *queue, const NetworkClientSocket *owner) static void DistributeQueue(CommandQueue &queue, const NetworkClientSocket *owner)
{ {
#ifdef DEBUG_DUMP_COMMANDS #ifdef DEBUG_DUMP_COMMANDS
/* When replaying we do not want this limitation. */ /* When replaying we do not want this limitation. */
@ -298,10 +224,20 @@ static void DistributeQueue(CommandQueue *queue, const NetworkClientSocket *owne
} }
#endif #endif
std::unique_ptr<CommandPacket> cp; /* Not technically the most performant way, but consider clients rarely click more than once per tick. */
while (--to_go >= 0 && (cp = queue->Pop(true)) != nullptr) { for (auto cp = queue.begin(); cp != queue.end(); /* removing some items */) {
/* Do not distribute commands when paused and the command is not allowed while paused. */
if (_pause_mode != PM_UNPAUSED && !IsCommandAllowedWhilePaused(cp->cmd)) {
++cp;
continue;
}
/* Limit the number of commands per client per tick. */
if (--to_go < 0) break;
DistributeCommandPacket(*cp, owner); DistributeCommandPacket(*cp, owner);
NetworkAdminCmdLogging(owner, cp.get()); NetworkAdminCmdLogging(owner, *cp);
cp = queue.erase(cp);
} }
} }
@ -309,11 +245,11 @@ static void DistributeQueue(CommandQueue *queue, const NetworkClientSocket *owne
void NetworkDistributeCommands() void NetworkDistributeCommands()
{ {
/* First send the server's commands. */ /* First send the server's commands. */
DistributeQueue(&_local_wait_queue, nullptr); DistributeQueue(_local_wait_queue, nullptr);
/* Then send the queues of the others. */ /* Then send the queues of the others. */
for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) { for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
DistributeQueue(&cs->incoming_queue, cs); DistributeQueue(cs->incoming_queue, cs);
} }
} }
@ -323,33 +259,33 @@ void NetworkDistributeCommands()
* @param cp the struct to write the data to. * @param cp the struct to write the data to.
* @return an error message. When nullptr there has been no error. * @return an error message. When nullptr there has been no error.
*/ */
const char *NetworkGameSocketHandler::ReceiveCommand(Packet *p, CommandPacket *cp) const char *NetworkGameSocketHandler::ReceiveCommand(Packet &p, CommandPacket &cp)
{ {
cp->company = (CompanyID)p->Recv_uint8(); cp.company = (CompanyID)p.Recv_uint8();
cp->cmd = p->Recv_uint32(); cp.cmd = p.Recv_uint32();
if (!IsValidCommand(cp->cmd)) return "invalid command"; if (!IsValidCommand(cp.cmd)) return "invalid command";
if (GetCommandFlags(cp->cmd) & CMD_OFFLINE) return "single-player only command"; if (GetCommandFlags(cp.cmd) & CMD_OFFLINE) return "single-player only command";
if ((cp->cmd & CMD_FLAGS_MASK) != 0) return "invalid command flag"; if ((cp.cmd & CMD_FLAGS_MASK) != 0) return "invalid command flag";
cp->p1 = p->Recv_uint32(); cp.p1 = p.Recv_uint32();
cp->p2 = p->Recv_uint32(); cp.p2 = p.Recv_uint32();
cp->p3 = p->Recv_uint64(); cp.p3 = p.Recv_uint64();
cp->tile = p->Recv_uint32(); cp.tile = p.Recv_uint32();
StringValidationSettings settings = (!_network_server && GetCommandFlags(cp->cmd) & CMD_STR_CTRL) != 0 ? SVS_ALLOW_CONTROL_CODE | SVS_REPLACE_WITH_QUESTION_MARK : SVS_REPLACE_WITH_QUESTION_MARK; StringValidationSettings settings = (!_network_server && GetCommandFlags(cp.cmd) & CMD_STR_CTRL) != 0 ? SVS_ALLOW_CONTROL_CODE | SVS_REPLACE_WITH_QUESTION_MARK : SVS_REPLACE_WITH_QUESTION_MARK;
p->Recv_string(cp->text, settings); p.Recv_string(cp.text, settings);
byte callback = p->Recv_uint8(); byte callback = p.Recv_uint8();
if (callback >= lengthof(_callback_table)) return "invalid callback"; if (callback >= lengthof(_callback_table)) return "invalid callback";
cp->callback = _callback_table[callback]; cp.callback = _callback_table[callback];
uint16_t aux_data_size = p->Recv_uint16(); uint16_t aux_data_size = p.Recv_uint16();
if (aux_data_size > 0 && p->CanReadFromPacket(aux_data_size, true)) { if (aux_data_size > 0 && p.CanReadFromPacket(aux_data_size, true)) {
CommandAuxiliarySerialised *aux_data = new CommandAuxiliarySerialised(); CommandAuxiliarySerialised *aux_data = new CommandAuxiliarySerialised();
cp->aux_data.reset(aux_data); cp.aux_data.reset(aux_data);
aux_data->serialised_data.resize(aux_data_size); aux_data->serialised_data.resize(aux_data_size);
p->Recv_binary((aux_data->serialised_data.data()), aux_data_size); p.Recv_binary((aux_data->serialised_data.data()), aux_data_size);
} }
return nullptr; return nullptr;
@ -360,32 +296,32 @@ const char *NetworkGameSocketHandler::ReceiveCommand(Packet *p, CommandPacket *c
* @param p the packet to send it in. * @param p the packet to send it in.
* @param cp the packet to actually send. * @param cp the packet to actually send.
*/ */
void NetworkGameSocketHandler::SendCommand(Packet *p, const CommandPacket *cp) void NetworkGameSocketHandler::SendCommand(Packet &p, const CommandPacket &cp)
{ {
p->Send_uint8 (cp->company); p.Send_uint8 (cp.company);
p->Send_uint32(cp->cmd); p.Send_uint32(cp.cmd);
p->Send_uint32(cp->p1); p.Send_uint32(cp.p1);
p->Send_uint32(cp->p2); p.Send_uint32(cp.p2);
p->Send_uint64(cp->p3); p.Send_uint64(cp.p3);
p->Send_uint32(cp->tile); p.Send_uint32(cp.tile);
p->Send_string(cp->text.c_str()); p.Send_string(cp.text.c_str());
byte callback = 0; byte callback = 0;
while (callback < lengthof(_callback_table) && _callback_table[callback] != cp->callback) { while (callback < lengthof(_callback_table) && _callback_table[callback] != cp.callback) {
callback++; callback++;
} }
if (callback == lengthof(_callback_table)) { if (callback == lengthof(_callback_table)) {
DEBUG(net, 0, "Unknown callback for command; no callback sent (command: %d)", cp->cmd); DEBUG(net, 0, "Unknown callback for command; no callback sent (command: %d)", cp.cmd);
callback = 0; // _callback_table[0] == nullptr callback = 0; // _callback_table[0] == nullptr
} }
p->Send_uint8 (callback); p.Send_uint8 (callback);
size_t aux_data_size_pos = p->Size(); size_t aux_data_size_pos = p.Size();
p->Send_uint16(0); p.Send_uint16(0);
if (cp->aux_data != nullptr) { if (cp.aux_data != nullptr) {
CommandSerialisationBuffer serialiser(p->GetSerialisationBuffer(), p->GetSerialisationLimit()); CommandSerialisationBuffer serialiser(p.GetSerialisationBuffer(), p.GetSerialisationLimit());
cp->aux_data->Serialise(serialiser); cp.aux_data->Serialise(serialiser);
p->WriteAtOffset_uint16(aux_data_size_pos, (uint16_t)(p->Size() - aux_data_size_pos - 2)); p.WriteAtOffset_uint16(aux_data_size_pos, (uint16_t)(p.Size() - aux_data_size_pos - 2));
} }
} }

@ -49,34 +49,34 @@ static bool HasGRFConfig(const ContentInfo *ci, bool md5sum)
*/ */
typedef bool (*HasProc)(const ContentInfo *ci, bool md5sum); typedef bool (*HasProc)(const ContentInfo *ci, bool md5sum);
bool ClientNetworkContentSocketHandler::Receive_SERVER_INFO(Packet *p) bool ClientNetworkContentSocketHandler::Receive_SERVER_INFO(Packet &p)
{ {
ContentInfo *ci = new ContentInfo(); ContentInfo *ci = new ContentInfo();
ci->type = (ContentType)p->Recv_uint8(); ci->type = (ContentType)p.Recv_uint8();
ci->id = (ContentID)p->Recv_uint32(); ci->id = (ContentID)p.Recv_uint32();
ci->filesize = p->Recv_uint32(); ci->filesize = p.Recv_uint32();
ci->name = p->Recv_string(NETWORK_CONTENT_NAME_LENGTH); ci->name = p.Recv_string(NETWORK_CONTENT_NAME_LENGTH);
ci->version = p->Recv_string(NETWORK_CONTENT_VERSION_LENGTH); ci->version = p.Recv_string(NETWORK_CONTENT_VERSION_LENGTH);
ci->url = p->Recv_string(NETWORK_CONTENT_URL_LENGTH); ci->url = p.Recv_string(NETWORK_CONTENT_URL_LENGTH);
ci->description = p->Recv_string(NETWORK_CONTENT_DESC_LENGTH, SVS_REPLACE_WITH_QUESTION_MARK | SVS_ALLOW_NEWLINE); ci->description = p.Recv_string(NETWORK_CONTENT_DESC_LENGTH, SVS_REPLACE_WITH_QUESTION_MARK | SVS_ALLOW_NEWLINE);
ci->unique_id = p->Recv_uint32(); ci->unique_id = p.Recv_uint32();
for (size_t j = 0; j < ci->md5sum.size(); j++) { for (size_t j = 0; j < ci->md5sum.size(); j++) {
ci->md5sum[j] = p->Recv_uint8(); ci->md5sum[j] = p.Recv_uint8();
} }
uint dependency_count = p->Recv_uint8(); uint dependency_count = p.Recv_uint8();
ci->dependencies.reserve(dependency_count); ci->dependencies.reserve(dependency_count);
for (uint i = 0; i < dependency_count; i++) { for (uint i = 0; i < dependency_count; i++) {
ContentID cid = (ContentID)p->Recv_uint32(); ContentID dependency_cid = (ContentID)p.Recv_uint32();
ci->dependencies.push_back(cid); ci->dependencies.push_back(dependency_cid);
this->reverse_dependency_map.insert({ cid, ci->id }); this->reverse_dependency_map.insert({ dependency_cid, ci->id });
} }
uint tag_count = p->Recv_uint8(); uint tag_count = p.Recv_uint8();
ci->tags.reserve(tag_count); ci->tags.reserve(tag_count);
for (uint i = 0; i < tag_count; i++) ci->tags.push_back(p->Recv_string(NETWORK_CONTENT_TAG_LENGTH)); for (uint i = 0; i < tag_count; i++) ci->tags.push_back(p.Recv_string(NETWORK_CONTENT_TAG_LENGTH));
if (!ci->IsValid()) { if (!ci->IsValid()) {
delete ci; delete ci;
@ -204,7 +204,7 @@ void ClientNetworkContentSocketHandler::RequestContentList(ContentType type)
this->Connect(); this->Connect();
Packet *p = new Packet(PACKET_CONTENT_CLIENT_INFO_LIST); auto p = std::make_unique<Packet>(PACKET_CONTENT_CLIENT_INFO_LIST);
p->Send_uint8 ((byte)type); p->Send_uint8 ((byte)type);
p->Send_uint32(0xffffffff); p->Send_uint32(0xffffffff);
p->Send_uint8 (2); p->Send_uint8 (2);
@ -220,7 +220,7 @@ void ClientNetworkContentSocketHandler::RequestContentList(ContentType type)
p->Send_string("jgrpp"); p->Send_string("jgrpp");
p->Send_string(_openttd_release_version); p->Send_string(_openttd_release_version);
this->SendPacket(p); this->SendPacket(std::move(p));
} }
/** /**
@ -239,14 +239,14 @@ void ClientNetworkContentSocketHandler::RequestContentList(uint count, const Con
* The rest of the packet can be used for the IDs. */ * The rest of the packet can be used for the IDs. */
uint p_count = std::min<uint>(count, (TCP_MTU - sizeof(PacketSize) - sizeof(byte) - sizeof(uint16_t)) / sizeof(uint32_t)); uint p_count = std::min<uint>(count, (TCP_MTU - sizeof(PacketSize) - sizeof(byte) - sizeof(uint16_t)) / sizeof(uint32_t));
Packet *p = new Packet(PACKET_CONTENT_CLIENT_INFO_ID, TCP_MTU); auto p = std::make_unique<Packet>(PACKET_CONTENT_CLIENT_INFO_ID, TCP_MTU);
p->Send_uint16(p_count); p->Send_uint16(p_count);
for (uint i = 0; i < p_count; i++) { for (uint i = 0; i < p_count; i++) {
p->Send_uint32(content_ids[i]); p->Send_uint32(content_ids[i]);
} }
this->SendPacket(p); this->SendPacket(std::move(p));
count -= p_count; count -= p_count;
content_ids += p_count; content_ids += p_count;
} }
@ -269,7 +269,7 @@ void ClientNetworkContentSocketHandler::RequestContentList(ContentVector *cv, bo
uint offset = 0; uint offset = 0;
while (cv->size() > offset) { while (cv->size() > offset) {
Packet *p = new Packet(send_md5sum ? PACKET_CONTENT_CLIENT_INFO_EXTID_MD5 : PACKET_CONTENT_CLIENT_INFO_EXTID, TCP_MTU); auto p = std::make_unique<Packet>(send_md5sum ? PACKET_CONTENT_CLIENT_INFO_EXTID_MD5 : PACKET_CONTENT_CLIENT_INFO_EXTID, TCP_MTU);
const uint to_send = std::min<uint>(static_cast<uint>(cv->size() - offset), max_per_packet); const uint to_send = std::min<uint>(static_cast<uint>(cv->size() - offset), max_per_packet);
p->Send_uint8(static_cast<uint8_t>(to_send)); p->Send_uint8(static_cast<uint8_t>(to_send));
@ -284,7 +284,7 @@ void ClientNetworkContentSocketHandler::RequestContentList(ContentVector *cv, bo
} }
} }
this->SendPacket(p); this->SendPacket(std::move(p));
offset += to_send; offset += to_send;
} }
@ -371,14 +371,14 @@ void ClientNetworkContentSocketHandler::DownloadSelectedContentFallback(const Co
* The rest of the packet can be used for the IDs. */ * The rest of the packet can be used for the IDs. */
uint p_count = std::min<uint>(count, (TCP_MTU - sizeof(PacketSize) - sizeof(byte) - sizeof(uint16_t)) / sizeof(uint32_t)); uint p_count = std::min<uint>(count, (TCP_MTU - sizeof(PacketSize) - sizeof(byte) - sizeof(uint16_t)) / sizeof(uint32_t));
Packet *p = new Packet(PACKET_CONTENT_CLIENT_CONTENT, TCP_MTU); auto p = std::make_unique<Packet>(PACKET_CONTENT_CLIENT_CONTENT, TCP_MTU);
p->Send_uint16(p_count); p->Send_uint16(p_count);
for (uint i = 0; i < p_count; i++) { for (uint i = 0; i < p_count; i++) {
p->Send_uint32(content_ids[i]); p->Send_uint32(content_ids[i]);
} }
this->SendPacket(p); this->SendPacket(std::move(p));
count -= p_count; count -= p_count;
content_ids += p_count; content_ids += p_count;
} }
@ -483,16 +483,16 @@ static inline ssize_t TransferOutFWrite(FILE *file, const char *buffer, size_t a
return fwrite(buffer, 1, amount, file); return fwrite(buffer, 1, amount, file);
} }
bool ClientNetworkContentSocketHandler::Receive_SERVER_CONTENT(Packet *p) bool ClientNetworkContentSocketHandler::Receive_SERVER_CONTENT(Packet &p)
{ {
if (this->curFile == nullptr) { if (this->curFile == nullptr) {
delete this->curInfo; delete this->curInfo;
/* When we haven't opened a file this must be our first packet with metadata. */ /* When we haven't opened a file this must be our first packet with metadata. */
this->curInfo = new ContentInfo; this->curInfo = new ContentInfo;
this->curInfo->type = (ContentType)p->Recv_uint8(); this->curInfo->type = (ContentType)p.Recv_uint8();
this->curInfo->id = (ContentID)p->Recv_uint32(); this->curInfo->id = (ContentID)p.Recv_uint32();
this->curInfo->filesize = p->Recv_uint32(); this->curInfo->filesize = p.Recv_uint32();
this->curInfo->filename = p->Recv_string(NETWORK_CONTENT_FILENAME_LENGTH); this->curInfo->filename = p.Recv_string(NETWORK_CONTENT_FILENAME_LENGTH);
if (!this->BeforeDownload()) { if (!this->BeforeDownload()) {
this->CloseConnection(); this->CloseConnection();
@ -500,8 +500,8 @@ bool ClientNetworkContentSocketHandler::Receive_SERVER_CONTENT(Packet *p)
} }
} else { } else {
/* We have a file opened, thus are downloading internal content */ /* We have a file opened, thus are downloading internal content */
size_t toRead = p->RemainingBytesToTransfer(); size_t toRead = p.RemainingBytesToTransfer();
if (toRead != 0 && (size_t)p->TransferOut(TransferOutFWrite, this->curFile) != toRead) { if (toRead != 0 && (size_t)p.TransferOut(TransferOutFWrite, this->curFile) != toRead) {
CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_CONTENT_DOWNLOAD); CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_CONTENT_DOWNLOAD);
ShowErrorMessage(STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD, STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD_FILE_NOT_WRITABLE, WL_ERROR); ShowErrorMessage(STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD, STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD_FILE_NOT_WRITABLE, WL_ERROR);
this->CloseConnection(); this->CloseConnection();

@ -83,8 +83,8 @@ protected:
friend class NetworkContentConnecter; friend class NetworkContentConnecter;
bool Receive_SERVER_INFO(Packet *p) override; bool Receive_SERVER_INFO(Packet &p) override;
bool Receive_SERVER_CONTENT(Packet *p) override; bool Receive_SERVER_CONTENT(Packet &p) override;
ContentInfo *GetContent(ContentID cid); ContentInfo *GetContent(ContentID cid);
const ContentInfo *GetContent(ContentID cid) const { return const_cast<ClientNetworkContentSocketHandler *>(this)->GetContent(cid); } const ContentInfo *GetContent(ContentID cid) const { return const_cast<ClientNetworkContentSocketHandler *>(this)->GetContent(cid); }

@ -124,10 +124,10 @@ public:
} }
}; };
bool ClientNetworkCoordinatorSocketHandler::Receive_GC_ERROR(Packet *p) bool ClientNetworkCoordinatorSocketHandler::Receive_GC_ERROR(Packet &p)
{ {
NetworkCoordinatorErrorType error = (NetworkCoordinatorErrorType)p->Recv_uint8(); NetworkCoordinatorErrorType error = (NetworkCoordinatorErrorType)p.Recv_uint8();
std::string detail = p->Recv_string(NETWORK_ERROR_DETAIL_LENGTH); std::string detail = p.Recv_string(NETWORK_ERROR_DETAIL_LENGTH);
switch (error) { switch (error) {
case NETWORK_COORDINATOR_ERROR_UNKNOWN: case NETWORK_COORDINATOR_ERROR_UNKNOWN:
@ -174,14 +174,14 @@ bool ClientNetworkCoordinatorSocketHandler::Receive_GC_ERROR(Packet *p)
} }
} }
bool ClientNetworkCoordinatorSocketHandler::Receive_GC_REGISTER_ACK(Packet *p) bool ClientNetworkCoordinatorSocketHandler::Receive_GC_REGISTER_ACK(Packet &p)
{ {
/* Schedule sending an update. */ /* Schedule sending an update. */
this->next_update = std::chrono::steady_clock::now(); this->next_update = std::chrono::steady_clock::now();
_settings_client.network.server_invite_code = p->Recv_string(NETWORK_INVITE_CODE_LENGTH); _settings_client.network.server_invite_code = p.Recv_string(NETWORK_INVITE_CODE_LENGTH);
_settings_client.network.server_invite_code_secret = p->Recv_string(NETWORK_INVITE_CODE_SECRET_LENGTH); _settings_client.network.server_invite_code_secret = p.Recv_string(NETWORK_INVITE_CODE_SECRET_LENGTH);
_network_server_connection_type = (ConnectionType)p->Recv_uint8(); _network_server_connection_type = (ConnectionType)p.Recv_uint8();
if (_network_server_connection_type == CONNECTION_TYPE_ISOLATED) { if (_network_server_connection_type == CONNECTION_TYPE_ISOLATED) {
ShowErrorMessage(STR_NETWORK_ERROR_COORDINATOR_ISOLATED, STR_NETWORK_ERROR_COORDINATOR_ISOLATED_DETAIL, WL_ERROR); ShowErrorMessage(STR_NETWORK_ERROR_COORDINATOR_ISOLATED, STR_NETWORK_ERROR_COORDINATOR_ISOLATED_DETAIL, WL_ERROR);
@ -230,9 +230,9 @@ bool ClientNetworkCoordinatorSocketHandler::Receive_GC_REGISTER_ACK(Packet *p)
return true; return true;
} }
bool ClientNetworkCoordinatorSocketHandler::Receive_GC_LISTING(Packet *p) bool ClientNetworkCoordinatorSocketHandler::Receive_GC_LISTING(Packet &p)
{ {
uint8_t servers = p->Recv_uint16(); uint8_t servers = p.Recv_uint16();
/* End of list; we can now remove all expired items from the list. */ /* End of list; we can now remove all expired items from the list. */
if (servers == 0) { if (servers == 0) {
@ -241,11 +241,11 @@ bool ClientNetworkCoordinatorSocketHandler::Receive_GC_LISTING(Packet *p)
} }
for (; servers > 0; servers--) { for (; servers > 0; servers--) {
std::string connection_string = p->Recv_string(NETWORK_HOSTNAME_PORT_LENGTH); std::string connection_string = p.Recv_string(NETWORK_HOSTNAME_PORT_LENGTH);
/* Read the NetworkGameInfo from the packet. */ /* Read the NetworkGameInfo from the packet. */
NetworkGameInfo ngi = {}; NetworkGameInfo ngi = {};
DeserializeNetworkGameInfo(p, &ngi, &this->newgrf_lookup_table); DeserializeNetworkGameInfo(p, ngi, &this->newgrf_lookup_table);
/* Now we know the connection string, we can add it to our list. */ /* Now we know the connection string, we can add it to our list. */
NetworkGameList *item = NetworkGameListAddItem(connection_string); NetworkGameList *item = NetworkGameListAddItem(connection_string);
@ -266,10 +266,10 @@ bool ClientNetworkCoordinatorSocketHandler::Receive_GC_LISTING(Packet *p)
return true; return true;
} }
bool ClientNetworkCoordinatorSocketHandler::Receive_GC_CONNECTING(Packet *p) bool ClientNetworkCoordinatorSocketHandler::Receive_GC_CONNECTING(Packet &p)
{ {
std::string token = p->Recv_string(NETWORK_TOKEN_LENGTH); std::string token = p.Recv_string(NETWORK_TOKEN_LENGTH);
std::string invite_code = p->Recv_string(NETWORK_INVITE_CODE_LENGTH); std::string invite_code = p.Recv_string(NETWORK_INVITE_CODE_LENGTH);
/* Find the connecter based on the invite code. */ /* Find the connecter based on the invite code. */
auto connecter_pre_it = this->connecter_pre.find(invite_code); auto connecter_pre_it = this->connecter_pre.find(invite_code);
@ -285,20 +285,20 @@ bool ClientNetworkCoordinatorSocketHandler::Receive_GC_CONNECTING(Packet *p)
return true; return true;
} }
bool ClientNetworkCoordinatorSocketHandler::Receive_GC_CONNECT_FAILED(Packet *p) bool ClientNetworkCoordinatorSocketHandler::Receive_GC_CONNECT_FAILED(Packet &p)
{ {
std::string token = p->Recv_string(NETWORK_TOKEN_LENGTH); std::string token = p.Recv_string(NETWORK_TOKEN_LENGTH);
this->CloseToken(token); this->CloseToken(token);
return true; return true;
} }
bool ClientNetworkCoordinatorSocketHandler::Receive_GC_DIRECT_CONNECT(Packet *p) bool ClientNetworkCoordinatorSocketHandler::Receive_GC_DIRECT_CONNECT(Packet &p)
{ {
std::string token = p->Recv_string(NETWORK_TOKEN_LENGTH); std::string token = p.Recv_string(NETWORK_TOKEN_LENGTH);
uint8_t tracking_number = p->Recv_uint8(); uint8_t tracking_number = p.Recv_uint8();
std::string hostname = p->Recv_string(NETWORK_HOSTNAME_LENGTH); std::string hostname = p.Recv_string(NETWORK_HOSTNAME_LENGTH);
uint16_t port = p->Recv_uint16(); uint16_t port = p.Recv_uint16();
/* Ensure all other pending connection attempts are killed. */ /* Ensure all other pending connection attempts are killed. */
if (this->game_connecter != nullptr) { if (this->game_connecter != nullptr) {
@ -310,22 +310,22 @@ bool ClientNetworkCoordinatorSocketHandler::Receive_GC_DIRECT_CONNECT(Packet *p)
return true; return true;
} }
bool ClientNetworkCoordinatorSocketHandler::Receive_GC_STUN_REQUEST(Packet *p) bool ClientNetworkCoordinatorSocketHandler::Receive_GC_STUN_REQUEST(Packet &p)
{ {
std::string token = p->Recv_string(NETWORK_TOKEN_LENGTH); std::string token = p.Recv_string(NETWORK_TOKEN_LENGTH);
this->stun_handlers[token][AF_INET6] = ClientNetworkStunSocketHandler::Stun(token, AF_INET6); this->stun_handlers[token][AF_INET6] = ClientNetworkStunSocketHandler::Stun(token, AF_INET6);
this->stun_handlers[token][AF_INET] = ClientNetworkStunSocketHandler::Stun(token, AF_INET); this->stun_handlers[token][AF_INET] = ClientNetworkStunSocketHandler::Stun(token, AF_INET);
return true; return true;
} }
bool ClientNetworkCoordinatorSocketHandler::Receive_GC_STUN_CONNECT(Packet *p) bool ClientNetworkCoordinatorSocketHandler::Receive_GC_STUN_CONNECT(Packet &p)
{ {
std::string token = p->Recv_string(NETWORK_TOKEN_LENGTH); std::string token = p.Recv_string(NETWORK_TOKEN_LENGTH);
uint8_t tracking_number = p->Recv_uint8(); uint8_t tracking_number = p.Recv_uint8();
uint8_t family = p->Recv_uint8(); uint8_t family = p.Recv_uint8();
std::string host = p->Recv_string(NETWORK_HOSTNAME_PORT_LENGTH); std::string host = p.Recv_string(NETWORK_HOSTNAME_PORT_LENGTH);
uint16_t port = p->Recv_uint16(); uint16_t port = p.Recv_uint16();
/* Check if we know this token. */ /* Check if we know this token. */
auto stun_it = this->stun_handlers.find(token); auto stun_it = this->stun_handlers.find(token);
@ -353,24 +353,24 @@ bool ClientNetworkCoordinatorSocketHandler::Receive_GC_STUN_CONNECT(Packet *p)
return true; return true;
} }
bool ClientNetworkCoordinatorSocketHandler::Receive_GC_NEWGRF_LOOKUP(Packet *p) bool ClientNetworkCoordinatorSocketHandler::Receive_GC_NEWGRF_LOOKUP(Packet &p)
{ {
this->newgrf_lookup_table_cursor = p->Recv_uint32(); this->newgrf_lookup_table_cursor = p.Recv_uint32();
uint16_t newgrfs = p->Recv_uint16(); uint16_t newgrfs = p.Recv_uint16();
for (; newgrfs> 0; newgrfs--) { for (; newgrfs> 0; newgrfs--) {
uint32_t index = p->Recv_uint32(); uint32_t index = p.Recv_uint32();
DeserializeGRFIdentifierWithName(p, &this->newgrf_lookup_table[index]); DeserializeGRFIdentifierWithName(p, this->newgrf_lookup_table[index]);
} }
return true; return true;
} }
bool ClientNetworkCoordinatorSocketHandler::Receive_GC_TURN_CONNECT(Packet *p) bool ClientNetworkCoordinatorSocketHandler::Receive_GC_TURN_CONNECT(Packet &p)
{ {
std::string token = p->Recv_string(NETWORK_TOKEN_LENGTH); std::string token = p.Recv_string(NETWORK_TOKEN_LENGTH);
uint8_t tracking_number = p->Recv_uint8(); uint8_t tracking_number = p.Recv_uint8();
std::string ticket = p->Recv_string(NETWORK_TOKEN_LENGTH); std::string ticket = p.Recv_string(NETWORK_TOKEN_LENGTH);
std::string connection_string = p->Recv_string(NETWORK_HOSTNAME_PORT_LENGTH); std::string connection_string = p.Recv_string(NETWORK_HOSTNAME_PORT_LENGTH);
/* Ensure all other pending connection attempts are killed. */ /* Ensure all other pending connection attempts are killed. */
if (this->game_connecter != nullptr) { if (this->game_connecter != nullptr) {
@ -458,7 +458,7 @@ void ClientNetworkCoordinatorSocketHandler::Register()
this->Connect(); this->Connect();
Packet *p = new Packet(PACKET_COORDINATOR_SERVER_REGISTER); auto p = std::make_unique<Packet>(PACKET_COORDINATOR_SERVER_REGISTER);
p->Send_uint8(NETWORK_COORDINATOR_VERSION); p->Send_uint8(NETWORK_COORDINATOR_VERSION);
p->Send_uint8(_settings_client.network.server_game_type); p->Send_uint8(_settings_client.network.server_game_type);
p->Send_uint16(_settings_client.network.server_port); p->Send_uint16(_settings_client.network.server_port);
@ -470,7 +470,7 @@ void ClientNetworkCoordinatorSocketHandler::Register()
p->Send_string(_settings_client.network.server_invite_code_secret); p->Send_string(_settings_client.network.server_invite_code_secret);
} }
this->SendPacket(p); this->SendPacket(std::move(p));
} }
/** /**
@ -480,11 +480,11 @@ void ClientNetworkCoordinatorSocketHandler::SendServerUpdate()
{ {
DEBUG(net, 6, "Sending server update to Game Coordinator"); DEBUG(net, 6, "Sending server update to Game Coordinator");
Packet *p = new Packet(PACKET_COORDINATOR_SERVER_UPDATE, TCP_MTU); auto p = std::make_unique<Packet>(PACKET_COORDINATOR_SERVER_UPDATE, TCP_MTU);
p->Send_uint8(NETWORK_COORDINATOR_VERSION); p->Send_uint8(NETWORK_COORDINATOR_VERSION);
SerializeNetworkGameInfo(p, GetCurrentNetworkServerGameInfo(), this->next_update.time_since_epoch() != std::chrono::nanoseconds::zero()); SerializeNetworkGameInfo(*p, GetCurrentNetworkServerGameInfo(), this->next_update.time_since_epoch() != std::chrono::nanoseconds::zero());
this->SendPacket(p); this->SendPacket(std::move(p));
this->next_update = std::chrono::steady_clock::now() + NETWORK_COORDINATOR_DELAY_BETWEEN_UPDATES; this->next_update = std::chrono::steady_clock::now() + NETWORK_COORDINATOR_DELAY_BETWEEN_UPDATES;
} }
@ -498,13 +498,13 @@ void ClientNetworkCoordinatorSocketHandler::GetListing()
_network_game_list_version++; _network_game_list_version++;
Packet *p = new Packet(PACKET_COORDINATOR_CLIENT_LISTING); auto p = std::make_unique<Packet>(PACKET_COORDINATOR_CLIENT_LISTING);
p->Send_uint8(NETWORK_COORDINATOR_VERSION); p->Send_uint8(NETWORK_COORDINATOR_VERSION);
p->Send_uint8(NETWORK_GAME_INFO_VERSION); p->Send_uint8(NETWORK_GAME_INFO_VERSION);
p->Send_string(_openttd_revision); p->Send_string(_openttd_revision);
p->Send_uint32(this->newgrf_lookup_table_cursor); p->Send_uint32(this->newgrf_lookup_table_cursor);
this->SendPacket(p); this->SendPacket(std::move(p));
} }
/** /**
@ -530,11 +530,11 @@ void ClientNetworkCoordinatorSocketHandler::ConnectToServer(const std::string &i
this->Connect(); this->Connect();
Packet *p = new Packet(PACKET_COORDINATOR_CLIENT_CONNECT); auto p = std::make_unique<Packet>(PACKET_COORDINATOR_CLIENT_CONNECT);
p->Send_uint8(NETWORK_COORDINATOR_VERSION); p->Send_uint8(NETWORK_COORDINATOR_VERSION);
p->Send_string(invite_code); p->Send_string(invite_code);
this->SendPacket(p); this->SendPacket(std::move(p));
} }
/** /**
@ -547,12 +547,12 @@ void ClientNetworkCoordinatorSocketHandler::ConnectFailure(const std::string &to
/* Connecter will destroy itself. */ /* Connecter will destroy itself. */
this->game_connecter = nullptr; this->game_connecter = nullptr;
Packet *p = new Packet(PACKET_COORDINATOR_SERCLI_CONNECT_FAILED); auto p = std::make_unique<Packet>(PACKET_COORDINATOR_SERCLI_CONNECT_FAILED);
p->Send_uint8(NETWORK_COORDINATOR_VERSION); p->Send_uint8(NETWORK_COORDINATOR_VERSION);
p->Send_string(token); p->Send_string(token);
p->Send_uint8(tracking_number); p->Send_uint8(tracking_number);
this->SendPacket(p); this->SendPacket(std::move(p));
/* We do not close the associated connecter here yet, as the /* We do not close the associated connecter here yet, as the
* Game Coordinator might have other methods of connecting available. */ * Game Coordinator might have other methods of connecting available. */
@ -578,10 +578,10 @@ void ClientNetworkCoordinatorSocketHandler::ConnectSuccess(const std::string &to
} else { } else {
/* The client informs the Game Coordinator about the success. The server /* The client informs the Game Coordinator about the success. The server
* doesn't have to, as it is implied by the client telling. */ * doesn't have to, as it is implied by the client telling. */
Packet *p = new Packet(PACKET_COORDINATOR_CLIENT_CONNECTED); auto p = std::make_unique<Packet>(PACKET_COORDINATOR_CLIENT_CONNECTED);
p->Send_uint8(NETWORK_COORDINATOR_VERSION); p->Send_uint8(NETWORK_COORDINATOR_VERSION);
p->Send_string(token); p->Send_string(token);
this->SendPacket(p); this->SendPacket(std::move(p));
/* Find the connecter; it can happen it no longer exist, in cases where /* Find the connecter; it can happen it no longer exist, in cases where
* we aborted the connect but the Game Coordinator was already in the * we aborted the connect but the Game Coordinator was already in the
@ -606,12 +606,12 @@ void ClientNetworkCoordinatorSocketHandler::ConnectSuccess(const std::string &to
*/ */
void ClientNetworkCoordinatorSocketHandler::StunResult(const std::string &token, uint8_t family, bool result) void ClientNetworkCoordinatorSocketHandler::StunResult(const std::string &token, uint8_t family, bool result)
{ {
Packet *p = new Packet(PACKET_COORDINATOR_SERCLI_STUN_RESULT); auto p = std::make_unique<Packet>(PACKET_COORDINATOR_SERCLI_STUN_RESULT);
p->Send_uint8(NETWORK_COORDINATOR_VERSION); p->Send_uint8(NETWORK_COORDINATOR_VERSION);
p->Send_string(token); p->Send_string(token);
p->Send_uint8(family); p->Send_uint8(family);
p->Send_bool(result); p->Send_bool(result);
this->SendPacket(p); this->SendPacket(std::move(p));
} }
/** /**

@ -64,16 +64,16 @@ private:
GameInfoNewGRFLookupTable newgrf_lookup_table; ///< Table to look up NewGRFs in the GC_LISTING packets. GameInfoNewGRFLookupTable newgrf_lookup_table; ///< Table to look up NewGRFs in the GC_LISTING packets.
protected: protected:
bool Receive_GC_ERROR(Packet *p) override; bool Receive_GC_ERROR(Packet &p) override;
bool Receive_GC_REGISTER_ACK(Packet *p) override; bool Receive_GC_REGISTER_ACK(Packet &p) override;
bool Receive_GC_LISTING(Packet *p) override; bool Receive_GC_LISTING(Packet &p) override;
bool Receive_GC_CONNECTING(Packet *p) override; bool Receive_GC_CONNECTING(Packet &p) override;
bool Receive_GC_CONNECT_FAILED(Packet *p) override; bool Receive_GC_CONNECT_FAILED(Packet &p) override;
bool Receive_GC_DIRECT_CONNECT(Packet *p) override; bool Receive_GC_DIRECT_CONNECT(Packet &p) override;
bool Receive_GC_STUN_REQUEST(Packet *p) override; bool Receive_GC_STUN_REQUEST(Packet &p) override;
bool Receive_GC_STUN_CONNECT(Packet *p) override; bool Receive_GC_STUN_CONNECT(Packet &p) override;
bool Receive_GC_NEWGRF_LOOKUP(Packet *p) override; bool Receive_GC_NEWGRF_LOOKUP(Packet &p) override;
bool Receive_GC_TURN_CONNECT(Packet *p) override; bool Receive_GC_TURN_CONNECT(Packet &p) override;
public: public:
/** The idle timeout; when to close the connection because it's idle. */ /** The idle timeout; when to close the connection because it's idle. */

@ -123,8 +123,7 @@ struct NetworkSharedSecrets {
*/ */
struct CommandPacket : CommandContainer { struct CommandPacket : CommandContainer {
/** Make sure the pointer is nullptr. */ /** Make sure the pointer is nullptr. */
CommandPacket() : next(nullptr), frame(0), client_id(INVALID_CLIENT_ID), company(INVALID_COMPANY), my_cmd(false) {} CommandPacket() : frame(0), client_id(INVALID_CLIENT_ID), company(INVALID_COMPANY), my_cmd(false) {}
CommandPacket *next; ///< the next command packet (if in queue)
uint32_t frame; ///< the frame in which this packet is executed uint32_t frame; ///< the frame in which this packet is executed
ClientID client_id; ///< originating client ID (or INVALID_CLIENT_ID if not specified) ClientID client_id; ///< originating client ID (or INVALID_CLIENT_ID if not specified)
CompanyID company; ///< company that is executing the command CompanyID company; ///< company that is executing the command

@ -82,17 +82,17 @@ void QueryNetworkGameSocketHandler::Send()
*/ */
NetworkRecvStatus QueryNetworkGameSocketHandler::SendGameInfo() NetworkRecvStatus QueryNetworkGameSocketHandler::SendGameInfo()
{ {
Packet *p = new Packet(PACKET_CLIENT_GAME_INFO); auto p = std::make_unique<Packet>(PACKET_CLIENT_GAME_INFO);
p->Send_uint32(FIND_SERVER_EXTENDED_TOKEN); p->Send_uint32(FIND_SERVER_EXTENDED_TOKEN);
p->Send_uint8(PACKET_SERVER_GAME_INFO_EXTENDED); // reply type p->Send_uint8(PACKET_SERVER_GAME_INFO_EXTENDED); // reply type
p->Send_uint16(0); // flags p->Send_uint16(0); // flags
p->Send_uint16(SERVER_GAME_INFO_EXTENDED_MAX_VERSION); // version p->Send_uint16(SERVER_GAME_INFO_EXTENDED_MAX_VERSION); // version
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus QueryNetworkGameSocketHandler::Receive_SERVER_FULL(Packet *) NetworkRecvStatus QueryNetworkGameSocketHandler::Receive_SERVER_FULL(Packet &)
{ {
NetworkGameList *item = NetworkGameListAddItem(this->connection_string); NetworkGameList *item = NetworkGameListAddItem(this->connection_string);
item->status = NGLS_FULL; item->status = NGLS_FULL;
@ -103,7 +103,7 @@ NetworkRecvStatus QueryNetworkGameSocketHandler::Receive_SERVER_FULL(Packet *)
return NETWORK_RECV_STATUS_CLOSE_QUERY; return NETWORK_RECV_STATUS_CLOSE_QUERY;
} }
NetworkRecvStatus QueryNetworkGameSocketHandler::Receive_SERVER_BANNED(Packet *) NetworkRecvStatus QueryNetworkGameSocketHandler::Receive_SERVER_BANNED(Packet &)
{ {
NetworkGameList *item = NetworkGameListAddItem(this->connection_string); NetworkGameList *item = NetworkGameListAddItem(this->connection_string);
item->status = NGLS_BANNED; item->status = NGLS_BANNED;
@ -114,14 +114,14 @@ NetworkRecvStatus QueryNetworkGameSocketHandler::Receive_SERVER_BANNED(Packet *)
return NETWORK_RECV_STATUS_CLOSE_QUERY; return NETWORK_RECV_STATUS_CLOSE_QUERY;
} }
NetworkRecvStatus QueryNetworkGameSocketHandler::Receive_SERVER_GAME_INFO(Packet *p) NetworkRecvStatus QueryNetworkGameSocketHandler::Receive_SERVER_GAME_INFO(Packet &p)
{ {
NetworkGameList *item = NetworkGameListAddItem(this->connection_string); NetworkGameList *item = NetworkGameListAddItem(this->connection_string);
/* Clear any existing GRFConfig chain. */ /* Clear any existing GRFConfig chain. */
ClearGRFConfigList(&item->info.grfconfig); ClearGRFConfigList(&item->info.grfconfig);
/* Retrieve the NetworkGameInfo from the packet. */ /* Retrieve the NetworkGameInfo from the packet. */
DeserializeNetworkGameInfo(p, &item->info); DeserializeNetworkGameInfo(p, item->info);
/* Check for compatability with the client. */ /* Check for compatability with the client. */
CheckGameCompatibility(item->info); CheckGameCompatibility(item->info);
/* Ensure we consider the server online. */ /* Ensure we consider the server online. */
@ -133,14 +133,14 @@ NetworkRecvStatus QueryNetworkGameSocketHandler::Receive_SERVER_GAME_INFO(Packet
return NETWORK_RECV_STATUS_CLOSE_QUERY; return NETWORK_RECV_STATUS_CLOSE_QUERY;
} }
NetworkRecvStatus QueryNetworkGameSocketHandler::Receive_SERVER_GAME_INFO_EXTENDED(Packet *p) NetworkRecvStatus QueryNetworkGameSocketHandler::Receive_SERVER_GAME_INFO_EXTENDED(Packet &p)
{ {
NetworkGameList *item = NetworkGameListAddItem(this->connection_string); NetworkGameList *item = NetworkGameListAddItem(this->connection_string);
/* Clear any existing GRFConfig chain. */ /* Clear any existing GRFConfig chain. */
ClearGRFConfigList(&item->info.grfconfig); ClearGRFConfigList(&item->info.grfconfig);
/* Retrieve the NetworkGameInfo from the packet. */ /* Retrieve the NetworkGameInfo from the packet. */
DeserializeNetworkGameInfoExtended(p, &item->info); DeserializeNetworkGameInfoExtended(p, item->info);
/* Check for compatability with the client. */ /* Check for compatability with the client. */
CheckGameCompatibility(item->info, true); CheckGameCompatibility(item->info, true);
/* Ensure we consider the server online. */ /* Ensure we consider the server online. */
@ -152,9 +152,9 @@ NetworkRecvStatus QueryNetworkGameSocketHandler::Receive_SERVER_GAME_INFO_EXTEND
return NETWORK_RECV_STATUS_CLOSE_QUERY; return NETWORK_RECV_STATUS_CLOSE_QUERY;
} }
NetworkRecvStatus QueryNetworkGameSocketHandler::Receive_SERVER_ERROR(Packet *p) NetworkRecvStatus QueryNetworkGameSocketHandler::Receive_SERVER_ERROR(Packet &p)
{ {
NetworkErrorCode error = (NetworkErrorCode)p->Recv_uint8(); NetworkErrorCode error = (NetworkErrorCode)p.Recv_uint8();
NetworkGameList *item = NetworkGameListAddItem(this->connection_string); NetworkGameList *item = NetworkGameListAddItem(this->connection_string);

@ -20,11 +20,11 @@ private:
std::string connection_string; ///< Address we are connected to. std::string connection_string; ///< Address we are connected to.
protected: protected:
NetworkRecvStatus Receive_SERVER_FULL(Packet *p) override; NetworkRecvStatus Receive_SERVER_FULL(Packet &p) override;
NetworkRecvStatus Receive_SERVER_BANNED(Packet *p) override; NetworkRecvStatus Receive_SERVER_BANNED(Packet &p) override;
NetworkRecvStatus Receive_SERVER_ERROR(Packet *p) override; NetworkRecvStatus Receive_SERVER_ERROR(Packet &p) override;
NetworkRecvStatus Receive_SERVER_GAME_INFO(Packet *p) override; NetworkRecvStatus Receive_SERVER_GAME_INFO(Packet &p) override;
NetworkRecvStatus Receive_SERVER_GAME_INFO_EXTENDED(Packet *p) override; NetworkRecvStatus Receive_SERVER_GAME_INFO_EXTENDED(Packet &p) override;
NetworkRecvStatus SendGameInfo(); NetworkRecvStatus SendGameInfo();

@ -140,20 +140,12 @@ struct PacketWriter : SaveFilter {
return last_packet; return last_packet;
} }
/** Append the current packet to the queue. */
void AppendQueue()
{
if (this->current == nullptr) return;
this->packets.push_back(std::move(this->current));
}
void Write(byte *buf, size_t size) override void Write(byte *buf, size_t size) override
{ {
/* We want to abort the saving when the socket is closed. */ /* We want to abort the saving when the socket is closed. */
if (this->cs == nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION); if (this->cs == nullptr) SlError(STR_NETWORK_ERROR_LOSTCONNECTION);
if (this->current == nullptr) this->current.reset(new Packet(PACKET_SERVER_MAP_DATA, SHRT_MAX)); if (this->current == nullptr) this->current = std::make_unique<Packet>(PACKET_SERVER_MAP_DATA, TCP_MTU);
std::lock_guard<std::mutex> lock(this->mutex); std::lock_guard<std::mutex> lock(this->mutex);
@ -163,8 +155,8 @@ struct PacketWriter : SaveFilter {
buf += written; buf += written;
if (!this->current->CanWriteToPacket(1)) { if (!this->current->CanWriteToPacket(1)) {
this->AppendQueue(); this->packets.push_back(std::move(this->current));
if (buf != bufe) this->current.reset(new Packet(PACKET_SERVER_MAP_DATA, SHRT_MAX)); if (buf != bufe) this->current = std::make_unique<Packet>(PACKET_SERVER_MAP_DATA, TCP_MTU);
} }
} }
@ -179,14 +171,13 @@ struct PacketWriter : SaveFilter {
std::lock_guard<std::mutex> lock(this->mutex); std::lock_guard<std::mutex> lock(this->mutex);
/* Make sure the last packet is flushed. */ /* Make sure the last packet is flushed. */
this->AppendQueue(); if (this->current != nullptr) this->packets.push_back(std::move(this->current));
/* Add a packet stating that this is the end to the queue. */ /* Add a packet stating that this is the end to the queue. */
this->current.reset(new Packet(PACKET_SERVER_MAP_DONE, SHRT_MAX)); this->packets.push_back(std::make_unique<Packet>(PACKET_SERVER_MAP_DONE));
this->AppendQueue();
/* Fast-track the size to the client. */ /* Fast-track the size to the client. */
this->map_size_packet.reset(new Packet(PACKET_SERVER_MAP_SIZE, SHRT_MAX)); this->map_size_packet.reset(new Packet(PACKET_SERVER_MAP_SIZE, TCP_MTU));
this->map_size_packet->Send_uint32((uint32_t)this->total_size); this->map_size_packet->Send_uint32((uint32_t)this->total_size);
} }
}; };
@ -227,14 +218,14 @@ ServerNetworkGameSocketHandler::~ServerNetworkGameSocketHandler()
} }
} }
bool ServerNetworkGameSocketHandler::ParseKeyPasswordPacket(Packet *p, NetworkSharedSecrets &ss, const std::string &password, std::string *payload, size_t length) bool ServerNetworkGameSocketHandler::ParseKeyPasswordPacket(Packet &p, NetworkSharedSecrets &ss, const std::string &password, std::string *payload, size_t length)
{ {
std::array<uint8_t, 32> client_pub_key; std::array<uint8_t, 32> client_pub_key;
std::array<uint8_t, 24> nonce; std::array<uint8_t, 24> nonce;
std::array<uint8_t, 16> mac; std::array<uint8_t, 16> mac;
p->Recv_binary(client_pub_key); p.Recv_binary(client_pub_key);
p->Recv_binary(nonce); p.Recv_binary(nonce);
p->Recv_binary(mac); p.Recv_binary(mac);
const NetworkGameKeys &keys = this->GetKeys(); const NetworkGameKeys &keys = this->GetKeys();
@ -257,7 +248,7 @@ bool ServerNetworkGameSocketHandler::ParseKeyPasswordPacket(Packet *p, NetworkSh
crypto_wipe(shared_secret.data(), shared_secret.size()); crypto_wipe(shared_secret.data(), shared_secret.size());
std::vector<byte> message = p->Recv_binary(p->RemainingBytesToTransfer()); std::vector<byte> message = p.Recv_binary(p.RemainingBytesToTransfer());
if (message.size() < 8) return false; if (message.size() < 8) return false;
if ((message.size() == 8) != (payload == nullptr)) { if ((message.size() == 8) != (payload == nullptr)) {
/* Payload expected but not present, or vice versa, just give up */ /* Payload expected but not present, or vice versa, just give up */
@ -391,7 +382,6 @@ static void NetworkHandleCommandQueue(NetworkClientSocket *cs);
/*********** /***********
* Sending functions * Sending functions
* DEF_SERVER_SEND_COMMAND has parameter: NetworkClientSocket *cs
************/ ************/
/** /**
@ -401,12 +391,12 @@ static void NetworkHandleCommandQueue(NetworkClientSocket *cs);
NetworkRecvStatus ServerNetworkGameSocketHandler::SendClientInfo(NetworkClientInfo *ci) NetworkRecvStatus ServerNetworkGameSocketHandler::SendClientInfo(NetworkClientInfo *ci)
{ {
if (ci->client_id != INVALID_CLIENT_ID) { if (ci->client_id != INVALID_CLIENT_ID) {
Packet *p = new Packet(PACKET_SERVER_CLIENT_INFO, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_CLIENT_INFO, TCP_MTU);
p->Send_uint32(ci->client_id); p->Send_uint32(ci->client_id);
p->Send_uint8 (ci->client_playas); p->Send_uint8 (ci->client_playas);
p->Send_string(ci->client_name); p->Send_string(ci->client_name);
this->SendPacket(p); this->SendPacket(std::move(p));
} }
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -414,20 +404,20 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendClientInfo(NetworkClientIn
/** Send the client information about the server. */ /** Send the client information about the server. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendGameInfo() NetworkRecvStatus ServerNetworkGameSocketHandler::SendGameInfo()
{ {
Packet *p = new Packet(PACKET_SERVER_GAME_INFO, TCP_MTU); auto p = std::make_unique<Packet>(PACKET_SERVER_GAME_INFO, TCP_MTU);
SerializeNetworkGameInfo(p, GetCurrentNetworkServerGameInfo()); SerializeNetworkGameInfo(*p, GetCurrentNetworkServerGameInfo());
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ServerNetworkGameSocketHandler::SendGameInfoExtended(PacketGameType reply_type, uint16_t flags, uint16_t version) NetworkRecvStatus ServerNetworkGameSocketHandler::SendGameInfoExtended(PacketGameType reply_type, uint16_t flags, uint16_t version)
{ {
Packet *p = new Packet(reply_type, SHRT_MAX); auto p = std::make_unique<Packet>(reply_type, TCP_MTU);
SerializeNetworkGameInfoExtended(p, GetCurrentNetworkServerGameInfo(), flags, version); SerializeNetworkGameInfoExtended(*p, GetCurrentNetworkServerGameInfo(), flags, version);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -439,11 +429,11 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendGameInfoExtended(PacketGam
*/ */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendError(NetworkErrorCode error, const std::string &reason) NetworkRecvStatus ServerNetworkGameSocketHandler::SendError(NetworkErrorCode error, const std::string &reason)
{ {
Packet *p = new Packet(PACKET_SERVER_ERROR, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_ERROR, TCP_MTU);
p->Send_uint8(error); p->Send_uint8(error);
if (!reason.empty()) p->Send_string(reason); if (!reason.empty()) p->Send_string(reason);
this->SendPacket(p); this->SendPacket(std::move(p));
StringID strid = GetNetworkErrorMsg(error); StringID strid = GetNetworkErrorMsg(error);
@ -484,11 +474,11 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendError(NetworkErrorCode err
NetworkRecvStatus ServerNetworkGameSocketHandler::SendDesyncLog(const std::string &log) NetworkRecvStatus ServerNetworkGameSocketHandler::SendDesyncLog(const std::string &log)
{ {
for (size_t offset = 0; offset < log.size();) { for (size_t offset = 0; offset < log.size();) {
Packet *p = new Packet(PACKET_SERVER_DESYNC_LOG, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_DESYNC_LOG, TCP_MTU);
size_t size = std::min<size_t>(log.size() - offset, SHRT_MAX - 2 - p->Size()); size_t size = std::min<size_t>(log.size() - offset, TCP_MTU - 2 - p->Size());
p->Send_uint16(static_cast<uint16_t>(size)); p->Send_uint16(static_cast<uint16_t>(size));
p->Send_binary((const byte *)(log.data() + offset), size); p->Send_binary((const byte *)(log.data() + offset), size);
this->SendPacket(p); this->SendPacket(std::move(p));
offset += size; offset += size;
} }
@ -498,7 +488,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendDesyncLog(const std::strin
/** Send the check for the NewGRFs. */ /** Send the check for the NewGRFs. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGRFCheck() NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGRFCheck()
{ {
Packet *p = new Packet(PACKET_SERVER_CHECK_NEWGRFS, TCP_MTU); auto p = std::make_unique<Packet>(PACKET_SERVER_CHECK_NEWGRFS, TCP_MTU);
const GRFConfig *c; const GRFConfig *c;
uint grf_count = 0; uint grf_count = 0;
@ -508,16 +498,21 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGRFCheck()
p->Send_uint32(grf_count); p->Send_uint32(grf_count);
for (c = _grfconfig; c != nullptr; c = c->next) { for (c = _grfconfig; c != nullptr; c = c->next) {
if (!HasBit(c->flags, GCF_STATIC)) SerializeGRFIdentifier(p, &c->ident); if (!HasBit(c->flags, GCF_STATIC)) SerializeGRFIdentifier(*p, c->ident);
} }
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
/** Request the game password. */ /** Request the game password. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendNeedGamePassword() NetworkRecvStatus ServerNetworkGameSocketHandler::SendNeedGamePassword()
{ {
if (_settings_client.network.server_password.empty()) {
/* Do not actually need a game password, continue with the company password. */
return this->SendNeedCompanyPassword();
}
/* Invalid packet when status is STATUS_AUTH_GAME or higher */ /* Invalid packet when status is STATUS_AUTH_GAME or higher */
if (this->status >= STATUS_AUTH_GAME) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET); if (this->status >= STATUS_AUTH_GAME) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
@ -527,17 +522,22 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendNeedGamePassword()
const NetworkGameKeys &keys = this->GetKeys(); const NetworkGameKeys &keys = this->GetKeys();
Packet *p = new Packet(PACKET_SERVER_NEED_GAME_PASSWORD, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_NEED_GAME_PASSWORD, TCP_MTU);
static_assert(std::tuple_size<decltype(keys.x25519_pub_key)>::value == 32); static_assert(std::tuple_size<decltype(keys.x25519_pub_key)>::value == 32);
p->Send_binary(keys.x25519_pub_key); p->Send_binary(keys.x25519_pub_key);
p->Send_string(_settings_client.network.network_id); p->Send_string(_settings_client.network.network_id);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
/** Request the company password. */ /** Request the company password. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendNeedCompanyPassword() NetworkRecvStatus ServerNetworkGameSocketHandler::SendNeedCompanyPassword()
{ {
NetworkClientInfo *ci = this->GetInfo();
if (!Company::IsValidID(ci->client_playas) || _network_company_states[ci->client_playas].password.empty()) {
return this->SendWelcome();
}
/* Invalid packet when status is STATUS_AUTH_COMPANY or higher */ /* Invalid packet when status is STATUS_AUTH_COMPANY or higher */
if (this->status >= STATUS_AUTH_COMPANY) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET); if (this->status >= STATUS_AUTH_COMPANY) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
@ -545,18 +545,16 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendNeedCompanyPassword()
/* Reset 'lag' counters */ /* Reset 'lag' counters */
this->last_frame = this->last_frame_server = _frame_counter; this->last_frame = this->last_frame_server = _frame_counter;
Packet *p = new Packet(PACKET_SERVER_NEED_COMPANY_PASSWORD, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_NEED_COMPANY_PASSWORD, TCP_MTU);
p->Send_uint32(_settings_game.game_creation.generation_seed); p->Send_uint32(_settings_game.game_creation.generation_seed);
p->Send_string(_network_company_server_id); p->Send_string(_network_company_server_id);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
/** Send the client a welcome message with some basic information. */ /** Send the client a welcome message with some basic information. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendWelcome() NetworkRecvStatus ServerNetworkGameSocketHandler::SendWelcome()
{ {
Packet *p;
/* Invalid packet when status is AUTH or higher */ /* Invalid packet when status is AUTH or higher */
if (this->status >= STATUS_AUTHORIZED) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET); if (this->status >= STATUS_AUTHORIZED) return this->CloseConnection(NETWORK_RECV_STATUS_MALFORMED_PACKET);
@ -568,14 +566,14 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendWelcome()
const NetworkGameKeys &keys = this->GetKeys(); const NetworkGameKeys &keys = this->GetKeys();
p = new Packet(PACKET_SERVER_WELCOME, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_WELCOME, TCP_MTU);
p->Send_uint32(this->client_id); p->Send_uint32(this->client_id);
p->Send_uint32(_settings_game.game_creation.generation_seed); p->Send_uint32(_settings_game.game_creation.generation_seed);
static_assert(std::tuple_size<decltype(keys.x25519_pub_key)>::value == 32); static_assert(std::tuple_size<decltype(keys.x25519_pub_key)>::value == 32);
p->Send_binary(keys.x25519_pub_key); p->Send_binary(keys.x25519_pub_key);
p->Send_string(_settings_client.network.network_id); p->Send_string(_settings_client.network.network_id);
p->Send_string(_network_company_server_id); p->Send_string(_network_company_server_id);
this->SendPacket(p); this->SendPacket(std::move(p));
/* Transmit info about all the active clients */ /* Transmit info about all the active clients */
for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) { for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
@ -591,7 +589,6 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendWelcome()
NetworkRecvStatus ServerNetworkGameSocketHandler::SendWait() NetworkRecvStatus ServerNetworkGameSocketHandler::SendWait()
{ {
int waiting = 1; // current player getting the map counts as 1 int waiting = 1; // current player getting the map counts as 1
Packet *p;
/* Count how many clients are waiting in the queue, in front of you! */ /* Count how many clients are waiting in the queue, in front of you! */
for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) { for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
@ -599,9 +596,9 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendWait()
if (new_cs->GetInfo()->join_date < this->GetInfo()->join_date || (new_cs->GetInfo()->join_date == this->GetInfo()->join_date && new_cs->client_id < this->client_id)) waiting++; if (new_cs->GetInfo()->join_date < this->GetInfo()->join_date || (new_cs->GetInfo()->join_date == this->GetInfo()->join_date && new_cs->client_id < this->client_id)) waiting++;
} }
p = new Packet(PACKET_SERVER_WAIT, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_WAIT, TCP_MTU);
p->Send_uint8(waiting); p->Send_uint8(waiting);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -645,9 +642,9 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendMap()
this->savegame = std::make_shared<PacketWriter>(this); this->savegame = std::make_shared<PacketWriter>(this);
/* Now send the _frame_counter and how many packets are coming */ /* Now send the _frame_counter and how many packets are coming */
Packet *p = new Packet(PACKET_SERVER_MAP_BEGIN, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_MAP_BEGIN, TCP_MTU);
p->Send_uint32(_frame_counter); p->Send_uint32(_frame_counter);
this->SendPacket(p); this->SendPacket(std::move(p));
NetworkSyncCommandQueue(this); NetworkSyncCommandQueue(this);
this->status = STATUS_MAP; this->status = STATUS_MAP;
@ -684,18 +681,18 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendMap()
*/ */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendJoin(ClientID client_id) NetworkRecvStatus ServerNetworkGameSocketHandler::SendJoin(ClientID client_id)
{ {
Packet *p = new Packet(PACKET_SERVER_JOIN, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_JOIN, TCP_MTU);
p->Send_uint32(client_id); p->Send_uint32(client_id);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
/** Tell the client that they may run to a particular frame. */ /** Tell the client that they may run to a particular frame. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendFrame() NetworkRecvStatus ServerNetworkGameSocketHandler::SendFrame()
{ {
Packet *p = new Packet(PACKET_SERVER_FRAME, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_FRAME, TCP_MTU);
p->Send_uint32(_frame_counter); p->Send_uint32(_frame_counter);
p->Send_uint32(_frame_counter_max); p->Send_uint32(_frame_counter_max);
#ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME #ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
@ -709,19 +706,19 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendFrame()
p->Send_uint8(this->last_token); p->Send_uint8(this->last_token);
} }
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
/** Request the client to sync. */ /** Request the client to sync. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendSync() NetworkRecvStatus ServerNetworkGameSocketHandler::SendSync()
{ {
Packet *p = new Packet(PACKET_SERVER_SYNC, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_SYNC, TCP_MTU);
p->Send_uint32(_frame_counter); p->Send_uint32(_frame_counter);
p->Send_uint32(_sync_seed_1); p->Send_uint32(_sync_seed_1);
p->Send_uint64(_sync_state_checksum); p->Send_uint64(_sync_state_checksum);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -729,15 +726,15 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendSync()
* Send a command to the client to execute. * Send a command to the client to execute.
* @param cp The command to send. * @param cp The command to send.
*/ */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendCommand(const CommandPacket *cp) NetworkRecvStatus ServerNetworkGameSocketHandler::SendCommand(const CommandPacket &cp)
{ {
Packet *p = new Packet(PACKET_SERVER_COMMAND, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_COMMAND, TCP_MTU);
this->NetworkGameSocketHandler::SendCommand(p, cp); this->NetworkGameSocketHandler::SendCommand(*p, cp);
p->Send_uint32(cp->frame); p->Send_uint32(cp.frame);
p->Send_bool (cp->my_cmd); p->Send_bool (cp.my_cmd);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -753,15 +750,15 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendChat(NetworkAction action,
{ {
if (this->status < STATUS_PRE_ACTIVE) return NETWORK_RECV_STATUS_OKAY; if (this->status < STATUS_PRE_ACTIVE) return NETWORK_RECV_STATUS_OKAY;
Packet *p = new Packet(PACKET_SERVER_CHAT, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_CHAT, TCP_MTU);
p->Send_uint8 (action); p->Send_uint8 (action);
p->Send_uint32(client_id); p->Send_uint32(client_id);
p->Send_bool (self_send); p->Send_bool (self_send);
p->Send_string(msg); p->Send_string(msg);
data.send(p); data.send(*p);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -776,14 +773,14 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendExternalChat(const std::st
{ {
if (this->status < STATUS_PRE_ACTIVE) return NETWORK_RECV_STATUS_OKAY; if (this->status < STATUS_PRE_ACTIVE) return NETWORK_RECV_STATUS_OKAY;
Packet *p = new Packet(PACKET_SERVER_EXTERNAL_CHAT); auto p = std::make_unique<Packet>(PACKET_SERVER_EXTERNAL_CHAT, TCP_MTU);
p->Send_string(source); p->Send_string(source);
p->Send_uint16(colour); p->Send_uint16(colour);
p->Send_string(user); p->Send_string(user);
p->Send_string(msg); p->Send_string(msg);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -794,12 +791,12 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendExternalChat(const std::st
*/ */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendErrorQuit(ClientID client_id, NetworkErrorCode errorno) NetworkRecvStatus ServerNetworkGameSocketHandler::SendErrorQuit(ClientID client_id, NetworkErrorCode errorno)
{ {
Packet *p = new Packet(PACKET_SERVER_ERROR_QUIT, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_ERROR_QUIT, TCP_MTU);
p->Send_uint32(client_id); p->Send_uint32(client_id);
p->Send_uint8 (errorno); p->Send_uint8 (errorno);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -809,27 +806,27 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendErrorQuit(ClientID client_
*/ */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendQuit(ClientID client_id) NetworkRecvStatus ServerNetworkGameSocketHandler::SendQuit(ClientID client_id)
{ {
Packet *p = new Packet(PACKET_SERVER_QUIT, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_QUIT, TCP_MTU);
p->Send_uint32(client_id); p->Send_uint32(client_id);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
/** Tell the client we're shutting down. */ /** Tell the client we're shutting down. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendShutdown() NetworkRecvStatus ServerNetworkGameSocketHandler::SendShutdown()
{ {
Packet *p = new Packet(PACKET_SERVER_SHUTDOWN, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_SHUTDOWN, TCP_MTU);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
/** Tell the client we're starting a new game. */ /** Tell the client we're starting a new game. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGame() NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGame()
{ {
Packet *p = new Packet(PACKET_SERVER_NEWGAME, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_NEWGAME, TCP_MTU);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -857,14 +854,14 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendRConResult(uint16_t colour
/* Encrypt in place, use first half of hash as key */ /* Encrypt in place, use first half of hash as key */
crypto_aead_lock(message.data(), mac.data(), this->rcon_reply_key, nonce.data(), nullptr, 0, message.data(), message.size()); crypto_aead_lock(message.data(), mac.data(), this->rcon_reply_key, nonce.data(), nullptr, 0, message.data(), message.size());
Packet *p = new Packet(PACKET_SERVER_RCON, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_RCON, TCP_MTU);
static_assert(nonce.size() == 24); static_assert(nonce.size() == 24);
static_assert(mac.size() == 16); static_assert(mac.size() == 16);
p->Send_binary(nonce); p->Send_binary(nonce);
p->Send_binary(mac); p->Send_binary(mac);
p->Send_binary(message); p->Send_binary(message);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -873,8 +870,8 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendRConResult(uint16_t colour
*/ */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendRConDenied() NetworkRecvStatus ServerNetworkGameSocketHandler::SendRConDenied()
{ {
Packet *p = new Packet(PACKET_SERVER_RCON, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_RCON, TCP_MTU);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
@ -885,84 +882,72 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendRConDenied()
*/ */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendMove(ClientID client_id, CompanyID company_id) NetworkRecvStatus ServerNetworkGameSocketHandler::SendMove(ClientID client_id, CompanyID company_id)
{ {
Packet *p = new Packet(PACKET_SERVER_MOVE, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_MOVE, TCP_MTU);
p->Send_uint32(client_id); p->Send_uint32(client_id);
p->Send_uint8(company_id); p->Send_uint8(company_id);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
/** Send an update about the company password states. */ /** Send an update about the company password states. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendCompanyUpdate() NetworkRecvStatus ServerNetworkGameSocketHandler::SendCompanyUpdate()
{ {
Packet *p = new Packet(PACKET_SERVER_COMPANY_UPDATE, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_COMPANY_UPDATE, TCP_MTU);
static_assert(sizeof(_network_company_passworded) <= sizeof(uint16_t)); static_assert(sizeof(_network_company_passworded) <= sizeof(uint16_t));
p->Send_uint16(_network_company_passworded); p->Send_uint16(_network_company_passworded);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
/** Send an update about the max company/spectator counts. */ /** Send an update about the max company/spectator counts. */
NetworkRecvStatus ServerNetworkGameSocketHandler::SendConfigUpdate() NetworkRecvStatus ServerNetworkGameSocketHandler::SendConfigUpdate()
{ {
Packet *p = new Packet(PACKET_SERVER_CONFIG_UPDATE, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_CONFIG_UPDATE, TCP_MTU);
p->Send_uint8(_settings_client.network.max_companies); p->Send_uint8(_settings_client.network.max_companies);
p->Send_string(_settings_client.network.server_name); p->Send_string(_settings_client.network.server_name);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ServerNetworkGameSocketHandler::SendSettingsAccessUpdate(bool ok) NetworkRecvStatus ServerNetworkGameSocketHandler::SendSettingsAccessUpdate(bool ok)
{ {
Packet *p = new Packet(PACKET_SERVER_SETTINGS_ACCESS, SHRT_MAX); auto p = std::make_unique<Packet>(PACKET_SERVER_SETTINGS_ACCESS, TCP_MTU);
p->Send_bool(ok); p->Send_bool(ok);
this->SendPacket(p); this->SendPacket(std::move(p));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
/*********** /***********
* Receiving functions * Receiving functions
* DEF_SERVER_RECEIVE_COMMAND has parameter: NetworkClientSocket *cs, Packet *p
************/ ************/
NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GAME_INFO(Packet *p) NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GAME_INFO(Packet &p)
{ {
if (p->CanReadFromPacket(9) && p->Recv_uint32() == FIND_SERVER_EXTENDED_TOKEN) { if (p.CanReadFromPacket(9) && p.Recv_uint32() == FIND_SERVER_EXTENDED_TOKEN) {
PacketGameType reply_type = (PacketGameType)p->Recv_uint8(); PacketGameType reply_type = (PacketGameType)p.Recv_uint8();
uint16_t flags = p->Recv_uint16(); uint16_t flags = p.Recv_uint16();
uint16_t version = p->Recv_uint16(); uint16_t version = p.Recv_uint16();
return this->SendGameInfoExtended(reply_type, flags, version); return this->SendGameInfoExtended(reply_type, flags, version);
} else { } else {
return this->SendGameInfo(); return this->SendGameInfo();
} }
} }
NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_NEWGRFS_CHECKED(Packet *) NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_NEWGRFS_CHECKED(Packet &)
{ {
if (this->status != STATUS_NEWGRFS_CHECK) { if (this->status != STATUS_NEWGRFS_CHECK) {
/* Illegal call, return error and ignore the packet */ /* Illegal call, return error and ignore the packet */
return this->SendError(NETWORK_ERROR_NOT_EXPECTED); return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
} }
NetworkClientInfo *ci = this->GetInfo(); return this->SendNeedGamePassword();
/* We now want a password from the client else we do not allow them in! */
if (!_settings_client.network.server_password.empty()) {
return this->SendNeedGamePassword();
}
if (Company::IsValidID(ci->client_playas) && !_network_company_states[ci->client_playas].password.empty()) {
return this->SendNeedCompanyPassword();
}
return this->SendWelcome();
} }
NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet *p) NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet &p)
{ {
if (this->status != STATUS_INACTIVE) { if (this->status != STATUS_INACTIVE) {
/* Illegal call, return error and ignore the packet */ /* Illegal call, return error and ignore the packet */
@ -974,8 +959,8 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet *p)
return this->SendError(NETWORK_ERROR_FULL); return this->SendError(NETWORK_ERROR_FULL);
} }
std::string client_revision = p->Recv_string(NETWORK_REVISION_LENGTH); std::string client_revision = p.Recv_string(NETWORK_REVISION_LENGTH);
uint32_t newgrf_version = p->Recv_uint32(); uint32_t newgrf_version = p.Recv_uint32();
/* Check if the client has revision control enabled */ /* Check if the client has revision control enabled */
if (!IsNetworkCompatibleVersion(client_revision.c_str()) || _openttd_newgrf_version != newgrf_version) { if (!IsNetworkCompatibleVersion(client_revision.c_str()) || _openttd_newgrf_version != newgrf_version) {
@ -983,8 +968,8 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet *p)
return this->SendError(NETWORK_ERROR_WRONG_REVISION); return this->SendError(NETWORK_ERROR_WRONG_REVISION);
} }
std::string client_name = p->Recv_string(NETWORK_CLIENT_NAME_LENGTH); std::string client_name = p.Recv_string(NETWORK_CLIENT_NAME_LENGTH);
CompanyID playas = (Owner)p->Recv_uint8(); CompanyID playas = (Owner)p.Recv_uint8();
if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT; if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT;
@ -1033,14 +1018,14 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet *p)
this->status = STATUS_NEWGRFS_CHECK; this->status = STATUS_NEWGRFS_CHECK;
if (_grfconfig == nullptr) { if (_grfconfig == nullptr) {
/* Behave as if we received PACKET_CLIENT_NEWGRFS_CHECKED */ /* Continue asking for the game password. */
return this->Receive_CLIENT_NEWGRFS_CHECKED(nullptr); return this->SendNeedGamePassword();
} }
return this->SendNewGRFCheck(); return this->SendNewGRFCheck();
} }
NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GAME_PASSWORD(Packet *p) NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GAME_PASSWORD(Packet &p)
{ {
if (this->status != STATUS_AUTH_GAME) { if (this->status != STATUS_AUTH_GAME) {
return this->SendError(NETWORK_ERROR_NOT_EXPECTED); return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
@ -1055,22 +1040,16 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GAME_PASSWORD(P
} }
} }
const NetworkClientInfo *ci = this->GetInfo(); return this->SendNeedCompanyPassword();
if (Company::IsValidID(ci->client_playas) && !_network_company_states[ci->client_playas].password.empty()) {
return this->SendNeedCompanyPassword();
}
/* Valid password, allow user */
return this->SendWelcome();
} }
NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMPANY_PASSWORD(Packet *p) NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMPANY_PASSWORD(Packet &p)
{ {
if (this->status != STATUS_AUTH_COMPANY) { if (this->status != STATUS_AUTH_COMPANY) {
return this->SendError(NETWORK_ERROR_NOT_EXPECTED); return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
} }
std::string password = p->Recv_string(NETWORK_PASSWORD_LENGTH); std::string password = p.Recv_string(NETWORK_PASSWORD_LENGTH);
/* Check company password. Allow joining if we cleared the password meanwhile. /* Check company password. Allow joining if we cleared the password meanwhile.
* Also, check the company is still valid - client could be moved to spectators * Also, check the company is still valid - client could be moved to spectators
@ -1085,7 +1064,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMPANY_PASSWOR
return this->SendWelcome(); return this->SendWelcome();
} }
NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SETTINGS_PASSWORD(Packet *p) NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SETTINGS_PASSWORD(Packet &p)
{ {
if (this->status != STATUS_ACTIVE) { if (this->status != STATUS_ACTIVE) {
/* Illegal call, return error and ignore the packet */ /* Illegal call, return error and ignore the packet */
@ -1095,7 +1074,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SETTINGS_PASSWO
NetworkSharedSecrets ss; NetworkSharedSecrets ss;
/* Check settings password. Deny if no password is set */ /* Check settings password. Deny if no password is set */
if (!p->CanReadFromPacket(1)) { if (!p.CanReadFromPacket(1)) {
if (this->settings_authed) DEBUG(net, 0, "[settings-ctrl] client-id %d deauthed", this->client_id); if (this->settings_authed) DEBUG(net, 0, "[settings-ctrl] client-id %d deauthed", this->client_id);
this->settings_authed = false; this->settings_authed = false;
} else if (_settings_client.network.settings_password.empty() || } else if (_settings_client.network.settings_password.empty() ||
@ -1114,7 +1093,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SETTINGS_PASSWO
return this->SendSettingsAccessUpdate(this->settings_authed); return this->SendSettingsAccessUpdate(this->settings_authed);
} }
NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GETMAP(Packet *p) NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GETMAP(Packet &p)
{ {
/* The client was never joined.. so this is impossible, right? /* The client was never joined.. so this is impossible, right?
* Ignore the packet, give the client a warning, and close the connection */ * Ignore the packet, give the client a warning, and close the connection */
@ -1122,7 +1101,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GETMAP(Packet *
return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED); return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
} }
this->supports_zstd = p->Recv_bool(); this->supports_zstd = p.Recv_bool();
/* Check if someone else is receiving the map */ /* Check if someone else is receiving the map */
for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) { for (NetworkClientSocket *new_cs : NetworkClientSocket::Iterate()) {
@ -1137,7 +1116,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_GETMAP(Packet *
return this->SendMap(); return this->SendMap();
} }
NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MAP_OK(Packet *) NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MAP_OK(Packet &)
{ {
/* Client has the map, now start syncing */ /* Client has the map, now start syncing */
if (this->status == STATUS_DONE_MAP && !this->HasClientQuit()) { if (this->status == STATUS_DONE_MAP && !this->HasClientQuit()) {
@ -1190,7 +1169,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MAP_OK(Packet *
* The client has done a command and wants us to handle it * The client has done a command and wants us to handle it
* @param p the packet in which the command was sent * @param p the packet in which the command was sent
*/ */
NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMMAND(Packet *p) NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMMAND(Packet &p)
{ {
/* The client was never joined.. so this is impossible, right? /* The client was never joined.. so this is impossible, right?
* Ignore the packet, give the client a warning, and close the connection */ * Ignore the packet, give the client a warning, and close the connection */
@ -1198,12 +1177,12 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMMAND(Packet
return this->SendError(NETWORK_ERROR_NOT_EXPECTED); return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
} }
if (this->incoming_queue.Count() >= _settings_client.network.max_commands_in_queue) { if (this->incoming_queue.size() >= _settings_client.network.max_commands_in_queue) {
return this->SendError(NETWORK_ERROR_TOO_MANY_COMMANDS); return this->SendError(NETWORK_ERROR_TOO_MANY_COMMANDS);
} }
CommandPacket cp; CommandPacket cp;
const char *err = this->ReceiveCommand(p, &cp); const char *err = this->ReceiveCommand(p, cp);
if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT; if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT;
@ -1252,19 +1231,19 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_COMMAND(Packet
if (GetCommandFlags(cp.cmd) & CMD_CLIENT_ID) cp.p2 = this->client_id; if (GetCommandFlags(cp.cmd) & CMD_CLIENT_ID) cp.p2 = this->client_id;
cp.client_id = this->client_id; cp.client_id = this->client_id;
this->incoming_queue.Append(std::move(cp)); this->incoming_queue.push_back(std::move(cp));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ERROR(Packet *p) NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ERROR(Packet &p)
{ {
/* This packets means a client noticed an error and is reporting this /* This packets means a client noticed an error and is reporting this
* to us. Display the error and report it to the other clients */ * to us. Display the error and report it to the other clients */
char client_name[NETWORK_CLIENT_NAME_LENGTH]; char client_name[NETWORK_CLIENT_NAME_LENGTH];
NetworkErrorCode errorno = (NetworkErrorCode)p->Recv_uint8(); NetworkErrorCode errorno = (NetworkErrorCode)p.Recv_uint8();
NetworkRecvStatus rx_status = p->CanReadFromPacket(1) ? (NetworkRecvStatus)p->Recv_uint8() : NETWORK_RECV_STATUS_OKAY; NetworkRecvStatus rx_status = p.CanReadFromPacket(1) ? (NetworkRecvStatus)p.Recv_uint8() : NETWORK_RECV_STATUS_OKAY;
int8_t status = p->CanReadFromPacket(1) ? (int8_t)p->Recv_uint8() : -1; int8_t status = p.CanReadFromPacket(1) ? (int8_t)p.Recv_uint8() : -1;
PacketGameType last_pkt_type = p->CanReadFromPacket(1) ? (PacketGameType)p->Recv_uint8() : PACKET_END; PacketGameType last_pkt_type = p.CanReadFromPacket(1) ? (PacketGameType)p.Recv_uint8() : PACKET_END;
/* The client was never joined.. thank the client for the packet, but ignore it */ /* The client was never joined.. thank the client for the packet, but ignore it */
if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) { if (this->status < STATUS_DONE_MAP || this->HasClientQuit()) {
@ -1312,32 +1291,32 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ERROR(Packet *p
return this->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT); return this->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT);
} }
NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_DESYNC_LOG(Packet *p) NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_DESYNC_LOG(Packet &p)
{ {
uint size = p->Recv_uint16(); uint size = p.Recv_uint16();
this->desync_log.resize(this->desync_log.size() + size); this->desync_log.resize(this->desync_log.size() + size);
p->Recv_binary((byte *)(this->desync_log.data() + this->desync_log.size() - size), size); p.Recv_binary((byte *)(this->desync_log.data() + this->desync_log.size() - size), size);
DEBUG(net, 2, "Received %u bytes of client desync log", size); DEBUG(net, 2, "Received %u bytes of client desync log", size);
this->receive_limit += p->Size(); this->receive_limit += p.Size();
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_DESYNC_MSG(Packet *p) NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_DESYNC_MSG(Packet &p)
{ {
EconTime::Date date = p->Recv_uint32(); EconTime::Date date = p.Recv_uint32();
EconTime::DateFract date_fract = p->Recv_uint16(); EconTime::DateFract date_fract = p.Recv_uint16();
uint8_t tick_skip_counter = p->Recv_uint8(); uint8_t tick_skip_counter = p.Recv_uint8();
std::string msg; std::string msg;
p->Recv_string(msg); p.Recv_string(msg);
DEBUG(desync, 0, "Client-id %d desync msg: %s", this->client_id, msg.c_str()); DEBUG(desync, 0, "Client-id %d desync msg: %s", this->client_id, msg.c_str());
extern void LogRemoteDesyncMsg(EconTime::Date date, EconTime::DateFract date_fract, uint8_t tick_skip_counter, uint32_t src_id, std::string msg); extern void LogRemoteDesyncMsg(EconTime::Date date, EconTime::DateFract date_fract, uint8_t tick_skip_counter, uint32_t src_id, std::string msg);
LogRemoteDesyncMsg(date, date_fract, tick_skip_counter, this->client_id, std::move(msg)); LogRemoteDesyncMsg(date, date_fract, tick_skip_counter, this->client_id, std::move(msg));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_DESYNC_SYNC_DATA(Packet *p) NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_DESYNC_SYNC_DATA(Packet &p)
{ {
uint32_t frame_count = p->Recv_uint32(); uint32_t frame_count = p.Recv_uint32();
DEBUG(net, 2, "Received desync sync data: %u frames", frame_count); DEBUG(net, 2, "Received desync sync data: %u frames", frame_count);
@ -1346,14 +1325,14 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_DESYNC_SYNC_DAT
size_t record_count_offset = 0; size_t record_count_offset = 0;
size_t record_offset = 0; size_t record_offset = 0;
for (uint i = 0; i < frame_count; i++) { for (uint i = 0; i < frame_count; i++) {
uint32_t item_count = p->Recv_uint32(); uint32_t item_count = p.Recv_uint32();
if (item_count == 0) continue; if (item_count == 0) continue;
uint32_t local_item_count = 0; uint32_t local_item_count = 0;
uint32_t frame = 0; uint32_t frame = 0;
NetworkSyncRecordEvents event = NSRE_BEGIN; NetworkSyncRecordEvents event = NSRE_BEGIN;
for (uint j = 0; j < item_count; j++) { for (uint j = 0; j < item_count; j++) {
if (j == 0) { if (j == 0) {
frame = p->Recv_uint32(); frame = p.Recv_uint32();
while (_network_sync_records[record_offset].frame != frame) { while (_network_sync_records[record_offset].frame != frame) {
if (record_count_offset == _network_sync_record_counts.size()) { if (record_count_offset == _network_sync_record_counts.size()) {
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
@ -1363,10 +1342,10 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_DESYNC_SYNC_DAT
} }
local_item_count = _network_sync_record_counts[record_count_offset]; local_item_count = _network_sync_record_counts[record_count_offset];
} else { } else {
event = (NetworkSyncRecordEvents)p->Recv_uint32(); event = (NetworkSyncRecordEvents)p.Recv_uint32();
} }
uint32_t seed_1 = p->Recv_uint32(); uint32_t seed_1 = p.Recv_uint32();
uint64_t state_checksum = p->Recv_uint64(); uint64_t state_checksum = p.Recv_uint64();
if (j == local_item_count) { if (j == local_item_count) {
this->desync_frame_info = stdstr_fmt("Desync subframe count mismatch: extra client record: %08X, %s", frame, GetSyncRecordEventName(event)); this->desync_frame_info = stdstr_fmt("Desync subframe count mismatch: extra client record: %08X, %s", frame, GetSyncRecordEventName(event));
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
@ -1394,7 +1373,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_DESYNC_SYNC_DAT
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_QUIT(Packet *p) NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_QUIT(Packet &p)
{ {
/* The client wants to leave. Display this and report it to the other /* The client wants to leave. Display this and report it to the other
* clients. */ * clients. */
@ -1420,14 +1399,14 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_QUIT(Packet *p)
return this->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT); return this->CloseConnection(NETWORK_RECV_STATUS_CLIENT_QUIT);
} }
NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ACK(Packet *p) NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ACK(Packet &p)
{ {
if (this->status < STATUS_AUTHORIZED) { if (this->status < STATUS_AUTHORIZED) {
/* Illegal call, return error and ignore the packet */ /* Illegal call, return error and ignore the packet */
return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED); return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
} }
uint32_t frame = p->Recv_uint32(); uint32_t frame = p.Recv_uint32();
/* The client is trying to catch up with the server */ /* The client is trying to catch up with the server */
if (this->status == STATUS_PRE_ACTIVE) { if (this->status == STATUS_PRE_ACTIVE) {
@ -1443,7 +1422,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_ACK(Packet *p)
} }
/* Get, and validate the token. */ /* Get, and validate the token. */
uint8_t token = p->Recv_uint8(); uint8_t token = p.Recv_uint8();
if (token == this->last_token) { if (token == this->last_token) {
/* We differentiate between last_token_frame and last_frame so the lag /* We differentiate between last_token_frame and last_frame so the lag
* test uses the actual lag of the client instead of the lag for getting * test uses the actual lag of the client instead of the lag for getting
@ -1604,18 +1583,18 @@ void NetworkServerSendExternalChat(const std::string &source, TextColour colour,
NetworkTextMessage(NETWORK_ACTION_EXTERNAL_CHAT, colour, false, user, msg, {}, source.c_str()); NetworkTextMessage(NETWORK_ACTION_EXTERNAL_CHAT, colour, false, user, msg, {}, source.c_str());
} }
NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_CHAT(Packet *p) NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_CHAT(Packet &p)
{ {
if (this->status < STATUS_PRE_ACTIVE) { if (this->status < STATUS_PRE_ACTIVE) {
/* Illegal call, return error and ignore the packet */ /* Illegal call, return error and ignore the packet */
return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED); return this->SendError(NETWORK_ERROR_NOT_AUTHORIZED);
} }
NetworkAction action = (NetworkAction)p->Recv_uint8(); NetworkAction action = (NetworkAction)p.Recv_uint8();
DestType desttype = (DestType)p->Recv_uint8(); DestType desttype = (DestType)p.Recv_uint8();
int dest = p->Recv_uint32(); int dest = p.Recv_uint32();
std::string msg = p->Recv_string(NETWORK_CHAT_LENGTH); std::string msg = p.Recv_string(NETWORK_CHAT_LENGTH);
NetworkTextMessageData data; NetworkTextMessageData data;
data.recv(p); data.recv(p);
@ -1636,21 +1615,21 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_CHAT(Packet *p)
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_PASSWORD(Packet *p) NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_PASSWORD(Packet &p)
{ {
if (this->status != STATUS_ACTIVE) { if (this->status != STATUS_ACTIVE) {
/* Illegal call, return error and ignore the packet */ /* Illegal call, return error and ignore the packet */
return this->SendError(NETWORK_ERROR_NOT_EXPECTED); return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
} }
std::string password = p->Recv_string(NETWORK_PASSWORD_LENGTH); std::string password = p.Recv_string(NETWORK_PASSWORD_LENGTH);
const NetworkClientInfo *ci = this->GetInfo(); const NetworkClientInfo *ci = this->GetInfo();
NetworkServerSetCompanyPassword(ci->client_playas, password); NetworkServerSetCompanyPassword(ci->client_playas, password);
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_NAME(Packet *p) NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_NAME(Packet &p)
{ {
if (this->status != STATUS_ACTIVE) { if (this->status != STATUS_ACTIVE) {
/* Illegal call, return error and ignore the packet */ /* Illegal call, return error and ignore the packet */
@ -1659,7 +1638,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_NAME(Packet
NetworkClientInfo *ci; NetworkClientInfo *ci;
std::string client_name = p->Recv_string(NETWORK_CLIENT_NAME_LENGTH); std::string client_name = p.Recv_string(NETWORK_CLIENT_NAME_LENGTH);
ci = this->GetInfo(); ci = this->GetInfo();
if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT; if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT;
@ -1682,7 +1661,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_NAME(Packet
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_RCON(Packet *p) NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_RCON(Packet &p)
{ {
if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED); if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
@ -1710,11 +1689,11 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_RCON(Packet *p)
return NETWORK_RECV_STATUS_OKAY; return NETWORK_RECV_STATUS_OKAY;
} }
NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MOVE(Packet *p) NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MOVE(Packet &p)
{ {
if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED); if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED);
CompanyID company_id = (Owner)p->Recv_uint8(); CompanyID company_id = (Owner)p.Recv_uint8();
/* Check if the company is valid, we don't allow moving to AI companies */ /* Check if the company is valid, we don't allow moving to AI companies */
if (company_id != COMPANY_SPECTATOR && !Company::IsValidHumanID(company_id)) return NETWORK_RECV_STATUS_OKAY; if (company_id != COMPANY_SPECTATOR && !Company::IsValidHumanID(company_id)) return NETWORK_RECV_STATUS_OKAY;
@ -1722,7 +1701,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_MOVE(Packet *p)
/* Check if we require a password for this company */ /* Check if we require a password for this company */
if (company_id != COMPANY_SPECTATOR && !_network_company_states[company_id].password.empty()) { if (company_id != COMPANY_SPECTATOR && !_network_company_states[company_id].password.empty()) {
/* we need a password from the client - should be in this packet */ /* we need a password from the client - should be in this packet */
std::string password = p->Recv_string(NETWORK_PASSWORD_LENGTH); std::string password = p.Recv_string(NETWORK_PASSWORD_LENGTH);
/* Incorrect password sent, return! */ /* Incorrect password sent, return! */
if (_network_company_states[company_id].password.compare(password) != 0) { if (_network_company_states[company_id].password.compare(password) != 0) {
@ -1981,10 +1960,8 @@ void NetworkServerSetCompanyPassword(CompanyID company_id, const std::string &pa
*/ */
static void NetworkHandleCommandQueue(NetworkClientSocket *cs) static void NetworkHandleCommandQueue(NetworkClientSocket *cs)
{ {
std::unique_ptr<CommandPacket> cp; for (auto &cp : cs->outgoing_queue) cs->SendCommand(cp);
while ((cp = cs->outgoing_queue.Pop()) != nullptr) { cs->outgoing_queue.clear();
cs->SendCommand(cp.get());
}
} }
/** /**

@ -27,26 +27,26 @@ class ServerNetworkGameSocketHandler : public NetworkClientSocketPool::PoolItem<
byte *rcon_reply_key = nullptr; byte *rcon_reply_key = nullptr;
protected: protected:
NetworkRecvStatus Receive_CLIENT_JOIN(Packet *p) override; NetworkRecvStatus Receive_CLIENT_JOIN(Packet &p) override;
NetworkRecvStatus Receive_CLIENT_GAME_INFO(Packet *p) override; NetworkRecvStatus Receive_CLIENT_GAME_INFO(Packet &p) override;
NetworkRecvStatus Receive_CLIENT_GAME_PASSWORD(Packet *p) override; NetworkRecvStatus Receive_CLIENT_GAME_PASSWORD(Packet &p) override;
NetworkRecvStatus Receive_CLIENT_COMPANY_PASSWORD(Packet *p) override; NetworkRecvStatus Receive_CLIENT_COMPANY_PASSWORD(Packet &p) override;
NetworkRecvStatus Receive_CLIENT_SETTINGS_PASSWORD(Packet *p) override; NetworkRecvStatus Receive_CLIENT_SETTINGS_PASSWORD(Packet &p) override;
NetworkRecvStatus Receive_CLIENT_GETMAP(Packet *p) override; NetworkRecvStatus Receive_CLIENT_GETMAP(Packet &p) override;
NetworkRecvStatus Receive_CLIENT_MAP_OK(Packet *p) override; NetworkRecvStatus Receive_CLIENT_MAP_OK(Packet &p) override;
NetworkRecvStatus Receive_CLIENT_ACK(Packet *p) override; NetworkRecvStatus Receive_CLIENT_ACK(Packet &p) override;
NetworkRecvStatus Receive_CLIENT_COMMAND(Packet *p) override; NetworkRecvStatus Receive_CLIENT_COMMAND(Packet &p) override;
NetworkRecvStatus Receive_CLIENT_CHAT(Packet *p) override; NetworkRecvStatus Receive_CLIENT_CHAT(Packet &p) override;
NetworkRecvStatus Receive_CLIENT_SET_PASSWORD(Packet *p) override; NetworkRecvStatus Receive_CLIENT_SET_PASSWORD(Packet &p) override;
NetworkRecvStatus Receive_CLIENT_SET_NAME(Packet *p) override; NetworkRecvStatus Receive_CLIENT_SET_NAME(Packet &p) override;
NetworkRecvStatus Receive_CLIENT_QUIT(Packet *p) override; NetworkRecvStatus Receive_CLIENT_QUIT(Packet &p) override;
NetworkRecvStatus Receive_CLIENT_ERROR(Packet *p) override; NetworkRecvStatus Receive_CLIENT_ERROR(Packet &p) override;
NetworkRecvStatus Receive_CLIENT_DESYNC_LOG(Packet *p) override; NetworkRecvStatus Receive_CLIENT_DESYNC_LOG(Packet &p) override;
NetworkRecvStatus Receive_CLIENT_DESYNC_MSG(Packet *p) override; NetworkRecvStatus Receive_CLIENT_DESYNC_MSG(Packet &p) override;
NetworkRecvStatus Receive_CLIENT_DESYNC_SYNC_DATA(Packet *p) override; NetworkRecvStatus Receive_CLIENT_DESYNC_SYNC_DATA(Packet &p) override;
NetworkRecvStatus Receive_CLIENT_RCON(Packet *p) override; NetworkRecvStatus Receive_CLIENT_RCON(Packet &p) override;
NetworkRecvStatus Receive_CLIENT_NEWGRFS_CHECKED(Packet *p) override; NetworkRecvStatus Receive_CLIENT_NEWGRFS_CHECKED(Packet &p) override;
NetworkRecvStatus Receive_CLIENT_MOVE(Packet *p) override; NetworkRecvStatus Receive_CLIENT_MOVE(Packet &p) override;
NetworkRecvStatus SendGameInfo(); NetworkRecvStatus SendGameInfo();
NetworkRecvStatus SendGameInfoExtended(PacketGameType reply_type, uint16_t flags, uint16_t version); NetworkRecvStatus SendGameInfoExtended(PacketGameType reply_type, uint16_t flags, uint16_t version);
@ -55,7 +55,7 @@ protected:
NetworkRecvStatus SendNeedGamePassword(); NetworkRecvStatus SendNeedGamePassword();
NetworkRecvStatus SendNeedCompanyPassword(); NetworkRecvStatus SendNeedCompanyPassword();
bool ParseKeyPasswordPacket(Packet *p, NetworkSharedSecrets &ss, const std::string &password, std::string *payload, size_t length); bool ParseKeyPasswordPacket(Packet &p, NetworkSharedSecrets &ss, const std::string &password, std::string *payload, size_t length);
public: public:
/** Status of a client */ /** Status of a client */
@ -80,7 +80,7 @@ public:
byte last_token; ///< The last random token we did send to verify the client is listening byte last_token; ///< The last random token we did send to verify the client is listening
uint32_t last_token_frame; ///< The last frame we received the right token uint32_t last_token_frame; ///< The last frame we received the right token
ClientStatus status; ///< Status of this client ClientStatus status; ///< Status of this client
CommandQueue outgoing_queue; ///< The command-queue awaiting delivery CommandQueue outgoing_queue; ///< The command-queue awaiting delivery; conceptually more a bucket to gather commands in, after which the whole bucket is sent to the client.
size_t receive_limit; ///< Amount of bytes that we can receive at this moment size_t receive_limit; ///< Amount of bytes that we can receive at this moment
bool settings_authed = false;///< Authorised to control all game settings bool settings_authed = false;///< Authorised to control all game settings
bool supports_zstd = false; ///< Client supports zstd compression bool supports_zstd = false; ///< Client supports zstd compression
@ -121,7 +121,7 @@ public:
NetworkRecvStatus SendJoin(ClientID client_id); NetworkRecvStatus SendJoin(ClientID client_id);
NetworkRecvStatus SendFrame(); NetworkRecvStatus SendFrame();
NetworkRecvStatus SendSync(); NetworkRecvStatus SendSync();
NetworkRecvStatus SendCommand(const CommandPacket *cp); NetworkRecvStatus SendCommand(const CommandPacket &cp);
NetworkRecvStatus SendCompanyUpdate(); NetworkRecvStatus SendCompanyUpdate();
NetworkRecvStatus SendConfigUpdate(); NetworkRecvStatus SendConfigUpdate();
NetworkRecvStatus SendSettingsAccessUpdate(bool ok); NetworkRecvStatus SendSettingsAccessUpdate(bool ok);

@ -86,12 +86,12 @@ std::unique_ptr<ClientNetworkStunSocketHandler> ClientNetworkStunSocketHandler::
stun_handler->Connect(token, family); stun_handler->Connect(token, family);
Packet *p = new Packet(PACKET_STUN_SERCLI_STUN); auto p = std::make_unique<Packet>(PACKET_STUN_SERCLI_STUN);
p->Send_uint8(NETWORK_COORDINATOR_VERSION); p->Send_uint8(NETWORK_COORDINATOR_VERSION);
p->Send_string(token); p->Send_string(token);
p->Send_uint8(family); p->Send_uint8(family);
stun_handler->SendPacket(p); stun_handler->SendPacket(std::move(p));
return stun_handler; return stun_handler;
} }

@ -32,6 +32,8 @@ public:
void OnFailure() override void OnFailure() override
{ {
DEBUG(net, 9, "Turn::OnFailure()");
this->handler->connecter = nullptr; this->handler->connecter = nullptr;
this->handler->ConnectFailure(); this->handler->ConnectFailure();
@ -39,22 +41,28 @@ public:
void OnConnect(SOCKET s) override void OnConnect(SOCKET s) override
{ {
DEBUG(net, 9, "Turn::OnConnect()");
this->handler->connecter = nullptr; this->handler->connecter = nullptr;
this->handler->sock = s; this->handler->sock = s;
} }
}; };
bool ClientNetworkTurnSocketHandler::Receive_TURN_ERROR(Packet *) bool ClientNetworkTurnSocketHandler::Receive_TURN_ERROR(Packet &)
{ {
DEBUG(net, 9, "Receive_TURN_ERROR()");
this->ConnectFailure(); this->ConnectFailure();
return false; return false;
} }
bool ClientNetworkTurnSocketHandler::Receive_TURN_CONNECTED(Packet *p) bool ClientNetworkTurnSocketHandler::Receive_TURN_CONNECTED(Packet &p)
{ {
std::string hostname = p->Recv_string(NETWORK_HOSTNAME_LENGTH); DEBUG(net, 9, "Receive_TURN_CONNECTED()");
std::string hostname = p.Recv_string(NETWORK_HOSTNAME_LENGTH);
/* Act like we no longer have a socket, as we are handing it over to the /* Act like we no longer have a socket, as we are handing it over to the
* game handler. */ * game handler. */
@ -72,6 +80,8 @@ bool ClientNetworkTurnSocketHandler::Receive_TURN_CONNECTED(Packet *p)
*/ */
void ClientNetworkTurnSocketHandler::Connect() void ClientNetworkTurnSocketHandler::Connect()
{ {
DEBUG(net, 9, "Turn::Connect()");
this->connect_started = true; this->connect_started = true;
this->connecter = TCPConnecter::Create<NetworkTurnConnecter>(this, this->connection_string); this->connecter = TCPConnecter::Create<NetworkTurnConnecter>(this, this->connection_string);
} }
@ -90,11 +100,11 @@ void ClientNetworkTurnSocketHandler::Connect()
{ {
auto turn_handler = std::make_unique<ClientNetworkTurnSocketHandler>(token, tracking_number, connection_string); auto turn_handler = std::make_unique<ClientNetworkTurnSocketHandler>(token, tracking_number, connection_string);
Packet *p = new Packet(PACKET_TURN_SERCLI_CONNECT); auto p = std::make_unique<Packet>(PACKET_TURN_SERCLI_CONNECT);
p->Send_uint8(NETWORK_COORDINATOR_VERSION); p->Send_uint8(NETWORK_COORDINATOR_VERSION);
p->Send_string(ticket); p->Send_string(ticket);
turn_handler->SendPacket(p); turn_handler->SendPacket(std::move(p));
return turn_handler; return turn_handler;
} }

@ -20,8 +20,8 @@ private:
std::string connection_string; ///< The connection string of the TURN server we are connecting to. std::string connection_string; ///< The connection string of the TURN server we are connecting to.
protected: protected:
bool Receive_TURN_ERROR(Packet *p) override; bool Receive_TURN_ERROR(Packet &p) override;
bool Receive_TURN_CONNECTED(Packet *p) override; bool Receive_TURN_CONNECTED(Packet &p) override;
public: public:
std::shared_ptr<TCPConnecter> connecter{}; ///< Connecter instance. std::shared_ptr<TCPConnecter> connecter{}; ///< Connecter instance.

@ -157,14 +157,14 @@ struct NetworkTextMessageData {
NetworkTextMessageData(int64_t data = 0, int64_t auxdata = 0) NetworkTextMessageData(int64_t data = 0, int64_t auxdata = 0)
: data(data), auxdata(auxdata) { } : data(data), auxdata(auxdata) { }
template <typename T> void recv(T *p) { template <typename T> void recv(T &p) {
this->data = p->Recv_uint64(); this->data = p.Recv_uint64();
this->auxdata = p->Recv_uint64(); this->auxdata = p.Recv_uint64();
} }
template <typename T> void send(T *p) const { template <typename T> void send(T &p) const {
p->Send_uint64(this->data); p.Send_uint64(this->data);
p->Send_uint64(this->auxdata); p.Send_uint64(this->auxdata);
} }
}; };

@ -74,8 +74,8 @@ static Packet PrepareUdpClientFindServerPacket()
/** Helper class for handling all server side communication. */ /** Helper class for handling all server side communication. */
class ServerNetworkUDPSocketHandler : public NetworkUDPSocketHandler { class ServerNetworkUDPSocketHandler : public NetworkUDPSocketHandler {
protected: protected:
void Receive_CLIENT_FIND_SERVER(Packet *p, NetworkAddress *client_addr) override; void Receive_CLIENT_FIND_SERVER(Packet &p, NetworkAddress &client_addr) override;
void Reply_CLIENT_FIND_SERVER_extended(Packet *p, NetworkAddress *client_addr); void Reply_CLIENT_FIND_SERVER_extended(Packet &p, NetworkAddress &client_addr);
public: public:
/** /**
* Create the socket. * Create the socket.
@ -85,28 +85,28 @@ public:
virtual ~ServerNetworkUDPSocketHandler() = default; virtual ~ServerNetworkUDPSocketHandler() = default;
}; };
void ServerNetworkUDPSocketHandler::Receive_CLIENT_FIND_SERVER(Packet *p, NetworkAddress *client_addr) void ServerNetworkUDPSocketHandler::Receive_CLIENT_FIND_SERVER(Packet &p, NetworkAddress &client_addr)
{ {
if (p->CanReadFromPacket(8) && p->Recv_uint32() == FIND_SERVER_EXTENDED_TOKEN) { if (p.CanReadFromPacket(8) && p.Recv_uint32() == FIND_SERVER_EXTENDED_TOKEN) {
this->Reply_CLIENT_FIND_SERVER_extended(p, client_addr); this->Reply_CLIENT_FIND_SERVER_extended(p, client_addr);
return; return;
} }
Packet packet(PACKET_UDP_SERVER_RESPONSE); Packet packet(PACKET_UDP_SERVER_RESPONSE);
this->SendPacket(&packet, client_addr); this->SendPacket(packet, client_addr);
DEBUG(net, 7, "Queried from %s", client_addr->GetHostname()); DEBUG(net, 7, "Queried from %s", client_addr.GetHostname());
} }
void ServerNetworkUDPSocketHandler::Reply_CLIENT_FIND_SERVER_extended(Packet *p, NetworkAddress *client_addr) void ServerNetworkUDPSocketHandler::Reply_CLIENT_FIND_SERVER_extended(Packet &p, NetworkAddress &client_addr)
{ {
[[maybe_unused]] uint16_t flags = p->Recv_uint16(); [[maybe_unused]] uint16_t flags = p.Recv_uint16();
uint16_t version = p->Recv_uint16(); uint16_t version = p.Recv_uint16();
Packet packet(PACKET_UDP_EX_SERVER_RESPONSE); Packet packet(PACKET_UDP_EX_SERVER_RESPONSE);
this->SendPacket(&packet, client_addr); this->SendPacket(packet, client_addr);
DEBUG(net, 7, "Queried (extended: %u) from %s", version, client_addr->GetHostname()); DEBUG(net, 7, "Queried (extended: %u) from %s", version, client_addr.GetHostname());
} }
///*** Communication with servers (we are client) ***/ ///*** Communication with servers (we are client) ***/
@ -114,24 +114,24 @@ void ServerNetworkUDPSocketHandler::Reply_CLIENT_FIND_SERVER_extended(Packet *p,
/** Helper class for handling all client side communication. */ /** Helper class for handling all client side communication. */
class ClientNetworkUDPSocketHandler : public NetworkUDPSocketHandler { class ClientNetworkUDPSocketHandler : public NetworkUDPSocketHandler {
protected: protected:
void Receive_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr) override; void Receive_SERVER_RESPONSE(Packet &p, NetworkAddress &client_addr) override;
void Receive_EX_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr) override; void Receive_EX_SERVER_RESPONSE(Packet &p, NetworkAddress &client_addr) override;
public: public:
virtual ~ClientNetworkUDPSocketHandler() = default; virtual ~ClientNetworkUDPSocketHandler() = default;
}; };
void ClientNetworkUDPSocketHandler::Receive_SERVER_RESPONSE(Packet *, NetworkAddress *client_addr) void ClientNetworkUDPSocketHandler::Receive_SERVER_RESPONSE(Packet &, NetworkAddress &client_addr)
{ {
DEBUG(net, 3, "Server response from %s", NetworkAddressDumper().GetAddressAsString(client_addr)); DEBUG(net, 3, "Server response from %s", NetworkAddressDumper().GetAddressAsString(client_addr));
NetworkAddServer(client_addr->GetAddressAsString(false), false, true); NetworkAddServer(client_addr.GetAddressAsString(false), false, true);
} }
void ClientNetworkUDPSocketHandler::Receive_EX_SERVER_RESPONSE(Packet *p, NetworkAddress *client_addr) void ClientNetworkUDPSocketHandler::Receive_EX_SERVER_RESPONSE(Packet &, NetworkAddress &client_addr)
{ {
DEBUG(net, 3, "Extended server response from %s", NetworkAddressDumper().GetAddressAsString(client_addr)); DEBUG(net, 3, "Extended server response from %s", NetworkAddressDumper().GetAddressAsString(client_addr));
NetworkAddServer(client_addr->GetAddressAsString(false), false, true); // TODO, mark as extended NetworkAddServer(client_addr.GetAddressAsString(false), false, true); // TODO, mark as extended
} }
/** Broadcast to all ips */ /** Broadcast to all ips */
@ -141,7 +141,7 @@ static void NetworkUDPBroadCast(NetworkUDPSocketHandler *socket)
DEBUG(net, 5, "Broadcasting to %s", addr.GetHostname()); DEBUG(net, 5, "Broadcasting to %s", addr.GetHostname());
Packet p = PrepareUdpClientFindServerPacket(); Packet p = PrepareUdpClientFindServerPacket();
socket->SendPacket(&p, &addr, true, true); socket->SendPacket(p, addr, true, true);
} }
} }

@ -2426,7 +2426,7 @@ static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, con
* in the temperate climate. */ * in the temperate climate. */
CargoID cid = housespec->accepts_cargo[2]; CargoID cid = housespec->accepts_cargo[2];
if (!IsValidCargoID(cid)) cid = GetCargoIDByLabel(housespec->accepts_cargo_label[2]); if (!IsValidCargoID(cid)) cid = GetCargoIDByLabel(housespec->accepts_cargo_label[2]);
if (!IsValidCargoID(cid) || !CargoSpec::Get(cid)->IsValid()) { if (!IsValidCargoID(cid)) {
housespec->cargo_acceptance[2] = 0; housespec->cargo_acceptance[2] = 0;
} }
} }
@ -2466,7 +2466,7 @@ static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, con
((_settings_game.game_creation.landscape == LT_TOYLAND) ? GetCargoIDByLabel(CT_FIZZY_DRINKS) : GetCargoIDByLabel(CT_FOOD)); ((_settings_game.game_creation.landscape == LT_TOYLAND) ? GetCargoIDByLabel(CT_FIZZY_DRINKS) : GetCargoIDByLabel(CT_FOOD));
/* Make sure the cargo type is valid in this climate. */ /* Make sure the cargo type is valid in this climate. */
if (!CargoSpec::Get(cid)->IsValid()) goods = 0; if (!IsValidCargoID(cid)) goods = 0;
housespec->accepts_cargo[2] = cid; housespec->accepts_cargo[2] = cid;
housespec->accepts_cargo_label[2] = CT_INVALID; housespec->accepts_cargo_label[2] = CT_INVALID;
@ -10613,6 +10613,38 @@ GRFFile::~GRFFile()
delete[] this->language_map; delete[] this->language_map;
} }
/**
* Find first cargo label that exists and is active from a list of cargo labels.
* @param labels List of cargo labels.
* @returns First cargo label in list that exists, or CT_INVALID if none exist.
*/
static CargoLabel GetActiveCargoLabel(const std::initializer_list<CargoLabel> &labels)
{
for (const CargoLabel &label : labels) {
CargoID cid = GetCargoIDByLabel(label);
if (cid != INVALID_CARGO) return label;
}
return CT_INVALID;
}
/**
* Get active cargo label from either a cargo label or climate-dependent mixed cargo type.
* @param label Cargo label or climate-dependent mixed cargo type.
* @returns Active cargo label, or CT_INVALID if cargo label is not active.
*/
static CargoLabel GetActiveCargoLabel(const std::variant<CargoLabel, MixedCargoType> &label)
{
if (std::holds_alternative<CargoLabel>(label)) return std::get<CargoLabel>(label);
if (std::holds_alternative<MixedCargoType>(label)) {
switch (std::get<MixedCargoType>(label)) {
case MCT_LIVESTOCK_FRUIT: return GetActiveCargoLabel({CT_LIVESTOCK, CT_FRUIT});
case MCT_GRAIN_WHEAT_MAIZE: return GetActiveCargoLabel({CT_GRAIN, CT_WHEAT, CT_MAIZE});
case MCT_VALUABLES_GOLD_DIAMONDS: return GetActiveCargoLabel({CT_VALUABLES, CT_GOLD, CT_DIAMONDS});
default: NOT_REACHED();
}
}
NOT_REACHED();
}
/** /**
* Precalculate refit masks from cargo classes for all vehicles. * Precalculate refit masks from cargo classes for all vehicles.
@ -10631,7 +10663,7 @@ static void CalculateRefitMasks()
/* Apply default cargo translation map if cargo type hasn't been set, either explicitly or by aircraft cargo handling. */ /* Apply default cargo translation map if cargo type hasn't been set, either explicitly or by aircraft cargo handling. */
if (!IsValidCargoID(e->info.cargo_type)) { if (!IsValidCargoID(e->info.cargo_type)) {
e->info.cargo_type = GetCargoIDByLabel(e->info.cargo_label); e->info.cargo_type = GetCargoIDByLabel(GetActiveCargoLabel(e->info.cargo_label));
} }
/* If the NewGRF did not set any cargo properties, we apply default values. */ /* If the NewGRF did not set any cargo properties, we apply default values. */
@ -10668,7 +10700,8 @@ static void CalculateRefitMasks()
_gted[engine].cargo_allowed = CC_PASSENGERS | CC_MAIL | CC_ARMOURED | CC_EXPRESS; _gted[engine].cargo_allowed = CC_PASSENGERS | CC_MAIL | CC_ARMOURED | CC_EXPRESS;
_gted[engine].cargo_disallowed = CC_LIQUID; _gted[engine].cargo_disallowed = CC_LIQUID;
} else if (e->type == VEH_SHIP) { } else if (e->type == VEH_SHIP) {
switch (ei->cargo_label.base()) { CargoLabel label = GetActiveCargoLabel(ei->cargo_label);
switch (label.base()) {
case CT_PASSENGERS.base(): case CT_PASSENGERS.base():
/* Ferries */ /* Ferries */
_gted[engine].cargo_allowed = CC_PASSENGERS; _gted[engine].cargo_allowed = CC_PASSENGERS;
@ -10699,9 +10732,10 @@ static void CalculateRefitMasks()
_gted[engine].cargo_disallowed = 0; _gted[engine].cargo_disallowed = 0;
} else { } else {
/* Train wagons and road vehicles are classified by their default cargo type */ /* Train wagons and road vehicles are classified by their default cargo type */
CargoLabel label = GetActiveCargoLabel(ei->cargo_label);
for (const auto &drm : _default_refit_masks) { for (const auto &drm : _default_refit_masks) {
if (!HasBit(drm.climate, _settings_game.game_creation.landscape)) continue; if (!HasBit(drm.climate, _settings_game.game_creation.landscape)) continue;
if (drm.cargo_label != ei->cargo_label) continue; if (drm.cargo_label != label) continue;
_gted[engine].cargo_allowed = drm.cargo_allowed; _gted[engine].cargo_allowed = drm.cargo_allowed;
_gted[engine].cargo_disallowed = drm.cargo_disallowed; _gted[engine].cargo_disallowed = drm.cargo_disallowed;
@ -11097,17 +11131,17 @@ static void FinaliseIndustriesArray()
/* Apply default cargo translation map for unset cargo slots */ /* Apply default cargo translation map for unset cargo slots */
for (uint i = 0; i < lengthof(indsp.produced_cargo); ++i) { for (uint i = 0; i < lengthof(indsp.produced_cargo); ++i) {
if (!IsValidCargoID(indsp.produced_cargo[i])) indsp.produced_cargo[i] = GetCargoIDByLabel(indsp.produced_cargo_label[i]); if (!IsValidCargoID(indsp.produced_cargo[i])) indsp.produced_cargo[i] = GetCargoIDByLabel(GetActiveCargoLabel(indsp.produced_cargo_label[i]));
} }
for (uint i = 0; i < lengthof(indsp.accepts_cargo); ++i) { for (uint i = 0; i < lengthof(indsp.accepts_cargo); ++i) {
if (!IsValidCargoID(indsp.accepts_cargo[i])) indsp.accepts_cargo[i] = GetCargoIDByLabel(indsp.accepts_cargo_label[i]); if (!IsValidCargoID(indsp.accepts_cargo[i])) indsp.accepts_cargo[i] = GetCargoIDByLabel(GetActiveCargoLabel(indsp.accepts_cargo_label[i]));
} }
} }
for (auto &indtsp : _industry_tile_specs) { for (auto &indtsp : _industry_tile_specs) {
/* Apply default cargo translation map for unset cargo slots */ /* Apply default cargo translation map for unset cargo slots */
for (uint i = 0; i < lengthof(indtsp.accepts_cargo); ++i) { for (uint i = 0; i < lengthof(indtsp.accepts_cargo); ++i) {
if (!IsValidCargoID(indtsp.accepts_cargo[i])) indtsp.accepts_cargo[i] = GetCargoIDByLabel(indtsp.accepts_cargo_label[i]); if (!IsValidCargoID(indtsp.accepts_cargo[i])) indtsp.accepts_cargo[i] = GetCargoIDByLabel(GetActiveCargoLabel(indtsp.accepts_cargo_label[i]));
} }
} }
} }

@ -1912,12 +1912,9 @@ private:
/** /**
* Draw dynamic a signal-sprite in a button in the signal GUI * Draw dynamic a signal-sprite in a button in the signal GUI
* Draw the sprite +1px to the right and down if the button is lowered
*
* @param widget_index index of this widget in the window
* @param image the sprite to draw * @param image the sprite to draw
*/ */
void DrawSignalSprite(const Rect &r, WidgetID widget_index, PalSpriteID image) const void DrawSignalSprite(const Rect &r, PalSpriteID image) const
{ {
Point offset; Point offset;
Dimension sprite_size = GetSpriteSize(image.sprite, &offset); Dimension sprite_size = GetSpriteSize(image.sprite, &offset);
@ -1926,9 +1923,7 @@ private:
int y = ir.top - sig_sprite_bottom_offset + int y = ir.top - sig_sprite_bottom_offset +
(ir.Height() + sig_sprite_size.height) / 2; // aligned to bottom (ir.Height() + sig_sprite_size.height) / 2; // aligned to bottom
DrawSprite(image.sprite, image.pal, DrawSprite(image.sprite, image.pal, x, y);
x + this->IsWidgetLowered(widget_index),
y + this->IsWidgetLowered(widget_index));
} }
void SetDisableStates() void SetDisableStates()
@ -2100,7 +2095,7 @@ public:
sprite = GetRailTypeInfo(_cur_railtype)->gui_sprites.signals[type][var][this->IsWidgetLowered(widget)]; sprite = GetRailTypeInfo(_cur_railtype)->gui_sprites.signals[type][var][this->IsWidgetLowered(widget)];
} }
this->DrawSignalSprite(r, widget, sprite); this->DrawSignalSprite(r, sprite);
} }
} }

@ -1751,14 +1751,21 @@ public:
this->OnClick({}, WID_BROS_IMAGE, 1); this->OnClick({}, WID_BROS_IMAGE, 1);
} }
static HotkeyList hotkeys; static HotkeyList road_hotkeys;
static HotkeyList tram_hotkeys;
}; };
static Hotkey buildroadstop_hotkeys[] = { static Hotkey buildroadstop_hotkeys[] = {
Hotkey('F', "focus_filter_box", BROSHK_FOCUS_FILTER_BOX), Hotkey('F', "focus_filter_box", BROSHK_FOCUS_FILTER_BOX),
HOTKEY_LIST_END HOTKEY_LIST_END
}; };
HotkeyList BuildRoadStationWindow::hotkeys("buildroadstop", buildroadstop_hotkeys); HotkeyList BuildRoadStationWindow::road_hotkeys("buildroadstop", buildroadstop_hotkeys);
static Hotkey buildtramstop_hotkeys[] = {
Hotkey('F', "focus_filter_box", BROSHK_FOCUS_FILTER_BOX),
HOTKEY_LIST_END
};
HotkeyList BuildRoadStationWindow::tram_hotkeys("buildtramstop", buildtramstop_hotkeys);
Listing BuildRoadStationWindow::last_sorting = { false, 0 }; Listing BuildRoadStationWindow::last_sorting = { false, 0 };
Filtering BuildRoadStationWindow::last_filtering = { false, 0 }; Filtering BuildRoadStationWindow::last_filtering = { false, 0 };
@ -1857,7 +1864,8 @@ static WindowDesc _road_station_picker_desc(__FILE__, __LINE__,
WDP_AUTO, "build_station_road", 0, 0, WDP_AUTO, "build_station_road", 0, 0,
WC_BUS_STATION, WC_BUILD_TOOLBAR, WC_BUS_STATION, WC_BUILD_TOOLBAR,
WDF_CONSTRUCTION, WDF_CONSTRUCTION,
std::begin(_nested_road_station_picker_widgets), std::end(_nested_road_station_picker_widgets) std::begin(_nested_road_station_picker_widgets), std::end(_nested_road_station_picker_widgets),
&BuildRoadStationWindow::road_hotkeys
); );
/** Widget definition of the build tram station window */ /** Widget definition of the build tram station window */
@ -1934,7 +1942,8 @@ static WindowDesc _tram_station_picker_desc(__FILE__, __LINE__,
WDP_AUTO, "build_station_tram", 0, 0, WDP_AUTO, "build_station_tram", 0, 0,
WC_BUS_STATION, WC_BUILD_TOOLBAR, WC_BUS_STATION, WC_BUILD_TOOLBAR,
WDF_CONSTRUCTION, WDF_CONSTRUCTION,
std::begin(_nested_tram_station_picker_widgets), std::end(_nested_tram_station_picker_widgets) std::begin(_nested_tram_station_picker_widgets), std::end(_nested_tram_station_picker_widgets),
&BuildRoadStationWindow::tram_hotkeys
); );
static void ShowRVStationPicker(Window *parent, RoadStopType rs) static void ShowRVStationPicker(Window *parent, RoadStopType rs)

@ -21,6 +21,7 @@
* \li AITimeMode * \li AITimeMode
* \li AITown::ROAD_LAYOUT_RANDOM * \li AITown::ROAD_LAYOUT_RANDOM
* \li AIVehicle::IsPrimaryVehicle * \li AIVehicle::IsPrimaryVehicle
* \li AITileList_StationCoverage
* *
* API removals: * API removals:
* \li AIError::ERR_PRECONDITION_TOO_MANY_PARAMETERS, that error is never returned anymore. * \li AIError::ERR_PRECONDITION_TOO_MANY_PARAMETERS, that error is never returned anymore.

@ -87,10 +87,11 @@
* \li GSStoryPage::IsValidStoryPageButtonColour * \li GSStoryPage::IsValidStoryPageButtonColour
* \li GSStoryPage::IsValidStoryPageButtonFlags * \li GSStoryPage::IsValidStoryPageButtonFlags
* \li GSStoryPage::IsValidStoryPageButtonCursor * \li GSStoryPage::IsValidStoryPageButtonCursor
* \li GSTileList_StationCoverage
* *
* API removals: * API removals:
* \li GSError::ERR_PRECONDITION_TOO_MANY_PARAMETERS, that error is never returned anymore. * \li GSError::ERR_PRECONDITION_TOO_MANY_PARAMETERS, that error is never returned anymore.
* \li AIInfo::CONFIG_RANDOM, no longer used. * \li GSInfo::CONFIG_RANDOM, no longer used.
* *
* Other changes: * Other changes:
* \li GSGroupList accepts an optional filter function * \li GSGroupList accepts an optional filter function

@ -185,6 +185,8 @@
{ {
company = ResolveCompanyID(company); company = ResolveCompanyID(company);
if (company == COMPANY_INVALID) return -1; if (company == COMPANY_INVALID) return -1;
/* If we return INT64_MAX as usual, overflows may occur in the script. So return a smaller value. */
if (_settings_game.difficulty.infinite_money) return INT32_MAX;
return GetAvailableMoney((::CompanyID)company); return GetAvailableMoney((::CompanyID)company);
} }

@ -260,9 +260,10 @@ public:
/** /**
* Gets the bank balance. In other words, the amount of money the given company can spent. * Gets the bank balance. In other words, the amount of money the given company can spent.
* If infinite money is enabled, it returns INT32_MAX.
* @param company The company to get the bank balance of. * @param company The company to get the bank balance of.
* @pre ResolveCompanyID(company) != COMPANY_INVALID. * @pre ResolveCompanyID(company) != COMPANY_INVALID.
* @return The actual bank balance. * @return The actual bank balance or INT32_MAX.
*/ */
static Money GetBankBalance(CompanyID company); static Money GetBankBalance(CompanyID company);

@ -284,6 +284,15 @@ void ScriptText::_FillParamList(ParamList &params)
} }
} }
void ScriptText::ParamCheck::Encode(std::back_insert_iterator<std::string> &output)
{
if (this->used) return;
if (std::holds_alternative<std::string>(*this->param)) fmt::format_to(output, ":\"{}\"", std::get<std::string>(*this->param));
if (std::holds_alternative<SQInteger>(*this->param)) fmt::format_to(output, ":{:X}", std::get<SQInteger>(*this->param));
if (std::holds_alternative<ScriptTextRef>(*this->param)) fmt::format_to(output, ":{:X}", this->owner);
this->used = true;
}
void ScriptText::_GetEncodedText(std::back_insert_iterator<std::string> &output, int &param_count, StringIDList &seen_ids, ParamSpan args) void ScriptText::_GetEncodedText(std::back_insert_iterator<std::string> &output, int &param_count, StringIDList &seen_ids, ParamSpan args)
{ {
const std::string &name = GetGameStringName(this->string); const std::string &name = GetGameStringName(this->string);
@ -301,7 +310,7 @@ void ScriptText::_GetEncodedText(std::back_insert_iterator<std::string> &output,
if (idx >= args.size()) throw Script_FatalError(fmt::format("{}({}): Not enough parameters", name, param_count + 1)); if (idx >= args.size()) throw Script_FatalError(fmt::format("{}({}): Not enough parameters", name, param_count + 1));
ParamCheck &pc = args[idx++]; ParamCheck &pc = args[idx++];
if (pc.owner != this->string) ScriptLog::Warning(fmt::format("{}({}): Consumes {}({})", name, param_count + 1, GetGameStringName(pc.owner), pc.idx + 1)); if (pc.owner != this->string) ScriptLog::Warning(fmt::format("{}({}): Consumes {}({})", name, param_count + 1, GetGameStringName(pc.owner), pc.idx + 1));
return pc.param; return &pc;
}; };
auto skip_args = [&](size_t nb) { idx += nb; }; auto skip_args = [&](size_t nb) { idx += nb; };
@ -312,19 +321,24 @@ void ScriptText::_GetEncodedText(std::back_insert_iterator<std::string> &output,
break; break;
case StringParam::RAW_STRING: { case StringParam::RAW_STRING: {
Param *p = get_next_arg(); ParamCheck &p = *get_next_arg();
if (!std::holds_alternative<std::string>(*p)) throw Script_FatalError(fmt::format("{}({}): {{{}}} expects a raw string", name, param_count + 1, cur_param.cmd)); if (!std::holds_alternative<std::string>(*p.param)) ScriptLog::Error(fmt::format("{}({}): {{{}}} expects a raw string", name, param_count + 1, cur_param.cmd));
fmt::format_to(output, ":\"{}\"", std::get<std::string>(*p)); p.Encode(output);
break; break;
} }
case StringParam::STRING: { case StringParam::STRING: {
Param *p = get_next_arg(); ParamCheck &p = *get_next_arg();
if (!std::holds_alternative<ScriptTextRef>(*p)) throw Script_FatalError(fmt::format("{}({}): {{{}}} expects a GSText", name, param_count + 1, cur_param.cmd)); if (!std::holds_alternative<ScriptTextRef>(*p.param)){
ScriptLog::Error(fmt::format("{}({}): {{{}}} expects a GSText", name, param_count + 1, cur_param.cmd));
p.Encode(output);
break;
}
int count = 0; int count = 0;
fmt::format_to(output, ":"); fmt::format_to(output, ":");
ScriptTextRef &ref = std::get<ScriptTextRef>(*p); ScriptTextRef &ref = std::get<ScriptTextRef>(*p.param);
ref->_GetEncodedText(output, count, seen_ids, args.subspan(idx)); ref->_GetEncodedText(output, count, seen_ids, args.subspan(idx));
p.used = true;
if (++count != cur_param.consumes) { if (++count != cur_param.consumes) {
ScriptLog::Error(fmt::format("{}({}): {{{}}} expects {} to be consumed, but {} consumes {}", name, param_count + 1, cur_param.cmd, cur_param.consumes - 1, GetGameStringName(ref->string), count - 1)); ScriptLog::Error(fmt::format("{}({}): {{{}}} expects {} to be consumed, but {} consumes {}", name, param_count + 1, cur_param.cmd, cur_param.consumes - 1, GetGameStringName(ref->string), count - 1));
/* Fill missing params if needed. */ /* Fill missing params if needed. */
@ -336,9 +350,9 @@ void ScriptText::_GetEncodedText(std::back_insert_iterator<std::string> &output,
default: default:
for (int i = 0; i < cur_param.consumes; i++) { for (int i = 0; i < cur_param.consumes; i++) {
Param *p = get_next_arg(); ParamCheck &p = *get_next_arg();
if (!std::holds_alternative<SQInteger>(*p)) throw Script_FatalError(fmt::format("{}({}): {{{}}} expects an integer", name, param_count + i + 1, cur_param.cmd)); if (!std::holds_alternative<SQInteger>(*p.param)) ScriptLog::Error(fmt::format("{}({}): {{{}}} expects an integer", name, param_count + i + 1, cur_param.cmd));
fmt::format_to(output, ":{:X}", std::get<SQInteger>(*p)); p.Encode(output);
} }
} }

@ -136,8 +136,11 @@ private:
StringID owner; StringID owner;
int idx; int idx;
Param *param; Param *param;
bool used;
ParamCheck(StringID owner, int idx, Param *param) : owner(owner), idx(idx), param(param) {} ParamCheck(StringID owner, int idx, Param *param) : owner(owner), idx(idx), param(param), used(false) {}
void Encode(std::back_insert_iterator<std::string> &output);
}; };
using ParamList = std::vector<ParamCheck>; using ParamList = std::vector<ParamCheck>;

@ -153,3 +153,13 @@ ScriptTileList_StationType::ScriptTileList_StationType(StationID station_id, Scr
this->AddTile(cur_tile); this->AddTile(cur_tile);
} }
} }
ScriptTileList_StationCoverage::ScriptTileList_StationCoverage(StationID station_id)
{
if (!ScriptStation::IsValidStation(station_id)) return;
BitmapTileIterator it(::Station::Get(station_id)->catchment_tiles);
for (TileIndex tile = it; tile != INVALID_TILE; tile = ++it) {
this->AddTile(tile);
}
}

@ -104,4 +104,17 @@ public:
ScriptTileList_StationType(StationID station_id, ScriptStation::StationType station_type); ScriptTileList_StationType(StationID station_id, ScriptStation::StationType station_type);
}; };
/**
* Creates a list of tiles in the catchment area of the StationID.
* @api ai game
* @ingroup ScriptList
*/
class ScriptTileList_StationCoverage : public ScriptTileList {
public:
/**
* @param station_id The station to create the ScriptTileList for.
*/
ScriptTileList_StationCoverage(StationID station_id);
};
#endif /* SCRIPT_TILELIST_HPP */ #endif /* SCRIPT_TILELIST_HPP */

@ -1211,7 +1211,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
208, 0xFFFFFFFF, 2, 0, 0, 0, 5, 0, 0, 0, 174, 208, 0xFFFFFFFF, 2, 0, 0, 0, 5, 0, 0, 0, 174,
IT_FARM, IT_STEEL_MILL, IT_INVALID, CHECK_NOTHING, IT_FARM, IT_STEEL_MILL, IT_INVALID, CHECK_NOTHING,
CT_GOODS, 0, CT_INVALID, 0, 5, CT_GOODS, 0, CT_INVALID, 0, 5,
CT_LIVESTOCK, 256, CT_GRAIN, 256, CT_STEEL, 256, MCT_LIVESTOCK_FRUIT, 256, MCT_GRAIN_WHEAT_MAIZE, 256, CT_STEEL, 256,
INDUSTRYLIFE_PROCESSING, 1 << LT_TEMPERATE, INDUSTRYLIFE_PROCESSING, 1 << LT_TEMPERATE,
INDUSTRYBEH_CHOPPER_ATTACKS, INDUSTRYBEH_CHOPPER_ATTACKS,
STR_INDUSTRY_NAME_FACTORY, STR_NEWS_INDUSTRY_CONSTRUCTION, STR_INDUSTRY_NAME_FACTORY, STR_NEWS_INDUSTRY_CONSTRUCTION,
@ -1240,7 +1240,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
MI(_tile_table_farm, 3, _farm_sounds, MI(_tile_table_farm, 3, _farm_sounds,
250, 0xD9999999, 2, 4, 0, 0, 9, 9, 0, 0, 48, 250, 0xD9999999, 2, 4, 0, 0, 9, 9, 0, 0, 48,
IT_FACTORY, IT_FOOD_PROCESS, IT_INVALID, CHECK_FARM, IT_FACTORY, IT_FOOD_PROCESS, IT_INVALID, CHECK_FARM,
CT_GRAIN, 10, CT_LIVESTOCK, 10, 5, MCT_GRAIN_WHEAT_MAIZE, 10, MCT_LIVESTOCK_FRUIT, 10, 5,
CT_INVALID, 256, CT_INVALID, 256, CT_INVALID, 256, CT_INVALID, 256, CT_INVALID, 256, CT_INVALID, 256,
INDUSTRYLIFE_ORGANIC, 1 << LT_TEMPERATE | 1 << LT_ARCTIC, INDUSTRYLIFE_ORGANIC, 1 << LT_TEMPERATE | 1 << LT_ARCTIC,
INDUSTRYBEH_PLANT_FIELDS | INDUSTRYBEH_PLANT_ON_BUILT, INDUSTRYBEH_PLANT_FIELDS | INDUSTRYBEH_PLANT_ON_BUILT,
@ -1270,8 +1270,8 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
MI(_tile_table_bank, 0, nullptr, MI(_tile_table_bank, 0, nullptr,
255, 0xA6666666, 7, 0, 0, 0, 0, 0, 0, 0, 15, 255, 0xA6666666, 7, 0, 0, 0, 0, 0, 0, 0, 15,
IT_BANK_TEMP, IT_INVALID, IT_INVALID, CHECK_NOTHING, IT_BANK_TEMP, IT_INVALID, IT_INVALID, CHECK_NOTHING,
CT_VALUABLES, 6, CT_INVALID, 0, 5, MCT_VALUABLES_GOLD_DIAMONDS, 6, CT_INVALID, 0, 5,
CT_VALUABLES, 0, CT_INVALID, 0, CT_INVALID, 0, MCT_VALUABLES_GOLD_DIAMONDS, 0, CT_INVALID, 0, CT_INVALID, 0,
INDUSTRYLIFE_BLACK_HOLE, 1 << LT_TEMPERATE, INDUSTRYLIFE_BLACK_HOLE, 1 << LT_TEMPERATE,
INDUSTRYBEH_TOWN1200_MORE, INDUSTRYBEH_TOWN1200_MORE,
STR_INDUSTRY_NAME_BANK, STR_NEWS_INDUSTRY_CONSTRUCTION, STR_INDUSTRY_NAME_BANK, STR_NEWS_INDUSTRY_CONSTRUCTION,
@ -1281,7 +1281,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
206, 0xFFFFFFFF, 0, 2, 2, 0, 0, 3, 4, 0, 55, 206, 0xFFFFFFFF, 0, 2, 2, 0, 0, 3, 4, 0, 55,
IT_FRUIT_PLANTATION, IT_FARM, IT_FARM_2, CHECK_NOTHING, IT_FRUIT_PLANTATION, IT_FARM, IT_FARM_2, CHECK_NOTHING,
CT_FOOD, 0, CT_INVALID, 0, 5, CT_FOOD, 0, CT_INVALID, 0, 5,
CT_FRUIT, 256, CT_MAIZE, 256, CT_INVALID, 256, MCT_LIVESTOCK_FRUIT, 256, MCT_GRAIN_WHEAT_MAIZE, 256, CT_INVALID, 256,
INDUSTRYLIFE_PROCESSING, 1 << LT_ARCTIC | 1 << LT_TROPIC, INDUSTRYLIFE_PROCESSING, 1 << LT_ARCTIC | 1 << LT_TROPIC,
INDUSTRYBEH_NONE, INDUSTRYBEH_NONE,
STR_INDUSTRY_NAME_FOOD_PROCESSING_PLANT, STR_NEWS_INDUSTRY_CONSTRUCTION, STR_INDUSTRY_NAME_FOOD_PROCESSING_PLANT, STR_NEWS_INDUSTRY_CONSTRUCTION,
@ -1300,7 +1300,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
MI(_tile_table_gold_mine, 0, nullptr, MI(_tile_table_gold_mine, 0, nullptr,
208, 0x99999999, 0, 3, 0, 0, 0, 4, 0, 0, 194, 208, 0x99999999, 0, 3, 0, 0, 0, 4, 0, 0, 194,
IT_BANK_TROPIC_ARCTIC, IT_INVALID, IT_INVALID, CHECK_NOTHING, IT_BANK_TROPIC_ARCTIC, IT_INVALID, IT_INVALID, CHECK_NOTHING,
CT_GOLD, 7, CT_INVALID, 0, 5, MCT_VALUABLES_GOLD_DIAMONDS, 7, CT_INVALID, 0, 5,
CT_INVALID, 256, CT_INVALID, 256, CT_INVALID, 256, CT_INVALID, 256, CT_INVALID, 256, CT_INVALID, 256,
INDUSTRYLIFE_EXTRACTIVE, 1 << LT_ARCTIC, INDUSTRYLIFE_EXTRACTIVE, 1 << LT_ARCTIC,
INDUSTRYBEH_NONE, INDUSTRYBEH_NONE,
@ -1311,7 +1311,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
151, 0xA6666666, 0, 3, 3, 0, 0, 6, 5, 0, 15, 151, 0xA6666666, 0, 3, 3, 0, 0, 6, 5, 0, 15,
IT_GOLD_MINE, IT_DIAMOND_MINE, IT_INVALID, CHECK_NOTHING, IT_GOLD_MINE, IT_DIAMOND_MINE, IT_INVALID, CHECK_NOTHING,
CT_INVALID, 0, CT_INVALID, 0, 5, CT_INVALID, 0, CT_INVALID, 0, 5,
CT_GOLD, 256, CT_INVALID, 256, CT_INVALID, 256, MCT_VALUABLES_GOLD_DIAMONDS, 256, CT_INVALID, 256, CT_INVALID, 256,
INDUSTRYLIFE_BLACK_HOLE, 1 << LT_ARCTIC | 1 << LT_TROPIC, INDUSTRYLIFE_BLACK_HOLE, 1 << LT_ARCTIC | 1 << LT_TROPIC,
INDUSTRYBEH_ONLY_INTOWN, INDUSTRYBEH_ONLY_INTOWN,
STR_INDUSTRY_NAME_BANK_TROPIC_ARCTIC, STR_NEWS_INDUSTRY_CONSTRUCTION, STR_INDUSTRY_NAME_BANK_TROPIC_ARCTIC, STR_NEWS_INDUSTRY_CONSTRUCTION,
@ -1320,7 +1320,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
MI(_tile_table_diamond_mine, 0, nullptr, MI(_tile_table_diamond_mine, 0, nullptr,
213, 0x99999999, 0, 0, 3, 0, 0, 0, 4, 0, 184, 213, 0x99999999, 0, 0, 3, 0, 0, 0, 4, 0, 184,
IT_BANK_TROPIC_ARCTIC, IT_INVALID, IT_INVALID, CHECK_NOTHING, IT_BANK_TROPIC_ARCTIC, IT_INVALID, IT_INVALID, CHECK_NOTHING,
CT_DIAMONDS, 7, CT_INVALID, 0, 5, MCT_VALUABLES_GOLD_DIAMONDS, 7, CT_INVALID, 0, 5,
CT_INVALID, 256, CT_INVALID, 256, CT_INVALID, 256, CT_INVALID, 256, CT_INVALID, 256, CT_INVALID, 256,
INDUSTRYLIFE_EXTRACTIVE, 1 << LT_TROPIC, INDUSTRYLIFE_EXTRACTIVE, 1 << LT_TROPIC,
INDUSTRYBEH_NONE, INDUSTRYBEH_NONE,
@ -1340,7 +1340,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
MI(_tile_table_fruit_plantation, 0, nullptr, MI(_tile_table_fruit_plantation, 0, nullptr,
225, 0xBFFFFFFF, 0, 0, 2, 0, 0, 0, 4, 0, 86, 225, 0xBFFFFFFF, 0, 0, 2, 0, 0, 0, 4, 0, 86,
IT_FOOD_PROCESS, IT_INVALID, IT_INVALID, CHECK_PLANTATION, IT_FOOD_PROCESS, IT_INVALID, IT_INVALID, CHECK_PLANTATION,
CT_FRUIT, 10, CT_INVALID, 0, 15, MCT_LIVESTOCK_FRUIT, 10, CT_INVALID, 0, 15,
CT_INVALID, 256, CT_INVALID, 256, CT_INVALID, 256, CT_INVALID, 256, CT_INVALID, 256, CT_INVALID, 256,
INDUSTRYLIFE_ORGANIC, 1 << LT_TROPIC, INDUSTRYLIFE_ORGANIC, 1 << LT_TROPIC,
INDUSTRYBEH_NONE, INDUSTRYBEH_NONE,
@ -1390,7 +1390,7 @@ static const IndustrySpec _origin_industry_specs[NEW_INDUSTRYOFFSET] = {
MI(_tile_table_farm2, 0, nullptr, MI(_tile_table_farm2, 0, nullptr,
250, 0xD9999999, 0, 0, 1, 0, 0, 0, 2, 0, 48, 250, 0xD9999999, 0, 0, 1, 0, 0, 0, 2, 0, 48,
IT_FOOD_PROCESS, IT_INVALID, IT_INVALID, CHECK_PLANTATION, IT_FOOD_PROCESS, IT_INVALID, IT_INVALID, CHECK_PLANTATION,
CT_MAIZE, 11, CT_INVALID, 0, 5, MCT_GRAIN_WHEAT_MAIZE, 11, CT_INVALID, 0, 5,
CT_INVALID, 256, CT_INVALID, 256, CT_INVALID, 256, CT_INVALID, 256, CT_INVALID, 256, CT_INVALID, 256,
INDUSTRYLIFE_ORGANIC, 1 << LT_TROPIC, INDUSTRYLIFE_ORGANIC, 1 << LT_TROPIC,
INDUSTRYBEH_PLANT_FIELDS | INDUSTRYBEH_PLANT_ON_BUILT, INDUSTRYBEH_PLANT_FIELDS | INDUSTRYBEH_PLANT_ON_BUILT,
@ -1594,10 +1594,10 @@ static const IndustryTileSpec _origin_industry_tile_specs[NEW_INDUSTRYTILEOFFSET
MT(0, CT_INVALID, 0, CT_INVALID, 0, CT_INVALID, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false), MT(0, CT_INVALID, 0, CT_INVALID, 0, CT_INVALID, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false),
/* Factory temperate */ /* Factory temperate */
MT(8, CT_GRAIN, 8, CT_LIVESTOCK, 8, CT_STEEL, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false), MT(8, MCT_GRAIN_WHEAT_MAIZE, 8, MCT_LIVESTOCK_FRUIT, 8, CT_STEEL, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false),
MT(8, CT_GRAIN, 8, CT_LIVESTOCK, 8, CT_STEEL, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false), MT(8, MCT_GRAIN_WHEAT_MAIZE, 8, MCT_LIVESTOCK_FRUIT, 8, CT_STEEL, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false),
MT(8, CT_GRAIN, 8, CT_LIVESTOCK, 8, CT_STEEL, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false), MT(8, MCT_GRAIN_WHEAT_MAIZE, 8, MCT_LIVESTOCK_FRUIT, 8, CT_STEEL, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false),
MT(8, CT_GRAIN, 8, CT_LIVESTOCK, 8, CT_STEEL, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false), MT(8, MCT_GRAIN_WHEAT_MAIZE, 8, MCT_LIVESTOCK_FRUIT, 8, CT_STEEL, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false),
/* Printing works */ /* Printing works */
MT(0, CT_INVALID, 8, CT_PAPER, 0, CT_INVALID, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false), MT(0, CT_INVALID, 8, CT_PAPER, 0, CT_INVALID, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false),
@ -1621,14 +1621,14 @@ static const IndustryTileSpec _origin_industry_tile_specs[NEW_INDUSTRYTILEOFFSET
MT(1, CT_PASSENGERS, 8, CT_IRON_ORE, 0, CT_INVALID, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false), MT(1, CT_PASSENGERS, 8, CT_IRON_ORE, 0, CT_INVALID, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false),
/* Bank temperate*/ /* Bank temperate*/
MT(1, CT_PASSENGERS, 8, CT_VALUABLES, 0, CT_INVALID, SLOPE_E, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false), MT(1, CT_PASSENGERS, 8, MCT_VALUABLES_GOLD_DIAMONDS, 0, CT_INVALID, SLOPE_E, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false),
MT(1, CT_PASSENGERS, 8, CT_VALUABLES, 0, CT_INVALID, SLOPE_S, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false), MT(1, CT_PASSENGERS, 8, MCT_VALUABLES_GOLD_DIAMONDS, 0, CT_INVALID, SLOPE_S, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false),
/* Food processing plant, tropic and arctic. CT_MAIZE or CT_WHEAT, CT_LIVESTOCK or CT_FRUIT*/ /* Food processing plant, tropic and arctic. CT_MAIZE or CT_WHEAT, CT_LIVESTOCK or CT_FRUIT*/
MT(8, CT_MAIZE, 8, CT_LIVESTOCK, 0, CT_INVALID, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false), MT(8, MCT_GRAIN_WHEAT_MAIZE, 8, MCT_LIVESTOCK_FRUIT, 0, CT_INVALID, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false),
MT(8, CT_MAIZE, 8, CT_LIVESTOCK, 0, CT_INVALID, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false), MT(8, MCT_GRAIN_WHEAT_MAIZE, 8, MCT_LIVESTOCK_FRUIT, 0, CT_INVALID, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false),
MT(8, CT_MAIZE, 8, CT_LIVESTOCK, 0, CT_INVALID, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false), MT(8, MCT_GRAIN_WHEAT_MAIZE, 8, MCT_LIVESTOCK_FRUIT, 0, CT_INVALID, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false),
MT(8, CT_MAIZE, 8, CT_LIVESTOCK, 0, CT_INVALID, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false), MT(8, MCT_GRAIN_WHEAT_MAIZE, 8, MCT_LIVESTOCK_FRUIT, 0, CT_INVALID, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false),
/* Paper mill */ /* Paper mill */
MT(0, CT_INVALID, 8, CT_WOOD, 0, CT_INVALID, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false), MT(0, CT_INVALID, 8, CT_WOOD, 0, CT_INVALID, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false),
@ -1660,8 +1660,8 @@ static const IndustryTileSpec _origin_industry_tile_specs[NEW_INDUSTRYTILEOFFSET
MT(0, CT_INVALID, 0, CT_INVALID, 0, CT_INVALID, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, true), MT(0, CT_INVALID, 0, CT_INVALID, 0, CT_INVALID, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, true),
/* Bank Sub Arctic */ /* Bank Sub Arctic */
MT(0, CT_INVALID, 8, CT_GOLD, 0, CT_INVALID, SLOPE_E, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false), MT(0, CT_INVALID, 8, MCT_VALUABLES_GOLD_DIAMONDS, 0, CT_INVALID, SLOPE_E, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false),
MT(0, CT_INVALID, 8, CT_GOLD, 0, CT_INVALID, SLOPE_S, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false), MT(0, CT_INVALID, 8, MCT_VALUABLES_GOLD_DIAMONDS, 0, CT_INVALID, SLOPE_S, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false),
/* Diamond mine */ /* Diamond mine */
MT(0, CT_INVALID, 0, CT_INVALID, 0, CT_INVALID, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false), MT(0, CT_INVALID, 0, CT_INVALID, 0, CT_INVALID, SLOPE_STEEP, INDUSTRYTILE_NOANIM, INDUSTRYTILE_NOANIM, false),

@ -135,11 +135,11 @@ static const EngineInfo _orig_engine_info[] = {
MW( 1827, 20, 20, 50, CT_OIL , T|A|S ), // 30 Oil Tanker MW( 1827, 20, 20, 50, CT_OIL , T|A|S ), // 30 Oil Tanker
MW( 1827, 20, 20, 50, CT_LIVESTOCK , T|A ), // 31 Livestock Van MW( 1827, 20, 20, 50, CT_LIVESTOCK , T|A ), // 31 Livestock Van
MW( 1827, 20, 20, 50, CT_GOODS , T|A|S ), // 32 Goods Van MW( 1827, 20, 20, 50, CT_GOODS , T|A|S ), // 32 Goods Van
MW( 1827, 20, 20, 50, CT_GRAIN , T|A|S ), // 33 Grain Hopper MW( 1827, 20, 20, 50, MCT_GRAIN_WHEAT_MAIZE, T|A|S ), // 33 Grain Hopper
MW( 1827, 20, 20, 50, CT_WOOD , T|A|S ), // 34 Wood Truck MW( 1827, 20, 20, 50, CT_WOOD , T|A|S ), // 34 Wood Truck
MW( 1827, 20, 20, 50, CT_IRON_ORE , T ), // 35 Iron Ore Hopper MW( 1827, 20, 20, 50, CT_IRON_ORE , T ), // 35 Iron Ore Hopper
MW( 1827, 20, 20, 50, CT_STEEL , T ), // 36 Steel Truck MW( 1827, 20, 20, 50, CT_STEEL , T ), // 36 Steel Truck
MW( 1827, 20, 20, 50, CT_VALUABLES , T|A|S ), // 37 Armoured Van MW( 1827, 20, 20, 50, MCT_VALUABLES_GOLD_DIAMONDS, T|A|S ), // 37 Armoured Van
MW( 1827, 20, 20, 50, CT_FOOD , A|S ), // 38 Food Van MW( 1827, 20, 20, 50, CT_FOOD , A|S ), // 38 Food Van
MW( 1827, 20, 20, 50, CT_PAPER , A ), // 39 Paper Truck MW( 1827, 20, 20, 50, CT_PAPER , A ), // 39 Paper Truck
MW( 1827, 20, 20, 50, CT_COPPER_ORE , S ), // 40 Copper Ore Hopper MW( 1827, 20, 20, 50, CT_COPPER_ORE , S ), // 40 Copper Ore Hopper
@ -165,11 +165,11 @@ static const EngineInfo _orig_engine_info[] = {
MW( 1827, 20, 20, 50, CT_OIL , T|A|S ), // 60 Oil Tanker MW( 1827, 20, 20, 50, CT_OIL , T|A|S ), // 60 Oil Tanker
MW( 1827, 20, 20, 50, CT_LIVESTOCK , T|A ), // 61 Livestock Van MW( 1827, 20, 20, 50, CT_LIVESTOCK , T|A ), // 61 Livestock Van
MW( 1827, 20, 20, 50, CT_GOODS , T|A|S ), // 62 Goods Van MW( 1827, 20, 20, 50, CT_GOODS , T|A|S ), // 62 Goods Van
MW( 1827, 20, 20, 50, CT_GRAIN , T|A|S ), // 63 Grain Hopper MW( 1827, 20, 20, 50, MCT_GRAIN_WHEAT_MAIZE, T|A|S ), // 63 Grain Hopper
MW( 1827, 20, 20, 50, CT_WOOD , T|A|S ), // 64 Wood Truck MW( 1827, 20, 20, 50, CT_WOOD , T|A|S ), // 64 Wood Truck
MW( 1827, 20, 20, 50, CT_IRON_ORE , T ), // 65 Iron Ore Hopper MW( 1827, 20, 20, 50, CT_IRON_ORE , T ), // 65 Iron Ore Hopper
MW( 1827, 20, 20, 50, CT_STEEL , T ), // 66 Steel Truck MW( 1827, 20, 20, 50, CT_STEEL , T ), // 66 Steel Truck
MW( 1827, 20, 20, 50, CT_VALUABLES , T|A|S ), // 67 Armoured Van MW( 1827, 20, 20, 50, MCT_VALUABLES_GOLD_DIAMONDS, T|A|S ), // 67 Armoured Van
MW( 1827, 20, 20, 50, CT_FOOD , A|S ), // 68 Food Van MW( 1827, 20, 20, 50, CT_FOOD , A|S ), // 68 Food Van
MW( 1827, 20, 20, 50, CT_PAPER , A ), // 69 Paper Truck MW( 1827, 20, 20, 50, CT_PAPER , A ), // 69 Paper Truck
MW( 1827, 20, 20, 50, CT_COPPER_ORE , S ), // 70 Copper Ore Hopper MW( 1827, 20, 20, 50, CT_COPPER_ORE , S ), // 70 Copper Ore Hopper
@ -197,11 +197,11 @@ static const EngineInfo _orig_engine_info[] = {
MW( 1827, 20, 20, 50, CT_OIL , T|A|S ), // 92 Oil Tanker MW( 1827, 20, 20, 50, CT_OIL , T|A|S ), // 92 Oil Tanker
MW( 1827, 20, 20, 50, CT_LIVESTOCK , T|A ), // 93 Livestock Van MW( 1827, 20, 20, 50, CT_LIVESTOCK , T|A ), // 93 Livestock Van
MW( 1827, 20, 20, 50, CT_GOODS , T|A|S ), // 94 Goods Van MW( 1827, 20, 20, 50, CT_GOODS , T|A|S ), // 94 Goods Van
MW( 1827, 20, 20, 50, CT_GRAIN , T|A|S ), // 95 Grain Hopper MW( 1827, 20, 20, 50, MCT_GRAIN_WHEAT_MAIZE, T|A|S ), // 95 Grain Hopper
MW( 1827, 20, 20, 50, CT_WOOD , T|A|S ), // 96 Wood Truck MW( 1827, 20, 20, 50, CT_WOOD , T|A|S ), // 96 Wood Truck
MW( 1827, 20, 20, 50, CT_IRON_ORE , T ), // 97 Iron Ore Hopper MW( 1827, 20, 20, 50, CT_IRON_ORE , T ), // 97 Iron Ore Hopper
MW( 1827, 20, 20, 50, CT_STEEL , T ), // 98 Steel Truck MW( 1827, 20, 20, 50, CT_STEEL , T ), // 98 Steel Truck
MW( 1827, 20, 20, 50, CT_VALUABLES , T|A|S ), // 99 Armoured Van MW( 1827, 20, 20, 50, MCT_VALUABLES_GOLD_DIAMONDS, T|A|S ), // 99 Armoured Van
MW( 1827, 20, 20, 50, CT_FOOD , A|S ), // 100 Food Van MW( 1827, 20, 20, 50, CT_FOOD , A|S ), // 100 Food Van
MW( 1827, 20, 20, 50, CT_PAPER , A ), // 101 Paper Truck MW( 1827, 20, 20, 50, CT_PAPER , A ), // 101 Paper Truck
MW( 1827, 20, 20, 50, CT_COPPER_ORE , S ), // 102 Copper Ore Hopper MW( 1827, 20, 20, 50, CT_COPPER_ORE , S ), // 102 Copper Ore Hopper
@ -243,9 +243,9 @@ static const EngineInfo _orig_engine_info[] = {
MR( 5479, 20, 15, 55, CT_GOODS , T|A|S ), // 138 Balogh Goods Truck MR( 5479, 20, 15, 55, CT_GOODS , T|A|S ), // 138 Balogh Goods Truck
MR( 19724, 20, 15, 55, CT_GOODS , T|A|S ), // 139 Craighead Goods Truck MR( 19724, 20, 15, 55, CT_GOODS , T|A|S ), // 139 Craighead Goods Truck
MR( 31047, 20, 15, 85, CT_GOODS , T|A|S ), // 140 Goss Goods Truck MR( 31047, 20, 15, 85, CT_GOODS , T|A|S ), // 140 Goss Goods Truck
MR( 5479, 20, 15, 55, CT_GRAIN , T|A|S ), // 141 Hereford Grain Truck MR( 5479, 20, 15, 55, MCT_GRAIN_WHEAT_MAIZE, T|A|S ), // 141 Hereford Grain Truck
MR( 21185, 20, 15, 55, CT_GRAIN , T|A|S ), // 142 Thomas Grain Truck MR( 21185, 20, 15, 55, MCT_GRAIN_WHEAT_MAIZE, T|A|S ), // 142 Thomas Grain Truck
MR( 32873, 20, 15, 85, CT_GRAIN , T|A|S ), // 143 Goss Grain Truck MR( 32873, 20, 15, 85, MCT_GRAIN_WHEAT_MAIZE, T|A|S ), // 143 Goss Grain Truck
MR( 5479, 20, 15, 55, CT_WOOD , T|A|S ), // 144 Witcombe Wood Truck MR( 5479, 20, 15, 55, CT_WOOD , T|A|S ), // 144 Witcombe Wood Truck
MR( 19724, 20, 15, 55, CT_WOOD , T|A|S ), // 145 Foster Wood Truck MR( 19724, 20, 15, 55, CT_WOOD , T|A|S ), // 145 Foster Wood Truck
MR( 35430, 20, 15, 85, CT_WOOD , T|A|S ), // 146 Moreland Wood Truck MR( 35430, 20, 15, 85, CT_WOOD , T|A|S ), // 146 Moreland Wood Truck
@ -255,9 +255,9 @@ static const EngineInfo _orig_engine_info[] = {
MR( 5479, 20, 15, 55, CT_STEEL , T ), // 150 Balogh Steel Truck MR( 5479, 20, 15, 55, CT_STEEL , T ), // 150 Balogh Steel Truck
MR( 21185, 20, 15, 55, CT_STEEL , T ), // 151 Uhl Steel Truck MR( 21185, 20, 15, 55, CT_STEEL , T ), // 151 Uhl Steel Truck
MR( 31777, 20, 15, 85, CT_STEEL , T ), // 152 Kelling Steel Truck MR( 31777, 20, 15, 85, CT_STEEL , T ), // 152 Kelling Steel Truck
MR( 5479, 20, 15, 55, CT_VALUABLES , T|A|S ), // 153 Balogh Armoured Truck MR( 5479, 20, 15, 55, MCT_VALUABLES_GOLD_DIAMONDS, T|A|S ), // 153 Balogh Armoured Truck
MR( 22281, 20, 15, 55, CT_VALUABLES , T|A|S ), // 154 Uhl Armoured Truck MR( 22281, 20, 15, 55, MCT_VALUABLES_GOLD_DIAMONDS, T|A|S ), // 154 Uhl Armoured Truck
MR( 33603, 20, 15, 85, CT_VALUABLES , T|A|S ), // 155 Foster Armoured Truck MR( 33603, 20, 15, 85, MCT_VALUABLES_GOLD_DIAMONDS, T|A|S ), // 155 Foster Armoured Truck
MR( 5479, 20, 15, 55, CT_FOOD , A|S ), // 156 Foster Food Van MR( 5479, 20, 15, 55, CT_FOOD , A|S ), // 156 Foster Food Van
MR( 18628, 20, 15, 55, CT_FOOD , A|S ), // 157 Perry Food Van MR( 18628, 20, 15, 55, CT_FOOD , A|S ), // 157 Perry Food Van
MR( 30681, 20, 15, 85, CT_FOOD , A|S ), // 158 Chippy Food Van MR( 30681, 20, 15, 85, CT_FOOD , A|S ), // 158 Chippy Food Van

Loading…
Cancel
Save