1#[cfg(any(target_os = "macos", target_os = "linux"))]
2use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream};
3#[cfg(any(target_os = "macos", target_os = "linux"))]
4use std::path::PathBuf;
5#[cfg(any(target_os = "macos", target_os = "linux"))]
6use std::time::{Duration, Instant};
7
8#[cfg(target_os = "macos")]
9const PLIST_LABEL: &str = "com.leanctx.proxy";
10#[cfg(target_os = "linux")]
11const SYSTEMD_SERVICE: &str = "lean-ctx-proxy";
12
13pub(crate) fn recorded_proxy_pid() -> Option<u32> {
18 let port = crate::core::proxy_endpoint::default_port();
19 if !crate::daemon_autostart::controls_user_services()
24 && port == crate::core::proxy_endpoint::uid_based_port()
25 {
26 return None;
27 }
28 health_proxy_pid(port)
29}
30
31#[must_use]
36pub fn health_proxy_pid(port: u16) -> Option<u32> {
37 let response = ureq::get(&format!("http://127.0.0.1:{port}/health"))
38 .config()
39 .timeout_global(Some(std::time::Duration::from_millis(500)))
40 .build()
41 .call()
42 .ok()?;
43 let body = response.into_body().read_to_string().ok()?;
44 proxy_pid_from_health(&body)
45}
46
47fn proxy_pid_from_health(body: &str) -> Option<u32> {
48 let health: serde_json::Value = serde_json::from_str(body).ok()?;
49 if health.get("status").and_then(serde_json::Value::as_str) != Some("ok")
50 || !health_identifies_lean_ctx_proxy(body)
51 {
52 return None;
53 }
54 let pid = u32::try_from(health.get("pid")?.as_u64()?).ok()?;
55 (pid > 0).then_some(pid)
56}
57
58fn health_identifies_lean_ctx_proxy(body: &str) -> bool {
59 serde_json::from_str::<serde_json::Value>(body)
60 .ok()
61 .and_then(|health| health.get("service")?.as_str().map(str::to_owned))
62 .is_some_and(|service| service == "lean-ctx-proxy")
63}
64
65#[must_use]
69pub fn proxy_on_port(port: u16) -> Option<crate::ipc::process::ServiceProcess> {
70 use crate::ipc::process::{RecordedPid, ServiceKind, ServiceSweep, find_service_processes};
71 let pid = health_proxy_pid(port)?;
72 find_service_processes(
73 &[RecordedPid::bare(pid)],
74 ServiceSweep::Only(ServiceKind::Proxy),
75 )
76 .into_iter()
77 .next()
78}
79
80#[cfg(any(target_os = "macos", target_os = "linux"))]
81fn port_is_open(port: u16) -> bool {
82 let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port);
83 TcpStream::connect_timeout(&addr, Duration::from_millis(150)).is_ok()
84}
85
86#[cfg(any(target_os = "macos", target_os = "linux"))]
93fn release_proxy_port(port: u16, quiet: bool) -> bool {
94 if !port_is_open(port) {
95 return true;
96 }
97
98 if !crate::daemon_autostart::controls_user_services()
102 && port == crate::core::proxy_endpoint::uid_based_port()
103 {
104 if !quiet {
105 eprintln!(
106 " Refusing managed proxy startup: port {port} belongs to the default install."
107 );
108 }
109 return false;
110 }
111
112 let Some(proxy) = proxy_on_port(port) else {
116 if !quiet {
117 eprintln!(
118 " Refusing managed proxy startup: port {port} is occupied by an unidentified service."
119 );
120 }
121 return false;
122 };
123 let pid = proxy.pid;
124
125 proxy.signal(crate::ipc::process::StopSignal::Terminate);
126 let graceful_deadline = Instant::now() + Duration::from_secs(2);
127 while Instant::now() < graceful_deadline {
128 if !proxy.is_running() && !port_is_open(port) {
129 if !quiet {
130 eprintln!(
131 " Handed port {port} from standalone proxy PID {pid} to managed service."
132 );
133 }
134 return true;
135 }
136 std::thread::sleep(Duration::from_millis(50));
137 }
138
139 if proxy.is_running() {
140 proxy.signal(crate::ipc::process::StopSignal::Kill);
141 }
142 let force_deadline = Instant::now() + Duration::from_secs(1);
143 while Instant::now() < force_deadline {
144 if !port_is_open(port) {
145 if !quiet {
146 eprintln!(
147 " Handed port {port} from standalone proxy PID {pid} to managed service."
148 );
149 }
150 return true;
151 }
152 std::thread::sleep(Duration::from_millis(50));
153 }
154
155 if !quiet {
156 eprintln!(" Refusing managed proxy startup: port {port} was not released by PID {pid}.");
157 }
158 false
159}
160
161pub fn install(port: u16, quiet: bool) -> bool {
162 let binary = find_binary();
163 install_with_binary(&binary, port, quiet)
164}
165
166pub fn install_with_binary(binary: &str, port: u16, quiet: bool) -> bool {
172 if !crate::daemon_autostart::controls_user_services() {
173 if !quiet {
174 eprintln!(" {}", crate::daemon_autostart::not_this_instance_message());
175 }
176 return false;
177 }
178 if binary.is_empty() {
179 if !quiet {
180 tracing::error!("Cannot find lean-ctx binary for autostart");
181 }
182 return false;
183 }
184
185 #[cfg(target_os = "macos")]
186 {
187 install_launchagent(binary, port, quiet)
188 }
189
190 #[cfg(target_os = "linux")]
191 {
192 install_systemd(binary, port, quiet)
193 }
194
195 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
196 {
197 let _ = (binary, quiet);
198 println!(" Autostart not supported on this platform");
199 println!(" Run manually: lean-ctx proxy start --port={port}");
200 false
201 }
202}
203
204pub fn stop() {
209 if !crate::daemon_autostart::controls_user_services() {
210 return;
211 }
212 #[cfg(target_os = "macos")]
213 {
214 let plist_path = launchagent_path();
215 if plist_path.exists() {
216 crate::core::launchd::bootout(PLIST_LABEL, &plist_path);
217 }
218 }
219
220 #[cfg(target_os = "linux")]
221 {
222 let _ = std::process::Command::new("systemctl")
223 .args(["--user", "stop", SYSTEMD_SERVICE])
224 .output();
225 }
226}
227
228pub fn start() -> bool {
229 start_on_port(crate::core::proxy_endpoint::default_port())
230}
231
232pub fn start_on_port(port: u16) -> bool {
236 if !crate::daemon_autostart::controls_user_services() {
237 return false;
238 }
239 #[cfg(target_os = "macos")]
240 {
241 let plist_path = launchagent_path();
242 if plist_path.exists() {
243 crate::core::launchd::bootout(PLIST_LABEL, &plist_path);
244 if !release_proxy_port(port, false) {
245 return false;
246 }
247 crate::daemon_autostart::repin_launchagent(&plist_path);
250 return crate::core::launchd::bootstrap(PLIST_LABEL, &plist_path);
251 }
252 false
253 }
254
255 #[cfg(target_os = "linux")]
256 {
257 let _ = std::process::Command::new("systemctl")
258 .args(["--user", "stop", SYSTEMD_SERVICE])
259 .output();
260 if release_proxy_port(port, false) {
261 std::process::Command::new("systemctl")
262 .args(["--user", "start", SYSTEMD_SERVICE])
263 .status()
264 .is_ok_and(|status| status.success())
265 } else {
266 false
267 }
268 }
269
270 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
271 {
272 let _ = port;
273 false
274 }
275}
276
277pub fn uninstall(quiet: bool) {
280 if !crate::daemon_autostart::controls_user_services() {
281 if !quiet {
282 println!(" {}", crate::daemon_autostart::not_this_instance_message());
283 }
284 return;
285 }
286 #[cfg(target_os = "macos")]
287 uninstall_launchagent(quiet);
288
289 #[cfg(target_os = "linux")]
290 uninstall_systemd(quiet);
291}
292
293pub fn is_supported() -> bool {
297 cfg!(any(target_os = "macos", target_os = "linux"))
298}
299
300pub fn is_installed() -> bool {
303 if !crate::daemon_autostart::controls_user_services() {
304 return false;
305 }
306 #[cfg(target_os = "macos")]
307 {
308 launchagent_path().exists()
309 }
310 #[cfg(target_os = "linux")]
311 {
312 systemd_path().exists()
313 }
314 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
315 {
316 false
317 }
318}
319
320pub fn is_loaded() -> bool {
324 if !crate::daemon_autostart::controls_user_services() {
325 return false;
326 }
327 #[cfg(target_os = "macos")]
328 {
329 is_installed() && crate::core::launchd::is_loaded(PLIST_LABEL)
330 }
331 #[cfg(target_os = "linux")]
332 {
333 is_installed()
334 && std::process::Command::new("systemctl")
335 .args(["--user", "is-active", "--quiet", SYSTEMD_SERVICE])
336 .status()
337 .is_ok_and(|status| status.success())
338 }
339 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
340 {
341 false
342 }
343}
344
345pub fn status() {
346 if !crate::daemon_autostart::controls_user_services() {
347 println!(" {}", crate::daemon_autostart::not_this_instance_message());
348 return;
349 }
350 #[cfg(target_os = "macos")]
351 {
352 let plist_path = launchagent_path();
353 if plist_path.exists() {
354 println!(" LaunchAgent: installed at {}", plist_path.display());
355 if crate::core::launchd::is_loaded(PLIST_LABEL) {
356 println!(" Status: loaded");
357 } else {
358 println!(" Status: not loaded (run: lean-ctx proxy start)");
359 }
360 } else {
361 println!(" LaunchAgent: not installed");
362 }
363 }
364
365 #[cfg(target_os = "linux")]
366 {
367 let service_path = systemd_path();
368 if service_path.exists() {
369 println!(" systemd user service: installed");
370 let output = std::process::Command::new("systemctl")
371 .args(["--user", "is-active", SYSTEMD_SERVICE])
372 .output();
373 match output {
374 Ok(o) => {
375 let state = String::from_utf8_lossy(&o.stdout).trim().to_string();
376 println!(" Status: {state}");
377 }
378 Err(_) => println!(" Status: unknown"),
379 }
380 } else {
381 println!(" systemd service: not installed");
382 }
383 }
384
385 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
386 {
387 println!(" Autostart not available on this platform");
388 }
389}
390
391#[cfg(target_os = "macos")]
392fn launchagent_path() -> PathBuf {
393 dirs::home_dir()
394 .unwrap_or_else(|| PathBuf::from("/tmp"))
395 .join("Library/LaunchAgents")
396 .join(format!("{PLIST_LABEL}.plist"))
397}
398
399#[cfg(target_os = "macos")]
400fn install_launchagent(binary: &str, port: u16, quiet: bool) -> bool {
401 let plist_dir = dirs::home_dir()
402 .unwrap_or_else(|| PathBuf::from("/tmp"))
403 .join("Library/LaunchAgents");
404 let _ = std::fs::create_dir_all(&plist_dir);
405
406 let plist_path = plist_dir.join(format!("{PLIST_LABEL}.plist"));
407 crate::core::launchd::bootout(PLIST_LABEL, &plist_path);
411 if !release_proxy_port(port, quiet) {
412 return false;
413 }
414 let log_dir = crate::core::paths::state_dir()
418 .unwrap_or_else(|_| std::env::temp_dir().join("lean-ctx"))
419 .join("logs");
420 let _ = std::fs::create_dir_all(&log_dir);
421
422 let port_arg = format!("--port={port}");
426 let program_args = crate::core::tcc_guard_sandbox::program_args_xml(
427 &crate::core::tcc_guard_sandbox::launchd_program_args(
428 binary,
429 &["proxy", "start", &port_arg],
430 ),
431 " ",
432 );
433 let bundle_ids = crate::core::tcc_guard_sandbox::associated_bundle_ids_xml(" ");
434
435 let env_vars = crate::core::tcc_guard_sandbox::pinned_layout_env_xml();
442
443 let plist = format!(
444 r#"<?xml version="1.0" encoding="UTF-8"?>
445<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
446<plist version="1.0">
447<dict>
448 <key>Label</key>
449 <string>{PLIST_LABEL}</string>
450 <key>ProgramArguments</key>
451 <array>
452{program_args}
453 </array>
454{bundle_ids}{env_vars} <key>RunAtLoad</key>
455 <true/>
456 <key>KeepAlive</key>
457 <true/>
458 <key>StandardOutPath</key>
459 <string>{stdout}</string>
460 <key>StandardErrorPath</key>
461 <string>{stderr}</string>
462</dict>
463</plist>"#,
464 stdout = log_dir.join("proxy.stdout.log").display(),
465 stderr = log_dir.join("proxy.stderr.log").display(),
466 );
467
468 let _ = std::fs::write(&plist_path, &plist);
469
470 let ok = crate::core::launchd::bootstrap(PLIST_LABEL, &plist_path);
471
472 if !quiet {
473 if ok {
474 println!(" Installed LaunchAgent: {}", plist_path.display());
475 println!(" Proxy will start on login and restart if stopped");
476 } else {
477 println!(" Created LaunchAgent at {}", plist_path.display());
478 println!(" Load reported a problem; check: launchctl print {PLIST_LABEL}");
479 }
480 }
481 ok
482}
483
484#[cfg(target_os = "macos")]
485fn uninstall_launchagent(quiet: bool) {
486 let plist_path = launchagent_path();
487 if !plist_path.exists() {
488 if !quiet {
489 println!(" LaunchAgent not installed, nothing to remove");
490 }
491 return;
492 }
493
494 crate::core::launchd::bootout(PLIST_LABEL, &plist_path);
495
496 let _ = std::fs::remove_file(&plist_path);
497 if !quiet {
498 println!(" Removed LaunchAgent: {}", plist_path.display());
499 }
500}
501
502#[cfg(target_os = "linux")]
503fn systemd_path() -> PathBuf {
504 dirs::home_dir()
505 .unwrap_or_else(|| PathBuf::from("/tmp"))
506 .join(".config/systemd/user")
507 .join(format!("{SYSTEMD_SERVICE}.service"))
508}
509
510#[cfg(target_os = "linux")]
511fn install_systemd(binary: &str, port: u16, quiet: bool) -> bool {
512 let service_dir = dirs::home_dir()
513 .unwrap_or_else(|| PathBuf::from("/tmp"))
514 .join(".config/systemd/user");
515 let _ = std::fs::create_dir_all(&service_dir);
516
517 let service_path = service_dir.join(format!("{SYSTEMD_SERVICE}.service"));
518
519 let _ = std::process::Command::new("systemctl")
520 .args(["--user", "stop", SYSTEMD_SERVICE])
521 .output();
522 if !release_proxy_port(port, quiet) {
523 return false;
524 }
525
526 let unit = format!(
527 r"[Unit]
528Description=lean-ctx API Proxy
529After=network.target
530StartLimitIntervalSec=300
531StartLimitBurst=5
532
533[Service]
534Type=simple
535ExecStart={binary} proxy start --port={port}
536Restart=on-failure
537RestartSec=5
538StandardOutput=journal
539StandardError=journal
540Environment=RUST_LOG=info
541
542[Install]
543WantedBy=default.target
544"
545 );
546
547 let _ = std::fs::write(&service_path, &unit);
548
549 let _ = std::process::Command::new("systemctl")
550 .args(["--user", "daemon-reload"])
551 .output();
552
553 let result = std::process::Command::new("systemctl")
554 .args(["--user", "enable", "--now", SYSTEMD_SERVICE])
555 .output();
556
557 if !quiet {
558 match &result {
559 Ok(o) if o.status.success() => {
560 println!(" Installed systemd user service: {SYSTEMD_SERVICE}");
561 println!(" Proxy will start on login and restart if stopped");
562 }
563 Ok(o) => {
564 let err = String::from_utf8_lossy(&o.stderr);
565 println!(" Created service file but enable failed: {err}");
566 }
567 Err(e) => {
568 println!(" Created service file at {}", service_path.display());
569 println!(" Could not enable: {e}");
570 }
571 }
572 }
573 result.is_ok_and(|output| output.status.success())
574}
575
576#[cfg(target_os = "linux")]
577fn uninstall_systemd(quiet: bool) {
578 let service_path = systemd_path();
579 if !service_path.exists() {
580 if !quiet {
581 println!(" systemd service not installed, nothing to remove");
582 }
583 return;
584 }
585
586 let _ = std::process::Command::new("systemctl")
587 .args(["--user", "stop", SYSTEMD_SERVICE])
588 .output();
589 let _ = std::process::Command::new("systemctl")
590 .args(["--user", "disable", SYSTEMD_SERVICE])
591 .output();
592 let _ = std::fs::remove_file(&service_path);
593 let _ = std::process::Command::new("systemctl")
594 .args(["--user", "daemon-reload"])
595 .output();
596
597 if !quiet {
598 println!(" Removed systemd service: {SYSTEMD_SERVICE}");
599 }
600}
601
602pub fn find_binary() -> String {
603 crate::core::portable_binary::resolve_portable_binary()
604}
605
606#[cfg(test)]
607mod tests {
608 use super::{health_identifies_lean_ctx_proxy, proxy_pid_from_health};
609 #[cfg(any(target_os = "macos", target_os = "linux"))]
610 use super::{port_is_open, release_proxy_port};
611 #[cfg(any(target_os = "macos", target_os = "linux"))]
612 use std::io::{Read, Write};
613 #[cfg(any(target_os = "macos", target_os = "linux"))]
614 use std::net::TcpListener;
615
616 #[test]
617 fn health_pid_parser_accepts_only_well_formed_health() {
618 assert_eq!(
619 proxy_pid_from_health(r#"{"status":"ok","service":"lean-ctx-proxy","pid":4242}"#),
620 Some(4242)
621 );
622 assert_eq!(proxy_pid_from_health(r#"{"status":"ok","pid":4242}"#), None);
625 assert_eq!(
626 proxy_pid_from_health(r#"{"status":"ok","service":"other","pid":4242}"#),
627 None
628 );
629 assert_eq!(
630 proxy_pid_from_health(r#"{"status":"busy","service":"lean-ctx-proxy","pid":4242}"#),
631 None
632 );
633 assert_eq!(
634 proxy_pid_from_health(r#"{"status":"ok","service":"lean-ctx-proxy","pid":0}"#),
635 None
636 );
637 assert_eq!(proxy_pid_from_health(r#"{"status":"ok"}"#), None);
638 assert_eq!(proxy_pid_from_health("not json"), None);
639 assert!(health_identifies_lean_ctx_proxy(
640 r#"{"status":"ok","service":"lean-ctx-proxy","pid":4242}"#
641 ));
642 assert!(!health_identifies_lean_ctx_proxy(
643 r#"{"status":"ok","pid":4242}"#
644 ));
645 }
646
647 #[test]
648 #[cfg(any(target_os = "macos", target_os = "linux"))]
649 fn managed_handoff_fails_closed_for_unidentified_listener() {
650 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
651 let port = listener.local_addr().unwrap().port();
652 let server = std::thread::spawn(move || {
653 for _ in 0..2 {
654 let (mut stream, _) = listener.accept().unwrap();
655 stream
656 .set_read_timeout(Some(std::time::Duration::from_secs(1)))
657 .unwrap();
658 let mut request = [0_u8; 512];
659 if stream.read(&mut request).unwrap_or(0) > 0 {
660 let body = r#"{"status":"ok"}"#;
661 write!(
662 stream,
663 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
664 body.len()
665 )
666 .unwrap();
667 }
668 }
669 });
670
671 assert!(!release_proxy_port(port, true));
672 server.join().unwrap();
673 }
674
675 #[cfg(unix)]
676 struct ChildGuard(std::process::Child);
677
678 #[cfg(unix)]
679 impl Drop for ChildGuard {
680 fn drop(&mut self) {
681 let _ = self.0.kill();
682 let _ = self.0.wait();
683 }
684 }
685
686 #[test]
690 #[cfg(unix)]
691 fn managed_handoff_never_signals_an_unverified_health_pid() {
692 let reservation = TcpListener::bind("127.0.0.1:0").unwrap();
693 let port = reservation.local_addr().unwrap().port();
694 drop(reservation);
695
696 let child = std::process::Command::new(std::env::current_exe().unwrap())
697 .args([
698 "--ignored",
699 "--exact",
700 "proxy_autostart::tests::managed_handoff_test_child",
701 "--nocapture",
702 ])
703 .env("LEAN_CTX_HANDOFF_TEST_PORT", port.to_string())
704 .spawn()
705 .unwrap();
706 let mut child = ChildGuard(child);
707
708 let ready_deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
709 while !port_is_open(port) && std::time::Instant::now() < ready_deadline {
710 std::thread::sleep(std::time::Duration::from_millis(25));
711 }
712 assert!(port_is_open(port), "test proxy did not bind port {port}");
713 assert!(!release_proxy_port(port, true));
714 assert!(
715 child.0.try_wait().unwrap().is_none(),
716 "an unverified /health PID must never be signalled"
717 );
718 assert!(port_is_open(port));
719 }
720
721 #[test]
722 #[ignore = "helper process for managed_handoff_never_signals_an_unverified_health_pid"]
723 #[cfg(unix)]
724 fn managed_handoff_test_child() {
725 let port: u16 = std::env::var("LEAN_CTX_HANDOFF_TEST_PORT")
726 .unwrap()
727 .parse()
728 .unwrap();
729 let listener = TcpListener::bind(("127.0.0.1", port)).unwrap();
730 loop {
731 let (mut stream, _) = listener.accept().unwrap();
732 stream
733 .set_read_timeout(Some(std::time::Duration::from_secs(1)))
734 .unwrap();
735 let mut request = [0_u8; 512];
736 if stream.read(&mut request).unwrap_or(0) > 0 {
737 let body = format!(
738 r#"{{"status":"ok","service":"lean-ctx-proxy","pid":{}}}"#,
739 std::process::id()
740 );
741 write!(
742 stream,
743 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
744 body.len()
745 )
746 .unwrap();
747 }
748 }
749 }
750}