Initial native C++ DUO-RDP release source and documentation

This commit is contained in:
SoGi committed 2026-10-21 13:38:44 +02:00
commit 65b2145791
42 files changed
+5506

No files matched your search

+68
View File
@@ -0,0 +1,68 @@
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
#include <windows.h>
#include <cstdio>
#include <string>
#include <vector>
namespace {
std::wstring module_directory() {
std::vector<wchar_t> buffer(32768U, L'\0');
const DWORD length = GetModuleFileNameW(nullptr, buffer.data(), static_cast<DWORD>(buffer.size()));
if (length == 0 || length >= buffer.size()) return {};
std::wstring path(buffer.data(), length);
const size_t slash = path.find_last_of(L"\\/");
return slash == std::wstring::npos ? std::wstring{} : path.substr(0, slash);
}
std::wstring quote(const std::wstring& value) {
std::wstring output = L"\"";
size_t slashCount = 0;
for (wchar_t character : value) {
if (character == L'\\') {
++slashCount;
continue;
}
if (character == L'\"') output.append(slashCount * 2U + 1U, L'\\');
else output.append(slashCount, L'\\');
slashCount = 0;
output.push_back(character);
}
output.append(slashCount * 2U, L'\\');
output.push_back(L'\"');
return output;
}
} // namespace
int wmain(int argc, wchar_t** argv) {
const std::wstring service = module_directory() + L"\\DuoRdpAuthService.exe";
if (GetFileAttributesW(service.c_str()) == INVALID_FILE_ATTRIBUTES) {
std::fwprintf(stderr, L"DuoRdpAuthService.exe is missing next to DuoRdpAdmin.exe.\n");
return 2;
}
std::wstring command = quote(service) + L" --admin";
for (int index = 1; index < argc; ++index) command += L" " + quote(argv[index]);
std::vector<wchar_t> mutableCommand(command.begin(), command.end());
mutableCommand.push_back(L'\0');
STARTUPINFOW startup{};
startup.cb = sizeof(startup);
PROCESS_INFORMATION process{};
if (!CreateProcessW(nullptr, mutableCommand.data(), nullptr, nullptr, TRUE, 0, nullptr, module_directory().c_str(), &startup, &process)) {
std::fwprintf(stderr, L"Cannot launch native admin core, error=%lu.\n", GetLastError());
return 1;
}
CloseHandle(process.hThread);
WaitForSingleObject(process.hProcess, INFINITE);
DWORD exitCode = 1;
GetExitCodeProcess(process.hProcess, &exitCode);
CloseHandle(process.hProcess);
return static_cast<int>(exitCode);
}
File diff suppressed because it is too large. Load diff
+457
View File
@@ -0,0 +1,457 @@
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
#include <windows.h>
#include <winsvc.h>
#include <sddl.h>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <string>
#include <string_view>
#include <vector>
namespace {
constexpr wchar_t kServiceName[] = L"DuoRdpAuthService";
constexpr wchar_t kPipeName[] = L"\\\\.\\pipe\\duordp-auth-pipe";
constexpr wchar_t kProviderClsid[] = L"{8F04B2A1-7C4C-4E47-9D26-9B8E744B2501}";
constexpr wchar_t kFilterClsid[] = L"{D6E4A825-8E89-49D8-A5B2-F30B7E681A39}";
std::wstring module_directory() {
std::vector<wchar_t> buffer(32768U, L'\0');
const DWORD length = GetModuleFileNameW(nullptr, buffer.data(), static_cast<DWORD>(buffer.size()));
if (length == 0 || length >= buffer.size()) return {};
std::wstring path(buffer.data(), length);
const size_t slash = path.find_last_of(L"\\/");
return slash == std::wstring::npos ? std::wstring{} : path.substr(0, slash);
}
std::wstring program_files_directory() {
wchar_t buffer[MAX_PATH]{};
const DWORD length = GetEnvironmentVariableW(L"ProgramFiles", buffer, ARRAYSIZE(buffer));
return length > 0 && length < ARRAYSIZE(buffer) ? std::wstring(buffer) : L"C:\\Program Files";
}
std::wstring program_data_directory() {
wchar_t buffer[MAX_PATH]{};
const DWORD length = GetEnvironmentVariableW(L"ProgramData", buffer, ARRAYSIZE(buffer));
return length > 0 && length < ARRAYSIZE(buffer) ? std::wstring(buffer) : L"C:\\ProgramData";
}
void ensure_directory(const std::wstring& directory) {
std::wstring current;
size_t start = 0;
if (directory.size() >= 2 && directory[1] == L':') {
current.assign(directory, 0, 2);
start = 2;
if (start < directory.size() && (directory[start] == L'\\' || directory[start] == L'/')) ++start;
}
while (start < directory.size()) {
const size_t end = directory.find_first_of(L"\\/", start);
const std::wstring part = directory.substr(start, end == std::wstring::npos ? std::wstring::npos : end - start);
if (!part.empty()) {
if (current.empty()) current = part;
else if (current.size() == 2 && current[1] == L':') current += L"\\" + part;
else current += L"\\" + part;
if (current.size() != 2 || current[1] != L':') CreateDirectoryW(current.c_str(), nullptr);
}
if (end == std::wstring::npos) break;
start = end + 1;
}
}
std::wstring timestamp() {
SYSTEMTIME now{};
GetLocalTime(&now);
wchar_t value[32]{};
std::swprintf(value, ARRAYSIZE(value), L"%04u%02u%02u-%02u%02u%02u", now.wYear, now.wMonth, now.wDay, now.wHour, now.wMinute, now.wSecond);
return value;
}
bool is_elevated() {
HANDLE token = nullptr;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) return false;
TOKEN_ELEVATION elevation{};
DWORD read = 0;
const bool result = GetTokenInformation(token, TokenElevation, &elevation, sizeof(elevation), &read) != FALSE && elevation.TokenIsElevated != 0;
CloseHandle(token);
return result;
}
bool exists(const std::wstring& path) {
return GetFileAttributesW(path.c_str()) != INVALID_FILE_ATTRIBUTES;
}
bool config_is_safe_to_migrate(const std::wstring& configPath, std::wstring& error) {
if (!exists(configPath)) return true;
FILE* file = _wfopen(configPath.c_str(), L"rb");
if (!file) {
error = L"cannot read existing configuration";
return false;
}
char prefix[64]{};
const size_t count = std::fread(prefix, 1, sizeof(prefix) - 1U, file);
std::fclose(file);
std::string head(prefix, count);
if (head.size() >= 3 && static_cast<unsigned char>(head[0]) == 0xefU && static_cast<unsigned char>(head[1]) == 0xbbU && static_cast<unsigned char>(head[2]) == 0xbfU) head.erase(0, 3);
if (head.rfind("DUORDP_CONFIG_V1:ENCv1:", 0) == 0) {
error = L"existing ENCv1 configuration must be migrated with the legacy DUO-RDP admin before installing the native release";
return false;
}
return true;
}
bool restrict_config_acl(const std::wstring& configPath, std::wstring& error) {
PSECURITY_DESCRIPTOR descriptor = nullptr;
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(A;;FA;;;SY)(A;;FA;;;BA)", SDDL_REVISION_1, &descriptor, nullptr)) {
error = L"cannot create restrictive config ACL";
return false;
}
const BOOL applied = SetFileSecurityW(configPath.c_str(), DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, descriptor);
LocalFree(descriptor);
if (!applied) {
error = L"cannot protect config ACL";
return false;
}
return true;
}
bool copy_file_with_backup(const std::wstring& source, const std::wstring& destination, const std::wstring& backupDirectory, std::wstring& error) {
if (!exists(source)) {
error = L"payload missing: " + source;
return false;
}
if (exists(destination)) {
ensure_directory(backupDirectory);
const size_t slash = destination.find_last_of(L"\\/");
const std::wstring name = slash == std::wstring::npos ? destination : destination.substr(slash + 1);
if (!CopyFileW(destination.c_str(), (backupDirectory + L"\\" + name).c_str(), TRUE)) {
error = L"cannot back up existing file: " + destination;
return false;
}
}
if (!CopyFileW(source.c_str(), destination.c_str(), FALSE)) {
error = L"cannot copy payload: " + source;
return false;
}
return true;
}
bool set_default_reg_value(HKEY root, const std::wstring& key, const wchar_t* value, std::wstring& error) {
HKEY handle = nullptr;
if (RegCreateKeyExW(root, key.c_str(), 0, nullptr, 0, KEY_SET_VALUE, nullptr, &handle, nullptr) != ERROR_SUCCESS) {
error = L"registry key creation failed: " + key;
return false;
}
const DWORD bytes = static_cast<DWORD>((std::wcslen(value) + 1U) * sizeof(wchar_t));
const LONG result = RegSetValueExW(handle, nullptr, 0, REG_SZ, reinterpret_cast<const BYTE*>(value), bytes);
RegCloseKey(handle);
if (result != ERROR_SUCCESS) {
error = L"registry value write failed: " + key;
return false;
}
return true;
}
void delete_reg_tree(const std::wstring& key) {
RegDeleteTreeW(HKEY_LOCAL_MACHINE, key.c_str());
}
bool invoke_registration(const std::wstring& dllPath, bool registerServer, std::wstring& error) {
HMODULE module = LoadLibraryExW(dllPath.c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
if (!module) {
error = L"Credential Provider DLL cannot be loaded, error=" + std::to_wstring(GetLastError());
return false;
}
using RegistrationFn = HRESULT(STDAPICALLTYPE*)();
const char* functionName = registerServer ? "DllRegisterServer" : "DllUnregisterServer";
const FARPROC rawRegistration = GetProcAddress(module, functionName);
RegistrationFn registration = nullptr;
static_assert(sizeof(rawRegistration) == sizeof(registration));
std::memcpy(&registration, &rawRegistration, sizeof(registration));
if (!registration) {
FreeLibrary(module);
error = L"Credential Provider export missing";
return false;
}
const HRESULT result = registration();
FreeLibrary(module);
if (FAILED(result)) {
error = L"Credential Provider registration failed, HRESULT=" + std::to_wstring(result);
return false;
}
return true;
}
bool validate_dll_load(const std::wstring& dllPath, std::wstring& error) {
HMODULE module = LoadLibraryExW(dllPath.c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
if (!module) {
error = L"Credential Provider DLL cannot be loaded, error=" + std::to_wstring(GetLastError());
return false;
}
FreeLibrary(module);
return true;
}
void stop_delete_service() {
SC_HANDLE manager = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_CONNECT);
if (!manager) return;
SC_HANDLE service = OpenServiceW(manager, kServiceName, SERVICE_STOP | SERVICE_QUERY_STATUS | DELETE);
if (!service) {
CloseServiceHandle(manager);
return;
}
SERVICE_STATUS status{};
ControlService(service, SERVICE_CONTROL_STOP, &status);
for (int i = 0; i < 50; ++i) {
SERVICE_STATUS_PROCESS process{};
DWORD needed = 0;
if (!QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO, reinterpret_cast<BYTE*>(&process), sizeof(process), &needed) || process.dwCurrentState == SERVICE_STOPPED) break;
Sleep(100);
}
DeleteService(service);
CloseServiceHandle(service);
CloseServiceHandle(manager);
}
bool create_start_service(const std::wstring& executable, std::wstring& error) {
stop_delete_service();
SC_HANDLE manager = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_CREATE_SERVICE);
if (!manager) {
error = L"cannot open Service Control Manager";
return false;
}
const std::wstring quoted = L"\"" + executable + L"\"";
SC_HANDLE service = CreateServiceW(manager, kServiceName, L"DUO-RDP native 2FA service", SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, quoted.c_str(), nullptr, nullptr, nullptr,
L"LocalSystem", nullptr);
if (!service) {
error = L"cannot create native service, error=" + std::to_wstring(GetLastError());
CloseServiceHandle(manager);
return false;
}
SERVICE_FAILURE_ACTIONSW failure{};
SC_ACTION actions[3]{};
for (SC_ACTION& action : actions) {
action.Type = SC_ACTION_RESTART;
action.Delay = 5000;
}
failure.dwResetPeriod = 86400;
failure.cActions = ARRAYSIZE(actions);
failure.lpsaActions = actions;
ChangeServiceConfig2W(service, SERVICE_CONFIG_FAILURE_ACTIONS, &failure);
if (!StartServiceW(service, 0, nullptr)) {
error = L"cannot start native service, error=" + std::to_wstring(GetLastError());
CloseServiceHandle(service);
CloseServiceHandle(manager);
return false;
}
CloseServiceHandle(service);
CloseServiceHandle(manager);
return true;
}
bool pipe_health(std::wstring& error) {
for (int attempt = 0; attempt < 60; ++attempt) {
if (!WaitNamedPipeW(kPipeName, 250)) {
Sleep(100);
continue;
}
HANDLE pipe = CreateFileW(kPipeName, GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr);
if (pipe == INVALID_HANDLE_VALUE) continue;
static constexpr char request[] = "{\"action\":\"GetPolicy\",\"username\":\"installer-health\",\"groups\":[]}\n";
DWORD written = 0;
char response[4096]{};
DWORD read = 0;
const bool ok = WriteFile(pipe, request, sizeof(request) - 1U, &written, nullptr) != FALSE
&& ReadFile(pipe, response, sizeof(response) - 1U, &read, nullptr) != FALSE
&& read > 0;
CloseHandle(pipe);
const std::string body(response, read);
if (ok && body.find("\"required\"") != std::string::npos && body.find("\"status\":\"error\"") == std::string::npos) return true;
Sleep(100);
}
error = L"native service did not pass the named-pipe health check";
return false;
}
int install(const std::wstring& payloadDirectory) {
if (!is_elevated()) {
std::fputs("Installer requires an elevated administrator token.\n", stderr);
return 2;
}
const std::wstring installDirectory = program_files_directory() + L"\\DuoRdp";
const std::wstring backupDirectory = installDirectory + L"\\backup\\" + timestamp();
const std::wstring serviceSource = payloadDirectory + L"\\DuoRdpAuthService.exe";
const std::wstring adminSource = payloadDirectory + L"\\DuoRdpAdmin.exe";
const std::wstring providerSource = payloadDirectory + L"\\DuoRdpCredentialProvider.dll";
const std::wstring uninstallerSource = payloadDirectory + L"\\DUOUnIstall.exe";
std::wstring error;
if (!exists(serviceSource) || !exists(adminSource) || !exists(providerSource) || !exists(uninstallerSource)) {
std::fputs("Payload must contain DuoRdpAuthService.exe, DuoRdpAdmin.exe, DuoRdpCredentialProvider.dll and DUOUnIstall.exe.\n", stderr);
return 2;
}
if (!config_is_safe_to_migrate(installDirectory + L"\\config.json", error)) {
std::fwprintf(stderr, L"Install blocked before service/filter changes: %s\n", error.c_str());
return 1;
}
if (!validate_dll_load(providerSource, error)) {
std::fwprintf(stderr, L"Preflight failed: %s\n", error.c_str());
return 1;
}
ensure_directory(installDirectory);
if (!copy_file_with_backup(serviceSource, installDirectory + L"\\DuoRdpAuthService.exe", backupDirectory, error)
|| !copy_file_with_backup(adminSource, installDirectory + L"\\DuoRdpAdmin.exe", backupDirectory, error)
|| !copy_file_with_backup(providerSource, installDirectory + L"\\DuoRdpCredentialProvider.dll", backupDirectory, error)
|| !copy_file_with_backup(uninstallerSource, installDirectory + L"\\DUOUnIstall.exe", backupDirectory, error)) {
std::fwprintf(stderr, L"Install failed: %s\n", error.c_str());
return 1;
}
const std::wstring installedService = installDirectory + L"\\DuoRdpAuthService.exe";
const std::wstring installedProvider = installDirectory + L"\\DuoRdpCredentialProvider.dll";
if (!exists(installDirectory + L"\\config.json")) {
std::wstring command = L"\"" + installedService + L"\" --admin init";
STARTUPINFOW startup{};
startup.cb = sizeof(startup);
PROCESS_INFORMATION process{};
std::vector<wchar_t> mutableCommand(command.begin(), command.end());
mutableCommand.push_back(L'\0');
if (!CreateProcessW(nullptr, mutableCommand.data(), nullptr, nullptr, FALSE, 0, nullptr, installDirectory.c_str(), &startup, &process)) {
std::fputs("Install failed: cannot initialize native configuration.\n", stderr);
return 1;
}
WaitForSingleObject(process.hProcess, INFINITE);
DWORD exitCode = 1;
GetExitCodeProcess(process.hProcess, &exitCode);
CloseHandle(process.hThread);
CloseHandle(process.hProcess);
if (exitCode != 0) return 1;
}
if (!restrict_config_acl(installDirectory + L"\\config.json", error)) {
std::fwprintf(stderr, L"Install failed before service/filter changes: %s\n", error.c_str());
return 1;
}
if (!invoke_registration(installedProvider, true, error)
|| !set_default_reg_value(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Authentication\\Credential Providers\\" + std::wstring(kProviderClsid), L"DuoRdp Credential Provider", error)
|| !create_start_service(installedService, error)
|| !pipe_health(error)) {
std::fwprintf(stderr, L"Install failed before filter activation: %s\n", error.c_str());
return 1;
}
// The filter can hide the stock password provider. It is enabled last,
// after the service and pipe have proved healthy.
if (!set_default_reg_value(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Authentication\\Credential Provider Filters\\" + std::wstring(kFilterClsid), L"DuoRdp Credential Filter", error)) {
std::fwprintf(stderr, L"Install failed while enabling filter: %s\n", error.c_str());
return 1;
}
std::wprintf(L"DUO-RDP native C++ installation complete: %s\n", installDirectory.c_str());
return 0;
}
int uninstall(bool purgeData) {
if (!is_elevated()) {
std::fputs("Uninstaller requires an elevated administrator token.\n", stderr);
return 2;
}
const std::wstring installDirectory = program_files_directory() + L"\\DuoRdp";
const std::wstring backupDirectory = installDirectory + L"\\backup\\uninstall-" + timestamp();
const std::wstring provider = installDirectory + L"\\DuoRdpCredentialProvider.dll";
// Recovery ordering: make the stock password provider visible first.
delete_reg_tree(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Authentication\\Credential Provider Filters\\" + std::wstring(kFilterClsid));
delete_reg_tree(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Authentication\\Credential Providers\\" + std::wstring(kProviderClsid));
stop_delete_service();
std::wstring ignored;
if (exists(provider)) invoke_registration(provider, false, ignored);
for (const wchar_t* name : {L"DuoRdpAuthService.exe", L"DuoRdpAdmin.exe", L"DuoRdpCredentialProvider.dll"}) {
const std::wstring source = installDirectory + L"\\" + name;
if (!exists(source)) continue;
ensure_directory(backupDirectory);
CopyFileW(source.c_str(), (backupDirectory + L"\\" + name).c_str(), TRUE);
DeleteFileW(source.c_str());
}
if (purgeData) {
DeleteFileW((installDirectory + L"\\config.json").c_str());
DeleteFileW((installDirectory + L"\\logs.txt").c_str());
const std::wstring logDirectory = program_data_directory() + L"\\DuoRdp";
DeleteFileW((logDirectory + L"\\logs.txt").c_str());
RemoveDirectoryW(logDirectory.c_str());
}
std::puts("DUO-RDP native uninstall complete. Config and logs were kept unless --purge-data was supplied.");
return 0;
}
void usage() {
std::puts("DuoRdpInstaller.exe --install [--payload <directory>] | --uninstall [--purge-data] | --self-test");
}
bool run_self_test() {
const bool constantsOk = std::wstring_view(kPipeName) == L"\\\\.\\pipe\\duordp-auth-pipe" && std::wstring_view(kServiceName) == L"DuoRdpAuthService";
wchar_t temporary[MAX_PATH]{};
if (!GetTempPathW(ARRAYSIZE(temporary), temporary)) return false;
const std::wstring directory = std::wstring(temporary) + L"DuoRdpNativeInstallerSelfTest";
ensure_directory(directory);
const std::wstring config = directory + L"\\config.json";
{
FILE* file = _wfopen(config.c_str(), L"wb");
if (!file) return false;
static constexpr char legacy[] = "DUORDP_CONFIG_V1:ENCv1:test";
std::fwrite(legacy, 1, sizeof(legacy) - 1U, file);
std::fclose(file);
}
std::wstring migrationError;
const bool legacyBlocked = !config_is_safe_to_migrate(config, migrationError) && !migrationError.empty();
{
FILE* file = _wfopen(config.c_str(), L"wb");
if (!file) return false;
static constexpr char plain[] = "{\"version\":1}";
std::fwrite(plain, 1, sizeof(plain) - 1U, file);
std::fclose(file);
}
migrationError.clear();
const bool plainAccepted = config_is_safe_to_migrate(config, migrationError);
DeleteFileW(config.c_str());
RemoveDirectoryW(directory.c_str());
return constantsOk && legacyBlocked && plainAccepted;
}
} // namespace
int wmain(int argc, wchar_t** argv) {
#ifdef DUO_RDP_UNINSTALL_DEFAULT
if (argc == 1) return uninstall(false);
#endif
if (argc == 2 && std::wstring_view(argv[1]) == L"--self-test") {
const bool passed = run_self_test();
std::puts(passed ? "INSTALLER SELFTEST PASS" : "INSTALLER SELFTEST FAIL");
return passed ? 0 : 1;
}
if (argc < 2) {
usage();
return 2;
}
const std::wstring_view command = argv[1];
if (command == L"--install") {
std::wstring payload = module_directory() + L"\\payload";
if (argc == 4 && std::wstring_view(argv[2]) == L"--payload") payload = argv[3];
else if (argc != 2) {
usage();
return 2;
}
return install(payload);
}
if (command == L"--uninstall") {
if (argc > 3 || (argc == 3 && std::wstring_view(argv[2]) != L"--purge-data")) {
usage();
return 2;
}
return uninstall(argc == 3);
}
usage();
return 2;
}
+13
View File
@@ -0,0 +1,13 @@
# Native C++ runtime
Этот каталог - canonical source для текущего DUO-RDP native release. Он заменяет прежний C#/Python broker, HTTP OTP service, PyInstaller GUI-admin и installer chain.
- `DuoRdpAuthService.exe` - Windows service и единственный OTP runtime. Он обслуживает `\\.\pipe\duordp-auth-pipe` по JSONL protocol v2, хранит OTP-сессии в памяти, отправляет Telegram через WinHTTP, проверяет TOTP и читает machine-DPAPI конфиг.
- `DuoRdpAdmin.exe` - launcher для `DuoRdpAuthService.exe --admin`; токен передаётся только через `--token-stdin`.
- `DuoRdpInstaller.exe` и `DUOUnIstall.exe` - native installer/recovery. Installer проверяет DLL, конфиг, service и live pipe до регистрации Filter. Uninstaller сначала снимает Filter и по умолчанию сохраняет config/logs.
Каждый явный `RequestOtp` заменяет запись конкретной плитки. Старый код этой плитки перестаёт работать немедленно; коды параллельных плиток не конфликтуют. Login-submit код сам не отправляет.
Legacy `ENCv1` config намеренно блокируется до любых изменений: сначала его нужно мигрировать старым admin tool, затем ставить native release. Это предотвращает fail-closed lockout.
Инструкции: [сборка](../../docs/BUILD.md), [установка](../../docs/INSTALL.md), [проверка](../../docs/TESTING.md), [protocol](../../docs/PROTOCOL.md).
+377
View File
@@ -0,0 +1,377 @@
#pragma once
#include <cctype>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <map>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
// Small, dependency-free JSON value/parser for DUO-RDP's local config and
// newline-delimited pipe protocol. It deliberately supports the complete JSON
// grammar used by the product, while keeping the native service self-contained.
namespace duo {
class Json final {
public:
enum class Type { Null, Bool, Number, String, Array, Object };
using Array = std::vector<Json>;
using Object = std::map<std::string, Json, std::less<>>;
Json() = default;
Json(std::nullptr_t) : type_(Type::Null) {}
Json(bool value) : type_(Type::Bool), bool_(value) {}
Json(int value) : type_(Type::Number), number_(static_cast<double>(value)) {}
Json(std::int64_t value) : type_(Type::Number), number_(static_cast<double>(value)) {}
Json(double value) : type_(Type::Number), number_(value) {}
Json(const char* value) : type_(Type::String), string_(value ? value : "") {}
Json(std::string value) : type_(Type::String), string_(std::move(value)) {}
Json(Array value) : type_(Type::Array), array_(std::move(value)) {}
Json(Object value) : type_(Type::Object), object_(std::move(value)) {}
[[nodiscard]] Type type() const noexcept { return type_; }
[[nodiscard]] bool is_null() const noexcept { return type_ == Type::Null; }
[[nodiscard]] bool is_bool() const noexcept { return type_ == Type::Bool; }
[[nodiscard]] bool is_number() const noexcept { return type_ == Type::Number; }
[[nodiscard]] bool is_string() const noexcept { return type_ == Type::String; }
[[nodiscard]] bool is_array() const noexcept { return type_ == Type::Array; }
[[nodiscard]] bool is_object() const noexcept { return type_ == Type::Object; }
[[nodiscard]] bool bool_or(bool fallback = false) const noexcept {
return is_bool() ? bool_ : fallback;
}
[[nodiscard]] int int_or(int fallback = 0) const noexcept {
if (!is_number() || !std::isfinite(number_)) return fallback;
return static_cast<int>(number_);
}
[[nodiscard]] std::string string_or(std::string fallback = {}) const {
return is_string() ? string_ : fallback;
}
[[nodiscard]] const Array& array_or_empty() const noexcept {
static const Array empty;
return is_array() ? array_ : empty;
}
[[nodiscard]] const Object& object_or_empty() const noexcept {
static const Object empty;
return is_object() ? object_ : empty;
}
[[nodiscard]] const Json* find(std::string_view key) const noexcept {
if (!is_object()) return nullptr;
const auto it = object_.find(key);
return it == object_.end() ? nullptr : &it->second;
}
[[nodiscard]] Json* find(std::string_view key) noexcept {
if (!is_object()) return nullptr;
const auto it = object_.find(key);
return it == object_.end() ? nullptr : &it->second;
}
Json& operator[](const std::string& key) {
if (!is_object()) {
type_ = Type::Object;
object_.clear();
string_.clear();
array_.clear();
}
return object_[key];
}
[[nodiscard]] std::string dump() const {
std::string out;
dump_into(out);
return out;
}
static Json parse(const std::string& input) {
Parser parser(input);
Json value = parser.parse_value();
parser.skip_space();
if (!parser.at_end()) throw std::runtime_error("trailing JSON input");
return value;
}
private:
class Parser final {
public:
explicit Parser(const std::string& input) : input_(input) {}
void skip_space() {
while (pos_ < input_.size() && std::isspace(static_cast<unsigned char>(input_[pos_]))) ++pos_;
}
[[nodiscard]] bool at_end() const noexcept { return pos_ >= input_.size(); }
Json parse_value() {
skip_space();
if (at_end()) throw std::runtime_error("unexpected end of JSON");
switch (input_[pos_]) {
case 'n': consume_literal("null"); return Json();
case 't': consume_literal("true"); return Json(true);
case 'f': consume_literal("false"); return Json(false);
case '"': return Json(parse_string());
case '[': return parse_array();
case '{': return parse_object();
default: return Json(parse_number());
}
}
private:
void consume_literal(std::string_view literal) {
if (input_.compare(pos_, literal.size(), literal) != 0) throw std::runtime_error("invalid JSON literal");
pos_ += literal.size();
}
char take() {
if (at_end()) throw std::runtime_error("unexpected end of JSON");
return input_[pos_++];
}
void expect(char expected) {
if (take() != expected) throw std::runtime_error("invalid JSON syntax");
}
static unsigned hex_value(char c) {
if (c >= '0' && c <= '9') return static_cast<unsigned>(c - '0');
if (c >= 'a' && c <= 'f') return static_cast<unsigned>(c - 'a' + 10);
if (c >= 'A' && c <= 'F') return static_cast<unsigned>(c - 'A' + 10);
throw std::runtime_error("invalid JSON unicode escape");
}
unsigned parse_u16() {
unsigned value = 0;
for (int i = 0; i < 4; ++i) value = (value << 4U) | hex_value(take());
return value;
}
static void append_utf8(std::string& out, std::uint32_t cp) {
if (cp <= 0x7fU) {
out.push_back(static_cast<char>(cp));
} else if (cp <= 0x7ffU) {
out.push_back(static_cast<char>(0xc0U | (cp >> 6U)));
out.push_back(static_cast<char>(0x80U | (cp & 0x3fU)));
} else if (cp <= 0xffffU) {
out.push_back(static_cast<char>(0xe0U | (cp >> 12U)));
out.push_back(static_cast<char>(0x80U | ((cp >> 6U) & 0x3fU)));
out.push_back(static_cast<char>(0x80U | (cp & 0x3fU)));
} else {
out.push_back(static_cast<char>(0xf0U | (cp >> 18U)));
out.push_back(static_cast<char>(0x80U | ((cp >> 12U) & 0x3fU)));
out.push_back(static_cast<char>(0x80U | ((cp >> 6U) & 0x3fU)));
out.push_back(static_cast<char>(0x80U | (cp & 0x3fU)));
}
}
std::string parse_string() {
expect('"');
std::string out;
while (!at_end()) {
const char c = take();
if (c == '"') return out;
if (static_cast<unsigned char>(c) < 0x20U) throw std::runtime_error("control character in JSON string");
if (c != '\\') {
out.push_back(c);
continue;
}
switch (take()) {
case '"': out.push_back('"'); break;
case '\\': out.push_back('\\'); break;
case '/': out.push_back('/'); break;
case 'b': out.push_back('\b'); break;
case 'f': out.push_back('\f'); break;
case 'n': out.push_back('\n'); break;
case 'r': out.push_back('\r'); break;
case 't': out.push_back('\t'); break;
case 'u': {
std::uint32_t cp = parse_u16();
if (cp >= 0xd800U && cp <= 0xdbffU) {
if (take() != '\\' || take() != 'u') throw std::runtime_error("unpaired JSON surrogate");
const std::uint32_t low = parse_u16();
if (low < 0xdc00U || low > 0xdfffU) throw std::runtime_error("invalid JSON surrogate");
cp = 0x10000U + ((cp - 0xd800U) << 10U) + (low - 0xdc00U);
}
append_utf8(out, cp);
break;
}
default: throw std::runtime_error("invalid JSON escape");
}
}
throw std::runtime_error("unterminated JSON string");
}
double parse_number() {
const size_t start = pos_;
if (input_[pos_] == '-') ++pos_;
if (pos_ >= input_.size()) throw std::runtime_error("invalid JSON number");
if (input_[pos_] == '0') {
++pos_;
} else {
if (!std::isdigit(static_cast<unsigned char>(input_[pos_]))) throw std::runtime_error("invalid JSON number");
while (pos_ < input_.size() && std::isdigit(static_cast<unsigned char>(input_[pos_]))) ++pos_;
}
if (pos_ < input_.size() && input_[pos_] == '.') {
++pos_;
const size_t fraction = pos_;
while (pos_ < input_.size() && std::isdigit(static_cast<unsigned char>(input_[pos_]))) ++pos_;
if (fraction == pos_) throw std::runtime_error("invalid JSON fraction");
}
if (pos_ < input_.size() && (input_[pos_] == 'e' || input_[pos_] == 'E')) {
++pos_;
if (pos_ < input_.size() && (input_[pos_] == '+' || input_[pos_] == '-')) ++pos_;
const size_t exponent = pos_;
while (pos_ < input_.size() && std::isdigit(static_cast<unsigned char>(input_[pos_]))) ++pos_;
if (exponent == pos_) throw std::runtime_error("invalid JSON exponent");
}
const std::string token = input_.substr(start, pos_ - start);
char* end = nullptr;
const double value = std::strtod(token.c_str(), &end);
if (!end || *end != '\0' || !std::isfinite(value)) throw std::runtime_error("invalid JSON number");
return value;
}
Json parse_array() {
expect('[');
Array result;
skip_space();
if (!at_end() && input_[pos_] == ']') {
++pos_;
return Json(std::move(result));
}
for (;;) {
result.emplace_back(parse_value());
skip_space();
const char separator = take();
if (separator == ']') break;
if (separator != ',') throw std::runtime_error("invalid JSON array");
}
return Json(std::move(result));
}
Json parse_object() {
expect('{');
Object result;
skip_space();
if (!at_end() && input_[pos_] == '}') {
++pos_;
return Json(std::move(result));
}
for (;;) {
skip_space();
if (at_end() || input_[pos_] != '"') throw std::runtime_error("invalid JSON object key");
std::string key = parse_string();
skip_space();
expect(':');
result[std::move(key)] = parse_value();
skip_space();
const char separator = take();
if (separator == '}') break;
if (separator != ',') throw std::runtime_error("invalid JSON object");
}
return Json(std::move(result));
}
const std::string& input_;
size_t pos_ = 0;
};
static void append_escaped(std::string& out, const std::string& value) {
out.push_back('"');
static constexpr char hex[] = "0123456789abcdef";
for (const unsigned char c : value) {
switch (c) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\b': out += "\\b"; break;
case '\f': out += "\\f"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (c < 0x20U) {
out += "\\u00";
out.push_back(hex[(c >> 4U) & 0x0fU]);
out.push_back(hex[c & 0x0fU]);
} else {
out.push_back(static_cast<char>(c));
}
}
}
out.push_back('"');
}
void dump_into(std::string& out) const {
switch (type_) {
case Type::Null: out += "null"; break;
case Type::Bool: out += bool_ ? "true" : "false"; break;
case Type::Number: {
const std::string number = std::to_string(number_);
const size_t point = number.find('.');
if (point == std::string::npos) {
out += number;
} else {
size_t end = number.size();
while (end > point + 1 && number[end - 1] == '0') --end;
if (end == point + 1) --end;
out.append(number, 0, end);
}
break;
}
case Type::String: append_escaped(out, string_); break;
case Type::Array:
out.push_back('[');
for (size_t i = 0; i < array_.size(); ++i) {
if (i) out.push_back(',');
array_[i].dump_into(out);
}
out.push_back(']');
break;
case Type::Object:
out.push_back('{');
for (auto it = object_.begin(); it != object_.end(); ++it) {
if (it != object_.begin()) out.push_back(',');
append_escaped(out, it->first);
out.push_back(':');
it->second.dump_into(out);
}
out.push_back('}');
break;
}
}
Type type_ = Type::Null;
bool bool_ = false;
double number_ = 0.0;
std::string string_;
Array array_;
Object object_;
};
inline const Json* json_member(const Json& value, std::string_view key) noexcept {
return value.find(key);
}
inline bool json_bool(const Json& value, std::string_view key, bool fallback = false) noexcept {
const Json* member = value.find(key);
return member ? member->bool_or(fallback) : fallback;
}
inline int json_int(const Json& value, std::string_view key, int fallback = 0) noexcept {
const Json* member = value.find(key);
return member ? member->int_or(fallback) : fallback;
}
inline std::string json_string(const Json& value, std::string_view key, std::string fallback = {}) {
const Json* member = value.find(key);
return member ? member->string_or(std::move(fallback)) : fallback;
}
} // namespace duo