rzfile 0.2.0

Library to handle RZ game data parsing and name decoding
Documentation
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
use crate::error::RZError;

/// Default XOR decryption key used for encrypted game resources.
///
/// This 256-byte static key is used by default in functions like [`cipher`] and [`parse_index`]
/// if no custom decryption key is provided. It defines the byte pattern used in the
/// simple XOR-based cipher that obfuscates or encrypts resource data.
///
/// # Purpose
///
/// This key is embedded in the game client and used to encrypt files in the `data.00x` archive files.
/// It enables symmetric encryption/decryption of asset indices and content blocks.
///
/// # Usage
///
/// If you don't want to supply a custom key when calling [`cipher`] or [`parse_index`],
/// this constant is used implicitly:
///
/// ```rust
/// use rzfile::file::cipher;
///
/// let mut buffer = vec![0x1F, 0x2B, 0x3C];
/// cipher(&mut buffer, None); // uses RESOURCE_ENCRYPTION_KEY
/// ```
///
/// # Security Warning
///
/// This key is part of a **non-cryptographic XOR cipher**, which is trivial to reverse-engineer
/// and should not be used for securing sensitive data. It is purely for obfuscation purposes.
///
/// # Length
///
/// The key has a fixed size of 256 bytes. This allows for efficient cycling over arbitrary-length buffers.
///
/// # See Also
///
/// - [`cipher`] – for buffer decryption using this key
/// - [`parse_index`] – for reading the `data.000` file using the default key
const RESOURCE_ENCRYPTION_KEY: [u8; 256] = [
    0x77, 0xe8, 0x5e, 0xec, 0xb7, 0x4e, 0xc1, 0x87, 0x4f, 0xe6, 0xf5, 0x3c, 0x1f, 0xb3, 0x15, 0x43,
    0x6a, 0x49, 0x30, 0xa6, 0xbf, 0x53, 0xa8, 0x35, 0x5b, 0xe5, 0x9e, 0x0e, 0x41, 0xec, 0x22, 0xb8,
    0xd4, 0x80, 0xa4, 0x8c, 0xce, 0x65, 0x13, 0x1d, 0x4b, 0x08, 0x5a, 0x6a, 0xbb, 0x6f, 0xad, 0x25,
    0xb8, 0xdd, 0xcc, 0x77, 0x30, 0x74, 0xac, 0x8c, 0x5a, 0x4a, 0x9a, 0x9b, 0x36, 0xbc, 0x53, 0x0a,
    0x3c, 0xf8, 0x96, 0x0b, 0x5d, 0xaa, 0x28, 0xa9, 0xb2, 0x82, 0x13, 0x6e, 0xf1, 0xc1, 0x93, 0xa9,
    0x9e, 0x5f, 0x20, 0xcf, 0xd4, 0xcc, 0x5b, 0x2e, 0x16, 0xf5, 0xc9, 0x4c, 0xb2, 0x1c, 0x57, 0xee,
    0x14, 0xed, 0xf9, 0x72, 0x97, 0x22, 0x1b, 0x4a, 0xa4, 0x2e, 0xb8, 0x96, 0xef, 0x4b, 0x3f, 0x8e,
    0xab, 0x60, 0x5d, 0x7f, 0x2c, 0xb8, 0xad, 0x43, 0xad, 0x76, 0x8f, 0x5f, 0x92, 0xe6, 0x4e, 0xa7,
    0xd4, 0x47, 0x19, 0x6b, 0x69, 0x34, 0xb5, 0x0e, 0x62, 0x6d, 0xa4, 0x52, 0xb9, 0xe3, 0xe0, 0x64,
    0x43, 0x3d, 0xe3, 0x70, 0xf5, 0x90, 0xb3, 0xa2, 0x06, 0x42, 0x02, 0x98, 0x29, 0x50, 0x3f, 0xfd,
    0x97, 0x58, 0x68, 0x01, 0x8c, 0x1e, 0x0f, 0xef, 0x8b, 0xb3, 0x41, 0x44, 0x96, 0x21, 0xa8, 0xda,
    0x5e, 0x8b, 0x4a, 0x53, 0x1b, 0xfd, 0xf5, 0x21, 0x3f, 0xf7, 0xba, 0x68, 0x47, 0xf9, 0x65, 0xdf,
    0x52, 0xce, 0xe0, 0xde, 0xec, 0xef, 0xcd, 0x77, 0xa2, 0x0e, 0xbc, 0x38, 0x2f, 0x64, 0x12, 0x8d,
    0xf0, 0x5c, 0xe0, 0x0b, 0x59, 0xd6, 0x2d, 0x99, 0xcd, 0xe7, 0x01, 0x15, 0xe0, 0x67, 0xf4, 0x32,
    0x35, 0xd4, 0x11, 0x21, 0xc3, 0xde, 0x98, 0x65, 0xed, 0x54, 0x9d, 0x1c, 0xb9, 0xb0, 0xaa, 0xa9,
    0x0c, 0x8a, 0xb4, 0x66, 0x60, 0xe1, 0xff, 0x2e, 0xc8, 0x00, 0x43, 0xa9, 0x67, 0x37, 0xdb, 0x9c,
];

/// List of file extensions considered **not encrypted** by default.
///
/// This list is used by [`is_decrypted`] if no custom extensions are provided.
///
/// # Contents
///
/// - `"dds"`
/// - `"cob"`
/// - `"naf"`
/// - `"nx3"`
/// - `"nfm"`
/// - `"tga"`
///
/// These file types are typically stored unencrypted in the client files.
///
/// # See Also
///
/// - [`is_decrypted`] for usage
const DECRYPTED_EXTENSIONS: [&str; 6] = ["dds", "cob", "naf", "nx3", "nfm", "tga"];

/// Represents a single entry in the decrypted `data.000` index file.
///
/// Each entry in `data.000` corresponds to one resource file and contains:
/// - a length-prefixed hash name,
/// - the offset within a `data.00x` file,
/// - and the size of the corresponding binary blob.
///
/// This structure is typically generated by [`parse_index`] after decryption.
///
/// # Binary Layout
///
/// Each entry is encoded in the following order:
/// ```text
/// [1 byte]   str_len     - length of the hash
/// [N bytes]  hash        - filename hash (usually includes data.00x reference)
/// [4 bytes]  offset      - u32 LE: byte offset in data.00x
/// [4 bytes]  size        - u32 LE: file size in bytes
/// ```
///
/// # Example
///
/// ```rust
/// use rzfile::file::IndexFile;
///
/// IndexFile {
///     str_len: 8,
///     hash: b"file_001".to_vec(),
///     offset: 1024,
///     size: 4096,
/// };
/// ```
#[derive(Default, Debug)]
pub struct IndexFile {
    /// Length of the `hash` field in bytes.
    ///
    /// The first byte of each record in `data.000` defines how many bytes follow for the hash.
    pub str_len: u8,

    /// The hashed or obfuscated filename of the resource.
    ///
    /// This is often a filename or identifier that includes the file segment,
    /// e.g., `file_002.dat` → `data.002`. Interpreted as raw bytes.
    pub hash: Vec<u8>,

    /// Offset (in bytes) into the corresponding `data.00x` file.
    ///
    /// Indicates where the actual file content begins within the referenced data segment.
    pub offset: u32,

    /// Size (in bytes) of the file stored at the given `offset`.
    ///
    /// This represents the full payload size and allows exact slicing from `data.00x`.
    pub size: u32,
}

/// Determines whether the given filename refers to a file that is *not* encrypted.
///
/// This function checks if the filename ends with a known decrypted extension.
/// You can either provide your own list of extensions, or use the default set by passing `None`.
///
/// # Arguments
///
/// * `file_name` – The full name (or path) of the file to check.
/// * `extensions` – An optional list of extensions (e.g., `vec![".txt".to_string()]`).  
///   If `None`, the default list (`DECRYPTED_EXTENSIONS`) is used.
///
/// # Returns
///
/// `true` if the file name ends with any of the provided (or default) decrypted extensions,  
/// otherwise `false`.
///
/// # Default Behavior
///
/// If `extensions` is `None`, this function uses the internal static list:
/// ```rust
/// const DECRYPTED_EXTENSIONS: [&str; 6] = ["dds", "cob", "naf", "nx3", "nfm", "tga"];
/// ```
/// *(Die tatsächliche Liste hängt von deiner Implementierung ab.)*
///
/// # Examples
///
/// Using the default extensions:
/// ```rust
/// use rzfile::file::is_decrypted;
///
/// let is_clear = is_decrypted("config/settings.json", None);
/// assert!(!is_clear);
/// ```
///
/// Using custom extensions:
/// ```rust
/// use rzfile::file::is_decrypted;
///
/// let exts = vec![".custom".to_string(), ".clear".to_string()];
/// let result = is_decrypted("file.custom", Some(exts));
/// assert!(result);
/// ```
///
/// # Note
///
/// The check is **case-sensitive** and simply uses `str::ends_with()`.  
/// For case-insensitive checks, consider normalizing the input beforehand.
pub fn is_decrypted(file_name: &str, extensions: Option<Vec<String>>) -> bool {
    let ext_to_test =
        extensions.unwrap_or(DECRYPTED_EXTENSIONS.iter().map(|s| s.to_string()).collect());
    ext_to_test.iter().any(|ext| file_name.ends_with(ext))
}

