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.
15 * 3. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
17 * This product includes software developed by Martin Husemann
18 * and Wolfgang Solfrank.
19 * 4. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 * $NetBSD: dir.c,v 1.14 1998/08/25 19:18:15 ross Exp $
35 * $FreeBSD: src/sbin/fsck_msdosfs/dir.c,v 1.1.2.1 2001/08/01 05:47:55 obrien Exp $
39 #include <sys/cdefs.h>
48 #include <sys/param.h>
53 #define SLOT_EMPTY 0x00 /* slot has never been used */
54 #define SLOT_E5 0x05 /* the real value is 0xe5 */
55 #define SLOT_DELETED 0xe5 /* file in this slot deleted */
57 #define ATTR_NORMAL 0x00 /* normal file */
58 #define ATTR_READONLY 0x01 /* file is readonly */
59 #define ATTR_HIDDEN 0x02 /* file is hidden */
60 #define ATTR_SYSTEM 0x04 /* file is a system file */
61 #define ATTR_VOLUME 0x08 /* entry is a volume label */
62 #define ATTR_DIRECTORY 0x10 /* entry is a directory name */
63 #define ATTR_ARCHIVE 0x20 /* file is new or modified */
65 #define ATTR_WIN95 0x0f /* long name record */
68 * This is the format of the contents of the deTime field in the direntry
70 * We don't use bitfields because we don't know how compilers for
71 * arbitrary machines will lay them out.
73 #define DT_2SECONDS_MASK 0x1F /* seconds divided by 2 */
74 #define DT_2SECONDS_SHIFT 0
75 #define DT_MINUTES_MASK 0x7E0 /* minutes */
76 #define DT_MINUTES_SHIFT 5
77 #define DT_HOURS_MASK 0xF800 /* hours */
78 #define DT_HOURS_SHIFT 11
81 * This is the format of the contents of the deDate field in the direntry
84 #define DD_DAY_MASK 0x1F /* day of month */
85 #define DD_DAY_SHIFT 0
86 #define DD_MONTH_MASK 0x1E0 /* month */
87 #define DD_MONTH_SHIFT 5
88 #define DD_YEAR_MASK 0xFE00 /* year - 1980 */
89 #define DD_YEAR_SHIFT 9
93 static struct dosDirEntry *newDosDirEntry(void);
94 static void freeDosDirEntry(struct dosDirEntry *);
95 static struct dirTodoNode *newDirTodo(void);
96 static void freeDirTodo(struct dirTodoNode *);
97 static char *fullpath(struct dosDirEntry *);
98 static u_char calcShortSum(u_char *);
99 static int delete(int, struct bootblock *, struct fatEntry *, cl_t, int,
101 static int removede(int, struct bootblock *, struct fatEntry *, u_char *,
102 u_char *, cl_t, cl_t, cl_t, char *, int);
103 static int checksize(struct bootblock *, struct fatEntry *, u_char *,
104 struct dosDirEntry *);
105 static int readDosDirSection(int, struct bootblock *, struct fatEntry *,
106 struct dosDirEntry *);
109 * Manage free dosDirEntry structures.
111 static struct dosDirEntry *freede;
113 static struct dosDirEntry *
116 struct dosDirEntry *de;
118 if (!(de = freede)) {
119 if (!(de = (struct dosDirEntry *)malloc(sizeof *de)))
127 freeDosDirEntry(struct dosDirEntry *de)
134 * The same for dirTodoNode structures.
136 static struct dirTodoNode *freedt;
138 static struct dirTodoNode *
141 struct dirTodoNode *dt;
143 if (!(dt = freedt)) {
144 if (!(dt = (struct dirTodoNode *)malloc(sizeof *dt)))
152 freeDirTodo(struct dirTodoNode *dt)
159 * The stack of unread directories
161 struct dirTodoNode *pendingDirectories = NULL;
164 * Return the full pathname for a directory entry.
167 fullpath(struct dosDirEntry *dir)
169 static char namebuf[MAXPATHLEN + 1];
173 cp = namebuf + sizeof namebuf - 1;
176 np = dir->lname[0] ? dir->lname : dir->name;
178 if ((cp -= nl) <= namebuf + 1)
182 } while ((dir = dir->parent) != NULL);
191 * Calculate a checksum over an 8.3 alias name
194 calcShortSum(u_char *p)
199 for (i = 0; i < 11; i++) {
200 sum = (sum << 7)|(sum >> 1); /* rotate right */
208 * Global variables temporarily used during a directory scan
210 static char longName[DOSLONGNAMELEN] = "";
211 static u_char *buffer = NULL;
212 static u_char *delbuf = NULL;
214 struct dosDirEntry *rootDir;
215 static struct dosDirEntry *lostDir;
218 * Init internal state for a new directory scan.
221 resetDosDirSection(struct bootblock *boot, struct fatEntry *fat)
227 b1 = boot->RootDirEnts * 32;
228 b2 = boot->SecPerClust * boot->BytesPerSec;
230 if (!(buffer = malloc(b1 > b2 ? b1 : b2))
231 || !(delbuf = malloc(b2))
232 || !(rootDir = newDosDirEntry())) {
233 perror("No space for directory");
236 memset(rootDir, 0, sizeof *rootDir);
237 if (boot->flags & FAT32) {
238 if (boot->RootCl < CLUST_FIRST || boot->RootCl >= boot->NumClusters) {
239 pfatal("Root directory starts with cluster out of range(%u)",
243 cl = fat[boot->RootCl].next;
245 || (cl >= CLUST_RSRVD && cl< CLUST_EOFS)
246 || fat[boot->RootCl].head != boot->RootCl) {
247 if (cl == CLUST_FREE)
248 pwarn("Root directory starts with free cluster\n");
249 else if (cl >= CLUST_RSRVD)
250 pwarn("Root directory starts with cluster marked %s\n",
253 pfatal("Root directory doesn't start a cluster chain");
257 fat[boot->RootCl].next = CLUST_FREE;
263 fat[boot->RootCl].flags |= FAT_USED;
264 rootDir->head = boot->RootCl;
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->SecPerClust * boot->BytesPerSec;
311 s = delbuf + startoff;
313 while (startcl >= CLUST_FIRST && startcl < boot->NumClusters) {
314 if (startcl == endcl) {
319 off = startcl * boot->SecPerClust + boot->ClusterOffset;
320 off *= boot->BytesPerSec;
321 if (lseek(f, off, SEEK_SET) != off
322 || read(f, delbuf, clsz) != clsz) {
323 perror("Unable to read directory");
330 if (lseek(f, off, SEEK_SET) != off
331 || write(f, delbuf, clsz) != clsz) {
332 perror("Unable to write directory");
335 if (startcl == endcl)
337 startcl = fat[startcl].next;
344 removede(int f, struct bootblock *boot, struct fatEntry *fat, u_char *start,
345 u_char *end, cl_t startcl, cl_t endcl, cl_t curcl, char *path,
350 pwarn("Invalid long filename entry for %s\n", path);
353 pwarn("Invalid long filename entry at end of directory %s\n", path);
356 pwarn("Invalid long filename entry for volume label\n");
359 if (ask(0, "Remove")) {
360 if (startcl != curcl) {
361 if (delete(f, boot, fat,
362 startcl, start - buffer,
364 endcl == curcl) == FSFATAL)
369 for (; start < end; start += 32)
370 *start = SLOT_DELETED;
377 * Check an in-memory file entry
380 checksize(struct bootblock *boot, struct fatEntry *fat, u_char *p,
381 struct dosDirEntry *dir)
384 * Check size on ordinary files
386 int32_t physicalSize;
388 if (dir->head == CLUST_FREE)
391 if (dir->head < CLUST_FIRST || dir->head >= boot->NumClusters)
393 physicalSize = fat[dir->head].length * boot->ClusterSize;
395 if (physicalSize < dir->size) {
396 pwarn("size of %s is %u, should at most be %u\n",
397 fullpath(dir), dir->size, physicalSize);
398 if (ask(1, "Truncate")) {
399 dir->size = physicalSize;
400 p[28] = (u_char)physicalSize;
401 p[29] = (u_char)(physicalSize >> 8);
402 p[30] = (u_char)(physicalSize >> 16);
403 p[31] = (u_char)(physicalSize >> 24);
407 } else if (physicalSize - dir->size >= boot->ClusterSize) {
408 pwarn("%s has too many clusters allocated\n",
410 if (ask(1, "Drop superfluous clusters")) {
414 for (cl = dir->head; (sz += boot->ClusterSize) < dir->size;)
416 clearchain(boot, fat, fat[cl].next);
417 fat[cl].next = CLUST_EOF;
426 * Read a directory and
427 * - resolve long name records
428 * - enter file and directory records into the parent's list
429 * - push directories onto the todo-stack
432 readDosDirSection(int f, struct bootblock *boot, struct fatEntry *fat,
433 struct dosDirEntry *dir)
435 struct dosDirEntry dirent, *d;
436 u_char *p, *vallfn, *invlfn, *empty;
439 cl_t cl, valcl = ~0, invcl = ~0, empcl = ~0;
444 #define THISMOD 0x8000 /* Only used within this routine */
447 if (dir->parent && (cl < CLUST_FIRST || cl >= boot->NumClusters)) {
449 * Already handled somewhere else.
454 vallfn = invlfn = empty = NULL;
456 if (!(boot->flags & FAT32) && !dir->parent) {
457 last = boot->RootDirEnts * 32;
458 off = boot->ResSectors + boot->FATs * boot->FATsecs;
460 last = boot->SecPerClust * boot->BytesPerSec;
461 off = cl * boot->SecPerClust + boot->ClusterOffset;
464 off *= boot->BytesPerSec;
465 if (lseek(f, off, SEEK_SET) != off
466 || read(f, buffer, last) != last) {
467 perror("Unable to read directory");
472 * Check `.' and `..' entries here? XXX
474 for (p = buffer, i = 0; i < last; i++, p += 32) {
475 if (dir->fsckflags & DIREMPWARN) {
480 if (*p == SLOT_EMPTY || *p == SLOT_DELETED) {
481 if (*p == SLOT_EMPTY) {
482 dir->fsckflags |= DIREMPTY;
489 if (dir->fsckflags & DIREMPTY) {
490 if (!(dir->fsckflags & DIREMPWARN)) {
491 pwarn("%s has entries after end of directory\n",
493 if (ask(1, "Extend")) {
496 dir->fsckflags &= ~DIREMPTY;
497 if (delete(f, boot, fat,
498 empcl, empty - buffer,
499 cl, p - buffer, 1) == FSFATAL)
501 q = empcl == cl ? empty : buffer;
502 for (; q < p; q += 32)
504 mod |= THISMOD|FSDIRMOD;
505 } else if (ask(0, "Truncate"))
506 dir->fsckflags |= DIREMPWARN;
508 if (dir->fsckflags & DIREMPWARN) {
510 mod |= THISMOD|FSDIRMOD;
512 } else if (dir->fsckflags & DIREMPTY)
517 if (p[11] == ATTR_WIN95) {
519 if (shortSum != -1) {
525 memset(longName, 0, sizeof longName);
529 } else if (shortSum != p[13]
530 || lidx != (*p & LRNOMASK)) {
541 lidx = *p & LRNOMASK;
542 t = longName + --lidx * 13;
543 for (k = 1; k < 11 && t < longName + sizeof(longName); k += 2) {
544 if (!p[k] && !p[k + 1])
548 * Warn about those unusable chars in msdosfs here? XXX
554 for (k = 14; k < 26 && t < longName + sizeof(longName); k += 2) {
555 if (!p[k] && !p[k + 1])
562 for (k = 28; k < 32 && t < longName + sizeof(longName); k += 2) {
563 if (!p[k] && !p[k + 1])
569 if (t >= longName + sizeof(longName)) {
570 pwarn("long filename too long\n");
577 if (p[26] | (p[27] << 8)) {
578 pwarn("long filename record cluster start != 0\n");
585 continue; /* long records don't carry further
590 * This is a standard msdosfs directory entry.
592 memset(&dirent, 0, sizeof dirent);
595 * it's a short name record, but we need to know
596 * more, so get the flags first.
598 dirent.flags = p[11];
601 * Translate from 850 to ISO here XXX
603 for (j = 0; j < 8; j++)
604 dirent.name[j] = p[j];
605 dirent.name[8] = '\0';
606 for (k = 7; k >= 0 && dirent.name[k] == ' '; k--)
607 dirent.name[k] = '\0';
608 if (dirent.name[k] != '\0')
610 if (dirent.name[0] == SLOT_E5)
611 dirent.name[0] = 0xe5;
613 if (dirent.flags & ATTR_VOLUME) {
614 if (vallfn || invlfn) {
615 mod |= removede(f, boot, fat,
616 invlfn ? invlfn : vallfn, p,
617 invlfn ? invcl : valcl, -1, 0,
626 dirent.name[k++] = '.';
627 for (j = 0; j < 3; j++)
628 dirent.name[k++] = p[j+8];
629 dirent.name[k] = '\0';
630 for (k--; k >= 0 && dirent.name[k] == ' '; k--)
631 dirent.name[k] = '\0';
633 if (vallfn && shortSum != calcShortSum(p)) {
640 dirent.head = p[26] | (p[27] << 8);
641 if (boot->ClustMask == CLUST32_MASK)
642 dirent.head |= (p[20] << 16) | (p[21] << 24);
643 dirent.size = p[28] | (p[29] << 8) | (p[30] << 16) | (p[31] << 24);
645 strcpy(dirent.lname, longName);
651 dirent.next = dir->child;
654 mod |= k = removede(f, boot, fat,
655 invlfn, vallfn ? vallfn : p,
656 invcl, vallfn ? valcl : cl, cl,
657 fullpath(&dirent), 0);
661 ? (valcl == cl && vallfn != buffer)
667 vallfn = NULL; /* not used any longer */
670 if (dirent.size == 0 && !(dirent.flags & ATTR_DIRECTORY)) {
671 if (dirent.head != 0) {
672 pwarn("%s has clusters, but size 0\n",
674 if (ask(1, "Drop allocated clusters")) {
676 if (boot->ClustMask == CLUST32_MASK)
678 clearchain(boot, fat, dirent.head);
680 mod |= THISMOD|FSDIRMOD|FSFATMOD;
684 } else if (dirent.head == 0
685 && !strcmp(dirent.name, "..")
686 && dir->parent /* XXX */
687 && !dir->parent->parent) {
689 * Do nothing, the parent is the root
691 } else if (dirent.head < CLUST_FIRST
692 || dirent.head >= boot->NumClusters
693 || fat[dirent.head].next == CLUST_FREE
694 || (fat[dirent.head].next >= CLUST_RSRVD
695 && fat[dirent.head].next < CLUST_EOFS)
696 || fat[dirent.head].head != dirent.head) {
697 if (dirent.head == 0)
698 pwarn("%s has no clusters\n",
700 else if (dirent.head < CLUST_FIRST
701 || dirent.head >= boot->NumClusters)
702 pwarn("%s starts with cluster out of range(%u)\n",
705 else if (fat[dirent.head].next == CLUST_FREE)
706 pwarn("%s starts with free cluster\n",
708 else if (fat[dirent.head].next >= CLUST_RSRVD)
709 pwarn("%s starts with cluster marked %s\n",
711 rsrvdcltype(fat[dirent.head].next));
713 pwarn("%s doesn't start a cluster chain\n",
715 if (dirent.flags & ATTR_DIRECTORY) {
716 if (ask(0, "Remove")) {
718 mod |= THISMOD|FSDIRMOD;
723 if (ask(1, "Truncate")) {
724 p[28] = p[29] = p[30] = p[31] = 0;
726 if (boot->ClustMask == CLUST32_MASK)
729 mod |= THISMOD|FSDIRMOD;
735 if (dirent.head >= CLUST_FIRST && dirent.head < boot->NumClusters)
736 fat[dirent.head].flags |= FAT_USED;
738 if (dirent.flags & ATTR_DIRECTORY) {
740 * gather more info for directories
742 struct dirTodoNode *n;
745 pwarn("Directory %s has size != 0\n",
747 if (ask(1, "Correct")) {
748 p[28] = p[29] = p[30] = p[31] = 0;
750 mod |= THISMOD|FSDIRMOD;
755 * handle `.' and `..' specially
757 if (strcmp(dirent.name, ".") == 0) {
758 if (dirent.head != dir->head) {
759 pwarn("`.' entry in %s has incorrect start cluster\n",
761 if (ask(1, "Correct")) {
762 dirent.head = dir->head;
763 p[26] = (u_char)dirent.head;
764 p[27] = (u_char)(dirent.head >> 8);
765 if (boot->ClustMask == CLUST32_MASK) {
766 p[20] = (u_char)(dirent.head >> 16);
767 p[21] = (u_char)(dirent.head >> 24);
769 mod |= THISMOD|FSDIRMOD;
775 if (strcmp(dirent.name, "..") == 0) {
776 if (dir->parent) { /* XXX */
777 if (!dir->parent->parent) {
779 pwarn("`..' entry in %s has non-zero start cluster\n",
781 if (ask(1, "Correct")) {
784 if (boot->ClustMask == CLUST32_MASK)
786 mod |= THISMOD|FSDIRMOD;
790 } else if (dirent.head != dir->parent->head) {
791 pwarn("`..' entry in %s has incorrect start cluster\n",
793 if (ask(1, "Correct")) {
794 dirent.head = dir->parent->head;
795 p[26] = (u_char)dirent.head;
796 p[27] = (u_char)(dirent.head >> 8);
797 if (boot->ClustMask == CLUST32_MASK) {
798 p[20] = (u_char)(dirent.head >> 16);
799 p[21] = (u_char)(dirent.head >> 24);
801 mod |= THISMOD|FSDIRMOD;
809 /* create directory tree node */
810 if (!(d = newDosDirEntry())) {
811 perror("No space for directory");
814 memcpy(d, &dirent, sizeof(struct dosDirEntry));
815 /* link it into the tree */
818 /* Enter this directory into the todo list */
819 if (!(n = newDirTodo())) {
820 perror("No space for todo list");
823 n->next = pendingDirectories;
825 pendingDirectories = n;
827 mod |= k = checksize(boot, fat, p, &dirent);
835 if (lseek(f, off, SEEK_SET) != off
836 || write(f, buffer, last) != last) {
837 perror("Unable to write directory");
842 } while ((cl = fat[cl].next) >= CLUST_FIRST && cl < boot->NumClusters);
843 if (invlfn || vallfn)
844 mod |= removede(f, boot, fat,
845 invlfn ? invlfn : vallfn, p,
846 invlfn ? invcl : valcl, -1, 0,
848 return mod & ~THISMOD;
852 handleDirTree(int dosfs, struct bootblock *boot, struct fatEntry *fat)
856 mod = readDosDirSection(dosfs, boot, fat, rootDir);
861 * process the directory todo list
863 while (pendingDirectories) {
864 struct dosDirEntry *dir = pendingDirectories->dir;
865 struct dirTodoNode *n = pendingDirectories->next;
868 * remove TODO entry now, the list might change during
871 freeDirTodo(pendingDirectories);
872 pendingDirectories = n;
875 * handle subdirectory
877 mod |= readDosDirSection(dosfs, boot, fat, dir);
886 * Try to reconnect a FAT chain into dir
888 static u_char *lfbuf;
893 reconnect(int dosfs, struct bootblock *boot, struct fatEntry *fat, cl_t head)
895 struct dosDirEntry d;
898 if (!ask(1, "Reconnect"))
902 for (lostDir = rootDir->child; lostDir; lostDir = lostDir->next) {
903 if (!strcmp(lostDir->name, LOSTDIR))
906 if (!lostDir) { /* Create LOSTDIR? XXX */
907 pwarn("No %s directory\n", LOSTDIR);
912 lfbuf = malloc(boot->ClusterSize);
914 perror("No space for buffer");
922 for (; p < lfbuf + boot->ClusterSize; p += 32)
924 || *p == SLOT_DELETED)
926 if (p && p < lfbuf + boot->ClusterSize)
928 lfcl = p ? fat[lfcl].next : lostDir->head;
929 if (lfcl < CLUST_FIRST || lfcl >= boot->NumClusters) {
930 /* Extend LOSTDIR? XXX */
931 pwarn("No space in %s\n", LOSTDIR);
934 lfoff = lfcl * boot->ClusterSize
935 + boot->ClusterOffset * boot->BytesPerSec;
936 if (lseek(dosfs, lfoff, SEEK_SET) != lfoff
937 || read(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) {
938 perror("could not read LOST.DIR");
945 /* Ensure uniqueness of entry here! XXX */
946 memset(&d, 0, sizeof d);
947 snprintf(d.name, sizeof(d.name), "%u", head);
950 d.size = fat[head].length * boot->ClusterSize;
954 memcpy(p, d.name, strlen(d.name));
955 p[26] = (u_char)d.head;
956 p[27] = (u_char)(d.head >> 8);
957 if (boot->ClustMask == CLUST32_MASK) {
958 p[20] = (u_char)(d.head >> 16);
959 p[21] = (u_char)(d.head >> 24);
961 p[28] = (u_char)d.size;
962 p[29] = (u_char)(d.size >> 8);
963 p[30] = (u_char)(d.size >> 16);
964 p[31] = (u_char)(d.size >> 24);
965 fat[head].flags |= FAT_USED;
966 if (lseek(dosfs, lfoff, SEEK_SET) != lfoff
967 || write(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) {
968 perror("could not write LOST.DIR");