summaryrefslogtreecommitdiff
path: root/src/scrounge.c
blob: ad340b07ab093a83338ad9c8ad3d21a96e82d0c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
/* 
 * AUTHOR
 * Stef Walter
 *
 * LICENSE
 * This software is in the public domain.
 *
 * The software is provided "as is", without warranty of any kind,
 * express or implied, including but not limited to the warranties
 * of merchantability, fitness for a particular purpose, and
 * noninfringement. In no event shall the author(s) be liable for any
 * claim, damages, or other liability, whether in an action of
 * contract, tort, or otherwise, arising from, out of, or in connection
 * with the software or the use or other dealings in the software.
 * 
 * SUPPORT
 * Send bug reports to: <stef@memberwebs.com>
 */

#define _LARGEFILE_SOURCE
#define _FILE_OFFSET_BITS 64

#include "usuals.h"
#include "scrounge.h"
#include "ntfs.h"
#include "ntfsx.h"
#include "locks.h"

#define PROCESS_MFT_FLAG_SUB      1 << 1
#define DEF_FILE_MODE 0x180
#define DEF_DIR_MODE 0x1C0

typedef struct _filebasics
{
  fchar_t filename[MAX_PATH + 1];
  uint64 created;
  uint64 modified;
  uint64 accessed;
  uint32 flags;
  uint64 parent;
}
filebasics;

void processRecordFileBasics(partitioninfo* pi, ntfsx_record* record, filebasics* basics)
{
  /* Data Attribute */
	ntfsx_attribute* attr = NULL; 
  ntfsx_attrib_enum* attrenum = NULL;

  {
    byte* resident = NULL;
    ntfs_attribfilename* filename;
    byte nameSpace;
    ntfs_char* name;
    size_t len;
#ifndef FC_WIDE
    char* temp;
#endif

    ASSERT(record);
    memset(basics, 0, sizeof(filebasics));
    basics->parent = kInvalidSector;

	  /* Now get the name and info... */
  	attrenum = ntfsx_attrib_enum_alloc(kNTFS_FILENAME, true);

		nameSpace = kNTFS_NameSpacePOSIX;
		memset(basics->filename, 0, sizeof(basics->filename));

		while((attr = ntfsx_attrib_enum_all(attrenum, record)) != NULL)
		{
			/* TODO ASSUMPTION: File name is always resident */
			if(!ntfsx_attribute_header(attr)->bNonResident)
      {
  			/* Get out all the info we need */
		  	filename = (ntfs_attribfilename*)ntfsx_attribute_getresidentdata(attr);
        ASSERT(filename);
		
  			/*
         * There can be multiple filenames with different 
         * namespaces so choose the best one
         */
			  if(ntfs_isbetternamespace(nameSpace, filename->nameSpace))
			  {
				  /* Dates */
          basics->created = filename->timeCreated;
          basics->modified = filename->timeModified;
          basics->accessed = filename->timeRead;

				  /* File Name */
          name = (ntfs_char*)(((byte*)filename) + sizeof(ntfs_attribfilename));
          len = filename->cFileName;
          if(len > MAX_PATH)
            len = MAX_PATH;

#ifdef FC_WIDE
          wcsncpy(basics->filename, name, len);
#else
          temp = unicode_transcode16to8(name, len);

          len = strlen(temp);
          if(len > MAX_PATH)
            len = MAX_PATH;
        
          strncpy(basics->filename, temp, len);
#endif

          basics->filename[len] = 0;


				  /* Attributes */
          basics->flags = filename->flags;


				  /* Parent Directory */
          basics->parent = filename->refParent & kNTFS_RefMask;


				  /* Namespace */
				  nameSpace = filename->nameSpace;
			  }
      }

      ntfsx_attribute_free(attr);
      attr = NULL;
		}
  }

  if(attr)
    ntfsx_attribute_free(attr);

  if(attrenum)
    ntfsx_attrib_enum_free(attrenum);
}

