fix: retain VPN cancellation throughout connection startup

This commit is contained in:
Kevin Yue committed 2026-09-21 13:24:11 +08:00
1 parent 308957283b
commit 56516abc62
5 files changed
+298 -53

No files matched your search

+20 -6
View File
@@ -53,24 +53,38 @@ pub(crate) struct VpnSessionInfoRaw {
#[link(name = "vpn")]
unsafe extern "C" {
fn vpn_write_cancel(fd: c_int) -> c_int;
#[link_name = "vpn_connect"]
fn vpn_connect(
options: *const ConnectOptions,
callback: extern "C" fn(i32, *const VpnSessionInfoRaw, *mut c_void),
) -> c_int;
#[link_name = "vpn_disconnect"]
fn vpn_disconnect();
}
pub(crate) fn write_cancel(fd: i32) -> std::io::Result<()> {
let error = unsafe { vpn_write_cancel(fd) };
if error == 0 {
Ok(())
} else {
Err(std::io::Error::from_raw_os_error(error))
}
}
#[unsafe(no_mangle)]
extern "C" fn vpn_attach_command_pipe(vpn: *mut c_void, fd: c_int) -> c_int {
unsafe { &*(vpn as *const Vpn) }.attach_command_pipe(fd).into()
}
#[unsafe(no_mangle)]
extern "C" fn vpn_detach_command_pipe(vpn: *mut c_void) {
unsafe { &*(vpn as *const Vpn) }.detach_command_pipe();
}
pub(crate) fn connect(options: &ConnectOptions) -> i32 {
unsafe { vpn_connect(options, on_vpn_connected) }
}
pub(crate) fn disconnect() {
unsafe { vpn_disconnect() }
}
#[unsafe(no_mangle)]
extern "C" fn on_vpn_connected(pipe_fd: i32, session_info: *const VpnSessionInfoRaw, vpn: *mut c_void) {
let vpn = unsafe { &*(vpn as *const Vpn) };
+48 -41
View File
@@ -1,4 +1,5 @@
#include <openconnect.h>
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
@@ -7,13 +8,12 @@
#include "vpn.h"
void *g_user_data;
static int g_cmd_pipe_fd;
static const char *g_vpnc_script;
static const char *g_vpnc_interface;
static int g_script_tun;
static vpn_connected_callback on_vpn_connected;
struct vpn_context {
struct openconnect_info *vpninfo;
int command_fd;
const vpn_options *options;
vpn_connected_callback on_connected;
};
/* Validate the peer certificate */
static int validate_peer_cert(__attribute__((unused)) void *_vpninfo,
@@ -40,14 +40,17 @@ static void print_progress(__attribute__((unused)) void *_vpninfo, int level,
}
}
static void setup_tun_handler(void *_vpninfo)
static void setup_tun_handler(void *private_data)
{
struct vpn_context *context = private_data;
struct openconnect_info *_vpninfo = context->vpninfo;
const vpn_options *options = context->options;
int ret;
if (g_script_tun) {
ret = openconnect_setup_tun_script(_vpninfo, g_vpnc_script);
if (options->script_tun) {
ret = openconnect_setup_tun_script(_vpninfo, options->script);
} else {
ret = openconnect_setup_tun_device(_vpninfo, g_vpnc_script,
g_vpnc_interface);
ret = openconnect_setup_tun_device(_vpninfo, options->script,
options->interface);
}
if (!ret) {
@@ -63,7 +66,7 @@ static void setup_tun_handler(void *_vpninfo)
.nlb_connected_gw_ip =
openconnect_get_gp_nlb_connected_gw_ip(_vpninfo),
};
on_vpn_connected(g_cmd_pipe_fd, &session_info, g_user_data);
context->on_connected(context->command_fd, &session_info, options->user_data);
}
}
@@ -74,18 +77,15 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
struct utsname utsbuf;
const char *effective_local_hostname = NULL;
g_user_data = options->user_data;
g_vpnc_script = options->script;
g_vpnc_interface = options->interface;
g_script_tun = options->script_tun;
on_vpn_connected = callback;
struct vpn_context context = { .options = options, .on_connected = callback };
int result = 1;
INFO("USER_AGENT: %s", options->user_agent);
INFO("OS: %s", options->os);
INFO("CLIENT_VERSION: %s", options->client_version);
INFO("HOST_ID: %s", options->host_id ? options->host_id : "(not set)");
INFO("VPNC_SCRIPT: %s", options->script);
INFO("SCRIPT_TUN: %d", g_script_tun);
INFO("SCRIPT_TUN: %d", options->script_tun);
INFO("CSD_USER: %d", options->csd_uid);
INFO("CSD_WRAPPER: %s", options->csd_wrapper);
INFO("RECONNECT_TIMEOUT: %d", options->reconnect_timeout);
@@ -97,13 +97,26 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
vpninfo =
openconnect_vpninfo_new(options->user_agent, validate_peer_cert,
NULL, NULL, print_progress, NULL);
NULL, NULL, print_progress, &context);
if (!vpninfo) {
ERROR("openconnect_vpninfo_new failed");
return 1;
}
context.vpninfo = vpninfo;
context.command_fd = openconnect_setup_cmd_pipe(vpninfo);
if (context.command_fd < 0) {
ERROR("openconnect_setup_cmd_pipe failed");
goto cleanup;
}
/* An earlier disconnect remains latched on this attempt. */
if (vpn_attach_command_pipe(options->user_data, context.command_fd)) {
INFO("VPN attempt canceled before startup");
result = -EINTR;
goto cleanup;
}
openconnect_set_loglevel(vpninfo, PRG_TRACE);
openconnect_init_ssl();
openconnect_set_protocol(vpninfo, "gp");
@@ -170,23 +183,15 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
if (options->dpd_interval > 0) {
openconnect_set_dpd(vpninfo, options->dpd_interval);
}
g_cmd_pipe_fd = openconnect_setup_cmd_pipe(vpninfo);
if (g_cmd_pipe_fd < 0) {
ERROR("openconnect_setup_cmd_pipe failed");
return 1;
}
// Essential step
if (openconnect_make_cstp_connection(vpninfo) != 0) {
ERROR("openconnect_make_cstp_connection failed");
return 1;
goto cleanup;
}
if (options->no_dtls || openconnect_setup_dtls(vpninfo, 60) != 0) {
openconnect_disable_dtls(vpninfo);
}
// Essential step
openconnect_set_setup_tun_handler(vpninfo, setup_tun_handler);
@@ -196,23 +201,25 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
if (ret) {
INFO("openconnect_mainloop returned %d, exiting", ret);
openconnect_vpninfo_free(vpninfo);
return ret;
result = ret;
goto cleanup;
}
INFO("openconnect_mainloop returned 0, reconnecting");
}
cleanup:
vpn_detach_command_pipe(options->user_data);
openconnect_vpninfo_free(vpninfo);
return result;
}
/* Stop the VPN connection */
void vpn_disconnect()
/* Called with the attempt cancellation mutex held, never after detach/free. */
int vpn_write_cancel(int fd)
{
char cmd = OC_CMD_CANCEL;
INFO("Stopping VPN connection: %d", g_cmd_pipe_fd);
if (write(g_cmd_pipe_fd, &cmd, 1) < 0) {
ERROR("Failed to write to command pipe, VPN connection may not "
"be stopped");
}
char command = OC_CMD_CANCEL;
ssize_t written;
do {
written = write(fd, &command, 1);
} while (written < 0 && errno == EINTR);
return written == 1 ? 0 : (written < 0 ? errno : EIO);
}
+3 -1
View File
@@ -52,7 +52,9 @@ typedef struct vpn_options {
} vpn_options;
int vpn_connect(const vpn_options *options, vpn_connected_callback callback);
void vpn_disconnect();
extern int vpn_attach_command_pipe(void *user_data, int fd);
extern void vpn_detach_command_pipe(void *user_data);
extern void vpn_log(int level, const char *msg);
+226 -4
View File
@@ -1,10 +1,10 @@
use std::{
ffi::{CStr, CString, c_char},
fmt,
sync::{Arc, RwLock},
fmt, io,
sync::{Arc, Mutex, RwLock},
};
use log::info;
use log::{info, warn};
use crate::ffi;
use crate::vpn_utils::{check_executable, find_csd_wrapper, find_vpnc_script};
@@ -60,7 +60,45 @@ fn positive_i64_to_u32(value: i64) -> Option<u32> {
u32::try_from(value).ok().filter(|value| *value > 0)
}
// The descriptor is borrowed only between attach and detach. Serialize writes
// against teardown and retain cancellation before the pipe exists.
#[derive(Default)]
struct Cancellation {
state: Mutex<CancellationState>,
}
#[derive(Default)]
struct CancellationState {
requested: bool,
command_fd: Option<i32>,
}
impl Cancellation {
fn attach(&self, fd: i32) -> bool {
let mut state = self.state.lock().unwrap();
state.command_fd = Some(fd);
state.requested
}
fn detach(&self) {
self.state.lock().unwrap().command_fd = None;
}
fn cancel(&self) -> io::Result<()> {
let mut state = self.state.lock().unwrap();
if state.requested {
return Ok(());
}
state.requested = true;
if let Some(fd) = state.command_fd {
ffi::write_cancel(fd)?;
}
Ok(())
}
}
pub struct Vpn {
cancellation: Cancellation,
server: CString,
cookie: CString,
@@ -114,8 +152,18 @@ impl Vpn {
}
}
pub(crate) fn attach_command_pipe(&self, fd: i32) -> bool {
self.cancellation.attach(fd)
}
pub(crate) fn detach_command_pipe(&self) {
self.cancellation.detach();
}
pub fn disconnect(&self) {
ffi::disconnect();
if let Err(error) = self.cancellation.cancel() {
warn!("Failed to signal VPN cancellation: {error}");
}
}
fn build_connect_options(&self) -> ffi::ConnectOptions {
@@ -401,6 +449,7 @@ impl VpnBuilder {
let os = self.os.unwrap_or("linux".to_string());
Ok(Vpn {
cancellation: Cancellation::default(),
server: Self::to_cstring(&self.server),
cookie: Self::to_cstring(&self.cookie),
@@ -529,6 +578,7 @@ mod tests {
#[test]
fn connect_options_include_host_id() {
let vpn = Vpn {
cancellation: Cancellation::default(),
server: CString::new("gateway.example.com").unwrap(),
cookie: CString::new("cookie").unwrap(),
user_agent: CString::new("agent").unwrap(),
@@ -560,4 +610,176 @@ mod tests {
let host_id = unsafe { CStr::from_ptr(options.host_id) }.to_str().unwrap();
assert_eq!(host_id, "profile-host-id");
}
#[test]
fn disconnect_before_connect_is_retained_without_contacting_server() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.set_nonblocking(true).unwrap();
let vpn = Vpn::builder(&format!("https://{}", listener.local_addr().unwrap()), "test-cookie")
.script_path("/bin/sh".to_string())
.build()
.unwrap();
vpn.disconnect();
vpn.disconnect();
assert_ne!(vpn.connect(|_| panic!("Canceled attempt connected")), 0);
assert_eq!(listener.accept().unwrap_err().kind(), io::ErrorKind::WouldBlock);
}
#[test]
fn command_pipe_failure_preserves_stdin() {
use std::{
ffi::{c_int, c_void},
fs::File,
os::fd::AsFd,
process::{Command, Stdio},
};
const CHILD: &str = "OPENCONNECT_TEST_PIPE_FAILURE";
if std::env::var_os(CHILD).is_none() {
// Limit descriptors only in a subprocess, leaving the test runner untouched.
let output = Command::new("sh")
.args([
"-c",
"ulimit -n 64 && exec \"$1\" --exact vpn::tests::command_pipe_failure_preserves_stdin --nocapture",
"sh",
])
.arg(std::env::current_exe().unwrap())
.env(CHILD, "1")
.stdin(Stdio::null())
.output()
.unwrap();
assert!(
output.status.success(),
"{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
return;
}
unsafe extern "C" {
fn openconnect_vpninfo_new(
agent: *const c_char,
validate: Option<unsafe extern "C" fn(*mut c_void, *const c_char) -> c_int>,
config: Option<unsafe extern "C" fn(*mut c_void, *const c_char, c_int) -> c_int>,
auth: Option<unsafe extern "C" fn(*mut c_void, *mut c_void) -> c_int>,
progress: Option<unsafe extern "C" fn(*mut c_void, c_int, *const c_char, ...)>,
data: *mut c_void,
) -> *mut c_void;
fn openconnect_setup_cmd_pipe(info: *mut c_void) -> c_int;
fn openconnect_vpninfo_free(info: *mut c_void);
}
// Construct first so resource exhaustion targets pipe creation specifically.
let info = unsafe { openconnect_vpninfo_new(c"test".as_ptr(), None, None, None, None, std::ptr::null_mut()) };
assert!(!info.is_null());
let mut descriptors = Vec::new();
loop {
match File::open("/dev/null") {
Ok(file) => descriptors.push(file),
Err(error) => {
assert_eq!(error.raw_os_error(), Some(24)); // EMFILE on supported Unix platforms.
break;
}
}
}
assert!(unsafe { openconnect_setup_cmd_pipe(info) } < 0);
unsafe { openconnect_vpninfo_free(info) };
// Constructor resource acquisition may also fail before selecting a protocol.
let info = unsafe { openconnect_vpninfo_new(c"test".as_ptr(), None, None, None, None, std::ptr::null_mut()) };
if !info.is_null() {
unsafe { openconnect_vpninfo_free(info) };
}
drop(descriptors);
std::io::stdin()
.as_fd()
.try_clone_to_owned()
.expect("Cleanup closed stdin");
}
#[test]
fn disconnect_interrupts_in_progress_tls_and_cannot_cancel_another_attempt() {
use std::{io::Read, sync::mpsc, thread, time::Duration};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.set_nonblocking(true).unwrap();
let vpn = Arc::new(
Vpn::builder(&format!("https://{}", listener.local_addr().unwrap()), "test-cookie")
.script_path("/bin/sh".to_string())
.build()
.unwrap(),
);
let (tx, rx) = mpsc::channel();
let worker_vpn = vpn.clone();
let worker = thread::spawn(move || {
tx.send(worker_vpn.connect(|_| panic!("Test peer never completes TLS")))
.unwrap();
});
let deadline = std::time::Instant::now() + Duration::from_secs(3);
let peer = loop {
match listener.accept() {
Ok((peer, _)) => break peer,
Err(error) if error.kind() == io::ErrorKind::WouldBlock && std::time::Instant::now() < deadline => {
thread::sleep(Duration::from_millis(5));
}
other => {
vpn.disconnect();
worker.join().unwrap();
panic!("Connection did not reach test peer: {other:?}");
}
}
};
vpn.disconnect();
let result = rx.recv_timeout(Duration::from_secs(2));
drop(peer); // Release the peer even if cancellation regresses.
worker.join().unwrap();
assert_ne!(result.expect("Cancellation did not interrupt TLS"), 0);
use std::os::{fd::AsRawFd, unix::net::UnixStream};
let next = Cancellation::default();
let (mut reader, writer) = UnixStream::pair().unwrap();
reader.set_nonblocking(true).unwrap();
assert!(!next.attach(writer.as_raw_fd()));
vpn.disconnect(); // A late stop of the old attempt cannot affect the new one.
assert_eq!(reader.read(&mut [0]).unwrap_err().kind(), io::ErrorKind::WouldBlock);
next.detach();
}
#[test]
fn cancellation_racing_pipe_attachment_is_never_lost() {
use std::{
io::Read,
os::{fd::AsRawFd, unix::net::UnixStream},
thread,
};
for _ in 0..100 {
let cancellation = Cancellation::default();
let (mut reader, writer) = UnixStream::pair().unwrap();
reader.set_nonblocking(true).unwrap();
let pending = thread::scope(|scope| {
let cancel = scope.spawn(|| cancellation.cancel().unwrap());
let pending = cancellation.attach(writer.as_raw_fd());
cancel.join().unwrap();
pending
});
if !pending {
let mut command = [0];
assert_eq!(reader.read(&mut command).unwrap(), 1);
assert_eq!(command[0], b'x');
}
cancellation.detach();
}
}
#[test]
fn disconnect_after_detach_never_writes_to_the_old_descriptor() {
use std::{
io::Read,
os::{fd::AsRawFd, unix::net::UnixStream},
};
let cancellation = Cancellation::default();
let (mut reader, writer) = UnixStream::pair().unwrap();
reader.set_nonblocking(true).unwrap();
assert!(!cancellation.attach(writer.as_raw_fd()));
cancellation.detach();
cancellation.cancel().unwrap();
assert_eq!(reader.read(&mut [0]).unwrap_err().kind(), io::ErrorKind::WouldBlock);
}
}