Compare commits

..

8 Commits

Author SHA1 Message Date
Kevin Yue
c70c7ee5b9 fix: multiple tray icon related: #464 2025-02-09 08:23:40 +00:00
Kevin Yue
fe3d3df662 ci: upload offline tarball 2025-01-23 21:59:59 +08:00
Kevin Yue
2f90b73683 fix: check the cli running state 2025-01-22 21:30:42 +08:00
Kevin Yue
5186e80c6f doc: update installation for Ubuntu 18.04 2025-01-21 23:00:32 +08:00
Kevin Yue
4ff1c1dc1f Release 2.4.3 2025-01-21 00:16:00 +08:00
Kevin Yue
c1427040f6 fix: do not use default value for os_version 2025-01-21 00:14:13 +08:00
Kevin Yue
a7ad02acb6 Release 2.4.2 2025-01-20 20:57:57 +08:00
Kevin Yue
b188d61be1 fix: disconnect VPN when sleep 2025-01-20 19:29:22 +08:00
30 changed files with 750 additions and 336 deletions

View File

@@ -14,6 +14,11 @@ on:
- release/*
tags:
- v*.*.*
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
# Include arm64 if ref is a tag
setup-matrix:
@@ -39,7 +44,8 @@ jobs:
with:
version: 9
- name: Prepare workspace
run: rm -rf source && mkdir source
run: rm -rf source && mkdir -p source/artifacts
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v4
with:
@@ -47,6 +53,7 @@ jobs:
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.ref }}
path: source/gp
- name: Create tarball
run: |
cd source/gp
@@ -55,13 +62,69 @@ jobs:
touch SNAPSHOT
fi
make tarball
mv -v .build/tarball/*.tar.gz ../artifacts/
- name: Generate RPM spec file
env:
RELEASE_TAG: ${{ github.ref == 'refs/heads/dev' && 'snapshot' || github.ref_name }}
run: |
cd source/gp
make init-rpm \
REVISION='1%{?dist}' \
RPM_SOURCE=https://github.com/yuezk/GlobalProtect-openconnect/releases/download/${RELEASE_TAG}/%{name}-%{version}.tar.gz
mv -v .build/rpm/*.spec ../artifacts/
- name: Upload tarball
uses: actions/upload-artifact@v4
with:
name: artifact-source
if-no-files-found: error
path: |
source/gp/.build/tarball/*.tar.gz
source/artifacts/*
tarball-offline:
if: ${{ github.ref == 'refs/heads/dev' || startsWith(github.ref, 'refs/tags/') }}
runs-on: ubuntu-latest
needs:
- tarball
steps:
- uses: pnpm/action-setup@v4
with:
version: 9
- name: Prepare workspace
run: rm -rf source-offline && mkdir source-offline
- name: Download tarball
uses: actions/download-artifact@v4
with:
name: artifact-source
path: source-offline
- name: Create offline tarball
run: |
cd source-offline
offline_tarball=$(basename *.tar.gz .tar.gz).offline.tar.gz
# Extract the tarball
tar -xzf *.tar.gz
cd */
make tarball OFFLINE=1
# Rename the tarball to .offline.tar.gz
mv -v .build/tarball/*.tar.gz ../$offline_tarball
- name: Upload offline tarball
uses: actions/upload-artifact@v4
with:
path: source-offline/*.offline.tar.gz
name: artifact-source-offline
if-no-files-found: error
build-gp:
needs:
@@ -163,6 +226,7 @@ jobs:
runs-on: ubuntu-latest
needs:
- tarball
- tarball-offline
- build-gp
- build-gpgui

View File

@@ -52,22 +52,26 @@ jobs:
version: 9
- name: Prepare workspace
run: rm -rf publish-ppa && mkdir publish-ppa
- name: Download ${{ inputs.tag }} source code
uses: robinraju/release-downloader@v1.9
with:
token: ${{ secrets.GH_PAT }}
tag: ${{ inputs.tag }}
fileName: globalprotect-openconnect-*.tar.gz
tarBall: false
zipBall: false
out-file-path: publish-ppa
- name: Make the offline tarball
- name: Download ${{ inputs.tag }} offline source code
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
run: |
gh -R yuezk/GlobalProtect-openconnect \
release download ${{ inputs.tag }} \
--pattern '*.offline.tar.gz' \
--dir publish-ppa
- name: Patch the source code
run: |
cd publish-ppa
tar -xf globalprotect-openconnect-*.tar.gz
cd globalprotect-openconnect-*/
make tarball OFFLINE=1
# Rename the source tarball without the offline suffix
mv -v *.tar.gz $(basename *.tar.gz .offline.tar.gz).tar.gz
# Extract the source tarball
tar -xzf *.tar.gz
# Prepare the debian directory with custom files
cd globalprotect-openconnect-*/
# Prepare the debian directory with custom files
mkdir -p .build/debian
@@ -78,7 +82,6 @@ jobs:
cp -v packaging/deb/postrm .build/debian/postrm
sed -i "s/@RUST@/cargo-1.80/g" .build/debian/control
sed -i "s/@OFFLINE@/1/g" .build/debian/rules
sed -i "s/@BUILD_GUI@/1/g" .build/debian/rules
sed -i "s/@RUST_VERSION@/1.80/g" .build/debian/rules
@@ -89,7 +92,7 @@ jobs:
repository: "yuezk/globalprotect-openconnect"
gpg_private_key: ${{ secrets.PPA_GPG_PRIVATE_KEY }}
gpg_passphrase: ${{ secrets.PPA_GPG_PASSPHRASE }}
tarball: publish-ppa/globalprotect-openconnect-*/.build/tarball/*.tar.gz
tarball: publish-ppa/globalprotect-openconnect-*.tar.gz
debian_dir: publish-ppa/globalprotect-openconnect-*/.build/debian
deb_email: "k3vinyue@gmail.com"
deb_fullname: "Kevin Yue"

