Support get global IP address

This commit is contained in:
2026-05-09 21:55:01 +10:00
parent cffdeb223b
commit eb1244c936
4 changed files with 414 additions and 0 deletions
+234
View File
@@ -7,6 +7,10 @@
#include <comdef.h>
#include <Wbemidl.h>
#include <dxgi.h>
#include <WinSock2.h> // inet_pton, in_addr — must precede windns.h
#include <WS2tcpip.h>
#include <windns.h>
#include <winhttp.h>
#include "Utility.h"
#include <hwinfo/PCIMapper.h>
@@ -1089,6 +1093,82 @@ private:
std::vector<GpuAdapter> _gpuAdaptersTemplate; // immutable after Init()
};
// ============================================================================
// Tiny synchronous HTTPS GET helper, used by GetPublicNetworkInformation().
// 5 s timeout on every WinHTTP step. Returns full response body in `body`,
// human-readable failure reason in `err`. No retries — caller decides.
// ============================================================================
struct WinHttpHandle {
HINTERNET h{nullptr};
explicit WinHttpHandle(HINTERNET hh) : h(hh) {}
~WinHttpHandle() { if (h) WinHttpCloseHandle(h); }
WinHttpHandle(const WinHttpHandle&) = delete;
WinHttpHandle& operator=(const WinHttpHandle&) = delete;
explicit operator bool() const { return h != nullptr; }
};
bool HttpsGetBody(const wchar_t* host, const wchar_t* path,
std::string& body, std::string& err) {
WinHttpHandle session(WinHttpOpen(L"ANSCENTER-LicensingSystem/1.0",
WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0));
if (!session) { err = "WinHttpOpen failed"; return false; }
// Resolve / connect / send / receive — each capped at 5 s.
WinHttpSetTimeouts(session.h, 5000, 5000, 5000, 5000);
WinHttpHandle conn(WinHttpConnect(session.h, host,
INTERNET_DEFAULT_HTTPS_PORT, 0));
if (!conn) { err = "WinHttpConnect failed"; return false; }
WinHttpHandle req(WinHttpOpenRequest(conn.h, L"GET", path,
nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_SECURE));
if (!req) { err = "WinHttpOpenRequest failed"; return false; }
if (!WinHttpSendRequest(req.h,
WINHTTP_NO_ADDITIONAL_HEADERS, 0,
WINHTTP_NO_REQUEST_DATA, 0, 0, 0)) {
err = "WinHttpSendRequest failed: " + std::to_string(GetLastError());
return false;
}
if (!WinHttpReceiveResponse(req.h, nullptr)) {
err = "WinHttpReceiveResponse failed: " + std::to_string(GetLastError());
return false;
}
DWORD status = 0, statusSize = sizeof(status);
if (!WinHttpQueryHeaders(req.h,
WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX, &status, &statusSize,
WINHTTP_NO_HEADER_INDEX)) {
err = "WinHttpQueryHeaders failed";
return false;
}
if (status != 200) {
err = "HTTP " + std::to_string(status);
return false;
}
DWORD avail = 0;
for (;;) {
if (!WinHttpQueryDataAvailable(req.h, &avail)) {
err = "WinHttpQueryDataAvailable failed";
return false;
}
if (avail == 0) break;
std::vector<char> buf(avail);
DWORD read = 0;
if (!WinHttpReadData(req.h, buf.data(), avail, &read)) {
err = "WinHttpReadData failed";
return false;
}
body.append(buf.data(), read);
}
if (body.empty()) { err = "empty response body"; return false; }
return true;
}
} // namespace
namespace ANSCENTER
@@ -1108,6 +1188,160 @@ namespace ANSCENTER
return info;
}
// ----------------------------------------------------------------------
// Public IPv4 via OpenDNS.
//
// `myip.opendns.com` is a special DNS name served by OpenDNS resolvers
// (208.67.222.222 / 208.67.220.220). The resolver returns an A record
// whose value IS the requesting client's public IP. One UDP/53 round
// trip — no HTTP, no third-party REST API, no database.
//
// Cached for 10 minutes; public IPs change rarely (typically only on
// ISP lease renewal or VPN toggle).
// ----------------------------------------------------------------------
std::string ANSLicenseHelper::GetPublicIPAddress()
{
static std::mutex mtx;
static std::string cachedIP;
static std::chrono::steady_clock::time_point lastFetch{};
std::lock_guard<std::mutex> lock(mtx);
const auto now = std::chrono::steady_clock::now();
if (!cachedIP.empty() &&
std::chrono::duration_cast<std::chrono::minutes>(now - lastFetch).count() < 10) {
return cachedIP;
}
// Pin the query to OpenDNS resolver1 — using the system's default
// resolver wouldn't work because most ISP resolvers don't honour
// the magic 'myip.opendns.com' name.
IP4_ARRAY dnsServers{};
dnsServers.AddrCount = 1;
DWORD opendns = 0;
if (inet_pton(AF_INET, "208.67.222.222", &opendns) != 1) {
ANS_DBG("PublicIP", "inet_pton failed for OpenDNS literal");
return cachedIP; // return whatever we had before, even if empty
}
dnsServers.AddrArray[0] = opendns;
PDNS_RECORDA records = nullptr;
const DNS_STATUS status = DnsQuery_A(
"myip.opendns.com",
DNS_TYPE_A,
DNS_QUERY_BYPASS_CACHE | DNS_QUERY_NO_HOSTS_FILE,
&dnsServers,
reinterpret_cast<PDNS_RECORD*>(&records),
nullptr);
std::string result;
if (status == ERROR_SUCCESS && records) {
for (PDNS_RECORDA r = records; r; r = r->pNext) {
if (r->wType == DNS_TYPE_A) {
in_addr a{};
a.S_un.S_addr = r->Data.A.IpAddress;
char buf[INET_ADDRSTRLEN] = {};
if (inet_ntop(AF_INET, &a, buf, sizeof(buf)) != nullptr)
result = buf;
break;
}
}
} else {
ANS_DBG("PublicIP", "DnsQuery_A status=0x%08lx", static_cast<unsigned long>(status));
}
if (records) DnsRecordListFree(records, DnsFreeRecordList);
if (!result.empty()) {
cachedIP = result;
lastFetch = now;
}
return result;
}
// ----------------------------------------------------------------------
// Public IP + IP-based geolocation via ipapi.co/json/.
//
// Single HTTPS GET; result cached 60 minutes on success, with a 60-second
// back-off on failure so a flapping network doesn't get hammered (every
// other call would otherwise wait for the 5 s WinHTTP timeout to expire).
//
// JSON keys we read (ipapi.co's documented schema):
// ip, country_name, country_code, region, city, org, timezone,
// latitude, longitude.
// ipapi.co reports rate-limit / blocked-IP errors as { "error": true,
// "reason": "..." } — those propagate into PublicNetworkInfo.error.
// ----------------------------------------------------------------------
PublicNetworkInfo ANSLicenseHelper::GetPublicNetworkInformation()
{
static std::mutex mtx;
static PublicNetworkInfo cache;
static std::chrono::steady_clock::time_point lastSuccess{};
static std::chrono::steady_clock::time_point lastAttempt{};
std::lock_guard<std::mutex> lock(mtx);
const auto now = std::chrono::steady_clock::now();
if (cache.ok &&
std::chrono::duration_cast<std::chrono::minutes>(now - lastSuccess).count() < 60) {
return cache;
}
// Failure backoff — don't retry within 60 s of a recent failed attempt.
if (!cache.ok &&
lastAttempt.time_since_epoch().count() != 0 &&
std::chrono::duration_cast<std::chrono::seconds>(now - lastAttempt).count() < 60) {
return cache;
}
lastAttempt = now;
PublicNetworkInfo info;
std::string body, err;
if (!HttpsGetBody(L"ipapi.co", L"/json/", body, err)) {
info.error = err;
ANS_DBG("PublicNet", "ipapi.co fetch failed: %s", err.c_str());
cache = info;
return info;
}
try {
boost::property_tree::ptree pt;
std::stringstream ss(body);
boost::property_tree::read_json(ss, pt);
if (pt.get<bool>("error", false)) {
info.error = pt.get<std::string>("reason", "ipapi.co reported an error");
ANS_DBG("PublicNet", "ipapi.co reported error: %s", info.error.c_str());
cache = info;
return info;
}
info.publicIP = pt.get<std::string>("ip", "");
info.country = pt.get<std::string>("country_name", "");
info.countryCode = pt.get<std::string>("country_code", "");
info.region = pt.get<std::string>("region", "");
info.city = pt.get<std::string>("city", "");
info.isp = pt.get<std::string>("org", "");
info.timezone = pt.get<std::string>("timezone", "");
info.latitude = pt.get<double> ("latitude", 0.0);
info.longitude = pt.get<double> ("longitude", 0.0);
info.ok = !info.publicIP.empty();
if (info.ok) {
cache = info;
lastSuccess = now;
ANS_DBG("PublicNet", "ipapi.co ok: ip=%s country=%s city=%s",
info.publicIP.c_str(), info.countryCode.c_str(), info.city.c_str());
} else {
info.error = "ipapi.co returned no IP field";
cache = info;
}
} catch (const std::exception& e) {
info.error = std::string("JSON parse: ") + e.what();
ANS_DBG("PublicNet", "JSON parse failed: %s", e.what());
cache = info;
}
return info;
}
EngineType ANSCENTER::ANSLicenseHelper::CheckHardwareInformation()
{
ANS_DBG("HWInfo", "CheckHardwareInformation: starting hardware detection");