sbin/fsck_msdosfs: Bring in freebsd/freebsd@ce3384ad (bsdl changes from NetBSD)
[dragonfly.git] / sbin / fsck_msdosfs / dir.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
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.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
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.
17  *
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.
28  */
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <ctype.h>
34 #include <unistd.h>
35 #include <time.h>
36
37 #include <sys/param.h>
38
39 #include "ext.h"
40 #include "fsutil.h"
41
42 #define SLOT_EMPTY      0x00            /* slot has never been used */
43 #define SLOT_E5         0x05            /* the real value is 0xe5 */
44 #define SLOT_DELETED    0xe5            /* file in this slot deleted */
45
46 #define ATTR_NORMAL     0x00            /* normal file */
47 #define ATTR_READONLY   0x01            /* file is readonly */
48 #define ATTR_HIDDEN     0x02            /* file is hidden */
49 #define ATTR_SYSTEM     0x04            /* file is a system file */
50 #define ATTR_VOLUME     0x08            /* entry is a volume label */
51 #define ATTR_DIRECTORY  0x10            /* entry is a directory name */
52 #define ATTR_ARCHIVE    0x20            /* file is new or modified */
53
54 #define ATTR_WIN95      0x0f            /* long name record */
55
56 /*
57  * This is the format of the contents of the deTime field in the direntry
58  * structure.
59  * We don't use bitfields because we don't know how compilers for
60  * arbitrary machines will lay them out.
61  */
62 #define DT_2SECONDS_MASK        0x1F    /* seconds divided by 2 */
63 #define DT_2SECONDS_SHIFT       0
64 #define DT_MINUTES_MASK         0x7E0   /* minutes */
65 #define DT_MINUTES_SHIFT        5
66 #define DT_HOURS_MASK           0xF800  /* hours */
67 #define DT_HOURS_SHIFT          11
68
69 /*
70  * This is the format of the contents of the deDate field in the direntry
71  * structure.
72  */
73 #define DD_DAY_MASK             0x1F    /* day of month */
74 #define DD_DAY_SHIFT            0
75 #define DD_MONTH_MASK           0x1E0   /* month */
76 #define DD_MONTH_SHIFT          5
77 #define DD_YEAR_MASK            0xFE00  /* year - 1980 */
78 #define DD_YEAR_SHIFT           9
79
80
81 /* dir.c */
82 static struct dosDirEntry *newDosDirEntry(void);
83 static void freeDosDirEntry(struct dosDirEntry *);
84 static struct dirTodoNode *newDirTodo(void);
85 static void freeDirTodo(struct dirTodoNode *);
86 static char *fullpath(struct dosDirEntry *);
87 static u_char calcShortSum(u_char *);
88 static int delete(int, struct bootblock *, struct fatEntry *, cl_t, int,
89     cl_t, int, int);
90 static int removede(int, struct bootblock *, struct fatEntry *, u_char *,
91     u_char *, cl_t, cl_t, cl_t, char *, int);
92 static int checksize(struct bootblock *, struct fatEntry *, u_char *,
93     struct dosDirEntry *);
94 static int readDosDirSection(int, struct bootblock *, struct fatEntry *,
95     struct dosDirEntry *);
96
97 /*
98  * Manage free dosDirEntry structures.
99  */
100 static struct dosDirEntry *freede;
101
102 static struct dosDirEntry *
103 newDosDirEntry(void)
104 {
105         struct dosDirEntry *de;
106
107         if (!(de = freede)) {
108                 if (!(de = malloc(sizeof(*de))))
109                         return 0;
110         } else
111                 freede = de->next;
112         return de;
113 }
114
115 static void
116 freeDosDirEntry(struct dosDirEntry *de)
117 {
118         de->next = freede;
119         freede = de;
120 }
121
122 /*
123  * The same for dirTodoNode structures.
124  */
125 static struct dirTodoNode *freedt;
126
127 static struct dirTodoNode *
128 newDirTodo(void)
129 {
130         struct dirTodoNode *dt;
131
132         if (!(dt = freedt)) {
133                 if (!(dt = malloc(sizeof(*dt))))
134                         return 0;
135         } else
136                 freedt = dt->next;
137         return dt;
138 }
139
140 static void
141 freeDirTodo(struct dirTodoNode *dt)
142 {
143         dt->next = freedt;
144         freedt = dt;
145 }
146
147 /*
148  * The stack of unread directories
149  */
150 struct dirTodoNode *pendingDirectories = NULL;
151
152 /*
153  * Return the full pathname for a directory entry.
154  */
155 static char *
156 fullpath(struct dosDirEntry *dir)
157 {
158         static char namebuf[MAXPATHLEN + 1];
159         char *cp, *np;
160         int nl;
161
162         cp = namebuf + sizeof namebuf;
163         *--cp = '\0';
164
165         for(;;) {
166                 np = dir->lname[0] ? dir->lname : dir->name;
167                 nl = strlen(np);
168                 if (cp <= namebuf + 1 + nl) {
169                         *--cp = '?';
170                         break;
171                 }
172                 cp -= nl;
173                 memcpy(cp, np, nl);
174                 dir = dir->parent;
175                 if (!dir)
176                         break;
177                 *--cp = '/';
178         }
179
180         return cp;
181 }
182
183 /*
184  * Calculate a checksum over an 8.3 alias name
185  */
186 static u_char
187 calcShortSum(u_char *p)
188 {
189         u_char sum = 0;
190         int i;
191
192         for (i = 0; i < 11; i++) {
193                 sum = (sum << 7)|(sum >> 1);    /* rotate right */
194                 sum += p[i];
195         }
196
197         return sum;
198 }
199
200 /*
201  * Global variables temporarily used during a directory scan
202  */
203 static char longName[DOSLONGNAMELEN] = "";
204 static u_char *buffer = NULL;
205 static u_char *delbuf = NULL;
206
207 struct dosDirEntry *rootDir;
208 static struct dosDirEntry *lostDir;
209
210 /*
211  * Init internal state for a new directory scan.
212  */
213 int
214 resetDosDirSection(struct bootblock *boot, struct fatEntry *fat)
215 {
216         int b1, b2;
217         cl_t cl;
218         int ret = FSOK;
219
220         b1 = boot->bpbRootDirEnts * 32;
221         b2 = boot->bpbSecPerClust * boot->bpbBytesPerSec;
222
223         if (!(buffer = malloc(b1 > b2 ? b1 : b2))
224             || !(delbuf = malloc(b2))
225             || !(rootDir = newDosDirEntry())) {
226                 perror("No space for directory");
227                 return FSFATAL;
228         }
229         memset(rootDir, 0, sizeof *rootDir);
230         if (boot->flags & FAT32) {
231                 if (boot->bpbRootClust < CLUST_FIRST || boot->bpbRootClust >= boot->NumClusters) {
232                         pfatal("Root directory starts with cluster out of range(%u)",
233                                boot->bpbRootClust);
234                         return FSFATAL;
235                 }
236                 cl = fat[boot->bpbRootClust].next;
237                 if (cl < CLUST_FIRST
238                     || (cl >= CLUST_RSRVD && cl< CLUST_EOFS)
239                     || fat[boot->bpbRootClust].head != boot->bpbRootClust) {
240                         if (cl == CLUST_FREE)
241                                 pwarn("Root directory starts with free cluster\n");
242                         else if (cl >= CLUST_RSRVD)
243                                 pwarn("Root directory starts with cluster marked %s\n",
244                                       rsrvdcltype(cl));
245                         else {
246                                 pfatal("Root directory doesn't start a cluster chain");
247                                 return FSFATAL;
248                         }
249                         if (ask(1, "Fix")) {
250                                 fat[boot->bpbRootClust].next = CLUST_FREE;
251                                 ret = FSFATMOD;
252                         } else
253                                 ret = FSFATAL;
254                 }
255
256                 fat[boot->bpbRootClust].flags |= FAT_USED;
257                 rootDir->head = boot->bpbRootClust;
258         }
259
260         return ret;
261 }
262
263 /*
264  * Cleanup after a directory scan
265  */
266 void
267 finishDosDirSection(void)
268 {
269         struct dirTodoNode *p, *np;
270         struct dosDirEntry *d, *nd;
271
272         for (p = pendingDirectories; p; p = np) {
273                 np = p->next;
274                 freeDirTodo(p);
275         }
276         pendingDirectories = NULL;
277         for (d = rootDir; d; d = nd) {
278                 if ((nd = d->child) != NULL) {
279                         d->child = 0;
280                         continue;
281                 }
282                 if (!(nd = d->next))
283                         nd = d->parent;
284                 freeDosDirEntry(d);
285         }
286         rootDir = lostDir = NULL;
287         free(buffer);
288         free(delbuf);
289         buffer = NULL;
290         delbuf = NULL;
291 }
292
293 /*
294  * Delete directory entries between startcl, startoff and endcl, endoff.
295  */
296 static int
297 delete(int f, struct bootblock *boot, struct fatEntry *fat, cl_t startcl,
298        int startoff, cl_t endcl, int endoff, int notlast)
299 {
300         u_char *s, *e;
301         off_t off;
302         int clsz = boot->bpbSecPerClust * boot->bpbBytesPerSec;
303
304         s = delbuf + startoff;
305         e = delbuf + clsz;
306         while (startcl >= CLUST_FIRST && startcl < boot->NumClusters) {
307                 if (startcl == endcl) {
308                         if (notlast)
309                                 break;
310                         e = delbuf + endoff;
311                 }
312                 off = startcl * boot->bpbSecPerClust + boot->ClusterOffset;
313                 off *= boot->bpbBytesPerSec;
314                 if (lseek(f, off, SEEK_SET) != off
315                     || read(f, delbuf, clsz) != clsz) {
316                         perror("Unable to read directory");
317                         return FSFATAL;
318                 }
319                 while (s < e) {
320                         *s = SLOT_DELETED;
321                         s += 32;
322                 }
323                 if (lseek(f, off, SEEK_SET) != off
324                     || write(f, delbuf, clsz) != clsz) {
325                         perror("Unable to write directory");
326                         return FSFATAL;
327                 }
328                 if (startcl == endcl)
329                         break;
330                 startcl = fat[startcl].next;
331                 s = delbuf;
332         }
333         return FSOK;
334 }
335
336 static int
337 removede(int f, struct bootblock *boot, struct fatEntry *fat, u_char *start,
338          u_char *end, cl_t startcl, cl_t endcl, cl_t curcl, char *path,
339          int type)
340 {
341         switch (type) {
342         case 0:
343                 pwarn("Invalid long filename entry for %s\n", path);
344                 break;
345         case 1:
346                 pwarn("Invalid long filename entry at end of directory %s\n", path);
347                 break;
348         case 2:
349                 pwarn("Invalid long filename entry for volume label\n");
350                 break;
351         }
352         if (ask(0, "Remove")) {
353                 if (startcl != curcl) {
354                         if (delete(f, boot, fat,
355                                    startcl, start - buffer,
356                                    endcl, end - buffer,
357                                    endcl == curcl) == FSFATAL)
358                                 return FSFATAL;
359                         start = buffer;
360                 }
361                 if (endcl == curcl)
362                         for (; start < end; start += 32)
363                                 *start = SLOT_DELETED;
364                 return FSDIRMOD;
365         }
366         return FSERROR;
367 }
368
369 /*
370  * Check an in-memory file entry
371  */
372 static int
373 checksize(struct bootblock *boot, struct fatEntry *fat, u_char *p,
374           struct dosDirEntry *dir)
375 {
376         /*
377          * Check size on ordinary files
378          */
379         int32_t physicalSize;
380
381         if (dir->head == CLUST_FREE)
382                 physicalSize = 0;
383         else {
384                 if (dir->head < CLUST_FIRST || dir->head >= boot->NumClusters)
385                         return FSERROR;
386                 physicalSize = fat[dir->head].length * boot->ClusterSize;
387         }
388         if (physicalSize < dir->size) {
389                 pwarn("size of %s is %u, should at most be %u\n",
390                       fullpath(dir), dir->size, physicalSize);
391                 if (ask(1, "Truncate")) {
392                         dir->size = physicalSize;
393                         p[28] = (u_char)physicalSize;
394                         p[29] = (u_char)(physicalSize >> 8);
395                         p[30] = (u_char)(physicalSize >> 16);
396                         p[31] = (u_char)(physicalSize >> 24);
397                         return FSDIRMOD;
398                 } else
399                         return FSERROR;
400         } else if (physicalSize - dir->size >= boot->ClusterSize) {
401                 pwarn("%s has too many clusters allocated\n",
402                       fullpath(dir));
403                 if (ask(1, "Drop superfluous clusters")) {
404                         cl_t cl;
405                         uint32_t sz = 0;
406
407                         for (cl = dir->head; (sz += boot->ClusterSize) < dir->size;)
408                                 cl = fat[cl].next;
409                         clearchain(boot, fat, fat[cl].next);
410                         fat[cl].next = CLUST_EOF;
411                         return FSFATMOD;
412                 } else
413                         return FSERROR;
414         }
415         return FSOK;
416 }
417
418 /*
419  * Read a directory and
420  *   - resolve long name records
421  *   - enter file and directory records into the parent's list
422  *   - push directories onto the todo-stack
423  */
424 static int
425 readDosDirSection(int f, struct bootblock *boot, struct fatEntry *fat,
426                   struct dosDirEntry *dir)
427 {
428         struct dosDirEntry dirent, *d;
429         u_char *p, *vallfn, *invlfn, *empty;
430         off_t off;
431         int i, j, k, last;
432         cl_t cl, valcl = ~0, invcl = ~0, empcl = ~0;
433         char *t;
434         u_int lidx = 0;
435         int shortSum;
436         int mod = FSOK;
437 #define THISMOD 0x8000                  /* Only used within this routine */
438
439         cl = dir->head;
440         if (dir->parent && (cl < CLUST_FIRST || cl >= boot->NumClusters)) {
441                 /*
442                  * Already handled somewhere else.
443                  */
444                 return FSOK;
445         }
446         shortSum = -1;
447         vallfn = invlfn = empty = NULL;
448         do {
449                 if (!(boot->flags & FAT32) && !dir->parent) {
450                         last = boot->bpbRootDirEnts * 32;
451                         off = boot->bpbResSectors + boot->bpbFATs * boot->FATsecs;
452                 } else {
453                         last = boot->bpbSecPerClust * boot->bpbBytesPerSec;
454                         off = cl * boot->bpbSecPerClust + boot->ClusterOffset;
455                 }
456
457                 off *= boot->bpbBytesPerSec;
458                 if (lseek(f, off, SEEK_SET) != off
459                     || read(f, buffer, last) != last) {
460                         perror("Unable to read directory");
461                         return FSFATAL;
462                 }
463                 last /= 32;
464                 /*
465                  * Check `.' and `..' entries here?                     XXX
466                  */
467                 for (p = buffer, i = 0; i < last; i++, p += 32) {
468                         if (dir->fsckflags & DIREMPWARN) {
469                                 *p = SLOT_EMPTY;
470                                 continue;
471                         }
472
473                         if (*p == SLOT_EMPTY || *p == SLOT_DELETED) {
474                                 if (*p == SLOT_EMPTY) {
475                                         dir->fsckflags |= DIREMPTY;
476                                         empty = p;
477                                         empcl = cl;
478                                 }
479                                 continue;
480                         }
481
482                         if (dir->fsckflags & DIREMPTY) {
483                                 if (!(dir->fsckflags & DIREMPWARN)) {
484                                         pwarn("%s has entries after end of directory\n",
485                                               fullpath(dir));
486                                         if (ask(1, "Extend")) {
487                                                 u_char *q;
488
489                                                 dir->fsckflags &= ~DIREMPTY;
490                                                 if (delete(f, boot, fat,
491                                                            empcl, empty - buffer,
492                                                            cl, p - buffer, 1) == FSFATAL)
493                                                         return FSFATAL;
494                                                 q = empcl == cl ? empty : buffer;
495                                                 for (; q < p; q += 32)
496                                                         *q = SLOT_DELETED;
497                                                 mod |= THISMOD|FSDIRMOD;
498                                         } else if (ask(0, "Truncate"))
499                                                 dir->fsckflags |= DIREMPWARN;
500                                 }
501                                 if (dir->fsckflags & DIREMPWARN) {
502                                         *p = SLOT_DELETED;
503                                         mod |= THISMOD|FSDIRMOD;
504                                         continue;
505                                 } else if (dir->fsckflags & DIREMPTY)
506                                         mod |= FSERROR;
507                                 empty = NULL;
508                         }
509
510                         if (p[11] == ATTR_WIN95) {
511                                 if (*p & LRFIRST) {
512                                         if (shortSum != -1) {
513                                                 if (!invlfn) {
514                                                         invlfn = vallfn;
515                                                         invcl = valcl;
516                                                 }
517                                         }
518                                         memset(longName, 0, sizeof longName);
519                                         shortSum = p[13];
520                                         vallfn = p;
521                                         valcl = cl;
522                                 } else if (shortSum != p[13]
523                                            || lidx != (*p & LRNOMASK)) {
524                                         if (!invlfn) {
525                                                 invlfn = vallfn;
526                                                 invcl = valcl;
527                                         }
528                                         if (!invlfn) {
529                                                 invlfn = p;
530                                                 invcl = cl;
531                                         }
532                                         vallfn = NULL;
533                                 }
534                                 lidx = *p & LRNOMASK;
535                                 if (lidx == 0) {
536                                         pwarn("invalid long name\n");
537                                         if (!invlfn) {
538                                                 invlfn = vallfn;
539                                                 invcl = valcl;
540                                         }
541                                         vallfn = NULL;
542                                         continue;
543                                 }
544                                 t = longName + --lidx * 13;
545                                 for (k = 1; k < 11 && t < longName + sizeof(longName); k += 2) {
546                                         if (!p[k] && !p[k + 1])
547                                                 break;
548                                         *t++ = p[k];
549                                         /*
550                                          * Warn about those unusable chars in msdosfs here?     XXX
551                                          */
552                                         if (p[k + 1])
553                                                 t[-1] = '?';
554                                 }
555                                 if (k >= 11)
556                                         for (k = 14; k < 26 && t < longName + sizeof(longName); k += 2) {
557                                                 if (!p[k] && !p[k + 1])
558                                                         break;
559                                                 *t++ = p[k];
560                                                 if (p[k + 1])
561                                                         t[-1] = '?';
562                                         }
563                                 if (k >= 26)
564                                         for (k = 28; k < 32 && t < longName + sizeof(longName); k += 2) {
565                                                 if (!p[k] && !p[k + 1])
566                                                         break;
567                                                 *t++ = p[k];
568                                                 if (p[k + 1])
569                                                         t[-1] = '?';
570                                         }
571                                 if (t >= longName + sizeof(longName)) {
572                                         pwarn("long filename too long\n");
573                                         if (!invlfn) {
574                                                 invlfn = vallfn;
575                                                 invcl = valcl;
576                                         }
577                                         vallfn = NULL;
578                                 }
579                                 if (p[26] | (p[27] << 8)) {
580                                         pwarn("long filename record cluster start != 0\n");
581                                         if (!invlfn) {
582                                                 invlfn = vallfn;
583                                                 invcl = cl;
584                                         }
585                                         vallfn = NULL;
586                                 }
587                                 continue;       /* long records don't carry further
588                                                  * information */
589                         }
590
591                         /*
592                          * This is a standard msdosfs directory entry.
593                          */
594                         memset(&dirent, 0, sizeof dirent);
595
596                         /*
597                          * it's a short name record, but we need to know
598                          * more, so get the flags first.
599                          */
600                         dirent.flags = p[11];
601
602                         /*
603                          * Translate from 850 to ISO here               XXX
604                          */
605                         for (j = 0; j < 8; j++)
606                                 dirent.name[j] = p[j];
607                         dirent.name[8] = '\0';
608                         for (k = 7; k >= 0 && dirent.name[k] == ' '; k--)
609                                 dirent.name[k] = '\0';
610                         if (dirent.name[k] != '\0')
611                                 k++;
612                         if (dirent.name[0] == SLOT_E5)
613                                 dirent.name[0] = 0xe5;
614
615                         if (dirent.flags & ATTR_VOLUME) {
616                                 if (vallfn || invlfn) {
617                                         mod |= removede(f, boot, fat,
618                                                         invlfn ? invlfn : vallfn, p,
619                                                         invlfn ? invcl : valcl, -1, 0,
620                                                         fullpath(dir), 2);
621                                         vallfn = NULL;
622                                         invlfn = NULL;
623                                 }
624                                 continue;
625                         }
626
627                         if (p[8] != ' ')
628                                 dirent.name[k++] = '.';
629                         for (j = 0; j < 3; j++)
630                                 dirent.name[k++] = p[j+8];
631                         dirent.name[k] = '\0';
632                         for (k--; k >= 0 && dirent.name[k] == ' '; k--)
633                                 dirent.name[k] = '\0';
634
635                         if (vallfn && shortSum != calcShortSum(p)) {
636                                 if (!invlfn) {
637                                         invlfn = vallfn;
638                                         invcl = valcl;
639                                 }
640                                 vallfn = NULL;
641                         }
642                         dirent.head = p[26] | (p[27] << 8);
643                         if (boot->ClustMask == CLUST32_MASK)
644                                 dirent.head |= (p[20] << 16) | (p[21] << 24);
645                         dirent.size = p[28] | (p[29] << 8) | (p[30] << 16) | (p[31] << 24);
646                         if (vallfn) {
647                                 strcpy(dirent.lname, longName);
648                                 longName[0] = '\0';
649                                 shortSum = -1;
650                         }
651
652                         dirent.parent = dir;
653                         dirent.next = dir->child;
654
655                         if (invlfn) {
656                                 mod |= k = removede(f, boot, fat,
657                                                     invlfn, vallfn ? vallfn : p,
658                                                     invcl, vallfn ? valcl : cl, cl,
659                                                     fullpath(&dirent), 0);
660                                 if (mod & FSFATAL)
661                                         return FSFATAL;
662                                 if (vallfn
663                                     ? (valcl == cl && vallfn != buffer)
664                                     : p != buffer)
665                                         if (k & FSDIRMOD)
666                                                 mod |= THISMOD;
667                         }
668
669                         vallfn = NULL; /* not used any longer */
670                         invlfn = NULL;
671
672                         if (dirent.size == 0 && !(dirent.flags & ATTR_DIRECTORY)) {
673                                 if (dirent.head != 0) {
674                                         pwarn("%s has clusters, but size 0\n",
675                                               fullpath(&dirent));
676                                         if (ask(1, "Drop allocated clusters")) {
677                                                 p[26] = p[27] = 0;
678                                                 if (boot->ClustMask == CLUST32_MASK)
679                                                         p[20] = p[21] = 0;
680                                                 clearchain(boot, fat, dirent.head);
681                                                 dirent.head = 0;
682                                                 mod |= THISMOD|FSDIRMOD|FSFATMOD;
683                                         } else
684                                                 mod |= FSERROR;
685                                 }
686                         } else if (dirent.head == 0
687                                    && !strcmp(dirent.name, "..")
688                                    && dir->parent                       /* XXX */
689                                    && !dir->parent->parent) {
690                                 /*
691                                  *  Do nothing, the parent is the root
692                                  */
693                         } else if (dirent.head < CLUST_FIRST
694                                    || dirent.head >= boot->NumClusters
695                                    || fat[dirent.head].next == CLUST_FREE
696                                    || (fat[dirent.head].next >= CLUST_RSRVD
697                                        && fat[dirent.head].next < CLUST_EOFS)
698                                    || fat[dirent.head].head != dirent.head) {
699                                 if (dirent.head == 0)
700                                         pwarn("%s has no clusters\n",
701                                               fullpath(&dirent));
702                                 else if (dirent.head < CLUST_FIRST
703                                          || dirent.head >= boot->NumClusters)
704                                         pwarn("%s starts with cluster out of range(%u)\n",
705                                               fullpath(&dirent),
706                                               dirent.head);
707                                 else if (fat[dirent.head].next == CLUST_FREE)
708                                         pwarn("%s starts with free cluster\n",
709                                               fullpath(&dirent));
710                                 else if (fat[dirent.head].next >= CLUST_RSRVD)
711                                         pwarn("%s starts with cluster marked %s\n",
712                                               fullpath(&dirent),
713                                               rsrvdcltype(fat[dirent.head].next));
714                                 else
715                                         pwarn("%s doesn't start a cluster chain\n",
716                                               fullpath(&dirent));
717                                 if (dirent.flags & ATTR_DIRECTORY) {
718                                         if (ask(0, "Remove")) {
719                                                 *p = SLOT_DELETED;
720                                                 mod |= THISMOD|FSDIRMOD;
721                                         } else
722                                                 mod |= FSERROR;
723                                         continue;
724                                 } else {
725                                         if (ask(1, "Truncate")) {
726                                                 p[28] = p[29] = p[30] = p[31] = 0;
727                                                 p[26] = p[27] = 0;
728                                                 if (boot->ClustMask == CLUST32_MASK)
729                                                         p[20] = p[21] = 0;
730                                                 dirent.size = 0;
731                                                 mod |= THISMOD|FSDIRMOD;
732                                         } else
733                                                 mod |= FSERROR;
734                                 }
735                         }
736
737                         if (dirent.head >= CLUST_FIRST && dirent.head < boot->NumClusters)
738                                 fat[dirent.head].flags |= FAT_USED;
739
740                         if (dirent.flags & ATTR_DIRECTORY) {
741                                 /*
742                                  * gather more info for directories
743                                  */
744                                 struct dirTodoNode *n;
745
746                                 if (dirent.size) {
747                                         pwarn("Directory %s has size != 0\n",
748                                               fullpath(&dirent));
749                                         if (ask(1, "Correct")) {
750                                                 p[28] = p[29] = p[30] = p[31] = 0;
751                                                 dirent.size = 0;
752                                                 mod |= THISMOD|FSDIRMOD;
753                                         } else
754                                                 mod |= FSERROR;
755                                 }
756                                 /*
757                                  * handle `.' and `..' specially
758                                  */
759                                 if (strcmp(dirent.name, ".") == 0) {
760                                         if (dirent.head != dir->head) {
761                                                 pwarn("`.' entry in %s has incorrect start cluster\n",
762                                                       fullpath(dir));
763                                                 if (ask(1, "Correct")) {
764                                                         dirent.head = dir->head;
765                                                         p[26] = (u_char)dirent.head;
766                                                         p[27] = (u_char)(dirent.head >> 8);
767                                                         if (boot->ClustMask == CLUST32_MASK) {
768                                                                 p[20] = (u_char)(dirent.head >> 16);
769                                                                 p[21] = (u_char)(dirent.head >> 24);
770                                                         }
771                                                         mod |= THISMOD|FSDIRMOD;
772                                                 } else
773                                                         mod |= FSERROR;
774                                         }
775                                         continue;
776                                 }
777                                 if (strcmp(dirent.name, "..") == 0) {
778                                         if (dir->parent) {              /* XXX */
779                                                 if (!dir->parent->parent) {
780                                                         if (dirent.head) {
781                                                                 pwarn("`..' entry in %s has non-zero start cluster\n",
782                                                                       fullpath(dir));
783                                                                 if (ask(1, "Correct")) {
784                                                                         dirent.head = 0;
785                                                                         p[26] = p[27] = 0;
786                                                                         if (boot->ClustMask == CLUST32_MASK)
787                                                                                 p[20] = p[21] = 0;
788                                                                         mod |= THISMOD|FSDIRMOD;
789                                                                 } else
790                                                                         mod |= FSERROR;
791                                                         }
792                                                 } else if (dirent.head != dir->parent->head) {
793                                                         pwarn("`..' entry in %s has incorrect start cluster\n",
794                                                               fullpath(dir));
795                                                         if (ask(1, "Correct")) {
796                                                                 dirent.head = dir->parent->head;
797                                                                 p[26] = (u_char)dirent.head;
798                                                                 p[27] = (u_char)(dirent.head >> 8);
799                                                                 if (boot->ClustMask == CLUST32_MASK) {
800                                                                         p[20] = (u_char)(dirent.head >> 16);
801                                                                         p[21] = (u_char)(dirent.head >> 24);
802                                                                 }
803                                                                 mod |= THISMOD|FSDIRMOD;
804                                                         } else
805                                                                 mod |= FSERROR;
806                                                 }
807                                         }
808                                         continue;
809                                 }
810
811                                 /* create directory tree node */
812                                 if (!(d = newDosDirEntry())) {
813                                         perror("No space for directory");
814                                         return FSFATAL;
815                                 }
816                                 memcpy(d, &dirent, sizeof(struct dosDirEntry));
817                                 /* link it into the tree */
818                                 dir->child = d;
819
820                                 /* Enter this directory into the todo list */
821                                 if (!(n = newDirTodo())) {
822                                         perror("No space for todo list");
823                                         return FSFATAL;
824                                 }
825                                 n->next = pendingDirectories;
826                                 n->dir = d;
827                                 pendingDirectories = n;
828                         } else {
829                                 mod |= k = checksize(boot, fat, p, &dirent);
830                                 if (k & FSDIRMOD)
831                                         mod |= THISMOD;
832                         }
833                         boot->NumFiles++;
834                 }
835                 if (mod & THISMOD) {
836                         last *= 32;
837                         if (lseek(f, off, SEEK_SET) != off
838                             || write(f, buffer, last) != last) {
839                                 perror("Unable to write directory");
840                                 return FSFATAL;
841                         }
842                         mod &= ~THISMOD;
843                 }
844         } while ((cl = fat[cl].next) >= CLUST_FIRST && cl < boot->NumClusters);
845         if (invlfn || vallfn)
846                 mod |= removede(f, boot, fat,
847                                 invlfn ? invlfn : vallfn, p,
848                                 invlfn ? invcl : valcl, -1, 0,
849                                 fullpath(dir), 1);
850         return mod & ~THISMOD;
851 }
852
853 int
854 handleDirTree(int dosfs, struct bootblock *boot, struct fatEntry *fat)
855 {
856         int mod;
857
858         mod = readDosDirSection(dosfs, boot, fat, rootDir);
859         if (mod & FSFATAL)
860                 return FSFATAL;
861
862         /*
863          * process the directory todo list
864          */
865         while (pendingDirectories) {
866                 struct dosDirEntry *dir = pendingDirectories->dir;
867                 struct dirTodoNode *n = pendingDirectories->next;
868
869                 /*
870                  * remove TODO entry now, the list might change during
871                  * directory reads
872                  */
873                 freeDirTodo(pendingDirectories);
874                 pendingDirectories = n;
875
876                 /*
877                  * handle subdirectory
878                  */
879                 mod |= readDosDirSection(dosfs, boot, fat, dir);
880                 if (mod & FSFATAL)
881                         return FSFATAL;
882         }
883
884         return mod;
885 }
886
887 /*
888  * Try to reconnect a FAT chain into dir
889  */
890 static u_char *lfbuf;
891 static cl_t lfcl;
892 static off_t lfoff;
893
894 int
895 reconnect(int dosfs, struct bootblock *boot, struct fatEntry *fat, cl_t head)
896 {
897         struct dosDirEntry d;
898         u_char *p;
899
900         if (!ask(1, "Reconnect"))
901                 return FSERROR;
902
903         if (!lostDir) {
904                 for (lostDir = rootDir->child; lostDir; lostDir = lostDir->next) {
905                         if (!strcmp(lostDir->name, LOSTDIR))
906                                 break;
907                 }
908                 if (!lostDir) {         /* Create LOSTDIR?              XXX */
909                         pwarn("No %s directory\n", LOSTDIR);
910                         return FSERROR;
911                 }
912         }
913         if (!lfbuf) {
914                 lfbuf = malloc(boot->ClusterSize);
915                 if (!lfbuf) {
916                         perror("No space for buffer");
917                         return FSFATAL;
918                 }
919                 p = NULL;
920         } else
921                 p = lfbuf;
922         while (1) {
923                 if (p)
924                         for (; p < lfbuf + boot->ClusterSize; p += 32)
925                                 if (*p == SLOT_EMPTY
926                                     || *p == SLOT_DELETED)
927                                         break;
928                 if (p && p < lfbuf + boot->ClusterSize)
929                         break;
930                 lfcl = p ? fat[lfcl].next : lostDir->head;
931                 if (lfcl < CLUST_FIRST || lfcl >= boot->NumClusters) {
932                         /* Extend LOSTDIR?                              XXX */
933                         pwarn("No space in %s\n", LOSTDIR);
934                         return FSERROR;
935                 }
936                 lfoff = lfcl * boot->ClusterSize
937                     + boot->ClusterOffset * boot->bpbBytesPerSec;
938                 if (lseek(dosfs, lfoff, SEEK_SET) != lfoff
939                     || read(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) {
940                         perror("could not read LOST.DIR");
941                         return FSFATAL;
942                 }
943                 p = lfbuf;
944         }
945
946         boot->NumFiles++;
947         /* Ensure uniqueness of entry here!                             XXX */
948         memset(&d, 0, sizeof d);
949         snprintf(d.name, sizeof(d.name), "%u", head);
950         d.flags = 0;
951         d.head = head;
952         d.size = fat[head].length * boot->ClusterSize;
953
954         memset(p, 0, 32);
955         memset(p, ' ', 11);
956         memcpy(p, d.name, strlen(d.name));
957         p[26] = (u_char)d.head;
958         p[27] = (u_char)(d.head >> 8);
959         if (boot->ClustMask == CLUST32_MASK) {
960                 p[20] = (u_char)(d.head >> 16);
961                 p[21] = (u_char)(d.head >> 24);
962         }
963         p[28] = (u_char)d.size;
964         p[29] = (u_char)(d.size >> 8);
965         p[30] = (u_char)(d.size >> 16);
966         p[31] = (u_char)(d.size >> 24);
967         fat[head].flags |= FAT_USED;
968         if (lseek(dosfs, lfoff, SEEK_SET) != lfoff
969             || write(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) {
970                 perror("could not write LOST.DIR");
971                 return FSFATAL;
972         }
973         return FSDIRMOD;
974 }
975
976 void
977 finishlf(void)
978 {
979         if (lfbuf)
980                 free(lfbuf);
981         lfbuf = NULL;
982 }