void processMFTRecord(partitioninfo* pi, uint64 sector, uint32 flags)
{
  ntfsx_record* record = NULL;
  ntfsx_attribute* attribdata = NULL;
  ntfsx_attrib_enum* attrenum = NULL;
  ntfsx_datarun* datarun = NULL;
  int ofile = -1;

  ntfsx_cluster cluster;
  memset(&cluster, 0, sizeof(cluster));

  {
    filebasics basics;
    ntfs_recordheader* header;
    uint64 parentSector;
    uint64 dataSector;
    uint16 rename = 0;
    uint64 dataSize = 0;       /* Length of initialized file data */
    uint64 sparseSize = 0;     /* Length of sparse data following */
    uint32 i;
    bool haddata = false;
    uint32 num;
    fchar_t filename2[MAX_PATH + 1];
    ntfs_attribheader* attrhead;
    ntfs_attribnonresident* nonres;

    ASSERT(sector != kInvalidSector);

    record = ntfsx_record_alloc(pi);

    /* Read the MFT record */
	  if(!ntfsx_record_read(record, sector, pi->device))
      RETURN;

    header = ntfsx_record_header(record);
    ASSERT(header);

    if(!(header->flags & kNTFS_RecFlagUse))
      RETURN;

    /* Try and get a file name out of the header */
    processRecordFileBasics(pi, record, &basics);

    /* Without files we skip */
    if(basics.filename[0] == 0)
      RETURN;

    /* If it's the root folder then return */
    if(!fcscmp(basics.filename, FC_DOT))
      RETURN;

    /* System, Hidden files that begin with $ are skipped */
    if(basics.flags & kNTFS_FileSystem && 
       basics.flags & kNTFS_FileHidden &&
       basics.filename[0] == kNTFS_SysPrefix)
      RETURN;

    /* Process parent folders if available */
    if(basics.parent != kInvalidSector)
    {
      /* Only if we have MFT map info available */
      if(pi->mftmap)
      {
        parentSector = ntfsx_mftmap_sectorforindex(pi->mftmap, basics.parent);

        if(parentSector == kInvalidSector)
          warnx("invalid parent directory for file: " FC_PRINTF, basics.filename);
        else
          processMFTRecord(pi, parentSector, flags | PROCESS_MFT_FLAG_SUB);
      }
    }

    printf(flags & PROCESS_MFT_FLAG_SUB ? 
            "\\" FC_PRINTF : "\\" FC_PRINTF "\n", basics.filename);

    /* Directory handling: */
    if(header->flags & kNTFS_RecFlagDir)
    {
      /* Try to change to the directory */
      if(fc_chdir(basics.filename) == -1)
      {
#ifdef _DEBUG
        if(!g_verifyMode)
#endif
        {
#ifdef _WIN32
          if(fc_mkdir(basics.filename) == -1)
#else
		  if(fc_mkdir(basics.filename, DEF_DIR_MODE) == -1)
#endif
          {
            warn("couldn't create directory '" FC_PRINTF "' putting files in parent directory", basics.filename);
          }
          else
          {
            setFileAttributes(basics.filename, basics.flags);
            fc_chdir(basics.filename);
          }
        }
      }

      RETURN;
    }

#ifdef _DEBUG 
    /* If in verify mode */
    if(g_verifyMode)
    {
      ofile = fc_open(basics.filename, O_BINARY | O_RDONLY);

      if(ofile == -1)
      {
        warn("couldn't open verify file: " FC_PRINTF, basics.filename);
        goto cleanup;
      }
    }

    /* Normal file handling: */
    else
#endif
    {
      ofile = fc_open(basics.filename, O_BINARY | O_CREAT | O_EXCL | O_WRONLY, DEF_FILE_MODE);
  
      fcsncpy(filename2, basics.filename, MAX_PATH);
      filename2[MAX_PATH] = 0;

      while(ofile == -1 && errno == EEXIST && rename < 0x1000)
      {
        if(fcslen(basics.filename) + 7 >= MAX_PATH)
        {
          warnx("file name too long on duplicate file: " FC_PRINTF, basics.filename);
          goto cleanup;
        }

        fcscpy(basics.filename, filename2);
        fcscat(basics.filename, FC_DOT);

        itofc(rename, basics.filename + fcslen(basics.filename), 10);
        rename++;

        ofile = fc_open(basics.filename, O_BINARY | O_CREAT | O_EXCL | O_WRONLY, DEF_FILE_MODE);
      }

      if(ofile == -1)
      {
        warn("couldn't open output file: " FC_PRINTF, basics.filename);
        goto cleanup;
      }
    }

    attrenum = ntfsx_attrib_enum_alloc(kNTFS_DATA, true);

    while((attribdata = ntfsx_attrib_enum_all(attrenum, record)) != NULL)
    {
      attrhead = ntfsx_attribute_header(attribdata);

      /* 
       * We don't do compressed/encrypted files. Eventually
       * we may be able to write in some support :)
       */
      if(attrhead->flags & kNTFS_AttrCompressed)
        RETWARNX("compressed file. skipping.");

      if(attrhead->flags & kNTFS_AttrEncrypted)
        RETWARNX("encrypted file. skipping.");

      /* On the first round figure out the file size */
      if(!haddata)
      {
        if(attrhead->bNonResident)
        {
          nonres = (ntfs_attribnonresident*)attrhead;

          if(nonres->cbInitData > nonres->cbAttribData)
            RETWARNX("invalid file length.");

          dataSize = nonres->cbInitData;
          sparseSize = nonres->cbAttribData - nonres->cbInitData;
        }
        else
        {
          dataSize = ntfsx_attribute_getresidentsize(attribdata);
          sparseSize = 0;
        }
      }

      haddata = true;

      /* For resident data just write it out */
      if(!attrhead->bNonResident)
      {
        uint32 length = ntfsx_attribute_getresidentsize(attribdata);
        byte* data = ntfsx_attribute_getresidentdata(attribdata);

        if(!data)
          RETWARNX("invalid mft record. resident data screwed up");

#ifdef _DEBUG
        if(g_verifyMode)
        {
          if(compareFileData(ofile, data, length) != 0)
            RETWARNX("verify failed. read file data wrong.");
        }
        else
#endif
          if(write(ofile, data, length) != (int32)length)
            RETWARN("couldn't write data to output file");

        dataSize -= length;
      }

      /* For non resident data it's a bit more involved */
      else
      {
        datarun = ntfsx_attribute_getdatarun(attribdata);
        nonres = (ntfs_attribnonresident*)attrhead;

        /* Allocate a cluster for reading and writing */
        ntfsx_cluster_reserve(&cluster, pi);

        if(ntfsx_datarun_first(datarun))
        {
          do
          {
            /* 
             * In some cases NTFS sloppily leaves many extra
             * data runs mapped for a file, so just cut out 
             * when that's the case 
             */
            if(dataSize == 0)
              break;

            /* Sparse clusters we just write zeros */
            if(datarun->sparse)
            {
              memset(cluster.data, 0, cluster.size);

              for(i = 0; i < datarun->length && dataSize; i++)
              {
                num = cluster.size;

                if(dataSize < 0xFFFFFFFF && num > (uint32)dataSize)
                  num = (uint32)dataSize;

#ifdef _DEBUG
                if(g_verifyMode)
                {
                  if(compareFileData(ofile, cluster.data, num) != 0)
                    RETWARNX("verify failed. read file data wrong.");
                }
                else
#endif
                  if(write(ofile, cluster.data, num) != (int32)num)
                    err(1, "couldn't write to output file: " FC_PRINTF, basics.filename);

                dataSize -= num;
              }
            }

            /* Handle not sparse clusters */
            else
            {
              if(pi->locks)
              {
                /* Add a location lock so any raw scrounging won't do 
                   this cluster later */
                addLocationLock(pi->locks, CLUSTER_TO_SECTOR(*pi, datarun->cluster), 
                      CLUSTER_TO_SECTOR(*pi, datarun->cluster + datarun->length));
              }

              for(i = 0; i < datarun->length && dataSize; i++)
              {
                num = min(cluster.size, (uint32)dataSize);
                dataSector = CLUSTER_TO_SECTOR(*pi, (datarun->cluster + i));

                if(!ntfsx_cluster_read(&cluster, pi, dataSector, pi->device))
                {
                  warn("couldn't read sector from disk");
                  break;
                }

#ifdef _DEBUG
                if(g_verifyMode)
                {
                  if(compareFileData(ofile, cluster.data, num) != 0)
                    RETWARNX("verify failed. read file data wrong.");
                }
                else
#endif
                  if(write(ofile, cluster.data, num) != (int32)num)
                    err(1, "couldn't write to output file: " FC_PRINTF, basics.filename);

                dataSize -= num;
              }
            }
          }
          while(ntfsx_datarun_next(datarun));
        }

        ntfsx_datarun_free(datarun);
        datarun = NULL;
      }

      ntfsx_attribute_free(attribdata);
      attribdata = NULL;

      /* Cut out when there's extra clusters allocated */
      if(dataSize == 0)
        break;
    }

    if(!haddata)
      RETWARNX("invalid mft record. no data attribute found");

		if(dataSize != 0)
      warnx("invalid mft record. couldn't find all data for file");

    /* 
     * Now we write blanks for all the sparse non-inited data 
     * We might be able to just resize the file to the right 
     * size, but let's go the safe way and write out zeros
     */

    if(sparseSize > 0)
    {
      ntfsx_cluster_reserve(&cluster, pi);
      memset(cluster.data, 0, cluster.size);

      while(sparseSize > 0)
      {
        num = cluster.size;

        if(sparseSize < 0xFFFFFFFF && num > (uint32)sparseSize)
          num = (uint32)sparseSize;

#ifdef _DEBUG
        if(g_verifyMode)
        {
          if(compareFileData(ofile, cluster.data, num) != 0)
            RETWARNX("verify failed. read file data wrong.");
        }
        else
#endif
          if(write(ofile, cluster.data, num) != (int32)num)
            err(1, "couldn't write to output file: " FC_PRINTF, basics.filename);

        sparseSize -= num;
      }
    }

    close(ofile);
    ofile = -1;

#ifdef _DEBUG
    if(!g_verifyMode)
#endif
    {
      setFileTime(basics.filename, &(basics.created), 
                &(basics.accessed), &(basics.modified));

      setFileAttributes(basics.filename, basics.flags);
    }
  }

cleanup:
  if(record)
    ntfsx_record_free(record);

  ntfsx_cluster_release(&cluster);

  if(attribdata)
    ntfsx_attribute_free(attribdata);

  if(datarun)
    ntfsx_datarun_free(datarun);

  if(attrenum)
    ntfsx_attrib_enum_free(attrenum);

  if(ofile != -1)
    close(ofile);
}


