1 /*
2 	node.c (09.10.09)
3 	exFAT file system implementation library.
4 
5 	Free exFAT implementation.
6 	Copyright (C) 2010-2023  Andrew Nayenko
7 
8 	This program is free software; you can redistribute it and/or modify
9 	it under the terms of the GNU General Public License as published by
10 	the Free Software Foundation, either version 2 of the License, or
11 	(at your option) any later version.
12 
13 	This program is distributed in the hope that it will be useful,
14 	but WITHOUT ANY WARRANTY; without even the implied warranty of
15 	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 	GNU General Public License for more details.
17 
18 	You should have received a copy of the GNU General Public License along
19 	with this program; if not, write to the Free Software Foundation, Inc.,
20 	51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
22 
23 #include "exfat.h"
24 #include <errno.h>
25 #include <string.h>
26 #include <inttypes.h>
27 
28 #define EXFAT_ENTRY_NONE (-1)
29 
exfat_get_node(struct exfat_node * node)30 struct exfat_node* exfat_get_node(struct exfat_node* node)
31 {
32 	/* if we switch to multi-threaded mode we will need atomic
33 	   increment here and atomic decrement in exfat_put_node() */
34 	node->references++;
35 	return node;
36 }
37 
exfat_put_node(struct exfat * ef,struct exfat_node * node)38 void exfat_put_node(struct exfat* ef, struct exfat_node* node)
39 {
40 	char buffer[EXFAT_UTF8_NAME_BUFFER_MAX];
41 
42 	--node->references;
43 	if (node->references < 0)
44 	{
45 		exfat_get_name(node, buffer);
46 		exfat_bug("reference counter of '%s' is below zero", buffer);
47 	}
48 	else if (node->references == 0 && node != ef->root)
49 	{
50 		if (node->is_dirty)
51 		{
52 			exfat_get_name(node, buffer);
53 			exfat_warn("dirty node '%s' with zero references", buffer);
54 		}
55 	}
56 }
57 
58 /**
59  * This function must be called on rmdir and unlink (after the last
60  * exfat_put_node()) to free clusters.
61  */
exfat_cleanup_node(struct exfat * ef,struct exfat_node * node)62 int exfat_cleanup_node(struct exfat* ef, struct exfat_node* node)
63 {
64 	int rc = 0;
65 
66 	if (node->references != 0)
67 		exfat_bug("unable to cleanup a node with %d references",
68 				node->references);
69 
70 	if (node->is_unlinked)
71 	{
72 		/* free all clusters and node structure itself */
73 		rc = exfat_truncate(ef, node, 0, true);
74 		/* free the node even in case of error or its memory will be lost */
75 		free(node);
76 	}
77 	return rc;
78 }
79 
read_entries(struct exfat * ef,struct exfat_node * dir,struct exfat_entry * entries,int n,off_t offset)80 static int read_entries(struct exfat* ef, struct exfat_node* dir,
81 		struct exfat_entry* entries, int n, off_t offset)
82 {
83 	ssize_t size;
84 
85 	if (!(dir->attrib & EXFAT_ATTRIB_DIR))
86 		exfat_bug("attempted to read entries from a file");
87 
88 	size = exfat_generic_pread(ef, dir, entries,
89 			sizeof(struct exfat_entry[n]), offset);
90 	if (size == (ssize_t) sizeof(struct exfat_entry) * n)
91 		return 0; /* success */
92 	if (size == 0)
93 		return -ENOENT;
94 	if (size < 0)
95 		return -EIO;
96 	exfat_error("read %zd bytes instead of %zu bytes", size,
97 			sizeof(struct exfat_entry[n]));
98 	return -EIO;
99 }
100 
write_entries(struct exfat * ef,struct exfat_node * dir,const struct exfat_entry * entries,int n,off_t offset)101 static int write_entries(struct exfat* ef, struct exfat_node* dir,
102 		const struct exfat_entry* entries, int n, off_t offset)
103 {
104 	ssize_t size;
105 
106 	if (!(dir->attrib & EXFAT_ATTRIB_DIR))
107 		exfat_bug("attempted to write entries into a file");
108 
109 	size = exfat_generic_pwrite(ef, dir, entries,
110 			sizeof(struct exfat_entry[n]), offset);
111 	if (size == (ssize_t) sizeof(struct exfat_entry) * n)
112 		return 0; /* success */
113 	if (size < 0)
114 		return -EIO;
115 	exfat_error("wrote %zd bytes instead of %zu bytes", size,
116 			sizeof(struct exfat_entry[n]));
117 	return -EIO;
118 }
119 
allocate_node(void)120 static struct exfat_node* allocate_node(void)
121 {
122 	struct exfat_node* node = malloc(sizeof(struct exfat_node));
123 	if (node == NULL)
124 	{
125 		exfat_error("failed to allocate node");
126 		return NULL;
127 	}
128 	memset(node, 0, sizeof(struct exfat_node));
129 	return node;
130 }
131 
init_node_meta1(struct exfat_node * node,const struct exfat_entry_meta1 * meta1)132 static void init_node_meta1(struct exfat_node* node,
133 		const struct exfat_entry_meta1* meta1)
134 {
135 	node->attrib = le16_to_cpu(meta1->attrib);
136 	node->continuations = meta1->continuations;
137 	node->mtime = exfat_exfat2unix(meta1->mdate, meta1->mtime,
138 			meta1->mtime_cs, meta1->mtime_tzo);
139 	/* there is no centiseconds field for atime */
140 	node->atime = exfat_exfat2unix(meta1->adate, meta1->atime,
141 			0, meta1->atime_tzo);
142 }
143 
init_node_meta2(struct exfat_node * node,const struct exfat_entry_meta2 * meta2)144 static void init_node_meta2(struct exfat_node* node,
145 		const struct exfat_entry_meta2* meta2)
146 {
147 	node->valid_size = le64_to_cpu(meta2->valid_size);
148 	node->size = le64_to_cpu(meta2->size);
149 	node->start_cluster = le32_to_cpu(meta2->start_cluster);
150 	node->fptr_cluster = node->start_cluster;
151 	node->is_contiguous = ((meta2->flags & EXFAT_FLAG_CONTIGUOUS) != 0);
152 }
153 
init_node_name(struct exfat_node * node,const struct exfat_entry * entries,int n)154 static void init_node_name(struct exfat_node* node,
155 		const struct exfat_entry* entries, int n)
156 {
157 	int i;
158 
159 	for (i = 0; i < n; i++)
160 		memcpy(node->name + i * EXFAT_ENAME_MAX,
161 				((const struct exfat_entry_name*) &entries[i])->name,
162 				EXFAT_ENAME_MAX * sizeof(le16_t));
163 }
164 
check_entries(const struct exfat_entry * entry,int n)165 static bool check_entries(const struct exfat_entry* entry, int n)
166 {
167 	int previous = EXFAT_ENTRY_NONE;
168 	int current;
169 	int i;
170 
171 	/* check transitions between entries types */
172 	for (i = 0; i < n + 1; previous = current, i++)
173 	{
174 		bool valid = false;
175 
176 		current = (i < n) ? entry[i].type : EXFAT_ENTRY_NONE;
177 		switch (previous)
178 		{
179 		case EXFAT_ENTRY_NONE:
180 			valid = (current == EXFAT_ENTRY_FILE);
181 			break;
182 		case EXFAT_ENTRY_FILE:
183 			valid = (current == EXFAT_ENTRY_FILE_INFO);
184 			break;
185 		case EXFAT_ENTRY_FILE_INFO:
186 			valid = (current == EXFAT_ENTRY_FILE_NAME);
187 			break;
188 		case EXFAT_ENTRY_FILE_NAME:
189 			valid = (current == EXFAT_ENTRY_FILE_NAME ||
190 			         current == EXFAT_ENTRY_NONE ||
191 			         current >= EXFAT_ENTRY_FILE_TAIL);
192 			break;
193 		case EXFAT_ENTRY_FILE_TAIL ... 0xff:
194 			valid = (current >= EXFAT_ENTRY_FILE_TAIL ||
195 			         current == EXFAT_ENTRY_NONE);
196 			break;
197 		}
198 
199 		if (!valid)
200 		{
201 			exfat_error("unexpected entry type %#x after %#x at %d/%d",
202 					current, previous, i, n);
203 			return false;
204 		}
205 	}
206 	return true;
207 }
208 
check_node(const struct exfat * ef,struct exfat_node * node,le16_t actual_checksum,const struct exfat_entry_meta1 * meta1)209 static bool check_node(const struct exfat* ef, struct exfat_node* node,
210 		le16_t actual_checksum, const struct exfat_entry_meta1* meta1)
211 {
212 	int cluster_size = CLUSTER_SIZE(*ef->sb);
213 	uint64_t clusters_heap_size =
214 			(uint64_t) le32_to_cpu(ef->sb->cluster_count) * cluster_size;
215 	char buffer[EXFAT_UTF8_NAME_BUFFER_MAX];
216 	bool ret = true;
217 
218 	/*
219 	   Validate checksum first. If it's invalid all other fields probably
220 	   contain just garbage.
221 	*/
222 	if (le16_to_cpu(actual_checksum) != le16_to_cpu(meta1->checksum))
223 	{
224 		exfat_get_name(node, buffer);
225 		exfat_error("'%s' has invalid checksum (%#hx != %#hx)", buffer,
226 				le16_to_cpu(actual_checksum), le16_to_cpu(meta1->checksum));
227 		if (!EXFAT_REPAIR(invalid_node_checksum, ef, node))
228 			ret = false;
229 	}
230 
231 	/*
232 	   exFAT does not support sparse files but allows files with uninitialized
233 	   clusters. For such files valid_size means initialized data size and
234 	   cannot be greater than file size. See SetFileValidData() function
235 	   description in MSDN.
236 	*/
237 	if (node->valid_size > node->size)
238 	{
239 		exfat_get_name(node, buffer);
240 		exfat_error("'%s' has valid size (%"PRIu64") greater than size "
241 				"(%"PRIu64")", buffer, node->valid_size, node->size);
242 		ret = false;
243 	}
244 
245 	/*
246 	   Empty file must have zero start cluster. Non-empty file must start
247 	   with a valid cluster. Directories cannot be empty (i.e. must always
248 	   have a valid start cluster), but we will check this later while
249 	   reading that directory to give user a chance to read this directory.
250 	*/
251 	if (node->size == 0 && node->start_cluster != EXFAT_CLUSTER_FREE)
252 	{
253 		exfat_get_name(node, buffer);
254 		exfat_error("'%s' is empty but start cluster is %#x", buffer,
255 				node->start_cluster);
256 		ret = false;
257 	}
258 	if (node->size > 0 && CLUSTER_INVALID(*ef->sb, node->start_cluster))
259 	{
260 		exfat_get_name(node, buffer);
261 		exfat_error("'%s' points to invalid cluster %#x", buffer,
262 				node->start_cluster);
263 		ret = false;
264 	}
265 
266 	/* File or directory cannot be larger than clusters heap. */
267 	if (node->size > clusters_heap_size)
268 	{
269 		exfat_get_name(node, buffer);
270 		exfat_error("'%s' is larger than clusters heap: %"PRIu64" > %"PRIu64,
271 				buffer, node->size, clusters_heap_size);
272 		ret = false;
273 	}
274 
275 	/* Empty file or directory must be marked as non-contiguous. */
276 	if (node->size == 0 && node->is_contiguous)
277 	{
278 		exfat_get_name(node, buffer);
279 		exfat_error("'%s' is empty but marked as contiguous (%#hx)", buffer,
280 				node->attrib);
281 		ret = false;
282 	}
283 
284 	/* Directory size must be aligned on at cluster boundary. */
285 	if ((node->attrib & EXFAT_ATTRIB_DIR) && node->size % cluster_size != 0)
286 	{
287 		exfat_get_name(node, buffer);
288 		exfat_error("'%s' directory size %"PRIu64" is not divisible by %d", buffer,
289 				node->size, cluster_size);
290 		ret = false;
291 	}
292 
293 	return ret;
294 }
295 
parse_file_entries(struct exfat * ef,struct exfat_node * node,const struct exfat_entry * entries,int n)296 static int parse_file_entries(struct exfat* ef, struct exfat_node* node,
297 		const struct exfat_entry* entries, int n)
298 {
299 	const struct exfat_entry_meta1* meta1;
300 	const struct exfat_entry_meta2* meta2;
301 	int mandatory_entries;
302 
303 	if (!check_entries(entries, n))
304 		return -EIO;
305 
306 	meta1 = (const struct exfat_entry_meta1*) &entries[0];
307 	if (meta1->continuations < 2)
308 	{
309 		exfat_error("too few continuations (%hhu)", meta1->continuations);
310 		return -EIO;
311 	}
312 	meta2 = (const struct exfat_entry_meta2*) &entries[1];
313 	if (meta2->flags & ~(EXFAT_FLAG_ALWAYS1 | EXFAT_FLAG_CONTIGUOUS))
314 	{
315 		exfat_error("unknown flags in meta2 (%#hhx)", meta2->flags);
316 		return -EIO;
317 	}
318 	mandatory_entries = 2 + DIV_ROUND_UP(meta2->name_length, EXFAT_ENAME_MAX);
319 	if (meta1->continuations < mandatory_entries - 1)
320 	{
321 		exfat_error("too few continuations (%hhu < %d)",
322 				meta1->continuations, mandatory_entries - 1);
323 		return -EIO;
324 	}
325 
326 	init_node_meta1(node, meta1);
327 	init_node_meta2(node, meta2);
328 	init_node_name(node, entries + 2, mandatory_entries - 2);
329 
330 	if (!check_node(ef, node, exfat_calc_checksum(entries, n), meta1))
331 		return -EIO;
332 
333 	return 0;
334 }
335 
parse_file_entry(struct exfat * ef,struct exfat_node * parent,struct exfat_node ** node,off_t * offset,int n)336 static int parse_file_entry(struct exfat* ef, struct exfat_node* parent,
337 		struct exfat_node** node, off_t* offset, int n)
338 {
339 	struct exfat_entry entries[n];
340 	int rc;
341 
342 	rc = read_entries(ef, parent, entries, n, *offset);
343 	if (rc != 0)
344 		return rc;
345 
346 	/* a new node has zero references */
347 	*node = allocate_node();
348 	if (*node == NULL)
349 		return -ENOMEM;
350 	(*node)->entry_offset = *offset;
351 
352 	rc = parse_file_entries(ef, *node, entries, n);
353 	if (rc != 0)
354 	{
355 		free(*node);
356 		return rc;
357 	}
358 
359 	*offset += sizeof(struct exfat_entry[n]);
360 	return 0;
361 }
362 
decompress_upcase(uint16_t * output,const le16_t * source,size_t size)363 static void decompress_upcase(uint16_t* output, const le16_t* source,
364 		size_t size)
365 {
366 	size_t si;
367 	size_t oi;
368 
369 	for (oi = 0; oi < EXFAT_UPCASE_CHARS; oi++)
370 		output[oi] = oi;
371 
372 	for (si = 0, oi = 0; si < size && oi < EXFAT_UPCASE_CHARS; si++)
373 	{
374 		uint16_t ch = le16_to_cpu(source[si]);
375 
376 		if (ch == 0xffff && si + 1 < size)	/* indicates a run */
377 			oi += le16_to_cpu(source[++si]);
378 		else
379 			output[oi++] = ch;
380 	}
381 }
382 
383 /*
384  * Read one entry in a directory at offset position and build a new node
385  * structure.
386  */
readdir(struct exfat * ef,struct exfat_node * parent,struct exfat_node ** node,off_t * offset)387 static int readdir(struct exfat* ef, struct exfat_node* parent,
388 		struct exfat_node** node, off_t* offset)
389 {
390 	int rc;
391 	struct exfat_entry entry;
392 	const struct exfat_entry_meta1* meta1;
393 	const struct exfat_entry_upcase* upcase;
394 	const struct exfat_entry_bitmap* bitmap;
395 	const struct exfat_entry_label* label;
396 	uint64_t upcase_size = 0;
397 	le16_t* upcase_comp = NULL;
398 	le16_t label_name[EXFAT_ENAME_MAX];
399 
400 	for (;;)
401 	{
402 		rc = read_entries(ef, parent, &entry, 1, *offset);
403 		if (rc != 0)
404 			return rc;
405 
406 		switch (entry.type)
407 		{
408 		case EXFAT_ENTRY_FILE:
409 			meta1 = (const struct exfat_entry_meta1*) &entry;
410 			return parse_file_entry(ef, parent, node, offset,
411 					1 + meta1->continuations);
412 
413 		case EXFAT_ENTRY_UPCASE:
414 			if (ef->upcase != NULL)
415 				break;
416 			upcase = (const struct exfat_entry_upcase*) &entry;
417 			if (CLUSTER_INVALID(*ef->sb, le32_to_cpu(upcase->start_cluster)))
418 			{
419 				exfat_error("invalid cluster 0x%x in upcase table",
420 						le32_to_cpu(upcase->start_cluster));
421 				return -EIO;
422 			}
423 			upcase_size = le64_to_cpu(upcase->size);
424 			if (upcase_size == 0 ||
425 				upcase_size > EXFAT_UPCASE_CHARS * sizeof(uint16_t) ||
426 				upcase_size % sizeof(uint16_t) != 0)
427 			{
428 				exfat_error("bad upcase table size (%"PRIu64" bytes)",
429 						upcase_size);
430 				return -EIO;
431 			}
432 			upcase_comp = malloc(upcase_size);
433 			if (upcase_comp == NULL)
434 			{
435 				exfat_error("failed to allocate upcase table (%"PRIu64" bytes)",
436 						upcase_size);
437 				return -ENOMEM;
438 			}
439 
440 			/* read compressed upcase table */
441 			if (exfat_pread(ef->dev, upcase_comp, upcase_size,
442 					exfat_c2o(ef, le32_to_cpu(upcase->start_cluster))) < 0)
443 			{
444 				free(upcase_comp);
445 				exfat_error("failed to read upper case table "
446 						"(%"PRIu64" bytes starting at cluster %#x)",
447 						upcase_size,
448 						le32_to_cpu(upcase->start_cluster));
449 				return -EIO;
450 			}
451 
452 			/* decompress upcase table */
453 			ef->upcase = calloc(EXFAT_UPCASE_CHARS, sizeof(uint16_t));
454 			if (ef->upcase == NULL)
455 			{
456 				free(upcase_comp);
457 				exfat_error("failed to allocate decompressed upcase table");
458 				return -ENOMEM;
459 			}
460 			decompress_upcase(ef->upcase, upcase_comp,
461 					upcase_size / sizeof(uint16_t));
462 			free(upcase_comp);
463 			break;
464 
465 		case EXFAT_ENTRY_BITMAP:
466 			bitmap = (const struct exfat_entry_bitmap*) &entry;
467 			ef->cmap.start_cluster = le32_to_cpu(bitmap->start_cluster);
468 			if (CLUSTER_INVALID(*ef->sb, ef->cmap.start_cluster))
469 			{
470 				exfat_error("invalid cluster 0x%x in clusters bitmap",
471 						ef->cmap.start_cluster);
472 				return -EIO;
473 			}
474 			ef->cmap.size = le32_to_cpu(ef->sb->cluster_count);
475 			if (le64_to_cpu(bitmap->size) < DIV_ROUND_UP(ef->cmap.size, 8))
476 			{
477 				exfat_error("invalid clusters bitmap size: %"PRIu64
478 						" (expected at least %u)",
479 						le64_to_cpu(bitmap->size),
480 						DIV_ROUND_UP(ef->cmap.size, 8));
481 				return -EIO;
482 			}
483 			/* FIXME bitmap can be rather big, up to 512 MB */
484 			ef->cmap.chunk_size = ef->cmap.size;
485 			ef->cmap.chunk = malloc(BMAP_SIZE(ef->cmap.chunk_size));
486 			if (ef->cmap.chunk == NULL)
487 			{
488 				exfat_error("failed to allocate clusters bitmap chunk "
489 						"(%"PRIu64" bytes)", le64_to_cpu(bitmap->size));
490 				return -ENOMEM;
491 			}
492 
493 			if (exfat_pread(ef->dev, ef->cmap.chunk,
494 					BMAP_SIZE(ef->cmap.chunk_size),
495 					exfat_c2o(ef, ef->cmap.start_cluster)) < 0)
496 			{
497 				exfat_error("failed to read clusters bitmap "
498 						"(%"PRIu64" bytes starting at cluster %#x)",
499 						le64_to_cpu(bitmap->size), ef->cmap.start_cluster);
500 				return -EIO;
501 			}
502 			break;
503 
504 		case EXFAT_ENTRY_LABEL:
505 			label = (const struct exfat_entry_label*) &entry;
506 			if (label->length > EXFAT_ENAME_MAX)
507 			{
508 				exfat_error("too long label (%hhu chars)", label->length);
509 				return -EIO;
510 			}
511 			/* copy to a temporary buffer to avoid unaligned access to a
512 			   packed member */
513 			memcpy(label_name, label->name, sizeof(label_name));
514 			if (exfat_utf16_to_utf8(ef->label, label_name,
515 						sizeof(ef->label), EXFAT_ENAME_MAX) != 0)
516 				return -EIO;
517 			break;
518 
519 		default:
520 			if (!(entry.type & EXFAT_ENTRY_VALID))
521 				break; /* deleted entry, ignore it */
522 
523 			exfat_error("unknown entry type %#hhx", entry.type);
524 			if (!EXFAT_REPAIR(unknown_entry, ef, parent, &entry, *offset))
525 				return -EIO;
526 		}
527 		*offset += sizeof(entry);
528 	}
529 	/* we never reach here */
530 }
531 
exfat_cache_directory(struct exfat * ef,struct exfat_node * dir)532 int exfat_cache_directory(struct exfat* ef, struct exfat_node* dir)
533 {
534 	off_t offset = 0;
535 	int rc;
536 	struct exfat_node* node;
537 	struct exfat_node* current = NULL;
538 
539 	if (dir->is_cached)
540 		return 0; /* already cached */
541 
542 	while ((rc = readdir(ef, dir, &node, &offset)) == 0)
543 	{
544 		node->parent = dir;
545 		if (current != NULL)
546 		{
547 			current->next = node;
548 			node->prev = current;
549 		}
550 		else
551 			dir->child = node;
552 
553 		current = node;
554 	}
555 
556 	if (rc != -ENOENT)
557 	{
558 		/* rollback */
559 		for (current = dir->child; current; current = node)
560 		{
561 			node = current->next;
562 			free(current);
563 		}
564 		dir->child = NULL;
565 		return rc;
566 	}
567 
568 	dir->is_cached = true;
569 	return 0;
570 }
571 
tree_attach(struct exfat_node * dir,struct exfat_node * node)572 static void tree_attach(struct exfat_node* dir, struct exfat_node* node)
573 {
574 	node->parent = dir;
575 	if (dir->child)
576 	{
577 		dir->child->prev = node;
578 		node->next = dir->child;
579 	}
580 	dir->child = node;
581 }
582 
tree_detach(struct exfat_node * node)583 static void tree_detach(struct exfat_node* node)
584 {
585 	if (node->prev)
586 		node->prev->next = node->next;
587 	else /* this is the first node in the list */
588 		node->parent->child = node->next;
589 	if (node->next)
590 		node->next->prev = node->prev;
591 	node->parent = NULL;
592 	node->prev = NULL;
593 	node->next = NULL;
594 }
595 
reset_cache(struct exfat * ef,struct exfat_node * node)596 static void reset_cache(struct exfat* ef, struct exfat_node* node)
597 {
598 	char buffer[EXFAT_UTF8_NAME_BUFFER_MAX];
599 
600 	while (node->child)
601 	{
602 		struct exfat_node* p = node->child;
603 		reset_cache(ef, p);
604 		tree_detach(p);
605 		free(p);
606 	}
607 	node->is_cached = false;
608 	if (node->references != 0)
609 	{
610 		exfat_get_name(node, buffer);
611 		exfat_warn("non-zero reference counter (%d) for '%s'",
612 				node->references, buffer);
613 	}
614 	if (node != ef->root && node->is_dirty)
615 	{
616 		exfat_get_name(node, buffer);
617 		exfat_bug("node '%s' is dirty", buffer);
618 	}
619 	while (node->references)
620 		exfat_put_node(ef, node);
621 }
622 
exfat_reset_cache(struct exfat * ef)623 void exfat_reset_cache(struct exfat* ef)
624 {
625 	reset_cache(ef, ef->root);
626 }
627 
exfat_flush_node(struct exfat * ef,struct exfat_node * node)628 int exfat_flush_node(struct exfat* ef, struct exfat_node* node)
629 {
630 	struct exfat_entry entries[1 + node->continuations];
631 	struct exfat_entry_meta1* meta1 = (struct exfat_entry_meta1*) &entries[0];
632 	struct exfat_entry_meta2* meta2 = (struct exfat_entry_meta2*) &entries[1];
633 	int rc;
634 	le16_t edate, etime;
635 
636 	if (!node->is_dirty)
637 		return 0; /* no need to flush */
638 
639 	if (ef->ro)
640 		exfat_bug("unable to flush node to read-only FS");
641 
642 	if (node->parent == NULL)
643 		return 0; /* do not flush unlinked node */
644 
645 	rc = read_entries(ef, node->parent, entries, 1 + node->continuations,
646 			node->entry_offset);
647 	if (rc != 0)
648 		return rc;
649 	if (!check_entries(entries, 1 + node->continuations))
650 		return -EIO;
651 
652 	meta1->attrib = cpu_to_le16(node->attrib);
653 	exfat_unix2exfat(node->mtime, &edate, &etime,
654 			&meta1->mtime_cs, &meta1->mtime_tzo);
655 	meta1->mdate = edate;
656 	meta1->mtime = etime;
657 	exfat_unix2exfat(node->atime, &edate, &etime,
658 			NULL, &meta1->atime_tzo);
659 	meta1->adate = edate;
660 	meta1->atime = etime;
661 	meta2->valid_size = cpu_to_le64(node->valid_size);
662 	meta2->size = cpu_to_le64(node->size);
663 	meta2->start_cluster = cpu_to_le32(node->start_cluster);
664 	meta2->flags = EXFAT_FLAG_ALWAYS1;
665 	/* empty files must not be marked as contiguous */
666 	if (node->size != 0 && node->is_contiguous)
667 		meta2->flags |= EXFAT_FLAG_CONTIGUOUS;
668 	/* name hash remains unchanged, no need to recalculate it */
669 
670 	meta1->checksum = exfat_calc_checksum(entries, 1 + node->continuations);
671 	rc = write_entries(ef, node->parent, entries, 1 + node->continuations,
672 			node->entry_offset);
673 	if (rc != 0)
674 		return rc;
675 
676 	node->is_dirty = false;
677 	return exfat_flush(ef);
678 }
679 
erase_entries(struct exfat * ef,struct exfat_node * dir,int n,off_t offset)680 static int erase_entries(struct exfat* ef, struct exfat_node* dir, int n,
681 		off_t offset)
682 {
683 	struct exfat_entry entries[n];
684 	int rc;
685 	int i;
686 
687 	rc = read_entries(ef, dir, entries, n, offset);
688 	if (rc != 0)
689 		return rc;
690 	for (i = 0; i < n; i++)
691 		entries[i].type &= ~EXFAT_ENTRY_VALID;
692 	return write_entries(ef, dir, entries, n, offset);
693 }
694 
erase_node(struct exfat * ef,struct exfat_node * node)695 static int erase_node(struct exfat* ef, struct exfat_node* node)
696 {
697 	int rc;
698 
699 	exfat_get_node(node->parent);
700 	rc = erase_entries(ef, node->parent, 1 + node->continuations,
701 			node->entry_offset);
702 	if (rc != 0)
703 	{
704 		exfat_put_node(ef, node->parent);
705 		return rc;
706 	}
707 	rc = exfat_flush_node(ef, node->parent);
708 	exfat_put_node(ef, node->parent);
709 	return rc;
710 }
711 
shrink_directory(struct exfat * ef,struct exfat_node * dir,off_t deleted_offset)712 static int shrink_directory(struct exfat* ef, struct exfat_node* dir,
713 		off_t deleted_offset)
714 {
715 	const struct exfat_node* node;
716 	const struct exfat_node* last_node;
717 	uint64_t entries = 0;
718 	uint64_t new_size;
719 
720 	if (!(dir->attrib & EXFAT_ATTRIB_DIR))
721 		exfat_bug("attempted to shrink a file");
722 	if (!dir->is_cached)
723 		exfat_bug("attempted to shrink uncached directory");
724 
725 	for (last_node = node = dir->child; node; node = node->next)
726 	{
727 		if (deleted_offset < node->entry_offset)
728 		{
729 			/* there are other entries after the removed one, no way to shrink
730 			   this directory */
731 			return 0;
732 		}
733 		if (last_node->entry_offset < node->entry_offset)
734 			last_node = node;
735 	}
736 
737 	if (last_node)
738 	{
739 		/* offset of the last entry */
740 		entries += last_node->entry_offset / sizeof(struct exfat_entry);
741 		/* two subentries with meta info */
742 		entries += 2;
743 		/* subentries with file name */
744 		entries += DIV_ROUND_UP(exfat_utf16_length(last_node->name),
745 				EXFAT_ENAME_MAX);
746 	}
747 
748 	new_size = DIV_ROUND_UP(entries * sizeof(struct exfat_entry),
749 				 CLUSTER_SIZE(*ef->sb)) * CLUSTER_SIZE(*ef->sb);
750 	if (new_size == 0) /* directory always has at least 1 cluster */
751 		new_size = CLUSTER_SIZE(*ef->sb);
752 	if (new_size == dir->size)
753 		return 0;
754 	return exfat_truncate(ef, dir, new_size, true);
755 }
756 
delete(struct exfat * ef,struct exfat_node * node)757 static int delete(struct exfat* ef, struct exfat_node* node)
758 {
759 	struct exfat_node* parent = node->parent;
760 	off_t deleted_offset = node->entry_offset;
761 	int rc;
762 
763 	exfat_get_node(parent);
764 	rc = erase_node(ef, node);
765 	if (rc != 0)
766 	{
767 		exfat_put_node(ef, parent);
768 		return rc;
769 	}
770 	tree_detach(node);
771 	rc = shrink_directory(ef, parent, deleted_offset);
772 	node->is_unlinked = true;
773 	if (rc != 0)
774 	{
775 		exfat_flush_node(ef, parent);
776 		exfat_put_node(ef, parent);
777 		return rc;
778 	}
779 	exfat_update_mtime(parent);
780 	rc = exfat_flush_node(ef, parent);
781 	exfat_put_node(ef, parent);
782 	return rc;
783 }
784 
exfat_unlink(struct exfat * ef,struct exfat_node * node)785 int exfat_unlink(struct exfat* ef, struct exfat_node* node)
786 {
787 	if (node->attrib & EXFAT_ATTRIB_DIR)
788 		return -EISDIR;
789 	return delete(ef, node);
790 }
791 
exfat_rmdir(struct exfat * ef,struct exfat_node * node)792 int exfat_rmdir(struct exfat* ef, struct exfat_node* node)
793 {
794 	int rc;
795 
796 	if (!(node->attrib & EXFAT_ATTRIB_DIR))
797 		return -ENOTDIR;
798 	/* check that directory is empty */
799 	rc = exfat_cache_directory(ef, node);
800 	if (rc != 0)
801 		return rc;
802 	if (node->child)
803 		return -ENOTEMPTY;
804 	return delete(ef, node);
805 }
806 
check_slot(struct exfat * ef,struct exfat_node * dir,off_t offset,int n)807 static int check_slot(struct exfat* ef, struct exfat_node* dir, off_t offset,
808 		int n)
809 {
810 	struct exfat_entry entries[n];
811 	int rc;
812 	int i;
813 
814 	/* Root directory contains entries, that don't have any nodes associated
815 	   with them (clusters bitmap, upper case table, label). We need to be
816 	   careful not to overwrite them. */
817 	if (dir != ef->root)
818 		return 0;
819 
820 	rc = read_entries(ef, dir, entries, n, offset);
821 	if (rc != 0)
822 		return rc;
823 	for (i = 0; i < n; i++)
824 		if (entries[i].type & EXFAT_ENTRY_VALID)
825 			return -EINVAL;
826 	return 0;
827 }
828 
find_slot(struct exfat * ef,struct exfat_node * dir,off_t * offset,int n)829 static int find_slot(struct exfat* ef, struct exfat_node* dir,
830 		off_t* offset, int n)
831 {
832 	bitmap_t* dmap;
833 	struct exfat_node* p;
834 	size_t i;
835 	int contiguous = 0;
836 
837 	if (!dir->is_cached)
838 		exfat_bug("directory is not cached");
839 
840 	/* build a bitmap of valid entries in the directory */
841 	dmap = calloc(BMAP_SIZE(dir->size / sizeof(struct exfat_entry)),
842 			sizeof(bitmap_t));
843 	if (dmap == NULL)
844 	{
845 		exfat_error("failed to allocate directory bitmap (%"PRIu64")",
846 				dir->size / sizeof(struct exfat_entry));
847 		return -ENOMEM;
848 	}
849 	for (p = dir->child; p != NULL; p = p->next)
850 		for (i = 0; i < 1u + p->continuations; i++)
851 			BMAP_SET(dmap, p->entry_offset / sizeof(struct exfat_entry) + i);
852 
853 	/* find a slot in the directory entries bitmap */
854 	for (i = 0; i < dir->size / sizeof(struct exfat_entry); i++)
855 	{
856 		if (BMAP_GET(dmap, i) == 0)
857 		{
858 			if (contiguous++ == 0)
859 				*offset = (off_t) i * sizeof(struct exfat_entry);
860 			if (contiguous == n)
861 			{
862 				int rc;
863 
864 				/* suitable slot is found, check that it's not occupied */
865 				rc = check_slot(ef, dir, *offset, n);
866 				if (rc == -EINVAL)
867 				{
868 					/* slot at (i-n) is occupied, go back and check (i-n+1) */
869 					i -= contiguous - 1;
870 					contiguous = 0;
871 				}
872 				else
873 				{
874 					/* slot is free or an error occurred */
875 					free(dmap);
876 					return rc;
877 				}
878 			}
879 		}
880 		else
881 			contiguous = 0;
882 	}
883 	free(dmap);
884 
885 	/* no suitable slots found, extend the directory */
886 	if (contiguous == 0)
887 		*offset = dir->size;
888 	return exfat_truncate(ef, dir,
889 			ROUND_UP(dir->size + sizeof(struct exfat_entry[n - contiguous]),
890 					CLUSTER_SIZE(*ef->sb)),
891 			true);
892 }
893 
commit_entry(struct exfat * ef,struct exfat_node * dir,const le16_t * name,off_t offset,uint16_t attrib)894 static int commit_entry(struct exfat* ef, struct exfat_node* dir,
895 		const le16_t* name, off_t offset, uint16_t attrib)
896 {
897 	struct exfat_node* node;
898 	const size_t name_length = exfat_utf16_length(name);
899 	const int name_entries = DIV_ROUND_UP(name_length, EXFAT_ENAME_MAX);
900 	struct exfat_entry entries[2 + name_entries];
901 	struct exfat_entry_meta1* meta1 = (struct exfat_entry_meta1*) &entries[0];
902 	struct exfat_entry_meta2* meta2 = (struct exfat_entry_meta2*) &entries[1];
903 	int i;
904 	int rc;
905 	le16_t edate, etime;
906 
907 	memset(entries, 0, sizeof(struct exfat_entry[2]));
908 
909 	meta1->type = EXFAT_ENTRY_FILE;
910 	meta1->continuations = 1 + name_entries;
911 	meta1->attrib = cpu_to_le16(attrib);
912 	exfat_unix2exfat(time(NULL), &edate, &etime,
913 			&meta1->crtime_cs, &meta1->crtime_tzo);
914 	meta1->adate = meta1->mdate = meta1->crdate = edate;
915 	meta1->atime = meta1->mtime = meta1->crtime = etime;
916 	meta1->mtime_cs = meta1->crtime_cs; /* there is no atime_cs */
917 	meta1->atime_tzo = meta1->mtime_tzo = meta1->crtime_tzo;
918 
919 	meta2->type = EXFAT_ENTRY_FILE_INFO;
920 	meta2->flags = EXFAT_FLAG_ALWAYS1;
921 	meta2->name_length = name_length;
922 	meta2->name_hash = exfat_calc_name_hash(ef, name, name_length);
923 	meta2->start_cluster = cpu_to_le32(EXFAT_CLUSTER_FREE);
924 
925 	for (i = 0; i < name_entries; i++)
926 	{
927 		struct exfat_entry_name* name_entry;
928 
929 		name_entry = (struct exfat_entry_name*) &entries[2 + i];
930 		name_entry->type = EXFAT_ENTRY_FILE_NAME;
931 		name_entry->__unknown = 0;
932 		memcpy(name_entry->name, name + i * EXFAT_ENAME_MAX,
933 				EXFAT_ENAME_MAX * sizeof(le16_t));
934 	}
935 
936 	meta1->checksum = exfat_calc_checksum(entries, 2 + name_entries);
937 	rc = write_entries(ef, dir, entries, 2 + name_entries, offset);
938 	if (rc != 0)
939 		return rc;
940 
941 	node = allocate_node();
942 	if (node == NULL)
943 		return -ENOMEM;
944 	node->entry_offset = offset;
945 	memcpy(node->name, name, name_length * sizeof(le16_t));
946 	init_node_meta1(node, meta1);
947 	init_node_meta2(node, meta2);
948 
949 	tree_attach(dir, node);
950 	return 0;
951 }
952 
create(struct exfat * ef,const char * path,uint16_t attrib)953 static int create(struct exfat* ef, const char* path, uint16_t attrib)
954 {
955 	struct exfat_node* dir;
956 	struct exfat_node* existing;
957 	off_t offset = -1;
958 	le16_t name[EXFAT_NAME_MAX + 1];
959 	int rc;
960 
961 	rc = exfat_split(ef, &dir, &existing, name, path);
962 	if (rc != 0)
963 		return rc;
964 	if (existing != NULL)
965 	{
966 		exfat_put_node(ef, existing);
967 		exfat_put_node(ef, dir);
968 		return -EEXIST;
969 	}
970 
971 	rc = find_slot(ef, dir, &offset,
972 			2 + DIV_ROUND_UP(exfat_utf16_length(name), EXFAT_ENAME_MAX));
973 	if (rc != 0)
974 	{
975 		exfat_put_node(ef, dir);
976 		return rc;
977 	}
978 	rc = commit_entry(ef, dir, name, offset, attrib);
979 	if (rc != 0)
980 	{
981 		exfat_put_node(ef, dir);
982 		return rc;
983 	}
984 	exfat_update_mtime(dir);
985 	rc = exfat_flush_node(ef, dir);
986 	exfat_put_node(ef, dir);
987 	return rc;
988 }
989 
exfat_mknod(struct exfat * ef,const char * path)990 int exfat_mknod(struct exfat* ef, const char* path)
991 {
992 	return create(ef, path, EXFAT_ATTRIB_ARCH);
993 }
994 
exfat_mkdir(struct exfat * ef,const char * path)995 int exfat_mkdir(struct exfat* ef, const char* path)
996 {
997 	int rc;
998 	struct exfat_node* node;
999 
1000 	rc = create(ef, path, EXFAT_ATTRIB_DIR);
1001 	if (rc != 0)
1002 		return rc;
1003 	rc = exfat_lookup(ef, &node, path);
1004 	if (rc != 0)
1005 		return 0;
1006 	/* directories always have at least one cluster */
1007 	rc = exfat_truncate(ef, node, CLUSTER_SIZE(*ef->sb), true);
1008 	if (rc != 0)
1009 	{
1010 		delete(ef, node);
1011 		exfat_put_node(ef, node);
1012 		return rc;
1013 	}
1014 	rc = exfat_flush_node(ef, node);
1015 	if (rc != 0)
1016 	{
1017 		delete(ef, node);
1018 		exfat_put_node(ef, node);
1019 		return rc;
1020 	}
1021 	exfat_put_node(ef, node);
1022 	return 0;
1023 }
1024 
rename_entry(struct exfat * ef,struct exfat_node * dir,struct exfat_node * node,const le16_t * name,off_t new_offset)1025 static int rename_entry(struct exfat* ef, struct exfat_node* dir,
1026 		struct exfat_node* node, const le16_t* name, off_t new_offset)
1027 {
1028 	const size_t name_length = exfat_utf16_length(name);
1029 	const int name_entries = DIV_ROUND_UP(name_length, EXFAT_ENAME_MAX);
1030 	struct exfat_entry entries[2 + name_entries];
1031 	struct exfat_entry_meta1* meta1 = (struct exfat_entry_meta1*) &entries[0];
1032 	struct exfat_entry_meta2* meta2 = (struct exfat_entry_meta2*) &entries[1];
1033 	int rc;
1034 	int i;
1035 
1036 	rc = read_entries(ef, node->parent, entries, 2, node->entry_offset);
1037 	if (rc != 0)
1038 		return rc;
1039 
1040 	meta1->continuations = 1 + name_entries;
1041 	meta2->name_length = name_length;
1042 	meta2->name_hash = exfat_calc_name_hash(ef, name, name_length);
1043 
1044 	rc = erase_node(ef, node);
1045 	if (rc != 0)
1046 		return rc;
1047 
1048 	node->entry_offset = new_offset;
1049 	node->continuations = 1 + name_entries;
1050 
1051 	for (i = 0; i < name_entries; i++)
1052 	{
1053 		struct exfat_entry_name* name_entry;
1054 
1055 		name_entry = (struct exfat_entry_name*) &entries[2 + i];
1056 		name_entry->type = EXFAT_ENTRY_FILE_NAME;
1057 		name_entry->__unknown = 0;
1058 		memcpy(name_entry->name, name + i * EXFAT_ENAME_MAX,
1059 				EXFAT_ENAME_MAX * sizeof(le16_t));
1060 	}
1061 
1062 	meta1->checksum = exfat_calc_checksum(entries, 2 + name_entries);
1063 	rc = write_entries(ef, dir, entries, 2 + name_entries, new_offset);
1064 	if (rc != 0)
1065 		return rc;
1066 
1067 	memcpy(node->name, name, (EXFAT_NAME_MAX + 1) * sizeof(le16_t));
1068 	tree_detach(node);
1069 	tree_attach(dir, node);
1070 	return 0;
1071 }
1072 
exfat_rename(struct exfat * ef,const char * old_path,const char * new_path)1073 int exfat_rename(struct exfat* ef, const char* old_path, const char* new_path)
1074 {
1075 	struct exfat_node* node;
1076 	struct exfat_node* existing;
1077 	struct exfat_node* dir;
1078 	off_t offset = -1;
1079 	le16_t name[EXFAT_NAME_MAX + 1];
1080 	int rc;
1081 
1082 	rc = exfat_lookup(ef, &node, old_path);
1083 	if (rc != 0)
1084 		return rc;
1085 
1086 	rc = exfat_split(ef, &dir, &existing, name, new_path);
1087 	if (rc != 0)
1088 	{
1089 		exfat_put_node(ef, node);
1090 		return rc;
1091 	}
1092 
1093 	/* check that target is not a subdirectory of the source */
1094 	if (node->attrib & EXFAT_ATTRIB_DIR)
1095 	{
1096 		struct exfat_node* p;
1097 
1098 		for (p = dir; p; p = p->parent)
1099 			if (node == p)
1100 			{
1101 				if (existing != NULL)
1102 					exfat_put_node(ef, existing);
1103 				exfat_put_node(ef, dir);
1104 				exfat_put_node(ef, node);
1105 				return -EINVAL;
1106 			}
1107 	}
1108 
1109 	if (existing != NULL)
1110 	{
1111 		/* remove target if it's not the same node as source */
1112 		if (existing != node)
1113 		{
1114 			if (existing->attrib & EXFAT_ATTRIB_DIR)
1115 			{
1116 				if (node->attrib & EXFAT_ATTRIB_DIR)
1117 					rc = exfat_rmdir(ef, existing);
1118 				else
1119 					rc = -ENOTDIR;
1120 			}
1121 			else
1122 			{
1123 				if (!(node->attrib & EXFAT_ATTRIB_DIR))
1124 					rc = exfat_unlink(ef, existing);
1125 				else
1126 					rc = -EISDIR;
1127 			}
1128 			exfat_put_node(ef, existing);
1129 			if (rc != 0)
1130 			{
1131 				/* free clusters even if something went wrong; otherwise they
1132 				   will be just lost */
1133 				exfat_cleanup_node(ef, existing);
1134 				exfat_put_node(ef, dir);
1135 				exfat_put_node(ef, node);
1136 				return rc;
1137 			}
1138 			rc = exfat_cleanup_node(ef, existing);
1139 			if (rc != 0)
1140 			{
1141 				exfat_put_node(ef, dir);
1142 				exfat_put_node(ef, node);
1143 				return rc;
1144 			}
1145 		}
1146 		else
1147 			exfat_put_node(ef, existing);
1148 	}
1149 
1150 	rc = find_slot(ef, dir, &offset,
1151 			2 + DIV_ROUND_UP(exfat_utf16_length(name), EXFAT_ENAME_MAX));
1152 	if (rc != 0)
1153 	{
1154 		exfat_put_node(ef, dir);
1155 		exfat_put_node(ef, node);
1156 		return rc;
1157 	}
1158 	rc = rename_entry(ef, dir, node, name, offset);
1159 	if (rc != 0)
1160 	{
1161 		exfat_put_node(ef, dir);
1162 		exfat_put_node(ef, node);
1163 		return rc;
1164 	}
1165 	rc = exfat_flush_node(ef, dir);
1166 	exfat_put_node(ef, dir);
1167 	exfat_put_node(ef, node);
1168 	/* node itself is not marked as dirty, no need to flush it */
1169 	return rc;
1170 }
1171 
exfat_utimes(struct exfat_node * node,const struct timespec tv[2])1172 void exfat_utimes(struct exfat_node* node, const struct timespec tv[2])
1173 {
1174 	node->atime = tv[0].tv_sec;
1175 	node->mtime = tv[1].tv_sec;
1176 	node->is_dirty = true;
1177 }
1178 
exfat_update_atime(struct exfat_node * node)1179 void exfat_update_atime(struct exfat_node* node)
1180 {
1181 	node->atime = time(NULL);
1182 	node->is_dirty = true;
1183 }
1184 
exfat_update_mtime(struct exfat_node * node)1185 void exfat_update_mtime(struct exfat_node* node)
1186 {
1187 	node->mtime = time(NULL);
1188 	node->is_dirty = true;
1189 }
1190 
1191 #ifndef __UBOOT__
exfat_get_label(struct exfat * ef)1192 const char* exfat_get_label(struct exfat* ef)
1193 {
1194 	return ef->label;
1195 }
1196 
find_label(struct exfat * ef,off_t * offset)1197 static int find_label(struct exfat* ef, off_t* offset)
1198 {
1199 	struct exfat_entry entry;
1200 	int rc;
1201 
1202 	for (*offset = 0; ; *offset += sizeof(entry))
1203 	{
1204 		rc = read_entries(ef, ef->root, &entry, 1, *offset);
1205 		if (rc != 0)
1206 			return rc;
1207 
1208 		if (entry.type == EXFAT_ENTRY_LABEL)
1209 			return 0;
1210 	}
1211 }
1212 
exfat_set_label(struct exfat * ef,const char * label)1213 int exfat_set_label(struct exfat* ef, const char* label)
1214 {
1215 	le16_t label_utf16[EXFAT_ENAME_MAX + 1];
1216 	int rc;
1217 	off_t offset;
1218 	struct exfat_entry_label entry;
1219 
1220 	memset(label_utf16, 0, sizeof(label_utf16));
1221 	rc = exfat_utf8_to_utf16(label_utf16, label, EXFAT_ENAME_MAX + 1,
1222 			strlen(label));
1223 	if (rc != 0)
1224 		return rc;
1225 
1226 	rc = find_label(ef, &offset);
1227 	if (rc == -ENOENT)
1228 		rc = find_slot(ef, ef->root, &offset, 1);
1229 	if (rc != 0)
1230 		return rc;
1231 
1232 	entry.type = EXFAT_ENTRY_LABEL;
1233 	entry.length = exfat_utf16_length(label_utf16);
1234 	memcpy(entry.name, label_utf16, sizeof(entry.name));
1235 	if (entry.length == 0)
1236 		entry.type ^= EXFAT_ENTRY_VALID;
1237 
1238 	rc = write_entries(ef, ef->root, (struct exfat_entry*) &entry, 1, offset);
1239 	if (rc != 0)
1240 		return rc;
1241 
1242 	strcpy(ef->label, label);
1243 	return 0;
1244 }
1245 #endif /* __UBOOT__ */
1246