hymmalm 0.2.0

Licensing client for license-management.com: JWS-signed license verification, trial bootstrap, activation and offline cache. Statically vendors the C core (Tauri-ready).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
/* Windows ports: WinHTTP transport, machine identity, sleep, trusted time.
 *
 * Machine identity reproduces the .NET SDK's DeviceId pipeline without WMI:
 *   Win32_BaseBoard.SerialNumber   -> SMBIOS type 2 serial (GetSystemFirmwareTable)
 *   Win32_Processor.ProcessorId    -> CPUID leaf 1, "%08X%08X" of EDX,EAX
 * so the same physical machine registers as the SAME computer whether the
 * vendor ships the .NET SDK or this core.
 *
 * Identity v2 (hlm_machine_id_win_v2) fingerprints the Windows MachineGuid
 * instead: the v1 sources collide across machines (ProcessorId is per CPU
 * model; OEM boards ship placeholder serials). See hlm.h for the
 * LegacyMacAddress re-key protocol.
 *
 * Trusted time reproduces the SDK's TimeSyncDiagnostic cascade:
 *   local clock IF w32time is running, configured for NTP, and within 1h of
 *   time.windows.com; otherwise SNTP to pool.ntp.org; otherwise fail (the
 *   client then falls back to GET DateTime, then the local clock).
 */
#if defined(_WIN32)

#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <winhttp.h>
#include <intrin.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "hymma/hlm.h"
#include "hlm_sntp.h"

#pragma comment(lib, "winhttp.lib")
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "advapi32.lib")

#define HLM_HTTP_TIMEOUT_MS 15000 /* per request, matches the .NET SDK */

/* ------------------------------------------------------------------ */
/* WinHTTP transport                                                   */
/* ------------------------------------------------------------------ */

static int utf8_to_wide(const char *s, wchar_t *out, int cap)
{
    int n = MultiByteToWideChar(CP_UTF8, 0, s, -1, out, cap);
    return n > 0 ? 0 : -1;
}

/* Append one formatted header line at *pos. Legacy _snwprintf returns a
 * negative value and may leave the buffer unterminated on truncation, so
 * check and re-terminate instead of blindly accumulating the return. */
static int append_header(wchar_t *buf, int cap, int *pos, const wchar_t *fmt,
                         const wchar_t *val)
{
    int n = _snwprintf(buf + *pos, (size_t)(cap - *pos), fmt, val);
    if (n < 0 || n >= cap - *pos) {
        buf[*pos] = L'\0';
        return -1;
    }
    *pos += n;
    return 0;
}

/* WinHttpOpen with the proxy behavior of a browser.
 * WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY (Windows 8.1+) resolves the proxy per
 * request the way Edge does: WPAD auto-detection, a PAC script, the user's
 * "Internet Options" proxy, falling back to direct. Earlier Windows rejects
 * that access type with ERROR_INVALID_PARAMETER; there the best available is
 * WINHTTP_ACCESS_TYPE_DEFAULT_PROXY (the `netsh winhttp` proxy). */
