-
Notifications
You must be signed in to change notification settings - Fork 763
Expand file tree
/
Copy pathcasc.py
More file actions
1613 lines (1288 loc) · 54.8 KB
/
casc.py
File metadata and controls
1613 lines (1288 loc) · 54.8 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
"""
CASC file formats, based on the work of Caali et al. @
http://www.ownedcore.com/forums/world-of-warcraft/world-of-warcraft-model-editing/471104-analysis-of-casc-filesystem.html
"""
import codecs
import collections
import glob
import hashlib
import io
import math
import mmap
import os
import random
import re
import socket
import struct
import sys
import time
import zlib
import jenkins
import keyfile
import build_cfg
try:
import salsa20
NO_DECRYPT = False
except ImportError as error:
print(
f"WARN: {error}, salsa20 decryption disabled. Install the Python fixedint "
f"(https://pypi.org/project/fixedint/) package to enable",
file=sys.stderr)
NO_DECRYPT = True
try:
import requests
except ImportError as error:
print(
f"ERROR: {error}, casc_extract.py requires the Python requests "
f"(http://docs.python-requests.org/en/master/) package to function",
file=sys.stderr)
sys.exit(1)
_S = requests.Session()
_S.mount('http://', requests.adapters.HTTPAdapter(pool_connections=5))
_BLTE_MAGIC = b'BLTE'
_CHUNK_DATA_OFFSET_LEN = 4
_CHUNK_HEADER_LEN = 4
_CHUNK_HEADER_2_LEN = 8
_CHUNK_SUM_LEN = 16
_MARKER_LEN = 1
_BLOCK_DATA_SIZE = 65535
_NULL_CHUNK = 0x00
_COMPRESSED_CHUNK = 0x5A
_UNCOMPRESSED_CHUNK = 0x4E
_ENCRYPTED_CHUNK = 0x45
_ROOT_MAGIC = b'TSFM'
_ROOT_HEADER = struct.Struct('<4sII')
_ROOT_HEADER_2 = struct.Struct('<III')
_ENCRYPTION_HEADER = struct.Struct('<B8sBIc')
_LOCAL_IDX_HEADER = struct.Struct('<IIHBBBBBBQ8sII')
# Note, hardcodes checksumSize to 8 bytes
_ARCHIVE_IDX_FOOTER = struct.Struct('<8sbbbbbbbbI8s')
_ARCHIVE_IDX_ENTRY = struct.Struct('>16sII')
CDNIndexRecord = collections.namedtuple('CDNIndexRecord',
['index', 'size', 'offset'])
class BLTEChunk:
def __init__(self, id_, chunk_length, output_length, md5s):
self.id = id_
self.chunk_length = chunk_length
self.output_length = output_length
self.sum = md5s
self.has_encryption = False
self.is_decrypted = False
self.output_data = b''
def decrypted(self):
return not self.has_encryption or self.is_decrypted
def extract(self, data):
if len(data) != self.chunk_length:
print(f"Invalid data length for chunk#{self.id}, expected {self.chunk_length} "
f"got {len(data)}",
file=sys.stderr)
return False
type_ = data[0]
if type_ not in [_NULL_CHUNK, _COMPRESSED_CHUNK, _UNCOMPRESSED_CHUNK, _ENCRYPTED_CHUNK]:
print(f"Unknown chunk type {type_:#x} for chunk{self.id} length={len(data)}",
file=sys.stderr)
return False
if type != 0x00:
self.__verify(data)
return self.__process(data)
def __process_compressed(self, data):
dc = zlib.decompressobj()
uncompressed_data = dc.decompress(data[1:])
if len(dc.unused_data) > 0:
print(
f"Unused {len(dc.unused_data)} bytes of compressed data in chunk{self.id}",
file=sys.stderr)
return False
if len(uncompressed_data) != self.output_length:
print(
f"Output chunk data length mismatch in chunk {self.id}, expected "
f"{self.output_length} got {len(uncompressed_data)}",
file=sys.stderr)
return False
self.output_data = uncompressed_data
return True
def __process_encrypted(self, data):
self.has_encryption = True
# Could not import salsa20, write zeros
if NO_DECRYPT:
self.output_data = b'\x00' * self.output_length
return True
offset = 1
key_name_len = struct.unpack_from('<B', data, offset)[0]
offset += 1
if key_name_len != 8:
print(
f"Only key name lengths of 8 bytes are supported for encrypted chunks, "
f"given {key_name_len}",
file=sys.stderr)
return False
key_name = data[offset:offset + key_name_len]
offset += key_name_len
iv_len = struct.unpack_from('<B', data, offset)[0]
offset += 1
if iv_len != 4:
print(
f"Only initial vector lengths of 4 bytes are supported for encrypted chunks, "
f"given {iv_len}",
file=sys.stderr)
return False
iv = data[offset:offset + iv_len]
offset += iv_len
normalized_iv = b''
for i, b in enumerate(iv):
val = (self.id >> (i * 8)) & 0xff
normalized_iv += (b ^ val).to_bytes(1, byteorder='little')
type_ = struct.unpack_from('<c', data, offset)[0]
offset += 1
if type_ != b'S':
print(
f"Only salsa20 encryption supported, given \"{type_.decode('ascii')}\"",
file=sys.stderr)
return False
"""
sys.stderr.write('Encrypted chunk %d, type=%s, key_name_len=%d, key_name=%s, iv_len=%d iv=%s (%s), sz=%d, c_len=%d, o_len=%d offset=%d\n' % (
self.id, type_.decode('ascii'), key_name_len, binascii.hexlify(key_name).decode('ascii'), iv_len,
binascii.hexlify(iv).decode('ascii'), binascii.hexlify(normalized_iv).decode('ascii'),
len(data) - offset, self.chunk_length, self.output_length, offset
))
"""
key = keyfile.find(key_name)
# No encryption key in the database, just write zeros
if not key:
self.output_data = b'\x00' * self.output_length
return True
state = salsa20.initialize(key, normalized_iv)
tmp_data = salsa20.decrypt(state, data[offset:])
self.is_decrypted = True
# Run chunk processing once more, since the decrypted data is now a valid
# chunk to perform (a non-decryption) BLTE operation on
return self.__process(tmp_data, True)
def __process(self, data, recursive=False):
type_ = data[0]
if type_ == _NULL_CHUNK:
self.output_data = b''
elif type_ == _UNCOMPRESSED_CHUNK:
self.output_data = data[1:]
elif type_ == _COMPRESSED_CHUNK:
return self.__process_compressed(data)
elif type_ == _ENCRYPTED_CHUNK:
if recursive:
print("ERROR: Encrypted chunk within encrypted chunk not supported",
file=sys.stderr)
self.output_data = b'\x00' * self.output_length
return False
return self.__process_encrypted(data)
else:
print(f"Unknown chunk {self.id}, type={data[0]:#x}, sz={len(data)}, "
f"out_len={self.output_length}",
file=sys.stderr)
self.output_data = b'\x00' * self.output_length
return True
def __verify(self, data):
md5s = hashlib.md5(data).digest()
if md5s != self.sum:
print(
f"Chunk{self.id} of type {data[0]:#x} fails verification, expects {self.sum.hex()} "
f"got {md5s.hex()}",
file=sys.stderr)
return False
return True
class BLTEFile:
def __init__(self, extractor):
self.data = extractor
self.offset = 0
self.chunks = []
self.output_data = b''
self.extract_status = True
self.data_md5 = None
def add_chunk(self, length, c_length, md5s):
self.chunks.append(BLTEChunk(len(self.chunks), length, c_length, md5s))
def fully_decrypted(self):
return False not in [chunk.decrypted() for chunk in self.chunks]
def __read(self, bytes_):
if isinstance(self.data, BLTEExtract):
return self.data.fd.read(bytes_)
nibble = self.data[self.offset:self.offset + bytes_]
self.offset += bytes_
return nibble
def __seek(self, offset, pos):
if isinstance(self.data, BLTEExtract):
self.data.fd.seek(offset, pos)
else:
if pos == os.SEEK_CUR:
self.offset += offset
elif pos == os.SEEK_SET:
self.offset = offset
elif pos == os.SEEK_END:
self.offset = len(self.data) + offset
def __tell(self):
if isinstance(self.data, BLTEExtract):
return self.data.fd.tell()
return self.offset
def __extract_direct(self):
type_ = self.__read(_MARKER_LEN)
if type_ != _COMPRESSED_CHUNK:
print(f"Direct extraction only supports compressed data, was given {type_:#x}",
file=sys.stderr)
return False
# We don't know where the compressed data ends, so read until it's done
compressed_data = self.__read(_BLOCK_DATA_SIZE)
dc = zlib.decompressobj()
while len(compressed_data) > 0:
self.output_data += dc.decompress(compressed_data)
if len(dc.unused_data) > 0:
# Compressed segment ended at some point, rewind file position
self.__seek(-len(dc.unused_data), os.SEEK_CUR)
break
# More data ..
compressed_data = self.__read(_BLOCK_DATA_SIZE)
return True
def extract(self):
if self.__read(4) != _BLTE_MAGIC:
print("Invalid BLTE magic in file", file=sys.stderr)
return False
chunk_data_offset = struct.unpack('>I', self.__read(_CHUNK_DATA_OFFSET_LEN))[0]
if chunk_data_offset == 0:
if not self.__extract_direct():
return False
else:
unk_1, cc_b1, cc_b2, cc_b3 = struct.unpack('BBBB', self.__read(_CHUNK_HEADER_LEN))
if unk_1 != 0x0F:
print(
f"Unknown magic byte {unk_1} {self.__tell():#x} in BLTE "
f"@{self.__tell() - _CHUNK_HEADER_LEN:#.8x}",
file=sys.stderr)
return False
n_chunks = (cc_b1 << 16) | (cc_b2 << 8) | cc_b3
if n_chunks == 0:
return False
# Chunk information
for chunk_id in range(0, n_chunks):
c_len, out_len = struct.unpack(
'>II', self.__read(_CHUNK_HEADER_2_LEN))
chunk_sum = self.__read(_CHUNK_SUM_LEN)
# print(f"Chunk#{chunk_id}@{self.__tell() - 24}: c_len={c_len} out_len={out_len} "
# f"sum={chunk_sum.hex()}")
self.add_chunk(c_len, out_len, chunk_sum)
# Read chunk data
sum_in_file = 0
for chunk_id in range(0, n_chunks):
chunk = self.chunks[chunk_id]
# print(f"Chunk#{chunk_id}@{self.__tell()}: Data extract len={chunk.chunk_length} "
# f"total={sum_in_file}")
data = self.__read(chunk.chunk_length)
if not chunk.extract(data):
self.extract_status = False
return False
self.output_data += chunk.output_data
sum_in_file += len(chunk.output_data)
return True
def verify(self, md5):
# If we cannot decrypt the BLTE file, we cannot do MD5 validation
if md5 is None or not self.fully_decrypted():
return True
self.data_md5 = hashlib.md5(self.output_data).digest()
return md5 == self.data_md5
class BLTEExtract:
def __init__(self, options):
self.options = options
def open(self, data_file):
if not os.access(data_file, os.R_OK):
self.options.parser.error(f"File {data_file} not readable.")
self.fsize = os.stat(data_file).st_size
if self.fsize == 0:
self.options.parser.error(f"File {data_file} is empty.")
with open(data_file, 'rb') as handle:
self.fdesc = handle
self.fd = mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ)
return True
def close(self):
if self.fd:
self.fd.close()
if self.fdesc:
self.fdesc.close()
def __extract_file(self):
file = BLTEFile(self)
if not file.extract():
return None
return file
def extract_buffer_to_file(self, data, fname, md5=None):
dirname = os.path.dirname(os.path.normpath(fname))
if not os.path.exists(dirname):
os.makedirs(dirname)
data = self.extract_buffer(data, md5)
if not data:
print(f"Unable to extract {os.path.basename(fname)} ...", file=sys.stderr)
return False
with open(fname, 'wb') as f:
f.write(data)
return True
def extract_buffer(self, data, md5=None):
file = BLTEFile(data)
if not file.extract():
return None
if not file.verify(md5):
data_md5 = hashlib.md5(data).digest()
print(
f"Unable to extract buffer, invalid md5ums, got={data_md5.hex()}, "
f"expected={md5.hex()}",
file=sys.stderr)
return None
return file.output_data
def extract_blte_file(self, file_name):
if not self.open(file_name):
return False
if not os.access(self.options.output, os.W_OK):
self.options.parser.error(f"Output file {self.options.output} is not writeable")
file = self.__extract_file()
if not file:
return False
self.close()
return True
def extract_data(self, file_key, file_md5sum, data_file_number,
data_file_offset, blte_file_size):
path = os.path.join(self.options.data_dir, 'Data', 'data', f'data.{data_file_number:03d}')
file_key_hex = codecs.encode(file_key, 'hex').decode()
if not self.open(path):
return None
self.fd.seek(data_file_offset, os.SEEK_SET)
key = self.fd.read(16)
blte_len = struct.unpack('<I', self.fd.read(4))[0]
if blte_len != blte_file_size:
# FIXME: some files don't extract?
# https://github.com/simulationcraft/simc/issues/10033
print(
f'Invalid file length, expected {blte_file_size} got '
f'{blte_len} (for {file_key_hex})'
)
return None
# Key is apparently in reverse byte order, and only 9 bytes of it are relevant (as in the
# index structures)
for idx in range(0, 9):
if file_key[idx] != key[len(key) - 1 - idx]:
self.options.parser.error(
f"Invalid file key for {file_key_hex}, "
f"got {codecs.encode(key, 'hex').decode('utf-8')}")
# Skip 10 bytes of unknown data
self.fd.seek(10, os.SEEK_CUR)
file = self.__extract_file()
if not file:
return None
if not file.verify(file_md5sum):
self.options.parser.error(
f"Invalid md5sum for extracted file, expected {file_md5sum.hex()}"
f" got {file.data_md5.hex()}")
return None
self.close()
return file.output_data
def extract_file(self, file_key, file_md5sum, file_output,
data_file_number, data_file_offset, blte_file_size):
output_path = ''
if file_output:
output_path = os.path.join(self.options.output, file_output)
else:
if file_key:
output_path = os.path.join(self.options.output, file_key.hex())
elif file_md5sum:
output_path = os.path.join(self.options.output,
file_md5sum.hex())
output_dir = os.path.dirname(os.path.abspath(output_path))
try:
if not os.path.exists(output_dir):
os.makedirs(output_dir)
except os.error as e:
self.options.parser.error('Output "%s" is not writable: %s' %
(output_path, e.strerror))
data = self.extract_data(file_key, file_md5sum, data_file_number,
data_file_offset, blte_file_size)
if not data:
return False
try:
with open(output_path, 'wb') as output_file:
output_file.write(data)
except IOError as e:
self.options.parser.error('Output "%s" is not writable: %s' %
(output_path, e.strerror))
return True
class CASCObject:
def __init__(self, options):
self.options = options
def get_url(self, url, headers=None):
attempt = 0
maxAttempts = 5
while attempt < maxAttempts:
r = None
try:
sys.stdout.write('Fetching %s ...\n' % url)
r = _S.get(url, headers=headers)
# Handle a 404 like a communication error, will retry and change the CDN
if r.status_code == 404:
raise Exception('404')
if r.status_code not in [200, 206]:
self.options.parser.error(
'HTTP request for %s returns %u' %
(url, r.status_code))
return r
except Exception as e:
print(
f"Unable to fetch {url} (attempt {attempt}): "
f"{r.reason if r else 'unknown error'}: {e}",
file=sys.stderr)
if attempt + 1 < maxAttempts:
print(f"Retrying {url} ...")
# try a random, different CDN host
# TODO: clean this up
# depending on how this gets called the cdn_host is buried in the build object
if self.cdn_host:
if len(self.cdn_host):
cur_host = ''
for host in self.cdn_host:
if url.find(host):
cur_host = host
if cur_host:
other_hosts = [host for host in self.cdn_host if host != cur_host]
url = url.replace(cur_host, random.choice(other_hosts))
time.sleep(2**attempt)
attempt += 1
elif self.build.cdn_host:
if len(self.build.cdn_host):
cur_host = ''
for host in self.build.cdn_host:
if url.find(host):
cur_host = host
if cur_host:
other_hosts = [host for host in self.build.cdn_host if host != cur_host]
url = url.replace(cur_host, random.choice(other_hosts))
time.sleep(2**attempt)
attempt += 1
else:
print("Problem parsing cdn_host from self")
exit(1)
self.options.parser.error(
'Unable to fetch CDN URL file %s (too many retries), aborting ...' %
url)
def cache_dir(self, path=None):
dir = self.options.cache
if path:
dir = os.path.join(self.options.cache, path)
if not os.path.exists(dir):
try:
os.makedirs(dir)
except os.error as e:
self.options.parser('Unable to make %s: %s' %
(dir, e.strerror))
return dir
def write_cache(self, file, handle):
if handle is None or not handle.seekable() or handle.closed or not handle.readable():
return
try:
handle.seek(0, os.SEEK_SET)
with open(os.path.abspath(file), 'wb') as f:
f.write(handle.read())
except (OSError, ValueError) as err:
self.options.parser(
f'Unable to commit data to cache {file}, {err}')
handle.seek(0, os.SEEK_SET)
def cached_open(self, file, url, headers=None):
handle = None
if not os.path.exists(file):
handle = self.get_url(url, headers)
if handle.status_code < 200 or handle.status_code > 299:
return None, False
return io.BytesIO(handle.content), False
else:
return open(file, 'rb'), True
class BuildCfg:
def __init__(self, handle):
self.handle = handle
for line in self.handle:
mobj = re.match('^([^ ]+)[ ]*=[^A-z0-9]*(.+)',
line.decode('utf-8'))
if not mobj:
continue
data = mobj.group(2)
if ' ' in data:
data = data.split(' ')
key = mobj.group(1).replace('-', '_')
setattr(self, key, data)
class CDNIndex(CASCObject):
def __init__(self, options):
CASCObject.__init__(self, options)
self.cdn_hash = None
self.cdn_host = None
self.cdn_path = None
self.build_cfg_hash = []
self.archives = []
self.cdn_index = {}
self.builds = []
self.version = None
self.build_number = 0
self.build_version = 0
self.cdn_idx = 0
self.bgdl = options.bgdl
# TODO: (More) Option based selectors
def get_build_cfg(self):
return self.builds[0]
def build(self):
return self.version
def root_file(self):
return self.get_build_cfg().root
def encoding_file(self):
return self.get_build_cfg().encoding[0]
def encoding_blte_url(self):
return self.cdn_url('data', self.get_build_cfg().encoding[1])
def patch_base_url(self):
return f'http://us.patch.battle.net:1119/{build_cfg.product_arg_str(self.options)}'
def open_cdns(self):
cdns_url = '%s/cdns' % self.patch_base_url()
handle = self.get_url(cdns_url)
data = handle.text.strip().split('\n')
for line in data:
split = line.split('|')
if split[0] != self.options.region:
continue
self.cdn_path = split[1]
# cdns = [urllib.parse.urlparse(x).netloc for x in split[3].split(' ')]
# self.cdn_host = cdns[-1]
self.cdn_host = split[2].split(' ')
if not self.cdn_path or not self.cdn_host:
sys.stderr.write('Unable to extract CDN information\n')
sys.exit(1)
def cdn_base_url(self):
s = 'http://%s/%s' % (self.cdn_host[self.cdn_idx], self.cdn_path)
self.cdn_idx += 1
if self.cdn_idx == len(self.cdn_host):
self.cdn_idx = 0
return s
def cdn_url(self, type, file):
return '%s/%s/%s/%s/%s' % (self.cdn_base_url(), type, file[:2],
file[2:4], file)
def open_version(self):
version_url = '%s/%s' % (self.patch_base_url(),
'bgdl' if self.bgdl else 'versions')
handle = self.get_url(version_url)
for line in handle.iter_lines():
split = line.decode('utf-8').strip().split('|')
if split[0] != 'us':
continue
if len(split) != 7:
sys.stderr.write(
'Version format mismatch, expected 7 fields, got %d\n' %
len(split))
sys.exit(1)
# The CDN hash name is what we want at this point
self.cdn_hash = split[2]
self.version = split[5]
self.build_number = int(split[4])
version_split = self.version.split('.')
if len(version_split) == 3:
self.build_version = split[6]
# Yank out the build number from the version
elif len(version_split) == 4:
self.build_version = '.'.join(version_split[0:-1])
else:
sys.stderr.write('Unable to parse version from "%s" data\n' %
self.version)
sys.exit(1)
# Also take build configuration information from the versions file
# nowadays, as the "CDN" file builds option may have things like
# background downloader builds in it
self.build_cfg_hash = [
split[1],
]
if not self.cdn_hash:
sys.stderr.write('Invalid version file\n')
sys.exit(1)
print('Current build version: %s [%d]' %
(self.version, self.build_number))
def open_cdn_build_cfg(self):
path = os.path.join(self.cache_dir('config'), self.cdn_hash)
url = self.cdn_url('config', self.cdn_hash)
handle, cached = self.cached_open(path, url)
if not handle:
self.options.parser.error('Unable to fetch CDN configuration')
for line in handle:
mobj = re.match('^archives = (.+)', line.decode('utf-8'))
if mobj:
self.archives = mobj.group(1).split(' ')
continue
mobj = re.match('^builds = (.+)', line.decode('utf-8'))
if mobj:
# Always take the first build configuration
self.build_cfg_hash = mobj.group(1).split(' ')
continue
if not cached:
self.write_cache(path, handle)
def open_build_cfg(self):
if self.options.custom_build is not None:
with open(self.options.custom_build, 'rb') as f:
self.builds.append(BuildCfg(f))
match = re.match(r'WOW-(\d+)patch(\d+\.\d+\.\d+)', self.get_build_cfg().build_name)
if match:
self.build_number = int(match.group(1))
self.version = '{}.{}'.format(match.group(2), self.build_number)
print('Custom build version: %s [%d]' %
(self.version, self.build_number))
else:
self.options.parser.error('Unable to load version from custom build')
return
for cfg in self.build_cfg_hash:
path = os.path.join(self.cache_dir('config'), cfg)
url = self.cdn_url('config', cfg)
handle, cached = self.cached_open(path, url)
if not handle:
self.options.parser.error(
'Unable to fetch build configuration')
self.builds.append(BuildCfg(handle))
if not cached:
self.write_cache(path, handle)
def open_archives(self):
sys.stdout.write('Parsing CDN index files ... \n')
index_cache = self.cache_dir('index')
for idx in range(0, len(self.archives)):
index_file_name = '%s.index' % self.archives[idx]
index_file_path = os.path.join(index_cache, index_file_name)
index_file_url = self.cdn_url('data', index_file_name)
handle, cached = self.cached_open(index_file_path, index_file_url)
if not self.parse_archive(handle, idx):
self.options.parser.error(
'Unable to parse index file %s, aborting ...' %
index_file_name)
if not cached:
self.write_cache(index_file_path, handle)
sys.stdout.write('%u entries\n' % len(self.cdn_index.keys()))
def parse_archive(self, handle, idx):
buf = handle.read()
data_size = len(buf) - _ARCHIVE_IDX_FOOTER.size
offset_footer = data_size
footer = _ARCHIVE_IDX_FOOTER.unpack_from(buf, offset_footer)
toc_csum = footer[0]
version = footer[1]
block_size = footer[4] << 10
key_size = footer[-4]
csum_size = footer[-3]
n_elements = footer[-2]
footer_csum = footer[-1]
if version != 1:
print(f"Unsupported archive index version {version}",
file=sys.stderr)
return False
# Validate footer
buf_footer = buf[offset_footer + csum_size:offset_footer +
_ARCHIVE_IDX_FOOTER.size - csum_size]
buf_footer += b'\x00' * csum_size
footer_digest = hashlib.md5(buf_footer).digest()
if footer_digest[:csum_size] != footer_csum:
print(
f"Footer fails checksum check,"
f" calculated: {footer_digest[:csum_size].hex()}, expected: {footer_csum.hex()}",
file=sys.stderr)
return False
if n_elements == 0:
return True
n_entries_per_block = block_size // _ARCHIVE_IDX_ENTRY.size
n_blocks = int(math.ceil(n_elements / n_entries_per_block))
offset_toc_base = n_blocks * block_size
offset_toc_hash = offset_toc_base + n_blocks * key_size
# Validate toc data
toc_digest = hashlib.md5(buf[offset_toc_base:offset_toc_hash +
n_blocks * csum_size]).digest()
if toc_digest[:csum_size] != toc_csum:
print(
f"Toc fails checksum check,"
f" calculated: {toc_digest[:csum_size].hex()}, expected: {toc_csum.hex()}",
file=sys.stderr)
return False
toc_block_lastkey = []
toc_block_hash = []
for record_idx in range(0, n_blocks):
record_offset = offset_toc_base + record_idx * key_size
toc_block_lastkey.append(buf[record_offset:record_offset +
key_size])
for record_idx in range(0, n_blocks):
record_offset = offset_toc_hash + record_idx * csum_size
toc_block_hash.append(buf[record_offset:record_offset + csum_size])
# Validate block data
for block_idx in range(0, n_blocks):
offset_block = block_idx * block_size
block_digest = hashlib.md5(buf[offset_block:offset_block +
block_size]).digest()
if block_digest[:csum_size] != toc_block_hash[block_idx]:
print(
f"Block #{block_idx} fails checksum check,"
f" calculated: {block_digest[:csum_size].hex()},"
f" expected: {toc_block_hash[block_idx].hex()}",
file=sys.stderr)
return False
block_idx = 0
offset_data = 0
for record_idx in range(0, n_elements):
key, size, offset = _ARCHIVE_IDX_ENTRY.unpack_from(
buf, offset_data)
offset_data += _ARCHIVE_IDX_ENTRY.size
if key in self.cdn_index:
print(
f"Key {key.hex()} (idx={idx}, size={size}, offset={offset}) exists in "
f"index @ ({self.archives[self.cdn_index[key].index]}, "
f"{self.cdn_index[key].size}, {self.cdn_index[key].offset}), overwriting ...",
file=sys.stderr)
self.cdn_index[key] = CDNIndexRecord(idx, size, offset)
if key == toc_block_lastkey[block_idx]:
offset_data += block_size - offset_data % block_size
block_idx += 1
return True
def CheckVersion(self):
self.open_version()
self.open_cdns()
self.open_cdn_build_cfg()
self.open_build_cfg()
return True
def open(self):
self.open_version()
self.open_cdns()
self.open_cdn_build_cfg()
self.open_build_cfg()
self.open_archives()
return True
def fetch_file(self, key):
key_info = self.cdn_index.get(key, None)
handle = None
cached = False
key_file_path = os.path.join(self.cache_dir('data'), key.hex())
if key_info:
key_file_url = self.cdn_url('data', self.archives[key_info.index])
handle, cached = self.cached_open(
key_file_path, key_file_url, {
'Range':
'bytes=%d-%d' %
(key_info.offset, key_info.offset + key_info.size - 1)
})
else:
handle, cached = self.cached_open(
key_file_path,
self.cdn_url('data', key.hex()))
if not handle:
return None
if not cached:
self.write_cache(key_file_path, handle)
return handle.read()
class RibbitIndex(CDNIndex):
def get_url(self, content, headers=None):
if headers or 'http://' in content:
return super().get_url(content, headers)
else:
s = socket.create_connection(('us.version.battle.net', 1119), 10)
s.send(bytes(content + '\r\n', 'ascii'))
return s.makefile('b')
def patch_base_url(self):
return f'v1/products/{build_cfg.product_arg_str(self.options)}'
class CASCDataIndexFile(object):
def __init__(self, options, index, version, file):
self.index = index
self.version = version
self.file = file
self.options = options
def _byte_size(self, sz):
if sz == 8:
return 'Q'
elif sz == 4:
return 'I'
elif sz == 2:
return 'H'
elif sz == 1:
return 'B'
else:
return f'{sz}s'
def open(self):
if not os.access(self.file, os.R_OK):
self.options.parser.error(f"Unable to read index file {self.file}")
with open(self.file, 'rb') as f:
data = f.read()