2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (C) 1995, 1996, 1997 Wolfgang Solfrank
5 * Copyright (c) 1995 Martin Husemann
6 * Some structure declaration borrowed from Paul Popelka
7 * (paulp@uts.amdahl.com), see /sys/msdosfs/ for reference.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #include <sys/cdefs.h>
33 __RCSID("$NetBSD: dir.c,v 1.20 2006/06/05 16:51:18 christos Exp $");
34 static const char rcsid[] =
46 #include <sys/param.h>
51 #define SLOT_EMPTY 0x00 /* slot has never been used */
52 #define SLOT_E5 0x05 /* the real value is 0xe5 */
53 #define SLOT_DELETED 0xe5 /* file in this slot deleted */
55 #define ATTR_NORMAL 0x00 /* normal file */
56 #define ATTR_READONLY 0x01 /* file is readonly */
57 #define ATTR_HIDDEN 0x02 /* file is hidden */
58 #define ATTR_SYSTEM 0x04 /* file is a system file */
59 #define ATTR_VOLUME 0x08 /* entry is a volume label */
60 #define ATTR_DIRECTORY 0x10 /* entry is a directory name */
61 #define ATTR_ARCHIVE 0x20 /* file is new or modified */
63 #define ATTR_WIN95 0x0f /* long name record */
66 * This is the format of the contents of the deTime field in the direntry
68 * We don't use bitfields because we don't know how compilers for
69 * arbitrary machines will lay them out.
71 #define DT_2SECONDS_MASK 0x1F /* seconds divided by 2 */
72 #define DT_2SECONDS_SHIFT 0
73 #define DT_MINUTES_MASK 0x7E0 /* minutes */
74 #define DT_MINUTES_SHIFT 5
75 #define DT_HOURS_MASK 0xF800 /* hours */
76 #define DT_HOURS_SHIFT 11
79 * This is the format of the contents of the deDate field in the direntry
82 #define DD_DAY_MASK 0x1F /* day of month */
83 #define DD_DAY_SHIFT 0
84 #define DD_MONTH_MASK 0x1E0 /* month */
85 #define DD_MONTH_SHIFT 5
86 #define DD_YEAR_MASK 0xFE00 /* year - 1980 */
87 #define DD_YEAR_SHIFT 9
91 static struct dosDirEntry *newDosDirEntry(void);
92 static void freeDosDirEntry(struct dosDirEntry *);
93 static struct dirTodoNode *newDirTodo(void);
94 static void freeDirTodo(struct dirTodoNode *);
95 static char *fullpath(struct dosDirEntry *);
96 static u_char calcShortSum(u_char *);
97 static int delete(int, struct bootblock *, struct fatEntry *, cl_t, int,
99 static int removede(int, struct bootblock *, struct fatEntry *, u_char *,
100 u_char *, cl_t, cl_t, cl_t, char *, int);
101 static int checksize(struct bootblock *, struct fatEntry *, u_char *,
102 struct dosDirEntry *);
103 static int readDosDirSection(int, struct bootblock *, struct fatEntry *,
104 struct dosDirEntry *);
107 * Manage free dosDirEntry structures.
109 static struct dosDirEntry *freede;
111 static struct dosDirEntry *
114 struct dosDirEntry *de;
116 if (!(de = freede)) {
117 if (!(de = (struct dosDirEntry *)malloc(sizeof *de)))
125 freeDosDirEntry(struct dosDirEntry *de)
132 * The same for dirTodoNode structures.
134 static struct dirTodoNode *freedt;
136 static struct dirTodoNode *
139 struct dirTodoNode *dt;
141 if (!(dt = freedt)) {
142 if (!(dt = (struct dirTodoNode *)malloc(sizeof *dt)))
150 freeDirTodo(struct dirTodoNode *dt)
157 * The stack of unread directories
159 static struct dirTodoNode *pendingDirectories = NULL;
162 * Return the full pathname for a directory entry.
165 fullpath(struct dosDirEntry *dir)
167 static char namebuf[MAXPATHLEN + 1];
171 cp = namebuf + sizeof namebuf;
175 np = dir->lname[0] ? dir->lname : dir->name;
177 if (cp <= namebuf + 1 + nl) {
193 * Calculate a checksum over an 8.3 alias name
196 calcShortSum(u_char *p)
201 for (i = 0; i < 11; i++) {
202 sum = (sum << 7)|(sum >> 1); /* rotate right */
210 * Global variables temporarily used during a directory scan
212 static char longName[DOSLONGNAMELEN] = "";
213 static u_char *buffer = NULL;
214 static u_char *delbuf = NULL;
216 static struct dosDirEntry *rootDir;
217 static struct dosDirEntry *lostDir;
220 * Init internal state for a new directory scan.
223 resetDosDirSection(struct bootblock *boot, struct fatEntry *fat)
229 b1 = boot->bpbRootDirEnts * 32;
230 b2 = boot->bpbSecPerClust * boot->bpbBytesPerSec;
232 if ((buffer = malloc(len = MAX(b1, b2))) == NULL) {
233 perr("No space for directory buffer (%zu)", len);
237 if ((delbuf = malloc(len = b2)) == NULL) {
239 perr("No space for directory delbuf (%zu)", len);
243 if ((rootDir = newDosDirEntry()) == NULL) {
246 perr("No space for directory entry");
250 memset(rootDir, 0, sizeof *rootDir);
251 if (boot->flags & FAT32) {
252 if (boot->bpbRootClust < CLUST_FIRST ||
253 boot->bpbRootClust >= boot->NumClusters) {
254 pfatal("Root directory starts with cluster out of range(%u)",
258 if (fat[boot->bpbRootClust].head != boot->bpbRootClust) {
259 pfatal("Root directory doesn't start a cluster chain");
263 fat[boot->bpbRootClust].flags |= FAT_USED;
264 rootDir->head = boot->bpbRootClust;
271 * Cleanup after a directory scan
274 finishDosDirSection(void)
276 struct dirTodoNode *p, *np;
277 struct dosDirEntry *d, *nd;
279 for (p = pendingDirectories; p; p = np) {
283 pendingDirectories = NULL;
284 for (d = rootDir; d; d = nd) {
285 if ((nd = d->child) != NULL) {
293 rootDir = lostDir = NULL;
301 * Delete directory entries between startcl, startoff and endcl, endoff.
304 delete(int f, struct bootblock *boot, struct fatEntry *fat, cl_t startcl,
305 int startoff, cl_t endcl, int endoff, int notlast)
309 int clsz = boot->bpbSecPerClust * boot->bpbBytesPerSec;
311 s = delbuf + startoff;
313 while (startcl >= CLUST_FIRST && startcl < boot->NumClusters) {
314 if (startcl == endcl) {
319 off = startcl * boot->bpbSecPerClust + boot->ClusterOffset;
320 off *= boot->bpbBytesPerSec;
321 if (lseek(f, off, SEEK_SET) != off) {
322 perr("Unable to lseek to %" PRId64, off);
325 if (read(f, delbuf, clsz) != clsz) {
326 perr("Unable to read directory");
333 if (lseek(f, off, SEEK_SET) != off) {
334 perr("Unable to lseek to %" PRId64, off);
337 if (write(f, delbuf, clsz) != clsz) {
338 perr("Unable to write directory");
341 if (startcl == endcl)
343 startcl = fat[startcl].next;
350 removede(int f, struct bootblock *boot, struct fatEntry *fat, u_char *start,
351 u_char *end, cl_t startcl, cl_t endcl, cl_t curcl, char *path, int type)
355 pwarn("Invalid long filename entry for %s\n", path);
358 pwarn("Invalid long filename entry at end of directory %s\n",
362 pwarn("Invalid long filename entry for volume label\n");
365 if (ask(0, "Remove")) {
366 if (startcl != curcl) {
367 if (delete(f, boot, fat,
368 startcl, start - buffer,
370 endcl == curcl) == FSFATAL)
374 /* startcl is < CLUST_FIRST for !fat32 root */
375 if ((endcl == curcl) || (startcl < CLUST_FIRST))
376 for (; start < end; start += 32)
377 *start = SLOT_DELETED;
384 * Check an in-memory file entry
387 checksize(struct bootblock *boot, struct fatEntry *fat, u_char *p,
388 struct dosDirEntry *dir)
391 * Check size on ordinary files
393 u_int32_t physicalSize;
395 if (dir->head == CLUST_FREE)
398 if (dir->head < CLUST_FIRST || dir->head >= boot->NumClusters)
400 physicalSize = fat[dir->head].length * boot->ClusterSize;
402 if (physicalSize < dir->size) {
403 pwarn("size of %s is %u, should at most be %u\n",
404 fullpath(dir), dir->size, physicalSize);
405 if (ask(1, "Truncate")) {
406 dir->size = physicalSize;
407 p[28] = (u_char)physicalSize;
408 p[29] = (u_char)(physicalSize >> 8);
409 p[30] = (u_char)(physicalSize >> 16);
410 p[31] = (u_char)(physicalSize >> 24);
414 } else if (physicalSize - dir->size >= boot->ClusterSize) {
415 pwarn("%s has too many clusters allocated\n",
417 if (ask(1, "Drop superfluous clusters")) {
421 for (cl = dir->head, len = sz = 0;
422 (sz += boot->ClusterSize) < dir->size; len++)
424 clearchain(boot, fat, fat[cl].next);
425 fat[cl].next = CLUST_EOF;
426 fat[dir->head].length = len;
435 * Read a directory and
436 * - resolve long name records
437 * - enter file and directory records into the parent's list
438 * - push directories onto the todo-stack
441 readDosDirSection(int f, struct bootblock *boot, struct fatEntry *fat,
442 struct dosDirEntry *dir)
444 struct dosDirEntry dirent, *d;
445 u_char *p, *vallfn, *invlfn, *empty;
448 cl_t cl, valcl = ~0, invcl = ~0, empcl = ~0;
453 #define THISMOD 0x8000 /* Only used within this routine */
456 if (dir->parent && (cl < CLUST_FIRST || cl >= boot->NumClusters)) {
458 * Already handled somewhere else.
463 vallfn = invlfn = empty = NULL;
465 if (!(boot->flags & FAT32) && !dir->parent) {
466 last = boot->bpbRootDirEnts * 32;
467 off = boot->bpbResSectors + boot->bpbFATs *
470 last = boot->bpbSecPerClust * boot->bpbBytesPerSec;
471 off = cl * boot->bpbSecPerClust + boot->ClusterOffset;
474 off *= boot->bpbBytesPerSec;
475 if (lseek(f, off, SEEK_SET) != off
476 || read(f, buffer, last) != last) {
477 perr("Unable to read directory");
482 * Check `.' and `..' entries here? XXX
484 for (p = buffer, i = 0; i < last; i++, p += 32) {
485 if (dir->fsckflags & DIREMPWARN) {
490 if (*p == SLOT_EMPTY || *p == SLOT_DELETED) {
491 if (*p == SLOT_EMPTY) {
492 dir->fsckflags |= DIREMPTY;
499 if (dir->fsckflags & DIREMPTY) {
500 if (!(dir->fsckflags & DIREMPWARN)) {
501 pwarn("%s has entries after end of directory\n",
503 if (ask(1, "Extend")) {
506 dir->fsckflags &= ~DIREMPTY;
507 if (delete(f, boot, fat,
508 empcl, empty - buffer,
509 cl, p - buffer, 1) == FSFATAL)
511 q = empcl == cl ? empty : buffer;
512 for (; q < p; q += 32)
514 mod |= THISMOD|FSDIRMOD;
515 } else if (ask(0, "Truncate"))
516 dir->fsckflags |= DIREMPWARN;
518 if (dir->fsckflags & DIREMPWARN) {
520 mod |= THISMOD|FSDIRMOD;
522 } else if (dir->fsckflags & DIREMPTY)
527 if (p[11] == ATTR_WIN95) {
529 if (shortSum != -1) {
535 memset(longName, 0, sizeof longName);
539 } else if (shortSum != p[13]
540 || lidx != (*p & LRNOMASK)) {
551 lidx = *p & LRNOMASK;
552 t = longName + --lidx * 13;
553 for (k = 1; k < 11 && t < longName +
554 sizeof(longName); k += 2) {
555 if (!p[k] && !p[k + 1])
559 * Warn about those unusable chars in msdosfs here? XXX
565 for (k = 14; k < 26 && t < longName + sizeof(longName); k += 2) {
566 if (!p[k] && !p[k + 1])
573 for (k = 28; k < 32 && t < longName + sizeof(longName); k += 2) {
574 if (!p[k] && !p[k + 1])
580 if (t >= longName + sizeof(longName)) {
581 pwarn("long filename too long\n");
588 if (p[26] | (p[27] << 8)) {
589 pwarn("long filename record cluster start != 0\n");
596 continue; /* long records don't carry further
601 * This is a standard msdosfs directory entry.
603 memset(&dirent, 0, sizeof dirent);
606 * it's a short name record, but we need to know
607 * more, so get the flags first.
609 dirent.flags = p[11];
612 * Translate from 850 to ISO here XXX
614 for (j = 0; j < 8; j++)
615 dirent.name[j] = p[j];
616 dirent.name[8] = '\0';
617 for (k = 7; k >= 0 && dirent.name[k] == ' '; k--)
618 dirent.name[k] = '\0';
619 if (k < 0 || dirent.name[k] != '\0')
621 if (dirent.name[0] == SLOT_E5)
622 dirent.name[0] = 0xe5;
624 if (dirent.flags & ATTR_VOLUME) {
625 if (vallfn || invlfn) {
626 mod |= removede(f, boot, fat,
627 invlfn ? invlfn : vallfn, p,
628 invlfn ? invcl : valcl, -1, 0,
637 dirent.name[k++] = '.';
638 for (j = 0; j < 3; j++)
639 dirent.name[k++] = p[j+8];
640 dirent.name[k] = '\0';
641 for (k--; k >= 0 && dirent.name[k] == ' '; k--)
642 dirent.name[k] = '\0';
644 if (vallfn && shortSum != calcShortSum(p)) {
651 dirent.head = p[26] | (p[27] << 8);
652 if (boot->ClustMask == CLUST32_MASK)
653 dirent.head |= (p[20] << 16) | (p[21] << 24);
654 dirent.size = p[28] | (p[29] << 8) | (p[30] << 16) | (p[31] << 24);
656 strlcpy(dirent.lname, longName,
657 sizeof(dirent.lname));
663 dirent.next = dir->child;
666 mod |= k = removede(f, boot, fat,
667 invlfn, vallfn ? vallfn : p,
668 invcl, vallfn ? valcl : cl, cl,
669 fullpath(&dirent), 0);
673 ? (valcl == cl && vallfn != buffer)
679 vallfn = NULL; /* not used any longer */
682 if (dirent.size == 0 && !(dirent.flags & ATTR_DIRECTORY)) {
683 if (dirent.head != 0) {
684 pwarn("%s has clusters, but size 0\n",
686 if (ask(1, "Drop allocated clusters")) {
688 if (boot->ClustMask == CLUST32_MASK)
690 clearchain(boot, fat, dirent.head);
692 mod |= THISMOD|FSDIRMOD|FSFATMOD;
696 } else if (dirent.head == 0
697 && !strcmp(dirent.name, "..")
698 && dir->parent /* XXX */
699 && !dir->parent->parent) {
701 * Do nothing, the parent is the root
703 } else if (dirent.head < CLUST_FIRST
704 || dirent.head >= boot->NumClusters
705 || fat[dirent.head].next == CLUST_FREE
706 || (fat[dirent.head].next >= CLUST_RSRVD
707 && fat[dirent.head].next < CLUST_EOFS)
708 || fat[dirent.head].head != dirent.head) {
709 if (dirent.head == 0)
710 pwarn("%s has no clusters\n",
712 else if (dirent.head < CLUST_FIRST
713 || dirent.head >= boot->NumClusters)
714 pwarn("%s starts with cluster out of range(%u)\n",
717 else if (fat[dirent.head].next == CLUST_FREE)
718 pwarn("%s starts with free cluster\n",
720 else if (fat[dirent.head].next >= CLUST_RSRVD)
721 pwarn("%s starts with cluster marked %s\n",
723 rsrvdcltype(fat[dirent.head].next));
725 pwarn("%s doesn't start a cluster chain\n",
727 if (dirent.flags & ATTR_DIRECTORY) {
728 if (ask(0, "Remove")) {
730 mod |= THISMOD|FSDIRMOD;
735 if (ask(1, "Truncate")) {
736 p[28] = p[29] = p[30] = p[31] = 0;
738 if (boot->ClustMask == CLUST32_MASK)
741 mod |= THISMOD|FSDIRMOD;
747 if (dirent.head >= CLUST_FIRST && dirent.head < boot->NumClusters)
748 fat[dirent.head].flags |= FAT_USED;
750 if (dirent.flags & ATTR_DIRECTORY) {
752 * gather more info for directories
754 struct dirTodoNode *n;
757 pwarn("Directory %s has size != 0\n",
759 if (ask(1, "Correct")) {
760 p[28] = p[29] = p[30] = p[31] = 0;
762 mod |= THISMOD|FSDIRMOD;
767 * handle `.' and `..' specially
769 if (strcmp(dirent.name, ".") == 0) {
770 if (dirent.head != dir->head) {
771 pwarn("`.' entry in %s has incorrect start cluster\n",
773 if (ask(1, "Correct")) {
774 dirent.head = dir->head;
775 p[26] = (u_char)dirent.head;
776 p[27] = (u_char)(dirent.head >> 8);
777 if (boot->ClustMask == CLUST32_MASK) {
778 p[20] = (u_char)(dirent.head >> 16);
779 p[21] = (u_char)(dirent.head >> 24);
781 mod |= THISMOD|FSDIRMOD;
787 if (strcmp(dirent.name, "..") == 0) {
788 if (dir->parent) { /* XXX */
789 if (!dir->parent->parent) {
791 pwarn("`..' entry in %s has non-zero start cluster\n",
793 if (ask(1, "Correct")) {
796 if (boot->ClustMask == CLUST32_MASK)
798 mod |= THISMOD|FSDIRMOD;
802 } else if (dirent.head != dir->parent->head) {
803 pwarn("`..' entry in %s has incorrect start cluster\n",
805 if (ask(1, "Correct")) {
806 dirent.head = dir->parent->head;
807 p[26] = (u_char)dirent.head;
808 p[27] = (u_char)(dirent.head >> 8);
809 if (boot->ClustMask == CLUST32_MASK) {
810 p[20] = (u_char)(dirent.head >> 16);
811 p[21] = (u_char)(dirent.head >> 24);
813 mod |= THISMOD|FSDIRMOD;
821 /* create directory tree node */
822 if (!(d = newDosDirEntry())) {
823 perr("No space for directory");
826 memcpy(d, &dirent, sizeof(struct dosDirEntry));
827 /* link it into the tree */
830 /* Enter this directory into the todo list */
831 if (!(n = newDirTodo())) {
832 perr("No space for todo list");
835 n->next = pendingDirectories;
837 pendingDirectories = n;
839 mod |= k = checksize(boot, fat, p, &dirent);
846 if (!(boot->flags & FAT32) && !dir->parent)
851 if (lseek(f, off, SEEK_SET) != off
852 || write(f, buffer, last) != last) {
853 perr("Unable to write directory");
858 } while ((cl = fat[cl].next) >= CLUST_FIRST && cl < boot->NumClusters);
859 if (invlfn || vallfn)
860 mod |= removede(f, boot, fat,
861 invlfn ? invlfn : vallfn, p,
862 invlfn ? invcl : valcl, -1, 0,
865 /* The root directory of non fat32 filesystems is in a special
866 * area and may have been modified above without being written out.
868 if ((mod & FSDIRMOD) && !(boot->flags & FAT32) && !dir->parent) {
870 if (lseek(f, off, SEEK_SET) != off
871 || write(f, buffer, last) != last) {
872 perr("Unable to write directory");
877 return mod & ~THISMOD;
881 handleDirTree(int dosfs, struct bootblock *boot, struct fatEntry *fat)
885 mod = readDosDirSection(dosfs, boot, fat, rootDir);
890 * process the directory todo list
892 while (pendingDirectories) {
893 struct dosDirEntry *dir = pendingDirectories->dir;
894 struct dirTodoNode *n = pendingDirectories->next;
897 * remove TODO entry now, the list might change during
900 freeDirTodo(pendingDirectories);
901 pendingDirectories = n;
904 * handle subdirectory
906 mod |= readDosDirSection(dosfs, boot, fat, dir);
915 * Try to reconnect a FAT chain into dir
917 static u_char *lfbuf;
922 reconnect(int dosfs, struct bootblock *boot, struct fatEntry *fat, cl_t head)
924 struct dosDirEntry d;
928 if (!ask(1, "Reconnect"))
932 for (lostDir = rootDir->child; lostDir; lostDir = lostDir->next) {
933 if (!strcmp(lostDir->name, LOSTDIR))
936 if (!lostDir) { /* Create LOSTDIR? XXX */
937 pwarn("No %s directory\n", LOSTDIR);
942 lfbuf = malloc(boot->ClusterSize);
944 perr("No space for buffer");
952 for (; p < lfbuf + boot->ClusterSize; p += 32)
954 || *p == SLOT_DELETED)
956 if (p && p < lfbuf + boot->ClusterSize)
958 lfcl = p ? fat[lfcl].next : lostDir->head;
959 if (lfcl < CLUST_FIRST || lfcl >= boot->NumClusters) {
960 /* Extend LOSTDIR? XXX */
961 pwarn("No space in %s\n", LOSTDIR);
964 lfoff = lfcl * boot->ClusterSize
965 + boot->ClusterOffset * boot->bpbBytesPerSec;
966 if (lseek(dosfs, lfoff, SEEK_SET) != lfoff
967 || (size_t)read(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) {
968 perr("could not read LOST.DIR");
975 /* Ensure uniqueness of entry here! XXX */
976 memset(&d, 0, sizeof d);
977 /* worst case -1 = 4294967295, 10 digits */
978 len = snprintf(d.name, sizeof(d.name), "%u", head);
981 d.size = fat[head].length * boot->ClusterSize;
983 memcpy(p, d.name, len);
984 memset(p + len, ' ', 11 - len);
985 memset(p + 11, 0, 32 - 11);
986 p[26] = (u_char)d.head;
987 p[27] = (u_char)(d.head >> 8);
988 if (boot->ClustMask == CLUST32_MASK) {
989 p[20] = (u_char)(d.head >> 16);
990 p[21] = (u_char)(d.head >> 24);
992 p[28] = (u_char)d.size;
993 p[29] = (u_char)(d.size >> 8);
994 p[30] = (u_char)(d.size >> 16);
995 p[31] = (u_char)(d.size >> 24);
996 fat[head].flags |= FAT_USED;
997 if (lseek(dosfs, lfoff, SEEK_SET) != lfoff
998 || (size_t)write(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) {
999 perr("could not write LOST.DIR");