1pub(crate) mod ptp_device;
36pub(crate) mod staging;
37
38use std::collections::HashMap;
39use std::ffi::OsString;
40use std::fs::{self, File, OpenOptions};
41use std::io::{self, BufWriter, Read, Seek, SeekFrom, Write};
42use std::path::{Path, PathBuf};
43use std::time::Instant;
44
45use capsule_core::crypto::hash::{Hash32, Sha256Hasher};
46use jiff::civil::DateTime;
47pub use ptp_device::PtpCamera;
48pub use staging::safe_file_name;
49use thiserror::Error;
50
51use crate::import::importers::{
52 AdapterError, ExtractedImport, ExtractedMetadata, ImportProvider, SourceAdapter, SourceEntry,
53};
54use crate::utils::hash_file;
55
56#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct CameraObject {
59 pub storage: u32,
61 pub handle: u32,
63 pub parent: u32,
65 pub filename: String,
67 pub size: Option<u64>,
69 pub captured_at: Option<DateTime>,
71 pub is_folder: bool,
73}
74
75#[derive(Debug, Error)]
77pub enum CameraError {
78 #[error("camera connection lost: {0}")]
80 Disconnected(String),
81 #[error("camera refused {operation}: {code}")]
83 Refused {
84 operation: String,
86 code: String,
88 },
89 #[error("camera cannot resume object {handle:08x} at byte {offset}")]
91 ResumeUnsupported {
92 handle: u32,
94 offset: u64,
96 },
97 #[error("staging {path}: {source}")]
99 Staging {
100 path: PathBuf,
102 source: io::Error,
104 },
105 #[error("staging write: {0}")]
107 Sink(io::Error),
108 #[error("object {handle:08x}: received {received} bytes, camera declared {declared}")]
110 SizeMismatch {
111 handle: u32,
113 declared: u64,
115 received: u64,
117 },
118 #[error("object {handle:08x}: staged bytes hash {staged}, received bytes hashed {received}")]
121 IntegrityMismatch {
122 handle: u32,
124 received: Hash32,
126 staged: Hash32,
128 },
129}
130
131impl CameraError {
132 pub fn is_fatal(&self) -> bool {
135 matches!(
136 self,
137 Self::Disconnected(_) | Self::Staging { .. } | Self::Sink(_)
138 )
139 }
140}
141
142pub trait CameraDevice {
144 fn supports_partial_reads(&self) -> bool;
146
147 fn storage_ids(&mut self) -> Result<Vec<u32>, CameraError>;
149
150 fn object_handles(&mut self, storage: u32) -> Result<Vec<u32>, CameraError>;
152
153 fn object(&mut self, handle: u32) -> Result<CameraObject, CameraError>;
155
156 fn read_object(
160 &mut self,
161 object: &CameraObject,
162 offset: u64,
163 sink: &mut dyn Write,
164 ) -> Result<u64, CameraError>;
165}
166
167#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct ReceivedObject {
170 pub object: CameraObject,
172 pub path: PathBuf,
174 pub size: u64,
176 pub sha256: Hash32,
178 pub resumed_from: u64,
180 pub already_staged: bool,
182}
183
184#[derive(Debug)]
186pub struct ObjectFailure {
187 pub storage: u32,
189 pub handle: u32,
191 pub filename: Option<String>,
193 pub error: CameraError,
195}
196
197#[derive(Debug)]
199pub struct StorageFailure {
200 pub storage: Option<u32>,
203 pub error: CameraError,
205}
206
207#[derive(Debug)]
209pub struct CameraReceipt {
210 pub objects_root: PathBuf,
212 pub received: Vec<ReceivedObject>,
214 pub failures: Vec<ObjectFailure>,
216 pub storage_failures: Vec<StorageFailure>,
219}
220
221#[derive(Debug, Clone)]
223pub struct CameraAdapter {
224 staging_root: PathBuf,
225}
226
227impl CameraAdapter {
228 pub fn new(staging_root: impl Into<PathBuf>) -> Self {
231 Self {
232 staging_root: staging_root.into(),
233 }
234 }
235
236 pub fn objects_root(&self) -> PathBuf {
238 staging::objects_dir(&self.staging_root)
239 }
240
241 pub fn receive(&self, device: &mut dyn CameraDevice) -> Result<CameraReceipt, CameraError> {
249 let started = Instant::now();
250 let root = &self.staging_root;
251 tracing::info!(staging_root = %root.display(), "camera import: receive starts");
252 let mut failures = Vec::new();
253 let mut storage_failures = Vec::new();
254 let objects = enumerate(device, &mut failures, &mut storage_failures)?;
255 tracing::info!(
256 objects = objects.len(),
257 unreadable = failures.len(),
258 unlisted_storages = storage_failures.len(),
259 "camera import: enumerated"
260 );
261
262 let generations = match group_generations(root, &objects) {
263 Ok(generations) => generations,
264 Err(error) => {
265 tracing::error!(
266 %error,
267 "camera import: receive halted before any transfer; the staging tree is unreadable"
268 );
269 return Err(error);
270 }
271 };
272
273 let mut received = Vec::new();
274 for object in objects {
275 let start = generations
276 .get(&StemGroup::of(&object))
277 .copied()
278 .unwrap_or(0);
279 match receive_one(root, device, &object, start) {
280 Ok(done) => received.push(done),
281 Err(error) if !error.is_fatal() => {
282 tracing::warn!(
283 storage = format_args!("{:08x}", object.storage),
284 handle = format_args!("{:08x}", object.handle),
285 filename = %object.filename,
286 %error,
287 "camera import: object failed"
288 );
289 failures.push(ObjectFailure {
290 storage: object.storage,
291 handle: object.handle,
292 filename: Some(object.filename.clone()),
293 error,
294 });
295 }
296 Err(error) => {
297 tracing::error!(
298 %error,
299 received = received.len(),
300 "camera import: receive halted; staged objects are kept for the next run"
301 );
302 return Err(error);
303 }
304 }
305 }
306
307 let bytes: u64 = received.iter().map(|r| r.size).sum();
308 tracing::info!(
309 received = received.len(),
310 already_staged = received.iter().filter(|r| r.already_staged).count(),
311 failed = failures.len(),
312 unlisted_storages = storage_failures.len(),
313 bytes,
314 elapsed_ms = started.elapsed().as_millis() as u64,
315 "camera import: receive complete"
316 );
317 Ok(CameraReceipt {
318 objects_root: self.objects_root(),
319 received,
320 failures,
321 storage_failures,
322 })
323 }
324}
325
326impl SourceAdapter for CameraAdapter {
327 fn provider(&self) -> ImportProvider {
328 ImportProvider::Camera
329 }
330
331 fn extract(&self, parts: &[PathBuf]) -> Result<ExtractedImport, AdapterError> {
335 if parts.is_empty() {
336 return Err(AdapterError::NoParts);
337 }
338 for part in parts {
339 if !part.is_dir() {
340 return Err(AdapterError::Io {
341 root: part.display().to_string(),
342 reason: "not a directory".into(),
343 });
344 }
345 }
346 let scan = crate::import::scanner::scan(parts).map_err(|e| AdapterError::Io {
347 root: parts
348 .iter()
349 .map(|p| p.display().to_string())
350 .collect::<Vec<_>>()
351 .join(", "),
352 reason: e.to_string(),
353 })?;
354 let mut entries: Vec<SourceEntry> = scan
355 .candidates
356 .into_iter()
357 .map(|candidate| SourceEntry {
358 candidate,
359 metadata: ExtractedMetadata::default(),
360 })
361 .collect();
362 entries.sort_by(|a, b| a.primary_path().cmp(b.primary_path()));
363 Ok(ExtractedImport { entries })
364 }
365}
366
367fn enumerate(
371 device: &mut dyn CameraDevice,
372 failures: &mut Vec<ObjectFailure>,
373 storage_failures: &mut Vec<StorageFailure>,
374) -> Result<Vec<CameraObject>, CameraError> {
375 let mut storages = match device.storage_ids() {
376 Ok(storages) => storages,
377 Err(error) if !error.is_fatal() => {
378 tracing::warn!(%error, "camera import: storage list refused");
379 storage_failures.push(StorageFailure {
380 storage: None,
381 error,
382 });
383 return Ok(Vec::new());
384 }
385 Err(error) => return Err(error),
386 };
387 storages.sort_unstable();
388 storages.dedup();
389 let mut objects = Vec::new();
390 for storage in storages {
391 let mut handles = match device.object_handles(storage) {
392 Ok(handles) => handles,
393 Err(error) if !error.is_fatal() => {
394 tracing::warn!(
395 storage = format_args!("{storage:08x}"),
396 %error,
397 "camera import: storage not listed; continuing with the others"
398 );
399 storage_failures.push(StorageFailure {
400 storage: Some(storage),
401 error,
402 });
403 continue;
404 }
405 Err(error) => return Err(error),
406 };
407 handles.sort_unstable();
408 handles.dedup();
409 tracing::debug!(
410 storage = format_args!("{storage:08x}"),
411 handles = handles.len(),
412 "camera import: storage listed"
413 );
414 for handle in handles {
415 match device.object(handle) {
416 Ok(object) if object.is_folder => {}
417 Ok(object) => objects.push(object),
418 Err(error) if !error.is_fatal() => failures.push(ObjectFailure {
419 storage,
420 handle,
421 filename: None,
422 error,
423 }),
424 Err(error) => return Err(error),
425 }
426 }
427 }
428 objects.sort_by(|a, b| {
429 (a.storage, a.handle, a.captured_at).cmp(&(b.storage, b.handle, b.captured_at))
430 });
431 Ok(objects)
432}
433
434struct HashingSink<W> {
436 inner: W,
437 hasher: Sha256Hasher,
438 written: u64,
439}
440
441impl<W: Write> Write for HashingSink<W> {
442 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
443 let n = self.inner.write(buf)?;
444 self.hasher.update(&buf[..n]);
445 self.written += n as u64;
446 Ok(n)
447 }
448
449 fn flush(&mut self) -> io::Result<()> {
450 self.inner.flush()
451 }
452}
453
454fn staging_error(path: &Path) -> impl FnOnce(io::Error) -> CameraError + '_ {
455 move |source| CameraError::Staging {
456 path: path.to_path_buf(),
457 source,
458 }
459}
460
461fn receive_one(
464 root: &Path,
465 device: &mut dyn CameraDevice,
466 object: &CameraObject,
467 start: u32,
468) -> Result<ReceivedObject, CameraError> {
469 let generation = match find_slot(root, object, start)? {
470 Slot::Staged(done) => return Ok(done),
471 Slot::Free { generation } => generation,
472 };
473 let final_path = staging::object_path(root, object, generation);
474
475 let partial = staging::partial_path(root, object);
476 let checkpoint = staging::checkpoint_path(&partial);
477 let parent = partial.parent().unwrap_or(root);
478 fs::create_dir_all(parent).map_err(staging_error(parent))?;
479
480 let durable = match object.size {
483 Some(size) if device.supports_partial_reads() => {
484 durable_prefix(&partial, &checkpoint, size)
485 }
486 _ => None,
487 };
488 let (file, hasher, offset) = if let Some((offset, hasher)) = durable {
489 let file = reopen_partial(&partial, offset).map_err(staging_error(&partial))?;
490 tracing::debug!(
491 handle = format_args!("{:08x}", object.handle),
492 offset,
493 "camera import: resuming partial object"
494 );
495 (file, hasher, offset)
496 } else {
497 let _ = fs::remove_file(&checkpoint);
499 let file = File::create(&partial).map_err(staging_error(&partial))?;
500 (file, Sha256Hasher::new(), 0)
501 };
502
503 let mut sink = HashingSink {
504 inner: BufWriter::new(file),
505 hasher,
506 written: 0,
507 };
508 let delivered = match device.read_object(object, offset, &mut sink) {
509 Ok(delivered) => delivered,
510 Err(CameraError::Sink(source)) => {
511 return Err(CameraError::Staging {
512 path: partial,
513 source,
514 });
515 }
516 Err(error @ CameraError::Disconnected(_)) => {
517 if let Err(source) = checkpoint_partial(sink, offset, &partial, &checkpoint) {
520 tracing::warn!(
521 handle = format_args!("{:08x}", object.handle),
522 path = %partial.display(),
523 %source,
524 "camera import: partial object not made durable; it will restart"
525 );
526 discard(&partial, &checkpoint);
527 }
528 return Err(error);
529 }
530 Err(error) => {
531 drop(sink);
533 discard(&partial, &checkpoint);
534 return Err(error);
535 }
536 };
537 let HashingSink {
538 inner,
539 hasher,
540 written,
541 } = sink;
542 let file = inner.into_inner().map_err(|e| CameraError::Staging {
543 path: partial.clone(),
544 source: e.into_error(),
545 })?;
546 file.sync_all().map_err(staging_error(&partial))?;
547 drop(file);
548
549 let size = offset + written;
550 if written != delivered {
551 tracing::warn!(
552 delivered,
553 written,
554 "camera import: device count and sink count differ; trusting the sink"
555 );
556 }
557 if let Some(declared) = object.size
558 && declared != size
559 {
560 discard(&partial, &checkpoint);
561 return Err(CameraError::SizeMismatch {
562 handle: object.handle,
563 declared,
564 received: size,
565 });
566 }
567
568 let received_hash = hasher.finalize();
569 let staged_hash = hash_file(&partial).map_err(staging_error(&partial))?;
570 if staged_hash != received_hash {
571 discard(&partial, &checkpoint);
572 return Err(CameraError::IntegrityMismatch {
573 handle: object.handle,
574 received: received_hash,
575 staged: staged_hash,
576 });
577 }
578
579 let identity = staging::identity_path(root, object, generation);
581 let identity_parent = identity.parent().unwrap_or(root);
582 fs::create_dir_all(identity_parent).map_err(staging_error(identity_parent))?;
583 write_synced(&identity, staging::identity_key(object).as_bytes())
584 .map_err(staging_error(&identity))?;
585 let dir = final_path.parent().unwrap_or(root);
586 fs::create_dir_all(dir).map_err(staging_error(dir))?;
587 fs::rename(&partial, &final_path).map_err(staging_error(&final_path))?;
588 let _ = fs::remove_file(&checkpoint);
589 tracing::debug!(
590 handle = format_args!("{:08x}", object.handle),
591 path = %final_path.display(),
592 generation,
593 size,
594 resumed_from = offset,
595 sha256 = %received_hash,
596 "camera import: object received"
597 );
598 Ok(ReceivedObject {
599 object: object.clone(),
600 path: final_path,
601 size,
602 sha256: received_hash,
603 resumed_from: offset,
604 already_staged: false,
605 })
606}
607
608const MAX_GENERATIONS: u32 = 1024;
610
611enum Slot {
613 Staged(ReceivedObject),
615 Free { generation: u32 },
617}
618
619#[derive(Debug, Clone, PartialEq, Eq, Hash)]
623struct StemGroup {
624 storage: u32,
625 parent: u32,
626 stem: String,
627}
628
629impl StemGroup {
630 fn of(object: &CameraObject) -> Self {
631 Self {
632 storage: object.storage,
633 parent: object.parent,
634 stem: stem_of(&staged_name(object)),
635 }
636 }
637}
638
639fn staged_name(object: &CameraObject) -> OsString {
641 staging::object_path(Path::new(""), object, 0)
642 .file_name()
643 .map(OsString::from)
644 .unwrap_or_default()
645}
646
647fn stem_of(name: &std::ffi::OsStr) -> String {
649 Path::new(name)
650 .file_stem()
651 .unwrap_or_default()
652 .to_string_lossy()
653 .to_lowercase()
654}
655
656type FolderListing = HashMap<String, Vec<OsString>>;
658
659fn list_folder(dir: &Path) -> Result<FolderListing, CameraError> {
661 let mut listing = FolderListing::new();
662 let entries = match fs::read_dir(dir) {
663 Ok(entries) => entries,
664 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(listing),
665 Err(error) => return Err(staging_error(dir)(error)),
666 };
667 for entry in entries {
668 let name = entry.map_err(staging_error(dir))?.file_name();
669 listing.entry(stem_of(&name)).or_default().push(name);
670 }
671 Ok(listing)
672}
673
674fn group_generations(
682 root: &Path,
683 objects: &[CameraObject],
684) -> Result<HashMap<StemGroup, u32>, CameraError> {
685 let mut groups: HashMap<StemGroup, Vec<&CameraObject>> = HashMap::new();
686 for object in objects {
687 groups
688 .entry(StemGroup::of(object))
689 .or_default()
690 .push(object);
691 }
692 let mut listings: HashMap<PathBuf, FolderListing> = HashMap::new();
693 let mut generations = HashMap::with_capacity(groups.len());
694 for (group, members) in groups {
695 let generation = group_generation(root, &group, &members, &mut listings)?;
696 if generation > 0 {
697 tracing::debug!(
698 storage = format_args!("{:08x}", group.storage),
699 parent = format_args!("{:08x}", group.parent),
700 stem = %group.stem,
701 members = members.len(),
702 generation,
703 "camera import: stem group staged in a later folder generation"
704 );
705 }
706 generations.insert(group, generation);
707 }
708 tracing::debug!(
709 groups = generations.len(),
710 moved = generations.values().filter(|g| **g > 0).count(),
711 folders_listed = listings.len(),
712 "camera import: folder generations chosen"
713 );
714 Ok(generations)
715}
716
717fn group_generation(
720 root: &Path,
721 group: &StemGroup,
722 members: &[&CameraObject],
723 listings: &mut HashMap<PathBuf, FolderListing>,
724) -> Result<u32, CameraError> {
725 let first = members[0];
726 for generation in 0..MAX_GENERATIONS {
727 let path = staging::object_path(root, first, generation);
728 let dir = path.parent().unwrap_or(root).to_path_buf();
729 if !listings.contains_key(&dir) {
730 let listing = list_folder(&dir)?;
731 listings.insert(dir.clone(), listing);
732 }
733 let staged = listings[&dir]
734 .get(&group.stem)
735 .map_or(&[][..], Vec::as_slice);
736 let own = |name: &OsString| {
737 members.iter().any(|member| {
738 staged_name(member) == *name && holds_identity(root, member, generation)
739 })
740 };
741 if staged.iter().any(own) {
745 tracing::trace!(
746 dir = %dir.display(),
747 stem = %group.stem,
748 generation,
749 "camera import: stem group already staged in this folder generation"
750 );
751 return Ok(generation);
752 }
753 if staged.is_empty() {
754 return Ok(generation);
755 }
756 tracing::debug!(
757 dir = %dir.display(),
758 stem = %group.stem,
759 "camera import: folder holds another object of this stem; trying the next generation"
760 );
761 }
762 Err(CameraError::Staging {
763 path: staging::object_path(root, first, 0),
764 source: io::Error::other(format!(
765 "{MAX_GENERATIONS} staged folders already hold this file stem"
766 )),
767 })
768}
769
770fn holds_identity(root: &Path, object: &CameraObject, generation: u32) -> bool {
772 fs::read_to_string(staging::identity_path(root, object, generation))
773 .is_ok_and(|recorded| recorded.trim() == staging::identity_key(object))
774}
775
776fn find_slot(root: &Path, object: &CameraObject, start: u32) -> Result<Slot, CameraError> {
786 let key = staging::identity_key(object);
787 for generation in start..MAX_GENERATIONS {
788 let path = staging::object_path(root, object, generation);
789 let Ok(metadata) = fs::metadata(&path) else {
790 return Ok(Slot::Free { generation });
791 };
792 let recorded = fs::read_to_string(staging::identity_path(root, object, generation)).ok();
793 if recorded.as_deref().map(str::trim) != Some(key.as_str()) {
794 tracing::debug!(
795 handle = format_args!("{:08x}", object.handle),
796 path = %path.display(),
797 "camera import: staged path holds another object; trying the next generation"
798 );
799 continue;
800 }
801 if object.size.is_some_and(|size| size != metadata.len()) {
802 tracing::warn!(
803 path = %path.display(),
804 staged = metadata.len(),
805 declared = ?object.size,
806 "camera import: staged file differs from the camera's object; fetching again"
807 );
808 return Ok(Slot::Free { generation });
809 }
810 let sha256 = hash_file(&path).map_err(staging_error(&path))?;
811 tracing::debug!(
812 handle = format_args!("{:08x}", object.handle),
813 path = %path.display(),
814 "camera import: already staged"
815 );
816 return Ok(Slot::Staged(ReceivedObject {
817 object: object.clone(),
818 path,
819 size: metadata.len(),
820 sha256,
821 resumed_from: 0,
822 already_staged: true,
823 }));
824 }
825 Err(CameraError::Staging {
826 path: staging::object_path(root, object, 0),
827 source: io::Error::other(format!(
828 "{MAX_GENERATIONS} staged objects already hold this path"
829 )),
830 })
831}
832
833fn durable_prefix(partial: &Path, checkpoint: &Path, size: u64) -> Option<(u64, Sha256Hasher)> {
837 let recorded = fs::read_to_string(checkpoint).ok()?;
838 let (len, digest) = recorded.trim().split_once(' ')?;
839 let len: u64 = len.parse().ok()?;
840 let digest = Hash32::from_hex(digest).ok()?;
841 if len == 0 || len >= size {
842 return None;
843 }
844 let mut hasher = Sha256Hasher::new();
845 let read = File::open(partial)
846 .and_then(|file| hash_into(&mut file.take(len), &mut hasher))
847 .ok()?;
848 if read != len || hasher.clone().finalize() != digest {
849 tracing::warn!(
850 path = %partial.display(),
851 checkpoint = len,
852 on_disk = read,
853 "camera import: partial object no longer matches its checkpoint; restarting it"
854 );
855 return None;
856 }
857 Some((len, hasher))
858}
859
860fn reopen_partial(partial: &Path, offset: u64) -> io::Result<File> {
866 let mut file = OpenOptions::new().write(true).open(partial)?;
867 file.set_len(offset)?;
868 file.seek(SeekFrom::Start(offset))?;
869 Ok(file)
870}
871
872fn checkpoint_partial(
874 sink: HashingSink<BufWriter<File>>,
875 offset: u64,
876 partial: &Path,
877 checkpoint: &Path,
878) -> io::Result<()> {
879 let HashingSink {
880 inner,
881 hasher,
882 written,
883 } = sink;
884 let file = inner.into_inner().map_err(io::IntoInnerError::into_error)?;
885 file.sync_all()?;
886 drop(file);
887 let len = offset + written;
888 write_synced(
889 checkpoint,
890 format!("{len} {}\n", hasher.finalize().to_hex()).as_bytes(),
891 )?;
892 tracing::debug!(
893 path = %partial.display(),
894 len,
895 "camera import: partial object checkpointed"
896 );
897 Ok(())
898}
899
900fn write_synced(path: &Path, bytes: &[u8]) -> io::Result<()> {
902 let mut file = File::create(path)?;
903 file.write_all(bytes)?;
904 file.sync_all()
905}
906
907fn discard(partial: &Path, checkpoint: &Path) {
909 let _ = fs::remove_file(partial);
910 let _ = fs::remove_file(checkpoint);
911}
912
913fn hash_into(reader: &mut dyn Read, hasher: &mut Sha256Hasher) -> io::Result<u64> {
915 let mut buf = vec![0u8; 64 * 1024];
916 let mut total = 0u64;
917 loop {
918 let n = reader.read(&mut buf)?;
919 if n == 0 {
920 return Ok(total);
921 }
922 hasher.update(&buf[..n]);
923 total += n as u64;
924 }
925}
926
927#[cfg(test)]
928mod tests;