term-session 0.9.5-alpha

Generic terminal session reproducer: run a PTY in a detached server and attach any number of terminals, locally or over SSH.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
//! Binary/daemon tests for the `term-session` gateway.
//!
//! These exercise the real compiled binary (`CARGO_BIN_EXE_term-session`):
//! detachment proof via `--daemon-selfcheck`, daemon resilience to client
//! disconnects and parent death, and clean teardown via `ShutdownGateway`.
//!
//! Each test uses a unique `TERM_WM_GATEWAY` so parallel runs never collide.

use std::io;
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::sync::Arc;
use std::time::{Duration, Instant};

use muxio_tokio_rpc_ipc_client::RpcCallPrebuffered;
use term_session_muxio_service_definitions::{Attach, ListChannels, ShutdownGateway, Spawn};

/// The compiled `term-session` binary under test.
fn bin() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_term-session"))
}

/// Path to the mock PTY binary used as a session child. Delegates to the
/// shared helper in the mock crate's library.
fn mock_bin() -> PathBuf {
    term_session_mock::get_mock_bin()
}

/// A unique per-test gateway name.
fn unique_gateway(tag: &str) -> String {
    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
    let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    format!("term-wm/dtest-{tag}-{id}")
}

/// Spawn the real daemon with the given gateway and an optional selfcheck
/// marker. Returns `(child, marker_path)`.
fn spawn_daemon(gateway: &str, selfcheck: bool) -> (Child, Option<PathBuf>) {
    let marker = if selfcheck {
        let path = std::env::temp_dir().join(format!(
            "term-session-selfcheck-{}.txt",
            gateway.replace('/', "-")
        ));
        let _ = std::fs::remove_file(&path);
        Some(path)
    } else {
        None
    };
    let mut cmd = Command::new(bin());
    cmd.env("TERM_WM_GATEWAY", gateway).arg("--daemon");
    if let Some(ref m) = marker {
        cmd.arg("--daemon-selfcheck").arg(m);
    }
    cmd.stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    let child = cmd.spawn().expect("spawn daemon");
    (child, marker)
}

/// Poll until a client can connect to the gateway, or panic after a timeout.
async fn wait_connectable(gateway: &str) -> Arc<muxio_tokio_rpc_ipc_client::RpcIpcClient> {
    let start = Instant::now();
    loop {
        match muxio_tokio_rpc_ipc_client::RpcIpcClient::new(gateway).await {
            Ok(c) => return c,
            Err(_) if start.elapsed() < Duration::from_secs(20) => {
                tokio::time::sleep(Duration::from_millis(50)).await;
            }
            Err(e) => panic!("gateway {gateway} not reachable after 20s: {e}"),
        }
    }
}

#[tokio::test]
async fn daemon_detaches_and_reports_proof() {
    let gateway = unique_gateway("detach");
    let (mut child, marker) = spawn_daemon(&gateway, true);
    let marker = marker.expect("marker requested");

    // Wait for the marker (daemon writes it once bound).
    let start = Instant::now();
    let proof = loop {
        if let Ok(content) = std::fs::read_to_string(&marker) {
            break content.trim().to_string();
        }
        assert!(
            start.elapsed() < Duration::from_secs(8),
            "daemon never wrote selfcheck marker"
        );
        tokio::time::sleep(Duration::from_millis(50)).await;
    };

    // Platform-specific detachment proof.
    #[cfg(windows)]
    assert_eq!(proof, "windows-no-console", "marker: {proof}");
    #[cfg(unix)]
    assert_eq!(proof, "unix-session-leader", "marker: {proof}");

    // Clean up.
    let client = wait_connectable(&gateway).await;
    ShutdownGateway::call(&*client, ()).await.unwrap();
    let _ = child.wait();
}

