bl4-ncs 0.8.2

NCS (Nexus Config Store) parser for Borderlands 4
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
//! Oodle decompression abstraction
//!
//! Provides a trait-based interface for Oodle decompression with multiple backends:
//! - `OozextractBackend`: Open-source implementation (default, ~97.6% compatibility)
//! - `NativeBackend`: Uses the official Oodle DLL via FFI (Windows only)
//! - `ExecBackend`: Executes an external command for decompression (cross-platform)

use std::io::Write;
use std::path::Path;
use std::process::{Command, Stdio};
use std::sync::Mutex;

use crate::{Error, Result};

/// Trait for Oodle block decompression
pub trait OodleDecompressor: Send + Sync {
    /// Decompress a single Oodle-compressed block
    ///
    /// # Arguments
    /// * `compressed` - The compressed block data
    /// * `decompressed_size` - Expected size after decompression
    ///
    /// # Returns
    /// The decompressed data, or an error if decompression fails
    fn decompress_block(&self, compressed: &[u8], decompressed_size: usize) -> Result<Vec<u8>>;

    /// Get the backend name for diagnostics
    fn name(&self) -> &'static str;

    /// Check if this backend supports all Oodle compression variants
    ///
    /// The oozextract backend returns false as it doesn't support all variants.
    fn is_full_support(&self) -> bool {
        false
    }
}

/// Open-source Oodle decompressor using oozextract crate
///
/// This is the default backend. It supports most Oodle-compressed data but
/// may fail on certain compression parameters used by some games.
pub struct OozextractBackend {
    extractor: Mutex<oozextract::Extractor>,
}

impl OozextractBackend {
    pub fn new() -> Self {
        Self {
            extractor: Mutex::new(oozextract::Extractor::new()),
        }
    }
}

impl Default for OozextractBackend {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for OozextractBackend {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OozextractBackend").finish_non_exhaustive()
    }
}

impl OodleDecompressor for OozextractBackend {
    fn decompress_block(&self, compressed: &[u8], decompressed_size: usize) -> Result<Vec<u8>> {
        let mut output = vec![0u8; decompressed_size];
        let mut extractor = self.extractor.lock().unwrap();

        let actual = extractor
            .read_from_slice(compressed, &mut output)
            .map_err(|e| Error::Oodle(format!("oozextract: {:?}", e)))?;

        if actual != decompressed_size {
            return Err(Error::DecompressionSize {
                expected: decompressed_size,
                actual,
            });
        }

        Ok(output)
    }

    fn name(&self) -> &'static str {
        "oozextract"
    }

    fn is_full_support(&self) -> bool {
        false
    }
}

/// Native Oodle decompressor using the official DLL
///
/// Requires the Oodle DLL (e.g., oo2core_9_win64.dll) to be available.
/// This backend supports all Oodle compression variants.
#[cfg(target_os = "windows")]
pub struct NativeBackend {
    decompress_fn: OodleLzDecompress,
}

#[cfg(target_os = "windows")]
type OodleLzDecompress = unsafe extern "C" fn(
    comp_buf: *const u8,
    comp_len: isize,
    raw_buf: *mut u8,
    raw_len: isize,
    fuzz_safe: i32,
    check_crc: i32,
    verbosity: i32,
    dec_buf_base: *mut u8,
    dec_buf_size: isize,
    fp_callback: *mut std::ffi::c_void,
    callback_user_data: *mut std::ffi::c_void,
    decoder_memory: *mut u8,
    decoder_memory_size: isize,
    thread_phase: i32,
) -> isize;

