This file is indexed.

/usr/bin/sorter is in sleuthkit 4.4.2-3.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

   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
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
#!/usr/bin/perl -w
my $BIN_DIR="/usr/bin";
my $DATA_DIR="/usr/share";
my $VER="4.4.2";
#
# The Sleuth Kit
#
# Brian Carrier [carrier <at> sleuthkit [dot] org]
# Copyright (c) 2003-2011 Brian Carrier.  All rights reserved
#
# TASK
# Copyright (c) 2002-2003 Brian Carrier, @stake Inc.  All rights reserved
#
# This software is distributed under the Common Public License 1.0

use strict;
use integer;

my $SHARE_DIR = "$DATA_DIR/tsk/sorter/";

my $SK_FLS     = "${BIN_DIR}/fls";
my $SK_ICAT    = "${BIN_DIR}/icat";
my $SK_HFIND   = "${BIN_DIR}/hfind";
my $SK_FSSTAT  = "${BIN_DIR}/fsstat";
my $SK_IMGSTAT = "${BIN_DIR}/img_stat";
my $SK_FILE    = "";
my $SK_MD5     = "";
my $SK_SHA1    = "";

my $MIS_NAME        = "mismatch";
my $UNK_NAME        = "unknown";
my $ALERT_NAME      = "alert";
my $EXCLUDE_NAME    = "exclude";
my $EXCLUDEMIS_NAME = "mismatch_exclude";
my $IGNORE_NAME     = "ignore";

# Formats for regular expressions
my $REG_DAY   = '\d\d\d\d\-\d\d\-\d\d';
my $REG_TIME  = '\d\d:\d\d:\d\d';
my $REG_ZONE2 = '\([\w\+\- ]*\)';
my $REG_DATE  = "$REG_DAY" . '\s+' . "$REG_TIME" . '\s+' . "$REG_ZONE2";

my $SUMMARY_NAME = "sorter.sum";

# CONSTANTS
my $DEL_ALLOC = 0;    # Allocated File
my $DEL_DEL   = 1;    # Deleted File

# Text / HTML CONSTANTS
my $NL  = "\n";
my $TAB = '  ';
my $EXT = '.txt';
my $BUL = "- ";

my $IMG_PAGE = 100;

# Globals
my $alloc_cnt   = 0;    # Number of allocated files processed
my $dirskip_cnt = 0;    # Files skipped because dir or null size
my $realloc_cnt = 0;    # Files skipped because they were marked as realloc
my $ignore_cnt  = 0;    # Files skipped bc in ignore category
my $alert_cnt   = 0;    # number of files flagged by hash
my $excl_cnt    = 0;    # number of files skipped bc known good
my $mis_cnt     = 0;    # number of mismatch files
my $exclmis_cnt = 0;    # known good file with extension mismatch
my $img_cnt     = 0;    # number of images

sub usage {
    print <<EOF;

sorter [-b size] [-E] [-e] [-h]  [-l] [-md5] [-s] [-sha1] [-U] [-v] [-V] [-a hash_alert] [-c config] [-C config] [-d dir] [-m mnt] [-n nsrl_db] [-x hash_exclude] [-o imgoffset] [-f fstype] [-i imgtype] image [images] [dir_meta_addr] 

    -b size: Minimum size.  Ignore files smaller than 'size'
	-E: Perform category indexing only (no extension checks - was '-i')
	-e: Perform extension checks only (no category index files)
	-h: HTML Format
	-l: List index to STDOUT (no files are ever written)
	-md5: Print the MD5 value with the index output
	-s: Save files to category directories
	-sha1: Print the SHA-1 value with the index output
	-U: Ignore the unknown category - only save catgories in config files
	-v: verbose debugging output
	-V: print version information
	-a hash_alert: hash database of hashes to alert on
	-c config: specify a config file to use (in addition to default files)
	   NOTE: This config file has priority over default files
	-C config: specify the ONLY config file to use
	-d dir: Save category index files in the specified directory
	-f fstype: file system type (Sleuth Kit types) of image
	-i imgtype: Format of image file
	-o imgoffset: Offset of file system in image (in sectors)
	-m mnt: The mounting point of the image
	-n nsrl_db: The NIST NSRL database file (NSRLFile.txt) (hashes to ignore)
	-x hash_exclude: hash database of hashes to ignore
	dir_meta_addr: Address of directory to start analyzing from 
	image: image to analyze
EOF
    exit(1);
}

sub version {
    print "The Sleuth Kit ver $VER\n";
}

my @s_dirs = (
    "/usr/local/bin/", "/usr/local/sbin/",
    "/usr/bin/",       "/usr/sbin/",
    "/bin/",           "/sbin/"
);

sub find_file {
    $SK_FILE = "";
    foreach my $d (@s_dirs) {
        if (-x "${d}file") {
            $SK_FILE = "${d}file";
            return;
        }
    }

    print "File tool not found\n";
    exit(1);
}

sub find_md5 {
    $SK_MD5 = "";
    foreach my $d (@s_dirs) {
        if (-x "${d}md5") {
            $SK_MD5 = "${d}md5";
            return;
        }
    }

    foreach my $d (@s_dirs) {
        if (-x "${d}md5sum") {
            $SK_MD5 = "${d}md5sum";
            return;
        }
    }

    print "md5 or md5sum tool not found\n";
    exit(1);
}

sub find_sha1 {
    $SK_SHA1 = "";
    foreach my $d (@s_dirs) {
        if (-x "${d}sha1") {
            $SK_SHA1 = "${d}sha1";
            return;
        }
    }

    foreach my $d (@s_dirs) {
        if (-x "${d}sha1sum") {
            $SK_SHA1 = "${d}sha1sum";
            return;
        }
    }

    print "sha1 or sha1sum tool not found\n";
    exit(1);
}

# Globals

# Globals
my %file_to_cat;
my @cat_order;
my %file_to_ext = (NOT_USED => [","]);
my @ext_order;
my %cat_handle;
my %output_used;

# Argument variables
my $HTML        = 0;
my $LIST        = 0;
my $SAVE        = 0;
my $VERBOSE     = 0;
my $DO_MD5      = 0;
my $DO_SHA1     = 0;
my $ALL_CONFIGS = 1;
my $DO_INDEX    = 1;    # create index files by category
my $DO_UNKNOWN  = 1;    # Process the files that are unknown
my $DO_EXT      = 1;    # Do extension mismatch analysis
my $MIN_SIZE    = 0;

my $CONFIG     = "";
my $DIR        = "";
my $FSTYPE     = "";
my $IMGTYPE    = "";
my $IMGOFF     = 0;
my $NSRL       = "";
my $PLATFORM   = "";
my $ALERT_DB   = "";
my $EXCLUDE_DB = "";

my $img_shrt;
my $TEMP_FILE;
my $img_str = "";
my $MNT     = "";

usage() if (scalar @ARGV == 0);

