| 207 | |
| 208 | #ifdef _WIN32 |
| 209 | int cbm_mkstemp(char *tmpl) { |
| 210 | /* Rewrite /tmp/ to %TEMP%\ like cbm_mkdtemp */ |
| 211 | /* Per-call storage: daemon project workers can create staging files |
| 212 | * concurrently, so a process-global scratch buffer is a data race. */ |
| 213 | char buf[CBM_SZ_4K]; |
| 214 | int written; |
| 215 | if (strncmp(tmpl, "/tmp/", 5) == 0) { |
| 216 | const char *tmp = getenv("TEMP"); |
| 217 | if (!tmp) |
| 218 | tmp = getenv("TMP"); |
| 219 | if (!tmp) |
| 220 | tmp = "."; |
| 221 | written = snprintf(buf, sizeof(buf), "%s\\%s", tmp, tmpl + 5); |
| 222 | } else { |
| 223 | written = snprintf(buf, sizeof(buf), "%s", tmpl); |
| 224 | } |
| 225 | if (written < 0 || (size_t)written >= sizeof(buf)) { |
| 226 | errno = ENAMETOOLONG; |
| 227 | return CBM_NOT_FOUND; |
| 228 | } |
| 229 | /* Wide-API expansion and open: worker staging files land inside |
| 230 | * CBM_CACHE_DIR, which users may place at non-ASCII paths; the ANSI CRT |
| 231 | * (_mktemp/_open) mangles those bytes in the local codepage. */ |
| 232 | wchar_t *wide_template = cbm_utf8_to_wide(buf); |
| 233 | if (!wide_template || !_wmktemp(wide_template)) { |
| 234 | free(wide_template); |
| 235 | return CBM_NOT_FOUND; |
| 236 | } |
| 237 | char *expanded_for_open = cbm_wide_to_utf8(wide_template); |
| 238 | wchar_t *wide_open = expanded_for_open ? cbm_path_to_wide(expanded_for_open) : NULL; |
| 239 | free(expanded_for_open); |
| 240 | if (!wide_open) { |
| 241 | free(wide_template); |
| 242 | return CBM_NOT_FOUND; |
| 243 | } |
| 244 | int fd = _wopen(wide_open, _O_CREAT | _O_EXCL | _O_RDWR | _O_BINARY, _S_IREAD | _S_IWRITE); |
| 245 | free(wide_open); |
| 246 | if (fd >= 0) { |
| 247 | char *expanded = cbm_wide_to_utf8(wide_template); |
| 248 | if (!expanded || strlen(expanded) >= sizeof(buf)) { |
| 249 | free(expanded); |
| 250 | free(wide_template); |
| 251 | (void)_close(fd); |
| 252 | return CBM_NOT_FOUND; |
| 253 | } |
| 254 | strcpy(tmpl, expanded); |
| 255 | free(expanded); |
| 256 | } |
| 257 | free(wide_template); |
| 258 | return fd; |
| 259 | } |
| 260 | #endif |
| 261 | |
| 262 | /* ── clock_gettime (Windows lacks it) ─────────────────────────── */ |