forked from ambv/bitrot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbitrot.py
2122 lines (1931 loc) · 99.6 KB
/
bitrot.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/python3
# -*- coding: utf-8 -*-
# Copyright (C) 2013 by Lukasz Langa
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
from importlib.metadata import version, PackageNotFoundError
from multiprocessing import freeze_support
from inspect import getframeinfo, stack
#import traceprint #for debugging
import argparse
import atexit
import datetime
from datetime import timedelta
import errno
import hashlib
import os
from os import path
from sys import platform as _platform
import pathlib
import shutil
import sqlite3
import stat
import sys
import tempfile
import time
import progressbar
import smtplib
from fnmatch import fnmatch
#import email.utils
#from email.mime.text import MIMEText
#import binascii
#from zlib import crc32
import zlib
import re
import unicodedata
import gc
#####Pushbbullet
from pushbullet import Pushbullet
#####Pushover
import http.client, urllib
#####Healthchecks.io
###Using Python 3 standard library
#import socket
#import urllib.request
###Using the requests library:
import requests
################### USER CONFIG ###################
HEALTHCHECKSIOPINGURL = 'https://hc-ping.com/XXXXXXXXXXXXXXXXXXX'
PUSHOVERUSERKEY = 'XXXXXXXXXXXXXXXXXXX'
PUSHOVERAPPLICATIONTOKEN = 'XXXXXXXXXXXXXXXXXXX'
PUSHBULLETAPIKEY = 'XXXXXXXXXXXXXXXXXXX'
#RECEIVER = '[email protected]'
#SENDER = '[email protected]'
#PASSWORD = 'XXXXXXXXXXXXXXXXXXX'
#SERVER = smtplib.SMTP('smtp.gmail.com', 587)
DEFAULT_HASH_FUNCTION = "SHA512"
DEFAULT_CHUNK_SIZE = 1048576 # used to be 16384 - block size in HFS+; 4X the block size in ext4
DEFAULT_COMMIT_INTERVAL = 300
###################################################
DOT_THRESHOLD = 2
VERSION = (1, 0, 2)
IGNORED_FILE_SYSTEM_ERRORS = {errno.ENOENT, errno.EACCES, errno.EINVAL}
FSENCODING = sys.getfilesystemencoding()
SOURCE_DIR='.'
SOURCE_DIR_PATH = '.'
DESTINATION_DIR=SOURCE_DIR
HASHPROGRESSCOUNTER = 0
LENPATHS = 0
# if sys.version[0] == '2':
# str = type(u'text')
# # use \'bytes\' for bytestrings
try:
VERSION = version("bitrot")
except PackageNotFoundError:
VERSION = "1.0.2"
def sendNotification(MESSAGE="", SUBJECT="", log=True, notify=1, verbosity=1):
#Pushbullet
if (notify == 1 or 2 or 5 or 6):
try:
pb = Pushbullet(PUSHBULLETAPIKEY)
push = pb.push_note(SUBJECT, MESSAGE)
#printAndOrLog("Pushbullet subject: \'{}\' message: \'{}\' sent".format(SUBJECT,MESSAGE))
except Exception as err:
printAndOrLog("Pushbullet sending error: \'{}\'".format(err), log, notify, sys.stderr)
catchErrorAndWarning(message="Pushbullet sending error: \'{}\'".format(err), subject="Pushbullet Error", isFatal=True,log=log,notify=3,verbosity=verbosity)
#Pushover
if (notify == 1 or 3 or 5 or 7):
try:
conn = http.client.HTTPSConnection("api.pushover.net:443")
conn.request("POST", "/1/messages.json",
urllib.parse.urlencode({
"token": PUSHOVERAPPLICATIONTOKEN,
"user": PUSHOVERUSERKEY,
"message": MESSAGE,
}), { "Content-type": "application/x-www-form-urlencoded" })
conn.getresponse()
#printAndOrLog("Pushover message: \'{}\' sent".format(MESSAGE))
except Exception as err:
printAndOrLog("Pushover sending error: \'{}\'".format(err), log, notify, sys.stderr)
catchErrorAndWarning(message="Pushover sending error: \'{}\'".format(err), subject="Pushover Error", isFatal=True,log=log,notify=3,verbosity=verbosity)
# #Email
# #SERVER.connect()
# SERVER.ehlo()
# SERVER.starttls()
# SERVER.login(SENDER, PASSWORD)
# BODY = '\r\n'.join(['To: %s' % RECEIVER,
# 'From: %s' % SENDER,
# 'Subject: %s' % SUBJECT,
# '', MESSAGE])
# try:
# SERVER.sendmail(SENDER, [RECEIVER], BODY)
# printAndOrLog("Email '{}' sent from {} to {}".format(SUBJECT,SENDER,RECEIVER))
# except Exception as err:
# printAndOrLog('Email sending error: {}'.format(err), log, notify, sys.stderr)
# SERVER.quit(
def debuginfo(message = ""):
caller = getframeinfo(stack()[2][0]) #try setting the [2] to [1] for diffeent output
#print("%s:%d - %s" % (caller.filename, caller.lineno, message)) # python3 syntax print
#return ("%s:%d" % (caller.filename, caller.lineno)) # python3 syntax print
#caller = inspect.getframeinfo(inspect.stack()[1][0])
#print(f"{caller.filename}:{caller.function}:{caller.lineno} - {message}")
#return(f"{caller.filename}:{caller.function}:{caller.lineno} - {message}")
# print("%s:%d:%s" % (caller.filename, caller.function, caller.lineno, message)) # python3 syntax print
return ("\n%s:%s:%d %s" % (caller.filename, caller.function, caller.lineno, message)) # python3 syntax print
def normalize_path(path):
if FSENCODING == 'utf-8' or FSENCODING == 'UTF-8':
return unicodedata.normalize('NFKD', str(path))
else:
return path
def printAndOrLog(stringToProcess, log=True, notify=False, verbosity=1, stream=sys.stdout):
print(stringToProcess,file=stream)
if (log):
writeToLog('\n', log, notify, verbosity)
writeToLog(stringToProcess, log, notify, verbosity)
def writeToLog(stringToWrite="", log = True, notify=False, verbosity = 1):
log_path = get_absolute_path(log, notify, verbosity, SOURCE_DIR_PATH,ext=b'log')
stringToWrite = cleanString(stringToWrite)
try:
with open(log_path, 'a') as logFile:
logFile.write(stringToWrite)
logFile.close()
except Exception as err:
print("Couldn't open log: \'{}\'. Received error: {}".format(log_path, err))
def writeToSFV(stringToWrite="", sfv="",log=True, notify=1, verbosity=1):
if (sfv == "MD5"):
sfv_path = get_absolute_path(log, notify, verbosity, SOURCE_DIR_PATH, ext=b'md5')
elif (sfv == "SFV"):
sfv_path = get_absolute_path(log, notify, verbosity, SOURCE_DIR_PATH,ext=b'sfv')
try:
with open(sfv_path, 'a') as sfvFile:
sfvFile.write(stringToWrite)
sfvFile.close()
except Exception as err:
printAndOrLog("Couldn't open checksum file: \'{}\'. Received error: {}".format(sfv_path, err),log,notify,verbosity,sys.stderr)
def print_statusline(msg: str, offset = 0):
last_msg_length = len(print_statusline.last_msg) if hasattr(print_statusline, 'last_msg') else 0
print(' ' * (last_msg_length + offset), end='\r')
print(msg, end='\r')
sys.stdout.flush() # Some say they needed this, I didn't.
print_statusline.last_msg = msg
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
catchErrorAndWarning(message="Boolean value expected", isFatal=True, exception=argparse.ArgumentTypeError)
def has_hidden_attribute(filepath):
return bool(os.stat(filepath).st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN)
def integrityHash(path, chunk_size=DEFAULT_CHUNK_SIZE, algorithm=DEFAULT_HASH_FUNCTION, log=True, notify=1, verbosity=1):
if (algorithm == "MD5"):
if(os.stat(path).st_size) == 0:
return "d41d8cd98f00b204e9800998ecf8427e"
else:
digest=hashlib.md5()
elif (algorithm == "SHA1"):
if(os.stat(path).st_size) == 0:
return "da39a3ee5e6b4b0d3255bfef95601890afd80709"
else:
digest=hashlib.sha1()
elif (algorithm == "SHA224"):
if(os.stat(path).st_size) == 0:
return "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f"
else:
digest=hashlib.sha224()
elif (algorithm == "SHA384"):
if(os.stat(path).st_size) == 0:
return "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b"
else:
digest=hashlib.sha384()
elif (algorithm == "SHA256"):
if(os.stat(path).st_size) == 0:
return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
else:
digest=hashlib.sha256()
elif (algorithm == "SHA512"):
if(os.stat(path).st_size) == 0:
return "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"
else:
digest=hashlib.sha512()
else:
#You should never get here
catchErrorAndWarning(message="Invalid hash function detected.", isFatal=True, log=log, notify=notify,verbosity=verbosity)
try:
if os.path.exists(path):
with open(path, 'rb') as f:
d = f.read(chunk_size)
while d:
digest.update(d)
d = f.read(chunk_size)
f.close()
except Exception as err:
printAndOrLog("Couldn't open file: \'{}\'. Received error: {}".format(path, err),log,notify,verbosity,sys.stderr)
return digest.hexdigest()
def hash(path, bar, format_custom_text, chunk_size=DEFAULT_CHUNK_SIZE, algorithm=DEFAULT_HASH_FUNCTION, verbosity=1, log=True, notify=1, sfv=""):
# 0 byte files:
# md5 d41d8cd98f00b204e9800998ecf8427e
# LM aad3b435b51404eeaad3b435b51404ee
# NTLM 31d6cfe0d16ae931b73c59d7e0c089c0
# sha1 da39a3ee5e6b4b0d3255bfef95601890afd80709
# sha256 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
# sha384 38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b
# sha512 cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e
# md5(md5()) 74be16979710d4c4e7c6647856088456
# MySQL4.1+ be1bdec0aa74b4dcb079943e70528096cca985f8
# ripemd160 9c1185a5c5e9fc54612808977ee8f548b2258d31
# whirlpool 19fa61d75522a4669b44e39c1d2e1726c530232130d407f89afee0964997f7a73e83be698b288febcf88e3e03c4f0757ea8964e59b63d93708b138cc42a66eb3
# adler32 00000001
# crc32 00000000
# crc32b 00000000
# fnv1a32 811c9dc5
# fnv1a64 cbf29ce484222325
# fnv132 811c9dc5
# fnv164 cbf29ce484222325
# gost ce85b99cc46752fffee35cab9a7b0278abb4c2d2055cff685af4912c49490f8d
# gost-crypto 981e5f3ca30c841487830f84fb433e13ac1101569b9c13584ac483234cd656c0
# haval128,3 c68f39913f901f3ddf44c707357a7d70
# haval128,4 ee6bbf4d6a46a679b3a856c88538bb98
# haval128,5 184b8482a0c050dca54b59c7f05bf5dd
# haval160,3 d353c3ae22a25401d257643836d7231a9a95f953
# haval160,4 1d33aae1be4146dbaaca0b6e70d7a11f10801525
# haval160,5 255158cfc1eed1a7be7c55ddd64d9790415b933b
# haval192,3 e9c48d7903eaf2a91c5b350151efcb175c0fc82de2289a4e
# haval192,4 4a8372945afa55c7dead800311272523ca19d42ea47b72da
# haval192,5 4839d0626f95935e17ee2fc4509387bbe2cc46cb382ffe85
# haval224,3 c5aae9d47bffcaaf84a8c6e7ccacd60a0dd1932be7b1a192b9214b6d
# haval224,4 3e56243275b3b81561750550e36fcd676ad2f5dd9e15f2e89e6ed78e
# haval224,5 4a0513c032754f5582a758d35917ac9adf3854219b39e3ac77d1837e
# haval256,3 4f6938531f0bc8991f62da7bbd6f7de3fad44562b8c6f4ebf146d5b4e46f7c17
# haval256,4 c92b2e23091e80e375dadce26982482d197b1a2521be82da819f8ca2c579b99b
# haval256,5 be417bb4dd5cfb76c7126f4f8eeb1553a449039307b1a3cd451dbfdc0fbbe330
# joaat 00000000
# md2 8350e5a3e24c153df2275c9f80692773
# md4 31d6cfe0d16ae931b73c59d7e0c089c0
# ripemd128 cdf26213a150dc3ecb610f18f6b38b46
# ripemd256 02ba4c4e5f8ecd1877fc52d64d30e37a2d9774fb1e5d026380ae0168e3c5522d
# ripemd320 22d65d5661536cdc75c1fdf5c6de7b41b9f27325ebc61e8557177d705a0ec880151c3a32a00899b8
# sha224 d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f
# snefru 8617f366566a011837f4fb4ba5bedea2b892f3ed8b894023d16ae344b2be5881
# snefru256 8617f366566a011837f4fb4ba5bedea2b892f3ed8b894023d16ae344b2be5881
# tiger128,3 3293ac630c13f0245f92bbb1766e1616
# tiger128,4 24cc78a7f6ff3546e7984e59695ca13d
# tiger160,3 3293ac630c13f0245f92bbb1766e16167a4e5849
# tiger160,4 24cc78a7f6ff3546e7984e59695ca13d804e0b68
# tiger192,3 3293ac630c13f0245f92bbb1766e16167a4e58492dde73f3
# tiger192,4 24cc78a7f6ff3546e7984e59695ca13d804e0b686e255194
global HASHPROGRESSCOUNTER
if (algorithm == "MD5"):
if(os.stat(path).st_size) == 0:
return "d41d8cd98f00b204e9800998ecf8427e"
else:
digest=hashlib.md5()
elif (algorithm == "SHA1"):
if(os.stat(path).st_size) == 0:
return "da39a3ee5e6b4b0d3255bfef95601890afd80709"
else:
digest=hashlib.sha1()
elif (algorithm == "SHA224"):
if(os.stat(path).st_size) == 0:
return "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f"
else:
digest=hashlib.sha224()
elif (algorithm == "SHA384"):
if(os.stat(path).st_size) == 0:
return "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b"
else:
digest=hashlib.sha384()
elif (algorithm == "SHA256"):
if(os.stat(path).st_size) == 0:
return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
else:
digest=hashlib.sha256()
elif (algorithm == "SHA512"):
if(os.stat(path).st_size) == 0:
return "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"
else:
digest=hashlib.sha512()
else:
#You should never get here
catchErrorAndWarning(message="Invalid hash function detected.: \'{}\'".format(algorithm), isFatal=True, log=self.log,notify=self.notify,verbosity=self.verbosity)
try:
if os.path.exists(path):
with open(path, 'rb') as f:
d = f.read(chunk_size)
while d:
if (verbosity):
format_custom_text.update_mapping(f=progressFormat(path))
bar.update(HASHPROGRESSCOUNTER)
digest.update(d)
d = f.read(chunk_size)
f.close()
except Exception as err:
printAndOrLog("Couldn't open file: \'{}\'. Received error: \'{}\'".format(path, err),log,notify,verbosity,sys.stderr)
if (sfv != ""):
if (sfv == "MD5" and algorithm.upper() == "MD5"):
sfvDigest = digest.hexdigest()
writeToSFV(stringToWrite="{} {}\n".format(sfvDigest,"*"+normalize_path(path)),sfv=sfv,log=log,notify=notify,verbosity=verbosity)
elif (sfv == "MD5"):
sfvDigest = hashlib.md5()
try:
if os.path.exists(path):
with open(path, 'rb') as f2:
d2 = f2.read(chunk_size)
while d2:
sfvDigest.update(d2)
d2 = f2.read(chunk_size)
f2.close
except Exception as err:
printAndOrLog("Couldn't open file: \'{}\'. Received error: {}".format(path, err),log,notify,verbosity,sys.stderr)
writeToSFV(stringToWrite="{} {}\n".format(sfvDigest.hexdigest(),"*"+normalize_path(path)),sfv=sfv,log=log,notify=notify,verbosity=verbosity)
elif (sfv == "SFV"):
try:
if os.path.exists(path):
with open(path, 'rb') as f2:
d2 = f2.read(chunk_size)
crcvalue = 0
while d2:
#zlib is faster
#import timeit
#print("b:", timeit.timeit("binascii.crc32(data)", setup="import binascii, zlib; data=b'X'*4096", number=100000))
#print("z:", timeit.timeit("zlib.crc32(data)", setup="import binascii, zlib; data=b'X'*4096", number=100000))
#Result:
#b: 1.0176826480001182
#z: 0.4006126120002591
crcvalue = (zlib.crc32(d2, crcvalue) & 0xFFFFFFFF)
#crcvalue = (binascii.crc32(d2,crcvalue) & 0xFFFFFFFF)
d2 = f2.read(chunk_size)
f2.close()
except Exception as err:
printAndOrLog("Couldn't open SFV file: \'{}\'. Received error: {}".format(path, err),log,notify,verbosity,sys.stderr)
writeToSFV(stringToWrite="{} {}\n".format(path, "%08X" % crcvalue),sfv=sfv,log=log,notify=notify,verbosity=verbosity)
return digest.hexdigest()
def is_int(val):
if type(val) == int:
return True
else:
if val.is_integer():
return True
else:
return False
def isValidHashingFunction(stringToValidate=""):
hashFunctions = ["SHA1", "SHA224", "SHA384", "SHA256", "SHA512", "MD5"]
if stringToValidate in hashFunctions:
return True
else:
return False
# if (stringToValidate.upper() == "SHA1"
# or stringToValidate.upper() == "SHA224"
# or stringToValidate.upper() == "SHA384"
# or stringToValidate.upper() == "SHA256"
# or stringToValidate.upper() == "SHA512"
# or stringToValidate.upper() == "MD5"):
# return True
# else:
# return False
def calculateUnits(total_size = 0):
units = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
size = 0
# Divides total size until it is less than 1024
while total_size >= 1024:
total_size = total_size/1024
size = size + 1 # Size is used as the index for Units
sizeUnits = units[size]
# if (total_size/1024/1024/1024/1024/1024/1024/1024/1024 >= 1):
# sizeUnits = "YB"
# total_size = total_size/1024/1024/1024/1024/1024/1024/1024/1024
# elif (total_size/1024/1024/1024/1024/1024/1024/1024 >= 1):
# sizeUnits = "ZB"
# total_size = total_size/1024/1024/1024/1024/1024/1024/1024
# elif (total_size/1024/1024/1024/1024/1024/1024 >= 1):
# sizeUnits = "EB"
# total_size = total_size/1024/1024/1024/1024/1024/1024
# elif (total_size/1024/1024/1024/1024/1024 >= 1):
# sizeUnits = "PB"
# total_size = total_size/1024/1024/1024/1024/1024
# elif (total_size/1024/1024/1024/1024 >= 1):
# sizeUnits = "TB"
# total_size = total_size/1024/1024/1024/1024
# elif (total_size/1024/1024/1024 >= 1):
# sizeUnits = "GB"
# total_size = total_size/1024/1024/1024
# elif (total_size/1024/1024 >= 1):
# sizeUnits = "MB"
# total_size = total_size/1024/1024
# elif (total_size/1024 >= 1):
# sizeUnits = "KB"
# total_size = total_size/1024
# else:
# sizeUnits = "B"
# total_size = total_size
return sizeUnits, total_size
def cleanString(stringToClean=""):
#stringToClean=re.sub(r'[\\/*?:"<>|]',"",stringToClean)
stringToClean = ''.join([x for x in stringToClean if ord(x) < 128])
return stringToClean
def isDirtyString(stringToCheck=""):
comparisonString = stringToCheck
cleanedString = cleanString(stringToCheck)
if (cleanedString == comparisonString):
return False
else:
return True
def progressFormat(current_path):
terminal_size = shutil.get_terminal_size()
cols = terminal_size.columns
max_path_size = int(shutil.get_terminal_size().columns/2)
if len(current_path) > max_path_size:
# show first half and last half, separated by ellipsis
# e.g. averylongpathnameaveryl...ameaverylongpathname
half_mps = (max_path_size - 3) // 2
current_path = current_path[:half_mps] + '...' + current_path[-half_mps:]
else:
# pad out with spaces, otherwise previous filenames won't be erased
current_path += ' ' * (max_path_size - len(current_path))
current_path = current_path + '|'
return current_path
def ts():
return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S%z')
def get_sqlite3_cursor(path, copy=False, log=True, notify=1, verbosity=1):
if (copy):
if not os.path.exists(path):
catchErrorAndWarning(message="Bitrot database at \'{}\' does not exist.".format(path), isFatal=True, log=log,notify=notify,verbosity=verbosity)
db_copy = tempfile.NamedTemporaryFile(prefix='bitrot_', suffix='.db',
delete=False)
try:
if os.path.exists(path):
with open(path, 'rb') as db_orig:
try:
shutil.copyfileobj(db_orig, db_copy)
finally:
db_copy.close()
db_orig.close()
# except IOError as e:
# if e.errno == errno.EACCES:
except Exception as e:
catchErrorAndWarning(message="Couldn't open database file: \'{}\'. Received error: \'{}\'".format(path, e), isFatal=True, log=log,notify=notify,verbosity=verbosity)
path = db_copy.name
atexit.register(os.unlink, path)
try:
conn = sqlite3.connect(path)
except Exception as err:
catchErrorAndWarning(message="Couldn't connect to database: \'{}\'. Received error: \'{}\'".format(path, err), isFatal=True,log=self.log,notify=self.notify,verbosity=self.verbosity)
atexit.register(conn.close)
cur = conn.cursor()
tables = set(t for t, in cur.execute('SELECT name FROM sqlite_master'))
if 'bitrot' not in tables:
cur.execute('CREATE TABLE bitrot (path TEXT PRIMARY KEY, '
'mtime INTEGER, hash TEXT, timestamp TEXT)')
if 'bitrot_hash_idx' not in tables:
cur.execute('CREATE INDEX bitrot_hash_idx ON bitrot (hash)')
atexit.register(conn.commit)
return conn
def fix_existing_paths(directory=SOURCE_DIR, verbosity = 1, log=True, notify=1, test = 0, fix=5, warnings = (), fixedRenameList = (), fixedRenameCounter = 0):
# Use os.getcwd() instead of "." since it doesn't seem to be resolved the way you want. This will be illustrated in the diagnostics function.
# Use relative path renaming by os.chdir(root). Of course using correct absolute paths also works, but IMHO relative paths are just more elegant.
# Pass an unambiguous string into os.walk() as others have mentioned.
# Also note that topdown=False in os.walk() doesn't matter. Since you are not renaming directories, the directory structure will be invariant during os.walk().
progressCounter=0
if verbosity:
print("Scanning file and directory names to fix... Please wait...")
bar = progressbar.ProgressBar(max_value=progressbar.UnknownLength)
start = time.time()
for root, dirs, files in os.walk(directory, topdown=False):
for file in files:
if (isDirtyString(file)):
if (fix == 2) or (fix == 3):
warnings.append(file)
catchErrorAndWarning(message="Invalid character detected in filename \'{}\'".format(os.path.join(root, file)), isFatal=False,log=log,notify=0,verbosity=verbosity)
if (not test):
try:
# chdir before renaming
#os.chdir(root)
#fullfilename=os.path.abspath(file)
#os.rename(f, cleanString(file)) # relative path, more elegant
pathBackup = file
if (fix == 2) or (fix == 3):
os.rename(os.path.join(root, f), os.path.join(root, cleanString(file)))
path = cleanString(file)
except Exception as ex:
warnings.append(file)
catchErrorAndWarning(message="Can\'t rename: \'{}\' due to: \'{}\'".format(os.path.join(root, f),ex), isFatal=False,log=log,notify=0,verbosity=verbosity)
continue
else:
fixedRenameList.append([])
fixedRenameList.append([])
fixedRenameList[fixedRenameCounter].append(os.path.join(root, pathBackup))
fixedRenameList[fixedRenameCounter].append(os.path.join(root, path))
fixedRenameCounter += 1
if verbosity:
progressCounter+=1
# statusString = "Files:" + str(progressCounter) + " Elapsed:" + recordTimeElapsed(start) + " " + progressFormat(path)
# print_statusline(statusString,15)
bar.update(progressCounter)
for directory in dirs:
if (isDirtyString(directory)):
if (not test):
try:
# chdir before renaming
#os.chdir(root)
#fullfilename=os.path.abspath(d)
pathBackup = directory
if (fix == 2) or (fix == 3):
os.rename(os.path.join(root, directory), os.path.join(root, cleanString(d)))
#os.rename(d, cleanString(d)) # relative path, more elegant
cleanedDirctory = cleanString(directory)
except Exception as ex:
warnings.append(d)
catchErrorAndWarning(message="Can\'t rename: {} due to: \'{}\'".format(os.path.join(root, directory),ex), isFatal=False,log=log,notify=0,verbosity=verbosity)
continue
else:
fixedRenameList.append([])
fixedRenameList.append([])
fixedRenameList[fixedRenameCounter].append(os.path.join(root, pathBackup))
fixedRenameList[fixedRenameCounter].append(os.path.join(root, cleanedDirctory))
fixedRenameCounter += 1
if verbosity:
progressCounter+=1
bar.update(progressCounter)
if verbosity:
print()
bar.finish()
return fixedRenameList, fixedRenameCounter
def list_existing_paths(directory=SOURCE_DIR, expected=(), excluded=(), included=(),
verbosity=1, follow_links=False, log=True, notify=1, hidden=True, fix=0, warnings = ()): #normalize=False,
"""list_existing_paths(b'/dir') -> ([path1, path2, ...], total_size)
Returns a tuple with a set of existing files in 'directory' and its subdirectories
and their 'total_size'. If directory was a bytes object, so will be the returned
paths.
Doesn't add entries listed in 'excluded'. Doesn't add symlinks if
'follow_links' is False (the default). All entries present in 'expected'
must be files (can't be directories or symlinks).
"""
# excluded = [get_relative_path(pathIterator) for pathIterator in excluded]
# excluded = [pathIterator.decode(FSENCODING) for pathIterator in excluded]
paths = set()
total_size = 0
excludedList = []
progressCounter=0
if verbosity:
print("Mapping all files... Please wait...")
start = time.time()
format_custom_text = progressbar.FormatCustomText(
'%(f)s',
dict(
f='',
)
)
bar = progressbar.ProgressBar(max_value=progressbar.UnknownLength)
for pathIterator, _, files in os.walk("."):
for f in files:
path = os.path.join(pathIterator, f)
path = normalize_path(path)
try:
if os.path.islink(path):
if follow_links:
st = os.stat(path)
else:
st = os.lstat(path)
else:
st = os.lstat(path)
except OSError as ex:
if ex.errno not in IGNORED_FILE_SYSTEM_ERRORS:
catchErrorAndWarning(message="Unhandled file system error: \'{}\'".format(ex.errno), isFatal=True,log=self.log,notify=self.notify,verbosity=self.verbosity)
else:
# split path /dir1/dir2/file.txt into
# ['dir1', 'dir2', 'file.txt']
# and match on any of these components
# so we could use 'dir*', '*2', '*.txt', etc. to exclude anything
try:
exclude_this = [fnmatch(file, wildcard)
for file in pathIterator.split(os.path.sep)
for wildcard in excluded]
except UnicodeEncodeError:
catchErrorAndWarning(message="Couldn't encode file name: \'{}\'".format(path), isFatal=False,log=log,notify=0,verbosity=verbosity)
continue
try:
include_this = [fnmatch(file, wildcard)
for file in pathIterator.split(os.path.sep)
for wildcard in included]
except UnicodeEncodeError:
atchErrorAndWarning(message="Couldn't encode file name: \'{}\'".format(path), isFatal=False,log=log,notify=0,verbosity=verbosity)
continue
if (not stat.S_ISREG(st.st_mode) and not os.path.islink(path)) or any(exclude_this) or any([fnmatch(path, exc) for exc in excluded]) or (included and not any([fnmatch(path, inc) for inc in included]) and not any(include_this)):
#if not stat.S_ISREG(st.st_mode) or any([fnmatch(path, exc) for exc in excluded]):
excludedList.append(path)
elif (not hidden and has_hidden_attribute(path)):
excludedList.append(path)
else:
# if (normalize):
# oldMatch = ""
# for filePath in paths:
# if normalize_path(path) == normalize_path(filePath):
# oldMatch = filePath
# break
# if oldMatch != "":
# oldFile = os.stat(oldMatch)
# new_mtime = int(st.st_mtime)
# old_mtime = int(oldFile.st_mtime)
# new_atime = int(st.st_atime)
# old_atime = int(oldFile.st_atime)
# now_date = datetime.datetime.now()
# if not new_mtime or not new_atime:
# nowTime = time.mktime(now_date.timetuple())
# if not old_mtime or not old_atime:
# nowTime = time.mktime(now_date.timetuple())
# if not new_mtime and not new_atime:
# new_mtime = int(nowTime)
# new_atime = int(nowTime)
# elif not (new_mtime):
# new_mtime = int(nowTime)
# elif not (new_atime):
# new_atime = int(nowTime)
# if not old_mtime and not old_atime:
# old_mtime = int(nowTime)
# old_atime = int(nowTime)
# elif not (old_mtime):
# old_mtime = int(nowTime)
# elif not (old_atime):
# old_atime = int(nowTime)
# new_mtime_date = datetime.datetime.fromtimestamp(new_mtime)
# new_atime_date = datetime.datetime.fromtimestamp(new_atime)
# old_mtime_date = datetime.datetime.fromtimestamp(old_mtime)
# old_atime_date = datetime.datetime.fromtimestamp(old_atime)
# delta_new_mtime_date = now_date - new_mtime_date
# delta_new_atime_date = now_date - new_atime_date
# delta_old_mtime_date = now_date - old_mtime_date
# delta_old_atime_date = now_date - old_atime_date
# if delta_new_mtime_date < delta_old_mtime_date:
# paths.add(path)
# paths.discard(filePath)
# total_size += st.st_size
# elif delta_new_atime_date < delta_old_atime_date:
# paths.add(path)
# paths.discard(filePath)
# total_size += st.st_size
# else:
# pass
# else:
# paths.add(path)
# total_size += st.st_size
# else:
paths.add(path)
total_size += st.st_size
if verbosity:
progressCounter+=1
# statusString = "Files:" + str(progressCounter) + " Elapsed:" + recordTimeElapsed(start) + " " + progressFormat(path)
# print_statusline(statusString,15)
bar.update(progressCounter)
if verbosity:
bar.finish()
print()
return paths, total_size, excludedList
def compute_one(path, bar, format_custom_text, chunk_size, algorithm="", follow_links=False, verbosity = 1, log=True, notify=1, sfv=""):
"""Return a tuple with (unicode path, size, mtime, sha1). Takes a binary path."""
global HASHPROGRESSCOUNTER
if (verbosity):
HASHPROGRESSCOUNTER+=1
try:
if os.path.islink(path):
if not os.path.exists(path):
catchErrorAndWarning(message="Symlink broken \'{}\'->\'{}\'".format(path, os.path.realpath(path)), isFatal=True,log=log,notify=notify,verbosity=verbosity)
if follow_links:
st = os.stat(path)
else:
st = os.lstat(path)
else:
st = os.lstat(path)
except OSError as ex:
if ex.errno in IGNORED_FILE_SYSTEM_ERRORS:
# The file disappeared between listing existing paths and
# this run or is (temporarily?) locked with different
# permissions. We'll just skip it for now.
catchErrorAndWarning(message="\'{}\' is currently unavailable for reading: \'{}\'".format(path, ex), isFatal=True,log=log,notify=notify,verbosity=verbosity)
catchErrorAndWarning(message="Unexpected file system error: \'{}\'".format(ex.errno), isFatal=True,log=log,notify=notify,verbosity=verbosity)
# Not expected? https://github.com/ambv/bitrot/issues/
try:
new_hash = hash(path, bar, format_custom_text, chunk_size, algorithm, verbosity, log, notify, sfv)
except (IOError, OSError) as e:
catchErrorAndWarning(message="Can't compute hash of \'{}\': \'{}\'".format(path, errno.errorcode[e.args[0]]), isFatal=True,log=log,notify=notify,verbosity=verbosity)
return path, st.st_size, int(st.st_mtime), int(st.st_atime), new_hash
class CustomETA(progressbar.widgets.ETA):
def __call__(self, progress, data):
# Run 'ETA.__call__' to update 'data'. This adds the 'eta_seconds'
data_plus_one = data.copy()
if (HASHPROGRESSCOUNTER == 1):
data_plus_one['value'] += 1
data_plus_one['percentage'] = ((HASHPROGRESSCOUNTER )/ LENPATHS * 100.0)
formatted = progressbar.widgets.ETA.__call__(self, progress, data_plus_one)
# ETA might not be available, if the maximum length is not available
# for example
if data.get('eta'):
# By using divmod we can split the timedelta to hours and the
# remaining timedelta
hours, delta = divmod(
timedelta(seconds=int(data['eta_seconds'])),
timedelta(hours=1),
)
data['eta'] = ' {hours}{delta_truncated}'.format(
hours=hours,
# Strip the 0 hours from the timedelta
delta_truncated=str(delta).lstrip('0'),
)
return progressbar.widgets.Timer.__call__(self, progress, data, format=self.format)
else:
return formatted
class BitrotException(Exception):
pass
def catchErrorAndWarning(message="", subject="Bitrot Error", log=True, notify=1, verbosity=1, exception=BitrotException, exceptionNumber="", isFatal=True, stream=sys.stderr):
message += debuginfo()
if (notify == 1) or (notify == 2):
sendNotification(MESSAGE=message, SUBJECT=subject, log=log,notify=notify,verbosity=verbosity)
if (isFatal):
if (verbosity):
printAndOrLog("Error: "+ message,log,notify,stream)
if (notify == 1 or 4 or 6 or 7):
try:
requests.get(HEALTHCHECKSIOPINGURL + "/fail")
except requests.exceptions.RequestException:
# If the network request fails for any reason, we don't want
# it to prevent the main job from running
pass
if (exceptionNumber):
raise exception(exceptionNumber)
else:
raise exception("Error: "+ message)
else:
if (verbosity):
printAndOrLog("Warning: "+ message,log,notify,stream)
class Bitrot(object):
def __init__(
self, verbosity=1, notify = 1, log = True, hidden = True, test = 0, recent = 0, follow_links = True, commit_interval=300,
chunk_size=DEFAULT_CHUNK_SIZE, workers=os.cpu_count(), include_list=[], exclude_list=[], algorithm="", sfv="MD5", fix=0):#, normalize=False
self.verbosity = verbosity
self.test = test
self.recent = recent
self.follow_links = follow_links
self.commit_interval = commit_interval
self.chunk_size = chunk_size
self.include_list = include_list
self.exclude_list = exclude_list
self._last_reported_size = ''
self._last_commit_ts = 0
#ProcessPoolExecutor runs each of your workers in its own separate child process. (CPU Bound)
#ThreadPoolExecutor runs each of your workers in separate threads within the main process. (IO Bound)
self.workers = workers
if (workers != 1):
self.pool = ThreadPoolExecutor(max_workers=workers)
self.notify = notify
self.log = log
self.hidden = hidden
self.startTime = time.time()
self.algorithm = algorithm
self.sfv = sfv
self.fix = fix
#self.normalize=normalize
def maybe_commit(self, conn):
if time.time() < self._last_commit_ts + self.commit_interval:
# no time for commit yet!
return
conn.commit()
self._last_commit_ts = time.time()
def run(self):
log=self.log
notify=self.notify
verbosity=self.verbosity
chunk_size=self.chunk_size
test=self.test
check_sha512_integrity(chunk_size=self.chunk_size, verbosity=self.verbosity, log=self.log, notify=self.notify)
bitrot_sha512 = get_relative_path(self.log,self.notify, get_absolute_path(self.log,self.notify,self.verbosity, SOURCE_DIR_PATH,ext=b'sha512'))
bitrot_log = get_relative_path(self.log,self.notify, get_absolute_path(self.log,self.notify,self.verbosity, SOURCE_DIR_PATH,ext=b'log'))
bitrot_db = get_relative_path(self.log,self.notify, get_absolute_path(self.log,self.notify,self.verbosity, SOURCE_DIR_PATH,b'db'))
bitrot_sfv = get_relative_path(self.log,self.notify, get_absolute_path(self.log,self.notify,self.verbosity, SOURCE_DIR_PATH,ext=b'sfv'))
bitrot_md5 = get_relative_path(self.log,self.notify, get_absolute_path(self.log,self.notify,self.verbosity,SOURCE_DIR_PATH,ext=b'md5'))
#bitrot_db = os.path.basename(get_absolute_path())
#bitrot_sha512 = os.path.basename(get_absolute_path(ext=b'sha512'))
#bitrot_log = os.path.basename(get_absolute_path(ext=b'log'))
if (not os.path.exists(bitrot_db) and self.test != 0):
catchErrorAndWarning(message="No database exists so cannot test. Run the tool once first.", isFatal=True,log=self.log,notify=self.notify,verbosity=self.verbosity)
try:
conn = get_sqlite3_cursor(bitrot_db, copy=self.test, log=self.log, verbosity=self.verbosity)
except ValueError:
catchErrorAndWarning(message="No database exists so cannot test. Run the tool once first.", isFatal=True,log=self.log,notify=self.notify,verbosity=self.verbosity)
except Exception as ex:
catchErrorAndWarning(message="Could not connect to the database. Received error: \'{}\'".format(ex), isFatal=True,log=self.log,notify=self.notify,verbosity=self.verbosity)
cur = conn.cursor()
futures = []
new_paths = []
missing_paths = []
existing_paths = []
updated_paths = []
renamed_paths = []
errors = []
notifications = []
tooOldList = []
temporary_paths = []
warnings = []
fixedRenameList = []
fixedRenameCounter = 0
fixedPropertiesList = []
fixedPropertiesCounter = 0
current_size = 0
global HASHPROGRESSCOUNTER
global LENPATHS
missing_paths = self.select_all_paths(cur, log, notify, verbosity)
hashes = self.select_all_hashes(cur, log, notify, verbosity)
if (SOURCE_DIR != DESTINATION_DIR):
os.chdir(DESTINATION_DIR)
if (self.fix >= 1):
fixedRenameList, fixedRenameCounter = fix_existing_paths(
#os.getcwd(),# pass an unambiguous string instead of: b'.'
SOURCE_DIR,
verbosity=self.verbosity,
log=self.log,
notify=self.notify,
test=self.test,
fix=self.fix,
warnings=warnings,
fixedRenameList = fixedRenameList,
fixedRenameCounter = fixedRenameCounter
)
paths, total_size, excludedList = list_existing_paths(
SOURCE_DIR,
expected=missing_paths,
excluded=[bitrot_db, bitrot_sha512, bitrot_log, bitrot_sfv, bitrot_md5 ] + self.exclude_list,
included=self.include_list,
follow_links=self.follow_links,
verbosity=self.verbosity,
log=self.log,
notify=self.notify,
hidden=self.hidden,
fix=self.fix,
#normalize=self.normalize,
warnings=warnings,
)
FIMErrorCounter = 0;
paths = sorted(paths)
LENPATHS = len(paths)
#These are missing entries that have recently been excluded
for pathIterator in missing_paths:
if (pathIterator in excludedList):
temporary_paths.append(pathIterator)
for pathIterator in temporary_paths:
missing_paths.discard(pathIterator)
if (self.test == 0):
cur.execute('DELETE FROM bitrot WHERE path=?', (pathIterator,))
if temporary_paths:
del temporary_paths
if self.verbosity:
print("Hashing all files... Please wait...")
format_custom_text = progressbar.FormatCustomText('%(f)s',dict(f='',))
bar = progressbar.ProgressBar(max_value=LENPATHS,widgets=[format_custom_text,
CustomETA(format_not_started='%(value)01d/%(max_value)d|%(percentage)3d%%|Elapsed:%(elapsed)8s|ETA:%(eta)8s', format_finished='%(value)01d/%(max_value)d|%(percentage)3d%%|Elapsed:%(elapsed)8s', format='%(value)01d/%(max_value)d|%(percentage)3d%%|Elapsed:%(elapsed)8s|ETA:%(eta)8s', format_zero='%(value)01d/%(max_value)d|%(percentage)3d%%|Elapsed:%(elapsed)8s', format_NA='%(value)01d/%(max_value)d|%(percentage)3d%%|Elapsed:%(elapsed)8s'),
progressbar.Bar(marker='#', left='|', right='|', fill=' ', fill_left=True),
])
if (self.workers == 1):
pointer = paths
if paths:
del paths
else:
futures = [self.pool.submit(compute_one, pathIterator, bar, format_custom_text, self.chunk_size, self.algorithm, self.follow_links, self.verbosity, self.log, self.sfv) for pathIterator in paths]
pointer = as_completed(futures)
if futures:
del futures
gc.collect()
for future in pointer:
if (self.workers == 1):
path = future
try:
st = os.stat(path)
except OSError as ex:
if ex.errno in IGNORED_FILE_SYSTEM_ERRORS: