File: TskHelper.cpp

package info (click to toggle)
sleuthkit 4.12.1%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 18,608 kB
  • sloc: ansic: 143,795; cpp: 52,225; java: 37,892; xml: 2,416; python: 1,076; perl: 874; makefile: 439; sh: 184
file content (838 lines) | stat: -rwxr-xr-x 29,862 bytes parent folder | download
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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
/*
** The Sleuth Kit
**
** Brian Carrier [carrier <at> sleuthkit [dot] org]
** Copyright (c) 2010-2019 Brian Carrier.  All Rights reserved
**
** This software is distributed under the Common Public License 1.0
**
*/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <codecvt>

#include "tsk/base/tsk_base_i.h"
#include "tsk/fs/tsk_fs_i.h"
#include "TskHelper.h"
#include "ReportUtil.h"

static std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;

Path2InumCacheData::Path2InumCacheData(TSK_INUM_T a_inum, TSK_FS_DIR *a_tsk_fs_dir) {
    m_inum = a_inum;
    m_tsk_fs_dir = a_tsk_fs_dir;
    m_fs_name_flags = TSK_FS_NAME_FLAG_ALLOC;
}

TskHelper::TskHelper()
{
    reset();
}

TskHelper::~TskHelper()
{
    if (m_img_info) {
        tsk_img_free(m_img_info);
    }
    for (auto itr = m_FSInfoList.begin(); itr != m_FSInfoList.end(); itr++) {
        tsk_fs_close(*itr);
        tsk_fs_free(*itr);
    }
}

void TskHelper::reset() {
    releasePath2InumCache();
    m_img_info = NULL;
    for (auto itr = m_FSInfoList.begin(); itr != m_FSInfoList.end(); itr++) {
        tsk_fs_close(*itr);
    }
    m_FSInfoList.clear();
}

/**
* toUpper: convert string to uppercase
* @param srcStr to convert
* @return uppercase string
*/
std::string TskHelper::toUpper(const std::string &srcStr) {
    std::string outStr(srcStr);
    std::transform(srcStr.begin(), srcStr.end(), outStr.begin(), ::toupper);

    return outStr;
}

/**
* Convert from UTF-16 to UTF-8.
* Returns empty string on error
*/
std::string TskHelper::toNarrow(const std::wstring & a_utf16Str) {
    try {
        std::string narrow = converter.to_bytes(a_utf16Str);
        return narrow;
    }
    catch (...) {
        return "";
    }
}

/**
* Convert from UTF-8 to UTF-16.
* Returns empty string on error
*/
std::wstring TskHelper::toWide(const std::string &a_utf8Str) {
    try {
        std::wstring wide = converter.from_bytes(a_utf8Str);
        return wide;
    }
    catch (...) {
        return L"";
    }
}

/**
* toLower: convert string to lowercase
* @param srcStr to convert
* @return lowercase string
*/
std::string TskHelper::toLower(const std::string &srcStr) {
    std::string outStr(srcStr);
    std::transform(srcStr.begin(), srcStr.end(), outStr.begin(), ::tolower);

    return outStr;
}

std::string TskHelper::intToStr(long l)
{
    std::stringstream ss;
    ss << l;
    return ss.str();
}

std::string TskHelper::intToStr(size_t l)
{
    std::stringstream ss;
    ss << l;
    return ss.str();
}

std::string TskHelper::stripExt(const char *a_name) {
    std::string nameNoExt;
    std::string nameStr = std::string(a_name);

    size_t dotPos = nameStr.rfind(".");
    if (dotPos != std::string::npos)
        nameNoExt = nameStr.substr(0, dotPos);
    else
        nameNoExt = nameStr;

    return nameNoExt;
}

/**
* @param curFileName File name that we are currently evaluating against target
* @param targetFileName File name that we want to match against
* @param ignoreExt True if we are ignoring extensions in file name
* @param a_fs File System that files are coming from
* @returns true if match
*/
bool TskHelper::compareNames(const char *curFileName, const char *targetFileName, bool ignoreExt, TSK_FS_INFO *a_fs) {
    const char *nameToMatch;
    std::string nameNoExt;

    if (ignoreExt) {
        nameNoExt = stripExt(curFileName);
        nameToMatch = nameNoExt.c_str();
    }
    else
        nameToMatch = curFileName;

    if (a_fs->name_cmp(a_fs, nameToMatch, targetFileName) == 0) {
        return true;
    }
    else {
        return false;
    }
}

