Files
2026-11-23 03:28:32 +02:00

616 lines
25 KiB
C++

#include "priority_auth.hpp"
#ifndef _WIN32
#error This adapter is for native Windows only.
#endif
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <winhttp.h>
#include <shellapi.h>
#include <shlobj.h>
#include <bcrypt.h>
#include <wincrypt.h>
#include <array>
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
#include <string_view>
namespace gw::priority {
namespace {
class HttpHandle {
public:
explicit HttpHandle(HINTERNET value = nullptr) : value_(value) {}
~HttpHandle() { if (value_) WinHttpCloseHandle(value_); }
HttpHandle(HttpHandle const&) = delete;
HttpHandle& operator=(HttpHandle const&) = delete;
HINTERNET get() const { return value_; }
explicit operator bool() const { return value_ != nullptr; }
private:
HINTERNET value_;
};
class FileHandle {
public:
explicit FileHandle(HANDLE value = INVALID_HANDLE_VALUE) : value_(value) {}
~FileHandle() { if (value_ != INVALID_HANDLE_VALUE) CloseHandle(value_); }
FileHandle(FileHandle const&) = delete;
FileHandle& operator=(FileHandle const&) = delete;
HANDLE get() const { return value_; }
void close() {
if (value_ != INVALID_HANDLE_VALUE) CloseHandle(value_);
value_ = INVALID_HANDLE_VALUE;
}
explicit operator bool() const { return value_ != INVALID_HANDLE_VALUE; }
private:
HANDLE value_;
};
class Winsock {
public:
Winsock() : ready_(WSAStartup(MAKEWORD(2, 2), &data_) == 0) {}
~Winsock() { if (ready_) WSACleanup(); }
explicit operator bool() const { return ready_; }
private:
WSADATA data_{};
bool ready_;
};
class Socket {
public:
explicit Socket(SOCKET value = INVALID_SOCKET) : value_(value) {}
~Socket() { if (value_ != INVALID_SOCKET) closesocket(value_); }
Socket(Socket const&) = delete;
Socket& operator=(Socket const&) = delete;
SOCKET get() const { return value_; }
explicit operator bool() const { return value_ != INVALID_SOCKET; }
private:
SOCKET value_;
};
class WipeWide {
public:
explicit WipeWide(std::wstring& value) : value_(value) {}
~WipeWide() { SecureZeroMemory(value_.data(), value_.size() * sizeof(wchar_t)); }
WipeWide(WipeWide const&) = delete;
WipeWide& operator=(WipeWide const&) = delete;
private:
std::wstring& value_;
};
class WipeNarrow {
public:
explicit WipeNarrow(std::string& value) : value_(value) {}
~WipeNarrow() { SecureZeroMemory(value_.data(), value_.size()); }
WipeNarrow(WipeNarrow const&) = delete;
WipeNarrow& operator=(WipeNarrow const&) = delete;
private:
std::string& value_;
};
std::wstring wide_ascii(std::string_view value) {
std::wstring out;
out.reserve(value.size());
for (unsigned char c : value) {
if (c < 0x20 || c > 0x7e) return {};
out.push_back(static_cast<wchar_t>(c));
}
return out;
}
bool writable(SOCKET socket, int timeout_ms) {
fd_set set;
FD_ZERO(&set);
FD_SET(socket, &set);
timeval timeout{timeout_ms / 1000, (timeout_ms % 1000) * 1000};
return select(0, nullptr, &set, nullptr, &timeout) == 1;
}
bool readable(SOCKET socket, int timeout_ms) {
fd_set set;
FD_ZERO(&set);
FD_SET(socket, &set);
timeval timeout{timeout_ms / 1000, (timeout_ms % 1000) * 1000};
return select(0, &set, nullptr, nullptr, &timeout) == 1;
}
int readable_poll(SOCKET socket, int timeout_ms) {
fd_set set;
FD_ZERO(&set);
FD_SET(socket, &set);
timeval timeout{timeout_ms / 1000, (timeout_ms % 1000) * 1000};
return select(0, &set, nullptr, nullptr, &timeout);
}
void answer(SOCKET socket, int status) {
static constexpr char ok[] =
"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n"
"Cache-Control: no-store\r\nReferrer-Policy: no-referrer\r\n"
"Connection: close\r\n\r\n"
"<!doctype html><title>Octo sign-in complete</title><p>Return to the game.</p>";
static constexpr char failed[] =
"HTTP/1.1 400 Bad Request\r\nContent-Type: text/html; charset=utf-8\r\n"
"Cache-Control: no-store\r\nReferrer-Policy: no-referrer\r\n"
"Connection: close\r\n\r\n"
"<!doctype html><title>Octo sign-in failed</title><p>Close this tab and try again.</p>";
static constexpr char missing[] =
"HTTP/1.1 404 Not Found\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n";
const char* text = status == 200 ? ok : status == 400 ? failed : missing;
(void)send(socket, text, static_cast<int>(std::strlen(text)), 0);
}
bool random_state(std::string& result) {
std::array<unsigned char, 16> raw{};
if (BCryptGenRandom(nullptr, raw.data(), static_cast<ULONG>(raw.size()),
BCRYPT_USE_SYSTEM_PREFERRED_RNG) != 0) return false;
constexpr char hex[] = "0123456789abcdef";
result.reserve(32);
for (unsigned char b : raw) {
result += hex[b >> 4];
result += hex[b & 15];
}
SecureZeroMemory(raw.data(), raw.size());
return true;
}
bool real_reply(SOCKET socket, int timeout_ms) {
// Equivalent to the official launcher's bounded nonexistent-account probe.
constexpr char account[] = "OCTO-PROBE";
constexpr std::size_t name_bytes = sizeof(account) - 1;
std::array<unsigned char, 4 + 30 + name_bytes> packet{};
const unsigned body = 30 + static_cast<unsigned>(name_bytes);
packet[0] = 0; packet[1] = 3;
packet[2] = static_cast<unsigned char>(body); packet[3] = 0;
std::memcpy(packet.data() + 4, "WoW\0", 4);
packet[8] = 1; packet[9] = 12; packet[10] = 1;
packet[11] = 0xf3; packet[12] = 0x16; // 5875, little endian
std::memcpy(packet.data() + 13, "68x\0", 4);
std::memcpy(packet.data() + 17, "niW\0", 4);
std::memcpy(packet.data() + 21, "SUne", 4);
packet[33] = static_cast<unsigned char>(name_bytes);
std::memcpy(packet.data() + 34, account, name_bytes);
int sent = send(socket, reinterpret_cast<char const*>(packet.data()),
static_cast<int>(packet.size()), 0);
if (sent != static_cast<int>(packet.size())) return false;
std::array<unsigned char, 3> reply{};
int count = 0;
const ULONGLONG deadline = GetTickCount64() + static_cast<ULONGLONG>(timeout_ms);
while (count < static_cast<int>(reply.size())) {
const ULONGLONG now = GetTickCount64();
if (now >= deadline || !readable(socket, static_cast<int>(deadline - now))) return false;
int n = recv(socket, reinterpret_cast<char*>(reply.data()) + count,
static_cast<int>(reply.size()) - count, 0);
if (n <= 0) return false;
count += n;
}
return reply[0] == 0;
}
bool probe_one(sockaddr_in const& address, int timeout_ms) {
Socket socket(::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP));
if (!socket) return false;
u_long nonblocking = 1;
if (ioctlsocket(socket.get(), FIONBIO, &nonblocking)) return false;
int connected = connect(socket.get(), reinterpret_cast<sockaddr const*>(&address),
sizeof(address));
if (connected == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK) return false;
if (connected == SOCKET_ERROR) {
if (!writable(socket.get(), timeout_ms)) return false;
int error = 0, length = sizeof(error);
if (getsockopt(socket.get(), SOL_SOCKET, SO_ERROR,
reinterpret_cast<char*>(&error), &length) || error) return false;
}
nonblocking = 0;
if (ioctlsocket(socket.get(), FIONBIO, &nonblocking)) return false;
DWORD send_timeout = 500;
(void)setsockopt(socket.get(), SOL_SOCKET, SO_SNDTIMEO,
reinterpret_cast<char*>(&send_timeout), sizeof(send_timeout));
return real_reply(socket.get(), timeout_ms);
}
bool public_ipv4(sockaddr_in const& address) {
const std::uint32_t value = ntohl(address.sin_addr.s_addr);
const unsigned a = (value >> 24) & 255;
const unsigned b = (value >> 16) & 255;
const unsigned c = (value >> 8) & 255;
if (a == 0 || a == 10 || a == 127 || a >= 224 ||
(a == 100 && b >= 64 && b <= 127) ||
(a == 169 && b == 254) ||
(a == 172 && b >= 16 && b <= 31) ||
(a == 192 && b == 168) ||
(a == 192 && b == 0 && c == 0) ||
(a == 192 && b == 0 && c == 2) ||
(a == 198 && (b == 18 || b == 19)) ||
(a == 198 && b == 51 && c == 100) ||
(a == 203 && b == 0 && c == 113)) return false;
return true;
}
} // namespace
bool load_auth_state_file(std::wstring_view path, std::string& json) {
if (!json.empty()) SecureZeroMemory(json.data(), json.size());
json.clear();
if (path.empty() || path.size() >= MAX_PATH) return false;
const std::wstring path_buffer(path);
FileHandle file(CreateFileW(path_buffer.c_str(), GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, nullptr));
if (!file) return false;
BY_HANDLE_FILE_INFORMATION info{};
if (!GetFileInformationByHandle(file.get(), &info) ||
(info.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)))
return false;
LARGE_INTEGER bytes{};
if (!GetFileSizeEx(file.get(), &bytes) || bytes.QuadPart <= 0 || bytes.QuadPart > 16384)
return false;
json.resize(static_cast<std::size_t>(bytes.QuadPart));
DWORD read = 0;
if (!ReadFile(file.get(), json.data(), static_cast<DWORD>(json.size()), &read, nullptr) ||
read != json.size()) {
SecureZeroMemory(json.data(), json.size());
json.clear();
return false;
}
return true;
}
bool load_launcher_auth_state(std::string& json) {
PWSTR roaming = nullptr;
if (FAILED(SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &roaming)) ||
!roaming) return false;
struct FreePath {
PWSTR value;
~FreePath() { CoTaskMemFree(value); }
} free_path{roaming};
std::wstring path(roaming);
path += L"\\octo-launcher\\auth.json";
return load_auth_state_file(path, json);
}
namespace {
constexpr char priority_store_magic[] = "GWP1";
bool valid_saved_bearer(std::string_view token) {
if (token.empty() || token.size() > 4096) return false;
for (unsigned char c : token)
if (c < 0x21 || c > 0x7e || c == '"' || c == '\\') return false;
return true;
}
bool client_store_path(std::wstring& path, bool create_directory) {
path.clear();
PWSTR local = nullptr;
if (FAILED(SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, nullptr, &local)) ||
!local) return false;
struct FreePath {
PWSTR value;
~FreePath() { CoTaskMemFree(value); }
} free_path{local};
std::wstring directory(local);
directory += L"\\WoW-Hybrid";
if (directory.size() + 22 >= MAX_PATH) return false;
if (create_directory && !CreateDirectoryW(directory.c_str(), nullptr) &&
GetLastError() != ERROR_ALREADY_EXISTS) return false;
const DWORD attributes = GetFileAttributesW(directory.c_str());
if (attributes == INVALID_FILE_ATTRIBUTES ||
!(attributes & FILE_ATTRIBUTE_DIRECTORY) ||
(attributes & FILE_ATTRIBUTE_REPARSE_POINT)) return false;
path = directory + L"\\priority-session.dat";
return true;
}
bool store_protected_file(std::wstring_view path, std::string_view token,
std::atomic_bool const* cancel) {
if (path.empty() || path.size() >= MAX_PATH - 24 || !valid_saved_bearer(token) ||
(cancel && cancel->load(std::memory_order_acquire))) return false;
const std::wstring target(path);
const DWORD existing = GetFileAttributesW(target.c_str());
if (existing != INVALID_FILE_ATTRIBUTES &&
(existing & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT))) return false;
DATA_BLOB input{static_cast<DWORD>(token.size()),
reinterpret_cast<BYTE*>(const_cast<char*>(token.data()))};
DATA_BLOB encrypted{};
if (!CryptProtectData(&input, L"WoW-Hybrid Octo priority session", nullptr,
nullptr, nullptr, CRYPTPROTECT_UI_FORBIDDEN, &encrypted)) return false;
struct FreeBlob {
DATA_BLOB& value;
~FreeBlob() {
if (value.pbData) {
SecureZeroMemory(value.pbData, value.cbData);
LocalFree(value.pbData);
}
}
} free_encrypted{encrypted};
if (!encrypted.pbData || !encrypted.cbData || encrypted.cbData > 16380) return false;
std::array<unsigned char, 8> nonce{};
if (BCryptGenRandom(nullptr, nonce.data(), static_cast<ULONG>(nonce.size()),
BCRYPT_USE_SYSTEM_PREFERRED_RNG) != 0) return false;
constexpr wchar_t hex[] = L"0123456789abcdef";
std::wstring temporary = target + L".tmp-";
for (unsigned char byte : nonce) {
temporary += hex[byte >> 4];
temporary += hex[byte & 15];
}
SecureZeroMemory(nonce.data(), nonce.size());
FileHandle file(CreateFileW(temporary.c_str(), GENERIC_WRITE, 0, nullptr,
CREATE_NEW, FILE_ATTRIBUTE_HIDDEN | FILE_FLAG_WRITE_THROUGH,
nullptr));
if (!file) return false;
DWORD written = 0;
const bool written_all =
WriteFile(file.get(), priority_store_magic, 4, &written, nullptr) && written == 4 &&
WriteFile(file.get(), encrypted.pbData, encrypted.cbData, &written, nullptr) &&
written == encrypted.cbData && FlushFileBuffers(file.get());
// Close before replacing the destination.
file.close();
if (!written_all || (cancel && cancel->load(std::memory_order_acquire)) ||
!MoveFileExW(temporary.c_str(), target.c_str(),
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
DeleteFileW(temporary.c_str());
return false;
}
if (cancel && cancel->load(std::memory_order_acquire)) {
DeleteFileW(target.c_str());
return false;
}
return true;
}
} // namespace
bool load_protected_priority_token_file(std::wstring_view path, std::string& token) {
if (!token.empty()) SecureZeroMemory(token.data(), token.size());
token.clear();
if (path.empty() || path.size() >= MAX_PATH) return false;
const std::wstring target(path);
FileHandle file(CreateFileW(target.c_str(), GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, nullptr));
if (!file) return false;
BY_HANDLE_FILE_INFORMATION info{};
if (!GetFileInformationByHandle(file.get(), &info) ||
(info.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)))
return false;
LARGE_INTEGER size{};
if (!GetFileSizeEx(file.get(), &size) || size.QuadPart <= 4 || size.QuadPart > 16384)
return false;
std::string contents(static_cast<std::size_t>(size.QuadPart), '\0');
WipeNarrow wipe_contents(contents);
DWORD read = 0;
if (!ReadFile(file.get(), contents.data(), static_cast<DWORD>(contents.size()),
&read, nullptr) || read != contents.size() ||
std::memcmp(contents.data(), priority_store_magic, 4) != 0) return false;
DATA_BLOB input{static_cast<DWORD>(contents.size() - 4),
reinterpret_cast<BYTE*>(contents.data() + 4)};
DATA_BLOB decrypted{};
if (!CryptUnprotectData(&input, nullptr, nullptr, nullptr, nullptr,
CRYPTPROTECT_UI_FORBIDDEN, &decrypted)) return false;
struct FreeBlob {
DATA_BLOB& value;
~FreeBlob() {
if (value.pbData) {
SecureZeroMemory(value.pbData, value.cbData);
LocalFree(value.pbData);
}
}
} free_decrypted{decrypted};
if (!decrypted.pbData || !decrypted.cbData || decrypted.cbData > 4096) return false;
const std::string_view bearer(reinterpret_cast<char const*>(decrypted.pbData),
decrypted.cbData);
if (!valid_saved_bearer(bearer)) return false;
token.assign(bearer);
return true;
}
bool store_protected_priority_token_file(std::wstring_view path, std::string_view token) {
return store_protected_file(path, token, nullptr);
}
bool load_client_priority_token(std::string& token) {
std::wstring path;
return client_store_path(path, false) && load_protected_priority_token_file(path, token);
}
bool store_client_priority_token(std::string_view token, std::atomic_bool const* cancel) {
std::wstring path;
return client_store_path(path, true) && store_protected_file(path, token, cancel);
}
void delete_client_priority_token() {
std::wstring path;
if (client_store_path(path, false)) DeleteFileW(path.c_str());
}
WindowsHttp::WindowsHttp(std::string launcher_version) : version_(std::move(launcher_version)) {}
HttpReply WindowsHttp::post(std::string_view path, std::string_view json,
std::string_view bearer) {
HttpReply reply;
if ((path != "/api/launcher/session" && path != "/api/launcher/address") ||
json.size() > 8192 || bearer.size() > 4096) return reply;
for (char c : bearer) if (c == '\r' || c == '\n') return reply;
const std::wstring wide_path = wide_ascii(path), wide_version = wide_ascii(version_);
std::wstring wide_bearer = wide_ascii(bearer);
WipeWide wipe_bearer(wide_bearer);
if (wide_path.empty() || wide_version.empty() || (!bearer.empty() && wide_bearer.empty()))
return reply;
HttpHandle session(WinHttpOpen(L"WoW-Hybrid priority login", WINHTTP_ACCESS_TYPE_NO_PROXY,
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0));
if (!session) return reply;
if (!WinHttpSetTimeouts(session.get(), 5000, 5000, 10000, 10000)) return reply;
HttpHandle connection(WinHttpConnect(session.get(), L"octowow.st", INTERNET_DEFAULT_HTTPS_PORT, 0));
if (!connection) return reply;
HttpHandle request(WinHttpOpenRequest(connection.get(), L"POST", wide_path.c_str(), nullptr,
WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_SECURE));
if (!request) return reply;
DWORD disable = WINHTTP_DISABLE_REDIRECTS;
if (!WinHttpSetOption(request.get(), WINHTTP_OPTION_DISABLE_FEATURE, &disable, sizeof(disable)))
return reply;
std::wstring headers = L"Content-Type: application/json\r\nAccept: application/json\r\n"
L"X-Launcher-Version: " + wide_version + L"\r\n";
WipeWide wipe_headers(headers);
if (!wide_bearer.empty()) headers += L"Authorization: Bearer " + wide_bearer + L"\r\n";
std::string body(json);
const BOOL sent = WinHttpSendRequest(request.get(), headers.c_str(),
static_cast<DWORD>(headers.size()), body.data(),
static_cast<DWORD>(body.size()),
static_cast<DWORD>(body.size()), 0);
SecureZeroMemory(body.data(), body.size());
if (!sent || !WinHttpReceiveResponse(request.get(), nullptr)) return reply;
DWORD status = 0, bytes = sizeof(status);
if (!WinHttpQueryHeaders(request.get(), WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX, &status, &bytes,
WINHTTP_NO_HEADER_INDEX)) return reply;
reply.status = static_cast<int>(status);
std::array<char, 2048> chunk{};
while (reply.body.size() <= 16384) {
DWORD read = 0;
if (!WinHttpReadData(request.get(), chunk.data(), static_cast<DWORD>(chunk.size()), &read)) {
reply = {}; break;
}
if (!read) break;
reply.body.append(chunk.data(), read);
}
if (reply.body.size() > 16384) reply = {};
return reply;
}
bool WindowsBrowser::obtain(std::string_view authorize_url, std::string& code) {
code.clear();
if (authorize_url != "https://octowow.st/launcher/authorize") return false;
Winsock winsock;
if (!winsock) return false;
Socket listener(::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP));
if (!listener) return false;
sockaddr_in local{};
local.sin_family = AF_INET;
local.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
local.sin_port = 0;
if (bind(listener.get(), reinterpret_cast<sockaddr*>(&local), sizeof(local)) ||
listen(listener.get(), 4)) return false;
int length = sizeof(local);
if (getsockname(listener.get(), reinterpret_cast<sockaddr*>(&local), &length)) return false;
const unsigned port = ntohs(local.sin_port);
std::string state;
WipeNarrow wipe_state(state);
if (!port || !random_state(state)) return false;
std::string target = std::string(authorize_url) + "?lp=" + std::to_string(port) +
"&st=" + state;
WipeNarrow wipe_target(target);
std::wstring wide = wide_ascii(target);
WipeWide wipe_wide(wide);
if (cancel_ && cancel_->load(std::memory_order_acquire)) return false;
if (wide.empty() || reinterpret_cast<std::intptr_t>(ShellExecuteW(
nullptr, L"open", wide.c_str(), nullptr, nullptr, SW_SHOWNORMAL)) <= 32) return false;
const ULONGLONG deadline = GetTickCount64() + 300000;
while (GetTickCount64() < deadline) {
if (cancel_ && cancel_->load(std::memory_order_acquire)) return false;
const auto remaining = static_cast<int>(deadline - GetTickCount64());
const int ready = readable_poll(listener.get(), remaining < 100 ? remaining : 100);
if (ready < 0) return false;
if (!ready) continue;
if (cancel_ && cancel_->load(std::memory_order_acquire)) return false;
Socket peer(accept(listener.get(), nullptr, nullptr));
if (!peer) continue;
DWORD read_timeout = 2000;
(void)setsockopt(peer.get(), SOL_SOCKET, SO_RCVTIMEO,
reinterpret_cast<char*>(&read_timeout), sizeof(read_timeout));
std::string headers;
WipeNarrow wipe_headers(headers);
std::array<char, 1024> chunk{};
while (headers.size() < 4096 && headers.find("\r\n\r\n") == std::string::npos) {
int n = recv(peer.get(), chunk.data(), static_cast<int>(chunk.size()), 0);
if (n <= 0) break;
headers.append(chunk.data(), n);
}
const auto line_end = headers.find("\r\n");
if (line_end == std::string::npos || line_end > 2300 ||
headers.substr(0, 4) != "GET ") { answer(peer.get(), 404); continue; }
const auto version = headers.find(" HTTP/1.", 4);
if (version == std::string::npos || version > line_end) {
answer(peer.get(), 404); continue;
}
const std::string_view path(headers.data() + 4, version - 4);
if (path.substr(0, 9) != "/callback") { answer(peer.get(), 404); continue; }
const bool accepted = parse_callback_target(path, state, code);
answer(peer.get(), accepted ? 200 : 400);
if (accepted) return true;
/* A stale or unrelated loopback callback must not end the current
* authorization attempt before the matching browser response. */
}
return false;
}
bool WindowsProbe::challenge(std::string_view host, std::string& numeric_ipv4) {
numeric_ipv4.clear();
if (host.empty() || host.size() > 253) return false;
Winsock winsock;
if (!winsock) return false;
/* A numeric route came from Octo's authenticated address response. Probe
* it directly so DNS cannot replace the server-selected endpoint. */
if (host.size() < INET_ADDRSTRLEN) {
const std::string literal(host);
sockaddr_in address{};
address.sin_family = AF_INET;
address.sin_port = htons(3724);
if (inet_pton(AF_INET, literal.c_str(), &address.sin_addr) == 1) {
if (!public_ipv4(address) || !probe_one(address, 3500)) return false;
std::array<char, INET_ADDRSTRLEN> text{};
if (!inet_ntop(AF_INET, &address.sin_addr, text.data(), text.size()))
return false;
numeric_ipv4.assign(text.data());
return true;
}
}
const std::wstring target = wide_ascii(host);
if (target.empty()) return false;
ADDRINFOEXW hints{};
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
const ULONGLONG deadline = GetTickCount64() + 4000;
PADDRINFOEXW results = nullptr;
timeval dns_timeout{3, 0};
if (GetAddrInfoExW(target.c_str(), L"3724", NS_ALL, nullptr, &hints,
&results, &dns_timeout, nullptr, nullptr, nullptr)) return false;
int attempts = 0;
for (PADDRINFOEXW item = results; item && attempts < 2;
item = item->ai_next) {
const ULONGLONG now = GetTickCount64();
if (now >= deadline) break;
if (item->ai_family != AF_INET || !item->ai_addr ||
item->ai_addrlen < static_cast<int>(sizeof(sockaddr_in))) continue;
const sockaddr_in address = *reinterpret_cast<sockaddr_in*>(item->ai_addr);
if (!public_ipv4(address)) continue;
++attempts;
const int remaining = static_cast<int>(deadline - now);
if (!probe_one(address, remaining < 3500 ? remaining : 3500)) continue;
std::array<char, INET_ADDRSTRLEN> text{};
if (inet_ntop(AF_INET, &address.sin_addr, text.data(), text.size()))
numeric_ipv4.assign(text.data());
break;
}
FreeAddrInfoExW(results);
return !numeric_ipv4.empty();
}
std::uint64_t WindowsClock::monotonic_ms() const { return GetTickCount64(); }
} // namespace gw::priority