aboutsummaryrefslogtreecommitdiff
path: root/lib/fstree/add_by_path.c
blob: 7e0a4ced807c49c7f31907e1d2276cd0e976d7f3 (plain)
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
74
75
76
77
78
79
80
81
82
83
84
85
86
/* SPDX-License-Identifier: GPL-3.0-or-later */
#include "fstree.h"

#include <string.h>
#include <errno.h>

static tree_node_t *child_by_name(tree_node_t *root, const char *name,
				  size_t len)
{
	tree_node_t *n = root->data.dir->children;

	while (n != NULL) {
		if (strncmp(n->name, name, len) == 0 && n->name[len] == '\0')
			break;

		n = n->next;
	}

	return n;
}

static tree_node_t *get_parent_node(fstree_t *fs, tree_node_t *root,
				    const char *path)
{
	const char *end;
	tree_node_t *n;

	for (;;) {
		if (!S_ISDIR(root->mode)) {
			errno = ENOTDIR;
			return NULL;
		}

		end = strchr(path, '/');
		if (end == NULL)
			break;

		n = child_by_name(root, path, end - path);

		if (n == NULL) {
			n = fstree_mknode(fs, root, path, end - path, NULL,
					  &fs->defaults);
			if (n == NULL)
				return NULL;

			n->data.dir->created_implicitly = true;
		}

		root = n;
		path = end + 1;
	}

	return root;
}

tree_node_t *fstree_add_generic(fstree_t *fs, const char *path,
				const struct stat *sb, const char *extra)
{
	tree_node_t *child, *parent;
	const char *name;

	parent = get_parent_node(fs, fs->root, path);
	if (parent == NULL)
		return NULL;

	name = strrchr(path, '/');
	name = (name == NULL ? path : (name + 1));

	child = child_by_name(parent, name, strlen(name));
	if (child != NULL) {
		if (!S_ISDIR(child->mode) || !S_ISDIR(sb->st_mode) ||
		    !child->data.dir->created_implicitly) {
			errno = EEXIST;
			return NULL;
		}

		child->uid = sb->st_uid;
		child->gid = sb->st_gid;
		child->mode = sb->st_mode;
		child->mod_time = sb->st_mtime;
		child->data.dir->created_implicitly = false;
		return child;
	}

	return fstree_mknode(fs, parent, name, strlen(name), extra, sb);
}