#[tokio::test]
async fn daemon_survives_all_clients_disconnecting() {
    let gateway = unique_gateway("survive");
    let (mut child, _marker) = spawn_daemon(&gateway, false);

    let client = wait_connectable(&gateway).await;
    let channel = "test/daemon_survive";
    Attach::call(
        &*client,
        (
            channel.to_string(),
            "t".to_string(),
            std::process::id() as u64,
        ),
    )
    .await
    .unwrap();
    Spawn::call(
        &*client,
        (
            Some(vec![
                mock_bin().to_string_lossy().to_string(),
                "sleep".into(),
                "60000".into(),
            ]),
            80u16,
            24u16,
        ),
    )
    .await
    .unwrap();
    drop(client);

    // After ALL clients disconnect, the daemon must still be reachable and a
    // fresh attach/spawn must succeed (session respawns / persists).
    let client2 = wait_connectable(&gateway).await;
    Attach::call(
        &*client2,
        (
            channel.to_string(),
            "t".to_string(),
            std::process::id() as u64,
        ),
    )
    .await
    .unwrap();
    Spawn::call(&*client2, (None, 80u16, 24u16)).await.unwrap();

    ShutdownGateway::call(&*client2, ()).await.unwrap();
    let _ = child.wait();
}

#[tokio::test]
async fn daemon_survives_parent_death() {
    let gateway = unique_gateway("parent_death");
    let channel = "test/daemon_parent_death";
    let mock = mock_bin().to_string_lossy().to_string();

    // Spawn an `attach` subprocess that auto-spawns the daemon, running a
    // LONG-LIVED session so its process survives the parent dying.
    let mut attach = Command::new(bin())
        .env("TERM_WM_GATEWAY", &gateway)
        .args([
            "attach",
            "--channel",
            channel,
            "--",
            &mock,
            "sleep",
            "60000",
        ])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .expect("spawn attach");

    // Give it time to auto-spawn the daemon and attach.
    tokio::time::sleep(Duration::from_millis(2000)).await;
    let _ = attach.kill();
    let _ = attach.wait();

    // The daemon it spawned must still be reachable and the session alive
    // (the `sleep` process is still running, so the daemon must not have
    // exited — sessions are torn down only when their process ends).
    let client = wait_connectable(&gateway).await;
    Attach::call(
        &*client,
        (
            channel.to_string(),
            "t".to_string(),
            std::process::id() as u64,
        ),
    )
    .await
    .unwrap();
    let (id, _, _) = Spawn::call(&*client, (None, 80u16, 24u16)).await.unwrap();
    assert_eq!(id, 1, "session from the orphaned daemon must persist");

    ShutdownGateway::call(&*client, ()).await.unwrap();
    // Give the daemon time to run its teardown and exit.
    tokio::time::sleep(Duration::from_millis(1000)).await;
}

/// The daemon must never inherit the parent's open handles. Regression guard
/// for the Windows `bInheritHandles = FALSE` auto-spawn: `std::process::Command`
/// always passes `TRUE`, so a future switch back to it would leak every
/// inheritable handle (pipe ends, sockets) into the daemon.
///
/// The test creates an inheritable pipe, auto-spawns the daemon through the
/// real `connect_or_spawn_server` path, closes the parent's write end, and
/// asserts the read end reaches EOF. If the daemon inherited the write handle
/// it stays open forever and the assertion times out.
#[tokio::test]
async fn daemon_does_not_inherit_parent_handles() {
    use term_session::auto_spawn::connect_or_spawn_server;

    let gateway = unique_gateway("no_inherit");
    // `connect_or_spawn_server` resolves the gateway from `TERM_WM_GATEWAY` in
    // this process's environment; point it at the unique per-test channel.
    // `set_var` is `unsafe` under edition 2024.
    unsafe {
        std::env::set_var("TERM_WM_GATEWAY", &gateway);
    }

    #[cfg(windows)]
    let (read_end, write_end) = create_inheritable_pipe();
    #[cfg(unix)]
    let (read_end, write_end) = create_cloexec_pipe();
    #[cfg(not(any(unix, windows)))]
    panic!("handle-inheritance test not supported on this platform");

    // Auto-spawn the detached daemon via the real auto-spawn path.
    connect_or_spawn_server(Some(&bin())).expect("auto-spawn daemon");

    // Close the parent's write end. A correctly detached daemon holds no copy,
    // so the read end reaches EOF; a daemon that inherited the handle keeps the
    // pipe open indefinitely.
    close_write_end(write_end);

    assert_eof_on_read_end(read_end, Duration::from_secs(5))
        .expect("daemon inherited the parent's pipe write end");

    close_read_end(read_end);

    // Clean up the daemon.
    let client = wait_connectable(&gateway).await;
    ShutdownGateway::call(&*client, ()).await.unwrap();
}

