OSDN Git Service

Add support for timezone offsets.
[android-x86/external-exfat.git] / libexfat / node.c
1 /*
2         node.c (09.10.09)
3         exFAT file system implementation library.
4
5         Free exFAT implementation.
6         Copyright (C) 2010-2018  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
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
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  */
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
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 == 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
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 == 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
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
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
144 static void init_node_meta2(struct exfat_node* node,
145                 const struct exfat_entry_meta2* meta2)
146 {
147         node->size = le64_to_cpu(meta2->size);
148         node->start_cluster = le32_to_cpu(meta2->start_cluster);
149         node->fptr_cluster = node->start_cluster;
150         node->is_contiguous = ((meta2->flags & EXFAT_FLAG_CONTIGUOUS) != 0);
151 }
152
153 static void init_node_name(struct exfat_node* node,
154                 const struct exfat_entry* entries, int n)
155 {
156         int i;
157
158         for (i = 0; i < n; i++)
159                 memcpy(node->name + i * EXFAT_ENAME_MAX,
160                                 ((const struct exfat_entry_name*) &entries[i])->name,
161                                 EXFAT_ENAME_MAX * sizeof(le16_t));
162 }
163
164 static bool check_entries(const struct exfat_entry* entry, int n)
165 {
166         int previous = EXFAT_ENTRY_NONE;
167         int current;
168         int i;
169
170         /* check transitions between entries types */
171         for (i = 0; i < n + 1; previous = current, i++)
172         {
173                 bool valid = false;
174
175                 current = (i < n) ? entry[i].type : EXFAT_ENTRY_NONE;
176                 switch (previous)
177                 {
178                 case EXFAT_ENTRY_NONE:
179                         valid = (current == EXFAT_ENTRY_FILE);
180                         break;
181                 case EXFAT_ENTRY_FILE:
182                         valid = (current == EXFAT_ENTRY_FILE_INFO);
183                         break;
184                 case EXFAT_ENTRY_FILE_INFO:
185                         valid = (current == EXFAT_ENTRY_FILE_NAME);
186                         break;
187                 case EXFAT_ENTRY_FILE_NAME:
188                         valid = (current == EXFAT_ENTRY_FILE_NAME ||
189                                  current == EXFAT_ENTRY_NONE ||
190                                  current >= EXFAT_ENTRY_FILE_TAIL);
191                         break;
192                 case EXFAT_ENTRY_FILE_TAIL ... 0xff:
193                         valid = (current >= EXFAT_ENTRY_FILE_TAIL ||
194                                  current == EXFAT_ENTRY_NONE);
195                         break;
196                 }
197
198                 if (!valid)
199                 {
200                         exfat_error("unexpected entry type %#x after %#x at %d/%d",
201                                         current, previous, i, n);
202                         return false;
203                 }
204         }
205         return true;
206 }
207
208 static bool check_node(const struct exfat* ef, struct exfat_node* node,
209                 le16_t actual_checksum, const struct exfat_entry_meta1* meta1,
210                 const struct exfat_entry_meta2* meta2)
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 (le64_to_cpu(meta2->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, le64_to_cpu(meta2->valid_size),
242                                 node->size);
243                 ret = false;
244         }
245
246         /*
247            Empty file must have zero start cluster. Non-empty file must start
248            with a valid cluster. Directories cannot be empty (i.e. must always
249            have a valid start cluster), but we will check this later while
250            reading that directory to give user a chance to read this directory.
251         */
252         if (node->size == 0 && node->start_cluster != EXFAT_CLUSTER_FREE)
253         {
254                 exfat_get_name(node, buffer);
255                 exfat_error("'%s' is empty but start cluster is %#x", buffer,
256                                 node->start_cluster);
257                 ret = false;
258         }
259         if (node->size > 0 && CLUSTER_INVALID(*ef->sb, node->start_cluster))
260         {
261                 exfat_get_name(node, buffer);
262                 exfat_error("'%s' points to invalid cluster %#x", buffer,
263                                 node->start_cluster);
264                 ret = false;
265         }
266
267         /* File or directory cannot be larger than clusters heap. */
268         if (node->size > clusters_heap_size)
269         {
270                 exfat_get_name(node, buffer);
271                 exfat_error("'%s' is larger than clusters heap: %"PRIu64" > %"PRIu64,
272                                 buffer, node->size, clusters_heap_size);
273                 ret = false;
274         }
275
276         /* Empty file or directory must be marked as non-contiguous. */
277         if (node->size == 0 && node->is_contiguous)
278         {
279                 exfat_get_name(node, buffer);
280                 exfat_error("'%s' is empty but marked as contiguous (%#hx)", buffer,
281                                 node->attrib);
282                 ret = false;
283         }
284
285         /* Directory size must be aligned on at cluster boundary. */
286         if ((node->attrib & EXFAT_ATTRIB_DIR) && node->size % cluster_size != 0)
287         {
288                 exfat_get_name(node, buffer);
289                 exfat_error("'%s' directory size %"PRIu64" is not divisible by %d", buffer,
290                                 node->size, cluster_size);
291                 ret = false;
292         }
293
294         return ret;
295 }
296
297 static int parse_file_entries(struct exfat* ef, struct exfat_node* node,
298                 const struct exfat_entry* entries, int n)
299 {
300         const struct exfat_entry_meta1* meta1;
301         const struct exfat_entry_meta2* meta2;
302         int mandatory_entries;
303
304         if (!check_entries(entries, n))
305                 return -EIO;
306
307         meta1 = (const struct exfat_entry_meta1*) &entries[0];
308         if (meta1->continuations < 2)
309         {
310                 exfat_error("too few continuations (%hhu)", meta1->continuations);
311                 return -EIO;
312         }
313         meta2 = (const struct exfat_entry_meta2*) &entries[1];
314         if (meta2->flags & ~(EXFAT_FLAG_ALWAYS1 | EXFAT_FLAG_CONTIGUOUS))
315         {
316                 exfat_error("unknown flags in meta2 (%#hhx)", meta2->flags);
317                 return -EIO;
318         }
319         mandatory_entries = 2 + DIV_ROUND_UP(meta2->name_length, EXFAT_ENAME_MAX);
320         if (meta1->continuations < mandatory_entries - 1)
321         {
322                 exfat_error("too few continuations (%hhu < %d)",
323                                 meta1->continuations, mandatory_entries - 1);
324                 return -EIO;
325         }
326
327         init_node_meta1(node, meta1);
328         init_node_meta2(node, meta2);
329         init_node_name(node, entries + 2, mandatory_entries - 2);
330
331         if (!check_node(ef, node, exfat_calc_checksum(entries, n), meta1, meta2))
332                 return -EIO;
333
334         return 0;
335 }
336
337 static int parse_file_entry(struct exfat* ef, struct exfat_node* parent,
338                 struct exfat_node** node, off_t* offset, int n)
339 {
340         struct exfat_entry entries[n];
341         int rc;
342
343         rc = read_entries(ef, parent, entries, n, *offset);
344         if (rc != 0)
345                 return rc;
346
347         /* a new node has zero references */
348         *node = allocate_node();
349         if (*node == NULL)
350                 return -ENOMEM;
351         (*node)->entry_offset = *offset;
352
353         rc = parse_file_entries(ef, *node, entries, n);
354         if (rc != 0)
355         {
356                 free(*node);
357                 return rc;
358         }
359
360         *offset += sizeof(struct exfat_entry[n]);
361         return 0;
362 }
363
364 static void decompress_upcase(uint16_t* output, const le16_t* source,
365                 size_t size)
366 {
367         size_t si;
368         size_t oi;
369
370         for (oi = 0; oi < EXFAT_UPCASE_CHARS; oi++)
371                 output[oi] = oi;
372
373         for (si = 0, oi = 0; si < size && oi < EXFAT_UPCASE_CHARS; si++)
374         {
375                 uint16_t ch = le16_to_cpu(source[si]);
376
377                 if (ch == 0xffff && si + 1 < size)      /* indicates a run */
378                         oi += le16_to_cpu(source[++si]);
379                 else
380                         output[oi++] = ch;
381         }
382 }
383
384 /*
385  * Read one entry in a directory at offset position and build a new node
386  * structure.
387  */
388 static int readdir(struct exfat* ef, struct exfat_node* parent,
389                 struct exfat_node** node, off_t* offset)
390 {
391         int rc;
392         struct exfat_entry entry;
393         const struct exfat_entry_meta1* meta1;
394         const struct exfat_entry_upcase* upcase;
395         const struct exfat_entry_bitmap* bitmap;
396         const struct exfat_entry_label* label;
397         uint64_t upcase_size = 0;
398         le16_t* upcase_comp = NULL;
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                         if (utf16_to_utf8(ef->label, label->name,
512                                                 sizeof(ef->label), EXFAT_ENAME_MAX) != 0)
513                                 return -EIO;
514                         break;
515
516                 default:
517                         if (!(entry.type & EXFAT_ENTRY_VALID))
518                                 break; /* deleted entry, ignore it */
519
520                         exfat_error("unknown entry type %#hhx", entry.type);
521                         if (!EXFAT_REPAIR(unknown_entry, ef, parent, &entry, *offset))
522                                 return -EIO;
523                 }
524                 *offset += sizeof(entry);
525         }
526         /* we never reach here */
527 }
528
529 int exfat_cache_directory(struct exfat* ef, struct exfat_node* dir)
530 {
531         off_t offset = 0;
532         int rc;
533         struct exfat_node* node;
534         struct exfat_node* current = NULL;
535
536         if (dir->is_cached)
537                 return 0; /* already cached */
538
539         while ((rc = readdir(ef, dir, &node, &offset)) == 0)
540         {
541                 node->parent = dir;
542                 if (current != NULL)
543                 {
544                         current->next = node;
545                         node->prev = current;
546                 }
547                 else
548                         dir->child = node;
549
550                 current = node;
551         }
552
553         if (rc != -ENOENT)
554         {
555                 /* rollback */
556                 for (current = dir->child; current; current = node)
557                 {
558                         node = current->next;
559                         free(current);
560                 }
561                 dir->child = NULL;
562                 return rc;
563         }
564
565         dir->is_cached = true;
566         return 0;
567 }
568
569 static void tree_attach(struct exfat_node* dir, struct exfat_node* node)
570 {
571         node->parent = dir;
572         if (dir->child)
573         {
574                 dir->child->prev = node;
575                 node->next = dir->child;
576         }
577         dir->child = node;
578 }
579
580 static void tree_detach(struct exfat_node* node)
581 {
582         if (node->prev)
583                 node->prev->next = node->next;
584         else /* this is the first node in the list */
585                 node->parent->child = node->next;
586         if (node->next)
587                 node->next->prev = node->prev;
588         node->parent = NULL;
589         node->prev = NULL;
590         node->next = NULL;
591 }
592
593 static void reset_cache(struct exfat* ef, struct exfat_node* node)
594 {
595         char buffer[EXFAT_UTF8_NAME_BUFFER_MAX];
596
597         while (node->child)
598         {
599                 struct exfat_node* p = node->child;
600                 reset_cache(ef, p);
601                 tree_detach(p);
602                 free(p);
603         }
604         node->is_cached = false;
605         if (node->references != 0)
606         {
607                 exfat_get_name(node, buffer);
608                 exfat_warn("non-zero reference counter (%d) for '%s'",
609                                 node->references, buffer);
610         }
611         if (node != ef->root && node->is_dirty)
612         {
613                 exfat_get_name(node, buffer);
614                 exfat_bug("node '%s' is dirty", buffer);
615         }
616         while (node->references)
617                 exfat_put_node(ef, node);
618 }
619
620 void exfat_reset_cache(struct exfat* ef)
621 {
622         reset_cache(ef, ef->root);
623 }
624
625 int exfat_flush_node(struct exfat* ef, struct exfat_node* node)
626 {
627         struct exfat_entry entries[1 + node->continuations];
628         struct exfat_entry_meta1* meta1 = (struct exfat_entry_meta1*) &entries[0];
629         struct exfat_entry_meta2* meta2 = (struct exfat_entry_meta2*) &entries[1];
630         int rc;
631
632         if (!node->is_dirty)
633                 return 0; /* no need to flush */
634
635         if (ef->ro)
636                 exfat_bug("unable to flush node to read-only FS");
637
638         if (node->parent == NULL)
639                 return 0; /* do not flush unlinked node */
640
641         rc = read_entries(ef, node->parent, entries, 1 + node->continuations,
642                         node->entry_offset);
643         if (rc != 0)
644                 return rc;
645         if (!check_entries(entries, 1 + node->continuations))
646                 return -EIO;
647
648         meta1->attrib = cpu_to_le16(node->attrib);
649         exfat_unix2exfat(node->mtime, &meta1->mdate, &meta1->mtime,
650                         &meta1->mtime_cs, &meta1->mtime_tzo);
651         exfat_unix2exfat(node->atime, &meta1->adate, &meta1->atime,
652                         NULL, &meta1->atime_tzo);
653         meta2->size = meta2->valid_size = cpu_to_le64(node->size);
654         meta2->start_cluster = cpu_to_le32(node->start_cluster);
655         meta2->flags = EXFAT_FLAG_ALWAYS1;
656         /* empty files must not be marked as contiguous */
657         if (node->size != 0 && node->is_contiguous)
658                 meta2->flags |= EXFAT_FLAG_CONTIGUOUS;
659         /* name hash remains unchanged, no need to recalculate it */
660
661         meta1->checksum = exfat_calc_checksum(entries, 1 + node->continuations);
662         rc = write_entries(ef, node->parent, entries, 1 + node->continuations,
663                         node->entry_offset);
664         if (rc != 0)
665                 return rc;
666
667         node->is_dirty = false;
668         return exfat_flush(ef);
669 }
670
671 static int erase_entries(struct exfat* ef, struct exfat_node* dir, int n,
672                 off_t offset)
673 {
674         struct exfat_entry entries[n];
675         int rc;
676         int i;
677
678         rc = read_entries(ef, dir, entries, n, offset);
679         if (rc != 0)
680                 return rc;
681         for (i = 0; i < n; i++)
682                 entries[i].type &= ~EXFAT_ENTRY_VALID;
683         return write_entries(ef, dir, entries, n, offset);
684 }
685
686 static int erase_node(struct exfat* ef, struct exfat_node* node)
687 {
688         int rc;
689
690         exfat_get_node(node->parent);
691         rc = erase_entries(ef, node->parent, 1 + node->continuations,
692                         node->entry_offset);
693         if (rc != 0)
694         {
695                 exfat_put_node(ef, node->parent);
696                 return rc;
697         }
698         rc = exfat_flush_node(ef, node->parent);
699         exfat_put_node(ef, node->parent);
700         return rc;
701 }
702
703 static int shrink_directory(struct exfat* ef, struct exfat_node* dir,
704                 off_t deleted_offset)
705 {
706         const struct exfat_node* node;
707         const struct exfat_node* last_node;
708         uint64_t entries = 0;
709         uint64_t new_size;
710
711         if (!(dir->attrib & EXFAT_ATTRIB_DIR))
712                 exfat_bug("attempted to shrink a file");
713         if (!dir->is_cached)
714                 exfat_bug("attempted to shrink uncached directory");
715
716         for (last_node = node = dir->child; node; node = node->next)
717         {
718                 if (deleted_offset < node->entry_offset)
719                 {
720                         /* there are other entries after the removed one, no way to shrink
721                            this directory */
722                         return 0;
723                 }
724                 if (last_node->entry_offset < node->entry_offset)
725                         last_node = node;
726         }
727
728         if (last_node)
729         {
730                 /* offset of the last entry */
731                 entries += last_node->entry_offset / sizeof(struct exfat_entry);
732                 /* two subentries with meta info */
733                 entries += 2;
734                 /* subentries with file name */
735                 entries += DIV_ROUND_UP(utf16_length(last_node->name),
736                                 EXFAT_ENAME_MAX);
737         }
738
739         new_size = DIV_ROUND_UP(entries * sizeof(struct exfat_entry),
740                                  CLUSTER_SIZE(*ef->sb)) * CLUSTER_SIZE(*ef->sb);
741         if (new_size == 0) /* directory always has at least 1 cluster */
742                 new_size = CLUSTER_SIZE(*ef->sb);
743         if (new_size == dir->size)
744                 return 0;
745         return exfat_truncate(ef, dir, new_size, true);
746 }
747
748 static int delete(struct exfat* ef, struct exfat_node* node)
749 {
750         struct exfat_node* parent = node->parent;
751         off_t deleted_offset = node->entry_offset;
752         int rc;
753
754         exfat_get_node(parent);
755         rc = erase_node(ef, node);
756         if (rc != 0)
757         {
758                 exfat_put_node(ef, parent);
759                 return rc;
760         }
761         tree_detach(node);
762         rc = shrink_directory(ef, parent, deleted_offset);
763         node->is_unlinked = true;
764         if (rc != 0)
765         {
766                 exfat_flush_node(ef, parent);
767                 exfat_put_node(ef, parent);
768                 return rc;
769         }
770         exfat_update_mtime(parent);
771         rc = exfat_flush_node(ef, parent);
772         exfat_put_node(ef, parent);
773         return rc;
774 }
775
776 int exfat_unlink(struct exfat* ef, struct exfat_node* node)
777 {
778         if (node->attrib & EXFAT_ATTRIB_DIR)
779                 return -EISDIR;
780         return delete(ef, node);
781 }
782
783 int exfat_rmdir(struct exfat* ef, struct exfat_node* node)
784 {
785         int rc;
786
787         if (!(node->attrib & EXFAT_ATTRIB_DIR))
788                 return -ENOTDIR;
789         /* check that directory is empty */
790         rc = exfat_cache_directory(ef, node);
791         if (rc != 0)
792                 return rc;
793         if (node->child)
794                 return -ENOTEMPTY;
795         return delete(ef, node);
796 }
797
798 static int check_slot(struct exfat* ef, struct exfat_node* dir, off_t offset,
799                 int n)
800 {
801         struct exfat_entry entries[n];
802         int rc;
803         size_t i;
804
805         /* Root directory contains entries, that don't have any nodes associated
806            with them (clusters bitmap, upper case table, label). We need to be
807            careful not to overwrite them. */
808         if (dir != ef->root)
809                 return 0;
810
811         rc = read_entries(ef, dir, entries, n, offset);
812         if (rc != 0)
813                 return rc;
814         for (i = 0; i < n; i++)
815                 if (entries[i].type & EXFAT_ENTRY_VALID)
816                         return -EINVAL;
817         return 0;
818 }
819
820 static int find_slot(struct exfat* ef, struct exfat_node* dir,
821                 off_t* offset, int n)
822 {
823         bitmap_t* dmap;
824         struct exfat_node* p;
825         size_t i;
826         int contiguous = 0;
827
828         if (!dir->is_cached)
829                 exfat_bug("directory is not cached");
830
831         /* build a bitmap of valid entries in the directory */
832         dmap = calloc(BMAP_SIZE(dir->size / sizeof(struct exfat_entry)),
833                         sizeof(bitmap_t));
834         if (dmap == NULL)
835         {
836                 exfat_error("failed to allocate directory bitmap (%"PRIu64")",
837                                 dir->size / sizeof(struct exfat_entry));
838                 return -ENOMEM;
839         }
840         for (p = dir->child; p != NULL; p = p->next)
841                 for (i = 0; i < 1 + p->continuations; i++)
842                         BMAP_SET(dmap, p->entry_offset / sizeof(struct exfat_entry) + i);
843
844         /* find a slot in the directory entries bitmap */
845         for (i = 0; i < dir->size / sizeof(struct exfat_entry); i++)
846         {
847                 if (BMAP_GET(dmap, i) == 0)
848                 {
849                         if (contiguous++ == 0)
850                                 *offset = (off_t) i * sizeof(struct exfat_entry);
851                         if (contiguous == n)
852                                 /* suitable slot is found, check that it's not occupied */
853                                 switch (check_slot(ef, dir, *offset, n))
854                                 {
855                                 case 0:
856                                         free(dmap);
857                                         return 0;
858                                 case -EIO:
859                                         free(dmap);
860                                         return -EIO;
861                                 case -EINVAL:
862                                         /* slot at (i-n) is occupied, go back and check (i-n+1) */
863                                         i -= contiguous - 1;
864                                         contiguous = 0;
865                                         break;
866                                 }
867                 }
868                 else
869                         contiguous = 0;
870         }
871         free(dmap);
872
873         /* no suitable slots found, extend the directory */
874         if (contiguous == 0)
875                 *offset = dir->size;
876         return exfat_truncate(ef, dir,
877                         ROUND_UP(dir->size + sizeof(struct exfat_entry[n - contiguous]),
878                                         CLUSTER_SIZE(*ef->sb)),
879                         true);
880 }
881
882 static int commit_entry(struct exfat* ef, struct exfat_node* dir,
883                 const le16_t* name, off_t offset, uint16_t attrib)
884 {
885         struct exfat_node* node;
886         const size_t name_length = utf16_length(name);
887         const int name_entries = DIV_ROUND_UP(name_length, EXFAT_ENAME_MAX);
888         struct exfat_entry entries[2 + name_entries];
889         struct exfat_entry_meta1* meta1 = (struct exfat_entry_meta1*) &entries[0];
890         struct exfat_entry_meta2* meta2 = (struct exfat_entry_meta2*) &entries[1];
891         int i;
892         int rc;
893
894         memset(entries, 0, sizeof(struct exfat_entry[2]));
895
896         meta1->type = EXFAT_ENTRY_FILE;
897         meta1->continuations = 1 + name_entries;
898         meta1->attrib = cpu_to_le16(attrib);
899         exfat_unix2exfat(time(NULL), &meta1->crdate, &meta1->crtime,
900                         &meta1->crtime_cs, &meta1->crtime_tzo);
901         meta1->adate = meta1->mdate = meta1->crdate;
902         meta1->atime = meta1->mtime = meta1->crtime;
903         meta1->mtime_cs = meta1->crtime_cs; /* there is no atime_cs */
904         meta1->atime_tzo = meta1->mtime_tzo = meta1->crtime_tzo;
905
906         meta2->type = EXFAT_ENTRY_FILE_INFO;
907         meta2->flags = EXFAT_FLAG_ALWAYS1;
908         meta2->name_length = name_length;
909         meta2->name_hash = exfat_calc_name_hash(ef, name, name_length);
910         meta2->start_cluster = cpu_to_le32(EXFAT_CLUSTER_FREE);
911
912         for (i = 0; i < name_entries; i++)
913         {
914                 struct exfat_entry_name* name_entry;
915
916                 name_entry = (struct exfat_entry_name*) &entries[2 + i];
917                 name_entry->type = EXFAT_ENTRY_FILE_NAME;
918                 name_entry->__unknown = 0;
919                 memcpy(name_entry->name, name + i * EXFAT_ENAME_MAX,
920                                 EXFAT_ENAME_MAX * sizeof(le16_t));
921         }
922
923         meta1->checksum = exfat_calc_checksum(entries, 2 + name_entries);
924         rc = write_entries(ef, dir, entries, 2 + name_entries, offset);
925         if (rc != 0)
926                 return rc;
927
928         node = allocate_node();
929         if (node == NULL)
930                 return -ENOMEM;
931         node->entry_offset = offset;
932         memcpy(node->name, name, name_length * sizeof(le16_t));
933         init_node_meta1(node, meta1);
934         init_node_meta2(node, meta2);
935
936         tree_attach(dir, node);
937         return 0;
938 }
939
940 static int create(struct exfat* ef, const char* path, uint16_t attrib)
941 {
942         struct exfat_node* dir;
943         struct exfat_node* existing;
944         off_t offset = -1;
945         le16_t name[EXFAT_NAME_MAX + 1];
946         int rc;
947
948         rc = exfat_split(ef, &dir, &existing, name, path);
949         if (rc != 0)
950                 return rc;
951         if (existing != NULL)
952         {
953                 exfat_put_node(ef, existing);
954                 exfat_put_node(ef, dir);
955                 return -EEXIST;
956         }
957
958         rc = find_slot(ef, dir, &offset,
959                         2 + DIV_ROUND_UP(utf16_length(name), EXFAT_ENAME_MAX));
960         if (rc != 0)
961         {
962                 exfat_put_node(ef, dir);
963                 return rc;
964         }
965         rc = commit_entry(ef, dir, name, offset, attrib);
966         if (rc != 0)
967         {
968                 exfat_put_node(ef, dir);
969                 return rc;
970         }
971         exfat_update_mtime(dir);
972         rc = exfat_flush_node(ef, dir);
973         exfat_put_node(ef, dir);
974         return rc;
975 }
976
977 int exfat_mknod(struct exfat* ef, const char* path)
978 {
979         return create(ef, path, EXFAT_ATTRIB_ARCH);
980 }
981
982 int exfat_mkdir(struct exfat* ef, const char* path)
983 {
984         int rc;
985         struct exfat_node* node;
986
987         rc = create(ef, path, EXFAT_ATTRIB_DIR);
988         if (rc != 0)
989                 return rc;
990         rc = exfat_lookup(ef, &node, path);
991         if (rc != 0)
992                 return 0;
993         /* directories always have at least one cluster */
994         rc = exfat_truncate(ef, node, CLUSTER_SIZE(*ef->sb), true);
995         if (rc != 0)
996         {
997                 delete(ef, node);
998                 exfat_put_node(ef, node);
999                 return rc;
1000         }
1001         rc = exfat_flush_node(ef, node);
1002         if (rc != 0)
1003         {
1004                 delete(ef, node);
1005                 exfat_put_node(ef, node);
1006                 return rc;
1007         }
1008         exfat_put_node(ef, node);
1009         return 0;
1010 }
1011
1012 static int rename_entry(struct exfat* ef, struct exfat_node* dir,
1013                 struct exfat_node* node, const le16_t* name, off_t new_offset)
1014 {
1015         const size_t name_length = utf16_length(name);
1016         const int name_entries = DIV_ROUND_UP(name_length, EXFAT_ENAME_MAX);
1017         struct exfat_entry entries[2 + name_entries];
1018         struct exfat_entry_meta1* meta1 = (struct exfat_entry_meta1*) &entries[0];
1019         struct exfat_entry_meta2* meta2 = (struct exfat_entry_meta2*) &entries[1];
1020         int rc;
1021         int i;
1022
1023         rc = read_entries(ef, node->parent, entries, 2, node->entry_offset);
1024         if (rc != 0)
1025                 return rc;
1026
1027         meta1->continuations = 1 + name_entries;
1028         meta2->name_length = name_length;
1029         meta2->name_hash = exfat_calc_name_hash(ef, name, name_length);
1030
1031         rc = erase_node(ef, node);
1032         if (rc != 0)
1033                 return rc;
1034
1035         node->entry_offset = new_offset;
1036         node->continuations = 1 + name_entries;
1037
1038         for (i = 0; i < name_entries; i++)
1039         {
1040                 struct exfat_entry_name* name_entry;
1041
1042                 name_entry = (struct exfat_entry_name*) &entries[2 + i];
1043                 name_entry->type = EXFAT_ENTRY_FILE_NAME;
1044                 name_entry->__unknown = 0;
1045                 memcpy(name_entry->name, name + i * EXFAT_ENAME_MAX,
1046                                 EXFAT_ENAME_MAX * sizeof(le16_t));
1047         }
1048
1049         meta1->checksum = exfat_calc_checksum(entries, 2 + name_entries);
1050         rc = write_entries(ef, dir, entries, 2 + name_entries, new_offset);
1051         if (rc != 0)
1052                 return rc;
1053
1054         memcpy(node->name, name, (EXFAT_NAME_MAX + 1) * sizeof(le16_t));
1055         tree_detach(node);
1056         tree_attach(dir, node);
1057         return 0;
1058 }
1059
1060 int exfat_rename(struct exfat* ef, const char* old_path, const char* new_path)
1061 {
1062         struct exfat_node* node;
1063         struct exfat_node* existing;
1064         struct exfat_node* dir;
1065         off_t offset = -1;
1066         le16_t name[EXFAT_NAME_MAX + 1];
1067         int rc;
1068
1069         rc = exfat_lookup(ef, &node, old_path);
1070         if (rc != 0)
1071                 return rc;
1072
1073         rc = exfat_split(ef, &dir, &existing, name, new_path);
1074         if (rc != 0)
1075         {
1076                 exfat_put_node(ef, node);
1077                 return rc;
1078         }
1079
1080         /* check that target is not a subdirectory of the source */
1081         if (node->attrib & EXFAT_ATTRIB_DIR)
1082         {
1083                 struct exfat_node* p;
1084
1085                 for (p = dir; p; p = p->parent)
1086                         if (node == p)
1087                         {
1088                                 if (existing != NULL)
1089                                         exfat_put_node(ef, existing);
1090                                 exfat_put_node(ef, dir);
1091                                 exfat_put_node(ef, node);
1092                                 return -EINVAL;
1093                         }
1094         }
1095
1096         if (existing != NULL)
1097         {
1098                 /* remove target if it's not the same node as source */
1099                 if (existing != node)
1100                 {
1101                         if (existing->attrib & EXFAT_ATTRIB_DIR)
1102                         {
1103                                 if (node->attrib & EXFAT_ATTRIB_DIR)
1104                                         rc = exfat_rmdir(ef, existing);
1105                                 else
1106                                         rc = -ENOTDIR;
1107                         }
1108                         else
1109                         {
1110                                 if (!(node->attrib & EXFAT_ATTRIB_DIR))
1111                                         rc = exfat_unlink(ef, existing);
1112                                 else
1113                                         rc = -EISDIR;
1114                         }
1115                         exfat_put_node(ef, existing);
1116                         if (rc != 0)
1117                         {
1118                                 /* free clusters even if something went wrong; overwise they
1119                                    will be just lost */
1120                                 exfat_cleanup_node(ef, existing);
1121                                 exfat_put_node(ef, dir);
1122                                 exfat_put_node(ef, node);
1123                                 return rc;
1124                         }
1125                         rc = exfat_cleanup_node(ef, existing);
1126                         if (rc != 0)
1127                         {
1128                                 exfat_put_node(ef, dir);
1129                                 exfat_put_node(ef, node);
1130                                 return rc;
1131                         }
1132                 }
1133                 else
1134                         exfat_put_node(ef, existing);
1135         }
1136
1137         rc = find_slot(ef, dir, &offset,
1138                         2 + DIV_ROUND_UP(utf16_length(name), EXFAT_ENAME_MAX));
1139         if (rc != 0)
1140         {
1141                 exfat_put_node(ef, dir);
1142                 exfat_put_node(ef, node);
1143                 return rc;
1144         }
1145         rc = rename_entry(ef, dir, node, name, offset);
1146         if (rc != 0)
1147         {
1148                 exfat_put_node(ef, dir);
1149                 exfat_put_node(ef, node);
1150                 return rc;
1151         }
1152         rc = exfat_flush_node(ef, dir);
1153         exfat_put_node(ef, dir);
1154         exfat_put_node(ef, node);
1155         /* node itself is not marked as dirty, no need to flush it */
1156         return rc;
1157 }
1158
1159 void exfat_utimes(struct exfat_node* node, const struct timespec tv[2])
1160 {
1161         node->atime = tv[0].tv_sec;
1162         node->mtime = tv[1].tv_sec;
1163         node->is_dirty = true;
1164 }
1165
1166 void exfat_update_atime(struct exfat_node* node)
1167 {
1168         node->atime = time(NULL);
1169         node->is_dirty = true;
1170 }
1171
1172 void exfat_update_mtime(struct exfat_node* node)
1173 {
1174         node->mtime = time(NULL);
1175         node->is_dirty = true;
1176 }
1177
1178 const char* exfat_get_label(struct exfat* ef)
1179 {
1180         return ef->label;
1181 }
1182
1183 static int find_label(struct exfat* ef, off_t* offset)
1184 {
1185         struct exfat_entry entry;
1186         int rc;
1187
1188         for (*offset = 0; ; *offset += sizeof(entry))
1189         {
1190                 rc = read_entries(ef, ef->root, &entry, 1, *offset);
1191                 if (rc != 0)
1192                         return rc;
1193
1194                 if (entry.type == EXFAT_ENTRY_LABEL)
1195                         return 0;
1196         }
1197 }
1198
1199 int exfat_set_label(struct exfat* ef, const char* label)
1200 {
1201         le16_t label_utf16[EXFAT_ENAME_MAX + 1];
1202         int rc;
1203         off_t offset;
1204         struct exfat_entry_label entry;
1205
1206         memset(label_utf16, 0, sizeof(label_utf16));
1207         rc = utf8_to_utf16(label_utf16, label, EXFAT_ENAME_MAX + 1, strlen(label));
1208         if (rc != 0)
1209                 return rc;
1210
1211         rc = find_label(ef, &offset);
1212         if (rc == -ENOENT)
1213                 rc = find_slot(ef, ef->root, &offset, 1);
1214         if (rc != 0)
1215                 return rc;
1216
1217         entry.type = EXFAT_ENTRY_LABEL;
1218         entry.length = utf16_length(label_utf16);
1219         memcpy(entry.name, label_utf16, sizeof(entry.name));
1220         if (entry.length == 0)
1221                 entry.type ^= EXFAT_ENTRY_VALID;
1222
1223         rc = write_entries(ef, ef->root, (struct exfat_entry*) &entry, 1, offset);
1224         if (rc != 0)
1225                 return rc;
1226
1227         strcpy(ef->label, label);
1228         return 0;
1229 }