aboutsummaryrefslogtreecommitdiff
path: root/src/libnpass/util.c
blob: 7f2f488942650ee172cc9668a5f824e78c8020ab (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#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)
		err_ret(-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))
				err_ret(-errno, "%s", strerror(errno));

			*p = '/';
		}
	}

	ret = mkdir(path, mode);
	if (ret < 0 && !(errno & EEXIST))
		err_ret(-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))
		err_ret(-EINVAL, "%s", "Path exceeded PATH_MAX");

	r = rmdir(abs_path);
	if (r < 0 && errno != EEXIST && errno != ENOTEMPTY)
		err_ret(-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;

	rend[1] = '\0';
}