static HINTERNET open_session(void)
{
    HINTERNET s = WinHttpOpen(L"license-management-core/1.0",
                              WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
                              WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
    if (s == NULL && GetLastError() == ERROR_INVALID_PARAMETER)
        s = WinHttpOpen(L"license-management-core/1.0",
                        WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
                        WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
    if (s != NULL)
        WinHttpSetTimeouts(s, HLM_HTTP_TIMEOUT_MS, HLM_HTTP_TIMEOUT_MS,
                           HLM_HTTP_TIMEOUT_MS, HLM_HTTP_TIMEOUT_MS);
    return s;
}

/* A proxy answered 407. If it offers an integrated scheme (Negotiate or
 * NTLM), arm the request with the signed-in user's Windows credentials —
 * what a browser offers a company proxy. NULL user/password means "default
 * credentials", which WinHTTP only releases under the LOW autologon policy
 * (MEDIUM, the default, limits them to intranet hosts). The policy is
 * lowered on THIS request only, and only after a proxy challenged it, so
 * credentials are never volunteered to anyone else. Basic/Digest would need
 * a typed password: not ours to ask for, so the 407 stands. */
static int arm_proxy_default_credentials(HINTERNET request)
{
    DWORD supported = 0, first = 0, target = 0, scheme = 0;
    DWORD policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW;

    if (!WinHttpQueryAuthSchemes(request, &supported, &first, &target) ||
        target != WINHTTP_AUTH_TARGET_PROXY)
        return 0;
    if (!WinHttpSetOption(request, WINHTTP_OPTION_AUTOLOGON_POLICY, &policy,
                          sizeof(policy)))
        return 0;
    if (supported & WINHTTP_AUTH_SCHEME_NEGOTIATE)
        scheme = WINHTTP_AUTH_SCHEME_NEGOTIATE;
    else if (supported & WINHTTP_AUTH_SCHEME_NTLM)
        scheme = WINHTTP_AUTH_SCHEME_NTLM;
    else
        return 0;
    return WinHttpSetCredentials(request, WINHTTP_AUTH_TARGET_PROXY, scheme,
                                 NULL, NULL, NULL) != FALSE;
}

static int winhttp_send(void *user, const hlm_http_request *req,
                        hlm_http_response *resp)
{
    hlm_http_cache *cache = (hlm_http_cache *)user;
    HINTERNET session = NULL, connect = NULL, request = NULL;
    wchar_t wurl[1024], whost[256], wpath[768], wmethod[16];
    wchar_t headers[1024];
    URL_COMPONENTS uc;
    int result = HLM_E_HTTP;
    DWORD status = 0, status_len = sizeof(status);
    size_t total = 0;
    int proxy_auth_tried = 0;

    resp->retry_after_seconds = -1;

    if (utf8_to_wide(req->url, wurl,
                     (int)(sizeof(wurl) / sizeof(wurl[0]))) < 0 ||
        utf8_to_wide(req->method, wmethod,
                     (int)(sizeof(wmethod) / sizeof(wmethod[0]))) < 0)
        return HLM_E_ARG;

    memset(&uc, 0, sizeof(uc));
    uc.dwStructSize = sizeof(uc);
    uc.lpszHostName = whost;
    uc.dwHostNameLength = (DWORD)(sizeof(whost) / sizeof(whost[0]));
    uc.lpszUrlPath = wpath;
    uc.dwUrlPathLength = (DWORD)(sizeof(wpath) / sizeof(wpath[0]));
    if (!WinHttpCrackUrl(wurl, 0, 0, &uc)) return HLM_E_ARG;

    /* With a cache, one session per client: the session owns WinHTTP's
     * connection pool, so the repeated same-host requests of a refresh
     * reuse a TCP/TLS connection instead of re-handshaking. */
    if (cache != NULL && cache->h != NULL) {
        session = (HINTERNET)cache->h;
    } else {
        session = open_session();
        if (session == NULL) goto done;
        if (cache != NULL) cache->h = session;
    }

    connect = WinHttpConnect(session, whost, uc.nPort, 0);
    if (connect == NULL) goto done;

    request = WinHttpOpenRequest(
        connect, wmethod, wpath, NULL, WINHTTP_NO_REFERER,
        WINHTTP_DEFAULT_ACCEPT_TYPES,
        uc.nScheme == INTERNET_SCHEME_HTTPS ? WINHTTP_FLAG_SECURE : 0);
    if (request == NULL) goto done;

    {
        wchar_t wkey[256], wcorr[64], widem[300];
        const int hcap = (int)(sizeof(headers) / sizeof(headers[0]));
        int hl = 0;
        headers[0] = L'\0';
        /* fail closed on conversion/truncation: sending a request with a
         * silently dropped or half-written header would only misauth */
        if (req->api_key != NULL &&
            (utf8_to_wide(req->api_key, wkey,
                          (int)(sizeof(wkey) / sizeof(wkey[0]))) < 0 ||
             append_header(headers, hcap, &hl, L"X-API-KEY: %s\r\n", wkey) < 0)) {
            result = HLM_E_ARG;
            goto done;
        }
        if (req->correlation_id != NULL &&
            (utf8_to_wide(req->correlation_id, wcorr,
                          (int)(sizeof(wcorr) / sizeof(wcorr[0]))) < 0 ||
             append_header(headers, hcap, &hl,
                           L"X-Correlation-Id: %s\r\n", wcorr) < 0)) {
            result = HLM_E_ARG;
            goto done;
        }
        if (req->idempotency_key != NULL &&
            (utf8_to_wide(req->idempotency_key, widem,
                          (int)(sizeof(widem) / sizeof(widem[0]))) < 0 ||
             append_header(headers, hcap, &hl,
                           L"Idempotency-Key: %s\r\n", widem) < 0)) {
            result = HLM_E_ARG;
            goto done;
        }
        if (req->body != NULL &&
            append_header(headers, hcap, &hl,
                          L"Content-Type: application/json\r\n", NULL) < 0) {
            result = HLM_E_ARG;
            goto done;
        }
    }

    for (;;) {
        if (!WinHttpSendRequest(request,
                                headers[0] != L'\0' ? headers : WINHTTP_NO_ADDITIONAL_HEADERS,
                                (DWORD)-1,
                                req->body != NULL ? (LPVOID)req->body : WINHTTP_NO_REQUEST_DATA,
                                req->body != NULL ? (DWORD)strlen(req->body) : 0,
                                req->body != NULL ? (DWORD)strlen(req->body) : 0,
                                0))
            goto done;

        if (!WinHttpReceiveResponse(request, NULL)) goto done;

        status_len = sizeof(status);
        if (!WinHttpQueryHeaders(request,
                                 WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
                                 WINHTTP_HEADER_NAME_BY_INDEX, &status, &status_len,
                                 WINHTTP_NO_HEADER_INDEX))
            goto done;

        /* one answer to a proxy challenge with the user's Windows logon;
         * a second 407 is returned as-is (the client reports HLM_NET_PROXY) */
        if (status == 407 /* HTTP_STATUS_PROXY_AUTH_REQ */ && !proxy_auth_tried) {
            proxy_auth_tried = 1;
            if (arm_proxy_default_credentials(request)) continue;
        }
        break;
    }

    /* Retry-After (delta-seconds form; date form is ignored) */
    {
        wchar_t ra[64];
        DWORD ra_len = sizeof(ra);
        if (WinHttpQueryHeaders(request, WINHTTP_QUERY_RETRY_AFTER,
                                WINHTTP_HEADER_NAME_BY_INDEX, ra, &ra_len,
                                WINHTTP_NO_HEADER_INDEX)) {
            long v = wcstol(ra, NULL, 10);
            if (v >= 0 && v < 24 * 3600) resp->retry_after_seconds = (int)v;
        }
    }

    for (;;) {
        DWORD avail = 0, got = 0;
        if (!WinHttpQueryDataAvailable(request, &avail)) goto done;
        if (avail == 0) break;
        if (total + avail > resp->body_cap) {
            result = HLM_E_BUFFER;
            goto done;
        }
        if (!WinHttpReadData(request, resp->body + total, avail, &got)) goto done;
        total += got;
    }

    resp->status = (int)status;
    resp->body_len = total;
    result = HLM_OK;

done:
    /* every transport `goto done` above comes straight from the failing
     * WinHTTP call, so its last-error is still intact here */
    if (result == HLM_E_HTTP)
        resp->failure = hlm_net_failure_from_winhttp(GetLastError());
    if (request) WinHttpCloseHandle(request);
    if (connect) WinHttpCloseHandle(connect);
    if (session && cache == NULL) WinHttpCloseHandle(session);
    return result;
}

hlm_http hlm_http_winhttp(void)
{
    hlm_http h;
    h.send = winhttp_send;
    h.user = 0;
    return h;
}

hlm_http hlm_http_winhttp_cached(hlm_http_cache *cache)
{
    hlm_http h;
    h.send = winhttp_send;
    h.user = cache;
    return h;
}

void hlm_http_cache_close(hlm_http_cache *cache)
{
    if (cache == NULL || cache->h == NULL) return;
    WinHttpCloseHandle((HINTERNET)cache->h);
    cache->h = NULL;
}

/* ------------------------------------------------------------------ */
/* Sleep                                                               */
/* ------------------------------------------------------------------ */

static void sleep_win(void *user, unsigned ms)
{
    (void)user;
    Sleep(ms);
}

hlm_sleep hlm_sleep_win(void)
{
    hlm_sleep s;
    s.sleep_ms = sleep_win;
    s.user = 0;
    return s;
}

/* ------------------------------------------------------------------ */
/* Trusted time (clock-tamper resistance)                              */
/* ------------------------------------------------------------------ */

/* One process-wide WSAStartup at first use: per-query startup/cleanup
 * churns the global Winsock refcount and is fragile next to a host app
 * managing Winsock itself. The matching WSACleanup is intentionally
 * omitted — the OS reclaims it at process exit. */
static INIT_ONCE g_wsa_once = INIT_ONCE_STATIC_INIT;
static int g_wsa_ok = 0;

static BOOL CALLBACK wsa_init_once(PINIT_ONCE once, PVOID param, PVOID *ctx)
{
    WSADATA wsa;
    (void)once; (void)param; (void)ctx;
    g_wsa_ok = WSAStartup(MAKEWORD(2, 2), &wsa) == 0;
    return TRUE;
}

/* Minimal SNTP client (RFC 4330): 48-byte packet, LI=0 VN=3 Mode=3,
 * transmit timestamp at bytes 40-47, epoch 1900-01-01. */
static int sntp_query(const char *host, int timeout_ms, int64_t *epoch_out)
{
    struct addrinfo hints, *ai = NULL;
    SOCKET sock = INVALID_SOCKET;
    uint8_t pkt[HLM_SNTP_PACKET_SIZE];
    int result = -1;

    InitOnceExecuteOnce(&g_wsa_once, wsa_init_once, NULL, NULL);
    if (!g_wsa_ok) return -1;

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_DGRAM;
    hints.ai_protocol = IPPROTO_UDP;
    if (getaddrinfo(host, "123", &hints, &ai) != 0 || ai == NULL) goto done;

    sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
    if (sock == INVALID_SOCKET) goto done;

    {
        DWORD tmo = (DWORD)timeout_ms;
        setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char *)&tmo, sizeof(tmo));
        setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (const char *)&tmo, sizeof(tmo));
    }

    hlm_sntp_build_request(pkt);

    if (sendto(sock, (const char *)pkt, sizeof(pkt), 0, ai->ai_addr,
               (int)ai->ai_addrlen) != sizeof(pkt))
        goto done;
    if (recv(sock, (char *)pkt, sizeof(pkt), 0) != sizeof(pkt)) goto done;

    if (hlm_sntp_parse_reply(pkt, epoch_out) != 0) goto done;
    result = 0;

