Files
EonaCat.XSBox/crates/engine/src/hle/modules/xgamesave.rs
T
EonaCat 1b0d534e6c
Rust validation / Formatting (push) Failing after 27s
EonaCat/ci-workflows: SonarQube / sonar (push) Successful in 47s
Rust validation / Windows x64 build and tests (push) Canceled after 0s
Initial
2026-12-04 21:03:25 +01:00

1036 lines
30 KiB
Rust

#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::ffi::{CString, c_char, c_void};
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use super::xasync::{self, AsyncBlock, E_INVALIDARG};
use super::xgameruntime::{
Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, with_spare,
};
use super::{storage, xuser};
use crate::hle::runtime;
pub const PROVIDER: Guid = Guid::new(
0x704c_3f58,
0xe629,
0x4cc2,
[0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6f, 0xe2],
);
pub const IID_2026: Guid = Guid::new(
0x1bff_f3af,
0xf14a,
0x40a3,
[0x8e, 0x35, 0x9a, 0xda, 0x90, 0x65, 0x93, 0xf9],
);
pub static OBJECT: Object = Object::new("game save", &VTABLE);
pub const INTERFACES: &[Interface] =
&[(PROVIDER, PROVIDER, &OBJECT), (PROVIDER, IID_2026, &OBJECT)];
pub const INVALID_CONTAINER_NAME: HRESULT = 0x8083_0001_u32 as i32;
pub const NO_ACCESS: HRESULT = 0x8083_0002_u32 as i32;
pub const OUT_OF_LOCAL_STORAGE: HRESULT = 0x8083_0003_u32 as i32;
pub const UPDATE_TOO_BIG: HRESULT = 0x8083_0005_u32 as i32;
pub const QUOTA_EXCEEDED: HRESULT = 0x8083_0006_u32 as i32;
pub const BUFFER_TOO_SMALL: HRESULT = 0x8083_0007_u32 as i32;
pub const BLOB_NOT_FOUND: HRESULT = 0x8083_0008_u32 as i32;
const QUOTA: u64 = 256 << 20;
const MAX_UPDATE: usize = 16 << 20;
const MANIFEST: &str = "manifest";
const READABLE: usize = 100;
static SAVES: Mutex<()> = Mutex::new(());
fn saves_lock() -> std::sync::MutexGuard<'static, ()> {
SAVES.lock().unwrap_or_else(|e| e.into_inner())
}
fn file_name(name: &str) -> String {
name.bytes()
.map(|b| match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' => (b as char).to_string(),
_ => format!("%{b:02X}"),
})
.collect()
}
fn decode(file: &str) -> Option<String> {
if file.contains('.') {
return None;
}
let mut out = Vec::new();
let mut bytes = file.bytes();
while let Some(b) = bytes.next() {
if b == b'%' {
let hex = [bytes.next()?, bytes.next()?];
out.push(u8::from_str_radix(std::str::from_utf8(&hex).ok()?, 16).ok()?);
} else {
out.push(b);
}
}
String::from_utf8(out).ok()
}
fn container_dir(root: &Path, name: &str) -> PathBuf {
let hash = name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| {
(h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3)
});
let mut readable = file_name(name);
readable.truncate(READABLE);
root.join(format!("{readable}~{hash:016x}"))
}
fn valid_container(name: &str) -> bool {
let (path, file) = name.rsplit_once('/').unwrap_or(("", name));
name.len() <= 256
&& path
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'/')
&& !file.is_empty()
&& !file.ends_with('.')
&& !file.contains("..")
&& file
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-'))
}
struct Version {
dir: PathBuf,
highest: u64,
name: String,
display: String,
blobs: Vec<String>,
}
impl Version {
fn blob(&self, i: usize) -> PathBuf {
self.dir.join(i.to_string())
}
fn sizes(&self) -> Vec<(String, u64)> {
let size = |i| std::fs::metadata(self.blob(i)).map_or(0, |m| m.len());
let blobs = self.blobs.iter().enumerate();
blobs.map(|(i, n)| (n.clone(), size(i))).collect()
}
}
fn manifest(name: &str, display: &str, blobs: &[&str]) -> Vec<u8> {
let mut out = Vec::new();
for s in [name, display].into_iter().chain(blobs.iter().copied()) {
out.extend_from_slice(&(s.len() as u32).to_le_bytes());
out.extend_from_slice(s.as_bytes());
}
out
}
fn parse_manifest(bytes: &[u8]) -> Option<Vec<String>> {
let mut out = Vec::new();
let mut rest = bytes;
while !rest.is_empty() {
let (len, tail) = rest.split_first_chunk::<4>()?;
let len = u32::from_le_bytes(*len) as usize;
out.push(String::from_utf8(tail.get(..len)?.to_vec()).ok()?);
rest = &tail[len..];
}
(out.len() >= 2).then_some(out)
}
fn version_number(file: &str) -> Option<u64> {
let n = file.strip_prefix('v')?.parse::<u64>().ok()?;
(n > 0 && format!("v{n}") == file).then_some(n)
}
fn load(dir: &Path) -> std::io::Result<Option<(String, String, Vec<String>)>> {
let bytes = match std::fs::read(dir.join(MANIFEST)) {
Ok(bytes) => bytes,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e),
};
let Some(mut names) = parse_manifest(&bytes) else {
return Ok(None);
};
let blobs = names.split_off(2);
let [name, display] = <[String; 2]>::try_from(names).expect("two names, checked by the parser");
Ok(Some((name, display, blobs)))
}
fn current(dir: &Path) -> std::io::Result<Option<Version>> {
let mut committed = Vec::new();
let mut highest = 0;
for entry in std::fs::read_dir(dir)?.flatten() {
let file = entry.file_name();
let file = file.to_string_lossy();
if file.ends_with(".new") {
if let Err(e) = std::fs::remove_dir_all(entry.path()) {
tracing::debug!(dir = %entry.path().display(), %e, "an unfinished save version stays for now");
}
} else if let Some(n) = version_number(&file) {
highest = highest.max(n);
if entry.file_type().is_ok_and(|t| t.is_dir()) {
committed.push(n);
}
}
}
committed.sort_unstable_by(|a, b| b.cmp(a));
if committed.is_empty() {
return Ok(None);
}
for (at, &number) in committed.iter().enumerate() {
let version = dir.join(format!("v{number}"));
let Some((name, display, blobs)) = load(&version)? else {
continue;
};
for old in &committed[at + 1..] {
let path = dir.join(format!("v{old}"));
if let Err(e) = std::fs::remove_dir_all(&path) {
tracing::info!(dir = %path.display(), %e, "an older save version stays for now; it goes at a later save");
}
}
return Ok(Some(Version {
dir: version,
highest,
name,
display,
blobs,
}));
}
Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"no save version has a readable manifest",
))
}
fn current_named(dir: &Path, name: &str) -> std::io::Result<Option<Version>> {
match current(dir) {
Ok(v) => Ok(v.filter(|v| v.name == name)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e),
}
}
fn step() {
}
enum Source<'a> {
Data(&'a [u8]),
Kept(PathBuf),
}
fn commit(
dir: &Path,
number: u64,
name: &str,
display: &str,
blobs: &[(&str, Source<'_>)],
) -> std::io::Result<()> {
let staged = dir.join(format!("v{number}.new"));
if staged.exists() {
std::fs::remove_dir_all(&staged)?;
}
std::fs::create_dir_all(&staged)?;
let write = |path: PathBuf, data: &[u8]| -> std::io::Result<()> {
let mut file = std::fs::File::create(path)?;
file.write_all(data)?;
file.sync_all()
};
for (i, (_, source)) in blobs.iter().enumerate() {
let path = staged.join(i.to_string());
match source {
Source::Data(data) => write(path, data)?,
Source::Kept(from) => {
std::fs::hard_link(from, &path).or_else(|_| write(path, &std::fs::read(from)?))?
}
}
step();
}
let names: Vec<&str> = blobs.iter().map(|(n, _)| *n).collect();
write(staged.join(MANIFEST), &manifest(name, display, &names))?;
step();
std::fs::rename(&staged, dir.join(format!("v{number}")))?;
step();
Ok(())
}
fn containers(root: &Path) -> Vec<(String, PathBuf)> {
let mut out = Vec::new();
for entry in std::fs::read_dir(root).into_iter().flatten().flatten() {
let path = entry.path();
let file = entry.file_name().to_string_lossy().into_owned();
if !path.is_dir() {
continue;
}
if file.ends_with(".gone") {
let _ = std::fs::remove_dir_all(&path);
} else if file.contains('~') {
if let Ok(Some(v)) = current(&path) {
out.push((v.name, path));
}
} else if let Some(name) = decode(&file)
&& let Some(dir) = migrate(root, &name, &path)
{
out.push((name, dir));
}
}
out.sort();
out
}
fn migrate(root: &Path, name: &str, old: &Path) -> Option<PathBuf> {
let dir = container_dir(root, name);
let done = current_named(&dir, name).ok()?.is_some();
if !done {
let display = std::fs::read_to_string(old.join(".display")).unwrap_or_default();
let mut blobs: Vec<(String, Vec<u8>)> = std::fs::read_dir(old)
.ok()?
.flatten()
.filter_map(|e| {
let blob = decode(e.file_name().to_str()?)?;
Some((blob, std::fs::read(e.path()).ok()?))
})
.collect();
blobs.sort();
let sources: Vec<_> = blobs
.iter()
.map(|(n, d)| (n.as_str(), Source::Data(d)))
.collect();
commit(&dir, 1, name, &display, &sources).ok()?;
}
std::fs::remove_dir_all(old).ok()?;
tracing::info!(container = name, "game save moved to the versioned layout");
Some(dir)
}
fn used_bytes(root: &Path) -> u64 {
containers(root)
.iter()
.filter_map(|(name, dir)| current_named(dir, name).ok().flatten())
.map(|v| v.sizes().iter().map(|(_, size)| size).sum::<u64>())
.sum()
}
struct Provider {
root: PathBuf,
}
struct Container {
name: String,
dir: PathBuf,
}
struct Update {
name: String,
dir: PathBuf,
display: Option<String>,
changes: Vec<(String, Option<Vec<u8>>)>,
}
fn get<'a, T>(handle: *const T) -> Option<&'a T> {
unsafe { handle.as_ref() }
}
fn give<T>(value: T) -> *mut T {
Box::into_raw(Box::new(value))
}
fn take<T>(handle: *mut T) {
if !handle.is_null() {
drop(unsafe { Box::from_raw(handle) });
}
}
impl Provider {
fn open(saves: &Path, config: Option<&str>) -> Result<Provider, HRESULT> {
let config = config.filter(|c| !c.is_empty()).unwrap_or("default");
let root = saves
.join(format!("{:016X}", xuser::XUID))
.join(file_name(config));
std::fs::create_dir_all(&root).map_err(|_| NO_ACCESS)?;
let _saves = saves_lock();
containers(&root);
Ok(Provider { root })
}
fn remaining(&self) -> u64 {
let _saves = saves_lock();
remaining(&self.root)
}
fn container(&self, name: &str) -> Container {
Container {
name: name.to_owned(),
dir: container_dir(&self.root, name),
}
}
}
fn remaining(root: &Path) -> u64 {
QUOTA
.saturating_sub(used_bytes(root))
.min(storage::disk_free(root))
}
fn no_room(written: u64, replaced: u64, used: u64, free: u64) -> Option<HRESULT> {
if written > QUOTA.saturating_sub(used) + replaced {
Some(QUOTA_EXCEEDED)
} else if written > free {
Some(OUT_OF_LOCAL_STORAGE)
} else {
None
}
}
fn io_error(dir: &Path, e: &std::io::Error) -> HRESULT {
tracing::warn!(dir = %dir.display(), %e, "game save");
if e.kind() == std::io::ErrorKind::StorageFull {
OUT_OF_LOCAL_STORAGE
} else {
NO_ACCESS
}
}
impl Update {
fn submit(&self) -> HRESULT {
let _saves = saves_lock();
let current = match current(&self.dir) {
Ok(v) => v,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
Err(e) => return io_error(&self.dir, &e),
};
if current.as_ref().is_some_and(|v| v.name != self.name) {
return NO_ACCESS;
}
let mut blobs: Vec<(&str, Source<'_>)> = current
.iter()
.flat_map(|v| {
let kept = v.blobs.iter().enumerate();
kept.map(|(i, n)| (n.as_str(), Source::Kept(v.blob(i))))
})
.collect();
for (name, data) in &self.changes {
blobs.retain(|(n, _)| n != name);
if let Some(data) = data {
blobs.push((name, Source::Data(data)));
}
}
blobs.sort_by(|a, b| a.0.cmp(b.0));
let written: usize = blobs
.iter()
.map(|(_, s)| match s {
Source::Data(d) => d.len(),
Source::Kept(_) => 0,
})
.sum();
if written > MAX_UPDATE {
return UPDATE_TOO_BIG;
}
let replaced: u64 = current.as_ref().map_or(0, |v| {
let sizes = v.sizes();
let changed = sizes.iter().filter(|(n, _)| self.changes.iter().any(|(c, _)| c == n));
changed.map(|(_, size)| size).sum()
});
let root = self.dir.parent().unwrap_or(&self.dir);
let free = storage::disk_free(root);
if let Some(hr) = no_room(written as u64, replaced, used_bytes(root), free) {
return hr;
}
let display = self.display.as_deref();
let display = display.or(current.as_ref().map(|v| v.display.as_str()));
let number = current.as_ref().map_or(1, |v| v.highest + 1);
if let Err(e) = commit(&self.dir, number, &self.name, display.unwrap_or(""), &blobs) {
return io_error(&self.dir, &e);
}
if let Some(old) = &current {
let _ = std::fs::remove_dir_all(&old.dir);
step();
}
S_OK
}
}
fn delete(root: &Path, name: &str) -> HRESULT {
let _saves = saves_lock();
let dir = container_dir(root, name);
match current_named(&dir, name) {
Ok(Some(_)) => {}
Ok(None) => return S_OK,
Err(e) => return io_error(&dir, &e),
}
let gone = dir.with_extension("gone");
let _ = std::fs::remove_dir_all(&gone);
step();
if let Err(e) = std::fs::rename(&dir, &gone) {
return io_error(&dir, &e);
}
step();
let _ = std::fs::remove_dir_all(&gone);
S_OK
}
fn read(c: &Container, names: Option<Vec<String>>) -> Result<Vec<(String, Vec<u8>)>, HRESULT> {
let _saves = saves_lock();
let version = current_named(&c.dir, &c.name)
.map_err(|e| io_error(&c.dir, &e))?
.ok_or(BLOB_NOT_FOUND)?;
let names = names.unwrap_or_else(|| version.blobs.clone());
names
.into_iter()
.map(|name| {
let i = version.blobs.iter().position(|b| *b == name).ok_or(BLOB_NOT_FOUND)?;
let data = std::fs::read(version.blob(i)).map_err(|e| io_error(&c.dir, &e))?;
Ok((name, data))
})
.collect()
}
const BLOB: usize = 24;
fn layout(blobs: &[(String, Vec<u8>)], base: usize) -> Vec<u8> {
let mut out = vec![0u8; blobs.len() * BLOB];
for (i, (name, data)) in blobs.iter().enumerate() {
let name_at = base + out.len();
out.extend_from_slice(name.as_bytes());
out.push(0);
let data_at = base + out.len();
out.extend_from_slice(data);
let entry = &mut out[i * BLOB..(i + 1) * BLOB];
entry[..8].copy_from_slice(&name_at.to_le_bytes());
entry[8..12].copy_from_slice(&(data.len() as u32).to_le_bytes());
entry[16..].copy_from_slice(&data_at.to_le_bytes());
}
out
}
fn names(names: *const *const c_char, count: u32) -> Option<Vec<String>> {
if names.is_null() {
return None;
}
let names = unsafe { std::slice::from_raw_parts(names, count as usize) };
Some(names.iter().map(|&n| text(n).unwrap_or_default()).collect())
}
type This = *const Object;
type ContainerCallback = extern "system" fn(*const ContainerInfo, *mut c_void) -> bool;
type BlobCallback = extern "system" fn(*const BlobInfo, *mut c_void) -> bool;
#[repr(C)]
pub struct ContainerInfo {
pub name: *const c_char,
pub display_name: *const c_char,
pub blob_count: u32,
pub total_size: u64,
pub last_modified: i64,
pub needs_sync: bool,
}
#[repr(C)]
pub struct BlobInfo {
pub name: *const c_char,
pub size: u32,
}
fn report(root: &Path, keep: impl Fn(&str) -> bool, context: *mut c_void, callback: ContainerCallback) {
let infos: Vec<(CString, CString, u32, u64, i64)> = {
let _saves = saves_lock();
containers(root)
.into_iter()
.filter(|(name, _)| keep(name))
.filter_map(|(name, dir)| current_named(&dir, &name).ok().flatten())
.map(|v| {
let modified = std::fs::metadata(v.dir.join(MANIFEST))
.and_then(|m| m.modified())
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map_or(0, |d| d.as_secs() as i64);
let size = v.sizes().iter().map(|(_, s)| s).sum();
let count = v.blobs.len() as u32;
(cstring(&v.name), cstring(&v.display), count, size, modified)
})
.collect()
};
for (name, display, blob_count, total_size, last_modified) in &infos {
let info = ContainerInfo {
name: name.as_ptr(),
display_name: display.as_ptr(),
blob_count: *blob_count,
total_size: *total_size,
last_modified: *last_modified,
needs_sync: false,
};
if !callback(&info, context) {
break;
}
}
}
fn cstring(s: &str) -> CString {
CString::new(s.replace('\0', "")).unwrap_or_default()
}
static INIT: u8 = 0;
static QUOTA_CALL: u8 = 0;
static DELETE: u8 = 0;
static READ: u8 = 0;
static SUBMIT: u8 = 0;
extern "system" fn initialize_async(
_: This,
_user: *const c_void,
config: *const c_char,
_sync_on_demand: bool,
block: *mut AsyncBlock,
) -> HRESULT {
let saves = runtime::title().saves();
let result = if saves.parent().is_none_or(|p| p.as_os_str().is_empty()) {
Err(NO_ACCESS)
} else {
Provider::open(&saves, text(config).as_deref()).map(|p| xasync::bytes(give(p)))
};
xasync::finished_with(block, (&raw const INIT).cast(), result)
}
extern "system" fn initialize_result(
_: This,
block: *mut AsyncBlock,
out: *mut *mut Provider,
) -> HRESULT {
xasync::result(block, (&raw const INIT).cast(), out)
}
extern "system" fn close_provider(_: This, provider: *mut Provider) {
take(provider);
}
extern "system" fn quota_async(
_: This,
provider: *const Provider,
block: *mut AsyncBlock,
) -> HRESULT {
let result = get(provider)
.ok_or(E_INVALIDARG)
.map(|p| xasync::bytes(p.remaining() as i64));
xasync::finished_with(block, (&raw const QUOTA_CALL).cast(), result)
}
extern "system" fn quota_result(_: This, block: *mut AsyncBlock, out: *mut i64) -> HRESULT {
xasync::result(block, (&raw const QUOTA_CALL).cast(), out)
}
extern "system" fn delete_async(
_: This,
provider: *const Provider,
name: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
let hr = match (get(provider), text(name)) {
(Some(p), Some(name)) if valid_container(&name) => delete(&p.root, &name),
(Some(_), Some(_)) => INVALID_CONTAINER_NAME,
_ => E_INVALIDARG,
};
xasync::finished(block, (&raw const DELETE).cast(), hr)
}
extern "system" fn delete_result(_: This, block: *mut AsyncBlock) -> HRESULT {
let none = std::ptr::null_mut();
xasync::XAsyncGetResult(block, (&raw const DELETE).cast(), 0, none, none.cast())
}
extern "system" fn container_info(
_: This,
provider: *const Provider,
name: *const c_char,
context: *mut c_void,
callback: Option<ContainerCallback>,
) -> HRESULT {
let (Some(p), Some(name), Some(callback)) = (get(provider), text(name), callback) else {
return E_INVALIDARG;
};
if !valid_container(&name) {
return INVALID_CONTAINER_NAME;
}
report(&p.root, |n| n == name, context, callback);
S_OK
}
extern "system" fn enumerate_containers(
_: This,
provider: *const Provider,
context: *mut c_void,
callback: Option<ContainerCallback>,
) -> HRESULT {
let (Some(p), Some(callback)) = (get(provider), callback) else {
return E_INVALIDARG;
};
report(&p.root, |_| true, context, callback);
S_OK
}
extern "system" fn create_container(
_: This,
provider: *const Provider,
name: *const c_char,
out: *mut *mut Container,
) -> HRESULT {
let (Some(p), Some(name)) = (get(provider), text(name)) else {
return E_INVALIDARG;
};
if !valid_container(&name) {
return INVALID_CONTAINER_NAME;
}
put(out, give(p.container(&name)))
}
extern "system" fn close_container(_: This, container: *mut Container) {
take(container);
}
extern "system" fn enumerate_blobs(
_: This,
container: *const Container,
prefix: *const c_char,
context: *mut c_void,
callback: Option<BlobCallback>,
) -> HRESULT {
let (Some(c), Some(callback)) = (get(container), callback) else {
return E_INVALIDARG;
};
let prefix = text(prefix).unwrap_or_default();
let blobs = {
let _saves = saves_lock();
let version = current_named(&c.dir, &c.name).ok().flatten();
version.map(|v| v.sizes()).unwrap_or_default()
};
for (name, size) in blobs.into_iter().filter(|(n, _)| n.starts_with(&prefix)) {
let name = cstring(&name);
let info = BlobInfo {
name: name.as_ptr(),
size: size as u32,
};
if !callback(&info, context) {
break;
}
}
S_OK
}
extern "system" fn read_blobs(
_: This,
container: *const Container,
blob_names: *const *const c_char,
count: *mut u32,
size: usize,
out: *mut u8,
) -> HRESULT {
let Some(c) = get(container) else {
return E_INVALIDARG;
};
let wanted = unsafe { count.as_ref() }.copied().unwrap_or(0);
let blobs = match read(c, names(blob_names, wanted)) {
Ok(blobs) => blobs,
Err(hr) => return hr,
};
let bytes = layout(&blobs, out as usize);
if out.is_null() || size < bytes.len() {
return BUFFER_TOO_SMALL;
}
unsafe { out.copy_from_nonoverlapping(bytes.as_ptr(), bytes.len()) };
put(count, blobs.len() as u32)
}
extern "system" fn read_async(
_: This,
container: *const Container,
blob_names: *const *const c_char,
count: u32,
block: *mut AsyncBlock,
) -> HRESULT {
let result = match get(container) {
Some(c) => read(c, names(blob_names, count)).map(|blobs| layout(&blobs, 0)),
None => Err(E_INVALIDARG),
};
xasync::finished_with(block, (&raw const READ).cast(), result)
}
extern "system" fn read_result(
_: This,
block: *mut AsyncBlock,
size: usize,
out: *mut u8,
count: *mut u32,
) -> HRESULT {
let mut used = 0;
let hr = xasync::XAsyncGetResult(block, (&raw const READ).cast(), size, out.cast(), &mut used);
if hr == xasync::E_NOT_SUFFICIENT_BUFFER {
return BUFFER_TOO_SMALL;
}
if hr < 0 {
return hr;
}
let blobs = if used == 0 {
0
} else {
unsafe { out.cast::<usize>().read_unaligned() / BLOB }
};
for i in 0..blobs {
for field in [0, 16] {
unsafe {
let p = out.add(i * BLOB + field).cast::<usize>();
p.write_unaligned(p.read_unaligned() + out as usize);
}
}
}
put(count, blobs as u32)
}
extern "system" fn create_update(
_: This,
container: *const Container,
display: *const c_char,
out: *mut *mut Update,
) -> HRESULT {
let Some(c) = get(container) else {
return E_INVALIDARG;
};
put(
out,
give(Update {
name: c.name.clone(),
dir: c.dir.clone(),
display: text(display),
changes: Vec::new(),
}),
)
}
extern "system" fn close_update(_: This, update: *mut Update) {
take(update);
}
extern "system" fn write_blob(
_: This,
update: *mut Update,
name: *const c_char,
data: *const u8,
size: usize,
) -> HRESULT {
let (Some(update), Some(name)) = (unsafe { update.as_mut() }, text(name)) else {
return E_INVALIDARG;
};
if name.is_empty() || (data.is_null() && size > 0) {
return E_INVALIDARG;
}
if size > MAX_UPDATE {
return UPDATE_TOO_BIG;
}
let data = if size == 0 {
Vec::new()
} else {
unsafe { std::slice::from_raw_parts(data, size) }.to_vec()
};
update.changes.push((name, Some(data)));
S_OK
}
extern "system" fn delete_blob(_: This, update: *mut Update, name: *const c_char) -> HRESULT {
match (unsafe { update.as_mut() }, text(name)) {
(Some(update), Some(name)) if !name.is_empty() => {
update.changes.push((name, None));
S_OK
}
_ => E_INVALIDARG,
}
}
extern "system" fn submit_async(_: This, update: *const Update, block: *mut AsyncBlock) -> HRESULT {
let hr = get(update).map_or(E_INVALIDARG, Update::submit);
xasync::finished(block, (&raw const SUBMIT).cast(), hr)
}
extern "system" fn submit_result(_: This, block: *mut AsyncBlock) -> HRESULT {
let none = std::ptr::null_mut();
xasync::XAsyncGetResult(block, (&raw const SUBMIT).cast(), 0, none, none.cast())
}
extern "system" fn initialize(
_: This,
_user: *const c_void,
config: *const c_char,
_sync_on_demand: bool,
out: *mut *mut Provider,
) -> HRESULT {
if out.is_null() {
return E_INVALIDARG;
}
unsafe { out.write(std::ptr::null_mut()) };
let saves = runtime::title().saves();
if saves.parent().is_none_or(|p| p.as_os_str().is_empty()) {
return NO_ACCESS;
}
match Provider::open(&saves, text(config).as_deref()) {
Ok(p) => put(out, give(p)),
Err(hr) => hr,
}
}
extern "system" fn quota(_: This, provider: *const Provider, out: *mut i64) -> HRESULT {
get(provider).map_or(E_INVALIDARG, |p| put(out, p.remaining() as i64))
}
extern "system" fn delete_container(_: This, provider: *const Provider, name: *const c_char) -> HRESULT {
match (get(provider), text(name)) {
(Some(p), Some(name)) if valid_container(&name) => delete(&p.root, &name),
(Some(_), Some(_)) => INVALID_CONTAINER_NAME,
_ => E_INVALIDARG,
}
}
extern "system" fn containers_by_name(
_: This,
provider: *const Provider,
prefix: *const c_char,
context: *mut c_void,
callback: Option<ContainerCallback>,
) -> HRESULT {
let (Some(p), Some(callback)) = (get(provider), callback) else {
return E_INVALIDARG;
};
let prefix = text(prefix).unwrap_or_default();
report(&p.root, |n| n.starts_with(&prefix), context, callback);
S_OK
}
extern "system" fn all_blobs(
this: This,
container: *const Container,
context: *mut c_void,
callback: Option<BlobCallback>,
) -> HRESULT {
enumerate_blobs(this, container, std::ptr::null(), context, callback)
}
extern "system" fn submit(_: This, update: *const Update) -> HRESULT {
get(update).map_or(E_INVALIDARG, Update::submit)
}
fn files_folder(config: Option<&str>) -> Option<PathBuf> {
let saves = runtime::title().saves();
if saves.parent().is_none_or(|p| p.as_os_str().is_empty()) {
return None;
}
Some(files_folder_in(&saves, config))
}
fn files_folder_in(saves: &Path, config: Option<&str>) -> PathBuf {
let config = config.filter(|c| !c.is_empty()).unwrap_or("default");
saves
.join("files")
.join(format!("{:016X}", xuser::XUID))
.join(file_name(config))
}
static FILES_FOLDER: u8 = 0;
extern "system" fn files_folder_async(
_: This,
_user: *const c_void,
config: *const c_char,
block: *mut AsyncBlock,
) -> HRESULT {
let folder = files_folder(text(config).as_deref()).ok_or(NO_ACCESS);
let result = folder.and_then(|dir| {
std::fs::create_dir_all(&dir).map_err(|_| NO_ACCESS)?;
#[cfg(windows)]
let path = super::files::mount(&dir).map(|letter| format!("{letter}:\\"));
#[cfg(not(windows))]
let path = Some(dir.display().to_string());
let mut bytes = path.ok_or(NO_ACCESS)?.into_bytes();
bytes.push(0);
Ok(bytes)
});
xasync::finished_with(block, (&raw const FILES_FOLDER).cast(), result)
}
extern "system" fn files_folder_result(
_: This,
block: *mut AsyncBlock,
size: usize,
out: *mut c_char,
) -> HRESULT {
let none = std::ptr::null_mut();
xasync::XAsyncGetResult(
block,
(&raw const FILES_FOLDER).cast(),
size,
out.cast(),
none,
)
}
extern "system" fn files_quota(
_: This,
_user: *const c_void,
config: *const c_char,
out: *mut i64,
) -> HRESULT {
let Some(dir) = files_folder(text(config).as_deref()) else {
return NO_ACCESS;
};
let used = storage::used_bytes(&dir);
let left = QUOTA.saturating_sub(used).min(storage::disk_free(&dir));
put(out, left as i64)
}
static VTABLE: Methods<41> = with_spare([
missing::<0> as *const (),
add_ref as *const (),
add_ref as *const (),
initialize as *const (),
initialize_async as *const (),
initialize_result as *const (),
close_provider as *const (),
quota as *const (),
quota_async as *const (),
quota_result as *const (),
delete_container as *const (),
delete_async as *const (),
delete_result as *const (),
container_info as *const (),
enumerate_containers as *const (),
containers_by_name as *const (),
create_container as *const (),
close_container as *const (),
all_blobs as *const (),
enumerate_blobs as *const (),
read_blobs as *const (),
read_async as *const (),
read_result as *const (),
create_update as *const (),
close_update as *const (),
write_blob as *const (),
delete_blob as *const (),
submit as *const (),
submit_async as *const (),
submit_result as *const (),
files_folder_async as *const (),
files_folder_result as *const (),
files_quota as *const (),
]);