/*
* Check if the bigStr begins with lilStr
*/

bool TskHelper::startsWith(const std::string &bigStr, const std::string &lilStr) {
    return lilStr.length() <= bigStr.length()
        && equal(lilStr.begin(), lilStr.end(), bigStr.begin());
}

/*
* Check if the string str ends with suffix
*/
bool TskHelper::endsWith(const std::string &str, const std::string &suffix) {
    return str.size() >= suffix.size() &&
        str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
}

/**
 * \ingroup fslib
 *
 * Find the meta data address for a given file name (UTF-8).
 * The basic idea of the function is to break the given name into its
 * subdirectories and start looking for each (starting in the root
 * directory).
 *
 * @param a_fs FS to analyze
 * @param a_path UTF-8 path of file to search for
 * @param anyExtension If true AND the path does not have an extension, then match any file with the same name, but different extension.  If false, then exact match is always done.
 * @param [out] a_result Meta data address, and TSK_FS_NAME_FLAGS of the file
 * @param [out] a_fs_name Copy of name details (or NULL if details not wanted)
 * @param [out] a_fs_file TSK_FS_FILE data if result is 0 (or NULL if file data not wanted). The caller should free the a_fs_file.
 * @returns -1 on (system) error, 0 if found, 1 if not found, 2 if the file path is found but the inode has been reallocated
 */
