Files
Martin Vogel 0baddf7887 daemon: permanent lifecycle, daemon-backed CLI/hooks, real-Windows hardening, long-path launcher transactions
Daemon lifecycle and Windows correctness, verified on a real Windows 11
ARM64 VM through the maintained test-infrastructure/vm drivers, plus the
macOS and Linux arm64 suites and the container lint gate.

Daemon lifecycle:

- daemon start/stop/status subcommands. `daemon start` launches a
  PERMANENT daemon (spawn shape is byte-exact argv; survives idle
  periods and session ends) and reports an already-active daemon
  instead of failing. Permanence is honored at every stop latch:
  last-committed-client disconnect, host initial-client window,
  coordinator release, and application final-session close — a
  permanent daemon also keeps admitting new sessions after its last
  one closes.
- daemon stop refuses while sessions are active and lists the blocking
  peers (pid/role) that must finish first; an idle daemon drains
  through the activation-shutdown machinery with the ACK ordered after
  connection interrupts. A second stop is idempotent. The wire ops are
  no-cohort first-frame requests with peer fingerprint authentication,
  so stop/status never conflict with an exact-build admission gate.
- One-shot CLI commands now execute through the daemon (index workers
  keep their local supervised path). A cold CLI run that had to spawn a
  temporary daemon prints a hint that `daemon start` removes the
  per-command startup tax; a warm daemon is recycled silently.
- Hooks are connect-only fail-open: with no daemon present the hook
  emits a visible, rate-limited notice (Claude-dialect systemMessage
  plus stderr for other dialects) and always exits 0 — augmentation is
  never allowed to block the caller's tool use.
- Version skew: a newer-build client automatically drains an
  older-build permanent daemon (strict semantic-version triples only;
  dev builds never auto-drain) and the build-conflict message names
  `cbm daemon stop` as the manual escape hatch.

Windows IPC/runtime (real-VM verified):

- ipc(win): persistent pending overlapped ConnectNamedPipe. The accept
  path used to destroy its listening pipe instance on every 20 ms poll
  timeout; a client attaching in the teardown window was severed or left
  on an orphaned pipe object whose HELLO no server handle could ever
  read, absorbing the connect until the client's own timeout expired.
  The pending connect now survives poll timeouts and nothing is
  destroyed while a client could be attaching.
- ipc(win): drain-before-close for final responses. Closing a named-pipe
  server handle can discard a just-sent response before the peer reads
  it (POSIX stream sockets never lose buffered data on close). A bounded
  cbm_daemon_ipc_connection_drain (read-until-peer-EOF; no-op on POSIX,
  immediate on interrupted connections) now precedes close in
  runtime_worker_finish and runtime_reject_inline, so hello-conflict,
  capacity and disconnect acknowledgements reliably reach the peer.
- runtime: CLOSE_INTENT wire frame. A Windows named-pipe client has no
  transport half-close, so close_begin now announces departure with an
  explicit frame (ordered after APPLICATION_CANCEL, before the local
  interrupt); the server releases the client's admission on receipt
  instead of waiting for the handle to close. Admission-drop timing is
  now identical to POSIX shutdown() semantics on every platform.
- runtime(win): client close cancellation. close_begin serializes with
  request publication under the send lock, best-effort sends the active
  token's APPLICATION_CANCEL frame, then interrupts local I/O; the
  server cancels MCP/subprocess work promptly. Contract tests accept
  both correct outcomes (interrupted transport or decoded CANCELLED).
- runtime: activation acknowledgement ordering. The activation ACK is
  the requester's license to act on "snapshotted and draining", so every
  connection interrupt is now initiated before the ACK is sent; a
  session could previously get one more request serviced after the
  requester observed the ACK.
- service(win): deadline-bounded private-file prepare. The conflict-log
  prepare retry loop (100 x Sleep(2), which rounds up to the ~16 ms
  timer granularity) burned ~1.6 s against permanently obstructed paths,
  stalling hello rejections past the client's timeout. The retry budget
  is now a 250 ms deadline; transient share collisions still retry.
- subprocess(win): cmd.exe /C payload encoder quotes metacharacters
  correctly (root cause of the git-on-Windows failure cluster).
- watcher: SHA-256 buffer sizing (CBM_SZ_64 -> CBM_SZ_128) and a native
  Windows stop/unwatch cancellation test with exact-image verification.
- httpd: send_all writes in bounded 64 KiB slices. A single giant
  nonblocking send() on Windows is absorbed wholesale into AFD kernel
  buffering regardless of SO_SNDBUF, so send deadlines and interrupts
  could never engage against a slow peer (and the full payload was
  pinned in nonpaged pool). Slicing restores a deterministic
  backpressure point; a test hook pins SO_SNDBUF for the deadline and
  interrupt tests.
- ui/http: shutdown lifecycle — interrupt checks, response-wide send
  deadline, explicit connection states, refusal to free a server while
  a listener-owned connection is active.

Windows long-path support:

- Central path-aware wide conversion (canonicalize via GetFullPathNameW
  and prepend the extended-length prefix for absolute paths >=240) at
  the compat chokepoints (cbm_fopen/compat_fs/mkstemp/mkdtemp), sqlite
  store opens, and the daemon build-fingerprint/log paths. Deep managed
  installs (a 64-hex generation directory routinely exceeds MAX_PATH)
  now index, stage and activate correctly.