/// Create an inheritable named pipe whose read end we keep. Both ends are
/// marked inheritable via `SECURITY_ATTRIBUTES`, so if the daemon is spawned
/// with `bInheritHandles = TRUE` (the regression under test) it keeps the
/// write end and the pipe never breaks.
#[cfg(windows)]
fn create_inheritable_pipe() -> (
    windows_sys::Win32::Foundation::HANDLE,
    windows_sys::Win32::Foundation::HANDLE,
) {
    use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;
    use windows_sys::Win32::System::Pipes::CreatePipe;

    let sa = SECURITY_ATTRIBUTES {
        nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
        lpSecurityDescriptor: std::ptr::null_mut(),
        bInheritHandle: 1,
    };
    let mut read = std::ptr::null_mut();
    let mut write = std::ptr::null_mut();
    let ok = unsafe { CreatePipe(&mut read, &mut write, &sa, 0) };
    assert_ne!(ok, 0, "CreatePipe failed: {}", io::Error::last_os_error());
    (read, write)
}

/// Create a pipe with both ends CLOEXEC. The std `Command` spawn path never
/// clears CLOEXEC, so a correctly detached daemon never holds the write end.
#[cfg(unix)]
fn create_cloexec_pipe() -> (libc::c_int, libc::c_int) {
    use std::os::unix::io::RawFd;

    let mut fds = [0 as RawFd; 2];
    assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0, "pipe() failed");
    for &fd in &fds {
        let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
        assert!(flags >= 0, "F_GETFD failed");
        let rc = unsafe { libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC) };
        assert_eq!(rc, 0, "F_SETFD failed");
    }
    (fds[0], fds[1])
}

/// Assert the read end reaches EOF (write end fully closed) within `timeout`.
#[cfg(windows)]
fn assert_eof_on_read_end(
    read: windows_sys::Win32::Foundation::HANDLE,
    timeout: Duration,
) -> io::Result<()> {
    use windows_sys::Win32::Foundation::ERROR_BROKEN_PIPE;
    use windows_sys::Win32::System::Pipes::PeekNamedPipe;

    let start = Instant::now();
    loop {
        let mut total_avail: u32 = 0;
        let ok = unsafe {
            PeekNamedPipe(
                read,
                std::ptr::null_mut(),
                0,
                std::ptr::null_mut(),
                &mut total_avail,
                std::ptr::null_mut(),
            )
        };
        if ok == 0 {
            let err = io::Error::last_os_error();
            if err.raw_os_error() == Some(ERROR_BROKEN_PIPE as i32) {
                // Every write-end handle is gone: the daemon inherited none.
                return Ok(());
            }
            return Err(err);
        }
        if start.elapsed() >= timeout {
            return Err(io::Error::new(
                io::ErrorKind::TimedOut,
                "read end never reached EOF (daemon inherited the write handle)",
            ));
        }
        std::thread::sleep(Duration::from_millis(50));
    }
}

