ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
path.c
Go to the documentation of this file.
1
6
7/* Storage capacities in elements; text buffers include the terminating NUL. */
8#define UTIL_PATH_BUFFER_BUFFER_SIZE 256
9
10/* Existing buffer budgets in bytes, including NUL for text storage. */
11#define PATH_COMPONENT_BUFFER_SIZE 256
12
13#include <recast/defer.h>
16#include <ascii-chat/common.h>
18#include <libplatform/system.h>
19#include <libplatform/filesystem.h>
20#include <ascii-chat/paths.h>
21#include <ascii-chat/source_root.h>
22#include <string.h>
23#include <stdbool.h>
24#include <ctype.h>
25#include <stdlib.h>
26#include <stdio.h>
27#include <sys/stat.h>
28#include <sys/stat.h>
29
30/* Generic path primitives are provided by libplatform. */
33
34/* Normalize a path by resolving .. and . components
35 * Handles both Windows (\‍) and Unix (/) separators
36 * Returns a pointer to a thread-local buffer.
37 */
38static const char *normalize_path(const char *path) {
39 if (!path) {
40 SET_ERRNO(ERROR_INVALID_PARAM, "path is null");
41 return "unknown";
42 }
43
44 /* Use thread-local storage to avoid buffer corruption when multiple threads
45 * or rapid calls reuse the same static buffer. Each thread gets its own buffer. */
46 static _Thread_local char normalized[PLATFORM_MAX_PATH_LENGTH];
47 size_t path_len = strlen(path);
48
49 if (path_len >= PLATFORM_MAX_PATH_LENGTH) {
50 return path; /* Can't normalize, return as-is */
51 }
52
53 const char *pos = path;
54 bool absolute = path_is_absolute(path);
55 size_t out_pos = 0;
56 size_t component_count = 0;
57
58#ifdef _WIN32
59 if (absolute && path_len >= 3 && isalpha((unsigned char)path[0]) && path[1] == ':') {
60 normalized[out_pos++] = path[0];
61 normalized[out_pos++] = ':';
62 normalized[out_pos++] = PATH_DELIM;
63 }
64#else
65 if (absolute) {
66 normalized[out_pos++] = PATH_DELIM;
67 }
68#endif
69 const size_t prefix_len = out_pos;
70
71 /* Skip past the absolute path prefix if present */
72 if (absolute) {
73#ifdef _WIN32
74 if (path_len >= 3 && isalpha((unsigned char)path[0]) && path[1] == ':' && path[2] == PATH_DELIM) {
75 pos += 3; /* Skip the drive letter and colon and separator (e.g., "C:\") */
76 }
77#else
78 if (path_len >= 1 && path[0] == PATH_DELIM) {
79 pos += 1; /* Skip the root separator */
80 }
81#endif
82 }
83
84 /* Split on either path separator and resolve dot components. */
85 const char *parse_pos = pos;
86 while (*parse_pos) {
87 while (*parse_pos == '/' || *parse_pos == '\\') {
88 parse_pos++;
89 }
90 if (!*parse_pos)
91 break;
92 const char *component_start = parse_pos;
93 while (*parse_pos && *parse_pos != '/' && *parse_pos != '\\') {
94 parse_pos++;
95 }
96 size_t component_len = (size_t)(parse_pos - component_start);
97 if (component_len == 0)
98 continue;
99 if (component_len >= PATH_COMPONENT_BUFFER_SIZE) {
100 component_len = PATH_COMPONENT_BUFFER_SIZE - 1;
101 }
102 if (component_len == 1 && component_start[0] == PATH_COMPONENT_DOT) {
103 continue;
104 }
105 if (component_len == 2 && component_start[0] == PATH_COMPONENT_DOT && component_start[1] == PATH_COMPONENT_DOT) {
106 if (component_count > 0) {
107 while (out_pos > prefix_len && normalized[out_pos - 1] != PATH_DELIM)
108 --out_pos;
109 if (out_pos > prefix_len)
110 --out_pos;
111 component_count--;
112 continue;
113 }
114 if (absolute)
115 continue;
116 }
117 if (component_count > 0) {
118 normalized[out_pos++] = PATH_DELIM;
119 }
120 if (out_pos + component_len >= PLATFORM_MAX_PATH_LENGTH) {
121 break;
122 }
123 memcpy(normalized + out_pos, component_start, component_len);
124 out_pos += component_len;
125 component_count++;
126 }
127
128 normalized[out_pos] = '\0';
129 return normalized;
130}
131
132const char *extract_project_relative_path(const char *file, const char *const *owned_dirs) {
133 // This runs inside logging and while the memory tracker holds its mutex.
134 // Avoid allocations, filesystem access, mutable caches, and error logging.
135 if (!file) {
136 return "unknown";
137 }
138 if (!owned_dirs) {
139 return file;
140 }
141
142 const char *root = NULL;
143 size_t root_length = 0;
144 if (owned_dirs) {
145 for (size_t dir_index = 0; owned_dirs[dir_index]; dir_index++) {
146 const char *candidate = owned_dirs[dir_index];
147 size_t candidate_length = strlen(candidate);
148 bool matches = true;
149 for (size_t i = 0; i < candidate_length; i++) {
150 unsigned char source_char = (unsigned char)candidate[i];
151 unsigned char file_char = (unsigned char)file[i];
152 if (source_char == '/' || source_char == '\\') {
153 if (file_char != '/' && file_char != '\\') {
154 matches = false;
155 break;
156 }
157 } else {
158#ifdef _WIN32
159 if (tolower(source_char) != tolower(file_char)) {
160 matches = false;
161 break;
162 }
163#else
164 if (source_char != file_char) {
165 matches = false;
166 break;
167 }
168#endif
169 }
170 }
171 if (matches && (file[candidate_length] == '/' || file[candidate_length] == '\\') && candidate_length > root_length) {
172 root = candidate;
173 root_length = candidate_length;
174 }
175 }
176 }
177 if (root) {
178 return file + root_length + 1;
179 }
180
181 root = ASCIICHAT_SOURCE_ROOT;
182 size_t i = 0;
183 bool root_matches = true;
184 for (; root[i]; i++) {
185 unsigned char source_char = (unsigned char)root[i];
186 unsigned char file_char = (unsigned char)file[i];
187 if (source_char == '/' || source_char == '\\') {
188 if (file_char != '/' && file_char != '\\') {
189 root_matches = false;
190 break;
191 }
192 } else {
193#ifdef _WIN32
194 // Windows source paths are case insensitive; POSIX paths are not.
195 if (tolower(source_char) != tolower(file_char)) {
196#else
197 if (source_char != file_char) {
198#endif
199 root_matches = false;
200 break;
201 }
202 }
203 }
204
205 // Match a whole directory, not a sibling whose name starts with the root.
206 if (root_matches && i > 0 && (file[i] == '/' || file[i] == '\\')) {
207 return file + i + 1;
208 }
209
210#ifdef _WIN32
211 // -ffile-prefix-map removes the checkout prefix from release debug records.
212 // CodeView/DbgHelp can anchor those relative records at the current drive
213 // root, producing paths such as C:\lib\debug\backtrace.c. Recognize only
214 // project source-tree roots so genuine external paths remain absolute.
215 if (isalpha((unsigned char)file[0]) && file[1] == ':' && (file[2] == '/' || file[2] == '\\')) {
216 const char *relative = file + 3;
217 static const char *project_roots[] = {"src", "lib", "tests", "include"};
218 for (size_t root_index = 0; root_index < sizeof(project_roots) / sizeof(project_roots[0]); root_index++) {
219 const char *project_root = project_roots[root_index];
220 size_t root_length = strlen(project_root);
221 if (_strnicmp(relative, project_root, root_length) == 0 && (relative[root_length] == '/' || relative[root_length] == '\\')) {
222 return relative;
223 }
224 }
225 }
226#endif
227 return file;
228}
229
230const char *path_last_components(const char *path, size_t component_count) {
231 if (!path || component_count == 0) {
232 return path;
233 }
234
235 const char *cursor = path + strlen(path);
236 size_t components_seen = 0;
237 while (cursor > path) {
238 cursor--;
239 if (*cursor != '/' && *cursor != '\\') {
240 continue;
241 }
242
243 const char *component_start = cursor + 1;
244 // Treat repeated separators as one boundary.
245 while (cursor > path && (cursor[-1] == '/' || cursor[-1] == '\\')) {
246 cursor--;
247 }
248 components_seen++;
249 if (components_seen == component_count) {
250 return component_start;
251 }
252 }
253
254 return path;
255}
256
257char *expand_path(const char *path) {
258 if (path[0] == PATH_TILDE) {
259 const char *home = platform_get_home_dir();
260 if (!home) {
261 return NULL;
262 }
263
264 char *expanded;
265 size_t total_len = strlen(home) + strlen(path) + 1; // path includes the tilde
266 expanded = SAFE_MALLOC(total_len, char *);
267 if (!expanded) {
268 return NULL;
269 }
270 safe_snprintf(expanded, total_len, "%s%s", home, path + 1);
271
273
274 return expanded;
275 }
276 return platform_strdup(path);
277}
278
279char *get_config_dir(void) {
280 /* Delegate to platform abstraction layer */
282}
283
284char *get_data_dir(void) {
285 /* Delegate to platform abstraction layer */
286 return platform_get_data_dir();
287}
288
289char *get_log_dir(void) {
290#ifdef __EMSCRIPTEN__
291 // WASM builds: Return NULL to skip SAFE_MALLOC before memory tracking is initialized
292 // The caller will use a fallback path (temp dir + filename)
293 return NULL;
294#endif
295
296#ifdef NDEBUG
297 // Release builds: Use $TMPDIR/ascii-chat/
298 // Get system temp directory
299 char temp_dir[PLATFORM_MAX_PATH_LENGTH];
300 if (!platform_get_temp_dir(temp_dir, sizeof(temp_dir))) {
301 // Fallback: Use current working directory if temp dir unavailable
302 char cwd_buf[PLATFORM_MAX_PATH_LENGTH];
303 if (!platform_get_cwd(cwd_buf, sizeof(cwd_buf))) {
304 return NULL;
305 }
306 char *result = SAFE_MALLOC(strlen(cwd_buf) + 1, char *);
307 if (!result) {
308 return NULL;
309 }
310 safe_snprintf(result, strlen(cwd_buf) + 1, "%s", cwd_buf);
311 return result;
312 }
313
314 // Build path to ascii-chat subdirectory
315 size_t log_dir_len = strlen(temp_dir) + strlen(PATH_SEPARATOR_STR) + strlen("ascii-chat") + 1;
316 char *log_dir = SAFE_MALLOC(log_dir_len, char *);
317 if (!log_dir) {
318 return NULL;
319 }
320 safe_snprintf(log_dir, log_dir_len, "%s%sascii-chat", temp_dir, PATH_SEPARATOR_STR);
321
322 // Create the directory if it doesn't exist (with owner-only permissions)
323 asciichat_error_t mkdir_result = platform_mkdir(log_dir, DIR_PERM_PRIVATE);
324 if (mkdir_result != ASCIICHAT_OK) {
325 // Directory creation failed - fall back to temp_dir without subdirectory
326 SAFE_FREE(log_dir);
327 char *result = SAFE_MALLOC(strlen(temp_dir) + 1, char *);
328 if (!result) {
329 return NULL;
330 }
331 safe_snprintf(result, strlen(temp_dir) + 1, "%s", temp_dir);
332 return result;
333 }
334
335 // Verify the directory is writable
336 if (platform_access(log_dir, PLATFORM_ACCESS_WRITE) != 0) {
337 // Directory not writable - fall back to temp_dir
338 SAFE_FREE(log_dir);
339 char *result = SAFE_MALLOC(strlen(temp_dir) + 1, char *);
340 if (!result) {
341 return NULL;
342 }
343 safe_snprintf(result, strlen(temp_dir) + 1, "%s", temp_dir);
344 return result;
345 }
346
347 return log_dir;
348#else
349 // Debug builds: Use the build checkout for logs when it is still writable.
350 const char *repo_root = ASCIICHAT_SOURCE_ROOT;
351 if (platform_access(repo_root, PLATFORM_ACCESS_WRITE) == 0) {
352 size_t len = strlen(repo_root) + 1;
353 char *result = SAFE_MALLOC(len, char *);
354 if (result) {
355 memcpy(result, repo_root, len);
356 }
357 return result;
358 }
359
360 // The binary may have been copied to a machine without the build checkout.
361 char cwd_buf[PLATFORM_MAX_PATH_LENGTH];
362 if (!platform_get_cwd(cwd_buf, sizeof(cwd_buf))) {
363 return NULL;
364 }
365
366 char *result = SAFE_MALLOC(strlen(cwd_buf) + 1, char *);
367 safe_snprintf(result, strlen(cwd_buf) + 1, "%s", cwd_buf);
368 return result;
369#endif
370}
371
373 platform_directory_list_t data_dirs = {0};
375 for (size_t i = 0; i < data_dirs.count; i++) {
376 platform_directory_candidate_t *candidate = &data_dirs.candidates[i];
377 if (platform_mkdir_recursive(candidate->path, candidate->mode) == ASCIICHAT_OK && platform_access(candidate->path, PLATFORM_ACCESS_WRITE) == 0) {
378 char *selected_dir = candidate->path;
379 candidate->path = NULL;
381 return selected_dir;
382 }
383 }
384 }
386
387 // Fall back to the platform's per-user application data directory.
388 char *data_dir = get_data_dir();
389 if (data_dir) {
390 asciichat_error_t mkdir_result = platform_mkdir_recursive(data_dir, DIR_PERM_PRIVATE);
391 if (mkdir_result == ASCIICHAT_OK) {
392 if (platform_access(data_dir, PLATFORM_ACCESS_WRITE) == 0) {
393 return data_dir;
394 }
395 }
396 SAFE_FREE(data_dir);
397 }
398
399 return NULL;
400}
401
402bool path_normalize_copy(const char *path, char *out, size_t out_len) {
403 if (!path || !out || out_len == 0) {
404 SET_ERRNO(ERROR_INVALID_PARAM, "null path or out or out_len is 0");
405 return false;
406 }
407
408 const char *normalized = normalize_path(path);
409 if (!normalized) {
410 return false;
411 }
412
413 size_t len = strlen(normalized);
414 if (len + 1 > out_len) {
415 return false;
416 }
417
418 memcpy(out, normalized, len + 1);
419 return true;
420}
421
422bool path_is_absolute(const char *path) {
423 if (!path || !*path) {
424 return false;
425 }
426
427#ifdef _WIN32
428 if ((path[0] == '\\' && path[1] == '\\')) {
429 return true; // UNC path
430 }
431 if (isalpha((unsigned char)path[0]) && path[1] == PATH_DRIVE_SEPARATOR && path[2] == PATH_DELIM) {
432 return true;
433 }
434 return false;
435#else
436 return path[0] == PATH_DELIM;
437#endif
438}
439
440bool path_is_within_base(const char *path, const char *base) {
441 if (!path || !base) {
442 return false;
443 }
444
445 if (!path_is_absolute(path) || !path_is_absolute(base)) {
446 return false;
447 }
448
449 char normalized_path[PLATFORM_MAX_PATH_LENGTH];
450 char normalized_base[PLATFORM_MAX_PATH_LENGTH];
451
452 if (!path_normalize_copy(path, normalized_path, sizeof(normalized_path))) {
453 return false;
454 }
455 if (!path_normalize_copy(base, normalized_base, sizeof(normalized_base))) {
456 return false;
457 }
458
459 size_t base_len = strlen(normalized_base);
460 if (base_len == 0) {
461 return false;
462 }
463
464 if (platform_path_strcasecmp(normalized_path, normalized_base, base_len) != 0) {
465 return false;
466 }
467 if (normalized_base[base_len - 1] == PATH_DELIM) {
468 return true;
469 }
470 char next = normalized_path[base_len];
471 if (next == '\0') {
472 return true;
473 }
474 return next == PATH_DELIM;
475}
476
477bool path_is_within_any_base(const char *path, const char *const *bases, size_t base_count) {
478 if (!path || !bases || base_count == 0) {
479 return false;
480 }
481
482 for (size_t i = 0; i < base_count; ++i) {
483 const char *base = bases[i];
484 if (!base) {
485 continue;
486 }
487 if (path_is_within_base(path, base)) {
488 return true;
489 }
490 }
491
492 return false;
493}
494
495bool path_looks_like_path(const char *value) {
496 if (!value || *value == '\0') {
497 return false;
498 }
499
500 if (value[0] == PATH_DELIM || value[0] == PATH_COMPONENT_DOT || value[0] == PATH_TILDE) {
501 return true;
502 }
503
504 if (strchr(value, PATH_DELIM)) {
505 return true;
506 }
507
508#ifdef _WIN32
509 if (isalpha((unsigned char)value[0]) && value[1] == ':' && value[2] == PATH_DELIM) {
510 return true;
511 }
512#endif
513
514 return false;
515}
516
517static asciichat_error_t map_role_to_error(path_role_t role) {
518 switch (role) {
520 return ERROR_CONFIG;
522 return ERROR_LOGGING_INIT;
526 return ERROR_CRYPTO_KEY;
527 }
528 return ERROR_GENERAL;
529}
530
531static void append_base_if_valid(const char *candidate, const char **bases, size_t *count) {
532 if (!candidate || *candidate == '\0' || *count >= MAX_PATH_BASES) {
533 return;
534 }
535 if (!path_is_absolute(candidate)) {
536 return;
537 }
538 bases[*count] = candidate;
539 (*count)++;
540}
541
542static void build_ascii_chat_path(const char *base, const char *suffix, char *out, size_t out_len) {
543 if (!base || !suffix || out_len == 0) {
544 out[0] = '\0';
545 return;
546 }
547
548 size_t base_len = strlen(base);
549 bool needs_sep = base_len > 0 && base[base_len - 1] != PATH_DELIM;
550
551 safe_snprintf(out, out_len, "%s%s%s", base, needs_sep ? PATH_SEPARATOR_STR : "", suffix);
552}
553
561static bool is_sensitive_system_path(const char *path) {
562 if (!path) {
563 return false;
564 }
565
566#ifdef _WIN32
567 // Windows system directories
568 const char *sensitive_paths[] = {"C:\\Windows", // System directory
569 "C:\\Program Files", // Program files
570 "C:\\Program Files (x86)", // 32-bit programs
571 "C:\\ProgramData", // All users data
572 "C:\\System Volume Information", // System recovery
573 "C:\\PerfLogs", // Performance logs
574 NULL};
575#else
576 // Unix/Linux/macOS system directories
577 const char *sensitive_paths[] = {"/etc", // System configuration
578 "/bin", // Essential binaries
579 "/sbin", // System binaries
580 "/usr/bin", // User binaries
581 "/usr/sbin", // User system binaries
582 "/usr/lib", // System libraries
583 "/lib", // Libraries
584 "/lib64", // 64-bit libraries
585 "/boot", // Boot files
586 "/sys", // System interface
587 "/proc", // Process interface
588 "/dev", // Devices
589 "/root", // Root home (should not write to)
590 "/var/lib", // Variable library data
591 "/var/cache", // Cache data
592 "/var/spool", // Spool data
593 NULL};
594
595#ifdef __APPLE__
596 // macOS-specific system paths
597 const char *macos_paths[] = {"/System", // Core system
598 "/Library", // System library
599 "/Applications", // Bundled apps
600 "/Developer", // Developer tools
601 "/Volumes", // Mounted volumes
602 NULL};
603#endif
604#endif
605
606 // Check each sensitive path
607 for (int i = 0; sensitive_paths[i] != NULL; i++) {
608 const char *base = sensitive_paths[i];
609 size_t base_len = strlen(base);
610
611 // Match if path equals base or starts with base + separator
612 if (strcmp(path, base) == 0) {
613 return true; // Exact match is sensitive
614 }
615 if (strncmp(path, base, base_len) == 0) {
616 // Make sure it's followed by a path separator, not a partial match
617 if (path[base_len] == PATH_DELIM || path[base_len] == '/' || path[base_len] == '\\') {
618 return true;
619 }
620 }
621 }
622
623#ifdef __APPLE__
624 // Check macOS paths
625 for (int i = 0; macos_paths[i] != NULL; i++) {
626 const char *base = macos_paths[i];
627 size_t base_len = strlen(base);
628
629 if (strcmp(path, base) == 0) {
630 return true;
631 }
632 if (strncmp(path, base, base_len) == 0) {
633 if (path[base_len] == PATH_DELIM || path[base_len] == '/' || path[base_len] == '\\') {
634 return true;
635 }
636 }
637 }
638#endif
639
640 return false;
641}
642
650static bool is_file_empty(const char *path) {
651 if (!path) {
652 SET_ERRNO(ERROR_INVALID_PARAM, "invalid parameter");
653 return false;
654 }
655
656 if (!platform_is_regular_file(path)) {
657 return false;
658 }
659
660 FILE *f = platform_fopen("file_stream", path, "r");
661 if (!f) {
662 return false;
663 }
664
665 int c = fgetc(f);
666 fclose(f);
667 return c == EOF;
668}
669
670static bool is_existing_ascii_chat_log(const char *path) {
671 if (!path) {
672 return false;
673 }
674
675 // Check if path is a regular file (not a directory) using platform abstraction
676 if (!platform_is_regular_file(path)) {
677 return false; // Not a regular file (could be directory, doesn't exist, symlink, etc.)
678 }
679
680 // Try to open and read the first line
681 FILE *f = platform_fopen("file_stream", path, "r");
682 if (!f) {
683 return false; // Can't read file
684 }
685
686 char buffer[UTIL_PATH_BUFFER_BUFFER_SIZE];
687 bool is_ascii_chat_log = false;
688
689 // Read first line and check for ascii-chat log signature
690 if (fgets(buffer, sizeof(buffer), f) != NULL) {
691 char plain[sizeof(buffer)];
692 strip_ansi_codes(buffer, plain, sizeof(plain));
693
694 // ascii-chat logs start with timestamps like: [HH:MM:SS.microseconds] [LEVEL]
695 // Pattern: [digit][digit]:[digit][digit]:[digit][digit].[digits]
696 if (plain[0] == '[' && isdigit((unsigned char)plain[1]) && isdigit((unsigned char)plain[2]) && plain[3] == ':') {
697 is_ascii_chat_log = true;
698 }
699 }
700
701 fclose(f);
702 return is_ascii_chat_log;
703}
704
705asciichat_error_t path_validate_user_path(const char *input, path_role_t role, char **normalized_out) {
706 if (!normalized_out) {
707 return SET_ERRNO(map_role_to_error(role), "Output pointer is required");
708 }
709 *normalized_out = NULL;
710
711 if (!input || *input == '\0') {
712 return SET_ERRNO(map_role_to_error(role), "Path is empty for role %d", role);
713 }
714
715 // SECURITY: For log files, if input is a simple filename (no separators or ..), constrain it to a safe directory
716 if (role == PATH_ROLE_LOG_FILE) {
717 // Check if input contains path separators or parent directory references
718 bool is_simple_filename = true;
719 for (const char *p = input; *p; p++) {
720 if (*p == PATH_DELIM || *p == '/' || *p == '\\') {
721 is_simple_filename = false;
722 break;
723 }
724 }
725 // Also reject ".." components (even without separators like "..something")
726 if (strstr(input, "..") != NULL) {
727 is_simple_filename = false;
728 }
729
730 // If it's a simple filename, resolve it to a safe base directory
731 if (is_simple_filename) {
732 // Always prefer current working directory for simple log filenames
733 // This ensures logs go to where the user is running the command from
734 char safe_base[PLATFORM_MAX_PATH_LENGTH];
735
736 if (!platform_get_cwd(safe_base, sizeof(safe_base))) {
737 // If cwd fails, try config dir as fallback
738 char *config_dir = get_config_dir();
739 if (config_dir) {
740 SAFE_STRNCPY(safe_base, config_dir, sizeof(safe_base));
741 SAFE_FREE(config_dir);
742 } else {
743 return SET_ERRNO(ERROR_LOGGING_INIT, "Failed to determine safe directory for log file");
744 }
745 }
746
747 // Build the full path: safe_base + separator + input
748 size_t base_len = strlen(safe_base);
749 size_t input_len = strlen(input);
750 bool needs_sep = base_len > 0 && safe_base[base_len - 1] != PATH_DELIM;
751 size_t total_len = base_len + (needs_sep ? 1 : 0) + input_len + 1;
752
753 if (total_len > PLATFORM_MAX_PATH_LENGTH) {
754 return SET_ERRNO(ERROR_LOGGING_INIT, "Log file path too long: %s/%s", safe_base, input);
755 }
756
757 char resolved_buf[PLATFORM_MAX_PATH_LENGTH];
758 safe_snprintf(resolved_buf, sizeof(resolved_buf), "%s%s%s", safe_base, needs_sep ? PATH_SEPARATOR_STR : "", input);
759
760 // Normalize the resolved path
761 char normalized_buf[PLATFORM_MAX_PATH_LENGTH];
762 if (!path_normalize_copy(resolved_buf, normalized_buf, sizeof(normalized_buf))) {
763 return SET_ERRNO(ERROR_LOGGING_INIT, "Failed to normalize log file path: %s", resolved_buf);
764 }
765
766 // Allocate and return the result
767 char *result = SAFE_MALLOC(strlen(normalized_buf) + 1, char *);
768 if (!result) {
769 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate normalized path");
770 }
771 safe_snprintf(result, strlen(normalized_buf) + 1, "%s", normalized_buf);
772 *normalized_out = result;
773 return ASCIICHAT_OK;
774 }
775 // If not a simple filename (contains separators), continue with normal validation below
776 }
777
778 // For non-log-files or log files with path separators, validate as usual
779 if (role != PATH_ROLE_LOG_FILE && !path_looks_like_path(input)) {
780 return SET_ERRNO(map_role_to_error(role), "Value does not look like a filesystem path: %s", input);
781 }
782
783 char *expanded = expand_path(input);
784 if (!expanded) {
785 return SET_ERRNO(map_role_to_error(role), "Failed to expand path: %s", input);
786 }
787
788 defer(SAFE_FREE(expanded));
789
790 char candidate_buf[PLATFORM_MAX_PATH_LENGTH];
791 const char *candidate_path = expanded;
792
793 if (!path_is_absolute(candidate_path)) {
794 char cwd_buf[PLATFORM_MAX_PATH_LENGTH];
795 if (!platform_get_cwd(cwd_buf, sizeof(cwd_buf))) {
796 return SET_ERRNO(map_role_to_error(role), "Failed to determine current working directory");
797 }
798
799 size_t total_len = strlen(cwd_buf) + 1 + strlen(candidate_path) + 1;
800 if (total_len >= sizeof(candidate_buf)) {
801 return SET_ERRNO(map_role_to_error(role), "Resolved path is too long: %s/%s", cwd_buf, candidate_path);
802 }
803 if (strlen(candidate_path) > 0 && candidate_path[0] == PATH_DELIM) {
804 safe_snprintf(candidate_buf, sizeof(candidate_buf), "%s%s", cwd_buf, candidate_path);
805 } else {
806 safe_snprintf(candidate_buf, sizeof(candidate_buf), "%s%c%s", cwd_buf, PATH_DELIM, candidate_path);
807 }
808 candidate_path = candidate_buf;
809 }
810
811 char normalized_buf[PLATFORM_MAX_PATH_LENGTH];
812 if (!path_normalize_copy(candidate_path, normalized_buf, sizeof(normalized_buf))) {
813 return SET_ERRNO(map_role_to_error(role), "Failed to normalize path: %s", candidate_path);
814 }
815
816 if (!path_is_absolute(normalized_buf)) {
817 return SET_ERRNO(map_role_to_error(role), "Normalized path is not absolute: %s", normalized_buf);
818 }
819
820 const char *bases[MAX_PATH_BASES] = {0};
821 size_t base_count = 0;
822
823 // Always add current working directory as an allowed base
824 // This is critical for log files and other paths relative to where the user runs the command
825 char cwd_base[PLATFORM_MAX_PATH_LENGTH];
826 if (platform_get_cwd(cwd_base, sizeof(cwd_base))) {
827 append_base_if_valid(cwd_base, bases, &base_count);
828 }
829
830#ifndef NDEBUG
831 // Debug builds select the source checkout as their default log directory,
832 // even when the process was launched from another working directory.
833 if (role == PATH_ROLE_LOG_FILE)
834 append_base_if_valid(ASCIICHAT_SOURCE_ROOT, bases, &base_count);
835#endif
836
837 char temp_base[PLATFORM_MAX_PATH_LENGTH];
838 if (platform_get_temp_dir(temp_base, sizeof(temp_base))) {
839 append_base_if_valid(temp_base, bases, &base_count);
840 }
841
842 char *config_dir = get_config_dir();
843 defer(SAFE_FREE(config_dir));
844 if (config_dir) {
845 append_base_if_valid(config_dir, bases, &base_count);
846 }
847
848 char home_base[PLATFORM_MAX_PATH_LENGTH];
849 const char *home_env = platform_get_home_dir();
850 if (home_env) {
851 // Windows environment lookups reuse a thread-local buffer. Keep this base
852 // stable when PROGRAMDATA is read below.
853 SAFE_STRNCPY(home_base, home_env, sizeof(home_base));
854 home_env = home_base;
855 append_base_if_valid(home_env, bases, &base_count);
856 }
857
858 char ascii_chat_home[PLATFORM_MAX_PATH_LENGTH];
859 if (home_env) {
860 build_ascii_chat_path(home_env, ".ascii-chat", ascii_chat_home, sizeof(ascii_chat_home));
861 append_base_if_valid(ascii_chat_home, bases, &base_count);
862 }
863
864#ifndef _WIN32
865 char ascii_chat_home_tmp[PLATFORM_MAX_PATH_LENGTH];
866 build_ascii_chat_path("/tmp", ".ascii-chat", ascii_chat_home_tmp, sizeof(ascii_chat_home_tmp));
867 append_base_if_valid(ascii_chat_home_tmp, bases, &base_count);
868#endif
869
870 char ssh_home[PLATFORM_MAX_PATH_LENGTH];
871 if (home_env) {
872 build_ascii_chat_path(home_env, ".ssh", ssh_home, sizeof(ssh_home));
873 append_base_if_valid(ssh_home, bases, &base_count);
874 }
875
876#ifdef _WIN32
877 char program_data_logs[PLATFORM_MAX_PATH_LENGTH];
878 const char *program_data = platform_getenv("PROGRAMDATA");
879 if (program_data) {
880 build_ascii_chat_path(program_data, "ascii-chat", program_data_logs, sizeof(program_data_logs));
881 append_base_if_valid(program_data_logs, bases, &base_count);
882 }
883#else
884 // System-wide config directories (for server deployments)
885 append_base_if_valid("/etc/ascii-chat", bases, &base_count);
886 append_base_if_valid("/usr/local/etc/ascii-chat", bases, &base_count);
887 append_base_if_valid("/var/log", bases, &base_count);
888 append_base_if_valid("/var/tmp", bases, &base_count);
889 append_base_if_valid("/tmp", bases, &base_count);
890#ifdef __APPLE__
891 // On macOS, /tmp is a symlink to /private/tmp
892 append_base_if_valid("/private/tmp", bases, &base_count);
893 // On macOS, all user home directories are under /Users
894 append_base_if_valid("/Users", bases, &base_count);
895#endif
896#endif
897
898 // Security check: Reject paths that point to sensitive system files
899 // This applies to all path roles, not just logs
900 if (is_sensitive_system_path(normalized_buf)) {
901 return SET_ERRNO(map_role_to_error(role), "Cannot write to protected system path: %s", normalized_buf);
902 }
903
904 // For log files, apply special validation rules
905 if (role == PATH_ROLE_LOG_FILE) {
906 // Check if path is a regular file (not a directory, not non-existent)
907 // On macOS, fopen() can succeed on directories, so we must use platform_is_regular_file()
908 bool is_regular_file = platform_is_regular_file(normalized_buf);
909
910 // If a regular file exists, it MUST be an ascii-chat log or empty file to be overwritten
911 if (is_regular_file && !is_existing_ascii_chat_log(normalized_buf) && !is_file_empty(normalized_buf)) {
913 "Cannot overwrite existing non-ascii-chat file: %s\n"
914 "For safety, ascii-chat will only overwrite its own log files or empty files",
915 normalized_buf);
916 }
917
918 // If file doesn't exist (or is a directory), check that path is in safe locations
919 if (!is_regular_file) {
920 bool allowed = base_count == 0 ? true : path_is_within_any_base(normalized_buf, bases, base_count);
921 if (!allowed) {
923 "Log path %s is outside allowed directories (use -L /tmp/file.log, ~/file.log, or "
924 "relative/absolute paths in safe locations)",
925 normalized_buf);
926 }
927 }
928 } else {
929 // For non-log-file paths, apply standard whitelist validation
930 bool allowed = base_count == 0 ? true : path_is_within_any_base(normalized_buf, bases, base_count);
931 if (!allowed) {
932 return SET_ERRNO(map_role_to_error(role), "Path %s is outside allowed directories", normalized_buf);
933 }
934 }
935
936 char *result = SAFE_MALLOC(strlen(normalized_buf) + 1, char *);
937 if (!result) {
938 return SET_ERRNO(ERROR_MEMORY, "Failed to allocate normalized path");
939 }
940 safe_snprintf(result, strlen(normalized_buf) + 1, "%s", normalized_buf);
941 *normalized_out = result;
942
943 return ASCIICHAT_OK;
944}
#define SET_ERRNO(code,...)
Error and exit codes - unified status values (0-255).
int platform_mkdir_recursive(const char *path, int mode)
Definition filesystem.c:36
int platform_get_data_dir_candidates(const char *install_prefix, platform_directory_list_t *list_out)
Definition filesystem.c:105
int platform_access(const char *pathname, int mode)
Definition filesystem.c:95
char * platform_get_data_dir(void)
Definition filesystem.c:101
FILE * platform_fopen(const char *name, const char *filename, const char *mode)
Definition filesystem.c:18
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define PLATFORM_MAX_PATH_LENGTH
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_LOGGING_INIT
Definition error_codes.h:58
@ ERROR_CRYPTO_KEY
Definition error_codes.h:98
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_GENERAL
Definition error_codes.h:51
@ ERROR_CONFIG
Definition error_codes.h:56
@ ERROR_INVALID_PARAM
#define PATH_DRIVE_SEPARATOR
Path component: Windows drive separator (colon).
Definition path.h:82
bool path_looks_like_path(const char *value)
Determine if a string is likely intended to reference the filesystem.
Definition path.c:495
char * get_log_dir(void)
Get log directory path appropriate for current build type.
Definition path.c:289
path_role_t
Classification for user-supplied filesystem paths.
Definition path.h:322
void strip_ansi_codes(const char *input, char *output, size_t output_size)
Strip ANSI escape codes from a string.
#define MAX_PATH_BASES
Maximum number of path base directories.
Definition path.h:89
const char * extract_project_relative_path(const char *file, const char *const *owned_dirs)
Extract a path relative to the source root embedded by CMake.
Definition path.c:132
bool path_is_absolute(const char *path)
Determine whether a path is absolute on the current platform.
Definition path.c:422
asciichat_error_t path_validate_user_path(const char *input, path_role_t role, char **normalized_out)
Validate and canonicalize a user-supplied filesystem path.
Definition path.c:705
char * expand_path(const char *path)
Expand path with tilde (~) support.
Definition path.c:257
bool path_is_within_base(const char *path, const char *base)
Check whether a path resides within a specified base directory.
Definition path.c:440
char * get_discovery_database_dir(void)
Get discovery service database directory with Homebrew-aware system-wide fallback.
Definition path.c:372
void path_cleanup_thread_locals(void)
Cleanup thread-local path resources.
Definition path.c:32
const char * path_last_components(const char *path, size_t component_count)
Return a pointer to the last components of a path.
Definition path.c:230
char * get_config_dir(void)
Get configuration directory path with XDG_CONFIG_HOME support.
Definition path.c:279
bool path_is_within_any_base(const char *path, const char *const *bases, size_t base_count)
Check whether a path resides within any of several base directories.
Definition path.c:477
#define PATH_COMPONENT_DOT
Path component: current directory (single dot).
Definition path.h:63
char * get_data_dir(void)
Get application data directory path.
Definition path.c:284
#define PATH_TILDE
Path component: home directory tilde.
Definition path.h:77
bool path_normalize_copy(const char *path, char *out, size_t out_len)
Normalize a path and copy it into the provided buffer.
Definition path.c:402
@ PATH_ROLE_CONFIG_FILE
Definition path.h:323
@ PATH_ROLE_CLIENT_KEYS
Definition path.h:327
@ PATH_ROLE_KEY_PUBLIC
Definition path.h:326
@ PATH_ROLE_LOG_FILE
Definition path.h:324
@ PATH_ROLE_KEY_PRIVATE
Definition path.h:325
⚙️ Common definitions, error codes, macros, and types shared throughout the application
#define UTIL_PATH_BUFFER_BUFFER_SIZE
Definition path.c:8
#define PATH_COMPONENT_BUFFER_SIZE
Definition path.c:11
📂 Path Manipulation Utilities
System paths configuration (generated by CMake).
#define ASCIICHAT_INSTALL_PREFIX
Installation prefix.
Definition paths.h:30
static bool size_t gotel_query_t * out
Definition queries.h:8
return true
Definition queries.h:13
char * platform_strdup(const char *s)
🔤 String Manipulation and Shell Escaping Utilities
const char * platform_getenv(const char *name)
Definition system.c:45
bool platform_get_cwd(char *cwd, size_t path_size)
Definition util.c:122
int platform_path_strcasecmp(const char *a, const char *b, size_t n)
Definition util.c:131
void platform_normalize_path_separators(char *path)
Definition util.c:110
bool platform_get_temp_dir(char *temp_dir, size_t path_size)
Definition util.c:81
void platform_directory_list_destroy(platform_directory_list_t *list)
Definition util.c:22
int platform_is_regular_file(const char *path)
Definition util.c:136
const char * platform_get_home_dir(void)
Definition util.c:106
char * platform_get_config_dir(void)
Definition util.c:116