#[cfg(target_os = "windows")]
impl NativeBackend {
    /// Load the native Oodle backend from a DLL path
    pub fn load<P: AsRef<Path>>(dll_path: P) -> Result<Self> {
        use std::ffi::OsStr;
        use std::os::windows::ffi::OsStrExt;

        let path = dll_path.as_ref();
        let wide_path: Vec<u16> = OsStr::new(path)
            .encode_wide()
            .chain(std::iter::once(0))
            .collect();

        unsafe {
            let handle = winapi::um::libloaderapi::LoadLibraryW(wide_path.as_ptr());
            if handle.is_null() {
                return Err(Error::Oodle(format!(
                    "Failed to load Oodle DLL: {}",
                    path.display()
                )));
            }

            let proc_name = b"OodleLZ_Decompress\0";
            let proc =
                winapi::um::libloaderapi::GetProcAddress(handle, proc_name.as_ptr() as *const i8);
            if proc.is_null() {
                return Err(Error::Oodle(
                    "Failed to find OodleLZ_Decompress in DLL".to_string(),
                ));
            }

            Ok(Self {
                decompress_fn: std::mem::transmute(proc),
            })
        }
    }
}

#[cfg(target_os = "windows")]
impl OodleDecompressor for NativeBackend {
    fn decompress_block(&self, compressed: &[u8], decompressed_size: usize) -> Result<Vec<u8>> {
        let mut output = vec![0u8; decompressed_size];

        let result = unsafe {
            (self.decompress_fn)(
                compressed.as_ptr(),
                compressed.len() as isize,
                output.as_mut_ptr(),
                decompressed_size as isize,
                1, // fuzz_safe
                0, // check_crc
                0, // verbosity
                std::ptr::null_mut(),
                0,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                0,
                0,
            )
        };

        if result < 0 {
            return Err(Error::Oodle(format!(
                "OodleLZ_Decompress failed with code {}",
                result
            )));
        }

        if result as usize != decompressed_size {
            return Err(Error::DecompressionSize {
                expected: decompressed_size,
                actual: result as usize,
            });
        }

        Ok(output)
    }

    fn name(&self) -> &'static str {
        "native"
    }

    fn is_full_support(&self) -> bool {
        true
    }
}

/// External command-based Oodle decompressor
///
/// Executes an external command for each decompression operation.
/// The command receives compressed data via stdin and outputs decompressed data to stdout.
///
/// # Protocol
///
/// The command is invoked as:
/// ```text
/// <command> decompress <decompressed_size>
/// ```
///
/// - Compressed data is written to the command's stdin
/// - Decompressed data is read from the command's stdout
/// - Exit code 0 indicates success
///
/// # Example Commands
///
/// A simple wrapper script could be:
/// ```bash
/// #!/bin/bash
/// # oodle-decompress.sh - wrapper for Oodle decompression via Wine
/// wine /path/to/oodle_helper.exe "$@"
/// ```
pub struct ExecBackend {
    command: String,
}

impl ExecBackend {
    /// Create a new exec backend with the given command
    ///
    /// The command should be an executable that accepts the decompression protocol.
    pub fn new<S: Into<String>>(command: S) -> Self {
        Self {
            command: command.into(),
        }
    }
}

impl std::fmt::Debug for ExecBackend {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ExecBackend")
            .field("command", &self.command)
            .finish()
    }
}

impl OodleDecompressor for ExecBackend {
    fn decompress_block(&self, compressed: &[u8], decompressed_size: usize) -> Result<Vec<u8>> {
        let parts: Vec<&str> = self.command.split_whitespace().collect();
        let (program, prefix_args) = parts
            .split_first()
            .ok_or_else(|| Error::Oodle("Empty exec command".into()))?;

        let mut child = Command::new(program)
            .args(prefix_args)
            .arg("decompress")
            .arg(decompressed_size.to_string())
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .map_err(|e| {
                Error::Oodle(format!("Failed to spawn command '{}': {}", self.command, e))
            })?;

        // Write compressed data to stdin
        if let Some(mut stdin) = child.stdin.take() {
            stdin
                .write_all(compressed)
                .map_err(|e| Error::Oodle(format!("Failed to write to command stdin: {}", e)))?;
        }

        let output = child
            .wait_with_output()
            .map_err(|e| Error::Oodle(format!("Failed to wait for command: {}", e)))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(Error::Oodle(format!(
                "Command '{}' failed with exit code {:?}: {}",
                self.command,
                output.status.code(),
                stderr.trim()
            )));
        }

        if output.stdout.len() != decompressed_size {
            return Err(Error::DecompressionSize {
                expected: decompressed_size,
                actual: output.stdout.len(),
            });
        }

