iw4x-client/src/Components/Modules/Node.cpp

398 lines
9.5 KiB
C++
Raw Normal View History

2022-02-27 07:53:44 -05:00
#include <STDInclude.hpp>
2018-10-09 04:53:15 -04:00
namespace Components
{
std::recursive_mutex Node::Mutex;
std::vector<Node::Entry> Node::Nodes;
2018-12-28 12:45:36 -05:00
bool Node::wasIngame = false;
2018-10-09 04:53:15 -04:00
bool Node::Entry::isValid()
{
return (this->lastResponse.has_value() && !this->lastResponse->elapsed(NODE_HALFLIFE * 2));
}
bool Node::Entry::isDead()
{
if (!this->lastResponse.has_value())
{
if (this->lastRequest.has_value() && this->lastRequest->elapsed(NODE_HALFLIFE))
{
return true;
}
}
else if(this->lastResponse->elapsed(NODE_HALFLIFE * 2) && this->lastRequest.has_value() && this->lastRequest->after(*this->lastResponse))
{
return true;
}
return false;
}
bool Node::Entry::requiresRequest()
{
return (!this->isDead() && (!this->lastRequest.has_value() || this->lastRequest->elapsed(NODE_HALFLIFE)));
}
void Node::Entry::sendRequest()
{
if (!this->lastRequest.has_value()) this->lastRequest.emplace(Utils::Time::Point());
this->lastRequest->update();
Session::Send(this->address, "nodeListRequest");
Node::SendList(this->address);
NODE_LOG("Sent request to %s\n", this->address.getCString());
}
void Node::Entry::reset()
{
// this->lastResponse.reset(); // This would invalidate the node, but maybe we don't want that?
this->lastRequest.reset();
}
2018-12-03 15:48:12 -05:00
json11::Json Node::Entry::to_json() const
{
return this->address.getString();
}
2018-10-09 04:53:15 -04:00
void Node::LoadNodeRemotePreset()
{
std::string nodes = Utils::Cache::GetFile("/iw4/nodes.txt");
if (nodes.empty()) return;
2022-02-26 17:50:53 -05:00
auto nodeList = Utils::String::Split(nodes, '\n');
2018-10-09 04:53:15 -04:00
for (auto& node : nodeList)
{
Utils::String::Replace(node, "\r", "");
node = Utils::String::Trim(node);
Node::Add(node);
}
}
void Node::LoadNodePreset()
{
Proto::Node::List list;
if (Monitor::IsEnabled())
{
std::string nodes = Utils::IO::ReadFile("players/nodes_default.dat");
if (nodes.empty() || !list.ParseFromString(Utils::Compression::ZLib::Decompress(nodes))) return;
}
else
{
FileSystem::File defaultNodes("nodes_default.dat");
if (!defaultNodes.exists() || !list.ParseFromString(Utils::Compression::ZLib::Decompress(defaultNodes.getBuffer()))) return;
}
for (int i = 0; i < list.nodes_size(); ++i)
{
const std::string& addr = list.nodes(i);
if (addr.size() == sizeof(sockaddr))
{
Node::Add(reinterpret_cast<sockaddr*>(const_cast<char*>(addr.data())));
}
}
}
void Node::LoadNodes()
{
Proto::Node::List list;
std::string nodes = Utils::IO::ReadFile("players/nodes.dat");
if (nodes.empty() || !list.ParseFromString(Utils::Compression::ZLib::Decompress(nodes))) return;
for (int i = 0; i < list.nodes_size(); ++i)
{
const std::string& addr = list.nodes(i);
if (addr.size() == sizeof(sockaddr))
{
Node::Add(reinterpret_cast<sockaddr*>(const_cast<char*>(addr.data())));
}
}
}
void Node::StoreNodes(bool force)
{
2022-05-03 19:03:11 -04:00
if (Dedicated::IsEnabled() && Dedicated::SVLanOnly.get<bool>()) return;
2018-10-09 04:53:15 -04:00
static Utils::Time::Interval interval;
if (!force && !interval.elapsed(1min)) return;
interval.update();
Proto::Node::List list;
Node::Mutex.lock();
for (auto& node : Node::Nodes)
{
if (node.isValid())
{
std::string* str = list.add_nodes();
sockaddr addr = node.address.getSockAddr();
str->append(reinterpret_cast<char*>(&addr), sizeof(addr));
}
}
Node::Mutex.unlock();
Utils::IO::WriteFile("players/nodes.dat", Utils::Compression::ZLib::Compress(list.SerializeAsString()));
}
void Node::Add(Network::Address address)
{
#ifndef DEBUG
if (address.isLocal() || address.isSelf()) return;
#endif
if (!address.isValid()) return;
std::lock_guard<std::recursive_mutex> _(Node::Mutex);
for (auto& session : Node::Nodes)
{
if (session.address == address) return;
}
Node::Entry node;
node.address = address;
Node::Nodes.push_back(node);
}
2018-12-02 12:17:45 -05:00
std::vector<Node::Entry> Node::GetNodes()
{
std::lock_guard<std::recursive_mutex> _(Node::Mutex);
return Node::Nodes;
}
2018-10-09 04:53:15 -04:00
void Node::RunFrame()
{
2022-05-03 19:03:11 -04:00
if (Dedicated::IsEnabled() && Dedicated::SVLanOnly.get<bool>()) return;
2018-10-09 04:53:15 -04:00
2022-05-10 07:22:36 -04:00
if (!Dedicated::IsEnabled())
2018-10-09 04:53:15 -04:00
{
2022-05-10 07:22:36 -04:00
if (ServerList::useMasterServer) return; // don't run node frame if master server is active
if (*Game::clcState > 0)
{
wasIngame = true;
return; // don't run while ingame because it can still cause lag spikes on lower end PCs
}
2018-10-09 04:53:15 -04:00
}
if (wasIngame) // our last frame we were ingame and now we aren't so touch all nodes
{
for (auto i = Node::Nodes.begin(); i != Node::Nodes.end();++i)
{
// clearing the last request and response times makes the
// dispatcher think its a new node and will force a refresh
i->lastRequest.reset();
i->lastResponse.reset();
}
wasIngame = false;
}
static Utils::Time::Interval frameLimit;
int interval = static_cast<int>(1000.0f / Dvar::Var("net_serverFrames").get<int>());
if (!frameLimit.elapsed(std::chrono::milliseconds(interval))) return;
frameLimit.update();
std::lock_guard<std::recursive_mutex> _(Node::Mutex);
Dvar::Var queryLimit("net_serverQueryLimit");
int sentRequests = 0;
for (auto i = Node::Nodes.begin(); i != Node::Nodes.end();)
{
if (i->isDead())
{
i = Node::Nodes.erase(i);
continue;
}
else if (sentRequests < queryLimit.get<int>() && i->requiresRequest())
{
++sentRequests;
i->sendRequest();
}
++i;
}
}
void Node::Synchronize()
{
std::lock_guard<std::recursive_mutex> _(Node::Mutex);
for (auto& node : Node::Nodes)
{
//if (node.isValid()) // Comment out to simulate 'syncnodes' behaviour
{
node.reset();
}
}
}
2018-12-17 08:29:18 -05:00
void Node::HandleResponse(Network::Address address, const std::string& data)
2018-10-09 04:53:15 -04:00
{
Proto::Node::List list;
if (!list.ParseFromString(data)) return;
NODE_LOG("Received response from %s\n", address.getCString());
std::lock_guard<std::recursive_mutex> _(Node::Mutex);
for (int i = 0; i < list.nodes_size(); ++i)
{
const std::string& addr = list.nodes(i);
if (addr.size() == sizeof(sockaddr))
{
Node::Add(reinterpret_cast<sockaddr*>(const_cast<char*>(addr.data())));
}
}
if (list.isnode() && (!list.port() || list.port() == address.getPort()))
{
if (!Dedicated::IsEnabled() && ServerList::IsOnlineList() && !ServerList::useMasterServer && list.protocol() == PROTOCOL)
2018-10-09 04:53:15 -04:00
{
NODE_LOG("Inserting %s into the serverlist\n", address.getCString());
ServerList::InsertRequest(address);
}
else
{
NODE_LOG("Dropping serverlist insertion for %s\n", address.getCString());
}
for (auto& node : Node::Nodes)
{
if (address == node.address)
{
if (!node.lastResponse.has_value()) node.lastResponse.emplace(Utils::Time::Point());
node.lastResponse->update();
node.data.protocol = list.protocol();
return;
}
}
Node::Entry entry;
entry.address = address;
entry.data.protocol = list.protocol();
entry.lastResponse.emplace(Utils::Time::Point());
Node::Nodes.push_back(entry);
}
}
2018-12-02 12:17:45 -05:00
2018-10-09 04:53:15 -04:00
void Node::SendList(Network::Address address)
{
std::lock_guard<std::recursive_mutex> _(Node::Mutex);
// need to keep the message size below 1404 bytes else recipient will just drop it
std::vector<std::string> nodeListReponseMessages;
for (size_t curNode = 0; curNode < Node::Nodes.size();)
2018-10-09 04:53:15 -04:00
{
Proto::Node::List list;
list.set_isnode(Dedicated::IsEnabled());
list.set_protocol(PROTOCOL);
list.set_port(Node::GetPort());
for (size_t i = 0; i < NODE_MAX_NODES_TO_SEND;)
2018-10-09 04:53:15 -04:00
{
if (curNode >= Node::Nodes.size())
break;
2018-10-09 04:53:15 -04:00
auto node = Node::Nodes.at(curNode++);
if (node.isValid())
{
std::string* str = list.add_nodes();
sockaddr addr = node.address.getSockAddr();
str->append(reinterpret_cast<char*>(&addr), sizeof(addr));
i++;
}
2018-10-09 04:53:15 -04:00
}
nodeListReponseMessages.push_back(list.SerializeAsString());
2018-10-09 04:53:15 -04:00
}
size_t i = 0;
for (auto& nodeListData : nodeListReponseMessages)
{
Scheduler::Once([nodeListData, i, address]()
{
NODE_LOG("Sending %d nodeListResponse length to %s\n", nodeListData.length(), address.getCString());
Session::Send(address, "nodeListResponse", nodeListData);
}, Scheduler::Pipeline::MAIN, NODE_SEND_RATE * i++);
}
2018-10-09 04:53:15 -04:00
}
unsigned short Node::GetPort()
{
if (Dvar::Var("net_natFix").get<bool>()) return 0;
return Network::GetPort();
}
Node::Node()
{
if (ZoneBuilder::IsEnabled()) return;
Dvar::Register<bool>("net_natFix", false, 0, "Fix node registration for certain firewalls/routers");
Scheduler::Loop([]
2018-10-09 04:53:15 -04:00
{
Node::StoreNodes(false);
2022-05-07 21:20:50 -04:00
}, Scheduler::Pipeline::MAIN);
2018-10-09 04:53:15 -04:00
Scheduler::Loop(Node::RunFrame, Scheduler::Pipeline::MAIN);
2018-10-09 04:53:15 -04:00
Session::Handle("nodeListResponse", Node::HandleResponse);
2018-12-17 08:29:18 -05:00
Session::Handle("nodeListRequest", [](Network::Address address, const std::string&)
2018-10-09 04:53:15 -04:00
{
Node::SendList(address);
});
// Load stored nodes
auto loadNodes = []()
{
Node::LoadNodePreset();
Node::LoadNodes();
};
if (Monitor::IsEnabled()) Network::OnStart(loadNodes);
2022-05-07 21:20:50 -04:00
else Scheduler::OnGameInitialized(loadNodes, Scheduler::Pipeline::MAIN);
2018-10-09 04:53:15 -04:00
2022-05-07 21:20:50 -04:00
Network::OnStart([]
2018-10-09 04:53:15 -04:00
{
2022-05-07 21:20:50 -04:00
std::thread([]
2018-10-09 04:53:15 -04:00
{
Node::LoadNodeRemotePreset();
}).detach();
});
Command::Add("listnodes", [](Command::Params*)
{
Logger::Print("Nodes: %d\n", Node::Nodes.size());
std::lock_guard<std::recursive_mutex> _(Node::Mutex);
for (auto& node : Node::Nodes)
{
Logger::Print("%s\t(%s)\n", node.address.getCString(), node.isValid() ? "Valid" : "Invalid");
}
});
Command::Add("addnode", [](Command::Params* params)
{
2022-03-17 14:50:20 -04:00
if (params->size() < 2) return;
2018-10-09 04:53:15 -04:00
Node::Add({ params->get(1) });
});
}
Node::~Node()
{
std::lock_guard<std::recursive_mutex> _(Node::Mutex);
Node::StoreNodes(true);
Node::Nodes.clear();
}
}