-
Notifications
You must be signed in to change notification settings - Fork 55
/
rarfile.py
3543 lines (2892 loc) · 103 KB
/
rarfile.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
# rarfile.py
#
# Copyright (c) 2005-2024 Marko Kreen <markokr@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""RAR archive reader.
This is Python module for Rar archive reading. The interface
is made as :mod:`zipfile`-like as possible.
Basic logic:
- Parse archive structure with Python.
- Extract non-compressed files with Python
- Extract compressed files with unrar.
- Optionally write compressed data to temp file to speed up unrar,
otherwise it needs to scan whole archive on each execution.
Example::
import rarfile
rf = rarfile.RarFile("myarchive.rar")
for f in rf.infolist():
print(f.filename, f.file_size)
if f.filename == "README":
print(rf.read(f))
Archive files can also be accessed via file-like object returned
by :meth:`RarFile.open`::
import rarfile
with rarfile.RarFile("archive.rar") as rf:
with rf.open("README") as f:
for ln in f:
print(ln.strip())
For decompression to work, either ``unrar`` or ``unar`` tool must be in PATH.
"""
import errno
import io
import os
import re
import shutil
import struct
import sys
import warnings
from binascii import crc32, hexlify
from datetime import datetime, timezone
from hashlib import blake2s, pbkdf2_hmac, sha1, sha256
from pathlib import Path
from struct import Struct, pack, unpack
from subprocess import DEVNULL, PIPE, STDOUT, Popen
from tempfile import mkstemp
AES = None
# only needed for encrypted headers
try:
try:
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import (
Cipher, algorithms, modes,
)
_have_crypto = 1
except ImportError:
from Crypto.Cipher import AES
_have_crypto = 2
except ImportError:
_have_crypto = 0
class AES_CBC_Decrypt:
"""Decrypt API"""
def __init__(self, key, iv):
if _have_crypto == 2:
self.decrypt = AES.new(key, AES.MODE_CBC, iv).decrypt
else:
ciph = Cipher(algorithms.AES(key), modes.CBC(iv), default_backend())
self.decrypt = ciph.decryptor().update
__version__ = "4.2"
# export only interesting items
__all__ = ["get_rar_version", "is_rarfile", "is_rarfile_sfx", "RarInfo", "RarFile", "RarExtFile"]
##
## Module configuration. Can be tuned after importing.
##
#: executable for unrar tool
UNRAR_TOOL = "unrar"
#: executable for unar tool
UNAR_TOOL = "unar"
#: executable for bsdtar tool
BSDTAR_TOOL = "bsdtar"
#: executable for p7zip/7z tool
SEVENZIP_TOOL = "7z"
#: executable for alternative 7z tool
SEVENZIP2_TOOL = "7zz"
#: default fallback charset
DEFAULT_CHARSET = "windows-1252"
#: list of encodings to try, with fallback to DEFAULT_CHARSET if none succeed
TRY_ENCODINGS = ("utf8", "utf-16le")
#: whether to speed up decompression by using tmp archive
USE_EXTRACT_HACK = 1
#: limit the filesize for tmp archive usage
HACK_SIZE_LIMIT = 20 * 1024 * 1024
#: set specific directory for mkstemp() used by hack dir usage
HACK_TMP_DIR = None
#: Separator for path name components. Always "/".
PATH_SEP = "/"
##
## rar constants
##
# block types
RAR_BLOCK_MARK = 0x72 # r
RAR_BLOCK_MAIN = 0x73 # s
RAR_BLOCK_FILE = 0x74 # t
RAR_BLOCK_OLD_COMMENT = 0x75 # u
RAR_BLOCK_OLD_EXTRA = 0x76 # v
RAR_BLOCK_OLD_SUB = 0x77 # w
RAR_BLOCK_OLD_RECOVERY = 0x78 # x
RAR_BLOCK_OLD_AUTH = 0x79 # y
RAR_BLOCK_SUB = 0x7a # z
RAR_BLOCK_ENDARC = 0x7b # {
# flags for RAR_BLOCK_MAIN
RAR_MAIN_VOLUME = 0x0001
RAR_MAIN_COMMENT = 0x0002
RAR_MAIN_LOCK = 0x0004
RAR_MAIN_SOLID = 0x0008
RAR_MAIN_NEWNUMBERING = 0x0010
RAR_MAIN_AUTH = 0x0020
RAR_MAIN_RECOVERY = 0x0040
RAR_MAIN_PASSWORD = 0x0080
RAR_MAIN_FIRSTVOLUME = 0x0100
RAR_MAIN_ENCRYPTVER = 0x0200
# flags for RAR_BLOCK_FILE
RAR_FILE_SPLIT_BEFORE = 0x0001
RAR_FILE_SPLIT_AFTER = 0x0002
RAR_FILE_PASSWORD = 0x0004
RAR_FILE_COMMENT = 0x0008
RAR_FILE_SOLID = 0x0010
RAR_FILE_DICTMASK = 0x00e0
RAR_FILE_DICT64 = 0x0000
RAR_FILE_DICT128 = 0x0020
RAR_FILE_DICT256 = 0x0040
RAR_FILE_DICT512 = 0x0060
RAR_FILE_DICT1024 = 0x0080
RAR_FILE_DICT2048 = 0x00a0
RAR_FILE_DICT4096 = 0x00c0
RAR_FILE_DIRECTORY = 0x00e0
RAR_FILE_LARGE = 0x0100
RAR_FILE_UNICODE = 0x0200
RAR_FILE_SALT = 0x0400
RAR_FILE_VERSION = 0x0800
RAR_FILE_EXTTIME = 0x1000
RAR_FILE_EXTFLAGS = 0x2000
# flags for RAR_BLOCK_ENDARC
RAR_ENDARC_NEXT_VOLUME = 0x0001
RAR_ENDARC_DATACRC = 0x0002
RAR_ENDARC_REVSPACE = 0x0004
RAR_ENDARC_VOLNR = 0x0008
# flags common to all blocks
RAR_SKIP_IF_UNKNOWN = 0x4000
RAR_LONG_BLOCK = 0x8000
# Host OS types
RAR_OS_MSDOS = 0 #: MSDOS (only in RAR3)
RAR_OS_OS2 = 1 #: OS2 (only in RAR3)
RAR_OS_WIN32 = 2 #: Windows
RAR_OS_UNIX = 3 #: UNIX
RAR_OS_MACOS = 4 #: MacOS (only in RAR3)
RAR_OS_BEOS = 5 #: BeOS (only in RAR3)
# Compression methods - "0".."5"
RAR_M0 = 0x30 #: No compression.
RAR_M1 = 0x31 #: Compression level `-m1` - Fastest compression.
RAR_M2 = 0x32 #: Compression level `-m2`.
RAR_M3 = 0x33 #: Compression level `-m3`.
RAR_M4 = 0x34 #: Compression level `-m4`.
RAR_M5 = 0x35 #: Compression level `-m5` - Maximum compression.
RAR_MAX_PASSWORD = 127 #: Max number of utf-16 chars in passwords.
RAR_MAX_KDF_SHIFT = 24 #: Max power-of-2 for KDF count
#
# RAR5 constants
#
RAR5_BLOCK_MAIN = 1
RAR5_BLOCK_FILE = 2
RAR5_BLOCK_SERVICE = 3
RAR5_BLOCK_ENCRYPTION = 4
RAR5_BLOCK_ENDARC = 5
RAR5_BLOCK_FLAG_EXTRA_DATA = 0x01
RAR5_BLOCK_FLAG_DATA_AREA = 0x02
RAR5_BLOCK_FLAG_SKIP_IF_UNKNOWN = 0x04
RAR5_BLOCK_FLAG_SPLIT_BEFORE = 0x08
RAR5_BLOCK_FLAG_SPLIT_AFTER = 0x10
RAR5_BLOCK_FLAG_DEPENDS_PREV = 0x20
RAR5_BLOCK_FLAG_KEEP_WITH_PARENT = 0x40
RAR5_MAIN_FLAG_ISVOL = 0x01
RAR5_MAIN_FLAG_HAS_VOLNR = 0x02
RAR5_MAIN_FLAG_SOLID = 0x04
RAR5_MAIN_FLAG_RECOVERY = 0x08
RAR5_MAIN_FLAG_LOCKED = 0x10
RAR5_FILE_FLAG_ISDIR = 0x01
RAR5_FILE_FLAG_HAS_MTIME = 0x02
RAR5_FILE_FLAG_HAS_CRC32 = 0x04
RAR5_FILE_FLAG_UNKNOWN_SIZE = 0x08
RAR5_COMPR_SOLID = 0x40
RAR5_ENC_FLAG_HAS_CHECKVAL = 0x01
RAR5_ENDARC_FLAG_NEXT_VOL = 0x01
RAR5_XFILE_ENCRYPTION = 1
RAR5_XFILE_HASH = 2
RAR5_XFILE_TIME = 3
RAR5_XFILE_VERSION = 4
RAR5_XFILE_REDIR = 5
RAR5_XFILE_OWNER = 6
RAR5_XFILE_SERVICE = 7
RAR5_XTIME_UNIXTIME = 0x01
RAR5_XTIME_HAS_MTIME = 0x02
RAR5_XTIME_HAS_CTIME = 0x04
RAR5_XTIME_HAS_ATIME = 0x08
RAR5_XTIME_UNIXTIME_NS = 0x10
RAR5_XENC_CIPHER_AES256 = 0
RAR5_XENC_CHECKVAL = 0x01
RAR5_XENC_TWEAKED = 0x02
RAR5_XHASH_BLAKE2SP = 0
RAR5_XREDIR_UNIX_SYMLINK = 1
RAR5_XREDIR_WINDOWS_SYMLINK = 2
RAR5_XREDIR_WINDOWS_JUNCTION = 3
RAR5_XREDIR_HARD_LINK = 4
RAR5_XREDIR_FILE_COPY = 5
RAR5_XREDIR_ISDIR = 0x01
RAR5_XOWNER_UNAME = 0x01
RAR5_XOWNER_GNAME = 0x02
RAR5_XOWNER_UID = 0x04
RAR5_XOWNER_GID = 0x08
RAR5_OS_WINDOWS = 0
RAR5_OS_UNIX = 1
DOS_MODE_ARCHIVE = 0x20
DOS_MODE_DIR = 0x10
DOS_MODE_SYSTEM = 0x04
DOS_MODE_HIDDEN = 0x02
DOS_MODE_READONLY = 0x01
RAR5_PW_CHECK_SIZE = 8
RAR5_PW_SUM_SIZE = 4
##
## internal constants
##
RAR_ID = b"Rar!\x1a\x07\x00"
RAR5_ID = b"Rar!\x1a\x07\x01\x00"
WIN32 = sys.platform == "win32"
BSIZE = 512 * 1024 if WIN32 else 64 * 1024
SFX_MAX_SIZE = 2 * 1024 * 1024
RAR_V3 = 3
RAR_V5 = 5
_BAD_CHARS = r"""\x00-\x1F<>|"?*"""
RC_BAD_CHARS_UNIX = re.compile(r"[%s]" % _BAD_CHARS)
RC_BAD_CHARS_WIN32 = re.compile(r"[%s:^\\]" % _BAD_CHARS)
FORCE_TOOL = False
def _find_sfx_header(xfile):
sig = RAR_ID[:-1]
buf = io.BytesIO()
steps = (64, SFX_MAX_SIZE)
with XFile(xfile) as fd:
for step in steps:
data = fd.read(step)
if not data:
break
buf.write(data)
curdata = buf.getvalue()
findpos = 0
while True:
pos = curdata.find(sig, findpos)
if pos < 0:
break
if curdata[pos:pos + len(RAR_ID)] == RAR_ID:
return RAR_V3, pos
if curdata[pos:pos + len(RAR5_ID)] == RAR5_ID:
return RAR_V5, pos
findpos = pos + len(sig)
return 0, 0
##
## Public interface
##
def get_rar_version(xfile):
"""Check quickly whether file is rar archive.
"""
with XFile(xfile) as fd:
buf = fd.read(len(RAR5_ID))
if buf.startswith(RAR_ID):
return RAR_V3
elif buf.startswith(RAR5_ID):
return RAR_V5
return 0
def is_rarfile(xfile):
"""Check quickly whether file is rar archive.
"""
try:
return get_rar_version(xfile) > 0
except OSError:
# File not found or not accessible, ignore
return False
def is_rarfile_sfx(xfile):
"""Check whether file is rar archive with support for SFX.
It will read 2M from file.
"""
return _find_sfx_header(xfile)[0] > 0
class Error(Exception):
"""Base class for rarfile errors."""
class BadRarFile(Error):
"""Incorrect data in archive."""
class NotRarFile(Error):
"""The file is not RAR archive."""
class BadRarName(Error):
"""Cannot guess multipart name components."""
class NoRarEntry(Error):
"""File not found in RAR"""
class PasswordRequired(Error):
"""File requires password"""
class NeedFirstVolume(Error):
"""Need to start from first volume.
Attributes:
current_volume
Volume number of current file or None if not known
"""
def __init__(self, msg, volume):
super().__init__(msg)
self.current_volume = volume
class NoCrypto(Error):
"""Cannot parse encrypted headers - no crypto available."""
class RarExecError(Error):
"""Problem reported by unrar/rar."""
class RarWarning(RarExecError):
"""Non-fatal error"""
class RarFatalError(RarExecError):
"""Fatal error"""
class RarCRCError(RarExecError):
"""CRC error during unpacking"""
class RarLockedArchiveError(RarExecError):
"""Must not modify locked archive"""
class RarWriteError(RarExecError):
"""Write error"""
class RarOpenError(RarExecError):
"""Open error"""
class RarUserError(RarExecError):
"""User error"""
class RarMemoryError(RarExecError):
"""Memory error"""
class RarCreateError(RarExecError):
"""Create error"""
class RarNoFilesError(RarExecError):
"""No files that match pattern were found"""
class RarUserBreak(RarExecError):
"""User stop"""
class RarWrongPassword(RarExecError):
"""Incorrect password"""
class RarUnknownError(RarExecError):
"""Unknown exit code"""
class RarSignalExit(RarExecError):
"""Unrar exited with signal"""
class RarCannotExec(RarExecError):
"""Executable not found."""
class UnsupportedWarning(UserWarning):
"""Archive uses feature that are unsupported by rarfile.
.. versionadded:: 4.0
"""
class RarInfo:
r"""An entry in rar archive.
Timestamps as :class:`~datetime.datetime` are without timezone in RAR3,
with UTC timezone in RAR5 archives.
Attributes:
filename
File name with relative path.
Path separator is "/". Always unicode string.
date_time
File modification timestamp. As tuple of (year, month, day, hour, minute, second).
RAR5 allows archives where it is missing, it's None then.
comment
Optional file comment field. Unicode string. (RAR3-only)
file_size
Uncompressed size.
compress_size
Compressed size.
compress_type
Compression method: one of :data:`RAR_M0` .. :data:`RAR_M5` constants.
extract_version
Minimal Rar version needed for decompressing. As (major*10 + minor),
so 2.9 is 29.
RAR3: 10, 20, 29
RAR5 does not have such field in archive, it's simply set to 50.
host_os
Host OS type, one of RAR_OS_* constants.
RAR3: :data:`RAR_OS_WIN32`, :data:`RAR_OS_UNIX`, :data:`RAR_OS_MSDOS`,
:data:`RAR_OS_OS2`, :data:`RAR_OS_BEOS`.
RAR5: :data:`RAR_OS_WIN32`, :data:`RAR_OS_UNIX`.
mode
File attributes. May be either dos-style or unix-style, depending on host_os.
mtime
File modification time. Same value as :attr:`date_time`
but as :class:`~datetime.datetime` object with extended precision.
ctime
Optional time field: creation time. As :class:`~datetime.datetime` object.
atime
Optional time field: last access time. As :class:`~datetime.datetime` object.
arctime
Optional time field: archival time. As :class:`~datetime.datetime` object.
(RAR3-only)
CRC
CRC-32 of uncompressed file, unsigned int.
RAR5: may be None.
blake2sp_hash
Blake2SP hash over decompressed data. (RAR5-only)
volume
Volume nr, starting from 0.
volume_file
Volume file name, where file starts.
file_redir
If not None, file is link of some sort. Contains tuple of (type, flags, target).
(RAR5-only)
Type is one of constants:
:data:`RAR5_XREDIR_UNIX_SYMLINK`
Unix symlink.
:data:`RAR5_XREDIR_WINDOWS_SYMLINK`
Windows symlink.
:data:`RAR5_XREDIR_WINDOWS_JUNCTION`
Windows junction.
:data:`RAR5_XREDIR_HARD_LINK`
Hard link to target.
:data:`RAR5_XREDIR_FILE_COPY`
Current file is copy of another archive entry.
Flags may contain bits:
:data:`RAR5_XREDIR_ISDIR`
Symlink points to directory.
"""
# zipfile-compatible fields
filename = None
file_size = None
compress_size = None
date_time = None
CRC = None
volume = None
orig_filename = None
# optional extended time fields, datetime() objects.
mtime = None
ctime = None
atime = None
extract_version = None
mode = None
host_os = None
compress_type = None
# rar3-only fields
comment = None
arctime = None
# rar5-only fields
blake2sp_hash = None
file_redir = None
# internal fields
flags = 0
type = None
# zipfile compat
def is_dir(self):
"""Returns True if entry is a directory.
.. versionadded:: 4.0
"""
return False
def is_symlink(self):
"""Returns True if entry is a symlink.
.. versionadded:: 4.0
"""
return False
def is_file(self):
"""Returns True if entry is a normal file.
.. versionadded:: 4.0
"""
return False
def needs_password(self):
"""Returns True if data is stored password-protected.
"""
if self.type == RAR_BLOCK_FILE:
return (self.flags & RAR_FILE_PASSWORD) > 0
return False
def isdir(self):
"""Returns True if entry is a directory.
.. deprecated:: 4.0
"""
return self.is_dir()
class RarFile:
"""Parse RAR structure, provide access to files in archive.
Parameters:
file
archive file name or file-like object.
mode
only "r" is supported.
charset
fallback charset to use, if filenames are not already Unicode-enabled.
info_callback
debug callback, gets to see all archive entries.
crc_check
set to False to disable CRC checks
errors
Either "stop" to quietly stop parsing on errors,
or "strict" to raise errors. Default is "stop".
part_only
If True, read only single file and allow it to be middle-part
of multi-volume archive.
.. versionadded:: 4.0
"""
#: File name, if available. Unicode string or None.
filename = None
#: Archive comment. Unicode string or None.
comment = None
def __init__(self, file, mode="r", charset=None, info_callback=None,
crc_check=True, errors="stop", part_only=False):
if is_filelike(file):
self.filename = getattr(file, "name", None)
else:
if isinstance(file, Path):
file = str(file)
self.filename = file
self._rarfile = file
self._charset = charset or DEFAULT_CHARSET
self._info_callback = info_callback
self._crc_check = crc_check
self._part_only = part_only
self._password = None
self._file_parser = None
if errors == "stop":
self._strict = False
elif errors == "strict":
self._strict = True
else:
raise ValueError("Invalid value for errors= parameter.")
if mode != "r":
raise NotImplementedError("RarFile supports only mode=r")
self._parse()
def __enter__(self):
"""Open context."""
return self
def __exit__(self, typ, value, traceback):
"""Exit context."""
self.close()
def __iter__(self):
"""Iterate over members."""
return iter(self.infolist())
def setpassword(self, pwd):
"""Sets the password to use when extracting.
"""
self._password = pwd
if self._file_parser:
if self._file_parser.has_header_encryption():
self._file_parser = None
if not self._file_parser:
self._parse()
else:
self._file_parser.setpassword(self._password)
def needs_password(self):
"""Returns True if any archive entries require password for extraction.
"""
return self._file_parser.needs_password()
def is_solid(self):
"""Returns True if archive uses solid compression.
.. versionadded:: 4.2
"""
return self._file_parser.is_solid()
def namelist(self):
"""Return list of filenames in archive.
"""
return [f.filename for f in self.infolist()]
def infolist(self):
"""Return RarInfo objects for all files/directories in archive.
"""
return self._file_parser.infolist()
def volumelist(self):
"""Returns filenames of archive volumes.
In case of single-volume archive, the list contains
just the name of main archive file.
"""
return self._file_parser.volumelist()
def getinfo(self, name):
"""Return RarInfo for file.
"""
return self._file_parser.getinfo(name)
def getinfo_orig(self, name):
"""Return RarInfo for file source.
RAR5: if name is hard-linked or copied file,
returns original entry with original filename.
.. versionadded:: 4.1
"""
return self._file_parser.getinfo_orig(name)
def open(self, name, mode="r", pwd=None):
"""Returns file-like object (:class:`RarExtFile`) from where the data can be read.
The object implements :class:`io.RawIOBase` interface, so it can
be further wrapped with :class:`io.BufferedReader`
and :class:`io.TextIOWrapper`.
On older Python where io module is not available, it implements
only .read(), .seek(), .tell() and .close() methods.
The object is seekable, although the seeking is fast only on
uncompressed files, on compressed files the seeking is implemented
by reading ahead and/or restarting the decompression.
Parameters:
name
file name or RarInfo instance.
mode
must be "r"
pwd
password to use for extracting.
"""
if mode != "r":
raise NotImplementedError("RarFile.open() supports only mode=r")
# entry lookup
inf = self.getinfo(name)
if inf.is_dir():
raise io.UnsupportedOperation("Directory does not have any data: " + inf.filename)
# check password
if inf.needs_password():
pwd = pwd or self._password
if pwd is None:
raise PasswordRequired("File %s requires password" % inf.filename)
else:
pwd = None
return self._file_parser.open(inf, pwd)
def read(self, name, pwd=None):
"""Return uncompressed data for archive entry.
For longer files using :meth:`~RarFile.open` may be better idea.
Parameters:
name
filename or RarInfo instance
pwd
password to use for extracting.
"""
with self.open(name, "r", pwd) as f:
return f.read()
def close(self):
"""Release open resources."""
pass
def printdir(self, file=None):
"""Print archive file list to stdout or given file.
"""
if file is None:
file = sys.stdout
for f in self.infolist():
print(f.filename, file=file)
def extract(self, member, path=None, pwd=None):
"""Extract single file into current directory.
Parameters:
member
filename or :class:`RarInfo` instance
path
optional destination path
pwd
optional password to use
"""
inf = self.getinfo(member)
return self._extract_one(inf, path, pwd, True)
def extractall(self, path=None, members=None, pwd=None):
"""Extract all files into current directory.
Parameters:
path
optional destination path
members
optional filename or :class:`RarInfo` instance list to extract
pwd
optional password to use
"""
if members is None:
members = self.namelist()
done = set()
dirs = []
for m in members:
inf = self.getinfo(m)
dst = self._extract_one(inf, path, pwd, not inf.is_dir())
if inf.is_dir():
if dst not in done:
dirs.append((dst, inf))
done.add(dst)
if dirs:
dirs.sort(reverse=True)
for dst, inf in dirs:
self._set_attrs(inf, dst)
def testrar(self, pwd=None):
"""Read all files and test CRC.
"""
for member in self.infolist():
if member.is_file():
with self.open(member, 'r', pwd) as f:
empty_read(f, member.file_size, BSIZE)
def strerror(self):
"""Return error string if parsing failed or None if no problems.
"""
if not self._file_parser:
return "Not a RAR file"
return self._file_parser.strerror()
##
## private methods
##
def _parse(self):
"""Run parser for file type
"""
ver, sfx_ofs = _find_sfx_header(self._rarfile)
if ver == RAR_V3:
p3 = RAR3Parser(self._rarfile, self._password, self._crc_check,
self._charset, self._strict, self._info_callback,
sfx_ofs, self._part_only)
self._file_parser = p3 # noqa
elif ver == RAR_V5:
p5 = RAR5Parser(self._rarfile, self._password, self._crc_check,
self._charset, self._strict, self._info_callback,
sfx_ofs, self._part_only)
self._file_parser = p5 # noqa
else:
raise NotRarFile("Not a RAR file")
self._file_parser.parse()
self.comment = self._file_parser.comment
def _extract_one(self, info, path, pwd, set_attrs):
fname = sanitize_filename(
info.filename, os.path.sep, WIN32
)
if path is None:
path = os.getcwd()
else:
path = os.fspath(path)
dstfn = os.path.join(path, fname)
dirname = os.path.dirname(dstfn)
if dirname and dirname != ".":
os.makedirs(dirname, exist_ok=True)
if info.is_file():
return self._make_file(info, dstfn, pwd, set_attrs)
if info.is_dir():
return self._make_dir(info, dstfn, pwd, set_attrs)
if info.is_symlink():
return self._make_symlink(info, dstfn, pwd, set_attrs)
return None
def _create_helper(self, name, flags, info):
return os.open(name, flags)
def _make_file(self, info, dstfn, pwd, set_attrs):
def helper(name, flags):
return self._create_helper(name, flags, info)
with self.open(info, "r", pwd) as src:
with open(dstfn, "wb", opener=helper) as dst:
shutil.copyfileobj(src, dst)
if set_attrs:
self._set_attrs(info, dstfn)
return dstfn
def _make_dir(self, info, dstfn, pwd, set_attrs):
os.makedirs(dstfn, exist_ok=True)
if set_attrs:
self._set_attrs(info, dstfn)
return dstfn
def _make_symlink(self, info, dstfn, pwd, set_attrs):
target_is_directory = False
if info.host_os == RAR_OS_UNIX:
link_name = self.read(info, pwd)
target_is_directory = (info.flags & RAR_FILE_DIRECTORY) == RAR_FILE_DIRECTORY
elif info.file_redir:
redir_type, redir_flags, link_name = info.file_redir
if redir_type == RAR5_XREDIR_WINDOWS_JUNCTION:
warnings.warn(f"Windows junction not supported - {info.filename}", UnsupportedWarning)
return None
target_is_directory = (redir_type & RAR5_XREDIR_ISDIR) > 0
else:
warnings.warn(f"Unsupported link type - {info.filename}", UnsupportedWarning)
return None
os.symlink(link_name, dstfn, target_is_directory=target_is_directory)
return dstfn
def _set_attrs(self, info, dstfn):
if info.host_os == RAR_OS_UNIX:
os.chmod(dstfn, info.mode & 0o777)