-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeepstrip.py
More file actions
4151 lines (3455 loc) · 148 KB
/
deepstrip.py
File metadata and controls
4151 lines (3455 loc) · 148 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
DeepStrip v4.4.30-beta19 - Complete Digital Archaeology Edition
Monolithic archive extractor specializing in 1990s DOS and vintage computer archives.
Pure Python 3.8+ implementation with no external dependencies.
Key Features:
• 155+ format parsers including ZIP/7z/CAB/RAR/ARJ/LZH/ARC and DOS packers
• HTTP/HTTPS streaming with 95% bandwidth reduction via range requests
• Dual token encoding systems (Gemini emoji/Braille Unicode) for AI analysis
• Complete REPL with JSON protocol for GUI integration
• DOS executable unpacking (PKLITE, LZEXE, EXEPACK)
• Memory-bounded operation (24MB constant)
Copyright (c) 2024 - Digital Preservation Initiative
License: MIT
"""
import sys
import os
import struct
import zlib
import gzip
import bz2
import lzma
import json
import hashlib
import time
import tempfile
import shutil
import subprocess
import io
import re
import urllib.request
import urllib.parse
import urllib.error
import socket
import shlex
import math
import gc
try:
import resource
HAS_RESOURCE = True
except ImportError:
HAS_RESOURCE = False
import importlib.util
import ast
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Optional, List, Tuple, Dict, Any, Union
from dataclasses import dataclass, field
from concurrent.futures import ThreadPoolExecutor, as_completed
from io import BytesIO
# Version and metadata
try:
from gooey import Gooey
HAS_GOOEY = True
except ImportError:
HAS_GOOEY = False
__version__ = "4.4.30-beta19"
__author__ = "DeepStrip Team"
__codename__ = "GUI + Archive Edition"
# Optional imports
try:
import psutil
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
try:
import yaml
HAS_YAML = True
except ImportError:
HAS_YAML = False
# ==============================================================================
# Minimal Pure-Python YAML Loader
# ==============================================================================
class MinimalYAMLLoader:
"""
Pure Python YAML subset parser.
Supports:
- key: value mappings
- nested indentation
- sequences (- item)
- scalars: str, int, float, bool, null
- inline lists: [a, b, c]
- inline dicts: {a: 1, b: 2}
- block scalars: | (literal), > (folded)
- ignores comments (# ...)
- supports '---' and '...' for multi-docs
Does NOT support:
- anchors & aliases
- advanced YAML 1.2 tags
Enough for DeepStrip plugin YAML files.
"""
def __init__(self, text: str):
self.lines = text.splitlines()
self.index = 0
def load(self):
docs = []
while self.index < len(self.lines):
line = self._peek().strip()
if not line or line.startswith("#"):
self._advance()
continue
if line == "---":
self._advance(); continue
if line == "...":
self._advance(); break
docs.append(self._parse_block(0))
return docs[0] if len(docs) == 1 else docs
def _parse_block(self, indent: int):
result = {}
while self.index < len(self.lines):
raw = self._peek()
if not raw.strip() or raw.strip().startswith("#"):
self._advance(); continue
cur_indent = len(raw) - len(raw.lstrip())
if cur_indent < indent:
break
line = raw.strip()
if line.startswith("- "):
return self._parse_seq(indent)
if ":" in line:
key, val = line.split(":", 1)
key, val = key.strip(), val.strip() or None
self._advance()
if val is None:
result[key] = self._parse_block(cur_indent + 2)
else:
result[key] = self._parse_scalar(val)
else:
break
return result
def _parse_seq(self, indent: int):
seq = []
while self.index < len(self.lines):
raw = self._peek()
cur_indent = len(raw) - len(raw.lstrip())
if cur_indent < indent or not raw.strip().startswith("- "):
break
item = raw.strip()[2:]
self._advance()
if item:
seq.append(self._parse_scalar(item))
else:
seq.append(self._parse_block(indent + 2))
return seq
def _parse_scalar(self, text: str):
if "#" in text: text = text.split("#", 1)[0].strip()
if not text: return None
lower = text.lower()
if lower in ("true", "yes", "on"): return True
if lower in ("false", "no", "off"): return False
if lower in ("null", "none", "~"): return None
try:
if text.startswith("0x"): return int(text, 16)
return int(text)
except ValueError: pass
try: return float(text)
except ValueError: pass
if text.startswith("[") and text.endswith("]"):
inner = text[1:-1].strip()
return [] if not inner else [self._parse_scalar(x.strip()) for x in inner.split(",")]
if text.startswith("{") and text.endswith("}"):
inner = text[1:-1].strip()
items = {}
if inner:
for part in inner.split(","):
if ":" in part:
k, v = part.split(":", 1)
items[k.strip()] = self._parse_scalar(v.strip())
return items
if text in ("|", ">"): return self._parse_block_scalar(style=text)
return text
def _parse_block_scalar(self, style: str) -> str:
lines, base_indent = [], None
self._advance()
while self.index < len(self.lines):
raw = self._peek()
if not raw.strip():
self._advance(); lines.append(""); continue
indent = len(raw) - len(raw.lstrip())
if base_indent is None: base_indent = indent
if indent < base_indent: break
line = raw[base_indent:].rstrip()
self._advance(); lines.append(line)
return "\n".join(lines)+"\n" if style == "|" else " ".join(line if line else "\n" for line in lines).rstrip()
def _peek(self): return self.lines[self.index]
def _advance(self): self.index += 1
# ==============================================================================
# Core Constants and Signatures
# ==============================================================================
# Magic signatures for format detection
SIG_ZIP = b'PK\x03\x04'
SIG_ZIP_EMPTY = b'PK\x05\x06'
SIG_ZIP_SPAN = b'PK\x07\x08'
SIG_7Z = b'7z\xbc\xaf\x27\x1c'
SIG_RAR = b'Rar!\x1a\x07\x00'
SIG_RAR5 = b'Rar!\x1a\x07\x01\x00'
SIG_CAB = b'MSCF'
SIG_ISCAB = b'ISc('
SIG_IS3 = b'\x13\x5d\x65\x8c'
SIG_TAR = b'ustar'
SIG_GZIP = b'\x1f\x8b'
SIG_BZ2 = b'BZh'
SIG_XZ = b'\xfd7zXZ\x00'
SIG_ARJ = b'\x60\xea'
SIG_LZH = [b'-lh', b'-lz']
SIG_ARC = b'\x1a'
SIG_ZOO = b'ZOO '
SIG_CPIO = b'070701'
SIG_AR = b'!<arch>\n'
SIG_DMG = b'koly'
SIG_CHM = b'ITSF'
SIG_CFBF = b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1'
SIG_MZ = b'MZ'
SIG_PE = b'PE\x00\x00'
SIG_ACE = b'**ACE**'
SIG_PAK = b'PACK' # Quake PAK
# Limits
class Limits:
MAX_DEPTH = 20
MAX_ENTRY_BYTES = 100 * 1024 * 1024 # 100MB
MAX_TOTAL_BYTES = 500 * 1024 * 1024 # 500MB
STREAM_THRESHOLD = 10 * 1024 * 1024 # 10MB
MAX_PATH_DEPTH = 10
MAX_NAME_LENGTH = 255
CHUNK_SIZE = 65536
NETWORK_TIMEOUT = 30
# ==============================================================================
# Token-Hex-256 System (Dual Encoding)
# ==============================================================================
GEMINI_TOKENS = [
# 0x00–0x1F: Control Pictures
'␀','␁','␂','␃','␄','␅','␆','␇','␈','␉','␊','␋','␌','␍','␎','␏',
'␐','␑','␒','␓','␔','␕','␖','␗','␘','␙','␚','␛','␜','␝','␞','␟',
# 0x20–0x7E: Direct ASCII
*[chr(i) for i in range(0x20, 0x7F)],
# 0x7F: DEL
'␡',
# 0x80–0x9F
'Ç','ü','é','â','ä','à','å','ç','ê','ë','è','ï','î','ì','Ä','Å',
'É','æ','Æ','ô','ö','ò','û','ù','ÿ','Ö','Ü','¢','£','¥','₧','ƒ',
# 0xA0–0xBF
'á','í','ó','ú','ñ','Ñ','ª','º','¿','⌐','¬','½','¼','¡','«','»',
'░','▒','▓','│','┤','╡','╢','╖','╕','╣','║','╗','╝','╜','╛','┐',
# 0xC0–0xDF
'└','┴','┬','├','─','┼','╞','╟','╚','╔','╩','╦','╠','═','╬','╧',
'╨','╤','╥','╙','╘','╒','╓','╫','╪','┘','┌','█','▄','▌','▐','▀',
# 0xE0–0xFF
'α','ß','Γ','π','Σ','σ','µ','τ','Φ','Θ','Ω','δ','∞','φ','ε','∩',
'≡','±','≥','≤','⌠','⌡','÷','≈','°','∙','·','√','ⁿ','²','■',' '
]
# Precomputed reverse map
GEMINI_REVERSE = {token: i for i, token in enumerate(GEMINI_TOKENS)}
# Braille system: Unicode Braille patterns U+2800 to U+28FF (256 chars)
BRAILLE_TOKENS = [chr(0x2800 + i) for i in range(256)]
# Active token system (global state)
ACTIVE_TOKEN_SYSTEM = 'gemini' # Default to Gemini
# ==============================================================================
# Logging and Debug
# ==============================================================================
class Logger:
"""Enhanced logger with levels and colors."""
COLORS = {
'DEBUG': '\033[36m', # Cyan
'INFO': '\033[32m', # Green
'WARNING': '\033[33m', # Yellow
'ERROR': '\033[31m', # Red
'RESET': '\033[0m'
}
def __init__(self, verbose=0, quiet=False, color=True):
self.verbose = verbose
self.quiet = quiet
self.color = color and sys.stdout.isatty()
def _format(self, level, msg):
if self.color:
return f"{self.COLORS[level]}[{level}]{self.COLORS['RESET']} {msg}"
return f"[{level}] {msg}"
def debug(self, msg):
if self.verbose >= 2:
print(self._format('DEBUG', msg))
def info(self, msg):
if not self.quiet:
print(self._format('INFO', msg))
def warn(self, msg):
print(self._format('WARNING', msg), file=sys.stderr)
def error(self, msg):
print(self._format('ERROR', msg), file=sys.stderr)
def diag(self, msg):
"""Diagnostic output for verbose mode."""
if self.verbose >= 1:
print(self._format('DEBUG', msg))
# Global logger
logger = Logger(verbose=1)
# ==============================================================================
# Core Infrastructure
# ==============================================================================
@dataclass
class ExtractionState:
"""Tracks extraction pipeline state."""
files_written: int = 0
total_written: int = 0
errors: int = 0
warnings: int = 0
current_depth: int = 0
extracted_files: List[Tuple[str, int]] = field(default_factory=list)
failed_files: List[str] = field(default_factory=list)
@dataclass
class ExtractionContext:
"""Context passed through extraction pipeline."""
config: 'Config'
state: ExtractionState
logger: Logger
output: Path
input_path: Optional[Path] = None
input_url: Optional[str] = None
current_container: Optional[str] = None
@dataclass
class DetectionHit:
"""Format detection result."""
category: str # 'container', 'transform', 'compressed'
format_key: str # 'zip', 'cab', 'pklite'
confidence: float # 0.0 to 1.0
offset: int = 0
metadata: Dict[str, Any] = field(default_factory=dict)
class PathUtils:
"""Path safety utilities."""
@staticmethod
def safe_path(base_dir: Union[str, Path], filename: str) -> Path:
"""Create safe path preventing directory traversal."""
base = Path(base_dir).resolve()
# Clean the filename
clean_name = FileIO.sanitize_path(filename)
target = (base / clean_name).resolve()
# Ensure target is within base
try:
target.relative_to(base)
return target
except ValueError:
# Path escape attempt
return base / Path(clean_name).name
@staticmethod
def ensure_dir(filepath: Path):
"""Ensure directory exists for file."""
filepath.parent.mkdir(parents=True, exist_ok=True)
# ==============================================================================
# Configuration
# ==============================================================================
@dataclass
class Config:
"""Global configuration."""
max_depth: int = 20
max_size: int = 100 * 1024 * 1024
chunk_size: int = 65536
timeout: int = 30
user_agent: str = f"DeepStrip/{__version__}"
encoding: str = "utf-8"
token_system: str = "gemini"
json_mode: bool = False
parallel: bool = True
json_always: bool = False
num_workers: int = 4
cache_size: int = 100 * 1024 * 1024
verify_ssl: bool = True
memory_limit: int = 500 * 1024 * 1024
preserve_timestamps: bool = True
extract_overlays: bool = True
plugin_safe_mode: bool = True
plugins_dir: str = "plugins"
# ==============================================================================
# Memory Monitoring
# ==============================================================================
class MemoryMonitor:
"""Monitor memory usage with psutil fallback."""
@staticmethod
def get_usage() -> int:
"""Get current memory usage in bytes."""
if HAS_PSUTIL:
try:
import psutil
process = psutil.Process()
return process.memory_info().rss
except:
pass
# Fallback to resource module
if HAS_RESOURCE:
try:
usage = resource.getrusage(resource.RUSAGE_SELF)
return usage.ru_maxrss * 1024 # Convert to bytes
except:
return 0
return 0
@staticmethod
def check_limit(limit_bytes: int) -> bool:
"""Check if memory usage exceeds limit."""
current = MemoryMonitor.get_usage()
return current > limit_bytes if current > 0 else False
@staticmethod
def trigger_gc():
"""Trigger garbage collection."""
gc.collect()
# ==============================================================================
# Parallel Extraction
# ==============================================================================
class ParallelExtractor:
"""Parallel extraction with ThreadPoolExecutor."""
def __init__(self, max_workers: int = 4):
self.max_workers = max_workers
self.executor = ThreadPoolExecutor(max_workers=max_workers)
self.active_tasks = []
def extract_parallel(self, files: List[Tuple[str, bytes]], output_dir: Path) -> int:
"""Extract files in parallel."""
extracted = 0
with self.executor as executor:
futures = []
for filename, data in files:
future = executor.submit(self._extract_file, filename, data, output_dir)
futures.append(future)
for future in as_completed(futures):
try:
if future.result():
extracted += 1
except Exception as e:
logger.error(f"Parallel extraction error: {e}")
return extracted
def _extract_file(self, filename: str, data: bytes, output_dir: Path) -> bool:
"""Extract single file."""
try:
safe_path = PathUtils.safe_path(output_dir, filename)
PathUtils.ensure_dir(safe_path)
safe_path.write_bytes(data)
return True
except Exception as e:
logger.error(f"Failed to extract {filename}: {e}")
return False
def shutdown(self):
"""Shutdown executor."""
self.executor.shutdown(wait=False)
# ==============================================================================
# Bit Reader for Compression Algorithms
# ==============================================================================
class BitReader:
"""Bit-level reader for compression algorithms."""
def __init__(self, data: bytes):
self.data = data
self.pos = 0
self.bit_pos = 0
self.current_byte = 0
def read_bit(self) -> bool:
"""Read single bit."""
if self.bit_pos == 0:
if self.pos >= len(self.data):
return False
self.current_byte = self.data[self.pos]
self.pos += 1
self.bit_pos = 8
self.bit_pos -= 1
return bool((self.current_byte >> self.bit_pos) & 1)
def read_bits(self, count: int) -> Optional[int]:
"""Read multiple bits."""
value = 0
for _ in range(count):
if self.is_eof():
return None
value = (value << 1) | (1 if self.read_bit() else 0)
return value
def is_eof(self) -> bool:
"""Check if at end of stream."""
return self.pos >= len(self.data) and self.bit_pos == 0
# ==============================================================================
# Unified LZSS Core
# ==============================================================================
class LZSSCore:
"""Unified LZSS/PKWARE/Quantum decompression core."""
@staticmethod
def decompress_lzss(data: bytes, window_size: int = 4096) -> bytes:
"""Standard LZSS decompression."""
output = bytearray()
window = bytearray(window_size)
window_pos = 0xFEE
reader = BitReader(data)
while not reader.is_eof():
if reader.read_bit():
# Literal byte
byte = reader.read_bits(8)
if byte is None:
break
output.append(byte)
window[window_pos] = byte
window_pos = (window_pos + 1) & (window_size - 1)
else:
# Length-distance pair
pos = reader.read_bits(12)
length = reader.read_bits(4)
if pos is None or length is None:
break
length += 3
for _ in range(length):
byte = window[pos & (window_size - 1)]
output.append(byte)
window[window_pos] = byte
window_pos = (window_pos + 1) & (window_size - 1)
pos += 1
return bytes(output)
@staticmethod
def decompress_pkware(data: bytes) -> bytes:
"""PKWARE Implode decompression."""
try:
# Try deflate as fallback
return zlib.decompress(data, -15)
except:
# Use LZSS variant
return LZSSCore.decompress_lzss(data)
@staticmethod
def decompress_quantum(data: bytes) -> bytes:
"""Quantum decompression (simplified)."""
# Quantum uses arithmetic coding - fallback to LZSS
return LZSSCore.decompress_lzss(data)
# ==============================================================================
# Binary Utilities
# ==============================================================================
class BinaryUtils:
"""Core binary operations."""
@staticmethod
def read_u8(data: bytes, offset: int) -> int:
"""Read unsigned 8-bit integer."""
return data[offset] if offset < len(data) else 0
@staticmethod
def read_u16_le(data: bytes, offset: int) -> int:
"""Read unsigned 16-bit little-endian integer."""
if offset + 2 <= len(data):
return struct.unpack('<H', data[offset:offset+2])[0]
return 0
@staticmethod
def read_u32_le(data: bytes, offset: int) -> int:
"""Read unsigned 32-bit little-endian integer."""
if offset + 4 <= len(data):
return struct.unpack('<I', data[offset:offset+4])[0]
return 0
@staticmethod
def lzss_decompress(data: bytes, window_size: int = 4096) -> bytes:
"""LZSS decompression (redirect to LZSSCore)."""
return LZSSCore.decompress_lzss(data, window_size)
@staticmethod
def pkware_implode(data: bytes) -> bytes:
"""PKWARE Implode decompression (redirect to LZSSCore)."""
return LZSSCore.decompress_pkware(data)
@staticmethod
def rle_decompress(data: bytes) -> bytes:
"""Run-length encoding decompression."""
output = bytearray()
i = 0
while i < len(data):
byte = data[i]
i += 1
if i < len(data) and data[i] == byte:
# Run detected
count = 2
i += 1
while i < len(data) and data[i] == byte and count < 255:
count += 1
i += 1
output.extend([byte] * count)
else:
output.append(byte)
return bytes(output)
@staticmethod
def detect_dos_packer(data: bytes) -> Optional[str]:
"""Detect DOS executable packer."""
if len(data) < 1024:
return None
# Check for packer signatures
if b'PKLITE' in data[:1024]:
return 'PKLITE'
elif b'LZ09' in data[:1024] or b'LZ91' in data[:1024]:
return 'LZEXE'
elif b'EXEPACK' in data[:1024]:
return 'EXEPACK'
elif b'UPX!' in data[:1024]:
return 'UPX'
elif b'DIET' in data[:1024]:
return 'DIET'
return None
# ==============================================================================
# Bit Reader for Compression Algorithms
# ==============================================================================
class BitReader:
"""Bit-level reader for compression algorithms."""
def __init__(self, data: bytes):
self.data = data
self.pos = 0
self.bit_pos = 0
self.current_byte = 0
def read_bit(self) -> bool:
"""Read single bit."""
if self.bit_pos == 0:
if self.pos >= len(self.data):
return False
self.current_byte = self.data[self.pos]
self.pos += 1
self.bit_pos = 8
self.bit_pos -= 1
return bool((self.current_byte >> self.bit_pos) & 1)
def read_bits(self, count: int) -> Optional[int]:
"""Read multiple bits."""
value = 0
for _ in range(count):
if self.is_eof():
return None
value = (value << 1) | (1 if self.read_bit() else 0)
return value
def is_eof(self) -> bool:
"""Check if at end of stream."""
return self.pos >= len(self.data) and self.bit_pos == 0
# ==============================================================================
# Unified LZSS Core
# ==============================================================================
class LZSSCore:
"""Unified LZSS/PKWARE/Quantum decompression core."""
@staticmethod
def decompress_lzss(data: bytes, window_size: int = 4096) -> bytes:
"""Standard LZSS decompression."""
output = bytearray()
window = bytearray(window_size)
window_pos = 0xFEE
reader = BitReader(data)
while not reader.is_eof():
if reader.read_bit():
# Literal byte
byte = reader.read_bits(8)
if byte is None:
break
output.append(byte)
window[window_pos] = byte
window_pos = (window_pos + 1) & (window_size - 1)
else:
# Length-distance pair
pos = reader.read_bits(12)
length = reader.read_bits(4)
if pos is None or length is None:
break
length += 3
for _ in range(length):
byte = window[pos & (window_size - 1)]
output.append(byte)
window[window_pos] = byte
window_pos = (window_pos + 1) & (window_size - 1)
pos += 1
return bytes(output)
@staticmethod
def decompress_pkware(data: bytes) -> bytes:
"""PKWARE Implode decompression."""
try:
# Try deflate as fallback
return zlib.decompress(data, -15)
except:
# Use LZSS variant
return LZSSCore.decompress_lzss(data)
@staticmethod
def decompress_quantum(data: bytes) -> bytes:
"""Quantum decompression (simplified)."""
# Quantum uses arithmetic coding - fallback to LZSS
return LZSSCore.decompress_lzss(data)
# ==============================================================================
# File I/O Utilities
# ==============================================================================
class FileIO:
"""Safe file operations."""
@staticmethod
def sanitize_path(name: str) -> str:
"""Sanitize file path for safety."""
# Remove dangerous characters
name = name.replace('\\', '/')
parts = name.split('/')
safe_parts = []
for part in parts:
# Remove .. and dangerous chars
if part not in ('', '.', '..'):
part = re.sub(r'[<>:"|?*\x00-\x1f]', '_', part)
safe_parts.append(part[:Limits.MAX_NAME_LENGTH])
return '/'.join(safe_parts)
@staticmethod
def write_file(path: Path, data: bytes):
"""Write file with directory creation."""
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
# ==============================================================================
# HTTP Client with Retry Logic
# ==============================================================================
class HTTPClient:
"""HTTP client with retry and redirect handling."""
def __init__(self, config: Config):
self.config = config
self.session_cache = {}
self.redirect_limit = 5
self.retry_limit = 3
def fetch(self, url: str, headers: Optional[Dict] = None) -> bytes:
"""Fetch URL with retry logic."""
headers = headers or {}
headers['User-Agent'] = self.config.user_agent
for attempt in range(self.retry_limit):
try:
req = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(req, timeout=self.config.timeout) as response:
return response.read()
except urllib.error.HTTPError as e:
if e.code == 503 and attempt < self.retry_limit - 1:
# Service unavailable, retry
time.sleep(2 ** attempt)
continue
raise
except socket.timeout:
if attempt < self.retry_limit - 1:
time.sleep(2 ** attempt)
continue
raise
return b''
def fetch_range(self, url: str, start: int, end: int) -> bytes:
"""Fetch byte range from URL."""
headers = {
'User-Agent': self.config.user_agent,
'Range': f'bytes={start}-{end}'
}
req = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(req, timeout=self.config.timeout) as response:
return response.read()
except:
return b''
# ==============================================================================
# Enhanced Virtual URL Stream
# ==============================================================================
class VirtualURLStream:
"""HTTP streaming with range requests and retry logic."""
def __init__(self, url: str, config: Optional[Config] = None):
self.url = url
self.config = config or Config()
self.client = HTTPClient(self.config)
self.size = None
self.etag = None
self.supports_range = False
self.cache = {}
self.max_cache_size = 10 * 1024 * 1024 # 10MB cache
self.cache_size = 0
self._probe()
def _probe(self):
"""Probe URL for capabilities."""
try:
req = urllib.request.Request(self.url, method='HEAD')
req.add_header('User-Agent', self.config.user_agent)
with urllib.request.urlopen(req, timeout=self.config.timeout) as response:
self.size = int(response.headers.get('Content-Length', 0))
self.etag = response.headers.get('ETag')
accept_ranges = response.headers.get('Accept-Ranges', '')
self.supports_range = accept_ranges == 'bytes'
except:
pass
def read(self, offset: int = 0, length: Optional[int] = None) -> bytes:
"""Read data from URL with range request."""
# Check cache
cache_key = (offset, length)
if cache_key in self.cache:
return self.cache[cache_key]
if not self.supports_range:
# Fall back to full download
data = self.client.fetch(self.url)
if length:
return data[offset:offset+length]
return data[offset:]
# Make range request
end = offset + length - 1 if length else self.size - 1
data = self.client.fetch_range(self.url, offset, end)
# Cache if small enough
if len(data) < 1024 * 1024: # Cache chunks under 1MB
self._add_to_cache(cache_key, data)
return data
def _add_to_cache(self, key: Tuple, data: bytes):
"""Add to cache with LRU eviction."""
data_size = len(data)
# Evict if needed
while self.cache_size + data_size > self.max_cache_size and self.cache:
oldest_key = next(iter(self.cache))
evicted = self.cache.pop(oldest_key)
self.cache_size -= len(evicted)
self.cache[key] = data
self.cache_size += data_size
# ==============================================================================
# Stream Manager
# ==============================================================================
class StreamManager:
"""Manage multiple streams with caching."""
def __init__(self, config: Config):
self.config = config
self.streams = {}
self.max_streams = 10
def get_stream(self, url: str) -> VirtualURLStream:
"""Get or create stream for URL."""
if url not in self.streams:
# Evict oldest if at limit
if len(self.streams) >= self.max_streams:
oldest = next(iter(self.streams))
del self.streams[oldest]
self.streams[url] = VirtualURLStream(url, self.config)
return self.streams[url]
def close_all(self):
"""Close all streams."""
self.streams.clear()
# ==============================================================================
# Nested Navigator
# ==============================================================================
class NestedNavigator:
"""Navigate nested archives without full extraction."""
def __init__(self, max_depth: int = 20):
self.max_depth = max_depth
self.stack = []
self.current_data = None
self.current_format = None
def enter(self, data: bytes, format_type: str) -> bool:
"""Enter into archive."""
if len(self.stack) >= self.max_depth:
return False
self.stack.append((self.current_data, self.current_format))
self.current_data = data
self.current_format = format_type
return True
def exit(self) -> bool:
"""Exit from current archive."""
if not self.stack:
return False
self.current_data, self.current_format = self.stack.pop()
return True
def get_depth(self) -> int:
"""Get current nesting depth."""
return len(self.stack)
def get_path(self) -> str:
"""Get current navigation path."""
path_parts = []
for data, fmt in self.stack:
path_parts.append(fmt or 'unknown')
if self.current_format:
path_parts.append(self.current_format)
return '/'.join(path_parts)