Release 3.6.0

This commit is contained in:
Kevin Yue committed 2026-11-19 23:44:43 +08:00
1 parent 92c19c55a3
commit eb3cebf8a9
58 files changed
+2191 -642

No files matched your search

+29 -8
View File
@@ -1,5 +1,5 @@
//! Adapter DNS settings and Windows name-resolution policy scoped to this connection.
use super::configuration::Configuration;
use super::{SystemTunnel, configuration::Configuration};
use base64::Engine;
use serde_json::json;
use std::{
@@ -23,6 +23,7 @@ pub(super) struct Installed {
guid: GUID,
snapshot: Option<Snapshot>,
tag: Option<String>,
tunnel: Option<SystemTunnel>,
}
fn check(status: u32) -> io::Result<()> {
if status == 0 {
@@ -77,7 +78,7 @@ impl Snapshot {
}
}
impl Installed {
pub fn apply(configuration: &Configuration) -> io::Result<Self> {
pub fn apply(configuration: &Configuration, recovery_key: &str, tunnel: Option<&SystemTunnel>) -> io::Result<Self> {
let mut luid = NET_LUID_LH::default();
let mut guid = GUID::default();
check(unsafe { ConvertInterfaceIndexToLuid(configuration.interface, &mut luid) })?;
@@ -86,6 +87,7 @@ impl Installed {
guid,
snapshot: Some(Snapshot::capture(guid)?),
tag: None,
tunnel: tunnel.cloned(),
};
Snapshot {
domain: configuration.domains.first().cloned().unwrap_or_default(),
@@ -105,9 +107,13 @@ impl Installed {
.map(|domain| format!(".{}", domain.trim_matches('.')))
.collect()
};
let tag = format!("GPConnect:{}", uuid::Uuid::new_v4());
let tag = match tunnel {
Some(_) => format!("GPConnect:{}", uuid::Uuid::new_v4()),
None => journal_tag(recovery_key),
};
installed.tag = Some(tag.clone());
policy(
tunnel,
json!({"operation":"add", "tag":tag, "namespaces":namespaces, "servers":configuration.servers.iter().map(ToString::to_string).collect::<Vec<_>>()}),
)?;
}
@@ -116,7 +122,7 @@ impl Installed {
pub fn restore(&mut self) -> io::Result<()> {
let mut failure = None;
if let Some(tag) = self.tag.take() {
if let Err(error) = policy(json!({"operation":"remove", "tag":tag})) {
if let Err(error) = policy(self.tunnel.as_ref(), json!({"operation":"remove", "tag":tag})) {
log::warn!("Could not remove VPN DNS policy: {error}");
failure = Some(error);
}
@@ -140,21 +146,36 @@ impl Drop for Installed {
/// A crashed service cannot run Drop. Remove only GP Connect's tagged policies
/// before accepting a new connection; adapter rows disappear with Wintun itself.
pub(super) fn clear_stale_policies() -> io::Result<()> {
policy(json!({"operation":"clear-stale"}))
pub(super) fn clear_stale_policies(tunnel: &SystemTunnel) -> io::Result<()> {
policy(Some(tunnel), json!({"operation":"clear-stale"}))
}
fn policy(request: serde_json::Value) -> io::Result<()> {
// Keep isolated journals outside the GPConnect:* namespace used by system recovery.
fn journal_tag(recovery_key: &str) -> String {
format!("GPConnectJournal:{recovery_key}")
}
pub(super) fn remove_journal_policy(recovery_key: &str) -> io::Result<()> {
policy(None, json!({"operation":"remove", "tag":journal_tag(recovery_key)}))
}
fn policy(tunnel: Option<&SystemTunnel>, request: serde_json::Value) -> io::Result<()> {
const SCRIPT: &str = include_str!("dns-policy.ps1");
let encoded = base64::engine::general_purpose::STANDARD
.encode(SCRIPT.encode_utf16().flat_map(u16::to_le_bytes).collect::<Vec<_>>());
let root =
std::env::var_os("SystemRoot").ok_or_else(|| io::Error::other("Windows system directory is unavailable"))?;
let executable = std::path::PathBuf::from(root).join("System32/WindowsPowerShell/v1.0/powershell.exe");
// The script produces no standard output. Use that handle to give the worker
// a copy of the lease so it keeps ownership if the tunnel process dies.
let stdout = match tunnel {
Some(tunnel) => Stdio::from(tunnel.duplicate_lock()?),
None => Stdio::null(),
};
let mut child = Command::new(executable)
.args(["-NoProfile", "-NonInteractive", "-EncodedCommand", &encoded])
.creation_flags(CREATE_NO_WINDOW)
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stdout(stdout)
.stderr(Stdio::piped())
.spawn()?;
let input = child
+17 -4
View File
@@ -3,24 +3,32 @@ mod configuration;
mod dns;
mod ip_helper;
mod recovery;
mod system_tunnel;
use configuration::Configuration;
use std::io;
pub use system_tunnel::SystemTunnel;
pub struct NetworkConfigurator {
connection: Option<Connection>,
recovery_key: String,
system_tunnel: Option<SystemTunnel>,
}
struct Connection {
dns: dns::Installed,
network: ip_helper::Installed,
}
impl NetworkConfigurator {
/// The owner supplies an HKLM key under its administrator-controlled namespace.
/// Use a separate HKLM journal and DNS tag for an isolated network configuration.
pub fn new(recovery_key: &str) -> io::Result<Self> {
Self::with_owner(recovery_key, None)
}
fn with_owner(recovery_key: &str, system_tunnel: Option<SystemTunnel>) -> io::Result<Self> {
recovery::Journal::begin(recovery_key)?;
Ok(Self {
connection: None,
recovery_key: recovery_key.into(),
system_tunnel,
})
}
pub fn configure(&mut self, reason: &str, environment: &[(String, Option<String>)]) -> io::Result<()> {
@@ -30,7 +38,7 @@ impl NetworkConfigurator {
let configuration = Configuration::parse(environment)?;
self.disconnect()?;
let network = ip_helper::Installed::apply(&configuration, &self.recovery_key)?;
let dns = dns::Installed::apply(&configuration)?;
let dns = dns::Installed::apply(&configuration, &self.recovery_key, self.system_tunnel.as_ref())?;
self.connection = Some(Connection { dns, network });
Ok(())
}
@@ -52,13 +60,18 @@ impl NetworkConfigurator {
}
}
/// Restore process-owned physical routes and DNS policy before service admission.
/// Recover an isolated journal and only the DNS rules recorded under its name.
pub fn recover(recovery_key: &str) -> io::Result<()> {
recover_routes(recovery_key)?;
dns::remove_journal_policy(recovery_key)
}
fn recover_routes(recovery_key: &str) -> io::Result<()> {
if let Some(journal) = recovery::Journal::open(recovery_key)? {
for (name, route) in journal.routes()? {
ip_helper::recover_route(&route)?;
journal.forget(&name)?;
}
}
dns::clear_stale_policies()
Ok(())
}
@@ -0,0 +1,85 @@
use super::NetworkConfigurator;
use std::{
ffi::OsString,
fs::{File, OpenOptions},
io,
os::windows::{ffi::OsStringExt, fs::OpenOptionsExt},
path::PathBuf,
ptr,
sync::Arc,
};
use windows_sys::Win32::{
Foundation::ERROR_SHARING_VIOLATION,
UI::Shell::{CSIDL_COMMON_APPDATA, SHGetFolderPathW},
};
const RECOVERY_KEY: &str = r"SOFTWARE\GP Connect\NetworkRecovery";
/// Exclusive ownership of the installed Windows system tunnel, including recovery.
#[derive(Clone)]
pub struct SystemTunnel {
lock: Arc<File>,
}
impl SystemTunnel {
pub fn try_acquire() -> io::Result<Option<Self>> {
let path = machine_data()?.join(r"GP Connect\Private\system-tunnel.lock");
let file = match OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.share_mode(0)
.open(path)
{
Ok(file) => file,
Err(error) if error.raw_os_error() == Some(ERROR_SHARING_VIOLATION as i32) => return Ok(None),
Err(error) => return Err(error),
};
let tunnel = Self { lock: Arc::new(file) };
super::recover_routes(RECOVERY_KEY)?;
super::dns::clear_stale_policies(&tunnel)?;
Ok(Some(tunnel))
}
pub fn acquire() -> io::Result<Self> {
Self::try_acquire()?.ok_or_else(|| {
io::Error::new(
io::ErrorKind::WouldBlock,
"Another GP Connect system tunnel or installer is active. Disconnect the tunnel or wait for setup to finish.",
)
})
}
pub fn configurator(&self) -> io::Result<NetworkConfigurator> {
NetworkConfigurator::with_owner(RECOVERY_KEY, Some(self.clone()))
}
pub(super) fn duplicate_lock(&self) -> io::Result<File> {
self.lock.try_clone()
}
}
fn machine_data() -> io::Result<PathBuf> {
let mut path = [0; 260];
let result = unsafe {
SHGetFolderPathW(
ptr::null_mut(),
CSIDL_COMMON_APPDATA as i32,
ptr::null_mut(),
0,
path.as_mut_ptr(),
)
};
if result < 0 {
return Err(io::Error::other(format!(
"Windows ProgramData lookup failed ({result:#x})"
)));
}
let length = path
.iter()
.position(|&c| c == 0)
.filter(|&n| n > 0)
.ok_or_else(|| io::Error::other("Windows ProgramData path is unavailable"))?;
Ok(PathBuf::from(OsString::from_wide(&path[..length])))
}