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