forked from fancycode/pylzma
-
Notifications
You must be signed in to change notification settings - Fork 0
/
py7zlib.py
1076 lines (915 loc) · 39.1 KB
/
py7zlib.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/python -u
#
# Python Bindings for LZMA
#
# Copyright (c) 2004-2015 by Joachim Bauch, [email protected]
# 7-Zip Copyright (C) 1999-2010 Igor Pavlov
# LZMA SDK Copyright (C) 1999-2010 Igor Pavlov
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# $Id$
#
"""Read 7zip format archives."""
from array import array
from binascii import unhexlify
from datetime import datetime
import pylzma
from struct import pack, unpack
from zlib import crc32
import zlib
import bz2
import os
import sys
try:
from io import BytesIO
except ImportError:
from cStringIO import StringIO as BytesIO
try:
from functools import reduce
except ImportError:
# reduce is available in functools starting with Python 2.6
pass
try:
from pytz import UTC
except ImportError:
# pytz is optional, define own "UTC" timestamp
# reference implementation from Python documentation
from datetime import timedelta, tzinfo
ZERO = timedelta(0)
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
def _call__(self):
return self
UTC = UTC()
try:
unicode
except NameError:
# Python 3.x
def unicode(s, encoding):
return s
else:
def bytes(s, encoding):
return s
try:
long
except NameError:
# Python 3.x
long = int
try:
xrange
except NameError:
# Python 3.x
xrange = range
IS_PYTHON3 = sys.version_info[0] == 3
NEED_BYTESWAP = sys.byteorder != 'little'
if array('L').itemsize == 4:
ARRAY_TYPE_UINT32 = 'L'
else:
assert array('I').itemsize == 4
ARRAY_TYPE_UINT32 = 'I'
READ_BLOCKSIZE = 16384
MAGIC_7Z = unhexlify('377abcaf271c') # '7z\xbc\xaf\x27\x1c'
PROPERTY_END = unhexlify('00') # '\x00'
PROPERTY_HEADER = unhexlify('01') # '\x01'
PROPERTY_ARCHIVE_PROPERTIES = unhexlify('02') # '\x02'
PROPERTY_ADDITIONAL_STREAMS_INFO = unhexlify('03') # '\x03'
PROPERTY_MAIN_STREAMS_INFO = unhexlify('04') # '\x04'
PROPERTY_FILES_INFO = unhexlify('05') # '\x05'
PROPERTY_PACK_INFO = unhexlify('06') # '\x06'
PROPERTY_UNPACK_INFO = unhexlify('07') # '\x07'
PROPERTY_SUBSTREAMS_INFO = unhexlify('08') # '\x08'
PROPERTY_SIZE = unhexlify('09') # '\x09'
PROPERTY_CRC = unhexlify('0a') # '\x0a'
PROPERTY_FOLDER = unhexlify('0b') # '\x0b'
PROPERTY_CODERS_UNPACK_SIZE = unhexlify('0c') # '\x0c'
PROPERTY_NUM_UNPACK_STREAM = unhexlify('0d') # '\x0d'
PROPERTY_EMPTY_STREAM = unhexlify('0e') # '\x0e'
PROPERTY_EMPTY_FILE = unhexlify('0f') # '\x0f'
PROPERTY_ANTI = unhexlify('10') # '\x10'
PROPERTY_NAME = unhexlify('11') # '\x11'
PROPERTY_CREATION_TIME = unhexlify('12') # '\x12'
PROPERTY_LAST_ACCESS_TIME = unhexlify('13') # '\x13'
PROPERTY_LAST_WRITE_TIME = unhexlify('14') # '\x14'
PROPERTY_ATTRIBUTES = unhexlify('15') # '\x15'
PROPERTY_COMMENT = unhexlify('16') # '\x16'
PROPERTY_ENCODED_HEADER = unhexlify('17') # '\x17'
PROPERTY_START_POS = unhexlify('18') # '\x18'
PROPERTY_DUMMY = unhexlify('19') # '\x19'
COMPRESSION_METHOD_COPY = unhexlify('00') # '\x00'
COMPRESSION_METHOD_DELTA = unhexlify('03') # '\x03'
COMPRESSION_METHOD_LZMA = unhexlify('030101') # '\x03\x01\x01'
COMPRESSION_METHOD_CRYPTO = unhexlify('06') # '\x06'
COMPRESSION_METHOD_MISC = unhexlify('04') # '\x04'
COMPRESSION_METHOD_MISC_ZIP = unhexlify('0401') # '\x04\x01'
COMPRESSION_METHOD_MISC_BZIP = unhexlify('0402') # '\x04\x02'
COMPRESSION_METHOD_7Z_AES256_SHA256 = unhexlify('06f10701') # '\x06\xf1\x07\x01'
COMPRESSION_METHOD_LZMA2 = unhexlify('21') # '\x21'
COMPRESSION_METHOD_BCJ = unhexlify('03030103') # '\x03\x03\x01\x03'
COMPRESSION_METHOD_BCJ_PPC = unhexlify('03030205') # '\x03\x03\x02\x05'
COMPRESSION_METHOD_BCJ_IA64 = unhexlify('03030401') # '\x03\x03\x03\x01'
COMPRESSION_METHOD_BCJ_ARM = unhexlify('03030501') # '\x03\x03\x05\x01'
COMPRESSION_METHOD_BCJ_ARMT = unhexlify('03030701') # '\x03\x03\x07\x01'
COMPRESSION_METHOD_BCJ_SPARC = unhexlify('03030805') # '\x03\x03\x08\x05'
COMPRESSION_METHOD_BCJ2 = unhexlify('0303011B') # '\x03\x03\x01\x1B'
COMPRESSION_METHOD_PPMD = unhexlify('030401') # '\x03\x03\x01'
FILE_ATTRIBUTE_DIRECTORY = 0x10
FILE_ATTRIBUTE_READONLY = 0x01
FILE_ATTRIBUTE_HIDDEN = 0x02
FILE_ATTRIBUTE_SYSTEM = 0x04
FILE_ATTRIBUTE_ARCHIVE = 0x20
# number of seconds between 1601/01/01 and 1970/01/01 (UTC)
# used to adjust 7z FILETIME to Python timestamp
TIMESTAMP_ADJUST = -11644473600
def toTimestamp(filetime):
"""Convert 7z FILETIME to Python timestamp."""
# FILETIME is 100-nanosecond intervals since 1601/01/01 (UTC)
return (filetime / 10000000.0) + TIMESTAMP_ADJUST
def calculate_crc32(data, value=None, blocksize=1024*1024):
"""Calculate CRC32 of strings with arbitrary lengths."""
length = len(data)
pos = blocksize
if value:
value = crc32(data[:pos], value)
else:
value = crc32(data[:pos])
while pos < length:
value = crc32(data[pos:pos+blocksize], value)
pos += blocksize
return value & 0xffffffff
class ArchiveError(Exception):
pass
class FormatError(ArchiveError):
pass
class EncryptedArchiveError(ArchiveError):
pass
class UnsupportedCompressionMethodError(ArchiveError):
pass
class DecryptionError(ArchiveError):
pass
class NoPasswordGivenError(DecryptionError):
pass
class WrongPasswordError(DecryptionError):
pass
class DecompressionError(ArchiveError):
pass
class ArchiveTimestamp(long):
"""Windows FILETIME timestamp."""
def __repr__(self):
return '%s(%d)' % (type(self).__name__, self)
def as_datetime(self):
"""Convert FILETIME to Python datetime object."""
return datetime.fromtimestamp(toTimestamp(self), UTC)
class Base(object):
""" base class with support for various basic read/write functions """
def _readReal64Bit(self, file):
res = file.read(8)
a, b = unpack('<LL', res)
return b << 32 | a, res
def _read64Bit(self, file):
b = ord(file.read(1))
mask = 0x80
for i in xrange(8):
if b & mask == 0:
bytes = array('B', file.read(i))
bytes.reverse()
value = (bytes and reduce(lambda x, y: x << 8 | y, bytes)) or 0
highpart = b & (mask - 1)
return value + (highpart << (i * 8))
mask >>= 1
def _readBoolean(self, file, count, checkall=0):
if checkall:
alldefined = file.read(1)
if alldefined != unhexlify('00'):
return [True] * count
result = []
b = 0
mask = 0
for i in xrange(count):
if mask == 0:
b = ord(file.read(1))
mask = 0x80
result.append(b & mask != 0)
mask >>= 1
return result
def checkcrc(self, crc, data):
check = calculate_crc32(data)
return crc == check
class PackInfo(Base):
""" informations about packed streams """
def __init__(self, file):
self.packpos = self._read64Bit(file)
self.numstreams = self._read64Bit(file)
id = file.read(1)
if id == PROPERTY_SIZE:
self.packsizes = [self._read64Bit(file) for x in xrange(self.numstreams)]
id = file.read(1)
if id == PROPERTY_CRC:
self.crcs = [self._read64Bit(file) for x in xrange(self.numstreams)]
id = file.read(1)
if id != PROPERTY_END:
raise FormatError('end id expected but %s found' % repr(id))
class Folder(Base):
""" a "Folder" represents a stream of compressed data """
solid = False
def __init__(self, file):
numcoders = self._read64Bit(file)
self.coders = []
self.digestdefined = False
totalin = 0
self.totalout = 0
for i in xrange(numcoders):
while True:
b = ord(file.read(1))
methodsize = b & 0xf
issimple = b & 0x10 == 0
noattributes = b & 0x20 == 0
last_alternative = b & 0x80 == 0
c = {}
c['method'] = file.read(methodsize)
if not issimple:
c['numinstreams'] = self._read64Bit(file)
c['numoutstreams'] = self._read64Bit(file)
else:
c['numinstreams'] = 1
c['numoutstreams'] = 1
totalin += c['numinstreams']
self.totalout += c['numoutstreams']
if not noattributes:
c['properties'] = file.read(self._read64Bit(file))
self.coders.append(c)
if last_alternative:
break
numbindpairs = self.totalout - 1
self.bindpairs = []
for i in xrange(numbindpairs):
self.bindpairs.append((self._read64Bit(file), self._read64Bit(file), ))
numpackedstreams = totalin - numbindpairs
self.packed_indexes = []
if numpackedstreams == 1:
for i in xrange(totalin):
if self.findInBindPair(i) < 0:
self.packed_indexes.append(i)
elif numpackedstreams > 1:
for i in xrange(numpackedstreams):
self.packed_indexes.append(self._read64Bit(file))
def getUnpackSize(self):
if not self.unpacksizes:
return 0
for i in xrange(len(self.unpacksizes)-1, -1, -1):
if self.findOutBindPair(i):
return self.unpacksizes[i]
raise TypeError('not found')
def findInBindPair(self, index):
for idx, (a, b) in enumerate(self.bindpairs):
if a == index:
return idx
return -1
def findOutBindPair(self, index):
for idx, (a, b) in enumerate(self.bindpairs):
if b == index:
return idx
return -1
def isEncrypted(self):
return COMPRESSION_METHOD_7Z_AES256_SHA256 in [x['method'] for x in self.coders]
class Digests(Base):
""" holds a list of checksums """
def __init__(self, file, count):
self.defined = self._readBoolean(file, count, checkall=1)
self.crcs = array(ARRAY_TYPE_UINT32, file.read(4*count))
if NEED_BYTESWAP:
self.crcs.byteswap()
UnpackDigests = Digests
class UnpackInfo(Base):
""" combines multiple folders """
def __init__(self, file):
id = file.read(1)
if id != PROPERTY_FOLDER:
raise FormatError('folder id expected but %s found' % repr(id))
self.numfolders = self._read64Bit(file)
self.folders = []
external = file.read(1)
if external == unhexlify('00'):
self.folders = [Folder(file) for x in xrange(self.numfolders)]
elif external == unhexlify('01'):
self.datastreamidx = self._read64Bit(file)
else:
raise FormatError('0x00 or 0x01 expected but %s found' % repr(external))
id = file.read(1)
if id != PROPERTY_CODERS_UNPACK_SIZE:
raise FormatError('coders unpack size id expected but %s found' % repr(id))
for folder in self.folders:
folder.unpacksizes = [self._read64Bit(file) for x in xrange(folder.totalout)]
id = file.read(1)
if id == PROPERTY_CRC:
digests = UnpackDigests(file, self.numfolders)
for idx, folder in enumerate(self.folders):
folder.digestdefined = digests.defined[idx]
folder.crc = digests.crcs[idx]
id = file.read(1)
if id != PROPERTY_END:
raise FormatError('end id expected but %s found' % repr(id))
class SubstreamsInfo(Base):
""" defines the substreams of a folder """
def __init__(self, file, numfolders, folders):
self.digests = []
self.digestsdefined = []
id = file.read(1)
if id == PROPERTY_NUM_UNPACK_STREAM:
self.numunpackstreams = [self._read64Bit(file) for x in xrange(numfolders)]
id = file.read(1)
else:
self.numunpackstreams = [1]*numfolders
if id == PROPERTY_SIZE:
self.unpacksizes = []
for i in xrange(len(self.numunpackstreams)):
sum = 0
for j in xrange(1, self.numunpackstreams[i]):
size = self._read64Bit(file)
self.unpacksizes.append(size)
sum += size
self.unpacksizes.append(folders[i].getUnpackSize() - sum)
id = file.read(1)
numdigests = 0
numdigeststotal = 0
for i in xrange(numfolders):
numsubstreams = self.numunpackstreams[i]
if numsubstreams != 1 or not folders[i].digestdefined:
numdigests += numsubstreams
numdigeststotal += numsubstreams
if id == PROPERTY_CRC:
digests = Digests(file, numdigests)
didx = 0
for i in xrange(numfolders):
folder = folders[i]
numsubstreams = self.numunpackstreams[i]
if numsubstreams == 1 and folder.digestdefined:
self.digestsdefined.append(True)
self.digests.append(folder.crc)
else:
for j in xrange(numsubstreams):
self.digestsdefined.append(digests.defined[didx])
self.digests.append(digests.crcs[didx])
didx += 1
id = file.read(1)
if id != PROPERTY_END:
raise FormatError('end id expected but %r found' % id)
if not self.digestsdefined:
self.digestsdefined = [False] * numdigeststotal
self.digests = [0] * numdigeststotal
class StreamsInfo(Base):
""" informations about compressed streams """
def __init__(self, file):
id = file.read(1)
if id == PROPERTY_PACK_INFO:
self.packinfo = PackInfo(file)
id = file.read(1)
if id == PROPERTY_UNPACK_INFO:
self.unpackinfo = UnpackInfo(file)
id = file.read(1)
if id == PROPERTY_SUBSTREAMS_INFO:
self.substreamsinfo = SubstreamsInfo(file, self.unpackinfo.numfolders, self.unpackinfo.folders)
id = file.read(1)
if id != PROPERTY_END:
raise FormatError('end id expected but %s found' % repr(id))
class FilesInfo(Base):
""" holds file properties """
def _readTimes(self, file, files, name):
defined = self._readBoolean(file, len(files), checkall=1)
# NOTE: the "external" flag is currently ignored, should be 0x00
external = file.read(1)
for i in xrange(len(files)):
if defined[i]:
files[i][name] = ArchiveTimestamp(self._readReal64Bit(file)[0])
else:
files[i][name] = None
def __init__(self, file):
self.numfiles = self._read64Bit(file)
self.files = [{'emptystream': False} for x in xrange(self.numfiles)]
numemptystreams = 0
while True:
typ = self._read64Bit(file)
if typ > 255:
raise FormatError('invalid type, must be below 256, is %d' % typ)
typ = pack('B', typ)
if typ == PROPERTY_END:
break
size = self._read64Bit(file)
if typ == PROPERTY_DUMMY:
# Added by newer versions of 7z to adjust padding.
file.seek(size, os.SEEK_CUR)
continue
buffer = BytesIO(file.read(size))
if typ == PROPERTY_EMPTY_STREAM:
isempty = self._readBoolean(buffer, self.numfiles)
list(map(lambda x, y: x.update({'emptystream': y}), self.files, isempty))
for x in isempty:
if x: numemptystreams += 1
emptyfiles = [False] * numemptystreams
antifiles = [False] * numemptystreams
elif typ == PROPERTY_EMPTY_FILE:
emptyfiles = self._readBoolean(buffer, numemptystreams)
elif typ == PROPERTY_ANTI:
antifiles = self._readBoolean(buffer, numemptystreams)
elif typ == PROPERTY_NAME:
external = buffer.read(1)
if external != unhexlify('00'):
self.dataindex = self._read64Bit(buffer)
# XXX: evaluate external
raise NotImplementedError
for f in self.files:
name = ''
while True:
ch = buffer.read(2)
if ch == unhexlify('0000'):
f['filename'] = name
break
name += ch.decode('utf-16')
elif typ == PROPERTY_CREATION_TIME:
self._readTimes(buffer, self.files, 'creationtime')
elif typ == PROPERTY_LAST_ACCESS_TIME:
self._readTimes(buffer, self.files, 'lastaccesstime')
elif typ == PROPERTY_LAST_WRITE_TIME:
self._readTimes(buffer, self.files, 'lastwritetime')
elif typ == PROPERTY_ATTRIBUTES:
defined = self._readBoolean(buffer, self.numfiles, checkall=1)
external = buffer.read(1)
if external != unhexlify('00'):
self.dataindex = self._read64Bit(buffer)
# XXX: evaluate external
raise NotImplementedError
for idx, f in enumerate(self.files):
if defined[idx]:
f['attributes'] = unpack('<L', buffer.read(4))[0]
else:
f['attributes'] = None
else:
raise FormatError('invalid type %r' % (typ))
class Header(Base):
""" the archive header """
def __init__(self, file):
id = file.read(1)
if id == PROPERTY_ARCHIVE_PROPERTIES:
self.properties = ArchiveProperties(file)
id = file.read(1)
if id == PROPERTY_ADDITIONAL_STREAMS_INFO:
self.additional_streams = StreamsInfo(file)
id = file.read(1)
if id == PROPERTY_MAIN_STREAMS_INFO:
self.main_streams = StreamsInfo(file)
id = file.read(1)
if id == PROPERTY_FILES_INFO:
self.files = FilesInfo(file)
id = file.read(1)
if id != PROPERTY_END:
raise FormatError('end id expected but %s found' % (repr(id)))
class ArchiveFile(Base):
""" wrapper around a file in the archive """
def __init__(self, info, start, src_start, folder, archive, maxsize=None):
self.digest = None
self._archive = archive
self._file = archive._file
self._start = start
self._src_start = src_start
self._folder = folder
# maxsize is only valid for solid archives
self._maxsize = maxsize
for k, v in info.items():
setattr(self, k, v)
self.size = self.uncompressed = self._uncompressed[-1]
if not hasattr(self, 'filename'):
# compressed file is stored without a name, generate one
try:
basefilename = self._file.name
except AttributeError:
# 7z archive file doesn't have a name
self.filename = 'contents'
else:
self.filename = os.path.splitext(os.path.basename(basefilename))[0]
self.reset()
self._decoders = {
COMPRESSION_METHOD_COPY: '_read_copy',
COMPRESSION_METHOD_DELTA: '_read_delta',
COMPRESSION_METHOD_LZMA: '_read_lzma',
COMPRESSION_METHOD_LZMA2: '_read_lzma2',
COMPRESSION_METHOD_MISC_ZIP: '_read_zip',
COMPRESSION_METHOD_MISC_BZIP: '_read_bzip',
COMPRESSION_METHOD_7Z_AES256_SHA256: '_read_7z_aes256_sha256',
COMPRESSION_METHOD_BCJ: '_read_bcj',
COMPRESSION_METHOD_BCJ_PPC: '_read_bcj_ppc',
COMPRESSION_METHOD_BCJ_IA64: '_read_bcj_ia64',
COMPRESSION_METHOD_BCJ_ARM: '_read_bcj_arm',
COMPRESSION_METHOD_BCJ_ARMT: '_read_bcj_armt',
COMPRESSION_METHOD_BCJ_SPARC: '_read_bcj_sparc',
COMPRESSION_METHOD_BCJ2: '_read_bcj2',
COMPRESSION_METHOD_PPMD: '_read_ppmd',
}
def _is_encrypted(self):
return self._folder.isEncrypted()
def reset(self):
self.pos = 0
def read(self):
if not self.size:
return ''
elif not self._folder.coders:
raise TypeError("file has no coder informations")
data = None
num_coders = len(self._folder.coders)
for level, coder in enumerate(self._folder.coders):
method = coder['method']
decoder = None
while method and decoder is None:
decoder = self._decoders.get(method, None)
method = method[:-1]
if decoder is None:
raise UnsupportedCompressionMethodError(repr(coder['method']))
data = getattr(self, decoder)(coder, data, level, num_coders)
return data
def _read_copy(self, coder, input, level, num_coders):
size = self._uncompressed[level]
if not input:
self._file.seek(self._src_start)
input = self._file.read(size)
return input[self._start:self._start+size]
def _read_delta(self, coder, input, level, num_coders):
size = self._uncompressed[level]
if not input:
self._file.seek(self._src_start)
input = self._file.read(size)
assert len(coder['properties']) == 1
delta = ord(coder['properties']) + 1
data = pylzma.delta_decode(input, delta)
return data[self._start:self._start+size]
def _read_from_decompressor(self, coder, decompressor, input, level, num_coders, can_partial_decompress=True, with_cache=False):
size = self._uncompressed[level]
data = ''
idx = 0
cnt = 0
properties = coder.get('properties', None)
if properties:
decompressor.decompress(properties)
total = self.compressed
is_last_coder = (level + 1) == num_coders
if not input and is_last_coder:
remaining = self._start+size
out = BytesIO()
cache = getattr(self._folder, '_decompress_cache', None)
if cache is not None:
data, pos, decompressor = cache
out.write(data)
remaining -= len(data)
self._file.seek(pos)
else:
self._file.seek(self._src_start)
checkremaining = is_last_coder and not self._folder.solid and can_partial_decompress
while remaining > 0:
data = self._file.read(READ_BLOCKSIZE)
if checkremaining or (with_cache and len(data) < READ_BLOCKSIZE):
tmp = decompressor.decompress(data, remaining)
else:
tmp = decompressor.decompress(data)
if not tmp and not data:
raise DecompressionError('end of stream while decompressing')
out.write(tmp)
remaining -= len(tmp)
data = out.getvalue()
if with_cache and self._folder.solid:
# don't decompress start of solid archive for next file
# TODO: limit size of cached data
self._folder._decompress_cache = (data, self._file.tell(), decompressor)
else:
if not input:
self._file.seek(self._src_start)
input = self._file.read(total)
if is_last_coder and can_partial_decompress:
data = decompressor.decompress(input, self._start+size)
elif can_partial_decompress:
total_decompressed = sum(self._uncompressed[level:])
data = decompressor.decompress(input, self._start+total_decompressed)
if not is_last_coder:
return data
else:
data = decompressor.decompress(input)
if can_partial_decompress and not is_last_coder:
return data
return data[self._start:self._start+size]
def _read_lzma(self, coder, input, level, num_coders):
size = self._uncompressed[level]
is_last_coder = (level + 1) == num_coders
if is_last_coder and not self._folder.solid:
dec = pylzma.decompressobj(maxlength=self._start+size)
else:
dec = pylzma.decompressobj()
try:
return self._read_from_decompressor(coder, dec, input, level, num_coders, with_cache=True)
except ValueError:
if self._is_encrypted():
raise WrongPasswordError('invalid password')
raise
def _read_lzma2(self, coder, input, level, num_coders):
size = self._uncompressed[level]
is_last_coder = (level + 1) == num_coders
if is_last_coder and not self._folder.solid:
dec = pylzma.decompressobj(maxlength=self._start+size, lzma2=True)
else:
dec = pylzma.decompressobj(lzma2=True)
try:
return self._read_from_decompressor(coder, dec, input, level, num_coders, with_cache=True)
except ValueError:
if self._is_encrypted():
raise WrongPasswordError('invalid password')
raise
def _read_zip(self, coder, input, level, num_coders):
dec = zlib.decompressobj(-15)
return self._read_from_decompressor(coder, dec, input, level, num_coders)
def _read_bzip(self, coder, input, level, num_coders):
dec = bz2.BZ2Decompressor()
return self._read_from_decompressor(coder, dec, input, level, num_coders, can_partial_decompress=False)
def _read_7z_aes256_sha256(self, coder, input, level, num_coders):
if not self._archive.password:
raise NoPasswordGivenError()
# TODO: this needs some sanity checks
firstbyte = coder['properties'][0]
if not IS_PYTHON3:
firstbyte = ord(firstbyte)
numcyclespower = firstbyte & 0x3f
if firstbyte & 0xc0 != 0:
saltsize = (firstbyte >> 7) & 1
ivsize = (firstbyte >> 6) & 1
secondbyte = coder['properties'][1]
if not IS_PYTHON3:
secondbyte = ord(secondbyte)
saltsize += (secondbyte >> 4)
ivsize += (secondbyte & 0x0f)
assert len(coder['properties']) == 2+saltsize+ivsize
salt = coder['properties'][2:2+saltsize]
iv = coder['properties'][2+saltsize:2+saltsize+ivsize]
assert len(salt) == saltsize
assert len(iv) == ivsize
assert numcyclespower <= 24
if ivsize < 16:
iv += bytes('\x00'*(16-ivsize), 'ascii')
else:
salt = iv = bytes('', 'ascii')
password = self._archive.password.encode('utf-16-le')
key = pylzma.calculate_key(password, numcyclespower, salt=salt)
cipher = pylzma.AESDecrypt(key, iv=iv)
if not input:
self._file.seek(self._src_start)
input = self._file.read(self.compressed)
result = cipher.decrypt(input)
return result
def _read_bcj2(self, coder, input, level, num_coders):
size = self._uncompressed[level]
if not input:
self._file.seek(self._src_start)
input = self._file.read(size)
if len(self._packsizes) != 4:
raise DecompressionError('BCJ2 expects 4 streams, got %d' % (len(self._packsizes)))
main_data = input[self._start:self._start+size]
call_data = self._file.read(self._packsizes[1])
jump_data = self._file.read(self._packsizes[2])
rc_data = self._file.read(self._packsizes[3])
return pylzma.bcj2_decode(main_data, call_data, jump_data, rc_data, self.uncompressed)
def _read_bcj(self, coder, input, level, num_coders):
size = self._uncompressed[level]
if not input:
self._file.seek(self._src_start)
input = self._file.read(size)
data = pylzma.bcj_x86_convert(input)
return data[self._start:self._start+size]
def _read_bcj_ppc(self, coder, input, level, num_coders):
size = self._uncompressed[level]
if not input:
self._file.seek(self._src_start)
input = self._file.read(size)
data = pylzma.bcj_ppc_convert(input)
return data[self._start:self._start+size]
def _read_bcj_ia64(self, coder, input, level, num_coders):
size = self._uncompressed[level]
if not input:
self._file.seek(self._src_start)
input = self._file.read(size)
data = pylzma.bcj_ia64_convert(input)
return data[self._start:self._start+size]
def _read_bcj_arm(self, coder, input, level, num_coders):
size = self._uncompressed[level]
if not input:
self._file.seek(self._src_start)
input = self._file.read(size)
data = pylzma.bcj_arm_convert(input)
return data[self._start:self._start+size]
def _read_bcj_armt(self, coder, input, level, num_coders):
size = self._uncompressed[level]
if not input:
self._file.seek(self._src_start)
input = self._file.read(size)
data = pylzma.bcj_armt_convert(input)
return data[self._start:self._start+size]
def _read_bcj_sparc(self, coder, input, level, num_coders):
size = self._uncompressed[level]
if not input:
self._file.seek(self._src_start)
input = self._file.read(size)
data = pylzma.bcj_sparc_convert(input)
return data[self._start:self._start+size]
def _read_ppmd(self, coder, input, level, num_coders):
size = self._uncompressed[level]
if not input:
self._file.seek(self._src_start)
input = self._file.read(self.compressed)
total_out = sum(self._unpacksizes)
data = pylzma.ppmd_decompress(input, coder['properties'], total_out)
return data[self._start:self._start+size]
def checkcrc(self):
if self.digest is None:
return True
self.reset()
data = self.read()
return super(ArchiveFile, self).checkcrc(self.digest, data)
class Archive7z(Base):
""" the archive itself """
def __init__(self, file, password=None):
self._file = file
self.password = password
self.header = file.read(len(MAGIC_7Z))
if self.header != MAGIC_7Z:
raise FormatError('not a 7z file')
self.version = unpack('BB', file.read(2))
self.startheadercrc = unpack('<L', file.read(4))[0]
self.nextheaderofs, data = self._readReal64Bit(file)
crc = calculate_crc32(data)
self.nextheadersize, data = self._readReal64Bit(file)
crc = calculate_crc32(data, crc)
data = file.read(4)
self.nextheadercrc = unpack('<L', data)[0]
crc = calculate_crc32(data, crc)
if crc != self.startheadercrc:
raise FormatError('invalid header data')
self.afterheader = file.tell()
file.seek(self.nextheaderofs, 1)
buffer = BytesIO(file.read(self.nextheadersize))
if not self.checkcrc(self.nextheadercrc, buffer.getvalue()):
raise FormatError('invalid header data')
while True:
id = buffer.read(1)
if not id or id == PROPERTY_HEADER:
break
if id != PROPERTY_ENCODED_HEADER:
raise TypeError('Unknown field: %r' % (id))
streams = StreamsInfo(buffer)
file.seek(self.afterheader + 0)
data = bytes('', 'ascii')
src_start = self.afterheader
for folder in streams.unpackinfo.folders:
if folder.isEncrypted() and not password:
raise NoPasswordGivenError()
src_start += streams.packinfo.packpos
uncompressed = folder.unpacksizes
if not isinstance(uncompressed, (list, tuple)):
uncompressed = [uncompressed] * len(folder.coders)
info = {
'compressed': streams.packinfo.packsizes[0],
'_uncompressed': uncompressed,
}
tmp = ArchiveFile(info, 0, src_start, folder, self)
uncompressed_size = uncompressed[-1]
folderdata = tmp.read()[:uncompressed_size]
src_start += uncompressed_size
if folder.digestdefined:
if not self.checkcrc(folder.crc, folderdata):
raise FormatError('invalid block data')
data += folderdata
buffer = BytesIO(data)
self.files = []
self.files_map = {}
if not id:
# empty archive
self.solid = False
self.numfiles = 0
self.filenames = []
return
self.header = Header(buffer)
files = self.header.files
if hasattr(self.header, 'main_streams'):
folders = self.header.main_streams.unpackinfo.folders
packinfo = self.header.main_streams.packinfo
subinfo = self.header.main_streams.substreamsinfo
packsizes = packinfo.packsizes
self.solid = packinfo.numstreams == 1
if hasattr(subinfo, 'unpacksizes'):
unpacksizes = subinfo.unpacksizes
else:
unpacksizes = [x.unpacksizes for x in folders]
else:
# TODO(fancycode): is it necessary to provide empty values for folder, packinfo, etc?
self.solid = False
fidx = 0
obidx = 0
streamidx = 0
src_pos = self.afterheader
pos = 0
folder_pos = src_pos
maxsize = (self.solid and packinfo.packsizes[0]) or None
instreamindex = 0
for info in files.files:
# Skip all directory entries.
attributes = info.get('attributes', None)
if attributes and attributes & FILE_ATTRIBUTE_DIRECTORY != 0:
continue
if not info['emptystream']:
folder = folders[fidx]
if streamidx == 0:
folder.solid = subinfo.numunpackstreams[fidx] > 1
maxsize = (folder.solid and packinfo.packsizes[instreamindex]) or None
uncompressed = unpacksizes[obidx]
if not isinstance(uncompressed, (list, tuple)):
uncompressed = [uncompressed] * len(folder.coders)
if pos > 0:
# file is part of solid archive
assert instreamindex < len(packsizes), 'Folder outside index for solid archive'
info['compressed'] = packsizes[instreamindex]