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-2018 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-2018 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 /* FALLTHRU */
571 case 'm': case 'M': result *= 4;
572 /* FALLTHRU */
573 case 'w': case 'W': result *= 7;
574 /* FALLTHRU */
575 case 'd': case 'D': result *= 24;
576 /* FALLTHRU */
577 case 'h': case 'H': result *= 3600;
578 /* FALLTHRU */
579 case 0:
580 break;
581
582 default:
583 ntfs_log_error("Invalid time suffix '%s'. Use Y, M, W, D or H.\n", suffix);
584 return 0;
585 }
586
587 now = time(NULL);
588
589 ntfs_log_debug("Time now = %lld, Time then = %lld.\n", (long long) now,
590 (long long) result);
591 *since = now - result;
592 return 1;
593 }
594
595 /**
596 * parse_options - Read and validate the programs command line
597 *
598 * Read the command line, verify the syntax and parse the options.
599 * This function is very long, but quite simple.
600 *
601 * Return: 1 Success
602 * 0 Error, one or more problems
603 */
parse_options(int argc,char * argv[])604 static int parse_options(int argc, char *argv[])
605 {
606 static const char *sopt = "-b:Cc:d:fh?i:m:o:OPp:sS:t:TuqvV";
607 static const struct option lopt[] = {
608 { "byte", required_argument, NULL, 'b' },
609 { "case", no_argument, NULL, 'C' },
610 { "copy", required_argument, NULL, 'c' },
611 { "destination", required_argument, NULL, 'd' },
612 { "force", no_argument, NULL, 'f' },
613 { "help", no_argument, NULL, 'h' },
614 { "inodes", required_argument, NULL, 'i' },
615 //{ "interactive", no_argument, NULL, 'I' },
616 { "match", required_argument, NULL, 'm' },
617 { "optimistic", no_argument, NULL, 'O' },
618 { "output", required_argument, NULL, 'o' },
619 { "parent", no_argument, NULL, 'P' },
620 { "percentage", required_argument, NULL, 'p' },
621 { "quiet", no_argument, NULL, 'q' },
622 { "scan", no_argument, NULL, 's' },
623 { "size", required_argument, NULL, 'S' },
624 { "time", required_argument, NULL, 't' },
625 { "truncate", no_argument, NULL, 'T' },
626 { "undelete", no_argument, NULL, 'u' },
627 { "verbose", no_argument, NULL, 'v' },
628 { "version", no_argument, NULL, 'V' },
629 { NULL, 0, NULL, 0 }
630 };
631
632 int c = -1;
633 char *end = NULL;
634 int err = 0;
635 int ver = 0;
636 int help = 0;
637 int levels = 0;
638
639 opterr = 0; /* We'll handle the errors, thank you. */
640
641 opts.mode = MODE_NONE;
642 opts.uinode = -1;
643 opts.percent = -1;
644 opts.fillbyte = -1;
645 while ((c = getopt_long(argc, argv, sopt, lopt, NULL)) != -1) {
646 switch (c) {
647 case 1: /* A non-option argument */
648 if (!opts.device) {
649 opts.device = argv[optind-1];
650 } else {
651 opts.device = NULL;
652 err++;
653 }
654 break;
655 case 'b':
656 if (opts.fillbyte == (char)-1) {
657 end = NULL;
658 opts.fillbyte = strtol(optarg, &end, 0);
659 if (end && *end)
660 err++;
661 } else {
662 err++;
663 }
664 break;
665 case 'C':
666 opts.match_case++;
667 break;
668 case 'c':
669 if (opts.mode == MODE_NONE) {
670 if (!utils_parse_range(optarg,
671 &opts.mft_begin, &opts.mft_end, TRUE))
672 err++;
673 opts.mode = MODE_COPY;
674 } else {
675 opts.mode = MODE_ERROR;
676 }
677 break;
678 case 'd':
679 if (!opts.dest)
680 opts.dest = optarg;
681 else
682 err++;
683 break;
684 case 'f':
685 opts.force++;
686 break;
687 case 'h':
688 help++;
689 break;
690 case '?':
691 if (ntfs_log_parse_option (argv[optind-1]))
692 break;
693 ntfs_log_error("Unknown option '%s'.\n", argv[optind-1]);
694 err++;
695 break;
696 case 'i':
697 end = NULL;
698 /* parse inodes */
699 if (parse_inode_arg() == -1)
700 err++;
701 if (end && *end)
702 err++;
703 break;
704 case 'm':
705 if (!opts.match) {
706 if (!transform(optarg, &opts.match)) {
707 err++;
708 } else {
709 /* set regex-flag on true ;) */
710 with_regex= 1;
711 }
712 } else {
713 err++;
714 }
715 break;
716 case 'o':
717 if (!opts.output) {
718 opts.output = optarg;
719 } else {
720 err++;
721 }
722 break;
723 case 'O':
724 if (!opts.optimistic) {
725 opts.optimistic++;
726 } else {
727 err++;
728 }
729 break;
730 case 'P':
731 if (!opts.parent) {
732 opts.parent++;
733 } else {
734 err++;
735 }
736 break;
737 case 'p':
738 if (opts.percent == -1) {
739 end = NULL;
740 opts.percent = strtol(optarg, &end, 0);
741 if (end && ((*end != '%') && (*end != 0)))
742 err++;
743 } else {
744 err++;
745 }
746 break;
747 case 'q':
748 opts.quiet++;
749 ntfs_log_clear_levels(NTFS_LOG_LEVEL_QUIET);
750 break;
751 case 's':
752 if (opts.mode == MODE_NONE)
753 opts.mode = MODE_SCAN;
754 else
755 opts.mode = MODE_ERROR;
756 break;
757 case 'S':
758 if ((opts.size_begin > 0) || (opts.size_end > 0) ||
759 !utils_parse_range(optarg, &opts.size_begin,
760 &opts.size_end, TRUE)) {
761 err++;
762 }
763 break;
764 case 't':
765 if (opts.since == 0) {
766 if (!parse_time(optarg, &opts.since))
767 err++;
768 } else {
769 err++;
770 }
771 break;
772 case 'T':
773 opts.truncate++;
774 break;
775 case 'u':
776 if (opts.mode == MODE_NONE) {
777 opts.mode = MODE_UNDELETE;
778 } else {
779 opts.mode = MODE_ERROR;
780 }
781 break;
782 case 'v':
783 opts.verbose++;
784 ntfs_log_set_levels(NTFS_LOG_LEVEL_VERBOSE);
785 break;
786 case 'V':
787 ver++;
788 break;
789 default:
790 if (((optopt == 'b') || (optopt == 'c') ||
791 (optopt == 'd') || (optopt == 'm') ||
792 (optopt == 'o') || (optopt == 'p') ||
793 (optopt == 'S') || (optopt == 't') ||
794 (optopt == 'u')) && (!optarg)) {
795 ntfs_log_error("Option '%s' requires an argument.\n", argv[optind-1]);
796 } else {
797 ntfs_log_error("Unknown option '%s'.\n", argv[optind-1]);
798 }
799 err++;
800 break;
801 }
802 }
803
804 /* Make sure we're in sync with the log levels */
805 levels = ntfs_log_get_levels();
806 if (levels & NTFS_LOG_LEVEL_VERBOSE)
807 opts.verbose++;
808 if (!(levels & NTFS_LOG_LEVEL_QUIET))
809 opts.quiet++;
810
811 if (help || ver) {
812 opts.quiet = 0;
813 } else {
814 if (opts.device == NULL) {
815 if (argc > 1)
816 ntfs_log_error("You must specify exactly one device.\n");
817 err++;
818 }
819
820 if (opts.mode == MODE_NONE) {
821 opts.mode = MODE_SCAN;
822 }
823
824 switch (opts.mode) {
825 case MODE_SCAN:
826 if (opts.output || opts.dest || opts.truncate ||
827 (opts.fillbyte != (char)-1)) {
828 ntfs_log_error("Scan can only be used with --percent, "
829 "--match, --ignore-case, --size and --time.\n");
830 err++;
831 }
832 if (opts.match_case && !opts.match) {
833 ntfs_log_error("The --case option doesn't make sense without the --match option\n");
834 err++;
835 }
836 break;
837
838 case MODE_UNDELETE:
839 /*if ((opts.percent != -1) || (opts.size_begin > 0) || (opts.size_end > 0)) {
840 ntfs_log_error("Undelete can only be used with "
841 "--output, --destination, --byte and --truncate.\n");
842 err++;
843 }*/
844 break;
845 case MODE_COPY:
846 if ((opts.fillbyte != (char)-1) || opts.truncate ||
847 (opts.percent != -1) ||
848 opts.match || opts.match_case ||
849 (opts.size_begin > 0) ||
850 (opts.size_end > 0)) {
851 ntfs_log_error("Copy can only be used with --output and --destination.\n");
852 err++;
853 }
854 break;
855 default:
856 ntfs_log_error("You can only select one of Scan, Undelete or Copy.\n");
857 err++;
858 }
859
860 if ((opts.percent < -1) || (opts.percent > 100)) {
861 ntfs_log_error("Percentage value must be in the range 0 - 100.\n");
862 err++;
863 }
864
865 if (opts.quiet) {
866 if (opts.verbose) {
867 ntfs_log_error("You may not use --quiet and --verbose at the same time.\n");
868 err++;
869 } else if (opts.mode == MODE_SCAN) {
870 ntfs_log_error("You may not use --quiet when scanning a volume.\n");
871 err++;
872 }
873 }
874
875 if (opts.parent && !opts.verbose) {
876 ntfs_log_error("To use --parent, you must also use --verbose.\n");
877 err++;
878 }
879 }
880
881 if (opts.fillbyte == (char)-1)
882 opts.fillbyte = 0;
883
884 if (ver)
885 version();
886 if (help || err)
887 usage();
888
889 /* tri-state 0 : done, 1 : error, -1 : proceed */
890 return (err ? 1 : (help || ver ? 0 : -1));
891 }
892
893 /**
894 * free_file - Release the resources used by a file object
895 * @file: The unwanted file object
896 *
897 * This will free up the memory used by a file object and iterate through the
898 * object's children, freeing their resources too.
899 *
900 * Return: none
901 */
free_file(struct ufile * file)902 static void free_file(struct ufile *file)
903 {
904 struct ntfs_list_head *item, *tmp;
905
906 if (!file)
907 return;
908
909 ntfs_list_for_each_safe(item, tmp, &file->name) {
910 /* List of filenames */
911 struct filename *f = ntfs_list_entry(item, struct filename, list);
912 ntfs_log_debug("freeing filename '%s'", f->name ? f->name :
913 NONE);
914 if (f->name)
915 free(f->name);
916 if (f->parent_name) {
917 ntfs_log_debug(" and parent filename '%s'",
918 f->parent_name);
919 free(f->parent_name);
920 }
921 ntfs_log_debug(".\n");
922 free(f);
923 }
924
925 ntfs_list_for_each_safe(item, tmp, &file->data) {
926 /* List of data streams */
927 struct data *d = ntfs_list_entry(item, struct data, list);
928 ntfs_log_debug("Freeing data stream '%s'.\n", d->name ?
929 d->name : UNNAMED);
930 if (d->name)
931 free(d->name);
932 if (d->runlist)
933 free(d->runlist);
934 free(d);
935 }
936
937 free(file->mft);
938 free(file);
939 }
940
941 /**
942 * verify_parent - confirm a record is parent of a file
943 * @name: a filename of the file
944 * @rec: the mft record of the possible parent
945 *
946 * Check that @rec is the parent of the file represented by @name.
947 * If @rec is a directory, but it is created after @name, then we
948 * can't determine whether @rec is really @name's parent.
949 *
950 * Return: @rec's filename, either same name space as @name or lowest space.
951 * NULL if can't determine parenthood or on error.
952 */
verify_parent(struct filename * name,MFT_RECORD * rec)953 static FILE_NAME_ATTR* verify_parent(struct filename* name, MFT_RECORD* rec)
954 {
955 ATTR_RECORD *attr30;
956 FILE_NAME_ATTR *filename_attr = NULL, *lowest_space_name = NULL;
957 ntfs_attr_search_ctx *ctx;
958 int found_same_space = 1;
959
960 if (!name || !rec)
961 return NULL;
962
963 if (!(rec->flags & MFT_RECORD_IS_DIRECTORY)) {
964 return NULL;
965 }
966
967 ctx = ntfs_attr_get_search_ctx(NULL, rec);
968 if (!ctx) {
969 ntfs_log_error("ERROR: Couldn't create a search context.\n");
970 return NULL;
971 }
972
973 attr30 = find_attribute(AT_FILE_NAME, ctx);
974 if (!attr30) {
975 return NULL;
976 }
977
978 filename_attr = (FILE_NAME_ATTR*)((char*)attr30 + le16_to_cpu(attr30->value_offset));
979 /* if name is older than this dir -> can't determine */
980 if (ntfs2timespec(filename_attr->creation_time).tv_sec > name->date_c) {
981 return NULL;
982 }
983
984 if (filename_attr->file_name_type != name->name_space) {
985 found_same_space = 0;
986 lowest_space_name = filename_attr;
987
988 while (!found_same_space && (attr30 = find_attribute(AT_FILE_NAME, ctx))) {
989 filename_attr = (FILE_NAME_ATTR*)((char*)attr30 + le16_to_cpu(attr30->value_offset));
990
991 if (filename_attr->file_name_type == name->name_space) {
992 found_same_space = 1;
993 } else {
994 if (filename_attr->file_name_type < lowest_space_name->file_name_type) {
995 lowest_space_name = filename_attr;
996 }
997 }
998 }
999 }
1000
1001 ntfs_attr_put_search_ctx(ctx);
1002
1003 return (found_same_space ? filename_attr : lowest_space_name);
1004 }
1005
1006 /**
1007 * get_parent_name - Find the name of a file's parent.
1008 * @name: the filename whose parent's name to find
1009 */
get_parent_name(struct filename * name,ntfs_volume * vol)1010 static void get_parent_name(struct filename* name, ntfs_volume* vol)
1011 {
1012 ntfs_attr* mft_data;
1013 MFT_RECORD* rec;
1014 FILE_NAME_ATTR* filename_attr;
1015 long long inode_num;
1016
1017 if (!name || !vol)
1018 return;
1019
1020 rec = calloc(1, vol->mft_record_size);
1021 if (!rec) {
1022 ntfs_log_error("ERROR: Couldn't allocate memory in "
1023 "get_parent_name()\n");
1024 return;
1025 }
1026
1027 mft_data = ntfs_attr_open(vol->mft_ni, AT_DATA, AT_UNNAMED, 0);
1028 if (!mft_data) {
1029 ntfs_log_perror("ERROR: Couldn't open $MFT/$DATA");
1030 } else {
1031 inode_num = MREF_LE(name->parent_mref);
1032
1033 if (ntfs_attr_pread(mft_data, vol->mft_record_size * inode_num,
1034 vol->mft_record_size, rec) < 1) {
1035 ntfs_log_error("ERROR: Couldn't read MFT Record %lld"
1036 ".\n", inode_num);
1037 } else if ((filename_attr = verify_parent(name, rec))) {
1038 if (ntfs_ucstombs(filename_attr->file_name,
1039 filename_attr->file_name_length,
1040 &name->parent_name, 0) < 0) {
1041 ntfs_log_debug("ERROR: Couldn't translate "
1042 "filename to current "
1043 "locale.\n");
1044 name->parent_name = NULL;
1045 }
1046 }
1047 }
1048
1049 if (mft_data) {
1050 ntfs_attr_close(mft_data);
1051 }
1052
1053 if (rec) {
1054 free(rec);
1055 }
1056
1057 return;
1058 }
1059
1060 /*
1061 * Rescue the last deleted name of a file
1062 *
1063 * Under some conditions, when a name is deleted and the MFT
1064 * record is shifted to reclaim the space, the name is still
1065 * present beyond the end of record.
1066 *
1067 * For this to be possible, the data record has to be small (less
1068 * than 80 bytes), and there must be no other attributes.
1069 * So only the names of plain unfragmented files can be rescued.
1070 *
1071 * Returns NULL when the name cannot be recovered.
1072 */
1073
rescue_name(MFT_RECORD * mft,ntfs_attr_search_ctx * ctx)1074 static struct filename *rescue_name(MFT_RECORD *mft, ntfs_attr_search_ctx *ctx)
1075 {
1076 ATTR_RECORD *rec;
1077 struct filename *name;
1078 int off_name;
1079 int length;
1080 int type;
1081
1082 name = (struct filename*)NULL;
1083 ntfs_attr_reinit_search_ctx(ctx);
1084 rec = find_attribute(AT_DATA, ctx);
1085 if (rec) {
1086 /*
1087 * If the data attribute replaced the name attribute,
1088 * the name itself is at offset 0x58 from the data attr.
1089 * First be sure this location is within the unused part
1090 * of the MFT record, then make extra checks.
1091 */
1092 off_name = (long)rec - (long)mft + 0x58;
1093 if ((off_name >= (int)le32_to_cpu(mft->bytes_in_use))
1094 && ((off_name + 4)
1095 <= (int)le32_to_cpu(mft->bytes_allocated))) {
1096 length = *((char*)mft + off_name);
1097 type = *((char*)mft + off_name + 1);
1098 /* check whether the name is fully allocated */
1099 if ((type <= 3)
1100 && (length > 0)
1101 && ((off_name + 2*length + 2)
1102 <= (int)le32_to_cpu(mft->bytes_allocated))) {
1103 /* create a (partial) name record */
1104 name = (struct filename*)
1105 ntfs_calloc(sizeof(*name));
1106 if (name) {
1107 name->uname = (ntfschar*)
1108 ((char*)mft + off_name + 2);
1109 name->uname_len = length;
1110 name->name_space = type;
1111 if (ntfs_ucstombs(name->uname, length,
1112 &name->name, 0) < 0) {
1113 free(name);
1114 name = (struct filename*)NULL;
1115 }
1116 }
1117 if (name && name->name)
1118 ntfs_log_verbose("Recovered file name %s\n",
1119 name->name);
1120 }
1121 }
1122 }
1123 return (name);
1124 }
1125
1126
1127
1128 /**
1129 * get_filenames - Read an MFT Record's $FILENAME attributes
1130 * @file: The file object to work with
1131 *
1132 * A single file may have more than one filename. This is quite common.
1133 * Windows creates a short DOS name for each long name, e.g. LONGFI~1.XYZ,
1134 * LongFiLeName.xyZ.
1135 *
1136 * The filenames that are found are put in filename objects and added to a
1137 * linked list of filenames in the file object. For convenience, the unicode
1138 * filename is converted into the current locale and stored in the filename
1139 * object.
1140 *
1141 * One of the filenames is picked (the one with the lowest numbered namespace)
1142 * and its locale friendly name is put in pref_name.
1143 *
1144 * Return: n The number of $FILENAME attributes found
1145 * -1 Error
1146 */
get_filenames(struct ufile * file,ntfs_volume * vol)1147 static int get_filenames(struct ufile *file, ntfs_volume* vol)
1148 {
1149 ATTR_RECORD *rec;
1150 FILE_NAME_ATTR *attr;
1151 ntfs_attr_search_ctx *ctx;
1152 struct filename *name;
1153 int count = 0;
1154 int space = 4;
1155
1156 if (!file)
1157 return -1;
1158
1159 ctx = ntfs_attr_get_search_ctx(NULL, file->mft);
1160 if (!ctx)
1161 return -1;
1162
1163 while ((rec = find_attribute(AT_FILE_NAME, ctx))) {
1164 /* We know this will always be resident. */
1165 attr = (FILE_NAME_ATTR *)((char *)rec +
1166 le16_to_cpu(rec->value_offset));
1167
1168 name = calloc(1, sizeof(*name));
1169 if (!name) {
1170 ntfs_log_error("ERROR: Couldn't allocate memory in "
1171 "get_filenames().\n");
1172 count = -1;
1173 break;
1174 }
1175
1176 name->uname = attr->file_name;
1177 name->uname_len = attr->file_name_length;
1178 name->name_space = attr->file_name_type;
1179 name->size_alloc = sle64_to_cpu(attr->allocated_size);
1180 name->size_data = sle64_to_cpu(attr->data_size);
1181 name->flags = attr->file_attributes;
1182
1183 name->date_c = ntfs2timespec(attr->creation_time).tv_sec;
1184 name->date_a = ntfs2timespec(attr->last_data_change_time).tv_sec;
1185 name->date_m = ntfs2timespec(attr->last_mft_change_time).tv_sec;
1186 name->date_r = ntfs2timespec(attr->last_access_time).tv_sec;
1187
1188 if (ntfs_ucstombs(name->uname, name->uname_len, &name->name,
1189 0) < 0) {
1190 ntfs_log_debug("ERROR: Couldn't translate filename to "
1191 "current locale.\n");
1192 }
1193
1194 name->parent_name = NULL;
1195
1196 if (opts.parent) {
1197 name->parent_mref = attr->parent_directory;
1198 get_parent_name(name, vol);
1199 }
1200
1201 if (name->name_space < space) {
1202 file->pref_name = name->name;
1203 file->pref_pname = name->parent_name;
1204 space = name->name_space;
1205 }
1206
1207 file->max_size = max(file->max_size, name->size_alloc);
1208 file->max_size = max(file->max_size, name->size_data);
1209
1210 ntfs_list_add_tail(&name->list, &file->name);
1211 count++;
1212 }
1213
1214 if (!count) {
1215 name = rescue_name(file->mft,ctx);
1216 if (name) {
1217 /* a name was recovered, get missing attributes */
1218 file->pref_name = name->name;
1219 ntfs_attr_reinit_search_ctx(ctx);
1220 rec = find_attribute(AT_STANDARD_INFORMATION, ctx);
1221 if (rec) {
1222 attr = (FILE_NAME_ATTR *)((char *)rec +
1223 le16_to_cpu(rec->value_offset));
1224 name->flags = attr->file_attributes;
1225
1226 name->date_c = ntfs2timespec(attr->creation_time).tv_sec;
1227 name->date_a = ntfs2timespec(attr->last_data_change_time).tv_sec;
1228 name->date_m = ntfs2timespec(attr->last_mft_change_time).tv_sec;
1229 name->date_r = ntfs2timespec(attr->last_access_time).tv_sec;
1230 }
1231 rec = find_attribute(AT_DATA, ctx);
1232 if (rec) {
1233 attr = (FILE_NAME_ATTR *)((char *)rec +
1234 le16_to_cpu(rec->value_offset));
1235 name->size_alloc = sle64_to_cpu(attr->allocated_size);
1236 name->size_data = sle64_to_cpu(attr->data_size);
1237 }
1238 ntfs_list_add_tail(&name->list, &file->name);
1239 count++;
1240 }
1241 }
1242 ntfs_attr_put_search_ctx(ctx);
1243 ntfs_log_debug("File has %d names.\n", count);
1244 return count;
1245 }
1246
1247 /**
1248 * get_data - Read an MFT Record's $DATA attributes
1249 * @file: The file object to work with
1250 * @vol: An ntfs volume obtained from ntfs_mount
1251 *
1252 * A file may have more than one data stream. All files will have an unnamed
1253 * data stream which contains the file's data. Some Windows applications store
1254 * extra information in a separate stream.
1255 *
1256 * The streams that are found are put in data objects and added to a linked
1257 * list of data streams in the file object.
1258 *
1259 * Return: n The number of $FILENAME attributes found
1260 * -1 Error
1261 */
get_data(struct ufile * file,ntfs_volume * vol)1262 static int get_data(struct ufile *file, ntfs_volume *vol)
1263 {
1264 ATTR_RECORD *rec;
1265 ntfs_attr_search_ctx *ctx;
1266 int count = 0;
1267 struct data *data;
1268
1269 if (!file)
1270 return -1;
1271
1272 ctx = ntfs_attr_get_search_ctx(NULL, file->mft);
1273 if (!ctx)
1274 return -1;
1275
1276 while ((rec = find_attribute(AT_DATA, ctx))) {
1277 data = calloc(1, sizeof(*data));
1278 if (!data) {
1279 ntfs_log_error("ERROR: Couldn't allocate memory in "
1280 "get_data().\n");
1281 count = -1;
1282 break;
1283 }
1284
1285 data->resident = !rec->non_resident;
1286 data->compressed = (rec->flags & ATTR_IS_COMPRESSED) ? 1 : 0;
1287 data->encrypted = (rec->flags & ATTR_IS_ENCRYPTED) ? 1 : 0;
1288
1289 if (rec->name_length) {
1290 data->uname = (ntfschar *)((char *)rec +
1291 le16_to_cpu(rec->name_offset));
1292 data->uname_len = rec->name_length;
1293
1294 if (ntfs_ucstombs(data->uname, data->uname_len,
1295 &data->name, 0) < 0) {
1296 ntfs_log_error("ERROR: Cannot translate name "
1297 "into current locale.\n");
1298 }
1299 }
1300
1301 if (data->resident) {
1302 data->size_data = le32_to_cpu(rec->value_length);
1303 data->data = (char*)rec +
1304 le16_to_cpu(rec->value_offset);
1305 } else {
1306 data->size_alloc = sle64_to_cpu(rec->allocated_size);
1307 data->size_data = sle64_to_cpu(rec->data_size);
1308 data->size_init = sle64_to_cpu(rec->initialized_size);
1309 data->size_vcn = sle64_to_cpu(rec->highest_vcn) + 1;
1310 }
1311
1312 data->runlist = ntfs_mapping_pairs_decompress(vol, rec, NULL);
1313 if (!data->runlist) {
1314 ntfs_log_debug("Couldn't decompress the data runs.\n");
1315 }
1316
1317 file->max_size = max(file->max_size, data->size_data);
1318 file->max_size = max(file->max_size, data->size_init);
1319
1320 ntfs_list_add_tail(&data->list, &file->data);
1321 count++;
1322 }
1323
1324 ntfs_attr_put_search_ctx(ctx);
1325 ntfs_log_debug("File has %d data streams.\n", count);
1326 return count;
1327 }
1328
1329 /**
1330 * read_record - Read an MFT record into memory
1331 * @vol: An ntfs volume obtained from ntfs_mount
1332 * @record: The record number to read
1333 *
1334 * Read the specified MFT record and gather as much information about it as
1335 * possible.
1336 *
1337 * Return: Pointer A ufile object containing the results
1338 * NULL Error
1339 */
read_record(ntfs_volume * vol,long long record)1340 static struct ufile * read_record(ntfs_volume *vol, long long record)
1341 {
1342 ATTR_RECORD *attr10, *attr20, *attr90;
1343 struct ufile *file;
1344 ntfs_attr *mft;
1345 u32 log_levels;
1346
1347 if (!vol)
1348 return NULL;
1349
1350 file = calloc(1, sizeof(*file));
1351 if (!file) {
1352 ntfs_log_error("ERROR: Couldn't allocate memory in read_record()\n");
1353 return NULL;
1354 }
1355
1356 NTFS_INIT_LIST_HEAD(&file->name);
1357 NTFS_INIT_LIST_HEAD(&file->data);
1358 file->inode = record;
1359
1360 file->mft = malloc(vol->mft_record_size);
1361 if (!file->mft) {
1362 ntfs_log_error("ERROR: Couldn't allocate memory in read_record()\n");
1363 free_file(file);
1364 return NULL;
1365 }
1366
1367 mft = ntfs_attr_open(vol->mft_ni, AT_DATA, AT_UNNAMED, 0);
1368 if (!mft) {
1369 ntfs_log_perror("ERROR: Couldn't open $MFT/$DATA");
1370 free_file(file);
1371 return NULL;
1372 }
1373
1374 if (ntfs_attr_mst_pread(mft, vol->mft_record_size * record, 1, vol->mft_record_size, file->mft) < 1) {
1375 ntfs_log_error("ERROR: Couldn't read MFT Record %lld.\n", record);
1376 ntfs_attr_close(mft);
1377 free_file(file);
1378 return NULL;
1379 }
1380
1381 ntfs_attr_close(mft);
1382 mft = NULL;
1383
1384 /* disable errors logging, while examining suspicious records */
1385 log_levels = ntfs_log_clear_levels(NTFS_LOG_LEVEL_PERROR);
1386 attr10 = find_first_attribute(AT_STANDARD_INFORMATION, file->mft);
1387 attr20 = find_first_attribute(AT_ATTRIBUTE_LIST, file->mft);
1388 attr90 = find_first_attribute(AT_INDEX_ROOT, file->mft);
1389
1390 ntfs_log_debug("Attributes present: %s %s %s.\n", attr10?"0x10":"",
1391 attr20?"0x20":"", attr90?"0x90":"");
1392
1393 if (attr10) {
1394 STANDARD_INFORMATION *si;
1395 si = (STANDARD_INFORMATION *) ((char *) attr10 + le16_to_cpu(attr10->value_offset));
1396 file->date = ntfs2timespec(si->last_data_change_time).tv_sec;
1397 }
1398
1399 if (attr20 || !attr10)
1400 file->attr_list = 1;
1401 if (attr90)
1402 file->directory = 1;
1403
1404 if (get_filenames(file, vol) < 0) {
1405 ntfs_log_error("ERROR: Couldn't get filenames.\n");
1406 }
1407 if (get_data(file, vol) < 0) {
1408 ntfs_log_error("ERROR: Couldn't get data streams.\n");
1409 }
1410 /* restore errors logging */
1411 ntfs_log_set_levels(log_levels);
1412
1413 return file;
1414 }
1415
1416 /**
1417 * calc_percentage - Calculate how much of the file is recoverable
1418 * @file: The file object to work with
1419 * @vol: An ntfs volume obtained from ntfs_mount
1420 *
1421 * Read through all the $DATA streams and determine if each cluster in each
1422 * stream is still free disk space. This is just measuring the potential for
1423 * recovery. The data may have still been overwritten by a another file which
1424 * was then deleted.
1425 *
1426 * Files with a resident $DATA stream will have a 100% potential.
1427 *
1428 * N.B. If $DATA attribute spans more than one MFT record (i.e. badly
1429 * fragmented) then only the data in this segment will be used for the
1430 * calculation.
1431 *
1432 * N.B. Currently, compressed and encrypted files cannot be recovered, so they
1433 * will return 0%.
1434 *
1435 * Return: n The percentage of the file that _could_ be recovered
1436 * -1 Error
1437 */
calc_percentage(struct ufile * file,ntfs_volume * vol)1438 static int calc_percentage(struct ufile *file, ntfs_volume *vol)
1439 {
1440 runlist_element *rl = NULL;
1441 struct ntfs_list_head *pos;
1442 struct data *data;
1443 long long i, j;
1444 long long start, end;
1445 int clusters_inuse, clusters_free;
1446 int percent = 0;
1447
1448 if (!file || !vol)
1449 return -1;
1450
1451 if (file->directory) {
1452 ntfs_log_debug("Found a directory: not recoverable.\n");
1453 return 0;
1454 }
1455
1456 if (ntfs_list_empty(&file->data)) {
1457 ntfs_log_verbose("File has no data streams.\n");
1458 return 0;
1459 }
1460
1461 ntfs_list_for_each(pos, &file->data) {
1462 data = ntfs_list_entry(pos, struct data, list);
1463 clusters_inuse = 0;
1464 clusters_free = 0;
1465
1466 if (data->encrypted) {
1467 ntfs_log_verbose("File is encrypted, recovery is "
1468 "impossible.\n");
1469 continue;
1470 }
1471
1472 if (data->compressed) {
1473 ntfs_log_verbose("File is compressed, recovery not yet "
1474 "implemented.\n");
1475 continue;
1476 }
1477
1478 if (data->resident) {
1479 ntfs_log_verbose("File is resident, therefore "
1480 "recoverable.\n");
1481 percent = 100;
1482 data->percent = 100;
1483 continue;
1484 }
1485
1486 rl = data->runlist;
1487 if (!rl) {
1488 ntfs_log_verbose("File has no runlist, hence no data."
1489 "\n");
1490 continue;
1491 }
1492
1493 if (rl[0].length <= 0) {
1494 ntfs_log_verbose("File has an empty runlist, hence no "
1495 "data.\n");
1496 continue;
1497 }
1498
1499 if (rl[0].lcn == LCN_RL_NOT_MAPPED) { /* extended mft record */
1500 ntfs_log_verbose("Missing segment at beginning, %lld "
1501 "clusters\n", (long long)rl[0].length);
1502 clusters_inuse += rl[0].length;
1503 rl++;
1504 }
1505
1506 for (i = 0; rl[i].length > 0; i++) {
1507 if (rl[i].lcn == LCN_RL_NOT_MAPPED) {
1508 ntfs_log_verbose("Missing segment at end, %lld "
1509 "clusters\n",
1510 (long long)rl[i].length);
1511 clusters_inuse += rl[i].length;
1512 continue;
1513 }
1514
1515 if (rl[i].lcn == LCN_HOLE) {
1516 clusters_free += rl[i].length;
1517 continue;
1518 }
1519
1520 start = rl[i].lcn;
1521 end = rl[i].lcn + rl[i].length;
1522
1523 for (j = start; j < end; j++) {
1524 if (utils_cluster_in_use(vol, j))
1525 clusters_inuse++;
1526 else
1527 clusters_free++;
1528 }
1529 }
1530
1531 if ((clusters_inuse + clusters_free) == 0) {
1532 ntfs_log_error("ERROR: Unexpected error whilst "
1533 "calculating percentage for inode %lld\n",
1534 file->inode);
1535 continue;
1536 }
1537
1538 data->percent = (clusters_free * 100) /
1539 (clusters_inuse + clusters_free);
1540
1541 percent = max(percent, data->percent);
1542 }
1543
1544 ntfs_log_verbose("File is %d%% recoverable\n", percent);
1545 return percent;
1546 }
1547
1548 /**
1549 * dump_record - Print everything we know about an MFT record
1550 * @file: The file to work with
1551 *
1552 * Output the contents of the file object. This will print everything that has
1553 * been read from the MFT record, or implied by various means.
1554 *
1555 * Because of the redundant nature of NTFS, there will be some duplication of
1556 * information, though it will have been read from different sources.
1557 *
1558 * N.B. If the filename is missing, or couldn't be converted to the current
1559 * locale, "<none>" will be displayed.
1560 *
1561 * Return: none
1562 */
dump_record(struct ufile * file)1563 static void dump_record(struct ufile *file)
1564 {
1565 char buffer[20];
1566 struct ntfs_list_head *item;
1567 int i;
1568
1569 if (!file)
1570 return;
1571
1572 ntfs_log_quiet("MFT Record %lld\n", file->inode);
1573 ntfs_log_quiet("Type: %s\n", (file->directory) ? "Directory" : "File");
1574 strftime(buffer, sizeof(buffer), "%F %R", localtime(&file->date));
1575 ntfs_log_quiet("Date: %s\n", buffer);
1576
1577 if (file->attr_list)
1578 ntfs_log_quiet("Metadata may span more than one MFT record\n");
1579
1580 ntfs_list_for_each(item, &file->name) {
1581 struct filename *f =
1582 ntfs_list_entry(item, struct filename, list);
1583
1584 ntfs_log_quiet("Filename: (%d) %s\n", f->name_space, f->name);
1585 ntfs_log_quiet("File Flags: ");
1586 if (f->flags & FILE_ATTR_SYSTEM)
1587 ntfs_log_quiet("System ");
1588 if (f->flags & FILE_ATTR_DIRECTORY)
1589 ntfs_log_quiet("Directory ");
1590 if (f->flags & FILE_ATTR_SPARSE_FILE)
1591 ntfs_log_quiet("Sparse ");
1592 if (f->flags & FILE_ATTR_REPARSE_POINT)
1593 ntfs_log_quiet("Reparse ");
1594 if (f->flags & FILE_ATTR_COMPRESSED)
1595 ntfs_log_quiet("Compressed ");
1596 if (f->flags & FILE_ATTR_ENCRYPTED)
1597 ntfs_log_quiet("Encrypted ");
1598 if (!(f->flags & (FILE_ATTR_SYSTEM | FILE_ATTR_DIRECTORY |
1599 FILE_ATTR_SPARSE_FILE | FILE_ATTR_REPARSE_POINT |
1600 FILE_ATTR_COMPRESSED | FILE_ATTR_ENCRYPTED))) {
1601 ntfs_log_quiet("%s", NONE);
1602 }
1603
1604 ntfs_log_quiet("\n");
1605
1606 if (opts.parent) {
1607 ntfs_log_quiet("Parent: %s\n", f->parent_name ?
1608 f->parent_name : "<non-determined>");
1609 }
1610
1611 ntfs_log_quiet("Size alloc: %lld\n", f->size_alloc);
1612 ntfs_log_quiet("Size data: %lld\n", f->size_data);
1613
1614 strftime(buffer, sizeof(buffer), "%F %R",
1615 localtime(&f->date_c));
1616 ntfs_log_quiet("Date C: %s\n", buffer);
1617 strftime(buffer, sizeof(buffer), "%F %R",
1618 localtime(&f->date_a));
1619 ntfs_log_quiet("Date A: %s\n", buffer);
1620 strftime(buffer, sizeof(buffer), "%F %R",
1621 localtime(&f->date_m));
1622 ntfs_log_quiet("Date M: %s\n", buffer);
1623 strftime(buffer, sizeof(buffer), "%F %R",
1624 localtime(&f->date_r));
1625 ntfs_log_quiet("Date R: %s\n", buffer);
1626 }
1627
1628 ntfs_log_quiet("Data Streams:\n");
1629 ntfs_list_for_each(item, &file->data) {
1630 struct data *d = ntfs_list_entry(item, struct data, list);
1631 ntfs_log_quiet("Name: %s\n", (d->name) ? d->name : UNNAMED);
1632 ntfs_log_quiet("Flags: ");
1633 if (d->resident) ntfs_log_quiet("Resident\n");
1634 if (d->compressed) ntfs_log_quiet("Compressed\n");
1635 if (d->encrypted) ntfs_log_quiet("Encrypted\n");
1636 if (!d->resident && !d->compressed && !d->encrypted)
1637 ntfs_log_quiet("None\n");
1638 else
1639 ntfs_log_quiet("\n");
1640
1641 ntfs_log_quiet("Size alloc: %lld\n", d->size_alloc);
1642 ntfs_log_quiet("Size data: %lld\n", d->size_data);
1643 ntfs_log_quiet("Size init: %lld\n", d->size_init);
1644 ntfs_log_quiet("Size vcn: %lld\n", d->size_vcn);
1645
1646 ntfs_log_quiet("Data runs:\n");
1647 if ((!d->runlist) || (d->runlist[0].length <= 0)) {
1648 ntfs_log_quiet(" None\n");
1649 } else {
1650 for (i = 0; d->runlist[i].length > 0; i++) {
1651 ntfs_log_quiet(" %lld @ %lld\n",
1652 (long long)d->runlist[i].length,
1653 (long long)d->runlist[i].lcn);
1654 }
1655 }
1656
1657 ntfs_log_quiet("Amount potentially recoverable %d%%\n",
1658 d->percent);
1659 }
1660
1661 ntfs_log_quiet("________________________________________\n\n");
1662 }
1663
1664 /**
1665 * list_record - Print a one line summary of the file
1666 * @file: The file to work with
1667 *
1668 * Print a one line description of a file.
1669 *
1670 * Inode Flags %age Date Time Size Filename
1671 *
1672 * The output will contain the file's inode number (MFT Record), some flags,
1673 * the percentage of the file that is recoverable, the last modification date,
1674 * the size and the filename.
1675 *
1676 * The flags are F/D = File/Directory, N/R = Data is (Non-)Resident,
1677 * C = Compressed, E = Encrypted, ! = Metadata may span multiple records.
1678 *
1679 * N.B. The file size is stored in many forms in several attributes. This
1680 * display the largest it finds.
1681 *
1682 * N.B. If the filename is missing, or couldn't be converted to the current
1683 * locale, "<none>" will be displayed.
1684 *
1685 * Return: none
1686 */
list_record(struct ufile * file)1687 static void list_record(struct ufile *file)
1688 {
1689 char buffer[20];
1690 struct ntfs_list_head *item;
1691 const char *name = NULL;
1692 long long size = 0;
1693 int percent = 0;
1694
1695 char flagd = '.', flagr = '.', flagc = '.', flagx = '.';
1696
1697 strftime(buffer, sizeof(buffer), "%F %R", localtime(&file->date));
1698
1699 if (file->attr_list)
1700 flagx = '!';
1701
1702 if (file->directory)
1703 flagd = 'D';
1704 else
1705 flagd = 'F';
1706
1707 ntfs_list_for_each(item, &file->data) {
1708 struct data *d = ntfs_list_entry(item, struct data, list);
1709
1710 if (!d->name) {
1711 if (d->resident)
1712 flagr = 'R';
1713 else
1714 flagr = 'N';
1715 if (d->compressed)
1716 flagc = 'C';
1717 if (d->encrypted)
1718 flagc = 'E';
1719
1720 percent = max(percent, d->percent);
1721 }
1722
1723 size = max(size, d->size_data);
1724 size = max(size, d->size_init);
1725 }
1726
1727 if (file->pref_name)
1728 name = file->pref_name;
1729 else
1730 name = NONE;
1731
1732 ntfs_log_quiet("%-8lld %c%c%c%c %3d%% %s %9lld %s\n",
1733 file->inode, flagd, flagr, flagc, flagx,
1734 percent, buffer, size, name);
1735
1736 }
1737
1738 /**
1739 * name_match - Does a file have a name matching a regex
1740 * @re: The regular expression object
1741 * @file: The file to be tested
1742 *
1743 * Iterate through the file's $FILENAME attributes and compare them against the
1744 * regular expression, created with regcomp.
1745 *
1746 * Return: 1 There is a matching filename.
1747 * 0 There is no match.
1748 */
name_match(regex_t * re,struct ufile * file)1749 static int name_match(regex_t *re, struct ufile *file)
1750 {
1751 struct ntfs_list_head *item;
1752 int result;
1753
1754 if (!re || !file)
1755 return 0;
1756
1757 ntfs_list_for_each(item, &file->name) {
1758 struct filename *f =
1759 ntfs_list_entry(item, struct filename, list);
1760
1761 if (!f->name)
1762 continue;
1763 #ifdef HAVE_REGEX_H
1764 result = regexec(re, f->name, 0, NULL, 0);
1765 #else
1766 result = regexec(re, f->uname, f->uname_len, NULL, 0);
1767 #endif
1768 if (result < 0) {
1769 ntfs_log_perror("Couldn't compare filename with regex");
1770 return 0;
1771 } else if (result == REG_NOERROR) {
1772 ntfs_log_debug("Found a matching filename.\n");
1773 return 1;
1774 }
1775 }
1776
1777 ntfs_log_debug("Filename '%s' doesn't match regex.\n", file->pref_name);
1778 return 0;
1779 }
1780
1781 /**
1782 * write_data - Write out a block of data
1783 * @fd: File descriptor to write to
1784 * @buffer: Data to write
1785 * @bufsize: Amount of data to write
1786 *
1787 * Write a block of data to a file descriptor.
1788 *
1789 * Return: -1 Error, something went wrong
1790 * 0 Success, all the data was written
1791 */
write_data(int fd,const char * buffer,unsigned int bufsize)1792 static unsigned int write_data(int fd, const char *buffer,
1793 unsigned int bufsize)
1794 {
1795 ssize_t result1, result2;
1796
1797 if (!buffer) {
1798 errno = EINVAL;
1799 return -1;
1800 }
1801
1802 result1 = write(fd, buffer, bufsize);
1803 if ((result1 == (ssize_t) bufsize) || (result1 < 0))
1804 return result1;
1805
1806 /* Try again with the rest of the buffer */
1807 buffer += result1;
1808 bufsize -= result1;
1809
1810 result2 = write(fd, buffer, bufsize);
1811 if (result2 < 0)
1812 return result1;
1813
1814 return result1 + result2;
1815 }
1816
1817 /**
1818 * create_pathname - Create a path/file from some components
1819 * @dir: Directory in which to create the file (optional)
1820 * @name: Filename to give the file (optional)
1821 * @stream: Name of the stream (optional)
1822 * @buffer: Store the result here
1823 * @bufsize: Size of buffer
1824 *
1825 * Create a filename from various pieces. The output will be of the form:
1826 * dir/file
1827 * dir/file:stream
1828 * file
1829 * file:stream
1830 *
1831 * All the components are optional. If the name is missing, "unknown" will be
1832 * used. If the directory is missing the file will be created in the current
1833 * directory. If the stream name is present it will be appended to the
1834 * filename, delimited by a colon.
1835 *
1836 * N.B. If the buffer isn't large enough the name will be truncated.
1837 *
1838 * Return: n Length of the allocated name
1839 */
create_pathname(const char * dir,const char * name,const char * stream,char * buffer,int bufsize)1840 static int create_pathname(const char *dir, const char *name,
1841 const char *stream, char *buffer, int bufsize)
1842 {
1843 struct stat st;
1844 int s;
1845 int len;
1846 int suffix;
1847
1848 if (!name)
1849 name = UNKNOWN;
1850
1851 if (dir) {
1852 #ifdef HAVE_WINDOWS_H
1853 if (stream)
1854 snprintf(buffer, bufsize, "%s\\%s:%s", dir, name,
1855 stream);
1856 else
1857 snprintf(buffer, bufsize, "%s\\%s", dir, name);
1858 #else
1859 if (stream)
1860 snprintf(buffer, bufsize, "%s/%s:%s", dir, name,
1861 stream);
1862 else
1863 snprintf(buffer, bufsize, "%s/%s", dir, name);
1864 #endif
1865 } else
1866 if (stream)
1867 snprintf(buffer, bufsize, "%s:%s", name, stream);
1868 else
1869 snprintf(buffer, bufsize, "%s", name);
1870 len = strlen(buffer);
1871 suffix = 0;
1872 #ifdef HAVE_WINDOWS_H
1873 s = stat(buffer, &st);
1874 #else
1875 s = lstat(buffer, &st);
1876 #endif
1877 while (!s && (suffix < 999)) {
1878 suffix++;
1879 snprintf(&buffer[len], bufsize - len, ".%d", suffix);
1880 #ifdef HAVE_WINDOWS_H
1881 s = stat(buffer, &st);
1882 #else
1883 s = lstat(buffer, &st);
1884 #endif
1885 }
1886
1887 return strlen(buffer);
1888 }
1889
1890 /**
1891 * open_file - Open a file to write to
1892 * @pathname: Path, name and stream of the file to open
1893 *
1894 * Create a file and return the file descriptor.
1895 *
1896 * N.B. If option force is given and existing file will be overwritten.
1897 *
1898 * Return: -1 Error, failed to create the file
1899 * n Success, this is the file descriptor
1900 */
open_file(const char * pathname)1901 static int open_file(const char *pathname)
1902 {
1903 int flags;
1904
1905 ntfs_log_verbose("Creating file: %s\n", pathname);
1906
1907 if (opts.force)
1908 flags = O_RDWR | O_CREAT | O_TRUNC;
1909 else
1910 flags = O_RDWR | O_CREAT | O_EXCL;
1911 #ifdef HAVE_WINDOWS_H
1912 flags ^= O_BINARY | O_RDWR | O_WRONLY;
1913 #endif
1914
1915 return open(pathname, flags, S_IRUSR | S_IWUSR);
1916 }
1917
1918 /**
1919 * set_date - Set the file's date and time
1920 * @pathname: Path and name of the file to alter
1921 * @date: Date and time to set
1922 *
1923 * Give a file a particular date and time.
1924 *
1925 * Return: 1 Success, set the file's date and time
1926 * 0 Error, failed to change the file's date and time
1927 */
set_date(const char * pathname,time_t date)1928 static int set_date(const char *pathname, time_t date)
1929 {
1930 struct utimbuf ut;
1931
1932 if (!pathname)
1933 return 0;
1934
1935 ut.actime = date;
1936 ut.modtime = date;
1937 if (utime(pathname, &ut)) {
1938 ntfs_log_error("ERROR: Couldn't set the file's date and time\n");
1939 return 0;
1940 }
1941 return 1;
1942 }
1943
1944 /**
1945 * undelete_file - Recover a deleted file from an NTFS volume
1946 * @vol: An ntfs volume obtained from ntfs_mount
1947 * @inode: MFT Record number to be recovered
1948 *
1949 * Read an MFT Record and try an recover any data associated with it. Some of
1950 * the clusters may be in use; these will be filled with zeros or the fill byte
1951 * supplied in the options.
1952 *
1953 * Each data stream will be recovered and saved to a file. The file's name will
1954 * be the original filename and it will be written to the current directory.
1955 * Any named data stream will be saved as filename:streamname.
1956 *
1957 * The output file's name and location can be altered by using the command line
1958 * options.
1959 *
1960 * N.B. We cannot tell if someone has overwritten some of the data since the
1961 * file was deleted.
1962 *
1963 * Return: 0 Error, something went wrong
1964 * 1 Success, the data was recovered
1965 */
undelete_file(ntfs_volume * vol,long long inode)1966 static int undelete_file(ntfs_volume *vol, long long inode)
1967 {
1968 char pathname[256];
1969 char *buffer = NULL;
1970 unsigned int bufsize;
1971 struct ufile *file;
1972 int i, j;
1973 long long start, end;
1974 runlist_element *rl;
1975 struct ntfs_list_head *item;
1976 int fd = -1;
1977 long long k;
1978 int result = 0;
1979 char *name;
1980 long long cluster_count; /* I'll need this variable (see below). +mabs */
1981
1982 if (!vol)
1983 return 0;
1984
1985 /* try to get record */
1986 file = read_record(vol, inode);
1987 if (!file || !file->mft) {
1988 ntfs_log_error("Can't read info from mft record %lld.\n", inode);
1989 return 0;
1990 }
1991
1992 /* if flag was not set, print file informations */
1993 if (avoid_duplicate_printing == 0) {
1994 if (opts.verbose) {
1995 dump_record(file);
1996 } else {
1997 list_record(file);
1998 //ntfs_log_quiet("\n");
1999 }
2000 }
2001
2002 bufsize = vol->cluster_size;
2003 buffer = malloc(bufsize);
2004 if (!buffer)
2005 goto free;
2006
2007 /* calc_percentage() must be called before dump_record() or
2008 * list_record(). Otherwise, when undeleting, a file will always be
2009 * listed as 0% recoverable even if successfully undeleted. +mabs
2010 */
2011 if (file->mft->flags & MFT_RECORD_IN_USE) {
2012 ntfs_log_error("Record is in use by the mft\n");
2013 if (!opts.force) {
2014 free(buffer);
2015 free_file(file);
2016 return 0;
2017 }
2018 ntfs_log_verbose("Forced to continue.\n");
2019 }
2020
2021 if (calc_percentage(file, vol) == 0) {
2022 ntfs_log_quiet("File has no recoverable data.\n");
2023 goto free;
2024 }
2025
2026 if (ntfs_list_empty(&file->data)) {
2027 ntfs_log_quiet("File has no data. There is nothing to recover.\n");
2028 goto free;
2029 }
2030
2031 ntfs_list_for_each(item, &file->data) {
2032 struct data *d = ntfs_list_entry(item, struct data, list);
2033 char defname[sizeof(UNKNOWN) + 25];
2034
2035 if (opts.output)
2036 name = opts.output;
2037 else
2038 if (file->pref_name)
2039 name = file->pref_name;
2040 else {
2041 sprintf(defname,"%s%lld",UNKNOWN,
2042 (long long)file->inode);
2043 name = defname;
2044 }
2045
2046 create_pathname(opts.dest, name, d->name, pathname, sizeof(pathname));
2047 if (d->resident) {
2048 fd = open_file(pathname);
2049 if (fd < 0) {
2050 ntfs_log_perror("Couldn't create file %s",
2051 pathname);
2052 goto free;
2053 }
2054
2055 ntfs_log_verbose("File has resident data.\n");
2056 if (write_data(fd, d->data, d->size_data) < d->size_data) {
2057 ntfs_log_perror("Write failed");
2058 close(fd);
2059 goto free;
2060 }
2061
2062 if (close(fd) < 0) {
2063 ntfs_log_perror("Close failed");
2064 }
2065 fd = -1;
2066 } else {
2067 rl = d->runlist;
2068 if (!rl) {
2069 ntfs_log_verbose("File has no runlist, hence no data.\n");
2070 continue;
2071 }
2072
2073 if (rl[0].length <= 0) {
2074 ntfs_log_verbose("File has an empty runlist, hence no data.\n");
2075 continue;
2076 }
2077
2078 fd = open_file(pathname);
2079 if (fd < 0) {
2080 ntfs_log_perror("Couldn't create file %s",
2081 pathname);
2082 goto free;
2083 }
2084
2085 if (rl[0].lcn == LCN_RL_NOT_MAPPED) { /* extended mft record */
2086 ntfs_log_verbose("Missing segment at beginning, %lld "
2087 "clusters.\n",
2088 (long long)rl[0].length);
2089 memset(buffer, opts.fillbyte, bufsize);
2090 for (k = 0; k < rl[0].length * vol->cluster_size; k += bufsize) {
2091 if (write_data(fd, buffer, bufsize) < bufsize) {
2092 ntfs_log_perror("Write failed");
2093 close(fd);
2094 goto free;
2095 }
2096 }
2097 }
2098
2099 cluster_count = 0LL;
2100 for (i = 0; rl[i].length > 0; i++) {
2101
2102 if (rl[i].lcn == LCN_RL_NOT_MAPPED) {
2103 ntfs_log_verbose("Missing segment at end, "
2104 "%lld clusters.\n",
2105 (long long)rl[i].length);
2106 memset(buffer, opts.fillbyte, bufsize);
2107 for (k = 0; k < rl[i].length * vol->cluster_size; k += bufsize) {
2108 if (write_data(fd, buffer, bufsize) < bufsize) {
2109 ntfs_log_perror("Write failed");
2110 close(fd);
2111 goto free;
2112 }
2113 cluster_count++;
2114 }
2115 continue;
2116 }
2117
2118 if (rl[i].lcn == LCN_HOLE) {
2119 ntfs_log_verbose("File has a sparse section.\n");
2120 memset(buffer, 0, bufsize);
2121 for (k = 0; k < rl[i].length * vol->cluster_size; k += bufsize) {
2122 if (write_data(fd, buffer, bufsize) < bufsize) {
2123 ntfs_log_perror("Write failed");
2124 close(fd);
2125 goto free;
2126 }
2127 }
2128 continue;
2129 }
2130
2131 start = rl[i].lcn;
2132 end = rl[i].lcn + rl[i].length;
2133
2134 for (j = start; j < end; j++) {
2135 if (utils_cluster_in_use(vol, j) && !opts.optimistic) {
2136 memset(buffer, opts.fillbyte, bufsize);
2137 if (write_data(fd, buffer, bufsize) < bufsize) {
2138 ntfs_log_perror("Write failed");
2139 close(fd);
2140 goto free;
2141 }
2142 } else {
2143 if (ntfs_cluster_read(vol, j, 1, buffer) < 1) {
2144 ntfs_log_perror("Read failed");
2145 close(fd);
2146 goto free;
2147 }
2148 if (write_data(fd, buffer, bufsize) < bufsize) {
2149 ntfs_log_perror("Write failed");
2150 close(fd);
2151 goto free;
2152 }
2153 cluster_count++;
2154 }
2155 }
2156 }
2157 ntfs_log_quiet("\n");
2158
2159 /*
2160 * The following block of code implements the --truncate option.
2161 * Its semantics are as follows:
2162 * IF opts.truncate is set AND data stream currently being recovered is
2163 * non-resident AND data stream has no holes (100% recoverability) AND
2164 * 0 <= (data->size_alloc - data->size_data) <= vol->cluster_size AND
2165 * cluster_count * vol->cluster_size == data->size_alloc THEN file
2166 * currently being written is truncated to data->size_data bytes before
2167 * it's closed.
2168 * This multiple checks try to ensure that only files with consistent
2169 * values of size/occupied clusters are eligible for truncation. Note
2170 * that resident streams need not be truncated, since the original code
2171 * already recovers their exact length. +mabs
2172 */
2173 if (opts.truncate) {
2174 if (d->percent == 100 && d->size_alloc >= d->size_data &&
2175 (d->size_alloc - d->size_data) <= (long long)vol->cluster_size &&
2176 cluster_count * (long long)vol->cluster_size == d->size_alloc) {
2177 if (ftruncate(fd, (off_t)d->size_data))
2178 ntfs_log_perror("Truncation failed");
2179 } else ntfs_log_quiet("Truncation not performed because file has an "
2180 "inconsistent $MFT record.\n");
2181 }
2182
2183 if (close(fd) < 0) {
2184 ntfs_log_perror("Close failed");
2185 }
2186 fd = -1;
2187
2188 }
2189 set_date(pathname, file->date);
2190 if (d->name)
2191 ntfs_log_quiet("Undeleted '%s:%s' successfully to %s.\n",
2192 file->pref_name, d->name, pathname);
2193 else
2194 ntfs_log_quiet("Undeleted '%s' successfully to %s.\n",
2195 file->pref_name, pathname);
2196 }
2197 result = 1;
2198 free:
2199 if (buffer)
2200 free(buffer);
2201 free_file(file);
2202 return result;
2203 }
2204
2205 /**
2206 * scan_disk - Search an NTFS volume for files that could be undeleted
2207 * @vol: An ntfs volume obtained from ntfs_mount
2208 *
2209 * Read through all the MFT entries looking for deleted files. For each one
2210 * determine how much of the data lies in unused disk space.
2211 *
2212 * The list can be filtered by name, size and date, using command line options.
2213 *
2214 * Return: -1 Error, something went wrong
2215 * n Success, the number of recoverable files
2216 */
scan_disk(ntfs_volume * vol)2217 static int scan_disk(ntfs_volume *vol)
2218 {
2219 s64 nr_mft_records;
2220 const int BUFSIZE = 8192;
2221 char *buffer = NULL;
2222 int results = 0;
2223 ntfs_attr *attr;
2224 long long size;
2225 long long bmpsize;
2226 long long i;
2227 int j, k, b;
2228 int percent;
2229 struct ufile *file;
2230 regex_t re;
2231
2232 if (!vol)
2233 return -1;
2234
2235 attr = ntfs_attr_open(vol->mft_ni, AT_BITMAP, AT_UNNAMED, 0);
2236 if (!attr) {
2237 ntfs_log_perror("ERROR: Couldn't open $MFT/$BITMAP");
2238 return -1;
2239 }
2240 NVolSetNoFixupWarn(vol);
2241 bmpsize = attr->initialized_size;
2242
2243 buffer = malloc(BUFSIZE);
2244 if (!buffer) {
2245 ntfs_log_error("ERROR: Couldn't allocate memory in scan_disk()\n");
2246 results = -1;
2247 goto out;
2248 }
2249
2250 if (opts.match) {
2251 int flags = REG_NOSUB;
2252
2253 if (!opts.match_case)
2254 flags |= REG_ICASE;
2255 if (regcomp(&re, opts.match, flags)) {
2256 ntfs_log_error("ERROR: Couldn't create a regex.\n");
2257 goto out;
2258 }
2259 #ifndef HAVE_REGEX_H
2260 re->upcase = vol->upcase;
2261 re->upcase_len = vol->upcase_len;
2262 #endif
2263 }
2264
2265 nr_mft_records = vol->mft_na->initialized_size >>
2266 vol->mft_record_size_bits;
2267
2268 ntfs_log_quiet("Inode Flags %%age Date Time Size Filename\n");
2269 ntfs_log_quiet("-----------------------------------------------------------------------\n");
2270 for (i = 0; i < bmpsize; i += BUFSIZE) {
2271 long long read_count = min((bmpsize - i), BUFSIZE);
2272 size = ntfs_attr_pread(attr, i, read_count, buffer);
2273 if (size < 0)
2274 break;
2275
2276 for (j = 0; j < size; j++) {
2277 b = buffer[j];
2278 for (k = 0; k < 8; k++, b>>=1) {
2279 if (((i+j)*8+k) >= nr_mft_records)
2280 goto done;
2281 if (b & 1)
2282 continue;
2283 file = read_record(vol, (i+j)*8+k);
2284 if (!file) {
2285 ntfs_log_error("Couldn't read MFT Record %lld.\n",
2286 (long long)(i+j)*8+k);
2287 continue;
2288 }
2289
2290 if ((opts.since > 0) && (file->date <= opts.since))
2291 goto skip;
2292 if (opts.match && !name_match(&re, file))
2293 goto skip;
2294 if (opts.size_begin && (opts.size_begin > file->max_size))
2295 goto skip;
2296 if (opts.size_end && (opts.size_end < file->max_size))
2297 goto skip;
2298
2299 percent = calc_percentage(file, vol);
2300 if ((opts.percent == -1) || (percent >= opts.percent)) {
2301 if (opts.verbose)
2302 dump_record(file);
2303 else
2304 list_record(file);
2305
2306 /* Was -u specified with no inode
2307 so undelete file by regex */
2308 if (opts.mode == MODE_UNDELETE) {
2309 if (!undelete_file(vol, file->inode))
2310 ntfs_log_verbose("ERROR: Failed to undelete "
2311 "inode %lli\n!",
2312 file->inode);
2313 ntfs_log_info("\n");
2314 }
2315 }
2316 if (((opts.percent == -1) && (percent > 0)) ||
2317 ((opts.percent > 0) && (percent >= opts.percent))) {
2318 results++;
2319 }
2320 skip:
2321 free_file(file);
2322 }
2323 }
2324 }
2325 done:
2326 ntfs_log_quiet("\nFiles with potentially recoverable content: %d\n",
2327 results);
2328 out:
2329 if (opts.match)
2330 regfree(&re);
2331 free(buffer);
2332 NVolClearNoFixupWarn(vol);
2333 if (attr)
2334 ntfs_attr_close(attr);
2335 return results;
2336 }
2337
2338 /**
2339 * copy_mft - Write a range of MFT Records to a file
2340 * @vol: An ntfs volume obtained from ntfs_mount
2341 * @mft_begin: First MFT Record to save
2342 * @mft_end: Last MFT Record to save
2343 *
2344 * Read a number of MFT Records and write them to a file.
2345 *
2346 * Return: 0 Success, all the records were written
2347 * 1 Error, something went wrong
2348 */
copy_mft(ntfs_volume * vol,long long mft_begin,long long mft_end)2349 static int copy_mft(ntfs_volume *vol, long long mft_begin, long long mft_end)
2350 {
2351 s64 nr_mft_records;
2352 char pathname[256];
2353 ntfs_attr *mft;
2354 char *buffer;
2355 const char *name;
2356 long long i;
2357 int result = 1;
2358 int fd;
2359
2360 if (!vol)
2361 return 1;
2362
2363 if (mft_end < mft_begin) {
2364 ntfs_log_error("Range to copy is backwards.\n");
2365 return 1;
2366 }
2367
2368 buffer = malloc(vol->mft_record_size);
2369 if (!buffer) {
2370 ntfs_log_error("Couldn't allocate memory in copy_mft()\n");
2371 return 1;
2372 }
2373
2374 mft = ntfs_attr_open(vol->mft_ni, AT_DATA, AT_UNNAMED, 0);
2375 if (!mft) {
2376 ntfs_log_perror("Couldn't open $MFT/$DATA");
2377 goto free;
2378 }
2379
2380 name = opts.output;
2381 if (!name) {
2382 name = MFTFILE;
2383 ntfs_log_debug("No output filename, defaulting to '%s'.\n",
2384 name);
2385 }
2386
2387 create_pathname(opts.dest, name, NULL, pathname, sizeof(pathname));
2388 fd = open_file(pathname);
2389 if (fd < 0) {
2390 ntfs_log_perror("Couldn't create output file '%s'", name);
2391 goto attr;
2392 }
2393
2394 nr_mft_records = vol->mft_na->initialized_size >>
2395 vol->mft_record_size_bits;
2396
2397 mft_end = min(mft_end, nr_mft_records - 1);
2398
2399 ntfs_log_debug("MFT records:\n");
2400 ntfs_log_debug("\tTotal: %8lld\n", (long long)nr_mft_records);
2401 ntfs_log_debug("\tBegin: %8lld\n", mft_begin);
2402 ntfs_log_debug("\tEnd: %8lld\n", mft_end);
2403
2404 for (i = mft_begin; i <= mft_end; i++) {
2405 if (ntfs_attr_pread(mft, vol->mft_record_size * i,
2406 vol->mft_record_size, buffer) < vol->mft_record_size) {
2407 ntfs_log_perror("Couldn't read MFT Record %lld", i);
2408 goto close;
2409 }
2410
2411 if (write_data(fd, buffer, vol->mft_record_size) < vol->mft_record_size) {
2412 ntfs_log_perror("Write failed");
2413 goto close;
2414 }
2415 }
2416
2417 ntfs_log_verbose("Read %lld MFT Records\n", mft_end - mft_begin + 1);
2418 ntfs_log_quiet("MFT extracted to file %s\n", pathname);
2419 result = 0;
2420 close:
2421 close(fd);
2422 attr:
2423 ntfs_attr_close(mft);
2424 free:
2425 free(buffer);
2426 return result;
2427 }
2428
2429 /**
2430 * handle_undelete
2431 *
2432 * Handles the undelete
2433 */
handle_undelete(ntfs_volume * vol)2434 static int handle_undelete(ntfs_volume *vol)
2435 {
2436 int result = 1;
2437 int i;
2438 unsigned long long inode;
2439
2440 /* Check whether (an) inode(s) was specified or at least a regex! */
2441 if (nr_entries == 0) {
2442 if (with_regex == 0) {
2443 ntfs_log_error("ERROR: NO inode(s) AND NO match-regex "
2444 "specified!\n");
2445 } else {
2446 avoid_duplicate_printing= 1;
2447 result = !scan_disk(vol);
2448 if (result)
2449 ntfs_log_verbose("ERROR: Failed to scan device "
2450 "'%s'.\n", opts.device);
2451 }
2452 } else {
2453 /* Normal undelete by specifying inode(s) */
2454 ntfs_log_quiet("Inode Flags %%age Date Size Filename\n");
2455 ntfs_log_quiet("---------------------------------------------------------------\n");
2456
2457 /* loop all given inodes */
2458 for (i = 0; i < nr_entries; i++) {
2459 for (inode = ranges[i].begin; inode <= ranges[i].end; inode ++) {
2460 /* Now undelete file */
2461 result = !undelete_file(vol, inode);
2462 if (result)
2463 ntfs_log_verbose("ERROR: Failed to "
2464 "undelete inode %lli\n!", inode);
2465 }
2466 }
2467 }
2468 return (result);
2469 }
2470
2471 /**
2472 * main - Begin here
2473 *
2474 * Start from here.
2475 *
2476 * Return: 0 Success, the program worked
2477 * 1 Error, something went wrong
2478 */
main(int argc,char * argv[])2479 int main(int argc, char *argv[])
2480 {
2481 ntfs_volume *vol;
2482 int result = 1;
2483
2484 ntfs_log_set_handler(ntfs_log_handler_outerr);
2485
2486 with_regex = 0;
2487 avoid_duplicate_printing = 0;
2488
2489 result = parse_options(argc, argv);
2490 if (result >= 0)
2491 goto free;
2492
2493 utils_set_locale();
2494
2495 vol = utils_mount_volume(opts.device, NTFS_MNT_RDONLY |
2496 (opts.force ? NTFS_MNT_RECOVER : 0));
2497 if (!vol)
2498 return 1;
2499
2500 /* handling of the different modes */
2501 switch (opts.mode) {
2502 /* Scanning */
2503 case MODE_SCAN:
2504 result = !scan_disk(vol);
2505 if (result)
2506 ntfs_log_verbose("ERROR: Failed to scan device '%s'.\n",
2507 opts.device);
2508 break;
2509
2510 /* Undelete-handling */
2511 case MODE_UNDELETE:
2512 result= handle_undelete(vol);
2513 break;
2514
2515 /* Handling of copy mft */
2516 case MODE_COPY:
2517 result = !copy_mft(vol, opts.mft_begin, opts.mft_end);
2518 if (result)
2519 ntfs_log_verbose("ERROR: Failed to read MFT blocks "
2520 "%lld-%lld.\n", (long long)opts.mft_begin,
2521 (long long)min((vol->mft_na->initialized_size >>
2522 vol->mft_record_size_bits) , opts.mft_end));
2523 break;
2524 default:
2525 ; /* Cannot happen */
2526 }
2527
2528 ntfs_umount(vol, FALSE);
2529 free:
2530 if (opts.match)
2531 free(opts.match);
2532
2533 return result;
2534 }
2535
2536