Skip to main content

win_custody/
session.rs

1//! Terminal Services sessions.
2#![allow(unsafe_code)]
3
4use std::io;
5use std::ptr::null_mut;
6
7use windows_sys::Win32::System::RemoteDesktop::{
8    ProcessIdToSessionId, WTSEnumerateProcessesW, WTSFreeMemory, WTSGetActiveConsoleSessionId,
9    WTS_PROCESS_INFOW,
10};
11
12use crate::wide::bounded_string;
13
14const MAX_PROCESS_NAME_UNITS: usize = 32_768;
15const NO_CONSOLE_SESSION: u32 = 0xFFFF_FFFF;
16
17/// The session the calling process runs in.
18pub fn current_session_id() -> io::Result<u32> {
19    process_session_id(std::process::id())
20}
21
22/// The session the process with `pid` runs in.
23pub fn process_session_id(pid: u32) -> io::Result<u32> {
24    let mut session_id = 0;
25    // SAFETY: plain integer in, local `u32` out.
26    if unsafe { ProcessIdToSessionId(pid, &mut session_id) } == 0 {
27        return Err(io::Error::last_os_error());
28    }
29    Ok(session_id)
30}
31
32/// The session attached to the physical console, or `None` while the console
33/// is between sessions (during a user switch, for example).
34pub fn active_console_session_id() -> Option<u32> {
35    // SAFETY: the call takes no arguments.
36    let session = unsafe { WTSGetActiveConsoleSessionId() };
37    (session != NO_CONSOLE_SESSION).then_some(session)
38}
39
40/// One process as Terminal Services reports it.
41#[derive(Clone, Debug, Eq, PartialEq)]
42pub struct SessionProcess {
43    /// The process ID.
44    pub pid: u32,
45    /// The session the process runs in.
46    pub session_id: u32,
47    /// The image name, or `None` when it was unreadable or exceeded a fixed
48    /// bound.
49    pub name: Option<String>,
50}
51
52/// Every process on the local machine with its session, copied out of the
53/// Terminal Services buffer before it is freed.
54pub fn session_processes() -> io::Result<Vec<SessionProcess>> {
55    let mut processes = null_mut();
56    let mut count = 0_u32;
57    // SAFETY: a null server handle means the local machine; both out pointers
58    // are locals that receive a WTS-allocated array and its length.
59    if unsafe { WTSEnumerateProcessesW(null_mut(), 0, 1, &mut processes, &mut count) } == 0 {
60        return Err(io::Error::last_os_error());
61    }
62    let list = WtsProcessList(processes);
63    if count == 0 {
64        return Ok(Vec::new());
65    }
66    if list.0.is_null() {
67        return Err(io::Error::new(
68            io::ErrorKind::InvalidData,
69            "Terminal Services reported processes without a buffer",
70        ));
71    }
72    // SAFETY: WTS returned `count` contiguous entries in `list.0`, which stays
73    // allocated until `list` is dropped after this copy.
74    let entries = unsafe { std::slice::from_raw_parts(list.0, count as usize) };
75    Ok(entries
76        .iter()
77        .map(|entry| SessionProcess {
78            pid: entry.ProcessId,
79            session_id: entry.SessionId,
80            // SAFETY: the name pointer belongs to the same WTS allocation and
81            // is read within a fixed bound.
82            name: unsafe { bounded_string(entry.pProcessName, MAX_PROCESS_NAME_UNITS) },
83        })
84        .collect())
85}
86
87struct WtsProcessList(*mut WTS_PROCESS_INFOW);
88
89impl Drop for WtsProcessList {
90    fn drop(&mut self) {
91        if !self.0.is_null() {
92            // SAFETY: the buffer was allocated by WTSEnumerateProcessesW and is
93            // freed exactly once.
94            unsafe { WTSFreeMemory(self.0.cast()) };
95        }
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use super::{current_session_id, session_processes};
102
103    #[test]
104    fn the_current_process_appears_with_its_session_and_name() {
105        let processes = session_processes().unwrap();
106        let own = processes
107            .iter()
108            .find(|process| process.pid == std::process::id())
109            .expect("the enumerating process is listed");
110        assert!(own.name.as_deref().is_some_and(|name| !name.is_empty()));
111        assert_eq!(own.session_id, current_session_id().unwrap());
112    }
113}