From 674bacf4593632cdbd00c4862c5a30708c5a9704 Mon Sep 17 00:00:00 2001 From: Xottab-DUTY Date: Sat, 19 Aug 2017 02:07:13 +0500 Subject: [PATCH] Refactor xrNetServer --- src/xrGame/Level.cpp | 2 +- src/xrGame/Level.h | 2 +- src/xrGame/xrServer.cpp | 2 +- src/xrGame/xrServer.h | 6 +- src/xrGame/xrServer_process_spawn.cpp | 2 +- src/xrNetServer/NET_AuthCheck.cpp | 23 +- src/xrNetServer/NET_AuthCheck.h | 5 +- src/xrNetServer/NET_Client.cpp | 1518 +++++++++++++------------ src/xrNetServer/NET_Client.h | 75 +- src/xrNetServer/NET_Common.cpp | 73 +- src/xrNetServer/NET_Common.h | 1 + src/xrNetServer/NET_Compressor.cpp | 260 +++-- src/xrNetServer/NET_Compressor.h | 7 +- src/xrNetServer/NET_Log.cpp | 27 +- src/xrNetServer/NET_Log.h | 62 +- src/xrNetServer/NET_Messages.h | 3 +- src/xrNetServer/NET_PlayersMonitor.h | 78 +- src/xrNetServer/NET_Server.cpp | 279 ++--- src/xrNetServer/NET_Server.h | 116 +- src/xrNetServer/NET_Shared.h | 21 +- src/xrNetServer/ip_filter.cpp | 14 +- src/xrNetServer/ip_filter.h | 3 + src/xrNetServer/stdafx.cpp | 3 - src/xrNetServer/stdafx.h | 6 - 24 files changed, 1330 insertions(+), 1258 deletions(-) diff --git a/src/xrGame/Level.cpp b/src/xrGame/Level.cpp index 5e01917cd76..6d8239b5cf0 100644 --- a/src/xrGame/Level.cpp +++ b/src/xrGame/Level.cpp @@ -1001,7 +1001,7 @@ void CLevel::OnAlifeSimulatorLoaded() GameTaskManager().ResetStorage(); } -void CLevel::OnSessionTerminate(LPCSTR reason) { MainMenu()->OnSessionTerminate(reason); } +void CLevel::OnSessionTerminate(pcstr reason) { MainMenu()->OnSessionTerminate(reason); } u32 GameID() { return Game().Type(); } CZoneList* CLevel::create_hud_zones_list() { diff --git a/src/xrGame/Level.h b/src/xrGame/Level.h index 02d54a1a278..c39b890c0a9 100644 --- a/src/xrGame/Level.h +++ b/src/xrGame/Level.h @@ -380,7 +380,7 @@ class CLevel : public IGame_Level, public IPureClient virtual u32 GetRealPing() { return m_dwRealPing; } public: void remove_objects(); - virtual void OnSessionTerminate(LPCSTR reason); + virtual void OnSessionTerminate(pcstr reason); file_transfer::client_site* m_file_transfer = nullptr; compression::ppmd_trained_stream* m_trained_stream = nullptr; compression::lzo_dictionary_buffer m_lzo_dictionary; diff --git a/src/xrGame/xrServer.cpp b/src/xrGame/xrServer.cpp index c86b35d421a..032bf48385e 100644 --- a/src/xrGame/xrServer.cpp +++ b/src/xrGame/xrServer.cpp @@ -782,7 +782,7 @@ void xrServer::SendBroadcast(ClientID exclude, NET_Packet& P, u32 dwFlags) net_players.ForFoundClientsDo(ClientExcluderPredicate(exclude), temp_functor); } //-------------------------------------------------------------------- -CSE_Abstract* xrServer::entity_Create(LPCSTR name) { return F_entity_Create(name); } +CSE_Abstract* xrServer::entity_Create(pcstr name) { return F_entity_Create(name); } void xrServer::entity_Destroy(CSE_Abstract*& P) { #ifdef DEBUG diff --git a/src/xrGame/xrServer.h b/src/xrGame/xrServer.h index 8025a061458..89185a64970 100644 --- a/src/xrGame/xrServer.h +++ b/src/xrGame/xrServer.h @@ -177,8 +177,8 @@ class xrServer : public IPureServer void Perform_reject(CSE_Abstract* what, CSE_Abstract* from, int delta); virtual void Perform_destroy(CSE_Abstract* tpSE_Abstract, u32 mode) override; - virtual CSE_Abstract* Process_spawn(NET_Packet& P, ClientID sender, - BOOL bSpawnWithClientsMainEntityAsParent = FALSE, CSE_Abstract* tpExistedEntity = 0) override; + CSE_Abstract* Process_spawn(NET_Packet& P, ClientID sender, + bool bSpawnWithClientsMainEntityAsParent = false, CSE_Abstract* tpExistedEntity = nullptr) override; void Process_update(NET_Packet& P, ClientID sender); void Process_save(NET_Packet& P, ClientID sender); void Process_event(NET_Packet& P, ClientID sender); @@ -244,7 +244,7 @@ class xrServer : public IPureServer virtual void client_Destroy(IClient* C); // destroy client info // utilities - virtual CSE_Abstract* entity_Create(LPCSTR name) override; + virtual CSE_Abstract* entity_Create(pcstr name) override; virtual void entity_Destroy(CSE_Abstract*& P) override; u32 GetEntitiesNum() { return entities.size(); }; CSE_Abstract* GetEntity(u32 Num); diff --git a/src/xrGame/xrServer_process_spawn.cpp b/src/xrGame/xrServer_process_spawn.cpp index 0f860a6429b..5e046fe8249 100644 --- a/src/xrGame/xrServer_process_spawn.cpp +++ b/src/xrGame/xrServer_process_spawn.cpp @@ -7,7 +7,7 @@ #endif CSE_Abstract* xrServer::Process_spawn( - NET_Packet& P, ClientID sender, BOOL bSpawnWithClientsMainEntityAsParent, CSE_Abstract* tpExistedEntity) + NET_Packet& P, ClientID sender, bool bSpawnWithClientsMainEntityAsParent, CSE_Abstract* tpExistedEntity) { // create server entity xrClientData* CL = ID_to_client(sender); diff --git a/src/xrNetServer/NET_AuthCheck.cpp b/src/xrNetServer/NET_AuthCheck.cpp index b1fb601ab71..361a2587f6c 100644 --- a/src/xrNetServer/NET_AuthCheck.cpp +++ b/src/xrNetServer/NET_AuthCheck.cpp @@ -4,7 +4,7 @@ void XRNETSERVER_API fill_auth_check_params(xr_auth_strings_t& ignore, xr_auth_strings_t& check) { string_path config; - LPCSTR pth = FS.get_path("$app_data_root$")->m_Path; + pcstr pth = FS.get_path("$app_data_root$")->m_Path; ignore.push_back(shared_str(pth)); ignore.push_back(shared_str(FS.update_path(config, "$game_config$", "localization.ltx"))); ignore.push_back(shared_str(FS.update_path(config, "$game_config$", "fonts.ltx"))); @@ -13,7 +13,7 @@ void XRNETSERVER_API fill_auth_check_params(xr_auth_strings_t& ignore, xr_auth_s ignore.push_back(shared_str(FS.update_path(config, "$game_config$", "gameplay"))); ignore.push_back(shared_str(FS.update_path(config, "$game_config$", "ui"))); ignore.push_back(shared_str(FS.update_path(config, "$game_config$", "scripts"))); - ignore.push_back(shared_str(FS.update_path(config, "$game_config$", "misc\\script_sound_pripyat.ltx"))); + ignore.push_back(shared_str(FS.update_path(config, "$game_config$", "misc//script_sound_pripyat.ltx"))); ignore.push_back(shared_str(FS.update_path(config, "$game_scripts$", "state_mgr_pri_a15.script"))); check.push_back(shared_str(FS.update_path(config, "$game_config$", ""))); @@ -24,17 +24,17 @@ void XRNETSERVER_API fill_auth_check_params(xr_auth_strings_t& ignore, xr_auth_s check.push_back(shared_str(FS.update_path(config, "$game_sounds$", "weapons"))); // check scopes - check.push_back(shared_str(FS.update_path(config, "$game_textures$", "wpn\\wpn_crosshair.dds"))); - check.push_back(shared_str(FS.update_path(config, "$game_textures$", "wpn\\wpn_crosshair_bino.dds"))); - check.push_back(shared_str(FS.update_path(config, "$game_textures$", "wpn\\wpn_crosshair_g36.dds"))); - check.push_back(shared_str(FS.update_path(config, "$game_textures$", "wpn\\wpn_crosshair_l85.dds"))); - check.push_back(shared_str(FS.update_path(config, "$game_textures$", "wpn\\wpn_crosshair_rpg.dds"))); + check.push_back(shared_str(FS.update_path(config, "$game_textures$", "wpn//wpn_crosshair.dds"))); + check.push_back(shared_str(FS.update_path(config, "$game_textures$", "wpn//wpn_crosshair_bino.dds"))); + check.push_back(shared_str(FS.update_path(config, "$game_textures$", "wpn//wpn_crosshair_g36.dds"))); + check.push_back(shared_str(FS.update_path(config, "$game_textures$", "wpn//wpn_crosshair_l85.dds"))); + check.push_back(shared_str(FS.update_path(config, "$game_textures$", "wpn//wpn_crosshair_rpg.dds"))); check.push_back(shared_str("xrD3D9-Null")); check.push_back(shared_str("ODE")); check.push_back(shared_str("xrCDB")); check.push_back(shared_str("xrCore")); - // check.push_back (shared_str("xrGame")); + //check.push_back(shared_str("xrGame")); check.push_back(shared_str("xrGamespy")); check.push_back(shared_str("xrNetserver")); check.push_back(shared_str("xrParticles")); @@ -42,15 +42,14 @@ void XRNETSERVER_API fill_auth_check_params(xr_auth_strings_t& ignore, xr_auth_s check.push_back(shared_str("xrRender_R2")); check.push_back(shared_str("xrSound")); check.push_back(shared_str("xrXMLParser")); - // check.push_back (shared_str("xrEngine.exe")); + //check.push_back(shared_str("xrEngine.exe")); } -bool XRNETSERVER_API allow_to_include_path(xr_auth_strings_t const& ignore, LPCSTR path) +bool XRNETSERVER_API allow_to_include_path(xr_auth_strings_t const& ignore, pcstr path) { for (xr_auth_strings_t::const_iterator i = ignore.begin(), ie = ignore.end(); i != ie; ++i) - { if (!strncmp(i->c_str(), path, i->size())) return false; - } + return true; } diff --git a/src/xrNetServer/NET_AuthCheck.h b/src/xrNetServer/NET_AuthCheck.h index a39519d650d..4e3ed42a673 100644 --- a/src/xrNetServer/NET_AuthCheck.h +++ b/src/xrNetServer/NET_AuthCheck.h @@ -1,10 +1,11 @@ +#pragma once #ifndef NET_AUTH_CHECK_INCLUDED #define NET_AUTH_CHECK_INCLUDED #include "net_shared.h" -typedef xr_vector xr_auth_strings_t; +using xr_auth_strings_t = xr_vector; void XRNETSERVER_API fill_auth_check_params(xr_auth_strings_t& ignore, xr_auth_strings_t& check); -bool XRNETSERVER_API allow_to_include_path(xr_auth_strings_t const& ignore, LPCSTR path); +bool XRNETSERVER_API allow_to_include_path(xr_auth_strings_t const& ignore, pcstr path); #endif //#ifndef NET_AUTH_CHECK_INCLUDED diff --git a/src/xrNetServer/NET_Client.cpp b/src/xrNetServer/NET_Client.cpp index 70bcaa3cbf1..7917c4d3cab 100644 --- a/src/xrNetServer/NET_Client.cpp +++ b/src/xrNetServer/NET_Client.cpp @@ -1,8 +1,8 @@ #include "stdafx.h" #include "NET_Common.h" -#include "net_client.h" -#include "net_server.h" -#include "net_messages.h" +#include "net_Client.h" +#include "net_Server.h" +#include "net_Messages.h" #include "NET_Log.h" #include "xrGameSpy/xrGameSpy_MainDefs.h" @@ -84,9 +84,9 @@ const GUID CLSID_DirectPlay8Address = {0x934a9523, 0xa3ca, 0x4bc5, {0xad, 0xa0, const GUID IID_IDirectPlay8Address = {0x83783300, 0x4063, 0x4c8a, {0x9d, 0xb3, 0x82, 0x83, 0x0a, 0x7f, 0xeb, 0x31}}; -static INetLog* pClNetLog = NULL; +static INetLog* pClNetLog = nullptr; -void dump_URL(LPCSTR p, IDirectPlay8Address* A) +void dump_URL(pcstr p, IDirectPlay8Address* A) { string256 aaaa; DWORD aaaa_s = sizeof(aaaa); @@ -94,11 +94,11 @@ void dump_URL(LPCSTR p, IDirectPlay8Address* A) Log(p, aaaa); } -// -INetQueue::INetQueue() #ifdef CONFIG_PROFILE_LOCKS - : cs(MUTEX_PROFILE_ID(INetQueue)) -#endif // CONFIG_PROFILE_LOCKS +INetQueue::INetQueue() : cs(MUTEX_PROFILE_ID(INetQueue)) +#else +INetQueue::INetQueue() +#endif { unused.reserve(128); for (int i = 0; i < 16; i++) @@ -117,13 +117,14 @@ INetQueue::~INetQueue() } static u32 LastTimeCreate = 0; + NET_Packet* INetQueue::Create() { - NET_Packet* P = 0; - // cs.Enter (); - //#ifdef _DEBUG - // Msg ("- INetQueue::Create - ready %d, unused %d", ready.size(), unused.size()); - //#endif + NET_Packet* P = nullptr; + //cs.Enter(); +//#ifdef _DEBUG + //Msg("- INetQueue::Create - ready %d, unused %d", ready.size(), unused.size()); +//#endif if (unused.empty()) { ready.push_back(new NET_Packet()); @@ -138,16 +139,17 @@ NET_Packet* INetQueue::Create() unused.pop_back(); P = ready.back(); } - // cs.Leave (); + //cs.Leave(); return P; } + NET_Packet* INetQueue::Create(const NET_Packet& _other) { - NET_Packet* P = 0; + NET_Packet* P = nullptr; cs.Enter(); - //#ifdef _DEBUG - // Msg ("- INetQueue::Create - ready %d, unused %d", ready.size(), unused.size()); - //#endif +//#ifdef _DEBUG + //Msg("- INetQueue::Create - ready %d, unused %d", ready.size(), unused.size()); +//#endif if (unused.empty()) { ready.push_back(new NET_Packet()); @@ -166,13 +168,14 @@ NET_Packet* INetQueue::Create(const NET_Packet& _other) cs.Leave(); return P; } + NET_Packet* INetQueue::Retreive() { - NET_Packet* P = 0; - // cs.Enter (); - //#ifdef _DEBUG - // Msg ("INetQueue::Retreive - ready %d, unused %d", ready.size(), unused.size()); - //#endif + NET_Packet* P = nullptr; + //cs.Enter(); +//#ifdef _DEBUG + //Msg("INetQueue::Retreive - ready %d, unused %d", ready.size(), unused.size()); +//#endif if (!ready.empty()) P = ready.front(); //--------------------------------------------- @@ -187,15 +190,16 @@ NET_Packet* INetQueue::Retreive() } } //--------------------------------------------- - // cs.Leave (); + //cs.Leave(); return P; } + void INetQueue::Release() { - // cs.Enter (); - //#ifdef _DEBUG - // Msg ("INetQueue::Release - ready %d, unused %d", ready.size(), unused.size()); - //#endif + //cs.Enter(); +//#ifdef _DEBUG + //Msg("INetQueue::Release - ready %d, unused %d", ready.size(), unused.size()); +//#endif VERIFY(!ready.empty()); //--------------------------------------------- u32 tmp_time = GetTickCount() - 60000; @@ -209,12 +213,13 @@ void INetQueue::Release() unused.push_back(ready.front()); //--------------------------------------------- ready.pop_front(); - // cs.Leave (); + //cs.Leave(); } // const u32 syncQueueSize = 512; const int syncSamples = 256; + class XRNETSERVER_API syncQueue { u32 table[syncQueueSize]; @@ -223,7 +228,8 @@ class XRNETSERVER_API syncQueue public: syncQueue() { clear(); } - IC void push(u32 value) + + void push(u32 value) { table[write++] = value; if (write == syncQueueSize) @@ -232,10 +238,12 @@ class XRNETSERVER_API syncQueue if (count <= syncQueueSize) count++; } - IC u32* begin() { return table; } - IC u32* end() { return table + count; } - IC u32 size() { return count; } - IC void clear() + + u32* begin() { return table; } + u32* end() { return table + count; } + u32 size() const { return count; } + + void clear() { write = 0; count = 0; @@ -247,7 +255,7 @@ XRNETSERVER_API Flags32 psNET_Flags = {0}; XRNETSERVER_API int psNET_ClientUpdate = 30; // FPS XRNETSERVER_API int psNET_ClientPending = 2; XRNETSERVER_API char psNET_Name[32] = "Player"; -XRNETSERVER_API BOOL psNET_direct_connect = FALSE; +XRNETSERVER_API bool psNET_direct_connect = false; /**************************************************************************** * @@ -278,7 +286,7 @@ void IPureClient::_Recieve(const void* data, u32 data_size, u32 /*param*/) if ((data_size >= 2 * sizeof(u32)) && (cfg->sign1 == 0x12071980) && (cfg->sign2 == 0x26111975)) { // Internal system message - if ((data_size == sizeof(MSYS_PING))) + if (data_size == sizeof(MSYS_PING)) { // It is reverted(server) ping u32 time = TimerAsync(device_timer); @@ -296,19 +304,18 @@ void IPureClient::_Recieve(const void* data, u32 data_size, u32 /*param*/) return; } Msg("! Unknown system message"); - return; } - else if (net_Connected == EnmConnectionCompleted) + if (net_Connected == EnmConnectionCompleted) { // one of the messages - decompress it if (psNET_Flags.test(NETFLAG_LOG_CL_PACKETS)) { if (!pClNetLog) - pClNetLog = new INetLog("logs\\net_cl_log.log", timeServer()); + pClNetLog = new INetLog("logs//net_cl_log.log", timeServer()); if (pClNetLog) - pClNetLog->LogData(timeServer(), const_cast(data), data_size, TRUE); + pClNetLog->LogData(timeServer(), const_cast(data), data_size, true); } OnMessage(const_cast(data), data_size); @@ -316,43 +323,40 @@ void IPureClient::_Recieve(const void* data, u32 data_size, u32 /*param*/) } //============================================================================== - -IPureClient::IPureClient(CTimer* timer) - : net_Statistic(timer) #ifdef CONFIG_PROFILE_LOCKS - , - net_csEnumeration(MUTEX_PROFILE_ID(IPureClient::net_csEnumeration)) -#endif // CONFIG_PROFILE_LOCKS +IPureClient::IPureClient(CTimer* timer) : net_Statistic(timer), net_csEnumeration(MUTEX_PROFILE_ID(IPureClient::net_csEnumeration)) +#else +IPureClient::IPureClient(CTimer* timer) : net_Statistic(timer) +#endif { - NET = NULL; - net_Address_server = NULL; - net_Address_device = NULL; + NET = nullptr; + net_Address_server = nullptr; + net_Address_device = nullptr; device_timer = timer; net_TimeDelta_User = 0; net_Time_LastUpdate = 0; net_TimeDelta = 0; net_TimeDelta_Calculated = 0; - pClNetLog = NULL; // new INetLog("logs\\net_cl_log.log", timeServer()); + pClNetLog = nullptr; // new INetLog("logs//net_cl_log.log", timeServer()); } IPureClient::~IPureClient() { xr_delete(pClNetLog); - pClNetLog = NULL; - psNET_direct_connect = FALSE; + pClNetLog = nullptr; + psNET_direct_connect = false; } -BOOL IPureClient::Connect(LPCSTR options) +bool IPureClient::Connect(pcstr options) { R_ASSERT(options); - net_Disconnected = FALSE; + net_Disconnected = false; if (!psNET_direct_connect) { - // string256 server_name = ""; - // xr_strcpy (server_name,options); + //xr_strcpy(server_name,options); if (strchr(options, '/')) strncpy_s(server_name, options, strchr(options, '/') - options); if (strchr(server_name, '/')) @@ -397,9 +401,9 @@ BOOL IPureClient::Connect(LPCSTR options) *strchr(portstr, '/') = 0; psSV_Port = atol(portstr); clamp(psSV_Port, int(START_PORT), int(END_PORT)); - }; + } - BOOL bPortWasSet = FALSE; + bool bPortWasSet = false; int psCL_Port = START_PORT_LAN_CL; if (strstr(options, "portcl=")) { @@ -409,792 +413,816 @@ BOOL IPureClient::Connect(LPCSTR options) *strchr(portstr, '/') = 0; psCL_Port = atol(portstr); clamp(psCL_Port, int(START_PORT), int(END_PORT)); - bPortWasSet = TRUE; - }; - // Msg("* Client connect on port %d\n",psNET_Port); + bPortWasSet = true; + } + //Msg("* Client connect on port %d\n", psNET_Port); // net_Connected = EnmConnectionWait; - net_Syncronised = FALSE; - net_Disconnected = FALSE; + net_Syncronised = false; + net_Disconnected = false; //--------------------------- string1024 tmp = ""; - // HRESULT CoInitializeExRes = CoInitializeEx(NULL, 0); - // if (CoInitializeExRes != S_OK && CoInitializeExRes != S_FALSE) - // { - // DXTRACE_ERR(tmp, CoInitializeExRes); - // CHK_DX(CoInitializeExRes); - // }; + //HRESULT CoInitializeExRes = CoInitializeEx(nullptr, 0); + //if (CoInitializeExRes != S_OK && CoInitializeExRes != S_FALSE) + //{ + // DXTRACE_ERR(tmp, CoInitializeExRes); + // CHK_DX(CoInitializeExRes); + //} //--------------------------- // Create the IDirectPlay8Client object. HRESULT CoCreateInstanceRes = CoCreateInstance( - CLSID_DirectPlay8Client, NULL, CLSCTX_INPROC_SERVER, IID_IDirectPlay8Client, (LPVOID*)&NET); + CLSID_DirectPlay8Client, nullptr, CLSCTX_INPROC_SERVER, IID_IDirectPlay8Client, (LPVOID*)&NET); //--------------------------- if (CoCreateInstanceRes != S_OK) { DXTRACE_ERR(tmp, CoCreateInstanceRes); CHK_DX(CoCreateInstanceRes); } -//--------------------------- + //--------------------------- -// Initialize IDirectPlay8Client object. + // Initialize IDirectPlay8Client object. #ifdef DEBUG R_CHK(NET->Initialize(this, Handler, 0)); #else R_CHK(NET->Initialize(this, Handler, DPNINITIALIZE_DISABLEPARAMVAL)); #endif - BOOL bSimulator = FALSE; + bool bSimulator = false; if (strstr(Core.Params, "-netsim")) - bSimulator = TRUE; + bSimulator = true; // Create our IDirectPlay8Address Device Address, --- Set the SP for our Device Address - net_Address_device = NULL; + net_Address_device = nullptr; R_CHK(CoCreateInstance(CLSID_DirectPlay8Address, NULL, CLSCTX_INPROC_SERVER, IID_IDirectPlay8Address, (LPVOID*)&net_Address_device)); - R_CHK(net_Address_device->SetSP(bSimulator ? &CLSID_NETWORKSIMULATOR_DP8SP_TCPIP : &CLSID_DP8SP_TCPIP)); + R_CHK(net_Address_device->SetSP(bSimulator ? &CLSID_NETWORKSIMULATOR_DP8SP_TCPIP : &CLSID_DP8SP_TCPIP)); + + // Create our IDirectPlay8Address Server Address, --- Set the SP for our Server Address + WCHAR ServerNameUNICODE[256]; + R_CHK(MultiByteToWideChar(CP_ACP, 0, server_name, -1, ServerNameUNICODE, 256)); + + net_Address_server = nullptr; + R_CHK(CoCreateInstance(CLSID_DirectPlay8Address, NULL, CLSCTX_INPROC_SERVER, IID_IDirectPlay8Address, + (LPVOID*)&net_Address_server)); + R_CHK(net_Address_server->SetSP(bSimulator ? &CLSID_NETWORKSIMULATOR_DP8SP_TCPIP : &CLSID_DP8SP_TCPIP)); + R_CHK(net_Address_server->AddComponent( + DPNA_KEY_HOSTNAME, ServerNameUNICODE, 2 * u32(wcslen(ServerNameUNICODE) + 1), DPNA_DATATYPE_STRING)); + R_CHK(net_Address_server->AddComponent(DPNA_KEY_PORT, &psSV_Port, sizeof(psSV_Port), DPNA_DATATYPE_DWORD)); + + // Debug + // dump_URL ("! cl ", net_Address_device); + // dump_URL ("! en ", net_Address_server); + + // Now set up the Application Description + DPN_APPLICATION_DESC dpAppDesc; + ZeroMemory(&dpAppDesc, sizeof(DPN_APPLICATION_DESC)); + dpAppDesc.dwSize = sizeof(DPN_APPLICATION_DESC); + dpAppDesc.guidApplication = NET_GUID; + + // Setup client info + /*xr_strcpy( tmp, server_name ); + xr_strcat( tmp, "/name=" ); + xr_strcat( tmp, user_name_str ); + xr_strcat( tmp, "/" );*/ + + WCHAR ClientNameUNICODE[256]; + R_CHK(MultiByteToWideChar(CP_ACP, 0, user_name_str, -1, ClientNameUNICODE, 256)); - // Create our IDirectPlay8Address Server Address, --- Set the SP for our Server Address - WCHAR ServerNameUNICODE[256]; - R_CHK(MultiByteToWideChar(CP_ACP, 0, server_name, -1, ServerNameUNICODE, 256)); - - net_Address_server = NULL; - R_CHK(CoCreateInstance(CLSID_DirectPlay8Address, NULL, CLSCTX_INPROC_SERVER, IID_IDirectPlay8Address, - (LPVOID*)&net_Address_server)); - R_CHK(net_Address_server->SetSP(bSimulator ? &CLSID_NETWORKSIMULATOR_DP8SP_TCPIP : &CLSID_DP8SP_TCPIP)); - R_CHK(net_Address_server->AddComponent( - DPNA_KEY_HOSTNAME, ServerNameUNICODE, 2 * u32(wcslen(ServerNameUNICODE) + 1), DPNA_DATATYPE_STRING)); - R_CHK(net_Address_server->AddComponent(DPNA_KEY_PORT, &psSV_Port, sizeof(psSV_Port), DPNA_DATATYPE_DWORD)); - - // Debug - // dump_URL ("! cl ", net_Address_device); - // dump_URL ("! en ", net_Address_server); - - // Now set up the Application Description - DPN_APPLICATION_DESC dpAppDesc; - ZeroMemory(&dpAppDesc, sizeof(DPN_APPLICATION_DESC)); - dpAppDesc.dwSize = sizeof(DPN_APPLICATION_DESC); - dpAppDesc.guidApplication = NET_GUID; - - // Setup client info - /*xr_strcpy( tmp, server_name ); - xr_strcat( tmp, "/name=" ); - xr_strcat( tmp, user_name_str ); - xr_strcat( tmp, "/" );*/ - - WCHAR ClientNameUNICODE[256]; - R_CHK(MultiByteToWideChar(CP_ACP, 0, user_name_str, -1, ClientNameUNICODE, 256)); - - { - DPN_PLAYER_INFO Pinfo; - ZeroMemory(&Pinfo, sizeof(Pinfo)); - Pinfo.dwSize = sizeof(Pinfo); - Pinfo.dwInfoFlags = DPNINFO_NAME | DPNINFO_DATA; - Pinfo.pwszName = ClientNameUNICODE; + { + DPN_PLAYER_INFO Pinfo; + ZeroMemory(&Pinfo, sizeof(Pinfo)); + Pinfo.dwSize = sizeof(Pinfo); + Pinfo.dwInfoFlags = DPNINFO_NAME | DPNINFO_DATA; + Pinfo.pwszName = ClientNameUNICODE; - SClientConnectData cl_data; - cl_data.process_id = GetCurrentProcessId(); - xr_strcpy(cl_data.name, user_name_str); - xr_strcpy(cl_data.pass, user_pass); + SClientConnectData cl_data; + cl_data.process_id = GetCurrentProcessId(); + xr_strcpy(cl_data.name, user_name_str); + xr_strcpy(cl_data.pass, user_pass); - Pinfo.pvData = &cl_data; - Pinfo.dwDataSize = sizeof(cl_data); + Pinfo.pvData = &cl_data; + Pinfo.dwDataSize = sizeof(cl_data); - R_CHK(NET->SetClientInfo(&Pinfo, 0, 0, DPNSETCLIENTINFO_SYNC)); - } - if (_stricmp(server_name, "localhost") == 0) - { - WCHAR SessionPasswordUNICODE[4096]; - if (xr_strlen(password_str)) - { - CHK_DX(MultiByteToWideChar(CP_ACP, 0, password_str, -1, SessionPasswordUNICODE, 4096)); - dpAppDesc.dwFlags |= DPNSESSION_REQUIREPASSWORD; - dpAppDesc.pwszPassword = SessionPasswordUNICODE; - }; - - u32 c_port = u32(psCL_Port); - HRESULT res = S_FALSE; - while (res != S_OK) - { - R_CHK(net_Address_device->AddComponent(DPNA_KEY_PORT, &c_port, sizeof(c_port), DPNA_DATATYPE_DWORD)); - res = NET->Connect(&dpAppDesc, // pdnAppDesc - net_Address_server, // pHostAddr - net_Address_device, // pDeviceInfo - NULL, // pdnSecurity - NULL, // pdnCredentials - NULL, 0, // pvUserConnectData/Size - NULL, // pvAsyncContext - NULL, // pvAsyncHandle - DPNCONNECT_SYNC); // dwFlags - if (res != S_OK) + R_CHK(NET->SetClientInfo(&Pinfo, nullptr, nullptr, DPNSETCLIENTINFO_SYNC)); + } + if (_stricmp(server_name, "localhost") == 0) { - // xr_string res = xrDebug::ErrorToString(HostSuccess); - - if (bPortWasSet) + WCHAR SessionPasswordUNICODE[4096]; + if (xr_strlen(password_str)) { - Msg("! IPureClient : port %d is BUSY!", c_port); - return FALSE; + CHK_DX(MultiByteToWideChar(CP_ACP, 0, password_str, -1, SessionPasswordUNICODE, 4096)); + dpAppDesc.dwFlags |= DPNSESSION_REQUIREPASSWORD; + dpAppDesc.pwszPassword = SessionPasswordUNICODE; } - else + + u32 c_port = u32(psCL_Port); + HRESULT res = S_FALSE; + while (res != S_OK) { - Msg("! IPureClient : port %d is BUSY!", c_port); + R_CHK(net_Address_device->AddComponent(DPNA_KEY_PORT, &c_port, sizeof(c_port), DPNA_DATATYPE_DWORD)); + res = NET->Connect(&dpAppDesc, // pdnAppDesc + net_Address_server, // pHostAddr + net_Address_device, // pDeviceInfo + nullptr, // pdnSecurity + nullptr, // pdnCredentials + nullptr, 0, // pvUserConnectData/Size + nullptr, // pvAsyncContext + nullptr, // pvAsyncHandle + DPNCONNECT_SYNC); // dwFlags + if (res != S_OK) + { + // xr_string res = xrDebug::ErrorToString(HostSuccess); + + if (bPortWasSet) + { + Msg("! IPureClient : port %d is BUSY!", c_port); + return false; + } + Msg("! IPureClient : port %d is BUSY!", c_port); + + c_port++; + if (c_port > END_PORT_LAN) + { + return false; + } + } + else + { + Msg("- IPureClient : created on port %d!", c_port); + } } - c_port++; - if (c_port > END_PORT_LAN) + // R_CHK(res); + if (res != S_OK) + return false; + + // Create ONE node + HOST_NODE NODE; + ZeroMemory(&NODE, sizeof(HOST_NODE)); + + // Copy the Host Address + R_CHK(net_Address_server->Duplicate(&NODE.pHostAddress)); + + // Retreive session name + char desc[4096]; + ZeroMemory(desc, sizeof(desc)); + DPN_APPLICATION_DESC* dpServerDesc = (DPN_APPLICATION_DESC*)desc; + DWORD dpServerDescSize = sizeof(desc); + dpServerDesc->dwSize = sizeof(DPN_APPLICATION_DESC); + R_CHK(NET->GetApplicationDesc(dpServerDesc, &dpServerDescSize, 0)); + if (!dpServerDesc->dwApplicationReservedDataSize || !dpServerDesc->pvApplicationReservedData) + { + OnInvalidHost(); + return false; + } + CopyMemory(&m_game_description, dpServerDesc->pvApplicationReservedData, + dpServerDesc->dwApplicationReservedDataSize); + if (dpServerDesc->pwszSessionName) { - return FALSE; + string4096 dpSessionName; + R_CHK(WideCharToMultiByte( + CP_ACP, 0, dpServerDesc->pwszSessionName, -1, dpSessionName, sizeof(dpSessionName), nullptr, nullptr)); + NODE.dpSessionName = (pstr)&dpSessionName[0]; } + net_Hosts.push_back(NODE); } else { - Msg("- IPureClient : created on port %d!", c_port); - } - }; - - // R_CHK(res); - if (res != S_OK) - return FALSE; - - // Create ONE node - HOST_NODE NODE; - ZeroMemory(&NODE, sizeof(HOST_NODE)); - - // Copy the Host Address - R_CHK(net_Address_server->Duplicate(&NODE.pHostAddress)); - - // Retreive session name - char desc[4096]; - ZeroMemory(desc, sizeof(desc)); - DPN_APPLICATION_DESC* dpServerDesc = (DPN_APPLICATION_DESC*)desc; - DWORD dpServerDescSize = sizeof(desc); - dpServerDesc->dwSize = sizeof(DPN_APPLICATION_DESC); - R_CHK(NET->GetApplicationDesc(dpServerDesc, &dpServerDescSize, 0)); - if (!dpServerDesc->dwApplicationReservedDataSize || !dpServerDesc->pvApplicationReservedData) - { - OnInvalidHost(); - return FALSE; - } - CopyMemory(&m_game_description, dpServerDesc->pvApplicationReservedData, - dpServerDesc->dwApplicationReservedDataSize); - if (dpServerDesc->pwszSessionName) - { - string4096 dpSessionName; - R_CHK(WideCharToMultiByte( - CP_ACP, 0, dpServerDesc->pwszSessionName, -1, dpSessionName, sizeof(dpSessionName), 0, 0)); - NODE.dpSessionName = (char*)(&dpSessionName[0]); - } - net_Hosts.push_back(NODE); - } - else - { - string64 EnumData; - EnumData[0] = 0; - xr_strcat(EnumData, "ToConnect"); - DWORD EnumSize = xr_strlen(EnumData) + 1; - // We now have the host address so lets enum - u32 c_port = psCL_Port; - HRESULT res = S_FALSE; - while (res != S_OK && c_port <= END_PORT) - { - R_CHK(net_Address_device->AddComponent(DPNA_KEY_PORT, &c_port, sizeof(c_port), DPNA_DATATYPE_DWORD)); - - res = NET->EnumHosts(&dpAppDesc, // pApplicationDesc - for unknown reason - net_Address_server, // pdpaddrHost - net_Address_device, // pdpaddrDeviceInfo - EnumData, EnumSize, // pvUserEnumData, size - 10, // dwEnumCount - 1000, // dwRetryInterval - 1000, // dwTimeOut - NULL, // pvUserContext - NULL, // pAsyncHandle - DPNENUMHOSTS_SYNC // dwFlags - ); - if (res != S_OK) - { - // xr_string res = xrDebug::ErrorToString(HostSuccess); - switch (res) - { - case DPNERR_INVALIDHOSTADDRESS: + string64 EnumData; + EnumData[0] = 0; + xr_strcat(EnumData, "ToConnect"); + DWORD EnumSize = xr_strlen(EnumData) + 1; + // We now have the host address so lets enum + u32 c_port = psCL_Port; + HRESULT res = S_FALSE; + while (res != S_OK && c_port <= END_PORT) { - OnInvalidHost(); - return FALSE; + R_CHK(net_Address_device->AddComponent(DPNA_KEY_PORT, &c_port, sizeof(c_port), DPNA_DATATYPE_DWORD)); + + res = NET->EnumHosts(&dpAppDesc, // pApplicationDesc - for unknown reason + net_Address_server, // pdpaddrHost + net_Address_device, // pdpaddrDeviceInfo + EnumData, EnumSize, // pvUserEnumData, size + 10, // dwEnumCount + 1000, // dwRetryInterval + 1000, // dwTimeOut + nullptr, // pvUserContext + nullptr, // pAsyncHandle + DPNENUMHOSTS_SYNC // dwFlags + ); + if (res != S_OK) + { + //xr_string res = xrDebug::ErrorToString(HostSuccess); + switch (res) + { + case DPNERR_INVALIDHOSTADDRESS: + { + OnInvalidHost(); + return false; + } + + case DPNERR_SESSIONFULL: + { + OnSessionFull(); + return false; + } + + } + + if (bPortWasSet) + { + Msg("! IPureClient : port %d is BUSY!", c_port); + return false; + } +#ifdef DEBUG + Msg("! IPureClient : port %d is BUSY!", c_port); + + //pcstr x = DXGetErrorString9(res); + string1024 tmp2 = ""; + DXTRACE_ERR(tmp2, res); +#endif + c_port++; + } + else + Msg("- IPureClient : created on port %d!", c_port); } - break; - case DPNERR_SESSIONFULL: + + // ****** Connection + IDirectPlay8Address* pHostAddress = nullptr; + if (net_Hosts.empty()) { - OnSessionFull(); - return FALSE; + OnInvalidHost(); + return false; } - break; - }; - if (bPortWasSet) + WCHAR SessionPasswordUNICODE[4096]; + if (xr_strlen(password_str)) { - Msg("! IPureClient : port %d is BUSY!", c_port); - return FALSE; + CHK_DX(MultiByteToWideChar(CP_ACP, 0, password_str, -1, SessionPasswordUNICODE, 4096)); + dpAppDesc.dwFlags |= DPNSESSION_REQUIREPASSWORD; + dpAppDesc.pwszPassword = SessionPasswordUNICODE; } -#ifdef DEBUG - else - Msg("! IPureClient : port %d is BUSY!", c_port); - // const char* x = DXGetErrorString9(res); - string1024 tmp2 = ""; - DXTRACE_ERR(tmp2, res); -#endif - c_port++; - } - else - { - Msg("- IPureClient : created on port %d!", c_port); - } - }; - - // ****** Connection - IDirectPlay8Address* pHostAddress = NULL; - if (net_Hosts.empty()) - { - OnInvalidHost(); - return FALSE; - }; - - WCHAR SessionPasswordUNICODE[4096]; - if (xr_strlen(password_str)) - { - CHK_DX(MultiByteToWideChar(CP_ACP, 0, password_str, -1, SessionPasswordUNICODE, 4096)); - dpAppDesc.dwFlags |= DPNSESSION_REQUIREPASSWORD; - dpAppDesc.pwszPassword = SessionPasswordUNICODE; - }; - - net_csEnumeration.Enter(); - // real connect - for (u32 I = 0; I < net_Hosts.size(); I++) - Msg("* HOST #%d: %s\n", I + 1, *net_Hosts[I].dpSessionName); - - R_CHK(net_Hosts.front().pHostAddress->Duplicate(&pHostAddress)); - // dump_URL ("! c2s ", pHostAddress); - res = NET->Connect(&dpAppDesc, // pdnAppDesc - pHostAddress, // pHostAddr - net_Address_device, // pDeviceInfo - NULL, // pdnSecurity - NULL, // pdnCredentials - NULL, 0, // pvUserConnectData/Size - NULL, // pvAsyncContext - NULL, // pvAsyncHandle - DPNCONNECT_SYNC); // dwFlags - // R_CHK(res); - net_csEnumeration.Leave(); - _RELEASE(pHostAddress); + net_csEnumeration.Enter(); + // real connect + for (u32 I = 0; I < net_Hosts.size(); I++) + Msg("* HOST #%d: %s\n", I + 1, *net_Hosts[I].dpSessionName); + + R_CHK(net_Hosts.front().pHostAddress->Duplicate(&pHostAddress)); + // dump_URL ("! c2s ", pHostAddress); + res = NET->Connect(&dpAppDesc, // pdnAppDesc + pHostAddress, // pHostAddr + net_Address_device, // pDeviceInfo + nullptr, // pdnSecurity + nullptr, // pdnCredentials + nullptr, 0, // pvUserConnectData/Size + nullptr, // pvAsyncContext + nullptr, // pvAsyncHandle + DPNCONNECT_SYNC); // dwFlags + // R_CHK(res); + net_csEnumeration.Leave(); + _RELEASE(pHostAddress); #ifdef DEBUG - // const char* x = DXGetErrorString9(res); + // const char* x = DXGetErrorString9(res); string1024 tmp2 = ""; DXTRACE_ERR(tmp2, res); #endif - switch (res) - { - case DPNERR_INVALIDPASSWORD: { OnInvalidPassword(); - } - break; - case DPNERR_SESSIONFULL: { OnSessionFull(); - } - break; - case DPNERR_CANTCREATEPLAYER: { Msg("! Error: Can\'t create player"); - } - break; - } - if (res != S_OK) - return FALSE; - } - - // Caps - /* - GUID sp_guid; - DPN_SP_CAPS sp_caps; - - net_Address_device->GetSP(&sp_guid); - ZeroMemory (&sp_caps,sizeof(sp_caps)); - sp_caps.dwSize = sizeof(sp_caps); - R_CHK (NET->GetSPCaps(&sp_guid,&sp_caps,0)); - sp_caps.dwSystemBufferSize = 0; - R_CHK (NET->SetSPCaps(&sp_guid,&sp_caps,0)); - R_CHK (NET->GetSPCaps(&sp_guid,&sp_caps,0)); - */ - } // psNET_direct_connect - // Sync - net_TimeDelta = 0; - return TRUE; -} - -void IPureClient::Disconnect() -{ - if (NET) - NET->Close(0); - - // Clean up Host _list_ - net_csEnumeration.Enter(); - for (u32 i = 0; i < net_Hosts.size(); i++) - { - HOST_NODE& N = net_Hosts[i]; - _RELEASE(N.pHostAddress); - } - net_Hosts.clear(); - net_csEnumeration.Leave(); - - // Release interfaces - _SHOW_REF("cl_netADR_Server", net_Address_server); - _RELEASE(net_Address_server); - _SHOW_REF("cl_netADR_Device", net_Address_device); - _RELEASE(net_Address_device); - _SHOW_REF("cl_netCORE", NET); - _RELEASE(NET); - - net_Connected = EnmConnectionWait; - net_Syncronised = FALSE; -} - -HRESULT IPureClient::net_Handler(u32 dwMessageType, PVOID pMessage) -{ - // HRESULT hr = S_OK; + switch (res) + { + case DPNERR_INVALIDPASSWORD: + { + OnInvalidPassword(); + } + break; + case DPNERR_SESSIONFULL: + { + OnSessionFull(); + } + break; + case DPNERR_CANTCREATEPLAYER: + { + Msg("! Error: Can\'t create player"); + } + break; + } + if (res != S_OK) + return false; + } - switch (dwMessageType) - { - case DPN_MSGID_ENUM_HOSTS_RESPONSE: - { - PDPNMSG_ENUM_HOSTS_RESPONSE pEnumHostsResponseMsg; - const DPN_APPLICATION_DESC* pDesc; - // HOST_NODE* pHostNode = NULL; - // WCHAR* pwszSession = NULL; + // Caps + /* + GUID sp_guid; + DPN_SP_CAPS sp_caps; + + net_Address_device->GetSP(&sp_guid); + ZeroMemory (&sp_caps,sizeof(sp_caps)); + sp_caps.dwSize = sizeof(sp_caps); + R_CHK (NET->GetSPCaps(&sp_guid,&sp_caps,0)); + sp_caps.dwSystemBufferSize = 0; + R_CHK (NET->SetSPCaps(&sp_guid,&sp_caps,0)); + R_CHK (NET->GetSPCaps(&sp_guid,&sp_caps,0)); + */ + } // psNET_direct_connect + // Sync + net_TimeDelta = 0; + return true; + } - pEnumHostsResponseMsg = (PDPNMSG_ENUM_HOSTS_RESPONSE)pMessage; - pDesc = pEnumHostsResponseMsg->pApplicationDescription; + void IPureClient::Disconnect() + { + if (NET) + NET->Close(0); - if (pDesc->dwApplicationReservedDataSize && pDesc->pvApplicationReservedData) - { - R_ASSERT(pDesc->dwApplicationReservedDataSize == sizeof(m_game_description)); - CopyMemory(&m_game_description, pDesc->pvApplicationReservedData, pDesc->dwApplicationReservedDataSize); - } + // Clean up Host _list_ + net_csEnumeration.Enter(); + for (u32 i = 0; i < net_Hosts.size(); i++) + { + HOST_NODE& N = net_Hosts[i]; + _RELEASE(N.pHostAddress); + } + net_Hosts.clear(); + net_csEnumeration.Leave(); + + // Release interfaces + _SHOW_REF("cl_netADR_Server", net_Address_server); + _RELEASE(net_Address_server); + _SHOW_REF("cl_netADR_Device", net_Address_device); + _RELEASE(net_Address_device); + _SHOW_REF("cl_netCORE", NET); + _RELEASE(NET); + + net_Connected = EnmConnectionWait; + net_Syncronised = false; + } - // Insert each host response if it isn't already present - net_csEnumeration.Enter(); - BOOL bHostRegistered = FALSE; - for (u32 I = 0; I < net_Hosts.size(); I++) - { - HOST_NODE& N = net_Hosts[I]; - if (pDesc->guidInstance == N.pdpAppDesc->guidInstance) - { - // This host is already in the list - bHostRegistered = TRUE; - break; - } - } + HRESULT IPureClient::net_Handler(u32 dwMessageType, PVOID pMessage) + { + // HRESULT hr = S_OK; - if (!bHostRegistered) - { - // This host session is not in the list then so insert it. - HOST_NODE NODE; - ZeroMemory(&NODE, sizeof(HOST_NODE)); - - // Copy the Host Address - R_CHK(pEnumHostsResponseMsg->pAddressSender->Duplicate(&NODE.pHostAddress)); - CopyMemory(NODE.pdpAppDesc, pDesc, sizeof(DPN_APPLICATION_DESC)); - - // Null out all the pointers we aren't copying - NODE.pdpAppDesc->pwszSessionName = NULL; - NODE.pdpAppDesc->pwszPassword = NULL; - NODE.pdpAppDesc->pvReservedData = NULL; - NODE.pdpAppDesc->dwReservedDataSize = 0; - NODE.pdpAppDesc->pvApplicationReservedData = NULL; - NODE.pdpAppDesc->dwApplicationReservedDataSize = 0; - - if (pDesc->pwszSessionName) - { - string4096 dpSessionName; - R_CHK(WideCharToMultiByte( - CP_ACP, 0, pDesc->pwszSessionName, -1, dpSessionName, sizeof(dpSessionName), 0, 0)); - NODE.dpSessionName = (char*)(&dpSessionName[0]); - } - - net_Hosts.push_back(NODE); - } - net_csEnumeration.Leave(); - } - break; + switch (dwMessageType) + { + case DPN_MSGID_ENUM_HOSTS_RESPONSE: + { + PDPNMSG_ENUM_HOSTS_RESPONSE pEnumHostsResponseMsg; + const DPN_APPLICATION_DESC* pDesc; + // HOST_NODE* pHostNode = NULL; + // WCHAR* pwszSession = NULL; + + pEnumHostsResponseMsg = (PDPNMSG_ENUM_HOSTS_RESPONSE)pMessage; + pDesc = pEnumHostsResponseMsg->pApplicationDescription; + + if (pDesc->dwApplicationReservedDataSize && pDesc->pvApplicationReservedData) + { + R_ASSERT(pDesc->dwApplicationReservedDataSize == sizeof(m_game_description)); + CopyMemory(&m_game_description, pDesc->pvApplicationReservedData, pDesc->dwApplicationReservedDataSize); + } + + // Insert each host response if it isn't already present + net_csEnumeration.Enter(); + bool bHostRegistered = false; + for (u32 I = 0; I < net_Hosts.size(); I++) + { + HOST_NODE& N = net_Hosts[I]; + if (pDesc->guidInstance == N.pdpAppDesc->guidInstance) + { + // This host is already in the list + bHostRegistered = true; + break; + } + } + + if (!bHostRegistered) + { + // This host session is not in the list then so insert it. + HOST_NODE NODE; + ZeroMemory(&NODE, sizeof(HOST_NODE)); + + // Copy the Host Address + R_CHK(pEnumHostsResponseMsg->pAddressSender->Duplicate(&NODE.pHostAddress)); + CopyMemory(NODE.pdpAppDesc, pDesc, sizeof(DPN_APPLICATION_DESC)); + + // Null out all the pointers we aren't copying + NODE.pdpAppDesc->pwszSessionName = nullptr; + NODE.pdpAppDesc->pwszPassword = nullptr; + NODE.pdpAppDesc->pvReservedData = nullptr; + NODE.pdpAppDesc->dwReservedDataSize = 0; + NODE.pdpAppDesc->pvApplicationReservedData = nullptr; + NODE.pdpAppDesc->dwApplicationReservedDataSize = 0; + + if (pDesc->pwszSessionName) + { + string4096 dpSessionName; + R_CHK(WideCharToMultiByte( + CP_ACP, 0, pDesc->pwszSessionName, -1, dpSessionName, sizeof(dpSessionName), nullptr, nullptr)); + NODE.dpSessionName = (pstr)(&dpSessionName[0]); + } + + net_Hosts.push_back(NODE); + } + net_csEnumeration.Leave(); + } + break; - case DPN_MSGID_RECEIVE: - { - PDPNMSG_RECEIVE pMsg = (PDPNMSG_RECEIVE)pMessage; + case DPN_MSGID_RECEIVE: + { + PDPNMSG_RECEIVE pMsg = (PDPNMSG_RECEIVE)pMessage; - MultipacketReciever::RecievePacket(pMsg->pReceiveData, pMsg->dwReceiveDataSize); - } - break; - case DPN_MSGID_TERMINATE_SESSION: - { - PDPNMSG_TERMINATE_SESSION pMsg = (PDPNMSG_TERMINATE_SESSION)pMessage; - char* m_data = (char*)pMsg->pvTerminateData; - u32 m_size = pMsg->dwTerminateDataSize; - HRESULT m_hResultCode = pMsg->hResultCode; + RecievePacket(pMsg->pReceiveData, pMsg->dwReceiveDataSize); + } + break; + case DPN_MSGID_TERMINATE_SESSION: + { + PDPNMSG_TERMINATE_SESSION pMsg = (PDPNMSG_TERMINATE_SESSION)pMessage; + auto m_data = (pstr)pMsg->pvTerminateData; + u32 m_size = pMsg->dwTerminateDataSize; + HRESULT m_hResultCode = pMsg->hResultCode; - net_Disconnected = TRUE; + net_Disconnected = true; - if (m_size != 0) - { - OnSessionTerminate(m_data); + if (m_size != 0) + { + OnSessionTerminate(m_data); #ifdef DEBUG - Msg("- Session terminated : %s", m_data); + //Msg("- Session terminated : %s", m_data); #endif - } - else - { + } + else + { #ifdef DEBUG - OnSessionTerminate((xrDebug::ErrorToString(m_hResultCode))); - Msg("- Session terminated : %s", (xrDebug::ErrorToString(m_hResultCode))); + OnSessionTerminate((xrDebug::ErrorToString(m_hResultCode))); + Msg("- Session terminated : %s", (xrDebug::ErrorToString(m_hResultCode))); #endif - } - }; - break; - default: { + } + } + break; + default: + { #if 1 - LPSTR msg = ""; - switch (dwMessageType) - { - case DPN_MSGID_ADD_PLAYER_TO_GROUP: msg = "DPN_MSGID_ADD_PLAYER_TO_GROUP"; break; - case DPN_MSGID_ASYNC_OP_COMPLETE: msg = "DPN_MSGID_ASYNC_OP_COMPLETE"; break; - case DPN_MSGID_CLIENT_INFO: msg = "DPN_MSGID_CLIENT_INFO"; break; - case DPN_MSGID_CONNECT_COMPLETE: { PDPNMSG_CONNECT_COMPLETE pMsg = (PDPNMSG_CONNECT_COMPLETE)pMessage; + pstr msg = ""; + switch (dwMessageType) + { + case DPN_MSGID_ADD_PLAYER_TO_GROUP: msg = "DPN_MSGID_ADD_PLAYER_TO_GROUP"; + break; + case DPN_MSGID_ASYNC_OP_COMPLETE: msg = "DPN_MSGID_ASYNC_OP_COMPLETE"; + break; + case DPN_MSGID_CLIENT_INFO: msg = "DPN_MSGID_CLIENT_INFO"; + break; + case DPN_MSGID_CONNECT_COMPLETE: + { + PDPNMSG_CONNECT_COMPLETE pMsg = (PDPNMSG_CONNECT_COMPLETE)pMessage; #ifdef DEBUG - // const char* x = DXGetErrorString9(pMsg->hResultCode); - if (pMsg->hResultCode != S_OK) - { - string1024 tmp = ""; - DXTRACE_ERR(tmp, pMsg->hResultCode); - } + //pcstr x = DXGetErrorString9(pMsg->hResultCode); + if (pMsg->hResultCode != S_OK) + { + string1024 tmp = ""; + DXTRACE_ERR(tmp, pMsg->hResultCode); + } #endif - if (pMsg->dwApplicationReplyDataSize) - { - string256 ResStr = ""; - strncpy_s(ResStr, (char*)(pMsg->pvApplicationReplyData), pMsg->dwApplicationReplyDataSize); - Msg("Connection result : %s", ResStr); - } - else - msg = "DPN_MSGID_CONNECT_COMPLETE"; - } - break; - case DPN_MSGID_CREATE_GROUP: msg = "DPN_MSGID_CREATE_GROUP"; break; - case DPN_MSGID_CREATE_PLAYER: msg = "DPN_MSGID_CREATE_PLAYER"; break; - case DPN_MSGID_DESTROY_GROUP: msg = "DPN_MSGID_DESTROY_GROUP"; break; - case DPN_MSGID_DESTROY_PLAYER: msg = "DPN_MSGID_DESTROY_PLAYER"; break; - case DPN_MSGID_ENUM_HOSTS_QUERY: msg = "DPN_MSGID_ENUM_HOSTS_QUERY"; break; - case DPN_MSGID_GROUP_INFO: msg = "DPN_MSGID_GROUP_INFO"; break; - case DPN_MSGID_HOST_MIGRATE: msg = "DPN_MSGID_HOST_MIGRATE"; break; - case DPN_MSGID_INDICATE_CONNECT: msg = "DPN_MSGID_INDICATE_CONNECT"; break; - case DPN_MSGID_INDICATED_CONNECT_ABORTED: msg = "DPN_MSGID_INDICATED_CONNECT_ABORTED"; break; - case DPN_MSGID_PEER_INFO: msg = "DPN_MSGID_PEER_INFO"; break; - case DPN_MSGID_REMOVE_PLAYER_FROM_GROUP: msg = "DPN_MSGID_REMOVE_PLAYER_FROM_GROUP"; break; - case DPN_MSGID_RETURN_BUFFER: msg = "DPN_MSGID_RETURN_BUFFER"; break; - case DPN_MSGID_SEND_COMPLETE: msg = "DPN_MSGID_SEND_COMPLETE"; break; - case DPN_MSGID_SERVER_INFO: msg = "DPN_MSGID_SERVER_INFO"; break; - case DPN_MSGID_TERMINATE_SESSION: msg = "DPN_MSGID_TERMINATE_SESSION"; break; - default: msg = "???"; break; - } -// Msg("! ************************************ : %s",msg); + if (pMsg->dwApplicationReplyDataSize) + { + string256 ResStr = ""; + strncpy_s(ResStr, (char*)pMsg->pvApplicationReplyData, pMsg->dwApplicationReplyDataSize); + Msg("Connection result : %s", ResStr); + } + else + msg = "DPN_MSGID_CONNECT_COMPLETE"; + } + break; + case DPN_MSGID_CREATE_GROUP: msg = "DPN_MSGID_CREATE_GROUP"; + break; + case DPN_MSGID_CREATE_PLAYER: msg = "DPN_MSGID_CREATE_PLAYER"; + break; + case DPN_MSGID_DESTROY_GROUP: msg = "DPN_MSGID_DESTROY_GROUP"; + break; + case DPN_MSGID_DESTROY_PLAYER: msg = "DPN_MSGID_DESTROY_PLAYER"; + break; + case DPN_MSGID_ENUM_HOSTS_QUERY: msg = "DPN_MSGID_ENUM_HOSTS_QUERY"; + break; + case DPN_MSGID_GROUP_INFO: msg = "DPN_MSGID_GROUP_INFO"; + break; + case DPN_MSGID_HOST_MIGRATE: msg = "DPN_MSGID_HOST_MIGRATE"; + break; + case DPN_MSGID_INDICATE_CONNECT: msg = "DPN_MSGID_INDICATE_CONNECT"; + break; + case DPN_MSGID_INDICATED_CONNECT_ABORTED: msg = "DPN_MSGID_INDICATED_CONNECT_ABORTED"; + break; + case DPN_MSGID_PEER_INFO: msg = "DPN_MSGID_PEER_INFO"; + break; + case DPN_MSGID_REMOVE_PLAYER_FROM_GROUP: msg = "DPN_MSGID_REMOVE_PLAYER_FROM_GROUP"; + break; + case DPN_MSGID_RETURN_BUFFER: msg = "DPN_MSGID_RETURN_BUFFER"; + break; + case DPN_MSGID_SEND_COMPLETE: msg = "DPN_MSGID_SEND_COMPLETE"; + break; + case DPN_MSGID_SERVER_INFO: msg = "DPN_MSGID_SERVER_INFO"; + break; + case DPN_MSGID_TERMINATE_SESSION: msg = "DPN_MSGID_TERMINATE_SESSION"; + break; + default: msg = "???"; + break; + } + //Msg("! ************************************ : %s", msg); #endif - } - break; - } - - return S_OK; -} + } + break; + } -void IPureClient::OnMessage(void* data, u32 size) -{ - // One of the messages - decompress it - net_Queue.Lock(); - NET_Packet* P = net_Queue.Create(); + return S_OK; + } - P->construct(data, size); - P->timeReceive = timeServer_Async(); // TimerAsync (device_timer); + void IPureClient::OnMessage(void* data, u32 size) + { + // One of the messages - decompress it + net_Queue.Lock(); + NET_Packet* P = net_Queue.Create(); - u16 m_type; - P->r_begin(m_type); - net_Queue.Unlock(); -} + P->construct(data, size); + P->timeReceive = timeServer_Async(); // TimerAsync(device_timer); -void IPureClient::timeServer_Correct(u32 sv_time, u32 cl_time) -{ - u32 ping = net_Statistic.getPing(); - u32 delta = sv_time + ping / 2 - cl_time; - net_DeltaArray.push(delta); - Sync_Average(); -} - -void IPureClient::SendTo_LL(void* data, u32 size, u32 dwFlags, u32 dwTimeout) -{ - if (net_Disconnected) - return; + u16 m_type; + P->r_begin(m_type); + net_Queue.Unlock(); + } - if (psNET_Flags.test(NETFLAG_LOG_CL_PACKETS)) - { - if (!pClNetLog) - pClNetLog = new INetLog("logs\\net_cl_log.log", timeServer()); - if (pClNetLog) - pClNetLog->LogData(timeServer(), data, size); - } - DPN_BUFFER_DESC desc; + void IPureClient::timeServer_Correct(u32 sv_time, u32 cl_time) + { + u32 ping = net_Statistic.getPing(); + u32 delta = sv_time + ping / 2 - cl_time; + net_DeltaArray.push(delta); + Sync_Average(); + } - desc.dwBufferSize = size; - desc.pBufferData = (BYTE*)data; + void IPureClient::SendTo_LL(void* data, u32 size, u32 dwFlags, u32 dwTimeout) + { + if (net_Disconnected) + return; - net_Statistic.dwBytesSended += size; + if (psNET_Flags.test(NETFLAG_LOG_CL_PACKETS)) + { + if (!pClNetLog) + pClNetLog = new INetLog("logs\\net_cl_log.log", timeServer()); + if (pClNetLog) + pClNetLog->LogData(timeServer(), data, size); + } + DPN_BUFFER_DESC desc; - // verify - VERIFY(desc.dwBufferSize); - VERIFY(desc.pBufferData); - VERIFY(NET); + desc.dwBufferSize = size; + desc.pBufferData = (BYTE*)data; - DPNHANDLE hAsync = 0; - HRESULT hr = NET->Send(&desc, 1, dwTimeout, 0, &hAsync, dwFlags | DPNSEND_COALESCE); + net_Statistic.dwBytesSended += size; - // Msg("- Client::SendTo_LL [%d]", size); - if (FAILED(hr)) - { - Msg("! ERROR: Failed to send net-packet, reason: %s", xrDebug::ErrorToString(hr)); - // const char* x = DXGetErrorString9(hr); - string1024 tmp = ""; - DXTRACE_ERR(tmp, hr); - } + // verify + VERIFY(desc.dwBufferSize); + VERIFY(desc.pBufferData); + VERIFY(NET); - // UpdateStatistic(); -} + DPNHANDLE hAsync = 0; + HRESULT hr = NET->Send(&desc, 1, dwTimeout, nullptr, &hAsync, dwFlags | DPNSEND_COALESCE); -void IPureClient::Send(NET_Packet& packet, u32 dwFlags, u32 dwTimeout) -{ - MultipacketSender::SendPacket(packet.B.data, packet.B.count, dwFlags, dwTimeout); -} + // Msg("- Client::SendTo_LL [%d]", size); + if (FAILED(hr)) + { + Msg("! ERROR: Failed to send net-packet, reason: %s", xrDebug::ErrorToString(hr)); + //pcstr x = DXGetErrorString9(hr); + string1024 tmp = ""; + DXTRACE_ERR(tmp, hr); + } -void IPureClient::Flush_Send_Buffer() { MultipacketSender::FlushSendBuffer(0); } -BOOL IPureClient::net_HasBandwidth() -{ - u32 dwTime = TimeGlobal(device_timer); - u32 dwInterval = 0; - if (net_Disconnected) - return FALSE; + // UpdateStatistic(); + } - if (psNET_ClientUpdate != 0) - dwInterval = 1000 / psNET_ClientUpdate; - if (psNET_Flags.test(NETFLAG_MINIMIZEUPDATES)) - dwInterval = 1000; // approx 3 times per second + void IPureClient::Send(NET_Packet& packet, u32 dwFlags, u32 dwTimeout) + { + SendPacket(packet.B.data, packet.B.count, dwFlags, dwTimeout); + } - if (psNET_direct_connect) - { - if (0 != psNET_ClientUpdate && (dwTime - net_Time_LastUpdate) > dwInterval) - { - net_Time_LastUpdate = dwTime; - return TRUE; - } - else - return FALSE; - } - else if (0 != psNET_ClientUpdate && (dwTime - net_Time_LastUpdate) > dwInterval) - { - HRESULT hr; - R_ASSERT(NET); - // check queue for "empty" state - DWORD dwPending = 0; - hr = NET->GetSendQueueInfo(&dwPending, 0, 0); - if (FAILED(hr)) - return FALSE; - - if (dwPending > u32(psNET_ClientPending)) - { - net_Statistic.dwTimesBlocked++; - return FALSE; - }; + void IPureClient::Flush_Send_Buffer() { FlushSendBuffer(0); } - UpdateStatistic(); + bool IPureClient::net_HasBandwidth() + { + u32 dwTime = TimeGlobal(device_timer); + u32 dwInterval = 0; + if (net_Disconnected) + return false; - // ok - net_Time_LastUpdate = dwTime; - return TRUE; - } - return FALSE; -} + if (psNET_ClientUpdate != 0) + dwInterval = 1000 / psNET_ClientUpdate; + if (psNET_Flags.test(NETFLAG_MINIMIZEUPDATES)) + dwInterval = 1000; // approx 3 times per second -void IPureClient::UpdateStatistic() -{ - // Query network statistic for this client - DPN_CONNECTION_INFO CI; - ZeroMemory(&CI, sizeof(CI)); - CI.dwSize = sizeof(CI); - HRESULT hr = NET->GetConnectionInfo(&CI, 0); - if (FAILED(hr)) - return; - - net_Statistic.Update(CI); -} + if (psNET_direct_connect) + { + if (0 != psNET_ClientUpdate && (dwTime - net_Time_LastUpdate) > dwInterval) + { + net_Time_LastUpdate = dwTime; + return true; + } + return false; + } + if (0 != psNET_ClientUpdate && (dwTime - net_Time_LastUpdate) > dwInterval) + { + HRESULT hr; + R_ASSERT(NET); + // check queue for "empty" state + DWORD dwPending = 0; + hr = NET->GetSendQueueInfo(&dwPending, nullptr, 0); + if (FAILED(hr)) + return false; + + if (dwPending > u32(psNET_ClientPending)) + { + net_Statistic.dwTimesBlocked++; + return false; + } + + UpdateStatistic(); + + // ok + net_Time_LastUpdate = dwTime; + return true; + } + return false; + } -void IPureClient::Sync_Thread() -{ - MSYS_PING clPing; + void IPureClient::UpdateStatistic() + { + // Query network statistic for this client + DPN_CONNECTION_INFO CI; + ZeroMemory(&CI, sizeof(CI)); + CI.dwSize = sizeof(CI); + HRESULT hr = NET->GetConnectionInfo(&CI, 0); + if (FAILED(hr)) + return; + + net_Statistic.Update(CI); + } - //***** Ping server - net_DeltaArray.clear(); - R_ASSERT(NET); - for (; NET && !net_Disconnected;) - { - // Waiting for queue empty state - if (net_Syncronised) - break; // Sleep(2000); - else - { - DWORD dwPending = 0; - do - { - R_CHK(NET->GetSendQueueInfo(&dwPending, 0, 0)); - Sleep(1); - } while (dwPending); - } + void IPureClient::Sync_Thread() + { + MSYS_PING clPing; - // Construct message - clPing.sign1 = 0x12071980; - clPing.sign2 = 0x26111975; - clPing.dwTime_ClientSend = TimerAsync(device_timer); + //***** Ping server + net_DeltaArray.clear(); + R_ASSERT(NET); + for (; NET && !net_Disconnected;) + { + // Waiting for queue empty state + if (net_Syncronised) + break; // Sleep(2000); + DWORD dwPending = 0; + do + { + R_CHK(NET->GetSendQueueInfo(&dwPending, nullptr, 0)); + Sleep(1); + } + while (dwPending); + + // Construct message + clPing.sign1 = 0x12071980; + clPing.sign2 = 0x26111975; + clPing.dwTime_ClientSend = TimerAsync(device_timer); + + // Send it + __try + { + DPN_BUFFER_DESC desc; + DPNHANDLE hAsync = 0; + desc.dwBufferSize = sizeof(clPing); + desc.pBufferData = LPBYTE(&clPing); + if (nullptr == NET || net_Disconnected) + break; + + if (FAILED(NET->Send(&desc, 1, 0, nullptr, &hAsync, net_flags(false, false, true)))) + { + Msg("* CLIENT: SyncThread: EXIT. (failed to send - disconnected?)"); + break; + } + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + Msg("* CLIENT: SyncThread: EXIT. (failed to send - disconnected?)"); + break; + } + + // Waiting for reply-packet to arrive + if (!net_Syncronised) + { + u32 old_size = net_DeltaArray.size(); + u32 timeBegin = TimerAsync(device_timer); + while ((net_DeltaArray.size() == old_size) && (TimerAsync(device_timer) - timeBegin < 5000)) + Sleep(1); + + if (net_DeltaArray.size() >= syncSamples) + { + net_Syncronised = true; + net_TimeDelta = net_TimeDelta_Calculated; + //Msg("* CL_TimeSync: DELTA: %d", net_TimeDelta); + } + } + } + } - // Send it - __try - { - DPN_BUFFER_DESC desc; - DPNHANDLE hAsync = 0; - desc.dwBufferSize = sizeof(clPing); - desc.pBufferData = LPBYTE(&clPing); - if (0 == NET || net_Disconnected) - break; - - if (FAILED(NET->Send(&desc, 1, 0, 0, &hAsync, net_flags(FALSE, FALSE, TRUE)))) - { - Msg("* CLIENT: SyncThread: EXIT. (failed to send - disconnected?)"); - break; - } - } - __except (EXCEPTION_EXECUTE_HANDLER) - { - Msg("* CLIENT: SyncThread: EXIT. (failed to send - disconnected?)"); - break; - } + void IPureClient::Sync_Average() + { + //***** Analyze results + s64 summary_delta = 0; + s32 size = net_DeltaArray.size(); + u32* I = net_DeltaArray.begin(); + u32* E = I + size; + for (; I != E; I++) + summary_delta += *((int*)I); + + s64 frac = s64(summary_delta) % s64(size); + if (frac < 0) + frac = -frac; + summary_delta /= s64(size); + if (frac > s64(size / 2)) + summary_delta += (summary_delta < 0) ? -1 : 1; + net_TimeDelta_Calculated = s32(summary_delta); + net_TimeDelta = (net_TimeDelta * 5 + net_TimeDelta_Calculated) / 6; + // Msg("* CLIENT: d(%d), dc(%d), s(%d)",net_TimeDelta,net_TimeDelta_Calculated,size); + } - // Waiting for reply-packet to arrive - if (!net_Syncronised) - { - u32 old_size = net_DeltaArray.size(); - u32 timeBegin = TimerAsync(device_timer); - while ((net_DeltaArray.size() == old_size) && (TimerAsync(device_timer) - timeBegin < 5000)) - Sleep(1); - - if (net_DeltaArray.size() >= syncSamples) - { - net_Syncronised = TRUE; - net_TimeDelta = net_TimeDelta_Calculated; - // Msg ("* CL_TimeSync: DELTA: %d",net_TimeDelta); - } - } - } -} + void sync_thread(void* P) + { + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); + IPureClient* C = (IPureClient*)P; + C->Sync_Thread(); + } -void IPureClient::Sync_Average() -{ - //***** Analyze results - s64 summary_delta = 0; - s32 size = net_DeltaArray.size(); - u32* I = net_DeltaArray.begin(); - u32* E = I + size; - for (; I != E; I++) - summary_delta += *((int*)I); - - s64 frac = s64(summary_delta) % s64(size); - if (frac < 0) - frac = -frac; - summary_delta /= s64(size); - if (frac > s64(size / 2)) - summary_delta += (summary_delta < 0) ? -1 : 1; - net_TimeDelta_Calculated = s32(summary_delta); - net_TimeDelta = (net_TimeDelta * 5 + net_TimeDelta_Calculated) / 6; - // Msg("* CLIENT: d(%d), dc(%d), s(%d)",net_TimeDelta,net_TimeDelta_Calculated,size); -} + void IPureClient::net_Syncronize() + { + net_Syncronised = false; + net_DeltaArray.clear(); + thread_spawn(sync_thread, "network-time-sync", 0, this); + } -void sync_thread(void* P) -{ - SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); - IPureClient* C = (IPureClient*)P; - C->Sync_Thread(); -} -void IPureClient::net_Syncronize() -{ - net_Syncronised = FALSE; - net_DeltaArray.clear(); - thread_spawn(sync_thread, "network-time-sync", 0, this); -} + bool IPureClient::net_isDisconnected() const { return net_Disconnected; } -void IPureClient::ClearStatistic() { net_Statistic.Clear(); } -BOOL IPureClient::net_IsSyncronised() { return net_Syncronised; } + void IPureClient::ClearStatistic() { net_Statistic.Clear(); } + bool IPureClient::net_IsSyncronised() { return net_Syncronised; } -IPureClient::HOST_NODE::HOST_NODE() : - pdpAppDesc(new DPN_APPLICATION_DESC), - pHostAddress(0) -{} + IPureClient::HOST_NODE::HOST_NODE() : + pdpAppDesc(new DPN_APPLICATION_DESC), + pHostAddress(nullptr) {} -IPureClient::HOST_NODE::HOST_NODE(const HOST_NODE& rhs) : - pdpAppDesc(new DPN_APPLICATION_DESC) -{ - *pdpAppDesc = *rhs.pdpAppDesc; - pHostAddress = rhs.pHostAddress; - dpSessionName = rhs.dpSessionName; -} + IPureClient::HOST_NODE::HOST_NODE(const HOST_NODE& rhs) : + pdpAppDesc(new DPN_APPLICATION_DESC) + { + *pdpAppDesc = *rhs.pdpAppDesc; + pHostAddress = rhs.pHostAddress; + dpSessionName = rhs.dpSessionName; + } -IPureClient::HOST_NODE::HOST_NODE(HOST_NODE&& rhs) throw() : - pdpAppDesc(rhs.pdpAppDesc) -{ - pHostAddress = rhs.pHostAddress; - dpSessionName.swap(rhs.dpSessionName); - rhs.pdpAppDesc = 0; - rhs.pHostAddress = 0; -} + IPureClient::HOST_NODE::HOST_NODE(HOST_NODE&& rhs) throw() : + pdpAppDesc(rhs.pdpAppDesc) + { + pHostAddress = rhs.pHostAddress; + dpSessionName.swap(rhs.dpSessionName); + rhs.pdpAppDesc = nullptr; + rhs.pHostAddress = nullptr; + } -IPureClient::HOST_NODE::~HOST_NODE() throw() -{ delete pdpAppDesc; } + IPureClient::HOST_NODE::~HOST_NODE() throw() + { + delete pdpAppDesc; + } #include #include -bool IPureClient::GetServerAddress(ip_address& pAddress, DWORD* pPort) -{ - *pPort = 0; - if (!net_Address_server) - return false; - - WCHAR wstrHostname[2048] = {0}; - DWORD dwHostNameSize = sizeof(wstrHostname); - DWORD dwHostNameDataType = DPNA_DATATYPE_STRING; - CHK_DX( - net_Address_server->GetComponentByName(DPNA_KEY_HOSTNAME, wstrHostname, &dwHostNameSize, &dwHostNameDataType)); - - string2048 HostName; - CHK_DX(WideCharToMultiByte(CP_ACP, 0, wstrHostname, -1, HostName, sizeof(HostName), 0, 0)); - - hostent* pHostEnt = gethostbyname(HostName); - char* localIP; - localIP = inet_ntoa(*(struct in_addr*)*pHostEnt->h_addr_list); - pHostEnt = gethostbyname(pHostEnt->h_name); - localIP = inet_ntoa(*(struct in_addr*)*pHostEnt->h_addr_list); - pAddress.set(localIP); - - //. pAddress[0] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_net; - //. pAddress[1] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_host; - //. pAddress[2] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_lh; - //. pAddress[3] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_impno; - - DWORD dwPort = 0; - DWORD dwPortSize = sizeof(dwPort); - DWORD dwPortDataType = DPNA_DATATYPE_DWORD; - CHK_DX(net_Address_server->GetComponentByName(DPNA_KEY_PORT, &dwPort, &dwPortSize, &dwPortDataType)); - *pPort = dwPort; - - return true; -}; + + bool IPureClient::GetServerAddress(ip_address& pAddress, DWORD* pPort) + { + *pPort = 0; + if (!net_Address_server) + return false; + + WCHAR wstrHostname[2048] = {0}; + DWORD dwHostNameSize = sizeof(wstrHostname); + DWORD dwHostNameDataType = DPNA_DATATYPE_STRING; + CHK_DX( + net_Address_server->GetComponentByName(DPNA_KEY_HOSTNAME, wstrHostname, &dwHostNameSize, &dwHostNameDataType)); + + string2048 HostName; + CHK_DX(WideCharToMultiByte(CP_ACP, 0, wstrHostname, -1, HostName, sizeof(HostName), nullptr, nullptr)); + + hostent* pHostEnt = gethostbyname(HostName); + pstr localIP = inet_ntoa(*(struct in_addr*)*pHostEnt->h_addr_list); + pHostEnt = gethostbyname(pHostEnt->h_name); + localIP = inet_ntoa(*(struct in_addr*)*pHostEnt->h_addr_list); + pAddress.set(localIP); + + //pAddress[0] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_net; + //pAddress[1] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_host; + //pAddress[2] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_lh; + //pAddress[3] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_impno; + + DWORD dwPort = 0; + DWORD dwPortSize = sizeof(dwPort); + DWORD dwPortDataType = DPNA_DATATYPE_DWORD; + CHK_DX(net_Address_server->GetComponentByName(DPNA_KEY_PORT, &dwPort, &dwPortSize, &dwPortDataType)); + *pPort = dwPort; + + return true; + }; diff --git a/src/xrNetServer/NET_Client.h b/src/xrNetServer/NET_Client.h index 3e6f7f3e3b1..1ee3cfe8c03 100644 --- a/src/xrNetServer/NET_Client.h +++ b/src/xrNetServer/NET_Client.h @@ -1,6 +1,6 @@ #pragma once -#include "net_shared.h" +#include "NET_Shared.h" #include "NET_Common.h" #include "xrCommon/xr_deque.h" #include "xrCommon/xr_vector.h" @@ -21,8 +21,8 @@ class XRNETSERVER_API INetQueue NET_Packet* Create(const NET_Packet& _other); NET_Packet* Retreive(); void Release(); - inline void Lock() { cs.Enter(); }; - inline void Unlock() { cs.Leave(); }; + void Lock() { cs.Enter(); } + void Unlock() { cs.Leave(); } }; //============================================================================== @@ -30,9 +30,9 @@ class XRNETSERVER_API INetQueue // DPlay extern "C" { -typedef struct _DPN_APPLICATION_DESC DPN_APPLICATION_DESC; -struct IDirectPlay8Address; -struct IDirectPlay8Client; + typedef struct _DPN_APPLICATION_DESC DPN_APPLICATION_DESC; + struct IDirectPlay8Address; + struct IDirectPlay8Client; } class XRNETSERVER_API IPureClient : private MultipacketReciever, private MultipacketSender @@ -43,6 +43,7 @@ class XRNETSERVER_API IPureClient : private MultipacketReciever, private Multipa EnmConnectionWait = -1, EnmConnectionCompleted = 1 }; + friend void sync_thread(void*); protected: @@ -56,13 +57,14 @@ class XRNETSERVER_API IPureClient : private MultipacketReciever, private Multipa DPN_APPLICATION_DESC* pdpAppDesc; IDirectPlay8Address* pHostAddress; shared_str dpSessionName; + private: void operator=(const HOST_NODE&) = delete; }; + GameDescriptionData m_game_description; CTimer* device_timer; -protected: IDirectPlay8Client* NET; IDirectPlay8Address* net_Address_device; IDirectPlay8Address* net_Address_server; @@ -73,8 +75,8 @@ class XRNETSERVER_API IPureClient : private MultipacketReciever, private Multipa NET_Compressor net_Compressor; ConnectionState net_Connected; - BOOL net_Syncronised; - BOOL net_Disconnected; + bool net_Syncronised; + bool net_Disconnected; INetQueue net_Queue; IClientStatistic net_Statistic; @@ -87,7 +89,7 @@ class XRNETSERVER_API IPureClient : private MultipacketReciever, private Multipa void Sync_Thread(); void Sync_Average(); - void SetClientID(ClientID const& local_client) { net_ClientID = local_client; }; + void SetClientID(ClientID const& local_client) { net_ClientID = local_client; } IC virtual void SendTo_LL(void* data, u32 size, u32 dwFlags = 0x0008 /*DPNSEND_GUARANTEED*/, u32 dwTimeout = 0); public: @@ -95,52 +97,53 @@ class XRNETSERVER_API IPureClient : private MultipacketReciever, private Multipa virtual ~IPureClient(); HRESULT net_Handler(u32 dwMessageType, PVOID pMessage); - BOOL Connect(LPCSTR server_name); + bool Connect(pcstr server_name); void Disconnect(); void net_Syncronize(); - BOOL net_isCompleted_Connect() { return net_Connected == EnmConnectionCompleted; } - BOOL net_isFails_Connect() { return net_Connected == EnmConnectionFails; } - BOOL net_isCompleted_Sync() { return net_Syncronised; } - BOOL net_isDisconnected() { return net_Disconnected; } - IC GameDescriptionData const& get_net_DescriptionData() const { return m_game_description; } - LPCSTR net_SessionName() { return *(net_Hosts.front().dpSessionName); } + bool net_isCompleted_Connect() const { return net_Connected == EnmConnectionCompleted; } + bool net_isFails_Connect() const { return net_Connected == EnmConnectionFails; } + bool net_isCompleted_Sync() const { return net_Syncronised; } + bool net_isDisconnected() const; + GameDescriptionData const& get_net_DescriptionData() const { return m_game_description; } + pcstr net_SessionName() { return *net_Hosts.front().dpSessionName; } // receive - IC void StartProcessQueue() { net_Queue.Lock(); }; // WARNING ! after Start mast be End !!! <- - IC virtual NET_Packet* net_msg_Retreive() { return net_Queue.Retreive(); }; // | - IC void net_msg_Release() { net_Queue.Release(); }; // | - IC void EndProcessQueue() { net_Queue.Unlock(); }; // <- + void StartProcessQueue() { net_Queue.Lock(); } // WARNING ! after Start must be End !!! <- + virtual NET_Packet* net_msg_Retreive() { return net_Queue.Retreive(); } // | + void net_msg_Release() { net_Queue.Release(); } // | + void EndProcessQueue() { net_Queue.Unlock(); } // <- // send virtual void Send(NET_Packet& P, u32 dwFlags = 0x0008 /*DPNSEND_GUARANTEED*/, u32 dwTimeout = 0); virtual void Flush_Send_Buffer(); virtual void OnMessage(void* data, u32 size); - virtual void OnInvalidHost(){}; - virtual void OnInvalidPassword(){}; - virtual void OnSessionFull(){}; - virtual void OnConnectRejected(){}; - BOOL net_HasBandwidth(); + virtual void OnInvalidHost() {} + virtual void OnInvalidPassword() {} + virtual void OnSessionFull() {} + virtual void OnConnectRejected() {} + bool net_HasBandwidth(); void ClearStatistic(); IClientStatistic& GetStatistic() { return net_Statistic; } void UpdateStatistic(); - ClientID const& GetClientID() { return net_ClientID; }; + ClientID const& GetClientID() const { return net_ClientID; } bool GetServerAddress(ip_address& pAddress, DWORD* pPort); // time management - IC u32 timeServer() { return TimeGlobal(device_timer) + net_TimeDelta + net_TimeDelta_User; } - IC u32 timeServer_Async() { return TimerAsync(device_timer) + net_TimeDelta + net_TimeDelta_User; } - IC u32 timeServer_Delta() { return net_TimeDelta; } - IC void timeServer_UserDelta(s32 d) { net_TimeDelta_User = d; } + u32 timeServer() const { return TimeGlobal(device_timer) + net_TimeDelta + net_TimeDelta_User; } + u32 timeServer_Async() const { return TimerAsync(device_timer) + net_TimeDelta + net_TimeDelta_User; } + u32 timeServer_Delta() const { return net_TimeDelta; } + void timeServer_UserDelta(s32 d) { net_TimeDelta_User = d; } IC void timeServer_Correct(u32 sv_time, u32 cl_time); - virtual BOOL net_IsSyncronised(); + virtual bool net_IsSyncronised(); - virtual LPCSTR GetMsgId2Name(u16 ID) { return ""; } - virtual void OnSessionTerminate(LPCSTR reason){}; + virtual pcstr GetMsgId2Name(u16 ID) { return ""; } + virtual void OnSessionTerminate(pcstr reason) {} virtual bool TestLoadBEClient() { return false; } + private: ClientID net_ClientID; - virtual void _Recieve(const void* data, u32 data_size, u32 param); - virtual void _SendTo_LL(const void* data, u32 size, u32 flags, u32 timeout); + void _Recieve(const void* data, u32 data_size, u32 param) override; + void _SendTo_LL(const void* data, u32 size, u32 flags, u32 timeout) override; }; diff --git a/src/xrNetServer/NET_Common.cpp b/src/xrNetServer/NET_Common.cpp index 39c7181a7d3..23e7f360fdc 100644 --- a/src/xrNetServer/NET_Common.cpp +++ b/src/xrNetServer/NET_Common.cpp @@ -3,41 +3,42 @@ #include "NET_Common.h" #include "NET_Messages.h" -/*#ifdef DEBUG -void PrintParsedPacket(const char* message, u16 message_type, const void* packet_data, u32 packet_size) +/* +#ifdef DEBUG +void PrintParsedPacket(pcstr message, u16 message_type, const void* packet_data, u32 packet_size) { - NET_Packet tNetPacket; - tNetPacket.construct ( packet_data, packet_size ); + NET_Packet tNetPacket; + tNetPacket.construct(packet_data, packet_size); u16 msg_type; - tNetPacket.r_begin (msg_type); + tNetPacket.r_begin(msg_type); if (msg_type == message_type) { if (message_type == 1) //M_SPAWN { - shared_str s_name; - tNetPacket.r_stringZ (s_name ); - - string256 temp; - tNetPacket.r_stringZ (temp); - u8 temp_gt; - tNetPacket.r_u8 (temp_gt ); - u8 s_RP; - tNetPacket.r_u8 (s_RP ); - Fvector o_Position, o_Angle; - tNetPacket.r_vec3 (o_Position ); - tNetPacket.r_vec3 (o_Angle ); - u16 RespawnTime, ID; - tNetPacket.r_u16 (RespawnTime ); - tNetPacket.r_u16 (ID ); + shared_str s_name; + tNetPacket.r_stringZ(s_name); + + string256 temp; + tNetPacket.r_stringZ(temp); + u8 temp_gt; + tNetPacket.r_u8(temp_gt); + u8 s_RP; + tNetPacket.r_u8(s_RP); + Fvector o_Position, o_Angle; + tNetPacket.r_vec3(o_Position); + tNetPacket.r_vec3(o_Angle); + u16 RespawnTime, ID; + tNetPacket.r_u16(RespawnTime); + tNetPacket.r_u16(ID); Msg("%s M_SPAWN for [%s]-[%d]", message, s_name.c_str(), ID); - } else - { - Msg("%s NOT_IMPLEMENTED_PRINT type[%d]", message, message_type); } + else + Msg("%s NOT_IMPLEMENTED_PRINT type[%d]", message, message_type); } } -#endif*/ +#endif +*/ //============================================================================== #pragma pack(push) @@ -62,29 +63,31 @@ void MultipacketSender::SendPacket(const void* packet_data, u32 packet_sz, u32 f { _buf_cs.Enter(); - // PrintParsedPacket("-- LL Sending:", 1, packet_data, packet_sz); + //PrintParsedPacket("-- LL Sending:", 1, packet_data, packet_sz); Buffer* buf = &_buf; switch (psNET_GuaranteedPacketMode) { - case NET_GUARANTEEDPACKET_IGNORE: { flags &= ~DPNSEND_GUARANTEED; + case NET_GUARANTEEDPACKET_IGNORE: + { + flags &= ~DPNSEND_GUARANTEED; } - break; + break; case NET_GUARANTEEDPACKET_SEPARATE: { if (flags & DPNSEND_GUARANTEED) buf = &_gbuf; } - break; + break; } - u32 old_flags = (buf->last_flags) & (~DPNSEND_IMMEDIATELLY); + u32 old_flags = buf->last_flags & ~DPNSEND_IMMEDIATELLY; u32 new_flags = flags & (~DPNSEND_IMMEDIATELLY); - if ((buf->buffer.B.count + packet_sz + sizeof(u16) >= NET_PacketSizeLimit) || (old_flags != new_flags) || - (flags & DPNSEND_IMMEDIATELLY)) + if (buf->buffer.B.count + packet_sz + sizeof(u16) >= NET_PacketSizeLimit || old_flags != new_flags || + flags & DPNSEND_IMMEDIATELLY) { _FlushSendBuffer(timeout, buf); } @@ -129,12 +132,12 @@ void MultipacketSender::_FlushSendBuffer(u32 timeout, Buffer* buf) R_ASSERT(comp_sz < 65535); comp_sz = Compressor.Compress(packet_data + sizeof(MultipacketHeader), - sizeof(packet_data) - sizeof(MultipacketHeader), buf->buffer.B.data, buf->buffer.B.count); + sizeof(packet_data) - sizeof(MultipacketHeader), buf->buffer.B.data, buf->buffer.B.count); header->tag = NET_TAG_MERGED; header->unpacked_size = (u16)buf->buffer.B.count; -// dump/log if needed + // dump/log if needed #if NET_LOG_PACKETS Msg("#send %smulti-packet %u flags= %08X", (buf->last_flags & DPNSEND_IMMEDIATELLY) ? "IMMEDIATE " : "", @@ -207,7 +210,7 @@ void MultipacketReciever::RecievePacket(const void* packet_data, u32 packet_sz, while (processed_sz < header->unpacked_size) { - u32 size = (is_multi_packet) ? u32(*((u16*)dat)) : header->unpacked_size; + u32 size = is_multi_packet ? u32(*(u16*)dat) : header->unpacked_size; if (is_multi_packet) dat += sizeof(u16); @@ -216,7 +219,7 @@ void MultipacketReciever::RecievePacket(const void* packet_data, u32 packet_sz, Msg(" packet %u", size); #endif - // PrintParsedPacket("-- LL Receiving:", 1, dat, size); + //PrintParsedPacket("-- LL Receiving:", 1, dat, size); _Recieve(dat, size, param); diff --git a/src/xrNetServer/NET_Common.h b/src/xrNetServer/NET_Common.h index 725c411f490..6f57f1c2ceb 100644 --- a/src/xrNetServer/NET_Common.h +++ b/src/xrNetServer/NET_Common.h @@ -1,6 +1,7 @@ #pragma once #ifndef _INCDEF_NETCOMMON_H_ #define _INCDEF_NETCOMMON_H_ + //============================================================================== struct GameDescriptionData diff --git a/src/xrNetServer/NET_Compressor.cpp b/src/xrNetServer/NET_Compressor.cpp index 8825892cc05..70a9c9cc975 100644 --- a/src/xrNetServer/NET_Compressor.cpp +++ b/src/xrNetServer/NET_Compressor.cpp @@ -2,7 +2,6 @@ // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" -#pragma hdrstop #include "NET_Common.h" #include "NET_Compressor.h" @@ -29,8 +28,8 @@ #if 1 // def DEBUG // static FILE* OriginalTrafficDump = NULL; // static FILE* CompressedTrafficDump = NULL; -static FILE* RawTrafficDump = NULL; -static FILE* CompressionDump = NULL; +static FILE* RawTrafficDump = nullptr; +static FILE* CompressionDump = nullptr; #endif // DEBUG #define NOWARN @@ -48,45 +47,45 @@ static FILE* CompressionDump = NULL; // c is written as first byte in the datastream // one could do without c, but then you have an additional if // per outputbyte. -void NET_Compressor::start_encoding ( BYTE* dest, u32 header_size ) +void NET_Compressor::start_encoding(BYTE* dest, u32 header_size) { - dest += header_size-1; - RNGC.low = 0; // Full code range - RNGC.range = PPM_TOP_VALUE; - RNGC.buffer = 0; - RNGC.help = 0; // No bytes to follow - RNGC.bytecount = 0; - RNGC.ptr = dest; + dest += header_size - 1; + RNGC.low = 0; // Full code range + RNGC.range = PPM_TOP_VALUE; + RNGC.buffer = 0; + RNGC.help = 0; // No bytes to follow + RNGC.bytecount = 0; + RNGC.ptr = dest; } // I do the normalization before I need a defined state instead of // after messing it up. This simplifies starting and ending. -void NET_Compressor::encode_normalize ( ) +void NET_Compressor::encode_normalize() { - while( RNGC.range <= PPM_BOTTOM_VALUE ) // do we need renormalisation? + while (RNGC.range <= PPM_BOTTOM_VALUE) // do we need renormalisation? { - if( RNGC.low < code_value(0xff) << SHIFT_BITS ) // no carry possible --> output + if (RNGC.low < code_value(0xff) << SHIFT_BITS) // no carry possible --> output { - RNGC.byte_out( RNGC.buffer ); - for( ; RNGC.help; RNGC.help--) + RNGC.byte_out(RNGC.buffer); + for (; RNGC.help; RNGC.help--) RNGC.byte_out(0xff); - RNGC.buffer = (BYTE)(RNGC.low >> SHIFT_BITS); + RNGC.buffer = (BYTE)(RNGC.low >> SHIFT_BITS); } - else if( RNGC.low & PPM_TOP_VALUE ) // carry now, no future carry + else if (RNGC.low & PPM_TOP_VALUE) // carry now, no future carry { - RNGC.byte_out( RNGC.buffer+1 ); - for(; RNGC.help; RNGC.help--) + RNGC.byte_out(RNGC.buffer + 1); + for (; RNGC.help; RNGC.help--) RNGC.byte_out(0); - RNGC.buffer = (BYTE)(RNGC.low >> SHIFT_BITS); + RNGC.buffer = (BYTE)(RNGC.low >> SHIFT_BITS); } - else // passes on a potential carry + else // passes on a potential carry { RNGC.help++; } - RNGC.range <<= 8; - RNGC.low = (RNGC.low<<8) & (PPM_TOP_VALUE-1); - RNGC.bytecount ++; + RNGC.range <<= 8; + RNGC.low = (RNGC.low << 8) & (PPM_TOP_VALUE - 1); + RNGC.bytecount ++; } } @@ -95,86 +94,86 @@ void NET_Compressor::encode_normalize ( ) // lt_f is the lower end (frequency sum of < symbols) // tot_f is the total interval length (total frequency sum) // or (faster): tot_f = (code_value)1<> shift; - code_value tmp = r * lt_f; + code_value r = RNGC.range >> shift; + code_value tmp = r * lt_f; RNGC.low += tmp; - if ((lt_f+sy_f) >> shift) RNGC.range -= tmp; - else RNGC.range = r * sy_f; + if ((lt_f + sy_f) >> shift) RNGC.range -= tmp; + else RNGC.range = r * sy_f; } // Finish encoding // actually not that many bytes need to be output, but who // cares. I output them because decode will read them :) // the return value is the number of bytes written -u32 NET_Compressor::done_encoding ( ) +u32 NET_Compressor::done_encoding() { - encode_normalize(); // now we have a normalized state + encode_normalize(); // now we have a normalized state - RNGC.bytecount += 3; + RNGC.bytecount += 3; - u32 tmp = ((RNGC.low & (PPM_BOTTOM_VALUE-1)) < ((RNGC.bytecount&0xffffffL)>>1)) - ? (RNGC.low >> SHIFT_BITS) - : (RNGC.low >> SHIFT_BITS) + 1; + u32 tmp = ((RNGC.low & (PPM_BOTTOM_VALUE - 1)) < ((RNGC.bytecount & 0xffffffL) >> 1)) + ? (RNGC.low >> SHIFT_BITS) + : (RNGC.low >> SHIFT_BITS) + 1; - if( tmp > 0xff ) // we have a carry + if (tmp > 0xff) // we have a carry { - RNGC.byte_out( RNGC.buffer+1 ); + RNGC.byte_out(RNGC.buffer + 1); - for( ; RNGC.help; RNGC.help-- ) + for (; RNGC.help; RNGC.help--) RNGC.byte_out(0); } - else // no carry + else // no carry { - RNGC.byte_out( RNGC.buffer ); + RNGC.byte_out(RNGC.buffer); - for( ; RNGC.help; RNGC.help-- ) + for (; RNGC.help; RNGC.help--) RNGC.byte_out(0xff); } - RNGC.byte_out( (BYTE)(tmp & 0xff) ); - RNGC.byte_out( 0 ); + RNGC.byte_out((BYTE)(tmp & 0xff)); + RNGC.byte_out(0); return RNGC.bytecount; } // Start the decoder -int NET_Compressor::start_decoding ( BYTE* src, u32 header_size ) +int NET_Compressor::start_decoding(BYTE* src, u32 header_size) { - src += header_size; - RNGC.ptr = src; + src += header_size; + RNGC.ptr = src; RNGC.buffer = RNGC.byte_in(); - RNGC.low = RNGC.buffer >> (8-EXTRA_BITS); - RNGC.range = (code_value)1 << EXTRA_BITS; + RNGC.low = RNGC.buffer >> (8 - EXTRA_BITS); + RNGC.range = (code_value)1 << EXTRA_BITS; return 0; } -void NET_Compressor::decode_normalize ( ) +void NET_Compressor::decode_normalize() { - while( RNGC.range <= PPM_BOTTOM_VALUE ) + while (RNGC.range <= PPM_BOTTOM_VALUE) { - RNGC.low = (RNGC.low<<8) | ((RNGC.buffer<> (8-EXTRA_BITS); - RNGC.range <<= 8; + RNGC.low = (RNGC.low << 8) | ((RNGC.buffer << EXTRA_BITS) & 0xff); + RNGC.buffer = RNGC.byte_in(); + RNGC.low |= RNGC.buffer >> (8 - EXTRA_BITS); + RNGC.range <<= 8; } } @@ -183,24 +182,24 @@ void NET_Compressor::decode_normalize ( ) // tot_f is the total frequency // or: totf is (code_value)1<=tot_f) ? (tot_f-1) : (tmp); + return (tmp >= tot_f) ? (tot_f - 1) : (tmp); } -NET_Compressor::freq NET_Compressor::decode_culshift ( freq shift ) +NET_Compressor::freq NET_Compressor::decode_culshift(freq shift) { decode_normalize(); - RNGC.help = RNGC.range>>shift; + RNGC.help = RNGC.range >> shift; - freq tmp = RNGC.low/RNGC.help; + freq tmp = RNGC.low / RNGC.help; - return (tmp>>shift) ? ((code_value(1)<> shift) ? ((code_value(1) << shift) - 1) : (tmp); } @@ -208,72 +207,71 @@ NET_Compressor::freq NET_Compressor::decode_culshift ( freq shift ) // sy_f is the interval length (frequency of the symbol) // lt_f is the lower end (frequency sum of < symbols) // tot_f is the total interval length (total frequency sum) -void NET_Compressor::decode_update ( freq sy_f, freq lt_f, freq tot_f ) +void NET_Compressor::decode_update(freq sy_f, freq lt_f, freq tot_f) { code_value tmp = RNGC.help * lt_f; - RNGC.low -= tmp; + RNGC.low -= tmp; - if( lt_f + sy_f < tot_f) RNGC.range = RNGC.help * sy_f; - else RNGC.range -= tmp; + if (lt_f + sy_f < tot_f) RNGC.range = RNGC.help * sy_f; + else RNGC.range -= tmp; } // Decode a byte/short without modelling -BYTE NET_Compressor::decode_byte ( ) +BYTE NET_Compressor::decode_byte() { - u32 tmp =decode_culshift( 8 ); + u32 tmp = decode_culshift(8); - decode_update( 1, tmp, (freq)1<<8 ); + decode_update(1, tmp, (freq)1 << 8); return BYTE(tmp); } -u16 NET_Compressor::decode_short ( ) +u16 NET_Compressor::decode_short() { - u32 tmp = decode_culshift( 16 ); + u32 tmp = decode_culshift(16); - decode_update( 1, tmp, (freq)1<<16 ); + decode_update(1, tmp, (freq)1 << 16); return u16(tmp); } // Finish decoding // rc is the range coder to be used -void NET_Compressor::done_decoding ( ) +void NET_Compressor::done_decoding() { - decode_normalize(); // normalize to use up all bytes + decode_normalize(); // normalize to use up all bytes } */ ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// - -NET_Compressor::NET_Compressor() #ifdef CONFIG_PROFILE_LOCKS - : CS(MUTEX_PROFILE_ID(NET_Compressor)) +NET_Compressor::NET_Compressor() : CS(MUTEX_PROFILE_ID(NET_Compressor)) +#else +NET_Compressor::NET_Compressor() #endif // CONFIG_PROFILE_LOCKS -{ -} +{} NET_Compressor::~NET_Compressor() { #if 1 // def DEBUG - // if( strstr(Core.Params,"-dump_traffic") ) - // { - // fclose( OriginalTrafficDump ); - // fclose( CompressedTrafficDump ); - // } + //if (strstr(Core.Params, "-dump_traffic")) + //{ + // fclose(OriginalTrafficDump); + // fclose(CompressedTrafficDump); + //} if (CompressionDump) { fclose(CompressionDump); - CompressionDump = NULL; + CompressionDump = nullptr; } if (RawTrafficDump) { fclose(RawTrafficDump); - RawTrafficDump = NULL; + RawTrafficDump = nullptr; } #endif // DEBUG } @@ -281,20 +279,20 @@ NET_Compressor::~NET_Compressor() /* void NET_Compressor::Initialize () { - CS.Enter (); + CS.Enter(); #if 1//def DEBUG - if( strstr(Core.Params,"-dump_traffic") ) + if (strstr(Core.Params, "-dump_traffic")) { - OriginalTrafficDump = fopen( "x:/network_out_original.dat", "wb" ); - CompressedTrafficDump = fopen( "x:/network_out_compressed.dat", "wb" ); + OriginalTrafficDump = fopen("x:/network_out_original.dat", "wb"); + CompressedTrafficDump = fopen("x:/network_out_compressed.dat", "wb"); } #endif // DEBUG - CS.Leave (); + CS.Leave(); }*/ -u16 NET_Compressor::compressed_size(const u32& count) +u16 NET_Compressor::compressed_size(const u32& count) const { #if NET_USE_COMPRESSION @@ -306,12 +304,10 @@ u16 NET_Compressor::compressed_size(const u32& count) R_ASSERT(result <= u32(u16(-1))); - return ((u16)result); + return (u16)result; #else - - return ((u16)count); - + return (u16)count; #endif // #if NET_USE_COMPRESSION } @@ -320,7 +316,7 @@ XRNETSERVER_API BOOL g_net_compressor_gather_stats = FALSE; u16 NET_Compressor::Compress(BYTE* dest, const u32& dest_size, BYTE* src, const u32& count) { - SCompressorStats::SStatPacket* _p = NULL; + SCompressorStats::SStatPacket* _p = nullptr; bool b_compress_packet = (count > 36); if (g_net_compressor_gather_stats && b_compress_packet) { @@ -333,11 +329,11 @@ u16 NET_Compressor::Compress(BYTE* dest, const u32& dest_size, BYTE* src, const VERIFY(src); VERIFY(count); -#if 1 // def DEBUG +#if 0 // def DEBUG if (strstr(Core.Params, "-dump_traffic")) { - // fwrite( src,count,1,OriginalTrafficDump ); - // fflush( OriginalTrafficDump ); + fwrite(src, count, 1, OriginalTrafficDump); + fflush(OriginalTrafficDump); } #endif // DEBUG @@ -411,26 +407,24 @@ u16 NET_Compressor::Compress(BYTE* dest, const u32& dest_size, BYTE* src, const if (g_net_compressor_gather_stats && b_compress_packet) _p->compressed_size += compressed_size; -#if 1 // def DEBUG -// if( strstr(Core.Params,"-dump_traffic")) -// { -// fwrite(dest,compressed_size,1,CompressedTrafficDump); -// fflush(CompressedTrafficDump); -// } +#if 0 // def DEBUG + if (strstr(Core.Params, "-dump_traffic")) + { + fwrite(dest, compressed_size, 1, CompressedTrafficDump); + fflush(CompressedTrafficDump); + } #endif // DEBUG -#ifdef DEBUG -/* - BYTE *src_back = (BYTE*)_alloca(count); - Decompress (src_back,count,dest,compressed_size); - BYTE *I = src_back; - BYTE *E = src_back + count; - BYTE *J = src; - for ( ; I != E; ++I, ++J) - VERIFY (*I == *J); +#if 0 //def DEBUG + BYTE* src_back = (BYTE*)_alloca(count); + Decompress(src_back, count, dest, compressed_size); + BYTE* I = src_back; + BYTE* E = src_back + count; + BYTE* J = src; + for (; I != E; ++I , ++J) + VERIFY (*I == *J); -*/ -// CS.Leave (); + CS.Leave(); #endif // DEBUG return (u16(compressed_size)); @@ -483,7 +477,7 @@ u16 NET_Compressor::Decompress(BYTE* dest, const u32& dest_size, BYTE* src, cons #if NET_USE_COMPRESSION_CRC u32 crc = crc32(src + offset, count); - // Msg ("decompressed %d -> ? [0x%08x]",count,crc); + //Msg("decompressed %d -> ? [0x%08x]", count, crc); if (crc != *((u32*)(src + 1))) Msg("!CRC mismatch"); @@ -494,15 +488,15 @@ u16 NET_Compressor::Decompress(BYTE* dest, const u32& dest_size, BYTE* src, cons u32 uncompressed_size = DECODE(dest, dest_size, src + offset, count - offset); CS.Leave(); - return (u16(uncompressed_size)); + return (u16)uncompressed_size; #endif // !NET_USE_COMPRESSION } -void NET_Compressor::DumpStats(bool brief) +void NET_Compressor::DumpStats(bool brief) const { - xr_map::const_iterator it = m_stats.m_packets.begin(); - xr_map::const_iterator it_e = m_stats.m_packets.end(); + auto cit = m_stats.m_packets.cbegin(); + auto cit_e = m_stats.m_packets.cend(); Msg("---------NET_Compressor::DumpStats-----------"); @@ -514,14 +508,14 @@ void NET_Compressor::DumpStats(bool brief) u32 total_hits = 0; u32 unlucky_hits = 0; - for (; it != it_e; ++it) + for (; cit != cit_e; ++cit) { - total_hits += it->second.hit_count; - unlucky_hits += it->second.unlucky_attempts; + total_hits += cit->second.hit_count; + unlucky_hits += cit->second.unlucky_attempts; if (!brief) { - Msg("size[%d] count[%d] unlucky[%d] avg_c[%d]", it->first, it->second.hit_count, - it->second.unlucky_attempts, iFloor(float(it->second.compressed_size) / float(it->second.hit_count))); + Msg("size[%d] count[%d] unlucky[%d] avg_c[%d]", cit->first, cit->second.hit_count, + cit->second.unlucky_attempts, iFloor(float(cit->second.compressed_size) / float(cit->second.hit_count))); } } Msg("total [%d]", total_hits); diff --git a/src/xrNetServer/NET_Compressor.h b/src/xrNetServer/NET_Compressor.h index 1c438151655..35aca5f09bf 100644 --- a/src/xrNetServer/NET_Compressor.h +++ b/src/xrNetServer/NET_Compressor.h @@ -1,6 +1,6 @@ +#pragma once #if !defined(AFX_NET_COMPRESSOR_H__21E1ED1C_BF92_4BF0_94A8_18A27486EBFD__INCLUDED_) #define AFX_NET_COMPRESSOR_H__21E1ED1C_BF92_4BF0_94A8_18A27486EBFD__INCLUDED_ -#pragma once #include "xrCore/Threading/Lock.hpp" @@ -20,6 +20,7 @@ class XRNETSERVER_API NET_Compressor u32 compressed_size; SStatPacket() : hit_count(0), unlucky_attempts(0), compressed_size(0) {} }; + xr_map m_packets; SCompressorStats() : total_uncompressed_bytes(0), total_compressed_bytes(0) {} @@ -30,10 +31,10 @@ class XRNETSERVER_API NET_Compressor NET_Compressor(); ~NET_Compressor(); - u16 compressed_size(const u32& count); + u16 compressed_size(const u32& count) const; u16 Compress(BYTE* dest, const u32& dest_size, BYTE* src, const u32& count); // return size of compressed u16 Decompress(BYTE* dest, const u32& dest_size, BYTE* src, const u32& count); // return size of compressed - void DumpStats(bool brief); + void DumpStats(bool brief) const; }; #endif // !defined(AFX_NET_COMPRESSOR_H__21E1ED1C_BF92_4BF0_94A8_18A27486EBFD__INCLUDED_) diff --git a/src/xrNetServer/NET_Log.cpp b/src/xrNetServer/NET_Log.cpp index b23272c3db5..eadb13a9437 100644 --- a/src/xrNetServer/NET_Log.cpp +++ b/src/xrNetServer/NET_Log.cpp @@ -45,14 +45,15 @@ string64 PacketName[] = {"M_UPDATE", // DUAL: Update state "MSG_FORCEDWORD"}; //--------------------------------------------------------- -INetLog::INetLog(LPCSTR sFileName, u32 dwStartTime) #ifdef CONFIG_PROFILE_LOCKS - : m_cs(MUTEX_PROFILE_ID(NET_Log)) -#endif // CONFIG_PROFILE_LOCKS +INetLog::INetLog(pcstr sFileName, u32 dwStartTime) : m_cs(MUTEX_PROFILE_ID(NET_Log)) +#else +INetLog::INetLog(pcstr sFileName, u32 dwStartTime) +#endif { xr_strcpy(m_cFileName, sFileName); - m_pLogFile = NULL; + m_pLogFile = nullptr; m_pLogFile = fopen(sFileName, "wb"); m_dwStartTime = 0; // dwStartTime; } @@ -62,24 +63,24 @@ INetLog::~INetLog() FlushLog(); if (m_pLogFile) fclose(m_pLogFile); - m_pLogFile = NULL; + m_pLogFile = nullptr; } void INetLog::FlushLog() { if (m_pLogFile) { - for (xr_vector::iterator it = m_aLogPackets.begin(); it != m_aLogPackets.end(); it++) + for (xr_vector::iterator it = m_aLogPackets.begin(); it != m_aLogPackets.end(); ++it) { SLogPacket* pLPacket = &(*it); if (pLPacket->m_u16Type >= sizeof(PacketName) / sizeof(PacketName[0])) fprintf(m_pLogFile, "%s %10u %10u %10u\n", pLPacket->m_bIsIn ? "In:" : "Out:", pLPacket->m_u32Time, - pLPacket->m_u16Type, pLPacket->m_u32Size); + pLPacket->m_u16Type, pLPacket->m_u32Size); else fprintf(m_pLogFile, "%s %10u %10s %10u\n", pLPacket->m_bIsIn ? "In:" : "Out:", pLPacket->m_u32Time, - PacketName[pLPacket->m_u16Type], pLPacket->m_u32Size); - }; - }; + PacketName[pLPacket->m_u16Type], pLPacket->m_u32Size); + } + } m_aLogPackets.clear(); } @@ -93,7 +94,7 @@ void INetLog::LogPacket(u32 Time, NET_Packet* pPacket, bool IsIn) SLogPacket NewPacket; - NewPacket.m_u16Type = *((u16*)&pPacket->B.data); + NewPacket.m_u16Type = *(u16*)&pPacket->B.data; NewPacket.m_u32Size = pPacket->B.count; NewPacket.m_u32Time = Time - m_dwStartTime; NewPacket.m_bIsIn = IsIn; @@ -103,7 +104,7 @@ void INetLog::LogPacket(u32 Time, NET_Packet* pPacket, bool IsIn) FlushLog(); m_cs.Leave(); -}; +} void INetLog::LogData(u32 Time, void* data, u32 size, bool IsIn) { @@ -114,7 +115,7 @@ void INetLog::LogData(u32 Time, void* data, u32 size, bool IsIn) SLogPacket NewPacket; - NewPacket.m_u16Type = *((u16*)data); + NewPacket.m_u16Type = *(u16*)data; NewPacket.m_u32Size = size; NewPacket.m_u32Time = Time - m_dwStartTime; NewPacket.m_bIsIn = IsIn; diff --git a/src/xrNetServer/NET_Log.h b/src/xrNetServer/NET_Log.h index eac8be9c7c6..2a34603fb36 100644 --- a/src/xrNetServer/NET_Log.h +++ b/src/xrNetServer/NET_Log.h @@ -1,6 +1,7 @@ #pragma once -#include "net_shared.h" +#include "NET_Shared.h" + struct SLogPacket { u32 m_u32Time; @@ -9,9 +10,9 @@ struct SLogPacket string64 m_sTypeStr; bool m_bIsIn; }; + class INetLog { -private: FILE* m_pLogFile; string1024 m_cFileName; u32 m_dwStartTime; @@ -23,52 +24,63 @@ class INetLog void FlushLog(); public: - INetLog(LPCSTR sFileName, u32 dwStartTime); + INetLog(pcstr sFileName, u32 dwStartTime); ~INetLog(); - void LogPacket(u32 Time, NET_Packet* pPacket, bool IsIn = FALSE); - void LogData(u32 Time, void* data, u32 size, bool IsIn = FALSE); + void LogPacket(u32 Time, NET_Packet* pPacket, bool IsIn = false); + void LogData(u32 Time, void* data, u32 size, bool IsIn = false); }; /* // Singleton template definition -template class CSingleton { -private: - static T* _self; - static int _refcount; +template +class CSingleton +{ + static T* _self; + static int _refcount; + public: //whether singleton will delete itself on FreeInst //when _refcount = 0 //otherwise user should call DestroySingleton() manually static bool _on_self_delete; -public: - CSingleton () {} - virtual ~CSingleton () {_self=NULL;} - static void DestroySingleton () { - if(!_self) return; - Log ("DestroySingleton::RefCounter:",_refcount); + CSingleton() {} + virtual ~CSingleton() { _self = nullptr; } + + static void DestroySingleton() + { + if (!_self) return; + Log("DestroySingleton::RefCounter:", _refcount); VERIFY(_on_self_delete == false); VERIFY(_refcount == 0); xr_delete(_self); }; -public: - static T* Instance () { - if(!_self) _self=new T(); + + static T* Instance() + { + if (!_self) _self = new T(); ++_refcount; return _self; } - void FreeInst () { - if(0 == --_refcount) { - if(_on_self_delete){ - CSingleton *ptr = this; + + void FreeInst() + { + if (0 == --_refcount) + { + if (_on_self_delete) + { + CSingleton* ptr = this; xr_delete(ptr); } } } }; -template T* CSingleton::_self = NULL; -template int CSingleton::_refcount = 0; -template bool CSingleton::_on_self_delete = true; +template +T* CSingleton::_self = nullptr; +template +int CSingleton::_refcount = 0; +template +bool CSingleton::_on_self_delete = true; */ diff --git a/src/xrNetServer/NET_Messages.h b/src/xrNetServer/NET_Messages.h index ad02f1ca62e..521840eb839 100644 --- a/src/xrNetServer/NET_Messages.h +++ b/src/xrNetServer/NET_Messages.h @@ -4,11 +4,12 @@ #define DPNSEND_IMMEDIATELLY 0x0100 IC u32 net_flags( - BOOL bReliable = FALSE, BOOL bSequental = TRUE, BOOL bHighPriority = FALSE, BOOL bSendImmediatelly = FALSE) + bool bReliable = false, bool bSequental = true, bool bHighPriority = false, bool bSendImmediatelly = false) { return (bReliable ? DPNSEND_GUARANTEED : DPNSEND_NOCOMPLETE) | (bSequental ? 0 : DPNSEND_NONSEQUENTIAL) | (bHighPriority ? DPNSEND_PRIORITY_HIGH : 0) | (bSendImmediatelly ? DPNSEND_IMMEDIATELLY : 0); } + struct MSYS_CONFIG { u32 sign1; // 0x12071980; diff --git a/src/xrNetServer/NET_PlayersMonitor.h b/src/xrNetServer/NET_PlayersMonitor.h index 9ae46228a94..adb09531ea2 100644 --- a/src/xrNetServer/NET_PlayersMonitor.h +++ b/src/xrNetServer/NET_PlayersMonitor.h @@ -1,7 +1,8 @@ +#pragma once #ifndef NET_PLAYERS_MONITOR #define NET_PLAYERS_MONITOR -#include "net_shared.h" +#include "NET_Shared.h" #include "NET_Common.h" #include "xrCore/fastdelegate.h" @@ -9,8 +10,7 @@ class IClient; class PlayersMonitor { -private: - typedef xr_vector players_collection_t; + using players_collection_t = xr_vector; Lock csPlayers; players_collection_t net_Players; players_collection_t net_Players_disconnected; @@ -61,6 +61,7 @@ class PlayersMonitor // Msg("-S- Leaving from csPlayers [%d]", GetCurrentThreadId()); csPlayers.Leave(); } + void ForEachClientDo(fastdelegate::FastDelegate1& fast_delegate) { // Msg("-S- Entering to csPlayers [%d]", GetCurrentThreadId()); @@ -80,6 +81,7 @@ class PlayersMonitor // Msg("-S- Leaving from csPlayers [%d]", GetCurrentThreadId()); csPlayers.Leave(); } + template u32 ForFoundClientsDo(SearchPredicate const& predicate, ActionFunctor& functor) { @@ -120,7 +122,7 @@ class PlayersMonitor iterator_thread_id = GetCurrentThreadId(); #endif players_collection_t::iterator client_iter = std::find_if(net_Players.begin(), net_Players.end(), predicate); - IClient* ret_client = NULL; + IClient* ret_client = nullptr; if (client_iter != net_Players.end()) { ret_client = *client_iter; @@ -131,6 +133,7 @@ class PlayersMonitor csPlayers.Leave(); return ret_client; } + template IClient* GetFoundClient(SearchPredicate const& predicate) { @@ -139,7 +142,7 @@ class PlayersMonitor // LogStackTrace( // make_string("-S- Entered to csPlayers [%d]", GetCurrentThreadId()).c_str()); players_collection_t::iterator client_iter = std::find_if(net_Players.begin(), net_Players.end(), predicate); - IClient* ret_client = NULL; + IClient* ret_client = nullptr; if (client_iter != net_Players.end()) { ret_client = *client_iter; @@ -148,43 +151,43 @@ class PlayersMonitor csPlayers.Leave(); return ret_client; } + void AddNewClient(IClient* new_client) { - // Msg("-S- Entering to csPlayers [%d]", GetCurrentThreadId()); + //Msg("-S- Entering to csPlayers [%d]", GetCurrentThreadId()); csPlayers.Enter(); - // LogStackTrace( - // make_string("-S- Entered to csPlayers [%d]", GetCurrentThreadId()).c_str()); + //LogStackTrace(make_string("-S- Entered to csPlayers [%d]", GetCurrentThreadId()).c_str()); VERIFY(!now_iterating_in_net_players); net_Players.push_back(new_client); - // Msg("-S- Leaving from csPlayers [%d]", GetCurrentThreadId()); + //Msg("-S- Leaving from csPlayers [%d]", GetCurrentThreadId()); csPlayers.Leave(); } - /*template - void ForEachDisconnectedClientDo (ActionFunctor & functor) + /* + template + void ForEachDisconnectedClientDo(ActionFunctor& functor) { //Msg("-S- Entering to csPlayers [%d]", GetCurrentThreadId()); csPlayers.Enter(); - //LogStackTrace( - // make_string("-S- Entered to csPlayers [%d]", GetCurrentThreadId()).c_str()); - now_iterating_in_net_players_disconn = true; + //LogStackTrace(make_string("-S- Entered to csPlayers [%d]", GetCurrentThreadId()).c_str()); + now_iterating_in_net_players_disconn = true; #ifdef DEBUG iterator_thread_id = GetCurrentThreadId(); #endif std::for_each(net_Players_disconnected.begin(), net_Players_disconnected.end(), functor); - now_iterating_in_net_players_disconn = false; + now_iterating_in_net_players_disconn = false; //Msg("-S- Leaving from csPlayers [%d]", GetCurrentThreadId()); csPlayers.Leave(); } - template - IClient* FindAndEraseDisconnectedClient (SearchPredicate const & predicate) + + template + IClient* FindAndEraseDisconnectedClient(SearchPredicate const& predicate) { //Msg("-S- Entering to csPlayers [%d]", GetCurrentThreadId()); csPlayers.Enter(); - //LogStackTrace( - // make_string("-S- Entered to csPlayers [%d]", GetCurrentThreadId()).c_str()); + //LogStackTrace(make_string("-S- Entered to csPlayers [%d]", GetCurrentThreadId()).c_str()); VERIFY(!now_iterating_in_net_players_disconn); - now_iterating_in_net_players_disconn = true; + now_iterating_in_net_players_disconn = true; #ifdef DEBUG iterator_thread_id = GetCurrentThreadId(); #endif @@ -192,25 +195,26 @@ class PlayersMonitor net_Players_disconnected.begin(), net_Players_disconnected.end(), predicate); - IClient* ret_client = NULL; + IClient* ret_client = nullptr; if (client_iter != net_Players_disconnected.end()) { ret_client = *client_iter; net_Players_disconnected.erase(client_iter); } - now_iterating_in_net_players_disconn = false; + now_iterating_in_net_players_disconn = false; //Msg("-S- Leaving from csPlayers [%d]", GetCurrentThreadId()); csPlayers.Leave(); return ret_client; } - template - IClient* GetFoundDisconnectedClient (SearchPredicate const & predicate) + + template + IClient* GetFoundDisconnectedClient(SearchPredicate const& predicate) { //Msg("-S- Entering to csPlayers [%d]", GetCurrentThreadId()); csPlayers.Enter(); //LogStackTrace( // make_string("-S- Entered to csPlayers [%d]", GetCurrentThreadId()).c_str()); - now_iterating_in_net_players_disconn = true; + now_iterating_in_net_players_disconn = true; #ifdef DEBUG iterator_thread_id = GetCurrentThreadId(); #endif @@ -218,15 +222,16 @@ class PlayersMonitor net_Players_disconnected.begin(), net_Players_disconnected.end(), predicate); - now_iterating_in_net_players_disconn = false; - IClient* ret_client = NULL; + now_iterating_in_net_players_disconn = false; + IClient* ret_client = nullptr; if (client_iter != net_Players_disconnected.end()) ret_client = *client_iter; //Msg("-S- Leaving from csPlayers [%d]", GetCurrentThreadId()); csPlayers.Leave(); return ret_client; } - void AddNewDisconnectedClient (IClient* new_client) + + void AddNewDisconnectedClient(IClient* new_client) { //Msg("-S- Entering to csPlayers [%d]", GetCurrentThreadId()); csPlayers.Enter(); @@ -236,28 +241,31 @@ class PlayersMonitor net_Players_disconnected.push_back(new_client); //Msg("-S- Leaving from csPlayers [%d]", GetCurrentThreadId()); csPlayers.Leave(); - }*/ + } + */ u32 ClientsCount() { - // Msg("-S- Entering to csPlayers [%d]", GetCurrentThreadId()); + //Msg("-S- Entering to csPlayers [%d]", GetCurrentThreadId()); csPlayers.Enter(); - // LogStackTrace( - // make_string("-S- Entered to csPlayers [%d]", GetCurrentThreadId()).c_str()); + //LogStackTrace(make_string("-S- Entered to csPlayers [%d]", GetCurrentThreadId()).c_str()); u32 ret_count = net_Players.size(); - // Msg("-S- Leaving from csPlayers [%d]", GetCurrentThreadId()); + //Msg("-S- Leaving from csPlayers [%d]", GetCurrentThreadId()); csPlayers.Leave(); return ret_count; } + // WARNING! for iteration in vector use ForEachClientDo ! // This function can be used carefully (single call) - /*IClient* GetClientByIndex (u32 index) + /* + IClient* GetClientByIndex(u32 index) { csPlayers.Enter(); IClient* ret_client = net_Players[index]; csPlayers.Leave(); return ret_client; - }*/ + } + */ }; // class PlayersMonitor #endif //#ifndef NET_PLAYERS_MONITOR diff --git a/src/xrNetServer/NET_Server.cpp b/src/xrNetServer/NET_Server.cpp index ed37ff20545..57d0c40c0d7 100644 --- a/src/xrNetServer/NET_Server.cpp +++ b/src/xrNetServer/NET_Server.cpp @@ -1,7 +1,7 @@ #include "stdafx.h" #include "xrCore/Debug/dxerr.h" #include "NET_Common.h" -#include "net_server.h" +#include "NET_Server.h" #include //#include "xrCore/net_utils.h" #include @@ -15,22 +15,22 @@ #include #pragma warning(pop) -static INetLog* pSvNetLog = NULL; +static INetLog* pSvNetLog = nullptr; #define NET_BANNED_STR "Player banned by server!" #define NET_PROTECTED_SERVER_STR "Access denied by protected server for this player!" #define NET_NOTFOR_SUBNET_STR "Your IP does not present in server's subnet" -void dump_URL(LPCSTR p, IDirectPlay8Address* A); +void dump_URL(pcstr p, IDirectPlay8Address* A); -LPCSTR nameTraffic = "traffic.net"; +pcstr nameTraffic = "traffic.net"; XRNETSERVER_API int psNET_ServerUpdate = 30; // FPS XRNETSERVER_API int psNET_ServerPending = 3; XRNETSERVER_API ClientID BroadcastCID(0xffffffff); -void ip_address::set(LPCSTR src_string) +void ip_address::set(pcstr src_string) { u32 buff[4]; int cnt = sscanf(src_string, "%d.%d.%d.%d", &buff[0], &buff[1], &buff[2], &buff[3]); @@ -62,7 +62,7 @@ void IBannedClient::Load(CInifile& ini, const shared_str& sect) tm _tm_banned; const shared_str& time_to = ini.r_string(sect, "time_to"); int res_t = sscanf(time_to.c_str(), "%02d.%02d.%d_%02d:%02d:%02d", &_tm_banned.tm_mday, &_tm_banned.tm_mon, - &_tm_banned.tm_year, &_tm_banned.tm_hour, &_tm_banned.tm_min, &_tm_banned.tm_sec); + &_tm_banned.tm_year, &_tm_banned.tm_hour, &_tm_banned.tm_min, &_tm_banned.tm_sec); VERIFY(res_t == 6); _tm_banned.tm_mon -= 1; @@ -73,19 +73,22 @@ void IBannedClient::Load(CInifile& ini, const shared_str& sect) Msg("- loaded banned client %s to %s", HAddr.to_string().c_str(), BannedTimeTo().c_str()); } -void IBannedClient::Save(CInifile& ini) { ini.w_string(HAddr.to_string().c_str(), "time_to", BannedTimeTo().c_str()); } +void IBannedClient::Save(CInifile& ini) +{ + ini.w_string(HAddr.to_string().c_str(), "time_to", BannedTimeTo().c_str()); +} + xr_string IBannedClient::BannedTimeTo() const { string256 res; - tm* _tm_banned; - _tm_banned = _localtime64(&BanTime); + tm* _tm_banned = _localtime64(&BanTime); xr_sprintf(res, sizeof(res), "%02d.%02d.%d_%02d:%02d:%02d", _tm_banned->tm_mday, _tm_banned->tm_mon + 1, - _tm_banned->tm_year + 1900, _tm_banned->tm_hour, _tm_banned->tm_min, _tm_banned->tm_sec); + _tm_banned->tm_year + 1900, _tm_banned->tm_hour, _tm_banned->tm_min, _tm_banned->tm_sec); return res; } -IClient::IClient(CTimer* timer) : stats(timer), server(NULL) +IClient::IClient(CTimer* timer) : stats(timer), server(nullptr) { dwTime_LastUpdate = 0; flags.bLocal = FALSE; @@ -106,8 +109,7 @@ struct ClientStatisticImpl }; IClientStatistic::IClientStatistic() : - m_pimpl(new ClientStatisticImpl) -{} + m_pimpl(new ClientStatisticImpl) {} IClientStatistic::IClientStatistic(CTimer* timer) { @@ -124,7 +126,9 @@ IClientStatistic::IClientStatistic(const IClientStatistic& rhs) : } IClientStatistic::~IClientStatistic() -{ delete m_pimpl; } +{ + delete m_pimpl; +} void IClientStatistic::Update(DPN_CONNECTION_INFO& CI) { @@ -134,7 +138,7 @@ void IClientStatistic::Update(DPN_CONNECTION_INFO& CI) m_pimpl->dwBaseTime = time_global; m_pimpl->mps_receive = CI.dwMessagesReceived - m_pimpl->mps_receive_base; - m_pimpl->mps_receive_base= CI.dwMessagesReceived; + m_pimpl->mps_receive_base = CI.dwMessagesReceived; u32 cur_msend = CI.dwMessagesTransmittedHighPriority + CI.dwMessagesTransmittedNormalPriority + CI.dwMessagesTransmittedLowPriority; @@ -195,12 +199,12 @@ void IClient::_SendTo_LL(const void* data, u32 size, u32 flags, u32 timeout) IClient* IPureServer::ID_to_client(ClientID ID, bool ScanAll) { if (0 == ID.value()) - return NULL; + return nullptr; IClient* ret_client = GetClientByID(ID); if (ret_client || !ScanAll) return ret_client; - return NULL; + return nullptr; } void IPureServer::_Recieve(const void* data, u32 data_size, u32 param) @@ -228,7 +232,7 @@ void IPureServer::_Recieve(const void* data, u32 data_size, u32 param) pSvNetLog = new INetLog("logs\\net_sv_log.log", TimeGlobal(device_timer)); if (pSvNetLog) - pSvNetLog->LogPacket(TimeGlobal(device_timer), &packet, TRUE); + pSvNetLog->LogPacket(TimeGlobal(device_timer), &packet, true); } //--------------------------------------- u32 result = OnMessage(packet, id); @@ -240,21 +244,21 @@ void IPureServer::_Recieve(const void* data, u32 data_size, u32 param) } //============================================================================== - -IPureServer::IPureServer(CTimer* timer, BOOL Dedicated) - : m_bDedicated(Dedicated) #ifdef CONFIG_PROFILE_LOCKS - , - csPlayers(MUTEX_PROFILE_ID(IPureServer::csPlayers)), csMessage(MUTEX_PROFILE_ID(IPureServer::csMessage)) -#endif // CONFIG_PROFILE_LOCKS +IPureServer::IPureServer(CTimer* timer, bool Dedicated) : m_bDedicated(Dedicated), + csPlayers(MUTEX_PROFILE_ID(IPureServer::csPlayers)), + csMessage(MUTEX_PROFILE_ID(csMessage)) +#else +IPureServer::IPureServer(CTimer* timer, bool Dedicated) : m_bDedicated(Dedicated) +#endif { device_timer = timer; stats.clear(); stats.dwSendTime = TimeGlobal(device_timer); - SV_Client = NULL; - NET = NULL; - net_Address_device = NULL; - pSvNetLog = NULL; // new INetLog("logs\\net_sv_log.log", TimeGlobal(device_timer)); + SV_Client = nullptr; + NET = nullptr; + net_Address_device = nullptr; + pSvNetLog = nullptr; // new INetLog("logs//net_sv_log.log", TimeGlobal(device_timer)); #ifdef DEBUG sender_functor_invoked = false; #endif @@ -267,20 +271,20 @@ IPureServer::~IPureServer() BannedAddresses.clear(); - SV_Client = NULL; + SV_Client = nullptr; xr_delete(pSvNetLog); - psNET_direct_connect = FALSE; + psNET_direct_connect = false; } -IPureServer::EConnect IPureServer::Connect(LPCSTR options, GameDescriptionData& game_descr) +IPureServer::EConnect IPureServer::Connect(pcstr options, GameDescriptionData& game_descr) { connect_options = options; - psNET_direct_connect = FALSE; + psNET_direct_connect = false; if (strstr(options, "/single")) - psNET_direct_connect = TRUE; + psNET_direct_connect = true; // Parse options string4096 session_name; @@ -288,8 +292,8 @@ IPureServer::EConnect IPureServer::Connect(LPCSTR options, GameDescriptionData& string64 password_str = ""; u32 dwMaxPlayers = 0; - // sertanly we can use game_descr structure for determinig level_name, but for backward compatibility we save next - // line... + // certainly we can use game_descr structure for determining level_name, + // but for backward compatibility we save next line... xr_strcpy(session_name, options); if (strchr(session_name, '/')) *strchr(session_name, '/') = 0; @@ -319,7 +323,7 @@ IPureServer::EConnect IPureServer::Connect(LPCSTR options, GameDescriptionData& #endif // #ifdef DEBUG //------------------------------------------------------------------- - BOOL bPortWasSet = FALSE; + bool bPortWasSet = false; u32 dwServerPort = START_PORT_LAN_SV; if (strstr(options, "portsv=")) { @@ -331,46 +335,46 @@ IPureServer::EConnect IPureServer::Connect(LPCSTR options, GameDescriptionData& strncpy_s(tmpStr, ServerPort, 63); dwServerPort = atol(tmpStr); clamp(dwServerPort, u32(START_PORT), u32(END_PORT)); - bPortWasSet = TRUE; // this is not casual game + bPortWasSet = true; // this is not casual game } //------------------------------------------------------------------- if (!psNET_direct_connect) { -//--------------------------- + //--------------------------- #ifdef DEBUG string1024 tmp; #endif // DEBUG - // HRESULT CoInitializeExRes = CoInitializeEx(NULL, 0); - // if (CoInitializeExRes != S_OK && CoInitializeExRes != S_FALSE) - // { - // DXTRACE_ERR(tmp, CoInitializeExRes); - // CHK_DX(CoInitializeExRes); - // }; + //HRESULT CoInitializeExRes = CoInitializeEx(nullptr, 0); + //if (CoInitializeExRes != S_OK && CoInitializeExRes != S_FALSE) + //{ + // DXTRACE_ERR(tmp, CoInitializeExRes); + // CHK_DX(CoInitializeExRes); + //} //--------------------------- // Create the IDirectPlay8Client object. HRESULT CoCreateInstanceRes = CoCreateInstance( - CLSID_DirectPlay8Server, NULL, CLSCTX_INPROC_SERVER, IID_IDirectPlay8Server, (LPVOID*)&NET); + CLSID_DirectPlay8Server, nullptr, CLSCTX_INPROC_SERVER, IID_IDirectPlay8Server, (LPVOID*)&NET); //--------------------------- if (CoCreateInstanceRes != S_OK) { DXTRACE_ERR(tmp, CoCreateInstanceRes); CHK_DX(CoCreateInstanceRes); } -//--------------------------- + //--------------------------- -// Initialize IDirectPlay8Client object. + // Initialize IDirectPlay8Client object. #ifdef DEBUG CHK_DX(NET->Initialize(this, Handler, 0)); #else CHK_DX(NET->Initialize(this, Handler, DPNINITIALIZE_DISABLEPARAMVAL)); #endif - BOOL bSimulator = FALSE; + bool bSimulator = false; if (strstr(Core.Params, "-netsim")) - bSimulator = TRUE; + bSimulator = true; - // dump_URL ("! sv ", net_Address_device); + //dump_URL("! sv ", net_Address_device); // Set server-player info DPN_APPLICATION_DESC dpAppDesc; @@ -381,7 +385,7 @@ IPureServer::EConnect IPureServer::Connect(LPCSTR options, GameDescriptionData& dpPlayerInfo.dwSize = sizeof(DPN_PLAYER_INFO); dpPlayerInfo.dwInfoFlags = DPNINFO_NAME; dpPlayerInfo.pwszName = wszName; - dpPlayerInfo.pvData = NULL; + dpPlayerInfo.pvData = nullptr; dpPlayerInfo.dwDataSize = NULL; dpPlayerInfo.dwPlayerFlags = 0; @@ -408,31 +412,29 @@ IPureServer::EConnect IPureServer::Connect(LPCSTR options, GameDescriptionData& CHK_DX(MultiByteToWideChar(CP_ACP, 0, password_str, -1, SessionPasswordUNICODE, 4096)); dpAppDesc.dwFlags |= DPNSESSION_REQUIREPASSWORD; dpAppDesc.pwszPassword = SessionPasswordUNICODE; - }; + } // Create our IDirectPlay8Address Device Address, --- Set the SP for our Device Address - net_Address_device = NULL; - CHK_DX(CoCreateInstance(CLSID_DirectPlay8Address, NULL, CLSCTX_INPROC_SERVER, IID_IDirectPlay8Address, - (LPVOID*)&net_Address_device)); + net_Address_device = nullptr; + CHK_DX(CoCreateInstance(CLSID_DirectPlay8Address, NULL, CLSCTX_INPROC_SERVER, IID_IDirectPlay8Address, (LPVOID*)&net_Address_device)); + CHK_DX(net_Address_device->SetSP(bSimulator ? &CLSID_NETWORKSIMULATOR_DP8SP_TCPIP : &CLSID_DP8SP_TCPIP)); DWORD dwTraversalMode = DPNA_TRAVERSALMODE_NONE; - CHK_DX(net_Address_device->AddComponent( - DPNA_KEY_TRAVERSALMODE, &dwTraversalMode, sizeof(dwTraversalMode), DPNA_DATATYPE_DWORD)); + CHK_DX(net_Address_device->AddComponent(DPNA_KEY_TRAVERSALMODE, &dwTraversalMode, sizeof(dwTraversalMode), DPNA_DATATYPE_DWORD)); HRESULT HostSuccess = S_FALSE; // We are now ready to host the app and will try different ports psNET_Port = dwServerPort; while (HostSuccess != S_OK) { - CHK_DX( - net_Address_device->AddComponent(DPNA_KEY_PORT, &psNET_Port, sizeof(psNET_Port), DPNA_DATATYPE_DWORD)); + CHK_DX(net_Address_device->AddComponent(DPNA_KEY_PORT, &psNET_Port, sizeof(psNET_Port), DPNA_DATATYPE_DWORD)); HostSuccess = NET->Host(&dpAppDesc, // AppDesc - &net_Address_device, 1, // Device Address - NULL, NULL, // Reserved - NULL, // Player Context - 0); // dwFlags + &net_Address_device, 1, // Device Address + nullptr, nullptr, // Reserved + nullptr, // Player Context + 0); // dwFlags if (HostSuccess != S_OK) { // xr_string res = xrDebug::ErrorToString(HostSuccess); @@ -441,28 +443,20 @@ IPureServer::EConnect IPureServer::Connect(LPCSTR options, GameDescriptionData& Msg("! IPureServer : port %d is BUSY!", psNET_Port); return ErrConnect; } - else - { - Msg("! IPureServer : port %d is BUSY!", psNET_Port); - } + Msg("! IPureServer : port %d is BUSY!", psNET_Port); psNET_Port++; if (psNET_Port > END_PORT_LAN) - { return ErrConnect; - } } else - { Msg("- IPureServer : created on port %d!", psNET_Port); - } - }; + } CHK_DX(HostSuccess); - } // psNET_direct_connect - //. config_Load (); + //config_Load(); if (!psNET_direct_connect) { @@ -502,7 +496,7 @@ HRESULT IPureServer::net_Handler(u32 dwMessageType, PVOID pMessage) PDPNMSG_ENUM_HOSTS_QUERY msg = PDPNMSG_ENUM_HOSTS_QUERY(pMessage); if (0 == msg->dwReceivedDataSize) return S_FALSE; - if (!_stricmp((const char*)msg->pvReceivedData, "ToConnect")) + if (!_stricmp((pcstr)msg->pvReceivedData, "ToConnect")) return S_OK; if (*((const GUID*)msg->pvReceivedData) != NET_GUID) return S_FALSE; @@ -510,7 +504,7 @@ HRESULT IPureServer::net_Handler(u32 dwMessageType, PVOID pMessage) return S_FALSE; return S_OK; } - break; + case DPN_MSGID_CREATE_PLAYER: { PDPNMSG_CREATE_PLAYER msg = PDPNMSG_CREATE_PLAYER(pMessage); @@ -520,7 +514,7 @@ HRESULT IPureServer::net_Handler(u32 dwMessageType, PVOID pMessage) ZeroMemory(bufferData, bufferSize); string512 res; - // retreive info + // retrieve info DPN_PLAYER_INFO* Pinfo = (DPN_PLAYER_INFO*)bufferData; Pinfo->dwSize = sizeof(DPN_PLAYER_INFO); HRESULT _hr = NET->GetClientInfo(msg->dpnidPlayer, Pinfo, &bufferSize, 0); @@ -532,21 +526,21 @@ HRESULT IPureServer::net_Handler(u32 dwMessageType, PVOID pMessage) CHK_DX(_hr); - // string64 cname; - // CHK_DX( WideCharToMultiByte( CP_ACP, 0, Pinfo->pwszName, -1, cname, sizeof(cname) , 0, 0 ) ); + //string64 cname; + //CHK_DX(WideCharToMultiByte( CP_ACP, 0, Pinfo->pwszName, -1, cname, sizeof(cname) , nullptr, nullptr ) ); SClientConnectData cl_data; - // xr_strcpy( cl_data.name, cname ); + //xr_strcpy(cl_data.name, cname); if (Pinfo->pvData && Pinfo->dwDataSize == sizeof(cl_data)) { - cl_data = *((SClientConnectData*)Pinfo->pvData); + cl_data = *(SClientConnectData*)Pinfo->pvData; } cl_data.clientID.set(msg->dpnidPlayer); new_client(&cl_data); } - break; + break; case DPN_MSGID_DESTROY_PLAYER: { PDPNMSG_DESTROY_PLAYER msg = PDPNMSG_DESTROY_PLAYER(pMessage); @@ -561,7 +555,7 @@ HRESULT IPureServer::net_Handler(u32 dwMessageType, PVOID pMessage) client_Destroy(tmp_client); } } - break; + break; case DPN_MSGID_RECEIVE: { PDPNMSG_RECEIVE pMsg = PDPNMSG_RECEIVE(pMessage); @@ -580,16 +574,14 @@ HRESULT IPureServer::net_Handler(u32 dwMessageType, PVOID pMessage) m_ping->dwTime_Server = TimerAsync(device_timer); ClientID ID; ID.set(m_sender); - // IPureServer::SendTo_LL (ID,m_data,m_size,net_flags(FALSE,FALSE,TRUE)); - IPureServer::SendTo_Buf(ID, m_data, m_size, net_flags(FALSE, FALSE, TRUE, TRUE)); + //IPureServer::SendTo_LL(ID, m_data, m_size, net_flags(false, false, true)); + IPureServer::SendTo_Buf(ID, m_data, m_size, net_flags(false, false, true, true)); } } else - { - MultipacketReciever::RecievePacket(pMsg->pReceiveData, pMsg->dwReceiveDataSize, m_sender); - } + RecievePacket(pMsg->pReceiveData, pMsg->dwReceiveDataSize, m_sender); } - break; + break; case DPN_MSGID_INDICATE_CONNECT: { @@ -603,7 +595,7 @@ HRESULT IPureServer::net_Handler(u32 dwMessageType, PVOID pMessage) msg->dwReplyDataSize = sizeof(NET_BANNED_STR); msg->pvReplyData = NET_BANNED_STR; return S_FALSE; - }; + } // first connected client is SV_Client so if it is NULL then this server client tries to connect ;) if (SV_Client && !m_ip_filter.is_ip_present(HAddr.m_data.data)) { @@ -612,7 +604,7 @@ HRESULT IPureServer::net_Handler(u32 dwMessageType, PVOID pMessage) return S_FALSE; } } - break; + break; } return S_OK; } @@ -661,7 +653,7 @@ void IPureServer::SendTo_LL(ClientID ID /*DPNID ID*/, void* data, u32 size, u32 stats.dwBytesPerSec = (stats.dwBytesPerSec * 9 + stats.dwBytesSended) / 10; stats.dwBytesSended = 0; stats.dwSendTime = time_global; - }; + } if (ID.value()) stats.dwBytesSended += size; #endif @@ -671,7 +663,7 @@ void IPureServer::SendTo_LL(ClientID ID /*DPNID ID*/, void* data, u32 size, u32 VERIFY(desc.pBufferData); DPNHANDLE hAsync = 0; - HRESULT _hr = NET->SendTo(ID.value(), &desc, 1, dwTimeout, 0, &hAsync, dwFlags | DPNSEND_COALESCE); + HRESULT _hr = NET->SendTo(ID.value(), &desc, 1, dwTimeout, nullptr, &hAsync, dwFlags | DPNSEND_COALESCE); // Msg("- IPureServer::SendTo_LL [%d]", size); @@ -692,6 +684,7 @@ void IPureServer::SendBroadcast_LL(ClientID exclude, void* data, u32 size, u32 d { ClientID id_to_exclude; ClientExcluderPredicate(ClientID exclude) : id_to_exclude(exclude) {} + bool operator()(IClient* client) { if (client->ID == id_to_exclude) @@ -701,18 +694,20 @@ void IPureServer::SendBroadcast_LL(ClientID exclude, void* data, u32 size, u32 d return true; } }; + struct ClientSenderFunctor { IPureServer* m_owner; void* m_data; u32 m_size; u32 m_dwFlags; + ClientSenderFunctor(IPureServer* owner, void* data, u32 size, u32 dwFlags) - : m_owner(owner), m_data(data), m_size(size), m_dwFlags(dwFlags) - { - } + : m_owner(owner), m_data(data), m_size(size), m_dwFlags(dwFlags) { } + void operator()(IClient* client) { m_owner->SendTo_LL(client->ID, m_data, m_size, m_dwFlags); } }; + ClientSenderFunctor temp_functor(this, data, size, dwFlags); net_players.ForFoundClientsDo(ClientExcluderPredicate(exclude), temp_functor); } @@ -727,15 +722,15 @@ u32 IPureServer::OnMessage(NET_Packet& P, ClientID sender) // Non-Zero means bro { /* u16 m_type; - P.r_begin (m_type); + P.r_begin(m_type); switch (m_type) { case M_CHAT: - { - char buffer[256]; - P.r_string(buffer); - printf ("RECEIVE: %s\n",buffer); - } + { + char buffer[256]; + P.r_string(buffer); + printf("RECEIVE: %s\n", buffer); + } break; } */ @@ -745,7 +740,8 @@ u32 IPureServer::OnMessage(NET_Packet& P, ClientID sender) // Non-Zero means bro void IPureServer::OnCL_Connected(IClient* CL) { Msg("* Player 0x%08x connected.\n", CL->ID.value()); } void IPureServer::OnCL_Disconnected(IClient* CL) { Msg("* Player 0x%08x disconnected.\n", CL->ID.value()); } -BOOL IPureServer::HasBandwidth(IClient* C) + +bool IPureServer::HasBandwidth(IClient* C) { u32 dwTime = TimeGlobal(device_timer); u32 dwInterval = 0; @@ -755,7 +751,7 @@ BOOL IPureServer::HasBandwidth(IClient* C) UpdateClientStatistic(C); C->dwTime_LastUpdate = dwTime; dwInterval = 1000; - return TRUE; + return true; } if (psNET_ServerUpdate != 0) @@ -768,22 +764,22 @@ BOOL IPureServer::HasBandwidth(IClient* C) { // check queue for "empty" state DWORD dwPending; - hr = NET->GetSendQueueInfo(C->ID.value(), &dwPending, 0, 0); + hr = NET->GetSendQueueInfo(C->ID.value(), &dwPending, nullptr, 0); if (FAILED(hr)) - return FALSE; + return false; if (dwPending > u32(psNET_ServerPending)) { C->stats.dwTimesBlocked++; - return FALSE; - }; + return false; + } UpdateClientStatistic(C); // ok C->dwTime_LastUpdate = dwTime; - return TRUE; + return true; } - return FALSE; + return false; } void IPureServer::UpdateClientStatistic(IClient* C) @@ -809,19 +805,21 @@ void IPureServer::ClearStatistic() static void Clear(IClient* client) { client->stats.Clear(); } }; net_players.ForEachClientDo(StatsClearFunctor::Clear); -}; +} -/*bool IPureServer::DisconnectClient (IClient* C) +/* +bool IPureServer::DisconnectClient(IClient* C) { if (!C) return false; string64 Reason = "st_kicked_by_server"; - HRESULT res = NET->DestroyClient(C->ID.value(), Reason, xr_strlen(Reason)+1, 0); + HRESULT res = NET->DestroyClient(C->ID.value(), Reason, xr_strlen(Reason) + 1, 0); CHK_DX(res); return true; -}*/ +} +*/ -bool IPureServer::DisconnectClient(IClient* C, LPCSTR Reason) +bool IPureServer::DisconnectClient(IClient* C, pcstr Reason) { if (!C) return false; @@ -831,30 +829,30 @@ bool IPureServer::DisconnectClient(IClient* C, LPCSTR Reason) return true; } -bool IPureServer::DisconnectAddress(const ip_address& Address, LPCSTR reason) +bool IPureServer::DisconnectAddress(const ip_address& Address, pcstr reason) { u32 players_count = net_players.ClientsCount(); buffer_vector PlayersToDisconnect(_alloca(players_count * sizeof(IClient*)), players_count); + struct ToDisconnectFillerFunctor { IPureServer* m_owner; buffer_vector* dest; ip_address const* address_to_disconnect; + ToDisconnectFillerFunctor( IPureServer* owner, buffer_vector* dest_disconnect, ip_address const* address) - : m_owner(owner), dest(dest_disconnect), address_to_disconnect(address) - { - } + : m_owner(owner), dest(dest_disconnect), address_to_disconnect(address) { } + void operator()(IClient* client) { ip_address tmp_address; m_owner->GetClientAddress(client->ID, tmp_address); if (*address_to_disconnect == tmp_address) - { dest->push_back(client); - }; } }; + ToDisconnectFillerFunctor tmp_functor(this, &PlayersToDisconnect, &Address); net_players.ForEachClientDo(tmp_functor); @@ -876,29 +874,29 @@ bool IPureServer::GetClientAddress(IDirectPlay8Address* pClientAddress, ip_addre CHK_DX(pClientAddress->GetComponentByName(DPNA_KEY_HOSTNAME, wstrHostname, &dwSize, &dwDataType)); string256 HostName; - CHK_DX(WideCharToMultiByte(CP_ACP, 0, wstrHostname, -1, HostName, sizeof(HostName), 0, 0)); + CHK_DX(WideCharToMultiByte(CP_ACP, 0, wstrHostname, -1, HostName, sizeof(HostName), nullptr, nullptr)); Address.set(HostName); - if (pPort != NULL) + if (pPort != nullptr) { DWORD dwPort = 0; DWORD dwPortSize = sizeof(dwPort); DWORD dwPortDataType = DPNA_DATATYPE_DWORD; CHK_DX(pClientAddress->GetComponentByName(DPNA_KEY_PORT, &dwPort, &dwPortSize, &dwPortDataType)); *pPort = dwPort; - }; + } return true; -}; +} bool IPureServer::GetClientAddress(ClientID ID, ip_address& Address, DWORD* pPort) { - IDirectPlay8Address* pClAddr = NULL; + IDirectPlay8Address* pClAddr = nullptr; CHK_DX(NET->GetClientAddress(ID.value(), &pClAddr, 0)); return GetClientAddress(pClAddr, Address, pPort); -}; +} IBannedClient* IPureServer::GetBannedClient(const ip_address& Address) { @@ -908,15 +906,15 @@ IBannedClient* IPureServer::GetBannedClient(const ip_address& Address) if (pBClient->HAddr == Address) return pBClient; } - return NULL; -}; + return nullptr; +} void IPureServer::BanClient(IClient* C, u32 BanTime) { ip_address ClAddress; GetClientAddress(C->ID, ClAddress); BanAddress(ClAddress, BanTime); -}; +} void IPureServer::BanAddress(const ip_address& Address, u32 BanTimeSec) { @@ -924,7 +922,7 @@ void IPureServer::BanAddress(const ip_address& Address, u32 BanTimeSec) { Msg("Already banned\n"); return; - }; + } IBannedClient* pNewClient = new IBannedClient(); pNewClient->HAddr = Address; @@ -935,7 +933,7 @@ void IPureServer::BanAddress(const ip_address& Address, u32 BanTimeSec) BannedAddresses.push_back(pNewClient); BannedList_Save(); } -}; +} void IPureServer::UnBanAddress(const ip_address& Address) { @@ -943,7 +941,7 @@ void IPureServer::UnBanAddress(const ip_address& Address) { Msg("! Can't find address %s in ban list.", Address.to_string().c_str()); return; - }; + } for (u32 it = 0; it < BannedAddresses.size(); it++) { @@ -956,8 +954,8 @@ void IPureServer::UnBanAddress(const ip_address& Address) BannedList_Save(); break; } - }; -}; + } +} void IPureServer::Print_Banned_Addreses() { @@ -975,13 +973,13 @@ void IPureServer::BannedList_Save() string_path temp; FS.update_path(temp, "$app_data_root$", GetBannedListName()); - CInifile ini(temp, FALSE, FALSE, TRUE); + CInifile ini(temp, false, false, true); for (u32 it = 0; it < BannedAddresses.size(); it++) { IBannedClient* cl = BannedAddresses[it]; cl->Save(ini); - }; + } } void IPureServer::BannedList_Load() @@ -1008,18 +1006,21 @@ void IPureServer::IpList_Load() Msg("* Initializing IP filter."); m_ip_filter.load(); } + void IPureServer::IpList_Unload() { Msg("* Deinitializing IP filter."); m_ip_filter.unload(); } + bool IPureServer::IsPlayerIPDenied(u32 ip_address) { return !m_ip_filter.is_ip_present(ip_address); } bool banned_client_comparer(IBannedClient* C1, IBannedClient* C2) { return C1->BanTime > C2->BanTime; } + void IPureServer::UpdateBannedList() { if (!BannedAddresses.size()) return; - std::sort(BannedAddresses.begin(), BannedAddresses.end(), banned_client_comparer); + sort(BannedAddresses.begin(), BannedAddresses.end(), banned_client_comparer); time_t T; time(&T); @@ -1031,4 +1032,4 @@ void IPureServer::UpdateBannedList() } } -LPCSTR IPureServer::GetBannedListName() { return "banned_list_ip.ltx"; } +pcstr IPureServer::GetBannedListName() const { return "banned_list_ip.ltx"; } diff --git a/src/xrNetServer/NET_Server.h b/src/xrNetServer/NET_Server.h index 95a0fed0673..eb46867dfeb 100644 --- a/src/xrNetServer/NET_Server.h +++ b/src/xrNetServer/NET_Server.h @@ -34,16 +34,20 @@ struct XRNETSERVER_API ip_address u8 a3; u8 a4; }; + u32 data; } m_data; - void set(LPCSTR src_string); + + void set(pcstr src_string); xr_string to_string() const; bool operator==(const ip_address& other) const { - return (m_data.data == other.m_data.data) || - ((m_data.a1 == other.m_data.a1) && (m_data.a2 == other.m_data.a2) && (m_data.a3 == other.m_data.a3) && - (m_data.a4 == 0)); + return m_data.data == other.m_data.data || + m_data.a1 == other.m_data.a1 && + m_data.a2 == other.m_data.a2 && + m_data.a3 == other.m_data.a3 && + m_data.a4 == 0; } }; @@ -77,15 +81,15 @@ class XRNETSERVER_API IClient : public MultipacketSender IPureServer* server; -public: using MultipacketSender::SendPacket; using MultipacketSender::FlushSendBuffer; private: - virtual void _SendTo_LL(const void* data, u32 size, u32 flags, u32 timeout); + void _SendTo_LL(const void* data, u32 size, u32 flags, u32 timeout) override; }; IC bool operator==(IClient const* pClient, ClientID const& ID) { return pClient->ID == ID; } + class XRNETSERVER_API IServerStatistic { public: @@ -117,7 +121,7 @@ class XRNETSERVER_API IBannedClient { HAddr.m_data.data = 0; BanTime = 0; - }; + } void Load(CInifile& ini, const shared_str& sect); void Save(CInifile& ini); @@ -130,7 +134,7 @@ struct ClientIdSearchPredicate { ClientID clientId; ClientIdSearchPredicate(ClientID clientIdToSearch) : clientId(clientIdToSearch) {} - inline bool operator()(IClient* client) const { return client->ID == clientId; } + bool operator()(IClient* client) const { return client->ID == clientId; } }; class CSE_Abstract; @@ -140,8 +144,8 @@ class IServerGameState; // DPlay extern "C" { -struct IDirectPlay8Server; -struct IDirectPlay8Address; + struct IDirectPlay8Server; + struct IDirectPlay8Address; } class XRNETSERVER_API IPureServer : private MultipacketReciever @@ -181,28 +185,28 @@ class XRNETSERVER_API IPureServer : private MultipacketReciever // Statistic IServerStatistic stats; CTimer* device_timer; - BOOL m_bDedicated; + bool m_bDedicated; IClient* ID_to_client(ClientID ID, bool ScanAll = false); virtual IClient* new_client(SClientConnectData* cl_data) = 0; - bool GetClientAddress(IDirectPlay8Address* pClientAddress, ip_address& Address, DWORD* pPort = NULL); + bool GetClientAddress(IDirectPlay8Address* pClientAddress, ip_address& Address, DWORD* pPort = nullptr); IBannedClient* GetBannedClient(const ip_address& Address); void BannedList_Save(); void BannedList_Load(); void IpList_Load(); void IpList_Unload(); - LPCSTR GetBannedListName(); + pcstr GetBannedListName() const; void UpdateBannedList(); public: - IPureServer(CTimer* timer, BOOL Dedicated = FALSE); + IPureServer(CTimer* timer, bool Dedicated = false); virtual ~IPureServer(); HRESULT net_Handler(u32 dwMessageType, PVOID pMessage); - virtual EConnect Connect(LPCSTR session_name, GameDescriptionData& game_descr); + virtual EConnect Connect(pcstr session_name, GameDescriptionData& game_descr); virtual void Disconnect(); // send @@ -215,7 +219,7 @@ class XRNETSERVER_API IPureServer : private MultipacketReciever virtual void SendBroadcast(ClientID exclude, NET_Packet& P, u32 dwFlags = 0x0008 /*DPNSEND_GUARANTEED*/); // statistic - const IServerStatistic* GetStatistic() { return &stats; } + const IServerStatistic* GetStatistic() const { return &stats; } void ClearStatistic(); void UpdateClientStatistic(IClient* C); @@ -223,62 +227,70 @@ class XRNETSERVER_API IPureServer : private MultipacketReciever virtual u32 OnMessage(NET_Packet& P, ClientID sender); // Non-Zero means broadcasting with "flags" as returned virtual void OnCL_Connected(IClient* C); virtual void OnCL_Disconnected(IClient* C); - virtual bool OnCL_QueryHost() { return true; }; + virtual bool OnCL_QueryHost() { return true; } virtual IClient* client_Create() = 0; // create client info virtual void client_Replicate() = 0; // replicate current state to client virtual void client_Destroy(IClient* C) = 0; // destroy client info - // IC u32 client_Count () { return net_Players.size(); } - // IC IClient* client_Get (u32 num) { return net_Players[num]; } + //u32 client_Count() { return net_Players.size(); } + //IClient* client_Get(u32 num) { return net_Players[num]; } - // IC u32 disconnected_client_Count () { return net_Players_disconnected.size(); } - // IC IClient* disconnected_client_Get (u32 num) { return net_Players_disconnected[num]; } + //u32 disconnected_client_Count() { return net_Players_disconnected.size(); } + //IClient* disconnected_client_Get(u32 num) { return net_Players_disconnected[num]; } - BOOL HasBandwidth(IClient* C); + bool HasBandwidth(IClient* C); - IC int GetPort() { return psNET_Port; }; - bool GetClientAddress(ClientID ID, ip_address& Address, DWORD* pPort = NULL); - // bool DisconnectClient (IClient* C); - virtual bool DisconnectClient(IClient* C, LPCSTR Reason); - virtual bool DisconnectAddress(const ip_address& Address, LPCSTR reason); + int GetPort() const { return psNET_Port; } + bool GetClientAddress(ClientID ID, ip_address& Address, DWORD* pPort = nullptr); + //bool DisconnectClient(IClient* C); + virtual bool DisconnectClient(IClient* C, pcstr Reason); + virtual bool DisconnectAddress(const ip_address& Address, pcstr reason); virtual void BanClient(IClient* C, u32 BanTime); virtual void BanAddress(const ip_address& Address, u32 BanTime); virtual void UnBanAddress(const ip_address& Address); void Print_Banned_Addreses(); virtual bool Check_ServerAccess(IClient* CL, string512& reason) { return true; } - virtual void Assign_ServerType(string512& res){}; - virtual void GetServerInfo(CServerInfo* si){}; + virtual void Assign_ServerType(string512& res) {} + virtual void GetServerInfo(CServerInfo* si) {} u32 GetClientsCount() { return net_players.ClientsCount(); }; - IClient* GetServerClient() { return SV_Client; }; + IClient* GetServerClient() const { return SV_Client; }; + template IClient* FindClient(SearchPredicate const& predicate) { return net_players.GetFoundClient(predicate); } + template void ForEachClientDo(ActionFunctor& action) { net_players.ForEachClientDo(action); } + template void ForEachClientDoSender(SenderFunctor& action) { csMessage.Enter(); #ifdef DEBUG sender_functor_invoked = true; -#endif //#ifdef DEBUG +#endif net_players.ForEachClientDo(action); #ifdef DEBUG sender_functor_invoked = false; -#endif //#ifdef DEBUG +#endif csMessage.Leave(); } -// template -// void ForEachDisconnectedClientDo(ActionFunctor & action) { -// net_players.ForEachDisconnectedClientDo(action); -// }; + + /* + template + void ForEachDisconnectedClientDo(ActionFunctor& action) + { + net_players.ForEachDisconnectedClientDo(action); + } + */ + #ifdef DEBUG bool IsPlayersMonitorLockedByMe() const { @@ -286,29 +298,43 @@ class XRNETSERVER_API IPureServer : private MultipacketReciever }; #endif bool IsPlayerIPDenied(u32 ip_address); + // WARNING! very bad method :( - // IClient* client_Get (u32 index) {return - // net_players.GetClientByIndex(index);}; - IClient* GetClientByID(ClientID clientId) { return net_players.GetFoundClient(ClientIdSearchPredicate(clientId)); }; - // IClient* GetDisconnectedClientByID(ClientID clientId) {return - // net_players.GetFoundDisconnectedClient(ClientIdSearchPredicate(clientId));} + /* + IClient* client_Get(u32 index) + { + return net_players.GetClientByIndex(index); + } + */ + + IClient* GetClientByID(ClientID clientId) + { + return net_players.GetFoundClient(ClientIdSearchPredicate(clientId)); + } + + /* + IClient* GetDisconnectedClientByID(ClientID clientId) + { + return net_players.GetFoundDisconnectedClient(ClientIdSearchPredicate(clientId)); + } + */ const shared_str& GetConnectOptions() const { return connect_options; } virtual IServerGameState* GetGameState() = 0; virtual u16 PerformIDgen(u16 ID) = 0; virtual void FreeID(u16 ID, u32 time) = 0; - virtual CSE_Abstract* entity_Create(LPCSTR name) = 0; + virtual CSE_Abstract* entity_Create(pcstr name) = 0; virtual void entity_Destroy(CSE_Abstract*& entity) = 0; virtual void Perform_destroy(CSE_Abstract* entity, u32 mode) = 0; - virtual CSE_Abstract* Process_spawn(NET_Packet& packet, ClientID sender, BOOL mainEntityAsParent = FALSE, - CSE_Abstract* currentEntity = nullptr) = 0; + virtual CSE_Abstract* Process_spawn(NET_Packet& packet, ClientID sender, bool mainEntityAsParent = false, + CSE_Abstract* currentEntity = nullptr) = 0; private: #ifdef DEBUG bool sender_functor_invoked; #endif - virtual void _Recieve(const void* data, u32 data_size, u32 param); + void _Recieve(const void* data, u32 data_size, u32 param) override; }; diff --git a/src/xrNetServer/NET_Shared.h b/src/xrNetServer/NET_Shared.h index af9d473ebda..309471fd60c 100644 --- a/src/xrNetServer/NET_Shared.h +++ b/src/xrNetServer/NET_Shared.h @@ -7,18 +7,14 @@ #define XRNETSERVER_API XR_EXPORT #else #define XRNETSERVER_API XR_IMPORT - -#ifndef _EDITOR -#pragma comment(lib, "xrNetServer") -#endif #endif // XXX: review and delete //#include "xrCore/net_utils.h" //#include -//#include "net_messages.h" +//#include "NET_Messages.h" -#include "net_compressor.h" +#include "NET_Compressor.h" XRNETSERVER_API extern ClientID BroadcastCID; @@ -31,22 +27,23 @@ XRNETSERVER_API extern int psNET_ServerUpdate; XRNETSERVER_API extern int get_psNET_ServerUpdate(); XRNETSERVER_API extern int psNET_ServerPending; -XRNETSERVER_API extern BOOL psNET_direct_connect; +XRNETSERVER_API extern bool psNET_direct_connect; enum { - NETFLAG_MINIMIZEUPDATES = (1 << 0), - NETFLAG_DBG_DUMPSIZE = (1 << 1), - NETFLAG_LOG_SV_PACKETS = (1 << 2), - NETFLAG_LOG_CL_PACKETS = (1 << 3), + NETFLAG_MINIMIZEUPDATES = 1 << 0, + NETFLAG_DBG_DUMPSIZE = 1 << 1, + NETFLAG_LOG_SV_PACKETS = 1 << 2, + NETFLAG_LOG_CL_PACKETS = 1 << 3, }; IC u32 TimeGlobal(CTimer* timer) { return timer->GetElapsed_ms(); } IC u32 TimerAsync(CTimer* timer) { return TimeGlobal(timer); } + // DPlay extern "C" { -typedef struct _DPN_CONNECTION_INFO DPN_CONNECTION_INFO; + typedef struct _DPN_CONNECTION_INFO DPN_CONNECTION_INFO; } class XRNETSERVER_API IClientStatistic diff --git a/src/xrNetServer/ip_filter.cpp b/src/xrNetServer/ip_filter.cpp index 57a73350b1e..1872eb36263 100644 --- a/src/xrNetServer/ip_filter.cpp +++ b/src/xrNetServer/ip_filter.cpp @@ -3,6 +3,7 @@ #include "xrCore/xr_ini.h" ip_filter::ip_filter() {} + ip_filter::~ip_filter() { for (subnets_coll_t::iterator i = m_all_subnets.begin(), ie = m_all_subnets.end(); i != ie; ++i) @@ -42,6 +43,7 @@ static void hton_bo(u32 const source_ip, subnet_item& dest) } #define SUBNET_LIST_SECT_NAME "subnet_list" + u32 ip_filter::load() { string_path temp; @@ -53,8 +55,8 @@ u32 ip_filter::load() for (u32 i = 0, line_count = ini.line_count(SUBNET_LIST_SECT_NAME); i != line_count; ++i) { - LPCSTR address; - LPCSTR line; + pcstr address; + pcstr line; ini.r_line(SUBNET_LIST_SECT_NAME, i, &address, &line); if (!xr_strlen(address)) continue; @@ -75,8 +77,8 @@ u32 ip_filter::load() unsigned int zero_count = 32 - parse_data[4]; tmp_item->subnet_mask = (u32(-1) >> zero_count) << zero_count; m_all_subnets.push_back(tmp_item); - }; - std::sort(m_all_subnets.begin(), m_all_subnets.end(), subnet_comparator()); + } + sort(m_all_subnets.begin(), m_all_subnets.end(), subnet_comparator()); return m_all_subnets.size(); } @@ -87,13 +89,13 @@ bool ip_filter::is_ip_present(u32 ip_address) subnet_item tmp_fake_item; hton_bo(ip_address, tmp_fake_item); tmp_fake_item.subnet_mask = 0; - return std::binary_search(m_all_subnets.begin(), m_all_subnets.end(), &tmp_fake_item, ip_searcher()); + return binary_search(m_all_subnets.begin(), m_all_subnets.end(), &tmp_fake_item, ip_searcher()); } void ip_filter::unload() { for (subnets_coll_t::iterator i = m_all_subnets.begin(), // delete_data(m_all_subnets); - ie = m_all_subnets.end(); + ie = m_all_subnets.end(); i != ie; ++i) { xr_delete(*i); diff --git a/src/xrNetServer/ip_filter.h b/src/xrNetServer/ip_filter.h index c0548dafce1..0b40e95d445 100644 --- a/src/xrNetServer/ip_filter.h +++ b/src/xrNetServer/ip_filter.h @@ -1,3 +1,4 @@ +#pragma once #ifndef NET_SERVER_IP_FILTER #define NET_SERVER_IP_FILTER @@ -12,9 +13,11 @@ struct subnet_item u8 a3; u8 a4; }; + u32 data; } subnet_ip; // IN NBO !!! u32 subnet_mask; + subnet_item() { subnet_ip.data = 0; diff --git a/src/xrNetServer/stdafx.cpp b/src/xrNetServer/stdafx.cpp index 56501cb0874..cf524364f72 100644 --- a/src/xrNetServer/stdafx.cpp +++ b/src/xrNetServer/stdafx.cpp @@ -2,6 +2,3 @@ // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" - -#pragma comment(lib, "xrCore") -#pragma comment(lib, "dxguid.lib") diff --git a/src/xrNetServer/stdafx.h b/src/xrNetServer/stdafx.h index a58040d615a..d1dc37272ed 100644 --- a/src/xrNetServer/stdafx.h +++ b/src/xrNetServer/stdafx.h @@ -3,10 +3,6 @@ // are changed infrequently // // Third generation by Oles. - -#ifndef stdafxH -#define stdafxH - #pragma once #include "xrCore/xrCore.h" @@ -17,5 +13,3 @@ #pragma warning(pop) #include "NET_Shared.h" - -#endif // stdafxH