1use std::{
2 collections::BTreeMap,
3 env,
4 error::Error,
5 ffi::OsString,
6 fmt, fs, io,
7 net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
8 path::{Path, PathBuf},
9 process,
10 time::Duration,
11};
12
13use fs4::{FileExt, TryLockError};
14use subc_protocol::PROTOCOL_VERSION;
15pub use subc_transport::user_connection_token;
16use subc_transport::{
17 authenticate_client, connection_file, generate_daemon_id, generate_key, write_atomic,
18 AuthError, ConnectionFileError, ConnectionInfo, Endpoint, SCHEMA_VERSION,
19};
20use tokio::{
21 net::{TcpListener, TcpStream},
22 task::{JoinError, JoinHandle},
23 time::{sleep, timeout},
24};
25use tracing::{error, info, warn};
26
27use crate::{
28 daemon_config::{self, ConfiguredModule, DaemonConfigError},
29 server::{serve_listeners, ServerAuth, ServerError},
30 supervise::HealthConfig,
31 ConnectedClients, ControlHandler, DaemonSelfWatchdog, DaemonSelfWatchdogConfig,
32 ForwardingTable, Registry, RestartPolicy, Router, Supervisor, SupervisorHandle,
33 SupervisorProcessLiveness,
34};
35use std::sync::Arc;
36
37pub const DEFAULT_SUBC_PORT: u16 = 8757;
38pub const SUBC_PORT_ENV: &str = "SUBC_PORT";
39use subc_transport::CONNECTION_FILE_NAME;
40const DAEMON_VERSION: &str = env!("CARGO_PKG_VERSION");
41const CONNECT_TIMEOUT: Duration = Duration::from_secs(2);
42const PROBE_AUTH_DEADLINE: Duration = Duration::from_secs(2);
43const START_LOCK_RETRIES: usize = 40;
44const START_LOCK_RETRY_DELAY: Duration = Duration::from_millis(25);
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum ConnectionFileSource {
48 XdgRuntimeDir,
49 TempDirFallback,
50 Explicit,
51}
52
53impl ConnectionFileSource {
54 fn reason(self) -> &'static str {
55 match self {
56 Self::XdgRuntimeDir => "XDG_RUNTIME_DIR set and non-empty",
57 Self::TempDirFallback => "XDG_RUNTIME_DIR unset or empty",
58 Self::Explicit => "configured path",
59 }
60 }
61}
62
63impl fmt::Display for ConnectionFileSource {
64 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
65 formatter.write_str(match self {
66 Self::XdgRuntimeDir => "xdg_runtime_dir",
67 Self::TempDirFallback => "temp_dir_fallback",
68 Self::Explicit => "explicit",
69 })
70 }
71}
72
73#[derive(Debug, Clone, Default)]
77struct AdmissionFactsConfig {
78 carrier_module_id: Option<String>,
79 targets: Option<Vec<String>>,
80}
81
82#[derive(Debug, Clone, Default, PartialEq, Eq)]
88pub enum CgroupPlacementConfig {
89 #[default]
90 Disabled,
91 Current,
92 Root(PathBuf),
93}
94
95#[derive(Debug, Clone)]
96pub struct BootstrapConfig {
97 pub connection_file_path: PathBuf,
98 pub port: u16,
99 pub daemon_ver: String,
100 configured_modules: Vec<ConfiguredModule>,
101 storage_config: Option<daemon_config::StorageConfig>,
102 admission_facts: AdmissionFactsConfig,
103 daemon_config_path: Option<PathBuf>,
104 configured_port: Option<u16>,
105 route_bind_relay_default_ms: Option<u64>,
109 reserved_capabilities: BTreeMap<String, String>,
110 watchdog_config: DaemonSelfWatchdogConfig,
111 connection_file_source: ConnectionFileSource,
112 cgroup_placement: CgroupPlacementConfig,
115 capture_logs_dir: Option<PathBuf>,
119 terminal_journal_path: Option<PathBuf>,
127 machine_id_path: Option<PathBuf>,
133}
134
135impl BootstrapConfig {
136 pub fn new(connection_file_path: impl Into<PathBuf>, port: u16) -> Self {
137 Self {
138 connection_file_path: connection_file_path.into(),
139 port,
140 daemon_ver: DAEMON_VERSION.to_owned(),
141 configured_modules: Vec::new(),
142 storage_config: None,
143 admission_facts: AdmissionFactsConfig::default(),
144 daemon_config_path: None,
145 configured_port: None,
146 route_bind_relay_default_ms: None,
147 reserved_capabilities: BTreeMap::new(),
148 watchdog_config: DaemonSelfWatchdogConfig::default(),
149 connection_file_source: ConnectionFileSource::Explicit,
150 cgroup_placement: CgroupPlacementConfig::default(),
151 capture_logs_dir: None,
152 terminal_journal_path: None,
153 machine_id_path: None,
154 }
155 }
156
157 pub fn with_machine_id_path(mut self, path: impl Into<PathBuf>) -> Self {
161 self.machine_id_path = Some(path.into());
162 self
163 }
164
165 pub fn with_cgroup_placement(mut self, placement: CgroupPlacementConfig) -> Self {
167 self.cgroup_placement = placement;
168 self
169 }
170
171 pub fn with_capture_logs_dir(mut self, dir: impl Into<PathBuf>) -> Self {
175 self.capture_logs_dir = Some(dir.into());
176 self
177 }
178
179 pub fn with_terminal_journal_path(mut self, path: impl Into<PathBuf>) -> Self {
182 self.terminal_journal_path = Some(path.into());
183 self
184 }
185
186 pub fn from_env() -> Result<Self, BootstrapError> {
187 Self::from_env_with_daemon_config_path(daemon_config::default_config_path())
188 }
189
190 pub fn from_env_for_daemon_binary() -> Result<Self, BootstrapError> {
199 let run_dir = daemon_config::daemon_run_dir().map_err(BootstrapError::RunDir)?;
200 let machine_id_path =
201 crate::machine_id::default_machine_id_path().map_err(BootstrapError::MachineId)?;
202 Ok(Self::from_env()?
203 .with_capture_logs_dir(run_dir.join("logs"))
204 .with_terminal_journal_path(run_dir.join("terminals.jsonl"))
205 .with_machine_id_path(machine_id_path))
206 }
207
208 pub fn from_env_with_daemon_config_path(
209 daemon_config_path: impl AsRef<Path>,
210 ) -> Result<Self, BootstrapError> {
211 let daemon_config_path = daemon_config_path.as_ref().to_path_buf();
212 let daemon_config =
213 daemon_config::load(&daemon_config_path).map_err(BootstrapError::DaemonConfig)?;
214 let config_port = daemon_config.as_ref().and_then(|config| config.port);
215 let storage_config = daemon_config
216 .as_ref()
217 .and_then(|config| config.storage.clone());
218 let admission_facts_carrier_module_id = daemon_config
219 .as_ref()
220 .and_then(|config| config.admission_facts_carrier_module_id.clone());
221 let admission_facts_targets = daemon_config
222 .as_ref()
223 .and_then(|config| config.admission_facts_targets.clone());
224 let route_bind_relay_default_ms = daemon_config
225 .as_ref()
226 .and_then(|config| config.route_bind_relay_timeout_ms);
227 let reserved_capabilities = daemon_config
228 .as_ref()
229 .map(|config| config.reserved_capabilities.clone())
230 .unwrap_or_default();
231 let configured_modules = daemon_config
232 .map(|config| config.modules)
233 .unwrap_or_default();
234
235 let port = match env::var(SUBC_PORT_ENV) {
236 Ok(raw) if !raw.trim().is_empty() => {
237 let port = raw
238 .parse::<u16>()
239 .map_err(|source| BootstrapError::InvalidPort { raw, source })?;
240 if let Some(config_port) = config_port {
241 info!(
242 env = SUBC_PORT_ENV,
243 env_port = port,
244 config_port,
245 "SUBC_PORT overrides daemon config port"
246 );
247 }
248 port
249 }
250 Ok(_) | Err(_) => config_port.unwrap_or(DEFAULT_SUBC_PORT),
251 };
252
253 let (connection_file_path, connection_file_source) =
254 connection_file_path_with_source(non_empty_os_var("XDG_RUNTIME_DIR"));
255 Ok(Self::new(connection_file_path, port)
256 .with_configured_modules(configured_modules)
257 .with_storage_config(storage_config)
258 .with_admission_facts_config(admission_facts_carrier_module_id, admission_facts_targets)
259 .with_route_bind_relay_default_ms(route_bind_relay_default_ms)
260 .with_reserved_capabilities(reserved_capabilities)
261 .with_daemon_config_source(daemon_config_path, config_port)
262 .with_connection_file_source(connection_file_source))
263 }
264
265 pub fn with_daemon_config_path(
266 self,
267 daemon_config_path: impl AsRef<Path>,
268 ) -> Result<Self, BootstrapError> {
269 let daemon_config_path = daemon_config_path.as_ref().to_path_buf();
270 let daemon_config =
271 daemon_config::load(&daemon_config_path).map_err(BootstrapError::DaemonConfig)?;
272 let configured_port = daemon_config.as_ref().and_then(|config| config.port);
273 let storage_config = daemon_config
274 .as_ref()
275 .and_then(|config| config.storage.clone());
276 let admission_facts_carrier_module_id = daemon_config
277 .as_ref()
278 .and_then(|config| config.admission_facts_carrier_module_id.clone());
279 let admission_facts_targets = daemon_config
280 .as_ref()
281 .and_then(|config| config.admission_facts_targets.clone());
282 let route_bind_relay_default_ms = daemon_config
283 .as_ref()
284 .and_then(|config| config.route_bind_relay_timeout_ms);
285 let reserved_capabilities = daemon_config
286 .as_ref()
287 .map(|config| config.reserved_capabilities.clone())
288 .unwrap_or_default();
289 let configured_modules = daemon_config
290 .map(|config| config.modules)
291 .unwrap_or_default();
292 Ok(self
293 .with_configured_modules(configured_modules)
294 .with_storage_config(storage_config)
295 .with_admission_facts_config(admission_facts_carrier_module_id, admission_facts_targets)
296 .with_route_bind_relay_default_ms(route_bind_relay_default_ms)
297 .with_reserved_capabilities(reserved_capabilities)
298 .with_daemon_config_source(daemon_config_path, configured_port))
299 }
300
301 pub fn with_configured_modules(
302 mut self,
303 modules: impl IntoIterator<Item = ConfiguredModule>,
304 ) -> Self {
305 self.configured_modules = modules.into_iter().collect();
306 self.configured_modules
307 .sort_by(|left, right| left.module_id.cmp(&right.module_id));
308 self
309 }
310
311 pub fn with_storage_config(
312 mut self,
313 storage_config: Option<daemon_config::StorageConfig>,
314 ) -> Self {
315 self.storage_config = storage_config;
316 self
317 }
318
319 pub fn with_admission_facts_config(
320 mut self,
321 carrier_module_id: Option<String>,
322 targets: Option<Vec<String>>,
323 ) -> Self {
324 self.admission_facts = AdmissionFactsConfig {
325 carrier_module_id,
326 targets,
327 };
328 self
329 }
330
331 pub fn with_route_bind_relay_default_ms(mut self, ms: Option<u64>) -> Self {
336 self.route_bind_relay_default_ms = ms;
337 self
338 }
339
340 pub fn with_reserved_capabilities(
341 mut self,
342 reserved_capabilities: BTreeMap<String, String>,
343 ) -> Self {
344 self.reserved_capabilities = reserved_capabilities;
345 self
346 }
347
348 fn with_daemon_config_source(
349 mut self,
350 daemon_config_path: PathBuf,
351 configured_port: Option<u16>,
352 ) -> Self {
353 self.daemon_config_path = Some(daemon_config_path);
354 self.configured_port = configured_port;
355 self
356 }
357
358 fn with_connection_file_source(mut self, source: ConnectionFileSource) -> Self {
359 self.connection_file_source = source;
360 self
361 }
362
363 pub fn with_watchdog_config(mut self, watchdog_config: DaemonSelfWatchdogConfig) -> Self {
364 self.watchdog_config = watchdog_config;
365 self
366 }
367}
368
369#[derive(Debug)]
371pub enum Outcome {
372 AlreadyRunning,
374 Bound(BoundDaemon),
377}
378
379#[derive(Debug)]
380pub struct BoundDaemon {
381 pub listeners: Vec<TcpListener>,
382 pub connection_info: ConnectionInfo,
383 pub connection_file_path: PathBuf,
384 pub connection_file_source: ConnectionFileSource,
385 pub machine_id: Option<crate::machine_id::MachineId>,
388}
389
390pub fn connection_file_path() -> PathBuf {
397 connection_file_path_with_source(non_empty_os_var("XDG_RUNTIME_DIR")).0
398}
399
400fn connection_file_path_with_source(
401 runtime_dir: Option<OsString>,
402) -> (PathBuf, ConnectionFileSource) {
403 if let Some(runtime_dir) = runtime_dir.filter(|value| !value.is_empty()) {
404 return (
405 PathBuf::from(runtime_dir).join(CONNECTION_FILE_NAME),
406 ConnectionFileSource::XdgRuntimeDir,
407 );
408 }
409
410 (
411 env::temp_dir().join(format!("subc-{}.connection.json", user_connection_token())),
412 ConnectionFileSource::TempDirFallback,
413 )
414}
415
416pub async fn run() -> Result<(), BootstrapError> {
422 run_with_config(
425 BootstrapConfig::from_env_for_daemon_binary()?
426 .with_cgroup_placement(CgroupPlacementConfig::Current),
427 )
428 .await
429}
430
431pub async fn run_with_config(config: BootstrapConfig) -> Result<(), BootstrapError> {
455 let configured_modules = config.configured_modules.clone();
456 let storage_config = config.storage_config.clone();
457 let admission_facts = config.admission_facts.clone();
458 let daemon_config_path = config.daemon_config_path.clone();
459 let configured_port = config.configured_port;
460 let route_bind_relay_default_ms = config.route_bind_relay_default_ms;
461 let reserved_capabilities = config.reserved_capabilities.clone();
462 let watchdog_config = config.watchdog_config.clone();
463 let cgroup_placement_config = config.cgroup_placement.clone();
464 let capture_logs_dir = config.capture_logs_dir.clone();
465 let terminal_journal_path = config.terminal_journal_path.clone();
466 match ensure_singleton_with_config(config).await? {
467 Outcome::AlreadyRunning => {
468 info!("subc daemon already running");
469 Ok(())
470 }
471 Outcome::Bound(bound) => {
472 #[cfg(target_os = "linux")]
473 let cgroup_placement = prepare_cgroup_placement(&cgroup_placement_config);
474 #[cfg(not(target_os = "linux"))]
475 let _ = cgroup_placement_config;
476 serve_bound_daemon(
477 bound,
478 configured_modules,
479 storage_config,
480 admission_facts,
481 daemon_config_path,
482 configured_port,
483 route_bind_relay_default_ms,
484 reserved_capabilities,
485 watchdog_config,
486 capture_logs_dir,
487 terminal_journal_path,
488 #[cfg(target_os = "linux")]
489 cgroup_placement,
490 )
491 .await
492 }
493 }
494}
495
496#[cfg(target_os = "linux")]
497fn prepare_cgroup_placement(config: &CgroupPlacementConfig) -> Option<subc_cgroup::Placement> {
498 let result = match config {
499 CgroupPlacementConfig::Disabled => return None,
500 CgroupPlacementConfig::Current => subc_cgroup::prepare_current(),
501 CgroupPlacementConfig::Root(root) => subc_cgroup::prepare_at(root),
502 };
503
504 match result {
505 Ok(Some(placement)) => Some(placement),
506 Ok(None) => {
507 warn!(
508 placement = ?config,
509 "module cgroup placement is disabled: configured cgroup root is not delegated"
510 );
511 None
512 }
513 Err(error) => {
514 warn!(
515 placement = ?config,
516 error = %error,
517 "module cgroup placement is disabled by an unexpected cgroup probe error"
518 );
519 None
520 }
521 }
522}
523
524#[cfg(unix)]
531const NOFILE_TARGET: u64 = 65536;
532
533#[cfg(unix)]
537fn raise_nofile_limit() {
538 match rlimit::Resource::NOFILE.get() {
539 Ok((soft, hard)) => {
540 if soft >= NOFILE_TARGET {
541 return;
542 }
543 let target = NOFILE_TARGET.min(hard);
544 match rlimit::Resource::NOFILE.set(target, hard) {
545 Ok(()) => info!(
546 previous_soft = soft,
547 new_soft = target,
548 hard,
549 "raised open-file soft limit for daemon and module children"
550 ),
551 Err(err) => warn!(
552 soft,
553 hard,
554 error = %err,
555 "could not raise open-file soft limit; multi-root modules may exhaust descriptors"
556 ),
557 }
558 }
559 Err(err) => warn!(error = %err, "could not read open-file limit"),
560 }
561}
562
563#[cfg(windows)]
570fn raise_nofile_limit() {
571 const MAXSTDIO_TARGET: u32 = 8192;
572 let current = rlimit::getmaxstdio();
573 if current >= MAXSTDIO_TARGET {
574 return;
575 }
576 match rlimit::setmaxstdio(MAXSTDIO_TARGET) {
577 Ok(new_max) => info!(
578 previous = current,
579 new_max, "raised CRT stdio-stream limit for daemon"
580 ),
581 Err(err) => warn!(
582 current,
583 error = %err,
584 "could not raise CRT stdio-stream limit"
585 ),
586 }
587}
588
589#[cfg(not(any(unix, windows)))]
590fn raise_nofile_limit() {}
591
592pub async fn run_with_daemon_config_path(
593 config: BootstrapConfig,
594 daemon_config_path: impl AsRef<Path>,
595) -> Result<(), BootstrapError> {
596 run_with_config(config.with_daemon_config_path(daemon_config_path)?).await
597}
598
599#[allow(clippy::too_many_arguments)]
600async fn serve_bound_daemon(
601 bound: BoundDaemon,
602 configured_modules: Vec<ConfiguredModule>,
603 storage_config: Option<daemon_config::StorageConfig>,
604 admission_facts: AdmissionFactsConfig,
605 daemon_config_path: Option<PathBuf>,
606 configured_port: Option<u16>,
607 route_bind_relay_default_ms: Option<u64>,
608 reserved_capabilities: BTreeMap<String, String>,
609 watchdog_config: DaemonSelfWatchdogConfig,
610 capture_logs_dir: Option<PathBuf>,
611 terminal_journal_path: Option<PathBuf>,
612 #[cfg(target_os = "linux")] cgroup_placement: Option<subc_cgroup::Placement>,
613) -> Result<(), BootstrapError> {
614 #[cfg(unix)]
615 let mut terminate = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
616 .map_err(BootstrapError::Signal)?;
617 raise_nofile_limit();
620
621 info!(
622 connection_file = %bound.connection_file_path.display(),
623 connection_file_source = %bound.connection_file_source,
624 connection_file_source_reason = bound.connection_file_source.reason(),
625 endpoints = ?bound.connection_info.endpoints,
626 configured_modules = configured_modules.len(),
627 machine_id = bound.machine_id.as_ref().map(|id| id.as_str()).unwrap_or("none"),
628 "subc daemon starting"
629 );
630
631 let registry = Arc::new(Registry::default());
632 let process_liveness = Arc::new(SupervisorProcessLiveness::new());
633 let supervisor_handle = SupervisorHandle::new();
634 let connected_clients = ConnectedClients::new();
635 let forwarding = Arc::new(ForwardingTable::default());
636 let daemon_incarnation = format!(
637 "{:032x}",
638 u128::from_be_bytes(bound.connection_info.daemon_id)
639 );
640 let supervisor = Supervisor::new(Arc::clone(®istry), RestartPolicy::default())
641 .with_process_liveness(process_liveness.clone())
642 .with_forwarding(Arc::clone(&forwarding))
643 .with_handle(supervisor_handle.clone())
644 .with_connection_file_path(bound.connection_file_path.clone())
645 .with_daemon_incarnation(daemon_incarnation.clone());
646 let supervisor = match terminal_journal_path {
683 Some(path) => supervisor.with_terminal_journal(path, daemon_incarnation),
684 None => supervisor,
685 };
686 let supervisor = match capture_logs_dir {
687 Some(dir) => supervisor.with_capture_logs_dir(dir),
688 None => supervisor,
689 };
690 #[cfg(target_os = "linux")]
691 let supervisor = supervisor.with_cgroup_placement(cgroup_placement);
692 let route_bind_relay_timeouts = configured_modules
698 .iter()
699 .filter_map(|module| {
700 module
701 .route_bind_relay_timeout_ms
702 .map(|ms| (module.module_id.clone(), Duration::from_millis(ms)))
703 })
704 .collect::<std::collections::BTreeMap<_, _>>();
705 let control_start_clock = crate::clock::StartClock::capture();
706 let mut control = ControlHandler::with_forwarding(Arc::clone(®istry), forwarding)
707 .with_process_liveness(process_liveness)
708 .with_supervisor(supervisor_handle)
709 .with_connected_clients(connected_clients.clone())
710 .with_storage_config(storage_config)
711 .with_machine_id(bound.machine_id.clone())
712 .with_admission_facts_config(admission_facts.carrier_module_id, admission_facts.targets)
713 .with_route_bind_relay_timeouts(route_bind_relay_timeouts)
714 .with_daemon_provenance(
715 bound.connection_info.pid,
716 control_start_clock.started_at_ms(),
717 std::env::current_exe().ok(),
718 normalized_build_provenance(env!("SUBC_BUILD_GIT_SHA")),
719 normalized_build_provenance(env!("SUBC_BUILD_LOCK_DIGEST")),
720 )
721 .with_daemon_start_clock(control_start_clock)
722 .with_capability_config(
723 configured_modules
724 .iter()
725 .map(|module| (module.module_id.clone(), module.enabled)),
726 reserved_capabilities,
727 );
728 if let Some(ms) = route_bind_relay_default_ms {
729 control = control.with_route_bind_relay_timeout(Duration::from_millis(ms));
732 }
733 if let Some(config_path) = daemon_config_path {
734 control = control.with_supervisor_rescan(supervisor.clone(), config_path, configured_port);
735 }
736 let control = Arc::new(control);
737 let router = Arc::new(Router::with_control_handler(Arc::clone(&control)));
738 let auth = ServerAuth::new(
739 bound.connection_info.key.clone(),
740 bound.connection_info.daemon_id,
741 bound.connection_info.daemon_ver.clone(),
742 )
743 .with_connected_clients(connected_clients);
744
745 let mut serve_task =
746 AbortOnDrop::new(tokio::spawn(serve_listeners(bound.listeners, router, auth)));
747 tokio::task::yield_now().await;
748 let _clock_step_task = AbortOnDrop::new(crate::watchdog::spawn_clock_step_monitor());
749 let _watchdog_task = AbortOnDrop::new(
750 DaemonSelfWatchdog::new(
751 bound.connection_info.clone(),
752 bound.connection_file_path.clone(),
753 )
754 .with_config(watchdog_config)
755 .spawn(),
756 );
757
758 for configured in configured_modules {
759 let enabled = configured.enabled;
760 let health = configured.health;
761 let module_id = configured.module_id.clone();
762 match supervisor.supervise_configured_with_health(
763 configured.module_spec(),
764 enabled,
765 health,
766 configured.drain_timeout_ms,
767 configured.restart,
768 ) {
769 Ok(_) => {
770 let default_threshold = HealthConfig::default().failure_threshold;
779 if enabled && health.failure_threshold > default_threshold {
780 warn!(
781 module_id = %module_id,
782 failure_threshold = health.failure_threshold,
783 default_threshold,
784 tolerance_secs = health.cadence.as_secs() * u64::from(health.failure_threshold),
785 "health failure threshold is relaxed above the default; a wedged module stays unflagged for longer"
786 );
787 }
788 info!(module_id = %module_id, enabled, "configured module supervised");
789 }
790 Err(err) => {
791 error!(module_id = %module_id, error = %err, "failed to supervise configured module; continuing daemon startup");
792 }
793 }
794 }
795
796 control.refresh_capability_requirements();
797 Arc::clone(&control).spawn_capability_deadline_loop();
798
799 #[cfg(unix)]
800 {
801 tokio::select! {
802 result = serve_task.join() => {
803 return result.map_err(BootstrapError::ServeJoin)?.map_err(BootstrapError::Serve);
804 }
805 _ = terminate.recv() => {}
806 }
807 supervisor.stamp_shutdown();
809 drop(serve_task);
812 let escalated = tokio::select! {
813 biased;
814 _ = terminate.recv() => {
815 info!("second SIGTERM: abandoning daemon shutdown wait");
816 true
817 }
818 result = supervisor.drain_for_daemon_shutdown() => {
819 if let Err(error) = result {
820 warn!(%error, "daemon shutdown drain failed; exiting anyway");
821 }
822 false
823 }
824 };
825 supervisor
830 .end_children_for_daemon_shutdown(escalated, async {
831 terminate.recv().await;
832 })
833 .await;
834 Ok(())
835 }
836 #[cfg(not(unix))]
837 serve_task
838 .join()
839 .await
840 .map_err(BootstrapError::ServeJoin)?
841 .map_err(BootstrapError::Serve)
842}
843
844fn normalized_build_provenance(value: &str) -> Option<String> {
845 match value.trim() {
846 "" | "unavailable" => None,
847 value => Some(value.to_string()),
848 }
849}
850
851pub async fn ensure_singleton(
859 connection_file_path: impl AsRef<Path>,
860 port: u16,
861) -> Result<Outcome, BootstrapError> {
862 ensure_singleton_with_config(BootstrapConfig::new(connection_file_path.as_ref(), port)).await
863}
864
865pub async fn ensure_singleton_with_config(
866 config: BootstrapConfig,
867) -> Result<Outcome, BootstrapError> {
868 let path = config.connection_file_path;
869
870 if matches!(probe_existing(&path).await?, Probe::Live) {
871 return Ok(Outcome::AlreadyRunning);
872 }
873
874 let _lock = StartLock::acquire(&path).await?;
875
876 if matches!(probe_existing(&path).await?, Probe::Live) {
880 return Ok(Outcome::AlreadyRunning);
881 }
882
883 remove_stale_connection_file_if_present(&path)?;
884
885 let machine_id = config
889 .machine_id_path
890 .as_deref()
891 .map(crate::machine_id::load_or_mint)
892 .transpose()
893 .map_err(BootstrapError::MachineId)?;
894
895 let (listeners, endpoints) = bind_loopback(config.port).await?;
896 let connection_info = ConnectionInfo {
897 schema: SCHEMA_VERSION,
898 wire_version: Some(PROTOCOL_VERSION),
899 endpoints,
900 key: generate_key().map_err(BootstrapError::GenerateConnectionFile)?,
901 daemon_id: generate_daemon_id().map_err(BootstrapError::GenerateConnectionFile)?,
902 pid: process::id(),
903 daemon_ver: config.daemon_ver,
904 };
905
906 if let Err(source) = write_atomic(&path, &connection_info) {
907 drop(listeners);
908 return Err(BootstrapError::ConnectionFileWrite { path, source });
909 }
910
911 Ok(Outcome::Bound(BoundDaemon {
912 listeners,
913 connection_info,
914 connection_file_path: path,
915 connection_file_source: config.connection_file_source,
916 machine_id,
917 }))
918}
919
920#[derive(Debug, Clone, Copy, PartialEq, Eq)]
921enum Probe {
922 Live,
923 StaleOrAbsent,
924}
925
926async fn probe_existing(path: &Path) -> Result<Probe, BootstrapError> {
927 let info = match connection_file::read(path) {
928 Ok(info) => info,
929 Err(source) if is_absent_or_stale_connection_file(&source) => {
930 return Ok(Probe::StaleOrAbsent)
931 }
932 Err(source) => {
933 return Err(BootstrapError::ConnectionFileRead {
934 path: path.to_path_buf(),
935 source,
936 })
937 }
938 };
939
940 for endpoint in &info.endpoints {
941 if matches!(probe_endpoint(&info, endpoint).await, Probe::Live) {
942 return Ok(Probe::Live);
943 }
944 }
945
946 Ok(Probe::StaleOrAbsent)
947}
948
949async fn probe_endpoint(info: &ConnectionInfo, endpoint: &Endpoint) -> Probe {
950 let Ok(ip) = endpoint.host.parse::<IpAddr>() else {
951 return Probe::StaleOrAbsent;
952 };
953 if !ip.is_loopback() {
954 return Probe::StaleOrAbsent;
955 }
956 let addr = SocketAddr::new(ip, endpoint.port);
957
958 let mut stream = match timeout(CONNECT_TIMEOUT, TcpStream::connect(addr)).await {
959 Ok(Ok(stream)) => stream,
960 Ok(Err(_)) | Err(_) => return Probe::StaleOrAbsent,
961 };
962
963 match authenticate_client(&mut stream, info, PROBE_AUTH_DEADLINE).await {
964 Ok(()) => Probe::Live,
965 Err(AuthError::DaemonIdMismatch)
966 | Err(AuthError::InvalidServerProof)
967 | Err(AuthError::UnexpectedEof { .. })
968 | Err(AuthError::Timeout { .. })
969 | Err(AuthError::JsonEncode { .. })
970 | Err(AuthError::JsonDecode { .. })
971 | Err(AuthError::Io { .. })
972 | Err(AuthError::MessageTooLarge { .. })
973 | Err(AuthError::KeyTooShort { .. })
974 | Err(AuthError::Random(_))
975 | Err(AuthError::InvalidClientAuth) => Probe::StaleOrAbsent,
976 }
977}
978
979fn is_absent_or_stale_connection_file(err: &ConnectionFileError) -> bool {
980 match err {
981 ConnectionFileError::Io { source, .. } if source.kind() == io::ErrorKind::NotFound => true,
982 ConnectionFileError::JsonRead { .. }
983 | ConnectionFileError::UnsupportedSchema { .. }
984 | ConnectionFileError::Invalid { .. }
985 | ConnectionFileError::KeyTooShort { .. }
986 | ConnectionFileError::InsecurePermissions { .. } => true,
990 ConnectionFileError::MissingParent { .. }
991 | ConnectionFileError::MissingFileName { .. }
992 | ConnectionFileError::InsecureParentDirectory { .. }
996 | ConnectionFileError::Io { .. }
997 | ConnectionFileError::JsonWrite { .. }
998 | ConnectionFileError::Random(_)
999 | ConnectionFileError::WireVersionMismatch { .. } => false,
1002 }
1003}
1004
1005fn remove_stale_connection_file_if_present(path: &Path) -> Result<(), BootstrapError> {
1006 match fs::remove_file(path) {
1007 Ok(()) => Ok(()),
1008 Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
1009 Err(source) => Err(BootstrapError::RemoveStale {
1010 path: path.to_path_buf(),
1011 source,
1012 }),
1013 }
1014}
1015
1016async fn bind_loopback(port: u16) -> Result<(Vec<TcpListener>, Vec<Endpoint>), BootstrapError> {
1017 let v4_host = Ipv4Addr::LOCALHOST;
1018 let v4 = TcpListener::bind((v4_host, port))
1019 .await
1020 .map_err(|source| BootstrapError::Bind {
1021 host: v4_host.to_string(),
1022 port,
1023 source,
1024 })?;
1025 let actual_port = v4
1026 .local_addr()
1027 .map_err(|source| BootstrapError::LocalAddr {
1028 host: v4_host.to_string(),
1029 source,
1030 })?
1031 .port();
1032
1033 let mut listeners = vec![v4];
1034 let mut endpoints = vec![Endpoint {
1035 host: v4_host.to_string(),
1036 port: actual_port,
1037 }];
1038
1039 let v6_host = Ipv6Addr::LOCALHOST;
1040 match TcpListener::bind((v6_host, actual_port)).await {
1041 Ok(v6) => {
1042 listeners.push(v6);
1043 endpoints.push(Endpoint {
1044 host: v6_host.to_string(),
1045 port: actual_port,
1046 });
1047 }
1048 Err(err) if ipv6_loopback_unavailable(&err) => {
1049 warn!(
1050 port = actual_port,
1051 error = %err,
1052 "IPv6 loopback unavailable; serving only IPv4 loopback"
1053 );
1054 }
1055 Err(source) => {
1056 drop(listeners);
1057 return Err(BootstrapError::Bind {
1058 host: v6_host.to_string(),
1059 port: actual_port,
1060 source,
1061 });
1062 }
1063 }
1064
1065 Ok((listeners, endpoints))
1066}
1067
1068fn ipv6_loopback_unavailable(err: &io::Error) -> bool {
1069 matches!(
1070 err.kind(),
1071 io::ErrorKind::AddrNotAvailable | io::ErrorKind::Unsupported
1072 ) || matches!(err.raw_os_error(), Some(47) | Some(49) | Some(97))
1073}
1074
1075struct AbortOnDrop<T> {
1076 handle: JoinHandle<T>,
1077}
1078
1079impl<T> AbortOnDrop<T> {
1080 fn new(handle: JoinHandle<T>) -> Self {
1081 Self { handle }
1082 }
1083
1084 async fn join(&mut self) -> Result<T, JoinError> {
1085 (&mut self.handle).await
1086 }
1087}
1088
1089impl<T> Drop for AbortOnDrop<T> {
1090 fn drop(&mut self) {
1091 if !self.handle.is_finished() {
1092 self.handle.abort();
1093 }
1094 }
1095}
1096
1097struct StartLock {
1098 _file: fs::File,
1101}
1102
1103impl StartLock {
1104 async fn acquire(connection_file_path: &Path) -> Result<Self, BootstrapError> {
1105 let path = start_lock_path(connection_file_path);
1106 for _ in 0..START_LOCK_RETRIES {
1107 let file = match open_owner_only_lock(&path) {
1108 Ok(file) => file,
1109 Err(source) => return Err(BootstrapError::StartLockCreate { path, source }),
1110 };
1111 match FileExt::try_lock(&file) {
1112 Ok(()) => return Ok(Self { _file: file }),
1113 Err(TryLockError::WouldBlock) => sleep(START_LOCK_RETRY_DELAY).await,
1114 Err(TryLockError::Error(source)) => {
1115 return Err(BootstrapError::StartLockCreate { path, source });
1116 }
1117 }
1118 }
1119
1120 Err(BootstrapError::StartLockBusy {
1121 path,
1122 attempts: START_LOCK_RETRIES,
1123 })
1124 }
1125}
1126
1127fn open_owner_only_lock(path: &Path) -> io::Result<fs::File> {
1128 let mut options = fs::OpenOptions::new();
1129 options.read(true).write(true).create(true);
1130 #[cfg(unix)]
1131 {
1132 use std::os::unix::fs::OpenOptionsExt;
1133 options.mode(0o600);
1134 }
1135 options.open(path)
1136}
1137
1138fn start_lock_path(connection_file_path: &Path) -> PathBuf {
1139 let file_name = connection_file_path
1140 .file_name()
1141 .map(|name| name.to_string_lossy())
1142 .unwrap_or_else(|| CONNECTION_FILE_NAME.into());
1143 let lock_name = format!("{file_name}.start-lock");
1144 connection_file_path
1145 .parent()
1146 .filter(|parent| !parent.as_os_str().is_empty())
1147 .unwrap_or_else(|| Path::new("."))
1148 .join(lock_name)
1149}
1150
1151fn non_empty_os_var(key: &str) -> Option<OsString> {
1152 let value = env::var_os(key)?;
1153 if value.is_empty() {
1154 None
1155 } else {
1156 Some(value)
1157 }
1158}
1159
1160#[derive(Debug)]
1163pub enum BootstrapError {
1164 #[cfg(unix)]
1165 Signal(io::Error),
1166 InvalidPort {
1167 raw: String,
1168 source: std::num::ParseIntError,
1169 },
1170 ConnectionFileRead {
1171 path: PathBuf,
1172 source: ConnectionFileError,
1173 },
1174 ConnectionFileWrite {
1175 path: PathBuf,
1176 source: ConnectionFileError,
1177 },
1178 GenerateConnectionFile(ConnectionFileError),
1179 StartLockCreate {
1180 path: PathBuf,
1181 source: io::Error,
1182 },
1183 StartLockBusy {
1184 path: PathBuf,
1185 attempts: usize,
1186 },
1187 RemoveStale {
1188 path: PathBuf,
1189 source: io::Error,
1190 },
1191 Bind {
1192 host: String,
1193 port: u16,
1194 source: io::Error,
1195 },
1196 LocalAddr {
1197 host: String,
1198 source: io::Error,
1199 },
1200 DaemonConfig(DaemonConfigError),
1201 MachineId(crate::machine_id::MachineIdFileError),
1204 RunDir(daemon_config::DaemonRunDirError),
1207 Serve(ServerError),
1208 ServeJoin(tokio::task::JoinError),
1209}
1210
1211impl fmt::Display for BootstrapError {
1212 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1213 match self {
1214 #[cfg(unix)]
1215 Self::Signal(error) => write!(f, "failed to register SIGTERM handler: {error}"),
1216 Self::InvalidPort { raw, source } => {
1217 write!(f, "invalid {SUBC_PORT_ENV} value '{raw}': {source}")
1218 }
1219 Self::ConnectionFileRead { path, source } => write!(
1220 f,
1221 "failed to read connection file {}: {source}",
1222 path.display()
1223 ),
1224 Self::ConnectionFileWrite { path, source } => write!(
1225 f,
1226 "failed to publish connection file {}: {source}",
1227 path.display()
1228 ),
1229 Self::GenerateConnectionFile(err) => {
1230 write!(f, "failed to generate connection-file auth material: {err}")
1231 }
1232 Self::StartLockCreate { path, source } => {
1233 write!(
1234 f,
1235 "failed to create start lock {}: {source}",
1236 path.display()
1237 )
1238 }
1239 Self::StartLockBusy { path, attempts } => write!(
1240 f,
1241 "start lock {} remained busy after {attempts} attempts",
1242 path.display()
1243 ),
1244 Self::RemoveStale { path, source } => write!(
1245 f,
1246 "failed to remove stale connection file {}: {source}",
1247 path.display()
1248 ),
1249 Self::Bind { host, port, source } if source.kind() == io::ErrorKind::AddrInUse => {
1250 write!(
1251 f,
1252 "port {port} in use on loopback {host}: {source}; set the port in config"
1253 )
1254 }
1255 Self::Bind { host, port, source } => {
1256 write!(f, "failed to bind loopback TCP {host}:{port}: {source}")
1257 }
1258 Self::LocalAddr { host, source } => {
1259 write!(f, "failed to read local address for {host}: {source}")
1260 }
1261 Self::DaemonConfig(err) => write!(f, "failed to load daemon config: {err}"),
1262 Self::MachineId(err) => write!(f, "refusing to start: {err}"),
1263 Self::RunDir(err) => write!(f, "refusing to start: {err}"),
1264 Self::Serve(err) => write!(f, "daemon server failed: {err}"),
1265 Self::ServeJoin(err) => write!(f, "daemon server task failed: {err}"),
1266 }
1267 }
1268}
1269
1270impl Error for BootstrapError {
1271 fn source(&self) -> Option<&(dyn Error + 'static)> {
1272 match self {
1273 #[cfg(unix)]
1274 Self::Signal(source) => Some(source),
1275 Self::InvalidPort { source, .. } => Some(source),
1276 Self::ConnectionFileRead { source, .. }
1277 | Self::ConnectionFileWrite { source, .. }
1278 | Self::GenerateConnectionFile(source) => Some(source),
1279 Self::StartLockCreate { source, .. }
1280 | Self::RemoveStale { source, .. }
1281 | Self::Bind { source, .. }
1282 | Self::LocalAddr { source, .. } => Some(source),
1283 Self::DaemonConfig(err) => Some(err),
1284 Self::MachineId(err) => Some(err),
1285 Self::RunDir(err) => Some(err),
1286 Self::Serve(err) => Some(err),
1287 Self::ServeJoin(err) => Some(err),
1288 Self::StartLockBusy { .. } => None,
1289 }
1290 }
1291}
1292
1293#[cfg(test)]
1294mod tests {
1295 use super::*;
1296 use crate::server::ServerAuth;
1297 use crate::test_support::TestTempDir;
1298 #[cfg(target_os = "linux")]
1299 use std::collections::BTreeSet;
1300 use std::sync::Mutex;
1301 #[cfg(target_os = "linux")]
1302 use subc_control::ModuleProtocol;
1303 use subc_transport::MIN_KEY_LEN;
1304 use tokio::io::AsyncReadExt;
1305 use tokio::task::JoinHandle;
1306
1307 #[cfg(unix)]
1308 use std::os::unix::fs::PermissionsExt;
1309
1310 static ENV_LOCK: Mutex<()> = Mutex::new(());
1311
1312 #[test]
1313 fn normalized_build_provenance_preserves_real_values() {
1314 assert_eq!(normalized_build_provenance("abc"), Some("abc".to_string()));
1315 }
1316
1317 #[test]
1318 fn normalized_build_provenance_omits_unavailable_and_empty_values() {
1319 assert_eq!(normalized_build_provenance("unavailable"), None);
1320 assert_eq!(normalized_build_provenance(""), None);
1321 }
1322
1323 #[cfg(target_os = "linux")]
1324 fn current_cgroup_path_for_test() -> io::Result<PathBuf> {
1325 let cgroups = fs::read_to_string("/proc/self/cgroup")?;
1326 let relative = cgroups
1327 .lines()
1328 .find_map(|line| line.strip_prefix("0::"))
1329 .ok_or_else(|| {
1330 io::Error::new(io::ErrorKind::Unsupported, "cgroup v2 is unavailable")
1331 })?;
1332 Ok(Path::new("/sys/fs/cgroup").join(relative.trim_start_matches('/')))
1333 }
1334
1335 #[cfg(target_os = "linux")]
1336 fn module_cgroup_directories() -> io::Result<BTreeSet<OsString>> {
1337 let modules = current_cgroup_path_for_test()?.join("subc-modules");
1338 let entries = match fs::read_dir(modules) {
1339 Ok(entries) => entries,
1340 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(BTreeSet::new()),
1341 Err(error) => return Err(error),
1342 };
1343 let mut directories = BTreeSet::new();
1344 for entry in entries {
1345 let entry = entry?;
1346 if entry.file_type()?.is_dir() {
1347 directories.insert(entry.file_name());
1348 }
1349 }
1350 Ok(directories)
1351 }
1352
1353 #[cfg(target_os = "linux")]
1354 async fn wait_for_path(path: &Path, task: &JoinHandle<Result<(), BootstrapError>>) {
1355 let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
1356 while !path.exists() && tokio::time::Instant::now() < deadline {
1357 assert!(
1358 !task.is_finished(),
1359 "daemon exited before creating {}",
1360 path.display()
1361 );
1362 sleep(Duration::from_millis(10)).await;
1363 }
1364 assert!(path.exists(), "daemon did not create {}", path.display());
1365 }
1366
1367 #[cfg(target_os = "linux")]
1372 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1373 async fn run_with_config_does_not_reconcile_the_ambient_cgroup_by_default() {
1374 let temp = unique_temp_dir("bootstrap-cgroup-default-disabled");
1375 let module_id = format!("cgroup-isolation-probe-{}", process::id());
1376 let before = module_cgroup_directories().expect("read ambient module cgroups before boot");
1377 assert!(
1378 !before.contains(&OsString::from(&module_id)),
1379 "isolation probe cgroup already exists before this daemon starts"
1380 );
1381 let capture = temp.join("logs").join(format!("{module_id}.stderr.log"));
1382 let module = ConfiguredModule {
1383 module_id,
1384 program: PathBuf::from("sh"),
1385 args: vec!["-c".to_string(), "sleep 30".to_string()],
1386 env: Vec::new(),
1387 log: None,
1388 enabled: true,
1389 reserved: false,
1390 reserved_prefixes: Vec::new(),
1391 protocol: ModuleProtocol::None,
1392 overlap: Default::default(),
1393 health: HealthConfig::default(),
1394 drain_timeout_ms: None,
1395 route_bind_relay_timeout_ms: None,
1396 restart: RestartPolicy::default(),
1397 };
1398 let config = BootstrapConfig::new(temp.join("connection.json"), 0)
1399 .with_configured_modules([module])
1400 .with_capture_logs_dir(temp.join("logs"))
1401 .with_terminal_journal_path(temp.join("terminals.jsonl"));
1402 let task = tokio::spawn(run_with_config(config));
1403
1404 wait_for_path(&capture, &task).await;
1405 let after = module_cgroup_directories().expect("read ambient module cgroups after boot");
1406
1407 task.abort();
1408 assert!(task
1409 .await
1410 .expect_err("aborted daemon task must cancel")
1411 .is_cancelled());
1412 assert_eq!(
1413 before, after,
1414 "an in-process daemon must not create or reconcile ambient module cgroups"
1415 );
1416 }
1417
1418 #[cfg(target_os = "linux")]
1419 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1420 async fn explicit_cgroup_root_is_prepared_inside_the_fixture_tree() {
1421 let temp = unique_temp_dir("bootstrap-cgroup-explicit-root");
1422 let cgroup_root = temp.join("cgroup");
1423 fs::create_dir(&cgroup_root).expect("create scratch cgroup root");
1424 fs::write(cgroup_root.join("cgroup.procs"), b"").expect("write scratch cgroup marker");
1425 let modules = cgroup_root.join("subc-modules");
1426 let config = BootstrapConfig::new(temp.join("connection.json"), 0)
1427 .with_cgroup_placement(CgroupPlacementConfig::Root(cgroup_root))
1428 .with_terminal_journal_path(temp.join("terminals.jsonl"));
1429 let task = tokio::spawn(run_with_config(config));
1430
1431 wait_for_path(&modules, &task).await;
1432
1433 task.abort();
1434 assert!(task
1435 .await
1436 .expect_err("aborted daemon task must cancel")
1437 .is_cancelled());
1438 assert!(
1439 fs::read_dir(&modules)
1440 .expect("read prepared modules directory")
1441 .next()
1442 .is_none(),
1443 "the delegation probe must clean up after itself"
1444 );
1445 }
1446
1447 struct EnvGuard {
1448 key: &'static str,
1449 previous: Option<OsString>,
1450 }
1451
1452 impl EnvGuard {
1453 fn set(key: &'static str, value: &Path) -> Self {
1454 let previous = env::var_os(key);
1455 env::set_var(key, value);
1456 Self { key, previous }
1457 }
1458
1459 fn set_str(key: &'static str, value: &str) -> Self {
1460 let previous = env::var_os(key);
1461 env::set_var(key, value);
1462 Self { key, previous }
1463 }
1464
1465 fn unset(key: &'static str) -> Self {
1466 let previous = env::var_os(key);
1467 env::remove_var(key);
1468 Self { key, previous }
1469 }
1470 }
1471
1472 impl Drop for EnvGuard {
1473 fn drop(&mut self) {
1474 match &self.previous {
1475 Some(value) => env::set_var(self.key, value),
1476 None => env::remove_var(self.key),
1477 }
1478 }
1479 }
1480
1481 fn unique_temp_dir(name: &str) -> TestTempDir {
1482 TestTempDir::new(name)
1483 }
1484
1485 fn temp_connection_file_path(name: &str) -> (TestTempDir, PathBuf) {
1486 let dir = unique_temp_dir(name);
1487 let path = dir.join("conn.json");
1488 (dir, path)
1489 }
1490
1491 fn auth_for(info: &ConnectionInfo) -> ServerAuth {
1492 ServerAuth::new(info.key.clone(), info.daemon_id, info.daemon_ver.clone())
1493 }
1494
1495 fn start_server(bound: BoundDaemon) -> JoinHandle<Result<(), ServerError>> {
1496 let auth = auth_for(&bound.connection_info);
1497 tokio::spawn(serve_listeners(
1498 bound.listeners,
1499 Arc::new(Router::with_default_self_handler()),
1500 auth,
1501 ))
1502 }
1503
1504 fn expect_bound(outcome: Outcome) -> BoundDaemon {
1505 match outcome {
1506 Outcome::Bound(bound) => bound,
1507 Outcome::AlreadyRunning => panic!("fresh connection file unexpectedly had a daemon"),
1508 }
1509 }
1510
1511 async fn connect_from_info(conn: &ConnectionInfo) -> io::Result<TcpStream> {
1512 let endpoint = conn
1513 .endpoints
1514 .first()
1515 .expect("test connection file should have an endpoint");
1516 let ip: IpAddr = endpoint.host.parse().unwrap();
1517 TcpStream::connect(SocketAddr::new(ip, endpoint.port)).await
1518 }
1519
1520 fn make_connection_info(port: u16) -> ConnectionInfo {
1521 ConnectionInfo {
1522 schema: SCHEMA_VERSION,
1523 wire_version: Some(PROTOCOL_VERSION),
1524 endpoints: vec![Endpoint {
1525 host: "127.0.0.1".to_owned(),
1526 port,
1527 }],
1528 key: generate_key().unwrap(),
1529 daemon_id: generate_daemon_id().unwrap(),
1530 pid: process::id(),
1531 daemon_ver: "test-subc".to_owned(),
1532 }
1533 }
1534
1535 fn write_raw_owner_only_connection_file(path: &Path, contents: &[u8]) {
1536 fs::write(path, contents).unwrap();
1537 #[cfg(unix)]
1538 fs::set_permissions(path, fs::Permissions::from_mode(0o600)).unwrap();
1539 }
1540
1541 fn assert_owner_only_connection_file(path: &Path) {
1542 #[cfg(unix)]
1545 {
1546 let mode = fs::metadata(path).unwrap().permissions().mode() & 0o777;
1547 assert_eq!(mode, 0o600);
1548 }
1549 #[cfg(not(unix))]
1550 let _ = path;
1551 }
1552
1553 #[test]
1554 fn connection_file_path_uses_xdg_runtime_dir_when_set() {
1555 let _env_lock = ENV_LOCK.lock().unwrap();
1556 let runtime_dir = unique_temp_dir("xdg-runtime");
1557 let _xdg = EnvGuard::set("XDG_RUNTIME_DIR", runtime_dir.path());
1558
1559 assert_eq!(
1560 connection_file_path(),
1561 runtime_dir.join(CONNECTION_FILE_NAME)
1562 );
1563 }
1564
1565 #[test]
1566 fn connection_file_path_source_is_xdg_runtime_dir_when_set() {
1567 let runtime_dir = OsString::from("/run/user/1000");
1568
1569 let (path, source) = connection_file_path_with_source(Some(runtime_dir));
1570
1571 assert_eq!(
1572 path,
1573 PathBuf::from("/run/user/1000").join(CONNECTION_FILE_NAME)
1574 );
1575 assert_eq!(source, ConnectionFileSource::XdgRuntimeDir);
1576 }
1577
1578 #[test]
1579 fn connection_file_path_falls_back_to_temp_dir_with_user_token_when_xdg_unset() {
1580 let _env_lock = ENV_LOCK.lock().unwrap();
1581 let _xdg = EnvGuard::unset("XDG_RUNTIME_DIR");
1582
1583 assert_eq!(
1584 connection_file_path(),
1585 env::temp_dir().join(format!("subc-{}.connection.json", user_connection_token()))
1586 );
1587 }
1588
1589 #[test]
1590 fn connection_file_path_source_is_temp_dir_when_xdg_unset() {
1591 let (path, source) = connection_file_path_with_source(None);
1592
1593 assert_eq!(
1594 path,
1595 env::temp_dir().join(format!("subc-{}.connection.json", user_connection_token()))
1596 );
1597 assert_eq!(source, ConnectionFileSource::TempDirFallback);
1598 }
1599
1600 #[test]
1605 fn user_connection_token_is_stable_under_concurrent_callers() {
1606 let expected = user_connection_token();
1607 let workers: Vec<_> = (0..32)
1608 .map(|_| {
1609 std::thread::spawn(|| (0..40).map(|_| user_connection_token()).collect::<Vec<_>>())
1610 })
1611 .collect();
1612 for worker in workers {
1613 for token in worker.join().expect("probe thread") {
1614 assert_eq!(token, expected, "token diverged under concurrent probes");
1615 }
1616 }
1617 }
1618
1619 #[test]
1620 fn connection_file_path_source_is_temp_dir_when_xdg_empty() {
1621 let (path, source) = connection_file_path_with_source(Some(OsString::new()));
1622
1623 assert_eq!(
1624 path,
1625 env::temp_dir().join(format!("subc-{}.connection.json", user_connection_token()))
1626 );
1627 assert_eq!(source, ConnectionFileSource::TempDirFallback);
1628 }
1629
1630 #[test]
1634 fn daemon_binary_config_journals_and_captures_into_the_run_dir() {
1635 let _env_lock = ENV_LOCK.lock().unwrap();
1636 let root = unique_temp_dir("daemon-binary-config");
1637 let data_home = root.join("data");
1638 let _data = EnvGuard::set("XDG_DATA_HOME", &data_home);
1639 let _config = EnvGuard::set("XDG_CONFIG_HOME", &root.join("config"));
1640 let _port = EnvGuard::unset(SUBC_PORT_ENV);
1641
1642 let config = BootstrapConfig::from_env_for_daemon_binary().unwrap();
1643
1644 let run_dir = data_home.join("cortexkit").join("run");
1645 assert_eq!(
1646 config.terminal_journal_path,
1647 Some(run_dir.join("terminals.jsonl"))
1648 );
1649 assert_eq!(config.capture_logs_dir, Some(run_dir.join("logs")));
1650 assert_eq!(
1651 BootstrapConfig::new(root.join("connection.json"), 0).terminal_journal_path,
1652 None,
1653 "an in-process config must not journal anywhere unless asked to"
1654 );
1655 }
1656
1657 #[test]
1658 fn daemon_binary_config_refuses_a_relative_data_home() {
1659 let _env_lock = ENV_LOCK.lock().unwrap();
1660 let root = unique_temp_dir("daemon-binary-relative-data");
1661 let _data = EnvGuard::set_str("XDG_DATA_HOME", "relative-data-home");
1662 let _config = EnvGuard::set("XDG_CONFIG_HOME", &root.join("config"));
1663 let _port = EnvGuard::unset(SUBC_PORT_ENV);
1664
1665 let error = BootstrapConfig::from_env_for_daemon_binary()
1666 .expect_err("a relative data home must refuse the daemon binary's config");
1667 assert!(
1668 matches!(error, BootstrapError::RunDir(_)),
1669 "expected a run-directory refusal, got {error}"
1670 );
1671 assert!(error.to_string().contains("XDG_DATA_HOME"), "{error}");
1672 }
1673
1674 #[test]
1675 fn configured_port_uses_default_config_and_env_override() {
1676 let _env_lock = ENV_LOCK.lock().unwrap();
1677 let (_dir, conn_path) = temp_connection_file_path("daemon-config-port");
1678 let config_path = conn_path.with_file_name("subc.jsonc");
1679
1680 let _port = EnvGuard::unset(SUBC_PORT_ENV);
1681 assert_eq!(
1682 BootstrapConfig::from_env_with_daemon_config_path(&config_path)
1683 .unwrap()
1684 .port,
1685 DEFAULT_SUBC_PORT
1686 );
1687
1688 fs::write(&config_path, r#"{ "version": 1, "port": 8123 }"#).unwrap();
1689 assert_eq!(
1690 BootstrapConfig::from_env_with_daemon_config_path(&config_path)
1691 .unwrap()
1692 .port,
1693 8123
1694 );
1695
1696 let _port = EnvGuard::set_str(SUBC_PORT_ENV, "9012");
1697 assert_eq!(
1698 BootstrapConfig::from_env_with_daemon_config_path(&config_path)
1699 .unwrap()
1700 .port,
1701 9012
1702 );
1703 }
1704
1705 #[tokio::test]
1706 async fn second_singleton_probe_against_served_tcp_daemon_reports_already_running() {
1707 let (_dir, path) = temp_connection_file_path("already-running");
1708
1709 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
1710 let server = start_server(bound);
1711
1712 let second = ensure_singleton(&path, 0).await.unwrap();
1713 assert!(matches!(second, Outcome::AlreadyRunning));
1714
1715 server.abort();
1716 let _ = server.await;
1717 }
1718
1719 #[tokio::test]
1720 async fn daemon_connection_file_publishes_protocol_wire_version() {
1721 let (_dir, path) = temp_connection_file_path("wire-version");
1722 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
1723 assert_eq!(bound.connection_info.wire_version, Some(PROTOCOL_VERSION));
1724 assert_eq!(
1725 connection_file::read(&path).unwrap().wire_version,
1726 Some(PROTOCOL_VERSION)
1727 );
1728
1729 drop(bound.listeners);
1730 }
1731
1732 #[tokio::test]
1733 async fn stale_unbound_connection_file_is_reclaimed() {
1734 let (_dir, path) = temp_connection_file_path("stale-reclaim");
1735 let stale = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
1736 let stale_port = stale.local_addr().unwrap().port();
1737 drop(stale);
1738 let stale_info = make_connection_info(stale_port);
1739 write_atomic(&path, &stale_info).unwrap();
1740
1741 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
1742 assert_ne!(bound.connection_info.key, stale_info.key);
1743 drop(bound.listeners);
1744 }
1745
1746 #[cfg(unix)]
1747 #[tokio::test]
1748 async fn ensure_singleton_reclaims_insecure_connection_file() {
1749 let (_dir, path) = temp_connection_file_path("insecure-reclaim");
1750 let stale = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
1751 let stale_port = stale.local_addr().unwrap().port();
1752 drop(stale);
1753 let stale_info = make_connection_info(stale_port);
1754 write_atomic(&path, &stale_info).unwrap();
1755 fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
1756
1757 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
1758 assert_ne!(bound.connection_info.key, stale_info.key);
1759 assert_ne!(bound.connection_info.daemon_id, stale_info.daemon_id);
1760 assert_owner_only_connection_file(&path);
1761
1762 drop(bound.listeners);
1763 }
1764
1765 #[tokio::test]
1766 async fn ensure_singleton_reclaims_non_loopback_connection_file() {
1767 let (_dir, path) = temp_connection_file_path("non-loopback-reclaim");
1768 let mut stale_info = make_connection_info(8757);
1769 stale_info.endpoints = vec![Endpoint {
1770 host: "192.0.2.10".to_owned(),
1771 port: 8757,
1772 }];
1773 write_atomic(&path, &stale_info).unwrap();
1774
1775 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
1776 assert_ne!(bound.connection_info.key, stale_info.key);
1777 assert_ne!(bound.connection_info.daemon_id, stale_info.daemon_id);
1778 assert!(bound
1779 .connection_info
1780 .endpoints
1781 .iter()
1782 .all(|endpoint| endpoint.host.parse::<IpAddr>().unwrap().is_loopback()));
1783 assert_owner_only_connection_file(&path);
1784
1785 drop(bound.listeners);
1786 }
1787
1788 #[tokio::test]
1789 async fn ensure_singleton_reclaims_invalid_connection_file_shapes() {
1790 let mut unsupported_schema = make_connection_info(8757);
1791 unsupported_schema.schema = SCHEMA_VERSION + 1;
1792
1793 let mut empty_endpoints = make_connection_info(8757);
1794 empty_endpoints.endpoints.clear();
1795
1796 let mut short_key = make_connection_info(8757);
1797 short_key.key = vec![0x5A; MIN_KEY_LEN - 1];
1798
1799 let cases = vec![
1800 (
1801 "unsupported-schema",
1802 serde_json::to_vec(&unsupported_schema).unwrap(),
1803 Some(unsupported_schema),
1804 ),
1805 (
1806 "empty-endpoints",
1807 serde_json::to_vec(&empty_endpoints).unwrap(),
1808 Some(empty_endpoints),
1809 ),
1810 (
1811 "short-key",
1812 serde_json::to_vec(&short_key).unwrap(),
1813 Some(short_key),
1814 ),
1815 ("invalid-json", b"{not valid connection json".to_vec(), None),
1816 ];
1817
1818 for (label, contents, old_info) in cases {
1819 let (_dir, path) = temp_connection_file_path(label);
1820 write_raw_owner_only_connection_file(&path, &contents);
1821
1822 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
1823 if let Some(old_info) = old_info {
1824 assert_ne!(bound.connection_info.key, old_info.key, "{label}");
1825 assert_ne!(
1826 bound.connection_info.daemon_id, old_info.daemon_id,
1827 "{label}"
1828 );
1829 }
1830 assert!(bound.connection_info.key.len() >= MIN_KEY_LEN, "{label}");
1831 assert_ne!(bound.connection_info.daemon_id, [0u8; 16], "{label}");
1832 assert_owner_only_connection_file(&path);
1833
1834 drop(bound.listeners);
1835 }
1836 }
1837
1838 #[tokio::test]
1839 async fn foreign_reused_port_connection_file_is_reclaimed_after_auth_probe_fails() {
1840 let (_dir, path) = temp_connection_file_path("foreign-reclaim");
1841 let foreign = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
1842 let foreign_port = foreign.local_addr().unwrap().port();
1843 write_atomic(&path, &make_connection_info(foreign_port)).unwrap();
1844 let foreign_task = tokio::spawn(async move {
1845 if let Ok((mut stream, _)) = foreign.accept().await {
1846 let mut buf = [0u8; 64];
1847 let _ = stream.read(&mut buf).await;
1848 }
1849 });
1850
1851 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
1852 assert!(bound
1853 .connection_info
1854 .endpoints
1855 .iter()
1856 .all(|endpoint| endpoint.port != foreign_port));
1857
1858 drop(bound.listeners);
1859 let _ = foreign_task.await;
1860 }
1861
1862 #[tokio::test]
1863 async fn stale_start_lock_file_is_reclaimable() {
1864 let (_dir, path) = temp_connection_file_path("start-lock-stale-file");
1865 let lock_path = start_lock_path(&path);
1866 drop(open_owner_only_lock(&lock_path).unwrap());
1867 assert!(lock_path.is_file());
1868
1869 let lock = StartLock::acquire(&path).await.unwrap();
1870 assert!(lock_path.is_file());
1871
1872 drop(lock);
1873 assert!(lock_path.is_file());
1874 }
1875
1876 #[tokio::test]
1877 async fn held_start_lock_blocks_second_acquire_until_release() {
1878 let (_dir, path) = temp_connection_file_path("start-lock-held");
1879 let lock_path = start_lock_path(&path);
1880 let first = StartLock::acquire(&path).await.unwrap();
1881
1882 let err = match StartLock::acquire(&path).await {
1883 Ok(_) => panic!("second acquire while held must stay busy"),
1884 Err(err) => err,
1885 };
1886 assert!(matches!(
1887 err,
1888 BootstrapError::StartLockBusy {
1889 ref path,
1890 attempts: START_LOCK_RETRIES,
1891 } if path == &lock_path
1892 ));
1893
1894 drop(first);
1895
1896 let second = StartLock::acquire(&path)
1897 .await
1898 .expect("released advisory lock should be reclaimable");
1899 drop(second);
1900 }
1901
1902 #[tokio::test]
1903 async fn bind_conflict_on_fixed_port_fails_loud_without_reselecting() {
1904 let (_dir, path) = temp_connection_file_path("bind-conflict");
1905 let occupied = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
1906 let occupied_port = occupied.local_addr().unwrap().port();
1907
1908 let err = ensure_singleton(&path, occupied_port).await.unwrap_err();
1909 assert!(matches!(
1910 err,
1911 BootstrapError::Bind { ref source, .. } if source.kind() == io::ErrorKind::AddrInUse
1912 ));
1913 assert!(err.to_string().contains("set the port in config"));
1914
1915 drop(occupied);
1916 }
1917
1918 #[tokio::test]
1919 async fn key_rotation_republishes_new_material_and_old_file_fails_auth() {
1920 let (_dir, path) = temp_connection_file_path("key-rotation");
1921 let first = expect_bound(ensure_singleton(&path, 0).await.unwrap());
1922 let old_info = first.connection_info.clone();
1923 let fixed_port = old_info.endpoints[0].port;
1924 drop(first.listeners);
1925
1926 let second = expect_bound(ensure_singleton(&path, fixed_port).await.unwrap());
1927 let new_info = second.connection_info.clone();
1928 assert_ne!(old_info.key, new_info.key);
1929 assert_ne!(old_info.daemon_id, new_info.daemon_id);
1930 let server = start_server(second);
1931
1932 let mut old_stream = connect_from_info(&old_info).await.unwrap();
1933 let old_auth = authenticate_client(&mut old_stream, &old_info, PROBE_AUTH_DEADLINE).await;
1934 assert!(
1935 old_auth.is_err(),
1936 "old key must not authenticate after restart"
1937 );
1938
1939 let reread = connection_file::read(&path).unwrap();
1940 let mut new_stream = connect_from_info(&reread).await.unwrap();
1941 authenticate_client(&mut new_stream, &reread, PROBE_AUTH_DEADLINE)
1942 .await
1943 .unwrap();
1944
1945 server.abort();
1946 let _ = server.await;
1947 }
1948
1949 #[cfg(unix)]
1950 #[tokio::test]
1951 async fn published_connection_file_permissions_are_owner_only() {
1952 let (_dir, path) = temp_connection_file_path("permissions");
1953 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
1954
1955 let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
1956 assert_eq!(mode, 0o600);
1957
1958 drop(bound.listeners);
1959 }
1960}