Sync bad-date test
[rarfile.git] / dumprar.py
blobb0835c0aad6463d55a37468b9a1db482b1a6f9fb
1 #! /usr/bin/env python3
3 """Dump archive contents, test extraction."""
5 import binascii
6 import getopt
7 import io
8 import sys
9 from datetime import datetime
11 import rarfile as rf
13 usage = """
14 dumprar [switches] [ARC1 ARC2 ...] [@ARCLIST]
15 switches:
16 @file read archive names from file
17 -pPWD set password
18 -Ccharset set fallback charset
19 -v increase verbosity
20 -t attempt to read all files
21 -x write read files out
22 -c show archive comment
23 -h show usage
24 -- stop switch parsing
25 """.strip()
27 os_list = ["DOS", "OS2", "WIN", "UNIX", "MACOS", "BEOS"]
29 block_strs = ["MARK", "MAIN", "FILE", "OLD_COMMENT", "OLD_EXTRA",
30 "OLD_SUB", "OLD_RECOVERY", "OLD_AUTH", "SUB", "ENDARC"]
32 r5_block_types = {
33 rf.RAR5_BLOCK_MAIN: "R5_MAIN",
34 rf.RAR5_BLOCK_FILE: "R5_FILE",
35 rf.RAR5_BLOCK_SERVICE: "R5_SVC",
36 rf.RAR5_BLOCK_ENCRYPTION: "R5_ENC",
37 rf.RAR5_BLOCK_ENDARC: "R5_ENDARC",
41 def rar3_type(btype):
42 """RAR3 type code as string."""
43 if btype < rf.RAR_BLOCK_MARK or btype > rf.RAR_BLOCK_ENDARC:
44 return "*UNKNOWN*"
45 return block_strs[btype - rf.RAR_BLOCK_MARK]
48 def rar5_type(btype):
49 """RAR5 type code as string."""
50 return r5_block_types.get(btype, "*UNKNOWN*")
53 main_bits = (
54 (rf.RAR_MAIN_VOLUME, "VOL"),
55 (rf.RAR_MAIN_COMMENT, "COMMENT"),
56 (rf.RAR_MAIN_LOCK, "LOCK"),
57 (rf.RAR_MAIN_SOLID, "SOLID"),
58 (rf.RAR_MAIN_NEWNUMBERING, "NEWNR"),
59 (rf.RAR_MAIN_AUTH, "AUTH"),
60 (rf.RAR_MAIN_RECOVERY, "RECOVERY"),
61 (rf.RAR_MAIN_PASSWORD, "PASSWORD"),
62 (rf.RAR_MAIN_FIRSTVOLUME, "FIRSTVOL"),
63 (rf.RAR_SKIP_IF_UNKNOWN, "SKIP"),
64 (rf.RAR_LONG_BLOCK, "LONG"),
67 endarc_bits = (
68 (rf.RAR_ENDARC_NEXT_VOLUME, "NEXTVOL"),
69 (rf.RAR_ENDARC_DATACRC, "DATACRC"),
70 (rf.RAR_ENDARC_REVSPACE, "REVSPACE"),
71 (rf.RAR_ENDARC_VOLNR, "VOLNR"),
72 (rf.RAR_SKIP_IF_UNKNOWN, "SKIP"),
73 (rf.RAR_LONG_BLOCK, "LONG"),
76 file_bits = (
77 (rf.RAR_FILE_SPLIT_BEFORE, "SPLIT_BEFORE"),
78 (rf.RAR_FILE_SPLIT_AFTER, "SPLIT_AFTER"),
79 (rf.RAR_FILE_PASSWORD, "PASSWORD"),
80 (rf.RAR_FILE_COMMENT, "COMMENT"),
81 (rf.RAR_FILE_SOLID, "SOLID"),
82 (rf.RAR_FILE_LARGE, "LARGE"),
83 (rf.RAR_FILE_UNICODE, "UNICODE"),
84 (rf.RAR_FILE_SALT, "SALT"),
85 (rf.RAR_FILE_VERSION, "VERSION"),
86 (rf.RAR_FILE_EXTTIME, "EXTTIME"),
87 (rf.RAR_FILE_EXTFLAGS, "EXTFLAGS"),
88 (rf.RAR_SKIP_IF_UNKNOWN, "SKIP"),
89 (rf.RAR_LONG_BLOCK, "LONG"),
92 generic_bits = (
93 (rf.RAR_SKIP_IF_UNKNOWN, "SKIP"),
94 (rf.RAR_LONG_BLOCK, "LONG"),
97 file_parms = ("D64", "D128", "D256", "D512",
98 "D1024", "D2048", "D4096", "DIR")
100 r5_block_flags = (
101 (rf.RAR5_BLOCK_FLAG_EXTRA_DATA, "EXTRA"),
102 (rf.RAR5_BLOCK_FLAG_DATA_AREA, "DATA"),
103 (rf.RAR5_BLOCK_FLAG_SKIP_IF_UNKNOWN, "SKIP"),
104 (rf.RAR5_BLOCK_FLAG_SPLIT_BEFORE, "SPLIT_BEFORE"),
105 (rf.RAR5_BLOCK_FLAG_SPLIT_AFTER, "SPLIT_AFTER"),
106 (rf.RAR5_BLOCK_FLAG_DEPENDS_PREV, "DEPENDS"),
107 (rf.RAR5_BLOCK_FLAG_KEEP_WITH_PARENT, "KEEP"),
110 r5_main_flags = (
111 (rf.RAR5_MAIN_FLAG_ISVOL, "ISVOL"),
112 (rf.RAR5_MAIN_FLAG_HAS_VOLNR, "VOLNR"),
113 (rf.RAR5_MAIN_FLAG_SOLID, "SOLID"),
114 (rf.RAR5_MAIN_FLAG_RECOVERY, "RECOVERY"),
115 (rf.RAR5_MAIN_FLAG_LOCKED, "LOCKED"),
118 r5_file_flags = (
119 (rf.RAR5_FILE_FLAG_ISDIR, "DIR"),
120 (rf.RAR5_FILE_FLAG_HAS_MTIME, "MTIME"),
121 (rf.RAR5_FILE_FLAG_HAS_CRC32, "CRC32"),
122 (rf.RAR5_FILE_FLAG_UNKNOWN_SIZE, "NOSIZE"),
125 r5_enc_flags = (
126 (rf.RAR5_ENC_FLAG_HAS_CHECKVAL, "CHECKVAL"),
129 r5_endarc_flags = (
130 (rf.RAR5_ENDARC_FLAG_NEXT_VOL, "NEXTVOL"),
133 r5_file_enc_flags = (
134 (rf.RAR5_XENC_CHECKVAL, "CHECKVAL"),
135 (rf.RAR5_XENC_TWEAKED, "TWEAKED"),
138 r5_file_redir_types = {
139 rf.RAR5_XREDIR_UNIX_SYMLINK: "UNIX_SYMLINK",
140 rf.RAR5_XREDIR_WINDOWS_SYMLINK: "WINDOWS_SYMLINK",
141 rf.RAR5_XREDIR_WINDOWS_JUNCTION: "WINDOWS_JUNCTION",
142 rf.RAR5_XREDIR_HARD_LINK: "HARD_LINK",
143 rf.RAR5_XREDIR_FILE_COPY: "FILE_COPY",
146 r5_file_redir_flags = (
147 (rf.RAR5_XREDIR_ISDIR, "DIR"),
151 dos_mode_bits = (
152 (0x01, "READONLY"),
153 (0x02, "HIDDEN"),
154 (0x04, "SYSTEM"),
155 (0x08, "VOLUME_ID"),
156 (0x10, "DIRECTORY"),
157 (0x20, "ARCHIVE"),
158 (0x40, "DEVICE"),
159 (0x80, "NORMAL"),
160 (0x0100, "TEMPORARY"),
161 (0x0200, "SPARSE_FILE"),
162 (0x0400, "REPARSE_POINT"),
163 (0x0800, "COMPRESSED"),
164 (0x1000, "OFFLINE"),
165 (0x2000, "NOT_CONTENT_INDEXED"),
166 (0x4000, "ENCRYPTED"),
167 (0x8000, "INTEGRITY_STREAM"),
168 (0x00010000, "VIRTUAL"),
169 (0x00020000, "NO_SCRUB_DATA"),
170 (0x00040000, "RECALL_ON_OPEN"),
171 (0x00080000, "PINNED"),
172 (0x00100000, "UNPINNED"),
173 (0x00400000, "RECALL_ON_DATA_ACCESS"),
174 (0x20000000, "STRICTLY_SEQUENTIAL"),
178 def xprint(m, *args):
179 """Print string to stdout.
181 if args:
182 m = m % args
183 print(m)
186 def tohex(data):
187 """Return hex string."""
188 return binascii.hexlify(data).decode("ascii")
191 def render_flags(flags, bit_list):
192 """Show bit names.
194 res = []
195 known = 0
196 for bit in bit_list:
197 known = known | bit[0]
198 if flags & bit[0]:
199 res.append(bit[1])
200 unknown = flags & ~known
201 n = 0
202 while unknown:
203 if unknown & 1:
204 res.append("UNK_%04x" % (1 << n))
205 unknown = unknown >> 1
206 n += 1
208 if not res:
209 return "-"
211 return ",".join(res)
214 def get_file_flags(flags):
215 """Show flag names and handle dict size.
217 res = render_flags(flags & ~rf.RAR_FILE_DICTMASK, file_bits)
219 xf = (flags & rf.RAR_FILE_DICTMASK) >> 5
220 res += "," + file_parms[xf]
221 return res
224 def fmt_time(t):
225 """Format time.
227 if t is None:
228 return "(-)"
229 if isinstance(t, datetime):
230 return t.isoformat("T")
231 return "%04d-%02d-%02d %02d:%02d:%02d" % t
234 def show_item(h):
235 """Show any RAR3/5 record.
237 if isinstance(h, rf.Rar3Info):
238 show_item_v3(h)
239 elif isinstance(h, rf.Rar5Info):
240 show_item_v5(h)
241 else:
242 xprint("Unknown info record")
245 def show_rftype(h):
246 return "".join([
247 h.is_file() and "F" or "-",
248 h.is_dir() and "D" or "-",
249 h.is_symlink() and "L" or "-",
253 def modex3(v):
254 return [v & 4 and "r" or "-", v & 2 and "w" or "-", v & 1 and "x" or "-"]
257 def unix_mode(mode):
258 perms = modex3(mode >> 6) + modex3(mode >> 3) + modex3(mode)
259 if mode & 0x0800:
260 perms[2] = perms[2] == "x" and "s" or "S"
261 if mode & 0x0400:
262 perms[5] = perms[5] == "x" and "s" or "S"
263 if mode & 0x0200:
264 perms[8] = perms[8] == "x" and "t" or "-"
265 rest = mode & 0xF000
266 if rest == 0x4000:
267 perms.insert(0, "d")
268 elif rest == 0xA000:
269 perms.insert(0, "l")
270 elif rest == 0x8000:
271 # common
272 perms.insert(0, "-")
273 elif rest == 0:
274 perms.insert(0, "-")
275 else:
276 perms.insert(0, "?")
277 perms.append("(0x%04x)" % rest)
278 return "".join(perms)
281 def show_mode(h):
282 if h.host_os in (rf.RAR_OS_UNIX, rf.RAR_OS_BEOS):
283 s_mode = unix_mode(h.mode)
284 elif h.host_os in (rf.RAR_OS_MSDOS, rf.RAR_OS_WIN32, rf.RAR_OS_OS2):
285 s_mode = render_flags(h.mode, dos_mode_bits)
286 else:
287 s_mode = "0x%x" % h.mode
288 return s_mode
291 def show_item_v3(h):
292 """Show any RAR3 record.
294 st = rar3_type(h.type)
295 xprint("%s: hdrlen=%d datlen=%d is=%s",
296 st, h.header_size, h.add_size, show_rftype(h))
297 if h.type in (rf.RAR_BLOCK_FILE, rf.RAR_BLOCK_SUB):
298 s_mode = show_mode(h)
299 xprint(" flags=0x%04x:%s", h.flags, get_file_flags(h.flags))
300 if h.host_os >= 0 and h.host_os < len(os_list):
301 s_os = os_list[h.host_os]
302 else:
303 s_os = "?"
304 if h.flags & rf.RAR_FILE_UNICODE:
305 s_namecmp = " namecmp=%d/%d" % (len(h.orig_filename), h._name_size)
306 else:
307 s_namecmp = ""
308 xprint(" os=%d:%s ver=%d mode=%s meth=%c cmp=%d dec=%d vol=%d%s",
309 h.host_os, s_os,
310 h.extract_version, s_mode, h.compress_type,
311 h.compress_size, h.file_size, h.volume, s_namecmp)
312 ucrc = (h.CRC + (1 << 32)) & ((1 << 32) - 1)
313 xprint(" crc=0x%08x (%d) date_time=%s", ucrc, h.CRC, fmt_time(h.date_time))
314 xprint(" name=%s", h.filename)
315 if h.mtime:
316 xprint(" mtime=%s", fmt_time(h.mtime))
317 if h.ctime:
318 xprint(" ctime=%s", fmt_time(h.ctime))
319 if h.atime:
320 xprint(" atime=%s", fmt_time(h.atime))
321 if h.arctime:
322 xprint(" arctime=%s", fmt_time(h.arctime))
323 elif h.type == rf.RAR_BLOCK_MAIN:
324 xprint(" flags=0x%04x:%s", h.flags, render_flags(h.flags, main_bits))
325 elif h.type == rf.RAR_BLOCK_ENDARC:
326 xprint(" flags=0x%04x:%s", h.flags, render_flags(h.flags, endarc_bits))
327 if h.flags & rf.RAR_ENDARC_DATACRC:
328 xprint(" datacrc=0x%08x", h.endarc_datacrc)
329 if h.flags & rf.RAR_ENDARC_DATACRC:
330 xprint(" volnr=%d", h.endarc_volnr)
331 elif h.type == rf.RAR_BLOCK_MARK:
332 xprint(" flags=0x%04x:", h.flags)
333 else:
334 xprint(" flags=0x%04x:%s", h.flags, render_flags(h.flags, generic_bits))
336 if h.comment is not None:
337 cm = repr(h.comment)
338 if cm[0] == "u":
339 cm = cm[1:]
340 xprint(" comment=%s", cm)
343 def show_item_v5(h):
344 """Show any RAR5 record.
346 st = rar5_type(h.block_type)
347 xprint("%s: hdrlen=%d datlen=%d hdr_extra=%d is=%s", st, h.header_size,
348 h.compress_size, h.block_extra_size, show_rftype(h))
349 xprint(" block_flags=0x%04x:%s", h.block_flags, render_flags(h.block_flags, r5_block_flags))
350 if h.block_type in (rf.RAR5_BLOCK_FILE, rf.RAR5_BLOCK_SERVICE):
351 xprint(" name=%s", h.filename)
352 s_mode = show_mode(h)
353 if h.file_host_os == rf.RAR5_OS_UNIX:
354 s_os = "UNIX"
355 else:
356 s_os = "WINDOWS"
357 xprint(" file_flags=0x%04x:%s", h.file_flags, render_flags(h.file_flags, r5_file_flags))
359 cmp_flags = h.file_compress_flags
360 xprint(" cmp_algo=%d cmp_meth=%d dict=%d solid=%r",
361 cmp_flags & 0x3f,
362 (cmp_flags >> 7) & 0x07,
363 cmp_flags >> 10,
364 cmp_flags & rf.RAR5_COMPR_SOLID > 0)
365 xprint(" os=%d:%s mode=%s cmp=%r dec=%r vol=%r",
366 h.file_host_os, s_os, s_mode,
367 h.compress_size, h.file_size, h.volume)
368 if h.CRC is not None:
369 xprint(" crc=0x%08x (%d)", h.CRC, h.CRC)
370 if h.blake2sp_hash is not None:
371 xprint(" blake2sp=%s", tohex(h.blake2sp_hash))
372 if h.date_time is not None:
373 xprint(" date_time=%s", fmt_time(h.date_time))
374 if h.mtime:
375 xprint(" mtime=%s", fmt_time(h.mtime))
376 if h.ctime:
377 xprint(" ctime=%s", fmt_time(h.ctime))
378 if h.atime:
379 xprint(" atime=%s", fmt_time(h.atime))
380 if h.arctime:
381 xprint(" arctime=%s", fmt_time(h.arctime))
382 if h.flags & rf.RAR_FILE_PASSWORD:
383 enc_algo, enc_flags, kdf_count, salt, iv, checkval = h.file_encryption
384 algo_name = "AES256" if enc_algo == rf.RAR5_XENC_CIPHER_AES256 else "UnknownAlgo"
385 xprint(" algo=%d:%s enc_flags=%04x:%s kdf_lg=%d kdf_count=%d salt=%s iv=%s checkval=%s",
386 enc_algo, algo_name, enc_flags, render_flags(enc_flags, r5_file_enc_flags),
387 kdf_count, 1 << kdf_count, tohex(salt), tohex(iv),
388 checkval and tohex(checkval) or "-")
389 if h.file_redir:
390 redir_type, redir_flags, redir_name = h.file_redir
391 xprint(" redir: type=%s flags=%d:%s destination=%s",
392 r5_file_redir_types.get(redir_type, "Unknown"),
393 redir_flags, render_flags(redir_flags, r5_file_redir_flags),
394 redir_name)
395 if h.file_owner:
396 uname, gname, uid, gid = h.file_owner
397 xprint(" owner: name=%r group=%r uid=%r gid=%r",
398 uname, gname, uid, gid)
399 if h.file_version:
400 flags, version = h.file_version
401 xprint(" version: flags=%r version=%r", flags, version)
402 elif h.block_type == rf.RAR5_BLOCK_MAIN:
403 xprint(" flags=0x%04x:%s", h.flags, render_flags(h.main_flags, r5_main_flags))
404 elif h.block_type == rf.RAR5_BLOCK_ENDARC:
405 xprint(" flags=0x%04x:%s", h.flags, render_flags(h.endarc_flags, r5_endarc_flags))
406 elif h.block_type == rf.RAR5_BLOCK_ENCRYPTION:
407 algo_name = "AES256" if h.encryption_algo == rf.RAR5_XENC_CIPHER_AES256 else "UnknownAlgo"
408 xprint(" algo=%d:%s flags=0x%04x:%s", h.encryption_algo, algo_name, h.flags,
409 render_flags(h.encryption_flags, r5_enc_flags))
410 xprint(" kdf_lg=%d kdf_count=%d", h.encryption_kdf_count, 1 << h.encryption_kdf_count)
411 xprint(" salt=%s", tohex(h.encryption_salt))
412 else:
413 xprint(" - missing info -")
415 if h.comment is not None:
416 cm = repr(h.comment)
417 if cm[0] == "u":
418 cm = cm[1:]
419 xprint(" comment=%s", cm)
422 cf_show_comment = 0
423 cf_verbose = 0
424 cf_charset = None
425 cf_extract = 0
426 cf_test_read = 0
427 cf_test_unrar = 0
428 cf_test_memory = 0
431 def check_crc(f, inf, desc):
432 """Compare result crc to expected value.
434 exp = inf._md_expect
435 if exp is None:
436 return
437 ucrc = f._md_context.digest()
438 if ucrc != exp:
439 print("crc error - %s - exp=%r got=%r" % (desc, exp, ucrc))
442 def test_read_long(r, inf):
443 """Test read and readinto.
445 md_class = inf._md_class or rf.NoHashContext
446 bctx = md_class()
447 f = r.open(inf.filename)
448 total = 0
449 while 1:
450 data = f.read(8192)
451 if not data:
452 break
453 bctx.update(data)
454 total += len(data)
455 if total != inf.file_size:
456 xprint("\n *** %s has corrupt file: %s ***", r.rarfile, inf.filename)
457 xprint(" *** short read: got=%d, need=%d ***\n", total, inf.file_size)
458 check_crc(f, inf, "read")
459 bhash = bctx.hexdigest()
460 if cf_verbose > 1:
461 if f._md_context.digest() == inf._md_expect:
462 #xprint(" checkhash: %r", bhash)
463 pass
464 else:
465 xprint(" checkhash: %r got=%r exp=%r cls=%r\n",
466 bhash, f._md_context.digest(), inf._md_expect, inf._md_class)
468 # test .seek() & .readinto()
469 if cf_test_read > 1:
470 f.seek(0, 0)
472 total = 0
473 buf = bytearray(1024)
474 while 1:
475 res = f.readinto(buf)
476 if not res:
477 break
478 total += res
479 if inf.file_size != total:
480 xprint(" *** readinto failed: got=%d, need=%d ***\n", total, inf.file_size)
481 #check_crc(f, inf, "readinto")
482 f.close()
485 def test_read(r, inf):
486 """Test file read."""
487 test_read_long(r, inf)
490 def test_real(fn, pwd):
491 """Actual archive processing.
493 xprint("Archive: %s", fn)
495 cb = None
496 if cf_verbose > 1:
497 cb = show_item
499 rfarg = fn
500 if cf_test_memory:
501 rfarg = io.BytesIO(open(fn, "rb").read())
503 # check if rar
504 if not rf.is_rarfile(rfarg):
505 xprint(" --- %s is not a RAR file ---", fn)
506 return
508 # open
509 r = rf.RarFile(rfarg, charset=cf_charset, info_callback=cb)
510 # set password
511 if r.needs_password():
512 if pwd:
513 r.setpassword(pwd)
514 else:
515 xprint(" --- %s requires password ---", fn)
516 return
518 # show comment
519 if cf_show_comment and r.comment:
520 for ln in r.comment.split("\n"):
521 xprint(" %s", ln)
522 elif cf_verbose > 0 and r.comment:
523 cm = repr(r.comment)
524 if cm[0] == "u":
525 cm = cm[1:]
526 xprint(" comment=%s", cm)
528 # process
529 for n in r.namelist():
530 inf = r.getinfo(n)
531 if cf_verbose == 1:
532 show_item(inf)
533 if cf_test_read and inf.is_file():
534 test_read(r, inf)
536 if cf_extract:
537 r.extractall()
538 for inf in r.infolist():
539 r.extract(inf)
541 if cf_test_unrar:
542 r.testrar()
545 def test(fn, pwd):
546 """Process one archive with error handling.
548 try:
549 test_real(fn, pwd)
550 except rf.NeedFirstVolume as ex:
551 xprint(" --- %s is middle part of multi-vol archive (%s)---", fn, str(ex))
552 except rf.Error:
553 exc, msg, tb = sys.exc_info()
554 xprint("\n *** %s: %s ***\n", exc.__name__, msg)
555 del tb
556 except IOError:
557 exc, msg, tb = sys.exc_info()
558 xprint("\n *** %s: %s ***\n", exc.__name__, msg)
559 del tb
562 def main():
563 """Program entry point.
565 global cf_verbose, cf_show_comment, cf_charset
566 global cf_extract, cf_test_read, cf_test_unrar
567 global cf_test_memory
569 pwd = None
571 # parse args
572 try:
573 opts, args = getopt.getopt(sys.argv[1:], "p:C:hvcxtRM")
574 except getopt.error as ex:
575 print(str(ex), file=sys.stderr)
576 sys.exit(1)
578 for o, v in opts:
579 if o == "-p":
580 pwd = v
581 elif o == "-h":
582 xprint(usage)
583 return
584 elif o == "-v":
585 cf_verbose += 1
586 elif o == "-c":
587 cf_show_comment = 1
588 elif o == "-x":
589 cf_extract = 1
590 elif o == "-t":
591 cf_test_read += 1
592 elif o == "-T":
593 cf_test_unrar = 1
594 elif o == "-M":
595 cf_test_memory = 1
596 elif o == "-C":
597 cf_charset = v
598 else:
599 raise Exception("unhandled switch: " + o)
601 args2 = []
602 for a in args:
603 if a[0] == "@":
604 for ln in open(a[1:], "r"):
605 fn = ln[:-1]
606 args2.append(fn)
607 else:
608 args2.append(a)
609 args = args2
611 if not args:
612 xprint(usage)
614 for fn in args:
615 test(fn, pwd)
618 if __name__ == "__main__":
619 try:
620 main()
621 except KeyboardInterrupt:
622 pass