The gateway's product table already runs to 1009 ANSMIND and 1010 ANSGW. The licensing library stopped at 1008, so a real ANSMIND licence could not be named, deactivated or listed here, while every product name it did not recognise quietly became product 1009. With 1009 now a real product, that fallback would mint an ANSMIND trial for a typo. ANSPRODUCTS gains ANSMIND = 1009 and ANSGW = 1010, and both are added wherever the product table is spelled out: ActivateTrialLicense, DeactivateLicense, ActivateLicense, ActivateLicenseWithCustomHWID and ListLicenses, which now reports an ANSMIND and an ANSGW row like the gateway does. Unknown names no longer map to any id. ActivateTrialLicense returns 0, its existing failure value, instead of generating a key. ListLicenses skips the row. ActivateLicense and ActivateLicenseWithCustomHWID keep passing the name through as the registration name: they never assigned an id, the key's own validation data rejects a name it was not issued for, and the gateway resolves an unknown product the same way. The ANSVIS master-licence rule in LicenseVerification is untouched. Separately, the fallback loops in ANSUtilities, ANSAWSS3 and ANSLLM asked for product 1008 under the registration name "ANSSRT". The product is ANSTS, so a genuine ANSTS licence could never satisfy them. Only that string changes; the loops still stop at 1008. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2099 lines
94 KiB
C++
2099 lines
94 KiB
C++
#include "ANSUtilities.h"
|
|
#ifdef _WIN32
|
|
#include <windows.h>
|
|
#include <winevt.h> // EvtQuery / EvtRender for GetANSLoggerErrorEvents
|
|
#pragma comment(lib, "wevtapi.lib")
|
|
#endif
|
|
#include <iostream>
|
|
#include <CkFileAccess.h>
|
|
#include <CkAuthGoogle.h>
|
|
#include <CkSocket.h>
|
|
#include <CkGlobal.h>
|
|
#include <CkMailMan.h>
|
|
#include <CkEmail.h>
|
|
#include <CkMht.h>
|
|
#include <vector>
|
|
|
|
static bool ansutilityLicenceValid = false;
|
|
static std::once_flag ansutilityLicenseOnceFlag;
|
|
std::timed_mutex timeImageMutex;
|
|
|
|
namespace ANSCENTER
|
|
{
|
|
// Helper: detect if a std::string is actually UTF-16LE (e.g. from LabVIEW).
|
|
// Heuristic: length >= 4, even, and first printable ASCII char is followed by 0x00.
|
|
static bool IsLikelyUTF16LE(const std::string& str) {
|
|
if (str.size() < 4 || (str.size() % 2 != 0)) return false;
|
|
unsigned char b0 = static_cast<unsigned char>(str[0]);
|
|
unsigned char b1 = static_cast<unsigned char>(str[1]);
|
|
return (b0 >= 0x20 && b0 <= 0x7E && b1 == 0x00);
|
|
}
|
|
|
|
static void VerifyGlobalANSUltilityLicense(const std::string& licenseKey) {
|
|
try {
|
|
static const std::vector<std::pair<int, std::string>> licenseChecks = {
|
|
{1000, "ANNHUB-LV"},
|
|
{1001, "DLHUB-LV"},
|
|
{1002, "ODHUB-LV"},
|
|
{1003, "ANSVIS"},
|
|
{1004, "ANSFR"},
|
|
{1005, "ANSOCR"},
|
|
{1006, "ANSALPR"},
|
|
{1007, "ANSCV"},
|
|
{1008, "ANSTS"}
|
|
};
|
|
ansutilityLicenceValid = false;
|
|
for (const auto& [productId, productName] : licenseChecks) {
|
|
if (ANSCENTER::ANSLicenseHelper::LicenseVerification(licenseKey, productId, productName)) {
|
|
ansutilityLicenceValid = true;
|
|
break; // Stop at the first valid license
|
|
}
|
|
}
|
|
}
|
|
catch (const std::exception& e) {
|
|
ansutilityLicenceValid = false;
|
|
}
|
|
}
|
|
ANSUtilities::ANSUtilities() {
|
|
_unlockCode = "ANSDRC.CB1122026_MEQCIFwO1IFQCG0BhZwsXFO68QUU6mDB5uge4duOsqOJanEyAiAB67ahqnXin4SRy0vIegISgbFlpldmbuS5gbU21GYVqA==";// "ANSDRC.CB1082025_Ax6P3M7F8B3d";//
|
|
_fireBaseSessionToken = "";
|
|
_proxyHost = "";
|
|
_proxyPort = 0;
|
|
_proxyUsername = "";
|
|
_proxyPassword = "";
|
|
_bProxy = false;
|
|
}
|
|
void ANSUtilities::CheckLicense() {
|
|
std::lock_guard<std::recursive_mutex> lock(_mutex);
|
|
try {
|
|
// Check once globally
|
|
std::call_once(ansutilityLicenseOnceFlag, [this]() {
|
|
VerifyGlobalANSUltilityLicense(_licenseKey);
|
|
});
|
|
// Update this instance's local license flag
|
|
_isLicenseValid = ansutilityLicenceValid;
|
|
}
|
|
catch (const std::exception& e) {
|
|
this->_logger.LogFatal("ANSUtilities::CheckLicense. Error:", e.what(), __FILE__, __LINE__);
|
|
}
|
|
}
|
|
void ANSUtilities::CheckUnlockCode() {
|
|
std::lock_guard<std::recursive_mutex> lock(_mutex);
|
|
try {
|
|
CkGlobal glob;
|
|
_unlockCode = "ANSDRC.CB1122026_MEQCIFwO1IFQCG0BhZwsXFO68QUU6mDB5uge4duOsqOJanEyAiAB67ahqnXin4SRy0vIegISgbFlpldmbuS5gbU21GYVqA==";// "ANSDRC.CB1082025_Ax6P3M7F8B3d";
|
|
_isUnlockCodeValid = glob.UnlockBundle(_unlockCode.c_str());
|
|
|
|
if (!_isUnlockCodeValid) {
|
|
_logger.LogFatal("ANSUtilities::CheckUnlockCode", glob.lastErrorText(), __FILE__, __LINE__);
|
|
return;
|
|
}
|
|
|
|
int status = glob.get_UnlockStatus();
|
|
if (status != 2) {
|
|
_logger.LogDebug("ANSUtilities::CheckUnlockCode", "Unlocked in trial mode.", __FILE__, __LINE__);
|
|
}
|
|
}
|
|
catch (const std::exception& e) {
|
|
_logger.LogFatal("ANSUtilities::CheckUnlockCode", e.what(), __FILE__, __LINE__);
|
|
}
|
|
}
|
|
ANSUtilities::~ANSUtilities()
|
|
{
|
|
_fireBaseSessionToken = "";
|
|
}
|
|
bool ANSUtilities::Initialize(const std::string& licenseKey) {
|
|
std::lock_guard<std::recursive_mutex> lock(_mutex);
|
|
try {
|
|
_licenseKey = licenseKey;
|
|
CheckLicense();
|
|
CheckUnlockCode();
|
|
return _isLicenseValid && _isUnlockCodeValid;
|
|
}
|
|
catch (const std::exception& e) {
|
|
_logger.LogFatal("ANSUtilities::Initialize", e.what(), __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
|
|
}
|
|
bool ANSUtilities::SetServerProxy(const std::string& proxyHost, int proxyPort, const std::string& proxyUsername, const std::string& proxyPassword) {
|
|
std::lock_guard<std::recursive_mutex> lock(_mutex);
|
|
try {
|
|
_proxyHost = proxyHost;
|
|
_proxyPort = proxyPort;
|
|
_proxyUsername = proxyUsername;
|
|
_proxyPassword = proxyPassword;
|
|
_bProxy = false;
|
|
|
|
if (!_proxyHost.empty() && (_proxyPort > 0)) {
|
|
_bProxy = true;
|
|
}
|
|
else {
|
|
_bProxy = false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
catch (const std::exception& e) {
|
|
_logger.LogFatal("ANSUtilities::SetServerProxy", e.what(), __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
}
|
|
std::string ANSUtilities::GetFirebaseCloudMessageAcccessToken(std::string privateKey)
|
|
{
|
|
std::lock_guard<std::recursive_mutex> lock(_mutex);
|
|
if (!_isLicenseValid) {
|
|
this->_logger.LogFatal("ANSUtilities::GetFirebaseCloudMessageAcccessToken()", "Error: Invalid license key", __FILE__, __LINE__);
|
|
return "Error: Invalid license key";
|
|
}
|
|
|
|
if (!_isUnlockCodeValid) {
|
|
this->_logger.LogFatal("ANSUtilities::GetFirebaseCloudMessageAcccessToken()", "Error: Invalid unlock code", __FILE__, __LINE__);
|
|
return "Error: Invalid unlock code";
|
|
}
|
|
try {
|
|
|
|
auto currentTime = std::chrono::system_clock::now();
|
|
|
|
// Check if we need to generate a new token
|
|
bool needNewToken = false;
|
|
|
|
if (!tokenInitialized) {
|
|
std::cout << "First time calling getToken(), generating initial token..." << std::endl;
|
|
needNewToken = true;
|
|
}
|
|
else {
|
|
// Calculate time difference in seconds since token was generated
|
|
auto timeDiff = std::chrono::duration_cast<std::chrono::seconds>(currentTime - tokenGeneratedTime);
|
|
long secondsElapsed = timeDiff.count();
|
|
|
|
std::cout << "Time since token generated: " << secondsElapsed << " seconds" << std::endl;
|
|
|
|
if (secondsElapsed >= TOKEN_EXPIRY_SECONDS) {
|
|
std::cout << "Token expired (" << secondsElapsed << "s >= " << TOKEN_EXPIRY_SECONDS << "s), regenerating..." << std::endl;
|
|
needNewToken = true;
|
|
}
|
|
else {
|
|
long remainingTime = TOKEN_EXPIRY_SECONDS - secondsElapsed;
|
|
std::cout << "Token still valid, " << remainingTime << " seconds remaining" << std::endl;
|
|
}
|
|
}
|
|
if (needNewToken) {
|
|
CkFileAccess fac;
|
|
const char* jsonKey = "{"
|
|
"\"type\": \"service_account\","
|
|
"\"project_id\": \"ansaiboxpushnotifications\","
|
|
"\"private_key_id\": \"62f7485c308b9ea613866c24c98736fec498d47d\","
|
|
"\"private_key\": \"-----BEGIN PRIVATE KEY-----\\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDSwXb/N4vPkANa\\nA7nwOTxS9NVCup/9mIdyR7FRYJNV8uHY7699I8LCCvG5rIhWGZ/Rb4Z9ocJKuuj9\\nRelsjTDEWeBU/o8ip41Ru8K3KlOO25HIVDckyhbmfDzzlf8Ham1HhOUZmfDUfQ2d\\n5YoUXflqoCyvOi8aqUgfcP9uZuIpEhyQvjqDfY0d0B36NoXpilFE8IuIlBsnpfZn\\nYkeHs/Cl6CDaKxGeUZmrqinyMH5f7m4Nz30V5s8Xdl4WZdoYhVatn1or57Zjy/zl\\ng+4rWeHRbYrBUJlMb8/7IaaZ7KuDkh0awEFIDvLuNvjXkaGKJT33vxKSsaH4yrhg\\nYiR5OVY3AgMBAAECggEADiUS5f0l4ofhWbS/UXqd7FlnSMO6wivvB0H9ih8ntFCJ\\nTOSFTCpOw3Q1lgcY3WJ54fYQujTVk+togLsk9/af68W2cy3kkGhbaT1nS6DJG+Dr\\nr1zLmKoBkHWNJ7IM/EPt0qt+LtIwoipEdDD4K/bEqx3V8eq/R5RN9WJBmnjIPAZO\\nXYGtTBu66yTjMVX9AFqYGJwaW96mHAi3lI5Mso5wTmFA8tSBiWmiYgpDDUNzu+4w\\nPnbDJabMbv4xnC6UtiqLIvv+P3BWWyLz0bzZ7W9P2fGK9Rz04leTXZlNcfC/IIAr\\nXDPVZfF7E5Wici53Cwc/QnxoCVH9n9hqsyTTUrKYbQKBgQD9WuCLVZRwKnAsW2Wx\\nZjh8Z92aGjIoc/lJTYaFsYGT7Hx496izhmg18kUillUDe/L9gHuDJPIMv89irjV1\\n07jN+z+tANyFT+h/NHCSxreG8FDbo8F88snekMEsBym3CicE/P6aWVx+lIig8rPS\\nHAqA1WOwdFzto/rG4zFKIiajYwKBgQDU9LxgERHwoy8mt2U5h/hg4oiKlycFJCFV\\nsgEqhVFN7Cs8jlov4tJh9863tVeYYGSKrP1HS9dVUE+7VY2qgPbyAtR5QZeHIV+b\\nzMx8o4HVLN4ffmld+/mYiAzIQiQeZOoC0mczakQpRDE8sghQQoYLwEcKXcTkLr75\\nk1XIpT4cHQKBgQCmMSzGeZbrlQsMLdAhdHptMPzuj2yDmL/X0+EAZhYn4KMt/tdN\\nHEfTy16Kd67AoFge7l8XAe89ab0ycDBlYEMD62IzrDL7yBUtDEskHPJas912lo7f\\n1auSMcZliTVV+nTqEsM4oJHJ/sk5Oru2gepp5JCGOW6T/FMOkA3PIWPTHQKBgQCG\\n456Om0Fp03OCaphLoLzLYbJrVuL4drJGvcHPVTLy0K1yZhjqTBpGw9jEtLEPa79D\\nt9+W0YtMFtrqJn7diWLiWLiNNebtSU5uOYMtT8Rla04nVMMZLQoke8jc8EhAmFtB\\n/lQwVRdnrDIj6AEsFXci6mAVSN/2SUXegFzOAx0cYQKBgBYCGGKWd/EFvszO5VS6\\nnegR3fpx4GRShA4iWfbQhPcjPunKthUAUguN4m+FfQuSA6xaBsz+om9hRiSCHe2l\\nGio/U7z2QYznnl/furGXEhS6yE+u3cSN82N0PV/c4XY0DUqKycE6cx9GVTOmx7NP\\n897fh7f103RrGgIRivtM1g3g\\n-----END PRIVATE KEY-----\\n\","
|
|
"\"client_email\": \"firebase-adminsdk-tcw8f@ansaiboxpushnotifications.iam.gserviceaccount.com\","
|
|
"\"client_id\": \"108921284506387607836\","
|
|
"\"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\","
|
|
"\"token_uri\": \"https://oauth2.googleapis.com/token\","
|
|
"\"auth_provider_x509_cert_url\": \"https://www.googleapis.com/oauth2/v1/certs\","
|
|
"\"client_x509_cert_url\": \"https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-tcw8f%40ansaiboxpushnotifications.iam.gserviceaccount.com\","
|
|
"\"universe_domain\": \"googleapis.com\""
|
|
"}";
|
|
if (!_isLicenseValid) {
|
|
this->_logger.LogFatal("ANSUtilities::GetFirebaseCloudMessageAcccessToken()", "Error: Invalid license key", __FILE__, __LINE__);
|
|
_fireBaseSessionToken = "";
|
|
return "Error: Invalid license key";
|
|
}
|
|
if (!_isUnlockCodeValid) {
|
|
this->_logger.LogFatal("ANSUtilities::GetFirebaseCloudMessageAcccessToken()", "Error: Invalid unlock code", __FILE__, __LINE__);
|
|
_fireBaseSessionToken = "";
|
|
return "Error: Invalid unlock code";
|
|
}
|
|
if (privateKey != "62f7485c308b9ea613866c24c98736fec498d47d") {
|
|
this->_logger.LogFatal("ANSUtilities::GetFirebaseCloudMessageAcccessToken()", "Error: Invalid private key", __FILE__, __LINE__);
|
|
_fireBaseSessionToken = "";
|
|
return "Error: Invalid private key";
|
|
}
|
|
CkAuthGoogle gAuth;
|
|
gAuth.put_JsonKey(jsonKey);
|
|
gAuth.put_Scope("https://www.googleapis.com/auth/cloud-platform");
|
|
gAuth.put_ExpireNumSeconds(TOKEN_EXPIRY_SECONDS);
|
|
gAuth.put_SubEmailAddress("");
|
|
CkSocket tlsSock;
|
|
bool success = tlsSock.Connect("www.googleapis.com", 443, true, 5000);
|
|
if (success != true) {
|
|
this->_logger.LogFatal("ANSUtilities::GetFirebaseCloudMessageAcccessToken()", tlsSock.lastErrorText(), __FILE__, __LINE__);
|
|
_fireBaseSessionToken = "";
|
|
return std::string("Error:") + tlsSock.lastErrorText();
|
|
}
|
|
success = gAuth.ObtainAccessToken(tlsSock);
|
|
if (success != true) {
|
|
this->_logger.LogFatal("ANSUtilities::GetFirebaseCloudMessageAcccessToken()", gAuth.lastErrorText(), __FILE__, __LINE__);
|
|
_fireBaseSessionToken = "";
|
|
return std::string("Error:") + tlsSock.lastErrorText();
|
|
}
|
|
_fireBaseSessionToken = gAuth.accessToken();
|
|
tokenGeneratedTime = currentTime; // Reset the time when token is generated
|
|
tokenInitialized = true;
|
|
}
|
|
return _fireBaseSessionToken;
|
|
}
|
|
catch (std::exception& e) {
|
|
this->_logger.LogFatal("ANSUtilities::GetFirebaseCloudMessageAcccessToken()", e.what(), __FILE__, __LINE__);
|
|
_fireBaseSessionToken = "";
|
|
return "Error: " + std::string(e.what());
|
|
}
|
|
|
|
}
|
|
std::string ANSUtilities::CreateAWSSNSTopic(const std::string& topicName) {
|
|
std::lock_guard<std::recursive_mutex> lock(_mutex);
|
|
if (!_isUnlockCodeValid) {
|
|
_logger.LogFatal("ANSUtilities::CreateAWSSNSTopic", "Error: Invalid unlock code", __FILE__, __LINE__);
|
|
return "Error: Invalid unlock code";
|
|
}
|
|
|
|
if (!_isLicenseValid) {
|
|
_logger.LogFatal("ANSUtilities::CreateAWSSNSTopic", "Error: Invalid license key", __FILE__, __LINE__);
|
|
return "Error: Invalid license key";
|
|
}
|
|
|
|
try {
|
|
CkRest _rest;
|
|
_rest.AddQueryParam("Action", "CreateTopic");
|
|
_rest.AddQueryParam("Name", topicName.c_str());
|
|
|
|
const char* responseXml = _rest.fullRequestNoBody("GET", "/");
|
|
if (!_rest.get_LastMethodSuccess()) {
|
|
_logger.LogFatal("ANSUtilities::CreateAWSSNSTopic", _rest.lastErrorText(), __FILE__, __LINE__);
|
|
return "Error: " + std::string(_rest.lastErrorText());
|
|
}
|
|
|
|
if (_rest.get_ResponseStatusCode() != 200) {
|
|
_logger.LogError("ANSUtilities::CreateAWSSNSTopic", _rest.responseHeader(), __FILE__, __LINE__);
|
|
return "Error: " + std::string(_rest.responseHeader());
|
|
}
|
|
|
|
CkXml xml;
|
|
xml.LoadXml(responseXml);
|
|
return xml.chilkatPath("CreateTopicResult|TopicArn|*");
|
|
}
|
|
catch (const std::exception& e) {
|
|
_logger.LogFatal("ANSUtilities::CreateAWSSNSTopic", e.what(), __FILE__, __LINE__);
|
|
return "Error: " + std::string(e.what());
|
|
}
|
|
}
|
|
bool ANSUtilities::DeleteAWSSNSTopic(const std::string& topicARN) {
|
|
std::lock_guard<std::recursive_mutex> lock(_mutex);
|
|
if (!_isUnlockCodeValid) {
|
|
_logger.LogFatal("ANSUtilities::DeleteAWSSNSTopic", "Error: Invalid unlock code", __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
|
|
if (!_isLicenseValid) {
|
|
_logger.LogFatal("ANSUtilities::DeleteAWSSNSTopic", "Error: Invalid license key", __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
|
|
try {
|
|
CkRest _rest;
|
|
_rest.AddQueryParam("Action", "DeleteTopic");
|
|
_rest.AddQueryParam("TopicArn", topicARN.c_str());
|
|
|
|
const char* responseXml = _rest.fullRequestNoBody("GET", "/");
|
|
if (!_rest.get_LastMethodSuccess()) {
|
|
_logger.LogFatal("ANSUtilities::DeleteAWSSNSTopic", _rest.lastErrorText(), __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
|
|
if (_rest.get_ResponseStatusCode() != 200) {
|
|
_logger.LogError("ANSUtilities::DeleteAWSSNSTopic", _rest.responseHeader(), __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
catch (const std::exception& e) {
|
|
_logger.LogFatal("ANSUtilities::DeleteAWSSNSTopic", e.what(), __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
}
|
|
std::string ANSUtilities::SubcribeSMSPhoneNumber(const std::string& topicARN, const std::string& phoneNumber) {
|
|
std::lock_guard<std::recursive_mutex> lock(_mutex);
|
|
if (!_isUnlockCodeValid) {
|
|
_logger.LogFatal("ANSUtilities::SubscribeSMSPhoneNumber", "Error: Invalid unlock code", __FILE__, __LINE__);
|
|
return "Error: Invalid unlock code";
|
|
}
|
|
|
|
if (!_isLicenseValid) {
|
|
_logger.LogFatal("ANSUtilities::SubscribeSMSPhoneNumber", "Error: Invalid license key", __FILE__, __LINE__);
|
|
return "Error: Invalid license key";
|
|
}
|
|
|
|
try {
|
|
CkRest _rest;
|
|
_rest.AddQueryParam("Action", "Subscribe");
|
|
_rest.AddQueryParam("Endpoint", phoneNumber.c_str()); // Phone number in E.164 format
|
|
_rest.AddQueryParam("Protocol", "sms");
|
|
_rest.AddQueryParam("TopicArn", topicARN.c_str());
|
|
|
|
const char* responseXml = _rest.fullRequestNoBody("GET", "/");
|
|
if (!_rest.get_LastMethodSuccess()) {
|
|
_logger.LogError("ANSUtilities::SubscribeSMSPhoneNumber", _rest.lastErrorText(), __FILE__, __LINE__);
|
|
return "Error: " + std::string(_rest.lastErrorText());
|
|
}
|
|
|
|
if (_rest.get_ResponseStatusCode() != 200) {
|
|
_logger.LogError("ANSUtilities::SubscribeSMSPhoneNumber", _rest.responseHeader(), __FILE__, __LINE__);
|
|
return "Error: " + std::string(_rest.responseHeader());
|
|
}
|
|
|
|
CkXml xml;
|
|
xml.LoadXml(responseXml);
|
|
|
|
return xml.chilkatPath("SubscribeResult|SubscriptionArn|*");
|
|
}
|
|
catch (const std::exception& e) {
|
|
_logger.LogFatal("ANSUtilities::SubscribeSMSPhoneNumber", e.what(), __FILE__, __LINE__);
|
|
return "Error: " + std::string(e.what());
|
|
}
|
|
}
|
|
std::string ANSUtilities::SubscribeEmailAddress(const std::string& topicARN, const std::string& emailAddress) {
|
|
std::lock_guard<std::recursive_mutex> lock(_mutex);
|
|
if (!_isUnlockCodeValid) {
|
|
_logger.LogFatal("ANSUtilities::SubscribeEmailAddress", "Error: Invalid unlock code", __FILE__, __LINE__);
|
|
return "Error: Invalid unlock code";
|
|
}
|
|
|
|
if (!_isLicenseValid) {
|
|
_logger.LogFatal("ANSUtilities::SubscribeEmailAddress", "Error: Invalid license key", __FILE__, __LINE__);
|
|
return "Error: Invalid license key";
|
|
}
|
|
|
|
try {
|
|
CkRest _rest;
|
|
_rest.AddQueryParam("Action", "Subscribe");
|
|
_rest.AddQueryParam("Endpoint", emailAddress.c_str());
|
|
_rest.AddQueryParam("Protocol", "email");
|
|
_rest.AddQueryParam("TopicArn", topicARN.c_str());
|
|
|
|
const char* responseXml = _rest.fullRequestNoBody("GET", "/");
|
|
if (!_rest.get_LastMethodSuccess()) {
|
|
_logger.LogError("ANSUtilities::SubscribeEmailAddress", _rest.lastErrorText(), __FILE__, __LINE__);
|
|
return "Error: " + std::string(_rest.lastErrorText());
|
|
}
|
|
|
|
if (_rest.get_ResponseStatusCode() != 200) {
|
|
_logger.LogError("ANSUtilities::SubscribeEmailAddress", _rest.responseHeader(), __FILE__, __LINE__);
|
|
return "Error: " + std::string(_rest.responseHeader());
|
|
}
|
|
|
|
CkXml xml;
|
|
xml.LoadXml(responseXml);
|
|
return xml.chilkatPath("SubscribeResult|SubscriptionArn|*"); // Usually "pending confirmation"
|
|
}
|
|
catch (const std::exception& e) {
|
|
_logger.LogFatal("ANSUtilities::SubscribeEmailAddress", e.what(), __FILE__, __LINE__);
|
|
return "Error: " + std::string(e.what());
|
|
}
|
|
}
|
|
std::string ANSUtilities::SendMessageToTopic(const std::string& topicARN, const std::string& subjectContent, const std::string& messageContent) {
|
|
std::lock_guard<std::recursive_mutex> lock(_mutex);
|
|
if (!_isUnlockCodeValid) {
|
|
_logger.LogFatal("ANSUtilities::SendMessageToTopic", "Error: Invalid unlock code", __FILE__, __LINE__);
|
|
return "Error: Invalid unlock code";
|
|
}
|
|
|
|
if (!_isLicenseValid) {
|
|
_logger.LogFatal("ANSUtilities::SendMessageToTopic", "Error: Invalid license key", __FILE__, __LINE__);
|
|
return "Error: Invalid license key";
|
|
}
|
|
|
|
try {
|
|
CkRest _rest;
|
|
_rest.AddQueryParam("Action", "Publish");
|
|
_rest.AddQueryParam("TopicArn", topicARN.c_str());
|
|
_rest.AddQueryParam("Subject", subjectContent.c_str()); // Subject line for emails
|
|
_rest.AddQueryParam("Message", messageContent.c_str()); // The message body
|
|
|
|
const char* responseXml = _rest.fullRequestNoBody("GET", "/");
|
|
if (!_rest.get_LastMethodSuccess()) {
|
|
_logger.LogError("ANSUtilities::SendMessageToTopic", _rest.lastErrorText(), __FILE__, __LINE__);
|
|
return "Error: " + std::string(_rest.lastErrorText());
|
|
}
|
|
|
|
if (_rest.get_ResponseStatusCode() != 200) {
|
|
_logger.LogError("ANSUtilities::SendMessageToTopic", _rest.responseHeader(), __FILE__, __LINE__);
|
|
return "Error: " + std::string(_rest.responseHeader());
|
|
}
|
|
|
|
CkXml xml;
|
|
xml.LoadXml(responseXml);
|
|
|
|
return xml.chilkatPath("PublishResult|MessageId|*"); // Return the MessageId
|
|
}
|
|
catch (const std::exception& e) {
|
|
_logger.LogFatal("ANSUtilities::SendMessageToTopic", e.what(), __FILE__, __LINE__);
|
|
return "Error: " + std::string(e.what());
|
|
}
|
|
}
|
|
std::string ANSUtilities::SendMessageToPhoneNumber(const std::string& phoneNumber, const std::string& messageContent) {
|
|
std::lock_guard<std::recursive_mutex> lock(_mutex);
|
|
if (!_isUnlockCodeValid) {
|
|
_logger.LogFatal("ANSUtilities::SendMessageToPhoneNumber", "Error: Invalid unlock code", __FILE__, __LINE__);
|
|
return "Error: Invalid unlock code";
|
|
}
|
|
|
|
if (!_isLicenseValid) {
|
|
_logger.LogFatal("ANSUtilities::SendMessageToPhoneNumber", "Error: Invalid license key", __FILE__, __LINE__);
|
|
return "Error: Invalid license key";
|
|
}
|
|
|
|
try {
|
|
CkRest _rest;
|
|
_rest.AddQueryParam("Action", "Publish");
|
|
_rest.AddQueryParam("PhoneNumber", phoneNumber.c_str());
|
|
_rest.AddQueryParam("Message", messageContent.c_str());
|
|
|
|
const char* responseXml = _rest.fullRequestNoBody("GET", "/");
|
|
if (!_rest.get_LastMethodSuccess()) {
|
|
_logger.LogError("ANSUtilities::SendMessageToPhoneNumber", _rest.lastErrorText(), __FILE__, __LINE__);
|
|
return "Error: " + std::string(_rest.lastErrorText());
|
|
}
|
|
|
|
if (_rest.get_ResponseStatusCode() != 200) {
|
|
_logger.LogError("ANSUtilities::SendMessageToPhoneNumber", _rest.responseHeader(), __FILE__, __LINE__);
|
|
return "Error: " + std::string(_rest.responseHeader());
|
|
}
|
|
|
|
CkXml xml;
|
|
xml.LoadXml(responseXml);
|
|
|
|
return xml.chilkatPath("PublishResult|MessageId|*"); // Return the MessageId
|
|
}
|
|
catch (const std::exception& e) {
|
|
_logger.LogFatal("ANSUtilities::SendMessageToPhoneNumber", e.what(), __FILE__, __LINE__);
|
|
return "Error: " + std::string(e.what());
|
|
}
|
|
}
|
|
std::string ANSUtilities::ListAWSSNSTopic() {
|
|
std::lock_guard<std::recursive_mutex> lock(_mutex);
|
|
if (!_isUnlockCodeValid) {
|
|
_logger.LogFatal("ANSUtilities::ListAWSSNSTopic", "Error: Invalid unlock code", __FILE__, __LINE__);
|
|
return "Error: Invalid unlock code";
|
|
}
|
|
|
|
if (!_isLicenseValid) {
|
|
_logger.LogFatal("ANSUtilities::ListAWSSNSTopic", "Error: Invalid license key", __FILE__, __LINE__);
|
|
return "Error: Invalid license key";
|
|
}
|
|
|
|
try {
|
|
CkRest _rest;
|
|
_rest.AddQueryParam("Action", "ListTopics");
|
|
const char* responseXml = _rest.fullRequestNoBody("GET", "/");
|
|
if (!_rest.get_LastMethodSuccess()) {
|
|
_logger.LogError("ANSUtilities::ListAWSSNSTopic", _rest.lastErrorText(), __FILE__, __LINE__);
|
|
return "Error: " + std::string(_rest.lastErrorText());
|
|
}
|
|
|
|
if (_rest.get_ResponseStatusCode() != 200) {
|
|
_logger.LogError("ANSUtilities::ListAWSSNSTopic", _rest.responseHeader(), __FILE__, __LINE__);
|
|
return "Error: " + std::string(_rest.responseHeader());
|
|
}
|
|
|
|
CkXml xml;
|
|
xml.LoadXml(responseXml);
|
|
|
|
// Move to Topics list
|
|
xml.chilkatPath("ListTopicsResult|Topics|$");
|
|
|
|
int numTopics = xml.get_NumChildren();
|
|
std::vector<std::string> topics;
|
|
topics.reserve(numTopics); // Slight optimization
|
|
|
|
for (int i = 0; i < numTopics; ++i) {
|
|
xml.GetChild2(i);
|
|
topics.emplace_back(xml.getChildContent("TopicArn"));
|
|
xml.GetParent2();
|
|
}
|
|
|
|
if (topics.empty()) {
|
|
_logger.LogError("ANSUtilities::ListAWSSNSTopic", "No topics found", __FILE__, __LINE__);
|
|
return "";
|
|
}
|
|
|
|
// Concatenate topics with ';'
|
|
std::string topicsStr;
|
|
for (size_t i = 0; i < topics.size(); ++i) {
|
|
topicsStr += topics[i];
|
|
if (i + 1 != topics.size()) {
|
|
topicsStr += ";";
|
|
}
|
|
}
|
|
|
|
return topicsStr;
|
|
}
|
|
catch (const std::exception& e) {
|
|
_logger.LogFatal("ANSUtilities::ListAWSSNSTopic", e.what(), __FILE__, __LINE__);
|
|
return "Error: " + std::string(e.what());
|
|
}
|
|
}
|
|
bool ANSUtilities::AuthenticateGCS(const std::string& jsonKeyFile) {
|
|
std::lock_guard<std::recursive_mutex> lock(_mutex);
|
|
if (!_isUnlockCodeValid) {
|
|
_logger.LogFatal("ANSUtilities::AuthenticateGCS", "Error: Invalid unlock code", __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
|
|
if (_isAuthenticated) {
|
|
return true;
|
|
}
|
|
|
|
try {
|
|
_authGoogle.put_JsonKey(jsonKeyFile.c_str());
|
|
_authGoogle.put_Scope("https://www.googleapis.com/auth/cloud-platform");
|
|
_authGoogle.put_ExpireNumSeconds(3600); // 1 hour token
|
|
_authGoogle.put_SubEmailAddress("");
|
|
|
|
CkSocket tlsSock;
|
|
bool success = tlsSock.Connect("www.googleapis.com", 443, true, 5000);
|
|
if (!success) {
|
|
_logger.LogError("ANSUtilities::AuthenticateGCS", tlsSock.lastErrorText(), __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
|
|
success = _authGoogle.ObtainAccessToken(tlsSock);
|
|
if (!success) {
|
|
_logger.LogError("ANSUtilities::AuthenticateGCS", _authGoogle.lastErrorText(), __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
|
|
if (!_authGoogle.accessToken()) {
|
|
_logger.LogError("ANSUtilities::AuthenticateGCS", _authGoogle.lastErrorText(), __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
|
|
_isAuthenticated = true;
|
|
return true;
|
|
}
|
|
catch (const std::exception& e) {
|
|
_logger.LogFatal("ANSUtilities::AuthenticateGCS", e.what(), __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
}
|
|
bool ANSUtilities::UploadMatToGCS(const std::string& bucketName, const std::string& objectName, const cv::Mat& image) {
|
|
std::lock_guard<std::recursive_mutex> lock(_mutex);
|
|
if (!_isUnlockCodeValid) {
|
|
_logger.LogFatal("ANSUtilities::UploadMatToGCS", "Error: Invalid unlock code", __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
|
|
if (!_isAuthenticated) {
|
|
_logger.LogError("ANSUtilities::UploadMatToGCS", "Not authenticated. Call AuthenticateGCS() first.", __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
try {
|
|
CkRest rest;
|
|
CkSocket _gcsSocket;
|
|
|
|
std::string gcsHost = "www.googleapis.com";
|
|
bool bTls = true;
|
|
bool autoReconnect = true;
|
|
int port = 443;
|
|
int maxWaitMs = 15000;
|
|
if (_bProxy) {
|
|
if (!_proxyHost.empty() && (_proxyPort > 0)) {
|
|
_gcsSocket.put_HttpProxyHostname(_proxyHost.c_str());
|
|
_gcsSocket.put_HttpProxyPort(_proxyPort);
|
|
_gcsSocket.put_HttpProxyUsername(_proxyUsername.c_str());
|
|
_gcsSocket.put_HttpProxyPassword(_proxyPassword.c_str());
|
|
_gcsSocket.put_HttpProxyForHttp(true);
|
|
|
|
if (!_gcsSocket.Connect(gcsHost.c_str(), port, bTls, maxWaitMs)) {
|
|
_logger.LogFatal("ANSUtilities::UploadMatToGCS", _gcsSocket.lastErrorText(), __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
|
|
// Bind socket to rest
|
|
if (!rest.UseConnection(_gcsSocket, autoReconnect)) {
|
|
_logger.LogFatal("ANSUtilities::UploadMatToGCS", rest.lastErrorText(), __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
rest.SetAuthGoogle(_authGoogle);
|
|
}
|
|
else {
|
|
_logger.LogFatal("ANSUtilities::UploadMatToGCS", "Invalid proxy hostname and port", __FILE__, __LINE__);
|
|
return false;
|
|
|
|
}
|
|
}
|
|
else { // No proxy
|
|
rest.SetAuthGoogle(_authGoogle);
|
|
// Connect to Google Cloud Storage REST API
|
|
if (!rest.Connect(gcsHost.c_str(), port, bTls, autoReconnect)) {
|
|
_logger.LogError("ANSUtilities::UploadMatToGCS", rest.lastErrorText(), __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
}
|
|
// Convert cv::Mat to JPEG binary
|
|
std::vector<uchar> jpegBuffer;
|
|
std::vector<int> compressionParams = { cv::IMWRITE_JPEG_QUALITY, 90 };
|
|
if (!cv::imencode(".jpg", image, jpegBuffer, compressionParams)) {
|
|
_logger.LogError("ANSUtilities::UploadMatToGCS", "Failed to encode cv::Mat as JPEG.", __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
// Convert std::vector<uchar> to CkByteData
|
|
CkByteData jpegBytes;
|
|
if (!jpegBuffer.empty()) {
|
|
jpegBytes.append2(jpegBuffer.data(), static_cast<unsigned long>(jpegBuffer.size()));
|
|
}
|
|
|
|
// Prepare the HTTP request to upload the file
|
|
std::string urlPath = "/upload/storage/v1/b/" + bucketName + "/o?uploadType=media&name=" + objectName;
|
|
rest.AddHeader("Content-Type", "image/jpeg");
|
|
|
|
// Upload the JPEG data to GCS
|
|
std::string jsonResponse = rest.fullRequestBinary("POST", urlPath.c_str(), jpegBytes);
|
|
if (!rest.get_LastMethodSuccess()) {
|
|
_logger.LogError("ANSUtilities::UploadMatToGCS", rest.lastErrorText(), __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
|
|
int statusCode = rest.get_ResponseStatusCode();
|
|
if (statusCode != 200) {
|
|
_logger.LogError("ANSUtilities::UploadMatToGCS", rest.responseHeader(), __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
|
|
_logger.LogDebug("ANSUtilities::UploadMatToGCS", "Upload successful. Status Code: " + std::to_string(statusCode), __FILE__, __LINE__);
|
|
return true;
|
|
}
|
|
catch (const std::exception& e) {
|
|
_logger.LogFatal("ANSUtilities::UploadMatToGCS", e.what(), __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
bool ANSUtilities::UploadMatToGCS(const std::string& bucketName, const std::string& objectName, unsigned char* jpeg_string, int32 bufferLength) {
|
|
std::lock_guard<std::recursive_mutex> lock(_mutex);
|
|
if (!_isUnlockCodeValid) {
|
|
_logger.LogFatal("ANSUtilities::UploadMatToGCS", "Error: Invalid unlock code", __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
|
|
if (!_isAuthenticated) {
|
|
_logger.LogError("ANSUtilities::UploadMatToGCS", "Not authenticated. Call AuthenticateGCS() first.", __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
if(bufferLength<=0) {
|
|
_logger.LogError("ANSUtilities::UploadMatToGCS", "Invalid buffer length", __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
try {
|
|
CkRest rest;
|
|
CkSocket _gcsSocket;
|
|
std::string gcsHost = "www.googleapis.com";
|
|
bool bTls = true;
|
|
bool autoReconnect = true;
|
|
int port = 443;
|
|
int maxWaitMs = 15000;
|
|
if (_bProxy) {
|
|
if (!_proxyHost.empty() && (_proxyPort > 0)) {
|
|
_gcsSocket.put_HttpProxyHostname(_proxyHost.c_str());
|
|
_gcsSocket.put_HttpProxyPort(_proxyPort);
|
|
_gcsSocket.put_HttpProxyUsername(_proxyUsername.c_str());
|
|
_gcsSocket.put_HttpProxyPassword(_proxyPassword.c_str());
|
|
_gcsSocket.put_HttpProxyForHttp(true);
|
|
|
|
if (!_gcsSocket.Connect(gcsHost.c_str(), port, bTls, maxWaitMs)) {
|
|
_logger.LogFatal("ANSUtilities::UploadMatToGCS", _gcsSocket.lastErrorText(), __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
// Bind socket to rest
|
|
if (!rest.UseConnection(_gcsSocket, autoReconnect)) {
|
|
_logger.LogFatal("ANSUtilities::UploadMatToGCS", rest.lastErrorText(), __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
rest.SetAuthGoogle(_authGoogle);
|
|
}
|
|
else {
|
|
_logger.LogFatal("ANSUtilities::UploadMatToGCS", "Invalid proxy hostname and port", __FILE__, __LINE__);
|
|
return false;
|
|
|
|
}
|
|
}
|
|
else { // No proxy
|
|
rest.SetAuthGoogle(_authGoogle);
|
|
// Connect to Google Cloud Storage REST API
|
|
if (!rest.Connect(gcsHost.c_str(), port, bTls, autoReconnect)) {
|
|
_logger.LogError("ANSUtilities::UploadMatToGCS", rest.lastErrorText(), __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Convert std::vector<uchar> to CkByteData
|
|
CkByteData jpegBytes;
|
|
jpegBytes.append2(jpeg_string, static_cast<unsigned long>(bufferLength));
|
|
|
|
// Prepare the HTTP request to upload the file
|
|
std::string urlPath = "/upload/storage/v1/b/" + bucketName + "/o?uploadType=media&name=" + objectName;
|
|
rest.AddHeader("Content-Type", "image/jpeg");
|
|
|
|
// Upload the JPEG data to GCS
|
|
std::string jsonResponse = rest.fullRequestBinary("POST", urlPath.c_str(), jpegBytes);
|
|
if (!rest.get_LastMethodSuccess()) {
|
|
_logger.LogError("ANSUtilities::UploadMatToGCS", rest.lastErrorText(), __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
|
|
int statusCode = rest.get_ResponseStatusCode();
|
|
if (statusCode != 200) {
|
|
_logger.LogError("ANSUtilities::UploadMatToGCS", rest.responseHeader(), __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
|
|
_logger.LogDebug("ANSUtilities::UploadMatToGCS", "Upload successful. Status Code: " + std::to_string(statusCode), __FILE__, __LINE__);
|
|
return true;
|
|
}
|
|
catch (const std::exception& e) {
|
|
_logger.LogFatal("ANSUtilities::UploadMatToGCS", e.what(), __FILE__, __LINE__);
|
|
return false;
|
|
}
|
|
}
|
|
bool ANSUtilities::SendEmail(const std::string& smtpServer, int port,
|
|
const std::string& userName, const std::string& password,
|
|
const std::string& subjectContent,
|
|
const std::string& bodyHTMLContent,
|
|
const std::string& bodyTextContent,
|
|
const std::string& fromEmailSender,
|
|
const std::vector<std::string>& toEmails,
|
|
const std::vector<std::string>& ccEmails,
|
|
const std::vector<std::string>& bccEmails)
|
|
|
|
{
|
|
std::unique_lock<std::timed_mutex> lock(timeImageMutex, std::defer_lock);
|
|
if (!lock.try_lock_for(std::chrono::milliseconds(45000))) {
|
|
std::cerr << "Error: Mutex timeout in ANSUtilities::SendEmail!" << std::endl;
|
|
return false;
|
|
}
|
|
if (!CheckUnlockCode_S()) {
|
|
return false;
|
|
}
|
|
try {
|
|
// The mailman object is used for sending and receiving email.
|
|
CkMailMan mailman;
|
|
mailman.put_SmtpHost(smtpServer.c_str());
|
|
mailman.put_SmtpPort(port);
|
|
mailman.put_StartTLS(true);//STARTTLS
|
|
// Set the SMTP login/password
|
|
mailman.put_SmtpUsername(userName.c_str());
|
|
mailman.put_SmtpPassword(password.c_str());
|
|
|
|
CkEmail email;
|
|
if (!bodyHTMLContent.empty()) {
|
|
CkMht mht;
|
|
mht.put_UseCids(true);
|
|
const char* mime = 0;
|
|
mime = mht.htmlToEML(bodyHTMLContent.c_str());
|
|
bool setmime = email.SetFromMimeText(mime);
|
|
email.ConvertInlineImages();
|
|
}
|
|
email.put_Subject(subjectContent.c_str());
|
|
if (!bodyTextContent.empty())
|
|
email.put_Body(bodyTextContent.c_str());
|
|
email.put_From(fromEmailSender.c_str());
|
|
for (const auto& toEmail : toEmails) {
|
|
email.AddTo("", toEmail.c_str());
|
|
}
|
|
for (const auto& ccEmail : ccEmails) {
|
|
email.AddCC("", ccEmail.c_str());
|
|
}
|
|
for (const auto& bccEmail : bccEmails) {
|
|
email.AddBcc("", bccEmail.c_str());
|
|
}
|
|
|
|
bool success = mailman.SendEmail(email);
|
|
if (success != true) {
|
|
return false;
|
|
}
|
|
|
|
success = mailman.CloseSmtpConnection();
|
|
if (success != true) {
|
|
}
|
|
return success;
|
|
}
|
|
catch (const std::exception& e) {
|
|
return false;
|
|
}
|
|
}
|
|
bool ANSUtilities::CheckUnlockCode_S() {
|
|
static std::once_flag unlockOnceFlag;
|
|
static bool isUnlockValid = false;
|
|
try {
|
|
std::call_once(unlockOnceFlag, []() {
|
|
CkGlobal glob;
|
|
const std::string unlockCode = "ANSDRC.CB1122026_MEQCIFwO1IFQCG0BhZwsXFO68QUU6mDB5uge4duOsqOJanEyAiAB67ahqnXin4SRy0vIegISgbFlpldmbuS5gbU21GYVqA==";// "ANSDRC.CB1082025_Ax6P3M7F8B3d";
|
|
if (glob.UnlockBundle(unlockCode.c_str()) && glob.get_UnlockStatus() == 2) {
|
|
isUnlockValid = true;
|
|
}
|
|
});
|
|
return isUnlockValid;
|
|
}
|
|
catch (...) {
|
|
return false;
|
|
}
|
|
}
|
|
std::string ANSUtilities::AESEncryption(const std::string& inputString, const std::string& inputKey) {
|
|
if (!CheckUnlockCode_S()) {
|
|
return "";
|
|
}
|
|
try {
|
|
CkCrypt2 crypt;
|
|
// AES is also known as Rijndael.
|
|
crypt.put_CryptAlgorithm("aes");
|
|
// CipherMode may be "ecb", "cbc", "ofb", "cfb", "gcm", etc.
|
|
crypt.put_CipherMode("cbc");
|
|
// KeyLength may be 128, 192, 256
|
|
crypt.put_KeyLength(256);
|
|
// The padding scheme determines the contents of the bytes
|
|
// that are added to pad the result to a multiple of the
|
|
// encryption algorithm's block size. AES has a block
|
|
// size of 16 bytes, so encrypted output is always
|
|
// a multiple of 16.
|
|
crypt.put_PaddingScheme(0); // 0 = RFC 1423 padding scheme
|
|
// EncodingMode specifies the encoding of the output for
|
|
// encryption, and the input for decryption.
|
|
// It may be "hex", "url", "base64", or "quoted-printable".
|
|
crypt.put_EncodingMode("base64");
|
|
|
|
// Ensure inputKey is exactly 16 characters for IV.
|
|
std::string ivKey = inputKey.substr(0, std::min<size_t>(16, inputKey.size()));
|
|
if (ivKey.size() < 16) {
|
|
ivKey.append(16 - ivKey.size(), 'A'); // Pad with spaces if less than 16 characters
|
|
}
|
|
crypt.SetEncodedIV(ivKey.c_str(), "ascii");
|
|
|
|
// The secret key must equal the size of the key. For
|
|
// 256-bit encryption, the binary secret key is 32 bytes.
|
|
// For 128-bit encryption, the binary secret key is 16 bytes.
|
|
std::string secreteKey = inputKey.substr(0, std::min<size_t>(32, inputKey.size()));
|
|
if (secreteKey.size() < 32) {
|
|
secreteKey.append(32 - secreteKey.size(), 'A'); // Pad with spaces if less than 32 characters
|
|
}
|
|
crypt.SetEncodedKey(secreteKey.c_str(), "ascii");
|
|
const char* encStr = crypt.encryptStringENC(inputString.c_str());
|
|
return encStr ? std::string(encStr) : std::string();
|
|
}
|
|
catch (const std::exception& e) {
|
|
// Optional: If you want logging, consider static logging in static functions
|
|
return "";
|
|
}
|
|
}
|
|
std::string ANSUtilities::AESDecryption(const std::string& encryptString, const std::string& inputKey) {
|
|
if (!CheckUnlockCode_S()) {
|
|
return "";
|
|
}
|
|
try {
|
|
CkCrypt2 crypt;
|
|
// AES is also known as Rijndael.
|
|
crypt.put_CryptAlgorithm("aes");
|
|
// CipherMode may be "ecb", "cbc", "ofb", "cfb", "gcm", etc.
|
|
crypt.put_CipherMode("cbc");
|
|
// KeyLength may be 128, 192, 256
|
|
crypt.put_KeyLength(256);
|
|
// The padding scheme determines the contents of the bytes
|
|
// that are added to pad the result to a multiple of the
|
|
// encryption algorithm's block size. AES has a block
|
|
// size of 16 bytes, so encrypted output is always
|
|
// a multiple of 16.
|
|
crypt.put_PaddingScheme(0); // 0 = RFC 1423 padding scheme
|
|
// EncodingMode specifies the encoding of the output for
|
|
// encryption, and the input for decryption.
|
|
// It may be "hex", "url", "base64", or "quoted-printable".
|
|
crypt.put_EncodingMode("base64");
|
|
|
|
// Ensure inputKey is exactly 16 characters for IV.
|
|
std::string ivKey = inputKey.substr(0, std::min<size_t>(16, inputKey.size()));
|
|
if (ivKey.size() < 16) {
|
|
ivKey.append(16 - ivKey.size(), 'A'); // Pad with spaces if less than 16 characters
|
|
}
|
|
crypt.SetEncodedIV(ivKey.c_str(), "ascii");
|
|
|
|
// The secret key must equal the size of the key. For
|
|
// 256-bit encryption, the binary secret key is 32 bytes.
|
|
// For 128-bit encryption, the binary secret key is 16 bytes.
|
|
std::string secreteKey = inputKey.substr(0, std::min<size_t>(32, inputKey.size()));
|
|
if (secreteKey.size() < 32) {
|
|
secreteKey.append(32 - secreteKey.size(), 'A'); // Pad with spaces if less than 32 characters
|
|
}
|
|
crypt.SetEncodedKey(secreteKey.c_str(), "ascii");
|
|
const char* decStr = crypt.decryptStringENC(encryptString.c_str());
|
|
return decStr ? std::string(decStr) : std::string();
|
|
}
|
|
catch (const std::exception& e) {
|
|
// Optional: If you want logging, consider static logging in static functions
|
|
return "";
|
|
}
|
|
}
|
|
std::string ANSUtilities::MD5HashFile(const std::string& inputFilePath) {
|
|
if (!CheckUnlockCode_S()) {
|
|
return "";
|
|
}
|
|
try {
|
|
CkCrypt2 crypt;
|
|
|
|
// Set the name of the hash algorithm.
|
|
// Other choices include "sha1", "sha256", "sha384", "sha512", "md2", "md5", and "haval".
|
|
crypt.put_HashAlgorithm("md5");
|
|
|
|
// EncodingMode specifies the encoding of the hash output.
|
|
// It may be "hex", "url", "base64", or "quoted-printable".
|
|
crypt.put_EncodingMode("hex");
|
|
|
|
// Files of any type may be hashed -- it doesn't matter
|
|
// if the file is binary or text...
|
|
const char* hashStr = nullptr;
|
|
hashStr = crypt.hashFileENC(inputFilePath.c_str());
|
|
return hashStr ? std::string(hashStr) : std::string();
|
|
}
|
|
catch (const std::exception& e) {
|
|
// Optional: If you want logging, consider static logging in static functions
|
|
return "";
|
|
}
|
|
}
|
|
bool ANSUtilities::RestartPC() {
|
|
try {
|
|
return system("shutdown /r /t 0") == 0;
|
|
}
|
|
catch (...) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
std::string ANSUtilities::DecodeJsonUnicodeToUTF16LE(const std::string& escapedStr) {
|
|
std::string result;
|
|
result.reserve(escapedStr.size() * 2);
|
|
size_t i = 0;
|
|
while (i < escapedStr.size()) {
|
|
if (i + 5 < escapedStr.size() && escapedStr[i] == '\\' && escapedStr[i + 1] == 'u') {
|
|
char hex[5] = { escapedStr[i + 2], escapedStr[i + 3], escapedStr[i + 4], escapedStr[i + 5], 0 };
|
|
uint16_t codepoint = (uint16_t)strtoul(hex, nullptr, 16);
|
|
result += static_cast<char>(codepoint & 0xFF);
|
|
result += static_cast<char>((codepoint >> 8) & 0xFF);
|
|
i += 6;
|
|
} else {
|
|
result += escapedStr[i];
|
|
result += '\0';
|
|
i++;
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
std::string ANSUtilities::ConvertUTF16LEToUTF8(const char* utf16leBytes, int byteLen) {
|
|
#ifdef _WIN32
|
|
if (!utf16leBytes || byteLen <= 0) return "";
|
|
int wideLen = byteLen / (int)sizeof(wchar_t);
|
|
const wchar_t* wideStr = reinterpret_cast<const wchar_t*>(utf16leBytes);
|
|
// First call: get required UTF-8 buffer size
|
|
int utf8Len = WideCharToMultiByte(CP_UTF8, 0, wideStr, wideLen, nullptr, 0, nullptr, nullptr);
|
|
if (utf8Len <= 0) return "";
|
|
std::string utf8Str(utf8Len, 0);
|
|
WideCharToMultiByte(CP_UTF8, 0, wideStr, wideLen, &utf8Str[0], utf8Len, nullptr, nullptr);
|
|
return utf8Str;
|
|
#else
|
|
return std::string(utf16leBytes, byteLen);
|
|
#endif
|
|
}
|
|
|
|
std::string ANSUtilities::ConvertUTF8ToUTF16LE(const std::string& utf8Str) {
|
|
#ifdef _WIN32
|
|
if (utf8Str.empty()) return "";
|
|
int wideLen = MultiByteToWideChar(CP_UTF8, 0, utf8Str.c_str(), (int)utf8Str.size(), nullptr, 0);
|
|
if (wideLen <= 0) return "";
|
|
std::wstring wideStr(wideLen, 0);
|
|
MultiByteToWideChar(CP_UTF8, 0, utf8Str.c_str(), (int)utf8Str.size(), &wideStr[0], wideLen);
|
|
const char* rawBytes = reinterpret_cast<const char*>(wideStr.data());
|
|
return std::string(rawBytes, wideLen * sizeof(wchar_t));
|
|
#else
|
|
return utf8Str;
|
|
#endif
|
|
}
|
|
|
|
std::vector<unsigned char> ANSUtilities::RepairLabVIEWUTF16LE(const unsigned char* data, int len) {
|
|
std::vector<unsigned char> repaired;
|
|
if (!data || len <= 0) return repaired;
|
|
repaired.reserve(len + 32);
|
|
|
|
// Helper: emit a BMP codepoint as UTF-16LE pair
|
|
auto emitU16 = [&](uint16_t cp) {
|
|
repaired.push_back(static_cast<unsigned char>(cp & 0xFF));
|
|
repaired.push_back(static_cast<unsigned char>((cp >> 8) & 0xFF));
|
|
};
|
|
|
|
for (int i = 0; i < len; ) {
|
|
unsigned char b = data[i];
|
|
|
|
// --- 1. Detect embedded UTF-8 multi-byte sequences ---
|
|
// LabVIEW text controls may mix UTF-8 encoded characters into a
|
|
// UTF-16LE stream. UTF-8 lead bytes (C2-F4) followed by valid
|
|
// continuation bytes (80-BF) are a strong signal.
|
|
// We decode the UTF-8 codepoint and re-encode as UTF-16LE.
|
|
|
|
// 2-byte UTF-8: 110xxxxx 10xxxxxx (U+0080 .. U+07FF)
|
|
if (b >= 0xC2 && b <= 0xDF && i + 1 < len) {
|
|
unsigned char b1 = data[i + 1];
|
|
if ((b1 & 0xC0) == 0x80) {
|
|
uint32_t cp = ((b & 0x1F) << 6) | (b1 & 0x3F);
|
|
emitU16(static_cast<uint16_t>(cp));
|
|
i += 2;
|
|
continue;
|
|
}
|
|
}
|
|
// 3-byte UTF-8: 1110xxxx 10xxxxxx 10xxxxxx (U+0800 .. U+FFFF)
|
|
if (b >= 0xE0 && b <= 0xEF && i + 2 < len) {
|
|
unsigned char b1 = data[i + 1];
|
|
unsigned char b2 = data[i + 2];
|
|
if ((b1 & 0xC0) == 0x80 && (b2 & 0xC0) == 0x80) {
|
|
uint32_t cp = ((b & 0x0F) << 12) | ((b1 & 0x3F) << 6) | (b2 & 0x3F);
|
|
// Reject overlong encodings and surrogates
|
|
if (cp >= 0x0800 && (cp < 0xD800 || cp > 0xDFFF)) {
|
|
emitU16(static_cast<uint16_t>(cp));
|
|
i += 3;
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
// 4-byte UTF-8: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx (U+10000 .. U+10FFFF)
|
|
if (b >= 0xF0 && b <= 0xF4 && i + 3 < len) {
|
|
unsigned char b1 = data[i + 1];
|
|
unsigned char b2 = data[i + 2];
|
|
unsigned char b3 = data[i + 3];
|
|
if ((b1 & 0xC0) == 0x80 && (b2 & 0xC0) == 0x80 && (b3 & 0xC0) == 0x80) {
|
|
uint32_t cp = ((b & 0x07) << 18) | ((b1 & 0x3F) << 12)
|
|
| ((b2 & 0x3F) << 6) | (b3 & 0x3F);
|
|
if (cp >= 0x10000 && cp <= 0x10FFFF) {
|
|
// Surrogate pair
|
|
cp -= 0x10000;
|
|
emitU16(static_cast<uint16_t>(0xD800 + (cp >> 10)));
|
|
emitU16(static_cast<uint16_t>(0xDC00 + (cp & 0x3FF)));
|
|
i += 4;
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
|
|
// --- 2. Normal UTF-16LE pair (low byte + 0x00 high byte) ---
|
|
if (i + 1 < len && data[i + 1] == 0x00) {
|
|
repaired.push_back(data[i]);
|
|
repaired.push_back(0x00);
|
|
i += 2;
|
|
}
|
|
// --- 3. Lone space byte — LabVIEW dropped the 0x00 high byte ---
|
|
else if (b == 0x20 && (i + 1 >= len || data[i + 1] != 0x00)) {
|
|
repaired.push_back(0x20);
|
|
repaired.push_back(0x00);
|
|
i += 1;
|
|
}
|
|
// --- 4. Non-ASCII UTF-16LE pair (e.g. ễ = C5 1E) ---
|
|
else if (i + 1 < len) {
|
|
repaired.push_back(data[i]);
|
|
repaired.push_back(data[i + 1]);
|
|
i += 2;
|
|
}
|
|
// --- 5. Trailing odd byte — skip ---
|
|
else {
|
|
i++;
|
|
}
|
|
}
|
|
return repaired;
|
|
}
|
|
|
|
bool ANSUtilities::IsValidUTF8(const unsigned char* data, int len) {
|
|
if (!data || len <= 0) return false;
|
|
bool hasMultiByte = false;
|
|
for (int i = 0; i < len; ) {
|
|
unsigned char b = data[i];
|
|
if (b <= 0x7F) {
|
|
// ASCII — valid, but alone doesn't prove UTF-8
|
|
i++;
|
|
} else if (b >= 0xC2 && b <= 0xDF) {
|
|
// 2-byte sequence
|
|
if (i + 1 >= len || (data[i + 1] & 0xC0) != 0x80) return false;
|
|
hasMultiByte = true;
|
|
i += 2;
|
|
} else if (b >= 0xE0 && b <= 0xEF) {
|
|
// 3-byte sequence
|
|
if (i + 2 >= len || (data[i + 1] & 0xC0) != 0x80 || (data[i + 2] & 0xC0) != 0x80) return false;
|
|
uint32_t cp = ((b & 0x0F) << 12) | ((data[i + 1] & 0x3F) << 6) | (data[i + 2] & 0x3F);
|
|
if (cp < 0x0800 || (cp >= 0xD800 && cp <= 0xDFFF)) return false; // overlong or surrogate
|
|
hasMultiByte = true;
|
|
i += 3;
|
|
} else if (b >= 0xF0 && b <= 0xF4) {
|
|
// 4-byte sequence
|
|
if (i + 3 >= len || (data[i + 1] & 0xC0) != 0x80 || (data[i + 2] & 0xC0) != 0x80 || (data[i + 3] & 0xC0) != 0x80) return false;
|
|
uint32_t cp = ((b & 0x07) << 18) | ((data[i + 1] & 0x3F) << 12) | ((data[i + 2] & 0x3F) << 6) | (data[i + 3] & 0x3F);
|
|
if (cp < 0x10000 || cp > 0x10FFFF) return false;
|
|
hasMultiByte = true;
|
|
i += 4;
|
|
} else {
|
|
return false; // invalid lead byte (C0, C1, F5-FF)
|
|
}
|
|
}
|
|
// Only confirm UTF-8 if we found at least one multi-byte sequence.
|
|
// Pure ASCII is ambiguous — let the caller decide.
|
|
return hasMultiByte;
|
|
}
|
|
|
|
std::string ANSUtilities::ConvertUTF16LEToUnicodeEscapes(const char* utf16leBytes, int byteLen) {
|
|
if (!utf16leBytes || byteLen <= 0) return "";
|
|
int offset = 0;
|
|
// Strip BOM (FF FE) if present
|
|
if (byteLen >= 2 &&
|
|
static_cast<unsigned char>(utf16leBytes[0]) == 0xFF &&
|
|
static_cast<unsigned char>(utf16leBytes[1]) == 0xFE) {
|
|
offset = 2;
|
|
}
|
|
int remaining = byteLen - offset;
|
|
if (remaining <= 0) return "";
|
|
// Drop trailing odd byte if present (e.g. null terminator appended by LabVIEW)
|
|
if (remaining % 2 != 0) remaining--;
|
|
|
|
int endPos = offset + remaining; // safe end position (even-aligned)
|
|
std::string result;
|
|
result.reserve(remaining * 3);
|
|
for (int i = offset; i + 1 < endPos; i += 2) {
|
|
uint16_t codepoint = static_cast<unsigned char>(utf16leBytes[i])
|
|
| (static_cast<unsigned char>(utf16leBytes[i + 1]) << 8);
|
|
// Pass through printable ASCII (0x20-0x7E) and common whitespace (tab, LF, CR)
|
|
// Escape other control characters and non-ASCII as \uXXXX
|
|
if ((codepoint >= 0x20 && codepoint <= 0x7E) || codepoint == 0x09 || codepoint == 0x0A || codepoint == 0x0D) {
|
|
result += static_cast<char>(codepoint);
|
|
} else {
|
|
char buf[7];
|
|
snprintf(buf, sizeof(buf), "\\u%04X", codepoint);
|
|
result += buf;
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
std::string ANSUtilities::ConvertUTF8ToUnicodeEscapes(const std::string& utf8Str) {
|
|
if (utf8Str.empty()) return "";
|
|
// Auto-detect UTF-16LE input (LabVIEW may pass UTF-16LE strings)
|
|
if (IsLikelyUTF16LE(utf8Str)) {
|
|
std::string asUtf8 = ConvertUTF16LEToUTF8(utf8Str.data(), static_cast<int>(utf8Str.size()));
|
|
return ConvertUTF8ToUnicodeEscapes(asUtf8);
|
|
}
|
|
std::string result;
|
|
result.reserve(utf8Str.size() * 2);
|
|
size_t i = 0;
|
|
while (i < utf8Str.size()) {
|
|
unsigned char c = static_cast<unsigned char>(utf8Str[i]);
|
|
if ((c >= 0x20 && c <= 0x7E) || c == '\t' || c == '\n' || c == '\r') {
|
|
// Printable ASCII (0x20-0x7E) and common whitespace (tab, LF, CR) — pass through
|
|
result += utf8Str[i];
|
|
i++;
|
|
} else if (c <= 0x7F) {
|
|
// Other control chars (0x00-0x08, 0x0B, 0x0C, 0x0E-0x1F), DEL (0x7F) — escape as \uXXXX
|
|
char buf[7];
|
|
snprintf(buf, sizeof(buf), "\\u%04x", c);
|
|
result += buf;
|
|
i++;
|
|
} else {
|
|
// Multi-byte UTF-8 sequence -- decode to Unicode codepoint
|
|
uint32_t codepoint = 0;
|
|
int seqLen = 0;
|
|
if ((c & 0xE0) == 0xC0) { codepoint = c & 0x1F; seqLen = 2; }
|
|
else if ((c & 0xF0) == 0xE0) { codepoint = c & 0x0F; seqLen = 3; }
|
|
else if ((c & 0xF8) == 0xF0) { codepoint = c & 0x07; seqLen = 4; }
|
|
else { result += utf8Str[i]; i++; continue; } // invalid lead byte
|
|
|
|
bool valid = true;
|
|
for (int j = 1; j < seqLen && i + j < utf8Str.size(); j++) {
|
|
unsigned char b = static_cast<unsigned char>(utf8Str[i + j]);
|
|
if ((b & 0xC0) != 0x80) { valid = false; break; }
|
|
codepoint = (codepoint << 6) | (b & 0x3F);
|
|
}
|
|
if (!valid || i + seqLen > utf8Str.size()) {
|
|
result += utf8Str[i]; i++; continue; // skip invalid
|
|
}
|
|
if (codepoint <= 0xFFFF) {
|
|
char buf[7];
|
|
snprintf(buf, sizeof(buf), "\\u%04x", codepoint);
|
|
result += buf;
|
|
} else {
|
|
// Surrogate pair for codepoints above U+FFFF
|
|
codepoint -= 0x10000;
|
|
uint16_t high = 0xD800 + (uint16_t)(codepoint >> 10);
|
|
uint16_t low = 0xDC00 + (uint16_t)(codepoint & 0x3FF);
|
|
char buf[14];
|
|
snprintf(buf, sizeof(buf), "\\u%04x\\u%04x", high, low);
|
|
result += buf;
|
|
}
|
|
i += seqLen;
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
std::string ANSUtilities::ConvertUnicodeEscapesToUTF8(const std::string& escapedStr) {
|
|
if (escapedStr.empty()) return "";
|
|
// First decode \uXXXX to UTF-16LE, then convert to UTF-8
|
|
std::string utf16le;
|
|
utf16le.reserve(escapedStr.size() * 2);
|
|
size_t i = 0;
|
|
while (i < escapedStr.size()) {
|
|
if (i + 5 < escapedStr.size() && escapedStr[i] == '\\' && escapedStr[i + 1] == 'u') {
|
|
char hex[5] = { escapedStr[i + 2], escapedStr[i + 3], escapedStr[i + 4], escapedStr[i + 5], 0 };
|
|
uint16_t codepoint = (uint16_t)strtoul(hex, nullptr, 16);
|
|
utf16le += static_cast<char>(codepoint & 0xFF);
|
|
utf16le += static_cast<char>((codepoint >> 8) & 0xFF);
|
|
i += 6;
|
|
} else {
|
|
utf16le += escapedStr[i];
|
|
utf16le += '\0';
|
|
i++;
|
|
}
|
|
}
|
|
return ConvertUTF16LEToUTF8(utf16le.data(), (int)utf16le.size());
|
|
}
|
|
|
|
std::string ANSUtilities::DoubleEscapeUnicode(const std::string& str) {
|
|
if (str.empty()) return "";
|
|
// Auto-detect UTF-16LE input (LabVIEW may pass UTF-16LE strings)
|
|
if (IsLikelyUTF16LE(str)) {
|
|
std::string asUtf8 = ConvertUTF16LEToUTF8(str.data(), static_cast<int>(str.size()));
|
|
return DoubleEscapeUnicode(asUtf8);
|
|
}
|
|
std::string result;
|
|
result.reserve(str.size() + str.size() / 4);
|
|
for (size_t i = 0; i < str.size(); i++) {
|
|
if (str[i] == '\\' && i + 1 < str.size() && str[i + 1] == 'u') {
|
|
result += "\\\\u";
|
|
i++; // skip 'u', loop advances past '\'
|
|
} else {
|
|
result += str[i];
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
std::string ANSUtilities::ConvertUTF8ToDoubleEscapedUnicode(const std::string& utf8Str) {
|
|
if (utf8Str.empty()) return "";
|
|
// Auto-detect UTF-16LE input (LabVIEW may pass UTF-16LE strings)
|
|
std::string inputStr = IsLikelyUTF16LE(utf8Str)
|
|
? ConvertUTF16LEToUTF8(utf8Str.data(), static_cast<int>(utf8Str.size()))
|
|
: utf8Str;
|
|
return DoubleEscapeUnicode(ConvertUTF8ToUnicodeEscapes(inputStr));
|
|
}
|
|
|
|
std::string ANSUtilities::UnescapeDoubleEscapedUnicode(const std::string& str) {
|
|
if (str.empty()) return "";
|
|
// Auto-detect UTF-16LE input (LabVIEW may pass UTF-16LE strings)
|
|
if (IsLikelyUTF16LE(str)) {
|
|
std::string asUtf8 = ConvertUTF16LEToUTF8(str.data(), static_cast<int>(str.size()));
|
|
return UnescapeDoubleEscapedUnicode(asUtf8);
|
|
}
|
|
// Quick scan: if no \\u pattern exists, return original string unchanged
|
|
bool found = false;
|
|
for (size_t i = 0; i + 2 < str.size(); i++) {
|
|
if (str[i] == '\\' && str[i + 1] == '\\' && str[i + 2] == 'u') {
|
|
found = true;
|
|
break;
|
|
}
|
|
}
|
|
if (!found) return str;
|
|
|
|
std::string result;
|
|
result.reserve(str.size());
|
|
for (size_t i = 0; i < str.size(); i++) {
|
|
if (str[i] == '\\' && i + 2 < str.size() && str[i + 1] == '\\' && str[i + 2] == 'u') {
|
|
result += "\\u";
|
|
i += 2; // skip past '\\' and 'u', loop will advance past first '\'
|
|
} else {
|
|
result += str[i];
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
// ====================================================================
|
|
// GetANSLoggerErrorEvents / GetANSLoggerErrorEventsSinceLastCall
|
|
//
|
|
// Reads every Error-level event written by the "ANSLogger" source in
|
|
// the Application channel using the modern winevt API. Events are
|
|
// produced by WindowsEventSink in ANSLicensingSystem (see
|
|
// ANSLicense.cpp::ReportEventW) — each carries a single inserted
|
|
// string in <EventData><Data>...</Data></EventData>.
|
|
//
|
|
// DebugView: filter "[EVTLOG]".
|
|
// ====================================================================
|
|
|
|
// ---- Watermark helpers (HKCU, no admin needed) ----------------------
|
|
static constexpr const wchar_t* kWatermarkRegKey =
|
|
L"Software\\ANSCENTER\\ANSUtilities\\EventLogWatermark";
|
|
static constexpr const wchar_t* kWatermarkValueName = L"ANSLogger";
|
|
|
|
static uint64_t ReadAnsLoggerWatermark() {
|
|
HKEY hKey = nullptr;
|
|
if (RegOpenKeyExW(HKEY_CURRENT_USER, kWatermarkRegKey, 0,
|
|
KEY_READ, &hKey) != ERROR_SUCCESS) {
|
|
return 0;
|
|
}
|
|
uint64_t value = 0;
|
|
DWORD size = sizeof(value), type = 0;
|
|
LONG rc = RegQueryValueExW(hKey, kWatermarkValueName, nullptr,
|
|
&type, reinterpret_cast<LPBYTE>(&value),
|
|
&size);
|
|
RegCloseKey(hKey);
|
|
return (rc == ERROR_SUCCESS && type == REG_QWORD) ? value : 0;
|
|
}
|
|
|
|
static void WriteAnsLoggerWatermark(uint64_t value) {
|
|
HKEY hKey = nullptr;
|
|
if (RegCreateKeyExW(HKEY_CURRENT_USER, kWatermarkRegKey, 0,
|
|
nullptr, REG_OPTION_NON_VOLATILE, KEY_WRITE,
|
|
nullptr, &hKey, nullptr) != ERROR_SUCCESS) {
|
|
ANS_DBG("EVTLOG", "watermark RegCreateKey failed err=%lu",
|
|
GetLastError());
|
|
return;
|
|
}
|
|
LONG rc = RegSetValueExW(hKey, kWatermarkValueName, 0, REG_QWORD,
|
|
reinterpret_cast<const BYTE*>(&value),
|
|
sizeof(value));
|
|
if (rc != ERROR_SUCCESS) {
|
|
ANS_DBG("EVTLOG", "watermark RegSetValue failed err=%ld", rc);
|
|
}
|
|
RegCloseKey(hKey);
|
|
}
|
|
|
|
// Extracts <EventRecordID>NNN</EventRecordID> from a rendered event XML.
|
|
// Returns 0 if not present (shouldn't happen — every Windows event has one).
|
|
static uint64_t ExtractRecordIdFromXml(const std::wstring& xml) {
|
|
auto open = xml.find(L"<EventRecordID>");
|
|
if (open == std::wstring::npos) return 0;
|
|
open += 15; // length of "<EventRecordID>"
|
|
auto close = xml.find(L"</EventRecordID>", open);
|
|
if (close == std::wstring::npos) return 0;
|
|
std::wstring numStr = xml.substr(open, close - open);
|
|
return std::wcstoull(numStr.c_str(), nullptr, 10);
|
|
}
|
|
|
|
// Returns the RecordID of the most recently written event in `channel`.
|
|
// Used to detect channel clears: if our stored watermark > channelMax,
|
|
// the channel was cleared and the new event counter restarted at 1, so
|
|
// we must reset our watermark or risk skipping all new events.
|
|
static uint64_t GetChannelMaxRecordId(const wchar_t* channel) {
|
|
EVT_HANDLE hQuery = EvtQuery(nullptr, channel, nullptr,
|
|
EvtQueryChannelPath | EvtQueryReverseDirection);
|
|
if (!hQuery) return 0;
|
|
|
|
EVT_HANDLE hEvent = nullptr;
|
|
DWORD returned = 0;
|
|
uint64_t maxId = 0;
|
|
if (EvtNext(hQuery, 1, &hEvent, 1000, 0, &returned) && returned > 0) {
|
|
std::vector<wchar_t> buf(4096);
|
|
DWORD used = 0, propCount = 0;
|
|
BOOL ok = EvtRender(nullptr, hEvent, EvtRenderEventXml,
|
|
static_cast<DWORD>(buf.size() * sizeof(wchar_t)),
|
|
buf.data(), &used, &propCount);
|
|
if (!ok && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
|
|
buf.resize(used / sizeof(wchar_t) + 1);
|
|
ok = EvtRender(nullptr, hEvent, EvtRenderEventXml,
|
|
static_cast<DWORD>(buf.size() * sizeof(wchar_t)),
|
|
buf.data(), &used, &propCount);
|
|
}
|
|
if (ok) maxId = ExtractRecordIdFromXml(std::wstring(buf.data()));
|
|
EvtClose(hEvent);
|
|
}
|
|
EvtClose(hQuery);
|
|
return maxId;
|
|
}
|
|
|
|
// ---- Shared implementation -----------------------------------------
|
|
// Runs `query` against the Application channel, formats events as
|
|
// "<DD/MM/YYYY h:mm:ss tt>: <event data>\n"
|
|
// and optionally clears the channel afterwards. If trackWatermark is
|
|
// true, also persists the highest EventRecordID seen to HKCU on return.
|
|
static std::string ReadAnsLoggerEventsImpl(const wchar_t* query,
|
|
bool clearAfterRead,
|
|
bool trackWatermark)
|
|
{
|
|
EVT_HANDLE hResults = EvtQuery(nullptr, L"Application", query,
|
|
EvtQueryChannelPath | EvtQueryForwardDirection);
|
|
if (!hResults) {
|
|
ANS_DBG("EVTLOG", "EvtQuery failed err=%lu", GetLastError());
|
|
return std::string();
|
|
}
|
|
|
|
std::string out;
|
|
uint64_t highestRecordId = 0;
|
|
constexpr DWORD kBatch = 64;
|
|
EVT_HANDLE events[kBatch];
|
|
DWORD returned = 0;
|
|
|
|
// Render-buffer reused across events to avoid per-event allocation.
|
|
std::vector<wchar_t> buf(8192);
|
|
|
|
while (EvtNext(hResults, kBatch, events, INFINITE, 0, &returned)) {
|
|
for (DWORD i = 0; i < returned; ++i) {
|
|
DWORD used = 0, propCount = 0;
|
|
if (!EvtRender(nullptr, events[i], EvtRenderEventXml,
|
|
static_cast<DWORD>(buf.size() * sizeof(wchar_t)),
|
|
buf.data(), &used, &propCount)) {
|
|
DWORD lastErr = GetLastError();
|
|
if (lastErr == ERROR_INSUFFICIENT_BUFFER) {
|
|
buf.resize(used / sizeof(wchar_t) + 1);
|
|
if (!EvtRender(nullptr, events[i], EvtRenderEventXml,
|
|
static_cast<DWORD>(buf.size() * sizeof(wchar_t)),
|
|
buf.data(), &used, &propCount)) {
|
|
EvtClose(events[i]);
|
|
continue;
|
|
}
|
|
} else {
|
|
ANS_DBG("EVTLOG", "EvtRender failed err=%lu", lastErr);
|
|
EvtClose(events[i]);
|
|
continue;
|
|
}
|
|
}
|
|
std::wstring xml(buf.data());
|
|
|
|
// Track the highest RecordID we've seen this call so we can
|
|
// persist it as the new watermark on exit. Done before the
|
|
// continue-on-malformed-XML paths below so an unrenderable
|
|
// event still advances the watermark.
|
|
if (trackWatermark) {
|
|
uint64_t rid = ExtractRecordIdFromXml(xml);
|
|
if (rid > highestRecordId) highestRecordId = rid;
|
|
}
|
|
|
|
// ---- TimeCreated SystemTime='2026-05-18T11:52:07.123Z' ----
|
|
// EvtRender produces either single- or double-quoted attrs
|
|
// depending on Windows version, so handle both.
|
|
std::string formattedTime;
|
|
auto tcPos = xml.find(L"TimeCreated SystemTime=");
|
|
if (tcPos != std::wstring::npos) {
|
|
tcPos += 23; // length of "TimeCreated SystemTime="
|
|
if (tcPos < xml.size() &&
|
|
(xml[tcPos] == L'"' || xml[tcPos] == L'\'')) {
|
|
wchar_t quote = xml[tcPos];
|
|
++tcPos;
|
|
auto endQuote = xml.find(quote, tcPos);
|
|
if (endQuote != std::wstring::npos) {
|
|
std::wstring iso = xml.substr(tcPos, endQuote - tcPos);
|
|
int Y = 0, M = 0, D = 0, h = 0, m = 0, s = 0;
|
|
if (swscanf_s(iso.c_str(), L"%d-%d-%dT%d:%d:%d",
|
|
&Y, &M, &D, &h, &m, &s) == 6) {
|
|
SYSTEMTIME utc{};
|
|
utc.wYear = (WORD)Y; utc.wMonth = (WORD)M; utc.wDay = (WORD)D;
|
|
utc.wHour = (WORD)h; utc.wMinute = (WORD)m; utc.wSecond = (WORD)s;
|
|
SYSTEMTIME local{};
|
|
if (!SystemTimeToTzSpecificLocalTime(nullptr, &utc, &local)) {
|
|
local = utc; // fallback: show UTC
|
|
}
|
|
wchar_t dateBuf[64] = {}, timeBuf[64] = {};
|
|
GetDateFormatW(LOCALE_USER_DEFAULT, 0, &local, nullptr,
|
|
dateBuf, _countof(dateBuf));
|
|
GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &local, nullptr,
|
|
timeBuf, _countof(timeBuf));
|
|
std::wstring combined = std::wstring(dateBuf) + L" " + timeBuf;
|
|
int need = WideCharToMultiByte(CP_UTF8, 0,
|
|
combined.c_str(), -1, nullptr, 0, nullptr, nullptr);
|
|
if (need > 1) {
|
|
formattedTime.resize(need - 1);
|
|
WideCharToMultiByte(CP_UTF8, 0, combined.c_str(), -1,
|
|
formattedTime.data(), need, nullptr, nullptr);
|
|
}
|
|
} // close: if (swscanf_s ... == 6)
|
|
} // close: if (endQuote != npos)
|
|
} // close: if (xml[tcPos] is quote)
|
|
} // close: if (tcPos != npos)
|
|
|
|
// ---- Concatenate every <Data>...</Data> inside <EventData> ----
|
|
// ReportEventW with N strings produces N consecutive <Data>
|
|
// elements. ANSLogger sends just one but we handle the general
|
|
// case so the function works for other sources too.
|
|
std::wstring wdata;
|
|
auto edStart = xml.find(L"<EventData");
|
|
auto edEnd = xml.find(L"</EventData>", edStart);
|
|
if (edStart != std::wstring::npos && edEnd != std::wstring::npos) {
|
|
auto bodyEnd = edEnd;
|
|
auto cursor = edStart;
|
|
while (cursor < bodyEnd) {
|
|
auto dOpen = xml.find(L"<Data", cursor);
|
|
if (dOpen == std::wstring::npos || dOpen >= bodyEnd) break;
|
|
auto dGt = xml.find(L'>', dOpen);
|
|
if (dGt == std::wstring::npos || dGt >= bodyEnd) break;
|
|
auto dClose = xml.find(L"</Data>", dGt);
|
|
if (dClose == std::wstring::npos || dClose > bodyEnd) break;
|
|
if (!wdata.empty()) wdata += L' ';
|
|
wdata.append(xml, dGt + 1, dClose - dGt - 1);
|
|
cursor = dClose + sizeof("</Data>") - 1;
|
|
}
|
|
}
|
|
std::string utf8Data;
|
|
if (!wdata.empty()) {
|
|
int need = WideCharToMultiByte(CP_UTF8, 0, wdata.c_str(), -1,
|
|
nullptr, 0, nullptr, nullptr);
|
|
if (need > 1) {
|
|
utf8Data.resize(need - 1);
|
|
WideCharToMultiByte(CP_UTF8, 0, wdata.c_str(), -1,
|
|
utf8Data.data(), need, nullptr, nullptr);
|
|
}
|
|
}
|
|
|
|
// Flatten embedded CR/LF in the message body so the
|
|
// "one line per event" contract holds. ChilkatLog and
|
|
// similar multi-line payloads otherwise break callers
|
|
// that split on '\n'.
|
|
for (char& c : utf8Data) if (c == '\r' || c == '\n') c = ' ';
|
|
|
|
out += formattedTime;
|
|
out += ": ";
|
|
out += utf8Data;
|
|
out += '\n';
|
|
|
|
EvtClose(events[i]);
|
|
}
|
|
}
|
|
DWORD lastErr = GetLastError();
|
|
if (lastErr != ERROR_NO_MORE_ITEMS) {
|
|
ANS_DBG("EVTLOG", "EvtNext stopped err=%lu", lastErr);
|
|
}
|
|
EvtClose(hResults);
|
|
|
|
// Persist watermark BEFORE clearing — once EvtClearLog succeeds,
|
|
// future events restart at RecordID 1, and we'd never see them
|
|
// again if the watermark stayed at e.g. 547.
|
|
// Special case: if clear is also going to succeed, the new
|
|
// watermark is irrelevant (we'll reset on next call via the
|
|
// GetChannelMaxRecordId check), so writing it here is harmless.
|
|
if (trackWatermark && highestRecordId > 0) {
|
|
WriteAnsLoggerWatermark(highestRecordId);
|
|
ANS_DBG("EVTLOG", "watermark updated to %llu", highestRecordId);
|
|
}
|
|
|
|
if (clearAfterRead) {
|
|
// Clears the entire Application channel — see header warning.
|
|
// DIAGNOSTIC: also print to stderr so callers without DebugView
|
|
// can see what's going on. Common failure codes:
|
|
// 5 ERROR_ACCESS_DENIED — process is not elevated
|
|
// 1314 ERROR_PRIVILEGE_NOT_HELD — token missing SeSecurityPriv
|
|
// 87 ERROR_INVALID_PARAMETER — channel name wrong
|
|
if (!EvtClearLog(nullptr, L"Application", nullptr, 0)) {
|
|
DWORD e = GetLastError();
|
|
ANS_DBG("EVTLOG", "EvtClearLog failed err=%lu (need admin)", e);
|
|
std::fprintf(stderr,
|
|
"[ANSUtilities] EvtClearLog(Application) FAILED, "
|
|
"GetLastError=%lu (5=AccessDenied, 1314=PrivNotHeld)\n", e);
|
|
} else {
|
|
ANS_DBG("EVTLOG", "EvtClearLog: Application channel cleared");
|
|
std::fprintf(stderr,
|
|
"[ANSUtilities] EvtClearLog(Application) OK\n");
|
|
// Clear succeeded → counter resets to 1, so our watermark
|
|
// is stale. Reset it now so the next call doesn't skip
|
|
// legitimate new events whose RecordID < old watermark.
|
|
if (trackWatermark) {
|
|
WriteAnsLoggerWatermark(0);
|
|
ANS_DBG("EVTLOG", "watermark reset to 0 after clear");
|
|
}
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
// ---- Public: full read, no skip ------------------------------------
|
|
std::string ANSUtilities::GetANSLoggerErrorEvents(bool clearAfterRead) {
|
|
// XPath: Provider name "ANSLogger" AND Level 2 (EVENTLOG_ERROR_TYPE).
|
|
// Forward direction keeps chronological insertion order so output
|
|
// matches a fresh "oldest first" scroll through Event Viewer.
|
|
return ReadAnsLoggerEventsImpl(
|
|
L"*[System[Provider[@Name='ANSLogger'] and Level=2]]",
|
|
clearAfterRead,
|
|
/*trackWatermark=*/false);
|
|
}
|
|
|
|
// ---- Public: incremental read using HKCU watermark -----------------
|
|
std::string ANSUtilities::GetANSLoggerErrorEventsSinceLastCall(bool clearAfterRead) {
|
|
uint64_t watermark = ReadAnsLoggerWatermark();
|
|
|
|
// Channel-clear detection: if the channel's current max RecordID
|
|
// is lower than our stored watermark, the log was cleared (by us
|
|
// or by something else like Event Viewer's "Clear Log") and the
|
|
// counter restarted at 1. Reset the watermark so we don't skip
|
|
// events 1..watermark that are actually fresh.
|
|
uint64_t channelMax = GetChannelMaxRecordId(L"Application");
|
|
if (channelMax > 0 && watermark > channelMax) {
|
|
ANS_DBG("EVTLOG", "watermark reset: stored=%llu channelMax=%llu "
|
|
"(channel was cleared externally)",
|
|
watermark, channelMax);
|
|
watermark = 0;
|
|
WriteAnsLoggerWatermark(0);
|
|
}
|
|
|
|
// Embed the watermark in the XPath so Windows does the filtering;
|
|
// we never see events <= watermark, which is more efficient than
|
|
// post-filtering thousands of events on the client side.
|
|
wchar_t queryBuf[256];
|
|
swprintf_s(queryBuf, _countof(queryBuf),
|
|
L"*[System[Provider[@Name='ANSLogger'] and Level=2 and "
|
|
L"(EventRecordID>%llu)]]",
|
|
watermark);
|
|
ANS_DBG("EVTLOG", "GetANSLoggerErrorEventsSinceLastCall watermark=%llu",
|
|
watermark);
|
|
return ReadAnsLoggerEventsImpl(queryBuf, clearAfterRead,
|
|
/*trackWatermark=*/true);
|
|
}
|
|
|
|
} // 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";
|
|
|
|
// HTTP ports answered by AIBOX boxes / ANSVIS servers. AIBOX listens on the
|
|
// default HTTP port; the ANSVIS LabVIEW web server (App_serverConfig.httpPort
|
|
// in ANSVIS.lvproj) listens on 22211. Each host gets probed on both ports.
|
|
constexpr unsigned short kPortAibox = 80;
|
|
constexpr unsigned short kPortAnsvis = 22211;
|
|
constexpr unsigned short kSweepPorts[] = { kPortAibox, kPortAnsvis };
|
|
|
|
// ---- 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 ----------------------------
|
|
// parts[0] and parts[1] are not used by the AIBOX Flutter app but the device
|
|
// still sends them. Observed devices put their listen port in one of those
|
|
// two fields, so we try both — first numeric wins. Unparseable -> port = 0.
|
|
void ParseUdpReply(const std::string& body, std::string& name,
|
|
std::string& firmware, int& port) {
|
|
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 = "-"; }
|
|
|
|
port = 0;
|
|
auto tryPort = [&](const std::string& s) {
|
|
if (port != 0 || s.empty() || s.size() > 5) return;
|
|
for (char c : s) if (c < '0' || c > '9') return;
|
|
int v = std::atoi(s.c_str());
|
|
if (v > 0 && v < 65536) port = v;
|
|
};
|
|
if (parts.size() > 0) tryPort(parts[0]);
|
|
if (parts.size() > 1) tryPort(parts[1]);
|
|
}
|
|
|
|
// ---- 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 port, 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;
|
|
// Port precedence: an HTTP probe proves the port actually responds,
|
|
// so a sweep-supplied port overwrites whatever UDP parsing guessed.
|
|
// A UDP-supplied port is only kept if HTTP hasn't filled it in.
|
|
if (port > 0) {
|
|
const bool fromHttp = (srcBit == kSrcSweep);
|
|
const bool fromHttpAlready = (d.source & kSrcSweep) != 0;
|
|
if (fromHttp || !fromHttpAlready) d.port = port;
|
|
}
|
|
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;
|
|
int port = 0;
|
|
ParseUdpReply(body, name, fw, port);
|
|
ANS_DBG("ANSDISC", "UDP reply from %s name=%s fw=%s port=%d raw=%s",
|
|
ipStr, name.c_str(), fw.c_str(), port, body.c_str());
|
|
state.merge(ipStr, name, fw, port, 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, unsigned short port, 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(),
|
|
static_cast<INTERNET_PORT>(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 (ip, port) -----
|
|
// Each host is probed on every port in kSweepPorts (80 + 22211) so one
|
|
// sweep covers both AIBOX and ANSVIS.
|
|
void RunHttpSweep(ScanState& state, const std::vector<LocalSubnet>& subnets) {
|
|
struct Target { std::string ip; unsigned short port; };
|
|
std::queue<Target> q;
|
|
for (const auto& net : subnets) {
|
|
for (int h = 1; h <= 254; ++h) {
|
|
std::string ip = net.prefix + std::to_string(h);
|
|
for (unsigned short p : kSweepPorts) q.push({ ip, p });
|
|
}
|
|
}
|
|
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;
|
|
Target t;
|
|
{
|
|
std::lock_guard<std::mutex> lk(qmu);
|
|
if (q.empty()) return;
|
|
t = std::move(q.front());
|
|
q.pop();
|
|
}
|
|
std::string ver;
|
|
if (ProbeHttp(t.ip, t.port, ver)) {
|
|
ANS_DBG("ANSDISC", "HTTP hit %s:%u version=%s",
|
|
t.ip.c_str(), static_cast<unsigned>(t.port), ver.c_str());
|
|
state.merge(t.ip, std::string(), ver, static_cast<int>(t.port), 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
|
|
|