diff --git a/scripts/memory-core-baseline.txt b/scripts/memory-core-baseline.txt index 67c3980c3..76e5e063d 100644 --- a/scripts/memory-core-baseline.txt +++ b/scripts/memory-core-baseline.txt @@ -29,7 +29,7 @@ src/daemon/application.c 107 src/daemon/bootstrap.c 13 src/daemon/daemon.c 31 src/daemon/frontend.c 12 -src/daemon/ipc.c 146 +src/daemon/ipc.c 144 src/daemon/project_lock.c 6 src/daemon/runtime.c 45 src/daemon/service.c 6 diff --git a/src/cli/cli.c b/src/cli/cli.c index 375499279..0ad58306d 100644 --- a/src/cli/cli.c +++ b/src/cli/cli.c @@ -7902,14 +7902,18 @@ cbm_config_t *cbm_config_open(const char *cache_dir) { return NULL; } - char dbpath[CLI_BUF_1K]; - snprintf(dbpath, sizeof(dbpath), "%s/" CBM_CONFIG_DB_FILENAME, cache_dir); + char dbpath[4096]; + int dbpath_length = snprintf(dbpath, sizeof(dbpath), "%s/" CBM_CONFIG_DB_FILENAME, cache_dir); + if (dbpath_length < 0 || (size_t)dbpath_length >= sizeof(dbpath)) { + return NULL; + } /* Ensure directory exists */ mkdirp(cache_dir, DIR_PERMS); sqlite3 *db = NULL; - if (sqlite3_open(dbpath, &db) != SQLITE_OK) { + if (cbm_runtime_settings_open_db(dbpath, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE) != + SQLITE_OK) { if (db) { sqlite3_close(db); } diff --git a/src/cli/runtime_settings.c b/src/cli/runtime_settings.c index 6b11101c6..97c7de5e3 100644 --- a/src/cli/runtime_settings.c +++ b/src/cli/runtime_settings.c @@ -5,6 +5,9 @@ #include "foundation/platform.h" #include "foundation/log.h" #include "foundation/compat_fs.h" +#ifdef _WIN32 +#include "foundation/win_utf8.h" +#endif #include "daemon/ipc.h" #include "ui/config.h" #include @@ -241,6 +244,24 @@ static bool canonical_cache_path(const char *cache, char out[SETTINGS_PATH_CAP], return cbm_daemon_ipc_private_directory_secure(out); } +int cbm_runtime_settings_open_db(const char *path, sqlite3 **db, int flags) { +#ifdef _WIN32 + *db = NULL; + wchar_t *wide = cbm_path_to_wide_in(CBM_MEM_CLASS_OTHER, path); + if (!wide) + return SQLITE_NOMEM; + char extended[SETTINGS_PATH_CAP + 8]; + int converted = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, wide, -1, extended, + sizeof(extended), NULL, NULL); + cbm_free(CBM_MEM_CLASS_OTHER, wide); + if (!converted) + return SQLITE_CANTOPEN; + return sqlite3_open_v2(extended, db, flags, "win32-longpath"); +#else + return sqlite3_open_v2(path, db, flags, NULL); +#endif +} + static sqlite3 *settings_open(const char *cache) { if (!cache || !cache[0] || strlen(cache) + 12 >= SETTINGS_PATH_CAP) return NULL; @@ -255,7 +276,8 @@ static sqlite3 *settings_open(const char *cache) { if (snprintf(path, sizeof(path), "%s/_config.db", canonical) >= (int)sizeof(path)) return NULL; sqlite3 *db = NULL; - if (sqlite3_open(path, &db) != SQLITE_OK) { + if (cbm_runtime_settings_open_db(path, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE) != + SQLITE_OK) { if (db) sqlite3_close(db); return NULL; @@ -477,7 +499,7 @@ void cbm_runtime_settings_reset_for_tests(void) { * progress; a live writer takes the busy path instead. */ static bool settings_recover_hot_journal(const char *path) { sqlite3 *db = NULL; - bool recovered = sqlite3_open_v2(path, &db, SQLITE_OPEN_READWRITE, NULL) == SQLITE_OK; + bool recovered = cbm_runtime_settings_open_db(path, &db, SQLITE_OPEN_READWRITE) == SQLITE_OK; if (recovered) { cbm_runtime_settings_wait_for_writers(db); recovered = @@ -505,7 +527,7 @@ static bool settings_recover_hot_journal(const char *path) { static sqlite3 *settings_open_snapshot(const char *path, bool *hot_journal) { *hot_journal = false; sqlite3 *db = NULL; - if (sqlite3_open_v2(path, &db, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) { + if (cbm_runtime_settings_open_db(path, &db, SQLITE_OPEN_READONLY) != SQLITE_OK) { if (db) sqlite3_close(db); return NULL; diff --git a/src/cli/runtime_settings.h b/src/cli/runtime_settings.h index 099a201e5..bce0e7e19 100644 --- a/src/cli/runtime_settings.h +++ b/src/cli/runtime_settings.h @@ -29,6 +29,8 @@ void cbm_runtime_settings_note_http_port(int port); * failing on its lock. Logs config_db.busy_wait once per busy wait. */ struct sqlite3; void cbm_runtime_settings_wait_for_writers(struct sqlite3 *db); +/* Open the configuration database with a Windows long-path capable VFS. */ +int cbm_runtime_settings_open_db(const char *path, struct sqlite3 **db, int flags); #ifdef CBM_ENABLE_TEST_SEAMS /* Single-threaded test teardown only; never exposed in production builds. */ diff --git a/src/daemon/host.c b/src/daemon/host.c index 9e50f121d..be78dda24 100644 --- a/src/daemon/host.c +++ b/src/daemon/host.c @@ -1153,6 +1153,7 @@ int cbm_daemon_host_run(const cbm_daemon_host_config_t *config) { cbm_daemon_runtime_service_config_t runtime_config = { .endpoint = config->endpoint, .identity = config->identity, + .cache_directory = cbm_resolve_cache_dir(), .conflict_log_path = conflict_log, .conflict_log_cap_bytes = HOST_CONFLICT_LOG_CAP, .max_clients = HOST_MAX_CLIENTS, diff --git a/src/daemon/ipc.c b/src/daemon/ipc.c index d7e075ebc..22f0558a6 100644 --- a/src/daemon/ipc.c +++ b/src/daemon/ipc.c @@ -9,10 +9,14 @@ #include "foundation/compat_thread.h" #include "foundation/log.h" #include "foundation/macos_acl.h" +#include "foundation/mem_core.h" #include "foundation/platform.h" #include "foundation/private_file_lock_internal.h" #include "foundation/sha256.h" #include "foundation/secure_random.h" +#ifdef _WIN32 +#include "foundation/win_utf8.h" +#endif #include #include @@ -5425,10 +5429,19 @@ static bool win_private_directory_tree_secure(const wchar_t *directory_path) { * absolute drive path. */ return false; } - wchar_t *path = wide_copy(directory_path); + /* Prefix the already validated drive-absolute spelling without resolving + * dot components: the component walk must still reject those itself. */ + bool extended = length >= 240U; + size_t prefix_length = extended ? 4U : 0U; + wchar_t *path = cbm_calloc(CBM_MEM_CLASS_OTHER, (length + prefix_length + 1U) * sizeof(*path)); if (!path) { return false; } + if (extended) { + wmemcpy(path, L"\\\\?\\", prefix_length); + } + wmemcpy(path + prefix_length, directory_path, length + 1U); + length = wcslen(path); for (size_t i = 0; i < length; i++) { if (path[i] == L'/') { path[i] = L'\\'; @@ -5436,11 +5449,11 @@ static bool win_private_directory_tree_secure(const wchar_t *directory_path) { } win_security_t security; if (!win_security_init(&security)) { - free(path); + cbm_free(CBM_MEM_CLASS_OTHER, path); return false; } bool ok = true; - size_t component_start = 3; + size_t component_start = 3U + prefix_length; for (size_t i = component_start; ok && i <= length; i++) { if (i < length && path[i] != L'\\') { continue; @@ -5509,7 +5522,7 @@ static bool win_private_directory_tree_secure(const wchar_t *directory_path) { if (ok) { ok = win_runtime_directory_secure(path); } - free(path); + cbm_free(CBM_MEM_CLASS_OTHER, path); return ok; } @@ -5577,8 +5590,8 @@ FILE *cbm_daemon_ipc_private_log_open(const char *directory_path, const char *ba wchar_t *wide_directory = utf8_to_wide(directory_path); char *path = string_format("%s/%s", directory_path, base_name); char *rotated_path = path ? string_format("%s.1", path) : NULL; - wchar_t *wide_path = path ? utf8_to_wide(path) : NULL; - wchar_t *wide_rotated = rotated_path ? utf8_to_wide(rotated_path) : NULL; + wchar_t *wide_path = path ? cbm_path_to_wide(path) : NULL; + wchar_t *wide_rotated = rotated_path ? cbm_path_to_wide(rotated_path) : NULL; if (!wide_directory || !path || !rotated_path || !wide_path || !wide_rotated || !win_private_directory_tree_secure(wide_directory)) { free(wide_directory); diff --git a/src/daemon/runtime.c b/src/daemon/runtime.c index eb2eddf70..689179174 100644 --- a/src/daemon/runtime.c +++ b/src/daemon/runtime.c @@ -4,6 +4,7 @@ #include "daemon/runtime.h" #include "daemon/ipc_internal.h" +#include "daemon/runtime_status_details_internal.h" #include "daemon/service_internal.h" #include "foundation/compat.h" @@ -280,6 +281,7 @@ struct cbm_daemon_runtime_service { char semantic_version[CBM_DAEMON_VERSION_TEXT_SIZE]; char build_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE]; + char cache_directory[CBM_DAEMON_STATUS_CACHE_PATH_SIZE]; cbm_daemon_build_identity_t identity; runtime_process_image_reference_t active_image; /* Guarded by mutex. Retained references keep each verified inode alive, @@ -2132,13 +2134,17 @@ static void runtime_control_collect_clients_locked(cbm_daemon_runtime_service_t } static void runtime_worker_handle_status(cbm_daemon_runtime_worker_t *worker, - const uint8_t *payload, uint32_t length) { + const uint8_t *payload, uint32_t length, + cbm_daemon_runtime_operation_t operation) { cbm_daemon_runtime_service_t *service = worker->service; char requested_build[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0}; bool peer_verified = runtime_control_request_decode(payload, length, requested_build) && runtime_activation_peer_matches_claim(service, worker->peer_process_id, requested_build); - uint8_t response[CBM_DAEMON_STATUS_RESPONSE_SIZE]; + uint8_t response[CBM_DAEMON_STATUS_DETAILS_RESPONSE_SIZE]; + uint32_t response_size = operation == CBM_DAEMON_RUNTIME_OP_STATUS_DETAILS + ? CBM_DAEMON_STATUS_DETAILS_RESPONSE_SIZE + : CBM_DAEMON_STATUS_RESPONSE_SIZE; memset(response, 0, sizeof(response)); if (peer_verified) { uint8_t count = 0U; @@ -2173,9 +2179,13 @@ static void runtime_worker_handle_status(cbm_daemon_runtime_worker_t *worker, service->identity.semantic_version ? service->identity.semantic_version : ""); cbm_mutex_unlock(&service->mutex); + if (operation == CBM_DAEMON_RUNTIME_OP_STATUS_DETAILS) { + memcpy(response + CBM_DAEMON_STATUS_RESPONSE_SIZE, service->cache_directory, + sizeof(service->cache_directory)); + } } - (void)runtime_worker_send_frame(worker, CBM_DAEMON_FRAME_RESPONSE, CBM_DAEMON_RUNTIME_OP_STATUS, - response, (uint32_t)sizeof(response)); + (void)runtime_worker_send_frame(worker, CBM_DAEMON_FRAME_RESPONSE, operation, response, + response_size); runtime_worker_finish(worker); } @@ -2377,8 +2387,9 @@ static void *runtime_connection_worker(void *opaque) { free(payload); return NULL; } - if (frame.flags == CBM_DAEMON_RUNTIME_OP_STATUS) { - runtime_worker_handle_status(worker, payload, frame.length); + if (frame.flags == CBM_DAEMON_RUNTIME_OP_STATUS || + frame.flags == CBM_DAEMON_RUNTIME_OP_STATUS_DETAILS) { + runtime_worker_handle_status(worker, payload, frame.length, frame.flags); free(payload); return NULL; } @@ -2919,6 +2930,15 @@ cbm_daemon_runtime_service_t *cbm_daemon_runtime_service_start_reserved( memcpy(service->semantic_version, config->identity.semantic_version, version_length + 1); memcpy(service->build_fingerprint, config->identity.build_fingerprint, build_length + 1); } + if (config->cache_directory) { + size_t cache_length = 0; + copied_identity = copied_identity && + runtime_bounded_length(config->cache_directory, + sizeof(service->cache_directory), &cache_length); + if (copied_identity) { + memcpy(service->cache_directory, config->cache_directory, cache_length + sizeof(char)); + } + } service->identity.semantic_version = service->semantic_version; service->identity.build_fingerprint = service->build_fingerprint; service->identity.protocol_abi = config->identity.protocol_abi; @@ -3304,6 +3324,32 @@ static uint32_t runtime_control_read_u32(const uint8_t *bytes) { (uint32_t)bytes[3]; } +static bool runtime_status_response_finish(uint8_t *payload, bool valid, + cbm_daemon_runtime_status_t *status_out, char *cache) { + if (valid) { + status_out->permanent = (payload[1] & 0x01U) != 0U; + status_out->stopping = (payload[1] & 0x02U) != 0U; + status_out->committed_clients = (uint16_t)(((uint16_t)payload[2] << 8) | payload[3]); + status_out->daemon_pid = runtime_control_read_u32(payload + 4); + status_out->client_count = payload[8] > CBM_DAEMON_CONTROL_CLIENT_CAP + ? (uint8_t)CBM_DAEMON_CONTROL_CLIENT_CAP + : payload[8]; + for (size_t index = 0; index < CBM_DAEMON_CONTROL_CLIENT_CAP; index++) { + status_out->client_pids[index] = runtime_control_read_u32(payload + 12U + index * 4U); + } + memcpy(status_out->build_fingerprint, payload + 44U, CBM_DAEMON_BUILD_FINGERPRINT_SIZE); + status_out->build_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE - 1U] = '\0'; + memcpy(status_out->semantic_version, payload + 109U, sizeof(status_out->semantic_version)); + status_out->semantic_version[sizeof(status_out->semantic_version) - 1U] = '\0'; + if (cache) { + memcpy(cache, payload + CBM_DAEMON_STATUS_RESPONSE_SIZE, + CBM_DAEMON_STATUS_CACHE_PATH_SIZE); + } + } + free(payload); + return valid; +} + bool cbm_daemon_runtime_request_status(const cbm_daemon_ipc_endpoint_t *endpoint, const cbm_daemon_build_identity_t *identity, uint32_t timeout_ms, @@ -3318,22 +3364,98 @@ bool cbm_daemon_runtime_request_status(const cbm_daemon_ipc_endpoint_t *endpoint &status_out->muted_endpoint_holder_pid)) { return false; } - status_out->permanent = (payload[1] & 0x01U) != 0U; - status_out->stopping = (payload[1] & 0x02U) != 0U; - status_out->committed_clients = (uint16_t)(((uint16_t)payload[2] << 8) | payload[3]); - status_out->daemon_pid = runtime_control_read_u32(payload + 4); - status_out->client_count = payload[8] > CBM_DAEMON_CONTROL_CLIENT_CAP - ? (uint8_t)CBM_DAEMON_CONTROL_CLIENT_CAP - : payload[8]; - for (size_t index = 0; index < CBM_DAEMON_CONTROL_CLIENT_CAP; index++) { - status_out->client_pids[index] = runtime_control_read_u32(payload + 12U + index * 4U); + return runtime_status_response_finish(payload, true, status_out, NULL); +} + +static const cbm_daemon_status_details_transport_t runtime_status_details_transport = { + .now_ms = cbm_now_ms, + .ipc_connect = cbm_daemon_ipc_connect, + .send = cbm_daemon_ipc_send_frame, + .receive = cbm_daemon_ipc_receive_frame_bounded, + .close = cbm_daemon_ipc_connection_close, +}; + +#ifdef CBM_ENABLE_TEST_SEAMS +static const cbm_daemon_status_details_transport_t *runtime_status_details_transport_seam; +void cbm_daemon_runtime_set_status_details_transport_for_testing( + const cbm_daemon_status_details_transport_t *transport) { + runtime_status_details_transport_seam = transport; +} +#endif + +static uint32_t runtime_status_details_remaining( + const cbm_daemon_status_details_transport_t *transport, uint64_t deadline) { + uint64_t now = transport->now_ms(); + return now < deadline ? (uint32_t)(deadline - now) : 0; +} + +/* This deadline belongs only to STATUS_DETAILS and its optional legacy retry. */ +static bool runtime_status_request_until(const cbm_daemon_ipc_endpoint_t *endpoint, + const cbm_daemon_build_identity_t *identity, + uint64_t deadline, + const cbm_daemon_status_details_transport_t *transport, + cbm_daemon_runtime_status_t *status, char *cache) { + uint8_t request[CBM_DAEMON_CONTROL_REQUEST_SIZE] = {0}; + int written = snprintf((char *)request, sizeof(request), "%s", identity->build_fingerprint); + if (written <= 0 || (size_t)written != CBM_DAEMON_BUILD_FINGERPRINT_SIZE - 1U) { + return false; } - memcpy(status_out->build_fingerprint, payload + 44U, CBM_DAEMON_BUILD_FINGERPRINT_SIZE); - status_out->build_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE - 1U] = '\0'; - memcpy(status_out->semantic_version, payload + 109U, sizeof(status_out->semantic_version)); - status_out->semantic_version[sizeof(status_out->semantic_version) - 1U] = '\0'; - free(payload); - return true; + uint32_t remaining = runtime_status_details_remaining(transport, deadline); + if (remaining == 0) { + return false; + } + cbm_daemon_ipc_connection_t *connection = transport->ipc_connect(endpoint, remaining); + if (!connection) { + return false; + } + cbm_daemon_runtime_operation_t operation = + cache ? CBM_DAEMON_RUNTIME_OP_STATUS_DETAILS : CBM_DAEMON_RUNTIME_OP_STATUS; + uint32_t response_size = + cache ? CBM_DAEMON_STATUS_DETAILS_RESPONSE_SIZE : CBM_DAEMON_STATUS_RESPONSE_SIZE; + bool sent = runtime_status_details_remaining(transport, deadline) > 0 && + transport->send(connection, CBM_DAEMON_FRAME_REQUEST, operation, request, + (uint32_t)sizeof(request)); + remaining = runtime_status_details_remaining(transport, deadline); + cbm_daemon_frame_t frame = {0}; + uint8_t *payload = NULL; + int received = sent && remaining > 0 + ? transport->receive(connection, remaining, response_size, &frame, &payload) + : 0; + bool valid = received == 1 && frame.type == CBM_DAEMON_FRAME_RESPONSE && + frame.flags == operation && frame.length == response_size && payload && + payload[0] == 1U && + (!cache || memchr(payload + CBM_DAEMON_STATUS_RESPONSE_SIZE, '\0', + CBM_DAEMON_STATUS_CACHE_PATH_SIZE)); + transport->close(connection); + return runtime_status_response_finish(payload, valid, status, cache); +} + +bool cbm_daemon_runtime_request_status_details(const cbm_daemon_ipc_endpoint_t *endpoint, + const cbm_daemon_build_identity_t *identity, + uint32_t timeout_ms, + cbm_daemon_runtime_status_details_t *details_out) { + if (!details_out) { + return false; + } + memset(details_out, 0, sizeof(*details_out)); + if (!endpoint || !identity || !identity->build_fingerprint || + timeout_ms == CBM_DAEMON_IPC_WAIT_FOREVER) { + return false; + } + const cbm_daemon_status_details_transport_t *transport = &runtime_status_details_transport; +#ifdef CBM_ENABLE_TEST_SEAMS + if (runtime_status_details_transport_seam) { + transport = runtime_status_details_transport_seam; + } +#endif + uint64_t now = transport->now_ms(); + uint64_t deadline = UINT64_MAX - now < timeout_ms ? UINT64_MAX : now + timeout_ms; + if (runtime_status_request_until(endpoint, identity, deadline, transport, &details_out->status, + details_out->cache_directory)) { + return true; + } + return runtime_status_request_until(endpoint, identity, deadline, transport, + &details_out->status, NULL); } /* "; CBM sessions using it: pids 1, 2 and 3 more" — empty when none are known. */ diff --git a/src/daemon/runtime.h b/src/daemon/runtime.h index 361a7e781..9418fdc61 100644 --- a/src/daemon/runtime.h +++ b/src/daemon/runtime.h @@ -55,6 +55,10 @@ #define CBM_DAEMON_CONTROL_REQUEST_SIZE 65U #define CBM_DAEMON_CONTROL_CLIENT_CAP 8U #define CBM_DAEMON_STATUS_RESPONSE_SIZE 121U +#define CBM_DAEMON_STATUS_CACHE_PATH_SIZE 4096U +/* Separate operation: the frozen STATUS response remains exactly 121 bytes. */ +#define CBM_DAEMON_STATUS_DETAILS_RESPONSE_SIZE \ + (CBM_DAEMON_STATUS_RESPONSE_SIZE + CBM_DAEMON_STATUS_CACHE_PATH_SIZE) #define CBM_DAEMON_STOP_RESPONSE_SIZE 40U #define CBM_DAEMON_RUNTIME_PROJECT_KEY_MAX 4096U #define CBM_DAEMON_RUNTIME_APPLICATION_PAYLOAD_MAX (CBM_DAEMON_MAX_FRAME_SIZE - 16U) @@ -87,6 +91,9 @@ typedef enum { * otherwise begins the normal stopping sequence — including for a * PERMANENT generation, which this op and process kill alone may end. */ CBM_DAEMON_RUNTIME_OP_STOP = 11, + /* Authenticated read-only STATUS plus a NUL-terminated canonical cache + * path in a fixed 4096-byte suffix. Empty means unavailable. */ + CBM_DAEMON_RUNTIME_OP_STATUS_DETAILS = 12, } cbm_daemon_runtime_operation_t; typedef enum { @@ -180,6 +187,8 @@ typedef struct { typedef struct { const cbm_daemon_ipc_endpoint_t *endpoint; cbm_daemon_build_identity_t identity; + /* Optional canonical path, copied at startup; never persisted in logs. */ + const char *cache_directory; const char *conflict_log_path; size_t conflict_log_cap_bytes; /* Hard cap on accepted connection threads, including sockets that have not @@ -278,6 +287,11 @@ typedef struct { uint64_t muted_endpoint_holder_pid; } cbm_daemon_runtime_status_t; +typedef struct { + cbm_daemon_runtime_status_t status; + char cache_directory[CBM_DAEMON_STATUS_CACHE_PATH_SIZE]; +} cbm_daemon_runtime_status_details_t; + typedef struct { bool accepted; /* stopping was initiated */ bool busy; /* refused: committed clients hold the daemon */ @@ -293,6 +307,13 @@ bool cbm_daemon_runtime_request_status(const cbm_daemon_ipc_endpoint_t *endpoint uint32_t timeout_ms, cbm_daemon_runtime_status_t *status_out); +/* Prefer STATUS_DETAILS, then fall back to legacy STATUS within one timeout. + * A successful legacy reply leaves cache_directory empty. */ +bool cbm_daemon_runtime_request_status_details(const cbm_daemon_ipc_endpoint_t *endpoint, + const cbm_daemon_build_identity_t *identity, + uint32_t timeout_ms, + cbm_daemon_runtime_status_details_t *details_out); + /* One-shot authenticated stop request. Refuses while committed clients exist * (result_out lists their pids); otherwise begins the stopping sequence, for * permanent generations too. */ diff --git a/src/daemon/runtime_status_details_internal.h b/src/daemon/runtime_status_details_internal.h new file mode 100644 index 000000000..60089a6c8 --- /dev/null +++ b/src/daemon/runtime_status_details_internal.h @@ -0,0 +1,24 @@ +#ifndef CBM_DAEMON_RUNTIME_STATUS_DETAILS_INTERNAL_H +#define CBM_DAEMON_RUNTIME_STATUS_DETAILS_INTERNAL_H + +#include "daemon/ipc.h" + +/* Dependencies of the new STATUS_DETAILS exchange only. Legacy STATUS/STOP + * continue to use runtime_control_request_send unchanged. */ +typedef struct { + uint64_t (*now_ms)(void); + cbm_daemon_ipc_connection_t *(*ipc_connect)(const cbm_daemon_ipc_endpoint_t *, uint32_t); + bool (*send)(cbm_daemon_ipc_connection_t *, cbm_daemon_frame_type_t, uint16_t, const void *, + uint32_t); + int (*receive)(cbm_daemon_ipc_connection_t *, uint32_t, uint32_t, cbm_daemon_frame_t *, + uint8_t **); + void (*close)(cbm_daemon_ipc_connection_t *); +} cbm_daemon_status_details_transport_t; + +#ifdef CBM_ENABLE_TEST_SEAMS +/* Single-threaded test scope; NULL restores real IPC and the monotonic clock. */ +void cbm_daemon_runtime_set_status_details_transport_for_testing( + const cbm_daemon_status_details_transport_t *transport); +#endif + +#endif diff --git a/src/main.c b/src/main.c index 257c5cb26..1a2b88df4 100644 --- a/src/main.c +++ b/src/main.c @@ -27,6 +27,8 @@ #include "daemon/application.h" #include "daemon/bootstrap.h" #include "daemon/frontend.h" +#include "daemon/runtime.h" +#include "daemon/service.h" #include "daemon/host.h" #include "daemon/ipc.h" #include "daemon/project_lock.h" @@ -1844,6 +1846,124 @@ static void main_conflict_remedy_probe(const cbm_daemon_ipc_endpoint_t *endpoint } } +static bool main_cache_path_matches(const char *path, const char *expected_fingerprint) { + if (!path || !path[0] || !expected_fingerprint) { + return false; + } + char fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE]; + cbm_sha256_hex(path, strlen(path), fingerprint); + return strcmp(fingerprint, expected_fingerprint) == 0; +} + +/* Stream the quoted path: two maximum-length roots must not pass through + * the frozen 512-byte rendezvous message or a truncating concatenation. */ +static void main_print_cache_path(const char *path) { + enum { ASCII_SPACE = 0x20, ASCII_DELETE = 0x7f }; + (void)fputc('"', stderr); + for (const unsigned char *p = (const unsigned char *)path; *p; p++) { + switch (*p) { + case '"': + case '\\': + (void)fputc('\\', stderr); + (void)fputc(*p, stderr); + break; + case '\n': + (void)fputs("\\n", stderr); + break; + case '\r': + (void)fputs("\\r", stderr); + break; + case '\t': + (void)fputs("\\t", stderr); + break; + case '\b': + (void)fputs("\\b", stderr); + break; + case '\f': + (void)fputs("\\f", stderr); + break; + default: + if (*p < ASCII_SPACE || *p == ASCII_DELETE) { + (void)fprintf(stderr, "\\u%04x", (unsigned)*p); + } else { + (void)fputc(*p, stderr); + } + } + } + (void)fputc('"', stderr); +} + +/* Client-only diagnostics: cohort records and durable logs retain hashes. + * A daemon may have turned over since rejection; prove the returned path + * belongs to the rejected cache/build before attributing it to that conflict. */ +static bool main_report_cache_conflict(const cbm_daemon_ipc_endpoint_t *endpoint, + const cbm_daemon_build_identity_t *identity, + const cbm_daemon_conflict_t *conflict) { + if (conflict->status != CBM_DAEMON_HELLO_CACHE_CONFLICT) { + return false; + } + char requested[MAIN_PATH_CAP] = ""; + const char *cache = cbm_resolve_cache_dir(); + if (cache) { + (void)snprintf(requested, sizeof(requested), "%s", cache); + } + cbm_daemon_runtime_status_details_t details; + bool known = cbm_daemon_runtime_request_status_details( + endpoint, identity, MAIN_CONFLICT_STATUS_PROBE_TIMEOUT_MS, &details); + bool paths_known = + known && + strcmp(details.status.build_fingerprint, conflict->active_build_fingerprint) == 0 && + main_cache_path_matches(details.cache_directory, conflict->active_cache_fingerprint) && + main_cache_path_matches(requested, conflict->requested_cache_fingerprint); + if (paths_known) { + (void)fputs("codebase-memory-mcp: CBM could not start because the active account daemon " + "uses a different cache directory.\n requested cache: ", + stderr); + main_print_cache_path(requested); + (void)fputs("\n daemon cache: ", stderr); + main_print_cache_path(details.cache_directory); + (void)fputs("\nClose all CBM sessions and commands, then retry with one consistent " + "CBM_CACHE_DIR.", + stderr); + } else { + char message[CBM_DAEMON_CONFLICT_MESSAGE_SIZE]; + if (!cbm_daemon_conflict_format(conflict, message, sizeof(message))) { + return false; + } + (void)fprintf(stderr, "codebase-memory-mcp: %s Cache paths unavailable or unverified.", + message); + } + char remedy[CBM_DAEMON_CONFLICT_REMEDY_SIZE]; + if (cbm_daemon_conflict_remedy_format(known ? &details.status : NULL, remedy, sizeof(remedy))) { + (void)fprintf(stderr, " %s", remedy); + } + (void)fputc('\n', stderr); + return true; +} + +static void main_report_cohort_failure(const cbm_daemon_ipc_endpoint_t *endpoint, + const cbm_daemon_build_identity_t *identity, + cbm_version_cohort_status_t status, + const cbm_daemon_conflict_t *conflict, const char *fallback, + bool probe) { + char message[CBM_DAEMON_CONFLICT_MESSAGE_SIZE]; + bool formatted = status == CBM_VERSION_COHORT_CONFLICT && + cbm_daemon_conflict_format(conflict, message, sizeof(message)); + char remedy[CBM_DAEMON_CONFLICT_REMEDY_SIZE] = ""; + if (status == CBM_VERSION_COHORT_CONFLICT) { + (void)cbm_version_cohort_log_conflict(conflict); + /* Hooks fail open on a tight budget; they skip both probes. */ + if (probe) { + if (main_report_cache_conflict(endpoint, identity, conflict)) { + return; + } + main_conflict_remedy_probe(endpoint, identity, NULL, remedy, sizeof(remedy)); + } + } + (void)fprintf(stderr, "codebase-memory-mcp: %s%s%s\n", formatted ? message : fallback, + remedy[0] ? " " : "", remedy); +} + /* Client bootstrap with the upgrade policy: a CONFLICT against a PERMANENT * daemon of a strictly OLDER release is resolved by draining that daemon * (the same authenticated path install/update use) and retrying once. A @@ -3009,20 +3129,11 @@ int main(int argc, char **argv) { main_deadline_after(MAIN_STARTUP_TIMEOUT_MS), &cohort_lease, &cohort_conflict); if (cohort_status != CBM_VERSION_COHORT_OK) { - char message[CBM_DAEMON_CONFLICT_MESSAGE_SIZE]; - bool formatted = cohort_status == CBM_VERSION_COHORT_CONFLICT && - cbm_daemon_conflict_format(&cohort_conflict, message, sizeof(message)); - char remedy[CBM_DAEMON_CONFLICT_REMEDY_SIZE] = ""; - if (cohort_status == CBM_VERSION_COHORT_CONFLICT) { - (void)cbm_version_cohort_log_conflict(&cohort_conflict); - main_conflict_remedy_probe(local_endpoint, &local_identity, NULL, remedy, - sizeof(remedy)); - } - (void)fprintf(stderr, "codebase-memory-mcp: %s%s%s\n", - formatted ? message - : "CLI exact-build admission could not be verified; retry " - "after active CBM operations exit", - remedy[0] ? " " : "", remedy); + main_report_cohort_failure(local_endpoint, &local_identity, cohort_status, + &cohort_conflict, + "CLI exact-build admission could not be verified; retry " + "after active CBM operations exit", + true); goto local_cli_cleanup; } main_local_maintenance_context_init(&maintenance_context); @@ -3341,21 +3452,9 @@ int main(int argc, char **argv) { &client_cohort_lease, &client_cohort_conflict) : CBM_VERSION_COHORT_IO; if (client_cohort_status != CBM_VERSION_COHORT_OK) { - char message[CBM_DAEMON_CONFLICT_MESSAGE_SIZE]; - bool formatted = - client_cohort_status == CBM_VERSION_COHORT_CONFLICT && - cbm_daemon_conflict_format(&client_cohort_conflict, message, sizeof(message)); - char remedy[CBM_DAEMON_CONFLICT_REMEDY_SIZE] = ""; - if (client_cohort_status == CBM_VERSION_COHORT_CONFLICT) { - (void)cbm_version_cohort_log_conflict(&client_cohort_conflict); - /* Hooks fail open on a tight budget; they skip the extra probe. */ - if (role != CBM_DAEMON_PROCESS_HOOK_CLIENT) { - main_conflict_remedy_probe(endpoint, &identity, NULL, remedy, sizeof(remedy)); - } - } - (void)fprintf(stderr, "codebase-memory-mcp: %s%s%s\n", - formatted ? message : "client exact-build admission failed", - remedy[0] ? " " : "", remedy); + main_report_cohort_failure(endpoint, &identity, client_cohort_status, + &client_cohort_conflict, "client exact-build admission failed", + role != CBM_DAEMON_PROCESS_HOOK_CLIENT); if (role == CBM_DAEMON_PROCESS_HOOK_CLIENT && client_cohort_status == CBM_VERSION_COHORT_CONFLICT) { main_hook_report_conflicted_daemon(hook_dialect); diff --git a/tests/test_daemon_runtime.c b/tests/test_daemon_runtime.c index c34c45f5b..3d72a88e8 100644 --- a/tests/test_daemon_runtime.c +++ b/tests/test_daemon_runtime.c @@ -14,6 +14,7 @@ #include "daemon/host_internal.h" #include "daemon/ipc.h" #include "daemon/runtime.h" +#include "daemon/runtime_status_details_internal.h" #include "daemon/service.h" #include "daemon/version_cohort.h" #include "foundation/compat.h" @@ -1272,6 +1273,7 @@ static bool runtime_test_fixture_start_failed(const char *tag, const char *stage } static bool runtime_test_fixture_permanent = false; +static const char *runtime_test_fixture_cache_directory; typedef struct { cbm_version_cohort_manager_t *manager; @@ -1329,6 +1331,7 @@ static bool runtime_test_fixture_start_configured( cbm_daemon_runtime_service_config_t config = { .endpoint = fixture->endpoint, .identity = *identity, + .cache_directory = runtime_test_fixture_cache_directory, .conflict_log_path = fixture->log_path, .conflict_log_cap_bytes = 64U * 1024U, .max_clients = max_clients, @@ -5512,6 +5515,307 @@ TEST(daemon_runtime_close_begin_releases_admission_with_inflight_request) { PASS(); } +TEST(daemon_runtime_status_details_preserves_long_paths_and_owns_copy) { + const size_t lengths[] = {259, 260, 261, 4095}; + cbm_daemon_build_identity_t identity = + runtime_test_identity("2.4.0", runtime_test_self_build()); + for (size_t i = 0; i < sizeof(lengths) / sizeof(lengths[0]); i++) { + char cache[4096] = {0}; + const char prefix[] = "C:/cache-中文 space/line\nbreak\t\"\\"; + memcpy(cache, prefix, sizeof(prefix) - 1); + memset(cache + sizeof(prefix) - 1, 'x', lengths[i] - sizeof(prefix) + 1); + cache[lengths[i]] = '\0'; + char expected[4096]; + memcpy(expected, cache, sizeof(cache)); + runtime_test_fixture_t fixture; + runtime_test_fixture_permanent = true; + runtime_test_fixture_cache_directory = cache; + bool started = runtime_test_fixture_start(&fixture, "status-path", &identity); + runtime_test_fixture_cache_directory = NULL; + runtime_test_fixture_permanent = false; + memset(cache, 'z', lengths[i]); /* must not change the service's path */ + cbm_daemon_runtime_status_details_t details = {0}; + cbm_daemon_runtime_status_t legacy = {0}; + bool queried = + started && cbm_daemon_runtime_request_status_details(fixture.endpoint, &identity, + RUNTIME_TEST_TIMEOUT_MS, &details); + bool legacy_ok = + started && cbm_daemon_runtime_request_status(fixture.endpoint, &identity, + RUNTIME_TEST_TIMEOUT_MS, &legacy); + size_t admitted = started ? cbm_daemon_runtime_service_active_clients(fixture.service) : 1; + runtime_test_fixture_finish(&fixture); + ASSERT_TRUE(started); + ASSERT_TRUE(queried); + ASSERT_STR_EQ(details.cache_directory, expected); + ASSERT_TRUE(legacy_ok); + ASSERT_EQ(details.status.daemon_pid, legacy.daemon_pid); + ASSERT_EQ(admitted, 0); + } + PASS(); +} + +TEST(daemon_runtime_status_details_does_not_disclose_paths_to_forged_peers) { + cbm_daemon_build_identity_t identity = + runtime_test_identity("2.4.0", runtime_test_self_build()); + runtime_test_fixture_t fixture; + runtime_test_fixture_permanent = true; + runtime_test_fixture_cache_directory = "C:/private cache"; + bool started = runtime_test_fixture_start(&fixture, "status-auth", &identity); + runtime_test_fixture_cache_directory = NULL; + runtime_test_fixture_permanent = false; + bool rejected = started; + for (uint32_t length = 64; started && length <= 65; length++) { + cbm_daemon_ipc_connection_t *connection = + cbm_daemon_ipc_connect(fixture.endpoint, RUNTIME_TEST_TIMEOUT_MS); + bool sent = connection && cbm_daemon_ipc_send_frame(connection, CBM_DAEMON_FRAME_REQUEST, + CBM_DAEMON_RUNTIME_OP_STATUS_DETAILS, + RUNTIME_BUILD_B, length); + cbm_daemon_frame_t frame = {0}; + uint8_t *payload = NULL; + int received = sent ? cbm_daemon_ipc_receive_frame(connection, RUNTIME_TEST_TIMEOUT_MS, + &frame, &payload) + : 0; + rejected = rejected && received == 1 && frame.length == 4217 && payload; + for (uint32_t byte = 0; payload && byte < frame.length; byte++) { + rejected = rejected && payload[byte] == 0; + } + free(payload); + cbm_daemon_ipc_connection_close(connection); + } + runtime_test_fixture_finish(&fixture); + ASSERT_TRUE(started); + ASSERT_TRUE(rejected); + PASS(); +} + +typedef struct { + cbm_daemon_ipc_listener_t *listener; + bool malformed_details; + bool served; +} runtime_legacy_status_t; + +static void *runtime_test_legacy_status_thread(void *opaque) { + runtime_legacy_status_t *server = opaque; + for (size_t attempt = 0; attempt < 2; attempt++) { + cbm_daemon_ipc_connection_t *connection = NULL; + if (cbm_daemon_ipc_accept(server->listener, RUNTIME_TEST_TIMEOUT_MS, &connection) != 1) { + return NULL; + } + cbm_daemon_frame_t frame = {0}; + uint8_t *payload = NULL; + int received = + cbm_daemon_ipc_receive_frame(connection, RUNTIME_TEST_TIMEOUT_MS, &frame, &payload); + if (received == 1 && frame.length == 65) { + if (attempt == 0 && server->malformed_details) { + uint8_t malformed[4217]; + memset(malformed, 'x', sizeof(malformed)); /* no path terminator */ + malformed[0] = 1; + (void)cbm_daemon_ipc_send_frame(connection, CBM_DAEMON_FRAME_RESPONSE, 12, + malformed, sizeof(malformed)); + } else if (attempt == 1 && frame.flags == 10) { + uint8_t legacy[121] = {1}; /* frozen legacy STATUS envelope */ + runtime_test_put_u32(legacy + 4, 77); + server->served = cbm_daemon_ipc_send_frame(connection, CBM_DAEMON_FRAME_RESPONSE, + 10, legacy, sizeof(legacy)); + } + } + free(payload); + cbm_daemon_ipc_connection_close(connection); + } + return NULL; +} + +/* An opaque token replaces IPC; only the scripted clock advances. Scheduler + * delays cannot consume the test budget or decide its result. */ +typedef struct { + uint64_t now; + uint32_t connect_cost[2], send_cost[2], receive_cost[2]; + uint32_t connect_budget[2], receive_budget[2]; + unsigned connects, sends, receives, closes; + int first_reply; /* 0 = unsupported, 1 = malformed, 2 = supported */ + bool valid; +} runtime_status_transport_stub_t; +static runtime_status_transport_stub_t runtime_status_stub; + +static uint64_t runtime_test_status_now(void) { + return runtime_status_stub.now; +} +static cbm_daemon_ipc_connection_t *runtime_test_status_connect( + const cbm_daemon_ipc_endpoint_t *endpoint, uint32_t timeout) { + runtime_status_transport_stub_t *stub = &runtime_status_stub; + if (stub->connects >= 2) { + stub->valid = false; + return NULL; + } + unsigned attempt = stub->connects++; + stub->valid &= endpoint == (const void *)stub; + stub->connect_budget[attempt] = timeout; + stub->now += stub->connect_cost[attempt]; + return (void *)stub; +} +static bool runtime_test_status_send(cbm_daemon_ipc_connection_t *connection, + cbm_daemon_frame_type_t type, uint16_t flags, + const void *payload, uint32_t length) { + runtime_status_transport_stub_t *stub = &runtime_status_stub; + unsigned attempt = stub->connects - 1; + stub->valid &= connection == (void *)stub && type == CBM_DAEMON_FRAME_REQUEST && + flags == (attempt == 0 ? CBM_DAEMON_RUNTIME_OP_STATUS_DETAILS + : CBM_DAEMON_RUNTIME_OP_STATUS) && + payload && length == CBM_DAEMON_CONTROL_REQUEST_SIZE; + stub->sends++; + stub->now += stub->send_cost[attempt]; + return true; +} +static int runtime_test_status_receive(cbm_daemon_ipc_connection_t *connection, uint32_t timeout, + uint32_t cap, cbm_daemon_frame_t *frame, uint8_t **payload) { + runtime_status_transport_stub_t *stub = &runtime_status_stub; + unsigned attempt = stub->connects - 1; + stub->valid &= + connection == (void *)stub && cap == (attempt == 0 ? CBM_DAEMON_STATUS_DETAILS_RESPONSE_SIZE + : CBM_DAEMON_STATUS_RESPONSE_SIZE); + stub->receives++; + stub->receive_budget[attempt] = timeout; + *payload = NULL; + if (stub->receive_cost[attempt] >= timeout) { + stub->now += timeout; + return 0; + } + stub->now += stub->receive_cost[attempt]; + if (attempt == 0 && stub->first_reply == 0) + return 0; + *payload = calloc(cap, 1); + if (!*payload) + return -1; + (*payload)[0] = 1; + runtime_test_put_u32(*payload + 4, 77); + if (attempt == 0) { + memset(*payload + CBM_DAEMON_STATUS_RESPONSE_SIZE, stub->first_reply == 1 ? 'x' : 0, + CBM_DAEMON_STATUS_CACHE_PATH_SIZE); + } + frame->type = CBM_DAEMON_FRAME_RESPONSE; + frame->flags = + attempt == 0 ? CBM_DAEMON_RUNTIME_OP_STATUS_DETAILS : CBM_DAEMON_RUNTIME_OP_STATUS; + frame->length = cap; + return 1; +} +static void runtime_test_status_close(cbm_daemon_ipc_connection_t *connection) { + runtime_status_stub.valid &= connection == (void *)&runtime_status_stub; + runtime_status_stub.closes++; +} +static const cbm_daemon_status_details_transport_t runtime_test_status_transport = { + .now_ms = runtime_test_status_now, + .ipc_connect = runtime_test_status_connect, + .send = runtime_test_status_send, + .receive = runtime_test_status_receive, + .close = runtime_test_status_close, +}; + +TEST(daemon_runtime_status_details_uses_one_budget_across_legacy_fallback) { + cbm_daemon_build_identity_t identity = runtime_test_identity("2.4.0", RUNTIME_BUILD_B); + for (int reply = 0; reply < 3; reply++) { + runtime_status_stub = (runtime_status_transport_stub_t){ + .now = 10000, + .connect_cost = {100, 200}, + .send_cost = {20, 30}, + .receive_cost = {200, 300}, + .first_reply = reply, + .valid = true, + }; + cbm_daemon_runtime_status_details_t details = {0}; + cbm_daemon_runtime_set_status_details_transport_for_testing(&runtime_test_status_transport); + bool queried = cbm_daemon_runtime_request_status_details((const void *)&runtime_status_stub, + &identity, 1000, &details); + cbm_daemon_runtime_set_status_details_transport_for_testing(NULL); + ASSERT_TRUE(queried && runtime_status_stub.valid); + ASSERT_EQ(details.status.daemon_pid, 77); + ASSERT_EQ(runtime_status_stub.connect_budget[0], 1000); + ASSERT_EQ(runtime_status_stub.receive_budget[0], 880); + ASSERT_EQ(runtime_status_stub.connects, reply == 2 ? 1 : 2); + ASSERT_EQ(runtime_status_stub.closes, runtime_status_stub.connects); + if (reply != 2) { + ASSERT_EQ(runtime_status_stub.connect_budget[1], 680); + ASSERT_EQ(runtime_status_stub.receive_budget[1], 450); + ASSERT_EQ(details.cache_directory[0], '\0'); + } + } + PASS(); +} + +TEST(daemon_runtime_status_details_stops_when_budget_expires) { + cbm_daemon_build_identity_t identity = runtime_test_identity("2.4.0", RUNTIME_BUILD_B); + for (int stage = 0; stage < 4; stage++) { + runtime_status_stub = (runtime_status_transport_stub_t){.now = 10000, .valid = true}; + if (stage == 0) + runtime_status_stub.connect_cost[0] = 1000; + else if (stage == 1) + runtime_status_stub.send_cost[0] = 1000; + else if (stage == 2) + runtime_status_stub.receive_cost[0] = 1000; + else { + runtime_status_stub.receive_cost[0] = 400; + runtime_status_stub.connect_cost[1] = 600; + } + cbm_daemon_runtime_status_details_t details = {0}; + cbm_daemon_runtime_set_status_details_transport_for_testing(&runtime_test_status_transport); + bool queried = cbm_daemon_runtime_request_status_details((const void *)&runtime_status_stub, + &identity, 1000, &details); + cbm_daemon_runtime_set_status_details_transport_for_testing(NULL); + ASSERT_FALSE(queried); + ASSERT_TRUE(runtime_status_stub.valid); + ASSERT_EQ(runtime_status_stub.now, 11000); + ASSERT_EQ(runtime_status_stub.connects, stage == 3 ? 2 : 1); + ASSERT_EQ(runtime_status_stub.closes, runtime_status_stub.connects); + ASSERT_EQ(runtime_status_stub.sends, stage == 0 ? 0 : 1); + ASSERT_EQ(runtime_status_stub.receives, stage < 2 ? 0 : 1); + if (stage == 3) + ASSERT_EQ(runtime_status_stub.connect_budget[1], 600); + } + PASS(); +} + +TEST(daemon_runtime_status_details_falls_back_to_legacy_on_unsupported_or_malformed_reply) { + cbm_daemon_build_identity_t identity = + runtime_test_identity("2.4.0", runtime_test_self_build()); + for (int malformed = 0; malformed < 2; malformed++) { + char parent[RUNTIME_TEST_PATH_CAP] = {0}; + char key[CBM_DAEMON_KEY_SIZE] = {0}; + char runtime_dir[RUNTIME_TEST_PATH_CAP] = {0}; + bool prepared = th_secure_runtime_parent_new(parent, sizeof(parent), "status-legacy") && + cbm_daemon_rendezvous_key(key); + cbm_daemon_ipc_endpoint_t *endpoint = + prepared ? cbm_daemon_ipc_endpoint_new(key, parent) : NULL; + bool copied = endpoint && runtime_test_copy_path( + runtime_dir, cbm_daemon_ipc_endpoint_runtime_dir(endpoint)); + runtime_legacy_status_t server = { + .listener = endpoint ? cbm_daemon_ipc_listen(endpoint) : NULL, + .malformed_details = malformed != 0, + }; + cbm_thread_t thread; + bool started = + server.listener && + cbm_thread_create(&thread, 0, runtime_test_legacy_status_thread, &server) == 0; + cbm_daemon_runtime_status_details_t details = {0}; + bool queried = started && cbm_daemon_runtime_request_status_details( + endpoint, &identity, RUNTIME_TEST_TIMEOUT_MS, &details); + if (started) { + (void)cbm_thread_join(&thread); + } + cbm_daemon_ipc_listener_close(server.listener); + cbm_daemon_ipc_endpoint_free(endpoint); + (void)cbm_rmdir(runtime_dir); + (void)cbm_rmdir(parent); + ASSERT_TRUE(prepared); + ASSERT_TRUE(copied); + ASSERT_TRUE(started); + ASSERT_TRUE(queried); + ASSERT_TRUE(server.served); + ASSERT_EQ(details.status.daemon_pid, 77); + ASSERT_EQ(details.cache_directory[0], '\0'); + ASSERT_EQ(details.status.muted_endpoint_holder_pid, 0); + } + PASS(); +} + TEST(daemon_runtime_permanent_service_survives_last_disconnect_until_stop) { cbm_daemon_build_identity_t identity = runtime_test_identity("2.4.0", runtime_test_self_build()); @@ -5598,6 +5902,11 @@ TEST(daemon_runtime_stop_refuses_while_committed_clients_exist) { } SUITE(daemon_runtime) { + RUN_TEST(daemon_runtime_status_details_uses_one_budget_across_legacy_fallback); + RUN_TEST(daemon_runtime_status_details_stops_when_budget_expires); + RUN_TEST(daemon_runtime_status_details_preserves_long_paths_and_owns_copy); + RUN_TEST(daemon_runtime_status_details_does_not_disclose_paths_to_forged_peers); + RUN_TEST(daemon_runtime_status_details_falls_back_to_legacy_on_unsupported_or_malformed_reply); RUN_TEST(daemon_runtime_permanent_service_survives_last_disconnect_until_stop); RUN_TEST(daemon_runtime_stop_refuses_while_committed_clients_exist); RUN_TEST(daemon_host_early_coordination_failure_is_durable); diff --git a/tests/test_daemon_smoke.py b/tests/test_daemon_smoke.py index 93ab933a4..57aa14619 100644 --- a/tests/test_daemon_smoke.py +++ b/tests/test_daemon_smoke.py @@ -973,6 +973,16 @@ def main(): "cache-root conflict did not emit visible remediation guidance: " + repr(mismatched_result.stderr), ) + check( + "requested cache: " + + json.dumps(str(mismatched_cache.resolve()), ensure_ascii=False) + in mismatched_result.stderr + and "daemon cache: " + + json.dumps(str(cache.resolve()), ensure_ascii=False) + in mismatched_result.stderr, + "cache-root conflict did not name both canonical paths: " + + repr(mismatched_result.stderr), + ) wait_until( lambda: any( item.get("reason") == "cache_root" diff --git a/tests/test_runtime_settings.c b/tests/test_runtime_settings.c index 28e8651d3..c20c87b62 100644 --- a/tests/test_runtime_settings.c +++ b/tests/test_runtime_settings.c @@ -626,7 +626,64 @@ TEST(runtime_settings_ui_load_recovers_a_hot_journal) { PASS(); } +#ifdef _WIN32 +TEST(runtime_settings_windows_long_cache_reads_and_writes_config) { + settings_fixture_t fixture; + ASSERT_TRUE(fixture_open(&fixture)); + const size_t lengths[] = {259, 260, 261, 1024}; + bool ok = true; + for (size_t i = 0; i < sizeof(lengths) / sizeof(lengths[0]) && ok; i++) { + char cache[1100]; + size_t base = strlen(fixture.path); + memcpy(cache, fixture.path, base + 1); + size_t used = base; + while (used < lengths[i]) { + size_t remaining = lengths[i] - used; + if (remaining == 1) { + cache[used++] = 'x'; + } else { + cache[used++] = '/'; + size_t part = remaining - 1 < 32 ? remaining - 1 : 32; + memset(cache + used, 'x', part); + used += part; + } + cache[used] = '\0'; + } + ok = cbm_mkdir_p(cache, 0700); + cbm_config_t *config = ok ? cbm_config_open(cache) : NULL; + ok = config && cbm_config_set(config, "auto_index", "true") == 0; + if (config) + cbm_config_close(config); + ok = ok && cbm_runtime_settings_init(cache); + yyjson_doc *document = ok ? read_snapshot(cache) : NULL; + yyjson_val *setting = document ? item(document, "auto_index") : NULL; + const char *value = setting ? yyjson_get_str(yyjson_obj_get(setting, "value")) : NULL; + ok = ok && value && strcmp(value, "true") == 0; + if (document) + yyjson_doc_free(document); + cbm_runtime_settings_reset_for_tests(); + char db[1120]; + snprintf(db, sizeof(db), "%s/_config.db", cache); + (void)cbm_remove_db_sidecars(db); + (void)cbm_unlink(db); + while (strlen(cache) > base) { + (void)cbm_rmdir(cache); + char *slash = strrchr(cache, '/'); + if (!slash || (size_t)(slash - cache) < base) + break; + *slash = '\0'; + } + } + fixture_close(&fixture); + ASSERT_TRUE(ok); + PASS(); +} +#endif + SUITE(runtime_settings) { +#ifdef _WIN32 + RUN_TEST(runtime_settings_windows_long_cache_reads_and_writes_config); +#endif RUN_TEST(runtime_settings_startup_recovers_a_hot_journal); RUN_TEST(runtime_settings_ui_load_recovers_a_hot_journal); RUN_TEST(runtime_settings_startup_waits_out_a_committing_writer); diff --git a/tests/windows/test_daemon_lifecycle.py b/tests/windows/test_daemon_lifecycle.py index c16abb044..bba609b23 100644 --- a/tests/windows/test_daemon_lifecycle.py +++ b/tests/windows/test_daemon_lifecycle.py @@ -9,6 +9,7 @@ * A cold one-shot ``cli`` command is quiet by default; ``cli --verbose`` opts into the startup-tax hint. * ``daemon stop`` on an idle daemon stops it; a second ``stop`` is idempotent. +* Cache mismatches name both canonical paths, including long Windows paths. Every path carries a kill-by-pid backstop so a stuck daemon can never hang the suite (the Windows leg's test-infra hang sensitivity is on record). @@ -18,6 +19,7 @@ Usage: python test_daemon_lifecycle.py """ +import json import os import re import subprocess @@ -40,9 +42,10 @@ def run_cli(binary, cache, args, timeout=60, extra_env=None): # Daemon coordination is account-wide and CBM_CACHE_DIR does not move the # rendezvous; a private CBM_RUNTIME_DIR per cache is what isolates a call # from every other daemon on the account (and makes a cold call cold). - env["CBM_RUNTIME_DIR"] = runtime_for(cache) if extra_env: env.update(extra_env) + if not extra_env or "CBM_RUNTIME_DIR" not in extra_env: + env["CBM_RUNTIME_DIR"] = runtime_for(cache) return subprocess.run([binary] + args, capture_output=True, timeout=timeout, env=env) @@ -59,6 +62,63 @@ def force_kill(pid): subprocess.run(["kill", "-9", str(pid)], capture_output=True, timeout=30) +def check_cache_conflict_paths(binary, cache, work): + def filesystem_path(path): + # Exercise CBM's own long-path support regardless of the runner's + # LongPathsEnabled policy; Python setup/inspection uses explicit Win32 paths. + if os.name == "nt": + absolute = os.path.abspath(path) + return "\\\\?\\UNC\\" + absolute[2:] if absolute.startswith("\\\\") else "\\\\?\\" + absolute + return path + + # Cache roots must share a rendezvous, or the mismatch would never occur. + shared_runtime = {"CBM_RUNTIME_DIR": runtime_for(cache), "CBM_STARTUP_TIMEOUT_MS": "1000"} + paths = [os.path.join(work, "cache-中文 space")] + for length in (259, 260, 261, 1024): + path = os.path.join(work, "cache-length-%d" % length) + while len(path) < length: + remaining = length - len(path) + if remaining == 1: + path += "x" + else: + path = os.path.join(path, "x" * min(32, remaining - 1)) + paths.append(path) + + for requested in paths: + os.makedirs(filesystem_path(requested), exist_ok=True) + for args in (["cli", "list_projects"], []): # [] enters the MCP frontend + result = run_cli(binary, requested, args, extra_env=shared_runtime) + text = output_text(result) + if result.returncode == 0: + raise AssertionError("different cache root unexpectedly admitted") + for label, path in (("requested cache", requested), ("daemon cache", cache)): + canonical = os.path.realpath(filesystem_path(path)).replace("\\", "/") + if canonical.startswith("//?/UNC/"): + canonical = "//" + canonical[8:] + elif canonical.startswith("//?/"): + canonical = canonical[4:] + expected = label + ": " + json.dumps(canonical, ensure_ascii=False) + if expected not in text: + raise AssertionError("missing complete escaped cache path %r in %r" + % (expected, text)) + if "different cache directory" not in text or "CBM_CACHE_DIR" not in text: + raise AssertionError("cache mismatch lost its explanation or remedy") + if "Cache paths unavailable or unverified." in text: + raise AssertionError("resolved paths were incorrectly marked unavailable") + log = os.path.join(requested, "logs", "daemon-conflicts.ndjson") + with open(filesystem_path(log), encoding="utf-8") as stream: + events = [json.loads(line) for line in stream if line.strip()] + if not any(event.get("reason") == "cache_root" for event in events): + raise AssertionError("cache mismatch was not recorded") + for event in events: + for key in ("active_cache", "requested_cache"): + if not re.fullmatch(r"[0-9a-f]{64}", event.get(key, "")): + raise AssertionError("conflict log must retain cache fingerprints") + healthy = run_cli(binary, cache, ["cli", "list_projects"]) + if healthy.returncode != 0: + raise AssertionError("cache rejection disturbed the active daemon") + + def main(): if len(sys.argv) < 2: print("usage: python test_daemon_lifecycle.py ") @@ -126,6 +186,9 @@ def main(): return 1 print("PASS: warm cli recycled the daemon; daemon survived its client") + check_cache_conflict_paths(binary, cache, work) + print("PASS: cache mismatch paths survive Unicode, escaping and long paths") + stop = run_cli(binary, cache, ["daemon", "stop"]) if stop.returncode != 0: print("RED: `daemon stop` on an idle daemon failed:\n%s"