RCON system refactor and improvements

* Use game's CNetAdr RCON and socket creator.
* Add support for constructing host from [ip]:port format in the netconsole client.
* Pass 'netadr_t' parameter by reference to 'CSocketCreator::OnSocketAccepted'.
This commit is contained in:
Kawe Mazidjatari 2023-01-29 15:24:24 +01:00
parent 6df498e5c8
commit b98eee0268
20 changed files with 275 additions and 917 deletions

View File

@ -98,7 +98,7 @@
#include "tier0/basetypes.h"
#include "tier0/platform.h"
#include "tier0/commonmacros.h"
#if !defined(SDKLAUNCHER) && !defined (NETCONSOLE) && !defined(PLUGINSDK)
#if !defined(SDKLAUNCHER) && !defined(PLUGINSDK)
#include "tier0/dbg.h"
#endif // !SDKLAUNCHER && !NETCONSOLE && !PLUGINSDK

View File

@ -22,7 +22,6 @@
CRConClient::CRConClient()
: m_bInitialized(false)
, m_bConnEstablished(false)
, m_NetAdr2("localhost", "37015")
{
}
@ -94,41 +93,31 @@ bool CRConClient::Connect(void)
{
if (strlen(rcon_address->GetString()) > 0)
{
// Default is [127.0.0.1]:37015
m_NetAdr2.SetIPAndPort(rcon_address->GetString());
return Connect(rcon_address->GetString());
}
if (m_Socket.ConnectSocket(m_NetAdr2, true) == SOCKET_ERROR)
{
Warning(eDLL_T::CLIENT, "Connection to RCON server failed: (%s)\n", "SOCKET_ERROR");
return false;
}
DevMsg(eDLL_T::CLIENT, "Connected to: %s\n", m_NetAdr2.GetIPAndPort().c_str());
m_bConnEstablished = true;
return true;
return false;
}
//-----------------------------------------------------------------------------
// Purpose: connect to specified address and port
// Input : *svInAdr -
// *svInPort -
// Input : *szInAdr -
// Output : true if connection succeeds, false otherwise
//-----------------------------------------------------------------------------
bool CRConClient::Connect(const std::string& svInAdr, const std::string& svInPort)
bool CRConClient::Connect(const char* szInAdr)
{
if (!svInAdr.empty() && !svInPort.empty())
if (!m_Address.SetFromString(szInAdr, true))
{
// Default is [127.0.0.1]:37015
m_NetAdr2.SetIPAndPort(svInAdr, svInPort);
Warning(eDLL_T::CLIENT, "Failed to set RCON address: %s\n", szInAdr);
return false;
}
if (m_Socket.ConnectSocket(m_NetAdr2, true) == SOCKET_ERROR)
if (m_Socket.ConnectSocket(m_Address, true) == SOCKET_ERROR)
{
Warning(eDLL_T::CLIENT, "Connection to RCON server failed: (%s)\n", "SOCKET_ERROR");
return false;
}
DevMsg(eDLL_T::CLIENT, "Connected to: %s\n", m_NetAdr2.GetIPAndPort().c_str());
DevMsg(eDLL_T::CLIENT, "Connected to: %s\n", m_Address.ToString());
m_bConnEstablished = true;
return true;

View File

@ -1,5 +1,5 @@
#pragma once
#include "tier1/NetAdr2.h"
#include "tier1/NetAdr.h"
#include "tier2/SocketCreator.h"
#include "protoc/sv_rcon.pb.h"
#include "protoc/cl_rcon.pb.h"
@ -17,7 +17,7 @@ public:
void RunFrame(void);
bool Connect(void);
bool Connect(const std::string& svInAdr, const std::string& svInPort);
bool Connect(const char* szInAdr);
void Disconnect(void);
void Send(const std::string& svMessage) const;
@ -36,7 +36,7 @@ private:
bool m_bInitialized = false;
bool m_bConnEstablished = false;
CNetAdr2 m_NetAdr2;
netadr_t m_Address;
CSocketCreator m_Socket;
};

View File

@ -8,7 +8,7 @@
#include "tier1/cmd.h"
#include "tier1/cvar.h"
#include "tier1/IConVar.h"
#include "tier1/NetAdr2.h"
#include "tier1/NetAdr.h"
#include "tier2/socketcreator.h"
#include "engine/net.h"
#include "engine/server/sv_rcon.h"
@ -47,8 +47,10 @@ void CRConServer::Init(void)
}
}
m_Adr2.SetIPAndPort(rcon_address->GetString(), hostport->GetString());
m_Socket.CreateListenSocket(m_Adr2, false);
m_Address.SetFromString(hostip->GetString(), true);
m_Address.SetPort(htons(hostport->GetInt()));
m_Socket.CreateListenSocket(m_Address, false);
DevMsg(eDLL_T::SERVER, "Remote server access initialized\n");
m_bInitialized = true;
@ -78,8 +80,8 @@ void CRConServer::Think(void)
{
for (m_nConnIndex = nCount - 1; m_nConnIndex >= 0; m_nConnIndex--)
{
const CNetAdr2 netAdr2 = m_Socket.GetAcceptedSocketAddress(m_nConnIndex);
if (netAdr2.GetIP(true).compare(sv_rcon_whitelist_address->GetString()) != 0)
const netadr_t& netAdr = m_Socket.GetAcceptedSocketAddress(m_nConnIndex);
if (strcmp(netAdr.ToString(true), sv_rcon_whitelist_address->GetString()) != 0) // TODO: doesn't work
{
const CConnectedNetConsoleData* pData = m_Socket.GetAcceptedSocketData(m_nConnIndex);
if (!pData->m_bAuthorized)
@ -95,7 +97,7 @@ void CRConServer::Think(void)
{
if (!m_Socket.IsListening())
{
m_Socket.CreateListenSocket(m_Adr2, false);
m_Socket.CreateListenSocket(m_Address, false);
}
}
}
@ -349,10 +351,10 @@ void CRConServer::Authenticate(const cl_rcon::request& cl_request, CConnectedNet
}
else // Bad password.
{
const CNetAdr2 netAdr2 = m_Socket.GetAcceptedSocketAddress(m_nConnIndex);
const netadr_t netAdr = m_Socket.GetAcceptedSocketAddress(m_nConnIndex);
if (sv_rcon_debug->GetBool())
{
DevMsg(eDLL_T::SERVER, "Bad RCON password attempt from '%s'\n", netAdr2.GetIPAndPort().c_str());
DevMsg(eDLL_T::SERVER, "Bad RCON password attempt from '%s'\n", netAdr.ToString());
}
this->Send(pData->m_hSocket, this->Serialize(s_pszWrongPwMessage, "", sv_rcon::response_t::SERVERDATA_RESPONSE_AUTH, static_cast<int>(EGlobalContext_t::NETCON_S)));
@ -540,11 +542,11 @@ bool CRConServer::CheckForBan(CConnectedNetConsoleData* pData)
}
pData->m_bValidated = true;
CNetAdr2 netAdr2 = m_Socket.GetAcceptedSocketAddress(m_nConnIndex);
netadr_t netAdr = m_Socket.GetAcceptedSocketAddress(m_nConnIndex);
// Check if IP is in the banned list.
if (std::find(m_vBannedList.begin(), m_vBannedList.end(),
netAdr2.GetIP(true)) != m_vBannedList.end())
if (std::find(m_BannedList.begin(), m_BannedList.end(),
netAdr.ToString(true)) != m_BannedList.end())
{
return true;
}
@ -554,15 +556,15 @@ bool CRConServer::CheckForBan(CConnectedNetConsoleData* pData)
|| pData->m_nIgnoredMessage >= sv_rcon_maxignores->GetInt())
{
// Don't add white listed address to banned list.
if (netAdr2.GetIP(true).compare(sv_rcon_whitelist_address->GetString()) == 0)
if (strcmp(netAdr.ToString(true), sv_rcon_whitelist_address->GetString()) == 0)
{
pData->m_nFailedAttempts = 0;
pData->m_nIgnoredMessage = 0;
return false;
}
DevMsg(eDLL_T::SERVER, "Banned '%s' for RCON hacking attempts\n", netAdr2.GetIPAndPort().c_str());
m_vBannedList.push_back(netAdr2.GetIP(true));
DevMsg(eDLL_T::SERVER, "Banned '%s' for RCON hacking attempts\n", netAdr.ToString());
m_BannedList.push_back(netAdr.ToString(true));
return true;
}
return false;
@ -577,8 +579,8 @@ void CRConServer::CloseConnection(void) // NETMGR
if (pData->m_bAuthorized)
{
// Inform server owner when authenticated connection has been closed.
CNetAdr2 netAdr2 = m_Socket.GetAcceptedSocketAddress(m_nConnIndex);
DevMsg(eDLL_T::SERVER, "Net console '%s' closed RCON connection\n", netAdr2.GetIPAndPort().c_str());
netadr_t netAdr = m_Socket.GetAcceptedSocketAddress(m_nConnIndex);
DevMsg(eDLL_T::SERVER, "Net console '%s' closed RCON connection\n", netAdr.ToString());
}
m_Socket.CloseAcceptedSocket(m_nConnIndex);
}

