diff --git a/utils.c b/utils.c index c22250d..db63238 100644 --- a/utils.c +++ b/utils.c @@ -17,9 +17,11 @@ */ #include +#include #include #include #include +#include #include "utils.h" #define foreach_arg(_arg, _addr, _len, _first_addr, _first_len) \ @@ -155,3 +157,33 @@ void cbuf_free(void *ptr, unsigned int order) { munmap(ptr, cbuf_size(order) * 2); } + +int mkdir_p(char *dir, mode_t mask) +{ + char *l; + int ret; + + ret = mkdir(dir, mask); + if (!ret || (ret && errno == EEXIST)) + return 0; + + if (ret && (errno != ENOENT)) + return -1; + + l = strrchr(dir, '/'); + if (!l || l == dir) + return -1; + + *l = '\0'; + + if (mkdir_p(dir, mask)) + return -1; + + *l = '/'; + + ret = mkdir(dir, mask); + if (!ret || (ret && errno == EEXIST)) + return 0; + else + return -1; +} diff --git a/utils.h b/utils.h index 27f81e5..5c53cc0 100644 --- a/utils.h +++ b/utils.h @@ -19,6 +19,7 @@ #ifndef __LIBUBOX_UTILS_H #define __LIBUBOX_UTILS_H +#include #include #include #include @@ -252,5 +253,6 @@ static inline unsigned long cbuf_size(int order) void *cbuf_alloc(unsigned int order); void cbuf_free(void *ptr, unsigned int order); +int mkdir_p(char *dir, mode_t mask); #endif