index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
11,438
subprocess
_wait
Internal implementation of wait() on POSIX.
def _wait(self, timeout): """Internal implementation of wait() on POSIX.""" if self.returncode is not None: return self.returncode if timeout is not None: endtime = _time() + timeout # Enter a busy loop if we have a timeout. This busy loop was # cribbed from Lib/threading.py in Thread.wait() at r71065. delay = 0.0005 # 500 us -> initial delay of 1 ms while True: if self._waitpid_lock.acquire(False): try: if self.returncode is not None: break # Another thread waited. (pid, sts) = self._try_wait(os.WNOHANG) assert pid == self.pid or pid == 0 if pid == self.pid: self._handle_exitstatus(sts) break finally: self._waitpid_lock.release() remaining = self._remaining_time(endtime) if remaining <= 0: raise TimeoutExpired(self.args, timeout) delay = min(delay * 2, remaining, .05) time.sleep(delay) else: while self.returncode is None: with self._waitpid_lock: if self.returncode is not None: break # Another thread waited. (pid, sts) = self._try_wait(0) # Check the pid and loop as waitpid has been known to # return 0 even without WNOHANG in odd situations. # http://bugs.python.org/issue14396. if pid == self.pid: self._handle_exitstatus(sts) return self.returncode
(self, timeout)
11,439
subprocess
communicate
Interact with process: Send data to stdin and close it. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional "input" argument should be data to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr). By default, all communication is in bytes, and therefore any "input" should be bytes, and the (stdout, stderr) will be bytes. If in text mode (indicated by self.text_mode), any "input" should be a string, and (stdout, stderr) will be strings decoded according to locale encoding, or by "encoding" if set. Text mode is triggered by setting any of text, encoding, errors or universal_newlines.
def communicate(self, input=None, timeout=None): """Interact with process: Send data to stdin and close it. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional "input" argument should be data to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr). By default, all communication is in bytes, and therefore any "input" should be bytes, and the (stdout, stderr) will be bytes. If in text mode (indicated by self.text_mode), any "input" should be a string, and (stdout, stderr) will be strings decoded according to locale encoding, or by "encoding" if set. Text mode is triggered by setting any of text, encoding, errors or universal_newlines. """ if self._communication_started and input: raise ValueError("Cannot send input after starting communication") # Optimization: If we are not worried about timeouts, we haven't # started communicating, and we have one or zero pipes, using select() # or threads is unnecessary. if (timeout is None and not self._communication_started and [self.stdin, self.stdout, self.stderr].count(None) >= 2): stdout = None stderr = None if self.stdin: self._stdin_write(input) elif self.stdout: stdout = self.stdout.read() self.stdout.close() elif self.stderr: stderr = self.stderr.read() self.stderr.close() self.wait() else: if timeout is not None: endtime = _time() + timeout else: endtime = None try: stdout, stderr = self._communicate(input, endtime, timeout) except KeyboardInterrupt: # https://bugs.python.org/issue25942 # See the detailed comment in .wait(). if timeout is not None: sigint_timeout = min(self._sigint_wait_secs, self._remaining_time(endtime)) else: sigint_timeout = self._sigint_wait_secs self._sigint_wait_secs = 0 # nothing else should wait. try: self._wait(timeout=sigint_timeout) except TimeoutExpired: pass raise # resume the KeyboardInterrupt finally: self._communication_started = True sts = self.wait(timeout=self._remaining_time(endtime)) return (stdout, stderr)
(self, input=None, timeout=None)
11,440
subprocess
kill
Kill the process with SIGKILL
def kill(self): """Kill the process with SIGKILL """ self.send_signal(signal.SIGKILL)
(self)
11,441
subprocess
poll
Check if child process has terminated. Set and return returncode attribute.
def poll(self): """Check if child process has terminated. Set and return returncode attribute.""" return self._internal_poll()
(self)
11,442
subprocess
send_signal
Send a signal to the process.
def send_signal(self, sig): """Send a signal to the process.""" # bpo-38630: Polling reduces the risk of sending a signal to the # wrong process if the process completed, the Popen.returncode # attribute is still None, and the pid has been reassigned # (recycled) to a new different process. This race condition can # happens in two cases. # # Case 1. Thread A calls Popen.poll(), thread B calls # Popen.send_signal(). In thread A, waitpid() succeed and returns # the exit status. Thread B calls kill() because poll() in thread A # did not set returncode yet. Calling poll() in thread B prevents # the race condition thanks to Popen._waitpid_lock. # # Case 2. waitpid(pid, 0) has been called directly, without # using Popen methods: returncode is still None is this case. # Calling Popen.poll() will set returncode to a default value, # since waitpid() fails with ProcessLookupError. self.poll() if self.returncode is not None: # Skip signalling a process that we know has already died. return # The race condition can still happen if the race condition # described above happens between the returncode test # and the kill() call. try: os.kill(self.pid, sig) except ProcessLookupError: # Supress the race condition error; bpo-40550. pass
(self, sig)
11,443
subprocess
terminate
Terminate the process with SIGTERM
def terminate(self): """Terminate the process with SIGTERM """ self.send_signal(signal.SIGTERM)
(self)
11,444
subprocess
wait
Wait for child process to terminate; returns self.returncode.
def wait(self, timeout=None): """Wait for child process to terminate; returns self.returncode.""" if timeout is not None: endtime = _time() + timeout try: return self._wait(timeout=timeout) except KeyboardInterrupt: # https://bugs.python.org/issue25942 # The first keyboard interrupt waits briefly for the child to # exit under the common assumption that it also received the ^C # generated SIGINT and will exit rapidly. if timeout is not None: sigint_timeout = min(self._sigint_wait_secs, self._remaining_time(endtime)) else: sigint_timeout = self._sigint_wait_secs self._sigint_wait_secs = 0 # nothing else should wait. try: self._wait(timeout=sigint_timeout) except TimeoutExpired: pass raise # resume the KeyboardInterrupt
(self, timeout=None)
11,445
rarfile
RAR3Parser
Parse RAR3 file format.
class RAR3Parser(CommonParser): """Parse RAR3 file format. """ _expect_sig = RAR_ID _last_aes_key = (None, None, None) # (salt, key, iv) def _decrypt_header(self, fd): if not _have_crypto: raise NoCrypto("Cannot parse encrypted headers - no crypto") salt = fd.read(8) if self._last_aes_key[0] == salt: key, iv = self._last_aes_key[1:] else: key, iv = rar3_s2k(self._password, salt) self._last_aes_key = (salt, key, iv) return HeaderDecrypt(fd, key, iv) def _parse_block_header(self, fd): """Parse common block header """ h = Rar3Info() h.header_offset = fd.tell() # read and parse base header buf = fd.read(S_BLK_HDR.size) if not buf: return None if len(buf) < S_BLK_HDR.size: self._set_error("Unexpected EOF when reading header") return None t = S_BLK_HDR.unpack_from(buf) h.header_crc, h.type, h.flags, h.header_size = t # read full header if h.header_size > S_BLK_HDR.size: hdata = buf + fd.read(h.header_size - S_BLK_HDR.size) else: hdata = buf h.data_offset = fd.tell() # unexpected EOF? if len(hdata) != h.header_size: self._set_error("Unexpected EOF when reading header") return None pos = S_BLK_HDR.size # block has data assiciated with it? if h.flags & RAR_LONG_BLOCK: h.add_size, pos = load_le32(hdata, pos) else: h.add_size = 0 # parse interesting ones, decide header boundaries for crc if h.type == RAR_BLOCK_MARK: return h elif h.type == RAR_BLOCK_MAIN: pos += 6 if h.flags & RAR_MAIN_ENCRYPTVER: pos += 1 crc_pos = pos if h.flags & RAR_MAIN_COMMENT: self._parse_subblocks(h, hdata, pos) elif h.type == RAR_BLOCK_FILE: pos = self._parse_file_header(h, hdata, pos - 4) crc_pos = pos if h.flags & RAR_FILE_COMMENT: pos = self._parse_subblocks(h, hdata, pos) elif h.type == RAR_BLOCK_SUB: pos = self._parse_file_header(h, hdata, pos - 4) crc_pos = h.header_size elif h.type == RAR_BLOCK_OLD_AUTH: pos += 8 crc_pos = pos elif h.type == RAR_BLOCK_OLD_EXTRA: pos += 7 crc_pos = pos elif h.type == RAR_BLOCK_ENDARC: if h.flags & RAR_ENDARC_DATACRC: h.endarc_datacrc, pos = load_le32(hdata, pos) if h.flags & RAR_ENDARC_VOLNR: h.endarc_volnr = S_SHORT.unpack_from(hdata, pos)[0] pos += 2 crc_pos = h.header_size else: crc_pos = h.header_size # check crc if h.type == RAR_BLOCK_OLD_SUB: crcdat = hdata[2:] + fd.read(h.add_size) else: crcdat = hdata[2:crc_pos] calc_crc = crc32(crcdat) & 0xFFFF # return good header if h.header_crc == calc_crc: return h # header parsing failed. self._set_error("Header CRC error (%02x): exp=%x got=%x (xlen = %d)", h.type, h.header_crc, calc_crc, len(crcdat)) # instead panicing, send eof return None def _parse_file_header(self, h, hdata, pos): """Read file-specific header """ fld = S_FILE_HDR.unpack_from(hdata, pos) pos += S_FILE_HDR.size h.compress_size = fld[0] h.file_size = fld[1] h.host_os = fld[2] h.CRC = fld[3] h.date_time = parse_dos_time(fld[4]) h.mtime = to_datetime(h.date_time) h.extract_version = fld[5] h.compress_type = fld[6] h._name_size = name_size = fld[7] h.mode = fld[8] h._md_class = CRC32Context h._md_expect = h.CRC if h.flags & RAR_FILE_LARGE: h1, pos = load_le32(hdata, pos) h2, pos = load_le32(hdata, pos) h.compress_size |= h1 << 32 h.file_size |= h2 << 32 h.add_size = h.compress_size name, pos = load_bytes(hdata, name_size, pos) if h.flags & RAR_FILE_UNICODE and b"\0" in name: # stored in custom encoding nul = name.find(b"\0") h.orig_filename = name[:nul] u = UnicodeFilename(h.orig_filename, name[nul + 1:]) h.filename = u.decode() # if parsing failed fall back to simple name if u.failed: h.filename = self._decode(h.orig_filename) elif h.flags & RAR_FILE_UNICODE: # stored in UTF8 h.orig_filename = name h.filename = name.decode("utf8", "replace") else: # stored in random encoding h.orig_filename = name h.filename = self._decode(name) # change separator, set dir suffix h.filename = h.filename.replace("\\", "/").rstrip("/") if h.is_dir(): h.filename = h.filename + "/" if h.flags & RAR_FILE_SALT: h.salt, pos = load_bytes(hdata, 8, pos) else: h.salt = None # optional extended time stamps if h.flags & RAR_FILE_EXTTIME: pos = _parse_ext_time(h, hdata, pos) else: h.mtime = h.atime = h.ctime = h.arctime = None return pos def _parse_subblocks(self, h, hdata, pos): """Find old-style comment subblock """ while pos < len(hdata): # ordinary block header t = S_BLK_HDR.unpack_from(hdata, pos) ___scrc, stype, sflags, slen = t pos_next = pos + slen pos += S_BLK_HDR.size # corrupt header if pos_next < pos: break # followed by block-specific header if stype == RAR_BLOCK_OLD_COMMENT and pos + S_COMMENT_HDR.size <= pos_next: declen, ver, meth, crc = S_COMMENT_HDR.unpack_from(hdata, pos) pos += S_COMMENT_HDR.size data = hdata[pos: pos_next] cmt = rar3_decompress(ver, meth, data, declen, sflags, crc, self._password) if not self._crc_check or (crc32(cmt) & 0xFFFF == crc): h.comment = self._decode_comment(cmt) pos = pos_next return pos def _read_comment_v3(self, inf, pwd=None): # read data with XFile(inf.volume_file) as rf: rf.seek(inf.data_offset) data = rf.read(inf.compress_size) # decompress cmt = rar3_decompress(inf.extract_version, inf.compress_type, data, inf.file_size, inf.flags, inf.CRC, pwd, inf.salt) # check crc if self._crc_check: crc = crc32(cmt) if crc != inf.CRC: return None return self._decode_comment(cmt) def _decode(self, val): for c in TRY_ENCODINGS: try: return val.decode(c) except UnicodeError: pass return val.decode(self._charset, "replace") def _decode_comment(self, val): return self._decode(val) def process_entry(self, fd, item): if item.type == RAR_BLOCK_FILE: # use only first part if item.flags & RAR_FILE_VERSION: pass # skip old versions elif (item.flags & RAR_FILE_SPLIT_BEFORE) == 0: self._info_map[item.filename.rstrip("/")] = item self._info_list.append(item) elif len(self._info_list) > 0: # final crc is in last block old = self._info_list[-1] old.CRC = item.CRC old._md_expect = item._md_expect old.compress_size += item.compress_size # parse new-style comment if item.type == RAR_BLOCK_SUB and item.filename == "CMT": if item.flags & (RAR_FILE_SPLIT_BEFORE | RAR_FILE_SPLIT_AFTER): pass elif item.flags & RAR_FILE_SOLID: # file comment cmt = self._read_comment_v3(item, self._password) if len(self._info_list) > 0: old = self._info_list[-1] old.comment = cmt else: # archive comment cmt = self._read_comment_v3(item, self._password) self.comment = cmt if item.type == RAR_BLOCK_MAIN: if item.flags & RAR_MAIN_COMMENT: self.comment = item.comment if item.flags & RAR_MAIN_PASSWORD: self._needs_password = True # put file compressed data into temporary .rar archive, and run # unrar on that, thus avoiding unrar going over whole archive def _open_hack(self, inf, pwd): # create main header: crc, type, flags, size, res1, res2 prefix = RAR_ID + S_BLK_HDR.pack(0x90CF, 0x73, 0, 13) + b"\0" * (2 + 4) return self._open_hack_core(inf, pwd, prefix, b"")
(rarfile, password, crc_check, charset, strict, info_cb, sfx_offset, part_only)
11,447
rarfile
_decode
null
def _decode(self, val): for c in TRY_ENCODINGS: try: return val.decode(c) except UnicodeError: pass return val.decode(self._charset, "replace")
(self, val)
11,448
rarfile
_decode_comment
null
def _decode_comment(self, val): return self._decode(val)
(self, val)
11,449
rarfile
_decrypt_header
null
def _decrypt_header(self, fd): if not _have_crypto: raise NoCrypto("Cannot parse encrypted headers - no crypto") salt = fd.read(8) if self._last_aes_key[0] == salt: key, iv = self._last_aes_key[1:] else: key, iv = rar3_s2k(self._password, salt) self._last_aes_key = (salt, key, iv) return HeaderDecrypt(fd, key, iv)
(self, fd)
11,452
rarfile
_open_hack
null
def _open_hack(self, inf, pwd): # create main header: crc, type, flags, size, res1, res2 prefix = RAR_ID + S_BLK_HDR.pack(0x90CF, 0x73, 0, 13) + b"\0" * (2 + 4) return self._open_hack_core(inf, pwd, prefix, b"")
(self, inf, pwd)
11,456
rarfile
_parse_block_header
Parse common block header
def _parse_block_header(self, fd): """Parse common block header """ h = Rar3Info() h.header_offset = fd.tell() # read and parse base header buf = fd.read(S_BLK_HDR.size) if not buf: return None if len(buf) < S_BLK_HDR.size: self._set_error("Unexpected EOF when reading header") return None t = S_BLK_HDR.unpack_from(buf) h.header_crc, h.type, h.flags, h.header_size = t # read full header if h.header_size > S_BLK_HDR.size: hdata = buf + fd.read(h.header_size - S_BLK_HDR.size) else: hdata = buf h.data_offset = fd.tell() # unexpected EOF? if len(hdata) != h.header_size: self._set_error("Unexpected EOF when reading header") return None pos = S_BLK_HDR.size # block has data assiciated with it? if h.flags & RAR_LONG_BLOCK: h.add_size, pos = load_le32(hdata, pos) else: h.add_size = 0 # parse interesting ones, decide header boundaries for crc if h.type == RAR_BLOCK_MARK: return h elif h.type == RAR_BLOCK_MAIN: pos += 6 if h.flags & RAR_MAIN_ENCRYPTVER: pos += 1 crc_pos = pos if h.flags & RAR_MAIN_COMMENT: self._parse_subblocks(h, hdata, pos) elif h.type == RAR_BLOCK_FILE: pos = self._parse_file_header(h, hdata, pos - 4) crc_pos = pos if h.flags & RAR_FILE_COMMENT: pos = self._parse_subblocks(h, hdata, pos) elif h.type == RAR_BLOCK_SUB: pos = self._parse_file_header(h, hdata, pos - 4) crc_pos = h.header_size elif h.type == RAR_BLOCK_OLD_AUTH: pos += 8 crc_pos = pos elif h.type == RAR_BLOCK_OLD_EXTRA: pos += 7 crc_pos = pos elif h.type == RAR_BLOCK_ENDARC: if h.flags & RAR_ENDARC_DATACRC: h.endarc_datacrc, pos = load_le32(hdata, pos) if h.flags & RAR_ENDARC_VOLNR: h.endarc_volnr = S_SHORT.unpack_from(hdata, pos)[0] pos += 2 crc_pos = h.header_size else: crc_pos = h.header_size # check crc if h.type == RAR_BLOCK_OLD_SUB: crcdat = hdata[2:] + fd.read(h.add_size) else: crcdat = hdata[2:crc_pos] calc_crc = crc32(crcdat) & 0xFFFF # return good header if h.header_crc == calc_crc: return h # header parsing failed. self._set_error("Header CRC error (%02x): exp=%x got=%x (xlen = %d)", h.type, h.header_crc, calc_crc, len(crcdat)) # instead panicing, send eof return None
(self, fd)
11,457
rarfile
_parse_file_header
Read file-specific header
def _parse_file_header(self, h, hdata, pos): """Read file-specific header """ fld = S_FILE_HDR.unpack_from(hdata, pos) pos += S_FILE_HDR.size h.compress_size = fld[0] h.file_size = fld[1] h.host_os = fld[2] h.CRC = fld[3] h.date_time = parse_dos_time(fld[4]) h.mtime = to_datetime(h.date_time) h.extract_version = fld[5] h.compress_type = fld[6] h._name_size = name_size = fld[7] h.mode = fld[8] h._md_class = CRC32Context h._md_expect = h.CRC if h.flags & RAR_FILE_LARGE: h1, pos = load_le32(hdata, pos) h2, pos = load_le32(hdata, pos) h.compress_size |= h1 << 32 h.file_size |= h2 << 32 h.add_size = h.compress_size name, pos = load_bytes(hdata, name_size, pos) if h.flags & RAR_FILE_UNICODE and b"\0" in name: # stored in custom encoding nul = name.find(b"\0") h.orig_filename = name[:nul] u = UnicodeFilename(h.orig_filename, name[nul + 1:]) h.filename = u.decode() # if parsing failed fall back to simple name if u.failed: h.filename = self._decode(h.orig_filename) elif h.flags & RAR_FILE_UNICODE: # stored in UTF8 h.orig_filename = name h.filename = name.decode("utf8", "replace") else: # stored in random encoding h.orig_filename = name h.filename = self._decode(name) # change separator, set dir suffix h.filename = h.filename.replace("\\", "/").rstrip("/") if h.is_dir(): h.filename = h.filename + "/" if h.flags & RAR_FILE_SALT: h.salt, pos = load_bytes(hdata, 8, pos) else: h.salt = None # optional extended time stamps if h.flags & RAR_FILE_EXTTIME: pos = _parse_ext_time(h, hdata, pos) else: h.mtime = h.atime = h.ctime = h.arctime = None return pos
(self, h, hdata, pos)
11,460
rarfile
_parse_subblocks
Find old-style comment subblock
def _parse_subblocks(self, h, hdata, pos): """Find old-style comment subblock """ while pos < len(hdata): # ordinary block header t = S_BLK_HDR.unpack_from(hdata, pos) ___scrc, stype, sflags, slen = t pos_next = pos + slen pos += S_BLK_HDR.size # corrupt header if pos_next < pos: break # followed by block-specific header if stype == RAR_BLOCK_OLD_COMMENT and pos + S_COMMENT_HDR.size <= pos_next: declen, ver, meth, crc = S_COMMENT_HDR.unpack_from(hdata, pos) pos += S_COMMENT_HDR.size data = hdata[pos: pos_next] cmt = rar3_decompress(ver, meth, data, declen, sflags, crc, self._password) if not self._crc_check or (crc32(cmt) & 0xFFFF == crc): h.comment = self._decode_comment(cmt) pos = pos_next return pos
(self, h, hdata, pos)
11,461
rarfile
_read_comment_v3
null
def _read_comment_v3(self, inf, pwd=None): # read data with XFile(inf.volume_file) as rf: rf.seek(inf.data_offset) data = rf.read(inf.compress_size) # decompress cmt = rar3_decompress(inf.extract_version, inf.compress_type, data, inf.file_size, inf.flags, inf.CRC, pwd, inf.salt) # check crc if self._crc_check: crc = crc32(cmt) if crc != inf.CRC: return None return self._decode_comment(cmt)
(self, inf, pwd=None)
11,471
rarfile
process_entry
null
def process_entry(self, fd, item): if item.type == RAR_BLOCK_FILE: # use only first part if item.flags & RAR_FILE_VERSION: pass # skip old versions elif (item.flags & RAR_FILE_SPLIT_BEFORE) == 0: self._info_map[item.filename.rstrip("/")] = item self._info_list.append(item) elif len(self._info_list) > 0: # final crc is in last block old = self._info_list[-1] old.CRC = item.CRC old._md_expect = item._md_expect old.compress_size += item.compress_size # parse new-style comment if item.type == RAR_BLOCK_SUB and item.filename == "CMT": if item.flags & (RAR_FILE_SPLIT_BEFORE | RAR_FILE_SPLIT_AFTER): pass elif item.flags & RAR_FILE_SOLID: # file comment cmt = self._read_comment_v3(item, self._password) if len(self._info_list) > 0: old = self._info_list[-1] old.comment = cmt else: # archive comment cmt = self._read_comment_v3(item, self._password) self.comment = cmt if item.type == RAR_BLOCK_MAIN: if item.flags & RAR_MAIN_COMMENT: self.comment = item.comment if item.flags & RAR_MAIN_PASSWORD: self._needs_password = True
(self, fd, item)
11,475
rarfile
RAR5Parser
Parse RAR5 format.
class RAR5Parser(CommonParser): """Parse RAR5 format. """ _expect_sig = RAR5_ID _hdrenc_main = None # AES encrypted headers _last_aes256_key = (-1, None, None) # (kdf_count, salt, key) def _get_utf8_password(self): pwd = self._password if isinstance(pwd, str): return pwd.encode("utf8") return pwd def _gen_key(self, kdf_count, salt): if self._last_aes256_key[:2] == (kdf_count, salt): return self._last_aes256_key[2] if kdf_count > 24: raise BadRarFile("Too large kdf_count") pwd = self._get_utf8_password() key = pbkdf2_hmac("sha256", pwd, salt, 1 << kdf_count) self._last_aes256_key = (kdf_count, salt, key) return key def _decrypt_header(self, fd): if not _have_crypto: raise NoCrypto("Cannot parse encrypted headers - no crypto") h = self._hdrenc_main key = self._gen_key(h.encryption_kdf_count, h.encryption_salt) iv = fd.read(16) return HeaderDecrypt(fd, key, iv) def _parse_block_header(self, fd): """Parse common block header """ header_offset = fd.tell() preload = 4 + 1 start_bytes = fd.read(preload) if len(start_bytes) < preload: self._set_error("Unexpected EOF when reading header") return None while start_bytes[-1] & 0x80: b = fd.read(1) if not b: self._set_error("Unexpected EOF when reading header") return None start_bytes += b header_crc, pos = load_le32(start_bytes, 0) hdrlen, pos = load_vint(start_bytes, pos) if hdrlen > 2 * 1024 * 1024: return None header_size = pos + hdrlen # read full header, check for EOF hdata = start_bytes + fd.read(header_size - len(start_bytes)) if len(hdata) != header_size: self._set_error("Unexpected EOF when reading header") return None data_offset = fd.tell() calc_crc = crc32(memoryview(hdata)[4:]) if header_crc != calc_crc: # header parsing failed. self._set_error("Header CRC error: exp=%x got=%x (xlen = %d)", header_crc, calc_crc, len(hdata)) return None block_type, pos = load_vint(hdata, pos) if block_type == RAR5_BLOCK_MAIN: h, pos = self._parse_block_common(Rar5MainInfo(), hdata) h = self._parse_main_block(h, hdata, pos) elif block_type == RAR5_BLOCK_FILE: h, pos = self._parse_block_common(Rar5FileInfo(), hdata) h = self._parse_file_block(h, hdata, pos) elif block_type == RAR5_BLOCK_SERVICE: h, pos = self._parse_block_common(Rar5ServiceInfo(), hdata) h = self._parse_file_block(h, hdata, pos) elif block_type == RAR5_BLOCK_ENCRYPTION: h, pos = self._parse_block_common(Rar5EncryptionInfo(), hdata) h = self._parse_encryption_block(h, hdata, pos) elif block_type == RAR5_BLOCK_ENDARC: h, pos = self._parse_block_common(Rar5EndArcInfo(), hdata) h = self._parse_endarc_block(h, hdata, pos) else: h = None if h: h.header_offset = header_offset h.data_offset = data_offset return h def _parse_block_common(self, h, hdata): h.header_crc, pos = load_le32(hdata, 0) hdrlen, pos = load_vint(hdata, pos) h.header_size = hdrlen + pos h.block_type, pos = load_vint(hdata, pos) h.block_flags, pos = load_vint(hdata, pos) if h.block_flags & RAR5_BLOCK_FLAG_EXTRA_DATA: h.block_extra_size, pos = load_vint(hdata, pos) if h.block_flags & RAR5_BLOCK_FLAG_DATA_AREA: h.add_size, pos = load_vint(hdata, pos) h.compress_size = h.add_size if h.block_flags & RAR5_BLOCK_FLAG_SKIP_IF_UNKNOWN: h.flags |= RAR_SKIP_IF_UNKNOWN if h.block_flags & RAR5_BLOCK_FLAG_DATA_AREA: h.flags |= RAR_LONG_BLOCK return h, pos def _parse_main_block(self, h, hdata, pos): h.main_flags, pos = load_vint(hdata, pos) if h.main_flags & RAR5_MAIN_FLAG_HAS_VOLNR: h.main_volume_number, pos = load_vint(hdata, pos) h.flags |= RAR_MAIN_NEWNUMBERING if h.main_flags & RAR5_MAIN_FLAG_SOLID: h.flags |= RAR_MAIN_SOLID if h.main_flags & RAR5_MAIN_FLAG_ISVOL: h.flags |= RAR_MAIN_VOLUME if h.main_flags & RAR5_MAIN_FLAG_RECOVERY: h.flags |= RAR_MAIN_RECOVERY if self._hdrenc_main: h.flags |= RAR_MAIN_PASSWORD if h.main_flags & RAR5_MAIN_FLAG_HAS_VOLNR == 0: h.flags |= RAR_MAIN_FIRSTVOLUME return h def _parse_file_block(self, h, hdata, pos): h.file_flags, pos = load_vint(hdata, pos) h.file_size, pos = load_vint(hdata, pos) h.mode, pos = load_vint(hdata, pos) if h.file_flags & RAR5_FILE_FLAG_HAS_MTIME: h.mtime, pos = load_unixtime(hdata, pos) h.date_time = h.mtime.timetuple()[:6] if h.file_flags & RAR5_FILE_FLAG_HAS_CRC32: h.CRC, pos = load_le32(hdata, pos) h._md_class = CRC32Context h._md_expect = h.CRC h.file_compress_flags, pos = load_vint(hdata, pos) h.file_host_os, pos = load_vint(hdata, pos) h.orig_filename, pos = load_vstr(hdata, pos) h.filename = h.orig_filename.decode("utf8", "replace").rstrip("/") # use compatible values if h.file_host_os == RAR5_OS_WINDOWS: h.host_os = RAR_OS_WIN32 else: h.host_os = RAR_OS_UNIX h.compress_type = RAR_M0 + ((h.file_compress_flags >> 7) & 7) if h.block_extra_size: # allow 1 byte of garbage while pos < len(hdata) - 1: xsize, pos = load_vint(hdata, pos) xdata, pos = load_bytes(hdata, xsize, pos) self._process_file_extra(h, xdata) if h.block_flags & RAR5_BLOCK_FLAG_SPLIT_BEFORE: h.flags |= RAR_FILE_SPLIT_BEFORE if h.block_flags & RAR5_BLOCK_FLAG_SPLIT_AFTER: h.flags |= RAR_FILE_SPLIT_AFTER if h.file_flags & RAR5_FILE_FLAG_ISDIR: h.flags |= RAR_FILE_DIRECTORY if h.file_compress_flags & RAR5_COMPR_SOLID: h.flags |= RAR_FILE_SOLID if h.is_dir(): h.filename = h.filename + "/" return h def _parse_endarc_block(self, h, hdata, pos): h.endarc_flags, pos = load_vint(hdata, pos) if h.endarc_flags & RAR5_ENDARC_FLAG_NEXT_VOL: h.flags |= RAR_ENDARC_NEXT_VOLUME return h def _check_password(self, check_value, kdf_count_shift, salt): if len(check_value) != RAR5_PW_CHECK_SIZE + RAR5_PW_SUM_SIZE: return hdr_check = check_value[:RAR5_PW_CHECK_SIZE] hdr_sum = check_value[RAR5_PW_CHECK_SIZE:] sum_hash = sha256(hdr_check).digest() if sum_hash[:RAR5_PW_SUM_SIZE] != hdr_sum: return kdf_count = (1 << kdf_count_shift) + 32 pwd = self._get_utf8_password() pwd_hash = pbkdf2_hmac("sha256", pwd, salt, kdf_count) pwd_check = bytearray(RAR5_PW_CHECK_SIZE) len_mask = RAR5_PW_CHECK_SIZE - 1 for i, v in enumerate(pwd_hash): pwd_check[i & len_mask] ^= v if pwd_check != hdr_check: raise RarWrongPassword() def _parse_encryption_block(self, h, hdata, pos): h.encryption_algo, pos = load_vint(hdata, pos) h.encryption_flags, pos = load_vint(hdata, pos) h.encryption_kdf_count, pos = load_byte(hdata, pos) h.encryption_salt, pos = load_bytes(hdata, 16, pos) if h.encryption_flags & RAR5_ENC_FLAG_HAS_CHECKVAL: h.encryption_check_value, pos = load_bytes(hdata, 12, pos) if h.encryption_algo != RAR5_XENC_CIPHER_AES256: raise BadRarFile("Unsupported header encryption cipher") if h.encryption_check_value and self._password: self._check_password(h.encryption_check_value, h.encryption_kdf_count, h.encryption_salt) self._hdrenc_main = h return h def _process_file_extra(self, h, xdata): xtype, pos = load_vint(xdata, 0) if xtype == RAR5_XFILE_TIME: self._parse_file_xtime(h, xdata, pos) elif xtype == RAR5_XFILE_ENCRYPTION: self._parse_file_encryption(h, xdata, pos) elif xtype == RAR5_XFILE_HASH: self._parse_file_hash(h, xdata, pos) elif xtype == RAR5_XFILE_VERSION: self._parse_file_version(h, xdata, pos) elif xtype == RAR5_XFILE_REDIR: self._parse_file_redir(h, xdata, pos) elif xtype == RAR5_XFILE_OWNER: self._parse_file_owner(h, xdata, pos) elif xtype == RAR5_XFILE_SERVICE: pass else: pass # extra block for file time record def _parse_file_xtime(self, h, xdata, pos): tflags, pos = load_vint(xdata, pos) ldr = load_windowstime if tflags & RAR5_XTIME_UNIXTIME: ldr = load_unixtime if tflags & RAR5_XTIME_HAS_MTIME: h.mtime, pos = ldr(xdata, pos) h.date_time = h.mtime.timetuple()[:6] if tflags & RAR5_XTIME_HAS_CTIME: h.ctime, pos = ldr(xdata, pos) if tflags & RAR5_XTIME_HAS_ATIME: h.atime, pos = ldr(xdata, pos) if tflags & RAR5_XTIME_UNIXTIME_NS: if tflags & RAR5_XTIME_HAS_MTIME: nsec, pos = load_le32(xdata, pos) h.mtime = to_nsdatetime(h.mtime, nsec) if tflags & RAR5_XTIME_HAS_CTIME: nsec, pos = load_le32(xdata, pos) h.ctime = to_nsdatetime(h.ctime, nsec) if tflags & RAR5_XTIME_HAS_ATIME: nsec, pos = load_le32(xdata, pos) h.atime = to_nsdatetime(h.atime, nsec) # just remember encryption info def _parse_file_encryption(self, h, xdata, pos): algo, pos = load_vint(xdata, pos) flags, pos = load_vint(xdata, pos) kdf_count, pos = load_byte(xdata, pos) salt, pos = load_bytes(xdata, 16, pos) iv, pos = load_bytes(xdata, 16, pos) checkval = None if flags & RAR5_XENC_CHECKVAL: checkval, pos = load_bytes(xdata, 12, pos) if flags & RAR5_XENC_TWEAKED: h._md_expect = None h._md_class = NoHashContext h.file_encryption = (algo, flags, kdf_count, salt, iv, checkval) h.flags |= RAR_FILE_PASSWORD def _parse_file_hash(self, h, xdata, pos): hash_type, pos = load_vint(xdata, pos) if hash_type == RAR5_XHASH_BLAKE2SP: h.blake2sp_hash, pos = load_bytes(xdata, 32, pos) if (h.file_encryption[1] & RAR5_XENC_TWEAKED) == 0: h._md_class = Blake2SP h._md_expect = h.blake2sp_hash def _parse_file_version(self, h, xdata, pos): flags, pos = load_vint(xdata, pos) version, pos = load_vint(xdata, pos) h.file_version = (flags, version) def _parse_file_redir(self, h, xdata, pos): redir_type, pos = load_vint(xdata, pos) redir_flags, pos = load_vint(xdata, pos) redir_name, pos = load_vstr(xdata, pos) redir_name = redir_name.decode("utf8", "replace") h.file_redir = (redir_type, redir_flags, redir_name) def _parse_file_owner(self, h, xdata, pos): user_name = group_name = user_id = group_id = None flags, pos = load_vint(xdata, pos) if flags & RAR5_XOWNER_UNAME: user_name, pos = load_vstr(xdata, pos) if flags & RAR5_XOWNER_GNAME: group_name, pos = load_vstr(xdata, pos) if flags & RAR5_XOWNER_UID: user_id, pos = load_vint(xdata, pos) if flags & RAR5_XOWNER_GID: group_id, pos = load_vint(xdata, pos) h.file_owner = (user_name, group_name, user_id, group_id) def process_entry(self, fd, item): if item.block_type == RAR5_BLOCK_FILE: if item.file_version: pass # skip old versions elif (item.block_flags & RAR5_BLOCK_FLAG_SPLIT_BEFORE) == 0: # use only first part self._info_map[item.filename.rstrip("/")] = item self._info_list.append(item) elif len(self._info_list) > 0: # final crc is in last block old = self._info_list[-1] old.CRC = item.CRC old._md_expect = item._md_expect old.blake2sp_hash = item.blake2sp_hash old.compress_size += item.compress_size elif item.block_type == RAR5_BLOCK_SERVICE: if item.filename == "CMT": self._load_comment(fd, item) def _load_comment(self, fd, item): if item.block_flags & (RAR5_BLOCK_FLAG_SPLIT_BEFORE | RAR5_BLOCK_FLAG_SPLIT_AFTER): return None if item.compress_type != RAR_M0: return None if item.flags & RAR_FILE_PASSWORD: algo, ___flags, kdf_count, salt, iv, ___checkval = item.file_encryption if algo != RAR5_XENC_CIPHER_AES256: return None key = self._gen_key(kdf_count, salt) f = HeaderDecrypt(fd, key, iv) cmt = f.read(item.file_size) else: # archive comment with self._open_clear(item) as cmtstream: cmt = cmtstream.read() # rar bug? - appends zero to comment cmt = cmt.split(b"\0", 1)[0] self.comment = cmt.decode("utf8") return None def _open_hack(self, inf, pwd): # len, type, blk_flags, flags main_hdr = b"\x03\x01\x00\x00" endarc_hdr = b"\x03\x05\x00\x00" main_hdr = S_LONG.pack(crc32(main_hdr)) + main_hdr endarc_hdr = S_LONG.pack(crc32(endarc_hdr)) + endarc_hdr return self._open_hack_core(inf, pwd, RAR5_ID + main_hdr, endarc_hdr)
(rarfile, password, crc_check, charset, strict, info_cb, sfx_offset, part_only)
11,477
rarfile
_check_password
null
def _check_password(self, check_value, kdf_count_shift, salt): if len(check_value) != RAR5_PW_CHECK_SIZE + RAR5_PW_SUM_SIZE: return hdr_check = check_value[:RAR5_PW_CHECK_SIZE] hdr_sum = check_value[RAR5_PW_CHECK_SIZE:] sum_hash = sha256(hdr_check).digest() if sum_hash[:RAR5_PW_SUM_SIZE] != hdr_sum: return kdf_count = (1 << kdf_count_shift) + 32 pwd = self._get_utf8_password() pwd_hash = pbkdf2_hmac("sha256", pwd, salt, kdf_count) pwd_check = bytearray(RAR5_PW_CHECK_SIZE) len_mask = RAR5_PW_CHECK_SIZE - 1 for i, v in enumerate(pwd_hash): pwd_check[i & len_mask] ^= v if pwd_check != hdr_check: raise RarWrongPassword()
(self, check_value, kdf_count_shift, salt)
11,478
rarfile
_decrypt_header
null
def _decrypt_header(self, fd): if not _have_crypto: raise NoCrypto("Cannot parse encrypted headers - no crypto") h = self._hdrenc_main key = self._gen_key(h.encryption_kdf_count, h.encryption_salt) iv = fd.read(16) return HeaderDecrypt(fd, key, iv)
(self, fd)
11,479
rarfile
_gen_key
null
def _gen_key(self, kdf_count, salt): if self._last_aes256_key[:2] == (kdf_count, salt): return self._last_aes256_key[2] if kdf_count > 24: raise BadRarFile("Too large kdf_count") pwd = self._get_utf8_password() key = pbkdf2_hmac("sha256", pwd, salt, 1 << kdf_count) self._last_aes256_key = (kdf_count, salt, key) return key
(self, kdf_count, salt)
11,480
rarfile
_get_utf8_password
null
def _get_utf8_password(self): pwd = self._password if isinstance(pwd, str): return pwd.encode("utf8") return pwd
(self)
11,481
rarfile
_load_comment
null
def _load_comment(self, fd, item): if item.block_flags & (RAR5_BLOCK_FLAG_SPLIT_BEFORE | RAR5_BLOCK_FLAG_SPLIT_AFTER): return None if item.compress_type != RAR_M0: return None if item.flags & RAR_FILE_PASSWORD: algo, ___flags, kdf_count, salt, iv, ___checkval = item.file_encryption if algo != RAR5_XENC_CIPHER_AES256: return None key = self._gen_key(kdf_count, salt) f = HeaderDecrypt(fd, key, iv) cmt = f.read(item.file_size) else: # archive comment with self._open_clear(item) as cmtstream: cmt = cmtstream.read() # rar bug? - appends zero to comment cmt = cmt.split(b"\0", 1)[0] self.comment = cmt.decode("utf8") return None
(self, fd, item)
11,484
rarfile
_open_hack
null
def _open_hack(self, inf, pwd): # len, type, blk_flags, flags main_hdr = b"\x03\x01\x00\x00" endarc_hdr = b"\x03\x05\x00\x00" main_hdr = S_LONG.pack(crc32(main_hdr)) + main_hdr endarc_hdr = S_LONG.pack(crc32(endarc_hdr)) + endarc_hdr return self._open_hack_core(inf, pwd, RAR5_ID + main_hdr, endarc_hdr)
(self, inf, pwd)
11,488
rarfile
_parse_block_common
null
def _parse_block_common(self, h, hdata): h.header_crc, pos = load_le32(hdata, 0) hdrlen, pos = load_vint(hdata, pos) h.header_size = hdrlen + pos h.block_type, pos = load_vint(hdata, pos) h.block_flags, pos = load_vint(hdata, pos) if h.block_flags & RAR5_BLOCK_FLAG_EXTRA_DATA: h.block_extra_size, pos = load_vint(hdata, pos) if h.block_flags & RAR5_BLOCK_FLAG_DATA_AREA: h.add_size, pos = load_vint(hdata, pos) h.compress_size = h.add_size if h.block_flags & RAR5_BLOCK_FLAG_SKIP_IF_UNKNOWN: h.flags |= RAR_SKIP_IF_UNKNOWN if h.block_flags & RAR5_BLOCK_FLAG_DATA_AREA: h.flags |= RAR_LONG_BLOCK return h, pos
(self, h, hdata)
11,489
rarfile
_parse_block_header
Parse common block header
def _parse_block_header(self, fd): """Parse common block header """ header_offset = fd.tell() preload = 4 + 1 start_bytes = fd.read(preload) if len(start_bytes) < preload: self._set_error("Unexpected EOF when reading header") return None while start_bytes[-1] & 0x80: b = fd.read(1) if not b: self._set_error("Unexpected EOF when reading header") return None start_bytes += b header_crc, pos = load_le32(start_bytes, 0) hdrlen, pos = load_vint(start_bytes, pos) if hdrlen > 2 * 1024 * 1024: return None header_size = pos + hdrlen # read full header, check for EOF hdata = start_bytes + fd.read(header_size - len(start_bytes)) if len(hdata) != header_size: self._set_error("Unexpected EOF when reading header") return None data_offset = fd.tell() calc_crc = crc32(memoryview(hdata)[4:]) if header_crc != calc_crc: # header parsing failed. self._set_error("Header CRC error: exp=%x got=%x (xlen = %d)", header_crc, calc_crc, len(hdata)) return None block_type, pos = load_vint(hdata, pos) if block_type == RAR5_BLOCK_MAIN: h, pos = self._parse_block_common(Rar5MainInfo(), hdata) h = self._parse_main_block(h, hdata, pos) elif block_type == RAR5_BLOCK_FILE: h, pos = self._parse_block_common(Rar5FileInfo(), hdata) h = self._parse_file_block(h, hdata, pos) elif block_type == RAR5_BLOCK_SERVICE: h, pos = self._parse_block_common(Rar5ServiceInfo(), hdata) h = self._parse_file_block(h, hdata, pos) elif block_type == RAR5_BLOCK_ENCRYPTION: h, pos = self._parse_block_common(Rar5EncryptionInfo(), hdata) h = self._parse_encryption_block(h, hdata, pos) elif block_type == RAR5_BLOCK_ENDARC: h, pos = self._parse_block_common(Rar5EndArcInfo(), hdata) h = self._parse_endarc_block(h, hdata, pos) else: h = None if h: h.header_offset = header_offset h.data_offset = data_offset return h
(self, fd)
11,490
rarfile
_parse_encryption_block
null
def _parse_encryption_block(self, h, hdata, pos): h.encryption_algo, pos = load_vint(hdata, pos) h.encryption_flags, pos = load_vint(hdata, pos) h.encryption_kdf_count, pos = load_byte(hdata, pos) h.encryption_salt, pos = load_bytes(hdata, 16, pos) if h.encryption_flags & RAR5_ENC_FLAG_HAS_CHECKVAL: h.encryption_check_value, pos = load_bytes(hdata, 12, pos) if h.encryption_algo != RAR5_XENC_CIPHER_AES256: raise BadRarFile("Unsupported header encryption cipher") if h.encryption_check_value and self._password: self._check_password(h.encryption_check_value, h.encryption_kdf_count, h.encryption_salt) self._hdrenc_main = h return h
(self, h, hdata, pos)
11,491
rarfile
_parse_endarc_block
null
def _parse_endarc_block(self, h, hdata, pos): h.endarc_flags, pos = load_vint(hdata, pos) if h.endarc_flags & RAR5_ENDARC_FLAG_NEXT_VOL: h.flags |= RAR_ENDARC_NEXT_VOLUME return h
(self, h, hdata, pos)
11,492
rarfile
_parse_file_block
null
def _parse_file_block(self, h, hdata, pos): h.file_flags, pos = load_vint(hdata, pos) h.file_size, pos = load_vint(hdata, pos) h.mode, pos = load_vint(hdata, pos) if h.file_flags & RAR5_FILE_FLAG_HAS_MTIME: h.mtime, pos = load_unixtime(hdata, pos) h.date_time = h.mtime.timetuple()[:6] if h.file_flags & RAR5_FILE_FLAG_HAS_CRC32: h.CRC, pos = load_le32(hdata, pos) h._md_class = CRC32Context h._md_expect = h.CRC h.file_compress_flags, pos = load_vint(hdata, pos) h.file_host_os, pos = load_vint(hdata, pos) h.orig_filename, pos = load_vstr(hdata, pos) h.filename = h.orig_filename.decode("utf8", "replace").rstrip("/") # use compatible values if h.file_host_os == RAR5_OS_WINDOWS: h.host_os = RAR_OS_WIN32 else: h.host_os = RAR_OS_UNIX h.compress_type = RAR_M0 + ((h.file_compress_flags >> 7) & 7) if h.block_extra_size: # allow 1 byte of garbage while pos < len(hdata) - 1: xsize, pos = load_vint(hdata, pos) xdata, pos = load_bytes(hdata, xsize, pos) self._process_file_extra(h, xdata) if h.block_flags & RAR5_BLOCK_FLAG_SPLIT_BEFORE: h.flags |= RAR_FILE_SPLIT_BEFORE if h.block_flags & RAR5_BLOCK_FLAG_SPLIT_AFTER: h.flags |= RAR_FILE_SPLIT_AFTER if h.file_flags & RAR5_FILE_FLAG_ISDIR: h.flags |= RAR_FILE_DIRECTORY if h.file_compress_flags & RAR5_COMPR_SOLID: h.flags |= RAR_FILE_SOLID if h.is_dir(): h.filename = h.filename + "/" return h
(self, h, hdata, pos)
11,493
rarfile
_parse_file_encryption
null
def _parse_file_encryption(self, h, xdata, pos): algo, pos = load_vint(xdata, pos) flags, pos = load_vint(xdata, pos) kdf_count, pos = load_byte(xdata, pos) salt, pos = load_bytes(xdata, 16, pos) iv, pos = load_bytes(xdata, 16, pos) checkval = None if flags & RAR5_XENC_CHECKVAL: checkval, pos = load_bytes(xdata, 12, pos) if flags & RAR5_XENC_TWEAKED: h._md_expect = None h._md_class = NoHashContext h.file_encryption = (algo, flags, kdf_count, salt, iv, checkval) h.flags |= RAR_FILE_PASSWORD
(self, h, xdata, pos)
11,494
rarfile
_parse_file_hash
null
def _parse_file_hash(self, h, xdata, pos): hash_type, pos = load_vint(xdata, pos) if hash_type == RAR5_XHASH_BLAKE2SP: h.blake2sp_hash, pos = load_bytes(xdata, 32, pos) if (h.file_encryption[1] & RAR5_XENC_TWEAKED) == 0: h._md_class = Blake2SP h._md_expect = h.blake2sp_hash
(self, h, xdata, pos)
11,495
rarfile
_parse_file_owner
null
def _parse_file_owner(self, h, xdata, pos): user_name = group_name = user_id = group_id = None flags, pos = load_vint(xdata, pos) if flags & RAR5_XOWNER_UNAME: user_name, pos = load_vstr(xdata, pos) if flags & RAR5_XOWNER_GNAME: group_name, pos = load_vstr(xdata, pos) if flags & RAR5_XOWNER_UID: user_id, pos = load_vint(xdata, pos) if flags & RAR5_XOWNER_GID: group_id, pos = load_vint(xdata, pos) h.file_owner = (user_name, group_name, user_id, group_id)
(self, h, xdata, pos)
11,496
rarfile
_parse_file_redir
null
def _parse_file_redir(self, h, xdata, pos): redir_type, pos = load_vint(xdata, pos) redir_flags, pos = load_vint(xdata, pos) redir_name, pos = load_vstr(xdata, pos) redir_name = redir_name.decode("utf8", "replace") h.file_redir = (redir_type, redir_flags, redir_name)
(self, h, xdata, pos)
11,497
rarfile
_parse_file_version
null
def _parse_file_version(self, h, xdata, pos): flags, pos = load_vint(xdata, pos) version, pos = load_vint(xdata, pos) h.file_version = (flags, version)
(self, h, xdata, pos)
11,498
rarfile
_parse_file_xtime
null
def _parse_file_xtime(self, h, xdata, pos): tflags, pos = load_vint(xdata, pos) ldr = load_windowstime if tflags & RAR5_XTIME_UNIXTIME: ldr = load_unixtime if tflags & RAR5_XTIME_HAS_MTIME: h.mtime, pos = ldr(xdata, pos) h.date_time = h.mtime.timetuple()[:6] if tflags & RAR5_XTIME_HAS_CTIME: h.ctime, pos = ldr(xdata, pos) if tflags & RAR5_XTIME_HAS_ATIME: h.atime, pos = ldr(xdata, pos) if tflags & RAR5_XTIME_UNIXTIME_NS: if tflags & RAR5_XTIME_HAS_MTIME: nsec, pos = load_le32(xdata, pos) h.mtime = to_nsdatetime(h.mtime, nsec) if tflags & RAR5_XTIME_HAS_CTIME: nsec, pos = load_le32(xdata, pos) h.ctime = to_nsdatetime(h.ctime, nsec) if tflags & RAR5_XTIME_HAS_ATIME: nsec, pos = load_le32(xdata, pos) h.atime = to_nsdatetime(h.atime, nsec)
(self, h, xdata, pos)
11,500
rarfile
_parse_main_block
null
def _parse_main_block(self, h, hdata, pos): h.main_flags, pos = load_vint(hdata, pos) if h.main_flags & RAR5_MAIN_FLAG_HAS_VOLNR: h.main_volume_number, pos = load_vint(hdata, pos) h.flags |= RAR_MAIN_NEWNUMBERING if h.main_flags & RAR5_MAIN_FLAG_SOLID: h.flags |= RAR_MAIN_SOLID if h.main_flags & RAR5_MAIN_FLAG_ISVOL: h.flags |= RAR_MAIN_VOLUME if h.main_flags & RAR5_MAIN_FLAG_RECOVERY: h.flags |= RAR_MAIN_RECOVERY if self._hdrenc_main: h.flags |= RAR_MAIN_PASSWORD if h.main_flags & RAR5_MAIN_FLAG_HAS_VOLNR == 0: h.flags |= RAR_MAIN_FIRSTVOLUME return h
(self, h, hdata, pos)
11,502
rarfile
_process_file_extra
null
def _process_file_extra(self, h, xdata): xtype, pos = load_vint(xdata, 0) if xtype == RAR5_XFILE_TIME: self._parse_file_xtime(h, xdata, pos) elif xtype == RAR5_XFILE_ENCRYPTION: self._parse_file_encryption(h, xdata, pos) elif xtype == RAR5_XFILE_HASH: self._parse_file_hash(h, xdata, pos) elif xtype == RAR5_XFILE_VERSION: self._parse_file_version(h, xdata, pos) elif xtype == RAR5_XFILE_REDIR: self._parse_file_redir(h, xdata, pos) elif xtype == RAR5_XFILE_OWNER: self._parse_file_owner(h, xdata, pos) elif xtype == RAR5_XFILE_SERVICE: pass else: pass
(self, h, xdata)
11,512
rarfile
process_entry
null
def process_entry(self, fd, item): if item.block_type == RAR5_BLOCK_FILE: if item.file_version: pass # skip old versions elif (item.block_flags & RAR5_BLOCK_FLAG_SPLIT_BEFORE) == 0: # use only first part self._info_map[item.filename.rstrip("/")] = item self._info_list.append(item) elif len(self._info_list) > 0: # final crc is in last block old = self._info_list[-1] old.CRC = item.CRC old._md_expect = item._md_expect old.blake2sp_hash = item.blake2sp_hash old.compress_size += item.compress_size elif item.block_type == RAR5_BLOCK_SERVICE: if item.filename == "CMT": self._load_comment(fd, item)
(self, fd, item)
11,516
rarfile
Rar3Info
RAR3 specific fields.
class Rar3Info(RarInfo): """RAR3 specific fields.""" extract_version = 15 salt = None add_size = 0 header_crc = None header_size = None header_offset = None data_offset = None _md_class = None _md_expect = None _name_size = None # make sure some rar5 fields are always present file_redir = None blake2sp_hash = None endarc_datacrc = None endarc_volnr = None def _must_disable_hack(self): if self.type == RAR_BLOCK_FILE: if self.flags & RAR_FILE_PASSWORD: return True elif self.flags & (RAR_FILE_SPLIT_BEFORE | RAR_FILE_SPLIT_AFTER): return True elif self.type == RAR_BLOCK_MAIN: if self.flags & (RAR_MAIN_SOLID | RAR_MAIN_PASSWORD): return True return False def is_dir(self): """Returns True if entry is a directory.""" if self.type == RAR_BLOCK_FILE and not self.is_symlink(): return (self.flags & RAR_FILE_DIRECTORY) == RAR_FILE_DIRECTORY return False def is_symlink(self): """Returns True if entry is a symlink.""" return ( self.type == RAR_BLOCK_FILE and self.host_os == RAR_OS_UNIX and self.mode & 0xF000 == 0xA000 ) def is_file(self): """Returns True if entry is a normal file.""" return ( self.type == RAR_BLOCK_FILE and not (self.is_dir() or self.is_symlink()) )
()
11,517
rarfile
_must_disable_hack
null
def _must_disable_hack(self): if self.type == RAR_BLOCK_FILE: if self.flags & RAR_FILE_PASSWORD: return True elif self.flags & (RAR_FILE_SPLIT_BEFORE | RAR_FILE_SPLIT_AFTER): return True elif self.type == RAR_BLOCK_MAIN: if self.flags & (RAR_MAIN_SOLID | RAR_MAIN_PASSWORD): return True return False
(self)
11,518
rarfile
is_dir
Returns True if entry is a directory.
def is_dir(self): """Returns True if entry is a directory.""" if self.type == RAR_BLOCK_FILE and not self.is_symlink(): return (self.flags & RAR_FILE_DIRECTORY) == RAR_FILE_DIRECTORY return False
(self)
11,519
rarfile
is_file
Returns True if entry is a normal file.
def is_file(self): """Returns True if entry is a normal file.""" return ( self.type == RAR_BLOCK_FILE and not (self.is_dir() or self.is_symlink()) )
(self)
11,520
rarfile
is_symlink
Returns True if entry is a symlink.
def is_symlink(self): """Returns True if entry is a symlink.""" return ( self.type == RAR_BLOCK_FILE and self.host_os == RAR_OS_UNIX and self.mode & 0xF000 == 0xA000 )
(self)
11,521
rarfile
isdir
Returns True if entry is a directory. .. deprecated:: 4.0
def isdir(self): """Returns True if entry is a directory. .. deprecated:: 4.0 """ return self.is_dir()
(self)
11,522
rarfile
needs_password
Returns True if data is stored password-protected.
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
(self)
11,523
rarfile
Rar3Sha1
Emulate buggy SHA1 from RAR3.
class Rar3Sha1: """Emulate buggy SHA1 from RAR3. """ digest_size = 20 block_size = 64 _BLK_BE = struct.Struct(b">16L") _BLK_LE = struct.Struct(b"<16L") __slots__ = ("_nbytes", "_md", "_rarbug") def __init__(self, data=b"", rarbug=False): self._md = sha1() self._nbytes = 0 self._rarbug = rarbug self.update(data) def update(self, data): """Process more data.""" self._md.update(data) bufpos = self._nbytes & 63 self._nbytes += len(data) if self._rarbug and len(data) > 64: dpos = self.block_size - bufpos while dpos + self.block_size <= len(data): self._corrupt(data, dpos) dpos += self.block_size def digest(self): """Return final state.""" return self._md.digest() def hexdigest(self): """Return final state as hex string.""" return self._md.hexdigest() def _corrupt(self, data, dpos): """Corruption from SHA1 core.""" ws = list(self._BLK_BE.unpack_from(data, dpos)) for t in range(16, 80): tmp = ws[(t - 3) & 15] ^ ws[(t - 8) & 15] ^ ws[(t - 14) & 15] ^ ws[(t - 16) & 15] ws[t & 15] = ((tmp << 1) | (tmp >> (32 - 1))) & 0xFFFFFFFF self._BLK_LE.pack_into(data, dpos, *ws)
(data=b'', rarbug=False)
11,524
rarfile
__init__
null
def __init__(self, data=b"", rarbug=False): self._md = sha1() self._nbytes = 0 self._rarbug = rarbug self.update(data)
(self, data=b'', rarbug=False)
11,525
rarfile
_corrupt
Corruption from SHA1 core.
def _corrupt(self, data, dpos): """Corruption from SHA1 core.""" ws = list(self._BLK_BE.unpack_from(data, dpos)) for t in range(16, 80): tmp = ws[(t - 3) & 15] ^ ws[(t - 8) & 15] ^ ws[(t - 14) & 15] ^ ws[(t - 16) & 15] ws[t & 15] = ((tmp << 1) | (tmp >> (32 - 1))) & 0xFFFFFFFF self._BLK_LE.pack_into(data, dpos, *ws)
(self, data, dpos)
11,526
rarfile
digest
Return final state.
def digest(self): """Return final state.""" return self._md.digest()
(self)
11,527
rarfile
hexdigest
Return final state as hex string.
def hexdigest(self): """Return final state as hex string.""" return self._md.hexdigest()
(self)
11,528
rarfile
update
Process more data.
def update(self, data): """Process more data.""" self._md.update(data) bufpos = self._nbytes & 63 self._nbytes += len(data) if self._rarbug and len(data) > 64: dpos = self.block_size - bufpos while dpos + self.block_size <= len(data): self._corrupt(data, dpos) dpos += self.block_size
(self, data)
11,529
rarfile
Rar5BaseFile
Shared sturct for file & service record.
class Rar5BaseFile(Rar5Info): """Shared sturct for file & service record. """ type = -1 file_flags = None file_encryption = (0, 0, 0, b"", b"", b"") file_compress_flags = None file_redir = None file_owner = None file_version = None blake2sp_hash = None def _must_disable_hack(self): if self.flags & RAR_FILE_PASSWORD: return True if self.block_flags & (RAR5_BLOCK_FLAG_SPLIT_BEFORE | RAR5_BLOCK_FLAG_SPLIT_AFTER): return True if self.file_compress_flags & RAR5_COMPR_SOLID: return True if self.file_redir: return True return False
()
11,530
rarfile
_must_disable_hack
null
def _must_disable_hack(self): if self.flags & RAR_FILE_PASSWORD: return True if self.block_flags & (RAR5_BLOCK_FLAG_SPLIT_BEFORE | RAR5_BLOCK_FLAG_SPLIT_AFTER): return True if self.file_compress_flags & RAR5_COMPR_SOLID: return True if self.file_redir: return True return False
(self)
11,531
rarfile
is_dir
Returns True if entry is a directory. .. versionadded:: 4.0
def is_dir(self): """Returns True if entry is a directory. .. versionadded:: 4.0 """ return False
(self)
11,532
rarfile
is_file
Returns True if entry is a normal file. .. versionadded:: 4.0
def is_file(self): """Returns True if entry is a normal file. .. versionadded:: 4.0 """ return False
(self)
11,533
rarfile
is_symlink
Returns True if entry is a symlink. .. versionadded:: 4.0
def is_symlink(self): """Returns True if entry is a symlink. .. versionadded:: 4.0 """ return False
(self)
11,536
rarfile
Rar5EncryptionInfo
RAR5 archive header encryption record.
class Rar5EncryptionInfo(Rar5Info): """RAR5 archive header encryption record. """ type = RAR5_BLOCK_ENCRYPTION encryption_algo = None encryption_flags = None encryption_kdf_count = None encryption_salt = None encryption_check_value = None def needs_password(self): return True
()
11,537
rarfile
_must_disable_hack
null
def _must_disable_hack(self): return False
(self)
11,542
rarfile
needs_password
null
def needs_password(self): return True
(self)
11,543
rarfile
Rar5EndArcInfo
RAR5 end of archive record.
class Rar5EndArcInfo(Rar5Info): """RAR5 end of archive record. """ type = RAR_BLOCK_ENDARC endarc_flags = None
()
11,550
rarfile
Rar5FileInfo
RAR5 file record.
class Rar5FileInfo(Rar5BaseFile): """RAR5 file record. """ type = RAR_BLOCK_FILE def is_symlink(self): """Returns True if entry is a symlink.""" # pylint: disable=unsubscriptable-object return ( self.file_redir is not None and self.file_redir[0] in ( RAR5_XREDIR_UNIX_SYMLINK, RAR5_XREDIR_WINDOWS_SYMLINK, RAR5_XREDIR_WINDOWS_JUNCTION, ) ) def is_file(self): """Returns True if entry is a normal file.""" return not (self.is_dir() or self.is_symlink()) def is_dir(self): """Returns True if entry is a directory.""" if not self.file_redir: if self.file_flags & RAR5_FILE_FLAG_ISDIR: return True return False
()
11,552
rarfile
is_dir
Returns True if entry is a directory.
def is_dir(self): """Returns True if entry is a directory.""" if not self.file_redir: if self.file_flags & RAR5_FILE_FLAG_ISDIR: return True return False
(self)
11,553
rarfile
is_file
Returns True if entry is a normal file.
def is_file(self): """Returns True if entry is a normal file.""" return not (self.is_dir() or self.is_symlink())
(self)
11,554
rarfile
is_symlink
Returns True if entry is a symlink.
def is_symlink(self): """Returns True if entry is a symlink.""" # pylint: disable=unsubscriptable-object return ( self.file_redir is not None and self.file_redir[0] in ( RAR5_XREDIR_UNIX_SYMLINK, RAR5_XREDIR_WINDOWS_SYMLINK, RAR5_XREDIR_WINDOWS_JUNCTION, ) )
(self)
11,557
rarfile
Rar5Info
Shared fields for RAR5 records.
class Rar5Info(RarInfo): """Shared fields for RAR5 records. """ extract_version = 50 header_crc = None header_size = None header_offset = None data_offset = None # type=all block_type = None block_flags = None add_size = 0 block_extra_size = 0 # type=MAIN volume_number = None _md_class = None _md_expect = None def _must_disable_hack(self): return False
()
11,564
rarfile
Rar5MainInfo
RAR5 archive main record.
class Rar5MainInfo(Rar5Info): """RAR5 archive main record. """ type = RAR_BLOCK_MAIN main_flags = None main_volume_number = None def _must_disable_hack(self): if self.main_flags & RAR5_MAIN_FLAG_SOLID: return True return False
()
11,565
rarfile
_must_disable_hack
null
def _must_disable_hack(self): if self.main_flags & RAR5_MAIN_FLAG_SOLID: return True return False
(self)
11,571
rarfile
Rar5ServiceInfo
RAR5 service record.
class Rar5ServiceInfo(Rar5BaseFile): """RAR5 service record. """ type = RAR_BLOCK_SUB
()
11,578
rarfile
RarCRCError
CRC error during unpacking
class RarCRCError(RarExecError): """CRC error during unpacking"""
null
11,579
rarfile
RarCannotExec
Executable not found.
class RarCannotExec(RarExecError): """Executable not found."""
null
11,580
rarfile
RarCreateError
Create error
class RarCreateError(RarExecError): """Create error"""
null
11,581
rarfile
RarExecError
Problem reported by unrar/rar.
class RarExecError(Error): """Problem reported by unrar/rar."""
null
11,582
rarfile
RarExtFile
Base class for file-like object that :meth:`RarFile.open` returns. Provides public methods and common crc checking. Behaviour: - no short reads - .read() and .readinfo() read as much as requested. - no internal buffer, use io.BufferedReader for that.
class RarExtFile(io.RawIOBase): """Base class for file-like object that :meth:`RarFile.open` returns. Provides public methods and common crc checking. Behaviour: - no short reads - .read() and .readinfo() read as much as requested. - no internal buffer, use io.BufferedReader for that. """ name = None #: Filename of the archive entry mode = "rb" _parser = None _inf = None _fd = None _remain = 0 _returncode = 0 _md_context = None _seeking = False def _open_extfile(self, parser, inf): self.name = inf.filename self._parser = parser self._inf = inf if self._fd: self._fd.close() if self._seeking: md_class = NoHashContext else: md_class = self._inf._md_class or NoHashContext self._md_context = md_class() self._fd = None self._remain = self._inf.file_size def read(self, n=-1): """Read all or specified amount of data from archive entry.""" # sanitize count if n is None or n < 0: n = self._remain elif n > self._remain: n = self._remain if n == 0: return b"" buf = [] orig = n while n > 0: # actual read data = self._read(n) if not data: break buf.append(data) self._md_context.update(data) self._remain -= len(data) n -= len(data) data = b"".join(buf) if n > 0: raise BadRarFile("Failed the read enough data: req=%d got=%d" % (orig, len(data))) # done? if not data or self._remain == 0: # self.close() self._check() return data def _check(self): """Check final CRC.""" final = self._md_context.digest() exp = self._inf._md_expect if exp is None: return if final is None: return if self._returncode: check_returncode(self._returncode, "", tool_setup().get_errmap()) if self._remain != 0: raise BadRarFile("Failed the read enough data") if final != exp: raise BadRarFile("Corrupt file - CRC check failed: %s - exp=%r got=%r" % ( self._inf.filename, exp, final)) def _read(self, cnt): """Actual read that gets sanitized cnt.""" raise NotImplementedError("_read") def close(self): """Close open resources.""" super().close() if self._fd: self._fd.close() self._fd = None def __del__(self): """Hook delete to make sure tempfile is removed.""" self.close() def readinto(self, buf): """Zero-copy read directly into buffer. Returns bytes read. """ raise NotImplementedError("readinto") def tell(self): """Return current reading position in uncompressed data.""" return self._inf.file_size - self._remain def seek(self, offset, whence=0): """Seek in data. On uncompressed files, the seeking works by actual seeks so it's fast. On compressed files its slow - forward seeking happens by reading ahead, backwards by re-opening and decompressing from the start. """ # disable crc check when seeking if not self._seeking: self._md_context = NoHashContext() self._seeking = True fsize = self._inf.file_size cur_ofs = self.tell() if whence == 0: # seek from beginning of file new_ofs = offset elif whence == 1: # seek from current position new_ofs = cur_ofs + offset elif whence == 2: # seek from end of file new_ofs = fsize + offset else: raise ValueError("Invalid value for whence") # sanity check if new_ofs < 0: new_ofs = 0 elif new_ofs > fsize: new_ofs = fsize # do the actual seek if new_ofs >= cur_ofs: self._skip(new_ofs - cur_ofs) else: # reopen and seek self._open_extfile(self._parser, self._inf) self._skip(new_ofs) return self.tell() def _skip(self, cnt): """Read and discard data""" empty_read(self, cnt, BSIZE) def readable(self): """Returns True""" return True def writable(self): """Returns False. Writing is not supported. """ return False def seekable(self): """Returns True. Seeking is supported, although it's slow on compressed files. """ return True def readall(self): """Read all remaining data""" # avoid RawIOBase default impl return self.read()
null
11,585
rarfile
_open_extfile
null
def _open_extfile(self, parser, inf): self.name = inf.filename self._parser = parser self._inf = inf if self._fd: self._fd.close() if self._seeking: md_class = NoHashContext else: md_class = self._inf._md_class or NoHashContext self._md_context = md_class() self._fd = None self._remain = self._inf.file_size
(self, parser, inf)
11,586
rarfile
_read
Actual read that gets sanitized cnt.
def _read(self, cnt): """Actual read that gets sanitized cnt.""" raise NotImplementedError("_read")
(self, cnt)
11,592
rarfile
readinto
Zero-copy read directly into buffer. Returns bytes read.
def readinto(self, buf): """Zero-copy read directly into buffer. Returns bytes read. """ raise NotImplementedError("readinto")
(self, buf)
11,597
rarfile
RarFatalError
Fatal error
class RarFatalError(RarExecError): """Fatal error"""
null
11,598
rarfile
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
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) elif info.host_os in (RAR_OS_WIN32, RAR_OS_MSDOS): # only keep R/O attr, except for dirs on win32 if info.mode & DOS_MODE_READONLY and (info.is_file() or not WIN32): st = os.stat(dstfn) new_mode = st.st_mode & ~0o222 os.chmod(dstfn, new_mode) if info.mtime: mtime_ns = to_nsecs(info.mtime) atime_ns = to_nsecs(info.atime) if info.atime else mtime_ns os.utime(dstfn, ns=(atime_ns, mtime_ns))
(file, mode='r', charset=None, info_callback=None, crc_check=True, errors='stop', part_only=False)
11,599
rarfile
__enter__
Open context.
def __enter__(self): """Open context.""" return self
(self)
11,600
rarfile
__exit__
Exit context.
def __exit__(self, typ, value, traceback): """Exit context.""" self.close()
(self, typ, value, traceback)
11,601
rarfile
__init__
null
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()
(self, file, mode='r', charset=None, info_callback=None, crc_check=True, errors='stop', part_only=False)
11,602
rarfile
__iter__
Iterate over members.
def __iter__(self): """Iterate over members.""" return iter(self.infolist())
(self)
11,603
rarfile
_create_helper
null
def _create_helper(self, name, flags, info): return os.open(name, flags)
(self, name, flags, info)
11,604
rarfile
_extract_one
null
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
(self, info, path, pwd, set_attrs)
11,605
rarfile
_make_dir
null
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
(self, info, dstfn, pwd, set_attrs)
11,606
rarfile
_make_file
null
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
(self, info, dstfn, pwd, set_attrs)
11,607
rarfile
_make_symlink
null
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
(self, info, dstfn, pwd, set_attrs)
11,608
rarfile
_parse
Run parser for file type
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
(self)
11,609
rarfile
_set_attrs
null
def _set_attrs(self, info, dstfn): if info.host_os == RAR_OS_UNIX: os.chmod(dstfn, info.mode & 0o777) elif info.host_os in (RAR_OS_WIN32, RAR_OS_MSDOS): # only keep R/O attr, except for dirs on win32 if info.mode & DOS_MODE_READONLY and (info.is_file() or not WIN32): st = os.stat(dstfn) new_mode = st.st_mode & ~0o222 os.chmod(dstfn, new_mode) if info.mtime: mtime_ns = to_nsecs(info.mtime) atime_ns = to_nsecs(info.atime) if info.atime else mtime_ns os.utime(dstfn, ns=(atime_ns, mtime_ns))
(self, info, dstfn)
11,610
rarfile
close
Release open resources.
def close(self): """Release open resources.""" pass
(self)
11,611
rarfile
extract
Extract single file into current directory. Parameters: member filename or :class:`RarInfo` instance path optional destination path pwd optional password to use
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)
(self, member, path=None, pwd=None)
11,612
rarfile
extractall
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
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)
(self, path=None, members=None, pwd=None)
11,613
rarfile
getinfo
Return RarInfo for file.
def getinfo(self, name): """Return RarInfo for file. """ return self._file_parser.getinfo(name)
(self, name)
11,614
rarfile
getinfo_orig
Return RarInfo for file source. RAR5: if name is hard-linked or copied file, returns original entry with original filename. .. versionadded:: 4.1
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)
(self, name)
11,615
rarfile
infolist
Return RarInfo objects for all files/directories in archive.
def infolist(self): """Return RarInfo objects for all files/directories in archive. """ return self._file_parser.infolist()
(self)
11,616
rarfile
is_solid
Returns True if archive uses solid compression. .. versionadded:: 4.2
def is_solid(self): """Returns True if archive uses solid compression. .. versionadded:: 4.2 """ return self._file_parser.is_solid()
(self)
11,617
rarfile
namelist
Return list of filenames in archive.
def namelist(self): """Return list of filenames in archive. """ return [f.filename for f in self.infolist()]
(self)
11,618
rarfile
needs_password
Returns True if any archive entries require password for extraction.
def needs_password(self): """Returns True if any archive entries require password for extraction. """ return self._file_parser.needs_password()
(self)
11,619
rarfile
open
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.
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)
(self, name, mode='r', pwd=None)
11,620
rarfile
printdir
Print archive file list to stdout or given file.
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)
(self, file=None)