int
TskHelper::path2Inum(TSK_FS_INFO *a_fs, const char *a_path, bool anyExtension,
    TSKFileNameInfo &a_result, TSK_FS_NAME *a_fs_name, TSK_FS_FILE **a_fs_file) {
    char *cpath;
    size_t clen;
    char *cur_name_to_match;              // The "current" directory or file we are looking for
    char *cur_attr_to_match;             // The "current" attribute of the dir we are looking for
    TSK_INUM_T next_meta;
    uint8_t is_done;

    // std::cout << "TskHlprPath2Inum: Looking for " << a_path << " in FS " << a_fs->offset << std::endl;

    a_result.setINUM(0);
    if (a_fs_file) {
        *a_fs_file = NULL;
    }

    std::string path_matched;
    bool ignoreExt = false;
    TSK_FS_DIR *starting_fs_dir = NULL;


    // copy path to a buffer that we can modify
    clen = strlen(a_path) + 1;
    if ((cpath = (char *)tsk_malloc(clen)) == NULL) {
        return -1;
    }
    strncpy(cpath, a_path, clen);

    //cerr << getNowTimeStr() << "  TSKHlprPath2inum(): Looking for = " << std::string(a_path) << endl;

    // check if we will be looking for an extension
    if (anyExtension) {
        // check if they gave us an extension
        if (stripExt(a_path).compare(a_path) == 0) {
            ignoreExt = true;
        }
    }

    // Get the first part of the directory path. 
    cur_name_to_match = (char *)strtok_r(cpath, "/", &strtok_last);
    cur_attr_to_match = NULL;

    /* If there is no token, then only a '/' was given */
    if (cur_name_to_match == NULL) {
        free(cpath);
        a_result.setINUM(a_fs->root_inum);

        // create the dummy entry if needed
        if (a_fs_name) {
            a_fs_name->meta_addr = a_fs->root_inum;
            // Note that we are not filling in meta_seq -- we could, we just aren't

            a_fs_name->type = TSK_FS_NAME_TYPE_DIR;
            a_fs_name->flags = TSK_FS_NAME_FLAG_ALLOC;
            if (a_fs_name->name)
                a_fs_name->name[0] = '\0';
            if (a_fs_name->shrt_name)
                a_fs_name->shrt_name[0] = '\0';
        }
        return 0;
    }

    /* If this is NTFS, seperate out the attribute of the current directory */
    if (TSK_FS_TYPE_ISNTFS(a_fs->ftype)
        && ((cur_attr_to_match = strchr(cur_name_to_match, ':')) != NULL)) {
        *(cur_attr_to_match) = '\0';
        cur_attr_to_match++;
    }

    std::string targetPathAsString = std::string(a_path);
    std::string targetPathSubString = std::string(a_path);
    bool bCacheHit = false;

    /* Try to find the full path or a subset of it in the cache
     * start with looking up the full path and if that is not found, then
     * strip away directories until we find something. */
    while ((targetPathSubString.length() > 0) && (!bCacheHit))
    {
        const Path2InumCacheData *pInumCacheData = lookupPathToInumCache(a_fs, targetPathSubString.c_str());

        // found in cache
        if (NULL != pInumCacheData) {

            bCacheHit = true;
            TSK_INUM_T inum = pInumCacheData->getInum();

            // We looked up the full path and found it - we're done.
            if (targetPathSubString.length() == targetPathAsString.length()) {
                a_result.setINUM(inum);
                a_result.setFSNameFlags(pInumCacheData->getFSNameFlag());
                if (a_fs_file) {
                    *a_fs_file = NULL;
                }
                free(cpath);
                return 0;
            }

            // We looked up a parent folder.  Store it as a starting point
            // for the next phase of look ups.
            else {
                // set the starting dir and inum for the loop below
                starting_fs_dir = pInumCacheData->getFSDir();
                next_meta = inum;

                std::string remainderPath = targetPathAsString.substr(targetPathSubString.length() + std::string("/").length());
                strcpy(cpath, remainderPath.c_str());
                path_matched = targetPathSubString; // matched so far

                // what is the next item in the path to find
                cur_name_to_match = (char *)strtok_r(cpath, "/", &strtok_last);
                cur_attr_to_match = NULL;

                /* This happens when we need to map to a folder and they
                * specify a trailing / at the end. */
                if (cur_name_to_match == NULL) {
                    a_result.setINUM(inum);
                    if (a_fs_file) {
                        *a_fs_file = NULL;
                    }
                    free(cpath);
                    return 0;
                }
            }
        }
        else { // path not found in cache, go up one level in the path and search in cache again

            size_t lastSlashPos = targetPathSubString.find_last_of("/");
            if ((std::string::npos != lastSlashPos)) {
                targetPathSubString = targetPathSubString.substr(0, lastSlashPos);
            }
            else {
                targetPathSubString.clear();
            }
        }
    }

    if (!bCacheHit) {

        // initialize the first place to look, the root dir
        next_meta = a_fs->root_inum;
        path_matched.clear();
    }

    // we loop until we know the outcome and then exit. 
    // everything should return from inside the loop.
    is_done = 0;
    while (is_done == 0) {
        size_t i;
        const TSK_FS_NAME *fs_name_best = NULL; // set to the best match in the given folder

        TSK_FS_DIR *fs_dir = NULL;
        bool bIsCachedFSDir = false;

        if (NULL != starting_fs_dir) {	// if we found a partial cache hit, then use the cached TSK_FS_DIR as a starting point 
            fs_dir = starting_fs_dir;
            bIsCachedFSDir = true;      // remember this is a cached TSK_FS_DIR, so we don't close it
            starting_fs_dir = NULL;		// not valid for subsequent iterations
        }
        else {
            // open the next directory in the recursion
            if ((fs_dir = tsk_fs_dir_open_meta(a_fs, next_meta)) == NULL) {
                free(cpath);
                return -1;
            }
        }

        /* Verify this is indeed a directory.  We had one reported
         * problem where a file was a disk image and opening it as
         * a directory found the directory entries inside of the file
         * and this caused problems... */
        if (fs_dir->fs_file->meta->type != TSK_FS_META_TYPE_DIR) {
            tsk_error_reset();
            tsk_error_set_errno(TSK_ERR_FS_GENFS);
            tsk_error_set_errstr("Address %" PRIuINUM
                " is not for a directory\n", next_meta);
            free(cpath);
            return -1;
        }

        // cycle through each entry and find the best match
        for (i = 0; i < tsk_fs_dir_getsize(fs_dir); i++) {

            const TSK_FS_NAME *fs_name = NULL;
            uint8_t found_name = 0;

            if ((fs_name = tsk_fs_dir_get_name(fs_dir, i)) == NULL) {
                if (!bIsCachedFSDir) {
                    tsk_fs_dir_close(fs_dir);		// fs-dir may be cached - can't close it
                }
                free(cpath);
                return -1;
            }

            if (fs_name->name == NULL) {
                continue;
            }
            else if ((fs_name->type == TSK_FS_NAME_TYPE_DIR) && (TSK_FS_ISDOT(fs_name->name))) {
                continue;
            }
            // deleted names that point to 0 are not pointing to a valid meta data structure,
            // so skip them since we only want to return valid addresses from this method
            else if ((fs_name->flags & TSK_FS_NAME_FLAG_UNALLOC) && (fs_name->meta_addr == 0)) {
                continue;
            }

            // cache any files that we see in windows/system32 because we so often look for these
            // Main idea was to cache any file in a subfolder of windows/system32.
            if ((fs_name->flags & TSK_FS_NAME_FLAG_ALLOC) &&
                (fs_name->type == TSK_FS_NAME_TYPE_REG) &&
                startsWith(toLower(path_matched), "windows/system32")) {

                Path2InumCacheData *pCacheData = new Path2InumCacheData(fs_name->meta_addr, NULL);
                pCacheData->setFSNameFlag(fs_name->flags);

                std::string tmp = path_matched;
                tmp.append("/");
                tmp.append(fs_name->name);
                if (addPathToInumCache(a_fs, tmp, pCacheData) == false) {
                    // it was already in the cache
                    tsk_fs_dir_close(pCacheData->getFSDir());
                    delete (pCacheData);
                }
            }

            /*
             * Check if this is the name that we are currently looking for,
             * as identified in 'cur_name_to_match'
             */

             /* FAT and NTFS gets a case insensitive comparisons and look for short name */
            if (TSK_FS_TYPE_ISFAT(a_fs->ftype) || TSK_FS_TYPE_ISNTFS(a_fs->ftype)) {
                bool found_base = false;

                if (compareNames(fs_name->name, cur_name_to_match, ignoreExt, a_fs))
                    found_base = true;

                if ((found_base == false) && (fs_name->shrt_name)) {
                    if (compareNames(fs_name->shrt_name, cur_name_to_match, ignoreExt, a_fs))
                        found_base = true;
                }

                if (found_base) {
                    // if we have FAT or NTFS with no attribute specified, we're good
                    if (TSK_FS_TYPE_ISFAT(a_fs->ftype) || (cur_attr_to_match == NULL)) {
                        found_name = 1;
                    }
                    // otherwise, match the attribute name now
                    else {
                        TSK_FS_FILE *fs_file_tmp1 = tsk_fs_file_open_meta(a_fs, NULL, fs_name->meta_addr);
                        if (fs_file_tmp1) {
                            if (fs_file_tmp1->meta) {
                                int cnt, i;

                                // cycle through the attributes
                                cnt = tsk_fs_file_attr_getsize(fs_file_tmp1);
                                for (i = 0; i < cnt; i++) {
                                    const TSK_FS_ATTR *fs_attr =
                                        tsk_fs_file_attr_get_idx(fs_file_tmp1, i);
                                    if (!fs_attr)
                                        continue;

                                    if ((fs_attr->name)
                                        && (a_fs->name_cmp(a_fs, fs_attr->name,
                                            cur_attr_to_match) == 0)) {
                                        found_name = 1;
                                    }
                                }
                            }
                            tsk_fs_file_close(fs_file_tmp1);
                        }
                    }
                }
            }  // not NTFS or FAT
            else {
                if (compareNames(fs_name->name, cur_name_to_match, ignoreExt, a_fs))
                    found_name = 1;
            }

            // If we didn't find the match, go to the next entry in the dir
            if (found_name == 0) {
                continue;
            }

            // if we found something, see if it is better than what we already have
            // if this is our first hit in this folder, it wins
            if (fs_name_best == NULL) {
                fs_name_best = fs_name;
            }
            // if we found an allocated entry, it replaces whatever was there
            else if (fs_name->flags & TSK_FS_NAME_FLAG_ALLOC) {
                fs_name_best = fs_name;
            }
            // we found an unallocated entry 
            else {
                // if the existing 'best' is alloc, it wins
                if (fs_name_best->flags & TSK_FS_NAME_FLAG_ALLOC) {
                    // no-op
                }
                // if the existing 'best' has meta address of 0, we win
                else if (fs_name_best->meta_addr == 0) {
                    fs_name_best = fs_name;
                }
                // the 'best' is equivalent to ours. Keep the original.
                else {
                    // no-op
                }
            }

            // if we matched on an alloc entry, we're done with this directory
            if (fs_name->flags & TSK_FS_NAME_FLAG_ALLOC) {
                break;
            }
        }

        // we found a hit in the directory, now process it
        if (fs_name_best) {
            const char *pname = cur_name_to_match; // save a copy of the current name pointer

            // update path_matched
            if (path_matched.length() == 0) {
                path_matched = cur_name_to_match;
            }
            else {
                path_matched.append("/");
                path_matched.append(cur_name_to_match);
            }

            // save the matched path and its inum/TSK_FS_DIR to cache 
            if (fs_name_best->flags & TSK_FS_NAME_FLAG_ALLOC) {
                TSK_FS_DIR *cache_fs_dir = NULL;
                Path2InumCacheData *pCacheData = NULL;
                if (fs_name_best->type == TSK_FS_NAME_TYPE_DIR) { // if the matched path is a dir, save the TSK_FS_DIR in cache
                    if ((cache_fs_dir = tsk_fs_dir_open_meta(a_fs, fs_name_best->meta_addr)) != NULL) {
                        pCacheData = new Path2InumCacheData(fs_name_best->meta_addr, cache_fs_dir);
                    }
                }
                else { // is a file not a dir, cache the inum alone
                    pCacheData = new Path2InumCacheData(fs_name_best->meta_addr, NULL);
                    pCacheData->setFSNameFlag(fs_name_best->flags);
                }

                if (pCacheData) {
                    if (addPathToInumCache(a_fs, path_matched, pCacheData) == false) {
                        // it was already in the cache
                        tsk_fs_dir_close(pCacheData->getFSDir());
                        delete (pCacheData);
                    }
                }
            }

            // advance to the next dir / file name
            cur_name_to_match = (char *)strtok_r(NULL, "/", &(strtok_last));
            cur_attr_to_match = NULL;

            if (tsk_verbose)
                tsk_fprintf(stderr,
                    "Found it (%s), now looking for %s\n", pname, cur_name_to_match);

            /* That was the last name in the path -- we found the file! */
            if (cur_name_to_match == NULL) {

                // Make sure the matched file hasn't been deleted and reallocated.
                bool isReallocated = false;
                if ((fs_name_best->flags & TSK_FS_NAME_FLAG_UNALLOC)) {
                    TSK_FS_FILE *fs_file2 = tsk_fs_file_open_meta(a_fs, NULL, fs_name_best->meta_addr);
                    if (NULL != fs_file2) {
                        if ((fs_file2->meta->flags & TSK_FS_NAME_FLAG_ALLOC) && (fs_file2->meta->seq != fs_name_best->meta_seq)) { // MFT entry has been reallocated
                            isReallocated = true;
                        }
                        else if ((fs_file2->meta->flags & TSK_FS_NAME_FLAG_UNALLOC) && (fs_file2->meta->seq + 1 != fs_name_best->meta_seq)) { // MFT entry has been reallocated 
                            isReallocated = true;

                        }
                    }
                    else {
                        isReallocated = true; // should this should be a different return code?
                    }
                    tsk_fs_file_close(fs_file2);
                }

                if (!isReallocated) {	// found a match and it isn't reallocated !! - return this
                    a_result.setINUM(fs_name_best->meta_addr);
                    a_result.setFSNameFlags(fs_name_best->flags);

                    // make a copy if one was requested
                    if (a_fs_name) {
                        tsk_fs_name_copy(a_fs_name, fs_name_best);
                    }

                    if (a_fs_file) {
                        // return the TSK_FS_FILE if one was requested
                        *a_fs_file = tsk_fs_file_open_meta(a_fs, NULL, fs_name_best->meta_addr);
                    }
                }

                //cerr << getNowTimeStr() << "TSKHlprPath2inum(): Found = " << std::string(a_path) << endl;

                if (!bIsCachedFSDir) {
                    tsk_fs_dir_close(fs_dir);
                }
                free(cpath);

                return (isReallocated) ? 2 : 0;
            }

            // update the attribute field, if needed
            if (TSK_FS_TYPE_ISNTFS(a_fs->ftype)
                && ((cur_attr_to_match = strchr(cur_name_to_match, ':')) != NULL)) {
                *(cur_attr_to_match) = '\0';
                cur_attr_to_match++;
            }

            // update the value for the next directory to open
            next_meta = fs_name_best->meta_addr;
        }

        // no hit in directory
        else {
            is_done = 1;
        }

        if (!bIsCachedFSDir) {
            tsk_fs_dir_close(fs_dir);
        }
        fs_dir = NULL;  
    }

    // std::out << "TSKHlprPath2inum(): Not found = " << std::string(a_path) << std::endl;

    free(cpath);
    return 1;
}