/// Decrypts (or encrypts) the given buffer using a simple XOR cipher.
/// Used for decryption (or encryption) of client files and the index file.
///
/// Applies a byte-wise XOR operation on the buffer using a repeating key.
/// The operation is symmetric — applying it twice with the same key restores the original data.
///
/// # Arguments
///
/// * `buffer` - A mutable reference to the byte buffer to decrypt (or encrypt).
/// * `resource_encode_key` - An optional key slice. If `None`, the default key
///   (`RESOURCE_ENCRYPTION_KEY`) is used.
///
/// # Behavior
///
/// - The key is used in a cyclic manner: if the buffer is longer than the key,
///   the key wraps around.
/// - This avoids panics and supports arbitrary-length buffers.
///
/// # Examples
///
/// Using the default key:
/// ```rust
/// use rzfile::file::cipher;
///
/// let mut data = vec![0x1F, 0x2B, 0x3C];
/// cipher(&mut data, None);
/// ```
///
/// Using a custom key:
/// ```rust
/// use rzfile::file::cipher;
///
/// let mut data = vec![0x1F, 0x2B, 0x3C];
/// let key = &[0x10, 0x20];
/// cipher(&mut data, Some(key));
/// ```
pub fn cipher(buffer: &mut [u8], resource_encode_key: Option<&[u8]>) {
    let key = resource_encode_key.unwrap_or(&RESOURCE_ENCRYPTION_KEY);
    let key_len = key.len();

    if key_len == 0 {
        return;
    }

    for (i, byte) in buffer.iter_mut().enumerate() {
        *byte ^= key[i % key_len];
    }
}

