mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 06:26:14 -05:00
release: prepare GP Connect 3.5.0 with Windows support
This commit is contained in:
172 files changed
+9629
-1171
No files matched your search
@@ -7,6 +7,7 @@ license = "MIT"
|
||||
links = "openconnect"
|
||||
|
||||
[dependencies]
|
||||
gp-xml = { path = "../gp-xml" }
|
||||
log.workspace = true
|
||||
libc = "0.2"
|
||||
is_executable.workspace = true
|
||||
@@ -19,3 +20,6 @@ fs_extra = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_Networking_WinSock"] }
|
||||
@@ -1,3 +1,6 @@
|
||||
#[path = "build/windows.rs"]
|
||||
mod windows;
|
||||
|
||||
use std::{env, path::PathBuf};
|
||||
|
||||
fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
|
||||
@@ -188,6 +191,10 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
|
||||
|
||||
fn main() {
|
||||
let target = target_os();
|
||||
if target == "windows" {
|
||||
windows::build();
|
||||
return;
|
||||
}
|
||||
assert!(
|
||||
matches!(target.as_str(), "macos" | "linux" | "freebsd" | "openbsd"),
|
||||
"Unsupported OpenConnect target: {target}"
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
//! Link the MinGW-built OpenConnect DLL into the native MSVC Rust service.
|
||||
use std::{env, path::PathBuf};
|
||||
|
||||
pub fn build() {
|
||||
println!("cargo:rerun-if-env-changed=OPENCONNECT_WINDOWS_PREFIX");
|
||||
let prefix = PathBuf::from(
|
||||
env::var_os("OPENCONNECT_WINDOWS_PREFIX")
|
||||
.expect("Build native OpenConnect and set OPENCONNECT_WINDOWS_PREFIX to its install directory"),
|
||||
);
|
||||
let include = prefix.join("include");
|
||||
let library = prefix.join("lib");
|
||||
assert!(
|
||||
library.join("openconnect.lib").is_file(),
|
||||
"The native OpenConnect MSVC import library is missing"
|
||||
);
|
||||
println!("cargo:rerun-if-changed={}", library.join("openconnect.lib").display());
|
||||
println!("cargo:rerun-if-changed={}", include.join("openconnect.h").display());
|
||||
println!("cargo:rustc-link-search=native={}", library.display());
|
||||
println!("cargo:rustc-link-lib=dylib=openconnect");
|
||||
println!("cargo:rustc-link-lib=ws2_32");
|
||||
println!("cargo:include={}", include.display());
|
||||
println!("cargo:lib_dir={}", prefix.join("bin").display());
|
||||
println!("cargo:rerun-if-changed=src/ffi/vpn.c");
|
||||
println!("cargo:rerun-if-changed=src/ffi/vpn.h");
|
||||
cc::Build::new()
|
||||
.file("src/ffi/vpn.c")
|
||||
.include("src/ffi")
|
||||
.include(include)
|
||||
.std("c11")
|
||||
.compile("vpn");
|
||||
}
|
||||
Submodule crates/openconnect/deps/openconnect updated: 43b36d7293...80b4f80926.
@@ -1,7 +1,11 @@
|
||||
#[cfg(unix)]
|
||||
use libc::{AF_INET, AF_INET6, addrinfo, getaddrinfo};
|
||||
use std::{
|
||||
ffi::{c_char, c_int},
|
||||
ptr,
|
||||
};
|
||||
#[cfg(windows)]
|
||||
use windows_sys::Win32::Networking::WinSock::{ADDRINFOA as addrinfo, AF_INET, AF_INET6, getaddrinfo};
|
||||
|
||||
/// Resolve with the system's normal policy, then prefer one family without
|
||||
/// discarding alternatives. The returned list remains owned by libc and is
|
||||
@@ -13,18 +17,18 @@ use std::{
|
||||
pub unsafe extern "C" fn vpn_resolve_gateway(
|
||||
node: *const c_char,
|
||||
service: *const c_char,
|
||||
hints: *const libc::addrinfo,
|
||||
result: *mut *mut libc::addrinfo,
|
||||
hints: *const addrinfo,
|
||||
result: *mut *mut addrinfo,
|
||||
preference: u32,
|
||||
) -> c_int {
|
||||
// SAFETY: The OpenConnect callback forwards valid getaddrinfo arguments.
|
||||
let status = unsafe { libc::getaddrinfo(node, service, hints, result) };
|
||||
let status = unsafe { getaddrinfo(node.cast(), service.cast(), hints, result) };
|
||||
if status != 0 {
|
||||
return status;
|
||||
}
|
||||
let family = match preference {
|
||||
4 => libc::AF_INET,
|
||||
6 => libc::AF_INET6,
|
||||
4 => AF_INET as c_int,
|
||||
6 => AF_INET6 as c_int,
|
||||
_ => return 0,
|
||||
};
|
||||
// SAFETY: A successful getaddrinfo call returns an owned, writable list.
|
||||
@@ -34,7 +38,7 @@ pub unsafe extern "C" fn vpn_resolve_gateway(
|
||||
|
||||
/// # Safety
|
||||
/// `head` must be an exclusively owned, writable addrinfo list with no cycles.
|
||||
unsafe fn prefer_family(head: *mut libc::addrinfo, family: c_int) -> *mut libc::addrinfo {
|
||||
unsafe fn prefer_family(head: *mut addrinfo, family: c_int) -> *mut addrinfo {
|
||||
let mut addresses = Vec::new();
|
||||
let mut current = head;
|
||||
// SAFETY: The caller owns every node; sorting only changes the list links.
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
#[cfg(unix)]
|
||||
pub(crate) type CommandHandle = i32;
|
||||
#[cfg(windows)]
|
||||
pub(crate) type CommandHandle = usize;
|
||||
|
||||
mod gateway;
|
||||
mod hip;
|
||||
mod network_configuration;
|
||||
@@ -41,9 +46,11 @@ pub(crate) struct ConnectOptions {
|
||||
|
||||
pub script: *const c_char,
|
||||
pub configure_network: Option<unsafe extern "C" fn(*mut c_void, *const c_char, *const VpnOptionRaw) -> c_int>,
|
||||
pub interface: *const c_char,
|
||||
pub interface_name: *const c_char,
|
||||
pub script_tun: u32,
|
||||
pub script_tun_launch: *const ScriptTunLaunchRaw,
|
||||
#[cfg(windows)]
|
||||
pub script_tun_pipe: isize,
|
||||
|
||||
pub certificate: *const c_char,
|
||||
pub sslkey: *const c_char,
|
||||
@@ -77,17 +84,17 @@ pub(crate) struct VpnSessionInfoRaw {
|
||||
|
||||
#[link(name = "vpn")]
|
||||
unsafe extern "C" {
|
||||
fn vpn_write_cancel(fd: c_int) -> c_int;
|
||||
fn vpn_write_statistics(fd: c_int) -> c_int;
|
||||
fn vpn_write_cancel(fd: CommandHandle) -> c_int;
|
||||
fn vpn_write_statistics(fd: CommandHandle) -> c_int;
|
||||
#[link_name = "vpn_connect"]
|
||||
fn vpn_connect(
|
||||
options: *const ConnectOptions,
|
||||
callback: extern "C" fn(i32, *const VpnSessionInfoRaw, *mut c_void),
|
||||
callback: extern "C" fn(CommandHandle, *const VpnSessionInfoRaw, *mut c_void),
|
||||
) -> c_int;
|
||||
|
||||
}
|
||||
|
||||
pub(crate) fn write_cancel(fd: i32) -> std::io::Result<()> {
|
||||
pub(crate) fn write_cancel(fd: CommandHandle) -> std::io::Result<()> {
|
||||
let error = unsafe { vpn_write_cancel(fd) };
|
||||
if error == 0 {
|
||||
Ok(())
|
||||
@@ -96,7 +103,7 @@ pub(crate) fn write_cancel(fd: i32) -> std::io::Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write_statistics(fd: i32) -> std::io::Result<()> {
|
||||
pub(crate) fn write_statistics(fd: CommandHandle) -> std::io::Result<()> {
|
||||
let error = unsafe { vpn_write_statistics(fd) };
|
||||
if error == 0 {
|
||||
Ok(())
|
||||
@@ -106,7 +113,7 @@ pub(crate) fn write_statistics(fd: i32) -> std::io::Result<()> {
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
extern "C" fn vpn_attach_command_pipe(vpn: *mut c_void, fd: c_int) -> c_int {
|
||||
extern "C" fn vpn_attach_command_pipe(vpn: *mut c_void, fd: CommandHandle) -> c_int {
|
||||
unsafe { &*(vpn as *const Vpn) }.attach_command_pipe(fd).into()
|
||||
}
|
||||
|
||||
@@ -134,7 +141,7 @@ pub(crate) extern "C" fn on_hip_report_submitted(vpn: *mut c_void, report: *cons
|
||||
}
|
||||
|
||||
#[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: CommandHandle, session_info: *const VpnSessionInfoRaw, vpn: *mut c_void) {
|
||||
let vpn = unsafe { &*(vpn as *const Vpn) };
|
||||
vpn.on_connected(pipe_fd, crate::vpn::session_info_from_raw(session_info));
|
||||
}
|
||||
@@ -146,6 +153,14 @@ extern "C" fn on_vpn_connected(pipe_fd: i32, session_info: *const VpnSessionInfo
|
||||
extern "C" fn vpn_log(level: i32, message: *const c_char) {
|
||||
let message = unsafe { std::ffi::CStr::from_ptr(message) };
|
||||
let message = message.to_str().unwrap_or("Invalid log message");
|
||||
// This dump comes from the native GlobalProtect protocol handler.
|
||||
if let Some(body) = message.strip_prefix("GlobalProtect getconfig.esp response:\n") {
|
||||
debug!(
|
||||
"GlobalProtect getconfig.esp response:\n{}",
|
||||
gp_xml::redact_xml(body.as_bytes())
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Strip the trailing newline
|
||||
let message = message.trim_end_matches('\n');
|
||||
|
||||
@@ -165,3 +180,41 @@ extern "C" fn vpn_log(level: i32, message: *const c_char) {
|
||||
debug!("{}", message);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod log_tests {
|
||||
use super::vpn_log;
|
||||
use std::sync::Mutex;
|
||||
|
||||
struct Capture(Mutex<String>);
|
||||
impl log::Log for Capture {
|
||||
fn enabled(&self, _: &log::Metadata<'_>) -> bool {
|
||||
true
|
||||
}
|
||||
fn flush(&self) {}
|
||||
fn log(&self, record: &log::Record<'_>) {
|
||||
if record.target() == module_path!().trim_end_matches("::log_tests") {
|
||||
self.0.lock().unwrap().push_str(&record.args().to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_config_dump_keeps_settings_and_redacts_keys_before_logging() {
|
||||
static CAPTURE: Capture = Capture(Mutex::new(String::new()));
|
||||
log::set_logger(&CAPTURE).unwrap();
|
||||
log::set_max_level(log::LevelFilter::Debug);
|
||||
let message = c"GlobalProtect getconfig.esp response:\n<response><mtu>1400</mtu><akey-c2s><val>fixture-secret</val></akey-c2s><hs-key><bits>128</bits><val>fixture-handshake-key</val></hs-key></response>\n";
|
||||
vpn_log(2, message.as_ptr());
|
||||
vpn_log(
|
||||
2,
|
||||
c"GlobalProtect getconfig.esp response:\n<malformed>fixture-secret".as_ptr(),
|
||||
);
|
||||
let output = CAPTURE.0.lock().unwrap();
|
||||
assert!(output.contains("<mtu>1400</mtu>"));
|
||||
assert!(output.contains("[redacted]"));
|
||||
assert!(output.contains("[XML omitted:"));
|
||||
assert!(!output.contains("fixture-secret"));
|
||||
assert!(!output.contains("fixture-handshake-key"));
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,15 @@
|
||||
#include <openconnect.h>
|
||||
#include "vpn.h"
|
||||
#include <errno.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/utsname.h>
|
||||
#ifndef _WIN32
|
||||
#include <unistd.h>
|
||||
|
||||
#include "vpn.h"
|
||||
#endif
|
||||
|
||||
struct vpn_context {
|
||||
struct openconnect_info *vpninfo;
|
||||
int command_fd;
|
||||
vpn_command_handle command_fd;
|
||||
const vpn_options *options;
|
||||
vpn_connected_callback on_connected;
|
||||
};
|
||||
@@ -59,21 +58,22 @@ static int validate_peer_cert(void *private_data,
|
||||
if (context->options->servercert)
|
||||
return openconnect_check_peer_cert_hash(context->vpninfo,
|
||||
context->options->servercert);
|
||||
INFO("Accepting the server certificate though %s", reason);
|
||||
VPN_INFO("Accepting the server certificate though %s", reason);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Print progress messages */
|
||||
static void print_progress(__attribute__((unused)) void *_vpninfo, int level,
|
||||
static void print_progress(void *_vpninfo, int level,
|
||||
const char *format, ...)
|
||||
{
|
||||
(void)_vpninfo;
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
char *message = format_message(format, args);
|
||||
va_end(args);
|
||||
|
||||
if (message == NULL) {
|
||||
ERROR("Failed to format log message");
|
||||
VPN_ERROR("Failed to format log message");
|
||||
} else {
|
||||
vpn_log(level, message);
|
||||
free(message);
|
||||
@@ -88,15 +88,24 @@ static void setup_tun_handler(void *private_data)
|
||||
int ret;
|
||||
if (options->script_tun) {
|
||||
const struct openconnect_script_tun_launch *launch = options->script_tun_launch;
|
||||
#ifdef _WIN32
|
||||
if (options->script_tun_pipe != -1) {
|
||||
ret = openconnect_setup_tun_pipe(_vpninfo, options->script_tun_pipe);
|
||||
} else
|
||||
#endif
|
||||
if (launch) {
|
||||
#ifndef _WIN32
|
||||
ret = openconnect_setup_tun_script_exec(_vpninfo, launch);
|
||||
vpn_script_started(options->user_data);
|
||||
#else
|
||||
ret = -EOPNOTSUPP;
|
||||
#endif
|
||||
} else {
|
||||
ret = openconnect_setup_tun_script(_vpninfo, options->script);
|
||||
}
|
||||
} else {
|
||||
ret = openconnect_setup_tun_device(_vpninfo, options->script,
|
||||
options->interface);
|
||||
options->interface_name);
|
||||
}
|
||||
|
||||
if (!ret) {
|
||||
@@ -122,39 +131,39 @@ static void setup_tun_handler(void *private_data)
|
||||
int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
|
||||
{
|
||||
struct openconnect_info *vpninfo;
|
||||
struct utsname utsbuf;
|
||||
char hostname[256];
|
||||
const char *effective_local_hostname = NULL;
|
||||
|
||||
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)");
|
||||
VPN_INFO("USER_AGENT: %s", options->user_agent);
|
||||
VPN_INFO("OS: %s", options->os);
|
||||
VPN_INFO("CLIENT_VERSION: %s", options->client_version);
|
||||
VPN_INFO("HOST_ID: %s", options->host_id ? options->host_id : "(not set)");
|
||||
const char *configuration = options->script;
|
||||
if (options->configure_network)
|
||||
configuration = "callback";
|
||||
else if (options->script_tun_launch)
|
||||
configuration = options->script_tun_launch->program;
|
||||
INFO("Network configuration: %s", configuration);
|
||||
INFO("SCRIPT_TUN: %d", options->script_tun);
|
||||
INFO("CSD_USER: %d", options->hip_script.uid);
|
||||
INFO("CSD_WRAPPER: %s", options->hip_script.path);
|
||||
INFO("RECONNECT_TIMEOUT: %d", options->reconnect_timeout);
|
||||
INFO("MTU: %d", options->mtu);
|
||||
INFO("DISABLE_IPV6: %d", options->disable_ipv6);
|
||||
INFO("GATEWAY_IP_PREFERENCE: %d", options->gateway_ip_preference);
|
||||
INFO("NO_DTLS: %d", options->no_dtls);
|
||||
INFO("DPD_INTERVAL: %d", options->dpd_interval);
|
||||
INFO("NO_XMLPOST: %d", options->no_xmlpost);
|
||||
VPN_INFO("Network configuration: %s", configuration);
|
||||
VPN_INFO("SCRIPT_TUN: %d", options->script_tun);
|
||||
VPN_INFO("CSD_USER: %d", options->hip_script.uid);
|
||||
VPN_INFO("CSD_WRAPPER: %s", options->hip_script.path);
|
||||
VPN_INFO("RECONNECT_TIMEOUT: %d", options->reconnect_timeout);
|
||||
VPN_INFO("MTU: %d", options->mtu);
|
||||
VPN_INFO("DISABLE_IPV6: %d", options->disable_ipv6);
|
||||
VPN_INFO("GATEWAY_IP_PREFERENCE: %d", options->gateway_ip_preference);
|
||||
VPN_INFO("NO_DTLS: %d", options->no_dtls);
|
||||
VPN_INFO("DPD_INTERVAL: %d", options->dpd_interval);
|
||||
VPN_INFO("NO_XMLPOST: %d", options->no_xmlpost);
|
||||
|
||||
vpninfo =
|
||||
openconnect_vpninfo_new(options->user_agent, validate_peer_cert,
|
||||
NULL, NULL, print_progress, &context);
|
||||
|
||||
if (!vpninfo) {
|
||||
ERROR("openconnect_vpninfo_new failed");
|
||||
VPN_ERROR("openconnect_vpninfo_new failed");
|
||||
vpn_tunnel_event(options->user_data, VPN_TUNNEL_ENDED);
|
||||
return 1;
|
||||
}
|
||||
@@ -168,20 +177,21 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
|
||||
openconnect_set_stats_handler(vpninfo, observe_statistics);
|
||||
openconnect_set_gp_hip_report_callback(vpninfo, options->user_data,
|
||||
options->on_hip_report_submitted);
|
||||
/* Windows command pipes are Winsock sockets. Initialize before creating them. */
|
||||
openconnect_init_ssl();
|
||||
context.command_fd = openconnect_setup_cmd_pipe(vpninfo);
|
||||
if (context.command_fd < 0) {
|
||||
ERROR("openconnect_setup_cmd_pipe failed");
|
||||
if (context.command_fd == (vpn_command_handle)-1) {
|
||||
VPN_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");
|
||||
VPN_INFO("VPN attempt canceled before startup");
|
||||
result = -EINTR;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
openconnect_set_loglevel(vpninfo, PRG_TRACE);
|
||||
openconnect_init_ssl();
|
||||
openconnect_set_protocol(vpninfo, "gp");
|
||||
openconnect_parse_url(vpninfo, options->server);
|
||||
if (options->gateway_ip_preference)
|
||||
@@ -207,18 +217,19 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
|
||||
}
|
||||
|
||||
effective_local_hostname = options->local_hostname;
|
||||
if (!effective_local_hostname && !uname(&utsbuf)) {
|
||||
effective_local_hostname = utsbuf.nodename;
|
||||
if (!effective_local_hostname && !gethostname(hostname, sizeof(hostname))) {
|
||||
hostname[sizeof(hostname) - 1] = 0;
|
||||
effective_local_hostname = hostname;
|
||||
}
|
||||
if (effective_local_hostname) {
|
||||
openconnect_set_localname(vpninfo, effective_local_hostname);
|
||||
}
|
||||
|
||||
INFO("LOCAL_HOSTNAME: %s",
|
||||
VPN_INFO("LOCAL_HOSTNAME: %s",
|
||||
effective_local_hostname ? effective_local_hostname : "(not set)");
|
||||
|
||||
if (options->certificate) {
|
||||
INFO("Setting client certificate: %s", options->certificate);
|
||||
VPN_INFO("Setting client certificate: %s", options->certificate);
|
||||
openconnect_set_client_cert(vpninfo, options->certificate,
|
||||
options->sslkey);
|
||||
}
|
||||
@@ -256,7 +267,7 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
|
||||
// Essential step
|
||||
vpn_tunnel_event(options->user_data, OC_TUNNEL_NEGOTIATING);
|
||||
if (openconnect_make_cstp_connection(vpninfo) != 0) {
|
||||
ERROR("openconnect_make_cstp_connection failed");
|
||||
VPN_ERROR("openconnect_make_cstp_connection failed");
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
@@ -273,12 +284,12 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
|
||||
options->reconnect_timeout, 10);
|
||||
|
||||
if (ret) {
|
||||
INFO("openconnect_mainloop returned %d, exiting", ret);
|
||||
VPN_INFO("openconnect_mainloop returned %d, exiting", ret);
|
||||
result = ret;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
INFO("openconnect_mainloop returned 0, reconnecting");
|
||||
VPN_INFO("openconnect_mainloop returned 0, reconnecting");
|
||||
}
|
||||
cleanup:
|
||||
vpn_detach_command_pipe(options->user_data);
|
||||
@@ -289,24 +300,28 @@ cleanup:
|
||||
}
|
||||
|
||||
/* Called with the attempt cancellation mutex held, never after detach/free. */
|
||||
int vpn_write_cancel(int fd)
|
||||
static int write_command(vpn_command_handle fd, char command)
|
||||
{
|
||||
char command = OC_CMD_CANCEL;
|
||||
#ifdef _WIN32
|
||||
int written = send(fd, &command, 1, 0);
|
||||
return written == 1 ? 0 : (written == SOCKET_ERROR ? WSAGetLastError() : EIO);
|
||||
#else
|
||||
ssize_t written;
|
||||
do {
|
||||
written = write(fd, &command, 1);
|
||||
} while (written < 0 && errno == EINTR);
|
||||
return written == 1 ? 0 : (written < 0 ? errno : EIO);
|
||||
#endif
|
||||
}
|
||||
|
||||
int vpn_write_statistics(int fd)
|
||||
int vpn_write_cancel(vpn_command_handle fd)
|
||||
{
|
||||
char command = OC_CMD_STATS;
|
||||
ssize_t written;
|
||||
do {
|
||||
written = write(fd, &command, 1);
|
||||
} while (written < 0 && errno == EINTR);
|
||||
return written == 1 ? 0 : (written < 0 ? errno : EIO);
|
||||
return write_command(fd, OC_CMD_CANCEL);
|
||||
}
|
||||
|
||||
int vpn_write_statistics(vpn_command_handle fd)
|
||||
{
|
||||
return write_command(fd, OC_CMD_STATS);
|
||||
}
|
||||
|
||||
int vpn_collect_hip_report(const vpn_hip_script *script,
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
#ifdef _WIN32
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
typedef SOCKET vpn_command_handle;
|
||||
#else
|
||||
typedef int vpn_command_handle;
|
||||
#endif
|
||||
#include <openconnect.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
@@ -13,7 +20,7 @@ typedef struct vpn_session_info {
|
||||
const char *nlb_connected_gw_ip;
|
||||
} vpn_session_info;
|
||||
|
||||
typedef void (*vpn_connected_callback)(int cmd_pipe_fd,
|
||||
typedef void (*vpn_connected_callback)(vpn_command_handle cmd_pipe_fd,
|
||||
const vpn_session_info *session_info,
|
||||
void *user_data);
|
||||
typedef void (*vpn_hip_report_callback)(void *user_data, const char *report,
|
||||
@@ -45,9 +52,12 @@ typedef struct vpn_options {
|
||||
|
||||
const char *script;
|
||||
openconnect_configure_tun_fn configure_network;
|
||||
const char *interface;
|
||||
const char *interface_name;
|
||||
const int script_tun;
|
||||
const struct openconnect_script_tun_launch *script_tun_launch;
|
||||
#ifdef _WIN32
|
||||
intptr_t script_tun_pipe;
|
||||
#endif
|
||||
|
||||
const char *certificate;
|
||||
const char *sslkey;
|
||||
@@ -73,7 +83,7 @@ extern int vpn_resolve_gateway(const char *node, const char *service,
|
||||
int vpn_collect_hip_report(const vpn_hip_script *, const struct openconnect_gp_hip_request *,
|
||||
const struct openconnect_gp_hip_control *, openconnect_gp_hip_generate_fn, void *, char *, size_t, size_t *);
|
||||
|
||||
extern int vpn_attach_command_pipe(void *user_data, int fd);
|
||||
extern int vpn_attach_command_pipe(void *user_data, vpn_command_handle fd);
|
||||
extern void vpn_detach_command_pipe(void *user_data);
|
||||
extern void vpn_script_started(void *user_data);
|
||||
enum vpn_tunnel_event {
|
||||
@@ -82,7 +92,7 @@ enum vpn_tunnel_event {
|
||||
VPN_TUNNEL_ENDED,
|
||||
};
|
||||
extern void vpn_tunnel_event(void *user_data, int event);
|
||||
extern void vpn_tunnel_configuration(void *user_data, const char *interface,
|
||||
extern void vpn_tunnel_configuration(void *user_data, const char *interface_name,
|
||||
const struct oc_ip_info *info);
|
||||
extern void vpn_tunnel_statistics(void *user_data, const struct oc_stats *stats);
|
||||
|
||||
@@ -122,8 +132,8 @@ static void _log(int level, ...)
|
||||
}
|
||||
}
|
||||
|
||||
#define LOG(level, ...) _log(level, __VA_ARGS__)
|
||||
#define ERROR(...) LOG(PRG_ERR, __VA_ARGS__)
|
||||
#define INFO(...) LOG(PRG_INFO, __VA_ARGS__)
|
||||
#define DEBUG(...) LOG(PRG_DEBUG, __VA_ARGS__)
|
||||
#define TRACE(...) LOG(PRG_TRACE, __VA_ARGS__)
|
||||
#define VPN_LOG(level, ...) _log(level, __VA_ARGS__)
|
||||
#define VPN_ERROR(...) VPN_LOG(PRG_ERR, __VA_ARGS__)
|
||||
#define VPN_INFO(...) VPN_LOG(PRG_INFO, __VA_ARGS__)
|
||||
#define VPN_DEBUG(...) VPN_LOG(PRG_DEBUG, __VA_ARGS__)
|
||||
#define VPN_TRACE(...) VPN_LOG(PRG_TRACE, __VA_ARGS__)
|
||||
@@ -1,7 +1,10 @@
|
||||
#[cfg(unix)]
|
||||
use std::os::fd::{AsRawFd, OwnedFd};
|
||||
#[cfg(windows)]
|
||||
use std::os::windows::io::{AsRawHandle, OwnedHandle};
|
||||
use std::{
|
||||
ffi::{CStr, CString, c_char},
|
||||
fmt, io,
|
||||
os::fd::{AsRawFd, OwnedFd},
|
||||
sync::{Arc, Mutex, RwLock},
|
||||
};
|
||||
|
||||
@@ -37,7 +40,8 @@ pub(crate) fn session_info_from_raw(raw: *const ffi::VpnSessionInfoRaw) -> VpnSe
|
||||
let raw = unsafe { &*raw };
|
||||
let warning_message =
|
||||
unsafe { optional_c_string(raw.lifetime_warning_message) }.filter(|message| !message.is_empty());
|
||||
let user_expires = positive_i64_to_u32(raw.user_expires).or_else(|| positive_i64_to_u32(raw.auth_expiration));
|
||||
let user_expires =
|
||||
positive_i64_to_u32(raw.user_expires.into()).or_else(|| positive_i64_to_u32(raw.auth_expiration.into()));
|
||||
|
||||
VpnSessionInfo {
|
||||
lifetime_secs: positive_i64_to_u32(raw.lifetime_secs as i64),
|
||||
@@ -73,12 +77,12 @@ struct Cancellation {
|
||||
#[derive(Default)]
|
||||
struct CancellationState {
|
||||
requested: bool,
|
||||
command_fd: Option<i32>,
|
||||
command_fd: Option<ffi::CommandHandle>,
|
||||
statistics_pending: bool,
|
||||
}
|
||||
|
||||
impl Cancellation {
|
||||
fn attach(&self, fd: i32) -> bool {
|
||||
fn attach(&self, fd: ffi::CommandHandle) -> bool {
|
||||
let mut state = self.state.lock().unwrap();
|
||||
state.command_fd = Some(fd);
|
||||
state.requested
|
||||
@@ -150,7 +154,10 @@ pub struct Vpn {
|
||||
pub(crate) network_configuration_handler: Option<Arc<NetworkConfigurationHandler>>,
|
||||
interface: Option<CString>,
|
||||
script_tun: bool,
|
||||
#[cfg(unix)]
|
||||
script_tun_launch: Option<ScriptTunLaunch>,
|
||||
#[cfg(windows)]
|
||||
script_tun_pipe: Option<OwnedHandle>,
|
||||
|
||||
certificate: Option<CString>,
|
||||
sslkey: Option<CString>,
|
||||
@@ -232,7 +239,9 @@ impl Vpn {
|
||||
}
|
||||
self.callback.write().unwrap().replace(Box::new(on_connected));
|
||||
let mut options = self.build_connect_options();
|
||||
#[cfg(unix)]
|
||||
let mut argv = Vec::new();
|
||||
#[cfg(unix)]
|
||||
let launch = self.script_tun_launch.as_ref().map(|launch| {
|
||||
argv.push(launch.program.as_ptr());
|
||||
argv.extend(launch.arguments.iter().map(|s| s.as_ptr()));
|
||||
@@ -245,7 +254,10 @@ impl Vpn {
|
||||
}
|
||||
});
|
||||
// Both the borrowed launch record and argv remain alive through native connect.
|
||||
options.script_tun_launch = launch.as_ref().map_or(std::ptr::null(), |launch| launch);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
options.script_tun_launch = launch.as_ref().map_or(std::ptr::null(), |launch| launch);
|
||||
}
|
||||
let environment = match self.hip_source.as_ref() {
|
||||
HipSource::Script(script) => ffi::script_environment(script),
|
||||
_ => Vec::new(),
|
||||
@@ -269,7 +281,7 @@ impl Vpn {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn on_connected(&self, pipe_fd: i32, session_info: VpnSessionInfo) {
|
||||
pub(crate) fn on_connected(&self, pipe_fd: ffi::CommandHandle, session_info: VpnSessionInfo) {
|
||||
info!("Connected to VPN, pipe_fd: {}", pipe_fd);
|
||||
|
||||
if let Some(callback) = self.callback.write().unwrap().take() {
|
||||
@@ -277,7 +289,7 @@ impl Vpn {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn attach_command_pipe(&self, fd: i32) -> bool {
|
||||
pub(crate) fn attach_command_pipe(&self, fd: ffi::CommandHandle) -> bool {
|
||||
self.cancellation.attach(fd)
|
||||
}
|
||||
|
||||
@@ -311,9 +323,15 @@ impl Vpn {
|
||||
.network_configuration_handler
|
||||
.as_ref()
|
||||
.map(|_| ffi::configure_network as _),
|
||||
interface: Self::option_to_ptr(&self.interface),
|
||||
interface_name: Self::option_to_ptr(&self.interface),
|
||||
script_tun: self.script_tun as u32,
|
||||
script_tun_launch: std::ptr::null(),
|
||||
#[cfg(windows)]
|
||||
script_tun_pipe: self
|
||||
.script_tun_pipe
|
||||
.as_ref()
|
||||
.map(|handle| handle.as_raw_handle() as isize)
|
||||
.unwrap_or(-1),
|
||||
|
||||
certificate: Self::option_to_ptr(&self.certificate),
|
||||
sslkey: Self::option_to_ptr(&self.sslkey),
|
||||
@@ -366,6 +384,7 @@ impl fmt::Display for VpnError {
|
||||
|
||||
impl std::error::Error for VpnError {}
|
||||
|
||||
#[cfg(unix)]
|
||||
struct ScriptTunLaunch {
|
||||
program: CString,
|
||||
arguments: Vec<CString>,
|
||||
@@ -381,7 +400,10 @@ pub struct VpnBuilder {
|
||||
script_is_path: bool,
|
||||
interface: Option<String>,
|
||||
script_tun: bool,
|
||||
#[cfg(unix)]
|
||||
script_tun_launch: Option<ScriptTunLaunch>,
|
||||
#[cfg(windows)]
|
||||
script_tun_pipe: Option<OwnedHandle>,
|
||||
|
||||
user_agent: Option<String>,
|
||||
os: Option<String>,
|
||||
@@ -416,7 +438,10 @@ impl VpnBuilder {
|
||||
script_is_path: false,
|
||||
interface: None,
|
||||
script_tun: false,
|
||||
#[cfg(unix)]
|
||||
script_tun_launch: None,
|
||||
#[cfg(windows)]
|
||||
script_tun_pipe: None,
|
||||
|
||||
user_agent: None,
|
||||
os: None,
|
||||
@@ -469,6 +494,7 @@ impl VpnBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub fn script_tun_program(
|
||||
mut self,
|
||||
program: &str,
|
||||
@@ -495,6 +521,19 @@ impl VpnBuilder {
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Deliver packets through a connected Windows message-mode pipe.
|
||||
///
|
||||
/// # Safety
|
||||
/// The handle must use overlapped I/O and must not be associated with an IOCP.
|
||||
/// OpenConnect duplicates it and owns its own completion events; attaching a
|
||||
/// Tokio/Mio handle would send native OVERLAPPED completions into that reactor.
|
||||
#[cfg(windows)]
|
||||
pub unsafe fn script_tun_pipe(mut self, pipe: OwnedHandle) -> Self {
|
||||
self.script_tun = true;
|
||||
self.script_tun_pipe = Some(pipe);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn script_tun(mut self, script_tun: bool) -> Self {
|
||||
self.script_tun = script_tun;
|
||||
self
|
||||
@@ -596,9 +635,17 @@ impl VpnBuilder {
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
if self.script_tun_launch.is_some() {
|
||||
return Ok(None);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
if self.script_tun_pipe.is_some() {
|
||||
if self.script.is_some() || !self.script_tun {
|
||||
return Err(VpnError::new("Packet pipe conflicts with script options".into()));
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
let script = match &self.script {
|
||||
Some(script) => {
|
||||
if self.script_is_path && !std::path::Path::new(script).exists() {
|
||||
@@ -618,6 +665,7 @@ impl VpnBuilder {
|
||||
}
|
||||
|
||||
pub fn build(self) -> Result<Vpn, VpnError> {
|
||||
#[cfg(unix)]
|
||||
if self.script_tun_launch.is_some() && !self.script_tun {
|
||||
return Err(VpnError::new("Child identity requires script-tun".into()));
|
||||
}
|
||||
@@ -642,7 +690,10 @@ impl VpnBuilder {
|
||||
network_configuration_handler: self.network_configuration_handler,
|
||||
interface: self.interface.as_deref().map(Self::to_cstring),
|
||||
script_tun: self.script_tun,
|
||||
#[cfg(unix)]
|
||||
script_tun_launch: self.script_tun_launch,
|
||||
#[cfg(windows)]
|
||||
script_tun_pipe: self.script_tun_pipe,
|
||||
|
||||
certificate: self.certificate.as_deref().map(Self::to_cstring),
|
||||
sslkey: self.sslkey.as_deref().map(Self::to_cstring),
|
||||
@@ -774,7 +825,10 @@ mod tests {
|
||||
network_configuration_handler: None,
|
||||
interface: None,
|
||||
script_tun: false,
|
||||
#[cfg(unix)]
|
||||
script_tun_launch: None,
|
||||
#[cfg(windows)]
|
||||
script_tun_pipe: None,
|
||||
certificate: None,
|
||||
sslkey: None,
|
||||
key_password: None,
|
||||
@@ -1078,6 +1132,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
#[cfg(unix)]
|
||||
extern "C" fn vpn_script_started(data: *mut std::ffi::c_void) {
|
||||
// Native setup has forked or failed; only the child may retain this endpoint.
|
||||
let vpn = unsafe { &*(data as *const Vpn) };
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
/* Exercise the DLL's packet mainloop without a VPN server or kernel adapter. */
|
||||
#include "config.h"
|
||||
#include "openconnect-internal.h"
|
||||
#include <assert.h>
|
||||
|
||||
struct test_context {
|
||||
wchar_t name[128];
|
||||
SOCKET command;
|
||||
int mode, seeded;
|
||||
volatile LONG statistics;
|
||||
};
|
||||
static void progress(void *data, int level, const char *format, ...)
|
||||
{
|
||||
(void)data; (void)level; (void)format;
|
||||
}
|
||||
static void statistics(void *data, const struct oc_stats *stats)
|
||||
{
|
||||
struct test_context *context = data;
|
||||
(void)stats;
|
||||
InterlockedIncrement(&context->statistics);
|
||||
}
|
||||
static int pump(struct openconnect_info *vpninfo, int *timeout, int readable)
|
||||
{
|
||||
struct test_context *context = vpninfo->cbdata;
|
||||
struct pkt *packet;
|
||||
int work = 0;
|
||||
(void)timeout; (void)readable;
|
||||
vpninfo->need_poll_cmd_fd = 1;
|
||||
while ((packet = dequeue_packet(&vpninfo->outgoing_queue))) {
|
||||
queue_packet(&vpninfo->incoming_queue, packet);
|
||||
work = 1;
|
||||
}
|
||||
if (context->mode == 2 && !context->seeded) {
|
||||
int index;
|
||||
context->seeded = 1;
|
||||
for (index = 0; index < 32; index++) {
|
||||
packet = calloc(1, sizeof(*packet) + 1500);
|
||||
assert(packet);
|
||||
packet->len = 1500;
|
||||
memset(packet->data, index, packet->len);
|
||||
queue_packet(&vpninfo->incoming_queue, packet);
|
||||
}
|
||||
work = 1;
|
||||
}
|
||||
return work;
|
||||
}
|
||||
static const struct vpn_proto protocol = { .name = "packet-test", .tcp_mainloop = pump };
|
||||
static DWORD WINAPI client(void *data)
|
||||
{
|
||||
struct test_context *context = data;
|
||||
HANDLE pipe = CreateFileW(context->name, GENERIC_READ | GENERIC_WRITE, 0, NULL,
|
||||
OPEN_EXISTING, 0, NULL);
|
||||
DWORD mode = PIPE_READMODE_MESSAGE, count;
|
||||
char bytes[1024], response[1024], command;
|
||||
assert(pipe != INVALID_HANDLE_VALUE);
|
||||
assert(SetNamedPipeHandleState(pipe, &mode, NULL, NULL));
|
||||
if (context->mode == 0) {
|
||||
int index;
|
||||
for (index = 0; index < 2; index++) {
|
||||
DWORD length = 257 + index * 97;
|
||||
memset(bytes, 'a' + index, length);
|
||||
assert(WriteFile(pipe, bytes, length, &count, NULL) && count == length);
|
||||
assert(ReadFile(pipe, response, sizeof(response), &count, NULL) && count == length);
|
||||
assert(!memcmp(bytes, response, length));
|
||||
}
|
||||
} else if (context->mode == 3) {
|
||||
/* Free before mainloop must close the duplicate and drain its read. */
|
||||
assert(!ReadFile(pipe, response, sizeof(response), &count, NULL));
|
||||
assert(GetLastError() == ERROR_BROKEN_PIPE);
|
||||
} else {
|
||||
/* No reads: mode 2 fills the service-to-worker packet buffer. */
|
||||
Sleep(100);
|
||||
command = OC_CMD_STATS;
|
||||
assert(send(context->command, &command, 1, 0) == 1);
|
||||
Sleep(100);
|
||||
command = OC_CMD_CANCEL;
|
||||
assert(send(context->command, &command, 1, 0) == 1);
|
||||
Sleep(100);
|
||||
}
|
||||
CloseHandle(pipe);
|
||||
return 0;
|
||||
}
|
||||
static DWORD WINAPI watchdog(void *event)
|
||||
{
|
||||
if (WaitForSingleObject(event, 15000) == WAIT_TIMEOUT) {
|
||||
fputs("FAIL: packet pipe test timed out\n", stderr);
|
||||
ExitProcess(99);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
static void run(int mode)
|
||||
{
|
||||
struct test_context context = { .mode = mode };
|
||||
struct openconnect_info *vpninfo;
|
||||
HANDLE pipe, thread, event;
|
||||
OVERLAPPED connected = { 0 };
|
||||
DWORD count;
|
||||
ULONGLONG started;
|
||||
int result;
|
||||
swprintf(context.name, 128, L"\\\\.\\pipe\\GPConnect.NativePacketTest.%lu.%d", GetCurrentProcessId(), mode);
|
||||
pipe = CreateNamedPipeW(context.name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE,
|
||||
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_REJECT_REMOTE_CLIENTS, 1, 4096, 4096, 0, NULL);
|
||||
assert(pipe != INVALID_HANDLE_VALUE);
|
||||
vpninfo = openconnect_vpninfo_new("packet-test", NULL, NULL, NULL, progress, &context);
|
||||
assert(vpninfo);
|
||||
context.command = openconnect_setup_cmd_pipe(vpninfo);
|
||||
assert(context.command != INVALID_SOCKET);
|
||||
vpninfo->proto = &protocol;
|
||||
vpninfo->dtls_state = DTLS_DISABLED;
|
||||
vpninfo->ip_info.mtu = 1500;
|
||||
openconnect_set_stats_handler(vpninfo, statistics);
|
||||
thread = CreateThread(NULL, 0, client, &context, 0, NULL);
|
||||
assert(thread);
|
||||
event = CreateEvent(NULL, TRUE, FALSE, NULL);
|
||||
assert(event);
|
||||
connected.hEvent = event;
|
||||
if (!ConnectNamedPipe(pipe, &connected)) {
|
||||
DWORD error = GetLastError();
|
||||
if (error != ERROR_PIPE_CONNECTED) {
|
||||
assert(error == ERROR_IO_PENDING);
|
||||
assert(GetOverlappedResult(pipe, &connected, &count, TRUE));
|
||||
}
|
||||
}
|
||||
CloseHandle(event);
|
||||
assert(!openconnect_setup_tun_pipe(vpninfo, (intptr_t)pipe));
|
||||
assert(vpninfo->tun_is_pipe && vpninfo->tun_fh != pipe);
|
||||
CloseHandle(pipe);
|
||||
started = GetTickCount64();
|
||||
if (mode == 3) {
|
||||
vpninfo->tun_pkt = calloc(1, sizeof(struct pkt) + 1500);
|
||||
assert(vpninfo->tun_pkt);
|
||||
assert(!ReadFile(vpninfo->tun_fh, vpninfo->tun_pkt->data, 1500, &count, &vpninfo->tun_rd_overlap));
|
||||
assert(GetLastError() == ERROR_IO_PENDING);
|
||||
vpninfo->tun_rd_pending = 1;
|
||||
openconnect_vpninfo_free(vpninfo);
|
||||
} else {
|
||||
result = openconnect_mainloop(vpninfo, 1, 1);
|
||||
assert(result < 0);
|
||||
assert(vpninfo->tun_fh == INVALID_HANDLE_VALUE && !vpninfo->tun_rd_pending);
|
||||
assert(!vpninfo->tun_rd_overlap.hEvent && !vpninfo->tun_wr_overlap.hEvent);
|
||||
if (mode) {
|
||||
assert(GetTickCount64() - started < 3000);
|
||||
assert(context.statistics == 1);
|
||||
if (mode == 2)
|
||||
assert(vpninfo->stats.rx_pkts > 0 && vpninfo->stats.rx_pkts < 32);
|
||||
} else {
|
||||
assert(vpninfo->stats.rx_pkts == 2 && vpninfo->stats.tx_pkts == 2);
|
||||
}
|
||||
openconnect_vpninfo_free(vpninfo);
|
||||
}
|
||||
assert(WaitForSingleObject(thread, 2000) == WAIT_OBJECT_0);
|
||||
CloseHandle(thread);
|
||||
printf("PASS: native packet pipe case %d\n", mode);
|
||||
}
|
||||
int main(void)
|
||||
{
|
||||
HANDLE stop = CreateEvent(NULL, TRUE, FALSE, NULL);
|
||||
HANDLE guard = CreateThread(NULL, 0, watchdog, stop, 0, NULL);
|
||||
int mode;
|
||||
assert(stop && guard);
|
||||
assert(!openconnect_init_ssl());
|
||||
for (mode = 0; mode < 4; mode++)
|
||||
run(mode);
|
||||
SetEvent(stop);
|
||||
WaitForSingleObject(guard, 1000);
|
||||
CloseHandle(guard);
|
||||
CloseHandle(stop);
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user