aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

dir.c (32651B)


      1 /*-
      2  * SPDX-License-Identifier: BSD-2-Clause
      3  *
      4  * Copyright (c) 2019 Google LLC
      5  * Copyright (C) 1995, 1996, 1997 Wolfgang Solfrank
      6  * Copyright (c) 1995 Martin Husemann
      7  * Some structure declaration borrowed from Paul Popelka
      8  * (paulp@uts.amdahl.com), see /sys/msdosfs/ for reference.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
     20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     22  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
     23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     29  */
     30 
     31 #include "freebsd-compat.h"
     32 #if defined(__RCSID) && !defined(lint)
     33 __RCSID("$NetBSD: dir.c,v 1.20 2006/06/05 16:51:18 christos Exp $");
     34 #endif /* not lint */
     35 
     36 #include <assert.h>
     37 #include <inttypes.h>
     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 #include "util.h"
     50 
     51 #define SLOT_EMPTY   0x00 /* slot has never been used */
     52 #define SLOT_E5      0x05 /* the real value is 0xe5 */
     53 #define SLOT_DELETED 0xe5 /* file in this slot deleted */
     54 
     55 #define ATTR_NORMAL    0x00 /* normal file */
     56 #define ATTR_READONLY  0x01 /* file is readonly */
     57 #define ATTR_HIDDEN    0x02 /* file is hidden */
     58 #define ATTR_SYSTEM    0x04 /* file is a system file */
     59 #define ATTR_VOLUME    0x08 /* entry is a volume label */
     60 #define ATTR_DIRECTORY 0x10 /* entry is a directory name */
     61 #define ATTR_ARCHIVE   0x20 /* file is new or modified */
     62 
     63 #define ATTR_WIN95 0x0f /* long name record */
     64 
     65 /*
     66  * This is the format of the contents of the deTime field in the direntry
     67  * structure.
     68  * We don't use bitfields because we don't know how compilers for
     69  * arbitrary machines will lay them out.
     70  */
     71 #define DT_2SECONDS_MASK  0x1F /* seconds divided by 2 */
     72 #define DT_2SECONDS_SHIFT 0
     73 #define DT_MINUTES_MASK   0x7E0 /* minutes */
     74 #define DT_MINUTES_SHIFT  5
     75 #define DT_HOURS_MASK     0xF800 /* hours */
     76 #define DT_HOURS_SHIFT    11
     77 
     78 /*
     79  * This is the format of the contents of the deDate field in the direntry
     80  * structure.
     81  */
     82 #define DD_DAY_MASK    0x1F /* day of month */
     83 #define DD_DAY_SHIFT   0
     84 #define DD_MONTH_MASK  0x1E0 /* month */
     85 #define DD_MONTH_SHIFT 5
     86 #define DD_YEAR_MASK   0xFE00 /* year - 1980 */
     87 #define DD_YEAR_SHIFT  9
     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 (struct fat_descriptor *, cl_t, int, cl_t, int, int);
     97 static int removede(struct fat_descriptor *, u_char *, u_char *, cl_t, cl_t, cl_t, char *, int);
     98 static int checksize(struct fat_descriptor *, u_char *, struct dosDirEntry *);
     99 static int readDosDirSection(struct fat_descriptor *, struct dosDirEntry *);
    100 
    101 /*
    102  * Manage free dosDirEntry structures.
    103  */
    104 static struct dosDirEntry *freede;
    105 
    106 static struct dosDirEntry *
    107 newDosDirEntry(void)
    108 {
    109   struct dosDirEntry *de;
    110 
    111   if (!(de = freede)) {
    112     if (!(de = malloc(sizeof *de)))
    113       return (NULL);
    114   } else
    115     freede = de->next;
    116   return de;
    117 }
    118 
    119 static void
    120 freeDosDirEntry(struct dosDirEntry *de)
    121 {
    122   de->next = freede;
    123   freede   = de;
    124 }
    125 
    126 /*
    127  * The same for dirTodoNode structures.
    128  */
    129 static struct dirTodoNode *freedt;
    130 
    131 static struct dirTodoNode *
    132 newDirTodo(void)
    133 {
    134   struct dirTodoNode *dt;
    135 
    136   if (!(dt = freedt)) {
    137     if (!(dt = malloc(sizeof *dt)))
    138       return 0;
    139   } else
    140     freedt = dt->next;
    141   return dt;
    142 }
    143 
    144 static void
    145 freeDirTodo(struct dirTodoNode *dt)
    146 {
    147   dt->next = freedt;
    148   freedt   = dt;
    149 }
    150 
    151 /*
    152  * The stack of unread directories
    153  */
    154 static struct dirTodoNode *pendingDirectories = NULL;
    155 
    156 /*
    157  * Return the full pathname for a directory entry.
    158  */
    159 static char *
    160 fullpath(struct dosDirEntry *dir)
    161 {
    162   static char namebuf[MAXPATHLEN + 1];
    163   char       *cp, *np;
    164   int         nl;
    165 
    166   cp    = namebuf + sizeof namebuf;
    167   *--cp = '\0';
    168 
    169   for (;;) {
    170     np = dir->lname[0] ? dir->lname : dir->name;
    171     nl = strlen(np);
    172     if (cp <= namebuf + 1 + nl) {
    173       *--cp = '?';
    174       break;
    175     }
    176     cp -= nl;
    177     memcpy(cp, np, nl);
    178     dir = dir->parent;
    179     if (!dir)
    180       break;
    181     *--cp = '/';
    182   }
    183 
    184   return cp;
    185 }
    186 
    187 /*
    188  * Calculate a checksum over an 8.3 alias name
    189  */
    190 static inline u_char
    191 calcShortSum(u_char *p)
    192 {
    193   u_char sum = 0;
    194   int    i;
    195 
    196   for (i = 0; i < 11; i++) {
    197     sum = (sum << 7) | (sum >> 1); /* rotate right */
    198     sum += p[i];
    199   }
    200 
    201   return sum;
    202 }
    203 
    204 /*
    205  * Global variables temporarily used during a directory scan
    206  */
    207 static char    longName[DOSLONGNAMELEN] = "";
    208 static u_char *buffer                   = NULL;
    209 static u_char *delbuf                   = NULL;
    210 
    211 static struct dosDirEntry *rootDir;
    212 static struct dosDirEntry *lostDir;
    213 
    214 /*
    215  * Init internal state for a new directory scan.
    216  */
    217 int
    218 resetDosDirSection(struct fat_descriptor *fat)
    219 {
    220   int               rootdir_size, cluster_size;
    221   int               ret = FSOK;
    222   size_t            len;
    223   struct bootblock *boot;
    224 
    225   boot = fat_get_boot(fat);
    226 
    227   rootdir_size = boot->bpbRootDirEnts * 32;
    228   cluster_size = boot->bpbSecPerClust * boot->bpbBytesPerSec;
    229 
    230   if ((buffer = malloc(len = MAX(rootdir_size, cluster_size))) == NULL) {
    231     perr("No space for directory buffer (%zu)", len);
    232     return FSFATAL;
    233   }
    234 
    235   if ((delbuf = malloc(len = cluster_size)) == 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 (!fat_is_cl_head(fat, boot->bpbRootClust)) {
    251       pfatal("Root directory doesn't start a cluster chain");
    252       return FSFATAL;
    253     }
    254     rootDir->head = boot->bpbRootClust;
    255   }
    256 
    257   return ret;
    258 }
    259 
    260 /*
    261  * Cleanup after a directory scan
    262  */
    263 void
    264 finishDosDirSection(void)
    265 {
    266   struct dirTodoNode *p, *np;
    267   struct dosDirEntry *d, *nd;
    268 
    269   for (p = pendingDirectories; p; p = np) {
    270     np = p->next;
    271     freeDirTodo(p);
    272   }
    273   pendingDirectories = NULL;
    274   for (d = rootDir; d; d = nd) {
    275     if ((nd = d->child) != NULL) {
    276       d->child = 0;
    277       continue;
    278     }
    279     if (!(nd = d->next))
    280       nd = d->parent;
    281     freeDosDirEntry(d);
    282   }
    283   rootDir = lostDir = NULL;
    284   free(buffer);
    285   free(delbuf);
    286   buffer = NULL;
    287   delbuf = NULL;
    288 }
    289 
    290 /*
    291  * Delete directory entries between startcl, startoff and endcl, endoff.
    292  */
    293 static int delete (
    294     struct fat_descriptor *fat, cl_t startcl, int startoff, cl_t endcl, int endoff, int notlast
    295 )
    296 {
    297   u_char           *s, *e;
    298   off_t             off;
    299   int               clsz, fd;
    300   struct bootblock *boot;
    301 
    302   boot = fat_get_boot(fat);
    303   fd   = fat_get_fd(fat);
    304   clsz = boot->bpbSecPerClust * boot->bpbBytesPerSec;
    305 
    306   s = delbuf + startoff;
    307   e = delbuf + clsz;
    308   while (fat_is_valid_cl(fat, startcl)) {
    309     if (startcl == endcl) {
    310       if (notlast)
    311         break;
    312       e = delbuf + endoff;
    313     }
    314     off = (startcl - CLUST_FIRST) * boot->bpbSecPerClust + boot->FirstCluster;
    315 
    316     off *= boot->bpbBytesPerSec;
    317     if (lseek(fd, off, SEEK_SET) != off) {
    318       perr("Unable to lseek to %" PRId64, off);
    319       return FSFATAL;
    320     }
    321     if (read(fd, delbuf, clsz) != clsz) {
    322       perr("Unable to read directory");
    323       return FSFATAL;
    324     }
    325     while (s < e) {
    326       *s = SLOT_DELETED;
    327       s += 32;
    328     }
    329     if (lseek(fd, off, SEEK_SET) != off) {
    330       perr("Unable to lseek to %" PRId64, off);
    331       return FSFATAL;
    332     }
    333     if (write(fd, delbuf, clsz) != clsz) {
    334       perr("Unable to write directory");
    335       return FSFATAL;
    336     }
    337     if (startcl == endcl)
    338       break;
    339     startcl = fat_get_cl_next(fat, startcl);
    340     s       = delbuf;
    341   }
    342   return FSOK;
    343 }
    344 
    345 static int
    346 removede(
    347     struct fat_descriptor *fat,
    348     u_char                *start,
    349     u_char                *end,
    350     cl_t                   startcl,
    351     cl_t                   endcl,
    352     cl_t                   curcl,
    353     char                  *path,
    354     int                    type
    355 )
    356 {
    357   switch (type) {
    358     case 0:
    359       pwarn("Invalid long filename entry for %s\n", path);
    360       break;
    361     case 1:
    362       pwarn("Invalid long filename entry at end of directory %s\n", path);
    363       break;
    364     case 2:
    365       pwarn("Invalid long filename entry for volume label\n");
    366       break;
    367   }
    368   if (ask(0, "Remove")) {
    369     if (startcl != curcl) {
    370       if (delete (fat, startcl, start - buffer, endcl, end - buffer, endcl == curcl) == FSFATAL)
    371         return FSFATAL;
    372       start = buffer;
    373     }
    374     /* startcl is < CLUST_FIRST for !FAT32 root */
    375     if ((endcl == curcl) || (startcl < CLUST_FIRST))
    376       for (; start < end; start += 32)
    377         *start = SLOT_DELETED;
    378     return FSDIRMOD;
    379   }
    380   return FSERROR;
    381 }
    382 
    383 /*
    384  * Check an in-memory file entry
    385  */
    386 static int
    387 checksize(struct fat_descriptor *fat, u_char *p, struct dosDirEntry *dir)
    388 {
    389   int               ret = FSOK;
    390   size_t            chainsize;
    391   u_int64_t         physicalSize;
    392   struct bootblock *boot;
    393 
    394   boot = fat_get_boot(fat);
    395 
    396   /*
    397    * Check size on ordinary files
    398    */
    399   if (dir->head == CLUST_FREE) {
    400     physicalSize = 0;
    401   } else {
    402     if (!fat_is_valid_cl(fat, dir->head) || !fat_is_cl_head(fat, dir->head)) {
    403       pwarn(
    404           "Directory entry %s of size %u referencing invalid cluster %u\n",
    405           fullpath(dir),
    406           dir->size,
    407           dir->head
    408       );
    409       if (ask(1, "Truncate")) {
    410         p[28] = p[29] = p[30] = p[31] = 0;
    411         p[26] = p[27] = 0;
    412         if (boot->ClustMask == CLUST32_MASK)
    413           p[20] = p[21] = 0;
    414         dir->size = 0;
    415         dir->head = CLUST_FREE;
    416         return FSDIRMOD;
    417       } else {
    418         return FSERROR;
    419       }
    420     }
    421     ret = checkchain(fat, dir->head, &chainsize);
    422     /*
    423      * Upon return, chainsize would hold the chain length
    424      * that checkchain() was able to validate, but if the user
    425      * refused the proposed repair, it would be unsafe to
    426      * proceed with directory entry fix, so bail out in that
    427      * case.
    428      */
    429     if (ret == FSERROR) {
    430       return (FSERROR);
    431     }
    432     /*
    433      * The maximum file size on FAT32 is 4GiB - 1, which
    434      * will occupy a cluster chain of exactly 4GiB in
    435      * size.  On 32-bit platforms, since size_t is 32-bit,
    436      * it would wrap back to 0.
    437      */
    438     physicalSize = (u_int64_t)chainsize * boot->ClusterSize;
    439   }
    440   if (physicalSize < dir->size) {
    441     pwarn(
    442         "size of %s is %u, should at most be %ju\n",
    443         fullpath(dir),
    444         dir->size,
    445         (uintmax_t)physicalSize
    446     );
    447     if (ask(1, "Truncate")) {
    448       dir->size = physicalSize;
    449       p[28]     = (u_char)physicalSize;
    450       p[29]     = (u_char)(physicalSize >> 8);
    451       p[30]     = (u_char)(physicalSize >> 16);
    452       p[31]     = (u_char)(physicalSize >> 24);
    453       return FSDIRMOD;
    454     } else
    455       return FSERROR;
    456   } else if (physicalSize - dir->size >= boot->ClusterSize) {
    457     pwarn("%s has too many clusters allocated\n", fullpath(dir));
    458     if (ask(1, "Drop superfluous clusters")) {
    459       cl_t      cl;
    460       u_int32_t sz, len;
    461 
    462       for (cl = dir->head, len = sz = 0; (sz += boot->ClusterSize) < dir->size; len++)
    463         cl = fat_get_cl_next(fat, cl);
    464       clearchain(fat, fat_get_cl_next(fat, cl));
    465       ret = fat_set_cl_next(fat, cl, CLUST_EOF);
    466       return (FSFATMOD | ret);
    467     } else
    468       return FSERROR;
    469   }
    470   return FSOK;
    471 }
    472 
    473 static const u_char dot_name[11]    = ".          ";
    474 static const u_char dotdot_name[11] = "..         ";
    475 
    476 /*
    477  * Basic sanity check if the subdirectory have good '.' and '..' entries,
    478  * and they are directory entries.  Further sanity checks are performed
    479  * when we traverse into it.
    480  */
    481 static int
    482 check_subdirectory(struct fat_descriptor *fat, struct dosDirEntry *dir)
    483 {
    484   u_char           *buf, *cp;
    485   off_t             off;
    486   cl_t              cl;
    487   int               retval = FSOK;
    488   int               fd;
    489   struct bootblock *boot;
    490 
    491   boot = fat_get_boot(fat);
    492   fd   = fat_get_fd(fat);
    493 
    494   cl = dir->head;
    495   if (dir->parent && !fat_is_valid_cl(fat, cl)) {
    496     return FSERROR;
    497   }
    498 
    499   if (!(boot->flags & FAT32) && !dir->parent) {
    500     off = boot->bpbResSectors + boot->bpbFATs * boot->FATsecs;
    501   } else {
    502     off = (cl - CLUST_FIRST) * boot->bpbSecPerClust + boot->FirstCluster;
    503   }
    504 
    505   /*
    506    * We only need to check the first two entries of the directory,
    507    * which is found in the first sector of the directory entry,
    508    * so read in only the first sector.
    509    */
    510   buf = malloc(boot->bpbBytesPerSec);
    511   if (buf == NULL) {
    512     perr("No space for directory buffer (%u)", boot->bpbBytesPerSec);
    513     return FSFATAL;
    514   }
    515 
    516   off *= boot->bpbBytesPerSec;
    517   if (lseek(fd, off, SEEK_SET) != off
    518       || read(fd, buf, boot->bpbBytesPerSec) != (ssize_t)boot->bpbBytesPerSec) {
    519     perr("Unable to read directory");
    520     free(buf);
    521     return FSFATAL;
    522   }
    523 
    524   /*
    525    * Both `.' and `..' must be present and be the first two entries
    526    * and be ATTR_DIRECTORY of a valid subdirectory.
    527    */
    528   cp = buf;
    529   if (memcmp(cp, dot_name, sizeof(dot_name)) != 0 || (cp[11] & ATTR_DIRECTORY) != ATTR_DIRECTORY) {
    530     pwarn("%s: Incorrect `.' for %s.\n", __func__, dir->name);
    531     retval |= FSERROR;
    532   }
    533   cp += 32;
    534   if (memcmp(cp, dotdot_name, sizeof(dotdot_name)) != 0
    535       || (cp[11] & ATTR_DIRECTORY) != ATTR_DIRECTORY) {
    536     pwarn("%s: Incorrect `..' for %s. \n", __func__, dir->name);
    537     retval |= FSERROR;
    538   }
    539 
    540   free(buf);
    541   return retval;
    542 }
    543 
    544 /*
    545  * Read a directory and
    546  *   - resolve long name records
    547  *   - enter file and directory records into the parent's list
    548  *   - push directories onto the todo-stack
    549  */
    550 static int
    551 readDosDirSection(struct fat_descriptor *fat, struct dosDirEntry *dir)
    552 {
    553   struct bootblock  *boot;
    554   struct dosDirEntry dirent, *d;
    555   u_char            *p, *vallfn, *invlfn, *empty;
    556   off_t              off;
    557   int                fd, i, j, k, iosize, entries;
    558   bool               is_legacyroot;
    559   cl_t               cl, valcl = ~0, invcl = ~0, empcl = ~0;
    560   char              *t;
    561   u_int              lidx = 0;
    562   int                shortSum;
    563   int                mod = FSOK;
    564   size_t             dirclusters;
    565 #define THISMOD 0x8000 /* Only used within this routine */
    566 
    567   boot = fat_get_boot(fat);
    568   fd   = fat_get_fd(fat);
    569 
    570   cl = dir->head;
    571   if (dir->parent && (!fat_is_valid_cl(fat, cl))) {
    572     /*
    573      * Already handled somewhere else.
    574      */
    575     return FSOK;
    576   }
    577   shortSum = -1;
    578   vallfn = invlfn = empty = NULL;
    579 
    580   /*
    581    * If we are checking the legacy root (for FAT12/FAT16),
    582    * we will operate on the whole directory; otherwise, we
    583    * will operate on one cluster at a time, and also take
    584    * this opportunity to examine the chain.
    585    *
    586    * Derive how many entries we are going to encounter from
    587    * the I/O size.
    588    */
    589   is_legacyroot = (dir->parent == NULL && !(boot->flags & FAT32));
    590   if (is_legacyroot) {
    591     iosize  = boot->bpbRootDirEnts * 32;
    592     entries = boot->bpbRootDirEnts;
    593   } else {
    594     iosize  = boot->bpbSecPerClust * boot->bpbBytesPerSec;
    595     entries = iosize / 32;
    596     mod |= checkchain(fat, dir->head, &dirclusters);
    597   }
    598 
    599   do {
    600     if (is_legacyroot) {
    601       /*
    602        * Special case for FAT12/FAT16 root -- read
    603        * in the whole root directory.
    604        */
    605       off = boot->bpbResSectors + boot->bpbFATs * boot->FATsecs;
    606     } else {
    607       /*
    608        * Otherwise, read in a cluster of the
    609        * directory.
    610        */
    611       off = (cl - CLUST_FIRST) * boot->bpbSecPerClust + boot->FirstCluster;
    612     }
    613 
    614     off *= boot->bpbBytesPerSec;
    615     if (lseek(fd, off, SEEK_SET) != off || read(fd, buffer, iosize) != iosize) {
    616       perr("Unable to read directory");
    617       return FSFATAL;
    618     }
    619 
    620     for (p = buffer, i = 0; i < entries; i++, p += 32) {
    621       if (dir->fsckflags & DIREMPWARN) {
    622         *p = SLOT_EMPTY;
    623         continue;
    624       }
    625 
    626       if (*p == SLOT_EMPTY || *p == SLOT_DELETED) {
    627         if (*p == SLOT_EMPTY) {
    628           dir->fsckflags |= DIREMPTY;
    629           empty = p;
    630           empcl = cl;
    631         }
    632         continue;
    633       }
    634 
    635       if (dir->fsckflags & DIREMPTY) {
    636         if (!(dir->fsckflags & DIREMPWARN)) {
    637           pwarn("%s has entries after end of directory\n", fullpath(dir));
    638           if (ask(1, "Extend")) {
    639             u_char *q;
    640 
    641             dir->fsckflags &= ~DIREMPTY;
    642             if (delete (fat, empcl, empty - buffer, cl, p - buffer, 1) == FSFATAL)
    643               return FSFATAL;
    644             q = ((empcl == cl) ? empty : buffer);
    645             assert(q != NULL);
    646             for (; q < p; q += 32)
    647               *q = SLOT_DELETED;
    648             mod |= THISMOD | FSDIRMOD;
    649           } else if (ask(0, "Truncate"))
    650             dir->fsckflags |= DIREMPWARN;
    651         }
    652         if (dir->fsckflags & DIREMPWARN) {
    653           *p = SLOT_DELETED;
    654           mod |= THISMOD | FSDIRMOD;
    655           continue;
    656         } else if (dir->fsckflags & DIREMPTY)
    657           mod |= FSERROR;
    658         empty = NULL;
    659       }
    660 
    661       if (p[11] == ATTR_WIN95) {
    662         if (*p & LRFIRST) {
    663           if (shortSum != -1) {
    664             if (!invlfn) {
    665               invlfn = vallfn;
    666               invcl  = valcl;
    667             }
    668           }
    669           memset(longName, 0, sizeof longName);
    670           shortSum = p[13];
    671           vallfn   = p;
    672           valcl    = cl;
    673         } else if (shortSum != p[13] || lidx != (*p & LRNOMASK)) {
    674           if (!invlfn) {
    675             invlfn = vallfn;
    676             invcl  = valcl;
    677           }
    678           if (!invlfn) {
    679             invlfn = p;
    680             invcl  = cl;
    681           }
    682           vallfn = NULL;
    683         }
    684         lidx = *p & LRNOMASK;
    685         if (lidx == 0) {
    686           pwarn("invalid long name\n");
    687           if (!invlfn) {
    688             invlfn = vallfn;
    689             invcl  = valcl;
    690           }
    691           vallfn = NULL;
    692           continue;
    693         }
    694         t = longName + --lidx * 13;
    695         for (k = 1; k < 11 && t < longName + sizeof(longName); k += 2) {
    696           if (!p[k] && !p[k + 1])
    697             break;
    698           *t++ = p[k];
    699           /*
    700            * Warn about those unusable chars in msdosfs here?	XXX
    701            */
    702           if (p[k + 1])
    703             t[-1] = '?';
    704         }
    705         if (k >= 11)
    706           for (k = 14; k < 26 && t < longName + sizeof(longName); k += 2) {
    707             if (!p[k] && !p[k + 1])
    708               break;
    709             *t++ = p[k];
    710             if (p[k + 1])
    711               t[-1] = '?';
    712           }
    713         if (k >= 26)
    714           for (k = 28; k < 32 && t < longName + sizeof(longName); k += 2) {
    715             if (!p[k] && !p[k + 1])
    716               break;
    717             *t++ = p[k];
    718             if (p[k + 1])
    719               t[-1] = '?';
    720           }
    721         if (t >= longName + sizeof(longName)) {
    722           pwarn("long filename too long\n");
    723           if (!invlfn) {
    724             invlfn = vallfn;
    725             invcl  = valcl;
    726           }
    727           vallfn = NULL;
    728         }
    729         if (p[26] | (p[27] << 8)) {
    730           pwarn("long filename record cluster start != 0\n");
    731           if (!invlfn) {
    732             invlfn = vallfn;
    733             invcl  = cl;
    734           }
    735           vallfn = NULL;
    736         }
    737         continue; /* long records don't carry further
    738                    * information */
    739       }
    740 
    741       /*
    742        * This is a standard msdosfs directory entry.
    743        */
    744       memset(&dirent, 0, sizeof dirent);
    745 
    746       /*
    747        * it's a short name record, but we need to know
    748        * more, so get the flags first.
    749        */
    750       dirent.flags = p[11];
    751 
    752       /*
    753        * Translate from 850 to ISO here		XXX
    754        */
    755       for (j = 0; j < 8; j++)
    756         dirent.name[j] = p[j];
    757       dirent.name[8] = '\0';
    758       for (k = 7; k >= 0 && dirent.name[k] == ' '; k--)
    759         dirent.name[k] = '\0';
    760       if (k < 0 || dirent.name[k] != '\0')
    761         k++;
    762       if (dirent.name[0] == SLOT_E5)
    763         dirent.name[0] = 0xe5;
    764 
    765       if (dirent.flags & ATTR_VOLUME) {
    766         if (vallfn || invlfn) {
    767           mod |= removede(
    768               fat, invlfn ? invlfn : vallfn, p, invlfn ? invcl : valcl, -1, 0, fullpath(dir), 2
    769           );
    770           vallfn = NULL;
    771           invlfn = NULL;
    772         }
    773         continue;
    774       }
    775 
    776       if (p[8] != ' ')
    777         dirent.name[k++] = '.';
    778       for (j = 0; j < 3; j++)
    779         dirent.name[k++] = p[j + 8];
    780       dirent.name[k] = '\0';
    781       for (k--; k >= 0 && dirent.name[k] == ' '; k--)
    782         dirent.name[k] = '\0';
    783 
    784       if (vallfn && shortSum != calcShortSum(p)) {
    785         if (!invlfn) {
    786           invlfn = vallfn;
    787           invcl  = valcl;
    788         }
    789         vallfn = NULL;
    790       }
    791       dirent.head = p[26] | (p[27] << 8);
    792       if (boot->ClustMask == CLUST32_MASK)
    793         dirent.head |= (p[20] << 16) | (p[21] << 24);
    794       dirent.size = p[28] | (p[29] << 8) | (p[30] << 16) | (p[31] << 24);
    795       if (vallfn) {
    796         strlcpy(dirent.lname, longName, sizeof(dirent.lname));
    797         longName[0] = '\0';
    798         shortSum    = -1;
    799       }
    800 
    801       dirent.parent = dir;
    802       dirent.next   = dir->child;
    803 
    804       if (invlfn) {
    805         mod |= k = removede(
    806             fat, invlfn, vallfn ? vallfn : p, invcl, vallfn ? valcl : cl, cl, fullpath(&dirent), 0
    807         );
    808         if (mod & FSFATAL)
    809           return FSFATAL;
    810         if (vallfn ? (valcl == cl && vallfn != buffer) : p != buffer)
    811           if (k & FSDIRMOD)
    812             mod |= THISMOD;
    813       }
    814 
    815       vallfn = NULL; /* not used any longer */
    816       invlfn = NULL;
    817 
    818       /*
    819        * Check if the directory entry is sane.
    820        *
    821        * '.' and '..' are skipped, their sanity is
    822        * checked somewhere else.
    823        *
    824        * For everything else, check if we have a new,
    825        * valid cluster chain (beginning of a file or
    826        * directory that was never previously claimed
    827        * by another file) when it's a non-empty file
    828        * or a directory. The sanity of the cluster
    829        * chain is checked at a later time when we
    830        * traverse into the directory, or examine the
    831        * file's directory entry.
    832        *
    833        * The only possible fix is to delete the entry
    834        * if it's a directory; for file, we have to
    835        * truncate the size to 0.
    836        */
    837       if (!(dirent.flags & ATTR_DIRECTORY)
    838           || (strcmp(dirent.name, ".") != 0 && strcmp(dirent.name, "..") != 0)) {
    839         if ((dirent.size != 0 || (dirent.flags & ATTR_DIRECTORY))
    840             && ((!fat_is_valid_cl(fat, dirent.head) || !fat_is_cl_head(fat, dirent.head)))) {
    841           if (!fat_is_valid_cl(fat, dirent.head)) {
    842             pwarn("%s starts with cluster out of range(%u)\n", fullpath(&dirent), dirent.head);
    843           } else {
    844             pwarn("%s doesn't start a new cluster chain\n", fullpath(&dirent));
    845           }
    846 
    847           if (dirent.flags & ATTR_DIRECTORY) {
    848             if (ask(0, "Remove")) {
    849               *p = SLOT_DELETED;
    850               mod |= THISMOD | FSDIRMOD;
    851             } else
    852               mod |= FSERROR;
    853             continue;
    854           } else {
    855             if (ask(1, "Truncate")) {
    856               p[28] = p[29] = p[30] = p[31] = 0;
    857               p[26] = p[27] = 0;
    858               if (boot->ClustMask == CLUST32_MASK)
    859                 p[20] = p[21] = 0;
    860               dirent.size = 0;
    861               dirent.head = 0;
    862               mod |= THISMOD | FSDIRMOD;
    863             } else
    864               mod |= FSERROR;
    865           }
    866         }
    867       }
    868       if (dirent.flags & ATTR_DIRECTORY) {
    869         /*
    870          * gather more info for directories
    871          */
    872         struct dirTodoNode *n;
    873 
    874         if (dirent.size) {
    875           pwarn("Directory %s has size != 0\n", fullpath(&dirent));
    876           if (ask(1, "Correct")) {
    877             p[28] = p[29] = p[30] = p[31] = 0;
    878             dirent.size                   = 0;
    879             mod |= THISMOD | FSDIRMOD;
    880           } else
    881             mod |= FSERROR;
    882         }
    883         /*
    884          * handle `.' and `..' specially
    885          */
    886         if (strcmp(dirent.name, ".") == 0) {
    887           if (dirent.head != dir->head) {
    888             pwarn("`.' entry in %s has incorrect start cluster\n", fullpath(dir));
    889             if (ask(1, "Correct")) {
    890               dirent.head = dir->head;
    891               p[26]       = (u_char)dirent.head;
    892               p[27]       = (u_char)(dirent.head >> 8);
    893               if (boot->ClustMask == CLUST32_MASK) {
    894                 p[20] = (u_char)(dirent.head >> 16);
    895                 p[21] = (u_char)(dirent.head >> 24);
    896               }
    897               mod |= THISMOD | FSDIRMOD;
    898             } else
    899               mod |= FSERROR;
    900           }
    901           continue;
    902         } else if (strcmp(dirent.name, "..") == 0) {
    903           if (dir->parent) { /* XXX */
    904             if (!dir->parent->parent) {
    905               if (dirent.head) {
    906                 pwarn("`..' entry in %s has non-zero start cluster\n", fullpath(dir));
    907                 if (ask(1, "Correct")) {
    908                   dirent.head = 0;
    909                   p[26] = p[27] = 0;
    910                   if (boot->ClustMask == CLUST32_MASK)
    911                     p[20] = p[21] = 0;
    912                   mod |= THISMOD | FSDIRMOD;
    913                 } else
    914                   mod |= FSERROR;
    915               }
    916             } else if (dirent.head != dir->parent->head) {
    917               pwarn("`..' entry in %s has incorrect start cluster\n", fullpath(dir));
    918               if (ask(1, "Correct")) {
    919                 dirent.head = dir->parent->head;
    920                 p[26]       = (u_char)dirent.head;
    921                 p[27]       = (u_char)(dirent.head >> 8);
    922                 if (boot->ClustMask == CLUST32_MASK) {
    923                   p[20] = (u_char)(dirent.head >> 16);
    924                   p[21] = (u_char)(dirent.head >> 24);
    925                 }
    926                 mod |= THISMOD | FSDIRMOD;
    927               } else
    928                 mod |= FSERROR;
    929             }
    930           }
    931           continue;
    932         } else {
    933           /*
    934            * Only one directory entry can point
    935            * to dir->head, it's '.'.
    936            */
    937           if (dirent.head == dir->head) {
    938             pwarn("%s entry in %s has incorrect start cluster\n", dirent.name, fullpath(dir));
    939             if (ask(1, "Remove")) {
    940               *p = SLOT_DELETED;
    941               mod |= THISMOD | FSDIRMOD;
    942             } else
    943               mod |= FSERROR;
    944             continue;
    945           } else if ((check_subdirectory(fat, &dirent) & FSERROR) == FSERROR) {
    946             /*
    947              * A subdirectory should have
    948              * a dot (.) entry and a dot-dot
    949              * (..) entry of ATTR_DIRECTORY,
    950              * we will inspect further when
    951              * traversing into it.
    952              */
    953             if (ask(1, "Remove")) {
    954               *p = SLOT_DELETED;
    955               mod |= THISMOD | FSDIRMOD;
    956             } else
    957               mod |= FSERROR;
    958             continue;
    959           }
    960         }
    961 
    962         /* create directory tree node */
    963         if (!(d = newDosDirEntry())) {
    964           perr("No space for directory");
    965           return FSFATAL;
    966         }
    967         memcpy(d, &dirent, sizeof(struct dosDirEntry));
    968         /* link it into the tree */
    969         dir->child = d;
    970 
    971         /* Enter this directory into the todo list */
    972         if (!(n = newDirTodo())) {
    973           perr("No space for todo list");
    974           return FSFATAL;
    975         }
    976         n->next            = pendingDirectories;
    977         n->dir             = d;
    978         pendingDirectories = n;
    979       } else if (!(mod & FSERROR)) {
    980         mod |= k = checksize(fat, p, &dirent);
    981         if (k & FSDIRMOD)
    982           mod |= THISMOD;
    983       }
    984       boot->NumFiles++;
    985     }
    986 
    987     if (is_legacyroot) {
    988       /*
    989        * Don't bother to write back right now because
    990        * we may continue to make modification to the
    991        * non-FAT32 root directory below.
    992        */
    993       break;
    994     } else if (mod & THISMOD) {
    995       if (lseek(fd, off, SEEK_SET) != off || write(fd, buffer, iosize) != iosize) {
    996         perr("Unable to write directory");
    997         return FSFATAL;
    998       }
    999       mod &= ~THISMOD;
   1000     }
   1001   } while (fat_is_valid_cl(fat, (cl = fat_get_cl_next(fat, cl))));
   1002   if (invlfn || vallfn)
   1003     mod |=
   1004         removede(fat, invlfn ? invlfn : vallfn, p, invlfn ? invcl : valcl, -1, 0, fullpath(dir), 1);
   1005 
   1006   /*
   1007    * The root directory of non-FAT32 filesystems is in a special
   1008    * area and may have been modified above removede() without
   1009    * being written out.
   1010    */
   1011   if ((mod & FSDIRMOD) && is_legacyroot) {
   1012     if (lseek(fd, off, SEEK_SET) != off || write(fd, buffer, iosize) != iosize) {
   1013       perr("Unable to write directory");
   1014       return FSFATAL;
   1015     }
   1016     mod &= ~THISMOD;
   1017   }
   1018   return mod & ~THISMOD;
   1019 }
   1020 
   1021 int
   1022 handleDirTree(struct fat_descriptor *fat)
   1023 {
   1024   int mod;
   1025 
   1026   mod = readDosDirSection(fat, rootDir);
   1027   if (mod & FSFATAL)
   1028     return FSFATAL;
   1029 
   1030   /*
   1031    * process the directory todo list
   1032    */
   1033   while (pendingDirectories) {
   1034     struct dosDirEntry *dir = pendingDirectories->dir;
   1035     struct dirTodoNode *n   = pendingDirectories->next;
   1036 
   1037     /*
   1038      * remove TODO entry now, the list might change during
   1039      * directory reads
   1040      */
   1041     freeDirTodo(pendingDirectories);
   1042     pendingDirectories = n;
   1043 
   1044     /*
   1045      * handle subdirectory
   1046      */
   1047     mod |= readDosDirSection(fat, dir);
   1048     if (mod & FSFATAL)
   1049       return FSFATAL;
   1050   }
   1051 
   1052   return mod;
   1053 }
   1054 
   1055 /*
   1056  * Try to reconnect a FAT chain into dir
   1057  */
   1058 static u_char *lfbuf;
   1059 static cl_t    lfcl;
   1060 static off_t   lfoff;
   1061 
   1062 int
   1063 reconnect(struct fat_descriptor *fat, cl_t head, size_t length)
   1064 {
   1065   struct bootblock  *boot = fat_get_boot(fat);
   1066   struct dosDirEntry d;
   1067   int                len, dosfs;
   1068   u_char            *p;
   1069 
   1070   dosfs = fat_get_fd(fat);
   1071 
   1072   if (!ask(1, "Reconnect"))
   1073     return FSERROR;
   1074 
   1075   if (!lostDir) {
   1076     for (lostDir = rootDir->child; lostDir; lostDir = lostDir->next) {
   1077       if (!strcmp(lostDir->name, LOSTDIR))
   1078         break;
   1079     }
   1080     if (!lostDir) { /* Create LOSTDIR?		XXX */
   1081       pwarn("No %s directory\n", LOSTDIR);
   1082       return FSERROR;
   1083     }
   1084   }
   1085   if (!lfbuf) {
   1086     lfbuf = malloc(boot->ClusterSize);
   1087     if (!lfbuf) {
   1088       perr("No space for buffer");
   1089       return FSFATAL;
   1090     }
   1091     p = NULL;
   1092   } else
   1093     p = lfbuf;
   1094   while (1) {
   1095     if (p)
   1096       for (; p < lfbuf + boot->ClusterSize; p += 32)
   1097         if (*p == SLOT_EMPTY || *p == SLOT_DELETED)
   1098           break;
   1099     if (p && p < lfbuf + boot->ClusterSize)
   1100       break;
   1101     lfcl = p ? fat_get_cl_next(fat, lfcl) : lostDir->head;
   1102     if (lfcl < CLUST_FIRST || lfcl >= boot->NumClusters) {
   1103       /* Extend LOSTDIR?				XXX */
   1104       pwarn("No space in %s\n", LOSTDIR);
   1105       lfcl = (lostDir->head < boot->NumClusters) ? lostDir->head : 0;
   1106       return FSERROR;
   1107     }
   1108     lfoff = (lfcl - CLUST_FIRST) * boot->ClusterSize + boot->FirstCluster * boot->bpbBytesPerSec;
   1109 
   1110     if (lseek(dosfs, lfoff, SEEK_SET) != lfoff
   1111         || (size_t)read(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) {
   1112       perr("could not read LOST.DIR");
   1113       return FSFATAL;
   1114     }
   1115     p = lfbuf;
   1116   }
   1117 
   1118   boot->NumFiles++;
   1119   /* Ensure uniqueness of entry here!				XXX */
   1120   memset(&d, 0, sizeof d);
   1121   /* worst case -1 = 4294967295, 10 digits */
   1122   len     = snprintf(d.name, sizeof(d.name), "%u", head);
   1123   d.flags = 0;
   1124   d.head  = head;
   1125   d.size  = length * boot->ClusterSize;
   1126 
   1127   memcpy(p, d.name, len);
   1128   memset(p + len, ' ', 11 - len);
   1129   memset(p + 11, 0, 32 - 11);
   1130   p[26] = (u_char)d.head;
   1131   p[27] = (u_char)(d.head >> 8);
   1132   if (boot->ClustMask == CLUST32_MASK) {
   1133     p[20] = (u_char)(d.head >> 16);
   1134     p[21] = (u_char)(d.head >> 24);
   1135   }
   1136   p[28] = (u_char)d.size;
   1137   p[29] = (u_char)(d.size >> 8);
   1138   p[30] = (u_char)(d.size >> 16);
   1139   p[31] = (u_char)(d.size >> 24);
   1140   if (lseek(dosfs, lfoff, SEEK_SET) != lfoff
   1141       || (size_t)write(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) {
   1142     perr("could not write LOST.DIR");
   1143     return FSFATAL;
   1144   }
   1145   return FSDIRMOD;
   1146 }
   1147 
   1148 void
   1149 finishlf(void)
   1150 {
   1151   if (lfbuf)
   1152     free(lfbuf);
   1153   lfbuf = NULL;
   1154 }