2 * Copyright (C) 1995, 1996, 1997 Wolfgang Solfrank
3 * Copyright (c) 1995 Martin Husemann
4 * Some structure declaration borrowed from Paul Popelka
5 * (paulp@uts.amdahl.com), see /sys/msdosfs/ for reference.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include <sys/cdefs.h>
31 __RCSID("$NetBSD: dir.c,v 1.20 2006/06/05 16:51:18 christos Exp $");
32 static const char rcsid[] =
43 #include <sys/param.h>
48 #define SLOT_EMPTY 0x00 /* slot has never been used */
49 #define SLOT_E5 0x05 /* the real value is 0xe5 */
50 #define SLOT_DELETED 0xe5 /* file in this slot deleted */
52 #define ATTR_NORMAL 0x00 /* normal file */
53 #define ATTR_READONLY 0x01 /* file is readonly */
54 #define ATTR_HIDDEN 0x02 /* file is hidden */
55 #define ATTR_SYSTEM 0x04 /* file is a system file */
56 #define ATTR_VOLUME 0x08 /* entry is a volume label */
57 #define ATTR_DIRECTORY 0x10 /* entry is a directory name */
58 #define ATTR_ARCHIVE 0x20 /* file is new or modified */
60 #define ATTR_WIN95 0x0f /* long name record */
63 * This is the format of the contents of the deTime field in the direntry
65 * We don't use bitfields because we don't know how compilers for
66 * arbitrary machines will lay them out.
68 #define DT_2SECONDS_MASK 0x1F /* seconds divided by 2 */
69 #define DT_2SECONDS_SHIFT 0
70 #define DT_MINUTES_MASK 0x7E0 /* minutes */
71 #define DT_MINUTES_SHIFT 5
72 #define DT_HOURS_MASK 0xF800 /* hours */
73 #define DT_HOURS_SHIFT 11
76 * This is the format of the contents of the deDate field in the direntry
79 #define DD_DAY_MASK 0x1F /* day of month */
80 #define DD_DAY_SHIFT 0
81 #define DD_MONTH_MASK 0x1E0 /* month */
82 #define DD_MONTH_SHIFT 5
83 #define DD_YEAR_MASK 0xFE00 /* year - 1980 */
84 #define DD_YEAR_SHIFT 9
88 static struct dosDirEntry *newDosDirEntry(void);
89 static void freeDosDirEntry(struct dosDirEntry *);
90 static struct dirTodoNode *newDirTodo(void);
91 static void freeDirTodo(struct dirTodoNode *);
92 static char *fullpath(struct dosDirEntry *);
93 static u_char calcShortSum(u_char *);
94 static int delete(int, struct bootblock *, struct fatEntry *, cl_t, int,
96 static int removede(int, struct bootblock *, struct fatEntry *, u_char *,
97 u_char *, cl_t, cl_t, cl_t, char *, int);
98 static int checksize(struct bootblock *, struct fatEntry *, u_char *,
99 struct dosDirEntry *);
100 static int readDosDirSection(int, struct bootblock *, struct fatEntry *,
101 struct dosDirEntry *);
104 * Manage free dosDirEntry structures.
106 static struct dosDirEntry *freede;
108 static struct dosDirEntry *
111 struct dosDirEntry *de;
113 if (!(de = freede)) {
114 if (!(de = (struct dosDirEntry *)malloc(sizeof *de)))
122 freeDosDirEntry(struct dosDirEntry *de)
129 * The same for dirTodoNode structures.
131 static struct dirTodoNode *freedt;
133 static struct dirTodoNode *
136 struct dirTodoNode *dt;
138 if (!(dt = freedt)) {
139 if (!(dt = (struct dirTodoNode *)malloc(sizeof *dt)))
147 freeDirTodo(struct dirTodoNode *dt)
154 * The stack of unread directories
156 static struct dirTodoNode *pendingDirectories = NULL;
159 * Return the full pathname for a directory entry.
162 fullpath(struct dosDirEntry *dir)
164 static char namebuf[MAXPATHLEN + 1];
168 cp = namebuf + sizeof namebuf - 1;
171 np = dir->lname[0] ? dir->lname : dir->name;
173 if ((cp -= nl) <= namebuf + 1)
177 } while ((dir = dir->parent) != NULL);
186 * Calculate a checksum over an 8.3 alias name
189 calcShortSum(u_char *p)
194 for (i = 0; i < 11; i++) {
195 sum = (sum << 7)|(sum >> 1); /* rotate right */
203 * Global variables temporarily used during a directory scan
205 static char longName[DOSLONGNAMELEN] = "";
206 static u_char *buffer = NULL;
207 static u_char *delbuf = NULL;
209 struct dosDirEntry *rootDir;
210 static struct dosDirEntry *lostDir;
213 * Init internal state for a new directory scan.
216 resetDosDirSection(struct bootblock *boot, struct fatEntry *fat)
223 b1 = boot->bpbRootDirEnts * 32;
224 b2 = boot->bpbSecPerClust * boot->bpbBytesPerSec;
226 if ((buffer = malloc(len = b1 > b2 ? b1 : b2)) == NULL) {
227 perr("No space for directory buffer (%zu)", len);
231 if ((delbuf = malloc(len = b2)) == NULL) {
233 perr("No space for directory delbuf (%zu)", len);
237 if ((rootDir = newDosDirEntry()) == NULL) {
240 perr("No space for directory entry");
244 memset(rootDir, 0, sizeof *rootDir);
245 if (boot->flags & FAT32) {
246 if (boot->bpbRootClust < CLUST_FIRST ||
247 boot->bpbRootClust >= boot->NumClusters) {
248 pfatal("Root directory starts with cluster out of range(%u)",
252 cl = fat[boot->bpbRootClust].next;
254 || (cl >= CLUST_RSRVD && cl< CLUST_EOFS)
255 || fat[boot->bpbRootClust].head != boot->bpbRootClust) {
256 if (cl == CLUST_FREE)
257 pwarn("Root directory starts with free cluster\n");
258 else if (cl >= CLUST_RSRVD)
259 pwarn("Root directory starts with cluster marked %s\n",
262 pfatal("Root directory doesn't start a cluster chain");
266 fat[boot->bpbRootClust].next = CLUST_FREE;
272 fat[boot->bpbRootClust].flags |= FAT_USED;
273 rootDir->head = boot->bpbRootClust;
280 * Cleanup after a directory scan
283 finishDosDirSection(void)
285 struct dirTodoNode *p, *np;
286 struct dosDirEntry *d, *nd;
288 for (p = pendingDirectories; p; p = np) {
292 pendingDirectories = 0;
293 for (d = rootDir; d; d = nd) {
294 if ((nd = d->child) != NULL) {
302 rootDir = lostDir = NULL;
310 * Delete directory entries between startcl, startoff and endcl, endoff.
313 delete(int f, struct bootblock *boot, struct fatEntry *fat, cl_t startcl,
314 int startoff, cl_t endcl, int endoff, int notlast)
318 int clsz = boot->bpbSecPerClust * boot->bpbBytesPerSec;
320 s = delbuf + startoff;
322 while (startcl >= CLUST_FIRST && startcl < boot->NumClusters) {
323 if (startcl == endcl) {
328 off = startcl * boot->bpbSecPerClust + boot->ClusterOffset;
329 off *= boot->bpbBytesPerSec;
330 if (lseek(f, off, SEEK_SET) != off
331 || read(f, delbuf, clsz) != clsz) {
332 perr("Unable to read directory");
339 if (lseek(f, off, SEEK_SET) != off
340 || write(f, delbuf, clsz) != clsz) {
341 perr("Unable to write directory");
344 if (startcl == endcl)
346 startcl = fat[startcl].next;
353 removede(int f, struct bootblock *boot, struct fatEntry *fat, u_char *start,
354 u_char *end, cl_t startcl, cl_t endcl, cl_t curcl, char *path, int type)
358 pwarn("Invalid long filename entry for %s\n", path);
361 pwarn("Invalid long filename entry at end of directory %s\n",
365 pwarn("Invalid long filename entry for volume label\n");
368 if (ask(0, "Remove")) {
369 if (startcl != curcl) {
370 if (delete(f, boot, fat,
371 startcl, start - buffer,
373 endcl == curcl) == FSFATAL)
377 /* startcl is < CLUST_FIRST for !fat32 root */
378 if ((endcl == curcl) || (startcl < CLUST_FIRST))
379 for (; start < end; start += 32)
380 *start = SLOT_DELETED;
387 * Check an in-memory file entry
390 checksize(struct bootblock *boot, struct fatEntry *fat, u_char *p,
391 struct dosDirEntry *dir)
394 * Check size on ordinary files
396 u_int32_t physicalSize;
398 if (dir->head == CLUST_FREE)
401 if (dir->head < CLUST_FIRST || dir->head >= boot->NumClusters)
403 physicalSize = fat[dir->head].length * boot->ClusterSize;
405 if (physicalSize < dir->size) {
406 pwarn("size of %s is %u, should at most be %u\n",
407 fullpath(dir), dir->size, physicalSize);
408 if (ask(1, "Truncate")) {
409 dir->size = physicalSize;
410 p[28] = (u_char)physicalSize;
411 p[29] = (u_char)(physicalSize >> 8);
412 p[30] = (u_char)(physicalSize >> 16);
413 p[31] = (u_char)(physicalSize >> 24);
417 } else if (physicalSize - dir->size >= boot->ClusterSize) {
418 pwarn("%s has too many clusters allocated\n",
420 if (ask(1, "Drop superfluous clusters")) {
424 for (cl = dir->head, len = sz = 0;
425 (sz += boot->ClusterSize) < dir->size; len++)
427 clearchain(boot, fat, fat[cl].next);
428 fat[cl].next = CLUST_EOF;
429 fat[dir->head].length = len;
438 * Read a directory and
439 * - resolve long name records
440 * - enter file and directory records into the parent's list
441 * - push directories onto the todo-stack
444 readDosDirSection(int f, struct bootblock *boot, struct fatEntry *fat,
445 struct dosDirEntry *dir)
447 struct dosDirEntry dirent, *d;
448 u_char *p, *vallfn, *invlfn, *empty;
451 cl_t cl, valcl = ~0, invcl = ~0, empcl = ~0;
456 #define THISMOD 0x8000 /* Only used within this routine */
459 if (dir->parent && (cl < CLUST_FIRST || cl >= boot->NumClusters)) {
461 * Already handled somewhere else.
466 vallfn = invlfn = empty = NULL;
468 if (!(boot->flags & FAT32) && !dir->parent) {
469 last = boot->bpbRootDirEnts * 32;
470 off = boot->bpbResSectors + boot->bpbFATs *
473 last = boot->bpbSecPerClust * boot->bpbBytesPerSec;
474 off = cl * boot->bpbSecPerClust + boot->ClusterOffset;
477 off *= boot->bpbBytesPerSec;
478 if (lseek(f, off, SEEK_SET) != off
479 || read(f, buffer, last) != last) {
480 perr("Unable to read directory");
485 * Check `.' and `..' entries here? XXX
487 for (p = buffer, i = 0; i < last; i++, p += 32) {
488 if (dir->fsckflags & DIREMPWARN) {
493 if (*p == SLOT_EMPTY || *p == SLOT_DELETED) {
494 if (*p == SLOT_EMPTY) {
495 dir->fsckflags |= DIREMPTY;
502 if (dir->fsckflags & DIREMPTY) {
503 if (!(dir->fsckflags & DIREMPWARN)) {
504 pwarn("%s has entries after end of directory\n",
506 if (ask(1, "Extend")) {
509 dir->fsckflags &= ~DIREMPTY;
510 if (delete(f, boot, fat,
511 empcl, empty - buffer,
512 cl, p - buffer, 1) == FSFATAL)
514 q = empcl == cl ? empty : buffer;
515 for (; q < p; q += 32)
517 mod |= THISMOD|FSDIRMOD;
518 } else if (ask(0, "Truncate"))
519 dir->fsckflags |= DIREMPWARN;
521 if (dir->fsckflags & DIREMPWARN) {
523 mod |= THISMOD|FSDIRMOD;
525 } else if (dir->fsckflags & DIREMPTY)
530 if (p[11] == ATTR_WIN95) {
532 if (shortSum != -1) {
538 memset(longName, 0, sizeof longName);
542 } else if (shortSum != p[13]
543 || lidx != (*p & LRNOMASK)) {
554 lidx = *p & LRNOMASK;
555 t = longName + --lidx * 13;
556 for (k = 1; k < 11 && t < longName +
557 sizeof(longName); k += 2) {
558 if (!p[k] && !p[k + 1])
562 * Warn about those unusable chars in msdosfs here? XXX
568 for (k = 14; k < 26 && t < longName + sizeof(longName); k += 2) {
569 if (!p[k] && !p[k + 1])
576 for (k = 28; k < 32 && t < longName + sizeof(longName); k += 2) {
577 if (!p[k] && !p[k + 1])
583 if (t >= longName + sizeof(longName)) {
584 pwarn("long filename too long\n");
591 if (p[26] | (p[27] << 8)) {
592 pwarn("long filename record cluster start != 0\n");
599 continue; /* long records don't carry further
604 * This is a standard msdosfs directory entry.
606 memset(&dirent, 0, sizeof dirent);
609 * it's a short name record, but we need to know
610 * more, so get the flags first.
612 dirent.flags = p[11];
615 * Translate from 850 to ISO here XXX
617 for (j = 0; j < 8; j++)
618 dirent.name[j] = p[j];
619 dirent.name[8] = '\0';
620 for (k = 7; k >= 0 && dirent.name[k] == ' '; k--)
621 dirent.name[k] = '\0';
622 if (dirent.name[k] != '\0')
624 if (dirent.name[0] == SLOT_E5)
625 dirent.name[0] = 0xe5;
627 if (dirent.flags & ATTR_VOLUME) {
628 if (vallfn || invlfn) {
629 mod |= removede(f, boot, fat,
630 invlfn ? invlfn : vallfn, p,
631 invlfn ? invcl : valcl, -1, 0,
640 dirent.name[k++] = '.';
641 for (j = 0; j < 3; j++)
642 dirent.name[k++] = p[j+8];
643 dirent.name[k] = '\0';
644 for (k--; k >= 0 && dirent.name[k] == ' '; k--)
645 dirent.name[k] = '\0';
647 if (vallfn && shortSum != calcShortSum(p)) {
654 dirent.head = p[26] | (p[27] << 8);
655 if (boot->ClustMask == CLUST32_MASK)
656 dirent.head |= (p[20] << 16) | (p[21] << 24);
657 dirent.size = p[28] | (p[29] << 8) | (p[30] << 16) | (p[31] << 24);
659 strlcpy(dirent.lname, longName,
660 sizeof(dirent.lname));
666 dirent.next = dir->child;
669 mod |= k = removede(f, boot, fat,
670 invlfn, vallfn ? vallfn : p,
671 invcl, vallfn ? valcl : cl, cl,
672 fullpath(&dirent), 0);
676 ? (valcl == cl && vallfn != buffer)
682 vallfn = NULL; /* not used any longer */
685 if (dirent.size == 0 && !(dirent.flags & ATTR_DIRECTORY)) {
686 if (dirent.head != 0) {
687 pwarn("%s has clusters, but size 0\n",
689 if (ask(1, "Drop allocated clusters")) {
691 if (boot->ClustMask == CLUST32_MASK)
693 clearchain(boot, fat, dirent.head);
695 mod |= THISMOD|FSDIRMOD|FSFATMOD;
699 } else if (dirent.head == 0
700 && !strcmp(dirent.name, "..")
701 && dir->parent /* XXX */
702 && !dir->parent->parent) {
704 * Do nothing, the parent is the root
706 } else if (dirent.head < CLUST_FIRST
707 || dirent.head >= boot->NumClusters
708 || fat[dirent.head].next == CLUST_FREE
709 || (fat[dirent.head].next >= CLUST_RSRVD
710 && fat[dirent.head].next < CLUST_EOFS)
711 || fat[dirent.head].head != dirent.head) {
712 if (dirent.head == 0)
713 pwarn("%s has no clusters\n",
715 else if (dirent.head < CLUST_FIRST
716 || dirent.head >= boot->NumClusters)
717 pwarn("%s starts with cluster out of range(%u)\n",
720 else if (fat[dirent.head].next == CLUST_FREE)
721 pwarn("%s starts with free cluster\n",
723 else if (fat[dirent.head].next >= CLUST_RSRVD)
724 pwarn("%s starts with cluster marked %s\n",
726 rsrvdcltype(fat[dirent.head].next));
728 pwarn("%s doesn't start a cluster chain\n",
730 if (dirent.flags & ATTR_DIRECTORY) {
731 if (ask(0, "Remove")) {
733 mod |= THISMOD|FSDIRMOD;
738 if (ask(1, "Truncate")) {
739 p[28] = p[29] = p[30] = p[31] = 0;
741 if (boot->ClustMask == CLUST32_MASK)
744 mod |= THISMOD|FSDIRMOD;
750 if (dirent.head >= CLUST_FIRST && dirent.head < boot->NumClusters)
751 fat[dirent.head].flags |= FAT_USED;
753 if (dirent.flags & ATTR_DIRECTORY) {
755 * gather more info for directories
757 struct dirTodoNode *n;
760 pwarn("Directory %s has size != 0\n",
762 if (ask(1, "Correct")) {
763 p[28] = p[29] = p[30] = p[31] = 0;
765 mod |= THISMOD|FSDIRMOD;
770 * handle `.' and `..' specially
772 if (strcmp(dirent.name, ".") == 0) {
773 if (dirent.head != dir->head) {
774 pwarn("`.' entry in %s has incorrect start cluster\n",
776 if (ask(1, "Correct")) {
777 dirent.head = dir->head;
778 p[26] = (u_char)dirent.head;
779 p[27] = (u_char)(dirent.head >> 8);
780 if (boot->ClustMask == CLUST32_MASK) {
781 p[20] = (u_char)(dirent.head >> 16);
782 p[21] = (u_char)(dirent.head >> 24);
784 mod |= THISMOD|FSDIRMOD;
790 if (strcmp(dirent.name, "..") == 0) {
791 if (dir->parent) { /* XXX */
792 if (!dir->parent->parent) {
794 pwarn("`..' entry in %s has non-zero start cluster\n",
796 if (ask(1, "Correct")) {
799 if (boot->ClustMask == CLUST32_MASK)
801 mod |= THISMOD|FSDIRMOD;
805 } else if (dirent.head != dir->parent->head) {
806 pwarn("`..' entry in %s has incorrect start cluster\n",
808 if (ask(1, "Correct")) {
809 dirent.head = dir->parent->head;
810 p[26] = (u_char)dirent.head;
811 p[27] = (u_char)(dirent.head >> 8);
812 if (boot->ClustMask == CLUST32_MASK) {
813 p[20] = (u_char)(dirent.head >> 16);
814 p[21] = (u_char)(dirent.head >> 24);
816 mod |= THISMOD|FSDIRMOD;
824 /* create directory tree node */
825 if (!(d = newDosDirEntry())) {
826 perr("No space for directory");
829 memcpy(d, &dirent, sizeof(struct dosDirEntry));
830 /* link it into the tree */
833 /* Enter this directory into the todo list */
834 if (!(n = newDirTodo())) {
835 perr("No space for todo list");
838 n->next = pendingDirectories;
840 pendingDirectories = n;
842 mod |= k = checksize(boot, fat, p, &dirent);
849 if (!(boot->flags & FAT32) && !dir->parent)
854 if (lseek(f, off, SEEK_SET) != off
855 || write(f, buffer, last) != last) {
856 perr("Unable to write directory");
861 } while ((cl = fat[cl].next) >= CLUST_FIRST && cl < boot->NumClusters);
862 if (invlfn || vallfn)
863 mod |= removede(f, boot, fat,
864 invlfn ? invlfn : vallfn, p,
865 invlfn ? invcl : valcl, -1, 0,
868 /* The root directory of non fat32 filesystems is in a special
869 * area and may have been modified above without being written out.
871 if ((mod & FSDIRMOD) && !(boot->flags & FAT32) && !dir->parent) {
873 if (lseek(f, off, SEEK_SET) != off
874 || write(f, buffer, last) != last) {
875 perr("Unable to write directory");
880 return mod & ~THISMOD;
884 handleDirTree(int dosfs, struct bootblock *boot, struct fatEntry *fat)
888 mod = readDosDirSection(dosfs, boot, fat, rootDir);
893 * process the directory todo list
895 while (pendingDirectories) {
896 struct dosDirEntry *dir = pendingDirectories->dir;
897 struct dirTodoNode *n = pendingDirectories->next;
900 * remove TODO entry now, the list might change during
903 freeDirTodo(pendingDirectories);
904 pendingDirectories = n;
907 * handle subdirectory
909 mod |= readDosDirSection(dosfs, boot, fat, dir);
918 * Try to reconnect a FAT chain into dir
920 static u_char *lfbuf;
925 reconnect(int dosfs, struct bootblock *boot, struct fatEntry *fat, cl_t head)
927 struct dosDirEntry d;
930 if (!ask(1, "Reconnect"))
934 for (lostDir = rootDir->child; lostDir; lostDir = lostDir->next) {
935 if (!strcmp(lostDir->name, LOSTDIR))
938 if (!lostDir) { /* Create LOSTDIR? XXX */
939 pwarn("No %s directory\n", LOSTDIR);
944 lfbuf = malloc(boot->ClusterSize);
946 perr("No space for buffer");
954 for (; p < lfbuf + boot->ClusterSize; p += 32)
956 || *p == SLOT_DELETED)
958 if (p && p < lfbuf + boot->ClusterSize)
960 lfcl = p ? fat[lfcl].next : lostDir->head;
961 if (lfcl < CLUST_FIRST || lfcl >= boot->NumClusters) {
962 /* Extend LOSTDIR? XXX */
963 pwarn("No space in %s\n", LOSTDIR);
966 lfoff = lfcl * boot->ClusterSize
967 + boot->ClusterOffset * boot->bpbBytesPerSec;
968 if (lseek(dosfs, lfoff, SEEK_SET) != lfoff
969 || (size_t)read(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) {
970 perr("could not read LOST.DIR");
977 /* Ensure uniqueness of entry here! XXX */
978 memset(&d, 0, sizeof d);
979 (void)snprintf(d.name, sizeof(d.name), "%u", head);
982 d.size = fat[head].length * boot->ClusterSize;
986 memcpy(p, d.name, strlen(d.name));
987 p[26] = (u_char)d.head;
988 p[27] = (u_char)(d.head >> 8);
989 if (boot->ClustMask == CLUST32_MASK) {
990 p[20] = (u_char)(d.head >> 16);
991 p[21] = (u_char)(d.head >> 24);
993 p[28] = (u_char)d.size;
994 p[29] = (u_char)(d.size >> 8);
995 p[30] = (u_char)(d.size >> 16);
996 p[31] = (u_char)(d.size >> 24);
997 fat[head].flags |= FAT_USED;
998 if (lseek(dosfs, lfoff, SEEK_SET) != lfoff
999 || (size_t)write(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) {
1000 perr("could not write LOST.DIR");