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
use bzip2::read::BzDecoder;
use flate2::bufread::GzDecoder;
use memmap2::Mmap;
use osrs_bytes::ReadExt;
use std::{
cmp,
collections::{BTreeMap, HashMap},
ffi::CStr,
fs::File,
io::{self, Cursor, Read},
mem,
os::raw::c_char,
path::Path,
};
use thiserror::Error;
use tracing::trace;
fn djb2_hash<T: AsRef<str>>(string: T) -> u32 {
let string = string.as_ref().as_bytes();
let mut hash: u32 = 0;
for char in string {
hash = *char as u32 + ((hash << 5).wrapping_sub(hash));
}
hash
}
#[derive(Error, Debug)]
pub enum CacheError {
#[error("data store disconnected")]
Disconnect(#[from] io::Error),
#[error("the data for key `{0}` is not available")]
Redaction(String),
#[error("invalid header (expected {expected:?}, found {found:?})")]
InvalidHeader { expected: String, found: String },
#[error("unknown data store error")]
Unknown,
}
struct DiskStore {
root: String,
data: Mmap,
music_data: Option<Mmap>,
indexes: HashMap<usize, Mmap>,
legacy: bool,
}
struct FlatFileStore {}
impl FlatFileStore {
pub fn open(path: &str) -> FlatFileStore {
FlatFileStore {}
}
}
impl Store for DiskStore {
fn list(&self, archive: u8) -> Vec<u8> {
todo!()
}
fn read(&self, archive: u8, group: u16) -> Vec<u8> {
todo!()
}
}
impl Store for FlatFileStore {
fn list(&self, archive: u8) -> Vec<u8> {
todo!()
}
fn read(&self, archive: u8, group: u16) -> Vec<u8> {
todo!()
}
}
enum StorageType {
Disk(DiskStore),
FlatFile(FlatFileStore),
}
impl DiskStore {
pub fn open(path: &str) -> DiskStore {
let js5_data_path = Path::new(path).join(DATA_PATH);
let legacy_data_path = Path::new(path).join(LEGACY_DATA_PATH);
let legacy = !js5_data_path.exists();
let data_path = if legacy {
legacy_data_path
} else {
js5_data_path
};
let data = unsafe { Mmap::map(&File::open(data_path).unwrap()) }.unwrap();
let music_data_path = Path::new(path).join(MUSIC_DATA_PATH);
let music_data = if music_data_path.exists() {
Some(unsafe { Mmap::map(&File::open(music_data_path).unwrap()).unwrap() })
} else {
None
};
let mut archives = HashMap::new();
for i in 0..MAX_ARCHIVE + 1 {
let path = format!("{}{}", INDEX_PATH, i);
if Path::new(&path).exists() {
let index = unsafe { Mmap::map(&File::open(&path).unwrap()).unwrap() };
archives.insert(i, index);
}
}
DiskStore {
root: path.to_string(),
data,
music_data,
indexes: archives,
legacy,
}
}
}
struct ArchiveOld {
dirty: bool,
}
trait Archive {
fn is_dirty(&self) -> bool;
}
const MAX_ARCHIVE: usize = 255;
const MAX_GROUP_SIZE: usize = (1 << 24) - 1;
const ARCHIVESET: usize = (1 << 24) - 1;
trait Store {
fn list(&self, archive: u8) -> Vec<u8>;
fn read(&self, archive: u8, group: u16) -> Vec<u8>;
}
fn store_open(path: &str) -> Box<dyn Store> {
let has_data_file = Path::new(&path).join(DATA_PATH).exists();
let has_legacy_data_file = Path::new(path).join(LEGACY_DATA_PATH).exists();
if has_data_file || has_legacy_data_file {
Box::new(DiskStore::open(path))
} else {
Box::new(FlatFileStore::open(path))
}
}
struct CacheArchive {
is_dirty: bool,
}
impl CacheArchive {
pub fn testy() {}
}
impl Archive for CacheArchive {
fn is_dirty(&self) -> bool {
self.is_dirty
}
}
impl ArchiveOld {
pub fn read(&self, group: u16, file: u16, data: &Mmap) -> Vec<u8> {
Vec::new()
}
}
pub struct Cache {
store_new: Box<dyn Store>,
archives: HashMap<u8, CacheArchive>,
unpacked_cache_size: usize,
}
enum Js5Protocol {
Original = 5,
Versioned = 6,
Smart = 7,
}
enum Js5IndexFlags {
FlagNames = 0x1,
FlagDigests = 0x2,
FlagLengths = 0x4,
FlagUncompressedChecksums = 0x8,
}
#[derive(Debug)]
struct Js5IndexFile {
name_hash: i32,
}
#[derive(Debug)]
struct Js5IndexEntry {
name_hash: i32,
version: u32,
checksum: u32,
uncompressed_checksum: u32,
length: u32,
uncompressed_length: u32,
digest: Option<bool>,
capacity: u32,
files: HashMap<u32, Js5IndexFile>,
}
struct Js5Index {
protocol: u8,
version: i32,
has_names: bool,
has_digests: bool,
has_lengths: bool,
has_uncompressed_checksums: bool,
groups: BTreeMap<u32, Js5IndexEntry>,
}
const MAX_INDEXES: usize = 255;
const META_INDEX: usize = 255;
static INDEX_PATH: &str = "main_file_cache.idx";
static DATA_PATH: &str = "main_file_cache.dat2";
static LEGACY_DATA_PATH: &str = "main_file_cache.dat2";
static MUSIC_DATA_PATH: &str = "main_file_cache.dat2m";
const UNPACKED_CACHE_SIZE_DEFAULT: usize = 1024;
impl Cache {
pub fn open(input_path: &str) -> io::Result<Cache> {
let cache = Self {
store_new: store_open(input_path),
archives: HashMap::new(),
unpacked_cache_size: UNPACKED_CACHE_SIZE_DEFAULT,
};
cache.init();
Ok(cache)
}
fn init(&self) {
for archive in self.store_new.list(ARCHIVESET as u8) {
let index = self.store_new.read(ARCHIVESET as u8, archive as u16);
}
}
pub fn read(
&self,
archive: u16,
group: u16,
file: u16,
xtea_keys: Option<[i32; 4]>,
) -> Vec<u8> {
let archive_data = self.read_archive_group_data(META_INDEX, archive);
trace!("Output len of (255,2) data: {}", archive_data.len());
let mut csr = Cursor::new(&archive_data);
let protocol = csr.read_u8().unwrap();
let read_func = if protocol >= Js5Protocol::Smart as u8 {
|v: &mut Cursor<&Vec<u8>>| -> u32 { todo!() }
} else {
|v: &mut Cursor<&Vec<u8>>| -> u32 { v.read_u16().unwrap() as u32 }
};
let version = if protocol >= Js5Protocol::Versioned as u8 {
csr.read_i32().unwrap()
} else {
0
};
let flags = csr.read_u8().unwrap();
let size = read_func(&mut csr);
trace!("Flags: {}", flags);
trace!("Size: {}", size);
let mut index = Js5Index {
protocol,
version,
has_names: (flags & Js5IndexFlags::FlagNames as u8) != 0,
has_digests: (flags & Js5IndexFlags::FlagDigests as u8) != 0,
has_lengths: (flags & Js5IndexFlags::FlagLengths as u8) != 0,
has_uncompressed_checksums: (flags & Js5IndexFlags::FlagUncompressedChecksums as u8)
!= 0,
groups: BTreeMap::new(),
};
let mut prev_group_id = 0;
(0..size).for_each(|_| {
prev_group_id += read_func(&mut csr);
index.groups.insert(
prev_group_id,
Js5IndexEntry {
name_hash: -1,
version: 0,
checksum: 0,
uncompressed_checksum: 0,
length: 0,
uncompressed_length: 0,
digest: None,
capacity: 0,
files: HashMap::new(),
},
);
});
if index.has_names {
for (id, group) in &mut index.groups {
group.name_hash = csr.read_i32().unwrap();
}
}
for (id, group) in &mut index.groups {
group.checksum = csr.read_u32().unwrap();
}
if index.has_uncompressed_checksums {
for (id, group) in &mut index.groups {
group.uncompressed_checksum = csr.read_u32().unwrap();
}
}
if index.has_digests {
}
if index.has_lengths {
for (id, group) in &mut index.groups {
group.length = csr.read_u32().unwrap();
group.uncompressed_length = csr.read_u32().unwrap();
}
}
for (id, group) in &mut index.groups {
group.version = csr.read_u32().unwrap();
}
let group_sizes: Vec<u32> = (0..size).map(|_| read_func(&mut csr)).collect();
for (i, (id, group)) in index.groups.iter_mut().enumerate() {
let group_size = group_sizes[i];
let mut prev_file_id = 0;
(0..group_size).for_each(|_| {
prev_file_id += read_func(&mut csr);
group
.files
.insert(prev_file_id, Js5IndexFile { name_hash: -1 });
});
}
if index.has_names {
for (id, group) in &mut index.groups {
for (file_id, file) in &mut group.files {
file.name_hash = csr.read_i32().unwrap();
}
}
}
let archive_data2 = self.read_archive_group_data(archive as usize, group);
trace!("Output size of compressed data: {}", archive_data2.len());
trace!(
"Some data here: {} {} {}",
archive_data2[0],
archive_data2[1],
archive_data2[2]
);
let stripes = *archive_data2.last().unwrap();
trace!("Stripes: {}", stripes);
let data_index = 0;
let trailer_index = archive_data2.len()
- (stripes as usize * index.groups.get(&(group as u32)).unwrap().files.len() * 4)
as usize
- 1;
trace!("Trailer index: {}", trailer_index);
let mut readerrr = Cursor::new(&archive_data2[trailer_index..]);
let mut lens = vec![0; index.groups.get(&(group as u32)).unwrap().files.len()];
for i in 0..stripes {
let mut prev_len = 0;
for j in &mut lens {
prev_len += readerrr.read_i32().unwrap();
*j += prev_len;
}
}
let mut file_reader_stuff = Cursor::new(&archive_data2);
let mut files_final: BTreeMap<u32, Vec<u8>> = BTreeMap::new();
for (x, y) in &index.groups.get(&(group as u32)).unwrap().files {
files_final.insert(*x, vec![0; lens[*x as usize] as usize]);
}
for i in 0..stripes {
let mut prev_len = 0;
for j in 0..index.groups.get(&(group as u32)).unwrap().files.len() {
prev_len += lens[j];
file_reader_stuff
.read_exact(&mut files_final.get_mut(&(j as u32)).unwrap())
.unwrap();
}
}
files_final.get(&(file as u32)).unwrap().to_vec()
}
fn read_archive_group_data(&self, archive: usize, group: u16) -> Vec<u8> {
let x = self.fun_name(archive, group);
decompress_archive(x)
}
fn fun_name(&self, archive: usize, group: u16) -> Vec<u8> {
let archive_data = Vec::new();
archive_data
}
}
const COMPRESSION_TYPE_NONE: u8 = 0;
const COMPRESSION_TYPE_BZIP: u8 = 1;
const COMPRESSION_TYPE_GZIP: u8 = 2;
fn decompress_archive(mut archive_data: Vec<u8>) -> Vec<u8> {
let mut header_length = 1;
trace!("Archive data len: {}", archive_data.len());
let compression_type = archive_data[0];
trace!("Compression type: {}", compression_type);
let archive_size = u32::from_be_bytes([
archive_data[1],
archive_data[2],
archive_data[3],
archive_data[4],
]);
trace!("Archive size: {}", archive_size);
if compression_type == COMPRESSION_TYPE_NONE {
header_length += 4;
} else {
header_length += 8;
}
if archive_data.len() == (archive_size + header_length + 2) as usize {
archive_data.pop();
archive_data.pop();
};
if compression_type == COMPRESSION_TYPE_NONE {
todo!("None compression not handled yet, check with OpenRS2 first")
}
let decompressed_size = u32::from_be_bytes([
archive_data[5],
archive_data[6],
archive_data[7],
archive_data[8],
]);
trace!("Decompressed size: {}", decompressed_size);
let decompressed_data = match compression_type {
COMPRESSION_TYPE_NONE => archive_data[9..].to_vec(),
COMPRESSION_TYPE_BZIP => decompress_archive_bzip2(archive_data, decompressed_size),
COMPRESSION_TYPE_GZIP => decompress_archive_gzip(archive_data, decompressed_size),
_ => panic!("Unknown compression type: {}", compression_type),
};
decompressed_data
}
fn decompress_archive_bzip2(archive_data: Vec<u8>, decompressed_size: u32) -> Vec<u8> {
let mut decompressed_data = vec![0; decompressed_size as usize];
let mut compressed_data = archive_data[5..archive_data.len() - 4].to_vec();
compressed_data[..4].copy_from_slice(b"BZh1");
let mut decompressor = BzDecoder::new(compressed_data.as_slice());
decompressor.read_exact(&mut decompressed_data).unwrap();
decompressed_data
}
fn decompress_archive_gzip(archive_data: Vec<u8>, decompressed_size: u32) -> Vec<u8> {
let mut decompressed_data = vec![0; decompressed_size as usize];
let mut decompressor = GzDecoder::new(&archive_data[9..]);
decompressor.read_exact(&mut decompressed_data).unwrap();
decompressed_data
}
#[no_mangle]
pub unsafe extern "C" fn cache_create(cache_ptr: *mut Cache, archive: u32) {}
#[no_mangle]
pub unsafe extern "C" fn cache_capacity(cache_ptr: *mut Cache, archive: u32) {}
#[no_mangle]
pub unsafe extern "C" fn cache_open(path: *const c_char) -> *mut Cache {
let path_cstr = CStr::from_ptr(path);
let path_str = path_cstr.to_str().unwrap();
let cache = Cache::open(path_str).expect("failed to open cache");
Box::into_raw(Box::new(cache))
}
#[no_mangle]
pub unsafe extern "C" fn cache_read(
cache_ptr: *mut Cache,
archive: u16,
group: u16,
file: u16,
xtea_keys_arg: *const [i32; 4],
out_len: *mut u32,
) -> *mut u8 {
trace!("cache_read(cache_ptr = {:?}, archive = {}, group = {}, file = {}, xtea_keys = {:?}, out_len = {:?})", cache_ptr, archive, group, file, xtea_keys_arg, out_len);
let cache = &*cache_ptr;
let mut xtea_keys = None;
if !xtea_keys_arg.is_null() {
xtea_keys = Some(*xtea_keys_arg);
}
let mut buf = cache.read(archive, group, file, xtea_keys);
let data = buf.as_mut_ptr();
*out_len = buf.len() as u32;
mem::forget(buf);
data
}
#[no_mangle]
pub unsafe extern "C" fn free_cache_read_buffer(buffer: *mut u8) {
if !buffer.is_null() {
drop(Vec::from_raw_parts(buffer, 0, 0))
}
}
#[no_mangle]
pub unsafe extern "C" fn cache_write(cache_ptr: *mut Cache, archive: u32) {}
#[no_mangle]
pub unsafe extern "C" fn cache_remove(cache_ptr: *mut Cache, archive: u32) {}
#[no_mangle]
pub unsafe extern "C" fn cache_close(cache_ptr: *mut Cache) {
if !cache_ptr.is_null() {
drop(Box::from_raw(cache_ptr))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_djb2_hashing() {
let hashed_value = djb2_hash("m50_50");
let assert_val = -1123920270;
assert_eq!(hashed_value, assert_val as u32);
}
}