mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 06:26:14 -05:00
feat(windows): support gpclient authentication and VPN connections
This commit is contained in:
49 files changed
+1888
-390
No files matched your search
+109
-41
@@ -1,8 +1,10 @@
|
||||
#[cfg(unix)]
|
||||
use std::{
|
||||
path::{Path, PathBuf},
|
||||
str::FromStr,
|
||||
};
|
||||
|
||||
#[cfg(unix)]
|
||||
use anyhow::bail;
|
||||
use clap::{Parser, Subcommand};
|
||||
use gpapi::{
|
||||
@@ -10,17 +12,22 @@ use gpapi::{
|
||||
log_format::{LogFormat, write_json_record},
|
||||
};
|
||||
use log::info;
|
||||
#[cfg(unix)]
|
||||
use sysinfo::{Pid, System};
|
||||
#[cfg(unix)]
|
||||
use tokio::fs;
|
||||
|
||||
#[cfg(unix)]
|
||||
use crate::{
|
||||
GP_CLIENT_LOCK_FILE,
|
||||
connect::{ConnectArgs, ConnectHandler},
|
||||
diagnostics::DiagnosticsArgs,
|
||||
disconnect::{DisconnectArgs, DisconnectHandler},
|
||||
hip::{HipArgs, HipHandler},
|
||||
launch_gui::{LaunchGuiArgs, LaunchGuiHandler},
|
||||
};
|
||||
use crate::{
|
||||
connect::{ConnectArgs, ConnectHandler},
|
||||
hip::{HipArgs, HipHandler},
|
||||
};
|
||||
|
||||
const VERSION: &str = concat!(
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
@@ -33,7 +40,10 @@ const VERSION: &str = concat!(
|
||||
|
||||
pub(crate) struct SharedArgs<'a> {
|
||||
pub(crate) ignore_tls_errors: bool,
|
||||
#[cfg(unix)]
|
||||
pub(crate) lock_file: &'a Path,
|
||||
#[cfg(windows)]
|
||||
pub(crate) system_tunnel: std::cell::RefCell<Option<gpvpnc::windows::SystemTunnel>>,
|
||||
pub(crate) verbose: &'a InfoLevelVerbosity,
|
||||
pub(crate) log_format: LogFormat,
|
||||
}
|
||||
@@ -42,12 +52,15 @@ pub(crate) struct SharedArgs<'a> {
|
||||
enum CliCommand {
|
||||
#[command(about = "Connect to a portal server")]
|
||||
Connect(Box<ConnectArgs>),
|
||||
#[cfg(unix)]
|
||||
#[command(about = "Disconnect from the server")]
|
||||
Disconnect(DisconnectArgs),
|
||||
#[cfg(unix)]
|
||||
#[command(about = "Launch the GUI")]
|
||||
LaunchGui(LaunchGuiArgs),
|
||||
#[command(about = "Generate HIP report")]
|
||||
Hip(HipArgs),
|
||||
#[cfg(unix)]
|
||||
#[command(about = "Collect system diagnostics for a bug report without connecting to a VPN")]
|
||||
Diagnostics(DiagnosticsArgs),
|
||||
#[command(hide = true)]
|
||||
@@ -89,11 +102,12 @@ struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: CliCommand,
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
#[arg(long, hide = true)]
|
||||
fix_openssl: bool,
|
||||
#[arg(long, help = "Ignore the TLS errors")]
|
||||
ignore_tls_errors: bool,
|
||||
#[cfg(unix)]
|
||||
#[arg(
|
||||
long,
|
||||
global = true,
|
||||
@@ -102,6 +116,7 @@ struct Cli {
|
||||
)]
|
||||
lock_file: PathBuf,
|
||||
|
||||
#[cfg(unix)]
|
||||
#[arg(long, hide = true, global = true)]
|
||||
background_worker_fd: Option<i32>,
|
||||
|
||||
@@ -128,6 +143,7 @@ impl Args for Cli {
|
||||
}
|
||||
|
||||
impl Cli {
|
||||
#[cfg(unix)]
|
||||
fn can_run_alongside_client(&self) -> bool {
|
||||
match &self.command {
|
||||
CliCommand::Connect(_) => false,
|
||||
@@ -136,6 +152,7 @@ impl Cli {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
async fn is_running(&self) -> bool {
|
||||
let Ok(c) = fs::read_to_string(&self.lock_file).await else {
|
||||
return false;
|
||||
@@ -156,50 +173,67 @@ impl Cli {
|
||||
}
|
||||
|
||||
async fn run(&self) -> anyhow::Result<()> {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
if self.fix_openssl
|
||||
&& !(matches!(&self.command, CliCommand::Connect(args) if args.background) && self.background_worker_fd.is_none())
|
||||
{
|
||||
log::warn!("--fix-openssl is deprecated and has no effect. It will be removed in a future release.");
|
||||
}
|
||||
|
||||
if let CliCommand::Connect(args) = &self.command {
|
||||
if args.dashboard {
|
||||
crate::dashboard::validate(self.log_format)?;
|
||||
#[cfg(unix)]
|
||||
let background_worker = {
|
||||
if let CliCommand::Connect(args) = &self.command {
|
||||
if args.dashboard {
|
||||
crate::dashboard::validate(self.log_format)?;
|
||||
}
|
||||
}
|
||||
if self.background_worker_fd.is_some() && !matches!(&self.command, CliCommand::Connect(args) if args.background) {
|
||||
bail!("Background worker requires connect --background");
|
||||
}
|
||||
if let CliCommand::Diagnostics(args) = &self.command {
|
||||
return args.run(VERSION).await;
|
||||
}
|
||||
}
|
||||
if self.background_worker_fd.is_some() && !matches!(&self.command, CliCommand::Connect(args) if args.background) {
|
||||
bail!("Background worker requires connect --background");
|
||||
}
|
||||
if let CliCommand::Diagnostics(args) = &self.command {
|
||||
return args.run(VERSION).await;
|
||||
}
|
||||
|
||||
// check if an instance is running
|
||||
if !self.can_run_alongside_client() && self.is_running().await {
|
||||
bail!("Another instance of the client is already running");
|
||||
}
|
||||
// check if an instance is running
|
||||
if !self.can_run_alongside_client() && self.is_running().await {
|
||||
bail!("Another instance of the client is already running");
|
||||
}
|
||||
|
||||
let background_worker = if let CliCommand::Connect(args) = &self.command {
|
||||
if args.background {
|
||||
let log_file = args
|
||||
.log_file
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| Path::new("/var/log/gpclient.log"));
|
||||
match self.background_worker_fd {
|
||||
Some(fd) => Some(crate::background::BackgroundWorker::new(fd, log_file)?),
|
||||
None => return crate::background::start(log_file, self.log_format).await,
|
||||
if let CliCommand::Connect(args) = &self.command {
|
||||
if args.background {
|
||||
let log_file = args
|
||||
.log_file
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| Path::new("/var/log/gpclient.log"));
|
||||
match self.background_worker_fd {
|
||||
Some(fd) => Some(crate::background::BackgroundWorker::new(fd, log_file)?),
|
||||
None => return crate::background::start(log_file, self.log_format).await,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
#[cfg(windows)]
|
||||
let system_tunnel = match &self.command {
|
||||
CliCommand::Connect(args) if !args.cookie_only => {
|
||||
anyhow::ensure!(
|
||||
gpapi::windows::is_elevated()?,
|
||||
"Run gpclient connect from an administrator terminal"
|
||||
);
|
||||
Some(gpvpnc::windows::SystemTunnel::acquire()?)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let shared_args = SharedArgs {
|
||||
ignore_tls_errors: self.ignore_tls_errors,
|
||||
#[cfg(unix)]
|
||||
lock_file: &self.lock_file,
|
||||
#[cfg(windows)]
|
||||
system_tunnel: system_tunnel.into(),
|
||||
verbose: &self.verbose,
|
||||
log_format: self.log_format,
|
||||
};
|
||||
@@ -210,14 +244,17 @@ impl Cli {
|
||||
|
||||
match &self.command {
|
||||
CliCommand::Connect(args) => {
|
||||
ConnectHandler::new(args, &shared_args)
|
||||
.with_background(background_worker)
|
||||
.handle()
|
||||
.await
|
||||
let handler = ConnectHandler::new(args, &shared_args);
|
||||
#[cfg(unix)]
|
||||
let handler = handler.with_background(background_worker);
|
||||
handler.handle().await
|
||||
}
|
||||
#[cfg(unix)]
|
||||
CliCommand::Disconnect(args) => DisconnectHandler::new(args, shared_args.lock_file).handle().await,
|
||||
#[cfg(unix)]
|
||||
CliCommand::LaunchGui(args) => LaunchGuiHandler::new(args).handle().await,
|
||||
CliCommand::Hip(args) => HipHandler::new(args).handle().await,
|
||||
#[cfg(unix)]
|
||||
CliCommand::Diagnostics(_) => unreachable!("diagnostics is dispatched before VPN setup"),
|
||||
CliCommand::DetectInternalHost { address, hostname } => {
|
||||
let internal = gpapi::session::desktop::network::native::detect_in_helper(*address, hostname)?;
|
||||
@@ -250,17 +287,20 @@ fn build_logger(cli: &Cli) -> env_logger::Builder {
|
||||
builder
|
||||
}
|
||||
|
||||
pub(crate) async fn run() {
|
||||
let cli = Cli::parse();
|
||||
|
||||
fn initialize_logger(cli: &Cli) {
|
||||
#[cfg(unix)]
|
||||
if matches!(&cli.command, CliCommand::Connect(args) if args.dashboard) {
|
||||
let logger = build_logger(&cli).build();
|
||||
let logger = build_logger(cli).build();
|
||||
log::set_max_level(logger.filter());
|
||||
log::set_boxed_logger(Box::new(crate::dashboard::NoticeLogger::new(logger))).expect("failed to initialize logger");
|
||||
} else {
|
||||
build_logger(&cli).init();
|
||||
return;
|
||||
}
|
||||
build_logger(cli).init();
|
||||
}
|
||||
|
||||
pub(crate) async fn run() {
|
||||
let cli = Cli::parse();
|
||||
initialize_logger(&cli);
|
||||
info!("gpclient started: {}", VERSION);
|
||||
|
||||
if let Err(err) = cli.run().await {
|
||||
@@ -269,7 +309,7 @@ pub(crate) async fn run() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use std::{
|
||||
io::Write,
|
||||
@@ -360,7 +400,7 @@ mod tests {
|
||||
fn diagnostics_accepts_output_options_and_runs_alongside_the_client() {
|
||||
let cli = Cli::try_parse_from([
|
||||
"gpclient",
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
"--fix-openssl",
|
||||
"diagnostics",
|
||||
"--json",
|
||||
@@ -593,3 +633,31 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, windows))]
|
||||
mod windows_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn terminal_auth_and_generated_hip_are_available() {
|
||||
assert!(Cli::try_parse_from(["gpclient", "connect", "vpn.example.com", "--cookie-only", "--hip"]).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unix_only_workflows_are_unavailable() {
|
||||
for flag in [
|
||||
"--background",
|
||||
"--dashboard",
|
||||
"--lock-file",
|
||||
"--script",
|
||||
"--hip-user",
|
||||
"--script-tun",
|
||||
] {
|
||||
assert!(
|
||||
Cli::try_parse_from(["gpclient", "connect", "vpn.example.com", flag]).is_err(),
|
||||
"{flag}"
|
||||
);
|
||||
}
|
||||
assert!(Cli::try_parse_from(["gpclient", "disconnect"]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -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::*;
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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::*;
|
||||
|
||||
|
||||
@@ -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(()))
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,19 @@
|
||||
#[cfg(unix)]
|
||||
mod background;
|
||||
mod cli;
|
||||
mod connect;
|
||||
#[cfg(unix)]
|
||||
mod dashboard;
|
||||
#[cfg(unix)]
|
||||
mod diagnostics;
|
||||
#[cfg(unix)]
|
||||
mod disconnect;
|
||||
mod hip;
|
||||
#[cfg(unix)]
|
||||
mod launch_gui;
|
||||
mod session;
|
||||
|
||||
#[cfg(unix)]
|
||||
pub(crate) const GP_CLIENT_LOCK_FILE: &str = "/var/run/gpclient.lock";
|
||||
|
||||
#[tokio::main]
|
||||
|
||||
@@ -75,8 +75,7 @@ async fn run_session_runtime(session_ctx: SessionContext, mut session_info: Sess
|
||||
|
||||
tokio::time::sleep(schedule.delay).await;
|
||||
|
||||
crate::dashboard::session_notice(Level::Warn, &schedule.message);
|
||||
report(log_format, Level::Warn, &format!("\nWARNING: {}", schedule.message));
|
||||
report_session_notice(log_format, Level::Warn, &schedule.message);
|
||||
|
||||
if !schedule.should_auto_extend {
|
||||
info!("Session extension is not allowed by the gateway");
|
||||
@@ -91,8 +90,7 @@ async fn run_session_runtime(session_ctx: SessionContext, mut session_info: Sess
|
||||
return;
|
||||
};
|
||||
|
||||
crate::dashboard::session_notice(Level::Info, "Session extended.");
|
||||
report(log_format, Level::Info, "Session extended.");
|
||||
report_session_notice(log_format, Level::Info, "Session extended.");
|
||||
session_info = next_session_info;
|
||||
}
|
||||
Err(err) => {
|
||||
@@ -108,6 +106,16 @@ async fn run_session_runtime(session_ctx: SessionContext, mut session_info: Sess
|
||||
}
|
||||
}
|
||||
|
||||
fn report_session_notice(log_format: LogFormat, level: Level, message: &str) {
|
||||
#[cfg(unix)]
|
||||
crate::dashboard::session_notice(level, message);
|
||||
if level == Level::Warn {
|
||||
report(log_format, level, &format!("\nWARNING: {message}"));
|
||||
} else {
|
||||
report(log_format, level, message);
|
||||
}
|
||||
}
|
||||
|
||||
fn build_session_warning_schedule(session_info: &SessionInfo) -> Option<SessionWarningSchedule> {
|
||||
let warning = session_info.lifetime_warning.as_ref()?;
|
||||
let warning_secs = if let Some(user_expires) = session_info.user_expires {
|
||||
@@ -149,6 +157,48 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn expiry_warning_is_reported_once() {
|
||||
const CHILD: &str = "GP_TEST_SESSION_WARNING_CHILD";
|
||||
const WARNING: &str = "Session expires soon";
|
||||
if std::env::var_os(CHILD).is_some() {
|
||||
env_logger::builder()
|
||||
.filter_level(log::LevelFilter::Info)
|
||||
.format(gpapi::log_format::write_json_record)
|
||||
.init();
|
||||
let context = SessionContext::new(
|
||||
"vpn.example.test".to_owned(),
|
||||
"vpn.example.test".to_owned(),
|
||||
SessionRequestArgs::new("synthetic".to_owned()),
|
||||
);
|
||||
let session = sample_session_info(Some(unix_timestamp() + 30), false);
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_time()
|
||||
.build()
|
||||
.unwrap()
|
||||
.block_on(run_session_runtime(context, session, LogFormat::Json));
|
||||
return;
|
||||
}
|
||||
|
||||
let output = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args([
|
||||
"--exact",
|
||||
"session::tests::expiry_warning_is_reported_once",
|
||||
"--nocapture",
|
||||
])
|
||||
.env(CHILD, "1")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success());
|
||||
let stderr = String::from_utf8(output.stderr).unwrap();
|
||||
assert_eq!(
|
||||
stderr.lines().filter(|line| line.contains(WARNING)).count(),
|
||||
1,
|
||||
"{stderr}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_warning_schedule_for_auto_extend() {
|
||||
let session_info = sample_session_info(Some(unix_timestamp() + 1830), true);
|
||||
|
||||
Reference in new issue
Block a user