• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * ntfsfix - Part of the Linux-NTFS project.
3  *
4  * Copyright (c) 2000-2006 Anton Altaparmakov
5  * Copyright (c) 2002-2006 Szabolcs Szakacsits
6  * Copyright (c) 2007      Yura Pakhuchiy
7  * Copyright (c) 2011-2015 Jean-Pierre Andre
8  *
9  * This utility fixes some common NTFS problems, resets the NTFS journal file
10  * and schedules an NTFS consistency check for the first boot into Windows.
11  *
12  *	Anton Altaparmakov <aia21@cantab.net>
13  *
14  * This program is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation; either version 2 of the License, or
17  * (at your option) any later version.
18  *
19  * This program is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program (in the main directory of the Linux-NTFS source
26  * in the file COPYING); if not, write to the Free Software Foundation,
27  * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
28  */
29 
30 /*
31  * WARNING: This program might not work on architectures which do not allow
32  * unaligned access. For those, the program would need to start using
33  * get/put_unaligned macros (#include <asm/unaligned.h>), but not doing it yet,
34  * since NTFS really mostly applies to ia32 only, which does allow unaligned
35  * accesses. We might not actually have a problem though, since the structs are
36  * defined as being packed so that might be enough for gcc to insert the
37  * correct code.
38  *
39  * If anyone using a non-little endian and/or an aligned access only CPU tries
40  * this program please let me know whether it works or not!
41  *
42  *	Anton Altaparmakov <aia21@cantab.net>
43  */
44 
45 #include "config.h"
46 
47 #ifdef HAVE_UNISTD_H
48 #include <unistd.h>
49 #endif
50 #ifdef HAVE_STDLIB_H
51 #include <stdlib.h>
52 #endif
53 #ifdef HAVE_STDIO_H
54 #include <stdio.h>
55 #endif
56 #ifdef HAVE_FCNTL_H
57 #include <fcntl.h>
58 #endif
59 #ifdef HAVE_ERRNO_H
60 #include <errno.h>
61 #endif
62 #ifdef HAVE_STRING_H
63 #include <string.h>
64 #endif
65 #ifdef HAVE_GETOPT_H
66 #include <getopt.h>
67 #endif
68 
69 #include "types.h"
70 #include "attrib.h"
71 #include "volume.h"
72 #include "bootsect.h"
73 #include "mft.h"
74 #include "device.h"
75 #include "logfile.h"
76 #include "runlist.h"
77 #include "mst.h"
78 #include "utils.h"
79 /* #include "version.h" */
80 #include "logging.h"
81 #include "misc.h"
82 
83 #ifdef NO_NTFS_DEVICE_DEFAULT_IO_OPS
84 #	error "No default device io operations!  Cannot build ntfsfix.  \
85 You need to run ./configure without the --disable-default-device-io-ops \
86 switch if you want to be able to build the NTFS utilities."
87 #endif
88 
89 static const char *EXEC_NAME = "ntfsfix";
90 static const char OK[]       = "OK\n";
91 static const char FAILED[]   = "FAILED\n";
92 static const char FOUND[]    = "FOUND\n";
93 
94 #define DEFAULT_SECTOR_SIZE 512
95 
96 static struct {
97 	char *volume;
98 	BOOL no_action;
99 	BOOL clear_bad_sectors;
100 	BOOL clear_dirty;
101 } opt;
102 
103 /*
104  *		Definitions for fixing the self-located MFT bug
105  */
106 
107 #define SELFLOC_LIMIT 16
108 
109 struct MFT_SELF_LOCATED {
110 	ntfs_volume *vol;
111 	MFT_RECORD *mft0;
112 	MFT_RECORD *mft1;
113 	MFT_RECORD *mft2;
114 	ATTR_LIST_ENTRY *attrlist;
115 	ATTR_LIST_ENTRY *attrlist_to_ref1;
116 	MFT_REF mft_ref0;
117 	MFT_REF mft_ref1;
118 	LCN attrlist_lcn;
119 	BOOL attrlist_resident;
120 } ;
121 
122 /**
123  * usage
124  */
125 __attribute__((noreturn))
usage(int ret)126 static void usage(int ret)
127 {
128 	ntfs_log_info("%s v%s (libntfs-3g)\n"
129 		   "\n"
130 		   "Usage: %s [options] device\n"
131 		   "    Attempt to fix an NTFS partition.\n"
132 		   "\n"
133 		   "    -b, --clear-bad-sectors Clear the bad sector list\n"
134 		   "    -d, --clear-dirty       Clear the volume dirty flag\n"
135 		   "    -h, --help              Display this help\n"
136 		   "    -n, --no-action         Do not write anything\n"
137 		   "    -V, --version           Display version information\n"
138 		   "\n"
139 		   "For example: %s /dev/hda6\n\n",
140 		   EXEC_NAME, VERSION, EXEC_NAME,
141 		   EXEC_NAME);
142 	ntfs_log_info("%s%s", ntfs_bugs, ntfs_home);
143 	exit(ret);
144 }
145 
146 /**
147  * version
148  */
149 __attribute__((noreturn))
version(void)150 static void version(void)
151 {
152 	ntfs_log_info("%s v%s\n\n"
153 		   "Attempt to fix an NTFS partition.\n\n"
154 		   "Copyright (c) 2000-2006 Anton Altaparmakov\n"
155 		   "Copyright (c) 2002-2006 Szabolcs Szakacsits\n"
156 		   "Copyright (c) 2007      Yura Pakhuchiy\n"
157 		   "Copyright (c) 2011-2015 Jean-Pierre Andre\n\n",
158 		   EXEC_NAME, VERSION);
159 	ntfs_log_info("%s\n%s%s", ntfs_gpl, ntfs_bugs, ntfs_home);
160 	exit(0);
161 }
162 
163 /**
164  * parse_options
165  */
parse_options(int argc,char ** argv)166 static void parse_options(int argc, char **argv)
167 {
168 	int c;
169 	static const char *sopt = "-bdhnV";
170 	static const struct option lopt[] = {
171 		{ "help",		no_argument,	NULL, 'h' },
172 		{ "no-action",		no_argument,	NULL, 'n' },
173 		{ "clear-bad-sectors",	no_argument,	NULL, 'b' },
174 		{ "clear-dirty",	no_argument,	NULL, 'd' },
175 		{ "version",		no_argument,	NULL, 'V' },
176 		{ NULL, 		0, NULL, 0 }
177 	};
178 
179 	memset(&opt, 0, sizeof(opt));
180 
181 	while ((c = getopt_long(argc, argv, sopt, lopt, NULL)) != -1) {
182 		switch (c) {
183 		case 1:	/* A non-option argument */
184 			if (!opt.volume)
185 				opt.volume = argv[optind - 1];
186 			else {
187 				ntfs_log_info("ERROR: Too many arguments.\n");
188 				usage(1);
189 			}
190 			break;
191 		case 'b':
192 			opt.clear_bad_sectors = TRUE;
193 			break;
194 		case 'd':
195 			opt.clear_dirty = TRUE;
196 			break;
197 		case 'n':
198 			opt.no_action = TRUE;
199 			break;
200 		case 'h':
201 			usage(0);
202 		case '?':
203 			usage(1);
204 			/* fall through */
205 		case 'V':
206 			version();
207 		default:
208 			ntfs_log_info("ERROR: Unknown option '%s'.\n", argv[optind - 1]);
209 			usage(1);
210 		}
211 	}
212 
213 	if (opt.volume == NULL) {
214 		ntfs_log_info("ERROR: You must specify a device.\n");
215 		usage(1);
216 	}
217 }
218 
219 /**
220  * OLD_ntfs_volume_set_flags
221  */
OLD_ntfs_volume_set_flags(ntfs_volume * vol,const le16 flags)222 static int OLD_ntfs_volume_set_flags(ntfs_volume *vol, const le16 flags)
223 {
224 	MFT_RECORD *m = NULL;
225 	ATTR_RECORD *a;
226 	VOLUME_INFORMATION *c;
227 	ntfs_attr_search_ctx *ctx;
228 	int ret = -1;   /* failure */
229 
230 	if (!vol) {
231 		errno = EINVAL;
232 		return -1;
233 	}
234 	if (ntfs_file_record_read(vol, FILE_Volume, &m, NULL)) {
235 		ntfs_log_perror("Failed to read $Volume");
236 		return -1;
237 	}
238 	/* Sanity check */
239 	if (!(m->flags & MFT_RECORD_IN_USE)) {
240 		ntfs_log_error("$Volume has been deleted. Cannot handle this "
241 				"yet. Run chkdsk to fix this.\n");
242 		errno = EIO;
243 		goto err_exit;
244 	}
245 	/* Get a pointer to the volume information attribute. */
246 	ctx = ntfs_attr_get_search_ctx(NULL, m);
247 	if (!ctx) {
248 		ntfs_log_debug("Failed to allocate attribute search "
249 				"context.\n");
250 		goto err_exit;
251 	}
252 	if (ntfs_attr_lookup(AT_VOLUME_INFORMATION, AT_UNNAMED, 0,
253 			CASE_SENSITIVE, 0, NULL, 0, ctx)) {
254 		ntfs_log_error("Attribute $VOLUME_INFORMATION was not found in "
255 				"$Volume!\n");
256 		goto err_out;
257 	}
258 	a = ctx->attr;
259 	/* Sanity check. */
260 	if (a->non_resident) {
261 		ntfs_log_error("Attribute $VOLUME_INFORMATION must be resident "
262 				"(and it isn't)!\n");
263 		errno = EIO;
264 		goto err_out;
265 	}
266 	/* Get a pointer to the value of the attribute. */
267 	c = (VOLUME_INFORMATION*)(le16_to_cpu(a->value_offset) + (char*)a);
268 	/* Sanity checks. */
269 	if ((char*)c + le32_to_cpu(a->value_length) >
270 			(char*)m + le32_to_cpu(m->bytes_in_use) ||
271 			le16_to_cpu(a->value_offset) +
272 			le32_to_cpu(a->value_length) > le32_to_cpu(a->length)) {
273 		ntfs_log_error("Attribute $VOLUME_INFORMATION in $Volume is "
274 				"corrupt!\n");
275 		errno = EIO;
276 		goto err_out;
277 	}
278 	/* Set the volume flags. */
279 	vol->flags = c->flags = flags;
280 	if (ntfs_mft_record_write(vol, FILE_Volume, m)) {
281 		ntfs_log_perror("Error writing $Volume");
282 		goto err_out;
283 	}
284 	ret = 0; /* success */
285 err_out:
286 	ntfs_attr_put_search_ctx(ctx);
287 err_exit:
288 	free(m);
289 	return ret;
290 }
291 
292 /**
293  * set_dirty_flag
294  */
set_dirty_flag(ntfs_volume * vol)295 static int set_dirty_flag(ntfs_volume *vol)
296 {
297 	le16 flags;
298 
299 	/* Porting note: We test for the current state of VOLUME_IS_DIRTY. This
300 	 * should actually be more appropriate than testing for NVolWasDirty. */
301 	if (vol->flags & VOLUME_IS_DIRTY)
302 		return 0;
303 	ntfs_log_info("Setting required flags on partition... ");
304 	/*
305 	 * Set chkdsk flag, i.e. mark the partition dirty so chkdsk will run
306 	 * and fix it for us.
307 	 */
308 	flags = vol->flags | VOLUME_IS_DIRTY;
309 	if (!opt.no_action && OLD_ntfs_volume_set_flags(vol, flags)) {
310 		ntfs_log_info(FAILED);
311 		ntfs_log_error("Error setting volume flags.\n");
312 		return -1;
313 	}
314 	vol->flags = flags;
315 
316 	/* Porting note: libntfs-3g does not have the 'WasDirty' flag/property,
317 	 * and never touches the 'dirty' bit except when explicitly told to do
318 	 * so. Since we just wrote the VOLUME_IS_DIRTY bit to disk, and
319 	 * vol->flags is up-to-date, we can just ignore the NVolSetWasDirty
320 	 * statement. */
321 	/* NVolSetWasDirty(vol); */
322 
323 	ntfs_log_info(OK);
324 	return 0;
325 }
326 
327 /**
328  * empty_journal
329  */
empty_journal(ntfs_volume * vol)330 static int empty_journal(ntfs_volume *vol)
331 {
332 	if (NVolLogFileEmpty(vol))
333 		return 0;
334 	ntfs_log_info("Going to empty the journal ($LogFile)... ");
335 	if (ntfs_logfile_reset(vol)) {
336 		ntfs_log_info(FAILED);
337 		ntfs_log_perror("Failed to reset $LogFile");
338 		return -1;
339 	}
340 	ntfs_log_info(OK);
341 	return 0;
342 }
343 
344 /*
345  *		Clear the sparse flag of an attribute
346  */
347 
clear_sparse(ntfs_attr * na,const char * name)348 static int clear_sparse(ntfs_attr *na, const char *name)
349 {
350 	ntfs_attr_search_ctx *ctx;
351 	int res;
352 
353 	res = -1;
354 	ctx = ntfs_attr_get_search_ctx(na->ni, NULL);
355 	if (ctx) {
356 		if (!ntfs_attr_lookup(na->type, na->name, na->name_len,
357 				CASE_SENSITIVE,	0, NULL, 0, ctx)) {
358 			na->data_flags &= ~ATTR_IS_SPARSE;
359 			ctx->attr->data_size = cpu_to_sle64(na->data_size);
360 			ctx->attr->initialized_size
361 					= cpu_to_sle64(na->initialized_size);
362 			ctx->attr->flags = na->data_flags;
363 			ctx->attr->compression_unit = 0;
364 			ntfs_inode_mark_dirty(ctx->ntfs_ino);
365 			NInoFileNameSetDirty(na->ni);
366 			res = 0;
367 		} else
368 			ntfs_log_perror("Could not locate attribute for %s",
369 						name);
370 		ntfs_attr_put_search_ctx(ctx);
371 	} else
372 		ntfs_log_perror("Could not get a search context for %s",
373 					name);
374 	return (res);
375 }
376 
377 /**
378  *		Clear the bad cluster marks (option)
379  */
clear_badclus(ntfs_volume * vol)380 static int clear_badclus(ntfs_volume *vol)
381 {
382 	static ntfschar badstream[] = {
383 				const_cpu_to_le16('$'), const_cpu_to_le16('B'),
384 				const_cpu_to_le16('a'), const_cpu_to_le16('d')
385 	} ;
386 	ntfs_inode *ni;
387 	ntfs_attr *na;
388 	BOOL ok;
389 
390 	ok = FALSE;
391 	ntfs_log_info("Going to un-mark the bad clusters ($BadClus)... ");
392 	ni = ntfs_inode_open(vol, FILE_BadClus);
393 	if (ni) {
394 		na = ntfs_attr_open(ni, AT_DATA, badstream, 4);
395 			/*
396 			 * chkdsk does not adjust the data size when
397 			 * moving clusters to $BadClus, so we have to
398 			 * check the runlist.
399 			 */
400 		if (na && !ntfs_attr_map_whole_runlist(na)) {
401 			if (na->rl
402 			    && na->rl[0].length && na->rl[1].length) {
403 			/*
404 			 * Truncate the stream to free all its clusters,
405 			 * (which requires setting the data size according
406 			 * to allocation), then reallocate a sparse stream
407 			 * to full size of volume and reset the data size.
408 			 * Note : the sparse flags should not be set.
409 			 */
410 				na->data_size = na->allocated_size;
411 				na->initialized_size = na->allocated_size;
412 				if (!ntfs_attr_truncate(na,0)
413 				    && !ntfs_attr_truncate(na,vol->nr_clusters
414 						<< vol->cluster_size_bits)) {
415 					na->initialized_size = 0;
416 					NInoFileNameSetDirty(ni);
417 					ok = TRUE;
418 				} else {
419 					ntfs_log_perror("Failed to un-mark the bad clusters");
420 				}
421 			} else {
422 				ntfs_log_info("No bad clusters...");
423 				ok = TRUE;
424 			}
425 			/*
426 			 * The sparse flags are not set after an initial
427 			 * formatting, so do the same.
428 			 */
429 			if (ok) {
430 				ni->flags &= ~FILE_ATTR_SPARSE_FILE;
431 				ok = !clear_sparse(na, "$BadClus::$Bad");
432 			}
433 			ntfs_attr_close(na);
434 		} else {
435 			ntfs_log_perror("Failed to open $BadClus::$Bad");
436 		}
437 		ntfs_inode_close(ni);
438 	} else {
439 		ntfs_log_perror("Failed to open inode FILE_BadClus");
440 	}
441 	if (ok)
442 		ntfs_log_info(OK);
443 	return (ok ? 0 : -1);
444 }
445 
446 /**
447  * fix_mftmirr
448  */
fix_mftmirr(ntfs_volume * vol)449 static int fix_mftmirr(ntfs_volume *vol)
450 {
451 	s64 l, br;
452 	unsigned char *m, *m2;
453 	int i, ret = -1; /* failure */
454 	BOOL done;
455 
456 	ntfs_log_info("\nProcessing $MFT and $MFTMirr...\n");
457 
458 	/* Load data from $MFT and $MFTMirr and compare the contents. */
459 	m = (u8*)malloc(vol->mftmirr_size << vol->mft_record_size_bits);
460 	if (!m) {
461 		ntfs_log_perror("Failed to allocate memory");
462 		return -1;
463 	}
464 	m2 = (u8*)malloc(vol->mftmirr_size << vol->mft_record_size_bits);
465 	if (!m2) {
466 		ntfs_log_perror("Failed to allocate memory");
467 		free(m);
468 		return -1;
469 	}
470 
471 	ntfs_log_info("Reading $MFT... ");
472 	l = ntfs_attr_mst_pread(vol->mft_na, 0, vol->mftmirr_size,
473 			vol->mft_record_size, m);
474 	if (l != vol->mftmirr_size) {
475 		ntfs_log_info(FAILED);
476 		if (l != -1)
477 			errno = EIO;
478 		ntfs_log_perror("Failed to read $MFT");
479 		goto error_exit;
480 	}
481 	ntfs_log_info(OK);
482 
483 	ntfs_log_info("Reading $MFTMirr... ");
484 	l = ntfs_attr_mst_pread(vol->mftmirr_na, 0, vol->mftmirr_size,
485 			vol->mft_record_size, m2);
486 	if (l != vol->mftmirr_size) {
487 		ntfs_log_info(FAILED);
488 		if (l != -1)
489 			errno = EIO;
490 		ntfs_log_perror("Failed to read $MFTMirr");
491 		goto error_exit;
492 	}
493 	ntfs_log_info(OK);
494 
495 	/*
496 	 * FIXME: Need to actually check the $MFTMirr for being real. Otherwise
497 	 * we might corrupt the partition if someone is experimenting with
498 	 * software RAID and the $MFTMirr is not actually in the position we
499 	 * expect it to be... )-:
500 	 * FIXME: We should emit a warning it $MFTMirr is damaged and ask
501 	 * user whether to recreate it from $MFT or whether to abort. - The
502 	 * warning needs to include the danger of software RAID arrays.
503 	 * Maybe we should go as far as to detect whether we are running on a
504 	 * MD disk and if yes then bomb out right at the start of the program?
505 	 */
506 
507 	ntfs_log_info("Comparing $MFTMirr to $MFT... ");
508 	done = FALSE;
509 	/*
510 	 * Since 2017, Windows 10 does not mirror to full $MFTMirr when
511 	 * using big clusters, and some records may be found different.
512 	 * Nevertheless chkdsk.exe mirrors it fully, so we do similarly.
513 	 */
514 	for (i = 0; i < vol->mftmirr_size; ++i) {
515 		MFT_RECORD *mrec, *mrec2;
516 		const char *ESTR[12] = { "$MFT", "$MFTMirr", "$LogFile",
517 			"$Volume", "$AttrDef", "root directory", "$Bitmap",
518 			"$Boot", "$BadClus", "$Secure", "$UpCase", "$Extend" };
519 		const char *s;
520 		BOOL use_mirr;
521 
522 		if (i < 12)
523 			s = ESTR[i];
524 		else if (i < 16)
525 			s = "system file";
526 		else
527 			s = "mft record";
528 
529 		use_mirr = FALSE;
530 		mrec = (MFT_RECORD*)(m + i * vol->mft_record_size);
531 		if (mrec->flags & MFT_RECORD_IN_USE) {
532 			if (ntfs_is_baad_record(mrec->magic)) {
533 				ntfs_log_info(FAILED);
534 				ntfs_log_error("$MFT error: Incomplete multi "
535 						"sector transfer detected in "
536 						"%s.\nCannot handle this yet. "
537 						")-:\n", s);
538 				goto error_exit;
539 			}
540 			if (!ntfs_is_mft_record(mrec->magic)) {
541 				ntfs_log_info(FAILED);
542 				ntfs_log_error("$MFT error: Invalid mft "
543 						"record for %s.\nCannot "
544 						"handle this yet. )-:\n", s);
545 				goto error_exit;
546 			}
547 		}
548 		mrec2 = (MFT_RECORD*)(m2 + i * vol->mft_record_size);
549 		if (mrec2->flags & MFT_RECORD_IN_USE) {
550 			if (ntfs_is_baad_record(mrec2->magic)) {
551 				ntfs_log_info(FAILED);
552 				ntfs_log_error("$MFTMirr error: Incomplete "
553 						"multi sector transfer "
554 						"detected in %s.\n", s);
555 				goto error_exit;
556 			}
557 			if (!ntfs_is_mft_record(mrec2->magic)) {
558 				ntfs_log_info(FAILED);
559 				ntfs_log_error("$MFTMirr error: Invalid mft "
560 						"record for %s.\n", s);
561 				goto error_exit;
562 			}
563 			/* $MFT is corrupt but $MFTMirr is ok, use $MFTMirr. */
564 			if (!(mrec->flags & MFT_RECORD_IN_USE) &&
565 					!ntfs_is_mft_record(mrec->magic))
566 				use_mirr = TRUE;
567 		}
568 		if (memcmp(mrec, mrec2, ntfs_mft_record_get_data_size(mrec))) {
569 			if (!done) {
570 				done = TRUE;
571 				ntfs_log_info(FAILED);
572 			}
573 			ntfs_log_info("Correcting differences in $MFT%s "
574 					"record %d...", use_mirr ? "" : "Mirr",
575 					i);
576 			br = ntfs_mft_record_write(vol, i,
577 					use_mirr ? mrec2 : mrec);
578 			if (br) {
579 				ntfs_log_info(FAILED);
580 				ntfs_log_perror("Error correcting $MFT%s",
581 						use_mirr ? "" : "Mirr");
582 				goto error_exit;
583 			}
584 			ntfs_log_info(OK);
585 		}
586 	}
587 	if (!done)
588 		ntfs_log_info(OK);
589 	ntfs_log_info("Processing of $MFT and $MFTMirr completed "
590 			"successfully.\n");
591 	ret = 0;
592 error_exit:
593 	free(m);
594 	free(m2);
595 	return ret;
596 }
597 
598 /*
599  *		Rewrite the $UpCase file as default
600  *
601  *	Returns 0 if could be written
602  */
603 
rewrite_upcase(ntfs_volume * vol,ntfs_attr * na)604 static int rewrite_upcase(ntfs_volume *vol, ntfs_attr *na)
605 {
606 	s64 l;
607 	int res;
608 
609 		/* writing the $UpCase may require bitmap updates */
610 	res = -1;
611 	vol->lcnbmp_ni = ntfs_inode_open(vol, FILE_Bitmap);
612 	if (!vol->lcnbmp_ni) {
613 		ntfs_log_perror("Failed to open bitmap inode");
614 	} else {
615 		vol->lcnbmp_na = ntfs_attr_open(vol->lcnbmp_ni, AT_DATA,
616 					AT_UNNAMED, 0);
617 		if (!vol->lcnbmp_na) {
618 			ntfs_log_perror("Failed to open bitmap data attribute");
619 		} else {
620 			/* minimal consistency check on the bitmap */
621 			if (((vol->lcnbmp_na->data_size << 3)
622 				< vol->nr_clusters)
623 			    || ((vol->lcnbmp_na->data_size << 3)
624 				>= (vol->nr_clusters << 1))
625 			    || (vol->lcnbmp_na->data_size
626 					> vol->lcnbmp_na->allocated_size)) {
627 				ntfs_log_error("Corrupt cluster map size %lld"
628 					" (allocated %lld minimum %lld)\n",
629 					(long long)vol->lcnbmp_na->data_size,
630 					(long long)vol->lcnbmp_na->allocated_size,
631 					(long long)(vol->nr_clusters + 7) >> 3);
632 			} else {
633 				ntfs_log_info("Rewriting $UpCase file\n");
634 				l = ntfs_attr_pwrite(na, 0, vol->upcase_len*2,
635 							vol->upcase);
636 				if (l != vol->upcase_len*2) {
637 					ntfs_log_error("Failed to rewrite $UpCase\n");
638 				} else {
639 					ntfs_log_info("$UpCase has been set to default\n");
640 					res = 0;
641 				}
642 			}
643 			ntfs_attr_close(vol->lcnbmp_na);
644 			vol->lcnbmp_na = (ntfs_attr*)NULL;
645 		}
646 		ntfs_inode_close(vol->lcnbmp_ni);
647 		vol->lcnbmp_ni = (ntfs_inode*)NULL;
648 	}
649 	return (res);
650 }
651 
652 /*
653  *		Fix the $UpCase file
654  *
655  *	Returns 0 if the table is valid or has been fixed
656  */
657 
fix_upcase(ntfs_volume * vol)658 static int fix_upcase(ntfs_volume *vol)
659 {
660 	ntfs_inode *ni;
661 	ntfs_attr *na;
662 	ntfschar *upcase;
663 	s64 l;
664 	u32 upcase_len;
665 	u32 k;
666 	int res;
667 
668 	res = -1;
669 	ni = (ntfs_inode*)NULL;
670 	na = (ntfs_attr*)NULL;
671 	/* Now load the upcase table from $UpCase. */
672 	ntfs_log_debug("Loading $UpCase...\n");
673 	ni = ntfs_inode_open(vol, FILE_UpCase);
674 	if (!ni) {
675 		ntfs_log_perror("Failed to open inode FILE_UpCase");
676 		goto error_exit;
677 	}
678 	/* Get an ntfs attribute for $UpCase/$DATA. */
679 	na = ntfs_attr_open(ni, AT_DATA, AT_UNNAMED, 0);
680 	if (!na) {
681 		ntfs_log_perror("Failed to open ntfs attribute");
682 		goto error_exit;
683 	}
684 	/*
685 	 * Note: Normally, the upcase table has a length equal to 65536
686 	 * 2-byte Unicode characters but allow for different cases, so no
687 	 * checks done. Just check we don't overflow 32-bits worth of Unicode
688 	 * characters.
689 	 */
690 	if (na->data_size & ~0x1ffffffffULL) {
691 		ntfs_log_error("Error: Upcase table is too big (max 32-bit "
692 				"allowed).\n");
693 		errno = EINVAL;
694 		goto error_exit;
695 	}
696 	upcase_len = na->data_size >> 1;
697 	upcase = (ntfschar*)ntfs_malloc(na->data_size);
698 	if (!upcase)
699 		goto error_exit;
700 	/* Read in the $DATA attribute value into the buffer. */
701 	l = ntfs_attr_pread(na, 0, na->data_size, upcase);
702 	if (l != na->data_size) {
703 		ntfs_log_error("Failed to read $UpCase, unexpected length "
704 			       "(%lld != %lld).\n", (long long)l,
705 			       (long long)na->data_size);
706 		errno = EIO;
707 		goto error_exit;
708 	}
709 	/* Consistency check of $UpCase, restricted to plain ASCII chars */
710 	k = 0x20;
711 	while ((k < upcase_len)
712 	    && (k < 0x7f)
713 	    && (le16_to_cpu(upcase[k])
714 			== ((k < 'a') || (k > 'z') ? k : k + 'A' - 'a')))
715 		k++;
716 	if (k < 0x7f) {
717 		ntfs_log_error("Corrupted file $UpCase\n");
718 		if (!opt.no_action) {
719 			/* rewrite the $UpCase file from default */
720 			res = rewrite_upcase(vol, na);
721 			/* free the bad upcase record */
722 			if (!res)
723 				free(upcase);
724 		} else {
725 			/* keep the default upcase but return an error */
726 			free(upcase);
727 		}
728 	} else {
729 			/* accept the upcase table read from $UpCase */
730 		free(vol->upcase);
731 		vol->upcase = upcase;
732 		vol->upcase_len = upcase_len;
733 		res = 0;
734 	}
735 error_exit :
736 	/* Done with the $UpCase mft record. */
737 	if (na)
738 		ntfs_attr_close(na);
739 	if (ni && ntfs_inode_close(ni)) {
740 		ntfs_log_perror("Failed to close $UpCase");
741 	}
742 	return (res);
743 }
744 
745 /*
746  *		Rewrite the boot sector
747  *
748  *	Returns 0 if successful
749  */
750 
rewrite_boot(struct ntfs_device * dev,char * full_bs,s32 sector_size)751 static int rewrite_boot(struct ntfs_device *dev, char *full_bs,
752 				s32 sector_size)
753 {
754 	s64 bw;
755 	int res;
756 
757 	res = -1;
758 	ntfs_log_info("Rewriting the bootsector\n");
759 	bw = ntfs_pwrite(dev, 0, sector_size, full_bs);
760 	if (bw == sector_size)
761 		res = 0;
762 	else {
763 		if (bw != -1)
764 			errno = EINVAL;
765 		if (!bw)
766 			ntfs_log_error("Failed to rewrite the bootsector (size=0)\n");
767 		else
768 			ntfs_log_perror("Error rewriting the bootsector");
769 	}
770 	return (res);
771 }
772 
773 /*
774  *		Locate an unnamed attribute in an MFT record
775  *
776  *	Returns NULL if not found (with no error message)
777  */
778 
find_unnamed_attr(MFT_RECORD * mrec,ATTR_TYPES type)779 static ATTR_RECORD *find_unnamed_attr(MFT_RECORD *mrec, ATTR_TYPES type)
780 {
781 	ATTR_RECORD *a;
782 	u32 offset;
783 	s32 space;
784 
785 			/* fetch the requested attribute */
786 	offset = le16_to_cpu(mrec->attrs_offset);
787 	space = le32_to_cpu(mrec->bytes_in_use) - offset;
788 	a = (ATTR_RECORD*)((char*)mrec + offset);
789 	while ((space >= (s32)offsetof(ATTR_RECORD, resident_end))
790 	    && (a->type != AT_END)
791 	    && (le32_to_cpu(a->length) <= (u32)space)
792 	    && !(le32_to_cpu(a->length) & 7)
793 	    && ((a->type != type) || a->name_length)) {
794 		offset += le32_to_cpu(a->length);
795 		space -= le32_to_cpu(a->length);
796 		a = (ATTR_RECORD*)((char*)mrec + offset);
797 	}
798 	if ((offset >= le32_to_cpu(mrec->bytes_in_use))
799 	    || (a->type != type)
800 	    || a->name_length)
801 		a = (ATTR_RECORD*)NULL;
802 	return (a);
803 }
804 
805 /*
806  *		First condition for having a self-located MFT :
807  *		only 16 MFT records are defined in MFT record 0
808  *
809  *	Only low-level library functions can be used.
810  *
811  *	Returns TRUE if the condition is met.
812  */
813 
short_mft_selfloc_condition(struct MFT_SELF_LOCATED * selfloc)814 static BOOL short_mft_selfloc_condition(struct MFT_SELF_LOCATED *selfloc)
815 {
816 	BOOL ok;
817 	ntfs_volume *vol;
818 	MFT_RECORD *mft0;
819 	ATTR_RECORD *a;
820 	runlist_element *rl;
821 	u16 seqn;
822 
823 	ok = FALSE;
824 	vol = selfloc->vol;
825 	mft0 = selfloc->mft0;
826 	if ((ntfs_pread(vol->dev,
827 			vol->mft_lcn << vol->cluster_size_bits,
828 			vol->mft_record_size, mft0)
829 				== vol->mft_record_size)
830 	    && !ntfs_mst_post_read_fixup((NTFS_RECORD*)mft0,
831 			vol->mft_record_size)
832 	    && !ntfs_mft_record_check(vol, 0, mft0)) {
833 		a = find_unnamed_attr(mft0,AT_DATA);
834 		if (a
835 		    && a->non_resident
836 		    && (((sle64_to_cpu(a->highest_vcn) + 1)
837 					<< vol->cluster_size_bits)
838 				== (SELFLOC_LIMIT*vol->mft_record_size))) {
839 			rl = ntfs_mapping_pairs_decompress(vol, a, NULL);
840 			if (rl) {
841 				/*
842 				 * The first error condition is having only
843 				 * 16 entries mapped in the first MFT record.
844 				 */
845 				if ((rl[0].lcn >= 0)
846 				  && ((rl[0].length << vol->cluster_size_bits)
847 					== SELFLOC_LIMIT*vol->mft_record_size)
848 				  && (rl[1].vcn == rl[0].length)
849 				  && (rl[1].lcn == LCN_RL_NOT_MAPPED)) {
850 					ok = TRUE;
851 					seqn = le16_to_cpu(
852 						mft0->sequence_number);
853 					selfloc->mft_ref0
854 						= ((MFT_REF)seqn) << 48;
855 				}
856 				free(rl);
857 			}
858 		}
859 	}
860 	return (ok);
861 }
862 
863 /*
864  *		Second condition for having a self-located MFT :
865  *		The 16th MFT record is defined in MFT record >= 16
866  *
867  *	Only low-level library functions can be used.
868  *
869  *	Returns TRUE if the condition is met.
870  */
871 
attrlist_selfloc_condition(struct MFT_SELF_LOCATED * selfloc)872 static BOOL attrlist_selfloc_condition(struct MFT_SELF_LOCATED *selfloc)
873 {
874 	ntfs_volume *vol;
875 	ATTR_RECORD *a;
876 	ATTR_LIST_ENTRY *attrlist;
877 	ATTR_LIST_ENTRY *al;
878 	runlist_element *rl;
879 	VCN vcn;
880 	leVCN levcn;
881 	u32 length;
882 	int ok;
883 
884 	ok = FALSE;
885 	length = 0;
886 	vol = selfloc->vol;
887 	a = find_unnamed_attr(selfloc->mft0,AT_ATTRIBUTE_LIST);
888 	if (a) {
889 		selfloc->attrlist_resident = !a->non_resident;
890 		selfloc->attrlist_lcn = 0;
891 		if (a->non_resident) {
892 			attrlist = selfloc->attrlist;
893 			rl = ntfs_mapping_pairs_decompress(vol, a, NULL);
894 			if (rl
895 			    && (rl->lcn >= 0)
896 			    && (sle64_to_cpu(a->data_size) < vol->cluster_size)
897 			    && (ntfs_pread(vol->dev,
898 					rl->lcn << vol->cluster_size_bits,
899 					vol->cluster_size, attrlist) == vol->cluster_size)) {
900 				selfloc->attrlist_lcn = rl->lcn;
901 				al = attrlist;
902 				length = sle64_to_cpu(a->data_size);
903 			}
904 		} else {
905 			al = (ATTR_LIST_ENTRY*)
906 				((char*)a + le16_to_cpu(a->value_offset));
907 			length = le32_to_cpu(a->value_length);
908 		}
909 		if (length) {
910 			/* search for a data attribute defining entry 16 */
911 			vcn = (SELFLOC_LIMIT*vol->mft_record_size)
912 					>> vol->cluster_size_bits;
913 			levcn = cpu_to_sle64(vcn);
914 			while ((length > 0)
915 			    && al->length
916 			    && ((al->type != AT_DATA)
917 				|| ((leVCN)al->lowest_vcn != levcn))) {
918 				length -= le16_to_cpu(al->length);
919 				al = (ATTR_LIST_ENTRY*)
920 					((char*)al + le16_to_cpu(al->length));
921 			}
922 			if ((length > 0)
923 			    && al->length
924 			    && (al->type == AT_DATA)
925 			    && !al->name_length
926 			    && ((leVCN)al->lowest_vcn == levcn)
927 			    && (MREF_LE(al->mft_reference) >= SELFLOC_LIMIT)) {
928 				selfloc->mft_ref1
929 					= le64_to_cpu(al->mft_reference);
930 				selfloc->attrlist_to_ref1 = al;
931 				ok = TRUE;
932 			}
933 		}
934 	}
935 	return (ok);
936 }
937 
938 /*
939  *		Third condition for having a self-located MFT :
940  *		The location of the second part of the MFT is defined in itself
941  *
942  *	To locate the second part, we have to assume the first and the
943  *	second part of the MFT data are contiguous.
944  *
945  *	Only low-level library functions can be used.
946  *
947  *	Returns TRUE if the condition is met.
948  */
949 
self_mapped_selfloc_condition(struct MFT_SELF_LOCATED * selfloc)950 static BOOL self_mapped_selfloc_condition(struct MFT_SELF_LOCATED *selfloc)
951 {
952 	BOOL ok;
953 	s64 inum;
954 	u64 offs;
955 	VCN lowest_vcn;
956 	MFT_RECORD *mft1;
957 	ATTR_RECORD *a;
958 	ntfs_volume *vol;
959 	runlist_element *rl;
960 
961 	ok = FALSE;
962 	vol = selfloc->vol;
963 	mft1 = selfloc->mft1;
964 	inum = MREF(selfloc->mft_ref1);
965 	offs = 	(vol->mft_lcn << vol->cluster_size_bits)
966 			+ (inum << vol->mft_record_size_bits);
967 	if ((ntfs_pread(vol->dev, offs, vol->mft_record_size,
968 			mft1) == vol->mft_record_size)
969 	    && !ntfs_mst_post_read_fixup((NTFS_RECORD*)mft1,
970 			vol->mft_record_size)
971 	    && !ntfs_mft_record_check(vol, inum, mft1)) {
972 
973 		lowest_vcn = (SELFLOC_LIMIT*vol->mft_record_size)
974 				>> vol->cluster_size_bits;
975 		a = find_unnamed_attr(mft1,AT_DATA);
976 		if (a
977 		    && (mft1->flags & MFT_RECORD_IN_USE)
978 		    && ((VCN)sle64_to_cpu(a->lowest_vcn) == lowest_vcn)
979 		    && (le64_to_cpu(mft1->base_mft_record)
980 				== selfloc->mft_ref0)
981 		    && ((u16)MSEQNO(selfloc->mft_ref1)
982 				== le16_to_cpu(mft1->sequence_number))) {
983 			rl = ntfs_mapping_pairs_decompress(vol, a, NULL);
984 			if ((rl[0].lcn == LCN_RL_NOT_MAPPED)
985 			   && !rl[0].vcn
986 			   && (rl[0].length == lowest_vcn)
987 			   && (rl[1].vcn == lowest_vcn)
988 			   && ((u64)(rl[1].lcn << vol->cluster_size_bits)
989 					<= offs)
990 			   && ((u64)((rl[1].lcn + rl[1].length)
991 					<< vol->cluster_size_bits) > offs)) {
992 				ok = TRUE;
993 			}
994 		}
995 	}
996 	return (ok);
997 }
998 
999 /*
1000  *		Fourth condition, to be able to fix a self-located MFT :
1001  *		The MFT record 15 must be available.
1002  *
1003  *	The MFT record 15 is expected to be marked in use, we assume
1004  *	it is available if it has no parent, no name and no attr list.
1005  *
1006  *	Only low-level library functions can be used.
1007  *
1008  *	Returns TRUE if the condition is met.
1009  */
1010 
spare_record_selfloc_condition(struct MFT_SELF_LOCATED * selfloc)1011 static BOOL spare_record_selfloc_condition(struct MFT_SELF_LOCATED *selfloc)
1012 {
1013 	BOOL ok;
1014 	s64 inum;
1015 	u64 offs;
1016 	MFT_RECORD *mft2;
1017 	ntfs_volume *vol;
1018 
1019 	ok = FALSE;
1020 	vol = selfloc->vol;
1021 	mft2 = selfloc->mft2;
1022 	inum = SELFLOC_LIMIT - 1;
1023 	offs = 	(vol->mft_lcn << vol->cluster_size_bits)
1024 			+ (inum << vol->mft_record_size_bits);
1025 	if ((ntfs_pread(vol->dev, offs, vol->mft_record_size,
1026 			mft2) == vol->mft_record_size)
1027 	    && !ntfs_mst_post_read_fixup((NTFS_RECORD*)mft2,
1028 			vol->mft_record_size)
1029 	    && !ntfs_mft_record_check(vol, inum, mft2)) {
1030 		if (!mft2->base_mft_record
1031 		    && (mft2->flags & MFT_RECORD_IN_USE)
1032 		    && !find_unnamed_attr(mft2,AT_ATTRIBUTE_LIST)
1033 		    && !find_unnamed_attr(mft2,AT_FILE_NAME)) {
1034 			ok = TRUE;
1035 		}
1036 	}
1037 	return (ok);
1038 }
1039 
1040 /*
1041  *		Fix a self-located MFT by swapping two MFT records
1042  *
1043  *	Only low-level library functions can be used.
1044  *
1045  *	Returns 0 if the MFT corruption could be fixed.
1046  */
fix_selfloc_conditions(struct MFT_SELF_LOCATED * selfloc)1047 static int fix_selfloc_conditions(struct MFT_SELF_LOCATED *selfloc)
1048 {
1049 	MFT_RECORD *mft1;
1050 	MFT_RECORD *mft2;
1051 	ATTR_RECORD *a;
1052 	ATTR_LIST_ENTRY *al;
1053 	ntfs_volume *vol;
1054 	s64 offs;
1055 	s64 offsm;
1056 	s64 offs1;
1057 	s64 offs2;
1058 	s64 inum;
1059 	u16 usa_ofs;
1060 	int res;
1061 
1062 	res = 0;
1063 			/*
1064 			 * In MFT1, we must fix :
1065 			 * - the self-reference, if present,
1066 			 * - its own sequence number, must be 15
1067 			 * - the sizes of the data attribute.
1068 			 */
1069 	vol = selfloc->vol;
1070 	mft1 = selfloc->mft1;
1071 	mft2 = selfloc->mft2;
1072 	usa_ofs = le16_to_cpu(mft1->usa_ofs);
1073 	if (usa_ofs >= 48)
1074 		mft1->mft_record_number = const_cpu_to_le32(SELFLOC_LIMIT - 1);
1075 	mft1->sequence_number = const_cpu_to_le16(SELFLOC_LIMIT - 1);
1076 	a = find_unnamed_attr(mft1,AT_DATA);
1077 	if (a) {
1078 		a->allocated_size = const_cpu_to_sle64(0);
1079 		a->data_size = const_cpu_to_sle64(0);
1080 		a->initialized_size = const_cpu_to_sle64(0);
1081 	} else
1082 		res = -1; /* bug : it has been found earlier */
1083 
1084 			/*
1085 			 * In MFT2, we must fix :
1086 			 * - the self-reference, if present
1087 			 */
1088 	usa_ofs = le16_to_cpu(mft2->usa_ofs);
1089 	if (usa_ofs >= 48)
1090 		mft2->mft_record_number = cpu_to_le32(MREF(selfloc->mft_ref1));
1091 
1092 			/*
1093 			 * In the attribute list, we must fix :
1094 			 * - the reference to MFT1
1095 			 */
1096 	al = selfloc->attrlist_to_ref1;
1097 	al->mft_reference = MK_LE_MREF(SELFLOC_LIMIT - 1, SELFLOC_LIMIT - 1);
1098 
1099 			/*
1100 			 * All fixes done, we can write all if allowed
1101 			 */
1102 	if (!res && !opt.no_action) {
1103 		inum = SELFLOC_LIMIT - 1;
1104 		offs2 = (vol->mft_lcn << vol->cluster_size_bits)
1105 			+ (inum << vol->mft_record_size_bits);
1106 		inum = MREF(selfloc->mft_ref1);
1107 		offs1 = (vol->mft_lcn << vol->cluster_size_bits)
1108 			+ (inum << vol->mft_record_size_bits);
1109 
1110 			/* rewrite the attribute list */
1111 		if (selfloc->attrlist_resident) {
1112 				/* write mft0 and mftmirr if it is resident */
1113 			offs = vol->mft_lcn << vol->cluster_size_bits;
1114 			offsm = vol->mftmirr_lcn << vol->cluster_size_bits;
1115 			if (ntfs_mst_pre_write_fixup(
1116 					(NTFS_RECORD*)selfloc->mft0,
1117 					vol->mft_record_size)
1118 			    || (ntfs_pwrite(vol->dev, offs, vol->mft_record_size,
1119 					selfloc->mft0) != vol->mft_record_size)
1120 			    || (ntfs_pwrite(vol->dev, offsm, vol->mft_record_size,
1121 					selfloc->mft0) != vol->mft_record_size))
1122 				res = -1;
1123 		} else {
1124 				/* write a full cluster if non resident */
1125 			offs = selfloc->attrlist_lcn << vol->cluster_size_bits;
1126 			if (ntfs_pwrite(vol->dev, offs, vol->cluster_size,
1127 					selfloc->attrlist) != vol->cluster_size)
1128 				res = -1;
1129 		}
1130 			/* replace MFT2 by MFT1 and replace MFT1 by MFT2 */
1131 		if (!res
1132 		    && (ntfs_mst_pre_write_fixup((NTFS_RECORD*)selfloc->mft1,
1133 					vol->mft_record_size)
1134 			|| ntfs_mst_pre_write_fixup((NTFS_RECORD*)selfloc->mft2,
1135 					vol->mft_record_size)
1136 			|| (ntfs_pwrite(vol->dev, offs2, vol->mft_record_size,
1137 					mft1) != vol->mft_record_size)
1138 			|| (ntfs_pwrite(vol->dev, offs1, vol->mft_record_size,
1139 					mft2) != vol->mft_record_size)))
1140 				res = -1;
1141 	}
1142 	return (res);
1143 }
1144 
1145 /*
1146  *		Detect and fix a Windows XP bug, leading to a corrupt MFT
1147  *
1148  *	Windows cannot boot anymore, so chkdsk cannot be started, which
1149  *	is a good point, because chkdsk would have deleted all the files.
1150  *	Older ntfs-3g fell into an endless recursion (recent versions
1151  *	refuse to mount).
1152  *
1153  *	This situation is very rare, but it was fun to fix it.
1154  *
1155  *	The corrupted condition is :
1156  *		- MFT entry 0 has only the runlist for MFT entries 0-15
1157  *		- The attribute list for MFT shows the second part
1158  *			in an MFT record beyond 15
1159  *	Of course, this record has to be read in order to know where it is.
1160  *
1161  *	Sample case, met in 2011 (Windows XP) :
1162  *		MFT record 0 has : stdinfo, nonres attrlist, the first
1163  *				part of MFT data (entries 0-15), and bitmap
1164  *		MFT record 16 has the name
1165  *		MFT record 17 has the third part of MFT data (16-117731)
1166  *		MFT record 18 has the second part of MFT data (117732-170908)
1167  *
1168  *	Assuming the second part of the MFT is contiguous to the first
1169  *	part, we can find it, and fix the condition by relocating it
1170  *	and swapping it with MFT record 15.
1171  *	This record number 15 appears to be hardcoded into Windows NTFS.
1172  *
1173  *	Only low-level library functions can be used.
1174  *
1175  *	Returns 0 if the conditions for the error was met and
1176  *			this error could be fixed,
1177  *		-1 if the condition was not met or some error
1178  *			which could not be fixed was encountered.
1179  */
1180 
fix_self_located_mft(ntfs_volume * vol)1181 static int fix_self_located_mft(ntfs_volume *vol)
1182 {
1183 	struct MFT_SELF_LOCATED selfloc;
1184 	BOOL res;
1185 
1186 	ntfs_log_info("Checking for self-located MFT segment... ");
1187 	res = -1;
1188 	selfloc.vol = vol;
1189 	selfloc.mft0 = (MFT_RECORD*)malloc(vol->mft_record_size);
1190 	selfloc.mft1 = (MFT_RECORD*)malloc(vol->mft_record_size);
1191 	selfloc.mft2 = (MFT_RECORD*)malloc(vol->mft_record_size);
1192 	selfloc.attrlist = (ATTR_LIST_ENTRY*)malloc(vol->cluster_size);
1193 	if (selfloc.mft0 && selfloc.mft1 && selfloc.mft2
1194 	    && selfloc.attrlist) {
1195 		if (short_mft_selfloc_condition(&selfloc)
1196 		    && attrlist_selfloc_condition(&selfloc)
1197 		    && self_mapped_selfloc_condition(&selfloc)
1198 		    && spare_record_selfloc_condition(&selfloc)) {
1199 			ntfs_log_info(FOUND);
1200 			ntfs_log_info("Fixing the self-located MFT segment... ");
1201 			res = fix_selfloc_conditions(&selfloc);
1202 			ntfs_log_info(res ? FAILED : OK);
1203 		} else {
1204 			ntfs_log_info(OK);
1205 			res = -1;
1206 		}
1207 		free(selfloc.mft0);
1208 		free(selfloc.mft1);
1209 		free(selfloc.mft2);
1210 		free(selfloc.attrlist);
1211 	}
1212 	return (res);
1213 }
1214 
1215 /*
1216  *		Try an alternate boot sector and fix the real one
1217  *
1218  *	Only after successful checks is the boot sector rewritten.
1219  *
1220  *	The alternate boot sector is not rewritten, either because it
1221  *	was found correct, or because we truncated the file system
1222  *	and the last actual sector might be part of some file.
1223  *
1224  *	Returns 0 if successful
1225  */
1226 
try_fix_boot(ntfs_volume * vol,char * full_bs,s64 read_sector,s64 fix_sectors,s32 sector_size)1227 static int try_fix_boot(ntfs_volume *vol, char *full_bs,
1228 			s64 read_sector, s64 fix_sectors, s32 sector_size)
1229 {
1230 	s64 br;
1231 	int res;
1232 	s64 got_sectors;
1233 	le16 sector_size_le;
1234 	NTFS_BOOT_SECTOR *bs;
1235 
1236 	res = -1;
1237 	br = ntfs_pread(vol->dev, read_sector*sector_size,
1238 					sector_size, full_bs);
1239 	if (br != sector_size) {
1240 		if (br != -1)
1241 			errno = EINVAL;
1242 		if (!br)
1243 			ntfs_log_error("Failed to read alternate bootsector (size=0)\n");
1244 		else
1245 			ntfs_log_perror("Error reading alternate bootsector");
1246 	} else {
1247 		bs = (NTFS_BOOT_SECTOR*)full_bs;
1248 		got_sectors = sle64_to_cpu(bs->number_of_sectors);
1249 		bs->number_of_sectors = cpu_to_sle64(fix_sectors);
1250 		/* alignment problem on Sparc, even doing memcpy() */
1251 		sector_size_le = cpu_to_le16(sector_size);
1252 		if (!memcmp(&sector_size_le, &bs->bpb.bytes_per_sector,2)
1253 		    && ntfs_boot_sector_is_ntfs(bs)
1254 		    && !ntfs_boot_sector_parse(vol, bs)) {
1255 			ntfs_log_info("The alternate bootsector is usable\n");
1256 			if (fix_sectors != got_sectors)
1257 				ntfs_log_info("Set sector count to %lld instead of %lld\n",
1258 						(long long)fix_sectors,
1259 						(long long)got_sectors);
1260 			/* fix the normal boot sector */
1261 			if (!opt.no_action) {
1262 				res = rewrite_boot(vol->dev, full_bs,
1263 							sector_size);
1264 			} else
1265 				res = 0;
1266 		}
1267 		if (!res && !opt.no_action)
1268 			ntfs_log_info("The boot sector has been rewritten\n");
1269 	}
1270 	return (res);
1271 }
1272 
1273 /*
1274  *		Try the alternate boot sector if the normal one is bad
1275  *
1276  *	Actually :
1277  *	- first try the last sector of the partition (expected location)
1278  *	- then try the last sector as shown in the main boot sector,
1279  *		(could be meaningful for an undersized partition)
1280  *	- finally try truncating the file system actual size of partition
1281  *		(could be meaningful for an oversized partition)
1282  *
1283  *	if successful, rewrite the normal boot sector accordingly
1284  *
1285  *	Returns 0 if successful
1286  */
1287 
try_alternate_boot(ntfs_volume * vol,char * full_bs,s32 sector_size,s64 shown_sectors)1288 static int try_alternate_boot(ntfs_volume *vol, char *full_bs,
1289 			s32 sector_size, s64 shown_sectors)
1290 {
1291 	s64 actual_sectors;
1292 	int res;
1293 
1294 	res = -1;
1295 	ntfs_log_info("Trying the alternate boot sector\n");
1296 
1297 		/*
1298 		 * We do not rely on the sector size defined in the
1299 		 * boot sector, supposed to be corrupt, so we try to get
1300 		 * the actual sector size and defaulting to 512 if failed
1301 		 * to get. This value is only used to guess the alternate
1302 		 * boot sector location and it is checked against the
1303 		 * value found in the sector itself. It should not damage
1304 		 * anything if wrong.
1305 		 *
1306 		 * Note : the real last sector is not accounted for here.
1307 		 */
1308 	actual_sectors = ntfs_device_size_get(vol->dev,sector_size) - 1;
1309 
1310 		/* first try the actual last sector */
1311 	if ((actual_sectors > 0)
1312 	    && !try_fix_boot(vol, full_bs, actual_sectors,
1313 				actual_sectors, sector_size))
1314 		res = 0;
1315 
1316 		/* then try the shown last sector, if less than actual */
1317 	if (res
1318 	    && (shown_sectors > 0)
1319 	    && (shown_sectors < actual_sectors)
1320 	    && !try_fix_boot(vol, full_bs, shown_sectors,
1321 				shown_sectors, sector_size))
1322 		res = 0;
1323 
1324 		/* then try reducing the number of sectors to actual value */
1325 	if (res
1326 	    && (shown_sectors > actual_sectors)
1327 	    && !try_fix_boot(vol, full_bs, 0, actual_sectors, sector_size))
1328 		res = 0;
1329 
1330 	return (res);
1331 }
1332 
1333 /*
1334  *		Check and fix the alternate boot sector
1335  *
1336  *	The alternate boot sector is usually in the last sector of a
1337  *	partition, which should not be used by the file system
1338  *	(the sector count in the boot sector should be less than
1339  *	the total sector count in the partition).
1340  *
1341  *	chkdsk never changes the count in the boot sector.
1342  *	- If this is less than the total count, chkdsk place the
1343  *	  alternate boot sector into the sector,
1344  *	- if the count is the same as the total count, chkdsk place
1345  *	  the alternate boot sector into the middle sector (half
1346  *	  the total count rounded upwards)
1347  *	- if the count is greater than the total count, chkdsk
1348  *	  declares the file system as raw, and refuses to fix anything.
1349  *
1350  *	Here, we check and fix the alternate boot sector, only in the
1351  *	first situation where the file system does not overflow on the
1352  *	last sector.
1353  *
1354  *	Note : when shrinking a partition, ntfsresize cannot determine
1355  *	the future size of the partition. As a consequence the number of
1356  *	sectors in the boot sectors may be less than the possible size.
1357  *
1358  *	Returns 0 if successful
1359  */
1360 
check_alternate_boot(ntfs_volume * vol)1361 static int check_alternate_boot(ntfs_volume *vol)
1362 {
1363 	s64 got_sectors;
1364 	s64 actual_sectors;
1365 	s64 last_sector_off;
1366 	char *full_bs;
1367 	char *alt_bs;
1368 	NTFS_BOOT_SECTOR *bs;
1369 	s64 br;
1370 	s64 bw;
1371 	int res;
1372 
1373 	res = -1;
1374 	full_bs = (char*)malloc(vol->sector_size);
1375 	alt_bs = (char*)malloc(vol->sector_size);
1376 	if (!full_bs || !alt_bs) {
1377 		ntfs_log_info("Error : failed to allocate memory\n");
1378 		goto error_exit;
1379 	}
1380 	/* Now read both bootsectors. */
1381 	br = ntfs_pread(vol->dev, 0, vol->sector_size, full_bs);
1382 	if (br == vol->sector_size) {
1383 		bs = (NTFS_BOOT_SECTOR*)full_bs;
1384 		got_sectors = sle64_to_cpu(bs->number_of_sectors);
1385 		actual_sectors = ntfs_device_size_get(vol->dev,
1386 						vol->sector_size);
1387 		if (actual_sectors > got_sectors) {
1388 			last_sector_off = (actual_sectors - 1)
1389 						<< vol->sector_size_bits;
1390 			ntfs_log_info("Checking the alternate boot sector... ");
1391 			br = ntfs_pread(vol->dev, last_sector_off,
1392 						vol->sector_size, alt_bs);
1393 		} else {
1394 			ntfs_log_info("Checking file system overflow... ");
1395 			br = -1;
1396 		}
1397 		/* accept getting no byte, needed for short image files */
1398 		if (br >= 0) {
1399 			if ((br != vol->sector_size)
1400 			    || memcmp(full_bs, alt_bs, vol->sector_size)) {
1401 				if (opt.no_action) {
1402 					ntfs_log_info("BAD\n");
1403 				} else {
1404 					bw = ntfs_pwrite(vol->dev,
1405 						last_sector_off,
1406 						vol->sector_size, full_bs);
1407 					if (bw == vol->sector_size) {
1408 						ntfs_log_info("FIXED\n");
1409 						res = 0;
1410 					} else {
1411 						ntfs_log_info(FAILED);
1412 					}
1413 				}
1414 			} else {
1415 				ntfs_log_info(OK);
1416 				res = 0;
1417 			}
1418 		} else {
1419 			ntfs_log_info(FAILED);
1420 		}
1421 	} else {
1422 		ntfs_log_info("Error : could not read the boot sector again\n");
1423 	}
1424 	free(full_bs);
1425 	free(alt_bs);
1426 
1427 error_exit :
1428 	return (res);
1429 }
1430 
1431 /*
1432  *		Try to fix problems which may arise in the start up sequence
1433  *
1434  *	This is a replay of the normal start up sequence with fixes when
1435  *	some problem arise.
1436  *
1437  *	Returns 0 if there was an error and a fix is available
1438  */
1439 
fix_startup(struct ntfs_device * dev,unsigned long flags)1440 static int fix_startup(struct ntfs_device *dev, unsigned long flags)
1441 {
1442 	s64 br;
1443 	ntfs_volume *vol;
1444 	BOOL dev_open;
1445 	s64 shown_sectors;
1446 	char *full_bs;
1447 	NTFS_BOOT_SECTOR *bs;
1448 	s32 sector_size;
1449 	int res;
1450 	int eo;
1451 
1452 	errno = 0;
1453 	res = -1;
1454 	dev_open = FALSE;
1455 	full_bs = (char*)NULL;
1456 	if (!dev || !dev->d_ops || !dev->d_name) {
1457 		errno = EINVAL;
1458 		ntfs_log_perror("%s: dev = %p", __FUNCTION__, dev);
1459 		vol = (ntfs_volume*)NULL;
1460 		goto error_exit;
1461 	}
1462 
1463 	/* Allocate the volume structure. */
1464 	vol = ntfs_volume_alloc();
1465 	if (!vol)
1466 		goto error_exit;
1467 
1468 	/* Create the default upcase table. */
1469 	vol->upcase_len = ntfs_upcase_build_default(&vol->upcase);
1470 	if (!vol->upcase_len || !vol->upcase)
1471 		goto error_exit;
1472 
1473 	/* Default with no locase table and case sensitive file names */
1474 	vol->locase = (ntfschar*)NULL;
1475 	NVolSetCaseSensitive(vol);
1476 
1477 		/* by default, all files are shown and not marked hidden */
1478 	NVolSetShowSysFiles(vol);
1479 	NVolSetShowHidFiles(vol);
1480 	NVolClearHideDotFiles(vol);
1481 	if (flags & NTFS_MNT_RDONLY)
1482 		NVolSetReadOnly(vol);
1483 
1484 	/* ...->open needs bracketing to compile with glibc 2.7 */
1485 	if ((dev->d_ops->open)(dev, NVolReadOnly(vol) ? O_RDONLY: O_RDWR)) {
1486 		ntfs_log_perror("Error opening '%s'", dev->d_name);
1487 		goto error_exit;
1488 	}
1489 	dev_open = TRUE;
1490 	/* Attach the device to the volume. */
1491 	vol->dev = dev;
1492 
1493 	sector_size = ntfs_device_sector_size_get(dev);
1494 	if (sector_size <= 0)
1495 		sector_size = DEFAULT_SECTOR_SIZE;
1496 	full_bs = (char*)malloc(sector_size);
1497 	if (!full_bs)
1498 		goto error_exit;
1499 	/* Now read the bootsector. */
1500 	br = ntfs_pread(dev, 0, sector_size, full_bs);
1501 	if (br != sector_size) {
1502 		if (br != -1)
1503 			errno = EINVAL;
1504 		if (!br)
1505 			ntfs_log_error("Failed to read bootsector (size=0)\n");
1506 		else
1507 			ntfs_log_perror("Error reading bootsector");
1508 		goto error_exit;
1509 	}
1510 	bs = (NTFS_BOOT_SECTOR*)full_bs;
1511 	if (!ntfs_boot_sector_is_ntfs(bs)
1512 		/* get the bootsector data, only fails when inconsistent */
1513 	    || (ntfs_boot_sector_parse(vol, bs) < 0)) {
1514 		shown_sectors = sle64_to_cpu(bs->number_of_sectors);
1515 		/* boot sector is wrong, try the alternate boot sector */
1516 		if (try_alternate_boot(vol, full_bs, sector_size,
1517 						shown_sectors)) {
1518 			errno = EINVAL;
1519 			goto error_exit;
1520 		}
1521 		res = 0;
1522 	} else {
1523 		res = fix_self_located_mft(vol);
1524 	}
1525 error_exit:
1526 	if (res) {
1527 		switch (errno) {
1528 		case ENOMEM :
1529 			ntfs_log_error("Failed to allocate memory\n");
1530 			break;
1531 		case EINVAL :
1532 			ntfs_log_error("Unrecoverable error\n");
1533 			break;
1534 		default :
1535 			break;
1536 		}
1537 	}
1538 	eo = errno;
1539 	free(full_bs);
1540 	if (vol) {
1541 		free(vol->upcase);
1542 		free(vol);
1543 	}
1544 	if (dev_open) {
1545 		(dev->d_ops->close)(dev);
1546 	}
1547 	errno = eo;
1548 	return (res);
1549 }
1550 
1551 /**
1552  * fix_mount
1553  */
fix_mount(void)1554 static int fix_mount(void)
1555 {
1556 	int ret = 0; /* default success */
1557 	ntfs_volume *vol;
1558 	struct ntfs_device *dev;
1559 	unsigned long flags;
1560 
1561 	ntfs_log_info("Attempting to correct errors... ");
1562 
1563 	dev = ntfs_device_alloc(opt.volume, 0, &ntfs_device_default_io_ops,
1564 			NULL);
1565 	if (!dev) {
1566 		ntfs_log_info(FAILED);
1567 		ntfs_log_perror("Failed to allocate device");
1568 		return -1;
1569 	}
1570 	flags = (opt.no_action ? NTFS_MNT_RDONLY : 0);
1571 	vol = ntfs_volume_startup(dev, flags);
1572 	if (!vol) {
1573 		ntfs_log_info(FAILED);
1574 		ntfs_log_perror("Failed to startup volume");
1575 
1576 		/* Try fixing the bootsector and MFT, then redo the startup */
1577 		if (!fix_startup(dev, flags)) {
1578 			if (opt.no_action)
1579 				ntfs_log_info("The startup data can be fixed, "
1580 						"but no change was requested\n");
1581 			else
1582 				vol = ntfs_volume_startup(dev, flags);
1583 		}
1584 		if (!vol) {
1585 			ntfs_log_error("Volume is corrupt. You should run chkdsk.\n");
1586 			ntfs_device_free(dev);
1587 			return -1;
1588 		}
1589 		if (opt.no_action)
1590 			ret = -1; /* error present and not fixed */
1591 	}
1592 		/* if option -n proceed despite errors, to display them all */
1593 	if ((!ret || opt.no_action) && (fix_mftmirr(vol) < 0))
1594 		ret = -1;
1595 	if ((!ret || opt.no_action) && (fix_upcase(vol) < 0))
1596 		ret = -1;
1597 	if ((!ret || opt.no_action) && (set_dirty_flag(vol) < 0))
1598 		ret = -1;
1599 	if ((!ret || opt.no_action) && (empty_journal(vol) < 0))
1600 		ret = -1;
1601 	/*
1602 	 * ntfs_umount() will invoke ntfs_device_free() for us.
1603 	 * Ignore the returned error resulting from partial mounting.
1604 	 */
1605 	ntfs_umount(vol, 1);
1606 	return ret;
1607 }
1608 
1609 /**
1610  * main
1611  */
main(int argc,char ** argv)1612 int main(int argc, char **argv)
1613 {
1614 	ntfs_volume *vol;
1615 	unsigned long mnt_flags;
1616 	unsigned long flags;
1617 	int ret = 1; /* failure */
1618 	BOOL force = FALSE;
1619 
1620 	ntfs_log_set_handler(ntfs_log_handler_outerr);
1621 
1622 	parse_options(argc, argv);
1623 
1624 	if (!ntfs_check_if_mounted(opt.volume, &mnt_flags)) {
1625 		if ((mnt_flags & NTFS_MF_MOUNTED) &&
1626 				!(mnt_flags & NTFS_MF_READONLY) && !force) {
1627 			ntfs_log_error("Refusing to operate on read-write "
1628 					"mounted device %s.\n", opt.volume);
1629 			exit(1);
1630 		}
1631 	} else
1632 		ntfs_log_perror("Failed to determine whether %s is mounted",
1633 				opt.volume);
1634 	/* Attempt a full mount first. */
1635 	flags = (opt.no_action ? NTFS_MNT_RDONLY : 0);
1636 	ntfs_log_info("Mounting volume... ");
1637 	vol = ntfs_mount(opt.volume, flags);
1638 	if (vol) {
1639 		ntfs_log_info(OK);
1640 		ntfs_log_info("Processing of $MFT and $MFTMirr completed "
1641 				"successfully.\n");
1642 	} else {
1643 		ntfs_log_info(FAILED);
1644 		if (fix_mount() < 0) {
1645 			if (opt.no_action)
1646 				ntfs_log_info("No change made\n");
1647 			exit(1);
1648 		}
1649 		vol = ntfs_mount(opt.volume, 0);
1650 		if (!vol) {
1651 			ntfs_log_perror("Remount failed");
1652 			exit(1);
1653 		}
1654 	}
1655 	if (check_alternate_boot(vol)) {
1656 		ntfs_log_error("Error: Failed to fix the alternate boot sector\n");
1657 		exit(1);
1658 	}
1659 	/* So the unmount does not clear it again. */
1660 
1661 	/* Porting note: The WasDirty flag was set here to prevent ntfs_unmount
1662 	 * from clearing the dirty bit (which might have been set in
1663 	 * fix_mount()). So the intention is to leave the dirty bit set.
1664 	 *
1665 	 * libntfs-3g does not automatically set or clear dirty flags on
1666 	 * mount/unmount, this means that the assumption that the dirty flag is
1667 	 * now set does not hold. So we need to set it if not already set.
1668 	 *
1669 	 * However clear the flag if requested to do so, at this stage
1670 	 * mounting was successful.
1671 	 */
1672 	if (opt.clear_dirty)
1673 		vol->flags &= ~VOLUME_IS_DIRTY;
1674 	else
1675 		vol->flags |= VOLUME_IS_DIRTY;
1676 	if (!opt.no_action && ntfs_volume_write_flags(vol, vol->flags)) {
1677 		ntfs_log_error("Error: Failed to set volume dirty flag (%d "
1678 			"(%s))!\n", errno, strerror(errno));
1679 	}
1680 
1681 	/* Check NTFS version is ok for us (in $Volume) */
1682 	ntfs_log_info("NTFS volume version is %i.%i.\n", vol->major_ver,
1683 			vol->minor_ver);
1684 	if (ntfs_version_is_supported(vol)) {
1685 		ntfs_log_error("Error: Unknown NTFS version.\n");
1686 		goto error_exit;
1687 	}
1688 	if (opt.clear_bad_sectors && !opt.no_action) {
1689 		if (clear_badclus(vol)) {
1690 			ntfs_log_error("Error: Failed to un-mark bad sectors.\n");
1691 			goto error_exit;
1692 		}
1693 	}
1694 	if (vol->major_ver >= 3) {
1695 		/*
1696 		 * FIXME: If on NTFS 3.0+, check for presence of the usn
1697 		 * journal and stamp it if present.
1698 		 */
1699 	}
1700 	/* FIXME: We should be marking the quota out of date, too. */
1701 	/* That's all for now! */
1702 	ntfs_log_info("NTFS partition %s was processed successfully.\n",
1703 			vol->dev->d_name);
1704 	/* Set return code to 0. */
1705 	ret = 0;
1706 error_exit:
1707 	if (ntfs_umount(vol, 1)) {
1708 		ntfs_log_info("Failed to unmount partition\n");
1709 		ret = 1;
1710 	}
1711 	if (ret)
1712 		exit(ret);
1713 	return ret;
1714 }
1715 
1716