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