11#include <ctype.h>
22#include <dirent.h>
33#include <errno.h>
4+ #include <fcntl.h>
45#include <libgen.h>
6+ #include <limits.h>
57#include <stdbool.h>
68#include <stdio.h>
7- #include <stdlib.h>
8- #include <string.h>
9- #include <strings.h>
109#include <sys/stat.h>
11- #include <sys/types.h>
1210#include <unistd.h>
1311
1412#include "core/path_utils.h"
@@ -38,14 +36,16 @@ int ensure_dir(const char *path) {
3836 if (!S_ISDIR (st .st_mode )) {
3937 // Path exists but is not a directory
4038 log_error ("Regular file in the way of directory at %s" , path );
41- return -1 ;
39+ // Also set errno
40+ errno = ENOTDIR ;
41+ return - ENOTDIR ;
4242 }
43- // If path exists and is directory, fall through to update p
43+ // If path exists and is directory, we're done
4444 } else {
4545 // Create this directory level
4646 if (mkdir (path , 0755 ) != 0 && errno != EEXIST ) {
4747 log_error ("Failed to create directory %s: %s" , path , strerror (errno ));
48- return -1 ;
48+ return - errno ;
4949 }
5050 }
5151
@@ -56,9 +56,9 @@ int ensure_dir(const char *path) {
5656 * Create a directory recursively (like mkdir -p), internal implementation.
5757 *
5858 * Will modify path in-place, but restores it before returning. Does not perform
59- * input validation.
59+ * input validation. Returns the negative error code if one is encountered.
6060 */
61- int _mkdir_recursive (char * path ) {
61+ static int _mkdir_recursive (char * path ) {
6262 // Iterate through path components and create each directory
6363 char * p = path ;
6464
@@ -126,7 +126,7 @@ int mkdir_recursive(const char *path) {
126126 * Set permissions on a file or directory (like chmod). Sets fd_out if the
127127 * path is a directory for use in recursive chmod.
128128 */
129- int _chmod_path (const char * path , mode_t mode , int * fd_out ) {
129+ static int _chmod_path (const char * path , mode_t mode , int * fd_out ) {
130130 // Open as a directory first (O_NOFOLLOW prevents following symlinks, eliminating
131131 // the TOCTOU race between the old lstat() check and chmod() on the same path).
132132 int fd = open (path , O_RDONLY | O_DIRECTORY | O_NOFOLLOW );
@@ -223,6 +223,13 @@ int chmod_recursive(const char *path, mode_t mode) {
223223 int result = 0 ;
224224
225225 size_t offset = snprintf (full_path , sizeof (full_path ), "%s/" , path );
226+ if (offset >= PATH_MAX ) {
227+ // If the path is already max length, we won't be able to append anything to
228+ // it. In this case emit an error and return.
229+ log_error ("Path too long to recur for chmod" );
230+ close (fd );
231+ return -1 ;
232+ }
226233 char * path_ptr = full_path + offset ;
227234
228235 while ((entry = readdir (dir )) != NULL ) {
0 commit comments