aboutsummaryrefslogtreecommitdiff
path: root/bin/gensquashfs/src/fstree_from_dir.c
blob: 25a6bd788cc7d0b6de02d92ff0982819a6ecc265 (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
118
119
120
121
122
123
124
125
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
 * fstree_from_dir.c
 *
 * Copyright (C) 2019 David Oberhollenzer <goliath@infraroot.at>
 */
#include "config.h"
#include "mkfs.h"

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

static sqfs_u32 clamp_timestamp(sqfs_s64 ts)
{
	if (ts < 0)
		return 0;
	if (ts > 0x0FFFFFFFFLL)
		return 0xFFFFFFFF;
	return ts;
}

static void discard_node(tree_node_t *root, tree_node_t *n)
{
	tree_node_t *it;

	if (n == root->data.children) {
		root->data.children = n->next;
	} else {
		it = root->data.children;

		while (it != NULL && it->next != n)
			it = it->next;

		if (it != NULL)
			it->next = n->next;
	}

	free(n);
}

static int scan_dir(fstree_t *fs, tree_node_t *root, dir_iterator_t *dir,
		    scan_node_callback cb, void *user)
{
	for (;;) {
		dir_entry_t *ent = NULL;
		tree_node_t *n = NULL;
		char *extra = NULL;
		struct stat sb;

		int ret = dir->next(dir, &ent);
		if (ret > 0)
			break;
		if (ret < 0) {
			sqfs_perror("readdir", NULL, ret);
			return -1;
		}

		n = fstree_get_node_by_path(fs, root, ent->name, false, true);
		if (n == NULL) {
			if (S_ISDIR(ent->mode))
				dir_tree_iterator_skip(dir);
			free(ent);
			continue;
		}

		if (S_ISLNK(ent->mode)) {
			ret = dir->read_link(dir, &extra);
			if (ret) {
				free(ent);
				sqfs_perror("readlink", ent->name, ret);
				return -1;
			}
		}

		memset(&sb, 0, sizeof(sb));
		sb.st_uid = ent->uid;
		sb.st_gid = ent->gid;
		sb.st_mode = ent->mode;
		sb.st_mtime = clamp_timestamp(ent->mtime);

		n = fstree_add_generic_at(fs, root, ent->name, &sb, extra);
		free(extra);
		free(ent);

		if (n == NULL) {
			perror("creating tree node");
			return -1;
		}

		ret = (cb == NULL) ? 0 : cb(user, fs, n);

		if (ret < 0)
			return -1;

		if (ret > 0) {
			if (S_ISDIR(n->mode))
				dir_tree_iterator_skip(dir);
			discard_node(n->parent, n);
		}
	}

	return 0;
}

int fstree_from_dir(fstree_t *fs, tree_node_t *root, const char *path,
		    scan_node_callback cb, void *user, unsigned int flags)
{
	dir_iterator_t *dir;
	dir_tree_cfg_t cfg;
	int ret;

	memset(&cfg, 0, sizeof(cfg));
	cfg.flags = flags;
	cfg.def_mtime = fs->defaults.mtime;

	dir = dir_tree_iterator_create(path, &cfg);
	if (dir == NULL)
		return -1;

	ret = scan_dir(fs, root, dir, cb, user);
	sqfs_drop(dir);
	return ret;
}