/// Parses and decrypts the contents of a `data.000` index buffer.
///
/// This function decrypts the given binary buffer using an XOR cipher (via [`cipher`])
/// and parses it into a sequence of [`IndexFile`] structures.  
/// Each entry in the file consists of:
/// - a length-prefixed hash string,
/// - followed by a 4-byte offset,
/// - and a 4-byte size value.
///
/// # Arguments
///
/// * `buffer` - A mutable reference to the raw `data.000` buffer.  
///   The buffer is modified in-place during decryption.
/// * `resource_encode_key` - An optional byte slice used as the XOR decryption key.  
///   If `None` is passed, the default [`RESOURCE_ENCRYPTION_KEY`] is used.
///
/// # Returns
///
/// A `Result` containing a vector of parsed [`IndexFile`] entries on success,  
/// or an [`RZError`] variant on failure.
///
/// # Errors
///
/// - [`RZError::InvalidLength`] if the input buffer is empty.
/// - [`RZError::Unknown`] if the buffer contains an incomplete or invalid record (e.g., truncated entry).
///
/// # Format of Each Entry
///
/// Each record in the decrypted buffer is structured as follows:
/// ```text
/// [1 byte]   Hash length (N)
/// [N bytes]  Hash bytes
/// [4 bytes]  Offset (u32, little-endian)
/// [4 bytes]  Size (u32, little-endian)
/// ```
///
/// The total size of each record is `1 + N + 4 + 4 = N + 9` bytes.
///
/// # Example
///
/// ```rust
/// use rzfile::file::parse_index;
///
/// // Fake input: hash_len = 3, hash = [0x41, 0x42, 0x43] ("ABC"),
/// // offset = 0x01020304, size = 0x0A0B0C0D
/// let mut buffer = vec![
///     3,              // hash_len
///     0x41, 0x42, 0x43, // hash: "ABC"
///     0x04, 0x03, 0x02, 0x01, // offset (LE): 0x01020304
///     0x0D, 0x0C, 0x0B, 0x0A, // size (LE): 0x0A0B0C0D
/// ];
///
/// // Use a dummy XOR key that does nothing (all 0s)
/// let dummy_key = &[0x00; 16];
///
/// // Parse entries
/// let entries = parse_index(&mut buffer, Some(dummy_key)).unwrap();
/// for entry in entries {
///     println!("{} @ {} [{} bytes]", String::from_utf8(entry.hash).unwrap(), entry.offset, entry.size);
/// }
/// ```
///
/// # Safety & Mutation
///
/// This function **modifies the input buffer in-place** (for decryption).  
/// If you need to preserve the original data, pass a clone.
///
/// # See Also
///
/// - [`cipher`] for the decryption logic.
/// - [`IndexFile`] for the parsed structure.
/// - [`RESOURCE_ENCRYPTION_KEY`] for the fallback default key.
pub fn parse_index(
    buffer: &mut [u8],
    resource_encode_key: Option<&[u8]>,
) -> Result<Vec<IndexFile>, RZError> {
    if buffer.is_empty() {
        return Err(RZError::InvalidLength);
    }

    cipher(buffer, resource_encode_key);
    let mut result: Vec<IndexFile> = Vec::new();

    let mut curr_pos = 0usize;
    while curr_pos < buffer.len() {
        let hash_len = buffer.get(curr_pos).unwrap();
        let full_block_size = *hash_len as usize + 9usize;
        if (curr_pos + full_block_size) > buffer.len() {
            return Err(RZError::Unknown);
        }

        let index_file = IndexFile {
            str_len: *hash_len,
            hash: buffer[(curr_pos + 1)..(curr_pos + *hash_len as usize + 1)].into(),
            offset: u32::from_le_bytes(
                buffer[(curr_pos + *hash_len as usize + 1)..(curr_pos + *hash_len as usize + 5)]
                    .try_into()
                    .unwrap(),
            ),
            size: u32::from_le_bytes(
                buffer[(curr_pos + *hash_len as usize + 5)..(curr_pos + *hash_len as usize + 9)]
                    .try_into()
                    .unwrap(),
            ),
        };
        curr_pos += full_block_size;
        result.push(index_file);
    }

    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cipher_reversible() {
        let mut buffer = vec![1, 2, 3, 4, 5];
        let original = buffer.clone();

        cipher(&mut buffer, None);
        assert_ne!(buffer, original);

        cipher(&mut buffer, None);
        assert_eq!(buffer, original);
    }

    #[test]
    fn test_cipher_with_custom_key() {
        let mut buffer = vec![0x10, 0x20, 0x30];
        let key = vec![0x01, 0x02, 0x03];
        cipher(&mut buffer, Some(&key));
        assert_eq!(buffer, vec![0x11, 0x22, 0x33]);

        cipher(&mut buffer, Some(&key));
        assert_eq!(buffer, vec![0x10, 0x20, 0x30]);
    }

    #[test]
    fn test_parse_index_valid() {
        // Contains 2 entries
        let mut buffer: [u8; 25] = [
            3, 97, 98, 99, 5, 0, 0, 0, 6, 0, 0, 0, 4, 97, 98, 99, 100, 7, 0, 0, 0, 8, 0, 0, 0,
        ];
        cipher(&mut buffer, None);
        let vec_result = parse_index(&mut buffer, None).unwrap();

        assert_eq!(vec_result.len(), 2);

        assert_eq!(vec_result[0].hash, b"abc");
        assert_eq!(vec_result[0].str_len, 3);
        assert_eq!(vec_result[0].offset, 5);
        assert_eq!(vec_result[0].size, 6);

        assert_eq!(vec_result[1].hash, b"abcd");
        assert_eq!(vec_result[1].str_len, 4);
        assert_eq!(vec_result[1].offset, 7);
        assert_eq!(vec_result[1].size, 8);
    }

    #[test]
    fn test_parse_index_empty_buffer() {
        let mut buffer: [u8; 0] = [];
        let result = parse_index(&mut buffer, None);
        assert_eq!(result.unwrap_err(), RZError::InvalidLength);
    }

    #[test]
    fn test_parse_index_incomplete_entry() {
        // entry length byte is 10, but only 5 bytes follow
        let mut buffer: [u8; 6] = [10, 0, 0, 0, 0, 0];
        cipher(&mut buffer, None);
        let result = parse_index(&mut buffer, None);
        assert_eq!(result.unwrap_err(), RZError::Unknown);
    }

    #[test]
    fn test_is_decrypted_default_extensions() {
        assert!(is_decrypted("texture.dds", None));
        assert!(is_decrypted("model.cob", None));
        assert!(!is_decrypted("archive.bin", None));
    }

    #[test]
    fn test_is_decrypted_custom_extensions() {
        let exts = vec![".xyz".to_string(), ".data".to_string()];
        assert!(is_decrypted("level1.xyz", Some(exts.clone())));
        assert!(!is_decrypted("file.tga", Some(exts)));
    }

    #[test]
    fn test_indexfile_helper_struct() {
        let file = IndexFile {
            str_len: 4,
            hash: b"test".to_vec(),
            offset: 123,
            size: 456,
        };

        assert_eq!(file.str_len, 4);
        assert_eq!(&file.hash[..], b"test");
        assert_eq!(file.offset, 123);
        assert_eq!(file.size, 456);
    }

    #[test]
    fn test_cipher_empty_key() {
        let mut buffer = vec![0xAA, 0xBB];
        cipher(&mut buffer, Some(&[]));
        assert_eq!(buffer, vec![0xAA, 0xBB]);
    }

    #[test]
    fn test_is_decrypted_no_extension() {
        assert!(!is_decrypted("README", None));
        assert!(!is_decrypted("datafile.", None));
    }
}