void scroungeMFT(partitioninfo* pi, ntfsx_mftmap* map)
{
  ntfsx_record* record = NULL;
  uint64 sector;
  filebasics basics;
  ntfs_recordheader* header;

  /* Try and find the MFT at the given location */
  sector = pi->mft + pi->first;

  if(sector >= pi->end)
    errx(2, "invalid mft. past end of partition");

  record = ntfsx_record_alloc(pi);

  /* Read the MFT record */
	if(!ntfsx_record_read(record, sector, pi->device))
		err(1, "couldn't read mft");

  header = ntfsx_record_header(record);
  ASSERT(header);

  if(!(header->flags & kNTFS_RecFlagUse))
    errx(2, "invalid mft. marked as not in use");

  /* Load the MFT data runs */

  if(!ntfsx_mftmap_load(map, record, pi->device))
    err(1, "error reading in mft");

  /* Try and get a file name out of the header */

  processRecordFileBasics(pi, record, &basics);

  if(fcscmp(basics.filename, kNTFS_MFTName))
    errx(2, "invalid mft. wrong record");

  fprintf(stderr, "[Processing MFT...]\n");

  if(ntfsx_mftmap_length(map) == 0)
    errx(1, "invalid mft. no records in mft");

  ntfsx_record_free(record);
}


