xgamesave.rs 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492
  1. //! XGameSave: the user's game saves, kept on the host under the title's
  2. //! data directory, next to persistent local storage (`runtime::Title::
  3. //! saves`), never in the cache. A provider is a folder per user and
  4. //! service configuration, a container a folder in it.
  5. //!
  6. //! An update is all or nothing, as documented: each one writes a complete
  7. //! new version of the container (`v<N>.new/`, unchanged blobs hard-linked
  8. //! from the previous version), flushed to disk, and one directory rename
  9. //! commits it (`v<N>`); the highest committed version is the container.
  10. //! A crash leaves the old version or the new one, never a mix; leftovers
  11. //! are removed on sight. Deleting a container renames it away first.
  12. //!
  13. //! Names are exact: a version's `manifest` holds the container's name, its
  14. //! display name and the blob names (blob `i` is the file `i`), so case,
  15. //! characters the host forbids, reserved device names and length never
  16. //! reach a file name. A container's folder is its name made safe (and
  17. //! shortened) plus a hash of the exact name, so names differing only in
  18. //! case get different folders. Offline there is no cloud copy, so nothing
  19. //! ever needs a sync.
  20. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  21. use std::ffi::{CString, c_char, c_void};
  22. use std::io::Write as _;
  23. use std::path::{Path, PathBuf};
  24. use std::sync::Mutex;
  25. use super::xasync::{self, AsyncBlock, E_INVALIDARG};
  26. use super::xgameruntime::{
  27. Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text,
  28. };
  29. use super::{storage, xuser};
  30. use crate::runtime;
  31. pub const PROVIDER: Guid = Guid::new(
  32. 0x704c_3f58,
  33. 0xe629,
  34. 0x4cc2,
  35. [0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6f, 0xe2],
  36. );
  37. /// As the title (2026) asks for it; every slot it calls takes
  38. /// the public API's arguments in the same order as under the provider's
  39. /// own id (older titles).
  40. pub const IID_2026: Guid = Guid::new(
  41. 0x1bff_f3af,
  42. 0xf14a,
  43. 0x40a3,
  44. [0x8e, 0x35, 0x9a, 0xda, 0x90, 0x65, 0x93, 0xf9],
  45. );
  46. pub static OBJECT: Object = Object::new("game save", &VTABLE);
  47. pub const INTERFACES: &[Interface] =
  48. &[(PROVIDER, PROVIDER, &OBJECT), (PROVIDER, IID_2026, &OBJECT)];
  49. // The public API's error codes.
  50. pub const INVALID_CONTAINER_NAME: HRESULT = 0x8083_0001_u32 as i32;
  51. pub const NO_ACCESS: HRESULT = 0x8083_0002_u32 as i32;
  52. pub const OUT_OF_LOCAL_STORAGE: HRESULT = 0x8083_0003_u32 as i32;
  53. pub const UPDATE_TOO_BIG: HRESULT = 0x8083_0005_u32 as i32;
  54. pub const QUOTA_EXCEEDED: HRESULT = 0x8083_0006_u32 as i32;
  55. pub const BUFFER_TOO_SMALL: HRESULT = 0x8083_0007_u32 as i32;
  56. pub const BLOB_NOT_FOUND: HRESULT = 0x8083_0008_u32 as i32;
  57. /// Per user and title, as documented.
  58. const QUOTA: u64 = 256 << 20;
  59. /// What one update may write in all, as documented.
  60. const MAX_UPDATE: usize = 16 << 20;
  61. const MANIFEST: &str = "manifest";
  62. /// Readable part of a container's folder name, at most.
  63. const READABLE: usize = 100;
  64. /// Every save operation, so none sees another's half-made version.
  65. static SAVES: Mutex<()> = Mutex::new(());
  66. fn saves_lock() -> std::sync::MutexGuard<'static, ()> {
  67. SAVES.lock().unwrap_or_else(|e| e.into_inner())
  68. }
  69. /// `name` as a file name: letters, digits, `-` and `_` stay, every other
  70. /// byte becomes `%XX`. The result never contains a dot.
  71. fn file_name(name: &str) -> String {
  72. name.bytes()
  73. .map(|b| match b {
  74. b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' => (b as char).to_string(),
  75. _ => format!("%{b:02X}"),
  76. })
  77. .collect()
  78. }
  79. /// The name behind a file name from [`file_name`]; `None` for other files.
  80. fn decode(file: &str) -> Option<String> {
  81. if file.contains('.') {
  82. return None;
  83. }
  84. let mut out = Vec::new();
  85. let mut bytes = file.bytes();
  86. while let Some(b) = bytes.next() {
  87. if b == b'%' {
  88. let hex = [bytes.next()?, bytes.next()?];
  89. out.push(u8::from_str_radix(std::str::from_utf8(&hex).ok()?, 16).ok()?);
  90. } else {
  91. out.push(b);
  92. }
  93. }
  94. String::from_utf8(out).ok()
  95. }
  96. /// The container's folder: its name made safe, cut short, then `~` and a
  97. /// hash of the exact name (64-bit FNV-1a, stable across builds).
  98. fn container_dir(root: &Path, name: &str) -> PathBuf {
  99. let hash = name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| {
  100. (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3)
  101. });
  102. let mut readable = file_name(name);
  103. readable.truncate(READABLE); // ASCII only
  104. root.join(format!("{readable}~{hash:016x}"))
  105. }
  106. /// Documented: the path part (up to the last `/`) letters, digits, `_` and
  107. /// `/`; the file part letters, digits, `_`, `.` and `-`, not empty, not
  108. /// ending in `.`, no `..`; 256 characters at most.
  109. fn valid_container(name: &str) -> bool {
  110. let (path, file) = name.rsplit_once('/').unwrap_or(("", name));
  111. name.len() <= 256
  112. && path
  113. .bytes()
  114. .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'/')
  115. && !file.is_empty()
  116. && !file.ends_with('.')
  117. && !file.contains("..")
  118. && file
  119. .bytes()
  120. .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-'))
  121. }
  122. /// A committed version of a container.
  123. struct Version {
  124. dir: PathBuf,
  125. /// The highest version number any entry in the container's folder
  126. /// carries, readable or not; the next commit goes above it.
  127. highest: u64,
  128. name: String,
  129. display: String,
  130. /// Blob names; blob `i` is the file `i`.
  131. blobs: Vec<String>,
  132. }
  133. impl Version {
  134. fn blob(&self, i: usize) -> PathBuf {
  135. self.dir.join(i.to_string())
  136. }
  137. fn sizes(&self) -> Vec<(String, u64)> {
  138. let size = |i| std::fs::metadata(self.blob(i)).map_or(0, |m| m.len());
  139. let blobs = self.blobs.iter().enumerate();
  140. blobs.map(|(i, n)| (n.clone(), size(i))).collect()
  141. }
  142. }
  143. /// The manifest: length-prefixed strings (u32 LE): container name, display
  144. /// name, then each blob name.
  145. fn manifest(name: &str, display: &str, blobs: &[&str]) -> Vec<u8> {
  146. let mut out = Vec::new();
  147. for s in [name, display].into_iter().chain(blobs.iter().copied()) {
  148. out.extend_from_slice(&(s.len() as u32).to_le_bytes());
  149. out.extend_from_slice(s.as_bytes());
  150. }
  151. out
  152. }
  153. fn parse_manifest(bytes: &[u8]) -> Option<Vec<String>> {
  154. let mut out = Vec::new();
  155. let mut rest = bytes;
  156. while !rest.is_empty() {
  157. let (len, tail) = rest.split_first_chunk::<4>()?;
  158. let len = u32::from_le_bytes(*len) as usize;
  159. out.push(String::from_utf8(tail.get(..len)?.to_vec()).ok()?);
  160. rest = &tail[len..];
  161. }
  162. (out.len() >= 2).then_some(out)
  163. }
  164. /// The number of a version folder exactly as [`commit`] names it (`v1`,
  165. /// `v2`, ...); `None` for anything else, such as `v01`, `v+1` or `v0`.
  166. fn version_number(file: &str) -> Option<u64> {
  167. let n = file.strip_prefix('v')?.parse::<u64>().ok()?;
  168. (n > 0 && format!("v{n}") == file).then_some(n)
  169. }
  170. /// The names in version folder `dir`: container, display, blobs; `None` if
  171. /// its manifest is missing or does not parse.
  172. fn load(dir: &Path) -> std::io::Result<Option<(String, String, Vec<String>)>> {
  173. let bytes = match std::fs::read(dir.join(MANIFEST)) {
  174. Ok(bytes) => bytes,
  175. Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
  176. Err(e) => return Err(e),
  177. };
  178. let Some(mut names) = parse_manifest(&bytes) else {
  179. return Ok(None);
  180. };
  181. let blobs = names.split_off(2);
  182. let [name, display] = <[String; 2]>::try_from(names).expect("two names, checked by the parser");
  183. Ok(Some((name, display, blobs)))
  184. }
  185. /// The container's newest readable committed version, if any. Removes what
  186. /// a crash left: unfinished versions, and versions older than that one.
  187. /// An unreadable newer folder (a stray, or a broken manifest) is neither
  188. /// taken nor removed, and never costs the version below it.
  189. fn current(dir: &Path) -> std::io::Result<Option<Version>> {
  190. let mut committed = Vec::new();
  191. let mut highest = 0;
  192. for entry in std::fs::read_dir(dir)?.flatten() {
  193. let file = entry.file_name();
  194. let file = file.to_string_lossy();
  195. if file.ends_with(".new") {
  196. std::fs::remove_dir_all(entry.path())?;
  197. } else if let Some(n) = version_number(&file) {
  198. highest = highest.max(n);
  199. if entry.file_type().is_ok_and(|t| t.is_dir()) {
  200. committed.push(n);
  201. }
  202. }
  203. }
  204. committed.sort_unstable_by(|a, b| b.cmp(a));
  205. if committed.is_empty() {
  206. return Ok(None);
  207. }
  208. for (at, &number) in committed.iter().enumerate() {
  209. let version = dir.join(format!("v{number}"));
  210. let Some((name, display, blobs)) = load(&version)? else {
  211. continue;
  212. };
  213. for old in &committed[at + 1..] {
  214. std::fs::remove_dir_all(dir.join(format!("v{old}")))?;
  215. }
  216. return Ok(Some(Version {
  217. dir: version,
  218. highest,
  219. name,
  220. display,
  221. blobs,
  222. }));
  223. }
  224. // Versions exist but none reads: keep them all, and refuse.
  225. Err(std::io::Error::new(
  226. std::io::ErrorKind::InvalidData,
  227. "no save version has a readable manifest",
  228. ))
  229. }
  230. /// The version of container `name` in `dir`; none for a missing container
  231. /// or another name that hashes alike.
  232. fn current_named(dir: &Path, name: &str) -> std::io::Result<Option<Version>> {
  233. match current(dir) {
  234. Ok(v) => Ok(v.filter(|v| v.name == name)),
  235. Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
  236. Err(e) => Err(e),
  237. }
  238. }
  239. /// Where a crash test stops the process (test builds only).
  240. fn step() {
  241. #[cfg(test)]
  242. tests::crash_point();
  243. }
  244. /// A blob of a new version: new data, or the previous version's file.
  245. enum Source<'a> {
  246. Data(&'a [u8]),
  247. Kept(PathBuf),
  248. }
  249. /// Writes version `number` of the container in `dir` and commits it.
  250. fn commit(
  251. dir: &Path,
  252. number: u64,
  253. name: &str,
  254. display: &str,
  255. blobs: &[(&str, Source<'_>)],
  256. ) -> std::io::Result<()> {
  257. let staged = dir.join(format!("v{number}.new"));
  258. if staged.exists() {
  259. std::fs::remove_dir_all(&staged)?;
  260. }
  261. std::fs::create_dir_all(&staged)?;
  262. let write = |path: PathBuf, data: &[u8]| -> std::io::Result<()> {
  263. let mut file = std::fs::File::create(path)?;
  264. file.write_all(data)?;
  265. file.sync_all()
  266. };
  267. for (i, (_, source)) in blobs.iter().enumerate() {
  268. let path = staged.join(i.to_string());
  269. match source {
  270. Source::Data(data) => write(path, data)?,
  271. // Files are never changed in place, so sharing one is safe.
  272. Source::Kept(from) => {
  273. std::fs::hard_link(from, &path).or_else(|_| write(path, &std::fs::read(from)?))?
  274. }
  275. }
  276. step();
  277. }
  278. let names: Vec<&str> = blobs.iter().map(|(n, _)| *n).collect();
  279. write(staged.join(MANIFEST), &manifest(name, display, &names))?;
  280. step();
  281. std::fs::rename(&staged, dir.join(format!("v{number}")))?;
  282. step();
  283. Ok(())
  284. }
  285. /// The containers under a provider's root, by exact name; containers in
  286. /// the old one-file-per-blob layout are converted first.
  287. fn containers(root: &Path) -> Vec<(String, PathBuf)> {
  288. let mut out = Vec::new();
  289. for entry in std::fs::read_dir(root).into_iter().flatten().flatten() {
  290. let path = entry.path();
  291. let file = entry.file_name().to_string_lossy().into_owned();
  292. if !path.is_dir() {
  293. continue;
  294. }
  295. if file.ends_with(".gone") {
  296. let _ = std::fs::remove_dir_all(&path);
  297. } else if file.contains('~') {
  298. if let Ok(Some(v)) = current(&path) {
  299. out.push((v.name, path));
  300. }
  301. } else if let Some(name) = decode(&file)
  302. && let Some(dir) = migrate(root, &name, &path)
  303. {
  304. out.push((name, dir));
  305. }
  306. }
  307. out.sort();
  308. out
  309. }
  310. /// Moves a container of the old layout (blob files named by encoded name,
  311. /// a `.display` file) into a committed version, then removes it.
  312. fn migrate(root: &Path, name: &str, old: &Path) -> Option<PathBuf> {
  313. let dir = container_dir(root, name);
  314. let done = current_named(&dir, name).ok()?.is_some(); // a crash after the commit
  315. if !done {
  316. let display = std::fs::read_to_string(old.join(".display")).unwrap_or_default();
  317. let mut blobs: Vec<(String, Vec<u8>)> = std::fs::read_dir(old)
  318. .ok()?
  319. .flatten()
  320. .filter_map(|e| {
  321. let blob = decode(e.file_name().to_str()?)?;
  322. Some((blob, std::fs::read(e.path()).ok()?))
  323. })
  324. .collect();
  325. blobs.sort();
  326. let sources: Vec<_> = blobs
  327. .iter()
  328. .map(|(n, d)| (n.as_str(), Source::Data(d)))
  329. .collect();
  330. commit(&dir, 1, name, &display, &sources).ok()?;
  331. }
  332. std::fs::remove_dir_all(old).ok()?;
  333. tracing::info!(container = name, "game save moved to the versioned layout");
  334. Some(dir)
  335. }
  336. fn used_bytes(root: &Path) -> u64 {
  337. containers(root)
  338. .iter()
  339. .filter_map(|(name, dir)| current_named(dir, name).ok().flatten())
  340. .map(|v| v.sizes().iter().map(|(_, size)| size).sum::<u64>())
  341. .sum()
  342. }
  343. struct Provider {
  344. root: PathBuf,
  345. }
  346. struct Container {
  347. name: String,
  348. dir: PathBuf,
  349. }
  350. struct Update {
  351. name: String,
  352. dir: PathBuf,
  353. display: Option<String>,
  354. /// Blob writes (`Some`) and deletions (`None`), in order.
  355. changes: Vec<(String, Option<Vec<u8>>)>,
  356. }
  357. /// A handle we gave out.
  358. fn get<'a, T>(handle: *const T) -> Option<&'a T> {
  359. // SAFETY: handles are boxes we created and the title has not closed.
  360. unsafe { handle.as_ref() }
  361. }
  362. fn give<T>(value: T) -> *mut T {
  363. Box::into_raw(Box::new(value))
  364. }
  365. fn take<T>(handle: *mut T) {
  366. if !handle.is_null() {
  367. // SAFETY: as in `get`; closing ends the handle.
  368. drop(unsafe { Box::from_raw(handle) });
  369. }
  370. }
  371. impl Provider {
  372. /// The provider for the only user and `config` (the service
  373. /// configuration id), under `saves`. An empty id names no
  374. /// configuration, like none: as a folder name it would be the user's
  375. /// folder itself, where the other configurations' folders are.
  376. fn open(saves: &Path, config: Option<&str>) -> Result<Provider, HRESULT> {
  377. let config = config.filter(|c| !c.is_empty()).unwrap_or("default");
  378. let root = saves
  379. .join(format!("{:016X}", xuser::XUID))
  380. .join(file_name(config));
  381. std::fs::create_dir_all(&root).map_err(|_| NO_ACCESS)?;
  382. let _saves = saves_lock();
  383. containers(&root); // converts old containers now
  384. Ok(Provider { root })
  385. }
  386. fn remaining(&self) -> u64 {
  387. let _saves = saves_lock();
  388. remaining(&self.root)
  389. }
  390. fn container(&self, name: &str) -> Container {
  391. Container {
  392. name: name.to_owned(),
  393. dir: container_dir(&self.root, name),
  394. }
  395. }
  396. }
  397. /// Quota left under a provider's root, or less if the host disk is fuller.
  398. fn remaining(root: &Path) -> u64 {
  399. QUOTA
  400. .saturating_sub(used_bytes(root))
  401. .min(storage::disk_free(root))
  402. }
  403. /// Why an update writing `written` bytes, `replaced` of them over blobs it
  404. /// replaces, does not fit: past the per-user quota (`used` bytes kept), or
  405. /// past the host disk's `free` bytes, which is not the user's quota (the
  406. /// new version is written before the old one goes, so nothing it replaces
  407. /// counts there).
  408. fn no_room(written: u64, replaced: u64, used: u64, free: u64) -> Option<HRESULT> {
  409. if written > QUOTA.saturating_sub(used) + replaced {
  410. Some(QUOTA_EXCEEDED)
  411. } else if written > free {
  412. Some(OUT_OF_LOCAL_STORAGE)
  413. } else {
  414. None
  415. }
  416. }
  417. fn io_error(dir: &Path, e: &std::io::Error) -> HRESULT {
  418. tracing::warn!(dir = %dir.display(), %e, "game save");
  419. if e.kind() == std::io::ErrorKind::StorageFull {
  420. OUT_OF_LOCAL_STORAGE
  421. } else {
  422. NO_ACCESS
  423. }
  424. }
  425. impl Update {
  426. /// Applies the update as one new version of the container.
  427. fn submit(&self) -> HRESULT {
  428. let _saves = saves_lock();
  429. let current = match current(&self.dir) {
  430. Ok(v) => v,
  431. Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
  432. Err(e) => return io_error(&self.dir, &e),
  433. };
  434. if current.as_ref().is_some_and(|v| v.name != self.name) {
  435. // Another container's name hashes alike: never mix the two.
  436. return NO_ACCESS;
  437. }
  438. // The blobs after the update: name → new data or the kept file.
  439. let mut blobs: Vec<(&str, Source<'_>)> = current
  440. .iter()
  441. .flat_map(|v| {
  442. let kept = v.blobs.iter().enumerate();
  443. kept.map(|(i, n)| (n.as_str(), Source::Kept(v.blob(i))))
  444. })
  445. .collect();
  446. for (name, data) in &self.changes {
  447. blobs.retain(|(n, _)| n != name);
  448. if let Some(data) = data {
  449. blobs.push((name, Source::Data(data)));
  450. }
  451. }
  452. blobs.sort_by(|a, b| a.0.cmp(b.0));
  453. let written: usize = blobs
  454. .iter()
  455. .map(|(_, s)| match s {
  456. Source::Data(d) => d.len(),
  457. Source::Kept(_) => 0,
  458. })
  459. .sum();
  460. if written > MAX_UPDATE {
  461. return UPDATE_TOO_BIG;
  462. }
  463. let replaced: u64 = current.as_ref().map_or(0, |v| {
  464. let sizes = v.sizes();
  465. let changed = sizes.iter().filter(|(n, _)| self.changes.iter().any(|(c, _)| c == n));
  466. changed.map(|(_, size)| size).sum()
  467. });
  468. let root = self.dir.parent().unwrap_or(&self.dir);
  469. let free = storage::disk_free(root);
  470. if let Some(hr) = no_room(written as u64, replaced, used_bytes(root), free) {
  471. return hr;
  472. }
  473. let display = self.display.as_deref();
  474. let display = display.or(current.as_ref().map(|v| v.display.as_str()));
  475. let number = current.as_ref().map_or(1, |v| v.highest + 1);
  476. if let Err(e) = commit(&self.dir, number, &self.name, display.unwrap_or(""), &blobs) {
  477. return io_error(&self.dir, &e);
  478. }
  479. // The old version is garbage now; a crash here leaves it for later.
  480. if let Some(old) = &current {
  481. let _ = std::fs::remove_dir_all(&old.dir);
  482. step();
  483. }
  484. S_OK
  485. }
  486. }
  487. /// Deletes a container: renamed away (one step), then removed.
  488. fn delete(root: &Path, name: &str) -> HRESULT {
  489. let _saves = saves_lock();
  490. let dir = container_dir(root, name);
  491. match current_named(&dir, name) {
  492. Ok(Some(_)) => {}
  493. Ok(None) => return S_OK,
  494. Err(e) => return io_error(&dir, &e),
  495. }
  496. let gone = dir.with_extension("gone");
  497. let _ = std::fs::remove_dir_all(&gone);
  498. step();
  499. if let Err(e) = std::fs::rename(&dir, &gone) {
  500. return io_error(&dir, &e);
  501. }
  502. step();
  503. let _ = std::fs::remove_dir_all(&gone);
  504. S_OK
  505. }
  506. /// Reads the named blobs (all of them for `None`) of a container.
  507. fn read(c: &Container, names: Option<Vec<String>>) -> Result<Vec<(String, Vec<u8>)>, HRESULT> {
  508. let _saves = saves_lock();
  509. let version = current_named(&c.dir, &c.name)
  510. .map_err(|e| io_error(&c.dir, &e))?
  511. .ok_or(BLOB_NOT_FOUND)?;
  512. let names = names.unwrap_or_else(|| version.blobs.clone());
  513. names
  514. .into_iter()
  515. .map(|name| {
  516. let i = version.blobs.iter().position(|b| *b == name).ok_or(BLOB_NOT_FOUND)?;
  517. let data = std::fs::read(version.blob(i)).map_err(|e| io_error(&c.dir, &e))?;
  518. Ok((name, data))
  519. })
  520. .collect()
  521. }
  522. /// One blob as the public API lays it out: name, size, data.
  523. const BLOB: usize = 24;
  524. /// Blobs laid out as the title reads them: the blob array, then each name
  525. /// (NUL-terminated) and its data, with pointers `base` plus offset.
  526. fn layout(blobs: &[(String, Vec<u8>)], base: usize) -> Vec<u8> {
  527. let mut out = vec![0u8; blobs.len() * BLOB];
  528. for (i, (name, data)) in blobs.iter().enumerate() {
  529. let name_at = base + out.len();
  530. out.extend_from_slice(name.as_bytes());
  531. out.push(0);
  532. let data_at = base + out.len();
  533. out.extend_from_slice(data);
  534. let entry = &mut out[i * BLOB..(i + 1) * BLOB];
  535. entry[..8].copy_from_slice(&name_at.to_le_bytes());
  536. entry[8..12].copy_from_slice(&(data.len() as u32).to_le_bytes());
  537. entry[16..].copy_from_slice(&data_at.to_le_bytes());
  538. }
  539. out
  540. }
  541. /// The names a title passes (`count` strings, or all blobs if null).
  542. fn names(names: *const *const c_char, count: u32) -> Option<Vec<String>> {
  543. if names.is_null() {
  544. return None;
  545. }
  546. // SAFETY: the title passes `count` strings.
  547. let names = unsafe { std::slice::from_raw_parts(names, count as usize) };
  548. Some(names.iter().map(|&n| text(n).unwrap_or_default()).collect())
  549. }
  550. type This = *const Object;
  551. type ContainerCallback = extern "system" fn(*const ContainerInfo, *mut c_void) -> bool;
  552. type BlobCallback = extern "system" fn(*const BlobInfo, *mut c_void) -> bool;
  553. #[repr(C)]
  554. pub struct ContainerInfo {
  555. pub name: *const c_char,
  556. pub display_name: *const c_char,
  557. pub blob_count: u32,
  558. pub total_size: u64,
  559. pub last_modified: i64,
  560. pub needs_sync: bool,
  561. }
  562. #[repr(C)]
  563. pub struct BlobInfo {
  564. pub name: *const c_char,
  565. pub size: u32,
  566. }
  567. /// Calls `callback` with the information of each container that passes
  568. /// `keep` until it returns false; never under our lock (it may call us).
  569. fn report(root: &Path, keep: impl Fn(&str) -> bool, context: *mut c_void, callback: ContainerCallback) {
  570. let infos: Vec<(CString, CString, u32, u64, i64)> = {
  571. let _saves = saves_lock();
  572. containers(root)
  573. .into_iter()
  574. .filter(|(name, _)| keep(name))
  575. .filter_map(|(name, dir)| current_named(&dir, &name).ok().flatten())
  576. .map(|v| {
  577. let modified = std::fs::metadata(v.dir.join(MANIFEST))
  578. .and_then(|m| m.modified())
  579. .ok()
  580. .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
  581. .map_or(0, |d| d.as_secs() as i64);
  582. let size = v.sizes().iter().map(|(_, s)| s).sum();
  583. let count = v.blobs.len() as u32;
  584. (cstring(&v.name), cstring(&v.display), count, size, modified)
  585. })
  586. .collect()
  587. };
  588. for (name, display, blob_count, total_size, last_modified) in &infos {
  589. let info = ContainerInfo {
  590. name: name.as_ptr(),
  591. display_name: display.as_ptr(),
  592. blob_count: *blob_count,
  593. total_size: *total_size,
  594. last_modified: *last_modified,
  595. needs_sync: false,
  596. };
  597. if !callback(&info, context) {
  598. break;
  599. }
  600. }
  601. }
  602. fn cstring(s: &str) -> CString {
  603. CString::new(s.replace('\0', "")).unwrap_or_default()
  604. }
  605. static INIT: u8 = 0;
  606. static QUOTA_CALL: u8 = 0;
  607. static DELETE: u8 = 0;
  608. static READ: u8 = 0;
  609. static SUBMIT: u8 = 0;
  610. extern "system" fn initialize_async(
  611. _: This,
  612. _user: *const c_void,
  613. config: *const c_char,
  614. _sync_on_demand: bool,
  615. block: *mut AsyncBlock,
  616. ) -> HRESULT {
  617. let saves = runtime::title().saves();
  618. let result = if saves.parent().is_none_or(|p| p.as_os_str().is_empty()) {
  619. Err(NO_ACCESS)
  620. } else {
  621. Provider::open(&saves, text(config).as_deref()).map(|p| xasync::bytes(give(p)))
  622. };
  623. xasync::finished_with(block, (&raw const INIT).cast(), result)
  624. }
  625. extern "system" fn initialize_result(
  626. _: This,
  627. block: *mut AsyncBlock,
  628. out: *mut *mut Provider,
  629. ) -> HRESULT {
  630. xasync::result(block, (&raw const INIT).cast(), out)
  631. }
  632. extern "system" fn close_provider(_: This, provider: *mut Provider) {
  633. take(provider);
  634. }
  635. extern "system" fn quota_async(
  636. _: This,
  637. provider: *const Provider,
  638. block: *mut AsyncBlock,
  639. ) -> HRESULT {
  640. let result = get(provider)
  641. .ok_or(E_INVALIDARG)
  642. .map(|p| xasync::bytes(p.remaining() as i64));
  643. xasync::finished_with(block, (&raw const QUOTA_CALL).cast(), result)
  644. }
  645. extern "system" fn quota_result(_: This, block: *mut AsyncBlock, out: *mut i64) -> HRESULT {
  646. xasync::result(block, (&raw const QUOTA_CALL).cast(), out)
  647. }
  648. extern "system" fn delete_async(
  649. _: This,
  650. provider: *const Provider,
  651. name: *const c_char,
  652. block: *mut AsyncBlock,
  653. ) -> HRESULT {
  654. let hr = match (get(provider), text(name)) {
  655. (Some(p), Some(name)) if valid_container(&name) => delete(&p.root, &name),
  656. (Some(_), Some(_)) => INVALID_CONTAINER_NAME,
  657. _ => E_INVALIDARG,
  658. };
  659. xasync::finished(block, (&raw const DELETE).cast(), hr)
  660. }
  661. extern "system" fn delete_result(_: This, block: *mut AsyncBlock) -> HRESULT {
  662. let none = std::ptr::null_mut();
  663. xasync::XAsyncGetResult(block, (&raw const DELETE).cast(), 0, none, none.cast())
  664. }
  665. /// Reports the container if it exists; a missing one is no error, the
  666. /// callback just does not run.
  667. extern "system" fn container_info(
  668. _: This,
  669. provider: *const Provider,
  670. name: *const c_char,
  671. context: *mut c_void,
  672. callback: Option<ContainerCallback>,
  673. ) -> HRESULT {
  674. let (Some(p), Some(name), Some(callback)) = (get(provider), text(name), callback) else {
  675. return E_INVALIDARG;
  676. };
  677. if !valid_container(&name) {
  678. return INVALID_CONTAINER_NAME;
  679. }
  680. report(&p.root, |n| n == name, context, callback);
  681. S_OK
  682. }
  683. extern "system" fn enumerate_containers(
  684. _: This,
  685. provider: *const Provider,
  686. context: *mut c_void,
  687. callback: Option<ContainerCallback>,
  688. ) -> HRESULT {
  689. let (Some(p), Some(callback)) = (get(provider), callback) else {
  690. return E_INVALIDARG;
  691. };
  692. report(&p.root, |_| true, context, callback);
  693. S_OK
  694. }
  695. /// The container exists once an update to it is submitted.
  696. extern "system" fn create_container(
  697. _: This,
  698. provider: *const Provider,
  699. name: *const c_char,
  700. out: *mut *mut Container,
  701. ) -> HRESULT {
  702. let (Some(p), Some(name)) = (get(provider), text(name)) else {
  703. return E_INVALIDARG;
  704. };
  705. if !valid_container(&name) {
  706. return INVALID_CONTAINER_NAME;
  707. }
  708. put(out, give(p.container(&name)))
  709. }
  710. extern "system" fn close_container(_: This, container: *mut Container) {
  711. take(container);
  712. }
  713. extern "system" fn enumerate_blobs(
  714. _: This,
  715. container: *const Container,
  716. prefix: *const c_char,
  717. context: *mut c_void,
  718. callback: Option<BlobCallback>,
  719. ) -> HRESULT {
  720. let (Some(c), Some(callback)) = (get(container), callback) else {
  721. return E_INVALIDARG;
  722. };
  723. let prefix = text(prefix).unwrap_or_default();
  724. let blobs = {
  725. let _saves = saves_lock();
  726. let version = current_named(&c.dir, &c.name).ok().flatten();
  727. version.map(|v| v.sizes()).unwrap_or_default()
  728. };
  729. for (name, size) in blobs.into_iter().filter(|(n, _)| n.starts_with(&prefix)) {
  730. let name = cstring(&name);
  731. let info = BlobInfo {
  732. name: name.as_ptr(),
  733. size: size as u32,
  734. };
  735. if !callback(&info, context) {
  736. break;
  737. }
  738. }
  739. S_OK
  740. }
  741. extern "system" fn read_blobs(
  742. _: This,
  743. container: *const Container,
  744. blob_names: *const *const c_char,
  745. count: *mut u32,
  746. size: usize,
  747. out: *mut u8,
  748. ) -> HRESULT {
  749. let Some(c) = get(container) else {
  750. return E_INVALIDARG;
  751. };
  752. // SAFETY: the title passes its count.
  753. let wanted = unsafe { count.as_ref() }.copied().unwrap_or(0);
  754. let blobs = match read(c, names(blob_names, wanted)) {
  755. Ok(blobs) => blobs,
  756. Err(hr) => return hr,
  757. };
  758. let bytes = layout(&blobs, out as usize);
  759. if out.is_null() || size < bytes.len() {
  760. return BUFFER_TOO_SMALL;
  761. }
  762. // SAFETY: the buffer holds `size` bytes, checked above.
  763. unsafe { out.copy_from_nonoverlapping(bytes.as_ptr(), bytes.len()) };
  764. put(count, blobs.len() as u32)
  765. }
  766. /// Read at once; the result holds the layout with pointers relative to the
  767. /// title's buffer, fixed up when the title takes it.
  768. extern "system" fn read_async(
  769. _: This,
  770. container: *const Container,
  771. blob_names: *const *const c_char,
  772. count: u32,
  773. block: *mut AsyncBlock,
  774. ) -> HRESULT {
  775. let result = match get(container) {
  776. Some(c) => read(c, names(blob_names, count)).map(|blobs| layout(&blobs, 0)),
  777. None => Err(E_INVALIDARG),
  778. };
  779. xasync::finished_with(block, (&raw const READ).cast(), result)
  780. }
  781. extern "system" fn read_result(
  782. _: This,
  783. block: *mut AsyncBlock,
  784. size: usize,
  785. out: *mut u8,
  786. count: *mut u32,
  787. ) -> HRESULT {
  788. let mut used = 0;
  789. let hr = xasync::XAsyncGetResult(block, (&raw const READ).cast(), size, out.cast(), &mut used);
  790. // The documented error for a small buffer; the result stays for a
  791. // retry with a larger one.
  792. if hr == xasync::E_NOT_SUFFICIENT_BUFFER {
  793. return BUFFER_TOO_SMALL;
  794. }
  795. if hr < 0 {
  796. return hr;
  797. }
  798. // The first name follows the blob array, so its offset gives the count.
  799. let blobs = if used == 0 {
  800. 0
  801. } else {
  802. // SAFETY: the result holds at least one blob entry.
  803. unsafe { out.cast::<usize>().read_unaligned() / BLOB }
  804. };
  805. for i in 0..blobs {
  806. for field in [0, 16] {
  807. // SAFETY: within the blob array just written.
  808. unsafe {
  809. let p = out.add(i * BLOB + field).cast::<usize>();
  810. p.write_unaligned(p.read_unaligned() + out as usize);
  811. }
  812. }
  813. }
  814. put(count, blobs as u32)
  815. }
  816. extern "system" fn create_update(
  817. _: This,
  818. container: *const Container,
  819. display: *const c_char,
  820. out: *mut *mut Update,
  821. ) -> HRESULT {
  822. let Some(c) = get(container) else {
  823. return E_INVALIDARG;
  824. };
  825. put(
  826. out,
  827. give(Update {
  828. name: c.name.clone(),
  829. dir: c.dir.clone(),
  830. display: text(display),
  831. changes: Vec::new(),
  832. }),
  833. )
  834. }
  835. extern "system" fn close_update(_: This, update: *mut Update) {
  836. take(update);
  837. }
  838. extern "system" fn write_blob(
  839. _: This,
  840. update: *mut Update,
  841. name: *const c_char,
  842. data: *const u8,
  843. size: usize,
  844. ) -> HRESULT {
  845. // SAFETY: a handle we gave out; the title does not use it concurrently.
  846. let (Some(update), Some(name)) = (unsafe { update.as_mut() }, text(name)) else {
  847. return E_INVALIDARG;
  848. };
  849. if name.is_empty() || (data.is_null() && size > 0) {
  850. return E_INVALIDARG;
  851. }
  852. if size > MAX_UPDATE {
  853. return UPDATE_TOO_BIG;
  854. }
  855. let data = if size == 0 {
  856. Vec::new()
  857. } else {
  858. // SAFETY: the title passes `size` bytes.
  859. unsafe { std::slice::from_raw_parts(data, size) }.to_vec()
  860. };
  861. update.changes.push((name, Some(data)));
  862. S_OK
  863. }
  864. extern "system" fn delete_blob(_: This, update: *mut Update, name: *const c_char) -> HRESULT {
  865. // SAFETY: as in `write_blob`.
  866. match (unsafe { update.as_mut() }, text(name)) {
  867. (Some(update), Some(name)) if !name.is_empty() => {
  868. update.changes.push((name, None));
  869. S_OK
  870. }
  871. _ => E_INVALIDARG,
  872. }
  873. }
  874. extern "system" fn submit_async(_: This, update: *const Update, block: *mut AsyncBlock) -> HRESULT {
  875. let hr = get(update).map_or(E_INVALIDARG, Update::submit);
  876. xasync::finished(block, (&raw const SUBMIT).cast(), hr)
  877. }
  878. extern "system" fn submit_result(_: This, block: *mut AsyncBlock) -> HRESULT {
  879. let none = std::ptr::null_mut();
  880. xasync::XAsyncGetResult(block, (&raw const SUBMIT).cast(), 0, none, none.cast())
  881. }
  882. static VTABLE: Methods<30> = Methods([
  883. missing::<0> as *const (),
  884. add_ref as *const (),
  885. add_ref as *const (),
  886. missing::<3> as *const (), // 0x18 initialize (blocking)
  887. initialize_async as *const (), // 0x20
  888. initialize_result as *const (), // 0x28
  889. close_provider as *const (), // 0x30
  890. missing::<7> as *const (), // 0x38 remaining quota (blocking)
  891. quota_async as *const (), // 0x40
  892. quota_result as *const (), // 0x48
  893. missing::<10> as *const (), // 0x50 delete (blocking)
  894. delete_async as *const (), // 0x58
  895. delete_result as *const (), // 0x60
  896. container_info as *const (), // 0x68
  897. enumerate_containers as *const (), // 0x70
  898. missing::<15> as *const (), // 0x78 by name prefix
  899. create_container as *const (), // 0x80
  900. close_container as *const (), // 0x88
  901. missing::<18> as *const (), // 0x90 all blob info
  902. enumerate_blobs as *const (), // 0x98 by name prefix
  903. read_blobs as *const (), // 0xa0
  904. read_async as *const (), // 0xa8
  905. read_result as *const (), // 0xb0
  906. create_update as *const (), // 0xb8
  907. close_update as *const (), // 0xc0
  908. write_blob as *const (), // 0xc8
  909. delete_blob as *const (), // 0xd0
  910. missing::<27> as *const (), // 0xd8 submit (blocking)
  911. submit_async as *const (), // 0xe0
  912. submit_result as *const (), // 0xe8
  913. ]);
  914. #[cfg(test)]
  915. mod tests {
  916. use std::io::BufRead;
  917. use std::sync::atomic::{AtomicU32, Ordering};
  918. use super::*;
  919. use crate::modules::xgameruntime::method;
  920. fn block() -> AsyncBlock {
  921. AsyncBlock {
  922. queue: std::ptr::null(),
  923. context: std::ptr::null_mut(),
  924. callback: None,
  925. internal: [0; 4],
  926. }
  927. }
  928. static STEPS: AtomicU32 = AtomicU32::new(0);
  929. /// In a child process of the crash test, stops for good at the step
  930. /// `VICTORY_SAVE_STOP` names and says so.
  931. pub(super) fn crash_point() {
  932. let Ok(stop) = std::env::var("VICTORY_SAVE_STOP") else {
  933. return;
  934. };
  935. if stop.parse() == Ok(STEPS.fetch_add(1, Ordering::SeqCst) + 1) {
  936. println!("STOPPED");
  937. let _ = std::io::stdout().flush();
  938. loop {
  939. std::thread::sleep(std::time::Duration::from_secs(60));
  940. }
  941. }
  942. }
  943. /// The per-user quota and the host disk fail with their own errors.
  944. #[test]
  945. fn a_full_disk_is_not_the_quota() {
  946. let mb = 1 << 20;
  947. assert_eq!(no_room(2 * mb, 0, 0, mb), Some(OUT_OF_LOCAL_STORAGE));
  948. assert_eq!(no_room(2 * mb, 0, QUOTA - mb, 100 * mb), Some(QUOTA_EXCEEDED));
  949. // Replacing a blob of the same size fits a full quota.
  950. assert_eq!(no_room(mb, mb, QUOTA, 100 * mb), None);
  951. assert_eq!(no_room(mb, 0, 0, mb), None);
  952. }
  953. fn update(root: &Path, display: &str, changes: &[(&str, Option<&str>)]) -> HRESULT {
  954. Update {
  955. name: "Slot".into(),
  956. dir: container_dir(root, "Slot"),
  957. display: Some(display.into()),
  958. changes: changes
  959. .iter()
  960. .map(|(n, d)| (n.to_string(), d.map(|d| d.as_bytes().to_vec())))
  961. .collect(),
  962. }
  963. .submit()
  964. }
  965. /// The container `Slot`: display name and blobs.
  966. fn state(root: &Path) -> Option<(String, Vec<(String, String)>)> {
  967. let c = Provider { root: root.into() }.container("Slot");
  968. let display = current_named(&c.dir, "Slot").unwrap()?.display;
  969. let blobs = read(&c, None).unwrap();
  970. let text = |(n, d): (String, Vec<u8>)| (n, String::from_utf8(d).unwrap());
  971. Some((display, blobs.into_iter().map(text).collect()))
  972. }
  973. fn old_state() -> Option<(String, Vec<(String, String)>)> {
  974. Some(("one".into(), vec![("a".into(), "old a".into()), ("b".into(), "old b".into())]))
  975. }
  976. /// Run by the crash test in a child process; does nothing otherwise.
  977. #[test]
  978. fn crash_child() {
  979. let (Ok(root), Ok(op)) = (std::env::var("VICTORY_SAVE_CHILD"), std::env::var("VICTORY_SAVE_OP")) else {
  980. return;
  981. };
  982. let root = PathBuf::from(root);
  983. let hr = if op == "update" {
  984. update(&root, "two", &[("a", Some("new a")), ("b", None), ("c", Some("new c"))])
  985. } else {
  986. delete(&root, "Slot")
  987. };
  988. assert_eq!(hr, S_OK);
  989. println!("FINISHED");
  990. }
  991. /// Kills a process in the middle of an update (and of a deletion) at
  992. /// every step: what is left is the whole old container or the whole
  993. /// new one.
  994. #[test]
  995. fn a_kill_at_any_step_leaves_old_or_new() {
  996. let new = Some(("two".into(), vec![("a".into(), "new a".into()), ("c".into(), "new c".into())]));
  997. for (op, after) in [("update", new), ("delete", None)] {
  998. let mut seen = (0, 0);
  999. for stop in 1.. {
  1000. let dir = tempfile::tempdir().unwrap();
  1001. let root = dir.path();
  1002. assert_eq!(update(root, "one", &[("a", Some("old a")), ("b", Some("old b"))]), S_OK);
  1003. let mut child = std::process::Command::new(std::env::current_exe().unwrap())
  1004. .args(["--exact", "modules::xgamesave::tests::crash_child", "--nocapture"])
  1005. .args(["--test-threads=1"])
  1006. .env("VICTORY_SAVE_CHILD", root)
  1007. .env("VICTORY_SAVE_OP", op)
  1008. .env("VICTORY_SAVE_STOP", stop.to_string())
  1009. .stdout(std::process::Stdio::piped())
  1010. .spawn()
  1011. .unwrap();
  1012. let out = std::io::BufReader::new(child.stdout.take().unwrap());
  1013. let mut finished = false;
  1014. for line in out.lines() {
  1015. let line = line.unwrap();
  1016. if line.contains("STOPPED") {
  1017. break;
  1018. }
  1019. finished |= line.contains("FINISHED");
  1020. }
  1021. let _ = child.kill();
  1022. child.wait().unwrap();
  1023. let left = state(root);
  1024. if left == old_state() {
  1025. seen.0 += 1;
  1026. } else {
  1027. assert_eq!(left, after, "{op}, killed at step {stop}");
  1028. seen.1 += 1;
  1029. }
  1030. if finished {
  1031. break;
  1032. }
  1033. }
  1034. assert!(seen.0 > 0 && seen.1 > 1, "{op}: {seen:?}");
  1035. }
  1036. }
  1037. /// A kept blob that cannot be hard-linked (NTFS allows 1024 links to a
  1038. /// file) is copied into the new version with its exact bytes.
  1039. #[cfg(windows)]
  1040. #[test]
  1041. fn a_kept_blob_past_the_link_limit_is_copied() {
  1042. let dir = tempfile::tempdir().unwrap();
  1043. let links = tempfile::tempdir().unwrap();
  1044. let root = dir.path();
  1045. assert_eq!(
  1046. update(root, "one", &[("a", Some("old a")), ("b", Some("old b"))]),
  1047. S_OK
  1048. );
  1049. const NTFS: &str = "the temp folder must be on NTFS, which allows 1024 links to a file";
  1050. let old_b = container_dir(root, "Slot").join("v1").join("1");
  1051. for i in 0..1023 {
  1052. std::fs::hard_link(&old_b, links.path().join(i.to_string())).expect(NTFS);
  1053. }
  1054. let full = std::fs::hard_link(&old_b, links.path().join("full")).expect_err(NTFS);
  1055. assert_eq!(full.kind(), std::io::ErrorKind::TooManyLinks, "{NTFS}");
  1056. assert_eq!(update(root, "two", &[("a", Some("new a"))]), S_OK);
  1057. let new = (
  1058. "two".into(),
  1059. vec![("a".into(), "new a".into()), ("b".into(), "old b".into())],
  1060. );
  1061. assert_eq!(state(root), Some(new));
  1062. assert!(!old_b.exists());
  1063. assert_eq!(std::fs::read(links.path().join("0")).unwrap(), b"old b");
  1064. }
  1065. #[test]
  1066. fn names_are_exact() {
  1067. for name in ["Save_1", "slot/2", "a.b c%", "\u{e9}t\u{e9}"] {
  1068. let file = file_name(name);
  1069. assert!(!file.contains(['.', '/', ' ']), "{file}");
  1070. assert_eq!(decode(&file).as_deref(), Some(name));
  1071. }
  1072. assert_eq!(decode("x.new"), None);
  1073. for good in ["Profile/Slot_1", "a/b/Save-2.sav", "x", &"a".repeat(256)] {
  1074. assert!(valid_container(good), "{good}");
  1075. }
  1076. for bad in ["a b", "", "a/", "a.", "a..b", "a.b/c", "a-b/c", &"a".repeat(257)] {
  1077. assert!(!valid_container(bad), "{bad}");
  1078. }
  1079. // Containers and blobs differing only in case, reserved device
  1080. // names, characters the host forbids, long names: all distinct.
  1081. let dir = tempfile::tempdir().unwrap();
  1082. let p = Provider { root: dir.path().into() };
  1083. let long = "n".repeat(300);
  1084. let blobs = ["A", "a", "CON", "nul.txt", "x/y:z*?\"<>|", long.as_str(), "end. "];
  1085. for container in ["Save", "save", "SAVE/CON.x"] {
  1086. let c = p.container(container);
  1087. let u = Update {
  1088. name: c.name.clone(),
  1089. dir: c.dir.clone(),
  1090. display: None,
  1091. changes: blobs
  1092. .iter()
  1093. .map(|b| (b.to_string(), Some(format!("{container}:{b}").into_bytes())))
  1094. .collect(),
  1095. };
  1096. assert_eq!(u.submit(), S_OK, "{container}");
  1097. }
  1098. let _saves = saves_lock();
  1099. let names: Vec<String> = containers(dir.path()).into_iter().map(|c| c.0).collect();
  1100. drop(_saves);
  1101. assert_eq!(names, ["SAVE/CON.x", "Save", "save"]);
  1102. for container in ["Save", "save", "SAVE/CON.x"] {
  1103. let read = read(&p.container(container), None).unwrap();
  1104. let mut expected: Vec<_> = blobs
  1105. .iter()
  1106. .map(|b| (b.to_string(), format!("{container}:{b}").into_bytes()))
  1107. .collect();
  1108. expected.sort();
  1109. assert_eq!(read, expected, "{container}");
  1110. }
  1111. }
  1112. #[test]
  1113. fn the_old_layout_moves_over() {
  1114. let saves = tempfile::tempdir().unwrap();
  1115. let root = saves.path().join(format!("{:016X}", xuser::XUID)).join("scid");
  1116. let old = root.join("Player");
  1117. std::fs::create_dir_all(&old).unwrap();
  1118. std::fs::write(old.join("Save%20Game%20Data"), b"data").unwrap();
  1119. std::fs::write(old.join("Save%20Game%20Header"), b"header").unwrap();
  1120. std::fs::write(old.join("Save%20Game%20Data.new"), b"half").unwrap();
  1121. std::fs::write(old.join(".display"), b"Chapter 1").unwrap();
  1122. let p = Provider::open(saves.path(), Some("scid")).unwrap();
  1123. assert!(!old.exists());
  1124. let c = p.container("Player");
  1125. let blobs = read(&c, None).unwrap();
  1126. assert_eq!(
  1127. blobs,
  1128. [
  1129. ("Save Game Data".into(), b"data".to_vec()),
  1130. ("Save Game Header".into(), b"header".to_vec())
  1131. ]
  1132. );
  1133. let v = current_named(&c.dir, "Player").unwrap().unwrap();
  1134. assert_eq!((v.dir.file_name(), v.display.as_str()), (Some("v1".as_ref()), "Chapter 1"));
  1135. }
  1136. /// An empty configuration id names none. As a folder name it would be
  1137. /// the folder every configuration lives in, whose folders then look
  1138. /// like containers of the old layout and are converted away.
  1139. #[test]
  1140. fn an_empty_configuration_id_is_the_default_one() {
  1141. let saves = tempfile::tempdir().unwrap();
  1142. let scid = Provider::open(saves.path(), Some("scid")).unwrap();
  1143. assert_eq!(update(&scid.root, "one", &[("a", Some("kept"))]), S_OK);
  1144. let kept = Some(("one".into(), vec![("a".into(), "kept".into())]));
  1145. assert_eq!(state(&scid.root), kept);
  1146. let empty = Provider::open(saves.path(), Some("")).unwrap();
  1147. assert!(scid.root.is_dir(), "another configuration's saves are gone");
  1148. assert_eq!(state(&scid.root), kept);
  1149. let default = Provider::open(saves.path(), None).unwrap();
  1150. assert_eq!(empty.root, default.root);
  1151. // Named configurations stay apart, from it and from each other.
  1152. assert_ne!(empty.root, scid.root);
  1153. assert_eq!(state(&empty.root), None);
  1154. let other = Provider::open(saves.path(), Some("other")).unwrap();
  1155. assert_eq!(state(&other.root), None);
  1156. assert_eq!(state(&scid.root), kept);
  1157. }
  1158. #[test]
  1159. fn saves_persist_across_providers() {
  1160. let this: This = &OBJECT;
  1161. let saves = tempfile::tempdir().unwrap();
  1162. let provider = give(Provider::open(saves.path(), Some("scid")).unwrap());
  1163. // Write two blobs through an update.
  1164. let mut container = std::ptr::null_mut();
  1165. type Create = extern "system" fn(
  1166. This,
  1167. *const Provider,
  1168. *const c_char,
  1169. *mut *mut Container,
  1170. ) -> HRESULT;
  1171. let create = method::<Create>(&OBJECT, 0x80);
  1172. assert_eq!(
  1173. create(this, provider, c"bad name".as_ptr(), &mut container),
  1174. INVALID_CONTAINER_NAME
  1175. );
  1176. assert_eq!(
  1177. create(this, provider, c"Slot_1".as_ptr(), &mut container),
  1178. S_OK
  1179. );
  1180. let mut update = std::ptr::null_mut();
  1181. type Update_ =
  1182. extern "system" fn(This, *const Container, *const c_char, *mut *mut Update) -> HRESULT;
  1183. assert_eq!(
  1184. method::<Update_>(&OBJECT, 0xb8)(this, container, c"Chapter 1".as_ptr(), &mut update),
  1185. S_OK
  1186. );
  1187. type Write =
  1188. extern "system" fn(This, *mut Update, *const c_char, *const u8, usize) -> HRESULT;
  1189. let write = method::<Write>(&OBJECT, 0xc8);
  1190. assert_eq!(
  1191. write(this, update, c"world".as_ptr(), b"hello".as_ptr(), 5),
  1192. S_OK
  1193. );
  1194. assert_eq!(
  1195. write(this, update, c"player.dat".as_ptr(), b"xy".as_ptr(), 2),
  1196. S_OK
  1197. );
  1198. assert_eq!(
  1199. write(this, update, c"gone".as_ptr(), b"z".as_ptr(), 1),
  1200. S_OK
  1201. );
  1202. type Delete = extern "system" fn(This, *mut Update, *const c_char) -> HRESULT;
  1203. assert_eq!(method::<Delete>(&OBJECT, 0xd0)(this, update, c"gone".as_ptr()), S_OK);
  1204. type Submit = extern "system" fn(This, *const Update, *mut AsyncBlock) -> HRESULT;
  1205. let mut b = block();
  1206. assert_eq!(method::<Submit>(&OBJECT, 0xe0)(this, update, &mut b), S_OK);
  1207. assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK);
  1208. close_update(this, update);
  1209. close_container(this, container);
  1210. close_provider(this, provider);
  1211. // A new provider sees the container and reads both blobs back.
  1212. let provider = give(Provider::open(saves.path(), Some("scid")).unwrap());
  1213. extern "system" fn seen(info: *const ContainerInfo, context: *mut c_void) -> bool {
  1214. // SAFETY: valid during the callback; the context is the test's vector.
  1215. let (info, out) = unsafe {
  1216. (
  1217. &*info,
  1218. &mut *context.cast::<Vec<(String, String, u32, u64)>>(),
  1219. )
  1220. };
  1221. out.push((
  1222. text(info.name).unwrap(),
  1223. text(info.display_name).unwrap(),
  1224. info.blob_count,
  1225. info.total_size,
  1226. ));
  1227. true
  1228. }
  1229. let mut found: Vec<(String, String, u32, u64)> = Vec::new();
  1230. let context = (&raw mut found).cast();
  1231. assert_eq!(
  1232. enumerate_containers(this, provider, context, Some(seen)),
  1233. S_OK
  1234. );
  1235. assert_eq!(found, [("Slot_1".into(), "Chapter 1".into(), 2, 7)]);
  1236. let mut container = std::ptr::null_mut();
  1237. assert_eq!(
  1238. create_container(this, provider, c"Slot_1".as_ptr(), &mut container),
  1239. S_OK
  1240. );
  1241. let mut b = block();
  1242. let wanted = [c"world".as_ptr(), c"player.dat".as_ptr()];
  1243. assert_eq!(
  1244. read_async(this, container, wanted.as_ptr(), 2, &mut b),
  1245. S_OK
  1246. );
  1247. assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK);
  1248. let mut size = 0;
  1249. assert_eq!(xasync::XAsyncGetResultSize(&mut b, &mut size), S_OK);
  1250. assert_eq!(
  1251. size,
  1252. 2 * BLOB + "world\0hello".len() + "player.dat\0xy".len()
  1253. );
  1254. let mut buffer = vec![0u64; size.div_ceil(8)];
  1255. let mut count = 0;
  1256. assert_eq!(
  1257. read_result(this, &mut b, 8, buffer.as_mut_ptr().cast(), &mut count),
  1258. BUFFER_TOO_SMALL
  1259. );
  1260. assert_eq!(
  1261. read_result(this, &mut b, size, buffer.as_mut_ptr().cast(), &mut count),
  1262. S_OK
  1263. );
  1264. assert_eq!(count, 2);
  1265. let blob = |i: usize| {
  1266. // SAFETY: the layout the call wrote.
  1267. unsafe {
  1268. let entry = buffer.as_ptr().cast::<u8>().add(i * BLOB);
  1269. let name = text(entry.cast::<*const c_char>().read_unaligned()).unwrap();
  1270. let len = entry.add(8).cast::<u32>().read_unaligned() as usize;
  1271. let data = std::slice::from_raw_parts(
  1272. entry.add(16).cast::<*const u8>().read_unaligned(),
  1273. len,
  1274. );
  1275. (name, data.to_vec())
  1276. }
  1277. };
  1278. assert_eq!(blob(0), ("world".into(), b"hello".to_vec()));
  1279. assert_eq!(blob(1), ("player.dat".into(), b"xy".to_vec()));
  1280. let missing = [c"nothing".as_ptr()];
  1281. let mut one = 1;
  1282. let mut small = [0u8; 8];
  1283. let read_now = method::<
  1284. extern "system" fn(
  1285. This,
  1286. *const Container,
  1287. *const *const c_char,
  1288. *mut u32,
  1289. usize,
  1290. *mut u8,
  1291. ) -> HRESULT,
  1292. >(&OBJECT, 0xa0);
  1293. assert_eq!(
  1294. read_now(
  1295. this,
  1296. container,
  1297. missing.as_ptr(),
  1298. &mut one,
  1299. 8,
  1300. small.as_mut_ptr()
  1301. ),
  1302. BLOB_NOT_FOUND
  1303. );
  1304. assert_eq!(
  1305. read_now(
  1306. this,
  1307. container,
  1308. wanted.as_ptr(),
  1309. &mut 2,
  1310. 8,
  1311. small.as_mut_ptr()
  1312. ),
  1313. BUFFER_TOO_SMALL
  1314. );
  1315. // Quota counts the blobs; deleting the container frees it.
  1316. let mut b = block();
  1317. assert_eq!(quota_async(this, provider, &mut b), S_OK);
  1318. let mut left = 0i64;
  1319. assert_eq!(quota_result(this, &mut b, &mut left), S_OK);
  1320. assert!(left as u64 <= QUOTA - 7);
  1321. let mut b = block();
  1322. assert_eq!(
  1323. delete_async(this, provider, c"Slot_1".as_ptr(), &mut b),
  1324. S_OK
  1325. );
  1326. assert_eq!(delete_result(this, &mut b), S_OK);
  1327. found.clear();
  1328. let context = (&raw mut found).cast();
  1329. assert_eq!(
  1330. enumerate_containers(this, provider, context, Some(seen)),
  1331. S_OK
  1332. );
  1333. assert!(found.is_empty());
  1334. close_container(this, container);
  1335. close_provider(this, provider);
  1336. }
  1337. /// Only `v<N>` as `commit` writes it is a version: `v01` and the like
  1338. /// are neither read, counted nor removed (#870).
  1339. #[test]
  1340. fn a_noncanonical_folder_does_not_remove_a_committed_save() {
  1341. let dir = tempfile::tempdir().unwrap();
  1342. let root = dir.path();
  1343. assert_eq!(update(root, "one", &[("a", Some("old a")), ("b", Some("old b"))]), S_OK);
  1344. let slot = container_dir(root, "Slot");
  1345. for stray in ["v01", "v001", "v+1", "v0", "v02"] {
  1346. std::fs::create_dir(slot.join(stray)).unwrap();
  1347. }
  1348. assert_eq!(state(root), old_state());
  1349. assert!(slot.join("v1").is_dir());
  1350. for stray in ["v01", "v001", "v+1", "v0", "v02"] {
  1351. assert!(slot.join(stray).exists(), "{stray} was removed");
  1352. }
  1353. }
  1354. /// A newer version folder that does not read (an empty folder, a file,
  1355. /// a broken manifest) neither hides the committed save, nor removes it,
  1356. /// nor blocks the next update, which goes above it.
  1357. #[test]
  1358. fn an_unreadable_newer_version_does_not_cost_the_save() {
  1359. type Make = fn(&Path);
  1360. let strays: [(&str, Make); 3] = [
  1361. ("empty folder", |p| std::fs::create_dir(p).unwrap()),
  1362. ("file", |p| std::fs::write(p, b"not a version").unwrap()),
  1363. ("broken manifest", |p| {
  1364. std::fs::create_dir(p).unwrap();
  1365. std::fs::write(p.join(MANIFEST), [9, 0, 0, 0, b'x']).unwrap();
  1366. }),
  1367. ];
  1368. for (what, make) in strays {
  1369. let dir = tempfile::tempdir().unwrap();
  1370. let root = dir.path();
  1371. assert_eq!(update(root, "one", &[("a", Some("old a")), ("b", Some("old b"))]), S_OK);
  1372. let slot = container_dir(root, "Slot");
  1373. make(&slot.join("v2"));
  1374. assert_eq!(state(root), old_state(), "{what}: read");
  1375. assert!(slot.join("v1").is_dir(), "{what}: v1 was removed");
  1376. assert_eq!(update(root, "two", &[("a", Some("new a"))]), S_OK, "{what}: update");
  1377. let blobs = vec![("a".into(), "new a".into()), ("b".into(), "old b".into())];
  1378. let after = Some(("two".into(), blobs));
  1379. assert_eq!(state(root), after, "{what}: after the update");
  1380. assert!(slot.join("v3").is_dir(), "{what}: the update did not go above v2");
  1381. // Read again: the new version stays the container.
  1382. assert_eq!(state(root), after, "{what}: second read");
  1383. }
  1384. }
  1385. /// With no readable version at all, reads and updates fail and nothing
  1386. /// is removed.
  1387. #[test]
  1388. fn no_readable_version_is_refused_and_kept() {
  1389. let dir = tempfile::tempdir().unwrap();
  1390. let root = dir.path();
  1391. assert_eq!(update(root, "one", &[("a", Some("old a"))]), S_OK);
  1392. let slot = container_dir(root, "Slot");
  1393. std::fs::write(slot.join("v1").join(MANIFEST), [1, 2, 3]).unwrap();
  1394. let c = Provider { root: root.into() }.container("Slot");
  1395. assert_eq!(read(&c, None).err(), Some(NO_ACCESS));
  1396. assert_eq!(update(root, "two", &[("a", Some("new a"))]), NO_ACCESS);
  1397. assert!(slot.join("v1").join("0").is_file());
  1398. assert!(!slot.join("v2").exists());
  1399. }
  1400. }