        Ok(output.stdout)
    }

    fn name(&self) -> &'static str {
        "exec"
    }

    fn is_full_support(&self) -> bool {
        true
    }
}

/// Create the default decompressor backend
pub fn default_backend() -> Box<dyn OodleDecompressor> {
    Box::new(OozextractBackend::new())
}

/// Create a native backend from a DLL path (Windows only)
#[cfg(target_os = "windows")]
pub fn native_backend<P: AsRef<Path>>(dll_path: P) -> Result<Box<dyn OodleDecompressor>> {
    Ok(Box::new(NativeBackend::load(dll_path)?))
}

/// Native Oodle DLL loading is not available on this platform
#[cfg(not(target_os = "windows"))]
pub fn native_backend<P: AsRef<Path>>(_dll_path: P) -> Result<Box<dyn OodleDecompressor>> {
    Err(Error::Oodle(
        "Native Oodle DLL loading requires Windows. On Linux/macOS, use \
         --oodle-exec with a decompression helper (add --oodle-fifo for Wine)"
            .to_string(),
    ))
}

/// Create an exec backend with the given command
pub fn exec_backend<S: Into<String>>(command: S) -> Box<dyn OodleDecompressor> {
    Box::new(ExecBackend::new(command))
}

/// FIFO-based external command decompressor (Unix only)
///
/// Uses named pipes (FIFOs) instead of stdin/stdout for data transfer. This is
/// required for Wine-based decompression, where Wine's console layer can corrupt
/// binary data over stdio. FIFOs look like regular files to the Wine process but
/// stream data in-memory without touching disk.
///
/// # Protocol
///
/// The command is invoked as:
/// ```text
/// <command> decompress <decompressed_size> <input_fifo> <output_fifo>
/// ```
///
/// - The helper reads compressed data from `<input_fifo>`
/// - The helper writes decompressed data to `<output_fifo>`
/// - Exit code 0 indicates success
#[cfg(unix)]
pub struct FifoExecBackend {
    command: String,
    _fifo_dir: tempfile::TempDir,
    input_fifo: std::path::PathBuf,
    output_fifo: std::path::PathBuf,
}

#[cfg(unix)]
impl FifoExecBackend {
    /// Create a new FIFO exec backend with the given command
    pub fn new<S: Into<String>>(command: S) -> Result<Self> {
        let fifo_dir = tempfile::tempdir()
            .map_err(|e| Error::Oodle(format!("Failed to create FIFO directory: {}", e)))?;

        let input_fifo = fifo_dir.path().join("input");
        let output_fifo = fifo_dir.path().join("output");

        mkfifo(&input_fifo)?;
        mkfifo(&output_fifo)?;

        Ok(Self {
            command: command.into(),
            _fifo_dir: fifo_dir,
            input_fifo,
            output_fifo,
        })
    }
}

#[cfg(unix)]
impl std::fmt::Debug for FifoExecBackend {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FifoExecBackend")
            .field("command", &self.command)
            .field("input_fifo", &self.input_fifo)
            .field("output_fifo", &self.output_fifo)
            .finish()
    }
}

#[cfg(unix)]
impl FifoExecBackend {
    fn spawn_helper(&self, decompressed_size: usize) -> Result<std::process::Child> {
        let parts: Vec<&str> = self.command.split_whitespace().collect();
        let (program, prefix_args) = parts
            .split_first()
            .ok_or_else(|| Error::Oodle("Empty exec command".into()))?;

        Command::new(program)
            .args(prefix_args)
            .arg("decompress")
            .arg(decompressed_size.to_string())
            .arg(&self.input_fifo)
            .arg(&self.output_fifo)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::piped())
            .spawn()
            .map_err(|e| Error::Oodle(format!("Failed to spawn command '{}': {}", self.command, e)))
    }

    fn check_exit(&self, child: &mut std::process::Child) -> Result<()> {
        let status = child
            .wait()
            .map_err(|e| Error::Oodle(format!("Failed to wait for command: {}", e)))?;

        if !status.success() {
            let stderr_output = child
                .stderr
                .take()
                .map(|mut s| {
                    let mut buf = String::new();
                    std::io::Read::read_to_string(&mut s, &mut buf).ok();
                    buf
                })
                .unwrap_or_default();
            return Err(Error::Oodle(format!(
                "Command '{}' failed with exit code {:?}: {}",
                self.command,
                status.code(),
                stderr_output.trim()
            )));
        }

        Ok(())
    }
}

