mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 22:46:14 -05:00
fix: retain VPN cancellation throughout connection startup
This commit is contained in:
5 files changed
+298
-53
No files matched your search
Submodule crates/openconnect/deps/openconnect updated: 706ca4d6f5...9066ad4f39.
@@ -53,24 +53,38 @@ pub(crate) struct VpnSessionInfoRaw {
|
|||||||
|
|
||||||
#[link(name = "vpn")]
|
#[link(name = "vpn")]
|
||||||
unsafe extern "C" {
|
unsafe extern "C" {
|
||||||
|
fn vpn_write_cancel(fd: c_int) -> c_int;
|
||||||
#[link_name = "vpn_connect"]
|
#[link_name = "vpn_connect"]
|
||||||
fn vpn_connect(
|
fn vpn_connect(
|
||||||
options: *const ConnectOptions,
|
options: *const ConnectOptions,
|
||||||
callback: extern "C" fn(i32, *const VpnSessionInfoRaw, *mut c_void),
|
callback: extern "C" fn(i32, *const VpnSessionInfoRaw, *mut c_void),
|
||||||
) -> c_int;
|
) -> 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 {
|
pub(crate) fn connect(options: &ConnectOptions) -> i32 {
|
||||||
unsafe { vpn_connect(options, on_vpn_connected) }
|
unsafe { vpn_connect(options, on_vpn_connected) }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn disconnect() {
|
|
||||||
unsafe { vpn_disconnect() }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[unsafe(no_mangle)]
|
#[unsafe(no_mangle)]
|
||||||
extern "C" fn on_vpn_connected(pipe_fd: i32, session_info: *const VpnSessionInfoRaw, vpn: *mut c_void) {
|
extern "C" fn on_vpn_connected(pipe_fd: i32, session_info: *const VpnSessionInfoRaw, vpn: *mut c_void) {
|
||||||
let vpn = unsafe { &*(vpn as *const Vpn) };
|
let vpn = unsafe { &*(vpn as *const Vpn) };
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
#include <openconnect.h>
|
#include <openconnect.h>
|
||||||
|
#include <errno.h>
|
||||||
#include <stdarg.h>
|
#include <stdarg.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
@@ -7,13 +8,12 @@
|
|||||||
|
|
||||||
#include "vpn.h"
|
#include "vpn.h"
|
||||||
|
|
||||||
void *g_user_data;
|
struct vpn_context {
|
||||||
|
struct openconnect_info *vpninfo;
|
||||||
static int g_cmd_pipe_fd;
|
int command_fd;
|
||||||
static const char *g_vpnc_script;
|
const vpn_options *options;
|
||||||
static const char *g_vpnc_interface;
|
vpn_connected_callback on_connected;
|
||||||
static int g_script_tun;
|
};
|
||||||
static vpn_connected_callback on_vpn_connected;
|
|
||||||
|
|
||||||
/* Validate the peer certificate */
|
/* Validate the peer certificate */
|
||||||
static int validate_peer_cert(__attribute__((unused)) void *_vpninfo,
|
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;
|
int ret;
|
||||||
if (g_script_tun) {
|
if (options->script_tun) {
|
||||||
ret = openconnect_setup_tun_script(_vpninfo, g_vpnc_script);
|
ret = openconnect_setup_tun_script(_vpninfo, options->script);
|
||||||
} else {
|
} else {
|
||||||
ret = openconnect_setup_tun_device(_vpninfo, g_vpnc_script,
|
ret = openconnect_setup_tun_device(_vpninfo, options->script,
|
||||||
g_vpnc_interface);
|
options->interface);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!ret) {
|
if (!ret) {
|
||||||
@@ -63,7 +66,7 @@ static void setup_tun_handler(void *_vpninfo)
|
|||||||
.nlb_connected_gw_ip =
|
.nlb_connected_gw_ip =
|
||||||
openconnect_get_gp_nlb_connected_gw_ip(_vpninfo),
|
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;
|
struct utsname utsbuf;
|
||||||
const char *effective_local_hostname = NULL;
|
const char *effective_local_hostname = NULL;
|
||||||
|
|
||||||
g_user_data = options->user_data;
|
struct vpn_context context = { .options = options, .on_connected = callback };
|
||||||
g_vpnc_script = options->script;
|
int result = 1;
|
||||||
g_vpnc_interface = options->interface;
|
|
||||||
g_script_tun = options->script_tun;
|
|
||||||
on_vpn_connected = callback;
|
|
||||||
|
|
||||||
INFO("USER_AGENT: %s", options->user_agent);
|
INFO("USER_AGENT: %s", options->user_agent);
|
||||||
INFO("OS: %s", options->os);
|
INFO("OS: %s", options->os);
|
||||||
INFO("CLIENT_VERSION: %s", options->client_version);
|
INFO("CLIENT_VERSION: %s", options->client_version);
|
||||||
INFO("HOST_ID: %s", options->host_id ? options->host_id : "(not set)");
|
INFO("HOST_ID: %s", options->host_id ? options->host_id : "(not set)");
|
||||||
INFO("VPNC_SCRIPT: %s", options->script);
|
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_USER: %d", options->csd_uid);
|
||||||
INFO("CSD_WRAPPER: %s", options->csd_wrapper);
|
INFO("CSD_WRAPPER: %s", options->csd_wrapper);
|
||||||
INFO("RECONNECT_TIMEOUT: %d", options->reconnect_timeout);
|
INFO("RECONNECT_TIMEOUT: %d", options->reconnect_timeout);
|
||||||
@@ -97,13 +97,26 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
|
|||||||
|
|
||||||
vpninfo =
|
vpninfo =
|
||||||
openconnect_vpninfo_new(options->user_agent, validate_peer_cert,
|
openconnect_vpninfo_new(options->user_agent, validate_peer_cert,
|
||||||
NULL, NULL, print_progress, NULL);
|
NULL, NULL, print_progress, &context);
|
||||||
|
|
||||||
if (!vpninfo) {
|
if (!vpninfo) {
|
||||||
ERROR("openconnect_vpninfo_new failed");
|
ERROR("openconnect_vpninfo_new failed");
|
||||||
return 1;
|
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_set_loglevel(vpninfo, PRG_TRACE);
|
||||||
openconnect_init_ssl();
|
openconnect_init_ssl();
|
||||||
openconnect_set_protocol(vpninfo, "gp");
|
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) {
|
if (options->dpd_interval > 0) {
|
||||||
openconnect_set_dpd(vpninfo, options->dpd_interval);
|
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
|
// Essential step
|
||||||
if (openconnect_make_cstp_connection(vpninfo) != 0) {
|
if (openconnect_make_cstp_connection(vpninfo) != 0) {
|
||||||
ERROR("openconnect_make_cstp_connection failed");
|
ERROR("openconnect_make_cstp_connection failed");
|
||||||
return 1;
|
goto cleanup;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options->no_dtls || openconnect_setup_dtls(vpninfo, 60) != 0) {
|
if (options->no_dtls || openconnect_setup_dtls(vpninfo, 60) != 0) {
|
||||||
openconnect_disable_dtls(vpninfo);
|
openconnect_disable_dtls(vpninfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Essential step
|
// Essential step
|
||||||
openconnect_set_setup_tun_handler(vpninfo, setup_tun_handler);
|
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) {
|
if (ret) {
|
||||||
INFO("openconnect_mainloop returned %d, exiting", ret);
|
INFO("openconnect_mainloop returned %d, exiting", ret);
|
||||||
openconnect_vpninfo_free(vpninfo);
|
result = ret;
|
||||||
return ret;
|
goto cleanup;
|
||||||
}
|
}
|
||||||
|
|
||||||
INFO("openconnect_mainloop returned 0, reconnecting");
|
INFO("openconnect_mainloop returned 0, reconnecting");
|
||||||
}
|
}
|
||||||
|
cleanup:
|
||||||
|
vpn_detach_command_pipe(options->user_data);
|
||||||
|
openconnect_vpninfo_free(vpninfo);
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Stop the VPN connection */
|
/* Called with the attempt cancellation mutex held, never after detach/free. */
|
||||||
void vpn_disconnect()
|
int vpn_write_cancel(int fd)
|
||||||
{
|
{
|
||||||
char cmd = OC_CMD_CANCEL;
|
char command = OC_CMD_CANCEL;
|
||||||
|
ssize_t written;
|
||||||
INFO("Stopping VPN connection: %d", g_cmd_pipe_fd);
|
do {
|
||||||
|
written = write(fd, &command, 1);
|
||||||
if (write(g_cmd_pipe_fd, &cmd, 1) < 0) {
|
} while (written < 0 && errno == EINTR);
|
||||||
ERROR("Failed to write to command pipe, VPN connection may not "
|
return written == 1 ? 0 : (written < 0 ? errno : EIO);
|
||||||
"be stopped");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -52,7 +52,9 @@ typedef struct vpn_options {
|
|||||||
} vpn_options;
|
} vpn_options;
|
||||||
|
|
||||||
int vpn_connect(const vpn_options *options, vpn_connected_callback callback);
|
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);
|
extern void vpn_log(int level, const char *msg);
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
use std::{
|
use std::{
|
||||||
ffi::{CStr, CString, c_char},
|
ffi::{CStr, CString, c_char},
|
||||||
fmt,
|
fmt, io,
|
||||||
sync::{Arc, RwLock},
|
sync::{Arc, Mutex, RwLock},
|
||||||
};
|
};
|
||||||
|
|
||||||
use log::info;
|
use log::{info, warn};
|
||||||
|
|
||||||
use crate::ffi;
|
use crate::ffi;
|
||||||
use crate::vpn_utils::{check_executable, find_csd_wrapper, find_vpnc_script};
|
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)
|
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 {
|
pub struct Vpn {
|
||||||
|
cancellation: Cancellation,
|
||||||
server: CString,
|
server: CString,
|
||||||
cookie: 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) {
|
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 {
|
fn build_connect_options(&self) -> ffi::ConnectOptions {
|
||||||
@@ -401,6 +449,7 @@ impl VpnBuilder {
|
|||||||
let os = self.os.unwrap_or("linux".to_string());
|
let os = self.os.unwrap_or("linux".to_string());
|
||||||
|
|
||||||
Ok(Vpn {
|
Ok(Vpn {
|
||||||
|
cancellation: Cancellation::default(),
|
||||||
server: Self::to_cstring(&self.server),
|
server: Self::to_cstring(&self.server),
|
||||||
cookie: Self::to_cstring(&self.cookie),
|
cookie: Self::to_cstring(&self.cookie),
|
||||||
|
|
||||||
@@ -529,6 +578,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn connect_options_include_host_id() {
|
fn connect_options_include_host_id() {
|
||||||
let vpn = Vpn {
|
let vpn = Vpn {
|
||||||
|
cancellation: Cancellation::default(),
|
||||||
server: CString::new("gateway.example.com").unwrap(),
|
server: CString::new("gateway.example.com").unwrap(),
|
||||||
cookie: CString::new("cookie").unwrap(),
|
cookie: CString::new("cookie").unwrap(),
|
||||||
user_agent: CString::new("agent").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();
|
let host_id = unsafe { CStr::from_ptr(options.host_id) }.to_str().unwrap();
|
||||||
assert_eq!(host_id, "profile-host-id");
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user