View File

@ -1,5 +1,5 @@
#pragma once
#include "tier1/NetAdr2.h"
#include "tier1/NetAdr.h"
#include "tier2/socketcreator.h"
#include "protoc/sv_rcon.pb.h"
#include "protoc/cl_rcon.pb.h"
@ -49,9 +49,9 @@ private:
bool m_bInitialized;
int m_nConnIndex;
std::vector<std::string> m_vBannedList;
std::vector<std::string> m_BannedList;
std::string m_svPasswordHash;
CNetAdr2 m_Adr2;
netadr_t m_Address;
CSocketCreator m_Socket;
};

View File

@ -0,0 +1,120 @@
//===========================================================================//
//
// Purpose: stub implementation of 'tier0/dbg.cpp'
//
//===========================================================================//
#include "core/stdafx.h"
void LogStub(const char* fmt, ...)
{
static char szBuf[4096] = {};
{/////////////////////////////
va_list args{};
va_start(args, fmt);
vsnprintf(szBuf, sizeof(szBuf), fmt, args);
szBuf[sizeof(szBuf) - 1] = '\0';
va_end(args);
}/////////////////////////////
printf("%s", szBuf);
}
//-----------------------------------------------------------------------------
// Purpose: Netconsole log
// Input : context -
// *fmt - ... -
//-----------------------------------------------------------------------------
void NetMsg(EGlobalContext_t context, const char* fmt, ...)
{
static char szBuf[4096] = {};
{/////////////////////////////
va_list args{};
va_start(args, fmt);
vsnprintf(szBuf, sizeof(szBuf), fmt, args);
szBuf[sizeof(szBuf) - 1] = '\0';
va_end(args);
}/////////////////////////////
printf("%s", szBuf);
}
//-----------------------------------------------------------------------------
// Purpose: Show logs to all console interfaces
// Input : context -
// *fmt - ... -
//-----------------------------------------------------------------------------
void DevMsg(eDLL_T context, const char* fmt, ...)
{
static char szBuf[4096] = {};
{/////////////////////////////
va_list args{};
va_start(args, fmt);
vsnprintf(szBuf, sizeof(szBuf), fmt, args);
szBuf[sizeof(szBuf) - 1] = '\0';
va_end(args);
}/////////////////////////////
printf("%s", szBuf);
}
//-----------------------------------------------------------------------------
// Purpose: Print engine and SDK errors
// Input : context -
// *fmt - ... -
//-----------------------------------------------------------------------------
void Warning(eDLL_T context, const char* fmt, ...)
{
static char szBuf[4096] = {};
{/////////////////////////////
va_list args{};
va_start(args, fmt);
vsnprintf(szBuf, sizeof(szBuf), fmt, args);
szBuf[sizeof(szBuf) - 1] = '\0';
va_end(args);
}/////////////////////////////
printf("%s", szBuf);
}
//-----------------------------------------------------------------------------
// Purpose: Print engine and SDK errors
// Input : context -
// code -
// *fmt - ... -
//-----------------------------------------------------------------------------
void Error(eDLL_T context, const UINT code, const char* fmt, ...)
{
static char szBuf[4096] = {};
{/////////////////////////////
va_list args{};
va_start(args, fmt);
vsnprintf(szBuf, sizeof(szBuf), fmt, args);
szBuf[sizeof(szBuf) - 1] = '\0';
va_end(args);
}/////////////////////////////
printf("%s", szBuf);
if (code) // Terminate the process if an exit code was passed.
{
if (MessageBoxA(NULL, szBuf, "SDK Error", MB_ICONERROR | MB_OK))
{
TerminateProcess(GetCurrentProcess(), code);
}
}
}

View File

