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 $
45 #include <sys/param.h>
50 #define SLOT_EMPTY 0x00 /* slot has never been used */
51 #define SLOT_E5 0x05 /* the real value is 0xe5 */
52 #define SLOT_DELETED 0xe5 /* file in this slot deleted */
54 #define ATTR_NORMAL 0x00 /* normal file */
55 #define ATTR_READONLY 0x01 /* file is readonly */
56 #define ATTR_HIDDEN 0x02 /* file is hidden */
57 #define ATTR_SYSTEM 0x04 /* file is a system file */
58 #define ATTR_VOLUME 0x08 /* entry is a volume label */
59 #define ATTR_DIRECTORY 0x10 /* entry is a directory name */
60 #define ATTR_ARCHIVE 0x20 /* file is new or modified */
62 #define ATTR_WIN95 0x0f /* long name record */
65 * This is the format of the contents of the deTime field in the direntry
67 * We don't use bitfields because we don't know how compilers for
68 * arbitrary machines will lay them out.
70 #define DT_2SECONDS_MASK 0x1F /* seconds divided by 2 */
71 #define DT_2SECONDS_SHIFT 0
72 #define DT_MINUTES_MASK 0x7E0 /* minutes */
73 #define DT_MINUTES_SHIFT 5
74 #define DT_HOURS_MASK 0xF800 /* hours */
75 #define DT_HOURS_SHIFT 11
78 * This is the format of the contents of the deDate field in the direntry
81 #define DD_DAY_MASK 0x1F /* day of month */
82 #define DD_DAY_SHIFT 0
83 #define DD_MONTH_MASK 0x1E0 /* month */
84 #define DD_MONTH_SHIFT 5
85 #define DD_YEAR_MASK 0xFE00 /* year - 1980 */
86 #define DD_YEAR_SHIFT 9
90 static struct dosDirEntry *newDosDirEntry(void);
91 static void freeDosDirEntry(struct dosDirEntry *);
92 static struct dirTodoNode *newDirTodo(void);
93 static void freeDirTodo(struct dirTodoNode *);
94 static char *fullpath(struct dosDirEntry *);
95 static u_char calcShortSum(u_char *);
96 static int delete(int, struct bootblock *, struct fatEntry *, cl_t, int,
98 static int removede(int, struct bootblock *, struct fatEntry *, u_char *,
99 u_char *, cl_t, cl_t, cl_t, char *, int);
100 static int checksize(struct bootblock *, struct fatEntry *, u_char *,
101 struct dosDirEntry *);
102 static int readDosDirSection(int, struct bootblock *, struct fatEntry *,
103 struct dosDirEntry *);
106 * Manage free dosDirEntry structures.
108 static struct dosDirEntry *freede;
110 static struct dosDirEntry *
113 struct dosDirEntry *de;
115 if (!(de = freede)) {
116 if (!(de = (struct dosDirEntry *)malloc(sizeof *de)))
124 freeDosDirEntry(struct dosDirEntry *de)
131 * The same for dirTodoNode structures.
133 static struct dirTodoNode *freedt;
135 static struct dirTodoNode *
138 struct dirTodoNode *dt;
140 if (!(dt = freedt)) {
141 if (!(dt = (struct dirTodoNode *)malloc(sizeof *dt)))
149 freeDirTodo(struct dirTodoNode *dt)
156 * The stack of unread directories
158 struct dirTodoNode *pendingDirectories = NULL;
161 * Return the full pathname for a directory entry.
164 fullpath(struct dosDirEntry *dir)
166 static char namebuf[MAXPATHLEN + 1];
170 cp = namebuf + sizeof namebuf;
174 np = dir->lname[0] ? dir->lname : dir->name;
176 if (cp <= namebuf + 1 + nl) {
192 * Calculate a checksum over an 8.3 alias name
195 calcShortSum(u_char *p)
200 for (i = 0; i < 11; i++) {
201 sum = (sum << 7)|(sum >> 1); /* rotate right */
209 * Global variables temporarily used during a directory scan
211 static char longName[DOSLONGNAMELEN] = "";
212 static u_char *buffer = NULL;
213 static u_char *delbuf = NULL;
215 struct dosDirEntry *rootDir;
216 static struct dosDirEntry *lostDir;
219 * Init internal state for a new directory scan.
222 resetDosDirSection(struct bootblock *boot, struct fatEntry *fat)
228 b1 = boot->RootDirEnts * 32;
229 b2 = boot->SecPerClust * boot->BytesPerSec;
231 if (!(buffer = malloc(b1 > b2 ? b1 : b2))
232 || !(delbuf = malloc(b2))
233 || !(rootDir = newDosDirEntry())) {
234 perror("No space for directory");
237 memset(rootDir, 0, sizeof *rootDir);
238 if (boot->flags & FAT32) {
239 if (boot->RootCl < CLUST_FIRST || boot->RootCl >= boot->NumClusters) {
240 pfatal("Root directory starts with cluster out of range(%u)",
244 cl = fat[boot->RootCl].next;
246 || (cl >= CLUST_RSRVD && cl< CLUST_EOFS)
247 || fat[boot->RootCl].head != boot->RootCl) {
248 if (cl == CLUST_FREE)
249 pwarn("Root directory starts with free cluster\n");
250 else if (cl >= CLUST_RSRVD)
251 pwarn("Root directory starts with cluster marked %s\n",
254 pfatal("Root directory doesn't start a cluster chain");
258 fat[boot->RootCl].next = CLUST_FREE;
264 fat[boot->RootCl].flags |= FAT_USED;
265 rootDir->head = boot->RootCl;
272 * Cleanup after a directory scan
275 finishDosDirSection(void)
277 struct dirTodoNode *p, *np;
278 struct dosDirEntry *d, *nd;
280 for (p = pendingDirectories; p; p = np) {
284 pendingDirectories = NULL;
285 for (d = rootDir; d; d = nd) {
286 if ((nd = d->child) != NULL) {
294 rootDir = lostDir = NULL;
302 * Delete directory entries between startcl, startoff and endcl, endoff.
305 delete(int f, struct bootblock *boot, struct fatEntry *fat, cl_t startcl,
306 int startoff, cl_t endcl, int endoff, int notlast)
310 int clsz = boot->SecPerClust * boot->BytesPerSec;
312 s = delbuf + startoff;
314 while (startcl >= CLUST_FIRST && startcl < boot->NumClusters) {
315 if (startcl == endcl) {
320 off = startcl * boot->SecPerClust + boot->ClusterOffset;
321 off *= boot->BytesPerSec;
322 if (lseek(f, off, SEEK_SET) != off
323 || read(f, delbuf, clsz) != clsz) {
324 perror("Unable to read directory");
331 if (lseek(f, off, SEEK_SET) != off
332 || write(f, delbuf, clsz) != clsz) {
333 perror("Unable to write directory");
336 if (startcl == endcl)
338 startcl = fat[startcl].next;
345 removede(int f, struct bootblock *boot, struct fatEntry *fat, u_char *start,
346 u_char *end, cl_t startcl, cl_t endcl, cl_t curcl, char *path,
351 pwarn("Invalid long filename entry for %s\n", path);
354 pwarn("Invalid long filename entry at end of directory %s\n", path);
357 pwarn("Invalid long filename entry for volume label\n");
360 if (ask(0, "Remove")) {
361 if (startcl != curcl) {
362 if (delete(f, boot, fat,
363 startcl, start - buffer,
365 endcl == curcl) == FSFATAL)
370 for (; start < end; start += 32)
371 *start = SLOT_DELETED;
378 * Check an in-memory file entry
381 checksize(struct bootblock *boot, struct fatEntry *fat, u_char *p,
382 struct dosDirEntry *dir)
385 * Check size on ordinary files
387 int32_t physicalSize;
389 if (dir->head == CLUST_FREE)
392 if (dir->head < CLUST_FIRST || dir->head >= boot->NumClusters)
394 physicalSize = fat[dir->head].length * boot->ClusterSize;
396 if (physicalSize < dir->size) {
397 pwarn("size of %s is %u, should at most be %u\n",
398 fullpath(dir), dir->size, physicalSize);
399 if (ask(1, "Truncate")) {
400 dir->size = physicalSize;
401 p[28] = (u_char)physicalSize;
402 p[29] = (u_char)(physicalSize >> 8);
403 p[30] = (u_char)(physicalSize >> 16);
404 p[31] = (u_char)(physicalSize >> 24);
408 } else if (physicalSize - dir->size >= boot->ClusterSize) {
409 pwarn("%s has too many clusters allocated\n",
411 if (ask(1, "Drop superfluous clusters")) {
415 for (cl = dir->head; (sz += boot->ClusterSize) < dir->size;)
417 clearchain(boot, fat, fat[cl].next);
418 fat[cl].next = CLUST_EOF;
427 * Read a directory and
428 * - resolve long name records
429 * - enter file and directory records into the parent's list
430 * - push directories onto the todo-stack
433 readDosDirSection(int f, struct bootblock *boot, struct fatEntry *fat,
434 struct dosDirEntry *dir)
436 struct dosDirEntry dirent, *d;
437 u_char *p, *vallfn, *invlfn, *empty;
440 cl_t cl, valcl = ~0, invcl = ~0, empcl = ~0;
445 #define THISMOD 0x8000 /* Only used within this routine */
448 if (dir->parent && (cl < CLUST_FIRST || cl >= boot->NumClusters)) {
450 * Already handled somewhere else.
455 vallfn = invlfn = empty = NULL;
457 if (!(boot->flags & FAT32) && !dir->parent) {
458 last = boot->RootDirEnts * 32;
459 off = boot->ResSectors + boot->FATs * boot->FATsecs;
461 last = boot->SecPerClust * boot->BytesPerSec;
462 off = cl * boot->SecPerClust + boot->ClusterOffset;
465 off *= boot->BytesPerSec;
466 if (lseek(f, off, SEEK_SET) != off
467 || read(f, buffer, last) != last) {
468 perror("Unable to read directory");
473 * Check `.' and `..' entries here? XXX
475 for (p = buffer, i = 0; i < last; i++, p += 32) {
476 if (dir->fsckflags & DIREMPWARN) {
481 if (*p == SLOT_EMPTY || *p == SLOT_DELETED) {
482 if (*p == SLOT_EMPTY) {
483 dir->fsckflags |= DIREMPTY;
490 if (dir->fsckflags & DIREMPTY) {
491 if (!(dir->fsckflags & DIREMPWARN)) {
492 pwarn("%s has entries after end of directory\n",
494 if (ask(1, "Extend")) {
497 dir->fsckflags &= ~DIREMPTY;
498 if (delete(f, boot, fat,
499 empcl, empty - buffer,
500 cl, p - buffer, 1) == FSFATAL)
502 q = empcl == cl ? empty : buffer;
503 for (; q < p; q += 32)
505 mod |= THISMOD|FSDIRMOD;
506 } else if (ask(0, "Truncate"))
507 dir->fsckflags |= DIREMPWARN;
509 if (dir->fsckflags & DIREMPWARN) {
511 mod |= THISMOD|FSDIRMOD;
513 } else if (dir->fsckflags & DIREMPTY)
518 if (p[11] == ATTR_WIN95) {
520 if (shortSum != -1) {
526 memset(longName, 0, sizeof longName);
530 } else if (shortSum != p[13]
531 || lidx != (*p & LRNOMASK)) {
542 lidx = *p & LRNOMASK;
543 t = longName + --lidx * 13;
544 for (k = 1; k < 11 && t < longName + sizeof(longName); k += 2) {
545 if (!p[k] && !p[k + 1])
549 * Warn about those unusable chars in msdosfs here? XXX
555 for (k = 14; k < 26 && t < longName + sizeof(longName); k += 2) {
556 if (!p[k] && !p[k + 1])
563 for (k = 28; k < 32 && t < longName + sizeof(longName); k += 2) {
564 if (!p[k] && !p[k + 1])
570 if (t >= longName + sizeof(longName)) {
571 pwarn("long filename too long\n");
578 if (p[26] | (p[27] << 8)) {
579 pwarn("long filename record cluster start != 0\n");
586 continue; /* long records don't carry further
591 * This is a standard msdosfs directory entry.
593 memset(&dirent, 0, sizeof dirent);
596 * it's a short name record, but we need to know
597 * more, so get the flags first.
599 dirent.flags = p[11];
602 * Translate from 850 to ISO here XXX
604 for (j = 0; j < 8; j++)
605 dirent.name[j] = p[j];
606 dirent.name[8] = '\0';
607 for (k = 7; k >= 0 && dirent.name[k] == ' '; k--)
608 dirent.name[k] = '\0';
609 if (dirent.name[k] != '\0')
611 if (dirent.name[0] == SLOT_E5)
612 dirent.name[0] = 0xe5;
614 if (dirent.flags & ATTR_VOLUME) {
615 if (vallfn || invlfn) {
616 mod |= removede(f, boot, fat,
617 invlfn ? invlfn : vallfn, p,
618 invlfn ? invcl : valcl, -1, 0,
627 dirent.name[k++] = '.';
628 for (j = 0; j < 3; j++)
629 dirent.name[k++] = p[j+8];
630 dirent.name[k] = '\0';
631 for (k--; k >= 0 && dirent.name[k] == ' '; k--)
632 dirent.name[k] = '\0';
634 if (vallfn && shortSum != calcShortSum(p)) {
641 dirent.head = p[26] | (p[27] << 8);
642 if (boot->ClustMask == CLUST32_MASK)
643 dirent.head |= (p[20] << 16) | (p[21] << 24);
644 dirent.size = p[28] | (p[29] << 8) | (p[30] << 16) | (p[31] << 24);
646 strcpy(dirent.lname, longName);
652 dirent.next = dir->child;
655 mod |= k = removede(f, boot, fat,
656 invlfn, vallfn ? vallfn : p,
657 invcl, vallfn ? valcl : cl, cl,
658 fullpath(&dirent), 0);
662 ? (valcl == cl && vallfn != buffer)
668 vallfn = NULL; /* not used any longer */
671 if (dirent.size == 0 && !(dirent.flags & ATTR_DIRECTORY)) {
672 if (dirent.head != 0) {
673 pwarn("%s has clusters, but size 0\n",
675 if (ask(1, "Drop allocated clusters")) {
677 if (boot->ClustMask == CLUST32_MASK)
679 clearchain(boot, fat, dirent.head);
681 mod |= THISMOD|FSDIRMOD|FSFATMOD;
685 } else if (dirent.head == 0
686 && !strcmp(dirent.name, "..")
687 && dir->parent /* XXX */
688 && !dir->parent->parent) {
690 * Do nothing, the parent is the root
692 } else if (dirent.head < CLUST_FIRST
693 || dirent.head >= boot->NumClusters
694 || fat[dirent.head].next == CLUST_FREE
695 || (fat[dirent.head].next >= CLUST_RSRVD
696 && fat[dirent.head].next < CLUST_EOFS)
697 || fat[dirent.head].head != dirent.head) {
698 if (dirent.head == 0)
699 pwarn("%s has no clusters\n",
701 else if (dirent.head < CLUST_FIRST
702 || dirent.head >= boot->NumClusters)
703 pwarn("%s starts with cluster out of range(%u)\n",
706 else if (fat[dirent.head].next == CLUST_FREE)
707 pwarn("%s starts with free cluster\n",
709 else if (fat[dirent.head].next >= CLUST_RSRVD)
710 pwarn("%s starts with cluster marked %s\n",
712 rsrvdcltype(fat[dirent.head].next));
714 pwarn("%s doesn't start a cluster chain\n",
716 if (dirent.flags & ATTR_DIRECTORY) {
717 if (ask(0, "Remove")) {
719 mod |= THISMOD|FSDIRMOD;
724 if (ask(1, "Truncate")) {
725 p[28] = p[29] = p[30] = p[31] = 0;
727 if (boot->ClustMask == CLUST32_MASK)
730 mod |= THISMOD|FSDIRMOD;
736 if (dirent.head >= CLUST_FIRST && dirent.head < boot->NumClusters)
737 fat[dirent.head].flags |= FAT_USED;
739 if (dirent.flags & ATTR_DIRECTORY) {
741 * gather more info for directories
743 struct dirTodoNode *n;
746 pwarn("Directory %s has size != 0\n",
748 if (ask(1, "Correct")) {
749 p[28] = p[29] = p[30] = p[31] = 0;
751 mod |= THISMOD|FSDIRMOD;
756 * handle `.' and `..' specially
758 if (strcmp(dirent.name, ".") == 0) {
759 if (dirent.head != dir->head) {
760 pwarn("`.' entry in %s has incorrect start cluster\n",
762 if (ask(1, "Correct")) {
763 dirent.head = dir->head;
764 p[26] = (u_char)dirent.head;
765 p[27] = (u_char)(dirent.head >> 8);
766 if (boot->ClustMask == CLUST32_MASK) {
767 p[20] = (u_char)(dirent.head >> 16);
768 p[21] = (u_char)(dirent.head >> 24);
770 mod |= THISMOD|FSDIRMOD;
776 if (strcmp(dirent.name, "..") == 0) {
777 if (dir->parent) { /* XXX */
778 if (!dir->parent->parent) {
780 pwarn("`..' entry in %s has non-zero start cluster\n",
782 if (ask(1, "Correct")) {
785 if (boot->ClustMask == CLUST32_MASK)
787 mod |= THISMOD|FSDIRMOD;
791 } else if (dirent.head != dir->parent->head) {
792 pwarn("`..' entry in %s has incorrect start cluster\n",
794 if (ask(1, "Correct")) {
795 dirent.head = dir->parent->head;
796 p[26] = (u_char)dirent.head;
797 p[27] = (u_char)(dirent.head >> 8);
798 if (boot->ClustMask == CLUST32_MASK) {
799 p[20] = (u_char)(dirent.head >> 16);
800 p[21] = (u_char)(dirent.head >> 24);
802 mod |= THISMOD|FSDIRMOD;
810 /* create directory tree node */
811 if (!(d = newDosDirEntry())) {
812 perror("No space for directory");
815 memcpy(d, &dirent, sizeof(struct dosDirEntry));
816 /* link it into the tree */
819 /* Enter this directory into the todo list */
820 if (!(n = newDirTodo())) {
821 perror("No space for todo list");
824 n->next = pendingDirectories;
826 pendingDirectories = n;
828 mod |= k = checksize(boot, fat, p, &dirent);
836 if (lseek(f, off, SEEK_SET) != off
837 || write(f, buffer, last) != last) {
838 perror("Unable to write directory");
843 } while ((cl = fat[cl].next) >= CLUST_FIRST && cl < boot->NumClusters);
844 if (invlfn || vallfn)
845 mod |= removede(f, boot, fat,
846 invlfn ? invlfn : vallfn, p,
847 invlfn ? invcl : valcl, -1, 0,
849 return mod & ~THISMOD;
853 handleDirTree(int dosfs, struct bootblock *boot, struct fatEntry *fat)
857 mod = readDosDirSection(dosfs, boot, fat, rootDir);
862 * process the directory todo list
864 while (pendingDirectories) {
865 struct dosDirEntry *dir = pendingDirectories->dir;
866 struct dirTodoNode *n = pendingDirectories->next;
869 * remove TODO entry now, the list might change during
872 freeDirTodo(pendingDirectories);
873 pendingDirectories = n;
876 * handle subdirectory
878 mod |= readDosDirSection(dosfs, boot, fat, dir);
887 * Try to reconnect a FAT chain into dir
889 static u_char *lfbuf;
894 reconnect(int dosfs, struct bootblock *boot, struct fatEntry *fat, cl_t head)
896 struct dosDirEntry d;
899 if (!ask(1, "Reconnect"))
903 for (lostDir = rootDir->child; lostDir; lostDir = lostDir->next) {
904 if (!strcmp(lostDir->name, LOSTDIR))
907 if (!lostDir) { /* Create LOSTDIR? XXX */
908 pwarn("No %s directory\n", LOSTDIR);
913 lfbuf = malloc(boot->ClusterSize);
915 perror("No space for buffer");
923 for (; p < lfbuf + boot->ClusterSize; p += 32)
925 || *p == SLOT_DELETED)
927 if (p && p < lfbuf + boot->ClusterSize)
929 lfcl = p ? fat[lfcl].next : lostDir->head;
930 if (lfcl < CLUST_FIRST || lfcl >= boot->NumClusters) {
931 /* Extend LOSTDIR? XXX */
932 pwarn("No space in %s\n", LOSTDIR);
935 lfoff = lfcl * boot->ClusterSize
936 + boot->ClusterOffset * boot->BytesPerSec;
937 if (lseek(dosfs, lfoff, SEEK_SET) != lfoff
938 || read(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) {
939 perror("could not read LOST.DIR");
946 /* Ensure uniqueness of entry here! XXX */
947 memset(&d, 0, sizeof d);
948 snprintf(d.name, sizeof(d.name), "%u", head);
951 d.size = fat[head].length * boot->ClusterSize;
955 memcpy(p, d.name, strlen(d.name));
956 p[26] = (u_char)d.head;
957 p[27] = (u_char)(d.head >> 8);
958 if (boot->ClustMask == CLUST32_MASK) {
959 p[20] = (u_char)(d.head >> 16);
960 p[21] = (u_char)(d.head >> 24);
962 p[28] = (u_char)d.size;
963 p[29] = (u_char)(d.size >> 8);
964 p[30] = (u_char)(d.size >> 16);
965 p[31] = (u_char)(d.size >> 24);
966 fat[head].flags |= FAT_USED;
967 if (lseek(dosfs, lfoff, SEEK_SET) != lfoff
968 || write(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) {
969 perror("could not write LOST.DIR");