/**
* lookupPathToInumCache - lookup the given <fs,path> in the cache and return corresponding inum & TSK_FS_DIR
*
* @param input a_fs TSK_FS_INFO for the file system containing the file
* @param input a_path pathname of file/dir to lookup
* @returns Path2InumCacheData* if the given path is found in the cache , NULL otherwise.
*/
const Path2InumCacheData* TskHelper::lookupPathToInumCache(const TSK_FS_INFO *a_fs, const char *a_path) {

    TSK_OFF_T fs_off = a_fs->offset;
    std::string lcPath = toLower(a_path);

    auto itr = m_path2InumCache.find(make_pair(fs_off, lcPath));
    if (itr != m_path2InumCache.end()) {
        const Path2InumCacheData* pCacheData = (*itr).second;
        return pCacheData;
    }
    else
        return NULL;
}

/**
* addPathToInumCache - adds the given <fs,path> & corresponding inum & TSK_FS_DIR to cache map
*
* @param input a_fs TSK_FS_INFO for the file system contaning the file
* @param input a_path pathname of file/dir
* @param input a_cacheData Inum and TSK_FS_DIR *, if applicable
* @returns TRUE if successfuly added to cache , false otherwise.
*/

bool TskHelper::addPathToInumCache(const TSK_FS_INFO *a_fs, const std::string &a_path, const Path2InumCacheData *a_cacheData) {
    TSK_OFF_T fs_off = a_fs->offset;
    std::string lcPath = toLower(a_path);

    if (m_path2InumCache.find(make_pair(fs_off, lcPath)) == m_path2InumCache.end()) {
        m_path2InumCache.insert(make_pair(make_pair(fs_off, lcPath), a_cacheData));
        return true;
    }
    else {
        return false;
    }
}

