2015-03-29 17:18:00 -04:00
|
|
|
#include "libi3.h"
|
|
|
|
#include <errno.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <string.h>
|
|
|
|
#include <sys/stat.h>
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Emulates mkdir -p (creates any missing folders)
|
|
|
|
*
|
|
|
|
*/
|
2015-07-27 20:47:12 -04:00
|
|
|
|
|
|
|
#if !defined(__sun)
|
|
|
|
int mkdirp(const char *path, mode_t mode) {
|
|
|
|
if (mkdir(path, mode) == 0)
|
|
|
|
return 0;
|
2015-05-23 07:12:18 -04:00
|
|
|
if (errno == EEXIST) {
|
|
|
|
struct stat st;
|
|
|
|
/* Check that the named file actually is a directory. */
|
|
|
|
if (stat(path, &st)) {
|
|
|
|
ELOG("stat(%s) failed: %s\n", path, strerror(errno));
|
2015-07-27 20:47:12 -04:00
|
|
|
return -1;
|
2015-05-23 07:12:18 -04:00
|
|
|
}
|
|
|
|
if (!S_ISDIR(st.st_mode)) {
|
|
|
|
ELOG("mkdir(%s) failed: %s\n", path, strerror(ENOTDIR));
|
2015-07-27 20:47:12 -04:00
|
|
|
return -1;
|
2015-05-23 07:12:18 -04:00
|
|
|
}
|
2015-07-27 20:47:12 -04:00
|
|
|
return 0;
|
2015-05-23 07:12:18 -04:00
|
|
|
} else if (errno != ENOENT) {
|
2015-03-29 17:18:00 -04:00
|
|
|
ELOG("mkdir(%s) failed: %s\n", path, strerror(errno));
|
2015-07-27 20:47:12 -04:00
|
|
|
return -1;
|
2015-03-29 17:18:00 -04:00
|
|
|
}
|
|
|
|
char *copy = sstrdup(path);
|
|
|
|
/* strip trailing slashes, if any */
|
|
|
|
while (copy[strlen(copy) - 1] == '/')
|
|
|
|
copy[strlen(copy) - 1] = '\0';
|
|
|
|
|
|
|
|
char *sep = strrchr(copy, '/');
|
|
|
|
if (sep == NULL) {
|
|
|
|
if (copy != NULL) {
|
|
|
|
free(copy);
|
|
|
|
copy = NULL;
|
|
|
|
}
|
2015-07-27 20:47:12 -04:00
|
|
|
return -1;
|
2015-03-29 17:18:00 -04:00
|
|
|
}
|
|
|
|
*sep = '\0';
|
2015-07-27 20:47:12 -04:00
|
|
|
int result = -1;
|
|
|
|
if (mkdirp(copy, mode) == 0)
|
|
|
|
result = mkdirp(path, mode);
|
2015-03-29 17:18:00 -04:00
|
|
|
free(copy);
|
|
|
|
|
|
|
|
return result;
|
|
|
|
}
|
2015-07-27 20:47:12 -04:00
|
|
|
#endif
|