OSDN Git Service

Relaxed node size check. This fixes pagefile.sys error.
[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-2013  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 /* on-disk nodes iterator */
29 struct iterator
30 {
31         cluster_t cluster;
32         off_t offset;
33         int contiguous;
34         char* chunk;
35 };
36
37 struct exfat_node* exfat_get_node(struct exfat_node* node)
38 {
39         /* if we switch to multi-threaded mode we will need atomic
40            increment here and atomic decrement in exfat_put_node() */
41         node->references++;
42         return node;
43 }
44
45 void exfat_put_node(struct exfat* ef, struct exfat_node* node)
46 {
47         if (--node->references < 0)
48         {
49                 char buffer[UTF8_BYTES(EXFAT_NAME_MAX) + 1];
50                 exfat_get_name(node, buffer, sizeof(buffer) - 1);
51                 exfat_bug("reference counter of `%s' is below zero", buffer);
52         }
53
54         if (node->references == 0)
55         {
56                 /* FIXME handle I/O error */
57                 if (exfat_flush_node(ef, node) != 0)
58                         exfat_bug("node flush failed");
59                 if (node->flags & EXFAT_ATTRIB_UNLINKED)
60                 {
61                         /* free all clusters and node structure itself */
62                         exfat_truncate(ef, node, 0, true);
63                         free(node);
64                 }
65                 /* FIXME handle I/O error */
66                 if (exfat_flush(ef) != 0)
67                         exfat_bug("flush failed");
68         }
69 }
70
71 /**
72  * Cluster + offset from the beginning of the directory to absolute offset.
73  */
74 static off_t co2o(struct exfat* ef, cluster_t cluster, off_t offset)
75 {
76         return exfat_c2o(ef, cluster) + offset % CLUSTER_SIZE(*ef->sb);
77 }
78
79 static int opendir(struct exfat* ef, const struct exfat_node* dir,
80                 struct iterator* it)
81 {
82         if (!(dir->flags & EXFAT_ATTRIB_DIR))
83                 exfat_bug("not a directory");
84         it->cluster = dir->start_cluster;
85         it->offset = 0;
86         it->contiguous = IS_CONTIGUOUS(*dir);
87         it->chunk = malloc(CLUSTER_SIZE(*ef->sb));
88         if (it->chunk == NULL)
89         {
90                 exfat_error("out of memory");
91                 return -ENOMEM;
92         }
93         if (exfat_pread(ef->dev, it->chunk, CLUSTER_SIZE(*ef->sb),
94                         exfat_c2o(ef, it->cluster)) < 0)
95         {
96                 exfat_error("failed to read directory cluster %#x", it->cluster);
97                 return -EIO;
98         }
99         return 0;
100 }
101
102 static void closedir(struct iterator* it)
103 {
104         it->cluster = 0;
105         it->offset = 0;
106         it->contiguous = 0;
107         free(it->chunk);
108         it->chunk = NULL;
109 }
110
111 static int fetch_next_entry(struct exfat* ef, const struct exfat_node* parent,
112                 struct iterator* it)
113 {
114         /* move iterator to the next entry in the directory */
115         it->offset += sizeof(struct exfat_entry);
116         /* fetch the next cluster if needed */
117         if ((it->offset & (CLUSTER_SIZE(*ef->sb) - 1)) == 0)
118         {
119                 /* reached the end of directory; the caller should check this
120                    condition too */
121                 if (it->offset >= parent->size)
122                         return 0;
123                 it->cluster = exfat_next_cluster(ef, parent, it->cluster);
124                 if (CLUSTER_INVALID(it->cluster))
125                 {
126                         exfat_error("invalid cluster 0x%x while reading directory",
127                                         it->cluster);
128                         return 1;
129                 }
130                 if (exfat_pread(ef->dev, it->chunk, CLUSTER_SIZE(*ef->sb),
131                                 exfat_c2o(ef, it->cluster)) < 0)
132                 {
133                         exfat_error("failed to read the next directory cluster %#x",
134                                         it->cluster);
135                         return 1;
136                 }
137         }
138         return 0;
139 }
140
141 static struct exfat_node* allocate_node(void)
142 {
143         struct exfat_node* node = malloc(sizeof(struct exfat_node));
144         if (node == NULL)
145         {
146                 exfat_error("failed to allocate node");
147                 return NULL;
148         }
149         memset(node, 0, sizeof(struct exfat_node));
150         return node;
151 }
152
153 static void init_node_meta1(struct exfat_node* node,
154                 const struct exfat_entry_meta1* meta1)
155 {
156         node->flags = le16_to_cpu(meta1->attrib);
157         node->mtime = exfat_exfat2unix(meta1->mdate, meta1->mtime,
158                         meta1->mtime_cs);
159         /* there is no centiseconds field for atime */
160         node->atime = exfat_exfat2unix(meta1->adate, meta1->atime, 0);
161 }
162
163 static void init_node_meta2(struct exfat_node* node,
164                 const struct exfat_entry_meta2* meta2)
165 {
166         node->size = le64_to_cpu(meta2->size);
167         node->start_cluster = le32_to_cpu(meta2->start_cluster);
168         node->fptr_cluster = node->start_cluster;
169         if (meta2->flags & EXFAT_FLAG_CONTIGUOUS)
170                 node->flags |= EXFAT_ATTRIB_CONTIGUOUS;
171 }
172
173 static const struct exfat_entry* get_entry_ptr(const struct exfat* ef,
174                 const struct iterator* it)
175 {
176         return (const struct exfat_entry*)
177                         (it->chunk + it->offset % CLUSTER_SIZE(*ef->sb));
178 }
179
180 static bool check_node(const struct exfat_node* node, uint16_t actual_checksum,
181                 uint16_t reference_checksum, uint64_t real_size)
182 {
183         char buffer[UTF8_BYTES(EXFAT_NAME_MAX) + 1];
184
185         /*
186            Validate checksum first. If it's invalid all other fields probably
187            contain just garbage.
188         */
189         if (actual_checksum != reference_checksum)
190         {
191                 exfat_get_name(node, buffer, sizeof(buffer) - 1);
192                 exfat_error("`%s' has invalid checksum (%#hx != %#hx)", buffer,
193                                 actual_checksum, reference_checksum);
194                 return false;
195         }
196
197         /*
198            It's unclear what is real_size field needed for. It usually equals to
199            the size but may contain any value less than size (including 0).
200         */
201         if (real_size > node->size)
202         {
203                 exfat_get_name(node, buffer, sizeof(buffer) - 1);
204                 exfat_error("`%s' has real size (%"PRIu64") greater than size "
205                                 "(%"PRIu64")", buffer, real_size, node->size);
206                 return false;
207         }
208
209         return true;
210 }
211
212 /*
213  * Reads one entry in directory at position pointed by iterator and fills
214  * node structure.
215  */
216 static int readdir(struct exfat* ef, const struct exfat_node* parent,
217                 struct exfat_node** node, struct iterator* it)
218 {
219         int rc = -EIO;
220         const struct exfat_entry* entry;
221         const struct exfat_entry_meta1* meta1;
222         const struct exfat_entry_meta2* meta2;
223         const struct exfat_entry_name* file_name;
224         const struct exfat_entry_upcase* upcase;
225         const struct exfat_entry_bitmap* bitmap;
226         const struct exfat_entry_label* label;
227         uint8_t continuations = 0;
228         le16_t* namep = NULL;
229         uint16_t reference_checksum = 0;
230         uint16_t actual_checksum = 0;
231         uint64_t real_size = 0;
232
233         *node = NULL;
234
235         for (;;)
236         {
237                 if (it->offset >= parent->size)
238                 {
239                         if (continuations != 0)
240                         {
241                                 exfat_error("expected %hhu continuations", continuations);
242                                 goto error;
243                         }
244                         return -ENOENT; /* that's OK, means end of directory */
245                 }
246
247                 entry = get_entry_ptr(ef, it);
248                 switch (entry->type)
249                 {
250                 case EXFAT_ENTRY_FILE:
251                         if (continuations != 0)
252                         {
253                                 exfat_error("expected %hhu continuations before new entry",
254                                                 continuations);
255                                 goto error;
256                         }
257                         meta1 = (const struct exfat_entry_meta1*) entry;
258                         continuations = meta1->continuations;
259                         /* each file entry must have at least 2 continuations:
260                            info and name */
261                         if (continuations < 2)
262                         {
263                                 exfat_error("too few continuations (%hhu)", continuations);
264                                 goto error;
265                         }
266                         if (continuations > 1 +
267                                         DIV_ROUND_UP(EXFAT_NAME_MAX, EXFAT_ENAME_MAX))
268                         {
269                                 exfat_error("too many continuations (%hhu)", continuations);
270                                 goto error;
271                         }
272                         reference_checksum = le16_to_cpu(meta1->checksum);
273                         actual_checksum = exfat_start_checksum(meta1);
274                         *node = allocate_node();
275                         if (*node == NULL)
276                         {
277                                 rc = -ENOMEM;
278                                 goto error;
279                         }
280                         /* new node has zero reference counter */
281                         (*node)->entry_cluster = it->cluster;
282                         (*node)->entry_offset = it->offset;
283                         init_node_meta1(*node, meta1);
284                         namep = (*node)->name;
285                         break;
286
287                 case EXFAT_ENTRY_FILE_INFO:
288                         if (continuations < 2)
289                         {
290                                 exfat_error("unexpected continuation (%hhu)",
291                                                 continuations);
292                                 goto error;
293                         }
294                         meta2 = (const struct exfat_entry_meta2*) entry;
295                         if (meta2->flags & ~(EXFAT_FLAG_ALWAYS1 | EXFAT_FLAG_CONTIGUOUS))
296                         {
297                                 exfat_error("unknown flags in meta2 (0x%hhx)", meta2->flags);
298                                 goto error;
299                         }
300                         init_node_meta2(*node, meta2);
301                         actual_checksum = exfat_add_checksum(entry, actual_checksum);
302                         real_size = le64_to_cpu(meta2->real_size);
303                         /* empty files must be marked as non-contiguous */
304                         if ((*node)->size == 0 && (meta2->flags & EXFAT_FLAG_CONTIGUOUS))
305                         {
306                                 exfat_error("empty file marked as contiguous (0x%hhx)",
307                                                 meta2->flags);
308                                 goto error;
309                         }
310                         /* directories must be aligned on at cluster boundary */
311                         if (((*node)->flags & EXFAT_ATTRIB_DIR) &&
312                                 (*node)->size % CLUSTER_SIZE(*ef->sb) != 0)
313                         {
314                                 exfat_error("directory has invalid size %"PRIu64" bytes",
315                                                 (*node)->size);
316                                 goto error;
317                         }
318                         --continuations;
319                         break;
320
321                 case EXFAT_ENTRY_FILE_NAME:
322                         if (continuations == 0)
323                         {
324                                 exfat_error("unexpected continuation");
325                                 goto error;
326                         }
327                         file_name = (const struct exfat_entry_name*) entry;
328                         actual_checksum = exfat_add_checksum(entry, actual_checksum);
329
330                         memcpy(namep, file_name->name,
331                                         MIN(EXFAT_ENAME_MAX,
332                                                 ((*node)->name + EXFAT_NAME_MAX - namep)) *
333                                         sizeof(le16_t));
334                         namep += EXFAT_ENAME_MAX;
335                         if (--continuations == 0)
336                         {
337                                 if (!check_node(*node, actual_checksum, reference_checksum,
338                                                 real_size))
339                                         goto error;
340                                 if (fetch_next_entry(ef, parent, it) != 0)
341                                         goto error;
342                                 return 0; /* entry completed */
343                         }
344                         break;
345
346                 case EXFAT_ENTRY_UPCASE:
347                         if (ef->upcase != NULL)
348                                 break;
349                         upcase = (const struct exfat_entry_upcase*) entry;
350                         if (CLUSTER_INVALID(le32_to_cpu(upcase->start_cluster)))
351                         {
352                                 exfat_error("invalid cluster 0x%x in upcase table",
353                                                 le32_to_cpu(upcase->start_cluster));
354                                 goto error;
355                         }
356                         if (le64_to_cpu(upcase->size) == 0 ||
357                                 le64_to_cpu(upcase->size) > 0xffff * sizeof(uint16_t) ||
358                                 le64_to_cpu(upcase->size) % sizeof(uint16_t) != 0)
359                         {
360                                 exfat_error("bad upcase table size (%"PRIu64" bytes)",
361                                                 le64_to_cpu(upcase->size));
362                                 goto error;
363                         }
364                         ef->upcase = malloc(le64_to_cpu(upcase->size));
365                         if (ef->upcase == NULL)
366                         {
367                                 exfat_error("failed to allocate upcase table (%"PRIu64" bytes)",
368                                                 le64_to_cpu(upcase->size));
369                                 rc = -ENOMEM;
370                                 goto error;
371                         }
372                         ef->upcase_chars = le64_to_cpu(upcase->size) / sizeof(le16_t);
373
374                         if (exfat_pread(ef->dev, ef->upcase, le64_to_cpu(upcase->size),
375                                         exfat_c2o(ef, le32_to_cpu(upcase->start_cluster))) < 0)
376                         {
377                                 exfat_error("failed to read upper case table "
378                                                 "(%"PRIu64" bytes starting at cluster %#x)",
379                                                 le64_to_cpu(upcase->size),
380                                                 le32_to_cpu(upcase->start_cluster));
381                                 goto error;
382                         }
383                         break;
384
385                 case EXFAT_ENTRY_BITMAP:
386                         bitmap = (const struct exfat_entry_bitmap*) entry;
387                         ef->cmap.start_cluster = le32_to_cpu(bitmap->start_cluster);
388                         if (CLUSTER_INVALID(ef->cmap.start_cluster))
389                         {
390                                 exfat_error("invalid cluster 0x%x in clusters bitmap",
391                                                 ef->cmap.start_cluster);
392                                 goto error;
393                         }
394                         ef->cmap.size = le32_to_cpu(ef->sb->cluster_count) -
395                                 EXFAT_FIRST_DATA_CLUSTER;
396                         if (le64_to_cpu(bitmap->size) < DIV_ROUND_UP(ef->cmap.size, 8))
397                         {
398                                 exfat_error("invalid clusters bitmap size: %"PRIu64
399                                                 " (expected at least %u)",
400                                                 le64_to_cpu(bitmap->size),
401                                                 DIV_ROUND_UP(ef->cmap.size, 8));
402                                 goto error;
403                         }
404                         /* FIXME bitmap can be rather big, up to 512 MB */
405                         ef->cmap.chunk_size = ef->cmap.size;
406                         ef->cmap.chunk = malloc(BMAP_SIZE(ef->cmap.chunk_size));
407                         if (ef->cmap.chunk == NULL)
408                         {
409                                 exfat_error("failed to allocate clusters bitmap chunk "
410                                                 "(%"PRIu64" bytes)", le64_to_cpu(bitmap->size));
411                                 rc = -ENOMEM;
412                                 goto error;
413                         }
414
415                         if (exfat_pread(ef->dev, ef->cmap.chunk,
416                                         BMAP_SIZE(ef->cmap.chunk_size),
417                                         exfat_c2o(ef, ef->cmap.start_cluster)) < 0)
418                         {
419                                 exfat_error("failed to read clusters bitmap "
420                                                 "(%"PRIu64" bytes starting at cluster %#x)",
421                                                 le64_to_cpu(bitmap->size), ef->cmap.start_cluster);
422                                 goto error;
423                         }
424                         break;
425
426                 case EXFAT_ENTRY_LABEL:
427                         label = (const struct exfat_entry_label*) entry;
428                         if (label->length > EXFAT_ENAME_MAX)
429                         {
430                                 exfat_error("too long label (%hhu chars)", label->length);
431                                 goto error;
432                         }
433                         if (utf16_to_utf8(ef->label, label->name,
434                                                 sizeof(ef->label) - 1, EXFAT_ENAME_MAX) != 0)
435                                 goto error;
436                         break;
437
438                 default:
439                         if (entry->type & EXFAT_ENTRY_VALID)
440                         {
441                                 exfat_error("unknown entry type 0x%hhx", entry->type);
442                                 goto error;
443                         }
444                         break;
445                 }
446
447                 if (fetch_next_entry(ef, parent, it) != 0)
448                         goto error;
449         }
450         /* we never reach here */
451
452 error:
453         free(*node);
454         *node = NULL;
455         return rc;
456 }
457
458 int exfat_cache_directory(struct exfat* ef, struct exfat_node* dir)
459 {
460         struct iterator it;
461         int rc;
462         struct exfat_node* node;
463         struct exfat_node* current = NULL;
464
465         if (dir->flags & EXFAT_ATTRIB_CACHED)
466                 return 0; /* already cached */
467
468         rc = opendir(ef, dir, &it);
469         if (rc != 0)
470                 return rc;
471         while ((rc = readdir(ef, dir, &node, &it)) == 0)
472         {
473                 node->parent = dir;
474                 if (current != NULL)
475                 {
476                         current->next = node;
477                         node->prev = current;
478                 }
479                 else
480                         dir->child = node;
481
482                 current = node;
483         }
484         closedir(&it);
485
486         if (rc != -ENOENT)
487         {
488                 /* rollback */
489                 for (current = dir->child; current; current = node)
490                 {
491                         node = current->next;
492                         free(current);
493                 }
494                 dir->child = NULL;
495                 return rc;
496         }
497
498         dir->flags |= EXFAT_ATTRIB_CACHED;
499         return 0;
500 }
501
502 static void tree_attach(struct exfat_node* dir, struct exfat_node* node)
503 {
504         node->parent = dir;
505         if (dir->child)
506         {
507                 dir->child->prev = node;
508                 node->next = dir->child;
509         }
510         dir->child = node;
511 }
512
513 static void tree_detach(struct exfat_node* node)
514 {
515         if (node->prev)
516                 node->prev->next = node->next;
517         else /* this is the first node in the list */
518                 node->parent->child = node->next;
519         if (node->next)
520                 node->next->prev = node->prev;
521         node->parent = NULL;
522         node->prev = NULL;
523         node->next = NULL;
524 }
525
526 static void reset_cache(struct exfat* ef, struct exfat_node* node)
527 {
528         while (node->child)
529         {
530                 struct exfat_node* p = node->child;
531                 reset_cache(ef, p);
532                 tree_detach(p);
533                 free(p);
534         }
535         node->flags &= ~EXFAT_ATTRIB_CACHED;
536         if (node->references != 0)
537         {
538                 char buffer[UTF8_BYTES(EXFAT_NAME_MAX) + 1];
539                 exfat_get_name(node, buffer, sizeof(buffer) - 1);
540                 exfat_warn("non-zero reference counter (%d) for `%s'",
541                                 node->references, buffer);
542         }
543         while (node->references)
544                 exfat_put_node(ef, node);
545 }
546
547 void exfat_reset_cache(struct exfat* ef)
548 {
549         reset_cache(ef, ef->root);
550 }
551
552 static bool next_entry(struct exfat* ef, const struct exfat_node* parent,
553                 cluster_t* cluster, off_t* offset)
554 {
555         *offset += sizeof(struct exfat_entry);
556         if (*offset % CLUSTER_SIZE(*ef->sb) == 0)
557         {
558                 *cluster = exfat_next_cluster(ef, parent, *cluster);
559                 if (CLUSTER_INVALID(*cluster))
560                 {
561                         exfat_error("invalid cluster %#x while getting next entry",
562                                         *cluster);
563                         return false;
564                 }
565         }
566         return true;
567 }
568
569 int exfat_flush_node(struct exfat* ef, struct exfat_node* node)
570 {
571         cluster_t cluster;
572         off_t offset;
573         off_t meta1_offset, meta2_offset;
574         struct exfat_entry_meta1 meta1;
575         struct exfat_entry_meta2 meta2;
576
577         if (!(node->flags & EXFAT_ATTRIB_DIRTY))
578                 return 0; /* no need to flush */
579
580         if (ef->ro)
581                 exfat_bug("unable to flush node to read-only FS");
582
583         if (node->parent == NULL)
584                 return 0; /* do not flush unlinked node */
585
586         cluster = node->entry_cluster;
587         offset = node->entry_offset;
588         meta1_offset = co2o(ef, cluster, offset);
589         if (!next_entry(ef, node->parent, &cluster, &offset))
590                 return -EIO;
591         meta2_offset = co2o(ef, cluster, offset);
592
593         if (exfat_pread(ef->dev, &meta1, sizeof(meta1), meta1_offset) < 0)
594         {
595                 exfat_error("failed to read meta1 entry on flush");
596                 return -EIO;
597         }
598         if (meta1.type != EXFAT_ENTRY_FILE)
599                 exfat_bug("invalid type of meta1: 0x%hhx", meta1.type);
600         meta1.attrib = cpu_to_le16(node->flags);
601         exfat_unix2exfat(node->mtime, &meta1.mdate, &meta1.mtime, &meta1.mtime_cs);
602         exfat_unix2exfat(node->atime, &meta1.adate, &meta1.atime, NULL);
603
604         if (exfat_pread(ef->dev, &meta2, sizeof(meta2), meta2_offset) < 0)
605         {
606                 exfat_error("failed to read meta2 entry on flush");
607                 return -EIO;
608         }
609         if (meta2.type != EXFAT_ENTRY_FILE_INFO)
610                 exfat_bug("invalid type of meta2: 0x%hhx", meta2.type);
611         meta2.size = meta2.real_size = cpu_to_le64(node->size);
612         meta2.start_cluster = cpu_to_le32(node->start_cluster);
613         meta2.flags = EXFAT_FLAG_ALWAYS1;
614         /* empty files must not be marked as contiguous */
615         if (node->size != 0 && IS_CONTIGUOUS(*node))
616                 meta2.flags |= EXFAT_FLAG_CONTIGUOUS;
617         /* name hash remains unchanged, no need to recalculate it */
618
619         meta1.checksum = exfat_calc_checksum(&meta1, &meta2, node->name);
620
621         if (exfat_pwrite(ef->dev, &meta1, sizeof(meta1), meta1_offset) < 0)
622         {
623                 exfat_error("failed to write meta1 entry on flush");
624                 return -EIO;
625         }
626         if (exfat_pwrite(ef->dev, &meta2, sizeof(meta2), meta2_offset) < 0)
627         {
628                 exfat_error("failed to write meta2 entry on flush");
629                 return -EIO;
630         }
631
632         node->flags &= ~EXFAT_ATTRIB_DIRTY;
633         return 0;
634 }
635
636 static bool erase_entry(struct exfat* ef, struct exfat_node* node)
637 {
638         cluster_t cluster = node->entry_cluster;
639         off_t offset = node->entry_offset;
640         int name_entries = DIV_ROUND_UP(utf16_length(node->name), EXFAT_ENAME_MAX);
641         uint8_t entry_type;
642
643         entry_type = EXFAT_ENTRY_FILE & ~EXFAT_ENTRY_VALID;
644         if (exfat_pwrite(ef->dev, &entry_type, 1, co2o(ef, cluster, offset)) < 0)
645         {
646                 exfat_error("failed to erase meta1 entry");
647                 return false;
648         }
649
650         if (!next_entry(ef, node->parent, &cluster, &offset))
651                 return false;
652         entry_type = EXFAT_ENTRY_FILE_INFO & ~EXFAT_ENTRY_VALID;
653         if (exfat_pwrite(ef->dev, &entry_type, 1, co2o(ef, cluster, offset)) < 0)
654         {
655                 exfat_error("failed to erase meta2 entry");
656                 return false;
657         }
658
659         while (name_entries--)
660         {
661                 if (!next_entry(ef, node->parent, &cluster, &offset))
662                         return false;
663                 entry_type = EXFAT_ENTRY_FILE_NAME & ~EXFAT_ENTRY_VALID;
664                 if (exfat_pwrite(ef->dev, &entry_type, 1,
665                                 co2o(ef, cluster, offset)) < 0)
666                 {
667                         exfat_error("failed to erase name entry");
668                         return false;
669                 }
670         }
671         return true;
672 }
673
674 static int shrink_directory(struct exfat* ef, struct exfat_node* dir,
675                 off_t deleted_offset)
676 {
677         const struct exfat_node* node;
678         const struct exfat_node* last_node;
679         uint64_t entries = 0;
680         uint64_t new_size;
681
682         if (!(dir->flags & EXFAT_ATTRIB_DIR))
683                 exfat_bug("attempted to shrink a file");
684         if (!(dir->flags & EXFAT_ATTRIB_CACHED))
685                 exfat_bug("attempted to shrink uncached directory");
686
687         for (last_node = node = dir->child; node; node = node->next)
688         {
689                 if (deleted_offset < node->entry_offset)
690                 {
691                         /* there are other entries after the removed one, no way to shrink
692                            this directory */
693                         return 0;
694                 }
695                 if (last_node->entry_offset < node->entry_offset)
696                         last_node = node;
697         }
698
699         if (last_node)
700         {
701                 /* offset of the last entry */
702                 entries += last_node->entry_offset / sizeof(struct exfat_entry);
703                 /* two subentries with meta info */
704                 entries += 2;
705                 /* subentries with file name */
706                 entries += DIV_ROUND_UP(utf16_length(last_node->name),
707                                 EXFAT_ENAME_MAX);
708         }
709
710         new_size = DIV_ROUND_UP(entries * sizeof(struct exfat_entry),
711                                  CLUSTER_SIZE(*ef->sb)) * CLUSTER_SIZE(*ef->sb);
712         if (new_size == 0) /* directory always has at least 1 cluster */
713                 new_size = CLUSTER_SIZE(*ef->sb);
714         if (new_size == dir->size)
715                 return 0;
716         return exfat_truncate(ef, dir, new_size, true);
717 }
718
719 static int delete(struct exfat* ef, struct exfat_node* node)
720 {
721         struct exfat_node* parent = node->parent;
722         off_t deleted_offset = node->entry_offset;
723         int rc;
724
725         exfat_get_node(parent);
726         if (!erase_entry(ef, node))
727         {
728                 exfat_put_node(ef, parent);
729                 return -EIO;
730         }
731         exfat_update_mtime(parent);
732         tree_detach(node);
733         rc = shrink_directory(ef, parent, deleted_offset);
734         exfat_put_node(ef, parent);
735         /* file clusters will be freed when node reference counter becomes 0 */
736         node->flags |= EXFAT_ATTRIB_UNLINKED;
737         return rc;
738 }
739
740 int exfat_unlink(struct exfat* ef, struct exfat_node* node)
741 {
742         if (node->flags & EXFAT_ATTRIB_DIR)
743                 return -EISDIR;
744         return delete(ef, node);
745 }
746
747 int exfat_rmdir(struct exfat* ef, struct exfat_node* node)
748 {
749         if (!(node->flags & EXFAT_ATTRIB_DIR))
750                 return -ENOTDIR;
751         /* check that directory is empty */
752         exfat_cache_directory(ef, node);
753         if (node->child)
754                 return -ENOTEMPTY;
755         return delete(ef, node);
756 }
757
758 static int grow_directory(struct exfat* ef, struct exfat_node* dir,
759                 uint64_t asize, uint32_t difference)
760 {
761         return exfat_truncate(ef, dir,
762                         DIV_ROUND_UP(asize + difference, CLUSTER_SIZE(*ef->sb))
763                                 * CLUSTER_SIZE(*ef->sb), true);
764 }
765
766 static int find_slot(struct exfat* ef, struct exfat_node* dir,
767                 cluster_t* cluster, off_t* offset, int subentries)
768 {
769         struct iterator it;
770         int rc;
771         const struct exfat_entry* entry;
772         int contiguous = 0;
773
774         rc = opendir(ef, dir, &it);
775         if (rc != 0)
776                 return rc;
777         for (;;)
778         {
779                 if (contiguous == 0)
780                 {
781                         *cluster = it.cluster;
782                         *offset = it.offset;
783                 }
784                 entry = get_entry_ptr(ef, &it);
785                 if (entry->type & EXFAT_ENTRY_VALID)
786                         contiguous = 0;
787                 else
788                         contiguous++;
789                 if (contiguous == subentries)
790                         break;  /* suitable slot is found */
791                 if (it.offset + sizeof(struct exfat_entry) >= dir->size)
792                 {
793                         rc = grow_directory(ef, dir, dir->size,
794                                         (subentries - contiguous) * sizeof(struct exfat_entry));
795                         if (rc != 0)
796                         {
797                                 closedir(&it);
798                                 return rc;
799                         }
800                 }
801                 if (fetch_next_entry(ef, dir, &it) != 0)
802                 {
803                         closedir(&it);
804                         return -EIO;
805                 }
806         }
807         closedir(&it);
808         return 0;
809 }
810
811 static int write_entry(struct exfat* ef, struct exfat_node* dir,
812                 const le16_t* name, cluster_t cluster, off_t offset, uint16_t attrib)
813 {
814         struct exfat_node* node;
815         struct exfat_entry_meta1 meta1;
816         struct exfat_entry_meta2 meta2;
817         const size_t name_length = utf16_length(name);
818         const int name_entries = DIV_ROUND_UP(name_length, EXFAT_ENAME_MAX);
819         int i;
820
821         node = allocate_node();
822         if (node == NULL)
823                 return -ENOMEM;
824         node->entry_cluster = cluster;
825         node->entry_offset = offset;
826         memcpy(node->name, name, name_length * sizeof(le16_t));
827
828         memset(&meta1, 0, sizeof(meta1));
829         meta1.type = EXFAT_ENTRY_FILE;
830         meta1.continuations = 1 + name_entries;
831         meta1.attrib = cpu_to_le16(attrib);
832         exfat_unix2exfat(time(NULL), &meta1.crdate, &meta1.crtime,
833                         &meta1.crtime_cs);
834         meta1.adate = meta1.mdate = meta1.crdate;
835         meta1.atime = meta1.mtime = meta1.crtime;
836         meta1.mtime_cs = meta1.crtime_cs; /* there is no atime_cs */
837
838         memset(&meta2, 0, sizeof(meta2));
839         meta2.type = EXFAT_ENTRY_FILE_INFO;
840         meta2.flags = EXFAT_FLAG_ALWAYS1;
841         meta2.name_length = name_length;
842         meta2.name_hash = exfat_calc_name_hash(ef, node->name);
843         meta2.start_cluster = cpu_to_le32(EXFAT_CLUSTER_FREE);
844
845         meta1.checksum = exfat_calc_checksum(&meta1, &meta2, node->name);
846
847         if (exfat_pwrite(ef->dev, &meta1, sizeof(meta1),
848                         co2o(ef, cluster, offset)) < 0)
849         {
850                 exfat_error("failed to write meta1 entry");
851                 return -EIO;
852         }
853         if (!next_entry(ef, dir, &cluster, &offset))
854                 return -EIO;
855         if (exfat_pwrite(ef->dev, &meta2, sizeof(meta2),
856                         co2o(ef, cluster, offset)) < 0)
857         {
858                 exfat_error("failed to write meta2 entry");
859                 return -EIO;
860         }
861         for (i = 0; i < name_entries; i++)
862         {
863                 struct exfat_entry_name name_entry = {EXFAT_ENTRY_FILE_NAME, 0};
864                 memcpy(name_entry.name, node->name + i * EXFAT_ENAME_MAX,
865                                 MIN(EXFAT_ENAME_MAX, EXFAT_NAME_MAX - i * EXFAT_ENAME_MAX) *
866                                 sizeof(le16_t));
867                 if (!next_entry(ef, dir, &cluster, &offset))
868                         return -EIO;
869                 if (exfat_pwrite(ef->dev, &name_entry, sizeof(name_entry),
870                                 co2o(ef, cluster, offset)) < 0)
871                 {
872                         exfat_error("failed to write name entry");
873                         return -EIO;
874                 }
875         }
876
877         init_node_meta1(node, &meta1);
878         init_node_meta2(node, &meta2);
879
880         tree_attach(dir, node);
881         exfat_update_mtime(dir);
882         return 0;
883 }
884
885 static int create(struct exfat* ef, const char* path, uint16_t attrib)
886 {
887         struct exfat_node* dir;
888         struct exfat_node* existing;
889         cluster_t cluster = EXFAT_CLUSTER_BAD;
890         off_t offset = -1;
891         le16_t name[EXFAT_NAME_MAX + 1];
892         int rc;
893
894         rc = exfat_split(ef, &dir, &existing, name, path);
895         if (rc != 0)
896                 return rc;
897         if (existing != NULL)
898         {
899                 exfat_put_node(ef, existing);
900                 exfat_put_node(ef, dir);
901                 return -EEXIST;
902         }
903
904         rc = find_slot(ef, dir, &cluster, &offset,
905                         2 + DIV_ROUND_UP(utf16_length(name), EXFAT_ENAME_MAX));
906         if (rc != 0)
907         {
908                 exfat_put_node(ef, dir);
909                 return rc;
910         }
911         rc = write_entry(ef, dir, name, cluster, offset, attrib);
912         exfat_put_node(ef, dir);
913         return rc;
914 }
915
916 int exfat_mknod(struct exfat* ef, const char* path)
917 {
918         return create(ef, path, EXFAT_ATTRIB_ARCH);
919 }
920
921 int exfat_mkdir(struct exfat* ef, const char* path)
922 {
923         int rc;
924         struct exfat_node* node;
925
926         rc = create(ef, path, EXFAT_ATTRIB_ARCH | EXFAT_ATTRIB_DIR);
927         if (rc != 0)
928                 return rc;
929         rc = exfat_lookup(ef, &node, path);
930         if (rc != 0)
931                 return 0;
932         /* directories always have at least one cluster */
933         rc = exfat_truncate(ef, node, CLUSTER_SIZE(*ef->sb), true);
934         if (rc != 0)
935         {
936                 delete(ef, node);
937                 exfat_put_node(ef, node);
938                 return rc;
939         }
940         exfat_put_node(ef, node);
941         return 0;
942 }
943
944 static int rename_entry(struct exfat* ef, struct exfat_node* dir,
945                 struct exfat_node* node, const le16_t* name, cluster_t new_cluster,
946                 off_t new_offset)
947 {
948         struct exfat_entry_meta1 meta1;
949         struct exfat_entry_meta2 meta2;
950         cluster_t old_cluster = node->entry_cluster;
951         off_t old_offset = node->entry_offset;
952         const size_t name_length = utf16_length(name);
953         const int name_entries = DIV_ROUND_UP(name_length, EXFAT_ENAME_MAX);
954         int i;
955
956         if (exfat_pread(ef->dev, &meta1, sizeof(meta1),
957                         co2o(ef, old_cluster, old_offset)) < 0)
958         {
959                 exfat_error("failed to read meta1 entry on rename");
960                 return -EIO;
961         }
962         if (!next_entry(ef, node->parent, &old_cluster, &old_offset))
963                 return -EIO;
964         if (exfat_pread(ef->dev, &meta2, sizeof(meta2),
965                         co2o(ef, old_cluster, old_offset)) < 0)
966         {
967                 exfat_error("failed to read meta2 entry on rename");
968                 return -EIO;
969         }
970         meta1.continuations = 1 + name_entries;
971         meta2.name_hash = exfat_calc_name_hash(ef, name);
972         meta2.name_length = name_length;
973         meta1.checksum = exfat_calc_checksum(&meta1, &meta2, name);
974
975         if (!erase_entry(ef, node))
976                 return -EIO;
977
978         node->entry_cluster = new_cluster;
979         node->entry_offset = new_offset;
980
981         if (exfat_pwrite(ef->dev, &meta1, sizeof(meta1),
982                         co2o(ef, new_cluster, new_offset)) < 0)
983         {
984                 exfat_error("failed to write meta1 entry on rename");
985                 return -EIO;
986         }
987         if (!next_entry(ef, dir, &new_cluster, &new_offset))
988                 return -EIO;
989         if (exfat_pwrite(ef->dev, &meta2, sizeof(meta2),
990                         co2o(ef, new_cluster, new_offset)) < 0)
991         {
992                 exfat_error("failed to write meta2 entry on rename");
993                 return -EIO;
994         }
995
996         for (i = 0; i < name_entries; i++)
997         {
998                 struct exfat_entry_name name_entry = {EXFAT_ENTRY_FILE_NAME, 0};
999                 memcpy(name_entry.name, name + i * EXFAT_ENAME_MAX,
1000                                 EXFAT_ENAME_MAX * sizeof(le16_t));
1001                 if (!next_entry(ef, dir, &new_cluster, &new_offset))
1002                         return -EIO;
1003                 if (exfat_pwrite(ef->dev, &name_entry, sizeof(name_entry),
1004                                 co2o(ef, new_cluster, new_offset)) < 0)
1005                 {
1006                         exfat_error("failed to write name entry on rename");
1007                         return -EIO;
1008                 }
1009         }
1010
1011         memcpy(node->name, name, (EXFAT_NAME_MAX + 1) * sizeof(le16_t));
1012         tree_detach(node);
1013         tree_attach(dir, node);
1014         return 0;
1015 }
1016
1017 int exfat_rename(struct exfat* ef, const char* old_path, const char* new_path)
1018 {
1019         struct exfat_node* node;
1020         struct exfat_node* existing;
1021         struct exfat_node* dir;
1022         cluster_t cluster = EXFAT_CLUSTER_BAD;
1023         off_t offset = -1;
1024         le16_t name[EXFAT_NAME_MAX + 1];
1025         int rc;
1026
1027         rc = exfat_lookup(ef, &node, old_path);
1028         if (rc != 0)
1029                 return rc;
1030
1031         rc = exfat_split(ef, &dir, &existing, name, new_path);
1032         if (rc != 0)
1033         {
1034                 exfat_put_node(ef, node);
1035                 return rc;
1036         }
1037
1038         /* check that target is not a subdirectory of the source */
1039         if (node->flags & EXFAT_ATTRIB_DIR)
1040         {
1041                 struct exfat_node* p;
1042
1043                 for (p = dir; p; p = p->parent)
1044                         if (node == p)
1045                         {
1046                                 if (existing != NULL)
1047                                         exfat_put_node(ef, existing);
1048                                 exfat_put_node(ef, dir);
1049                                 exfat_put_node(ef, node);
1050                                 return -EINVAL;
1051                         }
1052         }
1053
1054         if (existing != NULL)
1055         {
1056                 /* remove target if it's not the same node as source */
1057                 if (existing != node)
1058                 {
1059                         if (existing->flags & EXFAT_ATTRIB_DIR)
1060                         {
1061                                 if (node->flags & EXFAT_ATTRIB_DIR)
1062                                         rc = exfat_rmdir(ef, existing);
1063                                 else
1064                                         rc = -ENOTDIR;
1065                         }
1066                         else
1067                         {
1068                                 if (!(node->flags & EXFAT_ATTRIB_DIR))
1069                                         rc = exfat_unlink(ef, existing);
1070                                 else
1071                                         rc = -EISDIR;
1072                         }
1073                         exfat_put_node(ef, existing);
1074                         if (rc != 0)
1075                         {
1076                                 exfat_put_node(ef, dir);
1077                                 exfat_put_node(ef, node);
1078                                 return rc;
1079                         }
1080                 }
1081                 else
1082                         exfat_put_node(ef, existing);
1083         }
1084
1085         rc = find_slot(ef, dir, &cluster, &offset,
1086                         2 + DIV_ROUND_UP(utf16_length(name), EXFAT_ENAME_MAX));
1087         if (rc != 0)
1088         {
1089                 exfat_put_node(ef, dir);
1090                 exfat_put_node(ef, node);
1091                 return rc;
1092         }
1093         rc = rename_entry(ef, dir, node, name, cluster, offset);
1094         exfat_put_node(ef, dir);
1095         exfat_put_node(ef, node);
1096         return 0;
1097 }
1098
1099 void exfat_utimes(struct exfat_node* node, const struct timespec tv[2])
1100 {
1101         node->atime = tv[0].tv_sec;
1102         node->mtime = tv[1].tv_sec;
1103         node->flags |= EXFAT_ATTRIB_DIRTY;
1104 }
1105
1106 void exfat_update_atime(struct exfat_node* node)
1107 {
1108         node->atime = time(NULL);
1109         node->flags |= EXFAT_ATTRIB_DIRTY;
1110 }
1111
1112 void exfat_update_mtime(struct exfat_node* node)
1113 {
1114         node->mtime = time(NULL);
1115         node->flags |= EXFAT_ATTRIB_DIRTY;
1116 }
1117
1118 const char* exfat_get_label(struct exfat* ef)
1119 {
1120         return ef->label;
1121 }
1122
1123 static int find_label(struct exfat* ef, cluster_t* cluster, off_t* offset)
1124 {
1125         struct iterator it;
1126         int rc;
1127
1128         rc = opendir(ef, ef->root, &it);
1129         if (rc != 0)
1130                 return rc;
1131
1132         for (;;)
1133         {
1134                 if (it.offset >= ef->root->size)
1135                 {
1136                         closedir(&it);
1137                         return -ENOENT;
1138                 }
1139
1140                 if (get_entry_ptr(ef, &it)->type == EXFAT_ENTRY_LABEL)
1141                 {
1142                         *cluster = it.cluster;
1143                         *offset = it.offset;
1144                         closedir(&it);
1145                         return 0;
1146                 }
1147
1148                 if (fetch_next_entry(ef, ef->root, &it) != 0)
1149                 {
1150                         closedir(&it);
1151                         return -EIO;
1152                 }
1153         }
1154 }
1155
1156 int exfat_set_label(struct exfat* ef, const char* label)
1157 {
1158         le16_t label_utf16[EXFAT_ENAME_MAX + 1];
1159         int rc;
1160         cluster_t cluster;
1161         off_t offset;
1162         struct exfat_entry_label entry;
1163
1164         memset(label_utf16, 0, sizeof(label_utf16));
1165         rc = utf8_to_utf16(label_utf16, label, EXFAT_ENAME_MAX, strlen(label));
1166         if (rc != 0)
1167                 return rc;
1168
1169         rc = find_label(ef, &cluster, &offset);
1170         if (rc == -ENOENT)
1171                 rc = find_slot(ef, ef->root, &cluster, &offset, 1);
1172         if (rc != 0)
1173                 return rc;
1174
1175         entry.type = EXFAT_ENTRY_LABEL;
1176         entry.length = utf16_length(label_utf16);
1177         memcpy(entry.name, label_utf16, sizeof(entry.name));
1178         if (entry.length == 0)
1179                 entry.type ^= EXFAT_ENTRY_VALID;
1180
1181         if (exfat_pwrite(ef->dev, &entry, sizeof(struct exfat_entry_label),
1182                         co2o(ef, cluster, offset)) < 0)
1183         {
1184                 exfat_error("failed to write label entry");
1185                 return -EIO;
1186         }
1187         strcpy(ef->label, label);
1188         return 0;
1189 }