- activation transaction: its own file APIs and the component-walking
  ancestry validators now operate in the extended-length namespace;
  the launcher path is canonicalized (and prefixed when deep) once at
  entry so every downstream exact-string comparison stays
  form-consistent.
- Executable self-resolution uses the wide APIs (GetModuleFileNameW,
  GetFileAttributesW) so non-ASCII install paths survive argv[0]
  resolution.

Windows launcher install/uninstall transaction:

- FileRenameInfoEx names are NUL-terminated in an over-allocated
  buffer. FileNameLength governs per the contract, but filter drivers
  read FileName as NUL-terminated and appended adjacent heap bytes to
  created names — a flaky, garbage-suffixed rename target. Both the CLI
  and the launcher rename helpers are fixed.
- Uninstall retires state via rename-aside (.cbm ->
  .cbm-retired-v1-<tag>-<pid>) with the retired tag shortened to 16 hex
  chars so the bare rename target stays under the FileRenameInfoEx
  NT-conversion ceiling at guard depths; 64 bits still uniquely
  identify the generation.
- When the running launcher's mapped generation backings pin .cbm
  against rename, the backings are relocated to activation-<pid>-N
  .retired tombstones beside the install (a mapped image may be renamed,
  never deleted; the launcher's liveness-guarded sweep reclaims stale
  tombstones). Every relocation is recorded, and a FAILED uninstall
  reverses the moves after restoring .cbm — via MoveFileExW with
  extended-length paths on both arguments, since the deep generation
  target is beyond the handle-based rename's bare-path reach — so a
  restored install keeps its generation backings and stays runnable.
- After a committed uninstall the retired tree's backings are relocated
  out so the tree is shallow enough for the detached cleanup's rd, and
  the cleanup's working directory strips the extended-length prefix
  (CreateProcessW lpCurrentDirectory silently ignores prefixed paths).
- Files created under Administrators-default-owner directories
  (CopyFileW destinations, CREATE_NEW tombstones, probe directories)
  are explicitly owner-stamped so the exact-owner validators hold on
  runner images; guard fixtures stamp hand-built trees the same way.

Diagnostics, tests and infra:

- diagnostics: discovery is now an always-delivered JSON control record
  (new cbm_log_control) that survives CBM_LOG_LEVEL suppression and
  paths containing spaces; placement honors $TMPDIR with /tmp fallback
  via a diagnostics-local helper; the soak parser reads the JSON record;
  documented in docs/CONFIGURATION.md. Red-first coverage for suppressed
  log levels, TMPDIR-with-spaces, and native Windows output-contract
  assertions.
- tests(win): daemon_ipc/daemon_frontend fixtures now build endpoint
  parents with production-shaped ancestry (LocalAppData on Windows, via
  th_secure_runtime_parent_new) — the runtime ancestry validation
  correctly refuses temp roots whose ancestors grant mutation rights to
  Authenticated Users (C:/msys64/tmp, GitHub-runner work dirs) — and
  drive the documented startup-owner publication flow before reading
  generation-bound endpoint addresses. This turns the 26 Windows
  failures previously visible in CI's full-test job green without
  weakening any validation.
- tests(win): the launcher guard covers the full permanent-launcher
  contract including failed-uninstall restore and immediate reinstall
  after uninstall; new daemon lifecycle and reworked hook-augment
  guards run the start/recycle/stop flow end to end.
- tests: CBM_SKIP_PERF is now actually consumed by the test runner
  (it was set by CI but never read, so perf suites ran everywhere);
  four throughput/bench suites are classified as perf, the heavy
  store_arch suite moved to the slow-timeout tier, and two
  wall-clock-sensitive assertions were rewritten as invariant checks
  with coarse hang-detector backstops.
- build/test infra: build-dir safety contract, UI dev-proxy security
  contract, soak daemon-recovery contract, path-safety helper, the
  Windows VM worktree-sync contract wired into scripts/test.sh, and
  vm/win.sh guards building its clean embedded-UI product in an
  isolated BUILD_DIR so it cannot clobber the incremental test build.
  provision-windows.sh now installs Node.js for the guards UI build.

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-07-21 15:32:15 +02:00

1007 lines
31 KiB
C

