1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <sys/stat.h>
18#include <string.h>
19#include <stdio.h>
20
21#ifdef HAVE_ANDROID_OS
22#include <linux/capability.h>
23#else
24#include <private/android_filesystem_capability.h>
25#endif
26
27#define XATTR_SELINUX_SUFFIX "selinux"
28#define XATTR_CAPS_SUFFIX "capability"
29
30#include "ext4_utils.h"
31#include "make_ext4fs.h"
32#include "allocate.h"
33#include "contents.h"
34#include "extent.h"
35#include "indirect.h"
36
37#ifdef USE_MINGW
38#define S_IFLNK 0  /* used by make_link, not needed under mingw */
39#endif
40
41static u32 dentry_size(u32 entries, struct dentry *dentries)
42{
43	u32 len = 24;
44	unsigned int i;
45	unsigned int dentry_len;
46
47	for (i = 0; i < entries; i++) {
48		dentry_len = 8 + ALIGN(strlen(dentries[i].filename), 4);
49		if (len % info.block_size + dentry_len > info.block_size)
50			len += info.block_size - (len % info.block_size);
51		len += dentry_len;
52	}
53
54	return len;
55}
56
57static struct ext4_dir_entry_2 *add_dentry(u8 *data, u32 *offset,
58		struct ext4_dir_entry_2 *prev, u32 inode, const char *name,
59		u8 file_type)
60{
61	u8 name_len = strlen(name);
62	u16 rec_len = 8 + ALIGN(name_len, 4);
63	struct ext4_dir_entry_2 *dentry;
64
65	u32 start_block = *offset / info.block_size;
66	u32 end_block = (*offset + rec_len - 1) / info.block_size;
67	if (start_block != end_block) {
68		/* Adding this dentry will cross a block boundary, so pad the previous
69		   dentry to the block boundary */
70		if (!prev)
71			critical_error("no prev");
72		prev->rec_len += end_block * info.block_size - *offset;
73		*offset = end_block * info.block_size;
74	}
75
76	dentry = (struct ext4_dir_entry_2 *)(data + *offset);
77	dentry->inode = inode;
78	dentry->rec_len = rec_len;
79	dentry->name_len = name_len;
80	dentry->file_type = file_type;
81	memcpy(dentry->name, name, name_len);
82
83	*offset += rec_len;
84	return dentry;
85}
86
87/* Creates a directory structure for an array of directory entries, dentries,
88   and stores the location of the structure in an inode.  The new inode's
89   .. link is set to dir_inode_num.  Stores the location of the inode number
90   of each directory entry into dentries[i].inode, to be filled in later
91   when the inode for the entry is allocated.  Returns the inode number of the
92   new directory */
93u32 make_directory(u32 dir_inode_num, u32 entries, struct dentry *dentries,
94	u32 dirs)
95{
96	struct ext4_inode *inode;
97	u32 blocks;
98	u32 len;
99	u32 offset = 0;
100	u32 inode_num;
101	u8 *data;
102	unsigned int i;
103	struct ext4_dir_entry_2 *dentry;
104
105	blocks = DIV_ROUND_UP(dentry_size(entries, dentries), info.block_size);
106	len = blocks * info.block_size;
107
108	if (dir_inode_num) {
109		inode_num = allocate_inode(info);
110	} else {
111		dir_inode_num = EXT4_ROOT_INO;
112		inode_num = EXT4_ROOT_INO;
113	}
114
115	if (inode_num == EXT4_ALLOCATE_FAILED) {
116		error("failed to allocate inode\n");
117		return EXT4_ALLOCATE_FAILED;
118	}
119
120	add_directory(inode_num);
121
122	inode = get_inode(inode_num);
123	if (inode == NULL) {
124		error("failed to get inode %u", inode_num);
125		return EXT4_ALLOCATE_FAILED;
126	}
127
128	data = inode_allocate_data_extents(inode, len, len);
129	if (data == NULL) {
130		error("failed to allocate %u extents", len);
131		return EXT4_ALLOCATE_FAILED;
132	}
133
134	inode->i_mode = S_IFDIR;
135	inode->i_links_count = dirs + 2;
136	inode->i_flags |= aux_info.default_i_flags;
137
138	dentry = NULL;
139
140	dentry = add_dentry(data, &offset, NULL, inode_num, ".", EXT4_FT_DIR);
141	if (!dentry) {
142		error("failed to add . directory");
143		return EXT4_ALLOCATE_FAILED;
144	}
145
146	dentry = add_dentry(data, &offset, dentry, dir_inode_num, "..", EXT4_FT_DIR);
147	if (!dentry) {
148		error("failed to add .. directory");
149		return EXT4_ALLOCATE_FAILED;
150	}
151
152	for (i = 0; i < entries; i++) {
153		dentry = add_dentry(data, &offset, dentry, 0,
154				dentries[i].filename, dentries[i].file_type);
155		if (offset > len || (offset == len && i != entries - 1))
156			critical_error("internal error: dentry for %s ends at %d, past %d\n",
157				dentries[i].filename, offset, len);
158		dentries[i].inode = &dentry->inode;
159		if (!dentry) {
160			error("failed to add directory");
161			return EXT4_ALLOCATE_FAILED;
162		}
163	}
164
165	/* pad the last dentry out to the end of the block */
166	dentry->rec_len += len - offset;
167
168	return inode_num;
169}
170
171/* Creates a file on disk.  Returns the inode number of the new file */
172u32 make_file(const char *filename, u64 len)
173{
174	struct ext4_inode *inode;
175	u32 inode_num;
176
177	inode_num = allocate_inode(info);
178	if (inode_num == EXT4_ALLOCATE_FAILED) {
179		error("failed to allocate inode\n");
180		return EXT4_ALLOCATE_FAILED;
181	}
182
183	inode = get_inode(inode_num);
184	if (inode == NULL) {
185		error("failed to get inode %u", inode_num);
186		return EXT4_ALLOCATE_FAILED;
187	}
188
189	if (len > 0)
190		inode_allocate_file_extents(inode, len, filename);
191
192	inode->i_mode = S_IFREG;
193	inode->i_links_count = 1;
194	inode->i_flags |= aux_info.default_i_flags;
195
196	return inode_num;
197}
198
199/* Creates a file on disk.  Returns the inode number of the new file */
200u32 make_link(const char *link)
201{
202	struct ext4_inode *inode;
203	u32 inode_num;
204	u32 len = strlen(link);
205
206	inode_num = allocate_inode(info);
207	if (inode_num == EXT4_ALLOCATE_FAILED) {
208		error("failed to allocate inode\n");
209		return EXT4_ALLOCATE_FAILED;
210	}
211
212	inode = get_inode(inode_num);
213	if (inode == NULL) {
214		error("failed to get inode %u", inode_num);
215		return EXT4_ALLOCATE_FAILED;
216	}
217
218	inode->i_mode = S_IFLNK;
219	inode->i_links_count = 1;
220	inode->i_flags |= aux_info.default_i_flags;
221	inode->i_size_lo = len;
222
223	if (len + 1 <= sizeof(inode->i_block)) {
224		/* Fast symlink */
225		memcpy((char*)inode->i_block, link, len);
226	} else {
227		u8 *data = inode_allocate_data_indirect(inode, info.block_size, info.block_size);
228		memcpy(data, link, len);
229		inode->i_blocks_lo = info.block_size / 512;
230	}
231
232	return inode_num;
233}
234
235int inode_set_permissions(u32 inode_num, u16 mode, u16 uid, u16 gid, u32 mtime)
236{
237	struct ext4_inode *inode = get_inode(inode_num);
238
239	if (!inode)
240		return -1;
241
242	inode->i_mode |= mode;
243	inode->i_uid = uid;
244	inode->i_gid = gid;
245	inode->i_mtime = mtime;
246	inode->i_atime = mtime;
247	inode->i_ctime = mtime;
248
249	return 0;
250}
251
252/*
253 * Returns the amount of free space available in the specified
254 * xattr region
255 */
256static size_t xattr_free_space(struct ext4_xattr_entry *entry, char *end)
257{
258	while(!IS_LAST_ENTRY(entry) && (((char *) entry) < end)) {
259		end   -= EXT4_XATTR_SIZE(le32_to_cpu(entry->e_value_size));
260		entry  = EXT4_XATTR_NEXT(entry);
261	}
262
263	if (((char *) entry) > end) {
264		error("unexpected read beyond end of xattr space");
265		return 0;
266	}
267
268	return end - ((char *) entry);
269}
270
271/*
272 * Returns a pointer to the free space immediately after the
273 * last xattr element
274 */
275static struct ext4_xattr_entry* xattr_get_last(struct ext4_xattr_entry *entry)
276{
277	for (; !IS_LAST_ENTRY(entry); entry = EXT4_XATTR_NEXT(entry)) {
278		// skip entry
279	}
280	return entry;
281}
282
283/*
284 * assert that the elements in the ext4 xattr section are in sorted order
285 *
286 * The ext4 filesystem requires extended attributes to be sorted when
287 * they're not stored in the inode. The kernel ext4 code uses the following
288 * sorting algorithm:
289 *
290 * 1) First sort extended attributes by their name_index. For example,
291 *    EXT4_XATTR_INDEX_USER (1) comes before EXT4_XATTR_INDEX_SECURITY (6).
292 * 2) If the name_indexes are equal, then sorting is based on the length
293 *    of the name. For example, XATTR_SELINUX_SUFFIX ("selinux") comes before
294 *    XATTR_CAPS_SUFFIX ("capability") because "selinux" is shorter than "capability"
295 * 3) If the name_index and name_length are equal, then memcmp() is used to determine
296 *    which name comes first. For example, "selinux" would come before "yelinux".
297 *
298 * This method is intended to implement the sorting function defined in
299 * the Linux kernel file fs/ext4/xattr.c function ext4_xattr_find_entry().
300 */
301static void xattr_assert_sane(struct ext4_xattr_entry *entry)
302{
303	for( ; !IS_LAST_ENTRY(entry); entry = EXT4_XATTR_NEXT(entry)) {
304		struct ext4_xattr_entry *next = EXT4_XATTR_NEXT(entry);
305		if (IS_LAST_ENTRY(next)) {
306			return;
307		}
308
309		int cmp = next->e_name_index - entry->e_name_index;
310		if (cmp == 0)
311			cmp = next->e_name_len - entry->e_name_len;
312		if (cmp == 0)
313			cmp = memcmp(next->e_name, entry->e_name, next->e_name_len);
314		if (cmp < 0) {
315			error("BUG: extended attributes are not sorted\n");
316			return;
317		}
318		if (cmp == 0) {
319			error("BUG: duplicate extended attributes detected\n");
320			return;
321		}
322	}
323}
324
325#define NAME_HASH_SHIFT 5
326#define VALUE_HASH_SHIFT 16
327
328static void ext4_xattr_hash_entry(struct ext4_xattr_header *header,
329		struct ext4_xattr_entry *entry)
330{
331	u32 hash = 0;
332	char *name = entry->e_name;
333	int n;
334
335	for (n = 0; n < entry->e_name_len; n++) {
336		hash = (hash << NAME_HASH_SHIFT) ^
337			(hash >> (8*sizeof(hash) - NAME_HASH_SHIFT)) ^
338			*name++;
339	}
340
341	if (entry->e_value_block == 0 && entry->e_value_size != 0) {
342		u32 *value = (u32 *)((char *)header +
343			le16_to_cpu(entry->e_value_offs));
344		for (n = (le32_to_cpu(entry->e_value_size) +
345			EXT4_XATTR_ROUND) >> EXT4_XATTR_PAD_BITS; n; n--) {
346			hash = (hash << VALUE_HASH_SHIFT) ^
347				(hash >> (8*sizeof(hash) - VALUE_HASH_SHIFT)) ^
348				le32_to_cpu(*value++);
349		}
350	}
351	entry->e_hash = cpu_to_le32(hash);
352}
353
354#undef NAME_HASH_SHIFT
355#undef VALUE_HASH_SHIFT
356
357static struct ext4_xattr_entry* xattr_addto_range(
358		void *block_start,
359		void *block_end,
360		struct ext4_xattr_entry *first,
361		int name_index,
362		const char *name,
363		const void *value,
364		size_t value_len)
365{
366	size_t name_len = strlen(name);
367	if (name_len > 255)
368		return NULL;
369
370	size_t available_size = xattr_free_space(first, block_end);
371	size_t needed_size = EXT4_XATTR_LEN(name_len) + EXT4_XATTR_SIZE(value_len);
372
373	if (needed_size > available_size)
374		return NULL;
375
376	struct ext4_xattr_entry *new_entry = xattr_get_last(first);
377	memset(new_entry, 0, EXT4_XATTR_LEN(name_len));
378
379	new_entry->e_name_len = name_len;
380	new_entry->e_name_index = name_index;
381	memcpy(new_entry->e_name, name, name_len);
382	new_entry->e_value_block = 0;
383	new_entry->e_value_size = cpu_to_le32(value_len);
384
385	char *val = (char *) new_entry + available_size - EXT4_XATTR_SIZE(value_len);
386	size_t e_value_offs = val - (char *) block_start;
387
388	new_entry->e_value_offs = cpu_to_le16(e_value_offs);
389	memset(val, 0, EXT4_XATTR_SIZE(value_len));
390	memcpy(val, value, value_len);
391
392	xattr_assert_sane(first);
393	return new_entry;
394}
395
396static int xattr_addto_inode(struct ext4_inode *inode, int name_index,
397		const char *name, const void *value, size_t value_len)
398{
399	struct ext4_xattr_ibody_header *hdr = (struct ext4_xattr_ibody_header *) (inode + 1);
400	struct ext4_xattr_entry *first = (struct ext4_xattr_entry *) (hdr + 1);
401	char *block_end = ((char *) inode) + info.inode_size;
402
403	struct ext4_xattr_entry *result =
404		xattr_addto_range(first, block_end, first, name_index, name, value, value_len);
405
406	if (result == NULL)
407		return -1;
408
409	hdr->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);
410	inode->i_extra_isize = cpu_to_le16(sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE);
411
412	return 0;
413}
414
415static int xattr_addto_block(struct ext4_inode *inode, int name_index,
416		const char *name, const void *value, size_t value_len)
417{
418	struct ext4_xattr_header *header = get_xattr_block_for_inode(inode);
419	if (!header)
420		return -1;
421
422	struct ext4_xattr_entry *first = (struct ext4_xattr_entry *) (header + 1);
423	char *block_end = ((char *) header) + info.block_size;
424
425	struct ext4_xattr_entry *result =
426		xattr_addto_range(header, block_end, first, name_index, name, value, value_len);
427
428	if (result == NULL)
429		return -1;
430
431	ext4_xattr_hash_entry(header, result);
432	return 0;
433}
434
435
436static int xattr_add(u32 inode_num, int name_index, const char *name,
437		const void *value, size_t value_len)
438{
439	if (!value)
440		return 0;
441
442	struct ext4_inode *inode = get_inode(inode_num);
443
444	if (!inode)
445		return -1;
446
447	int result = xattr_addto_inode(inode, name_index, name, value, value_len);
448	if (result != 0) {
449		result = xattr_addto_block(inode, name_index, name, value, value_len);
450	}
451	return result;
452}
453
454int inode_set_selinux(u32 inode_num, const char *secon)
455{
456	if (!secon)
457		return 0;
458
459	return xattr_add(inode_num, EXT4_XATTR_INDEX_SECURITY,
460		XATTR_SELINUX_SUFFIX, secon, strlen(secon) + 1);
461}
462
463int inode_set_capabilities(u32 inode_num, uint64_t capabilities) {
464	if (capabilities == 0)
465		return 0;
466
467	struct vfs_cap_data cap_data;
468	memset(&cap_data, 0, sizeof(cap_data));
469
470	cap_data.magic_etc = VFS_CAP_REVISION | VFS_CAP_FLAGS_EFFECTIVE;
471	cap_data.data[0].permitted = (uint32_t) (capabilities & 0xffffffff);
472	cap_data.data[0].inheritable = 0;
473	cap_data.data[1].permitted = (uint32_t) (capabilities >> 32);
474	cap_data.data[1].inheritable = 0;
475
476	return xattr_add(inode_num, EXT4_XATTR_INDEX_SECURITY,
477		XATTR_CAPS_SUFFIX, &cap_data, sizeof(cap_data));
478}
479
480