-
Notifications
You must be signed in to change notification settings - Fork 141
/
u4pak.py
executable file
·1910 lines (1525 loc) · 58.9 KB
/
u4pak.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding=UTF-8
#
# Copyright (c) 2014 Mathias Panzenböck
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ import annotations, with_statement, division, print_function
import os
import io
import sys
import hashlib
import zlib
import math
import argparse
from struct import unpack as st_unpack, pack as st_pack
from collections import OrderedDict
from io import DEFAULT_BUFFER_SIZE
from binascii import hexlify
from typing import NamedTuple, Optional, Tuple, List, Dict, Set, Iterable, Iterator, Callable, IO, Any, Union
try:
import llfuse # type: ignore
except ImportError:
HAS_LLFUSE = False
else:
HAS_LLFUSE = True
HAS_STAT_NS = hasattr(os.stat_result, 'st_atime_ns')
__all__ = 'read_index', 'pack'
# for Python < 3.3 and Windows
def highlevel_sendfile(outfile: io.BufferedWriter, infile: io.BufferedReader, offset: int, size: int) -> None:
infile.seek(offset,0)
buf_size = DEFAULT_BUFFER_SIZE
buf = bytearray(buf_size)
while size > 0:
if size >= buf_size:
n = infile.readinto(buf) or 0
if n < buf_size:
raise IOError("unexpected end of file")
outfile.write(buf)
size -= buf_size
else:
data = infile.read(size) or b''
if len(data) < size:
raise IOError("unexpected end of file")
outfile.write(data)
size = 0
if hasattr(os, 'sendfile'):
def os_sendfile(outfile: io.BufferedWriter, infile: io.BufferedReader, offset: int, size: int) -> None:
try:
out_fd = outfile.fileno()
in_fd = infile.fileno()
except:
highlevel_sendfile(outfile, infile, offset, size)
else:
# size == 0 has special meaning for some sendfile implentations
if size > 0:
os.sendfile(out_fd, in_fd, offset, size)
sendfile = os_sendfile
else:
sendfile = highlevel_sendfile
def raise_check_error(ctx: Optional[Record], message: str) -> None:
if ctx is None:
raise ValueError(message)
elif isinstance(ctx, Record):
raise ValueError("%s: %s" % (ctx.filename, message))
else:
raise ValueError("%s: %s" % (ctx, message))
class FragInfo(object):
__slots__ = '__frags', '__size'
__size: int
__frags: List[Tuple[int, int]]
def __init__(self, size: int, frags: Optional[List[Tuple[int, int]]] = None) -> None:
self.__size = size
self.__frags = []
if frags:
for start, end in frags:
self.add(start, end)
@property
def size(self) -> int:
return self.__size
def __iter__(self) -> Iterator[Tuple[int, int]]:
return iter(self.__frags)
def __len__(self) -> int:
return len(self.__frags)
def __repr__(self) -> str:
return 'FragInfo(%r,%r)' % (self.__size, self.__frags)
def add(self, new_start: int, new_end: int) -> None:
if new_start >= new_end:
return
elif new_start >= self.__size or new_end > self.__size:
raise IndexError("range out of bounds: (%r, %r]" % (new_start, new_end))
frags = self.__frags
for i, (start, end) in enumerate(frags):
if new_end < start:
frags.insert(i, (new_start, new_end))
return
elif new_start <= start:
if new_end <= end:
frags[i] = (new_start, end)
return
elif new_start <= end:
if new_end > end:
new_start = start
else:
continue
j = i+1
n = len(frags)
while j < n:
next_start, next_end = frags[j]
if next_start <= new_end:
j += 1
if next_end > new_end:
new_end = next_end
break
else:
break
frags[i:j] = [(new_start, new_end)]
return
frags.append((new_start, new_end))
def invert(self) -> FragInfo:
inverted = FragInfo(self.__size)
append = inverted.__frags.append
prev_end = 0
for start, end in self.__frags:
if start > prev_end:
append((prev_end, start))
prev_end = end
if self.__size > prev_end:
append((prev_end, self.__size))
return inverted
def free(self) -> int:
free = 0
prev_end = 0
for start, end in self.__frags:
free += start - prev_end
prev_end = end
free += self.__size - prev_end
return free
class Pak(object):
__slots__ = ('version', 'index_offset', 'index_size', 'footer_offset', 'index_sha1', 'mount_point', 'records')
version: int
index_offset: int
index_size: int
footer_offset: int
index_sha1: bytes
mount_point: Optional[str]
records: List[Record]
def __init__(self, version: int, index_offset: int, index_size: int, footer_offset: int, index_sha1: bytes, mount_point: Optional[str] = None, records: Optional[List[Record]] = None) -> None:
self.version = version
self.index_offset = index_offset
self.index_size = index_size
self.footer_offset = footer_offset
self.index_sha1 = index_sha1
self.mount_point = mount_point
self.records = records or []
def __len__(self) -> int:
return len(self.records)
def __iter__(self) -> Iterator[Record]:
return iter(self.records)
def __repr__(self) -> str:
return 'Pak(version=%r, index_offset=%r, index_size=%r, footer_offset=%r, index_sha1=%r, mount_point=%r, records=%r)' % (
self.version, self.index_offset, self.index_size, self.footer_offset, self.index_sha1, self.mount_point, self.records)
def check_integrity(self, stream: io.BufferedReader, callback: Callable[[Optional[Record], str], None] = raise_check_error, ignore_null_checksums: bool = False) -> None:
index_offset = self.index_offset
buf = bytearray(DEFAULT_BUFFER_SIZE)
read_record: Callable[[io.BufferedReader, str], Record]
if self.version == 1:
read_record = read_record_v1
elif self.version == 2:
read_record = read_record_v2
elif self.version == 3:
read_record = read_record_v3
elif self.version == 4:
read_record = read_record_v4
elif self.version == 7:
read_record = read_record_v7
else:
raise ValueError(f'unsupported version: {self.version}')
def check_data(ctx, offset, size, sha1):
if ignore_null_checksums and sha1 == b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00':
return
hasher = hashlib.sha1()
stream.seek(offset, 0)
while size > 0:
if size >= DEFAULT_BUFFER_SIZE:
size -= stream.readinto(buf)
hasher.update(buf)
else:
rest = stream.read(size)
assert rest is not None
hasher.update(rest)
size = 0
if hasher.digest() != sha1:
callback(ctx,
'checksum missmatch:\n'
'\tgot: %s\n'
'\texpected: %s' % (
hasher.hexdigest(),
hexlify(sha1).decode('latin1')))
# test index sha1 sum
check_data("<archive index>", index_offset, self.index_size, self.index_sha1)
for r1 in self:
stream.seek(r1.offset, 0)
r2 = read_record(stream, r1.filename)
# test index metadata
if r2.offset != 0:
callback(r2, 'data record offset field is not 0 but %d' % r2.offset)
if not same_metadata(r1, r2):
callback(r1, 'metadata missmatch:\n%s' % metadata_diff(r1, r2))
if r1.compression_method not in COMPR_METHODS:
callback(r1, 'unknown compression method: 0x%02x' % r1.compression_method)
if r1.compression_method == COMPR_NONE and r1.compressed_size != r1.uncompressed_size:
callback(r1, 'file is not compressed but compressed size (%d) differes from uncompressed size (%d)' %
(r1.compressed_size, r1.uncompressed_size))
if r1.data_offset + r1.compressed_size > index_offset:
callback(None, 'data bleeds into index')
# test file sha1 sum
if ignore_null_checksums and r1.sha1 == b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00':
pass
elif r1.compression_blocks is None:
check_data(r1, r1.data_offset, r1.compressed_size, r1.sha1)
else:
hasher = hashlib.sha1()
base_offset = r1.base_offset
for start_offset, end_offset in r1.compression_blocks:
block_size = end_offset - start_offset
stream.seek(base_offset + start_offset, 0)
data = stream.read(block_size)
hasher.update(data)
if hasher.digest() != r1.sha1:
callback(r1,
'checksum missmatch:\n'
'\tgot: %s\n'
'\texpected: %s' % (
hasher.hexdigest(),
hexlify(r1.sha1).decode('latin1')))
def unpack(self, stream: io.BufferedReader, outdir: str=".", callback: Callable[[str], None] = lambda name: None) -> None:
for record in self:
record.unpack(stream, outdir, callback)
def unpack_only(self, stream: io.BufferedReader, files: Iterable[str], outdir: str = ".", callback: Callable[[str], None] = lambda name: None) -> None:
for record in self:
if shall_unpack(files, record.filename):
record.unpack(stream, outdir, callback)
def frag_info(self) -> FragInfo:
frags = FragInfo(self.footer_offset + 44)
frags.add(self.index_offset, self.index_offset + self.index_size)
frags.add(self.footer_offset, frags.size)
for record in self.records:
frags.add(record.offset, record.data_offset + record.compressed_size)
return frags
def print_list(self, details: bool = False, human: bool = False, delim: str = "\n", sort_key_func: Optional[Callable[[Record], Any]] = None, out: IO[str] = sys.stdout) -> None:
records = self.records
if sort_key_func:
records = sorted(records, key=sort_key_func)
if details:
size_to_str: Callable[[int], str]
if human:
size_to_str = human_size
else:
size_to_str = str
count = 0
sum_size = 0
out.write(" Offset Size Compr-Method Compr-Size SHA1 Name%s" % delim)
for record in records:
size = size_to_str(record.uncompressed_size)
sha1 = hexlify(record.sha1).decode('latin1')
cmeth = record.compression_method
if cmeth == COMPR_NONE:
out.write("%10u %10s - - %s %s%s" % (
record.data_offset, size, sha1, record.filename, delim))
else:
out.write("%10u %10s %12s %10s %s %s%s" % (
record.data_offset, size, COMPR_METHOD_NAMES[cmeth],
size_to_str(record.compressed_size), sha1,
record.filename, delim))
count += 1
sum_size += record.uncompressed_size
out.write("%d file(s) (%s) %s" % (count, size_to_str(sum_size), delim))
else:
for record in records:
out.write("%s%s" % (record.filename, delim))
def print_info(self, human: bool = False, out: IO[str] = sys.stdout) -> None:
size_to_str: Callable[[int], str]
if human:
size_to_str = human_size
else:
size_to_str = str
csize = 0
size = 0
for record in self.records:
csize += record.compressed_size
size += record.uncompressed_size
frags = self.frag_info()
out.write("Pak Version: %d\n" % self.version)
out.write("Index SHA1: %s\n" % hexlify(self.index_sha1).decode('latin1'))
out.write("Mount Point: %s\n" % self.mount_point)
out.write("File Count: %d\n" % len(self.records))
out.write("Archive Size: %10s\n" % size_to_str(frags.size))
out.write("Unallocated Bytes: %10s\n" % size_to_str(frags.free()))
out.write("Sum Compr. Files Size: %10s\n" % size_to_str(csize))
out.write("Sum Uncompr. Files Size: %10s\n" % size_to_str(size))
out.write("\n")
out.write("Fragments (%d):\n" % len(frags))
for start, end in frags:
out.write("\t%10s ... %10s (%10s)\n" % (start, end, size_to_str(end - start)))
def mount(self, stream: io.BufferedReader, mountpt: str, foreground: bool = False, debug: bool = False) -> None:
mountpt = os.path.abspath(mountpt)
ops = Operations(stream, self)
args = ['fsname=u4pak', 'subtype=u4pak', 'ro']
if debug:
foreground = True
args.append('debug')
if not foreground:
deamonize()
llfuse.init(ops, mountpt, args)
try:
llfuse.main()
finally:
llfuse.close()
# compare all metadata except for the filename
def same_metadata(r1: Record, r2: Record) -> bool:
# data records always have offset == 0 it seems, so skip that
return \
r1.compressed_size == r2.compressed_size and \
r1.uncompressed_size == r2.uncompressed_size and \
r1.compression_method == r2.compression_method and \
r1.timestamp == r2.timestamp and \
r1.sha1 == r2.sha1 and \
r1.compression_blocks == r2.compression_blocks and \
r1.encrypted == r2.encrypted and \
r1.compression_block_size == r2.compression_block_size
def metadata_diff(r1: Record, r2: Record) -> str:
diff = []
for attr in ['compressed_size', 'uncompressed_size', 'timestamp', 'encrypted', 'compression_block_size']:
v1 = getattr(r1,attr)
v2 = getattr(r2,attr)
if v1 != v2:
diff.append('\t%s: %r != %r' % (attr, v1, v2))
if r1.sha1 != r2.sha1:
diff.append('\tsha1: %s != %s' % (hexlify(r1.sha1).decode('latin1'), hexlify(r2.sha1).decode('latin1')))
if r1.compression_blocks != r2.compression_blocks:
diff.append('\tcompression_blocks:\n\t\t%r\n\t\t\t!=\n\t\t%r' % (r1.compression_blocks, r2.compression_blocks))
return '\n'.join(diff)
COMPR_NONE = 0x00
COMPR_ZLIB = 0x01
COMPR_BIAS_MEMORY = 0x10
COMPR_BIAS_SPEED = 0x20
COMPR_METHODS: Set[int] = {COMPR_NONE, COMPR_ZLIB, COMPR_BIAS_MEMORY, COMPR_BIAS_SPEED}
COMPR_METHOD_NAMES: Dict[int, str] = {
COMPR_NONE: 'none',
COMPR_ZLIB: 'zlib',
COMPR_BIAS_MEMORY: 'bias memory',
COMPR_BIAS_SPEED: 'bias speed'
}
class Record(NamedTuple):
filename: str
offset: int
compressed_size: int
uncompressed_size: int
compression_method: int
timestamp: Optional[int]
sha1: bytes
compression_blocks: Optional[List[Tuple[int, int]]]
encrypted: bool
compression_block_size: Optional[int]
def sendfile(self, outfile: io.BufferedWriter, infile: io.BufferedReader) -> None:
if self.compression_method == COMPR_NONE:
sendfile(outfile, infile, self.data_offset, self.uncompressed_size)
elif self.compression_method == COMPR_ZLIB:
if self.encrypted:
raise NotImplementedError('zlib decompression with encryption is not implemented yet')
assert self.compression_blocks is not None
base_offset = self.base_offset
for start_offset, end_offset in self.compression_blocks:
block_size = end_offset - start_offset
infile.seek(base_offset + start_offset)
block_content = infile.read(block_size)
assert block_content is not None
block_decompress = zlib.decompress(block_content)
outfile.write(block_decompress)
else:
raise NotImplementedError('decompression is not implemented yet')
@property
def base_offset(self):
return 0
def read(self, data: Union[memoryview, bytes, mmap.mmap], offset: int, size: int) -> Union[bytes, bytearray]:
if self.encrypted:
raise NotImplementedError('decryption is not supported')
if self.compression_method == COMPR_NONE:
uncompressed_size = self.uncompressed_size
if offset >= uncompressed_size:
return b''
i = self.data_offset + offset
j = i + min(uncompressed_size - offset, size)
return data[i:j]
elif self.compression_method == COMPR_ZLIB:
assert self.compression_blocks is not None
base_offset = self.base_offset
buffer = bytearray()
end_offset = offset + size
compression_block_size = self.compression_block_size
assert compression_block_size
start_block_index = offset // compression_block_size
end_block_index = end_offset // compression_block_size
current_offset = compression_block_size * start_block_index
for block_start_offset, block_end_offset in self.compression_blocks[start_block_index:end_block_index + 1]:
block_size = block_end_offset - block_start_offset
block_content = data[base_offset + block_start_offset:base_offset + block_end_offset]
block_decompress = zlib.decompress(block_content)
next_offset = current_offset + len(block_decompress)
if current_offset >= offset:
buffer.extend(block_decompress[:end_offset - current_offset])
else:
buffer.extend(block_decompress[offset - current_offset:end_offset - current_offset])
current_offset = next_offset
return buffer
else:
raise NotImplementedError(f'decompression method {self.compression_method} is not supported')
def unpack(self, stream: io.BufferedReader, outdir: str = ".", callback: Callable[[str], None] = lambda name: None) -> None:
prefix, name = os.path.split(self.filename)
prefix = os.path.join(outdir,prefix)
if not os.path.exists(prefix):
os.makedirs(prefix)
name = os.path.join(prefix,name)
callback(name)
fp: io.BufferedWriter
with open(name, "wb") as fp: # type: ignore
self.sendfile(fp, stream)
@property
def data_offset(self) -> int:
return self.offset + self.header_size
@property
def alloc_size(self) -> int:
return self.header_size + self.compressed_size
@property
def index_size(self) -> int:
name_size = 4 + len(self.filename.replace(os.path.sep,'/').encode('utf-8')) + 1
return name_size + self.header_size
@property
def header_size(self) -> int:
raise NotImplementedError
class RecordV1(Record):
__slots__ = ()
def __new__(cls, filename: str, offset: int, compressed_size: int, uncompressed_size: int, compression_method: int, timestamp: Optional[int], sha1: bytes) -> RecordV1:
return Record.__new__(cls, filename, offset, compressed_size, uncompressed_size,
compression_method, timestamp, sha1, None, False, None) # type: ignore
@property
def header_size(self) -> int:
return 56
class RecordV2(Record):
__slots__ = ()
def __new__(cls, filename: str, offset: int, compressed_size: int, uncompressed_size: int, compression_method: int, sha1: bytes) -> RecordV2:
return Record.__new__(cls, filename, offset, compressed_size, uncompressed_size,
compression_method, None, sha1, None, False, None) # type: ignore
@property
def header_size(self):
return 48
class RecordV3(Record):
__slots__ = ()
def __new__(cls, filename: str, offset: int, compressed_size: int, uncompressed_size: int, compression_method: int, sha1: bytes,
compression_blocks: Optional[List[Tuple[int, int]]], encrypted: bool, compression_block_size: Optional[int]) -> RecordV3:
return Record.__new__(cls, filename, offset, compressed_size, uncompressed_size,
compression_method, None, sha1, compression_blocks, encrypted,
compression_block_size) # type: ignore
@property
def header_size(self) -> int:
size = 53
if self.compression_method != COMPR_NONE:
assert self.compression_blocks is not None
size += len(self.compression_blocks) * 16
return size
# XXX: Don't know at which version exactly the change happens.
# Only know 4 is relative, 7 is absolute.
class RecordV7(RecordV3):
@property
def base_offset(self):
return self.offset
def read_path(stream: io.BufferedReader, encoding: str = 'utf-8') -> str:
path_len, = st_unpack('<i',stream.read(4))
if path_len < 0:
# in at least some format versions, this indicates a UTF-16 path
path_len = -2 * path_len
encoding = 'utf-16le'
return stream.read(path_len).decode(encoding).rstrip('\0').replace('/',os.path.sep)
def pack_path(path: str, encoding: str = 'utf-8') -> bytes:
encoded_path = path.replace(os.path.sep, '/').encode('utf-8') + b'\0'
return st_pack('<I', len(encoded_path)) + encoded_path
def write_path(stream: io.BufferedWriter, path: str, encoding: str = 'utf-8') -> bytes:
data = pack_path(path,encoding)
stream.write(data)
return data
def read_record_v1(stream: io.BufferedReader, filename: str) -> RecordV1:
return RecordV1(filename, *st_unpack('<QQQIQ20s',stream.read(56)))
def read_record_v2(stream: io.BufferedReader, filename: str) -> RecordV2:
return RecordV2(filename, *st_unpack('<QQQI20s',stream.read(48)))
def read_record_v3(stream: io.BufferedReader, filename: str) -> RecordV3:
offset, compressed_size, uncompressed_size, compression_method, sha1 = \
st_unpack('<QQQI20s',stream.read(48))
blocks: Optional[List[Tuple[int, int]]]
if compression_method != COMPR_NONE:
block_count, = st_unpack('<I',stream.read(4))
blocks_bin = st_unpack('<%dQ' % (block_count * 2), stream.read(16 * block_count))
blocks = [(blocks_bin[i], blocks_bin[i+1]) for i in range(0, block_count * 2, 2)]
else:
blocks = None
encrypted, compression_block_size = st_unpack('<BI',stream.read(5))
return RecordV3(filename, offset, compressed_size, uncompressed_size, compression_method,
sha1, blocks, encrypted != 0, compression_block_size) # type: ignore
read_record_v4 = read_record_v3
def read_record_v7(stream: io.BufferedReader, filename: str) -> RecordV3:
offset, compressed_size, uncompressed_size, compression_method, sha1 = \
st_unpack('<QQQI20s',stream.read(48))
blocks: Optional[List[Tuple[int, int]]]
if compression_method != COMPR_NONE:
block_count, = st_unpack('<I',stream.read(4))
blocks_bin = st_unpack('<%dQ' % (block_count * 2), stream.read(16 * block_count))
blocks = [(blocks_bin[i], blocks_bin[i+1]) for i in range(0, block_count * 2, 2)]
else:
blocks = None
encrypted, compression_block_size = st_unpack('<BI',stream.read(5))
return RecordV7(filename, offset, compressed_size, uncompressed_size, compression_method,
sha1, blocks, encrypted != 0, compression_block_size) # type: ignore
def write_data(
archive: io.BufferedWriter,
fh: io.BufferedReader,
size: int,
compression_method: int = COMPR_NONE,
encrypted: bool = False,
compression_block_size: int = 0
) -> Tuple[int, bytes]:
if compression_method != COMPR_NONE:
raise NotImplementedError("compression is not implemented")
if encrypted:
raise NotImplementedError("encryption is not implemented")
buf_size = DEFAULT_BUFFER_SIZE
buf = bytearray(buf_size)
bytes_left = size
hasher = hashlib.sha1()
while bytes_left > 0:
data: Union[bytes, bytearray]
if bytes_left >= buf_size:
n = fh.readinto(buf)
data = buf
if n is None or n < buf_size:
raise IOError('unexpected end of file')
else:
opt_data = fh.read(bytes_left)
assert opt_data is not None
n = len(opt_data)
if n < bytes_left:
raise IOError('unexpected end of file')
data = opt_data
bytes_left -= n
hasher.update(data)
archive.write(data)
return size, hasher.digest()
def write_data_zlib(
archive: io.BufferedWriter,
fh: io.BufferedReader,
size: int,
compression_method: int = COMPR_NONE,
encrypted: bool = False,
compression_block_size: int = 65536
) -> Tuple[int, bytes, int, List[int]]:
if encrypted:
raise NotImplementedError("encryption is not implemented")
buf_size = compression_block_size
block_count = int(math.ceil(size / compression_block_size))
base_offset = archive.tell()
archive.write(st_pack('<I',block_count))
# Seek Skip Offset
archive.seek(block_count * 8 * 2, 1)
record = st_pack('<BI', int(encrypted), compression_block_size)
archive.write(record)
cur_offset = base_offset + 4 + block_count * 8 * 2 + 5
compress_blocks = [0] * block_count * 2
compressed_size = 0
compress_block_no = 0
buf = bytearray(buf_size)
bytes_left: int = size
hasher = hashlib.sha1()
while bytes_left > 0:
n: int
if bytes_left >= buf_size:
n = fh.readinto(buf) or 0
data = zlib.compress(memoryview(buf))
compressed_size += len(data)
compress_blocks[compress_block_no * 2] = cur_offset
cur_offset += len(data)
compress_blocks[compress_block_no * 2 + 1] = cur_offset
compress_block_no += 1
if n < buf_size:
raise IOError('unexpected end of file')
else:
data = fh.read(bytes_left) or b''
n = len(data)
data = zlib.compress(data)
compressed_size += len(data)
compress_blocks[compress_block_no * 2] = cur_offset
cur_offset += len(data)
compress_blocks[compress_block_no * 2 + 1] = cur_offset
compress_block_no += 1
if n < bytes_left:
raise IOError('unexpected end of file')
bytes_left -= n
hasher.update(data)
archive.write(data)
cur_offset = archive.tell()
archive.seek(base_offset + 4, 0)
archive.write(st_pack('<%dQ' % (block_count * 2), *compress_blocks))
archive.seek(cur_offset, 0)
return compressed_size, hasher.digest(), block_count, compress_blocks
def write_record_v1(
archive: io.BufferedWriter,
fh: io.BufferedReader,
compression_method: int = COMPR_NONE,
encrypted: bool = False,
compression_block_size: int = 0) -> bytes:
if encrypted:
raise ValueError('version 1 does not support encryption')
record_offset = archive.tell()
st = os.fstat(fh.fileno())
size = st.st_size
# XXX: timestamp probably needs multiplication with some factor?
record = st_pack('<16xQIQ20x',size,compression_method,int(st.st_mtime))
archive.write(record)
compressed_size, sha1 = write_data(archive,fh,size,compression_method,encrypted,compression_block_size)
data_end = archive.tell()
archive.seek(record_offset+8, 0)
archive.write(st_pack('<Q',compressed_size))
archive.seek(record_offset+36, 0)
archive.write(sha1)
archive.seek(data_end, 0)
return st_pack('<QQQIQ20s',record_offset,compressed_size,size,compression_method,int(st.st_mtime),sha1)
def write_record_v2(
archive: io.BufferedWriter,
fh: io.BufferedReader,
compression_method: int = COMPR_NONE,
encrypted: bool = False,
compression_block_size: int = 0) -> bytes:
if encrypted:
raise ValueError('version 2 does not support encryption')
record_offset = archive.tell()
st = os.fstat(fh.fileno())
size = st.st_size
record = st_pack('<16xQI20x',size,compression_method)
archive.write(record)
compressed_size, sha1 = write_data(archive,fh,size,compression_method,encrypted,compression_block_size)
data_end = archive.tell()
archive.seek(record_offset+8, 0)
archive.write(st_pack('<Q',compressed_size))
archive.seek(record_offset+28, 0)
archive.write(sha1)
archive.seek(data_end, 0)
return st_pack('<QQQI20s',record_offset,compressed_size,size,compression_method,sha1)
def write_record_v3(
archive: io.BufferedWriter,
fh: io.BufferedReader,
compression_method: int = COMPR_NONE,
encrypted: bool = False,
compression_block_size: int = 0) -> bytes:
if compression_method != COMPR_NONE and compression_method != COMPR_ZLIB:
raise NotImplementedError("compression is not implemented")
record_offset = archive.tell()
if compression_block_size == 0 and compression_method == COMPR_ZLIB:
compression_block_size = 65536
st = os.fstat(fh.fileno())
size = st.st_size
record = st_pack('<16xQI20x',size,compression_method)
archive.write(record)
if compression_method == COMPR_ZLIB:
compressed_size, sha1, block_count, blocks = write_data_zlib(archive,fh,size,compression_method,encrypted,compression_block_size)
else:
record = st_pack('<BI',int(encrypted),compression_block_size)
archive.write(record)
compressed_size, sha1 = write_data(archive,fh,size,compression_method,encrypted,compression_block_size)
data_end = archive.tell()
archive.seek(record_offset+8, 0)
archive.write(st_pack('<Q',compressed_size))
archive.seek(record_offset+28, 0)
archive.write(sha1)
archive.seek(data_end, 0)
if compression_method == COMPR_ZLIB:
return st_pack('<QQQI20s',record_offset,compressed_size,size,compression_method,sha1) + st_pack('<I%dQ' % (block_count * 2), block_count, *blocks) + st_pack('<BI',int(encrypted),compression_block_size)
else:
return st_pack('<QQQI20sBI',record_offset,compressed_size,size,compression_method,sha1,int(encrypted),compression_block_size)
def read_index(
stream: io.BufferedReader,
check_integrity: bool = False,
ignore_magic: bool = False,
encoding: str = 'utf-8',
force_version: Optional[int] = None,
ignore_null_checksums: bool = False) -> Pak:
stream.seek(-44, 2)
footer_offset = stream.tell()
footer = stream.read(44)
magic, version, index_offset, index_size, index_sha1 = st_unpack('<IIQQ20s',footer)
if not ignore_magic and magic != 0x5A6F12E1:
raise ValueError('illegal file magic: 0x%08x' % magic)
if force_version is not None:
version = force_version
read_record: Callable[[io.BufferedReader, str], Record]
if version == 1:
read_record = read_record_v1
elif version == 2:
read_record = read_record_v2
elif version == 3:
read_record = read_record_v3
elif version == 4:
read_record = read_record_v4
elif version == 7:
read_record = read_record_v7
else:
raise ValueError('unsupported version: %d' % version)
if index_offset + index_size > footer_offset:
raise ValueError('illegal index offset/size')
stream.seek(index_offset, 0)
mount_point = read_path(stream, encoding)
entry_count = st_unpack('<I',stream.read(4))[0]
pak = Pak(version, index_offset, index_size, footer_offset, index_sha1, mount_point)
for i in range(entry_count):
filename = read_path(stream, encoding)
record = read_record(stream, filename)
pak.records.append(record)
if stream.tell() > footer_offset:
raise ValueError('index bleeds into footer')
if check_integrity:
pak.check_integrity(stream, ignore_null_checksums=ignore_null_checksums)
return pak
def _pack_callback(name: str, files: List[str]) -> None:
pass
def pack(stream: io.BufferedWriter, files_or_dirs: List[str], mount_point: str, version: int = 3, compression_method: int = COMPR_NONE,
encrypted: bool = False, compression_block_size: int = 0, callback: Callable[[str, List[str]], None] = _pack_callback,
encoding: str='utf-8') -> None:
if version == 1:
write_record = write_record_v1
elif version == 2:
write_record = write_record_v2
elif version == 3:
write_record = write_record_v3
else:
raise ValueError('version not supported: %d' % version)
files: List[str] = []
for name in files_or_dirs:
if os.path.isdir(name):
for dirpath, dirnames, filenames in os.walk(name):
for filename in filenames:
files.append(os.path.join(dirpath,filename))
else:
files.append(name)
files.sort()
records: List[Tuple[str, bytes]] = []
for filename in files:
callback(filename, files)
fh: io.BufferedReader
with open(filename, "rb") as fh: # type: ignore
record = write_record(stream, fh, compression_method, encrypted, compression_block_size)
records.append((filename, record))
write_index(stream,version,mount_point,records,encoding)
def write_index(stream: IO[bytes], version: int, mount_point: str, records: List[Tuple[str, bytes]], encoding: str = 'utf-8') -> None:
hasher = hashlib.sha1()
index_offset = stream.tell()
index_header = pack_path(mount_point, encoding) + st_pack('<I',len(records))
index_size = len(index_header)
hasher.update(index_header)
stream.write(index_header)
for filename, record in records:
encoded_filename = pack_path(filename, encoding)
hasher.update(encoded_filename)
stream.write(encoded_filename)
index_size += len(encoded_filename)
hasher.update(record)
stream.write(record)
index_size += len(record)
index_sha1 = hasher.digest()
stream.write(st_pack('<IIQQ20s', 0x5A6F12E1, version, index_offset, index_size, index_sha1))
def make_record_v1(filename: str) -> RecordV1:
st = os.stat(filename)
size = st.st_size
return RecordV1(filename, -1, size, size, COMPR_NONE, int(st.st_mtime), b'') # type: ignore