Skip to main content

term_session/
lib.rs

1pub mod auto_spawn;
2
3use std::io;
4use std::sync::Arc;
5
6use muxio_tokio_rpc_ipc_client::RpcCallPrebuffered;
7use term_session_muxio_service_definitions::{
8    KillChannel, KillClient, ListChannels, ListChannelsResponse, ShutdownGateway,
9};
10
11pub const CHANNEL_ENV_VAR: &str = "TERM_WM_CHANNEL";
12pub const DEFAULT_CHANNEL: &str = "default/main";
13
14/// Resolve the channel from an optional CLI arg, falling back to the env var,
15/// then the default.
16pub fn resolve_channel(cli_channel: Option<String>) -> String {
17    cli_channel
18        .or_else(|| std::env::var(CHANNEL_ENV_VAR).ok())
19        .unwrap_or_else(|| DEFAULT_CHANNEL.to_string())
20}
21
22/// Format a unix timestamp as a relative human string ("2s ago", "5m ago", …),
23/// falling back to an absolute HH:MM:SS for very old timestamps.
24pub fn format_unix_relative(ts: u64) -> String {
25    let now = std::time::SystemTime::now()
26        .duration_since(std::time::UNIX_EPOCH)
27        .map(|d| d.as_secs())
28        .unwrap_or(0);
29    if ts == 0 {
30        return "-".to_string();
31    }
32    let diff = now.saturating_sub(ts);
33    if diff < 60 {
34        format!("{diff}s")
35    } else if diff < 3600 {
36        format!("{}m", diff / 60)
37    } else if diff < 86400 {
38        format!("{}h", diff / 3600)
39    } else {
40        let secs = ts % 86400;
41        let (h, m, s) = (secs / 3600, (secs % 3600) / 60, secs % 60);
42        format!("{h:02}:{m:02}:{s:02}")
43    }
44}
45
46/// Connect to the gateway daemon and run `op` with a live client. The tokio
47/// runtime that hosts the muxio connection is kept alive for the whole `op`,
48/// so RPCs complete (dropping it early would tear down the connection and
49/// hang the call). `op` receives an owned `Arc` and runs on that runtime.
50pub fn with_gateway<F, Fut, T>(op: F) -> io::Result<T>
51where
52    F: FnOnce(Arc<muxio_tokio_rpc_ipc_client::RpcIpcClient>) -> Fut,
53    Fut: std::future::Future<Output = T>,
54{
55    let gateway = term_session_muxio_service_definitions::gateway_channel_name();
56    let rt =
57        tokio::runtime::Runtime::new().map_err(|e| io::Error::other(format!("runtime: {e}")))?;
58    rt.block_on(async {
59        let client = muxio_tokio_rpc_ipc_client::RpcIpcClient::new(&gateway.to_string())
60            .await
61            .map_err(|e| {
62                io::Error::new(
63                    io::ErrorKind::ConnectionRefused,
64                    format!(
65                        "No gateway daemon is running on '{gateway}'. Start one with `term-session attach` or `term-session --daemon` first.\n  cause: {e}"
66                    ),
67                )
68            })?;
69        Ok(op(client).await)
70    })
71}
72
73/// List channels from the gateway, including the daemon PID + socket name.
74pub fn list_channels() -> io::Result<ListChannelsResponse> {
75    with_gateway(|client| async move { ListChannels::call(&*client, ()).await })?
76        .map_err(|e| io::Error::other(format!("list: {e}")))
77}
78
79/// Kill a channel's session and detach all its sockets.
80pub fn kill_channel(channel: &str) -> io::Result<()> {
81    with_gateway(|client| async move { KillChannel::call(&*client, channel.to_string()).await })?
82        .map_err(|e| io::Error::other(format!("kill channel: {e}")))
83}
84
85/// Detach a single client socket from a channel by `conn_id`.
86pub fn kill_client(channel: &str, conn_id: usize) -> io::Result<()> {
87    with_gateway(|client| async move {
88        KillClient::call(&*client, (channel.to_string(), conn_id)).await
89    })?
90    .map_err(|e| io::Error::other(format!("kill client: {e}")))
91}
92
93/// Stop the gateway daemon.
94pub fn stop_gateway() -> io::Result<()> {
95    with_gateway(|client| async move { ShutdownGateway::call(&*client, ()).await })?
96        .map_err(|e| io::Error::other(format!("shutdown: {e}")))
97}
98
99/// Run the gateway daemon: rename the process, detach from the controlling
100/// terminal, and serve until `ShutdownGateway`. `selfcheck_marker` is a
101/// test-only path written with the platform's detachment proof once bound.
102pub fn run_daemon(selfcheck_marker: Option<std::path::PathBuf>) -> io::Result<()> {
103    tracing_subscriber::fmt::init();
104
105    // Make the daemon recognizable in process managers: every `term-session`
106    // process is the same binary, so rename this one so `ps`/`top`/Task
107    // Manager show `term-session-daemon` instead of generic `term-session`.
108    set_daemon_process_name();
109
110    // Self-detach: a `--daemon` that was not already started detached (e.g.
111    // spawned directly by a test or wrapper, not via
112    // `auto_spawn::connect_or_spawn_server`) detaches itself from the
113    // launching terminal so Ctrl+C / SIGHUP never reach it.
114    //
115    // - Unix: `setsid()` starts a new session and process group and drops the
116    //   controlling terminal. It fails with EPERM if the process is already a
117    //   process-group leader, which is exactly the already-detached case — so
118    //   ignore that error.
119    // - Windows: `FreeConsole()` detaches from the launching console so no
120    //   console control events (Ctrl+C, Ctrl+Close) are ever delivered to the
121    //   daemon. It reports failure when there is no console to detach from,
122    //   which is the already-detached `auto_spawn` case — so ignore that too.
123    #[cfg(unix)]
124    unsafe {
125        libc::setsid();
126    }
127    #[cfg(windows)]
128    unsafe {
129        let _ = windows_sys::Win32::System::Console::FreeConsole();
130    }
131
132    let gateway = term_session_muxio_service_definitions::gateway_channel_name();
133
134    // Test-only: as soon as the gateway socket is reachable, write the
135    // platform's detachment proof to the marker, then exit the probe thread.
136    if let Some(ref marker) = selfcheck_marker {
137        let gw = gateway.clone();
138        let marker = marker.clone();
139        std::thread::Builder::new()
140            .name("daemon-selfcheck".into())
141            .spawn(move || {
142                for _ in 0..200 {
143                    if term_session_muxio_service_definitions::probe_ipc_endpoint(&gw) {
144                        write_selfcheck_marker(&marker);
145                        return;
146                    }
147                    std::thread::sleep(std::time::Duration::from_millis(25));
148                }
149                let _ = std::fs::write(&marker, "bound-timeout");
150            })?;
151    }
152
153    let rt =
154        tokio::runtime::Runtime::new().map_err(|e| io::Error::other(format!("runtime: {e}")))?;
155    rt.block_on(term_session_server::run_gateway(gateway.clone()))
156        .map_err(|e| io::Error::other(format!("gateway error: {e}")))?;
157    Ok(())
158}
159
160/// Rename the running process so process managers can distinguish the gateway
161/// daemon from interactive `term-session` clients. Best-effort and cosmetic:
162/// a failure is ignored and never affects functionality.
163///
164/// Platform behavior (and limitations):
165/// - **Linux:** `PR_SET_NAME` sets the process comm (capped at 15 bytes →
166///   `term-session-d`), so `ps -comm`, `top`, and `htop` show the renamed
167///   value. This is the most complete rename on any platform.
168/// - **macOS:** `pthread_setname_np` sets the **thread** name, not the process
169///   comm — `ps -o comm` and Activity Monitor's process list still show
170///   `term-session`. The renamed value is only visible in Activity Monitor's
171///   per-thread view (and `sample`). This is an OS limitation: macOS has no
172///   portable user-space API to rename the process comm. Daemon disambiguation
173///   on macOS therefore relies primarily on the `--daemon` argv flag and the
174///   `Gateway Daemon PID` header printed by `term-session list`.
175/// - **Windows:** `SetThreadDescription` sets the thread description, which
176///   Process Explorer / Process Hacker show in the **Description** column.
177pub fn set_daemon_process_name() {
178    #[cfg(target_os = "linux")]
179    {
180        use std::ffi::CString;
181        if let Ok(name) = CString::new("term-session-d") {
182            unsafe {
183                libc::prctl(libc::PR_SET_NAME, name.as_ptr() as usize, 0, 0, 0);
184            }
185        }
186    }
187    #[cfg(target_os = "macos")]
188    {
189        use std::ffi::CString;
190        if let Ok(name) = CString::new("term-session-daemon") {
191            unsafe {
192                libc::pthread_setname_np(name.as_ptr());
193            }
194        }
195    }
196    #[cfg(windows)]
197    {
198        use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadDescription};
199        let wide: Vec<u16> = "term-session-daemon"
200            .encode_utf16()
201            .chain(std::iter::once(0))
202            .collect();
203        unsafe {
204            SetThreadDescription(GetCurrentThread(), wide.as_ptr());
205        }
206    }
207}
208
209/// Write the platform's detachment proof to the marker (test-only).
210fn write_selfcheck_marker(marker: &std::path::Path) {
211    #[cfg(windows)]
212    let proof = {
213        use windows_sys::Win32::System::Console::{
214            GetConsoleProcessList, GetStdHandle, STD_INPUT_HANDLE,
215        };
216        let mut pids = [0u32; 4];
217        let count = unsafe {
218            let _handle = GetStdHandle(STD_INPUT_HANDLE);
219            GetConsoleProcessList(pids.as_mut_ptr(), pids.len() as u32)
220        };
221        if count == 0 {
222            "windows-no-console"
223        } else {
224            "windows-has-console"
225        }
226    };
227    #[cfg(unix)]
228    let proof = {
229        let sid = unsafe { libc::getsid(0) };
230        let pid = unsafe { libc::getpid() };
231        if sid == pid {
232            "unix-session-leader"
233        } else {
234            "unix-not-leader"
235        }
236    };
237    #[cfg(not(any(unix, windows)))]
238    let proof = "unsupported";
239    let _ = std::fs::write(marker, proof);
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245
246    /// Serializes tests that mutate `TERM_WM_CHANNEL`, which is process-global.
247    fn env_lock() -> std::sync::MutexGuard<'static, ()> {
248        static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
249        LOCK.lock().unwrap_or_else(|e| e.into_inner())
250    }
251
252    #[test]
253    fn cli_channel_takes_precedence_over_env() {
254        let _guard = env_lock();
255        unsafe {
256            std::env::set_var(CHANNEL_ENV_VAR, "other/chan");
257        }
258        assert_eq!(resolve_channel(Some("work/dev".to_string())), "work/dev");
259        unsafe {
260            std::env::remove_var(CHANNEL_ENV_VAR);
261        }
262    }
263
264    #[test]
265    fn falls_back_to_env_channel() {
266        let _guard = env_lock();
267        unsafe {
268            std::env::set_var(CHANNEL_ENV_VAR, "work/dev");
269        }
270        assert_eq!(resolve_channel(None), "work/dev");
271        unsafe {
272            std::env::remove_var(CHANNEL_ENV_VAR);
273        }
274    }
275
276    #[test]
277    fn falls_back_to_default_channel() {
278        let _guard = env_lock();
279        unsafe {
280            std::env::remove_var(CHANNEL_ENV_VAR);
281        }
282        assert_eq!(resolve_channel(None), DEFAULT_CHANNEL);
283    }
284}