Line data Source code
1 : /* SPDX-License-Identifier: GPL-3.0-or-later */
2 : /* Copyright 2026 Peter Csaszar */
3 :
4 : #include "fs_util.h"
5 : #include "platform/path.h"
6 : #include <stdio.h>
7 : #include <stdlib.h>
8 : #include <string.h>
9 : #include <sys/stat.h>
10 : #include <unistd.h>
11 : #include <errno.h>
12 :
13 : /**
14 : * @brief Creates a directory and all missing parent directories.
15 : * @param path Directory path to create.
16 : * @param mode Permission bits applied to each created directory.
17 : * @return 0 on success, -1 on error.
18 : */
19 637 : int fs_mkdir_p(const char *path, mode_t mode) {
20 : char tmp[1024];
21 637 : char *p = NULL;
22 : size_t len;
23 :
24 637 : if (!path || !*path) return -1;
25 :
26 637 : snprintf(tmp, sizeof(tmp), "%s", path);
27 637 : len = strlen(tmp);
28 637 : if (len > 0 && tmp[len - 1] == '/')
29 1 : tmp[len - 1] = 0;
30 :
31 25484 : for (p = tmp + 1; *p; p++) {
32 24848 : if (*p == '/') {
33 1896 : *p = 0;
34 : /* Skip empty components (multiple slashes) */
35 1896 : if (strlen(tmp) > 0) {
36 1896 : if (mkdir(tmp, mode) != 0 && errno != EEXIST) {
37 1 : return -1;
38 : }
39 : }
40 1895 : *p = '/';
41 : }
42 : }
43 :
44 636 : if (strlen(tmp) > 0) {
45 636 : if (mkdir(tmp, mode) != 0 && errno != EEXIST) {
46 2 : return -1;
47 : }
48 : // Explicitly set mode in case of umask
49 634 : return chmod(tmp, mode);
50 : }
51 :
52 0 : return 0;
53 : }
54 :
55 : /**
56 : * @brief Sets the permission bits on an existing file or directory.
57 : * @param path Path to the file.
58 : * @param mode Desired permission bits.
59 : * @return 0 on success, -1 on error.
60 : */
61 541 : int fs_ensure_permissions(const char *path, mode_t mode) {
62 541 : return chmod(path, mode);
63 : }
64 :
65 : /**
66 : * @brief Returns the user's home directory path.
67 : *
68 : * Delegates to the platform layer (platform_home_dir()).
69 : * @return Pointer to the home path string (do not free), or NULL if unavailable.
70 : */
71 2 : const char* fs_get_home_dir(void) {
72 2 : return platform_home_dir();
73 : }
|