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.14 1998/08/25 19:18:15 ross Exp $");
32 static const char rcsid[] =
44 #include <sys/param.h>
49 #define SLOT_EMPTY 0x00 /* slot has never been used */
50 #define SLOT_E5 0x05 /* the real value is 0xe5 */
51 #define SLOT_DELETED 0xe5 /* file in this slot deleted */
53 #define ATTR_NORMAL 0x00 /* normal file */
54 #define ATTR_READONLY 0x01 /* file is readonly */
55 #define ATTR_HIDDEN 0x02 /* file is hidden */
56 #define ATTR_SYSTEM 0x04 /* file is a system file */
57 #define ATTR_VOLUME 0x08 /* entry is a volume label */
58 #define ATTR_DIRECTORY 0x10 /* entry is a directory name */
59 #define ATTR_ARCHIVE 0x20 /* file is new or modified */
61 #define ATTR_WIN95 0x0f /* long name record */
64 * This is the format of the contents of the deTime field in the direntry
66 * We don't use bitfields because we don't know how compilers for
67 * arbitrary machines will lay them out.
69 #define DT_2SECONDS_MASK 0x1F /* seconds divided by 2 */
70 #define DT_2SECONDS_SHIFT 0
71 #define DT_MINUTES_MASK 0x7E0 /* minutes */
72 #define DT_MINUTES_SHIFT 5
73 #define DT_HOURS_MASK 0xF800 /* hours */
74 #define DT_HOURS_SHIFT 11
77 * This is the format of the contents of the deDate field in the direntry
80 #define DD_DAY_MASK 0x1F /* day of month */
81 #define DD_DAY_SHIFT 0
82 #define DD_MONTH_MASK 0x1E0 /* month */
83 #define DD_MONTH_SHIFT 5
84 #define DD_YEAR_MASK 0xFE00 /* year - 1980 */
85 #define DD_YEAR_SHIFT 9
89 static struct dosDirEntry *newDosDirEntry(void);
90 static void freeDosDirEntry(struct dosDirEntry *);
91 static struct dirTodoNode *newDirTodo(void);
92 static void freeDirTodo(struct dirTodoNode *);
93 static char *fullpath(struct dosDirEntry *);
94 static u_char calcShortSum(u_char *);
95 static int delete(int, struct bootblock *, struct fatEntry *, cl_t, int,
97 static int removede(int, struct bootblock *, struct fatEntry *, u_char *,
98 u_char *, cl_t, cl_t, cl_t, char *, int);
99 static int checksize(struct bootblock *, struct fatEntry *, u_char *,
100 struct dosDirEntry *);
101 static int readDosDirSection(int, struct bootblock *, struct fatEntry *,
102 struct dosDirEntry *);
105 * Manage free dosDirEntry structures.
107 static struct dosDirEntry *freede;
109 static struct dosDirEntry *
112 struct dosDirEntry *de;
114 if (!(de = freede)) {
115 if (!(de = (struct dosDirEntry *)malloc(sizeof *de)))
123 freeDosDirEntry(struct dosDirEntry *de)
130 * The same for dirTodoNode structures.
132 static struct dirTodoNode *freedt;
134 static struct dirTodoNode *
137 struct dirTodoNode *dt;
139 if (!(dt = freedt)) {
140 if (!(dt = (struct dirTodoNode *)malloc(sizeof *dt)))
148 freeDirTodo(struct dirTodoNode *dt)
155 * The stack of unread directories
157 struct dirTodoNode *pendingDirectories = NULL;
160 * Return the full pathname for a directory entry.
163 fullpath(struct dosDirEntry *dir)
165 static char namebuf[MAXPATHLEN + 1];
169 cp = namebuf + sizeof namebuf - 1;
172 np = dir->lname[0] ? dir->lname : dir->name;
174 if ((cp -= nl) <= namebuf + 1)
178 } while ((dir = dir->parent) != NULL);
187 * Calculate a checksum over an 8.3 alias name
190 calcShortSum(u_char *p)
195 for (i = 0; i < 11; i++) {
196 sum = (sum << 7)|(sum >> 1); /* rotate right */
204 * Global variables temporarily used during a directory scan
206 static char longName[DOSLONGNAMELEN] = "";
207 static u_char *buffer = NULL;
208 static u_char *delbuf = NULL;
210 struct dosDirEntry *rootDir;
211 static struct dosDirEntry *lostDir;
214 * Init internal state for a new directory scan.
217 resetDosDirSection(struct bootblock *boot, struct fatEntry *fat)
223 b1 = boot->RootDirEnts * 32;
224 b2 = boot->SecPerClust * boot->BytesPerSec;
226 if (!(buffer = malloc(b1 > b2 ? b1 : b2))
227 || !(delbuf = malloc(b2))
228 || !(rootDir = newDosDirEntry())) {
229 perror("No space for directory");
232 memset(rootDir, 0, sizeof *rootDir);
233 if (boot->flags & FAT32) {
234 if (boot->RootCl < CLUST_FIRST || boot->RootCl >= boot->NumClusters) {
235 pfatal("Root directory starts with cluster out of range(%u)",
239 cl = fat[boot->RootCl].next;
241 || (cl >= CLUST_RSRVD && cl< CLUST_EOFS)
242 || fat[boot->RootCl].head != boot->RootCl) {
243 if (cl == CLUST_FREE)
244 pwarn("Root directory starts with free cluster\n");
245 else if (cl >= CLUST_RSRVD)
246 pwarn("Root directory starts with cluster marked %s\n",
249 pfatal("Root directory doesn't start a cluster chain");
253 fat[boot->RootCl].next = CLUST_FREE;
259 fat[boot->RootCl].flags |= FAT_USED;
260 rootDir->head = boot->RootCl;
267 * Cleanup after a directory scan
270 finishDosDirSection(void)
272 struct dirTodoNode *p, *np;
273 struct dosDirEntry *d, *nd;
275 for (p = pendingDirectories; p; p = np) {
279 pendingDirectories = 0;
280 for (d = rootDir; d; d = nd) {
281 if ((nd = d->child) != NULL) {
289 rootDir = lostDir = NULL;
297 * Delete directory entries between startcl, startoff and endcl, endoff.
300 delete(int f, struct bootblock *boot, struct fatEntry *fat, cl_t startcl,
301 int startoff, cl_t endcl, int endoff, int notlast)
305 int clsz = boot->SecPerClust * boot->BytesPerSec;
307 s = delbuf + startoff;
309 while (startcl >= CLUST_FIRST && startcl < boot->NumClusters) {
310 if (startcl == endcl) {
315 off = startcl * boot->SecPerClust + boot->ClusterOffset;
316 off *= boot->BytesPerSec;
317 if (lseek(f, off, SEEK_SET) != off
318 || read(f, delbuf, clsz) != clsz) {
319 perror("Unable to read directory");
326 if (lseek(f, off, SEEK_SET) != off
327 || write(f, delbuf, clsz) != clsz) {
328 perror("Unable to write directory");
331 if (startcl == endcl)
333 startcl = fat[startcl].next;
340 removede(int f, struct bootblock *boot, struct fatEntry *fat, u_char *start,
341 u_char *end, cl_t startcl, cl_t endcl, cl_t curcl, char *path, int type)
345 pwarn("Invalid long filename entry for %s\n", path);
348 pwarn("Invalid long filename entry at end of directory %s\n", path);
351 pwarn("Invalid long filename entry for volume label\n");
354 if (ask(0, "Remove")) {
355 if (startcl != curcl) {
356 if (delete(f, boot, fat,
357 startcl, start - buffer,
359 endcl == curcl) == FSFATAL)
364 for (; start < end; start += 32)
365 *start = SLOT_DELETED;
372 * Check an in-memory file entry
375 checksize(struct bootblock *boot, struct fatEntry *fat, u_char *p,
376 struct dosDirEntry *dir)
379 * Check size on ordinary files
381 int32_t physicalSize;
383 if (dir->head == CLUST_FREE)
386 if (dir->head < CLUST_FIRST || dir->head >= boot->NumClusters)
388 physicalSize = fat[dir->head].length * boot->ClusterSize;
390 if (physicalSize < dir->size) {
391 pwarn("size of %s is %u, should at most be %u\n",
392 fullpath(dir), dir->size, physicalSize);
393 if (ask(1, "Truncate")) {
394 dir->size = physicalSize;
395 p[28] = (u_char)physicalSize;
396 p[29] = (u_char)(physicalSize >> 8);
397 p[30] = (u_char)(physicalSize >> 16);
398 p[31] = (u_char)(physicalSize >> 24);
402 } else if (physicalSize - dir->size >= boot->ClusterSize) {
403 pwarn("%s has too many clusters allocated\n",
405 if (ask(1, "Drop superfluous clusters")) {
409 for (cl = dir->head; (sz += boot->ClusterSize) < dir->size;)
411 clearchain(boot, fat, fat[cl].next);
412 fat[cl].next = CLUST_EOF;
421 * Read a directory and
422 * - resolve long name records
423 * - enter file and directory records into the parent's list
424 * - push directories onto the todo-stack
427 readDosDirSection(int f, struct bootblock *boot, struct fatEntry *fat,
428 struct dosDirEntry *dir)
430 struct dosDirEntry dirent, *d;
431 u_char *p, *vallfn, *invlfn, *empty;
434 cl_t cl, valcl = ~0, invcl = ~0, empcl = ~0;
439 #define THISMOD 0x8000 /* Only used within this routine */
442 if (dir->parent && (cl < CLUST_FIRST || cl >= boot->NumClusters)) {
444 * Already handled somewhere else.
449 vallfn = invlfn = empty = NULL;
451 if (!(boot->flags & FAT32) && !dir->parent) {
452 last = boot->RootDirEnts * 32;
453 off = boot->ResSectors + boot->FATs * boot->FATsecs;
455 last = boot->SecPerClust * boot->BytesPerSec;
456 off = cl * boot->SecPerClust + boot->ClusterOffset;
459 off *= boot->BytesPerSec;
460 if (lseek(f, off, SEEK_SET) != off
461 || read(f, buffer, last) != last) {
462 perror("Unable to read directory");
467 * Check `.' and `..' entries here? XXX
469 for (p = buffer, i = 0; i < last; i++, p += 32) {
470 if (dir->fsckflags & DIREMPWARN) {
475 if (*p == SLOT_EMPTY || *p == SLOT_DELETED) {
476 if (*p == SLOT_EMPTY) {
477 dir->fsckflags |= DIREMPTY;
484 if (dir->fsckflags & DIREMPTY) {
485 if (!(dir->fsckflags & DIREMPWARN)) {
486 pwarn("%s has entries after end of directory\n",
488 if (ask(1, "Extend")) {
491 dir->fsckflags &= ~DIREMPTY;
492 if (delete(f, boot, fat,
493 empcl, empty - buffer,
494 cl, p - buffer, 1) == FSFATAL)
496 q = empcl == cl ? empty : buffer;
497 for (; q < p; q += 32)
499 mod |= THISMOD|FSDIRMOD;
500 } else if (ask(0, "Truncate"))
501 dir->fsckflags |= DIREMPWARN;
503 if (dir->fsckflags & DIREMPWARN) {
505 mod |= THISMOD|FSDIRMOD;
507 } else if (dir->fsckflags & DIREMPTY)
512 if (p[11] == ATTR_WIN95) {
514 if (shortSum != -1) {
520 memset(longName, 0, sizeof longName);
524 } else if (shortSum != p[13]
525 || lidx != (*p & LRNOMASK)) {
536 lidx = *p & LRNOMASK;
537 t = longName + --lidx * 13;
538 for (k = 1; k < 11 && t < longName + sizeof(longName); k += 2) {
539 if (!p[k] && !p[k + 1])
543 * Warn about those unusable chars in msdosfs here? XXX
549 for (k = 14; k < 26 && t < longName + sizeof(longName); k += 2) {
550 if (!p[k] && !p[k + 1])
557 for (k = 28; k < 32 && t < longName + sizeof(longName); k += 2) {
558 if (!p[k] && !p[k + 1])
564 if (t >= longName + sizeof(longName)) {
565 pwarn("long filename too long\n");
572 if (p[26] | (p[27] << 8)) {
573 pwarn("long filename record cluster start != 0\n");
580 continue; /* long records don't carry further
585 * This is a standard msdosfs directory entry.
587 memset(&dirent, 0, sizeof dirent);
590 * it's a short name record, but we need to know
591 * more, so get the flags first.
593 dirent.flags = p[11];
596 * Translate from 850 to ISO here XXX
598 for (j = 0; j < 8; j++)
599 dirent.name[j] = p[j];
600 dirent.name[8] = '\0';
601 for (k = 7; k >= 0 && dirent.name[k] == ' '; k--)
602 dirent.name[k] = '\0';
603 if (dirent.name[k] != '\0')
605 if (dirent.name[0] == SLOT_E5)
606 dirent.name[0] = 0xe5;
608 if (dirent.flags & ATTR_VOLUME) {
609 if (vallfn || invlfn) {
610 mod |= removede(f, boot, fat,
611 invlfn ? invlfn : vallfn, p,
612 invlfn ? invcl : valcl, -1, 0,
621 dirent.name[k++] = '.';
622 for (j = 0; j < 3; j++)
623 dirent.name[k++] = p[j+8];
624 dirent.name[k] = '\0';
625 for (k--; k >= 0 && dirent.name[k] == ' '; k--)
626 dirent.name[k] = '\0';
628 if (vallfn && shortSum != calcShortSum(p)) {
635 dirent.head = p[26] | (p[27] << 8);
636 if (boot->ClustMask == CLUST32_MASK)
637 dirent.head |= (p[20] << 16) | (p[21] << 24);
638 dirent.size = p[28] | (p[29] << 8) | (p[30] << 16) | (p[31] << 24);
640 strcpy(dirent.lname, longName);
646 dirent.next = dir->child;
649 mod |= k = removede(f, boot, fat,
650 invlfn, vallfn ? vallfn : p,
651 invcl, vallfn ? valcl : cl, cl,
652 fullpath(&dirent), 0);
656 ? (valcl == cl && vallfn != buffer)
662 vallfn = NULL; /* not used any longer */
665 if (dirent.size == 0 && !(dirent.flags & ATTR_DIRECTORY)) {
666 if (dirent.head != 0) {
667 pwarn("%s has clusters, but size 0\n",
669 if (ask(1, "Drop allocated clusters")) {
671 if (boot->ClustMask == CLUST32_MASK)
673 clearchain(boot, fat, dirent.head);
675 mod |= THISMOD|FSDIRMOD|FSFATMOD;
679 } else if (dirent.head == 0
680 && !strcmp(dirent.name, "..")
681 && dir->parent /* XXX */
682 && !dir->parent->parent) {
684 * Do nothing, the parent is the root
686 } else if (dirent.head < CLUST_FIRST
687 || dirent.head >= boot->NumClusters
688 || fat[dirent.head].next == CLUST_FREE
689 || (fat[dirent.head].next >= CLUST_RSRVD
690 && fat[dirent.head].next < CLUST_EOFS)
691 || fat[dirent.head].head != dirent.head) {
692 if (dirent.head == 0)
693 pwarn("%s has no clusters\n",
695 else if (dirent.head < CLUST_FIRST
696 || dirent.head >= boot->NumClusters)
697 pwarn("%s starts with cluster out of range(%u)\n",
700 else if (fat[dirent.head].next == CLUST_FREE)
701 pwarn("%s starts with free cluster\n",
703 else if (fat[dirent.head].next >= CLUST_RSRVD)
704 pwarn("%s starts with cluster marked %s\n",
706 rsrvdcltype(fat[dirent.head].next));
708 pwarn("%s doesn't start a cluster chain\n",
710 if (dirent.flags & ATTR_DIRECTORY) {
711 if (ask(0, "Remove")) {
713 mod |= THISMOD|FSDIRMOD;
718 if (ask(1, "Truncate")) {
719 p[28] = p[29] = p[30] = p[31] = 0;
721 if (boot->ClustMask == CLUST32_MASK)
724 mod |= THISMOD|FSDIRMOD;
730 if (dirent.head >= CLUST_FIRST && dirent.head < boot->NumClusters)
731 fat[dirent.head].flags |= FAT_USED;
733 if (dirent.flags & ATTR_DIRECTORY) {
735 * gather more info for directories
737 struct dirTodoNode *n;
740 pwarn("Directory %s has size != 0\n",
742 if (ask(1, "Correct")) {
743 p[28] = p[29] = p[30] = p[31] = 0;
745 mod |= THISMOD|FSDIRMOD;
750 * handle `.' and `..' specially
752 if (strcmp(dirent.name, ".") == 0) {
753 if (dirent.head != dir->head) {
754 pwarn("`.' entry in %s has incorrect start cluster\n",
756 if (ask(1, "Correct")) {
757 dirent.head = dir->head;
758 p[26] = (u_char)dirent.head;
759 p[27] = (u_char)(dirent.head >> 8);
760 if (boot->ClustMask == CLUST32_MASK) {
761 p[20] = (u_char)(dirent.head >> 16);
762 p[21] = (u_char)(dirent.head >> 24);
764 mod |= THISMOD|FSDIRMOD;
770 if (strcmp(dirent.name, "..") == 0) {
771 if (dir->parent) { /* XXX */
772 if (!dir->parent->parent) {
774 pwarn("`..' entry in %s has non-zero start cluster\n",
776 if (ask(1, "Correct")) {
779 if (boot->ClustMask == CLUST32_MASK)
781 mod |= THISMOD|FSDIRMOD;
785 } else if (dirent.head != dir->parent->head) {
786 pwarn("`..' entry in %s has incorrect start cluster\n",
788 if (ask(1, "Correct")) {
789 dirent.head = dir->parent->head;
790 p[26] = (u_char)dirent.head;
791 p[27] = (u_char)(dirent.head >> 8);
792 if (boot->ClustMask == CLUST32_MASK) {
793 p[20] = (u_char)(dirent.head >> 16);
794 p[21] = (u_char)(dirent.head >> 24);
796 mod |= THISMOD|FSDIRMOD;
804 /* create directory tree node */
805 if (!(d = newDosDirEntry())) {
806 perror("No space for directory");
809 memcpy(d, &dirent, sizeof(struct dosDirEntry));
810 /* link it into the tree */
813 /* Enter this directory into the todo list */
814 if (!(n = newDirTodo())) {
815 perror("No space for todo list");
818 n->next = pendingDirectories;
820 pendingDirectories = n;
822 mod |= k = checksize(boot, fat, p, &dirent);
830 if (lseek(f, off, SEEK_SET) != off
831 || write(f, buffer, last) != last) {
832 perror("Unable to write directory");
837 } while ((cl = fat[cl].next) >= CLUST_FIRST && cl < boot->NumClusters);
838 if (invlfn || vallfn)
839 mod |= removede(f, boot, fat,
840 invlfn ? invlfn : vallfn, p,
841 invlfn ? invcl : valcl, -1, 0,
843 return mod & ~THISMOD;
847 handleDirTree(int dosfs, struct bootblock *boot, struct fatEntry *fat)
851 mod = readDosDirSection(dosfs, boot, fat, rootDir);
856 * process the directory todo list
858 while (pendingDirectories) {
859 struct dosDirEntry *dir = pendingDirectories->dir;
860 struct dirTodoNode *n = pendingDirectories->next;
863 * remove TODO entry now, the list might change during
866 freeDirTodo(pendingDirectories);
867 pendingDirectories = n;
870 * handle subdirectory
872 mod |= readDosDirSection(dosfs, boot, fat, dir);
881 * Try to reconnect a FAT chain into dir
883 static u_char *lfbuf;
888 reconnect(int dosfs, struct bootblock *boot, struct fatEntry *fat, cl_t head)
890 struct dosDirEntry d;
893 if (!ask(1, "Reconnect"))
897 for (lostDir = rootDir->child; lostDir; lostDir = lostDir->next) {
898 if (!strcmp(lostDir->name, LOSTDIR))
901 if (!lostDir) { /* Create LOSTDIR? XXX */
902 pwarn("No %s directory\n", LOSTDIR);
907 lfbuf = malloc(boot->ClusterSize);
909 perror("No space for buffer");
917 for (; p < lfbuf + boot->ClusterSize; p += 32)
919 || *p == SLOT_DELETED)
921 if (p && p < lfbuf + boot->ClusterSize)
923 lfcl = p ? fat[lfcl].next : lostDir->head;
924 if (lfcl < CLUST_FIRST || lfcl >= boot->NumClusters) {
925 /* Extend LOSTDIR? XXX */
926 pwarn("No space in %s\n", LOSTDIR);
929 lfoff = lfcl * boot->ClusterSize
930 + boot->ClusterOffset * boot->BytesPerSec;
931 if (lseek(dosfs, lfoff, SEEK_SET) != lfoff
932 || read(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) {
933 perror("could not read LOST.DIR");
940 /* Ensure uniqueness of entry here! XXX */
941 memset(&d, 0, sizeof d);
942 (void)snprintf(d.name, sizeof(d.name), "%u", head);
945 d.size = fat[head].length * boot->ClusterSize;
949 memcpy(p, d.name, strlen(d.name));
950 p[26] = (u_char)d.head;
951 p[27] = (u_char)(d.head >> 8);
952 if (boot->ClustMask == CLUST32_MASK) {
953 p[20] = (u_char)(d.head >> 16);
954 p[21] = (u_char)(d.head >> 24);
956 p[28] = (u_char)d.size;
957 p[29] = (u_char)(d.size >> 8);
958 p[30] = (u_char)(d.size >> 16);
959 p[31] = (u_char)(d.size >> 24);
960 fat[head].flags |= FAT_USED;
961 if (lseek(dosfs, lfoff, SEEK_SET) != lfoff
962 || write(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) {
963 perror("could not write LOST.DIR");