release: prepare GP Connect 3.5.0 with Windows support

This commit is contained in:
Kevin Yue committed 2026-11-19 01:40:22 +08:00
1 parent 6ffb1e8709
commit 43c20d0976
172 files changed
+9629 -1171

No files matched your search

@@ -0,0 +1,42 @@
//! Resolve system collectors from Windows' system directory, never the working directory.
use super::command_runner::run_controlled;
use crate::collection::CollectionControl;
use std::{
io,
path::{Path, PathBuf},
process::{Command, Output},
};
pub struct CollectorCommands<'a> {
control: &'a dyn CollectionControl,
}
impl<'a> CollectorCommands<'a> {
pub fn new(control: &'a dyn CollectionControl) -> Self {
Self { control }
}
pub fn resolve(&self, name: &str) -> Option<PathBuf> {
let system = std::env::var_os("SystemRoot")?;
let path = PathBuf::from(system).join("System32").join(name).with_extension("exe");
path.is_file().then_some(path)
}
pub fn run(&self, name: &str, args: &[&str]) -> io::Result<Option<Output>> {
self.control.check()?;
match self.resolve(name) {
Some(path) => self.run_path(&path, args),
None => Ok(None),
}
}
pub fn run_executable(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
self.run_path(path, args)
}
pub fn run_path(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
self.control.check()?;
let mut command = Command::new(path);
command.args(args);
match run_controlled(command, self.control, 256 * 1024) {
Ok(output) => Ok(Some(output)),
Err(error) if matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) => Ok(None),
Err(error) => Err(error),
}
}
}
@@ -0,0 +1,198 @@
//! Controlled Windows child execution. Pipe polling keeps cancellation responsive.
use crate::collection::CollectionControl;
use std::{
io::{self, Read, Write},
os::windows::io::AsRawHandle,
process::{Child, Command, Output, Stdio},
thread,
time::Duration,
};
use windows_sys::Win32::System::Pipes::PeekNamedPipe;
pub(crate) enum ChildInput<'a> {
Null,
Terminal,
// Preserve the borrowed input type shared by callers without a Windows launcher.
#[allow(dead_code)]
Frame(&'a [u8]),
}
#[derive(Debug)]
pub(crate) struct ObservedOutput {
pub output: Output,
}
pub(crate) fn run_controlled(command: Command, control: &dyn CollectionControl, limit: usize) -> io::Result<Output> {
run_observed(
command,
control,
Some(limit),
&mut |_| {},
&mut io::sink(),
ChildInput::Null,
)
.map(|observed| observed.output)
}
pub(crate) fn run_observed(
mut command: Command,
control: &dyn CollectionControl,
output_limit: Option<usize>,
observer: &mut dyn FnMut(&[u8]),
stderr_sink: &mut dyn Write,
stdin: ChildInput<'_>,
) -> io::Result<ObservedOutput> {
control.check()?;
// Windows desktop processes must not open a console for each helper.
use std::os::windows::process::CommandExt;
if !matches!(stdin, ChildInput::Terminal) {
command.creation_flags(0x08000000); // CREATE_NO_WINDOW
}
command.stdout(if output_limit.is_some() {
Stdio::piped()
} else {
Stdio::inherit()
});
command.stderr(Stdio::piped());
command.stdin(match stdin {
ChildInput::Terminal => Stdio::inherit(),
ChildInput::Null => Stdio::null(),
ChildInput::Frame(_) => Stdio::piped(),
});
let mut child = ControlledChild(command.spawn()?);
let input = if let ChildInput::Frame(frame) = stdin {
let mut pipe = child.0.stdin.take().expect("piped stdin");
let frame = frame.to_vec();
Some(thread::spawn(move || pipe.write_all(&frame)))
} else {
None
};
let mut stdout = child.0.stdout.take();
let mut stderr = child.0.stderr.take().expect("piped stderr");
let mut output = Vec::new();
let mut buffer = [0u8; 8192];
loop {
control.check()?;
if let Some(pipe) = &mut stdout {
let length = read_available(pipe, &mut buffer)?;
if length > output_limit.unwrap().saturating_sub(output.len()) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Command output exceeds its limit",
));
}
output.extend_from_slice(&buffer[..length]);
}
let length = read_available(&mut stderr, &mut buffer)?;
observer(&buffer[..length]);
stderr_sink.write_all(&buffer[..length])?;
if let Some(status) = child.0.try_wait()? {
// Drain the remaining buffered output after the process exits.
if let Some(pipe) = &mut stdout {
loop {
let length = read_available(pipe, &mut buffer)?;
if length == 0 {
break;
}
if length > output_limit.unwrap().saturating_sub(output.len()) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Command output exceeds its limit",
));
}
output.extend_from_slice(&buffer[..length]);
}
}
loop {
let length = read_available(&mut stderr, &mut buffer)?;
if length == 0 {
break;
}
observer(&buffer[..length]);
stderr_sink.write_all(&buffer[..length])?;
}
if let Some(result) = input.and_then(|worker| worker.join().ok()) {
result?;
}
return Ok(ObservedOutput {
output: Output {
status,
stdout: output,
stderr: Vec::new(),
},
});
}
thread::sleep(Duration::from_millis(10));
}
}
fn read_available(pipe: &mut (impl Read + AsRawHandle), buffer: &mut [u8]) -> io::Result<usize> {
let mut available = 0;
let success = unsafe {
PeekNamedPipe(
pipe.as_raw_handle(),
std::ptr::null_mut(),
0,
std::ptr::null_mut(),
&mut available,
std::ptr::null_mut(),
)
};
if success == 0 {
let error = io::Error::last_os_error();
if error.raw_os_error() == Some(109) {
return Ok(0);
} // ERROR_BROKEN_PIPE
return Err(error);
}
let length = buffer.len().min(available as usize);
if length == 0 {
return Ok(0);
}
pipe.read(&mut buffer[..length])
}
struct ControlledChild(Child);
impl Drop for ControlledChild {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn captures_output_and_rejects_excess_output() {
let mut command = Command::new("cmd.exe");
command.args(["/D", "/C", "echo hello"]);
let result = run_controlled(command, &|| Ok(()), 1024).unwrap();
assert!(result.status.success());
assert_eq!(String::from_utf8(result.stdout).unwrap().trim(), "hello");
let mut command = Command::new("cmd.exe");
command.args(["/D", "/C", "echo too much"]);
assert_eq!(
run_controlled(command, &|| Ok(()), 2).unwrap_err().kind(),
io::ErrorKind::InvalidData
);
}
#[test]
fn cancels_a_running_helper() {
let start = std::time::Instant::now();
let mut command = Command::new("powershell.exe");
command.args(["-NoProfile", "-Command", "Start-Sleep -Seconds 30"]);
let control = || {
if start.elapsed() > Duration::from_millis(150) {
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
} else {
Ok(())
}
};
assert_eq!(
run_controlled(command, &control, 1024).unwrap_err().kind(),
io::ErrorKind::Interrupted
);
assert!(start.elapsed() < Duration::from_secs(3));
}
}
@@ -0,0 +1,12 @@
use tokio::process::Command;
/// Windows authentication runs in the interactive user's GUI process.
pub trait CommandExt {
fn into_non_root(self) -> anyhow::Result<Command>;
}
impl CommandExt for Command {
fn into_non_root(self) -> anyhow::Result<Command> {
Ok(self)
}
}
@@ -0,0 +1,309 @@
//! Launch a native worker with the admitted user's primary token and environment.
use std::{
ffi::{OsStr, c_void},
io,
os::windows::{
ffi::OsStrExt,
io::{AsRawHandle, BorrowedHandle, FromRawHandle, OwnedHandle},
},
path::Path,
ptr,
};
use windows_sys::Win32::{
Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT},
Globalization::{CSTR_EQUAL, CompareStringOrdinal},
Security::{ImpersonateLoggedOnUser, RevertToSelf},
System::{
Environment::{CreateEnvironmentBlock, DestroyEnvironmentBlock},
JobObjects::*,
Threading::*,
},
};
pub struct UserProcess {
process: OwnedHandle,
job: Option<OwnedHandle>,
pid: u32,
}
struct Environment(*mut c_void);
impl Drop for Environment {
fn drop(&mut self) {
unsafe {
DestroyEnvironmentBlock(self.0);
}
}
}
fn invalid(message: &str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidInput, message)
}
fn wide(value: &OsStr) -> io::Result<Vec<u16>> {
let value: Vec<_> = value.encode_wide().collect();
if value.contains(&0) {
return Err(invalid("Windows process strings cannot contain NUL"));
}
Ok(value)
}
fn quote(argument: &[u16], output: &mut Vec<u16>) {
output.push(b'"' as u16);
let mut backslashes = 0;
for &character in argument {
if character == b'\\' as u16 {
backslashes += 1;
continue;
}
let count = if character == b'"' as u16 {
backslashes * 2 + 1
} else {
backslashes
};
output.extend(std::iter::repeat_n(b'\\' as u16, count));
output.push(character);
backslashes = 0;
}
output.extend(std::iter::repeat_n(b'\\' as u16, backslashes * 2));
output.push(b'"' as u16);
}
fn command_line(program: &[u16], arguments: &[String]) -> io::Result<Vec<u16>> {
let mut output = Vec::new();
quote(program, &mut output);
for argument in arguments {
output.push(b' ' as u16);
quote(&wide(OsStr::new(argument))?, &mut output);
}
output.push(0);
if output.len() > 32767 {
return Err(invalid("Windows worker command line is too long"));
}
Ok(output)
}
fn key(entry: &[u16]) -> &[u16] {
let end = entry
.iter()
.enumerate()
.find(|(index, value)| *index != 0 && **value == b'=' as u16)
.map(|(index, _)| index)
.unwrap_or(entry.len());
&entry[..end]
}
fn compare(left: &[u16], right: &[u16]) -> std::cmp::Ordering {
// Environment names follow Windows' ordinal, case-insensitive ordering.
unsafe { CompareStringOrdinal(left.as_ptr(), left.len() as i32, right.as_ptr(), right.len() as i32, 1) }
.cmp(&CSTR_EQUAL)
}
fn user_environment(token: BorrowedHandle<'_>, variables: &[(&str, &str)]) -> io::Result<Vec<u16>> {
let mut pointer = ptr::null_mut();
if unsafe { CreateEnvironmentBlock(&mut pointer, token.as_raw_handle(), 0) } == 0 {
return Err(io::Error::last_os_error());
}
let environment = Environment(pointer);
let mut entries = Vec::new();
unsafe {
let mut current = environment.0.cast::<u16>();
while *current != 0 {
let mut length = 0;
while *current.add(length) != 0 {
length += 1;
}
entries.push(std::slice::from_raw_parts(current, length).to_vec());
current = current.add(length + 1);
}
}
for (name, value) in variables {
if name.is_empty() || name.contains('=') {
return Err(invalid("Invalid worker environment name"));
}
let name = wide(OsStr::new(name))?;
let value = wide(OsStr::new(value))?;
entries.retain(|entry| compare(key(entry), &name) != std::cmp::Ordering::Equal);
let mut entry = name;
entry.push(b'=' as u16);
entry.extend(value);
entries.push(entry);
}
entries.sort_by(|left, right| compare(key(left), key(right)));
let mut block = Vec::new();
for entry in entries {
block.extend(entry);
block.push(0);
}
if block.is_empty() {
block.push(0);
}
block.push(0);
Ok(block)
}
impl UserProcess {
/// No service handles or service environment are inherited. The user token
/// determines the Windows session, including an existing interactive desktop.
pub fn launch(
token: BorrowedHandle<'_>,
program: &Path,
arguments: &[String],
variables: &[(&str, &str)],
) -> io::Result<Self> {
if !program.is_absolute() {
return Err(invalid("Windows worker executable must be absolute"));
}
let mut executable = wide(program.as_os_str())?;
let mut command = command_line(&executable, arguments)?;
executable.push(0);
let mut environment = user_environment(token, variables)?;
let directory = program.parent().ok_or_else(|| invalid("Worker directory is missing"))?;
let mut directory = wide(directory.as_os_str())?;
directory.push(0);
let job = unsafe { CreateJobObjectW(ptr::null(), ptr::null()) };
if job.is_null() {
return Err(io::Error::last_os_error());
}
let job = unsafe { OwnedHandle::from_raw_handle(job) };
let limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
BasicLimitInformation: JOBOBJECT_BASIC_LIMIT_INFORMATION {
LimitFlags: JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
..Default::default()
},
..Default::default()
};
if unsafe {
SetInformationJobObject(
job.as_raw_handle(),
JobObjectExtendedLimitInformation,
(&limits as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(),
std::mem::size_of_val(&limits) as u32,
)
} == 0
{
return Err(io::Error::last_os_error());
}
let mut desktop: Vec<u16> = "winsta0\\default".encode_utf16().chain(Some(0)).collect();
let startup = STARTUPINFOW {
cb: std::mem::size_of::<STARTUPINFOW>() as u32,
lpDesktop: desktop.as_mut_ptr(),
..Default::default()
};
let mut information = PROCESS_INFORMATION::default();
// Read/execute the requested image as its user, as Unix exec-after-setuid
// does. The service's filesystem access must not authorize a private image.
if unsafe { ImpersonateLoggedOnUser(token.as_raw_handle()) } == 0 {
return Err(io::Error::last_os_error());
}
struct Revert;
impl Drop for Revert {
fn drop(&mut self) {
if unsafe { RevertToSelf() } == 0 {
std::process::abort();
}
}
}
let revert = Revert;
let created = unsafe {
CreateProcessAsUserW(
token.as_raw_handle(),
executable.as_ptr(),
command.as_mut_ptr(),
ptr::null(),
ptr::null(),
0,
CREATE_UNICODE_ENVIRONMENT | CREATE_SUSPENDED | CREATE_NO_WINDOW,
environment.as_mut_ptr().cast(),
directory.as_ptr(),
&startup,
&mut information,
)
};
let error = (created == 0).then(io::Error::last_os_error);
drop(revert);
if let Some(error) = error {
return Err(error);
}
let process = unsafe { OwnedHandle::from_raw_handle(information.hProcess) };
let thread = unsafe { OwnedHandle::from_raw_handle(information.hThread) };
if unsafe { AssignProcessToJobObject(job.as_raw_handle(), process.as_raw_handle()) } == 0 {
let error = io::Error::last_os_error();
// The suspended child is not owned by the job on this failure path.
unsafe {
TerminateProcess(process.as_raw_handle(), 1);
WaitForSingleObject(process.as_raw_handle(), 5000);
}
return Err(error);
}
let child = Self {
process,
job: Some(job),
pid: information.dwProcessId,
};
if unsafe { ResumeThread(thread.as_raw_handle()) } == u32::MAX {
return Err(io::Error::last_os_error());
}
Ok(child)
}
pub fn id(&self) -> u32 {
self.pid
}
pub fn has_exited(&self) -> io::Result<bool> {
match unsafe { WaitForSingleObject(self.process.as_raw_handle(), 0) } {
WAIT_OBJECT_0 => Ok(true),
WAIT_TIMEOUT => Ok(false),
_ => Err(io::Error::last_os_error()),
}
}
pub fn stop(&mut self) -> io::Result<()> {
if self.job.take().is_none() {
return Ok(());
}
match unsafe { WaitForSingleObject(self.process.as_raw_handle(), 5000) } {
WAIT_OBJECT_0 => Ok(()),
WAIT_TIMEOUT => Err(io::Error::new(
io::ErrorKind::TimedOut,
"Windows worker did not terminate",
)),
_ => Err(io::Error::last_os_error()),
}
}
}
impl Drop for UserProcess {
fn drop(&mut self) {
if let Err(error) = self.stop() {
log::warn!("Could not stop Windows worker: {error}");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use windows_sys::Win32::{Foundation::LocalFree, UI::Shell::CommandLineToArgvW};
#[test]
fn command_line_round_trips_through_windows_parser() {
let program: Vec<u16> = r"C:\Program Files\GP Connect\gpgui-nsh.exe".encode_utf16().collect();
let arguments = [
"proxy-worker",
"",
"space value",
"quoted\"value",
"two\\\\\"quotes",
"trailing\\",
"雪",
"&|<>",
]
.map(String::from);
let command = command_line(&program, &arguments).unwrap();
let mut count = 0;
unsafe {
let parsed = CommandLineToArgvW(command.as_ptr(), &mut count);
assert!(!parsed.is_null());
let result = std::slice::from_raw_parts(parsed, count as usize)
.iter()
.map(|&value| {
let mut length = 0;
while *value.add(length) != 0 {
length += 1;
}
String::from_utf16_lossy(std::slice::from_raw_parts(value, length))
})
.collect::<Vec<_>>();
LocalFree(parsed.cast());
assert_eq!(result[0], String::from_utf16_lossy(&program));
assert_eq!(result[1..], arguments);
}
}
}