Skip to content

Commit 9c97162

Browse files
authored
Merge pull request DeusData#1606 from ertankucukoglu/fix/search-temp-isolation
fix(platform): isolate concurrent temporary directories
2 parents fec1022 + d0cc55e commit 9c97162

2 files changed

Lines changed: 132 additions & 29 deletions

File tree

‎src/foundation/compat.c‎

Lines changed: 58 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
*/
77
#include "foundation/compat.h"
88
#include "foundation/constants.h"
9+
#include "foundation/secure_random.h"
910

1011
#include <errno.h>
1112
#include <stdlib.h>
@@ -114,52 +115,80 @@ static bool win_mkdtemp_private_create(const char *path) {
114115
}
115116

116117
char *cbm_mkdtemp(char *tmpl) {
117-
/* Build path in static buffer, then copy back to caller.
118-
* Callers must provide buffers >= CBM_SZ_256 bytes (all test code does). */
119-
static char buf[CBM_SZ_512];
118+
/* Per-call storage is required: daemon sessions invoke mkdtemp concurrently.
119+
* A process-global buffer lets one request overwrite another request's path
120+
* between expansion, creation, and the copy back to its caller. */
121+
char buf[CBM_SZ_512];
122+
int written;
120123
if (strncmp(tmpl, "/tmp/", 5) == 0) {
121124
const char *tmp = getenv("TEMP");
122125
if (!tmp)
123126
tmp = getenv("TMP");
124127
if (!tmp)
125128
tmp = ".";
126-
snprintf(buf, sizeof(buf), "%s\\%s", tmp, tmpl + 5);
129+
written = snprintf(buf, sizeof(buf), "%s\\%s", tmp, tmpl + 5);
127130
} else {
128-
snprintf(buf, sizeof(buf), "%s", tmpl);
131+
written = snprintf(buf, sizeof(buf), "%s", tmpl);
129132
}
130-
/* Wide-API template expansion: the ANSI CRT interprets the UTF-8 bytes of
131-
* non-ASCII cache/temp components in the local codepage and fails. */
132-
wchar_t *wide_template = cbm_utf8_to_wide(buf);
133-
if (!wide_template || !_wmktemp(wide_template)) {
134-
free(wide_template);
133+
if (written < 0 || (size_t)written >= sizeof(buf)) {
134+
errno = ENAMETOOLONG;
135135
return NULL;
136136
}
137-
char *expanded = cbm_wide_to_utf8(wide_template);
138-
free(wide_template);
139-
if (!expanded || strlen(expanded) >= sizeof(buf)) {
140-
free(expanded);
137+
138+
size_t length = strlen(buf);
139+
if (length < 6 || strcmp(buf + length - 6, "XXXXXX") != 0) {
140+
errno = EINVAL;
141141
return NULL;
142142
}
143-
strcpy(buf, expanded);
144-
free(expanded);
145-
if (!win_mkdtemp_private_create(buf)) {
146-
/* One-time note: every private-namespace validation downstream
147-
* depends on the explicit descriptor, so a silent fallback turns
148-
* into unexplained owner/DACL refusals far from this call site. */
149-
static bool fallback_reported;
143+
144+
static const char alphabet[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
145+
bool created = false;
146+
for (int attempt = 0; attempt < 128; attempt++) {
147+
unsigned char random_suffix[6];
148+
if (!cbm_secure_random(random_suffix, sizeof(random_suffix))) {
149+
errno = EIO;
150+
return NULL;
151+
}
152+
for (size_t index = 0; index < sizeof(random_suffix); index++) {
153+
buf[length - sizeof(random_suffix) + index] =
154+
alphabet[random_suffix[index] % (sizeof(alphabet) - 1)];
155+
}
156+
157+
if (win_mkdtemp_private_create(buf)) {
158+
created = true;
159+
break;
160+
}
161+
162+
/* Keep the existing compatibility fallback when an explicit private
163+
* descriptor is unavailable. A name collision is retried; any other
164+
* filesystem refusal is returned to the caller immediately. */
150165
DWORD create_error = GetLastError();
151166
wchar_t *wide_directory = cbm_utf8_to_wide(buf);
167+
errno = 0;
152168
int mkdir_result = wide_directory ? _wmkdir(wide_directory) : -1;
169+
int mkdir_error = errno;
153170
free(wide_directory);
154-
if (mkdir_result != 0)
155-
return NULL;
156-
if (!fallback_reported) {
157-
fallback_reported = true;
158-
(void)fprintf(stderr,
159-
"warning: private temp-directory descriptor unavailable "
160-
"(os %lu); using default directory security\n",
161-
(unsigned long)create_error);
171+
if (mkdir_result == 0) {
172+
static volatile LONG fallback_reported;
173+
if (InterlockedCompareExchange(&fallback_reported, 1, 0) == 0) {
174+
(void)fprintf(stderr,
175+
"warning: private temp-directory descriptor unavailable "
176+
"(os %lu); using default directory security\n",
177+
(unsigned long)create_error);
178+
}
179+
created = true;
180+
break;
181+
}
182+
if (create_error == ERROR_ALREADY_EXISTS || create_error == ERROR_FILE_EXISTS ||
183+
mkdir_error == EEXIST) {
184+
continue;
162185
}
186+
errno = mkdir_error != 0 ? mkdir_error : EACCES;
187+
return NULL;
188+
}
189+
if (!created) {
190+
errno = EEXIST;
191+
return NULL;
163192
}
164193
/* Normalize to forward slashes. Callers embed this path in JSON repo_path
165194
* (where "\t"/"\a" are invalid escapes → index fails) and pass it to git -C.

‎tests/test_platform.c‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
#endif
2525

2626
enum { PLATFORM_TIME_THREADS = 8 };
27+
enum { PLATFORM_MKDTEMP_THREADS = 8, PLATFORM_MKDTEMP_ITERATIONS = 32 };
2728

2829
#include <stdio.h>
2930
#include <string.h>
@@ -102,6 +103,78 @@ TEST(platform_mkstemp_and_mkdtemp_survive_non_ascii_directory) {
102103
PASS();
103104
}
104105

106+
typedef struct {
107+
atomic_int *ready;
108+
atomic_bool *go;
109+
int worker_index;
110+
int created;
111+
bool ok;
112+
char paths[PLATFORM_MKDTEMP_ITERATIONS][CBM_SZ_512];
113+
} platform_mkdtemp_worker_t;
114+
115+
static void *platform_mkdtemp_concurrent_worker(void *opaque) {
116+
platform_mkdtemp_worker_t *worker = opaque;
117+
(void)atomic_fetch_add_explicit(worker->ready, 1, memory_order_acq_rel);
118+
while (!atomic_load_explicit(worker->go, memory_order_acquire)) {
119+
atomic_signal_fence(memory_order_seq_cst);
120+
}
121+
worker->ok = true;
122+
for (int index = 0; index < PLATFORM_MKDTEMP_ITERATIONS; index++) {
123+
int written =
124+
snprintf(worker->paths[index], sizeof(worker->paths[index]),
125+
"/tmp/cbm-mkdtemp-concurrent-%d-%d-XXXXXX", worker->worker_index, index);
126+
if (written <= 0 || written >= (int)sizeof(worker->paths[index]) ||
127+
!cbm_mkdtemp(worker->paths[index])) {
128+
worker->ok = false;
129+
break;
130+
}
131+
worker->created++;
132+
}
133+
return NULL;
134+
}
135+
136+
/* MCP daemon sessions can enter cbm_mkdtemp simultaneously. Every request must
137+
* retain its own expanded path and create a distinct directory. */
138+
TEST(platform_mkdtemp_is_thread_safe) {
139+
cbm_thread_t threads[PLATFORM_MKDTEMP_THREADS];
140+
platform_mkdtemp_worker_t workers[PLATFORM_MKDTEMP_THREADS] = {0};
141+
atomic_int ready;
142+
atomic_bool go;
143+
atomic_init(&ready, 0);
144+
atomic_init(&go, false);
145+
146+
int started = 0;
147+
for (; started < PLATFORM_MKDTEMP_THREADS; started++) {
148+
workers[started].ready = &ready;
149+
workers[started].go = &go;
150+
workers[started].worker_index = started;
151+
if (cbm_thread_create(&threads[started], 0, platform_mkdtemp_concurrent_worker,
152+
&workers[started]) != 0) {
153+
break;
154+
}
155+
}
156+
while (started == PLATFORM_MKDTEMP_THREADS &&
157+
atomic_load_explicit(&ready, memory_order_acquire) != PLATFORM_MKDTEMP_THREADS) {
158+
atomic_signal_fence(memory_order_seq_cst);
159+
}
160+
atomic_store_explicit(&go, true, memory_order_release);
161+
for (int index = 0; index < started; index++) {
162+
(void)cbm_thread_join(&threads[index]);
163+
}
164+
165+
bool all_ok = started == PLATFORM_MKDTEMP_THREADS;
166+
for (int index = 0; index < started; index++) {
167+
all_ok =
168+
all_ok && workers[index].ok && workers[index].created == PLATFORM_MKDTEMP_ITERATIONS;
169+
for (int path_index = 0; path_index < workers[index].created; path_index++) {
170+
all_ok = all_ok && cbm_is_dir(workers[index].paths[path_index]);
171+
(void)cbm_rmdir(workers[index].paths[path_index]);
172+
}
173+
}
174+
ASSERT_TRUE(all_ok);
175+
PASS();
176+
}
177+
105178
TEST(platform_counter_scaling_avoids_intermediate_overflow) {
106179
const uint64_t frequency = UINT64_C(10000000);
107180
const uint64_t counter = UINT64_C(20000000000);
@@ -613,6 +686,7 @@ TEST(cgroup_no_mem_files) {
613686
SUITE(platform) {
614687
RUN_TEST(platform_file_apis_survive_max_path_overflow);
615688
RUN_TEST(platform_mkstemp_and_mkdtemp_survive_non_ascii_directory);
689+
RUN_TEST(platform_mkdtemp_is_thread_safe);
616690
RUN_TEST(platform_counter_scaling_avoids_intermediate_overflow);
617691
RUN_TEST(platform_counter_scaling_preserves_monotonic_deadlines);
618692
RUN_TEST(platform_now_ns_concurrent_first_call);

0 commit comments

Comments
 (0)