done:
    if (sock != INVALID_SOCKET) closesocket(sock);
    if (ai != NULL) freeaddrinfo(ai);
    return result;
}

static int w32time_running(void)
{
    SC_HANDLE scm, svc;
    SERVICE_STATUS ss;
    int running = 0;

    scm = OpenSCManagerA(NULL, NULL, SC_MANAGER_CONNECT);
    if (scm == NULL) return 0;
    svc = OpenServiceA(scm, "w32time", SERVICE_QUERY_STATUS);
    if (svc != NULL) {
        if (QueryServiceStatus(svc, &ss))
            running = ss.dwCurrentState == SERVICE_RUNNING;
        CloseServiceHandle(svc);
    }
    CloseServiceHandle(scm);
    return running;
}

static int w32time_uses_ntp(void)
{
    char type[32];
    DWORD len = sizeof(type);
    if (RegGetValueA(HKEY_LOCAL_MACHINE,
                     "SYSTEM\\CurrentControlSet\\Services\\W32Time\\Parameters",
                     "Type", RRF_RT_REG_SZ, NULL, type, &len) != ERROR_SUCCESS)
        return 0;
    return _stricmp(type, "NTP") == 0;
}

static int64_t local_utc_now(void)
{
    FILETIME ft;
    ULARGE_INTEGER u;
    GetSystemTimeAsFileTime(&ft);
    u.LowPart = ft.dwLowDateTime;
    u.HighPart = ft.dwHighDateTime;
    /* FILETIME epoch 1601-01-01, 100ns ticks */
    return (int64_t)(u.QuadPart / 10000000ULL) - 11644473600LL;
}