/**
* releasePath2InumCache - Frees up all data in the Path/Inum cache.
*
* @returns 0 on success, -1 on failure
*/
int TskHelper::releasePath2InumCache() {
    for (auto itr = m_path2InumCache.begin(); itr != m_path2InumCache.end(); itr++) {
        const Path2InumCacheData* pCacheData = (*itr).second;
        TSK_FS_DIR * fs_dir = pCacheData->getFSDir();
        if (NULL != fs_dir) {
            tsk_fs_dir_close(fs_dir);
        }
        delete pCacheData;
    }
    m_path2InumCache.clear();
    return 0;
}

void TskHelper::addFSInfo(TSK_FS_INFO *a_fs_info) {
    if (a_fs_info) {
        m_FSInfoList.push_back(a_fs_info);
    }
}

TSK_FS_INFO *TskHelper::getFSInfo(TSK_OFF_T offset) {
    for (auto itr = m_FSInfoList.begin(); itr != m_FSInfoList.end(); itr++) {
        if ((*itr)->offset == offset) {
            return (*itr);
        }
    }
    return NULL;
}

const std::list<TSK_FS_INFO *> TskHelper::getFSInfoList() {
    return m_FSInfoList;
}

void TskHelper::replaceAll(std::string &str, const std::string &from, const std::string &to) {
    if (from.empty())
        return;
    size_t start_pos = 0;
    while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length();
    }
}

