#include <sys/stat.h>
#include <ctype.h>
#include <errno.h>
#include <libgen.h>
#include <linux/limits.h>
#include <string.h>
#include <unistd.h>
#include "libnpass/util.h"
#include "util.h"
int r_mkdir(const char *path, mode_t mode)
{
char path_cp[PATH_MAX];
size_t len;
char *p;
int ret;
len = strlen(path);
if (len >= PATH_MAX)
return_err(-EINVAL, "%s", "Path exceeded PATH_MAX");
strcpy(path_cp, path);
for (p = path_cp + 1; *p; ++p) {
if (*p == '/') {
*p = '\0';
ret = mkdir(path_cp, mode);
if (ret < 0 && !(errno & EEXIST))
return_err(-errno, "%s", strerror(errno));
*p = '/';
}
}
ret = mkdir(path, mode);
if (ret < 0 && !(errno & EEXIST))
return_err(-errno, "%s", strerror(errno));
return 0;
}
int r_rmdir_empty(const char *prefix_path, char *rm_path)
{
char abs_path[PATH_MAX];
int r;
r = strcmp(rm_path, ".");
if (r == 0)
return 0;
r = snprintf(abs_path, sizeof(abs_path), "%s/%s", prefix_path, rm_path);
if (r < 0 || (size_t)r >= sizeof(abs_path))
return_err(-EINVAL, "%s", "Path exceeded PATH_MAX");
r = rmdir(abs_path);
if (r < 0 && errno != EEXIST && errno != ENOTEMPTY)
return_err(-errno, "%s", strerror(errno));
return r_rmdir_empty(prefix_path, dirname(rm_path));
}
void util_strtrim(char *s)
{
char *rend;
for (rend = s; *s; ++s)
if (!isspace(*s))
rend = s;
if (*rend)
rend[1] = '\0';
}