#[cfg(unix)]
impl OodleDecompressor for FifoExecBackend {
    fn decompress_block(&self, compressed: &[u8], decompressed_size: usize) -> Result<Vec<u8>> {
        let mut child = self.spawn_helper(decompressed_size)?;

        // Writer thread: opens input FIFO and writes compressed data.
        // Blocks until the helper opens the FIFO for reading.
        let input_path = self.input_fifo.clone();
        let compressed_data = compressed.to_vec();
        let writer = std::thread::spawn(move || -> Result<()> {
            let mut file = std::fs::File::create(&input_path)
                .map_err(|e| Error::Oodle(format!("Failed to open input FIFO: {}", e)))?;
            file.write_all(&compressed_data)
                .map_err(|e| Error::Oodle(format!("Failed to write to input FIFO: {}", e)))?;
            Ok(())
        });

        // Reader thread: opens output FIFO and reads decompressed data.
        // If the helper crashes before opening the output FIFO, this blocks
        // forever — the main thread detects the crash via wait() and opens
        // the FIFO itself to unblock the reader with an empty result.
        let output_path = self.output_fifo.clone();
        let reader =
            std::thread::spawn(move || -> std::io::Result<Vec<u8>> { std::fs::read(&output_path) });

        // Wait for the child to exit. If it crashes, open the output FIFO
        // ourselves so the reader thread gets EOF instead of blocking forever.
        let exit_result = self.check_exit(&mut child);
        if exit_result.is_err() {
            // Open the output FIFO for writing then immediately drop it,
            // which delivers EOF to the blocked reader thread.
            let _ = std::fs::OpenOptions::new()
                .write(true)
                .open(&self.output_fifo);
        }

        let output = reader
            .join()
            .map_err(|_| Error::Oodle("Reader thread panicked".into()))?
            .map_err(|e| Error::Oodle(format!("Failed to read from output FIFO: {}", e)))?;

        writer
            .join()
            .map_err(|_| Error::Oodle("Writer thread panicked".into()))??;

        exit_result?;

        if output.len() != decompressed_size {
            return Err(Error::DecompressionSize {
                expected: decompressed_size,
                actual: output.len(),
            });
        }

        Ok(output)
    }

    fn name(&self) -> &'static str {
        "fifo-exec"
    }

    fn is_full_support(&self) -> bool {
        true
    }
}

/// Create a FIFO-based exec backend (Unix only, required for Wine)
#[cfg(unix)]
pub fn fifo_exec_backend<S: Into<String>>(command: S) -> Result<Box<dyn OodleDecompressor>> {
    Ok(Box::new(FifoExecBackend::new(command)?))
}

