Support scanning ANSVIS servers device

This commit is contained in:
2026-05-23 18:03:22 +10:00
parent 4678d87e33
commit a2fa2c8ceb
5 changed files with 568 additions and 4 deletions
+420
View File
@@ -1309,5 +1309,425 @@ namespace ANSCENTER
}
return result;
}
} // namespace ANSCENTER
// ============================================================================
// ScanDevices — AIBOX / ANSVIS discovery on the local LAN
//
// Port of the AIBOX Flutter app's MulticastService
// (lib/src/core/network/multicast/multicast_service.dart). AIBOX boxes and
// ANSVIS servers answer the same UDP probe and the same /ServerApi HTTP
// endpoint, so one scan finds both. DebugView: filter "[ANSDISC]".
//
// Wire protocol:
// UDP: probe text "Hello, Multicast" -> 230.50.200.150:58839 and subnet
// broadcast :58839. Devices reply to UDP/58838 with
// "<a>:<b>:<deviceName>:<firmware>".
// HTTP: GET http://<ip>/ServerApi -> 200 + JSON with
// {"OK": true, "Version": "<firmware>"}.
//
// Implementation: a UDP listener thread + a periodic UDP sender + a 64-way
// HTTP sweep populate one mutex-guarded map. After `timeoutMs` the map is
// converted to a deduplicated vector and returned.
// ============================================================================
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <winhttp.h>
#include <mutex>
#include <condition_variable>
#include <unordered_map>
#include <chrono>
#include <queue>
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "winhttp.lib")
namespace {
// ---- Protocol constants (mirror AIBOX MulticastService) -----------------
constexpr const char* kMulticastGroup = "230.50.200.150";
constexpr unsigned short kProbePort = 58839; // device listens here
constexpr unsigned short kListenPort = 58838; // we listen here
constexpr const char* kProbeMessage = "Hello, Multicast";
constexpr int kMulticastTtl = 225;
constexpr int kHttpConcurrency = 64;
constexpr int kHttpConnectTimeoutMs = 700;
constexpr int kHttpProbeTimeoutMs = 2500;
constexpr int kUdpProbeIntervalMs = 2000;
constexpr const wchar_t* kHttpUserAgent = L"ANSUtilities-Scan/1.0";
constexpr const wchar_t* kHttpPath = L"/ServerApi";
// ---- Winsock init (refcounted; safe to call repeatedly) -----------------
struct WsaScope {
bool ok{false};
WsaScope() {
WSADATA d{};
ok = (WSAStartup(MAKEWORD(2, 2), &d) == 0);
}
~WsaScope() { if (ok) WSACleanup(); }
WsaScope(const WsaScope&) = delete;
WsaScope& operator=(const WsaScope&) = delete;
};
// ---- Local IPv4 interfaces ----------------------------------------------
struct LocalSubnet {
std::string prefix; // "192.168.1." (final dot included)
in_addr localAddr{};
in_addr broadcast{};
};
std::vector<LocalSubnet> EnumerateLocalSubnets() {
std::vector<LocalSubnet> out;
ULONG bufLen = 16 * 1024;
std::vector<char> buf(bufLen);
DWORD rc = GetAdaptersAddresses(AF_INET,
GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER,
nullptr, reinterpret_cast<PIP_ADAPTER_ADDRESSES>(buf.data()), &bufLen);
if (rc == ERROR_BUFFER_OVERFLOW) {
buf.resize(bufLen);
rc = GetAdaptersAddresses(AF_INET,
GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER,
nullptr, reinterpret_cast<PIP_ADAPTER_ADDRESSES>(buf.data()), &bufLen);
}
if (rc != NO_ERROR) {
ANS_DBG("ANSDISC", "GetAdaptersAddresses failed rc=%lu", static_cast<unsigned long>(rc));
return out;
}
auto* adapter = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(buf.data());
for (; adapter; adapter = adapter->Next) {
if (adapter->OperStatus != IfOperStatusUp) continue;
if (adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK) continue;
for (auto* ua = adapter->FirstUnicastAddress; ua; ua = ua->Next) {
if (!ua->Address.lpSockaddr || ua->Address.lpSockaddr->sa_family != AF_INET) continue;
auto* sin = reinterpret_cast<sockaddr_in*>(ua->Address.lpSockaddr);
// Skip APIPA 169.254.x.x — multicast on link-local rarely useful.
unsigned char b0 = reinterpret_cast<unsigned char*>(&sin->sin_addr)[0];
unsigned char b1 = reinterpret_cast<unsigned char*>(&sin->sin_addr)[1];
if (b0 == 169 && b1 == 254) continue;
if (b0 == 127) continue;
char ipStr[INET_ADDRSTRLEN] = {};
inet_ntop(AF_INET, &sin->sin_addr, ipStr, sizeof(ipStr));
std::string s(ipStr);
auto lastDot = s.find_last_of('.');
if (lastDot == std::string::npos) continue;
LocalSubnet net;
net.prefix = s.substr(0, lastDot + 1);
net.localAddr = sin->sin_addr;
inet_pton(AF_INET, (net.prefix + "255").c_str(), &net.broadcast);
out.push_back(net);
ANS_DBG("ANSDISC", "iface ip=%s subnet=%s/24", ipStr, net.prefix.c_str());
}
}
return out;
}
// ---- Parse "<a>:<b>:<name>:<firmware>" reply ----------------------------
void ParseUdpReply(const std::string& body, std::string& name, std::string& firmware) {
std::vector<std::string> parts;
size_t start = 0;
for (size_t i = 0; i <= body.size(); ++i) {
if (i == body.size() || body[i] == ':') {
parts.emplace_back(body.data() + start, i - start);
start = i + 1;
}
}
if (parts.size() > 3) { name = parts[2]; firmware = parts[3]; }
else { name = "Unknown"; firmware = "-"; }
}
// ---- Parse {"OK":true,"Version":"x"} ------------------------------------
// Tiny scan rather than a JSON dependency. Looks for the two keys with any
// amount of whitespace; rejects anything that doesn't say "OK":true.
bool ParseServerApiJson(const std::string& body, std::string& version) {
auto pos = body.find("\"OK\"");
if (pos == std::string::npos) return false;
pos = body.find(':', pos);
if (pos == std::string::npos) return false;
++pos;
while (pos < body.size() && (body[pos] == ' ' || body[pos] == '\t')) ++pos;
if (body.compare(pos, 4, "true") != 0) return false;
version.clear();
pos = body.find("\"Version\"");
if (pos == std::string::npos) { version = "-"; return true; }
pos = body.find(':', pos);
if (pos == std::string::npos) { version = "-"; return true; }
pos = body.find('"', pos);
if (pos == std::string::npos) { version = "-"; return true; }
++pos;
auto end = body.find('"', pos);
if (end == std::string::npos) { version = "-"; return true; }
version = body.substr(pos, end - pos);
if (version.empty()) version = "-";
return true;
}
// ---- Shared scan state --------------------------------------------------
enum SourceMask { kSrcMulticast = 1, kSrcSweep = 2 };
struct ScanState {
std::mutex mu;
std::unordered_map<std::string, ANSCENTER::ANSDeviceInfo> found;
std::atomic<bool> stop{false};
void merge(const std::string& ip, const std::string& name,
const std::string& firmware, int srcBit) {
std::lock_guard<std::mutex> lk(mu);
auto& d = found[ip];
if (d.ip.empty()) d.ip = ip;
// Prefer non-empty / non-"-" values, regardless of which source ran first.
if (!name.empty() && d.name.empty()) d.name = name;
if (!firmware.empty() && firmware != "-" &&
(d.firmware.empty() || d.firmware == "-")) d.firmware = firmware;
else if (!firmware.empty() && d.firmware.empty()) d.firmware = firmware;
d.source |= srcBit;
}
};
// ---- UDP listener thread -------------------------------------------------
// Single socket bound to 0.0.0.0:58838, joined to 230.50.200.150 on every
// local interface. Reads with a short timeout so it can poll `stop`.
void RunUdpListener(ScanState& state, const std::vector<LocalSubnet>& subnets) {
SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET) {
ANS_DBG("ANSDISC", "UDP socket() failed err=%d", WSAGetLastError());
return;
}
BOOL on = TRUE;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&on), sizeof(on));
setsockopt(s, SOL_SOCKET, SO_BROADCAST, reinterpret_cast<char*>(&on), sizeof(on));
sockaddr_in bindAddr{};
bindAddr.sin_family = AF_INET;
bindAddr.sin_port = htons(kListenPort);
bindAddr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(s, reinterpret_cast<sockaddr*>(&bindAddr), sizeof(bindAddr)) != 0) {
ANS_DBG("ANSDISC", "UDP bind :%u failed err=%d", kListenPort, WSAGetLastError());
closesocket(s);
return;
}
// Join multicast group on every interface so we receive replies on any path.
for (const auto& net : subnets) {
ip_mreq mreq{};
inet_pton(AF_INET, kMulticastGroup, &mreq.imr_multiaddr);
mreq.imr_interface = net.localAddr;
if (setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP,
reinterpret_cast<char*>(&mreq), sizeof(mreq)) != 0) {
ANS_DBG("ANSDISC", "IP_ADD_MEMBERSHIP on %.*s failed err=%d",
static_cast<int>(net.prefix.size() - 1), net.prefix.c_str(),
WSAGetLastError());
}
}
char buf[2048];
sockaddr_in from{};
int fromLen = sizeof(from);
while (!state.stop.load(std::memory_order_relaxed)) {
fd_set rfds; FD_ZERO(&rfds); FD_SET(s, &rfds);
timeval tv{ 0, 200 * 1000 }; // 200 ms
int sel = select(0, &rfds, nullptr, nullptr, &tv);
if (sel <= 0) continue;
int n = recvfrom(s, buf, sizeof(buf), 0,
reinterpret_cast<sockaddr*>(&from), &fromLen);
if (n <= 0) continue;
std::string body(buf, n);
if (body == kProbeMessage) continue; // our own echo
char ipStr[INET_ADDRSTRLEN] = {};
inet_ntop(AF_INET, &from.sin_addr, ipStr, sizeof(ipStr));
std::string name, fw;
ParseUdpReply(body, name, fw);
ANS_DBG("ANSDISC", "UDP reply from %s name=%s fw=%s",
ipStr, name.c_str(), fw.c_str());
state.merge(ipStr, name, fw, kSrcMulticast);
}
closesocket(s);
}
// ---- UDP sender thread ---------------------------------------------------
// Sends "Hello, Multicast" to the multicast group out each interface and
// to each subnet broadcast. Repeats every kUdpProbeIntervalMs.
void RunUdpSender(ScanState& state, const std::vector<LocalSubnet>& subnets) {
SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET) {
ANS_DBG("ANSDISC", "sender socket() failed err=%d", WSAGetLastError());
return;
}
BOOL on = TRUE;
setsockopt(s, SOL_SOCKET, SO_BROADCAST, reinterpret_cast<char*>(&on), sizeof(on));
int ttl = kMulticastTtl;
setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL,
reinterpret_cast<char*>(&ttl), sizeof(ttl));
sockaddr_in mc{};
mc.sin_family = AF_INET;
mc.sin_port = htons(kProbePort);
inet_pton(AF_INET, kMulticastGroup, &mc.sin_addr);
auto sendOnce = [&]() {
for (const auto& net : subnets) {
// Pin multicast egress to this interface so it leaves each NIC.
setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF,
reinterpret_cast<const char*>(&net.localAddr),
sizeof(net.localAddr));
sendto(s, kProbeMessage, static_cast<int>(strlen(kProbeMessage)), 0,
reinterpret_cast<sockaddr*>(&mc), sizeof(mc));
sockaddr_in bc{};
bc.sin_family = AF_INET;
bc.sin_port = htons(kProbePort);
bc.sin_addr = net.broadcast;
sendto(s, kProbeMessage, static_cast<int>(strlen(kProbeMessage)), 0,
reinterpret_cast<sockaddr*>(&bc), sizeof(bc));
}
};
sendOnce();
auto next = std::chrono::steady_clock::now() + std::chrono::milliseconds(kUdpProbeIntervalMs);
while (!state.stop.load(std::memory_order_relaxed)) {
auto now = std::chrono::steady_clock::now();
if (now >= next) {
sendOnce();
next = now + std::chrono::milliseconds(kUdpProbeIntervalMs);
} else {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
closesocket(s);
}
// ---- One synchronous HTTP probe via WinHTTP -----------------------------
// On AIBOX/ANSVIS reply: out_version is set and returns true. Otherwise false.
bool ProbeHttp(const std::string& ip, std::string& out_version) {
HINTERNET hSession = WinHttpOpen(kHttpUserAgent,
WINHTTP_ACCESS_TYPE_NO_PROXY,
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
if (!hSession) return false;
WinHttpSetTimeouts(hSession,
kHttpConnectTimeoutMs, kHttpConnectTimeoutMs,
kHttpProbeTimeoutMs, kHttpProbeTimeoutMs);
std::wstring host(ip.begin(), ip.end());
HINTERNET hConn = WinHttpConnect(hSession, host.c_str(),
INTERNET_DEFAULT_HTTP_PORT, 0);
if (!hConn) { WinHttpCloseHandle(hSession); return false; }
HINTERNET hReq = WinHttpOpenRequest(hConn, L"GET", kHttpPath,
nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
if (!hReq) {
WinHttpCloseHandle(hConn); WinHttpCloseHandle(hSession);
return false;
}
bool ok = false;
if (WinHttpSendRequest(hReq, L"Accept: application/json\r\n", static_cast<DWORD>(-1L),
WINHTTP_NO_REQUEST_DATA, 0, 0, 0) &&
WinHttpReceiveResponse(hReq, nullptr))
{
DWORD status = 0, statusSize = sizeof(status);
if (WinHttpQueryHeaders(hReq,
WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX, &status, &statusSize,
WINHTTP_NO_HEADER_INDEX) && status == 200)
{
std::string body;
DWORD avail = 0;
// Cap body at 64 KB — /ServerApi is a few hundred bytes.
while (body.size() < 65536 && WinHttpQueryDataAvailable(hReq, &avail) && avail) {
std::vector<char> buf(avail);
DWORD read = 0;
if (!WinHttpReadData(hReq, buf.data(), avail, &read)) break;
body.append(buf.data(), read);
}
ok = ParseServerApiJson(body, out_version);
}
}
WinHttpCloseHandle(hReq);
WinHttpCloseHandle(hConn);
WinHttpCloseHandle(hSession);
return ok;
}
// ---- HTTP sweep: 64-way worker pool consuming a queue of IPs ------------
void RunHttpSweep(ScanState& state, const std::vector<LocalSubnet>& subnets) {
std::queue<std::string> q;
for (const auto& net : subnets) {
for (int h = 1; h <= 254; ++h) {
q.push(net.prefix + std::to_string(h));
}
}
ANS_DBG("ANSDISC", "HTTP sweep targets=%zu workers=%d", q.size(), kHttpConcurrency);
std::mutex qmu;
auto worker = [&]() {
for (;;) {
if (state.stop.load(std::memory_order_relaxed)) return;
std::string ip;
{
std::lock_guard<std::mutex> lk(qmu);
if (q.empty()) return;
ip = std::move(q.front());
q.pop();
}
std::string ver;
if (ProbeHttp(ip, ver)) {
ANS_DBG("ANSDISC", "HTTP hit %s version=%s", ip.c_str(), ver.c_str());
state.merge(ip, std::string(), ver, kSrcSweep);
}
}
};
std::vector<std::thread> pool;
pool.reserve(kHttpConcurrency);
for (int i = 0; i < kHttpConcurrency; ++i) pool.emplace_back(worker);
for (auto& t : pool) t.join();
}
} // anonymous namespace
namespace ANSCENTER {
std::vector<ANSDeviceInfo> ANSUtilities::ScanDevices(int timeoutMs) {
if (timeoutMs < 500) timeoutMs = 500; // floor: enough for one UDP burst
ANS_DBG("ANSDISC", "ScanDevices: enter timeoutMs=%d", timeoutMs);
WsaScope wsa;
if (!wsa.ok) {
ANS_DBG("ANSDISC", "WSAStartup failed");
return {};
}
auto subnets = EnumerateLocalSubnets();
if (subnets.empty()) {
ANS_DBG("ANSDISC", "no usable IPv4 interfaces; aborting scan");
return {};
}
ScanState state;
std::thread tListen([&]{ RunUdpListener(state, subnets); });
std::thread tSend ([&]{ RunUdpSender (state, subnets); });
std::thread tSweep ([&]{ RunHttpSweep (state, subnets); });
std::this_thread::sleep_for(std::chrono::milliseconds(timeoutMs));
state.stop.store(true, std::memory_order_relaxed);
tListen.join();
tSend.join();
tSweep.join();
std::vector<ANSDeviceInfo> result;
{
std::lock_guard<std::mutex> lk(state.mu);
result.reserve(state.found.size());
for (auto& kv : state.found) result.push_back(std::move(kv.second));
}
ANS_DBG("ANSDISC", "ScanDevices: exit found=%zu", result.size());
return result;
}
} // namespace ANSCENTER