utils: introduce mkdir_p

Add new utility function mkdir_p(char *path, mode_t mode) to replace
the partially buggy implementations found accross fstools and procd.

Signed-off-by: Daniel Golle <daniel@makrotopia.org>
This commit is contained in:
Daniel Golle 2020-12-12 22:45:53 +00:00
parent 9e52171d70
commit 357877693c
2 changed files with 34 additions and 0 deletions

32
utils.c
View file

@ -17,9 +17,11 @@
*/ */
#include <sys/mman.h> #include <sys/mman.h>
#include <errno.h>
#include <stdarg.h> #include <stdarg.h>
#include <stdlib.h> #include <stdlib.h>
#include <stdio.h> #include <stdio.h>
#include <string.h>
#include "utils.h" #include "utils.h"
#define foreach_arg(_arg, _addr, _len, _first_addr, _first_len) \ #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); 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;
}

View file

@ -19,6 +19,7 @@
#ifndef __LIBUBOX_UTILS_H #ifndef __LIBUBOX_UTILS_H
#define __LIBUBOX_UTILS_H #define __LIBUBOX_UTILS_H
#include <sys/stat.h>
#include <sys/types.h> #include <sys/types.h>
#include <sys/time.h> #include <sys/time.h>
#include <stdint.h> #include <stdint.h>
@ -252,5 +253,6 @@ static inline unsigned long cbuf_size(int order)
void *cbuf_alloc(unsigned int order); void *cbuf_alloc(unsigned int order);
void cbuf_free(void *ptr, unsigned int order); void cbuf_free(void *ptr, unsigned int order);
int mkdir_p(char *dir, mode_t mask);
#endif #endif