-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBdplObjects.py
5126 lines (3937 loc) · 266 KB
/
BdplObjects.py
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
#!/usr/bin/env python3
import bagit
import chardet
from collections import OrderedDict
from collections import Counter
import csv
import datetime
import errno
import fnmatch
import glob
import hashlib
from lxml import etree
import math
import openpyxl
import os
import pickle
import psutil
import re
import shelve
import shutil
import sqlite3
import subprocess
import sys
import tarfile
import time
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
from urllib.parse import unquote
import urllib.request
import uuid
import webbrowser
import zipfile
# from dfxml project
import Objects
class Unit:
def __init__(self, controller):
self.controller = controller
self.unit_name = self.controller.unit_name.get()
self.unit_home = self.controller.bdpl_work_drive
self.ingest_dir = os.path.join(self.unit_home, 'ingest')
self.dropbox_dir = os.path.join(self.unit_home, 'dropbox')
self.media_image_dir = os.path.join(self.unit_home, 'media-images')
self.completed_shpt_dir = os.path.join(self.unit_home, 'completed_shipments')
self.completed_shpts_all = os.path.join(self.completed_shpt_dir, 'all')
for dir in [self.ingest_dir, self.dropbox_dir, self.media_image_dir, self.completed_shpt_dir, self.completed_shpts_all]:
if not os.path.exists(dir):
os.mkdir(dir)
def move_media_images(self):
if len(os.listdir(self.media_image_dir)) == 0:
print('\n\nNo images of media at {}'.format(self.media_image_dir))
return
# get a list of barcodes in each shipment
all_barcode_folders = list(filter(lambda f: os.path.isdir(f), glob.glob('{}\\*\\*'.format(self.ingest_dir))))
#list of files with no parent
bad_file_list = []
#loop through a list of all images in this folder; try to find match in list of barcodes; if not, add to 'bad file list'
for f in os.listdir(self.media_image_dir):
print('\nWorking on... ', f)
pic = f.split('-')[0]
barcode_folder = [s for s in all_barcode_folders if pic in s]
if len(barcode_folder) == 1:
media_pics = os.path.join(barcode_folder[0], 'metadata', 'media-image')
if not os.path.exists(media_pics):
os.makedirs(media_pics)
try:
shutil.move(os.path.join(self.media_image_dir, f), media_pics)
print('\n\tSuccessfully moved!\n')
except shutil.Error as e:
print('NOTE: ', e)
print('\n\nCheck the media image folder to determine if a file already exists or a filename is being duplicated.')
else:
bad_file_list.append(f)
if len(bad_file_list) > 0:
print('\n\nFilenames for the following images do not match current barcodes:\n{}'.format('\n'.join(bad_file_list)))
print('\nPlease correct filenames and try again.')
else:
print('\n\nMedia images successfully copied!')
class Shipment(Unit):
def __init__(self, controller):
Unit.__init__(self, controller)
self.controller = controller
self.shipment_date = self.controller.shipment_date.get()
self.shipment_name = '{}_{}'.format(self.unit_name, self.shipment_date)
self.ship_dir = os.path.join(self.ingest_dir, self.shipment_date)
self.deaccession_dir = os.path.join(self.ship_dir, 'deaccessioned')
self.item_ingest_info = os.path.join(self.ship_dir, 'item_ingest_info')
try:
if not os.path.exists(self.item_ingest_info):
os.makedirs(self.item_ingest_info)
except FileExistsError:
pass
self.spreadsheet = os.path.join(self.ship_dir, '{}_{}.xlsx'.format(self.unit_name, self.shipment_date))
def verify_spreadsheet(self):
if self.__class__.__name__ in ['Spreadsheet', 'Shipment']:
#check what is in the shipment dir
found = glob.glob(os.path.join(self.ship_dir, '*.xlsx'))
if len(found) == 0:
return (False, '\nWARNING: No .XLSX spreadsheet found in {}. Check {} dropbox or consult with digital preservation librarian.'.format(self.ship_dir, self.unit_name))
elif len(found) > 1:
if not self.spreadsheet in found:
return (False, '\nWARNING: multiple spreadsheets found; none follow the BDPL naming convention of {}_{}.xlsx:\n\n\t{}'.format(self.unit_name, self.shipment_date, '\n\t'.join(found)))
elif found[0] == self.spreadsheet:
pass
else:
return (False, '\n\tWARNING: {} only contains the following spreadsheet: {}'.format(self.ship_dir, found[0]))
elif self.__class__.__name__ == 'MasterSpreadsheet':
if not os.path.exists(self.spreadsheet):
return (False, 'Unable to locate {}. Consult with digital preservation librarian.'.format(self.spreadsheet))
#now check to see if spreadsheet is already open
temp_file = os.path.join(os.path.dirname(self.spreadsheet), '~${}'.format(os.path.basename(self.spreadsheet)))
if not os.path.isfile(temp_file):
return (True, "Let's roll!")
else:
#I don't know what the problem is, but I was having a LOT of problems with ghost lockfiles (~$); uncomment if problem persists!
#os.remove(temp_file)
return (False, '\n\nWARNING: {} is currently open. Close file before continuing and/or contact digital preservation librarian if other users are involved.'.format(self.spreadsheet))
def convert_size(self, size):
# convert size to human-readable form
if (size == 0):
return '0 bytes'
size_name = ("bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size,1024)))
p = math.pow(1024,i)
s = round(size/p, 2)
s = str(s)
s = s.replace('.0', '')
return '{} {}'.format(s,size_name[i])
class DigitalObject(Shipment):
def __init__(self, controller, skip_folders=False):
Shipment.__init__(self, controller)
self.controller = controller
self.identifier = self.controller.identifier.get()
self.skip_folders = skip_folders
'''SET VARIABLES'''
#main folders
self.barcode_dir = os.path.join(self.ship_dir, self.identifier)
self.image_dir = os.path.join(self.barcode_dir, "disk-image")
self.files_dir = os.path.join(self.barcode_dir, "files")
self.metadata_dir = os.path.join(self.barcode_dir, "metadata")
self.temp_dir = os.path.join(self.barcode_dir, "temp")
self.reports_dir = os.path.join(self.metadata_dir, "reports")
self.log_dir = os.path.join(self.metadata_dir, "logs")
self.bulkext_dir = os.path.join(self.barcode_dir, "bulk_extractor")
self.folders = [self.barcode_dir, self.image_dir, self.files_dir, self.metadata_dir, self.temp_dir, self.reports_dir, self.log_dir, self.bulkext_dir, self.media_image_dir]
#assets
self.imagefile = os.path.join(self.image_dir, '{}.dd'.format(self.identifier))
self.paranoia_out = os.path.join(self.files_dir, '{}.wav'.format(self.identifier))
self.tar_file = os.path.join(self.ship_dir, '{}.tar'.format(self.identifier))
#files related to disk imaging with ddrescue and FC5025
self.mapfile = os.path.join(self.log_dir, '{}.map'.format(self.identifier))
self.fc5025_log = os.path.join(self.log_dir, 'fcimage.log')
#log files
self.virus_log = os.path.join(self.log_dir, 'viruscheck-log.txt')
self.bulkext_log = os.path.join(self.log_dir, 'bulkext-log.txt')
self.lsdvd_out = os.path.join(self.reports_dir, "{}_lsdvd.xml".format(self.identifier))
self.paranoia_log = os.path.join(self.log_dir, '{}-cdparanoia.log'.format(self.identifier))
#reports
self.disk_info_report = os.path.join(self.reports_dir, '{}-cdrdao-diskinfo.txt'.format(self.identifier))
self.sf_file = os.path.join(self.reports_dir, 'siegfried.csv')
self.dup_report = os.path.join(self.reports_dir, 'duplicates.csv')
self.disktype_output = os.path.join(self.reports_dir, 'disktype.txt')
self.fsstat_output = os.path.join(self.reports_dir, 'fsstat.txt')
self.ils_output = os.path.join(self.reports_dir, 'ils.txt')
self.mmls_output = os.path.join(self.reports_dir, 'mmls.txt')
self.tree_dest = os.path.join(self.reports_dir, 'tree.txt')
self.new_html = os.path.join(self.reports_dir, 'report.html')
self.formatcsv = os.path.join(self.reports_dir, 'formats.csv')
self.assets_target = os.path.join(self.reports_dir, 'assets')
#temp files
self.ffmpeg_temp_dir = os.path.join(self.temp_dir, 'ffmpeg')
self.siegfried_db = os.path.join(self.temp_dir, 'siegfried.sqlite')
self.cumulative_be_report = os.path.join(self.bulkext_dir, 'cumulative.txt')
self.lsdvd_temp = os.path.join(self.temp_dir, 'lsdvd.txt')
self.temp_dfxml = os.path.join(self.temp_dir, 'temp_dfxml.txt')
self.dummy_audio = os.path.join(self.temp_dir, 'added_silence.mpg')
self.cdr_scan = os.path.join(self.temp_dir, 'cdr_scan.txt')
self.droid_profile = os.path.join(self.temp_dir, 'droid.droid')
self.droid_out = os.path.join(self.temp_dir, 'droid.csv')
self.temp_html = os.path.join(self.temp_dir, 'temp.html')
self.assets_dir = 'C:\\BDPL\\resources\\assets'
self.duplicates = os.path.join(self.temp_dir, 'duplicates.txt')
self.folders_created = os.path.join(self.temp_dir, 'folders-created.txt').replace(os.sep, os.altsep)
self.sqlite_done = os.path.join(self.temp_dir, 'sqlite_done.txt')
self.stats_done = os.path.join(self.temp_dir, 'stats_done.txt')
self.done_file = os.path.join(self.temp_dir, 'done.txt')
self.final_stats = os.path.join(self.temp_dir, 'final_stats.txt')
self.checksums_dvd = os.path.join(self.temp_dir, 'checksums_dvd.txt')
self.checksums = os.path.join(self.temp_dir, 'checksums.txt')
#metadata files
self.dfxml_output = os.path.join(self.metadata_dir, '{}-dfxml.xml'.format(self.identifier))
self.premis_xml_file = os.path.join(self.metadata_dir, '{}-premis.xml'.format(self.identifier))
#create folders; we will skip this step when moving content to MCO or SDA
if not self.skip_folders and not self.check_ingest_folders():
self.create_folders()
#set up shelve
self.temp_info = os.path.join(self.item_ingest_info, '{}-info'.format(self.identifier))
self.db = shelve.open(self.temp_info, writeback=True)
if not 'premis' in list(self.db.keys()):
#legacy items: check for pickled premis info
old_premis = os.path.join(self.temp_dir, 'premis_list.txt')
if os.path.exists(old_premis):
with open(old_premis, 'rb') as f:
self.db['premis'] = pickle.load(f)
else:
self.db['premis'] = []
self.db.sync()
#special vars for RipstationBatch
if self.controller.get_current_tab() == 'RipStation Ingest':
self.rs_wav_file = os.path.join(self.files_dir, "{}.wav".format(self.identifier))
self.rs_wav_cue = os.path.join(self.files_dir, "{}.cue".format(self.identifier))
self.rs_cdr_bin = os.path.join(self.image_dir, "{}-01.bin".format(self.identifier))
self.rs_cdr_toc = os.path.join(self.image_dir, "{}-01.toc".format(self.identifier))
self.rs_cdr_cue = os.path.join(self.image_dir, "{}-01.cue".format(self.identifier))
self.ripstation_item_log = os.path.join(self.log_dir, 'ripstation.txt')
self.ripstation_orig_imagefile = os.path.join(self.image_dir, '{}.iso'.format(self.identifier))
def prep_barcode(self):
shipment_spreadsheet = Spreadsheet(self.controller)
#verify spreadsheet exists and make sure it's not opened
if self.controller.get_current_tab() == 'BDPL Ingest':
status, msg = shipment_spreadsheet.verify_spreadsheet()
if not status:
return (status, msg)
#open spreadsheet and make sure current item exists in spreadsheet; if not, return
shipment_spreadsheet.open_wb()
status, row = shipment_spreadsheet.return_row(shipment_spreadsheet.inv_ws)
#if status is False, then barcode doesn't exist in spreadsheet. Close shelve and delete created folders
if not status:
self.db.close()
self.delete_folders()
return (False, '\n\nWARNING: barcode was not found in spreadsheet. Make sure value is entered correctly and/or check spreadsheet for value. Consult with digital preservation librarian as needed.')
#load metadata into item object
self.load_item_metadata(shipment_spreadsheet)
#assign variables to GUI
if self.controller.get_current_tab() == 'BDPL Ingest':
self.controller.content_source_type.set(self.db['info']['content_source_type'])
self.controller.collection_title.set(self.db['info']['collection_title'])
self.controller.collection_creator.set(self.db['info']['collection_creator'])
self.controller.item_title.set(self.db['info'].get('item_title', ''))
self.controller.label_transcription.set(self.db['info']['label_transcription'])
self.controller.item_description.set(self.db['info'].get('item_description', ''))
self.controller.appraisal_notes.set(self.db['info']['appraisal_notes'])
self.controller.bdpl_instructions.set(self.db['info']['bdpl_instructions'])
return (True, '\n\nRecord loaded successfully; ready for next operation.')
def check_barcode_status(self):
#If a 'done' file exists, we know the whole process was completed
done_file = os.path.join(self.temp_dir, 'done.txt')
if os.path.exists(done_file):
print('\n\nNOTE: this item barcode has completed the entire BDPL Ingest workflow. Consult with the digital preservation librarian if you believe additional procedures are needed.')
#if no 'done' file, see where we are with the item...
else:
if len(self.db['premis']) > 0:
print('\n\nIngest of item has been initiated; the following procedures have been completed:\n\t{}'.format('\n\t'.join(list(set((i['eventType'] for i in self.db['premis']))))))
def load_item_metadata(self, shipment_spreadsheet):
if not 'info' in list(self.db.keys()):
#catch legacy items where metadata was pickled
old_metadata = os.path.join(self.temp_dir, 'metadata_dict.txt')
if os.path.exists(old_metadata):
with open(old_metadata, 'rb') as f:
self.db['info'] = pickle.load(f)
else:
self.db['info'] = {}
self.db['info']['unit_name'] = self.unit_name
self.db['info']['shipment_date'] = self.shipment_date
#get info from inventory and appraisal sheets
for ws in (shipment_spreadsheet.inv_ws, shipment_spreadsheet.app_ws):
ws_columns = shipment_spreadsheet.get_spreadsheet_columns(ws)
status, row = shipment_spreadsheet.return_row(ws)
if ws == shipment_spreadsheet.app_ws and not status:
pass
else:
for key in ws_columns.keys():
if key == 'identifier':
self.db['info']['identifier'] = self.identifier
#if we've already recorded information for virus and pii scan results, don't overwrite
elif key == 'virus_scan_results':
if self.db['info'].get('virus_scan_results') and len(self.db['info']['virus_scan_results']) > 1:
pass
elif key == 'pii_scan_results':
if self.db['info'].get('pii_scan_results') and len(self.db['info']['pii_scan_results']) > 1:
pass
else:
_val = ws.cell(row=row, column=ws_columns[key]).value
if _val is None or str(_val).lower() in [' ', '-', 'n/a', 'none']:
self.db['info'][key] = ''
else:
self.db['info'][key] = _val
#save a copy so we can access later
self.db.sync()
def check_ingest_folders(self):
for f in self.folders:
if not os.path.exists(f):
return False
return True
def create_folders(self):
#folders-created file will help us check for completion
#if file doesn't exist, create folders
for target in self.folders:
try:
os.makedirs(target)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
#create file so we can check for completion later, if need be
open(self.folders_created, 'w').close()
def delete_folders(self):
#if file doesn't exist, delete folders
for target in self.folders:
try:
shutil.rmtree(target, ignore_errors=True)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
def verify_analysis_details(self):
#make sure main variables--unit_name, shipment_date, and barcode--are included. Return if either is missing
status, msg = self.controller.check_main_vars()
if not status:
return (status, msg)
#make sure we have already initiated a session for this barcode
if not self.check_ingest_folders():
return (False, '\n\nWARNING: load record before proceeding')
if not self.controller.job_type.get() in ['Copy_only', 'Disk_image', 'CDDA', 'DVD']:
return (False, '\nWARNING: Indicate the appropriate job type for this item and then run transfer again.')
else:
self.job_type = self.controller.job_type.get()
self.re_analyze = self.controller.re_analyze.get()
return (True, 'Ready to analyze!')
def verify_transfer_details(self):
#make sure directories have already been created (i.e., record was loaded)
if not os.path.exists(self.barcode_dir):
return (False, '\nWARNING: Load record before proceeding; directory structure has not been created.')
if self.controller.job_type.get() is None:
return (False, '\nWARNING: Indicate the appropriate job type for this item and then run transfer again.')
else:
self.job_type = self.controller.job_type.get()
#set copy_only variables
if self.job_type == 'Copy_only':
if self.controller.path_to_content.get() == '':
return (False, '\nERROR: no path to content provided. Be sure to click the "Browse" button and navigate to appropriate source.')
if not os.path.exists(self.controller.path_to_content.get()):
return (False, '\nWARNING: {} does not exist. Make sure path is entered correctly and try transfer again.')
self.path_to_content = self.controller.path_to_content.get().replace('/', '\\')
#if source is in 'Z:/bdpl_transfer_list', the path_to_content is a file
if 'bdpl_transfer_list' in self.path_to_content:
self.path_to_content = os.path.join(self.path_to_content, '{}.txt'.format(self.identifier))
return (True, 'Ready to transfer')
#set other variables
else:
self.media_attached = self.controller.media_attached.get()
self.source_device = self.controller.source_device.get()
self.other_device = self.controller.other_device.get()
self.disk_525_type = self.controller.disk_525_type.get()
self.disk_type_options = { 'Apple DOS 3.3 (16-sector)' : 'apple33', 'Apple DOS 3.2 (13-sector)' : 'apple32', 'Apple ProDOS' : 'applepro', 'Commodore 1541' : 'c1541', 'TI-99/4A 90k' : 'ti99', 'TI-99/4A 180k' : 'ti99ds180', 'TI-99/4A 360k' : 'ti99ds360', 'Atari 810' : 'atari810', 'MS-DOS 1200k' : 'msdos12', 'MS-DOS 360k' : 'msdos360', 'North Star MDS-A-D 175k' : 'mdsad', 'North Star MDS-A-D 350k' : 'mdsad350', 'Kaypro 2 CP/M 2.2' : 'kaypro2', 'Kaypro 4 CP/M 2.2' : 'kaypro4', 'CalComp Vistagraphics 4500' : 'vg4500', 'PMC MicroMate' : 'pmc', 'Tandy Color Computer Disk BASIC' : 'coco', 'Motorola VersaDOS' : 'versa' }
#make sure media has been attached
if not self.media_attached:
return (False, '\nWARNING: Make sure media is in drive and/or attached. Check the "Attached?" button and launch transfer again.')
#make sure we are using the optical drive for DVD and CDDA jobs
if self.job_type in ['DVD', 'CDDA'] and self.source_device != '/dev/sr0':
return (False, '\nWARNING: DVD and CDDA jobs must select the "CD/DVD" media source. Check settings and try transfer again.')
else:
self.ddrescue_target = self.source_device
return (True, 'Ready to transfer')
#we'll assign 'ddrescue_target' variable here
if self.job_type == 'Disk_image':
#must have a source device selected.
if self.source_device is None:
return (False, '\nWARNING: Indicate the appropriate source media/device for this item and then run transfer again.')
#make sure that a disk type is selected if this is a 5.25" floppy
if self.source_device == '5.25':
if self.disk_525_type == 'N/A':
return (False, '\nWARNING: Select a 5.25" disk type from the drop-down menu and try again.')
else:
return (True, 'Ready to transfer')
elif self.source_device in ['/dev/sr0', '/dev/fd0']:
self.ddrescue_target = self.source_device
return (True, 'Ready to transfer')
else:
#get POSIX device names from /proc/partitions
posix_names = subprocess.check_output('cat /proc/partitions', shell=True, text=True)
#get all physical drives and associated drive letters using PowerShell
ps_cmd = "Get-Partition | % {New-Object PSObject -Property @{'DiskModel'=(Get-Disk $_.DiskNumber).Model; 'DriveLetter'=$_.DriveLetter}}"
cmd = 'powershell.exe "{}"'.format(ps_cmd)
drive_letters = subprocess.check_output(cmd, shell=True, text=True)
#verify Zip drive device name
if self.source_device == 'Zip':
for letter in drive_letters.splitlines():
if 'ZIP 100' in letter:
drive_ltr = letter.split()[2]
#verify that Zip drive was recognized and drive letter variable was assigned
try:
drive_ltr
except UnboundLocalError:
return (False, '\nWARNING: Zip drive not recognized. Re-insert disk into drive, allow device to complete initial loading, and attempt transfer again.')
#match drive letter with POSIX device name
for line in drive_letters.splitlines():
if len(line.split()) == 5 and drive_ltr in line.split()[4]:
self.ddrescue_target = '/dev/{}'.format(line.split()[3])
return (True, 'Ready to transfer')
#if unable to match drive letter and posix name, return false
return (False, '\nWARNING: Zip drive not recognized. Re-insert disk into drive, allow device to complete initial loading, and attempt transfer again.')
elif self.source_device == 'Other':
if self.other_device in posix_names:
self.ddrescue_target = '/dev/{}'.format(self.other_device)
return (True, 'Ready to transfer')
else:
return (False, '\nWARNING: device "{}" was not found in /proc/partitions; verify name, re-enter information, and attempt transfer again.'.format(self.other_device))
def get_size(self, start_path):
total_size = 0
if os.path.isfile(start_path):
total_size = os.path.getsize(start_path)
else:
for dirpath, dirnames, filenames in os.walk(start_path):
for f in filenames:
fp = os.path.join(dirpath, f)
# skip if it is symbolic link
if not os.path.islink(fp):
total_size += os.path.getsize(fp)
return total_size
def secure_copy(self, content_source):
#function takes the file source and destination as well as a specific premis event to be used in documenting action
print('\n\nFILE REPLICATION: TERACOPY\n\n\tSOURCE: {} \n\tDESTINATION: {}'.format(content_source, self.files_dir))
#set variables for premis
timestamp = str(datetime.datetime.now())
teracopy_ver = "TeraCopy v3.26"
destination = self.files_dir.replace('/', '\\')
#set variables for copy operation; note that if we are using a file list, TERACOPY requires a '*' before the source.
if os.path.isfile(content_source):
copycmd = 'TERACOPY COPY *"{}" "{}" /SkipAll /CLOSE'.format(content_source, destination)
else:
copycmd = 'TERACOPY COPY "{}" "{}" /SkipAll /CLOSE'.format(content_source, destination)
try:
exitcode = subprocess.call(copycmd, shell=True, text=True)
except subprocess.CalledProcessError as e:
print('\n\tFile replication failed:\n\n\t{}'.format(e))
return
#need to find Teracopy SQLITE db and export list of copied files to csv log file
list_of_files = glob.glob(os.path.join(os.path.expandvars('C:\\Users\%USERNAME%\AppData\Roaming\TeraCopy\History'), '*'))
tera_db = max(list_of_files, key=os.path.getctime)
conn = sqlite3.connect(tera_db)
conn.text_factory = str
cur = conn.cursor()
results = cur.execute("SELECT * from Files")
#now write the results to a csv file
tera_log = os.path.join(self.log_dir, 'teracopy_log.csv')
with open(tera_log, 'w', encoding='utf8') as output:
writer = csv.writer(output, lineterminator='\n')
header = ['Source', 'Offset', 'State', 'Size', 'Attributes', 'IsFolder', 'Creation', 'Access', 'Write', 'SourceCRC', 'TargetCRC', 'TargetName', 'Message', 'Marked', 'Hidden']
writer.writerow(header)
writer.writerows(results)
cur.close()
conn.close()
#get count of files that were actually moved
count = 0
with open(tera_log, 'r', encoding='utf8') as input:
csvreader = csv.reader(input)
for row in csvreader:
if row[5] == '0':
count += 1
print('\n\t{} files successfully transferred to {}.'.format(count, self.files_dir))
#record premis
self.record_premis(timestamp, 'replication', exitcode, copycmd, 'Created a copy of an object that is, bit-wise, identical to the original.', teracopy_ver)
print('\n\tFile replication completed; proceed to content analysis.')
def fc5025_image(self):
print('\n\n\DISK IMAGE CREATION: DeviceSideData FC5025\n\n\tSOURCE: 5.25" floppy disk \n\tDESTINATION: {}\n\n'.format(self.imagefile))
timestamp = str(datetime.datetime.now())
copycmd = 'fcimage -f {} {} | tee -a {}'.format(self.disk_type_options[self.disk_525_type], self.imagefile, self.fc5025_log)
exitcode = subprocess.call(copycmd, shell=True, text=True)
#NOTE: FC5025 will return non-zero exitcode if any errors detected. As disk image creation may still be 'successful', we will fudge the results a little bit. Failure == no disk image.
if exitcode != 0:
if os.stat(imagefile).st_size > 0:
exitcode = 0
else:
messagebox.showwarning(title='WARNING', message='Disk image not successfully created. Verify you have selected the correct disk type and try again (if possible). Otherwise, indicate issues in note to collecting unit.', master=self.controller)
return
#record event in PREMIS metadata
self.record_premis(timestamp, 'disk image creation', exitcode, copycmd, 'Extracted a disk image from the physical information carrier.', 'FCIMAGE v1309')
print('\n\n\tDisk image created; proceeding to next step...')
def ddrescue_image(self):
print('\n\nDISK IMAGE CREATION: DDRESCUE\n\n\tSOURCE: {} \n\tDESTINATION: {}'.format(self.ddrescue_target, self.imagefile))
dd_ver = subprocess.check_output('ddrescue -V', shell=True, text=True).split('\n', 1)[0]
timestamp1 = str(datetime.datetime.now())
image_cmd1 = 'ddrescue -n {} {} {}'.format(self.ddrescue_target, self.imagefile, self.mapfile)
print('\n--------------------------------------First pass with ddrescue------------------------------------\n')
exitcode1 = subprocess.call(image_cmd1, shell=True, text=True)
#record event in PREMIS metadata
self.record_premis(timestamp1, 'disk image creation', exitcode1, image_cmd1, 'First pass; extracted a disk image from the physical information carrier.', dd_ver)
#new timestamp for second pass (recommended by ddrescue developers)
timestamp2 = str(datetime.datetime.now())
image_cmd2 = 'ddrescue -d -r2 {} {} {}'.format(self.ddrescue_target, self.imagefile, self.mapfile)
print('\n\n--------------------------------------Second pass with ddrescue------------------------------------\n')
exitcode2 = subprocess.call(image_cmd2, shell=True, text=True)
#record event in PREMIS metadata if successful
if os.path.exists(self.imagefile) and os.stat(self.imagefile).st_size > 0:
print('\n\n\tDisk image created; proceeding to next step...')
exitcode2 = 0
self.record_premis(timestamp2, 'disk image creation', exitcode2, image_cmd2, 'Second pass; extracted a disk image from the physical information carrier.', dd_ver)
else:
print('\n\nDISK IMAGE CREATION FAILED: Indicate any issues in note to collecting unit.')
def disk_image_info(self):
print('\n\nDISK IMAGE METADATA EXTRACTION: FSSTAT, ILS, MMLS')
#run disktype to get information on file systems on disk
disktype_command = 'disktype {} > {}'.format(self.imagefile, self.disktype_output)
timestamp = str(datetime.datetime.now())
exitcode = subprocess.call(disktype_command, shell=True, text=True)
#record event in PREMIS metadata
self.record_premis(timestamp, 'forensic feature analysis', exitcode, disktype_command, 'Determined disk image file system information.', 'disktype v9')
#get disktype output; check character encoding just in case there's something funky...
with open(self.disktype_output, 'rb') as f:
charenc = chardet.detect(f.read())
with open(self.disktype_output, 'r', encoding=charenc['encoding']) as f:
dt_out = f.read()
#print disktype output to screen
print(dt_out, end="")
#get a list of output
dt_info = dt_out.split('Partition ')
#now loop through the list to get all file systems ID'd by disktype. Split results so we just get the name of the file system (and make lower case to avoid issues)
self.db['fs_list'] = []
for dt in dt_info:
if 'file system' in dt:
self.db['fs_list'].append([d for d in dt.split('\n') if ' file system' in d][0].split(' file system')[0].lstrip().lower())
#save file system list for later...
self.db.sync()
#run fsstat: get range of meta-data values (inode numbers) and content units (blocks or clusters)
fsstat_ver = 'fsstat: {}'.format(subprocess.check_output('fsstat -V', shell=True, text=True).strip())
fsstat_command = 'fsstat {} > {} 2>&1'.format(self.imagefile, self.fsstat_output)
timestamp = str(datetime.datetime.now())
try:
exitcode = subprocess.call(fsstat_command, shell=True, text=True, timeout=60)
#if process times out, kill it and mark as failed
except subprocess.TimeoutExpired:
for proc in psutil.process_iter():
if proc.name() == 'fsstat.exe':
psutil.Process(proc.pid).terminate()
exitcode = 1
#record event in PREMIS metadata
self.record_premis(timestamp, 'forensic feature analysis', exitcode, fsstat_command, 'Determined range of meta-data values (inode numbers) and content units (blocks or clusters)', fsstat_ver)
#run ils to document inode information
ils_ver = 'ils: {}'.format(subprocess.check_output('ils -V', shell=True, text=True).strip())
ils_command = 'ils -e {} > {} 2>&1'.format(self.imagefile, self.ils_output)
timestamp = str(datetime.datetime.now())
try:
exitcode = subprocess.call(ils_command, shell=True, text=True, timeout=60)
#if the command times out, kill the process and report as a failure
except subprocess.TimeoutExpired:
for proc in psutil.process_iter():
if proc.name() == 'ils.exe':
psutil.Process(proc.pid).terminate()
exitcode = 1
#record event in PREMIS metadata
self.record_premis(timestamp, 'forensic feature analysis', exitcode, ils_command, 'Documented all inodes found on disk image.', ils_ver)
#run mmls to document the layout of partitions in a volume system
mmls_ver = 'mmls: {}'.format(subprocess.check_output('mmls -V', shell=True, text=True).strip())
mmls_command = 'mmls {} > {} 2>NUL'.format(self.imagefile, self.mmls_output)
timestamp = str(datetime.datetime.now())
exitcode = subprocess.call(mmls_command, shell=True, text=True)
#record event in PREMIS metadata
self.record_premis(timestamp, 'forensic feature analysis', exitcode, mmls_command, 'Determined the layout of partitions in a volume system.', mmls_ver)
#check mmls output for partition information; first make sure there's actually data in the mmls output file
self.db['partition_info_list'] = []
if os.stat(self.mmls_output).st_size > 0:
with open(self.mmls_output, 'r', encoding='utf8') as f:
mmls_info = [m.split('\n') for m in f.read().splitlines()[5:]]
#loop through mmls output; match file system info (block start/end and partition#) with what came from disktype
for mm in mmls_info:
temp = {}
for dt in dt_info:
if 'file system' in dt and ', {} sectors from {})'.format(mm[0].split()[4].lstrip('0'), mm[0].split()[2].lstrip('0')) in dt:
fsname = [d for d in dt.split('\n') if ' file system' in d][0].split(' file system')[0].lstrip().lower()
temp['start'] = mm[0].split()[2]
temp['desc'] = fsname
temp['slot'] = mm[0].split()[1]
#now save this dictionary to our list of partition info
if not temp in self.db['partition_info_list']:
self.db['partition_info_list'].append(temp)
#save partition info for later
self.db.sync()
def disk_image_replication(self):
print('\n\nDISK IMAGE FILE REPLICATION: ')
#get our software versions for unhfs and tsk_recover
cmd = 'unhfs 2>&1'
unhfs_tool_ver = subprocess.check_output(cmd, shell=True, text=True).splitlines()[0]
tsk_tool_ver = 'tsk_recover: {}'.format(subprocess.check_output('tsk_recover -V', text=True).strip())
#now get information on filesystems and (if present) partitions. We will need to choose which tool to use based on file system; if UDF or ISO9660 present, use TeraCopy; otherwise use unhfs or tsk_recover
secure_copy_list = ['udf', 'iso9660']
unhfs_list = ['osx', 'hfs', 'apple', 'apple_hfs', 'mfs', 'hfs plus']
tsk_list = ['ntfs', 'fat', 'fat12', 'fat16', 'fat32', 'exfat', 'ext2', 'ext3', 'ext4', 'ufs', 'ufs1', 'ufs2', 'ext', 'yaffs2', 'hfs+']
#Proceed if any file systems were found; return if none identified
if len(self.db['fs_list']) > 0:
print('\n\tDisktype has identified the following file system(s): ', ', '.join(self.db['fs_list']))
#now check for any partitions; if none, go ahead and use teracopy, tsk_recover, or unhfs depending on the file system
if len(self.db['partition_info_list']) <= 1:
print('\n\tNo partition information...')
if any(fs in ' '.join(self.db['fs_list']) for fs in secure_copy_list):
if self.controller.get_current_tab() == 'RipStation Ingest':
os.rename(self.imagefile, self.ripstation_orig_imagefile)
self.mount_iso()
drive_letter = self.get_iso_drive_letter()
self.secure_copy(drive_letter)
self.dismount_iso()
os.rename(self.ripstation_orig_imagefile, self.imagefile)
else:
self.secure_copy(self.optical_drive_letter())
elif any(fs in ' '.join(self.db['fs_list']) for fs in unhfs_list):
self.carve_files('unhfs', unhfs_tool_ver, '', self.files_dir)
elif any(fs in ' '.join(self.db['fs_list']) for fs in tsk_list):
self.carve_files('tsk_recover', tsk_tool_ver, '', self.files_dir)
else:
print('\n\tCurrent tools unable to address file system.')
return
#if there are one or more partitions, use tsk_recover or unhfs
elif len(self.db['partition_info_list']) > 1:
for partition in self.db['partition_info_list']:
outfolder = os.path.join(self.files_dir, 'partition_{}'.format(partition['slot']))
if partition['desc'] in unhfs_list:
self.carve_files('unhfs', unhfs_tool_ver, partition['slot'], outfolder)
elif partition['desc'] in tsk_list:
carve_files('tsk_recover', tsk_tool_ver, partition['start'], outfolder)
else:
print('\n\tNo files to be replicated.')
def optical_drive_letter(self):
#NOTE: this assumes only 1 optical disk drive is connected to workstation
drive_cmd = 'wmic logicaldisk get caption, drivetype | FINDSTR /C:"5"'
drive_ltr = subprocess.check_output(drive_cmd, shell=True, text=True).split()[0]
return drive_ltr
def carve_files(self, tool, tool_ver, partition, outfolder):
if not os.path.exists(outfolder):
os.makedirs(outfolder)
if tool == 'unhfs':
if partition == '':
carve_cmd = 'unhfs -sfm-substitutions -resforks APPLEDOUBLE -o "{}" "{}" 2>nul'.format(outfolder, self.imagefile)
else:
carve_cmd = 'unhfs -sfm-substitutions -partition {} -resforks APPLEDOUBLE -o "{}" "{}" 2>nul'.format(partition, outfolder, self.imagefile)
else:
if partition == '':
carve_cmd = 'tsk_recover -a {} {}'.format(self.imagefile, outfolder)
else:
carve_cmd = 'tsk_recover -a -o {} {} {}'.format(partition, self.imagefile, outfolder)
print('\n\tTOOL: {}\n\n\tSOURCE: {} \n\n\tDESTINATION: {}\n'.format(tool, self.imagefile, outfolder))
timestamp = str(datetime.datetime.now())
exitcode = subprocess.call(carve_cmd, shell=True)
#record event in PREMIS metadata
self.record_premis(timestamp, 'replication', exitcode, carve_cmd, "Created a copy of an object that is, bit-wise, identical to the original.", tool_ver)
#if no files were extracted, remove partition folder.
if not self.check_files(outfolder) and outfolder != self.files_dir:
os.rmdir(outfolder)
#if tsk_recover has been run, go through and fix the file MAC times
if tool == 'tsk_recover' and exitcode == 0:
#generate DFXML with fiwalk
if not os.path.exists(self.dfxml_output):
self.produce_dfxml(self.imagefile)
#use DFXML output to get correct MAC times and update files
self.fix_dates(outfolder)
elif tool == 'unhfs' and os.path.exists(outfolder):
file_count = sum([len(files) for r, d, files in os.walk(outfolder)])
print('\t{} files successfully transferred to {}.'.format(file_count, outfolder))
print('\n\tFile replication completed; proceed to content analysis.')
def produce_dfxml(self, target):
timestamp = str(datetime.datetime.now())
file_stats = []
#use fiwalk if we have an image file
if os.path.isfile(target):
print('\n\nDIGITAL FORENSICS XML CREATION: FIWALK')
dfxml_ver_cmd = 'fiwalk-0.6.3 -V'
dfxml_ver = subprocess.check_output(dfxml_ver_cmd, shell=True, text=True).splitlines()[0]
dfxml_cmd = 'fiwalk-0.6.3 -x {} > {}'.format(target, self.dfxml_output)
exitcode = subprocess.call(dfxml_cmd, shell=True, text=True)
#parse dfxml to get info for later; because large DFXML files pose a challenge; use iterparse to avoid crashing (Note: for DVD jobs we will also get stats on the files themselves later on)
print('\n\tCollecting file statistics...\n')
counter = 0
for event, element in etree.iterparse(self.dfxml_output, events = ("end",), tag="fileobject"):
#refresh dict for each fileobject
file_dict = {}
#default values; will make sure that we don't record info about non-allocated files and that we have a default timestamp value
good = True
mt = False
mtime = 'undated'
target = ''
size = ''
checksum = ''
for child in element:
if child.tag == "filename":
target = child.text
if child.tag == "name_type":
if child.text != "r":
element.clear()
good = False
break
if child.tag == "alloc":
if child.text != "1":
good = False
element.clear()
break
if child.tag == "unalloc":
if child.text == "1":
good = False
element.clear()
break
if child.tag == "filesize":
size = child.text
if child.tag == "hashdigest":
if child.attrib['type'] == 'md5':
checksum = child.text
if child.tag == "mtime":
mtime = datetime.datetime.utcfromtimestamp(int(child.text)).isoformat()
mt = True
if child.tag == "crtime" and mt == False:
mtime = datetime.datetime.utcfromtimestamp(int(child.text)).isoformat()
if good and not '' in file_dict.values():
file_dict = { 'name' : target, 'size' : size, 'mtime' : mtime, 'checksum' : checksum}
file_stats.append(file_dict)
counter+=1
print('\r\tWorking on file #: {}'.format(counter), end='')
element.clear()
if self.job_type == 'DVD':
#save info from DVD checksums to separate file
with open (self.checksums_dvd, 'wb') as f:
pickle.dump(file_stats, f)
#now compile stats for the normalized file versions
file_stats = []
for f in os.listdir(self.files_dir):
file = os.path.join(self.files_dir, f)
file_dict = {}
size = os.path.getsize(file)
mtime = datetime.datetime.fromtimestamp(os.path.getmtime(file)).isoformat()
ctime = datetime.datetime.fromtimestamp(os.path.getctime(file)).isoformat()
atime = datetime.datetime.fromtimestamp(os.path.getatime(file)).isoformat()[:-7]
checksum = self.md5(file)
file_dict = { 'name' : file, 'size' : size, 'mtime' : mtime, 'ctime' : ctime, 'atime' : atime, 'checksum' : checksum}
file_stats.append(file_dict)
#use custom operation for other cases
elif os.path.isdir(target):
print('\n\nDIGITAL FORENSICS XML CREATION: bdpl_ingest')
dfxml_ver = 'https://github.com/IUBLibTech/bdpl_ingest'
dfxml_cmd = 'bdpl_ingest.py'
timestamp = str(datetime.datetime.now().isoformat())
done_list = []
if os.path.exists(self.temp_dfxml):
with open(self.temp_dfxml, 'r', encoding='utf-8') as f:
done_so_far = f.read().splitlines()
for d in done_so_far:
line = d.split(' | ')
done_list.append(line[0])
file_dict = { 'name' : line[0], 'size' : line[1], 'mtime' : line[2], 'ctime' : line[3], 'atime' : line[4], 'checksum' : line[5], 'counter' : line[6] }
file_stats.append(file_dict)
if len(file_stats) > 0:
counter = int(file_stats[-1]['counter'])
else:
counter = 0
print('\n')
#get total number of files
total = sum([len(files) for r, d, files in os.walk(target)])
#now loop through, keeping count
for root, dirnames, filenames in os.walk(target):
for file in filenames:
#check to make sure that we haven't already added info for this file
file_target = os.path.join(root, file)
if file_target in done_list:
continue
counter += 1
print('\r\tCalculating checksum for file {} out of {}'.format(counter, total), end='')
size = os.path.getsize(file_target)
ctime = datetime.datetime.fromtimestamp(os.path.getctime(file_target)).isoformat()
try:
mtime = datetime.datetime.fromtimestamp(os.path.getmtime(file_target)).isoformat()
except:
mtime = ctime
atime = datetime.datetime.fromtimestamp(os.path.getatime(file_target)).isoformat()[:-7]
checksum = self.md5(file_target)
file_dict = { 'name' : file_target, 'size' : size, 'mtime' : mtime, 'ctime' : ctime, 'atime' : atime, 'checksum' : checksum, 'counter' : counter }
file_stats.append(file_dict)
done_list.append(file_target)
#save this list to file just in case we crash...
raw_stats = "{} | {} | {} | {} | {} | {} | {}\n".format(file_target, size, mtime, ctime, atime, checksum, counter)
with open(self.temp_dfxml, 'a', encoding='utf8') as f:
f.write(raw_stats)
print('\n')
dc_namespace = 'http://purl.org/dc/elements/1.1/'
dc = "{%s}" % dc_namespace
NSMAP = {None : 'http://www.forensicswiki.org/wiki/Category:Digital_Forensics_XML',
'xsi': "http://www.w3.org/2001/XMLSchema-instance",
'dc' : dc_namespace}
dfxml = etree.Element("dfxml", nsmap=NSMAP, version="1.0")
metadata = etree.SubElement(dfxml, "metadata")
dctype = etree.SubElement(metadata, dc + "type")
dctype.text = "Hash List"
creator = etree.SubElement(dfxml, 'creator')
program = etree.SubElement(creator, 'program')
program.text = 'bdpl_ingest'
execution_environment = etree.SubElement(creator, 'execution_environment')
start_time = etree.SubElement(execution_environment, 'start_time')
start_time.text = timestamp
for f in file_stats:
fileobject = etree.SubElement(dfxml, 'fileobject')