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
13#[cfg(any(target_os = "macos", target_os = "linux", test))]
14fn proxy_pid_from_health(body: &str) -> Option<u32> {
15 let health: serde_json::Value = serde_json::from_str(body).ok()?;
16 if health.get("status").and_then(serde_json::Value::as_str) != Some("ok") {
17 return None;
18 }
19 let pid = u32::try_from(health.get("pid")?.as_u64()?).ok()?;
20 (pid > 0).then_some(pid)
21}
22
23#[cfg(any(target_os = "macos", target_os = "linux", test))]
24fn health_identifies_lean_ctx_proxy(body: &str) -> bool {
25 serde_json::from_str::<serde_json::Value>(body)
26 .ok()
27 .and_then(|health| health.get("service")?.as_str().map(str::to_owned))
28 .is_some_and(|service| service == "lean-ctx-proxy")
29}
30
31#[cfg(any(target_os = "macos", target_os = "linux"))]
32fn port_is_open(port: u16) -> bool {
33 let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port);
34 TcpStream::connect_timeout(&addr, Duration::from_millis(150)).is_ok()
35}
36
37#[cfg(any(target_os = "macos", target_os = "linux"))]
38fn proxy_pid_on_port(port: u16) -> Option<u32> {
39 let health_url = format!("http://127.0.0.1:{port}/health");
40 let response = ureq::get(&health_url)
41 .config()
42 .timeout_global(Some(Duration::from_millis(500)))
43 .build()
44 .call()
45 .ok()?;
46 let body = response.into_body().read_to_string().ok()?;
47 let pid = proxy_pid_from_health(&body)?;
48 (health_identifies_lean_ctx_proxy(&body)
49 || crate::ipc::process::find_pids_by_name("lean-ctx").contains(&pid))
50 .then_some(pid)
51}
52
53#[cfg(any(target_os = "macos", target_os = "linux"))]
60fn release_proxy_port(port: u16, quiet: bool) -> bool {
61 if !port_is_open(port) {
62 return true;
63 }
64
65 let Some(pid) = proxy_pid_on_port(port) else {
66 if !quiet {
67 eprintln!(
68 " Refusing managed proxy startup: port {port} is occupied by an unidentified service."
69 );
70 }
71 return false;
72 };
73 if pid == std::process::id() {
74 if !quiet {
75 eprintln!(" Refusing to stop the current process while handing off port {port}.");
76 }
77 return false;
78 }
79
80 let _ = crate::ipc::process::terminate_gracefully(pid);
81 let graceful_deadline = Instant::now() + Duration::from_secs(2);
82 while Instant::now() < graceful_deadline {
83 if !crate::ipc::process::is_alive(pid) && !port_is_open(port) {
84 if !quiet {
85 eprintln!(
86 " Handed port {port} from standalone proxy PID {pid} to managed service."
87 );
88 }
89 return true;
90 }
91 std::thread::sleep(Duration::from_millis(50));
92 }
93
94 if crate::ipc::process::is_alive(pid) {
95 let _ = crate::ipc::process::force_kill(pid);
96 }
97 let force_deadline = Instant::now() + Duration::from_secs(1);
98 while Instant::now() < force_deadline {
99 if !port_is_open(port) {
100 if !quiet {
101 eprintln!(
102 " Handed port {port} from standalone proxy PID {pid} to managed service."
103 );
104 }
105 return true;
106 }
107 std::thread::sleep(Duration::from_millis(50));
108 }
109
110 if !quiet {
111 eprintln!(" Refusing managed proxy startup: port {port} was not released by PID {pid}.");
112 }
113 false
114}
115
116pub fn install(port: u16, quiet: bool) -> bool {
117 let binary = find_binary();
118 install_with_binary(&binary, port, quiet)
119}
120
121pub(crate) fn install_with_binary(binary: &str, port: u16, quiet: bool) -> bool {
122 if binary.is_empty() {
123 if !quiet {
124 tracing::error!("Cannot find lean-ctx binary for autostart");
125 }
126 return false;
127 }
128
129 #[cfg(target_os = "macos")]
130 {
131 install_launchagent(binary, port, quiet)
132 }
133
134 #[cfg(target_os = "linux")]
135 {
136 install_systemd(binary, port, quiet)
137 }
138
139 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
140 {
141 let _ = (binary, quiet);
142 println!(" Autostart not supported on this platform");
143 println!(" Run manually: lean-ctx proxy start --port={port}");
144 false
145 }
146}
147
148pub fn stop() {
149 #[cfg(target_os = "macos")]
150 {
151 let plist_path = launchagent_path();
152 if plist_path.exists() {
153 crate::core::launchd::bootout(PLIST_LABEL, &plist_path);
154 }
155 }
156
157 #[cfg(target_os = "linux")]
158 {
159 let _ = std::process::Command::new("systemctl")
160 .args(["--user", "stop", SYSTEMD_SERVICE])
161 .output();
162 }
163}
164
165pub fn start() -> bool {
166 start_on_port(crate::proxy_setup::default_port())
167}
168
169pub fn start_on_port(port: u16) -> bool {
173 #[cfg(target_os = "macos")]
174 {
175 let plist_path = launchagent_path();
176 if plist_path.exists() {
177 crate::core::launchd::bootout(PLIST_LABEL, &plist_path);
178 if !release_proxy_port(port, false) {
179 return false;
180 }
181 return crate::core::launchd::bootstrap(PLIST_LABEL, &plist_path);
182 }
183 false
184 }
185
186 #[cfg(target_os = "linux")]
187 {
188 let _ = std::process::Command::new("systemctl")
189 .args(["--user", "stop", SYSTEMD_SERVICE])
190 .output();
191 if release_proxy_port(port, false) {
192 std::process::Command::new("systemctl")
193 .args(["--user", "start", SYSTEMD_SERVICE])
194 .status()
195 .is_ok_and(|status| status.success())
196 } else {
197 false
198 }
199 }
200
201 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
202 {
203 let _ = port;
204 false
205 }
206}
207
208pub fn uninstall(_quiet: bool) {
209 #[cfg(target_os = "macos")]
210 uninstall_launchagent(_quiet);
211
212 #[cfg(target_os = "linux")]
213 uninstall_systemd(_quiet);
214}
215
216pub fn is_supported() -> bool {
220 cfg!(any(target_os = "macos", target_os = "linux"))
221}
222
223pub fn is_installed() -> bool {
225 #[cfg(target_os = "macos")]
226 {
227 launchagent_path().exists()
228 }
229 #[cfg(target_os = "linux")]
230 {
231 systemd_path().exists()
232 }
233 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
234 {
235 false
236 }
237}
238
239pub fn is_loaded() -> bool {
242 #[cfg(target_os = "macos")]
243 {
244 is_installed() && crate::core::launchd::is_loaded(PLIST_LABEL)
245 }
246 #[cfg(target_os = "linux")]
247 {
248 is_installed()
249 && std::process::Command::new("systemctl")
250 .args(["--user", "is-active", "--quiet", SYSTEMD_SERVICE])
251 .status()
252 .is_ok_and(|status| status.success())
253 }
254 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
255 {
256 false
257 }
258}
259
260pub fn status() {
261 #[cfg(target_os = "macos")]
262 {
263 let plist_path = launchagent_path();
264 if plist_path.exists() {
265 println!(" LaunchAgent: installed at {}", plist_path.display());
266 if crate::core::launchd::is_loaded(PLIST_LABEL) {
267 println!(" Status: loaded");
268 } else {
269 println!(" Status: not loaded (run: lean-ctx proxy start)");
270 }
271 } else {
272 println!(" LaunchAgent: not installed");
273 }
274 }
275
276 #[cfg(target_os = "linux")]
277 {
278 let service_path = systemd_path();
279 if service_path.exists() {
280 println!(" systemd user service: installed");
281 let output = std::process::Command::new("systemctl")
282 .args(["--user", "is-active", SYSTEMD_SERVICE])
283 .output();
284 match output {
285 Ok(o) => {
286 let state = String::from_utf8_lossy(&o.stdout).trim().to_string();
287 println!(" Status: {state}");
288 }
289 Err(_) => println!(" Status: unknown"),
290 }
291 } else {
292 println!(" systemd service: not installed");
293 }
294 }
295
296 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
297 {
298 println!(" Autostart not available on this platform");
299 }
300}
301
302#[cfg(target_os = "macos")]
303fn launchagent_path() -> PathBuf {
304 dirs::home_dir()
305 .unwrap_or_else(|| PathBuf::from("/tmp"))
306 .join("Library/LaunchAgents")
307 .join(format!("{PLIST_LABEL}.plist"))
308}
309
310#[cfg(target_os = "macos")]
311fn install_launchagent(binary: &str, port: u16, quiet: bool) -> bool {
312 let plist_dir = dirs::home_dir()
313 .unwrap_or_else(|| PathBuf::from("/tmp"))
314 .join("Library/LaunchAgents");
315 let _ = std::fs::create_dir_all(&plist_dir);
316
317 let plist_path = plist_dir.join(format!("{PLIST_LABEL}.plist"));
318 crate::core::launchd::bootout(PLIST_LABEL, &plist_path);
322 if !release_proxy_port(port, quiet) {
323 return false;
324 }
325 let log_dir = crate::core::paths::state_dir()
329 .unwrap_or_else(|_| std::env::temp_dir().join("lean-ctx"))
330 .join("logs");
331 let _ = std::fs::create_dir_all(&log_dir);
332
333 let port_arg = format!("--port={port}");
336 let program_args = crate::core::tcc_guard_sandbox::program_args_xml(
337 &crate::core::tcc_guard_sandbox::wrap_launchd_args(binary, &["proxy", "start", &port_arg]),
338 " ",
339 );
340
341 let env_vars = crate::core::tcc_guard_sandbox::pinned_layout_env_xml();
348
349 let plist = format!(
350 r#"<?xml version="1.0" encoding="UTF-8"?>
351<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
352<plist version="1.0">
353<dict>
354 <key>Label</key>
355 <string>{PLIST_LABEL}</string>
356 <key>ProgramArguments</key>
357 <array>
358{program_args}
359 </array>
360{env_vars} <key>RunAtLoad</key>
361 <true/>
362 <key>KeepAlive</key>
363 <true/>
364 <key>StandardOutPath</key>
365 <string>{stdout}</string>
366 <key>StandardErrorPath</key>
367 <string>{stderr}</string>
368</dict>
369</plist>"#,
370 stdout = log_dir.join("proxy.stdout.log").display(),
371 stderr = log_dir.join("proxy.stderr.log").display(),
372 );
373
374 let _ = std::fs::write(&plist_path, &plist);
375
376 let ok = crate::core::launchd::bootstrap(PLIST_LABEL, &plist_path);
377
378 if !quiet {
379 if ok {
380 println!(" Installed LaunchAgent: {}", plist_path.display());
381 println!(" Proxy will start on login and restart if stopped");
382 } else {
383 println!(" Created LaunchAgent at {}", plist_path.display());
384 println!(" Load reported a problem; check: launchctl print {PLIST_LABEL}");
385 }
386 }
387 ok
388}
389
390#[cfg(target_os = "macos")]
391fn uninstall_launchagent(quiet: bool) {
392 let plist_path = launchagent_path();
393 if !plist_path.exists() {
394 if !quiet {
395 println!(" LaunchAgent not installed, nothing to remove");
396 }
397 return;
398 }
399
400 crate::core::launchd::bootout(PLIST_LABEL, &plist_path);
401
402 let _ = std::fs::remove_file(&plist_path);
403 if !quiet {
404 println!(" Removed LaunchAgent: {}", plist_path.display());
405 }
406}
407
408#[cfg(target_os = "linux")]
409fn systemd_path() -> PathBuf {
410 dirs::home_dir()
411 .unwrap_or_else(|| PathBuf::from("/tmp"))
412 .join(".config/systemd/user")
413 .join(format!("{SYSTEMD_SERVICE}.service"))
414}
415
416#[cfg(target_os = "linux")]
417fn install_systemd(binary: &str, port: u16, quiet: bool) -> bool {
418 let service_dir = dirs::home_dir()
419 .unwrap_or_else(|| PathBuf::from("/tmp"))
420 .join(".config/systemd/user");
421 let _ = std::fs::create_dir_all(&service_dir);
422
423 let service_path = service_dir.join(format!("{SYSTEMD_SERVICE}.service"));
424
425 let _ = std::process::Command::new("systemctl")
426 .args(["--user", "stop", SYSTEMD_SERVICE])
427 .output();
428 if !release_proxy_port(port, quiet) {
429 return false;
430 }
431
432 let unit = format!(
433 r"[Unit]
434Description=lean-ctx API Proxy
435After=network.target
436StartLimitIntervalSec=300
437StartLimitBurst=5
438
439[Service]
440Type=simple
441ExecStart={binary} proxy start --port={port}
442Restart=on-failure
443RestartSec=5
444StandardOutput=journal
445StandardError=journal
446Environment=RUST_LOG=info
447
448[Install]
449WantedBy=default.target
450"
451 );
452
453 let _ = std::fs::write(&service_path, &unit);
454
455 let _ = std::process::Command::new("systemctl")
456 .args(["--user", "daemon-reload"])
457 .output();
458
459 let result = std::process::Command::new("systemctl")
460 .args(["--user", "enable", "--now", SYSTEMD_SERVICE])
461 .output();
462
463 if !quiet {
464 match &result {
465 Ok(o) if o.status.success() => {
466 println!(" Installed systemd user service: {SYSTEMD_SERVICE}");
467 println!(" Proxy will start on login and restart if stopped");
468 }
469 Ok(o) => {
470 let err = String::from_utf8_lossy(&o.stderr);
471 println!(" Created service file but enable failed: {err}");
472 }
473 Err(e) => {
474 println!(" Created service file at {}", service_path.display());
475 println!(" Could not enable: {e}");
476 }
477 }
478 }
479 result.is_ok_and(|output| output.status.success())
480}
481
482#[cfg(target_os = "linux")]
483fn uninstall_systemd(quiet: bool) {
484 let service_path = systemd_path();
485 if !service_path.exists() {
486 if !quiet {
487 println!(" systemd service not installed, nothing to remove");
488 }
489 return;
490 }
491
492 let _ = std::process::Command::new("systemctl")
493 .args(["--user", "stop", SYSTEMD_SERVICE])
494 .output();
495 let _ = std::process::Command::new("systemctl")
496 .args(["--user", "disable", SYSTEMD_SERVICE])
497 .output();
498 let _ = std::fs::remove_file(&service_path);
499 let _ = std::process::Command::new("systemctl")
500 .args(["--user", "daemon-reload"])
501 .output();
502
503 if !quiet {
504 println!(" Removed systemd service: {SYSTEMD_SERVICE}");
505 }
506}
507
508pub fn find_binary() -> String {
509 crate::core::portable_binary::resolve_portable_binary()
510}
511
512#[cfg(test)]
513mod tests {
514 use super::{health_identifies_lean_ctx_proxy, proxy_pid_from_health};
515 #[cfg(any(target_os = "macos", target_os = "linux"))]
516 use super::{port_is_open, release_proxy_port};
517 #[cfg(any(target_os = "macos", target_os = "linux"))]
518 use std::io::{Read, Write};
519 #[cfg(any(target_os = "macos", target_os = "linux"))]
520 use std::net::TcpListener;
521
522 #[test]
523 fn health_pid_parser_accepts_only_well_formed_health() {
524 assert_eq!(
525 proxy_pid_from_health(r#"{"status":"ok","pid":4242}"#),
526 Some(4242)
527 );
528 assert_eq!(
529 proxy_pid_from_health(r#"{"status":"busy","pid":4242}"#),
530 None
531 );
532 assert_eq!(proxy_pid_from_health(r#"{"status":"ok","pid":0}"#), None);
533 assert_eq!(proxy_pid_from_health(r#"{"status":"ok"}"#), None);
534 assert_eq!(proxy_pid_from_health("not json"), None);
535 assert!(health_identifies_lean_ctx_proxy(
536 r#"{"status":"ok","service":"lean-ctx-proxy","pid":4242}"#
537 ));
538 assert!(!health_identifies_lean_ctx_proxy(
539 r#"{"status":"ok","pid":4242}"#
540 ));
541 }
542
543 #[test]
544 #[cfg(any(target_os = "macos", target_os = "linux"))]
545 fn managed_handoff_fails_closed_for_unidentified_listener() {
546 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
547 let port = listener.local_addr().unwrap().port();
548 let server = std::thread::spawn(move || {
549 for _ in 0..2 {
550 let (mut stream, _) = listener.accept().unwrap();
551 stream
552 .set_read_timeout(Some(std::time::Duration::from_secs(1)))
553 .unwrap();
554 let mut request = [0_u8; 512];
555 if stream.read(&mut request).unwrap_or(0) > 0 {
556 let body = r#"{"status":"ok"}"#;
557 write!(
558 stream,
559 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
560 body.len()
561 )
562 .unwrap();
563 }
564 }
565 });
566
567 assert!(!release_proxy_port(port, true));
568 server.join().unwrap();
569 }
570
571 #[cfg(unix)]
572 struct ChildGuard(std::process::Child);
573
574 #[cfg(unix)]
575 impl Drop for ChildGuard {
576 fn drop(&mut self) {
577 let _ = self.0.kill();
578 let _ = self.0.wait();
579 }
580 }
581
582 #[test]
583 #[cfg(unix)]
584 fn managed_handoff_stops_identified_proxy_and_releases_port() {
585 let reservation = TcpListener::bind("127.0.0.1:0").unwrap();
586 let port = reservation.local_addr().unwrap().port();
587 drop(reservation);
588
589 let child = std::process::Command::new(std::env::current_exe().unwrap())
590 .args([
591 "--ignored",
592 "--exact",
593 "proxy_autostart::tests::managed_handoff_test_child",
594 "--nocapture",
595 ])
596 .env("LEAN_CTX_HANDOFF_TEST_PORT", port.to_string())
597 .spawn()
598 .unwrap();
599 let mut child = ChildGuard(child);
600
601 let ready_deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
602 while !port_is_open(port) && std::time::Instant::now() < ready_deadline {
603 std::thread::sleep(std::time::Duration::from_millis(25));
604 }
605 assert!(port_is_open(port), "test proxy did not bind port {port}");
606 assert!(release_proxy_port(port, true));
607 let status = child.0.wait().unwrap();
608 assert!(
609 !status.success(),
610 "handoff must terminate the standalone proxy"
611 );
612 assert!(!port_is_open(port), "handoff must release port {port}");
613 }
614
615 #[test]
616 #[ignore = "helper process for managed_handoff_stops_identified_proxy_and_releases_port"]
617 #[cfg(unix)]
618 fn managed_handoff_test_child() {
619 let port: u16 = std::env::var("LEAN_CTX_HANDOFF_TEST_PORT")
620 .unwrap()
621 .parse()
622 .unwrap();
623 let listener = TcpListener::bind(("127.0.0.1", port)).unwrap();
624 loop {
625 let (mut stream, _) = listener.accept().unwrap();
626 stream
627 .set_read_timeout(Some(std::time::Duration::from_secs(1)))
628 .unwrap();
629 let mut request = [0_u8; 512];
630 if stream.read(&mut request).unwrap_or(0) > 0 {
631 let body = format!(
632 r#"{{"status":"ok","service":"lean-ctx-proxy","pid":{}}}"#,
633 std::process::id()
634 );
635 write!(
636 stream,
637 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
638 body.len()
639 )
640 .unwrap();
641 }
642 }
643 }
644}