# Read the arguments
while (($_ = $ARGV[0]) =~ /^-(.)(.*)/) {

    # Alert hash database
    if (/^-a$/) {
        shift(@ARGV);
        if (defined $ARGV[0]) {
            $ALERT_DB = $ARGV[0];
        }
        else {
            print "-a requires hash database argument\n";
            usage();
        }
        unless (-e "$ALERT_DB") {
            print "Alert hash database $ALERT_DB does not exist\n";
            usage();
        }
        $DO_MD5 = 1;
    }

    # @@@ This is currently not used
    elsif (/^-b$/) {
        shift(@ARGV);
        if (defined $ARGV[0]) {
            $MIN_SIZE = $ARGV[0];
        }
        else {
            print "-b requires a size\n";
            usage();
        }
    }

    # config file to use in addition to other config files
    elsif (/^-c$/) {
        if ($ALL_CONFIGS == 0) {
            print "-c cannot be used with -C\n";
            exit(1);
        }
        shift(@ARGV);
        if (defined $ARGV[0]) {
            $CONFIG = $ARGV[0];
        }
        else {
            print "-c requires config file argument\n";
            usage();
        }
        unless (-e "$CONFIG") {
            print "Config file $CONFIG does not exist\n";
            usage();
        }
    }

    # Exclusive config file to use
    elsif (/^-C$/) {
        if ($CONFIG ne "") {
            print "-C cannot be used with -c\n";
            exit(1);
        }
        shift(@ARGV);
        if (defined $ARGV[0]) {
            $CONFIG = $ARGV[0];
        }
        else {
            print "-C requires config file argument\n";
            usage();
        }
        unless (-e "$CONFIG") {
            print "Config file $CONFIG does not exist\n";
            usage();
        }
        $ALL_CONFIGS = 0;
    }

    # output directory for category files
    elsif (/^-d$/) {
        shift(@ARGV);
        if (defined $ARGV[0]) {
            $DIR = $ARGV[0];
        }
        else {
            print "-d requires directory name\n";
            usage();
        }
        unless (-d "$DIR") {
            print "Directory $DIR does not exist\n";
            usage();
        }
    }

    # Extension mismatch only
    elsif (/^-e$/) {
        $DO_INDEX = 0;
    }

    # Category types only
    elsif (/^-E$/) {
        $DO_EXT = 0;
    }

    # file system type
    elsif (/^-f$/) {
        shift(@ARGV);
        if (defined $ARGV[0]) {
            $FSTYPE = "-f " . $ARGV[0];
        }
        else {
            print "-f requires file system type\n";
            usage();
        }
    }

    # HTML
    elsif (/^-h$/) {
        $HTML = 1;
        $NL   = "<BR>\n";
        $TAB  = "&nbsp;&nbsp;";
        $EXT  = ".html";
        $BUL  = "  <LI>";
    }

    # Image type
    elsif (/^-i$/) {
        shift(@ARGV);
        if (defined $ARGV[0]) {
            $IMGTYPE = "-i " . $ARGV[0];
        }
        else {
            print "-i requires file system type\n";
            usage();
        }
    }

    # List the data instead of saving to files
    elsif (/^-l$/) {
        $LIST = 1;
    }
    elsif (/^-m$/) {
        shift(@ARGV);
        if (defined $ARGV[0]) {
            $MNT = $ARGV[0];
        }
        else {
            print "-m requires a mounting point\n";
            usage();
        }
        $MNT .= "/" unless ($MNT =~ /\/$/);
    }

    # MD5 hashes
    elsif (/^-md5$/) {
        $DO_MD5 = 1;
    }

    # NIST NSRL hash database for excluding files
    elsif (/^-n$/) {
        shift(@ARGV);
        if (defined $ARGV[0]) {
            $NSRL = $ARGV[0];
        }
        else {
            print "-n requires file name\n";
            usage();
        }
        unless (-e "$NSRL") {
            print "NSRL Database file missing ($NSRL)\n";
            usage();
        }
        $DO_MD5 = 1;
    }

    elsif (/^-o$/) {
        shift(@ARGV);
        if (defined $ARGV[0]) {
            $IMGOFF = $ARGV[0];
            unless ($IMGOFF =~ /^\d+$/) {
                print "Invalid sector offset\n";
                usage();
            }
        }
        else {
            print "-o requires offset value\n";
            usage();
        }
    }

    # Do SHA
    elsif (/^-sha1$/) {
        $DO_SHA1 = 1;
    }

    # Save the files in category directories
    elsif (/^-s$/) {
        $SAVE = 1;
    }
    elsif (/^-U$/) {
        $DO_UNKNOWN = 0;
    }

    # Version
    elsif (/^-V$/) {
        version();
        exit(0);
    }

    # Verbose
    elsif (/^-v$/) {
        $VERBOSE = 1;
    }

    # Exclude hash database
    elsif (/^-x$/) {
        shift(@ARGV);
        if (defined $ARGV[0]) {
            $EXCLUDE_DB = $ARGV[0];
        }
        else {
            print "-x requires hash database argument\n";
            usage();
        }
        unless (-e "$EXCLUDE_DB") {
            print "Exclude hash database $EXCLUDE_DB does not exist\n";
            usage();
        }
        $DO_MD5 = 1;
    }
    else {
        print "Unknown option: $_\n";
        usage();
    }
    shift(@ARGV);
}

if (scalar @ARGV == 0) {
    print "Missing image argument\n";
    usage();
}

# Find local copies of std execs
find_file();
if ($DO_MD5 == 1) {
    find_md5();
}
if ($DO_SHA1 == 1) {
    find_sha1();
}

# Verify that the TSK binaries are there
check_execs();

# Process the rest of the arguments - image and optional meta addr
my $IMG       = "";    # global for image path
my $first_img = "";
my $META      = "";    # global for root directory to start with

# Cycle through the rest of the args
while (my $tmpimg = shift @ARGV) {

    # If it isn't a file, then it is probably the last meta addr
    unless ((-e "$tmpimg") || (-l "$tmpimg")) {
        if ($tmpimg =~ /^\d+$/) {
            if (scalar @ARGV != 0) {
                print "Invalid image file (additional args after meta addr)\n";
                usage();
            }

            $META = $tmpimg;
            print "Using Directory $META\n" if ($VERBOSE);

            last;
        }
        else {
            print "Image file not found: $tmpimg\n";
            exit(1);
        }
    }

    # Append it to the list
    $IMG .= " \"$tmpimg\"";
    $first_img = $tmpimg
      if ($first_img eq "");

}

# Update the output message
$img_str .= "${BUL}$first_img${NL}";

