1#![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
17pub fn current_session_id() -> io::Result<u32> {
19 process_session_id(std::process::id())
20}
21
22pub fn process_session_id(pid: u32) -> io::Result<u32> {
24 let mut session_id = 0;
25 if unsafe { ProcessIdToSessionId(pid, &mut session_id) } == 0 {
27 return Err(io::Error::last_os_error());
28 }
29 Ok(session_id)
30}
31
32pub fn active_console_session_id() -> Option<u32> {
35 let session = unsafe { WTSGetActiveConsoleSessionId() };
37 (session != NO_CONSOLE_SESSION).then_some(session)
38}
39
40#[derive(Clone, Debug, Eq, PartialEq)]
42pub struct SessionProcess {
43 pub pid: u32,
45 pub session_id: u32,
47 pub name: Option<String>,
50}
51
52pub fn session_processes() -> io::Result<Vec<SessionProcess>> {
55 let mut processes = null_mut();
56 let mut count = 0_u32;
57 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 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 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 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}