| 250 | |
| 251 | #ifdef _WIN32 |
| 252 | int cbm_mkstemp(char *tmpl) { |
| 253 | /* Rewrite /tmp/ to %TEMP%\ like cbm_mkdtemp */ |
| 254 | /* Per-call storage: daemon project workers can create staging files |
| 255 | * concurrently, so a process-global scratch buffer is a data race. */ |
| 256 | char buf[CBM_SZ_4K]; |
| 257 | int written; |
| 258 | if (strncmp(tmpl, "/tmp/", 5) == 0) { |
| 259 | const char *tmp = getenv("TEMP"); |
| 260 | if (!tmp) |
| 261 | tmp = getenv("TMP"); |
| 262 | if (!tmp) |
| 263 | tmp = "."; |
| 264 | written = snprintf(buf, sizeof(buf), "%s\\%s", tmp, tmpl + 5); |
| 265 | } else { |
| 266 | written = snprintf(buf, sizeof(buf), "%s", tmpl); |
| 267 | } |
| 268 | if (written < 0 || (size_t)written >= sizeof(buf)) { |
| 269 | errno = ENAMETOOLONG; |
| 270 | return CBM_NOT_FOUND; |
| 271 | } |
| 272 | /* Wide-API expansion and open: worker staging files land inside |
| 273 | * CBM_CACHE_DIR, which users may place at non-ASCII paths; the ANSI CRT |
| 274 | * (_mktemp/_open) mangles those bytes in the local codepage. */ |
| 275 | wchar_t *wide_template = cbm_utf8_to_wide(buf); |
| 276 | if (!wide_template || !_wmktemp(wide_template)) { |
| 277 | free(wide_template); |
| 278 | return CBM_NOT_FOUND; |
| 279 | } |
| 280 | char *expanded_for_open = cbm_wide_to_utf8(wide_template); |
| 281 | wchar_t *wide_open = expanded_for_open ? cbm_path_to_wide(expanded_for_open) : NULL; |
| 282 | free(expanded_for_open); |
| 283 | if (!wide_open) { |
| 284 | free(wide_template); |
| 285 | return CBM_NOT_FOUND; |
| 286 | } |
| 287 | int fd = _wopen(wide_open, _O_CREAT | _O_EXCL | _O_RDWR | _O_BINARY, _S_IREAD | _S_IWRITE); |
| 288 | free(wide_open); |
| 289 | if (fd >= 0) { |
| 290 | char *expanded = cbm_wide_to_utf8(wide_template); |
| 291 | if (!expanded || strlen(expanded) >= sizeof(buf)) { |
| 292 | free(expanded); |
| 293 | free(wide_template); |
| 294 | (void)_close(fd); |
| 295 | return CBM_NOT_FOUND; |
| 296 | } |
| 297 | strcpy(tmpl, expanded); |
| 298 | free(expanded); |
| 299 | } |
| 300 | free(wide_template); |
| 301 | return fd; |
| 302 | } |
| 303 | #endif |
| 304 | |
| 305 | /* ── clock_gettime (Windows lacks it) ─────────────────────────── */ |