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