summaryrefslogtreecommitdiff
path: root/lib/common/hardlink.c
blob: f28620f51d114b3a4e410a917c20d336309b1ade (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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
 * hardlink.c
 *
 * Copyright (C) 2019 David Oberhollenzer <goliath@infraroot.at>
 */
#include "common.h"
#include "util/rbtree.h"
#include "util/util.h"

#include <stdlib.h>
#include <assert.h>
#include <stdio.h>

static int map_nodes(rbtree_t *inumtree, sqfs_hard_link_t **out,
		     const sqfs_tree_node_t *n)
{
	const sqfs_tree_node_t *target;
	sqfs_hard_link_t *lnk;
	rbtree_node_t *tn;
	sqfs_u32 idx;
	int ret;

	/* XXX: refuse to generate hard links to directories */
	if (n->children != NULL) {
		for (n = n->children; n != NULL; n = n->next) {
			if (map_nodes(inumtree, out, n))
				return -1;
		}
		return 0;
	}

	if (!is_filename_sane((const char *)n->name, false))
		return 0;

	idx = n->inode->base.inode_number;
	tn = rbtree_lookup(inumtree, &idx);

	if (tn == NULL) {
		ret = rbtree_insert(inumtree, &idx, &n);
		if (ret != 0)
			goto fail_insert;
		return 0;
	}

	target = *((const sqfs_tree_node_t **)rbtree_node_value(tn));

	lnk = calloc(1, sizeof(*lnk));
	if (lnk == NULL)
		goto fail_oom;

	lnk->inode_number = idx;
	ret = sqfs_tree_node_get_path(target, &lnk->target);
	if (ret != 0)
		goto fail_path;

	if (canonicalize_name(lnk->target) == 0) {
		lnk->next = (*out);
		(*out) = lnk;
	} else {
		sqfs_free(lnk->target);
		free(lnk);
	}
	return 0;
fail_path:
	sqfs_perror(NULL, "re-constructing hard link path", ret);
	free(lnk);
	return -1;
fail_oom:
	fputs("detecting hard links in file system tree: out of memory\n",
	      stderr);
	free(lnk);
	return -1;
fail_insert:
	sqfs_perror(NULL, "detecting hard links in file system tree", ret);
	return -1;
}

static int compare_inum(const void *ctx, const void *lhs, const void *rhs)
{
	sqfs_u32 l = *((const sqfs_u32 *)lhs), r = *((const sqfs_u32 *)rhs);
	(void)ctx;

	return l < r ? -1 : (l > r ? 1 : 0);
}

int sqfs_tree_find_hard_links(const sqfs_tree_node_t *root,
			      sqfs_hard_link_t **out)
{
	sqfs_hard_link_t *lnk = NULL;
	rbtree_t inumtree;
	int ret;

	ret = rbtree_init(&inumtree, sizeof(sqfs_u32),
			  sizeof(sqfs_tree_node_t *),
			  compare_inum);
	if (ret != 0) {
		sqfs_perror(NULL,
			    "detecting hard links in file system tree", ret);
		return -1;
	}

	ret = map_nodes(&inumtree, out, root);
	rbtree_cleanup(&inumtree);

	if (ret != 0) {
		while ((*out) != NULL) {
			lnk = (*out);
			(*out) = lnk->next;
			free(lnk->target);
			free(lnk);
		}
		return -1;
	}

	return 0;
}