1#[cfg(windows)]
4use std::env::temp_dir;
5use std::env::var;
6use std::fs::File;
7#[cfg(windows)]
8use std::fs::{create_dir_all, remove_dir_all};
9use std::io::{Error, Read};
10use std::path::Path;
11#[cfg(windows)]
12use std::path::PathBuf;
13#[cfg(windows)]
14use std::process::{Command, Stdio};
15
16#[cfg(windows)]
17use winreg::RegKey;
18#[cfg(windows)]
19use winreg::enums::HKEY_CURRENT_USER;
20
21use crate::error;
22#[cfg(windows)]
23use crate::error::ErrorExt;
24use crate::warning::WarningSink;
25
26#[cfg(windows)]
27fn find_binarize_exe() -> Result<PathBuf, Error> {
28 let hkcu = RegKey::predef(HKEY_CURRENT_USER);
29 let binarize = hkcu.open_subkey("Software\\Bohemia Interactive\\binarize")?;
30 let value: String = binarize.get_value("path")?;
31
32 Ok(PathBuf::from(value).join("binarize_x64.exe"))
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37#[non_exhaustive]
38pub enum BinarizeBackend {
39 Native,
41 Proton,
43}
44
45#[derive(Debug)]
47pub struct Binarizer {
48 #[cfg(unix)]
49 sandbox: Option<proton::Sandbox>,
50}
51
52impl Binarizer {
53 pub fn new(backend: BinarizeBackend) -> Result<Binarizer, Error> {
59 match (backend, cfg!(windows)) {
60 (BinarizeBackend::Native, false) => Err(error!(
61 "The native binarize.exe is only available on Windows; on Linux use --proton-binarize (see README) or rapify to binarize configs."
62 )),
63 (BinarizeBackend::Proton, true) => Err(error!(
64 "Proton is not used on Windows; the native binarize.exe is used there (do not pass --proton-binarize)."
65 )),
66 _ => Ok(Binarizer {
67 #[cfg(unix)]
68 sandbox: None,
69 }),
70 }
71 }
72
73 pub fn binarize(
83 &mut self,
84 input: &Path,
85 addon_root: &Path,
86 prefix: &str,
87 warnings: &mut dyn WarningSink,
88 ) -> Result<Vec<u8>, Error> {
89 #[cfg(unix)]
90 {
91 if self.sandbox.is_none() {
92 self.sandbox = Some(proton::create_sandbox(warnings)?);
93 }
94 let sb = self
95 .sandbox
96 .as_mut()
97 .ok_or_else(|| error!("Binarize sandbox not initialized."))?;
98 proton::binarize(sb, input, addon_root, prefix, warnings)
99 }
100 #[cfg(windows)]
101 {
102 native_binarize(input, addon_root, prefix, warnings)
103 }
104 }
105}
106
107impl Binarizer {
108 #[cfg_attr(
116 windows,
117 expect(unused_variables, reason = "nothing to clean up on Windows")
118 )]
119 pub fn close(self, warnings: &mut dyn WarningSink) -> Result<(), Error> {
120 #[cfg(unix)]
121 {
122 use crate::warning::Warning;
123 let mut this = self;
124 if let Some(message) = this.sandbox.take().and_then(|sb| proton::destroy(&sb)) {
125 warnings.warn(Warning::note(message));
126 }
127 }
128 Ok(())
129 }
130}
131
132impl Drop for Binarizer {
133 fn drop(&mut self) {
134 #[cfg(unix)]
135 if let Some(sb) = self.sandbox.take() {
136 let _ = proton::destroy(&sb);
139 }
140 }
141}
142
143#[cfg(windows)]
144fn create_temp_directory(name: &str) -> Result<PathBuf, Error> {
145 let dir = temp_dir();
146 let mut i = 0;
147
148 let mut path;
149 loop {
150 path = dir.join(format!("dayzmake_{name}_{i}"));
151 if !path.exists() {
152 break;
153 }
154
155 i += 1;
156 }
157
158 create_dir_all(&path)?;
159
160 Ok(path)
161}
162
163#[cfg(windows)]
164fn native_binarize(
165 input: &Path,
166 _addon_root: &Path,
167 _prefix: &str,
168 _warnings: &mut dyn WarningSink,
169) -> Result<Vec<u8>, Error> {
170 let binarize_exe = find_binarize_exe().prepend_error("Failed to find BI's binarize.exe:")?;
171 if !binarize_exe.exists() {
172 return Err(error!(
173 "BI's binarize.exe found in registry, but doesn't exist."
174 ));
175 }
176
177 let input_dir = input
178 .parent()
179 .ok_or_else(|| error!("Invalid input path \"{}\".", input.display()))?
180 .to_path_buf();
181 let file_name = input
182 .file_name()
183 .and_then(|n| n.to_str())
184 .ok_or_else(|| error!("Invalid file name \"{}\".", input.display()))?
185 .to_string();
186 let name = file_name.clone();
187 let input_dir_str = input_dir
188 .to_str()
189 .ok_or_else(|| error!("Invalid path \"{}\".", input_dir.display()))?
190 .to_string();
191 let tempdir = create_temp_directory(&name).prepend_error("Failed to create tempfolder:")?;
192
193 let piped = var("BIOUTPUT").unwrap_or_else(|_| "0".to_string()) == "1";
194
195 let mut command = Command::new(binarize_exe);
196 if Path::new("P:\\").is_dir() {
198 command.current_dir("P:\\");
199 }
200 let binarize_output = command
201 .args([
202 "-norecurse",
203 "-always",
204 "-silent",
205 "-maxProcesses=0",
206 input_dir_str.as_str(),
207 tempdir
208 .to_str()
209 .ok_or_else(|| error!("Invalid path \"{}\".", tempdir.display()))?,
210 file_name.as_str(),
211 ])
212 .stdin(Stdio::null())
215 .stdout(if piped {
216 Stdio::from(std::io::stderr())
217 } else {
218 Stdio::null()
219 })
220 .stderr(if piped {
221 Stdio::inherit()
222 } else {
223 Stdio::null()
224 })
225 .output()
226 .prepend_error("Failed to run binarize.exe:")?;
227
228 if !binarize_output.status.success() {
229 let msg = match binarize_output.status.code() {
230 Some(code) => format!("binarize.exe terminated with exit code: {code}"),
231 None => "binarize.exe terminated by signal.".to_string(),
232 };
233 let outputhint = if piped {
234 ""
235 } else {
236 "\nUse BIOUTPUT=1 to see binarize.exe's output."
237 };
238
239 return Err(error!("{}{}", msg, outputhint));
240 }
241
242 let result_path = tempdir.join(&file_name);
243 let mut buffer: Vec<u8> = Vec::new();
244
245 {
246 let mut file =
247 File::open(result_path).prepend_error("Failed to open binarize.exe output:")?;
248 file.read_to_end(&mut buffer)
249 .prepend_error("Failed to read binarize.exe output:")?;
250 }
251
252 remove_dir_all(&tempdir).prepend_error("Failed to remove temp directory:")?;
253
254 Ok(buffer)
255}
256
257pub fn is_binarized(path: &Path) -> Result<bool, Error> {
263 Ok(binarized_description(path)?.is_some())
264}
265
266pub fn binarized_description(path: &Path) -> Result<Option<String>, Error> {
273 use crate::error::{ErrorExt, printable};
274 let mut header = Vec::with_capacity(8);
275 File::open(path)
276 .and_then(|f| f.take(8).read_to_end(&mut header))
277 .prepend_error(format!(
278 "Failed to read \"{}\":",
279 printable(&path.display().to_string())
280 ))?;
281 let Some(magic) = header.get(..4) else {
282 return Ok(None);
283 };
284 if magic != b"ODOL" && magic != b"BMTR" {
285 return Ok(None);
286 }
287 let format = String::from_utf8_lossy(magic).into_owned();
288 Ok(Some(
289 match header.get(4..8).and_then(|b| <[u8; 4]>::try_from(b).ok()) {
290 Some(bytes) if header.len() == 8 => {
291 format!("{} v{}", format, u32::from_le_bytes(bytes))
292 }
293 _ => format,
294 },
295 ))
296}
297
298#[cfg(all(test, unix))]
299mod tests {
300 use super::*;
301
302 #[test]
303 fn native_backend_is_refused_off_windows() {
304 let err = Binarizer::new(BinarizeBackend::Native).err().unwrap();
305 assert!(err.to_string().contains("--proton-binarize"));
306 }
307
308 #[test]
309 fn dropping_a_binarizer_removes_its_sandbox() {
310 let tmp = tempfile::tempdir().unwrap();
311 let root = tmp.path().join("sandbox");
312 std::fs::create_dir_all(root.join("P")).unwrap();
313 let mut b = Binarizer::new(BinarizeBackend::Proton).unwrap();
314 b.sandbox = Some(proton::Sandbox::for_test(root.clone()));
315 drop(b);
316 assert!(!root.exists());
317 }
318}
319
320#[cfg(unix)]
321mod proton {
322 use std::fs::{File, create_dir_all, read_to_string, remove_dir_all, remove_file};
323 use std::io::{Error, Read};
324 use std::os::unix::fs::symlink;
325 use std::path::{Path, PathBuf};
326 use std::process::{Command, Stdio};
327 use std::thread::sleep;
328 use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
329
330 use crate::error;
331 use crate::error::{ErrorExt, printable};
332 use crate::warning::{Warning, WarningSink};
333
334 const APP_ID: &str = "830640";
335 const PREFIX_TIMEOUT: Duration = Duration::from_secs(300);
336 const BINARIZE_TIMEOUT: Duration = Duration::from_secs(600);
337
338 #[derive(Debug)]
339 pub struct Sandbox {
340 pub(super) root: PathBuf,
341 proton_dir: PathBuf,
342 steam_root: PathBuf,
343 counter: u32,
344 }
345
346 impl Sandbox {
347 #[cfg(test)]
348 pub(super) fn for_test(root: PathBuf) -> Sandbox {
349 Sandbox {
350 root,
351 proton_dir: PathBuf::from("/nonexistent"),
352 steam_root: PathBuf::new(),
353 counter: 0,
354 }
355 }
356 }
357
358 pub fn find_steam_root(candidates: &[PathBuf]) -> Option<PathBuf> {
360 candidates
361 .iter()
362 .find(|c| c.join("steamapps").join("common").is_dir())
363 .cloned()
364 }
365
366 fn steam_candidates() -> Vec<PathBuf> {
367 let mut c: Vec<PathBuf> = Vec::new();
368 if let Some(r) = std::env::var_os("STEAM_ROOT")
369 && !r.is_empty()
370 {
371 c.push(PathBuf::from(r));
372 }
373 if let Some(home) = std::env::var_os("HOME") {
374 let home = PathBuf::from(home);
375 c.push(home.join(".steam/debian-installation"));
376 c.push(home.join(".steam/steam"));
377 c.push(home.join(".local/share/Steam"));
378 }
379 c
380 }
381
382 pub fn find_dayz_tools(
384 steam_root: Option<&Path>,
385 override_dir: Option<PathBuf>,
386 ) -> Result<PathBuf, Error> {
387 let tools = match (override_dir, steam_root) {
388 (Some(d), _) => d,
389 (None, Some(s)) => s.join("steamapps/common/DayZ Tools"),
390 (None, None) => {
391 return Err(error!(
392 "No Steam installation found (set STEAM_ROOT, or DAYZ_TOOLS to the DayZ Tools folder)."
393 ));
394 }
395 };
396 if !tools.join("Bin/Binarize/binarize.exe").is_file() {
397 return Err(error!(
398 "binarize.exe not found in \"{}\". Install DayZ Tools (Steam app {}) or set DAYZ_TOOLS.",
399 tools.display(),
400 APP_ID
401 ));
402 }
403 Ok(tools)
404 }
405
406 pub fn find_proton(
408 steam_root: Option<&Path>,
409 override_dir: Option<PathBuf>,
410 ) -> Result<PathBuf, Error> {
411 if let Some(d) = override_dir {
412 if d.join("proton").is_file() {
413 return Ok(d);
414 }
415 return Err(error!("No proton script in PROTON=\"{}\".", d.display()));
416 }
417 let common = match steam_root {
418 Some(s) => s.join("steamapps/common"),
419 None => {
420 return Err(error!(
421 "No Steam installation found (set STEAM_ROOT, or PROTON to a Proton folder)."
422 ));
423 }
424 };
425 for name in &[
426 "Proton Hotfix",
427 "Proton - Experimental",
428 "Proton Experimental",
429 ] {
430 if common.join(name).join("proton").is_file() {
431 return Ok(common.join(name));
432 }
433 }
434 let mut others: Vec<PathBuf> = match std::fs::read_dir(&common) {
435 Ok(rd) => rd
436 .filter_map(std::result::Result::ok)
437 .map(|e| e.path())
438 .filter(|p| {
439 p.file_name()
440 .and_then(|n| n.to_str())
441 .is_some_and(|n| n.starts_with("Proton"))
442 && p.join("proton").is_file()
443 })
444 .collect(),
445 Err(_) => Vec::new(),
446 };
447 others.sort();
448 others.pop().ok_or_else(|| {
449 error!(
450 "No Proton found under \"{}\". Install one in Steam or set PROTON.",
451 common.display()
452 )
453 })
454 }
455
456 pub fn win_path(root: &Path, path: &Path) -> String {
458 let rel = path.strip_prefix(root).unwrap_or(path);
459 let parts: Vec<&str> = rel.iter().filter_map(|c| c.to_str()).collect();
460 format!("Z:\\{}", parts.join("\\"))
461 }
462
463 fn copy_dir(src: &Path, dst: &Path) -> Result<(), Error> {
464 create_dir_all(dst)?;
465 for entry in std::fs::read_dir(src)? {
466 let entry = entry?;
467 let target = dst.join(entry.file_name());
468 if entry.file_type()?.is_dir() {
469 copy_dir(&entry.path(), &target)?;
470 } else {
471 std::fs::copy(entry.path(), &target)?;
472 }
473 }
474 Ok(())
475 }
476
477 fn warn_missing_textures(log: &Path, model: &str, warnings: &mut dyn WarningSink) {
479 let text = read_to_string(log).unwrap_or_default();
480 for line in text.lines() {
481 let lower = line.to_ascii_lowercase();
482 if lower.contains("texture")
483 && (lower.contains("cannot")
484 || lower.contains("can't")
485 || lower.contains("not found")
486 || lower.contains("failed"))
487 {
488 warnings.warn(Warning::new(
489 Some("binarize-missing-texture"),
490 format!("{}: {}", printable(model), printable(line.trim())),
491 ));
492 }
493 }
494 }
495
496 fn printable_lines(lines: &[&str]) -> String {
499 lines
500 .iter()
501 .map(|l| printable(l))
502 .collect::<Vec<_>>()
503 .join("\n")
504 }
505
506 fn tail(path: &Path, lines: usize) -> String {
507 let text = read_to_string(path).unwrap_or_default();
508 let all: Vec<&str> = text.lines().collect();
509 let start = all.len().saturating_sub(lines);
510 printable_lines(all.get(start..).unwrap_or(&[]))
511 }
512
513 fn run_proton(
515 sb: &Sandbox,
516 args: &[&str],
517 cwd: &Path,
518 log: &Path,
519 timeout: Duration,
520 warnings: &mut dyn WarningSink,
521 ) -> Result<(), Error> {
522 let logfile = File::create(log)?;
523 let mut child = Command::new(sb.proton_dir.join("proton"))
524 .arg("run")
525 .args(args)
526 .current_dir(cwd)
527 .env("STEAM_COMPAT_CLIENT_INSTALL_PATH", &sb.steam_root)
528 .env("STEAM_COMPAT_DATA_PATH", sb.root.join("prefix"))
529 .env("SteamAppId", APP_ID)
530 .env("SteamGameId", APP_ID)
531 .env("STEAM_COMPAT_APP_ID", APP_ID)
532 .stdin(Stdio::null())
533 .stdout(Stdio::from(logfile.try_clone()?))
534 .stderr(Stdio::from(logfile))
535 .spawn()
536 .prepend_error("Failed to run proton:")?;
537
538 let start = Instant::now();
539 let status = loop {
540 if let Some(status) = child.try_wait()? {
541 break status;
542 }
543 if start.elapsed() > timeout {
544 let _ = child.kill();
545 let _ = child.wait();
546 return Err(error!(
547 "Timed out after {} s.\n{}",
548 timeout.as_secs(),
549 tail(log, 15)
550 ));
551 }
552 sleep(Duration::from_millis(100));
553 };
554
555 if super::var("BIOUTPUT").unwrap_or_else(|_| "0".to_string()) == "1" {
556 let text = read_to_string(log).unwrap_or_default();
558 let lines: Vec<&str> = text.lines().collect();
559 warnings.warn(Warning::note(printable_lines(&lines)));
560 }
561
562 if !status.success() {
563 let msg = match status.code() {
564 Some(code) => format!("proton terminated with exit code: {code}"),
565 None => "proton terminated by signal.".to_string(),
566 };
567 return Err(error!("{}\n{}", msg, tail(log, 15)));
568 }
569 Ok(())
570 }
571
572 pub fn create_sandbox(warnings: &mut dyn WarningSink) -> Result<Sandbox, Error> {
573 let steam_root = find_steam_root(&steam_candidates());
574 let tools = find_dayz_tools(
575 steam_root.as_deref(),
576 std::env::var_os("DAYZ_TOOLS")
577 .filter(|v| !v.is_empty())
578 .map(PathBuf::from),
579 )?;
580 let proton_dir = find_proton(
581 steam_root.as_deref(),
582 std::env::var_os("PROTON")
583 .filter(|v| !v.is_empty())
584 .map(PathBuf::from),
585 )?;
586 let steam_root = steam_root.unwrap_or_else(|| {
587 proton_dir
589 .parent()
590 .and_then(|p| p.parent())
591 .and_then(|p| p.parent())
592 .map(Path::to_path_buf)
593 .unwrap_or_default()
594 });
595
596 let nanos = SystemTime::now()
597 .duration_since(UNIX_EPOCH)
598 .map_or(0, |d| d.subsec_nanos());
599 let root = std::env::temp_dir().join(format!(
600 "dayzmake-binarize-{}-{}",
601 std::process::id(),
602 nanos
603 ));
604 std::fs::create_dir(&root).prepend_error("Failed to create sandbox directory:")?;
605 let mut sb = Sandbox {
606 root,
607 proton_dir,
608 steam_root,
609 counter: 0,
610 };
611
612 let result = (|| -> Result<(), Error> {
614 for d in &["prefix", "in", "out", "P"] {
615 create_dir_all(sb.root.join(d))?;
616 }
617 copy_dir(&tools.join("Bin/Binarize"), &sb.root.join("Binarize"))
618 .prepend_error("Failed to copy Binarize:")?;
619
620 warnings.warn(Warning::note(
621 "Creating a Wine prefix for binarize.exe (the first run takes a while)...",
622 ));
623 let log = sb.root.join("prefix-init.log");
624 run_proton(
625 &sb,
626 &["cmd.exe", "/c", "exit"],
627 &sb.root,
628 &log,
629 PREFIX_TIMEOUT,
630 warnings,
631 )
632 .prepend_error("Failed to create the Wine prefix:")?;
633
634 let dosdevices = sb.root.join("prefix/pfx/dosdevices");
635 if !dosdevices.is_dir() {
636 return Err(error!(
637 "Proton did not create a prefix in \"{}\".",
638 sb.root.join("prefix").display()
639 ));
640 }
641 let z = dosdevices.join("z:");
643 let _ = remove_file(&z);
644 symlink(&sb.root, &z).prepend_error("Failed to confine drive Z:")?;
645 let p = dosdevices.join("p:");
647 let _ = remove_file(&p);
648 symlink(sb.root.join("P"), &p).prepend_error("Failed to create drive P:")?;
649 Ok(())
650 })();
651
652 match result {
653 Ok(()) => Ok(sb),
654 Err(e) => {
655 sb.counter = 0;
656 if let Some(message) = destroy(&sb) {
657 warnings.warn(Warning::note(message));
658 }
659 Err(e)
660 }
661 }
662 }
663
664 pub fn destroy(sb: &Sandbox) -> Option<String> {
666 let _ = Command::new(sb.proton_dir.join("files/bin/wineserver"))
668 .arg("-k")
669 .env("WINEPREFIX", sb.root.join("prefix/pfx"))
670 .stdin(Stdio::null())
671 .stdout(Stdio::null())
672 .stderr(Stdio::null())
673 .status();
674 sleep(Duration::from_secs(1));
675 remove_dir_all(&sb.root)
676 .err()
677 .map(|e| format!("Warning: failed to remove \"{}\": {}", sb.root.display(), e))
678 }
679
680 fn prefix_parts(prefix: &str) -> Result<Vec<String>, Error> {
683 if prefix.chars().all(|c| c == '\\' || c == '/') {
684 return Ok(Vec::new());
685 }
686 let unsafe_prefix = || error!("Unsafe PBO prefix \"{}\" for binarize.", printable(prefix));
687 let safe = crate::pbo::safe_relative_path(prefix.trim_end_matches(['\\', '/']))
689 .ok_or_else(unsafe_prefix)?;
690 safe.iter()
691 .map(|c| c.to_str().map(String::from).ok_or_else(unsafe_prefix))
692 .collect()
693 }
694
695 pub fn stage_addon(root: &Path, prefix: &str, addon_root: &Path) -> Result<(), Error> {
701 let mut link = root.join("P");
702 link.extend(prefix_parts(prefix)?);
703 if link.symlink_metadata().is_ok() {
704 return Ok(());
705 }
706 if let Some(parent) = link.parent() {
707 create_dir_all(parent)?;
708 }
709 symlink(addon_root.canonicalize()?, &link)
710 }
711
712 pub fn p_win_path(prefix: &str, relative_dir: &Path) -> Result<String, Error> {
718 let mut parts = prefix_parts(prefix)?;
719 parts.extend(
720 relative_dir
721 .iter()
722 .filter_map(|c| c.to_str())
723 .map(String::from),
724 );
725 Ok(format!("P:\\{}", parts.join("\\")))
726 }
727
728 pub fn binarize(
729 sb: &mut Sandbox,
730 input: &Path,
731 addon_root: &Path,
732 prefix: &str,
733 warnings: &mut dyn WarningSink,
734 ) -> Result<Vec<u8>, Error> {
735 let name = input
736 .file_name()
737 .and_then(|n| n.to_str())
738 .ok_or_else(|| error!("Invalid file name \"{}\".", input.display()))?
739 .to_string();
740 let relative_dir = input
741 .parent()
742 .unwrap_or_else(|| Path::new(""))
743 .strip_prefix(addon_root)
744 .map_err(|_| {
745 error!(
746 "\"{}\" is not inside the addon folder \"{}\".",
747 input.display(),
748 addon_root.display()
749 )
750 })?;
751 stage_addon(&sb.root, prefix, addon_root)
752 .prepend_error("Failed to map the addon onto drive P:")?;
753
754 sb.counter += 1;
755 let out_dir = sb.root.join("out").join(sb.counter.to_string());
756 create_dir_all(&out_dir)?;
757
758 let log = out_dir.join("binarize.log");
759 let in_w = p_win_path(prefix, relative_dir)?;
760 let out_w = win_path(&sb.root, &out_dir);
761 run_proton(
762 sb,
763 &[
764 "Z:\\Binarize\\binarize.exe",
765 "-norecurse",
766 "-always",
767 "-silent",
768 "-maxProcesses=0",
769 &in_w,
770 &out_w,
771 &name,
772 ],
773 &sb.root.join("P"),
774 &log,
775 BINARIZE_TIMEOUT,
776 warnings,
777 )
778 .prepend_error("binarize.exe failed:")?;
779
780 warn_missing_textures(&log, &name, warnings);
781
782 let mut buffer: Vec<u8> = Vec::new();
783 if let Ok(mut f) = File::open(out_dir.join(&name)) {
784 f.read_to_end(&mut buffer)
785 .prepend_error("Failed to read binarize.exe output:")?;
786 }
787 if buffer.is_empty() {
788 return Err(error!(
789 "binarize.exe produced no output for \"{}\" (models referencing textures/materials may need a P: drive).\n{}",
790 name,
791 tail(&log, 15)
792 ));
793 }
794
795 let _ = remove_dir_all(&out_dir);
796 Ok(buffer)
797 }
798
799 #[cfg(test)]
800 mod tests {
801 use super::*;
802 use std::fs;
803 use std::os::unix::fs::PermissionsExt;
804
805 fn touch(p: &Path) {
806 fs::create_dir_all(p.parent().unwrap()).unwrap();
807 fs::write(p, b"").unwrap();
808 fs::set_permissions(p, fs::Permissions::from_mode(0o755)).unwrap();
809 }
810
811 #[test]
812 fn sandbox_layout() {
813 let root = tempfile::tempdir().unwrap();
814 let src = tempfile::tempdir().unwrap();
815 fs::create_dir_all(root.path().join("P")).unwrap();
816 stage_addon(root.path(), "my\\mod", src.path()).unwrap();
817 let link = root.path().join("P/my/mod");
818 assert_eq!(
819 fs::read_link(&link).unwrap(),
820 src.path().canonicalize().unwrap()
821 );
822 stage_addon(root.path(), "my\\mod", src.path()).unwrap();
824 assert_eq!(
825 p_win_path("my\\mod", Path::new("sub/dir")).unwrap(),
826 "P:\\my\\mod\\sub\\dir"
827 );
828 assert_eq!(p_win_path("my\\mod", Path::new("")).unwrap(), "P:\\my\\mod");
829 }
830
831 const BAD_PREFIXES: [&str; 10] = [
832 "..\\..\\x",
833 "a\\..\\..\\x",
834 "/abs",
835 "\\abs",
836 "\\\\?\\x",
837 "C:\\x",
838 "C:x",
839 "a\\.\\b",
840 "a\\\\b",
841 "a\u{1b}b",
842 ];
843
844 fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
845 for e in fs::read_dir(dir).unwrap() {
846 let p = e.unwrap().path();
847 out.push(p.clone());
848 if p.is_dir() && !p.is_symlink() {
849 walk(&p, out);
850 }
851 }
852 }
853
854 #[test]
855 fn stage_addon_rejects_parent_components() {
856 let outer = tempfile::tempdir().unwrap();
857 let root = outer.path().join("root");
858 let src = tempfile::tempdir().unwrap();
859 fs::create_dir_all(root.join("P")).unwrap();
860 let snapshot = || {
861 let mut v = Vec::new();
862 walk(outer.path(), &mut v);
863 v.sort();
864 v
865 };
866 let before = snapshot();
867 for prefix in BAD_PREFIXES {
868 let err = stage_addon(&root, prefix, src.path()).unwrap_err();
869 assert!(
870 err.to_string().contains("Unsafe PBO prefix"),
871 "{prefix}: {err}"
872 );
873 assert_eq!(snapshot(), before, "{prefix}");
874 }
875 }
876
877 #[test]
878 fn p_win_path_rejects_parent_components() {
879 for prefix in BAD_PREFIXES {
880 assert!(p_win_path(prefix, Path::new("")).is_err(), "{prefix}");
881 }
882 }
883
884 #[test]
885 fn empty_and_trailing_separator_prefixes_are_accepted() {
886 assert_eq!(p_win_path("", Path::new("")).unwrap(), "P:\\");
887 assert_eq!(
888 p_win_path("my\\mod\\", Path::new("")).unwrap(),
889 "P:\\my\\mod"
890 );
891 }
892
893 #[test]
894 fn win_path_is_relative_to_sandbox() {
895 let root = Path::new("/tmp/dayzmake-binarize-1-2");
896 assert_eq!(win_path(root, &root.join("in/3")), "Z:\\in\\3");
897 assert_eq!(win_path(root, &root.join("Binarize")), "Z:\\Binarize");
898 }
899
900 #[test]
901 fn steam_root_needs_steamapps_common() {
902 let t = tempfile::tempdir().unwrap();
903 fs::create_dir_all(t.path().join("b/steamapps/common")).unwrap();
904 fs::create_dir_all(t.path().join("a")).unwrap();
905 let found = find_steam_root(&[t.path().join("a"), t.path().join("b")]);
906 assert_eq!(found, Some(t.path().join("b")));
907 assert_eq!(find_steam_root(&[t.path().join("a")]), None);
908 }
909
910 #[test]
911 fn dayz_tools_discovery() {
912 let t = tempfile::tempdir().unwrap();
913 assert!(find_dayz_tools(Some(t.path()), None).is_err());
914 assert!(find_dayz_tools(None, None).is_err());
915 touch(
916 &t.path()
917 .join("steamapps/common/DayZ Tools/Bin/Binarize/binarize.exe"),
918 );
919 assert_eq!(
920 find_dayz_tools(Some(t.path()), None).unwrap(),
921 t.path().join("steamapps/common/DayZ Tools")
922 );
923 let other = t.path().join("other");
924 assert!(find_dayz_tools(Some(t.path()), Some(other.clone())).is_err());
925 touch(&other.join("Bin/Binarize/binarize.exe"));
926 assert_eq!(find_dayz_tools(None, Some(other.clone())).unwrap(), other);
927 }
928
929 #[test]
930 fn proton_discovery_prefers_hotfix_then_experimental_then_any() {
931 let t = tempfile::tempdir().unwrap();
932 let common = t.path().join("steamapps/common");
933 assert!(find_proton(Some(t.path()), None).is_err());
934 touch(&common.join("Proton 9.0/proton"));
935 assert_eq!(
936 find_proton(Some(t.path()), None).unwrap(),
937 common.join("Proton 9.0")
938 );
939 touch(&common.join("Proton - Experimental/proton"));
940 assert_eq!(
941 find_proton(Some(t.path()), None).unwrap(),
942 common.join("Proton - Experimental")
943 );
944 touch(&common.join("Proton Hotfix/proton"));
945 assert_eq!(
946 find_proton(Some(t.path()), None).unwrap(),
947 common.join("Proton Hotfix")
948 );
949 let custom = t.path().join("custom");
950 assert!(find_proton(Some(t.path()), Some(custom.clone())).is_err());
951 touch(&custom.join("proton"));
952 assert_eq!(
953 find_proton(Some(t.path()), Some(custom.clone())).unwrap(),
954 custom
955 );
956 }
957 }
958}