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
14pub 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
22pub 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
46pub 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
73pub 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
79pub 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
85pub 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
93pub 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
99pub fn run_daemon(selfcheck_marker: Option<std::path::PathBuf>) -> io::Result<()> {
103 tracing_subscriber::fmt::init();
104
105 set_daemon_process_name();
109
110 #[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 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
160pub 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
209fn 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 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}