static int timesync_win_now(void *user, int64_t *now_utc)
{
    int64_t ntp_time;

    (void)user;

    /* Trust the local clock only when Windows itself keeps it honest AND it
     * actually agrees with an authoritative source — same three checks as
     * the SDK's TimeSyncDiagnostic. */
    if (w32time_running() && w32time_uses_ntp() &&
        sntp_query("time.windows.com", HLM_NTP_TIMEOUT_MS, &ntp_time) == 0) {
        int64_t local = local_utc_now();
        int64_t drift = local - ntp_time;
        if (drift < 0) drift = -drift;
        if (drift < HLM_MAX_DRIFT_SECONDS) {
            *now_utc = local;
            return HLM_OK;
        }
        /* drifted: the NTP answer itself is trustworthy */
        *now_utc = ntp_time;
        return HLM_OK;
    }

    if (sntp_query("pool.ntp.org", HLM_NTP_TIMEOUT_MS, &ntp_time) == 0) {
        *now_utc = ntp_time;
        return HLM_OK;
    }

    return HLM_E_HTTP; /* caller falls back to GET DateTime, then local */
}

hlm_timesync hlm_timesync_win(void)
{
    hlm_timesync t;
    t.now = timesync_win_now;
    t.user = 0;
    return t;
}

/* ------------------------------------------------------------------ */
/* Machine identity                                                    */
/* ------------------------------------------------------------------ */

