summaryrefslogtreecommitdiff
path: root/lib/fstree/mknode.c
blob: 1c3b3a06ac80a13adec322d92ac2e48ccd6f7a56 (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
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
 * mknode.c
 *
 * Copyright (C) 2019 David Oberhollenzer <goliath@infraroot.at>
 */
#include "config.h"

#include "fstree.h"
#include "util.h"

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

tree_node_t *fstree_mknode(fstree_t *fs, tree_node_t *parent, const char *name,
			   size_t name_len, const char *extra,
			   const struct stat *sb)
{
	size_t size = sizeof(tree_node_t), block_count = 0, total;
	tree_node_t *n;
	char *ptr;

	switch (sb->st_mode & S_IFMT) {
	case S_IFLNK:
		if (extra == NULL) {
			errno = EINVAL;
			return NULL;
		}
		if (SZ_ADD_OV(size, strlen(extra), &size) ||
		    SZ_ADD_OV(size, 1, &size)) {
			goto fail_ov;
		}
		break;
	case S_IFDIR:
		if (SZ_ADD_OV(size, sizeof(*n->data.dir), &size))
			goto fail_ov;
		break;
	case S_IFREG:
		block_count = (sb->st_size / fs->block_size);
		if ((sb->st_size % fs->block_size) != 0)
			++block_count;

		if (SZ_MUL_OV(block_count, sizeof(n->data.file->blocks[0]),
			      &total)) {
			goto fail_ov;
		}

		if (SZ_ADD_OV(size, sizeof(*n->data.file), &size) ||
		    SZ_ADD_OV(size, total, &size)) {
			goto fail_ov;
		}

		if (extra != NULL) {
			if (SZ_ADD_OV(size, strlen(extra), &size) ||
			    SZ_ADD_OV(size, 1, &size)) {
				goto fail_ov;
			}
		}
		break;
	}

	if (SZ_ADD_OV(size, name_len, &total) ||
	    SZ_ADD_OV(total, 1, &total)) {
		goto fail_ov;
	}

	n = calloc(1, total);
	if (n == NULL)
		return NULL;

	if (parent != NULL) {
		n->next = parent->data.dir->children;
		parent->data.dir->children = n;
		n->parent = parent;
	}

	n->uid = sb->st_uid;
	n->gid = sb->st_gid;
	n->mode = sb->st_mode;
	n->mod_time = sb->st_mtime;

	switch (sb->st_mode & S_IFMT) {
	case S_IFDIR:
		n->data.dir = (dir_info_t *)n->payload;
		break;
	case S_IFREG:
		n->data.file = (file_info_t *)n->payload;
		n->data.file->size = sb->st_size;
		n->data.file->fragment = 0xFFFFFFFF;
		n->data.file->fragment_offset = 0xFFFFFFFF;
		if (extra == NULL)
			break;

		ptr = (char *)n->data.file->blocks;
		ptr += block_count * sizeof(n->data.file->blocks[0]);
		n->data.file->input_file = ptr;
		strcpy(n->data.file->input_file, extra);
		break;
	case S_IFLNK:
		n->mode = S_IFLNK | 0777;
		n->data.slink_target = (char *)n->payload;
		if (extra != NULL)
			strcpy(n->data.slink_target, extra);
		break;
	case S_IFBLK:
	case S_IFCHR:
		n->data.devno = sb->st_rdev;
		break;
	}

	n->name = (char *)n + size;
	memcpy(n->name, name, name_len);
	return n;
fail_ov:
	errno = EOVERFLOW;
	return NULL;
}