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