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

+18 -3
View File
@@ -13,6 +13,7 @@ pub(crate) struct ConnectArgs {
#[arg(help = "The portal server to connect to")]
pub(super) server: String,
#[cfg(unix)]
#[arg(
long,
conflicts_with = "cookie_only",
@@ -20,6 +21,7 @@ pub(crate) struct ConnectArgs {
)]
pub(crate) background: bool,
#[cfg(unix)]
#[arg(
long,
conflicts_with_all = ["background", "cookie_only"],
@@ -27,6 +29,7 @@ pub(crate) struct ConnectArgs {
)]
pub(crate) dashboard: bool,
#[cfg(unix)]
#[arg(
long,
requires = "background",
@@ -61,18 +64,21 @@ pub(crate) struct ConnectArgs {
)]
pub(super) cookie_cache: Option<String>,
#[cfg(unix)]
#[arg(long, short, help = "The VPNC script to use", required_if_eq("script_tun", "true"))]
pub(super) script: Option<String>,
#[arg(long, short, help = "The IFNAME for tunnel interface")]
pub(super) interface: Option<String>,
#[cfg(unix)]
#[arg(long, short = 'S', help = "Pass traffic to '--script' program, not tun")]
pub(super) script_tun: bool,
#[arg(long, help = "Connect the server as a gateway, instead of a portal")]
pub(super) as_gateway: bool,
#[cfg(unix)]
#[arg(
long,
help = "Enable HIP (Host Information Profile), optionally specify a custom executable",
@@ -81,6 +87,11 @@ pub(crate) struct ConnectArgs {
)]
pub(super) hip: Option<String>,
#[cfg(windows)]
#[arg(long, help = "Generate a HIP (Host Information Profile) report")]
pub(super) hip: bool,
#[cfg(unix)]
#[arg(
long,
help = "Run a custom HIP executable as this user; otherwise inherit the process user"
@@ -100,9 +111,11 @@ pub(crate) struct ConnectArgs {
#[arg(short = 'p', long, help = "The key passphrase of the private key")]
pub(super) key_password: Option<String>,
#[cfg(unix)]
#[arg(long, hide = true)]
pub(super) csd_user: Option<String>,
#[cfg(unix)]
#[arg(long, hide = true)]
pub(super) csd_wrapper: Option<String>,
@@ -188,7 +201,7 @@ pub(crate) struct ConnectArgs {
VPN tunnel. Outputs two lines: COOKIE='<value>' and HOST='<gateway>'. Combine with \
--cookie-cache to avoid re-authenticating when the portal session is still valid."
)]
pub(super) cookie_only: bool,
pub(crate) cookie_only: bool,
}
pub(super) fn build_os_profile(args: &ConnectArgs) -> OsProfile {
@@ -207,17 +220,19 @@ pub(super) fn build_os_profile_with_host_id(args: &ConnectArgs, host_id: Option<
}
pub(super) fn cookie_cache_path(args: &ConnectArgs) -> Option<PathBuf> {
args.cookie_cache.as_deref().map(|path| {
args.cookie_cache.as_deref().and_then(|path| {
let custom = (!path.is_empty()).then_some(path);
cookie_store::cookie_path(custom)
})
}
pub(super) fn warn_deprecated_connect_args(args: &ConnectArgs) {
#[cfg(unix)]
if args.csd_user.is_some() {
warn!("Deprecated option --csd-user will be removed; use --hip-user instead");
}
#[cfg(unix)]
if args.csd_wrapper.is_some() {
warn!("Deprecated option --csd-wrapper will be removed; use --hip instead");
}
@@ -231,7 +246,7 @@ pub(super) fn warn_deprecated_connect_args(args: &ConnectArgs) {
}
}
#[cfg(test)]
#[cfg(all(test, unix))]
mod tests {
use super::*;
+2
View File
@@ -178,6 +178,8 @@ impl ConnectHandler<'_> {
}
}
#[cfg(windows)]
let auth_launcher = auth_launcher.with_windows_cli_launch();
let cred = auth_launcher.cancellation(&self.cancellation).launch().await?;
self.check_cancelled()?;
Ok(cred)
+65 -66
View File
@@ -1,12 +1,12 @@
use std::{
fs,
path::Path,
sync::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
},
use std::sync::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
};
#[cfg(unix)]
use std::{fs, path::Path};
#[cfg(unix)]
use gpapi::process::users::get_user_by_name;
use gpapi::{
clap::report,
cookie_store,
@@ -15,19 +15,22 @@ use gpapi::{
gp_params::GpParams,
os_profile::OsProfile,
portal::{PortalConfig, prelogin},
process::users::get_user_by_name,
session::{GatewayAuthentication, SessionMode},
};
use inquire::Text;
use log::{Level, info, warn};
use openconnect::{HipScript, HipSource, VpnBuilder};
#[cfg(unix)]
use openconnect::HipScript;
use openconnect::{HipSource, VpnBuilder};
use tokio::{runtime::Handle, task::JoinHandle};
use crate::session::{
SessionContextInput, build_session_context, session_info_from_vpn, spawn_session_runtime_with_info,
};
use super::{ConnectHandler, args::cookie_cache_path, vpn_script};
#[cfg(unix)]
use super::tunnel_output::TunnelOutput;
use super::{ConnectHandler, args::cookie_cache_path};
const OPENCONNECT_INTERRUPTED_EXIT_CODE: i32 = -4;
@@ -452,7 +455,10 @@ impl ConnectHandler<'_> {
disable_ipv6: self.args.disable_ipv6,
extension_auth: Some(extension_auth),
});
let vpn_builder = vpn_script::builder(gateway, cookie, self.args)
let vpn_builder = self
.vpn_builder(gateway, cookie)
.map_err(GatewayConnectError::before_establishment)?;
let vpn_builder = vpn_builder
.interface(self.args.interface.clone())
.certificate(certificate)
.sslkey(sslkey)
@@ -487,21 +493,8 @@ impl ConnectHandler<'_> {
let disconnect_requested_on_signal = Arc::clone(&disconnect_requested);
let cancellation = self.cancellation.clone();
let mut background_stdio = self
.background
.as_ref()
.map(|background| background.redirect_stdio())
.transpose()
.map_err(GatewayConnectError::before_establishment)?;
let mut dashboard = if self.args.dashboard {
Some(
crate::dashboard::Dashboard::prepare(gateway.to_owned(), self.cancellation.clone())
.map_err(GatewayConnectError::before_establishment)?,
)
} else {
None
};
#[cfg(unix)]
let mut output = TunnelOutput::prepare(self, gateway).map_err(GatewayConnectError::before_establishment)?;
let monitor = gptunnel::TunnelMonitor::attach(vpn.clone());
let disconnect_task = tokio::spawn(async move {
@@ -511,7 +504,9 @@ impl ConnectHandler<'_> {
vpn_clone.disconnect();
});
#[cfg(unix)]
let lock_file_on_connect = self.shared_args.lock_file.to_path_buf();
#[cfg(unix)]
let pid_written = self.pid_written.clone();
let log_format = self.shared_args.log_format;
let session_cancellation = self.cancellation.clone();
@@ -523,6 +518,7 @@ impl ConnectHandler<'_> {
return;
}
tunnel_established_on_connect.store(true, Ordering::SeqCst);
#[cfg(unix)]
pid_written.store(write_pid_file(&lock_file_on_connect), Ordering::SeqCst);
let _ = established_tx.send(());
@@ -536,7 +532,6 @@ impl ConnectHandler<'_> {
session_task_on_connect.lock().unwrap().replace(task);
})
});
let mut output_error = None;
let connect_result = tokio::select! {
result = &mut worker => result,
established = established_rx => {
@@ -550,23 +545,8 @@ impl ConnectHandler<'_> {
self.logout_gateway(&server).await;
}
}, || {
if let Some(dashboard) = &mut dashboard {
if let Err(error) = dashboard.start_tunnel(monitor.clone()) {
self.cancellation.cancel();
output_error = Some(error);
}
}
if let (Some(background), Some(stdio)) = (&self.background, &mut background_stdio) {
let detach = if self.pid_written.load(Ordering::SeqCst) {
background.detach(stdio)
} else {
Err(anyhow::anyhow!("Cannot detach without a writable PID lock file"))
};
if let Err(error) = detach {
self.cancellation.cancel();
output_error = Some(error);
}
}
#[cfg(unix)]
output.ready(monitor.clone());
}).await
} else {
(&mut worker).await
@@ -574,11 +554,8 @@ impl ConnectHandler<'_> {
}
};
monitor.stop().await;
if let Some(dashboard) = &mut dashboard {
if let Err(error) = dashboard.finish() {
output_error = Some(error);
}
}
#[cfg(unix)]
let output_result = output.finish();
let tunnel_established = tunnel_established.load(Ordering::SeqCst);
disconnect_task.abort();
let _ = disconnect_task.await;
@@ -589,15 +566,15 @@ impl ConnectHandler<'_> {
let _ = task.await;
}
if let Some(error) = output_error {
return Err(GatewayConnectError::after_establishment(error));
}
#[cfg(unix)]
output_result.map_err(GatewayConnectError::after_establishment)?;
let disconnect_requested = disconnect_requested.load(Ordering::SeqCst);
let connect_result = connect_result.map_err(|error| GatewayConnectError::after_establishment(error.into()))?;
classify_openconnect_result(connect_result, tunnel_established, disconnect_requested)
}
#[cfg(unix)]
pub(super) fn hip_source(&self, profile: OsProfile) -> anyhow::Result<HipSource> {
let user = self.determine_hip_user();
let script = self.args.hip.as_ref().or(self.args.csd_wrapper.as_ref());
@@ -605,19 +582,7 @@ impl ConnectHandler<'_> {
Some(path) if !path.is_empty() => Ok(HipSource::Script(HipScript::new(path.clone(), get_uid(&user)?)?)),
Some(_) => {
anyhow::ensure!(user.is_none(), "--hip-user requires an explicit HIP script");
Ok(HipSource::Generator(Arc::new(move |request, control| {
let input = gphip::ReportInput {
profile: profile.clone(),
context: gphip::ReportContext::Connected {
cookie: request.cookie.clone(),
client_ip: request.client_ip.clone(),
client_ipv6: request.client_ipv6.clone(),
md5: request.md5.clone(),
},
};
gphip::generate_report_with_control(&input, &|| control.check())
.map_err(|error| error.downcast::<std::io::Error>().unwrap_or_else(std::io::Error::other))
})))
Ok(generated_hip(profile))
}
None => {
anyhow::ensure!(user.is_none(), "--hip-user requires an explicit HIP script");
@@ -626,6 +591,16 @@ impl ConnectHandler<'_> {
}
}
#[cfg(windows)]
pub(super) fn hip_source(&self, profile: OsProfile) -> anyhow::Result<HipSource> {
Ok(if self.args.hip {
generated_hip(profile)
} else {
HipSource::Disabled
})
}
#[cfg(unix)]
fn determine_hip_user(&self) -> Option<String> {
if let Some(hip_user) = &self.args.hip_user {
return Some(hip_user.clone());
@@ -635,6 +610,22 @@ impl ConnectHandler<'_> {
}
}
fn generated_hip(profile: OsProfile) -> HipSource {
HipSource::Generator(Arc::new(move |request, control| {
let input = gphip::ReportInput {
profile: profile.clone(),
context: gphip::ReportContext::Connected {
cookie: request.cookie.clone(),
client_ip: request.client_ip.clone(),
client_ipv6: request.client_ipv6.clone(),
md5: request.md5.clone(),
},
};
gphip::generate_report_with_control(&input, &|| control.check())
.map_err(|error| error.downcast::<std::io::Error>().unwrap_or_else(std::io::Error::other))
}))
}
async fn wait_for_tunnel_exit(
worker: &mut JoinHandle<i32>,
cleanup: impl std::future::Future<Output = ()>,
@@ -678,10 +669,17 @@ fn classify_openconnect_result(
}
}
#[cfg(unix)]
fn direct_gateway_command(gateway: &str) -> String {
format!("gpauth --gateway {gateway} | sudo gpclient connect {gateway} --as-gateway --cookie-on-stdin")
}
#[cfg(windows)]
fn direct_gateway_command(gateway: &str) -> String {
format!("gpclient.exe connect {gateway} --as-gateway")
}
#[cfg(unix)]
pub(super) fn write_pid_file(lock_file: &Path) -> bool {
let pid = std::process::id();
@@ -694,6 +692,7 @@ pub(super) fn write_pid_file(lock_file: &Path) -> bool {
}
}
#[cfg(unix)]
fn get_uid(user: &Option<String>) -> anyhow::Result<Option<u32>> {
user
.as_ref()
@@ -710,7 +709,7 @@ fn apply_os_profile(builder: VpnBuilder, profile: &OsProfile) -> VpnBuilder {
.user_agent(Some(profile.user_agent().to_string()))
}
#[cfg(test)]
#[cfg(all(test, unix))]
mod tests {
use super::*;
+52 -55
View File
@@ -14,7 +14,7 @@ use gpapi::{
};
use log::{info, warn};
use super::ConnectHandler;
use super::{ConnectHandler, internal_output::InternalOutput};
impl ConnectHandler<'_> {
pub(super) async fn connect_internal_gateways(
@@ -26,6 +26,7 @@ impl ConnectHandler<'_> {
first_session: super::gateway::GatewayLoginSession,
remaining: &[&Gateway],
) -> anyhow::Result<()> {
#[cfg(unix)]
ensure!(
self.background.is_none(),
"--background requires a VPN tunnel; internal non-tunnel sessions must run in the foreground"
@@ -70,11 +71,18 @@ impl ConnectHandler<'_> {
}
self.check_cancelled()?;
let modes = authenticated.iter().map(|(_, session)| session.authentication.mode());
self.enter_non_tunnel_mode(modes)?;
self.run_internal_session(config, &authenticated).await
}
fn enter_non_tunnel_mode(&self, modes: impl Iterator<Item = SessionMode>) -> anyhow::Result<()> {
ensure!(
internal_session_mode(modes)? == SessionMode::NonTunnel,
"Expected non-tunnel authentication"
);
self.run_internal_session(config, &authenticated).await
#[cfg(windows)]
drop(self.shared_args.system_tunnel.take());
Ok(())
}
async fn run_internal_session(
@@ -112,18 +120,7 @@ impl ConnectHandler<'_> {
let source = Arc::new(source);
let validate_network = network.clone();
let validate_detection = detection.clone();
let members = crate::dashboard::InternalMembers::default();
let dashboard_members = members.clone();
let (established_tx, established_rx) = tokio::sync::oneshot::channel();
let established_tx = std::sync::Mutex::new(Some(established_tx));
let mut dashboard = if self.args.dashboard {
Some(crate::dashboard::Dashboard::prepare(
authenticated[0].0.server().to_owned(),
cancellation.clone(),
)?)
} else {
None
};
let (output, observe_status) = InternalOutput::prepare(self, authenticated[0].0.server())?;
let callbacks = SessionCallbacks {
produce_report: Arc::new(move |request, control| {
control.check()?;
@@ -165,16 +162,10 @@ impl ConnectHandler<'_> {
"Internal network — authenticated: {} (IPv4: {:?}, IPv6: {:?})",
member.gateway, member.client_ip, member.client_ipv6
);
if let Some(established) = established_tx.lock().unwrap().take() {
let _ = established.send(());
}
}
state => info!("Internal gateway {}: {state:?}", member.gateway),
}
members.lock().unwrap().insert(
member.gateway.server().to_owned(),
format!("{}: {:?}", member.gateway, member.maintenance),
);
observe_status(&member);
}),
validate_network: Arc::new(move |cancellation| {
let network = validate_network.clone();
@@ -204,43 +195,20 @@ impl ConnectHandler<'_> {
// The PID spans maintenance and cleanup, including initialization before the
// first successful HIP exchange. The outer handler owns final session logout.
#[cfg(unix)]
self.pid_written.store(
super::gateway::write_pid_file(self.shared_args.lock_file),
std::sync::atomic::Ordering::SeqCst,
);
let mut sessions = self.sessions.take();
let mut dashboard_error = None;
let result = {
let maintenance = maintain_non_tunnel_sessions(&mut sessions, policy, callbacks, cancellation, async move {
network_signal.await.unwrap_or(SessionEndReason::NetworkChanged)
});
tokio::pin!(maintenance);
tokio::select! {
result = &mut maintenance => result,
established = established_rx => {
if established.is_ok() {
if let Some(dashboard) = &mut dashboard {
if let Err(error) = dashboard.start_internal(dashboard_members) {
self.cancellation.cancel();
dashboard_error = Some(error);
}
}
}
maintenance.await
}
}
};
if let Some(dashboard) = &mut dashboard {
if let Err(error) = dashboard.finish() {
dashboard_error = Some(error);
}
}
let maintenance = maintain_non_tunnel_sessions(&mut sessions, policy, callbacks, cancellation, async move {
network_signal.await.unwrap_or(SessionEndReason::NetworkChanged)
});
let (result, output_result) = output.run(maintenance).await;
self.sessions.replace(sessions);
monitor_cancel.cancel();
monitor.await.context("Internal network monitor failed")?;
if let Some(error) = dashboard_error {
return Err(error);
}
output_result?;
match result? {
SessionExit::Disconnected => Ok(()),
SessionExit::Failed(reason) => bail!("Internal session ended: {reason:?}. Connect again to authenticate."),
@@ -254,8 +222,7 @@ impl ConnectHandler<'_> {
}
}
fn internal_session_mode(modes: impl Iterator<Item = SessionMode>) -> anyhow::Result<SessionMode> {
let mut modes = modes;
fn internal_session_mode(mut modes: impl Iterator<Item = SessionMode>) -> anyhow::Result<SessionMode> {
let mode = modes.next().context("No internal gateway authenticated successfully")?;
ensure!(
modes.all(|candidate| candidate == mode),
@@ -276,9 +243,39 @@ mod tests {
internal_session_mode([SessionMode::NonTunnel, SessionMode::NonTunnel].into_iter()).unwrap(),
SessionMode::NonTunnel
);
assert_eq!(
internal_session_mode([SessionMode::Tunnel].into_iter()).unwrap(),
SessionMode::Tunnel
}
#[cfg(windows)]
#[test]
#[ignore = "requires the installed Windows machine tunnel directory and administrator privileges"]
fn internal_maintenance_releases_the_machine_tunnel() {
use crate::{cli::SharedArgs, connect::ConnectArgs};
use clap::Parser;
use gpvpnc::windows::SystemTunnel;
#[derive(Parser)]
struct TestArgs {
#[command(flatten)]
connect: ConnectArgs,
}
let args = TestArgs::parse_from(["test", "portal.example.com"]);
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
let shared = SharedArgs {
ignore_tls_errors: false,
system_tunnel: Some(SystemTunnel::acquire().unwrap()).into(),
verbose: &verbose,
log_format: gpapi::log_format::LogFormat::Text,
};
let handler = ConnectHandler::new(&args.connect, &shared);
assert!(
handler
.enter_non_tunnel_mode([SessionMode::Tunnel].into_iter())
.is_err()
);
assert!(SystemTunnel::try_acquire().unwrap().is_none());
handler
.enter_non_tunnel_mode([SessionMode::NonTunnel].into_iter())
.unwrap();
assert!(SystemTunnel::try_acquire().unwrap().is_some());
}
}
@@ -0,0 +1,73 @@
use std::{future::Future, sync::Mutex};
use gpapi::session::{GatewaySessionSummary, MaintenanceState};
use tokio::sync::oneshot;
use tokio_util::sync::CancellationToken;
use crate::dashboard::{Dashboard, InternalMembers};
use super::ConnectHandler;
pub(super) struct InternalOutput(Option<DashboardState>);
struct DashboardState {
dashboard: Dashboard,
members: InternalMembers,
established: oneshot::Receiver<()>,
cancellation: CancellationToken,
}
impl InternalOutput {
pub(super) fn prepare(
handler: &ConnectHandler<'_>,
gateway: &str,
) -> anyhow::Result<(Self, impl Fn(&GatewaySessionSummary) + Send + Sync + 'static + use<>)> {
let (sender, established) = oneshot::channel();
let established_sender = Mutex::new(Some(sender));
let members = InternalMembers::default();
let dashboard_members = members.clone();
let output = if handler.args.dashboard {
Some(DashboardState {
dashboard: Dashboard::prepare(gateway.to_owned(), handler.cancellation.clone())?,
members,
established,
cancellation: handler.cancellation.clone(),
})
} else {
None
};
let observe = move |member: &GatewaySessionSummary| {
if member.maintenance == MaintenanceState::Healthy
&& let Some(ready) = established_sender.lock().unwrap().take()
{
let _ = ready.send(());
}
dashboard_members.lock().unwrap().insert(
member.gateway.server().to_owned(),
format!("{}: {:?}", member.gateway, member.maintenance),
);
};
Ok((Self(output), observe))
}
pub(super) async fn run<T>(self, maintenance: impl Future<Output = T>) -> (T, anyhow::Result<()>) {
let Some(mut output) = self.0 else {
return (maintenance.await, Ok(()));
};
let mut start = Ok(());
tokio::pin!(maintenance);
let result = tokio::select! {
result = &mut maintenance => result,
established = &mut output.established => {
if established.is_ok() {
start = output.dashboard.start_internal(output.members);
if start.is_err() {
output.cancellation.cancel();
}
}
maintenance.await
}
};
(result, output.dashboard.finish().and(start))
}
}
@@ -0,0 +1,20 @@
use std::future::Future;
use gpapi::session::GatewaySessionSummary;
use super::ConnectHandler;
pub(super) struct InternalOutput;
impl InternalOutput {
pub(super) fn prepare(
_: &ConnectHandler<'_>,
_: &str,
) -> anyhow::Result<(Self, impl Fn(&GatewaySessionSummary) + Send + Sync + 'static + use<>)> {
Ok((Self, |_: &GatewaySessionSummary| {}))
}
pub(super) async fn run<T>(self, maintenance: impl Future<Output = T>) -> (T, anyhow::Result<()>) {
(maintenance.await, Ok(()))
}
}
+16 -1
View File
@@ -1,12 +1,21 @@
mod args;
mod credential;
#[cfg(test)]
#[cfg(all(test, unix))]
mod flow_tests;
mod gateway;
mod internal;
#[cfg(unix)]
#[path = "internal_output/unix.rs"]
mod internal_output;
#[cfg(windows)]
#[path = "internal_output/windows.rs"]
mod internal_output;
#[cfg(unix)]
mod tunnel_output;
mod vpn_script;
use std::cell::RefCell;
#[cfg(unix)]
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
@@ -46,7 +55,9 @@ pub(crate) struct ConnectHandler<'a> {
auth_attempt_fixture: RefCell<credential::AuthAttemptFixture>,
auth_recovery: RefCell<gpapi::process::rendering_recovery::RecoveryState>,
sessions: RefCell<GatewaySessions>,
#[cfg(unix)]
pid_written: Arc<AtomicBool>,
#[cfg(unix)]
background: Option<crate::background::BackgroundWorker>,
}
@@ -72,11 +83,14 @@ impl<'a> ConnectHandler<'a> {
auth_attempt_fixture: Default::default(),
auth_recovery: RefCell::default(),
sessions: RefCell::default(),
#[cfg(unix)]
pid_written: Arc::default(),
#[cfg(unix)]
background: None,
}
}
#[cfg(unix)]
pub(crate) fn with_background(mut self, background: Option<crate::background::BackgroundWorker>) -> Self {
self.background = background;
self
@@ -134,6 +148,7 @@ impl<'a> ConnectHandler<'a> {
} else {
sessions.logout().await;
}
#[cfg(unix)]
if self.pid_written.load(Ordering::SeqCst) {
if let Err(error) = std::fs::remove_file(self.shared_args.lock_file) {
warn!("Failed to remove PID file: {error}");
@@ -0,0 +1,74 @@
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
use gptunnel::TunnelMonitor;
use tokio_util::sync::CancellationToken;
use crate::{
background::{BackgroundStdio, BackgroundWorker},
dashboard::Dashboard,
};
use super::ConnectHandler;
pub(super) struct TunnelOutput<'a> {
background: Option<(&'a BackgroundWorker, BackgroundStdio)>,
dashboard: Option<Dashboard>,
pid_written: &'a AtomicBool,
cancellation: &'a CancellationToken,
error: Option<anyhow::Error>,
}
impl<'a> TunnelOutput<'a> {
pub(super) fn prepare(handler: &'a ConnectHandler<'_>, gateway: &str) -> anyhow::Result<Self> {
let background = handler
.background
.as_ref()
.map(|worker| worker.redirect_stdio().map(|stdio| (worker, stdio)))
.transpose()?;
let dashboard = handler
.args
.dashboard
.then(|| Dashboard::prepare(gateway.to_owned(), handler.cancellation.clone()))
.transpose()?;
Ok(Self {
background,
dashboard,
pid_written: &handler.pid_written,
cancellation: &handler.cancellation,
error: None,
})
}
pub(super) fn ready(&mut self, monitor: Arc<TunnelMonitor>) {
if let Some(dashboard) = &mut self.dashboard
&& let Err(error) = dashboard.start_tunnel(monitor)
{
self.cancellation.cancel();
self.error = Some(error);
}
if let Some((worker, stdio)) = &mut self.background {
let detach = if self.pid_written.load(Ordering::SeqCst) {
worker.detach(stdio)
} else {
Err(anyhow::anyhow!("Cannot detach without a writable PID lock file"))
};
if let Err(error) = detach {
self.cancellation.cancel();
self.error = Some(error);
}
}
}
pub(super) fn finish(&mut self) -> anyhow::Result<()> {
if let Some(dashboard) = &mut self.dashboard {
dashboard.finish()?;
}
match self.error.take() {
Some(error) => Err(error),
None => Ok(()),
}
}
}
@@ -1,9 +1,13 @@
use openconnect::{Vpn, VpnBuilder};
use crate::connect::ConnectArgs;
use crate::connect::ConnectHandler;
pub(crate) fn builder(server: &str, cookie: &str, args: &ConnectArgs) -> VpnBuilder {
Vpn::builder(server, cookie)
.script(args.script.clone())
.script_tun(args.script_tun)
impl ConnectHandler<'_> {
pub(in crate::connect) fn vpn_builder(&self, server: &str, cookie: &str) -> anyhow::Result<VpnBuilder> {
Ok(
Vpn::builder(server, cookie)
.script(self.args.script.clone())
.script_tun(self.args.script_tun),
)
}
}
+11 -4
View File
@@ -2,11 +2,18 @@ use std::ffi::OsStr;
use openconnect::{Vpn, VpnBuilder};
use crate::connect::ConnectArgs;
use crate::connect::{ConnectArgs, ConnectHandler};
pub(crate) fn builder(server: &str, cookie: &str, args: &ConnectArgs) -> VpnBuilder {
let configured_script = std::env::var_os("GP_VPNC_SCRIPT");
configure_builder(server, cookie, args, configured_script.as_deref())
impl ConnectHandler<'_> {
pub(in crate::connect) fn vpn_builder(&self, server: &str, cookie: &str) -> anyhow::Result<VpnBuilder> {
let configured_script = std::env::var_os("GP_VPNC_SCRIPT");
Ok(configure_builder(
server,
cookie,
self.args,
configured_script.as_deref(),
))
}
}
fn configure_builder(server: &str, cookie: &str, args: &ConnectArgs, configured_script: Option<&OsStr>) -> VpnBuilder {
+4 -2
View File
@@ -1,8 +1,10 @@
#[cfg(target_os = "macos")]
#[path = "macos.rs"]
mod platform;
#[cfg(not(target_os = "macos"))]
#[cfg(all(unix, not(target_os = "macos")))]
#[path = "default.rs"]
mod platform;
pub(super) use platform::builder;
#[cfg(windows)]
#[path = "windows.rs"]
mod platform;
@@ -0,0 +1,23 @@
use std::sync::Mutex;
use openconnect::{Vpn, VpnBuilder};
use crate::connect::ConnectHandler;
impl ConnectHandler<'_> {
pub(in crate::connect) fn vpn_builder(&self, server: &str, cookie: &str) -> anyhow::Result<VpnBuilder> {
let owner = self.shared_args.system_tunnel.borrow();
let tunnel = owner
.as_ref()
.ok_or_else(|| anyhow::anyhow!("System tunnel ownership is unavailable"))?;
let network = Mutex::new(tunnel.configurator()?);
Ok(
Vpn::builder(server, cookie).network_configuration_handler(move |configuration| {
network
.lock()
.map_err(|_| std::io::Error::other("Windows network state is unavailable"))?
.configure(&configuration.reason, &configuration.environment)
}),
)
}
}