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