/*
* compat_fs.c — Portable file system operations.
*
* POSIX: direct wrappers around opendir/readdir/closedir, popen/pclose, mkdir, unlink.
* Windows: FindFirstFile/FindNextFile, _popen/_pclose, _mkdir, _unlink.
*/
#include "foundation/constants.h"
#include "foundation/compat_fs.h"
#include "foundation/compat_fs_internal.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
/* ── Windows implementation ────────────────────────────────── */
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <aclapi.h>
#include <direct.h> /* _wmkdir */
#include <errno.h> /* errno for spawn-failure logging */
#include <fcntl.h> /* _O_RDONLY */
#include <io.h> /* _wunlink, _open_osfhandle, _close */
#include <stdint.h> /* intptr_t */
#include "foundation/log.h"
#include "foundation/win_utf8.h"
struct cbm_dir {
HANDLE find_handle;
WIN32_FIND_DATAW find_data;
wchar_t wide_pattern[CBM_PATH_MAX];
cbm_dirent_t entry;
bool first;
bool done;
};
cbm_dir_t *cbm_opendir(const char *path) {
if (!path) {
return NULL;
}
wchar_t *wpath = cbm_path_to_wide(path);
if (!wpath) {
return NULL;
}
size_t wlen = wcslen(wpath);
if (wlen == 0 || wlen + 2 >= CBM_PATH_MAX) {
free(wpath);
return NULL;
}
cbm_dir_t *d = (cbm_dir_t *)calloc(CBM_ALLOC_ONE, sizeof(cbm_dir_t));
if (!d) {
free(wpath);
return NULL;
}
wmemcpy(d->wide_pattern, wpath, wlen + 1);
wchar_t *p = d->wide_pattern + wlen - SKIP_ONE;
if (*p != L'\\' && *p != L'/') {
++p;
*p++ = L'\\';
} else {
++p;
}
*p++ = L'*';
*p = L'\0';
free(wpath);
d->find_handle = FindFirstFileW(d->wide_pattern, &d->find_data);
if (d->find_handle == INVALID_HANDLE_VALUE) {
free(d);
return NULL;
}
d->first = true;
d->done = false;
return d;
}
cbm_dirent_t *cbm_readdir(cbm_dir_t *d) {
if (!d || d->done) {
return NULL;
}
if (!d->first) {
if (!FindNextFileW(d->find_handle, &d->find_data)) {
d->done = true;
return NULL;
}
}
d->first = false;
while (d->find_data.cFileName[0] == L'.' &&
(d->find_data.cFileName[1] == L'\0' ||
(d->find_data.cFileName[1] == L'.' && d->find_data.cFileName[2] == L'\0'))) {
if (!FindNextFileW(d->find_handle, &d->find_data)) {
d->done = true;
return NULL;
}
}
char *u8 = cbm_wide_to_utf8(d->find_data.cFileName);
if (!u8) {
d->done = true;
return NULL;
}
size_t nlen = strlen(u8);
if (nlen >= CBM_DIRENT_NAME_MAX) {
nlen = CBM_DIRENT_NAME_MAX - SKIP_ONE;
}
memcpy(d->entry.name, u8, nlen);
d->entry.name[nlen] = '\0';
free(u8);
d->entry.is_dir = (d->find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
d->entry.d_type = 0;
return &d->entry;
}
void cbm_closedir(cbm_dir_t *d) {
if (d) {
if (d->find_handle != INVALID_HANDLE_VALUE) {
FindClose(d->find_handle);
}
free(d);
}
}
/* Windows _popen replacement that inherits ONLY the child's stdout pipe.
*
* The CRT's _popen uses CreateProcess(bInheritHandles=TRUE), which leaks EVERY
* inheritable handle we hold into the child — listening/client sockets, the
* Winsock/AFD helper handles created by WSAStartup, the MCP stdio pipe, etc.
* When the child is git-for-Windows (MSYS2/Cygwin runtime), its startup walks
* every inherited handle and calls NtQueryObject on each to classify it; on an
* inherited socket/AFD handle NtQueryObject deadlocks. Since our UI server runs
* requests on a single thread, that wedges the whole server (list_projects,
* which shells out to git per project, never returns → the web UI hangs).
*
* The fix: spawn via CreateProcessW with STARTUPINFOEXW + an explicit
* PROC_THREAD_ATTRIBUTE_HANDLE_LIST containing only the stdout write-end and a
* NUL handle for stdin/stderr. Nothing else crosses into git, so there is no
* foreign handle to deadlock on. POSIX popen() already sets O_CLOEXEC on its
* pipe, so the POSIX path is unchanged.
*
* There is deliberately NO fallback to _popen when the isolated spawn fails:
* falling back would silently re-arm the deadlock. cbm_popen logs a structured
* warning and returns NULL instead (every call site handles NULL). */
enum { CBM_POPEN_MAX = 16 };
static struct {
FILE *fp;
HANDLE proc;
} g_popen_tab[CBM_POPEN_MAX];
static CRITICAL_SECTION g_popen_lock;
static INIT_ONCE g_popen_once = INIT_ONCE_STATIC_INIT;
/* Test hook (declared in compat_fs_internal.h): 1 when the most recent
* cbm_popen(..., "r") stream came from the isolated spawn. Test-only
* observable; not synchronized across threads. */
static volatile LONG g_popen_last_isolated = 0;
int cbm_popen_last_was_isolated(void) {
return (int)g_popen_last_isolated;
}
static BOOL CALLBACK cbm_popen_init(PINIT_ONCE once, PVOID param, PVOID *ctx) {
(void)once;
(void)param;
(void)ctx;
InitializeCriticalSection(&g_popen_lock);
return TRUE;
}
/* Resolve the shell explicitly — %COMSPEC%, else <system dir>\cmd.exe — so it
* can be passed as lpApplicationName and CreateProcess never walks the search
* path (no cmd.exe planting from a hostile CWD). Heap string; caller frees. */
static wchar_t *cbm_resolve_comspec(void) {
wchar_t buf[MAX_PATH];
const wchar_t suffix[] = L"\\cmd.exe";
DWORD n = GetEnvironmentVariableW(L"COMSPEC", buf, MAX_PATH);
if (n == 0 || n >= MAX_PATH) {
UINT sn = GetSystemDirectoryW(buf, MAX_PATH);
if (sn == 0 || (size_t)sn + wcslen(suffix) >= MAX_PATH) {
return NULL;
}
wmemcpy(buf + sn, suffix, wcslen(suffix) + 1);
}
return _wcsdup(buf);
}
/* On failure returns NULL with *stage naming the failing step and *gle the
* GetLastError value captured at that step (0 when errno is the signal). */
static FILE *cbm_popen_isolated(const char *cmd, const char **stage, DWORD *gle) {
*stage = "";
*gle = 0;
InitOnceExecuteOnce(&g_popen_once, cbm_popen_init, NULL, NULL);
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
HANDLE rd = NULL, wr = NULL;
if (!CreatePipe(&rd, &wr, &sa, 0)) {
*stage = "pipe";
*gle = GetLastError();
return NULL;
}
/* The parent read-end must never cross into the child. */
SetHandleInformation(rd, HANDLE_FLAG_INHERIT, 0);
/* NUL for the child's stdin/stderr so it never touches our real stdin
* pipe. If NUL cannot be opened, fail: STARTF_USESTDHANDLES slots must
* never carry INVALID_HANDLE_VALUE. */
HANDLE nul = CreateFileW(L"NUL", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL);
if (nul == INVALID_HANDLE_VALUE) {
*stage = "nul";
*gle = GetLastError();
CloseHandle(rd);
CloseHandle(wr);
return NULL;
}
HANDLE inherit[2];
inherit[0] = wr;
inherit[1] = nul;
SIZE_T attr_sz = 0;
InitializeProcThreadAttributeList(NULL, 1, 0, &attr_sz);
LPPROC_THREAD_ATTRIBUTE_LIST attr = (LPPROC_THREAD_ATTRIBUTE_LIST)malloc(attr_sz);
BOOL attr_init = attr && InitializeProcThreadAttributeList(attr, 1, 0, &attr_sz);
BOOL prepared =
attr_init && UpdateProcThreadAttribute(attr, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, inherit,
sizeof(inherit), NULL, NULL);
DWORD attr_gle = prepared ? 0 : GetLastError();
STARTUPINFOEXW si;
ZeroMemory(&si, sizeof(si));
si.StartupInfo.cb = sizeof(si);
si.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
si.StartupInfo.hStdInput = nul;
si.StartupInfo.hStdOutput = wr;
si.StartupInfo.hStdError = nul;
si.lpAttributeList = attr;
/* Run through cmd.exe /c so command quoting and `2>NUL` behave as under
* _popen. The command line is heap-composed (no fixed-size truncation)
* and widened via UTF-8 so non-ASCII repo paths survive intact. */
wchar_t *app = cbm_resolve_comspec();
wchar_t *wcmdline = NULL;
if (app) {
size_t u8len = strlen(cmd) + sizeof("cmd.exe /c ");
char *u8 = (char *)malloc(u8len);
if (u8) {
snprintf(u8, u8len, "cmd.exe /c %s", cmd);
wcmdline = cbm_utf8_to_wide(u8);
free(u8);
}
}
PROCESS_INFORMATION pi;
ZeroMemory(&pi, sizeof(pi));
BOOL created = FALSE;
if (!prepared) {
*stage = "attr";
*gle = attr_gle;
} else if (!app || !wcmdline) {
*stage = "cmdline";
*gle = ERROR_NOT_ENOUGH_MEMORY;
} else {
created = CreateProcessW(app, wcmdline, NULL, NULL, TRUE, EXTENDED_STARTUPINFO_PRESENT,
NULL, NULL, &si.StartupInfo, &pi);
if (!created) {
*stage = "spawn";
*gle = GetLastError();
}
}
free(app);
free(wcmdline);
if (attr) {
if (attr_init) {
DeleteProcThreadAttributeList(attr);
}
free(attr);
}
CloseHandle(wr); /* the child owns the write-end now */
CloseHandle(nul);
if (!created) {
CloseHandle(rd);
return NULL;
}
CloseHandle(pi.hThread);
int fd = _open_osfhandle((intptr_t)rd, _O_RDONLY);
if (fd == -1) {
*stage = "osfhandle";
CloseHandle(rd);
CloseHandle(pi.hProcess);
return NULL;
}
FILE *fp = _fdopen(fd, "r"); /* takes ownership of fd/rd */
if (!fp) {
*stage = "fdopen";
_close(fd);
CloseHandle(pi.hProcess);
return NULL;
}
EnterCriticalSection(&g_popen_lock);
for (int i = 0; i < CBM_POPEN_MAX; i++) {
if (!g_popen_tab[i].fp) {
g_popen_tab[i].fp = fp;
g_popen_tab[i].proc = pi.hProcess;
LeaveCriticalSection(&g_popen_lock);
return fp;
}
}
LeaveCriticalSection(&g_popen_lock);
/* Table full (shouldn't happen): don't leak the process handle. */
*stage = "table";
CloseHandle(pi.hProcess);
fclose(fp);
return NULL;
}
FILE *cbm_popen(const char *cmd, const char *mode) {
/* Our git shell-outs are all read-mode; they MUST use the isolated
* spawn. On failure, log and fail the call — never fall back to
* _popen, whose full handle inheritance re-arms the UI hang (#798). */
if (mode && mode[0] == 'r' && mode[1] == '\0') {
const char *stage = "";
DWORD gle = 0;
FILE *fp = cbm_popen_isolated(cmd, &stage, &gle);
g_popen_last_isolated = (fp != NULL);
if (!fp) {
char glebuf[CBM_SZ_16];
char errnobuf[CBM_SZ_16];
snprintf(glebuf, sizeof(glebuf), "%lu", (unsigned long)gle);
snprintf(errnobuf, sizeof(errnobuf), "%d", errno);
cbm_log_warn("compat.popen_isolated_failed", "stage", stage, "gle", glebuf, "errno",
errnobuf);
}
return fp;
}
g_popen_last_isolated = 0;
return _popen(cmd, mode);
}
int cbm_pclose(FILE *f) {
InitOnceExecuteOnce(&g_popen_once, cbm_popen_init, NULL, NULL);
HANDLE proc = NULL;
EnterCriticalSection(&g_popen_lock);
for (int i = 0; i < CBM_POPEN_MAX; i++) {
if (g_popen_tab[i].fp == f) {
proc = g_popen_tab[i].proc;
g_popen_tab[i].fp = NULL;
g_popen_tab[i].proc = NULL;
break;
}
}
LeaveCriticalSection(&g_popen_lock);
if (!proc) {
return _pclose(f); /* opened via _popen (non-read mode) */
}
fclose(f);
WaitForSingleObject(proc, INFINITE);
DWORD code = 0;
BOOL got = GetExitCodeProcess(proc, &code);
CloseHandle(proc);
return got ? (int)code : -1;
}
FILE *cbm_fopen(const char *path, const char *mode) {
wchar_t *wpath = cbm_path_to_wide(path);
if (!wpath) {
return NULL;
}
wchar_t *wmode = cbm_utf8_to_wide(mode);
if (!wmode) {
free(wpath);
return NULL;
}
FILE *f = _wfopen(wpath, wmode);
free(wpath);
free(wmode);
return f;
}
/* Stamp the exact current user as owner and apply an owner-only protected
* DACL on a directory cbm just created. Under the Administrators-default-owner
* policy (server/runner images), a plain _wmkdir yields an Administrators-owned
* directory that the launcher/activation exact-owner validators reject. Only
* freshly created directories are stamped; pre-existing ones keep their owner. */
static void cbm_windows_stamp_dir_owner(const wchar_t *path) {
HANDLE token = NULL;
TOKEN_USER *user = NULL;
PACL acl = NULL;
DWORD needed = 0U;
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token) &&
!GetTokenInformation(token, TokenUser, NULL, 0U, &needed) &&
GetLastError() == ERROR_INSUFFICIENT_BUFFER && (user = malloc(needed)) != NULL &&
GetTokenInformation(token, TokenUser, user, needed, &needed) && user->User.Sid &&
IsValidSid(user->User.Sid)) {
EXPLICIT_ACCESSW access;
memset(&access, 0, sizeof(access));
access.grfAccessPermissions = GENERIC_ALL;
access.grfAccessMode = SET_ACCESS;
access.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
access.Trustee.TrusteeType = TRUSTEE_IS_USER;
access.Trustee.ptstrName = (LPWSTR)user->User.Sid;
HANDLE directory =
CreateFileW(path, WRITE_OWNER | WRITE_DAC | READ_CONTROL,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
if (directory != INVALID_HANDLE_VALUE) {
if (SetEntriesInAclW(1U, &access, NULL, &acl) == ERROR_SUCCESS) {
(void)SetSecurityInfo(directory, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION |
PROTECTED_DACL_SECURITY_INFORMATION,
user->User.Sid, NULL, acl, NULL);
}
(void)CloseHandle(directory);
}
}
if (acl) {
(void)LocalFree(acl);
}
free(user);
if (token) {
(void)CloseHandle(token);
}
}
static bool cbm_windows_mkdir_component(wchar_t *path) {
bool created = _wmkdir(path) == 0;
if (!created && errno != EEXIST) {
return false;
}
DWORD attributes = GetFileAttributesW(path);
if (attributes == INVALID_FILE_ATTRIBUTES || (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0U ||
(attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0U) {
return false;
}
if (created) {
cbm_windows_stamp_dir_owner(path);
}
return true;
}
bool cbm_mkdir_p(const char *path, int mode) {
(void)mode;
if (!path || path[0] == '\0') {
return false;
}
wchar_t *wpath = cbm_path_to_wide(path);
if (!wpath) {
return false;
}
size_t wlen = wcslen(wpath);
wchar_t *tmp = (wchar_t *)malloc((wlen + 1) * sizeof(wchar_t));
if (!tmp) {
free(wpath);
return false;
}
wmemcpy(tmp, wpath, wlen + 1);
size_t start = wlen > 0U && (tmp[0] == L'/' || tmp[0] == L'\\') ? 1U : 0U;
if (wlen >= 3U && tmp[1] == L':' && (tmp[2] == L'/' || tmp[2] == L'\\')) {
start = 3U;
} else if (wlen >= 2U && (tmp[0] == L'/' || tmp[0] == L'\\') &&
(tmp[1] == L'/' || tmp[1] == L'\\')) {
size_t separators = 0U;
start = 2U;
while (start < wlen && separators < 2U) {
if (tmp[start] == L'/' || tmp[start] == L'\\') {
separators++;
}
start++;
}
}
bool ok = true;
for (wchar_t *p = tmp + start; ok && *p; p++) {
if (*p == L'/' || *p == L'\\') {
if (p == tmp || p[-1] == L'/' || p[-1] == L'\\') {
continue;
}
wchar_t separator = *p;
*p = L'\0';
ok = cbm_windows_mkdir_component(tmp);
*p = separator;
}
}
if (ok) {
ok = cbm_windows_mkdir_component(tmp);
}
free(tmp);
free(wpath);
return ok;
}
int cbm_unlink(const char *path) {
wchar_t *wpath = cbm_path_to_wide(path);
if (!wpath) {
return CBM_NOT_FOUND;
}
int ret = _wunlink(wpath);
free(wpath);
return ret;
}
int cbm_rmdir(const char *path) {
wchar_t *wpath = cbm_path_to_wide(path);
if (!wpath) {
return CBM_NOT_FOUND;
}
int ret = _wrmdir(wpath);
free(wpath);
return ret;
}
/* Build a properly-quoted Windows command line from an argv array.
* Returns a heap-allocated wide string, or NULL on allocation failure.
* Quoting follows the MSVC CRT convention: arguments containing spaces,
* tabs, or double-quotes are wrapped in double-quotes, with backslashes
* before a closing quote doubled and the quote itself escaped. Argument
* bytes are treated as UTF-8 and converted to wide via cbm_utf8_to_wide,
* so non-ASCII arguments (e.g. a non-ASCII %USERPROFILE%) survive intact.
* Declared in compat_fs_internal.h so the test suite can drive it. */
wchar_t *cbm_build_cmdline(const char *const *argv) {
/* First pass: compute required buffer size. */
size_t total = 1; /* NUL terminator */
for (int i = 0; argv[i]; i++) {
const char *arg = argv[i];
bool needs_quote = (arg[0] == '\0');
for (const char *p = arg; *p; p++) {
if (*p == ' ' || *p == '\t' || *p == '"') {
needs_quote = true;
}
}
if (i > 0) {
total++; /* space separator */
}
if (needs_quote) {
total += 2; /* opening and closing quote */
size_t backslashes = 0;
for (const char *p = arg; *p; p++) {
if (*p == '\\') {
backslashes++;
} else if (*p == '"') {
total += backslashes + 1; /* double backslashes + escape backslash */
backslashes = 0;
} else {
backslashes = 0;
}
total++;
}
/* Trailing backslashes before closing quote must be doubled. */
total += backslashes;
} else {
total += strlen(arg);
}
}
/* Build the quoted command line in UTF-8 first, then widen it as a
* whole via cbm_utf8_to_wide. Every character the quoting logic acts
* on (space, tab, '"', '\\') is ASCII and, by UTF-8's design, never
* appears inside a multibyte sequence, so operating on raw bytes here
* is safe and keeps multibyte argument bytes intact for conversion. */
char *buf = (char *)malloc(total);
if (!buf) {
return NULL;
}
/* Second pass: write the command line bytes. */
char *w = buf;
for (int i = 0; argv[i]; i++) {
const char *arg = argv[i];
bool needs_quote = (arg[0] == '\0');
for (const char *p = arg; *p; p++) {
if (*p == ' ' || *p == '\t' || *p == '"') {
needs_quote = true;
break;
}
}
if (i > 0) {
*w++ = ' ';
}
if (needs_quote) {
*w++ = '"';
size_t backslashes = 0;
for (const char *p = arg; *p; p++) {
if (*p == '\\') {
backslashes++;
*w++ = '\\';
} else if (*p == '"') {
/* Double the preceding backslashes, then escape the quote. */
for (size_t b = 0; b < backslashes; b++) {
*w++ = '\\';
}
*w++ = '\\';
*w++ = '"';
backslashes = 0;
} else {
backslashes = 0;
*w++ = *p;
}
}
/* Double trailing backslashes before the closing quote. */
for (size_t b = 0; b < backslashes; b++) {
*w++ = '\\';
}
*w++ = '"';
} else {
for (const char *p = arg; *p; p++) {
*w++ = *p;
}
}
}
*w = '\0';
wchar_t *out = cbm_utf8_to_wide(buf);
free(buf);
return out;
}
int cbm_exec_no_shell(const char *const *argv) {
if (!argv || !argv[0]) {
return CBM_NOT_FOUND;
}
wchar_t *cmdline = cbm_build_cmdline(argv);
if (!cmdline) {
return CBM_NOT_FOUND;
}
STARTUPINFOW si;
PROCESS_INFORMATION pi;
memset(&si, 0, sizeof(si));
memset(&pi, 0, sizeof(pi));
si.cb = sizeof(si);
if (!CreateProcessW(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
free(cmdline);
return CBM_NOT_FOUND;
}
free(cmdline);
WaitForSingleObject(pi.hProcess, INFINITE);
DWORD exit_code = (DWORD)CBM_NOT_FOUND;
GetExitCodeProcess(pi.hProcess, &exit_code);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return (int)exit_code;
}
#else /* POSIX */
/* ── POSIX implementation ────────────────────────────────── */
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
struct cbm_dir {
DIR *dir;
cbm_dirent_t entry;
};
cbm_dir_t *cbm_opendir(const char *path) {
if (!path) {
return NULL;
}
DIR *dir = opendir(path);
if (!dir) {
return NULL;
}
cbm_dir_t *d = (cbm_dir_t *)calloc(CBM_ALLOC_ONE, sizeof(cbm_dir_t));
if (!d) {
closedir(dir);
return NULL;
}
d->dir = dir;
return d;
}
cbm_dirent_t *cbm_readdir(cbm_dir_t *d) {
if (!d || !d->dir) {
return NULL;
}
struct dirent *de;
while ((de = readdir(d->dir)) != NULL) {
/* Skip "." and ".." */
if (de->d_name[0] == '.' &&
(de->d_name[SKIP_ONE] == '\0' ||
(de->d_name[SKIP_ONE] == '.' && de->d_name[PAIR_LEN] == '\0'))) {
continue;
}
size_t nlen = strlen(de->d_name);
if (nlen >= CBM_DIRENT_NAME_MAX) {
nlen = CBM_DIRENT_NAME_MAX - SKIP_ONE;
}
memcpy(d->entry.name, de->d_name, nlen);
d->entry.name[nlen] = '\0';
d->entry.is_dir = (de->d_type == DT_DIR);
d->entry.d_type = de->d_type;
return &d->entry;
}
return NULL;
}
void cbm_closedir(cbm_dir_t *d) {
if (d) {
if (d->dir) {
closedir(d->dir);
}
free(d);
}
}
FILE *cbm_popen(const char *cmd, const char *mode) {
return popen(cmd, mode);
}
int cbm_pclose(FILE *f) {
return pclose(f);
}
FILE *cbm_fopen(const char *path, const char *mode) {
return fopen(path, mode);
}
static int cbm_open_directory_component(int parent, const char *component, int flags) {
int descriptor = openat(parent, component, flags);
#if defined(O_NOFOLLOW) && defined(AT_SYMLINK_NOFOLLOW)
if (descriptor < 0) {
struct stat state;
if (fstatat(parent, component, &state, AT_SYMLINK_NOFOLLOW) == 0 &&
S_ISLNK(state.st_mode) && state.st_uid == 0U) {
descriptor = openat(parent, component, flags & ~O_NOFOLLOW);
}
}
#endif
return descriptor;
}
bool cbm_mkdir_p(const char *path, int mode) {
if (!path || path[0] == '\0') {
return false;
}
char *tmp = strdup(path);
if (!tmp) {
return false;
}
int flags = O_RDONLY;
#ifdef O_DIRECTORY
flags |= O_DIRECTORY;
#endif
#ifdef O_NOFOLLOW
flags |= O_NOFOLLOW;
#endif
#ifdef O_CLOEXEC
flags |= O_CLOEXEC;
#endif
int directory = open(path[0] == '/' ? "/" : ".", flags);
if (directory < 0) {
free(tmp);
return false;
}
bool ok = true;
char *cursor = tmp;
while (*cursor == '/') {
cursor++;
}
while (ok && *cursor) {
char *separator = strchr(cursor, '/');
if (separator) {
*separator = '\0';
}
if (cursor[0] != '\0' && strcmp(cursor, ".") != 0) {
int next = cbm_open_directory_component(directory, cursor, flags);
if (next < 0 && errno == ENOENT) {
if (mkdirat(directory, cursor, (mode_t)mode) != 0 && errno != EEXIST) {
ok = false;
} else {
next = cbm_open_directory_component(directory, cursor, flags);
}
}
if (ok && next < 0) {
ok = false;
}
if (ok) {
(void)close(directory);
directory = next;
}
}
if (!separator) {
break;
}
*separator = '/';
cursor = separator + 1;
while (*cursor == '/') {
cursor++;
}
}
(void)close(directory);
free(tmp);
return ok;
}
int cbm_unlink(const char *path) {
return unlink(path);
}
int cbm_rmdir(const char *path) {
return rmdir(path);
}
int cbm_exec_no_shell(const char *const *argv) {
if (!argv || !argv[0]) {
return CBM_NOT_FOUND;
}
pid_t pid = fork();
if (pid < 0) {
return CBM_NOT_FOUND;
}
if (pid == 0) {
/* Child: exec directly — no shell interpretation */
/* 127 = standard "command not found" exit code (POSIX convention) */
enum { EXEC_NOT_FOUND = 127 };
execvp(argv[0], (char *const *)argv);
_exit(EXEC_NOT_FOUND);
}
/* Parent: wait for child */
int status = 0;
if (waitpid(pid, &status, 0) < 0) {
return CBM_NOT_FOUND;
}
if (WIFEXITED(status)) {
return WEXITSTATUS(status);
}
return CBM_NOT_FOUND; /* killed by signal */
}
#endif /* _WIN32 */
/* Canonicalize an EXISTING path (collapse `..`, resolve links/junctions):
* realpath on POSIX; a final path queried from an opened handle on Windows.
* The previous Windows callers used the ANSI CRT (_access/_fullpath) on UTF-8
* input — locale-dependent by construction: on a CJK system codepage (e.g.
* Big5) the UTF-8 bytes of a CJK path re-decode into different characters and
* canonicalization corrupts the path (#973). GetFullPathNameW alone is also
* only lexical and would let an allowed-root check follow a junction outside
* the root. Returns 0 when the path does not exist or cannot be resolved. */
int cbm_canonical_path(const char *path, char *out, size_t out_sz) {
if (!path || !out || out_sz == 0) {
return 0;
}
#ifdef _WIN32
wchar_t *wpath = cbm_path_to_wide(path);
if (!wpath) {
return 0;
}
HANDLE handle = CreateFileW(wpath, FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
free(wpath);
if (handle == INVALID_HANDLE_VALUE) {
return 0;
}
DWORD needed =
GetFinalPathNameByHandleW(handle, NULL, 0, FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
if (needed == 0 || needed == MAXDWORD || (size_t)needed > SIZE_MAX / sizeof(wchar_t) - 1) {
(void)CloseHandle(handle);
return 0;
}
size_t capacity = (size_t)needed + 1;
wchar_t *wfull = calloc(capacity, sizeof(*wfull));
if (!wfull) {
(void)CloseHandle(handle);
return 0;
}
DWORD n = GetFinalPathNameByHandleW(handle, wfull, (DWORD)capacity,
FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
(void)CloseHandle(handle);
if (n == 0 || (size_t)n >= capacity) {
free(wfull);
return 0;
}
/* Preserve the conventional DOS/UNC form returned by the old API while
* retaining the handle-based resolution. */
if (wcsncmp(wfull, L"\\\\?\\UNC\\", 8) == 0) {
size_t tail_length = wcslen(wfull + 8);
wmemmove(wfull + 2, wfull + 8, tail_length + 1);
wfull[0] = L'\\';
wfull[1] = L'\\';
} else if (wcsncmp(wfull, L"\\\\?\\", 4) == 0) {
size_t tail_length = wcslen(wfull + 4);
wmemmove(wfull, wfull + 4, tail_length + 1);
}
char *utf8 = cbm_wide_to_utf8(wfull);
free(wfull);
if (!utf8) {
return 0;
}
size_t len = strlen(utf8);
if (len >= out_sz) {
free(utf8);
return 0;
}
memcpy(out, utf8, len + 1);
free(utf8);
return 1;
#else
/* Callers pass >= 4K buffers (>= PATH_MAX on our platforms). */
return realpath(path, out) != NULL;
#endif
}
/* rename() with overwrite semantics on every platform: POSIX rename already
* replaces atomically; Windows rename fails with EEXIST when the target
* exists, so use write-through MoveFileExW(MOVEFILE_REPLACE_EXISTING) there
* (wide paths — raw MoveFileExA would re-mangle non-ASCII cache paths). */
int cbm_rename_replace(const char *src, const char *dst) {
#ifdef _WIN32
wchar_t *wsrc = cbm_path_to_wide(src);
wchar_t *wdst = cbm_path_to_wide(dst);
int ret = CBM_NOT_FOUND;
if (wsrc && wdst) {
ret = MoveFileExW(wsrc, wdst, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)
? 0
: CBM_NOT_FOUND;
}
free(wsrc);
free(wdst);
return ret;
#else
return rename(src, dst);
#endif
}
/* Remove a SQLite database's -wal/-shm/-journal sidecars (both platforms). Any code
* path that installs a FRESH database file at a path where a previous
* generation lived must call this first: SQLite decides whether to replay a
* WAL purely from the sidecar's own header/checksums, so a leftover WAL
* from a crashed session is recovered ON TOP of the freshly installed file
* at the next open, splicing old-generation pages into it (#897). */
int cbm_remove_db_sidecars(const char *db_path) {
if (!db_path || !db_path[0]) {
return CBM_NOT_FOUND;
}
enum { SIDECAR_PATH_MAX = 4096 };
char side[SIDECAR_PATH_MAX];
/* Validate the longest suffix before unlinking anything. Otherwise a
* near-limit path can remove -wal/-shm, silently skip a truncated
* -journal, and report success after partially mutating the generation. */
if (strlen(db_path) > sizeof(side) - sizeof("-journal")) {
return CBM_NOT_FOUND;
}
int result = 0;
int n = snprintf(side, sizeof(side), "%s-wal", db_path);
if (n <= 0 || (size_t)n >= sizeof(side)) {
return CBM_NOT_FOUND;
}
errno = 0;
int unlink_rc = cbm_unlink(side);
int unlink_error = errno;
if (unlink_rc != 0 && unlink_error != ENOENT) {
result = CBM_NOT_FOUND;
}
n = snprintf(side, sizeof(side), "%s-shm", db_path);
if (n <= 0 || (size_t)n >= sizeof(side)) {
return CBM_NOT_FOUND;
}
errno = 0;
unlink_rc = cbm_unlink(side);
unlink_error = errno;
if (unlink_rc != 0 && unlink_error != ENOENT) {
result = CBM_NOT_FOUND;
}
n = snprintf(side, sizeof(side), "%s-journal", db_path);
if (n <= 0 || (size_t)n >= sizeof(side)) {
return CBM_NOT_FOUND;
}
errno = 0;
unlink_rc = cbm_unlink(side);
unlink_error = errno;
if (unlink_rc != 0 && unlink_error != ENOENT) {
result = CBM_NOT_FOUND;
}
return result;
}