sbin/fsck_msdosfs: Bring in FreeBSD/Git 9502e5ba (fix fullpath())
[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 = (struct dosDirEntry *)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 = (struct dirTodoNode *)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                                 t = longName + --lidx * 13;
544                                 for (k = 1; k < 11 && t < longName + sizeof(longName); k += 2) {
545                                         if (!p[k] && !p[k + 1])
546                                                 break;
547                                         *t++ = p[k];
548                                         /*
549                                          * Warn about those unusable chars in msdosfs here?     XXX
550                                          */
551                                         if (p[k + 1])
552                                                 t[-1] = '?';
553                                 }
554                                 if (k >= 11)
555                                         for (k = 14; k < 26 && t < longName + sizeof(longName); k += 2) {
556                                                 if (!p[k] && !p[k + 1])
557                                                         break;
558                                                 *t++ = p[k];
559                                                 if (p[k + 1])
560                                                         t[-1] = '?';
561                                         }
562                                 if (k >= 26)
563                                         for (k = 28; k < 32 && t < longName + sizeof(longName); k += 2) {
564                                                 if (!p[k] && !p[k + 1])
565                                                         break;
566                                                 *t++ = p[k];
567                                                 if (p[k + 1])
568                                                         t[-1] = '?';
569                                         }
570                                 if (t >= longName + sizeof(longName)) {
571                                         pwarn("long filename too long\n");
572                                         if (!invlfn) {
573                                                 invlfn = vallfn;
574                                                 invcl = valcl;
575                                         }
576                                         vallfn = NULL;
577                                 }
578                                 if (p[26] | (p[27] << 8)) {
579                                         pwarn("long filename record cluster start != 0\n");
580                                         if (!invlfn) {
581                                                 invlfn = vallfn;
582                                                 invcl = cl;
583                                         }
584                                         vallfn = NULL;
585                                 }
586                                 continue;       /* long records don't carry further
587                                                  * information */
588                         }
589
590                         /*
591                          * This is a standard msdosfs directory entry.
592                          */
593                         memset(&dirent, 0, sizeof dirent);
594
595                         /*
596                          * it's a short name record, but we need to know
597                          * more, so get the flags first.
598                          */
599                         dirent.flags = p[11];
600
601                         /*
602                          * Translate from 850 to ISO here               XXX
603                          */
604                         for (j = 0; j < 8; j++)
605                                 dirent.name[j] = p[j];
606                         dirent.name[8] = '\0';
607                         for (k = 7; k >= 0 && dirent.name[k] == ' '; k--)
608                                 dirent.name[k] = '\0';
609                         if (dirent.name[k] != '\0')
610                                 k++;
611                         if (dirent.name[0] == SLOT_E5)
612                                 dirent.name[0] = 0xe5;
613
614                         if (dirent.flags & ATTR_VOLUME) {
615                                 if (vallfn || invlfn) {
616                                         mod |= removede(f, boot, fat,
617                                                         invlfn ? invlfn : vallfn, p,
618                                                         invlfn ? invcl : valcl, -1, 0,
619                                                         fullpath(dir), 2);
620                                         vallfn = NULL;
621                                         invlfn = NULL;
622                                 }
623                                 continue;
624                         }
625
626                         if (p[8] != ' ')
627                                 dirent.name[k++] = '.';
628                         for (j = 0; j < 3; j++)
629                                 dirent.name[k++] = p[j+8];
630                         dirent.name[k] = '\0';
631                         for (k--; k >= 0 && dirent.name[k] == ' '; k--)
632                                 dirent.name[k] = '\0';
633
634                         if (vallfn && shortSum != calcShortSum(p)) {
635                                 if (!invlfn) {
636                                         invlfn = vallfn;
637                                         invcl = valcl;
638                                 }
639                                 vallfn = NULL;
640                         }
641                         dirent.head = p[26] | (p[27] << 8);
642                         if (boot->ClustMask == CLUST32_MASK)
643                                 dirent.head |= (p[20] << 16) | (p[21] << 24);
644                         dirent.size = p[28] | (p[29] << 8) | (p[30] << 16) | (p[31] << 24);
645                         if (vallfn) {
646                                 strcpy(dirent.lname, longName);
647                                 longName[0] = '\0';
648                                 shortSum = -1;
649                         }
650
651                         dirent.parent = dir;
652                         dirent.next = dir->child;
653
654                         if (invlfn) {
655                                 mod |= k = removede(f, boot, fat,
656                                                     invlfn, vallfn ? vallfn : p,
657                                                     invcl, vallfn ? valcl : cl, cl,
658                                                     fullpath(&dirent), 0);
659                                 if (mod & FSFATAL)
660                                         return FSFATAL;
661                                 if (vallfn
662                                     ? (valcl == cl && vallfn != buffer)
663                                     : p != buffer)
664                                         if (k & FSDIRMOD)
665                                                 mod |= THISMOD;
666                         }
667
668                         vallfn = NULL; /* not used any longer */
669                         invlfn = NULL;
670
671                         if (dirent.size == 0 && !(dirent.flags & ATTR_DIRECTORY)) {
672                                 if (dirent.head != 0) {
673                                         pwarn("%s has clusters, but size 0\n",
674                                               fullpath(&dirent));
675                                         if (ask(1, "Drop allocated clusters")) {
676                                                 p[26] = p[27] = 0;
677                                                 if (boot->ClustMask == CLUST32_MASK)
678                                                         p[20] = p[21] = 0;
679                                                 clearchain(boot, fat, dirent.head);
680                                                 dirent.head = 0;
681                                                 mod |= THISMOD|FSDIRMOD|FSFATMOD;
682                                         } else
683                                                 mod |= FSERROR;
684                                 }
685                         } else if (dirent.head == 0
686                                    && !strcmp(dirent.name, "..")
687                                    && dir->parent                       /* XXX */
688                                    && !dir->parent->parent) {
689                                 /*
690                                  *  Do nothing, the parent is the root
691                                  */
692                         } else if (dirent.head < CLUST_FIRST
693                                    || dirent.head >= boot->NumClusters
694                                    || fat[dirent.head].next == CLUST_FREE
695                                    || (fat[dirent.head].next >= CLUST_RSRVD
696                                        && fat[dirent.head].next < CLUST_EOFS)
697                                    || fat[dirent.head].head != dirent.head) {
698                                 if (dirent.head == 0)
699                                         pwarn("%s has no clusters\n",
700                                               fullpath(&dirent));
701                                 else if (dirent.head < CLUST_FIRST
702                                          || dirent.head >= boot->NumClusters)
703                                         pwarn("%s starts with cluster out of range(%u)\n",
704                                               fullpath(&dirent),
705                                               dirent.head);
706                                 else if (fat[dirent.head].next == CLUST_FREE)
707                                         pwarn("%s starts with free cluster\n",
708                                               fullpath(&dirent));
709                                 else if (fat[dirent.head].next >= CLUST_RSRVD)
710                                         pwarn("%s starts with cluster marked %s\n",
711                                               fullpath(&dirent),
712                                               rsrvdcltype(fat[dirent.head].next));
713                                 else
714                                         pwarn("%s doesn't start a cluster chain\n",
715                                               fullpath(&dirent));
716                                 if (dirent.flags & ATTR_DIRECTORY) {
717                                         if (ask(0, "Remove")) {
718                                                 *p = SLOT_DELETED;
719                                                 mod |= THISMOD|FSDIRMOD;
720                                         } else
721                                                 mod |= FSERROR;
722                                         continue;
723                                 } else {
724                                         if (ask(1, "Truncate")) {
725                                                 p[28] = p[29] = p[30] = p[31] = 0;
726                                                 p[26] = p[27] = 0;
727                                                 if (boot->ClustMask == CLUST32_MASK)
728                                                         p[20] = p[21] = 0;
729                                                 dirent.size = 0;
730                                                 mod |= THISMOD|FSDIRMOD;
731                                         } else
732                                                 mod |= FSERROR;
733                                 }
734                         }
735
736                         if (dirent.head >= CLUST_FIRST && dirent.head < boot->NumClusters)
737                                 fat[dirent.head].flags |= FAT_USED;
738
739                         if (dirent.flags & ATTR_DIRECTORY) {
740                                 /*
741                                  * gather more info for directories
742                                  */
743                                 struct dirTodoNode *n;
744
745                                 if (dirent.size) {
746                                         pwarn("Directory %s has size != 0\n",
747                                               fullpath(&dirent));
748                                         if (ask(1, "Correct")) {
749                                                 p[28] = p[29] = p[30] = p[31] = 0;
750                                                 dirent.size = 0;
751                                                 mod |= THISMOD|FSDIRMOD;
752                                         } else
753                                                 mod |= FSERROR;
754                                 }
755                                 /*
756                                  * handle `.' and `..' specially
757                                  */
758                                 if (strcmp(dirent.name, ".") == 0) {
759                                         if (dirent.head != dir->head) {
760                                                 pwarn("`.' entry in %s has incorrect start cluster\n",
761                                                       fullpath(dir));
762                                                 if (ask(1, "Correct")) {
763                                                         dirent.head = dir->head;
764                                                         p[26] = (u_char)dirent.head;
765                                                         p[27] = (u_char)(dirent.head >> 8);
766                                                         if (boot->ClustMask == CLUST32_MASK) {
767                                                                 p[20] = (u_char)(dirent.head >> 16);
768                                                                 p[21] = (u_char)(dirent.head >> 24);
769                                                         }
770                                                         mod |= THISMOD|FSDIRMOD;
771                                                 } else
772                                                         mod |= FSERROR;
773                                         }
774                                         continue;
775                                 }
776                                 if (strcmp(dirent.name, "..") == 0) {
777                                         if (dir->parent) {              /* XXX */
778                                                 if (!dir->parent->parent) {
779                                                         if (dirent.head) {
780                                                                 pwarn("`..' entry in %s has non-zero start cluster\n",
781                                                                       fullpath(dir));
782                                                                 if (ask(1, "Correct")) {
783                                                                         dirent.head = 0;
784                                                                         p[26] = p[27] = 0;
785                                                                         if (boot->ClustMask == CLUST32_MASK)
786                                                                                 p[20] = p[21] = 0;
787                                                                         mod |= THISMOD|FSDIRMOD;
788                                                                 } else
789                                                                         mod |= FSERROR;
790                                                         }
791                                                 } else if (dirent.head != dir->parent->head) {
792                                                         pwarn("`..' entry in %s has incorrect start cluster\n",
793                                                               fullpath(dir));
794                                                         if (ask(1, "Correct")) {
795                                                                 dirent.head = dir->parent->head;
796                                                                 p[26] = (u_char)dirent.head;
797                                                                 p[27] = (u_char)(dirent.head >> 8);
798                                                                 if (boot->ClustMask == CLUST32_MASK) {
799                                                                         p[20] = (u_char)(dirent.head >> 16);
800                                                                         p[21] = (u_char)(dirent.head >> 24);
801                                                                 }
802                                                                 mod |= THISMOD|FSDIRMOD;
803                                                         } else
804                                                                 mod |= FSERROR;
805                                                 }
806                                         }
807                                         continue;
808                                 }
809
810                                 /* create directory tree node */
811                                 if (!(d = newDosDirEntry())) {
812                                         perror("No space for directory");
813                                         return FSFATAL;
814                                 }
815                                 memcpy(d, &dirent, sizeof(struct dosDirEntry));
816                                 /* link it into the tree */
817                                 dir->child = d;
818
819                                 /* Enter this directory into the todo list */
820                                 if (!(n = newDirTodo())) {
821                                         perror("No space for todo list");
822                                         return FSFATAL;
823                                 }
824                                 n->next = pendingDirectories;
825                                 n->dir = d;
826                                 pendingDirectories = n;
827                         } else {
828                                 mod |= k = checksize(boot, fat, p, &dirent);
829                                 if (k & FSDIRMOD)
830                                         mod |= THISMOD;
831                         }
832                         boot->NumFiles++;
833                 }
834                 if (mod & THISMOD) {
835                         last *= 32;
836                         if (lseek(f, off, SEEK_SET) != off
837                             || write(f, buffer, last) != last) {
838                                 perror("Unable to write directory");
839                                 return FSFATAL;
840                         }
841                         mod &= ~THISMOD;
842                 }
843         } while ((cl = fat[cl].next) >= CLUST_FIRST && cl < boot->NumClusters);
844         if (invlfn || vallfn)
845                 mod |= removede(f, boot, fat,
846                                 invlfn ? invlfn : vallfn, p,
847                                 invlfn ? invcl : valcl, -1, 0,
848                                 fullpath(dir), 1);
849         return mod & ~THISMOD;
850 }
851
852 int
853 handleDirTree(int dosfs, struct bootblock *boot, struct fatEntry *fat)
854 {
855         int mod;
856
857         mod = readDosDirSection(dosfs, boot, fat, rootDir);
858         if (mod & FSFATAL)
859                 return FSFATAL;
860
861         /*
862          * process the directory todo list
863          */
864         while (pendingDirectories) {
865                 struct dosDirEntry *dir = pendingDirectories->dir;
866                 struct dirTodoNode *n = pendingDirectories->next;
867
868                 /*
869                  * remove TODO entry now, the list might change during
870                  * directory reads
871                  */
872                 freeDirTodo(pendingDirectories);
873                 pendingDirectories = n;
874
875                 /*
876                  * handle subdirectory
877                  */
878                 mod |= readDosDirSection(dosfs, boot, fat, dir);
879                 if (mod & FSFATAL)
880                         return FSFATAL;
881         }
882
883         return mod;
884 }
885
886 /*
887  * Try to reconnect a FAT chain into dir
888  */
889 static u_char *lfbuf;
890 static cl_t lfcl;
891 static off_t lfoff;
892
893 int
894 reconnect(int dosfs, struct bootblock *boot, struct fatEntry *fat, cl_t head)
895 {
896         struct dosDirEntry d;
897         u_char *p;
898
899         if (!ask(1, "Reconnect"))
900                 return FSERROR;
901
902         if (!lostDir) {
903                 for (lostDir = rootDir->child; lostDir; lostDir = lostDir->next) {
904                         if (!strcmp(lostDir->name, LOSTDIR))
905                                 break;
906                 }
907                 if (!lostDir) {         /* Create LOSTDIR?              XXX */
908                         pwarn("No %s directory\n", LOSTDIR);
909                         return FSERROR;
910                 }
911         }
912         if (!lfbuf) {
913                 lfbuf = malloc(boot->ClusterSize);
914                 if (!lfbuf) {
915                         perror("No space for buffer");
916                         return FSFATAL;
917                 }
918                 p = NULL;
919         } else
920                 p = lfbuf;
921         while (1) {
922                 if (p)
923                         for (; p < lfbuf + boot->ClusterSize; p += 32)
924                                 if (*p == SLOT_EMPTY
925                                     || *p == SLOT_DELETED)
926                                         break;
927                 if (p && p < lfbuf + boot->ClusterSize)
928                         break;
929                 lfcl = p ? fat[lfcl].next : lostDir->head;
930                 if (lfcl < CLUST_FIRST || lfcl >= boot->NumClusters) {
931                         /* Extend LOSTDIR?                              XXX */
932                         pwarn("No space in %s\n", LOSTDIR);
933                         return FSERROR;
934                 }
935                 lfoff = lfcl * boot->ClusterSize
936                     + boot->ClusterOffset * boot->BytesPerSec;
937                 if (lseek(dosfs, lfoff, SEEK_SET) != lfoff
938                     || read(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) {
939                         perror("could not read LOST.DIR");
940                         return FSFATAL;
941                 }
942                 p = lfbuf;
943         }
944
945         boot->NumFiles++;
946         /* Ensure uniqueness of entry here!                             XXX */
947         memset(&d, 0, sizeof d);
948         snprintf(d.name, sizeof(d.name), "%u", head);
949         d.flags = 0;
950         d.head = head;
951         d.size = fat[head].length * boot->ClusterSize;
952
953         memset(p, 0, 32);
954         memset(p, ' ', 11);
955         memcpy(p, d.name, strlen(d.name));
956         p[26] = (u_char)d.head;
957         p[27] = (u_char)(d.head >> 8);
958         if (boot->ClustMask == CLUST32_MASK) {
959                 p[20] = (u_char)(d.head >> 16);
960                 p[21] = (u_char)(d.head >> 24);
961         }
962         p[28] = (u_char)d.size;
963         p[29] = (u_char)(d.size >> 8);
964         p[30] = (u_char)(d.size >> 16);
965         p[31] = (u_char)(d.size >> 24);
966         fat[head].flags |= FAT_USED;
967         if (lseek(dosfs, lfoff, SEEK_SET) != lfoff
968             || write(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) {
969                 perror("could not write LOST.DIR");
970                 return FSFATAL;
971         }
972         return FSDIRMOD;
973 }
974
975 void
976 finishlf(void)
977 {
978         if (lfbuf)
979                 free(lfbuf);
980         lfbuf = NULL;
981 }