View File

@@ -96,15 +96,16 @@ jobs:
steps:
- name: Prepare workspace
run: rm -rf build-${{ matrix.package }} && mkdir -p build-${{ matrix.package }}
- name: Download ${{ inputs.tag }} source code
uses: robinraju/release-downloader@v1.9
with:
token: ${{ secrets.GH_PAT }}
tag: ${{ inputs.tag }}
fileName: globalprotect-openconnect-*.tar.gz
tarBall: false
zipBall: false
out-file-path: build-${{ matrix.package }}
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
run: |
gh -R yuezk/GlobalProtect-openconnect \
release download ${{ inputs.tag }} \
--pattern '*[^offline].tar.gz' \
--dir build-${{ matrix.package }}
- name: Docker Login
run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin
- name: Build ${{ matrix.package }} package in Docker

394
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +1,17 @@
[workspace]
resolver = "2"
members = ["crates/*", "apps/gpclient", "apps/gpservice", "apps/gpauth", "apps/gpgui-helper/src-tauri"]
members = [
"crates/*",
"apps/gpclient",
"apps/gpservice",
"apps/gpauth",
"apps/gpgui-helper/src-tauri",
]
[workspace.package]
rust-version = "1.80"
version = "2.4.1"
version = "2.4.3"
authors = ["Kevin Yue <k3vinyue@gmail.com>"]
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
edition = "2021"
@@ -31,11 +37,11 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sysinfo = "0.33"
tempfile = "3.8"
tokio = { version = "1", features = ["full"] }
tokio = { version = "1" }
tokio-util = "0.7"
url = "2.4"
urlencoding = "2.1.3"
axum = "0.7"
axum = "0.8"
futures = "0.3"
futures-util = "0.3"
uzers = "0.12"
@@ -44,9 +50,9 @@ thiserror = "2"
redact-engine = "0.1"
compile-time = "0.2"
serde_urlencoded = "0.7"
md5="0.7"
sha256="1"
which="7"
md5 = "0.7"
sha256 = "1"
which = "7"
# Tauri dependencies
tauri = { version = "2" }

View File

@@ -8,6 +8,8 @@ RUST_VERSION = 1.80
VERSION = $(shell $(CARGO) metadata --no-deps --format-version 1 | jq -r '.packages[0].version')
REVISION ?= 1
RPM_SOURCE ?= %{name}.tar.gz
PPA_REVISION ?= 1
PKG_NAME = globalprotect-openconnect
PKG = $(PKG_NAME)-$(VERSION)
@@ -130,6 +132,10 @@ install:
install -Dm755 .build/gpgui/gpgui_*/gpgui $(DESTDIR)/usr/bin/gpgui; \
fi
# Install the disconnect hooks
install -Dm755 packaging/files/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
install -Dm755 packaging/files/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
install -Dm644 packaging/files/usr/share/applications/gpgui.desktop $(DESTDIR)/usr/share/applications/gpgui.desktop
install -Dm644 packaging/files/usr/share/icons/hicolor/scalable/apps/gpgui.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
install -Dm644 packaging/files/usr/share/icons/hicolor/32x32/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png
@@ -146,6 +152,9 @@ uninstall:
rm -f $(DESTDIR)/usr/bin/gpgui-helper
rm -f $(DESTDIR)/usr/bin/gpgui
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
rm -f $(DESTDIR)/usr/share/applications/gpgui.desktop
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
rm -f $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png
@@ -227,6 +236,7 @@ init-rpm: clean-rpm
sed -i "s/@VERSION@/$(VERSION)/g" .build/rpm/globalprotect-openconnect.spec
sed -i "s/@REVISION@/$(REVISION)/g" .build/rpm/globalprotect-openconnect.spec
sed -i "s|@SOURCE@|$(RPM_SOURCE)|g" .build/rpm/globalprotect-openconnect.spec
sed -i "s/@OFFLINE@/$(OFFLINE)/g" .build/rpm/globalprotect-openconnect.spec
sed -i "s/@DATE@/$(shell LC_ALL=en.US date "+%a %b %d %Y")/g" .build/rpm/globalprotect-openconnect.spec

