Skip to main content

remote/
lib.rs

1//! Remote copy protocol and networking for distributed file operations
2//!
3//! This crate provides the networking layer and protocol definitions for remote file copying in the RCP tools suite.
4//! It enables efficient distributed copying between remote hosts using SSH for orchestration and TCP for high-throughput data transfer.
5//!
6//! # Overview
7//!
8//! The remote copy system uses a three-node architecture:
9//!
10//! ```text
11//! Master (rcp)
12//! ├── SSH → Source Host (rcpd)
13//! │   ├── TCP Server ← Master (control + tracing)
14//! │   └── TCP Server ← Destination (control + data)
15//! └── SSH → Destination Host (rcpd)
16//!     ├── TCP Server ← Master (control + tracing)
17//!     └── TCP Client → Source (control + data)
18//! ```
19//!
20//! ## Connection Flow
21//!
22//! 1. **Initialization**: Master starts `rcpd` processes on source and destination via SSH
23//! 2. **Control Connections**: Master connects to each `rcpd`'s TCP listener (address read
24//!    from the rcpd's stderr over SSH)
25//! 3. **Address Exchange**: Source starts TCP listeners and sends addresses to Master
26//! 4. **Direct Connection**: Master forwards addresses to Destination, which connects to Source
27//! 5. **Data Transfer**: Files flow directly from Source to Destination (not through Master)
28//!
29//! This design ensures efficient data transfer while allowing the Master to coordinate operations and monitor progress.
30//!
31//! # Key Components
32//!
33//! ## SSH Session Management
34//!
35//! The [`SshSession`] type represents an SSH connection to a remote host and is used to:
36//! - Launch `rcpd` daemons on remote hosts
37//! - Configure connection parameters (user, host, port)
38//!
39//! ## TCP Networking
40//!
41//! TCP provides high-throughput bulk data transfer with:
42//! - Connection pooling for parallel file transfers
43//! - Configurable buffer sizes for different network profiles
44//! - Length-delimited message framing for control messages
45//!
46//! Key functions:
47//! - [`create_tcp_control_listener`] - Create TCP listener for control connections
48//! - [`create_tcp_data_listener`] - Create TCP listener for data connections
49//! - [`connect_tcp_control`] - Connect to a TCP control server
50//! - [`get_tcp_listener_addr`] - Get externally-routable address of a listener
51//! - [`configure_tcp_socket`] - Apply the standard socket options to every established connection
52//!
53//! ## Port Range Configuration
54//!
55//! The [`port_ranges`] module allows restricting TCP to specific port ranges, useful for firewall-restricted environments:
56//!
57//! ```rust,no_run
58//! # async fn example() -> anyhow::Result<()> {
59//! let config = remote::TcpConfig {
60//!     port_ranges: Some("8000-8999".to_string()),
61//!     ..remote::TcpConfig::default()
62//! };
63//! let listener = remote::create_tcp_control_listener(&config, None).await?;
64//! # Ok(())
65//! # }
66//! ```
67//!
68//! ## Protocol Messages
69//!
70//! The [`protocol`] module defines the message types exchanged between nodes:
71//! - `MasterHello` - Master → rcpd configuration
72//! - `SourceMasterHello` - Source → Master address information
73//! - `RcpdResult` - rcpd → Master operation results
74//!
75//! ## Stream Communication
76//!
77//! The [`streams`] module provides high-level abstractions over TCP streams:
78//! - [`streams::SendStream`] / [`streams::RecvStream`] for framed message passing
79//! - [`streams::ControlConnection`] for bidirectional control channels
80//! - Object serialization/deserialization using bitcode
81//!
82//! ## Remote Tracing
83//!
84//! The [`tracelog`] module enables distributed logging and progress tracking:
85//! - Forward tracing events from remote `rcpd` processes to Master
86//! - Aggregate progress information across multiple remote operations
87//! - Display unified progress for distributed operations
88//!
89//! # Security Model
90//!
91//! The remote copy system provides multiple security layers:
92//!
93//! - **SSH Authentication**: All remote operations require SSH authentication to spawn rcpd
94//! - **TLS Encryption**: All TCP connections encrypted with TLS 1.3 by default
95//! - **Certificate Pinning**: Self-signed certificates with fingerprint verification
96//! - **Mutual Authentication**: Source↔Destination connections use mutual TLS
97//!
98//! **How it works**:
99//! 1. Each rcpd generates an ephemeral self-signed certificate
100//! 2. rcpd outputs its certificate fingerprint to stderr (read by master over the trusted SSH channel)
101//! 3. Master connects to rcpd as TLS client, verifies fingerprint
102//! 4. Master distributes fingerprints to enable Source↔Destination mutual auth
103//!
104//! Use `--no-encryption` to disable TLS for trusted networks where performance is critical.
105//!
106//! # Network Troubleshooting
107//!
108//! Common failure scenarios:
109//!
110//! - **SSH Connection Fails**: Host unreachable or authentication failure
111//! - **Master Cannot Connect to rcpd**: Firewall blocks TCP ports
112//! - **Destination Cannot Connect to Source**: Use `--port-ranges` to specify allowed ports
113//!
114//! # Module Organization
115//!
116//! - [`port_ranges`] - Port range parsing and socket binding
117//! - [`protocol`] - Protocol message definitions and serialization
118//! - [`streams`] - TCP stream wrappers with typed message passing
119//! - [`tls`] - TLS certificate generation and configuration
120//! - [`tracelog`] - Remote tracing and progress aggregation
121
122#[cfg(not(tokio_unstable))]
123compile_error!("tokio_unstable cfg must be enabled; see .cargo/config.toml");
124
125use anyhow::{Context, anyhow};
126use tracing::instrument;
127
128#[cfg(test)]
129const DEFAULT_REMOTE_BOOTSTRAP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
130const FAILED_RCPD_REAP_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
131const RCPD_OUTPUT_DRAIN_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
132const REMOTE_CLEANUP_GRACE: std::time::Duration = std::time::Duration::from_secs(3);
133const CLEANUP_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(10);
134const DIAGNOSTIC_CAPTURE_LIMIT: usize = 64 * 1024;
135const RCPD_STARTUP_RECORD_LIMIT: usize = 64 * 1024;
136pub(crate) const RCPD_PATH_DISCOVERY_SCRIPT: &str = "command -v \"$1\"";
137
138std::thread_local! {
139    static ACTIVE_REMOTE_CLEANUP_SCOPES: std::cell::RefCell<Vec<ActiveCleanupScope>> = const {
140        std::cell::RefCell::new(Vec::new())
141    };
142}
143
144#[derive(Clone)]
145struct ActiveCleanupScope {
146    scope_id: usize,
147    budget: CleanupBudget,
148}
149
150struct CleanupWorkers {
151    owners: usize,
152    pending: usize,
153    threads: Vec<std::thread::JoinHandle<()>>,
154    next_job_id: u64,
155    finalizations: Vec<CleanupFinalization>,
156}
157
158impl Default for CleanupWorkers {
159    fn default() -> Self {
160        Self {
161            owners: 1,
162            pending: 0,
163            threads: Vec::new(),
164            next_job_id: 0,
165            finalizations: Vec::new(),
166        }
167    }
168}
169
170impl CleanupWorkers {
171    fn allocate_job_id(&mut self) -> u64 {
172        let job_id = self.next_job_id;
173        self.next_job_id = self
174            .next_job_id
175            .checked_add(1)
176            .expect("cleanup job id overflow");
177        job_id
178    }
179}
180
181struct CleanupFinalization {
182    cutoff_job_id: u64,
183    deadline: std::time::Instant,
184}
185
186#[derive(Default)]
187struct CleanupState {
188    workers: std::sync::Mutex<CleanupWorkers>,
189    changed: std::sync::Condvar,
190    supervisor: std::sync::Mutex<Option<std::thread::JoinHandle<()>>>,
191}
192
193struct CleanupJob {
194    thread_name: &'static str,
195    deadline: std::time::Instant,
196    operation: CleanupOperation,
197}
198
199struct ScheduledCleanupJob {
200    id: u64,
201    job: CleanupJob,
202}
203
204enum CleanupOperation {
205    Bounded(Box<dyn FnOnce(CleanupBudget) + Send + 'static>),
206    Disposable(Box<dyn FnOnce() + Send + 'static>),
207}
208
209/// Mandatory liveness budget supplied by the cleanup scope to cooperative waits.
210#[derive(Clone)]
211pub(crate) struct CleanupBudget {
212    state: std::sync::Arc<CleanupState>,
213    job_id: u64,
214    job_deadline: std::time::Instant,
215}
216
217impl CleanupBudget {
218    #[cfg(test)]
219    fn for_job(state: std::sync::Arc<CleanupState>, grace: std::time::Duration) -> Self {
220        let job_id = state
221            .workers
222            .lock()
223            .unwrap_or_else(std::sync::PoisonError::into_inner)
224            .allocate_job_id();
225        Self {
226            state,
227            job_id,
228            job_deadline: std::time::Instant::now() + grace,
229        }
230    }
231
232    fn effective_deadline(&self, workers: &CleanupWorkers) -> std::time::Instant {
233        workers
234            .finalizations
235            .iter()
236            .filter(|finalization| self.job_id < finalization.cutoff_job_id)
237            .fold(self.job_deadline, |deadline, finalization| {
238                std::cmp::min(deadline, finalization.deadline)
239            })
240    }
241
242    fn wait_for_next_poll(&self) -> bool {
243        let workers = self
244            .state
245            .workers
246            .lock()
247            .unwrap_or_else(std::sync::PoisonError::into_inner);
248        let now = std::time::Instant::now();
249        let deadline = self.effective_deadline(&workers);
250        if now >= deadline {
251            return false;
252        }
253        let wait = std::cmp::min(CLEANUP_POLL_INTERVAL, deadline.duration_since(now));
254        drop(
255            self.state
256                .changed
257                .wait_timeout(workers, wait)
258                .unwrap_or_else(std::sync::PoisonError::into_inner),
259        );
260        true
261    }
262}
263
264/// Owns all blocking cleanup work started by one rcp invocation.
265pub struct RemoteCleanup {
266    state: std::sync::Arc<CleanupState>,
267    sender: Option<std::sync::mpsc::Sender<ScheduledCleanupJob>>,
268}
269
270impl Clone for RemoteCleanup {
271    fn clone(&self) -> Self {
272        let mut workers = self
273            .state
274            .workers
275            .lock()
276            .unwrap_or_else(std::sync::PoisonError::into_inner);
277        workers.owners = workers
278            .owners
279            .checked_add(1)
280            .expect("remote cleanup owner count overflow");
281        drop(workers);
282        Self {
283            state: self.state.clone(),
284            sender: Some(
285                self.sender
286                    .as_ref()
287                    .expect("a live cleanup owner retains its supervisor sender")
288                    .clone(),
289            ),
290        }
291    }
292}
293
294impl Drop for RemoteCleanup {
295    fn drop(&mut self) {
296        let mut workers = self
297            .state
298            .workers
299            .lock()
300            .unwrap_or_else(std::sync::PoisonError::into_inner);
301        workers.owners = workers
302            .owners
303            .checked_sub(1)
304            .expect("remote cleanup owner drop matches its construction");
305        self.state.changed.notify_all();
306    }
307}
308
309impl std::fmt::Debug for RemoteCleanup {
310    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
311        formatter
312            .debug_struct("RemoteCleanup")
313            .finish_non_exhaustive()
314    }
315}
316
317struct CleanupWorkerContext {
318    scope_id: usize,
319}
320
321impl CleanupWorkerContext {
322    fn enter(state: &std::sync::Arc<CleanupState>, budget: CleanupBudget) -> Self {
323        let scope_id = std::sync::Arc::as_ptr(state) as usize;
324        ACTIVE_REMOTE_CLEANUP_SCOPES.with(|scopes| {
325            scopes
326                .borrow_mut()
327                .push(ActiveCleanupScope { scope_id, budget });
328        });
329        Self { scope_id }
330    }
331}
332
333impl Drop for CleanupWorkerContext {
334    fn drop(&mut self) {
335        ACTIVE_REMOTE_CLEANUP_SCOPES.with(|scopes| {
336            let removed = scopes.borrow_mut().pop();
337            debug_assert_eq!(removed.map(|scope| scope.scope_id), Some(self.scope_id));
338        });
339    }
340}
341
342struct CleanupWorkerCompletion(std::sync::Arc<CleanupState>);
343
344impl Drop for CleanupWorkerCompletion {
345    fn drop(&mut self) {
346        let mut workers = self
347            .0
348            .workers
349            .lock()
350            .unwrap_or_else(std::sync::PoisonError::into_inner);
351        workers.pending = workers
352            .pending
353            .checked_sub(1)
354            .expect("cleanup worker completion matches a pending worker");
355        self.0.changed.notify_all();
356    }
357}
358
359impl RemoteCleanup {
360    /// Create a cleanup scope before any remote-resource ownership is accepted.
361    pub fn new() -> std::io::Result<Self> {
362        Self::try_new_with(|operation| {
363            std::thread::Builder::new()
364                .name("rcp-cleanup-supervisor".to_string())
365                .spawn(operation)
366        })
367    }
368
369    fn try_new_with<F>(start_supervisor: F) -> std::io::Result<Self>
370    where
371        F: FnOnce(
372            Box<dyn FnOnce() + Send + 'static>,
373        ) -> std::io::Result<std::thread::JoinHandle<()>>,
374    {
375        let state = std::sync::Arc::new(CleanupState {
376            workers: std::sync::Mutex::new(CleanupWorkers::default()),
377            changed: std::sync::Condvar::new(),
378            supervisor: std::sync::Mutex::new(None),
379        });
380        let (sender, receiver) = std::sync::mpsc::channel();
381        // retain the scope until every sender is gone so unwinding still drains queued cleanup
382        let supervisor_state = state.clone();
383        let supervisor = start_supervisor(Box::new(move || {
384            while let Ok(job) = receiver.recv() {
385                supervisor_state
386                    .start_cleanup_job(job, WorkerSpawnFallback::RunInSupervisor)
387                    .expect("the cleanup supervisor owns its worker-spawn fallback");
388            }
389        }))?;
390        *state
391            .supervisor
392            .lock()
393            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(supervisor);
394        Ok(Self {
395            state,
396            sender: Some(sender),
397        })
398    }
399
400    fn scope_id(&self) -> usize {
401        std::sync::Arc::as_ptr(&self.state) as usize
402    }
403
404    fn current_budget(&self) -> Option<CleanupBudget> {
405        let scope_id = self.scope_id();
406        ACTIVE_REMOTE_CLEANUP_SCOPES.with(|scopes| {
407            scopes
408                .borrow()
409                .iter()
410                .rev()
411                .find(|scope| scope.scope_id == scope_id)
412                .map(|scope| scope.budget.clone())
413        })
414    }
415
416    fn submit(&self, job: CleanupJob) -> std::io::Result<()> {
417        let mut workers = self
418            .state
419            .workers
420            .lock()
421            .unwrap_or_else(std::sync::PoisonError::into_inner);
422        workers.pending = workers
423            .pending
424            .checked_add(1)
425            .expect("cleanup worker count overflow");
426        let job_id = workers.allocate_job_id();
427        drop(workers);
428        let job = ScheduledCleanupJob { id: job_id, job };
429        match self
430            .sender
431            .as_ref()
432            .expect("a live cleanup owner retains its supervisor sender")
433            .send(job)
434        {
435            Ok(()) => Ok(()),
436            Err(error) => {
437                tracing::error!(
438                    "remote cleanup supervisor stopped unexpectedly; starting an isolated fallback worker"
439                );
440                self.state
441                    .start_cleanup_job(error.0, WorkerSpawnFallback::Abandon)
442            }
443        }
444    }
445
446    fn submit_disposable<F>(&self, thread_name: &'static str, operation: F) -> std::io::Result<()>
447    where
448        F: FnOnce() + Send + 'static,
449    {
450        self.submit(CleanupJob {
451            thread_name,
452            deadline: std::time::Instant::now() + REMOTE_CLEANUP_GRACE,
453            operation: CleanupOperation::Disposable(Box::new(operation)),
454        })
455    }
456
457    fn submit_bounded<F>(&self, thread_name: &'static str, operation: F) -> std::io::Result<()>
458    where
459        F: FnOnce(CleanupBudget) + Send + 'static,
460    {
461        self.submit(CleanupJob {
462            thread_name,
463            deadline: std::time::Instant::now() + REMOTE_CLEANUP_GRACE,
464            operation: CleanupOperation::Bounded(Box::new(operation)),
465        })
466    }
467
468    fn defer_drop<T>(&self, value: T, thread_name: &'static str)
469    where
470        T: Send + 'static,
471    {
472        if self.current_budget().is_some() {
473            drop(value);
474            return;
475        }
476        if let Err(error) = self.submit_disposable(thread_name, move || drop(value)) {
477            tracing::error!("failed to start deferred cleanup worker: {error:#}");
478        }
479    }
480
481    fn defer_bounded<F>(&self, thread_name: &'static str, operation: F)
482    where
483        F: FnOnce(CleanupBudget) + Send + 'static,
484    {
485        if let Some(budget) = self.current_budget() {
486            operation(budget);
487            return;
488        }
489        if let Err(error) = self.submit_bounded(thread_name, operation) {
490            tracing::error!("failed to start bounded cleanup worker: {error:#}");
491        }
492    }
493
494    /// Wait for this invocation's remaining owners and cleanup jobs under one shared time budget.
495    pub fn finish(self) {
496        let _supervisor_joined = self.finish_with_grace(REMOTE_CLEANUP_GRACE);
497    }
498
499    fn finish_with_grace(mut self, grace: std::time::Duration) -> bool {
500        let deadline = std::time::Instant::now() + grace;
501        let state = self.state.clone();
502        let mut workers = state
503            .workers
504            .lock()
505            .unwrap_or_else(std::sync::PoisonError::into_inner);
506        let cutoff_job_id = workers.next_job_id;
507        workers.finalizations.push(CleanupFinalization {
508            cutoff_job_id,
509            deadline,
510        });
511        state.changed.notify_all();
512        drop(workers);
513        // this owner cannot submit more work. Closing its sender before waiting lets an otherwise
514        // idle supervisor retire concurrently with workers instead of starting after grace expires.
515        drop(self.sender.take());
516        let mut workers = state
517            .workers
518            .lock()
519            .unwrap_or_else(std::sync::PoisonError::into_inner);
520        while workers.owners > 1
521            || workers.pending > 0
522            || workers.threads.iter().any(|worker| !worker.is_finished())
523            || state
524                .supervisor
525                .lock()
526                .unwrap_or_else(std::sync::PoisonError::into_inner)
527                .as_ref()
528                .is_some_and(|supervisor| !supervisor.is_finished())
529        {
530            let now = std::time::Instant::now();
531            if now >= deadline {
532                break;
533            }
534            // pending completion is signaled just before the OS marks its JoinHandle finished.
535            // poll that final transition under the same deadline rather than performing an
536            // unbounded join or detaching an almost-finished worker.
537            let wait = std::cmp::min(
538                CLEANUP_POLL_INTERVAL,
539                deadline.saturating_duration_since(now),
540            );
541            let (next, _) = state
542                .changed
543                .wait_timeout(workers, wait)
544                .unwrap_or_else(std::sync::PoisonError::into_inner);
545            workers = next;
546        }
547        let remaining_owners = workers.owners.saturating_sub(1);
548        let pending = workers.pending;
549        let mut completed = Vec::new();
550        let mut still_running = Vec::new();
551        for worker in std::mem::take(&mut workers.threads) {
552            if worker.is_finished() {
553                completed.push(worker);
554            } else {
555                still_running.push(worker);
556            }
557        }
558        let unfinished_workers = still_running.len();
559        workers.threads = still_running;
560        drop(workers);
561        for worker in completed {
562            if let Err(error) = worker.join() {
563                tracing::debug!("deferred remote cleanup worker panicked: {error:?}");
564            }
565        }
566        if pending > 0 || unfinished_workers > 0 {
567            tracing::debug!(
568                "{pending} deferred remote cleanup job(s) and {unfinished_workers} worker thread(s) did not finish within {}; abandoning them at process exit",
569                humantime::format_duration(grace)
570            );
571        }
572        if remaining_owners > 0 {
573            tracing::debug!(
574                "{remaining_owners} remote cleanup owner(s) remained live after {}; abandoning their cleanup at process exit",
575                humantime::format_duration(grace)
576            );
577        }
578        let supervisor = state
579            .supervisor
580            .lock()
581            .unwrap_or_else(std::sync::PoisonError::into_inner)
582            .take();
583        match supervisor {
584            Some(supervisor) if supervisor.is_finished() => {
585                if let Err(error) = supervisor.join() {
586                    tracing::debug!("remote cleanup supervisor panicked: {error:?}");
587                }
588                true
589            }
590            Some(_) => {
591                tracing::debug!(
592                    "remote cleanup supervisor did not finish within its shared cleanup grace"
593                );
594                false
595            }
596            None => true,
597        }
598    }
599}
600
601#[derive(Clone, Copy)]
602enum WorkerSpawnFallback {
603    RunInSupervisor,
604    Abandon,
605}
606
607impl CleanupState {
608    fn start_cleanup_job(
609        self: &std::sync::Arc<Self>,
610        job: ScheduledCleanupJob,
611        fallback: WorkerSpawnFallback,
612    ) -> std::io::Result<()> {
613        let thread_name = job.job.thread_name;
614        // retain the job until the OS confirms worker creation. The start gate lets the handle enter
615        // shared state before the worker can finish, without holding that mutex across thread spawn.
616        let job = std::sync::Arc::new(std::sync::Mutex::new(Some(job)));
617        let worker_job = job.clone();
618        let state = self.clone();
619        let (start_tx, start_rx) = std::sync::mpsc::channel();
620        match std::thread::Builder::new()
621            .name(thread_name.to_string())
622            .spawn(move || {
623                if start_rx.recv().is_err() {
624                    return;
625                }
626                if let Some(job) = worker_job
627                    .lock()
628                    .unwrap_or_else(std::sync::PoisonError::into_inner)
629                    .take()
630                {
631                    state.run_cleanup_job(job);
632                }
633            }) {
634            Ok(worker) => {
635                self.workers
636                    .lock()
637                    .unwrap_or_else(std::sync::PoisonError::into_inner)
638                    .threads
639                    .push(worker);
640                if start_tx.send(()).is_err() {
641                    let job = job
642                        .lock()
643                        .unwrap_or_else(std::sync::PoisonError::into_inner)
644                        .take()
645                        .expect("a failed worker start signal retains its job");
646                    return self.handle_worker_start_failure(
647                        job,
648                        fallback,
649                        std::io::Error::other("cleanup worker exited before its start signal"),
650                    );
651                }
652                Ok(())
653            }
654            Err(error) => {
655                let job = job
656                    .lock()
657                    .unwrap_or_else(std::sync::PoisonError::into_inner)
658                    .take()
659                    .expect("a failed cleanup worker start retains its job");
660                self.handle_worker_start_failure(job, fallback, error)
661            }
662        }
663    }
664
665    fn handle_worker_start_failure(
666        self: &std::sync::Arc<Self>,
667        job: ScheduledCleanupJob,
668        fallback: WorkerSpawnFallback,
669        error: std::io::Error,
670    ) -> std::io::Result<()> {
671        match fallback {
672            WorkerSpawnFallback::RunInSupervisor => {
673                tracing::error!(
674                    "failed to start deferred cleanup worker; running cleanup in its supervisor: {error:#}"
675                );
676                self.run_cleanup_job(job);
677                Ok(())
678            }
679            WorkerSpawnFallback::Abandon => {
680                tracing::error!(
681                    "failed to start an isolated fallback cleanup worker; leaking the cleanup job for process-exit reclamation: {error:#}"
682                );
683                std::mem::forget(job);
684                let mut workers = self
685                    .workers
686                    .lock()
687                    .unwrap_or_else(std::sync::PoisonError::into_inner);
688                workers.pending = workers
689                    .pending
690                    .checked_sub(1)
691                    .expect("abandoned cleanup matches a pending job");
692                self.changed.notify_all();
693                Err(error)
694            }
695        }
696    }
697
698    fn run_cleanup_job(self: &std::sync::Arc<Self>, scheduled: ScheduledCleanupJob) {
699        let _completion = CleanupWorkerCompletion(self.clone());
700        let budget = CleanupBudget {
701            state: self.clone(),
702            job_id: scheduled.id,
703            job_deadline: scheduled.job.deadline,
704        };
705        let _context = CleanupWorkerContext::enter(self, budget.clone());
706        let operation = move || match scheduled.job.operation {
707            CleanupOperation::Bounded(operation) => operation(budget),
708            CleanupOperation::Disposable(operation) => operation(),
709        };
710        if std::panic::catch_unwind(std::panic::AssertUnwindSafe(operation)).is_err() {
711            tracing::debug!("deferred remote cleanup job panicked");
712        }
713    }
714}
715
716/// Owns a Tokio task and aborts it if its supervising future is cancelled.
717pub struct AbortOnDropTask<T>(tokio::task::JoinHandle<T>);
718
719impl<T> AbortOnDropTask<T> {
720    /// Retain a task under cancellation-safe ownership.
721    pub fn new(task: tokio::task::JoinHandle<T>) -> Self {
722        Self(task)
723    }
724
725    /// Await and consume the retained task.
726    pub async fn join(mut self) -> Result<T, tokio::task::JoinError> {
727        (&mut self.0).await
728    }
729
730    async fn wait(&mut self) -> Result<T, tokio::task::JoinError> {
731        (&mut self.0).await
732    }
733
734    fn abort(&self) {
735        self.0.abort();
736    }
737
738    fn is_finished(&self) -> bool {
739        self.0.is_finished()
740    }
741}
742
743impl<T> Drop for AbortOnDropTask<T> {
744    fn drop(&mut self) {
745        self.0.abort();
746    }
747}
748
749#[derive(Default)]
750pub(crate) struct CapturedOutput {
751    pub(crate) bytes: Vec<u8>,
752    pub(crate) truncated: bool,
753    pub(crate) read_error: Option<std::io::Error>,
754}
755
756impl CapturedOutput {
757    pub(crate) fn rendered(&self) -> String {
758        let body = String::from_utf8_lossy(&self.bytes);
759        let truncation = self.truncated.then(|| {
760            format!(
761                "[output truncated to the last {} bytes]\n",
762                self.bytes.len()
763            )
764        });
765        let read_error = self
766            .read_error
767            .as_ref()
768            .map(|error| format!("\n[output read failed: {error:#}]"));
769        format!(
770            "{}{}{}",
771            truncation.as_deref().unwrap_or_default(),
772            body,
773            read_error.as_deref().unwrap_or_default()
774        )
775    }
776}
777
778fn retain_bounded_tail(output: &mut Vec<u8>, input: &[u8], limit: usize) -> bool {
779    if input.is_empty() {
780        return false;
781    }
782    if limit == 0 {
783        return true;
784    }
785    if input.len() >= limit {
786        let truncated = !output.is_empty() || input.len() > limit;
787        output.clear();
788        output.extend_from_slice(&input[input.len() - limit..]);
789        return truncated;
790    }
791    let overflow = output
792        .len()
793        .saturating_add(input.len())
794        .saturating_sub(limit);
795    if overflow > 0 {
796        output.drain(..overflow);
797    }
798    output.extend_from_slice(input);
799    overflow > 0
800}
801
802async fn drain_bounded_output_forwarding<R, F>(
803    mut reader: R,
804    limit: usize,
805    mut forward: F,
806) -> CapturedOutput
807where
808    R: tokio::io::AsyncRead + Unpin,
809    F: FnMut(&[u8]),
810{
811    use tokio::io::AsyncReadExt;
812
813    let mut output = CapturedOutput::default();
814    let mut chunk = [0_u8; 8192];
815    loop {
816        match reader.read(&mut chunk).await {
817            Ok(0) => break,
818            Ok(bytes_read) => {
819                forward(&chunk[..bytes_read]);
820                output.truncated |=
821                    retain_bounded_tail(&mut output.bytes, &chunk[..bytes_read], limit);
822            }
823            Err(error) => {
824                output.read_error = Some(error);
825                break;
826            }
827        }
828    }
829    output
830}
831
832pub(crate) async fn drain_bounded_output<R>(reader: R, limit: usize) -> CapturedOutput
833where
834    R: tokio::io::AsyncRead + Unpin,
835{
836    drain_bounded_output_forwarding(reader, limit, |_| {}).await
837}
838
839struct Utf8ChunkForwarder<F> {
840    pending: Vec<u8>,
841    forward: F,
842}
843
844impl<F> Utf8ChunkForwarder<F>
845where
846    F: FnMut(&str),
847{
848    fn new(forward: F) -> Self {
849        Self {
850            pending: Vec::new(),
851            forward,
852        }
853    }
854
855    fn push(&mut self, chunk: &[u8]) {
856        self.pending.extend_from_slice(chunk);
857        let complete = complete_utf8_prefix_len(&self.pending);
858        if complete == 0 {
859            return;
860        }
861        let incomplete = self.pending.split_off(complete);
862        let output = String::from_utf8_lossy(&self.pending);
863        (self.forward)(&output);
864        self.pending = incomplete;
865    }
866
867    fn finish(&mut self) {
868        if self.pending.is_empty() {
869            return;
870        }
871        let output = String::from_utf8_lossy(&self.pending);
872        (self.forward)(&output);
873        self.pending.clear();
874    }
875}
876
877fn complete_utf8_prefix_len(bytes: &[u8]) -> usize {
878    let mut consumed = 0;
879    while consumed < bytes.len() {
880        match std::str::from_utf8(&bytes[consumed..]) {
881            Ok(_) => return bytes.len(),
882            Err(error) => {
883                consumed += error.valid_up_to();
884                let Some(invalid) = error.error_len() else {
885                    return consumed;
886                };
887                consumed += invalid;
888            }
889        }
890    }
891    bytes.len()
892}
893
894async fn drain_rcpd_output<R>(reader: R, host: String, stream: &'static str) -> CapturedOutput
895where
896    R: tokio::io::AsyncRead + Unpin,
897{
898    let mut forwarder = Utf8ChunkForwarder::new(move |output: &str| {
899        let output = output.trim_end_matches(['\r', '\n']);
900        if !output.is_empty() {
901            tracing::debug!(host, stream, output, "rcpd output");
902        }
903    });
904    let captured = drain_bounded_output_forwarding(reader, DIAGNOSTIC_CAPTURE_LIMIT, |chunk| {
905        forwarder.push(chunk);
906    })
907    .await;
908    forwarder.finish();
909    captured
910}
911
912/// Prefix for an intentional daemon refusal in place of a readiness record.
913pub const RCPD_STARTUP_ERROR_PREFIX: &str = "RCP_ERROR ";
914
915#[derive(Debug)]
916struct PeerPreparationCancelled;
917
918impl std::fmt::Display for PeerPreparationCancelled {
919    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
920        formatter.write_str("rcpd preparation cancelled because peer preparation failed")
921    }
922}
923
924impl std::error::Error for PeerPreparationCancelled {}
925
926/// Cancellation and owned-work completion policy for one endpoint preparation.
927#[derive(Clone)]
928pub(crate) struct PreparationContext {
929    cancellation: tokio_util::sync::CancellationToken,
930    cleanup: RemoteCleanup,
931    control_directory_exclusions: std::sync::Arc<[std::path::PathBuf]>,
932}
933
934struct SshMasterReaper {
935    launcher: Option<tokio::process::Child>,
936    control_directory: Option<std::path::PathBuf>,
937}
938
939pub(crate) fn poll_process_exit_until_deadline(
940    budget: &CleanupBudget,
941    mut try_wait: impl FnMut() -> std::io::Result<bool>,
942) -> std::io::Result<bool> {
943    loop {
944        if try_wait()? {
945            return Ok(true);
946        }
947        if !budget.wait_for_next_poll() {
948            return Ok(false);
949        }
950    }
951}
952
953fn reap_process_and_control_directory(
954    budget: &CleanupBudget,
955    control_directory: Option<&std::path::Path>,
956    try_wait: impl FnMut() -> std::io::Result<bool>,
957) {
958    let master_exited = match poll_process_exit_until_deadline(budget, try_wait) {
959        Ok(exited) => exited,
960        Err(error) => {
961            tracing::debug!("failed to reap SSH multiplex master: {error:#}");
962            false
963        }
964    };
965    if !master_exited {
966        tracing::debug!(
967            "SSH multiplex master did not exit within its cleanup budget; preserving its control directory"
968        );
969    }
970    if master_exited
971        && let Some(control_directory) = control_directory
972        && let Err(error) = std::fs::remove_dir_all(control_directory)
973    {
974        tracing::debug!(
975            "failed to remove SSH control directory {}: {error:#}",
976            control_directory.display()
977        );
978    }
979}
980
981impl SshMasterReaper {
982    fn reap(mut self, budget: CleanupBudget) {
983        if let Some(launcher) = self.launcher.as_mut() {
984            reap_process_and_control_directory(&budget, self.control_directory.as_deref(), || {
985                launcher.try_wait().map(|status| status.is_some())
986            });
987        } else {
988            reap_process_and_control_directory(&budget, self.control_directory.as_deref(), || {
989                Ok(true)
990            });
991        }
992    }
993}
994
995struct PreparingSshMaster {
996    launcher: Option<tokio::process::Child>,
997    control_directory: Option<std::path::PathBuf>,
998    cleanup: RemoteCleanup,
999}
1000
1001impl PreparingSshMaster {
1002    fn new(control_directory: std::path::PathBuf, cleanup: RemoteCleanup) -> Self {
1003        Self {
1004            launcher: None,
1005            control_directory: Some(control_directory),
1006            cleanup,
1007        }
1008    }
1009
1010    fn control_directory(&self) -> &std::path::Path {
1011        self.control_directory
1012            .as_deref()
1013            .expect("preparing SSH control directory remains owned")
1014    }
1015
1016    fn retain_launcher(&mut self, launcher: tokio::process::Child) {
1017        debug_assert!(self.launcher.is_none());
1018        self.launcher = Some(launcher);
1019    }
1020
1021    fn launcher_mut(&mut self) -> &mut tokio::process::Child {
1022        self.launcher
1023            .as_mut()
1024            .expect("preparing SSH master retains its launcher")
1025    }
1026
1027    fn into_managed(mut self, session: openssh::Session) -> ManagedSshSession {
1028        let launcher = self
1029            .launcher
1030            .take()
1031            .expect("prepared SSH session takes its launcher once");
1032        let control_directory = self
1033            .control_directory
1034            .take()
1035            .expect("prepared SSH session takes its control directory once");
1036        ManagedSshSession::new(session, launcher, control_directory, self.cleanup.clone())
1037    }
1038}
1039
1040impl Drop for PreparingSshMaster {
1041    fn drop(&mut self) {
1042        if let Some(launcher) = self.launcher.as_mut()
1043            && let Err(error) = launcher.start_kill()
1044        {
1045            tracing::debug!("failed to terminate preparing SSH multiplex master: {error:#}");
1046        }
1047        if self.launcher.is_none() && self.control_directory.is_none() {
1048            return;
1049        }
1050        let reaper = SshMasterReaper {
1051            launcher: self.launcher.take(),
1052            control_directory: self.control_directory.take(),
1053        };
1054        self.cleanup
1055            .defer_bounded("rcp-ssh-cleanup", move |budget| reaper.reap(budget));
1056    }
1057}
1058
1059struct ManagedSshSessionInner {
1060    session: Option<openssh::Session>,
1061    launcher: Option<tokio::process::Child>,
1062    control_directory: Option<std::path::PathBuf>,
1063    cleanup: RemoteCleanup,
1064}
1065
1066impl Drop for ManagedSshSessionInner {
1067    fn drop(&mut self) {
1068        // release the resumed native-mux handle without asking it to shut down the externally owned
1069        // master. Signal that retained process before returning from Drop, then move reaping and
1070        // directory removal to an executor that remains available after Tokio shutdown.
1071        let _detached_paths = self.session.take().map(openssh::Session::detach);
1072        if let Some(launcher) = self.launcher.as_mut()
1073            && let Err(error) = launcher.start_kill()
1074        {
1075            tracing::debug!("failed to terminate SSH multiplex master: {error:#}");
1076        }
1077        let reaper = SshMasterReaper {
1078            launcher: self.launcher.take(),
1079            control_directory: self.control_directory.take(),
1080        };
1081        self.cleanup
1082            .defer_bounded("rcp-ssh-cleanup", move |budget| reaper.reap(budget));
1083    }
1084}
1085
1086/// Cloneable session ownership whose final drop cannot block or depend on Tokio still running.
1087#[derive(Clone)]
1088pub(crate) struct ManagedSshSession(std::sync::Arc<ManagedSshSessionInner>);
1089
1090impl std::fmt::Debug for ManagedSshSession {
1091    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1092        formatter
1093            .debug_struct("ManagedSshSession")
1094            .finish_non_exhaustive()
1095    }
1096}
1097
1098impl ManagedSshSession {
1099    fn new(
1100        session: openssh::Session,
1101        launcher: tokio::process::Child,
1102        control_directory: std::path::PathBuf,
1103        cleanup: RemoteCleanup,
1104    ) -> Self {
1105        Self(std::sync::Arc::new(ManagedSshSessionInner {
1106            session: Some(session),
1107            launcher: Some(launcher),
1108            control_directory: Some(control_directory),
1109            cleanup,
1110        }))
1111    }
1112
1113    fn cleanup(&self) -> RemoteCleanup {
1114        self.0.cleanup.clone()
1115    }
1116}
1117
1118impl std::ops::Deref for ManagedSshSession {
1119    type Target = openssh::Session;
1120
1121    fn deref(&self) -> &Self::Target {
1122        self.0
1123            .session
1124            .as_ref()
1125            .expect("managed SSH session is present before final drop")
1126    }
1127}
1128
1129pub(crate) trait SshSessionOwner:
1130    Clone + std::ops::Deref<Target = openssh::Session> + Send + Sync + 'static
1131{
1132}
1133
1134impl<T> SshSessionOwner for T where
1135    T: Clone + std::ops::Deref<Target = openssh::Session> + Send + Sync + 'static
1136{
1137}
1138
1139impl PreparationContext {
1140    fn new(cancellation: tokio_util::sync::CancellationToken, cleanup: RemoteCleanup) -> Self {
1141        Self {
1142            cancellation,
1143            cleanup,
1144            control_directory_exclusions: Vec::new().into(),
1145        }
1146    }
1147
1148    fn uncancelled(cleanup: RemoteCleanup) -> Self {
1149        Self::new(tokio_util::sync::CancellationToken::new(), cleanup)
1150    }
1151
1152    fn with_control_directory_exclusions(
1153        mut self,
1154        exclusions: std::sync::Arc<[std::path::PathBuf]>,
1155    ) -> Self {
1156        self.control_directory_exclusions = exclusions;
1157        self
1158    }
1159
1160    fn cancellation_error() -> anyhow::Error {
1161        anyhow::Error::new(PeerPreparationCancelled)
1162    }
1163
1164    fn ensure_active(&self) -> anyhow::Result<()> {
1165        if self.cancellation.is_cancelled() {
1166            return Err(Self::cancellation_error());
1167        }
1168        Ok(())
1169    }
1170
1171    fn record_owned_completion<T>(
1172        cleanup: &RemoteCleanup,
1173        result: Result<anyhow::Result<T>, tokio::task::JoinError>,
1174        operation: &str,
1175        timing: &str,
1176    ) where
1177        T: Send + 'static,
1178    {
1179        match result {
1180            Ok(Ok(value)) => {
1181                tracing::debug!("{operation} completed {timing}");
1182                cleanup.defer_drop(value, "rcp-owned-result-dispose");
1183            }
1184            Ok(Err(error)) => {
1185                tracing::debug!("{operation} failed {timing}: {error:#}");
1186            }
1187            Err(error) => {
1188                tracing::debug!("{operation} owner task failed {timing}: {error:#}");
1189            }
1190        }
1191    }
1192
1193    async fn finish_or_abort_owned_during_grace<T>(
1194        &self,
1195        mut task: AbortOnDropTask<anyhow::Result<T>>,
1196        grace: std::time::Duration,
1197        operation: &'static str,
1198    ) where
1199        T: Send + 'static,
1200    {
1201        match tokio::time::timeout(grace, task.wait()).await {
1202            Ok(result) => {
1203                Self::record_owned_completion(
1204                    &self.cleanup,
1205                    result,
1206                    operation,
1207                    "during cancellation grace",
1208                );
1209            }
1210            Err(_) => {
1211                self.abort_owned(task, operation, "cancellation grace");
1212            }
1213        }
1214    }
1215
1216    /// Await cancellation-safe work that owns no process or session after its future is dropped.
1217    pub(crate) async fn run<T>(
1218        &self,
1219        operation: impl std::future::Future<Output = anyhow::Result<T>>,
1220    ) -> anyhow::Result<T> {
1221        tokio::select! {
1222            biased;
1223            () = self.cancellation.cancelled() => Err(Self::cancellation_error()),
1224            result = operation => result,
1225        }
1226    }
1227
1228    /// Await a transaction with no wall-clock deadline, closing its local owner after cancellation.
1229    pub(crate) async fn run_cancellation_owned_transaction<T>(
1230        &self,
1231        task: tokio::task::JoinHandle<anyhow::Result<T>>,
1232        grace: std::time::Duration,
1233        operation: &'static str,
1234    ) -> anyhow::Result<T>
1235    where
1236        T: Send + 'static,
1237    {
1238        let mut task = AbortOnDropTask::new(task);
1239        tokio::select! {
1240            biased;
1241            () = self.cancellation.cancelled() => {
1242                self.finish_or_abort_owned_during_grace(task, grace, operation).await;
1243                Err(Self::cancellation_error())
1244            }
1245            result = task.wait() => result
1246                .with_context(|| format!("{operation} owner task failed"))?,
1247        }
1248    }
1249
1250    fn abort_owned<T>(
1251        &self,
1252        task: AbortOnDropTask<anyhow::Result<T>>,
1253        operation: &str,
1254        reason: &str,
1255    ) where
1256        T: Send + 'static,
1257    {
1258        task.abort();
1259        let cleanup = self.cleanup.clone();
1260        let result_cleanup = cleanup.clone();
1261        let operation = operation.to_string();
1262        let reason = reason.to_string();
1263        let completion_timing = format!("as {reason} arrived");
1264        cleanup.defer_bounded("rcp-owned-task-reap", move |budget| {
1265            while !task.is_finished() {
1266                if !budget.wait_for_next_poll() {
1267                    tracing::debug!(
1268                        "{operation} owner task did not finish after {reason} within its cleanup budget"
1269                    );
1270                    return;
1271                }
1272            }
1273            let result = futures::executor::block_on(task.join());
1274            Self::record_owned_completion(
1275                &result_cleanup,
1276                result,
1277                &operation,
1278                &completion_timing,
1279            );
1280        });
1281    }
1282
1283    async fn run_abortable_with_deadline<T>(
1284        &self,
1285        task: tokio::task::JoinHandle<anyhow::Result<T>>,
1286        operation: &str,
1287        deadline: BootstrapDeadline,
1288    ) -> anyhow::Result<T>
1289    where
1290        T: Send + 'static,
1291    {
1292        let mut task = AbortOnDropTask::new(task);
1293        tokio::select! {
1294            biased;
1295            () = self.cancellation.cancelled() => {
1296                self.abort_owned(task, operation, "peer cancellation");
1297                Err(Self::cancellation_error())
1298            }
1299            result = deadline.wait(operation, task.wait()) => {
1300                match result {
1301                    Ok(result) => result
1302                        .with_context(|| format!("{operation} owner task failed"))?,
1303                    Err(error) => {
1304                        self.abort_owned(task, operation, "its bootstrap deadline");
1305                        Err(error)
1306                    }
1307                }
1308            }
1309        }
1310    }
1311
1312    /// Run a remote command in an owned task so cancellation cannot orphan its local SSH child.
1313    fn remote_output_task<S: SshSessionOwner>(
1314        mut command: openssh::OwningCommand<S>,
1315        operation: String,
1316    ) -> tokio::task::JoinHandle<anyhow::Result<std::process::Output>> {
1317        tokio::spawn(async move {
1318            command
1319                .stdin(openssh::Stdio::null())
1320                .stdout(openssh::Stdio::piped())
1321                .stderr(openssh::Stdio::piped());
1322            let mut child = command
1323                .spawn()
1324                .await
1325                .with_context(|| format!("{operation} failed to start"))?;
1326            let stdout = child
1327                .stdout()
1328                .take()
1329                .with_context(|| format!("{operation} stdout was not piped"))?;
1330            let stderr = child
1331                .stderr()
1332                .take()
1333                .with_context(|| format!("{operation} stderr was not piped"))?;
1334            let (status, stdout, stderr) = tokio::join!(
1335                child.wait(),
1336                drain_bounded_output(stdout, DIAGNOSTIC_CAPTURE_LIMIT),
1337                drain_bounded_output(stderr, DIAGNOSTIC_CAPTURE_LIMIT),
1338            );
1339            let status = status.with_context(|| format!("{operation} failed to wait"))?;
1340            let stdout = finish_remote_output_capture(&operation, "stdout", stdout, true)?;
1341            let stderr = finish_remote_output_capture(&operation, "stderr", stderr, false)?;
1342            Ok(std::process::Output {
1343                status,
1344                stdout,
1345                stderr,
1346            })
1347        })
1348    }
1349
1350    /// Run a remote probe with its required hard deadline.
1351    ///
1352    /// On deadline the local SSH channel is explicitly aborted. The remote command may outlive
1353    /// that channel, which is why this is reserved for probes whose hard deadline is itself part
1354    /// of the protocol contract, never for staging ownership.
1355    async fn remote_output<S: SshSessionOwner>(
1356        &self,
1357        command: openssh::OwningCommand<S>,
1358        operation: &str,
1359        deadline: BootstrapDeadline,
1360    ) -> anyhow::Result<std::process::Output> {
1361        self.run_abortable_with_deadline(
1362            Self::remote_output_task(command, operation.to_string()),
1363            operation,
1364            deadline,
1365        )
1366        .await
1367    }
1368}
1369
1370fn finish_remote_output_capture(
1371    operation: &str,
1372    stream: &str,
1373    mut output: CapturedOutput,
1374    reject_truncation: bool,
1375) -> anyhow::Result<Vec<u8>> {
1376    if let Some(error) = output.read_error.take() {
1377        return Err(error).with_context(|| format!("failed to read {operation} {stream}"));
1378    }
1379    if output.truncated && reject_truncation {
1380        anyhow::bail!(
1381            "{operation} {stream} exceeded the {}-byte capture limit",
1382            DIAGNOSTIC_CAPTURE_LIMIT
1383        );
1384    }
1385    if output.truncated {
1386        Ok(output.rendered().into_bytes())
1387    } else {
1388        Ok(output.bytes)
1389    }
1390}
1391
1392#[derive(Clone, Copy)]
1393struct BootstrapDeadline(std::time::Duration);
1394
1395impl BootstrapDeadline {
1396    const fn new(duration: std::time::Duration) -> Self {
1397        Self(duration)
1398    }
1399
1400    fn at_least(self, minimum: std::time::Duration) -> Self {
1401        Self(std::cmp::max(self.0, minimum))
1402    }
1403
1404    async fn run<T>(
1405        self,
1406        operation: &str,
1407        future: impl std::future::Future<Output = anyhow::Result<T>>,
1408    ) -> anyhow::Result<T> {
1409        self.wait(operation, future).await?
1410    }
1411
1412    async fn wait<T>(
1413        self,
1414        operation: &str,
1415        future: impl std::future::Future<Output = T>,
1416    ) -> anyhow::Result<T> {
1417        tokio::time::timeout(self.0, future).await.with_context(|| {
1418            format!(
1419                "{operation} timed out after {}",
1420                humantime::format_duration(self.0)
1421            )
1422        })
1423    }
1424}
1425
1426mod deploy;
1427pub mod port_ranges;
1428pub mod protocol;
1429pub mod streams;
1430pub mod tls;
1431pub mod tracelog;
1432
1433/// Network profile for TCP configuration tuning
1434///
1435/// Profiles provide pre-configured settings optimized for different network environments.
1436/// The Datacenter profile is optimized for high-bandwidth, low-latency datacenter networks,
1437/// while the Internet profile uses more conservative settings suitable for internet connections.
1438#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
1439pub enum NetworkProfile {
1440    /// Optimized for datacenter networks: <1ms RTT, 25-100 Gbps
1441    /// Uses aggressive buffer sizes
1442    #[default]
1443    Datacenter,
1444    /// Conservative settings for internet connections
1445    /// Uses standard buffer sizes
1446    Internet,
1447}
1448
1449impl std::fmt::Display for NetworkProfile {
1450    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1451        match self {
1452            Self::Datacenter => write!(f, "datacenter"),
1453            Self::Internet => write!(f, "internet"),
1454        }
1455    }
1456}
1457
1458impl std::str::FromStr for NetworkProfile {
1459    type Err = String;
1460    fn from_str(s: &str) -> Result<Self, Self::Err> {
1461        match s.to_lowercase().as_str() {
1462            "datacenter" => Ok(Self::Datacenter),
1463            "internet" => Ok(Self::Internet),
1464            _ => Err(format!(
1465                "invalid network profile '{}', expected 'datacenter' or 'internet'",
1466                s
1467            )),
1468        }
1469    }
1470}
1471
1472/// Datacenter profile: buffer size for remote copy operations (16 MiB)
1473pub const DATACENTER_REMOTE_COPY_BUFFER_SIZE: usize = 16 * 1024 * 1024;
1474
1475/// Internet profile: buffer size for remote copy operations (2 MiB)
1476pub const INTERNET_REMOTE_COPY_BUFFER_SIZE: usize = 2 * 1024 * 1024;
1477
1478impl NetworkProfile {
1479    /// Returns the default maximum transfer buffer and file I/O request size for this profile.
1480    ///
1481    /// Datacenter uses 16 MiB and internet uses 2 MiB. Per-file I/O limits are capped for
1482    /// small files; individual disk and network operations can be shorter.
1483    pub fn default_remote_copy_buffer_size(&self) -> usize {
1484        match self {
1485            Self::Datacenter => DATACENTER_REMOTE_COPY_BUFFER_SIZE,
1486            Self::Internet => INTERNET_REMOTE_COPY_BUFFER_SIZE,
1487        }
1488    }
1489}
1490
1491/// Configuration for TCP connections
1492///
1493/// Used to configure TCP listeners and clients for file transfers.
1494#[derive(Debug, Clone)]
1495pub struct TcpConfig {
1496    /// Port ranges to use for TCP connections (e.g., "8000-8999,9000-9999")
1497    pub port_ranges: Option<String>,
1498    /// Connection timeout for remote operations (seconds)
1499    pub conn_timeout_sec: u64,
1500    /// Network profile for tuning (default: Datacenter)
1501    pub network_profile: NetworkProfile,
1502    /// Maximum transfer buffer and file I/O request size (defaults to profile-specific value).
1503    pub buffer_size: Option<usize>,
1504    /// Maximum retained receiver scratch per data connection; defaults to min(chunk, 2 MiB).
1505    /// Zero disables retention without changing I/O chunk sizes.
1506    pub buffer_retention_limit: Option<usize>,
1507    /// Liveness budget for every rcp TCP connection (seconds), 0 disables it.
1508    /// See [`configure_tcp_socket`].
1509    pub keepalive_sec: u64,
1510}
1511
1512/// Default ceiling for retained receiver scratch per data connection.
1513/// The effective default also respects smaller configured I/O chunks.
1514pub const DEFAULT_COPY_BUFFER_RETENTION_LIMIT: usize = 2 * 1024 * 1024;
1515
1516/// Default ceiling for concurrent remote data connections.
1517pub const DEFAULT_MAX_CONNECTIONS: usize = 100;
1518
1519/// Default multiplier for pending writes (4× max_connections).
1520pub const DEFAULT_PENDING_WRITES_MULTIPLIER: usize = 4;
1521
1522/// Default liveness budget for an rcp TCP connection (seconds).
1523///
1524/// Detects a vanished peer host in about two minutes while surviving any stall shorter than that.
1525/// Exposed as `--remote-keepalive-sec`; see [`configure_tcp_socket`].
1526pub const DEFAULT_REMOTE_KEEPALIVE_SEC: u64 = 120;
1527
1528/// Validated capacities used by the remote file-transfer pipeline.
1529#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1530pub struct ResolvedRemoteConcurrency {
1531    files_in_flight: common::ConcurrencyLimit,
1532    max_connections: std::num::NonZeroUsize,
1533    max_pending_files: std::num::NonZeroUsize,
1534}
1535
1536impl ResolvedRemoteConcurrency {
1537    #[must_use]
1538    pub const fn files_in_flight(self) -> common::ConcurrencyLimit {
1539        self.files_in_flight
1540    }
1541
1542    #[must_use]
1543    pub const fn max_connections(self) -> std::num::NonZeroUsize {
1544        self.max_connections
1545    }
1546
1547    #[must_use]
1548    pub const fn max_pending_files(self) -> std::num::NonZeroUsize {
1549        self.max_pending_files
1550    }
1551}
1552
1553/// Resolve and validate all capacities that become Tokio semaphores in remote copy.
1554pub fn resolve_remote_concurrency(
1555    files_in_flight: common::ConcurrencyLimit,
1556    max_connections: std::num::NonZeroUsize,
1557    pending_writes_multiplier: std::num::NonZeroUsize,
1558) -> anyhow::Result<ResolvedRemoteConcurrency> {
1559    let max_connections = effective_max_connections(files_in_flight, max_connections);
1560    if max_connections.get() > tokio::sync::Semaphore::MAX_PERMITS {
1561        anyhow::bail!(
1562            "effective stream capacity {} exceeds the Tokio semaphore maximum {}",
1563            max_connections,
1564            tokio::sync::Semaphore::MAX_PERMITS,
1565        );
1566    }
1567    let max_pending_files = max_connections
1568        .get()
1569        .checked_mul(pending_writes_multiplier.get())
1570        .context("pending file capacity overflow")?;
1571    if max_pending_files > tokio::sync::Semaphore::MAX_PERMITS {
1572        anyhow::bail!(
1573            "pending file capacity {} exceeds the Tokio semaphore maximum {}",
1574            max_pending_files,
1575            tokio::sync::Semaphore::MAX_PERMITS,
1576        );
1577    }
1578    Ok(ResolvedRemoteConcurrency {
1579        files_in_flight,
1580        max_connections,
1581        max_pending_files: std::num::NonZeroUsize::new(max_pending_files)
1582            .expect("nonzero factors have a nonzero product"),
1583    })
1584}
1585
1586/// Intersect the configured data-stream ceiling with the file-work ceiling.
1587#[must_use]
1588fn effective_max_connections(
1589    files_in_flight: common::ConcurrencyLimit,
1590    configured: std::num::NonZeroUsize,
1591) -> std::num::NonZeroUsize {
1592    match files_in_flight.meet(common::ConcurrencyLimit::Limited(configured)) {
1593        common::ConcurrencyLimit::Limited(value) => value,
1594        common::ConcurrencyLimit::Unlimited => {
1595            unreachable!("a finite connection ceiling always makes the intersection finite")
1596        }
1597    }
1598}
1599
1600impl Default for TcpConfig {
1601    fn default() -> Self {
1602        Self {
1603            port_ranges: None,
1604            conn_timeout_sec: 15,
1605            network_profile: NetworkProfile::default(),
1606            buffer_size: None,
1607            buffer_retention_limit: None,
1608            keepalive_sec: DEFAULT_REMOTE_KEEPALIVE_SEC,
1609        }
1610    }
1611}
1612
1613impl TcpConfig {
1614    /// Get the effective buffer size (explicit or profile default)
1615    pub fn effective_buffer_size(&self) -> usize {
1616        self.buffer_size
1617            .unwrap_or_else(|| self.network_profile.default_remote_copy_buffer_size())
1618    }
1619    /// Get the explicit receiver retention limit, or min(effective I/O chunk, 2 MiB).
1620    /// This does not change the I/O chunk size.
1621    pub fn effective_buffer_retention_limit(&self) -> usize {
1622        self.buffer_retention_limit.unwrap_or_else(|| {
1623            self.effective_buffer_size()
1624                .min(DEFAULT_COPY_BUFFER_RETENTION_LIMIT)
1625        })
1626    }
1627}
1628
1629#[derive(Debug, PartialEq, Eq, Clone, Hash)]
1630pub struct SshSession {
1631    pub user: Option<String>,
1632    pub host: String,
1633    pub port: Option<u16>,
1634}
1635
1636impl SshSession {
1637    pub fn local() -> Self {
1638        Self {
1639            user: None,
1640            host: "localhost".to_string(),
1641            port: None,
1642        }
1643    }
1644
1645    /// Return the host spelling accepted by OpenSSH's direct argv interface.
1646    fn openssh_host(&self) -> &str {
1647        let Some(host) = self
1648            .host
1649            .strip_prefix('[')
1650            .and_then(|host| host.strip_suffix(']'))
1651        else {
1652            return &self.host;
1653        };
1654        let address = match host.split_once('%') {
1655            Some((_, "")) => return &self.host,
1656            Some((address, _scope_id)) => address,
1657            None => host,
1658        };
1659        address
1660            .parse::<std::net::Ipv6Addr>()
1661            .map_or(&self.host, |_| host)
1662    }
1663}
1664
1665// re-export is_localhost from common for convenience
1666pub use common::is_localhost;
1667
1668async fn setup_ssh_session(
1669    session: &SshSession,
1670    preparation: &PreparationContext,
1671    deadline: BootstrapDeadline,
1672) -> anyhow::Result<ManagedSshSession> {
1673    setup_ssh_session_with_program(session, preparation, std::path::Path::new("ssh"), deadline)
1674        .await
1675}
1676
1677async fn setup_ssh_session_with_program(
1678    session: &SshSession,
1679    preparation: &PreparationContext,
1680    ssh_program: &std::path::Path,
1681    deadline: BootstrapDeadline,
1682) -> anyhow::Result<ManagedSshSession> {
1683    let session = session.clone();
1684    let ssh_program = ssh_program.to_path_buf();
1685    let cleanup = preparation.cleanup.clone();
1686    let control_directory_exclusions = preparation.control_directory_exclusions.clone();
1687    let connect = tokio::spawn(async move {
1688        let control_dir =
1689            run_disposable_blocking(cleanup.clone(), "rcp-ssh-control-select", move || {
1690                ssh_control_directory(&control_directory_exclusions)
1691                    .context("no usable SSH control directory found outside local copy operands")
1692            })
1693            .await?;
1694        launch_ssh_master(&session, &control_dir, &ssh_program, cleanup)
1695            .await
1696            .context("Failed to establish SSH connection")
1697    });
1698    preparation
1699        .run_abortable_with_deadline(connect, "SSH session setup", deadline)
1700        .await
1701}
1702
1703/// Run filesystem preflight on a disposable OS thread.
1704///
1705/// The caller may abandon the receiver at a bootstrap deadline without waiting for an uninterruptible
1706/// filesystem syscall. These probes launch no process, and a value produced after abandonment is
1707/// dropped on the worker thread.
1708async fn run_disposable_blocking<T, F>(
1709    cleanup: RemoteCleanup,
1710    thread_name: &'static str,
1711    operation: F,
1712) -> anyhow::Result<T>
1713where
1714    T: Send + 'static,
1715    F: FnOnce() -> anyhow::Result<T> + Send + 'static,
1716{
1717    let (result_tx, result_rx) = tokio::sync::oneshot::channel();
1718    cleanup
1719        .submit_disposable(thread_name, move || {
1720            let _ = result_tx.send(operation());
1721        })
1722        .with_context(|| format!("failed to start {thread_name} worker"))?;
1723    result_rx
1724        .await
1725        .with_context(|| format!("{thread_name} worker exited without a result"))?
1726}
1727
1728struct StopSocketProbe(std::sync::Arc<std::sync::atomic::AtomicBool>);
1729
1730impl Drop for StopSocketProbe {
1731    fn drop(&mut self) {
1732        self.0.store(true, std::sync::atomic::Ordering::Release);
1733    }
1734}
1735
1736async fn wait_for_ssh_control_socket<F>(
1737    cleanup: &RemoteCleanup,
1738    mut inspect: F,
1739) -> anyhow::Result<()>
1740where
1741    F: FnMut() -> anyhow::Result<bool> + Send + 'static,
1742{
1743    let stopped = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1744    let _stop_on_exit = StopSocketProbe(stopped.clone());
1745    run_disposable_blocking(cleanup.clone(), "rcp-ssh-control-inspect", move || {
1746        while !stopped.load(std::sync::atomic::Ordering::Acquire) {
1747            if inspect()? {
1748                return Ok(());
1749            }
1750            std::thread::sleep(std::time::Duration::from_millis(10));
1751        }
1752        Ok(())
1753    })
1754    .await
1755}
1756
1757/// Launch and retain the foreground OpenSSH multiplex master.
1758fn ssh_master_launcher_command(ssh_program: &std::path::Path) -> tokio::process::Command {
1759    // launch a known-local shell first so resolving the configured SSH program happens inside a
1760    // child that the bootstrap deadline can kill and reap. Calling Command::new(ssh_program)
1761    // directly can block the Tokio worker in the parent's synchronous spawn handshake.
1762    let mut launcher = tokio::process::Command::new("/bin/sh");
1763    launcher
1764        .args(["-c", "exec \"$@\"", "rcp-ssh-master"])
1765        .arg(ssh_program);
1766    launcher
1767}
1768
1769async fn launch_ssh_master(
1770    session: &SshSession,
1771    control_dir: &std::path::Path,
1772    ssh_program: &std::path::Path,
1773    cleanup: RemoteCleanup,
1774) -> anyhow::Result<ManagedSshSession> {
1775    tracing::debug!("Connecting to SSH destination: {}", session.host);
1776    tracing::debug!("Using SSH control directory: {}", control_dir.display());
1777    let control_dir = control_dir.to_path_buf();
1778    let directory = run_disposable_blocking(cleanup.clone(), "rcp-ssh-control-create", move || {
1779        let mut temp = tempfile::Builder::new();
1780        temp.prefix(".ssh-connection");
1781        temp.tempdir_in(control_dir)
1782            .context("failed to create SSH control directory")
1783    })
1784    .await?;
1785    // persist the TempDir only after the disposable worker returned it. If that wait is abandoned,
1786    // tempfile cleanup stays on the worker; after persistence every exit is guarded below.
1787    let mut preparing = PreparingSshMaster::new(directory.keep(), cleanup.clone());
1788    let log = preparing.control_directory().join("log");
1789    let control_path = preparing.control_directory().join("master");
1790    let mut launcher = ssh_master_launcher_command(ssh_program);
1791    launcher
1792        .kill_on_drop(true)
1793        .stdin(std::process::Stdio::null())
1794        .stdout(std::process::Stdio::null())
1795        .stderr(std::process::Stdio::null())
1796        .arg("-E")
1797        .arg(&log)
1798        .arg("-S")
1799        .arg(&control_path)
1800        .arg("-M")
1801        .arg("-N")
1802        .arg("-o")
1803        .arg("BatchMode=yes")
1804        .arg("-o")
1805        .arg("StrictHostKeyChecking=no")
1806        .arg("-o")
1807        .arg("ForkAfterAuthentication=no")
1808        .arg("-o")
1809        .arg("ControlPersist=no");
1810    if let Some(port) = session.port {
1811        launcher.arg("-p").arg(port.to_string());
1812    }
1813    if let Some(user) = session.user.as_deref() {
1814        launcher.arg("-l").arg(user);
1815    }
1816    let launcher = launcher
1817        .arg(session.openssh_host())
1818        .spawn()
1819        .context("failed to launch SSH multiplex master")?;
1820    preparing.retain_launcher(launcher);
1821    {
1822        let socket_path = control_path.clone();
1823        let socket_ready = wait_for_ssh_control_socket(&cleanup, move || {
1824            socket_path
1825                .try_exists()
1826                .context("failed to inspect SSH multiplex control socket")
1827        });
1828        tokio::pin!(socket_ready);
1829        tokio::select! {
1830            biased;
1831            status = preparing.launcher_mut().wait() => {
1832                let status = status.context("failed to wait for SSH multiplex master")?;
1833                let diagnostic_path = log.clone();
1834                let diagnostic = run_disposable_blocking(
1835                    cleanup.clone(),
1836                    "rcp-ssh-log-read",
1837                    move || Ok(std::fs::read_to_string(diagnostic_path).unwrap_or_default()),
1838                )
1839                .await?;
1840                anyhow::bail!(
1841                    "SSH multiplex master exited with {status}: {}",
1842                    diagnostic.trim()
1843                );
1844            }
1845            result = &mut socket_ready => {
1846                result?;
1847            }
1848        }
1849    }
1850    // use the native multiplex client so every remote command opens the retained control socket
1851    // directly. The process backend synchronously spawns a fresh local `ssh` executable for each
1852    // command, which would create an uninterruptible pre-deadline PATH/exec window.
1853    let session =
1854        openssh::Session::resume_mux(control_path.into_boxed_path(), Some(log.into_boxed_path()));
1855    Ok(preparing.into_managed(session))
1856}
1857
1858/// Where to put the SSH connection-multiplexing socket.
1859///
1860/// `openssh` defaults this to `$XDG_STATE_HOME`, else `$HOME/.local/state`, and the resulting
1861/// socket path is subject to `sockaddr_un`'s 108-byte `sun_path` limit -- a limit that counts the
1862/// terminating NUL, the `/.ssh-connectionXXXXXX/master` the library appends, AND the further
1863/// `.XXXXXXXXXXXXXXXX` that ssh(1) itself appends while creating the socket before renaming it.
1864/// That leaves only about 48 bytes for `$HOME`, and exceeding it fails with ssh's rather opaque
1865/// `unix_listener: path "..." too long for Unix domain socket`, which names neither `$HOME` nor
1866/// rcp. (Kept as an inline span rather than an indented block: rustdoc reads an indented block as
1867/// a doctest, and a doctest on a private item is denied by the workspace rustdoc lints.)
1868///
1869/// 48 bytes is not a comfortable margin: container workspaces, network homes and CI checkout paths
1870/// routinely run longer.
1871///
1872/// Candidates are tried in order and the first genuinely usable one wins:
1873///
1874/// 1. `$XDG_RUNTIME_DIR` -- typically `/run/user/<uid>`, ~14 bytes, and semantically the right
1875///    home for a runtime socket: per-user, mode 0700, cleared when the session ends.
1876/// 2. `std::env::temp_dir()` -- honours `TMPDIR`, so it follows a sandbox that redirects it.
1877/// 3. `/tmp` -- for when `TMPDIR` itself points somewhere long or unusable.
1878/// 4. `$XDG_STATE_HOME` -- the first location used by `openssh`'s own default.
1879/// 5. `$HOME` -- a shorter final fallback when the state directory is absent or unusable.
1880///
1881/// Falling through the list is the point rather than a nicety: the environments named above as
1882/// motivation -- containers, CI runners, `su` sessions -- are exactly the ones that tend NOT to set
1883/// `$XDG_RUNTIME_DIR`, so stopping at step 1 would have left the intended beneficiaries on the very
1884/// `$HOME`-derived path this exists to avoid. The state candidate preserves the library's first
1885/// fallback, while the shorter home alternative remains available when its `.local/state` path
1886/// would be unusable. The launcher creates the socket directory through `tempfile`, which makes it
1887/// mode 0700, so a shared parent is still private. Candidates inside a canonical local operand are
1888/// deliberately excluded: an unreapable SSH master requires its private directory to survive until
1889/// process exit, so that directory must not appear inside a copied tree. Remote-only operands impose
1890/// no such exclusion, regardless of the master's working directory. The filesystem root is also
1891/// omitted because no absolute socket candidate could otherwise be selected.
1892///
1893/// Returns `None` only when none of the candidates can safely hold a control socket; callers then
1894/// fail before launching SSH rather than selecting a path known to be broken.
1895fn ssh_control_directory(excluded_roots: &[std::path::PathBuf]) -> Option<std::path::PathBuf> {
1896    select_ssh_control_directory_from_environment(
1897        std::env::var_os("XDG_RUNTIME_DIR").map(Into::into),
1898        std::env::temp_dir(),
1899        std::path::PathBuf::from("/tmp"),
1900        std::env::var_os("XDG_STATE_HOME").map(Into::into),
1901        std::env::var_os("HOME").map(Into::into),
1902        excluded_roots,
1903    )
1904}
1905
1906fn select_ssh_control_directory_from_environment(
1907    runtime_dir: Option<std::path::PathBuf>,
1908    temp_dir: std::path::PathBuf,
1909    system_temp_dir: std::path::PathBuf,
1910    state_dir: Option<std::path::PathBuf>,
1911    home: Option<std::path::PathBuf>,
1912    excluded_roots: &[std::path::PathBuf],
1913) -> Option<std::path::PathBuf> {
1914    let mut candidates = Vec::with_capacity(5);
1915    candidates.extend(runtime_dir);
1916    candidates.push(temp_dir);
1917    candidates.push(system_temp_dir);
1918    candidates.extend(state_dir);
1919    candidates.extend(home);
1920    let excluded_roots: Vec<_> = excluded_roots
1921        .iter()
1922        .filter_map(|path| {
1923            std::fs::canonicalize(path)
1924                .ok()
1925                .or_else(|| std::path::absolute(path).ok())
1926        })
1927        .filter(|path| path.parent().is_some())
1928        .collect();
1929    select_ssh_control_directory(candidates.into_iter().filter(|candidate| {
1930        excluded_roots.is_empty()
1931            || std::fs::canonicalize(candidate).is_ok_and(|candidate| {
1932                excluded_roots
1933                    .iter()
1934                    .all(|excluded_root| !candidate.starts_with(excluded_root))
1935            })
1936    }))
1937}
1938
1939fn select_ssh_control_directory(
1940    candidates: impl IntoIterator<Item = std::path::PathBuf>,
1941) -> Option<std::path::PathBuf> {
1942    candidates
1943        .into_iter()
1944        .find(|dir| control_dir_is_usable(dir))
1945}
1946
1947/// Longest socket path `sockaddr_un` can hold, counting the terminating NUL.
1948const SUN_PATH_MAX: usize = 108;
1949
1950/// What gets appended to the control directory before the socket finally exists:
1951///
1952/// - `/.ssh-connectionXXXXXX` (22) -- the private dir our launcher makes via `tempfile`
1953/// - `/master` (7) -- the `ControlPath` itself
1954/// - `.XXXXXXXXXXXXXXXX` (17) -- the temporary name ssh(1) creates it under before renaming
1955const CONTROL_PATH_SUFFIX: usize = 22 + 7 + 17;
1956
1957/// Whether `dir` can actually host the control socket: short enough to leave room for everything
1958/// appended to it, and writable by us.
1959///
1960/// Both halves matter. Length is the original bug. Writability is what makes the candidate list
1961/// above mean anything -- a directory that merely *exists* is not enough, and `$XDG_RUNTIME_DIR`
1962/// surviving into a `su`/`sudo -u` session while pointing at the original user's `/run/user/<uid>`
1963/// is a common way to get one that is present but unusable. Without this check we would select it
1964/// confidently and fail, instead of moving on to `/tmp`.
1965fn control_dir_is_usable(dir: &std::path::Path) -> bool {
1966    if dir.as_os_str().is_empty() || !dir.is_dir() {
1967        return false;
1968    }
1969    if dir.as_os_str().len() + CONTROL_PATH_SUFFIX >= SUN_PATH_MAX {
1970        tracing::debug!(
1971            "skipping SSH control directory {}: too long to hold the socket path",
1972            dir.display()
1973        );
1974        return false;
1975    }
1976    // probe rather than inspect the mode: ownership, ACLs and read-only mounts all decide this,
1977    // and creating a directory is exactly what `openssh` is about to do anyway.
1978    match tempfile::Builder::new()
1979        .prefix(".rcp-control-probe-")
1980        .tempdir_in(dir)
1981    {
1982        Ok(probe) => {
1983            drop(probe);
1984            true
1985        }
1986        Err(error) => {
1987            tracing::debug!(
1988                "skipping SSH control directory {}: not writable: {:#}",
1989                dir.display(),
1990                &error
1991            );
1992            false
1993        }
1994    }
1995}
1996
1997/// Retrieve a remote home directory with a caller-selected bootstrap timeout.
1998#[instrument(skip(cleanup, local_operand_roots))]
1999pub async fn get_remote_home_for_session_with_timeout(
2000    session: &SshSession,
2001    cleanup: &RemoteCleanup,
2002    bootstrap_timeout: std::time::Duration,
2003    local_operand_roots: &[std::path::PathBuf],
2004) -> anyhow::Result<std::path::PathBuf> {
2005    let preparation = PreparationContext::uncancelled(cleanup.clone())
2006        .with_control_directory_exclusions(local_operand_roots.to_vec().into());
2007    let deadline = BootstrapDeadline::new(bootstrap_timeout);
2008    let ssh_session = setup_ssh_session(session, &preparation, deadline).await?;
2009    let home = get_remote_home_with_context(&ssh_session, &preparation, deadline).await?;
2010    Ok(std::path::PathBuf::from(home))
2011}
2012
2013#[instrument(skip(process))]
2014pub async fn wait_for_rcpd_process(mut process: RcpdProcess) -> anyhow::Result<()> {
2015    let child = process
2016        .child
2017        .take()
2018        .expect("an owned rcpd process retains its child until wait");
2019    let stderr_drain = process
2020        .stderr_drain
2021        .take()
2022        .expect("an owned rcpd process retains its stderr collector until wait");
2023    let stdout_drain = process.stdout_drain.take();
2024    tracing::info!("Waiting on rcpd server on: {:?}", child);
2025    // closing the child's stdin is the daemon watchdog signal. Always join the output collectors,
2026    // even when waiting fails, so teardown neither detaches tasks nor loses bounded diagnostics.
2027    let wait = tokio::time::timeout(std::time::Duration::from_secs(10), child.wait()).await;
2028    let (stderr, stdout) = tokio::join!(
2029        finish_rcpd_output_drain(stderr_drain, "stderr"),
2030        finish_optional_rcpd_output_drain(stdout_drain, "stdout"),
2031    );
2032    let status = wait
2033        .context("Timeout waiting for rcpd process to exit")?
2034        .context("Failed to wait for rcpd process")?;
2035    if !status.success() {
2036        return Err(anyhow!(
2037            "rcpd command failed on remote host, status code: {:?}\nstdout:\n{}\nstderr:\n{}",
2038            status.code(),
2039            stdout.rendered(),
2040            stderr.rendered()
2041        ));
2042    }
2043    for (stream, output) in [("stdout", stdout), ("stderr", stderr)] {
2044        if let Some(error) = output.read_error {
2045            tracing::debug!("rcpd {stream} collector failed after startup: {error:#}");
2046        }
2047        if output.truncated {
2048            tracing::debug!("rcpd {stream} diagnostic tail was truncated after live forwarding");
2049        }
2050    }
2051    Ok(())
2052}
2053
2054async fn finish_rcpd_output_drain(
2055    task: AbortOnDropTask<CapturedOutput>,
2056    stream: &'static str,
2057) -> CapturedOutput {
2058    match tokio::time::timeout(RCPD_OUTPUT_DRAIN_GRACE, task.join()).await {
2059        Ok(Ok(output)) => output,
2060        Ok(Err(error)) => {
2061            tracing::debug!("rcpd {stream} collector task failed: {error:#}");
2062            CapturedOutput::default()
2063        }
2064        Err(_) => {
2065            tracing::debug!("rcpd {stream} collector did not finish during drain grace");
2066            CapturedOutput::default()
2067        }
2068    }
2069}
2070
2071async fn finish_optional_rcpd_output_drain(
2072    task: Option<AbortOnDropTask<CapturedOutput>>,
2073    stream: &'static str,
2074) -> CapturedOutput {
2075    match task {
2076        Some(task) => finish_rcpd_output_drain(task, stream).await,
2077        None => CapturedOutput::default(),
2078    }
2079}
2080
2081/// Escape a string for safe use in POSIX shell single quotes
2082///
2083/// Wraps the string in single quotes and escapes any single quotes within
2084pub(crate) fn shell_escape(s: &str) -> String {
2085    format!("'{}'", s.replace('\'', r"'\''"))
2086}
2087
2088/// Marker error used when a remote host has no usable HOME directory.
2089#[derive(Debug)]
2090struct RemoteHomeUnavailable(String);
2091
2092impl std::fmt::Display for RemoteHomeUnavailable {
2093    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2094        formatter.write_str(&self.0)
2095    }
2096}
2097
2098impl std::error::Error for RemoteHomeUnavailable {}
2099
2100/// Validate and retrieve the HOME directory on a remote host.
2101///
2102/// The lookup rejects an unset or empty HOME so callers cannot accidentally construct paths such
2103/// as `/.cache/rcp/bin/rcpd-{version}`.
2104///
2105/// # Errors
2106///
2107/// Returns an error when the lookup fails or HOME is unset or empty.
2108async fn get_remote_home_with_context<S: SshSessionOwner>(
2109    session: &S,
2110    preparation: &PreparationContext,
2111    deadline: BootstrapDeadline,
2112) -> anyhow::Result<String> {
2113    if let Ok(home_override) = std::env::var("RCP_REMOTE_HOME_OVERRIDE")
2114        && !home_override.is_empty()
2115    {
2116        return Ok(home_override);
2117    }
2118    let mut command = openssh::Session::to_command(session.clone(), "sh");
2119    command.arg("-c").arg("echo \"${HOME:?HOME not set}\"");
2120    run_remote_home_probe(command, preparation, deadline).await
2121}
2122
2123async fn run_remote_home_probe<S: SshSessionOwner>(
2124    command: openssh::OwningCommand<S>,
2125    preparation: &PreparationContext,
2126    deadline: BootstrapDeadline,
2127) -> anyhow::Result<String> {
2128    let output = preparation
2129        .remote_output(command, "remote HOME lookup", deadline)
2130        .await
2131        .context("failed to check HOME environment variable on remote host")?;
2132
2133    if !output.status.success() {
2134        let stderr = String::from_utf8_lossy(&output.stderr);
2135        return Err(anyhow::Error::new(RemoteHomeUnavailable(format!(
2136            "HOME environment variable is not set on remote host\n\
2137            \n\
2138            stderr: {}\n\
2139            \n\
2140            The HOME environment variable is required for remote ~ expansion and rcpd deployment.\n\
2141            Please ensure your SSH configuration preserves environment variables.",
2142            stderr
2143        ))));
2144    }
2145
2146    let home = String::from_utf8_lossy(&output.stdout).trim().to_string();
2147
2148    if home.is_empty() {
2149        return Err(anyhow::Error::new(RemoteHomeUnavailable(
2150            "HOME environment variable is empty on remote host\n\
2151            \n\
2152            The HOME environment variable is required for remote ~ expansion and rcpd deployment.\n\
2153            Please ensure your SSH configuration sets HOME correctly."
2154                .to_string(),
2155        )));
2156    }
2157
2158    Ok(home)
2159}
2160
2161#[cfg(test)]
2162mod shell_escape_tests {
2163    use super::*;
2164
2165    #[test]
2166    fn test_shell_escape_simple() {
2167        assert_eq!(shell_escape("simple"), "'simple'");
2168    }
2169
2170    #[test]
2171    fn test_shell_escape_with_spaces() {
2172        assert_eq!(shell_escape("path with spaces"), "'path with spaces'");
2173    }
2174
2175    #[test]
2176    fn test_shell_escape_with_single_quote() {
2177        // single quote becomes: close quote, escaped quote, open quote
2178        assert_eq!(
2179            shell_escape("path'with'quotes"),
2180            r"'path'\''with'\''quotes'"
2181        );
2182    }
2183
2184    #[test]
2185    fn test_shell_escape_injection_attempt() {
2186        // attempt to inject command
2187        assert_eq!(shell_escape("foo; rm -rf /"), "'foo; rm -rf /'");
2188        // the semicolon is now safely quoted and won't execute
2189    }
2190
2191    #[test]
2192    fn test_shell_escape_special_chars() {
2193        assert_eq!(shell_escape("$PATH && echo pwned"), "'$PATH && echo pwned'");
2194        // special chars are safely quoted
2195    }
2196}
2197
2198trait DiscoverySession {
2199    fn test_executable<'a>(
2200        &'a self,
2201        path: &'a str,
2202    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<bool>> + Send + 'a>>;
2203    fn find_in_path<'a>(
2204        &'a self,
2205        binary: &'a str,
2206    ) -> std::pin::Pin<
2207        Box<dyn std::future::Future<Output = anyhow::Result<Option<String>>> + Send + 'a>,
2208    >;
2209    fn remote_home<'a>(
2210        &'a self,
2211    ) -> std::pin::Pin<
2212        Box<dyn std::future::Future<Output = anyhow::Result<Option<String>>> + Send + 'a>,
2213    >;
2214}
2215
2216struct RealDiscoverySession<'a, S> {
2217    session: &'a S,
2218    preparation: &'a PreparationContext,
2219    deadline: BootstrapDeadline,
2220}
2221
2222impl<S: SshSessionOwner> DiscoverySession for RealDiscoverySession<'_, S> {
2223    fn test_executable<'b>(
2224        &'b self,
2225        path: &'b str,
2226    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<bool>> + Send + 'b>>
2227    {
2228        Box::pin(async move {
2229            let mut command = openssh::Session::to_command(self.session.clone(), "sh");
2230            command
2231                .arg("-c")
2232                .arg(format!("test -x {}", shell_escape(path)));
2233            let output = self
2234                .preparation
2235                .remote_output(command, "remote executable discovery", self.deadline)
2236                .await?;
2237            Ok(output.status.success())
2238        })
2239    }
2240    fn find_in_path<'b>(
2241        &'b self,
2242        binary: &'b str,
2243    ) -> std::pin::Pin<
2244        Box<dyn std::future::Future<Output = anyhow::Result<Option<String>>> + Send + 'b>,
2245    > {
2246        Box::pin(async move {
2247            let mut command = openssh::Session::to_command(self.session.clone(), "sh");
2248            command
2249                .arg("-c")
2250                .arg(RCPD_PATH_DISCOVERY_SCRIPT)
2251                .arg("rcp-path-discovery")
2252                .arg(binary);
2253            let output = self
2254                .preparation
2255                .remote_output(command, "remote PATH discovery", self.deadline)
2256                .await?;
2257            if output.status.success() {
2258                let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
2259                if !path.is_empty() {
2260                    return Ok(Some(path));
2261                }
2262            }
2263            Ok(None)
2264        })
2265    }
2266    fn remote_home<'b>(
2267        &'b self,
2268    ) -> std::pin::Pin<
2269        Box<dyn std::future::Future<Output = anyhow::Result<Option<String>>> + Send + 'b>,
2270    > {
2271        Box::pin(async move {
2272            match get_remote_home_with_context(self.session, self.preparation, self.deadline).await
2273            {
2274                Ok(home) => Ok(Some(home)),
2275                Err(error) if error.downcast_ref::<RemoteHomeUnavailable>().is_some() => Ok(None),
2276                Err(error) => Err(error),
2277            }
2278        })
2279    }
2280}
2281
2282/// Discover rcpd binary on remote host
2283///
2284/// Searches in the following order:
2285/// 1. Explicit path (if provided)
2286/// 2. Same directory as local rcp binary
2287/// 3. PATH (via the shell's `command -v rcpd`)
2288/// 4. Deployed cache directory (~/.cache/rcp/bin/rcpd-{version})
2289///
2290/// The cache is checked last as it contains auto-deployed binaries and should
2291/// only be used as a fallback after checking user-installed locations.
2292///
2293/// Returns the path to rcpd if found, otherwise an error
2294async fn discover_rcpd_path<S: SshSessionOwner>(
2295    session: &S,
2296    explicit_path: Option<&str>,
2297    preparation: &PreparationContext,
2298    deadline: BootstrapDeadline,
2299) -> anyhow::Result<String> {
2300    let real_session = RealDiscoverySession {
2301        session,
2302        preparation,
2303        deadline,
2304    };
2305    discover_rcpd_path_internal(&real_session, explicit_path, None).await
2306}
2307
2308async fn discover_rcpd_path_internal<S: DiscoverySession + ?Sized>(
2309    session: &S,
2310    explicit_path: Option<&str>,
2311    current_exe_override: Option<std::path::PathBuf>,
2312) -> anyhow::Result<String> {
2313    let local_version = common::version::ProtocolVersion::current();
2314    // try explicit path first
2315    if let Some(path) = explicit_path {
2316        tracing::debug!("Trying explicit rcpd path: {}", path);
2317        if session.test_executable(path).await? {
2318            tracing::info!("Found rcpd at explicit path: {}", path);
2319            return Ok(path.to_string());
2320        }
2321        // explicit path was provided but not found - return error immediately
2322        // don't fall back to other discovery methods
2323        return Err(anyhow::anyhow!(
2324            "rcpd binary not found or not executable at explicit path: {}",
2325            path
2326        ));
2327    }
2328    // try same directory as local rcp binary
2329    if let Ok(current_exe) = current_exe_override
2330        .map(Ok)
2331        .unwrap_or_else(std::env::current_exe)
2332        && let Some(bin_dir) = current_exe.parent()
2333    {
2334        let path = bin_dir.join("rcpd").display().to_string();
2335        tracing::debug!("Trying same directory as rcp: {}", path);
2336        if session.test_executable(&path).await? {
2337            tracing::info!("Found rcpd in same directory as rcp: {}", path);
2338            return Ok(path);
2339        }
2340    }
2341    // try PATH
2342    tracing::debug!("Trying to find rcpd in PATH");
2343    if let Some(path) = session.find_in_path("rcpd").await? {
2344        tracing::info!("Found rcpd in PATH: {}", path);
2345        return Ok(path);
2346    }
2347    // try deployed cache directory as last resort (reuse already-deployed binaries)
2348    // if HOME is not set, skip cache check
2349    let cache_path = match session.remote_home().await? {
2350        Some(home) => {
2351            let path = format!("{}/.cache/rcp/bin/rcpd-{}", home, local_version.cache_tag());
2352            tracing::debug!("Trying deployed cache path: {}", path);
2353            if session.test_executable(&path).await? {
2354                tracing::info!("Found rcpd in deployed cache: {}", path);
2355                return Ok(path);
2356            }
2357            Some(path)
2358        }
2359        None => {
2360            tracing::debug!("HOME not set on remote host, skipping cache directory check");
2361            None
2362        }
2363    };
2364    // build error message with what we searched
2365    let mut searched = vec![];
2366    searched.push("- Same directory as local rcp binary".to_string());
2367    searched.push("- PATH (via 'command -v rcpd')".to_string());
2368    if let Some(path) = cache_path.as_ref() {
2369        searched.push(format!("- Deployed cache: {}", path));
2370    } else {
2371        searched.push("- Deployed cache: (skipped, HOME not set)".to_string());
2372    }
2373    Err(anyhow::anyhow!(
2374        "rcpd binary not found on remote host\n\
2375        \n\
2376        Searched in:\n\
2377        {}\n\
2378        \n\
2379        Options:\n\
2380        - Use automatic deployment: rcp --auto-deploy-rcpd ...\n\
2381        - Install rcpd manually: cargo install rcp-tools-rcp --version {}\n\
2382        - Specify explicit path: rcp --rcpd-path=/path/to/rcpd ...",
2383        searched.join("\n"),
2384        local_version.crate_version()
2385    ))
2386}
2387
2388/// Try to discover rcpd and check version compatibility
2389///
2390/// Combines discovery and version checking into one function for cleaner error handling.
2391/// Returns the path to a compatible rcpd if found, or an error describing the problem.
2392async fn try_discover_and_check_version<S: SshSessionOwner>(
2393    session: &S,
2394    explicit_path: Option<&str>,
2395    remote_host: &str,
2396    preparation: &PreparationContext,
2397    version_probe_timeout: std::time::Duration,
2398) -> anyhow::Result<String> {
2399    // discover rcpd binary on remote host
2400    let rcpd_path = discover_rcpd_path(
2401        session,
2402        explicit_path,
2403        preparation,
2404        BootstrapDeadline::new(version_probe_timeout),
2405    )
2406    .await?;
2407    // check version compatibility
2408    check_rcpd_version(
2409        session,
2410        &rcpd_path,
2411        remote_host,
2412        preparation,
2413        version_probe_timeout,
2414    )
2415    .await?;
2416    Ok(rcpd_path)
2417}
2418
2419/// Check version compatibility between local rcp and remote rcpd
2420///
2421/// Returns Ok if versions are compatible, Err with detailed message if not
2422async fn check_rcpd_version<S: SshSessionOwner>(
2423    session: &S,
2424    rcpd_path: &str,
2425    remote_host: &str,
2426    preparation: &PreparationContext,
2427    version_probe_timeout: std::time::Duration,
2428) -> anyhow::Result<()> {
2429    let local_version = common::version::ProtocolVersion::current();
2430
2431    tracing::debug!("Checking rcpd version on remote host: {}", remote_host);
2432
2433    // run rcpd --protocol-version on remote (call binary directly, no shell)
2434    let mut command = openssh::Session::to_command(session.clone(), rcpd_path.to_string());
2435    command.arg("--protocol-version");
2436    let operation = format!("rcpd --protocol-version probe on remote host '{remote_host}'");
2437    let output = preparation
2438        .remote_output(
2439            command,
2440            &operation,
2441            BootstrapDeadline::new(version_probe_timeout),
2442        )
2443        .await?;
2444
2445    if !output.status.success() {
2446        let stderr = String::from_utf8_lossy(&output.stderr);
2447        return Err(anyhow::anyhow!(
2448            "rcpd --protocol-version failed on remote host '{}'\n\
2449            \n\
2450            stderr: {}\n\
2451            \n\
2452            This may indicate an old version of rcpd that does not support --protocol-version.\n\
2453            Please install a matching version of rcpd on the remote host:\n\
2454            - cargo install rcp-tools-rcp --version {}",
2455            remote_host,
2456            stderr,
2457            local_version.crate_version()
2458        ));
2459    }
2460
2461    let stdout = String::from_utf8_lossy(&output.stdout);
2462    let remote_version = common::version::ProtocolVersion::from_json(stdout.trim())
2463        .context("Failed to parse rcpd version JSON from remote host")?;
2464
2465    tracing::info!(
2466        "Local version: {}, Remote version: {}",
2467        local_version,
2468        remote_version
2469    );
2470
2471    if !local_version.is_compatible_with(&remote_version) {
2472        return Err(anyhow::anyhow!(
2473            "rcpd version mismatch\n\
2474            \n\
2475            Local:  rcp {}\n\
2476            Remote: rcpd {} on host '{}'\n\
2477            \n\
2478            The rcpd version on the remote host must exactly match the rcp version,\n\
2479            including the +w compatibility revision — two builds of the same release can\n\
2480            differ when the development remote protocol or rcpd spawn contract moved\n\
2481            between them (then\n\
2482            reinstall/redeploy the remote build rather than pinning a version).\n\
2483            \n\
2484            To fix this, install the matching version on the remote host:\n\
2485            - ssh {} 'cargo install rcp-tools-rcp --version {}'",
2486            local_version,
2487            remote_version,
2488            remote_host,
2489            shell_escape(remote_host),
2490            local_version.crate_version()
2491        ));
2492    }
2493
2494    Ok(())
2495}
2496
2497/// Connection info received from rcpd after it starts listening.
2498#[derive(Debug, Clone)]
2499pub struct RcpdConnectionInfo {
2500    /// Address rcpd is listening on
2501    pub addr: std::net::SocketAddr,
2502    /// TLS certificate fingerprint (None if encryption disabled)
2503    pub fingerprint: Option<tls::Fingerprint>,
2504    /// Logical file-work ceiling resolved by this daemon.
2505    pub files_in_flight: common::ConcurrencyLimit,
2506    /// Effective data-stream count resolved by this daemon.
2507    pub max_connections: std::num::NonZeroUsize,
2508}
2509
2510/// Format the first stderr record emitted by a successfully started rcpd.
2511#[must_use]
2512pub fn format_rcpd_readiness(
2513    addr: std::net::SocketAddr,
2514    fingerprint: Option<&tls::Fingerprint>,
2515    concurrency: ResolvedRemoteConcurrency,
2516) -> String {
2517    let files_in_flight = match concurrency.files_in_flight() {
2518        common::ConcurrencyLimit::Unlimited => "unlimited".to_string(),
2519        common::ConcurrencyLimit::Limited(value) => value.to_string(),
2520    };
2521    match fingerprint {
2522        Some(fingerprint) => format!(
2523            "RCP_TLS {} {} {} {}",
2524            addr,
2525            tls::fingerprint_to_hex(fingerprint),
2526            files_in_flight,
2527            concurrency.max_connections(),
2528        ),
2529        None => format!(
2530            "RCP_TCP {} {} {}",
2531            addr,
2532            files_in_flight,
2533            concurrency.max_connections(),
2534        ),
2535    }
2536}
2537
2538/// Parse the version-sensitive first stderr record emitted by rcpd.
2539fn parse_rcpd_readiness(line: &str) -> anyhow::Result<RcpdConnectionInfo> {
2540    fn parse_files_in_flight(token: &str) -> anyhow::Result<common::ConcurrencyLimit> {
2541        if token == "unlimited" {
2542            return Ok(common::ConcurrencyLimit::Unlimited);
2543        }
2544        let value = token
2545            .parse::<usize>()
2546            .with_context(|| format!("invalid file limit in rcpd readiness record: {token}"))?;
2547        let value = std::num::NonZeroUsize::new(value).with_context(|| {
2548            format!("invalid zero file limit in rcpd readiness record: {token}")
2549        })?;
2550        Ok(common::ConcurrencyLimit::Limited(value))
2551    }
2552
2553    let (kind, rest) = line
2554        .split_once(' ')
2555        .context("rcpd readiness record is missing its fields")?;
2556    let parts: Vec<&str> = rest.split_whitespace().collect();
2557    let (addr, fingerprint, files_token, connections_token) =
2558        match (kind, parts.as_slice()) {
2559            ("RCP_TLS", [addr, fingerprint, files, connections]) => (
2560                addr,
2561                Some(tls::fingerprint_from_hex(fingerprint).with_context(|| {
2562                    format!("invalid fingerprint in RCP_TLS line: {fingerprint}")
2563                })?),
2564                files,
2565                connections,
2566            ),
2567            ("RCP_TCP", [addr, files, connections]) => (addr, None, files, connections),
2568            ("RCP_TLS", _) => anyhow::bail!("invalid RCP_TLS line from rcpd: {line}"),
2569            ("RCP_TCP", _) => anyhow::bail!("invalid RCP_TCP line from rcpd: {line}"),
2570            _ => anyhow::bail!("unexpected output from rcpd (expected RCP_TLS or RCP_TCP): {line}"),
2571        };
2572    let addr = addr
2573        .parse()
2574        .with_context(|| format!("invalid address in rcpd readiness record: {addr}"))?;
2575    let files_in_flight = parse_files_in_flight(files_token)?;
2576    let max_connections = connections_token.parse::<usize>().with_context(|| {
2577        format!("invalid effective stream count in rcpd readiness record: {connections_token}")
2578    })?;
2579    let max_connections = std::num::NonZeroUsize::new(max_connections).with_context(|| {
2580        format!("invalid zero stream count in rcpd readiness record: {connections_token}")
2581    })?;
2582    Ok(RcpdConnectionInfo {
2583        addr,
2584        fingerprint,
2585        files_in_flight,
2586        max_connections,
2587    })
2588}
2589
2590#[derive(Debug)]
2591struct RcpdStartupRefusal(String);
2592
2593impl std::fmt::Display for RcpdStartupRefusal {
2594    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2595        f.write_str(&self.0)
2596    }
2597}
2598
2599impl std::error::Error for RcpdStartupRefusal {}
2600
2601fn parse_rcpd_startup_record(line: &str) -> anyhow::Result<RcpdConnectionInfo> {
2602    let refusal_token = RCPD_STARTUP_ERROR_PREFIX.trim_end();
2603    let diagnostic = if line == refusal_token {
2604        Some("")
2605    } else {
2606        line.strip_prefix(RCPD_STARTUP_ERROR_PREFIX)
2607    };
2608    if let Some(diagnostic) = diagnostic {
2609        let diagnostic = diagnostic.trim();
2610        if diagnostic.is_empty() {
2611            anyhow::bail!("rcpd refused startup without a diagnostic");
2612        }
2613        return Err(anyhow::Error::new(RcpdStartupRefusal(
2614            diagnostic.to_string(),
2615        )))
2616        .context("rcpd refused startup");
2617    }
2618    parse_rcpd_readiness(line)
2619}
2620
2621async fn read_rcpd_startup_record<R>(reader: &mut R) -> anyhow::Result<RcpdConnectionInfo>
2622where
2623    R: tokio::io::AsyncBufRead + Unpin,
2624{
2625    use tokio::io::AsyncBufReadExt;
2626
2627    let mut bytes = Vec::new();
2628    loop {
2629        let available = reader
2630            .fill_buf()
2631            .await
2632            .context("failed to read connection info from rcpd")?;
2633        if available.is_empty() {
2634            if bytes.is_empty() {
2635                anyhow::bail!("rcpd exited before writing a readiness record");
2636            }
2637            break;
2638        }
2639        let newline = available.iter().position(|byte| *byte == b'\n');
2640        let take = newline.map_or(available.len(), |index| index + 1);
2641        if bytes.len().saturating_add(take) > RCPD_STARTUP_RECORD_LIMIT {
2642            anyhow::bail!(
2643                "rcpd readiness record exceeds the {}-byte limit",
2644                RCPD_STARTUP_RECORD_LIMIT
2645            );
2646        }
2647        bytes.extend_from_slice(&available[..take]);
2648        reader.consume(take);
2649        if newline.is_some() {
2650            break;
2651        }
2652    }
2653    let line = String::from_utf8(bytes).context("rcpd readiness record is not valid UTF-8")?;
2654    let line = line.trim();
2655    tracing::debug!("rcpd connection line: {line}");
2656    parse_rcpd_startup_record(line)
2657}
2658
2659/// Result of starting an rcpd process.
2660///
2661/// Dropping it closes the SSH child channel and aborts both owned output collectors.
2662pub struct RcpdProcess {
2663    /// SSH child process handle
2664    child: Option<openssh::Child<ManagedSshSession>>,
2665    /// Connection info (address and optional fingerprint)
2666    pub conn_info: RcpdConnectionInfo,
2667    /// Handle for the bounded stderr collector.
2668    stderr_drain: Option<AbortOnDropTask<CapturedOutput>>,
2669    /// Handle for the bounded stdout collector.
2670    stdout_drain: Option<AbortOnDropTask<CapturedOutput>>,
2671}
2672
2673#[derive(Clone)]
2674pub struct PreparedRcpd {
2675    session: ManagedSshSession,
2676    rcpd_path: String,
2677    remote: SshSession,
2678}
2679
2680/// Prepare two endpoints with a caller-selected remote bootstrap timeout.
2681pub async fn prepare_rcpd_endpoints_with_timeout(
2682    source: &SshSession,
2683    destination: &SshSession,
2684    explicit_rcpd_path: Option<&str>,
2685    auto_deploy_rcpd: bool,
2686    cleanup: &RemoteCleanup,
2687    bootstrap_timeout: std::time::Duration,
2688    local_operand_roots: &[std::path::PathBuf],
2689) -> anyhow::Result<(PreparedRcpd, PreparedRcpd)> {
2690    let control_directory_exclusions: std::sync::Arc<[std::path::PathBuf]> =
2691        local_operand_roots.to_vec().into();
2692    if source == destination {
2693        let prepared = prepare_rcpd_with_context(
2694            source,
2695            explicit_rcpd_path,
2696            auto_deploy_rcpd,
2697            PreparationContext::uncancelled(cleanup.clone())
2698                .with_control_directory_exclusions(control_directory_exclusions),
2699            bootstrap_timeout,
2700        )
2701        .await?;
2702        return Ok((prepared.clone(), prepared));
2703    }
2704    let source_control_directory_exclusions = control_directory_exclusions.clone();
2705    join_remote_preparations(
2706        cleanup,
2707        move |preparation| {
2708            prepare_rcpd_with_context(
2709                source,
2710                explicit_rcpd_path,
2711                auto_deploy_rcpd,
2712                preparation.with_control_directory_exclusions(source_control_directory_exclusions),
2713                bootstrap_timeout,
2714            )
2715        },
2716        move |preparation| {
2717            prepare_rcpd_with_context(
2718                destination,
2719                explicit_rcpd_path,
2720                auto_deploy_rcpd,
2721                preparation.with_control_directory_exclusions(control_directory_exclusions),
2722                bootstrap_timeout,
2723            )
2724        },
2725    )
2726    .await
2727}
2728
2729/// Await both preparations after the first intrinsic error cancels its peer.
2730///
2731/// Every production endpoint path receives a [`PreparationContext`], so awaiting both preserves
2732/// cleanup ownership without allowing an uncancellable peer to hide the first error indefinitely.
2733pub(crate) async fn join_remote_preparations<
2734    Source,
2735    Destination,
2736    SourceFuture,
2737    DestinationFuture,
2738    S,
2739    D,
2740>(
2741    cleanup: &RemoteCleanup,
2742    source: Source,
2743    destination: Destination,
2744) -> anyhow::Result<(S, D)>
2745where
2746    Source: FnOnce(PreparationContext) -> SourceFuture,
2747    Destination: FnOnce(PreparationContext) -> DestinationFuture,
2748    SourceFuture: std::future::Future<Output = anyhow::Result<S>>,
2749    DestinationFuture: std::future::Future<Output = anyhow::Result<D>>,
2750    S: Send + 'static,
2751    D: Send + 'static,
2752{
2753    const SOURCE: u8 = 1;
2754    const DESTINATION: u8 = 2;
2755
2756    fn take_error_and_defer_success<T: Send + 'static>(
2757        cleanup: &RemoteCleanup,
2758        result: anyhow::Result<T>,
2759    ) -> Option<anyhow::Error> {
2760        match result {
2761            Ok(value) => {
2762                // successful preparation values are generic and may own blocking destructors; keep
2763                // their disposal off the endpoint coordinator and independent of Tokio shutdown
2764                cleanup.defer_drop(value, "rcp-preparation-dispose");
2765                None
2766            }
2767            Err(error) => Some(error),
2768        }
2769    }
2770
2771    async fn prepare<Prepare, PrepareFuture, Prepared>(
2772        prepare: Prepare,
2773        preparation: PreparationContext,
2774        first_failure: std::sync::Arc<std::sync::atomic::AtomicU8>,
2775        endpoint: u8,
2776    ) -> anyhow::Result<Prepared>
2777    where
2778        Prepare: FnOnce(PreparationContext) -> PrepareFuture,
2779        PrepareFuture: std::future::Future<Output = anyhow::Result<Prepared>>,
2780    {
2781        let cancellation = preparation.cancellation.clone();
2782        let result = prepare(preparation).await;
2783        if result.is_err()
2784            && first_failure
2785                .compare_exchange(
2786                    0,
2787                    endpoint,
2788                    std::sync::atomic::Ordering::SeqCst,
2789                    std::sync::atomic::Ordering::SeqCst,
2790                )
2791                .is_ok()
2792        {
2793            cancellation.cancel();
2794        }
2795        result
2796    }
2797
2798    let cancellation = tokio_util::sync::CancellationToken::new();
2799    let first_failure = std::sync::Arc::new(std::sync::atomic::AtomicU8::new(0));
2800    let source_preparation = prepare(
2801        source,
2802        PreparationContext::new(cancellation.clone(), cleanup.clone()),
2803        first_failure.clone(),
2804        SOURCE,
2805    );
2806    let destination_preparation = prepare(
2807        destination,
2808        PreparationContext::new(cancellation, cleanup.clone()),
2809        first_failure.clone(),
2810        DESTINATION,
2811    );
2812    let (source, destination) = tokio::join!(source_preparation, destination_preparation);
2813    match (source, destination) {
2814        (Ok(source), Ok(destination)) => Ok((source, destination)),
2815        (source, destination) => {
2816            let source_error = take_error_and_defer_success(cleanup, source);
2817            let destination_error = take_error_and_defer_success(cleanup, destination);
2818            match (
2819                first_failure.load(std::sync::atomic::Ordering::SeqCst),
2820                source_error,
2821                destination_error,
2822            ) {
2823                (SOURCE, Some(error), _) | (DESTINATION, _, Some(error)) => Err(error),
2824                (_, Some(error), _) | (_, _, Some(error)) => Err(error),
2825                (_, None, None) => unreachable!("an error outcome must retain at least one error"),
2826            }
2827        }
2828    }
2829}
2830
2831#[instrument(skip(preparation))]
2832async fn prepare_rcpd_with_context(
2833    session: &SshSession,
2834    explicit_rcpd_path: Option<&str>,
2835    auto_deploy_rcpd: bool,
2836    preparation: PreparationContext,
2837    bootstrap_timeout: std::time::Duration,
2838) -> anyhow::Result<PreparedRcpd> {
2839    tracing::info!("Preparing rcpd server on: {:?}", session);
2840    let remote_host = &session.host;
2841    let ssh_session = setup_ssh_session(
2842        session,
2843        &preparation,
2844        BootstrapDeadline::new(bootstrap_timeout),
2845    )
2846    .await?;
2847    let rcpd_path = match try_discover_and_check_version(
2848        &ssh_session,
2849        explicit_rcpd_path,
2850        remote_host,
2851        &preparation,
2852        bootstrap_timeout,
2853    )
2854    .await
2855    {
2856        Ok(path) => path,
2857        Err(error) => {
2858            preparation.ensure_active()?;
2859            if !auto_deploy_rcpd {
2860                return Err(error);
2861            }
2862            tracing::info!("rcpd unavailable or incompatible, attempting auto-deployment");
2863            let local_rcpd = deploy::find_local_rcpd_binary_with_context(&preparation)
2864                .await
2865                .context("failed to find local rcpd binary for deployment")?;
2866            tracing::info!("Found local rcpd binary at {}", local_rcpd.display());
2867            let local_version = common::version::ProtocolVersion::current();
2868            let deployed_path = deploy::deploy_rcpd_with_context(
2869                &ssh_session,
2870                &local_rcpd,
2871                &local_version.cache_tag(),
2872                remote_host,
2873                &preparation,
2874                bootstrap_timeout,
2875            )
2876            .await
2877            .context("failed to deploy rcpd to remote host")?;
2878            check_rcpd_version(
2879                &ssh_session,
2880                &deployed_path,
2881                remote_host,
2882                &preparation,
2883                bootstrap_timeout,
2884            )
2885            .await
2886            .with_context(|| {
2887                format!("deployed rcpd at {deployed_path} failed compatibility verification")
2888            })?;
2889            tracing::info!("Successfully deployed rcpd to {deployed_path}");
2890            match deploy::cleanup_old_versions_with_context(
2891                &ssh_session,
2892                3,
2893                &preparation,
2894                bootstrap_timeout,
2895            )
2896            .await
2897            {
2898                Ok(()) => {}
2899                Err(_) if preparation.cancellation.is_cancelled() => {
2900                    return Err(PreparationContext::cancellation_error());
2901                }
2902                Err(error) => {
2903                    tracing::warn!("failed to cleanup old versions (non-fatal): {error:#}");
2904                }
2905            }
2906            deployed_path
2907        }
2908    };
2909    preparation.ensure_active()?;
2910    Ok(PreparedRcpd {
2911        session: ssh_session,
2912        rcpd_path,
2913        remote: session.clone(),
2914    })
2915}
2916
2917impl PreparedRcpd {
2918    pub async fn spawn(
2919        &self,
2920        rcpd_config: &protocol::RcpdConfig,
2921        bind_ip: Option<&str>,
2922        role: protocol::RcpdRole,
2923    ) -> anyhow::Result<RcpdProcess> {
2924        tracing::info!("Starting prepared rcpd server on: {}", self.remote.host);
2925        let session = &self.remote;
2926        // build the exact remote argv once so execution and the stable diagnostic cannot drift
2927        let mut rcpd_args = vec!["--role".to_string(), role.to_string()];
2928        rcpd_args.extend(rcpd_config.to_args());
2929        if let Some(ip) = bind_ip {
2930            rcpd_args.push("--bind-ip".to_string());
2931            rcpd_args.push(ip.to_string());
2932        }
2933        tracing::info!(
2934            "Will run remote rcpd: path={:?} role={} args={:?}",
2935            self.rcpd_path,
2936            role,
2937            rcpd_args
2938        );
2939        let mut cmd = openssh::Session::to_command(self.session.clone(), &self.rcpd_path);
2940        cmd.args(rcpd_args);
2941        // configure stdin/stdout/stderr
2942        // stdin must be piped so rcpd can monitor it for master disconnection (stdin watchdog)
2943        cmd.stdin(openssh::Stdio::piped());
2944        cmd.stdout(openssh::Stdio::piped());
2945        cmd.stderr(openssh::Stdio::piped());
2946        let startup_deadline = BootstrapDeadline::new(std::time::Duration::from_secs(
2947            rcpd_config.remote_copy_conn_timeout_sec,
2948        ));
2949        let spawn =
2950            tokio::spawn(async move { cmd.spawn().await.context("Failed to spawn rcpd command") });
2951        let mut child = PreparationContext::uncancelled(self.session.cleanup())
2952            .run_abortable_with_deadline(spawn, "spawning rcpd command", startup_deadline)
2953            .await?;
2954        // read connection info from rcpd's stderr
2955        // (rcpd uses stderr for the protocol line because stdout is reserved for logs per convention;
2956        // rcpd doesn't display progress bars locally - it sends progress data over the network)
2957        // format: "RCP_TLS <addr> <fingerprint> <F> <E>" or "RCP_TCP <addr> <F> <E>"
2958        let Some(stderr) = child.stderr().take() else {
2959            let error = anyhow::anyhow!("rcpd stderr not available");
2960            let diagnostic = reap_failed_rcpd(child, &session.host, None).await;
2961            return Err(attach_startup_diagnostic(error, diagnostic));
2962        };
2963        let mut stderr_reader = tokio::io::BufReader::new(stderr);
2964        let startup = startup_deadline
2965            .run(
2966                "waiting for rcpd readiness record",
2967                read_rcpd_startup_record(&mut stderr_reader),
2968            )
2969            .await;
2970        let conn_info = match startup {
2971            Ok(conn_info) => conn_info,
2972            Err(error) => {
2973                let diagnostic = reap_failed_rcpd(child, &session.host, Some(stderr_reader)).await;
2974                return Err(attach_startup_diagnostic(error, diagnostic));
2975            }
2976        };
2977        // drain both streams concurrently so the daemon cannot block on a full pipe; retain only a
2978        // bounded tail for completion diagnostics
2979        let stderr_drain = AbortOnDropTask::new(tokio::spawn(drain_rcpd_output(
2980            stderr_reader,
2981            session.host.clone(),
2982            "stderr",
2983        )));
2984        let stdout_drain = child.stdout().take().map(|stdout| {
2985            AbortOnDropTask::new(tokio::spawn(drain_rcpd_output(
2986                stdout,
2987                session.host.clone(),
2988                "stdout",
2989            )))
2990        });
2991        tracing::info!(
2992            "rcpd listening on {} (encryption={})",
2993            conn_info.addr,
2994            conn_info.fingerprint.is_some()
2995        );
2996        Ok(RcpdProcess {
2997            child: Some(child),
2998            conn_info,
2999            stderr_drain: Some(stderr_drain),
3000            stdout_drain,
3001        })
3002    }
3003}
3004
3005fn attach_startup_diagnostic(error: anyhow::Error, diagnostic: Option<String>) -> anyhow::Error {
3006    match diagnostic {
3007        Some(diagnostic) => error.context(format!("rcpd startup output: {diagnostic}")),
3008        None => error,
3009    }
3010}
3011
3012async fn reap_failed_rcpd(
3013    mut child: openssh::Child<ManagedSshSession>,
3014    host: &str,
3015    stderr_reader: Option<tokio::io::BufReader<openssh::ChildStderr>>,
3016) -> Option<String> {
3017    let stdout_reader = child.stdout().take();
3018    let reaper = async move {
3019        let stdout = async move {
3020            match stdout_reader {
3021                Some(stdout) => drain_bounded_output(stdout, DIAGNOSTIC_CAPTURE_LIMIT).await,
3022                None => CapturedOutput::default(),
3023            }
3024        };
3025        let stderr = async move {
3026            match stderr_reader {
3027                Some(stderr) => drain_bounded_output(stderr, DIAGNOSTIC_CAPTURE_LIMIT).await,
3028                None => CapturedOutput::default(),
3029            }
3030        };
3031        let (status, stdout, stderr) = tokio::join!(child.wait(), stdout, stderr);
3032        anyhow::Ok((status?, stdout, stderr))
3033    };
3034    match tokio::time::timeout(FAILED_RCPD_REAP_GRACE, reaper).await {
3035        Ok(Ok((status, stdout, stderr))) => {
3036            tracing::debug!(
3037                host,
3038                status = ?status.code(),
3039                "reaped rcpd after failed startup"
3040            );
3041            format_failed_rcpd_output(stdout.rendered().as_bytes(), &stderr.rendered())
3042        }
3043        Ok(Err(error)) => {
3044            tracing::debug!(host, "failed to reap rcpd after startup error: {error:#}");
3045            None
3046        }
3047        Err(_) => {
3048            tracing::debug!(
3049                host,
3050                "rcpd did not exit within the startup cleanup grace; released its SSH child and output pipes"
3051            );
3052            None
3053        }
3054    }
3055}
3056
3057fn format_failed_rcpd_output(stdout: &[u8], stderr: &str) -> Option<String> {
3058    let stdout = String::from_utf8_lossy(stdout);
3059    let stdout = common::format_startup_diagnostic(None, stdout.trim());
3060    let stderr = common::format_startup_diagnostic(None, stderr.trim());
3061    match (stdout.is_empty(), stderr.is_empty()) {
3062        (true, true) => None,
3063        (false, true) => Some(format!("stdout: {stdout}")),
3064        (true, false) => Some(format!("stderr: {stderr}")),
3065        (false, false) => Some(format!("stdout: {stdout}; stderr: {stderr}")),
3066    }
3067}
3068
3069// ============================================================================
3070// ip address detection
3071// ============================================================================
3072
3073fn get_local_ip(explicit_bind_ip: Option<&str>) -> anyhow::Result<std::net::IpAddr> {
3074    // if explicit IP provided, validate and use it
3075    if let Some(ip_str) = explicit_bind_ip {
3076        let ip = ip_str
3077            .parse::<std::net::IpAddr>()
3078            .with_context(|| format!("invalid IP address: {}", ip_str))?;
3079        match ip {
3080            std::net::IpAddr::V4(ipv4) => {
3081                tracing::debug!("using explicit bind IP: {}", ipv4);
3082                return Ok(std::net::IpAddr::V4(ipv4));
3083            }
3084            std::net::IpAddr::V6(_) => {
3085                anyhow::bail!(
3086                    "IPv6 address not supported for binding (got {}). \
3087                     TCP endpoints bind to 0.0.0.0 (IPv4 only)",
3088                    ip
3089                );
3090            }
3091        }
3092    }
3093    // auto-detection: try kernel routing first
3094    if let Some(ipv4) = try_ipv4_via_kernel_routing()? {
3095        return Ok(std::net::IpAddr::V4(ipv4));
3096    }
3097    // fallback to interface enumeration
3098    tracing::debug!("routing-based detection failed, falling back to interface enumeration");
3099    let interfaces = collect_ipv4_interfaces().context("Failed to enumerate network interfaces")?;
3100    if let Some(ipv4) = choose_best_ipv4(&interfaces) {
3101        tracing::debug!("using IPv4 address from interface scan: {}", ipv4);
3102        return Ok(std::net::IpAddr::V4(ipv4));
3103    }
3104    anyhow::bail!("No IPv4 interfaces found (TCP endpoints require IPv4 as they bind to 0.0.0.0)")
3105}
3106
3107fn try_ipv4_via_kernel_routing() -> anyhow::Result<Option<std::net::Ipv4Addr>> {
3108    // strategy: ask the kernel which interface it would use by connecting to RFC1918 targets.
3109    // these addresses never leave the local network but still exercise the routing table.
3110    let private_ips = ["10.0.0.1:80", "172.16.0.1:80", "192.168.1.1:80"];
3111    for addr_str in &private_ips {
3112        let addr = addr_str
3113            .parse::<std::net::SocketAddr>()
3114            .expect("hardcoded socket addresses are valid");
3115        let socket = match std::net::UdpSocket::bind("0.0.0.0:0") {
3116            Ok(socket) => socket,
3117            Err(err) => {
3118                tracing::debug!(?err, "failed to bind UDP socket for routing detection");
3119                continue;
3120            }
3121        };
3122        if let Err(err) = socket.connect(addr) {
3123            tracing::debug!(?err, "connect() failed for routing target {}", addr);
3124            continue;
3125        }
3126        match socket.local_addr() {
3127            Ok(std::net::SocketAddr::V4(local_addr)) => {
3128                let ipv4 = *local_addr.ip();
3129                if !ipv4.is_loopback() && !ipv4.is_unspecified() {
3130                    tracing::debug!(
3131                        "using IPv4 address from kernel routing (via {}): {}",
3132                        addr,
3133                        ipv4
3134                    );
3135                    return Ok(Some(ipv4));
3136                }
3137            }
3138            Ok(_) => {
3139                tracing::debug!("kernel routing returned IPv6 despite IPv4 bind, ignoring");
3140            }
3141            Err(err) => {
3142                tracing::debug!(?err, "local_addr() failed for routing-based detection");
3143            }
3144        }
3145    }
3146    Ok(None)
3147}
3148
3149#[derive(Clone, Debug, PartialEq, Eq)]
3150struct InterfaceIpv4 {
3151    name: String,
3152    addr: std::net::Ipv4Addr,
3153}
3154
3155fn collect_ipv4_interfaces() -> anyhow::Result<Vec<InterfaceIpv4>> {
3156    use if_addrs::get_if_addrs;
3157    let mut interfaces = Vec::new();
3158    for iface in get_if_addrs()? {
3159        if let std::net::IpAddr::V4(ipv4) = iface.addr.ip() {
3160            interfaces.push(InterfaceIpv4 {
3161                name: iface.name,
3162                addr: ipv4,
3163            });
3164        }
3165    }
3166    Ok(interfaces)
3167}
3168
3169fn choose_best_ipv4(interfaces: &[InterfaceIpv4]) -> Option<std::net::Ipv4Addr> {
3170    interfaces
3171        .iter()
3172        .filter(|iface| !iface.addr.is_unspecified())
3173        .min_by_key(|iface| interface_priority(&iface.name, &iface.addr))
3174        .map(|iface| iface.addr)
3175}
3176
3177fn interface_priority(
3178    name: &str,
3179    addr: &std::net::Ipv4Addr,
3180) -> (InterfaceCategory, u8, u8, std::net::Ipv4Addr) {
3181    (
3182        classify_interface(name, addr),
3183        if addr.is_link_local() { 1 } else { 0 },
3184        if addr.is_private() { 1 } else { 0 },
3185        *addr,
3186    )
3187}
3188
3189#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
3190enum InterfaceCategory {
3191    Preferred = 0,
3192    Normal = 1,
3193    Virtual = 2,
3194    Loopback = 3,
3195}
3196
3197fn classify_interface(name: &str, addr: &std::net::Ipv4Addr) -> InterfaceCategory {
3198    if addr.is_loopback() {
3199        return InterfaceCategory::Loopback;
3200    }
3201    let normalized = normalize_interface_name(name);
3202    if is_virtual_interface(&normalized) {
3203        return InterfaceCategory::Virtual;
3204    }
3205    if is_preferred_physical_interface(&normalized) {
3206        return InterfaceCategory::Preferred;
3207    }
3208    InterfaceCategory::Normal
3209}
3210
3211fn normalize_interface_name(original: &str) -> String {
3212    let mut normalized = String::with_capacity(original.len());
3213    for ch in original.chars() {
3214        if ch.is_ascii_alphanumeric() {
3215            normalized.push(ch.to_ascii_lowercase());
3216        }
3217    }
3218    normalized
3219}
3220
3221fn is_virtual_interface(name: &str) -> bool {
3222    const VIRTUAL_PREFIXES: &[&str] = &[
3223        "br",
3224        "docker",
3225        "veth",
3226        "virbr",
3227        "vmnet",
3228        "wg",
3229        "tailscale",
3230        "zt",
3231        "zerotier",
3232        "tap",
3233        "tun",
3234        "utun",
3235        "ham",
3236        "vpn",
3237        "lo",
3238        "lxc",
3239    ];
3240    VIRTUAL_PREFIXES
3241        .iter()
3242        .any(|prefix| name.starts_with(prefix))
3243        || name.contains("virtual")
3244}
3245
3246fn is_preferred_physical_interface(name: &str) -> bool {
3247    const PHYSICAL_PREFIXES: &[&str] = &[
3248        "en", "eth", "em", "eno", "ens", "enp", "wl", "ww", "wlan", "ethernet", "lan", "wifi",
3249    ];
3250    PHYSICAL_PREFIXES
3251        .iter()
3252        .any(|prefix| name.starts_with(prefix))
3253}
3254
3255/// Generate a random server name for identifying connections
3256#[instrument]
3257pub fn get_random_server_name() -> String {
3258    rand::random_iter::<u8>()
3259        .filter(|b| b.is_ascii_alphanumeric())
3260        .take(20)
3261        .map(char::from)
3262        .collect()
3263}
3264
3265// ============================================================================
3266// tcp server and client functions
3267// ============================================================================
3268
3269/// Create a TCP listener for control connections
3270///
3271/// Returns a listener bound to the specified port range (or any available port).
3272#[instrument(skip(config))]
3273pub async fn create_tcp_control_listener(
3274    config: &TcpConfig,
3275    bind_ip: Option<&str>,
3276) -> anyhow::Result<tokio::net::TcpListener> {
3277    let bind_addr = if let Some(ip_str) = bind_ip {
3278        let ip = ip_str
3279            .parse::<std::net::IpAddr>()
3280            .with_context(|| format!("invalid IP address: {}", ip_str))?;
3281        std::net::SocketAddr::new(ip, 0)
3282    } else {
3283        std::net::SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED), 0)
3284    };
3285    let listener = if let Some(ranges_str) = config.port_ranges.as_deref() {
3286        let ranges = port_ranges::PortRanges::parse(ranges_str)?;
3287        ranges.bind_tcp_listener(bind_addr.ip()).await?
3288    } else {
3289        tokio::net::TcpListener::bind(bind_addr).await?
3290    };
3291    let local_addr = listener.local_addr()?;
3292    tracing::info!("TCP control listener bound to {}", local_addr);
3293    Ok(listener)
3294}
3295
3296/// Create a TCP listener for data connections (file transfers)
3297///
3298/// Returns a listener bound to the specified port range (or any available port).
3299#[instrument(skip(config))]
3300pub async fn create_tcp_data_listener(
3301    config: &TcpConfig,
3302    bind_ip: Option<&str>,
3303) -> anyhow::Result<tokio::net::TcpListener> {
3304    let bind_addr = if let Some(ip_str) = bind_ip {
3305        let ip = ip_str
3306            .parse::<std::net::IpAddr>()
3307            .with_context(|| format!("invalid IP address: {}", ip_str))?;
3308        std::net::SocketAddr::new(ip, 0)
3309    } else {
3310        std::net::SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED), 0)
3311    };
3312    let listener = if let Some(ranges_str) = config.port_ranges.as_deref() {
3313        let ranges = port_ranges::PortRanges::parse(ranges_str)?;
3314        ranges.bind_tcp_listener(bind_addr.ip()).await?
3315    } else {
3316        tokio::net::TcpListener::bind(bind_addr).await?
3317    };
3318    let local_addr = listener.local_addr()?;
3319    tracing::info!("TCP data listener bound to {}", local_addr);
3320    Ok(listener)
3321}
3322
3323/// Get the external address of a TCP listener
3324///
3325/// Similar to `get_endpoint_addr_with_bind_ip`, replaces 0.0.0.0 with the local IP.
3326pub fn get_tcp_listener_addr(
3327    listener: &tokio::net::TcpListener,
3328    bind_ip: Option<&str>,
3329) -> anyhow::Result<std::net::SocketAddr> {
3330    let local_addr = listener.local_addr()?;
3331    if local_addr.ip().is_unspecified() {
3332        let local_ip = get_local_ip(bind_ip).context("failed to get local IP address")?;
3333        Ok(std::net::SocketAddr::new(local_ip, local_addr.port()))
3334    } else {
3335        Ok(local_addr)
3336    }
3337}
3338
3339/// Connect to a TCP control server, applying the connect timeout and the standard socket options
3340#[instrument(skip(config))]
3341pub async fn connect_tcp_control(
3342    addr: std::net::SocketAddr,
3343    config: &TcpConfig,
3344) -> anyhow::Result<tokio::net::TcpStream> {
3345    let timeout_sec = config.conn_timeout_sec;
3346    let stream = tokio::time::timeout(
3347        std::time::Duration::from_secs(timeout_sec),
3348        tokio::net::TcpStream::connect(addr),
3349    )
3350    .await
3351    .with_context(|| format!("connection to {} timed out after {}s", addr, timeout_sec))?
3352    .with_context(|| format!("failed to connect to {}", addr))?;
3353    configure_tcp_socket(
3354        &stream,
3355        config.network_profile,
3356        config.keepalive_sec,
3357        ConnectionKind::Control,
3358    );
3359    tracing::debug!("connected to TCP control server at {}", addr);
3360    Ok(stream)
3361}
3362
3363/// Connect a TCP data connection, applying the standard socket options.
3364///
3365/// Deliberately NOT bounded here: the data pool bounds TCP connect + TLS handshake under ONE
3366/// caller-side deadline, and an inner timeout would double-count it. Takes the profile and
3367/// keepalive budget rather than a whole [`TcpConfig`] because that is what the pool carries.
3368///
3369/// These helpers exist so no connection can be established without its socket options:
3370/// `scripts/check-tcp-socket-config.sh` forbids raw `TcpStream::connect`/`.accept()` outside this
3371/// file, and inside it requires every connecting/accepting function to configure what it opened.
3372pub async fn connect_tcp_data(
3373    addr: std::net::SocketAddr,
3374    profile: NetworkProfile,
3375    keepalive_sec: u64,
3376) -> std::io::Result<tokio::net::TcpStream> {
3377    let stream = tokio::net::TcpStream::connect(addr).await?;
3378    configure_tcp_socket(&stream, profile, keepalive_sec, ConnectionKind::Data);
3379    Ok(stream)
3380}
3381
3382/// Accept one TCP control connection, applying the standard socket options before returning it.
3383///
3384/// The wait is bounded by the CALLER (each control accept awaits one specific peer under its own
3385/// timeout and error wording); the configuration lives here so no accepted control connection can
3386/// miss it. Cancel-safe exactly as `TcpListener::accept` is: the accept is the only await, and the
3387/// configuration runs synchronously in the same poll that completes it.
3388pub async fn accept_tcp_control(
3389    listener: &tokio::net::TcpListener,
3390    config: &TcpConfig,
3391) -> std::io::Result<(tokio::net::TcpStream, std::net::SocketAddr)> {
3392    let (stream, addr) = listener.accept().await?;
3393    configure_tcp_socket(
3394        &stream,
3395        config.network_profile,
3396        config.keepalive_sec,
3397        ConnectionKind::Control,
3398    );
3399    Ok((stream, addr))
3400}
3401
3402/// Accept one TCP data connection, applying the standard socket options before returning it.
3403///
3404/// Data connections get no `TCP_USER_TIMEOUT` — a throttled receiver legitimately stops reading
3405/// mid-file, and aborting that sender would fail a copy that used to just run slow (see
3406/// [`configure_tcp_socket`]). Unbounded like [`connect_tcp_data`]: the source's accept loop runs
3407/// for the life of the pool. Cancel-safe as `TcpListener::accept` is (see
3408/// [`accept_tcp_control`]), so it can sit in a `select!` arm.
3409pub async fn accept_tcp_data(
3410    listener: &tokio::net::TcpListener,
3411    profile: NetworkProfile,
3412    keepalive_sec: u64,
3413) -> std::io::Result<(tokio::net::TcpStream, std::net::SocketAddr)> {
3414    let (stream, addr) = listener.accept().await?;
3415    configure_tcp_socket(&stream, profile, keepalive_sec, ConnectionKind::Data);
3416    Ok((stream, addr))
3417}
3418
3419/// Number of unacknowledged keepalive probes tolerated before a connection is declared dead.
3420///
3421/// Decides the outcome only where `TCP_USER_TIMEOUT` is NOT set — on Linux the user timeout
3422/// overrides the probe count, so this is inert on [`ConnectionKind::Control`] and is what actually
3423/// ends a dead [`ConnectionKind::Data`] connection (after idle + retries × interval).
3424pub const TCP_KEEPALIVE_RETRIES: u32 = 6;
3425
3426/// What an rcp TCP connection carries, which decides whether `TCP_USER_TIMEOUT` applies.
3427///
3428/// The user timeout aborts a connection whose data stays unacknowledged for the budget — and a
3429/// peer that has simply STOPPED READING is indistinguishable from a dead one at that level. It is
3430/// therefore only safe on a connection that application backpressure never legitimately blocks.
3431#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3432pub enum ConnectionKind {
3433    /// Protocol messages: master↔rcpd (control and tracing) and source↔destination control.
3434    /// Reads are driven by a dispatch loop that does not block on transfer-sized work.
3435    Control,
3436    /// Pooled source→destination bulk file transfer, where the receiver legitimately stops
3437    /// reading for as long as its throttles make it wait.
3438    Data,
3439}
3440
3441impl std::fmt::Display for ConnectionKind {
3442    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3443        match self {
3444            Self::Control => write!(f, "control"),
3445            Self::Data => write!(f, "data"),
3446        }
3447    }
3448}
3449
3450/// Configure an rcp TCP connection: no-delay, buffer sizes, and dead-peer detection.
3451///
3452/// This is the ONE place these options are set — call it at every site that establishes or accepts
3453/// an rcp TCP connection. They used to be hand-paired per connection (`set_nodelay` at 7 sites,
3454/// buffer sizing at 4, so two sites got no buffer sizing at all), which is the missed-exit-path
3455/// smell: a new option has to be copied into every site and eventually is not.
3456/// `scripts/check-tcp-socket-config.sh` enforces that no other site sets any of these options
3457/// itself, and that every file opening or accepting a TCP connection routes through here.
3458///
3459/// `keepalive_sec` is the budget for noticing that the peer's HOST has vanished (power loss,
3460/// severed link, destroyed VM). Such a peer sends neither FIN nor RST, so an await on it never
3461/// completes — the master waiting for `RcpdResult` hangs forever, and so do the control reads on
3462/// both rcpds. Two options cover different halves of that, and `kind` decides which apply:
3463///
3464/// - `SO_KEEPALIVE` (`TCP_KEEPIDLE`/`TCP_KEEPINTVL`/`TCP_KEEPCNT`), on EVERY connection, probes an
3465///   IDLE one — the awaiting-`RcpdResult` case, the control streams generally, and a data
3466///   connection between transfers.
3467/// - `TCP_USER_TIMEOUT`, on [`ConnectionKind::Control`] ONLY, bounds how long UNACKED data may
3468///   stay outstanding. Keepalive never fires while data is in flight, so without it the kernel
3469///   retransmits for roughly 15 minutes (`tcp_retries2`) before giving up.
3470///
3471/// **Why data connections do not get the user timeout.** It cannot tell a dead peer from a live
3472/// one that has stopped reading: with the receiver's window at zero and every zero-window probe
3473/// ACKed, the sender is still aborted once the budget expires. The destination does exactly that —
3474/// it awaits its per-file iops reservation after reading a file header and before reading any of
3475/// its bytes, so `--iops-throttle 50` on a 10 GiB file at 1 MiB chunks leaves that socket unread
3476/// for minutes. Under a shared budget the copy would FAIL where it used to merely run slow. The
3477/// price is stated plainly: a host that vanishes MID-TRANSFER is detected only by the kernel's
3478/// retransmission limit (~15 minutes), exactly as before this option existed — an idle data
3479/// connection is still caught by keepalive after idle + retries × interval.
3480///
3481/// Control bookkeeping does not consume filesystem ops tokens, but the reader can still wait for
3482/// parent creation, owned directory-job capacity, or inline finalization. The filesystem work
3483/// behind those waits remains rate- and congestion-limited, so a low `--ops-throttle` or stalled
3484/// storage can stop reads. Pending sender data can reach the user-timeout budget once the receive
3485/// buffer fills and closes the window. Removing the per-message rate charge does not make control
3486/// connections backpressure-free.
3487///
3488/// The keepalive sub-values are derived from the single budget rather than exposed individually, so
3489/// their relationship stays correct by construction: idle at half the budget, probes every twelfth
3490/// of it, [`TCP_KEEPALIVE_RETRIES`] of them. `keepalive_sec == 0` disables both mechanisms and
3491/// leaves only no-delay and buffer sizing.
3492///
3493/// Every option is best effort: a failure is logged and tolerated, because a socket option that a
3494/// platform or a container policy refuses is not a reason to fail a copy.
3495pub fn configure_tcp_socket(
3496    stream: &tokio::net::TcpStream,
3497    profile: NetworkProfile,
3498    keepalive_sec: u64,
3499    kind: ConnectionKind,
3500) {
3501    if let Err(err) = stream.set_nodelay(true) {
3502        tracing::warn!("failed to set TCP_NODELAY: {err:#}");
3503    }
3504    let (send_buf, recv_buf) = match profile {
3505        NetworkProfile::Datacenter => (16 * 1024 * 1024, 16 * 1024 * 1024),
3506        NetworkProfile::Internet => (2 * 1024 * 1024, 2 * 1024 * 1024),
3507    };
3508    let sock_ref = socket2::SockRef::from(stream);
3509    if let Err(err) = sock_ref.set_send_buffer_size(send_buf) {
3510        tracing::warn!("failed to set TCP send buffer size: {err:#}");
3511    }
3512    if let Err(err) = sock_ref.set_recv_buffer_size(recv_buf) {
3513        tracing::warn!("failed to set TCP receive buffer size: {err:#}");
3514    }
3515    if let (Ok(send), Ok(recv)) = (sock_ref.send_buffer_size(), sock_ref.recv_buffer_size()) {
3516        tracing::debug!(
3517            "TCP socket buffer sizes: send={} recv={}",
3518            bytesize::ByteSize(send as u64),
3519            bytesize::ByteSize(recv as u64),
3520        );
3521    }
3522    if keepalive_sec == 0 {
3523        tracing::debug!("TCP keepalive and user timeout disabled on {kind} connection");
3524        return;
3525    }
3526    // clamped to 1s: the kernel rejects a zero idle/interval, which a budget under 12s would
3527    // otherwise produce
3528    let idle_sec = std::cmp::max(keepalive_sec / 2, 1);
3529    let interval_sec = std::cmp::max(keepalive_sec / 12, 1);
3530    let keepalive = socket2::TcpKeepalive::new()
3531        .with_time(std::time::Duration::from_secs(idle_sec))
3532        .with_interval(std::time::Duration::from_secs(interval_sec))
3533        .with_retries(TCP_KEEPALIVE_RETRIES);
3534    // each log reports what LANDED, not what was attempted: `set_tcp_keepalive` turns SO_KEEPALIVE
3535    // on and then bails on the first sub-option that fails, so a partial failure leaves keepalive
3536    // enabled at the system defaults (7200s idle) — a line claiming the configured values would be
3537    // actively misleading about how long a dead peer goes unnoticed
3538    match sock_ref.set_tcp_keepalive(&keepalive) {
3539        Ok(()) => tracing::debug!(
3540            "TCP keepalive on {kind} connection: idle {idle_sec}s, interval {interval_sec}s, retries {TCP_KEEPALIVE_RETRIES}"
3541        ),
3542        Err(err) => tracing::warn!(
3543            "failed to configure TCP keepalive on {kind} connection (it may be enabled at system defaults): {err:#}"
3544        ),
3545    }
3546    // tcp_user_timeout is Linux-only; elsewhere keepalive alone covers the idle case
3547    #[cfg(target_os = "linux")]
3548    if kind == ConnectionKind::Control {
3549        let user_timeout = std::time::Duration::from_secs(keepalive_sec);
3550        match sock_ref.set_tcp_user_timeout(Some(user_timeout)) {
3551            Ok(()) => {
3552                tracing::debug!("TCP_USER_TIMEOUT on control connection: {keepalive_sec}s")
3553            }
3554            Err(err) => tracing::warn!("failed to set TCP_USER_TIMEOUT: {err:#}"),
3555        }
3556    }
3557}
3558
3559#[cfg(test)]
3560mod tests {
3561    use super::*;
3562    use std::collections::HashMap;
3563    use std::path::PathBuf;
3564    use std::sync::{Condvar, Mutex};
3565
3566    fn nonzero(value: usize) -> std::num::NonZeroUsize {
3567        std::num::NonZeroUsize::new(value).unwrap()
3568    }
3569
3570    mod localhost_ssh_tests {
3571        use super::*;
3572
3573        fn test_rcpd_config() -> protocol::RcpdConfig {
3574            protocol::RcpdConfig {
3575                verbose: 0,
3576                fail_early: false,
3577                preview_only: false,
3578                max_workers: 0,
3579                max_blocking_threads: 0,
3580                files_in_flight: protocol::RcpdFilesInFlight::Explicit(
3581                    common::ConcurrencyLimit::Limited(nonzero(4)),
3582                ),
3583                ops_throttle: 0,
3584                iops_throttle: 0,
3585                chunk_size: 0,
3586                auto_meta: None,
3587                auto_meta_histogram: false,
3588                auto_meta_histogram_log: None,
3589                auto_meta_histogram_interval: std::time::Duration::from_secs(1),
3590                dereference: false,
3591                require_toctou_safe: false,
3592                overwrite: false,
3593                overwrite_compare: "size,mtime".to_string(),
3594                overwrite_manifest_max_entries: protocol::DEFAULT_OVERWRITE_MANIFEST_MAX_ENTRIES,
3595                overwrite_filter: None,
3596                ignore_existing: false,
3597                skip_specials: false,
3598                debug_log_prefix: None,
3599                port_ranges: None,
3600                progress: false,
3601                progress_delay: None,
3602                remote_copy_conn_timeout_sec: 1,
3603                remote_keepalive_sec: DEFAULT_REMOTE_KEEPALIVE_SEC,
3604                network_profile: NetworkProfile::default(),
3605                buffer_size: None,
3606                buffer_retention_limit: None,
3607                max_connections: 4,
3608                pending_writes_multiplier: 1,
3609                chrome_trace_prefix: None,
3610                timings_prefix: None,
3611                timings_detail: false,
3612                flamegraph_prefix: None,
3613                profile_level: None,
3614                tokio_console: false,
3615                tokio_console_port: None,
3616                encryption: false,
3617                master_cert_fingerprint: None,
3618            }
3619        }
3620
3621        async fn prepare_test_rcpd(
3622            session: &SshSession,
3623            explicit_rcpd_path: Option<&str>,
3624            auto_deploy_rcpd: bool,
3625            cleanup: &RemoteCleanup,
3626        ) -> anyhow::Result<PreparedRcpd> {
3627            prepare_rcpd_with_context(
3628                session,
3629                explicit_rcpd_path,
3630                auto_deploy_rcpd,
3631                PreparationContext::uncancelled(cleanup.clone()),
3632                DEFAULT_REMOTE_BOOTSTRAP_TIMEOUT,
3633            )
3634            .await
3635        }
3636
3637        #[cfg(target_os = "linux")]
3638        struct KillTestProcessOnDrop {
3639            pid: String,
3640            process: std::path::PathBuf,
3641            start_time: String,
3642        }
3643
3644        #[cfg(target_os = "linux")]
3645        impl KillTestProcessOnDrop {
3646            fn new(pid: String) -> Self {
3647                let process = std::path::PathBuf::from(format!("/proc/{pid}"));
3648                let start_time = linux_process_start_time(&process)
3649                    .expect("failed-rcpd test process must expose a stable identity");
3650                Self {
3651                    pid,
3652                    process,
3653                    start_time,
3654                }
3655            }
3656        }
3657
3658        #[cfg(target_os = "linux")]
3659        impl Drop for KillTestProcessOnDrop {
3660            fn drop(&mut self) {
3661                if linux_process_start_time(&self.process).as_ref() == Some(&self.start_time) {
3662                    let _ = std::process::Command::new("kill")
3663                        .args(["-KILL", self.pid.as_str()])
3664                        .status();
3665                }
3666            }
3667        }
3668
3669        #[cfg(target_os = "linux")]
3670        async fn spawn_failed_rcpd_that_never_exits(
3671            session: &ManagedSshSession,
3672            directory: &std::path::Path,
3673        ) -> (
3674            openssh::Child<ManagedSshSession>,
3675            tokio::io::BufReader<openssh::ChildStderr>,
3676            KillTestProcessOnDrop,
3677        ) {
3678            use std::os::unix::fs::PermissionsExt;
3679            use tokio::io::AsyncBufReadExt;
3680
3681            let script = directory.join("failed-rcpd");
3682            let process_pid = directory.join("process-pid");
3683            std::fs::write(
3684            &script,
3685            format!(
3686                "#!/bin/sh\nprintf '%s\\n' \"$$\" > {}\nprintf '%s\\n' 'not a readiness record' >&2\nexec sleep 30\n",
3687                shell_escape(process_pid.to_str().unwrap()),
3688            ),
3689        )
3690        .unwrap();
3691            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
3692            let mut command =
3693                openssh::Session::to_command(session.clone(), script.to_str().unwrap());
3694            command
3695                .stdin(openssh::Stdio::piped())
3696                .stdout(openssh::Stdio::piped())
3697                .stderr(openssh::Stdio::piped());
3698            let mut child = command.spawn().await.unwrap();
3699            let stderr = child.stderr().take().unwrap();
3700            let mut stderr_reader = tokio::io::BufReader::new(stderr);
3701            let mut readiness = String::new();
3702            stderr_reader.read_line(&mut readiness).await.unwrap();
3703            assert_eq!(readiness, "not a readiness record\n");
3704            let pid = std::fs::read_to_string(process_pid).unwrap();
3705            let guard = KillTestProcessOnDrop::new(pid.trim().to_string());
3706            (child, stderr_reader, guard)
3707        }
3708
3709        #[cfg(target_os = "linux")]
3710        #[cfg_attr(
3711            rcp_nix_sandbox,
3712            ignore = "Nix sandbox lacks the SSH client and authenticated localhost service"
3713        )]
3714        #[tokio::test]
3715        async fn test_remote_failed_rcpd_reap_timeout_releases_child_session() {
3716            let directory = tempfile::tempdir().unwrap();
3717            let cleanup = RemoteCleanup::new().unwrap();
3718            let preparation = PreparationContext::uncancelled(cleanup.clone());
3719            let session = setup_ssh_session(
3720                &SshSession::local(),
3721                &preparation,
3722                BootstrapDeadline::new(std::time::Duration::from_secs(5)),
3723            )
3724            .await
3725            .expect("localhost SSH must be available");
3726            let weak_session = std::sync::Arc::downgrade(&session.0);
3727            let (child, stderr_reader, _process) =
3728                spawn_failed_rcpd_that_never_exits(&session, directory.path()).await;
3729
3730            let diagnostic = reap_failed_rcpd(child, "localhost", Some(stderr_reader)).await;
3731            assert!(diagnostic.is_none());
3732            drop(session);
3733            drop(preparation);
3734
3735            assert!(
3736                weak_session.upgrade().is_none(),
3737                "an expired failed-rcpd reap must release its child and managed SSH session"
3738            );
3739            cleanup.finish();
3740        }
3741
3742        #[cfg(target_os = "linux")]
3743        #[cfg_attr(
3744            rcp_nix_sandbox,
3745            ignore = "Nix sandbox lacks the SSH client and authenticated localhost service"
3746        )]
3747        #[tokio::test]
3748        async fn test_remote_cancelled_failed_rcpd_reap_releases_child_session() {
3749            let directory = tempfile::tempdir().unwrap();
3750            let cleanup = RemoteCleanup::new().unwrap();
3751            let preparation = PreparationContext::uncancelled(cleanup.clone());
3752            let session = setup_ssh_session(
3753                &SshSession::local(),
3754                &preparation,
3755                BootstrapDeadline::new(std::time::Duration::from_secs(5)),
3756            )
3757            .await
3758            .expect("localhost SSH must be available");
3759            let weak_session = std::sync::Arc::downgrade(&session.0);
3760            let (child, stderr_reader, _process) =
3761                spawn_failed_rcpd_that_never_exits(&session, directory.path()).await;
3762            let (first_poll_tx, first_poll_rx) = tokio::sync::oneshot::channel();
3763            let reaper = tokio::spawn(async move {
3764                let mut reaper =
3765                    Box::pin(reap_failed_rcpd(child, "localhost", Some(stderr_reader)));
3766                let mut first_poll_tx = Some(first_poll_tx);
3767                std::future::poll_fn(move |context| {
3768                    let result = std::future::Future::poll(reaper.as_mut(), context);
3769                    if let Some(first_poll_tx) = first_poll_tx.take() {
3770                        let _ = first_poll_tx.send(());
3771                    }
3772                    result
3773                })
3774                .await
3775            });
3776            first_poll_rx.await.unwrap();
3777
3778            reaper.abort();
3779            let error = reaper.await.unwrap_err();
3780            assert!(error.is_cancelled());
3781            drop(session);
3782            drop(preparation);
3783
3784            assert!(
3785                weak_session.upgrade().is_none(),
3786                "cancelling a failed-rcpd reap must release its child and managed SSH session"
3787            );
3788            cleanup.finish();
3789        }
3790
3791        #[cfg_attr(
3792            rcp_nix_sandbox,
3793            ignore = "Nix sandbox lacks the SSH client and authenticated localhost service"
3794        )]
3795        #[tokio::test]
3796        async fn test_remote_command_output_uses_required_bootstrap_deadline() {
3797            let cleanup = RemoteCleanup::new().unwrap();
3798            let preparation = PreparationContext::uncancelled(cleanup.clone());
3799            let session = setup_ssh_session(
3800                &SshSession::local(),
3801                &preparation,
3802                BootstrapDeadline::new(std::time::Duration::from_secs(5)),
3803            )
3804            .await
3805            .expect("localhost SSH must be available");
3806            let mut command = openssh::Session::to_command(session, "sh");
3807            command.arg("-c").arg("sleep 30");
3808            let result = tokio::time::timeout(
3809                std::time::Duration::from_secs(2),
3810                preparation.remote_output(
3811                    command,
3812                    "remote discovery probe",
3813                    BootstrapDeadline::new(std::time::Duration::from_millis(100)),
3814                ),
3815            )
3816            .await
3817            .expect("the shared remote-command helper did not enforce its deadline");
3818            let error = result.expect_err("the hanging remote command unexpectedly completed");
3819            assert!(
3820                format!("{error:#}").contains("remote discovery probe timed out after 100ms"),
3821                "configured deadline missing from remote-command error: {error:#}"
3822            );
3823            drop(preparation);
3824            cleanup.finish();
3825        }
3826
3827        #[cfg_attr(
3828            rcp_nix_sandbox,
3829            ignore = "Nix sandbox lacks the SSH client and authenticated localhost service"
3830        )]
3831        #[tokio::test]
3832        async fn test_remote_home_lookup_uses_required_bootstrap_deadline() {
3833            let cleanup = RemoteCleanup::new().unwrap();
3834            let preparation = PreparationContext::uncancelled(cleanup.clone());
3835            let session = setup_ssh_session(
3836                &SshSession::local(),
3837                &preparation,
3838                BootstrapDeadline::new(std::time::Duration::from_secs(5)),
3839            )
3840            .await
3841            .expect("localhost SSH must be available");
3842            let mut command = openssh::Session::to_command(session, "sh");
3843            command.arg("-c").arg("sleep 30");
3844            let result = tokio::time::timeout(
3845                std::time::Duration::from_secs(2),
3846                run_remote_home_probe(
3847                    command,
3848                    &preparation,
3849                    BootstrapDeadline::new(std::time::Duration::from_millis(100)),
3850                ),
3851            )
3852            .await
3853            .expect("the HOME lookup ignored its configured deadline");
3854            let error = result.expect_err("the hanging HOME lookup unexpectedly completed");
3855            assert!(
3856                format!("{error:#}").contains("remote HOME lookup timed out after 100ms"),
3857                "configured deadline missing from HOME lookup error: {error:#}"
3858            );
3859            drop(preparation);
3860            cleanup.finish();
3861        }
3862
3863        #[cfg_attr(
3864            rcp_nix_sandbox,
3865            ignore = "Nix sandbox lacks the SSH client and authenticated localhost service"
3866        )]
3867        #[tokio::test]
3868        async fn test_remote_cancelled_command_output_is_bounded() {
3869            let cancellation = tokio_util::sync::CancellationToken::new();
3870            let cleanup = RemoteCleanup::new().unwrap();
3871            let preparation = PreparationContext::new(cancellation.clone(), cleanup.clone());
3872            let session = setup_ssh_session(
3873                &SshSession::local(),
3874                &preparation,
3875                BootstrapDeadline::new(std::time::Duration::from_secs(5)),
3876            )
3877            .await
3878            .expect("localhost SSH must be available");
3879            let mut command = openssh::Session::to_command(session, "sh");
3880            command.arg("-c").arg("sleep 30");
3881            let cancel = tokio::spawn(async move {
3882                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
3883                cancellation.cancel();
3884            });
3885
3886            let result = tokio::time::timeout(
3887                std::time::Duration::from_secs(5),
3888                preparation.remote_output(
3889                    command,
3890                    "remote cancellation probe",
3891                    BootstrapDeadline::new(std::time::Duration::from_secs(30)),
3892                ),
3893            )
3894            .await
3895            .expect("peer cancellation did not bound the remote command");
3896            cancel.await.unwrap();
3897            drop(preparation);
3898            cleanup.finish();
3899            let error = result.expect_err("the cancelled remote command unexpectedly completed");
3900            assert!(
3901                format!("{error:#}")
3902                    .contains("rcpd preparation cancelled because peer preparation failed"),
3903                "peer cancellation missing from remote-command error: {error:#}"
3904            );
3905        }
3906
3907        #[cfg(unix)]
3908        #[cfg_attr(
3909            rcp_nix_sandbox,
3910            ignore = "Nix sandbox lacks the SSH client and authenticated localhost service"
3911        )]
3912        #[tokio::test]
3913        async fn test_remote_start_rcpd_uses_configured_version_probe_timeout() {
3914            use std::os::unix::fs::PermissionsExt;
3915
3916            let directory = std::env::temp_dir().join(format!(
3917                "rcp-configured-probe-timeout-{}-{:016x}",
3918                std::process::id(),
3919                rand::random::<u64>()
3920            ));
3921            std::fs::create_dir(&directory).unwrap();
3922            let script = directory.join("rcpd");
3923            std::fs::write(
3924            &script,
3925            "#!/bin/sh\nif [ \"$1\" = \"--protocol-version\" ]; then\n  exec sleep 30\nfi\nexit 99\n",
3926        )
3927        .unwrap();
3928            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
3929            let cleanup = RemoteCleanup::new().unwrap();
3930
3931            let config = test_rcpd_config();
3932            let result = tokio::time::timeout(std::time::Duration::from_secs(8), async {
3933                prepare_rcpd_with_context(
3934                    &SshSession::local(),
3935                    Some(script.to_str().unwrap()),
3936                    false,
3937                    PreparationContext::uncancelled(cleanup.clone()),
3938                    std::time::Duration::from_secs(config.remote_copy_conn_timeout_sec),
3939                )
3940                .await?
3941                .spawn(&config, None, protocol::RcpdRole::Source)
3942                .await
3943            })
3944            .await
3945            .expect("the configured one-second probe deadline was not honored");
3946            let error = match result {
3947                Ok(_) => panic!("the hanging version probe unexpectedly succeeded"),
3948                Err(error) => error,
3949            };
3950            let error = format!("{error:#}");
3951            assert!(
3952                error.contains("timed out after 1s"),
3953                "configured deadline missing from probe error: {error}"
3954            );
3955
3956            cleanup.finish();
3957            std::fs::remove_dir_all(directory).unwrap();
3958        }
3959
3960        #[cfg(unix)]
3961        #[cfg_attr(
3962            rcp_nix_sandbox,
3963            ignore = "Nix sandbox lacks the SSH client and authenticated localhost service"
3964        )]
3965        #[tokio::test]
3966        async fn test_remote_prepared_rcpd_readiness_uses_configured_timeout() {
3967            use std::os::unix::fs::PermissionsExt;
3968
3969            let directory = tempfile::tempdir().unwrap();
3970            let script = directory.path().join("rcpd");
3971            let daemon_exit = directory.path().join("daemon-exit");
3972            let version = common::version::ProtocolVersion::current()
3973                .to_json()
3974                .unwrap();
3975            let contents = format!(
3976                "#!/bin/sh\nif [ \"$1\" = \"--protocol-version\" ]; then\n  printf '%s\\n' {}\n  exit 0\nfi\ncat >/dev/null\nprintf 'exited\\n' > {}\n",
3977                shell_escape(&version),
3978                shell_escape(daemon_exit.to_str().unwrap()),
3979            );
3980            std::fs::write(&script, contents).unwrap();
3981            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
3982            let cleanup = RemoteCleanup::new().unwrap();
3983            let prepared = prepare_test_rcpd(
3984                &SshSession::local(),
3985                Some(script.to_str().unwrap()),
3986                false,
3987                &cleanup,
3988            )
3989            .await
3990            .unwrap();
3991            let result = tokio::time::timeout(
3992                std::time::Duration::from_secs(5),
3993                prepared.spawn(&test_rcpd_config(), None, protocol::RcpdRole::Source),
3994            )
3995            .await
3996            .expect("the configured one-second readiness deadline was not honored");
3997            let error = match result {
3998                Ok(_) => panic!("rcpd without a readiness record unexpectedly started"),
3999                Err(error) => format!("{error:#}"),
4000            };
4001            assert!(
4002                error.contains("timed out after 1s"),
4003                "configured deadline missing from readiness error: {error}"
4004            );
4005            assert_eq!(std::fs::read_to_string(daemon_exit).unwrap(), "exited\n");
4006            drop(prepared);
4007            cleanup.finish();
4008        }
4009
4010        #[cfg(unix)]
4011        #[cfg_attr(
4012            rcp_nix_sandbox,
4013            ignore = "Nix sandbox lacks the SSH client and authenticated localhost service"
4014        )]
4015        #[tokio::test]
4016        async fn test_remote_prepared_rcpd_rejects_an_oversized_readiness_record() {
4017            use std::os::unix::fs::PermissionsExt;
4018
4019            let directory = tempfile::tempdir().unwrap();
4020            let script = directory.path().join("rcpd");
4021            let version = common::version::ProtocolVersion::current()
4022                .to_json()
4023                .unwrap();
4024            let contents = format!(
4025                "#!/bin/sh\nif [ \"$1\" = \"--protocol-version\" ]; then\n  printf '%s\\n' {}\n  exit 0\nfi\ndd if=/dev/zero bs=71680 count=1 2>/dev/null | tr '\\000' x >&2\ncat >/dev/null\n",
4026                shell_escape(&version),
4027            );
4028            std::fs::write(&script, contents).unwrap();
4029            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
4030            let cleanup = RemoteCleanup::new().unwrap();
4031            let prepared = prepare_test_rcpd(
4032                &SshSession::local(),
4033                Some(script.to_str().unwrap()),
4034                false,
4035                &cleanup,
4036            )
4037            .await
4038            .unwrap();
4039            let mut config = test_rcpd_config();
4040            config.remote_copy_conn_timeout_sec = 5;
4041            let result = tokio::time::timeout(
4042                std::time::Duration::from_secs(3),
4043                prepared.spawn(&config, None, protocol::RcpdRole::Source),
4044            )
4045            .await
4046            .expect("an oversized readiness record must fail before the connection deadline");
4047            let error = match result {
4048                Ok(_) => panic!("an oversized readiness record unexpectedly started rcpd"),
4049                Err(error) => format!("{error:#}"),
4050            };
4051            assert!(
4052                error.contains("readiness record exceeds"),
4053                "oversized readiness error omitted the size limit: {error}"
4054            );
4055            drop(prepared);
4056            cleanup.finish();
4057        }
4058
4059        #[cfg(unix)]
4060        #[cfg_attr(
4061            rcp_nix_sandbox,
4062            ignore = "Nix sandbox lacks the SSH client and authenticated localhost service"
4063        )]
4064        #[tokio::test]
4065        async fn test_remote_prepared_rcpd_spawns_both_roles_after_one_preparation() {
4066            use std::os::unix::fs::PermissionsExt;
4067
4068            let directory = std::env::temp_dir().join(format!(
4069                "rcp-prepared-rcpd-{}-{:016x}",
4070                std::process::id(),
4071                rand::random::<u64>()
4072            ));
4073            std::fs::create_dir(&directory).unwrap();
4074            let script = directory.join("rcpd");
4075            let marker = directory.join("version-probes");
4076            let version = common::version::ProtocolVersion::current()
4077                .to_json()
4078                .unwrap();
4079            let contents = format!(
4080                "#!/bin/sh\nif [ \"$1\" = \"--protocol-version\" ]; then\n  printf 'probe\\n' >> {}\n  printf '%s\\n' {}\n  exit 0\nfi\nprintf '%s\\n' 'RCP_TCP 127.0.0.1:1234 4 4' >&2\ncat >/dev/null\n",
4081                shell_escape(marker.to_str().unwrap()),
4082                shell_escape(&version),
4083            );
4084            std::fs::write(&script, contents).unwrap();
4085            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
4086            let config = test_rcpd_config();
4087            let cleanup = RemoteCleanup::new().unwrap();
4088            let prepared = prepare_test_rcpd(
4089                &SshSession::local(),
4090                Some(script.to_str().unwrap()),
4091                false,
4092                &cleanup,
4093            )
4094            .await
4095            .unwrap();
4096            let source = prepared
4097                .spawn(&config, None, protocol::RcpdRole::Source)
4098                .await
4099                .unwrap();
4100            let destination = prepared
4101                .spawn(&config, None, protocol::RcpdRole::Destination)
4102                .await
4103                .unwrap();
4104            assert_eq!(std::fs::read_to_string(&marker).unwrap(), "probe\n");
4105            wait_for_rcpd_process(source).await.unwrap();
4106            wait_for_rcpd_process(destination).await.unwrap();
4107            drop(prepared);
4108            cleanup.finish();
4109            std::fs::remove_dir_all(directory).unwrap();
4110        }
4111
4112        #[cfg(unix)]
4113        #[cfg_attr(
4114            rcp_nix_sandbox,
4115            ignore = "Nix sandbox lacks the SSH client and authenticated localhost service"
4116        )]
4117        #[tokio::test]
4118        async fn test_remote_wait_for_rcpd_process_retains_daemon_diagnostics() {
4119            use std::os::unix::fs::PermissionsExt;
4120
4121            let directory = std::env::temp_dir().join(format!(
4122                "rcp-rcpd-diagnostics-{}-{:016x}",
4123                std::process::id(),
4124                rand::random::<u64>()
4125            ));
4126            std::fs::create_dir(&directory).unwrap();
4127            let script = directory.join("rcpd");
4128            let version = common::version::ProtocolVersion::current()
4129                .to_json()
4130                .unwrap();
4131            let contents = format!(
4132                "#!/bin/sh\nif [ \"$1\" = \"--protocol-version\" ]; then\n  printf '%s\\n' {}\n  exit 0\nfi\nprintf '%s\\n' 'RCP_TCP 127.0.0.1:1234 4 4' >&2\nprintf '%s\\n' 'daemon stdout detail'\nprintf '%s\\n' 'daemon stderr detail' >&2\nexit 42\n",
4133                shell_escape(&version),
4134            );
4135            std::fs::write(&script, contents).unwrap();
4136            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
4137
4138            let cleanup = RemoteCleanup::new().unwrap();
4139            let prepared = prepare_test_rcpd(
4140                &SshSession::local(),
4141                Some(script.to_str().unwrap()),
4142                false,
4143                &cleanup,
4144            )
4145            .await
4146            .unwrap();
4147            let process = prepared
4148                .spawn(&test_rcpd_config(), None, protocol::RcpdRole::Source)
4149                .await
4150                .unwrap();
4151            let error = wait_for_rcpd_process(process).await.unwrap_err();
4152            let error = format!("{error:#}");
4153            assert!(
4154                error.contains("daemon stdout detail"),
4155                "stdout diagnostic missing: {error}"
4156            );
4157            assert!(
4158                error.contains("daemon stderr detail"),
4159                "stderr diagnostic missing: {error}"
4160            );
4161            drop(prepared);
4162            cleanup.finish();
4163            std::fs::remove_dir_all(directory).unwrap();
4164        }
4165
4166        #[cfg(unix)]
4167        #[cfg_attr(
4168            rcp_nix_sandbox,
4169            ignore = "Nix sandbox lacks the SSH client and authenticated localhost service"
4170        )]
4171        #[tokio::test]
4172        async fn test_remote_failed_rcpd_bootstrap_reaps_child_before_returning() {
4173            use std::os::unix::fs::PermissionsExt;
4174
4175            let directory = std::env::temp_dir().join(format!(
4176                "rcp-failed-bootstrap-{}-{:016x}",
4177                std::process::id(),
4178                rand::random::<u64>()
4179            ));
4180            std::fs::create_dir(&directory).unwrap();
4181            let script = directory.join("rcpd");
4182            let source_exit = directory.join("source-exit");
4183            let destination_exit = directory.join("destination-exit");
4184            let version = common::version::ProtocolVersion::current()
4185                .to_json()
4186                .unwrap();
4187            let contents = format!(
4188                "#!/bin/sh\nif [ \"$1\" = \"--protocol-version\" ]; then\n  printf '%s\\n' {}\n  exit 0\nfi\nif [ \"$2\" = source ]; then\n  printf '%s\\n' 'RCP_ERROR pending file capacity test refusal' >&2\n  marker={}\nelse\n  printf '%s\\n' 'not a readiness record' >&2\n  printf '%s\\n' 'destination listener bind failed'\n  marker={}\nfi\ncat >/dev/null\nprintf 'exited\\n' > \"$marker\"\n",
4189                shell_escape(&version),
4190                shell_escape(source_exit.to_str().unwrap()),
4191                shell_escape(destination_exit.to_str().unwrap()),
4192            );
4193            std::fs::write(&script, contents).unwrap();
4194            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
4195            let cleanup = RemoteCleanup::new().unwrap();
4196            let prepared = prepare_test_rcpd(
4197                &SshSession::local(),
4198                Some(script.to_str().unwrap()),
4199                false,
4200                &cleanup,
4201            )
4202            .await
4203            .unwrap();
4204            let config = test_rcpd_config();
4205
4206            let refusal = match prepared
4207                .spawn(&config, None, protocol::RcpdRole::Source)
4208                .await
4209            {
4210                Ok(_) => panic!("startup refusal unexpectedly produced an rcpd process"),
4211                Err(error) => error,
4212            };
4213            assert!(refusal.to_string().contains("rcpd refused startup"));
4214            assert!(refusal.chain().any(|cause| {
4215                cause
4216                    .to_string()
4217                    .contains("pending file capacity test refusal")
4218            }));
4219            assert_eq!(std::fs::read_to_string(&source_exit).unwrap(), "exited\n");
4220
4221            let malformed = match prepared
4222                .spawn(&config, None, protocol::RcpdRole::Destination)
4223                .await
4224            {
4225                Ok(_) => panic!("malformed readiness unexpectedly produced an rcpd process"),
4226                Err(error) => error,
4227            };
4228            assert!(
4229                format!("{malformed:#}").contains("unexpected output from rcpd"),
4230                "unexpected startup error: {malformed:#}"
4231            );
4232            assert!(
4233                format!("{malformed:#}").contains("destination listener bind failed"),
4234                "startup output must retain the daemon's failure: {malformed:#}"
4235            );
4236            assert_eq!(
4237                std::fs::read_to_string(&destination_exit).unwrap(),
4238                "exited\n"
4239            );
4240            drop(prepared);
4241            cleanup.finish();
4242            std::fs::remove_dir_all(directory).unwrap();
4243        }
4244    }
4245
4246    #[test]
4247    fn rejects_effective_streams_above_tokio_semaphore_capacity() {
4248        let too_many = tokio::sync::Semaphore::MAX_PERMITS.checked_add(1).unwrap();
4249        let error = resolve_remote_concurrency(
4250            common::ConcurrencyLimit::Unlimited,
4251            std::num::NonZeroUsize::new(too_many).unwrap(),
4252            std::num::NonZeroUsize::new(1).unwrap(),
4253        )
4254        .unwrap_err();
4255        assert!(error.to_string().contains("Tokio semaphore maximum"));
4256    }
4257
4258    #[test]
4259    fn rejects_nonoverflowing_pending_capacity_above_tokio_maximum() {
4260        let half_plus_one = tokio::sync::Semaphore::MAX_PERMITS / 2 + 1;
4261        let error = resolve_remote_concurrency(
4262            common::ConcurrencyLimit::Unlimited,
4263            std::num::NonZeroUsize::new(half_plus_one).unwrap(),
4264            std::num::NonZeroUsize::new(2).unwrap(),
4265        )
4266        .unwrap_err();
4267        assert!(error.to_string().contains("pending file capacity"));
4268    }
4269
4270    #[test]
4271    fn readiness_records_report_negotiated_file_and_stream_limits() {
4272        let fingerprint_hex = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
4273        let cases = [
4274            (
4275                "RCP_TCP 127.0.0.1:1234 8 8".to_string(),
4276                common::ConcurrencyLimit::Limited(nonzero(8)),
4277                nonzero(8),
4278                None,
4279            ),
4280            (
4281                "RCP_TCP 127.0.0.1:1234 unlimited 100".to_string(),
4282                common::ConcurrencyLimit::Unlimited,
4283                nonzero(100),
4284                None,
4285            ),
4286            (
4287                format!("RCP_TLS 127.0.0.1:1234 {fingerprint_hex} 32 16"),
4288                common::ConcurrencyLimit::Limited(nonzero(32)),
4289                nonzero(16),
4290                Some(tls::fingerprint_from_hex(fingerprint_hex).unwrap()),
4291            ),
4292        ];
4293        for (record, expected_files, expected_streams, expected_fingerprint) in cases {
4294            let parsed = parse_rcpd_readiness(&record).unwrap();
4295            assert_eq!(parsed.addr, "127.0.0.1:1234".parse().unwrap());
4296            assert_eq!(parsed.fingerprint, expected_fingerprint);
4297            assert_eq!(parsed.files_in_flight, expected_files);
4298            assert_eq!(parsed.max_connections, expected_streams);
4299        }
4300    }
4301
4302    #[test]
4303    fn readiness_records_reject_invalid_limit_tokens() {
4304        for record in [
4305            "RCP_TCP 127.0.0.1:1234 0 1",
4306            "RCP_TCP 127.0.0.1:1234 automatic 1",
4307            "RCP_TCP 127.0.0.1:1234 1 0",
4308        ] {
4309            assert!(
4310                parse_rcpd_readiness(record).is_err(),
4311                "invalid readiness record was accepted: {record}"
4312            );
4313        }
4314    }
4315
4316    #[tokio::test]
4317    async fn empty_startup_refusal_reports_missing_diagnostic() {
4318        for record in ["RCP_ERROR\n", "RCP_ERROR \n"] {
4319            let mut reader = tokio::io::BufReader::new(record.as_bytes());
4320            let error = read_rcpd_startup_record(&mut reader)
4321                .await
4322                .expect_err("an empty startup refusal must fail");
4323            assert!(
4324                format!("{error:#}").contains("rcpd refused startup without a diagnostic"),
4325                "empty refusal was misclassified for {record:?}: {error:#}"
4326            );
4327        }
4328    }
4329
4330    #[tokio::test]
4331    async fn startup_error_prefix_requires_a_token_boundary() {
4332        let mut reader = tokio::io::BufReader::new("RCP_ERRORfoo\n".as_bytes());
4333        let error = read_rcpd_startup_record(&mut reader)
4334            .await
4335            .expect_err("an unknown readiness token must fail");
4336        assert!(
4337            !format!("{error:#}").contains("rcpd refused startup"),
4338            "a prefix collision was treated as a typed refusal: {error:#}"
4339        );
4340    }
4341
4342    #[cfg(target_os = "linux")]
4343    #[tokio::test]
4344    async fn test_remote_cancelled_ssh_setup_terminates_its_launcher() {
4345        use std::os::unix::fs::PermissionsExt;
4346
4347        let directory = std::env::temp_dir().join(format!(
4348            "rcp-ssh-launcher-{}-{:016x}",
4349            std::process::id(),
4350            rand::random::<u64>()
4351        ));
4352        std::fs::create_dir(&directory).unwrap();
4353        let launcher = directory.join("ssh");
4354        let pid_file = directory.join("pid");
4355        let args_file = directory.join("args");
4356        std::fs::write(
4357            &launcher,
4358            format!(
4359                "#!/bin/sh\nprintf '%s\\n' \"$*\" > {}\ncase \" $* \" in *\" ForkAfterAuthentication=no \"*) no_fork=yes ;; esac\ncase \" $* \" in *\" ControlPersist=no \"*) no_persist=yes ;; esac\nif [ \"$no_fork\" != yes ] || [ \"$no_persist\" != yes ]; then\n  setsid sh -c 'trap \"\" HUP TERM; printf \"%s\\n\" \"$$\" > \"$1\"; exec sleep 30' sh {} &\n  while [ ! -s {} ]; do sleep 0.01; done\n  sleep 0.2\n  exit 0\nfi\nprintf '%s\\n' \"$$\" > {}\nexec sleep 30\n",
4360                shell_escape(args_file.to_str().unwrap()),
4361                shell_escape(pid_file.to_str().unwrap()),
4362                shell_escape(pid_file.to_str().unwrap()),
4363                shell_escape(pid_file.to_str().unwrap()),
4364            ),
4365        )
4366        .unwrap();
4367        std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).unwrap();
4368        let session = SshSession::local();
4369        let cancellation = tokio_util::sync::CancellationToken::new();
4370        let cleanup = RemoteCleanup::new().unwrap();
4371        let preparation = PreparationContext::new(cancellation.clone(), cleanup.clone());
4372        let setup = tokio::spawn(async move {
4373            setup_ssh_session_with_program(
4374                &session,
4375                &preparation,
4376                &launcher,
4377                BootstrapDeadline::new(DEFAULT_REMOTE_BOOTSTRAP_TIMEOUT),
4378            )
4379            .await
4380        });
4381        tokio::time::timeout(std::time::Duration::from_secs(1), async {
4382            while std::fs::read_to_string(&pid_file)
4383                .map(|pid| pid.trim().is_empty())
4384                .unwrap_or(true)
4385            {
4386                tokio::task::yield_now().await;
4387            }
4388        })
4389        .await
4390        .expect("fake SSH launcher must start");
4391        let pid = std::fs::read_to_string(&pid_file).unwrap();
4392        let process = std::path::PathBuf::from(format!("/proc/{}", pid.trim()));
4393        assert!(process.exists(), "fake SSH launcher must still be running");
4394        let start_time = linux_process_start_time(&process)
4395            .expect("fake SSH launcher must expose a process identity");
4396        let arguments = std::fs::read_to_string(&args_file).unwrap();
4397        let control_directory = ssh_control_directory_from_arguments(&arguments);
4398        assert!(control_directory.exists());
4399        cancellation.cancel();
4400        let error = match setup.await.unwrap() {
4401            Ok(_) => panic!("cancelled SSH setup unexpectedly succeeded"),
4402            Err(error) => error,
4403        };
4404        assert!(
4405            error
4406                .to_string()
4407                .contains("cancelled because peer preparation failed")
4408        );
4409        assert!(
4410            arguments.contains("ForkAfterAuthentication=no")
4411                && arguments.contains("ControlPersist=no"),
4412            "launcher must override SSH config that could background the owned master: {arguments}"
4413        );
4414        cleanup.finish();
4415        if !wait_for_process_identity_to_disappear(&process, &start_time).await {
4416            let _ = std::process::Command::new("kill")
4417                .args(["-KILL", pid.trim()])
4418                .status();
4419            panic!("cancelling SSH setup left its launcher unreaped");
4420        }
4421        assert!(
4422            !control_directory.exists(),
4423            "cancelled SSH setup must remove its private control directory"
4424        );
4425        std::fs::remove_dir_all(directory).unwrap();
4426    }
4427
4428    #[test]
4429    fn ssh_master_launcher_resolves_configured_program_in_owned_shell_child() {
4430        let launcher = ssh_master_launcher_command(std::path::Path::new("/stalled/path/ssh"));
4431        let command = launcher.as_std();
4432        assert_eq!(command.get_program(), std::ffi::OsStr::new("/bin/sh"));
4433        let arguments = command.get_args().collect::<Vec<_>>();
4434        assert_eq!(
4435            arguments,
4436            [
4437                std::ffi::OsStr::new("-c"),
4438                std::ffi::OsStr::new("exec \"$@\""),
4439                std::ffi::OsStr::new("rcp-ssh-master"),
4440                std::ffi::OsStr::new("/stalled/path/ssh"),
4441            ]
4442        );
4443    }
4444
4445    #[test]
4446    fn openssh_host_strips_only_ipv6_operand_brackets() {
4447        for (host, expected) in [
4448            ("[2001:db8::1]", "2001:db8::1"),
4449            ("[fe80::1%eth0]", "fe80::1%eth0"),
4450            ("host.example", "host.example"),
4451            ("[host.example]", "[host.example]"),
4452            ("[host:name]", "[host:name]"),
4453            ("[fe80::1%]", "[fe80::1%]"),
4454            ("[2001:db8::1", "[2001:db8::1"),
4455        ] {
4456            let session = SshSession {
4457                user: None,
4458                host: host.to_string(),
4459                port: None,
4460            };
4461            assert_eq!(session.openssh_host(), expected, "unexpected host: {host}");
4462        }
4463    }
4464
4465    #[cfg(target_os = "linux")]
4466    #[tokio::test]
4467    async fn test_remote_ssh_setup_passes_bare_ipv6_host_to_launcher() {
4468        use std::os::unix::fs::PermissionsExt;
4469
4470        let directory = tempfile::tempdir().unwrap();
4471        let launcher = directory.path().join("ssh");
4472        let args_file = directory.path().join("args");
4473        std::fs::write(
4474            &launcher,
4475            format!(
4476                "#!/bin/sh\nprintf '%s\\n' \"$*\" > {}\nsocket=\nwhile [ \"$#\" -gt 0 ]; do\n  if [ \"$1\" = -S ]; then\n    shift\n    socket=$1\n  fi\n  shift\ndone\n: > \"$socket\"\nexec sleep 30\n",
4477                shell_escape(args_file.to_str().unwrap()),
4478            ),
4479        )
4480        .unwrap();
4481        std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).unwrap();
4482        let cleanup = RemoteCleanup::new().unwrap();
4483        let preparation = PreparationContext::uncancelled(cleanup.clone());
4484        let managed = setup_ssh_session_with_program(
4485            &SshSession {
4486                user: Some("remote-user".to_string()),
4487                host: "[2001:db8::1]".to_string(),
4488                port: Some(2222),
4489            },
4490            &preparation,
4491            &launcher,
4492            BootstrapDeadline::new(DEFAULT_REMOTE_BOOTSTRAP_TIMEOUT),
4493        )
4494        .await
4495        .unwrap();
4496
4497        let arguments = std::fs::read_to_string(&args_file).unwrap();
4498        let arguments = arguments.split_whitespace().collect::<Vec<_>>();
4499        assert_eq!(
4500            arguments.last().copied(),
4501            Some("2001:db8::1"),
4502            "the direct OpenSSH argv must not retain operand-syntax brackets: {arguments:?}"
4503        );
4504        assert!(
4505            arguments.windows(2).any(|pair| pair == ["-p", "2222"]),
4506            "the IPv6 normalization must retain the SSH port: {arguments:?}"
4507        );
4508        assert!(
4509            arguments
4510                .windows(2)
4511                .any(|pair| pair == ["-l", "remote-user"]),
4512            "the IPv6 normalization must retain the SSH user: {arguments:?}"
4513        );
4514
4515        drop(managed);
4516        drop(preparation);
4517        cleanup.finish();
4518    }
4519
4520    #[cfg(target_os = "linux")]
4521    #[tokio::test]
4522    async fn test_remote_ssh_setup_deadline_terminates_its_launcher() {
4523        use std::os::unix::fs::PermissionsExt;
4524
4525        let directory = tempfile::tempdir().unwrap();
4526        let launcher = directory.path().join("ssh");
4527        let pid_file = directory.path().join("pid");
4528        let args_file = directory.path().join("args");
4529        std::fs::write(
4530            &launcher,
4531            format!(
4532                "#!/bin/sh\nprintf '%s\\n' \"$*\" > {}\nprintf '%s\\n' \"$$\" > {}\nexec sleep 30\n",
4533                shell_escape(args_file.to_str().unwrap()),
4534                shell_escape(pid_file.to_str().unwrap()),
4535            ),
4536        )
4537        .unwrap();
4538        std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).unwrap();
4539        let session = SshSession::local();
4540        let cleanup = RemoteCleanup::new().unwrap();
4541        let preparation = PreparationContext::uncancelled(cleanup.clone());
4542        let mut setup = tokio::spawn(async move {
4543            setup_ssh_session_with_program(
4544                &session,
4545                &preparation,
4546                &launcher,
4547                BootstrapDeadline::new(std::time::Duration::from_millis(500)),
4548            )
4549            .await
4550        });
4551        tokio::time::timeout(std::time::Duration::from_secs(1), async {
4552            while std::fs::read_to_string(&pid_file)
4553                .map(|pid| pid.trim().is_empty())
4554                .unwrap_or(true)
4555            {
4556                tokio::task::yield_now().await;
4557            }
4558        })
4559        .await
4560        .expect("fake SSH launcher must start");
4561        let pid = std::fs::read_to_string(&pid_file).unwrap();
4562        let process = std::path::PathBuf::from(format!("/proc/{}", pid.trim()));
4563        let start_time = linux_process_start_time(&process)
4564            .expect("fake SSH launcher must expose a process identity");
4565        let arguments = std::fs::read_to_string(&args_file).unwrap();
4566        let control_directory = ssh_control_directory_from_arguments(&arguments);
4567        assert!(control_directory.exists());
4568        let result = match tokio::time::timeout(std::time::Duration::from_secs(2), &mut setup).await
4569        {
4570            Ok(result) => result.unwrap(),
4571            Err(_) => {
4572                setup.abort();
4573                let _ = setup.await;
4574                let _ = std::process::Command::new("kill")
4575                    .args(["-KILL", pid.trim()])
4576                    .status();
4577                panic!("the configured SSH setup deadline was not honored");
4578            }
4579        };
4580        let error = match result {
4581            Ok(_) => panic!("SSH setup without a control socket unexpectedly succeeded"),
4582            Err(error) => format!("{error:#}"),
4583        };
4584        assert!(
4585            error.contains("SSH session setup timed out after 500ms"),
4586            "configured deadline missing from SSH setup error: {error}"
4587        );
4588        cleanup.finish();
4589        if !wait_for_process_identity_to_disappear(&process, &start_time).await {
4590            let _ = std::process::Command::new("kill")
4591                .args(["-KILL", pid.trim()])
4592                .status();
4593            panic!("timed-out SSH setup must reap its launcher");
4594        }
4595        assert!(
4596            !control_directory.exists(),
4597            "timed-out SSH setup must remove its private control directory"
4598        );
4599    }
4600
4601    #[cfg(target_os = "linux")]
4602    #[test]
4603    fn test_remote_managed_ssh_drop_terminates_master_without_a_runtime() {
4604        use std::os::unix::fs::PermissionsExt;
4605
4606        let directory = std::env::temp_dir().join(format!(
4607            "rcp-managed-ssh-{}-{:016x}",
4608            std::process::id(),
4609            rand::random::<u64>()
4610        ));
4611        std::fs::create_dir(&directory).unwrap();
4612        let launcher = directory.join("ssh");
4613        let pid_file = directory.join("pid");
4614        let socket_file = directory.join("socket");
4615        std::fs::write(
4616            &launcher,
4617            format!(
4618                "#!/bin/sh\nsocket=\nwhile [ \"$#\" -gt 0 ]; do\n  if [ \"$1\" = -S ]; then\n    shift\n    socket=$1\n  fi\n  shift\ndone\nprintf '%s\\n' \"$$\" > {}\nprintf '%s\\n' \"$socket\" > {}\n: > \"$socket\"\nexec sleep 30\n",
4619                shell_escape(pid_file.to_str().unwrap()),
4620                shell_escape(socket_file.to_str().unwrap()),
4621            ),
4622        )
4623        .unwrap();
4624        std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).unwrap();
4625
4626        let runtime = tokio::runtime::Builder::new_current_thread()
4627            .enable_all()
4628            .build()
4629            .unwrap();
4630        let cleanup = RemoteCleanup::new().unwrap();
4631        let preparation = PreparationContext::uncancelled(cleanup.clone());
4632        let managed = runtime
4633            .block_on(setup_ssh_session_with_program(
4634                &SshSession::local(),
4635                &preparation,
4636                &launcher,
4637                BootstrapDeadline::new(DEFAULT_REMOTE_BOOTSTRAP_TIMEOUT),
4638            ))
4639            .unwrap();
4640        let pid = std::fs::read_to_string(&pid_file).unwrap();
4641        let process = std::path::PathBuf::from(format!("/proc/{}", pid.trim()));
4642        assert!(process_is_running(&process));
4643        let control_path =
4644            std::path::PathBuf::from(std::fs::read_to_string(&socket_file).unwrap().trim());
4645        let control_directory = control_path.parent().unwrap().to_path_buf();
4646        assert!(control_directory.exists());
4647        runtime.shutdown_timeout(std::time::Duration::from_millis(100));
4648
4649        drop(managed);
4650        drop(preparation);
4651        cleanup.finish();
4652        if process_is_running(&process) {
4653            let _ = std::process::Command::new("kill")
4654                .args(["-KILL", pid.trim()])
4655                .status();
4656            panic!("dropping the managed session did not terminate its SSH master");
4657        }
4658        assert!(
4659            !control_directory.exists(),
4660            "off-runtime SSH cleanup must remove its private control directory"
4661        );
4662        std::fs::remove_dir_all(directory).unwrap();
4663    }
4664
4665    #[cfg(target_os = "linux")]
4666    fn process_is_running(process: &std::path::Path) -> bool {
4667        let Ok(status) = std::fs::read_to_string(process.join("status")) else {
4668            return false;
4669        };
4670        !status.lines().any(|line| line.starts_with("State:\tZ"))
4671    }
4672
4673    #[cfg(target_os = "linux")]
4674    fn linux_process_start_time(process: &std::path::Path) -> Option<String> {
4675        let stat = std::fs::read_to_string(process.join("stat")).ok()?;
4676        let (_, fields) = stat.rsplit_once(") ")?;
4677        fields.split_whitespace().nth(19).map(str::to_string)
4678    }
4679
4680    #[cfg(target_os = "linux")]
4681    async fn wait_for_process_identity_to_disappear(
4682        process: &std::path::Path,
4683        start_time: &str,
4684    ) -> bool {
4685        tokio::time::timeout(std::time::Duration::from_secs(1), async {
4686            while linux_process_start_time(process).as_deref() == Some(start_time) {
4687                tokio::task::yield_now().await;
4688            }
4689        })
4690        .await
4691        .is_ok()
4692    }
4693
4694    #[cfg(target_os = "linux")]
4695    fn ssh_control_directory_from_arguments(arguments: &str) -> std::path::PathBuf {
4696        let mut arguments = arguments.split_whitespace();
4697        while let Some(argument) = arguments.next() {
4698            if argument == "-S" {
4699                let socket = arguments
4700                    .next()
4701                    .expect("SSH -S must be followed by its socket path");
4702                return std::path::Path::new(socket)
4703                    .parent()
4704                    .expect("SSH control socket must have a parent directory")
4705                    .to_path_buf();
4706            }
4707        }
4708        panic!("SSH launcher arguments are missing -S: {arguments:?}");
4709    }
4710
4711    #[test]
4712    fn failed_rcpd_output_keeps_both_captured_streams() {
4713        assert_eq!(
4714            format_failed_rcpd_output(b"destination listener bind failed\n", "daemon detail\n"),
4715            Some("stdout: destination listener bind failed; stderr: daemon detail".to_string())
4716        );
4717    }
4718
4719    #[test]
4720    fn bounded_diagnostic_capture_retains_only_the_tail() {
4721        let mut output = b"012345".to_vec();
4722        assert!(retain_bounded_tail(&mut output, b"6789", 6));
4723        assert_eq!(output, b"456789");
4724        assert!(retain_bounded_tail(&mut output, b"abcdefgh", 6));
4725        assert_eq!(output, b"cdefgh");
4726    }
4727
4728    #[tokio::test]
4729    async fn cancelling_output_drain_aborts_its_collector() {
4730        struct NotifyDrop(Option<tokio::sync::oneshot::Sender<()>>);
4731
4732        impl Drop for NotifyDrop {
4733            fn drop(&mut self) {
4734                if let Some(sender) = self.0.take() {
4735                    let _ = sender.send(());
4736                }
4737            }
4738        }
4739
4740        let (started_tx, started_rx) = tokio::sync::oneshot::channel();
4741        let (dropped_tx, dropped_rx) = tokio::sync::oneshot::channel();
4742        let collector = tokio::spawn(async move {
4743            let _notify_drop = NotifyDrop(Some(dropped_tx));
4744            let _ = started_tx.send(());
4745            std::future::pending::<CapturedOutput>().await
4746        });
4747        started_rx.await.unwrap();
4748        let drain = tokio::spawn(finish_rcpd_output_drain(
4749            AbortOnDropTask::new(collector),
4750            "test",
4751        ));
4752        tokio::task::yield_now().await;
4753
4754        drain.abort();
4755        let _ = drain.await;
4756
4757        tokio::time::timeout(std::time::Duration::from_secs(1), dropped_rx)
4758            .await
4759            .expect("cancelling output drain must abort its collector")
4760            .unwrap();
4761    }
4762
4763    #[tokio::test]
4764    async fn daemon_output_is_forwarded_before_eof_and_capture_remains_bounded() {
4765        use tokio::io::AsyncWriteExt;
4766
4767        let (mut writer, reader) = tokio::io::duplex(64);
4768        let (forwarded_tx, mut forwarded_rx) = tokio::sync::mpsc::unbounded_channel();
4769        let collector = tokio::spawn(drain_bounded_output_forwarding(reader, 8, move |chunk| {
4770            let _ = forwarded_tx.send(chunk.to_vec());
4771        }));
4772        writer.write_all(b"sentinel\n").await.unwrap();
4773
4774        let forwarded =
4775            tokio::time::timeout(std::time::Duration::from_secs(1), forwarded_rx.recv())
4776                .await
4777                .expect("daemon output must be forwarded while its stream is open")
4778                .expect("daemon output collector must remain connected");
4779
4780        assert_eq!(forwarded, b"sentinel\n");
4781        assert!(
4782            !collector.is_finished(),
4783            "forwarding output must not require EOF"
4784        );
4785        writer.write_all(b"0123456789").await.unwrap();
4786        drop(writer);
4787        let captured = collector.await.unwrap();
4788        assert_eq!(captured.bytes, b"23456789");
4789        assert!(captured.truncated);
4790    }
4791
4792    #[test]
4793    fn daemon_output_forwarding_preserves_utf8_split_across_reads() {
4794        let mut forwarded = Vec::new();
4795        {
4796            let mut forwarder = Utf8ChunkForwarder::new(|text| forwarded.push(text.to_string()));
4797            let output = "prefix € suffix".as_bytes();
4798            forwarder.push(&output[..8]);
4799            forwarder.push(&output[8..9]);
4800            forwarder.push(&output[9..]);
4801            forwarder.finish();
4802        }
4803
4804        assert_eq!(forwarded.concat(), "prefix € suffix");
4805    }
4806
4807    #[test]
4808    fn control_directory_selection_reaches_a_usable_home_fallback() {
4809        let home = tempfile::tempdir().unwrap();
4810        let missing = home.path().join("missing");
4811        assert_eq!(
4812            select_ssh_control_directory([missing.clone(), home.path().to_path_buf()]),
4813            Some(home.path().to_path_buf())
4814        );
4815        assert_eq!(select_ssh_control_directory([missing]), None);
4816    }
4817
4818    #[test]
4819    fn control_directory_selection_stays_outside_a_local_operand_tree() {
4820        let local_operand = tempfile::tempdir().unwrap();
4821        let nested_temp = local_operand.path().join("tmp");
4822        std::fs::create_dir(&nested_temp).unwrap();
4823        let missing_system_temp = local_operand.path().join("missing-system-temp");
4824
4825        assert_eq!(
4826            select_ssh_control_directory_from_environment(
4827                None,
4828                nested_temp,
4829                missing_system_temp,
4830                None,
4831                None,
4832                &[local_operand.path().to_path_buf()],
4833            ),
4834            None,
4835            "a usable directory inside a local operand is not an SSH artifact fallback"
4836        );
4837    }
4838
4839    #[test]
4840    fn control_directory_selection_without_local_operands_accepts_an_absolute_candidate() {
4841        let temp = tempfile::tempdir().unwrap();
4842
4843        assert_eq!(
4844            select_ssh_control_directory_from_environment(
4845                None,
4846                temp.path().to_path_buf(),
4847                temp.path().to_path_buf(),
4848                None,
4849                None,
4850                &[],
4851            ),
4852            Some(temp.path().to_path_buf()),
4853            "remote-to-remote copies have no local operand tree to exclude"
4854        );
4855    }
4856
4857    #[test]
4858    fn control_directory_selection_accepts_an_ancestor_of_a_local_operand() {
4859        let candidate = tempfile::tempdir().unwrap();
4860        let local_operand = candidate.path().join("copy-source");
4861        std::fs::create_dir(&local_operand).unwrap();
4862
4863        assert_eq!(
4864            select_ssh_control_directory_from_environment(
4865                None,
4866                candidate.path().to_path_buf(),
4867                candidate.path().to_path_buf(),
4868                None,
4869                None,
4870                &[local_operand],
4871            ),
4872            Some(candidate.path().to_path_buf()),
4873            "a private sibling in the candidate directory is outside the copied subtree"
4874        );
4875    }
4876
4877    #[test]
4878    fn control_directory_selection_does_not_exclude_the_filesystem_root() {
4879        let temp = tempfile::tempdir().unwrap();
4880
4881        assert_eq!(
4882            select_ssh_control_directory_from_environment(
4883                None,
4884                temp.path().to_path_buf(),
4885                temp.path().to_path_buf(),
4886                None,
4887                None,
4888                &[std::path::PathBuf::from("/")],
4889            ),
4890            Some(temp.path().to_path_buf()),
4891            "the root operand cannot exclude every absolute socket candidate"
4892        );
4893    }
4894
4895    #[cfg(unix)]
4896    #[test]
4897    fn control_directory_selection_resolves_aliases_into_a_local_operand_tree() {
4898        use std::os::unix::fs::symlink;
4899
4900        let local_operand = tempfile::tempdir().unwrap();
4901        let nested_temp = local_operand.path().join("tmp");
4902        std::fs::create_dir(&nested_temp).unwrap();
4903        let aliases = tempfile::tempdir().unwrap();
4904        let nested_alias = aliases.path().join("tmp-alias");
4905        symlink(&nested_temp, &nested_alias).unwrap();
4906        let missing_system_temp = aliases.path().join("missing-system-temp");
4907
4908        assert_eq!(
4909            select_ssh_control_directory_from_environment(
4910                None,
4911                nested_alias,
4912                missing_system_temp,
4913                None,
4914                None,
4915                &[local_operand.path().to_path_buf()],
4916            ),
4917            None,
4918            "a path alias into a local operand is not an SSH artifact fallback"
4919        );
4920    }
4921
4922    #[test]
4923    fn tcp_config_effective_connections_meet_finite_file_ceiling() {
4924        let configured = nonzero(8);
4925        for (files_in_flight, expected) in [(3, 3), (8, 8), (12, 8)] {
4926            assert_eq!(
4927                effective_max_connections(
4928                    common::ConcurrencyLimit::Limited(nonzero(files_in_flight)),
4929                    configured,
4930                ),
4931                nonzero(expected),
4932            );
4933        }
4934    }
4935
4936    #[test]
4937    fn tcp_config_effective_connections_keep_configured_ceiling_when_files_are_unlimited() {
4938        assert_eq!(
4939            effective_max_connections(common::ConcurrencyLimit::Unlimited, nonzero(8)),
4940            nonzero(8),
4941        );
4942    }
4943
4944    #[test]
4945    fn remote_concurrency_pending_capacity_uses_connections_and_multiplier() {
4946        let concurrency =
4947            resolve_remote_concurrency(common::ConcurrencyLimit::Unlimited, nonzero(3), nonzero(4))
4948                .unwrap();
4949        assert_eq!(concurrency.max_pending_files().get(), 12);
4950    }
4951
4952    #[test]
4953    fn remote_concurrency_pending_capacity_rejects_overflow() {
4954        let valid_streams = tokio::sync::Semaphore::MAX_PERMITS;
4955        let overflowing_multiplier = usize::MAX / valid_streams + 1;
4956        let error = resolve_remote_concurrency(
4957            common::ConcurrencyLimit::Unlimited,
4958            nonzero(valid_streams),
4959            nonzero(overflowing_multiplier),
4960        )
4961        .unwrap_err();
4962        assert!(
4963            error.to_string().contains("pending file capacity overflow"),
4964            "unexpected error: {error:#}"
4965        );
4966    }
4967
4968    #[test]
4969    fn remote_concurrency_rejects_stream_limit_before_pending_overflow() {
4970        let error = resolve_remote_concurrency(
4971            common::ConcurrencyLimit::Unlimited,
4972            nonzero(tokio::sync::Semaphore::MAX_PERMITS + 1),
4973            nonzero(usize::MAX),
4974        )
4975        .unwrap_err();
4976
4977        assert!(
4978            error.to_string().contains("effective stream capacity"),
4979            "unexpected capacity error: {error:#}"
4980        );
4981    }
4982
4983    struct MockDiscoverySession {
4984        test_responses: HashMap<String, bool>,
4985        path_response: Option<String>,
4986        home_response: Result<Option<String>, String>,
4987        calls: Mutex<Vec<String>>,
4988    }
4989
4990    impl Default for MockDiscoverySession {
4991        fn default() -> Self {
4992            Self {
4993                test_responses: HashMap::new(),
4994                path_response: None,
4995                home_response: Ok(None),
4996                calls: Mutex::new(Vec::new()),
4997            }
4998        }
4999    }
5000
5001    impl MockDiscoverySession {
5002        fn new() -> Self {
5003            Self::default()
5004        }
5005
5006        fn with_home(mut self, home: Option<&str>) -> Self {
5007            self.home_response = Ok(home.map(str::to_string));
5008            self
5009        }
5010        fn with_home_error(mut self, error: &str) -> Self {
5011            self.home_response = Err(error.to_string());
5012            self
5013        }
5014        fn with_path(mut self, path: Option<&str>) -> Self {
5015            self.path_response = path.map(|p| p.to_string());
5016            self
5017        }
5018        fn set_test_response(&mut self, path: &str, exists: bool) {
5019            self.test_responses.insert(path.to_string(), exists);
5020        }
5021        fn calls(&self) -> Vec<String> {
5022            self.calls.lock().unwrap().clone()
5023        }
5024    }
5025
5026    impl DiscoverySession for MockDiscoverySession {
5027        fn test_executable<'a>(
5028            &'a self,
5029            path: &'a str,
5030        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<bool>> + Send + 'a>>
5031        {
5032            self.calls.lock().unwrap().push(format!("test:{}", path));
5033            let exists = self.test_responses.get(path).copied().unwrap_or(false);
5034            Box::pin(async move { Ok(exists) })
5035        }
5036        fn find_in_path<'a>(
5037            &'a self,
5038            binary: &'a str,
5039        ) -> std::pin::Pin<
5040            Box<dyn std::future::Future<Output = anyhow::Result<Option<String>>> + Send + 'a>,
5041        > {
5042            self.calls.lock().unwrap().push(format!("path:{}", binary));
5043            let result = self.path_response.clone();
5044            Box::pin(async move { Ok(result) })
5045        }
5046        fn remote_home<'a>(
5047            &'a self,
5048        ) -> std::pin::Pin<
5049            Box<dyn std::future::Future<Output = anyhow::Result<Option<String>>> + Send + 'a>,
5050        > {
5051            self.calls.lock().unwrap().push("home".to_string());
5052            let result = self.home_response.clone();
5053            Box::pin(async move {
5054                match result {
5055                    Ok(home) => Ok(home),
5056                    Err(e) => Err(anyhow::anyhow!(e)),
5057                }
5058            })
5059        }
5060    }
5061
5062    struct BlockingDrop {
5063        started: Option<std::sync::mpsc::Sender<()>>,
5064        release: std::sync::Arc<(Mutex<bool>, Condvar)>,
5065        finished: Option<std::sync::mpsc::Sender<()>>,
5066    }
5067
5068    impl Drop for BlockingDrop {
5069        fn drop(&mut self) {
5070            let _ = self.started.take().unwrap().send(());
5071            let (released, release_changed) = &*self.release;
5072            let mut released = released.lock().unwrap();
5073            while !*released {
5074                released = release_changed.wait(released).unwrap();
5075            }
5076            let _ = self.finished.take().unwrap().send(());
5077        }
5078    }
5079
5080    struct BlockingDropRelease(std::sync::Arc<(Mutex<bool>, Condvar)>);
5081
5082    impl BlockingDropRelease {
5083        fn release(&self) {
5084            let (released, release_changed) = &*self.0;
5085            *released.lock().unwrap() = true;
5086            release_changed.notify_all();
5087        }
5088    }
5089
5090    impl Drop for BlockingDropRelease {
5091        fn drop(&mut self) {
5092            self.release();
5093        }
5094    }
5095
5096    #[test]
5097    fn deferred_drop_is_nonblocking_without_a_tokio_runtime() {
5098        let cleanup = RemoteCleanup::new().unwrap();
5099        let watchdog = std::time::Duration::from_secs(1);
5100        let (drop_started, wait_for_drop) = std::sync::mpsc::channel();
5101        let (drop_finished, wait_for_drop_finish) = std::sync::mpsc::channel();
5102        let (drop_returned, wait_for_return) = std::sync::mpsc::channel();
5103        let release = std::sync::Arc::new((Mutex::new(false), Condvar::new()));
5104        let release_guard = BlockingDropRelease(release.clone());
5105        let blocking_drop = BlockingDrop {
5106            started: Some(drop_started),
5107            release,
5108            finished: Some(drop_finished),
5109        };
5110        let cleanup_for_drop = cleanup.clone();
5111
5112        let coordinator = std::thread::spawn(move || {
5113            cleanup_for_drop.defer_drop(blocking_drop, "rcp-test-cleanup");
5114            drop_returned.send(()).unwrap();
5115        });
5116        wait_for_drop
5117            .recv_timeout(watchdog)
5118            .expect("deferred destructor must start");
5119        let returned_before_destructor = wait_for_return.recv_timeout(watchdog).is_ok();
5120        release_guard.release();
5121        coordinator.join().unwrap();
5122        wait_for_drop_finish
5123            .recv_timeout(watchdog)
5124            .expect("deferred destructor must finish after release");
5125
5126        assert!(
5127            returned_before_destructor,
5128            "dropping the owner must not wait for its blocking destructor"
5129        );
5130        cleanup.finish();
5131    }
5132
5133    #[test]
5134    fn cleanup_construction_failure_accepts_no_work() {
5135        let error = RemoteCleanup::try_new_with(|_| {
5136            Err(std::io::Error::other("cleanup supervisor unavailable"))
5137        })
5138        .expect_err("a scope without its supervisor must not be created");
5139
5140        assert_eq!(error.kind(), std::io::ErrorKind::Other);
5141        assert_eq!(error.to_string(), "cleanup supervisor unavailable");
5142    }
5143
5144    #[test]
5145    fn stopped_supervisor_never_runs_cleanup_on_the_submitter() {
5146        let (supervisor_stopped_tx, supervisor_stopped_rx) = std::sync::mpsc::channel();
5147        let cleanup = RemoteCleanup::try_new_with(move |_operation| {
5148            std::thread::Builder::new()
5149                .name("rcp-test-stopped-cleanup-supervisor".to_string())
5150                .spawn(move || {
5151                    supervisor_stopped_tx.send(()).unwrap();
5152                })
5153        })
5154        .unwrap();
5155        supervisor_stopped_rx
5156            .recv_timeout(std::time::Duration::from_secs(1))
5157            .expect("test supervisor must stop before submission");
5158        let stopped_deadline = std::time::Instant::now() + std::time::Duration::from_secs(1);
5159        while !cleanup
5160            .state
5161            .supervisor
5162            .lock()
5163            .unwrap_or_else(std::sync::PoisonError::into_inner)
5164            .as_ref()
5165            .is_some_and(std::thread::JoinHandle::is_finished)
5166        {
5167            assert!(
5168                std::time::Instant::now() < stopped_deadline,
5169                "test supervisor did not finish after reporting shutdown"
5170            );
5171            std::thread::yield_now();
5172        }
5173        let submitter = std::thread::current().id();
5174        let (executed_tx, executed_rx) = std::sync::mpsc::channel();
5175
5176        cleanup.defer_bounded("rcp-test-supervisor-fallback", move |_budget| {
5177            executed_tx.send(std::thread::current().id()).unwrap();
5178        });
5179
5180        let executor = executed_rx
5181            .recv_timeout(std::time::Duration::from_secs(1))
5182            .expect("fallback cleanup must execute");
5183        assert_ne!(
5184            executor, submitter,
5185            "a stopped supervisor must not move blocking cleanup onto its submitter"
5186        );
5187        cleanup.finish();
5188    }
5189
5190    #[test]
5191    fn cleanup_grace_also_retires_the_supervisor() {
5192        let cleanup = RemoteCleanup::new().unwrap();
5193        let state = cleanup.state.clone();
5194        let (started_tx, started_rx) = std::sync::mpsc::channel();
5195        let release = std::sync::Arc::new((Mutex::new(false), Condvar::new()));
5196        let worker_release = release.clone();
5197        cleanup
5198            .submit_disposable("rcp-test-blocked-cleanup", move || {
5199                started_tx.send(()).unwrap();
5200                let (released, release_changed) = &*worker_release;
5201                let mut released = released.lock().unwrap();
5202                while !*released {
5203                    released = release_changed.wait(released).unwrap();
5204                }
5205            })
5206            .unwrap();
5207        started_rx
5208            .recv_timeout(std::time::Duration::from_secs(1))
5209            .expect("cleanup worker must start");
5210
5211        let supervisor_joined = cleanup.finish_with_grace(std::time::Duration::from_millis(250));
5212
5213        assert!(
5214            state
5215                .supervisor
5216                .lock()
5217                .unwrap_or_else(std::sync::PoisonError::into_inner)
5218                .is_none(),
5219            "the supervisor handle must leave shared state within the same cleanup grace"
5220        );
5221        assert!(
5222            supervisor_joined,
5223            "the cleanup supervisor itself must be joined within the shared cleanup grace"
5224        );
5225        let (released, release_changed) = &*release;
5226        *released.lock().unwrap() = true;
5227        release_changed.notify_all();
5228    }
5229
5230    #[test]
5231    fn cleanup_grace_never_joins_a_still_running_supervisor() {
5232        let (operation_finished_tx, operation_finished_rx) = std::sync::mpsc::channel();
5233        let release = std::sync::Arc::new((Mutex::new(false), Condvar::new()));
5234        let supervisor_release = release.clone();
5235        let cleanup = RemoteCleanup::try_new_with(move |operation| {
5236            std::thread::Builder::new()
5237                .name("rcp-test-blocked-supervisor-exit".to_string())
5238                .spawn(move || {
5239                    operation();
5240                    operation_finished_tx.send(()).unwrap();
5241                    let (released, release_changed) = &*supervisor_release;
5242                    let mut released = released.lock().unwrap();
5243                    while !*released {
5244                        released = release_changed.wait(released).unwrap();
5245                    }
5246                })
5247        })
5248        .unwrap();
5249
5250        let supervisor_joined = cleanup.finish_with_grace(std::time::Duration::from_millis(20));
5251
5252        operation_finished_rx
5253            .recv_timeout(std::time::Duration::from_secs(1))
5254            .expect("the supervisor operation must finish before the wrapper remains blocked");
5255        assert!(
5256            !supervisor_joined,
5257            "a supervisor wrapper still running after the deadline must be detached"
5258        );
5259        let (released, release_changed) = &*release;
5260        *released.lock().unwrap() = true;
5261        release_changed.notify_all();
5262    }
5263
5264    #[test]
5265    fn cleanup_finish_deadline_shortens_an_active_job_budget() {
5266        let cleanup = RemoteCleanup::new().unwrap();
5267        let (started_tx, started_rx) = std::sync::mpsc::channel();
5268        let (finished_tx, finished_rx) = std::sync::mpsc::channel();
5269        cleanup.defer_bounded("rcp-test-shared-cleanup-deadline", move |budget| {
5270            started_tx.send(()).unwrap();
5271            let started = std::time::Instant::now();
5272            let exited = poll_process_exit_until_deadline(&budget, || Ok(false)).unwrap();
5273            finished_tx.send((exited, started.elapsed())).unwrap();
5274        });
5275        started_rx
5276            .recv_timeout(std::time::Duration::from_secs(1))
5277            .expect("bounded cleanup must start before publishing the finish deadline");
5278
5279        cleanup.finish_with_grace(std::time::Duration::from_millis(20));
5280
5281        let (exited, elapsed) = finished_rx
5282            .recv_timeout(std::time::Duration::from_secs(1))
5283            .expect("the shared finish deadline must wake and stop the cleanup worker");
5284        assert!(!exited, "a process that never exited must remain unreaped");
5285        assert!(
5286            elapsed < std::time::Duration::from_secs(1),
5287            "the per-job cleanup deadline ignored the shorter shared finish deadline"
5288        );
5289    }
5290
5291    #[test]
5292    fn cleanup_submitted_after_finish_gets_a_fresh_job_budget() {
5293        let cleanup = RemoteCleanup::new().unwrap();
5294        let later_owner = cleanup.clone();
5295
5296        cleanup.finish_with_grace(std::time::Duration::from_millis(20));
5297
5298        let (waited_tx, waited_rx) = std::sync::mpsc::channel();
5299        later_owner.defer_bounded("rcp-test-late-cleanup-budget", move |budget| {
5300            waited_tx.send(budget.wait_for_next_poll()).unwrap();
5301        });
5302        assert!(
5303            waited_rx
5304                .recv_timeout(std::time::Duration::from_secs(1))
5305                .expect("cleanup submitted by a remaining owner must run"),
5306            "an earlier owner's expired finish deadline must not poison a later cleanup job"
5307        );
5308        later_owner.finish();
5309    }
5310
5311    #[test]
5312    fn process_polling_stops_at_its_cleanup_budget() {
5313        let cleanup = RemoteCleanup::new().unwrap();
5314        let budget =
5315            CleanupBudget::for_job(cleanup.state.clone(), std::time::Duration::from_millis(20));
5316        let polls = std::sync::atomic::AtomicUsize::new(0);
5317        let started = std::time::Instant::now();
5318
5319        let reaped = poll_process_exit_until_deadline(&budget, || {
5320            polls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5321            Ok(false)
5322        })
5323        .unwrap();
5324
5325        assert!(
5326            !reaped,
5327            "a process still running at the deadline is unreaped"
5328        );
5329        assert!(
5330            started.elapsed() < std::time::Duration::from_secs(1),
5331            "cleanup process polling exceeded its mandatory budget"
5332        );
5333        assert!(polls.load(std::sync::atomic::Ordering::Relaxed) >= 1);
5334        cleanup.finish();
5335    }
5336
5337    #[test]
5338    fn dropping_last_cleanup_owner_still_drains_queued_work() {
5339        let start_supervisor = std::sync::Arc::new(std::sync::Barrier::new(2));
5340        let supervisor_gate = start_supervisor.clone();
5341        let cleanup = RemoteCleanup::try_new_with(move |operation| {
5342            std::thread::Builder::new()
5343                .name("rcp-test-gated-cleanup-supervisor".to_string())
5344                .spawn(move || {
5345                    supervisor_gate.wait();
5346                    operation();
5347                })
5348        })
5349        .unwrap();
5350        let (executed_tx, executed_rx) = std::sync::mpsc::channel();
5351        cleanup.defer_bounded("rcp-test-drop-cleanup", move |_budget| {
5352            executed_tx.send(()).unwrap();
5353        });
5354
5355        drop(cleanup);
5356        start_supervisor.wait();
5357
5358        executed_rx
5359            .recv_timeout(std::time::Duration::from_secs(1))
5360            .expect("the supervisor must retain queued cleanup after its final owner drops");
5361    }
5362
5363    #[test]
5364    fn ssh_control_directory_waits_for_master_exit() {
5365        let root = tempfile::tempdir().unwrap();
5366        let control_directory = root.path().join("control");
5367        std::fs::create_dir(&control_directory).unwrap();
5368        let cleanup = RemoteCleanup::new().unwrap();
5369        let budget = CleanupBudget::for_job(cleanup.state.clone(), REMOTE_CLEANUP_GRACE);
5370        let (polled_tx, polled_rx) = std::sync::mpsc::channel();
5371        let (exit_tx, exit_rx) = std::sync::mpsc::channel();
5372        let worker_control_directory = control_directory.clone();
5373        let worker = std::thread::spawn(move || {
5374            reap_process_and_control_directory(
5375                &budget,
5376                Some(&worker_control_directory),
5377                move || {
5378                    polled_tx.send(()).unwrap();
5379                    exit_rx.recv().unwrap();
5380                    Ok(true)
5381                },
5382            );
5383        });
5384
5385        polled_rx
5386            .recv_timeout(std::time::Duration::from_secs(1))
5387            .expect("the reaper must inspect the process before changing the directory");
5388        assert!(
5389            control_directory.exists(),
5390            "the control directory must outlive a still-running SSH master"
5391        );
5392
5393        exit_tx.send(()).unwrap();
5394        worker.join().unwrap();
5395        assert!(
5396            !control_directory.exists(),
5397            "the control directory must be removed after the SSH master exits"
5398        );
5399        cleanup.finish();
5400    }
5401
5402    #[cfg(unix)]
5403    #[tokio::test]
5404    async fn ssh_control_directory_survives_reap_budget_expiry() {
5405        let root = tempfile::tempdir().unwrap();
5406        let control_directory = root.path().join("control");
5407        std::fs::create_dir(&control_directory).unwrap();
5408        let mut command = tokio::process::Command::new("sh");
5409        // exec prevents a descendant from retaining nextest's output pipes after the launcher dies
5410        command.args(["-c", "exec sleep 2"]).kill_on_drop(true);
5411        let launcher = command.spawn().unwrap();
5412        let reaper = SshMasterReaper {
5413            launcher: Some(launcher),
5414            control_directory: Some(control_directory.clone()),
5415        };
5416        let cleanup = RemoteCleanup::new().unwrap();
5417        let budget =
5418            CleanupBudget::for_job(cleanup.state.clone(), std::time::Duration::from_millis(20));
5419
5420        reaper.reap(budget);
5421
5422        assert!(
5423            control_directory.exists(),
5424            "an unconfirmed process exit must not remove its live control directory"
5425        );
5426        cleanup.finish();
5427    }
5428
5429    #[test]
5430    fn cleanup_scope_drains_nested_cleanup_in_its_parent_worker() {
5431        struct EnqueueSshCleanup {
5432            cleanup: RemoteCleanup,
5433            control_directory: std::path::PathBuf,
5434        }
5435
5436        impl Drop for EnqueueSshCleanup {
5437            fn drop(&mut self) {
5438                let reaper = SshMasterReaper {
5439                    launcher: None,
5440                    control_directory: Some(self.control_directory.clone()),
5441                };
5442                self.cleanup
5443                    .defer_bounded("rcp-test-nested-ssh-cleanup", move |budget| {
5444                        reaper.reap(budget);
5445                    });
5446            }
5447        }
5448
5449        let cleanup = RemoteCleanup::new().unwrap();
5450        let root = tempfile::tempdir().unwrap();
5451        let control_directory = root.path().join("control");
5452        std::fs::create_dir(&control_directory).unwrap();
5453
5454        cleanup.defer_drop(
5455            EnqueueSshCleanup {
5456                cleanup: cleanup.clone(),
5457                control_directory: control_directory.clone(),
5458            },
5459            "rcp-test-nested-cleanup",
5460        );
5461        cleanup.finish();
5462
5463        assert!(
5464            !control_directory.exists(),
5465            "the scope must finish nested SSH cleanup before its parent worker completes"
5466        );
5467    }
5468
5469    #[test]
5470    fn cleanup_scopes_do_not_drain_each_others_workers() {
5471        fn blocked_cleanup(
5472            cleanup: &RemoteCleanup,
5473        ) -> (
5474            std::sync::mpsc::Receiver<()>,
5475            std::sync::Arc<(Mutex<bool>, Condvar)>,
5476        ) {
5477            let (started_tx, started_rx) = std::sync::mpsc::channel();
5478            let release = std::sync::Arc::new((Mutex::new(false), Condvar::new()));
5479            let worker_release = release.clone();
5480            cleanup
5481                .submit_disposable("rcp-test-isolated-cleanup", move || {
5482                    started_tx.send(()).unwrap();
5483                    let (released, release_changed) = &*worker_release;
5484                    let mut released = released.lock().unwrap();
5485                    while !*released {
5486                        released = release_changed.wait(released).unwrap();
5487                    }
5488                })
5489                .unwrap();
5490            (started_rx, release)
5491        }
5492
5493        let cleanup_a = RemoteCleanup::new().unwrap();
5494        let cleanup_b = RemoteCleanup::new().unwrap();
5495        let (started_a, release_a) = blocked_cleanup(&cleanup_a);
5496        let (started_b, release_b) = blocked_cleanup(&cleanup_b);
5497        started_a
5498            .recv_timeout(std::time::Duration::from_secs(1))
5499            .unwrap();
5500        started_b
5501            .recv_timeout(std::time::Duration::from_secs(1))
5502            .unwrap();
5503
5504        let (finished_a_tx, finished_a_rx) = std::sync::mpsc::channel();
5505        let finish_a = std::thread::spawn(move || {
5506            cleanup_a.finish();
5507            finished_a_tx.send(()).unwrap();
5508        });
5509        let (released, release_changed) = &*release_a;
5510        *released.lock().unwrap() = true;
5511        release_changed.notify_all();
5512        finished_a_rx
5513            .recv_timeout(std::time::Duration::from_secs(1))
5514            .expect("finishing one scope must not wait for another scope's worker");
5515        finish_a.join().unwrap();
5516
5517        let (released, release_changed) = &*release_b;
5518        *released.lock().unwrap() = true;
5519        release_changed.notify_all();
5520        cleanup_b.finish();
5521    }
5522
5523    #[test]
5524    fn cleanup_finish_waits_for_work_queued_by_a_last_owner() {
5525        let cleanup = RemoteCleanup::new().unwrap();
5526        let last_owner = cleanup.clone();
5527        let (finish_started_tx, finish_started_rx) = std::sync::mpsc::channel();
5528        let (finished_tx, finished_rx) = std::sync::mpsc::channel();
5529        let finisher = std::thread::spawn(move || {
5530            finish_started_tx.send(()).unwrap();
5531            cleanup.finish();
5532            finished_tx.send(()).unwrap();
5533        });
5534        finish_started_rx.recv().unwrap();
5535        assert!(
5536            finished_rx
5537                .recv_timeout(std::time::Duration::from_millis(100))
5538                .is_err(),
5539            "cleanup scope finished while another owner was still live"
5540        );
5541
5542        let release = std::sync::Arc::new((Mutex::new(false), Condvar::new()));
5543        let release_guard = BlockingDropRelease(release.clone());
5544        let worker_release = release.clone();
5545        let (job_started_tx, job_started_rx) = std::sync::mpsc::channel();
5546        last_owner
5547            .submit_disposable("rcp-test-last-owner-cleanup", move || {
5548                job_started_tx.send(()).unwrap();
5549                let (released, release_changed) = &*worker_release;
5550                let mut released = released.lock().unwrap();
5551                while !*released {
5552                    released = release_changed.wait(released).unwrap();
5553                }
5554            })
5555            .unwrap();
5556        job_started_rx
5557            .recv_timeout(std::time::Duration::from_secs(1))
5558            .expect("last-owner cleanup must start");
5559        drop(last_owner);
5560        assert!(
5561            finished_rx
5562                .recv_timeout(std::time::Duration::from_millis(100))
5563                .is_err(),
5564            "cleanup scope finished before the last owner's worker"
5565        );
5566
5567        release_guard.release();
5568        finished_rx
5569            .recv_timeout(std::time::Duration::from_secs(1))
5570            .expect("cleanup scope must finish after the last owner's worker");
5571        finisher.join().unwrap();
5572    }
5573
5574    #[test]
5575    fn panicking_cleanup_worker_still_completes_its_scope() {
5576        let cleanup = RemoteCleanup::new().unwrap();
5577        let state = cleanup.state.clone();
5578        cleanup
5579            .submit_disposable("rcp-test-panicking-cleanup", || panic!("cleanup panic"))
5580            .unwrap();
5581
5582        cleanup.finish_with_grace(REMOTE_CLEANUP_GRACE);
5583
5584        let workers = state
5585            .workers
5586            .lock()
5587            .unwrap_or_else(std::sync::PoisonError::into_inner);
5588        assert_eq!(workers.pending, 0);
5589        assert!(workers.threads.is_empty());
5590    }
5591
5592    #[tokio::test]
5593    async fn ssh_socket_readiness_reuses_one_worker() {
5594        let cleanup = RemoteCleanup::new().unwrap();
5595        let thread_ids = std::sync::Arc::new(Mutex::new(Vec::new()));
5596        let observed_ids = thread_ids.clone();
5597        let mut probes = 0;
5598        wait_for_ssh_control_socket(&cleanup, move || {
5599            observed_ids
5600                .lock()
5601                .unwrap()
5602                .push(std::thread::current().id());
5603            probes += 1;
5604            Ok(probes == 4)
5605        })
5606        .await
5607        .unwrap();
5608        cleanup.finish();
5609
5610        let thread_ids = thread_ids.lock().unwrap();
5611        assert_eq!(thread_ids.len(), 4);
5612        assert!(
5613            thread_ids
5614                .iter()
5615                .all(|thread_id| *thread_id == thread_ids[0])
5616        );
5617    }
5618
5619    #[tokio::test]
5620    async fn cleanup_barrier_joins_an_abandoned_disposable_worker() {
5621        let cleanup = RemoteCleanup::new().unwrap();
5622        let release = std::sync::Arc::new((Mutex::new(false), Condvar::new()));
5623        let worker_release = release.clone();
5624        let (started_tx, started_rx) = tokio::sync::oneshot::channel();
5625        let operation = tokio::spawn(run_disposable_blocking(
5626            cleanup.clone(),
5627            "rcp-test-disposable-cleanup",
5628            move || {
5629                let _ = started_tx.send(());
5630                let (released, release_changed) = &*worker_release;
5631                let mut released = released.lock().unwrap();
5632                while !*released {
5633                    released = release_changed.wait(released).unwrap();
5634                }
5635                anyhow::Ok(())
5636            },
5637        ));
5638        tokio::time::timeout(std::time::Duration::from_secs(1), started_rx)
5639            .await
5640            .expect("disposable worker must start before the timeout")
5641            .expect("disposable worker must report that it started");
5642        operation.abort();
5643        let _ = operation.await;
5644
5645        let (barrier_started_tx, barrier_started_rx) = std::sync::mpsc::channel();
5646        let (finished_tx, finished_rx) = std::sync::mpsc::channel();
5647        let barrier = std::thread::spawn(move || {
5648            barrier_started_tx.send(()).unwrap();
5649            cleanup.finish();
5650            finished_tx.send(()).unwrap();
5651        });
5652        barrier_started_rx
5653            .recv_timeout(std::time::Duration::from_secs(1))
5654            .expect("cleanup barrier thread must start");
5655        assert!(
5656            finished_rx
5657                .recv_timeout(std::time::Duration::from_millis(100))
5658                .is_err(),
5659            "cleanup barrier returned while its abandoned filesystem worker was still running"
5660        );
5661        let (released, release_changed) = &*release;
5662        *released.lock().unwrap() = true;
5663        release_changed.notify_all();
5664        finished_rx
5665            .recv_timeout(std::time::Duration::from_secs(1))
5666            .expect("cleanup barrier must return after its disposable worker exits");
5667        barrier.join().unwrap();
5668    }
5669
5670    #[test]
5671    fn paired_preparation_returns_error_while_successful_peer_drop_is_blocked() {
5672        let watchdog = std::time::Duration::from_secs(5);
5673        let (drop_started, wait_for_drop) = std::sync::mpsc::channel();
5674        let (drop_finished, wait_for_drop_finish) = std::sync::mpsc::channel();
5675        let release = std::sync::Arc::new((Mutex::new(false), Condvar::new()));
5676        let release_guard = BlockingDropRelease(release.clone());
5677        let successful_peer = BlockingDrop {
5678            started: Some(drop_started),
5679            release,
5680            finished: Some(drop_finished),
5681        };
5682        let (success_ready, wait_for_success) = tokio::sync::oneshot::channel();
5683        let (result_ready, wait_for_result) = std::sync::mpsc::channel();
5684
5685        let coordinator = std::thread::spawn(move || {
5686            let cleanup = RemoteCleanup::new().unwrap();
5687            let runtime = tokio::runtime::Builder::new_current_thread()
5688                .enable_all()
5689                .build()
5690                .unwrap();
5691            let result = runtime.block_on(join_remote_preparations(
5692                &cleanup,
5693                move |_preparation| async move {
5694                    success_ready.send(()).unwrap();
5695                    anyhow::Ok(successful_peer)
5696                },
5697                move |_preparation| async move {
5698                    wait_for_success.await.unwrap();
5699                    Err::<(), _>(anyhow::anyhow!("destination preparation failed"))
5700                },
5701            ));
5702            let _ = result_ready.send(result);
5703            runtime.shutdown_timeout(watchdog);
5704            cleanup.finish();
5705        });
5706
5707        let drop_started_result = wait_for_drop.recv_timeout(watchdog);
5708        let result_before_release = wait_for_result.recv_timeout(watchdog);
5709        let returned_while_drop_blocked = result_before_release.is_ok();
5710        release_guard.release();
5711        let drop_finished_result = wait_for_drop_finish.recv_timeout(watchdog);
5712        let coordinator_result = match result_before_release {
5713            Ok(result) => Some(result),
5714            Err(_) => wait_for_result.recv_timeout(watchdog).ok(),
5715        };
5716        let coordinator_joined = coordinator.join();
5717
5718        assert!(
5719            drop_started_result.is_ok(),
5720            "successful peer disposal must start before the watchdog"
5721        );
5722        assert!(
5723            drop_finished_result.is_ok(),
5724            "successful peer disposal must finish after release"
5725        );
5726        assert!(
5727            coordinator_joined.is_ok(),
5728            "coordinator thread must finish after disposal is released"
5729        );
5730        assert!(
5731            returned_while_drop_blocked,
5732            "the intrinsic endpoint error must return without synchronously waiting for successful peer Drop"
5733        );
5734        let error = match coordinator_result.expect("coordinator must return a result") {
5735            Ok(_) => panic!("paired preparation unexpectedly succeeded"),
5736            Err(error) => error,
5737        };
5738        assert_eq!(error.to_string(), "destination preparation failed");
5739    }
5740
5741    #[tokio::test]
5742    async fn cancelled_transaction_reaps_a_cooperative_owner() {
5743        struct ActiveOwner {
5744            active: std::sync::Arc<std::sync::atomic::AtomicBool>,
5745            dropped: Option<tokio::sync::oneshot::Sender<()>>,
5746        }
5747
5748        impl Drop for ActiveOwner {
5749            fn drop(&mut self) {
5750                self.active
5751                    .store(false, std::sync::atomic::Ordering::SeqCst);
5752                if let Some(dropped) = self.dropped.take() {
5753                    let _ = dropped.send(());
5754                }
5755            }
5756        }
5757
5758        let cancellation = tokio_util::sync::CancellationToken::new();
5759        let cleanup = RemoteCleanup::new().unwrap();
5760        let preparation = PreparationContext::new(cancellation.clone(), cleanup.clone());
5761        let active = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
5762        let active_in_owner = active.clone();
5763        let (started, owner_started) = tokio::sync::oneshot::channel();
5764        let (dropped, owner_dropped) = tokio::sync::oneshot::channel();
5765        let owner = tokio::spawn(async move {
5766            active_in_owner.store(true, std::sync::atomic::Ordering::SeqCst);
5767            let _active_owner = ActiveOwner {
5768                active: active_in_owner,
5769                dropped: Some(dropped),
5770            };
5771            started.send(()).unwrap();
5772            std::future::pending::<anyhow::Result<()>>().await
5773        });
5774        owner_started.await.unwrap();
5775        cancellation.cancel();
5776
5777        let error = preparation
5778            .run_cancellation_owned_transaction(
5779                owner,
5780                std::time::Duration::from_millis(20),
5781                "test owned transaction",
5782            )
5783            .await
5784            .expect_err("a pending owned transaction must observe cancellation");
5785
5786        assert!(
5787            format!("{error:#}")
5788                .contains("rcpd preparation cancelled because peer preparation failed"),
5789            "peer cancellation missing from owned-transaction error: {error:#}"
5790        );
5791        tokio::time::timeout(std::time::Duration::from_secs(1), owner_dropped)
5792            .await
5793            .expect("the cleanup funnel must reap a cooperative cancelled owner")
5794            .unwrap();
5795        assert!(
5796            !active.load(std::sync::atomic::Ordering::SeqCst),
5797            "the cleanup funnel must drop the transaction owner"
5798        );
5799        drop(preparation);
5800        cleanup.finish();
5801    }
5802
5803    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5804    async fn cancelled_transaction_returns_after_grace_for_an_uncooperative_owner() {
5805        let cancellation = tokio_util::sync::CancellationToken::new();
5806        let cleanup = RemoteCleanup::new().unwrap();
5807        let preparation = PreparationContext::new(cancellation.clone(), cleanup.clone());
5808        let (started_tx, started_rx) = tokio::sync::oneshot::channel();
5809        let (release_tx, release_rx) = std::sync::mpsc::channel();
5810        let owner = tokio::spawn(async move {
5811            started_tx.send(()).unwrap();
5812            release_rx.recv().unwrap();
5813            anyhow::Ok(())
5814        });
5815        started_rx.await.unwrap();
5816        cancellation.cancel();
5817
5818        let result = tokio::time::timeout(
5819            std::time::Duration::from_secs(1),
5820            preparation.run_cancellation_owned_transaction(
5821                owner,
5822                std::time::Duration::from_millis(20),
5823                "test uncooperative transaction",
5824            ),
5825        )
5826        .await;
5827        release_tx.send(()).unwrap();
5828
5829        let error = result
5830            .expect("cancellation must not await an uncooperative owner after its grace")
5831            .expect_err("the cancelled transaction must fail");
5832        assert!(error.downcast_ref::<PeerPreparationCancelled>().is_some());
5833        drop(preparation);
5834        cleanup.finish();
5835    }
5836
5837    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5838    async fn bootstrap_deadline_reaps_a_raced_result_off_the_runtime_worker() {
5839        #[derive(Debug)]
5840        struct DropThreadReporter(Option<tokio::sync::oneshot::Sender<String>>);
5841
5842        impl Drop for DropThreadReporter {
5843            fn drop(&mut self) {
5844                if let Some(dropped) = self.0.take() {
5845                    let thread_name = std::thread::current()
5846                        .name()
5847                        .unwrap_or("unnamed")
5848                        .to_string();
5849                    let _ = dropped.send(thread_name);
5850                }
5851            }
5852        }
5853
5854        let cleanup = RemoteCleanup::new().unwrap();
5855        let preparation = PreparationContext::uncancelled(cleanup.clone());
5856        let (started_tx, started_rx) = tokio::sync::oneshot::channel();
5857        let (release_tx, release_rx) = std::sync::mpsc::channel();
5858        let (dropped_tx, dropped_rx) = tokio::sync::oneshot::channel();
5859        let owner = tokio::spawn(async move {
5860            started_tx.send(()).unwrap();
5861            release_rx.recv().unwrap();
5862            anyhow::Ok(DropThreadReporter(Some(dropped_tx)))
5863        });
5864        started_rx.await.unwrap();
5865
5866        let result = tokio::time::timeout(
5867            std::time::Duration::from_secs(1),
5868            preparation.run_abortable_with_deadline(
5869                owner,
5870                "test uncooperative bootstrap",
5871                BootstrapDeadline::new(std::time::Duration::from_millis(20)),
5872            ),
5873        )
5874        .await;
5875        release_tx.send(()).unwrap();
5876
5877        let error = result
5878            .expect("a bootstrap deadline must not await an uncooperative owner")
5879            .expect_err("the expired bootstrap operation must fail");
5880        assert!(
5881            format!("{error:#}").contains("test uncooperative bootstrap timed out"),
5882            "bootstrap timeout missing from error: {error:#}"
5883        );
5884        let drop_thread = tokio::time::timeout(std::time::Duration::from_secs(1), dropped_rx)
5885            .await
5886            .expect("the cleanup funnel must retain and dispose the raced owner result")
5887            .unwrap();
5888        assert_eq!(drop_thread, "rcp-owned-task-reap");
5889        drop(preparation);
5890        cleanup.finish();
5891    }
5892
5893    #[tokio::test]
5894    async fn owned_transaction_error_propagates_without_cancellation_grace() {
5895        let cleanup = RemoteCleanup::new().unwrap();
5896        let preparation = PreparationContext::uncancelled(cleanup.clone());
5897        let owner = tokio::spawn(async { Err::<(), _>(anyhow::anyhow!("owned failure")) });
5898        let started = std::time::Instant::now();
5899
5900        let error = preparation
5901            .run_cancellation_owned_transaction(
5902                owner,
5903                std::time::Duration::from_secs(1),
5904                "test failing transaction",
5905            )
5906            .await
5907            .expect_err("the owner failure must propagate");
5908
5909        assert!(
5910            started.elapsed() < std::time::Duration::from_millis(500),
5911            "a completed owner failure must not enter deadline grace"
5912        );
5913        assert!(
5914            format!("{error:#}").contains("owned failure"),
5915            "owner error missing from chain: {error:#}"
5916        );
5917        drop(preparation);
5918        cleanup.finish();
5919    }
5920
5921    #[tokio::test]
5922    async fn discover_rcpd_prefers_explicit_path() {
5923        let mut session = MockDiscoverySession::new();
5924        session.set_test_response("/opt/rcpd", true);
5925        let path = discover_rcpd_path_internal(&session, Some("/opt/rcpd"), None)
5926            .await
5927            .expect("should return explicit path");
5928        assert_eq!(path, "/opt/rcpd");
5929        assert_eq!(session.calls(), vec!["test:/opt/rcpd"]);
5930    }
5931
5932    #[tokio::test]
5933    async fn discover_rcpd_explicit_path_errors_without_fallbacks() {
5934        let session = MockDiscoverySession::new();
5935        let err = discover_rcpd_path_internal(&session, Some("/missing/rcpd"), None)
5936            .await
5937            .expect_err("should fail when explicit path is missing");
5938        assert!(
5939            err.to_string()
5940                .contains("rcpd binary not found or not executable"),
5941            "unexpected error: {err}"
5942        );
5943        assert_eq!(session.calls(), vec!["test:/missing/rcpd"]);
5944    }
5945
5946    #[tokio::test]
5947    async fn discover_rcpd_uses_same_dir_first() {
5948        let mut session = MockDiscoverySession::new();
5949        session.set_test_response("/custom/bin/rcpd", true);
5950        let path =
5951            discover_rcpd_path_internal(&session, None, Some(PathBuf::from("/custom/bin/rcp")))
5952                .await
5953                .expect("should find in same directory");
5954        assert_eq!(path, "/custom/bin/rcpd");
5955        assert_eq!(session.calls(), vec!["test:/custom/bin/rcpd"]);
5956    }
5957
5958    #[tokio::test]
5959    async fn discover_rcpd_falls_back_to_path_after_same_dir() {
5960        let mut session = MockDiscoverySession::new().with_path(Some("/usr/bin/rcpd"));
5961        session.set_test_response("/custom/bin/rcpd", false);
5962        let path =
5963            discover_rcpd_path_internal(&session, None, Some(PathBuf::from("/custom/bin/rcp")))
5964                .await
5965                .expect("should find in PATH after same dir miss");
5966        assert_eq!(path, "/usr/bin/rcpd");
5967        assert_eq!(session.calls(), vec!["test:/custom/bin/rcpd", "path:rcpd"]);
5968    }
5969
5970    #[cfg(unix)]
5971    #[test]
5972    fn remote_path_discovery_script_does_not_require_external_which() {
5973        use std::os::unix::fs::PermissionsExt;
5974
5975        let directory = tempfile::tempdir().unwrap();
5976        let candidate = directory.path().join("rcpd");
5977        std::fs::write(&candidate, "#!/bin/sh\nexit 0\n").unwrap();
5978        std::fs::set_permissions(&candidate, std::fs::Permissions::from_mode(0o755)).unwrap();
5979        let output = std::process::Command::new("/bin/sh")
5980            .args([
5981                "-c",
5982                RCPD_PATH_DISCOVERY_SCRIPT,
5983                "rcp-path-discovery",
5984                "rcpd",
5985            ])
5986            .env("PATH", directory.path())
5987            .output()
5988            .unwrap();
5989
5990        assert!(output.status.success());
5991        assert_eq!(
5992            String::from_utf8(output.stdout).unwrap().trim(),
5993            candidate.to_str().unwrap()
5994        );
5995    }
5996
5997    #[tokio::test]
5998    async fn discover_rcpd_uses_cache_last() {
5999        let mut session = MockDiscoverySession::new()
6000            .with_home(Some("/home/rcp"))
6001            .with_path(None);
6002        session.set_test_response("/custom/bin/rcpd", false);
6003        let local_version = common::version::ProtocolVersion::current();
6004        let cache_path = format!(
6005            "/home/rcp/.cache/rcp/bin/rcpd-{}",
6006            local_version.cache_tag()
6007        );
6008        session.set_test_response(&cache_path, true);
6009        let path =
6010            discover_rcpd_path_internal(&session, None, Some(PathBuf::from("/custom/bin/rcp")))
6011                .await
6012                .expect("should fall back to cache");
6013        assert_eq!(path, cache_path);
6014        assert_eq!(
6015            session.calls(),
6016            vec![
6017                "test:/custom/bin/rcpd".to_string(),
6018                "path:rcpd".to_string(),
6019                "home".to_string(),
6020                format!("test:{cache_path}")
6021            ]
6022        );
6023    }
6024
6025    #[tokio::test]
6026    async fn discover_rcpd_reports_home_missing_in_error() {
6027        let mut session = MockDiscoverySession::new().with_path(None);
6028        session.set_test_response("/custom/bin/rcpd", false);
6029        let err =
6030            discover_rcpd_path_internal(&session, None, Some(PathBuf::from("/custom/bin/rcp")))
6031                .await
6032                .expect_err("should fail when nothing is found");
6033        let msg = err.to_string();
6034        assert!(
6035            msg.contains("Deployed cache: (skipped, HOME not set)"),
6036            "expected searched list to mention skipped cache, got: {msg}"
6037        );
6038        assert_eq!(
6039            session.calls(),
6040            vec!["test:/custom/bin/rcpd", "path:rcpd", "home"]
6041        );
6042    }
6043
6044    #[tokio::test]
6045    async fn discover_rcpd_propagates_home_lookup_failure() {
6046        let mut session = MockDiscoverySession::new()
6047            .with_path(None)
6048            .with_home_error("sentinel HOME lookup timeout");
6049        session.set_test_response("/custom/bin/rcpd", false);
6050
6051        let error =
6052            discover_rcpd_path_internal(&session, None, Some(PathBuf::from("/custom/bin/rcp")))
6053                .await
6054                .expect_err("a failed HOME probe must not look like an absent HOME");
6055
6056        assert!(
6057            format!("{error:#}").contains("sentinel HOME lookup timeout"),
6058            "HOME lookup failure missing from discovery error: {error:#}"
6059        );
6060        assert_eq!(
6061            session.calls(),
6062            vec!["test:/custom/bin/rcpd", "path:rcpd", "home"]
6063        );
6064    }
6065
6066    /// verify that tokio_unstable is enabled
6067    ///
6068    /// this test ensures that the tokio_unstable cfg flag is properly set, which is required
6069    /// for console-subscriber (used in common/src/lib.rs) to function correctly.
6070    ///
6071    /// the compile_error! at the top of this file prevents compilation without tokio_unstable,
6072    /// but this test provides additional verification that the cfg flag is properly configured
6073    /// and catches cases where someone might remove the compile_error! macro.
6074    #[test]
6075    fn test_tokio_unstable_enabled() {
6076        // compile-time check: this will cause a test failure if tokio_unstable is not set
6077        #[cfg(not(tokio_unstable))]
6078        {
6079            panic!(
6080                "tokio_unstable cfg flag is not enabled! \
6081                 This is required for console-subscriber support. \
6082                 Check .cargo/config.toml"
6083            );
6084        }
6085
6086        // runtime verification: if we get here, tokio_unstable is enabled
6087        #[cfg(tokio_unstable)]
6088        {
6089            // test passes - verify we can access tokio unstable features
6090            // tokio::task::JoinSet is an example of a type that uses unstable features
6091            let _join_set: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
6092        }
6093    }
6094
6095    fn iface(name: &str, addr: [u8; 4]) -> InterfaceIpv4 {
6096        InterfaceIpv4 {
6097            name: name.to_string(),
6098            addr: std::net::Ipv4Addr::new(addr[0], addr[1], addr[2], addr[3]),
6099        }
6100    }
6101
6102    #[test]
6103    fn choose_best_ipv4_prefers_physical_interfaces() {
6104        let interfaces = vec![
6105            iface("docker0", [172, 17, 0, 1]),
6106            iface("enp3s0", [192, 168, 1, 44]),
6107            iface("tailscale0", [100, 115, 92, 5]),
6108        ];
6109        assert_eq!(
6110            choose_best_ipv4(&interfaces),
6111            Some(std::net::Ipv4Addr::new(192, 168, 1, 44))
6112        );
6113    }
6114
6115    #[test]
6116    fn choose_best_ipv4_deprioritizes_link_local() {
6117        let interfaces = vec![
6118            iface("enp0s8", [169, 254, 10, 2]),
6119            iface("wlan0", [10, 0, 0, 23]),
6120        ];
6121        assert_eq!(
6122            choose_best_ipv4(&interfaces),
6123            Some(std::net::Ipv4Addr::new(10, 0, 0, 23))
6124        );
6125    }
6126
6127    #[test]
6128    fn choose_best_ipv4_falls_back_to_loopback() {
6129        let interfaces = vec![iface("lo", [127, 0, 0, 1]), iface("docker0", [0, 0, 0, 0])];
6130        assert_eq!(
6131            choose_best_ipv4(&interfaces),
6132            Some(std::net::Ipv4Addr::new(127, 0, 0, 1))
6133        );
6134    }
6135
6136    #[test]
6137    fn test_get_local_ip_with_explicit_ipv4() {
6138        // test that providing a valid IPv4 address works
6139        let result = get_local_ip(Some("192.168.1.100"));
6140        assert!(result.is_ok(), "should accept valid IPv4 address");
6141        let ip = result.unwrap();
6142        assert_eq!(
6143            ip,
6144            std::net::IpAddr::V4(std::net::Ipv4Addr::new(192, 168, 1, 100))
6145        );
6146    }
6147
6148    #[test]
6149    fn test_get_local_ip_with_explicit_loopback() {
6150        // test that providing loopback address works
6151        let result = get_local_ip(Some("127.0.0.1"));
6152        assert!(result.is_ok(), "should accept loopback address");
6153        let ip = result.unwrap();
6154        assert_eq!(
6155            ip,
6156            std::net::IpAddr::V4(std::net::Ipv4Addr::new(127, 0, 0, 1))
6157        );
6158    }
6159
6160    #[test]
6161    fn test_get_local_ip_rejects_ipv6() {
6162        // test that providing an IPv6 address fails with a good error message
6163        let result = get_local_ip(Some("::1"));
6164        assert!(result.is_err(), "should reject IPv6 address");
6165        let err = result.unwrap_err();
6166        let err_msg = format!("{err:#}");
6167        assert!(
6168            err_msg.contains("IPv6 address not supported"),
6169            "error should mention IPv6 not supported, got: {err_msg}"
6170        );
6171        assert!(
6172            err_msg.contains("0.0.0.0"),
6173            "error should mention IPv4-only binding, got: {err_msg}"
6174        );
6175    }
6176
6177    #[test]
6178    fn test_get_local_ip_rejects_ipv6_full() {
6179        // test that providing a full IPv6 address fails
6180        let result = get_local_ip(Some("2001:db8::1"));
6181        assert!(result.is_err(), "should reject IPv6 address");
6182        let err = result.unwrap_err();
6183        let err_msg = format!("{err:#}");
6184        assert!(
6185            err_msg.contains("IPv6 address not supported"),
6186            "error should mention IPv6 not supported, got: {err_msg}"
6187        );
6188    }
6189
6190    #[test]
6191    fn test_get_local_ip_rejects_invalid_ip() {
6192        // test that providing an invalid IP format fails with a good error message
6193        let result = get_local_ip(Some("not-an-ip"));
6194        assert!(result.is_err(), "should reject invalid IP format");
6195        let err = result.unwrap_err();
6196        let err_msg = format!("{err:#}");
6197        assert!(
6198            err_msg.contains("invalid IP address"),
6199            "error should mention invalid IP address, got: {err_msg}"
6200        );
6201    }
6202
6203    #[test]
6204    fn test_get_local_ip_rejects_invalid_ipv4() {
6205        // test that providing an invalid IPv4 format fails
6206        let result = get_local_ip(Some("999.999.999.999"));
6207        assert!(result.is_err(), "should reject invalid IPv4 address");
6208        let err = result.unwrap_err();
6209        let err_msg = format!("{err:#}");
6210        assert!(
6211            err_msg.contains("invalid IP address"),
6212            "error should mention invalid IP address, got: {err_msg}"
6213        );
6214    }
6215
6216    /// A real connected pair on loopback. The accepted half is returned so the caller keeps it
6217    /// alive — dropping it would reset the connection under the socket being inspected.
6218    async fn connected_pair() -> (tokio::net::TcpStream, tokio::net::TcpStream) {
6219        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
6220        let addr = listener.local_addr().unwrap();
6221        let (client, accepted) =
6222            tokio::join!(tokio::net::TcpStream::connect(addr), listener.accept());
6223        (client.unwrap(), accepted.unwrap().0)
6224    }
6225
6226    // the options are read back with getsockopt rather than trusted: a wrong constant, a value the
6227    // kernel rejects, or a call that a socket2 feature gate silently compiled out would otherwise
6228    // leave the connection with no liveness detection at all and nothing to show for it.
6229    #[tokio::test]
6230    async fn configure_tcp_socket_applies_every_option() {
6231        let (stream, _accepted) = connected_pair().await;
6232        configure_tcp_socket(
6233            &stream,
6234            NetworkProfile::Datacenter,
6235            120,
6236            ConnectionKind::Control,
6237        );
6238        let sock = socket2::SockRef::from(&stream);
6239        assert!(stream.nodelay().unwrap(), "TCP_NODELAY must be set");
6240        assert!(sock.keepalive().unwrap(), "SO_KEEPALIVE must be on");
6241        assert_eq!(
6242            sock.tcp_keepalive_time().unwrap(),
6243            std::time::Duration::from_secs(60),
6244            "TCP_KEEPIDLE must be half the budget"
6245        );
6246        assert_eq!(
6247            sock.tcp_keepalive_interval().unwrap(),
6248            std::time::Duration::from_secs(10),
6249            "TCP_KEEPINTVL must be a twelfth of the budget"
6250        );
6251        assert_eq!(
6252            sock.tcp_keepalive_retries().unwrap(),
6253            TCP_KEEPALIVE_RETRIES,
6254            "TCP_KEEPCNT must be the configured retry count"
6255        );
6256        #[cfg(target_os = "linux")]
6257        assert_eq!(
6258            sock.tcp_user_timeout().unwrap(),
6259            Some(std::time::Duration::from_secs(120)),
6260            "TCP_USER_TIMEOUT must be the budget itself"
6261        );
6262    }
6263
6264    #[tokio::test]
6265    async fn configure_tcp_socket_derives_keepalive_from_the_budget() {
6266        let (stream, _accepted) = connected_pair().await;
6267        configure_tcp_socket(
6268            &stream,
6269            NetworkProfile::Internet,
6270            60,
6271            ConnectionKind::Control,
6272        );
6273        let sock = socket2::SockRef::from(&stream);
6274        assert_eq!(
6275            sock.tcp_keepalive_time().unwrap(),
6276            std::time::Duration::from_secs(30)
6277        );
6278        assert_eq!(
6279            sock.tcp_keepalive_interval().unwrap(),
6280            std::time::Duration::from_secs(5)
6281        );
6282        #[cfg(target_os = "linux")]
6283        assert_eq!(
6284            sock.tcp_user_timeout().unwrap(),
6285            Some(std::time::Duration::from_secs(60))
6286        );
6287    }
6288
6289    // a budget under 12s would derive a zero interval, which the kernel rejects outright — the
6290    // whole keepalive call would then fail and leave the connection unprotected
6291    #[tokio::test]
6292    async fn configure_tcp_socket_clamps_sub_second_derivations() {
6293        let (stream, _accepted) = connected_pair().await;
6294        configure_tcp_socket(
6295            &stream,
6296            NetworkProfile::Datacenter,
6297            1,
6298            ConnectionKind::Control,
6299        );
6300        let sock = socket2::SockRef::from(&stream);
6301        assert!(sock.keepalive().unwrap(), "SO_KEEPALIVE must still be on");
6302        assert_eq!(
6303            sock.tcp_keepalive_time().unwrap(),
6304            std::time::Duration::from_secs(1)
6305        );
6306        assert_eq!(
6307            sock.tcp_keepalive_interval().unwrap(),
6308            std::time::Duration::from_secs(1)
6309        );
6310    }
6311
6312    #[tokio::test]
6313    async fn configure_tcp_socket_leaves_keepalive_off_when_disabled() {
6314        let (stream, _accepted) = connected_pair().await;
6315        configure_tcp_socket(
6316            &stream,
6317            NetworkProfile::Datacenter,
6318            0,
6319            ConnectionKind::Control,
6320        );
6321        let sock = socket2::SockRef::from(&stream);
6322        assert!(
6323            !sock.keepalive().unwrap(),
6324            "SO_KEEPALIVE must stay off when the budget is 0"
6325        );
6326        #[cfg(target_os = "linux")]
6327        assert_eq!(
6328            sock.tcp_user_timeout().unwrap(),
6329            None,
6330            "TCP_USER_TIMEOUT must stay at the system default when the budget is 0"
6331        );
6332        assert!(
6333            stream.nodelay().unwrap(),
6334            "no-delay is not part of liveness detection and must still be set"
6335        );
6336    }
6337
6338    // a data connection must NOT get TCP_USER_TIMEOUT: the destination stops reading for the whole
6339    // of its per-file iops reservation, and the user timeout would abort that live-but-silent peer
6340    // — failing a copy that used to merely run slow. Keepalive stays on, so an IDLE data connection
6341    // to a vanished host is still caught.
6342    #[tokio::test]
6343    async fn configure_tcp_socket_omits_user_timeout_on_data_connections() {
6344        let (stream, _accepted) = connected_pair().await;
6345        configure_tcp_socket(
6346            &stream,
6347            NetworkProfile::Datacenter,
6348            120,
6349            ConnectionKind::Data,
6350        );
6351        let sock = socket2::SockRef::from(&stream);
6352        #[cfg(target_os = "linux")]
6353        assert_eq!(
6354            sock.tcp_user_timeout().unwrap(),
6355            None,
6356            "a data connection must be left at the system retransmission limit"
6357        );
6358        assert!(
6359            sock.keepalive().unwrap(),
6360            "keepalive still covers an idle data connection"
6361        );
6362        assert_eq!(
6363            sock.tcp_keepalive_time().unwrap(),
6364            std::time::Duration::from_secs(60)
6365        );
6366        assert_eq!(
6367            sock.tcp_keepalive_retries().unwrap(),
6368            TCP_KEEPALIVE_RETRIES,
6369            "with no user timeout to override it, TCP_KEEPCNT is what ends a dead data connection"
6370        );
6371        assert!(stream.nodelay().unwrap());
6372    }
6373
6374    // absolute sizes are not assertable — the kernel doubles the request and clamps it to
6375    // net.core.{r,w}mem_max — but a THIRD, untouched socket from the same host pins the baseline,
6376    // so the comparison fails if the sizing calls are removed. Comparing the two profiles to each
6377    // other cannot: they collapse to equality whenever both clamp to the same maximum.
6378    #[tokio::test]
6379    async fn configure_tcp_socket_sizes_buffers_by_profile() {
6380        let (datacenter, _a) = connected_pair().await;
6381        let (internet, _b) = connected_pair().await;
6382        let (untouched, _c) = connected_pair().await;
6383        configure_tcp_socket(
6384            &datacenter,
6385            NetworkProfile::Datacenter,
6386            0,
6387            ConnectionKind::Data,
6388        );
6389        configure_tcp_socket(&internet, NetworkProfile::Internet, 0, ConnectionKind::Data);
6390        let (dc, net, base) = (
6391            socket2::SockRef::from(&datacenter),
6392            socket2::SockRef::from(&internet),
6393            socket2::SockRef::from(&untouched),
6394        );
6395        // what is (and is not) assertable across kernels: an explicit SO_SNDBUF/SO_RCVBUF is
6396        // clamped to `wmem_max`/`rmem_max`, and on hosts whose sysctls leave those at the default
6397        // (~208 KiB) while TCP auto-tuning grows untouched sockets into megabytes — GitHub's
6398        // runners measure 425984 configured vs 2626560 untouched — the configured size sits BELOW
6399        // the untouched default no matter what this code does. So "configured > default" is a
6400        // property of the host, not of configure_tcp_socket, and is deliberately NOT asserted.
6401        // what the code does guarantee: both profiles issue a set (asserted as ordering below —
6402        // datacenter requests 8x Internet, so wherever the clamp permits any distinction the
6403        // ordering holds, and equality is exactly the fully-clamped case), and the sizes are sane.
6404        for (name, sock) in [("datacenter", &dc), ("internet", &net)] {
6405            assert!(
6406                sock.send_buffer_size().unwrap() > 0 && sock.recv_buffer_size().unwrap() > 0,
6407                "{name} buffer sizes must be readable and non-zero"
6408            );
6409        }
6410        // the untouched socket is read (not asserted against) so a debugging run shows all three
6411        let _ = (base.send_buffer_size(), base.recv_buffer_size());
6412        assert!(dc.send_buffer_size().unwrap() >= net.send_buffer_size().unwrap());
6413        assert!(dc.recv_buffer_size().unwrap() >= net.recv_buffer_size().unwrap());
6414    }
6415}