capsule_library/import/camera/staging.rs
1//! Where received camera objects are staged on local disk.
2//!
3//! ```text
4//! <staging root>/
5//! objects/<storage:08x>/<parent:08x>[~<n>]/<camera file name> complete, verified objects
6//! identity/<storage:08x>/<parent:08x>[~<n>]/<file name>.id which object each one is
7//! partial/<storage:08x>-<handle:08x>-<key>.part objects still arriving
8//! partial/<storage:08x>-<handle:08x>-<key>.part.ckpt the prefix made durable
9//! ```
10//!
11//! Complete objects keep the camera's own file name under a directory per camera folder, so a
12//! RAW+JPEG pair (`DSC00001.ARW`, `DSC00001.JPG`) lands side by side and the scanner's stem
13//! grouping stacks it exactly as it would from a card reader. Two DCIM folders can each hold a
14//! `DSC00001.JPG`; the parent folder's handle keeps them apart.
15//!
16//! Every object has an [identity key](identity_key) over its parent, name, size and capture
17//! date. A complete object's key is recorded beside it, outside the scanned tree, so a later run
18//! takes a staged file as already received only for the same object. A reused staging root can
19//! meet a different object under the same path (a reformatted card restarts its file counter);
20//! that object goes to the next free *generation* of the folder directory (`<parent>~1`,
21//! `<parent>~2`, ...), and the earlier file is never overwritten.
22//!
23//! A partial file's name carries the identity key as well as its handle. PTP promises handles
24//! only within a session, so a resumed transfer continues a partial file only when every one of
25//! those still matches the object it is about to read — a handle the camera reassigned to another
26//! object starts a fresh file. Its checkpoint records the length and SHA-256 of the prefix last
27//! synced to disk; a resume continues only from a prefix that still hashes to it.
28
29use std::borrow::Cow;
30use std::path::{Path, PathBuf};
31
32use capsule_core::crypto::hash::hash_bytes;
33
34use super::CameraObject;
35
36/// The directory holding complete objects: the root the import pipeline scans.
37pub(crate) fn objects_dir(root: &Path) -> PathBuf {
38 root.join("objects")
39}
40
41/// The directory recording which object each complete file is. Never scanned.
42pub(crate) fn identity_dir(root: &Path) -> PathBuf {
43 root.join("identity")
44}
45
46/// The directory holding objects still arriving. Never scanned.
47pub(crate) fn partial_dir(root: &Path) -> PathBuf {
48 root.join("partial")
49}
50
51/// The identity of `object` across sessions: its parent folder, name, size and capture date,
52/// hashed. The handle is left out of it, because a camera may renumber handles between sessions.
53pub(crate) fn identity_key(object: &CameraObject) -> String {
54 let identity = format!(
55 "{}\u{0}{}\u{0}{:?}\u{0}{:?}",
56 object.parent, object.filename, object.size, object.captured_at
57 );
58 hash_bytes(identity.as_bytes()).to_hex()
59}
60
61/// The path of `object` in folder `generation`, relative to the objects and identity directories.
62fn relative_path(object: &CameraObject, generation: u32) -> PathBuf {
63 let name = safe_file_name(&object.filename)
64 .map_or_else(|| format!("object-{:08x}", object.handle), Cow::into_owned);
65 let folder = if generation == 0 {
66 format!("{:08x}", object.parent)
67 } else {
68 format!("{:08x}~{generation}", object.parent)
69 };
70 PathBuf::from(format!("{:08x}", object.storage))
71 .join(folder)
72 .join(name)
73}
74
75/// Where `object` lives once it is complete and verified, in folder `generation`: `0` unless an
76/// earlier, different object already holds that path.
77pub(crate) fn object_path(root: &Path, object: &CameraObject, generation: u32) -> PathBuf {
78 objects_dir(root).join(relative_path(object, generation))
79}
80
81/// Where the identity key of the object at the same [`object_path`] is recorded.
82pub(crate) fn identity_path(root: &Path, object: &CameraObject, generation: u32) -> PathBuf {
83 let mut path = identity_dir(root)
84 .join(relative_path(object, generation))
85 .into_os_string();
86 path.push(".id");
87 PathBuf::from(path)
88}
89
90/// Where `object`'s bytes accumulate while it is arriving.
91pub(crate) fn partial_path(root: &Path, object: &CameraObject) -> PathBuf {
92 let identity = identity_key(object);
93 let key = &identity[..16];
94 partial_dir(root).join(format!(
95 "{:08x}-{:08x}-{key}.part",
96 object.storage, object.handle
97 ))
98}
99
100/// Where the length and digest of `partial`'s durable prefix are recorded.
101pub(crate) fn checkpoint_path(partial: &Path) -> PathBuf {
102 let mut path = partial.as_os_str().to_owned();
103 path.push(".ckpt");
104 PathBuf::from(path)
105}
106
107/// Characters no Windows file name may hold, beyond separators and control characters.
108const WINDOWS_RESERVED_CHARS: [char; 7] = [':', '*', '?', '"', '<', '>', '|'];
109
110/// Device names Windows reserves, whatever extension follows them.
111const WINDOWS_DEVICE_NAMES: [&str; 4] = ["CON", "PRN", "AUX", "NUL"];
112
113/// The camera's file name made safe to use as one path component on every platform, or `None`
114/// where it cannot be.
115///
116/// A camera is an untrusted peer. A name that is empty, `.` or `..`, longer than 255 bytes, or
117/// holds a separator, NUL or another control character is refused, and the caller names the file
118/// after its handle instead. A name that is otherwise usable but invalid on Windows is repaired so
119/// it keeps its extension: each of `: * ? " < > |` becomes `_`, trailing dots and spaces (which
120/// Windows strips) become `_`, and a reserved device name (`CON`, `PRN`, `AUX`, `NUL`,
121/// `COM1`-`COM9`, `LPT1`-`LPT9`, with or without an extension) gains a leading `_`. A repaired
122/// name can equal another object's real name; the identity record keeps the two apart.
123#[must_use]
124pub fn safe_file_name(name: &str) -> Option<Cow<'_, str>> {
125 let trimmed = name.trim();
126 if trimmed.is_empty()
127 || trimmed == "."
128 || trimmed == ".."
129 || name.len() > 255
130 || name
131 .chars()
132 .any(|c| c == '/' || c == '\\' || c.is_control())
133 {
134 return None;
135 }
136 let kept = name.trim_end_matches(['.', ' ']);
137 let trailing = name.len() - kept.len();
138 let stem = kept.split('.').next().unwrap_or(kept).trim_end();
139 let device = is_windows_device_name(stem);
140 if trailing == 0 && !device && !kept.contains(WINDOWS_RESERVED_CHARS) {
141 return Some(Cow::Borrowed(name));
142 }
143 let mut repaired = String::with_capacity(name.len() + 1);
144 if device {
145 repaired.push('_');
146 }
147 repaired.extend(kept.chars().map(|c| {
148 if WINDOWS_RESERVED_CHARS.contains(&c) {
149 '_'
150 } else {
151 c
152 }
153 }));
154 repaired.extend(std::iter::repeat_n('_', trailing));
155 (repaired.len() <= 255).then_some(Cow::Owned(repaired))
156}
157
158/// Whether `stem` is a device name Windows reserves, compared case-insensitively.
159fn is_windows_device_name(stem: &str) -> bool {
160 let upper = stem.to_ascii_uppercase();
161 if WINDOWS_DEVICE_NAMES.contains(&upper.as_str()) {
162 return true;
163 }
164 let Some(digit) = upper
165 .strip_prefix("COM")
166 .or_else(|| upper.strip_prefix("LPT"))
167 else {
168 return false;
169 };
170 matches!(
171 digit,
172 "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "\u{b9}" | "\u{b2}" | "\u{b3}"
173 )
174}
175
176#[cfg(test)]
177mod tests;