1use serde::{Deserialize, Serialize};
53use std::fs::{self, File, OpenOptions, Permissions};
54use std::io::{self, Write};
55use std::path::{Path, PathBuf};
56use tempfile::NamedTempFile;
57
58use super::inventory::{Inventory, InventorySlot, ItemType};
59
60#[derive(Serialize, Deserialize)]
64struct SlotDto {
65 item_byte: u8,
66 count: u32,
67}
68
69#[derive(Serialize, Deserialize)]
71struct InventoryDto {
72 capacity: usize,
73 slots: Vec<Option<SlotDto>>,
74}
75
76pub fn save_inventory<I: ItemType + Serialize>(
113 inventory: &Inventory<I>,
114 path: &str,
115) -> Result<(), Box<dyn std::error::Error>> {
116 save_inventory_with_ops(inventory, Path::new(path), &mut FileWriteOps)
117}
118
119fn save_inventory_with_ops<I: ItemType + Serialize>(
120 inventory: &Inventory<I>,
121 path: &Path,
122 ops: &mut impl AtomicWriteOps,
123) -> Result<(), Box<dyn std::error::Error>> {
124 inventory
125 .validate_integrity()
126 .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid inventory source"))?;
127 let dto = InventoryDto {
128 capacity: inventory.capacity,
129 slots: inventory
130 .slots
131 .iter()
132 .map(|slot| {
133 slot.as_ref().map(|s| SlotDto {
134 item_byte: s.item.to_byte(),
135 count: s.count,
136 })
137 })
138 .collect(),
139 };
140
141 decode_inventory::<I>(&dto, io::ErrorKind::InvalidInput)?;
144 let json = serde_json::to_vec_pretty(&dto)?;
145 let (target, permissions) = prepare_target(path)?;
146 let mut temp = private_tempfile(parent_directory(&target))?;
147 ops.check_private(temp.as_file())?;
148 ops.write_all(temp.as_file_mut(), &json)?;
149 if let Some(permissions) = permissions {
150 if let Err(error) = temp.as_file().set_permissions(permissions) {
151 return Err(error.into());
152 }
153 }
154 ops.sync_all(temp.as_file())?;
155 ops.replace(temp, &target)?;
156 Ok(())
157}
158
159fn parent_directory(path: &Path) -> &Path {
160 path.parent()
161 .filter(|parent| !parent.as_os_str().is_empty())
162 .unwrap_or_else(|| Path::new("."))
163}
164
165fn prepare_target(path: &Path) -> io::Result<(PathBuf, Option<Permissions>)> {
166 let metadata = match fs::symlink_metadata(path) {
168 Ok(metadata) => metadata,
169 Err(error) if error.kind() == io::ErrorKind::NotFound => {
170 fs::create_dir_all(parent_directory(path))?;
171 return Ok((path.to_path_buf(), None));
172 }
173 Err(error) => return Err(error),
174 };
175 let target = if metadata.file_type().is_symlink() {
176 resolved_link_target(path)?
177 } else {
178 path.to_path_buf()
179 };
180 let metadata = match fs::metadata(&target) {
181 Ok(metadata) => metadata,
182 Err(error) => return Err(error),
183 };
184 if !metadata.is_file() {
185 return Err(io::Error::new(
186 io::ErrorKind::InvalidInput,
187 "inventory destination must be a regular file",
188 ));
189 }
190 let permissions = metadata.permissions();
191 if permissions.readonly() {
192 return Err(io::Error::new(
193 io::ErrorKind::PermissionDenied,
194 "inventory destination is read-only",
195 ));
196 }
197 #[cfg(unix)]
198 {
199 use std::os::unix::fs::MetadataExt;
200 if metadata.nlink() > 1 {
201 return Err(io::Error::new(
202 io::ErrorKind::InvalidInput,
203 "inventory destination has multiple hard links",
204 ));
205 }
206 }
207 drop(OpenOptions::new().write(true).open(&target)?);
210 Ok((target, Some(permissions)))
211}
212
213#[cfg(windows)]
227fn resolved_link_target(path: &Path) -> io::Result<PathBuf> {
228 let raw = fs::read_link(path)?;
229 let joined = if raw.is_absolute() {
230 raw
231 } else {
232 parent_directory(path).join(raw)
233 };
234 Ok(lexically_normalize_windows(&joined))
235}
236
237#[cfg(windows)]
241fn lexically_normalize_windows(path: &Path) -> PathBuf {
242 use std::ffi::OsString;
243 use std::path::Component;
244
245 let mut prefix = PathBuf::new();
246 let mut absolute = false;
247 let mut stack: Vec<OsString> = Vec::new();
248 let mut parents = 0usize;
250 for component in path.components() {
251 match component {
252 Component::Prefix(_) | Component::RootDir => {
253 absolute = true;
254 prefix.push(component.as_os_str());
255 }
256 Component::CurDir => {}
257 Component::ParentDir => {
258 if stack.pop().is_some() {
259 } else if absolute {
261 } else {
263 parents += 1;
264 }
265 }
266 Component::Normal(part) => stack.push(part.to_os_string()),
267 }
268 }
269 let mut normalized = prefix;
270 for _ in 0..parents {
271 normalized.push("..");
272 }
273 for part in &stack {
274 normalized.push(part);
275 }
276 normalized
277}
278
279#[cfg(not(windows))]
281fn resolved_link_target(path: &Path) -> io::Result<PathBuf> {
282 fs::canonicalize(path)
283}
284
285trait AtomicWriteOps {
288 fn check_private(&mut self, file: &File) -> io::Result<()> {
289 #[cfg(windows)]
290 windows_private::verify_private(file)?;
291 #[cfg(not(windows))]
292 let _ = file;
293 Ok(())
294 }
295 fn write_all(&mut self, file: &mut File, bytes: &[u8]) -> io::Result<()>;
296 fn sync_all(&mut self, file: &File) -> io::Result<()>;
297 fn replace(&mut self, temp: NamedTempFile, target: &Path) -> io::Result<()>;
298}
299
300struct FileWriteOps;
301
302fn private_tempfile(parent: &Path) -> io::Result<NamedTempFile> {
303 #[cfg(windows)]
304 {
305 windows_private::tempfile(parent)
306 }
307 #[cfg(not(windows))]
308 {
309 NamedTempFile::new_in(parent)
310 }
311}
312
313impl AtomicWriteOps for FileWriteOps {
314 fn write_all(&mut self, file: &mut File, bytes: &[u8]) -> io::Result<()> {
315 file.write_all(bytes)
316 }
317
318 fn sync_all(&mut self, file: &File) -> io::Result<()> {
319 file.sync_all()
320 }
321
322 fn replace(&mut self, temp: NamedTempFile, target: &Path) -> io::Result<()> {
323 #[cfg(windows)]
324 {
325 windows_private::replace(temp, target)
326 }
327 #[cfg(not(windows))]
328 {
329 temp.persist(target)
331 .map(|_| ())
332 .map_err(|error| error.error)
333 }
334 }
335}
336
337#[cfg(windows)]
340mod windows_private {
341 use super::*;
342 use std::ffi::c_void;
343 use std::mem::size_of;
344 use std::os::windows::ffi::OsStrExt;
345 use std::os::windows::fs::OpenOptionsExt;
346 use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
347 use std::ptr::null_mut;
348 use windows_sys::Win32::Foundation::{
349 ERROR_NO_TOKEN, ERROR_SUCCESS, INVALID_HANDLE_VALUE, LocalFree,
350 };
351 use windows_sys::Win32::Security::Authorization::{
352 ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW,
353 GetSecurityInfo, SDDL_REVISION_1, SE_FILE_OBJECT,
354 };
355 use windows_sys::Win32::Security::{
356 ACCESS_ALLOWED_ACE, ACL, DACL_SECURITY_INFORMATION, EqualSid, GetAce, GetLengthSid,
357 GetSecurityDescriptorControl, GetSecurityDescriptorDacl, GetTokenInformation, IsValidAcl,
358 IsValidSecurityDescriptor, IsValidSid, SE_DACL_PROTECTED, SECURITY_ATTRIBUTES, TOKEN_QUERY,
359 TOKEN_USER, TokenUser,
360 };
361 use windows_sys::Win32::Storage::FileSystem::{
362 CREATE_NEW, CreateFileW, DELETE, FILE_ALL_ACCESS, FILE_ATTRIBUTE_NORMAL,
363 FILE_ATTRIBUTE_TEMPORARY, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT,
364 FILE_GENERIC_READ, FILE_GENERIC_WRITE, FILE_SHARE_DELETE, FILE_SHARE_READ,
365 FILE_SHARE_WRITE, GetVolumeInformationByHandleW, SetFileAttributesW,
366 };
367 use windows_sys::Win32::System::SystemServices::{
368 ACCESS_ALLOWED_ACE_TYPE, FILE_PERSISTENT_ACLS,
369 };
370 use windows_sys::Win32::System::Threading::{
371 GetCurrentProcess, GetCurrentThread, OpenProcessToken, OpenThreadToken,
372 };
373
374 struct LocalBuffer(*mut c_void);
376
377 impl Drop for LocalBuffer {
378 fn drop(&mut self) {
379 if !self.0.is_null() {
380 unsafe { LocalFree(self.0) };
383 }
384 }
385 }
386
387 fn denied(message: &'static str) -> io::Error {
388 io::Error::new(io::ErrorKind::PermissionDenied, message)
389 }
390
391 fn descriptor(sddl: &str) -> io::Result<LocalBuffer> {
392 let wide: Vec<u16> = sddl.encode_utf16().chain(Some(0)).collect();
393 let mut pointer = null_mut();
394 let result = unsafe {
397 ConvertStringSecurityDescriptorToSecurityDescriptorW(
398 wide.as_ptr(),
399 SDDL_REVISION_1,
400 &mut pointer,
401 null_mut(),
402 )
403 };
404 let buffer = LocalBuffer(pointer);
405 if result == 0 {
406 return Err(io::Error::last_os_error());
407 }
408 if buffer.0.is_null() {
409 return Err(denied("Windows returned no security descriptor"));
410 }
411 Ok(buffer)
412 }
413
414 fn user_descriptor() -> io::Result<LocalBuffer> {
415 let sid = effective_user_sid()?;
416 descriptor(&format!("D:P(A;;FA;;;{sid})"))
417 }
418
419 fn effective_user_sid() -> io::Result<String> {
420 let mut handle = null_mut();
421 let opened = unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, 1, &mut handle) };
424 if opened == 0 {
425 let error = io::Error::last_os_error();
426 if error.raw_os_error() != Some(ERROR_NO_TOKEN as i32) {
427 return Err(error);
428 }
429 if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut handle) } == 0 {
432 return Err(io::Error::last_os_error());
433 }
434 }
435 let token = unsafe { OwnedHandle::from_raw_handle(handle) };
437 let mut needed = 0;
438 unsafe {
440 GetTokenInformation(token.as_raw_handle(), TokenUser, null_mut(), 0, &mut needed)
441 };
442 if needed < size_of::<TOKEN_USER>() as u32 {
443 return Err(denied("Windows returned invalid token-user size"));
444 }
445 let mut data = vec![0usize; (needed as usize).div_ceil(size_of::<usize>())];
447 let mut returned = 0;
448 if unsafe {
451 GetTokenInformation(
452 token.as_raw_handle(),
453 TokenUser,
454 data.as_mut_ptr().cast(),
455 needed,
456 &mut returned,
457 )
458 } == 0
459 {
460 return Err(io::Error::last_os_error());
461 }
462 if returned < size_of::<TOKEN_USER>() as u32 || returned > needed {
463 return Err(denied("Windows returned invalid token-user data"));
464 }
465 let user = unsafe { &*data.as_ptr().cast::<TOKEN_USER>() };
468 let mut pointer = null_mut();
469 let result = unsafe { ConvertSidToStringSidW(user.User.Sid, &mut pointer) };
471 let text = LocalBuffer(pointer.cast());
472 if result == 0 {
473 return Err(io::Error::last_os_error());
474 }
475 if text.0.is_null() {
476 return Err(denied("Windows returned no user SID"));
477 }
478 let mut length = 0;
479 unsafe {
482 while *pointer.add(length) != 0 {
483 length += 1;
484 }
485 String::from_utf16(std::slice::from_raw_parts(pointer, length))
486 .map_err(|_| denied("Windows returned invalid user SID text"))
487 }
488 }
489
490 pub(super) fn tempfile(parent: &Path) -> io::Result<NamedTempFile> {
491 let security = user_descriptor()?;
492 tempfile::Builder::new().make_in(parent, |path| create(path, &security))
495 }
496
497 fn create(path: &Path, security: &LocalBuffer) -> io::Result<File> {
498 let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
499 if wide[..wide.len() - 1].contains(&0) {
500 return Err(io::Error::new(
501 io::ErrorKind::InvalidInput,
502 "NUL in inventory path",
503 ));
504 }
505 let attributes = SECURITY_ATTRIBUTES {
506 nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
507 lpSecurityDescriptor: security.0,
508 bInheritHandle: 0,
509 };
510 let handle = unsafe {
514 CreateFileW(
515 wide.as_ptr(),
516 FILE_GENERIC_READ | FILE_GENERIC_WRITE,
517 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
518 &attributes,
519 CREATE_NEW,
520 FILE_ATTRIBUTE_TEMPORARY,
521 null_mut(),
522 )
523 };
524 if handle == INVALID_HANDLE_VALUE {
525 return Err(io::Error::last_os_error());
526 }
527 Ok(unsafe { File::from_raw_handle(handle) })
529 }
530
531 pub(super) fn replace(temp: NamedTempFile, target: &Path) -> io::Result<()> {
532 let persist = match temp.persist(target) {
533 Ok(_file) => return Ok(()),
534 Err(error) => error,
535 };
536 if !matches!(
544 persist.error.kind(),
545 io::ErrorKind::PermissionDenied
546 | io::ErrorKind::InvalidFilename
547 | io::ErrorKind::WouldBlock
548 ) {
549 return Err(persist.error);
550 }
551 let replace = replace_fallback(persist.file.path(), target);
552 drop(persist.file);
556 if replace.is_ok() {
557 Ok(())
558 } else {
559 Err(persist.error)
560 }
561 }
562
563 fn replace_fallback(path: &Path, target: &Path) -> io::Result<()> {
574 let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
575 if unsafe { SetFileAttributesW(wide.as_ptr(), FILE_ATTRIBUTE_NORMAL) } == 0 {
578 return Err(io::Error::last_os_error());
579 }
580 let handle = OpenOptions::new()
584 .access_mode(DELETE)
585 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
586 .open(path)?;
587 rename_with_posix_semantics(&handle, target)
588 }
589
590 fn rename_with_posix_semantics(source: &File, target: &Path) -> io::Result<()> {
595 use std::mem::offset_of;
596 use windows_sys::Win32::Storage::FileSystem::{
597 FILE_RENAME_INFO, FileRenameInfoEx, SetFileInformationByHandle,
598 };
599 const FILE_RENAME_FLAG_REPLACE_IF_EXISTS: u32 = 0x0000_0001;
600 const FILE_RENAME_FLAG_POSIX_SEMANTICS: u32 = 0x0000_0002;
601 let name: Vec<u16> = target.as_os_str().encode_wide().collect();
602 let name_bytes = u32::try_from(name.len() * size_of::<u16>())
605 .map_err(|_| io::Error::from_raw_os_error(123))?;
606 let offset = offset_of!(FILE_RENAME_INFO, FileName) as u32;
607 let struct_size = offset + name_bytes + 2;
608 let mut info = vec![0u64; (struct_size as usize).div_ceil(size_of::<u64>())];
611 let header = info.as_mut_ptr().cast::<FILE_RENAME_INFO>();
612 unsafe {
615 (*header).Anonymous.Flags =
616 FILE_RENAME_FLAG_REPLACE_IF_EXISTS | FILE_RENAME_FLAG_POSIX_SEMANTICS;
617 (*header).RootDirectory = null_mut();
618 (*header).FileNameLength = name_bytes;
619 name.as_ptr()
620 .copy_to_nonoverlapping((*header).FileName.as_mut_ptr(), name.len());
621 }
622 if unsafe {
625 SetFileInformationByHandle(
626 source.as_raw_handle(),
627 FileRenameInfoEx,
628 info.as_ptr().cast(),
629 struct_size,
630 )
631 } == 0
632 {
633 return Err(io::Error::last_os_error());
634 }
635 let target_wide: Vec<u16> = target.as_os_str().encode_wide().chain(Some(0)).collect();
639 unsafe { SetFileAttributesW(target_wide.as_ptr(), FILE_ATTRIBUTE_NORMAL) };
641 Ok(())
642 }
643
644 pub(super) fn verify_private(file: &File) -> io::Result<()> {
645 let expected = user_descriptor()?;
646 verify_against(file, &expected)
647 }
648
649 fn require_acl_support(flags: u32) -> io::Result<()> {
650 if flags & FILE_PERSISTENT_ACLS == 0 {
651 return Err(denied(
652 "inventory volume does not support persistent private ACLs",
653 ));
654 }
655 Ok(())
656 }
657
658 fn verify_against(file: &File, expected: &LocalBuffer) -> io::Result<()> {
659 let mut flags = 0;
660 if unsafe {
663 GetVolumeInformationByHandleW(
664 file.as_raw_handle(),
665 null_mut(),
666 0,
667 null_mut(),
668 null_mut(),
669 &mut flags,
670 null_mut(),
671 0,
672 )
673 } == 0
674 {
675 return Err(io::Error::last_os_error());
676 }
677 require_acl_support(flags)?;
678 let actual = file_descriptor(file)?;
679 let actual_ace = single_private_ace(&actual)?;
680 let expected_ace = single_private_ace(expected)?;
681 if unsafe { EqualSid(actual_ace.1, expected_ace.1) } == 0 {
684 return Err(denied(
685 "inventory DACL does not belong exclusively to current user",
686 ));
687 }
688 Ok(())
689 }
690
691 fn file_descriptor(file: &File) -> io::Result<LocalBuffer> {
692 let mut pointer = null_mut();
693 let result = unsafe {
696 GetSecurityInfo(
697 file.as_raw_handle(),
698 SE_FILE_OBJECT,
699 DACL_SECURITY_INFORMATION,
700 null_mut(),
701 null_mut(),
702 null_mut(),
703 null_mut(),
704 &mut pointer,
705 )
706 };
707 let security = LocalBuffer(pointer);
708 if result != ERROR_SUCCESS {
709 return Err(io::Error::from_raw_os_error(result as i32));
710 }
711 if security.0.is_null() {
712 return Err(denied("Windows returned no file security descriptor"));
713 }
714 Ok(security)
715 }
716
717 fn single_private_ace(security: &LocalBuffer) -> io::Result<(u32, *mut c_void)> {
718 let mut control = 0;
719 let mut revision = 0;
720 let mut present = 0;
721 let mut defaulted = 0;
722 let mut acl: *mut ACL = null_mut();
723 unsafe {
726 if IsValidSecurityDescriptor(security.0) == 0
727 || GetSecurityDescriptorControl(security.0, &mut control, &mut revision) == 0
728 || control & SE_DACL_PROTECTED == 0
729 || GetSecurityDescriptorDacl(security.0, &mut present, &mut acl, &mut defaulted)
730 == 0
731 || present == 0
732 || defaulted != 0
733 || acl.is_null()
734 || IsValidAcl(acl) == 0
735 {
736 return Err(denied("inventory DACL is absent, invalid or unprotected"));
737 }
738 if (*acl).AceCount != 1 {
739 return Err(denied("inventory DACL must contain exactly one user ACE"));
740 }
741 let mut pointer = null_mut();
742 if GetAce(acl, 0, &mut pointer) == 0 || pointer.is_null() {
743 return Err(denied("inventory user ACE is unavailable"));
744 }
745 let header = &*pointer.cast::<windows_sys::Win32::Security::ACE_HEADER>();
748 if header.AceType != ACCESS_ALLOWED_ACE_TYPE as u8
749 || header.AceFlags != 0
750 || (header.AceSize as usize) < size_of::<ACCESS_ALLOWED_ACE>() + 4
751 {
752 return Err(denied(
753 "inventory ACE is inherited or not a simple user allow",
754 ));
755 }
756 let ace = &*pointer.cast::<ACCESS_ALLOWED_ACE>();
757 if ace.Mask != FILE_ALL_ACCESS {
758 return Err(denied("inventory user ACE has unexpected access rights"));
759 }
760 let sid = std::ptr::addr_of!(ace.SidStart).cast_mut().cast();
762 if GetLengthSid(sid) as usize > header.AceSize as usize - 8 || IsValidSid(sid) == 0 {
763 return Err(denied("inventory user ACE contains an invalid SID"));
764 }
765 Ok((ace.Mask, sid))
766 }
767 }
768
769 #[cfg(test)]
770 pub(super) fn reject_unsupported_volume() -> io::Result<()> {
771 require_acl_support(0)
772 }
773
774 #[cfg(test)]
775 pub(super) fn set_test_dacl(file: &File, sddl: &str) -> io::Result<()> {
776 use windows_sys::Win32::Security::Authorization::SetSecurityInfo;
777 use windows_sys::Win32::Security::PROTECTED_DACL_SECURITY_INFORMATION;
778 use windows_sys::Win32::Storage::FileSystem::{
779 FILE_FLAG_BACKUP_SEMANTICS, READ_CONTROL, ReOpenFile, WRITE_DAC,
780 };
781 let security = descriptor(sddl)?;
782 let mut present = 0;
783 let mut defaulted = 0;
784 let mut acl = null_mut();
785 if unsafe { GetSecurityDescriptorDacl(security.0, &mut present, &mut acl, &mut defaulted) }
787 == 0
788 || present == 0
789 || acl.is_null()
790 {
791 return Err(denied("test DACL missing"));
792 }
793 let flags = if file.metadata()?.is_dir() {
794 FILE_FLAG_BACKUP_SEMANTICS
795 } else {
796 0
797 };
798 let handle = unsafe {
801 ReOpenFile(
802 file.as_raw_handle(),
803 READ_CONTROL | WRITE_DAC,
804 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
805 flags,
806 )
807 };
808 if handle == INVALID_HANDLE_VALUE {
809 return Err(io::Error::last_os_error());
810 }
811 let writable = unsafe { OwnedHandle::from_raw_handle(handle) };
813 let result = unsafe {
816 SetSecurityInfo(
817 writable.as_raw_handle(),
818 SE_FILE_OBJECT,
819 DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
820 null_mut(),
821 null_mut(),
822 acl,
823 null_mut(),
824 )
825 };
826 if result != ERROR_SUCCESS {
827 return Err(io::Error::from_raw_os_error(result as i32));
828 }
829 Ok(())
830 }
831
832 #[cfg(test)]
839 pub(super) fn set_test_dacl_handle(file: &File, sddl: &str) -> io::Result<()> {
840 use windows_sys::Win32::Security::Authorization::SetSecurityInfo;
841 use windows_sys::Win32::Security::PROTECTED_DACL_SECURITY_INFORMATION;
842 let security = descriptor(sddl)?;
843 let mut present = 0;
844 let mut defaulted = 0;
845 let mut acl = null_mut();
846 if unsafe { GetSecurityDescriptorDacl(security.0, &mut present, &mut acl, &mut defaulted) }
848 == 0
849 || present == 0
850 || acl.is_null()
851 {
852 return Err(denied("test DACL missing"));
853 }
854 let result = unsafe {
858 SetSecurityInfo(
859 file.as_raw_handle(),
860 SE_FILE_OBJECT,
861 DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
862 null_mut(),
863 null_mut(),
864 acl,
865 null_mut(),
866 )
867 };
868 if result != ERROR_SUCCESS {
869 return Err(io::Error::from_raw_os_error(result as i32));
870 }
871 Ok(())
872 }
873}
874
875pub fn load_inventory<I: ItemType + for<'de> Deserialize<'de>>(
907 path: &str,
908) -> Result<Inventory<I>, Box<dyn std::error::Error>> {
909 let json = fs::read_to_string(load_target(Path::new(path))?)?;
910 let dto: InventoryDto = serde_json::from_str(&json)?;
911 Ok(decode_inventory::<I>(&dto, io::ErrorKind::InvalidData)?)
912}
913
914fn load_target(path: &Path) -> io::Result<PathBuf> {
922 match fs::symlink_metadata(path) {
923 Ok(metadata) if metadata.file_type().is_symlink() => resolved_link_target(path),
924 Ok(_) => Ok(path.to_path_buf()),
925 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(path.to_path_buf()),
926 Err(error) => Err(error),
927 }
928}
929
930fn decode_inventory<I: ItemType>(
931 dto: &InventoryDto,
932 error_kind: io::ErrorKind,
933) -> io::Result<Inventory<I>> {
934 if dto.capacity != dto.slots.len() {
935 return Err(io::Error::new(
936 error_kind,
937 "inventory capacity does not match slot count",
938 ));
939 }
940
941 let slots = dto
942 .slots
943 .iter()
944 .map(|slot| {
945 slot.as_ref().and_then(|s| {
946 let item = I::from_byte(s.item_byte);
947 (s.count > 0 && item != I::default() && !item.is_empty()).then_some(InventorySlot {
948 item,
949 count: s.count,
950 })
951 })
952 })
953 .collect();
954
955 let inventory = Inventory {
956 capacity: dto.capacity,
957 slots,
958 };
959 inventory
960 .validate_integrity()
961 .map_err(|_| io::Error::new(error_kind, "invalid inventory item totals"))?;
962 Ok(inventory)
963}
964
965#[cfg(test)]
968mod tests {
969 use super::*;
970 use crate::items::DefaultItem;
971
972 fn sample(count: u32) -> Inventory<DefaultItem> {
973 Inventory {
974 capacity: 5,
975 slots: vec![
976 None,
977 Some(InventorySlot {
978 item: DefaultItem::IronOre,
979 count,
980 }),
981 None,
982 Some(InventorySlot {
983 item: DefaultItem::Crystal,
984 count: 3,
985 }),
986 Some(InventorySlot {
987 item: DefaultItem::IronOre,
988 count: 2,
989 }),
990 ],
991 }
992 }
993
994 fn assert_layout<I: ItemType>(actual: &Inventory<I>, expected: &Inventory<I>) {
995 assert_eq!(actual.capacity, expected.capacity);
996 assert_eq!(actual.slots.len(), expected.slots.len());
997 for (actual, expected) in actual.slots.iter().zip(&expected.slots) {
998 match (actual, expected) {
999 (None, None) => {}
1000 (Some(actual), Some(expected)) => {
1001 assert!(actual.item == expected.item);
1002 assert_eq!(actual.count, expected.count);
1003 }
1004 _ => panic!("slot layout changed"),
1005 }
1006 }
1007 }
1008
1009 fn io_kind(error: &(dyn std::error::Error + 'static)) -> io::ErrorKind {
1010 error.downcast_ref::<io::Error>().expect("I/O error").kind()
1011 }
1012
1013 fn entries(directory: &Path) -> Vec<PathBuf> {
1014 let mut entries: Vec<_> = fs::read_dir(directory)
1015 .unwrap()
1016 .map(|entry| entry.unwrap().path())
1017 .collect();
1018 entries.sort();
1019 entries
1020 }
1021
1022 #[test]
1023 fn test_save_and_load_roundtrip() {
1024 let directory = tempfile::tempdir().unwrap();
1025 let path = directory.path().join("inventory.json");
1026 let inventory = sample(7);
1027 save_inventory(&inventory, path.to_str().unwrap()).unwrap();
1028 let loaded = load_inventory::<DefaultItem>(path.to_str().unwrap()).unwrap();
1029 assert_layout(&loaded, &inventory);
1030 let json: serde_json::Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
1031 assert_eq!(json.as_object().unwrap().len(), 2);
1032 assert_eq!(json["capacity"], 5);
1033 assert_eq!(
1034 json["slots"][1]["item_byte"],
1035 DefaultItem::IronOre.to_byte()
1036 );
1037 assert_eq!(json["slots"][1]["count"], 7);
1038 assert_eq!(json["slots"][1].as_object().unwrap().len(), 2);
1039 assert_eq!(entries(directory.path()), vec![path]);
1040 }
1041
1042 #[test]
1043 fn zero_capacity_roundtrip_and_nested_parent_creation() {
1044 let directory = tempfile::tempdir().unwrap();
1045 let path = directory.path().join("nested/saves/empty.json");
1046 let inventory = Inventory::<DefaultItem>::new(0);
1047 save_inventory(&inventory, path.to_str().unwrap()).unwrap();
1048 assert_layout(
1049 &load_inventory::<DefaultItem>(path.to_str().unwrap()).unwrap(),
1050 &inventory,
1051 );
1052 }
1053
1054 #[test]
1055 fn bare_basename_save_without_changing_current_directory() {
1056 let guard = NamedTempFile::new_in(".").unwrap().into_temp_path();
1059 let basename = guard.file_name().unwrap().to_str().unwrap();
1060 assert_eq!(parent_directory(Path::new(basename)), Path::new("."));
1061 let inventory = sample(4);
1062 save_inventory(&inventory, basename).unwrap();
1063 assert_layout(
1064 &load_inventory::<DefaultItem>(basename).unwrap(),
1065 &inventory,
1066 );
1067 }
1068
1069 #[test]
1070 fn invalid_source_preserves_old_file_or_missing_destination() {
1071 let directory = tempfile::tempdir().unwrap();
1072 let old = directory.path().join("old.json");
1073 let absent = directory.path().join("missing/absent.json");
1074 fs::write(&old, b"old bytes").unwrap();
1075 let mut mismatch = sample(1);
1076 mismatch.capacity += 1;
1077 let mut zero = sample(1);
1078 zero.slots[1].as_mut().unwrap().count = 0;
1079 let mut sentinel = sample(1);
1080 sentinel.slots[1].as_mut().unwrap().item = DefaultItem::Empty;
1081 let overflow = sample(u32::MAX);
1082 for inventory in [mismatch, zero, sentinel, overflow] {
1083 for target in [&old, &absent] {
1084 let error = save_inventory(&inventory, target.to_str().unwrap()).unwrap_err();
1085 assert_eq!(io_kind(error.as_ref()), io::ErrorKind::InvalidInput);
1086 assert_eq!(fs::read(&old).unwrap(), b"old bytes");
1087 assert!(!absent.parent().unwrap().exists());
1088 assert_eq!(entries(directory.path()), vec![old.clone()]);
1089 }
1090 }
1091 }
1092
1093 fn aliased_inventory(count: u32) -> Inventory<DefaultItem> {
1094 Inventory {
1095 capacity: 3,
1096 slots: vec![
1097 Some(InventorySlot {
1098 item: DefaultItem::IronOre,
1099 count,
1100 }),
1101 None,
1102 Some(InventorySlot {
1103 item: DefaultItem::IronOreItem,
1104 count: 1,
1105 }),
1106 ],
1107 }
1108 }
1109
1110 #[test]
1111 fn save_valid_byte_aliases_loads_collapsed_items_at_original_indexes() {
1112 let directory = tempfile::tempdir().unwrap();
1113 let path = directory.path().join("inventory.json");
1114 let inventory = aliased_inventory(u32::MAX - 1);
1115 assert_ne!(DefaultItem::IronOre, DefaultItem::IronOreItem);
1116 assert_eq!(
1117 DefaultItem::IronOre.to_byte(),
1118 DefaultItem::IronOreItem.to_byte()
1119 );
1120 assert!(inventory.validate_integrity().is_ok());
1121 save_inventory(&inventory, path.to_str().unwrap()).unwrap();
1122 let loaded = load_inventory::<DefaultItem>(path.to_str().unwrap()).unwrap();
1123 let mut expected = inventory;
1124 expected.slots[2].as_mut().unwrap().item = DefaultItem::IronOre;
1125 assert_layout(&loaded, &expected);
1126 assert_eq!(loaded.count_of(DefaultItem::IronOre), u32::MAX);
1127 assert_eq!(entries(directory.path()), vec![path]);
1128 }
1129
1130 #[test]
1131 fn save_rejects_byte_alias_overflow_before_filesystem_changes() {
1132 let directory = tempfile::tempdir().unwrap();
1133 let old = directory.path().join("old.json");
1134 let absent = directory.path().join("missing/absent.json");
1135 let original = sample(7);
1136 save_inventory(&original, old.to_str().unwrap()).unwrap();
1137 let old_bytes = fs::read(&old).unwrap();
1138 let inventory = aliased_inventory(u32::MAX);
1139 assert!(inventory.validate_integrity().is_ok());
1141 for target in [&old, &absent] {
1142 let error = save_inventory(&inventory, target.to_str().unwrap()).unwrap_err();
1143 assert_eq!(io_kind(error.as_ref()), io::ErrorKind::InvalidInput);
1144 assert_eq!(fs::read(&old).unwrap(), old_bytes);
1145 assert_layout(
1146 &load_inventory::<DefaultItem>(old.to_str().unwrap()).unwrap(),
1147 &original,
1148 );
1149 assert!(!absent.parent().unwrap().exists());
1150 assert_eq!(entries(directory.path()), vec![old.clone()]);
1151 }
1152 }
1153
1154 #[test]
1155 fn load_rejects_missing_malformed_schema_shape_and_overflow() {
1156 let directory = tempfile::tempdir().unwrap();
1157 let path = directory.path().join("inventory.json");
1158 let error = load_inventory::<DefaultItem>(path.to_str().unwrap()).unwrap_err();
1159 assert_eq!(io_kind(error.as_ref()), io::ErrorKind::NotFound);
1160 for json in ["{", "{}", r#"{"capacity":0,"slots":[{"item_byte":11}]}"#] {
1161 fs::write(&path, json).unwrap();
1162 let error = load_inventory::<DefaultItem>(path.to_str().unwrap()).unwrap_err();
1163 assert!(error.downcast_ref::<serde_json::Error>().is_some());
1164 }
1165 for json in [
1166 r#"{"capacity":2,"slots":[null]}"#,
1167 r#"{"capacity":0,"slots":[null]}"#,
1168 r#"{"capacity":2,"slots":[{"item_byte":11,"count":4294967295},{"item_byte":11,"count":1}]}"#,
1169 ] {
1170 fs::write(&path, json).unwrap();
1171 let error = load_inventory::<DefaultItem>(path.to_str().unwrap()).unwrap_err();
1172 assert_eq!(io_kind(error.as_ref()), io::ErrorKind::InvalidData);
1173 }
1174 }
1175
1176 #[test]
1177 fn load_normalizes_zero_unknown_and_default_without_repacking() {
1178 let directory = tempfile::tempdir().unwrap();
1179 let path = directory.path().join("inventory.json");
1180 fs::write(
1181 &path,
1182 r#"{"capacity":7,"slots":[null,{"item_byte":11,"count":0},{"item_byte":255,"count":99},{"item_byte":0,"count":2},{"item_byte":11,"count":4294967294},null,{"item_byte":11,"count":1}]}"#,
1183 ).unwrap();
1184 let inventory = load_inventory::<DefaultItem>(path.to_str().unwrap()).unwrap();
1185 assert_eq!(inventory.capacity, 7);
1186 assert!(inventory.slots[..4].iter().all(Option::is_none));
1187 assert_eq!(inventory.slots[4].as_ref().unwrap().count, u32::MAX - 1);
1188 assert!(inventory.slots[5].is_none());
1189 assert_eq!(inventory.slots[6].as_ref().unwrap().count, 1);
1190 assert_eq!(inventory.count_of(DefaultItem::IronOre), u32::MAX);
1191 }
1192
1193 #[derive(Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, Debug)]
1194 enum TestItem {
1195 #[default]
1196 DefaultSentinel,
1197 EmptyAlias,
1198 Live,
1199 }
1200
1201 impl ItemType for TestItem {
1202 fn name(&self) -> &'static str {
1203 "test"
1204 }
1205 fn color(&self) -> [f32; 4] {
1206 [1.0; 4]
1207 }
1208 fn to_byte(&self) -> u8 {
1209 *self as u8
1210 }
1211 fn from_byte(byte: u8) -> Self {
1212 match byte {
1213 1 => Self::EmptyAlias,
1214 2 => Self::Live,
1215 _ => Self::DefaultSentinel,
1216 }
1217 }
1218 fn is_empty(&self) -> bool {
1219 *self == Self::EmptyAlias
1220 }
1221 }
1222
1223 #[test]
1224 fn load_checks_default_equality_and_nondefault_empty_independently() {
1225 let directory = tempfile::tempdir().unwrap();
1226 let path = directory.path().join("inventory.json");
1227 fs::write(&path, r#"{"capacity":3,"slots":[{"item_byte":0,"count":1},{"item_byte":1,"count":1},{"item_byte":2,"count":1}]}"#).unwrap();
1228 let inventory = load_inventory::<TestItem>(path.to_str().unwrap()).unwrap();
1229 assert!(inventory.slots[0].is_none());
1230 assert!(inventory.slots[1].is_none());
1231 assert_eq!(inventory.slots[2].as_ref().unwrap().item, TestItem::Live);
1232 let invalid = Inventory {
1233 capacity: 1,
1234 slots: vec![Some(InventorySlot {
1235 item: TestItem::EmptyAlias,
1236 count: 1,
1237 })],
1238 };
1239 let old = fs::read(&path).unwrap();
1240 let error = save_inventory(&invalid, path.to_str().unwrap()).unwrap_err();
1241 assert_eq!(io_kind(error.as_ref()), io::ErrorKind::InvalidInput);
1242 assert_eq!(fs::read(path).unwrap(), old);
1243 }
1244
1245 #[derive(Clone, Copy, PartialEq, Eq)]
1246 enum Failure {
1247 PrefixWrite,
1248 Sync,
1249 Replace,
1250 RealReplace,
1251 }
1252
1253 struct InjectedOps {
1254 failure: Option<Failure>,
1255 events: Vec<&'static str>,
1256 expected_parent: PathBuf,
1257 expected_permissions: Permissions,
1258 }
1259
1260 impl AtomicWriteOps for InjectedOps {
1261 fn write_all(&mut self, file: &mut File, bytes: &[u8]) -> io::Result<()> {
1262 self.events.push("write");
1263 if self.failure == Some(Failure::PrefixWrite) {
1264 file.write_all(&bytes[..bytes.len().min(13)])?;
1265 return Err(io::Error::other("injected prefix-write failure"));
1266 }
1267 FileWriteOps.write_all(file, bytes)
1268 }
1269
1270 fn sync_all(&mut self, file: &File) -> io::Result<()> {
1271 self.events.push("sync");
1272 let actual = file.metadata()?.permissions();
1273 assert_eq!(actual.readonly(), self.expected_permissions.readonly());
1274 #[cfg(unix)]
1275 {
1276 use std::os::unix::fs::PermissionsExt;
1277 assert_eq!(actual.mode(), self.expected_permissions.mode());
1278 }
1279 if self.failure == Some(Failure::Sync) {
1280 return Err(io::Error::other("injected sync failure"));
1281 }
1282 FileWriteOps.sync_all(file)
1283 }
1284
1285 fn replace(&mut self, temp: NamedTempFile, target: &Path) -> io::Result<()> {
1286 self.events.push("replace");
1287 assert_eq!(
1288 fs::canonicalize(parent_directory(temp.path()))?,
1289 self.expected_parent
1290 );
1291 if self.failure == Some(Failure::Replace) {
1292 return Err(io::Error::other("injected replacement failure"));
1293 }
1294 if self.failure == Some(Failure::RealReplace) {
1295 return FileWriteOps.replace(temp, &target.join("missing/invalid.json"));
1298 }
1299 FileWriteOps.replace(temp, target)
1300 }
1301 }
1302
1303 #[test]
1304 fn injected_failures_preserve_existing_and_absent_targets_and_clean_temps() {
1305 for existing in [false, true] {
1306 for failure in [
1307 Failure::PrefixWrite,
1308 Failure::Sync,
1309 Failure::Replace,
1310 Failure::RealReplace,
1311 ] {
1312 let directory = tempfile::tempdir().unwrap();
1313 let path = directory.path().join("inventory.json");
1314 let expected_permissions = if existing {
1315 fs::write(&path, b"old bytes").unwrap();
1316 fs::metadata(&path).unwrap().permissions()
1317 } else {
1318 let probe = NamedTempFile::new_in(directory.path()).unwrap();
1319 probe.as_file().metadata().unwrap().permissions()
1320 };
1321 let before = entries(directory.path());
1322 let mut ops = InjectedOps {
1323 failure: Some(failure),
1324 events: vec![],
1325 expected_parent: fs::canonicalize(directory.path()).unwrap(),
1326 expected_permissions,
1327 };
1328 assert!(save_inventory_with_ops(&sample(7), &path, &mut ops).is_err());
1329 let expected_events = match failure {
1330 Failure::PrefixWrite => vec!["write"],
1331 Failure::Sync => vec!["write", "sync"],
1332 Failure::Replace | Failure::RealReplace => vec!["write", "sync", "replace"],
1333 };
1334 assert_eq!(ops.events, expected_events);
1335 if existing {
1336 assert_eq!(fs::read(&path).unwrap(), b"old bytes");
1337 } else {
1338 assert!(!path.exists());
1339 }
1340 assert_eq!(entries(directory.path()), before);
1341 }
1342 }
1343 }
1344
1345 #[test]
1346 fn successful_replacement_orders_write_permissions_sync_then_replace() {
1347 let directory = tempfile::tempdir().unwrap();
1348 let path = directory.path().join("inventory.json");
1349 fs::write(&path, b"old").unwrap();
1350 #[cfg(unix)]
1351 {
1352 use std::os::unix::fs::PermissionsExt;
1353 fs::set_permissions(&path, Permissions::from_mode(0o640)).unwrap();
1354 }
1355 let permissions = fs::metadata(&path).unwrap().permissions();
1356 let mut ops = InjectedOps {
1357 failure: None,
1358 events: vec![],
1359 expected_parent: fs::canonicalize(directory.path()).unwrap(),
1360 expected_permissions: permissions.clone(),
1361 };
1362 let inventory = sample(8);
1363 save_inventory_with_ops(&inventory, &path, &mut ops).unwrap();
1364 assert_eq!(ops.events, vec!["write", "sync", "replace"]);
1365 assert_layout(
1366 &load_inventory::<DefaultItem>(path.to_str().unwrap()).unwrap(),
1367 &inventory,
1368 );
1369 assert_eq!(
1370 fs::metadata(&path).unwrap().permissions().readonly(),
1371 permissions.readonly()
1372 );
1373 #[cfg(unix)]
1374 {
1375 use std::os::unix::fs::PermissionsExt;
1376 assert_eq!(
1377 fs::metadata(&path).unwrap().permissions().mode(),
1378 permissions.mode()
1379 );
1380 }
1381 assert_eq!(entries(directory.path()), vec![path]);
1382 }
1383
1384 #[test]
1385 fn read_only_and_directory_targets_are_rejected_unchanged() {
1386 let directory = tempfile::tempdir().unwrap();
1387 let path = directory.path().join("readonly.json");
1388 fs::write(&path, b"old").unwrap();
1389 let original = fs::metadata(&path).unwrap().permissions();
1390 let mut readonly = original.clone();
1391 readonly.set_readonly(true);
1392 fs::set_permissions(&path, readonly).unwrap();
1393 let result = save_inventory(&sample(2), path.to_str().unwrap());
1394 let bytes = fs::read(&path).unwrap();
1395 fs::set_permissions(&path, original).unwrap();
1397 assert_eq!(
1398 io_kind(result.unwrap_err().as_ref()),
1399 io::ErrorKind::PermissionDenied
1400 );
1401 assert_eq!(bytes, b"old");
1402 let result = save_inventory(&sample(2), directory.path().to_str().unwrap());
1403 assert_eq!(
1404 io_kind(result.unwrap_err().as_ref()),
1405 io::ErrorKind::InvalidInput
1406 );
1407 assert_eq!(entries(directory.path()), vec![path]);
1408 }
1409
1410 #[cfg(unix)]
1411 #[test]
1412 fn new_save_has_private_unix_permissions() {
1413 use std::os::unix::fs::PermissionsExt;
1414 let directory = tempfile::tempdir().unwrap();
1415 let path = directory.path().join("new.json");
1416 save_inventory(&sample(1), path.to_str().unwrap()).unwrap();
1417 assert_eq!(fs::metadata(path).unwrap().permissions().mode() & 0o077, 0);
1418 }
1419
1420 #[cfg(windows)]
1421 #[test]
1422 fn windows_private_creation_excludes_broad_parent_default_inheritance() {
1423 use std::os::windows::fs::OpenOptionsExt;
1424 use windows_sys::Win32::Storage::FileSystem::{
1425 FILE_FLAG_BACKUP_SEMANTICS, READ_CONTROL, WRITE_DAC,
1426 };
1427 let directory = tempfile::tempdir().unwrap();
1428 let parent = OpenOptions::new()
1432 .read(true)
1433 .access_mode(READ_CONTROL | WRITE_DAC)
1434 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
1435 .open(directory.path())
1436 .unwrap();
1437 windows_private::set_test_dacl_handle(&parent, "D:P(A;OICI;FA;;;WD)").unwrap();
1439 drop(parent);
1440 let inherited = NamedTempFile::new_in(directory.path()).unwrap();
1441 assert!(windows_private::verify_private(inherited.as_file()).is_err());
1442 drop(inherited);
1443 let private = private_tempfile(directory.path()).unwrap();
1444 assert_eq!(private.as_file().metadata().unwrap().len(), 0);
1445 windows_private::verify_private(private.as_file()).unwrap();
1446 drop(private);
1447 let path = directory.path().join("inventory.json");
1448 save_inventory(&sample(7), path.to_str().unwrap()).unwrap();
1449 windows_private::verify_private(&File::open(&path).unwrap()).unwrap();
1450 assert_layout(
1451 &load_inventory::<DefaultItem>(path.to_str().unwrap()).unwrap(),
1452 &sample(7),
1453 );
1454 assert_eq!(entries(directory.path()), vec![path]);
1455 }
1456
1457 #[cfg(windows)]
1458 struct WindowsSecurityOps {
1459 corrupt_dacl: bool,
1460 unsupported_volume: bool,
1461 events: Vec<&'static str>,
1462 }
1463
1464 #[cfg(windows)]
1465 impl AtomicWriteOps for WindowsSecurityOps {
1466 fn check_private(&mut self, file: &File) -> io::Result<()> {
1467 self.events.push("private");
1468 assert_eq!(file.metadata()?.len(), 0);
1469 FileWriteOps.check_private(file)?;
1472 if self.corrupt_dacl {
1473 windows_private::set_test_dacl(file, "D:P(A;;FA;;;WD)")?;
1474 }
1475 if self.unsupported_volume {
1476 return windows_private::reject_unsupported_volume();
1477 }
1478 FileWriteOps.check_private(file)
1479 }
1480 fn write_all(&mut self, file: &mut File, bytes: &[u8]) -> io::Result<()> {
1481 self.events.push("write");
1482 windows_private::verify_private(file)?;
1484 FileWriteOps.write_all(file, bytes)
1485 }
1486 fn sync_all(&mut self, file: &File) -> io::Result<()> {
1487 self.events.push("sync");
1488 FileWriteOps.sync_all(file)
1489 }
1490 fn replace(&mut self, temp: NamedTempFile, target: &Path) -> io::Result<()> {
1491 self.events.push("replace");
1492 FileWriteOps.replace(temp, target)
1493 }
1494 }
1495
1496 #[cfg(windows)]
1497 #[test]
1498 fn windows_security_check_precedes_json_write_and_final_file_is_private() {
1499 let directory = tempfile::tempdir().unwrap();
1500 let path = directory.path().join("inventory.json");
1501 let mut ops = WindowsSecurityOps {
1502 corrupt_dacl: false,
1503 unsupported_volume: false,
1504 events: vec![],
1505 };
1506 save_inventory_with_ops(&sample(7), &path, &mut ops).unwrap();
1507 assert_eq!(ops.events, vec!["private", "write", "sync", "replace"]);
1508 windows_private::verify_private(&File::open(&path).unwrap()).unwrap();
1509 assert_eq!(entries(directory.path()), vec![path]);
1510 }
1511
1512 #[cfg(windows)]
1513 #[test]
1514 fn windows_security_failures_preserve_old_or_absent_save_without_writes_or_temps() {
1515 for existing in [false, true] {
1516 for corrupt_dacl in [false, true] {
1517 let directory = tempfile::tempdir().unwrap();
1518 let path = directory.path().join("inventory.json");
1519 if existing {
1520 save_inventory(&sample(3), path.to_str().unwrap()).unwrap();
1521 }
1522 let old = existing.then(|| fs::read(&path).unwrap());
1523 let before = entries(directory.path());
1524 let mut ops = WindowsSecurityOps {
1525 corrupt_dacl,
1526 unsupported_volume: !corrupt_dacl,
1527 events: vec![],
1528 };
1529 let error = save_inventory_with_ops(&sample(7), &path, &mut ops).unwrap_err();
1530 assert_eq!(io_kind(error.as_ref()), io::ErrorKind::PermissionDenied);
1531 assert_eq!(ops.events, vec!["private"]);
1532 if let Some(bytes) = old {
1533 assert_eq!(fs::read(&path).unwrap(), bytes);
1534 assert_layout(
1535 &load_inventory::<DefaultItem>(path.to_str().unwrap()).unwrap(),
1536 &sample(3),
1537 );
1538 } else {
1539 assert!(!path.exists());
1540 }
1541 assert_eq!(entries(directory.path()), before);
1542 }
1543 }
1544 }
1545
1546 #[cfg(unix)]
1547 #[test]
1548 fn unix_socket_and_hardlinks_are_rejected_unchanged() {
1549 use std::os::unix::net::UnixListener;
1550 let directory = tempfile::tempdir().unwrap();
1551 let socket = directory.path().join("socket");
1552 match UnixListener::bind(&socket) {
1553 Ok(_listener) => {
1554 let error = save_inventory(&sample(1), socket.to_str().unwrap()).unwrap_err();
1555 assert_eq!(io_kind(error.as_ref()), io::ErrorKind::InvalidInput);
1556 }
1557 Err(error)
1560 if error.kind() == io::ErrorKind::PermissionDenied
1561 || matches!(error.raw_os_error(), Some(1 | 13)) =>
1562 {
1563 eprintln!(
1564 "skipping Unix-socket rejection assertion: environment denied socket creation: {error}"
1565 );
1566 }
1567 Err(error) => panic!("Unix socket creation failed unexpectedly: {error}"),
1568 }
1569 let path = directory.path().join("inventory.json");
1570 let alias = directory.path().join("alias.json");
1571 fs::write(&path, b"old").unwrap();
1572 fs::hard_link(&path, &alias).unwrap();
1573 let before = entries(directory.path());
1574 for target in [&path, &alias] {
1575 let error = save_inventory(&sample(1), target.to_str().unwrap()).unwrap_err();
1576 assert_eq!(io_kind(error.as_ref()), io::ErrorKind::InvalidInput);
1577 assert_eq!(fs::read(&path).unwrap(), b"old");
1578 assert_eq!(fs::read(&alias).unwrap(), b"old");
1579 assert_eq!(entries(directory.path()), before);
1580 }
1581 }
1582
1583 #[cfg(any(unix, windows))]
1584 fn symlink_file(target: &Path, link: &Path) -> io::Result<()> {
1585 #[cfg(unix)]
1586 {
1587 std::os::unix::fs::symlink(target, link)
1588 }
1589 #[cfg(windows)]
1590 {
1591 std::os::windows::fs::symlink_file(target, link)
1592 }
1593 }
1594
1595 #[cfg(any(unix, windows))]
1596 #[test]
1597 fn final_symlink_is_preserved_and_temp_is_in_target_directory() {
1598 let directory = tempfile::tempdir().unwrap();
1599 let targets = directory.path().join("targets");
1600 let links = directory.path().join("links");
1601 fs::create_dir(&targets).unwrap();
1602 fs::create_dir(&links).unwrap();
1603 let target = targets.join("inventory.json");
1604 let link = links.join("save.json");
1605 fs::write(&target, b"old").unwrap();
1606 let relative_target = Path::new("../targets/inventory.json");
1607 if let Err(error) = symlink_file(relative_target, &link) {
1608 #[cfg(windows)]
1609 if error.kind() == io::ErrorKind::PermissionDenied {
1610 eprintln!(
1611 "symlink test requires Windows Developer Mode or symlink privilege: {error}"
1612 );
1613 return;
1614 }
1615 panic!("symlink creation failed: {error}");
1616 }
1617 let mut ops = InjectedOps {
1618 failure: None,
1619 events: vec![],
1620 expected_parent: fs::canonicalize(&targets).unwrap(),
1621 expected_permissions: fs::metadata(&target).unwrap().permissions(),
1622 };
1623 for failure in [Failure::PrefixWrite, Failure::Sync, Failure::Replace] {
1624 ops.failure = Some(failure);
1625 ops.events.clear();
1626 assert!(save_inventory_with_ops(&sample(9), &link, &mut ops).is_err());
1627 assert_eq!(fs::read(&target).unwrap(), b"old");
1628 assert_eq!(fs::read_link(&link).unwrap(), relative_target);
1629 assert_eq!(entries(&targets), vec![target.clone()]);
1630 assert_eq!(entries(&links), vec![link.clone()]);
1631 }
1632 ops.failure = None;
1633 ops.events.clear();
1634 let inventory = sample(9);
1635 save_inventory_with_ops(&inventory, &link, &mut ops).unwrap();
1636 assert!(
1637 fs::symlink_metadata(&link)
1638 .unwrap()
1639 .file_type()
1640 .is_symlink()
1641 );
1642 assert_eq!(fs::read_link(&link).unwrap(), relative_target);
1643 assert_layout(
1644 &load_inventory::<DefaultItem>(link.to_str().unwrap()).unwrap(),
1645 &inventory,
1646 );
1647 assert_eq!(entries(&targets), vec![target]);
1648 assert_eq!(entries(&links), vec![link]);
1649 }
1650
1651 #[cfg(any(unix, windows))]
1652 #[test]
1653 fn dangling_symlink_is_not_replaced_or_followed_into_new_file() {
1654 let directory = tempfile::tempdir().unwrap();
1655 let link = directory.path().join("dangling.json");
1656 let missing = directory.path().join("missing.json");
1657 if let Err(error) = symlink_file(Path::new("missing.json"), &link) {
1658 #[cfg(windows)]
1659 if error.kind() == io::ErrorKind::PermissionDenied {
1660 eprintln!(
1661 "symlink test requires Windows Developer Mode or symlink privilege: {error}"
1662 );
1663 return;
1664 }
1665 panic!("symlink creation failed: {error}");
1666 }
1667 assert!(save_inventory(&sample(1), link.to_str().unwrap()).is_err());
1668 assert!(
1669 fs::symlink_metadata(&link)
1670 .unwrap()
1671 .file_type()
1672 .is_symlink()
1673 );
1674 assert_eq!(fs::read_link(&link).unwrap(), Path::new("missing.json"));
1675 assert!(!missing.exists());
1676 assert_eq!(entries(directory.path()), vec![link]);
1677 }
1678
1679 #[test]
1680 fn concurrent_writers_leave_one_whole_snapshot_and_no_temps() {
1681 use std::sync::{Arc, Barrier};
1682 let directory = tempfile::tempdir().unwrap();
1683 let path = directory.path().join("inventory.json");
1684 save_inventory(&sample(1), path.to_str().unwrap()).unwrap();
1685 let barrier = Arc::new(Barrier::new(8));
1686 let writers: Vec<_> = (2..10)
1687 .map(|count| {
1688 let path = path.clone();
1689 let barrier = Arc::clone(&barrier);
1690 std::thread::spawn(move || {
1691 barrier.wait();
1692 save_inventory(&sample(count), path.to_str().unwrap()).unwrap();
1693 })
1694 })
1695 .collect();
1696 for writer in writers {
1697 writer.join().unwrap();
1698 }
1699 let loaded = load_inventory::<DefaultItem>(path.to_str().unwrap()).unwrap();
1700 let count = loaded.slots[1].as_ref().unwrap().count;
1701 assert!((2..10).contains(&count));
1702 assert_layout(&loaded, &sample(count));
1703 assert_eq!(entries(directory.path()), vec![path]);
1704 }
1705
1706 #[cfg(windows)]
1707 #[test]
1708 fn lexically_normalize_windows_collapses_dots_and_parents() {
1709 let cases = [
1710 (
1712 r"C:\Users\RUNNER~1\AppData\Local\Temp\.tmpX\links\..\targets\inv.json",
1713 r"C:\Users\RUNNER~1\AppData\Local\Temp\.tmpX\targets\inv.json",
1714 ),
1715 (
1716 r"C:\Users\app\.\links\inv.json",
1717 r"C:\Users\app\links\inv.json",
1718 ),
1719 (r"C:\a\b\..\..\c", r"C:\c"),
1720 (r"C:\a\..\..\..", r"C:\"),
1721 (r"\a\b\..\c", r"\a\c"),
1723 (r"a\b\..\..\..\c", r"..\c"),
1724 (r"..\a", r"..\a"),
1725 (r"\\?\C:\a\..\b", r"\\?\C:\b"),
1727 ];
1728 for (input, expected) in cases {
1729 assert_eq!(
1730 lexically_normalize_windows(Path::new(input)),
1731 Path::new(expected),
1732 "normalizing {input}"
1733 );
1734 }
1735 }
1736
1737 #[cfg(windows)]
1738 #[test]
1739 fn lexically_normalize_windows_preserves_drive_and_unc_prefix_case() {
1740 let drive = lexically_normalize_windows(Path::new(r"c:\Temp\a\..\b.json"));
1741 assert_eq!(drive, Path::new(r"c:\Temp\b.json"));
1742 let unc = lexically_normalize_windows(Path::new(r"\\SERVER\Share\a\..\b.json"));
1743 assert_eq!(unc, Path::new(r"\\SERVER\Share\b.json"));
1744 }
1745}