storage.rs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. //! Persistent local storage: a host folder of the title's own
  2. //! (`runtime::Title::storage`, under the data directory, never the cache)
  3. //! with the quota its manifest declares, seen by the title as a drive
  4. //! (`files`).
  5. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  6. use std::path::Path;
  7. use super::xasync::{self, AsyncBlock, E_ABORT};
  8. use super::xgameruntime::{
  9. Guid, HRESULT, Interface, Methods, NOT_SUPPORTED, Object, S_OK, add_ref, missing, put,
  10. put_string,
  11. };
  12. use crate::runtime;
  13. pub const PROVIDER: Guid = Guid::new(
  14. 0xf4fa_f4d4,
  15. 0x2d04,
  16. 0x4fce,
  17. [0xb3, 0xe0, 0x47, 0x4a, 0x71, 0x3a, 0x3e, 0x84],
  18. );
  19. pub const IID: Guid = Guid::new(
  20. 0xd294_11df,
  21. 0x0794,
  22. 0x4553,
  23. [0x8b, 0x27, 0x95, 0xfc, 0x02, 0xd0, 0xf7, 0x5d],
  24. );
  25. /// As the title (2026) asks for it; it calls 0x20 (path) and 0x28
  26. /// (space) with the same arguments.
  27. pub const IID_2026: Guid = Guid::new(
  28. 0x41a4_e10c,
  29. 0x5a7e,
  30. 0x41d9,
  31. [0x8c, 0x37, 0x37, 0xbd, 0xe6, 0x2a, 0x07, 0xd6],
  32. );
  33. pub static OBJECT: Object = Object::new("persistent local storage", &VTABLE);
  34. pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT), (PROVIDER, IID_2026, &OBJECT)];
  35. const E_FAIL: HRESULT = 0x8000_4005_u32 as i32;
  36. type This = *const Object;
  37. /// The path titles get: the root of a virtual drive over the folder. On the
  38. /// console storage is a drive of its own, and titles rely on it: Minecraft
  39. /// keeps only what precedes the path's last `:\` and mounts that as a
  40. /// drive, so a host folder such as `C:\Users\..` would make it write to the
  41. /// root of `C:`. None (the path calls fail) before the title is set.
  42. fn folder() -> Option<String> {
  43. let storage = runtime::title().storage;
  44. if storage.as_os_str().is_empty() {
  45. return None;
  46. }
  47. #[cfg(windows)]
  48. return super::files::mount(&storage).map(|letter| format!("{letter}:\\"));
  49. #[cfg(not(windows))]
  50. None
  51. }
  52. extern "system" fn path_size(_: This, out: *mut usize) -> HRESULT {
  53. match folder() {
  54. Some(path) => put(out, path.len() + 1),
  55. None => NOT_SUPPORTED,
  56. }
  57. }
  58. /// A buffer too small for the path fails with `E_FAIL`, the documented
  59. /// Xbox result (a PC gets `ERROR_INSUFFICIENT_BUFFER`).
  60. extern "system" fn path(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT {
  61. match folder() {
  62. Some(path) if size <= path.len() => E_FAIL,
  63. Some(path) => put_string(&path, size, buffer, used),
  64. None => NOT_SUPPORTED,
  65. }
  66. }
  67. #[repr(C)]
  68. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  69. pub struct SpaceInfo {
  70. /// Writable now.
  71. pub available_free: u64,
  72. /// Left in the quota.
  73. pub total_free: u64,
  74. pub used: u64,
  75. /// The quota.
  76. pub total: u64,
  77. }
  78. fn used_bytes(dir: &Path) -> u64 {
  79. let Ok(entries) = std::fs::read_dir(dir) else {
  80. return 0;
  81. };
  82. entries
  83. .flatten()
  84. .map(|e| match e.metadata() {
  85. Ok(m) if m.is_dir() => used_bytes(&e.path()),
  86. Ok(m) => m.len(),
  87. Err(_) => 0,
  88. })
  89. .sum()
  90. }
  91. /// What the host disk under `dir` has free (unlimited if unknown).
  92. pub(crate) fn disk_free(dir: &Path) -> u64 {
  93. #[cfg(windows)]
  94. {
  95. use std::os::windows::ffi::OsStrExt;
  96. let wide: Vec<u16> = dir.as_os_str().encode_wide().chain([0]).collect();
  97. let mut free = 0;
  98. let null = std::ptr::null_mut();
  99. // SAFETY: a NUL-terminated path and a valid output.
  100. let ok = unsafe {
  101. windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW(
  102. wide.as_ptr(),
  103. &mut free,
  104. null,
  105. null,
  106. )
  107. };
  108. if ok != 0 {
  109. return free;
  110. }
  111. }
  112. let _ = dir;
  113. u64::MAX
  114. }
  115. fn space() -> SpaceInfo {
  116. let title = runtime::title();
  117. let used = used_bytes(&title.storage);
  118. let free = title.storage_bytes.saturating_sub(used);
  119. SpaceInfo {
  120. // Writable now: the quota's rest, as far as the host disk allows.
  121. available_free: free.min(disk_free(&title.storage)),
  122. total_free: free,
  123. used,
  124. total: title.storage_bytes,
  125. }
  126. }
  127. extern "system" fn space_info(_: This, out: *mut SpaceInfo) -> HRESULT {
  128. put(out, space())
  129. }
  130. /// Tells our prompts apart from other calls on the same block.
  131. static PROMPT: u8 = 0;
  132. /// There is nobody to ask: granted when the quota has room, else declined.
  133. extern "system" fn prompt_for_space(_: This, bytes: u64, block: *mut AsyncBlock) -> HRESULT {
  134. let hr = if bytes <= space().total_free {
  135. S_OK
  136. } else {
  137. E_ABORT
  138. };
  139. xasync::finished(block, (&raw const PROMPT).cast(), hr)
  140. }
  141. extern "system" fn prompt_result(_: This, block: *mut AsyncBlock) -> HRESULT {
  142. let none = std::ptr::null_mut();
  143. xasync::XAsyncGetResult(block, (&raw const PROMPT).cast(), 0, none, none.cast())
  144. }
  145. static VTABLE: Methods<8> = Methods([
  146. missing::<0> as *const (),
  147. add_ref as *const (),
  148. add_ref as *const (),
  149. path_size as *const (), // 0x18
  150. path as *const (), // 0x20
  151. space_info as *const (), // 0x28
  152. prompt_for_space as *const (), // 0x30
  153. prompt_result as *const (), // 0x38
  154. ]);
  155. #[cfg(test)]
  156. mod tests {
  157. use super::*;
  158. use crate::modules::xgameruntime::method;
  159. #[test]
  160. fn serves_a_drive_over_the_title_folder_and_its_quota() {
  161. type Size = extern "system" fn(This, *mut usize) -> HRESULT;
  162. type Get = extern "system" fn(This, usize, *mut u8, *mut usize) -> HRESULT;
  163. type Space = extern "system" fn(This, *mut SpaceInfo) -> HRESULT;
  164. type Prompt = extern "system" fn(This, u64, *mut AsyncBlock) -> HRESULT;
  165. type Result = extern "system" fn(This, *mut AsyncBlock) -> HRESULT;
  166. let this: This = &OBJECT;
  167. let dir = tempfile::tempdir().unwrap();
  168. std::fs::write(dir.path().join("save.dat"), [0u8; 100]).unwrap();
  169. runtime::set_title(runtime::Title {
  170. id: 1,
  171. storage: dir.path().to_owned(),
  172. storage_bytes: 1000,
  173. ..Default::default()
  174. });
  175. // The path is a drive root, never the host folder.
  176. let mut size = 0;
  177. assert_eq!(method::<Size>(&OBJECT, 0x18)(this, &mut size), S_OK);
  178. assert_eq!(size, 4, "X:\\ and its NUL");
  179. let (mut buffer, mut used) = ([0u8; 4], 0);
  180. let get = method::<Get>(&OBJECT, 0x20);
  181. assert_eq!(get(this, 4, buffer.as_mut_ptr(), &mut used), S_OK);
  182. assert_eq!(get(this, 3, buffer.as_mut_ptr(), &mut used), E_FAIL);
  183. let drive = std::str::from_utf8(&buffer[..3]).unwrap();
  184. assert!(drive.ends_with(":\\"), "{drive}");
  185. // Title file calls on it reach the folder.
  186. let path = format!("{drive}save.dat\0");
  187. let mut attributes = [0u8; 36];
  188. let get_attributes = super::super::files::GetFileAttributesExW;
  189. let wide: Vec<u16> = path.encode_utf16().collect();
  190. assert_ne!(
  191. get_attributes(wide.as_ptr(), 0, attributes.as_mut_ptr().cast()),
  192. 0
  193. );
  194. let mut info = SpaceInfo {
  195. available_free: 0,
  196. total_free: 0,
  197. used: 0,
  198. total: 0,
  199. };
  200. assert_eq!(method::<Space>(&OBJECT, 0x28)(this, &mut info), S_OK);
  201. assert_eq!((info.used, info.total_free, info.total), (100, 900, 1000));
  202. let prompt = method::<Prompt>(&OBJECT, 0x30);
  203. let result = method::<Result>(&OBJECT, 0x38);
  204. for (bytes, expect) in [(900, S_OK), (901, E_ABORT)] {
  205. let mut block = AsyncBlock {
  206. queue: std::ptr::null(),
  207. context: std::ptr::null_mut(),
  208. callback: None,
  209. internal: [0; 4],
  210. };
  211. assert_eq!(prompt(this, bytes, &mut block), S_OK);
  212. assert_eq!(xasync::XAsyncGetStatus(&mut block, true), expect);
  213. assert_eq!(result(this, &mut block), expect, "{bytes} bytes");
  214. }
  215. }
  216. }