void TskHelper::replaceAll(std::wstring &str, const std::wstring &from, const std::wstring &to) {
    if (from.empty())
        return;
    size_t start_pos = 0;
    while ((start_pos = str.find(from, start_pos)) != std::wstring::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length();
    }
}

/**
* replaceAll - replaces all occurences of 'from' string with the 'to' string, in the given input string, starting the search from specified position
*
* @param input str - input string to examine and modified
* @param input from - string to search for
* @param input to -  string to replace with
* @param input pos - starting position for search
*
* @returns
*/
void TskHelper::replaceAll(std::string &str, const std::string &from, const std::string &to, size_t pos) {
    if (from.empty() || pos >= str.length())
        return;
    size_t start_pos = pos;
    while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length();
    }
}

/*
* Open the file system in the disk image and add it to the TskHelper.getInstance()
*
* @param img Disk image to open
* @param byteOffset Byte offset to start analyzing from
*/
void TskHelper::openFs(TSK_IMG_INFO *img, TSK_OFF_T byteOffset) {
    TSK_FS_INFO *fs_info;
    if ((fs_info = tsk_fs_open_img(img, byteOffset, TSK_FS_TYPE_DETECT)) != NULL) {
        // Tell TSKHelper about this FS
        TskHelper::getInstance().addFSInfo(fs_info);
    }
    else {
        // check if it is bitlocker - POC effort
        char buffer[32];
        tsk_img_read(img, byteOffset, buffer, 32);
        if ((buffer[3] == '-') && (buffer[4] == 'F') &&
            (buffer[5] == 'V') && (buffer[6] == 'E') &&
            (buffer[7] == '-') && (buffer[8] == 'F') &&
            (buffer[9] == 'S') && (buffer[10] == '-'))
        {
            std::cerr << "Volume is encrypted with BitLocker." << std::endl
                << "Volume did not have a file system and has a BitLocker signature" << std::endl;
        }

        ReportUtil::printDebug("Volume does not contain a file system");
        tsk_error_reset();
    }
}