/* GetSystemFirmwareTable provider signature 'RSMB' spelled out — the
 * multi-char constant draws -Wmultichar under the mingw cgo build. */
#define HLM_FIRMWARE_RSMB 0x52534D42u

/* SMBIOS raw table layout per the RSMB firmware table. */
typedef struct {
    BYTE Used20CallingMethod;
    BYTE SMBIOSMajorVersion;
    BYTE SMBIOSMinorVersion;
    BYTE DmiRevision;
    DWORD Length;
    BYTE SMBIOSTableData[1];
} raw_smbios;

/* Fetch string `index` (1-based) trailing an SMBIOS structure. */
static const char *smbios_string(const BYTE *strings, const BYTE *end, int index)
{
    int i;
    const BYTE *p = strings;

    if (index <= 0) return NULL;
    for (i = 1; p < end; i++) {
        size_t len = strnlen((const char *)p, (size_t)(end - p));
        if (len == (size_t)(end - p)) return NULL; /* no NUL before end */
        if (len == 0) return NULL; /* end of string-set */
        if (i == index) return (const char *)p;
        p += len + 1;
    }
    return NULL;
}

/* Baseboard (SMBIOS type 2) serial number -> out. */
static int smbios_baseboard_serial(char *out, size_t out_len)
{
    UINT size;
    BYTE *buf;
    raw_smbios *smb;
    const BYTE *p, *end;
    int found = 0;

    size = GetSystemFirmwareTable(HLM_FIRMWARE_RSMB, 0, NULL, 0);
    if (size <= offsetof(raw_smbios, SMBIOSTableData) || size > 1024 * 1024)
        return -1;
    buf = (BYTE *)HeapAlloc(GetProcessHeap(), 0, size);
    if (buf == NULL) return -1;
    if (GetSystemFirmwareTable(HLM_FIRMWARE_RSMB, 0, buf, size) != size)
        goto done;

    smb = (raw_smbios *)buf;
    p = smb->SMBIOSTableData;
    {
        /* never trust the firmware-reported Length past the allocation */
        size_t cap = size - offsetof(raw_smbios, SMBIOSTableData);
        end = p + (smb->Length <= cap ? smb->Length : cap);
    }

    while (p + 4 <= end) {
        BYTE type = p[0];
        BYTE len = p[1];
        const BYTE *strings;
        const BYTE *q;

        if (len < 4 || len > (size_t)(end - p)) break;
        strings = p + len;
        q = strings;

        /* find the end of this structure's string-set (double NUL) */
        while (q + 1 < end && !(q[0] == 0 && q[1] == 0)) q++;
        if (q + 1 >= end) break; /* truncated table: no terminator */
        q += 2;

        if (type == 2 && len > 0x07) {
            const char *serial = smbios_string(strings, end, p[0x07]);
            if (serial != NULL && serial[0] != '\0') {
                size_t sl = strlen(serial);
                if (sl < out_len) {
                    memcpy(out, serial, sl + 1);
                    found = 1;
                }
            }
            break;
        }
        p = q;
    }

done:
    HeapFree(GetProcessHeap(), 0, buf);
    return found ? 0 : -1;
}

