1 /**
2  * ntfsundelete - Part of the Linux-NTFS project.
3  *
4  * Copyright (c) 2002-2005 Richard Russon
5  * Copyright (c) 2004-2005 Holger Ohmacht
6  * Copyright (c) 2005      Anton Altaparmakov
7  * Copyright (c) 2007      Yura Pakhuchiy
8  * Copyright (c) 2013-2014 Jean-Pierre Andre
9  *
10  * This utility will recover deleted files from an NTFS volume.
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program (in the main directory of the Linux-NTFS
24  * distribution in the file COPYING); if not, write to the Free Software
25  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26  */
27 
28 #include "config.h"
29 
30 #ifdef HAVE_FEATURES_H
31 #include <features.h>
32 #endif
33 #ifdef HAVE_STDIO_H
34 #include <stdio.h>
35 #endif
36 #ifdef HAVE_STDLIB_H
37 #include <stdlib.h>
38 #endif
39 #ifdef HAVE_STRING_H
40 #include <string.h>
41 #endif
42 #ifdef HAVE_ERRNO_H
43 #include <errno.h>
44 #endif
45 #ifdef HAVE_SYS_TYPES_H
46 #include <sys/types.h>
47 #endif
48 #ifdef HAVE_SYS_STAT_H
49 #include <sys/stat.h>
50 #endif
51 #ifdef HAVE_UNISTD_H
52 #include <unistd.h>
53 #endif
54 #ifdef HAVE_FCNTL_H
55 #include <fcntl.h>
56 #endif
57 #ifdef HAVE_GETOPT_H
58 #include <getopt.h>
59 #endif
60 #ifdef HAVE_TIME_H
61 #include <time.h>
62 #endif
63 #ifdef HAVE_LIMITS_H
64 #include <limits.h>
65 #endif
66 #ifdef HAVE_STDARG_H
67 #include <stdarg.h>
68 #endif
69 #ifdef HAVE_UTIME_H
70 #include <utime.h>
71 #endif
72 #ifdef HAVE_REGEX_H
73 #include <regex.h>
74 #endif
75 
76 #if !defined(REG_NOERROR) || (REG_NOERROR != 0)
77 #define REG_NOERROR 0
78 #endif
79 
80 #ifndef REG_NOMATCH
81 #define REG_NOMATCH 1
82 #endif
83 
84 #include "ntfsundelete.h"
85 #include "bootsect.h"
86 #include "mft.h"
87 #include "attrib.h"
88 #include "layout.h"
89 #include "inode.h"
90 #include "device.h"
91 #include "utils.h"
92 #include "debug.h"
93 #include "ntfstime.h"
94 /* #include "version.h" */
95 #include "logging.h"
96 #include "misc.h"
97 
98 #ifdef HAVE_WINDOWS_H
99 /*
100  *		Replacements for functions which do not exist on Windows
101  */
102 #define ftruncate(fd, size) ntfs_win32_ftruncate(fd, size)
103 #endif
104 
105 static const char *EXEC_NAME = "ntfsundelete";
106 static const char *MFTFILE   = "mft";
107 static const char *UNNAMED   = "<unnamed>";
108 static const char *NONE      = "<none>";
109 static const char *UNKNOWN   = "unknown";
110 static struct options opts;
111 
112 typedef struct
113 {
114 	u32 begin;
115 	u32 end;
116 } range;
117 
118 static short	with_regex;			/* Flag  Regular expression available */
119 static short	avoid_duplicate_printing;	/* Flag  No duplicate printing of file infos */
120 static range	*ranges;			/* Array containing all Inode-Ranges for undelete */
121 static long	nr_entries;			/* Number of range entries */
122 
123 #ifdef HAVE_WINDOWS_H
124 /*
125  *		Replacement for strftime() on Windows
126  *
127  *	strftime() on Windows uses format codes different from those
128  *	defined in C99 sect. 7.23.3.5
129  *	Use snprintf() instead.
130  */
win32_strftime(char * buffer,int size,const char * format,const struct tm * ptm)131 static int win32_strftime(char *buffer, int size, const char *format,
132 					const struct tm *ptm)
133 {
134 	int ret;
135 
136 	if (!strcmp(format, "%F %R"))
137 		ret = snprintf(buffer, size, "%4d-%02d-%02d %02d:%02d",
138 			ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday,
139 			ptm->tm_hour, ptm->tm_min);
140 	else
141 		ret = snprintf(buffer, size, "%4d-%02d-%02d",
142 			ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday);
143 	return (ret);
144 }
145 #define strftime(buf, sz, fmt, ptm) win32_strftime(buf, sz, fmt, ptm)
146 #endif
147 
148 #ifndef HAVE_REGEX_H
149 
150 /*
151  *		Pattern matching routing for systems with no regex.
152  */
153 
154 typedef struct REGEX {
155 	ntfschar *upcase;
156 	u32 upcase_len;
157 	int flags;
158 	int pattern_len;
159 	ntfschar pattern[1];
160 } *regex_t;
161 
162 enum { REG_NOSUB = 1, REG_ICASE = 2 };
163 
patmatch(regex_t * re,const ntfschar * f,int flen,const ntfschar * p,int plen,BOOL dot)164 static BOOL patmatch(regex_t *re, const ntfschar *f, int flen,
165 			const ntfschar *p, int plen, BOOL dot)
166 {
167 	regex_t pre;
168 	BOOL ok;
169 	BOOL anyextens;
170 	int i;
171 	unsigned int c;
172 
173 	pre = *re;
174 	if (pre->flags & REG_ICASE) {
175 		while ((flen > 0) && (plen > 0)
176 		    && ((*f == *p)
177 			|| (*p == const_cpu_to_le16('?'))
178 			|| ((c = le16_to_cpu(*f)) < pre->upcase_len
179 				? pre->upcase[c] : *f) == *p)) {
180 			flen--;
181 			if (*f++ == const_cpu_to_le16('.'))
182 				dot = TRUE;
183 			plen--;
184 			p++;
185 		}
186 	} else {
187 		while ((flen > 0) && (plen > 0)
188 		    && ((*f == *p) || (*p == const_cpu_to_le16('?')))) {
189 			flen--;
190 			if (*f++ == const_cpu_to_le16('.'))
191 				dot = TRUE;
192 			plen--;
193 			p++;
194 		}
195 	}
196 	if ((flen <= 0) && (plen <= 0))
197 		ok = TRUE;
198 	else {
199 		ok = FALSE;
200 		plen--;
201 		if (*p++ == const_cpu_to_le16('*')) {
202 			/* special case "*.*" requires the end or a dot */
203 			anyextens = FALSE;
204 			if ((plen == 2)
205 			    && (p[0] == const_cpu_to_le16('.'))
206 			    && (p[1] == const_cpu_to_le16('*'))
207 			    && !dot) {
208 				for (i=0; (i<flen) && !anyextens; i++)
209 					if (f[i] == const_cpu_to_le16('.'))
210 						anyextens = TRUE;
211 			}
212 			if (!plen || anyextens)
213 				ok = TRUE;
214 			else
215 				while ((flen > 0) && !ok)
216 					if (patmatch(re,f,flen,p,plen,dot))
217 						ok = TRUE;
218 					else {
219 						flen--;
220 						f++;
221 					}
222 		}
223 	}
224 	return (ok);
225 }
226 
regcomp(regex_t * re,const char * pattern,int flags)227 static int regcomp(regex_t *re, const char *pattern, int flags)
228 {
229 	regex_t pre;
230 	ntfschar *rp;
231 	ntfschar *p;
232 	unsigned int c;
233 	int lth;
234 	int i;
235 
236 	pre = (regex_t)malloc(sizeof(struct REGEX)
237 			+ strlen(pattern)*sizeof(ntfschar));
238 	*re = pre;
239 	if (pre) {
240 		pre->flags = flags;
241 		pre->upcase_len = 0;
242 		rp = pre->pattern;
243 		lth = ntfs_mbstoucs(pattern, &rp);
244 		pre->pattern_len = lth;
245 		p = pre->pattern;
246 		if (flags & REG_ICASE) {
247 			for (i=0; i<lth; i++) {
248 				c = le16_to_cpu(*p);
249 				if (c < pre->upcase_len)
250 					*p = pre->upcase[c];
251 				p++;
252 			}
253 		}
254 	}
255 	return (*re && (lth > 0) ? 0 : -1);
256 }
257 
regexec(regex_t * re,const ntfschar * uname,int len,char * q,int r)258 static int regexec(regex_t *re, const ntfschar *uname, int len,
259 		char *q __attribute__((unused)), int r __attribute__((unused)))
260 {
261 	BOOL m;
262 
263 	m = patmatch(re, uname, len, (*re)->pattern, (*re)->pattern_len, FALSE);
264 	return (m ? REG_NOERROR : REG_NOMATCH);
265 }
266 
regfree(regex_t * re)267 static void regfree(regex_t *re)
268 {
269 	free(*re);
270 }
271 
272 #endif
273 
274 /**
275  * parse_inode_arg - parses the inode expression
276  *
277  * Parses the optarg after parameter -u for valid ranges
278  *
279  * Return: Number of correct inode specifications or -1 for error
280  */
parse_inode_arg(void)281 static int parse_inode_arg(void)
282 {
283 	int p;
284 	u32 range_begin;
285 	u32 range_end;
286 	u32 range_temp;
287 	u32 inode;
288 	char *opt_arg_ptr;
289 	char *opt_arg_temp;
290 	char *opt_arg_end1;
291 	char *opt_arg_end2;
292 
293 	/* Check whether optarg is available or not */
294 	nr_entries = 0;
295 	if (optarg == NULL)
296 		return (0);	/* bailout if no optarg */
297 
298 	/* init variables */
299 	p = strlen(optarg);
300 	opt_arg_ptr = optarg;
301 	opt_arg_end1 = optarg;
302 	opt_arg_end2 = &(optarg[p]);
303 
304 	/* alloc mem for range table */
305 	ranges = (range *) malloc((p + 1) * sizeof(range));
306 	if (ranges == NULL) {
307 		ntfs_log_error("ERROR: Couldn't alloc mem for parsing inodes!\n");
308 		return (-1);
309 	}
310 
311 	/* loop */
312 	while ((opt_arg_end1 != opt_arg_end2) && (p > 0)) {
313 		/* Try to get inode */
314 		inode = strtoul(opt_arg_ptr, &opt_arg_end1, 0);
315 		p--;
316 
317 		/* invalid char at begin */
318 		if ((opt_arg_ptr == opt_arg_end1) || (opt_arg_ptr == opt_arg_end2)) {
319 			ntfs_log_error("ERROR: Invalid Number: %s\n", opt_arg_ptr);
320 			return (-1);
321 		}
322 
323 		/* RANGE - Check for range */
324 		if (opt_arg_end1[0] == '-') {
325 			/* get range end */
326 			opt_arg_temp = opt_arg_end1;
327 			opt_arg_end1 = & (opt_arg_temp[1]);
328 			if (opt_arg_temp >= opt_arg_end2) {
329 				ntfs_log_error("ERROR: Missing range end!\n");
330 				return (-1);
331 			}
332 			range_begin = inode;
333 
334 			/* get count */
335 			range_end = strtoul(opt_arg_end1, &opt_arg_temp, 0);
336 			if (opt_arg_temp == opt_arg_end1) {
337 				ntfs_log_error("ERROR: Invalid Number: %s\n", opt_arg_temp);
338 				return (-1);
339 			}
340 
341 			/* check for correct values */
342 			if (range_begin > range_end) {
343 				range_temp = range_end;
344 				range_end = range_begin;
345 				range_begin = range_temp;
346 			}
347 
348 			/* put into struct */
349 			ranges[nr_entries].begin = range_begin;
350 			ranges[nr_entries].end = range_end;
351 			nr_entries++;
352 
353 			/* Last check */
354 			opt_arg_ptr = & (opt_arg_temp[1]);
355 			if (opt_arg_ptr >= opt_arg_end2)
356 				break;
357 		} else if (opt_arg_end1[0] == ',') {
358 			/* SINGLE VALUE, BUT CONTINUING */
359 			/* put inode into range list */
360 			ranges[nr_entries].begin = inode;
361 			ranges[nr_entries].end = inode;
362 			nr_entries++;
363 
364 			/* Next inode */
365 			opt_arg_ptr = & (opt_arg_end1[1]);
366 			if (opt_arg_ptr >= opt_arg_end2) {
367 				ntfs_log_error("ERROR: Missing new value at end of input!\n");
368 				return (-1);
369 			}
370 			continue;
371 		} else { /* SINGLE VALUE, END */
372 			ranges[nr_entries].begin = inode;
373 			ranges[nr_entries].end = inode;
374 			nr_entries++;
375 		}
376 	}
377 	return (nr_entries);
378 }
379 
380 /**
381  * version - Print version information about the program
382  *
383  * Print a copyright statement and a brief description of the program.
384  *
385  * Return:  none
386  */
version(void)387 static void version(void)
388 {
389 	ntfs_log_info("\n%s v%s (libntfs-3g) - Recover deleted files from an "
390 			"NTFS Volume.\n\n", EXEC_NAME, VERSION);
391 	ntfs_log_info("Copyright (c) 2002-2005 Richard Russon\n"
392 			"Copyright (c) 2004-2005 Holger Ohmacht\n"
393 			"Copyright (c) 2005      Anton Altaparmakov\n"
394 			"Copyright (c) 2007      Yura Pakhuchiy\n"
395 			"Copyright (c) 2013-2014 Jean-Pierre Andre\n");
396 	ntfs_log_info("\n%s\n%s%s\n", ntfs_gpl, ntfs_bugs, ntfs_home);
397 }
398 
399 /**
400  * usage - Print a list of the parameters to the program
401  *
402  * Print a list of the parameters and options for the program.
403  *
404  * Return:  none
405  */
usage(void)406 static void usage(void)
407 {
408 	ntfs_log_info("\nUsage: %s [options] device\n"
409 		"    -s, --scan             Scan for files (default)\n"
410 		"    -p, --percentage NUM   Minimum percentage recoverable\n"
411 		"    -m, --match PATTERN    Only work on files with matching names\n"
412 		"    -C, --case             Case sensitive matching\n"
413 		"    -S, --size RANGE       Match files of this size\n"
414 		"    -t, --time SINCE       Last referenced since this time\n"
415 		"\n"
416 		"    -u, --undelete         Undelete mode\n"
417 		"    -i, --inodes RANGE     Recover these inodes\n"
418 		//"    -I, --interactive      Interactive mode\n"
419 		"    -o, --output FILE      Save with this filename\n"
420 		"    -O, --optimistic       Undelete in-use clusters as well\n"
421 		"    -d, --destination DIR  Destination directory\n"
422 		"    -b, --byte NUM         Fill missing parts with this byte\n"
423 		"    -T, --truncate         Truncate 100%% recoverable file to exact size.\n"
424 		"    -P, --parent           Show parent directory\n"
425 		"\n"
426 		"    -c, --copy RANGE       Write a range of MFT records to a file\n"
427 		"\n"
428 		"    -f, --force            Use less caution\n"
429 		"    -q, --quiet            Less output\n"
430 		"    -v, --verbose          More output\n"
431 		"    -V, --version          Display version information\n"
432 		"    -h, --help             Display this help\n\n",
433 		EXEC_NAME);
434 	ntfs_log_info("%s%s\n", ntfs_bugs, ntfs_home);
435 }
436 
437 /**
438  * transform - Convert a shell style pattern to a regex
439  * @pattern:  String to be converted
440  * @regex:    Resulting regular expression is put here
441  *
442  * This will transform patterns, such as "*.doc" to true regular expressions.
443  * The function will also place '^' and '$' around the expression to make it
444  * behave as the user would expect
445  *
446  * Before  After
447  *   .       \.
448  *   *       .*
449  *   ?       .
450  *
451  * Notes:
452  *     The returned string must be freed by the caller.
453  *     If transform fails, @regex will not be changed.
454  *
455  * Return:  1, Success, the string was transformed
456  *	    0, An error occurred
457  */
transform(const char * pattern,char ** regex)458 static int transform(const char *pattern, char **regex)
459 {
460 	char *result;
461 	int length, i;
462 #ifdef HAVE_REGEX_H
463 	int j;
464 #endif
465 
466 	if (!pattern || !regex)
467 		return 0;
468 
469 	length = strlen(pattern);
470 	if (length < 1) {
471 		ntfs_log_error("Pattern to transform is empty\n");
472 		return 0;
473 	}
474 
475 	for (i = 0; pattern[i]; i++) {
476 		if ((pattern[i] == '*') || (pattern[i] == '.'))
477 			length++;
478 	}
479 
480 	result = malloc(length + 3);
481 	if (!result) {
482 		ntfs_log_error("Couldn't allocate memory in transform()\n");
483 		return 0;
484 	}
485 
486 #ifdef HAVE_REGEX_H
487 	result[0] = '^';
488 
489 	for (i = 0, j = 1; pattern[i]; i++, j++) {
490 		if (pattern[i] == '*') {
491 			result[j] = '.';
492 			j++;
493 			result[j] = '*';
494 		} else if (pattern[i] == '.') {
495 			result[j] = '\\';
496 			j++;
497 			result[j] = '.';
498 		} else if (pattern[i] == '?') {
499 			result[j] = '.';
500 		} else {
501 			result[j] = pattern[i];
502 		}
503 	}
504 
505 	result[j]   = '$';
506 	result[j+1] = 0;
507 	ntfs_log_debug("Pattern '%s' replaced with regex '%s'.\n", pattern,
508 			result);
509 #else
510 	strcpy(result, pattern);
511 #endif
512 
513 	*regex = result;
514 	return 1;
515 }
516 
517 /**
518  * parse_time - Convert a time abbreviation to seconds
519  * @string:  The string to be converted
520  * @since:   The absolute time referred to
521  *
522  * Strings representing times will be converted into a time_t.  The numbers will
523  * be regarded as seconds unless suffixed.
524  *
525  * Suffix  Description
526  *  [yY]      Year
527  *  [mM]      Month
528  *  [wW]      Week
529  *  [dD]      Day
530  *  [sS]      Second
531  *
532  * Therefore, passing "1W" will return the time_t representing 1 week ago.
533  *
534  * Notes:
535  *     Only the first character of the suffix is read.
536  *     If parse_time fails, @since will not be changed
537  *
538  * Return:  1  Success
539  *	    0  Error, the string was malformed
540  */
parse_time(const char * value,time_t * since)541 static int parse_time(const char *value, time_t *since)
542 {
543 	long long result;
544 	time_t now;
545 	char *suffix = NULL;
546 
547 	if (!value || !since)
548 		return -1;
549 
550 	ntfs_log_trace("Parsing time '%s' ago.\n", value);
551 
552 	result = strtoll(value, &suffix, 10);
553 	if (result < 0 || errno == ERANGE) {
554 		ntfs_log_error("Invalid time '%s'.\n", value);
555 		return 0;
556 	}
557 
558 	if (!suffix) {
559 		ntfs_log_error("Internal error, strtoll didn't return a suffix.\n");
560 		return 0;
561 	}
562 
563 	if (strlen(suffix) > 1) {
564 		ntfs_log_error("Invalid time suffix '%s'.  Use Y, M, W, D or H.\n", suffix);
565 		return 0;
566 	}
567 
568 	switch (suffix[0]) {
569 		case 'y': case 'Y': result *=   12;
570 		case 'm': case 'M': result *=    4;
571 		case 'w': case 'W': result *=    7;
572 		case 'd': case 'D': result *=   24;
573 		case 'h': case 'H': result *= 3600;
574 		case 0:
575 		    break;
576 
577 		default:
578 			ntfs_log_error("Invalid time suffix '%s'.  Use Y, M, W, D or H.\n", suffix);
579 			return 0;
580 	}
581 
582 	now = time(NULL);
583 
584 	ntfs_log_debug("Time now = %lld, Time then = %lld.\n", (long long) now,
585 			(long long) result);
586 	*since = now - result;
587 	return 1;
588 }
589 
590 /**
591  * parse_options - Read and validate the programs command line
592  *
593  * Read the command line, verify the syntax and parse the options.
594  * This function is very long, but quite simple.
595  *
596  * Return:  1 Success
597  *	    0 Error, one or more problems
598  */
parse_options(int argc,char * argv[])599 static int parse_options(int argc, char *argv[])
600 {
601 	static const char *sopt = "-b:Cc:d:fh?i:m:o:OPp:sS:t:TuqvV";
602 	static const struct option lopt[] = {
603 		{ "byte",	 required_argument,	NULL, 'b' },
604 		{ "case",	 no_argument,		NULL, 'C' },
605 		{ "copy",	 required_argument,	NULL, 'c' },
606 		{ "destination", required_argument,	NULL, 'd' },
607 		{ "force",	 no_argument,		NULL, 'f' },
608 		{ "help",	 no_argument,		NULL, 'h' },
609 		{ "inodes",	 required_argument,	NULL, 'i' },
610 		//{ "interactive", no_argument,		NULL, 'I' },
611 		{ "match",	 required_argument,	NULL, 'm' },
612 		{ "optimistic",  no_argument,		NULL, 'O' },
613 		{ "output",	 required_argument,	NULL, 'o' },
614 		{ "parent",	 no_argument,		NULL, 'P' },
615 		{ "percentage",  required_argument,	NULL, 'p' },
616 		{ "quiet",	 no_argument,		NULL, 'q' },
617 		{ "scan",	 no_argument,		NULL, 's' },
618 		{ "size",	 required_argument,	NULL, 'S' },
619 		{ "time",	 required_argument,	NULL, 't' },
620 		{ "truncate",	 no_argument,		NULL, 'T' },
621 		{ "undelete",	 no_argument,		NULL, 'u' },
622 		{ "verbose",	 no_argument,		NULL, 'v' },
623 		{ "version",	 no_argument,		NULL, 'V' },
624 		{ NULL, 0, NULL, 0 }
625 	};
626 
627 	int c = -1;
628 	char *end = NULL;
629 	int err  = 0;
630 	int ver  = 0;
631 	int help = 0;
632 	int levels = 0;
633 
634 	opterr = 0; /* We'll handle the errors, thank you. */
635 
636 	opts.mode     = MODE_NONE;
637 	opts.uinode   = -1;
638 	opts.percent  = -1;
639 	opts.fillbyte = -1;
640 	while ((c = getopt_long(argc, argv, sopt, lopt, NULL)) != -1) {
641 		switch (c) {
642 		case 1:	/* A non-option argument */
643 			if (!opts.device) {
644 				opts.device = argv[optind-1];
645 			} else {
646 				opts.device = NULL;
647 				err++;
648 			}
649 			break;
650 		case 'b':
651 			if (opts.fillbyte == (char)-1) {
652 				end = NULL;
653 				opts.fillbyte = strtol(optarg, &end, 0);
654 				if (end && *end)
655 					err++;
656 			} else {
657 				err++;
658 			}
659 			break;
660 		case 'C':
661 			opts.match_case++;
662 			break;
663 		case 'c':
664 			if (opts.mode == MODE_NONE) {
665 				if (!utils_parse_range(optarg,
666 				    &opts.mft_begin, &opts.mft_end, TRUE))
667 					err++;
668 				opts.mode = MODE_COPY;
669 			} else {
670 				opts.mode = MODE_ERROR;
671 			}
672 			break;
673 		case 'd':
674 			if (!opts.dest)
675 				opts.dest = optarg;
676 			else
677 				err++;
678 			break;
679 		case 'f':
680 			opts.force++;
681 			break;
682 		case 'h':
683 			help++;
684 			break;
685 		case '?':
686 			if (ntfs_log_parse_option (argv[optind-1]))
687 				break;
688 			ntfs_log_error("Unknown option '%s'.\n", argv[optind-1]);
689 			err++;
690 			break;
691 		case 'i':
692 			end = NULL;
693 			/* parse inodes */
694 			if (parse_inode_arg() == -1)
695 				err++;
696 			if (end && *end)
697 				err++;
698 			break;
699 		case 'm':
700 			if (!opts.match) {
701 				if (!transform(optarg, &opts.match)) {
702 					err++;
703 				} else {
704 					/* set regex-flag on true ;) */
705 					with_regex= 1;
706 				}
707 			} else {
708 				err++;
709 			}
710 			break;
711 		case 'o':
712 			if (!opts.output) {
713 				opts.output = optarg;
714 			} else {
715 				err++;
716 			}
717 			break;
718 		case 'O':
719 			if (!opts.optimistic) {
720 				opts.optimistic++;
721 			} else {
722 				err++;
723 			}
724 			break;
725 		case 'P':
726 			if (!opts.parent) {
727 				opts.parent++;
728 			} else {
729 				err++;
730 			}
731 			break;
732 		case 'p':
733 			if (opts.percent == -1) {
734 				end = NULL;
735 				opts.percent = strtol(optarg, &end, 0);
736 				if (end && ((*end != '%') && (*end != 0)))
737 					err++;
738 			} else {
739 				err++;
740 			}
741 			break;
742 		case 'q':
743 			opts.quiet++;
744 			ntfs_log_clear_levels(NTFS_LOG_LEVEL_QUIET);
745 			break;
746 		case 's':
747 			if (opts.mode == MODE_NONE)
748 				opts.mode = MODE_SCAN;
749 			else
750 				opts.mode = MODE_ERROR;
751 			break;
752 		case 'S':
753 			if ((opts.size_begin > 0) || (opts.size_end > 0) ||
754 			    !utils_parse_range(optarg, &opts.size_begin,
755 			     &opts.size_end, TRUE)) {
756 			    err++;
757 			}
758 			break;
759 		case 't':
760 			if (opts.since == 0) {
761 				if (!parse_time(optarg, &opts.since))
762 					err++;
763 			} else {
764 			    err++;
765 			}
766 			break;
767 		case 'T':
768 			opts.truncate++;
769 			break;
770 		case 'u':
771 			if (opts.mode == MODE_NONE) {
772 				opts.mode = MODE_UNDELETE;
773 			} else {
774 				opts.mode = MODE_ERROR;
775 			}
776 			break;
777 		case 'v':
778 			opts.verbose++;
779 			ntfs_log_set_levels(NTFS_LOG_LEVEL_VERBOSE);
780 			break;
781 		case 'V':
782 			ver++;
783 			break;
784 		default:
785 			if (((optopt == 'b') || (optopt == 'c') ||
786 			     (optopt == 'd') || (optopt == 'm') ||
787 			     (optopt == 'o') || (optopt == 'p') ||
788 			     (optopt == 'S') || (optopt == 't') ||
789 			     (optopt == 'u')) && (!optarg)) {
790 				ntfs_log_error("Option '%s' requires an argument.\n", argv[optind-1]);
791 			} else {
792 				ntfs_log_error("Unknown option '%s'.\n", argv[optind-1]);
793 			}
794 			err++;
795 			break;
796 		}
797 	}
798 
799 	/* Make sure we're in sync with the log levels */
800 	levels = ntfs_log_get_levels();
801 	if (levels & NTFS_LOG_LEVEL_VERBOSE)
802 		opts.verbose++;
803 	if (!(levels & NTFS_LOG_LEVEL_QUIET))
804 		opts.quiet++;
805 
806 	if (help || ver) {
807 		opts.quiet = 0;
808 	} else {
809 		if (opts.device == NULL) {
810 			if (argc > 1)
811 				ntfs_log_error("You must specify exactly one device.\n");
812 			err++;
813 		}
814 
815 		if (opts.mode == MODE_NONE) {
816 			opts.mode = MODE_SCAN;
817 		}
818 
819 		switch (opts.mode) {
820 		case MODE_SCAN:
821 			if (opts.output || opts.dest || opts.truncate ||
822 					(opts.fillbyte != (char)-1)) {
823 				ntfs_log_error("Scan can only be used with --percent, "
824 					"--match, --ignore-case, --size and --time.\n");
825 				err++;
826 			}
827 			if (opts.match_case && !opts.match) {
828 				ntfs_log_error("The --case option doesn't make sense without the --match option\n");
829 				err++;
830 			}
831 			break;
832 
833 		case MODE_UNDELETE:
834 			/*if ((opts.percent != -1) || (opts.size_begin > 0) || (opts.size_end > 0)) {
835 				ntfs_log_error("Undelete can only be used with "
836 					"--output, --destination, --byte and --truncate.\n");
837 				err++;
838 			}*/
839 			break;
840 		case MODE_COPY:
841 			if ((opts.fillbyte != (char)-1) || opts.truncate ||
842 			    (opts.percent != -1) ||
843 			    opts.match || opts.match_case ||
844 			    (opts.size_begin > 0) ||
845 			    (opts.size_end > 0)) {
846 				ntfs_log_error("Copy can only be used with --output and --destination.\n");
847 				err++;
848 			}
849 			break;
850 		default:
851 			ntfs_log_error("You can only select one of Scan, Undelete or Copy.\n");
852 			err++;
853 		}
854 
855 		if ((opts.percent < -1) || (opts.percent > 100)) {
856 			ntfs_log_error("Percentage value must be in the range 0 - 100.\n");
857 			err++;
858 		}
859 
860 		if (opts.quiet) {
861 			if (opts.verbose) {
862 				ntfs_log_error("You may not use --quiet and --verbose at the same time.\n");
863 				err++;
864 			} else if (opts.mode == MODE_SCAN) {
865 				ntfs_log_error("You may not use --quiet when scanning a volume.\n");
866 				err++;
867 			}
868 		}
869 
870 		if (opts.parent && !opts.verbose) {
871 			ntfs_log_error("To use --parent, you must also use --verbose.\n");
872 			err++;
873 		}
874 	}
875 
876 	if (opts.fillbyte == (char)-1)
877 		opts.fillbyte = 0;
878 
879 	if (ver)
880 		version();
881 	if (help || err)
882 		usage();
883 
884 		/* tri-state 0 : done, 1 : error, -1 : proceed */
885 	return (err ? 1 : (help || ver ? 0 : -1));
886 }
887 
888 /**
889  * free_file - Release the resources used by a file object
890  * @file:  The unwanted file object
891  *
892  * This will free up the memory used by a file object and iterate through the
893  * object's children, freeing their resources too.
894  *
895  * Return:  none
896  */
free_file(struct ufile * file)897 static void free_file(struct ufile *file)
898 {
899 	struct ntfs_list_head *item, *tmp;
900 
901 	if (!file)
902 		return;
903 
904 	ntfs_list_for_each_safe(item, tmp, &file->name) {
905 		/* List of filenames */
906 		struct filename *f = ntfs_list_entry(item, struct filename, list);
907 		ntfs_log_debug("freeing filename '%s'", f->name ? f->name :
908 				NONE);
909 		if (f->name)
910 			free(f->name);
911 		if (f->parent_name) {
912 			ntfs_log_debug(" and parent filename '%s'",
913 					f->parent_name);
914 			free(f->parent_name);
915 		}
916 		ntfs_log_debug(".\n");
917 		free(f);
918 	}
919 
920 	ntfs_list_for_each_safe(item, tmp, &file->data) {
921 		/* List of data streams */
922 		struct data *d = ntfs_list_entry(item, struct data, list);
923 		ntfs_log_debug("Freeing data stream '%s'.\n", d->name ?
924 				d->name : UNNAMED);
925 		if (d->name)
926 			free(d->name);
927 		if (d->runlist)
928 			free(d->runlist);
929 		free(d);
930 	}
931 
932 	free(file->mft);
933 	free(file);
934 }
935 
936 /**
937  * verify_parent - confirm a record is parent of a file
938  * @name:	a filename of the file
939  * @rec:	the mft record of the possible parent
940  *
941  * Check that @rec is the parent of the file represented by @name.
942  * If @rec is a directory, but it is created after @name, then we
943  * can't determine whether @rec is really @name's parent.
944  *
945  * Return:	@rec's filename, either same name space as @name or lowest space.
946  *		NULL if can't determine parenthood or on error.
947  */
verify_parent(struct filename * name,MFT_RECORD * rec)948 static FILE_NAME_ATTR* verify_parent(struct filename* name, MFT_RECORD* rec)
949 {
950 	ATTR_RECORD *attr30;
951 	FILE_NAME_ATTR *filename_attr = NULL, *lowest_space_name = NULL;
952 	ntfs_attr_search_ctx *ctx;
953 	int found_same_space = 1;
954 
955 	if (!name || !rec)
956 		return NULL;
957 
958 	if (!(rec->flags & MFT_RECORD_IS_DIRECTORY)) {
959 		return NULL;
960 	}
961 
962 	ctx = ntfs_attr_get_search_ctx(NULL, rec);
963 	if (!ctx) {
964 		ntfs_log_error("ERROR: Couldn't create a search context.\n");
965 		return NULL;
966 	}
967 
968 	attr30 = find_attribute(AT_FILE_NAME, ctx);
969 	if (!attr30) {
970 		return NULL;
971 	}
972 
973 	filename_attr = (FILE_NAME_ATTR*)((char*)attr30 + le16_to_cpu(attr30->value_offset));
974 	/* if name is older than this dir -> can't determine */
975 	if (ntfs2timespec(filename_attr->creation_time).tv_sec > name->date_c) {
976 		return NULL;
977 	}
978 
979 	if (filename_attr->file_name_type != name->name_space) {
980 		found_same_space = 0;
981 		lowest_space_name = filename_attr;
982 
983 		while (!found_same_space && (attr30 = find_attribute(AT_FILE_NAME, ctx))) {
984 			filename_attr = (FILE_NAME_ATTR*)((char*)attr30 + le16_to_cpu(attr30->value_offset));
985 
986 			if (filename_attr->file_name_type == name->name_space) {
987 				found_same_space = 1;
988 			} else {
989 				if (filename_attr->file_name_type < lowest_space_name->file_name_type) {
990 					lowest_space_name = filename_attr;
991 				}
992 			}
993 		}
994 	}
995 
996 	ntfs_attr_put_search_ctx(ctx);
997 
998 	return (found_same_space ? filename_attr : lowest_space_name);
999 }
1000 
1001 /**
1002  * get_parent_name - Find the name of a file's parent.
1003  * @name:	the filename whose parent's name to find
1004  */
get_parent_name(struct filename * name,ntfs_volume * vol)1005 static void get_parent_name(struct filename* name, ntfs_volume* vol)
1006 {
1007 	ntfs_attr* mft_data;
1008 	MFT_RECORD* rec;
1009 	FILE_NAME_ATTR* filename_attr;
1010 	long long inode_num;
1011 
1012 	if (!name || !vol)
1013 		return;
1014 
1015 	rec = calloc(1, vol->mft_record_size);
1016 	if (!rec) {
1017 		ntfs_log_error("ERROR: Couldn't allocate memory in "
1018 				"get_parent_name()\n");
1019 		return;
1020 	}
1021 
1022 	mft_data = ntfs_attr_open(vol->mft_ni, AT_DATA, AT_UNNAMED, 0);
1023 	if (!mft_data) {
1024 		ntfs_log_perror("ERROR: Couldn't open $MFT/$DATA");
1025 	} else {
1026 		inode_num = MREF_LE(name->parent_mref);
1027 
1028 		if (ntfs_attr_pread(mft_data, vol->mft_record_size * inode_num,
1029 					vol->mft_record_size, rec) < 1) {
1030 			ntfs_log_error("ERROR: Couldn't read MFT Record %lld"
1031 					".\n", inode_num);
1032 		} else if ((filename_attr = verify_parent(name, rec))) {
1033 			if (ntfs_ucstombs(filename_attr->file_name,
1034 					filename_attr->file_name_length,
1035 					&name->parent_name, 0) < 0) {
1036 				ntfs_log_debug("ERROR: Couldn't translate "
1037 						"filename to current "
1038 						"locale.\n");
1039 				name->parent_name = NULL;
1040 			}
1041 		}
1042 	}
1043 
1044 	if (mft_data) {
1045 		ntfs_attr_close(mft_data);
1046 	}
1047 
1048 	if (rec) {
1049 		free(rec);
1050 	}
1051 
1052 	return;
1053 }
1054 
1055 /*
1056  *		Rescue the last deleted name of a file
1057  *
1058  *	Under some conditions, when a name is deleted and the MFT
1059  *	record is shifted to reclaim the space, the name is still
1060  *	present beyond the end of record.
1061  *
1062  *	For this to be possible, the data record has to be small (less
1063  *	than 80 bytes), and there must be no other attributes.
1064  *	So only the names of plain unfragmented files can be rescued.
1065  *
1066  *	Returns NULL when the name cannot be recovered.
1067  */
1068 
rescue_name(MFT_RECORD * mft,ntfs_attr_search_ctx * ctx)1069 static struct filename *rescue_name(MFT_RECORD *mft, ntfs_attr_search_ctx *ctx)
1070 {
1071 	ATTR_RECORD *rec;
1072 	struct filename *name;
1073 	int off_name;
1074 	int length;
1075 	int type;
1076 
1077 	name = (struct filename*)NULL;
1078 	ntfs_attr_reinit_search_ctx(ctx);
1079 	rec = find_attribute(AT_DATA, ctx);
1080 	if (rec) {
1081 		/*
1082 		 * If the data attribute replaced the name attribute,
1083 		 * the name itself is at offset 0x58 from the data attr.
1084 		 * First be sure this location is within the unused part
1085 		 * of the MFT record, then make extra checks.
1086 		 */
1087 		off_name = (long)rec - (long)mft + 0x58;
1088 		if ((off_name >= (int)le32_to_cpu(mft->bytes_in_use))
1089 		    && ((off_name + 4)
1090 				 <= (int)le32_to_cpu(mft->bytes_allocated))) {
1091 			length = *((char*)mft + off_name);
1092 			type = *((char*)mft + off_name + 1);
1093 			/* check whether the name is fully allocated */
1094 			if ((type <= 3)
1095 			   && (length > 0)
1096 			   && ((off_name + 2*length + 2)
1097 				<= (int)le32_to_cpu(mft->bytes_allocated))) {
1098 				/* create a (partial) name record */
1099 				name = (struct filename*)
1100 						ntfs_calloc(sizeof(*name));
1101 				if (name) {
1102 					name->uname = (ntfschar*)
1103 						((char*)mft + off_name + 2);
1104 					name->uname_len = length;
1105 					name->name_space = type;
1106 					if (ntfs_ucstombs(name->uname, length,
1107 							&name->name, 0) < 0) {
1108 						free(name);
1109 						name = (struct filename*)NULL;
1110 					}
1111 				}
1112 			if (name && name->name)
1113 				ntfs_log_verbose("Recovered file name %s\n",
1114 						name->name);
1115 			}
1116 		}
1117 	}
1118 	return (name);
1119 }
1120 
1121 
1122 
1123 /**
1124  * get_filenames - Read an MFT Record's $FILENAME attributes
1125  * @file:  The file object to work with
1126  *
1127  * A single file may have more than one filename.  This is quite common.
1128  * Windows creates a short DOS name for each long name, e.g. LONGFI~1.XYZ,
1129  * LongFiLeName.xyZ.
1130  *
1131  * The filenames that are found are put in filename objects and added to a
1132  * linked list of filenames in the file object.  For convenience, the unicode
1133  * filename is converted into the current locale and stored in the filename
1134  * object.
1135  *
1136  * One of the filenames is picked (the one with the lowest numbered namespace)
1137  * and its locale friendly name is put in pref_name.
1138  *
1139  * Return:  n  The number of $FILENAME attributes found
1140  *	   -1  Error
1141  */
get_filenames(struct ufile * file,ntfs_volume * vol)1142 static int get_filenames(struct ufile *file, ntfs_volume* vol)
1143 {
1144 	ATTR_RECORD *rec;
1145 	FILE_NAME_ATTR *attr;
1146 	ntfs_attr_search_ctx *ctx;
1147 	struct filename *name;
1148 	int count = 0;
1149 	int space = 4;
1150 
1151 	if (!file)
1152 		return -1;
1153 
1154 	ctx = ntfs_attr_get_search_ctx(NULL, file->mft);
1155 	if (!ctx)
1156 		return -1;
1157 
1158 	while ((rec = find_attribute(AT_FILE_NAME, ctx))) {
1159 		/* We know this will always be resident. */
1160 		attr = (FILE_NAME_ATTR *)((char *)rec +
1161 				le16_to_cpu(rec->value_offset));
1162 
1163 		name = calloc(1, sizeof(*name));
1164 		if (!name) {
1165 			ntfs_log_error("ERROR: Couldn't allocate memory in "
1166 					"get_filenames().\n");
1167 			count = -1;
1168 			break;
1169 		}
1170 
1171 		name->uname      = attr->file_name;
1172 		name->uname_len  = attr->file_name_length;
1173 		name->name_space = attr->file_name_type;
1174 		name->size_alloc = sle64_to_cpu(attr->allocated_size);
1175 		name->size_data  = sle64_to_cpu(attr->data_size);
1176 		name->flags      = attr->file_attributes;
1177 
1178 		name->date_c     = ntfs2timespec(attr->creation_time).tv_sec;
1179 		name->date_a     = ntfs2timespec(attr->last_data_change_time).tv_sec;
1180 		name->date_m     = ntfs2timespec(attr->last_mft_change_time).tv_sec;
1181 		name->date_r     = ntfs2timespec(attr->last_access_time).tv_sec;
1182 
1183 		if (ntfs_ucstombs(name->uname, name->uname_len, &name->name,
1184 				0) < 0) {
1185 			ntfs_log_debug("ERROR: Couldn't translate filename to "
1186 					"current locale.\n");
1187 		}
1188 
1189 		name->parent_name = NULL;
1190 
1191 		if (opts.parent) {
1192 			name->parent_mref = attr->parent_directory;
1193 			get_parent_name(name, vol);
1194 		}
1195 
1196 		if (name->name_space < space) {
1197 			file->pref_name = name->name;
1198 			file->pref_pname = name->parent_name;
1199 			space = name->name_space;
1200 		}
1201 
1202 		file->max_size = max(file->max_size, name->size_alloc);
1203 		file->max_size = max(file->max_size, name->size_data);
1204 
1205 		ntfs_list_add_tail(&name->list, &file->name);
1206 		count++;
1207 	}
1208 
1209 	if (!count) {
1210 		name = rescue_name(file->mft,ctx);
1211 		if (name) {
1212 			/* a name was recovered, get missing attributes */
1213 			file->pref_name = name->name;
1214 			ntfs_attr_reinit_search_ctx(ctx);
1215 			rec = find_attribute(AT_STANDARD_INFORMATION, ctx);
1216 			if (rec) {
1217 				attr = (FILE_NAME_ATTR *)((char *)rec +
1218 						le16_to_cpu(rec->value_offset));
1219 				name->flags      = attr->file_attributes;
1220 
1221 				name->date_c     = ntfs2timespec(attr->creation_time).tv_sec;
1222 				name->date_a     = ntfs2timespec(attr->last_data_change_time).tv_sec;
1223 				name->date_m     = ntfs2timespec(attr->last_mft_change_time).tv_sec;
1224 				name->date_r     = ntfs2timespec(attr->last_access_time).tv_sec;
1225 			}
1226 			rec = find_attribute(AT_DATA, ctx);
1227 			if (rec) {
1228 				attr = (FILE_NAME_ATTR *)((char *)rec +
1229 						le16_to_cpu(rec->value_offset));
1230 				name->size_alloc = sle64_to_cpu(attr->allocated_size);
1231 				name->size_data  = sle64_to_cpu(attr->data_size);
1232 			}
1233 		ntfs_list_add_tail(&name->list, &file->name);
1234 		count++;
1235 		}
1236 	}
1237 	ntfs_attr_put_search_ctx(ctx);
1238 	ntfs_log_debug("File has %d names.\n", count);
1239 	return count;
1240 }
1241 
1242 /**
1243  * get_data - Read an MFT Record's $DATA attributes
1244  * @file:  The file object to work with
1245  * @vol:  An ntfs volume obtained from ntfs_mount
1246  *
1247  * A file may have more than one data stream.  All files will have an unnamed
1248  * data stream which contains the file's data.  Some Windows applications store
1249  * extra information in a separate stream.
1250  *
1251  * The streams that are found are put in data objects and added to a linked
1252  * list of data streams in the file object.
1253  *
1254  * Return:  n  The number of $FILENAME attributes found
1255  *	   -1  Error
1256  */
get_data(struct ufile * file,ntfs_volume * vol)1257 static int get_data(struct ufile *file, ntfs_volume *vol)
1258 {
1259 	ATTR_RECORD *rec;
1260 	ntfs_attr_search_ctx *ctx;
1261 	int count = 0;
1262 	struct data *data;
1263 
1264 	if (!file)
1265 		return -1;
1266 
1267 	ctx = ntfs_attr_get_search_ctx(NULL, file->mft);
1268 	if (!ctx)
1269 		return -1;
1270 
1271 	while ((rec = find_attribute(AT_DATA, ctx))) {
1272 		data = calloc(1, sizeof(*data));
1273 		if (!data) {
1274 			ntfs_log_error("ERROR: Couldn't allocate memory in "
1275 					"get_data().\n");
1276 			count = -1;
1277 			break;
1278 		}
1279 
1280 		data->resident   = !rec->non_resident;
1281 		data->compressed = (rec->flags & ATTR_IS_COMPRESSED) ? 1 : 0;
1282 		data->encrypted  = (rec->flags & ATTR_IS_ENCRYPTED) ? 1 : 0;
1283 
1284 		if (rec->name_length) {
1285 			data->uname = (ntfschar *)((char *)rec +
1286 					le16_to_cpu(rec->name_offset));
1287 			data->uname_len = rec->name_length;
1288 
1289 			if (ntfs_ucstombs(data->uname, data->uname_len,
1290 						&data->name, 0) < 0) {
1291 				ntfs_log_error("ERROR: Cannot translate name "
1292 						"into current locale.\n");
1293 			}
1294 		}
1295 
1296 		if (data->resident) {
1297 			data->size_data = le32_to_cpu(rec->value_length);
1298 			data->data = (char*)rec +
1299 				le16_to_cpu(rec->value_offset);
1300 		} else {
1301 			data->size_alloc = sle64_to_cpu(rec->allocated_size);
1302 			data->size_data  = sle64_to_cpu(rec->data_size);
1303 			data->size_init  = sle64_to_cpu(rec->initialized_size);
1304 			data->size_vcn   = sle64_to_cpu(rec->highest_vcn) + 1;
1305 		}
1306 
1307 		data->runlist = ntfs_mapping_pairs_decompress(vol, rec, NULL);
1308 		if (!data->runlist) {
1309 			ntfs_log_debug("Couldn't decompress the data runs.\n");
1310 		}
1311 
1312 		file->max_size = max(file->max_size, data->size_data);
1313 		file->max_size = max(file->max_size, data->size_init);
1314 
1315 		ntfs_list_add_tail(&data->list, &file->data);
1316 		count++;
1317 	}
1318 
1319 	ntfs_attr_put_search_ctx(ctx);
1320 	ntfs_log_debug("File has %d data streams.\n", count);
1321 	return count;
1322 }
1323 
1324 /**
1325  * read_record - Read an MFT record into memory
1326  * @vol:     An ntfs volume obtained from ntfs_mount
1327  * @record:  The record number to read
1328  *
1329  * Read the specified MFT record and gather as much information about it as
1330  * possible.
1331  *
1332  * Return:  Pointer  A ufile object containing the results
1333  *	    NULL     Error
1334  */
read_record(ntfs_volume * vol,long long record)1335 static struct ufile * read_record(ntfs_volume *vol, long long record)
1336 {
1337 	ATTR_RECORD *attr10, *attr20, *attr90;
1338 	struct ufile *file;
1339 	ntfs_attr *mft;
1340 	u32 log_levels;
1341 
1342 	if (!vol)
1343 		return NULL;
1344 
1345 	file = calloc(1, sizeof(*file));
1346 	if (!file) {
1347 		ntfs_log_error("ERROR: Couldn't allocate memory in read_record()\n");
1348 		return NULL;
1349 	}
1350 
1351 	NTFS_INIT_LIST_HEAD(&file->name);
1352 	NTFS_INIT_LIST_HEAD(&file->data);
1353 	file->inode = record;
1354 
1355 	file->mft = malloc(vol->mft_record_size);
1356 	if (!file->mft) {
1357 		ntfs_log_error("ERROR: Couldn't allocate memory in read_record()\n");
1358 		free_file(file);
1359 		return NULL;
1360 	}
1361 
1362 	mft = ntfs_attr_open(vol->mft_ni, AT_DATA, AT_UNNAMED, 0);
1363 	if (!mft) {
1364 		ntfs_log_perror("ERROR: Couldn't open $MFT/$DATA");
1365 		free_file(file);
1366 		return NULL;
1367 	}
1368 
1369 	if (ntfs_attr_mst_pread(mft, vol->mft_record_size * record, 1, vol->mft_record_size, file->mft) < 1) {
1370 		ntfs_log_error("ERROR: Couldn't read MFT Record %lld.\n", record);
1371 		ntfs_attr_close(mft);
1372 		free_file(file);
1373 		return NULL;
1374 	}
1375 
1376 	ntfs_attr_close(mft);
1377 	mft = NULL;
1378 
1379 	/* disable errors logging, while examining suspicious records */
1380 	log_levels = ntfs_log_clear_levels(NTFS_LOG_LEVEL_PERROR);
1381 	attr10 = find_first_attribute(AT_STANDARD_INFORMATION,	file->mft);
1382 	attr20 = find_first_attribute(AT_ATTRIBUTE_LIST,	file->mft);
1383 	attr90 = find_first_attribute(AT_INDEX_ROOT,		file->mft);
1384 
1385 	ntfs_log_debug("Attributes present: %s %s %s.\n", attr10?"0x10":"",
1386 			attr20?"0x20":"", attr90?"0x90":"");
1387 
1388 	if (attr10) {
1389 		STANDARD_INFORMATION *si;
1390 		si = (STANDARD_INFORMATION *) ((char *) attr10 + le16_to_cpu(attr10->value_offset));
1391 		file->date = ntfs2timespec(si->last_data_change_time).tv_sec;
1392 	}
1393 
1394 	if (attr20 || !attr10)
1395 		file->attr_list = 1;
1396 	if (attr90)
1397 		file->directory = 1;
1398 
1399 	if (get_filenames(file, vol) < 0) {
1400 		ntfs_log_error("ERROR: Couldn't get filenames.\n");
1401 	}
1402 	if (get_data(file, vol) < 0) {
1403 		ntfs_log_error("ERROR: Couldn't get data streams.\n");
1404 	}
1405 	/* restore errors logging */
1406 	ntfs_log_set_levels(log_levels);
1407 
1408 	return file;
1409 }
1410 
1411 /**
1412  * calc_percentage - Calculate how much of the file is recoverable
1413  * @file:  The file object to work with
1414  * @vol:   An ntfs volume obtained from ntfs_mount
1415  *
1416  * Read through all the $DATA streams and determine if each cluster in each
1417  * stream is still free disk space.  This is just measuring the potential for
1418  * recovery.  The data may have still been overwritten by a another file which
1419  * was then deleted.
1420  *
1421  * Files with a resident $DATA stream will have a 100% potential.
1422  *
1423  * N.B.  If $DATA attribute spans more than one MFT record (i.e. badly
1424  *       fragmented) then only the data in this segment will be used for the
1425  *       calculation.
1426  *
1427  * N.B.  Currently, compressed and encrypted files cannot be recovered, so they
1428  *       will return 0%.
1429  *
1430  * Return:  n  The percentage of the file that _could_ be recovered
1431  *	   -1  Error
1432  */
calc_percentage(struct ufile * file,ntfs_volume * vol)1433 static int calc_percentage(struct ufile *file, ntfs_volume *vol)
1434 {
1435 	runlist_element *rl = NULL;
1436 	struct ntfs_list_head *pos;
1437 	struct data *data;
1438 	long long i, j;
1439 	long long start, end;
1440 	int clusters_inuse, clusters_free;
1441 	int percent = 0;
1442 
1443 	if (!file || !vol)
1444 		return -1;
1445 
1446 	if (file->directory) {
1447 		ntfs_log_debug("Found a directory: not recoverable.\n");
1448 		return 0;
1449 	}
1450 
1451 	if (ntfs_list_empty(&file->data)) {
1452 		ntfs_log_verbose("File has no data streams.\n");
1453 		return 0;
1454 	}
1455 
1456 	ntfs_list_for_each(pos, &file->data) {
1457 		data  = ntfs_list_entry(pos, struct data, list);
1458 		clusters_inuse = 0;
1459 		clusters_free  = 0;
1460 
1461 		if (data->encrypted) {
1462 			ntfs_log_verbose("File is encrypted, recovery is "
1463 					"impossible.\n");
1464 			continue;
1465 		}
1466 
1467 		if (data->compressed) {
1468 			ntfs_log_verbose("File is compressed, recovery not yet "
1469 					"implemented.\n");
1470 			continue;
1471 		}
1472 
1473 		if (data->resident) {
1474 			ntfs_log_verbose("File is resident, therefore "
1475 					"recoverable.\n");
1476 			percent = 100;
1477 			data->percent = 100;
1478 			continue;
1479 		}
1480 
1481 		rl = data->runlist;
1482 		if (!rl) {
1483 			ntfs_log_verbose("File has no runlist, hence no data."
1484 					"\n");
1485 			continue;
1486 		}
1487 
1488 		if (rl[0].length <= 0) {
1489 			ntfs_log_verbose("File has an empty runlist, hence no "
1490 					"data.\n");
1491 			continue;
1492 		}
1493 
1494 		if (rl[0].lcn == LCN_RL_NOT_MAPPED) { /* extended mft record */
1495 			ntfs_log_verbose("Missing segment at beginning, %lld "
1496 					"clusters\n", (long long)rl[0].length);
1497 			clusters_inuse += rl[0].length;
1498 			rl++;
1499 		}
1500 
1501 		for (i = 0; rl[i].length > 0; i++) {
1502 			if (rl[i].lcn == LCN_RL_NOT_MAPPED) {
1503 				ntfs_log_verbose("Missing segment at end, %lld "
1504 						"clusters\n",
1505 						(long long)rl[i].length);
1506 				clusters_inuse += rl[i].length;
1507 				continue;
1508 			}
1509 
1510 			if (rl[i].lcn == LCN_HOLE) {
1511 				clusters_free += rl[i].length;
1512 				continue;
1513 			}
1514 
1515 			start = rl[i].lcn;
1516 			end   = rl[i].lcn + rl[i].length;
1517 
1518 			for (j = start; j < end; j++) {
1519 				if (utils_cluster_in_use(vol, j))
1520 					clusters_inuse++;
1521 				else
1522 					clusters_free++;
1523 			}
1524 		}
1525 
1526 		if ((clusters_inuse + clusters_free) == 0) {
1527 			ntfs_log_error("ERROR: Unexpected error whilst "
1528 				"calculating percentage for inode %lld\n",
1529 				file->inode);
1530 			continue;
1531 		}
1532 
1533 		data->percent = (clusters_free * 100) /
1534 				(clusters_inuse + clusters_free);
1535 
1536 		percent = max(percent, data->percent);
1537 	}
1538 
1539 	ntfs_log_verbose("File is %d%% recoverable\n", percent);
1540 	return percent;
1541 }
1542 
1543 /**
1544  * dump_record - Print everything we know about an MFT record
1545  * @file:  The file to work with
1546  *
1547  * Output the contents of the file object.  This will print everything that has
1548  * been read from the MFT record, or implied by various means.
1549  *
1550  * Because of the redundant nature of NTFS, there will be some duplication of
1551  * information, though it will have been read from different sources.
1552  *
1553  * N.B.  If the filename is missing, or couldn't be converted to the current
1554  *       locale, "<none>" will be displayed.
1555  *
1556  * Return:  none
1557  */
dump_record(struct ufile * file)1558 static void dump_record(struct ufile *file)
1559 {
1560 	char buffer[20];
1561 	struct ntfs_list_head *item;
1562 	int i;
1563 
1564 	if (!file)
1565 		return;
1566 
1567 	ntfs_log_quiet("MFT Record %lld\n", file->inode);
1568 	ntfs_log_quiet("Type: %s\n", (file->directory) ? "Directory" : "File");
1569 	strftime(buffer, sizeof(buffer), "%F %R", localtime(&file->date));
1570 	ntfs_log_quiet("Date: %s\n", buffer);
1571 
1572 	if (file->attr_list)
1573 		ntfs_log_quiet("Metadata may span more than one MFT record\n");
1574 
1575 	ntfs_list_for_each(item, &file->name) {
1576 		struct filename *f =
1577 			ntfs_list_entry(item, struct filename, list);
1578 
1579 		ntfs_log_quiet("Filename: (%d) %s\n", f->name_space, f->name);
1580 		ntfs_log_quiet("File Flags: ");
1581 		if (f->flags & FILE_ATTR_SYSTEM)
1582 			ntfs_log_quiet("System ");
1583 		if (f->flags & FILE_ATTR_DIRECTORY)
1584 			ntfs_log_quiet("Directory ");
1585 		if (f->flags & FILE_ATTR_SPARSE_FILE)
1586 			ntfs_log_quiet("Sparse ");
1587 		if (f->flags & FILE_ATTR_REPARSE_POINT)
1588 			ntfs_log_quiet("Reparse ");
1589 		if (f->flags & FILE_ATTR_COMPRESSED)
1590 			ntfs_log_quiet("Compressed ");
1591 		if (f->flags & FILE_ATTR_ENCRYPTED)
1592 			ntfs_log_quiet("Encrypted ");
1593 		if (!(f->flags & (FILE_ATTR_SYSTEM | FILE_ATTR_DIRECTORY |
1594 		    FILE_ATTR_SPARSE_FILE | FILE_ATTR_REPARSE_POINT |
1595 		    FILE_ATTR_COMPRESSED | FILE_ATTR_ENCRYPTED))) {
1596 			ntfs_log_quiet("%s", NONE);
1597 		}
1598 
1599 		ntfs_log_quiet("\n");
1600 
1601 		if (opts.parent) {
1602 			ntfs_log_quiet("Parent: %s\n", f->parent_name ?
1603 				f->parent_name : "<non-determined>");
1604 		}
1605 
1606 		ntfs_log_quiet("Size alloc: %lld\n", f->size_alloc);
1607 		ntfs_log_quiet("Size data: %lld\n", f->size_data);
1608 
1609 		strftime(buffer, sizeof(buffer), "%F %R",
1610 				localtime(&f->date_c));
1611 		ntfs_log_quiet("Date C: %s\n", buffer);
1612 		strftime(buffer, sizeof(buffer), "%F %R",
1613 				localtime(&f->date_a));
1614 		ntfs_log_quiet("Date A: %s\n", buffer);
1615 		strftime(buffer, sizeof(buffer), "%F %R",
1616 				localtime(&f->date_m));
1617 		ntfs_log_quiet("Date M: %s\n", buffer);
1618 		strftime(buffer, sizeof(buffer), "%F %R",
1619 				localtime(&f->date_r));
1620 		ntfs_log_quiet("Date R: %s\n", buffer);
1621 	}
1622 
1623 	ntfs_log_quiet("Data Streams:\n");
1624 	ntfs_list_for_each(item, &file->data) {
1625 		struct data *d = ntfs_list_entry(item, struct data, list);
1626 		ntfs_log_quiet("Name: %s\n", (d->name) ? d->name : UNNAMED);
1627 		ntfs_log_quiet("Flags: ");
1628 		if (d->resident)   ntfs_log_quiet("Resident\n");
1629 		if (d->compressed) ntfs_log_quiet("Compressed\n");
1630 		if (d->encrypted)  ntfs_log_quiet("Encrypted\n");
1631 		if (!d->resident && !d->compressed && !d->encrypted)
1632 			ntfs_log_quiet("None\n");
1633 		else
1634 			ntfs_log_quiet("\n");
1635 
1636 		ntfs_log_quiet("Size alloc: %lld\n", d->size_alloc);
1637 		ntfs_log_quiet("Size data: %lld\n", d->size_data);
1638 		ntfs_log_quiet("Size init: %lld\n", d->size_init);
1639 		ntfs_log_quiet("Size vcn: %lld\n", d->size_vcn);
1640 
1641 		ntfs_log_quiet("Data runs:\n");
1642 		if ((!d->runlist) || (d->runlist[0].length <= 0)) {
1643 			ntfs_log_quiet("    None\n");
1644 		} else {
1645 			for (i = 0; d->runlist[i].length > 0; i++) {
1646 				ntfs_log_quiet("    %lld @ %lld\n",
1647 						(long long)d->runlist[i].length,
1648 						(long long)d->runlist[i].lcn);
1649 			}
1650 		}
1651 
1652 		ntfs_log_quiet("Amount potentially recoverable %d%%\n",
1653 				d->percent);
1654 	}
1655 
1656 	ntfs_log_quiet("________________________________________\n\n");
1657 }
1658 
1659 /**
1660  * list_record - Print a one line summary of the file
1661  * @file:  The file to work with
1662  *
1663  * Print a one line description of a file.
1664  *
1665  *   Inode    Flags  %age     Date  Time        Size  Filename
1666  *
1667  * The output will contain the file's inode number (MFT Record), some flags,
1668  * the percentage of the file that is recoverable, the last modification date,
1669  * the size and the filename.
1670  *
1671  * The flags are F/D = File/Directory, N/R = Data is (Non-)Resident,
1672  * C = Compressed, E = Encrypted, ! = Metadata may span multiple records.
1673  *
1674  * N.B.  The file size is stored in many forms in several attributes.   This
1675  *       display the largest it finds.
1676  *
1677  * N.B.  If the filename is missing, or couldn't be converted to the current
1678  *       locale, "<none>" will be displayed.
1679  *
1680  * Return:  none
1681  */
list_record(struct ufile * file)1682 static void list_record(struct ufile *file)
1683 {
1684 	char buffer[20];
1685 	struct ntfs_list_head *item;
1686 	const char *name = NULL;
1687 	long long size = 0;
1688 	int percent = 0;
1689 
1690 	char flagd = '.', flagr = '.', flagc = '.', flagx = '.';
1691 
1692 	strftime(buffer, sizeof(buffer), "%F %R", localtime(&file->date));
1693 
1694 	if (file->attr_list)
1695 		flagx = '!';
1696 
1697 	if (file->directory)
1698 		flagd = 'D';
1699 	else
1700 		flagd = 'F';
1701 
1702 	ntfs_list_for_each(item, &file->data) {
1703 		struct data *d = ntfs_list_entry(item, struct data, list);
1704 
1705 		if (!d->name) {
1706 			if (d->resident)
1707 				flagr = 'R';
1708 			else
1709 				flagr = 'N';
1710 			if (d->compressed)
1711 				flagc = 'C';
1712 			if (d->encrypted)
1713 				flagc = 'E';
1714 
1715 			percent = max(percent, d->percent);
1716 		}
1717 
1718 		size = max(size, d->size_data);
1719 		size = max(size, d->size_init);
1720 	}
1721 
1722 	if (file->pref_name)
1723 		name = file->pref_name;
1724 	else
1725 		name = NONE;
1726 
1727 	ntfs_log_quiet("%-8lld %c%c%c%c   %3d%%  %s %9lld  %s\n",
1728 		file->inode, flagd, flagr, flagc, flagx,
1729 		percent, buffer, size, name);
1730 
1731 }
1732 
1733 /**
1734  * name_match - Does a file have a name matching a regex
1735  * @re:    The regular expression object
1736  * @file:  The file to be tested
1737  *
1738  * Iterate through the file's $FILENAME attributes and compare them against the
1739  * regular expression, created with regcomp.
1740  *
1741  * Return:  1  There is a matching filename.
1742  *	    0  There is no match.
1743  */
name_match(regex_t * re,struct ufile * file)1744 static int name_match(regex_t *re, struct ufile *file)
1745 {
1746 	struct ntfs_list_head *item;
1747 	int result;
1748 
1749 	if (!re || !file)
1750 		return 0;
1751 
1752 	ntfs_list_for_each(item, &file->name) {
1753 		struct filename *f =
1754 			ntfs_list_entry(item, struct filename, list);
1755 
1756 		if (!f->name)
1757 			continue;
1758 #ifdef HAVE_REGEX_H
1759 		result = regexec(re, f->name, 0, NULL, 0);
1760 #else
1761 		result = regexec(re, f->uname, f->uname_len, NULL, 0);
1762 #endif
1763 		if (result < 0) {
1764 			ntfs_log_perror("Couldn't compare filename with regex");
1765 			return 0;
1766 		} else if (result == REG_NOERROR) {
1767 			ntfs_log_debug("Found a matching filename.\n");
1768 			return 1;
1769 		}
1770 	}
1771 
1772 	ntfs_log_debug("Filename '%s' doesn't match regex.\n", file->pref_name);
1773 	return 0;
1774 }
1775 
1776 /**
1777  * write_data - Write out a block of data
1778  * @fd:       File descriptor to write to
1779  * @buffer:   Data to write
1780  * @bufsize:  Amount of data to write
1781  *
1782  * Write a block of data to a file descriptor.
1783  *
1784  * Return:  -1  Error, something went wrong
1785  *	     0  Success, all the data was written
1786  */
write_data(int fd,const char * buffer,unsigned int bufsize)1787 static unsigned int write_data(int fd, const char *buffer,
1788 	unsigned int bufsize)
1789 {
1790 	ssize_t result1, result2;
1791 
1792 	if (!buffer) {
1793 		errno = EINVAL;
1794 		return -1;
1795 	}
1796 
1797 	result1 = write(fd, buffer, bufsize);
1798 	if ((result1 == (ssize_t) bufsize) || (result1 < 0))
1799 		return result1;
1800 
1801 	/* Try again with the rest of the buffer */
1802 	buffer  += result1;
1803 	bufsize -= result1;
1804 
1805 	result2 = write(fd, buffer, bufsize);
1806 	if (result2 < 0)
1807 		return result1;
1808 
1809 	return result1 + result2;
1810 }
1811 
1812 /**
1813  * create_pathname - Create a path/file from some components
1814  * @dir:      Directory in which to create the file (optional)
1815  * @name:     Filename to give the file (optional)
1816  * @stream:   Name of the stream (optional)
1817  * @buffer:   Store the result here
1818  * @bufsize:  Size of buffer
1819  *
1820  * Create a filename from various pieces.  The output will be of the form:
1821  *	dir/file
1822  *	dir/file:stream
1823  *	file
1824  *	file:stream
1825  *
1826  * All the components are optional.  If the name is missing, "unknown" will be
1827  * used.  If the directory is missing the file will be created in the current
1828  * directory.  If the stream name is present it will be appended to the
1829  * filename, delimited by a colon.
1830  *
1831  * N.B. If the buffer isn't large enough the name will be truncated.
1832  *
1833  * Return:  n  Length of the allocated name
1834  */
create_pathname(const char * dir,const char * name,const char * stream,char * buffer,int bufsize)1835 static int create_pathname(const char *dir, const char *name,
1836 	const char *stream, char *buffer, int bufsize)
1837 {
1838 	if (!name)
1839 		name = UNKNOWN;
1840 
1841 	if (dir)
1842 		if (stream)
1843 			snprintf(buffer, bufsize, "%s/%s:%s", dir, name, stream);
1844 		else
1845 			snprintf(buffer, bufsize, "%s/%s", dir, name);
1846 	else
1847 		if (stream)
1848 			snprintf(buffer, bufsize, "%s:%s", name, stream);
1849 		else
1850 			snprintf(buffer, bufsize, "%s", name);
1851 
1852 	return strlen(buffer);
1853 }
1854 
1855 /**
1856  * open_file - Open a file to write to
1857  * @pathname:  Path, name and stream of the file to open
1858  *
1859  * Create a file and return the file descriptor.
1860  *
1861  * N.B.  If option force is given and existing file will be overwritten.
1862  *
1863  * Return:  -1  Error, failed to create the file
1864  *	     n  Success, this is the file descriptor
1865  */
open_file(const char * pathname)1866 static int open_file(const char *pathname)
1867 {
1868 	int flags;
1869 
1870 	ntfs_log_verbose("Creating file: %s\n", pathname);
1871 
1872 	if (opts.force)
1873 		flags = O_RDWR | O_CREAT | O_TRUNC;
1874 	else
1875 		flags = O_RDWR | O_CREAT | O_EXCL;
1876 #ifdef HAVE_WINDOWS_H
1877 	flags ^= O_BINARY | O_RDWR | O_WRONLY;
1878 #endif
1879 
1880 	return open(pathname, flags, S_IRUSR | S_IWUSR);
1881 }
1882 
1883 /**
1884  * set_date - Set the file's date and time
1885  * @pathname:  Path and name of the file to alter
1886  * @date:      Date and time to set
1887  *
1888  * Give a file a particular date and time.
1889  *
1890  * Return:  1  Success, set the file's date and time
1891  *	    0  Error, failed to change the file's date and time
1892  */
set_date(const char * pathname,time_t date)1893 static int set_date(const char *pathname, time_t date)
1894 {
1895 	struct utimbuf ut;
1896 
1897 	if (!pathname)
1898 		return 0;
1899 
1900 	ut.actime  = date;
1901 	ut.modtime = date;
1902 	if (utime(pathname, &ut)) {
1903 		ntfs_log_error("ERROR: Couldn't set the file's date and time\n");
1904 		return 0;
1905 	}
1906 	return 1;
1907 }
1908 
1909 /**
1910  * undelete_file - Recover a deleted file from an NTFS volume
1911  * @vol:    An ntfs volume obtained from ntfs_mount
1912  * @inode:  MFT Record number to be recovered
1913  *
1914  * Read an MFT Record and try an recover any data associated with it.  Some of
1915  * the clusters may be in use; these will be filled with zeros or the fill byte
1916  * supplied in the options.
1917  *
1918  * Each data stream will be recovered and saved to a file.  The file's name will
1919  * be the original filename and it will be written to the current directory.
1920  * Any named data stream will be saved as filename:streamname.
1921  *
1922  * The output file's name and location can be altered by using the command line
1923  * options.
1924  *
1925  * N.B.  We cannot tell if someone has overwritten some of the data since the
1926  *       file was deleted.
1927  *
1928  * Return:  0  Error, something went wrong
1929  *	    1  Success, the data was recovered
1930  */
undelete_file(ntfs_volume * vol,long long inode)1931 static int undelete_file(ntfs_volume *vol, long long inode)
1932 {
1933 	char pathname[256];
1934 	char *buffer = NULL;
1935 	unsigned int bufsize;
1936 	struct ufile *file;
1937 	int i, j;
1938 	long long start, end;
1939 	runlist_element *rl;
1940 	struct ntfs_list_head *item;
1941 	int fd = -1;
1942 	long long k;
1943 	int result = 0;
1944 	char *name;
1945 	long long cluster_count;	/* I'll need this variable (see below). +mabs */
1946 
1947 	if (!vol)
1948 		return 0;
1949 
1950 	/* try to get record */
1951 	file = read_record(vol, inode);
1952 	if (!file || !file->mft) {
1953 		ntfs_log_error("Can't read info from mft record %lld.\n", inode);
1954 		return 0;
1955 	}
1956 
1957 	/* if flag was not set, print file informations */
1958 	if (avoid_duplicate_printing == 0) {
1959 		if (opts.verbose) {
1960 			dump_record(file);
1961 		} else {
1962 			list_record(file);
1963 			//ntfs_log_quiet("\n");
1964 		}
1965 	}
1966 
1967 	bufsize = vol->cluster_size;
1968 	buffer = malloc(bufsize);
1969 	if (!buffer)
1970 		goto free;
1971 
1972 	/* calc_percentage() must be called before dump_record() or
1973 	 * list_record(). Otherwise, when undeleting, a file will always be
1974 	 * listed as 0% recoverable even if successfully undeleted. +mabs
1975 	 */
1976 	if (file->mft->flags & MFT_RECORD_IN_USE) {
1977 		ntfs_log_error("Record is in use by the mft\n");
1978 		if (!opts.force) {
1979 			free(buffer);
1980 			free_file(file);
1981 			return 0;
1982 		}
1983 		ntfs_log_verbose("Forced to continue.\n");
1984 	}
1985 
1986 	if (calc_percentage(file, vol) == 0) {
1987 		ntfs_log_quiet("File has no recoverable data.\n");
1988 		goto free;
1989 	}
1990 
1991 	if (ntfs_list_empty(&file->data)) {
1992 		ntfs_log_quiet("File has no data.  There is nothing to recover.\n");
1993 		goto free;
1994 	}
1995 
1996 	ntfs_list_for_each(item, &file->data) {
1997 		struct data *d = ntfs_list_entry(item, struct data, list);
1998 		char defname[sizeof(UNKNOWN) + 25];
1999 
2000 		if (opts.output)
2001 			name = opts.output;
2002 		else
2003 			if (file->pref_name)
2004 				name = file->pref_name;
2005 			else {
2006 				sprintf(defname,"%s%lld",UNKNOWN,
2007 						(long long)file->inode);
2008 				name = defname;
2009 			}
2010 
2011 		create_pathname(opts.dest, name, d->name, pathname, sizeof(pathname));
2012 		if (d->resident) {
2013 			fd = open_file(pathname);
2014 			if (fd < 0) {
2015 				ntfs_log_perror("Couldn't create file");
2016 				goto free;
2017 			}
2018 
2019 			ntfs_log_verbose("File has resident data.\n");
2020 			if (write_data(fd, d->data, d->size_data) < d->size_data) {
2021 				ntfs_log_perror("Write failed");
2022 				close(fd);
2023 				goto free;
2024 			}
2025 
2026 			if (close(fd) < 0) {
2027 				ntfs_log_perror("Close failed");
2028 			}
2029 			fd = -1;
2030 		} else {
2031 			rl = d->runlist;
2032 			if (!rl) {
2033 				ntfs_log_verbose("File has no runlist, hence no data.\n");
2034 				continue;
2035 			}
2036 
2037 			if (rl[0].length <= 0) {
2038 				ntfs_log_verbose("File has an empty runlist, hence no data.\n");
2039 				continue;
2040 			}
2041 
2042 			fd = open_file(pathname);
2043 			if (fd < 0) {
2044 				ntfs_log_perror("Couldn't create output file");
2045 				goto free;
2046 			}
2047 
2048 			if (rl[0].lcn == LCN_RL_NOT_MAPPED) {	/* extended mft record */
2049 				ntfs_log_verbose("Missing segment at beginning, %lld "
2050 						"clusters.\n",
2051 						(long long)rl[0].length);
2052 				memset(buffer, opts.fillbyte, bufsize);
2053 				for (k = 0; k < rl[0].length * vol->cluster_size; k += bufsize) {
2054 					if (write_data(fd, buffer, bufsize) < bufsize) {
2055 						ntfs_log_perror("Write failed");
2056 						close(fd);
2057 						goto free;
2058 					}
2059 				}
2060 			}
2061 
2062 			cluster_count = 0LL;
2063 			for (i = 0; rl[i].length > 0; i++) {
2064 
2065 				if (rl[i].lcn == LCN_RL_NOT_MAPPED) {
2066 					ntfs_log_verbose("Missing segment at end, "
2067 							"%lld clusters.\n",
2068 							(long long)rl[i].length);
2069 					memset(buffer, opts.fillbyte, bufsize);
2070 					for (k = 0; k < rl[i].length * vol->cluster_size; k += bufsize) {
2071 						if (write_data(fd, buffer, bufsize) < bufsize) {
2072 							ntfs_log_perror("Write failed");
2073 							close(fd);
2074 							goto free;
2075 						}
2076 						cluster_count++;
2077 					}
2078 					continue;
2079 				}
2080 
2081 				if (rl[i].lcn == LCN_HOLE) {
2082 					ntfs_log_verbose("File has a sparse section.\n");
2083 					memset(buffer, 0, bufsize);
2084 					for (k = 0; k < rl[i].length * vol->cluster_size; k += bufsize) {
2085 						if (write_data(fd, buffer, bufsize) < bufsize) {
2086 							ntfs_log_perror("Write failed");
2087 							close(fd);
2088 							goto free;
2089 						}
2090 					}
2091 					continue;
2092 				}
2093 
2094 				start = rl[i].lcn;
2095 				end   = rl[i].lcn + rl[i].length;
2096 
2097 				for (j = start; j < end; j++) {
2098 					if (utils_cluster_in_use(vol, j) && !opts.optimistic) {
2099 						memset(buffer, opts.fillbyte, bufsize);
2100 						if (write_data(fd, buffer, bufsize) < bufsize) {
2101 							ntfs_log_perror("Write failed");
2102 							close(fd);
2103 							goto free;
2104 						}
2105 					} else {
2106 						if (ntfs_cluster_read(vol, j, 1, buffer) < 1) {
2107 							ntfs_log_perror("Read failed");
2108 							close(fd);
2109 							goto free;
2110 						}
2111 						if (write_data(fd, buffer, bufsize) < bufsize) {
2112 							ntfs_log_perror("Write failed");
2113 							close(fd);
2114 							goto free;
2115 						}
2116 						cluster_count++;
2117 					}
2118 				}
2119 			}
2120 			ntfs_log_quiet("\n");
2121 
2122 			/*
2123 			 * The following block of code implements the --truncate option.
2124 			 * Its semantics are as follows:
2125 			 * IF opts.truncate is set AND data stream currently being recovered is
2126 			 * non-resident AND data stream has no holes (100% recoverability) AND
2127 			 * 0 <= (data->size_alloc - data->size_data) <= vol->cluster_size AND
2128 			 * cluster_count * vol->cluster_size == data->size_alloc THEN file
2129 			 * currently being written is truncated to data->size_data bytes before
2130 			 * it's closed.
2131 			 * This multiple checks try to ensure that only files with consistent
2132 			 * values of size/occupied clusters are eligible for truncation. Note
2133 			 * that resident streams need not be truncated, since the original code
2134 			 * already recovers their exact length.                           +mabs
2135 			 */
2136 			if (opts.truncate) {
2137 				if (d->percent == 100 && d->size_alloc >= d->size_data &&
2138 					(d->size_alloc - d->size_data) <= (long long)vol->cluster_size &&
2139 					cluster_count * (long long)vol->cluster_size == d->size_alloc) {
2140 					if (ftruncate(fd, (off_t)d->size_data))
2141 						ntfs_log_perror("Truncation failed");
2142 				} else ntfs_log_quiet("Truncation not performed because file has an "
2143 					"inconsistent $MFT record.\n");
2144 			}
2145 
2146 			if (close(fd) < 0) {
2147 				ntfs_log_perror("Close failed");
2148 			}
2149 			fd = -1;
2150 
2151 		}
2152 		set_date(pathname, file->date);
2153 		if (d->name)
2154 			ntfs_log_quiet("Undeleted '%s:%s' successfully.\n", file->pref_name, d->name);
2155 		else
2156 			ntfs_log_quiet("Undeleted '%s' successfully.\n", file->pref_name);
2157 	}
2158 	result = 1;
2159 free:
2160 	if (buffer)
2161 		free(buffer);
2162 	free_file(file);
2163 	return result;
2164 }
2165 
2166 /**
2167  * scan_disk - Search an NTFS volume for files that could be undeleted
2168  * @vol:  An ntfs volume obtained from ntfs_mount
2169  *
2170  * Read through all the MFT entries looking for deleted files.  For each one
2171  * determine how much of the data lies in unused disk space.
2172  *
2173  * The list can be filtered by name, size and date, using command line options.
2174  *
2175  * Return:  -1  Error, something went wrong
2176  *	     n  Success, the number of recoverable files
2177  */
scan_disk(ntfs_volume * vol)2178 static int scan_disk(ntfs_volume *vol)
2179 {
2180 	s64 nr_mft_records;
2181 	const int BUFSIZE = 8192;
2182 	char *buffer = NULL;
2183 	int results = 0;
2184 	ntfs_attr *attr;
2185 	long long size;
2186 	long long bmpsize;
2187 	long long i;
2188 	int j, k, b;
2189 	int percent;
2190 	struct ufile *file;
2191 	regex_t re;
2192 
2193 	if (!vol)
2194 		return -1;
2195 
2196 	attr = ntfs_attr_open(vol->mft_ni, AT_BITMAP, AT_UNNAMED, 0);
2197 	if (!attr) {
2198 		ntfs_log_perror("ERROR: Couldn't open $MFT/$BITMAP");
2199 		return -1;
2200 	}
2201 	NVolSetNoFixupWarn(vol);
2202 	bmpsize = attr->initialized_size;
2203 
2204 	buffer = malloc(BUFSIZE);
2205 	if (!buffer) {
2206 		ntfs_log_error("ERROR: Couldn't allocate memory in scan_disk()\n");
2207 		results = -1;
2208 		goto out;
2209 	}
2210 
2211 	if (opts.match) {
2212 		int flags = REG_NOSUB;
2213 
2214 		if (!opts.match_case)
2215 			flags |= REG_ICASE;
2216 		if (regcomp(&re, opts.match, flags)) {
2217 			ntfs_log_error("ERROR: Couldn't create a regex.\n");
2218 			goto out;
2219 		}
2220 #ifndef HAVE_REGEX_H
2221 		re->upcase = vol->upcase;
2222 		re->upcase_len = vol->upcase_len;
2223 #endif
2224 	}
2225 
2226 	nr_mft_records = vol->mft_na->initialized_size >>
2227 			vol->mft_record_size_bits;
2228 
2229 	ntfs_log_quiet("Inode    Flags  %%age     Date    Time       Size  Filename\n");
2230 	ntfs_log_quiet("-----------------------------------------------------------------------\n");
2231 	for (i = 0; i < bmpsize; i += BUFSIZE) {
2232 		long long read_count = min((bmpsize - i), BUFSIZE);
2233 		size = ntfs_attr_pread(attr, i, read_count, buffer);
2234 		if (size < 0)
2235 			break;
2236 
2237 		for (j = 0; j < size; j++) {
2238 			b = buffer[j];
2239 			for (k = 0; k < 8; k++, b>>=1) {
2240 				if (((i+j)*8+k) >= nr_mft_records)
2241 					goto done;
2242 				if (b & 1)
2243 					continue;
2244 				file = read_record(vol, (i+j)*8+k);
2245 				if (!file) {
2246 					ntfs_log_error("Couldn't read MFT Record %lld.\n",
2247 							(long long)(i+j)*8+k);
2248 					continue;
2249 				}
2250 
2251 				if ((opts.since > 0) && (file->date <= opts.since))
2252 					goto skip;
2253 				if (opts.match && !name_match(&re, file))
2254 					goto skip;
2255 				if (opts.size_begin && (opts.size_begin > file->max_size))
2256 					goto skip;
2257 				if (opts.size_end && (opts.size_end < file->max_size))
2258 					goto skip;
2259 
2260 				percent = calc_percentage(file, vol);
2261 				if ((opts.percent == -1) || (percent >= opts.percent)) {
2262 					if (opts.verbose)
2263 						dump_record(file);
2264 					else
2265 						list_record(file);
2266 
2267 					/* Was -u specified with no inode
2268 					   so undelete file by regex */
2269 					if (opts.mode == MODE_UNDELETE) {
2270 						if  (!undelete_file(vol, file->inode))
2271 							ntfs_log_verbose("ERROR: Failed to undelete "
2272 								  "inode %lli\n!",
2273 								  file->inode);
2274 						ntfs_log_info("\n");
2275 					}
2276 				}
2277 				if (((opts.percent == -1) && (percent > 0)) ||
2278 				    ((opts.percent > 0)  && (percent >= opts.percent))) {
2279 					results++;
2280 				}
2281 skip:
2282 				free_file(file);
2283 			}
2284 		}
2285 	}
2286 done:
2287 	ntfs_log_quiet("\nFiles with potentially recoverable content: %d\n",
2288 		results);
2289 out:
2290 	if (opts.match)
2291 		regfree(&re);
2292 	free(buffer);
2293 	NVolClearNoFixupWarn(vol);
2294 	if (attr)
2295 		ntfs_attr_close(attr);
2296 	return results;
2297 }
2298 
2299 /**
2300  * copy_mft - Write a range of MFT Records to a file
2301  * @vol:	An ntfs volume obtained from ntfs_mount
2302  * @mft_begin:	First MFT Record to save
2303  * @mft_end:	Last MFT Record to save
2304  *
2305  * Read a number of MFT Records and write them to a file.
2306  *
2307  * Return:  0  Success, all the records were written
2308  *	    1  Error, something went wrong
2309  */
copy_mft(ntfs_volume * vol,long long mft_begin,long long mft_end)2310 static int copy_mft(ntfs_volume *vol, long long mft_begin, long long mft_end)
2311 {
2312 	s64 nr_mft_records;
2313 	char pathname[256];
2314 	ntfs_attr *mft;
2315 	char *buffer;
2316 	const char *name;
2317 	long long i;
2318 	int result = 1;
2319 	int fd;
2320 
2321 	if (!vol)
2322 		return 1;
2323 
2324 	if (mft_end < mft_begin) {
2325 		ntfs_log_error("Range to copy is backwards.\n");
2326 		return 1;
2327 	}
2328 
2329 	buffer = malloc(vol->mft_record_size);
2330 	if (!buffer) {
2331 		ntfs_log_error("Couldn't allocate memory in copy_mft()\n");
2332 		return 1;
2333 	}
2334 
2335 	mft = ntfs_attr_open(vol->mft_ni, AT_DATA, AT_UNNAMED, 0);
2336 	if (!mft) {
2337 		ntfs_log_perror("Couldn't open $MFT/$DATA");
2338 		goto free;
2339 	}
2340 
2341 	name = opts.output;
2342 	if (!name) {
2343 		name = MFTFILE;
2344 		ntfs_log_debug("No output filename, defaulting to '%s'.\n",
2345 				name);
2346 	}
2347 
2348 	create_pathname(opts.dest, name, NULL, pathname, sizeof(pathname));
2349 	fd = open_file(pathname);
2350 	if (fd < 0) {
2351 		ntfs_log_perror("Couldn't open output file '%s'", name);
2352 		goto attr;
2353 	}
2354 
2355 	nr_mft_records = vol->mft_na->initialized_size >>
2356 			vol->mft_record_size_bits;
2357 
2358 	mft_end = min(mft_end, nr_mft_records - 1);
2359 
2360 	ntfs_log_debug("MFT records:\n");
2361 	ntfs_log_debug("\tTotal: %8lld\n", (long long)nr_mft_records);
2362 	ntfs_log_debug("\tBegin: %8lld\n", mft_begin);
2363 	ntfs_log_debug("\tEnd:   %8lld\n", mft_end);
2364 
2365 	for (i = mft_begin; i <= mft_end; i++) {
2366 		if (ntfs_attr_pread(mft, vol->mft_record_size * i,
2367 		    vol->mft_record_size, buffer) < vol->mft_record_size) {
2368 			ntfs_log_perror("Couldn't read MFT Record %lld", i);
2369 			goto close;
2370 		}
2371 
2372 		if (write_data(fd, buffer, vol->mft_record_size) < vol->mft_record_size) {
2373 			ntfs_log_perror("Write failed");
2374 			goto close;
2375 		}
2376 	}
2377 
2378 	ntfs_log_verbose("Read %lld MFT Records\n", mft_end - mft_begin + 1);
2379 	result = 0;
2380 close:
2381 	close(fd);
2382 attr:
2383 	ntfs_attr_close(mft);
2384 free:
2385 	free(buffer);
2386 	return result;
2387 }
2388 
2389 /**
2390  * handle_undelete
2391  *
2392  * Handles the undelete
2393  */
handle_undelete(ntfs_volume * vol)2394 static int handle_undelete(ntfs_volume *vol)
2395 {
2396 	int result = 1;
2397 	int i;
2398 	unsigned long long	inode;
2399 
2400 	/* Check whether (an) inode(s) was specified or at least a regex! */
2401 	if (nr_entries == 0) {
2402 		if (with_regex == 0) {
2403 			ntfs_log_error("ERROR: NO inode(s) AND NO match-regex "
2404 				"specified!\n");
2405 		} else {
2406 			avoid_duplicate_printing= 1;
2407 			result = !scan_disk(vol);
2408 			if (result)
2409 				ntfs_log_verbose("ERROR: Failed to scan device "
2410 					"'%s'.\n", opts.device);
2411 		}
2412 	} else {
2413 		/* Normal undelete by specifying inode(s) */
2414 		ntfs_log_quiet("Inode    Flags  %%age  Date            Size  Filename\n");
2415 		ntfs_log_quiet("---------------------------------------------------------------\n");
2416 
2417 		/* loop all given inodes */
2418 		for (i = 0; i < nr_entries; i++) {
2419 			for (inode = ranges[i].begin; inode <= ranges[i].end; inode ++) {
2420 				/* Now undelete file */
2421 				result = !undelete_file(vol, inode);
2422 				if (result)
2423 					ntfs_log_verbose("ERROR: Failed to "
2424 						"undelete inode %lli\n!", inode);
2425 			}
2426 		}
2427 	}
2428 	return (result);
2429 }
2430 
2431 /**
2432  * main - Begin here
2433  *
2434  * Start from here.
2435  *
2436  * Return:  0  Success, the program worked
2437  *	    1  Error, something went wrong
2438  */
main(int argc,char * argv[])2439 int main(int argc, char *argv[])
2440 {
2441 	ntfs_volume *vol;
2442 	int result = 1;
2443 
2444 	ntfs_log_set_handler(ntfs_log_handler_outerr);
2445 
2446 	with_regex = 0;
2447 	avoid_duplicate_printing = 0;
2448 
2449 	result = parse_options(argc, argv);
2450 	if (result >= 0)
2451 		goto free;
2452 
2453 	utils_set_locale();
2454 
2455 	vol = utils_mount_volume(opts.device, NTFS_MNT_RDONLY |
2456 			(opts.force ? NTFS_MNT_RECOVER : 0));
2457 	if (!vol)
2458 		return 1;
2459 
2460 	/* handling of the different modes */
2461 	switch (opts.mode) {
2462 	/* Scanning */
2463 	case MODE_SCAN:
2464 		result = !scan_disk(vol);
2465 		if (result)
2466 			ntfs_log_verbose("ERROR: Failed to scan device '%s'.\n",
2467 				opts.device);
2468 		break;
2469 
2470 	/* Undelete-handling */
2471 	case MODE_UNDELETE:
2472 		result= handle_undelete(vol);
2473 		break;
2474 
2475 	/* Handling of copy mft */
2476 	case MODE_COPY:
2477 		result = !copy_mft(vol, opts.mft_begin, opts.mft_end);
2478 		if (result)
2479 			ntfs_log_verbose("ERROR: Failed to read MFT blocks "
2480 				"%lld-%lld.\n", (long long)opts.mft_begin,
2481 				(long long)min((vol->mft_na->initialized_size >>
2482 				vol->mft_record_size_bits) , opts.mft_end));
2483 		break;
2484 	default:
2485 		; /* Cannot happen */
2486 	}
2487 
2488 	ntfs_umount(vol, FALSE);
2489 free:
2490 	if (opts.match)
2491 		free(opts.match);
2492 
2493 	return result;
2494 }
2495 
2496