void TskHelper::enumerateFileAndVolumeSystems(TSK_IMG_INFO *img) {
    TSK_VS_INFO *vs_info;
    if ((vs_info = tsk_vs_open(img, 0, TSK_VS_TYPE_DETECT)) == NULL) {
        ReportUtil::printDebug("No volume system found. Looking for file system");
        TskHelper::getInstance().openFs(img, 0);
    }
    else {
        // process the volume system
        //fprintf(stdout, "Partition:\n");
        for (TSK_PNUM_T i = 0; i < vs_info->part_count; i++) {
            const TSK_VS_PART_INFO *vs_part = tsk_vs_part_get(vs_info, i);
            //fprintf(stdout, "#%i: %s Start: %s Length: %s\n",
            //    i, vs_part->desc, std::to_string(vs_part->start).c_str(), std::to_string(vs_part->len).c_str());
            if ((vs_part->flags & TSK_VS_PART_FLAG_UNALLOC) || (vs_part->flags & TSK_VS_PART_FLAG_META)) {
                continue;
            }
            TskHelper::getInstance().openFs(img, vs_part->start * vs_part->vs->block_size);
        }
        tsk_vs_close(vs_info);
    }
}

/*
* Add all FS found in the given image to TskHelp::getInstance()
* Returns TSK_IMG_INFO *, caller should call tsk_img_close(img) when done.
* The FS can be obtained by calling TskHelper::getInstance().getFSInfoList()
* Caller must call TskHelper::getInstance().reset() when done with the FS.
* May exit the program if image failed to open.
*
* @param image Path to image
* @return TSK_IMG_INFO of the opened image if success, NULL if fail.
*/
TSK_IMG_INFO *TskHelper::addFSFromImage(const TSK_TCHAR *image) {
    TSK_IMG_INFO *img;
    TSK_IMG_TYPE_ENUM imgtype = TSK_IMG_TYPE_DETECT;
    unsigned int ssize = 0;

    if ((img = tsk_img_open(1, &image, imgtype, ssize)) == NULL) {
        ReportUtil::consoleOutput(stderr, "%s\n", tsk_error_get());
        return NULL;
    }

    TskHelper::getInstance().reset();
    TskHelper::getInstance().setImgInfo(img);

    TSK_VS_INFO *vs_info;
    if ((vs_info = tsk_vs_open(img, 0, TSK_VS_TYPE_DETECT)) == NULL) {
        TskHelper::getInstance().openFs(img, 0);
    }
    else {
        // process the volume system
        for (TSK_PNUM_T i = 0; i < vs_info->part_count; i++) {
            const TSK_VS_PART_INFO *vs_part = tsk_vs_part_get(vs_info, i);
            if ((vs_part->flags & TSK_VS_PART_FLAG_UNALLOC) || (vs_part->flags & TSK_VS_PART_FLAG_META)) {
                continue;
            }
            TskHelper::getInstance().openFs(img, vs_part->start * vs_part->vs->block_size);
        }
        tsk_vs_close(vs_info);
    }
    return img;
}