1use std::{
2 collections::{BTreeMap, BTreeSet},
3 fs::{self, File},
4 io::{self, Read},
5 os::{
6 fd::{AsFd, RawFd},
7 unix::fs::MetadataExt,
8 },
9 time::{Duration, Instant, SystemTime},
10};
11
12use rustix::{
13 fs::{self as rfs, FileType, Mode, OFlags},
14 io::{fcntl_setfd, FdFlags},
15};
16use sha2::{Digest, Sha256};
17use subc_os::child_spawn::{monotonic_ns, InheritedDescriptors};
18
19use crate::{
20 config_store::{StoreRoot, StoreWriterLock},
21 live_children::{self, AdoptedPids},
22 run_dir_lock::{RunDirLock, RUN_DIR_LOCK_FILE_NAME},
23 supervise::{
24 handover::{
25 self, Cohort, Handover, HexBytes, LockPaths, LockRole, StreamWitness, VerifiedImage,
26 },
27 live_upgrade::{reconcile_child, InheritedStreams, ReconciledChild},
28 resume_hello::Preparation,
29 RegisteredConfiguredModule,
30 },
31};
32
33use super::{
34 start_lock_path, BootstrapConfig, BootstrapError, Path, PathBuf, StartLock, Supervisor,
35 SupervisorHandle,
36};
37
38pub const HANDOVER_VERSIONS: &[u32] = handover::HANDOVER_VERSIONS;
40
41pub struct ResumeBootstrap {
43 config: BootstrapConfig,
44 inherited: Result<Inherited, io::Error>,
45}
46
47impl ResumeBootstrap {
48 pub fn validate(
52 config: BootstrapConfig,
53 path: &Path,
54 key_fd: RawFd,
55 inherited: InheritedDescriptors,
56 ) -> Result<Self, BootstrapError> {
57 let inherited = validate(&config, path, key_fd, inherited)?;
58 Ok(Self { config, inherited })
59 }
60
61 pub async fn run(self) -> Result<(), BootstrapError> {
62 let inherited = match self.inherited {
63 Ok(inherited) => Some(inherited),
64 Err(error) => {
65 tracing::warn!(%error, "running image did not match the upgrade target; starting cold");
66 eprintln!("ck-subc: running image did not match the upgrade target; starting cold: {error}");
67 None
68 }
69 };
70 super::run_with_config_inner(self.config, inherited).await
71 }
72}
73
74pub(super) struct Inherited {
75 pub(super) start: StartLock,
76 pub(super) run: RunDirLock,
77 pub(super) store: Option<(StoreRoot, StoreWriterLock)>,
78 pub(super) resume: Resume,
79}
80
81pub(super) struct Resume {
82 handover: Handover,
83 streams: BTreeMap<RawFd, std::os::fd::OwnedFd>,
84 deadline: Instant,
85 #[cfg(feature = "test-support")]
86 pause_install: Option<(String, PathBuf)>,
87}
88
89fn refused(error: impl std::fmt::Display) -> BootstrapError {
90 BootstrapError::Resume(io::Error::other(error.to_string()))
91}
92
93fn validate(
94 config: &BootstrapConfig,
95 path: &Path,
96 key_fd: RawFd,
97 mut inherited: InheritedDescriptors,
98) -> Result<Result<Inherited, io::Error>, BootstrapError> {
99 let record = config
100 .live_children_path
101 .as_ref()
102 .ok_or_else(|| refused("no live-children record configured"))?;
103 let expected = record.with_file_name(handover::HANDOVER_FILE_NAME);
104 if path.as_os_str() != expected.as_os_str() {
105 return Err(refused(
106 "handover path does not match the configured run directory",
107 ));
108 }
109 let file = File::from(
110 rfs::open(
111 path,
112 OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
113 Mode::empty(),
114 )
115 .map_err(refused)?,
116 );
117 let stat = file.metadata().map_err(refused)?;
118 if !stat.is_file() || stat.uid() != subc_os::effective_uid() || stat.mode() & 0o7777 != 0o600 {
119 return Err(refused(
120 "handover must be a regular file owned by this user with mode 0600",
121 ));
122 }
123 let key =
124 read_key(File::from(inherited.take_key(key_fd).map_err(refused)?)).map_err(refused)?;
125 let mut bytes = Vec::new();
126 (&file).read_to_end(&mut bytes).map_err(refused)?;
127 let mut handover = handover::decode(&bytes, &key).map_err(refused)?;
128 validate_cohort(&handover)?;
129 let now_ms = crate::stderr_tail::unix_ms(SystemTime::now());
130 let deadline = Instant::now()
131 .checked_add(Duration::from_millis(
132 handover.reconnect_by_ms.saturating_sub(now_ms),
133 ))
134 .ok_or_else(|| refused("handover reconnect deadline is out of range"))?;
135
136 let run = record.with_file_name(RUN_DIR_LOCK_FILE_NAME);
137 let publication = start_lock_path(&config.connection_file_path);
138 let store = config
139 .config_store_root()
140 .map(StoreWriterLock::inherited_layout)
141 .transpose()
142 .map_err(refused)?;
143 let paths = LockPaths {
144 run_dir: &run,
145 publication: &publication,
146 store_writer: store.as_ref().map(|(_, lock)| lock.as_path()),
147 };
148 let expected_fds = handover
149 .locks
150 .iter()
151 .map(|lock| lock.fd)
152 .chain(
153 handover
154 .children
155 .iter()
156 .flat_map(|child| [&child.stdout, &child.stderr])
157 .filter_map(|stream| match stream {
158 StreamWitness::Open { fd, .. } => Some(*fd),
159 StreamWitness::Ended {} => None,
160 }),
161 )
162 .collect();
163 let mut descriptors = inherited.into_named(&expected_fds).map_err(refused)?;
164 handover::validate_inherited_fds(&handover, config, &paths, |fd| {
165 descriptors.get(&fd).map(AsFd::as_fd)
166 })
167 .map_err(refused)?;
168
169 if let Err(error) = verify_running_image(config, &handover.verified_image) {
170 return Ok(Err(error));
173 }
174
175 let current = fs::symlink_metadata(path).map_err(refused)?;
176 if current.dev() != stat.dev() || current.ino() != stat.ino() {
177 return Err(refused("handover file changed during validation"));
178 }
179 fs::remove_file(path).map_err(refused)?;
180 for fd in descriptors.values() {
181 fcntl_setfd(fd, FdFlags::CLOEXEC).map_err(refused)?;
182 }
183
184 let mut locks: BTreeMap<_, _> = handover
185 .locks
186 .drain(..)
187 .map(|lock| {
188 (
189 lock.role,
190 File::from(
191 descriptors
192 .remove(&lock.fd)
193 .expect("validated lock descriptor"),
194 ),
195 )
196 })
197 .collect();
198 let start = StartLock {
199 _file: locks
200 .remove(&LockRole::Publication)
201 .expect("validated publication lock"),
202 };
203 let run = RunDirLock::from_inherited(
204 record.clone(),
205 locks.remove(&LockRole::RunDir).expect("validated run lock"),
206 );
207 let store = store.map(|(root, _)| {
208 (
209 root,
210 StoreWriterLock::from_inherited(
211 locks
212 .remove(&LockRole::StoreWriter)
213 .expect("validated store lock"),
214 ),
215 )
216 });
217 Ok(Ok(Inherited {
218 start,
219 run,
220 store,
221 resume: Resume {
222 handover,
223 streams: descriptors,
224 deadline,
225 #[cfg(feature = "test-support")]
226 pause_install: config
227 .upgrade_binary
228 .as_ref()
229 .filter(|binary| binary.test_hooks)
230 .and_then(|_| std::env::var("SUBC_TEST_RESUME_PAUSE_MODULE").ok())
231 .map(|module| (module, record.with_file_name("rp.sock"))),
234 },
235 }))
236}
237
238fn read_key(mut pipe: File) -> io::Result<[u8; 32]> {
239 let flags = rfs::fcntl_getfl(&pipe)?;
240 if FileType::from_raw_mode(rfs::fstat(&pipe)?.st_mode) != FileType::Fifo
241 || flags.intersects(OFlags::WRONLY | OFlags::RDWR)
242 {
243 return Err(io::Error::other(
244 "handover key descriptor must be a pipe read end",
245 ));
246 }
247 rfs::fcntl_setfl(&pipe, flags | OFlags::NONBLOCK)?;
250 let mut key = [0; 32];
251 pipe.read_exact(&mut key)?;
252 if pipe.read(&mut [0])? != 0 {
253 return Err(io::Error::other("handover key must be exactly 32 bytes"));
254 }
255 Ok(key)
256}
257
258fn validate_cohort(handover: &Handover) -> Result<(), BootstrapError> {
259 let cohort = &handover.cohort;
260 let mut modules = BTreeSet::new();
261 let carried: BTreeSet<_> = cohort.carried.iter().collect();
262 let mut children = BTreeSet::new();
263 let mut pids = BTreeSet::new();
264 if !cohort
265 .carried
266 .iter()
267 .chain(&cohort.restarting)
268 .chain(&cohort.stopped)
269 .all(|id| modules.insert(id))
270 || !handover
271 .children
272 .iter()
273 .all(|child| children.insert(&child.module_id) && pids.insert(child.pid))
274 || carried != children
275 {
276 return Err(refused("handover children and cohort disagree"));
277 }
278 let mut streams = BTreeSet::new();
279 for stream in handover
280 .children
281 .iter()
282 .flat_map(|child| [&child.stdout, &child.stderr])
283 {
284 if let StreamWitness::Open { fd, .. } = stream {
285 if !streams.insert(*fd) {
286 return Err(refused(format!(
287 "duplicate handover stream descriptor {fd}"
288 )));
289 }
290 }
291 }
292 Ok(())
293}
294
295fn verify_running_image(_config: &BootstrapConfig, expected: &VerifiedImage) -> io::Result<()> {
296 #[cfg(target_os = "linux")]
297 let (path, cdhash_matches) = (PathBuf::from("/proc/self/exe"), expected.cdhash.is_none());
298 #[cfg(target_os = "macos")]
299 let (path, cdhash_matches) = {
300 use subc_os::code_signature::{self, SignatureError};
301 let cdhash_matches = match (expected.cdhash, code_signature::self_cdhash()) {
302 (Some(expected), Ok(actual)) => expected.0 == actual.0,
303 #[cfg(feature = "test-support")]
304 (None, Err(SignatureError::NotSigned)) => _config
305 .upgrade_binary
306 .as_ref()
307 .is_some_and(|binary| binary.test_hooks),
308 (_, Err(SignatureError::NotSigned)) | (None, Ok(_)) => false,
309 (_, Err(error)) => return Err(io::Error::other(error)),
310 };
311 (std::env::current_exe()?, cdhash_matches)
312 };
313 let mut digest = Sha256::new();
314 io::copy(&mut File::open(path)?, &mut digest)?;
315 if !cdhash_matches || HexBytes(digest.finalize().into()) != expected.sha256 {
316 return Err(io::Error::other(
317 "running executable digest or code signature differs from the verified target",
318 ));
319 }
320 Ok(())
321}
322
323pub(super) fn discard_leftover(owner: &RunDirLock) {
325 let path = owner
326 .live_children_record()
327 .with_file_name(handover::HANDOVER_FILE_NAME);
328 if let Err(error) = fs::remove_file(&path) {
329 if error.kind() != io::ErrorKind::NotFound {
330 tracing::warn!(path = %path.display(), %error, "could not remove a leftover daemon handover");
331 }
332 }
333}
334
335pub(super) struct AdoptionPlan {
336 pub(super) protected: AdoptedPids,
337 pub(super) monotonic_ns: u64,
338 cohort: Cohort,
339 children: BTreeMap<String, (ReconciledChild, InheritedStreams)>,
340 attempt: HexBytes<16>,
341 started_at_ms: u64,
342 deadline: Instant,
343 #[cfg(feature = "test-support")]
344 pause_install: Option<(String, PathBuf)>,
345}
346
347impl Resume {
348 pub(super) fn verified_digest(&self) -> HexBytes<32> {
349 self.handover.verified_image.sha256
350 }
351
352 pub(super) fn reconcile(mut self, owner: &RunDirLock) -> Result<AdoptionPlan, BootstrapError> {
353 let records = match live_children::read_record_entries(owner.live_children_record()) {
354 Ok((records, _)) => records,
355 Err(error) => {
356 tracing::warn!(%error, "could not read the carried children's durable identities");
359 Vec::new()
360 }
361 };
362 let by_pid: BTreeMap<_, _> = records
363 .iter()
364 .map(|record| (record.child.pid, record))
365 .collect();
366 let mut adopted = Vec::new();
367 let mut held = Vec::new();
368 let mut children = BTreeMap::new();
369 for mut child in self.handover.children {
370 let streams = [&mut child.stdout, &mut child.stderr].map(|stream| {
371 match std::mem::replace(stream, StreamWitness::Ended {}) {
372 StreamWitness::Open { fd, tail } => Some((
373 self.streams
374 .remove(&fd)
375 .expect("validated stream descriptor"),
376 tail,
377 )),
378 StreamWitness::Ended {} => None,
379 }
380 });
381 let pid = child.pid;
382 let module = child.module_id.clone();
383 let reconciled = reconcile_child(child, by_pid.get(&pid).copied()).map_err(refused)?;
384 match &reconciled {
385 ReconciledChild::Adopt(_) => adopted.push(pid),
386 ReconciledChild::Held(_) => held.push(pid),
387 ReconciledChild::Exited => {}
388 }
389 children.insert(module, (reconciled, streams));
390 }
391 Ok(AdoptionPlan {
392 protected: AdoptedPids::from_classes(adopted, held),
393 monotonic_ns: self.handover.monotonic_ns,
394 cohort: self.handover.cohort,
395 children,
396 attempt: self.handover.attempt_id,
397 started_at_ms: self.handover.started_at_ms,
398 deadline: self.deadline,
399 #[cfg(feature = "test-support")]
400 pause_install: self.pause_install,
401 })
402 }
403}
404
405type RegisteredCohort = BTreeMap<String, (RegisteredConfiguredModule, bool)>;
406pub(super) type PlannedStarts = Vec<(String, Option<RegisteredConfiguredModule>, bool)>;
407type Preparations = BTreeMap<String, Preparation>;
408
409impl AdoptionPlan {
410 fn modules(&self) -> impl Iterator<Item = &String> {
411 self.cohort
412 .carried
413 .iter()
414 .chain(&self.cohort.restarting)
415 .chain(&self.cohort.stopped)
416 }
417
418 pub(super) fn begin_report(&self, supervisor: &SupervisorHandle) {
419 supervisor.begin_resume_report(
420 self.attempt.to_string(),
421 self.started_at_ms,
422 self.modules().cloned(),
423 );
424 }
425
426 pub(super) fn enabled(&self, module: &str, configured: bool) -> Option<bool> {
427 self.modules()
428 .any(|id| id == module)
429 .then(|| self.cohort.allow_start(module, Some(configured)))
430 }
431
432 pub(super) fn stage_preparations(
433 &self,
434 handle: &SupervisorHandle,
435 registered: &RegisteredCohort,
436 ) -> Result<Preparations, BootstrapError> {
437 self.children
438 .iter()
439 .filter_map(|(module, (child, _))| {
440 let ReconciledChild::Adopt(child) = child else {
441 return None;
442 };
443 registered.get(module).filter(|(_, enabled)| *enabled)?;
444 Some(
445 child
446 .begin_preparation(handle, self.deadline.into())
447 .map(|guard| (module.clone(), guard))
448 .map_err(refused),
449 )
450 })
451 .collect()
452 }
453
454 pub(super) async fn install(
455 mut self,
456 supervisor: &Supervisor,
457 mut registered: RegisteredCohort,
458 mut preparations: Preparations,
459 ) -> Result<PlannedStarts, BootstrapError> {
460 let mut planned = Vec::new();
461 let mut installing = tokio::task::JoinSet::new();
462 let attempt = self.attempt.0;
463 let deadline = self.deadline.into();
464 for module in self
465 .cohort
466 .carried
467 .into_iter()
468 .chain(self.cohort.restarting)
469 .chain(self.cohort.stopped)
470 {
471 let (registered, enabled) = match registered.remove(&module) {
472 Some((registered, enabled)) => (Some(registered), enabled),
473 None => (None, false),
474 };
475 match self.children.remove(&module) {
476 Some((ReconciledChild::Adopt(child), streams)) => {
477 if let Some(registered) = registered {
478 let supervisor = supervisor.clone();
479 let preparation = preparations.remove(&module);
480 #[cfg(feature = "test-support")]
481 let pause = self
482 .pause_install
483 .as_ref()
484 .filter(|(id, _)| *id == module)
485 .map(|(_, path)| path.clone());
486 installing.spawn(async move {
487 let _preparation = preparation;
488 #[cfg(feature = "test-support")]
489 if let Some(path) = pause {
490 let _ = tokio::time::timeout_at(
491 deadline,
492 crate::control::upgrade_in_place::wait_at_gate(&path, 1),
493 )
494 .await;
495 }
496 supervisor
497 .start_adopted_after_upgrade(
498 registered, *child, streams, attempt, deadline, enabled,
499 )
500 .await
501 });
502 } else {
503 supervisor.watch_unresolved_after_upgrade(child.stop(), None, false);
504 }
505 }
506 Some((ReconciledChild::Held(child), _)) => {
507 supervisor.watch_unresolved_after_upgrade(*child, registered, enabled);
508 }
509 Some((ReconciledChild::Exited, _)) | None => {
510 planned.push((module, registered, enabled))
511 }
512 }
513 }
514 while let Some(result) = installing.join_next().await {
515 result.map_err(refused)?.map_err(refused)?;
516 }
517 Ok(planned)
518 }
519}
520
521pub(super) fn log_accept(sample: u64) {
522 match monotonic_ns() {
523 Ok(now) => tracing::info!(
524 resume_accept_ms = now.saturating_sub(sample) / 1_000_000,
525 "local listener accepting daemon upgrade reconnects"
526 ),
527 Err(error) => {
528 tracing::warn!(%error, "could not measure when the local listener started accepting")
529 }
530 }
531}
532
533#[cfg(test)]
534mod tests {
535 use super::*;
536 use std::io::Write;
537
538 #[test]
539 fn duplicate_stream_descriptor_is_refused_before_adoption() {
540 let mut handover = handover::decode(
541 include_bytes!("../../tests/fixtures/handover-format-2.txt"),
542 b"0123456789abcdef0123456789abcdef",
543 )
544 .unwrap();
545 validate_cohort(&handover).unwrap();
546 let StreamWitness::Open { fd, .. } = handover.children[0].stdout else {
547 panic!("golden handover must have an open stdout");
548 };
549 handover.children[1].stderr = StreamWitness::Open { fd, tail: vec![] };
550 assert!(validate_cohort(&handover)
551 .unwrap_err()
552 .to_string()
553 .contains("duplicate handover stream descriptor"));
554 }
555
556 #[test]
557 fn handover_key_requires_exactly_32_bytes_and_a_closed_writer() {
558 for key in [&[7; 31][..], &[7; 32], &[7; 33]] {
559 let (reader, mut writer) = io::pipe().unwrap();
560 writer.write_all(key).unwrap();
561 drop(writer);
562 let result = read_key(File::from(std::os::fd::OwnedFd::from(reader)));
563 if key.len() == 32 {
564 assert_eq!(result.unwrap(), [7; 32]);
565 } else {
566 assert!(result.is_err());
567 }
568 }
569 let (reader, mut writer) = io::pipe().unwrap();
570 writer.write_all(&[7; 32]).unwrap();
571 let error = read_key(File::from(std::os::fd::OwnedFd::from(reader))).unwrap_err();
572 assert_eq!(error.kind(), io::ErrorKind::WouldBlock);
573 drop(writer);
574 }
575}