@ -6,7 +6,7 @@
#include "core/stdafx.h"
#include "core/termutil.h"
#include "tier1/NetAdr2.h"
#include "tier1/NetAdr.h"
#include "tier2/socketcreator.h"
#include "protoc/sv_rcon.pb.h"
#include "protoc/cl_rcon.pb.h"
@ -23,7 +23,6 @@ CNetCon::CNetCon(void)
, m_bQuitApplication(false)
, m_abPromptConnect(true)
, m_abConnEstablished(false)
, m_NetAdr2("localhost", "37015")
{
}
@ -45,7 +44,7 @@ bool CNetCon::Init(void)
if (nError != 0)
{
std::cerr << "Failed to start Winsock via WSAStartup: (" << NET_ErrorString(WSAGetLastError()) << ")" << std::endl;
Error(eDLL_T::NETCON, NO_ERROR, "%s - Failed to start Winsock: (%s)\n", __FUNCTION__, NET_ErrorString(WSAGetLastError()));
return false;
}
@ -75,7 +74,7 @@ bool CNetCon::Shutdown(void)
const int nError = ::WSACleanup();
if (nError != 0)
{
std::cerr << "Failed to stop Winsock via WSACleanup: (" << NET_ErrorString(WSAGetLastError()) << ")" << std::endl;
Error(eDLL_T::NETCON, NO_ERROR, "%s - Failed to stop Winsock: (%s)\n", __FUNCTION__, NET_ErrorString(WSAGetLastError()));
return false;
}
return true;
@ -172,7 +171,8 @@ void CNetCon::UserInput(void)
}
else // Setup connection from input.
{
if (!svInput.empty())
const std::vector<std::string> vSubStrings = StringSplit(svInput, ' ', 2);
if (vSubStrings.size() > 1)
{
const string::size_type nPos = svInput.find(' ');
if (nPos > 0
@ -189,9 +189,9 @@ void CNetCon::UserInput(void)
}
}
}
else // Initialize as [127.0.0.1]:37015.
else // Initialize as [ip]:port.
{
if (!this->Connect("", ""))
if (!this->Connect(svInput, ""))
{
m_abPromptConnect = true;
return;
@ -215,7 +215,7 @@ void CNetCon::RunFrame(void)
}
else if (m_abPromptConnect)
{
std::cout << "Enter <IP> <PORT>: ";
DevMsg(eDLL_T::NETCON, "Enter [<IP>]:<PORT> or <IP> <PORT>: ");
m_abPromptConnect = false;
}
}
@ -237,18 +237,33 @@ bool CNetCon::ShouldQuit(void) const
//-----------------------------------------------------------------------------
bool CNetCon::Connect(const std::string& svInAdr, const std::string& svInPort)
{
if (!svInAdr.empty() && !svInPort.empty())
if (!svInAdr.empty() && !svInPort.empty()) // Construct from ip port
{
// Default is [127.0.0.1]:37015
m_NetAdr2.SetIPAndPort(svInAdr, svInPort);
const string svFull = fmt::format("[{:s}]:{:s}", svInAdr, svInPort).c_str();
if (!m_Address.SetFromString(svFull.c_str(), true))
{
Warning(eDLL_T::CLIENT, "Failed to set RCON address: %s\n", svFull.c_str());
}
}
if (m_Socket.ConnectSocket(m_NetAdr2, true) == SOCKET_ERROR)
else if (!svInAdr.empty()) // construct from [ip]:port
{
std::cerr << "Failed to connect. Error: (SOCKET_ERROR). Verify IP and PORT." << std::endl;
if (!m_Address.SetFromString(svInAdr.c_str(), true))
{
Warning(eDLL_T::CLIENT, "Failed to set RCON address: %s\n", svInAdr.c_str());
}
}
else
{
Warning(eDLL_T::NETCON, "No IP address provided\n");
return false;
}
std::cout << "Connected to: " << m_NetAdr2.GetIPAndPort() << std::endl;
if (m_Socket.ConnectSocket(m_Address, true) == SOCKET_ERROR)
{
Error(eDLL_T::NETCON, NO_ERROR, "Failed to connect: error(%s); verify IP and PORT\n", "SOCKET_ERROR");
return false;
}
DevMsg(eDLL_T::NETCON, "Connected to: %s\n", m_Address.ToString());
m_abConnEstablished = true;
return true;
@ -280,7 +295,7 @@ void CNetCon::Send(const std::string& svMessage) const
ssSendBuf.str().data(), static_cast<int>(ssSendBuf.str().size()), MSG_NOSIGNAL);
if (nSendResult == SOCKET_ERROR)
{
std::cout << "Failed to send message: (SOCKET_ERROR)" << std::endl;
Error(eDLL_T::NETCON, NO_ERROR, "Failed to send message (%s)\n", "SOCKET_ERROR");
}
}
@ -301,7 +316,7 @@ void CNetCon::Recv(void)
if (nPendingLen <= 0 && m_abConnEstablished) // EOF or error.
{
this->Disconnect();
std::cout << "Server closed connection" << std::endl;
DevMsg(eDLL_T::NETCON, "Server closed connection\n");
return;
}
}//////////////////////////////////////////////
@ -315,12 +330,12 @@ void CNetCon::Recv(void)
if (nRecvLen == 0 && m_abConnEstablished) // Socket was closed.
{
this->Disconnect();
std::cout << "Server closed connection" << std::endl;
DevMsg(eDLL_T::NETCON, "Server closed connection\n");
break;
}
if (nRecvLen < 0 && !m_Socket.IsSocketBlocking())
{
std::cout << "RCON Cmd: recv error (" << NET_ErrorString(WSAGetLastError()) << ")" << std::endl;
Error(eDLL_T::NETCON, NO_ERROR, "RCON Cmd: recv error (%s)\n", NET_ErrorString(WSAGetLastError()));
break;
}
@ -372,7 +387,7 @@ void CNetCon::ProcessBuffer(const char* pRecvBuf, int nRecvLen, CConnectedNetCon
if (pData->m_nPayloadLen < 0 ||
pData->m_nPayloadLen > pData->m_RecvBuffer.max_size())
{
std::cout << "RCON Cmd: sync error (" << pData->m_nPayloadLen << ")" << std::endl;
Error(eDLL_T::NETCON, NO_ERROR, "RCON Cmd: sync error (%zu)\n", pData->m_nPayloadLen);
this->Disconnect(); // Out of sync (irrecoverable).
break;
@ -417,7 +432,7 @@ void CNetCon::ProcessMessage(const sv_rcon::response& sv_response) const
{
svOut.append(g_svReset);
}
std::cout << svOut;
NetMsg(EGlobalContext_t::GLOBAL_NONE, svOut.c_str());
break;
}
default:
@ -479,7 +494,7 @@ sv_rcon::response CNetCon::Deserialize(const std::string& svBuf) const
//-----------------------------------------------------------------------------
int main(int argc, char* argv[])
{
std::cout << "R5Reloaded TCP net console [Version " << NETCON_VERSION << "]" << std::endl;
DevMsg(eDLL_T::NETCON, "R5Reloaded TCP net console [Version %s]\n", NETCON_VERSION);
if (!NetConsole()->Init())
{

View File

@ -43,7 +43,7 @@ private:
std::atomic<bool> m_abPromptConnect;
std::atomic<bool> m_abConnEstablished;
CNetAdr2 m_NetAdr2;
CNetAdr m_Address;
CSocketCreator m_Socket;
mutable std::mutex m_Mutex;

View File

@ -1,659 +0,0 @@
//===========================================================================//
//
// Purpose: Protocol-agnostic implementation of the CNetAdr class.
//
//===========================================================================//
#include <core/stdafx.h>
#include <tier1/NetAdr2.h>
#ifndef NETCONSOLE
#include <engine/sys_utils.h> // !! IMPLEMENT 'Warning(..)' !!
#endif // !NETCONSOLE
//-----------------------------------------------------------------------------
// Purpose: constructor (use this when string contains <[IP]:PORT>).
// Input : svInAdr -
//-----------------------------------------------------------------------------
CNetAdr2::CNetAdr2(const string& svInAdr)
{
SetIPAndPort(svInAdr);
}
//-----------------------------------------------------------------------------
// Purpose: constructor (expects string format <IPv4/IPv6> <PORT>).
// Input : &svInAdr -
// &svInPort -
//-----------------------------------------------------------------------------
CNetAdr2::CNetAdr2(const string& svInAdr, const string& svInPort)
{
SetIPAndPort(svInAdr, svInPort);
}
//-----------------------------------------------------------------------------
// Purpose: destructor.
//-----------------------------------------------------------------------------
CNetAdr2::~CNetAdr2(void)
{
Clear();
}
//-----------------------------------------------------------------------------
// Purpose: sets the IP address.
// Input : *svInAdr -
//-----------------------------------------------------------------------------
void CNetAdr2::SetIP(const string& svInAdr)
{
m_svip = '[' + svInAdr + ']';
}
//-----------------------------------------------------------------------------
// Purpose: sets the port.
// Input : *svInPort -
//-----------------------------------------------------------------------------
void CNetAdr2::SetPort(const string& svInPort)
{
m_svip += ':' + svInPort;
}
//-----------------------------------------------------------------------------
// Purpose: sets the IP address and port.
// Input : *svInAdr -
//-----------------------------------------------------------------------------
void CNetAdr2::SetIPAndPort(string svInAdr)
{
SetType(netadrtype_t::NA_IP);
if (svInAdr.find("loopback") != string::npos || svInAdr.find("::1") != string::npos)
{
SetType(netadrtype_t::NA_LOOPBACK);
svInAdr = "[127.0.0.1]:" + GetPort(svInAdr);
}
else if (svInAdr.find("localhost") != string::npos)
{
svInAdr = "[127.0.0.1]:" + GetPort(svInAdr);
}
// [IP]:PORT
m_svip = svInAdr;
SetVersion();
if (GetVersion() == netadrversion_t::NA_V4)
{
reinterpret_cast<sockaddr_in*>(&m_sadr)->sin_port = htons(stoi(GetPort()));
}
else if (GetVersion() == netadrversion_t::NA_V6)
{
reinterpret_cast<sockaddr_in6*>(&m_sadr)->sin6_port = htons(stoi(GetPort()));
}
}
//-----------------------------------------------------------------------------
// Purpose: sets the IP address and port.
// Input : *svInAdr -
// *svInPort -
//-----------------------------------------------------------------------------
void CNetAdr2::SetIPAndPort(string svInAdr, string svInPort)
{
SetType(netadrtype_t::NA_IP);
if (svInAdr.compare("loopback") == 0 || svInAdr.compare("::1") == 0)
{
SetType(netadrtype_t::NA_LOOPBACK);
}
else if (svInAdr.compare("localhost") == 0)
{
svInAdr = "127.0.0.1";
}
if (svInAdr.find("[") != string::npos || svInAdr.find("]") != string::npos)
{
svInAdr = GetBase(svInAdr);
}
m_svip = "[" + svInAdr + "]:" + svInPort;
SetVersion();
if (m_version == netadrversion_t::NA_V4)
{
reinterpret_cast<sockaddr_in*>(&m_sadr)->sin_port = htons(stoi(GetPort()));
}
else if (m_version == netadrversion_t::NA_V6)
{
reinterpret_cast<sockaddr_in6*>(&m_sadr)->sin6_port = htons(stoi(GetPort()));
}
}
//-----------------------------------------------------------------------------
// Purpose: sets the type.
// Input : *type -
//-----------------------------------------------------------------------------
void CNetAdr2::SetType(const netadrtype_t& type)
{
m_type = type;
}
//-----------------------------------------------------------------------------
// Purpose: sets the IP version (IPv4/IPv6/INVALID) based on input.
//-----------------------------------------------------------------------------
void CNetAdr2::SetVersion(void)
{
if (inet_pton(reinterpret_cast<sockaddr_in*>(&m_sadr)->sin_family,
GetBase().c_str(), &reinterpret_cast<sockaddr_in*>(m_sadr)->sin_addr) &&
GetBase().find("::") == string::npos)
{
m_version = netadrversion_t::NA_V4;
return;
}
else if (inet_pton(reinterpret_cast<sockaddr_in6*>(&m_sadr)->sin6_family,
GetBase().c_str(), &reinterpret_cast<sockaddr_in6*>(m_sadr)->sin6_addr))
{
m_version = netadrversion_t::NA_V6;
return;
}
m_version = netadrversion_t::NA_INVALID;
}
//-----------------------------------------------------------------------------
// Purpose: sets IP address and port from sockaddr struct.
// Input : hSocket -
//-----------------------------------------------------------------------------
void CNetAdr2::SetFromSocket(const int& hSocket)
{
Clear();
m_type = netadrtype_t::NA_IP;
sockaddr_storage address{};
socklen_t namelen = sizeof(address);
if (getsockname(hSocket, (sockaddr*)&address, &namelen) == 0)
{
SetFromSockadr(&address);
}
}
//-----------------------------------------------------------------------------
// Purpose: sets fields based on 'sockaddr' input.
// Input : *s -
//-----------------------------------------------------------------------------
bool CNetAdr2::SetFromSockadr(sockaddr_storage* s)
{
if (reinterpret_cast<sockaddr_in*>(s)->sin_family == AF_INET)
{
char szAdrv4[INET_ADDRSTRLEN]{};
sockaddr_in* pAdrv4 = reinterpret_cast<sockaddr_in*>(s);
inet_ntop(pAdrv4->sin_family, &pAdrv4->sin_addr, szAdrv4, sizeof(sockaddr_in));
SetIPAndPort(szAdrv4, std::to_string(ntohs(pAdrv4->sin_port)));
return true;
}
else if (reinterpret_cast<sockaddr_in6*>(s)->sin6_family == AF_INET6)
{
char szAdrv6[INET6_ADDRSTRLEN]{};
sockaddr_in6* pAdrv6 = reinterpret_cast<sockaddr_in6*>(s);
inet_ntop(pAdrv6->sin6_family, &pAdrv6->sin6_addr, szAdrv6, sizeof(sockaddr_in6));
SetIPAndPort(szAdrv6, std::to_string(ntohs(pAdrv6->sin6_port)));
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: removes brackets and port from IP address.
//-----------------------------------------------------------------------------
string CNetAdr2::GetBase(void) const
{
static std::regex rx("[^\\[]*.(.*)(\\]).*");
std::smatch smRegexMatches;
std::regex_search(m_svip, smRegexMatches, rx);
if (smRegexMatches.empty())
{
return "127.0.0.1";
}
else
{
return smRegexMatches[1].str();
}
}
//-----------------------------------------------------------------------------
// Purpose: removes brackets and port from IP address.
// Input : svInAdr -
//-----------------------------------------------------------------------------
string CNetAdr2::GetBase(const string& svInAdr) const
{
static std::regex rx("[^\\[]*.(.*)(\\]).*");
std::smatch smRegexMatches;
std::regex_search(svInAdr, smRegexMatches, rx);
if (smRegexMatches.empty())
{
return "127.0.0.1";
}
else
{
return smRegexMatches[1].str();
}
}
//-----------------------------------------------------------------------------
// Purpose: gets the IP address.
// Input : bBaseOnly -
//-----------------------------------------------------------------------------
string CNetAdr2::GetIP(bool bBaseOnly = false) const
{
if (GetType() == netadrtype_t::NA_LOOPBACK)
{
return "loopback";
}
else if (GetType() == netadrtype_t::NA_IP)
{
if (bBaseOnly)
{
return GetBase();
}
else
{
return m_svip;
}
}
else
{
return "unknown";
}
}
//-----------------------------------------------------------------------------
// Purpose: removes brackets and IP address from port.
//-----------------------------------------------------------------------------
string CNetAdr2::GetPort(void) const
{
string svport = m_svip;
static std::regex rx(".*\\]:");
svport = std::regex_replace(svport, rx, "");
if (!IsValidPort(svport))
{
return "37015";
}
return svport;
}
//-----------------------------------------------------------------------------
// Purpose: removes brackets and IP address from port.
// Input : svInPort -
//-----------------------------------------------------------------------------
string CNetAdr2::GetPort(string svInPort) const
{
static std::regex rx(".*\\]:");
svInPort = std::regex_replace(svInPort, rx, "");
if (!IsValidPort(svInPort))
{
return "37015";
}
return svInPort;
}
//-----------------------------------------------------------------------------
// Purpose: returns the IP address and port.
//-----------------------------------------------------------------------------
string CNetAdr2::GetIPAndPort(void) const
{
return m_svip;
}
//-----------------------------------------------------------------------------
// Purpose: returns the address type.
//-----------------------------------------------------------------------------
netadrtype_t CNetAdr2::GetType(void) const
{
return m_type;
}
//-----------------------------------------------------------------------------
// Purpose: returns the IP version.
//-----------------------------------------------------------------------------
netadrversion_t CNetAdr2::GetVersion(void) const
{
return m_version;
}
//-----------------------------------------------------------------------------
// Purpose: splits IP address into parts by their delimiters.
// Output : string vector containing IP parts.
//-----------------------------------------------------------------------------
vector<string> CNetAdr2::GetParts(void) const
{
vector<string> results;
// Make sure we have a valid address.
if (m_version == netadrversion_t::NA_INVALID || m_type != netadrtype_t::NA_IP)
{
assert(m_version == netadrversion_t::NA_INVALID && "Invalid IP address for 'GetParts()'.");
return results;
}
string svIpAdr = m_svip, svDelim;
string::size_type prev_pos = 0, curr_pos = 0;
// 000.000.000.000 -> vparts.
if (m_version == netadrversion_t::NA_V4)
{
svDelim = '.';
}
// 0000:0000:0000:0000:0000:0000:0000:0000 -> vparts.
else if (m_version == netadrversion_t::NA_V6)
{
svDelim = ':';
StringReplace(svIpAdr, "::", ":");
}
while ((curr_pos = svIpAdr.find(svDelim, curr_pos)) != string::npos)
{
string substr(svIpAdr.substr(prev_pos, curr_pos - prev_pos));
results.push_back(substr);
prev_pos = ++curr_pos;
}
results.push_back(m_svip.substr(prev_pos, curr_pos - prev_pos));
return results;
}
//-----------------------------------------------------------------------------
// Purpose: returns the size of the network family struct.
//-----------------------------------------------------------------------------
int CNetAdr2::GetSize(void) const
{
if (GetVersion() == netadrversion_t::NA_V4)
{
return sizeof(sockaddr_in);
}
else if (GetVersion() == netadrversion_t::NA_V6)
{
return sizeof(sockaddr_in6);
}
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: returns the network family version.
//-----------------------------------------------------------------------------
int CNetAdr2::GetFamily(void) const
{
if (GetVersion() == netadrversion_t::NA_V4)
{
return AF_INET;
}
else if (GetVersion() == netadrversion_t::NA_V6)
{
return AF_INET6;
}
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: sets fields from 'sockaddr'.
// Input : *pSadr -
//-----------------------------------------------------------------------------
void CNetAdr2::ToSockadr(sockaddr_storage* pSadr) const
{
if (GetVersion() == netadrversion_t::NA_V4)
{
if (GetType() == netadrtype_t::NA_IP)
{
reinterpret_cast<sockaddr_in*>(pSadr)->sin_family = AF_INET;
reinterpret_cast<sockaddr_in*>(pSadr)->sin_port = htons(stoi(GetPort()));
inet_pton(AF_INET, GetBase().c_str(), &reinterpret_cast<sockaddr_in*>(pSadr)->sin_addr.s_addr);
}
else if (GetType() == netadrtype_t::NA_LOOPBACK)
{
reinterpret_cast<sockaddr_in*>(pSadr)->sin_family = AF_INET;
reinterpret_cast<sockaddr_in*>(pSadr)->sin_port = htons(stoi(GetPort()));
reinterpret_cast<sockaddr_in*>(pSadr)->sin_addr.s_addr = INADDR_LOOPBACK;
}
}
else if (GetVersion() == netadrversion_t::NA_V6)
{
if (GetType() == netadrtype_t::NA_IP)
{
reinterpret_cast<sockaddr_in6*>(pSadr)->sin6_family = AF_INET6;
reinterpret_cast<sockaddr_in6*>(pSadr)->sin6_port = htons(stoi(GetPort()));
inet_pton(AF_INET6, GetBase().c_str(), &reinterpret_cast<sockaddr_in6*>(pSadr)->sin6_addr);
}
else if (GetType() == netadrtype_t::NA_LOOPBACK)
{
reinterpret_cast<sockaddr_in6*>(pSadr)->sin6_family = AF_INET6;
reinterpret_cast<sockaddr_in6*>(pSadr)->sin6_port = htons(stoi(GetPort()));
reinterpret_cast<sockaddr_in6*>(pSadr)->sin6_addr = in6addr_loopback;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: sets fields from 'addrinfo'.
// Input : *pHint -
//-----------------------------------------------------------------------------
void CNetAdr2::ToAdrinfo(addrinfo* pHint) const
{
int results{ };
addrinfo hint{ }; // <-- TODO: Pass these instead.
if (GetVersion() == netadrversion_t::NA_V4)
{
hint.ai_flags = AI_PASSIVE;
hint.ai_family = AF_INET;
hint.ai_socktype = SOCK_STREAM;
hint.ai_protocol = IPPROTO_TCP;
results = getaddrinfo(GetBase().c_str(), GetPort().c_str(), &hint, &pHint);
if (results != 0)
{
WCHAR* wszError = gai_strerror(results);
_bstr_t bStr(wszError);
const char* pszError = bStr;
#ifndef NETCONSOLE
Warning(eDLL_T::ENGINE, "Address info translation failed (%s)\n", pszError);
#else
printf("Address info translation failed (%s)\n", pszError);
#endif // !NETCONSOLE
}
}
else if (GetVersion() == netadrversion_t::NA_V6)
{
hint.ai_flags = AI_PASSIVE;
hint.ai_family = AF_INET6;
hint.ai_socktype = SOCK_STREAM;
hint.ai_protocol = IPPROTO_TCP;
results = getaddrinfo(GetBase().c_str(), GetPort().c_str(), &hint, &pHint);
if (results != 0)
{
WCHAR* wszError = gai_strerror(results);
_bstr_t bStr(wszError);
const char* pszError = bStr;
#ifndef NETCONSOLE
Warning(eDLL_T::ENGINE, "Address info translation failed (%s)\n", pszError);
#else
printf("Address info translation failed (%s)\n", pszError);
#endif // !NETCONSOLE
}
}
}
//-----------------------------------------------------------------------------
// Purpose: returns true if this is a valid port string.
//-----------------------------------------------------------------------------
bool CNetAdr2::IsValidPort(const string& svInPort) const
{
for (char const& c : svInPort)
{
if (std::isdigit(c) == 0)
{
return false;
}
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose: returns true if we are localhost.
//-----------------------------------------------------------------------------
bool CNetAdr2::IsLocalhost(void) const
{
return (GetBase().compare("127.0.0.1") == NULL);
}
//-----------------------------------------------------------------------------
// Purpose: returns true if we use the loopback buffers.
//-----------------------------------------------------------------------------
bool CNetAdr2::IsLoopback(void) const
{
return (GetType() == netadrtype_t::NA_LOOPBACK);
}
//-----------------------------------------------------------------------------
// Purpose: check if address is reserved and not routable.
//-----------------------------------------------------------------------------
bool CNetAdr2::IsReservedAdr(void) const
{
if (GetType() == netadrtype_t::NA_LOOPBACK)
{
return true;
}
if (GetType() == netadrtype_t::NA_IP)
{
vector<string> ip_parts = GetParts();
int n0 = stoi(ip_parts[0]);
int n1 = stoi(ip_parts[1]);
if ((n0 == 10) || // 10.x.x.x is reserved
(n0 == 127) || // 127.x.x.x
(n0 == 172 && n1 >= 16 && n1 <= 31) || // 172.16.x.x - 172.31.x.x
(n0 == 192 && n1 >= 168)) // 192.168.x.x
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: compares IP for equality (IPv4/IPv6).
// Input : *netAdr2 -
// bBaseOnly -
// Output : true if equal, false otherwise.
//-----------------------------------------------------------------------------
bool CNetAdr2::CompareAdr(const CNetAdr2& netAdr2, bool bBaseOnly) const
{
if (netAdr2.GetType() != GetType())
{
return false;
}
if (GetType() == netadrtype_t::NA_LOOPBACK)
{
return true;
}
if (GetType() == netadrtype_t::NA_IP)
{
if (!bBaseOnly &&
(netAdr2.GetPort().compare(GetPort()) != NULL))
{
return false;
}
if (netAdr2.GetBase().compare(GetBase()) == NULL)
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: compares Class-B IP for equality.
// Input : *netAdr2 -
// Output : true if equal, false otherwise.
//-----------------------------------------------------------------------------
bool CNetAdr2::CompareClassBAdr(const CNetAdr2& netAdr2) const
{
if (netAdr2.m_version != netadrversion_t::NA_V4 && m_version != netadrversion_t::NA_V4)
{
return false;
}
if (netAdr2.GetType() != GetType())
{
return false;
}
if (GetType() == netadrtype_t::NA_LOOPBACK)
{
return true;
}
if (GetType() == netadrtype_t::NA_IP)
{
vector<string> v0 = netAdr2.GetParts();
vector<string> v1 = GetParts();
if (v0[0].compare(v1[0]) == NULL &&
v0[1].compare(v1[1]) == NULL)
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: compares Class-C IP for equality.
// Input : *netAdr2 -
// Output : true if equal, false otherwise.
//-----------------------------------------------------------------------------
bool CNetAdr2::CompareClassCAdr(const CNetAdr2& netAdr2) const
{
if (netAdr2.GetVersion() != netadrversion_t::NA_V4 && GetVersion() != netadrversion_t::NA_V4)
{
return false;
}
if (netAdr2.GetType() != GetType())
{
return false;
}
if (GetType() == netadrtype_t::NA_LOOPBACK)
{
return true;
}
if (GetType() == netadrtype_t::NA_IP)
{
vector<string> v0 = netAdr2.GetParts();
vector<string> v1 = GetParts();
if (v0[0].compare(v1[0]) == NULL &&
v0[1].compare(v1[1]) == NULL &&
v0[2].compare(v1[2]) == NULL)
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: clears IP address.
//-----------------------------------------------------------------------------
void CNetAdr2::Clear(void)
{
m_svip.clear();
m_type = netadrtype_t::NA_NULL;
m_version = netadrversion_t::NA_INVALID;
m_sadr = nullptr;
}

View File

@ -1,93 +0,0 @@
#pragma once
#include "tier1/bitbuf.h"
enum class netadrtype_t
{
NA_NULL = 0,
NA_LOOPBACK,
NA_IP,
};
enum class netadrversion_t
{
NA_INVALID = -1,
NA_V4 = 4,
NA_V6 = 6,
};
class CNetAdr2
{
public:
CNetAdr2(void) {};
CNetAdr2(const string& svInAdr);
CNetAdr2(const string& svInAdr, const string& svInPort);
~CNetAdr2(void);
void SetIP(const string& svInAdr);
void SetPort(const string& svInPort);
void SetIPAndPort(string svInAdr);
void SetIPAndPort(string svInAdr, string svInPort);
void SetType(const netadrtype_t& type);
void SetVersion(void);
void SetFromSocket(const int& hSocket);
bool SetFromSockadr(sockaddr_storage* s);
string GetIP(bool bBaseOnly) const;
string GetPort(void) const;
string GetPort(string svInPort) const;
string GetIPAndPort(void) const;
netadrtype_t GetType(void) const;
netadrversion_t GetVersion(void) const;
string GetBase(void) const;
string GetBase(const string& svInAdr) const;
vector<string> GetParts(void) const;
int GetSize(void) const;
int GetFamily(void) const;
void ToSockadr(sockaddr_storage* pSadr) const;
void ToAdrinfo(addrinfo* pHint) const;
bool IsValidPort(const string& svInPort) const;
bool IsLocalhost(void) const;
bool IsLoopback(void) const;
bool IsReservedAdr(void) const;
bool CompareAdr(const CNetAdr2& adr2, bool bBaseOnly) const;
bool CompareClassBAdr(const CNetAdr2& adr2) const;
bool CompareClassCAdr(const CNetAdr2& adr2) const;
void Clear(void);
private:
string m_svip;
netadrtype_t m_type;
netadrversion_t m_version;
sockaddr_storage* m_sadr;
};
class v_netadr_t // !TODO: Move this to 'NetAdr.h' instead and adjust existing class to new system.
{
public:
inline netadrtype_t GetType(void) const
{
return this->type;
}
inline void GetAddress(char* pchBuffer, uint32_t nBufferLen) const
{
assert(nBufferLen >= INET6_ADDRSTRLEN);
inet_ntop(AF_INET6, &this->adr, pchBuffer, nBufferLen);
}
inline uint16_t GetPort(void) const
{
return this->port;
}
inline bool IsReliable(void) const
{
return this->reliable;
}
netadrtype_t type{};
IN6_ADDR adr{};
uint16_t port{};
bool field_16{};
bool reliable{};
};

View File

@ -5,7 +5,7 @@
//===========================================================================//
#include <core/stdafx.h>
#include <tier1/NetAdr2.h>
#include <tier1/NetAdr.h>
#include <tier2/socketcreator.h>
#ifndef NETCONSOLE
#include <engine/sys_utils.h>
@ -51,11 +51,7 @@ void CSocketCreator::ProcessAccept(void)
{
if (!IsSocketBlocking())
{
#ifndef NETCONSOLE
Error(eDLL_T::ENGINE, NO_ERROR, "Socket ProcessAccept Error: %s\n", NET_ErrorString(WSAGetLastError()));
#else
printf("Socket ProcessAccept Error: %s\n", NET_ErrorString(WSAGetLastError()));
#endif // !NETCONSOLE
Error(eDLL_T::ENGINE, NO_ERROR, "%s - Error: %s\n", __FUNCTION__, NET_ErrorString(WSAGetLastError()));
}
return;
}
@ -66,10 +62,10 @@ void CSocketCreator::ProcessAccept(void)
return;
}
CNetAdr2 netAdr2;
netAdr2.SetFromSockadr(&inClient);
netadr_t netAdr;
netAdr.SetFromSockadr(&inClient);
OnSocketAccepted(newSocket, netAdr2);
OnSocketAccepted(newSocket, netAdr);
}
//-----------------------------------------------------------------------------
@ -91,11 +87,7 @@ bool CSocketCreator::ConfigureListenSocket(int iSocket)
int results = ::ioctlsocket(iSocket, FIONBIO, (u_long*)&opt); // Non-blocking.
if (results == -1)
{
#ifndef NETCONSOLE
Warning(eDLL_T::ENGINE, "Socket accept 'ioctl(FIONBIO)' failed (%s)\n", NET_ErrorString(WSAGetLastError()));
#else
printf("Socket accept 'ioctl(FIONBIO)' failed (%s)\n", NET_ErrorString(WSAGetLastError()));
#endif // !NETCONSOLE
Warning(eDLL_T::ENGINE, "Socket accept 'ioctl(%s)' failed (%s)\n", "FIONBIO", NET_ErrorString(WSAGetLastError()));
return false;
}
return true;
@ -114,11 +106,7 @@ bool CSocketCreator::ConfigureConnectSocket(SocketHandle_t hSocket)
ret = ::ioctlsocket(hSocket, FIONBIO, reinterpret_cast<u_long*>(&opt)); // Non-blocking
if (ret == -1)
{
#ifndef NETCONSOLE
Warning(eDLL_T::ENGINE, "Socket ioctl(FIONBIO) failed (%s)\n", NET_ErrorString(WSAGetLastError()));
#else
printf("Socket ioctl(FIONBIO) failed (%s)\n", NET_ErrorString(WSAGetLastError()));
#endif // !NETCONSOLE
Warning(eDLL_T::ENGINE, "Socket ioctl(%s) failed (%s)\n", "FIONBIO", NET_ErrorString(WSAGetLastError()));
::closesocket(hSocket);
return false;
}
@ -132,14 +120,14 @@ bool CSocketCreator::ConfigureConnectSocket(SocketHandle_t hSocket)
//-----------------------------------------------------------------------------
// Purpose: bind to a TCP port and accept incoming connections
// Input : *netAdr2 -
// Input : *netAdr -
// bListenOnAllInterfaces -
// Output : true on success, failed otherwise
//-----------------------------------------------------------------------------
bool CSocketCreator::CreateListenSocket(const CNetAdr2& netAdr2, bool bListenOnAllInterfaces = false)
bool CSocketCreator::CreateListenSocket(const netadr_t& netAdr, bool bListenOnAllInterfaces)
{
CloseListenSocket();
m_ListenAddress = netAdr2;
m_ListenAddress = netAdr;
m_hListenSocket = ::socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
if (m_hListenSocket != INVALID_SOCKET)
@ -153,27 +141,21 @@ bool CSocketCreator::CreateListenSocket(const CNetAdr2& netAdr2, bool bListenOnA
sockaddr_storage sadr{};
m_ListenAddress.ToSockadr(&sadr);
int results = ::bind(m_hListenSocket, reinterpret_cast<sockaddr*>(&sadr), m_ListenAddress.GetSize());
int results = ::bind(m_hListenSocket, reinterpret_cast<sockaddr*>(&sadr), sizeof(sockaddr_in6));
if (results == -1)
{
#ifndef NETCONSOLE
Warning(eDLL_T::ENGINE, "Socket bind failed (%s)\n", NET_ErrorString(WSAGetLastError()));
#else
printf("Socket bind failed (%s)\n", NET_ErrorString(WSAGetLastError()));
#endif // !NETCONSOLE
CloseListenSocket();
return false;
}
results = ::listen(m_hListenSocket, SOCKET_TCP_MAX_ACCEPTS);
if (results == -1)
{
#ifndef NETCONSOLE
Warning(eDLL_T::ENGINE, "Socket listen failed (%s)\n", NET_ErrorString(WSAGetLastError()));
#else
printf("Socket listen failed (%s)\n", NET_ErrorString(WSAGetLastError()));
#endif // !NETCONSOLE
CloseListenSocket();
return false;
}
}
@ -194,25 +176,21 @@ void CSocketCreator::CloseListenSocket(void)
//-----------------------------------------------------------------------------
// Purpose: connect to the remote server
// Input : *netAdr2 -
// Input : *netAdr -
// bSingleSocker -
// Output : accepted socket index, SOCKET_ERROR (-1) if failed
//-----------------------------------------------------------------------------
int CSocketCreator::ConnectSocket(const CNetAdr2& netAdr2, bool bSingleSocket)
int CSocketCreator::ConnectSocket(const netadr_t& netAdr, bool bSingleSocket)
{
if (bSingleSocket)
{ // NOTE: Closing an accepted socket will re-index all the sockets with higher indices
CloseAllAcceptedSockets();
}
SocketHandle_t hSocket = ::socket(netAdr2.GetFamily(), SOCK_STREAM, IPPROTO_TCP);
SocketHandle_t hSocket = ::socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
if (hSocket == SOCKET_ERROR)
{
#ifndef NETCONSOLE
Warning(eDLL_T::ENGINE, "Unable to create socket (%s)\n", NET_ErrorString(WSAGetLastError()));
#else
printf("Unable to create socket (%s)\n", NET_ErrorString(WSAGetLastError()));
#endif // !NETCONSOLE
return SOCKET_ERROR;
}
@ -222,18 +200,15 @@ int CSocketCreator::ConnectSocket(const CNetAdr2& netAdr2, bool bSingleSocket)
}
struct sockaddr_storage s{};
netAdr2.ToSockadr(&s);
netAdr.ToSockadr(&s);
int results = ::connect(hSocket, reinterpret_cast<sockaddr*>(&s), netAdr2.GetSize());
int results = ::connect(hSocket, reinterpret_cast<sockaddr*>(&s), sizeof(sockaddr_in6));
if (results == SOCKET_ERROR)
{
if (!IsSocketBlocking())
{
#ifndef NETCONSOLE
Warning(eDLL_T::ENGINE, "Socket connection failed (%s)\n", NET_ErrorString(WSAGetLastError()));
#else
printf("Socket connection failed (%s)\n", NET_ErrorString(WSAGetLastError()));
#endif // !NETCONSOLE
::closesocket(hSocket);
return SOCKET_ERROR;
}
@ -247,16 +222,16 @@ int CSocketCreator::ConnectSocket(const CNetAdr2& netAdr2, bool bSingleSocket)
FD_ZERO(&writefds);
FD_SET(static_cast<u_int>(hSocket), &writefds);
if (::select(hSocket + 1, NULL, &writefds, NULL, &tv) < 1) // block for at most 1 second
if (::select(hSocket + 1, NULL, &writefds, NULL, &tv) < 1) // block for at most 1 second.
{
::closesocket(hSocket); // took too long to connect to, give up
::closesocket(hSocket); // took too long to connect to, give up.
return SOCKET_ERROR;
}
}
// TODO: CRConClient check if connected.
int nIndex = OnSocketAccepted(hSocket, netAdr2);
int nIndex = OnSocketAccepted(hSocket, netAdr);
return nIndex;
}
@ -272,18 +247,18 @@ void CSocketCreator::DisconnectSocket(void)
//-----------------------------------------------------------------------------
// Purpose: handles new TCP requests and puts them in accepted queue
// Input : hSocket -
// *netAdr2 -
// *netAdr -
// Output : accepted socket index, -1 if failed
//-----------------------------------------------------------------------------
int CSocketCreator::OnSocketAccepted(SocketHandle_t hSocket, CNetAdr2 netAdr2)
int CSocketCreator::OnSocketAccepted(SocketHandle_t hSocket, const netadr_t& netAdr)
{
AcceptedSocket_t pNewEntry;
AcceptedSocket_t newEntry;
pNewEntry.m_hSocket = hSocket;
pNewEntry.m_Address = netAdr2;
pNewEntry.m_pData = new CConnectedNetConsoleData(hSocket);
newEntry.m_hSocket = hSocket;
newEntry.m_Address = netAdr;
newEntry.m_pData = new CConnectedNetConsoleData(hSocket);
m_hAcceptedSockets.push_back(pNewEntry);
m_hAcceptedSockets.push_back(newEntry);
int nIndex = static_cast<int>(m_hAcceptedSockets.size()) - 1;
return nIndex;
@ -362,9 +337,9 @@ SocketHandle_t CSocketCreator::GetAcceptedSocketHandle(int nIndex) const
//-----------------------------------------------------------------------------
// Purpose: returns accepted socket address
// Input : nIndex -
// Output : const CNetAdr2&
// Output : const netadr_t&
//-----------------------------------------------------------------------------
const CNetAdr2& CSocketCreator::GetAcceptedSocketAddress(int nIndex) const
const netadr_t& CSocketCreator::GetAcceptedSocketAddress(int nIndex) const
{
return m_hAcceptedSockets[nIndex].m_Address;
}

View File

@ -1,5 +1,5 @@
#pragma once
#include "tier1/netadr2.h"
#include "tier1/netadr.h"
#include "common/igameserverdata.h"
//-----------------------------------------------------------------------------
@ -17,13 +17,13 @@ public:
bool ConfigureListenSocket(int iSocket);
bool ConfigureConnectSocket(SocketHandle_t hSocket);
bool CreateListenSocket(const CNetAdr2& netAdr2, bool bListenOnAllInterfaces);
bool CreateListenSocket(const netadr_t& netAdr, bool bListenOnAllInterfaces = false);
void CloseListenSocket(void);
int ConnectSocket(const CNetAdr2& netAdr2, bool bSingleSocket);
int ConnectSocket(const netadr_t& netAdr, bool bSingleSocket);
void DisconnectSocket(void);
int OnSocketAccepted(SocketHandle_t hSocket, CNetAdr2 netAdr2);
int OnSocketAccepted(SocketHandle_t hSocket, const netadr_t& netAdr);
void CloseAcceptedSocket(int nIndex);
void CloseAllAcceptedSockets(void);
@ -33,22 +33,20 @@ public:
int GetAcceptedSocketCount(void) const;
SocketHandle_t GetAcceptedSocketHandle(int nIndex) const;
const CNetAdr2& GetAcceptedSocketAddress(int nIndex) const;
const netadr_t& GetAcceptedSocketAddress(int nIndex) const;
CConnectedNetConsoleData* GetAcceptedSocketData(int nIndex) const;
public:
struct AcceptedSocket_t
{
SocketHandle_t m_hSocket{};
CNetAdr2 m_Address{};
netadr_t m_Address{};
CConnectedNetConsoleData* m_pData = nullptr;
bool operator==(const AcceptedSocket_t& rhs) const { return (m_Address.CompareAdr(rhs.m_Address, false) == 0); }
};
std::vector<AcceptedSocket_t> m_hAcceptedSockets{};
SocketHandle_t m_hListenSocket {}; // Used to accept connections.
CNetAdr2 m_ListenAddress {}; // Address used to listen on.
std::vector<AcceptedSocket_t> m_hAcceptedSockets;
SocketHandle_t m_hListenSocket; // Used to accept connections.
netadr_t m_ListenAddress; // Address used to listen on.
private:
enum

View File

@ -140,7 +140,7 @@
<ClCompile Include="..\tier1\cvar.cpp" />
<ClCompile Include="..\tier1\generichash.cpp" />
<ClCompile Include="..\tier1\IConVar.cpp" />
<ClCompile Include="..\tier1\NetAdr2.cpp" />
<ClCompile Include="..\tier1\NetAdr.cpp" />
<ClCompile Include="..\tier1\splitstring.cpp" />
<ClCompile Include="..\tier1\strtools.cpp" />
<ClCompile Include="..\tier1\utlbuffer.cpp" />
@ -570,7 +570,7 @@
<ClInclude Include="..\tier1\generichash.h" />
<ClInclude Include="..\tier1\IConVar.h" />
<ClInclude Include="..\tier1\mempool.h" />
<ClInclude Include="..\tier1\NetAdr2.h" />
<ClInclude Include="..\tier1\NetAdr.h" />
<ClInclude Include="..\tier1\strtools.h" />
<ClInclude Include="..\tier1\utlblockmemory.h" />
<ClInclude Include="..\tier1\utlbuffer.h" />

View File

@ -372,9 +372,6 @@
<ClCompile Include="..\tier2\socketcreator.cpp">
<Filter>sdk\tier2</Filter>
</ClCompile>
<ClCompile Include="..\tier1\NetAdr2.cpp">
<Filter>sdk\tier1</Filter>
</ClCompile>
<ClCompile Include="..\mathlib\sha256.cpp">
<Filter>sdk\mathlib</Filter>
</ClCompile>
@ -675,6 +672,9 @@
<ClCompile Include="..\tier2\curlutils.cpp">
<Filter>sdk\tier2</Filter>
</ClCompile>
<ClCompile Include="..\tier1\NetAdr.cpp">
<Filter>sdk\tier1</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\client\cdll_engine_int.h">
@ -1178,9 +1178,6 @@
<ClInclude Include="..\tier2\socketcreator.h">
<Filter>sdk\tier2</Filter>
</ClInclude>
<ClInclude Include="..\tier1\NetAdr2.h">
<Filter>sdk\tier1</Filter>
</ClInclude>
<ClInclude Include="..\mathlib\sha256.h">
<Filter>sdk\mathlib</Filter>
</ClInclude>
@ -1985,6 +1982,9 @@
<ClInclude Include="..\tier2\curlutils.h">
<Filter>sdk\tier2</Filter>
</ClInclude>
<ClInclude Include="..\tier1\NetAdr.h">
<Filter>sdk\tier1</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<Image Include="..\shared\resource\lockedserver.png">

View File

@ -495,7 +495,7 @@
<ClInclude Include="..\tier1\generichash.h" />
<ClInclude Include="..\tier1\IConVar.h" />
<ClInclude Include="..\tier1\mempool.h" />
<ClInclude Include="..\tier1\NetAdr2.h" />
<ClInclude Include="..\tier1\NetAdr.h" />
<ClInclude Include="..\tier1\strtools.h" />
<ClInclude Include="..\tier1\utlblockmemory.h" />
<ClInclude Include="..\tier1\utlbuffer.h" />
@ -643,7 +643,7 @@
<ClCompile Include="..\tier1\cvar.cpp" />
<ClCompile Include="..\tier1\generichash.cpp" />
<ClCompile Include="..\tier1\IConVar.cpp" />
<ClCompile Include="..\tier1\NetAdr2.cpp" />
<ClCompile Include="..\tier1\NetAdr.cpp" />
<ClCompile Include="..\tier1\splitstring.cpp" />
<ClCompile Include="..\tier1\strtools.cpp" />
<ClCompile Include="..\tier1\utlbuffer.cpp" />

View File

@ -630,9 +630,6 @@
<ClInclude Include="..\mathlib\swap.h">
<Filter>sdk\mathlib</Filter>
</ClInclude>
<ClInclude Include="..\tier1\NetAdr2.h">
<Filter>sdk\tier1</Filter>
</ClInclude>
<ClInclude Include="..\mathlib\sha256.h">
<Filter>sdk\mathlib</Filter>
</ClInclude>
@ -1386,6 +1383,9 @@
<ClInclude Include="..\tier2\curlutils.h">
<Filter>sdk\tier2</Filter>
</ClInclude>
<ClInclude Include="..\tier1\NetAdr.h">
<Filter>sdk\tier1</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\common\opcodes.cpp">
@ -1493,9 +1493,6 @@
<ClCompile Include="..\tier2\socketcreator.cpp">
<Filter>sdk\tier2</Filter>
</ClCompile>
<ClCompile Include="..\tier1\NetAdr2.cpp">
<Filter>sdk\tier1</Filter>
</ClCompile>
<ClCompile Include="..\mathlib\sha256.cpp">
<Filter>sdk\mathlib</Filter>
</ClCompile>
@ -1769,6 +1766,9 @@
<ClCompile Include="..\tier2\curlutils.cpp">
<Filter>sdk\tier2</Filter>
</ClCompile>
<ClCompile Include="..\tier1\NetAdr.cpp">
<Filter>sdk\tier1</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<None Include="..\Dedicated.def" />

View File

@ -158,7 +158,7 @@
<ClCompile Include="..\tier1\cvar.cpp" />
<ClCompile Include="..\tier1\generichash.cpp" />
<ClCompile Include="..\tier1\IConVar.cpp" />
<ClCompile Include="..\tier1\NetAdr2.cpp" />
<ClCompile Include="..\tier1\NetAdr.cpp" />
<ClCompile Include="..\tier1\splitstring.cpp" />
<ClCompile Include="..\tier1\strtools.cpp" />
<ClCompile Include="..\tier1\utlbuffer.cpp" />
@ -622,7 +622,7 @@
<ClInclude Include="..\tier1\generichash.h" />
<ClInclude Include="..\tier1\IConVar.h" />
<ClInclude Include="..\tier1\mempool.h" />
<ClInclude Include="..\tier1\NetAdr2.h" />
<ClInclude Include="..\tier1\NetAdr.h" />
<ClInclude Include="..\tier1\strtools.h" />
<ClInclude Include="..\tier1\utlblockmemory.h" />
<ClInclude Include="..\tier1\utlbuffer.h" />

View File

@ -387,9 +387,6 @@
<ClCompile Include="..\tier2\socketcreator.cpp">
<Filter>sdk\tier2</Filter>
</ClCompile>
<ClCompile Include="..\tier1\NetAdr2.cpp">
<Filter>sdk\tier1</Filter>
</ClCompile>
<ClCompile Include="..\mathlib\sha256.cpp">
<Filter>sdk\mathlib</Filter>
</ClCompile>
@ -738,6 +735,9 @@
<ClCompile Include="..\tier2\curlutils.cpp">
<Filter>sdk\tier2</Filter>
</ClCompile>
<ClCompile Include="..\tier1\NetAdr.cpp">
<Filter>sdk\tier1</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\client\cdll_engine_int.h">
@ -1244,9 +1244,6 @@
<ClInclude Include="..\tier2\socketcreator.h">
<Filter>sdk\tier2</Filter>
</ClInclude>
<ClInclude Include="..\tier1\NetAdr2.h">
<Filter>sdk\tier1</Filter>
</ClInclude>
<ClInclude Include="..\mathlib\sha256.h">
<Filter>sdk\mathlib</Filter>
</ClInclude>
@ -2150,6 +2147,9 @@
<ClInclude Include="..\tier2\curlutils.h">
<Filter>sdk\tier2</Filter>
</ClInclude>
<ClInclude Include="..\tier1\NetAdr.h">
<Filter>sdk\tier1</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<Image Include="..\shared\resource\lockedserver.png">

View File

@ -27,6 +27,7 @@
</ClCompile>
<ClCompile Include="..\core\termutil.cpp" />
<ClCompile Include="..\engine\net.cpp" />
<ClCompile Include="..\netconsole\dbg_stub.cpp" />
<ClCompile Include="..\netconsole\netconsole.cpp" />
<ClCompile Include="..\protoc\cl_rcon.pb.cc">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">NotUsing</PrecompiledHeader>
@ -41,7 +42,7 @@
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="..\public\utility\utility.cpp" />
<ClCompile Include="..\tier1\NetAdr2.cpp" />
<ClCompile Include="..\tier1\NetAdr.cpp" />
<ClCompile Include="..\tier2\socketcreator.cpp" />
</ItemGroup>
<ItemGroup>
@ -52,7 +53,8 @@
<ClInclude Include="..\protoc\cl_rcon.pb.h" />
<ClInclude Include="..\protoc\sv_rcon.pb.h" />
<ClInclude Include="..\public\utility\utility.h" />
<ClInclude Include="..\tier1\NetAdr2.h" />
<ClInclude Include="..\tier0\dbg.h" />
<ClInclude Include="..\tier1\NetAdr.h" />
<ClInclude Include="..\tier2\socketcreator.h" />
</ItemGroup>
<PropertyGroup Label="Globals">

View File

@ -26,11 +26,11 @@
<Filter Include="thirdparty\protobuf">
<UniqueIdentifier>{7c7da8dd-043a-46b7-9413-832924e4574e}</UniqueIdentifier>
</Filter>
<Filter Include="sdk\tier0">
<UniqueIdentifier>{7064c656-b1c1-4940-be0a-eeb46b78a221}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\tier1\NetAdr2.cpp">
<Filter>sdk\tier1</Filter>
</ClCompile>
<ClCompile Include="..\core\stdafx.cpp">
<Filter>core</Filter>
</ClCompile>
@ -55,11 +55,14 @@
<ClCompile Include="..\public\utility\utility.cpp">
<Filter>sdk\public</Filter>
</ClCompile>
<ClCompile Include="..\netconsole\dbg_stub.cpp">
<Filter>core</Filter>
</ClCompile>
<ClCompile Include="..\tier1\NetAdr.cpp">
<Filter>sdk\tier1</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\tier1\NetAdr2.h">
<Filter>sdk\tier1</Filter>
</ClInclude>
<ClInclude Include="..\core\stdafx.h">
<Filter>core</Filter>
</ClInclude>
@ -84,5 +87,11 @@
<ClInclude Include="..\public\utility\utility.h">
<Filter>sdk\public</Filter>
</ClInclude>
<ClInclude Include="..\tier0\dbg.h">
<Filter>sdk\tier0</Filter>
</ClInclude>
<ClInclude Include="..\tier1\NetAdr.h">
<Filter>sdk\tier1</Filter>
</ClInclude>
</ItemGroup>
</Project>