/* CPUID leaf 1 -> the 16-hex-char string WMI reports as ProcessorId. */
static void processor_id(char out[17])
{
    int regs[4] = { 0, 0, 0, 0 };
    __cpuid(regs, 1);
    /* EDX (feature flags) then EAX (signature), uppercase hex. */
    snprintf(out, 17, "%08X%08X", (unsigned)regs[3], (unsigned)regs[0]);
}

int hlm_machine_id_win(char *out, size_t out_len)
{
    char serial[128];
    char cpu[17];
    const char *components[2];

    if (smbios_baseboard_serial(serial, sizeof(serial)) != 0)
        return HLM_E_ARG; /* no baseboard serial exposed — caller must supply one */
    processor_id(cpu);

    /* DeviceId orders components by name: MotherboardSerialNumber < ProcessorId */
    components[0] = serial;
    components[1] = cpu;
    return hlm_fingerprint(components, 2, out, out_len);
}

/* HKLM\SOFTWARE\Microsoft\Cryptography\MachineGuid: generated once at
 * Windows installation, unique per install, immune to the placeholder
 * hardware strings that make v1 collide. Read from the 64-bit hive
 * regardless of process bitness (DeviceId's AddMachineGuid does the same). */
static int registry_machine_guid(char *out, size_t out_len)
{
    HKEY key;
    DWORD type = 0, sz;

    if (out_len < 2) return -1;
    if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Cryptography",
                      0, KEY_QUERY_VALUE | KEY_WOW64_64KEY, &key) !=
        ERROR_SUCCESS)
        return -1;
    sz = (DWORD)(out_len - 1);
    if (RegQueryValueExA(key, "MachineGuid", NULL, &type, (LPBYTE)out, &sz) !=
            ERROR_SUCCESS ||
        type != REG_SZ) {
        RegCloseKey(key);
        return -1;
    }
    RegCloseKey(key);
    out[sz] = '\0'; /* REG_SZ is not guaranteed to include the NUL */
    return strlen(out) >= 8 ? 0 : -1;
}

int hlm_machine_id_win_v2(char *out, size_t out_len)
{
    char guid[128];
    const char *components[1];

    if (registry_machine_guid(guid, sizeof(guid)) != 0)
        return HLM_E_ARG; /* no MachineGuid -- fall back to hlm_machine_id_win */
    components[0] = guid;
    return hlm_fingerprint(components, 1, out, out_len);
}

int hlm_machine_name_win(char *out, size_t out_len)
{
    DWORD n = (DWORD)out_len;
    if (!GetComputerNameA(out, &n)) return HLM_E_ARG;
    return HLM_OK;
}

#endif /* _WIN32 */