| 1 | #include <dirent.h> |
| 2 | #include <sys/stat.h> |
| 3 | #include <string.h> |
| 4 | #include <stdio.h> |
| 5 | #include <unistd.h> |
| 6 | #include <stdlib.h> |
| 7 | #include <limits.h> |
| 8 | |
| 9 | /* Helper to list directory and return entry names |
| 10 | This avoids issues with dirent structure layout differences */ |
| 11 | int list_dir_helper(const char *path, char names[][256], int max_entries) { |
| 12 | DIR *dir; |
| 13 | struct dirent *entry; |
| 14 | int count = 0; |
| 15 | |
| 16 | dir = opendir(path); |
| 17 | if (dir == NULL) { |
| 18 | return 0; /* Couldn't open directory */ |
| 19 | } |
| 20 | |
| 21 | while ((entry = readdir(dir)) != NULL && count < max_entries) { |
| 22 | /* Skip . and .. */ |
| 23 | if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { |
| 24 | continue; |
| 25 | } |
| 26 | |
| 27 | /* Copy name */ |
| 28 | strncpy(names[count], entry->d_name, 255); |
| 29 | names[count][255] = '\0'; /* Ensure null termination */ |
| 30 | count++; |
| 31 | } |
| 32 | |
| 33 | closedir(dir); |
| 34 | return count; |
| 35 | } |
| 36 | |
| 37 | /* Helper to check if path is a directory */ |
| 38 | int is_dir_helper(const char *path) { |
| 39 | struct stat st; |
| 40 | if (stat(path, &st) != 0) { |
| 41 | return 0; /* stat failed */ |
| 42 | } |
| 43 | return S_ISDIR(st.st_mode) ? 1 : 0; |
| 44 | } |
| 45 | |
| 46 | /* Helper to check if path is a symlink */ |
| 47 | int is_link_helper(const char *path) { |
| 48 | struct stat st; |
| 49 | if (lstat(path, &st) != 0) { |
| 50 | return 0; /* lstat failed */ |
| 51 | } |
| 52 | return S_ISLNK(st.st_mode) ? 1 : 0; |
| 53 | } |
| 54 | |
| 55 | /* Helper to get file size */ |
| 56 | long long get_size_helper(const char *path) { |
| 57 | struct stat st; |
| 58 | if (stat(path, &st) != 0) { |
| 59 | return 0; /* stat failed */ |
| 60 | } |
| 61 | return (long long)st.st_size; |
| 62 | } |
| 63 | |
| 64 | /* Helper to check if running as root */ |
| 65 | int is_running_as_root() { |
| 66 | return (geteuid() == 0) ? 1 : 0; |
| 67 | } |
| 68 | |
| 69 | /* Helper to get absolute path from relative path */ |
| 70 | int get_absolute_path(const char *path, char *result, int result_len) { |
| 71 | char *abs_path = realpath(path, NULL); |
| 72 | if (abs_path == NULL) { |
| 73 | return 0; /* Failed to resolve path */ |
| 74 | } |
| 75 | |
| 76 | /* Copy to result buffer */ |
| 77 | strncpy(result, abs_path, result_len - 1); |
| 78 | result[result_len - 1] = '\0'; |
| 79 | |
| 80 | free(abs_path); |
| 81 | return 1; /* Success */ |
| 82 | } |