# Determine the short name
$img_shrt = $first_img;
$img_shrt = substr($first_img, rindex($first_img, '/') + 1)
  if ($first_img =~ /\//);

# Figure out the temp file name
$TEMP_FILE = "${DIR}/.sorter-$img_shrt-$$-";

# verify that the correct arguments were given
check_args();

# Set the $PLATFORM variable based on $FSTYPE
set_platform();

# Read the config file
if ($ALL_CONFIGS == 1) {
    read_config("${SHARE_DIR}default.sort")
      if (-e "$SHARE_DIR/default.sort");

    read_config("${SHARE_DIR}${PLATFORM}.sort")
      if (($PLATFORM ne "") && (-e "${SHARE_DIR}${PLATFORM}.sort"));

    read_config("${SHARE_DIR}${PLATFORM}.lcl.sort")
      if (($PLATFORM ne "") && (-e "${SHARE_DIR}${PLATFORM}.lcl.sort"));
}

read_config($CONFIG) if ($CONFIG ne "");

# any config data?
if ((scalar(keys %file_to_cat) == 0) && ($DO_INDEX == 1) && ($DO_EXT == 0)) {
    print "Error: Empty config files\n";
    exit(1);
}

if ((scalar(keys %file_to_ext) == 0) && ($DO_EXT == 1) && ($DO_INDEX == 0)) {
    print "Error: No defined extensions\n";
    exit(1);
}

# Open the file handles
open_files() if ($LIST == 0);

analyze_img();

if ($LIST == 0) {
    close_files();
    print "\nAll files have been saved to: ${DIR}\n";
}

# close off the thumbnails if we used them
print_thumb_footer() if ($img_cnt != 0);

print_summary();

exit(0);

#########################################################################
#
# subroutines
#
#################################################################3

#################################################################3
# analyze_img
#
# Analyze one image.  This function calls 'fls', parses the
# output, and then calls analyze_file for each file
#
# Argument is the meta address of directory (null to use root)
#
sub analyze_img {

    #################################################################3
    # Process the allocated files in the image
    my $pr_str = "";

    $pr_str = "of Directory $META"
      unless ($META eq "");

    print "\nAnalyzing $IMG\n" . "  Loading Allocated File Listing $pr_str\n"
      if ($LIST == 0);

    my @out     = `\"$SK_FLS\" $IMGTYPE -o $IMGOFF $FSTYPE -rpl $IMG $META`;
    my $tmp_cnt = scalar @out;
    $alloc_cnt += $tmp_cnt;
    print "  Processing $tmp_cnt Allocated Files and Directories\n  "
      if ($LIST == 0);

    my $prev = 0;
    my $cnt  = 0;
    foreach (@out) {
        my $del;
        my $inode;
        my $path;
        my $size;

        # Print the status
        if ((++$cnt % 1000) == 0) {
            my $cur = int(100 * ($cnt / $tmp_cnt));
            if ($cur > $prev + 1) {
                print "$cur%," if ($LIST == 0);
                $prev = $cur;
            }
        }

        # Extract the file name and inode, skip if it is a directory
        # TYPE/TYPE * INUM (realloc): NAME
        if (
/^([\w\-])\/[\w\-]\s+(\*?)\s*([\d\-]+)([\(\)\w]*):\s+(.*)\s+$REG_DATE\s+$REG_DATE\s+$REG_DATE\s+$REG_DATE\s+(\d+)\s+\d+\s+\d+\s*$/
          )
        {
            if (($1 ne "r") && ($1 ne "-")) {
                $dirskip_cnt++;
                next;
            }
            # skip the realloc entries because we'll process the
            # allocated name that points to the content.
            if ($4 eq "(realloc)") {
                $realloc_cnt++;
                next;
            }

            $inode = $3;
            $path  = $5;
            $size  = $6;
            $del   = ($2 eq '*') ? $DEL_DEL : $DEL_ALLOC;
        }
        else {
            print "Error Parsing Output: $_";
            next;
        }

        # skip if file is too small
        if (($MIN_SIZE > 0) && ($size < $MIN_SIZE)) {
            $dirskip_cnt++;
            next;
        }

        # NTFS can have an inode of 0, but the others cannot
        my $inode_int = $inode;
        $inode_int = $1 if ($inode_int =~ /^(\d+)-[\d\-]+$/);
        if (($inode_int == 0) && ($FSTYPE ne "-f ntfs")) {
            $dirskip_cnt++;
            next;
        }

        analyze_file($path, $inode, $del);
    }
    print "100%\n" if ($LIST == 0);
}

#################################################################3
# analyze_file
#
# Process one file
#
# Arguments are the name of the file, the inode number of the file,
# and the deletion status ($DEL_*)
sub analyze_file {
    if (scalar(@_) != 3) {
        print "Incorrect Number of Arguments for analyze_file\n";
        return;
    }

    my $path  = shift;
    my $inode = shift;
    my $del   = shift;

    my $sha1 = "";
    my $md5  = "";
    my $file;

    my $recflag = "";
    $recflag = " -R " if ($del != $DEL_ALLOC);

    ###############################################################
    # Setup & Data Collection

    # The FAT full path has the short name in parenths, so
    # take them off first
    if (($path =~ /\)$/) && ($FSTYPE =~ /fat/)) {
        $path = substr($path, 0, rindex($path, '(') - 1);
    }

    # This was mainly because of the ils output which is <sdas-dead-X>
    my $path_encode = $path;
    if ($HTML == 1) {
        $path_encode =~ s/</&lt;/gs;
        $path_encode =~ s/>/&gt;/gs;
    }

    # Get the hash values and file type

    # Are we listing (i.e. can't write files) or we aren't going to save
    # the file and do not need the MD5?
    if (($LIST) || (($SAVE == 0) && ($DO_MD5 == 0) && ($DO_SHA1 == 0))) {
        $file =
`\"$SK_ICAT\" $IMGTYPE -o $IMGOFF $FSTYPE $recflag $IMG \"$inode\" | \"$SK_FILE\" -b -z -`;
        chomp $file;
        if ($DO_SHA1 == 1) {
            $sha1 =
`\"$SK_ICAT\" $IMGTYPE -o $IMGOFF $FSTYPE $recflag $IMG \"$inode\" | \"$SK_SHA1\"`;
            chomp $sha1;
            $sha1 = $1 if ($sha1 =~ /^([A-Fa-f0-9]+)\s+.*$/);
        }
        if ($DO_MD5 == 1) {
            $md5 =
`\"$SK_ICAT\" $IMGTYPE -o $IMGOFF $FSTYPE $recflag $IMG \"$inode\" | \"$SK_MD5\"`;
            chomp $md5;
            $md5 = $1 if ($md5 =~ /^([A-Fa-f0-9]+)\s+.*$/);
        }
    }

    # Save to temp file
    else {
`\"$SK_ICAT\" $IMGTYPE -o $IMGOFF $FSTYPE $recflag $IMG \"$inode\" > \"${TEMP_FILE}$inode\"`;
        $file = `\"$SK_FILE\" -b -z \"${TEMP_FILE}$inode\"`;
        chomp $file;
        if ($DO_SHA1 == 1) {
            $sha1 = `\"$SK_SHA1\" \"${TEMP_FILE}$inode\"`;
            if ($sha1 =~ /^([A-Fa-f0-9]+)\s+.*$/) {
                $sha1 = $1;
            }
            elsif ($sha1 =~ /=\s+([A-Fa-f0-9]+)$/) {
                $sha1 = $1;
            }
        }
        if ($DO_MD5 == 1) {
            $md5 = `\"$SK_MD5\" \"${TEMP_FILE}$inode\"`;
            if ($md5 =~ /^([A-Fa-f0-9]+)\s+.*$/) {
                $md5 = $1;
            }
            elsif ($md5 =~ /=\s+([A-Fa-f0-9]+)$/) {
                $md5 = $1;
            }
        }

        unlink("${TEMP_FILE}$inode") if ($SAVE == 0);
    }

    # Remove non-printable values from the 'file' output
    $file =~ s/[\x00-\x19\x7F-\xFF]//g;

    # "empty" is a null size file
    if ($file eq 'empty') {
        unlink("${TEMP_FILE}$inode") if ($SAVE == 1);
        $dirskip_cnt++;
        return;
    }

    ###############################################################
    # Lookup in hash databases

    #
    # We will first examine any hashes of known files to alert on.
    # Next, we wil look if this is a file that is known and that we can
    # ignore (NSRL and the -x flag).  If one of these files is found, we do
    # no immediately exit the function.  We also check the extension and
    # make sure that it is appropriate.

    my $exclude = "";
    my $alert   = 0;

    # First the alert data base
    if ("$ALERT_DB" ne "") {
        print "Looking up in Alert Hash Database\n" if ($VERBOSE);
        my $out = `\"$SK_HFIND\" -q \"$ALERT_DB\" \"$md5\"`;
        if ($out =~ /^1\s+$/) {
            $alert = 1;
        }
        elsif ($out !~ /^0\s+$/) {
            print "Error running 'hfind': $out\n";
            exit(1);
        }
    }

    # Ones we can ignore
    if (($alert == 0) && ("$EXCLUDE_DB" ne "")) {
        print "Looking up in Exclude Hash Database\n" if ($VERBOSE);

        my $out = `\"$SK_HFIND\" -q \"$EXCLUDE_DB\" \"$md5\"`;
        if ($out =~ /^1\s+$/) {

            # Print to the appropriate files
            if ($LIST == 0) {
                print EXCLUDE "${MNT}$path_encode${NL}";
                print EXCLUDE "${TAB}Image: $first_img  Inode: $inode${NL}";
                print EXCLUDE "${TAB}$file${NL}";
                print EXCLUDE "${TAB}MD5: $md5${NL}";
                print EXCLUDE "${TAB}Exclude Database${NL}${NL}";

            }
            $exclude = "Exclude Hash Database";
            $excl_cnt++;
        }
        elsif ($out !~ /^0\s+$/) {
            print "Error running 'hfind': $out\n";
            exit(1);
        }
    }

    # NSRL
    if (($alert == 0) && ("$NSRL" ne "") && ($exclude eq "")) {
        print "Looking up in NSRL Hash Database\n" if ($VERBOSE);

        my $out = `\"$SK_HFIND\" -q \"$NSRL\" \"$md5\"`;
        if ($out =~ /^1\s+$/) {

            # Print to the appropriate files
            if ($LIST == 0) {
                print EXCLUDE "${MNT}$path_encode${NL}";
                print EXCLUDE "${TAB}Image: $first_img  Inode: $inode${NL}";
                print EXCLUDE "${TAB}$file${NL}";
                print EXCLUDE "${TAB}MD5: $md5${NL}";
                print EXCLUDE "${TAB}NSRL Database${NL}${NL}";
            }
            $exclude = "NSRL";
            $excl_cnt++;
        }
        elsif ($out !~ /^0\s+$/) {
            print "Error running 'hfind': $out\n";
            exit(1);
        }
    }

    ###############################################################
    #
    # Extension versus File Type
    #
    ###############################################################

    my $mismatch = 0;
    my $ext      = "";

    # Is there an extension on this file?
    my $ext_off = rindex($path, ".");

    # Some sanity checks to verify that the '.' is after the '/' and
    # add one so that we don't process /.asd as an extension
    if (($ext_off != -1) && ($ext_off > (rindex($path, "/") + 1))) {
        $ext = substr($path, $ext_off + 1);
        $ext =~ tr/[A-Z]/[a-z]/;
    }

    $path .= " (deleted)" if ($del == $DEL_DEL);

    if ($VERBOSE) {
        print "File ${MNT}$path (ext: $ext)\n";
        print "File Output: $file\n";
    }

    # Check the extension if it exists
    # Ignore data as it is unknown stuff
    if (($DO_EXT == 1) && ($ext ne "") && ($file ne 'data')) {

        my $found = 0;

        # cycle through the known file keywords that have a known ext
        for (my $ext_i = $#ext_order; $ext_i >= 0; $ext_i--) {
            my $ext_kw = $ext_order[$ext_i];

            print "Trying Extension Keyword: $ext_kw\n" if ($VERBOSE);

            # is this the 'file' category?
            if ($file =~ /$ext_kw/i) {

                print "Found Extension Keyword\n" if ($VERBOSE);

                # we found at least one set of extensions that matches
                # this file type, so set the mismatch to 1 and if we
                # find this extension we will set it to 0, otherwise
                # it will be considered a mismatch
                $mismatch = 1;

                $ext =~ tr/[A-Z]/[a-z]/;

                # cycle through each possible extension for this type
                foreach my $cat_ext (@{$file_to_ext{$ext_kw}}) {
                    print "Comparing ext with $cat_ext\n" if ($VERBOSE);
                    if ($cat_ext eq $ext) {
                        print "Found ext\n" if ($VERBOSE);
                        $mismatch = 0;
                        $found    = 1;
                        last;
                    }
                }
            }

            # If we have found the extension, then get out of the loop
            last if ($found == 1);
        }

    }

    # The special mismatch file for those that we should be ignoring
    # but they may be worthwhile looking at now
    if (($mismatch == 1) && ($exclude ne "")) {

        $exclmis_cnt++;

        if ($LIST == 0) {
            print EXCLUDEMIS "${MNT}$path_encode${NL}";
            print EXCLUDEMIS "${TAB}$file$  (Ext: $ext)${NL}";
            print EXCLUDEMIS "${TAB}Image: $first_img  Inode: $inode${NL}";
            print EXCLUDEMIS "${TAB}SHA-1: $sha1${NL}" if ($DO_SHA1 == 1);
            print EXCLUDEMIS "${TAB}MD5: $md5${NL}"    if ($DO_MD5 == 1);
            print EXCLUDEMIS "${TAB}$exclude${NL}${NL}";
        }
    }

    # Now we will return if we are supposed to ignore this file
    return if ($exclude ne "");

    ###############################################################
    # File Type Category

    my $save_name = "";

    my $cat = "";
    if ($DO_INDEX) {

        # is this a category we want to save data about?
        for (my $cat_i = $#cat_order; $cat_i >= 0; $cat_i--) {
            my $cat_kw = $cat_order[$cat_i];

            if ($file =~ /$cat_kw/i) {
                $cat = $file_to_cat{$cat_kw};

                last if ($cat eq $IGNORE_NAME);

                $output_used{$cat}++;

                # Are we going to save this to a directory?
                if ($SAVE == 1) {
                    my $save_dir = "${DIR}/${cat}";
                    mkdir($save_dir, 0775) unless (-d $save_dir);

                    if ($ext eq "") {
                        $save_name = "${img_shrt}-${inode}";
                    }
                    else {
                        $save_name = "${img_shrt}-${inode}.${ext}";
                    }
                    rename("${TEMP_FILE}$inode", "${save_dir}/${save_name}");

                    # Add to the thumbnail file
                    if (($cat eq "images") && ($HTML == 1)) {
                        print_thumb($save_name, $path_encode);
                    }
                }

                last;
            }
        }
    }

    # make sure it is gone if we did not move it to a category
    unlink("${TEMP_FILE}$inode")
      if (($SAVE == 1) && (-e "${TEMP_FILE}$inode"));

    if ($cat eq $IGNORE_NAME) {
        $ignore_cnt++;
        goto PRINT_ALERT;
    }

    # Print the category results

    # If we are listing, then print anything to STDOUT
    if ($LIST == 1) {
        if ($cat eq "") {
            print "Category: Unknown\n";
            $output_used{'unknown'}++;
        }
        else {
            print "Category: $cat\n";
        }
        print "${MNT}$path_encode\n" . "$file\n";
        print "--- Found in Alert Hash Database ---\n"
          if ($alert == 1);
        print "--- Extension Mismatch! ---\n" if ($mismatch == 1);

        print "Image: $first_img  Inode: $inode\n";
        print "SHA-1: $sha1\n" if ($DO_SHA1 == 1);
        print "MD5: $md5\n"    if ($DO_MD5 == 1);

        print "\n";
    }

    # print to a specific category file
    elsif ($DO_INDEX == 1) {
        if ($cat ne "") {
            my $tmphandle = $cat_handle{$cat};

            print $tmphandle "<A NAME=\"${save_name}\">\n"
              if ($HTML == 1);

            print $tmphandle "${MNT}$path_encode${NL}";
            print $tmphandle "${TAB}$file${NL}";
            print $tmphandle "${TAB}--- Found in Alert Database ---${NL}"
              if ($alert == 1);
            print $tmphandle "${TAB}--- Extension Mismatch! ---${NL}"
              if ($mismatch == 1);

            print $tmphandle "${TAB}Image: $first_img  Inode: $inode${NL}";
            print $tmphandle "${TAB}SHA-1: $sha1${NL}" if ($DO_SHA1 == 1);
            print $tmphandle "${TAB}MD5: $md5${NL}"    if ($DO_MD5 == 1);
            if ($SAVE == 1) {
                if ($HTML == 0) {
                    print $tmphandle "${TAB}Saved to: ${cat}/${save_name}${NL}";
                }
                else {
                    print $tmphandle
                      "${TAB}Saved to: <A HREF=\"./${cat}/${save_name}\">"
                      . "${cat}/${save_name}</A>${NL}";
                }
            }

            print $tmphandle "${NL}";
        }

        # the $cat is "" and we are making index files and it has some
        # uniqe file output, so save it to the unknown file
        #
        # Ignore the 'data' type and the 'empty' type has already been removed
        # data should be saved by the default config file and if not then the
        # user obviously does not want it
        elsif ($file ne 'data') {
            if ($DO_UNKNOWN == 1) {
                print UNKNOWN "${MNT}$path_encode${NL}";
                print UNKNOWN "${TAB}--- Found in Alert Database ---${NL}"
                  if ($alert == 1);
                print UNKNOWN "${TAB}$file${NL}";
                print UNKNOWN
                  "${TAB}Image: $first_img  Inode: $inode${NL}${NL}";
            }

            $output_used{'unknown'}++;
        }
    }

    # Print the mismatch info
    if (($DO_EXT == 1) && ($mismatch == 1)) {

        $mis_cnt++;

        if ($LIST == 0) {
            print MISMATCH "${MNT}$path_encode${NL}";
            print MISMATCH "${TAB}$file  (Ext: $ext)${NL}";
            print MISMATCH "${TAB}Image: $first_img  Inode: $inode${NL}";
            print MISMATCH "${TAB}SHA-1: $sha1${NL}" if ($DO_SHA1 == 1);
            print MISMATCH "${TAB}MD5: $md5${NL}"    if ($DO_MD5 == 1);
            if ($SAVE == 1) {
                if ($HTML == 0) {
                    print MISMATCH "${TAB}Saved to: ${cat}/${save_name}${NL}";
                }
                else {
                    print MISMATCH
                      "${TAB}Saved to: <A HREF=\"./${cat}/${save_name}\">"
                      . "${cat}/${save_name}</A>${NL}";
                }
            }
            print MISMATCH "${NL}";
        }

    }

  PRINT_ALERT:

    # If we are alerting because of a hash value, do it now.  It is all
    # the way down here so that we know the path that it was saved to
    if ($alert == 1) {

        $alert_cnt++;

        if ($LIST == 0) {
            print ALERT "${MNT}$path_encode${NL}";
            print ALERT "${TAB}Image: $first_img  Inode: $inode${NL}";
            print ALERT "${TAB}SHA-1: $sha1${NL}" if ($DO_SHA1 == 1);
            print ALERT "${TAB}MD5: $md5${NL}"    if ($DO_MD5 == 1);
            if ($SAVE == 1) {
                if ($HTML == 0) {
                    print ALERT "${TAB}Saved to: ${cat}/${save_name}${NL}";
                }
                else {
                    print ALERT
                      "${TAB}Saved to: <A HREF=\"./${cat}/${save_name}\">"
                      . "${cat}/${save_name}</A>${NL}";
                }
            }
            print ALERT "${NL}";
        }
    }

    return;
}

