Compare commits

..
1 Commits
Author SHA1 Message Date
Kevin Yue 69ef7f5cce ci: upload offline tarball 2025-01-22 22:48:30 +08:00
118 changed files with 3993 additions and 9961 deletions

No files matched your search

-6
View File
@@ -1,6 +0,0 @@
BasedOnStyle: LLVM
IndentWidth: 8
TabWidth: 8
UseTab: Always
ColumnLimit: 80
BreakBeforeBraces: Linux
+27 -28
View File
@@ -7,37 +7,19 @@ ARG USER_GID=$USER_UID
ENV RUSTUP_HOME=/usr/local/rustup \ ENV RUSTUP_HOME=/usr/local/rustup \
CARGO_HOME=/usr/local/cargo \ CARGO_HOME=/usr/local/cargo \
PATH=/usr/local/cargo/bin:$PATH \ PATH=/usr/local/cargo/bin:$PATH \
RUST_VERSION=1.89.0 \ RUST_VERSION=1.80.0
DEBIAN_FRONTEND=noninteractive
# Install all system dependencies in a single layer and clean up apt cache # Install common dependencies
RUN set -eux; \ RUN set -eux; \
apt-get update; \ apt-get update; \
apt-get install -y --no-install-recommends \ apt-get install -y --no-install-recommends \
# Common utilities
dh-autoreconf \
sudo \ sudo \
ca-certificates \ ca-certificates \
curl \ curl \
gnupg \ gnupg \
git \ git \
less \ less \
wget \ software-properties-common
file \
software-properties-common \
# libopenconnect-dev to install the related dependencies for building openconnect from source
# Otherwise, we have to install them manually one by one
libopenconnect-dev \
# Tauri dependencies
libwebkit2gtk-4.1-dev \
build-essential \
libxdo-dev \
libssl-dev \
libayatana-appindicator3-dev \
librsvg2-dev; \
# Clean up apt cache to reduce image size
apt-get clean; \
rm -rf /var/lib/apt/lists/*
# Create a non-root user # Create a non-root user
RUN set -eux; \ RUN set -eux; \
@@ -48,21 +30,38 @@ RUN set -eux; \
# Install Rust # Install Rust
RUN set -eux; \ RUN set -eux; \
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain $RUST_VERSION --profile minimal; \ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain $RUST_VERSION; \
chown -R $USERNAME:$USERNAME $RUSTUP_HOME $CARGO_HOME; \ chown -R $USERNAME:$USERNAME $RUSTUP_HOME $CARGO_HOME; \
rustup --version; \ rustup --version; \
cargo --version; \ cargo --version; \
rustc --version rustc --version
# Install Node.js and global npm packages # Install Node.js
RUN set -eux; \ RUN set -eux; \
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -; \ curl -fsSL https://deb.nodesource.com/setup_20.x | bash -; \
apt-get install -y --no-install-recommends nodejs; \ apt-get install -y nodejs; \
corepack enable; \ corepack enable; \
npm install -g diff-so-fancy; \ # Install diff-so-fancy
# Clean up apt cache npm install -g diff-so-fancy
apt-get clean; \
rm -rf /var/lib/apt/lists/* # Install openconnect
RUN set -eux; \
add-apt-repository ppa:yuezk/globalprotect-openconnect; \
apt-get update; \
apt-get install -y openconnect libopenconnect-dev
# Tauri dependencies
RUN set -eux; \
apt-get install -y \
libwebkit2gtk-4.1-dev \
build-essential \
curl \
wget \
file \
libxdo-dev \
libssl-dev \
libayatana-appindicator3-dev \
librsvg2-dev
USER $USERNAME USER $USERNAME
-4
View File
@@ -8,9 +8,5 @@ end_of_line = lf
insert_final_newline = true insert_final_newline = true
trim_trailing_whitespace = true trim_trailing_whitespace = true
[{*.c,*.h}]
indent_style = tab
indent_size = 8
[{Makefile,Makefile.in}] [{Makefile,Makefile.in}]
indent_style = tab indent_style = tab
+25 -55
View File
@@ -1,6 +1,5 @@
name: Build name: Build
on: on:
workflow_dispatch:
push: push:
paths-ignore: paths-ignore:
- LICENSE - LICENSE
@@ -32,7 +31,7 @@ jobs:
run: | run: |
# Set the matrix to include arm64 if the ref is a tag or is the dev branch # Set the matrix to include arm64 if the ref is a tag or is the dev branch
if [[ "${{ github.ref }}" == "refs/tags/"* || "${{ github.ref }}" == "refs/heads/dev" ]]; then if [[ "${{ github.ref }}" == "refs/tags/"* || "${{ github.ref }}" == "refs/heads/dev" ]]; then
echo 'matrix=[{"runner": "ubuntu-latest", "arch": "amd64"}, {"runner": "ubuntu-24.04-arm", "arch": "ubuntu-24.04-arm"}]' >> $GITHUB_OUTPUT echo 'matrix=[{"runner": "ubuntu-latest", "arch": "amd64"}, {"runner": "arm64", "arch": "arm64"}]' >> $GITHUB_OUTPUT
else else
echo 'matrix=[{"runner": "ubuntu-latest", "arch": "amd64"}]' >> $GITHUB_OUTPUT echo 'matrix=[{"runner": "ubuntu-latest", "arch": "amd64"}]' >> $GITHUB_OUTPUT
fi fi
@@ -41,21 +40,18 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: [setup-matrix] needs: [setup-matrix]
steps: steps:
- uses: pnpm/action-setup@v5 - uses: pnpm/action-setup@v4
with: with:
version: 9 version: 9
- name: Prepare workspace - name: Prepare workspace
run: rm -rf source && mkdir -p source/artifacts run: rm -rf source && mkdir source
- name: Checkout GlobalProtect-openconnect - name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6 uses: actions/checkout@v4
with: with:
token: ${{ secrets.GH_PAT }} token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.ref }} ref: ${{ github.ref }}
path: source/gp path: source/gp
submodules: recursive
- name: Create tarball - name: Create tarball
run: | run: |
cd source/gp cd source/gp
@@ -64,28 +60,13 @@ jobs:
touch SNAPSHOT touch SNAPSHOT
fi fi
make tarball 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 - name: Upload tarball
uses: actions/upload-artifact@v7 uses: actions/upload-artifact@v4
with: with:
name: artifact-source name: artifact-source
if-no-files-found: error if-no-files-found: error
path: | path: |
source/artifacts/* source/gp/.build/tarball/*.tar.gz
tarball-offline: tarball-offline:
if: ${{ github.ref == 'refs/heads/dev' || startsWith(github.ref, 'refs/tags/') }} if: ${{ github.ref == 'refs/heads/dev' || startsWith(github.ref, 'refs/tags/') }}
@@ -93,7 +74,7 @@ jobs:
needs: needs:
- tarball - tarball
steps: steps:
- uses: pnpm/action-setup@v5 - uses: pnpm/action-setup@v4
with: with:
version: 9 version: 9
@@ -101,7 +82,7 @@ jobs:
run: rm -rf source-offline && mkdir source-offline run: rm -rf source-offline && mkdir source-offline
- name: Download tarball - name: Download tarball
uses: actions/download-artifact@v8 uses: actions/download-artifact@v4
with: with:
name: artifact-source name: artifact-source
path: source-offline path: source-offline
@@ -122,7 +103,7 @@ jobs:
mv -v .build/tarball/*.tar.gz ../$offline_tarball mv -v .build/tarball/*.tar.gz ../$offline_tarball
- name: Upload offline tarball - name: Upload offline tarball
uses: actions/upload-artifact@v7 uses: actions/upload-artifact@v4
with: with:
path: source-offline/*.offline.tar.gz path: source-offline/*.offline.tar.gz
name: artifact-source-offline name: artifact-source-offline
@@ -134,8 +115,9 @@ jobs:
- tarball - tarball
strategy: strategy:
matrix: matrix:
os: ${{fromJson(needs.setup-matrix.outputs.matrix)}} # Only build gp on amd64, as the arm64 package will be built in release.yaml
package: [deb, rpm, pkg, binary, ubuntu-rolling] os: [{runner: ubuntu-latest, arch: amd64}]
package: [deb, rpm, pkg, binary]
runs-on: ${{ matrix.os.runner }} runs-on: ${{ matrix.os.runner }}
name: build-gp (${{ matrix.package }}, ${{ matrix.os.arch }}) name: build-gp (${{ matrix.package }}, ${{ matrix.os.arch }})
steps: steps:
@@ -144,32 +126,26 @@ jobs:
rm -rf build-gp-${{ matrix.package }} rm -rf build-gp-${{ matrix.package }}
mkdir -p build-gp-${{ matrix.package }} mkdir -p build-gp-${{ matrix.package }}
- name: Download tarball - name: Download tarball
uses: actions/download-artifact@v8 uses: actions/download-artifact@v4
with: with:
name: artifact-source name: artifact-source
path: build-gp-${{ matrix.package }} path: build-gp-${{ matrix.package }}
- name: Docker Login - name: Docker Login
run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin
- name: Build ${{ matrix.package }} package in Docker - name: Build ${{ matrix.package }} package in Docker
# LIBXML2_STATIC is needed to avoid the dynamic linking issue on different distros
run: | run: |
docker run --pull=always --rm \ docker run --pull=always --rm \
-e COREPACK_INTEGRITY_KEYS=0 \ -v $(pwd)/build-gp-${{ matrix.package }}:/${{ matrix.package }} \
-e LIBXML2_STATIC=1 \
-v $(pwd)/build-gp-${{ matrix.package }}:/workspace \
yuezk/gpdev:${{ matrix.package }}-builder-tauri2 yuezk/gpdev:${{ matrix.package }}-builder-tauri2
- name: Install ${{ matrix.package }} package in Docker - name: Install ${{ matrix.package }} package in Docker
run: | run: |
docker run --pull=always --rm \ docker run --pull=always --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-e GPGUI_INSTALLED=0 \ -e GPGUI_INSTALLED=0 \
-v $(pwd)/build-gp-${{ matrix.package }}:/workspace \ -v $(pwd)/build-gp-${{ matrix.package }}:/${{ matrix.package }} \
yuezk/gpdev:${{ matrix.package }}-builder-tauri2 \ yuezk/gpdev:${{ matrix.package }}-builder-tauri2 \
bash install.sh bash install.sh
# Don't upload package for ubuntu-rolling because it's duplicate of deb package
- name: Upload ${{ matrix.package }} package - name: Upload ${{ matrix.package }} package
if: ${{ matrix.package != 'ubuntu-rolling' }} uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with: with:
name: artifact-gp-${{ matrix.package }}-${{ matrix.os.arch }} name: artifact-gp-${{ matrix.package }}-${{ matrix.os.arch }}
if-no-files-found: error if-no-files-found: error
@@ -185,21 +161,20 @@ jobs:
runs-on: ${{ matrix.os.runner }} runs-on: ${{ matrix.os.runner }}
name: build-gpgui (${{ matrix.os.arch }}) name: build-gpgui (${{ matrix.os.arch }})
steps: steps:
- uses: pnpm/action-setup@v5 - uses: pnpm/action-setup@v4
with: with:
version: 9 version: 9
- name: Prepare workspace - name: Prepare workspace
run: rm -rf gpgui-source && mkdir gpgui-source run: rm -rf gpgui-source && mkdir gpgui-source
- name: Checkout GlobalProtect-openconnect - name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6 uses: actions/checkout@v4
with: with:
token: ${{ secrets.GH_PAT }} token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.ref }} ref: ${{ github.ref }}
path: gpgui-source/gp path: gpgui-source/gp
submodules: recursive
- name: Checkout gpgui@${{ github.ref_name }} - name: Checkout gpgui@${{ github.ref_name }}
uses: actions/checkout@v6 uses: actions/checkout@v4
with: with:
token: ${{ secrets.GH_PAT }} token: ${{ secrets.GH_PAT }}
repository: yuezk/gpgui repository: yuezk/gpgui
@@ -213,19 +188,15 @@ jobs:
run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin
- name: Build gpgui in Docker - name: Build gpgui in Docker
run: | run: |
docker run --pull=always --rm \ docker run --pull=always --rm -v $(pwd)/gpgui-source:/gpgui yuezk/gpdev:gpgui-builder-tauri2
-e COREPACK_INTEGRITY_KEYS=0 \
-v $(pwd)/gpgui-source:/workspace yuezk/gpdev:gpgui-builder-tauri2
- name: Install gpgui in Docker - name: Install gpgui in Docker
run: | run: |
cd gpgui-source cd gpgui-source
tar -xJf *.bin.tar.xz tar -xJf *.bin.tar.xz
docker run --pull=always --rm \ docker run --pull=always --rm -v $(pwd):/gpgui yuezk/gpdev:gpgui-builder-tauri2 \
-e COREPACK_INTEGRITY_KEYS=0 \ bash -c "cd /gpgui/gpgui_*/ && ./gpgui --version"
-v $(pwd):/workspace yuezk/gpdev:gpgui-builder-tauri2 \
bash -c "cd /workspace/gpgui_*/ && ./gpgui --version"
- name: Upload gpgui - name: Upload gpgui
uses: actions/upload-artifact@v7 uses: actions/upload-artifact@v4
with: with:
name: artifact-gpgui-${{ matrix.os.arch }} name: artifact-gpgui-${{ matrix.os.arch }}
if-no-files-found: error if-no-files-found: error
@@ -247,16 +218,15 @@ jobs:
run: rm -rf gh-release && mkdir gh-release run: rm -rf gh-release && mkdir gh-release
- name: Checkout GlobalProtect-openconnect - name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6 uses: actions/checkout@v4
with: with:
token: ${{ secrets.GH_PAT }} token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.ref }} ref: ${{ github.ref }}
path: gh-release/gp path: gh-release/gp
submodules: recursive
- name: Download all artifacts - name: Download all artifacts
uses: actions/download-artifact@v8 uses: actions/download-artifact@v4
with: with:
path: gh-release/gp/.build/artifacts path: gh-release/gp/.build/artifacts
@@ -1,4 +1,4 @@
name: Publish PPA name: Publish Packages
on: on:
workflow_dispatch: workflow_dispatch:
@@ -8,23 +8,24 @@ on:
required: true required: true
revision: revision:
description: 'Package revision' description: 'Package revision'
required: false
default: "1"
series:
description: 'Ubuntu series to publish'
type: "string"
required: false
default: ""
excluded_series:
description: 'Additional Ubuntu series to exclude from publishing'
type: "string"
required: false
default: ""
rust:
description: 'Rust version to use'
type: "string"
required: true required: true
default: "1.89" default: "1"
ppa:
description: 'Publish to PPA'
type: boolean
required: true
default: true
obs:
description: 'Publish to OBS'
type: boolean
required: true
default: true
aur:
description: 'Publish to AUR'
type: boolean
required: true
default: true
jobs: jobs:
check: check:
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -43,9 +44,10 @@ jobs:
publish-ppa: publish-ppa:
needs: check needs: check
if: ${{ inputs.ppa }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: pnpm/action-setup@v5 - uses: pnpm/action-setup@v4
with: with:
version: 9 version: 9
- name: Prepare workspace - name: Prepare workspace
@@ -79,12 +81,10 @@ jobs:
cp -v packaging/deb/compat .build/debian/compat cp -v packaging/deb/compat .build/debian/compat
cp -v packaging/deb/postrm .build/debian/postrm cp -v packaging/deb/postrm .build/debian/postrm
sed -i "s/@BUILD_GUI_HELPER@/1/g" .build/debian/rules sed -i "s/@RUST@/cargo-1.80/g" .build/debian/control
sed -i "s/@OFFLINE@/1/g" .build/debian/rules
# Update the control file with the correct Rust version sed -i "s/@BUILD_GUI@/1/g" .build/debian/rules
sed -i "s/@RUST_VERSION@/${{ inputs.rust }}/g" .build/debian/control sed -i "s/@RUST_VERSION@/1.80/g" .build/debian/rules
sed -i "s/@RUST_VERSION@/${{ inputs.rust }}/g" .build/debian/rules
sed -i "s/DISABLE_RUST_TOOLCHAIN = 0/DISABLE_RUST_TOOLCHAIN = 1/g" .build/debian/rules
- name: Publish to PPA - name: Publish to PPA
uses: yuezk/publish-ppa-package@gp uses: yuezk/publish-ppa-package@gp
@@ -96,8 +96,7 @@ jobs:
debian_dir: publish-ppa/globalprotect-openconnect-*/.build/debian debian_dir: publish-ppa/globalprotect-openconnect-*/.build/debian
deb_email: "[email protected]" deb_email: "[email protected]"
deb_fullname: "Kevin Yue" deb_fullname: "Kevin Yue"
extra_ppa: "yuezk/globalprotect-openconnect" extra_ppa: "yuezk/globalprotect-openconnect liushuyu-011/rust-updates-1.80"
# Ubuntu 18.04 and 20.04 are excluded because tauri2 no longer supports them # Ubuntu 18.04 and 20.04 are excluded because tauri2 no longer supports them
excluded_series: "bionic focal ${{ inputs.excluded_series }}" excluded_series: "bionic focal"
series: ${{ inputs.series }}
revision: ${{ inputs.revision }} revision: ${{ inputs.revision }}
+7 -10
View File
@@ -73,9 +73,9 @@ jobs:
const inputs = ${{ toJson(inputs) }} const inputs = ${{ toJson(inputs) }}
const { arch } = inputs const { arch } = inputs
const osMap = { const osMap = {
"all": ["ubuntu-latest", "ubuntu-24.04-arm"], "all": ["ubuntu-latest", "arm64"],
"x86_64": ["ubuntu-latest"], "x86_64": ["ubuntu-latest"],
"arm64": ["ubuntu-24.04-arm"] "arm64": ["arm64"]
} }
const package = Object.entries(inputs) const package = Object.entries(inputs)
@@ -109,25 +109,21 @@ jobs:
- name: Docker Login - name: Docker Login
run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin
- name: Build ${{ matrix.package }} package in Docker - name: Build ${{ matrix.package }} package in Docker
# LIBXML2_STATIC is needed to avoid the dynamic linking issue on different distros
run: | run: |
docker run --pull=always --rm \ docker run --pull=always --rm \
-v $(pwd)/build-${{ matrix.package }}:/workspace \ -v $(pwd)/build-${{ matrix.package }}:/${{ matrix.package }} \
-e COREPACK_INTEGRITY_KEYS=0 \
-e LIBXML2_STATIC=1 \
-e INCLUDE_GUI=1 \ -e INCLUDE_GUI=1 \
yuezk/gpdev:${{ matrix.package }}-builder-tauri2 yuezk/gpdev:${{ matrix.package }}-builder-tauri2
- name: Install ${{ matrix.package }} package in Docker - name: Install ${{ matrix.package }} package in Docker
run: | run: |
docker run --pull=always --rm \ docker run --pull=always --rm \
-e COREPACK_INTEGRITY_KEYS=0 \ -v $(pwd)/build-${{ matrix.package }}:/${{ matrix.package }} \
-v $(pwd)/build-${{ matrix.package }}:/workspace \
yuezk/gpdev:${{ matrix.package }}-builder-tauri2 \ yuezk/gpdev:${{ matrix.package }}-builder-tauri2 \
bash install.sh bash install.sh
- name: Upload ${{ matrix.package }} package - name: Upload ${{ matrix.package }} package
uses: actions/upload-artifact@v7 uses: actions/upload-artifact@v4
with: with:
name: artifact-${{ matrix.os }}-${{ matrix.package }} name: artifact-${{ matrix.os }}-${{ matrix.package }}
if-no-files-found: error if-no-files-found: error
@@ -143,7 +139,7 @@ jobs:
- name: Prepare workspace - name: Prepare workspace
run: rm -rf gh-release && mkdir gh-release run: rm -rf gh-release && mkdir gh-release
- name: Download artifact - name: Download artifact
uses: actions/download-artifact@v8 uses: actions/download-artifact@v4
with: with:
path: gh-release path: gh-release
- name: Update release - name: Update release
@@ -155,3 +151,4 @@ jobs:
tag_name: ${{ inputs.tag }} tag_name: ${{ inputs.tag }}
files: | files: |
gh-release/artifact-*/* gh-release/artifact-*/*
-3
View File
@@ -11,6 +11,3 @@ SNAPSHOT
# Tauri generated files # Tauri generated files
gen gen
# Nix files
result
-6
View File
@@ -1,6 +0,0 @@
[submodule "crates/openconnect/deps/openconnect"]
path = crates/openconnect/deps/openconnect
url = https://gitlab.com/openconnect/openconnect.git
[submodule "crates/openconnect/deps/libxml2"]
path = crates/openconnect/deps/libxml2
url = https://gitlab.gnome.org/GNOME/libxml2.git
+1 -1
View File
@@ -2,7 +2,7 @@
"configurations": [ "configurations": [
{ {
"name": "Mac", "name": "Mac",
"includePath": ["crates/openconnect/deps/openconnect"], "includePath": ["/opt/homebrew/include"],
"macFrameworkPath": ["/System/Library/Frameworks", "/Library/Frameworks"], "macFrameworkPath": ["/System/Library/Frameworks", "/Library/Frameworks"],
"intelliSenseMode": "macos-clang-x64", "intelliSenseMode": "macos-clang-x64",
"compilerPath": "/usr/bin/clang", "compilerPath": "/usr/bin/clang",
Generated
+1565 -2044
View File
File diff suppressed because it is too large. Load diff
+9 -16
View File
@@ -10,23 +10,21 @@ members = [
] ]
[workspace.package] [workspace.package]
rust-version = "1.89" rust-version = "1.80"
version = "2.5.2" version = "2.4.3"
authors = ["Kevin Yue <[email protected]>"] authors = ["Kevin Yue <[email protected]>"]
homepage = "https://github.com/yuezk/GlobalProtect-openconnect" homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
edition = "2024" edition = "2021"
license = "GPL-3.0" license = "GPL-3.0"
[workspace.dependencies] [workspace.dependencies]
anyhow = "1.0" anyhow = "1.0"
askama = "0.14"
base64 = "0.22" base64 = "0.22"
chrono = "0.4"
clap = { version = "4", features = ["derive"] } clap = { version = "4", features = ["derive"] }
clap-verbosity-flag = "3" clap-verbosity-flag = "3"
ctrlc = "3.4" ctrlc = "3.4"
directories = "6.0" directories = "5.0"
dns-lookup = "3" dns-lookup = "2.0.4"
env_logger = "0.11" env_logger = "0.11"
is_executable = "1.0" is_executable = "1.0"
log = "0.4" log = "0.4"
@@ -34,11 +32,10 @@ regex = "1"
reqwest = { version = "0.12", features = ["native-tls", "json"] } reqwest = { version = "0.12", features = ["native-tls", "json"] }
openssl = "0.10" openssl = "0.10"
pem = "3" pem = "3"
xmltree = "0.12" roxmltree = "0.20"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
# Use 0.36 as newer versions requires Rust 1.88+ sysinfo = "0.33"
sysinfo = "0.36"
tempfile = "3.8" tempfile = "3.8"
tokio = { version = "1" } tokio = { version = "1" }
tokio-util = "0.7" tokio-util = "0.7"
@@ -53,13 +50,9 @@ thiserror = "2"
redact-engine = "0.1" redact-engine = "0.1"
compile-time = "0.2" compile-time = "0.2"
serde_urlencoded = "0.7" serde_urlencoded = "0.7"
md5 = "0.8" md5 = "0.7"
sha256 = "1" sha256 = "1"
which = "8" which = "7"
uuid = "1"
netdev = "0.40"
machine-uid = "0.5"
humantime = "2"
# Tauri dependencies # Tauri dependencies
tauri = { version = "2" } tauri = { version = "2" }
+49 -47
View File
@@ -1,15 +1,13 @@
.SHELLFLAGS += -e .SHELLFLAGS += -e
OFFLINE ?= 0
BUILD_FE ?= 1
INCLUDE_GUI ?= 0 INCLUDE_GUI ?= 0
CARGO ?= cargo CARGO ?= cargo
DISABLE_RUST_TOOLCHAIN ?= 0 RUST_VERSION = 1.80
RUST_VERSION ?= 1.89
IGNORE_RUST_VERSION ?= 0
VERSION = $(shell grep '^version' Cargo.toml | head -1 | sed 's/version *= *"\(.*\)"/\1/') VERSION = $(shell $(CARGO) metadata --no-deps --format-version 1 | jq -r '.packages[0].version')
REVISION ?= 1 REVISION ?= 1
RPM_SOURCE ?= %{name}.tar.gz
PPA_REVISION ?= 1 PPA_REVISION ?= 1
PKG_NAME = globalprotect-openconnect PKG_NAME = globalprotect-openconnect
PKG = $(PKG_NAME)-$(VERSION) PKG = $(PKG_NAME)-$(VERSION)
@@ -17,16 +15,11 @@ SERIES ?= $(shell lsb_release -cs)
PUBLISH ?= 0 PUBLISH ?= 0
# Indicates whether to build the GUI components # Indicates whether to build the GUI components
BUILD_GUI_HELPER ?= 1 BUILD_GUI ?= 1
export DEBEMAIL = [email protected] export DEBEMAIL = [email protected]
export DEBFULLNAME = Kevin Yue export DEBFULLNAME = Kevin Yue
export SNAPSHOT = $(shell test -f SNAPSHOT && echo "true" || echo "false") export SNAPSHOT = $(shell test -f SNAPSHOT && echo "true" || echo "false")
export OFFLINE_BUILD = $(shell test -f OFFLINE_BUILD && echo "1" || echo "0")
# If OFFLINE is not set, use OFFLINE_BUILD
ifndef OFFLINE
OFFLINE = $(OFFLINE_BUILD)
endif
ifeq ($(SNAPSHOT), true) ifeq ($(SNAPSHOT), true)
RELEASE_TAG = snapshot RELEASE_TAG = snapshot
@@ -40,10 +33,6 @@ ifeq ($(OFFLINE), 1)
CARGO_BUILD_ARGS += --frozen CARGO_BUILD_ARGS += --frozen
endif endif
ifeq ($(IGNORE_RUST_VERSION), 1)
CARGO_BUILD_ARGS += --ignore-rust-version
endif
default: build default: build
version: version:
@@ -57,15 +46,21 @@ clean-tarball:
# Create a tarball, include the cargo dependencies if OFFLINE is set to 1 # Create a tarball, include the cargo dependencies if OFFLINE is set to 1
tarball: clean-tarball tarball: clean-tarball
if [ $(BUILD_GUI) -eq 1 ] && [ $(BUILD_FE) -eq 1 ]; then \
echo "Building frontend..."; \
cd apps/gpgui-helper && pnpm install && pnpm build; \
fi
# Remove node_modules to reduce the tarball size
rm -rf apps/gpgui-helper/node_modules
mkdir -p .cargo mkdir -p .cargo
mkdir -p .build/tarball mkdir -p .build/tarball
# If OFFLINE is set to 1, vendor all cargo dependencies # If OFFLINE is set to 1, vendor all cargo dependencies
# Generate a OFFLINE_BUILD file to indicate offline build
if [ $(OFFLINE) -eq 1 ]; then \ if [ $(OFFLINE) -eq 1 ]; then \
$(CARGO) vendor .vendor > .cargo/config.toml; \ $(CARGO) vendor .vendor > .cargo/config.toml; \
tar -cJf vendor.tar.xz .vendor; \ tar -cJf vendor.tar.xz .vendor; \
touch OFFLINE_BUILD; \
fi fi
@echo "Creating tarball..." @echo "Creating tarball..."
@@ -84,21 +79,31 @@ download-gui:
echo "Skipping GlobalProtect GUI download (INCLUDE_GUI=0)"; \ echo "Skipping GlobalProtect GUI download (INCLUDE_GUI=0)"; \
fi fi
build: download-gui build-rs build: download-gui build-fe build-rs
# Install and build the frontend
# If OFFLINE is set to 1, skip it
build-fe:
if [ $(BUILD_GUI) -eq 0 ] || [ $(OFFLINE) -eq 1 ] || [ $(BUILD_FE) -eq 0 ]; then \
echo "Skipping frontend build (BUILD_GUI=0 or OFFLINE=1 or BUILD_FE=0)"; \
else \
cd apps/gpgui-helper && pnpm install && pnpm build; \
fi
if [ $(BUILD_GUI) -eq 1 ] && [ ! -d apps/gpgui-helper/dist ]; then \
echo "Error: frontend build failed"; \
exit 1; \
fi
build-rs: build-rs:
if [ $(OFFLINE) -eq 1 ]; then \ if [ $(OFFLINE) -eq 1 ]; then \
tar -xJf vendor.tar.xz; \ tar -xJf vendor.tar.xz; \
fi fi
# Remove the rust-toolchain.toml if DISABLE_RUST_TOOLCHAIN is set to 1 # Only build the GUI components if BUILD_GUI is set to 1
if [ $(DISABLE_RUST_TOOLCHAIN) -eq 1 ]; then \ if [ $(BUILD_GUI) -eq 1 ]; then \
rm -vf rust-toolchain.toml; \ $(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice -p gpauth; \
fi $(CARGO) build $(CARGO_BUILD_ARGS) -p gpgui-helper --features "tauri/custom-protocol"; \
# Only build the GUI components if BUILD_GUI_HELPER is set to 1
if [ $(BUILD_GUI_HELPER) -eq 1 ]; then \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice -p gpauth -p gpgui-helper; \
else \ else \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice -p gpauth --no-default-features; \ $(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice -p gpauth --no-default-features; \
fi fi
@@ -116,8 +121,8 @@ install:
install -Dm755 target/release/gpauth $(DESTDIR)/usr/bin/gpauth install -Dm755 target/release/gpauth $(DESTDIR)/usr/bin/gpauth
install -Dm755 target/release/gpservice $(DESTDIR)/usr/bin/gpservice install -Dm755 target/release/gpservice $(DESTDIR)/usr/bin/gpservice
# Install the GUI components if BUILD_GUI_HELPER is set to 1 # Install the GUI components if BUILD_GUI is set to 1
if [ $(BUILD_GUI_HELPER) -eq 1 ]; then \ if [ $(BUILD_GUI) -eq 1 ]; then \
install -Dm755 target/release/gpgui-helper $(DESTDIR)/usr/bin/gpgui-helper; \ install -Dm755 target/release/gpgui-helper $(DESTDIR)/usr/bin/gpgui-helper; \
fi fi
@@ -125,9 +130,6 @@ install:
install -Dm755 .build/gpgui/gpgui_*/gpgui $(DESTDIR)/usr/bin/gpgui; \ install -Dm755 .build/gpgui/gpgui_*/gpgui $(DESTDIR)/usr/bin/gpgui; \
fi fi
install -Dm755 packaging/files/usr/libexec/gpclient/vpnc-script $(DESTDIR)/usr/libexec/gpclient/vpnc-script
install -Dm755 packaging/files/usr/libexec/gpclient/hipreport.sh $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
# Install the disconnect hooks # 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/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 -Dm755 packaging/files/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
@@ -148,9 +150,6 @@ uninstall:
rm -f $(DESTDIR)/usr/bin/gpgui-helper rm -f $(DESTDIR)/usr/bin/gpgui-helper
rm -f $(DESTDIR)/usr/bin/gpgui rm -f $(DESTDIR)/usr/bin/gpgui
rm -f $(DESTDIR)/usr/libexec/gpclient/vpnc-script
rm -f $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down 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/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
@@ -177,28 +176,28 @@ init-debian: clean-debian tarball
cp -f packaging/deb/postrm .build/deb/$(PKG)/debian/postrm cp -f packaging/deb/postrm .build/deb/$(PKG)/debian/postrm
cp -f packaging/deb/compat .build/deb/$(PKG)/debian/compat cp -f packaging/deb/compat .build/deb/$(PKG)/debian/compat
sed -i "s/@RUST_VERSION@/$(RUST_VERSION)/g" .build/deb/$(PKG)/debian/control sed -i "s/@OFFLINE@/$(OFFLINE)/g" .build/deb/$(PKG)/debian/rules
sed -i "s/@BUILD_GUI@/$(BUILD_GUI)/g" .build/deb/$(PKG)/debian/rules
sed -i "s/@RUST_VERSION@/$(RUST_VERSION)/g" .build/deb/$(PKG)/debian/rules
# Remove the GUI dependencies if BUILD_GUI_HELPER is set to 0 # Remove the GUI dependencies if BUILD_GUI is set to 0
if [ $(BUILD_GUI_HELPER) -eq 0 ]; then \ if [ $(BUILD_GUI) -eq 0 ]; then \
sed -i "/libxml2/d" .build/deb/$(PKG)/debian/control; \
sed -i "/libsecret-1-0/d" .build/deb/$(PKG)/debian/control; \ sed -i "/libsecret-1-0/d" .build/deb/$(PKG)/debian/control; \
sed -i "/libayatana-appindicator3-1/d" .build/deb/$(PKG)/debian/control; \ sed -i "/libayatana-appindicator3-1/d" .build/deb/$(PKG)/debian/control; \
sed -i "/gnome-keyring/d" .build/deb/$(PKG)/debian/control; \ sed -i "/gnome-keyring/d" .build/deb/$(PKG)/debian/control; \
sed -i "/libwebkit2gtk-4.1-dev/d" .build/deb/$(PKG)/debian/control; \ sed -i "/libwebkit2gtk-4.1-dev/d" .build/deb/$(PKG)/debian/control; \
fi fi
sed -i "s/@BUILD_GUI_HELPER@/$(BUILD_GUI_HELPER)/g" .build/deb/$(PKG)/debian/rules
sed -i "s/@RUST_VERSION@/$(RUST_VERSION)/g" .build/deb/$(PKG)/debian/rules
rm -f .build/deb/$(PKG)/debian/changelog rm -f .build/deb/$(PKG)/debian/changelog
deb: init-debian deb: init-debian
# Remove the rust build dependency from the control file
sed -i "s/@RUST@//g" .build/deb/$(PKG)/debian/control
cd .build/deb/$(PKG) && dch --create --distribution unstable --package $(PKG_NAME) --newversion $(VERSION)-$(REVISION) "Bugfix and improvements." cd .build/deb/$(PKG) && dch --create --distribution unstable --package $(PKG_NAME) --newversion $(VERSION)-$(REVISION) "Bugfix and improvements."
# Install build dependencies cd .build/deb/$(PKG) && debuild --preserve-env -e PATH -us -uc -b
cd .build/deb/$(PKG) && sudo mk-build-deps --install --remove debian/control || echo "mk-build-deps failed, continuing"
cd .build/deb/$(PKG) && debuild --preserve-env -e PATH -us -uc -b -d
check-ppa: check-ppa:
if [ $(OFFLINE) -eq 0 ]; then \ if [ $(OFFLINE) -eq 0 ]; then \
@@ -207,6 +206,8 @@ check-ppa:
# Usage: make ppa SERIES=focal OFFLINE=1 PUBLISH=1 # Usage: make ppa SERIES=focal OFFLINE=1 PUBLISH=1
ppa: check-ppa init-debian ppa: check-ppa init-debian
sed -i "s/@RUST@/cargo-1.80/g" .build/deb/$(PKG)/debian/control
$(eval SERIES_VER = $(shell distro-info --series $(SERIES) -r | cut -d' ' -f1)) $(eval SERIES_VER = $(shell distro-info --series $(SERIES) -r | cut -d' ' -f1))
@echo "Building for $(SERIES) $(SERIES_VER)" @echo "Building for $(SERIES) $(SERIES_VER)"
@@ -233,7 +234,7 @@ init-rpm: clean-rpm
sed -i "s/@VERSION@/$(VERSION)/g" .build/rpm/globalprotect-openconnect.spec 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/@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 sed -i "s/@DATE@/$(shell LC_ALL=en.US date "+%a %b %d %Y")/g" .build/rpm/globalprotect-openconnect.spec
sed -i "s/@VERSION@/$(VERSION)/g" .build/rpm/globalprotect-openconnect.changes sed -i "s/@VERSION@/$(VERSION)/g" .build/rpm/globalprotect-openconnect.changes
@@ -266,6 +267,7 @@ init-pkgbuild: clean-pkgbuild tarball
sed -i "s/@PKG_NAME@/$(PKG_NAME)/g" .build/pkgbuild/PKGBUILD sed -i "s/@PKG_NAME@/$(PKG_NAME)/g" .build/pkgbuild/PKGBUILD
sed -i "s/@VERSION@/$(VERSION)/g" .build/pkgbuild/PKGBUILD sed -i "s/@VERSION@/$(VERSION)/g" .build/pkgbuild/PKGBUILD
sed -i "s/@REVISION@/$(REVISION)/g" .build/pkgbuild/PKGBUILD sed -i "s/@REVISION@/$(REVISION)/g" .build/pkgbuild/PKGBUILD
sed -i "s/@OFFLINE@/$(OFFLINE)/g" .build/pkgbuild/PKGBUILD
pkgbuild: init-pkgbuild pkgbuild: init-pkgbuild
cd .build/pkgbuild && makepkg -s --noconfirm cd .build/pkgbuild && makepkg -s --noconfirm
@@ -281,7 +283,7 @@ binary: clean-binary tarball
mkdir -p .build/binary/$(PKG_NAME)_$(VERSION)/artifacts mkdir -p .build/binary/$(PKG_NAME)_$(VERSION)/artifacts
make -C .build/binary/${PKG} build INCLUDE_GUI=$(INCLUDE_GUI) make -C .build/binary/${PKG} build OFFLINE=$(OFFLINE) BUILD_FE=0 INCLUDE_GUI=$(INCLUDE_GUI)
make -C .build/binary/${PKG} install DESTDIR=$(PWD)/.build/binary/$(PKG_NAME)_$(VERSION)/artifacts make -C .build/binary/${PKG} install DESTDIR=$(PWD)/.build/binary/$(PKG_NAME)_$(VERSION)/artifacts
cp packaging/binary/Makefile.in .build/binary/$(PKG_NAME)_$(VERSION)/Makefile cp packaging/binary/Makefile.in .build/binary/$(PKG_NAME)_$(VERSION)/Makefile
+93 -303
View File
@@ -1,52 +1,32 @@
# GlobalProtect-openconnect # GlobalProtect-openconnect
A modern GlobalProtect VPN client for Linux, built on OpenConnect with full support for SSO authentication. This project provides both command-line and graphical interfaces for seamless VPN connectivity. A GUI for GlobalProtect VPN, based on OpenConnect, supports the SSO authentication method. Inspired by [gp-saml-gui](https://github.com/dlenski/gp-saml-gui).
<p align="center"> <p align="center">
<img width="300" src="https://github.com/user-attachments/assets/2fb6116c-dc57-43f2-af75-9c3d97ab7122"> <img width="300" src="https://github.com/yuezk/GlobalProtect-openconnect/assets/3297602/9242df9c-217d-42ab-8c21-8f9f69cd4eb5">
</p> </p>
> **Inspired by** [gp-saml-gui](https://github.com/dlenski/gp-saml-gui)
## Table of Contents
- [Features](#features)
- [Usage](#usage)
- [Command-Line Interface](#command-line-interface)
- [Graphical User Interface](#graphical-user-interface)
- [Installation](#installation)
- [Debian / Ubuntu](#debian--ubuntu)
- [Arch Linux / Manjaro](#arch-linux--manjaro)
- [Fedora 38+ / Rawhide](#fedora-38--rawhide)
- [openSUSE Leap 15.6+ / Tumbleweed](#opensuse-leap-156--tumbleweed)
- [Other RPM-based Distributions](#other-rpm-based-distributions)
- [Gentoo](#gentoo)
- [NixOS](#nixos)
- [Other Distributions](#other-distributions)
- [Building from Source](#building-from-source)
- [Frequently Asked Questions](#frequently-asked-questions)
- [License](#license)
## Features ## Features
- **Cross-Platform Linux Support** – Optimized for various Linux distributions - [x] Better Linux support
- **Dual Interface** – Available as both CLI and GUI applications - [x] Support both CLI and GUI
- **Flexible Authentication** – Supports SSO, non-SSO, FIDO2 (e.g., YubiKey), and client certificate authentication - [x] Support both SSO and non-SSO authentication
- **Browser Integration** – Authenticate using your default browser or any specified browser - [x] Support the FIDO2 authentication (e.g., YubiKey)
- **Multi-Portal Support** – Connect to multiple portals and gateways - [x] Support authentication using default browser
- **Direct Gateway Connection** – Bypass portal selection when needed - [x] Support client certificate authentication
- **Auto-Connect** – Automatically connect on system startup - [x] Support multiple portals
- **System Tray Integration** – Convenient system tray icon (requires [gnome-shell-extension-appindicator](https://extensions.gnome.org/extension/615/appindicator-support/) on GNOME) - [x] Support gateway selection
- [x] Support connect gateway directly
- [x] Support auto-connect on startup
- [x] Support system tray icon
## Usage ## Usage
### Command-Line Interface ### CLI
The CLI version is fully open source and feature-rich, providing nearly identical functionality to the GUI version. The CLI version is always free and open source in this repo. It has almost the same features as the GUI version.
#### Basic Commands ```
```bash
Usage: gpclient [OPTIONS] <COMMAND> Usage: gpclient [OPTIONS] <COMMAND>
Commands: Commands:
@@ -56,70 +36,54 @@ Commands:
help Print this message or the help of the given subcommand(s) help Print this message or the help of the given subcommand(s)
Options: Options:
--fix-openssl Get around the OpenSSL 'unsafe legacy renegotiation' error --fix-openssl Get around the OpenSSL `unsafe legacy renegotiation` error
--ignore-tls-errors Ignore TLS errors --ignore-tls-errors Ignore the TLS errors
-h, --help Print help -h, --help Print help
-V, --version Print version -V, --version Print version
See 'gpclient help <command>' for more information on a specific command.
``` ```
> **Tip:** Use `gpclient help <command>` for detailed information on a specific command. To use the external browser for authentication with the CLI version, you need to use the following command:
#### External Browser Authentication
For browser-based authentication with the CLI:
**Method 1:** Using sudo with environment preservation:
```bash
sudo -E gpclient connect --browser <portal>
```
**Method 2:** Using authentication piping:
```bash
gpauth <portal> --browser 2>/dev/null | sudo gpclient connect <portal> --cookie-on-stdin
```
**Browser Options:**
- Use `--browser <browser>` to specify a browser (e.g., `firefox`, `chrome`)
- Use `--browser remote` for headless servers – this provides a URL you can access from another machine to complete authentication
### Graphical User Interface
The GUI application provides an intuitive interface for managing VPN connections. Launch it from your application menu or via the terminal:
```bash ```bash
gpclient launch-gui sudo -E gpclient connect --browser default <portal>
``` ```
Or you can try the following command if the above command does not work:
```bash
gpauth <portal> --browser default 2>/dev/null | sudo gpclient connect <portal> --cookie-on-stdin
```
You can specify the browser with the `--browser <browser>` option, e.g., `--browser firefox`, `--browser chrome`, etc.
### GUI
The GUI version is also available after you installed it. You can launch it from the application menu or run `gpclient launch-gui` in the terminal.
> [!Note] > [!Note]
> >
> The GUI version is partially open source. The background service ([gpservice](./apps/gpservice/)) is open source, while the GUI wrapper is proprietary. > The GUI version is partially open source. Its background service is open sourced in this repo as [gpservice](./apps/gpservice/). The GUI part is a wrapper of the background service, which is not open sourced.
## Installation ## Installation
> [!Note] ### Debian/Ubuntu based distributions
>
> For older Linux distributions, use [v2.3.13](https://github.com/yuezk/GlobalProtect-openconnect/releases/tag/v2.3.13) instead of the latest release. It provides release assets for common distro families, including Debian/Ubuntu (`.deb`), Arch Linux / Manjaro (`.pkg.tar.zst`), RPM-based distros such as Fedora / RHEL / Rocky / AlmaLinux / CentOS (`.rpm`), and generic Linux tarballs (`.bin.tar.xz`).
### Debian / Ubuntu #### Install from PPA
#### Option 1: Install from PPA (Recommended) ```
```bash
sudo add-apt-repository ppa:yuezk/globalprotect-openconnect sudo add-apt-repository ppa:yuezk/globalprotect-openconnect
sudo apt-get update
sudo apt-get install globalprotect-openconnect sudo apt-get install globalprotect-openconnect
``` ```
> [!Note] > [!Note]
> >
> **For Linux Mint users:** If you encounter a GPG key error, import the key manually: > 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`.
> ```bash
> sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 7937C393082992E5D6E4A60453FC26B43838D761
> ```
#### Option 2: Install from DEB Package #### Install from deb package
Download the latest `.deb` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install: Download the latest deb package from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page. Then install it with `apt`:
```bash ```bash
sudo apt install --fix-broken globalprotect-openconnect_*.deb sudo apt install --fix-broken globalprotect-openconnect_*.deb
@@ -127,60 +91,44 @@ sudo apt install --fix-broken globalprotect-openconnect_*.deb
### Arch Linux / Manjaro ### Arch Linux / Manjaro
#### Option 1: Install from AUR #### Install from AUR
Package: [globalprotect-openconnect-git](https://aur.archlinux.org/packages/globalprotect-openconnect-git/) Install from AUR: [globalprotect-openconnect-git](https://aur.archlinux.org/packages/globalprotect-openconnect-git/)
You can install it using an AUR helper like [`yay`](https://github.com/Jguer/yay):
```bash ```bash
yay -S globalprotect-openconnect-git yay -S globalprotect-openconnect-git
``` ```
#### Option 2: Install from the Official Extra Repository #### Install from package
The package is also available in the official Arch Linux Extra repository. Download the latest package from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page. Then install it with `pacman`:
Package: [globalprotect-openconnect](https://archlinux.org/packages/extra/x86_64/globalprotect-openconnect/)
> [!Note]
>
> Since the official package does not include the system tray support dependency, you need to install `libappindicator` manually:
```bash
sudo pacman -S libappindicator globalprotect-openconnect
```
#### Option 3: Install from Package
Download the latest package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
```bash ```bash
sudo pacman -U globalprotect-openconnect-*.pkg.tar.zst sudo pacman -U globalprotect-openconnect-*.pkg.tar.zst
``` ```
### Fedora 38+ / Rawhide ### Fedora 38 and later / Fedora Rawhide
#### Install from COPR #### Install from COPR
The package is available on [COPR](https://copr.fedorainfracloud.org/coprs/yuezk/globalprotect-openconnect/) for RPM-based distributions: The package is available on [COPR](https://copr.fedorainfracloud.org/coprs/yuezk/globalprotect-openconnect/) for various RPM-based distributions. You can install it with the following commands:
```bash ```bash
sudo dnf copr enable yuezk/globalprotect-openconnect sudo dnf copr enable yuezk/globalprotect-openconnect
sudo dnf install globalprotect-openconnect sudo dnf install globalprotect-openconnect
``` ```
### openSUSE Leap 15.6+ / Tumbleweed ### openSUSE Leap 15.6 / openSUSE Tumbleweed
#### Install from OBS (openSUSE Build Service) #### Install from OBS (openSUSE Build Service)
Packages are available on the [openSUSE Build Service](https://build.opensuse.org/package/show/home:yuezk/globalprotect-openconnect). Follow the [installation instructions](https://software.opensuse.org//download.html?project=home%3Ayuezk&package=globalprotect-openconnect) for your distribution. The package is also available on [OBS](https://build.opensuse.org/package/show/home:yuezk/globalprotect-openconnect) for various RPM-based distributions. You can follow the instructions [on this page](https://software.opensuse.org//download.html?project=home%3Ayuezk&package=globalprotect-openconnect) to install it.
### Other RPM-based Distributions ### Other RPM-based distributions
#### Install from RPM Package #### Install from RPM package
Download the latest RPM package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page: Download the latest RPM package from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page.
```bash ```bash
sudo rpm -i globalprotect-openconnect-*.rpm sudo rpm -i globalprotect-openconnect-*.rpm
@@ -188,225 +136,67 @@ sudo rpm -i globalprotect-openconnect-*.rpm
### Gentoo ### Gentoo
Available via the `guru` and `lamdness` overlays: It is available via `guru` and `lamdness` overlays.
```bash ```bash
sudo eselect repository enable guru sudo eselect repository enable guru
sudo emerge --sync guru sudo emerge -r guru sync
sudo emerge --ask --verbose net-vpn/GlobalProtect-openconnect sudo emerge -av net-vpn/globalprotect-openconnect
``` ```
### NixOS ### Other distributions
This repository includes a flake for NixOS integration. - Install `openconnect >= 8.20`, `webkit2gtk`, `libsecret`, `libayatana-appindicator` or `libappindicator-gtk3`.
- Download `globalprotect-openconnect_${version}_${arch}.bin.tar.xz` from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page.
- Extract the tarball with `tar -xJf globalprotect-openconnect_${version}_${arch}.bin.tar.xz`.
- Run `sudo make install` to install the client.
If you want a quick user-level install, you can install it directly from the flake: ## Build from source
```bash You can also build the client from source, steps are as follows:
nix profile add github:yuezk/GlobalProtect-openconnect
```
If you want it managed as part of your NixOS system configuration, use the steps below. ### Prerequisites
#### Installation Steps - [Install Rust 1.80 or later](https://www.rust-lang.org/tools/install)
- Install Tauri dependencies: https://tauri.app/start/prerequisites/
- Install `perl` and `jq`
- Install `openconnect >= 8.20` and `libopenconnect-dev` (or `openconnect-devel` on RPM-based distributions)
- Install `pkexec`, `gnome-keyring` (or `pam_kwallet` on KDE)
- Install `nodejs` and `pnpm` (optional only if you downloaded the source tarball from the release page and run with the `BUILD_FE=0` flag, see below)
1. Add the flake to your `flake.nix`: ### Build
```nix 1. Download the source code tarball from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page. Choose `globalprotect-openconnect-${version}.tar.gz`.
{ 2. Extract the tarball with `tar -xzf globalprotect-openconnect-${version}.tar.gz`.
inputs = { 3. Enter the source directory and run `make build BUILD_FE=0` to build the client.
# ... other inputs 3. Run `sudo make install` to install the client. (Note, `DESTDIR` is not supported)
globalprotect-openconnect.url = "github:yuezk/GlobalProtect-openconnect";
};
outputs = { nixpkgs, ... }@inputs: { ## FAQ
nixosConfigurations.<your-host> = nixpkgs.lib.nixosSystem {
specialArgs = { inherit inputs; };
modules = [
./configuration.nix
];
};
};
}
```
2. Add the package to your `configuration.nix`: 1. How to deal with error `Secure Storage not ready`
```nix Try upgrade the client to `2.2.0` or later, which will use a file-based storage as a fallback.
{ config, pkgs, inputs, ... }:
{ You need to install the `gnome-keyring` package, and restart the system (See [#321](https://github.com/yuezk/GlobalProtect-openconnect/issues/321), [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)).
# ... other configurations
environment.systemPackages = with pkgs; [
# ... other packages
] ++ [
inputs.globalprotect-openconnect.packages.${pkgs.stdenv.hostPlatform.system}.default
];
}
```
3. Apply the changes: 2. How to deal with error `(gpauth:18869): Gtk-WARNING **: 10:33:37.566: cannot open display:`
```bash If you encounter this error when using the CLI version, try to run the command with `sudo -E` (See [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)).
sudo nixos-rebuild switch
```
### Other Distributions ## About Trial
#### Manual Installation The CLI version is always free, while the GUI version is paid. There are two trial modes for the GUI version:
1. **Install dependencies:** 1. 10-day trial: You can use the GUI stable release for 10 days after the installation.
- `webkit2gtk` 2. 14-day trial: Each beta release has a fresh trial period (at most 14 days) after released.
- `libsecret`
- `libayatana-appindicator` or `libappindicator-gtk3`
2. **Download and extract:** ## License
Download `globalprotect-openconnect_${version}_${arch}.bin.tar.xz` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page:
```bash
tar -xJf globalprotect-openconnect_${version}_${arch}.bin.tar.xz
```
3. **Install:** - crate [gpapi](./crates/gpapi): [MIT](./crates/gpapi/LICENSE)
```bash - crate [openconnect](./crates/openconnect): [GPL-3.0](./crates/openconnect/LICENSE)
sudo make install - crate [common](./crates/common): [GPL-3.0](./crates/common/LICENSE)
``` - crate [auth](./crates/auth): [GPL-3.0](./crates/auth/LICENSE)
- app [gpservice](./apps/gpservice): [GPL-3.0](./apps/gpservice/LICENSE)
## Building from Source - app [gpclient](./apps/gpclient): [GPL-3.0](./apps/gpclient/LICENSE)
- app [gpauth](./apps/gpauth): [GPL-3.0](./apps/gpauth/LICENSE)
You can build the application from source using either a DevContainer (recommended) or a local development environment. - app [gpgui-helper](./apps/gpgui-helper): [GPL-3.0](./apps/gpgui-helper/LICENSE)
### Method 1: Using DevContainer (Recommended)
This project includes a DevContainer configuration that provides a consistent, reproducible build environment with all dependencies pre-installed.
#### Prerequisites
- [Docker](https://docs.docker.com/get-docker/)
- [Visual Studio Code](https://code.visualstudio.com/) (optional, for IDE support)
- [Dev Containers extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) (if using VS Code)
#### Build Steps
1. **Clone the repository:**
```bash
git clone https://github.com/yuezk/GlobalProtect-openconnect.git
cd GlobalProtect-openconnect
git submodule update --init --recursive
```
2. **Build the DevContainer image:**
```bash
docker build -t gpoc-devcontainer .devcontainer/
```
3. **Build the project:**
To build everything including the GUI helper run this command:
```bash
docker run --privileged --cap-add=NET_ADMIN --device=/dev/net/tun \
--tty -v "$(pwd)":/workspace -w /workspace gpoc-devcontainer \
bash -c "export PATH=/usr/local/cargo/bin:\$PATH && make build"
```
To build without the GUI helper run the same command as above, but with `BUILD_GUI=0` passed as an argument to `make`.
5. **Locate build artifacts:**
The compiled binaries will be available in `target/release/`:
- `gpclient` – CLI client
- `gpservice` – Background service
- `gpauth` – Authentication helper
- `gpgui-helper` – GUI helper
#### Alternative: Using VS Code
1. Open the project in VS Code
2. When prompted, click "Reopen in Container" (or run **Dev Containers: Reopen in Container**)
3. Once the container is ready, open a terminal and run:
```bash
make build
```
### Method 2: Local Development Build
#### Prerequisites
- [Rust 1.89 or later](https://www.rust-lang.org/tools/install)
- [Tauri dependencies](https://tauri.app/start/prerequisites/)
- OpenConnect source-build dependencies: `autoconf`, `automake`, `autopoint`/`gettext`, `libtool`, `patch`, `pkg-config`, `libxml2`, `zlib`, `lz4`, `gnutls`, `p11-kit`, `nettle`, and `gmp` development packages
- `pkexec` and `gnome-keyring` (or `pam_kwallet` on KDE)
- `nodejs` and `pnpm` (optional)
#### Build Steps
1. **Download source code:**
Download `globalprotect-openconnect-${version}.tar.gz` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page.
2. **Extract and build:**
```bash
tar -xzf globalprotect-openconnect-${version}.tar.gz
cd globalprotect-openconnect-${version}
make build
```
3. **Install:**
```bash
sudo make install
```
> **Note:** `DESTDIR` is not currently supported.
### Testing Your Build
Verify the CLI client is working correctly:
```bash
./target/release/gpclient --help
```
### Build Options
- `BUILD_GUI_HELPER=0` – Build CLI components only (excludes GUI)
- `OFFLINE=1` – Build in offline mode using vendored dependencies
## Frequently Asked Questions
### Q: How do I resolve the "Secure Storage not ready" error?
**Solution 1:** Update to version 2.2.0 or later, which includes a file-based storage fallback.
**Solution 2:** Install the `gnome-keyring` package and restart your system.
See related issues: [#321](https://github.com/yuezk/GlobalProtect-openconnect/issues/321), [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)
### Q: How do I fix the "cannot open display" error when using CLI?
If you encounter `(gpauth:18869): Gtk-WARNING **: 10:33:37.566: cannot open display:`, try running the command with `sudo -E`:
```bash
sudo -E gpclient connect <portal>
```
See related issue: [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)
## Licensing
### Trial and Pricing
The **CLI version** is completely free and open source.
The **GUI version** is a paid application with a **7-day trial period** after installation.
### Open Source Licenses
This project consists of multiple components, each with its own license:
| Component | Type | License |
|-----------|------|---------|
| [gpapi](./crates/gpapi) | Crate | [MIT](./crates/gpapi/LICENSE) |
| [openconnect](./crates/openconnect) | Crate | [GPL-3.0](./crates/openconnect/LICENSE) |
| [common](./crates/common) | Crate | [GPL-3.0](./crates/common/LICENSE) |
| [auth](./crates/auth) | Crate | [GPL-3.0](./crates/auth/LICENSE) |
| [gpservice](./apps/gpservice) | Application | [GPL-3.0](./apps/gpservice/LICENSE) |
| [gpclient](./apps/gpclient) | Application | [GPL-3.0](./apps/gpclient/LICENSE) |
| [gpauth](./apps/gpauth) | Application | [GPL-3.0](./apps/gpauth/LICENSE) |
| [gpgui-helper](./apps/gpgui-helper) | Application | [GPL-3.0](./apps/gpgui-helper/LICENSE) |
+2 -3
View File
@@ -10,7 +10,6 @@ license.workspace = true
tauri-build = { version = "2", features = [], optional = true } tauri-build = { version = "2", features = [], optional = true }
[dependencies] [dependencies]
common = { path = "../../crates/common" }
gpapi = { path = "../../crates/gpapi", features = ["clap"] } gpapi = { path = "../../crates/gpapi", features = ["clap"] }
auth = { path = "../../crates/auth", features = ["browser-auth"] } auth = { path = "../../crates/auth", features = ["browser-auth"] }
@@ -25,8 +24,8 @@ tokio.workspace = true
tempfile.workspace = true tempfile.workspace = true
compile-time.workspace = true compile-time.workspace = true
# Pin to specific version due to MSRV # Pin the version of home because the latest version requires Rust 1.81
home = "=0.5.11" home = "=0.5.9"
# webview auth dependencies # webview auth dependencies
tauri = { workspace = true, optional = true } tauri = { workspace = true, optional = true }
+4 -6
View File
@@ -1,11 +1,11 @@
use auth::{BrowserAuthenticator, auth_prelogin}; use auth::{auth_prelogin, BrowserAuthenticator};
use clap::Parser; use clap::Parser;
use common::constants::GP_USER_AGENT;
use gpapi::{ use gpapi::{
auth::{SamlAuthData, SamlAuthResult}, auth::{SamlAuthData, SamlAuthResult},
clap::{Args, InfoLevelVerbosity, args::Os, handle_error}, clap::{args::Os, handle_error, Args, InfoLevelVerbosity},
gp_params::{ClientOs, GpParams}, gp_params::{ClientOs, GpParams},
utils::{normalize_server, openssl}, utils::{normalize_server, openssl},
GP_USER_AGENT,
}; };
use log::info; use log::info;
use serde_json::json; use serde_json::json;
@@ -62,9 +62,7 @@ struct Cli {
#[arg( #[arg(
long, long,
help = "The browser to use for authentication, e.g., `default`, `firefox`, `chrome`, `chromium`, or the path to the browser executable", help = "The browser to use for authentication, e.g., `default`, `firefox`, `chrome`, `chromium`, or the path to the browser executable"
default_missing_value = "default",
num_args=0..=1
)] )]
browser: Option<String>, browser: Option<String>,
+1 -6
View File
@@ -12,23 +12,18 @@ gpapi = { path = "../../crates/gpapi", features = ["clap"] }
openconnect = { path = "../../crates/openconnect" } openconnect = { path = "../../crates/openconnect" }
anyhow.workspace = true anyhow.workspace = true
askama.workspace = true
chrono.workspace = true
clap.workspace = true clap.workspace = true
env_logger.workspace = true env_logger.workspace = true
inquire = "0.9" inquire = "0.7"
log.workspace = true log.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] } tokio = { workspace = true, features = ["rt-multi-thread"] }
sysinfo.workspace = true sysinfo.workspace = true
serde_json.workspace = true serde_json.workspace = true
serde_urlencoded.workspace = true
whoami.workspace = true whoami.workspace = true
tempfile.workspace = true tempfile.workspace = true
reqwest.workspace = true reqwest.workspace = true
directories.workspace = true directories.workspace = true
compile-time.workspace = true compile-time.workspace = true
netdev.workspace = true
xmltree.workspace = true
[features] [features]
default = ["webview-auth"] default = ["webview-auth"]
+3 -7
View File
@@ -3,7 +3,7 @@ use std::{env::temp_dir, fs::File, str::FromStr};
use anyhow::bail; use anyhow::bail;
use clap::{Parser, Subcommand}; use clap::{Parser, Subcommand};
use gpapi::{ use gpapi::{
clap::{Args, InfoLevelVerbosity, handle_error}, clap::{handle_error, Args, InfoLevelVerbosity},
utils::openssl, utils::openssl,
}; };
use log::info; use log::info;
@@ -12,11 +12,10 @@ use tempfile::NamedTempFile;
use tokio::fs; use tokio::fs;
use crate::{ use crate::{
GP_CLIENT_LOCK_FILE,
connect::{ConnectArgs, ConnectHandler}, connect::{ConnectArgs, ConnectHandler},
disconnect::{DisconnectArgs, DisconnectHandler}, disconnect::{DisconnectArgs, DisconnectHandler},
hip::{HipArgs, HipHandler},
launch_gui::{LaunchGuiArgs, LaunchGuiHandler}, launch_gui::{LaunchGuiArgs, LaunchGuiHandler},
GP_CLIENT_LOCK_FILE,
}; };
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")"); const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
@@ -35,8 +34,6 @@ enum CliCommand {
Disconnect(DisconnectArgs), Disconnect(DisconnectArgs),
#[command(about = "Launch the GUI")] #[command(about = "Launch the GUI")]
LaunchGui(LaunchGuiArgs), LaunchGui(LaunchGuiArgs),
#[command(about = "Generate HIP report")]
Hip(HipArgs),
} }
#[derive(Parser)] #[derive(Parser)]
@@ -114,7 +111,7 @@ impl Cli {
async fn run(&self) -> anyhow::Result<()> { async fn run(&self) -> anyhow::Result<()> {
// check if an instance is running // check if an instance is running
if !matches!(self.command, CliCommand::Disconnect(_)) && self.is_running().await { if self.is_running().await {
bail!("Another instance of the client is already running"); bail!("Another instance of the client is already running");
} }
@@ -135,7 +132,6 @@ impl Cli {
CliCommand::Connect(args) => ConnectHandler::new(args, &shared_args).handle().await, CliCommand::Connect(args) => ConnectHandler::new(args, &shared_args).handle().await,
CliCommand::Disconnect(args) => DisconnectHandler::new(args).handle().await, CliCommand::Disconnect(args) => DisconnectHandler::new(args).handle().await,
CliCommand::LaunchGui(args) => LaunchGuiHandler::new(args).handle().await, CliCommand::LaunchGui(args) => LaunchGuiHandler::new(args).handle().await,
CliCommand::Hip(args) => HipHandler::new(args).handle().await,
} }
} }
} }
+85 -320
View File
@@ -1,42 +1,28 @@
use std::{ use std::{cell::RefCell, fs, sync::Arc};
borrow::Cow,
cell::RefCell,
fs,
sync::{Arc, Mutex},
};
use anyhow::{Context, bail}; use anyhow::bail;
use clap::Args; use clap::Args;
use common::constants::{GP_CLIENT_VERSION, GP_USER_AGENT}; use common::vpn_utils::find_csd_wrapper;
use gpapi::{ use gpapi::{
auth::SamlAuthResult, auth::SamlAuthResult,
clap::{ToVerboseArg, args::Os}, clap::{args::Os, ToVerboseArg},
credential::{Credential, PasswordCredential}, credential::{Credential, PasswordCredential},
error::PortalError, error::PortalError,
gateway::{GatewayLogin, SessionExtensionAuth, gateway_login}, gateway::{gateway_login, GatewayLogin},
gp_params::{ClientOs, GpParams}, gp_params::{ClientOs, GpParams},
portal::{Prelogin, StandardPrelogin, prelogin, retrieve_config}, portal::{prelogin, retrieve_config, Prelogin},
process::{ process::{
auth_launcher::SamlAuthLauncher, auth_launcher::SamlAuthLauncher,
users::{get_non_root_user, get_user_by_name}, users::{get_non_root_user, get_user_by_name},
}, },
utils::{host_utils, request::RequestIdentityError, shutdown_signal}, utils::{request::RequestIdentityError, shutdown_signal},
GP_USER_AGENT,
}; };
use inquire::{Password, PasswordDisplayMode, Select, Text}; use inquire::{Password, PasswordDisplayMode, Select, Text};
use log::{info, warn}; use log::{info, warn};
use openconnect::Vpn; use openconnect::Vpn;
use tokio::{runtime::Handle, task::JoinHandle};
use crate::{ use crate::{cli::SharedArgs, GP_CLIENT_LOCK_FILE};
GP_CLIENT_LOCK_FILE,
cli::SharedArgs,
session::{SessionContextInput, build_session_context, session_info_from_vpn, spawn_session_runtime_with_info},
};
struct GatewayLoginSession {
cookie: String,
extension_auth: SessionExtensionAuth,
}
#[derive(Args)] #[derive(Args)]
pub(crate) struct ConnectArgs { pub(crate) struct ConnectArgs {
@@ -55,28 +41,17 @@ pub(crate) struct ConnectArgs {
#[arg(long, help = "Read the cookie from standard input")] #[arg(long, help = "Read the cookie from standard input")]
cookie_on_stdin: bool, cookie_on_stdin: bool,
#[arg(long, short, help = "The VPNC script to use", required_if_eq("script_tun", "true"))] #[arg(long, short, help = "The VPNC script to use")]
script: Option<String>, script: Option<String>,
#[arg(long, short, help = "The IFNAME for tunnel interface")]
interface: Option<String>,
#[arg(long, short = 'S', help = "Pass traffic to '--script' program, not tun")]
script_tun: bool,
#[arg(long, help = "Connect the server as a gateway, instead of a portal")] #[arg(long, help = "Connect the server as a gateway, instead of a portal")]
as_gateway: bool, as_gateway: bool,
#[arg( #[arg(
long, long,
help = "Use HIP (Host Integrity Protection) extension, optionally specify the HIP script path", help = "Use the default CSD wrapper to generate the HIP report and send it to the server"
default_missing_value = "",
num_args=0..=1
)] )]
hip: Option<String>, hip: bool,
#[arg(long, help = "The user used to run the HIP script")]
hip_user: Option<String>,
#[arg( #[arg(
short, short,
@@ -91,10 +66,10 @@ pub(crate) struct ConnectArgs {
#[arg(short = 'p', long, help = "The key passphrase of the private key")] #[arg(short = 'p', long, help = "The key passphrase of the private key")]
key_password: Option<String>, key_password: Option<String>,
#[arg(long, help = "Deprecated: Use the '--hip-user' option instead")] #[arg(long, help = "Same as the '--csd-user' option in the openconnect command")]
csd_user: Option<String>, csd_user: Option<String>,
#[arg(long, help = "Deprecated: Use the '--hip' option instead")] #[arg(long, help = "Same as the '--csd-wrapper' option in the openconnect command")]
csd_wrapper: Option<String>, csd_wrapper: Option<String>,
#[arg(long, default_value = "300", help = "Reconnection retry timeout in seconds")] #[arg(long, default_value = "300", help = "Reconnection retry timeout in seconds")]
@@ -106,11 +81,8 @@ pub(crate) struct ConnectArgs {
#[arg(long, help = "Do not ask for IPv6 connectivity")] #[arg(long, help = "Do not ask for IPv6 connectivity")]
disable_ipv6: bool, disable_ipv6: bool,
#[arg( #[arg(long, default_value = GP_USER_AGENT, help = "The user agent to use")]
long, user_agent: String,
help = "The user agent to use, if not specified, it will be generated based on the OS and client version"
)]
user_agent: Option<String>,
#[arg(long, value_enum, default_value_t = ConnectArgs::default_os())] #[arg(long, value_enum, default_value_t = ConnectArgs::default_os())]
os: Os, os: Os,
@@ -118,30 +90,9 @@ pub(crate) struct ConnectArgs {
#[arg(long, help = "If not specified, it will be computed based on the --os option")] #[arg(long, help = "If not specified, it will be computed based on the --os option")]
os_version: Option<String>, os_version: Option<String>,
#[arg(long, help = "The GP client version to emulate, e.g., '6.2.4-49'")]
client_version: Option<String>,
#[arg(long, help = "Disable DTLS and ESP")] #[arg(long, help = "Disable DTLS and ESP")]
no_dtls: bool, no_dtls: bool,
#[arg(
long = "local-hostname",
help = "Same as the '--local-hostname' option in the openconnect command"
)]
local_hostname: Option<String>,
#[arg(
long = "force-dpd",
help = "Same as the '--force-dpd' option in the openconnect command"
)]
dpd_interval: Option<u32>,
#[arg(
long = "no-xmlpost",
help = "Same as the '--no-xmlpost' option in the openconnect command"
)]
no_xmlpost: bool,
#[cfg(feature = "webview-auth")] #[cfg(feature = "webview-auth")]
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")] #[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
hidpi: bool, hidpi: bool,
@@ -151,38 +102,34 @@ pub(crate) struct ConnectArgs {
clean: bool, clean: bool,
#[cfg(feature = "webview-auth")] #[cfg(feature = "webview-auth")]
#[arg(long, help = "Deprecated: Use the `--browser` option instead")] #[arg(long, help = "Use the default browser to authenticate")]
default_browser: bool, default_browser: bool,
#[cfg(feature = "webview-auth")]
#[arg( #[arg(
long, long,
help = "Use the specified browser to authenticate, e.g., `default`, `firefox`, `chrome`, `chromium`, `remote`.\nOr the path to the browser executable.\nUse 'remote' for headless servers.", help = "Use the specified browser to authenticate, e.g., `default`, `firefox`, `chrome`, `chromium`, or the path to the browser executable"
default_missing_value = "default",
num_args=0..=1
)] )]
browser: Option<String>, browser: Option<String>,
} }
impl ConnectArgs { impl ConnectArgs {
fn default_os() -> Os { fn default_os() -> Os {
#[cfg(target_os = "macos")] if cfg!(target_os = "macos") {
return Os::Mac; Os::Mac
#[cfg(target_os = "windows")] } else {
return Os::Windows; Os::Linux
#[cfg(not(any(target_os = "macos", target_os = "windows")))] }
return Os::Linux;
} }
fn os_version(&self) -> &str { fn os_version(&self) -> String {
if let Some(os_version) = self.os_version.as_deref() { if let Some(os_version) = self.os_version.as_deref() {
return os_version; return os_version.to_string();
} }
match self.os { match self.os {
Os::Linux => host_utils::get_linux_os_string(), Os::Linux => format!("Linux {}", whoami::distro()),
Os::Windows => host_utils::get_windows_os_string(), Os::Windows => String::from("Microsoft Windows 11 Pro , 64-bit"),
Os::Mac => host_utils::get_macos_os_string(), Os::Mac => String::from("Apple Mac OS X 13.4.0"),
} }
} }
} }
@@ -191,8 +138,6 @@ pub(crate) struct ConnectHandler<'a> {
args: &'a ConnectArgs, args: &'a ConnectArgs,
shared_args: &'a SharedArgs<'a>, shared_args: &'a SharedArgs<'a>,
latest_key_password: RefCell<Option<String>>, latest_key_password: RefCell<Option<String>>,
password_from_stdin: RefCell<Option<String>>,
cookie_from_stdin: RefCell<Option<String>>,
} }
impl<'a> ConnectHandler<'a> { impl<'a> ConnectHandler<'a> {
@@ -201,41 +146,19 @@ impl<'a> ConnectHandler<'a> {
args, args,
shared_args, shared_args,
latest_key_password: Default::default(), latest_key_password: Default::default(),
password_from_stdin: Default::default(),
cookie_from_stdin: Default::default(),
}
}
fn user_agent(&self) -> Cow<'_, str> {
if let Some(user_agent) = self.args.user_agent.as_deref() {
Cow::Borrowed(user_agent)
} else {
let client_version = self.args.client_version.as_deref().unwrap_or(GP_CLIENT_VERSION);
Cow::Owned(format!(
"{}/{} ({})",
GP_USER_AGENT,
client_version,
self.args.os_version()
))
} }
} }
fn build_gp_params(&self) -> GpParams { fn build_gp_params(&self) -> GpParams {
let mut builder = GpParams::builder(); GpParams::builder()
builder .user_agent(&self.args.user_agent)
.user_agent(&self.user_agent())
.client_os(ClientOs::from(&self.args.os)) .client_os(ClientOs::from(&self.args.os))
.os_version(self.args.os_version().to_owned()) .os_version(self.args.os_version())
.ignore_tls_errors(self.shared_args.ignore_tls_errors) .ignore_tls_errors(self.shared_args.ignore_tls_errors)
.certificate(self.args.certificate.clone()) .certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone()) .sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone()); .key_password(self.latest_key_password.borrow().clone())
.build()
if let Some(local_hostname) = self.args.local_hostname.as_deref() {
builder.computer(local_hostname);
}
builder.build()
} }
pub(crate) async fn handle(&self) -> anyhow::Result<()> { pub(crate) async fn handle(&self) -> anyhow::Result<()> {
@@ -244,19 +167,6 @@ impl<'a> ConnectHandler<'a> {
bail!("Cannot use `--default-browser` and `--browser` options at the same time"); bail!("Cannot use `--default-browser` and `--browser` options at the same time");
} }
// Warn if deprecated options are used and will be removed in the future
if self.args.csd_user.is_some() {
warn!(
"The '--csd-user' option is deprecated and will be removed in future releases, please use the '--hip-user' option instead"
);
}
if self.args.csd_wrapper.is_some() {
warn!(
"The '--csd-wrapper' option is deprecated and will be removed in future releases, please use the '--hip' option instead"
);
}
self.latest_key_password.replace(self.args.key_password.clone()); self.latest_key_password.replace(self.args.key_password.clone());
loop { loop {
@@ -294,9 +204,7 @@ impl<'a> ConnectHandler<'a> {
if as_gateway { if as_gateway {
info!("Treating the server as a gateway"); info!("Treating the server as a gateway");
return self return self.connect_gateway_with_prelogin(server).await;
.connect_gateway_with_prelogin(server, server, self.args.client_version.as_deref(), false)
.await;
} }
let Err(err) = self.connect_portal_with_prelogin(server).await else { let Err(err) = self.connect_portal_with_prelogin(server).await else {
@@ -306,9 +214,7 @@ impl<'a> ConnectHandler<'a> {
warn!("Failed to connect portal with prelogin: {}", err); warn!("Failed to connect portal with prelogin: {}", err);
if err.root_cause().downcast_ref::<PortalError>().is_some() { if err.root_cause().downcast_ref::<PortalError>().is_some() {
info!("Trying the gateway authentication workflow..."); info!("Trying the gateway authentication workflow...");
self self.connect_gateway_with_prelogin(server).await?;
.connect_gateway_with_prelogin(server, server, self.args.client_version.as_deref(), false)
.await?;
eprintln!("\nNOTE: the server may be a gateway, not a portal."); eprintln!("\nNOTE: the server may be a gateway, not a portal.");
eprintln!("NOTE: try to use the `--as-gateway` option if you were authenticated twice."); eprintln!("NOTE: try to use the `--as-gateway` option if you were authenticated twice.");
@@ -351,42 +257,18 @@ impl<'a> ConnectHandler<'a> {
let gateway = selected_gateway.server(); let gateway = selected_gateway.server();
let cred = portal_config.auth_cookie().into(); let cred = portal_config.auth_cookie().into();
let login_session = match self.login_gateway(gateway, &cred, &gp_params).await { let cookie = match self.login_gateway(gateway, &cred, &gp_params).await {
Ok(login_session) => login_session, Ok(cookie) => cookie,
Err(err) => { Err(err) => {
info!("Gateway login failed: {}", err); info!("Gateway login failed: {}", err);
let client_version = self.args.client_version.as_deref().or_else(|| portal_config.version()); return self.connect_gateway_with_prelogin(gateway).await;
let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false);
return self
.connect_gateway_with_prelogin(portal, gateway, client_version, allow_extend_session)
.await;
} }
}; };
// Use the client version from the command line argument if specified, otherwise self.connect_gateway(gateway, &cookie).await
// use the version from the portal config if available
let client_version = self.args.client_version.as_deref().or_else(|| portal_config.version());
let allow_extend_session = portal_config.allow_extend_session().unwrap_or(false);
self
.connect_gateway(
portal,
gateway,
&login_session.cookie,
client_version,
allow_extend_session,
login_session.extension_auth,
)
.await
} }
async fn connect_gateway_with_prelogin( async fn connect_gateway_with_prelogin(&self, gateway: &str) -> anyhow::Result<()> {
&self,
portal: &str,
gateway: &str,
client_version: Option<&str>,
allow_extend_session: bool,
) -> anyhow::Result<()> {
info!("Performing the gateway authentication..."); info!("Performing the gateway authentication...");
let mut gp_params = self.build_gp_params(); let mut gp_params = self.build_gp_params();
@@ -395,36 +277,17 @@ impl<'a> ConnectHandler<'a> {
let prelogin = prelogin(gateway, &gp_params).await?; let prelogin = prelogin(gateway, &gp_params).await?;
let cred = self.obtain_credential(&prelogin, gateway).await?; let cred = self.obtain_credential(&prelogin, gateway).await?;
let login_session = self.login_gateway(gateway, &cred, &gp_params).await?; let cookie = self.login_gateway(gateway, &cred, &gp_params).await?;
self self.connect_gateway(gateway, &cookie).await
.connect_gateway(
portal,
gateway,
&login_session.cookie,
client_version,
allow_extend_session,
login_session.extension_auth,
)
.await
} }
async fn login_gateway( async fn login_gateway(&self, gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<String> {
&self,
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
) -> anyhow::Result<GatewayLoginSession> {
let mut gp_params = gp_params.clone(); let mut gp_params = gp_params.clone();
loop { loop {
match gateway_login(gateway, cred, &gp_params).await? { match gateway_login(gateway, cred, &gp_params).await? {
GatewayLogin::Cookie(cookie) => { GatewayLogin::Cookie(cookie) => return Ok(cookie),
return Ok(GatewayLoginSession {
cookie,
extension_auth: SessionExtensionAuth::new(cred.clone(), gp_params),
});
}
GatewayLogin::Mfa(message, input_str) => { GatewayLogin::Mfa(message, input_str) => {
let otp = Text::new(&message).prompt()?; let otp = Text::new(&message).prompt()?;
gp_params.set_input_str(&input_str); gp_params.set_input_str(&input_str);
@@ -436,67 +299,35 @@ impl<'a> ConnectHandler<'a> {
} }
} }
async fn connect_gateway( async fn connect_gateway(&self, gateway: &str, cookie: &str) -> anyhow::Result<()> {
&self,
portal: &str,
gateway: &str,
cookie: &str,
client_version: Option<&str>,
allow_extend_session: bool,
extension_auth: SessionExtensionAuth,
) -> anyhow::Result<()> {
let mtu = self.args.mtu.unwrap_or(0); let mtu = self.args.mtu.unwrap_or(0);
let (hip, csd_wrapper) = self.determine_hip_script(); let csd_uid = get_csd_uid(&self.args.csd_user)?;
let hip_user = self.determine_hip_user(); let csd_wrapper = if self.args.csd_wrapper.is_some() {
let csd_uid = get_uid(&hip_user)?; self.args.csd_wrapper.clone()
} else if self.args.hip {
find_csd_wrapper()
} else {
None
};
let os = ClientOs::from(&self.args.os).to_openconnect_os().to_owned(); let os = ClientOs::from(&self.args.os).to_openconnect_os().to_string();
let os_version = self.args.os_version().to_owned();
let client_version = client_version.map(|s| s.to_owned());
let session_ctx = build_session_context(SessionContextInput {
portal: portal.to_string(),
gateway: gateway.to_string(),
cookie: cookie.to_string(),
user_agent: self.user_agent().into_owned(),
os: ClientOs::from(&self.args.os),
os_version: os_version.clone(),
client_version: client_version.clone(),
certificate: self.args.certificate.clone(),
sslkey: self.args.sslkey.clone(),
key_password: self.latest_key_password.borrow().clone(),
disable_ipv6: self.args.disable_ipv6,
extension_auth: Some(extension_auth),
});
let vpn = Vpn::builder(gateway, cookie) let vpn = Vpn::builder(gateway, cookie)
.script(self.args.script.clone()) .script(self.args.script.clone())
.interface(self.args.interface.clone()) .user_agent(self.args.user_agent.clone())
.script_tun(self.args.script_tun)
.user_agent(self.user_agent().into_owned())
.os(Some(os)) .os(Some(os))
.os_version(Some(os_version))
.client_version(client_version)
.certificate(self.args.certificate.clone()) .certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone()) .sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone()) .key_password(self.latest_key_password.borrow().clone())
.hip(hip)
.csd_uid(csd_uid) .csd_uid(csd_uid)
.csd_wrapper(csd_wrapper) .csd_wrapper(csd_wrapper)
.reconnect_timeout(self.args.reconnect_timeout) .reconnect_timeout(self.args.reconnect_timeout)
.mtu(mtu) .mtu(mtu)
.disable_ipv6(self.args.disable_ipv6) .disable_ipv6(self.args.disable_ipv6)
.no_dtls(self.args.no_dtls) .no_dtls(self.args.no_dtls)
.local_hostname(self.args.local_hostname.clone())
.dpd_interval(self.args.dpd_interval.unwrap_or(0))
.no_xmlpost(self.args.no_xmlpost)
.build()?; .build()?;
let vpn = Arc::new(vpn); let vpn = Arc::new(vpn);
let vpn_clone = vpn.clone(); let vpn_clone = vpn.clone();
let runtime_handle = Handle::current();
let session_ctx = Arc::new(Mutex::new(Some(session_ctx)));
let session_task: Arc<Mutex<Option<JoinHandle<()>>>> = Arc::new(Mutex::new(None));
let session_task_on_connect = Arc::clone(&session_task);
let session_ctx_on_connect = Arc::clone(&session_ctx);
// Listen for the interrupt signal in the background // Listen for the interrupt signal in the background
tokio::spawn(async move { tokio::spawn(async move {
@@ -505,22 +336,7 @@ impl<'a> ConnectHandler<'a> {
vpn_clone.disconnect(); vpn_clone.disconnect();
}); });
vpn.connect(move |vpn_session_info| { vpn.connect(write_pid_file);
write_pid_file();
let Some(session_ctx) = session_ctx_on_connect.lock().unwrap().take() else {
return;
};
let session_info = session_info_from_vpn(vpn_session_info, allow_extend_session);
info!("VPN session info: {}", session_info.log_summary());
let task = spawn_session_runtime_with_info(&runtime_handle, session_ctx, session_info);
session_task_on_connect.lock().unwrap().replace(task);
});
if let Some(task) = session_task.lock().unwrap().take() {
task.abort();
}
if fs::metadata(GP_CLIENT_LOCK_FILE).is_ok() { if fs::metadata(GP_CLIENT_LOCK_FILE).is_ok() {
info!("Removing PID file"); info!("Removing PID file");
@@ -532,7 +348,7 @@ impl<'a> ConnectHandler<'a> {
async fn obtain_credential(&self, prelogin: &Prelogin, server: &str) -> anyhow::Result<Credential> { async fn obtain_credential(&self, prelogin: &Prelogin, server: &str) -> anyhow::Result<Credential> {
if self.args.cookie_on_stdin { if self.args.cookie_on_stdin {
return self.read_cookie_from_stdin(); return read_cookie_from_stdin();
} }
let is_gateway = prelogin.is_gateway(); let is_gateway = prelogin.is_gateway();
@@ -542,20 +358,17 @@ impl<'a> ConnectHandler<'a> {
let browser = if prelogin.support_default_browser() { let browser = if prelogin.support_default_browser() {
self.args.browser.as_deref() self.args.browser.as_deref()
} else if !cfg!(feature = "webview-auth") { } else if !cfg!(feature = "webview-auth") {
bail!( bail!("The server does not support authentication via the default browser and the gpclient is not built with the `webview-auth` feature");
"The server does not support authentication via the default browser and the gpclient is not built with the `webview-auth` feature"
);
} else { } else {
None None
}; };
let os_version = self.args.os_version(); let os_version = self.args.os_version();
let verbose = self.shared_args.verbose.to_verbose_arg(); let verbose = self.shared_args.verbose.to_verbose_arg();
let user_agent = self.user_agent();
let auth_launcher = SamlAuthLauncher::new(&self.args.server) let auth_launcher = SamlAuthLauncher::new(&self.args.server)
.gateway(is_gateway) .gateway(is_gateway)
.saml_request(prelogin.saml_request()) .saml_request(prelogin.saml_request())
.user_agent(&user_agent) .user_agent(&self.args.user_agent)
.os(self.args.os.as_str()) .os(self.args.os.as_str())
.os_version(Some(&os_version)) .os_version(Some(&os_version))
.fix_openssl(self.shared_args.fix_openssl) .fix_openssl(self.shared_args.fix_openssl)
@@ -584,97 +397,49 @@ impl<'a> ConnectHandler<'a> {
|user| Ok(user.to_owned()), |user| Ok(user.to_owned()),
)?; )?;
let password = self.obtain_password(prelogin)?; let password = if self.args.passwd_on_stdin {
info!("Reading password from standard input");
let mut input = String::new();
std::io::stdin().read_line(&mut input)?;
input.trim_end().to_owned()
} else {
Password::new(&format!("{}:", prelogin.label_password()))
.without_confirmation()
.with_display_mode(PasswordDisplayMode::Masked)
.prompt()?
};
let password_cred = PasswordCredential::new(&user, &password); let password_cred = PasswordCredential::new(&user, &password);
Ok(password_cred.into()) Ok(password_cred.into())
} }
} }
} }
}
fn read_cookie_from_stdin(&self) -> anyhow::Result<Credential> { fn read_cookie_from_stdin() -> anyhow::Result<Credential> {
// If the cookie has been read from stdin, use it directly info!("Reading cookie from standard input");
if let Some(cookie) = self.cookie_from_stdin.borrow().as_ref() {
info!("Reusing the cookie read from standard input");
return Credential::try_from(serde_json::from_str::<SamlAuthResult>(cookie)?);
}
info!("Reading cookie from standard input"); let mut cookie = String::new();
std::io::stdin().read_line(&mut cookie)?;
let mut cookie = String::new(); let Ok(auth_result) = serde_json::from_str::<SamlAuthResult>(cookie.trim_end()) else {
std::io::stdin().read_line(&mut cookie)?; bail!("Failed to parse auth data")
};
// Considering that the gateway connection may fail even though the cookie read Credential::try_from(auth_result)
// from stdin is correct. It may retry the gateway connection, so we need to
// save the cookie read from stdin to avoid reading stdin again.
self.cookie_from_stdin.replace(Some(cookie.trim_end().to_owned()));
let auth_result = serde_json::from_str::<SamlAuthResult>(cookie.trim_end()).context("Failed to parse auth data")?;
Credential::try_from(auth_result)
}
fn obtain_password(&self, prelogin: &StandardPrelogin) -> anyhow::Result<String> {
let password = if self.args.passwd_on_stdin {
// If the password has been read from stdin, use it directly
if let Some(password) = self.password_from_stdin.borrow().as_ref() {
info!("Reusing the password read from standard input");
return Ok(password.clone());
}
info!("Reading password from standard input");
let mut input = String::new();
std::io::stdin().read_line(&mut input)?;
let password = input.trim_end().to_owned();
// Considering that the gateway connection may fail even though the password read
// from stdin is correct. It may retry the gateway connection, so we need to
// save the password read from stdin to avoid reading stdin again.
self.password_from_stdin.replace(Some(password.clone()));
password
} else {
Password::new(&format!("{}:", prelogin.label_password()))
.without_confirmation()
.with_display_mode(PasswordDisplayMode::Masked)
.prompt()?
};
Ok(password)
}
fn determine_hip_script(&self) -> (bool, Option<String>) {
if let Some(hip) = &self.args.hip {
return if hip.is_empty() {
(true, None)
} else {
(true, Some(hip.clone()))
};
}
(self.args.csd_wrapper.is_some(), self.args.csd_wrapper.clone())
}
fn determine_hip_user(&self) -> Option<String> {
if let Some(hip_user) = &self.args.hip_user {
return Some(hip_user.clone());
}
self.args.csd_user.clone()
}
} }
fn write_pid_file() { fn write_pid_file() {
let pid = std::process::id(); let pid = std::process::id();
if let Err(err) = fs::write(GP_CLIENT_LOCK_FILE, pid.to_string()) { fs::write(GP_CLIENT_LOCK_FILE, pid.to_string()).unwrap();
warn!("Failed to write PID file: {}", err); info!("Wrote PID {} to {}", pid, GP_CLIENT_LOCK_FILE);
} else {
info!("Wrote PID {} to {}", pid, GP_CLIENT_LOCK_FILE);
}
} }
fn get_uid(user: &Option<String>) -> anyhow::Result<u32> { fn get_csd_uid(csd_user: &Option<String>) -> anyhow::Result<u32> {
if let Some(user) = user { if let Some(csd_user) = csd_user {
get_user_by_name(user).map(|user| user.uid()) get_user_by_name(csd_user).map(|user| user.uid())
} else { } else {
get_non_root_user().map_or_else(|_| Ok(0), |user| Ok(user.uid())) get_non_root_user().map_or_else(|_| Ok(0), |user| Ok(user.uid()))
} }
-374
View File
@@ -1,374 +0,0 @@
use askama::Template;
use clap::Args;
use gpapi::{clap::args::Os, utils::host_utils};
use log::debug;
use std::collections::HashMap;
use xmltree::Element;
#[derive(Template)]
#[template(path = "hip_report.xml")]
struct HipReportTemplate<'a> {
client_version: &'a str,
generate_time: String,
day: String,
month: String,
year: String,
user_name: &'a str,
host_info: HostInfo<'a>,
md5: &'a str,
}
/// Host information for HIP reporting
struct HostInfo<'a> {
/// Common for all OSes, e.g., "Apple", "Microsoft", "Linux"
os_vendor: &'a str,
/// Common for all OSes, e.g., "Linux Ubuntu 20.04", "Apple Mac OS X 10.15.7", etc.
os_version: &'a str,
/// Only for macOS and Windows
host_id: String,
/// Common for all OSes
host_name: String,
/// Only for macOS and Windows, e.g., "10.15.7", "10.0.19044.2130"
software_version: &'a str,
domain: String,
network_interfaces: Vec<NetworkInterface>,
}
impl<'a> HostInfo<'a> {
/// Get the first available IPv4 address from network interfaces
pub fn default_ipv4(&self) -> &str {
self
.network_interfaces
.first()
.and_then(|iface| iface.ipv4.as_deref())
.unwrap_or_default()
}
/// Get the first available IPv6 address from network interfaces
pub fn default_ipv6(&self) -> &str {
self
.network_interfaces
.first()
.and_then(|iface| iface.ipv6.as_deref())
.unwrap_or_default()
}
}
/// Network interface information
#[derive(Clone)]
struct NetworkInterface {
name: String,
description: String,
mac_address: Option<String>,
ipv4: Option<String>,
ipv6: Option<String>,
}
impl NetworkInterface {
/// Create a new network interface with basic information
fn new(name: String, description: String) -> Self {
Self {
name,
description,
mac_address: None,
ipv4: None,
ipv6: None,
}
}
/// Set MAC address
fn with_mac(mut self, mac: Option<String>) -> Self {
self.mac_address = mac;
self
}
/// Set IPv4 address
fn with_ipv4(mut self, ipv4: Option<String>) -> Self {
self.ipv4 = ipv4;
self
}
/// Set IPv6 address
fn with_ipv6(mut self, ipv6: Option<String>) -> Self {
self.ipv6 = ipv6;
self
}
}
#[derive(Args)]
pub(crate) struct HipArgs {
#[arg(long, help = "The GP client version, e.g., 6.2.4-49")]
client_version: String,
#[arg(long, value_enum, help = "The client OS")]
client_os: Os,
#[arg(long, help = "The OS version string, e.g., Apple Mac OS X 10.15.7")]
os_version: String,
#[arg(long, help = "The authentication cookie")]
cookie: String,
#[arg(long, help = "The client IPv4 address")]
client_ip: Option<String>,
#[arg(long, help = "The client IPv6 address")]
client_ipv6: Option<String>,
#[arg(long, help = "The MD5 digest to encode into the HIP report")]
md5: String,
}
pub(crate) struct HipHandler<'a> {
args: &'a HipArgs,
}
impl<'a> HipHandler<'a> {
pub(crate) fn new(args: &'a HipArgs) -> Self {
Self { args }
}
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
let cookie_params = self.parse_cookie();
let report = self.generate_hip_report(&cookie_params)?;
debug!("Generated HIP report:\n{}", report);
println!("{}", report);
Ok(())
}
fn parse_cookie(&self) -> HashMap<String, String> {
// Parse URL-encoded cookie string using serde_urlencoded
serde_urlencoded::from_str(&self.args.cookie).unwrap_or_default()
}
/// Generate the complete HIP report XML
fn generate_hip_report(&self, cookie_params: &HashMap<String, String>) -> anyhow::Result<String> {
let (generate_time, day, month, year) = get_current_time_components();
let user_name = cookie_params.get("user").map(|s| s.as_str()).unwrap_or("");
let host_info = self.collect_host_info(cookie_params);
let template = HipReportTemplate {
client_version: &self.args.client_version,
generate_time,
day,
month,
year,
user_name,
host_info,
md5: &self.args.md5,
};
let report = template.render()?;
format_xml(&report)
}
/// Collect host information based on the client OS
fn collect_host_info(&self, cookie_params: &'a HashMap<String, String>) -> HostInfo<'a> {
let collector = HostInfoCollector::new(self.args, cookie_params);
match self.args.client_os {
Os::Linux => collector.collect_linux(),
Os::Mac => collector.collect_macos(),
Os::Windows => collector.collect_windows(),
}
}
}
// ============================================================================
// Host Information Collector
// ============================================================================
/// Helper struct for collecting host information
struct HostInfoCollector<'a> {
args: &'a HipArgs,
cookie_params: &'a HashMap<String, String>,
}
impl<'a> HostInfoCollector<'a> {
fn new(args: &'a HipArgs, cookie_params: &'a HashMap<String, String>) -> Self {
Self { args, cookie_params }
}
/// Get domain from cookie parameters
fn get_domain(&self) -> String {
self
.cookie_params
.get("domain")
.map(|s| s.to_string())
.unwrap_or_default()
}
/// Collect network interface information with fallback
fn collect_network_interface(&self) -> NetworkInterface {
match netdev::get_default_interface() {
Ok(iface) => NetworkInterface::new(
iface.name.clone(),
iface.description.unwrap_or_else(|| iface.name.clone()),
)
.with_mac(iface.mac_addr.map(|mac| mac.address()))
.with_ipv4(iface.ipv4.first().map(|ip| ip.addr().to_string()))
.with_ipv6(iface.ipv6.first().map(|ip| ip.addr().to_string())),
Err(_) => NetworkInterface::new("unknown".to_string(), "unknown".to_string())
.with_ipv4(self.args.client_ip.clone())
.with_ipv6(self.args.client_ipv6.clone()),
}
}
/// Collect Linux-specific host information
fn collect_linux(&self) -> HostInfo<'a> {
let iface = self.collect_network_interface();
// Use the fixed interface name enp1s0f0 for Linux if it is not on Linux
let iface = NetworkInterface {
#[cfg(target_os = "linux")]
name: iface.name,
#[cfg(target_os = "linux")]
description: iface.description,
#[cfg(not(target_os = "linux"))]
name: "enp1s0f0".to_string(),
#[cfg(not(target_os = "linux"))]
description: "enp1s0f0".to_string(),
mac_address: iface.mac_address,
ipv4: iface.ipv4,
ipv6: iface.ipv6,
};
HostInfo {
os_vendor: "Linux",
os_version: &self.args.os_version,
host_id: host_utils::derive_uuid(&[]),
host_name: whoami::devicename(),
software_version: "",
domain: String::new(),
network_interfaces: vec![iface],
}
}
/// Collect macOS-specific host information
fn collect_macos(&self) -> HostInfo<'a> {
let iface = self.collect_network_interface();
// macOS use the mac address as host ID
let host_id = iface
.mac_address
.as_ref()
.map(|s| s.to_string())
.unwrap_or_else(|| "00:00:00:00:00:00".to_string());
// Use the fixed interface name en0 for macOS if it is not on macOS
let iface = NetworkInterface {
#[cfg(target_os = "macos")]
name: iface.name,
#[cfg(target_os = "macos")]
description: iface.description,
#[cfg(not(target_os = "macos"))]
name: "en0".to_string(),
#[cfg(not(target_os = "macos"))]
description: "en0".to_string(),
mac_address: iface.mac_address,
ipv4: iface.ipv4,
ipv6: iface.ipv6,
};
HostInfo {
os_vendor: "Apple",
os_version: &self.args.os_version,
host_id,
host_name: whoami::devicename(),
software_version: host_utils::get_macos_version(),
domain: self.get_domain(),
network_interfaces: vec![iface],
}
}
/// Collect Windows-specific host information
fn collect_windows(&self) -> HostInfo<'a> {
// Use the actual machine ID on Windows
#[cfg(target_os = "windows")]
let host_id = host_utils::get_machine_id().to_string();
#[cfg(not(target_os = "windows"))]
let host_id = host_utils::derive_uuid(&[]);
let iface = self.collect_network_interface();
// Use the fixed interface name if it is not on Windows
let iface = NetworkInterface {
#[cfg(target_os = "windows")]
name: iface.name,
#[cfg(target_os = "windows")]
description: iface.description,
#[cfg(not(target_os = "windows"))]
name: derive_windows_network_name(&iface),
#[cfg(not(target_os = "windows"))]
description: "PANGP Virtual Ethernet Adapter Secure".to_string(),
// mac address on windows should replace ':' with '-'
mac_address: iface.mac_address.map(|mac| mac.replace(':', "-")),
ipv4: iface.ipv4,
ipv6: iface.ipv6,
};
// Add the local loopback interface
let loopback_iface = NetworkInterface {
name: derive_windows_network_name(&iface),
description: "Software Loopback Interface 1".to_string(),
mac_address: Some(String::new()),
ipv4: Some("127.0.0.1".to_string()),
ipv6: Some("::1".to_string()),
};
let ifaces = vec![iface, loopback_iface];
HostInfo {
os_vendor: "Microsoft",
os_version: &self.args.os_version,
host_id,
host_name: whoami::devicename(),
software_version: host_utils::get_windows_version(),
domain: self.get_domain(),
network_interfaces: ifaces,
}
}
}
// ============================================================================
// Utility Functions
// ============================================================================
/// Get current time components for HIP report
fn get_current_time_components() -> (String, String, String, String) {
let now = chrono::Local::now();
(
now.format("%m/%d/%Y %H:%M:%S").to_string(),
now.format("%d").to_string(),
now.format("%m").to_string(),
now.format("%Y").to_string(),
)
}
/// Format XML string with proper indentation
fn format_xml(xml_str: &str) -> anyhow::Result<String> {
let xml = Element::parse(xml_str.as_bytes())?;
let config = xmltree::EmitterConfig::new().perform_indent(true);
let mut xml_buf = Vec::new();
xml.write_with_config(&mut xml_buf, config)?;
Ok(String::from_utf8(xml_buf)?)
}
fn derive_windows_network_name(iface: &NetworkInterface) -> String {
let seeds = [
iface.mac_address.as_deref().unwrap_or("00:00:00:00:00:00"),
iface.name.as_str(),
];
format!("{{{}}}", host_utils::derive_uuid(&seeds).to_uppercase())
}
+1 -1
View File
@@ -1,11 +1,11 @@
use std::{collections::HashMap, env::temp_dir, fs, path::PathBuf}; use std::{collections::HashMap, env::temp_dir, fs, path::PathBuf};
use clap::Args; use clap::Args;
use common::constants::GP_CALLBACK_PORT_FILENAME;
use directories::ProjectDirs; use directories::ProjectDirs;
use gpapi::{ use gpapi::{
process::service_launcher::ServiceLauncher, process::service_launcher::ServiceLauncher,
utils::{endpoint::http_endpoint, env_utils, shutdown_signal}, utils::{endpoint::http_endpoint, env_utils, shutdown_signal},
GP_CALLBACK_PORT_FILENAME,
}; };
use log::info; use log::info;
use tokio::io::AsyncWriteExt; use tokio::io::AsyncWriteExt;
-2
View File
@@ -1,9 +1,7 @@
mod cli; mod cli;
mod connect; mod connect;
mod disconnect; mod disconnect;
mod hip;
mod launch_gui; mod launch_gui;
mod session;
pub(crate) const GP_CLIENT_LOCK_FILE: &str = "/var/run/gpclient.lock"; pub(crate) const GP_CLIENT_LOCK_FILE: &str = "/var/run/gpclient.lock";
-252
View File
@@ -1,252 +0,0 @@
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use common::constants::GP_CLIENT_VERSION;
use gpapi::{
gateway::{SessionContext, SessionExtensionAuth, extend_session},
gp_params::ClientOs,
session::{SessionInfo, SessionRequestArgs, SessionWarning},
};
use log::{info, warn};
use openconnect::VpnSessionInfo;
use tokio::{runtime::Handle, task::JoinHandle};
#[derive(Debug, PartialEq, Eq)]
struct SessionWarningSchedule {
delay: Duration,
message: String,
should_auto_extend: bool,
}
pub(crate) struct SessionContextInput {
pub(crate) portal: String,
pub(crate) gateway: String,
pub(crate) cookie: String,
pub(crate) user_agent: String,
pub(crate) os: ClientOs,
pub(crate) os_version: String,
pub(crate) client_version: Option<String>,
pub(crate) certificate: Option<String>,
pub(crate) sslkey: Option<String>,
pub(crate) key_password: Option<String>,
pub(crate) disable_ipv6: bool,
pub(crate) extension_auth: Option<SessionExtensionAuth>,
}
pub(crate) fn build_session_context(input: SessionContextInput) -> SessionContext {
let session_args = SessionRequestArgs::new(input.cookie)
.with_user_agent(Some(input.user_agent))
.with_os(Some(input.os))
.with_os_version(Some(input.os_version))
.with_client_version(Some(
input.client_version.unwrap_or_else(|| GP_CLIENT_VERSION.to_string()),
))
.with_certificate(input.certificate)
.with_sslkey(input.sslkey)
.with_key_password(input.key_password)
.with_disable_ipv6(input.disable_ipv6);
let ctx = SessionContext::new(input.gateway, input.portal, session_args);
match input.extension_auth {
Some(extension_auth) => ctx.with_extension_auth(extension_auth),
None => ctx,
}
}
pub(crate) fn session_info_from_vpn(vpn_session_info: VpnSessionInfo, allow_extend_session: bool) -> SessionInfo {
SessionInfo::from_vpn_session_fields(
vpn_session_info.lifetime_secs,
vpn_session_info.user_expires,
vpn_session_info.lifetime_warning.map(|warning| SessionWarning {
prior_secs: warning.prior_secs,
message: warning.message,
}),
allow_extend_session,
)
}
pub(crate) fn spawn_session_runtime_with_info(
handle: &Handle,
session_ctx: SessionContext,
session_info: SessionInfo,
) -> JoinHandle<()> {
handle.spawn(run_session_runtime(session_ctx, session_info))
}
async fn run_session_runtime(session_ctx: SessionContext, mut session_info: SessionInfo) {
loop {
let Some(schedule) = build_session_warning_schedule(&session_info) else {
info!("No session warning schedule provided by the gateway");
return;
};
tokio::time::sleep(schedule.delay).await;
eprintln!("\nWARNING: {}", schedule.message);
if !schedule.should_auto_extend {
info!("Session extension is not allowed by the gateway");
return;
}
info!("Attempting to extend the session");
match extend_session(&session_ctx).await {
Ok(()) => {
let Some(next_session_info) = session_info.rescheduled_after_extension() else {
info!("Session extended, but no lifetime is available to schedule another warning");
return;
};
eprintln!("Session extended.");
session_info = next_session_info;
}
Err(err) => {
warn!("Failed to extend session: {}", err);
eprintln!("WARNING: Failed to extend session: {}", err);
return;
}
}
}
}
fn build_session_warning_schedule(session_info: &SessionInfo) -> Option<SessionWarningSchedule> {
let warning = session_info.lifetime_warning.as_ref()?;
let warning_secs = if let Some(user_expires) = session_info.user_expires {
let now = unix_timestamp();
user_expires.saturating_sub(warning.prior_secs).saturating_sub(now)
} else if let Some(lifetime_secs) = session_info.lifetime_secs {
lifetime_secs.saturating_sub(warning.prior_secs)
} else {
return None;
};
Some(SessionWarningSchedule {
delay: Duration::from_secs(warning_secs as u64),
message: warning.message.clone(),
should_auto_extend: session_info.allow_extend_session,
})
}
fn unix_timestamp() -> u32 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as u32
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_session_info(user_expires: Option<u32>, allow_extend_session: bool) -> SessionInfo {
SessionInfo {
user_expires,
lifetime_warning: Some(SessionWarning {
prior_secs: 1800,
message: "Session expires soon".to_string(),
}),
allow_extend_session,
..Default::default()
}
}
#[test]
fn builds_warning_schedule_for_auto_extend() {
let session_info = sample_session_info(Some(unix_timestamp() + 1830), true);
let schedule = build_session_warning_schedule(&session_info).unwrap();
assert_eq!(schedule.message, "Session expires soon");
assert!(schedule.delay <= Duration::from_secs(30));
assert!(schedule.should_auto_extend);
}
#[test]
fn builds_warning_schedule_without_auto_extend() {
let session_info = sample_session_info(Some(unix_timestamp() + 1830), false);
let schedule = build_session_warning_schedule(&session_info).unwrap();
assert!(!schedule.should_auto_extend);
}
#[test]
fn schedules_next_warning_after_extension_from_lifetime() {
let mut session_info = sample_session_info(Some(unix_timestamp() + 1830), true);
session_info.lifetime_secs = Some(7200);
let next_session_info = session_info.rescheduled_after_extension().unwrap();
let schedule = build_session_warning_schedule(&next_session_info).unwrap();
assert!(schedule.delay <= Duration::from_secs(5400));
}
#[test]
fn builds_session_context_from_cli_runtime_values() {
let ctx = build_session_context(SessionContextInput {
portal: "portal.example.com".to_string(),
gateway: "vpn.example.com".to_string(),
cookie: "authcookie=AUTH".to_string(),
user_agent: "UA".to_string(),
os: ClientOs::Mac,
os_version: "macOS 15.0".to_string(),
client_version: Some("6.3.1-12".to_string()),
certificate: Some("/tmp/client.pem".to_string()),
sslkey: Some("/tmp/client.key".to_string()),
key_password: Some("secret".to_string()),
disable_ipv6: true,
extension_auth: None,
});
assert_eq!(ctx.portal(), "portal.example.com");
assert_eq!(ctx.server(), "vpn.example.com");
assert_eq!(ctx.session_args().cookie(), "authcookie=AUTH");
assert_eq!(ctx.session_args().user_agent().as_deref(), Some("UA"));
assert!(matches!(ctx.session_args().os(), Some(ClientOs::Mac)));
assert_eq!(ctx.session_args().os_version().as_deref(), Some("macOS 15.0"));
assert_eq!(ctx.session_args().client_version().as_deref(), Some("6.3.1-12"));
assert_eq!(ctx.session_args().certificate().as_deref(), Some("/tmp/client.pem"));
assert_eq!(ctx.session_args().sslkey().as_deref(), Some("/tmp/client.key"));
assert_eq!(ctx.session_args().key_password().as_deref(), Some("secret"));
assert!(ctx.session_args().disable_ipv6());
}
#[test]
fn maps_openconnect_session_metadata_to_runtime_session_info() {
let info = session_info_from_vpn(
VpnSessionInfo {
lifetime_secs: Some(43_200),
user_expires: Some(1_776_828_409),
lifetime_warning: Some(openconnect::VpnSessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
},
true,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert_eq!(info.user_expires, Some(1_776_828_409));
assert_eq!(info.lifetime_warning.unwrap().prior_secs, 1_800);
assert!(info.allow_extend_session);
}
#[test]
fn direct_gateway_session_info_does_not_allow_extension_without_portal_policy() {
let info = session_info_from_vpn(
VpnSessionInfo {
lifetime_secs: Some(43_200),
user_expires: Some(1_776_828_409),
lifetime_warning: Some(openconnect::VpnSessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
},
false,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert_eq!(info.user_expires, Some(1_776_828_409));
assert_eq!(info.lifetime_warning.unwrap().prior_secs, 1_800);
assert!(!info.allow_extend_session);
}
}
-277
View File
@@ -1,277 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<hip-report name="hip-report">
<md5-sum>{{ md5 }}</md5-sum>
<user-name>{{ user_name }}</user-name>
<domain>{{ host_info.domain }}.internal</domain>
<host-name>{{ host_info.host_name }}</host-name>
<host-id>{{ host_info.host_id }}</host-id>
<ip-address>{{ host_info.default_ipv4() }}</ip-address>
<ipv6-address>{{ host_info.default_ipv6() }}</ipv6-address>
<generate-time>{{ generate_time }}</generate-time>
<hip-report-version>4</hip-report-version>
<categories>
<entry name="host-info">
<client-version>{{ client_version }}</client-version>
<os>{{ host_info.os_version }}</os>
<os-vendor>{{ host_info.os_vendor }}</os-vendor>
<domain>{{ host_info.domain }}.internal</domain>
<host-name>{{ host_info.host_name }}</host-name>
<host-id>{{ host_info.host_id }}</host-id>
<network-interface>
{% for iface in host_info.network_interfaces.iter() -%}
<entry name="{{ iface.name }}">
<description>{{ iface.description }}</description>
{% if let Some(mac) = iface.mac_address -%}
<mac-address>{{ mac }}</mac-address>
{% endif -%}
{% if let Some(ipv4) = iface.ipv4 -%}
<ip-address>
<entry name="{{ ipv4 }}"/>
</ip-address>
{% endif -%}
{% if let Some(ipv6) = iface.ipv6 -%}
<ipv6-address>
<entry name="{{ ipv6 }}"/>
</ipv6-address>
{% endif -%}
</entry>
{% endfor -%}
</network-interface>
</entry>
{% if host_info.os_vendor == "Microsoft" -%}
<entry name="antivirus">
<list>
<entry>
<ProductInfo>
<Prod name="McAfee VirusScan Enterprise" version="8.8.0.1804" defver="8682.0" prodType="1" engver="5900.7806" osType="1" vendor="McAfee, Inc." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>{{ generate_time }}</last-full-scan-time>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="Windows Defender" version="4.11.15063.332" defver="1.245.683.0" prodType="1" engver="1.1.13804.0" osType="1" vendor="Microsoft Corp." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>no</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="anti-spyware">
<list>
<entry>
<ProductInfo>
<Prod name="McAfee VirusScan Enterprise" version="8.8.0.1804" defver="8682.0" prodType="2" engver="5900.7806" osType="1" vendor="McAfee, Inc." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>{{ generate_time }}</last-full-scan-time>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="Windows Defender" version="4.11.15063.332" defver="1.245.683.0" prodType="2" engver="1.1.13804.0" osType="1" vendor="Microsoft Corp." dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>no</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-backup">
<list>
<entry>
<ProductInfo>
<Prod name="Windows Backup and Restore" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
</Prod>
<last-backup-time>n/a</last-backup-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-encryption">
<list>
<entry>
<ProductInfo>
<Prod name="Windows Drive Encryption" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
</Prod>
<drives>
<entry>
<drive-name>C:\\</drive-name>
<enc-state>full</enc-state>
</entry>
</drives>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="firewall">
<list>
<entry>
<ProductInfo>
<Prod name="Microsoft Windows Firewall" version="10.0.22621.4830" vendor="Microsoft Corp.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="patch-management">
<list>
<entry>
<ProductInfo>
<Prod name="McAfee ePolicy Orchestrator Agent" version="5.0.5.658" vendor="McAfee, Inc.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="Microsoft Windows Update Agent" version="{{ host_info.software_version }}" vendor="Microsoft Corp.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
<missing-patches/>
</entry>
{% elif host_info.os_vendor == "Apple" -%}
<entry name="anti-malware">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Xprotect" version="2167" defver="235000000000000" engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="4"/>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Gatekeeper" version="{{ host_info.software_version }}" defver="" engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="4"/>
<real-time-protection>yes</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-backup">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Time Machine" version="1.3"/>
<last-backup-time>n/a</last-backup-time>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="disk-encryption">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="FileVault" version="{{ host_info.software_version }}"/>
<drives>
<entry>
<drive-name>Macintosh HD</drive-name>
<enc-state>encrypted</enc-state>
</entry>
<entry>
<drive-name>Data</drive-name>
<enc-state>encrypted</enc-state>
</entry>
<entry>
<drive-name>All</drive-name>
<enc-state>encrypted</enc-state>
</entry>
</drives>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="firewall">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Mac OS X Builtin Firewall" version="{{ host_info.software_version }}"/>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod vendor="OpenBSD" name="Packet Filter" version="{{ host_info.software_version }}"/>
<is-enabled>no</is-enabled>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="patch-management">
<list>
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Software Update" version="3.0"/>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
<missing-patches>
</missing-patches>
</entry>
{% elif host_info.os_vendor == "Linux" -%}
<entry name="anti-malware">
<list/>
</entry>
<entry name="disk-backup">
<list/>
</entry>
<entry name="disk-encryption">
<list>
<entry>
<ProductInfo>
<Prod name="cryptsetup" version="2.3.3" vendor="GitLab Inc.">
</Prod>
<drives>
<entry>
<drive-name>/</drive-name>
<enc-state>encrypted</enc-state>
</entry>
</drives>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="firewall">
<list>
<entry>
<ProductInfo>
<Prod name="IPTables" version="1.8.4" vendor="IPTables">
</Prod>
<is-enabled>no</is-enabled>
</ProductInfo>
</entry>
<entry>
<ProductInfo>
<Prod name="nftables" version="0.9.3" vendor="The Netfilter Project">
</Prod>
<is-enabled>n/a</is-enabled>
</ProductInfo>
</entry>
</list>
</entry>
<entry name="patch-management">
<list>
<entry>
<ProductInfo>
<Prod name="Dandified Yum" version="4.2.23" vendor="Red Hat, Inc.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
<missing-patches/>
</entry>
{% endif -%}
<entry name="data-loss-prevention">
<list/>
</entry>
</categories>
</hip-report>
+1
View File
@@ -0,0 +1 @@
html,body,#root{height:100%;margin:0;padding:0;-webkit-user-select:none;user-select:none;cursor:default}
-1
View File
@@ -1 +0,0 @@
html,body,#root{-webkit-user-select:none;user-select:none;cursor:default;height:100%;margin:0;padding:0}
+193
View File
@@ -0,0 +1,193 @@
var zg=Object.defineProperty;var wg=(l,i,c)=>i in l?zg(l,i,{enumerable:!0,configurable:!0,writable:!0,value:c}):l[i]=c;var Ni=(l,i,c)=>wg(l,typeof i!="symbol"?i+"":i,c);function Rg(l,i){for(var c=0;c<i.length;c++){const o=i[c];if(typeof o!="string"&&!Array.isArray(o)){for(const s in o)if(s!=="default"&&!(s in l)){const d=Object.getOwnPropertyDescriptor(o,s);d&&Object.defineProperty(l,s,d.get?d:{enumerable:!0,get:()=>o[s]})}}}return Object.freeze(Object.defineProperty(l,Symbol.toStringTag,{value:"Module"}))}(function(){const i=document.createElement("link").relList;if(i&&i.supports&&i.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))o(s);new MutationObserver(s=>{for(const d of s)if(d.type==="childList")for(const m of d.addedNodes)m.tagName==="LINK"&&m.rel==="modulepreload"&&o(m)}).observe(document,{childList:!0,subtree:!0});function c(s){const d={};return s.integrity&&(d.integrity=s.integrity),s.referrerPolicy&&(d.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?d.credentials="include":s.crossOrigin==="anonymous"?d.credentials="omit":d.credentials="same-origin",d}function o(s){if(s.ep)return;s.ep=!0;const d=c(s);fetch(s.href,d)}})();function Mg(l){return l&&l.__esModule&&Object.prototype.hasOwnProperty.call(l,"default")?l.default:l}var Jo={exports:{}},Ui={};/**
* @license React
* react-jsx-runtime.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var wh;function Dg(){if(wh)return Ui;wh=1;var l=Symbol.for("react.transitional.element"),i=Symbol.for("react.fragment");function c(o,s,d){var m=null;if(d!==void 0&&(m=""+d),s.key!==void 0&&(m=""+s.key),"key"in s){d={};for(var b in s)b!=="key"&&(d[b]=s[b])}else d=s;return s=d.ref,{$$typeof:l,type:o,key:m,ref:s!==void 0?s:null,props:d}}return Ui.Fragment=i,Ui.jsx=c,Ui.jsxs=c,Ui}var Rh;function Bg(){return Rh||(Rh=1,Jo.exports=Dg()),Jo.exports}var rt=Bg(),Fo={exports:{}},Hi={},Po={exports:{}},Io={};/**
* @license React
* scheduler.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var Mh;function Ng(){return Mh||(Mh=1,function(l){function i(G,it){var tt=G.length;G.push(it);t:for(;0<tt;){var ot=tt-1>>>1,S=G[ot];if(0<s(S,it))G[ot]=it,G[tt]=S,tt=ot;else break t}}function c(G){return G.length===0?null:G[0]}function o(G){if(G.length===0)return null;var it=G[0],tt=G.pop();if(tt!==it){G[0]=tt;t:for(var ot=0,S=G.length,q=S>>>1;ot<q;){var at=2*(ot+1)-1,lt=G[at],J=at+1,bt=G[J];if(0>s(lt,tt))J<S&&0>s(bt,lt)?(G[ot]=bt,G[J]=tt,ot=J):(G[ot]=lt,G[at]=tt,ot=at);else if(J<S&&0>s(bt,tt))G[ot]=bt,G[J]=tt,ot=J;else break t}}return it}function s(G,it){var tt=G.sortIndex-it.sortIndex;return tt!==0?tt:G.id-it.id}if(l.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var d=performance;l.unstable_now=function(){return d.now()}}else{var m=Date,b=m.now();l.unstable_now=function(){return m.now()-b}}var v=[],p=[],C=1,_=null,w=3,j=!1,B=!1,U=!1,X=typeof setTimeout=="function"?setTimeout:null,Q=typeof clearTimeout=="function"?clearTimeout:null,F=typeof setImmediate<"u"?setImmediate:null;function V(G){for(var it=c(p);it!==null;){if(it.callback===null)o(p);else if(it.startTime<=G)o(p),it.sortIndex=it.expirationTime,i(v,it);else break;it=c(p)}}function L(G){if(U=!1,V(G),!B)if(c(v)!==null)B=!0,St();else{var it=c(p);it!==null&&_t(L,it.startTime-G)}}var O=!1,$=-1,W=5,gt=-1;function K(){return!(l.unstable_now()-gt<W)}function y(){if(O){var G=l.unstable_now();gt=G;var it=!0;try{t:{B=!1,U&&(U=!1,Q($),$=-1),j=!0;var tt=w;try{e:{for(V(G),_=c(v);_!==null&&!(_.expirationTime>G&&K());){var ot=_.callback;if(typeof ot=="function"){_.callback=null,w=_.priorityLevel;var S=ot(_.expirationTime<=G);if(G=l.unstable_now(),typeof S=="function"){_.callback=S,V(G),it=!0;break e}_===c(v)&&o(v),V(G)}else o(v);_=c(v)}if(_!==null)it=!0;else{var q=c(p);q!==null&&_t(L,q.startTime-G),it=!1}}break t}finally{_=null,w=tt,j=!1}it=void 0}}finally{it?Y():O=!1}}}var Y;if(typeof F=="function")Y=function(){F(y)};else if(typeof MessageChannel<"u"){var et=new MessageChannel,ct=et.port2;et.port1.onmessage=y,Y=function(){ct.postMessage(null)}}else Y=function(){X(y,0)};function St(){O||(O=!0,Y())}function _t(G,it){$=X(function(){G(l.unstable_now())},it)}l.unstable_IdlePriority=5,l.unstable_ImmediatePriority=1,l.unstable_LowPriority=4,l.unstable_NormalPriority=3,l.unstable_Profiling=null,l.unstable_UserBlockingPriority=2,l.unstable_cancelCallback=function(G){G.callback=null},l.unstable_continueExecution=function(){B||j||(B=!0,St())},l.unstable_forceFrameRate=function(G){0>G||125<G?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):W=0<G?Math.floor(1e3/G):5},l.unstable_getCurrentPriorityLevel=function(){return w},l.unstable_getFirstCallbackNode=function(){return c(v)},l.unstable_next=function(G){switch(w){case 1:case 2:case 3:var it=3;break;default:it=w}var tt=w;w=it;try{return G()}finally{w=tt}},l.unstable_pauseExecution=function(){},l.unstable_requestPaint=function(){},l.unstable_runWithPriority=function(G,it){switch(G){case 1:case 2:case 3:case 4:case 5:break;default:G=3}var tt=w;w=G;try{return it()}finally{w=tt}},l.unstable_scheduleCallback=function(G,it,tt){var ot=l.unstable_now();switch(typeof tt=="object"&&tt!==null?(tt=tt.delay,tt=typeof tt=="number"&&0<tt?ot+tt:ot):tt=ot,G){case 1:var S=-1;break;case 2:S=250;break;case 5:S=1073741823;break;case 4:S=1e4;break;default:S=5e3}return S=tt+S,G={id:C++,callback:it,priorityLevel:G,startTime:tt,expirationTime:S,sortIndex:-1},tt>ot?(G.sortIndex=tt,i(p,G),c(v)===null&&G===c(p)&&(U?(Q($),$=-1):U=!0,_t(L,tt-ot))):(G.sortIndex=S,i(v,G),B||j||(B=!0,St())),G},l.unstable_shouldYield=K,l.unstable_wrapCallback=function(G){var it=w;return function(){var tt=w;w=it;try{return G.apply(this,arguments)}finally{w=tt}}}}(Io)),Io}var Dh;function Ug(){return Dh||(Dh=1,Po.exports=Ng()),Po.exports}var ts={exports:{}},ht={};/**
* @license React
* react.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var Bh;function Hg(){if(Bh)return ht;Bh=1;var l=Symbol.for("react.transitional.element"),i=Symbol.for("react.portal"),c=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),d=Symbol.for("react.consumer"),m=Symbol.for("react.context"),b=Symbol.for("react.forward_ref"),v=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),C=Symbol.for("react.lazy"),_=Symbol.iterator;function w(S){return S===null||typeof S!="object"?null:(S=_&&S[_]||S["@@iterator"],typeof S=="function"?S:null)}var j={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},B=Object.assign,U={};function X(S,q,at){this.props=S,this.context=q,this.refs=U,this.updater=at||j}X.prototype.isReactComponent={},X.prototype.setState=function(S,q){if(typeof S!="object"&&typeof S!="function"&&S!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,S,q,"setState")},X.prototype.forceUpdate=function(S){this.updater.enqueueForceUpdate(this,S,"forceUpdate")};function Q(){}Q.prototype=X.prototype;function F(S,q,at){this.props=S,this.context=q,this.refs=U,this.updater=at||j}var V=F.prototype=new Q;V.constructor=F,B(V,X.prototype),V.isPureReactComponent=!0;var L=Array.isArray,O={H:null,A:null,T:null,S:null},$=Object.prototype.hasOwnProperty;function W(S,q,at,lt,J,bt){return at=bt.ref,{$$typeof:l,type:S,key:q,ref:at!==void 0?at:null,props:bt}}function gt(S,q){return W(S.type,q,void 0,void 0,void 0,S.props)}function K(S){return typeof S=="object"&&S!==null&&S.$$typeof===l}function y(S){var q={"=":"=0",":":"=2"};return"$"+S.replace(/[=:]/g,function(at){return q[at]})}var Y=/\/+/g;function et(S,q){return typeof S=="object"&&S!==null&&S.key!=null?y(""+S.key):q.toString(36)}function ct(){}function St(S){switch(S.status){case"fulfilled":return S.value;case"rejected":throw S.reason;default:switch(typeof S.status=="string"?S.then(ct,ct):(S.status="pending",S.then(function(q){S.status==="pending"&&(S.status="fulfilled",S.value=q)},function(q){S.status==="pending"&&(S.status="rejected",S.reason=q)})),S.status){case"fulfilled":return S.value;case"rejected":throw S.reason}}throw S}function _t(S,q,at,lt,J){var bt=typeof S;(bt==="undefined"||bt==="boolean")&&(S=null);var ft=!1;if(S===null)ft=!0;else switch(bt){case"bigint":case"string":case"number":ft=!0;break;case"object":switch(S.$$typeof){case l:case i:ft=!0;break;case C:return ft=S._init,_t(ft(S._payload),q,at,lt,J)}}if(ft)return J=J(S),ft=lt===""?"."+et(S,0):lt,L(J)?(at="",ft!=null&&(at=ft.replace(Y,"$&/")+"/"),_t(J,q,at,"",function(Yt){return Yt})):J!=null&&(K(J)&&(J=gt(J,at+(J.key==null||S&&S.key===J.key?"":(""+J.key).replace(Y,"$&/")+"/")+ft)),q.push(J)),1;ft=0;var ie=lt===""?".":lt+":";if(L(S))for(var At=0;At<S.length;At++)lt=S[At],bt=ie+et(lt,At),ft+=_t(lt,q,at,bt,J);else if(At=w(S),typeof At=="function")for(S=At.call(S),At=0;!(lt=S.next()).done;)lt=lt.value,bt=ie+et(lt,At++),ft+=_t(lt,q,at,bt,J);else if(bt==="object"){if(typeof S.then=="function")return _t(St(S),q,at,lt,J);throw q=String(S),Error("Objects are not valid as a React child (found: "+(q==="[object Object]"?"object with keys {"+Object.keys(S).join(", ")+"}":q)+"). If you meant to render a collection of children, use an array instead.")}return ft}function G(S,q,at){if(S==null)return S;var lt=[],J=0;return _t(S,lt,"","",function(bt){return q.call(at,bt,J++)}),lt}function it(S){if(S._status===-1){var q=S._result;q=q(),q.then(function(at){(S._status===0||S._status===-1)&&(S._status=1,S._result=at)},function(at){(S._status===0||S._status===-1)&&(S._status=2,S._result=at)}),S._status===-1&&(S._status=0,S._result=q)}if(S._status===1)return S._result.default;throw S._result}var tt=typeof reportError=="function"?reportError:function(S){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var q=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof S=="object"&&S!==null&&typeof S.message=="string"?String(S.message):String(S),error:S});if(!window.dispatchEvent(q))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",S);return}console.error(S)};function ot(){}return ht.Children={map:G,forEach:function(S,q,at){G(S,function(){q.apply(this,arguments)},at)},count:function(S){var q=0;return G(S,function(){q++}),q},toArray:function(S){return G(S,function(q){return q})||[]},only:function(S){if(!K(S))throw Error("React.Children.only expected to receive a single React element child.");return S}},ht.Component=X,ht.Fragment=c,ht.Profiler=s,ht.PureComponent=F,ht.StrictMode=o,ht.Suspense=v,ht.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=O,ht.act=function(){throw Error("act(...) is not supported in production builds of React.")},ht.cache=function(S){return function(){return S.apply(null,arguments)}},ht.cloneElement=function(S,q,at){if(S==null)throw Error("The argumeLine truncated
* @license React
* react-dom.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var Uh;function jg(){if(Uh)return de;Uh=1;var l=_s();function i(v){var p="https://react.dev/errors/"+v;if(1<arguments.length){p+="?args[]="+encodeURIComponent(arguments[1]);for(var C=2;C<arguments.length;C++)p+="&args[]="+encodeURIComponent(arguments[C])}return"Minified React error #"+v+"; visit "+p+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function c(){}var o={d:{f:c,r:function(){throw Error(i(522))},D:c,C:c,L:c,m:c,X:c,S:c,M:c},p:0,findDOMNode:null},s=Symbol.for("react.portal");function d(v,p,C){var _=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:s,key:_==null?null:""+_,children:v,containerInfo:p,implementation:C}}var m=l.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function b(v,p){if(v==="font")return"";if(typeof p=="string")return p==="use-credentials"?p:""}return de.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=o,de.createPortal=function(v,p){var C=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!p||p.nodeType!==1&&p.nodeType!==9&&p.nodeType!==11)throw Error(i(299));return d(v,p,null,C)},de.flushSync=function(v){var p=m.T,C=o.p;try{if(m.T=null,o.p=2,v)return v()}finally{m.T=p,o.p=C,o.d.f()}},de.preconnect=function(v,p){typeof v=="string"&&(p?(p=p.crossOrigin,p=typeof p=="string"?p==="use-credentials"?p:"":void 0):p=null,o.d.C(v,p))},de.prefetchDNS=function(v){typeof v=="string"&&o.d.D(v)},de.preinit=function(v,p){if(typeof v=="string"&&p&&typeof p.as=="string"){var C=p.as,_=b(C,p.crossOrigin),w=typeof p.integrity=="string"?p.integrity:void 0,j=typeof p.fetchPriority=="string"?p.fetchPriority:void 0;C==="style"?o.d.S(v,typeof p.precedence=="string"?p.precedence:void 0,{crossOrigin:_,integrity:w,fetchPriority:j}):C==="script"&&o.d.X(v,{crossOrigin:_,integrity:w,fetchPriority:j,nonce:typeof p.nonce=="string"?p.nonce:void 0})}},de.preinitModule=function(v,p){if(typeof v=="string")if(typeof p=="object"&&p!==null){if(p.as==null||p.as==="script"){var C=b(p.as,p.crossOrigin);o.d.M(v,{crossOrigin:C,integrity:typeof p.integrity=="string"?p.integrity:void 0,nonce:typeof p.nonce=="string"?p.nonce:void 0})}}else p==null&&o.d.M(v)},de.preload=function(v,p){if(typeof v=="string"&&typeof p=="object"&&p!==null&&typeof p.as=="string"){var C=p.as,_=b(C,p.crossOrigin);o.d.L(v,C,{crossOrigin:_,integrity:typeof p.integrity=="string"?p.integrity:void 0,nonce:typeof p.nonce=="string"?p.nonce:void 0,type:typeof p.type=="string"?p.type:void 0,fetchPriority:typeof p.fetchPriority=="string"?p.fetchPriority:void 0,referrerPolicy:typeof p.referrerPolicy=="string"?p.referrerPolicy:void 0,imageSrcSet:typeof p.imageSrcSet=="string"?p.imageSrcSet:void 0,imageSizes:typeof p.imageSizes=="string"?p.imageSizes:void 0,media:typeof p.media=="string"?p.media:void 0})}},de.preloadModule=function(v,p){if(typeof v=="string")if(p){var C=b(p.as,p.crossOrigin);o.d.m(v,{as:typeof p.as=="string"&&p.as!=="script"?p.as:void 0,crossOrigin:C,integrity:typeof p.integrity=="string"?p.integrity:void 0})}else o.d.m(v)},de.requestFormReset=function(v){o.d.r(v)},de.unstable_batchedUpdates=function(v,p){return v(p)},de.useFormState=function(v,p,C){return m.H.useFormState(v,p,C)},de.useFormStatus=function(){return m.H.useHostTransitionStatus()},de.version="19.0.0",de}var Hh;function qg(){if(Hh)return es.exports;Hh=1;function l(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(l)}catch(i){console.error(i)}}return l(),es.exports=jg(),es.exports}/**
* @license React
* react-dom-client.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var jh;function Lg(){if(jh)return Hi;jh=1;var l=Ug(),i=_s(),c=qg();function o(t){var e="https://react.dev/errors/"+t;if(1<arguments.length){e+="?args[]="+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)e+="&args[]="+encodeURIComponent(arguments[n])}return"Minified React error #"+t+"; visit "+e+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function s(t){return!(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11)}var d=Symbol.for("react.element"),m=Symbol.for("react.transitional.element"),b=Symbol.for("react.portal"),v=Symbol.for("react.fragment"),p=Symbol.for("react.strict_mode"),C=Symbol.for("react.profiler"),_=Symbol.for("react.provider"),w=Symbol.for("react.consumer"),j=Symbol.for("react.context"),B=Symbol.for("react.forward_ref"),U=Symbol.for("react.suspense"),X=Symbol.for("react.suspense_list"),Q=Symbol.for("react.memo"),F=Symbol.for("react.lazy"),V=Symbol.for("react.offscreen"),L=Symbol.for("react.memo_cache_sentinel"),O=Symbol.iterator;function $(t){return t===null||typeof t!="object"?null:(t=O&&t[O]||t["@@iterator"],typeof t=="function"?t:null)}var W=Symbol.for("react.client.reference");function gt(t){if(t==null)return null;if(typeof t=="function")return t.$$typeof===W?null:t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case v:return"Fragment";case b:return"Portal";case C:return"Profiler";case p:return"StrictMode";case U:return"Suspense";case X:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case j:return(t.displayName||"Context")+".Provider";case w:return(t._context.displayName||"Context")+".Consumer";case B:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case Q:return e=t.displayName||null,e!==null?e:gt(t.type)||"Memo";case F:e=t._payload,t=t._init;try{return gt(t(e))}catch{}}return null}var K=i.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,y=Object.assign,Y,et;function ct(t){if(Y===void 0)try{throw Error()}catch(n){var e=n.stack.trim().match(/\n( *(at )?)/);Y=e&&e[1]||"",et=-1<n.stack.indexOf(`
at`)?" (<anonymous>)":-1<n.stack.indexOf("@")?"@unknown:0:0":""}return`
`+Y+t+et}var St=!1;function _t(t,e){if(!t||St)return"";St=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var a={DetermineComponentFrameRoot:function(){try{if(e){var H=function(){throw Error()};if(Object.defineProperty(H.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(H,[])}catch(M){var z=M}Reflect.construct(t,[],H)}else{try{H.call()}catch(M){z=M}t.call(H.prototype)}}else{try{throw Error()}catch(M){z=M}(H=t())&&typeof H.catch=="function"&&H.catch(function(){})}}catch(M){if(M&&z&&typeof M.stack=="string")return[M.stack,z.stack]}return[null,null]}};a.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var u=Object.getOwnPropertyDescriptor(a.DetermineComponentFrameRoot,"name");u&&u.configurable&&Object.defineProperty(a.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var r=a.DetermineComponentFrameRoot(),f=r[0],h=r[1];if(f&&h){var g=f.split(`
`),A=h.split(`
`);for(u=a=0;a<g.length&&!g[a].includes("DetermineComponentFrameRoot");)a++;for(;u<A.length&&!A[u].includes("DetermineComponentFrameRoot");)u++;if(a===g.length||u===A.length)for(a=g.length-1,u=A.length-1;1<=a&&0<=u&&g[a]!==A[u];)u--;for(;1<=a&&0<=u;a--,u--)if(g[a]!==A[u]){if(a!==1||u!==1)do if(a--,u--,0>u||g[a]!==A[u]){var D=`
`+g[a].replace(" at new "," at ");return t.displayName&&D.includes("<anonymous>")&&(D=D.replace("<anonymous>",t.displayName)),D}while(1<=a&&0<=u);break}}}finally{St=!1,Error.prepareStackTrace=n}return(n=t?t.displayName||t.name:"")?ct(n):""}function G(t){switch(t.tag){case 26:case 27:case 5:return ct(t.type);case 16:return ct("Lazy");case 13:return ct("Suspense");case 19:return ct("SuspenseList");case 0:case 15:return t=_t(t.type,!1),t;case 11:return t=_t(t.type.render,!1),t;case 1:return t=_t(t.type,!0),t;default:return""}}function it(t){try{var e="";do e+=G(t),t=t.return;while(t);return e}catch(n){return`
Error generating stack: `+n.message+`
`+n.stack}}function tt(t){var e=t,n=t;if(t.alternate)for(;e.return;)e=e.return;else{t=e;do e=t,e.flags&4098&&(n=e.return),t=e.return;while(t)}return e.tag===3?n:null}function ot(t){if(t.tag===13){var e=t.memoizedState;if(e===null&&(t=t.alternate,t!==null&&(e=t.memoizedState)),e!==null)return e.dehydrated}return null}function S(t){if(tt(t)!==t)throw Error(o(188))}function q(t){var e=t.alternate;if(!e){if(e=tt(t),e===null)throw Error(o(188));return e!==t?null:t}for(var n=t,a=e;;){var u=n.return;if(u===null)break;var r=u.alternate;if(r===null){if(a=u.return,a!==null){n=a;continue}break}if(u.child===r.child){for(r=u.child;r;){if(r===n)return S(u),t;if(r===a)return S(u),e;r=r.sibling}throw Error(o(188))}if(n.return!==a.return)n=u,a=r;else{for(var f=!1,h=u.child;h;){if(h===n){f=!0,n=u,a=r;break}if(h===a){f=!0,a=u,n=r;break}h=h.sibling}if(!f){for(h=r.child;h;){if(h===n){f=!0,n=r,a=u;break}if(h===a){f=!0,a=r,n=u;break}h=h.sibling}if(!f)throw Error(o(189))}}if(n.alternate!==a)throw Error(o(190))}if(n.tag!==3)throw Error(o(188));return n.stateNode.current===n?t:e}function at(t){var e=t.tag;if(e===5||e===26||e===27||e===6)return t;for(t=t.child;t!==null;){if(e=at(t),e!==null)return e;t=t.sibling}return null}var lt=Array.isArray,J=c.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,bt={pending:!1,data:null,method:null,action:null},ft=[],ie=-1;function At(t){return{current:t}}function Yt(t){0>ie||(t.current=ft[ie],ft[ie]=null,ie--)}function Nt(t,e){ie++,ft[ie]=t.current,t.current=e}var De=At(null),oa=At(null),tn=At(null),Un=At(null);function Ha(t,e){switch(Nt(tn,e),Nt(oa,t),Nt(De,null),t=e.nodeType,t){case 9:case 11:e=(e=e.documentElement)&&(e=e.namespaceURI)?lh(e):0;break;default:if(t=t===8?e.parentNode:e,e=t.tagName,t=t.namespaceURI)t=lh(t),e=ih(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}Yt(De),Nt(De,e)}function Hn(){Yt(De),Yt(oa),Yt(tn)}function jn(t){t.memoizedState!==null&&Nt(Un,t);var e=De.current,n=ih(e,t.type);e!==n&&(Nt(oa,t),Nt(De,n))}function en(t){oa.current===t&&(Yt(De),Yt(oa)),Un.current===t&&(Yt(Un),wi._currentValue=bt)}var Hl=Object.prototype.hasOwnProperty,ja=l.unstable_scheduleCallback,jl=l.unstable_cancelCallback,dt=l.unstable_shouldYield,ry=l.unstable_requestPaint,nn=l.unstable_now,cy=l.unstable_getCurrentPriorityLevel,Qs=l.unstable_ImmediatePriority,Zs=l.unstable_UserBlockingPriority,tu=l.unstable_NormalPriority,oy=l.unstable_LowPriority,Ks=l.unstable_IdlePriority,sy=l.log,fy=l.unstable_setDisableYieldValue,ql=null,Te=null;function dy(t){if(Te&&typeof Te.onCommitFiberRoot=="function")try{Te.onCommitFiberRoot(ql,t,void 0,(t.current.flags&128)===128)}catch{}}function qn(t){if(typeof sy=="function"&&fy(t),Te&&typeof Te.setStrictMode=="function")try{Te.setStrictMode(ql,t)}catch{}}var Ae=Math.clz32?Math.clz32:yy,hy=Math.log,my=Math.LN2;function yy(t){return t>>>=0,t===0?32:31-(hy(t)/my|0)|0}var eu=128,nu=4194304;function sa(t){var e=t&42;if(e!==0)return e;switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t&4194176;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function au(t,e){var n=t.pendingLanes;if(n===0)return 0;var a=0,u=t.suspendedLanes,r=t.pingedLanes,f=t.warmLanes;t=t.finishedLanes!==0;var h=n&134217727;return h!==0?(n=h&~u,n!==0?a=sa(n):(r&=h,r!==0?a=sa(r):t||(f=h&~f,f!==0&&(a=sa(f))))):(h=n&~u,h!==0?a=sa(h):r!==0?a=sa(r):t||(f=n&~f,f!==0&&(a=sa(f)))),a===0?0:e!==0&&e!==a&&!(e&u)&&(u=a&-a,f=e&-e,u>=f||u===32&&(f&4194176)!==0)?e:a}function Ll(t,e){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&e)===0}function py(t,e){switch(t){case 1:case 2:case 4:case 8:return e+250;case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Ws(){var t=eu;return eu<<=1,!(eu&4194176)&&(eu=128),t}function Js(){var t=nu;return nu<<=1,!(nu&62914560)&&(nu=4194304),t}function $r(t){for(var e=[],n=0;31>n;n++)e.push(t);return e}function Gl(t,e){t.pendingLanes|=e,e!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function gy(t,e,n,a,u,r){var f=t.pendingLanes;t.pendingLanes=n,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=n,t.entangledLanes&=n,t.errorRecoveryDisabledLanes&=n,t.shellSuspendCounter=0;var h=t.entanglements,g=t.expirationTimes,A=t.hiddenUpdates;for(n=f&~n;0<n;){var D=31-Ae(n),H=1<<D; Line truncated
`).replace(Fp,"")}function ah(t,e){return e=nh(e),nh(t)===e}function Fu(){}function Rt(t,e,n,a,u,r){switch(n){case"children":typeof a=="string"?e==="body"||e==="textarea"&&a===""||Xa(t,a):(typeof a=="number"||typeof a=="bigint")&&e!=="body"&&Xa(t,""+a);break;case"className":iu(t,"class",a);break;case"tabIndex":iu(t,"tabindex",a);break;case"dir":case"role":case"viewBox":case"width":case"height":iu(t,n,a);break;case"style":hf(t,a,r);break;case"data":if(e!=="object"){iu(t,"data",a);break}case"src":case"href":if(a===""&&(e!=="a"||n!=="href")){t.removeAttribute(n);break}if(a==null||typeof a=="function"||typeof a=="symbol"||typeof a=="boolean"){t.removeAttribute(n);break}a=cu(""+a),t.setAttribute(n,a);break;case"action":case"formAction":if(typeof a=="function"){t.setAttribute(n,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof r=="function"&&(n==="formAction"?(e!=="input"&&Rt(t,e,"name",u.name,u,null),Rt(t,e,"formEncType",u.formEncType,u,null),Rt(t,e,"formMethod",u.formMethod,u,null),Rt(t,e,"formTarget",u.formTarget,u,null)):(Rt(t,e,"encType",u.encType,u,null),Rt(t,e,"method",u.method,u,null),Rt(t,e,"target",u.target,u,null)));if(a==null||typeof a=="symbol"||typeof a=="boolean"){t.removeAttribute(n);break}a=cu(""+a),t.setAttribute(n,a);break;case"onClick":a!=null&&(t.onclick=Fu);break;case"onScroll":a!=null&&vt("scroll",t);break;case"onScrollEnd":a!=null&&vt("scrollend",t);break;case"dangerouslySetInnerHTML":if(a!=null){if(typeof a!="object"||!("__html"in a))throw Error(o(61));if(n=a.__html,n!=null){if(u.children!=null)throw Error(o(60));t.innerHTML=n}}break;case"multiple":t.multiple=a&&typeof a!="function"&&typeof a!="symbol";break;case"muted":t.muted=a&&typeof a!="function"&&typeof a!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(a==null||typeof a=="function"||typeof a=="boolean"||typeof a=="symbol"){t.removeAttribute("xlink:href");break}n=cu(""+a),t.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",n);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":a!=null&&typeof a!="function"&&typeof a!="symbol"?t.setAttribute(n,""+a):t.removeAttribute(n);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":a&&typeof a!="function"&&typeof a!="symbol"?t.setAttribute(n,""):t.removeAttribute(n);break;case"capture":case"download":a===!0?t.setAttribute(n,""):a!==!1&&a!=null&&typeof a!="function"&&typeof a!="symbol"?t.setAttribute(n,a):t.removeAttribute(n);break;case"cols":case"rows":case"size":case"span":a!=null&&typeof a!="function"&&typeof a!="symbol"&&!isNaN(a)&&1<=a?t.setAttribute(n,a):t.removeAttribute(n);break;case"rowSpan":case"start":a==null||typeof a=="function"||typeof a=="symbol"||isNaN(a)?t.removeAttribute(n):t.setAttribute(n,a);break;case"popover":vt("beforetoggle",t),vt("toggle",t),lu(t,"popover",a);break;case"xlinkActuate":yn(t,"http://www.w3.org/1999/xlink","xlink:actuate",a);break;case"xlinkArcrole":yn(t,"http://www.w3.org/1999/xlink","xlink:arcrole",a);break;case"xlinkRole":yn(t,"http://www.w3.org/1999/xlink","xlink:role",a);break;case"xlinkShow":yn(t,"http://www.w3.org/1999/xlink","xlink:show",a);break;case"xlinkTitle":yn(t,"http://www.w3.org/1999/xlink","xlink:title",a);break;case"xlinkType":yn(t,"http://www.w3.org/1999/xlink","xlink:type",a);break;case"xmlBase":yn(t,"http://www.w3.org/XML/1998/namespace","xml:base",a);break;case"xmlLang":yn(t,"http://www.w3.org/XML/1998/namespace","xml:lang",a);break;case"xmlSpace":yn(t,"http://www.w3.org/XML/1998/namespace","xml:space",a);break;case"is":lu(t,"is",a);break;case"innerText":case"textContent":break;default:(!(2<n.length)||n[0]!=="o"&&n[0]!=="O"||n[1]!=="n"&&n[1]!=="N")&&(n=Oy.get(n)||n,lu(t,n,a))}}function No(t,e,n,a,u,r){switch(n){case"style":hf(t,a,r);break;case"dangerouslySetInnerHTML":if(a!=null){if(typeof a!="object"||!("__html"in a))throw Error(o(61));if(n=a.__html,n!=null){if(u.children!=null)throw Error(o(60));t.innerHTML=n}}break;case"children":typeof a=="string"?Xa(t,a):(typeof a=="number"||typeof a=="bigint")&&Xa(t,""+a);break;case"onScroll":a!=null&&vt("scroll",t);break;case"onScrollEnd":a!=null&&vt("scrollend",t);break;case"onClick":a!=null&&(t.onclick=Fu);break;case"suppressContentEditableWarning":case"suppressHydrationWar Line truncated
* react-is.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var Xh;function v1(){if(Xh)return zt;Xh=1;var l=typeof Symbol=="function"&&Symbol.for,i=l?Symbol.for("react.element"):60103,c=l?Symbol.for("react.portal"):60106,o=l?Symbol.for("react.fragment"):60107,s=l?Symbol.for("react.strict_mode"):60108,d=l?Symbol.for("react.profiler"):60114,m=l?Symbol.for("react.provider"):60109,b=l?Symbol.for("react.context"):60110,v=l?Symbol.for("react.async_mode"):60111,p=l?Symbol.for("react.concurrent_mode"):60111,C=l?Symbol.for("react.forward_ref"):60112,_=l?Symbol.for("react.suspense"):60113,w=l?Symbol.for("react.suspense_list"):60120,j=l?Symbol.for("react.memo"):60115,B=l?Symbol.for("react.lazy"):60116,U=l?Symbol.for("react.block"):60121,X=l?Symbol.for("react.fundamental"):60117,Q=l?Symbol.for("react.responder"):60118,F=l?Symbol.for("react.scope"):60119;function V(O){if(typeof O=="object"&&O!==null){var $=O.$$typeof;switch($){case i:switch(O=O.type,O){case v:case p:case o:case d:case s:case _:return O;default:switch(O=O&&O.$$typeof,O){case b:case C:case B:case j:case m:return O;default:return $}}case c:return $}}}function L(O){return V(O)===p}return zt.AsyncMode=v,zt.ConcurrentMode=p,zt.ContextConsumer=b,zt.ContextProvider=m,zt.Element=i,zt.ForwardRef=C,zt.Fragment=o,zt.Lazy=B,zt.Memo=j,zt.Portal=c,zt.Profiler=d,zt.StrictMode=s,zt.Suspense=_,zt.isAsyncMode=function(O){return L(O)||V(O)===v},zt.isConcurrentMode=L,zt.isContextConsumer=function(O){return V(O)===b},zt.isContextProvider=function(O){return V(O)===m},zt.isElement=function(O){return typeof O=="object"&&O!==null&&O.$$typeof===i},zt.isForwardRef=function(O){return V(O)===C},zt.isFragment=function(O){return V(O)===o},zt.isLazy=function(O){return V(O)===B},zt.isMemo=function(O){return V(O)===j},zt.isPortal=function(O){return V(O)===c},zt.isProfiler=function(O){return V(O)===d},zt.isStrictMode=function(O){return V(O)===s},zt.isSuspense=function(O){return V(O)===_},zt.isValidElementType=function(O){return typeof O=="string"||typeof O=="function"||O===o||O===p||O===d||O===s||O===_||O===w||typeof O=="object"&&O!==null&&(O.$$typeof===B||O.$$typeof===j||O.$$typeof===m||O.$$typeof===b||O.$$typeof===C||O.$$typeof===X||O.$$typeof===Q||O.$$typeof===F||O.$$typeof===U)},zt.typeOf=V,zt}var $h;function S1(){return $h||($h=1,ns.exports=v1()),ns.exports}var as,kh;function T1(){if(kh)return as;kh=1;var l=S1(),i={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},c={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},o={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},s={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},d={};d[l.ForwardRef]=o,d[l.Memo]=s;function m(B){return l.isMemo(B)?s:d[B.$$typeof]||i}var b=Object.defineProperty,v=Object.getOwnPropertyNames,p=Object.getOwnPropertySymbols,C=Object.getOwnPropertyDescriptor,_=Object.getPrototypeOf,w=Object.prototype;function j(B,U,X){if(typeof U!="string"){if(w){var Q=_(U);Q&&Q!==w&&j(B,Q,X)}var F=v(U);p&&(F=F.concat(p(U)));for(var V=m(B),L=m(U),O=0;O<F.length;++O){var $=F[O];if(!c[$]&&!(X&&X[$])&&!(L&&L[$])&&!(V&&V[$])){var W=C(U,$);try{b(B,$,W)}catch{}}}}return B}return as=j,as}T1();var A1=!0;function Cm(l,i,c){var o="";return c.split(" ").forEach(function(s){l[s]!==void 0?i.push(l[s]+";"):s&&(o+=s+" ")}),o}var Rs=function(i,c,o){var s=i.key+"-"+c.name;(o===!1||A1===!1)&&i.registered[s]===void 0&&(i.registered[s]=c.styles)},Ms=function(i,c,o){Rs(i,c,o);var s=i.key+"-"+c.name;if(i.inserted[c.name]===void 0){var d=c;do i.insert(c===d?"."+s:"",d,i.sheet,!0),d=d.next;while(d!==void 0)}};function E1(l){for(var i=0,c,o=0,s=l.length;s>=4;++o,s-=4)c=l.charCodeAt(o)&255|(l.charCodeAt(++o)&255)<<8|(l.charCodeAt(++o)&255)<<16|(l.charCodeAt(++o)&255)<<24,c=(c&65535)*1540483477+((c>>>16)*59797<<16),c^=c>>>24,i=(c&65535)*1540483477+((c>>>16)*59797<<16)^(i&65535)*1540483477+((i>>>16)*59797<<16);switch(s){case 3:i^=(l.charCodeAt(o+2)&255)<<16;case 2:i^=(l.charCodeAt(o+1)&255)<<8;case 1:i^=l.charCodeAt(o)&255,i=(i&65535)*1540483477+((i>>>16)*59797<<16)}return i^=i>>>13,i=(i&65535)*1540483477+((i>>>16)*59797<<16),((i^i>>>15)>>>0).toString(36)}var x1={animationIterationCount:1,aspectRatio:1,borderImageOutset:1,borderImageSlice:1,borderImageWidth:1,boxFlex:1,boxFlexGroup:1,boxOrdinalGroup:1,columnCount:1,columns:1,flex:1,flexGrow:1,flexPositive:1,flexShrink:1,flexNegative:1,flexOrder:1,gridRow:1,gridRowEnd:1,gridRowSpan:1,gridRowStart:1,gridColumn:1,gridColumnEnd:1,gridColumnSpan:1,gridColumnStart:1,msGridRow:1,msGridRowSpan:1,msGridColumn:1,msGridColumnSpan:1,fontWeight:1,lineHeight:1,opacity:1,order:1,orphans:1,scale:1,tabSize:1,widows:1,zIndex:1,zoom:1,WebkitLineClamp:1,fillOpacity:1,floodOpacity:1,stopOpacity:1,strokeDasharray:1,strokeDashoffset:1,strokeMiterlimit:1,strokeOpacity:1,strokeWidth:1},_1=/[A-Z]|^ms/g,O1=/_EMO_([^_]+?)_([^]*?)_EMO_/g,zm=function(i){return i.charCodeAt(1)===45},Qh=functioLine truncated
* @mui/styled-engine v6.3.0
*
* @license MIT
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/function Dm(l,i){return hs(l,i)}function k1(l,i){Array.isArray(l.__emotion_styles)&&(l.__emotion_styles=i(l.__emotion_styles))}const Ph=[];function Ih(l){return Ph[0]=l,Wi(Ph)}function dn(l){if(typeof l!="object"||l===null)return!1;const i=Object.getPrototypeOf(l);return(i===null||i===Object.prototype||Object.getPrototypeOf(i)===null)&&!(Symbol.toStringTag in l)&&!(Symbol.iterator in l)}function Bm(l){if(k.isValidElement(l)||!dn(l))return l;const i={};return Object.keys(l).forEach(c=>{i[c]=Bm(l[c])}),i}function Me(l,i,c={clone:!0}){const o=c.clone?{...l}:l;return dn(l)&&dn(i)&&Object.keys(i).forEach(s=>{k.isValidElement(i[s])?o[s]=i[s]:dn(i[s])&&Object.prototype.hasOwnProperty.call(l,s)&&dn(l[s])?o[s]=Me(l[s],i[s],c):c.clone?o[s]=dn(i[s])?Bm(i[s]):i[s]:o[s]=i[s]}),o}const Q1=l=>{const i=Object.keys(l).map(c=>({key:c,val:l[c]}))||[];return i.sort((c,o)=>c.val-o.val),i.reduce((c,o)=>({...c,[o.key]:o.val}),{})};function Z1(l){const{values:i={xs:0,sm:600,md:900,lg:1200,xl:1536},unit:c="px",step:o=5,...s}=l,d=Q1(i),m=Object.keys(d);function b(w){return`@media (min-width:${typeof i[w]=="number"?i[w]:w}${c})`}function v(w){return`@media (max-width:${(typeof i[w]=="number"?i[w]:w)-o/100}${c})`}function p(w,j){const B=m.indexOf(j);return`@media (min-width:${typeof i[w]=="number"?i[w]:w}${c}) and (max-width:${(B!==-1&&typeof i[m[B]]=="number"?i[m[B]]:j)-o/100}${c})`}function C(w){return m.indexOf(w)+1<m.length?p(w,m[m.indexOf(w)+1]):b(w)}function _(w){const j=m.indexOf(w);return j===0?b(m[1]):j===m.length-1?v(m[j]):p(w,m[m.indexOf(w)+1]).replace("@media","@media not all and")}return{keys:m,values:d,up:b,down:v,between:p,only:C,not:_,unit:c,...s}}function K1(l,i){if(!l.containerQueries)return i;const c=Object.keys(i).filter(o=>o.startsWith("@container")).sort((o,s)=>{var m,b;const d=/min-width:\s*([0-9.]+)/;return+(((m=o.match(d))==null?void 0:m[1])||0)-+(((b=s.match(d))==null?void 0:b[1])||0)});return c.length?c.reduce((o,s)=>{const d=i[s];return delete o[s],o[s]=d,o},{...i}):i}function W1(l,i){return i==="@"||i.startsWith("@")&&(l.some(c=>i.startsWith(`@${c}`))||!!i.match(/^@\d/))}function J1(l,i){const c=i.match(/^@([^/]+)?\/?(.+)?$/);if(!c)return null;const[,o,s]=c,d=Number.isNaN(+o)?o||0:+o;return l.containerQueries(s).up(d)}function F1(l){const i=(d,m)=>d.replace("@media",m?`@container ${m}`:"@container");function c(d,m){d.up=(...b)=>i(l.breakpoints.up(...b),m),d.down=(...b)=>i(l.breakpoints.down(...b),m),d.between=(...b)=>i(l.breakpoints.between(...b),m),d.only=(...b)=>i(l.breakpoints.only(...b),m),d.not=(...b)=>{const v=i(l.breakpoints.not(...b),m);return v.includes("not all and")?v.replace("not all and ","").replace("min-width:","width<").replace("max-width:","width>").replace("and","or"):v}}const o={},s=d=>(c(o,d),o);return c(s),{...l,containerQueries:s}}const P1={borderRadius:4};function Yi(l,i){return i?Me(l,i,{clone:!1}):l}const Br={xs:0,sm:600,md:900,lg:1200,xl:1536},tm={keys:["xs","sm","md","lg","xl"],up:l=>`@media (min-width:${Br[l]}px)`},I1={containerQueries:l=>({up:i=>{let c=typeof i=="number"?i:Br[i]||i;return typeof c=="number"&&(c=`${c}px`),l?`@container ${l} (min-width:${c})`:`@container (min-width:${c})`}})};function Nn(l,i,c){const o=l.theme||{};if(Array.isArray(i)){const d=o.breakpoints||tm;return i.reduce((m,b,v)=>(m[d.up(d.keys[v])]=c(i[v]),m),{})}if(typeof i=="object"){const d=o.breakpoints||tm;return Object.keys(i).reduce((m,b)=>{if(W1(d.keys,b)){const v=J1(o.containerQueries?o:I1,b);v&&(m[v]=c(i[b],b))}else if(Object.keys(d.values||Br).includes(b)){const v=d.up(b);m[v]=c(i[b],b)}else{const v=b;m[v]=i[v]}return m},{})}return c(i)}function tb(l={}){var c;return((c=l.keys)==null?void 0:c.reduce((o,s)=>{const d=l.up(s);return o[d]={},o},{}))||{}}function eb(l,i){return l.reduce((c,o)=>{const s=c[o];return(!s||Object.keys(s).length===0)&&delete c[o],c},i)}function jt(l){if(typeof l!="string")throw new Error(Ba(7));return l.charAt(0).toUpperCase()+l.slice(1)}function Nr(l,i,c=!0){if(!i||typeof i!="string")return null;if(l&&l.vars&&c){const o=`vars.${i}`.split(".").reduce((s,d)=>s&&s[d]?s[d]:null,l);if(o!=null)return o}return i.split(".").reduce((o,s)=>o&&o[s]!=null?o[s]:null,l)}function _r(l,i,c,o=c){let s;return typeof l=="function"?s=l(c):Array.isArray(l)?s=l[c]||o:s=Nr(l,c)||o,i&&(s=i(s,o,l)),s}function Kt(l){const{prop:i,cssProperty:c=l.prop,themeKey:o,transform:s}=l,d=m=>{if(m[i]==null)return null;const b=m[i],v=m.theme,p=Nr(v,o)||{};return Nn(m,b,_=>{let w=_r(p,s,_);return _===w&&typeof _=="string"&&(w=_r(p,s,`${i}${_==="default"?"":jt(_)}`,_)),c===!1?w:{[c]:w}})};return d.propTypes={},d.filterProps=[i],d}function nb(l){const i={};return c=>(i[c]===void 0&&(i[c]=l(c)),i[c])}const ab={m:"margin",p:"padding"},lb={t:"Top",r:"Right",b:"Bottom",l:"Left",x:["Left","Right"],y:["Top","Bottom"]},em={marginX:"mx",marginY:"my",paddingX:"px",paddingY:"py"},ib=nb(l=>{if(l.length>2)if(em[l])l=em[l];else return[l];const[i,c]=l.split(""),o=ab[i],s=lb[c]||"";return Array.isArray(s)?s.map(d=>o+d):[o+s]Line truncated
const theme = ${JSON.stringify(i,null,2)};
theme.breakpoints = createBreakpoints(theme.breakpoints || {});
theme.transitions = createTransitions(theme.transitions || {});
export default theme;`}function ys(l={},...i){const{breakpoints:c,mixins:o={},spacing:s,palette:d={},transitions:m={},typography:b={},shape:v,...p}=l;if(l.vars)throw new Error(Ba(20));const C=Ys(d),_=qs(l);let w=Me(_,{mixins:Bv(_.breakpoints,o),palette:C,shadows:Lv.slice(),typography:Uv(C,b),transitions:Xv(m),zIndex:{...$v}});return w=Me(w,p),w=i.reduce((j,B)=>Me(j,B),w),w.unstable_sxConfig={...Pi,...p==null?void 0:p.unstable_sxConfig},w.unstable_sx=function(B){return Na({sx:B,theme:this})},w.toRuntimeSource=Qm,w}function Qv(l){let i;return l<1?i=5.11916*l**2:i=4.5*Math.log(l+1)+2,Math.round(i*10)/1e3}const Zv=[...Array(25)].map((l,i)=>{if(i===0)return"none";const c=Qv(i);return`linear-gradient(rgba(255 255 255 / ${c}), rgba(255 255 255 / ${c}))`});function Zm(l){return{inputPlaceholder:l==="dark"?.5:.42,inputUnderline:l==="dark"?.7:.42,switchTrackDisabled:l==="dark"?.2:.12,switchTrack:l==="dark"?.3:.38}}function Km(l){return l==="dark"?Zv:[]}function Kv(l){const{palette:i={mode:"light"},opacity:c,overlays:o,...s}=l,d=Ys(i);return{palette:d,opacity:{...Zm(d.mode),...c},overlays:o||Km(d.mode),...s}}function Wv(l){var i;return!!l[0].match(/(cssVarPrefix|colorSchemeSelector|rootSelector|typography|mixins|breakpoints|direction|transitions)/)||!!l[0].match(/sxConfig$/)||l[0]==="palette"&&!!((i=l[1])!=null&&i.match(/(mode|contrastThreshold|tonalOffset)/))}const Jv=l=>[...[...Array(25)].map((i,c)=>`--${l?`${l}-`:""}overlays-${c}`),`--${l?`${l}-`:""}palette-AppBar-darkBg`,`--${l?`${l}-`:""}palette-AppBar-darkColor`],Fv=l=>(i,c)=>{const o=l.rootSelector||":root",s=l.colorSchemeSelector;let d=s;if(s==="class"&&(d=".%s"),s==="data"&&(d="[data-%s]"),s!=null&&s.startsWith("data-")&&!s.includes("%s")&&(d=`[${s}="%s"]`),l.defaultColorScheme===i){if(i==="dark"){const m={};return Jv(l.cssVarPrefix).forEach(b=>{m[b]=c[b],delete c[b]}),d==="media"?{[o]:c,"@media (prefers-color-scheme: dark)":{[o]:m}}:d?{[d.replace("%s",i)]:m,[`${o}, ${d.replace("%s",i)}`]:c}:{[o]:{...c,...m}}}if(d&&d!=="media")return`${o}, ${d.replace("%s",String(i))}`}else if(i){if(d==="media")return{[`@media (prefers-color-scheme: ${String(i)})`]:{[o]:c}};if(d)return d.replace("%s",String(i))}return o};function Pv(l,i){i.forEach(c=>{l[c]||(l[c]={})})}function R(l,i,c){!l[i]&&c&&(l[i]=c)}function Gi(l){return typeof l!="string"||!l.startsWith("hsl")?l:Vm(l)}function Mn(l,i){`${i}Channel`in l||(l[`${i}Channel`]=Li(Gi(l[i])))}function Iv(l){return typeof l=="number"?`${l}px`:typeof l=="string"||typeof l=="function"||Array.isArray(l)?l:"8px"}const on=l=>{try{return l()}catch{}},tS=(l="mui")=>Sv(l);function rs(l,i,c,o){if(!i)return;i=i===!0?{}:i;const s=o==="dark"?"dark":"light";if(!c){l[o]=Kv({...i,palette:{mode:s,...i==null?void 0:i.palette}});return}const{palette:d,...m}=ys({...c,palette:{mode:s,...i==null?void 0:i.palette}});return l[o]={...i,palette:d,opacity:{...Zm(s),...i==null?void 0:i.opacity},overlays:(i==null?void 0:i.overlays)||Km(s)},m}function eS(l={},...i){const{colorSchemes:c={light:!0},defaultColorScheme:o,disableCssColorScheme:s=!1,cssVarPrefix:d="mui",shouldSkipGeneratingVar:m=Wv,colorSchemeSelector:b=c.light&&c.dark?"media":void 0,rootSelector:v=":root",...p}=l,C=Object.keys(c)[0],_=o||(c.light&&C!=="light"?"light":C),w=tS(d),{[_]:j,light:B,dark:U,...X}=c,Q={...X};let F=j;if((_==="dark"&&!("dark"in c)||_==="light"&&!("light"in c))&&(F=!0),!F)throw new Error(Ba(21,_));const V=rs(Q,F,p,_);B&&!Q.light&&rs(Q,B,void 0,"light"),U&&!Q.dark&&rs(Q,U,void 0,"dark");let L={defaultColorScheme:_,...V,cssVarPrefix:d,colorSchemeSelector:b,rootSelector:v,getCssVar:w,colorSchemes:Q,font:{...Dv(V.typography),...V.font},spacing:Iv(p.spacing)};Object.keys(L.colorSchemes).forEach(K=>{const y=L.colorSchemes[K].palette,Y=et=>{const ct=et.split("-"),St=ct[1],_t=ct[2];return w(et,y[St][_t])};if(y.mode==="light"&&(R(y.common,"background","#fff"),R(y.common,"onBackground","#000")),y.mode==="dark"&&(R(y.common,"background","#000"),R(y.common,"onBackground","#fff")),Pv(y,["Alert","AppBar","Avatar","Button","Chip","FilledInput","LinearProgress","Skeleton","Slider","SnackbarContent","SpeedDialAction","StepConnector","StepContent","Switch","TableCell","Tooltip"]),y.mode==="light"){R(y.Alert,"errorColor",Dt(y.error.light,.6)),R(y.Alert,"infoColor",Dt(y.info.light,.6)),R(y.Alert,"successColor",Dt(y.success.light,.6)),R(y.Alert,"warningColor",Dt(y.warning.light,.6)),R(y.Alert,"errorFilledBg",Y("palette-error-main")),R(y.Alert,"infoFilledBg",Y("palette-info-main")),R(y.Alert,"successFilledBg",Y("palette-success-main")),R(y.Alert,"warningFilledBg",Y("palette-warning-main")),R(y.Alert,"errorFilledColor",on(()=>y.getContrastText(y.error.main))),R(y.Alert,"infoFilledColor",on(()=>y.getContrastText(y.info.main))),R(y.Alert,"successFilledColor",on(()=>y.getContrastText(y.success.main))),R(y.Alert,"warningFilledColor",on(()=>y.getContrastText(y.warning.main))),R(y.Alert,"errorStandardBg",Bt(y.error.light,.9)),R(y.Alert,"infoStandardBg",Bt(y.info.light,.9)),R(y.Alert,"successStandardB Line truncated
0% {
transform: scale(0);
opacity: 0.1;
}
100% {
transform: scale(1);
opacity: 0.3;
}
`,bS=Dl`
0% {
opacity: 1;
}
100% {
opacity: 0;
}
`,vS=Dl`
0% {
transform: scale(1);
}
50% {
transform: scale(0.92);
}
100% {
transform: scale(1);
}
`,SS=Ie("span",{name:"MuiTouchRipple",slot:"Root"})({overflow:"hidden",pointerEvents:"none",position:"absolute",zIndex:0,top:0,right:0,bottom:0,left:0,borderRadius:"inherit"}),TS=Ie(yS,{name:"MuiTouchRipple",slot:"Ripple"})`
opacity: 0;
position: absolute;
&.${ke.rippleVisible} {
opacity: 0.3;
transform: scale(1);
animation-name: ${gS};
animation-duration: ${gs}ms;
animation-timing-function: ${({theme:l})=>l.transitions.easing.easeInOut};
}
&.${ke.ripplePulsate} {
animation-duration: ${({theme:l})=>l.transitions.duration.shorter}ms;
}
& .${ke.child} {
opacity: 1;
display: block;
width: 100%;
height: 100%;
border-radius: 50%;
background-color: currentColor;
}
& .${ke.childLeaving} {
opacity: 0;
animation-name: ${bS};
animation-duration: ${gs}ms;
animation-timing-function: ${({theme:l})=>l.transitions.easing.easeInOut};
}
& .${ke.childPulsate} {
position: absolute;
/* @noflip */
left: 0px;
top: 0;
animation-name: ${vS};
animation-duration: 2500ms;
animation-timing-function: ${({theme:l})=>l.transitions.easing.easeInOut};
animation-iteration-count: infinite;
animation-delay: 200ms;
}
`,AS=k.forwardRef(function(i,c){const o=Ul({props:i,name:"MuiTouchRipple"}),{center:s=!1,classes:d={},className:m,...b}=o,[v,p]=k.useState([]),C=k.useRef(0),_=k.useRef(null);k.useEffect(()=>{_.current&&(_.current(),_.current=null)},[v]);const w=k.useRef(!1),j=hv(),B=k.useRef(null),U=k.useRef(null),X=k.useCallback(L=>{const{pulsate:O,rippleX:$,rippleY:W,rippleSize:gt,cb:K}=L;p(y=>[...y,rt.jsx(TS,{classes:{ripple:pe(d.ripple,ke.ripple),rippleVisible:pe(d.rippleVisible,ke.rippleVisible),ripplePulsate:pe(d.ripplePulsate,ke.ripplePulsate),child:pe(d.child,ke.child),childLeaving:pe(d.childLeaving,ke.childLeaving),childPulsate:pe(d.childPulsate,ke.childPulsate)},timeout:gs,pulsate:O,rippleX:$,rippleY:W,rippleSize:gt},C.current)]),C.current+=1,_.current=K},[d]),Q=k.useCallback((L={},O={},$=()=>{})=>{const{pulsate:W=!1,center:gt=s||O.pulsate,fakeElement:K=!1}=O;if((L==null?void 0:L.type)==="mousedown"&&w.current){w.current=!1;return}(L==null?void 0:L.type)==="touchstart"&&(w.current=!0);const y=K?null:U.current,Y=y?y.getBoundingClientRect():{width:0,height:0,left:0,top:0};let et,ct,St;if(gt||L===void 0||L.clientX===0&&L.clientY===0||!L.clientX&&!L.touches)et=Math.round(Y.width/2),ct=Math.round(Y.height/2);else{const{clientX:_t,clientY:G}=L.touches&&L.touches.length>0?L.touches[0]:L;et=Math.round(_t-Y.left),ct=Math.round(G-Y.top)}if(gt)St=Math.sqrt((2*Y.width**2+Y.height**2)/3),St%2===0&&(St+=1);else{const _t=Math.max(Math.abs((y?y.clientWidth:0)-et),et)*2+2,G=Math.max(Math.abs((y?y.clientHeight:0)-ct),ct)*2+2;St=Math.sqrt(_t**2+G**2)}L!=null&&L.touches?B.current===null&&(B.current=()=>{X({pulsate:W,rippleX:et,rippleY:ct,rippleSize:St,cb:$})},j.start(pS,()=>{B.current&&(B.current(),B.current=null)})):X({pulsate:W,rippleX:et,rippleY:ct,rippleSize:St,cb:$})},[s,X,j]),F=k.useCallback(()=>{Q({},{pulsate:!0})},[Q]),V=k.useCallback((L,O)=>{if(j.clear(),(L==null?void 0:L.type)==="touchend"&&B.current){B.current(),B.current=null,j.start(0,()=>{V(L,O)});return}B.current=null,p($=>$.length>0?$.slice(1):$),_.current=O},[j]);return k.useImperativeHandle(c,()=>({pulsate:F,start:Q,stop:V}),[F,Q,V]),rt.jsx(SS,{className:pe(ke.root,d.root,m),ref:U,...b,children:rt.jsx(Xs,{component:null,exit:!0,children:v})})});function ES(l){return Ii("MuiButtonBase",l)}const xS=Bl("MuiButtonBase",["root","disabled","focusVisible"]),_S=l=>{const{disabled:i,focusVisible:c,focusVisibleClassName:o,classes:s}=l,m=Xr({root:["root",i&&"disabled",c&&"focusVisible"]},ES,s);return c&&o&&(m.root+=` ${o}`),m},OS=Ie("button",{name:"MuiButtonBase",slot:"Root",overridesResolver:(l,i)=>i.root})({display:"inline-flex",alignItems:"center",justifyContent:"center",position:"relative",boxSizing:"border-box",WebkitTapHighlightColor:"transparent",backgroundColor:"transparent",outline:0,border:0,margin:0,borderRadius:0,padding:0,cursor:"pointer",userSelect:"none",verticalAlign:"middle",MozAppearance:"none",WebkitAppearance:"none",textDecoration:"none",color:"inherit","&::-moz-focus-inner":{borderStyle:"none"},[`&.${xS.disabled}`]:{pointerEvents:"none",cursor:"default"},"@media print":{colorAdjust:"exact"}}),CS=k.forwardRef(function(i,c){const o=Ul({props:i,name:"MuiButtonBase"}),{action:s,centerRipple:d=!1,children:m,className:b,component:v="button",disabled:p=!1,disableRipple:C=!1,disableTouchRipple:_=!1,focusRipple:w=!1,focusVisibleClassName:j,LinkComponent:B="a",onBlur:U,onClick:X,onContextMenu:Q,onDragLeave:F,onFocus:V,onFocusVisible:L,onKeyDown:O,onKeyUp:$,onMouseDown:W,onMouseLeave:gt,onMouseUp:K,onTouchEnd:y,onTouchMove:Y,onTouchStart:et,tabIndex:ct=0,TouchRippleProps:St,touchRippleRef:_t,type:G,...it}=o,tt=k.useRef(null),ot=hS(),S=am(ot.ref,_t),[q,at]=k.useState(!1);p&&q&&at(!1),k.useImperativeHandle(s,()=>({focusVisible:()=>{at(!0),tt.current.focus()}}),[]);const lt=ot.shouldMount&&!C&&!p;k.useEffect(()=>{q&&w&&!C&&ot.pulsate()},[C,w,q,ot]);const J=Dn(ot,"start",W,_),bt=Dn(ot,"stop",Q,_),ft=Dn(ot,"stop",F,_),ie=Dn(ot,"stop",K,_),At=Dn(ot,"stop",dt=>{q&&dt.preventDefault(),gt&&gt(dt)},_),Yt=Dn(ot,"start",et,_),Nt=Dn(ot,"stop",y,_),De=Dn(ot,"stop",Y,_),oa=Dn(ot,"stop",dt=>{im(dt.target)||at(!1),U&&U(dt)},!1),tn=vr(dt=>{tt.current||(tt.current=dt.currentTarget),im(dt.target)&&(at(!0),L&&L(dt)),V&&V(dt)}),Un=()=>{const dt=tt.current;return v&&v!=="button"&&!(dt.tagName==="A"&&dt.href)},Ha=vr(dt=>{w&&!dt.repeat&&q&&dt.key===" "&&ot.stop(dt,()=>{ot.start(dt)}),dt.target===dt.currentTarget&&Un()&&dt.key===" "&&dt.preventDefault(),O&&O(dt),dt.target===dt.currentTarget&&Un()&&dt.key==="Enter"&&!p&&(dt.preventDefault(),X&&X(dt))}),Hn=vr(dt=>{w&&dt.key===" "&&q&&!dt.defaultPrevented&&ot.stop(dt,()=>{ot.pulsate(dt)}),$&&$(dt),X&&dt.target===dt.currentTarget&&Un()&&dt.key===" "&&!dt.defaultPrevented&&X(dt)});let jn=v;jn==="button"&&(it.href||it.to)&&(jn=B);const en={};jn==="button"?(en.type=G===void 0?"button":G,en.disabled=p):(!it.href&&!it.to&&(en.role="button"),p&&(en["aria-disabled"]=p));const Hl=am(c,tt),ja={...o,centerRipple:d,component:v,disabled:p,disableRipple:C,di Line truncated
0% {
left: -35%;
right: 100%;
}
60% {
left: 100%;
right: -90%;
}
100% {
left: 100%;
right: -90%;
}
`,FS=typeof Ss!="string"?Dr`
animation: ${Ss} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite;
`:null,Ts=Dl`
0% {
left: -200%;
right: 100%;
}
60% {
left: 107%;
right: -8%;
}
100% {
left: 107%;
right: -8%;
}
`,PS=typeof Ts!="string"?Dr`
animation: ${Ts} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite;
`:null,As=Dl`
0% {
opacity: 1;
background-position: 0 -23px;
}
60% {
opacity: 0;
background-position: 0 -23px;
}
100% {
opacity: 1;
background-position: -200px -23px;
}
`,IS=typeof As!="string"?Dr`
animation: ${As} 3s infinite linear;
`:null,t2=l=>{const{classes:i,variant:c,color:o}=l,s={root:["root",`color${jt(o)}`,c],dashed:["dashed",`dashedColor${jt(o)}`],bar1:["bar",`barColor${jt(o)}`,(c==="indeterminate"||c==="query")&&"bar1Indeterminate",c==="determinate"&&"bar1Determinate",c==="buffer"&&"bar1Buffer"],bar2:["bar",c!=="buffer"&&`barColor${jt(o)}`,c==="buffer"&&`color${jt(o)}`,(c==="indeterminate"||c==="query")&&"bar2Indeterminate",c==="buffer"&&"bar2Buffer"]};return Xr(s,JS,i)},ks=(l,i)=>l.vars?l.vars.palette.LinearProgress[`${i}Bg`]:l.palette.mode==="light"?Vr(l.palette[i].main,.62):Yr(l.palette[i].main,.5),e2=Ie("span",{name:"MuiLinearProgress",slot:"Root",overridesResolver:(l,i)=>{const{ownerState:c}=l;return[i.root,i[`color${jt(c.color)}`],i[c.variant]]}})(Nl(({theme:l})=>({position:"relative",overflow:"hidden",display:"block",height:4,zIndex:0,"@media print":{colorAdjust:"exact"},variants:[...Object.entries(l.palette).filter(Ua()).map(([i])=>({props:{color:i},style:{backgroundColor:ks(l,i)}})),{props:({ownerState:i})=>i.color==="inherit"&&i.variant!=="buffer",style:{"&::before":{content:'""',position:"absolute",left:0,top:0,right:0,bottom:0,backgroundColor:"currentColor",opacity:.3}}},{props:{variant:"buffer"},style:{backgroundColor:"transparent"}},{props:{variant:"query"},style:{transform:"rotate(180deg)"}}]}))),n2=Ie("span",{name:"MuiLinearProgress",slot:"Dashed",overridesResolver:(l,i)=>{const{ownerState:c}=l;return[i.dashed,i[`dashedColor${jt(c.color)}`]]}})(Nl(({theme:l})=>({position:"absolute",marginTop:0,height:"100%",width:"100%",backgroundSize:"10px 10px",backgroundPosition:"0 -23px",variants:[{props:{color:"inherit"},style:{opacity:.3,backgroundImage:"radial-gradient(currentColor 0%, currentColor 16%, transparent 42%)"}},...Object.entries(l.palette).filter(Ua()).map(([i])=>{const c=ks(l,i);return{props:{color:i},style:{backgroundImage:`radial-gradient(${c} 0%, ${c} 16%, transparent 42%)`}}})]})),IS||{animation:`${As} 3s infinite linear`}),a2=Ie("span",{name:"MuiLinearProgress",slot:"Bar1",overridesResolver:(l,i)=>{const{ownerState:c}=l;return[i.bar,i[`barColor${jt(c.color)}`],(c.variant==="indeterminate"||c.variant==="query")&&i.bar1Indeterminate,c.variant==="determinate"&&i.bar1Determinate,c.variant==="buffer"&&i.bar1Buffer]}})(Nl(({theme:l})=>({width:"100%",position:"absolute",left:0,bottom:0,top:0,transition:"transform 0.2s linear",transformOrigin:"left",variants:[{props:{color:"inherit"},style:{backgroundColor:"currentColor"}},...Object.entries(l.palette).filter(Ua()).map(([i])=>({props:{color:i},style:{backgroundColor:(l.vars||l).palette[i].main}})),{props:{variant:"determinate"},style:{transition:`transform .${vs}s linear`}},{props:{variant:"buffer"},style:{zIndex:1,transition:`transform .${vs}s linear`}},{props:({ownerState:i})=>i.variant==="indeterminate"||i.variant==="query",style:{width:"auto"}},{props:({ownerState:i})=>i.variant==="indeterminate"||i.variant==="query",style:FS||{animation:`${Ss} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite`}}]}))),l2=Ie("span",{name:"MuiLinearProgress",slot:"Bar2",overridesResolver:(l,i)=>{const{ownerState:c}=l;return[i.bar,i[`barColor${jt(c.color)}`],(c.variant==="indeterminate"||c.variant==="query")&&i.bar2Indeterminate,c.variant==="buffer"&&i.bar2Buffer]}})(Nl(({theme:l})=>({width:"100%",position:"absolute",left:0,bottom:0,top:0,transition:"transform 0.2s linear",transformOrigin:"left",variants:[...Object.entries(l.palette).filter(Ua()).map(([i])=>({props:{color:i},style:{"--LinearProgressBar2-barColor":(l.vars||l).palette[i].main}})),{props:({ownerState:i})=>i.variant!=="buffer"&&i.color!=="inherit",style:{backgroundColor:"var(--LinearProgressBar2-barColor, currentColor)"}},{props:({ownerState:i})=>i.variant!=="buffer"&&i.color==="inherit",style:{backgroundColor:"currentColor"}},{props:{color:"inherit"},style:{opacity:.3}},...Object.entries(l.palette).filter(Ua()).map(([i])=>({props:{color:i,variant:"buffer"},style:{backgroundColor:ks(l,i),transition:`transform .${vs}s linear`}})),{props:({ownerState:i})=>i.variant==="indeterminate"||i.variant==="query",style:{width:"auto"}},{props:({ownerState:i})=>i.variant==="indeterminate"||i.variant==="query",style:PS||{animation:`${Ts} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite`}}]}))),i2=k.forwardRef(function(i,c){const o=Ul({props:i,name:"MuiLinearProgress"}),{className:s,color:d="primary",value:m,valueBuffer:b,variant:v="indeterminate",...p}=o,C={...o,color:d,variant:v},_=t2(C),w=yv(),j={},B={bar1:{},bar2:{}};if((v==="determinate"||v==="buffer")&&m!==void 0){j["aria-valuenow"]=Math.round(m),j["aria-valuemin"]=0,j["aria-valuemax"]=100;let U=m-100;w&&(U=-U),B.bar1.transform=`translateX(${U}%)`}if(v==="buffer"&&b!==void 0){let U=(b||0)-100;w&&(U=-U),B.bar2.transform=`translateX(${U}%)`}return rt.jsxs(e2,{className:pe(_.root,s),ownerState:C,role:"progressbar",...j,ref:c,...p,children:[v==="buffer"?rt.jsx(n2,{className:_.dashed,ownerState:C}):null,rt.jsx(a2,{className:_.bar1,ownerState:C,style:B.bar1}),v== Line truncated
-168
View File
@@ -1,168 +0,0 @@
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var l=o((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0<n;){var r=n-1>>>1,a=e[r];if(0<i(a,t))e[r]=t,e[n]=a,n=r;else break a}}function n(e){return e.length===0?null:e[0]}function r(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;a:for(var r=0,a=e.length,o=a>>>1;r<o;){var s=2*(r+1)-1,c=e[s],l=s+1,u=e[l];if(0>i(c,n))l<a&&0>i(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(l<a&&0>i(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m)if(n(c)!==null)m=!0,S||(S=!0,re());else{var t=n(l);t!==null&&oe(x,t.startTime-e)}}var S=!1,C=-1,w=5,ee=-1;function te(){return g?!0:!(e.unstable_now()-ee<w)}function ne(){if(g=!1,S){var t=e.unstable_now();ee=t;var i=!0;try{a:{m=!1,h&&(h=!1,v(C),C=-1),p=!0;var a=f;try{b:{for(b(t),d=n(c);d!==null&&!(d.expirationTime>t&&te());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&oe(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?re():S=!1}}}var re;if(typeof y==`function`)re=function(){y(ne)};else if(typeof MessageChannel<`u`){var ie=new MessageChannel,ae=ie.port2;ie.port1.onmessage=ne,re=function(){ae.postMessage(null)}}else re=function(){_(ne,0)};function oe(t,n){C=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125<e?console.error(`forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported`):w=0<e?Math.floor(1e3/e):5},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(e){switch(f){case 1:case 2:case 3:var t=3;break;default:t=f}var n=f;f=t;try{return e()}finally{f=n}},e.unstable_requestPaint=function(){g=!0},e.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=f;f=e;try{return t()}finally{f=n}},e.unstable_scheduleCallback=function(r,i,a){var o=e.unstable_now();switch(typeof a==`object`&&a?(a=a.delay,a=typeof a==`number`&&0<a?o+a:o):a=o,r){case 1:var s=-1;break;case 2:s=250;break;case 5:s=1073741823;break;case 4:s=1e4;break;default:s=5e3}return s=a+s,r={id:u++,callback:i,priorityLevel:r,startTime:a,expirationTime:s,sortIndex:-1},a>o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,oe(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,re()))),r},e.unstable_shouldYield=te,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),u=o(((e,t)=>{t.exports=l()})),d=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`)Line truncated
at`)?` (<anonymous>)`:-1<e.stack.indexOf(`@`)?`@unknown:0:0`:``}return`
`+be+e+xe}var Ce=!1;function we(e,t){if(!e||Ce)return``;Ce=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var r={DetermineComponentFrameRoot:function(){try{if(t){var n=function(){throw Error()};if(Object.defineProperty(n.prototype,`props`,{set:function(){throw Error()}}),typeof Reflect==`object`&&Reflect.construct){try{Reflect.construct(n,[])}catch(e){var r=e}Reflect.construct(e,[],n)}else{try{n.call()}catch(e){r=e}e.call(n.prototype)}}else{try{throw Error()}catch(e){r=e}(n=e())&&typeof n.catch==`function`&&n.catch(function(){})}}catch(e){if(e&&r&&typeof e.stack==`string`)return[e.stack,r.stack]}return[null,null]}};r.DetermineComponentFrameRoot.displayName=`DetermineComponentFrameRoot`;var i=Object.getOwnPropertyDescriptor(r.DetermineComponentFrameRoot,`name`);i&&i.configurable&&Object.defineProperty(r.DetermineComponentFrameRoot,`name`,{value:`DetermineComponentFrameRoot`});var a=r.DetermineComponentFrameRoot(),o=a[0],s=a[1];if(o&&s){var c=o.split(`
`),l=s.split(`
`);for(i=r=0;r<c.length&&!c[r].includes(`DetermineComponentFrameRoot`);)r++;for(;i<l.length&&!l[i].includes(`DetermineComponentFrameRoot`);)i++;if(r===c.length||i===l.length)for(r=c.length-1,i=l.length-1;1<=r&&0<=i&&c[r]!==l[i];)i--;for(;1<=r&&0<=i;r--,i--)if(c[r]!==l[i]){if(r!==1||i!==1)do if(r--,i--,0>i||c[r]!==l[i]){var u=`
`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(`<anonymous>`)&&(u=u.replace(`<anonymous>`,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{Ce=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?Se(n):``}function Te(e,t){switch(e.tag){case 26:case 27:case 5:return Se(e.type);case 16:return Se(`Lazy`);case 13:return e.child!==t&&t!==null?Se(`Suspense Fallback`):Se(`Suspense`);case 19:return Se(`SuspenseList`);case 0:case 15:return we(e.type,!1);case 11:return we(e.type.render,!1);case 1:return we(e.type,!0);case 31:return Se(`Activity`);default:return``}}function Ee(e){try{var t=``,n=null;do t+=Te(e,n),n=e,e=e.return;while(e);return t}catch(e){return`
Error generating stack: `+e.message+`
`+e.stack}}var De=Object.prototype.hasOwnProperty,Oe=t.unstable_scheduleCallback,ke=t.unstable_cancelCallback,Ae=t.unstable_shouldYield,je=t.unstable_requestPaint,Me=t.unstable_now,Ne=t.unstable_getCurrentPriorityLevel,Pe=t.unstable_ImmediatePriority,Fe=t.unstable_UserBlockingPriority,Ie=t.unstable_NormalPriority,Le=t.unstable_LowPriority,Re=t.unstable_IdlePriority,ze=t.log,Be=t.unstable_setDisableYieldValue,Ve=null,He=null;function Ue(e){if(typeof ze==`function`&&Be(e),He&&typeof He.setStrictMode==`function`)try{He.setStrictMode(Ve,e)}catch{}}var We=Math.clz32?Math.clz32:qe,Ge=Math.log,Ke=Math.LN2;function qe(e){return e>>>=0,e===0?32:31-(Ge(e)/Ke|0)|0}var Je=256,Ye=262144,Xe=4194304;function Ze(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Qe(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=Ze(n))):i=Ze(o):i=Ze(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=Ze(n))):i=Ze(o)):i=Ze(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function $e(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function et(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function tt(){var e=Xe;return Xe<<=1,!(Xe&62914560)&&(Xe=4194304),e}function nt(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function rt(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function it(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0<n;){var u=31-We(n),d=1<<u;s[u]=0,c[u]=-1;var f=l[u];if(f!==null)for(l[u]=null,u=0;u<f.length;u++){var p=f[u];p!==null&&(p.lane&=-536870913)}n&=~d}r!==0&&at(e,r,0),a!==0&&i===0&&e.tag!==0&&(e.suspendedLanes|=a&~(o&~t))}function at(e,t,n){e.pendingLanes|=t,e.suspendedLanes&=~t;var r=31-We(t);e.entangledLanes|=t,e.entanglements[r]=e.entanglements[r]|1073741824|n&261930}function ot(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-We(n),i=1<<r;i&t|e[r]&t&&(e[r]|=t),n&=~i}}function st(e,t){var n=t&-t;return n=n&42?1:ct(n),(n&(e.suspendedLanes|t))===0?n:0}function ct(e){switch(e){case 2:e=1;break;case 8:e=4;break;case 32:e=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:e=128;break;case 268435456:e=134217728;break;default:e=0}return e}function lt(e){return e&=-e,2<e?8<e?e&134217727?32:268435456:8:2}function ut(){var e=O.p;return e===0?(e=window.event,e===void 0?32:mp(e.type)):e}function dt(e,t){var n=O.p;try{return O.p=e,t()}finally{O.p=n}}var ft=Math.random().toString(36).slice(2),pt=`__reactFiber$`+ft,mt=`__reactProps$`+ft,ht=`__reactContainer$`+ft,gt=`__reactEvents$`+ft,_t=`__reactListeners$`+ft,vt=`__reactHandles$`+ft,yt=`__reactResources$`+ft,bt=`__reactMarker$`+ft;function xt(e){delete e[pt],delete e[mt],delete e[gt],delete e[_t],delete e[vt]}function St(e){var t=e[pt];if(t)return t;for(var n=e.parentNode;n;){if(t=n[ht]||n[pt]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=df(e);e!==null;){if(n=e[pt])return n;e=df(e)}return t}e=n,n=e.parentNode}return null}function Ct(e){if(e=e[pt]||e[ht]){var t=e.tag;if(t===5||t===6||t===13||t===31||t===26||t===27||t===3)return e}return null}function wt(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e.stateNode;throw Error(i(33))}function Tt(e){var t=e[yt];return t||=e[yt]={hoistableStyles:new Map,hoistableScripts:new Map},t}function Et(e){e[bt]=!0}var Dt=new Set,Ot={};function kt(e,t){At(e,t),At(e+`Capture`,t)}function At(e,t){for(Ot[e]=t,e=0;e<t.length;e++)Dt.add(t[e])}var jt=RegExp(`^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001Line truncated
`).replace(Ad,``)}function Md(e,t){return t=jd(t),jd(e)===t}function $(e,t,n,r,a,o){switch(n){case`children`:typeof r==`string`?t===`body`||t===`textarea`&&r===``||Zt(e,r):(typeof r==`number`||typeof r==`bigint`)&&t!==`body`&&Zt(e,``+r);break;case`className`:Ft(e,`class`,r);break;case`tabIndex`:Ft(e,`tabindex`,r);break;case`dir`:case`role`:case`viewBox`:case`width`:case`height`:Ft(e,n,r);break;case`style`:en(e,r,o);break;case`data`:if(t!==`object`){Ft(e,`data`,r);break}case`src`:case`href`:if(r===``&&(t!==`a`||n!==`href`)){e.removeAttribute(n);break}if(r==null||typeof r==`function`||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=an(``+r),e.setAttribute(n,r);break;case`action`:case`formAction`:if(typeof r==`function`){e.setAttribute(n,`javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')`);break}else typeof o==`function`&&(n===`formAction`?(t!==`input`&&$(e,t,`name`,a.name,a,null),$(e,t,`formEncType`,a.formEncType,a,null),$(e,t,`formMethod`,a.formMethod,a,null),$(e,t,`formTarget`,a.formTarget,a,null)):($(e,t,`encType`,a.encType,a,null),$(e,t,`method`,a.method,a,null),$(e,t,`target`,a.target,a,null)));if(r==null||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=an(``+r),e.setAttribute(n,r);break;case`onClick`:r!=null&&(e.onclick=on);break;case`onScroll`:r!=null&&Q(`scroll`,e);break;case`onScrollEnd`:r!=null&&Q(`scrollend`,e);break;case`dangerouslySetInnerHTML`:if(r!=null){if(typeof r!=`object`||!(`__html`in r))throw Error(i(61));if(n=r.__html,n!=null){if(a.children!=null)throw Error(i(60));e.innerHTML=n}}break;case`multiple`:e.multiple=r&&typeof r!=`function`&&typeof r!=`symbol`;break;case`muted`:e.muted=r&&typeof r!=`function`&&typeof r!=`symbol`;break;case`suppressContentEditableWarning`:case`suppressHydrationWarning`:case`defaultValue`:case`defaultChecked`:case`innerHTML`:case`ref`:break;case`autoFocus`:break;case`xlinkHref`:if(r==null||typeof r==`function`||typeof r==`boolean`||typeof r==`symbol`){e.removeAttribute(`xlink:href`);break}n=an(``+r),e.setAttributeNS(`http://www.w3.org/1999/xlink`,`xlink:href`,n);break;case`contentEditable`:case`spellCheck`:case`draggable`:case`value`:case`autoReverse`:case`externalResourcesRequired`:case`focusable`:case`preserveAlpha`:r!=null&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,``+r):e.removeAttribute(n);break;case`inert`:case`allowFullScreen`:case`async`:case`autoPlay`:case`controls`:case`default`:case`defer`:case`disabled`:case`disablePictureInPicture`:case`disableRemotePlayback`:case`formNoValidate`:case`hidden`:case`loop`:case`noModule`:case`noValidate`:case`open`:case`playsInline`:case`readOnly`:case`required`:case`reversed`:case`scoped`:case`seamless`:case`itemScope`:r&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,``):e.removeAttribute(n);break;case`capture`:case`download`:!0===r?e.setAttribute(n,``):!1!==r&&r!=null&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,r):e.removeAttribute(n);break;case`cols`:case`rows`:case`size`:case`span`:r!=null&&typeof r!=`function`&&typeof r!=`symbol`&&!isNaN(r)&&1<=r?e.setAttribute(n,r):e.removeAttribute(n);break;case`rowSpan`:case`start`:r==null||typeof r==`function`||typeof r==`symbol`||isNaN(r)?e.removeAttribute(n):e.setAttribute(n,r);break;case`popover`:Q(`beforetoggle`,e),Q(`toggle`,e),Pt(e,`popover`,r);break;case`xlinkActuate`:It(e,`http://www.w3.org/1999/xlink`,`xlink:actuate`,r);break;case`xlinkArcrole`:It(e,`http://www.w3.org/1999/xlink`,`xlink:arcrole`,r);break;case`xlinkRole`:It(e,`http://www.w3.org/1999/xlink`,`xlink:role`,r);break;case`xlinkShow`:It(e,`http://www.w3.org/1999/xlink`,`xlink:show`,r);break;case`xlinkTitle`:It(e,`http://www.w3.org/1999/xlink`,`xlink:title`,r);break;case`xlinkType`:It(e,`http://www.w3.org/1999/xlink`,`xlink:type`,r);break;case`xmlBase`:It(e,`http://www.w3.org/XML/1998/namespace`,`xml:base`,r);break;case`xmlLang`:It(e,`http://www.w3.org/XML/1998/namespace`,`xml:lang`,r);break;case`xmlSpace`:It(e,`http://www.w3.org/XML/1998/namespace`,`xml:space`,r);break;case`is`:Pt(e,`is`,r);break;case`innerText`:case`textContent`:break;default:(!(2<n.length)||n[0]!==`o`&&n[0]!==`O`||n[1]!==`n`&&n[1]!==`N`)&&(n=nn.get(n)||n,Pt(e,n,r))}}function Nd(e,t,n,r,a,o){switch(n){case`style`:en(e,r,o);break;case`dangerouslySetInnerHTML`:if(r!=null){if(typeof r!=`object`||!(`__html`in r))throw Error(i(61));if(n=r.__html,n!=null){if(a.children!=null)throw Error(i(60));e.innerHTML=n}}break;case`children`:typeof r==`string`?Zt(e,r):(typeof r==`number`||typeof r==`bigint`)&&Zt(e,``+r);break;case`onScroll`:r!=null&&Q(`scroll`,e);break;case`onScrollEnd`:r!=null&&Q(`scrollend`,e);break;case`onClick`:r!=null&&(e.onclick=on);break;case`suppressContentEditableWarning`:case`suppressHydrationWarning`:case`innerHTML`:case`re Line truncated
const theme = ${JSON.stringify(t,null,2)};
theme.breakpoints = createBreakpoints(theme.breakpoints || {});
theme.transitions = createTransitions(theme.transitions || {});
export default theme;`}function xa(e){return typeof e==`number`?`${(e*100).toFixed(0)}%`:`calc((${e}) * 100%)`}var Sa=e=>{if(!Number.isNaN(+e))return+e;let t=e.match(/\d*\.?\d+/g);if(!t)return 0;let n=0;for(let e=0;e<t.length;e+=1)n+=+t[e];return n};function Ca(e){Object.assign(e,{alpha(t,n){let r=this||e;return r.colorSpace?`oklch(from ${t} l c h / ${typeof n==`string`?`calc(${n})`:n})`:r.vars?`rgba(${t.replace(/var\(--([^,\s)]+)(?:,[^)]+)?\)+/g,`var(--$1Channel)`)} / ${typeof n==`string`?`calc(${n})`:n})`:bi(t,Sa(n))},lighten(t,n){let r=this||e;return r.colorSpace?`color-mix(in ${r.colorSpace}, ${t}, #fff ${xa(n)})`:Ci(t,n)},darken(t,n){let r=this||e;return r.colorSpace?`color-mix(in ${r.colorSpace}, ${t}, #000 ${xa(n)})`:Si(t,n)}})}function wa(e={},...t){let{breakpoints:n,mixins:r={},spacing:i,palette:a={},transitions:o={},typography:s={},shape:c,colorSpace:l,...u}=e;if(e.vars&&e.generateThemeVars===void 0)throw Error(ee(20));let d=na({...a,colorSpace:l}),f=Nr(e),p=vn(f,{mixins:ia(f.breakpoints,r),palette:d,shadows:fa.slice(),typography:ca(d,s),transitions:_a(o),zIndex:{...va}});return p=vn(p,u),p=t.reduce((e,t)=>vn(e,t),p),p.unstable_sxConfig={...Dr,...u?.unstable_sxConfig},p.unstable_sx=function(e){return jr({sx:e,theme:this})},p.toRuntimeSource=ba,Ca(p),p}function Ta(e){let t;return t=e<1?5.11916*e**2:4.5*Math.log(e+1)+2,Math.round(t*10)/1e3}var Ea=[...Array(25)].map((e,t)=>{if(t===0)return`none`;let n=Ta(t);return`linear-gradient(rgba(255 255 255 / ${n}), rgba(255 255 255 / ${n}))`});function Da(e){return{inputPlaceholder:e===`dark`?.5:.42,inputUnderline:e===`dark`?.7:.42,switchTrackDisabled:e===`dark`?.2:.12,switchTrack:e===`dark`?.3:.38}}function Oa(e){return e===`dark`?Ea:[]}function ka(e){let{palette:t={mode:`light`},opacity:n,overlays:r,colorSpace:i,...a}=e,o=na({...t,colorSpace:i});return{palette:o,opacity:{...Da(o.mode),...n},overlays:r||Oa(o.mode),...a}}function Aa(e){return!!e[0].match(/(cssVarPrefix|colorSchemeSelector|modularCssLayers|rootSelector|typography|mixins|breakpoints|direction|transitions)/)||!!e[0].match(/sxConfig$/)||e[0]===`palette`&&!!e[1]?.match(/(mode|contrastThreshold|tonalOffset)/)}var ja=e=>[...[...Array(25)].map((t,n)=>`--${e?`${e}-`:``}overlays-${n}`),`--${e?`${e}-`:``}palette-AppBar-darkBg`,`--${e?`${e}-`:``}palette-AppBar-darkColor`],Ma=e=>(t,n)=>{let r=e.rootSelector||`:root`,i=e.colorSchemeSelector,a=i;if(i===`class`&&(a=`.%s`),i===`data`&&(a=`[data-%s]`),i?.startsWith(`data-`)&&!i.includes(`%s`)&&(a=`[${i}="%s"]`),e.defaultColorScheme===t){if(t===`dark`){let i={};return ja(e.cssVarPrefix).forEach(e=>{i[e]=n[e],delete n[e]}),a===`media`?{[r]:n,"@media (prefers-color-scheme: dark)":{[r]:i}}:a?{[a.replace(`%s`,t)]:i,[`${r}, ${a.replace(`%s`,t)}`]:n}:{[r]:{...n,...i}}}if(a&&a!==`media`)return`${r}, ${a.replace(`%s`,String(t))}`}else if(t){if(a===`media`)return{[`@media (prefers-color-scheme: ${String(t)})`]:{[r]:n}};if(a)return a.replace(`%s`,String(t))}return r};function Na(e,t){t.forEach(t=>{e[t]||(e[t]={})})}function B(e,t,n){!e[t]&&n&&(e[t]=n)}function Pa(e){return typeof e!=`string`||!e.startsWith(`hsl`)?e:_i(e)}function Fa(e,t){`${t}Channel`in e||(e[`${t}Channel`]=hi(Pa(e[t]),`MUI: Can't create \`palette.${t}Channel\` because \`palette.${t}\` is not one of these formats: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color().
To suppress this warning, you need to explicitly provide the \`palette.${t}Channel\` as a string (in rgb format, for example "12 12 12") or undefined if you want to remove the channel token.`))}function Ia(e){return typeof e==`number`?`${e}px`:typeof e==`string`||typeof e==`function`||Array.isArray(e)?e:`8px`}var La=e=>{try{return e()}catch{}},Ra=(e=`mui`)=>R(e);function za(e,t,n,r,i){if(!n)return;n=n===!0?{}:n;let a=i===`dark`?`dark`:`light`;if(!r){t[i]=ka({...n,palette:{mode:a,...n?.palette},colorSpace:e});return}let{palette:o,...s}=wa({...r,palette:{mode:a,...n?.palette},colorSpace:e});return t[i]={...n,palette:o,opacity:{...Da(a),...n?.opacity},overlays:n?.overlays||Oa(a)},s}function Ba(e={},...t){let{colorSchemes:n={light:!0},defaultColorScheme:r,disableCssColorScheme:i=!1,cssVarPrefix:a=`mui`,nativeColor:o=!1,shouldSkipGeneratingVar:s=Aa,colorSchemeSelector:c=n.light&&n.dark?`media`:void 0,rootSelector:l=`:root`,...u}=e,d=Object.keys(n)[0],f=r||(n.light&&d!==`light`?`light`:d),p=Ra(a),{[f]:m,light:h,dark:g,..._}=n,v={..._},y=m;if((f===`dark`&&!(`dark`in n)||f===`light`&&!(`light`in n))&&(y=!0),!y)throw Error(ee(21,f));let b;o&&(b=`oklch`);let x=za(b,v,y,u,f);h&&!v.light&&za(b,v,h,void 0,`light`),g&&!v.dark&&za(b,v,g,void 0,`dark`);let S={defaultColorScheme:f,...x,cssVarPrefix:a,colorSchemeSelector:c,rootSelector:l,getCssVar:p,colorSchemes:v,font:{...ra(x.typography),...x.font},spacing:Ia(u.spacing)};Object.keys(S.colorSchemes).forEach(e=>{let t=S.colorSchemes[e].palette,n=e=>{let n=e.split(`-`),r=n[1],i=n[2];return p(e,t[r][i])};t.mode===`light`&&(B(t.common,`background`,`#fff`),B(t.common,`onBackground`,`#000`)),t.mode===`dark`&&(B(t.common,`background`,`#000`),B(t.common,`onBackground`,`#fff`));function r(e,t,n){if(b){let r;return e===xi&&(r=`transparent ${((1-n)*100).toFixed(0)}%`),e===F&&(r=`#000 ${(n*100).toFixed(0)}%`),e===I&&(r=`#fff ${(n*100).toFixed(0)}%`),`color-mix(in ${b}, ${t}, ${r})`}return e(t,n)}if(Na(t,[`Alert`,`AppBar`,`Avatar`,`Button`,`Chip`,`FilledInput`,`LinearProgress`,`Skeleton`,`Slider`,`SnackbarContent`,`SpeedDialAction`,`StepConnector`,`StepContent`,`Switch`,`TableCell`,`Tooltip`]),t.mode===`light`){B(t.Alert,`errorColor`,r(F,t.error.light,.6)),B(t.Alert,`infoColor`,r(F,t.info.light,.6)),B(t.Alert,`successColor`,r(F,t.success.light,.6)),B(t.Alert,`warningColor`,r(F,t.warning.light,.6)),B(t.Alert,`errorFilledBg`,n(`palette-error-main`)),B(t.Alert,`infoFilledBg`,n(`palette-info-main`)),B(t.Alert,`successFilledBg`,n(`palette-success-main`)),B(t.Alert,`warningFilledBg`,n(`palette-warning-main`)),B(t.Alert,`errorFilledColor`,La(()=>t.getContrastText(t.error.main))),B(t.Alert,`infoFilledColor`,La(()=>t.getContrastText(t.info.main))),B(t.Alert,`successFilledColor`,La(()=>t.getContrastText(t.success.main))),B(t.Alert,`warningFilledColor`,La(()=>t.getContrastText(t.warning.main))),B(t.Alert,`errorStandardBg`,r(I,t.error.light,.9)),B(t.Alert,`infoStandardBg`,r(I,t.info.light,.9)),B(t.Alert,`successStandardBg`,r(I,t.success.light,.9)),B(t.Alert,`warningStandardBg`,r(I,t.warning.light,.9)),B(t.Alert,`errorIconColor`,n(`palette-error-main`)),B(t.Alert,`infoIconColor`,n(`palette-info-main`)),B(t.Alert,`successIconColor`,n(`palette-success-main`)),B(t.Alert,`warningIconColor`,n(`palette-warning-main`)),B(t.AppBar,`defaultBg`,n(`palette-grey-100`)),B(t.Avatar,`defaultBg`,n(`palette-grey-400`)),B(t.Button,`inheritContainedBg`,n(`palette-grey-300`)),B(t.Button,`inheritContainedHoverBg`,n(`palette-grey-A100`)),B(t.Chip,`defaultBorder`,n(`palette-grey-400`)),B(t.Chip,`defaultAvatarColor`,n(`palette-grey-700`)),B(t.Chip,`defaultIconColor`,n(`palette-grey-700`)),B(t.FilledInput,`bg`,`rgba(0, 0, 0, 0.06)`),B(t.FilledInput,`hoverBg`,`rgba(0, 0, 0, 0.09)`),B(t.FilledInput,`disabledBg`,`rgba(0, 0, 0, 0.12)`),B(t.LinearProgress,`primaryBg`,r(I,t.primary.main,.62)),B(t.LinearProgress,`secondaryBg`,r(I,t.secondary.main,.62)),B(t.LinearProgress,`errorBg`,r(I,t.error.main,.62)),B(t.LinearProgress,`infoBg`,r(I,t.info.main,.62)),B(t.LinearProgress,`successBg`,r(I,t.success.main,.62)),B(t.LinearProgress,`warningBg`,r(I,t.warning.main,.62)),B(t.Skeleton,`bg`,b?r(xi,t.text.primary,.11):`rgba(${n(`palette-text-primaryChannel`)} / 0.11)`),B(t.Slider,`primaryTrack`,r(I,t.primary.main,.62)),B(t.Slider,`secondaryTrack`,r(I,t.secondary.main,.62)),B(t.Slider,`errorTrack`,r(I,t.error.main,.62)),B(t.Slider,`infoTrack`,r(I,t.info.main,.62)),B(t.Slider,`successTrack`,r(I,t.success.main,.62)),B(t.Slider,`warningTrack`,r(I,t.warning.main,.62));let e=b?r(F,t.background.default,.6825):Ti(t.background.default,.8);B(t.SnackbarContent,`bg`,e),B(t.SnackbarContent,`color`,La(()=>b?Ki.text.primary:t.getContrastText(e))),B(t.SpeedDialAction,`fabHoverBg`,Ti(t.background.paper,.15)),B(t.StepConnector,`border`,n(`palette-grey-400`)),B(t.StepContent,`border`,n(`palette-grey-400`)),B(t.Switch,`defaultColor`,n(`palette-common-white`)),B(t.Switch,`defaultDisabledColor`,n(`palette-grey-100`)),B(t.Switch,`primaryDisabledColor`,r(I,t.primarLine truncated
0% {
transform: scale(0);
opacity: 0.1;
}
100% {
transform: scale(1);
opacity: 0.3;
}
`,ko=Jt`
0% {
opacity: 1;
}
100% {
opacity: 0;
}
`,Ao=Jt`
0% {
transform: scale(1);
}
50% {
transform: scale(0.92);
}
100% {
transform: scale(1);
}
`,jo=Ka(`span`,{name:`MuiTouchRipple`,slot:`Root`})({overflow:`hidden`,pointerEvents:`none`,position:`absolute`,zIndex:0,top:0,right:0,bottom:0,left:0,borderRadius:`inherit`}),Mo=Ka(To,{name:`MuiTouchRipple`,slot:`Ripple`})`
opacity: 0;
position: absolute;
&.${Eo.rippleVisible} {
opacity: 0.3;
transform: scale(1);
animation-name: ${Oo};
animation-duration: ${Do}ms;
animation-timing-function: ${({theme:e})=>e.transitions.easing.easeInOut};
}
&.${Eo.ripplePulsate} {
animation-duration: ${({theme:e})=>e.transitions.duration.shorter}ms;
}
& .${Eo.child} {
opacity: 1;
display: block;
width: 100%;
height: 100%;
border-radius: 50%;
background-color: currentColor;
}
& .${Eo.childLeaving} {
opacity: 0;
animation-name: ${ko};
animation-duration: ${Do}ms;
animation-timing-function: ${({theme:e})=>e.transitions.easing.easeInOut};
}
& .${Eo.childPulsate} {
position: absolute;
/* @noflip */
left: 0px;
top: 0;
animation-name: ${Ao};
animation-duration: 2500ms;
animation-timing-function: ${({theme:e})=>e.transitions.easing.easeInOut};
animation-iteration-count: infinite;
animation-delay: 200ms;
}
`,No=M.forwardRef(function(e,t){let{center:n=!1,classes:r={},className:i,...a}=Za({props:e,name:`MuiTouchRipple`}),[o,s]=M.useState([]),c=M.useRef(0),l=M.useRef(null);M.useEffect(()=>{l.current&&=(l.current(),null)},[o]);let u=M.useRef(!1),d=bo(),f=M.useRef(null),p=M.useRef(null),m=M.useCallback(e=>{let{pulsate:t,rippleX:n,rippleY:i,rippleSize:a,cb:o}=e;s(e=>[...e,(0,N.jsx)(Mo,{classes:{ripple:Gr(r.ripple,Eo.ripple),rippleVisible:Gr(r.rippleVisible,Eo.rippleVisible),ripplePulsate:Gr(r.ripplePulsate,Eo.ripplePulsate),child:Gr(r.child,Eo.child),childLeaving:Gr(r.childLeaving,Eo.childLeaving),childPulsate:Gr(r.childPulsate,Eo.childPulsate)},timeout:Do,pulsate:t,rippleX:n,rippleY:i,rippleSize:a},c.current)]),c.current+=1,l.current=o},[r]),h=M.useCallback((e={},t={},r=()=>{})=>{let{pulsate:i=!1,center:a=n||t.pulsate,fakeElement:o=!1}=t;if(e?.type===`mousedown`&&u.current){u.current=!1;return}e?.type===`touchstart`&&(u.current=!0);let s=o?null:p.current,c=s?s.getBoundingClientRect():{width:0,height:0,left:0,top:0},l,h,g;if(a||e===void 0||e.clientX===0&&e.clientY===0||!e.clientX&&!e.touches)l=Math.round(c.width/2),h=Math.round(c.height/2);else{let{clientX:t,clientY:n}=e.touches&&e.touches.length>0?e.touches[0]:e;l=Math.round(t-c.left),h=Math.round(n-c.top)}if(a)g=Math.sqrt((2*c.width**2+c.height**2)/3),g%2==0&&(g+=1);else{let e=Math.max(Math.abs((s?s.clientWidth:0)-l),l)*2+2,t=Math.max(Math.abs((s?s.clientHeight:0)-h),h)*2+2;g=Math.sqrt(e**2+t**2)}e?.touches?f.current===null&&(f.current=()=>{m({pulsate:i,rippleX:l,rippleY:h,rippleSize:g,cb:r})},d.start(80,()=>{f.current&&=(f.current(),null)})):m({pulsate:i,rippleX:l,rippleY:h,rippleSize:g,cb:r})},[n,m,d]),g=M.useCallback(()=>{h({},{pulsate:!0})},[h]),_=M.useCallback((e,t)=>{if(d.clear(),e?.type===`touchend`&&f.current){f.current(),f.current=null,d.start(0,()=>{_(e,t)});return}f.current=null,s(e=>e.length>0?e.slice(1):e),l.current=t},[d]);return M.useImperativeHandle(t,()=>({pulsate:g,start:h,stop:_}),[g,h,_]),(0,N.jsx)(jo,{className:Gr(Eo.root,r.root,i),ref:p,...a,children:(0,N.jsx)(mo,{component:null,exit:!0,children:o})})});function Po(e){return Jr(`MuiButtonBase`,e)}var Fo=Yr(`MuiButtonBase`,[`root`,`disabled`,`focusVisible`]),Io=e=>{let{disabled:t,focusVisible:n,focusVisibleClassName:r,classes:i}=e,a=Hi({root:[`root`,t&&`disabled`,n&&`focusVisible`]},Po,i);return n&&r&&(a.root+=` ${r}`),a},Lo=Ka(`button`,{name:`MuiButtonBase`,slot:`Root`})({display:`inline-flex`,alignItems:`center`,justifyContent:`center`,position:`relative`,boxSizing:`border-box`,WebkitTapHighlightColor:`transparent`,backgroundColor:`transparent`,outline:0,border:0,margin:0,borderRadius:0,padding:0,cursor:`pointer`,userSelect:`none`,verticalAlign:`middle`,MozAppearance:`none`,WebkitAppearance:`none`,textDecoration:`none`,color:`inherit`,"&::-moz-focus-inner":{borderStyle:`none`},[`&.${Fo.disabled}`]:{pointerEvents:`none`,cursor:`default`},"@media print":{colorAdjust:`exact`}}),Ro=M.forwardRef(function(e,t){let n=Za({props:e,name:`MuiButtonBase`}),{action:r,centerRipple:i=!1,children:a,className:o,component:s=`button`,disabled:c=!1,disableRipple:l=!1,disableTouchRipple:u=!1,focusRipple:d=!1,focusVisibleClassName:f,LinkComponent:p=`a`,onBlur:m,onClick:h,onContextMenu:g,onDragLeave:_,onFocus:v,onFocusVisible:y,onKeyDown:b,onKeyUp:x,onMouseDown:S,onMouseLeave:C,onMouseUp:w,onTouchEnd:ee,onTouchMove:te,onTouchStart:ne,tabIndex:re=0,TouchRippleProps:ie,touchRippleRef:ae,type:oe,...T}=n,se=M.useRef(null),E=Co(),ce=no(E.ref,ae),[D,O]=M.useState(!1);c&&D&&O(!1),M.useImperativeHandle(r,()=>({focusVisible:()=>{O(!0),se.current.focus()}}),[]);let le=E.shouldMount&&!l&&!c;M.useEffect(()=>{D&&d&&!l&&E.pulsate()},[l,d,D,E]);let ue=zo(E,`start`,S,u),de=zo(E,`stop`,g,u),fe=zo(E,`stop`,_,u),pe=zo(E,`stop`,w,u),k=zo(E,`stop`,e=>{D&&e.preventDefault(),C&&C(e)},u),me=zo(E,`start`,ne,u),he=zo(E,`stop`,ee,u),ge=zo(E,`stop`,te,u),A=zo(E,`stop`,e=>{xo(e.target)||O(!1),m&&m(e)},!1),_e=eo(e=>{se.current||=e.currentTarget,xo(e.target)&&(O(!0),y&&y(e)),v&&v(e)}),j=()=>{let e=se.current;return s&&s!==`button`&&!(e.tagName===`A`&&e.href)},ve=eo(e=>{d&&!e.repeat&&D&&e.key===` `&&E.stop(e,()=>{E.start(e)}),e.target===e.currentTarget&&j()&&e.key===` `&&e.preventDefault(),b&&b(e),e.target===e.currentTarget&&j()&&e.key===`Enter`&&!c&&(e.preventDefault(),h&&h(e))}),ye=eo(e=>{d&&e.key===` `&&D&&!e.defaultPrevented&&E.stop(e,()=>{E.pulsate(e)}),x&&x(e),h&&e.target===e.currentTarget&&j()&&e.key===` `&&!e.defaultPrevented&&h(e)}),be=s;be===`button`&&(T.href||T.to)&&(be=p);let xe={};if(be===`button`){let e=!!T.formAction;xe.type=oe===void 0&&!e?`button`:oe,xe.disabled=c}else !T.href&&!T.to&&(xe.role=`button`),c&&(xe[`aria-disabled`]=c);let Se=no(t,se),Ce={...n,centerRipple:i,component:s,disabled:c,disableRipple:l,disableTouchRipple:u,focusRipple:d,tabIndex:re,focusVisible:D},we=Io(Ce);return(0,N.jsxs)(Lo,{as:be,className:Gr(we.root,o),ownerState:Ce,onBlur:A,onClick:h,onContextMenu:de,onFocus:_e,onKeyDown:ve,onKeyUp:ye,onMouseDown:ue Line truncated
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
`,Ko=Jt`
0% {
stroke-dasharray: 1px, 200px;
stroke-dashoffset: 0;
}
50% {
stroke-dasharray: 100px, 200px;
stroke-dashoffset: -15px;
}
100% {
stroke-dasharray: 1px, 200px;
stroke-dashoffset: -126px;
}
`,qo=typeof Go==`string`?null:qt`
animation: ${Go} 1.4s linear infinite;
`,Jo=typeof Ko==`string`?null:qt`
animation: ${Ko} 1.4s ease-in-out infinite;
`,Yo=e=>{let{classes:t,variant:n,color:r,disableShrink:i}=e;return Hi({root:[`root`,n,`color${V(r)}`],svg:[`svg`],track:[`track`],circle:[`circle`,`circle${V(n)}`,i&&`circleDisableShrink`]},Uo,t)},Xo=Ka(`span`,{name:`MuiCircularProgress`,slot:`Root`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.root,t[n.variant],t[`color${V(n.color)}`]]}})(Xa(({theme:e})=>({display:`inline-block`,variants:[{props:{variant:`determinate`},style:{transition:e.transitions.create(`transform`)}},{props:{variant:`indeterminate`},style:qo||{animation:`${Go} 1.4s linear infinite`}},...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t},style:{color:(e.vars||e).palette[t].main}}))]}))),Zo=Ka(`svg`,{name:`MuiCircularProgress`,slot:`Svg`})({display:`block`}),Qo=Ka(`circle`,{name:`MuiCircularProgress`,slot:`Circle`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.circle,t[`circle${V(n.variant)}`],n.disableShrink&&t.circleDisableShrink]}})(Xa(({theme:e})=>({stroke:`currentColor`,variants:[{props:{variant:`determinate`},style:{transition:e.transitions.create(`stroke-dashoffset`)}},{props:{variant:`indeterminate`},style:{strokeDasharray:`80px, 200px`,strokeDashoffset:0}},{props:({ownerState:e})=>e.variant===`indeterminate`&&!e.disableShrink,style:Jo||{animation:`${Ko} 1.4s ease-in-out infinite`}}]}))),$o=Ka(`circle`,{name:`MuiCircularProgress`,slot:`Track`})(Xa(({theme:e})=>({stroke:`currentColor`,opacity:(e.vars||e).palette.action.activatedOpacity}))),es=M.forwardRef(function(e,t){let n=Za({props:e,name:`MuiCircularProgress`}),{className:r,color:i=`primary`,disableShrink:a=!1,enableTrackSlot:o=!1,size:s=40,style:c,thickness:l=3.6,value:u=0,variant:d=`indeterminate`,...f}=n,p={...n,color:i,disableShrink:a,size:s,thickness:l,value:u,variant:d,enableTrackSlot:o},m=Yo(p),h={},g={},_={};if(d===`determinate`){let e=2*Math.PI*((Wo-l)/2);h.strokeDasharray=e.toFixed(3),_[`aria-valuenow`]=Math.round(u),h.strokeDashoffset=`${((100-u)/100*e).toFixed(3)}px`,g.transform=`rotate(-90deg)`}return(0,N.jsx)(Xo,{className:Gr(m.root,r),style:{width:s,height:s,...g,...c},ownerState:p,ref:t,role:`progressbar`,..._,...f,children:(0,N.jsxs)(Zo,{className:m.svg,ownerState:p,viewBox:`${Wo/2} ${Wo/2} ${Wo} ${Wo}`,children:[o?(0,N.jsx)($o,{className:m.track,ownerState:p,cx:Wo,cy:Wo,r:(Wo-l)/2,fill:`none`,strokeWidth:l,"aria-hidden":`true`}):null,(0,N.jsx)(Qo,{className:m.circle,style:h,ownerState:p,cx:Wo,cy:Wo,r:(Wo-l)/2,fill:`none`,strokeWidth:l})]})})});function ts(e){return Jr(`MuiTypography`,e)}Yr(`MuiTypography`,[`root`,`h1`,`h2`,`h3`,`h4`,`h5`,`h6`,`subtitle1`,`subtitle2`,`body1`,`body2`,`inherit`,`button`,`caption`,`overline`,`alignLeft`,`alignRight`,`alignCenter`,`alignJustify`,`noWrap`,`gutterBottom`,`paragraph`]);var ns={primary:!0,secondary:!0,error:!0,info:!0,success:!0,warning:!0,textPrimary:!0,textSecondary:!0,textDisabled:!0},rs=Ya(),is=e=>{let{align:t,gutterBottom:n,noWrap:r,paragraph:i,variant:a,classes:o}=e;return Hi({root:[`root`,a,e.align!==`inherit`&&`align${V(t)}`,n&&`gutterBottom`,r&&`noWrap`,i&&`paragraph`]},ts,o)},as=Ka(`span`,{name:`MuiTypography`,slot:`Root`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.root,n.variant&&t[n.variant],n.align!==`inherit`&&t[`align${V(n.align)}`],n.noWrap&&t.noWrap,n.gutterBottom&&t.gutterBottom,n.paragraph&&t.paragraph]}})(Xa(({theme:e})=>({margin:0,variants:[{props:{variant:`inherit`},style:{font:`inherit`,lineHeight:`inherit`,letterSpacing:`inherit`}},...Object.entries(e.typography).filter(([e,t])=>e!==`inherit`&&t&&typeof t==`object`).map(([e,t])=>({props:{variant:e},style:t})),...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t},style:{color:(e.vars||e).palette[t].main}})),...Object.entries(e.palette?.text||{}).filter(([,e])=>typeof e==`string`).map(([t])=>({props:{color:`text${V(t)}`},style:{color:(e.vars||e).palette.text[t]}})),{props:({ownerState:e})=>e.align!==`inherit`,style:{textAlign:`var(--Typography-textAlign)`}},{props:({ownerState:e})=>e.noWrap,style:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`}},{props:({ownerState:e})=>e.gutterBottom,style:{marginBottom:`0.35em`}},{props:({ownerState:e})=>e.paragraph,style:{marginBottom:16}}]}))),os={h1:`h1`,h2:`h2`,h3:`h3`,h4:`h4`,h5:`h5`,h6:`h6`,subtitle1:`h6`,subtitle2:`h6`,body1:`p`,body2:`p`,inherit:`p`},ss=M.forwardRef(function(e,t){let{color:n,...r}=Za({props:e,name:`MuiTypography`}),i=!ns[n],a=rs({...r,...i&&{color:n}}),{align:o=`inherit`,className:s,component:c,gutterBottom:l=!1,noWrap:u=!1,paragraph:d=!1,variant:f=`body1`,variantMapping:p=os,...m}=a,h={...a,align:o,color:n,className:s,component:c,gutterBottom:l,noWrap:u,paragraph:d,variant:f,variantMapping:p};return(0,N.jsx)(as,{as:c||(d?`p`:p[f]||os[f])||`span`,ref:t,className:Gr(is(h).root,s),...m,ownerState:h,style:{...o!==`inherit`&&{"--Typography-textAlign":o},...m.style}})}),cs=Yr(`MuiBox`,[`root`]),ls=Kr({themeId:te,defaultTheme:Ha(),defaultClassName:cs.root,generateClassName:Ur.generate});function us(e){return Line truncated
0% {
left: -35%;
right: 100%;
}
60% {
left: 100%;
right: -90%;
}
100% {
left: 100%;
right: -90%;
}
`,Ns=typeof Ms==`string`?null:qt`
animation: ${Ms} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite;
`,Ps=Jt`
0% {
left: -200%;
right: 100%;
}
60% {
left: 107%;
right: -8%;
}
100% {
left: 107%;
right: -8%;
}
`,Fs=typeof Ps==`string`?null:qt`
animation: ${Ps} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite;
`,Is=Jt`
0% {
opacity: 1;
background-position: 0 -23px;
}
60% {
opacity: 0;
background-position: 0 -23px;
}
100% {
opacity: 1;
background-position: -200px -23px;
}
`,Ls=typeof Is==`string`?null:qt`
animation: ${Is} 3s infinite linear;
`,Rs=e=>{let{classes:t,variant:n,color:r}=e;return Hi({root:[`root`,`color${V(r)}`,n],dashed:[`dashed`,`dashedColor${V(r)}`],bar1:[`bar`,`bar1`,`barColor${V(r)}`,(n===`indeterminate`||n===`query`)&&`bar1Indeterminate`,n===`determinate`&&`bar1Determinate`,n===`buffer`&&`bar1Buffer`],bar2:[`bar`,`bar2`,n!==`buffer`&&`barColor${V(r)}`,n===`buffer`&&`color${V(r)}`,(n===`indeterminate`||n===`query`)&&`bar2Indeterminate`,n===`buffer`&&`bar2Buffer`]},As,t)},zs=(e,t)=>e.vars?e.vars.palette.LinearProgress[`${t}Bg`]:e.palette.mode===`light`?e.lighten(e.palette[t].main,.62):e.darken(e.palette[t].main,.5),Bs=Ka(`span`,{name:`MuiLinearProgress`,slot:`Root`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.root,t[`color${V(n.color)}`],t[n.variant]]}})(Xa(({theme:e})=>({position:`relative`,overflow:`hidden`,display:`block`,height:4,zIndex:0,"@media print":{colorAdjust:`exact`},variants:[...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t},style:{backgroundColor:zs(e,t)}})),{props:({ownerState:e})=>e.color===`inherit`&&e.variant!==`buffer`,style:{"&::before":{content:`""`,position:`absolute`,left:0,top:0,right:0,bottom:0,backgroundColor:`currentColor`,opacity:.3}}},{props:{variant:`buffer`},style:{backgroundColor:`transparent`}},{props:{variant:`query`},style:{transform:`rotate(180deg)`}}]}))),Vs=Ka(`span`,{name:`MuiLinearProgress`,slot:`Dashed`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.dashed,t[`dashedColor${V(n.color)}`]]}})(Xa(({theme:e})=>({position:`absolute`,marginTop:0,height:`100%`,width:`100%`,backgroundSize:`10px 10px`,backgroundPosition:`0 -23px`,variants:[{props:{color:`inherit`},style:{opacity:.3,backgroundImage:`radial-gradient(currentColor 0%, currentColor 16%, transparent 42%)`}},...Object.entries(e.palette).filter(Ho()).map(([t])=>{let n=zs(e,t);return{props:{color:t},style:{backgroundImage:`radial-gradient(${n} 0%, ${n} 16%, transparent 42%)`}}})]})),Ls||{animation:`${Is} 3s infinite linear`}),Hs=Ka(`span`,{name:`MuiLinearProgress`,slot:`Bar1`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.bar,t.bar1,t[`barColor${V(n.color)}`],(n.variant===`indeterminate`||n.variant===`query`)&&t.bar1Indeterminate,n.variant===`determinate`&&t.bar1Determinate,n.variant===`buffer`&&t.bar1Buffer]}})(Xa(({theme:e})=>({width:`100%`,position:`absolute`,left:0,bottom:0,top:0,transition:`transform 0.2s linear`,transformOrigin:`left`,variants:[{props:{color:`inherit`},style:{backgroundColor:`currentColor`}},...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t},style:{backgroundColor:(e.vars||e).palette[t].main}})),{props:{variant:`determinate`},style:{transition:`transform .${js}s linear`}},{props:{variant:`buffer`},style:{zIndex:1,transition:`transform .${js}s linear`}},{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:{width:`auto`}},{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:Ns||{animation:`${Ms} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite`}}]}))),Us=Ka(`span`,{name:`MuiLinearProgress`,slot:`Bar2`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.bar,t.bar2,t[`barColor${V(n.color)}`],(n.variant===`indeterminate`||n.variant===`query`)&&t.bar2Indeterminate,n.variant===`buffer`&&t.bar2Buffer]}})(Xa(({theme:e})=>({width:`100%`,position:`absolute`,left:0,bottom:0,top:0,transition:`transform 0.2s linear`,transformOrigin:`left`,variants:[...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t},style:{"--LinearProgressBar2-barColor":(e.vars||e).palette[t].main}})),{props:({ownerState:e})=>e.variant!==`buffer`&&e.color!==`inherit`,style:{backgroundColor:`var(--LinearProgressBar2-barColor, currentColor)`}},{props:({ownerState:e})=>e.variant!==`buffer`&&e.color===`inherit`,style:{backgroundColor:`currentColor`}},{props:{color:`inherit`},style:{opacity:.3}},...Object.entries(e.palette).filter(Ho()).map(([t])=>({props:{color:t,variant:`buffer`},style:{backgroundColor:zs(e,t),transition:`transform .${js}s linear`}})),{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:{width:`auto`}},{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:Fs||{animation:`${Ps} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite`}}]}))),Ws=M.forwardRef(function(e,t){let n=Za({props:e,name:`MuiLinearProgress`}),{className:r,color:i=`primary`,value:a,valueBuffer:o,variant:s=`indeterminate`,...c}=n,l={...n,color:i,variant:s},u=Rs(l),d=Di(),f={},p={bar1:{},bar2:{}};if((s===`determinate`||s===`buffer`)&&a!==void 0){f[`aria-valuenow`]=Math.round(a),f[`aria-valuemin`]=0,f[`aria-valuemax`]=100;let e=a-100;d&&(e=-e),p.bar1.transform=`translateX(${e}%)`}if(s===`buffer`&&o!==void 0){let e=(o||0)-100;d&&(e=-e),p.bar2.transform=`translateX(${e}%)`}return(0,N.jsxs)(Bs,{className:Gr(u.root,r),ownerState:l,role:`progressbar`,...f,ref:t,...c,children:[s===`buffer`?(0,N.jsx)(Vs,{className:u.dashed,ownerState:l}):null,(0,N.jsx)(Hs,{className:u.bar1,ownerState:l,s Line truncated
+3 -3
View File
@@ -4,9 +4,9 @@
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<title>GP Connect Helper</title> <title>GlobalProtect</title>
<script type="module" crossorigin src="/assets/main-CyyZK63u.js"></script> <script type="module" crossorigin src="/assets/main-CQPVXkdn.js"></script>
<link rel="stylesheet" crossorigin href="/assets/main-C5muOSVO.css"> <link rel="stylesheet" crossorigin href="/assets/main-B3YRsHQ2.css">
</head> </head>
<body> <body>
<script> <script>
+1 -1
View File
@@ -4,7 +4,7 @@
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<title>GP Connect Helper</title> <title>GlobalProtect</title>
</head> </head>
<body> <body>
<script> <script>
+20 -20
View File
@@ -10,28 +10,28 @@
}, },
"dependencies": { "dependencies": {
"@emotion/react": "^11.14.0", "@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.1", "@emotion/styled": "^11.14.0",
"@mui/icons-material": "^7.3.10", "@mui/icons-material": "^6.3.0",
"@mui/material": "^7.3.10", "@mui/material": "^6.3.0",
"@tauri-apps/api": "^2.11.0", "@tauri-apps/api": "^2.1.1",
"react": "^19.2.5", "react": "^19.0.0",
"react-dom": "^19.2.5" "react-dom": "^19.0.0"
}, },
"devDependencies": { "devDependencies": {
"@tauri-apps/cli": "^2.11.1", "@tauri-apps/cli": "^2.1.0",
"@types/node": "^25.6.0", "@types/node": "^22.10.2",
"@types/react": "^19.2.14", "@types/react": "^19.0.2",
"@types/react-dom": "^19.2.3", "@types/react-dom": "^19.0.2",
"@typescript-eslint/eslint-plugin": "^8.59.2", "@typescript-eslint/eslint-plugin": "^8.18.2",
"@typescript-eslint/parser": "^8.59.2", "@typescript-eslint/parser": "^8.18.2",
"@vitejs/plugin-react": "^6.0.1", "@vitejs/plugin-react": "^4.3.4",
"eslint": "^9.39.4", "eslint": "^9.17.0",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^9.1.0",
"eslint-plugin-react": "^7.37.5", "eslint-plugin-react": "^7.37.3",
"eslint-plugin-react-hooks": "^7.1.1", "eslint-plugin-react-hooks": "^5.1.0",
"prettier": "3.8.3", "prettier": "3.4.2",
"typescript": "^6.0.3", "typescript": "^5.7.2",
"vite": "^8.0.10" "vite": "^6.0.5"
}, },
"packageManager": "[email protected]" "packageManager": "[email protected]"
} }
+1285 -1523
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -24,4 +24,4 @@ tempfile.workspace = true
reqwest = { workspace = true, features = ["stream"] } reqwest = { workspace = true, features = ["stream"] }
[features] [features]
default = ["tauri/custom-protocol"] custom-protocol = ["tauri/custom-protocol"]
+4 -9
View File
@@ -88,10 +88,6 @@ impl GuiUpdater {
} }
pub async fn update(&self) { pub async fn update(&self) {
if !cfg!(any(target_arch = "x86_64", target_arch = "aarch64")) {
info!("GUI version is not supported on this architecture.");
return;
}
info!("Update GUI, version: {}", self.version); info!("Update GUI, version: {}", self.version);
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
@@ -103,11 +99,10 @@ impl GuiUpdater {
format!("v{}", self.version) format!("v{}", self.version)
}; };
let arch = if cfg!(target_arch = "x86_64") { #[cfg(target_arch = "x86_64")]
"x86_64" let arch = "x86_64";
} else { #[cfg(target_arch = "aarch64")]
"aarch64" let arch = "aarch64";
};
let file_url = format!( let file_url = format!(
"https://github.com/yuezk/GlobalProtect-openconnect/releases/download/{}/gpgui_{}.bin.tar.xz", "https://github.com/yuezk/GlobalProtect-openconnect/releases/download/{}/gpgui_{}.bin.tar.xz",
+1 -1
View File
@@ -15,7 +15,7 @@
}, },
"windows": [ "windows": [
{ {
"title": "GP Connect Helper", "title": "GlobalProtect GUI Helper",
"center": true, "center": true,
"resizable": true, "resizable": true,
"width": 500, "width": 500,
+1 -1
View File
@@ -20,7 +20,7 @@ export default defineConfig(async () => {
// https://tauri.app/v1/api/config#buildconfig.beforedevcommand // https://tauri.app/v1/api/config#buildconfig.beforedevcommand
envPrefix: ["VITE_", "TAURI_"], envPrefix: ["VITE_", "TAURI_"],
build: { build: {
rolldownOptions: { rollupOptions: {
input: { input: {
main: resolve(__dirname, "index.html"), main: resolve(__dirname, "index.html"),
}, },
-1
View File
@@ -5,7 +5,6 @@ edition.workspace = true
license.workspace = true license.workspace = true
[dependencies] [dependencies]
common = { path = "../../crates/common" }
gpapi = { path = "../../crates/gpapi", features = ["clap", "logger"] } gpapi = { path = "../../crates/gpapi", features = ["clap", "logger"] }
openconnect = { path = "../../crates/openconnect" } openconnect = { path = "../../crates/openconnect" }
clap.workspace = true clap.workspace = true
+3 -3
View File
@@ -3,13 +3,13 @@ use std::{collections::HashMap, io::Write};
use anyhow::bail; use anyhow::bail;
use clap::Parser; use clap::Parser;
use common::constants::GP_SERVICE_LOCK_FILE;
use gpapi::clap::InfoLevelVerbosity; use gpapi::clap::InfoLevelVerbosity;
use gpapi::logger; use gpapi::logger;
use gpapi::{ use gpapi::{
process::gui_launcher::GuiLauncher, process::gui_launcher::GuiLauncher,
service::{request::WsRequest, vpn_state::VpnState}, service::{request::WsRequest, vpn_state::VpnState},
utils::{crypto::generate_key, env_utils, lock_file::LockFile, redact::Redaction, shutdown_signal}, utils::{crypto::generate_key, env_utils, lock_file::LockFile, redact::Redaction, shutdown_signal},
GP_SERVICE_LOCK_FILE,
}; };
use log::{info, warn}; use log::{info, warn};
use tokio::sync::{mpsc, watch}; use tokio::sync::{mpsc, watch};
@@ -120,7 +120,7 @@ impl Cli {
let timestamp = buf.timestamp(); let timestamp = buf.timestamp();
writeln!( writeln!(
buf, buf,
"[{} {:<5} {}] {}", "[{} {} {}] {}",
timestamp, timestamp,
record.level(), record.level(),
record.module_path().unwrap_or_default(), record.module_path().unwrap_or_default(),
@@ -159,7 +159,7 @@ mod signals {
pub async fn handle_signals(vpn_ctx: Arc<VpnTaskContext>, ws_ctx: Arc<WsServerContext>) { pub async fn handle_signals(vpn_ctx: Arc<VpnTaskContext>, ws_ctx: Arc<WsServerContext>) {
use gpapi::service::event::WsEvent; use gpapi::service::event::WsEvent;
use tokio::signal::unix::{Signal, SignalKind, signal}; use tokio::signal::unix::{signal, Signal, SignalKind};
let (mut user_sig1, mut user_sig2) = match || -> anyhow::Result<(Signal, Signal)> { let (mut user_sig1, mut user_sig2) = match || -> anyhow::Result<(Signal, Signal)> {
let user_sig1 = signal(SignalKind::user_defined1())?; let user_sig1 = signal(SignalKind::user_defined1())?;
+2 -2
View File
@@ -11,17 +11,17 @@ use anyhow::bail;
use axum::{ use axum::{
body::Bytes, body::Bytes,
extract::{ extract::{
State, WebSocketUpgrade,
ws::{self, CloseFrame, Message, Utf8Bytes, WebSocket}, ws::{self, CloseFrame, Message, Utf8Bytes, WebSocket},
State, WebSocketUpgrade,
}, },
http::StatusCode, http::StatusCode,
response::IntoResponse, response::IntoResponse,
}; };
use common::constants::GP_GUI_BINARY;
use futures::{SinkExt, StreamExt}; use futures::{SinkExt, StreamExt};
use gpapi::{ use gpapi::{
service::{event::WsEvent, request::UpdateGuiRequest}, service::{event::WsEvent, request::UpdateGuiRequest},
utils::checksum::verify_checksum, utils::checksum::verify_checksum,
GP_GUI_BINARY,
}; };
use log::{info, warn}; use log::{info, warn};
use tar::Archive; use tar::Archive;
+1 -1
View File
@@ -1,8 +1,8 @@
use std::sync::Arc; use std::sync::Arc;
use axum::{ use axum::{
Router,
routing::{get, post}, routing::{get, post},
Router,
}; };
use crate::{handlers, ws_server::WsServerContext}; use crate::{handlers, ws_server::WsServerContext};
+6 -62
View File
@@ -4,13 +4,12 @@ use gpapi::{
logger, logger,
service::{ service::{
request::{ConnectRequest, UpdateLogLevelRequest, WsRequest}, request::{ConnectRequest, UpdateLogLevelRequest, WsRequest},
vpn_state::{ConnectedInfo, VpnState}, vpn_state::VpnState,
}, },
session::{SessionInfo, SessionWarning},
}; };
use log::{info, warn}; use log::{info, warn};
use openconnect::Vpn; use openconnect::Vpn;
use tokio::sync::{RwLock, mpsc, oneshot, watch}; use tokio::sync::{mpsc, oneshot, watch, RwLock};
use tokio_util::sync::CancellationToken; use tokio_util::sync::CancellationToken;
pub(crate) struct VpnTaskContext { pub(crate) struct VpnTaskContext {
@@ -39,26 +38,19 @@ impl VpnTaskContext {
let info = req.info().clone(); let info = req.info().clone();
let vpn_handle = Arc::clone(&self.vpn_handle); let vpn_handle = Arc::clone(&self.vpn_handle);
let args = req.args(); let args = req.args();
let allow_extend_session = args.allow_extend_session();
let vpn = match Vpn::builder(req.gateway().server(), args.cookie()) let vpn = match Vpn::builder(req.gateway().server(), args.cookie())
.script(args.vpnc_script()) .script(args.vpnc_script())
.user_agent(args.user_agent()) .user_agent(args.user_agent())
.os(args.openconnect_os()) .os(args.openconnect_os())
.os_version(args.os_version())
.client_version(args.client_version())
.certificate(args.certificate()) .certificate(args.certificate())
.sslkey(args.sslkey()) .sslkey(args.sslkey())
.key_password(args.key_password()) .key_password(args.key_password())
.hip(args.hip())
.csd_uid(args.csd_uid()) .csd_uid(args.csd_uid())
.csd_wrapper(args.csd_wrapper()) .csd_wrapper(args.csd_wrapper())
.reconnect_timeout(args.reconnect_timeout()) .reconnect_timeout(args.reconnect_timeout())
.mtu(args.mtu()) .mtu(args.mtu())
.disable_ipv6(args.disable_ipv6()) .disable_ipv6(args.disable_ipv6())
.no_dtls(args.no_dtls()) .no_dtls(args.no_dtls())
.local_hostname(args.local_hostname())
.dpd_interval(args.force_dpd())
.no_xmlpost(args.no_xmlpost())
.build() .build()
{ {
Ok(vpn) => vpn, Ok(vpn) => vpn,
@@ -83,19 +75,9 @@ impl VpnTaskContext {
let vpn_state_tx_clone = vpn_state_tx.clone(); let vpn_state_tx_clone = vpn_state_tx.clone();
vpn_handle.blocking_read().as_ref().map(|vpn| { vpn_handle.blocking_read().as_ref().map(|vpn| {
vpn.connect(move |vpn_session_info| { vpn.connect(move || {
let session_info = SessionInfo::from_vpn_session_fields( let connect_info = Box::new(info.clone());
vpn_session_info.lifetime_secs, vpn_state_tx.send(VpnState::Connected(connect_info)).ok();
vpn_session_info.user_expires,
vpn_session_info.lifetime_warning.map(|warning| SessionWarning {
prior_secs: warning.prior_secs,
message: warning.message,
}),
allow_extend_session,
);
info!("VPN session info: {}", session_info.log_summary());
let connected_info = Box::new(ConnectedInfo::new(info.clone(), Some(session_info)));
vpn_state_tx.send(VpnState::Connected(connected_info)).ok();
}) })
}); });
@@ -124,6 +106,7 @@ impl VpnTaskContext {
} else { } else {
info!("VPN is not connected, skip disconnect"); info!("VPN is not connected, skip disconnect");
self.vpn_state_tx.send(VpnState::Disconnected).ok(); self.vpn_state_tx.send(VpnState::Disconnected).ok();
false false
} }
} }
@@ -195,42 +178,3 @@ async fn process_ws_req(req: WsRequest, ctx: Arc<VpnTaskContext>) {
} }
} }
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn maps_openconnect_session_metadata_to_service_session_info() {
let info = SessionInfo::from_vpn_session_fields(
Some(43_200),
None,
Some(SessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
true,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert_eq!(info.expires_in_human.as_deref(), Some("12h"));
assert_eq!(info.lifetime_warning.unwrap().prior_secs, 1_800);
assert!(info.allow_extend_session);
}
#[test]
fn direct_request_session_metadata_keeps_extension_disabled() {
let info = SessionInfo::from_vpn_session_fields(
Some(43_200),
None,
Some(SessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
false,
);
assert_eq!(info.lifetime_secs, Some(43_200));
assert!(!info.allow_extend_session);
}
}
+5 -13
View File
@@ -1,17 +1,15 @@
use std::sync::Arc; use std::sync::Arc;
use axum::extract::ws::Message; use axum::extract::ws::Message;
use common::constants::GP_AUTH_BINARY;
use gpapi::{ use gpapi::{
service::{event::WsEvent, request::WsRequest, vpn_env::VpnEnv, vpn_state::VpnState}, service::{event::WsEvent, request::WsRequest, vpn_state::VpnState},
utils::{crypto::Crypto, lock_file::LockFile, redact::Redaction}, utils::{crypto::Crypto, lock_file::LockFile, redact::Redaction},
}; };
use log::{info, warn}; use log::{info, warn};
use openconnect::{find_csd_wrapper, find_vpnc_script};
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use tokio::{ use tokio::{
net::TcpListener, net::TcpListener,
sync::{RwLock, mpsc, watch}, sync::{mpsc, watch, RwLock},
}; };
use tokio_util::sync::CancellationToken; use tokio_util::sync::CancellationToken;
@@ -58,15 +56,9 @@ impl WsServerContext {
let conn = Arc::new(WsConnection::new(Arc::clone(&self.crypto), tx)); let conn = Arc::new(WsConnection::new(Arc::clone(&self.crypto), tx));
// Send current VPN state to new client // Send current VPN state to new client
info!("Sending current environment to new client"); info!("Sending current VPN state to new client");
let vpn_env = VpnEnv { let vpn_state = self.vpn_state_rx.borrow().clone();
vpn_state: self.vpn_state_rx.borrow().clone(), if let Err(err) = conn.send_event(&WsEvent::VpnState(vpn_state)).await {
vpnc_script: find_vpnc_script().map(|s| s.to_owned()),
csd_wrapper: find_csd_wrapper().map(|s| s.to_owned()),
auth_executable: GP_AUTH_BINARY.to_owned(),
};
if let Err(err) = conn.send_event(&WsEvent::VpnEnv(vpn_env)).await {
warn!("Failed to send VPN state to new client: {}", err); warn!("Failed to send VPN state to new client: {}", err);
} }
-51
View File
@@ -1,56 +1,5 @@
# Changelog # Changelog
## 2.5.2 - 2026-05-06
- Experimental: GUI/CLI add session expiry warnings and support automatic session extension when allowed by the portal.
- GUI/CLI: expose additional OpenConnect connection options.
- Fix Linux packages to vendor the `vpnc-script`.
- Remove OpenConnect from the packaging dependency.
- Fix reconnect handling by preserving GlobalProtect cookie fields.
- Fix auth callback data parsing
- Improve NixOS packaging and user-level installation docs.
- Upgrade Rust, Tauri, Vite, frontend, and Rust dependencies.
## 2.5.1 - 2025-12-22
- Fix the `.deb` package installation issue (fix [#563](https://github.com/yuezk/GlobalProtect-openconnect/issues/563))
- GUI: fix the tray icon size issue on GNOME Flashback (fix [#564](https://github.com/yuezk/GlobalProtect-openconnect/issues/564))
- Improve the HIP report generation logic
## 2.5.0 - 2025-12-08
- GUI/CLI: statically link OpenConnect
- GUI/CLI: support configure the client version
- CLI: add the `-S/--script-tun` option to pass traffic to the `--script` handler
- GUI: update the branding to `GP Connect`
## 2.4.7 - 2025-11-12
- Support NixOS package installation
- Fix the VPNC script location on Void Linux
- Upgrade to Rust 1.85
- `--browser` without argument uses the system default browser
## 2.4.6 - 2025-10-15
- GUI: support the default configuration file for GUI client (fix [#492](https://github.com/yuezk/GlobalProtect-openconnect/issues/492))
- GUI: add the option to not reuse the authentication cookies (fix [#540](https://github.com/yuezk/GlobalProtect-openconnect/issues/540))
- GUI: improve the license validation logic (fix [#502](https://github.com/yuezk/GlobalProtect-openconnect/issues/502))
- CLI: support the `--browser remote` option to use the remote browser for authentication ([#544](https://github.com/yuezk/GlobalProtect-openconnect/pull/544) by [@dark12](https://github.com/dark12))
- CLI: fix gpclient disconnect bailing with client is already running issue ([#542](https://github.com/yuezk/GlobalProtect-openconnect/pull/542) by [@zeroepoch](https://github.com/zeroepoch))
- CLI: fix the `--passwd-on-stdin` reads again on gateway failure ([#546](https://github.com/yuezk/GlobalProtect-openconnect/issues/546))
## 2.4.5 - 2025-07-16
- GUI/CLI: fix the issue that the custom port is not supported issue (fix [#404](https://github.com/yuezk/GlobalProtect-openconnect/issues/404))
- CLI: add the `--force-dpd` option to specify the interval for DPD (Dead Peer Detection).
- CLI: add the `-i/--interface` option to specify the interface to use.
## 2.4.4 - 2025-02-09
- GUI: fix multiple tray icons issue (fix [#464](https://github.com/yuezk/GlobalProtect-openconnect/issues/464))
- CLI: check the cli running state before running the `gpclient` command (fix [#447](https://github.com/yuezk/GlobalProtect-openconnect/issues/447))
## 2.4.3 - 2025-01-21 ## 2.4.3 - 2025-01-21
- Do not use static default value for `--os-version` option. - Do not use static default value for `--os-version` option.
+4 -5
View File
@@ -8,7 +8,6 @@ edition.workspace = true
license.workspace = true license.workspace = true
[dependencies] [dependencies]
common = { path = "../common" }
gpapi = { path = "../gpapi" } gpapi = { path = "../gpapi" }
# Shared dependencies # Shared dependencies
@@ -33,10 +32,10 @@ html-escape = { version = "0.2.13", optional = true }
webkit2gtk = { version = "2", optional = true } webkit2gtk = { version = "2", optional = true }
[target.'cfg(target_os = "macos")'.dependencies] [target.'cfg(target_os = "macos")'.dependencies]
block2 = { version = "0.6", optional = true } block2 = { version = "0.5", optional = true }
objc2 = { version = "0.6", optional = true } objc2 = { version = "0.5", optional = true }
objc2-foundation = { version = "0.3", optional = true } objc2-foundation = { version = "0.2", optional = true }
objc2-web-kit = { version = "0.3", optional = true } objc2-web-kit = { version = "0.2", optional = true }
[features] [features]
browser-auth = [ browser-auth = [
+2 -2
View File
@@ -10,8 +10,8 @@ pub(super) struct AuthServer {
} }
impl AuthServer { impl AuthServer {
pub fn new(addr: &str) -> anyhow::Result<Self> { pub fn new() -> anyhow::Result<Self> {
let server = Server::http(addr).map_err(|err| anyhow::anyhow!(err))?; let server = Server::http("127.0.0.1:0").map_err(|err| anyhow::anyhow!(err))?;
let auth_id = Uuid::new_v4().to_string(); let auth_id = Uuid::new_v4().to_string();
Ok(Self { server, auth_id }) Ok(Self { server, auth_id })
+3 -60
View File
@@ -1,12 +1,8 @@
use std::{env::temp_dir, fs, os::unix::fs::PermissionsExt}; use std::{env::temp_dir, fs, os::unix::fs::PermissionsExt};
use common::constants::GP_CALLBACK_PORT_FILENAME; use gpapi::{auth::SamlAuthData, GP_CALLBACK_PORT_FILENAME};
use gpapi::auth::SamlAuthData;
use log::info; use log::info;
use tokio::{ use tokio::{io::AsyncReadExt, net::TcpListener};
io::AsyncReadExt,
net::{TcpListener, UdpSocket},
};
use crate::browser::auth_server::AuthServer; use crate::browser::auth_server::AuthServer;
@@ -14,7 +10,6 @@ pub enum Browser<'a> {
Default, Default,
Chrome, Chrome,
Firefox, Firefox,
Remote,
Other(&'a str), Other(&'a str),
} }
@@ -24,7 +19,6 @@ impl<'a> Browser<'a> {
"default" => Browser::Default, "default" => Browser::Default,
"chrome" => Browser::Chrome, "chrome" => Browser::Chrome,
"firefox" => Browser::Firefox, "firefox" => Browser::Firefox,
"remote" => Browser::Remote,
_ => Browser::Other(browser), _ => Browser::Other(browser),
} }
} }
@@ -34,7 +28,6 @@ impl<'a> Browser<'a> {
Browser::Default => "default", Browser::Default => "default",
Browser::Chrome => "chrome", Browser::Chrome => "chrome",
Browser::Firefox => "firefox", Browser::Firefox => "firefox",
Browser::Remote => "remote",
Browser::Other(browser) => browser, Browser::Other(browser) => browser,
} }
} }
@@ -54,8 +47,7 @@ impl<'a> BrowserAuthenticator<'a> {
} }
pub async fn authenticate(&self) -> anyhow::Result<SamlAuthData> { pub async fn authenticate(&self) -> anyhow::Result<SamlAuthData> {
let addr = self.determine_addr().await?; let auth_server = AuthServer::new()?;
let auth_server = AuthServer::new(&addr)?;
let auth_url = auth_server.auth_url(); let auth_url = auth_server.auth_url();
let auth_request = self.auth_request.to_string(); let auth_request = self.auth_request.to_string();
@@ -64,25 +56,6 @@ impl<'a> BrowserAuthenticator<'a> {
}); });
match self.browser { match self.browser {
Browser::Remote => {
info!(
r#"
==== Manual Authentication Required ====
Please open the following URL in your browser:
{}
After completing the authentication, please paste the authentication data back to this terminal.
(The data should start with "globalprotectcallback:...")
Note that the URL is only valid for a single use.
"#,
auth_url
);
return read_auth_data_from_stdin();
}
Browser::Default => { Browser::Default => {
info!("Launching the default browser..."); info!("Launching the default browser...");
webbrowser::open(&auth_url)?; webbrowser::open(&auth_url)?;
@@ -98,28 +71,6 @@ Note that the URL is only valid for a single use.
info!("Please continue the authentication process in the default browser"); info!("Please continue the authentication process in the default browser");
wait_auth_data().await wait_auth_data().await
} }
async fn determine_addr(&self) -> anyhow::Result<String> {
if matches!(self.browser, Browser::Remote) {
let local_ip = detect_local_ip().await?;
Ok(format!("{}:0", local_ip))
} else {
Ok("127.0.0.1:0".to_string())
}
}
}
/// Detect the local IP address by creating a UDP socket and connecting to an external address
async fn detect_local_ip() -> anyhow::Result<String> {
let socket = UdpSocket::bind("0.0.0.0:0").await?;
if let Err(err) = socket.connect("1.1.1.1:80").await {
anyhow::bail!("Failed to connect to external address to determine local IP: {}", err);
}
let local_addr = socket.local_addr()?;
let ip = local_addr.ip().to_string();
info!("Determined local IP address: {}", ip);
Ok(ip.to_string())
} }
fn find_browser_path(browser: &Browser) -> String { fn find_browser_path(browser: &Browser) -> String {
@@ -168,11 +119,3 @@ async fn wait_auth_data() -> anyhow::Result<SamlAuthData> {
let auth_data = SamlAuthData::from_gpcallback(&data)?; let auth_data = SamlAuthData::from_gpcallback(&data)?;
Ok(auth_data) Ok(auth_data)
} }
fn read_auth_data_from_stdin() -> anyhow::Result<SamlAuthData> {
let mut data = String::new();
std::io::stdin().read_line(&mut data)?;
let auth_data = SamlAuthData::from_gpcallback(data.trim())?;
Ok(auth_data)
}
+1 -1
View File
@@ -1,7 +1,7 @@
use anyhow::bail; use anyhow::bail;
use gpapi::{ use gpapi::{
gp_params::GpParams, gp_params::GpParams,
portal::{Prelogin, prelogin}, portal::{prelogin, Prelogin},
}; };
#[cfg(feature = "browser-auth")] #[cfg(feature = "browser-auth")]
+1 -1
View File
@@ -2,7 +2,7 @@ use anyhow::bail;
use gpapi::{auth::SamlAuthData, error::AuthDataParseError}; use gpapi::{auth::SamlAuthData, error::AuthDataParseError};
use log::{error, info}; use log::{error, info};
use regex::Regex; use regex::Regex;
use tokio::sync::{RwLock, mpsc}; use tokio::sync::{mpsc, RwLock};
use tokio_util::sync::CancellationToken; use tokio_util::sync::CancellationToken;
#[derive(Debug)] #[derive(Debug)]
+1 -1
View File
@@ -1,7 +1,7 @@
use block2::RcBlock; use block2::RcBlock;
use log::warn; use log::warn;
use objc2::runtime::AnyObject; use objc2::runtime::AnyObject;
use objc2_foundation::{NSError, NSString, NSURL, NSURLRequest}; use objc2_foundation::{NSError, NSString, NSURLRequest, NSURL};
use objc2_web_kit::WKWebView; use objc2_web_kit::WKWebView;
use tauri::webview::PlatformWebview; use tauri::webview::PlatformWebview;
+2 -2
View File
@@ -5,8 +5,8 @@ use gpapi::utils::redact::redact_uri;
use log::warn; use log::warn;
use tauri::webview::PlatformWebview; use tauri::webview::PlatformWebview;
use webkit2gtk::{ use webkit2gtk::{
LoadEvent, TLSErrorsPolicy, URIResponseExt, WebResource, WebResourceExt, WebViewExt, WebsiteDataManagerExt, gio::Cancellable, glib::GString, LoadEvent, TLSErrorsPolicy, URIResponseExt, WebResource, WebResourceExt, WebViewExt,
gio::Cancellable, glib::GString, WebsiteDataManagerExt,
}; };
use super::{ use super::{
+2 -3
View File
@@ -4,8 +4,8 @@ use anyhow::bail;
use gpapi::{auth::SamlAuthData, gp_params::GpParams, utils::redact::redact_uri}; use gpapi::{auth::SamlAuthData, gp_params::GpParams, utils::redact::redact_uri};
use log::{info, warn}; use log::{info, warn};
use tauri::{ use tauri::{
AppHandle, WebviewUrl, WebviewWindow, WindowEvent,
webview::{PageLoadEvent, PageLoadPayload}, webview::{PageLoadEvent, PageLoadPayload},
AppHandle, WebviewUrl, WebviewWindow, WindowEvent,
}; };
use tokio::{sync::oneshot, time}; use tokio::{sync::oneshot, time};
@@ -103,8 +103,7 @@ impl<'a> WebviewAuthenticator<'a> {
.title("GlobalProtect Login") .title("GlobalProtect Login")
.inner_size(900.0, 650.0 + title_bar_height) .inner_size(900.0, 650.0 + title_bar_height)
.focused(true) .focused(true)
// when clean is true, the window is expected to be shown because the cookies are cleared .visible(false)
.visible(self.clean)
.center() .center()
.build()?; .build()?;
+3
View File
@@ -6,3 +6,6 @@ authors.workspace = true
homepage.workspace = true homepage.workspace = true
edition.workspace = true edition.workspace = true
license.workspace = true license.workspace = true
[dependencies]
is_executable.workspace = true
-52
View File
@@ -1,52 +0,0 @@
pub const GP_USER_AGENT: &str = "PAN GlobalProtect";
pub const GP_CLIENT_VERSION: &str = "6.3.0-33";
pub const GP_SERVICE_LOCK_FILE: &str = "/var/run/gpservice.lock";
pub const GP_CALLBACK_PORT_FILENAME: &str = "gpcallback.port";
// Release binaries - macOS (Apple Silicon Homebrew)
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))]
pub const GP_CLIENT_BINARY: &str = "/opt/homebrew/bin/gpclient";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))]
pub const GP_SERVICE_BINARY: &str = "/opt/homebrew/bin/gpservice";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))]
pub const GP_GUI_BINARY: &str = "/opt/homebrew/bin/gpgui";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))]
pub const GP_GUI_HELPER_BINARY: &str = "/opt/homebrew/bin/gpgui-helper";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "aarch64"))]
pub const GP_AUTH_BINARY: &str = "/opt/homebrew/bin/gpauth";
// Release binaries - macOS (Intel Homebrew)
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))]
pub const GP_CLIENT_BINARY: &str = "/usr/local/bin/gpclient";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))]
pub const GP_SERVICE_BINARY: &str = "/usr/local/bin/gpservice";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))]
pub const GP_GUI_BINARY: &str = "/usr/local/bin/gpgui";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))]
pub const GP_GUI_HELPER_BINARY: &str = "/usr/local/bin/gpgui-helper";
#[cfg(all(not(debug_assertions), target_os = "macos", target_arch = "x86_64"))]
pub const GP_AUTH_BINARY: &str = "/usr/local/bin/gpauth";
// Release binaries - Linux
#[cfg(all(not(debug_assertions), not(target_os = "macos")))]
pub const GP_CLIENT_BINARY: &str = "/usr/bin/gpclient";
#[cfg(all(not(debug_assertions), not(target_os = "macos")))]
pub const GP_SERVICE_BINARY: &str = "/usr/bin/gpservice";
#[cfg(all(not(debug_assertions), not(target_os = "macos")))]
pub const GP_GUI_BINARY: &str = "/usr/bin/gpgui";
#[cfg(all(not(debug_assertions), not(target_os = "macos")))]
pub const GP_GUI_HELPER_BINARY: &str = "/usr/bin/gpgui-helper";
#[cfg(all(not(debug_assertions), not(target_os = "macos")))]
pub const GP_AUTH_BINARY: &str = "/usr/bin/gpauth";
// Debug binaries are set in build.rs via environment variables
#[cfg(debug_assertions)]
pub const GP_CLIENT_BINARY: &str = env!("GP_CLIENT_BINARY");
#[cfg(debug_assertions)]
pub const GP_SERVICE_BINARY: &str = env!("GP_SERVICE_BINARY");
#[cfg(debug_assertions)]
pub const GP_GUI_BINARY: &str = env!("GP_GUI_BINARY");
#[cfg(debug_assertions)]
pub const GP_GUI_HELPER_BINARY: &str = env!("GP_GUI_HELPER_BINARY");
#[cfg(debug_assertions)]
pub const GP_AUTH_BINARY: &str = env!("GP_AUTH_BINARY");
+1 -1
View File
@@ -1 +1 @@
pub mod constants; pub mod vpn_utils;
@@ -3,51 +3,43 @@ use std::{io, path::Path};
use is_executable::IsExecutable; use is_executable::IsExecutable;
const VPNC_SCRIPT_LOCATIONS: &[&str] = &[ const VPNC_SCRIPT_LOCATIONS: &[&str] = &[
"/usr/libexec/gpclient/vpnc-script",
"/usr/lib/gpclient/vpnc-script",
"/usr/local/share/vpnc-scripts/vpnc-script", "/usr/local/share/vpnc-scripts/vpnc-script",
"/usr/local/sbin/vpnc-script", "/usr/local/sbin/vpnc-script",
"/usr/share/vpnc-scripts/vpnc-script", "/usr/share/vpnc-scripts/vpnc-script",
"/usr/sbin/vpnc-script", "/usr/sbin/vpnc-script",
"/etc/vpnc/vpnc-script", "/etc/vpnc/vpnc-script",
"/etc/openconnect/vpnc-script", "/etc/openconnect/vpnc-script",
"/usr/libexec/vpnc-scripts/vpnc-script", #[cfg(target_os = "macos")]
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
"/opt/homebrew/etc/vpnc/vpnc-script", "/opt/homebrew/etc/vpnc/vpnc-script",
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
"/usr/local/etc/vpnc/vpnc-script",
]; ];
const CSD_WRAPPER_LOCATIONS: &[&str] = &[ const CSD_WRAPPER_LOCATIONS: &[&str] = &[
"/usr/libexec/gpclient/hipreport.sh",
#[cfg(target_arch = "x86_64")] #[cfg(target_arch = "x86_64")]
"/usr/lib/x86_64-linux-gnu/openconnect/hipreport.sh", "/usr/lib/x86_64-linux-gnu/openconnect/hipreport.sh",
#[cfg(target_arch = "aarch64")] #[cfg(target_arch = "aarch64")]
"/usr/lib/aarch64-linux-gnu/openconnect/hipreport.sh", "/usr/lib/aarch64-linux-gnu/openconnect/hipreport.sh",
"/usr/lib/openconnect/hipreport.sh", "/usr/lib/openconnect/hipreport.sh",
"/usr/libexec/openconnect/hipreport.sh", "/usr/libexec/openconnect/hipreport.sh",
#[cfg(all(target_os = "macos", target_arch = "aarch64"))] #[cfg(target_os = "macos")]
"/opt/homebrew/opt/openconnect/libexec/openconnect/hipreport.sh", "/opt/homebrew/opt/openconnect/libexec/openconnect/hipreport.sh",
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
"/usr/local/opt/openconnect/libexec/openconnect/hipreport.sh",
]; ];
fn find_executable(locations: &[&'static str]) -> Option<&'static str> { fn find_executable(locations: &[&str]) -> Option<String> {
for location in locations.iter() { for location in locations.iter() {
let path = Path::new(location); let path = Path::new(location);
if path.is_executable() { if path.is_executable() {
return Some(*location); return Some(location.to_string());
} }
} }
None None
} }
pub fn find_vpnc_script() -> Option<&'static str> { pub fn find_vpnc_script() -> Option<String> {
find_executable(&VPNC_SCRIPT_LOCATIONS) find_executable(&VPNC_SCRIPT_LOCATIONS)
} }
pub fn find_csd_wrapper() -> Option<&'static str> { pub fn find_csd_wrapper() -> Option<String> {
find_executable(&CSD_WRAPPER_LOCATIONS) find_executable(&CSD_WRAPPER_LOCATIONS)
} }
+1 -15
View File
@@ -6,7 +6,6 @@ edition.workspace = true
license = "MIT" license = "MIT"
[dependencies] [dependencies]
common = { path = "../common" }
anyhow.workspace = true anyhow.workspace = true
base64.workspace = true base64.workspace = true
dns-lookup.workspace = true dns-lookup.workspace = true
@@ -15,7 +14,7 @@ reqwest.workspace = true
openssl.workspace = true openssl.workspace = true
version-compare = "0.2" version-compare = "0.2"
pem.workspace = true pem.workspace = true
xmltree.workspace = true roxmltree.workspace = true
serde.workspace = true serde.workspace = true
specta = { workspace = true, features = ["derive"] } specta = { workspace = true, features = ["derive"] }
urlencoding.workspace = true urlencoding.workspace = true
@@ -32,12 +31,7 @@ uzers.workspace = true
serde_urlencoded.workspace = true serde_urlencoded.workspace = true
md5.workspace = true md5.workspace = true
sha256.workspace = true sha256.workspace = true
machine-uid.workspace = true
uuid = { workspace = true, features = ["v5"] }
chrono.workspace = true
humantime.workspace = true
# Optional dependencies for features
tauri = { workspace = true, optional = true } tauri = { workspace = true, optional = true }
clap = { workspace = true, optional = true } clap = { workspace = true, optional = true }
clap-verbosity-flag = { workspace = true, optional = true } clap-verbosity-flag = { workspace = true, optional = true }
@@ -45,14 +39,6 @@ clap-verbosity-flag = { workspace = true, optional = true }
env_logger = { workspace = true, optional = true } env_logger = { workspace = true, optional = true }
log-reload = { version = "0.1", optional = true } log-reload = { version = "0.1", optional = true }
# Dependencies for macOS and Windows only
[target.'cfg(any(target_os="macos", target_os="windows"))'.dependencies]
os_info = { version = "3", default-features = false }
# Dependencies for Linux and other OSes only
[target.'cfg(not(any(target_os="macos", target_os="windows")))'.dependencies]
gtk = "0.18"
[features] [features]
tauri = ["dep:tauri"] tauri = ["dep:tauri"]
clap = ["dep:clap", "dep:clap-verbosity-flag"] clap = ["dep:clap", "dep:clap-verbosity-flag"]
@@ -14,9 +14,6 @@ fn main() {
println!("cargo:rustc-env=GP_SERVICE_BINARY={}", gp_service_binary.display()); println!("cargo:rustc-env=GP_SERVICE_BINARY={}", gp_service_binary.display());
println!("cargo:rustc-env=GP_CLIENT_BINARY={}", gp_client_binary.display()); println!("cargo:rustc-env=GP_CLIENT_BINARY={}", gp_client_binary.display());
println!("cargo:rustc-env=GP_AUTH_BINARY={}", gp_auth_binary.display()); println!("cargo:rustc-env=GP_AUTH_BINARY={}", gp_auth_binary.display());
println!( println!("cargo:rustc-env=GP_GUI_HELPER_BINARY={}", gp_gui_helper_binary.display());
"cargo:rustc-env=GP_GUI_HELPER_BINARY={}",
gp_gui_helper_binary.display()
);
println!("cargo:rustc-env=GP_GUI_BINARY={}", gp_gui_binary.display()); println!("cargo:rustc-env=GP_GUI_BINARY={}", gp_gui_binary.display());
} }
+1 -3
View File
@@ -84,8 +84,6 @@ impl SamlAuthData {
pub fn from_gpcallback(data: &str) -> anyhow::Result<SamlAuthData, AuthDataParseError> { pub fn from_gpcallback(data: &str) -> anyhow::Result<SamlAuthData, AuthDataParseError> {
let auth_data = data.trim_start_matches("globalprotectcallback:"); let auth_data = data.trim_start_matches("globalprotectcallback:");
// Further remove the leading "/" if it exists, because some versions of GP may include it
let auth_data = auth_data.trim_start_matches('/');
if auth_data.starts_with("cas-as") { if auth_data.starts_with("cas-as") {
info!("Got CAS auth data from globalprotectcallback"); info!("Got CAS auth data from globalprotectcallback");
@@ -106,7 +104,7 @@ impl SamlAuthData {
} }
let auth_data = decode_to_string(auth_data).map_err(|e| { let auth_data = decode_to_string(auth_data).map_err(|e| {
warn!("Failed to decode SAML auth data: {}, data: {}", e, data); warn!("Failed to decode SAML auth data: {}", e);
AuthDataParseError::Invalid(anyhow::anyhow!(e)) AuthDataParseError::Invalid(anyhow::anyhow!(e))
})?; })?;
let auth_data = Self::from_html(&auth_data)?; let auth_data = Self::from_html(&auth_data)?;
+1 -1
View File
@@ -1,4 +1,4 @@
use clap::{ValueEnum, builder::PossibleValue}; use clap::{builder::PossibleValue, ValueEnum};
use crate::gp_params::ClientOs; use crate::gp_params::ClientOs;
+13 -12
View File
@@ -2,13 +2,9 @@ use std::collections::HashMap;
use log::{info, warn}; use log::{info, warn};
use reqwest::Client; use reqwest::Client;
use xmltree::Element; use roxmltree::Document;
use crate::{ use crate::{gp_params::GpParams, process::hip_launcher::HipLauncher, utils::normalize_server};
gp_params::GpParams,
process::hip_launcher::HipLauncher,
utils::{normalize_server, xml::ElementExt},
};
struct HipReporter<'a> { struct HipReporter<'a> {
server: String, server: String,
@@ -69,11 +65,13 @@ impl HipReporter<'_> {
let res = self.client.post(&config_url).form(&params).send().await?; let res = self.client.post(&config_url).form(&params).send().await?;
let res_xml = res.error_for_status()?.text().await?; let res_xml = res.error_for_status()?.text().await?;
let root = Element::parse(res_xml.as_bytes())?; let doc = Document::parse(&res_xml)?;
// Get <ip-address> // Get <ip-address>
let ip = root let ip = doc
.descendant_text("ip-address") .descendants()
.find(|n| n.has_tag_name("ip-address"))
.and_then(|n| n.text())
.ok_or_else(|| anyhow::anyhow!("ip-address not found"))?; .ok_or_else(|| anyhow::anyhow!("ip-address not found"))?;
Ok(ip.to_string()) Ok(ip.to_string())
@@ -124,9 +122,12 @@ impl HipReporter<'_> {
} }
fn is_hip_needed(res_xml: &str) -> anyhow::Result<bool> { fn is_hip_needed(res_xml: &str) -> anyhow::Result<bool> {
let root = Element::parse(res_xml.as_bytes())?; let doc = Document::parse(res_xml)?;
let hip_needed = root
.descendant_text("hip-report-needed") let hip_needed = doc
.descendants()
.find(|n| n.has_tag_name("hip-report-needed"))
.and_then(|n| n.text())
.ok_or_else(|| anyhow::anyhow!("hip-report-needed not found"))?; .ok_or_else(|| anyhow::anyhow!("hip-report-needed not found"))?;
Ok(hip_needed == "yes") Ok(hip_needed == "yes")
+29 -210
View File
@@ -1,16 +1,14 @@
use std::{borrow::Cow, collections::HashMap};
use anyhow::bail; use anyhow::bail;
use log::{debug, info, warn}; use log::{info, warn};
use reqwest::Client; use reqwest::Client;
use urlencoding::{decode, encode}; use roxmltree::Document;
use xmltree::Element; use urlencoding::encode;
use crate::{ use crate::{
credential::Credential, credential::Credential,
error::PortalError, error::PortalError,
gp_params::GpParams, gp_params::GpParams,
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt}, utils::{normalize_server, parse_gp_response, remove_url_scheme},
}; };
pub enum GatewayLogin { pub enum GatewayLogin {
@@ -19,30 +17,17 @@ pub enum GatewayLogin {
} }
pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<GatewayLogin> { pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, false).await
}
pub async fn gateway_login_with_extend_lifetime(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, true).await
}
async fn gateway_login_with_options(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
extend_lifetime: bool,
) -> anyhow::Result<GatewayLogin> {
let url = normalize_server(gateway)?; let url = normalize_server(gateway)?;
let gateway = remove_url_scheme(&url); let gateway = remove_url_scheme(&url);
let login_url = format!("{}/ssl-vpn/login.esp", url); let login_url = format!("{}/ssl-vpn/login.esp", url);
let client = Client::try_from(gp_params)?; let client = Client::try_from(gp_params)?;
let params = build_gateway_login_params(&gateway, cred, gp_params, extend_lifetime); let mut params = cred.to_params();
let extra_params = gp_params.to_params();
params.extend(extra_params);
params.insert("server", &gateway);
info!("Perform gateway login, user_agent: {}", gp_params.user_agent()); info!("Perform gateway login, user_agent: {}", gp_params.user_agent());
@@ -56,12 +41,6 @@ async fn gateway_login_with_options(
anyhow::anyhow!("Gateway login error: {}", err.reason) anyhow::anyhow!("Gateway login error: {}", err.reason)
})?; })?;
// It's possible to get an empty response, log the response headers for debugging
if res.trim().is_empty() {
info!("Empty gateway login response headers: {:?}", res);
bail!("Got empty gateway login response");
}
// MFA detected // MFA detected
if res.contains("Challenge") { if res.contains("Challenge") {
let Some((message, input_str)) = parse_mfa(&res) else { let Some((message, input_str)) = parse_mfa(&res) else {
@@ -71,62 +50,28 @@ async fn gateway_login_with_options(
return Ok(GatewayLogin::Mfa(message, input_str)); return Ok(GatewayLogin::Mfa(message, input_str));
} }
debug!("Gateway login response: {}", res); let doc = Document::parse(&res)?;
let root = Element::parse(res.as_bytes())?; let cookie = build_gateway_token(&doc, gp_params.computer())?;
let cookie = build_gateway_token(&root, gp_params.computer())?;
Ok(GatewayLogin::Cookie(cookie)) Ok(GatewayLogin::Cookie(cookie))
} }
fn build_gateway_login_params( fn build_gateway_token(doc: &Document, computer: &str) -> anyhow::Result<String> {
gateway: &str, let args = doc
cred: &Credential, .descendants()
gp_params: &GpParams, .filter(|n| n.has_tag_name("argument"))
extend_lifetime: bool, .map(|n| n.text().unwrap_or("").to_string())
) -> HashMap<String, String> {
let mut params = cred
.to_params()
.into_iter()
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect::<HashMap<_, _>>();
params.extend(
gp_params
.to_params()
.into_iter()
.map(|(key, value)| (key.to_string(), value.to_string())),
);
params.insert("server".to_string(), gateway.to_string());
if extend_lifetime {
params.insert("extend-lifetime".to_string(), "true".to_string());
}
params
}
fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<String> {
let args = element
.descendants("argument")
.iter()
.map(|e| e.get_text().unwrap_or_default())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let mut params = vec![ let params = [
read_required_arg(&args, 1, "authcookie")?, read_args(&args, 1, "authcookie")?,
read_optional_arg(&args, 2, "persistent-cookie")?, read_args(&args, 3, "portal")?,
read_optional_arg(&args, 3, "portal")?, read_args(&args, 4, "user")?,
read_required_arg(&args, 4, "user")?, read_args(&args, 7, "domain")?,
read_optional_arg(&args, 7, "domain")?, read_args(&args, 15, "preferred-ip")?,
read_optional_arg(&args, 15, "preferred-ip")?, ("computer", computer),
read_optional_arg(&args, 18, "preferred-ipv6")?, ];
]
.into_iter()
.flatten()
.collect::<Vec<_>>();
params.push(("computer", computer.to_string()));
let token = params let token = params
.iter() .iter()
@@ -137,43 +82,11 @@ fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<Stri
Ok(token) Ok(token)
} }
fn read_required_arg( fn read_args<'a>(args: &'a [String], index: usize, key: &'a str) -> anyhow::Result<(&'a str, &'a str)> {
args: &[Cow<'_, str>], args
index: usize, .get(index)
key: &'static str, .ok_or_else(|| anyhow::anyhow!("Failed to read {key} from args"))
) -> anyhow::Result<Option<(&'static str, String)>> { .map(|s| (key, s.as_ref()))
let Some(value) = read_arg_value(args, index)? else {
bail!("Failed to read {key} from args");
};
Ok(Some((key, value)))
}
fn read_optional_arg(
args: &[Cow<'_, str>],
index: usize,
key: &'static str,
) -> anyhow::Result<Option<(&'static str, String)>> {
Ok(read_arg_value(args, index)?.map(|value| (key, value)))
}
fn read_arg_value(args: &[Cow<'_, str>], index: usize) -> anyhow::Result<Option<String>> {
Ok(
args
.get(index)
.map(|s| normalize_arg_value(s.as_ref()))
.transpose()
.map_err(|err| anyhow::anyhow!("Failed to decode gateway login argument {index}: {err}"))?
.flatten(),
)
}
fn normalize_arg_value(value: &str) -> anyhow::Result<Option<String>> {
if value.is_empty() || value == "(null)" || value == "-1" {
return Ok(None);
}
Ok(Some(decode(value)?.into_owned()))
} }
fn parse_mfa(res: &str) -> Option<(String, String)> { fn parse_mfa(res: &str) -> Option<(String, String)> {
@@ -204,98 +117,4 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
assert_eq!(message, "MFA message"); assert_eq!(message, "MFA message");
assert_eq!(input_str, "5ef64e83000119ed"); assert_eq!(input_str, "5ef64e83000119ed");
} }
#[test]
fn normal_gateway_login_params_do_not_extend_lifetime() {
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, false);
assert!(!params.contains_key("extend-lifetime"));
}
#[test]
fn extension_gateway_login_params_extend_lifetime() {
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, true);
assert_eq!(params.get("extend-lifetime").map(String::as_str), Some("true"));
}
#[test]
fn gateway_token_keeps_upstream_cookie_fields() {
let res = r#"
<jnlp>
<application-desc>
<argument></argument>
<argument>AUTHCOOKIE</argument>
<argument>PERSISTENTCOOKIE</argument>
<argument>vpn.example.com</argument>
<argument>alice</argument>
<argument>LDAP-auth</argument>
<argument>vsys1</argument>
<argument>%28empty_domain%29</argument>
<argument></argument>
<argument></argument>
<argument></argument>
<argument></argument>
<argument>tunnel</argument>
<argument>-1</argument>
<argument>4100</argument>
<argument>10.0.0.10</argument>
<argument>unused-user-cookie</argument>
<argument>unused-prelogon-cookie</argument>
<argument>2001:db8::10</argument>
</application-desc>
</jnlp>
"#;
let root = Element::parse(res.as_bytes()).unwrap();
let token = build_gateway_token(&root, "metalklesk").unwrap();
assert_eq!(
token,
"authcookie=AUTHCOOKIE&persistent-cookie=PERSISTENTCOOKIE&portal=vpn.example.com&user=alice&domain=%28empty_domain%29&preferred-ip=10.0.0.10&preferred-ipv6=2001%3Adb8%3A%3A10&computer=metalklesk"
);
}
#[test]
fn gateway_token_omits_empty_optional_fields() {
let res = r#"
<jnlp>
<application-desc>
<argument></argument>
<argument>AUTHCOOKIE</argument>
<argument></argument>
<argument>vpn.example.com</argument>
<argument>alice</argument>
<argument>LDAP-auth</argument>
<argument>vsys1</argument>
<argument>-1</argument>
<argument></argument>
<argument></argument>
<argument></argument>
<argument></argument>
<argument>tunnel</argument>
<argument>-1</argument>
<argument>4100</argument>
<argument></argument>
<argument>unused-user-cookie</argument>
<argument>unused-prelogon-cookie</argument>
<argument>(null)</argument>
</application-desc>
</jnlp>
"#;
let root = Element::parse(res.as_bytes()).unwrap();
let token = build_gateway_token(&root, "metalklesk").unwrap();
assert_eq!(
token,
"authcookie=AUTHCOOKIE&portal=vpn.example.com&user=alice&computer=metalklesk"
);
}
} }
+1 -3
View File
@@ -1,11 +1,9 @@
pub mod hip;
mod login; mod login;
mod parse_gateways; mod parse_gateways;
pub mod session; pub mod hip;
pub use login::*; pub use login::*;
pub(crate) use parse_gateways::*; pub(crate) use parse_gateways::*;
pub use session::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use specta::Type; use specta::Type;
+36 -36
View File
@@ -1,64 +1,64 @@
use log::info; use log::info;
use xmltree::Element; use roxmltree::Node;
use crate::utils::xml::ElementExt; use crate::utils::xml::NodeExt;
use super::{Gateway, PriorityRule}; use super::{Gateway, PriorityRule};
pub(crate) fn parse_gateways(element: &Element, prefer_internal: bool) -> Option<Vec<Gateway>> { pub(crate) fn parse_gateways(node: &Node, prefer_internal: bool) -> Option<Vec<Gateway>> {
let node_gateways = element.descendant("gateways")?; let node_gateways = node.find_descendant("gateways")?;
let internal_gateway_list = if prefer_internal { let internal_gateway_list = if prefer_internal {
info!("Try to parse the internal gateways..."); info!("Try to parse the internal gateways...");
node_gateways.descendant("internal").and_then(|n| n.child("list")) node_gateways.find_descendant("internal").and_then(|n| n.find_child("list"))
} else { } else {
None None
}; };
let gateway_list = internal_gateway_list.or_else(|| { let gateway_list = internal_gateway_list.or_else(|| {
info!("Try to parse the external gateways..."); info!("Try to parse the external gateways...");
node_gateways.descendant("external").and_then(|n| n.child("list")) node_gateways.find_descendant("external").and_then(|n| n.find_child("list"))
})?; })?;
let gateways = gateway_list let gateways = gateway_list
.children("entry") .children()
.iter() .filter_map(|gateway_item| {
.map(|gateway_item| { if !gateway_item.has_tag_name("entry") {
let address = gateway_item.attr("name").map(|s| s.to_string()).unwrap_or_default(); return None;
let name = gateway_item.child_text("description").unwrap_or_default(); }
let priority = parse_priority(gateway_item); let address = gateway_item.attribute("name").unwrap_or_default().to_string();
let name = gateway_item.child_text("description").unwrap_or_default().to_string();
let priority = gateway_item
.child_text("priority")
.and_then(|s| s.parse().ok())
.unwrap_or(u32::MAX);
let priority_rules = gateway_item let priority_rules = gateway_item
.child("priority-rule") .find_child("priority-rule")
.map(|n| parse_priority_rules(n)) .map(|n| {
n.children()
.filter_map(|n| {
if !n.has_tag_name("entry") {
return None;
}
let name = n.attribute("name").unwrap_or_default().to_string();
let priority: u32 = n
.child_text("priority")
.and_then(|s| s.parse().ok())
.unwrap_or(u32::MAX);
Some(PriorityRule { name, priority })
})
.collect()
})
.unwrap_or_default(); .unwrap_or_default();
Gateway { Some(Gateway {
name, name,
address, address,
priority, priority,
priority_rules, priority_rules,
} })
}) })
.collect(); .collect();
Some(gateways) Some(gateways)
} }
fn parse_priority_rules(element: &Element) -> Vec<PriorityRule> {
element
.children("entry")
.iter()
.map(|n| {
let name = n.attr("name").map(|s| s.to_string()).unwrap_or_default();
let priority: u32 = parse_priority(n);
PriorityRule { name, priority }
})
.collect()
}
fn parse_priority(element: &Element) -> u32 {
element
.child_text("priority")
.and_then(|s| s.parse().ok())
.unwrap_or(u32::MAX)
}
-246
View File
@@ -1,246 +0,0 @@
use std::{
collections::HashMap,
time::{SystemTime, UNIX_EPOCH},
};
use anyhow::bail;
use log::{info, warn};
use reqwest::Client;
use xmltree::Element;
use crate::{
credential::Credential,
gateway::login::{GatewayLogin, gateway_login_with_extend_lifetime},
gp_params::GpParams,
session::SessionRequestArgs,
utils::{normalize_server, parse_gp_response, xml::ElementExt},
};
const EXTEND_SESSION_MESSAGE: &str = "User Session Extension";
const EXTEND_SESSION_COMMENT: &str = "User extends the login lifetime";
#[derive(Clone)]
pub struct SessionExtensionAuth {
credential: Credential,
gp_params: GpParams,
}
impl SessionExtensionAuth {
pub fn new(credential: Credential, gp_params: GpParams) -> Self {
Self { credential, gp_params }
}
}
impl std::fmt::Debug for SessionExtensionAuth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SessionExtensionAuth")
.field("username", &self.credential.username())
.field("gp_params", &"<redacted>")
.finish()
}
}
#[derive(Debug, Clone)]
pub struct SessionContext {
server: String,
portal: String,
session_args: SessionRequestArgs,
extension_auth: Option<SessionExtensionAuth>,
}
impl SessionContext {
pub fn new(server: String, portal: String, session_args: SessionRequestArgs) -> Self {
Self {
server,
portal,
session_args,
extension_auth: None,
}
}
pub fn with_extension_auth(mut self, extension_auth: SessionExtensionAuth) -> Self {
self.extension_auth = Some(extension_auth);
self
}
pub fn server(&self) -> &str {
&self.server
}
pub fn portal(&self) -> &str {
&self.portal
}
pub fn session_args(&self) -> &SessionRequestArgs {
&self.session_args
}
fn extension_auth(&self) -> Option<&SessionExtensionAuth> {
self.extension_auth.as_ref()
}
}
pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<()> {
extend_session_lifetime(ctx).await?;
let base_url = normalize_server(ctx.server())?;
let client = build_session_client(ctx.session_args())?;
let form = build_extend_session_form(ctx)?;
let url = format!("{base_url}/ssl-vpn/agentmessage.esp");
info!("Sending extend-session request");
let response = client.post(&url).form(&form).send().await?;
let response = parse_gp_response(response).await?;
let root = Element::parse(response.as_bytes())?;
let status = parse_extend_session_status(&root, &response)?;
info!("Extend-session gateway response status: {}", status);
match status.as_str() {
"success" => Ok(()),
status => bail!("Extend session rejected: {status}"),
}
}
async fn extend_session_lifetime(ctx: &SessionContext) -> anyhow::Result<()> {
let auth = ctx
.extension_auth()
.ok_or_else(|| anyhow::anyhow!("Session extension requires retained gateway auth state"))?;
let login = gateway_login_with_extend_lifetime(ctx.server(), &auth.credential, &auth.gp_params).await?;
validate_extension_login(login)
}
fn validate_extension_login(login: GatewayLogin) -> anyhow::Result<()> {
match login {
GatewayLogin::Cookie(_) => Ok(()),
GatewayLogin::Mfa(_, _) => bail!("Session extension requires an interactive gateway challenge"),
}
}
fn build_session_client(args: &SessionRequestArgs) -> anyhow::Result<Client> {
let mut builder = GpParams::builder();
builder.user_agent(args.user_agent().as_deref().unwrap_or_default());
builder.client_os(args.os().unwrap_or_default());
builder.os_version(args.os_version());
builder.client_version(args.client_version());
builder.certificate(args.certificate());
builder.sslkey(args.sslkey());
builder.key_password(args.key_password());
Client::try_from(&builder.build())
}
fn parse_cookie_form(args: &SessionRequestArgs) -> anyhow::Result<HashMap<String, String>> {
Ok(serde_urlencoded::from_str(args.cookie())?)
}
fn build_extend_session_form(ctx: &SessionContext) -> anyhow::Result<HashMap<String, String>> {
let mut form = parse_cookie_form(ctx.session_args())?;
form.insert("portal".to_string(), ctx.portal().to_string());
form.insert("timestamp".to_string(), unix_timestamp().to_string());
form.insert("message".to_string(), EXTEND_SESSION_MESSAGE.to_string());
form.insert("comment".to_string(), EXTEND_SESSION_COMMENT.to_string());
Ok(form)
}
fn parse_extend_session_status(root: &Element, response: &str) -> anyhow::Result<String> {
match root.attr("status") {
Some(status) => Ok(status.to_string()),
None => {
warn!("Malformed extend-session response body: {}", response.trim());
bail!("Malformed extend session response")
}
}
}
fn unix_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
#[cfg(test)]
mod tests {
use crate::{gp_params::ClientOs, session::SessionRequestArgs};
use super::*;
fn build_session_args() -> SessionRequestArgs {
SessionRequestArgs::new("authcookie=AUTH&portal=vpn.example.com&user=alice&preferred-ip=10.0.0.10".to_string())
.with_os(Some(ClientOs::Mac))
.with_os_version(Some("macOS 15.0".to_string()))
.with_client_version(Some("6.3.1-12".to_string()))
.with_disable_ipv6(true)
}
#[test]
fn active_session_context_preserves_connect_args_for_extension() {
let session_args = build_session_args();
let ctx = SessionContext::new(
"vpn.example.com".to_string(),
"portal.example.com".to_string(),
session_args,
);
let form = parse_cookie_form(ctx.session_args()).unwrap();
assert_eq!(form.get("authcookie").map(String::as_str), Some("AUTH"));
assert_eq!(form.get("portal").map(String::as_str), Some("vpn.example.com"));
assert_eq!(form.get("user").map(String::as_str), Some("alice"));
assert_eq!(form.get("preferred-ip").map(String::as_str), Some("10.0.0.10"));
}
#[test]
fn builds_extend_session_form() {
let session_args = build_session_args();
let ctx = SessionContext::new(
"vpn.example.com".to_string(),
"portal.example.com".to_string(),
session_args,
);
let form = build_extend_session_form(&ctx).unwrap();
assert_eq!(form.get("authcookie").map(String::as_str), Some("AUTH"));
assert_eq!(form.get("portal").map(String::as_str), Some("portal.example.com"));
assert_eq!(form.get("message").map(String::as_str), Some(EXTEND_SESSION_MESSAGE));
assert_eq!(form.get("comment").map(String::as_str), Some(EXTEND_SESSION_COMMENT));
assert!(form.contains_key("timestamp"));
}
#[test]
fn parses_extend_session_status_attribute() {
let root = Element::parse(r#"<response status="success"></response>"#.as_bytes()).unwrap();
assert_eq!(
parse_extend_session_status(&root, r#"<response status="success"></response>"#).unwrap(),
"success"
);
}
#[test]
fn rejects_extend_session_response_without_status() {
let root = Element::parse("<response><result>ok</result></response>".as_bytes()).unwrap();
assert_eq!(
parse_extend_session_status(&root, "<response><result>ok</result></response>")
.unwrap_err()
.to_string(),
"Malformed extend session response"
);
}
#[test]
fn rejects_extension_login_mfa_challenge() {
assert_eq!(
validate_extension_login(GatewayLogin::Mfa("MFA required".to_string(), "input".to_string()))
.unwrap_err()
.to_string(),
"Session extension requires an interactive gateway challenge"
);
}
}
+1 -2
View File
@@ -1,12 +1,11 @@
use std::collections::HashMap; use std::collections::HashMap;
use common::constants::GP_USER_AGENT;
use log::info; use log::info;
use reqwest::Client; use reqwest::Client;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use specta::Type; use specta::Type;
use crate::utils::request::create_identity; use crate::{utils::request::create_identity, GP_USER_AGENT};
#[derive(Debug, Serialize, Deserialize, Clone, Type, Default)] #[derive(Debug, Serialize, Deserialize, Clone, Type, Default)]
pub enum ClientOs { pub enum ClientOs {
+26 -1
View File
@@ -6,7 +6,6 @@ pub mod gp_params;
pub mod portal; pub mod portal;
pub mod process; pub mod process;
pub mod service; pub mod service;
pub mod session;
pub mod utils; pub mod utils;
#[cfg(feature = "logger")] #[cfg(feature = "logger")]
@@ -17,3 +16,29 @@ pub mod clap;
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
pub const GP_API_KEY: &[u8; 32] = &[0; 32]; pub const GP_API_KEY: &[u8; 32] = &[0; 32];
pub const GP_USER_AGENT: &str = "PAN GlobalProtect";
pub const GP_SERVICE_LOCK_FILE: &str = "/var/run/gpservice.lock";
pub const GP_CALLBACK_PORT_FILENAME: &str = "gpcallback.port";
#[cfg(not(debug_assertions))]
pub const GP_CLIENT_BINARY: &str = "/usr/bin/gpclient";
#[cfg(not(debug_assertions))]
pub const GP_SERVICE_BINARY: &str = "/usr/bin/gpservice";
#[cfg(not(debug_assertions))]
pub const GP_GUI_BINARY: &str = "/usr/bin/gpgui";
#[cfg(not(debug_assertions))]
pub const GP_GUI_HELPER_BINARY: &str = "/usr/bin/gpgui-helper";
#[cfg(not(debug_assertions))]
pub(crate) const GP_AUTH_BINARY: &str = "/usr/bin/gpauth";
#[cfg(debug_assertions)]
pub const GP_CLIENT_BINARY: &str = env!("GP_CLIENT_BINARY");
#[cfg(debug_assertions)]
pub const GP_SERVICE_BINARY: &str = env!("GP_SERVICE_BINARY");
#[cfg(debug_assertions)]
pub const GP_GUI_BINARY: &str = env!("GP_GUI_BINARY");
#[cfg(debug_assertions)]
pub const GP_GUI_HELPER_BINARY: &str = env!("GP_GUI_HELPER_BINARY");
#[cfg(debug_assertions)]
pub(crate) const GP_AUTH_BINARY: &str = env!("GP_AUTH_BINARY");
+1 -1
View File
@@ -2,7 +2,7 @@ use std::sync::OnceLock;
use anyhow::bail; use anyhow::bail;
use env_logger::Logger; use env_logger::Logger;
use log::{Level, warn}; use log::{warn, Level};
use log_reload::{ReloadHandle, ReloadLog}; use log_reload::{ReloadHandle, ReloadLog};
static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<Logger>>> = OnceLock::new(); static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<Logger>>> = OnceLock::new();
+11 -78
View File
@@ -1,17 +1,17 @@
use anyhow::bail; use anyhow::bail;
use dns_lookup::lookup_addr; use dns_lookup::lookup_addr;
use log::{debug, info, warn}; use log::{info, warn};
use reqwest::{Client, StatusCode}; use reqwest::{Client, StatusCode};
use roxmltree::{Document, Node};
use serde::Serialize; use serde::Serialize;
use specta::Type; use specta::Type;
use xmltree::Element;
use crate::{ use crate::{
credential::{AuthCookieCredential, Credential}, credential::{AuthCookieCredential, Credential},
error::PortalError, error::PortalError,
gateway::{Gateway, parse_gateways}, gateway::{parse_gateways, Gateway},
gp_params::GpParams, gp_params::GpParams,
utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::ElementExt}, utils::{normalize_server, parse_gp_response, remove_url_scheme, xml::NodeExt},
}; };
#[derive(Debug, Serialize, Type)] #[derive(Debug, Serialize, Type)]
@@ -29,14 +29,6 @@ pub struct PortalConfig {
* - Some(true): Internal host detection is supported and the user is connected to the internal network * - Some(true): Internal host detection is supported and the user is connected to the internal network
*/ */
internal_host_detection: Option<bool>, internal_host_detection: Option<bool>,
/**
* The version returned by the portal config, if any
*/
version: Option<String>,
/**
* Whether the portal policy allows extending the gateway session.
*/
allow_extend_session: Option<bool>,
} }
impl PortalConfig { impl PortalConfig {
@@ -60,14 +52,6 @@ impl PortalConfig {
self.internal_host_detection self.internal_host_detection
} }
pub fn version(&self) -> Option<&str> {
self.version.as_deref()
}
pub fn allow_extend_session(&self) -> Option<bool> {
self.allow_extend_session
}
/// In-place sort the gateways by region /// In-place sort the gateways by region
pub fn sort_gateways(&mut self, region: &str) { pub fn sort_gateways(&mut self, region: &str) {
let preferred_gateway = self.find_preferred_gateway(region); let preferred_gateway = self.find_preferred_gateway(region);
@@ -149,12 +133,12 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
bail!(PortalError::ConfigError("Empty portal config response".to_string())) bail!(PortalError::ConfigError("Empty portal config response".to_string()))
} }
debug!("Portal config response: {}", res_xml); let doc = Document::parse(&res_xml).map_err(|e| PortalError::ConfigError(e.to_string()))?;
let root = Element::parse(res_xml.as_bytes()).map_err(|e| PortalError::ConfigError(e.to_string()))?; let root = doc.root();
let mut ihd_enabled = false; let mut ihd_enabled = false;
let mut prefer_internal = false; let mut prefer_internal = false;
if let Some(ihd_node) = root.descendant("internal-host-detection") { if let Some(ihd_node) = root.find_descendant("internal-host-detection") {
ihd_enabled = true; ihd_enabled = true;
prefer_internal = internal_host_detect(&ihd_node) prefer_internal = internal_host_detect(&ihd_node)
} }
@@ -174,35 +158,21 @@ pub async fn retrieve_config(portal: &str, cred: &Credential, gp_params: &GpPara
gateways.push(Gateway::new(server.to_string(), server.to_string())); gateways.push(Gateway::new(server.to_string(), server.to_string()));
} }
let version = root.descendant_text("version").map(|s| s.to_string());
info!("Detected portal version: {:?}", version);
let allow_extend_session = parse_allow_extend_session(&root);
Ok(PortalConfig { Ok(PortalConfig {
portal: server.to_string(), portal: server.to_string(),
auth_cookie: AuthCookieCredential::new(cred.username(), &user_auth_cookie, &prelogon_user_auth_cookie), auth_cookie: AuthCookieCredential::new(cred.username(), user_auth_cookie, prelogon_user_auth_cookie),
config_cred: cred.clone(), config_cred: cred.clone(),
gateways, gateways,
config_digest: config_digest.map(|s| s.to_string()), config_digest: config_digest.map(|s| s.to_string()),
internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None }, internal_host_detection: if ihd_enabled { Some(prefer_internal) } else { None },
version,
allow_extend_session,
}) })
} }
fn parse_allow_extend_session(root: &Element) -> Option<bool> {
match root.descendant_text("allow-extend-session")?.trim() {
"yes" => Some(true),
"no" => Some(false),
_ => None,
}
}
// Perform DNS lookup and compare the result with the expected hostname // Perform DNS lookup and compare the result with the expected hostname
fn internal_host_detect(element: &Element) -> bool { fn internal_host_detect(node: &Node) -> bool {
let ip_info = [ let ip_info = [
(element.child_text("ip-address"), element.child_text("host")), (node.child_text("ip-address"), node.child_text("host")),
(element.child_text("ipv6-address"), element.child_text("ipv6-host")), (node.child_text("ipv6-address"), node.child_text("ipv6-host")),
]; ];
info!("Found internal-host-detection, performing DNS lookup"); info!("Found internal-host-detection, performing DNS lookup");
@@ -231,40 +201,3 @@ fn internal_host_detect(element: &Element) -> bool {
false false
} }
#[cfg(test)]
mod tests {
use super::*;
fn parse_xml(xml: &str) -> Element {
Element::parse(xml.as_bytes()).unwrap()
}
#[test]
fn parses_allow_extend_session_yes() {
let root = parse_xml("<response><allow-extend-session>yes</allow-extend-session></response>");
assert_eq!(parse_allow_extend_session(&root), Some(true));
}
#[test]
fn parses_allow_extend_session_no() {
let root = parse_xml("<response><allow-extend-session>no</allow-extend-session></response>");
assert_eq!(parse_allow_extend_session(&root), Some(false));
}
#[test]
fn leaves_absent_allow_extend_session_unknown() {
let root = parse_xml("<response></response>");
assert_eq!(parse_allow_extend_session(&root), None);
}
#[test]
fn ignores_non_official_allow_extend_session_values() {
let root = parse_xml("<response><allow-extend-session>true</allow-extend-session></response>");
assert_eq!(parse_allow_extend_session(&root), None);
}
}
+30 -23
View File
@@ -1,14 +1,14 @@
use anyhow::{anyhow, bail}; use anyhow::{anyhow, bail};
use log::{debug, info, warn}; use log::{info, warn};
use reqwest::{Client, StatusCode}; use reqwest::{Client, StatusCode};
use roxmltree::Document;
use serde::Serialize; use serde::Serialize;
use specta::Type; use specta::Type;
use xmltree::Element;
use crate::{ use crate::{
error::PortalError, error::PortalError,
gp_params::GpParams, gp_params::GpParams,
utils::{base64, normalize_server, parse_gp_response, xml::ElementExt}, utils::{base64, normalize_server, parse_gp_response, xml::NodeExt},
}; };
const REQUIRED_PARAMS: [&str; 8] = [ const REQUIRED_PARAMS: [&str; 8] = [
@@ -134,8 +134,6 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result<Prel
Err(anyhow!(PortalError::PreloginError(err.reason))) Err(anyhow!(PortalError::PreloginError(err.reason)))
})?; })?;
debug!("Prelogin response XML: {}", res_xml);
let prelogin = parse_res_xml(&res_xml, is_gateway).map_err(|err| { let prelogin = parse_res_xml(&res_xml, is_gateway).map_err(|err| {
warn!("Parse response error, response: {}", res_xml); warn!("Parse response error, response: {}", res_xml);
PortalError::PreloginError(err.to_string()) PortalError::PreloginError(err.to_string())
@@ -145,30 +143,32 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result<Prel
} }
fn parse_res_xml(res_xml: &str, is_gateway: bool) -> anyhow::Result<Prelogin> { fn parse_res_xml(res_xml: &str, is_gateway: bool) -> anyhow::Result<Prelogin> {
let root = Element::parse(res_xml.as_bytes())?; let doc = Document::parse(res_xml)?;
let root = doc.root();
let status = root let status = root
.descendant_text("status") .descendant_text("status")
.ok_or_else(|| anyhow::anyhow!("Prelogin response does not contain status element"))?; .ok_or_else(|| anyhow::anyhow!("Prelogin response does not contain status element"))?;
// Check the status of the prelogin response // Check the status of the prelogin response
if status.to_uppercase() != "SUCCESS" { if status.to_uppercase() != "SUCCESS" {
let msg = root let msg = root.descendant_text("msg").unwrap_or("Unknown error");
.descendant_text("msg")
.unwrap_or_else(|| String::from("Unknown error"));
bail!("{}", msg) bail!("{}", msg)
} }
let region = root.descendant_text("region").unwrap_or_else(|| { let region = root
info!("Prelogin response does not contain region element"); .descendant_text("region")
String::from("Unknown") .unwrap_or_else(|| {
}); info!("Prelogin response does not contain region element");
"Unknown"
})
.to_string();
let saml_method = root.descendant_text("saml-auth-method"); let saml_method = root.descendant_text("saml-auth-method");
let saml_request = root.descendant_text("saml-request"); let saml_request = root.descendant_text("saml-request");
let saml_default_browser = root.descendant_text("saml-default-browser"); let saml_default_browser = root.descendant_text("saml-default-browser");
// Check if the prelogin response is SAML // Check if the prelogin response is SAML
if saml_method.is_some() && saml_request.is_some() { if saml_method.is_some() && saml_request.is_some() {
let saml_request = base64::decode_to_string(&saml_request.unwrap())?; let saml_request = base64::decode_to_string(saml_request.unwrap())?;
let support_default_browser = saml_default_browser.map(|s| s.to_lowercase() == "yes").unwrap_or(false); let support_default_browser = saml_default_browser.map(|s| s.to_lowercase() == "yes").unwrap_or(false);
let saml_prelogin = SamlPrelogin { let saml_prelogin = SamlPrelogin {
@@ -181,18 +181,25 @@ fn parse_res_xml(res_xml: &str, is_gateway: bool) -> anyhow::Result<Prelogin> {
return Ok(Prelogin::Saml(saml_prelogin)); return Ok(Prelogin::Saml(saml_prelogin));
} }
let label_username = root.descendant_text("username-label").unwrap_or_else(|| { let label_username = root
info!("Username label has no value, using default"); .descendant_text("username-label")
String::from("Username") .unwrap_or_else(|| {
}); info!("Username label has no value, using default");
let label_password = root.descendant_text("password-label").unwrap_or_else(|| { "Username"
info!("Password label has no value, using default"); })
String::from("Password") .to_string();
}); let label_password = root
.descendant_text("password-label")
.unwrap_or_else(|| {
info!("Password label has no value, using default");
"Password"
})
.to_string();
let auth_message = root let auth_message = root
.descendant_text("authentication-message") .descendant_text("authentication-message")
.unwrap_or_else(|| String::from("Please enter the login credentials")); .unwrap_or("Please enter the login credentials")
.to_string();
let standard_prelogin = StandardPrelogin { let standard_prelogin = StandardPrelogin {
region, region,
is_gateway, is_gateway,
+8 -21
View File
@@ -1,16 +1,14 @@
use std::process::Stdio; use std::process::Stdio;
use anyhow::bail; use anyhow::bail;
use common::constants::GP_AUTH_BINARY;
use tokio::process::Command; use tokio::process::Command;
use crate::{auth::SamlAuthResult, credential::Credential}; use crate::{auth::SamlAuthResult, credential::Credential, GP_AUTH_BINARY};
use super::command_traits::CommandExt; use super::command_traits::CommandExt;
pub struct SamlAuthLauncher<'a> { pub struct SamlAuthLauncher<'a> {
server: &'a str, server: &'a str,
auth_executable: Option<&'a str>,
gateway: bool, gateway: bool,
saml_request: Option<&'a str>, saml_request: Option<&'a str>,
user_agent: Option<&'a str>, user_agent: Option<&'a str>,
@@ -32,7 +30,6 @@ impl<'a> SamlAuthLauncher<'a> {
pub fn new(server: &'a str) -> Self { pub fn new(server: &'a str) -> Self {
Self { Self {
server, server,
auth_executable: None,
gateway: false, gateway: false,
saml_request: None, saml_request: None,
user_agent: None, user_agent: None,
@@ -51,11 +48,6 @@ impl<'a> SamlAuthLauncher<'a> {
} }
} }
pub fn auth_executable(mut self, auth_executable: Option<&'a str>) -> Self {
self.auth_executable = auth_executable;
self
}
pub fn gateway(mut self, gateway: bool) -> Self { pub fn gateway(mut self, gateway: bool) -> Self {
self.gateway = gateway; self.gateway = gateway;
self self
@@ -121,8 +113,7 @@ impl<'a> SamlAuthLauncher<'a> {
/// Launch the authenticator binary as the current user or SUDO_USER if available. /// Launch the authenticator binary as the current user or SUDO_USER if available.
pub async fn launch(self) -> anyhow::Result<Credential> { pub async fn launch(self) -> anyhow::Result<Credential> {
let program = self.auth_executable.unwrap_or(GP_AUTH_BINARY); let mut auth_cmd = Command::new(GP_AUTH_BINARY);
let mut auth_cmd = Command::new(program);
auth_cmd.arg(self.server); auth_cmd.arg(self.server);
if self.gateway { if self.gateway {
@@ -177,16 +168,12 @@ impl<'a> SamlAuthLauncher<'a> {
} }
let mut non_root_cmd = auth_cmd.into_non_root()?; let mut non_root_cmd = auth_cmd.into_non_root()?;
let child = non_root_cmd.kill_on_drop(true).stdout(Stdio::piped()).spawn(); let output = non_root_cmd
.kill_on_drop(true)
let child = match child { .stdout(Stdio::piped())
Ok(child) => child, .spawn()?
Err(err) => { .wait_with_output()
bail!("Failed to spawn {}: {}", program, err); .await?;
}
};
let output = child.wait_with_output().await?;
let Ok(auth_result) = serde_json::from_slice::<SamlAuthResult>(&output.stdout) else { let Ok(auth_result) = serde_json::from_slice::<SamlAuthResult>(&output.stdout) else {
bail!("Failed to parse auth data") bail!("Failed to parse auth data")
+4 -12
View File
@@ -11,18 +11,10 @@ pub trait CommandExt {
impl CommandExt for Command { impl CommandExt for Command {
fn new_pkexec<S: AsRef<OsStr>>(program: S) -> Command { fn new_pkexec<S: AsRef<OsStr>>(program: S) -> Command {
#[cfg(target_os = "macos")] let mut cmd = Command::new("pkexec");
{ cmd.arg("--user").arg("root").arg(program);
let mut cmd = Command::new("sudo");
cmd.arg(program); cmd
cmd
}
#[cfg(not(target_os = "macos"))]
{
let mut cmd = Command::new("pkexec");
cmd.arg("--user").arg("root").arg(program);
cmd
}
} }
fn into_non_root(mut self) -> anyhow::Result<Command> { fn into_non_root(mut self) -> anyhow::Result<Command> {
@@ -1,11 +1,10 @@
use std::{collections::HashMap, path::PathBuf, process::Stdio}; use std::{collections::HashMap, path::PathBuf, process::Stdio};
use anyhow::bail; use anyhow::bail;
use common::constants::GP_GUI_HELPER_BINARY;
use log::info; use log::info;
use tokio::{io::AsyncWriteExt, process::Command}; use tokio::{io::AsyncWriteExt, process::Command};
use crate::{process::command_traits::CommandExt, utils}; use crate::{process::command_traits::CommandExt, utils, GP_GUI_HELPER_BINARY};
pub struct GuiHelperLauncher<'a> { pub struct GuiHelperLauncher<'a> {
program: PathBuf, program: PathBuf,
@@ -50,12 +49,7 @@ impl<'a> GuiHelperLauncher<'a> {
info!("Launching gpgui-helper"); info!("Launching gpgui-helper");
let mut non_root_cmd = cmd.into_non_root()?; let mut non_root_cmd = cmd.into_non_root()?;
let child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn(); let mut child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn()?;
let mut child = match child {
Ok(child) => child,
Err(err) => bail!("Failed to spawn {}: {}", self.program.display(), err),
};
let Some(mut stdin) = child.stdin.take() else { let Some(mut stdin) = child.stdin.take() else {
bail!("Failed to open stdin"); bail!("Failed to open stdin");
}; };
+2 -8
View File
@@ -5,11 +5,10 @@ use std::{
}; };
use anyhow::bail; use anyhow::bail;
use common::constants::GP_GUI_BINARY;
use log::info; use log::info;
use tokio::{io::AsyncWriteExt, process::Command}; use tokio::{io::AsyncWriteExt, process::Command};
use crate::{process::gui_helper_launcher::GuiHelperLauncher, utils::base64}; use crate::{process::gui_helper_launcher::GuiHelperLauncher, utils::base64, GP_GUI_BINARY};
use super::command_traits::CommandExt; use super::command_traits::CommandExt;
@@ -69,12 +68,7 @@ impl<'a> GuiLauncher<'a> {
info!("Launching gpgui"); info!("Launching gpgui");
let mut non_root_cmd = cmd.into_non_root()?; let mut non_root_cmd = cmd.into_non_root()?;
let child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn(); let mut child = non_root_cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn()?;
let mut child = match child {
Ok(child) => child,
Err(err) => bail!("Failed to spawn {}: {}", self.program.display(), err),
};
let Some(mut stdin) = child.stdin.take() else { let Some(mut stdin) = child.stdin.take() else {
bail!("Failed to open stdin"); bail!("Failed to open stdin");
}; };
+6 -8
View File
@@ -72,14 +72,12 @@ impl<'a> HipLauncher<'a> {
cmd.env("APP_VERSION", client_version); cmd.env("APP_VERSION", client_version);
} }
let child = cmd.kill_on_drop(true).stdout(Stdio::piped()).spawn(); let output = cmd
.kill_on_drop(true)
let child = match child { .stdout(Stdio::piped())
Ok(child) => child, .spawn()?
Err(err) => bail!("Failed to spawn {}: {}", self.program, err), .wait_with_output()
}; .await?;
let output = child.wait_with_output().await?;
if let Some(exit_status) = output.status.code() { if let Some(exit_status) = output.status.code() {
if exit_status != 0 { if exit_status != 0 {
+4 -3
View File
@@ -4,9 +4,10 @@ use std::{
process::{ExitStatus, Stdio}, process::{ExitStatus, Stdio},
}; };
use common::constants::GP_SERVICE_BINARY;
use tokio::process::Command; use tokio::process::Command;
use crate::GP_SERVICE_BINARY;
use super::command_traits::CommandExt; use super::command_traits::CommandExt;
pub struct ServiceLauncher<'a> { pub struct ServiceLauncher<'a> {
@@ -14,7 +15,7 @@ pub struct ServiceLauncher<'a> {
minimized: bool, minimized: bool,
env_file: Option<String>, env_file: Option<String>,
log_file: Option<String>, log_file: Option<String>,
verbose: Option<&'a str>, verbose: Option<&'a str>
} }
impl Default for ServiceLauncher<'_> { impl Default for ServiceLauncher<'_> {
@@ -30,7 +31,7 @@ impl<'a> ServiceLauncher<'a> {
minimized: false, minimized: false,
env_file: None, env_file: None,
log_file: None, log_file: None,
verbose: None, verbose: None
} }
} }
+1 -2
View File
@@ -1,11 +1,10 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::service::{vpn_env::VpnEnv, vpn_state::VpnState}; use super::vpn_state::VpnState;
/// Events that can be emitted by the service /// Events that can be emitted by the service
#[derive(Debug, Serialize, Deserialize, Clone)] #[derive(Debug, Serialize, Deserialize, Clone)]
pub enum WsEvent { pub enum WsEvent {
VpnEnv(VpnEnv),
VpnState(VpnState), VpnState(VpnState),
ActiveGui, ActiveGui,
ResumeConnection, ResumeConnection,
-1
View File
@@ -1,4 +1,3 @@
pub mod event; pub mod event;
pub mod request; pub mod request;
pub mod vpn_env;
pub mod vpn_state; pub mod vpn_state;
+2 -105
View File
@@ -27,33 +27,21 @@ impl LaunchGuiRequest {
} }
} }
#[derive(Debug, Deserialize, Serialize, Type, Clone)] #[derive(Debug, Deserialize, Serialize, Type)]
pub struct ConnectArgs { pub struct ConnectArgs {
cookie: String, cookie: String,
vpnc_script: Option<String>, vpnc_script: Option<String>,
user_agent: Option<String>, user_agent: Option<String>,
os: Option<ClientOs>, os: Option<ClientOs>,
os_version: Option<String>,
client_version: Option<String>,
certificate: Option<String>, certificate: Option<String>,
sslkey: Option<String>, sslkey: Option<String>,
key_password: Option<String>, key_password: Option<String>,
hip: bool,
csd_uid: u32, csd_uid: u32,
csd_wrapper: Option<String>, csd_wrapper: Option<String>,
reconnect_timeout: u32, reconnect_timeout: u32,
mtu: u32, mtu: u32,
disable_ipv6: bool, disable_ipv6: bool,
no_dtls: bool, no_dtls: bool,
local_hostname: Option<String>,
force_dpd: u32,
no_xmlpost: bool,
#[serde(rename = "allowExtendSession")]
allow_extend_session: bool,
} }
impl ConnectArgs { impl ConnectArgs {
@@ -63,22 +51,15 @@ impl ConnectArgs {
vpnc_script: None, vpnc_script: None,
user_agent: None, user_agent: None,
os: None, os: None,
os_version: None,
client_version: None,
certificate: None, certificate: None,
sslkey: None, sslkey: None,
key_password: None, key_password: None,
hip: false,
csd_uid: 0, csd_uid: 0,
csd_wrapper: None, csd_wrapper: None,
reconnect_timeout: 300, reconnect_timeout: 300,
mtu: 0, mtu: 0,
disable_ipv6: false, disable_ipv6: false,
no_dtls: false, no_dtls: false,
local_hostname: None,
force_dpd: 0,
no_xmlpost: false,
allow_extend_session: false,
} }
} }
@@ -98,18 +79,6 @@ impl ConnectArgs {
self.os.as_ref().map(|os| os.to_openconnect_os().to_string()) self.os.as_ref().map(|os| os.to_openconnect_os().to_string())
} }
pub fn os(&self) -> Option<ClientOs> {
self.os.clone()
}
pub fn os_version(&self) -> Option<String> {
self.os_version.clone()
}
pub fn client_version(&self) -> Option<String> {
self.client_version.clone()
}
pub fn certificate(&self) -> Option<String> { pub fn certificate(&self) -> Option<String> {
self.certificate.clone() self.certificate.clone()
} }
@@ -122,10 +91,6 @@ impl ConnectArgs {
self.key_password.clone() self.key_password.clone()
} }
pub fn hip(&self) -> bool {
self.hip
}
pub fn csd_uid(&self) -> u32 { pub fn csd_uid(&self) -> u32 {
self.csd_uid self.csd_uid
} }
@@ -149,25 +114,9 @@ impl ConnectArgs {
pub fn no_dtls(&self) -> bool { pub fn no_dtls(&self) -> bool {
self.no_dtls self.no_dtls
} }
pub fn local_hostname(&self) -> Option<String> {
self.local_hostname.clone()
}
pub fn force_dpd(&self) -> u32 {
self.force_dpd
}
pub fn no_xmlpost(&self) -> bool {
self.no_xmlpost
}
pub fn allow_extend_session(&self) -> bool {
self.allow_extend_session
}
} }
#[derive(Debug, Deserialize, Serialize, Type, Clone)] #[derive(Debug, Deserialize, Serialize, Type)]
pub struct ConnectRequest { pub struct ConnectRequest {
info: ConnectInfo, info: ConnectInfo,
args: ConnectArgs, args: ConnectArgs,
@@ -186,11 +135,6 @@ impl ConnectRequest {
self self
} }
pub fn with_hip(mut self, hip: bool) -> Self {
self.args.hip = hip;
self
}
pub fn with_csd_uid(mut self, csd_uid: u32) -> Self { pub fn with_csd_uid(mut self, csd_uid: u32) -> Self {
self.args.csd_uid = csd_uid; self.args.csd_uid = csd_uid;
self self
@@ -211,16 +155,6 @@ impl ConnectRequest {
self self
} }
pub fn with_os_version<T: Into<Option<String>>>(mut self, os_version: T) -> Self {
self.args.os_version = os_version.into();
self
}
pub fn with_client_version(mut self, client_version: &str) -> Self {
self.args.client_version = Some(client_version.to_string());
self
}
pub fn with_certificate<T: Into<Option<String>>>(mut self, certificate: T) -> Self { pub fn with_certificate<T: Into<Option<String>>>(mut self, certificate: T) -> Self {
self.args.certificate = certificate.into(); self.args.certificate = certificate.into();
self self
@@ -256,26 +190,6 @@ impl ConnectRequest {
self self
} }
pub fn with_local_hostname<T: Into<Option<String>>>(mut self, local_hostname: T) -> Self {
self.args.local_hostname = local_hostname.into();
self
}
pub fn with_force_dpd(mut self, force_dpd: u32) -> Self {
self.args.force_dpd = force_dpd;
self
}
pub fn with_no_xmlpost(mut self, no_xmlpost: bool) -> Self {
self.args.no_xmlpost = no_xmlpost;
self
}
pub fn with_allow_extend_session(mut self, allow_extend_session: bool) -> Self {
self.args.allow_extend_session = allow_extend_session;
self
}
pub fn gateway(&self) -> &Gateway { pub fn gateway(&self) -> &Gateway {
self.info.gateway() self.info.gateway()
} }
@@ -308,20 +222,3 @@ pub struct UpdateGuiRequest {
pub path: String, pub path: String,
pub checksum: String, pub checksum: String,
} }
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn connect_request_serializes_allow_extend_session() {
let gateway = Gateway::new("Gateway".to_string(), "vpn.example.com".to_string());
let info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]);
let req = ConnectRequest::new(info, "authcookie=AUTH".to_string()).with_allow_extend_session(true);
let value = serde_json::to_value(req).unwrap();
assert_eq!(value["args"]["allowExtendSession"], json!(true));
}
}
-22
View File
@@ -1,22 +0,0 @@
use serde::{Deserialize, Serialize};
use crate::service::vpn_state::VpnState;
/// Represents the VPN environment configuration.
/// When a client connects, the gpservice sends the current VPN environment
/// to the client so that it can configure itself accordingly.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct VpnEnv {
/// The VPN connection state
pub vpn_state: VpnState,
/// The default VPN script path
pub vpnc_script: Option<String>,
/// The default CSD wrapper script path
pub csd_wrapper: Option<String>,
/// The gpauth executable path
/// Used by the client to launch gpauth for authentication
pub auth_executable: String,
}
+2 -51
View File
@@ -1,7 +1,7 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use specta::Type; use specta::Type;
use crate::{gateway::Gateway, session::SessionInfo}; use crate::gateway::Gateway;
#[derive(Debug, Deserialize, Serialize, Type, Clone)] #[derive(Debug, Deserialize, Serialize, Type, Clone)]
pub struct ConnectInfo { pub struct ConnectInfo {
@@ -10,30 +10,6 @@ pub struct ConnectInfo {
gateways: Vec<Gateway>, gateways: Vec<Gateway>,
} }
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ConnectedInfo {
info: Box<ConnectInfo>,
session_info: Option<SessionInfo>,
}
impl ConnectedInfo {
pub fn new(info: ConnectInfo, session_info: Option<SessionInfo>) -> Self {
Self {
info: Box::new(info),
session_info,
}
}
pub fn info(&self) -> &ConnectInfo {
&self.info
}
pub fn session_info(&self) -> Option<&SessionInfo> {
self.session_info.as_ref()
}
}
impl ConnectInfo { impl ConnectInfo {
pub fn new(portal: String, gateway: Gateway, gateways: Vec<Gateway>) -> Self { pub fn new(portal: String, gateway: Gateway, gateways: Vec<Gateway>) -> Self {
Self { Self {
@@ -53,31 +29,6 @@ impl ConnectInfo {
pub enum VpnState { pub enum VpnState {
Disconnected, Disconnected,
Connecting(Box<ConnectInfo>), Connecting(Box<ConnectInfo>),
Connected(Box<ConnectedInfo>), Connected(Box<ConnectInfo>),
Disconnecting, Disconnecting,
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn connected_state_serializes_session_info() {
let gateway = Gateway::new("vpn".to_string(), "vpn.example.com".to_string());
let connect_info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]);
let session_info = SessionInfo {
lifetime_secs: Some(43_200),
allow_extend_session: true,
..Default::default()
};
let value = serde_json::to_value(VpnState::Connected(Box::new(ConnectedInfo::new(
connect_info,
Some(session_info),
))))
.unwrap();
assert_eq!(value["connected"]["sessionInfo"]["lifetimeSecs"], 43_200);
assert_eq!(value["connected"]["sessionInfo"]["allowExtendSession"], true);
}
}
-302
View File
@@ -1,302 +0,0 @@
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use chrono::{Local, TimeZone};
use serde::{Deserialize, Serialize};
use specta::Type;
use crate::gp_params::ClientOs;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct SessionWarning {
pub prior_secs: u32,
pub message: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct SessionRequestArgs {
cookie: String,
user_agent: Option<String>,
os: Option<ClientOs>,
os_version: Option<String>,
client_version: Option<String>,
certificate: Option<String>,
sslkey: Option<String>,
key_password: Option<String>,
disable_ipv6: bool,
}
impl SessionRequestArgs {
pub fn new(cookie: String) -> Self {
Self {
cookie,
user_agent: None,
os: None,
os_version: None,
client_version: None,
certificate: None,
sslkey: None,
key_password: None,
disable_ipv6: false,
}
}
pub fn with_user_agent<T: Into<Option<String>>>(mut self, user_agent: T) -> Self {
self.user_agent = user_agent.into();
self
}
pub fn with_os<T: Into<Option<ClientOs>>>(mut self, os: T) -> Self {
self.os = os.into();
self
}
pub fn with_os_version<T: Into<Option<String>>>(mut self, os_version: T) -> Self {
self.os_version = os_version.into();
self
}
pub fn with_client_version<T: Into<Option<String>>>(mut self, client_version: T) -> Self {
self.client_version = client_version.into();
self
}
pub fn with_certificate<T: Into<Option<String>>>(mut self, certificate: T) -> Self {
self.certificate = certificate.into();
self
}
pub fn with_sslkey<T: Into<Option<String>>>(mut self, sslkey: T) -> Self {
self.sslkey = sslkey.into();
self
}
pub fn with_key_password<T: Into<Option<String>>>(mut self, key_password: T) -> Self {
self.key_password = key_password.into();
self
}
pub fn with_disable_ipv6(mut self, disable_ipv6: bool) -> Self {
self.disable_ipv6 = disable_ipv6;
self
}
pub fn cookie(&self) -> &str {
&self.cookie
}
pub fn user_agent(&self) -> Option<String> {
self.user_agent.clone()
}
pub fn os(&self) -> Option<ClientOs> {
self.os.clone()
}
pub fn os_version(&self) -> Option<String> {
self.os_version.clone()
}
pub fn client_version(&self) -> Option<String> {
self.client_version.clone()
}
pub fn certificate(&self) -> Option<String> {
self.certificate.clone()
}
pub fn sslkey(&self) -> Option<String> {
self.sslkey.clone()
}
pub fn key_password(&self) -> Option<String> {
self.key_password.clone()
}
pub fn disable_ipv6(&self) -> bool {
self.disable_ipv6
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SessionInfo {
pub lifetime_secs: Option<u32>,
pub user_expires: Option<u32>,
pub expires_in_human: Option<String>,
pub lifetime_warning: Option<SessionWarning>,
pub inactivity_warning: Option<SessionWarning>,
pub admin_logout_message: Option<String>,
pub allow_extend_session: bool,
}
impl SessionInfo {
pub fn with_computed_human_times(mut self) -> Self {
self.expires_in_human = build_human_readable_expiry(self.user_expires, self.lifetime_secs);
self
}
pub fn from_vpn_session_fields(
lifetime_secs: Option<u32>,
user_expires: Option<u32>,
lifetime_warning: Option<SessionWarning>,
allow_extend_session: bool,
) -> Self {
Self {
lifetime_secs,
user_expires,
expires_in_human: None,
lifetime_warning,
inactivity_warning: None,
admin_logout_message: None,
allow_extend_session,
}
.with_computed_human_times()
}
pub fn rescheduled_after_extension(&self) -> Option<Self> {
let lifetime_secs = self.lifetime_secs?;
let mut session_info = self.clone();
session_info.user_expires = Some(unix_timestamp().saturating_add(lifetime_secs));
Some(session_info.with_computed_human_times())
}
pub fn log_summary(&self) -> String {
let lifetime_secs = self
.lifetime_secs
.map(format_secs_with_duration)
.unwrap_or_else(|| "none".to_string());
let user_expires = self
.user_expires
.map(format_epoch_with_local_time)
.unwrap_or_else(|| "none".to_string());
let lifetime_warning_prior = self
.lifetime_warning
.as_ref()
.map(|warning| format_secs_with_duration(warning.prior_secs))
.unwrap_or_else(|| "none".to_string());
format!(
"lifetime_secs={lifetime_secs}, user_expires={user_expires}, lifetime_warning_prior={lifetime_warning_prior}, allow_extend_session={}",
self.allow_extend_session
)
}
}
pub fn format_duration_secs(total_secs: u32) -> String {
humantime::format_duration(Duration::from_secs(total_secs as u64)).to_string()
}
fn format_secs_with_duration(secs: u32) -> String {
format!("{secs} ({})", format_duration_secs(secs))
}
fn format_epoch_with_local_time(epoch: u32) -> String {
let local_time = Local
.timestamp_opt(epoch as i64, 0)
.single()
.map(|time| time.format("%Y-%m-%d %H:%M:%S").to_string())
.unwrap_or_else(|| "invalid time".to_string());
let now = unix_timestamp();
let relative = if epoch >= now {
format!("in {}", format_duration_secs(epoch.saturating_sub(now)))
} else {
format!("{} ago", format_duration_secs(now.saturating_sub(epoch)))
};
format!("{epoch} ({local_time}, {relative})")
}
fn build_human_readable_expiry(user_expires: Option<u32>, lifetime_secs: Option<u32>) -> Option<String> {
if let Some(user_expires) = user_expires {
let now = unix_timestamp();
return Some(format_duration_secs(user_expires.saturating_sub(now)));
}
lifetime_secs.map(format_duration_secs)
}
fn unix_timestamp() -> u32 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as u32
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_duration_secs() {
assert_eq!(format_duration_secs(43_200), "12h");
assert_eq!(format_duration_secs(1_830), "30m 30s");
}
#[test]
fn logs_session_info_with_human_readable_times() {
let info = SessionInfo {
lifetime_secs: Some(43_200),
user_expires: Some(unix_timestamp().saturating_add(43_200)),
lifetime_warning: Some(SessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
allow_extend_session: true,
..Default::default()
};
let summary = info.log_summary();
assert!(summary.contains("lifetime_secs=43200 (12h)"));
assert!(summary.contains("user_expires="));
assert!(summary.contains(", in "));
assert!(summary.contains("lifetime_warning_prior=1800 (30m)"));
assert!(summary.contains("allow_extend_session=true"));
}
#[test]
fn computes_expires_in_human_from_lifetime_or_epoch() {
let from_lifetime = SessionInfo {
lifetime_secs: Some(43_200),
..Default::default()
}
.with_computed_human_times();
assert_eq!(from_lifetime.expires_in_human.as_deref(), Some("12h"));
let from_epoch = SessionInfo {
user_expires: Some(unix_timestamp().saturating_add(1_830)),
..Default::default()
}
.with_computed_human_times();
assert!(
from_epoch
.expires_in_human
.as_deref()
.is_some_and(|value| value.starts_with("30m"))
);
}
#[test]
fn reschedules_after_extension_from_lifetime() {
let now = unix_timestamp();
let info = SessionInfo {
lifetime_secs: Some(7_200),
user_expires: Some(now.saturating_add(1_830)),
..Default::default()
};
let next = info.rescheduled_after_extension().unwrap();
assert!(
next
.user_expires
.is_some_and(|expires| expires >= now.saturating_add(7_200))
);
assert!(next.expires_in_human.is_some());
}
#[test]
fn reschedule_after_extension_requires_lifetime() {
assert!(SessionInfo::default().rescheduled_after_extension().is_none());
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
use base64::{Engine, engine::general_purpose}; use base64::{engine::general_purpose, Engine};
pub fn encode(data: &[u8]) -> String { pub fn encode(data: &[u8]) -> String {
let engine = general_purpose::STANDARD; let engine = general_purpose::STANDARD;
+4 -4
View File
@@ -1,8 +1,8 @@
use chacha20poly1305::{ use chacha20poly1305::{
AeadCore, ChaCha20Poly1305, Key, KeyInit,
aead::{Aead, OsRng}, aead::{Aead, OsRng},
AeadCore, ChaCha20Poly1305, Key, KeyInit, Nonce,
}; };
use serde::{Serialize, de::DeserializeOwned}; use serde::{de::DeserializeOwned, Serialize};
pub fn generate_key() -> Key { pub fn generate_key() -> Key {
ChaCha20Poly1305::generate_key(&mut OsRng) ChaCha20Poly1305::generate_key(&mut OsRng)
@@ -31,10 +31,10 @@ where
{ {
let cipher = ChaCha20Poly1305::new(key); let cipher = ChaCha20Poly1305::new(key);
let nonce = &encrypted[..12]; let nonce = Nonce::from_slice(&encrypted[..12]);
let cipher_text = &encrypted[12..]; let cipher_text = &encrypted[12..];
let plaintext = cipher.decrypt(nonce.into(), cipher_text)?; let plaintext = cipher.decrypt(nonce, cipher_text)?;
let value = serde_json::from_slice(&plaintext)?; let value = serde_json::from_slice(&plaintext)?;
+7 -54
View File
@@ -1,6 +1,5 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::env; use std::env;
use std::ffi::OsStr;
use std::io::Write; use std::io::Write;
use std::path::Path; use std::path::Path;
@@ -40,63 +39,17 @@ pub fn load_env_vars<T: AsRef<Path>>(env_file: T) -> anyhow::Result<HashMap<Stri
pub fn patch_gui_runtime_env(hidpi: bool) { pub fn patch_gui_runtime_env(hidpi: bool) {
// This is to avoid blank screen on some systems // This is to avoid blank screen on some systems
unsafe { std::env::set_var("WEBKIT_DISABLE_COMPOSITING_MODE", "1") }; std::env::set_var("WEBKIT_DISABLE_COMPOSITING_MODE", "1");
if is_wayland_session( // Workaround for https://github.com/tauri-apps/tao/issues/929
env::var_os("WAYLAND_DISPLAY").as_deref(), let is_wayland = std::env::var("XDG_SESSION_TYPE").unwrap_or_default() == "wayland";
env::var("XDG_SESSION_TYPE").ok().as_deref(), if is_wayland {
) { env::set_var("GDK_BACKEND", "x11");
info!("Wayland session detected, enabling Linux WebKit rendering fallbacks");
set_env_if_missing("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
set_env_if_missing("LIBGL_ALWAYS_SOFTWARE", "1");
} }
if hidpi { if hidpi {
info!("Setting GDK_SCALE=2 and GDK_DPI_SCALE=0.5"); info!("Setting GDK_SCALE=2 and GDK_DPI_SCALE=0.5");
unsafe { std::env::set_var("GDK_SCALE", "2");
std::env::set_var("GDK_SCALE", "2"); std::env::set_var("GDK_DPI_SCALE", "0.5");
std::env::set_var("GDK_DPI_SCALE", "0.5");
};
}
}
fn is_wayland_session(wayland_display: Option<&OsStr>, xdg_session_type: Option<&str>) -> bool {
if wayland_display.is_some() {
return true;
}
matches!(xdg_session_type, Some("wayland"))
}
fn set_env_if_missing(key: &str, value: &str) {
if env::var_os(key).is_some() {
return;
}
info!("Setting {}={}", key, value);
unsafe { env::set_var(key, value) };
}
#[cfg(test)]
mod tests {
use std::ffi::OsStr;
use super::is_wayland_session;
#[test]
fn detects_wayland_from_wayland_display() {
assert!(is_wayland_session(Some(OsStr::new("wayland-1")), None));
}
#[test]
fn detects_wayland_from_session_type() {
assert!(is_wayland_session(None, Some("wayland")));
}
#[test]
fn ignores_non_wayland_sessions() {
assert!(!is_wayland_session(None, None));
assert!(!is_wayland_session(None, Some("x11")));
assert!(!is_wayland_session(None, Some("tty")));
} }
} }
-108
View File
@@ -1,108 +0,0 @@
use std::sync::OnceLock;
const DEFAULT_MACOS_VERSION: &str = "13.4.0";
#[cfg(not(target_os = "linux"))]
const DEFAULT_LINUX_DISTRO: &str = "Ubuntu 24.04.3 LTS";
#[cfg(not(target_os = "windows"))]
const DEFAULT_WINDOWS_DISTRO: &str = "Windows 11 Pro";
const DEFAULT_WINDOWS_VERSION: &str = "10.0.22631.0";
const DEFAULT_MACHINE_ID: &str = "DEADBEEF-DEAD-BEEF-DEAD-BEEFDEADBEEF";
static MACHINE_ID: OnceLock<&'static str> = OnceLock::new();
static MACOS_VERSION: OnceLock<&'static str> = OnceLock::new();
static MACOS_OS_STRING: OnceLock<String> = OnceLock::new();
static LINUX_OS_STRING: OnceLock<String> = OnceLock::new();
static WINDOWS_VERSION: OnceLock<&'static str> = OnceLock::new();
static WINDOWS_OS_STRING: OnceLock<String> = OnceLock::new();
/// On macOS, get the OS version, or fallback to default
/// On other OSes, always return default
pub fn get_macos_version() -> &'static str {
MACOS_VERSION.get_or_init(|| {
#[cfg(target_os = "macos")]
{
match os_info::get().version() {
os_info::Version::Unknown => DEFAULT_MACOS_VERSION,
v => v.to_string().leak(),
}
}
#[cfg(not(target_os = "macos"))]
DEFAULT_MACOS_VERSION
})
}
pub fn get_macos_os_string() -> &'static str {
MACOS_OS_STRING.get_or_init(|| format!("Apple Mac OS X {}", get_macos_version()))
}
/// On Linux, use the real distro name if possible
/// On other OSes, fallback to default
pub fn get_linux_os_string() -> &'static str {
LINUX_OS_STRING.get_or_init(|| {
#[cfg(target_os = "linux")]
{
format!("Linux {}", whoami::distro())
}
#[cfg(not(target_os = "linux"))]
{
format!("Linux {}", DEFAULT_LINUX_DISTRO)
}
})
}
/// On Windows, get the OS version, or fallback to default
/// On other OSes, always return default
pub fn get_windows_version() -> &'static str {
WINDOWS_VERSION.get_or_init(|| {
#[cfg(target_os = "windows")]
{
match os_info::get().version() {
os_info::Version::Unknown => DEFAULT_WINDOWS_VERSION,
v => format!("{}.0", v).leak(),
}
}
#[cfg(not(target_os = "windows"))]
DEFAULT_WINDOWS_VERSION
})
}
/// On Windows, use the real edition if possible
/// On other OSes, fallback to default
/// The trailing space is intentional
pub fn get_windows_os_string() -> &'static str {
WINDOWS_OS_STRING.get_or_init(|| {
#[cfg(target_os = "windows")]
{
let edition = os_info::get()
.edition()
.map(|e| e.to_string())
.unwrap_or_else(|| whoami::distro());
format!("Microsoft {} , 64-bit", edition)
}
#[cfg(not(target_os = "windows"))]
{
format!("Microsoft {} , 64-bit", DEFAULT_WINDOWS_DISTRO)
}
})
}
/// Get machine ID or fallback to default
pub fn get_machine_id() -> &'static str {
MACHINE_ID.get_or_init(|| {
machine_uid::get()
.map(|id| id.to_string().leak() as &'static str)
.unwrap_or(DEFAULT_MACHINE_ID)
})
}
/// Generate a UUID v5 based on machine ID and provided seeds
pub fn derive_uuid(seeds: &[&str]) -> String {
use uuid::Uuid;
let namespace = Uuid::NAMESPACE_DNS;
let name = format!("{}-{}", get_machine_id(), seeds.join("-"));
let uuid = Uuid::new_v5(&namespace, name.as_bytes());
uuid.hyphenated().to_string()
}
+1 -2
View File
@@ -1,6 +1,5 @@
use std::path::PathBuf; use std::path::PathBuf;
use common::constants::GP_SERVICE_LOCK_FILE;
use thiserror::Error; use thiserror::Error;
use tokio::fs; use tokio::fs;
@@ -95,7 +94,7 @@ impl LockInfo {
} }
pub async fn gpservice_lock_info() -> Result<LockInfo, LockFileError> { pub async fn gpservice_lock_info() -> Result<LockInfo, LockFileError> {
LockInfo::from_file(GP_SERVICE_LOCK_FILE).await LockInfo::from_file(crate::GP_SERVICE_LOCK_FILE).await
} }
#[cfg(test)] #[cfg(test)]
+3 -4
View File
@@ -1,11 +1,10 @@
pub mod xml; pub(crate) mod xml;
pub mod base64; pub mod base64;
pub mod checksum; pub mod checksum;
pub mod crypto; pub mod crypto;
pub mod endpoint; pub mod endpoint;
pub mod env_utils; pub mod env_utils;
pub mod host_utils;
pub mod lock_file; pub mod lock_file;
pub mod openssl; pub mod openssl;
pub mod redact; pub mod redact;
@@ -48,7 +47,7 @@ pub fn remove_url_scheme(s: &str) -> String {
#[derive(Error, Debug)] #[derive(Error, Debug)]
#[error("GP response error: reason={reason}, status={status}, body={body}")] #[error("GP response error: reason={reason}, status={status}, body={body}")]
pub struct GpError { pub(crate) struct GpError {
pub status: StatusCode, pub status: StatusCode,
pub reason: String, pub reason: String,
body: String, body: String,
@@ -60,7 +59,7 @@ impl GpError {
} }
} }
pub async fn parse_gp_response(res: Response) -> anyhow::Result<String, GpError> { pub(crate) async fn parse_gp_response(res: Response) -> anyhow::Result<String, GpError> {
let status = res.status(); let status = res.status();
if status.is_client_error() || status.is_server_error() { if status.is_client_error() || status.is_server_error() {
+2 -2
View File
@@ -3,7 +3,7 @@ use std::path::Path;
use log::{info, warn}; use log::{info, warn};
use regex::Regex; use regex::Regex;
use tempfile::NamedTempFile; use tempfile::NamedTempFile;
use version_compare::{Cmp, compare_to}; use version_compare::{compare_to, Cmp};
pub fn openssl_conf() -> String { pub fn openssl_conf() -> String {
let option = get_openssl_option(); let option = get_openssl_option();
@@ -46,7 +46,7 @@ pub fn fix_openssl_env() -> anyhow::Result<NamedTempFile> {
let openssl_conf_path = openssl_conf.path(); let openssl_conf_path = openssl_conf.path();
fix_openssl(openssl_conf_path)?; fix_openssl(openssl_conf_path)?;
unsafe { std::env::set_var("OPENSSL_CONF", openssl_conf_path) }; std::env::set_var("OPENSSL_CONF", openssl_conf_path);
Ok(openssl_conf) Ok(openssl_conf)
} }
+1 -1
View File
@@ -2,7 +2,7 @@ use std::sync::RwLock;
use redact_engine::{Pattern, Redaction as RedactEngine}; use redact_engine::{Pattern, Redaction as RedactEngine};
use regex::Regex; use regex::Regex;
use url::{Url, form_urlencoded}; use url::{form_urlencoded, Url};
pub struct Redaction { pub struct Redaction {
redact_engine: RwLock<Option<RedactEngine>>, redact_engine: RwLock<Option<RedactEngine>>,
+51 -75
View File
@@ -1,97 +1,73 @@
use std::{process::ExitStatus, time::Duration};
use anyhow::bail;
use log::info;
use tauri::WebviewWindow; use tauri::WebviewWindow;
use tokio::process::Command;
pub trait WindowExt { pub trait WindowExt {
fn raise(&self) -> anyhow::Result<()>; fn raise(&self) -> anyhow::Result<()>;
} }
impl WindowExt for WebviewWindow { impl WindowExt for WebviewWindow {
#[cfg(any(target_os = "macos", target_os = "windows"))]
fn raise(&self) -> anyhow::Result<()> { fn raise(&self) -> anyhow::Result<()> {
self.show()?; raise_window(self)
Ok(())
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
fn raise(&self) -> anyhow::Result<()> {
unix::raise_window(self)
} }
} }
#[cfg(not(any(target_os = "macos", target_os = "windows")))] pub fn raise_window(win: &WebviewWindow) -> anyhow::Result<()> {
mod unix { let is_wayland = std::env::var("XDG_SESSION_TYPE").unwrap_or_default() == "wayland";
use std::{process::ExitStatus, time::Duration};
use anyhow::bail; if is_wayland {
use gtk::{ win.hide()?;
EventBox, win.show()?;
glib::Cast, } else {
traits::{EventBoxExt, GtkWindowExt, WidgetExt}, if !win.is_visible()? {
}; win.show()?;
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 {
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()?;
}
let title = win.title()?;
tokio::spawn(async move {
if let Err(err) = wmctrl_raise_window(&title).await {
info!("Window not raised: {}", err);
}
});
} }
let title = win.title()?;
// Calling window.show() on window object will cause the menu to be shown. tokio::spawn(async move {
// We need to hide it again. if let Err(err) = wmctrl_raise_window(&title).await {
win.hide_menu()?; info!("Window not raised: {}", err);
}
Ok(()) });
} }
async fn wmctrl_raise_window(title: &str) -> anyhow::Result<()> { // Calling window.show() on Windows will cause the menu to be shown.
let mut counter = 0; // We need to hide it again.
win.hide_menu()?;
loop { Ok(())
if let Ok(exit_status) = wmctrl_try_raise_window(title).await { }
if exit_status.success() {
info!("Window raised after {} attempts", counter + 1); async fn wmctrl_raise_window(title: &str) -> anyhow::Result<()> {
return Ok(()); let mut counter = 0;
}
loop {
if let Ok(exit_status) = wmctrl_try_raise_window(title).await {
if exit_status.success() {
info!("Window raised after {} attempts", counter + 1);
return Ok(());
} }
if counter >= 10 {
bail!("Failed to raise window: {}", title)
}
counter += 1;
tokio::time::sleep(Duration::from_millis(100)).await;
} }
}
async fn wmctrl_try_raise_window(title: &str) -> anyhow::Result<ExitStatus> { if counter >= 10 {
let exit_status = Command::new("wmctrl") bail!("Failed to raise window: {}", title)
.arg("-F") }
.arg("-a")
.arg(title)
.spawn()?
.wait()
.await?;
Ok(exit_status) counter += 1;
tokio::time::sleep(Duration::from_millis(100)).await;
} }
} }
async fn wmctrl_try_raise_window(title: &str) -> anyhow::Result<ExitStatus> {
let exit_status = Command::new("wmctrl")
.arg("-F")
.arg("-a")
.arg(title)
.spawn()?
.wait()
.await?;
Ok(exit_status)
}
+15 -75
View File
@@ -1,87 +1,27 @@
use xmltree::Element; use roxmltree::Node;
pub trait ElementExt { pub(crate) trait NodeExt<'a> {
/// Recursively find all descendants with the given name fn find_descendant(&self, name: &str) -> Option<Node<'a, 'a>>;
fn descendants(&self, name: &str) -> Vec<&Element>; fn descendant_text(&self, name: &str) -> Option<&'a str>;
/// Recursively find the first descendant with the given name fn find_child(&self, name: &str) -> Option<Node<'a, 'a>>;
fn descendant(&self, name: &str) -> Option<&Element>; fn child_text(&self, name: &str) -> Option<&'a str>;
/// Recursively find the text of the first descendant with the given name
fn descendant_text(&self, name: &str) -> Option<String>;
/// Find the first child with the given name
fn child(&self, name: &str) -> Option<&Element>;
/// Find the text of the first child with the given name
fn child_text(&self, name: &str) -> Option<String>;
/// Get the direct child element with the given name
fn children(&self, name: &str) -> Vec<&Element>;
/// Get the attribute value by name
fn attr(&self, name: &str) -> Option<&str>;
} }
impl ElementExt for Element { impl<'a> NodeExt<'a> for Node<'a, 'a> {
fn descendants(&self, name: &str) -> Vec<&Element> { fn find_descendant(&self, name: &str) -> Option<Node<'a, 'a>> {
let mut results = Vec::new(); self.descendants().find(|n| n.has_tag_name(name))
if self.name == name {
results.push(self);
}
for child in &self.children {
if let Some(element) = child.as_element() {
results.extend(element.descendants(name));
}
}
results
} }
fn descendant(&self, name: &str) -> Option<&Element> { fn descendant_text(&self, name: &str) -> Option<&'a str> {
if self.name == name { self.find_descendant(name).and_then(|node| node.text())
return Some(self);
}
for child in &self.children {
if let Some(element) = child.as_element() {
if let Some(found) = element.descendant(name) {
return Some(found);
}
}
}
None
} }
fn descendant_text(&self, name: &str) -> Option<String> { fn find_child(&self, name: &str) -> Option<Node<'a, 'a>> {
self self.children().find(|n| n.has_tag_name(name))
.descendant(name)
.and_then(|element| element.get_text().map(|s| s.to_string()))
} }
fn child(&self, name: &str) -> Option<&Element> { fn child_text(&self, name: &str) -> Option<&'a str> {
self.get_child(name) self.find_child(name).and_then(|node| node.text())
}
fn child_text(&self, name: &str) -> Option<String> {
self
.get_child(name)
.and_then(|element| element.get_text().map(|s| s.to_string()))
}
fn children(&self, name: &str) -> Vec<&Element> {
self
.children
.iter()
.filter_map(|child| child.as_element())
.filter(|element| element.name == name)
.collect()
}
fn attr(&self, name: &str) -> Option<&str> {
self.attributes.get(name).map(|s| s.as_str())
} }
} }
+1 -4
View File
@@ -6,11 +6,8 @@ license.workspace = true
links = "openconnect" links = "openconnect"
[dependencies] [dependencies]
common = { path = "../common" }
log.workspace = true log.workspace = true
is_executable.workspace = true
[build-dependencies] [build-dependencies]
cc = "1" cc = "1"
autotools = "0.2"
pkg-config = "0.3"
fs_extra = "1"
+5 -196
View File
@@ -1,205 +1,14 @@
use std::{env, path::PathBuf, process::Command};
fn apply_patches(patches_dir: &PathBuf, build_src: &PathBuf) {
let patches = std::fs::read_dir(patches_dir)
.expect("Failed to read patches directory")
.filter_map(|entry| entry.ok())
.filter(|entry| entry.path().extension().and_then(|s| s.to_str()) == Some("patch"))
.map(|entry| entry.path())
.collect::<Vec<_>>();
// Sort patches to ensure they are applied in order
let mut patches = patches;
patches.sort();
for patch in patches {
println!("cargo:rerun-if-changed={}", patch.display());
println!("Applying patch: {}", patch.display());
let status = Command::new("patch")
.arg("-p1") // Strip one level of path (standard for git diffs)
.arg("-i") // Input file
.arg(&patch)
.current_dir(build_src) // Run INSIDE the copied dir
.status()
.expect("Failed to execute patch command");
if !status.success() {
panic!("Failed to apply patch file: {}", patch.display());
}
}
}
fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
let libxml2_dir = deps_dir.join("libxml2");
// The temporary location where we will build
let build_src = out_dir.join("libxml2_build");
// Track changes so cargo rebuilds if submodule changes
println!("cargo:rerun-if-changed={}", libxml2_dir.display());
// Prepare the build directory
// If the directory exists from a previous run, remove it to ensure a clean slate
if build_src.exists() {
std::fs::remove_dir_all(&build_src).unwrap();
}
std::fs::create_dir_all(&build_src).unwrap();
// Copy the source code to OUT_DIR
// We use fs_extra options to copy contents recursively
let mut options = fs_extra::dir::CopyOptions::new();
options.overwrite = true;
options.content_only = true; // Copy content of src into dest, not src folder itself
fs_extra::dir::copy(&libxml2_dir, &build_src, &options).expect("Failed to copy C source code to OUT_DIR");
// Build the libxml2 library using autotools
let dst = autotools::Config::new(&build_src)
.reconf("-ivf")
.enable_static()
.disable_shared()
// Disable optional features that complicate static builds
.with("python", Some("no"))
.with("icu", Some("no"))
.with("http", Some("no"))
.with("ftp", Some("no"))
.with("catalog", Some("no"))
.with("docbook", Some("no"))
.with("legacy", Some("no"))
.with("threads", Some("no"))
.with("zlib", Some("no"))
.with("lzma", Some("no"))
// Ensure position-independent code (safe for static linking)
.cflag("-fPIC")
.build();
let lib_dir = dst.join("lib");
let include_dir = dst.join("include/libxml2");
// Tell rustc where to find the static library
println!("cargo:rustc-link-search=native={}", lib_dir.display());
// Static linking of libxml2
println!("cargo:rustc-link-lib=static=xml2");
// Export include path for downstream use (bindgen / cc)
println!("cargo:include={}", include_dir.display());
dst
}
fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
let openconnect_dir = deps_dir.join("openconnect");
let patches_dir = deps_dir.join("patches");
// The temporary location where we will build
let build_src = out_dir.join("openconnect_build");
// Track changes so cargo rebuilds if patch or submodule changes
println!("cargo:rerun-if-changed={}", openconnect_dir.display());
// Prepare the build directory
// If the directory exists from a previous run, remove it to ensure a clean slate
if build_src.exists() {
std::fs::remove_dir_all(&build_src).unwrap();
}
std::fs::create_dir_all(&build_src).unwrap();
// Copy the source code to OUT_DIR
// We use fs_extra options to copy contents recursively
let mut options = fs_extra::dir::CopyOptions::new();
options.overwrite = true;
options.content_only = true; // Copy content of src into dest, not src folder itself
fs_extra::dir::copy(&openconnect_dir, &build_src, &options).expect("Failed to copy C source code to OUT_DIR");
// Apply all patches from the patches directory
apply_patches(&patches_dir, &build_src);
// Build the OpenConnect library using autotools
// We explicitly enable static and disable shared to ensure we get a .a file.
// .reconf("-ivf") is CRITICAL for git submodules because 'configure'
// usually doesn't exist yet and needs to be generated.
let mut config = autotools::Config::new(&build_src);
config
.reconf("-ivf")
.enable_static()
.disable_shared()
.disable("nls", None) // disable translations to save space
.disable("docs", None)
.disable("dsa-tests", None)
.without("libproxy", None)
.without("stoken", None)
.without("libpcsclite", None)
.without("libpskc", None)
.without("gssapi", None)
.with("gnutls-tss2", Some("no"))
.with("vpnc-script", Some("/etc/vpnc/vpnc-script")); // Specify vpnc-script, otherwise it will fail on macOS
#[cfg(target_os = "macos")]
{
config.ldflag("-liconv");
config.env("LIBS", "-liconv");
}
let dst = config.build();
let lib_dir = dst.join("lib");
let include_dir = dst.join("include");
// Tell rustc where to find the static library
println!("cargo:rustc-link-search=native={}", lib_dir.display());
// Static linking of openconnect
println!("cargo:rustc-link-lib=static=openconnect");
// Export include path for downstream use (bindgen / cc)
println!("cargo:include={}", include_dir.display());
dst
}
fn main() { fn main() {
let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); // Link to the native openconnect library
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); println!("cargo:rustc-link-lib=openconnect");
let deps_dir = PathBuf::from(manifest_dir).join("deps"); println!("cargo:rustc-link-search=/opt/homebrew/lib"); // Homebrew path
let oc_dst = build_openconnect(&deps_dir, &out_dir);
// Only statically link libxml2 if `LIBXML2_STATIC` is set
if env::var("LIBXML2_STATIC").is_ok() {
let _libxml2_dst = build_libxml2(&deps_dir, &out_dir);
} else {
// Using pkg-config to find system libxml2
pkg_config::probe_library("libxml-2.0").unwrap();
}
// Using pkg-config to find system deps
pkg_config::probe_library("zlib").unwrap();
pkg_config::probe_library("liblz4").unwrap();
pkg_config::probe_library("gnutls").unwrap();
// Below are required by gnutls
pkg_config::probe_library("p11-kit-1").unwrap();
pkg_config::probe_library("hogweed").unwrap();
pkg_config::probe_library("nettle").unwrap();
pkg_config::probe_library("gmp").unwrap();
// Compile the vpn.c file
println!("cargo:rerun-if-changed=src/ffi/vpn.c"); println!("cargo:rerun-if-changed=src/ffi/vpn.c");
println!("cargo:rerun-if-changed=src/ffi/vpn.h"); println!("cargo:rerun-if-changed=src/ffi/vpn.h");
// Prevent silent fallback to dynamic libraries // Compile the vpn.c file
#[cfg(target_os = "linux")]
{
println!("cargo:rustc-link-arg=-Wl,-Bstatic");
println!("cargo:rustc-link-arg=-Wl,-Bdynamic");
}
cc::Build::new() cc::Build::new()
.file("src/ffi/vpn.c") .file("src/ffi/vpn.c")
.include("src/ffi") .include("src/ffi")
.include(&oc_dst.join("include")) .include("/opt/homebrew/include") // Homebrew path
.compile("vpn"); .compile("vpn");
} }
@@ -1,114 +0,0 @@
From a8d5ec198ca9ae47a0e6b4f1ea244d2738acf055 Mon Sep 17 00:00:00 2001
From: Kevin Yue <[email protected]>
Date: Sun, 14 Dec 2025 17:10:02 +0800
Subject: [PATCH 1/4] Add support for GlobalProtect app version handling
- Introduced `gp_app_version` field in `openconnect_info` structure.
- Implemented `openconnect_set_gp_app_version` and `openconnect_get_gp_app_version` functions.
- Updated `gpst_get_config` to use the app version in requests.
- Free `gp_app_version` in `openconnect_vpninfo_free` to prevent memory leaks.
---
gpst.c | 8 +++++---
library.c | 15 +++++++++++++++
openconnect-internal.h | 4 ++++
openconnect.h | 2 ++
4 files changed, 26 insertions(+), 3 deletions(-)
diff --git a/gpst.c b/gpst.c
index 244aaf04..5c24bbd2 100644
--- a/gpst.c
+++ b/gpst.c
@@ -650,8 +650,11 @@ static int gpst_get_config(struct openconnect_info *vpninfo)
/* submit getconfig request */
+ const char *app_version = openconnect_get_gp_app_version(vpninfo);
+ vpn_progress(vpninfo, PRG_DEBUG, _("Using GlobalProtect app version: %s\n"), app_version);
+
buf_append(request_body, "client-type=1&protocol-version=p1&internal=no");
- append_opt(request_body, "app-version", vpninfo->csd_ticket ? : "6.3.0-33");
+ append_opt(request_body, "app-version", app_version);
append_opt(request_body, "ipv6-support", vpninfo->disable_ipv6 ? "no" : "yes");
append_opt(request_body, "clientos", gpst_os_name(vpninfo));
append_opt(request_body, "os-version", vpninfo->platname);
@@ -1040,8 +1043,7 @@ static int run_hip_script(struct openconnect_info *vpninfo)
* accept new ones.
*/
unsetenv("APP_VERSION");
- if (vpninfo->csd_ticket)
- if (setenv("APP_VERSION", vpninfo->csd_ticket, 1))
+ if (setenv("APP_VERSION", openconnect_get_gp_app_version(vpninfo), 1))
goto out;
execv(hip_argv[0], (char **)hip_argv);
diff --git a/library.c b/library.c
index b5e74e9b..18334c76 100644
--- a/library.c
+++ b/library.c
@@ -896,6 +896,7 @@ void openconnect_vpninfo_free(struct openconnect_info *vpninfo)
free(vpninfo->localname);
free(vpninfo->useragent);
+ free(vpninfo->gp_app_version);
free(vpninfo->authgroup);
#ifdef HAVE_LIBSTOKEN
if (vpninfo->stoken_pin)
@@ -1019,6 +1020,20 @@ int openconnect_set_useragent(struct openconnect_info *vpninfo,
return 0;
}
+int openconnect_set_gp_app_version(struct openconnect_info *vpninfo,
+ const char *gp_app_version)
+{
+ UTF8CHECK(gp_app_version);
+
+ STRDUP(vpninfo->gp_app_version, gp_app_version);
+ return 0;
+}
+
+const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo)
+{
+ return vpninfo->csd_ticket ?: (vpninfo->gp_app_version ?: "6.3.0-33");
+}
+
int openconnect_set_urlpath(struct openconnect_info *vpninfo,
const char *urlpath)
{
diff --git a/openconnect-internal.h b/openconnect-internal.h
index abf45bbd..988f85f0 100644
--- a/openconnect-internal.h
+++ b/openconnect-internal.h
@@ -786,6 +786,7 @@ struct openconnect_info {
int is_dyndns; /* Attempt to redo DNS lookup on each CSTP reconnect */
char *useragent;
char *version_string;
+ char *gp_app_version;
const char *quit_reason;
const char *delay_tunnel_reason; /* If non-null, provides a reason why protocol is not yet ready for tunnel setup */
@@ -1677,6 +1678,9 @@ void openconnect_set_juniper(struct openconnect_info *vpninfo);
/* hpke.c */
int handle_external_browser(struct openconnect_info *vpninfo);
+/* Get the app version */
+const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo);
+
/* version.c */
extern const char openconnect_version_str[];
diff --git a/openconnect.h b/openconnect.h
index 136f181a..7d4f3399 100644
--- a/openconnect.h
+++ b/openconnect.h
@@ -470,6 +470,8 @@ int openconnect_set_http_proxy(struct openconnect_info *vpninfo,
int openconnect_set_useragent(struct openconnect_info *vpninfo,
const char *useragent);
+int openconnect_set_gp_app_version(struct openconnect_info *vpninfo,
+ const char *gp_app_version);
int openconnect_passphrase_from_fsid(struct openconnect_info *vpninfo);
int openconnect_obtain_cookie(struct openconnect_info *vpninfo);
int openconnect_init_ssl(void);
--
2.50.1 (Apple Git-155)
@@ -1,32 +0,0 @@
From 8591eba702f52dae335601c997271786be50dff7 Mon Sep 17 00:00:00 2001
From: Kevin Yue <[email protected]>
Date: Sun, 14 Dec 2025 17:10:52 +0800
Subject: [PATCH 2/4] Update user agent for common headers in GlobalProtect
authentication
---
auth-globalprotect.c | 7 -------
1 file changed, 7 deletions(-)
diff --git a/auth-globalprotect.c b/auth-globalprotect.c
index 8d094273..27e41c2b 100644
--- a/auth-globalprotect.c
+++ b/auth-globalprotect.c
@@ -34,14 +34,7 @@ struct login_context {
void gpst_common_headers(struct openconnect_info *vpninfo,
struct oc_text_buf *buf)
{
- char *orig_ua = vpninfo->useragent;
-
- /* XX: more recent servers don't appear to require this specific UA value,
- * but we don't have any good way to detect them.
- */
- vpninfo->useragent = (char *)"PAN GlobalProtect";
http_common_headers(vpninfo, buf);
- vpninfo->useragent = orig_ua;
}
/* Translate platform names (derived from AnyConnect) into the values
--
2.50.1 (Apple Git-155)
@@ -1,121 +0,0 @@
From dda2aceca7e614af65b968e632065ef223cb6612 Mon Sep 17 00:00:00 2001
From: Kevin Yue <[email protected]>
Date: Sun, 14 Dec 2025 17:14:08 +0800
Subject: [PATCH 3/4] Add support for OS version handling in GlobalProtect
authentication
---
auth-globalprotect.c | 2 +-
gpst.c | 4 ++--
library.c | 15 +++++++++++++++
openconnect-internal.h | 4 ++++
openconnect.h | 3 +++
5 files changed, 25 insertions(+), 3 deletions(-)
diff --git a/auth-globalprotect.c b/auth-globalprotect.c
index 27e41c2b..59d6de3b 100644
--- a/auth-globalprotect.c
+++ b/auth-globalprotect.c
@@ -731,7 +731,7 @@ static int gpst_login(struct openconnect_info *vpninfo, int portal, struct login
buf_append(request_body, "jnlpReady=jnlpReady&ok=Login&direct=yes&clientVer=4100&prot=https:&internal=no");
append_opt(request_body, "ipv6-support", vpninfo->disable_ipv6 ? "no" : "yes");
append_opt(request_body, "clientos", gpst_os_name(vpninfo));
- append_opt(request_body, "os-version", vpninfo->platname);
+ append_opt(request_body, "os-version", openconnect_get_gp_os_version(vpninfo));
append_opt(request_body, "server", vpninfo->hostname);
append_opt(request_body, "computer", vpninfo->localname);
if (ctx->portal_userauthcookie)
diff --git a/gpst.c b/gpst.c
index 5c24bbd2..0373fce0 100644
--- a/gpst.c
+++ b/gpst.c
@@ -657,7 +657,7 @@ static int gpst_get_config(struct openconnect_info *vpninfo)
append_opt(request_body, "app-version", app_version);
append_opt(request_body, "ipv6-support", vpninfo->disable_ipv6 ? "no" : "yes");
append_opt(request_body, "clientos", gpst_os_name(vpninfo));
- append_opt(request_body, "os-version", vpninfo->platname);
+ append_opt(request_body, "os-version", openconnect_get_gp_os_version(vpninfo));
append_opt(request_body, "hmac-algo", "sha1,md5,sha256");
append_opt(request_body, "enc-algo", "aes-128-cbc,aes-256-cbc");
if (old_addr || old_addr6) {
@@ -1044,7 +1044,7 @@ static int run_hip_script(struct openconnect_info *vpninfo)
*/
unsetenv("APP_VERSION");
if (setenv("APP_VERSION", openconnect_get_gp_app_version(vpninfo), 1))
- goto out;
+ goto out;
execv(hip_argv[0], (char **)hip_argv);
diff --git a/library.c b/library.c
index 18334c76..e2169054 100644
--- a/library.c
+++ b/library.c
@@ -897,6 +897,7 @@ void openconnect_vpninfo_free(struct openconnect_info *vpninfo)
free(vpninfo->localname);
free(vpninfo->useragent);
free(vpninfo->gp_app_version);
+ free(vpninfo->gp_os_version);
free(vpninfo->authgroup);
#ifdef HAVE_LIBSTOKEN
if (vpninfo->stoken_pin)
@@ -1034,6 +1035,20 @@ const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo)
return vpninfo->csd_ticket ?: (vpninfo->gp_app_version ?: "6.3.0-33");
}
+int openconnect_set_gp_os_version(struct openconnect_info *vpninfo,
+ const char *gp_os_version)
+{
+ UTF8CHECK(gp_os_version);
+
+ STRDUP(vpninfo->gp_os_version, gp_os_version);
+ return 0;
+}
+
+const char *openconnect_get_gp_os_version(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_os_version ?: vpninfo->platname;
+}
+
int openconnect_set_urlpath(struct openconnect_info *vpninfo,
const char *urlpath)
{
diff --git a/openconnect-internal.h b/openconnect-internal.h
index 988f85f0..5c8d2909 100644
--- a/openconnect-internal.h
+++ b/openconnect-internal.h
@@ -787,6 +787,7 @@ struct openconnect_info {
char *useragent;
char *version_string;
char *gp_app_version;
+ char *gp_os_version;
const char *quit_reason;
const char *delay_tunnel_reason; /* If non-null, provides a reason why protocol is not yet ready for tunnel setup */
@@ -1681,6 +1682,9 @@ int handle_external_browser(struct openconnect_info *vpninfo);
/* Get the app version */
const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo);
+/* Get the OS version string for GP */
+const char *openconnect_get_gp_os_version(struct openconnect_info *vpninfo);
+
/* version.c */
extern const char openconnect_version_str[];
diff --git a/openconnect.h b/openconnect.h
index 7d4f3399..aa96a53b 100644
--- a/openconnect.h
+++ b/openconnect.h
@@ -472,6 +472,9 @@ int openconnect_set_useragent(struct openconnect_info *vpninfo,
int openconnect_set_gp_app_version(struct openconnect_info *vpninfo,
const char *gp_app_version);
+int openconnect_set_gp_os_version(struct openconnect_info *vpninfo,
+ const char *gp_os_version);
+
int openconnect_passphrase_from_fsid(struct openconnect_info *vpninfo);
int openconnect_obtain_cookie(struct openconnect_info *vpninfo);
int openconnect_init_ssl(void);
--
2.50.1 (Apple Git-155)
@@ -1,39 +0,0 @@
From 3915a51c81831a1a9b087d82f0c760365682f23b Mon Sep 17 00:00:00 2001
From: Kevin Yue <[email protected]>
Date: Mon, 15 Dec 2025 19:20:44 +0800
Subject: [PATCH 4/4] Add client version and OS information to HIP script
arguments
---
gpst.c | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
diff --git a/gpst.c b/gpst.c
index 0373fce0..d04c42c2 100644
--- a/gpst.c
+++ b/gpst.c
@@ -1013,6 +1013,12 @@ static int run_hip_script(struct openconnect_info *vpninfo)
exit(1);
hip_argv[i++] = openconnect_utf8_to_legacy(vpninfo, vpninfo->csd_wrapper);
+ hip_argv[i++] = "--client-version";
+ hip_argv[i++] = openconnect_get_gp_app_version(vpninfo);
+ hip_argv[i++] = "--client-os";
+ hip_argv[i++] = gpst_os_name(vpninfo);
+ hip_argv[i++] = "--os-version";
+ hip_argv[i++] = openconnect_get_gp_os_version(vpninfo);
hip_argv[i++] = "--cookie";
hip_argv[i++] = vpninfo->cookie;
if (vpninfo->ip_info.addr) {
@@ -1025,8 +1031,6 @@ static int run_hip_script(struct openconnect_info *vpninfo)
}
hip_argv[i++] = "--md5";
hip_argv[i++] = vpninfo->csd_token;
- hip_argv[i++] = "--client-os";
- hip_argv[i++] = gpst_os_name(vpninfo);
hip_argv[i++] = NULL;
/* XX: Sending the above parameters as --long-options was a mistake that was
--
2.50.1 (Apple Git-155)
@@ -1,124 +0,0 @@
diff --git a/gpst.c b/gpst.c
index 244aaf04..78c16d1c 100644
--- a/gpst.c
+++ b/gpst.c
@@ -438,8 +438,19 @@ static int gpst_parse_config_xml(struct openconnect_info *vpninfo, xmlNode *xml_
new_ip_info.netmask = add_option_steal(&new_opts, "netmask", &s);
} else if (!xmlnode_get_val(xml_node, "mtu", &s))
new_ip_info.mtu = atoi(s);
- else if (!xmlnode_get_val(xml_node, "lifetime", &s))
+ else if (!xmlnode_get_val(xml_node, "lifetime", &s)) {
+ vpninfo->gp_session_lifetime = atoi(s);
vpninfo->auth_expiration = time(NULL) + atol(s);
+ } else if (!xmlnode_get_val(xml_node, "user-expires", &s) ||
+ !xmlnode_get_val(xml_node, "user_expires", &s)) {
+ vpninfo->gp_user_expires = atol(s);
+ } else if (!xmlnode_get_val(xml_node, "lifetime-notify-prior", &s)) {
+ vpninfo->gp_lifetime_notify_prior = atoi(s);
+ } else if (!xmlnode_get_val(xml_node, "lifetime-notify-message", &s)) {
+ free(vpninfo->gp_lifetime_notify_message);
+ vpninfo->gp_lifetime_notify_message = s;
+ s = NULL;
+ }
else if (!xmlnode_get_val(xml_node, "quarantine", &s)) {
if (strcmp(s, "no"))
vpn_progress(vpninfo, PRG_DEBUG,
diff --git a/libopenconnect.map.in b/libopenconnect.map.in
index f036c071..44110486 100644
--- a/libopenconnect.map.in
+++ b/libopenconnect.map.in
@@ -113,6 +113,10 @@ OPENCONNECT_5_7 {
openconnect_set_cookie;
openconnect_set_allow_insecure_crypto;
openconnect_get_auth_expiration;
+ openconnect_get_gp_session_lifetime;
+ openconnect_get_gp_user_expires;
+ openconnect_get_gp_lifetime_notify_prior;
+ openconnect_get_gp_lifetime_notify_message;
openconnect_disable_dtls;
openconnect_get_connect_url;
openconnect_set_webview_callback;
diff --git a/libopenconnect5.symbols b/libopenconnect5.symbols
index 7cb04d05..2c7af781 100644
--- a/libopenconnect5.symbols
+++ b/libopenconnect5.symbols
@@ -94,6 +94,10 @@ libopenconnect.so.5 libopenconnect5 #MINVER#
openconnect_set_cookie@OPENCONNECT_5_7 8.20
openconnect_set_allow_insecure_crypto@OPENCONNECT_5_7 8.20
openconnect_get_auth_expiration@OPENCONNECT_5_7 8.20
+ openconnect_get_gp_session_lifetime@OPENCONNECT_5_7 8.20
+ openconnect_get_gp_user_expires@OPENCONNECT_5_7 8.20
+ openconnect_get_gp_lifetime_notify_prior@OPENCONNECT_5_7 8.20
+ openconnect_get_gp_lifetime_notify_message@OPENCONNECT_5_7 8.20
openconnect_disable_dtls@OPENCONNECT_5_7 8.20
openconnect_get_connect_url@OPENCONNECT_5_7 8.20
openconnect_set_webview_callback@OPENCONNECT_5_7 8.20
diff --git a/library.c b/library.c
index b5e74e9b..03f47004 100644
--- a/library.c
+++ b/library.c
@@ -838,6 +838,7 @@ void openconnect_vpninfo_free(struct openconnect_info *vpninfo)
free(vpninfo->dtls_cipher);
free(vpninfo->peer_cert_hash);
free(vpninfo->ciphersuite_config);
+ free(vpninfo->gp_lifetime_notify_message);
#if defined(OPENCONNECT_OPENSSL)
free(vpninfo->cstp_cipher);
#if defined(HAVE_BIO_METH_FREE)
@@ -1137,6 +1138,26 @@ time_t openconnect_get_auth_expiration(struct openconnect_info *vpninfo)
return vpninfo->auth_expiration;
}
+int openconnect_get_gp_session_lifetime(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_session_lifetime;
+}
+
+time_t openconnect_get_gp_user_expires(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_user_expires;
+}
+
+int openconnect_get_gp_lifetime_notify_prior(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_lifetime_notify_prior;
+}
+
+const char *openconnect_get_gp_lifetime_notify_message(struct openconnect_info *vpninfo)
+{
+ return vpninfo->gp_lifetime_notify_message;
+}
+
int openconnect_get_ip_info(struct openconnect_info *vpninfo,
const struct oc_ip_info **info,
const struct oc_vpn_option **cstp_options,
diff --git a/openconnect-internal.h b/openconnect-internal.h
index abf45bbd..dd5507ca 100644
--- a/openconnect-internal.h
+++ b/openconnect-internal.h
@@ -647,6 +647,10 @@ struct openconnect_info {
int dtls_attempt_period;
int udp_probes_sent;
time_t auth_expiration;
+ int gp_session_lifetime;
+ time_t gp_user_expires;
+ int gp_lifetime_notify_prior;
+ char *gp_lifetime_notify_message;
time_t new_dtls_started;
#if defined(OPENCONNECT_OPENSSL)
SSL_CTX *dtls_ctx;
diff --git a/openconnect.h b/openconnect.h
index 136f181a..febf15cc 100644
--- a/openconnect.h
+++ b/openconnect.h
@@ -655,6 +655,10 @@ void openconnect_set_dpd(struct openconnect_info *, int min_seconds);
void openconnect_set_trojan_interval(struct openconnect_info *, int seconds);
int openconnect_get_idle_timeout(struct openconnect_info *);
time_t openconnect_get_auth_expiration(struct openconnect_info *);
+int openconnect_get_gp_session_lifetime(struct openconnect_info *);
+time_t openconnect_get_gp_user_expires(struct openconnect_info *);
+int openconnect_get_gp_lifetime_notify_prior(struct openconnect_info *);
+const char *openconnect_get_gp_lifetime_notify_message(struct openconnect_info *);
/* The returned structures are owned by the library and may be freed/replaced
due to rekey or reconnect. Assume that once the mainloop starts, the
@@ -1,15 +0,0 @@
diff --git a/gpst.c b/gpst.c
index 244aaf04..fb8d945d 100644
--- a/gpst.c
+++ b/gpst.c
@@ -669,6 +669,10 @@ static int gpst_get_config(struct openconnect_info *vpninfo)
result = do_https_request(vpninfo, "POST", "application/x-www-form-urlencoded", request_body, &xml_buf, NULL, HTTP_NO_FLAGS);
free(vpninfo->urlpath);
vpninfo->urlpath = orig_path;
+ if (result >= 0 && xml_buf)
+ vpn_progress(vpninfo, PRG_DEBUG,
+ "GlobalProtect getconfig.esp response:\n%s\n",
+ xml_buf);
/* parse getconfig result */
if (result >= 0)
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff. Show more