Skip to main content

ferry_core/
lib.rs

1pub mod error;
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::fs::Metadata;
5use std::io::SeekFrom;
6use std::net::SocketAddr;
7use std::path::{Component, Path, PathBuf};
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::sync::{Arc, Mutex};
10use std::time::{Duration, SystemTime, UNIX_EPOCH};
11
12use directories::BaseDirs;
13use mdns_sd::{ResolvedService, ServiceDaemon, ServiceEvent, ServiceInfo};
14use quinn::crypto::rustls::QuicClientConfig;
15use rcgen::{CertifiedKey, generate_simple_self_signed};
16use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
17use rustls::crypto::{CryptoProvider, verify_tls12_signature, verify_tls13_signature};
18use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, ServerName, UnixTime};
19use rustls::{DigitallySignedStruct, SignatureScheme};
20use serde::{Deserialize, Serialize};
21use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
22use uuid::Uuid;
23
24pub use error::{Error, Result};
25
26pub const NATIVE_PROTOCOL_VERSION: u16 = 1;
27pub const MIN_NATIVE_PROTOCOL_VERSION: u16 = 1;
28pub const NATIVE_SERVICE_TYPE: &str = "_ferry._udp.local.";
29
30const DIRECT_MAGIC: &[u8; 8] = b"FERRY01\n";
31const MAX_FRAME_LEN: usize = 16 * 1024 * 1024;
32const IO_BUFFER_SIZE: usize = 64 * 1024;
33const MANIFEST_VERSION: u16 = 1;
34const DEFAULT_CHUNK_SIZE: u64 = 1024 * 1024;
35const DEFAULT_MANIFEST_CONCURRENCY: usize = 8;
36const CONFIG_DIR_NAME: &str = "ferry";
37const PSK_PROOF_CONTEXT: &[u8] = b"fileferry-direct-psk-v1";
38
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct DirectPeer {
41    address: SocketAddr,
42    expected_fingerprint: Option<String>,
43}
44
45impl DirectPeer {
46    pub fn parse(value: &str) -> Result<Self> {
47        Ok(Self {
48            address: value.parse()?,
49            expected_fingerprint: None,
50        })
51    }
52
53    pub const fn address(&self) -> SocketAddr {
54        self.address
55    }
56
57    pub const fn from_address(address: SocketAddr) -> Self {
58        Self {
59            address,
60            expected_fingerprint: None,
61        }
62    }
63
64    pub fn with_expected_fingerprint(mut self, fingerprint: impl Into<String>) -> Result<Self> {
65        self.expected_fingerprint = Some(normalized_fingerprint(fingerprint.into())?);
66        Ok(self)
67    }
68
69    pub fn expected_fingerprint(&self) -> Option<&str> {
70        self.expected_fingerprint.as_deref()
71    }
72}
73
74#[derive(Clone, PartialEq, Eq, Deserialize)]
75pub struct PskSecret(String);
76
77impl PskSecret {
78    pub fn new(psk: impl Into<String>) -> Result<Self> {
79        validate_psk(psk.into()).map(Self)
80    }
81
82    fn expose_secret(&self) -> &str {
83        &self.0
84    }
85}
86
87impl std::fmt::Debug for PskSecret {
88    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89        formatter.write_str("PskSecret(<redacted>)")
90    }
91}
92
93impl Serialize for PskSecret {
94    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
95    where
96        S: serde::Serializer,
97    {
98        serializer.serialize_str("<redacted>")
99    }
100}
101
102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
103pub struct SendRequest {
104    peer: DirectPeer,
105    paths: Vec<PathBuf>,
106    #[serde(default, skip_serializing)]
107    psk: Option<PskSecret>,
108}
109
110impl SendRequest {
111    pub fn new(peer: DirectPeer, paths: Vec<PathBuf>) -> Result<Self> {
112        if paths.is_empty() {
113            return Err(Error::InvalidInput(
114                "at least one file path is required".to_string(),
115            ));
116        }
117
118        Ok(Self {
119            peer,
120            paths,
121            psk: None,
122        })
123    }
124
125    pub const fn peer(&self) -> &DirectPeer {
126        &self.peer
127    }
128
129    pub fn paths(&self) -> &[PathBuf] {
130        &self.paths
131    }
132
133    pub fn with_psk(mut self, psk: impl Into<String>) -> Result<Self> {
134        self.psk = Some(PskSecret::new(psk)?);
135        Ok(self)
136    }
137
138    pub fn psk(&self) -> Option<&str> {
139        self.psk.as_ref().map(PskSecret::expose_secret)
140    }
141}
142
143#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
144pub struct ReceiveRequest {
145    listen: SocketAddr,
146    #[serde(default, skip_serializing)]
147    psk: Option<PskSecret>,
148}
149
150impl ReceiveRequest {
151    pub fn new(listen: SocketAddr) -> Self {
152        Self { listen, psk: None }
153    }
154
155    pub const fn listen(&self) -> SocketAddr {
156        self.listen
157    }
158
159    pub fn with_psk(mut self, psk: impl Into<String>) -> Result<Self> {
160        self.psk = Some(PskSecret::new(psk)?);
161        Ok(self)
162    }
163
164    pub fn psk(&self) -> Option<&str> {
165        self.psk.as_ref().map(PskSecret::expose_secret)
166    }
167}
168
169#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
170pub struct AppConfig {
171    pub alias: String,
172    pub listen_port: u16,
173    pub quic_port: u16,
174    pub download_dir: String,
175    pub auto_accept_known: bool,
176    pub auto_accept_unknown: bool,
177    pub discovery: Vec<String>,
178    pub max_concurrent_files: usize,
179    pub trust: TrustConfig,
180}
181
182impl Default for AppConfig {
183    fn default() -> Self {
184        Self {
185            alias: default_alias(),
186            listen_port: 53317,
187            quic_port: 53318,
188            download_dir: "~/Downloads/ferry".to_string(),
189            auto_accept_known: true,
190            auto_accept_unknown: false,
191            discovery: vec!["native".to_string()],
192            max_concurrent_files: 8,
193            trust: TrustConfig::default(),
194        }
195    }
196}
197
198impl AppConfig {
199    pub fn load_or_default() -> Result<Self> {
200        Self::load_or_default_from(config_dir()?.join("config.toml"))
201    }
202
203    pub fn load_or_default_from(path: impl AsRef<Path>) -> Result<Self> {
204        let path = path.as_ref();
205        match std::fs::read_to_string(path) {
206            Ok(contents) => {
207                toml::from_str(&contents).map_err(|error| Error::ConfigParse(error.to_string()))
208            }
209            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
210            Err(source) => Err(Error::IoPath {
211                path: path.to_path_buf(),
212                source,
213            }),
214        }
215    }
216
217    pub fn save_default_path(&self) -> Result<()> {
218        self.save_to_path(config_dir()?.join("config.toml"))
219    }
220
221    pub fn save_to_path(&self, path: impl AsRef<Path>) -> Result<()> {
222        write_toml_file(path.as_ref(), self)
223    }
224
225    pub fn to_toml_string(&self) -> Result<String> {
226        toml::to_string_pretty(self).map_err(|error| Error::ConfigSerialize(error.to_string()))
227    }
228
229    pub fn redacted(&self) -> Self {
230        let mut config = self.clone();
231        config.trust = config.trust.redacted();
232        config
233    }
234
235    pub fn to_redacted_toml_string(&self) -> Result<String> {
236        self.redacted().to_toml_string()
237    }
238}
239
240#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
241pub struct DaemonConfig {
242    pub listen: SocketAddr,
243    pub destination: PathBuf,
244}
245
246impl DaemonConfig {
247    pub fn from_app_config(config: &AppConfig) -> Result<Self> {
248        Ok(Self {
249            listen: SocketAddr::from(([0, 0, 0, 0], config.quic_port)),
250            destination: expand_home_path(&config.download_dir)?,
251        })
252    }
253
254    pub fn load_or_default() -> Result<Self> {
255        let app_config = AppConfig::load_or_default()?;
256        Self::load_or_default_from(config_dir()?.join("daemon.toml"), &app_config)
257    }
258
259    pub fn load_or_default_from(path: impl AsRef<Path>, app_config: &AppConfig) -> Result<Self> {
260        let path = path.as_ref();
261        match std::fs::read_to_string(path) {
262            Ok(contents) => {
263                toml::from_str(&contents).map_err(|error| Error::ConfigParse(error.to_string()))
264            }
265            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
266                Self::from_app_config(app_config)
267            }
268            Err(source) => Err(Error::IoPath {
269                path: path.to_path_buf(),
270                source,
271            }),
272        }
273    }
274
275    pub fn save_default_path(&self) -> Result<()> {
276        self.save_to_path(config_dir()?.join("daemon.toml"))
277    }
278
279    pub fn save_to_path(&self, path: impl AsRef<Path>) -> Result<()> {
280        write_toml_file(path.as_ref(), self)
281    }
282
283    pub fn to_toml_string(&self) -> Result<String> {
284        toml::to_string_pretty(self).map_err(|error| Error::ConfigSerialize(error.to_string()))
285    }
286}
287
288#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
289pub struct TrustConfig {
290    pub require_fingerprint: bool,
291    pub psk: String,
292}
293
294impl Default for TrustConfig {
295    fn default() -> Self {
296        Self {
297            require_fingerprint: true,
298            psk: String::new(),
299        }
300    }
301}
302
303impl TrustConfig {
304    pub fn redacted(&self) -> Self {
305        let psk = if self.psk.is_empty() {
306            String::new()
307        } else {
308            "<redacted>".to_string()
309        };
310        Self {
311            require_fingerprint: self.require_fingerprint,
312            psk,
313        }
314    }
315}
316
317#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
318pub struct NativeIdentity {
319    cert_der: Vec<u8>,
320    key_der: Vec<u8>,
321    fingerprint: String,
322}
323
324impl NativeIdentity {
325    pub fn load_or_generate() -> Result<Self> {
326        Self::load_or_generate_in(config_dir()?)
327    }
328
329    pub fn load_or_generate_in(config_dir: impl AsRef<Path>) -> Result<Self> {
330        let config_dir = config_dir.as_ref();
331        let cert_path = config_dir.join("identity.cert.der");
332        let key_path = config_dir.join("identity.key.der");
333
334        if cert_path.exists() && key_path.exists() {
335            let cert_der = std::fs::read(&cert_path).map_err(|source| Error::IoPath {
336                path: cert_path,
337                source,
338            })?;
339            let key_der = std::fs::read(&key_path).map_err(|source| Error::IoPath {
340                path: key_path,
341                source,
342            })?;
343
344            return Ok(Self::from_parts(cert_der, key_der));
345        }
346
347        std::fs::create_dir_all(config_dir).map_err(|source| Error::IoPath {
348            path: config_dir.to_path_buf(),
349            source,
350        })?;
351
352        let identity = Self::generate()?;
353        write_private_file(&cert_path, &identity.cert_der)?;
354        write_private_file(&key_path, &identity.key_der)?;
355        Ok(identity)
356    }
357
358    pub fn generate() -> Result<Self> {
359        let CertifiedKey { cert, signing_key } =
360            generate_simple_self_signed(vec!["localhost".to_string()])?;
361        Ok(Self::from_parts(
362            cert.der().to_vec(),
363            signing_key.serialize_der(),
364        ))
365    }
366
367    pub fn fingerprint(&self) -> &str {
368        &self.fingerprint
369    }
370
371    fn cert_chain(&self) -> Vec<CertificateDer<'static>> {
372        vec![CertificateDer::from(self.cert_der.clone())]
373    }
374
375    fn private_key(&self) -> PrivateKeyDer<'static> {
376        PrivateKeyDer::from(PrivatePkcs8KeyDer::from(self.key_der.clone()))
377    }
378
379    fn from_parts(cert_der: Vec<u8>, key_der: Vec<u8>) -> Self {
380        let fingerprint = blake3::hash(&cert_der).to_hex().to_string();
381        Self {
382            cert_der,
383            key_der,
384            fingerprint,
385        }
386    }
387}
388
389#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
390#[serde(rename_all = "snake_case")]
391pub enum TransferDirection {
392    Send,
393    Receive,
394}
395
396#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
397pub struct TransferProgress {
398    pub direction: TransferDirection,
399    pub file_name: String,
400    pub bytes_done: u64,
401    pub bytes_total: u64,
402}
403
404#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
405#[serde(tag = "event", rename_all = "snake_case")]
406pub enum TransferEvent {
407    SessionStarted {
408        direction: TransferDirection,
409        session_id: Uuid,
410        files_total: usize,
411        bytes_total: u64,
412    },
413    FileStarted {
414        direction: TransferDirection,
415        file_name: String,
416        bytes_total: u64,
417        resume_offset: u64,
418    },
419    Progress {
420        direction: TransferDirection,
421        file_name: String,
422        bytes_done: u64,
423        bytes_total: u64,
424    },
425    FileFinished {
426        direction: TransferDirection,
427        file_name: String,
428        bytes: u64,
429        blake3: String,
430        status: TransferFileStatus,
431    },
432    SessionFinished {
433        direction: TransferDirection,
434        files_total: usize,
435        bytes_total: u64,
436        blake3: String,
437    },
438    SessionCancelled {
439        direction: TransferDirection,
440        session_id: Uuid,
441    },
442}
443
444impl TransferEvent {
445    pub fn progress(&self) -> Option<TransferProgress> {
446        match self {
447            Self::Progress {
448                direction,
449                file_name,
450                bytes_done,
451                bytes_total,
452            } => Some(TransferProgress {
453                direction: *direction,
454                file_name: file_name.clone(),
455                bytes_done: *bytes_done,
456                bytes_total: *bytes_total,
457            }),
458            _ => None,
459        }
460    }
461}
462
463#[derive(Debug, Clone, Default)]
464pub struct TransferControl {
465    cancelled: Arc<AtomicBool>,
466}
467
468impl TransferControl {
469    pub fn new() -> Self {
470        Self::default()
471    }
472
473    pub fn cancel(&self) {
474        self.cancelled.store(true, Ordering::SeqCst);
475    }
476
477    pub fn is_cancelled(&self) -> bool {
478        self.cancelled.load(Ordering::SeqCst)
479    }
480
481    fn check_cancelled(&self) -> Result<()> {
482        if self.is_cancelled() {
483            Err(Error::TransferCancelled)
484        } else {
485            Ok(())
486        }
487    }
488}
489
490#[derive(Debug, Clone, PartialEq, Eq)]
491pub struct TransferSummary {
492    pub path: PathBuf,
493    pub file_name: String,
494    pub bytes: u64,
495    pub blake3: String,
496    pub files: Vec<TransferFileSummary>,
497}
498
499#[derive(Debug, Clone, PartialEq, Eq)]
500pub struct TransferFileSummary {
501    pub path: PathBuf,
502    pub relative_path: PathBuf,
503    pub bytes: u64,
504    pub blake3: String,
505    pub status: TransferFileStatus,
506}
507
508#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
509#[serde(rename_all = "snake_case")]
510pub enum TransferFileStatus {
511    Sent,
512    Received,
513    Skipped,
514    Resumed,
515}
516
517#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
518pub struct TransferManifest {
519    pub version: u16,
520    pub session_id: Uuid,
521    pub chunk_size: u64,
522    pub entries: Vec<ManifestEntry>,
523}
524
525impl TransferManifest {
526    pub fn file_entries(&self) -> impl Iterator<Item = &ManifestEntry> {
527        self.entries
528            .iter()
529            .filter(|entry| entry.kind == ManifestEntryKind::File)
530    }
531
532    pub fn total_file_bytes(&self) -> u64 {
533        self.file_entries().map(|entry| entry.size).sum()
534    }
535
536    pub fn digest(&self) -> Result<String> {
537        let bytes = serde_json::to_vec(self).map_err(|error| Error::Protocol(error.to_string()))?;
538        Ok(blake3::hash(&bytes).to_hex().to_string())
539    }
540}
541
542#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
543pub struct ManifestEntry {
544    pub relative_path: PathBuf,
545    pub kind: ManifestEntryKind,
546    pub size: u64,
547    pub blake3: Option<String>,
548    pub chunks: Vec<String>,
549    pub unix_mode: Option<u32>,
550    pub modified_unix_ms: Option<i128>,
551}
552
553#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
554#[serde(rename_all = "snake_case")]
555pub enum ManifestEntryKind {
556    File,
557    Directory,
558}
559
560#[derive(Debug, Clone, PartialEq, Eq)]
561pub enum ResumeDecision {
562    Create,
563    Skip,
564    ResumeFrom(u64),
565    Conflict(String),
566}
567
568#[derive(Debug, Clone, PartialEq, Eq)]
569pub struct PeerObservation {
570    pub fingerprint: String,
571    pub alias: Option<String>,
572    pub hostname: Option<String>,
573    pub address: SocketAddr,
574    pub transports: BTreeSet<String>,
575    pub seen_unix_ms: i128,
576}
577
578impl PeerObservation {
579    pub fn new(fingerprint: impl Into<String>, address: SocketAddr, seen_unix_ms: i128) -> Self {
580        Self {
581            fingerprint: fingerprint.into(),
582            alias: None,
583            hostname: None,
584            address,
585            transports: BTreeSet::new(),
586            seen_unix_ms,
587        }
588    }
589
590    pub fn with_alias(mut self, alias: impl Into<String>) -> Self {
591        self.alias = Some(alias.into());
592        self
593    }
594
595    pub fn with_hostname(mut self, hostname: impl Into<String>) -> Self {
596        self.hostname = Some(hostname.into());
597        self
598    }
599
600    pub fn with_transport(mut self, transport: impl Into<String>) -> Self {
601        self.transports.insert(transport.into());
602        self
603    }
604}
605
606#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
607pub struct PeerRecord {
608    pub fingerprint: String,
609    pub aliases: BTreeSet<String>,
610    pub hostnames: BTreeSet<String>,
611    pub addresses: BTreeSet<SocketAddr>,
612    pub transports: BTreeSet<String>,
613    pub first_seen_unix_ms: i128,
614    pub last_seen_unix_ms: i128,
615}
616
617impl PeerRecord {
618    fn from_observation(observation: PeerObservation) -> Self {
619        let mut aliases = BTreeSet::new();
620        if let Some(alias) = observation.alias {
621            aliases.insert(alias);
622        }
623
624        let mut hostnames = BTreeSet::new();
625        if let Some(hostname) = observation.hostname {
626            hostnames.insert(hostname);
627        }
628
629        let mut addresses = BTreeSet::new();
630        addresses.insert(observation.address);
631
632        Self {
633            fingerprint: observation.fingerprint,
634            aliases,
635            hostnames,
636            addresses,
637            transports: observation.transports,
638            first_seen_unix_ms: observation.seen_unix_ms,
639            last_seen_unix_ms: observation.seen_unix_ms,
640        }
641    }
642
643    fn merge(&mut self, observation: PeerObservation) {
644        if let Some(alias) = observation.alias {
645            self.aliases.insert(alias);
646        }
647        if let Some(hostname) = observation.hostname {
648            self.hostnames.insert(hostname);
649        }
650        self.addresses.insert(observation.address);
651        self.transports.extend(observation.transports);
652        self.first_seen_unix_ms = self.first_seen_unix_ms.min(observation.seen_unix_ms);
653        self.last_seen_unix_ms = self.last_seen_unix_ms.max(observation.seen_unix_ms);
654    }
655
656    pub fn preferred_quic_address(&self) -> Option<SocketAddr> {
657        if !self.transports.contains("quic") {
658            return None;
659        }
660
661        self.addresses.iter().copied().next()
662    }
663}
664
665#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
666#[serde(rename_all = "snake_case")]
667pub enum TrustState {
668    Trusted,
669    Blocked,
670}
671
672#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
673pub struct KnownPeerEntry {
674    pub fingerprint: String,
675    #[serde(default)]
676    pub aliases: BTreeSet<String>,
677    #[serde(default)]
678    pub hostnames: BTreeSet<String>,
679    #[serde(default)]
680    pub addresses: BTreeSet<SocketAddr>,
681    #[serde(default)]
682    pub transports: BTreeSet<String>,
683    pub trust_state: TrustState,
684    pub first_seen_unix_ms: Option<i128>,
685    pub last_seen_unix_ms: Option<i128>,
686}
687
688impl KnownPeerEntry {
689    pub fn trusted(fingerprint: impl Into<String>) -> Result<Self> {
690        let fingerprint = normalized_fingerprint(fingerprint.into())?;
691        Ok(Self {
692            fingerprint,
693            aliases: BTreeSet::new(),
694            hostnames: BTreeSet::new(),
695            addresses: BTreeSet::new(),
696            transports: BTreeSet::new(),
697            trust_state: TrustState::Trusted,
698            first_seen_unix_ms: None,
699            last_seen_unix_ms: None,
700        })
701    }
702
703    pub fn from_record(record: &PeerRecord, trust_state: TrustState) -> Result<Self> {
704        let fingerprint = normalized_fingerprint(record.fingerprint.clone())?;
705        Ok(Self {
706            fingerprint,
707            aliases: record.aliases.clone(),
708            hostnames: record.hostnames.clone(),
709            addresses: record.addresses.clone(),
710            transports: record.transports.clone(),
711            trust_state,
712            first_seen_unix_ms: Some(record.first_seen_unix_ms),
713            last_seen_unix_ms: Some(record.last_seen_unix_ms),
714        })
715    }
716}
717
718#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
719pub struct TrustStore {
720    #[serde(default)]
721    pub peers: BTreeMap<String, KnownPeerEntry>,
722}
723
724impl TrustStore {
725    pub fn load_or_default() -> Result<Self> {
726        Self::load_or_default_from(config_dir()?.join("known_peers.toml"))
727    }
728
729    pub fn load_or_default_from(path: impl AsRef<Path>) -> Result<Self> {
730        let path = path.as_ref();
731        match std::fs::read_to_string(path) {
732            Ok(contents) => {
733                toml::from_str(&contents).map_err(|error| Error::ConfigParse(error.to_string()))
734            }
735            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
736            Err(source) => Err(Error::IoPath {
737                path: path.to_path_buf(),
738                source,
739            }),
740        }
741    }
742
743    pub fn save_default_path(&self) -> Result<()> {
744        self.save_to_path(config_dir()?.join("known_peers.toml"))
745    }
746
747    pub fn save_to_path(&self, path: impl AsRef<Path>) -> Result<()> {
748        write_toml_file(path.as_ref(), self)
749    }
750
751    pub fn trust_fingerprint(&mut self, fingerprint: impl Into<String>) -> Result<&KnownPeerEntry> {
752        let entry = KnownPeerEntry::trusted(fingerprint)?;
753        let fingerprint = entry.fingerprint.clone();
754        self.peers
755            .entry(fingerprint.clone())
756            .and_modify(|existing| existing.trust_state = TrustState::Trusted)
757            .or_insert(entry);
758        Ok(self
759            .peers
760            .get(&fingerprint)
761            .expect("trusted peer entry should exist"))
762    }
763
764    pub fn trust_record(&mut self, record: &PeerRecord) -> Result<&KnownPeerEntry> {
765        let entry = KnownPeerEntry::from_record(record, TrustState::Trusted)?;
766        let fingerprint = entry.fingerprint.clone();
767        self.peers
768            .entry(fingerprint.clone())
769            .and_modify(|existing| {
770                existing.aliases.extend(record.aliases.clone());
771                existing.hostnames.extend(record.hostnames.clone());
772                existing.addresses.extend(record.addresses.clone());
773                existing.transports.extend(record.transports.clone());
774                existing.first_seen_unix_ms = Some(
775                    existing
776                        .first_seen_unix_ms
777                        .unwrap_or(record.first_seen_unix_ms)
778                        .min(record.first_seen_unix_ms),
779                );
780                existing.last_seen_unix_ms = Some(
781                    existing
782                        .last_seen_unix_ms
783                        .unwrap_or(record.last_seen_unix_ms)
784                        .max(record.last_seen_unix_ms),
785                );
786                existing.trust_state = TrustState::Trusted;
787            })
788            .or_insert(entry);
789        Ok(self
790            .peers
791            .get(&fingerprint)
792            .expect("trusted peer entry should exist"))
793    }
794
795    pub fn trust_direct_address(
796        &mut self,
797        fingerprint: impl Into<String>,
798        address: SocketAddr,
799    ) -> Result<&KnownPeerEntry> {
800        let mut entry = KnownPeerEntry::trusted(fingerprint)?;
801        let seen = system_time_unix_ms(SystemTime::now()).unwrap_or_default();
802        entry.addresses.insert(address);
803        entry.transports.insert("quic".to_string());
804        entry.first_seen_unix_ms = Some(seen);
805        entry.last_seen_unix_ms = Some(seen);
806
807        let fingerprint = entry.fingerprint.clone();
808        self.peers
809            .entry(fingerprint.clone())
810            .and_modify(|existing| {
811                existing.addresses.insert(address);
812                existing.transports.insert("quic".to_string());
813                existing.first_seen_unix_ms =
814                    Some(existing.first_seen_unix_ms.unwrap_or(seen).min(seen));
815                existing.last_seen_unix_ms =
816                    Some(existing.last_seen_unix_ms.unwrap_or(seen).max(seen));
817                existing.trust_state = TrustState::Trusted;
818            })
819            .or_insert(entry);
820        Ok(self
821            .peers
822            .get(&fingerprint)
823            .expect("trusted peer entry should exist"))
824    }
825
826    pub fn is_trusted_fingerprint(&self, fingerprint: &str) -> bool {
827        self.peers
828            .get(fingerprint)
829            .is_some_and(|entry| entry.trust_state == TrustState::Trusted)
830    }
831
832    pub fn trusted_fingerprint_for_address(&self, address: SocketAddr) -> Option<&str> {
833        self.peers
834            .values()
835            .find(|entry| {
836                entry.trust_state == TrustState::Trusted && entry.addresses.contains(&address)
837            })
838            .map(|entry| entry.fingerprint.as_str())
839    }
840
841    pub fn forget(&mut self, fingerprint: &str) -> bool {
842        self.peers.remove(fingerprint).is_some()
843    }
844
845    pub fn records(&self) -> impl Iterator<Item = &KnownPeerEntry> {
846        self.peers.values()
847    }
848
849    pub fn to_toml_string(&self) -> Result<String> {
850        toml::to_string_pretty(self).map_err(|error| Error::ConfigSerialize(error.to_string()))
851    }
852}
853
854#[derive(Debug, Default, Clone, PartialEq, Eq)]
855pub struct PeerRegistry {
856    peers: BTreeMap<String, PeerRecord>,
857}
858
859#[derive(Debug, Clone, PartialEq, Eq)]
860pub enum PeerLookup<'a> {
861    Found(&'a PeerRecord),
862    Ambiguous(Vec<&'a PeerRecord>),
863    Missing,
864}
865
866impl PeerRegistry {
867    pub fn new() -> Self {
868        Self::default()
869    }
870
871    pub fn observe(&mut self, observation: PeerObservation) -> Result<&PeerRecord> {
872        if observation.fingerprint.trim().is_empty() {
873            return Err(Error::InvalidInput(
874                "peer fingerprint must not be empty".to_string(),
875            ));
876        }
877
878        let fingerprint = observation.fingerprint.clone();
879        if let Some(record) = self.peers.get_mut(&fingerprint) {
880            record.merge(observation);
881        } else {
882            self.peers.insert(
883                fingerprint.clone(),
884                PeerRecord::from_observation(observation),
885            );
886        }
887
888        Ok(self
889            .peers
890            .get(&fingerprint)
891            .expect("observed peer record should exist"))
892    }
893
894    pub fn get_by_fingerprint(&self, fingerprint: &str) -> Option<&PeerRecord> {
895        self.peers.get(fingerprint)
896    }
897
898    pub fn lookup(&self, query: &str) -> Option<&PeerRecord> {
899        match self.lookup_detail(query) {
900            PeerLookup::Found(record) => Some(record),
901            PeerLookup::Ambiguous(_) | PeerLookup::Missing => None,
902        }
903    }
904
905    pub fn lookup_detail(&self, query: &str) -> PeerLookup<'_> {
906        if let Some(record) = self.peers.get(query) {
907            return PeerLookup::Found(record);
908        }
909
910        let matches = self
911            .peers
912            .values()
913            .filter(|record| {
914                record.fingerprint.starts_with(query)
915                    || record.aliases.iter().any(|alias| alias == query)
916                    || record.hostnames.iter().any(|hostname| hostname == query)
917            })
918            .collect::<Vec<_>>();
919
920        match matches.as_slice() {
921            [] => PeerLookup::Missing,
922            [record] => PeerLookup::Found(record),
923            _ => PeerLookup::Ambiguous(matches),
924        }
925    }
926
927    pub fn records(&self) -> impl Iterator<Item = &PeerRecord> {
928        self.peers.values()
929    }
930}
931
932#[derive(Debug, Clone, PartialEq, Eq)]
933pub struct NativeAnnouncement {
934    pub alias: String,
935    pub fingerprint: String,
936    pub quic_port: u16,
937    pub listen_port: Option<u16>,
938}
939
940impl NativeAnnouncement {
941    pub fn from_config(config: &AppConfig, identity: &NativeIdentity) -> Self {
942        Self {
943            alias: config.alias.clone(),
944            fingerprint: identity.fingerprint().to_string(),
945            quic_port: config.quic_port,
946            listen_port: Some(config.listen_port),
947        }
948    }
949
950    fn service_info(&self) -> Result<ServiceInfo> {
951        let alias = sanitize_dns_label(&self.alias);
952        let fingerprint_prefix = self
953            .fingerprint
954            .get(..12)
955            .unwrap_or(self.fingerprint.as_str());
956        let instance = format!("{alias}-{fingerprint_prefix}");
957        let hostname = format!("{alias}.local.");
958        let properties = [
959            ("pv", NATIVE_PROTOCOL_VERSION.to_string()),
960            ("minpv", MIN_NATIVE_PROTOCOL_VERSION.to_string()),
961            ("fp", self.fingerprint.clone()),
962            ("alias", self.alias.clone()),
963            ("transports", "quic".to_string()),
964            ("quic_port", self.quic_port.to_string()),
965            (
966                "listen_port",
967                self.listen_port
968                    .map(|port| port.to_string())
969                    .unwrap_or_default(),
970            ),
971        ];
972
973        ServiceInfo::new(
974            NATIVE_SERVICE_TYPE,
975            &instance,
976            &hostname,
977            "",
978            self.quic_port,
979            &properties[..],
980        )
981        .map(ServiceInfo::enable_addr_auto)
982        .map_err(|error| Error::Discovery(error.to_string()))
983    }
984}
985
986pub struct NativeAnnouncer {
987    daemon: ServiceDaemon,
988    fullname: String,
989}
990
991impl NativeAnnouncer {
992    pub fn start(announcement: &NativeAnnouncement) -> Result<Self> {
993        let daemon = ServiceDaemon::new().map_err(|error| Error::Discovery(error.to_string()))?;
994        let service = announcement.service_info()?;
995        let fullname = service.get_fullname().to_string();
996        daemon
997            .register(service)
998            .map_err(|error| Error::Discovery(error.to_string()))?;
999        Ok(Self { daemon, fullname })
1000    }
1001}
1002
1003impl Drop for NativeAnnouncer {
1004    fn drop(&mut self) {
1005        let _ = self.daemon.unregister(&self.fullname);
1006        let _ = self.daemon.shutdown();
1007    }
1008}
1009
1010pub async fn discover_native_peers(timeout: Duration) -> Result<PeerRegistry> {
1011    let daemon = ServiceDaemon::new().map_err(|error| Error::Discovery(error.to_string()))?;
1012    let receiver = daemon
1013        .browse(NATIVE_SERVICE_TYPE)
1014        .map_err(|error| Error::Discovery(error.to_string()))?;
1015    let deadline = tokio::time::Instant::now() + timeout;
1016    let mut registry = PeerRegistry::new();
1017
1018    loop {
1019        let now = tokio::time::Instant::now();
1020        if now >= deadline {
1021            break;
1022        }
1023
1024        let wait = deadline - now;
1025        match tokio::time::timeout(wait, receiver.recv_async()).await {
1026            Ok(Ok(ServiceEvent::ServiceResolved(service))) => {
1027                observe_resolved_service(&mut registry, &service)?;
1028            }
1029            Ok(Ok(_)) => {}
1030            Ok(Err(error)) => {
1031                return Err(Error::Discovery(error.to_string()));
1032            }
1033            Err(_) => break,
1034        }
1035    }
1036
1037    daemon
1038        .stop_browse(NATIVE_SERVICE_TYPE)
1039        .map_err(|error| Error::Discovery(error.to_string()))?;
1040    let _ = daemon.shutdown();
1041    Ok(registry)
1042}
1043
1044fn observe_resolved_service(registry: &mut PeerRegistry, service: &ResolvedService) -> Result<()> {
1045    let Some(fingerprint) = service.get_property_val_str("fp") else {
1046        return Ok(());
1047    };
1048    let fingerprint = match normalized_fingerprint(fingerprint.to_string()) {
1049        Ok(fingerprint) => fingerprint,
1050        Err(_) => return Ok(()),
1051    };
1052    let Some(highest_version) = parse_txt_u16(service, "pv") else {
1053        return Ok(());
1054    };
1055    let Some(minimum_version) = parse_txt_u16(service, "minpv") else {
1056        return Ok(());
1057    };
1058    if minimum_version > highest_version
1059        || minimum_version > NATIVE_PROTOCOL_VERSION
1060        || highest_version < MIN_NATIVE_PROTOCOL_VERSION
1061    {
1062        return Ok(());
1063    }
1064
1065    let Some(quic_port) = parse_txt_u16(service, "quic_port") else {
1066        return Ok(());
1067    };
1068    let transports = service
1069        .get_property_val_str("transports")
1070        .unwrap_or_default()
1071        .split(',')
1072        .map(str::trim)
1073        .filter(|value| !value.is_empty())
1074        .map(ToOwned::to_owned)
1075        .collect::<Vec<_>>();
1076    if !transports.iter().any(|transport| transport == "quic") {
1077        return Ok(());
1078    }
1079
1080    let alias = service.get_property_val_str("alias").map(ToOwned::to_owned);
1081    let hostname = Some(service.get_hostname().trim_end_matches('.').to_string());
1082    let seen_unix_ms = system_time_unix_ms(SystemTime::now()).unwrap_or_default();
1083
1084    for address in service.get_addresses_v4() {
1085        let mut observation = PeerObservation::new(
1086            fingerprint.clone(),
1087            SocketAddr::from((address, quic_port)),
1088            seen_unix_ms,
1089        );
1090        if let Some(alias) = &alias {
1091            observation = observation.with_alias(alias.clone());
1092        }
1093        if let Some(hostname) = &hostname {
1094            observation = observation.with_hostname(hostname.clone());
1095        }
1096        for transport in &transports {
1097            observation = observation.with_transport(transport.clone());
1098        }
1099        registry.observe(observation)?;
1100    }
1101
1102    Ok(())
1103}
1104
1105fn parse_txt_u16(service: &ResolvedService, key: &str) -> Option<u16> {
1106    service.get_property_val_str(key)?.parse().ok()
1107}
1108
1109fn sanitize_dns_label(value: &str) -> String {
1110    let mut label = value
1111        .chars()
1112        .map(|ch| {
1113            if ch.is_ascii_alphanumeric() || ch == '-' {
1114                ch.to_ascii_lowercase()
1115            } else {
1116                '-'
1117            }
1118        })
1119        .collect::<String>();
1120    while label.contains("--") {
1121        label = label.replace("--", "-");
1122    }
1123    let label = label.trim_matches('-').to_string();
1124    if label.is_empty() {
1125        "fileferry-device".to_string()
1126    } else {
1127        label
1128    }
1129}
1130
1131#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1132struct DirectReceivePlan {
1133    files: Vec<DirectFilePlan>,
1134}
1135
1136#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1137struct DirectProtocolHello {
1138    protocol_version: u16,
1139    min_protocol_version: u16,
1140    client_fingerprint: String,
1141    #[serde(default)]
1142    psk: bool,
1143}
1144
1145impl DirectProtocolHello {
1146    fn new(identity: &NativeIdentity, psk: Option<&str>) -> Self {
1147        Self {
1148            protocol_version: NATIVE_PROTOCOL_VERSION,
1149            min_protocol_version: MIN_NATIVE_PROTOCOL_VERSION,
1150            client_fingerprint: identity.fingerprint().to_string(),
1151            psk: psk.is_some(),
1152        }
1153    }
1154}
1155
1156#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1157struct DirectProtocolResponse {
1158    accepted: bool,
1159    protocol_version: Option<u16>,
1160    #[serde(default)]
1161    psk_challenge: Option<String>,
1162    error: Option<String>,
1163}
1164
1165impl DirectProtocolResponse {
1166    fn accept(protocol_version: u16) -> Self {
1167        Self {
1168            accepted: true,
1169            protocol_version: Some(protocol_version),
1170            psk_challenge: None,
1171            error: None,
1172        }
1173    }
1174
1175    fn accept_with_psk(protocol_version: u16, challenge: impl Into<String>) -> Self {
1176        Self {
1177            accepted: true,
1178            protocol_version: Some(protocol_version),
1179            psk_challenge: Some(challenge.into()),
1180            error: None,
1181        }
1182    }
1183
1184    fn reject(error: impl Into<String>) -> Self {
1185        Self {
1186            accepted: false,
1187            protocol_version: None,
1188            psk_challenge: None,
1189            error: Some(error.into()),
1190        }
1191    }
1192}
1193
1194#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1195struct DirectPskProof {
1196    proof: String,
1197}
1198
1199#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1200struct DirectPskResult {
1201    accepted: bool,
1202    error: Option<String>,
1203}
1204
1205impl DirectPskResult {
1206    fn accept() -> Self {
1207        Self {
1208            accepted: true,
1209            error: None,
1210        }
1211    }
1212
1213    fn reject(error: impl Into<String>) -> Self {
1214        Self {
1215            accepted: false,
1216            error: Some(error.into()),
1217        }
1218    }
1219}
1220
1221#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1222struct DirectFilePlan {
1223    relative_path: PathBuf,
1224    action: DirectFileAction,
1225    offset: u64,
1226}
1227
1228#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1229#[serde(rename_all = "snake_case")]
1230enum DirectFileAction {
1231    Receive,
1232    Skip,
1233}
1234
1235#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1236struct DirectPayloadHeader {
1237    relative_path: PathBuf,
1238    offset: u64,
1239    bytes: u64,
1240}
1241
1242#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1243struct DirectAck {
1244    ok: bool,
1245    error: Option<String>,
1246}
1247
1248pub fn validate_send_paths(paths: &[PathBuf]) -> Result<()> {
1249    if paths.is_empty() {
1250        return Err(Error::InvalidInput(
1251            "at least one file path is required".to_string(),
1252        ));
1253    }
1254
1255    for path in paths {
1256        if path.as_os_str().is_empty() {
1257            return Err(Error::InvalidInput("empty file path".to_string()));
1258        }
1259    }
1260
1261    Ok(())
1262}
1263
1264pub fn display_path(path: &Path) -> String {
1265    path.to_string_lossy().into_owned()
1266}
1267
1268pub async fn build_manifest(paths: &[PathBuf]) -> Result<TransferManifest> {
1269    validate_send_paths(paths)?;
1270
1271    let sources = collect_manifest_sources(paths)?;
1272    let mut seen = BTreeSet::new();
1273    for source in &sources {
1274        if !seen.insert(source.relative_path.clone()) {
1275            return Err(Error::InvalidInput(format!(
1276                "duplicate transfer path: {}",
1277                display_path(&source.relative_path)
1278            )));
1279        }
1280    }
1281
1282    Ok(TransferManifest {
1283        version: MANIFEST_VERSION,
1284        session_id: Uuid::new_v4(),
1285        chunk_size: DEFAULT_CHUNK_SIZE,
1286        entries: build_manifest_entries(sources).await?,
1287    })
1288}
1289
1290async fn build_manifest_entries(sources: Vec<ManifestSource>) -> Result<Vec<ManifestEntry>> {
1291    if sources.len() <= 1 {
1292        let mut entries = Vec::with_capacity(sources.len());
1293        for source in sources {
1294            entries.push(build_manifest_entry(source).await?);
1295        }
1296        return Ok(entries);
1297    }
1298
1299    let len = sources.len();
1300    let concurrency = std::thread::available_parallelism()
1301        .map(|parallelism| parallelism.get())
1302        .unwrap_or(1)
1303        .clamp(1, DEFAULT_MANIFEST_CONCURRENCY)
1304        .min(len);
1305    let mut sources = sources.into_iter().enumerate();
1306    let mut tasks = tokio::task::JoinSet::new();
1307    let mut entries = vec![None; len];
1308
1309    for _ in 0..concurrency {
1310        if let Some((index, source)) = sources.next() {
1311            tasks.spawn(async move {
1312                build_manifest_entry(source)
1313                    .await
1314                    .map(|entry| (index, entry))
1315            });
1316        }
1317    }
1318
1319    while let Some(result) = tasks.join_next().await {
1320        let (index, entry) =
1321            result.map_err(|error| Error::Protocol(format!("manifest task failed: {error}")))??;
1322        entries[index] = Some(entry);
1323
1324        if let Some((index, source)) = sources.next() {
1325            tasks.spawn(async move {
1326                build_manifest_entry(source)
1327                    .await
1328                    .map(|entry| (index, entry))
1329            });
1330        }
1331    }
1332
1333    Ok(entries
1334        .into_iter()
1335        .map(|entry| entry.expect("manifest task should fill every entry"))
1336        .collect())
1337}
1338
1339pub fn safe_destination_path(destination: &Path, relative_path: &Path) -> Result<PathBuf> {
1340    validate_relative_transfer_path(relative_path)?;
1341    Ok(destination.join(relative_path))
1342}
1343
1344pub async fn decide_resume(
1345    destination: &Path,
1346    entry: &ManifestEntry,
1347    chunk_size: u64,
1348) -> Result<ResumeDecision> {
1349    if entry.kind != ManifestEntryKind::File {
1350        return Ok(ResumeDecision::Create);
1351    }
1352
1353    let path = safe_destination_path(destination, &entry.relative_path)?;
1354    let metadata = match tokio::fs::metadata(&path).await {
1355        Ok(metadata) => metadata,
1356        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
1357            return Ok(ResumeDecision::Create);
1358        }
1359        Err(source) => {
1360            return Err(Error::IoPath { path, source });
1361        }
1362    };
1363
1364    if !metadata.is_file() {
1365        return Ok(ResumeDecision::Conflict(format!(
1366            "{} already exists and is not a regular file",
1367            display_path(&path)
1368        )));
1369    }
1370
1371    if metadata.len() == entry.size {
1372        let expected = entry
1373            .blake3
1374            .as_deref()
1375            .ok_or_else(|| Error::Protocol("file manifest entry is missing BLAKE3".to_string()))?;
1376        let actual = hash_file(&path).await?;
1377        return if actual == expected {
1378            Ok(ResumeDecision::Skip)
1379        } else {
1380            Ok(ResumeDecision::Conflict(format!(
1381                "{} already exists with different contents",
1382                display_path(&path)
1383            )))
1384        };
1385    }
1386
1387    if metadata.len() > entry.size {
1388        return Ok(ResumeDecision::Conflict(format!(
1389            "{} is larger than incoming file",
1390            display_path(&path)
1391        )));
1392    }
1393
1394    let verified_offset = verified_prefix_offset(&path, entry, metadata.len(), chunk_size).await?;
1395    if verified_offset > 0 {
1396        Ok(ResumeDecision::ResumeFrom(verified_offset))
1397    } else {
1398        Ok(ResumeDecision::Conflict(format!(
1399            "{} already exists and does not match a verified prefix",
1400            display_path(&path)
1401        )))
1402    }
1403}
1404
1405pub async fn send_direct_file(
1406    request: &SendRequest,
1407    identity: &NativeIdentity,
1408    mut events: impl FnMut(TransferEvent),
1409) -> Result<TransferSummary> {
1410    send_direct_file_with_control(request, identity, TransferControl::new(), &mut events).await
1411}
1412
1413pub async fn send_direct_file_with_control(
1414    request: &SendRequest,
1415    identity: &NativeIdentity,
1416    control: TransferControl,
1417    mut events: impl FnMut(TransferEvent),
1418) -> Result<TransferSummary> {
1419    send_direct_file_with_control_and_trust(request, identity, control, &mut events, |_| Ok(()))
1420        .await
1421}
1422
1423pub async fn send_direct_file_with_control_and_trust(
1424    request: &SendRequest,
1425    identity: &NativeIdentity,
1426    control: TransferControl,
1427    mut events: impl FnMut(TransferEvent),
1428    mut confirm_unpinned_receiver: impl FnMut(&str) -> Result<()>,
1429) -> Result<TransferSummary> {
1430    ensure_rustls_provider();
1431
1432    control.check_cancelled()?;
1433    let manifest = build_manifest(request.paths()).await?;
1434    let sources = manifest_source_map(request.paths())?;
1435    events(TransferEvent::SessionStarted {
1436        direction: TransferDirection::Send,
1437        session_id: manifest.session_id,
1438        files_total: manifest.file_entries().count(),
1439        bytes_total: manifest.total_file_bytes(),
1440    });
1441    control.check_cancelled()?;
1442
1443    let (client_config, server_fingerprint) = client_config_capturing_server_fingerprint()?;
1444    let mut endpoint = quinn::Endpoint::client(SocketAddr::from(([0, 0, 0, 0], 0)))?;
1445    endpoint.set_default_client_config(client_config);
1446    let connection = endpoint
1447        .connect(request.peer().address(), "localhost")?
1448        .await?;
1449    let actual = captured_server_fingerprint(&server_fingerprint)?;
1450    match request.peer().expected_fingerprint() {
1451        Some(expected) if actual != expected => {
1452            connection.close(1u32.into(), b"fingerprint mismatch");
1453            return Err(Error::PeerFingerprintMismatch {
1454                expected: expected.to_string(),
1455                actual,
1456            });
1457        }
1458        Some(_) => {}
1459        None => {
1460            if let Err(error) = confirm_unpinned_receiver(&actual) {
1461                connection.close(1u32.into(), b"receiver fingerprint not trusted");
1462                return Err(error);
1463            }
1464        }
1465    }
1466    let (mut send, mut recv) = connection.open_bi().await?;
1467
1468    send.write_all(DIRECT_MAGIC).await?;
1469    write_json_frame(
1470        &mut send,
1471        &DirectProtocolHello::new(identity, request.psk()),
1472    )
1473    .await?;
1474    let protocol: DirectProtocolResponse = read_json_frame(&mut recv).await?;
1475    if !protocol.accepted {
1476        return Err(Error::Protocol(protocol.error.unwrap_or_else(|| {
1477            "receiver rejected protocol negotiation".to_string()
1478        })));
1479    }
1480    if protocol.protocol_version != Some(NATIVE_PROTOCOL_VERSION) {
1481        return Err(Error::Protocol(format!(
1482            "receiver selected unsupported protocol version {:?}",
1483            protocol.protocol_version
1484        )));
1485    }
1486    match (request.psk(), protocol.psk_challenge.as_deref()) {
1487        (Some(psk), Some(challenge)) => {
1488            let proof = DirectPskProof {
1489                proof: psk_proof(
1490                    psk,
1491                    challenge,
1492                    identity.fingerprint(),
1493                    NATIVE_PROTOCOL_VERSION,
1494                )?,
1495            };
1496            write_json_frame(&mut send, &proof).await?;
1497            let auth: DirectPskResult = read_json_frame(&mut recv).await?;
1498            if !auth.accepted {
1499                return Err(Error::Authentication(
1500                    auth.error
1501                        .unwrap_or_else(|| "PSK authentication rejected".to_string()),
1502                ));
1503            }
1504        }
1505        (Some(_), None) => {
1506            return Err(Error::Authentication(
1507                "receiver is not configured for PSK mode".to_string(),
1508            ));
1509        }
1510        (None, Some(_)) => {
1511            return Err(Error::Authentication(
1512                "receiver requires PSK authentication".to_string(),
1513            ));
1514        }
1515        (None, None) => {}
1516    }
1517
1518    write_json_frame(&mut send, &manifest).await?;
1519
1520    let plan: DirectReceivePlan = read_json_frame(&mut recv).await?;
1521    let mut summaries = Vec::new();
1522    for file_plan in plan.files {
1523        let Some(entry) = manifest
1524            .file_entries()
1525            .find(|entry| entry.relative_path == file_plan.relative_path)
1526        else {
1527            return Err(Error::Protocol(format!(
1528                "receiver requested unknown file: {}",
1529                display_path(&file_plan.relative_path)
1530            )));
1531        };
1532
1533        let Some(source_path) = sources.get(&file_plan.relative_path) else {
1534            return Err(Error::Protocol(format!(
1535                "missing source for manifest file: {}",
1536                display_path(&file_plan.relative_path)
1537            )));
1538        };
1539
1540        if file_plan.action == DirectFileAction::Skip {
1541            let blake3 = entry.blake3.clone().unwrap_or_default();
1542            events(TransferEvent::FileFinished {
1543                direction: TransferDirection::Send,
1544                file_name: display_path(&entry.relative_path),
1545                bytes: entry.size,
1546                blake3: blake3.clone(),
1547                status: TransferFileStatus::Skipped,
1548            });
1549            summaries.push(TransferFileSummary {
1550                path: source_path.clone(),
1551                relative_path: entry.relative_path.clone(),
1552                bytes: entry.size,
1553                blake3,
1554                status: TransferFileStatus::Skipped,
1555            });
1556            continue;
1557        }
1558
1559        match send_payload_file(
1560            &mut send,
1561            source_path,
1562            entry,
1563            file_plan.offset,
1564            &control,
1565            &mut events,
1566        )
1567        .await
1568        {
1569            Ok(()) => {}
1570            Err(Error::TransferCancelled) => {
1571                events(TransferEvent::SessionCancelled {
1572                    direction: TransferDirection::Send,
1573                    session_id: manifest.session_id,
1574                });
1575                connection.close(1u32.into(), b"cancelled");
1576                return Err(Error::TransferCancelled);
1577            }
1578            Err(error) => return Err(error),
1579        }
1580        let status = if file_plan.offset > 0 {
1581            TransferFileStatus::Resumed
1582        } else {
1583            TransferFileStatus::Sent
1584        };
1585        let blake3 = entry.blake3.clone().unwrap_or_default();
1586        events(TransferEvent::FileFinished {
1587            direction: TransferDirection::Send,
1588            file_name: display_path(&entry.relative_path),
1589            bytes: entry.size,
1590            blake3: blake3.clone(),
1591            status,
1592        });
1593        summaries.push(TransferFileSummary {
1594            path: source_path.clone(),
1595            relative_path: entry.relative_path.clone(),
1596            bytes: entry.size,
1597            blake3,
1598            status,
1599        });
1600    }
1601    send.finish()?;
1602
1603    let ack: DirectAck = read_json_frame(&mut recv).await?;
1604    if !ack.ok {
1605        return Err(Error::Transfer(
1606            ack.error
1607                .unwrap_or_else(|| "receiver rejected transfer".to_string()),
1608        ));
1609    }
1610
1611    connection.close(0u32.into(), b"done");
1612    endpoint.wait_idle().await;
1613
1614    let summary = summary_from_files(&manifest, summaries)?;
1615    events(TransferEvent::SessionFinished {
1616        direction: TransferDirection::Send,
1617        files_total: summary.files.len(),
1618        bytes_total: summary.bytes,
1619        blake3: summary.blake3.clone(),
1620    });
1621    Ok(summary)
1622}
1623
1624pub async fn receive_direct_file(
1625    request: &ReceiveRequest,
1626    destination: impl AsRef<Path>,
1627    identity: &NativeIdentity,
1628    events: impl FnMut(TransferEvent),
1629) -> Result<TransferSummary> {
1630    receive_direct_file_with_control(
1631        request,
1632        destination,
1633        identity,
1634        TransferControl::new(),
1635        events,
1636    )
1637    .await
1638}
1639
1640pub async fn receive_direct_file_with_control(
1641    request: &ReceiveRequest,
1642    destination: impl AsRef<Path>,
1643    identity: &NativeIdentity,
1644    control: TransferControl,
1645    mut events: impl FnMut(TransferEvent),
1646) -> Result<TransferSummary> {
1647    ensure_rustls_provider();
1648
1649    control.check_cancelled()?;
1650    let destination = destination.as_ref();
1651    tokio::fs::create_dir_all(destination)
1652        .await
1653        .map_err(|source| Error::IoPath {
1654            path: destination.to_path_buf(),
1655            source,
1656        })?;
1657
1658    let server_config =
1659        quinn::ServerConfig::with_single_cert(identity.cert_chain(), identity.private_key())?;
1660    let endpoint = quinn::Endpoint::server(server_config, request.listen())?;
1661    let incoming = endpoint.accept().await.ok_or(Error::NoIncomingConnection)?;
1662    let connection = incoming.await?;
1663    let (mut send, mut recv) = connection.accept_bi().await?;
1664
1665    let result = receive_stream_file(
1666        destination,
1667        request.psk(),
1668        &mut recv,
1669        &mut send,
1670        &control,
1671        &mut events,
1672    )
1673    .await;
1674    let ack = match &result {
1675        Ok(_) => DirectAck {
1676            ok: true,
1677            error: None,
1678        },
1679        Err(error) => DirectAck {
1680            ok: false,
1681            error: Some(error.to_string()),
1682        },
1683    };
1684    write_json_frame(&mut send, &ack).await?;
1685    send.finish()?;
1686    let _ = tokio::time::timeout(Duration::from_secs(1), connection.closed()).await;
1687    endpoint.close(0u32.into(), b"done");
1688    endpoint.wait_idle().await;
1689
1690    result
1691}
1692
1693async fn receive_stream_file(
1694    destination: &Path,
1695    psk: Option<&str>,
1696    recv: &mut quinn::RecvStream,
1697    send: &mut quinn::SendStream,
1698    control: &TransferControl,
1699    events: &mut impl FnMut(TransferEvent),
1700) -> Result<TransferSummary> {
1701    let mut magic = [0; DIRECT_MAGIC.len()];
1702    recv.read_exact(&mut magic).await?;
1703    if &magic != DIRECT_MAGIC {
1704        return Err(Error::Protocol("bad direct-transfer magic".to_string()));
1705    }
1706
1707    let hello: DirectProtocolHello = read_json_frame(recv).await?;
1708    let protocol = negotiate_direct_protocol(&hello, psk);
1709    write_json_frame(send, &protocol).await?;
1710    if !protocol.accepted {
1711        return Err(Error::Protocol(protocol.error.unwrap_or_else(|| {
1712            "unsupported direct protocol version".to_string()
1713        })));
1714    }
1715    if let (Some(psk), Some(challenge)) = (psk, protocol.psk_challenge.as_deref()) {
1716        let proof: DirectPskProof = read_json_frame(recv).await?;
1717        let expected = psk_proof(
1718            psk,
1719            challenge,
1720            &hello.client_fingerprint,
1721            protocol.protocol_version.unwrap_or(NATIVE_PROTOCOL_VERSION),
1722        )?;
1723        if proof.proof != expected {
1724            write_json_frame(send, &DirectPskResult::reject("PSK proof mismatch")).await?;
1725            return Err(Error::Authentication("PSK proof mismatch".to_string()));
1726        }
1727        write_json_frame(send, &DirectPskResult::accept()).await?;
1728    }
1729
1730    let manifest: TransferManifest = read_json_frame(recv).await?;
1731    validate_manifest(&manifest)?;
1732    events(TransferEvent::SessionStarted {
1733        direction: TransferDirection::Receive,
1734        session_id: manifest.session_id,
1735        files_total: manifest.file_entries().count(),
1736        bytes_total: manifest.total_file_bytes(),
1737    });
1738    control.check_cancelled()?;
1739
1740    for entry in &manifest.entries {
1741        if entry.kind == ManifestEntryKind::Directory {
1742            let path = safe_destination_path(destination, &entry.relative_path)?;
1743            tokio::fs::create_dir_all(&path)
1744                .await
1745                .map_err(|source| Error::IoPath { path, source })?;
1746        }
1747    }
1748
1749    let mut plan = DirectReceivePlan { files: Vec::new() };
1750    for entry in manifest.file_entries() {
1751        let decision = decide_resume(destination, entry, manifest.chunk_size).await?;
1752        let (action, offset) = match decision {
1753            ResumeDecision::Create => (DirectFileAction::Receive, 0),
1754            ResumeDecision::Skip => (DirectFileAction::Skip, entry.size),
1755            ResumeDecision::ResumeFrom(offset) => (DirectFileAction::Receive, offset),
1756            ResumeDecision::Conflict(message) => return Err(Error::InvalidInput(message)),
1757        };
1758        plan.files.push(DirectFilePlan {
1759            relative_path: entry.relative_path.clone(),
1760            action,
1761            offset,
1762        });
1763    }
1764    write_json_frame(send, &plan).await?;
1765
1766    let mut summaries = Vec::new();
1767    for file_plan in &plan.files {
1768        let Some(entry) = manifest
1769            .file_entries()
1770            .find(|entry| entry.relative_path == file_plan.relative_path)
1771        else {
1772            return Err(Error::Protocol(format!(
1773                "planned file missing from manifest: {}",
1774                display_path(&file_plan.relative_path)
1775            )));
1776        };
1777
1778        let final_path = safe_destination_path(destination, &entry.relative_path)?;
1779        if file_plan.action == DirectFileAction::Skip {
1780            let blake3 = entry.blake3.clone().unwrap_or_default();
1781            events(TransferEvent::FileFinished {
1782                direction: TransferDirection::Receive,
1783                file_name: display_path(&entry.relative_path),
1784                bytes: entry.size,
1785                blake3: blake3.clone(),
1786                status: TransferFileStatus::Skipped,
1787            });
1788            summaries.push(TransferFileSummary {
1789                path: final_path,
1790                relative_path: entry.relative_path.clone(),
1791                bytes: entry.size,
1792                blake3,
1793                status: TransferFileStatus::Skipped,
1794            });
1795            continue;
1796        }
1797
1798        match receive_payload_file(recv, destination, entry, file_plan.offset, control, events)
1799            .await
1800        {
1801            Ok(()) => {}
1802            Err(Error::TransferCancelled) => {
1803                events(TransferEvent::SessionCancelled {
1804                    direction: TransferDirection::Receive,
1805                    session_id: manifest.session_id,
1806                });
1807                return Err(Error::TransferCancelled);
1808            }
1809            Err(error) => return Err(error),
1810        }
1811        let actual_hash = hash_file(&final_path).await?;
1812        let expected_hash = entry
1813            .blake3
1814            .as_deref()
1815            .ok_or_else(|| Error::Protocol("file manifest entry is missing BLAKE3".to_string()))?;
1816        if actual_hash != expected_hash {
1817            return Err(Error::Transfer(format!(
1818                "BLAKE3 hash mismatch for {}",
1819                display_path(&entry.relative_path)
1820            )));
1821        }
1822
1823        let status = if file_plan.offset > 0 {
1824            TransferFileStatus::Resumed
1825        } else {
1826            TransferFileStatus::Received
1827        };
1828        events(TransferEvent::FileFinished {
1829            direction: TransferDirection::Receive,
1830            file_name: display_path(&entry.relative_path),
1831            bytes: entry.size,
1832            blake3: actual_hash.clone(),
1833            status,
1834        });
1835        summaries.push(TransferFileSummary {
1836            path: final_path,
1837            relative_path: entry.relative_path.clone(),
1838            bytes: entry.size,
1839            blake3: actual_hash,
1840            status,
1841        });
1842    }
1843
1844    let summary = summary_from_files(&manifest, summaries)?;
1845    events(TransferEvent::SessionFinished {
1846        direction: TransferDirection::Receive,
1847        files_total: summary.files.len(),
1848        bytes_total: summary.bytes,
1849        blake3: summary.blake3.clone(),
1850    });
1851    Ok(summary)
1852}
1853
1854async fn send_payload_file(
1855    send: &mut quinn::SendStream,
1856    source_path: &Path,
1857    entry: &ManifestEntry,
1858    offset: u64,
1859    control: &TransferControl,
1860    events: &mut impl FnMut(TransferEvent),
1861) -> Result<()> {
1862    if offset > entry.size {
1863        return Err(Error::Protocol(format!(
1864            "resume offset exceeds file size for {}",
1865            display_path(&entry.relative_path)
1866        )));
1867    }
1868
1869    let header = DirectPayloadHeader {
1870        relative_path: entry.relative_path.clone(),
1871        offset,
1872        bytes: entry.size - offset,
1873    };
1874    write_json_frame(send, &header).await?;
1875    events(TransferEvent::FileStarted {
1876        direction: TransferDirection::Send,
1877        file_name: display_path(&entry.relative_path),
1878        bytes_total: entry.size,
1879        resume_offset: offset,
1880    });
1881
1882    let mut file = tokio::fs::File::open(source_path)
1883        .await
1884        .map_err(|source| Error::IoPath {
1885            path: source_path.to_path_buf(),
1886            source,
1887        })?;
1888    file.seek(SeekFrom::Start(offset))
1889        .await
1890        .map_err(|source| Error::IoPath {
1891            path: source_path.to_path_buf(),
1892            source,
1893        })?;
1894
1895    let mut buffer = vec![0; IO_BUFFER_SIZE];
1896    let mut bytes_done = offset;
1897    while bytes_done < entry.size {
1898        control.check_cancelled()?;
1899        let remaining = entry.size - bytes_done;
1900        let read_size = buffer.len().min(remaining as usize);
1901        let read = file
1902            .read(&mut buffer[..read_size])
1903            .await
1904            .map_err(|source| Error::IoPath {
1905                path: source_path.to_path_buf(),
1906                source,
1907            })?;
1908        if read == 0 {
1909            return Err(Error::Protocol(format!(
1910                "source file ended early: {}",
1911                display_path(source_path)
1912            )));
1913        }
1914        send.write_all(&buffer[..read]).await?;
1915        bytes_done += read as u64;
1916        events(TransferEvent::Progress {
1917            direction: TransferDirection::Send,
1918            file_name: display_path(&entry.relative_path),
1919            bytes_done,
1920            bytes_total: entry.size,
1921        });
1922        control.check_cancelled()?;
1923    }
1924
1925    Ok(())
1926}
1927
1928async fn receive_payload_file(
1929    recv: &mut quinn::RecvStream,
1930    destination: &Path,
1931    entry: &ManifestEntry,
1932    offset: u64,
1933    control: &TransferControl,
1934    events: &mut impl FnMut(TransferEvent),
1935) -> Result<()> {
1936    let header: DirectPayloadHeader = read_json_frame(recv).await?;
1937    if header.relative_path != entry.relative_path
1938        || header.offset != offset
1939        || header.bytes != entry.size - offset
1940    {
1941        return Err(Error::Protocol(format!(
1942            "payload header does not match receive plan for {}",
1943            display_path(&entry.relative_path)
1944        )));
1945    }
1946    events(TransferEvent::FileStarted {
1947        direction: TransferDirection::Receive,
1948        file_name: display_path(&entry.relative_path),
1949        bytes_total: entry.size,
1950        resume_offset: offset,
1951    });
1952
1953    let final_path = safe_destination_path(destination, &entry.relative_path)?;
1954    if let Some(parent) = final_path.parent() {
1955        tokio::fs::create_dir_all(parent)
1956            .await
1957            .map_err(|source| Error::IoPath {
1958                path: parent.to_path_buf(),
1959                source,
1960            })?;
1961    }
1962
1963    let write_path = if offset == 0 {
1964        temp_path_for(&final_path)
1965    } else {
1966        final_path.clone()
1967    };
1968
1969    let mut file = if offset == 0 {
1970        tokio::fs::File::create(&write_path)
1971            .await
1972            .map_err(|source| Error::IoPath {
1973                path: write_path.clone(),
1974                source,
1975            })?
1976    } else {
1977        let mut file = tokio::fs::OpenOptions::new()
1978            .write(true)
1979            .open(&write_path)
1980            .await
1981            .map_err(|source| Error::IoPath {
1982                path: write_path.clone(),
1983                source,
1984            })?;
1985        file.set_len(offset).await.map_err(|source| Error::IoPath {
1986            path: write_path.clone(),
1987            source,
1988        })?;
1989        file.seek(SeekFrom::Start(offset))
1990            .await
1991            .map_err(|source| Error::IoPath {
1992                path: write_path.clone(),
1993                source,
1994            })?;
1995        file
1996    };
1997
1998    let mut bytes_done = offset;
1999    let mut bytes_remaining = header.bytes;
2000    let mut buffer = vec![0; IO_BUFFER_SIZE];
2001    while bytes_remaining > 0 {
2002        if control.is_cancelled() {
2003            if offset == 0 {
2004                let _ = tokio::fs::remove_file(&write_path).await;
2005            }
2006            return Err(Error::TransferCancelled);
2007        }
2008        let read_size = buffer.len().min(bytes_remaining as usize);
2009        let read = match recv.read(&mut buffer[..read_size]).await {
2010            Ok(Some(read)) => read,
2011            Ok(None) => {
2012                if offset == 0 {
2013                    let _ = tokio::fs::remove_file(&write_path).await;
2014                }
2015                return Err(Error::Protocol(
2016                    "stream ended before file payload".to_string(),
2017                ));
2018            }
2019            Err(error) => {
2020                if offset == 0 {
2021                    let _ = tokio::fs::remove_file(&write_path).await;
2022                }
2023                return Err(Error::Read(error));
2024            }
2025        };
2026
2027        file.write_all(&buffer[..read])
2028            .await
2029            .map_err(|source| Error::IoPath {
2030                path: write_path.clone(),
2031                source,
2032            })?;
2033        bytes_done += read as u64;
2034        bytes_remaining -= read as u64;
2035        events(TransferEvent::Progress {
2036            direction: TransferDirection::Receive,
2037            file_name: display_path(&entry.relative_path),
2038            bytes_done,
2039            bytes_total: entry.size,
2040        });
2041        if control.is_cancelled() {
2042            if offset == 0 {
2043                let _ = tokio::fs::remove_file(&write_path).await;
2044            }
2045            return Err(Error::TransferCancelled);
2046        }
2047    }
2048
2049    file.flush().await.map_err(|source| Error::IoPath {
2050        path: write_path.clone(),
2051        source,
2052    })?;
2053    drop(file);
2054
2055    if offset == 0 {
2056        tokio::fs::rename(&write_path, &final_path)
2057            .await
2058            .map_err(|source| Error::IoPath {
2059                path: final_path,
2060                source,
2061            })?;
2062    }
2063
2064    Ok(())
2065}
2066
2067async fn write_json_frame<T: Serialize>(send: &mut quinn::SendStream, value: &T) -> Result<()> {
2068    let bytes = serde_json::to_vec(value).map_err(|error| Error::Protocol(error.to_string()))?;
2069    if bytes.len() > MAX_FRAME_LEN {
2070        return Err(Error::Protocol("frame exceeds maximum length".to_string()));
2071    }
2072    send.write_all(&(bytes.len() as u32).to_be_bytes()).await?;
2073    send.write_all(&bytes).await?;
2074    Ok(())
2075}
2076
2077async fn read_json_frame<T: for<'de> Deserialize<'de>>(recv: &mut quinn::RecvStream) -> Result<T> {
2078    let mut len = [0; 4];
2079    recv.read_exact(&mut len).await?;
2080    let len = u32::from_be_bytes(len) as usize;
2081    if len > MAX_FRAME_LEN {
2082        return Err(Error::Protocol("frame exceeds maximum length".to_string()));
2083    }
2084
2085    let mut bytes = vec![0; len];
2086    recv.read_exact(&mut bytes).await?;
2087    serde_json::from_slice(&bytes).map_err(|error| Error::Protocol(error.to_string()))
2088}
2089
2090fn negotiate_direct_protocol(
2091    hello: &DirectProtocolHello,
2092    psk: Option<&str>,
2093) -> DirectProtocolResponse {
2094    if hello.min_protocol_version > NATIVE_PROTOCOL_VERSION {
2095        return DirectProtocolResponse::reject(format!(
2096            "peer requires protocol version {}, local max is {}",
2097            hello.min_protocol_version, NATIVE_PROTOCOL_VERSION
2098        ));
2099    }
2100
2101    if hello.protocol_version < MIN_NATIVE_PROTOCOL_VERSION {
2102        return DirectProtocolResponse::reject(format!(
2103            "peer max protocol version {} is below local minimum {}",
2104            hello.protocol_version, MIN_NATIVE_PROTOCOL_VERSION
2105        ));
2106    }
2107
2108    let selected_version = NATIVE_PROTOCOL_VERSION.min(hello.protocol_version);
2109    match (psk, hello.psk) {
2110        (Some(_), false) => DirectProtocolResponse::reject("receiver requires PSK authentication"),
2111        (Some(_), true) => {
2112            DirectProtocolResponse::accept_with_psk(selected_version, Uuid::new_v4().to_string())
2113        }
2114        (None, true) => DirectProtocolResponse::reject("receiver is not configured for PSK mode"),
2115        (None, false) => DirectProtocolResponse::accept(selected_version),
2116    }
2117}
2118
2119#[derive(Debug, Clone)]
2120struct ManifestSource {
2121    source_path: PathBuf,
2122    relative_path: PathBuf,
2123}
2124
2125fn collect_manifest_sources(paths: &[PathBuf]) -> Result<Vec<ManifestSource>> {
2126    let mut sources = Vec::new();
2127    for path in paths {
2128        let metadata = std::fs::symlink_metadata(path).map_err(|source| Error::IoPath {
2129            path: path.clone(),
2130            source,
2131        })?;
2132        if metadata.file_type().is_symlink() {
2133            return Err(Error::InvalidInput(format!(
2134                "{} is a symlink; symlink transfers are not supported",
2135                display_path(path)
2136            )));
2137        }
2138
2139        let root_name = path
2140            .file_name()
2141            .ok_or_else(|| Error::InvalidInput(format!("{} has no file name", display_path(path))))?
2142            .to_os_string();
2143        let relative_path = PathBuf::from(root_name);
2144
2145        if metadata.is_dir() {
2146            sources.push(ManifestSource {
2147                source_path: path.clone(),
2148                relative_path: relative_path.clone(),
2149            });
2150            collect_dir_sources(path, &relative_path, &mut sources)?;
2151        } else if metadata.is_file() {
2152            sources.push(ManifestSource {
2153                source_path: path.clone(),
2154                relative_path,
2155            });
2156        } else {
2157            return Err(Error::InvalidInput(format!(
2158                "{} is not a regular file or directory",
2159                display_path(path)
2160            )));
2161        }
2162    }
2163
2164    Ok(sources)
2165}
2166
2167fn collect_dir_sources(
2168    dir: &Path,
2169    relative_dir: &Path,
2170    sources: &mut Vec<ManifestSource>,
2171) -> Result<()> {
2172    for entry in std::fs::read_dir(dir).map_err(|source| Error::IoPath {
2173        path: dir.to_path_buf(),
2174        source,
2175    })? {
2176        let entry = entry.map_err(|source| Error::IoPath {
2177            path: dir.to_path_buf(),
2178            source,
2179        })?;
2180        let path = entry.path();
2181        let metadata = std::fs::symlink_metadata(&path).map_err(|source| Error::IoPath {
2182            path: path.clone(),
2183            source,
2184        })?;
2185        if metadata.file_type().is_symlink() {
2186            return Err(Error::InvalidInput(format!(
2187                "{} is a symlink; symlink transfers are not supported",
2188                display_path(&path)
2189            )));
2190        }
2191
2192        let relative_path = relative_dir.join(entry.file_name());
2193        if metadata.is_dir() {
2194            sources.push(ManifestSource {
2195                source_path: path.clone(),
2196                relative_path: relative_path.clone(),
2197            });
2198            collect_dir_sources(&path, &relative_path, sources)?;
2199        } else if metadata.is_file() {
2200            sources.push(ManifestSource {
2201                source_path: path,
2202                relative_path,
2203            });
2204        }
2205    }
2206
2207    Ok(())
2208}
2209
2210fn manifest_source_map(paths: &[PathBuf]) -> Result<BTreeMap<PathBuf, PathBuf>> {
2211    Ok(collect_manifest_sources(paths)?
2212        .into_iter()
2213        .filter_map(|source| {
2214            let metadata = std::fs::metadata(&source.source_path).ok()?;
2215            metadata
2216                .is_file()
2217                .then_some((source.relative_path, source.source_path))
2218        })
2219        .collect())
2220}
2221
2222async fn build_manifest_entry(source: ManifestSource) -> Result<ManifestEntry> {
2223    validate_relative_transfer_path(&source.relative_path)?;
2224    let metadata = tokio::fs::metadata(&source.source_path)
2225        .await
2226        .map_err(|source_error| Error::IoPath {
2227            path: source.source_path.clone(),
2228            source: source_error,
2229        })?;
2230    let unix_mode = unix_mode(&metadata);
2231    let modified_unix_ms = modified_unix_ms(&metadata);
2232
2233    if metadata.is_dir() {
2234        return Ok(ManifestEntry {
2235            relative_path: source.relative_path,
2236            kind: ManifestEntryKind::Directory,
2237            size: 0,
2238            blake3: None,
2239            chunks: Vec::new(),
2240            unix_mode,
2241            modified_unix_ms,
2242        });
2243    }
2244
2245    let (blake3, chunks) = hash_file_with_chunks(&source.source_path, DEFAULT_CHUNK_SIZE).await?;
2246    Ok(ManifestEntry {
2247        relative_path: source.relative_path,
2248        kind: ManifestEntryKind::File,
2249        size: metadata.len(),
2250        blake3: Some(blake3),
2251        chunks,
2252        unix_mode,
2253        modified_unix_ms,
2254    })
2255}
2256
2257fn validate_manifest(manifest: &TransferManifest) -> Result<()> {
2258    if manifest.version != MANIFEST_VERSION {
2259        return Err(Error::Protocol(format!(
2260            "unsupported manifest version {}",
2261            manifest.version
2262        )));
2263    }
2264    if manifest.chunk_size == 0 {
2265        return Err(Error::Protocol("manifest chunk size is zero".to_string()));
2266    }
2267
2268    let mut seen = BTreeSet::new();
2269    for entry in &manifest.entries {
2270        validate_relative_transfer_path(&entry.relative_path)?;
2271        if !seen.insert(entry.relative_path.clone()) {
2272            return Err(Error::Protocol(format!(
2273                "duplicate manifest path: {}",
2274                display_path(&entry.relative_path)
2275            )));
2276        }
2277        if entry.kind == ManifestEntryKind::File && entry.blake3.is_none() {
2278            return Err(Error::Protocol(format!(
2279                "file manifest entry is missing BLAKE3: {}",
2280                display_path(&entry.relative_path)
2281            )));
2282        }
2283    }
2284
2285    Ok(())
2286}
2287
2288fn validate_relative_transfer_path(path: &Path) -> Result<()> {
2289    if path.as_os_str().is_empty() || path.is_absolute() {
2290        return Err(Error::InvalidInput(format!(
2291            "unsafe transfer path: {}",
2292            display_path(path)
2293        )));
2294    }
2295
2296    let mut normal_components = 0usize;
2297    for component in path.components() {
2298        match component {
2299            Component::Normal(value) => {
2300                let Some(name) = value.to_str() else {
2301                    return Err(Error::InvalidInput(format!(
2302                        "transfer path must be UTF-8: {}",
2303                        display_path(path)
2304                    )));
2305                };
2306                validate_path_component(name, path)?;
2307                normal_components += 1;
2308            }
2309            Component::CurDir
2310            | Component::ParentDir
2311            | Component::RootDir
2312            | Component::Prefix(_) => {
2313                return Err(Error::InvalidInput(format!(
2314                    "unsafe transfer path: {}",
2315                    display_path(path)
2316                )));
2317            }
2318        }
2319    }
2320
2321    if normal_components == 0 {
2322        return Err(Error::InvalidInput(format!(
2323            "unsafe transfer path: {}",
2324            display_path(path)
2325        )));
2326    }
2327
2328    Ok(())
2329}
2330
2331fn validate_path_component(component: &str, full_path: &Path) -> Result<()> {
2332    if component.is_empty()
2333        || component.contains('\\')
2334        || component.contains('/')
2335        || component.contains(':')
2336        || component.ends_with(' ')
2337        || component.ends_with('.')
2338        || is_windows_reserved_name(component)
2339    {
2340        return Err(Error::InvalidInput(format!(
2341            "unsafe transfer path: {}",
2342            display_path(full_path)
2343        )));
2344    }
2345
2346    Ok(())
2347}
2348
2349fn is_windows_reserved_name(component: &str) -> bool {
2350    let stem = component
2351        .split('.')
2352        .next()
2353        .unwrap_or(component)
2354        .trim_end_matches([' ', '.'])
2355        .to_ascii_uppercase();
2356    matches!(
2357        stem.as_str(),
2358        "CON"
2359            | "PRN"
2360            | "AUX"
2361            | "NUL"
2362            | "COM1"
2363            | "COM2"
2364            | "COM3"
2365            | "COM4"
2366            | "COM5"
2367            | "COM6"
2368            | "COM7"
2369            | "COM8"
2370            | "COM9"
2371            | "LPT1"
2372            | "LPT2"
2373            | "LPT3"
2374            | "LPT4"
2375            | "LPT5"
2376            | "LPT6"
2377            | "LPT7"
2378            | "LPT8"
2379            | "LPT9"
2380    )
2381}
2382
2383async fn hash_file(path: &Path) -> Result<String> {
2384    hash_file_with_chunks(path, DEFAULT_CHUNK_SIZE)
2385        .await
2386        .map(|(hash, _)| hash)
2387}
2388
2389async fn hash_file_with_chunks(path: &Path, chunk_size: u64) -> Result<(String, Vec<String>)> {
2390    let mut file = tokio::fs::File::open(path)
2391        .await
2392        .map_err(|source| Error::IoPath {
2393            path: path.to_path_buf(),
2394            source,
2395        })?;
2396    let mut hasher = blake3::Hasher::new();
2397    let mut chunk_hasher = blake3::Hasher::new();
2398    let mut chunk_bytes = 0u64;
2399    let mut chunks = Vec::new();
2400    let mut buffer = vec![0; IO_BUFFER_SIZE];
2401
2402    loop {
2403        let read = file
2404            .read(&mut buffer)
2405            .await
2406            .map_err(|source| Error::IoPath {
2407                path: path.to_path_buf(),
2408                source,
2409            })?;
2410        if read == 0 {
2411            break;
2412        }
2413        hasher.update(&buffer[..read]);
2414
2415        let mut remaining = &buffer[..read];
2416        while !remaining.is_empty() {
2417            let take = remaining.len().min((chunk_size - chunk_bytes) as usize);
2418            chunk_hasher.update(&remaining[..take]);
2419            chunk_bytes += take as u64;
2420            remaining = &remaining[take..];
2421            if chunk_bytes == chunk_size {
2422                chunks.push(chunk_hasher.finalize().to_hex().to_string());
2423                chunk_hasher = blake3::Hasher::new();
2424                chunk_bytes = 0;
2425            }
2426        }
2427    }
2428
2429    if chunk_bytes > 0 {
2430        chunks.push(chunk_hasher.finalize().to_hex().to_string());
2431    }
2432
2433    Ok((hasher.finalize().to_hex().to_string(), chunks))
2434}
2435
2436async fn verified_prefix_offset(
2437    path: &Path,
2438    entry: &ManifestEntry,
2439    existing_len: u64,
2440    chunk_size: u64,
2441) -> Result<u64> {
2442    if existing_len == 0 || entry.chunks.is_empty() {
2443        return Ok(0);
2444    }
2445
2446    let chunks_to_check = (existing_len / chunk_size).min(entry.chunks.len() as u64) as usize;
2447    if chunks_to_check == 0 {
2448        return Ok(0);
2449    }
2450
2451    let mut file = tokio::fs::File::open(path)
2452        .await
2453        .map_err(|source| Error::IoPath {
2454            path: path.to_path_buf(),
2455            source,
2456        })?;
2457    let mut buffer = vec![0; IO_BUFFER_SIZE];
2458    let mut verified_chunks = 0usize;
2459
2460    for expected in entry.chunks.iter().take(chunks_to_check) {
2461        let mut remaining = chunk_size;
2462        let mut hasher = blake3::Hasher::new();
2463        while remaining > 0 {
2464            let read_size = buffer.len().min(remaining as usize);
2465            file.read_exact(&mut buffer[..read_size])
2466                .await
2467                .map_err(|source| Error::IoPath {
2468                    path: path.to_path_buf(),
2469                    source,
2470                })?;
2471            hasher.update(&buffer[..read_size]);
2472            remaining -= read_size as u64;
2473        }
2474
2475        if hasher.finalize().to_hex().as_str() != expected {
2476            break;
2477        }
2478        verified_chunks += 1;
2479    }
2480
2481    Ok(verified_chunks as u64 * chunk_size)
2482}
2483
2484fn summary_from_files(
2485    manifest: &TransferManifest,
2486    files: Vec<TransferFileSummary>,
2487) -> Result<TransferSummary> {
2488    let bytes = manifest.total_file_bytes();
2489    let blake3 = if files.len() == 1 {
2490        files[0].blake3.clone()
2491    } else {
2492        manifest.digest()?
2493    };
2494    let file_name = if files.len() == 1 {
2495        display_path(&files[0].relative_path)
2496    } else {
2497        format!("{} files", files.len())
2498    };
2499    let path = files
2500        .first()
2501        .map(|file| file.path.clone())
2502        .unwrap_or_default();
2503
2504    Ok(TransferSummary {
2505        path,
2506        file_name,
2507        bytes,
2508        blake3,
2509        files,
2510    })
2511}
2512
2513fn temp_path_for(final_path: &Path) -> PathBuf {
2514    let file_name = final_path
2515        .file_name()
2516        .and_then(|name| name.to_str())
2517        .unwrap_or("transfer");
2518    final_path.with_file_name(format!(".{file_name}.{}.ferry-part", Uuid::new_v4()))
2519}
2520
2521fn modified_unix_ms(metadata: &Metadata) -> Option<i128> {
2522    system_time_unix_ms(metadata.modified().ok()?)
2523}
2524
2525fn system_time_unix_ms(time: SystemTime) -> Option<i128> {
2526    match time.duration_since(UNIX_EPOCH) {
2527        Ok(duration) => Some(duration.as_millis() as i128),
2528        Err(error) => Some(-(error.duration().as_millis() as i128)),
2529    }
2530}
2531
2532#[cfg(unix)]
2533fn unix_mode(metadata: &Metadata) -> Option<u32> {
2534    use std::os::unix::fs::PermissionsExt;
2535
2536    Some(metadata.permissions().mode())
2537}
2538
2539#[cfg(not(unix))]
2540fn unix_mode(_metadata: &Metadata) -> Option<u32> {
2541    None
2542}
2543
2544fn client_config_capturing_server_fingerprint()
2545-> Result<(quinn::ClientConfig, Arc<Mutex<Option<String>>>)> {
2546    let server_fingerprint = Arc::new(Mutex::new(None));
2547    let crypto = rustls::ClientConfig::builder()
2548        .dangerous()
2549        .with_custom_certificate_verifier(ServerFingerprintVerifier::new(
2550            server_fingerprint.clone(),
2551        ))
2552        .with_no_client_auth();
2553
2554    let config = quinn::ClientConfig::new(Arc::new(
2555        QuicClientConfig::try_from(crypto)
2556            .map_err(|error| Error::CryptoConfig(error.to_string()))?,
2557    ));
2558    Ok((config, server_fingerprint))
2559}
2560
2561fn captured_server_fingerprint(fingerprint: &Arc<Mutex<Option<String>>>) -> Result<String> {
2562    fingerprint
2563        .lock()
2564        .map_err(|_| Error::CryptoConfig("server fingerprint capture lock poisoned".to_string()))?
2565        .clone()
2566        .ok_or_else(|| {
2567            Error::CryptoConfig("server certificate fingerprint was not captured".to_string())
2568        })
2569}
2570
2571#[derive(Debug)]
2572struct ServerFingerprintVerifier {
2573    provider: Arc<CryptoProvider>,
2574    server_fingerprint: Arc<Mutex<Option<String>>>,
2575}
2576
2577impl ServerFingerprintVerifier {
2578    fn new(server_fingerprint: Arc<Mutex<Option<String>>>) -> Arc<Self> {
2579        Arc::new(Self {
2580            provider: Arc::new(rustls::crypto::ring::default_provider()),
2581            server_fingerprint,
2582        })
2583    }
2584}
2585
2586impl ServerCertVerifier for ServerFingerprintVerifier {
2587    fn verify_server_cert(
2588        &self,
2589        end_entity: &CertificateDer<'_>,
2590        _intermediates: &[CertificateDer<'_>],
2591        _server_name: &ServerName<'_>,
2592        _ocsp: &[u8],
2593        _now: UnixTime,
2594    ) -> std::result::Result<ServerCertVerified, rustls::Error> {
2595        let fingerprint = blake3::hash(end_entity.as_ref()).to_hex().to_string();
2596        *self.server_fingerprint.lock().map_err(|_| {
2597            rustls::Error::General("server fingerprint capture lock poisoned".to_string())
2598        })? = Some(fingerprint);
2599        Ok(ServerCertVerified::assertion())
2600    }
2601
2602    fn verify_tls12_signature(
2603        &self,
2604        message: &[u8],
2605        cert: &CertificateDer<'_>,
2606        dss: &DigitallySignedStruct,
2607    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
2608        verify_tls12_signature(
2609            message,
2610            cert,
2611            dss,
2612            &self.provider.signature_verification_algorithms,
2613        )
2614    }
2615
2616    fn verify_tls13_signature(
2617        &self,
2618        message: &[u8],
2619        cert: &CertificateDer<'_>,
2620        dss: &DigitallySignedStruct,
2621    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
2622        verify_tls13_signature(
2623            message,
2624            cert,
2625            dss,
2626            &self.provider.signature_verification_algorithms,
2627        )
2628    }
2629
2630    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
2631        self.provider
2632            .signature_verification_algorithms
2633            .supported_schemes()
2634    }
2635}
2636
2637fn ensure_rustls_provider() {
2638    let _ = rustls::crypto::ring::default_provider().install_default();
2639}
2640
2641pub fn config_dir() -> Result<PathBuf> {
2642    let base_dirs = BaseDirs::new().ok_or(Error::ConfigDirUnavailable)?;
2643    Ok(base_dirs.config_dir().join(CONFIG_DIR_NAME))
2644}
2645
2646fn default_alias() -> String {
2647    std::env::var("HOSTNAME")
2648        .or_else(|_| std::env::var("COMPUTERNAME"))
2649        .ok()
2650        .filter(|value| !value.trim().is_empty())
2651        .unwrap_or_else(|| "fileferry-device".to_string())
2652}
2653
2654fn expand_home_path(path: &str) -> Result<PathBuf> {
2655    if path == "~" {
2656        return Ok(BaseDirs::new()
2657            .ok_or(Error::ConfigDirUnavailable)?
2658            .home_dir()
2659            .to_path_buf());
2660    }
2661
2662    if let Some(rest) = path.strip_prefix("~/") {
2663        return Ok(BaseDirs::new()
2664            .ok_or(Error::ConfigDirUnavailable)?
2665            .home_dir()
2666            .join(rest));
2667    }
2668
2669    Ok(PathBuf::from(path))
2670}
2671
2672fn normalized_fingerprint(fingerprint: String) -> Result<String> {
2673    let fingerprint = fingerprint.trim().to_ascii_lowercase();
2674    if fingerprint.len() != 64 || !fingerprint.chars().all(|char| char.is_ascii_hexdigit()) {
2675        return Err(Error::InvalidInput(
2676            "peer fingerprint must be a full 64-character hex BLAKE3 fingerprint".to_string(),
2677        ));
2678    }
2679
2680    Ok(fingerprint)
2681}
2682
2683fn validate_psk(psk: String) -> Result<String> {
2684    if psk.is_empty() {
2685        return Err(Error::InvalidInput("PSK must not be empty".to_string()));
2686    }
2687
2688    Ok(psk)
2689}
2690
2691fn psk_proof(
2692    psk: &str,
2693    challenge: &str,
2694    client_fingerprint: &str,
2695    protocol_version: u16,
2696) -> Result<String> {
2697    validate_psk(psk.to_string())?;
2698    let key = blake3::hash(psk.as_bytes());
2699    let mut message = Vec::new();
2700    message.extend_from_slice(PSK_PROOF_CONTEXT);
2701    message.push(0);
2702    message.extend_from_slice(challenge.as_bytes());
2703    message.push(0);
2704    message.extend_from_slice(client_fingerprint.as_bytes());
2705    message.push(0);
2706    message.extend_from_slice(protocol_version.to_string().as_bytes());
2707    Ok(blake3::keyed_hash(key.as_bytes(), &message)
2708        .to_hex()
2709        .to_string())
2710}
2711
2712fn write_toml_file<T: Serialize>(path: &Path, value: &T) -> Result<()> {
2713    let bytes =
2714        toml::to_string_pretty(value).map_err(|error| Error::ConfigSerialize(error.to_string()))?;
2715    if let Some(parent) = path.parent() {
2716        std::fs::create_dir_all(parent).map_err(|source| Error::IoPath {
2717            path: parent.to_path_buf(),
2718            source,
2719        })?;
2720    }
2721
2722    let temp_path = path.with_extension(format!("tmp-{}", Uuid::new_v4()));
2723    std::fs::write(&temp_path, bytes).map_err(|source| Error::IoPath {
2724        path: temp_path.clone(),
2725        source,
2726    })?;
2727    std::fs::rename(&temp_path, path).map_err(|source| Error::IoPath {
2728        path: path.to_path_buf(),
2729        source,
2730    })?;
2731    Ok(())
2732}
2733
2734fn write_private_file(path: &Path, bytes: &[u8]) -> Result<()> {
2735    std::fs::write(path, bytes).map_err(|source| Error::IoPath {
2736        path: path.to_path_buf(),
2737        source,
2738    })?;
2739
2740    #[cfg(unix)]
2741    {
2742        use std::os::unix::fs::PermissionsExt;
2743
2744        let mut permissions = std::fs::metadata(path)
2745            .map_err(|source| Error::IoPath {
2746                path: path.to_path_buf(),
2747                source,
2748            })?
2749            .permissions();
2750        permissions.set_mode(0o600);
2751        std::fs::set_permissions(path, permissions).map_err(|source| Error::IoPath {
2752            path: path.to_path_buf(),
2753            source,
2754        })?;
2755    }
2756
2757    Ok(())
2758}
2759
2760#[cfg(test)]
2761mod tests {
2762    use super::*;
2763    use std::sync::{Arc, Mutex};
2764
2765    #[test]
2766    fn direct_peer_parses_socket_address() {
2767        let peer = DirectPeer::parse("127.0.0.1:53318").expect("address parses");
2768
2769        assert_eq!(peer.address().to_string(), "127.0.0.1:53318");
2770        assert_eq!(peer.expected_fingerprint(), None);
2771    }
2772
2773    #[test]
2774    fn direct_peer_accepts_expected_fingerprint() {
2775        let fingerprint = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
2776        let peer = DirectPeer::parse("127.0.0.1:53318")
2777            .expect("address parses")
2778            .with_expected_fingerprint(fingerprint)
2779            .expect("fingerprint parses");
2780
2781        assert_eq!(peer.expected_fingerprint(), Some(fingerprint));
2782    }
2783
2784    #[test]
2785    fn direct_peer_rejects_missing_port() {
2786        assert!(DirectPeer::parse("127.0.0.1").is_err());
2787    }
2788
2789    #[test]
2790    fn send_request_requires_at_least_one_path() {
2791        let peer = DirectPeer::parse("127.0.0.1:53318").expect("address parses");
2792
2793        assert!(SendRequest::new(peer, Vec::new()).is_err());
2794    }
2795
2796    #[test]
2797    fn psk_secret_is_redacted_in_debug_and_serialization() {
2798        let secret = PskSecret::new("do-not-print").expect("psk accepted");
2799
2800        assert_eq!(format!("{secret:?}"), "PskSecret(<redacted>)");
2801        assert_eq!(
2802            serde_json::to_string(&secret).expect("secret serializes"),
2803            r#""<redacted>""#
2804        );
2805
2806        let peer = DirectPeer::parse("127.0.0.1:53318").expect("address parses");
2807        let request = SendRequest::new(peer, vec![PathBuf::from("file.txt")])
2808            .expect("send request")
2809            .with_psk("do-not-print")
2810            .expect("psk accepted");
2811        assert!(!format!("{request:?}").contains("do-not-print"));
2812    }
2813
2814    #[test]
2815    fn validate_send_paths_rejects_empty_slice() {
2816        assert!(validate_send_paths(&[]).is_err());
2817    }
2818
2819    #[tokio::test]
2820    async fn manifest_walks_directory_and_serializes_entries() {
2821        let temp = tempfile::tempdir().expect("tempdir");
2822        let root = temp.path().join("bundle");
2823        let nested = root.join("nested");
2824        tokio::fs::create_dir_all(&nested).await.expect("dirs");
2825        tokio::fs::write(root.join("a.txt"), b"alpha")
2826            .await
2827            .expect("file a");
2828        tokio::fs::write(nested.join("b.txt"), b"beta")
2829            .await
2830            .expect("file b");
2831
2832        let manifest = build_manifest(&[root]).await.expect("manifest");
2833        let json = serde_json::to_string(&manifest).expect("manifest serializes");
2834        let decoded: TransferManifest = serde_json::from_str(&json).expect("manifest decodes");
2835
2836        assert_eq!(decoded.version, MANIFEST_VERSION);
2837        assert!(decoded.entries.iter().any(|entry| {
2838            entry.kind == ManifestEntryKind::Directory
2839                && entry.relative_path == Path::new("bundle/nested")
2840        }));
2841        assert!(decoded.entries.iter().any(|entry| {
2842            entry.kind == ManifestEntryKind::File
2843                && entry.relative_path == Path::new("bundle/nested/b.txt")
2844                && entry.size == 4
2845                && entry.blake3.is_some()
2846        }));
2847    }
2848
2849    #[test]
2850    fn safe_destination_path_rejects_unsafe_paths() {
2851        let dest = Path::new("/tmp/ferry-dest");
2852
2853        assert!(safe_destination_path(dest, Path::new("../escape.txt")).is_err());
2854        assert!(safe_destination_path(dest, Path::new("/absolute.txt")).is_err());
2855        assert!(safe_destination_path(dest, Path::new("nested/CON")).is_err());
2856        assert!(safe_destination_path(dest, Path::new("nested\\escape.txt")).is_err());
2857        assert!(safe_destination_path(dest, Path::new("nested/ok.txt")).is_ok());
2858    }
2859
2860    #[test]
2861    fn safe_destination_path_rejects_generated_escape_and_reserved_patterns() {
2862        let dest = Path::new("/tmp/ferry-dest");
2863        let unsafe_components = [
2864            "..",
2865            ".",
2866            "CON",
2867            "con.txt",
2868            "NUL",
2869            "COM1",
2870            "LPT9",
2871            "trailingspace ",
2872            "trailingdot.",
2873            "has:colon",
2874            "has\\backslash",
2875        ];
2876
2877        for component in unsafe_components {
2878            assert!(
2879                safe_destination_path(dest, Path::new(component)).is_err(),
2880                "{component} should be rejected as a top-level path"
2881            );
2882            if component != "." {
2883                assert!(
2884                    safe_destination_path(dest, Path::new("safe").join(component).as_path())
2885                        .is_err(),
2886                    "{component} should be rejected as a nested path"
2887                );
2888            }
2889        }
2890
2891        for component in ["alpha", "alpha-1", "alpha_1", "report.final.txt"] {
2892            let path = safe_destination_path(dest, Path::new("safe").join(component).as_path())
2893                .expect("safe generated path accepted");
2894            assert!(path.starts_with(dest));
2895        }
2896    }
2897
2898    #[tokio::test]
2899    async fn resume_decision_skips_existing_matching_file() {
2900        let temp = tempfile::tempdir().expect("tempdir");
2901        let source = temp.path().join("source.txt");
2902        let dest = temp.path().join("dest");
2903        tokio::fs::create_dir_all(&dest).await.expect("dest dir");
2904        tokio::fs::write(&source, b"same contents")
2905            .await
2906            .expect("source");
2907        tokio::fs::write(dest.join("source.txt"), b"same contents")
2908            .await
2909            .expect("dest file");
2910        let manifest = build_manifest(&[source]).await.expect("manifest");
2911        let entry = manifest.file_entries().next().expect("file entry");
2912
2913        let decision = decide_resume(&dest, entry, manifest.chunk_size)
2914            .await
2915            .expect("decision");
2916
2917        assert_eq!(decision, ResumeDecision::Skip);
2918    }
2919
2920    #[tokio::test]
2921    async fn resume_decision_returns_verified_chunk_offset() {
2922        let temp = tempfile::tempdir().expect("tempdir");
2923        let source = temp.path().join("large.bin");
2924        let dest = temp.path().join("dest");
2925        tokio::fs::create_dir_all(&dest).await.expect("dest dir");
2926        let bytes = vec![42; (DEFAULT_CHUNK_SIZE as usize * 2) + 128];
2927        tokio::fs::write(&source, &bytes).await.expect("source");
2928        tokio::fs::write(
2929            dest.join("large.bin"),
2930            &bytes[..DEFAULT_CHUNK_SIZE as usize + 99],
2931        )
2932        .await
2933        .expect("partial");
2934        let manifest = build_manifest(&[source]).await.expect("manifest");
2935        let entry = manifest.file_entries().next().expect("file entry");
2936
2937        let decision = decide_resume(&dest, entry, manifest.chunk_size)
2938            .await
2939            .expect("decision");
2940
2941        assert_eq!(decision, ResumeDecision::ResumeFrom(DEFAULT_CHUNK_SIZE));
2942    }
2943
2944    #[tokio::test]
2945    async fn resume_decision_rejects_existing_file_with_mismatched_contents() {
2946        let temp = tempfile::tempdir().expect("tempdir");
2947        let source = temp.path().join("source.txt");
2948        let dest = temp.path().join("dest");
2949        tokio::fs::create_dir_all(&dest).await.expect("dest dir");
2950        tokio::fs::write(&source, b"expected contents")
2951            .await
2952            .expect("source");
2953        tokio::fs::write(dest.join("source.txt"), b"different contents")
2954            .await
2955            .expect("conflicting dest file");
2956        let manifest = build_manifest(&[source]).await.expect("manifest");
2957        let entry = manifest.file_entries().next().expect("file entry");
2958
2959        let decision = decide_resume(&dest, entry, manifest.chunk_size)
2960            .await
2961            .expect("decision");
2962
2963        assert!(matches!(decision, ResumeDecision::Conflict(_)));
2964    }
2965
2966    #[tokio::test]
2967    async fn resume_decision_rejects_existing_file_larger_than_manifest_entry() {
2968        let temp = tempfile::tempdir().expect("tempdir");
2969        let source = temp.path().join("source.txt");
2970        let dest = temp.path().join("dest");
2971        tokio::fs::create_dir_all(&dest).await.expect("dest dir");
2972        tokio::fs::write(&source, b"small").await.expect("source");
2973        tokio::fs::write(dest.join("source.txt"), b"larger destination")
2974            .await
2975            .expect("larger dest file");
2976        let manifest = build_manifest(&[source]).await.expect("manifest");
2977        let entry = manifest.file_entries().next().expect("file entry");
2978
2979        let decision = decide_resume(&dest, entry, manifest.chunk_size)
2980            .await
2981            .expect("decision");
2982
2983        assert!(matches!(decision, ResumeDecision::Conflict(_)));
2984    }
2985
2986    #[test]
2987    fn identity_is_loaded_after_generation() {
2988        let temp = tempfile::tempdir().expect("tempdir");
2989        let generated =
2990            NativeIdentity::load_or_generate_in(temp.path()).expect("identity generated");
2991        let loaded = NativeIdentity::load_or_generate_in(temp.path()).expect("identity loaded");
2992
2993        assert_eq!(generated.fingerprint(), loaded.fingerprint());
2994    }
2995
2996    #[test]
2997    fn app_config_round_trips_toml() {
2998        let temp = tempfile::tempdir().expect("tempdir");
2999        let path = temp.path().join("config.toml");
3000        let config = AppConfig {
3001            alias: "desk".to_string(),
3002            ..AppConfig::default()
3003        };
3004
3005        config.save_to_path(&path).expect("config saved");
3006        let loaded = AppConfig::load_or_default_from(&path).expect("config loaded");
3007
3008        assert_eq!(loaded.alias, "desk");
3009        assert_eq!(loaded.listen_port, 53317);
3010        assert!(loaded.trust.require_fingerprint);
3011    }
3012
3013    #[test]
3014    fn app_config_redacts_psk_for_display_output() {
3015        let config = AppConfig {
3016            trust: TrustConfig {
3017                psk: "super-secret-psk".to_string(),
3018                ..TrustConfig::default()
3019            },
3020            ..AppConfig::default()
3021        };
3022
3023        let redacted = config.to_redacted_toml_string().expect("config serializes");
3024
3025        assert!(!redacted.contains("super-secret-psk"));
3026        assert!(redacted.contains(r#"psk = "<redacted>""#));
3027    }
3028
3029    #[test]
3030    fn daemon_config_defaults_from_app_config_and_round_trips_toml() {
3031        let temp = tempfile::tempdir().expect("tempdir");
3032        let path = temp.path().join("daemon.toml");
3033        let app_config = AppConfig {
3034            quic_port: 54444,
3035            download_dir: temp.path().join("downloads").display().to_string(),
3036            ..AppConfig::default()
3037        };
3038
3039        let defaulted =
3040            DaemonConfig::load_or_default_from(&path, &app_config).expect("daemon config");
3041        assert_eq!(
3042            defaulted.listen,
3043            SocketAddr::from(([0, 0, 0, 0], app_config.quic_port))
3044        );
3045        assert_eq!(defaulted.destination, temp.path().join("downloads"));
3046
3047        let config = DaemonConfig {
3048            listen: SocketAddr::from(([127, 0, 0, 1], 53318)),
3049            destination: temp.path().join("daemon-dest"),
3050        };
3051        config.save_to_path(&path).expect("daemon config saved");
3052        let loaded =
3053            DaemonConfig::load_or_default_from(&path, &app_config).expect("daemon config loaded");
3054
3055        assert_eq!(loaded, config);
3056    }
3057
3058    #[test]
3059    fn trust_store_load_save_and_forget_round_trip() {
3060        let temp = tempfile::tempdir().expect("tempdir");
3061        let path = temp.path().join("known_peers.toml");
3062        let fingerprint = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
3063        let mut store = TrustStore::default();
3064
3065        store
3066            .trust_fingerprint(fingerprint)
3067            .expect("fingerprint trusted");
3068        store.save_to_path(&path).expect("trust store saved");
3069        let mut loaded = TrustStore::load_or_default_from(&path).expect("trust store loaded");
3070
3071        assert_eq!(loaded.records().count(), 1);
3072        assert_eq!(loaded.peers[fingerprint].trust_state, TrustState::Trusted);
3073        assert!(loaded.forget(fingerprint));
3074        assert_eq!(loaded.records().count(), 0);
3075    }
3076
3077    #[test]
3078    fn trust_store_rejects_short_fingerprint_without_discovery_lookup() {
3079        let mut store = TrustStore::default();
3080
3081        assert!(store.trust_fingerprint("9a4f2c").is_err());
3082    }
3083
3084    #[test]
3085    fn trust_store_pins_direct_address_to_fingerprint() {
3086        let fingerprint = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
3087        let address = SocketAddr::from(([192, 168, 1, 42], 53318));
3088        let mut store = TrustStore::default();
3089
3090        store
3091            .trust_direct_address(fingerprint, address)
3092            .expect("direct address trusted");
3093
3094        assert!(store.is_trusted_fingerprint(fingerprint));
3095        assert_eq!(
3096            store.trusted_fingerprint_for_address(address),
3097            Some(fingerprint)
3098        );
3099        assert!(store.peers[fingerprint].addresses.contains(&address));
3100        assert!(store.peers[fingerprint].transports.contains("quic"));
3101        assert_eq!(store.peers[fingerprint].trust_state, TrustState::Trusted);
3102    }
3103
3104    #[test]
3105    fn transfer_events_serialize_with_stable_event_names() {
3106        let event = TransferEvent::Progress {
3107            direction: TransferDirection::Send,
3108            file_name: "bundle/a.txt".to_string(),
3109            bytes_done: 5,
3110            bytes_total: 9,
3111        };
3112
3113        let json = serde_json::to_value(&event).expect("event serializes");
3114
3115        assert_eq!(json["event"], "progress");
3116        assert_eq!(json["direction"], "send");
3117        assert_eq!(json["file_name"], "bundle/a.txt");
3118        assert_eq!(json["bytes_done"], 5);
3119        assert_eq!(json["bytes_total"], 9);
3120    }
3121
3122    #[test]
3123    fn direct_protocol_hello_has_stable_golden_json() {
3124        let hello = DirectProtocolHello {
3125            protocol_version: 1,
3126            min_protocol_version: 1,
3127            client_fingerprint: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
3128                .to_string(),
3129            psk: false,
3130        };
3131
3132        let json = serde_json::to_string(&hello).expect("hello serializes");
3133
3134        assert_eq!(
3135            json,
3136            r#"{"protocol_version":1,"min_protocol_version":1,"client_fingerprint":"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef","psk":false}"#
3137        );
3138    }
3139
3140    #[test]
3141    fn direct_protocol_response_has_stable_golden_json() {
3142        let response = DirectProtocolResponse::accept(1);
3143
3144        let json = serde_json::to_string(&response).expect("response serializes");
3145
3146        assert_eq!(
3147            json,
3148            r#"{"accepted":true,"protocol_version":1,"psk_challenge":null,"error":null}"#
3149        );
3150    }
3151
3152    #[test]
3153    fn direct_protocol_decodes_pre_psk_negotiation_frames() {
3154        let hello: DirectProtocolHello = serde_json::from_str(
3155            r#"{"protocol_version":1,"min_protocol_version":1,"client_fingerprint":"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}"#,
3156        )
3157        .expect("old hello decodes");
3158        assert!(!hello.psk);
3159
3160        let response: DirectProtocolResponse =
3161            serde_json::from_str(r#"{"accepted":true,"protocol_version":1,"error":null}"#)
3162                .expect("old response decodes");
3163        assert_eq!(response, DirectProtocolResponse::accept(1));
3164    }
3165
3166    #[test]
3167    fn direct_protocol_negotiates_supported_overlap() {
3168        let hello = DirectProtocolHello {
3169            protocol_version: 3,
3170            min_protocol_version: 1,
3171            client_fingerprint: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
3172                .to_string(),
3173            psk: false,
3174        };
3175
3176        let response = negotiate_direct_protocol(&hello, None);
3177
3178        assert_eq!(response, DirectProtocolResponse::accept(1));
3179    }
3180
3181    #[test]
3182    fn direct_protocol_rejects_incompatible_versions() {
3183        let too_new = DirectProtocolHello {
3184            protocol_version: 3,
3185            min_protocol_version: 2,
3186            client_fingerprint: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
3187                .to_string(),
3188            psk: false,
3189        };
3190        let too_old = DirectProtocolHello {
3191            protocol_version: 0,
3192            min_protocol_version: 0,
3193            client_fingerprint: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
3194                .to_string(),
3195            psk: false,
3196        };
3197
3198        assert!(!negotiate_direct_protocol(&too_new, None).accepted);
3199        assert!(!negotiate_direct_protocol(&too_old, None).accepted);
3200    }
3201
3202    #[test]
3203    fn direct_protocol_requires_matching_psk_mode() {
3204        let no_psk = DirectProtocolHello {
3205            protocol_version: 1,
3206            min_protocol_version: 1,
3207            client_fingerprint: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
3208                .to_string(),
3209            psk: false,
3210        };
3211        let with_psk = DirectProtocolHello {
3212            psk: true,
3213            ..no_psk.clone()
3214        };
3215
3216        assert!(!negotiate_direct_protocol(&no_psk, Some("secret")).accepted);
3217        assert!(!negotiate_direct_protocol(&with_psk, None).accepted);
3218
3219        let accepted = negotiate_direct_protocol(&with_psk, Some("secret"));
3220        assert!(accepted.accepted);
3221        assert!(accepted.psk_challenge.is_some());
3222    }
3223
3224    #[test]
3225    fn transfer_manifest_has_stable_golden_json() {
3226        let manifest = TransferManifest {
3227            version: MANIFEST_VERSION,
3228            session_id: Uuid::parse_str("00000000-0000-0000-0000-000000000001")
3229                .expect("uuid parses"),
3230            chunk_size: DEFAULT_CHUNK_SIZE,
3231            entries: vec![ManifestEntry {
3232                relative_path: PathBuf::from("bundle/a.txt"),
3233                kind: ManifestEntryKind::File,
3234                size: 5,
3235                blake3: Some(
3236                    "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".to_string(),
3237                ),
3238                chunks: vec![
3239                    "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".to_string(),
3240                ],
3241                unix_mode: Some(0o100644),
3242                modified_unix_ms: Some(1_700_000_000_000),
3243            }],
3244        };
3245
3246        let json = serde_json::to_string(&manifest).expect("manifest serializes");
3247
3248        assert_eq!(
3249            json,
3250            r#"{"version":1,"session_id":"00000000-0000-0000-0000-000000000001","chunk_size":1048576,"entries":[{"relative_path":"bundle/a.txt","kind":"file","size":5,"blake3":"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef","chunks":["abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"],"unix_mode":33188,"modified_unix_ms":1700000000000}]}"#
3251        );
3252    }
3253
3254    #[test]
3255    fn peer_registry_merges_observations_by_fingerprint() {
3256        let mut registry = PeerRegistry::new();
3257        let fingerprint = "abcdef1234567890";
3258        let first = PeerObservation::new(
3259            fingerprint,
3260            SocketAddr::from(([192, 168, 1, 10], 53318)),
3261            100,
3262        )
3263        .with_alias("desk")
3264        .with_hostname("desk.local")
3265        .with_transport("quic");
3266        let second = PeerObservation::new(
3267            fingerprint,
3268            SocketAddr::from(([192, 168, 1, 11], 53318)),
3269            200,
3270        )
3271        .with_alias("workstation")
3272        .with_transport("quic");
3273
3274        registry.observe(first).expect("first observation");
3275        registry.observe(second).expect("second observation");
3276        let record = registry
3277            .get_by_fingerprint(fingerprint)
3278            .expect("record by fingerprint");
3279
3280        assert_eq!(registry.records().count(), 1);
3281        assert!(record.aliases.contains("desk"));
3282        assert!(record.aliases.contains("workstation"));
3283        assert!(record.hostnames.contains("desk.local"));
3284        assert_eq!(record.addresses.len(), 2);
3285        assert_eq!(record.first_seen_unix_ms, 100);
3286        assert_eq!(record.last_seen_unix_ms, 200);
3287    }
3288
3289    #[test]
3290    fn peer_registry_looks_up_unique_fingerprint_prefix_alias_and_hostname() {
3291        let mut registry = PeerRegistry::new();
3292        registry
3293            .observe(
3294                PeerObservation::new(
3295                    "abcdef1234567890",
3296                    SocketAddr::from(([192, 168, 1, 10], 53318)),
3297                    100,
3298                )
3299                .with_alias("desk")
3300                .with_hostname("desk.local"),
3301            )
3302            .expect("first observation");
3303        registry
3304            .observe(
3305                PeerObservation::new(
3306                    "123456abcdef7890",
3307                    SocketAddr::from(([192, 168, 1, 20], 53318)),
3308                    100,
3309                )
3310                .with_alias("laptop"),
3311            )
3312            .expect("second observation");
3313
3314        assert_eq!(
3315            registry
3316                .lookup("abcdef")
3317                .map(|record| record.fingerprint.as_str()),
3318            Some("abcdef1234567890")
3319        );
3320        assert_eq!(
3321            registry
3322                .lookup("desk")
3323                .map(|record| record.fingerprint.as_str()),
3324            Some("abcdef1234567890")
3325        );
3326        assert_eq!(
3327            registry
3328                .lookup("desk.local")
3329                .map(|record| record.fingerprint.as_str()),
3330            Some("abcdef1234567890")
3331        );
3332        assert!(registry.lookup("missing").is_none());
3333    }
3334
3335    #[test]
3336    fn peer_registry_rejects_ambiguous_lookup_hints() {
3337        let mut registry = PeerRegistry::new();
3338        registry
3339            .observe(
3340                PeerObservation::new(
3341                    "abcdef1234567890",
3342                    SocketAddr::from(([192, 168, 1, 10], 53318)),
3343                    100,
3344                )
3345                .with_alias("desk"),
3346            )
3347            .expect("first observation");
3348        registry
3349            .observe(
3350                PeerObservation::new(
3351                    "abcdef9999999999",
3352                    SocketAddr::from(([192, 168, 1, 11], 53318)),
3353                    100,
3354                )
3355                .with_alias("desk"),
3356            )
3357            .expect("second observation");
3358
3359        assert!(registry.lookup("abcdef").is_none());
3360        assert!(registry.lookup("desk").is_none());
3361        assert_eq!(
3362            registry
3363                .lookup("abcdef1234567890")
3364                .map(|record| record.fingerprint.as_str()),
3365            Some("abcdef1234567890")
3366        );
3367        match registry.lookup_detail("desk") {
3368            PeerLookup::Ambiguous(records) => assert_eq!(records.len(), 2),
3369            other => panic!("expected ambiguous duplicate-alias lookup, got {other:?}"),
3370        }
3371        assert!(matches!(
3372            registry.lookup_detail("missing"),
3373            PeerLookup::Missing
3374        ));
3375    }
3376
3377    #[test]
3378    fn native_announcement_builds_expected_txt_properties() {
3379        let announcement = NativeAnnouncement {
3380            alias: "Stephen MBP".to_string(),
3381            fingerprint: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
3382                .to_string(),
3383            quic_port: 53318,
3384            listen_port: Some(53317),
3385        };
3386
3387        let service = announcement.service_info().expect("service info");
3388
3389        assert_eq!(service.get_type(), NATIVE_SERVICE_TYPE);
3390        assert!(
3391            service
3392                .get_fullname()
3393                .starts_with("stephen-mbp-0123456789ab.")
3394        );
3395        assert_eq!(service.get_property_val_str("pv"), Some("1"));
3396        assert_eq!(service.get_property_val_str("minpv"), Some("1"));
3397        assert_eq!(
3398            service.get_property_val_str("fp"),
3399            Some("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")
3400        );
3401        assert_eq!(service.get_property_val_str("alias"), Some("Stephen MBP"));
3402        assert_eq!(service.get_property_val_str("transports"), Some("quic"));
3403        assert_eq!(service.get_property_val_str("quic_port"), Some("53318"));
3404        assert_eq!(service.get_property_val_str("listen_port"), Some("53317"));
3405    }
3406
3407    #[test]
3408    fn resolved_native_service_merges_into_registry() {
3409        let properties = [
3410            ("pv", "1"),
3411            ("minpv", "1"),
3412            (
3413                "fp",
3414                "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
3415            ),
3416            ("alias", "desk"),
3417            ("transports", "quic"),
3418            ("quic_port", "53318"),
3419        ];
3420        let service = ServiceInfo::new(
3421            NATIVE_SERVICE_TYPE,
3422            "desk-0123456789ab",
3423            "desk.local.",
3424            "192.168.1.42",
3425            53318,
3426            &properties[..],
3427        )
3428        .expect("service info")
3429        .as_resolved_service();
3430        let mut registry = PeerRegistry::new();
3431
3432        observe_resolved_service(&mut registry, &service).expect("observation");
3433
3434        let record = registry.lookup("desk").expect("record by alias");
3435        assert_eq!(
3436            record.fingerprint,
3437            "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
3438        );
3439        assert_eq!(
3440            record.preferred_quic_address(),
3441            Some(SocketAddr::from(([192, 168, 1, 42], 53318)))
3442        );
3443    }
3444
3445    #[test]
3446    fn resolved_native_service_ignores_incompatible_protocol_ranges() {
3447        let properties = [
3448            ("pv", "3"),
3449            ("minpv", "2"),
3450            (
3451                "fp",
3452                "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
3453            ),
3454            ("alias", "desk"),
3455            ("transports", "quic"),
3456            ("quic_port", "53318"),
3457        ];
3458        let service = ServiceInfo::new(
3459            NATIVE_SERVICE_TYPE,
3460            "desk-0123456789ab",
3461            "desk.local.",
3462            "192.168.1.42",
3463            53318,
3464            &properties[..],
3465        )
3466        .expect("service info")
3467        .as_resolved_service();
3468        let mut registry = PeerRegistry::new();
3469
3470        observe_resolved_service(&mut registry, &service).expect("observation");
3471
3472        assert_eq!(registry.records().count(), 0);
3473    }
3474
3475    #[tokio::test]
3476    async fn direct_quic_loopback_sends_one_file() {
3477        let source_dir = tempfile::tempdir().expect("source tempdir");
3478        let dest_dir = tempfile::tempdir().expect("dest tempdir");
3479        let identity_dir = tempfile::tempdir().expect("identity tempdir");
3480        let file_path = source_dir.path().join("hello.txt");
3481        tokio::fs::write(&file_path, b"hello from ferry")
3482            .await
3483            .expect("source file written");
3484
3485        let identity =
3486            NativeIdentity::load_or_generate_in(identity_dir.path()).expect("identity generated");
3487        let recv_identity = identity.clone();
3488        let reserved_socket =
3489            std::net::UdpSocket::bind(SocketAddr::from(([127, 0, 0, 1], 0))).expect("udp bind");
3490        let recv_addr = reserved_socket.local_addr().expect("local addr");
3491        drop(reserved_socket);
3492        let receive_progress = Arc::new(Mutex::new(Vec::new()));
3493        let receive_progress_log = receive_progress.clone();
3494        let dest_path = dest_dir.path().to_path_buf();
3495        let server = tokio::spawn(async move {
3496            receive_direct_file(
3497                &ReceiveRequest::new(recv_addr),
3498                dest_path,
3499                &recv_identity,
3500                |event| {
3501                    receive_progress_log
3502                        .lock()
3503                        .expect("progress lock")
3504                        .push(event);
3505                },
3506            )
3507            .await
3508        });
3509
3510        tokio::time::sleep(Duration::from_millis(100)).await;
3511
3512        let peer = DirectPeer::parse(&recv_addr.to_string()).expect("peer parses");
3513        let send_request = SendRequest::new(peer, vec![file_path]).expect("send request is valid");
3514        let send_progress = Arc::new(Mutex::new(Vec::new()));
3515        let send_progress_log = send_progress.clone();
3516        let send_summary = send_direct_file(&send_request, &identity, |event| {
3517            send_progress_log.lock().expect("progress lock").push(event);
3518        })
3519        .await
3520        .expect("file sent");
3521        let receive_summary = server.await.expect("server joined").expect("file received");
3522
3523        let received = tokio::fs::read(dest_dir.path().join("hello.txt"))
3524            .await
3525            .expect("received file readable");
3526        assert_eq!(received, b"hello from ferry");
3527        assert_eq!(send_summary.bytes, receive_summary.bytes);
3528        assert_eq!(send_summary.blake3, receive_summary.blake3);
3529        let send_progress = send_progress.lock().expect("progress lock");
3530        let receive_progress = receive_progress.lock().expect("progress lock");
3531        assert!(matches!(
3532            send_progress.first(),
3533            Some(TransferEvent::SessionStarted {
3534                direction: TransferDirection::Send,
3535                ..
3536            })
3537        ));
3538        assert!(
3539            send_progress
3540                .iter()
3541                .any(|event| matches!(event, TransferEvent::Progress { .. }))
3542        );
3543        assert!(
3544            send_progress
3545                .iter()
3546                .any(|event| matches!(event, TransferEvent::SessionFinished { .. }))
3547        );
3548        assert!(matches!(
3549            receive_progress.first(),
3550            Some(TransferEvent::SessionStarted {
3551                direction: TransferDirection::Receive,
3552                ..
3553            })
3554        ));
3555        assert!(
3556            receive_progress
3557                .iter()
3558                .any(|event| matches!(event, TransferEvent::Progress { .. }))
3559        );
3560        assert!(
3561            receive_progress
3562                .iter()
3563                .any(|event| matches!(event, TransferEvent::SessionFinished { .. }))
3564        );
3565    }
3566
3567    #[tokio::test]
3568    async fn direct_transfer_accepts_expected_receiver_fingerprint() {
3569        let source_dir = tempfile::tempdir().expect("source tempdir");
3570        let dest_dir = tempfile::tempdir().expect("dest tempdir");
3571        let sender_identity_dir = tempfile::tempdir().expect("sender identity tempdir");
3572        let receiver_identity_dir = tempfile::tempdir().expect("receiver identity tempdir");
3573        let file_path = source_dir.path().join("hello.txt");
3574        tokio::fs::write(&file_path, b"hello from ferry")
3575            .await
3576            .expect("source file written");
3577
3578        let sender_identity = NativeIdentity::load_or_generate_in(sender_identity_dir.path())
3579            .expect("sender identity");
3580        let receiver_identity = NativeIdentity::load_or_generate_in(receiver_identity_dir.path())
3581            .expect("receiver identity");
3582        let expected_fingerprint = receiver_identity.fingerprint().to_string();
3583        let reserved_socket =
3584            std::net::UdpSocket::bind(SocketAddr::from(([127, 0, 0, 1], 0))).expect("udp bind");
3585        let recv_addr = reserved_socket.local_addr().expect("local addr");
3586        drop(reserved_socket);
3587        let dest_path = dest_dir.path().to_path_buf();
3588        let server = tokio::spawn(async move {
3589            receive_direct_file(
3590                &ReceiveRequest::new(recv_addr),
3591                dest_path,
3592                &receiver_identity,
3593                |_| {},
3594            )
3595            .await
3596        });
3597
3598        tokio::time::sleep(Duration::from_millis(100)).await;
3599
3600        let peer = DirectPeer::from_address(recv_addr)
3601            .with_expected_fingerprint(expected_fingerprint)
3602            .expect("expected fingerprint accepted");
3603        let send_request = SendRequest::new(peer, vec![file_path]).expect("send request is valid");
3604        let send_summary = send_direct_file(&send_request, &sender_identity, |_| {})
3605            .await
3606            .expect("file sent");
3607        let receive_summary = server.await.expect("server joined").expect("file received");
3608
3609        let received = tokio::fs::read(dest_dir.path().join("hello.txt"))
3610            .await
3611            .expect("received file readable");
3612        assert_eq!(received, b"hello from ferry");
3613        assert_eq!(send_summary.bytes, receive_summary.bytes);
3614        assert_eq!(send_summary.blake3, receive_summary.blake3);
3615    }
3616
3617    #[tokio::test]
3618    async fn direct_transfer_confirms_unpinned_receiver_before_payload() {
3619        let source_dir = tempfile::tempdir().expect("source tempdir");
3620        let dest_dir = tempfile::tempdir().expect("dest tempdir");
3621        let sender_identity_dir = tempfile::tempdir().expect("sender identity tempdir");
3622        let receiver_identity_dir = tempfile::tempdir().expect("receiver identity tempdir");
3623        let file_path = source_dir.path().join("hello.txt");
3624        tokio::fs::write(&file_path, b"hello from ferry")
3625            .await
3626            .expect("source file written");
3627
3628        let sender_identity = NativeIdentity::load_or_generate_in(sender_identity_dir.path())
3629            .expect("sender identity");
3630        let receiver_identity = NativeIdentity::load_or_generate_in(receiver_identity_dir.path())
3631            .expect("receiver identity");
3632        let expected_fingerprint = receiver_identity.fingerprint().to_string();
3633        let reserved_socket =
3634            std::net::UdpSocket::bind(SocketAddr::from(([127, 0, 0, 1], 0))).expect("udp bind");
3635        let recv_addr = reserved_socket.local_addr().expect("local addr");
3636        drop(reserved_socket);
3637        let dest_path = dest_dir.path().to_path_buf();
3638        let server = tokio::spawn(async move {
3639            receive_direct_file(
3640                &ReceiveRequest::new(recv_addr),
3641                dest_path,
3642                &receiver_identity,
3643                |_| {},
3644            )
3645            .await
3646        });
3647
3648        tokio::time::sleep(Duration::from_millis(100)).await;
3649
3650        let peer = DirectPeer::from_address(recv_addr);
3651        let send_request = SendRequest::new(peer, vec![file_path]).expect("send request is valid");
3652        let callback_seen = Arc::new(AtomicBool::new(false));
3653        let callback_seen_send = callback_seen.clone();
3654        let send_summary = send_direct_file_with_control_and_trust(
3655            &send_request,
3656            &sender_identity,
3657            TransferControl::new(),
3658            |_| {},
3659            |fingerprint| {
3660                callback_seen_send.store(true, Ordering::SeqCst);
3661                assert_eq!(fingerprint, expected_fingerprint);
3662                Ok(())
3663            },
3664        )
3665        .await
3666        .expect("file sent after trust callback");
3667        let receive_summary = server.await.expect("server joined").expect("file received");
3668
3669        assert!(callback_seen.load(Ordering::SeqCst));
3670        assert_eq!(send_summary.bytes, receive_summary.bytes);
3671        assert_eq!(send_summary.blake3, receive_summary.blake3);
3672    }
3673
3674    #[tokio::test]
3675    async fn direct_transfer_rejects_unexpected_receiver_fingerprint_before_payload() {
3676        let source_dir = tempfile::tempdir().expect("source tempdir");
3677        let dest_dir = tempfile::tempdir().expect("dest tempdir");
3678        let sender_identity_dir = tempfile::tempdir().expect("sender identity tempdir");
3679        let receiver_identity_dir = tempfile::tempdir().expect("receiver identity tempdir");
3680        let other_identity_dir = tempfile::tempdir().expect("other identity tempdir");
3681        let file_path = source_dir.path().join("hello.txt");
3682        tokio::fs::write(&file_path, b"hello from ferry")
3683            .await
3684            .expect("source file written");
3685
3686        let sender_identity = NativeIdentity::load_or_generate_in(sender_identity_dir.path())
3687            .expect("sender identity");
3688        let receiver_identity = NativeIdentity::load_or_generate_in(receiver_identity_dir.path())
3689            .expect("receiver identity");
3690        let other_identity =
3691            NativeIdentity::load_or_generate_in(other_identity_dir.path()).expect("other identity");
3692        let reserved_socket =
3693            std::net::UdpSocket::bind(SocketAddr::from(([127, 0, 0, 1], 0))).expect("udp bind");
3694        let recv_addr = reserved_socket.local_addr().expect("local addr");
3695        drop(reserved_socket);
3696        let dest_path = dest_dir.path().to_path_buf();
3697        let server = tokio::spawn(async move {
3698            receive_direct_file(
3699                &ReceiveRequest::new(recv_addr),
3700                dest_path,
3701                &receiver_identity,
3702                |_| {},
3703            )
3704            .await
3705        });
3706
3707        tokio::time::sleep(Duration::from_millis(100)).await;
3708
3709        let peer = DirectPeer::from_address(recv_addr)
3710            .with_expected_fingerprint(other_identity.fingerprint().to_string())
3711            .expect("expected fingerprint accepted");
3712        let send_request = SendRequest::new(peer, vec![file_path]).expect("send request is valid");
3713        let error = send_direct_file(&send_request, &sender_identity, |_| {})
3714            .await
3715            .expect_err("fingerprint mismatch should reject send");
3716
3717        assert!(matches!(error, Error::PeerFingerprintMismatch { .. }));
3718        let server_error = server
3719            .await
3720            .expect("server joined")
3721            .expect_err("server closed");
3722        assert!(matches!(
3723            server_error,
3724            Error::Connection(_) | Error::NoIncomingConnection
3725        ));
3726        assert!(
3727            !tokio::fs::try_exists(dest_dir.path().join("hello.txt"))
3728                .await
3729                .expect("destination checked")
3730        );
3731    }
3732
3733    #[tokio::test]
3734    async fn direct_transfer_accepts_matching_psk_before_payload() {
3735        let source_dir = tempfile::tempdir().expect("source tempdir");
3736        let dest_dir = tempfile::tempdir().expect("dest tempdir");
3737        let identity_dir = tempfile::tempdir().expect("identity tempdir");
3738        let file_path = source_dir.path().join("hello.txt");
3739        tokio::fs::write(&file_path, b"hello from ferry")
3740            .await
3741            .expect("source file written");
3742
3743        let identity =
3744            NativeIdentity::load_or_generate_in(identity_dir.path()).expect("identity generated");
3745        let recv_identity = identity.clone();
3746        let reserved_socket =
3747            std::net::UdpSocket::bind(SocketAddr::from(([127, 0, 0, 1], 0))).expect("udp bind");
3748        let recv_addr = reserved_socket.local_addr().expect("local addr");
3749        drop(reserved_socket);
3750        let dest_path = dest_dir.path().to_path_buf();
3751        let receive_request = ReceiveRequest::new(recv_addr)
3752            .with_psk("correct horse battery staple")
3753            .expect("receiver psk accepted");
3754        let server = tokio::spawn(async move {
3755            receive_direct_file(&receive_request, dest_path, &recv_identity, |_| {}).await
3756        });
3757
3758        tokio::time::sleep(Duration::from_millis(100)).await;
3759
3760        let peer = DirectPeer::parse(&recv_addr.to_string()).expect("peer parses");
3761        let send_request = SendRequest::new(peer, vec![file_path])
3762            .expect("send request is valid")
3763            .with_psk("correct horse battery staple")
3764            .expect("sender psk accepted");
3765        let send_summary = send_direct_file(&send_request, &identity, |_| {})
3766            .await
3767            .expect("file sent");
3768        let receive_summary = server.await.expect("server joined").expect("file received");
3769
3770        let received = tokio::fs::read(dest_dir.path().join("hello.txt"))
3771            .await
3772            .expect("received file readable");
3773        assert_eq!(received, b"hello from ferry");
3774        assert_eq!(send_summary.bytes, receive_summary.bytes);
3775    }
3776
3777    #[tokio::test]
3778    async fn direct_transfer_rejects_missing_psk_before_payload() {
3779        let source_dir = tempfile::tempdir().expect("source tempdir");
3780        let dest_dir = tempfile::tempdir().expect("dest tempdir");
3781        let identity_dir = tempfile::tempdir().expect("identity tempdir");
3782        let file_path = source_dir.path().join("hello.txt");
3783        tokio::fs::write(&file_path, b"hello from ferry")
3784            .await
3785            .expect("source file written");
3786
3787        let identity =
3788            NativeIdentity::load_or_generate_in(identity_dir.path()).expect("identity generated");
3789        let recv_identity = identity.clone();
3790        let reserved_socket =
3791            std::net::UdpSocket::bind(SocketAddr::from(([127, 0, 0, 1], 0))).expect("udp bind");
3792        let recv_addr = reserved_socket.local_addr().expect("local addr");
3793        drop(reserved_socket);
3794        let dest_path = dest_dir.path().to_path_buf();
3795        let receive_request = ReceiveRequest::new(recv_addr)
3796            .with_psk("receiver secret")
3797            .expect("receiver psk accepted");
3798        let server = tokio::spawn(async move {
3799            receive_direct_file(&receive_request, dest_path, &recv_identity, |_| {}).await
3800        });
3801
3802        tokio::time::sleep(Duration::from_millis(100)).await;
3803
3804        let peer = DirectPeer::parse(&recv_addr.to_string()).expect("peer parses");
3805        let send_request = SendRequest::new(peer, vec![file_path]).expect("send request is valid");
3806        let error = send_direct_file(&send_request, &identity, |_| {})
3807            .await
3808            .expect_err("missing psk should reject send");
3809
3810        assert!(matches!(error, Error::Protocol(_)));
3811        let _ = server.await.expect("server joined");
3812        assert!(
3813            !tokio::fs::try_exists(dest_dir.path().join("hello.txt"))
3814                .await
3815                .expect("destination checked")
3816        );
3817    }
3818
3819    #[tokio::test]
3820    async fn direct_transfer_rejects_wrong_psk_before_payload() {
3821        let source_dir = tempfile::tempdir().expect("source tempdir");
3822        let dest_dir = tempfile::tempdir().expect("dest tempdir");
3823        let identity_dir = tempfile::tempdir().expect("identity tempdir");
3824        let file_path = source_dir.path().join("hello.txt");
3825        tokio::fs::write(&file_path, b"hello from ferry")
3826            .await
3827            .expect("source file written");
3828
3829        let identity =
3830            NativeIdentity::load_or_generate_in(identity_dir.path()).expect("identity generated");
3831        let recv_identity = identity.clone();
3832        let reserved_socket =
3833            std::net::UdpSocket::bind(SocketAddr::from(([127, 0, 0, 1], 0))).expect("udp bind");
3834        let recv_addr = reserved_socket.local_addr().expect("local addr");
3835        drop(reserved_socket);
3836        let dest_path = dest_dir.path().to_path_buf();
3837        let receive_request = ReceiveRequest::new(recv_addr)
3838            .with_psk("receiver secret")
3839            .expect("receiver psk accepted");
3840        let server = tokio::spawn(async move {
3841            receive_direct_file(&receive_request, dest_path, &recv_identity, |_| {}).await
3842        });
3843
3844        tokio::time::sleep(Duration::from_millis(100)).await;
3845
3846        let peer = DirectPeer::parse(&recv_addr.to_string()).expect("peer parses");
3847        let send_request = SendRequest::new(peer, vec![file_path])
3848            .expect("send request is valid")
3849            .with_psk("wrong secret")
3850            .expect("sender psk accepted");
3851        let error = send_direct_file(&send_request, &identity, |_| {})
3852            .await
3853            .expect_err("wrong psk should reject send");
3854
3855        assert!(matches!(error, Error::Authentication(_)));
3856        assert!(!error.to_string().contains("wrong secret"));
3857        assert!(!error.to_string().contains("receiver secret"));
3858        let server_error = server
3859            .await
3860            .expect("server joined")
3861            .expect_err("server should reject wrong psk");
3862        assert!(matches!(
3863            server_error,
3864            Error::Authentication(_) | Error::Write(_)
3865        ));
3866        assert!(
3867            !tokio::fs::try_exists(dest_dir.path().join("hello.txt"))
3868                .await
3869                .expect("destination checked")
3870        );
3871    }
3872
3873    #[tokio::test]
3874    async fn direct_quic_loopback_sends_directory_and_resumes_partial_file() {
3875        let source_dir = tempfile::tempdir().expect("source tempdir");
3876        let dest_dir = tempfile::tempdir().expect("dest tempdir");
3877        let identity_dir = tempfile::tempdir().expect("identity tempdir");
3878        let bundle = source_dir.path().join("bundle");
3879        let nested = bundle.join("nested");
3880        tokio::fs::create_dir_all(&nested)
3881            .await
3882            .expect("source dirs");
3883        tokio::fs::write(nested.join("small.txt"), b"small")
3884            .await
3885            .expect("small file");
3886        let large_bytes = vec![7; (DEFAULT_CHUNK_SIZE as usize * 2) + 17];
3887        tokio::fs::write(bundle.join("large.bin"), &large_bytes)
3888            .await
3889            .expect("large file");
3890
3891        let dest_bundle = dest_dir.path().join("bundle");
3892        tokio::fs::create_dir_all(&dest_bundle)
3893            .await
3894            .expect("dest bundle");
3895        tokio::fs::write(
3896            dest_bundle.join("large.bin"),
3897            &large_bytes[..DEFAULT_CHUNK_SIZE as usize + 5],
3898        )
3899        .await
3900        .expect("partial large");
3901
3902        let identity =
3903            NativeIdentity::load_or_generate_in(identity_dir.path()).expect("identity generated");
3904        let recv_identity = identity.clone();
3905        let reserved_socket =
3906            std::net::UdpSocket::bind(SocketAddr::from(([127, 0, 0, 1], 0))).expect("udp bind");
3907        let recv_addr = reserved_socket.local_addr().expect("local addr");
3908        drop(reserved_socket);
3909        let dest_path = dest_dir.path().to_path_buf();
3910        let server = tokio::spawn(async move {
3911            receive_direct_file(
3912                &ReceiveRequest::new(recv_addr),
3913                dest_path,
3914                &recv_identity,
3915                |_| {},
3916            )
3917            .await
3918        });
3919
3920        tokio::time::sleep(Duration::from_millis(100)).await;
3921
3922        let peer = DirectPeer::parse(&recv_addr.to_string()).expect("peer parses");
3923        let send_request = SendRequest::new(peer, vec![bundle]).expect("send request is valid");
3924        let send_summary = send_direct_file(&send_request, &identity, |_| {})
3925            .await
3926            .expect("directory sent");
3927        let receive_summary = server
3928            .await
3929            .expect("server joined")
3930            .expect("directory received");
3931
3932        let received_large = tokio::fs::read(dest_bundle.join("large.bin"))
3933            .await
3934            .expect("large file readable");
3935        let received_small = tokio::fs::read(dest_bundle.join("nested/small.txt"))
3936            .await
3937            .expect("small file readable");
3938        assert_eq!(received_large, large_bytes);
3939        assert_eq!(received_small, b"small");
3940        assert_eq!(send_summary.bytes, receive_summary.bytes);
3941        assert!(
3942            receive_summary
3943                .files
3944                .iter()
3945                .any(|file| file.status == TransferFileStatus::Resumed)
3946        );
3947    }
3948
3949    #[tokio::test]
3950    async fn direct_quic_loopback_cancels_send_and_does_not_finalize_partial_file() {
3951        let source_dir = tempfile::tempdir().expect("source tempdir");
3952        let dest_dir = tempfile::tempdir().expect("dest tempdir");
3953        let identity_dir = tempfile::tempdir().expect("identity tempdir");
3954        let file_path = source_dir.path().join("payload.bin");
3955        tokio::fs::write(&file_path, vec![3; IO_BUFFER_SIZE * 64])
3956            .await
3957            .expect("source file written");
3958
3959        let identity =
3960            NativeIdentity::load_or_generate_in(identity_dir.path()).expect("identity generated");
3961        let recv_identity = identity.clone();
3962        let reserved_socket =
3963            std::net::UdpSocket::bind(SocketAddr::from(([127, 0, 0, 1], 0))).expect("udp bind");
3964        let recv_addr = reserved_socket.local_addr().expect("local addr");
3965        drop(reserved_socket);
3966
3967        let dest_path = dest_dir.path().to_path_buf();
3968        let server = tokio::spawn(async move {
3969            receive_direct_file(
3970                &ReceiveRequest::new(recv_addr),
3971                dest_path,
3972                &recv_identity,
3973                |_| {},
3974            )
3975            .await
3976        });
3977
3978        tokio::time::sleep(Duration::from_millis(100)).await;
3979
3980        let peer = DirectPeer::parse(&recv_addr.to_string()).expect("peer parses");
3981        let send_request =
3982            SendRequest::new(peer, vec![file_path.clone()]).expect("send request is valid");
3983        let send_control = TransferControl::new();
3984        let cancel_on_progress = send_control.clone();
3985        let send_events = Arc::new(Mutex::new(Vec::new()));
3986        let send_events_log = send_events.clone();
3987        let send_result =
3988            send_direct_file_with_control(&send_request, &identity, send_control, |event| {
3989                if matches!(event, TransferEvent::Progress { .. }) {
3990                    cancel_on_progress.cancel();
3991                }
3992                send_events_log.lock().expect("events lock").push(event);
3993            })
3994            .await;
3995
3996        assert!(matches!(send_result, Err(Error::TransferCancelled)));
3997
3998        let receive_result = tokio::time::timeout(Duration::from_secs(5), server)
3999            .await
4000            .expect("receiver should finish after sender cancellation")
4001            .expect("server joined");
4002        assert!(receive_result.is_err());
4003
4004        assert!(!dest_dir.path().join("payload.bin").exists());
4005        assert!(
4006            send_events
4007                .lock()
4008                .expect("events lock")
4009                .iter()
4010                .any(|event| matches!(event, TransferEvent::SessionCancelled { .. }))
4011        );
4012    }
4013}