# Read the config files
sub read_config {
    my $config = shift;

    open(CONFIG, "$config") or die "Can't open $config";

    print "Reading $config\n" if ($VERBOSE);

    while (<CONFIG>) {
        next if ((/^\#/) || (/^\s+$/));

        # category definition
        # category name key_words
        if (/^\s*category\s+([\w\d]+)\s+(.*?)\s*$/) {
            my $kw  = $2;
            my $cat = $1;

            # Make lowercase
            $cat =~ tr/[A-Z]/[a-z]/;

            # we have some reservered categories already
            if (   ($cat eq $MIS_NAME)
                || ($cat eq $UNK_NAME)
                || ($cat eq $ALERT_NAME)
                || ($cat eq $EXCLUDE_NAME)
                || ($cat eq $EXCLUDEMIS_NAME))
            {
                print "Invalid Category Name: $cat (Reserved)\n";
                exit(1);
            }

            # do a sanity check to see if we are overriding a
            # category that already existed for this file type
            if (   (exists $file_to_cat{$kw})
                && ($file_to_cat{$kw} ne $cat))
            {
                print
"Warning: overriding category $file_to_cat{$kw} with $cat for key words: $kw\n";
            }
            else {
                push @cat_order, $kw;
            }

            $file_to_cat{$kw} = $cat;
            print "Adding Category: $cat   File Keywords: $kw\n" if ($VERBOSE);
        }

        # extension defn
        # ext ext1,ext2, key_words
        elsif (/^\s*ext\s+([\w\d\,]+)\s+(.*?)\s*$/) {
            my $ext = $1;
            my $kw  = $2;

            # Make lowercase
            $ext =~ tr/[A-Z]/[a-z]/;

            # If there are already some extensions, then we will just
            # extend them
            if (exists $file_to_ext{$kw}) {

                # We could just do a push, but then we risk having
                # duplicate entries, which will waste time later
                foreach my $e1 (split(/,/, $ext)) {
                    my $exists = 0;
                    foreach my $e2 (@{$file_to_ext{$kw}}) {
                        if ($e1 eq $e2) {
                            $exists = 1;
                            last;
                        }
                    }
                    push @{$file_to_ext{$kw}}, $e1 if ($exists == 0);
                }
                print "Adding Extensions: $ext   File Keywords: $kw\n"
                  if ($VERBOSE);

            }
            else {
                $file_to_ext{$kw} = [split(/,/, $ext)];
                push @ext_order, $kw;
                print "New Extensions: $ext   File Keywords: $kw\n"
                  if ($VERBOSE);
            }
        }
        else {
            print "Invalid line in $config:$.\n";
            exit(1);
        }
    }

    close(CONFIG);
}

# This is needed to assign the handle to a local variable
sub myopen {
    my $path = shift;
    local *FH;
    open(FH, $path) or die("Can not open $path");
    return *FH;
}

# Open the summary files into an array of handles
sub open_files {
    return if ($LIST == 1);

    if ($DO_EXT == 1) {
        open(MISMATCH, ">${DIR}/${MIS_NAME}${EXT}")
          or die "Can't open ${DIR}/${MIS_NAME}${EXT}";
        $mis_cnt = 0;

        print MISMATCH "<HTML><HEAD>\n"
          . "<TITLE>Extension Mismatches</TITLE>"
          . "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></HEAD>\n"
          . "<BODY>\n"
          . "<CENTER><H2>Extension Mismatch</H2></CENTER>\n"
          if ($HTML == 1);
    }

    if ("$ALERT_DB" ne "") {
        open(ALERT, ">${DIR}/${ALERT_NAME}${EXT}")
          or die "Can't open ${DIR}/${ALERT_NAME}${EXT}";

        $alert_cnt = 0;

        print ALERT "<HTML><HEAD>\n"
          . "<TITLE>Hash Database Alerts</TITLE>"
          . "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></HEAD>\n"
          . "<BODY>\n"
          . "<CENTER><H2>Hash Database Alerts</H2></CENTER>\n"
          if ($HTML == 1);
    }

    if (("$EXCLUDE_DB" ne "") || ("$NSRL" ne "")) {
        open(EXCLUDE, ">${DIR}/${EXCLUDE_NAME}${EXT}")
          or die "Can't open ${DIR}/${EXCLUDE_NAME}${EXT}";

        $excl_cnt = 0;

        print EXCLUDE "<HTML><HEAD>\n"
          . "<TITLE>Hash Database Excludes</TITLE>"
          . "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></HEAD>\n"
          . "<BODY>\n"
          . "<CENTER><H2>Hash Database Excludes</H2></CENTER>\n"
          if ($HTML == 1);

        if ($DO_EXT == 1) {
            open(EXCLUDEMIS, ">${DIR}/${EXCLUDEMIS_NAME}${EXT}")
              or die "Can't open ${DIR}/${EXCLUDEMIS_NAME}${EXT}";
            $exclmis_cnt = 0;

            print EXCLUDEMIS "<HTML><HEAD>\n"
              . "<TITLE>Hash Database Excludes with Mismatches</TITLE>"
              . "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></HEAD>\n"
              . "<BODY>\n"
              . "<CENTER><H2>Hash Database Excludes with Mismatches</H2></CENTER>\n"
              if ($HTML == 1);
        }
    }

    if ($DO_INDEX == 1) {

        $output_used{'unknown'} = 0;

        if ($DO_UNKNOWN == 1) {
            open(UNKNOWN, ">${DIR}/${UNK_NAME}${EXT}")
              or die "Can't open ${DIR}/${UNK_NAME}${EXT}";

            print UNKNOWN "<HTML><HEAD>\n"
              . "<TITLE>Unknown Category</TITLE>"
              . "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></HEAD>\n"
              . "<BODY>\n"
              . "<CENTER><H2>Unknown Category</H2></CENTER>\n"
              if ($HTML == 1);

        }

        foreach my $cat (values %file_to_cat) {
            next if (exists $cat_handle{$cat});
            next if ($cat eq $IGNORE_NAME);

            $cat_handle{$cat} = myopen(">${DIR}/${cat}${EXT}");
            my $tmphandle = $cat_handle{$cat};

            $output_used{$cat} = 0;

            print $tmphandle "<HTML><HEAD>\n"
              . "<TITLE>$cat Category</TITLE>"
              . "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></HEAD>\n"
              . "<BODY>\n"
              . "<CENTER><H2>$cat Category</H2></CENTER>\n"
              if ($HTML == 1);

            # make a directory for the thumbnail images
            if (($cat eq "images") && ($SAVE == 1) && ($HTML == 1)) {
                mkdir("${DIR}/images", 0775)
                  unless (-d "${DIR}/images");

                open(IMG_INDEX, ">${DIR}/images/index.html")
                  or die "Can't open ${DIR}/images/index.html";

                print IMG_INDEX "<HTML><HEAD>\n"
                  . "<TITLE>Image Thumbnails Index</TITLE>"
                  . "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></HEAD>\n"
                  . "<BODY>\n"
                  . "<CENTER><H2>Image Thumbnails Index</H2></CENTER>\n<UL>\n";
            }
        }
    }

    return;
}

# Close the output summary files and remove them if they have
# a size of 0
#
sub close_files {
    return if ($LIST == 1);

    # Extension Mismatch
    if ($DO_EXT == 1) {
        close(MISMATCH);
        unlink "${DIR}/${MIS_NAME}${EXT}" if ($mis_cnt == 0);
    }

    # Alert Hash database
    if ("$ALERT_DB" ne "") {
        close(ALERT);
        unlink "${DIR}/${ALERT_NAME}${EXT}"
          if ($alert_cnt == 0);
    }

    # Exclude hash databases (-x and NSRL)
    if (("$EXCLUDE_DB" ne "") || ("$NSRL" ne "")) {
        close(EXCLUDE);
        unlink "${DIR}/${EXCLUDE_NAME}${EXT}"
          if ($excl_cnt == 0);

        if ($DO_EXT == 1) {
            close(EXCLUDEMIS);
            unlink "${DIR}/${EXCLUDEMIS_NAME}${EXT}"
              if ($exclmis_cnt == 0);
        }
    }

    # Categories
    if ($DO_INDEX == 1) {
        if ($DO_UNKNOWN == 1) {
            close(UNKNOWN);
            unlink "${DIR}/${UNK_NAME}${EXT}"
              if ($output_used{'unknown'} == 0);
        }

        foreach my $cat (keys %cat_handle) {
            if ($HTML == 1) {
                my $tmphandle = $cat_handle{$cat};
                print $tmphandle "</BODY></HTML>\n";
            }

            close($cat_handle{$cat});
            unlink "${DIR}/${cat}${EXT}" if ($output_used{$cat} == 0);

            if (($cat eq "images") && ($SAVE == 1) && ($HTML == 1)) {
                print IMG_INDEX "</UL>\n</HTML>\n";
                close(IMG_INDEX);
            }
        }
    }
}

sub check_execs {
    unless (-e "$SK_FLS") {
        print "Missing Sleuth Kit fls executable: $SK_FLS\n";
        exit(1);
    }

    unless (-e "$SK_FILE") {
        print "Missing file executable: $SK_FILE\n";
        exit(1);
    }

    unless (-e "$SK_ICAT") {
        print "Missing Sleuth Kit icat executable: $SK_ICAT\n";
        exit(1);
    }

    unless (-e "$SK_HFIND") {
        print "Missing Sleuth Kit hfind executable: $SK_HFIND\n";
        exit(1);
    }

    unless (-e "$SK_IMGSTAT") {
        print "Missing Sleuth Kit img_stat executable: $SK_IMGSTAT\n";
        exit(1);
    }

    if ($DO_SHA1 == 1) {
        unless (-e "$SK_SHA1") {
            print "Missing sha1 executable: $SK_SHA1\n";
            exit(1);
        }
    }

    if ($DO_MD5 == 1) {
        unless (-e "$SK_MD5") {
            print "Missing md5 executable: $SK_MD5\n";
            exit(1);
        }
    }
}

# Set the $PLATFORM value from $FSTYPE
sub set_platform {

    if (   ($FSTYPE eq "-f ntfs")
        || ($FSTYPE eq "-f fat")
        || ($FSTYPE eq "-f fat32")
        || ($FSTYPE eq "-f fat16")
        || ($FSTYPE eq "-f fat12"))
    {
        $PLATFORM = "windows";
    }
    elsif ($FSTYPE eq "-f solaris") {
        $PLATFORM = "solaris";
    }
    elsif ($FSTYPE eq "-f openbsd") {
        $PLATFORM = "openbsd";
    }
    elsif ($FSTYPE eq "-f freebsd") {
        $PLATFORM = "freebsd";
    }

    # Use freebsd as a default for UFS
    elsif (($FSTYPE eq "-f ufs")
        || ($FSTYPE eq "-f ufs1")
        || ($FSTYPE eq "-f ufs2"))
    {
        $PLATFORM = "freebsd";
    }
    elsif (($FSTYPE eq "-f linux-ext2")
        || ($FSTYPE eq "-f linux-ext3")
        || ($FSTYPE eq "-f linux-ext4")
        || ($FSTYPE eq "-f ext")
        || ($FSTYPE eq "-f ext2")
        || ($FSTYPE eq "-f ext3")
        || ($FSTYPE eq "-f ext4"))
    {
        $PLATFORM = "linux";
    }
    elsif ($FSTYPE eq "-f iso9660") {
        $PLATFORM = "";
    }
    elsif ($FSTYPE eq "-f hfs") {
        $PLATFORM = "mac";
    }
    else {
        print "Unknown file system type: $FSTYPE\n";
        exit(1);
    }

    print "Platform set to: $PLATFORM\n" if ($VERBOSE);
}

sub check_args {

    # Sanity check the arguments
    if ("$IMGTYPE" eq "") {

        # Test that autodetect works
        my $out = `\"$SK_IMGSTAT\" -t $IMG`;
        if ($out =~ /^(\w+)$/) {
            $IMGTYPE = "-i $1";
        }
        else {
            print "Missing image file type (and autodetect is not working)\n";
            usage();
        }
    }

    if ("$FSTYPE" eq "") {

        # Test that autodetect works
        my $out = `\"$SK_FSSTAT\" $IMGTYPE -o $IMGOFF -t $IMG`;
        if ($out =~ /^([\w\-]+)$/) {
            $FSTYPE = "-f $1";
        }
        else {
            print "Missing file system type (and autodetect is not working)\n";
            usage();
        }
    }
    else {
        my $out = `\"$SK_FSSTAT\" $IMGTYPE -o $IMGOFF $FSTYPE -t $IMG`;
        unless ($out =~ /^([\w\d\-]+)$/) {
            print "Incorrect file system type ($FSTYPE)\n";
            exit(1);
        }
    }

    if (("$DIR" eq "") && ($LIST == 0)) {
        print "Missing directory location\n";
        usage();
    }

    elsif (("$DIR" ne "") && ($LIST == 1)) {
        print "Directory (-d) and List (-l) flags cannot be used together\n";
        usage();
    }

    elsif (($SAVE == 1) && ($LIST == 1)) {
        print "Save Files (-s) and List (-l) flags cannot be used together\n";
        usage();
    }
}

# Print a summary of results to the screen
sub print_summary {

    if ($HTML == 1) {
        print_index();
        return;
    }

    my $str = "";

    $str .= "Images\n" . $img_str . ${NL};

    $str .= "Files (" . ($alloc_cnt) . ")\n\n";

    $str .=
        "Files Skipped ("
      . ($dirskip_cnt + $ignore_cnt + $realloc_cnt) . ")\n"
      . "- Non-Files ($dirskip_cnt)\n"
      . "- Reallocated Name Files ($realloc_cnt)\n"
      . "- 'ignore' category ($ignore_cnt)\n\n";

    if (("$EXCLUDE_DB" ne "") || ("$NSRL" ne "") || ("$ALERT_DB" ne "")) {
        $str .= "Hash Databases\n";

        if ("$ALERT_DB" ne "") {
            $str .= "- Hash Database Alerts" . " ($alert_cnt)\n";
        }

        if (("$EXCLUDE_DB" ne "") || ("$NSRL" ne "")) {
            $str .= "- Hash Database Exclusions ($excl_cnt)\n";
        }

        $str .= "\n";
    }

    if ($DO_EXT == 1) {
        $str .= "Extensions\n";

        $str .= "- Extension Mismatches" . " ($mis_cnt)\n";

        if (("$EXCLUDE_DB" ne "") || ("$NSRL" ne "")) {
            $str .=
"- Hash Database Exclusions with Extension Mismatch ($exclmis_cnt)\n";
        }
        $str .= "\n";
    }

    if ($DO_INDEX == 1) {
        my $tot  = 0;
        my $str2 = "";

        foreach my $cat (sort { lc($a) cmp lc($b) } keys %output_used) {
            $str2 .= "- $cat ($output_used{$cat})\n";
            $tot += $output_used{$cat};
        }

        $str .= "Categories ($tot)\n" . $str2 . "\n";
    }

    if ($LIST == 1) {
        print "\n--------------------------------------------------\n" . $str;
    }
    else {
        open(SUM, ">${DIR}/${SUMMARY_NAME}")
          or die "Can't open ${SUMMARY_NAME}";
        print SUM $str;
        close(SUM);
    }

    return;
}

# index.html file with links to specific sections
sub print_index {
    return if (($HTML == 0) || ($LIST == 1));

    open(INDEX, ">${DIR}/index.html")
      or die "Can't open index.html";

    print INDEX "<HTML><HEAD><TITLE>sorter output</TITLE>"
      . "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></HEAD>\n"
      . "<BODY>"
      . "<CENTER><H2>sorter output</H2></CENTER>\n"
      . "<P><B>Images</B><BR>"
      . "<UL>$img_str</UL>\n"
      . "<P><B>Files</B> ("
      . ($alloc_cnt) . ")\n"
      . "<P><B>Files Skipped</B> ("
      . ($dirskip_cnt + $ignore_cnt)
      . ")\n<UL>\n"
      . "  <LI>Non-Files ($dirskip_cnt)\n"
      . "  <LI>Reallocated Name Files ($realloc_cnt)\n"
      . "  <LI>'ignore' category ($ignore_cnt)\n"
      . "</UL>\n";

    if (("$EXCLUDE_DB" ne "") || ("$NSRL" ne "") || ("$ALERT_DB" ne "")) {
        print INDEX "<P><B>Hash Databases</B>\n<UL>\n";
    }

    if ("$ALERT_DB" ne "") {
        if ($alert_cnt > 0) {
            print INDEX "<LI><A HREF=\"./${ALERT_NAME}${EXT}\">"
              . "Hash Database Alerts</A> ($alert_cnt)\n";
        }
        else {
            print INDEX "<LI>Hash Database Alerts" . " ($alert_cnt)\n";
        }
    }

    if (("$EXCLUDE_DB" ne "") || ("$NSRL" ne "")) {
        if ($excl_cnt > 0) {
            print INDEX "<LI><A HREF=\"./${EXCLUDE_NAME}${EXT}\">"
              . "Hash Database Exclusions</A> ($excl_cnt)\n";
        }
        else {
            print INDEX "<LI>Hash Database Exclusions ($excl_cnt)\n";
        }
    }
    if (("$EXCLUDE_DB" ne "") || ("$NSRL" ne "") || ("$ALERT_DB" ne "")) {
        print INDEX "</UL>\n";
    }

    if ($DO_EXT == 1) {

        print INDEX "<P><B>Extensions</B>\n<UL>\n";
        if ($mis_cnt > 0) {
            print INDEX "<LI><A HREF=\"./${MIS_NAME}${EXT}\">"
              . "Extension Mismatches</A>"
              . " ($mis_cnt)\n";
        }
        else {
            print INDEX "<LI>Extension Mismatches" . " ($mis_cnt)\n";
        }

        if (("$EXCLUDE_DB" ne "") || ("$NSRL" ne "")) {
            if ($exclmis_cnt > 0) {
                print INDEX "<LI><A HREF=\"./${EXCLUDEMIS_NAME}${EXT}\">"
                  . "Hash Database Exclusions with Extension Mismatch</A> ($exclmis_cnt)\n";
            }
            else {
                print INDEX
"<LI>Hash Database Exclusions with Extension Mismatch ($exclmis_cnt)\n";
            }
        }
        print INDEX "</UL>\n";
    }

    if ($DO_INDEX == 1) {
        my $str = "<UL>\n";
        my $tot = 0;

        foreach my $cat (sort { lc($a) cmp lc($b) } keys %output_used) {

            # Print no link if there were no files or we are not saving
            # the unknown files
            if (   ($output_used{$cat} == 0)
                || (($cat eq $UNK_NAME) && ($DO_UNKNOWN == 0)))
            {
                $str .= "  <LI>$cat ($output_used{$cat})\n";
            }
            else {
                $str .=
                    "  <LI><A HREF=\"./${cat}${EXT}\">"
                  . "$cat</A> ($output_used{$cat})\n";
            }

            # Note that an Autopsy regexp that removes the link
            # may need to be changed if this line is changed
            $str .= " (<A HREF=\"./images/index.html\">thumbnails</A>)\n"
              if (($cat eq 'images') && ($img_cnt > 0));

            $tot += $output_used{$cat};
        }

        print INDEX "<P><B>Categories</B> ($tot)\n" . $str . "</UL>\n";
    }

    close(INDEX);

    return;
}

sub print_thumb_footer {
    return if (($HTML == 0) || ($LIST == 1));

    my $close_page;

    # Get the location of the page that we are closing
    if (($img_cnt % $IMG_PAGE) == 0) {

        # We are closing a page because we hit the limit
        $close_page = ($img_cnt - 1) / $IMG_PAGE + 1;
    }
    else {

        # we are closing the page because we are done
        $close_page = ($img_cnt) / $IMG_PAGE + 1;
    }

    # This could be called to close off the final file, so check if
    # we need to finish off the last row
    print IMG_THUMB "</TR>\n"
      unless (($img_cnt % 4) == 0);

    print IMG_THUMB "</TABLE>\n";

    # Print a previous unless we are closing page 1
    unless ($close_page == 1) {
        my $tmp = $close_page - 1;
        print IMG_THUMB
          "<A HREF=./thumbs-${tmp}.html>previous $IMG_PAGE</A>&nbsp;&nbsp;\n";
    }

    print IMG_THUMB "<A HREF=./index.html>Main Index</A>&nbsp;&nbsp;\n";

    # only do next if we are making a new page next
    if (($img_cnt % $IMG_PAGE) == 0) {
        my $tmp = $close_page + 1;
        print IMG_THUMB "<A HREF=./thumbs-${tmp}.html>next $IMG_PAGE</A>\n";
    }

    print IMG_THUMB "</BODY></HTML>";

    close IMG_THUMB;
}

# Arguments: Saved name and path

sub print_thumb {
    return if (($HTML == 0) || ($LIST == 1));

    my $save_name = shift;
    my $path      = shift;

    # A new page is required
    # $IMG_PAGE per page
    if (($img_cnt % $IMG_PAGE) == 0) {

        my $page = $img_cnt / $IMG_PAGE + 1;

        # Close off the current one - if there is one
        if ($img_cnt != 0) {
            print_thumb_footer();
        }

        open(IMG_THUMB, ">${DIR}/images/thumbs-" . $page . ".html")
          or die "Can't open ${DIR}/images/thumbs-" . $page . ".html";

        print IMG_THUMB "<HTML><HEAD>\n"
          . "<TITLE>Image Thumbnails - Page $page</TITLE>"
          . "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></HEAD>\n"
          . "<BODY>\n"
          . "<CENTER><H2>Image Thumbnails - Page $page</H2>\n<P>"
          . "<TABLE WIDTH=630 CELLSPACING=5 CELLPADDING=0 BORDER=0>\n"
          . "<TR><TD></TD><TD ALIGN=CENTER>A</TD><TD ALIGN=CENTER>B</TD>"
          . "<TD ALIGN=CENTER>C</TD><TD ALIGN=CENTER>D</TD></TR>\n";

        # Add to the main index
        print IMG_INDEX
          "<LI><A HREF=\"./thumbs-${page}.html\">Page $page</A></LI>\n";

    }

    # A new row
    if (($img_cnt % 4) == 0) {
        my $row = (($img_cnt % 100) / 4) + 1;
        print IMG_THUMB "<TR>\n  <TD>$row</TD>\n";
    }

    my $img_shrt = $path;
    $img_shrt = substr($path, rindex($path, '/') + 1)
      if ($path =~ /\//);

    print IMG_THUMB "  <TD WIDTH=150>"
      . "<A HREF=\"./$save_name\" TARGET=_blank>"
      . "<IMG SRC=\"./$save_name\" "
      . "WIDTH=150 HEIGHT=150 ALT=\"$img_shrt\"></A><BR>"
      . "$img_shrt<BR>"
      . "<A HREF=\"../images.html#${save_name}\" TARGET=\"_blank\">details</A>"
      . "</TD>\n";

    $img_cnt++;

    # Ending a row
    print IMG_THUMB "</TR>\n"
      if (($img_cnt % 4) == 0);

    return;
}