/// Assert the read end reaches EOF (write end fully closed) within `timeout`.
#[cfg(unix)]
fn assert_eof_on_read_end(fd: libc::c_int, timeout: Duration) -> io::Result<()> {
    let start = Instant::now();
    loop {
        let mut poll_fds = [libc::pollfd {
            fd,
            events: libc::POLLIN | libc::POLLHUP,
            revents: 0,
        }];
        let n = unsafe { libc::poll(poll_fds.as_mut_ptr(), 1, 50) };
        if n < 0 {
            return Err(io::Error::last_os_error());
        }
        if n > 0 {
            // Drain any buffered bytes; EOF is a zero-length read.
            let mut buf = [0u8; 64];
            loop {
                let r = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void, buf.len()) };
                if r < 0 {
                    if io::Error::last_os_error().kind() == io::ErrorKind::Interrupted {
                        continue;
                    }
                    return Err(io::Error::last_os_error());
                }
                if r == 0 {
                    return Ok(());
                }
                if (r as usize) < buf.len() {
                    break;
                }
            }
        }
        if start.elapsed() >= timeout {
            return Err(io::Error::new(
                io::ErrorKind::TimedOut,
                "read end never reached EOF (child inherited the write fd)",
            ));
        }
        std::thread::sleep(Duration::from_millis(10));
    }
}

#[cfg(windows)]
fn close_read_end(read: windows_sys::Win32::Foundation::HANDLE) {
    unsafe {
        let _ = windows_sys::Win32::Foundation::CloseHandle(read);
    }
}

#[cfg(windows)]
fn close_write_end(write: windows_sys::Win32::Foundation::HANDLE) {
    unsafe {
        let _ = windows_sys::Win32::Foundation::CloseHandle(write);
    }
}

#[cfg(unix)]
fn close_read_end(read: libc::c_int) {
    unsafe {
        let _ = libc::close(read);
    }
}

#[cfg(unix)]
fn close_write_end(write: libc::c_int) {
    unsafe {
        let _ = libc::close(write);
    }
}

#[tokio::test]
async fn cli_kill_client_detaches_one_client() {
    let gateway = unique_gateway("kill_client");
    let channel = "test/kill_client";
    let (mut child, _marker) = spawn_daemon(&gateway, false);

    // Two attached clients on the same channel.
    let c1 = wait_connectable(&gateway).await;
    let c2 = wait_connectable(&gateway).await;
    Attach::call(
        &*c1,
        (
            channel.to_string(),
            "one".to_string(),
            std::process::id() as u64,
        ),
    )
    .await
    .unwrap();
    Attach::call(
        &*c2,
        (
            channel.to_string(),
            "two".to_string(),
            std::process::id() as u64,
        ),
    )
    .await
    .unwrap();
    Spawn::call(
        &*c1,
        (
            Some(vec![
                mock_bin().to_string_lossy().to_string(),
                "sleep".into(),
                "60000".into(),
            ]),
            80u16,
            24u16,
        ),
    )
    .await
    .unwrap();
    Spawn::call(&*c2, (None, 80u16, 24u16)).await.unwrap();

    // Read the conn ids from `list` (as an operator would).
    let resp = ListChannels::call(&*c1, ()).await.unwrap();
    let ch = resp
        .channels
        .iter()
        .find(|c| c.name == channel)
        .expect("channel listed");
    assert_eq!(ch.clients.len(), 2, "two clients attached");
    let target = ch.clients[0].conn_id;

    // Kill one client through the real CLI subcommand.
    let out = Command::new(bin())
        .env("TERM_WM_GATEWAY", &gateway)
        .args(["kill-client", channel, &target.to_string()])
        .output()
        .expect("run kill-client");
    assert!(
        out.status.success(),
        "kill-client failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    // One client remains.
    let resp = ListChannels::call(&*c1, ()).await.unwrap();
    let ch = resp
        .channels
        .iter()
        .find(|c| c.name == channel)
        .expect("channel listed");
    assert_eq!(
        ch.clients.len(),
        1,
        "one client should remain after kill-client"
    );

    ShutdownGateway::call(&*c1, ()).await.unwrap();
    let _ = child.wait();
}