aboutsummaryrefslogtreecommitdiff
path: root/src/libnpass/util.c
blob: 182f117bb459f5105c85d96ba19dc15d5fa94490 (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
#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)
{
	int r;
	size_t len;
	char *p;
	char tmp[NAME_MAX];

	strncpy(tmp, path, sizeof(tmp) - 1);
	len = strlen(tmp);
	if (tmp[len - 1] == '/')
		tmp[len - 1] = '\0';

	for (p = tmp + 1; *p; ++p) {
		if (*p == '/') {
			*p = '\0';

			r = mkdir(tmp, mode);
			if (r && !(errno & EEXIST))
				return r;

			*p = '/';
		}
	}

	return mkdir(path, mode);
}

int r_rmdir(const char *prefix_path, char *rm_path)
{
	int r;
	char abs_path[PATH_MAX];

	if (!strcmp(rm_path, "."))
		return 0;

	r = snprintf(abs_path, sizeof(abs_path), "%s/%s", prefix_path, rm_path);
	if (r > (int)sizeof(abs_path))
		err_ret(1, "path exceeded PATH_MAX");

	r = rmdir(abs_path);
	if (r && errno != EEXIST && errno != ENOTEMPTY)
		err_ret(1, "%s", strerror(errno));

	return r_rmdir(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';
}