1use std::io::{BufRead, BufReader, Read, Write};
20use std::path::{Path, PathBuf};
21use std::process::{Child, ChildStdin, Command, Stdio};
22use std::sync::{Mutex, PoisonError, mpsc};
23use std::time::{Duration, Instant};
24
25use serde::{Deserialize, Serialize};
26
27use super::{InstallError, Result, RuntimeKind, VerifiedPackage, bootstrap, install};
28
29const ACTIVATION: &str = "activation.json";
32const EXECUTABLE: &str = if cfg!(windows) {
34 "leanctx-cockpit.exe"
35} else {
36 "leanctx-cockpit"
37};
38const HANDSHAKE: Duration = Duration::from_secs(10);
40const EXIT_GRACE: Duration = Duration::from_secs(2);
42const RESTART_BACKOFF: [Duration; 3] = [
45 Duration::from_secs(1),
46 Duration::from_secs(5),
47 Duration::from_secs(30),
48];
49const STABLE: Duration = Duration::from_mins(1);
50const MAX_PORT_LINE: u64 = 256;
52
53pub struct CockpitLaunch {
55 pub engine_port: u16,
57 pub engine_token: String,
59 pub project_root: PathBuf,
60}
61
62#[derive(Clone, PartialEq, Eq)]
65pub struct CockpitEndpoint {
66 pub port: u16,
67 pub cockpit_token: String,
69}
70
71impl std::fmt::Debug for CockpitEndpoint {
72 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73 formatter
74 .debug_struct("CockpitEndpoint")
75 .field("port", &self.port)
76 .field("cockpit_token", &"<redacted>")
77 .finish()
78 }
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum CockpitUnavailable {
84 NotInstalled,
86 VerificationFailed,
88 StartFailed,
91 Disabled,
93 SourceBuild,
96 DownloadFailed,
99}
100
101impl CockpitUnavailable {
102 pub const fn as_str(self) -> &'static str {
103 match self {
104 Self::NotInstalled => "not_installed",
105 Self::VerificationFailed => "verification_failed",
106 Self::StartFailed => "start_failed",
107 Self::Disabled => "disabled",
108 Self::SourceBuild => "source_build",
109 Self::DownloadFailed => "download_failed",
110 }
111 }
112
113 pub const fn message(self) -> &'static str {
117 match self {
118 Self::NotInstalled => {
119 "The Cockpit is not installed. Install it with: lean-ctx cockpit install"
120 }
121 Self::VerificationFailed => {
122 "The installed Cockpit did not verify and was not started. Reinstall it with: lean-ctx cockpit install"
123 }
124 Self::StartFailed => {
125 "The Cockpit is installed but did not start. See why: lean-ctx cockpit --foreground (it logs the cause)"
126 }
127 Self::Disabled => {
128 "The Cockpit is deactivated. Activate it again with: lean-ctx cockpit install"
129 }
130 Self::SourceBuild => {
131 "Source build: the Cockpit ships with official installs (install.sh, Homebrew, npm, AUR)"
132 }
133 Self::DownloadFailed => {
134 "The Cockpit download failed (network error or timeout). Try again with: lean-ctx cockpit install, or install a local bundle with: lean-ctx cockpit install --from <bundle>"
135 }
136 }
137 }
138}
139
140const BUNDLE_FILES: [(&str, usize); 5] = [
142 ("channel.json", 65_536),
143 ("channel.sig", 64),
144 ("manifest.json", 65_536),
145 ("manifest.sig", 64),
146 ("archive.tar.gz", super::manifest::MAX_ARCHIVE),
147];
148
149fn read_bundle(path: &Path) -> Result<super::catalog::Bundle> {
152 let mut files: [Option<Vec<u8>>; 5] = Default::default();
153 if std::fs::symlink_metadata(path)?.is_dir() {
154 for (slot, (name, limit)) in files.iter_mut().zip(BUNDLE_FILES) {
155 *slot = Some(super::read_regular(&path.join(name), limit)?);
156 }
157 } else {
158 let packed = super::read_regular(path, super::manifest::MAX_ARCHIVE + (1 << 20))?;
159 let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(packed.as_slice()));
160 for entry in archive.entries().map_err(|_| InstallError::Archive)? {
161 let entry = entry.map_err(|_| InstallError::Archive)?;
162 let kind = entry.header().entry_type();
163 if kind.is_dir() {
164 continue;
165 }
166 let entry_path = entry
167 .path()
168 .map_err(|_| InstallError::Archive)?
169 .into_owned();
170 let parts: Vec<_> = entry_path.components().collect();
171 if !kind.is_file()
172 || parts.len() > 2
173 || parts
174 .iter()
175 .any(|part| !matches!(part, std::path::Component::Normal(_)))
176 {
177 return Err(InstallError::Archive);
178 }
179 let name = entry_path.file_name().and_then(|name| name.to_str());
180 let Some(index) = BUNDLE_FILES
181 .iter()
182 .position(|(known, _)| Some(*known) == name)
183 else {
184 return Err(InstallError::Archive);
185 };
186 let limit = BUNDLE_FILES[index].1;
187 let mut bytes = Vec::new();
188 entry
189 .take(limit as u64 + 1)
190 .read_to_end(&mut bytes)
191 .map_err(|_| InstallError::Archive)?;
192 if bytes.len() > limit || files[index].replace(bytes).is_some() {
193 return Err(InstallError::Archive);
194 }
195 }
196 }
197 let [
198 Some(catalog),
199 Some(catalog_signature),
200 Some(manifest),
201 Some(signature),
202 Some(archive),
203 ] = files
204 else {
205 return Err(InstallError::Archive);
206 };
207 Ok(super::catalog::Bundle {
208 catalog,
209 catalog_signature,
210 archive,
211 manifest,
212 signature,
213 })
214}
215
216fn import(bundle: &super::catalog::Bundle, downgrade: bool) -> Result<serde_json::Value> {
220 let channel = bootstrap::cockpit_channel()?.ok_or(InstallError::Policy)?;
221 let root = bootstrap::cockpit_root()?;
222 install::prepare_parent_chain(root.parent().ok_or(InstallError::Directory)?)?;
223 let _guard = install::configuration_guard(&root)?;
224 let expected = install::active_manifest(&root)?;
225 let installation = super::catalog::import_kind(
226 RuntimeKind::Cockpit,
227 bundle,
228 &channel.key,
229 &root,
230 &expected,
231 downgrade,
232 )?;
233 activate_installation(&root, &installation, "bundle")
234}
235
236pub(crate) fn install_from(path: &Path, downgrade: bool) -> Result<serde_json::Value> {
238 import(&read_bundle(path)?, downgrade)
239}
240
241pub fn install_from_cli(args: &[String]) -> bool {
245 if args.is_empty() {
246 return false;
247 }
248 let downgrade = args.iter().any(|arg| arg == "--allow-downgrade");
249 let rest: Vec<&str> = args
250 .iter()
251 .map(String::as_str)
252 .filter(|arg| *arg != "--allow-downgrade")
253 .collect();
254 let path = match rest.as_slice() {
255 ["--from", path] => *path,
256 [flag] if flag.starts_with("--from=") => &flag["--from=".len()..],
257 _ => {
258 eprintln!(
259 "Usage: lean-ctx cockpit install [--from <dir|file.tar.gz> [--allow-downgrade]]"
260 );
261 std::process::exit(2);
262 }
263 };
264 match install_from(Path::new(path), downgrade) {
265 Ok(result) => {
266 println!(
267 "{}",
268 serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string())
269 );
270 println!("Open it with: lean-ctx cockpit");
271 }
272 Err(InstallError::Downgrade) => {
273 eprintln!(
274 "lean-ctx cockpit install --from: this bundle is older than the active Cockpit; \
275 add --allow-downgrade to install it"
276 );
277 std::process::exit(1);
278 }
279 Err(error) => {
280 eprintln!("lean-ctx cockpit install --from: the bundle was not installed ({error:?})");
281 std::process::exit(1);
282 }
283 }
284 true
285}
286
287fn bundled_dir() -> Option<PathBuf> {
289 let exe = std::env::current_exe().ok()?.canonicalize().ok()?;
290 let prefix = exe.parent()?.parent()?;
291 ["share", "libexec"]
292 .iter()
293 .map(|place| prefix.join(place).join("lean-ctx").join("cockpit"))
294 .find(|dir| dir.join("manifest.json").is_file())
295}
296
297fn import_bundled() {
301 let Some(dir) = bundled_dir() else {
302 return;
303 };
304 let Ok(manifest) = super::read_regular(&dir.join("manifest.json"), 65_536) else {
305 return;
306 };
307 let shipped = super::sha256(&manifest);
308 let active = bootstrap::cockpit_root()
309 .ok()
310 .and_then(|root| read_activation(&root).ok().flatten());
311 if active
314 .as_ref()
315 .is_some_and(|active| !active.enabled || active.manifest_sha256 == shipped)
316 {
317 return;
318 }
319 match read_bundle(&dir).and_then(|bundle| import(&bundle, false)) {
320 Ok(_) => tracing::info!("imported the bundled cockpit"),
321 Err(InstallError::Downgrade) => {
322 tracing::info!("bundled cockpit is older than the active one; kept the active one");
323 }
324 Err(error) => tracing::debug!("bundled cockpit not imported: {error:?}"),
325 }
326}
327
328#[derive(Serialize, Deserialize)]
329#[serde(deny_unknown_fields)]
330struct Activation {
331 schema_version: u32,
332 enabled: bool,
333 manifest_sha256: String,
334 trust_key_hex: String,
335}
336
337fn read_activation(root: &Path) -> Result<Option<Activation>> {
338 let path = root.join(ACTIVATION);
339 if !path.try_exists()? {
340 return Ok(None);
341 }
342 let activation: Activation = serde_json::from_slice(&super::read_regular(&path, 4096)?)
343 .map_err(|_| InstallError::State)?;
344 if activation.schema_version != 1
345 || !super::is_digest(&activation.manifest_sha256, 64)
346 || !super::is_digest(&activation.trust_key_hex, 64)
347 {
348 return Err(InstallError::State);
349 }
350 Ok(Some(activation))
351}
352
353fn write_activation(root: &Path, activation: &Activation) -> Result<()> {
355 let bytes = serde_json::to_vec_pretty(activation).map_err(|_| InstallError::State)?;
356 crate::core::updater::atomic_write_bytes(&root.join(ACTIVATION), &bytes)
357 .map_err(|_| InstallError::Commit)
358}
359
360fn activate_locked(root: &Path, selected: &str, key_hex: &str) -> Result<serde_json::Value> {
363 let key = super::trust_key(key_hex)?;
364 let package = install::verified_active_kind(RuntimeKind::Cockpit, root, selected, &key)?;
365 write_activation(
366 root,
367 &Activation {
368 schema_version: 1,
369 enabled: true,
370 manifest_sha256: selected.to_owned(),
371 trust_key_hex: key_hex.to_owned(),
372 },
373 )?;
374 Ok(serde_json::json!({"status": "activated", "kind": "cockpit",
375 "receipt": package.receipt, "runtime_started": false, "release_approved": false}))
376}
377
378fn authenticated() -> std::result::Result<(PathBuf, VerifiedPackage), CockpitUnavailable> {
380 let root = bootstrap::cockpit_root().map_err(|_| CockpitUnavailable::NotInstalled)?;
381 let activation = match read_activation(&root) {
382 Ok(Some(activation)) => activation,
383 Ok(None) => return Err(CockpitUnavailable::NotInstalled),
384 Err(_) => return Err(CockpitUnavailable::VerificationFailed),
385 };
386 if !activation.enabled {
387 return Err(CockpitUnavailable::Disabled);
388 }
389 let package = super::trust_key(&activation.trust_key_hex)
390 .and_then(|key| {
391 install::verified_active_kind(
392 RuntimeKind::Cockpit,
393 &root,
394 &activation.manifest_sha256,
395 &key,
396 )
397 })
398 .map_err(|_| CockpitUnavailable::VerificationFailed)?;
399 Ok((root, package))
400}
401
402fn install_configured(staging: Option<bool>) -> Result<serde_json::Value> {
406 let channel = bootstrap::cockpit_channel()?.ok_or(InstallError::Policy)?;
407 if staging.is_some_and(|staging| staging != channel.staging) {
408 return Err(InstallError::Usage);
409 }
410 let root = bootstrap::cockpit_root()?;
411 install::prepare_parent_chain(root.parent().ok_or(InstallError::Directory)?)?;
412 let _guard = install::configuration_guard(&root)?;
413 let expected = install::active_manifest(&root)?;
414 let installation = super::catalog::sync_kind(
415 RuntimeKind::Cockpit,
416 channel.urls,
417 &channel.key,
418 &root,
419 &expected,
420 super::catalog::Companions::Inline,
421 )?;
422 activate_installation(&root, &installation, "channel")
423}
424
425fn activate_installation(
428 root: &Path,
429 installation: &serde_json::Value,
430 source: &str,
431) -> Result<serde_json::Value> {
432 let selected = installation["receipt"]["manifest_sha256"]
433 .as_str()
434 .ok_or(InstallError::State)?;
435 let key = installation["artifact_key_hex"]
436 .as_str()
437 .ok_or(InstallError::State)?;
438 let activation = activate_locked(root, selected, key)?;
439 retire();
440 Ok(
441 serde_json::json!({"status": "installed_and_activated", "kind": "cockpit", "source": source,
442 "installation": installation, "activation": activation, "release_approved": false}),
443 )
444}
445
446pub fn install_cockpit() -> std::result::Result<serde_json::Value, CockpitUnavailable> {
450 install_configured(None).map_err(|error| install_failure(&error))
451}
452
453fn install_failure(error: &InstallError) -> CockpitUnavailable {
455 match error {
456 InstallError::Manifest
457 | InstallError::ChannelExpired
458 | InstallError::ChannelMismatch
459 | InstallError::PlatformUnavailable
460 | InstallError::Signature
461 | InstallError::Archive
462 | InstallError::Size
463 | InstallError::State
464 | InstallError::Downgrade => CockpitUnavailable::VerificationFailed,
465 InstallError::Download => CockpitUnavailable::DownloadFailed,
468 InstallError::NotOffered => CockpitUnavailable::SourceBuild,
471 _ => CockpitUnavailable::NotInstalled,
472 }
473}
474
475pub fn availability() -> std::result::Result<(), CockpitUnavailable> {
480 import_bundled();
481 match authenticated() {
482 Ok(_) => Ok(()),
483 Err(CockpitUnavailable::NotInstalled)
484 if bootstrap::cockpit_channel().ok().flatten().is_none() =>
485 {
486 Err(CockpitUnavailable::SourceBuild)
487 }
488 Err(reason) => Err(reason),
489 }
490}
491
492fn installs_opted_out() -> bool {
494 std::env::var_os("LEAN_CTX_NO_COCKPIT").is_some_and(|value| !value.is_empty() && value != "0")
495}
496
497pub fn available_or_installed() -> std::result::Result<(), CockpitUnavailable> {
500 match availability() {
501 Err(CockpitUnavailable::NotInstalled) if !installs_opted_out() => {
502 eprintln!(
503 "Installing the LeanCTX Cockpit (signed, free) from the LeanCTX runtime channel…"
504 );
505 install_cockpit()?;
506 availability()
507 }
508 other => other,
509 }
510}
511
512const AUTO_RETRY: Duration = Duration::from_hours(24);
514
515fn auto_attempt_marker() -> Option<PathBuf> {
516 crate::core::data_dir::resolve_data_dir()
517 .ok()
518 .map(|dir| dir.join("cockpit-auto-install.failed"))
519}
520
521fn retry_blocked(failed_at: Option<std::time::SystemTime>, now: std::time::SystemTime) -> bool {
523 failed_at
524 .and_then(|failed_at| now.duration_since(failed_at).ok())
525 .is_some_and(|elapsed| elapsed < AUTO_RETRY)
526}
527
528pub(crate) fn install_if_missing(retry_now: bool) -> bool {
534 if installs_opted_out()
535 || crate::core::telemetry_consent::ci_detected(crate::core::host_env::var)
536 {
537 return false;
538 }
539 if !matches!(availability(), Err(CockpitUnavailable::NotInstalled)) {
540 return false;
541 }
542 let marker = auto_attempt_marker();
543 let failed_at = marker
544 .as_deref()
545 .and_then(|path| std::fs::metadata(path).ok())
546 .and_then(|metadata| metadata.modified().ok());
547 if !retry_now && retry_blocked(failed_at, std::time::SystemTime::now()) {
548 return false;
549 }
550 match install_cockpit() {
551 Ok(_) => {
552 if let Some(path) = &marker {
553 let _ = std::fs::remove_file(path);
554 }
555 tracing::info!("installed the cockpit automatically");
556 true
557 }
558 Err(reason) => {
559 if let Some(path) = &marker {
560 let _ = std::fs::write(path, reason.as_str());
561 }
562 tracing::debug!("automatic cockpit install failed: {}", reason.as_str());
563 false
564 }
565 }
566}
567
568pub fn install_if_missing_in_background() {
571 let _ = std::thread::Builder::new()
572 .name("cockpit-install".into())
573 .spawn(|| {
574 install_if_missing(false);
575 });
576}
577
578pub(crate) fn status() -> serde_json::Value {
581 let (status, version) = match authenticated() {
582 Ok((_, package)) => ("installed", Some(package.receipt.version)),
583 Err(reason) => (reason.as_str(), None),
584 };
585 let channel = bootstrap::cockpit_channel().ok().flatten();
586 serde_json::json!({"schema_version": 1, "kind": "cockpit", "status": status,
587 "version": version, "channel_available": channel.is_some(),
588 "staging": channel.map(|channel| channel.staging),
589 "runtime_started": false, "release_approved": false})
590}
591
592fn deactivate() -> Result<serde_json::Value> {
593 let root = bootstrap::cockpit_root()?;
594 if !root.try_exists()? {
595 return Ok(serde_json::json!({"status": "not_installed", "kind": "cockpit"}));
596 }
597 let _guard = install::configuration_guard(&root)?;
598 let Some(mut activation) = read_activation(&root)? else {
599 return Ok(serde_json::json!({"status": "not_installed", "kind": "cockpit"}));
600 };
601 activation.enabled = false;
602 write_activation(&root, &activation)?;
603 retire();
604 Ok(serde_json::json!({"status": "disabled", "kind": "cockpit", "release_approved": false}))
605}
606
607pub(super) fn run_cli(
611 operation: &str,
612 staging: bool,
613 accepted: bool,
614 flags: &std::collections::BTreeMap<&str, &str>,
615) -> Result<serde_json::Value> {
616 match operation {
617 "status" if flags.is_empty() => Ok(status()),
618 "deactivate" if flags.is_empty() => deactivate(),
619 "sync-configured" if flags.is_empty() && accepted => install_configured(Some(staging)),
620 "activate" if staging && accepted && flags.len() == 4 => {
623 let get = |name| flags.get(name).copied().ok_or(InstallError::Usage);
624 let root = Path::new(get("--root")?);
625 let selected = get("--manifest-sha256")?;
626 if get("--expected-active")? != selected
627 || root != bootstrap::cockpit_root()?
628 || bootstrap::production_key(root)?.is_some()
629 {
630 return Err(InstallError::Usage);
631 }
632 let _guard = install::configuration_guard(root)?;
633 let result = activate_locked(root, selected, get("--trust-key-hex")?)?;
634 retire();
635 Ok(result)
636 }
637 _ => Err(InstallError::Usage),
638 }
639}
640
641#[cfg(any(windows, test))]
644const MEMORY_BUDGET_DEFAULT_MIB: u64 = 4096;
645#[cfg(any(windows, test))]
647const MEMORY_BUDGET_MIN_MIB: u64 = 256;
648const STDERR_TAIL: usize = 4096;
650const STDERR_SETTLE: Duration = Duration::from_millis(500);
652
653#[cfg(any(windows, test))]
657fn memory_budget(setting: Option<&str>) -> Option<u64> {
658 let mib = match setting.map(str::trim) {
659 Some("0") => return None,
660 Some(value) => value
661 .parse::<u64>()
662 .map_or(MEMORY_BUDGET_DEFAULT_MIB, |mib| {
663 mib.max(MEMORY_BUDGET_MIN_MIB)
664 }),
665 None => MEMORY_BUDGET_DEFAULT_MIB,
666 };
667 Some(mib.saturating_mul(1024 * 1024))
668}
669
670#[derive(Default)]
672struct StderrTail {
673 bytes: Vec<u8>,
674 cut: bool,
676}
677
678fn keep_tail(tail: &mut StderrTail, chunk: &[u8], cap: usize) {
680 tail.bytes.extend_from_slice(chunk);
681 if tail.bytes.len() > cap {
682 tail.bytes.drain(..tail.bytes.len() - cap);
683 tail.cut = true;
684 }
685}
686
687const MIN_SECRET_FRAGMENT: usize = 4;
689
690fn stderr_report(tail: &[u8], cut: bool, open_end: bool, secrets: &[String]) -> String {
697 let mut text = String::from_utf8_lossy(tail).into_owned();
698 if cut {
699 text = text
700 .split_once('\n')
701 .map_or_else(String::new, |(_, rest)| rest.to_owned());
702 }
703 if open_end {
704 text.truncate(text.rfind('\n').map_or(0, |end| end + 1));
705 }
706 for secret in secrets.iter().filter(|secret| !secret.is_empty()) {
707 text = text.replace(secret.as_str(), "[REDACTED:token]");
708 for len in (MIN_SECRET_FRAGMENT..secret.len()).rev() {
709 let (Some(head), Some(rest)) = (secret.get(..len), secret.get(secret.len() - len..))
710 else {
711 continue;
712 };
713 if let Some(kept) = text.strip_prefix(rest) {
714 text = format!("[REDACTED:token]{kept}");
715 }
716 if let Some(kept) = text.strip_suffix(head) {
717 text = format!("{kept}[REDACTED:token]");
718 }
719 }
720 }
721 crate::core::redaction::redact_text(&text)
722 .chars()
723 .filter(|c| !c.is_control() || matches!(c, '\n' | '\t'))
724 .collect::<String>()
725 .trim()
726 .to_owned()
727}
728
729#[cfg(windows)]
732struct MemoryJob {
733 handle: windows_sys::Win32::Foundation::HANDLE,
734 limit: u64,
735}
736
737#[cfg(windows)]
738impl MemoryJob {
739 fn assign(child: &Child, limit: Option<u64>) -> std::io::Result<Self> {
740 use std::os::windows::io::AsRawHandle;
741 use windows_sys::Win32::System::JobObjects::{
742 AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
743 JOB_OBJECT_LIMIT_PROCESS_MEMORY, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
744 JobObjectExtendedLimitInformation, SetInformationJobObject,
745 };
746 let handle = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
748 if handle.is_null() {
749 return Err(std::io::Error::last_os_error());
750 }
751 let job = Self {
752 handle,
753 limit: limit.unwrap_or(0),
754 };
755 let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
756 limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
757 if let Some(limit) = limit {
758 limits.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_PROCESS_MEMORY;
759 limits.ProcessMemoryLimit = usize::try_from(limit).unwrap_or(usize::MAX);
760 }
761 let configured = unsafe {
763 SetInformationJobObject(
764 job.handle,
765 JobObjectExtendedLimitInformation,
766 std::ptr::from_ref(&limits).cast(),
767 std::mem::size_of_val(&limits) as u32,
768 )
769 };
770 if configured == 0 {
771 return Err(std::io::Error::last_os_error());
772 }
773 let assigned =
775 unsafe { AssignProcessToJobObject(job.handle, child.as_raw_handle().cast()) };
776 if assigned == 0 {
777 return Err(std::io::Error::last_os_error());
778 }
779 Ok(job)
780 }
781
782 fn peak(&self) -> Option<u64> {
784 use windows_sys::Win32::System::JobObjects::{
785 JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation,
786 QueryInformationJobObject,
787 };
788 let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
789 let queried = unsafe {
791 QueryInformationJobObject(
792 self.handle,
793 JobObjectExtendedLimitInformation,
794 std::ptr::from_mut(&mut limits).cast(),
795 std::mem::size_of_val(&limits) as u32,
796 std::ptr::null_mut(),
797 )
798 };
799 (queried != 0).then_some(limits.PeakProcessMemoryUsed as u64)
800 }
801}
802
803#[cfg(windows)]
806unsafe impl Send for MemoryJob {}
807
808#[cfg(windows)]
809impl Drop for MemoryJob {
810 fn drop(&mut self) {
811 unsafe {
813 windows_sys::Win32::Foundation::CloseHandle(self.handle);
814 }
815 }
816}
817
818pub(super) struct Process {
820 child: Child,
821 stdin: Option<ChildStdin>,
822 port: u16,
823 stderr: std::sync::Arc<Mutex<StderrTail>>,
826 stderr_reader: Option<std::thread::JoinHandle<()>>,
827 secrets: Vec<String>,
829 killed: bool,
832 #[cfg(windows)]
835 job: Option<MemoryJob>,
836}
837
838impl Process {
839 fn exit_report(&mut self) -> String {
843 let (status, failed) = match self.child.try_wait() {
844 Ok(Some(status)) => (status.to_string(), !status.success()),
845 _ => ("still running".to_owned(), false),
846 };
847 let mut report = format!("status {status}");
848 if self.killed {
849 report.push_str(" (stopped by the supervisor)");
850 }
851 #[cfg(windows)]
852 if let Some(job) = &self.job {
853 if let Some(peak) = job.peak() {
854 let mib = |bytes: u64| bytes / (1024 * 1024);
855 if job.limit > 0 {
856 report.push_str(&format!(
857 ", peak memory {} MiB of its {} MiB budget",
858 mib(peak),
859 mib(job.limit)
860 ));
861 if peak.saturating_add(16 * 1024 * 1024) >= job.limit {
862 report.push_str(
863 " (it reached the budget; raise it with LEAN_CTX_COCKPIT_MEMORY_MB)",
864 );
865 } else if failed && !self.killed {
866 report.push_str(
869 " (an allocation beyond the budget may have failed; raise it with LEAN_CTX_COCKPIT_MEMORY_MB)",
870 );
871 }
872 } else {
873 report.push_str(&format!(", peak memory {} MiB", mib(peak)));
874 }
875 }
876 }
877 #[cfg(not(windows))]
878 let _ = failed;
879 let mut open_end = false;
880 if let Some(reader) = self.stderr_reader.take() {
881 let settle = Instant::now() + STDERR_SETTLE;
882 while !reader.is_finished() && Instant::now() < settle {
883 std::thread::sleep(Duration::from_millis(10));
884 }
885 if reader.is_finished() {
886 let _ = reader.join();
887 } else {
888 open_end = true;
891 }
892 }
893 let tail = self.stderr.lock().unwrap_or_else(PoisonError::into_inner);
894 let stderr = stderr_report(&tail.bytes, tail.cut, open_end, &self.secrets);
895 if !stderr.is_empty() {
896 report.push_str(&format!(
897 "; last stderr (redacted, at most {STDERR_TAIL} bytes):\n{stderr}"
898 ));
899 }
900 report
901 }
902
903 pub(super) fn stop(&mut self, grace: Duration) -> bool {
906 drop(self.stdin.take());
907 let deadline = Instant::now() + grace;
908 loop {
909 match self.child.try_wait() {
910 Ok(Some(_)) => return true,
911 Ok(None) if Instant::now() < deadline => {
912 std::thread::sleep(Duration::from_millis(20));
913 }
914 _ => {
915 let _ = self.child.kill();
916 let _ = self.child.wait();
917 self.killed = true;
918 return false;
919 }
920 }
921 }
922 }
923
924 fn running(&mut self) -> bool {
925 matches!(self.child.try_wait(), Ok(None))
926 }
927}
928
929impl Drop for Process {
930 fn drop(&mut self) {
931 self.stop(EXIT_GRACE);
932 }
933}
934
935pub(super) fn handshake(
938 mut command: Command,
939 start: &[u8],
940 secrets: Vec<String>,
941 deadline: Duration,
942) -> std::result::Result<Process, CockpitUnavailable> {
943 command
944 .stdin(Stdio::piped())
945 .stdout(Stdio::piped())
946 .stderr(Stdio::piped());
949 let child = command.spawn().map_err(|error| {
950 tracing::warn!("cockpit not started: the process could not be spawned: {error}");
951 CockpitUnavailable::StartFailed
952 })?;
953 #[cfg(windows)]
954 let job = {
955 let budget = memory_budget(std::env::var("LEAN_CTX_COCKPIT_MEMORY_MB").ok().as_deref());
956 match MemoryJob::assign(&child, budget) {
957 Ok(job) => Some(job),
958 Err(error) => {
959 tracing::warn!(
960 "cockpit runs without its memory budget, the job could not be set up: {error}"
961 );
962 None
963 }
964 }
965 };
966 let mut process = Process {
967 child,
968 stdin: None,
969 port: 0,
970 stderr: std::sync::Arc::default(),
971 stderr_reader: None,
972 secrets,
973 killed: false,
974 #[cfg(windows)]
975 job,
976 };
977 if let Some(mut stderr) = process.child.stderr.take() {
978 let tail = std::sync::Arc::clone(&process.stderr);
979 process.stderr_reader = std::thread::Builder::new()
980 .name("cockpit-stderr".to_owned())
981 .spawn(move || {
982 let mut chunk = [0_u8; 1024];
983 while let Ok(read @ 1..) = stderr.read(&mut chunk) {
984 let mut tail = tail.lock().unwrap_or_else(PoisonError::into_inner);
985 keep_tail(&mut tail, &chunk[..read], STDERR_TAIL);
986 }
987 })
988 .ok();
989 }
990 let (Some(mut stdin), Some(stdout)) = (process.child.stdin.take(), process.child.stdout.take())
991 else {
992 process.stop(Duration::ZERO);
993 return Err(CockpitUnavailable::StartFailed);
994 };
995 if stdin.write_all(start).and_then(|()| stdin.flush()).is_err() {
996 process.stop(Duration::ZERO);
997 return Err(CockpitUnavailable::StartFailed);
998 }
999 process.stdin = Some(stdin);
1000 let (sender, receiver) = mpsc::sync_channel(1);
1001 let reader = std::thread::Builder::new()
1002 .name("cockpit-output".to_owned())
1003 .spawn(move || {
1004 let mut output = BufReader::new(stdout);
1005 let mut line = Vec::new();
1006 let read = (&mut output)
1007 .take(MAX_PORT_LINE)
1008 .read_until(b'\n', &mut line);
1009 let _ = sender.send(read.ok().map(|_| line));
1010 let _ = std::io::copy(&mut output, &mut std::io::sink());
1012 });
1013 let port = reader
1014 .ok()
1015 .and_then(|_| receiver.recv_timeout(deadline).ok().flatten())
1016 .and_then(|line| listening(&line));
1017 if let Some(port) = port {
1018 process.port = port;
1019 Ok(process)
1020 } else {
1021 let exited = process.child.try_wait().ok().flatten().is_some();
1022 process.stop(Duration::ZERO);
1023 let report = process.exit_report();
1024 if exited {
1025 tracing::warn!(
1026 "cockpit not started: it exited before naming its loopback port: {report}"
1027 );
1028 } else {
1029 tracing::warn!(
1030 "cockpit not started: it did not name its loopback port within {} s: {report}",
1031 deadline.as_secs()
1032 );
1033 }
1034 Err(CockpitUnavailable::StartFailed)
1035 }
1036}
1037
1038fn listening(line: &[u8]) -> Option<u16> {
1040 #[derive(Deserialize)]
1041 #[serde(deny_unknown_fields)]
1042 struct Listening {
1043 listening: u16,
1044 }
1045 if line.last() != Some(&b'\n') {
1046 return None;
1047 }
1048 serde_json::from_slice::<Listening>(line)
1049 .ok()
1050 .map(|listening| listening.listening)
1051 .filter(|port| *port != 0)
1052}
1053
1054struct Running {
1055 process: Process,
1056 prepared: Option<super::health::Prepared>,
1058 cockpit_token: String,
1059 launch: [u8; 32],
1060 started: Instant,
1061}
1062
1063impl Drop for Running {
1064 fn drop(&mut self) {
1065 self.process.stop(EXIT_GRACE);
1066 if let Some(prepared) = self.prepared.take() {
1067 let _ = prepared.close();
1068 }
1069 }
1070}
1071
1072struct State {
1073 running: Option<Running>,
1074 failures: usize,
1076 retry_at: Option<Instant>,
1077 last_failure: CockpitUnavailable,
1078}
1079
1080static STATE: Mutex<State> = Mutex::new(State {
1081 running: None,
1082 failures: 0,
1083 retry_at: None,
1084 last_failure: CockpitUnavailable::StartFailed,
1085});
1086
1087fn launch_key(launch: &CockpitLaunch) -> [u8; 32] {
1088 let mut hasher = blake3::Hasher::new();
1089 hasher.update(&launch.engine_port.to_le_bytes());
1090 hasher.update(&(launch.engine_token.len() as u64).to_le_bytes());
1091 hasher.update(launch.engine_token.as_bytes());
1092 hasher.update(launch.project_root.as_os_str().as_encoded_bytes());
1093 *hasher.finalize().as_bytes()
1094}
1095
1096pub fn cockpit_endpoint(
1099 launch: &CockpitLaunch,
1100) -> std::result::Result<CockpitEndpoint, CockpitUnavailable> {
1101 let key = launch_key(launch);
1102 let mut state = STATE.lock().unwrap_or_else(PoisonError::into_inner);
1103 let now = Instant::now();
1104 if let Some(running) = state.running.as_mut() {
1105 if running.process.running() {
1106 if running.launch == key {
1107 return Ok(CockpitEndpoint {
1108 port: running.process.port,
1109 cockpit_token: running.cockpit_token.clone(),
1110 });
1111 }
1112 state.running = None;
1114 } else {
1115 let stable = running.started.elapsed() >= STABLE;
1116 let report = running.process.exit_report();
1117 state.running = None;
1118 if stable {
1119 state.failures = 0;
1120 }
1121 tracing::warn!("cockpit exited ({report}); restarting after backoff");
1122 fail(&mut state, CockpitUnavailable::StartFailed, now);
1123 }
1124 }
1125 if state.retry_at.is_some_and(|at| now < at) {
1126 return Err(state.last_failure);
1127 }
1128 match start(launch, key) {
1129 Ok(running) => {
1130 let endpoint = CockpitEndpoint {
1131 port: running.process.port,
1132 cockpit_token: running.cockpit_token.clone(),
1133 };
1134 state.retry_at = None;
1135 state.running = Some(running);
1136 Ok(endpoint)
1137 }
1138 Err(
1140 reason @ (CockpitUnavailable::NotInstalled
1141 | CockpitUnavailable::Disabled
1142 | CockpitUnavailable::SourceBuild),
1143 ) => Err(reason),
1144 Err(reason) => {
1145 tracing::warn!("cockpit not started: {}", reason.as_str());
1146 fail(&mut state, reason, now);
1147 Err(reason)
1148 }
1149 }
1150}
1151
1152fn fail(state: &mut State, reason: CockpitUnavailable, now: Instant) {
1153 let wait = RESTART_BACKOFF[state.failures.min(RESTART_BACKOFF.len() - 1)];
1154 state.failures = state.failures.saturating_add(1);
1155 state.retry_at = Some(now + wait);
1156 state.last_failure = reason;
1157}
1158
1159pub fn retire() {
1162 let mut state = STATE.lock().unwrap_or_else(PoisonError::into_inner);
1163 state.running = None;
1164 state.failures = 0;
1165 state.retry_at = None;
1166}
1167
1168fn start(
1169 launch: &CockpitLaunch,
1170 key: [u8; 32],
1171) -> std::result::Result<Running, CockpitUnavailable> {
1172 import_bundled();
1173 let (root, package) = match authenticated() {
1174 Err(CockpitUnavailable::NotInstalled)
1175 if bootstrap::cockpit_channel().ok().flatten().is_none() =>
1176 {
1177 return Err(CockpitUnavailable::SourceBuild);
1178 }
1179 other => other?,
1180 };
1181 let mut token = [0_u8; 32];
1182 getrandom::fill(&mut token).map_err(|_| CockpitUnavailable::StartFailed)?;
1183 let cockpit_token = hex::encode(token);
1184 let start_line = start_line(launch, &cockpit_token).ok_or(CockpitUnavailable::StartFailed)?;
1185 let (prepared, command) = super::health::prepare_binary(&package.binary, &root, EXECUTABLE)
1186 .map_err(|error| {
1187 tracing::warn!("cockpit not started: its private copy was not prepared ({error:?})");
1188 CockpitUnavailable::StartFailed
1189 })?;
1190 match handshake(
1191 command,
1192 &start_line,
1193 vec![cockpit_token.clone(), launch.engine_token.clone()],
1194 HANDSHAKE,
1195 ) {
1196 Ok(process) => Ok(Running {
1197 process,
1198 prepared: Some(prepared),
1199 cockpit_token,
1200 launch: key,
1201 started: Instant::now(),
1202 }),
1203 Err(reason) => {
1204 let _ = prepared.close();
1205 Err(reason)
1206 }
1207 }
1208}
1209
1210fn start_line(launch: &CockpitLaunch, cockpit_token: &str) -> Option<Vec<u8>> {
1212 let engine_exe = std::env::current_exe().ok()?;
1213 let data_dir = crate::core::data_dir::resolve_data_dir().ok()?;
1216 let state_dir = crate::core::paths::state_dir().ok()?;
1217 if !data_dir.is_absolute() || !state_dir.is_absolute() {
1218 return None;
1219 }
1220 let home_dir = dirs::home_dir()
1222 .filter(|home| home.is_absolute())
1223 .and_then(|home| home.to_str().map(str::to_owned));
1224 let cache_dir = crate::core::paths::cache_dir()
1226 .ok()
1227 .filter(|cache| cache.is_absolute())
1228 .and_then(|cache| cache.to_str().map(str::to_owned));
1229 let config_dir = crate::core::paths::config_dir_read_only()
1232 .ok()
1233 .filter(|config| config.is_absolute())
1234 .and_then(|config| config.to_str().map(str::to_owned));
1235 let search_path = std::env::var("PATH").ok();
1236 let mut line = serde_json::to_vec(&serde_json::json!({
1237 "home_dir": home_dir,
1238 "engine_cache_dir": cache_dir,
1239 "engine_config_dir": config_dir,
1240 "search_path": search_path,
1241 "cockpit_token": cockpit_token,
1242 "engine_url": format!("http://127.0.0.1:{}", launch.engine_port),
1243 "engine_token": launch.engine_token,
1244 "engine_exe": engine_exe.to_str()?,
1245 "project_root": launch.project_root.to_str()?,
1246 "data_dir": data_dir.to_str()?,
1247 "engine_state_dir": state_dir.to_str()?,
1248 "engine_version": env!("CARGO_PKG_VERSION"),
1249 }))
1250 .ok()?;
1251 line.push(b'\n');
1252 Some(line)
1253}
1254
1255#[cfg(all(test, unix))]
1256#[path = "cockpit_tests.rs"]
1257mod tests;
1258
1259#[cfg(all(test, windows))]
1260mod windows_tests {
1261 use super::*;
1262
1263 #[test]
1264 fn the_memory_job_reports_its_peak_and_ends_the_cockpit_when_closed() {
1265 let mut child = Command::new("cmd")
1266 .args(["/C", "ping -n 30 127.0.0.1 >NUL"])
1267 .stdout(Stdio::null())
1268 .spawn()
1269 .unwrap();
1270 let job = MemoryJob::assign(&child, memory_budget(Some("256"))).unwrap();
1271 assert_eq!(job.limit, 256 * 1024 * 1024);
1272 assert!(job.peak().is_some_and(|peak| peak > 0));
1273 assert!(child.try_wait().unwrap().is_none());
1274 drop(job);
1275 let deadline = Instant::now() + Duration::from_secs(10);
1276 while child.try_wait().unwrap().is_none() {
1277 assert!(Instant::now() < deadline, "closing the job ends the child");
1278 std::thread::sleep(Duration::from_millis(20));
1279 }
1280 }
1281}