xref: /dragonfly/sbin/fsck_msdosfs/dir.c (revision e0eb7cf0)
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 chainsize;
386 	u_int64_t physicalSize;
387 	struct bootblock *boot;
388 
389 	boot = fat_get_boot(fat);
390 
391 	/*
392 	 * Check size on ordinary files
393 	 */
394 	if (dir->head == CLUST_FREE) {
395 		physicalSize = 0;
396 	} else {
397 		if (!fat_is_valid_cl(fat, dir->head))
398 			return FSERROR;
399 		ret = checkchain(fat, dir->head, &chainsize);
400 		/*
401 		 * Upon return, chainsize would hold the chain length
402 		 * that checkchain() was able to validate, but if the user
403 		 * refused the proposed repair, it would be unsafe to
404 		 * proceed with directory entry fix, so bail out in that
405 		 * case.
406 		 */
407 		if (ret == FSERROR) {
408 			return (FSERROR);
409 		}
410 		/*
411 		 * The maximum file size on FAT32 is 4GiB - 1, which
412 		 * will occupy a cluster chain of exactly 4GiB in
413 		 * size.  On 32-bit platforms, since size_t is 32-bit,
414 		 * it would wrap back to 0.
415 		 */
416 		physicalSize = (u_int64_t)chainsize * boot->ClusterSize;
417 	}
418 	if (physicalSize < dir->size) {
419 		pwarn("size of %s is %u, should at most be %ju\n",
420 		      fullpath(dir), dir->size, (uintmax_t)physicalSize);
421 		if (ask(1, "Truncate")) {
422 			dir->size = physicalSize;
423 			p[28] = (u_char)physicalSize;
424 			p[29] = (u_char)(physicalSize >> 8);
425 			p[30] = (u_char)(physicalSize >> 16);
426 			p[31] = (u_char)(physicalSize >> 24);
427 			return FSDIRMOD;
428 		} else
429 			return FSERROR;
430 	} else if (physicalSize - dir->size >= boot->ClusterSize) {
431 		pwarn("%s has too many clusters allocated\n",
432 		      fullpath(dir));
433 		if (ask(1, "Drop superfluous clusters")) {
434 			cl_t cl;
435 			uint32_t sz, len;
436 
437 			for (cl = dir->head, len = sz = 0;
438 			    (sz += boot->ClusterSize) < dir->size; len++)
439 				cl = fat_get_cl_next(fat, cl);
440 			clearchain(fat, fat_get_cl_next(fat, cl));
441 			ret = fat_set_cl_next(fat, cl, CLUST_EOF);
442 			return (FSFATMOD | ret);
443 		} else
444 			return FSERROR;
445 	}
446 	return FSOK;
447 }
448 
449 static const u_char dot_name[11]    = ".          ";
450 static const u_char dotdot_name[11] = "..         ";
451 
452 /*
453  * Basic sanity check if the subdirectory have good '.' and '..' entries,
454  * and they are directory entries.  Further sanity checks are performed
455  * when we traverse into it.
456  */
457 static int
458 check_subdirectory(struct fat_descriptor *fat, struct dosDirEntry *dir)
459 {
460 	u_char *buf, *cp;
461 	off_t off;
462 	cl_t cl;
463 	int retval = FSOK;
464 	int fd;
465 	struct bootblock *boot;
466 
467 	boot = fat_get_boot(fat);
468 	fd = fat_get_fd(fat);
469 
470 	cl = dir->head;
471 	if (dir->parent && !fat_is_valid_cl(fat, cl)) {
472 		return FSERROR;
473 	}
474 
475 	if (!(boot->flags & FAT32) && !dir->parent) {
476 		off = boot->bpbResSectors + boot->bpbFATs *
477 			boot->FATsecs;
478 	} else {
479 		off = (cl - CLUST_FIRST) * boot->bpbSecPerClust + boot->FirstCluster;
480 	}
481 
482 	/*
483 	 * We only need to check the first two entries of the directory,
484 	 * which is found in the first sector of the directory entry,
485 	 * so read in only the first sector.
486 	 */
487 	buf = malloc(boot->bpbBytesPerSec);
488 	if (buf == NULL) {
489 		perr("No space for directory buffer (%u)",
490 		    boot->bpbBytesPerSec);
491 		return FSFATAL;
492 	}
493 
494 	off *= boot->bpbBytesPerSec;
495 	if (lseek(fd, off, SEEK_SET) != off ||
496 	    read(fd, buf, boot->bpbBytesPerSec) != (ssize_t)boot->bpbBytesPerSec) {
497 		perr("Unable to read directory");
498 		free(buf);
499 		return FSFATAL;
500 	}
501 
502 	/*
503 	 * Both `.' and `..' must be present and be the first two entries
504 	 * and be ATTR_DIRECTORY of a valid subdirectory.
505 	 */
506 	cp = buf;
507 	if (memcmp(cp, dot_name, sizeof(dot_name)) != 0 ||
508 	    (cp[11] & ATTR_DIRECTORY) != ATTR_DIRECTORY) {
509 		pwarn("%s: Incorrect `.' for %s.\n", __func__, dir->name);
510 		retval |= FSERROR;
511 	}
512 	cp += 32;
513 	if (memcmp(cp, dotdot_name, sizeof(dotdot_name)) != 0 ||
514 	    (cp[11] & ATTR_DIRECTORY) != ATTR_DIRECTORY) {
515 		pwarn("%s: Incorrect `..' for %s. \n", __func__, dir->name);
516 		retval |= FSERROR;
517 	}
518 
519 	free(buf);
520 	return retval;
521 }
522 
523 /*
524  * Read a directory and
525  *   - resolve long name records
526  *   - enter file and directory records into the parent's list
527  *   - push directories onto the todo-stack
528  */
529 static int
530 readDosDirSection(struct fat_descriptor *fat, struct dosDirEntry *dir)
531 {
532 	struct bootblock *boot;
533 	struct dosDirEntry dirent, *d;
534 	u_char *p, *vallfn, *invlfn, *empty;
535 	off_t off;
536 	int fd, i, j, k, iosize, entries;
537 	bool is_legacyroot;
538 	cl_t cl, valcl = ~0, invcl = ~0, empcl = ~0;
539 	char *t;
540 	u_int lidx = 0;
541 	int shortSum;
542 	int mod = FSOK;
543 	size_t dirclusters;
544 #define	THISMOD	0x8000			/* Only used within this routine */
545 
546 	boot = fat_get_boot(fat);
547 	fd = fat_get_fd(fat);
548 
549 	cl = dir->head;
550 	if (dir->parent && (!fat_is_valid_cl(fat, cl))) {
551 		/*
552 		 * Already handled somewhere else.
553 		 */
554 		return FSOK;
555 	}
556 	shortSum = -1;
557 	vallfn = invlfn = empty = NULL;
558 
559 	/*
560 	 * If we are checking the legacy root (for FAT12/FAT16),
561 	 * we will operate on the whole directory; otherwise, we
562 	 * will operate on one cluster at a time, and also take
563 	 * this opportunity to examine the chain.
564 	 *
565 	 * Derive how many entries we are going to encounter from
566 	 * the I/O size.
567 	 */
568 	is_legacyroot = (dir->parent == NULL && !(boot->flags & FAT32));
569 	if (is_legacyroot) {
570 		iosize = boot->bpbRootDirEnts * 32;
571 		entries = boot->bpbRootDirEnts;
572 	} else {
573 		iosize = boot->bpbSecPerClust * boot->bpbBytesPerSec;
574 		entries = iosize / 32;
575 		mod |= checkchain(fat, dir->head, &dirclusters);
576 	}
577 
578 	do {
579 		if (is_legacyroot) {
580 			/*
581 			 * Special case for FAT12/FAT16 root -- read
582 			 * in the whole root directory.
583 			 */
584 			off = boot->bpbResSectors + boot->bpbFATs *
585 			    boot->FATsecs;
586 		} else {
587 			/*
588 			 * Otherwise, read in a cluster of the
589 			 * directory.
590 			 */
591 			off = (cl - CLUST_FIRST) * boot->bpbSecPerClust + boot->FirstCluster;
592 		}
593 
594 		off *= boot->bpbBytesPerSec;
595 		if (lseek(fd, off, SEEK_SET) != off ||
596 		    read(fd, buffer, iosize) != iosize) {
597 			perr("Unable to read directory");
598 			return FSFATAL;
599 		}
600 
601 		for (p = buffer, i = 0; i < entries; i++, p += 32) {
602 			if (dir->fsckflags & DIREMPWARN) {
603 				*p = SLOT_EMPTY;
604 				continue;
605 			}
606 
607 			if (*p == SLOT_EMPTY || *p == SLOT_DELETED) {
608 				if (*p == SLOT_EMPTY) {
609 					dir->fsckflags |= DIREMPTY;
610 					empty = p;
611 					empcl = cl;
612 				}
613 				continue;
614 			}
615 
616 			if (dir->fsckflags & DIREMPTY) {
617 				if (!(dir->fsckflags & DIREMPWARN)) {
618 					pwarn("%s has entries after end of directory\n",
619 					      fullpath(dir));
620 					if (ask(1, "Extend")) {
621 						u_char *q;
622 
623 						dir->fsckflags &= ~DIREMPTY;
624 						if (delete(fat,
625 							   empcl, empty - buffer,
626 							   cl, p - buffer, 1) == FSFATAL)
627 							return FSFATAL;
628 						q = ((empcl == cl) ? empty : buffer);
629 						assert(q != NULL);
630 						for (; q < p; q += 32)
631 							*q = SLOT_DELETED;
632 						mod |= THISMOD|FSDIRMOD;
633 					} else if (ask(0, "Truncate"))
634 						dir->fsckflags |= DIREMPWARN;
635 				}
636 				if (dir->fsckflags & DIREMPWARN) {
637 					*p = SLOT_DELETED;
638 					mod |= THISMOD|FSDIRMOD;
639 					continue;
640 				} else if (dir->fsckflags & DIREMPTY)
641 					mod |= FSERROR;
642 				empty = NULL;
643 			}
644 
645 			if (p[11] == ATTR_WIN95) {
646 				if (*p & LRFIRST) {
647 					if (shortSum != -1) {
648 						if (!invlfn) {
649 							invlfn = vallfn;
650 							invcl = valcl;
651 						}
652 					}
653 					memset(longName, 0, sizeof longName);
654 					shortSum = p[13];
655 					vallfn = p;
656 					valcl = cl;
657 				} else if (shortSum != p[13]
658 					   || lidx != (*p & LRNOMASK)) {
659 					if (!invlfn) {
660 						invlfn = vallfn;
661 						invcl = valcl;
662 					}
663 					if (!invlfn) {
664 						invlfn = p;
665 						invcl = cl;
666 					}
667 					vallfn = NULL;
668 				}
669 				lidx = *p & LRNOMASK;
670 				if (lidx == 0) {
671 					pwarn("invalid long name\n");
672 					if (!invlfn) {
673 						invlfn = vallfn;
674 						invcl = valcl;
675 					}
676 					vallfn = NULL;
677 					continue;
678 				}
679 				t = longName + --lidx * 13;
680 				for (k = 1; k < 11 && t < longName +
681 				    sizeof(longName); k += 2) {
682 					if (!p[k] && !p[k + 1])
683 						break;
684 					*t++ = p[k];
685 					/*
686 					 * Warn about those unusable chars in msdosfs here?	XXX
687 					 */
688 					if (p[k + 1])
689 						t[-1] = '?';
690 				}
691 				if (k >= 11)
692 					for (k = 14; k < 26 && t < longName + sizeof(longName); k += 2) {
693 						if (!p[k] && !p[k + 1])
694 							break;
695 						*t++ = p[k];
696 						if (p[k + 1])
697 							t[-1] = '?';
698 					}
699 				if (k >= 26)
700 					for (k = 28; k < 32 && t < longName + sizeof(longName); k += 2) {
701 						if (!p[k] && !p[k + 1])
702 							break;
703 						*t++ = p[k];
704 						if (p[k + 1])
705 							t[-1] = '?';
706 					}
707 				if (t >= longName + sizeof(longName)) {
708 					pwarn("long filename too long\n");
709 					if (!invlfn) {
710 						invlfn = vallfn;
711 						invcl = valcl;
712 					}
713 					vallfn = NULL;
714 				}
715 				if (p[26] | (p[27] << 8)) {
716 					pwarn("long filename record cluster start != 0\n");
717 					if (!invlfn) {
718 						invlfn = vallfn;
719 						invcl = cl;
720 					}
721 					vallfn = NULL;
722 				}
723 				continue;	/* long records don't carry further
724 						 * information */
725 			}
726 
727 			/*
728 			 * This is a standard msdosfs directory entry.
729 			 */
730 			memset(&dirent, 0, sizeof dirent);
731 
732 			/*
733 			 * it's a short name record, but we need to know
734 			 * more, so get the flags first.
735 			 */
736 			dirent.flags = p[11];
737 
738 			/*
739 			 * Translate from 850 to ISO here		XXX
740 			 */
741 			for (j = 0; j < 8; j++)
742 				dirent.name[j] = p[j];
743 			dirent.name[8] = '\0';
744 			for (k = 7; k >= 0 && dirent.name[k] == ' '; k--)
745 				dirent.name[k] = '\0';
746 			if (k < 0 || dirent.name[k] != '\0')
747 				k++;
748 			if (dirent.name[0] == SLOT_E5)
749 				dirent.name[0] = 0xe5;
750 
751 			if (dirent.flags & ATTR_VOLUME) {
752 				if (vallfn || invlfn) {
753 					mod |= removede(fat,
754 							invlfn ? invlfn : vallfn, p,
755 							invlfn ? invcl : valcl, -1, 0,
756 							fullpath(dir), 2);
757 					vallfn = NULL;
758 					invlfn = NULL;
759 				}
760 				continue;
761 			}
762 
763 			if (p[8] != ' ')
764 				dirent.name[k++] = '.';
765 			for (j = 0; j < 3; j++)
766 				dirent.name[k++] = p[j+8];
767 			dirent.name[k] = '\0';
768 			for (k--; k >= 0 && dirent.name[k] == ' '; k--)
769 				dirent.name[k] = '\0';
770 
771 			if (vallfn && shortSum != calcShortSum(p)) {
772 				if (!invlfn) {
773 					invlfn = vallfn;
774 					invcl = valcl;
775 				}
776 				vallfn = NULL;
777 			}
778 			dirent.head = p[26] | (p[27] << 8);
779 			if (boot->ClustMask == CLUST32_MASK)
780 				dirent.head |= (p[20] << 16) | (p[21] << 24);
781 			dirent.size = p[28] | (p[29] << 8) | (p[30] << 16) | (p[31] << 24);
782 			if (vallfn) {
783 				strlcpy(dirent.lname, longName,
784 				    sizeof(dirent.lname));
785 				longName[0] = '\0';
786 				shortSum = -1;
787 			}
788 
789 			dirent.parent = dir;
790 			dirent.next = dir->child;
791 
792 			if (invlfn) {
793 				mod |= k = removede(fat,
794 						    invlfn, vallfn ? vallfn : p,
795 						    invcl, vallfn ? valcl : cl, cl,
796 						    fullpath(&dirent), 0);
797 				if (mod & FSFATAL)
798 					return FSFATAL;
799 				if (vallfn
800 				    ? (valcl == cl && vallfn != buffer)
801 				    : p != buffer)
802 					if (k & FSDIRMOD)
803 						mod |= THISMOD;
804 			}
805 
806 			vallfn = NULL; /* not used any longer */
807 			invlfn = NULL;
808 
809 			/*
810 			 * Check if the directory entry is sane.
811 			 *
812 			 * '.' and '..' are skipped, their sanity is
813 			 * checked somewhere else.
814 			 *
815 			 * For everything else, check if we have a new,
816 			 * valid cluster chain (beginning of a file or
817 			 * directory that was never previously claimed
818 			 * by another file) when it's a non-empty file
819 			 * or a directory. The sanity of the cluster
820 			 * chain is checked at a later time when we
821 			 * traverse into the directory, or examine the
822 			 * file's directory entry.
823 			 *
824 			 * The only possible fix is to delete the entry
825 			 * if it's a directory; for file, we have to
826 			 * truncate the size to 0.
827 			 */
828 			if (!(dirent.flags & ATTR_DIRECTORY) ||
829 			    (strcmp(dirent.name, ".") != 0 &&
830 			    strcmp(dirent.name, "..") != 0)) {
831 				if ((dirent.size != 0 || (dirent.flags & ATTR_DIRECTORY)) &&
832 				    ((!fat_is_valid_cl(fat, dirent.head) ||
833 				    !fat_is_cl_head(fat, dirent.head)))) {
834 					if (!fat_is_valid_cl(fat, dirent.head)) {
835 						pwarn("%s starts with cluster out of range(%u)\n",
836 						    fullpath(&dirent),
837 						    dirent.head);
838 					} else {
839 						pwarn("%s doesn't start a new cluster chain\n",
840 						    fullpath(&dirent));
841 					}
842 
843 					if (dirent.flags & ATTR_DIRECTORY) {
844 						if (ask(0, "Remove")) {
845 							*p = SLOT_DELETED;
846 							mod |= THISMOD|FSDIRMOD;
847 						} else
848 							mod |= FSERROR;
849 						continue;
850 					} else {
851 						if (ask(1, "Truncate")) {
852 							p[28] = p[29] = p[30] = p[31] = 0;
853 							p[26] = p[27] = 0;
854 							if (boot->ClustMask == CLUST32_MASK)
855 								p[20] = p[21] = 0;
856 							dirent.size = 0;
857 							dirent.head = 0;
858 							mod |= THISMOD|FSDIRMOD;
859 						} else
860 							mod |= FSERROR;
861 					}
862 				}
863 			}
864 			if (dirent.flags & ATTR_DIRECTORY) {
865 				/*
866 				 * gather more info for directories
867 				 */
868 				struct dirTodoNode *n;
869 
870 				if (dirent.size) {
871 					pwarn("Directory %s has size != 0\n",
872 					      fullpath(&dirent));
873 					if (ask(1, "Correct")) {
874 						p[28] = p[29] = p[30] = p[31] = 0;
875 						dirent.size = 0;
876 						mod |= THISMOD|FSDIRMOD;
877 					} else
878 						mod |= FSERROR;
879 				}
880 				/*
881 				 * handle `.' and `..' specially
882 				 */
883 				if (strcmp(dirent.name, ".") == 0) {
884 					if (dirent.head != dir->head) {
885 						pwarn("`.' entry in %s has incorrect start cluster\n",
886 						      fullpath(dir));
887 						if (ask(1, "Correct")) {
888 							dirent.head = dir->head;
889 							p[26] = (u_char)dirent.head;
890 							p[27] = (u_char)(dirent.head >> 8);
891 							if (boot->ClustMask == CLUST32_MASK) {
892 								p[20] = (u_char)(dirent.head >> 16);
893 								p[21] = (u_char)(dirent.head >> 24);
894 							}
895 							mod |= THISMOD|FSDIRMOD;
896 						} else
897 							mod |= FSERROR;
898 					}
899 					continue;
900 				} else if (strcmp(dirent.name, "..") == 0) {
901 					if (dir->parent) {		/* XXX */
902 						if (!dir->parent->parent) {
903 							if (dirent.head) {
904 								pwarn("`..' entry in %s has non-zero start cluster\n",
905 								      fullpath(dir));
906 								if (ask(1, "Correct")) {
907 									dirent.head = 0;
908 									p[26] = p[27] = 0;
909 									if (boot->ClustMask == CLUST32_MASK)
910 										p[20] = p[21] = 0;
911 									mod |= THISMOD|FSDIRMOD;
912 								} else
913 									mod |= FSERROR;
914 							}
915 						} else if (dirent.head != dir->parent->head) {
916 							pwarn("`..' entry in %s has incorrect start cluster\n",
917 							      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",
939 								dirent.name, fullpath(dir));
940 						if (ask(1, "Remove")) {
941 							*p = SLOT_DELETED;
942 							mod |= THISMOD|FSDIRMOD;
943 						} else
944 							mod |= FSERROR;
945 						continue;
946 					} else if ((check_subdirectory(fat,
947 					    &dirent) & FSERROR) == FSERROR) {
948 						/*
949 						 * A subdirectory should have
950 						 * a dot (.) entry and a dot-dot
951 						 * (..) entry of ATTR_DIRECTORY,
952 						 * we will inspect further when
953 						 * traversing into it.
954 						 */
955 						if (ask(1, "Remove")) {
956 							*p = SLOT_DELETED;
957 							mod |= THISMOD|FSDIRMOD;
958 						} else
959 							mod |= FSERROR;
960 						continue;
961 					}
962 				}
963 
964 				/* create directory tree node */
965 				if (!(d = newDosDirEntry())) {
966 					perr("No space for directory");
967 					return FSFATAL;
968 				}
969 				memcpy(d, &dirent, sizeof(struct dosDirEntry));
970 				/* link it into the tree */
971 				dir->child = d;
972 
973 				/* Enter this directory into the todo list */
974 				if (!(n = newDirTodo())) {
975 					perr("No space for todo list");
976 					return FSFATAL;
977 				}
978 				n->next = pendingDirectories;
979 				n->dir = d;
980 				pendingDirectories = n;
981 			} else {
982 				mod |= k = checksize(fat, p, &dirent);
983 				if (k & FSDIRMOD)
984 					mod |= THISMOD;
985 			}
986 			boot->NumFiles++;
987 		}
988 
989 		if (is_legacyroot) {
990 			/*
991 			 * Don't bother to write back right now because
992 			 * we may continue to make modification to the
993 			 * non-FAT32 root directory below.
994 			 */
995 			break;
996 		} else if (mod & THISMOD) {
997 			if (lseek(fd, off, SEEK_SET) != off
998 			    || write(fd, buffer, iosize) != iosize) {
999 				perr("Unable to write directory");
1000 				return FSFATAL;
1001 			}
1002 			mod &= ~THISMOD;
1003 		}
1004 	} while (fat_is_valid_cl(fat, (cl = fat_get_cl_next(fat, cl))));
1005 	if (invlfn || vallfn)
1006 		mod |= removede(fat,
1007 				invlfn ? invlfn : vallfn, p,
1008 				invlfn ? invcl : valcl, -1, 0,
1009 				fullpath(dir), 1);
1010 
1011 	/*
1012 	 * The root directory of non-FAT32 filesystems is in a special
1013 	 * area and may have been modified above removede() without
1014 	 * being written out.
1015 	 */
1016 	if ((mod & FSDIRMOD) && is_legacyroot) {
1017 		if (lseek(fd, off, SEEK_SET) != off
1018 		    || write(fd, buffer, iosize) != iosize) {
1019 			perr("Unable to write directory");
1020 			return FSFATAL;
1021 		}
1022 		mod &= ~THISMOD;
1023 	}
1024 	return mod & ~THISMOD;
1025 }
1026 
1027 int
1028 handleDirTree(struct fat_descriptor *fat)
1029 {
1030 	int mod;
1031 
1032 	mod = readDosDirSection(fat, rootDir);
1033 	if (mod & FSFATAL)
1034 		return FSFATAL;
1035 
1036 	/*
1037 	 * process the directory todo list
1038 	 */
1039 	while (pendingDirectories) {
1040 		struct dosDirEntry *dir = pendingDirectories->dir;
1041 		struct dirTodoNode *n = pendingDirectories->next;
1042 
1043 		/*
1044 		 * remove TODO entry now, the list might change during
1045 		 * directory reads
1046 		 */
1047 		freeDirTodo(pendingDirectories);
1048 		pendingDirectories = n;
1049 
1050 		/*
1051 		 * handle subdirectory
1052 		 */
1053 		mod |= readDosDirSection(fat, dir);
1054 		if (mod & FSFATAL)
1055 			return FSFATAL;
1056 	}
1057 
1058 	return mod;
1059 }
1060 
1061 /*
1062  * Try to reconnect a FAT chain into dir
1063  */
1064 static u_char *lfbuf;
1065 static cl_t lfcl;
1066 static off_t lfoff;
1067 
1068 int
1069 reconnect(struct fat_descriptor *fat, cl_t head, size_t length)
1070 {
1071 	struct bootblock *boot = fat_get_boot(fat);
1072 	struct dosDirEntry d;
1073 	int len, dosfs;
1074 	u_char *p;
1075 
1076 	dosfs = fat_get_fd(fat);
1077 
1078 	if (!ask(1, "Reconnect"))
1079 		return FSERROR;
1080 
1081 	if (!lostDir) {
1082 		for (lostDir = rootDir->child; lostDir; lostDir = lostDir->next) {
1083 			if (!strcmp(lostDir->name, LOSTDIR))
1084 				break;
1085 		}
1086 		if (!lostDir) {		/* Create LOSTDIR?		XXX */
1087 			pwarn("No %s directory\n", LOSTDIR);
1088 			return FSERROR;
1089 		}
1090 	}
1091 	if (!lfbuf) {
1092 		lfbuf = malloc(boot->ClusterSize);
1093 		if (!lfbuf) {
1094 			perr("No space for buffer");
1095 			return FSFATAL;
1096 		}
1097 		p = NULL;
1098 	} else
1099 		p = lfbuf;
1100 	while (1) {
1101 		if (p)
1102 			for (; p < lfbuf + boot->ClusterSize; p += 32)
1103 				if (*p == SLOT_EMPTY
1104 				    || *p == SLOT_DELETED)
1105 					break;
1106 		if (p && p < lfbuf + boot->ClusterSize)
1107 			break;
1108 		lfcl = p ? fat_get_cl_next(fat, lfcl) : lostDir->head;
1109 		if (lfcl < CLUST_FIRST || lfcl >= boot->NumClusters) {
1110 			/* Extend LOSTDIR?				XXX */
1111 			pwarn("No space in %s\n", LOSTDIR);
1112 			lfcl = (lostDir->head < boot->NumClusters) ? lostDir->head : 0;
1113 			return FSERROR;
1114 		}
1115 		lfoff = (lfcl - CLUST_FIRST) * boot->ClusterSize
1116 		    + boot->FirstCluster * boot->bpbBytesPerSec;
1117 
1118 		if (lseek(dosfs, lfoff, SEEK_SET) != lfoff
1119 		    || (size_t)read(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) {
1120 			perr("could not read LOST.DIR");
1121 			return FSFATAL;
1122 		}
1123 		p = lfbuf;
1124 	}
1125 
1126 	boot->NumFiles++;
1127 	/* Ensure uniqueness of entry here!				XXX */
1128 	memset(&d, 0, sizeof d);
1129 	/* worst case -1 = 4294967295, 10 digits */
1130 	len = snprintf(d.name, sizeof(d.name), "%u", head);
1131 	d.flags = 0;
1132 	d.head = head;
1133 	d.size = length * boot->ClusterSize;
1134 
1135 	memcpy(p, d.name, len);
1136 	memset(p + len, ' ', 11 - len);
1137 	memset(p + 11, 0, 32 - 11);
1138 	p[26] = (u_char)d.head;
1139 	p[27] = (u_char)(d.head >> 8);
1140 	if (boot->ClustMask == CLUST32_MASK) {
1141 		p[20] = (u_char)(d.head >> 16);
1142 		p[21] = (u_char)(d.head >> 24);
1143 	}
1144 	p[28] = (u_char)d.size;
1145 	p[29] = (u_char)(d.size >> 8);
1146 	p[30] = (u_char)(d.size >> 16);
1147 	p[31] = (u_char)(d.size >> 24);
1148 	if (lseek(dosfs, lfoff, SEEK_SET) != lfoff
1149 	    || (size_t)write(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) {
1150 		perr("could not write LOST.DIR");
1151 		return FSFATAL;
1152 	}
1153 	return FSDIRMOD;
1154 }
1155 
1156 void
1157 finishlf(void)
1158 {
1159 	if (lfbuf)
1160 		free(lfbuf);
1161 	lfbuf = NULL;
1162 }
1163