void scroungeUsingMFT(partitioninfo* pi)
{
	uint64 numRecords = 0;
	fchar_t dir[MAX_PATH];
  ntfsx_mftmap map;
  uint64 length;
  uint64 sector;
  uint64 i;

  fprintf(stderr, "[Scrounging via MFT...]\n");

	/* Save current directory away */
	fc_getcwd(dir, MAX_PATH);

  /* Get the MFT map ready */
  memset(&map, 0, sizeof(map));
  ntfsx_mftmap_init(&map, pi);
  pi->mftmap = &map;


  /* 
   * Make sure the MFT is actually where they say it is.
   * This also fills in the valid cluster size if needed
   */
  scroungeMFT(pi, &map);
  length = ntfsx_mftmap_length(&map);
 
  for(i = 1; i < length; i ++)
  {
    sector = ntfsx_mftmap_sectorforindex(&map, i);
    if(sector == kInvalidSector)
    {
      warnx("invalid index in mft: %d", i);
      continue;
    }

    /* Process the record */
    processMFTRecord(pi, sector, 0);

  	/* Move to right output directory */
    fc_chdir(dir);
	}

  pi->mftmap = NULL;
}

void scroungeUsingRaw(partitioninfo* pi, uint64 skip)
{
  byte buffSec[kSectorSize];
  fchar_t dir[MAX_PATH + 1];
  uint64 sec;
  drivelocks locks;
  int64 pos;
  size_t sz;
  uint32 magic = kNTFS_RecMagic;

  fprintf(stderr, "[Scrounging raw records...]\n");

	/* Save current directory away */
	fc_getcwd(dir, MAX_PATH);

  /* Get the locks ready */
  memset(&locks, 0, sizeof(locks));
  pi->locks = &locks;

	/* Loop through sectors */
	for(sec = pi->first + skip; sec < pi->end; sec++)
	{
    if(checkLocationLock(&locks, sec))
      continue;

#ifdef _WIN32
	fprintf(stderr, "sector: %I64u\r", sec);
#else
	fprintf(stderr, "sector: %llu\r", (unsigned long long)sec);
#endif

  	/* Read	the record */
    pos = SECTOR_TO_BYTES(sec);
    if(lseek64(pi->device, pos, SEEK_SET) == -1)
      errx(1, "can't seek device to sector");

    sz = read(pi->device, buffSec, kSectorSize);
    if(sz == -1 || sz != kSectorSize)
    {
      warn("can't read drive sector");
      continue;
    }

		/* Check beginning of sector for the magic signature */
		if(!memcmp(&magic, &buffSec, sizeof(magic)))
		{
      /* Process the record */
      processMFTRecord(pi, sec, 0);
		}

  	/* Move to right output directory */
    fc_chdir(dir);
	}

  pi->locks = NULL;
}