View File

@@ -70,7 +70,7 @@ The GUI version is also available after you installed it. You can launch it from
### Debian/Ubuntu based distributions
#### Install from PPA (Ubuntu > 18.04)
#### Install from PPA
```
sudo add-apt-repository ppa:yuezk/globalprotect-openconnect
@@ -81,10 +81,6 @@ sudo apt-get install globalprotect-openconnect
>
> For Linux Mint, you might need to import the GPG key with: `sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 7937C393082992E5D6E4A60453FC26B43838D761` if you encountered an error `gpg: keyserver receive failed: General error`.
#### **Ubuntu 18.04**
The latest package is not available in the PPA, but you still needs to add the `ppa:yuezk/globalprotect-openconnect` repo beforehand to use the required `openconnect` package. Then you can follow the [Install from deb package](#install-from-deb-package) section to install the latest package.
#### Install from deb package
Download the latest deb package from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page. Then install it with `apt`:

View File

@@ -16,13 +16,13 @@ clap.workspace = true
env_logger.workspace = true
inquire = "0.7"
log.workspace = true
tokio.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] }
sysinfo.workspace = true
serde_json.workspace = true
whoami.workspace = true
tempfile.workspace = true
reqwest.workspace = true
directories = "5.0"
directories.workspace = true
compile-time.workspace = true
[features]

View File

@@ -1,17 +1,21 @@
use std::{env::temp_dir, fs::File};
use std::{env::temp_dir, fs::File, str::FromStr};
use anyhow::bail;
use clap::{Parser, Subcommand};
use gpapi::{
clap::{handle_error, Args, InfoLevelVerbosity},
utils::openssl,
};
use log::info;
use sysinfo::{Pid, System};
use tempfile::NamedTempFile;
use tokio::fs;
use crate::{
connect::{ConnectArgs, ConnectHandler},
disconnect::DisconnectHandler,
disconnect::{DisconnectArgs, DisconnectHandler},
launch_gui::{LaunchGuiArgs, LaunchGuiHandler},
GP_CLIENT_LOCK_FILE,
};
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
@@ -27,7 +31,7 @@ enum CliCommand {
#[command(about = "Connect to a portal server")]
Connect(Box<ConnectArgs>),
#[command(about = "Disconnect from the server")]
Disconnect,
Disconnect(DisconnectArgs),
#[command(about = "Launch the GUI")]
LaunchGui(LaunchGuiArgs),
}
@@ -77,6 +81,25 @@ impl Args for Cli {
}
impl Cli {
async fn is_running(&self) -> bool {
let Ok(c) = fs::read_to_string(GP_CLIENT_LOCK_FILE).await else {
return false;
};
let Ok(pid) = Pid::from_str(c.trim()) else {
return false;
};
let s = System::new_all();
let Some(p) = s.process(pid) else {
return false;
};
p.exe()
.map(|exe| exe.to_string_lossy().contains("gpclient"))
.unwrap_or(false)
}
fn fix_openssl(&self) -> anyhow::Result<Option<NamedTempFile>> {
if self.fix_openssl {
let file = openssl::fix_openssl_env()?;
@@ -87,6 +110,11 @@ impl Cli {
}
async fn run(&self) -> anyhow::Result<()> {
// check if an instance is running
if self.is_running().await {
bail!("Another instance of the client is already running");
}
// The temp file will be dropped automatically when the file handle is dropped
// So, declare it here to ensure it's not dropped
let _file = self.fix_openssl()?;
@@ -102,7 +130,7 @@ impl Cli {
match &self.command {
CliCommand::Connect(args) => ConnectHandler::new(args, &shared_args).handle().await,
CliCommand::Disconnect => DisconnectHandler::new().handle(),
CliCommand::Disconnect(args) => DisconnectHandler::new(args).handle().await,
CliCommand::LaunchGui(args) => LaunchGuiHandler::new(args).handle().await,
}
}

View File

@@ -84,10 +84,10 @@ pub(crate) struct ConnectArgs {
#[arg(long, default_value = GP_USER_AGENT, help = "The user agent to use")]
user_agent: String,
#[arg(long, default_value = "Linux")]
#[arg(long, value_enum, default_value_t = ConnectArgs::default_os())]
os: Os,
#[arg(long)]
#[arg(long, help = "If not specified, it will be computed based on the --os option")]
os_version: Option<String>,
#[arg(long, help = "Disable DTLS and ESP")]
@@ -113,9 +113,17 @@ pub(crate) struct ConnectArgs {
}
impl ConnectArgs {
fn default_os() -> Os {
if cfg!(target_os = "macos") {
Os::Mac
} else {
Os::Linux
}
}
fn os_version(&self) -> String {
if let Some(os_version) = &self.os_version {
return os_version.to_owned();
if let Some(os_version) = self.os_version.as_deref() {
return os_version.to_string();
}
match self.os {

View File

@@ -1,31 +1,63 @@
use crate::GP_CLIENT_LOCK_FILE;
use clap::Args;
use gpapi::utils::lock_file::gpservice_lock_info;
use log::{info, warn};
use std::fs;
use std::{fs, str::FromStr, thread, time::Duration};
use sysinfo::{Pid, Signal, System};
pub(crate) struct DisconnectHandler;
#[derive(Args)]
pub struct DisconnectArgs {
#[arg(
long,
required = false,
help = "The time in seconds to wait for the VPN connection to disconnect"
)]
wait: Option<u64>,
}
impl DisconnectHandler {
pub(crate) fn new() -> Self {
Self
pub struct DisconnectHandler<'a> {
args: &'a DisconnectArgs,
}
impl<'a> DisconnectHandler<'a> {
pub fn new(args: &'a DisconnectArgs) -> Self {
Self { args }
}
pub(crate) fn handle(&self) -> anyhow::Result<()> {
if fs::metadata(GP_CLIENT_LOCK_FILE).is_err() {
warn!("PID file not found, maybe the client is not running");
return Ok(());
pub async fn handle(&self) -> anyhow::Result<()> {
// Try to disconnect the CLI client
if let Ok(c) = fs::read_to_string(GP_CLIENT_LOCK_FILE) {
send_signal(c.trim(), Signal::Interrupt).unwrap_or_else(|err| {
warn!("Failed to send signal to client: {}", err);
});
};
// Try to disconnect the GUI service
if let Ok(c) = gpservice_lock_info().await {
send_signal(&c.pid.to_string(), Signal::User1).unwrap_or_else(|err| {
warn!("Failed to send signal to service: {}", err);
});
};
// sleep, to give the client and service time to disconnect
if let Some(wait) = self.args.wait {
thread::sleep(Duration::from_secs(wait));
}
let pid = fs::read_to_string(GP_CLIENT_LOCK_FILE)?;
let pid = pid.trim().parse::<usize>()?;
Ok(())
}
}
fn send_signal(pid: &str, signal: Signal) -> anyhow::Result<()> {
let s = System::new_all();
let pid = Pid::from_str(pid)?;
if let Some(process) = s.process(Pid::from(pid)) {
info!("Found process {}, killing...", pid);
if process.kill_with(Signal::Interrupt).is_none() {
if let Some(process) = s.process(pid) {
info!("Found process {}, sending signal...", pid);
if process.kill_with(signal).is_none() {
warn!("Failed to kill process {}", pid);
}
}
Ok(())
}
}

View File

@@ -9,7 +9,7 @@ gpapi = { path = "../../crates/gpapi", features = ["clap", "logger"] }
openconnect = { path = "../../crates/openconnect" }
clap.workspace = true
anyhow.workspace = true
tokio.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] }
tokio-util.workspace = true
axum = { workspace = true, features = ["ws"] }
futures.workspace = true

View File

@@ -38,7 +38,8 @@ impl Cli {
let redaction = self.init_logger();
info!("gpservice started: {}", VERSION);
let lock_file = Arc::new(LockFile::new(GP_SERVICE_LOCK_FILE));
let pid = std::process::id();
let lock_file = Arc::new(LockFile::new(GP_SERVICE_LOCK_FILE, pid));
if lock_file.check_health().await {
bail!("Another instance of the service is already running");
@@ -56,9 +57,17 @@ impl Cli {
let (shutdown_tx, mut shutdown_rx) = mpsc::channel::<()>(4);
let shutdown_tx_clone = shutdown_tx.clone();
let vpn_task_token = vpn_task.cancel_token();
let vpn_task_cancel_token = vpn_task.cancel_token();
let server_token = ws_server.cancel_token();
#[cfg(unix)]
{
let vpn_ctx = vpn_task.context();
let ws_ctx = ws_server.context();
tokio::spawn(async move { signals::handle_signals(vpn_ctx, ws_ctx).await });
}
let vpn_task_handle = tokio::spawn(async move { vpn_task.start(server_token).await });
let ws_server_handle = tokio::spawn(async move { ws_server.start(shutdown_tx_clone).await });
@@ -90,7 +99,7 @@ impl Cli {
}
}
vpn_task_token.cancel();
vpn_task_cancel_token.cancel();
let _ = tokio::join!(vpn_task_handle, ws_server_handle);
lock_file.unlock()?;
@@ -137,6 +146,54 @@ impl Cli {
}
}
#[cfg(unix)]
mod signals {
use std::sync::Arc;
use log::{info, warn};
use crate::vpn_task::VpnTaskContext;
use crate::ws_server::WsServerContext;
const DISCONNECTED_PID_FILE: &str = "/tmp/gpservice_disconnected.pid";
pub async fn handle_signals(vpn_ctx: Arc<VpnTaskContext>, ws_ctx: Arc<WsServerContext>) {
use gpapi::service::event::WsEvent;
use tokio::signal::unix::{signal, Signal, SignalKind};
let (mut user_sig1, mut user_sig2) = match || -> anyhow::Result<(Signal, Signal)> {
let user_sig1 = signal(SignalKind::user_defined1())?;
let user_sig2 = signal(SignalKind::user_defined2())?;
Ok((user_sig1, user_sig2))
}() {
Ok(signals) => signals,
Err(err) => {
warn!("Failed to create signal: {}", err);
return;
}
};
loop {
tokio::select! {
_ = user_sig1.recv() => {
info!("Received SIGUSR1 signal");
if vpn_ctx.disconnect().await {
// Write the PID to a dedicated file to indicate that the VPN task is disconnected via SIGUSR1
let pid = std::process::id();
if let Err(err) = tokio::fs::write(DISCONNECTED_PID_FILE, pid.to_string()).await {
warn!("Failed to write PID to file: {}", err);
}
}
}
_ = user_sig2.recv() => {
info!("Received SIGUSR2 signal");
ws_ctx.send_event(WsEvent::ResumeConnection).await;
}
}
}
}
}
async fn launch_gui(envs: Option<HashMap<String, String>>, api_key: Vec<u8>, mut minimized: bool) {
loop {
let gui_launcher = GuiLauncher::new(env!("CARGO_PKG_VERSION"), &api_key)

View File

@@ -1,5 +1,4 @@
use std::{
borrow::Cow,
fs::{File, Permissions},
io::BufReader,
ops::ControlFlow,
@@ -12,7 +11,7 @@ use anyhow::bail;
use axum::{
body::Bytes,
extract::{
ws::{self, CloseFrame, Message, WebSocket},
ws::{self, CloseFrame, Message, Utf8Bytes, WebSocket},
State, WebSocketUpgrade,
},
http::StatusCode,
@@ -133,7 +132,7 @@ async fn handle_socket(mut socket: WebSocket, ctx: Arc<WsServerContext>) {
let close_msg = Message::Close(Some(CloseFrame {
code: ws::close_code::NORMAL,
reason: Cow::from("Goodbye"),
reason: Utf8Bytes::from("Goodbye"),
}));
if let Err(err) = sender.send(close_msg).await {

View File

@@ -90,7 +90,7 @@ impl VpnTaskContext {
});
}
pub async fn disconnect(&self) {
pub async fn disconnect(&self) -> bool {
if let Some(disconnect_rx) = self.disconnect_rx.write().await.take() {
info!("Disconnecting VPN...");
if let Some(vpn) = self.vpn_handle.read().await.as_ref() {
@@ -101,9 +101,13 @@ impl VpnTaskContext {
// Wait for the VPN to be disconnected
disconnect_rx.await.ok();
info!("VPN disconnected");
true
} else {
info!("VPN is not connected, skip disconnect");
self.vpn_state_tx.send(VpnState::Disconnected).ok();
false
}
}
}
@@ -146,6 +150,10 @@ impl VpnTask {
server_cancel_token.cancel();
}
pub fn context(&self) -> Arc<VpnTaskContext> {
return Arc::clone(&self.ctx);
}
async fn recv(&mut self) {
while let Some(req) = self.ws_req_rx.recv().await {
tokio::spawn(process_ws_req(req, self.ctx.clone()));

View File

@@ -20,7 +20,7 @@ impl WsConnection {
pub async fn send_event(&self, event: &WsEvent) -> anyhow::Result<()> {
let encrypted = self.crypto.encrypt(event)?;
let msg = Message::Binary(encrypted);
let msg = Message::Binary(encrypted.into());
self.tx.send(msg).await?;
@@ -29,7 +29,7 @@ impl WsConnection {
pub fn recv_msg(&self, msg: Message) -> ControlFlow<(), WsRequest> {
match msg {
Message::Binary(data) => match self.crypto.decrypt(data) {
Message::Binary(data) => match self.crypto.decrypt(data.into()) {
Ok(ws_req) => ControlFlow::Continue(ws_req),
Err(err) => {
info!("Failed to decrypt message: {}", err);

View File

@@ -113,6 +113,10 @@ impl WsServer {
}
}
pub fn context(&self) -> Arc<WsServerContext> {
Arc::clone(&self.ctx)
}
pub fn cancel_token(&self) -> CancellationToken {
self.cancel_token.clone()
}
@@ -124,7 +128,7 @@ impl WsServer {
warn!("Failed to start WS server: {}", err);
let _ = shutdown_tx.send(()).await;
return;
},
}
};
tokio::select! {
@@ -149,7 +153,7 @@ impl WsServer {
info!("WS server listening on port: {}", port);
self.lock_file.lock(port.to_string())?;
self.lock_file.lock(&port.to_string())?;
Ok(listener)
}

View File

@@ -1,5 +1,13 @@
# Changelog
## 2.4.3 - 2025-01-21
- Do not use static default value for `--os-version` option.
## 2.4.2 - 2025-01-20
- Disconnect the VPN when sleep (fix [#166](https://github.com/yuezk/GlobalProtect-openconnect/issues/166), [#267](https://github.com/yuezk/GlobalProtect-openconnect/issues/267))
## 2.4.1 - 2025-01-09
- Fix the network issue with OpenSSL < 3.0.4

View File

@@ -18,7 +18,7 @@ roxmltree.workspace = true
serde.workspace = true
specta = { workspace = true, features = ["derive"] }
urlencoding.workspace = true
tokio.workspace = true
tokio = { workspace = true, features = ["process", "signal", "macros"] }
serde_json.workspace = true
whoami.workspace = true
tempfile.workspace = true
@@ -39,6 +39,9 @@ clap-verbosity-flag = { workspace = true, optional = true }
env_logger = { workspace = true, optional = true }
log-reload = { version = "0.1", optional = true }
[target.'cfg(not(any(target_os="macos", target_os="windows")))'.dependencies]
gtk = "0.18"
[features]
tauri = ["dep:tauri"]
clap = ["dep:clap", "dep:clap-verbosity-flag"]

View File

@@ -7,4 +7,5 @@ use super::vpn_state::VpnState;
pub enum WsEvent {
VpnState(VpnState),
ActiveGui,
ResumeConnection,
}

View File

@@ -1,10 +1,9 @@
use tokio::fs;
use crate::GP_SERVICE_LOCK_FILE;
use super::lock_file::gpservice_lock_info;
async fn read_port() -> anyhow::Result<String> {
let port = fs::read_to_string(GP_SERVICE_LOCK_FILE).await?;
Ok(port.trim().to_string())
let lock_info = gpservice_lock_info().await?;
Ok(lock_info.port.to_string())
}
pub async fn http_endpoint() -> anyhow::Result<String> {

View File

@@ -41,12 +41,6 @@ pub fn patch_gui_runtime_env(hidpi: bool) {
// This is to avoid blank screen on some systems
std::env::set_var("WEBKIT_DISABLE_COMPOSITING_MODE", "1");
// Workaround for https://github.com/tauri-apps/tao/issues/929
let is_wayland = std::env::var("XDG_SESSION_TYPE").unwrap_or_default() == "wayland";
if is_wayland {
env::set_var("GDK_BACKEND", "x11");
}
if hidpi {
info!("Setting GDK_SCALE=2 and GDK_DPI_SCALE=0.5");
std::env::set_var("GDK_SCALE", "2");

View File

@@ -1,19 +1,24 @@
use std::path::PathBuf;
use thiserror::Error;
use tokio::fs;
pub struct LockFile {
path: PathBuf,
pid: u32,
}
impl LockFile {
pub fn new<P: Into<PathBuf>>(path: P) -> Self {
Self { path: path.into() }
pub fn new<P: Into<PathBuf>>(path: P, pid: u32) -> Self {
Self { path: path.into(), pid }
}
pub fn exists(&self) -> bool {
self.path.exists()
}
pub fn lock(&self, content: impl AsRef<[u8]>) -> anyhow::Result<()> {
pub fn lock(&self, content: &str) -> anyhow::Result<()> {
let content = format!("{}:{}", self.pid, content);
std::fs::write(&self.path, content)?;
Ok(())
}
@@ -37,3 +42,87 @@ impl LockFile {
}
}
}
#[derive(Error, Debug)]
pub enum LockFileError {
#[error("Failed to read lock file: {0}")]
IoError(#[from] std::io::Error),
#[error("Invalid lock file format: expected 'pid:port'")]
InvalidFormat,
#[error("Invalid PID value: {0}")]
InvalidPid(std::num::ParseIntError),
#[error("Invalid port value: {0}")]
InvalidPort(std::num::ParseIntError),
}
pub struct LockInfo {
pub pid: u32,
pub port: u32,
}
impl LockInfo {
async fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self, LockFileError> {
let content = fs::read_to_string(path).await?;
Self::parse(&content)
}
fn parse(content: &str) -> Result<Self, LockFileError> {
let mut parts = content.trim().split(':');
let pid = parts
.next()
.ok_or(LockFileError::InvalidFormat)?
.parse()
.map_err(LockFileError::InvalidPid)?;
let port = parts
.next()
.ok_or(LockFileError::InvalidFormat)?
.parse()
.map_err(LockFileError::InvalidPort)?;
// Ensure there are no extra parts after pid:port
if parts.next().is_some() {
return Err(LockFileError::InvalidFormat);
}
Ok(Self { pid, port })
}
}
pub async fn gpservice_lock_info() -> Result<LockInfo, LockFileError> {
LockInfo::from_file(crate::GP_SERVICE_LOCK_FILE).await
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_valid_input() {
let info = LockInfo::parse("1234:8080").unwrap();
assert_eq!(info.pid, 1234);
assert_eq!(info.port, 8080);
}
#[test]
fn test_parse_invalid_format() {
assert!(matches!(
LockInfo::parse("123:456:789"),
Err(LockFileError::InvalidFormat)
));
}
#[test]
fn test_parse_invalid_numbers() {
assert!(matches!(LockInfo::parse("abc:8080"), Err(LockFileError::InvalidPid(_))));
assert!(matches!(
LockInfo::parse("1234:abc"),
Err(LockFileError::InvalidPort(_))
));
}
}

View File

@@ -1,26 +1,49 @@
use std::{process::ExitStatus, time::Duration};
use anyhow::bail;
use log::info;
use tauri::WebviewWindow;
use tokio::process::Command;
pub trait WindowExt {
fn raise(&self) -> anyhow::Result<()>;
}
impl WindowExt for WebviewWindow {
#[cfg(any(target_os = "macos", target_os = "windows"))]
fn raise(&self) -> anyhow::Result<()> {
raise_window(self)
self.show()?;
Ok(())
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
fn raise(&self) -> anyhow::Result<()> {
unix::raise_window(self)
}
}
pub fn raise_window(win: &WebviewWindow) -> anyhow::Result<()> {
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
mod unix {
use std::{process::ExitStatus, time::Duration};
use anyhow::bail;
use gtk::{
glib::Cast,
traits::{EventBoxExt, GtkWindowExt, WidgetExt},
EventBox,
};
use log::info;
use tauri::WebviewWindow;
use tokio::process::Command;
pub fn raise_window(win: &WebviewWindow) -> anyhow::Result<()> {
let is_wayland = std::env::var("XDG_SESSION_TYPE").unwrap_or_default() == "wayland";
if is_wayland {
win.hide()?;
win.show()?;
let gtk_win = win.gtk_window()?;
if let Some(header) = gtk_win.titlebar() {
let _ = header.downcast::<EventBox>().map(|event_box| {
event_box.set_above_child(false);
});
}
gtk_win.hide();
gtk_win.show_all();
} else {
if !win.is_visible()? {
win.show()?;
@@ -33,14 +56,14 @@ pub fn raise_window(win: &WebviewWindow) -> anyhow::Result<()> {
});
}
// Calling window.show() on Windows will cause the menu to be shown.
// Calling window.show() on window object will cause the menu to be shown.
// We need to hide it again.
win.hide_menu()?;
Ok(())
}
}
async fn wmctrl_raise_window(title: &str) -> anyhow::Result<()> {
async fn wmctrl_raise_window(title: &str) -> anyhow::Result<()> {
let mut counter = 0;
loop {
@@ -58,9 +81,9 @@ async fn wmctrl_raise_window(title: &str) -> anyhow::Result<()> {
counter += 1;
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
}
async fn wmctrl_try_raise_window(title: &str) -> anyhow::Result<ExitStatus> {
async fn wmctrl_try_raise_window(title: &str) -> anyhow::Result<ExitStatus> {
let exit_status = Command::new("wmctrl")
.arg("-F")
.arg("-a")
@@ -70,4 +93,5 @@ async fn wmctrl_try_raise_window(title: &str) -> anyhow::Result<ExitStatus> {
.await?;
Ok(exit_status)
}
}

View File

@@ -10,6 +10,10 @@ install:
install -Dm755 artifacts/usr/bin/gpgui $(DESTDIR)/usr/bin/gpgui; \
fi
# Install the disconnect hooks
install -Dm755 artifacts/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
install -Dm755 artifacts/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
install -Dm644 artifacts/usr/share/applications/gpgui.desktop $(DESTDIR)/usr/share/applications/gpgui.desktop
install -Dm644 artifacts/usr/share/icons/hicolor/scalable/apps/gpgui.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
install -Dm644 artifacts/usr/share/icons/hicolor/32x32/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png
@@ -26,6 +30,9 @@ uninstall:
rm -f $(DESTDIR)/usr/bin/gpgui-helper
rm -f $(DESTDIR)/usr/bin/gpgui
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
rm -f $(DESTDIR)/usr/share/applications/gpgui.desktop
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
rm -f $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png

View File

@@ -0,0 +1,26 @@
#!/bin/sh
# Resume the VPN connection if the network comes back up
set -e
PIDFILE=/tmp/gpservice_disconnected.pid
resume_vpn() {
if [ -f $PIDFILE ]; then
PID=$(cat $PIDFILE)
# Always remove the PID file
rm $PIDFILE
# Ensure the PID is a gpservice process
if ps -p $PID -o comm= | grep -q gpservice; then
# Send a USR2 signal to the gpclient process to resume the VPN connection
kill -USR2 $PID
fi
fi
}
if [ "$2" = "up" ]; then
resume_vpn
fi

View File

@@ -0,0 +1,6 @@
#!/bin/sh
set -e
# Disconnect the VPN connection before the network goes down
/usr/bin/gpclient disconnect --wait 3

View File

@@ -6,7 +6,7 @@ Group: Productivity/Networking/PPP
License: GPL-3.0
URL: https://github.com/yuezk/GlobalProtect-openconnect
Source: %{name}.tar.gz
Source: @SOURCE@
BuildRequires: make
BuildRequires: rust
@@ -60,6 +60,13 @@ make build OFFLINE=@OFFLINE@ BUILD_FE=0
%{_datadir}/icons/hicolor/scalable/apps/gpgui.svg
%{_datadir}/polkit-1/actions/com.yuezk.gpgui.policy
%dir /usr/lib/NetworkManager
%dir /usr/lib/NetworkManager/dispatcher.d
%dir /usr/lib/NetworkManager/dispatcher.d/pre-down.d
/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
%dir %{_datadir}/icons/hicolor
%dir %{_datadir}/icons/hicolor/32x32
%dir %{_datadir}/icons/hicolor/32x32/apps

2
rust-toolchain.toml Normal file
View File

@@ -0,0 +1,2 @@
[toolchain]
channel = "1.80.1"

View File

@@ -28,7 +28,7 @@ release_snapshot() {
echo "Uploading new assets..."
gh -R "$REPO" release upload "$TAG" \
"$PROJECT_DIR"/.build/artifacts/artifact-source/* \
"$PROJECT_DIR"/.build/artifacts/artifact-source*/* \
"$PROJECT_DIR"/.build/artifacts/artifact-gpgui-*/*
}
@@ -40,7 +40,7 @@ release_tag() {
gh -R "$REPO" release create $TAG \
--title "$TAG" \
--notes "$RELEASE_NOTES" \
"$PROJECT_DIR"/.build/artifacts/artifact-source/* \
"$PROJECT_DIR"/.build/artifacts/artifact-source*/* \
"$PROJECT_DIR"/.build/artifacts/artifact-gpgui-*/*
}