/// Create named FIFO at the given path
#[cfg(unix)]
fn mkfifo(path: &std::path::Path) -> Result<()> {
    let c_path = std::ffi::CString::new(
        path.to_str()
            .ok_or_else(|| Error::Oodle("non-UTF8 FIFO path".into()))?,
    )
    .map_err(|e| Error::Oodle(format!("invalid FIFO path: {}", e)))?;

    let result = unsafe { libc::mkfifo(c_path.as_ptr(), 0o600) };
    if result != 0 {
        return Err(Error::Io(std::io::Error::last_os_error()));
    }
    Ok(())
}

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

    #[test]
    fn test_oozextract_backend_name() {
        let backend = OozextractBackend::new();
        assert_eq!(backend.name(), "oozextract");
        assert!(!backend.is_full_support());
    }

    #[test]
    fn test_default_backend() {
        let backend = default_backend();
        assert_eq!(backend.name(), "oozextract");
    }

    #[test]
    fn test_exec_backend_empty_command() {
        let backend = ExecBackend::new("");
        let result = backend.decompress_block(&[0u8; 4], 4);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Empty exec command"), "got: {}", err);
    }

    #[test]
    fn test_exec_backend_single_word_command() {
        let backend = ExecBackend::new("nonexistent_oodle_helper");
        let result = backend.decompress_block(&[0u8; 4], 4);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Failed to spawn"), "got: {}", err);
    }

    #[test]
    fn test_exec_backend_multi_word_command() {
        let backend = ExecBackend::new("nonexistent_wine nonexistent_helper.exe --dll foo.dll");
        let result = backend.decompress_block(&[0u8; 4], 4);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Failed to spawn"), "got: {}", err);
    }

    #[cfg(not(target_os = "windows"))]
    #[test]
    fn test_native_backend_not_available_on_non_windows() {
        match native_backend("/path/to/oodle.dll") {
            Err(e) => {
                let msg = e.to_string();
                assert!(
                    msg.contains("--oodle-exec"),
                    "error should suggest --oodle-exec, got: {}",
                    msg
                );
            }
            Ok(_) => panic!("native_backend should return Err on non-Windows"),
        }
    }

    #[cfg(unix)]
    #[test]
    fn test_fifo_exec_backend_creates_fifos() {
        let backend = FifoExecBackend::new("nonexistent_helper").unwrap();
        assert!(backend.input_fifo.exists());
        assert!(backend.output_fifo.exists());
    }

    #[cfg(unix)]
    #[test]
    fn test_fifo_exec_backend_name() {
        let backend = FifoExecBackend::new("test_helper").unwrap();
        assert_eq!(backend.name(), "fifo-exec");
        assert!(backend.is_full_support());
    }

    #[cfg(unix)]
    #[test]
    fn test_fifo_exec_backend_cleanup_on_drop() {
        let (input_path, output_path);
        {
            let backend = FifoExecBackend::new("test_helper").unwrap();
            input_path = backend.input_fifo.clone();
            output_path = backend.output_fifo.clone();
            assert!(input_path.exists());
            assert!(output_path.exists());
        }
        // TempDir dropped — FIFOs should be cleaned up
        assert!(!input_path.exists());
        assert!(!output_path.exists());
    }

    #[cfg(unix)]
    #[test]
    fn test_fifo_exec_backend_empty_command() {
        let backend = FifoExecBackend::new("").unwrap();
        let result = backend.decompress_block(&[0u8; 4], 4);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Empty exec command"), "got: {}", err);
    }

    #[cfg(unix)]
    #[test]
    fn test_fifo_exec_backend_nonexistent_command() {
        let backend = FifoExecBackend::new("nonexistent_fifo_helper").unwrap();
        let result = backend.decompress_block(&[0u8; 4], 4);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Failed to spawn"), "got: {}", err);
    }

    #[cfg(unix)]
    #[test]
    fn test_fifo_exec_backend_end_to_end() {
        use std::os::unix::fs::PermissionsExt;

        // Create a helper script that reads from input FIFO and writes to output FIFO.
        // Identity "decompression": cat input → output.
        // Args: $1=decompress $2=size $3=input_fifo $4=output_fifo
        let script_dir = tempfile::tempdir().unwrap();
        let script_path = script_dir.path().join("test_helper.sh");
        std::fs::write(&script_path, "#!/bin/sh\ncat < \"$3\" > \"$4\"\n").unwrap();
        std::fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755)).unwrap();

        let backend = FifoExecBackend::new(script_path.to_str().unwrap()).unwrap();

        let input_data = b"hello world test data";
        let result = backend.decompress_block(input_data, input_data.len());

        match result {
            Ok(output) => assert_eq!(output, input_data),
            Err(e) => panic!("FIFO decompression failed: {}", e),
        }
    }

    #[cfg(unix)]
    #[test]
    fn test_fifo_exec_factory() {
        match fifo_exec_backend("test_helper") {
            Ok(backend) => assert_eq!(backend.name(), "fifo-exec"),
            Err(e) => panic!("fifo_exec_backend factory failed: {}", e),
        }
    }
}