Compare commits

..
39 Commits
Author SHA1 Message Date
Kevin Yue 2bce296f05 chore: cut 2.3.13 2026-04-19 11:03:27 +08:00
Kevin Yue 0e32dab997 fix: update 2.3.x package and release flow 2026-04-19 10:58:39 +08:00
Kevin Yue 6db0ed726a ci: rename publish to publish-ppa 2026-04-19 09:43:54 +08:00
Kevin Yue 2a089f69d1 ci: align release workflow matrix with build 2026-04-19 09:24:55 +08:00
Kevin Yue ef4770c0dd Release 2.3.12 2026-04-19 09:00:50 +08:00
Kevin Yue 21822074a8 fix: support custom VPN ports on 2.3.x 2026-04-19 08:37:05 +08:00
Kevin Yue e0db4631ca chore: pin vendored openssl in lockfile 2026-04-19 00:46:43 +08:00
Kevin Yue e733b38ab7 refactor: backport xmltree parser migration to 2.3.x 2026-04-19 00:40:00 +08:00
Kevin Yue c206e72885 docs: note epel and restore rpm appindicator deps 2026-04-19 00:24:59 +08:00
Kevin Yue c1f00aca82 chore: refresh lockfile deps for Rust 1.71 2026-04-19 00:13:18 +08:00
Kevin Yue d28c567e95 chore: add ayatana appindicator rpm runtime dep 2026-04-19 00:00:27 +08:00
Kevin Yue e305af607b chore: add ayatana appindicator rpm build dep 2026-04-18 23:53:31 +08:00
Kevin Yue af903f5d5b ci: run build-gp on arm64 2026-04-18 23:28:54 +08:00
Kevin Yue 745e72892d ci: always include arm64 in build matrix 2026-04-18 23:25:01 +08:00
Kevin Yue ce7df6ea5c ci: add 2.3.x branch to workflow triggers 2026-04-18 23:18:09 +08:00
Kevin Yue a269a60e93 Merge pull request #593 from yuezk/codex/backport-openconnect-2.3 2026-04-18 11:16:11 -04:00
Kevin Yue 3bb27f0193 ci: use GitHub hosted arm action runner 2026-04-18 23:05:38 +08:00
Kevin Yue 3028224bd2 backport browser flag default value support 2026-04-18 23:01:26 +08:00
Kevin Yue 2576b08a89 backport remote browser and arm64 runner updates 2026-04-18 22:54:25 +08:00
Kevin Yue 19106150dd fix: bump wry to 0.24.12 2026-04-18 22:26:37 +08:00
Kevin Yue 11c4a16f73 fix: fall back to direct gmp linking 2026-04-18 22:05:59 +08:00
Kevin Yue 90d3f409d6 fix: force utf-8 locale for debmake 2026-04-18 21:55:36 +08:00
Kevin Yue 56835a5c4d ci: add 2.3.x pull request builds 2026-04-18 21:42:12 +08:00
Kevin Yue 46564ed65d ci: only run 2.3.x builds for pull requests 2026-04-18 21:40:52 +08:00
Kevin Yue 06a25354a7 Revert "ci: use tauri2 builders for 2.3.x pushes"
This reverts commit 7e4f65b1c8.
2026-04-18 21:39:14 +08:00
Kevin Yue 7e4f65b1c8 ci: use tauri2 builders for 2.3.x pushes 2026-04-18 21:37:29 +08:00
Kevin Yue fd4702c2f4 ci: use artifact actions v4 2026-04-18 21:28:38 +08:00
Kevin Yue 8785f7308a ci: use artifact actions v4 2026-04-18 21:28:22 +08:00
Kevin Yue e18d6d3ed0 ci: trigger 2.3.x pull request builds 2026-04-18 21:26:49 +08:00
Kevin Yue f754a7f3c7 Backport vendored openconnect and HIP flow 2026-04-18 20:21:10 +08:00
Kevin Yue 51c55376e8 ci: use gh to download release asset 2025-01-21 22:48:40 +08:00
Kevin Yue 26d5d5bcf0 Release 2.3.11 2025-01-21 21:37:56 +08:00
Kevin Yue b99053718a ci: upload offline tarball 2025-01-21 21:11:03 +08:00
Kevin Yue 6e603c84b3 chore: pin rust version 1.71.1 2025-01-21 20:18:06 +08:00
Kevin Yue eeb60125e6 ci: update publish PPA action 2025-01-21 00:54:43 +08:00
Kevin Yue 875c463bc2 ci: update publish PPA action 2025-01-21 00:46:03 +08:00
Kevin Yue 8cc73df3d6 Release 2.3.10 2025-01-21 00:06:02 +08:00
Kevin Yue fd3ff7b0de Do not use default value for os version 2025-01-21 00:05:46 +08:00
Kevin Yue 72a83f12d0 fix: disconnect VPN when sleep 2025-01-20 20:17:18 +08:00
332 changed files with 11495 additions and 49420 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
+20 -38
View File
@@ -1,4 +1,4 @@
FROM ubuntu:22.04
FROM ubuntu:18.04
ARG USERNAME=vscode
ARG USER_UID=1000
@@ -7,63 +7,45 @@ ARG USER_GID=$USER_UID
ENV RUSTUP_HOME=/usr/local/rustup \
CARGO_HOME=/usr/local/cargo \
PATH=/usr/local/cargo/bin:$PATH \
RUST_VERSION=1.89.0 \
DEBIAN_FRONTEND=noninteractive
RUST_VERSION=1.75.0
# Install all system dependencies in a single layer and clean up apt cache
RUN set -eux; \
apt-get update; \
apt-get install -y --no-install-recommends \
# Common utilities
dh-autoreconf \
sudo \
ca-certificates \
curl \
gnupg \
git \
less \
wget \
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
RUN set -eux; \
libwebkit2gtk-4.0-dev build-essential wget libssl-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev; \
# Install openconnect
add-apt-repository ppa:yuezk/globalprotect-openconnect; \
apt-get update; \
apt-get install -y openconnect libopenconnect-dev; \
# Create a non-root user
groupadd --gid $USER_GID $USERNAME; \
useradd --uid $USER_UID --gid $USER_GID -m $USERNAME; \
echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME; \
chmod 0440 /etc/sudoers.d/$USERNAME
# Install Rust
RUN set -eux; \
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain $RUST_VERSION --profile minimal; \
chmod 0440 /etc/sudoers.d/$USERNAME; \
# Install Node.js
mkdir -p /etc/apt/keyrings; \
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg; \
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_16.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list; \
apt-get update; \
apt-get install -y nodejs; \
corepack enable; \
# Install diff-so-fancy
npm install -g diff-so-fancy; \
# Install Rust
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; \
rustup --version; \
cargo --version; \
rustc --version
# Install Node.js and global npm packages
RUN set -eux; \
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -; \
apt-get install -y --no-install-recommends nodejs; \
corepack enable; \
npm install -g diff-so-fancy; \
# Clean up apt cache
apt-get clean; \
rm -rf /var/lib/apt/lists/*
USER $USERNAME
# Install Oh My Zsh
-6
View File
@@ -1,6 +0,0 @@
.build
.git
.vendor
apps/gpgui-helper/node_modules
target
vendor.tar.xz
-4
View File
@@ -8,9 +8,5 @@ end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[{*.c,*.h}]
indent_style = tab
indent_size = 8
[{Makefile,Makefile.in}]
indent_style = tab
+30
View File
@@ -0,0 +1,30 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Logs**
- For the GUI version, you can find the logs at `~/.local/share/gpclient/gpclient.log`
- For the CLI version, copy the output of the `gpclient` command.
**Environment:**
- OS: [e.g. Ubuntu 22.04]
- Desktop Environment: [e.g. GNOME or KDE]
- Output of `ps aux | grep 'gnome-keyring\|kwalletd5' | grep -v grep`: [Required for secure store error]
- Is remote SSH? [Yes/No]
**Additional context**
Add any other context about the problem here.
-115
View File
@@ -1,115 +0,0 @@
name: Bug report
description: Report a problem with GP Connect or gpclient.
body:
- type: markdown
attributes:
value: |
Thank you for reporting a problem. You can report against your installed version; you do not need to upgrade first.
Review everything before posting. Remove passwords, cookies, tokens, SAML payloads, and private VPN addresses. Do not attach a complete environment dump.
- type: dropdown
id: component
attributes:
label: Affected component
options:
- CLI connection
- GP Connect GUI
- Login window or browser authentication
- Installation or update
- Credential storage
- Other or unsure
validations:
required: true
- type: input
id: version
attributes:
label: Application version
description: Run gpclient --version, or use the version shown in the GUI's About dialog. Include helper versions if relevant.
placeholder: "For example: gpclient 3.0.1"
validations:
required: true
- type: dropdown
id: installation
attributes:
label: Installation method
options:
- APT
- AUR
- RPM package or repository
- Nix
- Homebrew
- Downloaded release package
- FreeBSD or OpenBSD package
- Source build
- Other or unknown
validations:
required: true
- type: input
id: os
attributes:
label: Operating system and version
description: Include the Linux distribution, macOS version, or FreeBSD/OpenBSD version, and architecture if known.
placeholder: "For example: Fedora 43 x86_64, macOS 26 arm64, or FreeBSD 14.4 amd64"
validations:
required: true
- type: textarea
id: reproduction
attributes:
label: Steps to reproduce
description: Include the exact command and options, or the GUI steps. Replace private portal names with a placeholder and omit credentials.
placeholder: |
1. Run sudo gpclient connect <portal> --browser
2. ...
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected behavior
validations:
required: true
- type: textarea
id: actual
attributes:
label: Actual behavior
description: Describe the failure and any error message.
validations:
required: true
- type: textarea
id: regression
attributes:
label: Last working version and recent changes
description: If this worked before, give the last working app version and any recent OS, desktop, graphics driver, or package updates. It is okay if you do not know.
- type: textarea
id: diagnostics
attributes:
label: Diagnostics
description: Run gpclient diagnostics as your normal desktop user, without sudo. If the command is unavailable, use the standalone script linked below or provide the relevant information manually. Reports include raw desktop identifiers and are not guaranteed anonymous; review before posting.
render: text
- type: markdown
attributes:
value: |
**Older versions:** download and inspect the [standalone diagnostic script](https://github.com/yuezk/GlobalProtect-openconnect/blob/dev/scripts/collect-diagnostics.sh), then run it with `sh collect-diagnostics.sh`. See [collection instructions](https://github.com/yuezk/GlobalProtect-openconnect/blob/dev/docs/diagnostics.md). Do not pipe a download directly into a shell.
If you cannot run either collector, provide the relevant details below. You do not need graphics details for unrelated connection problems.
- type: textarea
id: rendering
attributes:
label: Window or rendering failures only
description: Desktop/compositor and version; Wayland or X11; GPU and driver version; GTK/WebKitGTK version when available; VM or remote session; any rendering environment overrides. Skip for unrelated problems. The diagnostics report may already contain this information.
- type: textarea
id: authentication
attributes:
label: Authentication or credential storage failures only
description: Embedded login window or external browser (name/version)? At what stage does it stop? For credential storage errors, include the keyring implementation or macOS Keychain error. Omit cookies, tokens, passwords, and SAML data.
- type: textarea
id: logs
attributes:
label: Relevant logs
description: For the CLI, paste relevant terminal output. For the GUI, use its built-in option to open or export logs, if available. Review and remove sensitive authentication data before posting; avoid full verbose logs unless requested.
render: text
- type: textarea
id: screenshots
attributes:
label: Screenshots and additional context
description: Attach screenshots if helpful. Hide private portal names, account details, and other sensitive content.
-98
View File
@@ -1,98 +0,0 @@
name: Build Linux GUI
on:
workflow_call:
inputs:
gp_ref:
required: true
type: string
gpgui_ref:
required: true
type: string
channel:
required: true
type: string
builder:
required: true
type: string
artifact_suffix:
default: ""
type: string
verify_desktop_assets:
default: false
type: boolean
secrets:
GH_PAT:
required: true
jobs:
build:
strategy:
fail-fast: false
matrix:
os:
- runner: ubuntu-latest
arch: amd64
- runner: ubuntu-24.04-arm
arch: ubuntu-24.04-arm
runs-on: ${{ matrix.os.runner }}
name: build (${{ matrix.os.arch }})
steps:
- uses: pnpm/action-setup@v5
with:
version: 9
- name: Prepare workspace
run: rm -rf gpgui-source && mkdir gpgui-source
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ inputs.gp_ref }}
path: gpgui-source/gp
submodules: recursive
- name: Checkout gpgui
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/gpgui
ref: ${{ inputs.gpgui_ref }}
path: gpgui-source/gpgui
- name: Verify Linux desktop assets
if: matrix.os.arch == 'amd64' && inputs.verify_desktop_assets
run: gpgui-source/gp/scripts/verify-linux-desktop-assets.sh gpgui-source/gpgui
- name: Tarball
run: |
cd gpgui-source
tar -czf gpgui.tar.gz gpgui gp
- name: Build gpgui in Docker
env:
GPGUI_BUILDER: ${{ inputs.builder }}
GPGUI_BUILD_VERSION: ${{ github.run_number }}.${{ github.run_attempt }}
GPGUI_UPDATE_CHANNEL: ${{ inputs.channel }}
GPGUI_LICENSE_SIGNING_KEYS: ${{ vars.GPGUI_LICENSE_SIGNING_KEYS }}
run: |
docker run --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-e GPGUI_BUILD_VERSION \
-e GPGUI_UPDATE_CHANNEL \
-e GPGUI_LICENSE_SIGNING_KEYS \
-v "$(pwd)/gpgui-source:/workspace" "yuezk/gpdev:$GPGUI_BUILDER"
- name: Install gpgui in Docker
env:
GPGUI_BUILDER: ${{ inputs.builder }}
run: |
cd gpgui-source
tar -xJf ./*.bin.tar.xz
docker run --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-v "$(pwd):/workspace" "yuezk/gpdev:$GPGUI_BUILDER" \
bash -c "cd /workspace/gpgui_*/ && ./gpgui --version"
- name: Upload gpgui
uses: actions/upload-artifact@v7
with:
name: artifact-gpgui${{ inputs.artifact_suffix }}-${{ matrix.os.arch }}
if-no-files-found: error
path: |
gpgui-source/*.bin.tar.xz
gpgui-source/*.bin.tar.xz.sha256
File diff suppressed because it is too large. Load diff
-118
View File
@@ -1,118 +0,0 @@
name: Nix
on:
pull_request:
paths:
- "flake.nix"
- "flake.lock"
- "nix/**"
- ".github/workflows/nix.yaml"
push:
branches:
- main
paths:
- "flake.nix"
- "flake.lock"
- "nix/**"
- ".github/workflows/nix.yaml"
permissions:
contents: read
jobs:
standalone-package:
name: standalone-package (${{ matrix.platform.system }})
strategy:
fail-fast: false
matrix:
platform:
- runner: ubuntu-latest
system: x86_64-linux
- runner: ubuntu-24.04-arm
system: aarch64-linux
runs-on: ${{ matrix.platform.runner }}
steps:
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
- name: Install Nix
uses: cachix/install-nix-action@v31
- name: Build standalone prebuilt package
run: |
nix build .#prebuilt \
--extra-experimental-features "nix-command flakes" \
--print-build-logs
- name: Inspect prebuilt package
run: |
test -x result/bin/gpclient
test -x result/bin/gpauth
test -x result/bin/gpservice
test -x result/bin/gpgui-helper
test -x result/bin/gpgui
nixos-module:
name: nixos-module (${{ matrix.platform.system }}, ${{ matrix.nixpkgs }})
strategy:
fail-fast: false
matrix:
platform:
- runner: ubuntu-latest
system: x86_64-linux
- runner: ubuntu-24.04-arm
system: aarch64-linux
nixpkgs:
- nixos-25.11
- nixos-26.05
- nixpkgs-unstable
runs-on: ${{ matrix.platform.runner }}
steps:
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
- name: Install Nix
uses: cachix/install-nix-action@v31
- name: Build package through host NixOS module
env:
NIXPKGS_URL: github:NixOS/nixpkgs/${{ matrix.nixpkgs }}
NIX_SYSTEM: ${{ matrix.platform.system }}
run: |
nix build \
--impure \
--extra-experimental-features "nix-command flakes" \
--print-build-logs \
--expr '
let
gp = builtins.getFlake (toString ./.);
hostNixpkgs =
builtins.getFlake (builtins.getEnv "NIXPKGS_URL");
hostSystem = hostNixpkgs.lib.nixosSystem {
system = builtins.getEnv "NIX_SYSTEM";
modules = [
gp.nixosModules.default
{
programs.globalprotect-openconnect.enable = true;
system.stateVersion = "25.11";
}
];
};
package =
hostSystem.config.programs.globalprotect-openconnect.package;
in
assert builtins.elem package
hostSystem.config.environment.systemPackages;
assert hostSystem.config.services.ayatana-indicators.enable;
package
'
- name: Inspect module package
run: |
test -x result/bin/gpclient
test -x result/bin/gpauth
test -x result/bin/gpservice
test -x result/bin/gpgui-helper
test -x result/bin/gpgui
-175
View File
@@ -1,175 +0,0 @@
name: Publish AUR git package
on:
workflow_dispatch:
inputs:
build-package:
type: boolean
description: "Build the package before publishing"
required: true
default: true
publish:
type: boolean
description: "Push PKGBUILD, .SRCINFO, and gp.install to AUR"
required: true
default: true
push:
branches:
- main
paths:
- packaging/aur/globalprotect-openconnect-git/**
- .github/workflows/publish-aur-git.yaml
permissions:
contents: read
jobs:
validate:
name: Validate AUR package
runs-on: ubuntu-latest
container: archlinux:base-devel
defaults:
run:
shell: bash
env:
AUR_PACKAGE_DIR: packaging/aur/globalprotect-openconnect-git
steps:
- name: Install checkout tools
run: pacman -Syu --noconfirm --needed git openssh
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
- name: Install build tools
run: |
pacman -Syu --noconfirm --needed \
appmenu-gtk-module \
cargo \
curl \
desktop-file-utils \
file \
git \
libappindicator-gtk3 \
libsecret \
libxml2 \
namcap \
openconnect \
openssl \
pkgconf \
librsvg \
shared-mime-info \
vpnc \
wget \
webkit2gtk-4.1
- name: Save committed .SRCINFO
if: ${{ github.event_name == 'push' }}
run: cp "$AUR_PACKAGE_DIR/.SRCINFO" /tmp/committed.SRCINFO
- name: Prepare build user
run: |
useradd -m builder
chown -R builder:builder "$GITHUB_WORKSPACE"
- name: Refresh VCS package version
if: ${{ github.event_name == 'workflow_dispatch' }}
run: |
cd "$AUR_PACKAGE_DIR"
runuser -u builder -- makepkg --nobuild --noconfirm --cleanbuild
- name: Regenerate .SRCINFO
run: |
cd "$AUR_PACKAGE_DIR"
runuser -u builder -- makepkg --printsrcinfo > .SRCINFO
- name: Check committed .SRCINFO
if: ${{ github.event_name == 'push' }}
run: |
cmp -s /tmp/committed.SRCINFO "$AUR_PACKAGE_DIR/.SRCINFO" || {
diff -u /tmp/committed.SRCINFO "$AUR_PACKAGE_DIR/.SRCINFO"
echo ".SRCINFO is out of date. Regenerate it with makepkg --printsrcinfo." >&2
exit 1
}
- name: Run namcap
run: |
cd "$AUR_PACKAGE_DIR"
runuser -u builder -- namcap PKGBUILD
- name: Build package
if: ${{ github.event_name == 'workflow_dispatch' && inputs['build-package'] }}
run: |
cd "$AUR_PACKAGE_DIR"
runuser -u builder -- makepkg --noconfirm --clean --cleanbuild
- name: Upload AUR package metadata
if: ${{ github.event_name == 'workflow_dispatch' && inputs.publish }}
uses: actions/upload-artifact@v7
with:
name: aur-package-metadata
path: |
${{ env.AUR_PACKAGE_DIR }}/PKGBUILD
${{ env.AUR_PACKAGE_DIR }}/.SRCINFO
${{ env.AUR_PACKAGE_DIR }}/gp.install
if-no-files-found: error
include-hidden-files: true
overwrite: true
publish:
name: Publish to AUR
needs: validate
if: ${{ github.event_name == 'workflow_dispatch' && inputs.publish }}
runs-on: ubuntu-latest
container: archlinux:base-devel
defaults:
run:
shell: bash
env:
AUR_PACKAGE_DIR: /tmp/aur-package
AUR_REPO: ssh://[email protected]/globalprotect-openconnect-git.git
steps:
- name: Install publish tools
run: pacman -Syu --noconfirm --needed git openssh
- name: Download AUR package metadata
uses: actions/download-artifact@v8
with:
name: aur-package-metadata
path: ${{ env.AUR_PACKAGE_DIR }}
- name: Configure SSH
env:
AUR_SSH_PRIVATE_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
run: |
if [[ -z "$AUR_SSH_PRIVATE_KEY" ]]; then
echo "AUR_SSH_PRIVATE_KEY is required to publish to AUR" >&2
exit 1
fi
install -d -m 700 ~/.ssh
printf '%s\n' "$AUR_SSH_PRIVATE_KEY" > ~/.ssh/aur
chmod 600 ~/.ssh/aur
ssh-keyscan -t rsa,ecdsa,ed25519 aur.archlinux.org > ~/.ssh/known_hosts
- name: Publish to AUR
env:
GIT_SSH_COMMAND: ssh -i /github/home/.ssh/aur -o UserKnownHostsFile=/github/home/.ssh/known_hosts -o StrictHostKeyChecking=yes
run: |
workdir="$(mktemp -d)"
git clone "$AUR_REPO" "$workdir/aur"
cp "$AUR_PACKAGE_DIR"/PKGBUILD "$workdir/aur/PKGBUILD"
cp "$AUR_PACKAGE_DIR"/.SRCINFO "$workdir/aur/.SRCINFO"
cp "$AUR_PACKAGE_DIR"/gp.install "$workdir/aur/gp.install"
cd "$workdir/aur"
if git diff --quiet; then
echo "AUR package is already up to date"
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add PKGBUILD .SRCINFO gp.install
git commit -m "Update globalprotect-openconnect-git"
git push origin master
-143
View File
@@ -1,143 +0,0 @@
name: Publish COPR
on:
workflow_dispatch:
inputs:
tag:
description: 'Tag to publish'
required: true
revision:
description: 'Package revision'
type: string
required: true
default: "1"
build_id:
description: 'Existing Copr build ID to verify; leave empty to submit a new build'
type: string
required: false
distros:
description: 'Space-separated distro releases, e.g. fedora-44 fedora-45; all configured architectures are included'
type: string
required: false
concurrency:
group: publish-copr
cancel-in-progress: false
permissions:
contents: read
jobs:
publish-copr:
runs-on: ubuntu-latest
container: fedora:latest
timeout-minutes: 210
defaults:
run:
shell: bash
steps:
- name: Install tools
run: dnf install -y copr-cli gh python3 zstd
- uses: actions/checkout@v6
- name: Check inputs
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ inputs.tag }}
REVISION: ${{ inputs.revision }}
run: |
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ || ! "$REVISION" =~ ^[1-9][0-9]*$ ]]; then
echo "Expected a stable vX.Y.Z tag and positive package revision" >&2
exit 1
fi
gh api "repos/${{ github.repository }}/git/ref/tags/$TAG" >/dev/null
- name: Resolve publication distros
id: targets
env:
DISTROS: ${{ inputs.distros }}
BUILD_ID: ${{ inputs.build_id }}
run: |
build_args=()
if [[ -n "$BUILD_ID" ]]; then
build_args+=(--build-id "$BUILD_ID")
fi
python3 scripts/select-publication-targets.py copr \
--distros "$DISTROS" "${build_args[@]}"
- name: Download published spec
if: ${{ inputs.build_id == '' }}
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ inputs.tag }}
run: |
mkdir -p publish-copr
gh release download "$TAG" \
--repo "${{ github.repository }}" \
--pattern globalprotect-openconnect.spec \
--dir publish-copr
- name: Set package revision
if: ${{ inputs.build_id == '' }}
env:
REVISION: ${{ inputs.revision }}
run: |
spec=publish-copr/globalprotect-openconnect.spec
if [[ "$(grep -c '^Release:' "$spec")" -ne 1 ]]; then
echo "Expected exactly one Release field in $spec" >&2
exit 1
fi
sed -Ei \
"s/^Release:[[:space:]]+.*/Release: ${REVISION}%{?dist}/" \
"$spec"
grep '^Release:' "$spec"
- name: Configure COPR authentication
if: ${{ inputs.build_id == '' }}
env:
COPR_CONFIG: ${{ secrets.COPR_CONFIG }}
run: |
install -d -m 700 "$HOME/.config"
printf '%s\n' "$COPR_CONFIG" > "$HOME/.config/copr"
chmod 600 "$HOME/.config/copr"
- name: Submit or select Copr build
id: build
env:
EXISTING_BUILD_ID: ${{ inputs.build_id }}
CHROOTS: ${{ steps.targets.outputs.targets }}
run: |
set -euo pipefail
build_id="$EXISTING_BUILD_ID"
if [[ -z "$build_id" ]]; then
read -r -a chroots <<< "$CHROOTS"
chroot_args=()
for chroot in "${chroots[@]}"; do
chroot_args+=(--chroot "$chroot")
done
copr-cli build --nowait yuezk/globalprotect-openconnect \
"${chroot_args[@]}" \
publish-copr/globalprotect-openconnect.spec | tee copr-submission.log
build_id="$(sed -n 's/^Created builds: \([0-9][0-9]*\)$/\1/p' copr-submission.log)"
fi
[[ "$build_id" =~ ^[0-9]+$ ]]
echo "id=$build_id" >> "$GITHUB_OUTPUT"
echo "Copr build: https://copr.fedorainfracloud.org/coprs/yuezk/globalprotect-openconnect/build/$build_id/" \
>> "$GITHUB_STEP_SUMMARY"
- name: Wait for Copr builds and public repositories
env:
TAG: ${{ inputs.tag }}
REVISION: ${{ inputs.revision }}
BUILD_ID: ${{ steps.build.outputs.id }}
CHROOTS: ${{ steps.targets.outputs.targets }}
run: |
read -r -a chroots <<< "$CHROOTS"
python3 scripts/wait-for-publication.py copr \
--chroots "${chroots[@]}" \
--build-id "$BUILD_ID" --version "${TAG#v}" --revision "$REVISION"
-112
View File
@@ -1,112 +0,0 @@
name: Publish OBS
on:
workflow_dispatch:
inputs:
tag:
description: 'Tag to publish'
required: true
revision:
description: 'Package revision'
type: string
required: true
default: "1"
verify_only:
description: 'Verify the existing source and publication without uploading again'
type: boolean
default: false
repositories:
description: 'Space-separated distro repositories, e.g. 16.0 openSUSE_Tumbleweed; empty keeps enabled targets'
type: string
required: false
concurrency:
group: publish-obs
cancel-in-progress: false
permissions:
contents: read
jobs:
publish-obs:
runs-on: ubuntu-latest
timeout-minutes: 210
steps:
- uses: actions/checkout@v6
- name: Install metadata decompressor
run: sudo apt-get update && sudo apt-get install -y zstd
- name: Check inputs
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ inputs.tag }}
REVISION: ${{ inputs.revision }}
run: |
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ || ! "$REVISION" =~ ^[1-9][0-9]*$ ]]; then
echo "Expected a stable vX.Y.Z tag and positive package revision" >&2
exit 1
fi
gh api "repos/${{ github.repository }}/git/ref/tags/$TAG" >/dev/null
- name: Prepare OBS package
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ inputs.tag }}
REVISION: ${{ inputs.revision }}
run: |
version="${TAG#v}"
archive="globalprotect-openconnect-${version}.offline.tar.gz"
source_dir="publish-obs/source/globalprotect-openconnect-${version}"
mkdir -p publish-obs/files publish-obs/source
gh release download "$TAG" \
--repo "${{ github.repository }}" \
--pattern "$archive" \
--dir publish-obs
tar -xzf "publish-obs/$archive" -C publish-obs/source
make -C "$source_dir" init-rpm \
REVISION="$REVISION" \
RPM_SOURCE='%{name}.tar.gz'
mv "publish-obs/$archive" \
publish-obs/files/globalprotect-openconnect.tar.gz
cp "$source_dir/.build/rpm/globalprotect-openconnect.spec" \
"$source_dir/.build/rpm/globalprotect-openconnect.changes" \
publish-obs/files/
- name: Select OBS publication targets
env:
REPOSITORIES: ${{ inputs.repositories }}
VERIFY_ONLY: ${{ inputs.verify_only }}
OBS_USERNAME: yuezk
OBS_PASSWORD: ${{ secrets.OBS_PASSWORD }}
run: |
verify_args=()
if [[ "$VERIFY_ONLY" == 'true' ]]; then
verify_args+=(--verify-only)
fi
python3 scripts/select-publication-targets.py obs \
--repositories "$REPOSITORIES" "${verify_args[@]}" --output publish-obs/targets.json
- name: Publish OBS package
if: ${{ !inputs.verify_only }}
uses: yuezk/publish-obs-package@main
with:
project: home:yuezk
package: globalprotect-openconnect
username: yuezk
password: ${{ secrets.OBS_PASSWORD }}
files: ./publish-obs/files/*
commit_message: 'Release ${{ inputs.tag }}-${{ inputs.revision }}'
- name: Wait for OBS builds and public repositories
env:
TAG: ${{ inputs.tag }}
REVISION: ${{ inputs.revision }}
run: |
python3 scripts/wait-for-publication.py obs \
--targets-file publish-obs/targets.json \
--version "${TAG#v}" --revision "$REVISION" --files publish-obs/files
+46 -148
View File
@@ -8,189 +8,87 @@ on:
required: true
revision:
description: 'Package revision'
required: false
default: "1"
series:
description: 'Space-separated Ubuntu series. Leave empty to publish all supported series.'
type: "string"
required: false
default: ""
rust:
description: 'Rust version to use'
type: "string"
required: true
default: "1.91"
verify_only:
description: 'Verify an existing upload without building or uploading source again'
default: "1"
ppa:
description: 'Publish to PPA'
type: boolean
default: false
concurrency:
group: publish-ppa
cancel-in-progress: false
defaults:
run:
shell: bash
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:
check:
runs-on: ubuntu-latest
steps:
- name: Check tag exists
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ inputs.tag }}
REVISION: ${{ inputs.revision }}
uses: mukunku/[email protected]
id: check-tag
with:
tag: ${{ inputs.tag }}
- name: Exit if tag does not exist
run: |
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ || ! "$REVISION" =~ ^[1-9][0-9]*$ ]]; then
echo "Expected a stable vX.Y.Z tag and positive package revision" >&2
if [[ "${{ steps.check-tag.outputs.exists }}" == "false" ]]; then
echo "Tag ${{ inputs.tag }} does not exist"
exit 1
fi
if ! gh api "repos/${{ github.repository }}/git/ref/tags/$TAG" >/dev/null 2>&1; then
echo "Tag $TAG does not exist"
exit 1
fi
resolve-series:
needs: check
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.resolve.outputs.matrix }}
steps:
- name: Resolve Ubuntu series
id: resolve
env:
INPUT_SERIES: ${{ inputs.series }}
run: |
sudo apt-get update
sudo apt-get install -y distro-info distro-info-data
if [[ "$INPUT_SERIES" == *","* ]]; then
echo "Use space-separated series, for example: jammy noble" >&2
exit 1
fi
series=()
if [[ -z "${INPUT_SERIES// }" ]]; then
while IFS= read -r item; do
[[ -n "$item" ]] && series+=("$item")
done < <(ubuntu-distro-info --supported)
else
read -r -a series <<< "$INPUT_SERIES"
fi
if [[ "${#series[@]}" -eq 0 ]]; then
echo "No Ubuntu series resolved" >&2
exit 1
fi
declare -A seen=()
for item in "${series[@]}"; do
ubuntu-distro-info --series "$item" >/dev/null
if [[ -n "${seen[$item]+present}" ]]; then
echo "Duplicate Ubuntu series: $item" >&2
exit 1
fi
seen[$item]=1
done
matrix="$(printf '%s\n' "${series[@]}" | jq -R . | jq -s -c '{series: .}')"
echo "Resolved matrix: $matrix"
echo "matrix=$matrix" >> "$GITHUB_OUTPUT"
publish-ppa:
needs: [check, resolve-series]
name: publish-ppa (${{ matrix.series }})
needs: check
if: ${{ inputs.ppa }}
runs-on: ubuntu-latest
timeout-minutes: 210
container:
image: ubuntu:${{ matrix.series }}
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.resolve-series.outputs.matrix) }}
steps:
- name: Install container tools
run: |
apt-get update
apt-get install -y ca-certificates curl gpg sudo python3 distro-info distro-info-data
mkdir -p /etc/apt/keyrings
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg \
| gpg --dearmor -o /etc/apt/keyrings/githubcli-archive-keyring.gpg
chmod go+r /etc/apt/keyrings/githubcli-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" \
> /etc/apt/sources.list.d/github-cli.list
apt-get update
apt-get install -y gh
- uses: actions/checkout@v6
- uses: pnpm/action-setup@v2
with:
version: 8
- name: Prepare workspace
if: ${{ !inputs.verify_only }}
run: rm -rf publish-ppa && mkdir publish-ppa
- name: Download ${{ inputs.tag }} offline source code
if: ${{ !inputs.verify_only }}
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
run: |
gh -R yuezk/GlobalProtect-openconnect \
release download ${{ inputs.tag }} \
--pattern '*.offline.tar.gz' \
--dir publish-ppa
uses: robinraju/[email protected]
with:
token: ${{ secrets.GH_PAT }}
tag: ${{ inputs.tag }}
fileName: globalprotect-openconnect-*.offline.tar.gz
tarBall: false
zipBall: false
out-file-path: publish-ppa
- name: Patch the source code
if: ${{ !inputs.verify_only }}
run: |
cd publish-ppa
# Rename the source tarball without the offline suffix
archives=(./*.offline.tar.gz)
[[ "${#archives[@]}" -eq 1 && -f "${archives[0]}" ]]
archive="${archives[0]%.offline.tar.gz}.tar.gz"
mv -v -- "${archives[0]}" "$archive"
mv *.tar.gz $(basename *.tar.gz .offline.tar.gz).tar.gz
# Extract the source tarball
tar -xzf "$archive"
tar -xzf *.tar.gz
# Prepare the debian directory with custom files
source_dirs=(./globalprotect-openconnect-*/)
[[ "${#source_dirs[@]}" -eq 1 && -d "${source_dirs[0]}" ]]
cd "${source_dirs[0]}"
cd globalprotect-openconnect-*/
# Prepare the debian directory with custom files
mkdir -p .build/debian
cp -v packaging/deb/control.in .build/debian/control
cp -v packaging/deb/rules.in .build/debian/rules
cp -v packaging/deb/compat .build/debian/compat
cp -v packaging/deb/postrm .build/debian/postrm
sed -i "s/@BUILD_GUI_HELPER@/1/g" .build/debian/rules
sed -i "s/@BUILD_WEBVIEW_AUTH@/1/g" .build/debian/rules
# Update the control file with the correct Rust version
sed -i "s/@RUST_VERSION@/${{ inputs.rust }}/g" .build/debian/control
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
sed 's/@RUST@/rust-all(>=1.71)/g' packaging/deb/control.in > .build/debian/control
sed 's/@OFFLINE@/1/g' packaging/deb/rules.in > .build/debian/rules
cp packaging/deb/postrm .build/debian/postrm
- name: Publish to PPA
if: ${{ !inputs.verify_only }}
uses: yuezk/publish-ppa-package@main
uses: yuezk/publish-ppa-package@gp_2.3.x
with:
repository: "yuezk/globalprotect-openconnect"
gpg_private_key: ${{ secrets.PPA_GPG_PRIVATE_KEY }}
gpg_passphrase: ${{ secrets.PPA_GPG_PASSPHRASE }}
tarball: publish-ppa/globalprotect-openconnect-*.tar.gz
debian_dir: publish-ppa/globalprotect-openconnect-*/.build/debian
deb_email: ${{ vars.DEB_EMAIL }}
deb_fullname: ${{ vars.DEB_FULLNAME }}
extra_ppa: "yuezk/globalprotect-openconnect"
series: ${{ matrix.series }}
deb_email: "[email protected]"
deb_fullname: "Kevin Yue"
extra_ppa: "yuezk/globalprotect-openconnect liushuyu-011/rust-bpo-1.75"
series: "bionic focal"
revision: ${{ inputs.revision }}
- name: Wait for Launchpad builds and public package indexes
if: ${{ inputs.verify_only }}
env:
TAG: ${{ inputs.tag }}
REVISION: ${{ inputs.revision }}
SERIES: ${{ matrix.series }}
run: |
ubuntu_version="$(ubuntu-distro-info --series "$SERIES" --release | cut -d' ' -f1)"
python3 scripts/wait-for-publication.py ppa --series "$SERIES" \
--version "${TAG#v}-ppa${REVISION}~ubuntu${ubuntu_version}"
-38
View File
@@ -1,38 +0,0 @@
name: Release infrastructure checks
on:
pull_request:
paths:
- '.github/workflows/**'
- 'scripts/wait-for-publication.py'
- 'scripts/select-publication-targets.py'
- 'scripts/verify-docker-publication.sh'
- 'scripts/tests/test_*publication.py'
push:
branches: [main]
paths:
- '.github/workflows/**'
- 'scripts/wait-for-publication.py'
- 'scripts/select-publication-targets.py'
- 'scripts/verify-docker-publication.sh'
- 'scripts/tests/test_*publication.py'
permissions:
contents: read
jobs:
release-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Validate workflow expressions and schema
run: |
docker run --rm -v "$PWD:/repo" -w /repo \
rhysd/actionlint:1.7.12@sha256:b1934ee5f1c509618f2508e6eb47ee0d3520686341fec936f3b79331f9315667 \
-shellcheck='' -pyflakes=''
- name: Check Docker publication script
run: |
bash -n scripts/verify-docker-publication.sh
shellcheck scripts/verify-docker-publication.sh
- name: Test publication verification
run: python3 -m unittest discover -s scripts/tests -p 'test_*publication.py'
+26 -210
View File
@@ -30,21 +30,11 @@ on:
description: 'Build PKG package'
required: true
default: true
release-apk:
type: boolean
description: 'Build APK package'
required: true
default: true
release-binary:
type: boolean
description: 'Build binary package'
required: true
default: true
release-docker:
type: boolean
description: 'Publish Docker image'
required: true
default: true
gh-release:
type: boolean
description: 'Update GitHub release'
@@ -83,13 +73,16 @@ jobs:
const inputs = ${{ toJson(inputs) }}
const { arch } = inputs
const osMap = {
"all": ["ubuntu-latest", "ubuntu-24.04-arm"],
"x86_64": ["ubuntu-latest"],
"arm64": ["ubuntu-24.04-arm"]
"all": [
{ runner: "ubuntu-latest", arch: "amd64" },
{ runner: "ubuntu-24.04-arm", arch: "ubuntu-24.04-arm" },
],
"x86_64": [{ runner: "ubuntu-latest", arch: "amd64" }],
"arm64": [{ runner: "ubuntu-24.04-arm", arch: "ubuntu-24.04-arm" }],
}
const package = Object.entries(inputs)
.filter(([key, value]) => key.startsWith('release-') && key !== 'release-docker' && value)
.filter(([key, value]) => key.startsWith('release-') && value)
.map(([key, value]) => key.replace('release-', ''))
return JSON.stringify({
@@ -102,7 +95,8 @@ jobs:
- setup-matrix
strategy:
matrix: ${{ fromJson(needs.setup-matrix.outputs.matrix) }}
runs-on: ${{ matrix.os }}
runs-on: ${{ matrix.os.runner }}
name: build (${{ matrix.package }}, ${{ matrix.os.arch }})
steps:
- name: Prepare workspace
run: rm -rf build-${{ matrix.package }} && mkdir -p build-${{ matrix.package }}
@@ -116,227 +110,49 @@ jobs:
--pattern '*[^offline].tar.gz' \
--dir build-${{ matrix.package }}
- name: Docker Login
run: echo ${{ secrets.DOCKER_HUB_TOKEN }} | docker login -u ${{ secrets.DOCKER_HUB_USERNAME }} --password-stdin
- name: Build ${{ matrix.package }} package in Docker
# LIBXML2_STATIC is needed to avoid the dynamic linking issue on different distros
run: |
docker run --rm \
-v $(pwd)/build-${{ matrix.package }}:/workspace \
-e COREPACK_INTEGRITY_KEYS=0 \
-e LIBXML2_STATIC=1 \
-v $(pwd)/build-${{ matrix.package }}:/${{ matrix.package }} \
-e INCLUDE_GUI=1 \
yuezk/gpdev:${{ matrix.package }}-builder-tauri2
yuezk/gpdev:${{ matrix.package }}-builder
- name: Install ${{ matrix.package }} package in Docker
run: |
docker run --rm \
-e COREPACK_INTEGRITY_KEYS=0 \
-v $(pwd)/build-${{ matrix.package }}:/workspace \
yuezk/gpdev:${{ matrix.package }}-builder-tauri2 \
-v $(pwd)/build-${{ matrix.package }}:/${{ matrix.package }} \
yuezk/gpdev:${{ matrix.package }}-builder \
bash install.sh
- name: Upload ${{ matrix.package }} package
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v4
with:
name: artifact-${{ matrix.os }}-${{ matrix.package }}
name: artifact-${{ matrix.os.arch }}-${{ matrix.package }}
if-no-files-found: error
path: |
build-${{ matrix.package }}/artifacts/*
build-docker-image:
needs:
- check
if: ${{ inputs.release-docker }}
strategy:
fail-fast: false
matrix:
include:
- runner: ubuntu-latest
platform: linux/amd64
- runner: ubuntu-24.04-arm
platform: linux/arm64
runs-on: ${{ matrix.runner }}
steps:
- name: Prepare
run: |
platform=${{ matrix.platform }}
echo "PLATFORM_PAIR=${platform//\//-}" >> "$GITHUB_ENV"
- name: Prepare workspace
run: rm -rf docker-image && mkdir -p docker-image/source
- name: Download ${{ inputs.tag }} source code
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
run: |
gh -R yuezk/GlobalProtect-openconnect \
release download ${{ inputs.tag }} \
--pattern '*[^offline].tar.gz' \
--dir docker-image
tar -xzf docker-image/*.tar.gz -C docker-image/source --strip-components=1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Build and push by digest
id: build
uses: docker/build-push-action@v7
with:
context: docker-image/source
file: docker-image/source/packaging/docker/alpine/Dockerfile
platforms: ${{ matrix.platform }}
outputs: type=image,name=yuezk/globalprotect-openconnect,push-by-digest=true,name-canonical=true,push=true
- name: Verify CLI tools
env:
IMAGE: yuezk/globalprotect-openconnect
DIGEST: ${{ steps.build.outputs.digest }}
run: |
docker run --rm "$IMAGE@$DIGEST" --help
docker run --rm --entrypoint gpauth "$IMAGE@$DIGEST" --help
docker run --rm --entrypoint sh "$IMAGE@$DIGEST" -lc 'test "$(id -u gp)" = "1000" && test "$SUDO_UID" = "1000"'
- name: Export digest
run: |
mkdir -p /tmp/digests
digest="${{ steps.build.outputs.digest }}"
touch "/tmp/digests/${digest#sha256:}"
- name: Upload digest
uses: actions/upload-artifact@v7
with:
name: digests-${{ env.PLATFORM_PAIR }}
path: /tmp/digests/*
if-no-files-found: error
retention-days: 1
publish-docker-image:
needs:
- build-docker-image
if: ${{ inputs.release-docker }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Download digests
uses: actions/download-artifact@v8
with:
path: /tmp/digests
pattern: digests-*
merge-multiple: true
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKER_HUB_USERNAME }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}
- name: Publish Docker manifest
working-directory: /tmp/digests
env:
IMAGE: yuezk/globalprotect-openconnect
TAG: ${{ inputs.tag }}
run: |
VERSION="${TAG#v}"
tags=(-t "$IMAGE:$TAG")
if [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
tags+=(-t "$IMAGE:$VERSION" -t "$IMAGE:latest")
fi
docker buildx imagetools create "${tags[@]}" \
$(printf "$IMAGE@sha256:%s " *)
"$GITHUB_WORKSPACE/scripts/verify-docker-publication.sh" "$IMAGE:$TAG" /tmp/digests "${{ inputs.arch }}"
if [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
for alias in "$VERSION" latest; do
"$GITHUB_WORKSPACE/scripts/verify-docker-publication.sh" "$IMAGE:$alias" /tmp/digests "${{ inputs.arch }}"
done
fi
gh-release:
needs:
- build
runs-on: ubuntu-latest
if: ${{ inputs.gh-release }}
outputs:
stable_version: ${{ steps.stable-release.outputs.version }}
permissions:
actions: read
contents: read
id-token: write
attestations: write
artifact-metadata: write
steps:
- name: Prepare workspace
run: rm -rf gh-release && mkdir gh-release
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
with:
token: ${{ secrets.GH_PAT }}
repository: yuezk/GlobalProtect-openconnect
ref: ${{ github.ref }}
path: gh-release/gp
submodules: recursive
- name: Download artifact
uses: actions/download-artifact@v8
uses: actions/download-artifact@v4
with:
path: gh-release
- name: Rename APK artifacts
run: |
shopt -s nullglob
for file in gh-release/artifact-ubuntu-latest-apk/*.apk; do
mv "$file" "${file%.apk}-x86_64.apk"
done
for file in gh-release/artifact-ubuntu-24.04-arm-apk/*.apk; do
mv "$file" "${file%.apk}-aarch64.apk"
done
- name: Generate release asset checksums
run: |
cd gh-release/gp
mkdir -p .build
scripts/release-assets.sh all "$GITHUB_WORKSPACE/gh-release" > .build/release-assets.txt
if [ ! -s .build/release-assets.txt ]; then
echo "No release assets found"
exit 1
fi
while IFS= read -r file; do
digest=$(sha256sum "$file" | cut -d ' ' -f 1)
printf '%s %s\n' "$digest" "$(basename "$file")"
done < .build/release-assets.txt > .build/release-assets.sha256
- name: Attest release assets
uses: actions/attest-build-provenance@v4
- name: Update release
uses: softprops/action-gh-release@v1
with:
subject-checksums: gh-release/gp/.build/release-assets.sha256
- name: Upload release assets
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
run: |
mapfile -t files < gh-release/gp/.build/release-assets.txt
if [[ "${{ inputs.tag }}" == "snapshot" ]]; then
for file in "${files[@]}"; do
gh release upload snapshot "$file" --clobber \
--repo yuezk/GlobalProtect-openconnect
done
else
gh-release/gp/scripts/upload-release-assets.sh "${{ inputs.tag }}" "${files[@]}"
fi
- name: Resolve stable release version
id: stable-release
env:
TAG: ${{ inputs.tag }}
run: |
if [[ "$TAG" =~ ^v([0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
echo "version=${BASH_REMATCH[1]}" >> "$GITHUB_OUTPUT"
fi
update-flake-hashes:
needs: gh-release
if: ${{ inputs.release-binary && inputs.arch == 'all' && needs.gh-release.outputs.stable_version != '' }}
permissions:
contents: write
pull-requests: write
uses: ./.github/workflows/update-flake-hashes.yaml
with:
version: ${{ needs.gh-release.outputs.stable_version }}
release_tag: ${{ inputs.tag }}
token: ${{ secrets.GH_PAT }}
prerelease: ${{ contains(github.ref, 'snapshot') }}
fail_on_unmatched_files: true
tag_name: ${{ inputs.tag }}
files: |
gh-release/artifact-*/*
-148
View File
@@ -1,148 +0,0 @@
name: Update flake hashes
on:
workflow_call:
inputs:
version:
required: true
type: string
release_tag:
required: true
type: string
workflow_dispatch:
inputs:
version:
description: "Release version. Defaults to Cargo.toml workspace version."
required: false
release_tag:
description: "GitHub release tag to fetch assets from. Defaults to v<version>; use snapshot for snapshot assets."
required: false
permissions:
contents: write
pull-requests: write
jobs:
update-flake-hashes:
runs-on: ubuntu-latest
steps:
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
- name: Install Nix
uses: cachix/install-nix-action@v31
- name: Update Nixpkgs lock
run: |
nix flake update nixpkgs \
--extra-experimental-features "nix-command flakes"
- name: Update flake hashes
env:
RELEASE_VERSION: ${{ inputs.version }}
RELEASE_TAG: ${{ inputs.release_tag }}
run: |
if [[ -n "$RELEASE_VERSION" ]]; then
scripts/update-flake-hashes.sh "$RELEASE_VERSION" "$RELEASE_TAG"
else
scripts/update-flake-hashes.sh "" "$RELEASE_TAG"
fi
- name: Upload updated flake
uses: actions/upload-artifact@v7
with:
name: updated-flake
path: |
flake.nix
flake.lock
if-no-files-found: error
validate-nix-prebuilt:
needs:
- update-flake-hashes
strategy:
fail-fast: false
matrix:
runner:
- ubuntu-latest
- ubuntu-24.04-arm
nixpkgs:
- locked
- nixos-25.11
- nixos-26.05
- nixpkgs-unstable
exclude:
- runner: ubuntu-24.04-arm
nixpkgs: locked
name: validate-nix-prebuilt (${{ matrix.nixpkgs }}, ${{ matrix.runner }})
runs-on: ${{ matrix.runner }}
steps:
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
- name: Download updated flake
uses: actions/download-artifact@v8
with:
name: updated-flake
path: .
- name: Install Nix
uses: cachix/install-nix-action@v31
- name: Build prebuilt Nix package
env:
NIXPKGS: ${{ matrix.nixpkgs }}
run: |
if [[ "$NIXPKGS" == "locked" ]]; then
nix build .#prebuilt \
--extra-experimental-features "nix-command flakes" \
--print-build-logs
else
nix build .#prebuilt \
--override-input nixpkgs "github:NixOS/nixpkgs/$NIXPKGS" \
--extra-experimental-features "nix-command flakes" \
--print-build-logs
fi
- name: Inspect prebuilt Nix package
run: |
test -x result/bin/gpclient
test -x result/bin/gpauth
test -x result/bin/gpservice
test -x result/bin/gpgui-helper
test -x result/bin/gpgui
test ! -L result/bin/gpservice
test -x result/libexec/gpclient/gp-vpnc-script-installer
test -x result/libexec/gpclient/gp-hip-script-installer
result/bin/gpclient --version
result/bin/gpservice --version
result/bin/gpauth --version
if grep -R '/usr/bin/gp' result/share; then
echo "Desktop assets contain paths outside the Nix package" >&2
exit 1
fi
- name: Verify desktop authorization runs on the host
run: bash scripts/tests/nix-desktop-authorization.sh result
open-pull-request:
needs:
- validate-nix-prebuilt
runs-on: ubuntu-latest
steps:
- name: Checkout GlobalProtect-openconnect
uses: actions/checkout@v6
- name: Download updated flake
uses: actions/download-artifact@v8
with:
name: updated-flake
path: .
- name: Open pull request
env:
GH_TOKEN: ${{ github.token }}
RELEASE_VERSION: ${{ inputs.version }}
RELEASE_TAG: ${{ inputs.release_tag }}
run: scripts/open-flake-hashes-pr.sh "$RELEASE_VERSION" "$RELEASE_TAG"
-8
View File
@@ -1,5 +1,4 @@
.idea
.DS_Store
/target
.pnpm-store
.env
@@ -9,10 +8,3 @@
.cargo
.build
SNAPSHOT
SOURCE_COMMIT
# Tauri generated files
gen
# Nix files
result
+2 -3
View File
@@ -1,7 +1,6 @@
[submodule "crates/openconnect/deps/openconnect"]
path = crates/openconnect/deps/openconnect
url = https://github.com/yuezk/openconnect.git
branch = globalprotect
url = https://gitlab.com/openconnect/openconnect.git
[submodule "crates/openconnect/deps/libxml2"]
path = crates/openconnect/deps/libxml2
url = https://github.com/GNOME/libxml2.git
url = https://gitlab.gnome.org/GNOME/libxml2.git
-14
View File
@@ -1,14 +0,0 @@
{
"configurations": [
{
"name": "Mac",
"includePath": ["crates/openconnect/deps/openconnect"],
"macFrameworkPath": ["/System/Library/Frameworks", "/Library/Frameworks"],
"intelliSenseMode": "macos-clang-x64",
"compilerPath": "/usr/bin/clang",
"cStandard": "c17",
"cppStandard": "c++17"
}
],
"version": 4
}
-11
View File
@@ -23,12 +23,8 @@
"gpgui",
"gpservice",
"hidpi",
"Ivars",
"jnlp",
"LOGNAME",
"NSHTTPURL",
"NSURL",
"objc",
"oneshot",
"openconnect",
"pkcs",
@@ -59,16 +55,9 @@
"Vite",
"vpnc",
"vpninfo",
"webbrowser",
"wmctrl",
"XAUTHORITY",
"yuezk"
],
"rust-analyzer.cargo.features": "all",
"files.associations": {
"unistd.h": "c",
"utsname.h": "c",
"vpn.h": "c",
"openconnect.h": "c"
},
}
Generated
+2014 -2542
View File
File diff suppressed because it is too large. Load diff
+18 -31
View File
@@ -10,68 +10,55 @@ members = [
]
[workspace.package]
rust-version = "1.91"
version = "3.0.3"
rust-version = "1.71.1"
version = "2.3.13"
authors = ["Kevin Yue <[email protected]>"]
homepage = "https://github.com/yuezk/GlobalProtect-openconnect"
edition = "2024"
edition = "2021"
license = "GPL-3.0"
[workspace.dependencies]
anyhow = "1.0"
askama = "0.16"
base64 = "0.22"
chrono = "0.4"
clap = { version = "4", features = ["derive"] }
clap-verbosity-flag = "3"
clap = { version = "~4.4.2", features = ["derive"] }
ctrlc = "3.4"
directories = "6.0"
dns-lookup = "3"
directories = "5.0"
dns-lookup = "2.0.4"
env_logger = "0.11"
is_executable = "1.0"
log = "0.4"
regex = "1"
reqwest = { version = "0.13", default-features = false, features = ["native-tls", "charset", "http2", "system-proxy", "json", "form", "query"] }
reqwest = { version = "0.11", features = ["native-tls-vendored", "json"] }
openssl = "0.10"
pem = "3"
xmltree = { version = "0.12", features = ["attribute-order"] }
xmltree = "0.11"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
# Use 0.36 as newer versions requires Rust 1.88+
sysinfo = "0.36"
sysinfo = "0.30"
tempfile = "3.8"
tokio = { version = "1" }
tokio-util = "0.7"
url = "2.4"
urlencoding = "2.1.3"
axum = "0.8"
axum = "0.7"
futures = "0.3"
futures-util = "0.3"
tokio-tungstenite = "0.26.1"
uzers = "0.12"
whoami = "2"
whoami = "1"
thiserror = "2"
redact-engine = "0.1"
compile-time = "0.2"
serde_urlencoded = "0.7"
md5 = "0.8"
md5 = "0.7"
sha256 = "1"
which = "8"
uuid = "1"
netdev = "0.40"
humantime = "2"
snow = { version = "0.10", default-features = false, features = ["std", "use-getrandom", "use-curve25519", "use-chacha20poly1305", "use-sha2"] }
zeroize = "1"
which = "7"
# Tauri dependencies
tauri = { version = "2" }
specta = "=2.0.0-rc.20"
proptest = "1"
[patch.crates-io]
# Restore BSD GTK resize hit testing until https://github.com/tauri-apps/tao/pull/1356 is released.
tao = { git = "https://github.com/yuezk/tao", rev = "1452ae7a42c9f134296ba199f91f514fc9077f61" }
# Use one macro source for Tao and Wry so Cargo can vendor the workspace.
tao-macros = { git = "https://github.com/yuezk/tao", rev = "1452ae7a42c9f134296ba199f91f514fc9077f61" }
tauri = { version = "1" }
specta = "=2.0.0-rc.1"
specta-macros = "=2.0.0-rc.1"
rspc = { version = "1.0.0-rc.5", features = ["tauri"] }
[profile.release]
opt-level = 'z' # Optimize for size
+78 -309
View File
@@ -1,59 +1,21 @@
SHELL := /bin/sh
.SHELLFLAGS := -ec
.SHELLFLAGS += -e
OFFLINE ?= 0
BUILD_FE ?= 1
INCLUDE_GUI ?= 0
CARGO ?= cargo
CARGO_TARGET_DIR ?= target
CARGO_RELEASE_DIR ?= $(CARGO_TARGET_DIR)/$(if $(CARGO_BUILD_TARGET),$(CARGO_BUILD_TARGET)/)release
DISABLE_RUST_TOOLCHAIN ?= 0
RUST_VERSION ?= 1.91
IGNORE_RUST_VERSION ?= 0
VERSION = $(shell grep '^version' Cargo.toml | head -1 | sed 's/version *= *"\(.*\)"/\1/')
SOURCE_COMMIT_VALUE := $(shell \
if [ -n "$$SOURCE_GIT_COMMIT" ]; then \
printf '%s' "$$SOURCE_GIT_COMMIT" | cut -c1-9; \
elif [ -n "$$GITHUB_SHA" ]; then \
printf '%s' "$$GITHUB_SHA" | cut -c1-9; \
elif [ -f SOURCE_COMMIT ]; then \
head -n1 SOURCE_COMMIT | tr -d '[:space:]' | cut -c1-9; \
else \
git rev-parse --short=9 HEAD 2>/dev/null || printf unknown; \
fi)
GUI_LIBC_SUFFIX ?= $(shell ldd --version 2>&1 | grep -qi musl && echo -musl || true)
VERSION = $(shell $(CARGO) metadata --no-deps --format-version 1 | jq -r '.packages[0].version')
REVISION ?= 1
RPM_SOURCE ?= %{name}.tar.gz
PPA_REVISION ?= 1
PKG_NAME = globalprotect-openconnect
PKG = $(PKG_NAME)-$(VERSION)
SERIES ?= $(shell lsb_release -cs)
PUBLISH ?= 0
# Indicates whether to build the GUI components
BUILD_GUI_HELPER ?= 1
# Indicates whether to build embedded webview auth support into gpauth
BUILD_WEBVIEW_AUTH ?= 1
ifeq ($(shell uname -s),Linux)
PREFIX ?= /usr
GPGUI_BINARY ?= $(wildcard .build/gpgui/gpgui_*/gpgui)
else ifeq ($(shell uname -s)-$(shell uname -m),Darwin-arm64)
PREFIX ?= /opt/homebrew
else
PREFIX ?= /usr/local
endif
BSD_FLAVOR ?= $(shell uname -s | tr '[:upper:]' '[:lower:]')
GPGUI_BINARY ?= ../gpgui/target/release/gpgui
export DEBEMAIL = [email protected]
export DEBFULLNAME = Kevin Yue
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)
RELEASE_TAG = snapshot
@@ -67,15 +29,8 @@ ifeq ($(OFFLINE), 1)
CARGO_BUILD_ARGS += --frozen
endif
ifeq ($(IGNORE_RUST_VERSION), 1)
CARGO_BUILD_ARGS += --ignore-rust-version
endif
default: build
dev-service:
./scripts/dev-service.sh
version:
@echo $(VERSION)
@@ -84,20 +39,24 @@ clean-tarball:
rm -rf .vendor
rm -rf vendor.tar.xz
rm -rf .cargo
rm -f SOURCE_COMMIT
# Create a tarball, include the cargo dependencies if OFFLINE is set to 1
tarball: clean-tarball
if [ $(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 .build/tarball
printf '%s\n' "$(SOURCE_COMMIT_VALUE)" > SOURCE_COMMIT
# If OFFLINE is set to 1, vendor all cargo dependencies
# Generate a OFFLINE_BUILD file to indicate offline build
if [ $(OFFLINE) -eq 1 ]; then \
$(CARGO) vendor .vendor > .cargo/config.toml; \
tar -cJf vendor.tar.xz .vendor; \
touch OFFLINE_BUILD; \
fi
@echo "Creating tarball..."
@@ -109,38 +68,36 @@ download-gui:
if [ $(INCLUDE_GUI) -eq 1 ]; then \
echo "Downloading GlobalProtect GUI..."; \
mkdir -p .build/gpgui; \
curl -sSL https://github.com/yuezk/GlobalProtect-openconnect/releases/download/$(RELEASE_TAG)/gpgui_$(shell uname -m)$(GUI_LIBC_SUFFIX).bin.tar.xz \
-o .build/gpgui/gpgui_$(shell uname -m)$(GUI_LIBC_SUFFIX).bin.tar.xz; \
curl -sSL https://github.com/yuezk/GlobalProtect-openconnect/releases/download/$(RELEASE_TAG)/gpgui_$(shell uname -m).bin.tar.xz \
-o .build/gpgui/gpgui_$(shell uname -m).bin.tar.xz; \
tar -xJf .build/gpgui/*.tar.xz -C .build/gpgui; \
else \
echo "Skipping GlobalProtect GUI download (INCLUDE_GUI=0)"; \
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 [ $(OFFLINE) -eq 1 ] || [ $(BUILD_FE) -eq 0 ]; then \
echo "Skipping frontend build (OFFLINE=1 or BUILD_FE=0)"; \
else \
cd apps/gpgui-helper && pnpm install && pnpm build; \
fi
if [ ! -d apps/gpgui-helper/dist ]; then \
echo "Error: frontend build failed"; \
exit 1; \
fi
build-rs:
if [ $(OFFLINE) -eq 1 ]; then \
tar -xJf vendor.tar.xz; \
fi
# Remove the rust-toolchain.toml if DISABLE_RUST_TOOLCHAIN is set to 1
if [ $(DISABLE_RUST_TOOLCHAIN) -eq 1 ]; then \
rm -vf rust-toolchain.toml; \
fi
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice
# Build gpauth with or without embedded webview auth support
if [ $(BUILD_WEBVIEW_AUTH) -eq 1 ]; then \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpauth; \
else \
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpauth --no-default-features; \
fi
# 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 gpgui-helper; \
fi
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpclient -p gpservice -p gpauth
$(CARGO) build $(CARGO_BUILD_ARGS) -p gpgui-helper --features "tauri/custom-protocol"
clean:
$(CARGO) clean
@@ -148,193 +105,53 @@ clean:
rm -rf .vendor
rm -rf apps/gpgui-helper/node_modules
ifeq ($(shell uname -s),Darwin)
install: install-macos
install-gpclient: install-gpclient-macos
else ifneq ($(filter FreeBSD OpenBSD,$(shell uname -s)),)
install: install-bsd
install-gpclient: install-gpclient-unix
else
install: install-linux
install-gpclient: install-gpclient-unix
endif
install:
@echo "Installing $(PKG_NAME)..."
install-gpclient-unix:
install -d "$(DESTDIR)$(PREFIX)/bin" "$(DESTDIR)$(PREFIX)/libexec/gpclient"
install -m 755 "$(CARGO_RELEASE_DIR)/gpclient" "$(DESTDIR)$(PREFIX)/bin/"
install -m 755 packaging/files/usr/libexec/gpclient/vpnc-script "$(DESTDIR)$(PREFIX)/libexec/gpclient/"
install -Dm755 target/release/gpclient $(DESTDIR)/usr/bin/gpclient
install -Dm755 target/release/gpauth $(DESTDIR)/usr/bin/gpauth
install -Dm755 target/release/gpservice $(DESTDIR)/usr/bin/gpservice
install -Dm755 target/release/gpgui-helper $(DESTDIR)/usr/bin/gpgui-helper
install-gpclient-macos:
install -d "$(DESTDIR)$(PREFIX)/bin" "$(DESTDIR)$(PREFIX)/lib/gpclient" "$(DESTDIR)$(PREFIX)/libexec/gpclient"
install -m 755 "$(CARGO_RELEASE_DIR)/gpclient" "$(DESTDIR)$(PREFIX)/bin/"
set -e; library=$$(sh scripts/macos-openconnect-library.sh "$(CARGO_RELEASE_DIR)/gpclient"); \
install -m 755 "$$library" "$(DESTDIR)$(PREFIX)/lib/gpclient/"; \
install_name_tool -delete_rpath "$$(dirname "$$library")" "$(DESTDIR)$(PREFIX)/bin/gpclient"; \
codesign --force --sign - "$(DESTDIR)$(PREFIX)/bin/gpclient"
install -m 755 packaging/files/usr/libexec/gpclient/vpnc-script "$(DESTDIR)$(PREFIX)/libexec/gpclient/"
install-macos: install-gpclient-macos
install -m 755 "$(CARGO_RELEASE_DIR)/gpauth" "$(DESTDIR)$(PREFIX)/bin/"
# Common executable and icon installation uses portable install options on Linux/BSD.
install-unix: install-gpclient-unix
set -e; for binary in gpauth gpservice; do \
install -m 755 "$(CARGO_RELEASE_DIR)/$$binary" "$(DESTDIR)$(PREFIX)/bin/"; \
done
set -e; for binary in gp-hip-script-installer gp-vpnc-script-installer; do \
install -m 755 "$(CARGO_RELEASE_DIR)/$$binary" "$(DESTDIR)$(PREFIX)/libexec/gpclient/"; \
done
set -e; if [ "$(BUILD_GUI_HELPER)" = "1" ]; then \
install -m 755 "$(CARGO_RELEASE_DIR)/gpgui-helper" "$(DESTDIR)$(PREFIX)/bin/"; \
if [ -f .build/gpgui/gpgui_*/gpgui ]; then \
install -Dm755 .build/gpgui/gpgui_*/gpgui $(DESTDIR)/usr/bin/gpgui; \
fi
set -e; if [ -f "$(GPGUI_BINARY)" ]; then \
install -m 755 "$(GPGUI_BINARY)" "$(DESTDIR)$(PREFIX)/bin/gpgui"; \
fi
set -e; for file in packaging/files/usr/share/icons/hicolor/*/apps/gpgui.* \
packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-*.svg; do \
destination="$(DESTDIR)$(PREFIX)/$${file#packaging/files/usr/}"; \
install -d "$$(dirname "$$destination")"; \
install -m 644 "$$file" "$$destination"; \
done
install-linux: install-unix
@echo "Installing Linux integration under $(PREFIX)..."
set -e; for file in share/applications/gpgui.desktop \
share/polkit-1/actions/com.yuezk.gpgui.policy \
lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down \
lib/NetworkManager/dispatcher.d/gpclient-nm-hook; do \
mode=644; case "$$file" in lib/*) mode=755 ;; esac; \
destination="$(DESTDIR)$(PREFIX)/$$file"; \
install -d "$$(dirname "$$destination")"; \
install -m "$$mode" "packaging/files/usr/$$file" "$$destination"; \
done
sh scripts/relocate-install-paths.sh "$(PREFIX)" /usr "$(DESTDIR)$(PREFIX)"
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-bsd: install-unix
@echo "Installing BSD integration under $(PREFIX)..."
install -d "$(DESTDIR)$(PREFIX)/share/applications" "$(DESTDIR)$(PREFIX)/share/polkit-1/actions"
install -m 644 packaging/bsd/gpgui.desktop "$(DESTDIR)$(PREFIX)/share/applications/"
install -m 644 packaging/bsd/com.yuezk.gpgui.policy "$(DESTDIR)$(PREFIX)/share/polkit-1/actions/"
sh scripts/relocate-install-paths.sh "$(PREFIX)" /usr/local "$(DESTDIR)$(PREFIX)"
# Install the disconnect hooks
install -Dm755 packaging/files/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
install -Dm755 packaging/files/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
clean-bsd-package:
rm -rf .build/$(BSD_FLAVOR)
install -Dm644 packaging/files/usr/share/applications/gpgui.desktop $(DESTDIR)/usr/share/applications/gpgui.desktop
install -Dm644 packaging/files/usr/share/icons/hicolor/scalable/apps/gpgui.svg $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
install -Dm644 packaging/files/usr/share/icons/hicolor/32x32/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png
install -Dm644 packaging/files/usr/share/icons/hicolor/128x128/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/128x128/apps/gpgui.png
install -Dm644 packaging/files/usr/share/icons/hicolor/256x256@2/apps/gpgui.png $(DESTDIR)/usr/share/icons/hicolor/256x256@2/apps/gpgui.png
install -Dm644 packaging/files/usr/share/polkit-1/actions/com.yuezk.gpgui.policy $(DESTDIR)/usr/share/polkit-1/actions/com.yuezk.gpgui.policy
bsd-gpgui-tarball:
test -x "$(GPGUI_BINARY)"
rm -rf .build/$(BSD_FLAVOR)/gpgui
mkdir -p .build/$(BSD_FLAVOR)/artifacts .build/$(BSD_FLAVOR)/gpgui/gpgui_$(VERSION)
cp "$(GPGUI_BINARY)" .build/$(BSD_FLAVOR)/gpgui/gpgui_$(VERSION)/
tar -cf - -C .build/$(BSD_FLAVOR)/gpgui gpgui_$(VERSION) | xz -c > .build/$(BSD_FLAVOR)/artifacts/gpgui_$(BSD_FLAVOR)_$(shell uname -m).bin.tar.xz
file=.build/$(BSD_FLAVOR)/artifacts/gpgui_$(BSD_FLAVOR)_$(shell uname -m).bin.tar.xz; \
if command -v sha256sum >/dev/null 2>&1; then sha256sum "$$file" | cut -d ' ' -f 1; \
elif command -v sha256 >/dev/null 2>&1; then sha256 -q "$$file"; \
else cksum -a sha256 "$$file" | awk '{print $$1}'; fi > "$$file.sha256"
uninstall:
@echo "Uninstalling $(PKG_NAME)..."
package-freebsd: BSD_FLAVOR=freebsd
package-freebsd: clean-bsd-package
test -x "$(GPGUI_BINARY)"
mkdir -p .build/freebsd/pkgroot .build/freebsd/artifacts .build/freebsd/metadata
$(MAKE) install-bsd DESTDIR=$(CURDIR)/.build/freebsd/pkgroot PREFIX=$(PREFIX) GPGUI_BINARY="$(GPGUI_BINARY)"
find .build/freebsd/pkgroot$(PREFIX) -type f -print | sed 's|^.build/freebsd/pkgroot$(PREFIX)/||' | sort > .build/freebsd/PLIST
freebsd_major=$$(freebsd-version -u | sed 's/\..*//'); \
freebsd_arch=$$(uname -m | sed -e 's/x86_64/amd64/' -e 's/arm64/aarch64/'); \
sed \
-e 's/@PKG_NAME@/$(PKG_NAME)/g' \
-e 's/@VERSION@/$(VERSION)/g' \
-e "s/@ABI@/FreeBSD:$$freebsd_major:$$freebsd_arch/g" \
-e "s/@ARCH@/freebsd:$$freebsd_major:$$freebsd_arch/g" \
-e 's|@PREFIX@|$(PREFIX)|g' \
packaging/bsd/freebsd/MANIFEST.in > .build/freebsd/metadata/+MANIFEST
cp packaging/bsd/freebsd/POST_DEINSTALL .build/freebsd/metadata/+POST_DEINSTALL
pkg create -r .build/freebsd/pkgroot -M .build/freebsd/metadata -p .build/freebsd/PLIST -o .build/freebsd/artifacts
freebsd_arch=$$(uname -m | sed -e 's/x86_64/amd64/' -e 's/arm64/aarch64/'); \
mv .build/freebsd/artifacts/$(PKG_NAME)-$(VERSION).pkg .build/freebsd/artifacts/$(PKG_NAME)-$(VERSION)-freebsd-$$freebsd_arch.pkg
$(MAKE) bsd-gpgui-tarball BSD_FLAVOR=freebsd GPGUI_BINARY="$(GPGUI_BINARY)"
rm -f $(DESTDIR)/usr/bin/gpclient
rm -f $(DESTDIR)/usr/bin/gpauth
rm -f $(DESTDIR)/usr/bin/gpservice
rm -f $(DESTDIR)/usr/bin/gpgui-helper
rm -f $(DESTDIR)/usr/bin/gpgui
package-openbsd: BSD_FLAVOR=openbsd
package-openbsd: clean-bsd-package
test -x "$(GPGUI_BINARY)"
mkdir -p .build/openbsd/pkgroot .build/openbsd/artifacts
$(MAKE) install-bsd DESTDIR=$(CURDIR)/.build/openbsd/pkgroot PREFIX=$(PREFIX) GPGUI_BINARY="$(GPGUI_BINARY)"
cp packaging/bsd/openbsd/COMMENT .build/openbsd/+COMMENT
cp packaging/bsd/openbsd/DESC .build/openbsd/+DESC
{ \
echo '@unexec-delete /bin/rm -f /usr/local/libexec/gpclient/gpgui /var/db/gpclient/scripts/vpnc-script /var/db/gpclient/scripts/vpnc-script.metadata || echo "Warning: failed to remove gpclient runtime files" >&2'; \
echo '@unexec-delete /bin/rmdir /usr/local/libexec/gpclient 2>/dev/null || true'; \
echo '@unexec-delete /bin/rmdir /var/db/gpclient/scripts 2>/dev/null || true'; \
echo '@unexec-delete /bin/rmdir /var/db/gpclient 2>/dev/null || true'; \
find .build/openbsd/pkgroot$(PREFIX) -type f -print | sed 's|^.build/openbsd/pkgroot$(PREFIX)/||' | sort; \
} > .build/openbsd/PLIST
comment=$$(cat .build/openbsd/+COMMENT); \
openbsd_arch=$$(uname -m | sed 's/x86_64/amd64/'); \
gnome_keyring_pkg=$$(pkg_info -e 'gnome-keyring-*' | sed 's/^inst://' | head -n 1); \
dbus_pkg=$$(pkg_info -e 'dbus-*' | sed 's/^inst://' | head -n 1); \
polkit_pkg=$$(pkg_info -e 'polkit-*' | sed 's/^inst://' | head -n 1); \
webkitgtk_pkg=$$(pkg_info -e 'webkitgtk41-*' | sed 's/^inst://' | head -n 1); \
xdg_utils_pkg=$$(pkg_info -e 'xdg-utils-*' | sed 's/^inst://' | head -n 1); \
pkg_create \
-B .build/openbsd/pkgroot \
-D COMMENT="$$comment" \
-d .build/openbsd/+DESC \
-f .build/openbsd/PLIST \
-p $(PREFIX) \
-P x11/gnome/keyring:gnome-keyring-*:$$gnome_keyring_pkg \
-P x11/dbus:dbus-*:$$dbus_pkg \
-P sysutils/polkit:polkit-*:$$polkit_pkg \
-P www/webkitgtk4,webkitgtk41:webkitgtk41-*:$$webkitgtk_pkg \
-P devel/xdg-utils:xdg-utils-*:$$xdg_utils_pkg \
.build/openbsd/artifacts/$(PKG_NAME)-$(VERSION)-openbsd-$$openbsd_arch.tgz
$(MAKE) bsd-gpgui-tarball BSD_FLAVOR=openbsd GPGUI_BINARY="$(GPGUI_BINARY)"
rm -f $(DESTDIR)/usr/libexec/gpclient/vpnc-script
rm -f $(DESTDIR)/usr/libexec/gpclient/hipreport.sh
ifeq ($(shell uname -s),Darwin)
uninstall: uninstall-macos
else ifneq ($(filter FreeBSD OpenBSD,$(shell uname -s)),)
uninstall: uninstall-bsd
else
uninstall: uninstall-linux
endif
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down
rm -f $(DESTDIR)/usr/lib/NetworkManager/dispatcher.d/gpclient-nm-hook
.PHONY: install install-gpclient install-macos install-unix install-linux install-bsd \
install-gpclient-macos install-gpclient-unix \
uninstall uninstall-macos uninstall-unix uninstall-linux uninstall-bsd
uninstall-macos:
@echo "Uninstalling $(PKG_NAME) for macOS under $(PREFIX)..."
rm -f "$(DESTDIR)$(PREFIX)/bin/gpclient" "$(DESTDIR)$(PREFIX)/bin/gpauth" \
"$(DESTDIR)$(PREFIX)/libexec/gpclient/vpnc-script" \
"$(DESTDIR)$(PREFIX)/lib/gpclient/"libopenconnect.*.dylib
rmdir "$(DESTDIR)$(PREFIX)/lib/gpclient" "$(DESTDIR)$(PREFIX)/libexec/gpclient" 2>/dev/null || true
uninstall-unix:
@echo "Uninstalling $(PKG_NAME) under $(PREFIX)..."
set -e; for binary in gpclient gpauth gpservice gpgui-helper gpgui; do \
rm -f "$(DESTDIR)$(PREFIX)/bin/$$binary"; \
done
set -e; for file in gp-hip-script-installer gp-vpnc-script-installer vpnc-script; do \
rm -f "$(DESTDIR)$(PREFIX)/libexec/gpclient/$$file"; \
done
set -e; for file in packaging/files/usr/share/icons/hicolor/*/apps/gpgui.* \
packaging/files/usr/share/icons/hicolor/scalable/status/gpgui-*.svg; do \
rm -f "$(DESTDIR)$(PREFIX)/$${file#packaging/files/usr/}"; \
done
rm -f "$(DESTDIR)$(PREFIX)/share/applications/gpgui.desktop" \
"$(DESTDIR)$(PREFIX)/share/polkit-1/actions/com.yuezk.gpgui.policy"
rmdir "$(DESTDIR)$(PREFIX)/libexec/gpclient" 2>/dev/null || true
uninstall-linux: uninstall-unix
rm -f "$(DESTDIR)$(PREFIX)/lib/NetworkManager/dispatcher.d/pre-down.d/gpclient.down" \
"$(DESTDIR)$(PREFIX)/lib/NetworkManager/dispatcher.d/gpclient-nm-hook"
rm -f "$(DESTDIR)/var/lib/gpclient/gpgui" \
"$(DESTDIR)/var/lib/gpclient/scripts/vpnc-script" \
"$(DESTDIR)/var/lib/gpclient/scripts/vpnc-script.metadata"
rmdir "$(DESTDIR)/var/lib/gpclient/scripts" "$(DESTDIR)/var/lib/gpclient" 2>/dev/null || true
uninstall-bsd: uninstall-unix
rm -f "$(DESTDIR)/usr/local/libexec/gpclient/gpgui" \
"$(DESTDIR)/var/db/gpclient/scripts/vpnc-script" \
"$(DESTDIR)/var/db/gpclient/scripts/vpnc-script.metadata"
rmdir "$(DESTDIR)/var/db/gpclient/scripts" "$(DESTDIR)/var/db/gpclient" 2>/dev/null || true
rm -f $(DESTDIR)/usr/share/applications/gpgui.desktop
rm -f $(DESTDIR)/usr/share/icons/hicolor/scalable/apps/gpgui.svg
rm -f $(DESTDIR)/usr/share/icons/hicolor/32x32/apps/gpgui.png
rm -f $(DESTDIR)/usr/share/icons/hicolor/128x128/apps/gpgui.png
rm -f $(DESTDIR)/usr/share/icons/hicolor/256x256@2/apps/gpgui.png
rm -f $(DESTDIR)/usr/share/polkit-1/actions/com.yuezk.gpgui.policy
clean-debian:
rm -rf .build/deb
@@ -345,41 +162,23 @@ init-debian: clean-debian tarball
cp .build/tarball/${PKG}.tar.gz .build/deb
tar -xzf .build/deb/${PKG}.tar.gz -C .build/deb
cd .build/deb/${PKG} && debmake
cd .build/deb/${PKG} && LC_ALL=C.UTF-8 LANG=C.UTF-8 PYTHONUTF8=1 debmake
cp -f packaging/deb/control.in .build/deb/$(PKG)/debian/control
cp -f packaging/deb/rules.in .build/deb/$(PKG)/debian/rules
cp -f packaging/deb/postrm .build/deb/$(PKG)/debian/postrm
cp -f packaging/deb/compat .build/deb/$(PKG)/debian/compat
sed -i "s/@RUST_VERSION@/$(RUST_VERSION)/g" .build/deb/$(PKG)/debian/control
# Remove the GUI dependencies if neither GUI component is included
if [ $(INCLUDE_GUI) -eq 0 ] && [ $(BUILD_GUI_HELPER) -eq 0 ]; then \
sed -i "/libsecret-1-0/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; \
fi
# Remove WebKitGTK only if no included component needs it
if [ $(INCLUDE_GUI) -eq 0 ] && [ $(BUILD_GUI_HELPER) -eq 0 ] && [ $(BUILD_WEBVIEW_AUTH) -eq 0 ]; then \
sed -i "/libwebkit2gtk-4.1-dev/d" .build/deb/$(PKG)/debian/control; \
fi
sed -i "s/@INCLUDE_GUI@/$(INCLUDE_GUI)/g" .build/deb/$(PKG)/debian/rules
sed -i "s/@BUILD_GUI_HELPER@/$(BUILD_GUI_HELPER)/g" .build/deb/$(PKG)/debian/rules
sed -i "s/@BUILD_WEBVIEW_AUTH@/$(BUILD_WEBVIEW_AUTH)/g" .build/deb/$(PKG)/debian/rules
sed -i "s/@RUST_VERSION@/$(RUST_VERSION)/g" .build/deb/$(PKG)/debian/rules
sed -i "s/@OFFLINE@/$(OFFLINE)/g" .build/deb/$(PKG)/debian/rules
rm -f .build/deb/$(PKG)/debian/changelog
deb: init-debian
# Remove the rust build depdency 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."
# Install build dependencies
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
cd .build/deb/$(PKG) && debuild --preserve-env -e PATH -us -uc -b
check-ppa:
if [ $(OFFLINE) -eq 0 ]; then \
@@ -388,6 +187,8 @@ check-ppa:
# Usage: make ppa SERIES=focal OFFLINE=1 PUBLISH=1
ppa: check-ppa init-debian
sed -i "s/@RUST@/rust-all(>=1.70)/g" .build/deb/$(PKG)/debian/control
$(eval SERIES_VER = $(shell distro-info --series $(SERIES) -r | cut -d' ' -f1))
@echo "Building for $(SERIES) $(SERIES_VER)"
@@ -414,7 +215,7 @@ init-rpm: clean-rpm
sed -i "s/@VERSION@/$(VERSION)/g" .build/rpm/globalprotect-openconnect.spec
sed -i "s/@REVISION@/$(REVISION)/g" .build/rpm/globalprotect-openconnect.spec
sed -i "s|@SOURCE@|$(RPM_SOURCE)|g" .build/rpm/globalprotect-openconnect.spec
sed -i "s/@OFFLINE@/$(OFFLINE)/g" .build/rpm/globalprotect-openconnect.spec
sed -i "s/@DATE@/$(shell LC_ALL=en.US date "+%a %b %d %Y")/g" .build/rpm/globalprotect-openconnect.spec
sed -i "s/@VERSION@/$(VERSION)/g" .build/rpm/globalprotect-openconnect.changes
@@ -443,47 +244,15 @@ init-pkgbuild: clean-pkgbuild tarball
cp .build/tarball/${PKG}.tar.gz .build/pkgbuild
cp packaging/pkgbuild/PKGBUILD.in .build/pkgbuild/PKGBUILD
cp packaging/pkgbuild/gp.install .build/pkgbuild/gp.install
sed -i "s/@PKG_NAME@/$(PKG_NAME)/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/@OFFLINE@/$(OFFLINE)/g" .build/pkgbuild/PKGBUILD
pkgbuild: init-pkgbuild
cd .build/pkgbuild && makepkg -s --noconfirm
clean-apk:
rm -rf .build/apk
init-apk: clean-apk tarball
mkdir -p .build/apk
cp .build/tarball/${PKG}.tar.gz .build/apk
cp packaging/apk/APKBUILD.in .build/apk/APKBUILD
cp packaging/apk/post-deinstall .build/apk/$(PKG_NAME).post-deinstall
sed -i "s/@PKG_NAME@/$(PKG_NAME)/g" .build/apk/APKBUILD
sed -i "s/@VERSION@/$(VERSION)/g" .build/apk/APKBUILD
sed -i "s/@REVISION@/$(REVISION)/g" .build/apk/APKBUILD
checksum=$$(sha512sum .build/apk/${PKG}.tar.gz | cut -d' ' -f1); \
sed -i "s/@SHA512@/$$checksum/g" .build/apk/APKBUILD
# Remove the GUI dependencies if neither GUI component is included
if [ $(INCLUDE_GUI) -eq 0 ] && [ $(BUILD_GUI_HELPER) -eq 0 ]; then \
sed -i "/^\tlibayatana-appindicator$$/d" .build/apk/APKBUILD; \
sed -i "/^\tlibsecret$$/d" .build/apk/APKBUILD; \
fi
# Remove WebKitGTK only if no included component needs it
if [ $(INCLUDE_GUI) -eq 0 ] && [ $(BUILD_GUI_HELPER) -eq 0 ] && [ $(BUILD_WEBVIEW_AUTH) -eq 0 ]; then \
sed -i "/^\twebkit2gtk-4.1$$/d" .build/apk/APKBUILD; \
fi
apk: init-apk
cd .build/apk && abuild -r -P "$(CURDIR)/.build/apk/packages"
find .build/apk/packages -type f -name "$(PKG_NAME)-*.apk" -exec cp {} .build/apk \;
clean-binary:
rm -rf .build/binary
@@ -495,7 +264,7 @@ binary: clean-binary tarball
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
cp packaging/binary/Makefile.in .build/binary/$(PKG_NAME)_$(VERSION)/Makefile
+107 -456
View File
@@ -1,162 +1,79 @@
# GlobalProtect-openconnect
A GlobalProtect VPN client built on OpenConnect with support for SSO authentication. It provides command-line tools and the GP Connect desktop application for macOS, Linux, FreeBSD, and OpenBSD.
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">
<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>
> **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)
- [macOS](#macos)
- [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)
- [Alpine Linux](#alpine-linux)
- [FreeBSD](#freebsd)
- [OpenBSD](#openbsd)
- [Gentoo](#gentoo)
- [NixOS](#nixos)
- [Official Docker Image](#official-docker-image)
- [Other Distributions](#other-distributions)
- [Building from Source](#building-from-source)
- [Frequently Asked Questions](#frequently-asked-questions)
- [NetworkManager Integration](#networkmanager-integration)
- [Licensing](#licensing)
## Features
- **Desktop Platform Support** – macOS, Linux, FreeBSD, and OpenBSD
- **Dual Interface** – Available as both CLI and GUI applications
- **Flexible Authentication** – Supports SSO, non-SSO, FIDO2 (e.g., YubiKey), and client certificate authentication
- **Browser Integration** – Authenticate using your default browser or any specified browser
- **Multi-Portal Support** – Connect to multiple portals and gateways
- **Direct Gateway Connection** – Bypass portal selection when needed
- **Auto-Connect** – Automatically connect on system startup
- **System Tray Integration** – Convenient system tray icon (requires [gnome-shell-extension-appindicator](https://extensions.gnome.org/extension/615/appindicator-support/) on GNOME)
- [x] Better Linux support
- [x] Support both CLI and GUI
- [x] Support both SSO and non-SSO authentication
- [x] Support the FIDO2 authentication (e.g., YubiKey)
- [x] Support authentication using default browser
- [x] Support client certificate authentication
- [x] Support multiple portals
- [x] Support gateway selection
- [x] Support connect gateway directly
- [x] Support auto-connect on startup
- [x] Support system tray icon
## Usage
### Command-Line Interface
### CLI
The CLI is free and open source. Use it to authenticate, connect to portals or gateways, and generate HIP reports from the terminal.
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>
Commands:
connect Connect to a portal server
disconnect Disconnect from the server
launch-gui Launch the GUI
hip Generate HIP report
help Print this message or the help of the given subcommand(s)
Options:
--fix-openssl Uses extended compatibility mode for OpenSSL operations to support a broader range of systems and formats.
--ignore-tls-errors Ignore the TLS errors
--lock-file <LOCK_FILE> Path to the gpclient PID lock file
--log-format <LOG_FORMAT> Log output format. JSON is intended for non-interactive consumers; interactive prompts remain text. [default: text] [possible values: text, json]
-v, --verbose... Enable verbose output, -v for debug, -vv for trace
-q, --quiet... Decrease logging verbosity, -q for warnings, -qq for errors
-h, --help Print help (see more with '--help')
-V, --version Print version
--fix-openssl Get around the OpenSSL `unsafe legacy renegotiation` error
--ignore-tls-errors Ignore the TLS errors
-h, --help Print help
-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.
#### HIP reports
HIP is disabled in the CLI unless enabled explicitly. Use `--hip` to generate reports inside `gpclient`, including later reports requested by the gateway:
To use the external browser for authentication with the CLI version, you need to use the following command:
```bash
sudo gpclient connect <portal> --hip
sudo -E gpclient connect --browser default <portal>
```
Use `--hip=/absolute/path/to/script` for a custom executable. It runs as the `gpclient` process user unless `--hip-user` specifies another user. No installed HIP script is discovered automatically. `--hip-user` applies only to custom executables.
`gpclient hip` generates a report on demand for inspection; see `gpclient hip --help` for report inputs. The GUI's HIP tab supports generated reports, edited XML, and HIP Off on all desktop platforms. Linux, FreeBSD, and OpenBSD also support desktop-user scripts and explicitly approved root scripts.
#### External Browser Authentication
Use `gpclient` directly for browser-based authentication. It opens the browser as your normal desktop user while keeping VPN tunnel setup privileged:
Or you can try the following command if the above command does not work:
```bash
sudo gpclient connect <portal> --browser
gpauth <portal> --browser default 2>/dev/null | sudo gpclient connect <portal> --cookie-on-stdin
```
To reuse a saved portal cookie for later connections, add `--cookie-cache`:
You can specify the browser with the `--browser <browser>` option, e.g., `--browser firefox`, `--browser chrome`, etc.
```bash
sudo gpclient connect <portal> --browser --cookie-cache
```
### GUI
Add `--gateway <gateway>` to select a particular gateway. Cookie caching is handled by `gpclient`. Its default cache file is `$HOME/.config/gpclient/cookie.json`, which normally belongs to root when running with `sudo`. To choose a predictable location, specify the path explicitly:
```bash
sudo gpclient connect <portal> --browser --cookie-cache=/absolute/path/to/cookie.json
```
**Browser Options:**
- Use `--browser` to try your recognized default browser first, then another detected browser, and finally the system URL handler
- Use `--browser default` to use the system default browser
- 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
GP Connect provides a desktop interface for managing VPN connections. On macOS, open GP Connect from Applications. On Linux, FreeBSD, and OpenBSD, launch it from your application menu or via the terminal:
```bash
gpclient launch-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]
>
> 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
> [!Note]
>
> 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 based distributions
### macOS
#### Install from PPA (Ubuntu 18.04 and later, except 24.04)
GP Connect requires Apple silicon and macOS 13 or later. The macOS app includes both the desktop application and the free `gpclient` CLI. The CLI does not require a GUI license.
#### Option 1: Install with Homebrew
```bash
brew install --cask yuezk/gp-connect/gp-connect
```
Open GP Connect from Applications, or connect from the terminal:
```bash
sudo gpclient connect <portal> --browser
```
#### Option 2: Install from DMG
Download the GP Connect `.dmg` from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, open it, and drag GP Connect into Applications.
### Debian / Ubuntu
#### Option 1: Install from PPA (Recommended)
```bash
sudo apt-get install gir1.2-gtk-3.0 gir1.2-webkit2-4.0
sudo add-apt-repository ppa:yuezk/globalprotect-openconnect
sudo apt-get update
sudo apt-get install globalprotect-openconnect
@@ -164,408 +81,142 @@ sudo apt-get install globalprotect-openconnect
> [!Note]
>
> **For Linux Mint users:** If you encounter a GPG key error, import the key manually:
> ```bash
> sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 7937C393082992E5D6E4A60453FC26B43838D761
> ```
> 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`.
#### Option 2: Install from DEB Package
#### **Ubuntu 24.04 and later**
Download the latest `.deb` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
The `libwebkit2gtk-4.0-37` package was [removed](https://bugs.launchpad.net/ubuntu/+source/webkit2gtk/+bug/2061914) from its repo. You can use the [`deb-install.sh`](./scripts/deb-install.sh) script to install the package:
```bash
sudo apt install --fix-broken ./globalprotect-openconnect_*.deb
curl -o- https://raw.githubusercontent.com/yuezk/GlobalProtect-openconnect/main/scripts/deb-install.sh \
| bash -s -- 2.3.9
```
#### **Ubuntu 18.04**
The latest package is not available in the PPA either, but you still needs to add the `ppa:yuezk/globalprotect-openconnect` repo beforehand to use the required `openconnect` package. Then you can follow the [Install from deb package](#install-from-deb-package) section to install the latest package.
#### Install from deb package
Download the latest deb package from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page. Then install it with `apt`:
```bash
sudo apt install --fix-broken globalprotect-openconnect_*.deb
```
### Arch Linux / Manjaro
#### Option 1: Install from AUR
#### Install from AUR
Package: [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):
Install from AUR: [globalprotect-openconnect-git](https://aur.archlinux.org/packages/globalprotect-openconnect-git/)
```bash
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.
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:
Download the latest package from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page. Then install it with `pacman`:
```bash
sudo pacman -U globalprotect-openconnect-*.pkg.tar.zst
```
### Fedora 38+ / Rawhide
### Fedora 38 and later / Fedora Rawhide
#### 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
sudo dnf copr enable yuezk/globalprotect-openconnect
sudo dnf install globalprotect-openconnect
```
### openSUSE Leap 15.6+ / Tumbleweed
### openSUSE Leap 15.6 / openSUSE Tumbleweed
#### 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.
On RHEL / Rocky Linux / AlmaLinux / CentOS, enable EPEL first:
```bash
sudo dnf install epel-release
```
```bash
sudo rpm -i globalprotect-openconnect-*.rpm
```
### Alpine Linux
Download the latest `.apk` package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
```bash
sudo apk add --allow-untrusted globalprotect-openconnect-*.apk
```
The package uses Alpine's native musl build. Make sure the `community` repository is enabled so GUI dependencies such as `webkit2gtk-4.1`, `libsecret`, and `libayatana-appindicator` can be resolved. GUI-launched connections use polkit, and VPN tunnel creation requires `/dev/net/tun`.
### FreeBSD
Download the latest FreeBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
```bash
sudo pkg install ./globalprotect-openconnect-*-freebsd-*.pkg
```
To build from source, see [Building from Source on FreeBSD and OpenBSD](./docs/bsd-source-build.md).
### OpenBSD
Download the latest OpenBSD package from the [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page, then install:
```bash
doas pkg_add -D unsigned ./globalprotect-openconnect-*-openbsd-*.tgz
```
To build from source, see [Building from Source on FreeBSD and OpenBSD](./docs/bsd-source-build.md).
### Gentoo
Available via the `guru` and `lamdness` overlays:
It is available via `guru` and `lamdness` overlays.
```bash
sudo eselect repository enable guru
sudo emerge --sync guru
sudo emerge --ask --verbose net-vpn/GlobalProtect-openconnect
sudo emerge -r guru sync
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.
#### Installation Steps
## Build from source
Add the flake input and NixOS module to your `flake.nix`:
You can also build the client from source, steps are as follows:
The module builds the package with your NixOS configuration's `pkgs`, so the
GlobalProtect GUI and the system use the same Nixpkgs dependency versions.
It also enables Polkit and its setuid `pkexec` wrapper for privileged operations.
### Prerequisites
```nix
{
inputs = {
# ... other inputs
globalprotect-openconnect.url = "github:yuezk/GlobalProtect-openconnect";
};
- [Install Rust 1.75 or later](https://www.rust-lang.org/tools/install)
- Install Tauri dependencies: https://tauri.app/v1/guides/getting-started/prerequisites/#setting-up-linux
- 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)
outputs = { self, nixpkgs, globalprotect-openconnect, ... }:
let
system = "x86_64-linux"; # or "aarch64-linux" for ARM64
hostname = "<your-host>";
in {
nixosConfigurations.${hostname} = nixpkgs.lib.nixosSystem {
inherit system;
### Build
modules = [
./configuration.nix
globalprotect-openconnect.nixosModules.default
{
programs.globalprotect-openconnect.enable = true;
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`.
3. Enter the source directory and run `make build BUILD_FE=0` to build the client.
3. Run `sudo make install` to install the client. (Note, `DESTDIR` is not supported)
environment.systemPackages = [
nixpkgs.legacyPackages.${system}.gnomeExtensions.appindicator
];
}
];
};
};
}
```
## FAQ
Apply:
1. How to deal with error `Secure Storage not ready`
```bash
sudo nixos-rebuild switch
loginctl terminate-user "$USER"
```
Try upgrade the client to `2.2.0` or later, which will use a file-based storage as a fallback.
After logging back in to GNOME, enable AppIndicator support if needed:
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)).
```bash
gnome-extensions enable [email protected]
```
2. How to deal with error `(gpauth:18869): Gtk-WARNING **: 10:33:37.566: cannot open display:`
NixOS does not run an imperative package-uninstall hook when a package is
removed from the system configuration. Remove an installed replacement VPN
script from the app settings before removing the package.
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)).
The `prebuilt` package and NixOS module use the published release pinned in `flake.nix`. Both `prebuilt` and `fromSource` run natively on the host with packaged dependencies and installer paths. The `fromSource` package builds the current flake checkout, including its Git submodules:
## About Trial
```bash
git submodule update --init --recursive
nix build "git+file://$PWD?submodules=1#fromSource"
```
The CLI version is always free, while the GUI version is paid. There are two trial modes for the GUI version:
Local source builds require initialized Git submodules and a flake URL with `submodules=1`, as shown above. For a remote source flake, use a Git URL with submodules enabled, such as `git+https://github.com/yuezk/GlobalProtect-openconnect?submodules=1#fromSource`. The `prebuilt` package and NixOS module do not require Git submodules. Build output (`target`, `.build`, and `node_modules`) is excluded from the source input. Updating release asset hashes changes the prebuilt package, independently of source builds.
1. 10-day trial: You can use the GUI stable release for 10 days after the installation.
2. 14-day trial: Each beta release has a fresh trial period (at most 14 days) after released.
### Official Docker Image
## License
The [official Docker image](https://hub.docker.com/r/yuezk/globalprotect-openconnect) provides the CLI tools on Alpine Linux:
```bash
docker pull yuezk/globalprotect-openconnect:<version>
```
Release images are tagged as `vX.Y.Z`, `X.Y.Z`, and `latest`.
Run it with access to the TUN device:
```bash
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
yuezk/globalprotect-openconnect:<version> \
connect <portal>
```
For browser authentication in a headless environment, use remote browser authentication:
```bash
docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \
yuezk/globalprotect-openconnect:<version> \
connect <portal> --browser remote
```
On a host with multiple network interfaces, use `--browser-listen` to select the IP address reachable from the browser machine:
```bash
gpclient connect <portal> --browser remote --browser-listen 192.168.107.15
```
On a Linux host, add host networking if the VPN routes should affect the host network namespace:
```bash
docker run --rm -it --network host --cap-add=NET_ADMIN --device=/dev/net/tun \
yuezk/globalprotect-openconnect:<version> \
connect <portal> --browser remote
```
Without `--network host`, the VPN connection stays inside the container's network namespace. Docker Desktop on macOS and Windows does not make the host use the VPN through `--network host`; run `gpclient` on the host or use a container gateway setup for host traffic.
The image includes `gpclient` and `gpauth` only. It does not include embedded webview authentication, `gpgui-helper`, or `gpgui`.
### Other Distributions
#### Manual Installation
1. **Install dependencies:**
- WebKitGTK 4.1 (for example, `libwebkit2gtk-4.1-0` on Debian/Ubuntu)
- `libsecret`
- `libayatana-appindicator` or `libappindicator-gtk3`
- polkit (`pkexec`) for GUI-launched VPN connections
2. **Download and extract:**
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
cd globalprotect-openconnect_${version}
```
3. **Install:**
```bash
sudo make install
```
## Building from Source
The instructions below build the open-source components on Linux. For FreeBSD and OpenBSD, see [Building from Source on FreeBSD and OpenBSD](./docs/bsd-source-build.md).
### Method 1: Using DevContainer
This project includes a DevContainer configuration for Linux development. The repository's `rust-toolchain.toml` selects the Rust toolchain; rustup may need to download it on the first build.
#### 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 the open-source components, including the GUI helper, run:
```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_HELPER=0` passed as an argument to `make`.
4. **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
- `gp-hip-script-installer` – Privileged HIP script installer
- `gp-vpnc-script-installer` – Privileged VPN script installer
The proprietary GP Connect desktop application is distributed separately. Use `INCLUDE_GUI=1` with `make build` to download its matching published Linux build for installation.
#### 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.91 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)
- Node.js and pnpm if rebuilding the GUI helper frontend
#### 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
```
To stage the files for packaging instead of installing them into the system, use `make install DESTDIR=/absolute/path/to/staging`.
### Testing Your Build
Verify the CLI client is working correctly:
```bash
./target/release/gpclient --help
```
### Build Options
- `BUILD_GUI_HELPER=0` – Skip building and installing the GUI helper
- `BUILD_WEBVIEW_AUTH=0` – Build `gpauth` without embedded browser authentication; use an external or remote browser
- `INCLUDE_GUI=1` – Download the matching published Linux desktop application for installation
- `OFFLINE=1` – Build in offline mode using vendored dependencies
## Frequently Asked Questions
When reporting a problem, follow the [diagnostics collection instructions](docs/diagnostics.md). A standalone script is available for versions without the diagnostics command; you do not need to upgrade first.
### Q: How do I resolve the "Secure Storage not ready" error?
Unlock your desktop keyring and ensure the application can access it. On Linux and BSD, check that a keyring service such as GNOME Keyring is installed and running in your desktop session. On macOS, check Keychain access.
Linux and BSD can use file storage when secure storage is unavailable during initial setup. An existing configuration that uses the keyring still needs access to that keyring.
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?
Run the client from a terminal in your normal desktop session and use an external browser:
```bash
sudo gpclient connect <portal> --browser
```
See related issue: [#316](https://github.com/yuezk/GlobalProtect-openconnect/issues/316)
On a headless server, use `--browser remote` and complete authentication from another machine.
## NetworkManager Integration
- [WMP/GlobalProtect-SAML-NetworkManager](https://github.com/WMP/GlobalProtect-SAML-NetworkManager) – NetworkManager VPN plugin with SAML/SSO support for GNOME and KDE Plasma
- [jdpipe/networkmanager-gpclient](https://github.com/jdpipe/networkmanager-gpclient) – NetworkManager VPN plugin that uses `gpclient`
## 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**. Start the trial in the app by verifying your email address with a one-time code. Installing the app alone does not start the trial.
### 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) | Rust wrapper crate | [MIT](./crates/openconnect/LICENSE) |
| [upstream OpenConnect](./crates/openconnect/deps/openconnect) | C library | [LGPL-2.1](./crates/openconnect/deps/openconnect/COPYING.LGPL) |
| [common](./crates/common) | Crate | [MIT](./crates/common/LICENSE) |
| [browser-launcher](./crates/browser-launcher) | Crate | [MIT](./crates/browser-launcher/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) |
- crate [gpapi](./crates/gpapi): [MIT](./crates/gpapi/LICENSE)
- crate [openconnect](./crates/openconnect): [GPL-3.0](./crates/openconnect/LICENSE)
- crate [common](./crates/common): [GPL-3.0](./crates/common/LICENSE)
- app [gpservice](./apps/gpservice): [GPL-3.0](./apps/gpservice/LICENSE)
- app [gpclient](./apps/gpclient): [GPL-3.0](./apps/gpclient/LICENSE)
- app [gpauth](./apps/gpauth): [GPL-3.0](./apps/gpauth/LICENSE)
- app [gpgui-helper](./apps/gpgui-helper): [GPL-3.0](./apps/gpgui-helper/LICENSE)
+13 -20
View File
@@ -1,36 +1,29 @@
[package]
name = "gpauth"
rust-version.workspace = true
authors.workspace = true
version.workspace = true
edition.workspace = true
license.workspace = true
[build-dependencies]
tauri-build = { version = "2", features = [], optional = true }
tauri-build = { version = "1.5", features = [] }
[dependencies]
common = { path = "../../crates/common" }
gpapi = { path = "../../crates/gpapi", features = ["clap", "logger"] }
auth = { path = "../../crates/auth", features = ["browser-auth"] }
# Shared dependencies
gpapi = { path = "../../crates/gpapi", features = [
"tauri",
"clap",
"browser-auth",
] }
anyhow.workspace = true
clap.workspace = true
env_logger.workspace = true
log.workspace = true
regex.workspace = true
serde_json.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] }
tokio.workspace = true
tokio-util.workspace = true
tempfile.workspace = true
html-escape = "0.2.13"
webkit2gtk = "0.18.2"
tauri = { workspace = true, features = ["http-all"] }
compile-time.workspace = true
# Pin to specific version due to MSRV
home = "=0.5.11"
# webview auth dependencies
tauri = { workspace = true, optional = true }
[features]
default = ["webview-auth"]
webview-auth = ["auth/webview-auth", "dep:tauri", "dep:tauri-build"]
release-devtools = ["auth/release-devtools"]
-19
View File
@@ -1,19 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>LSUIElement</key>
<true/>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>GlobalProtect authentication callback</string>
<key>CFBundleURLSchemes</key>
<array>
<string>globalprotectcallback</string>
</array>
</dict>
</array>
</dict>
</plist>
-60
View File
@@ -1,63 +1,3 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
println!("cargo:rerun-if-env-changed=GPAUTH_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
println!(
"cargo:rustc-env=GPAUTH_GIT_COMMIT={}",
resolve_commit(&repo_root, &source_commit)
);
#[cfg(feature = "webview-auth")]
tauri_build::build()
}
fn resolve_commit(repo_root: &PathBuf, source_commit: &PathBuf) -> String {
env_commit("GPAUTH_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(source_commit))
.or_else(|| git_commit(repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string())
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=9", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

After

Width:  |  Height:  |  Size: 83 KiB

+523
View File
@@ -0,0 +1,523 @@
use std::{
rc::Rc,
sync::Arc,
time::{Duration, Instant},
};
use anyhow::bail;
use gpapi::{
auth::SamlAuthData,
error::AuthDataParseError,
gp_params::GpParams,
portal::{prelogin, Prelogin},
utils::{redact::redact_uri, window::WindowExt},
};
use log::{info, warn};
use regex::Regex;
use tauri::{AppHandle, Window, WindowEvent, WindowUrl};
use tokio::sync::{mpsc, oneshot, RwLock};
use tokio_util::sync::CancellationToken;
use webkit2gtk::{
gio::Cancellable,
glib::{GString, TimeSpan},
LoadEvent, SettingsExt, TLSErrorsPolicy, URIResponse, URIResponseExt, WebContextExt, WebResource, WebResourceExt,
WebView, WebViewExt, WebsiteDataManagerExtManual, WebsiteDataTypes,
};
enum AuthDataError {
/// Failed to load page due to TLS error
TlsError,
/// 1. Found auth data in headers/body but it's invalid
/// 2. Loaded an empty page, failed to load page. etc.
Invalid,
/// No auth data found in headers/body
NotFound,
}
type AuthResult = Result<SamlAuthData, AuthDataError>;
pub(crate) struct AuthWindow<'a> {
app_handle: AppHandle,
server: &'a str,
saml_request: &'a str,
user_agent: &'a str,
gp_params: Option<GpParams>,
clean: bool,
}
impl<'a> AuthWindow<'a> {
pub fn new(app_handle: AppHandle) -> Self {
Self {
app_handle,
server: "",
saml_request: "",
user_agent: "",
gp_params: None,
clean: false,
}
}
pub fn server(mut self, server: &'a str) -> Self {
self.server = server;
self
}
pub fn saml_request(mut self, saml_request: &'a str) -> Self {
self.saml_request = saml_request;
self
}
pub fn user_agent(mut self, user_agent: &'a str) -> Self {
self.user_agent = user_agent;
self
}
pub fn gp_params(mut self, gp_params: GpParams) -> Self {
self.gp_params.replace(gp_params);
self
}
pub fn clean(mut self, clean: bool) -> Self {
self.clean = clean;
self
}
pub async fn open(&self) -> anyhow::Result<SamlAuthData> {
info!("Open auth window, user_agent: {}", self.user_agent);
let window = Window::builder(&self.app_handle, "auth_window", WindowUrl::default())
.title("GlobalProtect Login")
// .user_agent(self.user_agent)
.focused(true)
.visible(false)
.center()
.build()?;
let window = Arc::new(window);
let cancel_token = CancellationToken::new();
let cancel_token_clone = cancel_token.clone();
window.on_window_event(move |event| {
if let WindowEvent::CloseRequested { .. } = event {
cancel_token_clone.cancel();
}
});
let window_clone = Arc::clone(&window);
let timeout_secs = 15;
tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(timeout_secs)).await;
let visible = window_clone.is_visible().unwrap_or(false);
if !visible {
info!("Try to raise auth window after {} seconds", timeout_secs);
raise_window(&window_clone);
}
});
tokio::select! {
_ = cancel_token.cancelled() => {
bail!("Auth cancelled");
}
saml_result = self.auth_loop(&window) => {
window.close()?;
saml_result
}
}
}
async fn auth_loop(&self, window: &Arc<Window>) -> anyhow::Result<SamlAuthData> {
let saml_request = self.saml_request.to_string();
let (auth_result_tx, mut auth_result_rx) = mpsc::unbounded_channel::<AuthResult>();
let raise_window_cancel_token: Arc<RwLock<Option<CancellationToken>>> = Default::default();
let gp_params = self.gp_params.as_ref().unwrap();
let tls_err_policy = if gp_params.ignore_tls_errors() {
TLSErrorsPolicy::Ignore
} else {
TLSErrorsPolicy::Fail
};
if self.clean {
clear_webview_cookies(window).await?;
}
let raise_window_cancel_token_clone = Arc::clone(&raise_window_cancel_token);
window.with_webview(move |wv| {
let wv = wv.inner();
if let Some(context) = wv.context() {
context.set_tls_errors_policy(tls_err_policy);
}
if let Some(settings) = wv.settings() {
let ua = settings.user_agent().unwrap_or("".into());
info!("Auth window user agent: {}", ua);
}
// Load the initial SAML request
load_saml_request(&wv, &saml_request);
let auth_result_tx_clone = auth_result_tx.clone();
wv.connect_load_changed(move |wv, event| {
if event == LoadEvent::Started {
let Ok(mut cancel_token) = raise_window_cancel_token_clone.try_write() else {
return;
};
// Cancel the raise window task
if let Some(cancel_token) = cancel_token.take() {
cancel_token.cancel();
}
return;
}
if event != LoadEvent::Finished {
return;
}
if let Some(main_resource) = wv.main_resource() {
let uri = main_resource.uri().unwrap_or("".into());
if uri.is_empty() {
warn!("Loaded an empty uri");
send_auth_result(&auth_result_tx_clone, Err(AuthDataError::Invalid));
return;
}
info!("Loaded uri: {}", redact_uri(&uri));
if uri.starts_with("globalprotectcallback:") {
return;
}
read_auth_data(&main_resource, auth_result_tx_clone.clone());
}
});
let auth_result_tx_clone = auth_result_tx.clone();
wv.connect_load_failed_with_tls_errors(move |_wv, uri, cert, err| {
let redacted_uri = redact_uri(uri);
warn!(
"Failed to load uri: {} with error: {}, cert: {}",
redacted_uri, err, cert
);
send_auth_result(&auth_result_tx_clone, Err(AuthDataError::TlsError));
true
});
wv.connect_load_failed(move |_wv, _event, uri, err| {
let redacted_uri = redact_uri(uri);
if !uri.starts_with("globalprotectcallback:") {
warn!("Failed to load uri: {} with error: {}", redacted_uri, err);
}
// NOTE: Don't send error here, since load_changed event will be triggered after this
// send_auth_result(&auth_result_tx, Err(AuthDataError::Invalid));
// true to stop other handlers from being invoked for the event. false to propagate the event further.
true
});
})?;
let portal = self.server.to_string();
loop {
if let Some(auth_result) = auth_result_rx.recv().await {
match auth_result {
Ok(auth_data) => return Ok(auth_data),
Err(AuthDataError::TlsError) => bail!("TLS error: certificate verify failed"),
Err(AuthDataError::NotFound) => {
info!("No auth data found, it may not be the /SAML20/SP/ACS endpoint");
// The user may need to interact with the auth window, raise it in 3 seconds
if !window.is_visible().unwrap_or(false) {
let window = Arc::clone(window);
let cancel_token = CancellationToken::new();
raise_window_cancel_token.write().await.replace(cancel_token.clone());
tokio::spawn(async move {
let delay_secs = 1;
info!("Raise window in {} second(s)", delay_secs);
tokio::select! {
_ = tokio::time::sleep(Duration::from_secs(delay_secs)) => {
raise_window(&window);
}
_ = cancel_token.cancelled() => {
info!("Raise window cancelled");
}
}
});
}
}
Err(AuthDataError::Invalid) => {
info!("Got invalid auth data, retrying...");
window.with_webview(|wv| {
let wv = wv.inner();
wv.run_javascript(r#"
var loading = document.createElement("div");
loading.innerHTML = '<div style="position: absolute; width: 100%; text-align: center; font-size: 20px; font-weight: bold; top: 50%; left: 50%; transform: translate(-50%, -50%);">Got invalid token, retrying...</div>';
loading.style = "position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.85); z-index: 99999;";
document.body.appendChild(loading);
"#,
Cancellable::NONE,
|_| info!("Injected loading element successfully"),
);
})?;
let saml_request = portal_prelogin(&portal, gp_params).await?;
window.with_webview(move |wv| {
let wv = wv.inner();
load_saml_request(&wv, &saml_request);
})?;
}
}
}
}
}
}
fn raise_window(window: &Arc<Window>) {
let visible = window.is_visible().unwrap_or(false);
if !visible {
if let Err(err) = window.raise() {
warn!("Failed to raise window: {}", err);
}
}
}
pub async fn portal_prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result<String> {
match prelogin(portal, gp_params).await? {
Prelogin::Saml(prelogin) => Ok(prelogin.saml_request().to_string()),
Prelogin::Standard(_) => bail!("Received non-SAML prelogin response"),
}
}
fn send_auth_result(auth_result_tx: &mpsc::UnboundedSender<AuthResult>, auth_result: AuthResult) {
if let Err(err) = auth_result_tx.send(auth_result) {
warn!("Failed to send auth event: {}", err);
}
}
fn load_saml_request(wv: &Rc<WebView>, saml_request: &str) {
if saml_request.starts_with("http") {
info!("Load the SAML request as URI...");
wv.load_uri(saml_request);
} else {
info!("Load the SAML request as HTML...");
wv.load_html(saml_request, None);
}
}
fn read_auth_data_from_headers(response: &URIResponse) -> AuthResult {
response.http_headers().map_or_else(
|| {
info!("No headers found in response");
Err(AuthDataError::NotFound)
},
|mut headers| match headers.get("saml-auth-status") {
Some(status) if status == "1" => {
let username = headers.get("saml-username").map(GString::into);
let prelogin_cookie = headers.get("prelogin-cookie").map(GString::into);
let portal_userauthcookie = headers.get("portal-userauthcookie").map(GString::into);
if SamlAuthData::check(&username, &prelogin_cookie, &portal_userauthcookie) {
return Ok(SamlAuthData::new(
username.unwrap(),
prelogin_cookie,
portal_userauthcookie,
));
}
info!("Found invalid auth data in headers");
Err(AuthDataError::Invalid)
}
Some(status) => {
info!("Found invalid SAML status: {} in headers", status);
Err(AuthDataError::Invalid)
}
None => {
info!("No saml-auth-status header found");
Err(AuthDataError::NotFound)
}
},
)
}
fn read_auth_data_from_body<F>(main_resource: &WebResource, callback: F)
where
F: FnOnce(Result<SamlAuthData, AuthDataParseError>) + Send + 'static,
{
main_resource.data(Cancellable::NONE, |data| match data {
Ok(data) => {
let html = String::from_utf8_lossy(&data);
callback(read_auth_data_from_html(&html));
}
Err(err) => {
info!("Failed to read response body: {}", err);
callback(Err(AuthDataParseError::Invalid))
}
});
}
fn read_auth_data_from_html(html: &str) -> Result<SamlAuthData, AuthDataParseError> {
if html.contains("Temporarily Unavailable") {
info!("Found 'Temporarily Unavailable' in HTML, auth failed");
return Err(AuthDataParseError::Invalid);
}
SamlAuthData::from_html(html).or_else(|err| {
if let Some(gpcallback) = extract_gpcallback(html) {
info!("Found gpcallback from html...");
SamlAuthData::from_gpcallback(&gpcallback)
} else {
Err(err)
}
})
}
fn extract_gpcallback(html: &str) -> Option<String> {
let re = Regex::new(r#"globalprotectcallback:[^"]+"#).unwrap();
re.captures(html)
.and_then(|captures| captures.get(0))
.map(|m| html_escape::decode_html_entities(m.as_str()).to_string())
}
fn read_auth_data(main_resource: &WebResource, auth_result_tx: mpsc::UnboundedSender<AuthResult>) {
let Some(response) = main_resource.response() else {
info!("No response found in main resource");
send_auth_result(&auth_result_tx, Err(AuthDataError::Invalid));
return;
};
info!("Trying to read auth data from response headers...");
match read_auth_data_from_headers(&response) {
Ok(auth_data) => {
info!("Got auth data from headers");
send_auth_result(&auth_result_tx, Ok(auth_data));
}
Err(AuthDataError::Invalid) => {
info!("Found invalid auth data in headers, trying to read from body...");
read_auth_data_from_body(main_resource, move |auth_result| {
// Since we have already found invalid auth data in headers, which means this could be the `/SAML20/SP/ACS` endpoint
// any error result from body should be considered as invalid, and trigger a retry
let auth_result = auth_result.map_err(|err| {
info!("Failed to read auth data from body: {}", err);
AuthDataError::Invalid
});
send_auth_result(&auth_result_tx, auth_result);
});
}
Err(AuthDataError::NotFound) => {
info!("No auth data found in headers, trying to read from body...");
let is_acs_endpoint = main_resource.uri().map_or(false, |uri| uri.contains("/SAML20/SP/ACS"));
read_auth_data_from_body(main_resource, move |auth_result| {
// If the endpoint is `/SAML20/SP/ACS` and no auth data found in body, it should be considered as invalid
let auth_result = auth_result.map_err(|err| {
info!("Failed to read auth data from body: {}", err);
if !is_acs_endpoint && matches!(err, AuthDataParseError::NotFound) {
AuthDataError::NotFound
} else {
AuthDataError::Invalid
}
});
send_auth_result(&auth_result_tx, auth_result)
});
}
Err(AuthDataError::TlsError) => {
// NOTE: This is unreachable
info!("TLS error found in headers, trying to read from body...");
send_auth_result(&auth_result_tx, Err(AuthDataError::TlsError));
}
}
}
pub(crate) async fn clear_webview_cookies(window: &Window) -> anyhow::Result<()> {
let (tx, rx) = oneshot::channel::<Result<(), String>>();
window.with_webview(|wv| {
let send_result = move |result: Result<(), String>| {
if let Err(err) = tx.send(result) {
info!("Failed to send result: {:?}", err);
}
};
let wv = wv.inner();
let context = match wv.context() {
Some(context) => context,
None => {
send_result(Err("No webview context found".into()));
return;
}
};
let data_manager = match context.website_data_manager() {
Some(manager) => manager,
None => {
send_result(Err("No data manager found".into()));
return;
}
};
let now = Instant::now();
data_manager.clear(
WebsiteDataTypes::COOKIES,
TimeSpan(0),
Cancellable::NONE,
move |result| match result {
Err(err) => {
send_result(Err(err.to_string()));
}
Ok(_) => {
info!("Cookies cleared in {} ms", now.elapsed().as_millis());
send_result(Ok(()));
}
},
);
})?;
rx.await?.map_err(|err| anyhow::anyhow!(err))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn extract_gpcallback_some() {
let html = r#"
<meta http-equiv="refresh" content="0; URL=globalprotectcallback:PGh0bWw+PCEtLSA8c">
<meta http-equiv="refresh" content="0; URL=globalprotectcallback:PGh0bWw+PCEtLSA8c">
"#;
assert_eq!(
extract_gpcallback(html).as_deref(),
Some("globalprotectcallback:PGh0bWw+PCEtLSA8c")
);
}
#[test]
fn extract_gpcallback_cas() {
let html = r#"
<meta http-equiv="refresh" content="0; URL=globalprotectcallback:cas-as=1&amp;[email protected]&amp;token=very_long_string">
"#;
assert_eq!(
extract_gpcallback(html).as_deref(),
Some("globalprotectcallback:cas-as=1&[email protected]&token=very_long_string")
);
}
#[test]
fn extract_gpcallback_none() {
let html = r#"
<meta http-equiv="refresh" content="0; URL=PGh0bWw+PCEtLSA8c">
"#;
assert_eq!(extract_gpcallback(html), None);
}
}
-58
View File
@@ -1,58 +0,0 @@
use std::{
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
time::Duration,
};
use tauri::RunEvent;
pub fn run() -> anyhow::Result<()> {
let handled = Arc::new(AtomicBool::new(false));
let timeout_handled = Arc::clone(&handled);
let app = tauri::Builder::default()
.setup(move |app| {
#[cfg(target_os = "macos")]
app.set_activation_policy(tauri::ActivationPolicy::Accessory);
let app_handle = app.handle().clone();
tauri::async_runtime::spawn(async move {
tokio::time::sleep(Duration::from_secs(10)).await;
if !timeout_handled.swap(true, Ordering::AcqRel) {
app_handle.exit(1);
}
});
Ok(())
})
.build(crate::tauri_context::get())?;
app.run(move |app_handle, event| {
let RunEvent::Opened { urls } = event else {
return;
};
let Some(callback) = urls
.into_iter()
.find(|url| url.scheme().eq_ignore_ascii_case("globalprotectcallback"))
else {
return;
};
if handled.swap(true, Ordering::AcqRel) {
return;
}
let app_handle = app_handle.clone();
tauri::async_runtime::spawn(async move {
let exit_code = match auth::forward_auth_callback(callback.as_str()).await {
Ok(()) => 0,
Err(err) => {
eprintln!("Failed to forward authentication callback: {err}");
1
}
};
app_handle.exit(exit_code);
});
});
Ok(())
}
+175 -366
View File
@@ -1,40 +1,29 @@
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
use auth::forward_auth_callback;
use auth::{BrowserAuthenticator, auth_prelogin};
use std::{env::temp_dir, fs, os::unix::fs::PermissionsExt};
use clap::Parser;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
use clap::Subcommand;
#[cfg(feature = "webview-auth")]
use gpapi::auth::AuthWindowTheme;
use gpapi::{
auth::{AuthenticationCancelled, SamlAuthData, SamlAuthResult},
clap::{Args, InfoLevelVerbosity, args::Os, handle_error},
gp_params::GpParams,
log_format::LogFormat,
os_profile::{ClientOs, OsProfile},
auth::{SamlAuthData, SamlAuthResult},
clap::args::Os,
gp_params::{ClientOs, GpParams},
process::browser_authenticator::BrowserAuthenticator,
utils::{normalize_server, openssl},
GP_USER_AGENT,
};
use log::info;
use log::{info, LevelFilter};
use serde_json::json;
use std::net::IpAddr;
use tauri::{App, AppHandle, RunEvent};
use tempfile::NamedTempFile;
use tokio::{io::AsyncReadExt, net::TcpListener};
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPAUTH_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
use crate::auth_window::{portal_prelogin, AuthWindow};
#[derive(Parser)]
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
#[derive(Parser, Clone)]
#[command(
version = VERSION,
author,
about = "The authentication component for the GlobalProtect VPN client, supports the SSO authentication method.",
args_conflicts_with_subcommands = true,
subcommand_negates_reqs = true,
help_template = "\
{before-help}{name} {version}
{author}
@@ -49,12 +38,8 @@ See 'gpauth -h' for more information.
"
)]
struct Cli {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[command(subcommand)]
command: Option<CliCommand>,
#[arg(required = true, help = "The portal server to authenticate")]
server: Option<String>,
#[arg(help = "The portal server to authenticate")]
server: String,
#[arg(long, help = "Treating the server as a gateway")]
gateway: bool,
@@ -62,27 +47,17 @@ struct Cli {
#[arg(long, help = "The SAML authentication request")]
saml_request: Option<String>,
#[arg(long, value_enum, default_value_t = Os::default())]
#[arg(long, default_value = GP_USER_AGENT, help = "The user agent to use")]
user_agent: String,
#[arg(long, default_value = "Linux")]
os: Os,
#[arg(long, help = "Use this runtime host ID when building the OS profile")]
host_id: Option<String>,
#[arg(long)]
os_version: Option<String>,
#[arg(long, help = "Override the GlobalProtect client version reported to the server")]
client_version: Option<String>,
#[arg(
short,
long,
help = "Use SSL client certificate file in pkcs#8 (.pem) or pkcs#12 (.p12, .pfx) format"
)]
certificate: Option<String>,
#[arg(short = 'k', long, help = "Use SSL private key file in pkcs#8 (.pem) format")]
sslkey: Option<String>,
#[arg(short = 'p', long, help = "The key passphrase of the private key")]
key_password: Option<String>,
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
hidpi: bool,
#[arg(long, help = "Get around the OpenSSL `unsafe legacy renegotiation` error")]
fix_openssl: bool,
@@ -90,77 +65,94 @@ struct Cli {
#[arg(long, help = "Ignore TLS errors")]
ignore_tls_errors: bool,
#[arg(
long,
value_enum,
default_value_t = LogFormat::Text,
help = "Log output format. JSON is intended for non-interactive consumers; interactive prompts remain text."
)]
log_format: LogFormat,
#[arg(long, help = "Clean the cache of the embedded browser")]
clean: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "Use the default browser for authentication")]
default_browser: bool,
#[arg(
long,
help = "Use external browser authentication. With no value, auto-select Chrome, Firefox, then system default. Use `default` for the system default browser or `remote` for headless servers.",
default_missing_value = "auto",
help = "The browser to use for authentication, e.g., `default`, `firefox`, `chrome`, `chromium`, `remote`, or the path to the browser executable. Use `remote` for headless servers",
default_missing_value = "default",
num_args=0..=1
)]
browser: Option<String>,
#[arg(long, help = "Listen on this IP address when using '--browser remote'")]
browser_listen: Option<IpAddr>,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
hidpi: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "Clean the cache of the embedded browser")]
pub clean: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "Set the embedded authentication window title")]
window_title: Option<String>,
#[cfg(feature = "webview-auth")]
#[arg(long, value_enum, default_value_t = AuthWindowTheme::default(), help = "Set the embedded authentication window appearance")]
window_theme: AuthWindowTheme,
#[command(flatten)]
verbose: InfoLevelVerbosity,
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[derive(Subcommand)]
enum CliCommand {
#[command(hide = true)]
AuthCallback {
#[arg(help = "The globalprotectcallback URL to forward")]
callback: String,
},
}
impl Args for Cli {
fn fix_openssl(&self) -> bool {
self.fix_openssl
}
fn ignore_tls_errors(&self) -> bool {
self.ignore_tls_errors
}
fn log_format(&self) -> LogFormat {
self.log_format
}
}
impl Cli {
async fn run(&mut self) -> anyhow::Result<()> {
if self.ignore_tls_errors {
info!("TLS errors will be ignored");
}
let mut openssl_conf = self.prepare_env()?;
self.server = normalize_server(&self.server)?;
let gp_params = self.build_gp_params();
// Get the initial SAML request
let saml_request = match self.saml_request {
Some(ref saml_request) => saml_request.clone(),
None => portal_prelogin(&self.server, &gp_params).await?,
};
let browser_auth = if let Some(browser) = &self.browser {
Some(BrowserAuthenticator::new_with_browser(&saml_request, browser))
} else if self.default_browser {
Some(BrowserAuthenticator::new(&saml_request))
} else {
None
};
if let Some(browser_auth) = browser_auth {
if let Some(auth_data) = browser_auth.authenticate()? {
info!("Authentication completed");
println!("{}", json!(SamlAuthResult::Success(auth_data)));
return Ok(());
}
info!("Please continue the authentication process in the default browser");
let auth_result = match wait_auth_data().await {
Ok(auth_data) => SamlAuthResult::Success(auth_data),
Err(err) => SamlAuthResult::Failure(format!("{}", err)),
};
info!("Authentication completed");
println!("{}", json!(auth_result));
return Ok(());
}
self.saml_request.replace(saml_request);
let app = create_app(self.clone())?;
app.run(move |_app_handle, event| {
if let RunEvent::Exit = event {
if let Some(file) = openssl_conf.take() {
if let Err(err) = file.close() {
info!("Error closing OpenSSL config file: {}", err);
}
}
}
});
Ok(())
}
fn prepare_env(&self) -> anyhow::Result<Option<NamedTempFile>> {
#[cfg(feature = "webview-auth")]
gpapi::utils::env_utils::patch_gui_runtime_env(self.hidpi);
std::env::set_var("WEBKIT_DISABLE_COMPOSITING_MODE", "1");
if self.hidpi {
info!("Setting GDK_SCALE=2 and GDK_DPI_SCALE=0.5");
std::env::set_var("GDK_SCALE", "2");
std::env::set_var("GDK_DPI_SCALE", "0.5");
}
if self.fix_openssl {
info!("Fixing OpenSSL environment");
@@ -172,285 +164,102 @@ impl Cli {
Ok(None)
}
async fn run(&self) -> anyhow::Result<()> {
if self.browser_listen.is_some()
&& !matches!(self.browser.as_deref(), Some(browser) if browser.eq_ignore_ascii_case("remote"))
{
anyhow::bail!("The '--browser-listen' option requires '--browser remote'");
}
if self.ignore_tls_errors {
info!("TLS errors will be ignored");
}
let openssl_conf = self.prepare_env()?;
let server = normalize_server(self.server.as_deref().expect("server is required for authentication"))?;
let gp_params = self.build_gp_params();
info!(
"gpauth auth host-id: {}",
gp_params.os_profile().host_identity().host_id()
);
let auth_request = match self.saml_request.as_deref() {
Some(auth_request) => auth_request.to_string(),
None => auth_prelogin(&server, &gp_params, self.external_browser_requested(), self.gateway).await?,
};
#[cfg(feature = "webview-auth")]
let browser = self
.browser
.as_deref()
.or_else(|| self.default_browser.then(|| "default"));
#[cfg(not(feature = "webview-auth"))]
let browser = self.browser.as_deref().or(Some("default"));
if let Some(browser) = browser {
let auth_host_id = gp_params.os_profile().host_identity().host_id().to_string();
let authenticator = BrowserAuthenticator::new(&auth_request, browser, self.browser_listen);
let auth_result = authenticator.authenticate().await;
print_auth_result(auth_result, Some(&auth_host_id));
// explicitly drop openssl_conf to avoid the unused variable warning
drop(openssl_conf);
return Ok(());
}
#[cfg(feature = "webview-auth")]
crate::webview_auth::authenticate(
server,
gp_params,
auth_request,
self.clean,
self.window_title.clone(),
self.window_theme,
openssl_conf,
)
.await?;
Ok(())
}
fn build_gp_params(&self) -> GpParams {
GpParams::builder(self.build_os_profile())
let gp_params = GpParams::builder()
.user_agent(&self.user_agent)
.client_os(ClientOs::from(&self.os))
.os_version(self.os_version.clone())
.ignore_tls_errors(self.ignore_tls_errors)
.certificate(self.certificate.clone())
.sslkey(self.sslkey.clone())
.key_password(self.key_password.clone())
.is_gateway(self.gateway)
.build()
.build();
gp_params
}
fn build_os_profile(&self) -> OsProfile {
let mut builder = OsProfile::builder(ClientOs::from(self.os));
if let Some(host_id) = self.host_id.as_deref() {
builder = builder.host_id_override(host_id);
}
if let Some(client_version) = self.client_version.as_deref() {
builder = builder.client_version(client_version);
}
builder.build()
}
async fn saml_auth(&self, app_handle: AppHandle) -> anyhow::Result<SamlAuthData> {
let auth_window = AuthWindow::new(app_handle)
.server(&self.server)
.user_agent(&self.user_agent)
.gp_params(self.build_gp_params())
.saml_request(self.saml_request.as_ref().unwrap())
.clean(self.clean);
fn external_browser_requested(&self) -> bool {
#[cfg(feature = "webview-auth")]
{
self.default_browser || self.browser.is_some()
}
#[cfg(not(feature = "webview-auth"))]
{
true
}
auth_window.open().await
}
}
fn init_logger(cli: &Cli) {
let Some(level) = cli.verbose.log_level_filter().to_level() else {
log::set_max_level(log::LevelFilter::Off);
return;
};
fn create_app(cli: Cli) -> anyhow::Result<App> {
let app = tauri::Builder::default()
.setup(|app| {
let app_handle = app.handle();
gpapi::logger::init(level, "com.yuezk.gpgui", "gpauth", cli.log_format);
tauri::async_runtime::spawn(async move {
let auth_result = match cli.saml_auth(app_handle.clone()).await {
Ok(auth_data) => SamlAuthResult::Success(auth_data),
Err(err) => SamlAuthResult::Failure(format!("{}", err)),
};
println!("{}", json!(auth_result));
});
Ok(())
})
.build(tauri::generate_context!())?;
Ok(app)
}
fn init_logger() {
env_logger::builder().filter_level(LevelFilter::Info).init();
}
pub async fn run() {
let cli = Cli::parse();
let mut cli = Cli::parse();
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
if let Some(CliCommand::AuthCallback { callback }) = &cli.command {
if let Err(err) = forward_auth_callback(callback).await {
eprintln!("Failed to forward authentication callback: {err}");
std::process::exit(1);
}
return;
}
init_logger(&cli);
init_logger();
info!("gpauth started: {}", VERSION);
if let Err(err) = cli.run().await {
handle_error(err, &cli);
eprintln!("\nError: {}", err);
if err.to_string().contains("unsafe legacy renegotiation") && !cli.fix_openssl {
eprintln!("\nRe-run it with the `--fix-openssl` option to work around this issue, e.g.:\n");
// Print the command
let args = std::env::args().collect::<Vec<_>>();
eprintln!("{} --fix-openssl {}\n", args[0], args[1..].join(" "));
}
std::process::exit(1);
}
}
pub fn print_auth_result(auth_result: anyhow::Result<SamlAuthData>, host_id: Option<&str>) {
let auth_result = match auth_result {
Ok(auth_data) => {
let auth_data = match host_id {
Some(host_id) => auth_data.with_host_id(host_id),
None => auth_data,
};
SamlAuthResult::Success(auth_data)
}
Err(err) if err.downcast_ref::<AuthenticationCancelled>().is_some() => SamlAuthResult::Cancelled,
Err(err) => SamlAuthResult::Failure(format!("{}", err)),
};
async fn wait_auth_data() -> anyhow::Result<SamlAuthData> {
// Start a local server to receive the browser authentication data
let listener = TcpListener::bind("127.0.0.1:0").await?;
let port = listener.local_addr()?.port();
let port_file = temp_dir().join("gpcallback.port");
println!("{}", json!(auth_result));
}
#[cfg(test)]
mod tests {
use super::*;
/// gpauth's own result already goes to stdout as JSON; this makes its *logs*
/// readable the same way, so a caller driving it does not have to parse prose
/// on stderr to find out why an attempt failed.
#[test]
fn log_format_defaults_to_text() {
let cli = Cli::try_parse_from(["gpauth", "portal.example.com"]).expect("gpauth args should parse");
assert_eq!(cli.log_format, LogFormat::Text);
}
#[test]
fn log_format_accepts_json() {
let cli =
Cli::try_parse_from(["gpauth", "portal.example.com", "--log-format", "json"]).expect("gpauth args should parse");
assert_eq!(cli.log_format, LogFormat::Json);
}
#[test]
fn os_defaults_to_runtime_os() {
let cli = Cli::try_parse_from(["gpauth", "portal.example.com"]).expect("gpauth args should parse");
assert_eq!(cli.os, Os::default());
}
#[test]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
fn callback_arguments_parse_separately() {
let cli = Cli::try_parse_from([
"gpauth",
"auth-callback",
"globalprotectcallback:cas-as=1&[email protected]&token=token",
])
.unwrap();
assert!(matches!(
cli.command,
Some(CliCommand::AuthCallback { callback }) if callback.starts_with("globalprotectcallback:")
));
assert!(cli.server.is_none());
}
#[test]
fn host_id_arg_sets_profile_host_id_seed() {
let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--host-id", "host-seed"])
.expect("gpauth args should parse");
let profile = cli.build_os_profile();
assert_eq!(profile.host_identity().host_id(), "host-seed");
}
#[test]
fn browser_arg_requests_external_browser() {
let cli =
Cli::try_parse_from(["gpauth", "portal.example.com", "--browser", "firefox"]).expect("gpauth args should parse");
assert!(cli.external_browser_requested());
}
#[test]
fn browser_without_value_uses_auto_mode() {
let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--browser"]).expect("gpauth args should parse");
assert_eq!(cli.browser.as_deref(), Some("auto"));
assert!(cli.external_browser_requested());
}
#[test]
fn browser_default_keeps_system_default_mode() {
let cli =
Cli::try_parse_from(["gpauth", "portal.example.com", "--browser", "default"]).expect("gpauth args should parse");
assert_eq!(cli.browser.as_deref(), Some("default"));
assert!(cli.external_browser_requested());
}
#[test]
fn browser_listen_accepts_ip_address() {
let cli = Cli::try_parse_from([
"gpauth",
"portal.example.com",
"--browser",
"remote",
"--browser-listen",
"192.168.107.15",
])
.expect("gpauth args should parse");
assert_eq!(cli.browser_listen, Some("192.168.107.15".parse().unwrap()));
}
#[test]
fn client_version_arg_sets_profile_client_version() {
let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--client-version", "legacy-client"])
.expect("gpauth args should parse");
let profile = cli.build_os_profile();
assert_eq!(profile.client_version(), "legacy-client");
assert!(profile.user_agent().contains("legacy-client"));
}
#[test]
fn client_certificate_args_parse() {
let cli = Cli::try_parse_from([
"gpauth",
"portal.example.com",
"--certificate",
"/tmp/client.pem",
"--sslkey",
"/tmp/client.key",
"--key-password",
"secret",
])
.expect("gpauth args should parse");
assert_eq!(cli.certificate.as_deref(), Some("/tmp/client.pem"));
assert_eq!(cli.sslkey.as_deref(), Some("/tmp/client.key"));
assert_eq!(cli.key_password.as_deref(), Some("secret"));
}
#[cfg(feature = "webview-auth")]
#[test]
fn auth_window_options_parse() {
let cli = Cli::try_parse_from([
"gpauth",
"portal.example.com",
"--window-title",
"GP Connect Login",
"--window-theme",
"dark",
])
.expect("gpauth window options should parse");
assert_eq!(cli.window_title.as_deref(), Some("GP Connect Login"));
assert_eq!(cli.window_theme, AuthWindowTheme::Dark);
}
// Write the port to a file
fs::write(&port_file, port.to_string())?;
fs::set_permissions(&port_file, fs::Permissions::from_mode(0o600))?;
// Remove the previous log file
let callback_log = temp_dir().join("gpcallback.log");
let _ = fs::remove_file(&callback_log);
info!("Listening authentication data on port {}", port);
info!(
"If it hangs, please check the logs at `{}` for more information",
callback_log.display()
);
let (mut socket, _) = listener.accept().await?;
info!("Received the browser authentication data from the socket");
let mut data = String::new();
socket.read_to_string(&mut data).await?;
// Remove the port file
fs::remove_file(&port_file)?;
let auth_data = SamlAuthData::from_gpcallback(&data)?;
Ok(auth_data)
}
+1 -27
View File
@@ -1,35 +1,9 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod auth_window;
mod cli;
#[cfg(all(target_os = "macos", feature = "webview-auth"))]
mod callback_app;
#[cfg(feature = "webview-auth")]
mod tauri_context;
#[cfg(feature = "webview-auth")]
mod webview_auth;
#[tokio::main]
async fn main() {
#[cfg(all(target_os = "macos", feature = "webview-auth"))]
if is_callback_app_launch() {
if let Err(err) = callback_app::run() {
eprintln!("Failed to handle authentication callback: {err}");
}
return;
}
cli::run().await;
}
#[cfg(all(target_os = "macos", feature = "webview-auth"))]
fn is_callback_app_launch() -> bool {
std::env::args_os().len() == 1
&& std::env::current_exe().is_ok_and(|executable| {
executable
.ancestors()
.any(|path| path.extension().is_some_and(|extension| extension == "app"))
})
}
-3
View File
@@ -1,3 +0,0 @@
pub fn get() -> tauri::Context<tauri::Wry> {
tauri::generate_context!()
}
-57
View File
@@ -1,57 +0,0 @@
use auth::{WebviewAuthenticator, apply_auth_theme};
use gpapi::{auth::AuthWindowTheme, gp_params::GpParams};
use log::info;
use tauri::RunEvent;
use tempfile::NamedTempFile;
use crate::cli::print_auth_result;
pub async fn authenticate(
server: String,
gp_params: GpParams,
auth_request: String,
clean: bool,
window_title: Option<String>,
window_theme: AuthWindowTheme,
mut openssl_conf: Option<NamedTempFile>,
) -> anyhow::Result<()> {
let auth_host_id = gp_params.os_profile().host_identity().host_id().to_string();
tauri::Builder::default()
.setup(move |app| {
#[cfg(target_os = "macos")]
app.set_activation_policy(tauri::ActivationPolicy::Accessory);
apply_auth_theme(app.handle(), window_theme);
let app_handle = app.handle().clone();
tauri::async_runtime::spawn(async move {
let authenticator = WebviewAuthenticator::new(&server, &gp_params)
.with_auth_request(&auth_request)
.with_webview_user_agent(gp_params.os_profile().webview_user_agent())
.with_clean(clean)
.with_window_title(window_title.as_deref().unwrap_or("GlobalProtect Login"))
.with_window_theme(window_theme);
let auth_result = authenticator.authenticate(&app_handle).await;
print_auth_result(auth_result, Some(&auth_host_id));
// Ensure the app exits after the authentication process
app_handle.exit(0);
});
Ok(())
})
.build(crate::tauri_context::get())?
.run(move |_app_handle, event| {
if let RunEvent::Exit = event {
if let Some(file) = openssl_conf.take() {
if let Err(err) = file.close() {
info!("Error closing OpenSSL config file: {}", err);
}
}
}
});
Ok(())
}
+39 -11
View File
@@ -1,19 +1,47 @@
{
"$schema": "https://cdn.jsdelivr.net/gh/tauri-apps/tauri@tauri-v2.1.1/crates/tauri-cli/config.schema.json",
"$schema": "https://cdn.jsdelivr.net/gh/tauri-apps/tauri@tauri-v1.5.0/tooling/cli/schema.json",
"build": {
"frontendDist": ["index.html"],
"distDir": [
"index.html"
],
"devPath": [
"index.html"
],
"beforeDevCommand": "",
"beforeBuildCommand": ""
"beforeBuildCommand": "",
"withGlobalTauri": false
},
"identifier": "com.yuezk.gpauth",
"productName": "GP Connect Login",
"app": {
"withGlobalTauri": false,
"package": {
"productName": "gpauth",
"version": "0.0.0"
},
"tauri": {
"allowlist": {
"all": false,
"http": {
"all": true,
"request": true,
"scope": [
"http://*",
"https://*"
]
}
},
"bundle": {
"active": true,
"targets": "deb",
"identifier": "com.yuezk.gpauth",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/[email protected]",
"icons/icon.icns",
"icons/icon.ico"
]
},
"security": {
"csp": null
}
},
"bundle": {
"icon": ["icons/icon.png"]
},
"windows": []
}
}
+6 -12
View File
@@ -1,6 +1,5 @@
[package]
name = "gpclient"
rust-version.workspace = true
authors.workspace = true
version.workspace = true
edition.workspace = true
@@ -9,26 +8,21 @@ license.workspace = true
[dependencies]
common = { path = "../../crates/common" }
gpapi = { path = "../../crates/gpapi", features = ["clap"] }
gphip = { path = "../../crates/gphip" }
openconnect = { path = "../../crates/openconnect" }
anyhow.workspace = true
askama = "0.12"
chrono = "0.4"
clap.workspace = true
env_logger.workspace = true
inquire = "0.9"
inquire = "0.6.2"
log.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] }
tokio-util.workspace = true
sysinfo.workspace = true
serde.workspace = true
serde_json.workspace = true
serde_urlencoded.workspace = true
whoami.workspace = true
tempfile.workspace = true
reqwest.workspace = true
directories.workspace = true
directories = "5.0"
compile-time.workspace = true
uzers.workspace = true
[features]
default = ["webview-auth"]
webview-auth = ["gpapi/webview-auth"]
xmltree = "0.11"
-65
View File
@@ -1,65 +0,0 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
// Installed OpenConnect lives in the private ../lib/gpclient directory.
// Build executables also locate their exact Cargo library; installers remove that rpath.
#[cfg(target_os = "macos")]
{
println!("cargo:rustc-link-arg=-Wl,-rpath,@executable_path/../lib/gpclient");
let library_dir = env::var("DEP_OPENCONNECT_LIB_DIR").expect("OpenConnect exports its build library directory");
println!("cargo:rustc-link-arg=-Wl,-rpath,{library_dir}");
}
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GPCLIENT_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
let commit = env_commit("GPCLIENT_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(&source_commit))
.or_else(|| git_commit(&repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string());
println!("cargo:rustc-env=GPCLIENT_GIT_COMMIT={commit}");
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=12", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
+37 -354
View File
@@ -1,44 +1,22 @@
use std::{
path::{Path, PathBuf},
str::FromStr,
};
use std::{env::temp_dir, fs::File};
use anyhow::bail;
use clap::{Parser, Subcommand};
use gpapi::{
clap::{Args, InfoLevelVerbosity, handle_error},
log_format::{LogFormat, write_json_record},
utils::openssl,
};
use log::info;
use sysinfo::{Pid, System};
use gpapi::utils::openssl;
use log::{info, LevelFilter};
use tempfile::NamedTempFile;
use tokio::fs;
use crate::{
GP_CLIENT_LOCK_FILE,
connect::{ConnectArgs, ConnectHandler},
diagnostics::DiagnosticsArgs,
disconnect::{DisconnectArgs, DisconnectHandler},
hip::{HipArgs, HipHandler},
launch_gui::{LaunchGuiArgs, LaunchGuiHandler},
};
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPCLIENT_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
pub(crate) struct SharedArgs<'a> {
pub(crate) struct SharedArgs {
pub(crate) fix_openssl: bool,
pub(crate) ignore_tls_errors: bool,
pub(crate) lock_file: &'a Path,
pub(crate) verbose: &'a InfoLevelVerbosity,
pub(crate) log_format: LogFormat,
}
#[derive(Subcommand)]
@@ -51,23 +29,6 @@ enum CliCommand {
LaunchGui(LaunchGuiArgs),
#[command(about = "Generate HIP report")]
Hip(HipArgs),
#[command(about = "Collect system diagnostics for a bug report without connecting to a VPN")]
Diagnostics(DiagnosticsArgs),
#[command(hide = true)]
DetectInternalHost {
#[arg(long)]
address: std::net::IpAddr,
#[arg(long)]
hostname: String,
},
#[command(hide = true)]
ResolveGateway {
host: String,
#[arg(long, default_value_t = 443)]
port: u16,
#[arg(long)]
disable_ipv6: bool,
},
}
#[derive(Parser)]
@@ -99,68 +60,9 @@ struct Cli {
fix_openssl: bool,
#[arg(long, help = "Ignore the TLS errors")]
ignore_tls_errors: bool,
#[arg(
long,
global = true,
default_value = GP_CLIENT_LOCK_FILE,
help = "Path to the gpclient PID lock file"
)]
lock_file: PathBuf,
#[arg(
long,
value_enum,
default_value_t = LogFormat::Text,
help = "Log output format. JSON is intended for non-interactive consumers; interactive prompts remain text."
)]
log_format: LogFormat,
#[command(flatten)]
verbose: InfoLevelVerbosity,
}
impl Args for Cli {
fn fix_openssl(&self) -> bool {
self.fix_openssl
}
fn ignore_tls_errors(&self) -> bool {
self.ignore_tls_errors
}
fn log_format(&self) -> LogFormat {
self.log_format
}
}
impl Cli {
fn can_run_alongside_client(&self) -> bool {
match &self.command {
CliCommand::Connect(_) => false,
CliCommand::LaunchGui(args) => args.is_auth_callback(),
_ => true,
}
}
async fn is_running(&self) -> bool {
let Ok(c) = fs::read_to_string(&self.lock_file).await else {
return false;
};
let Ok(pid) = Pid::from_str(c.trim()) else {
return false;
};
let s = System::new_all();
let Some(p) = s.process(pid) else {
return false;
};
p.exe()
.map(|exe| exe.to_string_lossy().contains("gpclient"))
.unwrap_or(false)
}
fn fix_openssl(&self) -> anyhow::Result<Option<NamedTempFile>> {
if self.fix_openssl {
let file = openssl::fix_openssl_env()?;
@@ -171,24 +73,12 @@ impl Cli {
}
async fn run(&self) -> anyhow::Result<()> {
if let CliCommand::Diagnostics(args) = &self.command {
return args.run(VERSION).await;
}
// check if an instance is running
if !self.can_run_alongside_client() && self.is_running().await {
bail!("Another instance of the client is already running");
}
// The temp file will be dropped automatically when the file handle is dropped
// So, declare it here to ensure it's not dropped
let _file = self.fix_openssl()?;
let shared_args = SharedArgs {
fix_openssl: self.fix_openssl,
ignore_tls_errors: self.ignore_tls_errors,
lock_file: &self.lock_file,
verbose: &self.verbose,
log_format: self.log_format,
};
if self.ignore_tls_errors {
@@ -197,264 +87,57 @@ impl Cli {
match &self.command {
CliCommand::Connect(args) => ConnectHandler::new(args, &shared_args).handle().await,
CliCommand::Disconnect(args) => DisconnectHandler::new(args, shared_args.lock_file).handle().await,
CliCommand::Disconnect(args) => DisconnectHandler::new(args).handle().await,
CliCommand::LaunchGui(args) => LaunchGuiHandler::new(args).handle().await,
CliCommand::Hip(args) => HipHandler::new(args).handle().await,
CliCommand::Diagnostics(_) => unreachable!("diagnostics is dispatched before VPN setup"),
CliCommand::DetectInternalHost { address, hostname } => {
let internal = gpapi::session::network::native::detect_in_helper(*address, hostname)?;
println!("{}", serde_json::to_string(&internal)?);
Ok(())
}
CliCommand::ResolveGateway {
host,
port,
disable_ipv6,
} => {
let addresses = gpapi::session::network::native::lookup_in_helper(host, *port, *disable_ipv6)?;
println!("{}", serde_json::to_string(&addresses)?);
Ok(())
}
}
}
}
fn build_logger(cli: &Cli) -> env_logger::Builder {
fn init_logger(command: &CliCommand) {
let mut builder = env_logger::builder();
builder.filter_level(cli.verbose.log_level_filter());
builder.filter_level(LevelFilter::Info);
// Text is env_logger's own format, so leave it untouched rather than
// reimplementing it.
if cli.log_format == LogFormat::Json {
builder.format(write_json_record);
// Output the log messages to a file if the command is the auth callback
if let CliCommand::LaunchGui(args) = command {
let auth_data = args.auth_data.as_deref().unwrap_or_default();
if !auth_data.is_empty() {
if let Ok(log_file) = File::create(temp_dir().join("gpcallback.log")) {
let target = Box::new(log_file);
builder.target(env_logger::Target::Pipe(target));
}
}
}
builder
builder.init();
}
pub(crate) async fn run() {
let cli = Cli::parse();
build_logger(&cli).init();
init_logger(&cli.command);
info!("gpclient started: {}", VERSION);
if let Err(err) = cli.run().await {
handle_error(err, &cli);
eprintln!("\nError: {}", err);
let err = err.to_string();
if err.contains("unsafe legacy renegotiation") && !cli.fix_openssl {
eprintln!("\nRe-run it with the `--fix-openssl` option to work around this issue, e.g.:\n");
// Print the command
let args = std::env::args().collect::<Vec<_>>();
eprintln!("{} --fix-openssl {}\n", args[0], args[1..].join(" "));
}
if err.contains("certificate verify failed") && !cli.ignore_tls_errors {
eprintln!("\nRe-run it with the `--ignore-tls-errors` option to ignore the certificate error, e.g.:\n");
// Print the command
let args = std::env::args().collect::<Vec<_>>();
eprintln!("{} --ignore-tls-errors {}\n", args[0], args[1..].join(" "));
}
std::process::exit(1);
}
}
#[cfg(test)]
mod tests {
use std::{
io::Write,
sync::{Arc, Mutex},
};
use log::Log;
use super::*;
#[test]
fn diagnostics_accepts_output_options_and_runs_alongside_the_client() {
let cli = Cli::try_parse_from([
"gpclient",
"--fix-openssl",
"diagnostics",
"--json",
"--output",
"report.json",
])
.unwrap();
assert!(matches!(cli.command, CliCommand::Diagnostics(_)));
assert!(cli.can_run_alongside_client());
}
#[test]
fn resolver_helper_runs_alongside_client_and_is_hidden_from_help() {
let cli = Cli::try_parse_from([
"gpclient",
"resolve-gateway",
"localhost",
"--port",
"444",
"--disable-ipv6",
])
.unwrap();
assert!(cli.can_run_alongside_client());
use clap::CommandFactory;
let help = Cli::command().render_help().to_string();
assert!(!help.contains("resolve-gateway"));
}
#[test]
fn lock_file_defaults_to_standard_path() {
let cli = Cli::try_parse_from(["gpclient", "connect", "portal.example.com"]).expect("cli should parse");
assert_eq!(cli.lock_file, PathBuf::from(GP_CLIENT_LOCK_FILE));
}
#[test]
fn lock_file_can_be_overridden_after_subcommand() {
let cli = Cli::try_parse_from([
"gpclient",
"connect",
"portal.example.com",
"--lock-file",
"/tmp/gpclient-portal.lock",
])
.expect("global lock file option should parse after subcommand");
assert_eq!(cli.lock_file, PathBuf::from("/tmp/gpclient-portal.lock"));
}
#[test]
fn hip_can_run_alongside_connected_client() {
let cli = Cli::try_parse_from([
"gpclient",
"hip",
"--client-version",
"6.2.4-49",
"--client-os",
"Mac",
"--cookie",
"user=alice",
"--md5",
"test",
])
.expect("HIP arguments should parse");
assert!(cli.can_run_alongside_client());
}
#[test]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
fn launch_gui_accepts_auth_callback() {
let cli = Cli::try_parse_from([
"gpclient",
"launch-gui",
"globalprotectcallback:cas-as=1&[email protected]&token=token",
])
.expect("authentication callback should parse");
assert!(matches!(
&cli.command,
CliCommand::LaunchGui(args) if args.is_auth_callback()
));
assert!(cli.can_run_alongside_client());
}
#[test]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
fn launch_gui_rejects_callback_with_minimized() {
assert!(Cli::try_parse_from(["gpclient", "launch-gui", "globalprotectcallback:token", "--minimized",]).is_err());
}
#[test]
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
fn launch_gui_rejects_non_callback_positional() {
assert!(Cli::try_parse_from(["gpclient", "launch-gui", "https://example.com/callback"]).is_err());
}
fn parse_cli(args: &[&str]) -> Cli {
Cli::try_parse_from(args).expect("arguments should parse")
}
/// Text stays the default: a plain `gpclient connect` must keep the output it
/// has always had, or every existing user's terminal changes under them.
#[test]
fn log_format_defaults_to_text() {
assert_eq!(parse_cli(&["gpclient", "disconnect"]).log_format, LogFormat::Text);
}
#[test]
fn log_format_accepts_json() {
assert_eq!(
parse_cli(&["gpclient", "--log-format", "json", "disconnect"]).log_format,
LogFormat::Json
);
}
/// An unknown value is a mistake worth reporting rather than silently
/// falling back to text, which would leave a caller parsing prose.
#[test]
fn log_format_rejects_an_unknown_value() {
// `.err()` rather than `unwrap_err()`: the Ok side is `Cli`, which is not
// `Debug`, and it is not worth deriving it just to print an error we expect.
let err = Cli::try_parse_from(["gpclient", "--log-format", "yaml", "disconnect"])
.err()
.expect("an unknown log format should be rejected");
let msg = err.to_string();
assert!(msg.contains("yaml"), "error should name the input: {msg}");
assert!(msg.contains("json"), "error should list the valid values: {msg}");
}
/// A `Write` that keeps what was written, so the logger can be driven for
/// real instead of asserting on how it was configured.
#[derive(Clone, Default)]
struct Captured(Arc<Mutex<Vec<u8>>>);
impl Captured {
fn contents(&self) -> String {
String::from_utf8(self.0.lock().unwrap().clone()).expect("log output should be UTF-8")
}
}
impl Write for Captured {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
fn log_one_record(args: &[&str]) -> String {
let captured = Captured::default();
let logger = build_logger(&parse_cli(args))
.target(env_logger::Target::Pipe(Box::new(captured.clone())))
.build();
// Drive the logger directly: `init()` installs a global that a second test
// could not replace.
logger.log(
&log::Record::builder()
.level(log::Level::Info)
.target("gpclient")
.args(format_args!("connected to {}", "vpn.example.com"))
.build(),
);
logger.flush();
captured.contents()
}
/// The point of the flag: with `json`, a caller gets fields, and gets them one
/// record per line so the stream can be read incrementally.
#[test]
fn json_format_emits_one_json_object_per_record() {
let out = log_one_record(&["gpclient", "--log-format", "json", "disconnect"]);
let lines: Vec<_> = out.lines().collect();
assert_eq!(lines.len(), 1, "expected exactly one line, got: {out:?}");
let v: serde_json::Value = serde_json::from_str(lines[0]).unwrap_or_else(|e| panic!("not JSON: {out:?} ({e})"));
assert_eq!(v["level"], "INFO");
assert_eq!(v["target"], "gpclient");
assert_eq!(v["message"], "connected to vpn.example.com");
}
#[test]
fn text_format_is_left_alone() {
let out = log_one_record(&["gpclient", "disconnect"]);
assert!(out.contains("connected to vpn.example.com"), "message missing: {out:?}");
assert!(
serde_json::from_str::<serde_json::Value>(out.trim()).is_err(),
"text output should not be JSON: {out:?}"
);
}
}
+436
View File
@@ -0,0 +1,436 @@
use std::{cell::RefCell, fs, sync::Arc};
use anyhow::bail;
use clap::Args;
use common::vpn_utils::find_csd_wrapper;
use gpapi::{
auth::SamlAuthResult,
clap::args::Os,
credential::{Credential, PasswordCredential},
error::PortalError,
gateway::{gateway_login, GatewayLogin},
gp_params::{ClientOs, GpParams},
portal::{prelogin, retrieve_config, Prelogin},
process::{
auth_launcher::SamlAuthLauncher,
users::{get_non_root_user, get_user_by_name},
},
utils::{request::RequestIdentityError, shutdown_signal},
GP_USER_AGENT,
};
use inquire::{Password, PasswordDisplayMode, Select, Text};
use log::info;
use openconnect::Vpn;
use crate::{cli::SharedArgs, GP_CLIENT_LOCK_FILE};
#[derive(Args)]
pub(crate) struct ConnectArgs {
#[arg(help = "The portal server to connect to")]
server: String,
#[arg(short, long, help = "The gateway to connect to, it will prompt if not specified")]
gateway: Option<String>,
#[arg(short, long, help = "The username to use, it will prompt if not specified")]
user: Option<String>,
#[arg(long, help = "Read the password from standard input")]
passwd_on_stdin: bool,
#[arg(long, help = "Read the cookie from standard input")]
cookie_on_stdin: bool,
#[arg(long, short, help = "The VPNC script to use")]
script: Option<String>,
#[arg(long, help = "Connect the server as a gateway, instead of a portal")]
as_gateway: bool,
#[arg(
long,
help = "Use the default CSD wrapper to generate the HIP report and send it to the server"
)]
hip: bool,
#[arg(
short,
long,
help = "Use SSL client certificate file in pkcs#8 (.pem) or pkcs#12 (.p12, .pfx) format"
)]
certificate: Option<String>,
#[arg(short = 'k', long, help = "Use SSL private key file in pkcs#8 (.pem) format")]
sslkey: Option<String>,
#[arg(short = 'p', long, help = "The key passphrase of the private key")]
key_password: Option<String>,
#[arg(long, help = "Same as the '--csd-user' option in the openconnect command")]
csd_user: Option<String>,
#[arg(long, help = "Same as the '--csd-wrapper' option in the openconnect command")]
csd_wrapper: Option<String>,
#[arg(long, default_value = "300", help = "Reconnection retry timeout in seconds")]
reconnect_timeout: u32,
#[arg(short, long, help = "Request MTU from server (legacy servers only)")]
mtu: Option<u32>,
#[arg(long, help = "Do not ask for IPv6 connectivity")]
disable_ipv6: bool,
#[arg(long, default_value = GP_USER_AGENT, help = "The user agent to use")]
user_agent: String,
#[arg(long, value_enum, default_value_t = ConnectArgs::default_os())]
os: Os,
#[arg(long, help = "If not specified, it will be computed based on the --os option")]
os_version: Option<String>,
#[arg(long, help = "Disable DTLS and ESP")]
no_dtls: bool,
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
hidpi: bool,
#[arg(long, help = "Do not reuse the remembered authentication cookie")]
clean: bool,
#[arg(long, help = "Use the default browser to authenticate")]
default_browser: bool,
#[arg(
long,
help = "Use the specified browser to authenticate, e.g., `default`, `firefox`, `chrome`, `chromium`, `remote`, or the path to the browser executable. Use `remote` for headless servers",
default_missing_value = "default",
num_args=0..=1
)]
browser: Option<String>,
}
impl ConnectArgs {
fn default_os() -> Os {
if cfg!(target_os = "macos") {
Os::Mac
} else {
Os::Linux
}
}
fn os_version(&self) -> String {
if let Some(os_version) = self.os_version.as_deref() {
return os_version.to_string();
}
match self.os {
Os::Linux => format!("Linux {}", whoami::distro()),
Os::Windows => String::from("Microsoft Windows 11 Pro , 64-bit"),
Os::Mac => String::from("Apple Mac OS X 13.4.0"),
}
}
}
pub(crate) struct ConnectHandler<'a> {
args: &'a ConnectArgs,
shared_args: &'a SharedArgs,
latest_key_password: RefCell<Option<String>>,
}
impl<'a> ConnectHandler<'a> {
pub(crate) fn new(args: &'a ConnectArgs, shared_args: &'a SharedArgs) -> Self {
Self {
args,
shared_args,
latest_key_password: Default::default(),
}
}
fn build_gp_params(&self) -> GpParams {
GpParams::builder()
.user_agent(&self.args.user_agent)
.client_os(ClientOs::from(&self.args.os))
.os_version(self.args.os_version())
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
.certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone())
.build()
}
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
if self.args.default_browser && self.args.browser.is_some() {
bail!("Cannot use `--default-browser` and `--browser` options at the same time");
}
self.latest_key_password.replace(self.args.key_password.clone());
loop {
let Err(err) = self.handle_impl().await else {
return Ok(());
};
let Some(root_cause) = err.root_cause().downcast_ref::<RequestIdentityError>() else {
return Err(err);
};
match root_cause {
RequestIdentityError::NoKey => {
eprintln!("ERROR: No private key found in the certificate file");
eprintln!("ERROR: Please provide the private key file using the `-k` option");
return Ok(());
}
RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => {
// Decrypt the private key error, ask for the key password
let message = format!("Enter the {} passphrase:", cert_type);
let password = Password::new(&message)
.without_confirmation()
.with_display_mode(PasswordDisplayMode::Masked)
.prompt()?;
self.latest_key_password.replace(Some(password));
}
}
}
}
pub(crate) async fn handle_impl(&self) -> anyhow::Result<()> {
let server = self.args.server.as_str();
let as_gateway = self.args.as_gateway;
if as_gateway {
info!("Treating the server as a gateway");
return self.connect_gateway_with_prelogin(server).await;
}
let Err(err) = self.connect_portal_with_prelogin(server).await else {
return Ok(());
};
info!("Failed to connect portal with prelogin: {}", err);
if err.root_cause().downcast_ref::<PortalError>().is_some() {
info!("Trying the gateway authentication workflow...");
self.connect_gateway_with_prelogin(server).await?;
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.");
Ok(())
} else {
Err(err)
}
}
async fn connect_portal_with_prelogin(&self, portal: &str) -> anyhow::Result<()> {
let gp_params = self.build_gp_params();
let prelogin = prelogin(portal, &gp_params).await?;
let cred = self.obtain_credential(&prelogin, portal).await?;
let mut portal_config = retrieve_config(portal, &cred, &gp_params).await?;
let selected_gateway = match &self.args.gateway {
Some(gateway) => portal_config
.find_gateway(gateway)
.ok_or_else(|| anyhow::anyhow!("Cannot find gateway specified: {}", gateway))?,
None => {
portal_config.sort_gateways(prelogin.region());
let gateways = portal_config.gateways();
if gateways.len() > 1 {
let gateway = Select::new("Which gateway do you want to connect to?", gateways)
.with_vim_mode(true)
.prompt()?;
info!("Connecting to the selected gateway: {}", gateway);
gateway
} else {
info!("Connecting to the only available gateway: {}", gateways[0]);
gateways[0]
}
}
};
let gateway = selected_gateway.server();
let cred = portal_config.auth_cookie().into();
let cookie = match self.login_gateway(gateway, &cred, &gp_params).await {
Ok(cookie) => cookie,
Err(err) => {
info!("Gateway login failed: {}", err);
return self.connect_gateway_with_prelogin(gateway).await;
}
};
self.connect_gateway(gateway, &cookie).await
}
async fn connect_gateway_with_prelogin(&self, gateway: &str) -> anyhow::Result<()> {
info!("Performing the gateway authentication...");
let mut gp_params = self.build_gp_params();
gp_params.set_is_gateway(true);
let prelogin = prelogin(gateway, &gp_params).await?;
let cred = self.obtain_credential(&prelogin, gateway).await?;
let cookie = self.login_gateway(gateway, &cred, &gp_params).await?;
self.connect_gateway(gateway, &cookie).await
}
async fn login_gateway(&self, gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<String> {
let mut gp_params = gp_params.clone();
loop {
match gateway_login(gateway, cred, &gp_params).await? {
GatewayLogin::Cookie(cookie) => return Ok(cookie),
GatewayLogin::Mfa(message, input_str) => {
let otp = Text::new(&message).prompt()?;
gp_params.set_input_str(&input_str);
gp_params.set_otp(&otp);
info!("Retrying gateway login with MFA...");
}
}
}
}
async fn connect_gateway(&self, gateway: &str, cookie: &str) -> anyhow::Result<()> {
let mtu = self.args.mtu.unwrap_or(0);
let csd_uid = get_csd_uid(&self.args.csd_user)?;
let csd_wrapper = if self.args.csd_wrapper.is_some() {
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_string();
let vpn = Vpn::builder(gateway, cookie)
.script(self.args.script.clone())
.user_agent(self.args.user_agent.clone())
.os(Some(os))
.certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone())
.csd_uid(csd_uid)
.csd_wrapper(csd_wrapper)
.reconnect_timeout(self.args.reconnect_timeout)
.mtu(mtu)
.disable_ipv6(self.args.disable_ipv6)
.no_dtls(self.args.no_dtls)
.build()?;
let vpn = Arc::new(vpn);
let vpn_clone = vpn.clone();
// Listen for the interrupt signal in the background
tokio::spawn(async move {
shutdown_signal().await;
info!("Received the interrupt signal, disconnecting...");
vpn_clone.disconnect();
});
vpn.connect(write_pid_file);
if fs::metadata(GP_CLIENT_LOCK_FILE).is_ok() {
info!("Removing PID file");
fs::remove_file(GP_CLIENT_LOCK_FILE)?;
}
Ok(())
}
async fn obtain_credential(&self, prelogin: &Prelogin, server: &str) -> anyhow::Result<Credential> {
if self.args.cookie_on_stdin {
return read_cookie_from_stdin();
}
let is_gateway = prelogin.is_gateway();
match prelogin {
Prelogin::Saml(prelogin) => {
let use_default_browser = prelogin.support_default_browser() && self.args.default_browser;
let browser = if prelogin.support_default_browser() {
self.args.browser.as_deref()
} else {
None
};
let cred = SamlAuthLauncher::new(&self.args.server)
.gateway(is_gateway)
.saml_request(prelogin.saml_request())
.user_agent(&self.args.user_agent)
.os(self.args.os.as_str())
.os_version(Some(&self.args.os_version()))
.hidpi(self.args.hidpi)
.fix_openssl(self.shared_args.fix_openssl)
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
.clean(self.args.clean)
.default_browser(use_default_browser)
.browser(browser)
.launch()
.await?;
Ok(cred)
}
Prelogin::Standard(prelogin) => {
let prefix = if is_gateway { "Gateway" } else { "Portal" };
println!("{} ({}: {})", prelogin.auth_message(), prefix, server);
let user = self.args.user.as_ref().map_or_else(
|| Text::new(&format!("{}:", prelogin.label_username())).prompt(),
|user| Ok(user.to_owned()),
)?;
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);
Ok(password_cred.into())
}
}
}
}
fn read_cookie_from_stdin() -> anyhow::Result<Credential> {
info!("Reading cookie from standard input");
let mut cookie = String::new();
std::io::stdin().read_line(&mut cookie)?;
let Ok(auth_result) = serde_json::from_str::<SamlAuthResult>(cookie.trim_end()) else {
bail!("Failed to parse auth data")
};
Credential::try_from(auth_result)
}
fn write_pid_file() {
let pid = std::process::id();
fs::write(GP_CLIENT_LOCK_FILE, pid.to_string()).unwrap();
info!("Wrote PID {} to {}", pid, GP_CLIENT_LOCK_FILE);
}
fn get_csd_uid(csd_user: &Option<String>) -> anyhow::Result<u32> {
if let Some(csd_user) = csd_user {
get_user_by_name(csd_user).map(|user| user.uid())
} else {
get_non_root_user().map_or_else(|_| Ok(0), |user| Ok(user.uid()))
}
}
-451
View File
@@ -1,451 +0,0 @@
use clap::Args;
use gpapi::{
clap::args::Os,
cookie_store,
gp_params::CscMode,
os_profile::{ClientOs, OsProfile},
};
use log::warn;
use std::{net::IpAddr, path::PathBuf};
#[derive(Args)]
pub(crate) struct ConnectArgs {
#[arg(help = "The portal server to connect to")]
pub(super) server: String,
#[arg(short, long, help = "The gateway to connect to, it will prompt if not specified")]
pub(super) gateway: Option<String>,
#[arg(
long,
conflicts_with = "gateway",
help = "Automatically try gateways in priority order until gateway auth/config succeeds, without prompting"
)]
pub(super) auto_gateway: bool,
#[arg(short, long, help = "The username to use, it will prompt if not specified")]
pub(super) user: Option<String>,
#[arg(long, help = "Read the password from standard input")]
pub(super) passwd_on_stdin: bool,
#[arg(long, help = "Read the gpauth authentication result from standard input")]
pub(super) cookie_on_stdin: bool,
#[arg(
long,
help = "Read and write the portal cookie cache, optionally specify the cache file path",
default_missing_value = "",
num_args=0..=1
)]
pub(super) cookie_cache: Option<String>,
#[arg(long, short, help = "The VPNC script to use", required_if_eq("script_tun", "true"))]
pub(super) script: Option<String>,
#[arg(long, short, help = "The IFNAME for tunnel interface")]
pub(super) interface: Option<String>,
#[arg(long, short = 'S', help = "Pass traffic to '--script' program, not tun")]
pub(super) script_tun: bool,
#[arg(long, help = "Connect the server as a gateway, instead of a portal")]
pub(super) as_gateway: bool,
#[arg(
long,
help = "Enable HIP (Host Information Profile), optionally specify a custom executable",
default_missing_value = "",
num_args=0..=1
)]
pub(super) hip: Option<String>,
#[arg(
long,
help = "Run a custom HIP executable as this user; otherwise inherit the process user"
)]
pub(super) hip_user: Option<String>,
#[arg(
short,
long,
help = "Use SSL client certificate file in pkcs#8 (.pem) or pkcs#12 (.p12, .pfx) format"
)]
pub(super) certificate: Option<String>,
#[arg(short = 'k', long, help = "Use SSL private key file in pkcs#8 (.pem) format")]
pub(super) sslkey: Option<String>,
#[arg(short = 'p', long, help = "The key passphrase of the private key")]
pub(super) key_password: Option<String>,
#[arg(long, hide = true)]
pub(super) csd_user: Option<String>,
#[arg(long, hide = true)]
pub(super) csd_wrapper: Option<String>,
#[arg(long, default_value = "300", help = "Reconnection retry timeout in seconds")]
pub(super) reconnect_timeout: u32,
#[arg(short, long, help = "Request MTU from server (legacy servers only)")]
pub(super) mtu: Option<u32>,
#[arg(long, help = "Do not ask for IPv6 connectivity")]
pub(super) disable_ipv6: bool,
#[arg(long = "user-agent", hide = true)]
pub(super) deprecated_user_agent: Option<String>,
#[arg(long = "os-version", hide = true)]
pub(super) deprecated_os_version: Option<String>,
#[arg(long, help = "Override the client version reported to the server, e.g., '6.2.4-49'")]
pub(super) client_version: Option<String>,
#[arg(long, value_enum, default_value_t = Os::default())]
pub(super) os: Os,
#[arg(long, value_enum, default_value_t = CscMode::Auto, help = "CSC support mode: auto, yes, or no")]
pub(super) csc: CscMode,
#[arg(long, help = "Disable DTLS and ESP")]
pub(super) no_dtls: bool,
#[arg(
long = "local-hostname",
help = "Same as the '--local-hostname' option in the openconnect command"
)]
pub(super) local_hostname: Option<String>,
#[arg(
long = "force-dpd",
help = "Same as the '--force-dpd' option in the openconnect command"
)]
pub(super) dpd_interval: Option<u32>,
#[arg(
long = "no-xmlpost",
help = "Same as the '--no-xmlpost' option in the openconnect command"
)]
pub(super) no_xmlpost: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "The HiDPI mode, useful for high-resolution screens")]
pub(super) hidpi: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "Do not reuse the remembered authentication cookie")]
pub(super) clean: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "Deprecated: Use the `--browser` option instead")]
pub(super) default_browser: bool,
#[arg(
long,
help = "Use external browser authentication. With no value, auto-select Chrome, Firefox, then system default. Use `default` for the system default browser or `remote` for headless servers.",
default_missing_value = "auto",
num_args=0..=1
)]
pub(super) browser: Option<String>,
#[arg(long, help = "Listen on this IP address when using '--browser remote'")]
pub(super) browser_listen: Option<IpAddr>,
#[arg(
long,
help = "Authenticate and print the gateway cookie to stdout, then exit without starting the \
VPN tunnel. Outputs two lines: COOKIE='<value>' and HOST='<gateway>'. Combine with \
--cookie-cache to avoid re-authenticating when the portal session is still valid."
)]
pub(super) cookie_only: bool,
}
pub(super) fn build_os_profile(args: &ConnectArgs) -> OsProfile {
build_os_profile_with_host_id(args, None)
}
pub(super) fn build_os_profile_with_host_id(args: &ConnectArgs, host_id: Option<&str>) -> OsProfile {
let mut builder = OsProfile::builder(ClientOs::from(args.os));
if let Some(client_version) = args.client_version.as_deref() {
builder = builder.client_version(client_version.to_string());
}
if let Some(local_hostname) = args.local_hostname.as_deref() {
builder = builder.computer_name_override(local_hostname.to_string());
}
if let Some(host_id) = host_id {
builder = builder.host_id_override(host_id);
}
builder.build()
}
pub(super) fn cookie_cache_path(args: &ConnectArgs) -> Option<PathBuf> {
args.cookie_cache.as_deref().map(|path| {
let custom = (!path.is_empty()).then_some(path);
cookie_store::cookie_path(custom)
})
}
pub(super) fn warn_deprecated_connect_args(args: &ConnectArgs) {
if args.csd_user.is_some() {
warn!("Deprecated option --csd-user will be removed; use --hip-user instead");
}
if args.csd_wrapper.is_some() {
warn!("Deprecated option --csd-wrapper will be removed; use --hip instead");
}
if args.deprecated_user_agent.is_some() {
warn!("Deprecated option --user-agent is ignored; user agent is derived from --os");
}
if args.deprecated_os_version.is_some() {
warn!("Deprecated option --os-version is ignored; OS version is derived from --os");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(clap::Parser)]
struct ConnectArgsTestCli {
#[command(flatten)]
args: ConnectArgs,
}
#[test]
fn parses_csc_mode_values() {
use clap::ValueEnum;
assert_eq!(CscMode::from_str("auto", false), Ok(CscMode::Auto));
assert_eq!(CscMode::from_str("yes", false), Ok(CscMode::Yes));
assert_eq!(CscMode::from_str("no", false), Ok(CscMode::No));
assert!(CscMode::from_str("maybe", false).is_err());
}
#[test]
fn auto_gateway_flag_parses() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--auto-gateway"])
.expect("--auto-gateway alone should parse");
assert!(cli.args.auto_gateway);
assert!(cli.args.gateway.is_none());
}
#[test]
fn auto_gateway_help_describes_auth_config_retry() {
use clap::CommandFactory;
let help = ConnectArgsTestCli::command().render_long_help().to_string();
assert!(help.contains("--auto-gateway"));
assert!(help.contains("Automatically try gateways in priority order until gateway auth/config succeeds"));
}
#[test]
fn gateway_flag_alone_parses() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--gateway", "gw1"])
.expect("--gateway alone should parse");
assert!(!cli.args.auto_gateway);
assert_eq!(cli.args.gateway.as_deref(), Some("gw1"));
}
#[test]
fn browser_without_value_uses_auto_mode() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--browser"])
.expect("--browser without value should parse");
assert_eq!(cli.args.browser.as_deref(), Some("auto"));
}
#[test]
fn browser_default_keeps_system_default_mode() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--browser", "default"])
.expect("--browser default should parse");
assert_eq!(cli.args.browser.as_deref(), Some("default"));
}
#[test]
fn browser_listen_accepts_ip_address() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from([
"test",
"portal.example.com",
"--browser",
"remote",
"--browser-listen",
"192.168.107.15",
])
.expect("connect args should parse");
assert_eq!(cli.args.browser_listen, Some("192.168.107.15".parse().unwrap()));
}
#[test]
fn os_defaults_to_runtime_os() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com"]).expect("connect args should parse");
assert_eq!(cli.args.os, Os::default());
}
#[test]
fn deprecated_profile_override_flags_still_parse() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from([
"test",
"portal.example.com",
"--user-agent",
"legacy-agent",
"--os-version",
"legacy-os",
"--client-version",
"legacy-client",
])
.expect("deprecated profile override flags should remain parse-compatible");
assert_eq!(cli.args.deprecated_user_agent.as_deref(), Some("legacy-agent"));
assert_eq!(cli.args.deprecated_os_version.as_deref(), Some("legacy-os"));
assert_eq!(cli.args.client_version.as_deref(), Some("legacy-client"));
}
#[test]
fn deprecated_profile_override_flags_do_not_affect_os_profile() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from([
"test",
"portal.example.com",
"--os",
"Linux",
"--user-agent",
"legacy-agent",
"--os-version",
"legacy-os",
"--client-version",
"legacy-client",
])
.expect("deprecated profile override flags should remain parse-compatible");
let profile = build_os_profile(&cli.args);
assert_ne!(profile.user_agent(), "legacy-agent");
assert_ne!(profile.os_version(), "legacy-os");
assert_eq!(profile.client_version(), "legacy-client");
assert!(profile.user_agent().contains("legacy-client"));
}
#[test]
fn stdin_host_id_sets_profile_runtime_identity_seed() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--os", "Linux"])
.expect("connect args should parse");
let profile = build_os_profile_with_host_id(&cli.args, Some("auth-host-id"));
assert_eq!(profile.host_identity().host_id(), "auth-host-id");
}
#[test]
fn cookie_cache_is_disabled_by_default() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com"]).expect("connect args should parse");
assert!(cli.args.cookie_cache.is_none());
assert!(cookie_cache_path(&cli.args).is_none());
}
#[test]
fn cookie_cache_accepts_default_path_without_value() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--cookie-cache"])
.expect("--cookie-cache without value should parse");
assert_eq!(cli.args.cookie_cache.as_deref(), Some(""));
assert!(cookie_cache_path(&cli.args).is_some());
}
#[test]
fn cookie_cache_accepts_custom_path() {
use clap::Parser;
let cli =
ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--cookie-cache", "/tmp/gp-cookie.json"])
.expect("--cookie-cache with value should parse");
assert_eq!(
cookie_cache_path(&cli.args).as_deref(),
Some(std::path::Path::new("/tmp/gp-cookie.json"))
);
}
#[test]
fn deprecated_hip_alias_flags_still_parse() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from([
"test",
"portal.example.com",
"--csd-user",
"legacy-user",
"--csd-wrapper",
"/tmp/legacy-hip.sh",
])
.expect("deprecated HIP alias flags should remain parse-compatible");
assert_eq!(cli.args.csd_user.as_deref(), Some("legacy-user"));
assert_eq!(cli.args.csd_wrapper.as_deref(), Some("/tmp/legacy-hip.sh"));
}
#[test]
fn auto_gateway_and_gateway_are_mutually_exclusive() {
use clap::Parser;
use clap::error::ErrorKind;
let result =
ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--gateway", "gw1", "--auto-gateway"]);
let err = match result {
Ok(_) => panic!("--gateway and --auto-gateway must conflict"),
Err(err) => err,
};
assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
}
#[test]
fn cookie_only_flag_parses() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com", "--cookie-only"])
.expect("--cookie-only should parse");
assert!(cli.args.cookie_only);
}
#[test]
fn cookie_only_is_disabled_by_default() {
use clap::Parser;
let cli = ConnectArgsTestCli::try_parse_from(["test", "portal.example.com"]).expect("connect args should parse");
assert!(!cli.args.cookie_only);
}
}
-337
View File
@@ -1,337 +0,0 @@
use anyhow::{Context, bail};
use gpapi::{
auth::SamlAuthResult,
clap::ToVerboseArg,
credential::{Credential, PasswordCredential},
portal::{Prelogin, StandardPrelogin},
process::auth_launcher::SamlAuthLauncher,
};
use inquire::{Password, PasswordDisplayMode, Text};
use log::info;
use super::ConnectHandler;
/// Replaces only the child launch boundary in workflow tests.
#[cfg(test)]
#[derive(Default)]
pub(super) struct AuthAttemptFixture {
pub(super) outcomes: std::collections::VecDeque<anyhow::Result<Credential>>,
pub(super) observed: Vec<(String, bool, bool)>,
}
#[derive(Default)]
pub(super) struct CleanAuthState {
requested: bool,
}
impl CleanAuthState {
pub(super) fn new(requested: bool) -> Self {
Self { requested }
}
fn consume_for_webview(&mut self, webview_auth: bool) -> bool {
if !webview_auth || !self.requested {
return false;
}
self.requested = false;
true
}
}
impl ConnectHandler<'_> {
pub(super) fn prepare_cookie_from_stdin(&self) -> anyhow::Result<()> {
if !self.args.cookie_on_stdin || self.cookie_from_stdin.borrow().is_some() {
return Ok(());
}
let auth_result = self.read_auth_result_from_stdin()?;
log_stdin_host_id(auth_result.host_id());
self.apply_stdin_host_id(auth_result.host_id());
Ok(())
}
pub(super) async fn obtain_credential_with_recovery(
&self,
mut response: Prelogin,
server: &str,
browser_allowed: bool,
) -> anyhow::Result<(Prelogin, Credential)> {
loop {
self.check_cancelled()?;
let result = self.obtain_credential(&response, server, browser_allowed).await;
self.check_cancelled()?;
match result {
Ok(credential) => return Ok((response, credential)),
Err(error) => {
if !self.auth_recovery.borrow_mut().recover(&error) {
return Err(self.auth_recovery.borrow().terminal(error));
}
log::warn!("Authenticator exited with a Wayland rendering error; retrying with DMABUF disabled");
let refreshed = self
.refresh_auth_prelogin(server, response.is_gateway(), browser_allowed)
.await;
response = refreshed.map_err(|error| self.auth_recovery.borrow().terminal(error))?;
}
}
}
}
pub(super) async fn refresh_auth_prelogin(
&self,
server: &str,
is_gateway: bool,
browser_allowed: bool,
) -> anyhow::Result<Prelogin> {
let mut params = self.build_gp_params();
params.set_is_gateway(is_gateway);
tokio::select! {
biased;
_ = self.cancellation.cancelled() => Err(gpapi::auth::AuthenticationCancelled.into()),
result = gpapi::portal::prelogin(server, &params, self.prelogin_options(browser_allowed)) => result,
}
}
pub(super) async fn obtain_credential(
&self,
prelogin: &Prelogin,
server: &str,
gateway_browser_auth_allowed: bool,
) -> anyhow::Result<Credential> {
if should_read_stdin_credential(self.args.cookie_on_stdin, self.args.as_gateway, prelogin.is_gateway()) {
return self.read_cookie_from_stdin();
}
let is_gateway = prelogin.is_gateway();
match prelogin {
Prelogin::Saml(prelogin) => {
let external_browser_supported = can_use_external_browser_auth(
prelogin.support_default_browser(),
is_gateway,
gateway_browser_auth_allowed,
);
let browser = if external_browser_supported {
self.args.browser.as_deref()
} else if !cfg!(feature = "webview-auth") {
bail!(
"The server does not support authentication via the default browser and the gpclient is not built with the `webview-auth` feature"
);
} else {
None
};
let verbose = self.shared_args.verbose.to_verbose_arg();
let os_profile = self.os_profile.borrow().clone();
let key_password = self.latest_key_password.borrow().clone();
let auth_launcher = SamlAuthLauncher::new(server)
.dmabuf_disabled(self.auth_recovery.borrow().dmabuf_disabled())
.gateway(is_gateway)
.saml_request(prelogin.saml_request())
.os_profile(&os_profile)
.fix_openssl(self.shared_args.fix_openssl)
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
.certificate(self.args.certificate.as_deref())
.sslkey(self.args.sslkey.as_deref())
.key_password(key_password.as_deref())
.browser(browser)
.browser_listen(self.args.browser_listen)
.log_format(self.shared_args.log_format)
.verbose(verbose);
#[cfg(feature = "webview-auth")]
let use_default_browser = external_browser_supported && self.args.default_browser;
#[cfg(feature = "webview-auth")]
let browser_kind = if browser.is_some() || use_default_browser {
"external"
} else {
"embedded"
};
#[cfg(not(feature = "webview-auth"))]
let browser_kind = "external";
let clean_auth = self
.clean_auth_state
.borrow_mut()
.consume_for_webview(browser_kind == "embedded");
info!(
"SAML auth launch: gateway={}, clean={}, browser={}",
is_gateway, clean_auth, browser_kind
);
#[cfg(feature = "webview-auth")]
let auth_launcher = auth_launcher
.hidpi(self.args.hidpi)
.clean(clean_auth)
.default_browser(use_default_browser);
#[cfg(test)]
{
let mut fixture = self.auth_attempt_fixture.borrow_mut();
if let Some(outcome) = fixture.outcomes.pop_front() {
fixture.observed.push((
prelogin.saml_request().to_owned(),
self.auth_recovery.borrow().dmabuf_disabled(),
clean_auth,
));
return outcome;
}
}
let cred = auth_launcher.cancellation(&self.cancellation).launch().await?;
self.check_cancelled()?;
Ok(cred)
}
Prelogin::Standard(prelogin) => {
let prefix = if is_gateway { "Gateway" } else { "Portal" };
println!("{} ({}: {})", prelogin.auth_message(), prefix, server);
let user = self.args.user.as_ref().map_or_else(
|| Text::new(&format!("{}:", prelogin.label_username())).prompt(),
|user| Ok(user.to_owned()),
)?;
let password = self.obtain_password(prelogin)?;
let password_cred = PasswordCredential::new(&user, &password);
Ok(password_cred.into())
}
}
}
fn read_cookie_from_stdin(&self) -> anyhow::Result<Credential> {
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)?);
}
let auth_result = self.read_auth_result_from_stdin()?;
log_stdin_host_id(auth_result.host_id());
self.apply_stdin_host_id(auth_result.host_id());
Credential::try_from(auth_result)
}
fn read_auth_result_from_stdin(&self) -> anyhow::Result<SamlAuthResult> {
info!("Reading cookie from standard input");
let mut cookie = String::new();
std::io::stdin().read_line(&mut cookie)?;
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")?;
Ok(auth_result)
}
fn obtain_password(&self, prelogin: &StandardPrelogin) -> anyhow::Result<String> {
let password = if self.args.passwd_on_stdin {
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();
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 should_read_stdin_credential(cookie_on_stdin: bool, as_gateway: bool, prelogin_is_gateway: bool) -> bool {
cookie_on_stdin && (!prelogin_is_gateway || as_gateway)
}
fn can_use_external_browser_auth(
saml_support_default_browser: bool,
is_gateway: bool,
gateway_browser_auth_allowed: bool,
) -> bool {
saml_support_default_browser && (!is_gateway || gateway_browser_auth_allowed)
}
fn log_stdin_host_id(host_id: Option<&str>) {
match host_id {
Some(host_id) => info!("stdin auth result host-id: {}", host_id),
None => info!("stdin auth result host-id: <none>"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clean_auth_state_is_consumed_once_for_webview() {
let mut state = CleanAuthState::new(true);
assert!(state.consume_for_webview(true));
assert!(!state.consume_for_webview(true));
}
#[test]
fn clean_auth_state_is_not_consumed_by_external_browser() {
let mut state = CleanAuthState::new(true);
assert!(!state.consume_for_webview(false));
assert!(state.consume_for_webview(true));
}
#[test]
fn clean_auth_state_remains_false_when_not_requested() {
let mut state = CleanAuthState::new(false);
assert!(!state.consume_for_webview(true));
assert!(!state.consume_for_webview(false));
}
#[test]
fn stdin_credential_is_allowed_for_portal_auth() {
assert!(should_read_stdin_credential(true, false, false));
}
#[test]
fn stdin_credential_is_allowed_for_direct_gateway_auth() {
assert!(should_read_stdin_credential(true, true, true));
}
#[test]
fn stdin_credential_is_not_reused_for_gateway_fallback_auth() {
assert!(!should_read_stdin_credential(true, false, true));
}
#[test]
fn stdin_credential_is_not_used_when_flag_is_disabled() {
assert!(!should_read_stdin_credential(false, false, false));
assert!(!should_read_stdin_credential(false, true, true));
}
#[test]
fn portal_saml_can_use_default_browser_when_supported() {
assert!(can_use_external_browser_auth(true, false, false));
}
#[test]
fn gateway_saml_requires_gateway_browser_auth_allowance() {
assert!(!can_use_external_browser_auth(true, true, false));
assert!(can_use_external_browser_auth(true, true, true));
}
#[test]
fn default_browser_auth_requires_saml_support() {
assert!(!can_use_external_browser_auth(false, false, true));
assert!(!can_use_external_browser_auth(false, true, true));
}
}
-520
View File
@@ -1,520 +0,0 @@
use std::time::Duration;
use clap::Parser;
use gpapi::{
cookie_store::{self, StoredCookie},
credential::AuthCookieCredential,
gateway::{Gateway, GatewayLoginContext, GatewaySelection},
log_format::LogFormat,
session::SessionMode,
};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use super::{ConnectArgs, ConnectHandler};
use crate::cli::SharedArgs;
#[derive(Parser)]
struct TestArgs {
#[command(flatten)]
connect: ConnectArgs,
}
fn login_response() -> String {
let mut fields = [""; 20];
fields[1] = "issued-cookie";
fields[3] = "gateway";
fields[4] = "alice";
fields[5] = "fixture-auth";
fields[6] = "vsys1";
fields[12] = "tunnel";
format!(
"<jnlp><application-desc>{}</application-desc></jnlp>",
fields
.iter()
.map(|field| format!("<argument>{field}</argument>"))
.collect::<String>()
)
}
async fn gateway(responses: Vec<(&'static str, String)>) -> (String, tokio::task::JoinHandle<Vec<String>>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
let worker = tokio::spawn(async move {
tokio::time::timeout(Duration::from_secs(5), async move {
let mut requests = Vec::new();
for (status, body) in responses {
let (mut stream, _) = listener.accept().await.unwrap();
let mut request = Vec::new();
loop {
let mut buf = [0; 4096];
let count = stream.read(&mut buf).await.unwrap();
assert_ne!(count, 0, "Request ended before its body");
request.extend_from_slice(&buf[..count]);
if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") {
let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
let length = headers
.lines()
.find_map(|line| line.strip_prefix("content-length:"))
.map(|value| value.trim().parse::<usize>().unwrap())
.unwrap_or(0);
if request.len() >= end + 4 + length {
break;
}
}
}
requests.push(String::from_utf8(request).unwrap());
stream
.write_all(
format!(
"HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
.as_bytes(),
)
.await
.unwrap();
}
requests
})
.await
.expect("Gateway fixture timed out")
});
(origin, worker)
}
#[tokio::test]
async fn cached_tunnel_authentication_does_not_require_portal_discovery() {
let (gateway, worker) = gateway(vec![("200 OK", login_response())]).await;
let directory = tempfile::tempdir().unwrap();
let cache = directory.path().join("cookie.json");
let args = TestArgs::parse_from([
"test",
"http://unavailable-portal.invalid",
"--cookie-only",
"--cookie-cache",
cache.to_str().unwrap(),
])
.connect;
let lock = directory.path().join("client.pid");
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
let shared = SharedArgs {
fix_openssl: false,
ignore_tls_errors: true,
lock_file: &lock,
verbose: &verbose,
log_format: LogFormat::Text,
};
let handler = ConnectHandler::new(&args, &shared);
cookie_store::save(
&cache,
&StoredCookie::new(
args.server.clone(),
"alice".into(),
handler.os_profile.borrow().host_identity().host_id().into(),
gateway,
AuthCookieCredential::new("alice", "portal-cookie", ""),
),
)
.unwrap();
handler.handle_impl().await.unwrap();
let requests = worker.await.unwrap();
assert_eq!(requests.len(), 1);
assert!(requests[0].starts_with("POST /ssl-vpn/login.esp "));
assert!(requests[0].contains("portal-cookie"));
assert_eq!(
handler.sessions.borrow().members()[0].transport.authentication().mode(),
SessionMode::Tunnel
);
}
#[tokio::test]
async fn internal_tunnel_keeps_gateway_authentication_after_portal_cookie_rejection() {
let (origin, worker) = gateway(vec![
(
"200 OK",
"<prelogin-response><status>Success</status></prelogin-response>".into(),
),
("403 Forbidden", "<response><error>rejected</error></response>".into()),
("200 OK", login_response()),
])
.await;
let args = TestArgs::parse_from(["test", &origin, "--user", "alice", "--passwd-on-stdin"]).connect;
let directory = tempfile::tempdir().unwrap();
let lock = directory.path().join("client.pid");
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
let shared = SharedArgs {
fix_openssl: false,
ignore_tls_errors: true,
lock_file: &lock,
verbose: &verbose,
log_format: LogFormat::Text,
};
let handler = ConnectHandler::new(&args, &shared);
handler.password_from_stdin.replace(Some("gateway-password".into()));
let mut value = serde_json::to_value(Gateway::new("internal".into(), origin.clone())).unwrap();
value["kind"] = serde_json::json!("internal");
let gateway: Gateway = serde_json::from_value(value).unwrap();
let session = handler
.authenticate_gateway(
&origin,
&origin,
&AuthCookieCredential::new("alice", "rejected-cookie", ""),
false,
GatewayLoginContext::new(&gateway, GatewaySelection::Auto),
)
.await
.unwrap();
assert_eq!(session.authentication.mode(), SessionMode::Tunnel);
assert!(session.extension_auth.binding().is_none());
let requests = worker.await.unwrap();
assert_eq!(requests.len(), 3);
assert!(requests[1].contains("rejected-cookie"));
assert!(requests[2].contains("gateway-password"));
}
#[tokio::test]
async fn rendering_recovery_fetches_new_prelogin_metadata_and_preserves_gateway_mode() {
let (origin, worker) = gateway(vec![
(
"200 OK",
"<prelogin-response><status>Success</status><region>old</region></prelogin-response>".into(),
),
(
"200 OK",
"<prelogin-response><status>Success</status><region>replacement</region></prelogin-response>".into(),
),
])
.await;
let args = TestArgs::parse_from(["test", &origin]).connect;
let directory = tempfile::tempdir().unwrap();
let lock = directory.path().join("client.pid");
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
let shared = SharedArgs {
fix_openssl: false,
ignore_tls_errors: true,
lock_file: &lock,
verbose: &verbose,
log_format: LogFormat::Text,
};
let handler = ConnectHandler::new(&args, &shared);
let original = handler.refresh_auth_prelogin(&origin, true, true).await.unwrap();
let replacement = handler
.refresh_auth_prelogin(&origin, original.is_gateway(), true)
.await
.unwrap();
assert_eq!(original.region(), "old");
assert_eq!(replacement.region(), "replacement");
assert!(replacement.is_gateway());
let requests = worker.await.unwrap();
assert_eq!(requests.len(), 2);
assert!(
requests
.iter()
.all(|request| request.starts_with("POST /ssl-vpn/prelogin.esp"))
);
}
#[cfg(feature = "webview-auth")]
#[tokio::test]
async fn cancellation_during_recovery_prelogin_stops_request() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
let args = TestArgs::parse_from(["test", &origin]).connect;
let directory = tempfile::tempdir().unwrap();
let lock = directory.path().join("client.pid");
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
let shared = SharedArgs {
fix_openssl: false,
ignore_tls_errors: true,
lock_file: &lock,
verbose: &verbose,
log_format: LogFormat::Text,
};
let handler = ConnectHandler::new(&args, &shared);
handler
.auth_attempt_fixture
.borrow_mut()
.outcomes
.push_back(Err(rendering_crash()));
let (result, ()) = tokio::time::timeout(Duration::from_secs(3), async {
tokio::join!(
async {
let original = handler.refresh_auth_prelogin(&origin, false, false).await?;
handler.obtain_credential_with_recovery(original, &origin, false).await
},
async {
let (mut socket, _) = listener.accept().await.unwrap();
let mut byte = [0];
socket.read_exact(&mut byte).await.unwrap();
handler.cancellation.cancel();
}
)
})
.await
.unwrap();
assert!(
result
.unwrap_err()
.downcast_ref::<gpapi::auth::AuthenticationCancelled>()
.is_some()
);
}
#[cfg(feature = "webview-auth")]
fn rendering_crash() -> anyhow::Error {
use std::os::unix::process::ExitStatusExt;
gpapi::process::rendering_recovery::RenderingCrash {
status: std::process::ExitStatus::from_raw(71 << 8),
}
.into()
}
#[cfg(feature = "webview-auth")]
fn saml_prelogin_response(region: &str, encoded_request: &str) -> String {
format!(
"<prelogin-response><status>Success</status><region>{region}</region><saml-auth-method>POST</saml-auth-method><saml-request>{encoded_request}</saml-request></prelogin-response>"
)
}
#[cfg(feature = "webview-auth")]
#[tokio::test]
async fn auth_crash_uses_fresh_saml_and_clean_once_with_shared_budget() {
use gpapi::credential::{Credential, PreloginCredential};
let (origin, worker) = gateway(vec![
("200 OK", saml_prelogin_response("old-region", "b2xk")),
("200 OK", saml_prelogin_response("new-region", "bmV3")),
("200 OK", saml_prelogin_response("gateway-region", "Z2F0ZXdheQ==")),
])
.await;
let args = TestArgs::parse_from(["test", &origin, "--clean"]).connect;
let directory = tempfile::tempdir().unwrap();
let lock = directory.path().join("client.pid");
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
let shared = SharedArgs {
fix_openssl: false,
ignore_tls_errors: true,
lock_file: &lock,
verbose: &verbose,
log_format: LogFormat::Text,
};
let handler = ConnectHandler::new(&args, &shared);
handler.auth_attempt_fixture.borrow_mut().outcomes.extend([
Err(rendering_crash()),
Ok(Credential::Prelogin(PreloginCredential::new(
"alice",
Some("new-cookie"),
None,
None,
))),
Err(rendering_crash()),
]);
let original = handler.refresh_auth_prelogin(&origin, false, false).await.unwrap();
let (replacement, credential) = handler
.obtain_credential_with_recovery(original, &origin, false)
.await
.unwrap();
assert_eq!(replacement.region(), "new-region");
assert_eq!(credential.username(), "alice");
assert!(matches!(credential, Credential::Prelogin(ref value) if value.prelogin_cookie() == Some("new-cookie")));
let gateway_prelogin = handler.refresh_auth_prelogin(&origin, true, false).await.unwrap();
let error = handler
.obtain_credential_with_recovery(gateway_prelogin, &origin, false)
.await
.unwrap_err();
assert!(
error
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
.is_some()
);
assert_eq!(
handler.auth_attempt_fixture.borrow().observed,
[
("old".into(), false, true),
("new".into(), true, false),
("gateway".into(), true, false),
]
);
assert_eq!(worker.await.unwrap().len(), 3);
}
#[cfg(feature = "webview-auth")]
#[tokio::test]
async fn exhausted_auth_recovery_is_terminal_before_portal_gateway_fallback() {
let (origin, worker) = gateway(vec![
("200 OK", saml_prelogin_response("old-region", "b2xk")),
("200 OK", saml_prelogin_response("new-region", "bmV3")),
])
.await;
let args = TestArgs::parse_from(["test", &origin, "--clean"]).connect;
let directory = tempfile::tempdir().unwrap();
let lock = directory.path().join("client.pid");
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
let shared = SharedArgs {
fix_openssl: false,
ignore_tls_errors: true,
lock_file: &lock,
verbose: &verbose,
log_format: LogFormat::Text,
};
let handler = ConnectHandler::new(&args, &shared);
handler.auth_attempt_fixture.borrow_mut().outcomes.extend([
Err(rendering_crash()),
Err(anyhow::anyhow!(gpapi::error::PortalError::PreloginError(
"second failure".into()
))),
]);
let error = handler.handle_impl().await.unwrap_err();
assert!(
error
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
.is_some()
);
assert_eq!(handler.auth_attempt_fixture.borrow().observed.len(), 2);
assert_eq!(worker.await.unwrap().len(), 2);
}
#[cfg(all(
feature = "webview-auth",
any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")
))]
mod gtk_retry {
use super::*;
#[tokio::test]
async fn real_gtk_crash_retries_bundled_authenticator() {
// Environment overrides belong to a separate test process, never the parallel test runner.
if let Some(directory) = std::env::var_os("GP_TEST_GTK_AUTH_DIR") {
verify_real_authenticator_retry(std::path::Path::new(&directory)).await;
} else {
run_real_authenticator_retry(false);
}
}
#[cfg(target_os = "linux")]
#[test]
#[ignore = "requires non-interactive sudo authorization and a running Wayland desktop session"]
fn sudo_gtk_crash_retries_after_restoring_desktop_environment() {
run_real_authenticator_retry(true);
}
fn run_real_authenticator_retry(sudo: bool) {
use std::{fs, os::unix::fs::PermissionsExt, process::Command};
let directory = tempfile::tempdir().unwrap();
let executable = directory.path().join("gpauth");
// Fixtures contain only dummy data and must remain accessible after a root test drops privileges.
fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o755)).unwrap();
let attempts_path = directory.path().join("attempts");
fs::write(&attempts_path, "").unwrap();
fs::set_permissions(&attempts_path, fs::Permissions::from_mode(0o666)).unwrap();
fs::write(&executable, r#"#!/bin/sh
set -eu
request=
while [ "$#" -gt 0 ]; do
if [ "$1" = '--saml-request' ]; then
shift
request=$1
fi
shift
done
printf '%s|%s|%s|%s\n' "$(id -u)" "${WAYLAND_DISPLAY:-}" "${WEBKIT_DISABLE_DMABUF_RENDERER-unset}" "$request" >> "$GP_TEST_GTK_AUTH_DIR/attempts"
if [ "$request" = 'old' ]; then
printf 'Gdk-Message: 10:49:22.617: Error 71 (Protocol error) dispatching to Wayland display.\n' >&2
exit 1
fi
[ "$request" = 'new' ] && [ "${WEBKIT_DISABLE_DMABUF_RENDERER:-}" = '1' ] || exit 2
printf '%s\n' '{"success":{"username":"alice","preloginCookie":"new-cookie"}}'
"#).unwrap();
fs::set_permissions(&executable, fs::Permissions::from_mode(0o755)).unwrap();
let mut command = if sudo {
assert_ne!(
uzers::get_effective_uid(),
0,
"run this test as the Wayland desktop user"
);
let mut command = Command::new("sudo");
command.args([
"-n",
"env",
"-u",
"WAYLAND_DISPLAY",
"-u",
"DISPLAY",
"-u",
"XDG_SESSION_TYPE",
"-u",
"WEBKIT_DISABLE_DMABUF_RENDERER",
]);
command.arg("GP_TEST_EXPECT_ROOT=1");
command
} else {
let mut command = Command::new("env");
command.arg("-u").arg("WEBKIT_DISABLE_DMABUF_RENDERER");
command.arg("WAYLAND_DISPLAY=wayland-test");
command
};
command.arg(format!("GP_AUTH_BINARY={}", executable.display()));
command.arg(format!("GP_TEST_GTK_AUTH_DIR={}", directory.path().display()));
command.arg(std::env::current_exe().unwrap()).args([
"--exact",
"connect::flow_tests::gtk_retry::real_gtk_crash_retries_bundled_authenticator",
"--nocapture",
]);
let output = command.output().unwrap();
assert!(
output.status.success(),
"retry subprocess failed: {}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
let expected_uid = gpapi::process::users::get_non_root_user().unwrap().uid().to_string();
let attempts = fs::read_to_string(attempts_path).unwrap();
let attempts: Vec<Vec<&str>> = attempts.lines().map(|line| line.split('|').collect()).collect();
assert_eq!(attempts.len(), 2, "expected exactly one retry");
for attempt in &attempts {
assert_eq!(attempt[0], expected_uid, "authenticator must run as the desktop user");
assert!(!attempt[1].is_empty(), "authenticator must receive WAYLAND_DISPLAY");
}
assert_eq!(&attempts[0][2..], ["unset", "old"]);
assert_eq!(&attempts[1][2..], ["1", "new"]);
}
async fn verify_real_authenticator_retry(directory: &std::path::Path) {
use gpapi::credential::Credential;
if std::env::var_os("GP_TEST_EXPECT_ROOT").is_some() {
assert_eq!(uzers::get_effective_uid(), 0);
assert!(std::env::var_os("SUDO_UID").is_some());
assert!(std::env::var_os("WAYLAND_DISPLAY").is_none());
}
let (origin, worker) = gateway(vec![
("200 OK", saml_prelogin_response("old-region", "b2xk")),
("200 OK", saml_prelogin_response("new-region", "bmV3")),
])
.await;
let args = TestArgs::parse_from(["test", &origin]).connect;
let lock = directory.join("client.pid");
let verbose = gpapi::clap::InfoLevelVerbosity::new(0, 0);
let shared = SharedArgs {
fix_openssl: false,
ignore_tls_errors: true,
lock_file: &lock,
verbose: &verbose,
log_format: LogFormat::Text,
};
let handler = ConnectHandler::new(&args, &shared);
let original = handler.refresh_auth_prelogin(&origin, false, false).await.unwrap();
let (replacement, credential) = handler
.obtain_credential_with_recovery(original, &origin, false)
.await
.unwrap();
assert_eq!(replacement.region(), "new-region");
assert!(matches!(credential, Credential::Prelogin(ref value) if value.prelogin_cookie() == Some("new-cookie")));
assert_eq!(
worker.await.unwrap().len(),
2,
"recovery must fetch fresh prelogin data"
);
}
}
-701
View File
@@ -1,701 +0,0 @@
use std::{
fs,
path::Path,
sync::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
},
};
use gpapi::{
clap::report,
cookie_store,
credential::{AuthCookieCredential, Credential},
gateway::{Gateway, GatewayLogin, GatewayLoginClient, GatewayLoginContext, GatewaySelection, SessionExtensionAuth},
gp_params::GpParams,
os_profile::OsProfile,
portal::{PortalConfig, prelogin},
process::users::get_user_by_name,
session::{GatewayAuthentication, SessionMode},
};
use inquire::Text;
use log::{Level, info, warn};
use openconnect::{HipScript, HipSource, Vpn, VpnBuilder};
use tokio::{runtime::Handle, task::JoinHandle};
use crate::session::{
SessionContextInput, build_session_context, session_info_from_vpn, spawn_session_runtime_with_info,
};
use super::{ConnectHandler, args::cookie_cache_path};
const OPENCONNECT_INTERRUPTED_EXIT_CODE: i32 = -4;
pub(super) struct GatewayLoginSession {
pub(super) authentication: GatewayAuthentication,
pub(super) extension_auth: SessionExtensionAuth,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum GatewayConnectFailureStage {
BeforeEstablishment,
AfterEstablishment,
}
#[derive(Debug)]
pub(super) struct GatewayConnectError {
stage: GatewayConnectFailureStage,
error: anyhow::Error,
}
impl GatewayConnectError {
fn before_establishment(error: anyhow::Error) -> Self {
Self {
stage: GatewayConnectFailureStage::BeforeEstablishment,
error,
}
}
fn after_establishment(error: anyhow::Error) -> Self {
Self {
stage: GatewayConnectFailureStage::AfterEstablishment,
error,
}
}
pub(super) fn is_before_establishment(&self) -> bool {
self.stage == GatewayConnectFailureStage::BeforeEstablishment
}
pub(super) fn as_error(&self) -> &anyhow::Error {
&self.error
}
pub(super) fn into_error(self) -> anyhow::Error {
self.error
}
}
impl ConnectHandler<'_> {
pub(super) async fn try_cached_cookie(&self, server: &str) -> Option<anyhow::Result<()>> {
let path = cookie_cache_path(self.args)?;
let host_id = self.os_profile.borrow().host_identity().host_id().to_string();
let stored = cookie_store::load(&path, server, &host_id)?;
if !stored.auth_cookie.can_authenticate_gateway() {
cookie_store::clear(&path);
return None;
}
let credential = (&stored.auth_cookie).into();
let mut params = self.build_gp_params();
params.set_is_gateway(true);
let session = match self
.login_gateway(&stored.last_gateway, &credential, &params, None)
.await
{
Ok(session) => session,
Err(error) => {
if self.cancellation.is_cancelled()
|| error
.downcast_ref::<gpapi::gateway::GatewayLoginProtocolError>()
.is_some()
{
return Some(Err(error));
}
cookie_store::clear(&path);
warn!("Cached gateway authentication failed: {error}");
return None;
}
};
if session.authentication.mode() == SessionMode::NonTunnel && !self.args.cookie_only {
self.logout_gateway(&stored.last_gateway).await;
info!("Cached non-tunnel login requires fresh portal discovery");
return None;
}
let result = self
.connect_gateway(
server,
&stored.last_gateway,
&session.authentication,
false,
session.extension_auth,
)
.await;
match result {
Ok(()) => Some(Ok(())),
Err(error) if self.cancellation.is_cancelled() => Some(Err(error.into_error())),
Err(error) => {
self.logout_gateway(&stored.last_gateway).await;
warn!("Cached gateway connection failed: {}", error.as_error());
None
}
}
}
pub(super) fn cached_portal_credential(&self, server: &str) -> Option<Credential> {
if self.args.cookie_on_stdin {
return None;
}
let path = cookie_cache_path(self.args)?;
let host_id = self.os_profile.borrow().host_identity().host_id().to_string();
let stored = cookie_store::load(&path, server, &host_id)?;
if !stored.auth_cookie.can_authenticate_gateway() {
cookie_store::clear(&path);
return None;
}
info!("Using cached credential for fresh portal discovery");
Some((&stored.auth_cookie).into())
}
pub(super) fn clear_cookie_cache(&self) {
if let Some(path) = cookie_cache_path(self.args) {
cookie_store::clear(&path);
}
}
pub(super) async fn connect_gateway_with_prelogin(
&self,
portal: &str,
gateway: &str,
allow_extend_session: bool,
gateway_context: Option<GatewayLoginContext>,
) -> anyhow::Result<()> {
info!("Performing the gateway authentication...");
let mut gp_params = self.build_gp_params();
gp_params.set_is_gateway(true);
let gateway_browser_auth_allowed = true;
let prelogin = tokio::select! {
biased;
_ = self.cancellation.cancelled() => return Err(gpapi::auth::AuthenticationCancelled.into()),
result = prelogin(gateway, &gp_params, self.direct_gateway_prelogin_options()) => result?,
};
let (_, cred) = self
.obtain_credential_with_recovery(prelogin, gateway, gateway_browser_auth_allowed)
.await?;
let login_session = self
.login_gateway(gateway, &cred, &gp_params, gateway_context.as_ref())
.await?;
self
.connect_gateway(
portal,
gateway,
&login_session.authentication,
allow_extend_session,
login_session.extension_auth,
)
.await
.map_err(GatewayConnectError::into_error)
}
pub(super) async fn connect_gateway_with_fallback(
&self,
portal: &str,
gateway: &Gateway,
portal_cred: &AuthCookieCredential,
config: &PortalConfig,
selection: GatewaySelection,
remaining: &[&Gateway],
) -> Result<(), GatewayConnectError> {
let session = self
.authenticate_gateway(
portal,
gateway.server(),
portal_cred,
config.default_browser().unwrap_or(false),
GatewayLoginContext::new(gateway, selection).with_connect_method(config.connect_method()),
)
.await
.map_err(GatewayConnectError::before_establishment)?;
if !self.args.cookie_only && session.authentication.mode() == SessionMode::NonTunnel {
if gateway.kind() != gpapi::gateway::GatewayKind::Internal {
return Err(GatewayConnectError::after_establishment(anyhow::anyhow!(
"Non-tunnel authentication requires freshly discovered internal gateways"
)));
}
return self
.connect_internal_gateways(portal, config, portal_cred, gateway, session, remaining)
.await
.map_err(GatewayConnectError::after_establishment);
}
self
.connect_gateway(
portal,
gateway.server(),
&session.authentication,
config.allow_extend_session().unwrap_or(false),
session.extension_auth,
)
.await
}
pub(super) async fn authenticate_gateway(
&self,
portal: &str,
gateway: &str,
portal_cred: &AuthCookieCredential,
portal_config_default_browser: bool,
gateway_context: GatewayLoginContext,
) -> anyhow::Result<GatewayLoginSession> {
self.check_cancelled()?;
let mut gp_params = self.build_gp_params();
gp_params.set_is_gateway(true);
let browser_allowed = self.gateway_browser_auth_allowed(portal_config_default_browser);
let gateway_prelogin = tokio::select! {
biased;
_ = self.cancellation.cancelled() => return Err(gpapi::auth::AuthenticationCancelled.into()),
result = prelogin(gateway, &gp_params, self.prelogin_options(browser_allowed)) => result?,
};
self.check_cancelled()?;
if portal_cred.can_authenticate_gateway() {
let credential: Credential = portal_cred.into();
match self
.login_gateway(gateway, &credential, &gp_params, Some(&gateway_context))
.await
{
Ok(session) => {
self.save_cookie_cache(portal, gateway, portal_cred);
return Ok(session);
}
Err(error) => {
self.check_cancelled()?;
let error = self.auth_recovery.borrow().terminal(error);
if error
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
.is_some()
{
return Err(error);
}
if error
.downcast_ref::<gpapi::gateway::GatewayLoginProtocolError>()
.is_some()
{
return Err(error);
}
info!("Portal cookie login failed; using gateway prelogin authentication: {error}");
}
}
}
let (_, credential) = self
.obtain_credential_with_recovery(gateway_prelogin, gateway, browser_allowed)
.await
.inspect_err(|_| self.print_direct_gateway_recommendation(gateway))?;
self.check_cancelled()?;
let result = self
.login_gateway(gateway, &credential, &gp_params, Some(&gateway_context))
.await;
if result.is_err() {
self.print_direct_gateway_recommendation(gateway);
}
result
}
fn save_cookie_cache(&self, portal: &str, gateway: &str, auth_cookie: &AuthCookieCredential) {
let Some(path) = cookie_cache_path(self.args) else {
return;
};
if !auth_cookie.can_authenticate_gateway() {
return;
}
let stored = cookie_store::StoredCookie::new(
portal.to_string(),
auth_cookie.username().to_string(),
self.os_profile.borrow().host_identity().host_id().to_string(),
gateway.to_string(),
auth_cookie.clone(),
);
match cookie_store::save(&path, &stored) {
Ok(()) => info!("Saved portal cookie cache to {}", path.display()),
Err(err) => warn!("Failed to save portal cookie cache to {}: {}", path.display(), err),
}
}
fn print_direct_gateway_recommendation(&self, gateway: &str) {
if !self.args.cookie_on_stdin {
return;
}
let format = self.shared_args.log_format;
report(
format,
Level::Warn,
"\nNOTE: Gateway authentication failed after portal login.",
);
report(
format,
Level::Warn,
"NOTE: If this server also accepts direct gateway login, try:",
);
report(
format,
Level::Warn,
&format!("NOTE: {}", direct_gateway_command(gateway)),
);
}
async fn login_gateway(
&self,
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
gateway_context: Option<&GatewayLoginContext>,
) -> anyhow::Result<GatewayLoginSession> {
let mut gp_params = gp_params.clone();
gp_params.prepare_client_identity()?;
let cancellation = self.cancellation.clone();
let internal = gateway_context.is_some_and(|context| context.kind() == gpapi::gateway::GatewayKind::Internal);
let mut client = GatewayLoginClient::new(gateway, gp_params)?;
loop {
self.check_cancelled()?;
let login = client.login(cred, gateway_context, &cancellation).await?;
match login {
GatewayLogin::Authenticated(authentication) => {
let descriptor = Gateway::new(gateway.to_string(), gateway.to_string());
client.register_session(
descriptor.clone(),
authentication.clone(),
&mut self.sessions.borrow_mut(),
);
self.check_cancelled()?;
if internal && authentication.mode() == SessionMode::NonTunnel && !self.args.cookie_only {
client
.bind_non_tunnel(self.args.disable_ipv6, None, &cancellation)
.await
.map_err(|error| error.context(gpapi::gateway::GatewayLoginProtocolError))?;
client.update_registered_session(&descriptor, &authentication, &mut self.sessions.borrow_mut());
}
return Ok(GatewayLoginSession {
authentication,
extension_auth: SessionExtensionAuth::new(cred.clone(), client),
});
}
GatewayLogin::Mfa(message, input_str) => {
let otp = Text::new(&message).prompt()?;
client.respond_mfa(&input_str, &otp);
info!("Retrying gateway login with MFA...");
}
}
}
}
pub(super) async fn connect_gateway(
&self,
portal: &str,
gateway: &str,
authentication: &GatewayAuthentication,
allow_extend_session: bool,
extension_auth: SessionExtensionAuth,
) -> Result<(), GatewayConnectError> {
let cookie = authentication.cookie();
// --cookie-only: print the gateway cookie and exit without opening a tunnel.
// No tun device is allocated, no root is required, and no logout is issued
// against the gateway — the cookie remains valid for subsequent use.
// Output format matches openconnect --authenticate for easy shell consumption.
if self.args.cookie_only {
println!("COOKIE='{}'", cookie);
println!("HOST='{}'", gateway);
return Ok(());
}
if authentication.mode() != SessionMode::Tunnel {
return Err(GatewayConnectError::after_establishment(anyhow::anyhow!(
"Non-tunnel authentication requires fresh internal portal discovery"
)));
}
self
.check_cancelled()
.map_err(GatewayConnectError::after_establishment)?;
let identity_files = extension_auth
.client_identity()
.map(|identity| identity.write_files(None))
.transpose()
.map_err(GatewayConnectError::before_establishment)?;
let certificate = identity_files.as_ref().map(|files| files.certificate().to_owned());
let sslkey = identity_files.as_ref().and_then(|files| files.key().map(str::to_owned));
let key_password = extension_auth
.client_identity()
.and_then(|identity| identity.key_password())
.map(str::to_owned);
let mtu = self.args.mtu.unwrap_or(0);
let os_profile = self.os_profile.borrow().clone();
let hip_source = self
.hip_source(os_profile.clone())
.map_err(GatewayConnectError::before_establishment)?;
let session_ctx = build_session_context(SessionContextInput {
portal: portal.to_string(),
gateway: gateway.to_string(),
cookie: cookie.to_string(),
os_profile: os_profile.clone(),
certificate: certificate.clone(),
sslkey: sslkey.clone(),
key_password: key_password.clone(),
disable_ipv6: self.args.disable_ipv6,
extension_auth: Some(extension_auth),
});
let vpn_builder = Vpn::builder(gateway, cookie)
.script(self.args.script.clone())
.interface(self.args.interface.clone())
.script_tun(self.args.script_tun)
.certificate(certificate)
.sslkey(sslkey)
.key_password(key_password)
.hip_source(hip_source)
.reconnect_timeout(self.args.reconnect_timeout)
.mtu(mtu)
.disable_ipv6(self.args.disable_ipv6)
.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);
#[cfg(target_os = "macos")]
let vpn_builder = if self.args.script.is_none()
&& std::env::var_os("GP_VPNC_SCRIPT").is_none_or(|value| value.is_empty())
&& let Some(script) = common::binary_paths::bundled_vpnc_script()
{
vpn_builder.script_path(script.to_string_lossy().into_owned())
} else {
vpn_builder
};
let vpn = apply_os_profile(vpn_builder, &os_profile)
.build()
.map_err(|err| GatewayConnectError::before_establishment(err.into()))?;
let vpn = Arc::new(vpn);
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);
let tunnel_established = Arc::new(AtomicBool::new(false));
let tunnel_established_on_connect = Arc::clone(&tunnel_established);
let disconnect_requested = Arc::new(AtomicBool::new(false));
let disconnect_requested_on_signal = Arc::clone(&disconnect_requested);
let cancellation = self.cancellation.clone();
let disconnect_task = tokio::spawn(async move {
cancellation.cancelled().await;
info!("Received the interrupt signal, disconnecting...");
disconnect_requested_on_signal.store(true, Ordering::SeqCst);
vpn_clone.disconnect();
});
let lock_file_on_connect = self.shared_args.lock_file.to_path_buf();
let pid_written = self.pid_written.clone();
let log_format = self.shared_args.log_format;
let session_cancellation = self.cancellation.clone();
let (established_tx, established_rx) = tokio::sync::oneshot::channel();
self.sessions.borrow_mut().relinquish_gateway(gateway);
let worker = tokio::task::spawn_blocking(move || {
vpn.connect(move |vpn_session_info| {
if session_cancellation.is_cancelled() {
return;
}
tunnel_established_on_connect.store(true, Ordering::SeqCst);
pid_written.store(write_pid_file(&lock_file_on_connect), Ordering::SeqCst);
let _ = established_tx.send(());
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, log_format);
session_task_on_connect.lock().unwrap().replace(task);
})
});
tokio::pin!(worker);
let connect_result = tokio::select! {
result = &mut worker => result,
established = established_rx => {
if established.is_ok() {
let unused = self.sessions.borrow().members().iter()
.filter(|session| session.gateway.server() != gateway)
.map(|session| session.gateway.server().to_owned())
.collect::<Vec<_>>();
for server in unused {
self.logout_gateway(&server).await;
}
}
(&mut worker).await
}
};
let tunnel_established = tunnel_established.load(Ordering::SeqCst);
disconnect_task.abort();
let _ = disconnect_task.await;
let session_task = { session_task.lock().unwrap().take() };
if let Some(task) = session_task {
task.abort();
let _ = task.await;
}
let disconnect_requested = disconnect_requested.load(Ordering::SeqCst);
let connect_result = connect_result.map_err(|error| GatewayConnectError::after_establishment(error.into()))?;
classify_openconnect_result(connect_result, tunnel_established, disconnect_requested)
}
pub(super) fn hip_source(&self, profile: OsProfile) -> anyhow::Result<HipSource> {
let user = self.determine_hip_user();
let script = self.args.hip.as_ref().or(self.args.csd_wrapper.as_ref());
match script {
Some(path) if !path.is_empty() => Ok(HipSource::Script(HipScript::new(path.clone(), get_uid(&user)?)?)),
Some(_) => {
anyhow::ensure!(user.is_none(), "--hip-user requires an explicit HIP script");
Ok(HipSource::Generator(Arc::new(move |request, control| {
let input = gphip::ReportInput {
profile: profile.clone(),
context: gphip::ReportContext::Connected {
cookie: request.cookie.clone(),
client_ip: request.client_ip.clone(),
client_ipv6: request.client_ipv6.clone(),
md5: request.md5.clone(),
},
};
gphip::generate_report_with_control(&input, &|| control.check())
.map_err(|error| error.downcast::<std::io::Error>().unwrap_or_else(std::io::Error::other))
})))
}
None => {
anyhow::ensure!(user.is_none(), "--hip-user requires an explicit HIP script");
Ok(HipSource::Disabled)
}
}
}
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 classify_openconnect_result(
exit_code: i32,
tunnel_established: bool,
disconnect_requested: bool,
) -> Result<(), GatewayConnectError> {
if exit_code == 0 {
return Ok(());
}
if disconnect_requested && exit_code == OPENCONNECT_INTERRUPTED_EXIT_CODE {
return Ok(());
}
let error = anyhow::anyhow!("OpenConnect exited with status {}", exit_code);
if tunnel_established {
Err(GatewayConnectError::after_establishment(error))
} else {
Err(GatewayConnectError::before_establishment(error))
}
}
fn direct_gateway_command(gateway: &str) -> String {
format!("gpauth --gateway {gateway} | sudo gpclient connect {gateway} --as-gateway --cookie-on-stdin")
}
pub(super) fn write_pid_file(lock_file: &Path) -> bool {
let pid = std::process::id();
if let Err(err) = fs::write(lock_file, pid.to_string()) {
warn!("Failed to write PID file: {}", err);
false
} else {
info!("Wrote PID {} to {}", pid, lock_file.display());
true
}
}
fn get_uid(user: &Option<String>) -> anyhow::Result<Option<u32>> {
user
.as_ref()
.map(|user| get_user_by_name(user).map(|user| user.uid()))
.transpose()
}
fn apply_os_profile(builder: VpnBuilder, profile: &OsProfile) -> VpnBuilder {
builder
.os(Some(profile.client_os().to_openconnect_os().to_string()))
.os_version(Some(profile.os_version().to_string()))
.client_version(Some(profile.client_version().to_string()))
.host_id(Some(profile.host_identity().host_id().to_string()))
.user_agent(Some(profile.user_agent().to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hip_script_defaults_to_inherited_process_identity() {
assert_eq!(get_uid(&None).unwrap(), None);
}
#[test]
fn explicit_hip_user_must_exist() {
assert!(get_uid(&Some("gpclient-nonexistent-hip-user".to_string())).is_err());
}
#[test]
fn explicit_hip_user_resolves_to_the_selected_account() {
let current = uzers::get_user_by_uid(uzers::get_effective_uid()).unwrap();
let name = current.name().to_string_lossy().into_owned();
assert_eq!(get_uid(&Some(name)).unwrap(), Some(current.uid()));
}
#[test]
fn openconnect_success_is_not_a_gateway_failure() {
assert!(classify_openconnect_result(0, false, false).is_ok());
assert!(classify_openconnect_result(0, true, false).is_ok());
}
#[test]
fn openconnect_failure_before_callback_is_retryable_gateway_failure() {
let err = classify_openconnect_result(1, false, false).expect_err("nonzero exit should fail");
assert!(err.is_before_establishment());
}
#[test]
fn openconnect_failure_after_callback_is_terminal_gateway_failure() {
let err = classify_openconnect_result(1, true, false).expect_err("nonzero exit should fail");
assert!(!err.is_before_establishment());
}
#[test]
fn interrupted_exit_after_requested_disconnect_is_success() {
assert!(classify_openconnect_result(OPENCONNECT_INTERRUPTED_EXIT_CODE, true, true).is_ok());
}
#[test]
fn interrupted_exit_without_requested_disconnect_is_failure() {
let err = classify_openconnect_result(OPENCONNECT_INTERRUPTED_EXIT_CODE, true, false)
.expect_err("unexpected interrupt should fail");
assert!(!err.is_before_establishment());
}
#[test]
fn direct_gateway_recommendation_uses_gateway_server() {
assert_eq!(
direct_gateway_command("gateway.example.test"),
"gpauth --gateway gateway.example.test | sudo gpclient connect gateway.example.test --as-gateway --cookie-on-stdin"
);
}
}
-229
View File
@@ -1,229 +0,0 @@
use std::sync::Arc;
use anyhow::{Context, bail, ensure};
use gpapi::{
credential::AuthCookieCredential,
gateway::{Gateway, GatewayLoginContext, GatewaySelection},
portal::PortalConfig,
process::collection::CollectionControl,
session::{
MaintenanceState, SessionEndReason, SessionMode,
network::PhysicalNetwork,
non_tunnel::{SessionCallbacks, SessionExit, maintain_non_tunnel_sessions},
},
};
use log::{info, warn};
use super::ConnectHandler;
impl ConnectHandler<'_> {
pub(super) async fn connect_internal_gateways(
&self,
portal: &str,
config: &PortalConfig,
credential: &AuthCookieCredential,
first_gateway: &Gateway,
first_session: super::gateway::GatewayLoginSession,
remaining: &[&Gateway],
) -> anyhow::Result<()> {
ensure!(remaining.len() < 64, "Too many internal non-tunnel candidates");
let mut hosts = std::collections::HashSet::new();
for gateway in std::iter::once(first_gateway).chain(remaining.iter().copied()) {
ensure!(
gateway.kind() == gpapi::gateway::GatewayKind::Internal,
"Non-tunnel candidates must be internal"
);
ensure!(
hosts.insert(gpapi::utils::normalize_server(gateway.server())?),
"Duplicate internal gateway"
);
}
let mut authenticated = vec![(first_gateway, first_session)];
for gateway in remaining.iter().copied() {
self.check_cancelled()?;
let context =
GatewayLoginContext::new(gateway, GatewaySelection::Auto).with_connect_method(config.connect_method());
match self
.authenticate_gateway(
portal,
gateway.server(),
credential,
config.default_browser().unwrap_or(false),
context,
)
.await
{
Ok(session) => authenticated.push((gateway, session)),
Err(error) => {
self.logout_gateway(gateway.server()).await;
self.check_cancelled()?;
if self.auth_recovery.borrow().dmabuf_disabled() {
return Err(self.auth_recovery.borrow().terminal(error));
}
warn!("Internal gateway {gateway} authentication failed: {error}");
}
}
}
self.check_cancelled()?;
let modes = authenticated.iter().map(|(_, session)| session.authentication.mode());
ensure!(
internal_session_mode(modes)? == SessionMode::NonTunnel,
"Expected non-tunnel authentication"
);
self.run_internal_session(config, &authenticated).await
}
async fn run_internal_session(
&self,
config: &PortalConfig,
authenticated: &[(&gpapi::gateway::Gateway, super::gateway::GatewayLoginSession)],
) -> anyhow::Result<()> {
let cancellation = self.cancellation.clone();
let network = Arc::new(PhysicalNetwork::capture_controlled(&cancellation).await?);
let detection = config.internal_detection().cloned();
let bindings = authenticated
.iter()
.map(|(_, session)| {
session
.extension_auth
.binding()
.cloned()
.context("Non-tunnel binding is missing")
})
.collect::<anyhow::Result<Vec<_>>>()?;
for binding in &bindings {
network
.validate_internal_binding(binding, detection.as_ref(), &cancellation)
.await?;
}
let policy = config
.internal_session_policy()
.context("Invalid internal session policy")?;
let profile = self.os_profile.borrow().clone();
let source = if policy.collect_hip_data() {
self.hip_source(profile.clone())?
} else {
openconnect::HipSource::Disabled
};
let source = Arc::new(source);
let validate_network = network.clone();
let validate_detection = detection.clone();
let callbacks = SessionCallbacks {
produce_report: Arc::new(move |request, control| {
control.check()?;
if matches!(source.as_ref(), openconnect::HipSource::Disabled) {
return gphip::generate_identity_report(&gphip::ReportInput {
profile: profile.clone(),
context: gphip::ReportContext::Connected {
cookie: request.cookie.clone(),
client_ip: request.client_ip.clone(),
client_ipv6: request.client_ipv6.clone(),
md5: request.md5.clone(),
},
})
.map_err(std::io::Error::other);
}
source.collect(
&openconnect::HipRequest {
cookie: request.cookie.clone(),
client_ip: request.client_ip.clone(),
client_ipv6: request.client_ipv6.clone(),
md5: request.md5.clone(),
client_version: profile.client_version().into(),
client_os: profile.client_os().as_str().into(),
os_version: profile.os_version().into(),
host_id: Some(profile.host_id().into()),
local_hostname: Some(profile.computer().into()),
},
&|| control.check(),
)
}),
report_submitted: Arc::new(|_, _| {}),
status_changed: Arc::new(|member| match member.maintenance {
MaintenanceState::Healthy => info!(
"Internal network — authenticated: {} (IPv4: {:?}, IPv6: {:?})",
member.gateway, member.client_ip, member.client_ipv6
),
state => info!("Internal gateway {}: {state:?}", member.gateway),
}),
validate_network: Arc::new(move |cancellation| {
let network = validate_network.clone();
let detection = validate_detection.clone();
let bindings = bindings.clone();
Box::pin(async move {
for binding in &bindings {
network
.validate_internal_binding(binding, detection.as_ref(), &cancellation)
.await?;
}
Ok(())
})
}),
};
let monitor_cancel = cancellation.child_token();
let monitor_token = monitor_cancel.clone();
let (network_changed, network_signal) = tokio::sync::oneshot::channel();
let monitor = tokio::spawn(async move {
match network.wait_for_change(detection, monitor_token).await {
Ok(false) => {}
Ok(true) | Err(_) => {
let _ = network_changed.send(SessionEndReason::NetworkChanged);
}
}
});
// The PID spans maintenance and cleanup, including initialization before the
// first successful HIP exchange. The outer handler owns final session logout.
self.pid_written.store(
super::gateway::write_pid_file(self.shared_args.lock_file),
std::sync::atomic::Ordering::SeqCst,
);
let mut sessions = self.sessions.take();
let result = maintain_non_tunnel_sessions(&mut sessions, policy, callbacks, cancellation, async move {
network_signal.await.unwrap_or(SessionEndReason::NetworkChanged)
})
.await;
self.sessions.replace(sessions);
monitor_cancel.cancel();
monitor.await.context("Internal network monitor failed")?;
match result? {
SessionExit::Disconnected => Ok(()),
SessionExit::Failed(reason) => bail!("Internal session ended: {reason:?}. Connect again to authenticate."),
}
}
pub(super) async fn logout_gateway(&self, gateway: &str) {
let mut sessions = self.sessions.take();
sessions.logout_gateway(gateway).await;
self.sessions.replace(sessions);
}
}
fn internal_session_mode(modes: impl Iterator<Item = SessionMode>) -> anyhow::Result<SessionMode> {
let mut modes = modes;
let mode = modes.next().context("No internal gateway authenticated successfully")?;
ensure!(
modes.all(|candidate| candidate == mode),
"Mixed tunnel and non-tunnel internal gateways are unsupported; select a gateway explicitly"
);
Ok(mode)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn internal_modes_reject_mixed_and_empty_sets() {
assert!(internal_session_mode([].into_iter()).is_err());
assert!(internal_session_mode([SessionMode::Tunnel, SessionMode::NonTunnel].into_iter()).is_err());
assert_eq!(
internal_session_mode([SessionMode::NonTunnel, SessionMode::NonTunnel].into_iter()).unwrap(),
SessionMode::NonTunnel
);
assert_eq!(
internal_session_mode([SessionMode::Tunnel].into_iter()).unwrap(),
SessionMode::Tunnel
);
}
}
-432
View File
@@ -1,432 +0,0 @@
mod args;
mod credential;
#[cfg(test)]
mod flow_tests;
mod gateway;
mod internal;
use std::cell::RefCell;
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
use anyhow::bail;
use gpapi::{
clap::report,
error::PortalError,
gateway::GatewaySelection,
gp_params::GpParams,
os_profile::OsProfile,
portal::{PreloginOptions, prelogin, retrieve_config},
session::GatewaySessions,
utils::request::RequestIdentityError,
};
use inquire::{Password, PasswordDisplayMode, Select};
use log::{Level, info, warn};
use crate::cli::SharedArgs;
pub(crate) use args::ConnectArgs;
use args::{build_os_profile, build_os_profile_with_host_id, warn_deprecated_connect_args};
use credential::CleanAuthState;
use gateway::GatewayConnectError;
pub(crate) struct ConnectHandler<'a> {
cancellation: tokio_util::sync::CancellationToken,
args: &'a ConnectArgs,
shared_args: &'a SharedArgs<'a>,
os_profile: RefCell<OsProfile>,
latest_key_password: RefCell<Option<String>>,
password_from_stdin: RefCell<Option<String>>,
cookie_from_stdin: RefCell<Option<String>>,
clean_auth_state: RefCell<CleanAuthState>,
#[cfg(test)]
auth_attempt_fixture: RefCell<credential::AuthAttemptFixture>,
auth_recovery: RefCell<gpapi::process::rendering_recovery::RecoveryState>,
sessions: RefCell<GatewaySessions>,
pid_written: Arc<AtomicBool>,
}
impl<'a> ConnectHandler<'a> {
pub(crate) fn new(args: &'a ConnectArgs, shared_args: &'a SharedArgs) -> Self {
warn_deprecated_connect_args(args);
#[cfg(feature = "webview-auth")]
let clean_auth = args.clean;
#[cfg(not(feature = "webview-auth"))]
let clean_auth = false;
Self {
cancellation: tokio_util::sync::CancellationToken::new(),
args,
shared_args,
os_profile: RefCell::new(build_os_profile(args)),
latest_key_password: Default::default(),
password_from_stdin: Default::default(),
cookie_from_stdin: Default::default(),
clean_auth_state: RefCell::new(CleanAuthState::new(clean_auth)),
#[cfg(test)]
auth_attempt_fixture: Default::default(),
auth_recovery: RefCell::default(),
sessions: RefCell::default(),
pid_written: Arc::default(),
}
}
fn build_gp_params(&self) -> GpParams {
let mut builder = GpParams::builder(self.os_profile.borrow().clone());
builder
.csc_mode(self.args.csc)
.ignore_tls_errors(self.shared_args.ignore_tls_errors)
.certificate(self.args.certificate.clone())
.sslkey(self.args.sslkey.clone())
.key_password(self.latest_key_password.borrow().clone());
builder.build()
}
pub(super) fn prelogin_options(&self, gateway_browser_auth_allowed: bool) -> PreloginOptions {
PreloginOptions::default()
.external_browser_requested(self.external_browser_requested())
.gateway_external_browser_allowed(gateway_browser_auth_allowed)
}
pub(super) fn direct_gateway_prelogin_options(&self) -> PreloginOptions {
self.prelogin_options(true)
}
pub(super) fn gateway_browser_auth_allowed(&self, portal_config_default_browser: bool) -> bool {
gateway_browser_auth_allowed(portal_config_default_browser, self.external_browser_requested())
}
fn external_browser_requested(&self) -> bool {
#[cfg(feature = "webview-auth")]
{
self.args.default_browser || self.args.browser.is_some()
}
#[cfg(not(feature = "webview-auth"))]
{
self.args.browser.is_some()
}
}
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
let cancellation = self.cancellation.clone();
let signal = tokio::spawn(async move {
gpapi::utils::shutdown_signal().await;
cancellation.cancel();
});
self.auth_recovery.replace(Default::default());
let result = self.handle_attempt().await;
let sessions = self.sessions.take();
if self.args.cookie_only && result.is_ok() {
sessions.relinquish();
} else {
sessions.logout().await;
}
if self.pid_written.load(Ordering::SeqCst) {
if let Err(error) = std::fs::remove_file(self.shared_args.lock_file) {
warn!("Failed to remove PID file: {error}");
}
}
signal.abort();
let _ = signal.await;
result
}
fn check_cancelled(&self) -> anyhow::Result<()> {
if self.cancellation.is_cancelled() {
Err(gpapi::auth::AuthenticationCancelled.into())
} else {
Ok(())
}
}
async fn handle_attempt(&self) -> anyhow::Result<()> {
if self.args.browser_listen.is_some()
&& !matches!(self.args.browser.as_deref(), Some(browser) if browser.eq_ignore_ascii_case("remote"))
{
bail!("The '--browser-listen' option requires '--browser remote'");
}
#[cfg(feature = "webview-auth")]
if self.args.default_browser && self.args.browser.is_some() {
bail!("Cannot use `--default-browser` and `--browser` options at the same time");
}
self.latest_key_password.replace(self.args.key_password.clone());
loop {
self.check_cancelled()?;
let result = self.handle_impl().await;
let Err(err) = self.auth_recovery.borrow().finish(result) else {
return Ok(());
};
if err
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
.is_some()
{
return Err(err);
}
let Some(root_cause) = err.root_cause().downcast_ref::<RequestIdentityError>() else {
return Err(err);
};
match root_cause {
RequestIdentityError::NoKey => {
let format = self.shared_args.log_format;
report(
format,
Level::Error,
"ERROR: No private key found in the certificate file",
);
report(
format,
Level::Error,
"ERROR: Please provide the private key file using the `-k` option",
);
return Ok(());
}
RequestIdentityError::NoPassphrase(cert_type) | RequestIdentityError::DecryptError(cert_type) => {
let message = format!("Enter the {} passphrase:", cert_type);
let password = Password::new(&message)
.without_confirmation()
.with_display_mode(PasswordDisplayMode::Masked)
.prompt()?;
self.latest_key_password.replace(Some(password));
}
}
}
}
pub(crate) async fn handle_impl(&self) -> anyhow::Result<()> {
self.check_cancelled()?;
let server = self.args.server.as_str();
let as_gateway = self.args.as_gateway;
self.prepare_cookie_from_stdin()?;
if as_gateway {
info!("Treating the server as a gateway");
return self.connect_gateway_with_prelogin(server, server, false, None).await;
}
if !self.args.cookie_on_stdin {
if let Some(result) = self.try_cached_cookie(server).await {
return result;
}
}
self.check_cancelled()?;
let Err(err) = self.connect_portal_with_prelogin(server).await else {
return Ok(());
};
let err = self.auth_recovery.borrow().terminal(err);
if err
.downcast_ref::<gpapi::process::rendering_recovery::RecoveryFailed>()
.is_some()
{
return Err(err);
}
warn!("Failed to connect portal with prelogin: {}", err);
if err.root_cause().downcast_ref::<PortalError>().is_some() {
info!("Trying the gateway authentication workflow...");
self.connect_gateway_with_prelogin(server, server, false, None).await?;
let format = self.shared_args.log_format;
report(
format,
Level::Warn,
"\nNOTE: the server may be a gateway, not a portal.",
);
report(
format,
Level::Warn,
"NOTE: try to use the `--as-gateway` option if you were authenticated twice.",
);
Ok(())
} else {
Err(err)
}
}
async fn connect_portal_with_prelogin(&self, portal: &str) -> anyhow::Result<()> {
let gp_params = self.build_gp_params();
let mut prelogin = tokio::select! {
biased;
_ = self.cancellation.cancelled() => return Err(gpapi::auth::AuthenticationCancelled.into()),
result = prelogin(portal, &gp_params, self.prelogin_options(false)) => result?,
};
let cached = self.cached_portal_credential(portal);
let cached_config = match cached {
Some(cred) => match retrieve_config(portal, &cred, &gp_params, &self.cancellation).await {
Ok(config) => Some((cred, config)),
Err(error) => {
self.check_cancelled()?;
warn!("Cached portal authentication failed: {error}");
self.clear_cookie_cache();
None
}
},
None => None,
};
let (cred, mut portal_config) = match cached_config {
Some(result) => result,
None => {
let (replacement, cred) = self
.obtain_credential_with_recovery(prelogin.clone(), portal, false)
.await?;
prelogin = replacement;
self.check_cancelled()?;
let config = retrieve_config(portal, &cred, &gp_params, &self.cancellation).await?;
(cred, config)
}
};
self.check_cancelled()?;
portal_config.sort_gateways(prelogin.region());
let auth_cookie = match cred.password() {
Some(password) => portal_config.auth_cookie().clone().with_password(password),
None => portal_config.auth_cookie().clone(),
};
let portal_config_default_browser = portal_config.default_browser().unwrap_or(false);
info!("Portal config default-browser: {}", portal_config_default_browser);
if self.args.auto_gateway {
let gateways = portal_config.gateways();
if gateways.is_empty() {
bail!("No gateways available in portal config for auto-gateway selection");
}
info!(
"Auto-gateway mode: trying {} gateway(s) in priority order",
gateways.len()
);
let mut last_err: Option<anyhow::Error> = None;
for (index, gateway) in gateways.iter().enumerate() {
info!("Auto-gateway: attempting gateway {}", gateway);
match self
.connect_gateway_with_fallback(
portal,
gateway,
&auth_cookie,
&portal_config,
GatewaySelection::Auto,
&gateways[index + 1..],
)
.await
{
Ok(()) => return Ok(()),
Err(err) => {
self.logout_gateway(gateway.server()).await;
if self.auth_recovery.borrow().dmabuf_disabled() || !err.is_before_establishment() {
return Err(self.auth_recovery.borrow().terminal(err.into_error()));
}
warn!(
"Auto-gateway: gateway {} failed before session establishment: {}",
gateway,
err.as_error()
);
last_err = Some(err.into_error());
}
}
}
let detail = last_err
.map(|e| e.to_string())
.unwrap_or_else(|| "unknown error".to_string());
bail!(
"Auto-gateway: all {} gateway(s) failed to connect; last error: {}",
gateways.len(),
detail
);
}
let gateway_selection = if self.args.gateway.is_some() {
GatewaySelection::Manual
} else {
GatewaySelection::Auto
};
let selected_gateway = match &self.args.gateway {
Some(gateway) => portal_config
.find_gateway(gateway)
.ok_or_else(|| anyhow::anyhow!("Cannot find gateway specified: {}", gateway))?,
None => {
let gateways = portal_config.gateways();
if gateways.is_empty() {
bail!("No gateways available in portal configuration");
}
if gateways.len() > 1 {
let gateway = Select::new("Which gateway do you want to connect to?", gateways)
.with_vim_mode(true)
.prompt()?;
info!("Connecting to the selected gateway: {}", gateway);
gateway
} else {
info!("Connecting to the only available gateway: {}", gateways[0]);
gateways[0]
}
}
};
self
.connect_gateway_with_fallback(
portal,
selected_gateway,
&auth_cookie,
&portal_config,
gateway_selection,
&[],
)
.await
.map_err(GatewayConnectError::into_error)
}
fn apply_stdin_host_id(&self, host_id: Option<&str>) {
let Some(host_id) = host_id else {
return;
};
self
.os_profile
.replace(build_os_profile_with_host_id(self.args, Some(host_id)));
info!(
"connect profile host-id: {}",
self.os_profile.borrow().host_identity().host_id()
);
}
}
fn gateway_browser_auth_allowed(portal_config_default_browser: bool, external_browser_requested: bool) -> bool {
portal_config_default_browser || external_browser_requested
}
#[cfg(test)]
mod tests {
use super::gateway_browser_auth_allowed;
#[test]
fn gateway_browser_auth_is_allowed_by_portal_config() {
assert!(gateway_browser_auth_allowed(true, false));
}
#[test]
fn gateway_browser_auth_is_allowed_by_explicit_browser_request() {
assert!(gateway_browser_auth_allowed(false, true));
}
#[test]
fn gateway_browser_auth_is_disabled_without_portal_config_or_user_request() {
assert!(!gateway_browser_auth_allowed(false, false));
}
}
-285
View File
@@ -1,285 +0,0 @@
use std::{
collections::BTreeMap, fs::OpenOptions, io::Write, os::unix::fs::OpenOptionsExt, path::PathBuf, process::Stdio,
};
use anyhow::{Context, ensure};
use clap::Args;
use common::binary_paths;
use serde::Serialize;
use tokio::{io::AsyncWriteExt, process::Command};
const COLLECTOR: &str = include_str!("../../../scripts/collect-diagnostics.sh");
const MAX_REPORT_BYTES: usize = 64 * 1024;
const FIELDS: &[&str] = &[
"os",
"os_version",
"kernel",
"architecture",
"execution_user",
"ssh_session",
"virtualization",
"gpclient_path",
"gpclient_version",
"gpauth_path",
"gpauth_version",
"gpgui_path",
"gpgui_version",
"display_protocol",
"graphics",
"graphics_packages",
"desktop_version",
"env.XDG_CURRENT_DESKTOP",
"env.XDG_SESSION_DESKTOP",
"env.XDG_SESSION_TYPE",
"env.DESKTOP_SESSION",
"env.WEBKIT_DISABLE_DMABUF_RENDERER",
"env.WEBKIT_DISABLE_COMPOSITING_MODE",
"env.LIBGL_ALWAYS_SOFTWARE",
"env.__NV_DISABLE_EXPLICIT_SYNC",
"env.GDK_BACKEND",
"env.GDK_GL",
];
#[derive(Args)]
pub(crate) struct DiagnosticsArgs {
/// Print the report as JSON instead of text
#[arg(long)]
json: bool,
/// Save the report to a new file instead of stdout (existing files are preserved)
#[arg(long, value_name = "PATH")]
output: Option<PathBuf>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
enum ProbeStatus {
Ok,
Unset,
Unavailable,
Failed,
TimedOut,
NotApplicable,
}
#[derive(Debug, Serialize)]
struct DiagnosticField {
status: ProbeStatus,
value: Option<String>,
}
#[derive(Debug, Serialize)]
struct DiagnosticsReport {
schema_version: u32,
fields: BTreeMap<String, DiagnosticField>,
}
impl DiagnosticsReport {
fn parse(bytes: &[u8]) -> anyhow::Result<Self> {
ensure!(
bytes.len() <= MAX_REPORT_BYTES,
"Diagnostics report exceeds its size limit"
);
let mut fields = BTreeMap::new();
let mut schema_version = None;
for raw_line in bytes.split(|byte| *byte == b'\n').filter(|line| !line.is_empty()) {
let line = String::from_utf8_lossy(raw_line);
let (name, rest) = line.split_once(": ").context("Invalid diagnostics record")?;
let (status, value) = rest.split_once(": ").context("Invalid diagnostics status")?;
let raw_value_length = raw_line
.len()
.checked_sub(name.len() + status.len() + 4)
.context("Invalid diagnostics framing")?;
ensure!(raw_value_length <= 512, "Diagnostics field exceeds its size limit");
ensure!(
!value.chars().any(|c| c.is_ascii_control()),
"Invalid diagnostics value"
);
let status = match status {
"ok" => ProbeStatus::Ok,
"unset" => ProbeStatus::Unset,
"unavailable" => ProbeStatus::Unavailable,
"failed" => ProbeStatus::Failed,
"timed_out" => ProbeStatus::TimedOut,
"not_applicable" => ProbeStatus::NotApplicable,
_ => anyhow::bail!("Unknown diagnostics status"),
};
if name == "schema_version" {
ensure!(schema_version.is_none(), "Duplicate diagnostics schema version");
ensure!(
matches!(status, ProbeStatus::Ok) && value == "1",
"Unsupported diagnostics schema"
);
schema_version = Some(1);
continue;
}
ensure!(FIELDS.contains(&name), "Unknown diagnostics field");
let value = if matches!(status, ProbeStatus::Ok) {
let mut normalized = String::new();
for character in value.chars() {
let character = if character.is_control() { ' ' } else { character };
if normalized.len() + character.len_utf8() > 512 {
break;
}
normalized.push(character);
}
Some(normalized)
} else {
ensure!(value.is_empty(), "Unexpected value for unavailable diagnostics field");
None
};
ensure!(
fields
.insert(name.to_owned(), DiagnosticField { status, value })
.is_none(),
"Duplicate diagnostics field"
);
}
ensure!(fields.len() == FIELDS.len(), "Incomplete diagnostics report");
Ok(Self {
schema_version: schema_version.context("Missing diagnostics schema version")?,
fields,
})
}
fn text(&self) -> String {
let mut text = format!("schema_version: ok: {}\n", self.schema_version);
for name in FIELDS {
let field = &self.fields[*name];
let status = match field.status {
ProbeStatus::Ok => "ok",
ProbeStatus::Unset => "unset",
ProbeStatus::Unavailable => "unavailable",
ProbeStatus::Failed => "failed",
ProbeStatus::TimedOut => "timed_out",
ProbeStatus::NotApplicable => "not_applicable",
};
text.push_str(&format!(
"{name}: {status}: {}\n",
field.value.as_deref().unwrap_or_default()
));
}
text
}
}
impl DiagnosticsArgs {
pub(crate) async fn run(&self, version: &str) -> anyhow::Result<()> {
let mut child = Command::new("/bin/sh")
.args(["-s", "--", "--client-version", version, "--client-path"])
.arg(std::env::current_exe().context("Cannot locate gpclient")?)
.arg("--auth-path")
.arg(binary_paths::gpauth())
.arg("--gui-path")
.arg(binary_paths::gpgui())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.kill_on_drop(true)
.spawn()
.context("Cannot start diagnostics collector")?;
let mut input = child.stdin.take().context("Collector input is unavailable")?;
let (_, output) = tokio::try_join!(
async move {
input.write_all(COLLECTOR.as_bytes()).await?;
drop(input);
Ok::<_, std::io::Error>(())
},
child.wait_with_output(),
)
.context("Diagnostics collection failed")?;
ensure!(
output.status.success(),
"Diagnostics collector exited with {}",
output.status
);
let report = DiagnosticsReport::parse(&output.stdout)?;
let content = if self.json {
format!("{}\n", serde_json::to_string_pretty(&report)?)
} else {
report.text()
};
if let Some(path) = &self.output {
save_report(path, &content)?;
} else {
std::io::stdout().lock().write_all(content.as_bytes())?;
}
Ok(())
}
}
fn save_report(path: &std::path::Path, content: &str) -> anyhow::Result<()> {
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(path)
.context("Cannot create diagnostics file; use a new path")?;
file
.write_all(content.as_bytes())
.context("Cannot save diagnostics report")
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_report() -> String {
let mut text = String::from("schema_version: ok: 1\n");
for name in FIELDS {
text.push_str(&format!("{name}: unavailable: \n"));
}
text
}
#[test]
fn json_preserves_collected_values_and_distinguishes_missing_probes() {
let text = sample_report().replace("os: unavailable: ", "os: ok: FreeBSD");
let report = DiagnosticsReport::parse(text.as_bytes()).unwrap();
let json = serde_json::to_value(report).unwrap();
assert_eq!(json["schema_version"], 1);
assert_eq!(json["fields"]["os"]["value"], "FreeBSD");
assert_eq!(json["fields"]["graphics"]["status"], "unavailable");
assert!(json["fields"]["graphics"]["value"].is_null());
}
#[test]
fn malformed_or_injected_records_are_rejected() {
let good = sample_report();
for bad in [
good.replace("os: unavailable: ", "os: mystery: "),
good.replace("os: unavailable: ", "os: ok: text\u{1b}[31m"),
good.replace("os: unavailable: ", "os: ok: value\nsecret: ok: token"),
format!("{good}os: ok: duplicate\n"),
good.replace("schema_version: ok: 1", "schema_version: ok: 2"),
good.replace("os: unavailable: \n", ""),
] {
assert!(DiagnosticsReport::parse(bad.as_bytes()).is_err());
}
}
#[test]
fn invalid_utf8_and_unicode_controls_produce_a_bounded_readable_value() {
let mut bytes = sample_report()
.replace("os: unavailable: ", "os: ok: REPLACE")
.into_bytes();
let start = bytes.windows(7).position(|value| value == b"REPLACE").unwrap();
bytes.splice(start..start + 7, [0xff; 500]);
let report = DiagnosticsReport::parse(&bytes).unwrap();
let value = report.fields["os"].value.as_ref().unwrap();
assert!(value.len() <= 512);
assert!(value.starts_with('\u{fffd}'));
let text = sample_report().replace("os: unavailable: ", "os: ok: Test\u{85}OS");
let report = DiagnosticsReport::parse(text.as_bytes()).unwrap();
assert_eq!(report.fields["os"].value.as_deref(), Some("Test OS"));
assert!(report.text().contains("os: ok: Test OS"));
}
#[test]
fn saving_a_report_does_not_overwrite_existing_files() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("diagnostics.txt");
save_report(&path, "first").unwrap();
assert!(save_report(&path, "second").is_err());
assert_eq!(std::fs::read_to_string(path).unwrap(), "first");
}
}
+5 -5
View File
@@ -1,7 +1,8 @@
use crate::GP_CLIENT_LOCK_FILE;
use clap::Args;
use gpapi::utils::lock_file::gpservice_lock_info;
use log::{info, warn};
use std::{fs, path::Path, str::FromStr, thread, time::Duration};
use std::{fs, str::FromStr, thread, time::Duration};
use sysinfo::{Pid, Signal, System};
#[derive(Args)]
@@ -16,17 +17,16 @@ pub struct DisconnectArgs {
pub struct DisconnectHandler<'a> {
args: &'a DisconnectArgs,
lock_file: &'a Path,
}
impl<'a> DisconnectHandler<'a> {
pub fn new(args: &'a DisconnectArgs, lock_file: &'a Path) -> Self {
Self { args, lock_file }
pub fn new(args: &'a DisconnectArgs) -> Self {
Self { args }
}
pub async fn handle(&self) -> anyhow::Result<()> {
// Try to disconnect the CLI client
if let Ok(c) = fs::read_to_string(self.lock_file) {
if let Ok(c) = fs::read_to_string(GP_CLIENT_LOCK_FILE) {
send_signal(c.trim(), Signal::Interrupt).unwrap_or_else(|err| {
warn!("Failed to send signal to client: {}", err);
});
+223 -34
View File
@@ -1,27 +1,96 @@
use std::time::Duration;
use askama::Template;
use clap::Args;
use gpapi::{
clap::args::Os,
os_profile::{ClientOs, OsProfileBuilder},
process::collection::CollectionBudget,
};
use gphip::{ReportContext, ReportInput, generate_report_with_control};
use gpapi::{clap::args::Os, utils::host_utils};
use log::debug;
use std::{collections::HashMap, env};
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,
}
struct HostInfo<'a> {
os_vendor: &'a str,
os_version: &'a str,
host_id: String,
host_name: String,
software_version: &'a str,
domain: String,
network_interfaces: Vec<NetworkInterface>,
}
impl<'a> HostInfo<'a> {
fn default_ipv4(&self) -> &str {
self
.network_interfaces
.first()
.and_then(|iface| iface.ipv4.as_deref())
.unwrap_or_default()
}
fn default_ipv6(&self) -> &str {
self
.network_interfaces
.first()
.and_then(|iface| iface.ipv6.as_deref())
.unwrap_or_default()
}
}
#[derive(Clone)]
struct NetworkInterface {
name: String,
description: String,
mac_address: Option<String>,
ipv4: Option<String>,
ipv6: Option<String>,
}
impl NetworkInterface {
fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
Self {
name: name.into(),
description: description.into(),
mac_address: None,
ipv4: None,
ipv6: None,
}
}
fn with_ipv4(mut self, ipv4: Option<String>) -> Self {
self.ipv4 = ipv4;
self
}
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,
help = "The GP client version, defaults to APP_VERSION or the packaged version"
)]
client_version: Option<String>,
#[arg(long, value_enum, help = "The client OS")]
#[arg(long, value_enum, default_value_t = HipArgs::default_os(), help = "The client OS")]
client_os: Os,
#[arg(long, hide = true)]
#[arg(long, help = "The OS version string, defaults to a computed value for the target OS")]
os_version: Option<String>,
#[arg(long, help = "Use this runtime host ID when building the OS profile")]
host_id: Option<String>,
#[arg(long, help = "The authentication cookie")]
cookie: String,
@@ -35,6 +104,34 @@ pub(crate) struct HipArgs {
md5: String,
}
impl HipArgs {
fn default_os() -> Os {
if cfg!(target_os = "macos") {
Os::Mac
} else if cfg!(target_os = "windows") {
Os::Windows
} else {
Os::Linux
}
}
fn client_version(&self) -> String {
self
.client_version
.clone()
.or_else(|| env::var("APP_VERSION").ok())
.unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string())
}
fn os_version(&self) -> String {
self.os_version.clone().unwrap_or_else(|| match self.client_os {
Os::Linux => host_utils::get_linux_os_string().to_string(),
Os::Windows => host_utils::get_windows_os_string().to_string(),
Os::Mac => host_utils::get_macos_os_string().to_string(),
})
}
}
pub(crate) struct HipHandler<'a> {
args: &'a HipArgs,
}
@@ -45,25 +142,117 @@ impl<'a> HipHandler<'a> {
}
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
let budget = CollectionBudget::new(Duration::from_secs(60));
let client_os = ClientOs::from(self.args.client_os);
let mut builder = OsProfileBuilder::new(client_os).client_version(self.args.client_version.clone());
if let Some(os_version) = self.args.os_version.as_deref() {
builder = builder.os_version(os_version);
}
if let Some(host_id) = self.args.host_id.as_deref() {
builder = builder.host_id_override(host_id);
}
let input = ReportInput {
profile: builder.build_with_control(&budget)?,
context: ReportContext::Connected {
cookie: self.args.cookie.clone(),
client_ip: self.args.client_ip.clone(),
client_ipv6: self.args.client_ipv6.clone(),
md5: self.args.md5.clone(),
},
};
println!("{}", generate_report_with_control(&input, &budget)?);
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> {
serde_urlencoded::from_str(&self.args.cookie).unwrap_or_default()
}
fn generate_hip_report(&self, cookie_params: &HashMap<String, String>) -> anyhow::Result<String> {
let (generate_time, day, month, year) = get_current_time_components();
let client_version = self.args.client_version();
let os_version = self.args.os_version();
let user_name = cookie_params.get("user").map(|value| value.as_str()).unwrap_or("");
let host_info = self.collect_host_info(cookie_params, &os_version);
let template = HipReportTemplate {
client_version: &client_version,
generate_time,
day,
month,
year,
user_name,
host_info,
md5: &self.args.md5,
};
format_xml(&template.render()?)
}
fn collect_host_info<'b>(&'b self, cookie_params: &'b HashMap<String, String>, os_version: &'b str) -> HostInfo<'b> {
let domain = cookie_params.get("domain").cloned().unwrap_or_default();
let ipv4 = self
.args
.client_ip
.clone()
.or_else(|| cookie_params.get("preferred-ip").cloned());
let ipv6 = self
.args
.client_ipv6
.clone()
.or_else(|| cookie_params.get("preferred-ipv6").cloned());
match self.args.client_os {
Os::Linux => HostInfo {
os_vendor: "Linux",
os_version,
host_id: host_utils::derive_uuid(&["linux"]),
host_name: whoami::devicename(),
software_version: "",
domain,
network_interfaces: vec![NetworkInterface::new("enp1s0f0", "enp1s0f0")
.with_ipv4(ipv4)
.with_ipv6(ipv6)],
},
Os::Mac => HostInfo {
os_vendor: "Apple",
os_version,
host_id: host_utils::get_machine_id().to_string(),
host_name: whoami::devicename(),
software_version: host_utils::get_macos_version(),
domain,
network_interfaces: vec![NetworkInterface::new("en0", "en0").with_ipv4(ipv4).with_ipv6(ipv6)],
},
Os::Windows => {
let iface = NetworkInterface::new(
format!("{{{}}}", host_utils::derive_uuid(&["pangp"]).to_uppercase()),
"PANGP Virtual Ethernet Adapter Secure",
)
.with_ipv4(ipv4)
.with_ipv6(ipv6);
let loopback = NetworkInterface {
name: iface.name.clone(),
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()),
};
HostInfo {
os_vendor: "Microsoft",
os_version,
host_id: host_utils::get_machine_id().to_string(),
host_name: whoami::devicename(),
software_version: host_utils::get_windows_version(),
domain,
network_interfaces: vec![iface, loopback],
}
}
}
}
}
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(),
)
}
fn format_xml(xml_str: &str) -> anyhow::Result<String> {
let xml = Element::parse(xml_str.as_bytes())?;
let mut xml_buf = Vec::new();
xml.write_with_config(&mut xml_buf, xmltree::EmitterConfig::new().perform_indent(true))?;
Ok(String::from_utf8(xml_buf)?)
}
+65 -87
View File
@@ -1,45 +1,25 @@
use std::{fs, path::PathBuf};
use std::{collections::HashMap, env::temp_dir, fs, path::PathBuf};
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
use std::process::{Command, ExitStatus};
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
use anyhow::Context;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
use anyhow::bail;
use clap::Args;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
use common::binary_paths;
use directories::ProjectDirs;
use gpapi::{process::desktop_launcher::DesktopLauncher, utils::endpoint::http_endpoint};
use gpapi::{
process::service_launcher::ServiceLauncher,
utils::{endpoint::http_endpoint, env_file, shutdown_signal},
};
use log::info;
use tokio::io::AsyncWriteExt;
#[derive(Args)]
pub(crate) struct LaunchGuiArgs {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[arg(
required = false,
conflicts_with = "minimized",
value_parser = parse_auth_callback,
help = "The external-browser authentication callback URL"
help = "The authentication data, used for the default browser authentication"
)]
callback: Option<String>,
pub auth_data: Option<String>,
#[arg(long, help = "Launch the GUI minimized")]
minimized: bool,
}
impl LaunchGuiArgs {
pub(crate) fn is_auth_callback(&self) -> bool {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
{
return self.callback.is_some();
}
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
false
}
}
pub(crate) struct LaunchGuiHandler<'a> {
args: &'a LaunchGuiArgs,
}
@@ -51,14 +31,16 @@ impl<'a> LaunchGuiHandler<'a> {
pub(crate) async fn handle(&self) -> anyhow::Result<()> {
// `launch-gui`cannot be run as root
let user = whoami::username().map_err(|err| anyhow::anyhow!("Failed to resolve current user: {err}"))?;
let user = whoami::username();
if user == "root" {
anyhow::bail!("`launch-gui` cannot be run as root");
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
if let Some(callback) = &self.args.callback {
return forward_auth_callback(callback);
let auth_data = self.args.auth_data.as_deref().unwrap_or_default();
if !auth_data.is_empty() {
info!("Received auth callback data");
// Process the authentication data, its format is `globalprotectcallback:<data>`
return feed_auth_data(auth_data).await;
}
if try_active_gui().await.is_ok() {
@@ -66,13 +48,27 @@ impl<'a> LaunchGuiHandler<'a> {
return Ok(());
}
tokio::spawn(async move {
shutdown_signal().await;
info!("Shutting down...");
});
let log_file = get_log_file()?;
let log_file_path = log_file.to_string_lossy().to_string();
info!("Log file: {}", log_file_path);
let exit_status = DesktopLauncher::new(env!("CARGO_PKG_VERSION"))
let mut extra_envs = HashMap::<String, String>::new();
extra_envs.insert("GP_LOG_FILE".into(), log_file_path.clone());
// Persist the environment variables to a file
let env_file = env_file::persist_env_vars(Some(extra_envs))?;
let env_file = env_file.into_temp_path();
let env_file_path = env_file.to_string_lossy().to_string();
let exit_status = ServiceLauncher::new()
.minimized(self.args.minimized)
.env_file(&env_file_path)
.log_file(&log_file_path)
.launch()
.await?;
@@ -83,36 +79,49 @@ impl<'a> LaunchGuiHandler<'a> {
}
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
fn forward_auth_callback(callback: &str) -> anyhow::Result<()> {
let status = auth_callback_command(callback)
.status()
.context("Failed to start the authentication callback handler")?;
ensure_auth_callback_succeeded(status)
}
async fn feed_auth_data(auth_data: &str) -> anyhow::Result<()> {
let (res_gui, res_cli) = tokio::join!(feed_auth_data_gui(auth_data), feed_auth_data_cli(auth_data));
if let Err(err) = res_gui {
info!("Failed to feed auth data to the GUI: {}", err);
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
fn auth_callback_command(callback: &str) -> Command {
let mut command = Command::new(binary_paths::gpauth());
command.args(["auth-callback", callback]);
command
}
if let Err(err) = res_cli {
info!("Failed to feed auth data to the CLI: {}", err);
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
fn ensure_auth_callback_succeeded(status: ExitStatus) -> anyhow::Result<()> {
if !status.success() {
bail!("Authentication callback handler exited with {status}");
// Cleanup the temporary file
let html_file = temp_dir().join("gpauth.html");
if let Err(err) = std::fs::remove_file(&html_file) {
info!("Failed to remove {}: {}", html_file.display(), err);
}
Ok(())
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
fn parse_auth_callback(callback: &str) -> Result<String, String> {
callback
.starts_with("globalprotectcallback:")
.then(|| callback.to_owned())
.ok_or_else(|| "callback URL must use the globalprotectcallback scheme".to_owned())
async fn feed_auth_data_gui(auth_data: &str) -> anyhow::Result<()> {
info!("Feeding auth data to the GUI");
let service_endpoint = http_endpoint().await?;
reqwest::Client::default()
.post(format!("{}/auth-data", service_endpoint))
.body(auth_data.to_string())
.send()
.await?
.error_for_status()?;
Ok(())
}
async fn feed_auth_data_cli(auth_data: &str) -> anyhow::Result<()> {
info!("Feeding auth data to the CLI");
let port_file = temp_dir().join("gpcallback.port");
let port = tokio::fs::read_to_string(port_file).await?;
let mut stream = tokio::net::TcpStream::connect(format!("127.0.0.1:{}", port.trim())).await?;
stream.write_all(auth_data.as_bytes()).await?;
Ok(())
}
async fn try_active_gui() -> anyhow::Result<()> {
@@ -135,34 +144,3 @@ fn get_log_file() -> anyhow::Result<PathBuf> {
Ok(dirs.data_dir().join("gpclient.log"))
}
#[cfg(all(test, unix))]
mod tests {
use std::os::unix::process::ExitStatusExt;
use super::*;
const CALLBACK: &str = "globalprotectcallback:cas-as=1&[email protected]&token=token";
#[test]
fn callback_command_preserves_callback_argument() {
let command = auth_callback_command(CALLBACK);
let args = command
.get_args()
.map(|argument| argument.to_str().unwrap())
.collect::<Vec<_>>();
assert_eq!(args, ["auth-callback", CALLBACK]);
}
#[test]
fn callback_command_status_is_propagated() {
assert!(ensure_auth_callback_succeeded(ExitStatus::from_raw(0)).is_ok());
assert!(ensure_auth_callback_succeeded(ExitStatus::from_raw(1 << 8)).is_err());
}
#[test]
fn rejects_non_callback_url() {
assert!(parse_auth_callback("https://example.com/callback").is_err());
}
}
-2
View File
@@ -1,10 +1,8 @@
mod cli;
mod connect;
mod diagnostics;
mod disconnect;
mod hip;
mod launch_gui;
mod session;
pub(crate) const GP_CLIENT_LOCK_FILE: &str = "/var/run/gpclient.lock";
-254
View File
@@ -1,254 +0,0 @@
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use gpapi::{
clap::report,
gateway::{SessionContext, SessionExtensionAuth, extend_session},
log_format::LogFormat,
os_profile::OsProfile,
session::{SessionInfo, SessionRequestArgs, SessionWarning},
};
use log::{Level, 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) os_profile: OsProfile,
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(input.os_profile.user_agent().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,
log_format: LogFormat,
) -> JoinHandle<()> {
handle.spawn(run_session_runtime(session_ctx, session_info, log_format))
}
async fn run_session_runtime(session_ctx: SessionContext, mut session_info: SessionInfo, log_format: LogFormat) {
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;
report(log_format, Level::Warn, &format!("\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;
};
report(log_format, Level::Info, "Session extended.");
session_info = next_session_info;
}
Err(err) => {
warn!("Failed to extend session: {}", err);
report(
log_format,
Level::Warn,
&format!("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_os_profile() {
let profile = OsProfile::builder(gpapi::os_profile::ClientOs::Mac)
.client_version("6.3.1-12".to_string())
.build();
let expected_user_agent = profile.user_agent().to_string();
let ctx = build_session_context(SessionContextInput {
portal: "portal.example.com".to_string(),
gateway: "vpn.example.com".to_string(),
cookie: "authcookie=AUTH".to_string(),
os_profile: profile,
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(expected_user_agent.as_str())
);
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(),
}),
..Default::default()
},
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(),
}),
..Default::default()
},
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);
}
}
@@ -136,18 +136,9 @@
</list>
<missing-patches/>
</entry>
{% elif host_info.os_vendor == "Apple" -%}
{% else if host_info.os_vendor == "Apple" -%}
<entry name="anti-malware">
<list>
{% if let Some(sentinel) = &host_info.sentinel %}
<entry>
<ProductInfo>
<Prod vendor="SentinelOne" name="Sentinel Agent" version="{{ sentinel.version }}" engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="4"/>
<real-time-protection>{% if sentinel.real_time_protection %}yes{% else %}no{% endif %}</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
{% endif -%}
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Xprotect" version="2167" defver="235000000000000" engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="4"/>
@@ -199,16 +190,6 @@
</entry>
<entry name="firewall">
<list>
{% if let Some(sentinel) = &host_info.sentinel %}
{% if let Some(firewall_enabled) = sentinel.firewall_enabled %}
<entry>
<ProductInfo>
<Prod vendor="SentinelOne" name="Sentinel Agent" version="{{ sentinel.version }}"/>
<is-enabled>{% if firewall_enabled %}yes{% else %}no{% endif %}</is-enabled>
</ProductInfo>
</entry>
{% endif -%}
{% endif -%}
<entry>
<ProductInfo>
<Prod vendor="Apple Inc." name="Mac OS X Builtin Firewall" version="{{ host_info.software_version }}"/>
@@ -235,38 +216,9 @@
<missing-patches>
</missing-patches>
</entry>
{% elif host_info.os_vendor == "Linux" -%}
{% else if host_info.os_vendor == "Linux" -%}
<entry name="anti-malware">
<list>
{% if let Some(sentinel) = &host_info.sentinel %}
<entry>
<ProductInfo>
<Prod vendor="SentinelOne" name="Sentinel Agent" version="{{ sentinel.version }}" engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="1"/>
<real-time-protection>{% if sentinel.real_time_protection %}yes{% else %}no{% endif %}</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
{% endif -%}
{% if let Some(defender) = &host_info.defender %}
<entry>
<ProductInfo>
<Prod name="Microsoft Defender ATP" version="{{ defender.app_version }}" defver="{{ defender.definitions_version }}" prodType="3" engver="{{ defender.engine_version }}" osType="1" vendor="Microsoft Corporation" dateday="{{ day }}" dateyear="{{ year }}" datemon="{{ month }}">
</Prod>
<real-time-protection>{% if defender.real_time_protection_enabled.value %}yes{% else %}no{% endif %}</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
{% endif -%}
{% if let Some(clamav) = &host_info.clamav %}
<entry>
<ProductInfo>
<Prod vendor="Cisco Systems, Inc." name="ClamAV" version="{{ clamav.version }}"{% if let Some(definitions_version) = &clamav.definitions_version %} defver="{{ definitions_version }}"{% endif %} engver="" datemon="{{ month }}" dateday="{{ day }}" dateyear="{{ year }}" prodType="3" osType="1"/>
<real-time-protection>{% if clamav.real_time_protection %}yes{% else %}no{% endif %}</real-time-protection>
<last-full-scan-time>n/a</last-full-scan-time>
</ProductInfo>
</entry>
{% endif -%}
</list>
<list/>
</entry>
<entry name="disk-backup">
<list/>
@@ -289,14 +241,6 @@
</entry>
<entry name="firewall">
<list>
{% if let Some(ufw) = &host_info.ufw %}
<entry>
<ProductInfo>
<Prod vendor="Canonical Ltd." name="UFW" version="{{ ufw.version }}"/>
<is-enabled>{% if ufw.is_enabled %}yes{% else %}no{% endif %}</is-enabled>
</ProductInfo>
</entry>
{% endif -%}
<entry>
<ProductInfo>
<Prod name="IPTables" version="1.8.4" vendor="IPTables">
@@ -317,17 +261,15 @@
<list>
<entry>
<ProductInfo>
<Prod name="Dandified Yum" version="4.2.23" vendor="Red Hat, Inc.">
<Prod name="Apt" version="2.0.11" vendor="Canonical Ltd.">
</Prod>
<is-enabled>yes</is-enabled>
</ProductInfo>
</entry>
</list>
<missing-patches/>
<missing-patches>
</missing-patches>
</entry>
{% endif -%}
<entry name="data-loss-prevention">
<list/>
</entry>
</categories>
</hip-report>
-71
View File
@@ -1,71 +0,0 @@
use std::{os::unix::fs::PermissionsExt, process::Stdio, time::Duration};
use tokio::process::Command;
fn executable(dir: &std::path::Path, name: &str, body: &str) {
let path = dir.join(name);
std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
}
#[tokio::test]
async fn embedded_collector_reports_missing_helpers_without_recursing_or_exposing_private_environment() {
let dir = tempfile::tempdir().unwrap();
let bin = dir.path().join("bin");
std::fs::create_dir(&bin).unwrap();
executable(
&bin,
"uname",
"case \"$1\" in -s) echo Linux ;; -m) echo aarch64 ;; *) echo test-kernel ;; esac",
);
executable(&bin, "gpclient", "echo unexpected-recursion >&2; exit 99");
executable(&bin, "systemd-detect-virt", "echo kvm");
executable(
&bin,
"lspci",
"echo '00:02.0 VGA compatible controller: Test GPU'; echo ' Kernel driver in use: test'",
);
executable(&bin, "pacman", "echo 'gtk3 test-version'");
let report_file = dir.path().join("report.json");
let output = tokio::time::timeout(
Duration::from_secs(30),
Command::new(env!("CARGO_BIN_EXE_gpclient"))
.args(["--fix-openssl", "diagnostics", "--json", "--output"])
.arg(&report_file)
.env("PATH", format!("{}:/usr/bin:/bin", bin.display()))
.env("GP_AUTH_BINARY", dir.path().join("missing-gpauth"))
.env("GP_GUI_BINARY", dir.path().join("missing-gpgui"))
.env("GP_DIAGNOSTICS_PRIVATE_TOKEN", "secret-value-must-not-appear")
.env("XDG_CURRENT_DESKTOP", "TestDesktop\nInjected: secret")
.stdin(Stdio::null())
.kill_on_drop(true)
.output(),
)
.await
.expect("collector must close stdin and terminate")
.unwrap();
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
assert!(output.stdout.is_empty());
let text = std::fs::read_to_string(&report_file).unwrap();
assert!(!text.contains("secret-value-must-not-appear"));
assert!(!String::from_utf8_lossy(&output.stderr).contains("unexpected-recursion"));
let report: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(report["schema_version"], 1);
assert_eq!(report["fields"]["os"]["value"], "Linux");
assert_eq!(report["fields"]["gpclient_path"]["status"], "ok");
for field in ["gpauth_path", "gpauth_version", "gpgui_path", "gpgui_version"] {
assert_eq!(report["fields"][field]["status"], "unavailable");
assert!(report["fields"][field]["value"].is_null());
}
assert!(
report["fields"]["gpclient_version"]["value"]
.as_str()
.unwrap()
.starts_with(env!("CARGO_PKG_VERSION"))
);
assert_eq!(
report["fields"]["env.XDG_CURRENT_DESKTOP"]["value"],
"TestDesktop Injected: secret"
);
assert!(!String::from_utf8_lossy(&output.stderr).contains("Using 'UnsafeLegacyServerConnect'"));
}
+99
View File
@@ -0,0 +1,99 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
version="1.1"
id="Layer_1"
x="0px"
y="0px"
viewBox="0 0 96 96"
style="enable-background:new 0 0 96 96;"
xml:space="preserve"
sodipodi:docname="com.yuezk.qt.gpclient.svg"
inkscape:version="0.92.4 5da689c313, 2019-01-14"><metadata
id="metadata14"><rdf:RDF><cc:Work
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
id="defs12" /><sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="1920"
inkscape:window-height="1006"
id="namedview10"
showgrid="false"
inkscape:zoom="6.9532168"
inkscape:cx="7.9545315"
inkscape:cy="59.062386"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:current-layer="g8499" />
<style
type="text/css"
id="style2">
.st0{fill:#2980B9;}
.st1{fill:#3498DB;}
.st2{fill:#2ECC71;}
.st3{fill:#27AE60;}
</style>
<g
id="g8499"
transform="matrix(1.3407388,0,0,1.3407388,-16.409202,-16.355463)"><g
id="XMLID_1_">
<circle
r="32.5"
cy="48"
cx="48"
class="st0"
id="XMLID_3_"
style="fill:#2980b9" />
<path
d="m 48,15.5 v 65 C 65.9,80.5 80.5,65.7 80.5,48 80.5,30 65.9,15.5 48,15.5 Z"
class="st1"
id="XMLID_4_"
inkscape:connector-curvature="0"
style="fill:#3498db" />
<path
d="m 48,15.5 v 0.6 l 1.2,-0.3 c 0.3,-0.3 0.4,-0.3 0.6,-0.3 h -1.1 z m 7.3,0.9 c -0.1,0 0.4,0.9 1.1,1.8 0.8,1.5 1.1,2.1 1.3,2.1 0.3,-0.3 1.9,-1.2 3,-2.1 -1.7,-0.9 -3.5,-1.5 -5.4,-1.8 z m 10.3,6.2 c -0.1,0 -0.4,0 -0.9,0.6 l -0.8,0.9 0.6,0.6 c 0.3,0.6 0.8,0.9 1,1.2 0.5,0.6 0.6,0.6 0.1,1.5 -0.2,0.6 -0.3,0.9 -0.3,0.9 0.1,0.3 0.3,0.3 1.4,0.3 h 1.6 c 0.1,0 0.3,-0.6 0.4,-1.2 l 0.1,-0.9 -1.1,-0.9 c -1,-0.9 -1,-0.9 -1.4,-1.8 -0.3,-0.6 -0.6,-1.2 -0.7,-1.2 z m -3,2.4 c -0.2,0 -1.3,2.1 -1.3,2.4 0,0 0.3,0.6 0.7,0.9 0.4,0.3 0.7,0.6 0.7,0.6 0.1,0 1.2,-1.2 1.4,-1.5 C 64.2,27.1 64,26.8 63.5,26.2 63.1,25.5 62.7,25 62.6,25 Z m 9.5,1.1 0.2,0.3 c 0,0.3 -0.7,0.9 -1.4,1.5 -1.2,0.9 -1.4,1.2 -2,1.2 -0.6,0 -0.9,0.3 -1.8,0.9 -0.6,0.6 -1.2,0.9 -1.2,1.2 0,0 0.2,0.3 0.6,0.9 0.7,0.6 0.7,0.9 0.2,1.8 l -0.4,0.3 h -1.1 c -0.6,0 -1.5,0 -1.8,-0.3 -0.9,0 -0.8,0 -0.1,2.1 1,3 1.1,3.2 1.3,3.2 0.1,0 1.3,-1.2 2.8,-2.4 1.5,-1.2 2.7,-2.4 2.8,-2.4 l 0.6,0.3 c 0.4,0.3 0.5,0 1.3,-0.6 l 0.8,-0.6 0.8,0.6 c 1.9,1.2 2.2,1.5 2.3,2.4 0.2,1.5 0.3,1.8 0.5,1.8 0.1,0 1.3,-1.5 1.6,-1.8 0.1,-0.3 -0.1,-0.6 -1.1,-2.1 -0.7,-0.9 -1.1,-1.8 -1.1,-2.1 0,0 0.1,0 0.3,-0.3 0.2,0 0.4,0.3 1,0.9 -1.6,-2.3 -3.2,-4.7 -5.1,-6.8 z m 2.8,10.7 c -0.2,0 -0.9,0.9 -0.8,1.2 l 0.5,0.3 H 75 c 0.2,0 0.3,0 0.2,-0.3 C 75.1,37.4 75,36.8 74.9,36.8 Z M 72.3,38 h -2.4 l -2.4,0.3 -4.5,3.5 -4.4,3.8 v 3.5 c 0,2.1 0,3.8 0.1,3.8 0.1,0 0.7,0.9 1.5,1.5 0.8,0.9 1.5,1.5 1.8,1.8 0.4,0.3 0.5,0.3 4,0.6 l 3.4,0.3 1.6,0.9 c 0.8,0.6 1.5,1.2 1.6,1.2 0.1,0 -0.3,0.3 -0.6,0.6 l -0.6,0.6 1,1.2 c 0.5,0.6 1.3,1.5 1.7,1.8 l 0.6,0.9 v 1.7 0.9 c 3.7,-5 5.9,-11.5 6.1,-18.3 0.1,-2.7 -0.3,-5.3 -0.8,-8 l -0.6,-0.3 c -0.1,0 -0.5,0.3 -1,0.6 -0.5,0.3 -1,0.9 -1.1,0.9 -0.1,0 -0.8,-0.3 -1.8,-0.6 l -1.8,-0.6 v -0.9 c 0,-0.6 0,-0.9 -0.6,-1.5 z M 48,63.7 V 64 h 0.2 z"
class="st2"
id="XMLID_13_"
inkscape:connector-curvature="0"
style="fill:#2ecc71" />
<path
d="m 48,15.5 c -3.1,0 -6.2,0.5 -9,1.3 0.3,0.4 0.3,0.4 0.6,0.9 1.5,2.5 1.7,2.8 2.1,2.9 0.3,0 0.9,0.1 1.6,0.1 h 1.2 l 0.9,-2 0.8,-1.9 1.8,-0.6 z m -16.9,4.7 c -2.8,1.7 -5.4,3.9 -7.6,6.4 -3.8,4.3 -6.3,9.6 -7.4,15.4 0.5,0 0.9,-0.1 1.8,-0.1 2.8,0.1 2.5,0 3.4,1.4 0.5,0.8 0.6,0.8 1.4,0.8 1,0.1 0.9,0 0.5,-1.6 -0.2,-0.6 -0.3,-1.2 -0.3,-1.4 0,-0.2 0.5,-0.7 1.7,-1.6 1.9,-1.5 1.8,-1.3 1.5,-2.9 -0.1,-0.3 0.1,-0.6 0.6,-1.2 0.7,-0.7 0.7,-0.6 1.4,-0.6 h 0.7 l 0.1,-1.2 c 0.1,-0.7 0.1,-1.3 0.2,-1.3 0,0 1.9,-1.1 4.1,-2.3 2.2,-1.2 4.1,-2.2 4.2,-2.3 0.2,-0.2 -0.3,-0.8 -2.7,-3.8 -1.5,-1.9 -2.8,-3.6 -2.9,-3.7 z m -5.8,23 c -0.1,0 -0.1,0.3 -0.1,0.6 0,0.6 0,0.7 0.6,1 0.8,0.4 0.9,0.5 0.8,0.2 -0.1,-0.4 -1.2,-1.9 -1.3,-1.8 z m -3.4,2.1 -0.5,1.8 c 0.1,0.1 0.9,0.3 1.8,0.5 1,0.2 1.6,0.4 1.8,0.3 l 0.5,-1.3 z m -3.8,1 -1.1,0.6 c -0.6,0.3 -1.2,0.6 -1.4,0.6 h -0.1 c 0,1.4 0.1,2.8 0.3,4.2 l 0.6,0.4 1,-0.1 h 1 l 0.6,1.4 c 0.3,0.7 0.7,1.4 0.8,1.5 0.1,0.1 1,0.1 1.8,0.1 h 1.5 L 23,56.2 c 0,1.2 0,1.3 -0.6,2.2 -0.4,0.5 -0.6,1.2 -0.6,1.4 0,0.2 0.7,2.1 1.6,4.3 l 1.5,4 1.6,0.8 c 1.2,0.6 1.5,0.8 1.5,1 0,0.1 -0.4,2.1 -0.6,3.1 3,2.5 6.4,4.5 10.2,5.8 3.5,-3.6 6.8,-7.1 7.3,-7.6 l 0.7,-0.7 0.2,-1.9 c 0.2,-1.1 0.4,-2.1 0.4,-2.2 0,-0.1 0.5,-0.6 1,-1.2 0.5,-0.5 0.8,-1 0.8,-1.1 v -0.2 c -0.1,-0.1 -1.4,-1.1 -3,-2.2 l -3.1,-2.1 -1.1,-0.1 c -0.8,0 -1.2,0 -1.3,-0.2 C 39.4,59.2 39.2,58.5 39.1,57.7 39,56.9 38.9,56.2 38.8,56.1 38.8,56 38,56 37.1,56 36.2,56 35.4,55.9 35.3,55.8 35.2,55.7 35.2,55.1 35.1,54.3 35,53.6 34.9,53 34.8,52.9 34.7,52.8 33.7,52.7 32.5,52.6 30.5,52.5 30.1,52.5 29.1,52 l -1.2,-0.6 -1.6,0.7 -1.7,0.9 -1.8,-0.1 c -2,0 -1.9,0.2 -2.1,-1.6 C 20.6,50.7 20.6,50.1 20.5,50.1 20.4,50 20,50 19.6,49.9 L 18.9,49.7 19,49.2 c 0,-0.3 0,-1 0.1,-1.4 L 19.2,47 18.7,46.5 Z m 9.1,1.1 C 27.1,47.5 27.1,47.8 27,48 l -0.1,0.5 2.9,1.2 c 2.9,1.1 3.4,1.2 3.9,0.7 0.2,-0.2 0.1,-0.2 -0.3,-0.4 -0.3,-0.1 -1.7,-0.9 -3.2,-1.6 -1.7,-0.7 -2.9,-1.1 -3,-1 z"
class="st3"
id="XMLID_20_"
inkscape:connector-curvature="0"
style="fill:#27ae60" />
</g><g
transform="matrix(1.458069,0,0,1.458069,-22.631538,-19.615144)"
id="g7664"><path
inkscape:connector-curvature="0"
id="XMLID_6_"
class="st3"
d="m 38.8,56.1 c 0,1.2 1,2.2 2.2,2.2 h 15.2 c 1.2,0 2.2,-1 2.2,-2.2 V 45.3 c 0,-1.2 -1,-2.2 -2.2,-2.2 H 40.9 c -1.2,0 -2.2,1 -2.2,2.2 v 10.8 z"
style="fill:#f1aa27;fill-opacity:1" /><path
style="fill:#e6e6e6"
inkscape:connector-curvature="0"
id="XMLID_7_"
class="st4"
d="m 55.5,43.1 h -3.3 v -3.7 c 0,-2.1 -1.7,-3.8 -3.8,-3.8 -2.1,0 -3.8,1.7 -3.8,3.8 v 3.8 h -3.1 v -3.8 c 0,-3.9 3.2,-7 7,-7 3.9,0 7,3.2 7,7 z" /><path
style="fill:#e6e6e6;fill-opacity:1"
inkscape:connector-curvature="0"
id="XMLID_8_"
class="st5"
d="m 50.35,48.2 c 0,-1 -0.8,-1.8 -1.8,-1.8 -1,0 -1.8,0.8 -1.8,1.8 0,0.7 0.4,1.3 1,1.6 l -1,5.2 h 3.6 l -1,-5.2 c 0.6,-0.3 1,-0.9 1,-1.6 z" /></g></g></svg>

After

Width:  |  Height:  |  Size: 6.7 KiB

-43
View File
@@ -1,43 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
<defs>
<linearGradient id="ocean" x1="245" y1="170" x2="770" y2="770" gradientUnits="userSpaceOnUse">
<stop stop-color="#579bc1"/>
<stop offset=".52" stop-color="#438fbd"/>
<stop offset="1" stop-color="#2f719e"/>
</linearGradient>
<linearGradient id="land" x1="260" y1="190" x2="750" y2="735" gradientUnits="userSpaceOnUse">
<stop stop-color="#56c78a"/>
<stop offset=".55" stop-color="#3bbf78"/>
<stop offset="1" stop-color="#279b5d"/>
</linearGradient>
<linearGradient id="lock" x1="385" y1="400" x2="650" y2="700" gradientUnits="userSpaceOnUse">
<stop stop-color="#f3b84c"/>
<stop offset=".55" stop-color="#e8a12f"/>
<stop offset="1" stop-color="#d4871e"/>
</linearGradient>
<clipPath id="globe-clip">
<circle cx="512" cy="455" r="315"/>
</clipPath>
</defs>
<g transform="translate(512 512) scale(1.3) translate(-512 -455)">
<circle cx="512" cy="455" r="315" fill="url(#ocean)"/>
<g clip-path="url(#globe-clip)" fill="url(#land)">
<path d="M177 326c74-121 177-185 302-190-13 51-49 84-105 98-4 45-32 79-86 101-37 17-75 14-111-9Z"/>
<path d="M564 135c129 18 229 103 273 220-69-3-121 15-157 54-51-14-83-50-95-107-38-36-45-92-21-167Z"/>
<path d="M189 467c63-39 125-34 187 16 57 25 73 73 48 144-45 90-108 146-189 166-58-88-73-197-46-326Z"/>
<path d="M612 572c78-38 157-18 238 59-45 89-122 144-231 164-20-67-22-122-7-165-22-17-22-36 0-58Z"/>
</g>
<circle cx="512" cy="455" r="308" fill="none" stroke="#9ccde2" stroke-width="11" stroke-opacity=".4"/>
<g transform="translate(512 490) scale(.82) translate(-512 -490)">
<path d="M405 429v-75c0-142 214-142 214 0v75" fill="none" stroke="#eef1f2" stroke-width="58" stroke-linecap="round"/>
<rect x="340" y="403" width="344" height="278" rx="62" fill="url(#lock)"/>
<rect x="346" y="409" width="332" height="266" rx="56" fill="none" stroke="#f7cb75" stroke-width="10" stroke-opacity=".45"/>
<g fill="#85500f" opacity=".85">
<path d="M501 538h22l16 69h-54Z"/>
<circle cx="512" cy="521" r="27"/>
</g>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 2.2 KiB

+1
View File
@@ -0,0 +1 @@
html,body,#root{height:100%;margin:0;padding:0;-webkit-user-select:none;user-select:none;cursor:default}
-9
View File
@@ -1,9 +0,0 @@
var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);(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),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var t=e((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 ee(e){if(h=!1,b(e),!m){if(n(c)!==null)m=!0,x||(x=!0,ie());else{var t=n(l);t!==null&&se(ee,t.startTime-e)}}}var x=!1,te=-1,ne=5,S=-1;function re(){return g?!0:!(e.unstable_now()-S<ne)}function C(){if(g=!1,x){var t=e.unstable_now();S=t;var i=!0;try{a:{m=!1,h&&(h=!1,v(te),te=-1),p=!0;var a=f;try{b:{for(b(t),d=n(c);d!==null&&!(d.expirationTime>t&&re());){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&&se(ee,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?ie():x=!1}}}var ie;if(typeof y==`function`)ie=function(){y(C)};else if(typeof MessageChannel<`u`){var ae=new MessageChannel,oe=ae.port2;ae.port1.onmessage=C,ie=function(){oe.postMessage(null)}}else ie=function(){_(C,0)};function se(t,n){te=_(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`):ne=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(te),te=-1):h=!0,se(ee,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,x||(x=!0,ie()))),r},e.unstable_shouldYield=re,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),n=e(((e,n)=>{n.exports=t()})),r=e((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`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.for(`react.view_transition`),m=Symbol.iterator;function h(e){return typeof e!=`object`||!e?null:(e=m&&e[m]||e[`@@iterator`],typeof e==`function`?e:null)}var g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,v={};function y(e,t,n){Line truncated
at`)?` (<anonymous>)`:-1<e.stack.indexOf(`@`)?`@unknown:0:0`:``}return`
`+ze+e+Be}var He=!1;function Ue(e,t){if(!e||He)return``;He=!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}n=!1;try{var i=Object.getOwnPropertyDescriptor(e.prototype,`props`);Object.defineProperty(e.prototype,"props",{configurable:!0,set:function(){throw Error()}}),n=!0,new e}finally{n&&(i===void 0?delete e.prototype.props:Object.defineProperty(e.prototype,"props",i))}}}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{He=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?Ve(n):``}function We(e,t){switch(e.tag){case 26:case 27:case 5:return Ve(e.type);case 16:return Ve(`Lazy`);case 13:return e.child!==t&&t!==null?Ve(`Suspense Fallback`):Ve(`Suspense`);case 19:return Ve(`SuspenseList`);case 0:case 15:return Ue(e.type,!1);case 11:return Ue(e.type.render,!1);case 1:return Ue(e.type,!0);case 31:return Ve(`Activity`);case 30:return Ve(`ViewTransition`);default:return``}}function Ge(e){try{var t=``,n=null;do t+=We(e,n),n=e,e=e.return;while(e);return t}catch(e){return`
Error generating stack: `+e.message+`
`+e.stack}}var Ke=Object.prototype.hasOwnProperty,qe=t.unstable_scheduleCallback,Je=t.unstable_cancelCallback,Ye=t.unstable_shouldYield,Xe=t.unstable_requestPaint,Ze=t.unstable_now,Qe=t.unstable_getCurrentPriorityLevel,$e=t.unstable_ImmediatePriority,et=t.unstable_UserBlockingPriority,tt=t.unstable_NormalPriority,nt=t.unstable_LowPriority,rt=t.unstable_IdlePriority,it=t.log,at=t.unstable_setDisableYieldValue,ot=null,st=null;function ct(e){if(typeof it==`function`&&at(e),st&&typeof st.setStrictMode==`function`)try{st.setStrictMode(ot,e)}catch{}}var lt=Math.clz32?Math.clz32:ft,ut=Math.log,dt=Math.LN2;function ft(e){return e>>>=0,e===0?32:31-(ut(e)/dt|0)|0}var pt=256,mt=262144,ht=4194304;function gt(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&-e;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 _t(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=gt(n))):i=gt(o):i=gt(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=gt(n))):i=gt(o)):i=gt(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 vt(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function yt(e,t){t&8&&(t|=t&32);var n=e.entangledLanes;if(n!==0)for(e=e.entanglements,n&=t;0<n;){var r=31-lt(n),i=1<<r;t|=e[r],n&=~i}return t}function bt(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 xt(){var e=ht;return ht<<=1,!(ht&62914560)&&(ht=4194304),e}function St(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Ct(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function wt(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-lt(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&&Tt(e,r,0),a!==0&&i===0&&e.tag!==0&&(e.suspendedLanes|=a&~(o&~t))}function Tt(e,t,n){e.pendingLanes|=t,e.suspendedLanes&=~t;var r=31-lt(t);e.entangledLanes|=t,e.entanglements[r]=e.entanglements[r]|1073741824|n&261930}function Et(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-lt(n),i=1<<r;i&t|e[r]&t&&(e[r]|=t),n&=~i}}function Dt(e,t){var n=t&-t;return n=n&42?1:Ot(n),(n&(e.suspendedLanes|t))===0?n:0}function Ot(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 kt(e){return e&=-e,2<e?8<e?e&134217727?32:268435456:8:2}function At(){var e=E.p;return e===0?(e=window.event,e===void 0?32:Ch(e.type)):e}function jt(e,t){var n=E.p;try{return E.p=e,t()}finally{E.p=n}}var Mt=Math.random().toString(36).slice(2),Nt=`__reactFiber$`+Mt,Pt=`__reactProps$`+Mt,Ft=`__reactContainer$`+Mt,It=`__reactEvents$`+Mt,Lt=`__reactListeners$`+Mt,Rt=`__reactHandles$`+Mt,zt=`__reactResources$`+Mt,Bt=`__reactMarker$`+Mt,Vt=`__reactLoad$`+Mt;function Ht(e){delete e[Nt],delete e[Pt],delete e[Lt],delete e[Rt]}function Ut(e){var t;if(t=e[Nt])return t;for(var n=e.parentNode;n;){if(t=n[Ft]||n[Nt]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=fm(e);e!==null;){if(n=e[Nt])return n;e=fm(e)}return t}e=n,n=e.parentNode}return null}function Wt(e){if(e=e[Nt]||e[Ft]){var t=e.tag;if(t===5||t===6||t===13||t===31||t===26||t===27||t===3)return e}return null}function Gt(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e.stateNode;throw Error(s(33))}function Kt(e){var t=e[zt];return t||=e[zt]={hoistableStyles:new Map,hoistableScripts:new Map},t}function qt(e){e[Bt]=!0}function Jt(e){e[Vt]=void 0}var Yt=new Set,Xt={};function Zt(e,t){Qt(e,t),Qt(e+`Capture`,t)}function Qt(e,t){for(Xt[e]=t,e=0;e<t.le Line truncated
`).replace(Qf,``)}function ep(e,t){return t=$f(t),$f(e)===t}function $(e,t,n,r,i,a){switch(n){case`children`:if(typeof r==`string`)t===`body`||t===`textarea`&&r===``||xn(e,r);else if(typeof r==`number`||typeof r==`bigint`)t!==`body`&&xn(e,``+r);else return;break;case`className`:on(e,`class`,r);break;case`tabIndex`:on(e,`tabindex`,r);break;case`dir`:case`role`:case`viewBox`:case`width`:case`height`:on(e,n,r);break;case`style`:wn(e,r,a);return;case`data`:if(t!==`object`){on(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=On(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}if(typeof a==`function`&&(n===`formAction`?(t!==`input`&&$(e,t,`name`,i.name,i,null),$(e,t,`formEncType`,i.formEncType,i,null),$(e,t,`formMethod`,i.formMethod,i,null),$(e,t,`formTarget`,i.formTarget,i,null)):($(e,t,`encType`,i.encType,i,null),$(e,t,`method`,i.method,i,null),$(e,t,`target`,i.target,i,null))),r==null||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=On(r),e.setAttribute(n,r);break;case`onClick`:r!=null&&(e.onclick=kn);return;case`onScroll`:r!=null&&Q(`scroll`,e);return;case`onScrollEnd`:r!=null&&Q(`scrollend`,e);return;case`dangerouslySetInnerHTML`:if(r!=null){if(typeof r!=`object`||!(`__html`in r))throw Error(s(61));if(n=r.__html,n!=null){if(i.children!=null)throw Error(s(60));a?.__html!==n&&(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=On(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`credentialless`: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),an(e,`popover`,r);break;case`xlinkActuate`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:actuate`,r);break;case`xlinkArcrole`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:arcrole`,r);break;case`xlinkRole`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:role`,r);break;case`xlinkShow`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:show`,r);break;case`xlinkTitle`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:title`,r);break;case`xlinkType`:sn(e,`http://www.w3.org/1999/xlink`,`xlink:type`,r);break;case`xmlBase`:sn(e,`http://www.w3.org/XML/1998/namespace`,`xml:base`,r);break;case`xmlLang`:sn(e,`http://www.w3.org/XML/1998/namespace`,`xml:lang`,r);break;case`xmlSpace`:sn(e,`http://www.w3.org/XML/1998/namespace`,`xml:space`,r);break;case`is`:an(e,`is`,r);break;case`innerText`:case`textContent`:return;default:if(!(2<n.length)||n[0]!==`o`&&n[0]!==`O`||n[1]!==`n`&&n[1]!==`N`)n=En.get(n)||n,an(e,n,r);else return}O=!0}function tp(e,t,n,r,i,a){switch(n){case`style`:wn(e,r,a);return;case`dangerouslySetInnerHTML`:if(r!=null){if(typeof r!=`object`||!(`__html`in r))throw Error(s(61));if(n=r.__html,n!=null){if(i.children!=null)throw Error(s(60));a?.__html!==n&&(e.innerHTML=n)}}break;case`children`:if(typeof r==`string`)xn(e,r);else if(typeof r==`number`||typeof r==`bigint`)xn(e,``+r);else return;break;case`onScroll`:r!=null&&Q(`scroll`,e);return;case`onScrollEnd`:r!=null&&Q(`scrollend`,e);return;case`onClick`:r!=null&&(e.onclick=k Line truncated
-1
View File
@@ -1 +0,0 @@
html,body,#root{box-sizing:border-box;-webkit-user-select:none;user-select:none;cursor:default;height:100%;margin:0;padding:0;overflow:hidden}body{color:#2e3436;background:#f6f5f4;font-family:Inter,ui-sans-serif,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif}button{font:inherit}.update-window{box-sizing:border-box;background:#f6f5f4;align-items:center;gap:15px;width:100%;height:100%;padding:16px 18px;display:flex}.update-logo{flex:none;width:48px;height:48px}.update-content,.update-status{width:100%;min-width:0}.update-title{color:#2e3436;letter-spacing:-.01em;margin:0;font-size:16px;font-weight:600;line-height:1.25}.update-description{color:#5e5c64;margin:3px 0 0;font-size:12px;line-height:1.4}.progress-summary{justify-content:space-between;align-items:baseline;gap:12px;margin-top:3px;display:flex}.progress-summary .update-description{margin:0}.progress-bar{background-color:#d5d3d1;border-radius:3px;width:100%;height:6px;margin-top:9px;position:relative;overflow:hidden}.progress-fill{background:#3584e4;border-radius:3px;height:100%;transition:width .18s ease-out}.progress-bar-indeterminate .progress-fill{width:35%;animation:1.4s ease-in-out infinite progress-indeterminate}@keyframes progress-indeterminate{0%{transform:translate(-110%)}to{transform:translate(300%)}}@media (prefers-reduced-motion:reduce){.progress-fill{transition:none}.progress-bar-indeterminate .progress-fill{animation:none;transform:translate(90%)}}.progress-label{color:#3d3846;font-variant-numeric:tabular-nums;text-align:right;white-space:nowrap;flex:none;font-size:12px;font-weight:500}.error-status{justify-content:space-between;align-items:center;gap:16px;display:flex}.error-status .update-title{color:#9c2f2f}.error-copy{min-width:0}.retry-button{color:#fff;cursor:pointer;background:#1c71d8;border:0;border-radius:8px;min-width:68px;padding:4px 14px;font-size:12px;font-weight:600;line-height:1.5}.retry-button:hover{background:#1a5fb4}.retry-button:active{background:#174a8b}.retry-button:focus-visible{outline-offset:2px;outline:2px solid #1a5fb4}
+188
View File
@@ -0,0 +1,188 @@
function dh(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const o in r)if(o!=="default"&&!(o in e)){const i=Object.getOwnPropertyDescriptor(r,o);i&&Object.defineProperty(e,o,i.get?i:{enumerable:!0,get:()=>r[o]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();function ph(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function sn(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var n=function r(){return this instanceof r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})}),n}var jf={exports:{}},Bi={},Ff={exports:{}},D={};/**
* @license React
* react.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 yo=Symbol.for("react.element"),mh=Symbol.for("react.portal"),hh=Symbol.for("react.fragment"),yh=Symbol.for("react.strict_mode"),gh=Symbol.for("react.profiler"),vh=Symbol.for("react.provider"),wh=Symbol.for("react.context"),xh=Symbol.for("react.forward_ref"),Sh=Symbol.for("react.suspense"),kh=Symbol.for("react.memo"),_h=Symbol.for("react.lazy"),Uu=Symbol.iterator;function Ch(e){return e===null||typeof e!="object"?null:(e=Uu&&e[Uu]||e["@@iterator"],typeof e=="function"?e:null)}var Wf={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Bf=Object.assign,Uf={};function fr(e,t,n){this.props=e,this.context=t,this.refs=Uf,this.updater=n||Wf}fr.prototype.isReactComponent={};fr.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};fr.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Vf(){}Vf.prototype=fr.prototype;function _s(e,t,n){this.props=e,this.context=t,this.refs=Uf,this.updater=n||Wf}var Cs=_s.prototype=new Vf;Cs.constructor=_s;Bf(Cs,fr.prototype);Cs.isPureReactComponent=!0;var Vu=Array.isArray,Hf=Object.prototype.hasOwnProperty,Es={current:null},Kf={key:!0,ref:!0,__self:!0,__source:!0};function Qf(e,t,n){var r,o={},i=null,l=null;if(t!=null)for(r in t.ref!==void 0&&(l=t.ref),t.key!==void 0&&(i=""+t.key),t)Hf.call(t,r)&&!Kf.hasOwnProperty(r)&&(o[r]=t[r]);var a=arguments.length-2;if(a===1)o.children=n;else if(1<a){for(var s=Array(a),u=0;u<a;u++)s[u]=arguments[u+2];o.children=s}if(e&&e.defaultProps)for(r in a=e.defaultProps,a)o[r]===void 0&&(o[r]=a[r]);return{$$typeof:yo,type:e,key:i,ref:l,props:o,_owner:Es.current}}function Eh(e,t){return{$$typeof:yo,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}function Ps(e){return typeof e=="object"&&e!==null&&e.$$typeof===yo}function Ph(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(n){return t[n]})}var Hu=/\/+/g;function Wl(e,t){return typeof e=="object"&&e!==null&&e.key!=null?Ph(""+e.key):t.toString(36)}function qo(e,t,n,r,o){var i=typeof e;(i==="undefined"||i==="boolean")&&(e=null);var l=!1;if(e===null)l=!0;else switch(i){case"string":case"number":l=!0;break;case"object":switch(e.$$typeof){case yo:case mh:l=!0}}if(l)return l=e,o=o(l),e=r===""?"."+Wl(l,0):r,Vu(o)?(n="",e!=null&&(n=e.replace(Hu,"$&/")+"/"),qo(o,t,n,"",function(u){return u})):o!=null&&(Ps(o)&&(o=Eh(o,n+(!o.key||l&&l.key===o.key?"":(""+o.key).replace(Hu,"$&/")+"/")+e)),t.push(o)),1;if(l=0,r=r===""?".":r+":",Vu(e))for(var a=0;a<e.length;a++){i=e[a];var s=r+Wl(i,a);l+=qo(i,t,n,s,o)}else if(s=Ch(e),typeof s=="function")for(e=s.call(e),a=0;!(i=e.next()).done;)i=i.value,s=r+Wl(i,a++),l+=qo(i,t,n,s,o);else if(i==="object")throw t=String(e),Error("Objects are not valid as a React child (found: "+(t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.");return l}function Ro(e,t,n){if(e==null)return e;var r=[],o=0;return qo(e,r,"","",function(i){return t.call(n,i,o++)}),r}function $h(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(n){(e._status===0||e._status===-1)&&(e._status=1,e._result=n)},function(n){(e._status===0||e._status===-1)&&(e._status=2,e._result=n)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var be={current:null},Zo={transition:null},Th={ReactCurrentDispatcher:be,ReactCurrentBatchConfig:Zo,ReactCurrentOwner:Es};function Gf(){throw Error("act(...) is not supported in production builds of React.")}D.Children={map:Ro,forEach:function(e,t,n){Ro(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return Ro(e,function(){t++}),t},toArray:function(e){return Ro(e,function(t){return t})||[]},only:function(e){if(!Ps(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};D.Component=fr;D.Fragment=hh;D.Profiler=gh;D.PureComponent=_s;D.StrictMode=yh;D.Suspense=Sh;D.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Th;D.act=Gf;D.cloneElement=function(e,t,n){if(e==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var r=Bf({},e.props),o=e.key,i=e.ref,l=e._owner;if(t!=null){if(t.ref!==void 0&&(i=t.ref,l=Es.current),t.key!==void 0&&(o=""+t.key),e.type&&e.type.defaultProps)var a=e.type.defaultProps;for(s in t)Hf.call(t,s)&&!Kf.hasOwnProperty(s)&&(r[s]=t[s]===void 0&&a!==void 0?a[s]:t[s])}var s=arguments.length-2;if(s===1)r.children=n;else if(1<s){a=Array(s);for(var u=0;u<s;u++)a[u]=arguments[u+2];r.children=a}return{$$typeof:yo,type:e.type,key:o,ref:i,props:r,_owner:l}};D.createContext=function(e){return e={$$typeof:wh,_currentValue:e,_currentValue2:e,_threadCount:0,ProviderLine truncated
* @license React
* react-jsx-runtime.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 Rh=C,Oh=Symbol.for("react.element"),Mh=Symbol.for("react.fragment"),bh=Object.prototype.hasOwnProperty,zh=Rh.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,Nh={key:!0,ref:!0,__self:!0,__source:!0};function Yf(e,t,n){var r,o={},i=null,l=null;n!==void 0&&(i=""+n),t.key!==void 0&&(i=""+t.key),t.ref!==void 0&&(l=t.ref);for(r in t)bh.call(t,r)&&!Nh.hasOwnProperty(r)&&(o[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps,t)o[r]===void 0&&(o[r]=t[r]);return{$$typeof:Oh,type:e,key:i,ref:l,props:o,_owner:zh.current}}Bi.Fragment=Mh;Bi.jsx=Yf;Bi.jsxs=Yf;jf.exports=Bi;var b=jf.exports,Xf={exports:{}},Ge={},qf={exports:{}},Zf={};/**
* @license React
* scheduler.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.
*/(function(e){function t(E,z){var N=E.length;E.push(z);e:for(;0<N;){var Z=N-1>>>1,ue=E[Z];if(0<o(ue,z))E[Z]=z,E[N]=ue,N=Z;else break e}}function n(E){return E.length===0?null:E[0]}function r(E){if(E.length===0)return null;var z=E[0],N=E.pop();if(N!==z){E[0]=N;e:for(var Z=0,ue=E.length,Tn=ue>>>1;Z<Tn;){var Te=2*(Z+1)-1,Bt=E[Te],ct=Te+1,Rn=E[ct];if(0>o(Bt,N))ct<ue&&0>o(Rn,Bt)?(E[Z]=Rn,E[ct]=N,Z=ct):(E[Z]=Bt,E[Te]=N,Z=Te);else if(ct<ue&&0>o(Rn,N))E[Z]=Rn,E[ct]=N,Z=ct;else break e}}return z}function o(E,z){var N=E.sortIndex-z.sortIndex;return N!==0?N:E.id-z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var l=Date,a=l.now();e.unstable_now=function(){return l.now()-a}}var s=[],u=[],p=1,m=null,d=3,v=!1,g=!1,y=!1,$=typeof setTimeout=="function"?setTimeout:null,f=typeof clearTimeout=="function"?clearTimeout:null,c=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function h(E){for(var z=n(u);z!==null;){if(z.callback===null)r(u);else if(z.startTime<=E)r(u),z.sortIndex=z.expirationTime,t(s,z);else break;z=n(u)}}function w(E){if(y=!1,h(E),!g)if(n(s)!==null)g=!0,$e(x);else{var z=n(u);z!==null&&Tt(w,z.startTime-E)}}function x(E,z){g=!1,y&&(y=!1,f(P),P=-1),v=!0;var N=d;try{for(h(z),m=n(s);m!==null&&(!(m.expirationTime>z)||E&&!W());){var Z=m.callback;if(typeof Z=="function"){m.callback=null,d=m.priorityLevel;var ue=Z(m.expirationTime<=z);z=e.unstable_now(),typeof ue=="function"?m.callback=ue:m===n(s)&&r(s),h(z)}else r(s);m=n(s)}if(m!==null)var Tn=!0;else{var Te=n(u);Te!==null&&Tt(w,Te.startTime-z),Tn=!1}return Tn}finally{m=null,d=N,v=!1}}var k=!1,S=null,P=-1,I=5,O=-1;function W(){return!(e.unstable_now()-O<I)}function H(){if(S!==null){var E=e.unstable_now();O=E;var z=!0;try{z=S(!0,E)}finally{z?se():(k=!1,S=null)}}else k=!1}var se;if(typeof c=="function")se=function(){c(H)};else if(typeof MessageChannel<"u"){var Se=new MessageChannel,ut=Se.port2;Se.port1.onmessage=H,se=function(){ut.postMessage(null)}}else se=function(){$(H,0)};function $e(E){S=E,k||(k=!0,se())}function Tt(E,z){P=$(function(){E(e.unstable_now())},z)}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_continueExecution=function(){g||v||(g=!0,$e(x))},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"):I=0<E?Math.floor(1e3/E):5},e.unstable_getCurrentPriorityLevel=function(){return d},e.unstable_getFirstCallbackNode=function(){return n(s)},e.unstable_next=function(E){switch(d){case 1:case 2:case 3:var z=3;break;default:z=d}var N=d;d=z;try{return E()}finally{d=N}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(E,z){switch(E){case 1:case 2:case 3:case 4:case 5:break;default:E=3}var N=d;d=E;try{return z()}finally{d=N}},e.unstable_scheduleCallback=function(E,z,N){var Z=e.unstable_now();switch(typeof N=="object"&&N!==null?(N=N.delay,N=typeof N=="number"&&0<N?Z+N:Z):N=Z,E){case 1:var ue=-1;break;case 2:ue=250;break;case 5:ue=1073741823;break;case 4:ue=1e4;break;default:ue=5e3}return ue=N+ue,E={id:p++,callback:z,priorityLevel:E,startTime:N,expirationTime:ue,sortIndex:-1},N>Z?(E.sortIndex=N,t(u,E),n(s)===null&&E===n(u)&&(y?(f(P),P=-1):y=!0,Tt(w,N-Z))):(E.sortIndex=ue,t(s,E),g||v||(g=!0,$e(x))),E},e.unstable_shouldYield=W,e.unstable_wrapCallback=function(E){var z=d;return function(){var N=d;d=z;try{return E.apply(this,arguments)}finally{d=N}}}})(Zf);qf.exports=Zf;var Lh=qf.exports;/**
* @license React
* react-dom.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 Ih=C,Qe=Lh;function _(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n<arguments.length;n++)t+="&args[]="+encodeURIComponent(arguments[n]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var Jf=new Set,Hr={};function En(e,t){rr(e,t),rr(e+"Capture",t)}function rr(e,t){for(Hr[e]=t,e=0;e<t.length;e++)Jf.add(t[e])}var It=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),va=Object.prototype.hasOwnProperty,Dh=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Qu={},Gu={};function Ah(e){return va.call(Gu,e)?!0:va.call(Qu,e)?!1:Dh.test(e)?Gu[e]=!0:(Qu[e]=!0,!1)}function jh(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Fh(e,t,n,r){if(t===null||typeof t>"u"||jh(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function ze(e,t,n,r,o,i,l){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=l}var xe={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){xe[e]=new ze(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];xe[t]=new ze(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){xe[e]=new ze(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){xe[e]=new ze(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){xe[e]=new ze(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){xe[e]=new ze(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){xe[e]=new ze(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){xe[e]=new ze(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){xe[e]=new ze(e,5,!1,e.toLowerCase(),null,!1,!1)});var $s=/[\-:]([a-z])/g;function Ts(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace($s,Ts);xe[t]=new ze(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace($s,Ts);xe[t]=new ze(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace($s,Ts);xe[t]=new ze(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){xe[e]=new ze(e,1,!1,e.toLowerCase(),null,!1,!1)});xe.xlinkHref=new ze("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){xe[e]=new ze(e,1,!1,e.toLowerCase(),null,!0,!0)});function Rs(e,t,n,r){var o=xe.hasOwnProperty(t)?xe[t]:null;(o!==null?o.type!==0:r||!(2<t.length)||t[0]!=="o"&&t[0]!==" Line truncated
`+Bl+e}var Ul=!1;function Vl(e,t){if(!e||Ul)return"";Ul=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t)if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(t,[])}catch(u){var r=u}Reflect.construct(e,[],t)}else{try{t.call()}catch(u){r=u}e.call(t.prototype)}else{try{throw Error()}catch(u){r=u}e()}}catch(u){if(u&&r&&typeof u.stack=="string"){for(var o=u.stack.split(`
`),i=r.stack.split(`
`),l=o.length-1,a=i.length-1;1<=l&&0<=a&&o[l]!==i[a];)a--;for(;1<=l&&0<=a;l--,a--)if(o[l]!==i[a]){if(l!==1||a!==1)do if(l--,a--,0>a||o[l]!==i[a]){var s=`
`+o[l].replace(" at new "," at ");return e.displayName&&s.includes("<anonymous>")&&(s=s.replace("<anonymous>",e.displayName)),s}while(1<=l&&0<=a);break}}}finally{Ul=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?Mr(e):""}function Wh(e){switch(e.tag){case 5:return Mr(e.type);case 16:return Mr("Lazy");case 13:return Mr("Suspense");case 19:return Mr("SuspenseList");case 0:case 2:case 15:return e=Vl(e.type,!1),e;case 11:return e=Vl(e.type.render,!1),e;case 1:return e=Vl(e.type,!0),e;default:return""}}function ka(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case An:return"Fragment";case Dn:return"Portal";case wa:return"Profiler";case Os:return"StrictMode";case xa:return"Suspense";case Sa:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case td:return(e.displayName||"Context")+".Consumer";case ed:return(e._context.displayName||"Context")+".Provider";case Ms:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case bs:return t=e.displayName||null,t!==null?t:ka(e.type)||"Memo";case Vt:t=e._payload,e=e._init;try{return ka(e(t))}catch{}}return null}function Bh(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ka(t);case 8:return t===Os?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function ln(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function rd(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Uh(e){var t=rd(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(l){r=""+l,i.call(this,l)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(l){r=""+l},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Mo(e){e._valueTracker||(e._valueTracker=Uh(e))}function od(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=rd(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function mi(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function _a(e,t){var n=t.checked;return te({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Xu(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=ln(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function id(e,t){t=t.checked,t!=null&&Rs(e,"checked",t,!1)}function Ca(e,t){id(e,t);var n=ln(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Ea(e,t.type,n):t.hasOwnProperty("defaultValue")&&Ea(e,t.type,ln(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function qu(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Ea(e,t,n){(t!=="number"||mi(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var br=Array.isArray;function Yn(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o<n.length;o++)t["$"+n[o]]=!0;for(n=0;n<e.length;n++)o=t.hasOwnProperty("$"+e[n].value),e[n].selected!==o&&(e[n].selected=o),o&&r&&(e[n].defaultSelected=!0)}else{for(n=""+ln(n),t=null,o=0;o<e.length;o++){if(e[o].value===n){e[o].selected=!0,r&&(e[o].defaultSelected=!0);return}t!==null||e[o].disabled||(t=e[o])}t!==null&&(t.selected=!0)}}function Pa(e,t){if(t.dan Line truncated
`).replace(J0,"")}function jo(e,t,n){if(t=xc(t),xc(e)!==t&&n)throw Error(_(425))}function ki(){}var ja=null,Fa=null;function Wa(e,t){return e==="textarea"||e==="noscript"||typeof t.children=="string"||typeof t.children=="number"||typeof t.dangerouslySetInnerHTML=="object"&&t.dangerouslySetInnerHTML!==null&&t.dangerouslySetInnerHTML.__html!=null}var Ba=typeof setTimeout=="function"?setTimeout:void 0,ey=typeof clearTimeout=="function"?clearTimeout:void 0,Sc=typeof Promise=="function"?Promise:void 0,ty=typeof queueMicrotask=="function"?queueMicrotask:typeof Sc<"u"?function(e){return Sc.resolve(null).then(e).catch(ny)}:Ba;function ny(e){setTimeout(function(){throw e})}function ra(e,t){var n=t,r=0;do{var o=n.nextSibling;if(e.removeChild(n),o&&o.nodeType===8)if(n=o.data,n==="/$"){if(r===0){e.removeChild(o),Xr(t);return}r--}else n!=="$"&&n!=="$?"&&n!=="$!"||r++;n=o}while(n);Xr(t)}function en(e){for(;e!=null;e=e.nextSibling){var t=e.nodeType;if(t===1||t===3)break;if(t===8){if(t=e.data,t==="$"||t==="$!"||t==="$?")break;if(t==="/$")return null}}return e}function kc(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var n=e.data;if(n==="$"||n==="$!"||n==="$?"){if(t===0)return e;t--}else n==="/$"&&t++}e=e.previousSibling}return null}var pr=Math.random().toString(36).slice(2),_t="__reactFiber$"+pr,to="__reactProps$"+pr,Dt="__reactContainer$"+pr,Ua="__reactEvents$"+pr,ry="__reactListeners$"+pr,oy="__reactHandles$"+pr;function mn(e){var t=e[_t];if(t)return t;for(var n=e.parentNode;n;){if(t=n[Dt]||n[_t]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=kc(e);e!==null;){if(n=e[_t])return n;e=kc(e)}return t}e=n,n=e.parentNode}return null}function wo(e){return e=e[_t]||e[Dt],!e||e.tag!==5&&e.tag!==6&&e.tag!==13&&e.tag!==3?null:e}function Bn(e){if(e.tag===5||e.tag===6)return e.stateNode;throw Error(_(33))}function Qi(e){return e[to]||null}var Va=[],Un=-1;function cn(e){return{current:e}}function Y(e){0>Un||(e.current=Va[Un],Va[Un]=null,Un--)}function K(e,t){Un++,Va[Un]=e.current,e.current=t}var an={},Pe=cn(an),Ie=cn(!1),xn=an;function or(e,t){var n=e.type.contextTypes;if(!n)return an;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function De(e){return e=e.childContextTypes,e!=null}function _i(){Y(Ie),Y(Pe)}function _c(e,t,n){if(Pe.current!==an)throw Error(_(168));K(Pe,t),K(Ie,n)}function Qd(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(_(108,Bh(e)||"Unknown",o));return te({},n,r)}function Ci(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||an,xn=Pe.current,K(Pe,e),K(Ie,Ie.current),!0}function Cc(e,t,n){var r=e.stateNode;if(!r)throw Error(_(169));n?(e=Qd(e,t,xn),r.__reactInternalMemoizedMergedChildContext=e,Y(Ie),Y(Pe),K(Pe,e)):Y(Ie),K(Ie,n)}var Mt=null,Gi=!1,oa=!1;function Gd(e){Mt===null?Mt=[e]:Mt.push(e)}function iy(e){Gi=!0,Gd(e)}function fn(){if(!oa&&Mt!==null){oa=!0;var e=0,t=B;try{var n=Mt;for(B=1;e<n.length;e++){var r=n[e];do r=r(!0);while(r!==null)}Mt=null,Gi=!1}catch(o){throw Mt!==null&&(Mt=Mt.slice(e+1)),wd(Ns,fn),o}finally{B=t,oa=!1}}return null}var Vn=[],Hn=0,Ei=null,Pi=0,Je=[],et=0,Sn=null,bt=1,zt="";function dn(e,t){Vn[Hn++]=Pi,Vn[Hn++]=Ei,Ei=e,Pi=t}function Yd(e,t,n){Je[et++]=bt,Je[et++]=zt,Je[et++]=Sn,Sn=e;var r=bt;e=zt;var o=32-ht(r)-1;r&=~(1<<o),n+=1;var i=32-ht(t)+o;if(30<i){var l=o-o%5;i=(r&(1<<l)-1).toString(32),r>>=l,o-=l,bt=1<<32-ht(t)+o|n<<o|r,zt=i+e}else bt=1<<i|n<<o|r,zt=e}function Us(e){e.return!==null&&(dn(e,1),Yd(e,1,0))}function Vs(e){for(;e===Ei;)Ei=Vn[--Hn],Vn[Hn]=null,Pi=Vn[--Hn],Vn[Hn]=null;for(;e===Sn;)Sn=Je[--et],Je[et]=null,zt=Je[--et],Je[et]=null,bt=Je[--et],Je[et]=null}var He=null,Ve=null,q=!1,mt=null;function Xd(e,t){var n=nt(5,null,null,0);n.elementType="DELETED",n.stateNode=t,n.return=e,t=e.deletions,t===null?(e.deletions=[n],e.flags|=16):t.push(n)}function Ec(e,t){switch(e.tag){case 5:var n=e.type;return t=t.nodeType!==1||n.toLowerCase()!==t.nodeName.toLowerCase()?null:t,t!==null?(e.stateNode=t,He=e,Ve=en(t.firstChild),!0):!1;case 6:return t=e.pendingProps===""||t.nodeType!==3?null:t,t!==null?(e.stateNode=t,He=e,Ve=null,!0):!1;case 13:return t=t.nodeType!==8?null:t,t!==null?(n=Sn!==null?{id:bt,overflow:zt}:null,e.memoizedState={dehydrated:t,treeContext:n,retryLane:1073741824},n=nt(18,null,null,0),n.stateNode=t,n.return=e,e.child=n,He=e,Ve=null,!0):!1;default:return!1}}function Ha(e){return(e.mode&1)!==0&&(e.flags&128)===0}function Ka(e){if(q){var t=Ve;if(t){var n=t;if(!Ec(e,t)){if(Ha(e))throw Error(_(418));t=en(n.nextSibling);var r=He;t&&Ec(e,t)?Xd(r,n):(e.flags=e.flags&-4097|2,q=!1,He=e)}}else{if(Ha(e))throw Error(_(418));e.flags=e.flags&-4097|2,q=!1,He=e}}}function Pc(e){for(e=e.return;e!==null&&e. Line truncated
Error generating stack: `+i.message+`
`+i.stack}return{value:e,source:t,stack:o,digest:null}}function ua(e,t,n){return{value:e,source:null,stack:n??null,digest:t??null}}function Xa(e,t){try{console.error(t.value)}catch(n){setTimeout(function(){throw n})}}var my=typeof WeakMap=="function"?WeakMap:Map;function _p(e,t,n){n=Lt(-1,n),n.tag=3,n.payload={element:null};var r=t.value;return n.callback=function(){Ni||(Ni=!0,ls=r),Xa(e,t)},n}function Cp(e,t,n){n=Lt(-1,n),n.tag=3;var r=e.type.getDerivedStateFromError;if(typeof r=="function"){var o=t.value;n.payload=function(){return r(o)},n.callback=function(){Xa(e,t)}}var i=e.stateNode;return i!==null&&typeof i.componentDidCatch=="function"&&(n.callback=function(){Xa(e,t),typeof r!="function"&&(nn===null?nn=new Set([this]):nn.add(this));var l=t.stack;this.componentDidCatch(t.value,{componentStack:l!==null?l:""})}),n}function Nc(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new my;var o=new Set;r.set(t,o)}else o=r.get(t),o===void 0&&(o=new Set,r.set(t,o));o.has(n)||(o.add(n),e=Ty.bind(null,e,t,n),t.then(e,e))}function Lc(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t!==null?t.dehydrated!==null:!0),t)return e;e=e.return}while(e!==null);return null}function Ic(e,t,n,r,o){return e.mode&1?(e.flags|=65536,e.lanes=o,e):(e===t?e.flags|=65536:(e.flags|=128,n.flags|=131072,n.flags&=-52805,n.tag===1&&(n.alternate===null?n.tag=17:(t=Lt(-1,1),t.tag=2,tn(n,t,1))),n.lanes|=1),e)}var hy=Wt.ReactCurrentOwner,Le=!1;function Re(e,t,n,r){t.child=e===null?Jd(t,null,n,r):lr(t,e.child,n,r)}function Dc(e,t,n,r,o){n=n.render;var i=t.ref;return Jn(t,o),r=tu(e,t,n,r,i,o),n=nu(),e!==null&&!Le?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~o,jt(e,t,o)):(q&&n&&Us(t),t.flags|=1,Re(e,t,r,o),t.child)}function Ac(e,t,n,r,o){if(e===null){var i=n.type;return typeof i=="function"&&!du(i)&&i.defaultProps===void 0&&n.compare===null&&n.defaultProps===void 0?(t.tag=15,t.type=i,Ep(e,t,i,r,o)):(e=si(n.type,null,r,t,t.mode,o),e.ref=t.ref,e.return=t,t.child=e)}if(i=e.child,!(e.lanes&o)){var l=i.memoizedProps;if(n=n.compare,n=n!==null?n:Zr,n(l,r)&&e.ref===t.ref)return jt(e,t,o)}return t.flags|=1,e=on(i,r),e.ref=t.ref,e.return=t,t.child=e}function Ep(e,t,n,r,o){if(e!==null){var i=e.memoizedProps;if(Zr(i,r)&&e.ref===t.ref)if(Le=!1,t.pendingProps=r=i,(e.lanes&o)!==0)e.flags&131072&&(Le=!0);else return t.lanes=e.lanes,jt(e,t,o)}return qa(e,t,n,r,o)}function Pp(e,t,n){var r=t.pendingProps,o=r.children,i=e!==null?e.memoizedState:null;if(r.mode==="hidden")if(!(t.mode&1))t.memoizedState={baseLanes:0,cachePool:null,transitions:null},K(Gn,Be),Be|=n;else{if(!(n&1073741824))return e=i!==null?i.baseLanes|n:n,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,K(Gn,Be),Be|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=i!==null?i.baseLanes:n,K(Gn,Be),Be|=r}else i!==null?(r=i.baseLanes|n,t.memoizedState=null):r=n,K(Gn,Be),Be|=r;return Re(e,t,o,n),t.child}function $p(e,t){var n=t.ref;(e===null&&n!==null||e!==null&&e.ref!==n)&&(t.flags|=512,t.flags|=2097152)}function qa(e,t,n,r,o){var i=De(n)?xn:Pe.current;return i=or(t,i),Jn(t,o),n=tu(e,t,n,r,i,o),r=nu(),e!==null&&!Le?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~o,jt(e,t,o)):(q&&r&&Us(t),t.flags|=1,Re(e,t,n,o),t.child)}function jc(e,t,n,r,o){if(De(n)){var i=!0;Ci(t)}else i=!1;if(Jn(t,o),t.stateNode===null)ii(e,t),kp(t,n,r),Ya(t,n,r,o),r=!0;else if(e===null){var l=t.stateNode,a=t.memoizedProps;l.props=a;var s=l.context,u=n.contextType;typeof u=="object"&&u!==null?u=ot(u):(u=De(n)?xn:Pe.current,u=or(t,u));var p=n.getDerivedStateFromProps,m=typeof p=="function"||typeof l.getSnapshotBeforeUpdate=="function";m||typeof l.UNSAFE_componentWillReceiveProps!="function"&&typeof l.componentWillReceiveProps!="function"||(a!==r||s!==u)&&zc(t,l,r,u),Ht=!1;var d=t.memoizedState;l.state=d,Ri(t,r,l,o),s=t.memoizedState,a!==r||d!==s||Ie.current||Ht?(typeof p=="function"&&(Ga(t,n,p,r),s=t.memoizedState),(a=Ht||bc(t,n,a,r,d,s,u))?(m||typeof l.UNSAFE_componentWillMount!="function"&&typeof l.componentWillMount!="function"||(typeof l.componentWillMount=="function"&&l.componentWillMount(),typeof l.UNSAFE_componentWillMount=="function"&&l.UNSAFE_componentWillMount()),typeof l.componentDidMount=="function"&&(t.flags|=4194308)):(typeof l.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=r,t.memoizedState=s),l.props=r,l.state=s,l.context=u,r=a):(typeof l.componentDidMount=="function"&&(t.flags|=4194308),r=!1)}else{l=t.stateNode,tp(e,t),a=t.memoizedProps,u=t.type===t.elementType?a:dt(t.type,a),l.props=u,m=t.pendingProps,d=l.context,s=n.contextType,typeof s=="object"&&s!==null?s=ot(s):(s=De(n)?xn:Pe.current,s=or(t,s));var v=n.getDerivedStateFromProps;(p=typeof v=="function"||typeof l.getSnapshotBeforeUpdate=="function")||typeof l.UNSAFE_componentWillReceiveProps!="function"&&typeof l.componentWillReceiveProps!="function"||(a!==m||d!==s)&&zc(t,l,r,s),Ht=!1,d=t.memoizedState,l.state=d,Ri(t,r,l,o);var g=t.memoizedState;a 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 ye=typeof Symbol=="function"&&Symbol.for,Su=ye?Symbol.for("react.element"):60103,ku=ye?Symbol.for("react.portal"):60106,al=ye?Symbol.for("react.fragment"):60107,sl=ye?Symbol.for("react.strict_mode"):60108,ul=ye?Symbol.for("react.profiler"):60114,cl=ye?Symbol.for("react.provider"):60109,fl=ye?Symbol.for("react.context"):60110,_u=ye?Symbol.for("react.async_mode"):60111,dl=ye?Symbol.for("react.concurrent_mode"):60111,pl=ye?Symbol.for("react.forward_ref"):60112,ml=ye?Symbol.for("react.suspense"):60113,$g=ye?Symbol.for("react.suspense_list"):60120,hl=ye?Symbol.for("react.memo"):60115,yl=ye?Symbol.for("react.lazy"):60116,Tg=ye?Symbol.for("react.block"):60121,Rg=ye?Symbol.for("react.fundamental"):60117,Og=ye?Symbol.for("react.responder"):60118,Mg=ye?Symbol.for("react.scope"):60119;function Xe(e){if(typeof e=="object"&&e!==null){var t=e.$$typeof;switch(t){case Su:switch(e=e.type,e){case _u:case dl:case al:case ul:case sl:case ml:return e;default:switch(e=e&&e.$$typeof,e){case fl:case pl:case yl:case hl:case cl:return e;default:return t}}case ku:return t}}}function sm(e){return Xe(e)===dl}U.AsyncMode=_u;U.ConcurrentMode=dl;U.ContextConsumer=fl;U.ContextProvider=cl;U.Element=Su;U.ForwardRef=pl;U.Fragment=al;U.Lazy=yl;U.Memo=hl;U.Portal=ku;U.Profiler=ul;U.StrictMode=sl;U.Suspense=ml;U.isAsyncMode=function(e){return sm(e)||Xe(e)===_u};U.isConcurrentMode=sm;U.isContextConsumer=function(e){return Xe(e)===fl};U.isContextProvider=function(e){return Xe(e)===cl};U.isElement=function(e){return typeof e=="object"&&e!==null&&e.$$typeof===Su};U.isForwardRef=function(e){return Xe(e)===pl};U.isFragment=function(e){return Xe(e)===al};U.isLazy=function(e){return Xe(e)===yl};U.isMemo=function(e){return Xe(e)===hl};U.isPortal=function(e){return Xe(e)===ku};U.isProfiler=function(e){return Xe(e)===ul};U.isStrictMode=function(e){return Xe(e)===sl};U.isSuspense=function(e){return Xe(e)===ml};U.isValidElementType=function(e){return typeof e=="string"||typeof e=="function"||e===al||e===dl||e===ul||e===sl||e===ml||e===$g||typeof e=="object"&&e!==null&&(e.$$typeof===yl||e.$$typeof===hl||e.$$typeof===cl||e.$$typeof===fl||e.$$typeof===pl||e.$$typeof===Rg||e.$$typeof===Og||e.$$typeof===Mg||e.$$typeof===Tg)};U.typeOf=Xe;am.exports=U;var bg=am.exports,um=bg,zg={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},Ng={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},cm={};cm[um.ForwardRef]=zg;cm[um.Memo]=Ng;var Lg=!0;function Ig(e,t,n){var r="";return n.split(" ").forEach(function(o){e[o]!==void 0?t.push(e[o]+";"):r+=o+" "}),r}var fm=function(t,n,r){var o=t.key+"-"+n.name;(r===!1||Lg===!1)&&t.registered[o]===void 0&&(t.registered[o]=n.styles)},dm=function(t,n,r){fm(t,n,r);var o=t.key+"-"+n.name;if(t.inserted[n.name]===void 0){var i=n;do t.insert(n===i?"."+o:"",i,t.sheet,!0),i=i.next;while(i!==void 0)}};function Dg(e){for(var t=0,n,r=0,o=e.length;o>=4;++r,o-=4)n=e.charCodeAt(r)&255|(e.charCodeAt(++r)&255)<<8|(e.charCodeAt(++r)&255)<<16|(e.charCodeAt(++r)&255)<<24,n=(n&65535)*1540483477+((n>>>16)*59797<<16),n^=n>>>24,t=(n&65535)*1540483477+((n>>>16)*59797<<16)^(t&65535)*1540483477+((t>>>16)*59797<<16);switch(o){case 3:t^=(e.charCodeAt(r+2)&255)<<16;case 2:t^=(e.charCodeAt(r+1)&255)<<8;case 1:t^=e.charCodeAt(r)&255,t=(t&65535)*1540483477+((t>>>16)*59797<<16)}return t^=t>>>13,t=(t&65535)*1540483477+((t>>>16)*59797<<16),((t^t>>>15)>>>0).toString(36)}var Ag={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,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},jg=!1,Fg=/[A-Z]|^ms/g,Wg=/_EMO_([^_]+?)_([^]*?)_EMO_/g,pm=function(t){return t.charCodeAt(1)===45},nf=function(t){return t!=null&&typeof t!="boolean"},pa=Zp(function(e){return pm(e)?e:e.replace(Fg,"-$&").toLowerCase()}),rf=function(t,n){switch(t){case"animation":case"animationName":if(typeof n=="string")return n.replace(Wg,function(r,o,i){return kt={name:o,styles:i,next:kt},o})}return Ag[t]!==1&&!pm(t)&&typeof n=="number"&&n!==0?n+"px":n},Bg="Component selectors can only be used in conjunction with @emotion/babel-plugin, the swc Emotion plugin, or another Emotion-aware compiler transform.";function po(e,t,n){if(n==null)return"";var r=n;if(r.__emotion_styles!==void 0)return r;switch(typeof n){case"boolean":return"";case"object":{var o=n;if(o.anim===1)return kt={name:o.name,styles:o.styles,next:kt},o.name;var i=n;if(i.styles!==void 0){var l=i.next;if(l!==void 0)for(;l!==void 0;)kt={name:l.name,styles:l.styles,nextLine truncated
* @mui/styled-engine v5.16.6
*
* @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 vm(e,t){return ds(e,t)}const n1=(e,t)=>{Array.isArray(e.__emotion_styles)&&(e.__emotion_styles=t(e.__emotion_styles))},r1=Object.freeze(Object.defineProperty({__proto__:null,GlobalStyles:gm,StyledEngineProvider:e1,ThemeContext:gl,css:ko,default:vm,internal_processStyles:n1,keyframes:$n},Symbol.toStringTag,{value:"Module"}));function Gt(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function wm(e){if(!Gt(e))return e;const t={};return Object.keys(e).forEach(n=>{t[n]=wm(e[n])}),t}function $t(e,t,n={clone:!0}){const r=n.clone?R({},e):e;return Gt(e)&&Gt(t)&&Object.keys(t).forEach(o=>{Gt(t[o])&&Object.prototype.hasOwnProperty.call(e,o)&&Gt(e[o])?r[o]=$t(e[o],t[o],n):n.clone?r[o]=Gt(t[o])?wm(t[o]):t[o]:r[o]=t[o]}),r}const o1=Object.freeze(Object.defineProperty({__proto__:null,default:$t,isPlainObject:Gt},Symbol.toStringTag,{value:"Module"})),i1=["values","unit","step"],l1=e=>{const t=Object.keys(e).map(n=>({key:n,val:e[n]}))||[];return t.sort((n,r)=>n.val-r.val),t.reduce((n,r)=>R({},n,{[r.key]:r.val}),{})};function xm(e){const{values:t={xs:0,sm:600,md:900,lg:1200,xl:1536},unit:n="px",step:r=5}=e,o=Fe(e,i1),i=l1(t),l=Object.keys(i);function a(d){return`@media (min-width:${typeof t[d]=="number"?t[d]:d}${n})`}function s(d){return`@media (max-width:${(typeof t[d]=="number"?t[d]:d)-r/100}${n})`}function u(d,v){const g=l.indexOf(v);return`@media (min-width:${typeof t[d]=="number"?t[d]:d}${n}) and (max-width:${(g!==-1&&typeof t[l[g]]=="number"?t[l[g]]:v)-r/100}${n})`}function p(d){return l.indexOf(d)+1<l.length?u(d,l[l.indexOf(d)+1]):a(d)}function m(d){const v=l.indexOf(d);return v===0?a(l[1]):v===l.length-1?s(l[v]):u(d,l[l.indexOf(d)+1]).replace("@media","@media not all and")}return R({keys:l,values:i,up:a,down:s,between:u,only:p,not:m,unit:n},o)}const a1={borderRadius:4},s1=a1;function Vr(e,t){return t?$t(e,t,{clone:!1}):e}const Eu={xs:0,sm:600,md:900,lg:1200,xl:1536},uf={keys:["xs","sm","md","lg","xl"],up:e=>`@media (min-width:${Eu[e]}px)`};function Ft(e,t,n){const r=e.theme||{};if(Array.isArray(t)){const i=r.breakpoints||uf;return t.reduce((l,a,s)=>(l[i.up(i.keys[s])]=n(t[s]),l),{})}if(typeof t=="object"){const i=r.breakpoints||uf;return Object.keys(t).reduce((l,a)=>{if(Object.keys(i.values||Eu).indexOf(a)!==-1){const s=i.up(a);l[s]=n(t[a],a)}else{const s=a;l[s]=t[s]}return l},{})}return n(t)}function u1(e={}){var t;return((t=e.keys)==null?void 0:t.reduce((r,o)=>{const i=e.up(o);return r[i]={},r},{}))||{}}function c1(e,t){return e.reduce((n,r)=>{const o=n[r];return(!o||Object.keys(o).length===0)&&delete n[r],n},t)}function G(e){if(typeof e!="string")throw new Error(uo(7));return e.charAt(0).toUpperCase()+e.slice(1)}const f1=Object.freeze(Object.defineProperty({__proto__:null,default:G},Symbol.toStringTag,{value:"Module"}));function vl(e,t,n=!0){if(!t||typeof t!="string")return null;if(e&&e.vars&&n){const r=`vars.${t}`.split(".").reduce((o,i)=>o&&o[i]?o[i]:null,e);if(r!=null)return r}return t.split(".").reduce((r,o)=>r&&r[o]!=null?r[o]:null,e)}function ji(e,t,n,r=n){let o;return typeof e=="function"?o=e(n):Array.isArray(e)?o=e[n]||r:o=vl(e,n)||r,t&&(o=t(o,r,e)),o}function le(e){const{prop:t,cssProperty:n=e.prop,themeKey:r,transform:o}=e,i=l=>{if(l[t]==null)return null;const a=l[t],s=l.theme,u=vl(s,r)||{};return Ft(l,a,m=>{let d=ji(u,o,m);return m===d&&typeof m=="string"&&(d=ji(u,o,`${t}${m==="default"?"":G(m)}`,m)),n===!1?d:{[n]:d}})};return i.propTypes={},i.filterProps=[t],i}function d1(e){const t={};return n=>(t[n]===void 0&&(t[n]=e(n)),t[n])}const p1={m:"margin",p:"padding"},m1={t:"Top",r:"Right",b:"Bottom",l:"Left",x:["Left","Right"],y:["Top","Bottom"]},cf={marginX:"mx",marginY:"my",paddingX:"px",paddingY:"py"},h1=d1(e=>{if(e.length>2)if(cf[e])e=cf[e];else return[e];const[t,n]=e.split(""),r=p1[t],o=m1[n]||"";return Array.isArray(o)?o.map(i=>r+i):[r+o]}),Pu=["m","mt","mr","mb","ml","mx","my","margin","marginTop","marginRight","marginBottom","marginLeft","marginX","marginY","marginInline","marginInlineStart","marginInlineEnd","marginBlock","marginBlockStart","marginBlockEnd"],$u=["p","pt","pr","pb","pl","px","py","padding","paddingTop","paddingRight","paddingBottom","paddingLeft","paddingX","paddingY","paddingInline","paddingInlineStart","paddingInlineEnd","paddingBlock","paddingBlockStart","paddingBlockEnd"];[...Pu,...$u];function _o(e,t,n,r){var o;const i=(o=vl(e,t,!1))!=null?o:n;return typeof i=="number"?l=>typeof l=="string"?l:i*l:Array.isArray(i)?l=>typeof l=="string"?l:i[l]:typeof i=="function"?i:()=>{}}function Sm(e){return _o(e,"spacing",8)}function Co(e,t){if(typeof t=="string"||t==null)return t;const n=Math.abs(t),r=e(n);return t>=0?r:typeof r=="number"?-r:`-${r}`}function y1(e,t){return n=>e.reduce((r,o)=>(r[o]=Co(t,n),r),{})}function g1(e,t,n,r){if(t.indexOf(n)===-1)return null;const o=h1(n),i=y1(o,r),l=e[n];return Ft(e,l,i)}function km(e,Line truncated
* @license React
* 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 Mu=Symbol.for("react.element"),bu=Symbol.for("react.portal"),El=Symbol.for("react.fragment"),Pl=Symbol.for("react.strict_mode"),$l=Symbol.for("react.profiler"),Tl=Symbol.for("react.provider"),Rl=Symbol.for("react.context"),dv=Symbol.for("react.server_context"),Ol=Symbol.for("react.forward_ref"),Ml=Symbol.for("react.suspense"),bl=Symbol.for("react.suspense_list"),zl=Symbol.for("react.memo"),Nl=Symbol.for("react.lazy"),pv=Symbol.for("react.offscreen"),Om;Om=Symbol.for("react.module.reference");function st(e){if(typeof e=="object"&&e!==null){var t=e.$$typeof;switch(t){case Mu:switch(e=e.type,e){case El:case $l:case Pl:case Ml:case bl:return e;default:switch(e=e&&e.$$typeof,e){case dv:case Rl:case Ol:case Nl:case zl:case Tl:return e;default:return t}}case bu:return t}}}V.ContextConsumer=Rl;V.ContextProvider=Tl;V.Element=Mu;V.ForwardRef=Ol;V.Fragment=El;V.Lazy=Nl;V.Memo=zl;V.Portal=bu;V.Profiler=$l;V.StrictMode=Pl;V.Suspense=Ml;V.SuspenseList=bl;V.isAsyncMode=function(){return!1};V.isConcurrentMode=function(){return!1};V.isContextConsumer=function(e){return st(e)===Rl};V.isContextProvider=function(e){return st(e)===Tl};V.isElement=function(e){return typeof e=="object"&&e!==null&&e.$$typeof===Mu};V.isForwardRef=function(e){return st(e)===Ol};V.isFragment=function(e){return st(e)===El};V.isLazy=function(e){return st(e)===Nl};V.isMemo=function(e){return st(e)===zl};V.isPortal=function(e){return st(e)===bu};V.isProfiler=function(e){return st(e)===$l};V.isStrictMode=function(e){return st(e)===Pl};V.isSuspense=function(e){return st(e)===Ml};V.isSuspenseList=function(e){return st(e)===bl};V.isValidElementType=function(e){return typeof e=="string"||typeof e=="function"||e===El||e===$l||e===Pl||e===Ml||e===bl||e===pv||typeof e=="object"&&e!==null&&(e.$$typeof===Nl||e.$$typeof===zl||e.$$typeof===Tl||e.$$typeof===Rl||e.$$typeof===Ol||e.$$typeof===Om||e.getModuleId!==void 0)};V.typeOf=st;Rm.exports=V;var df=Rm.exports;const mv=/^\s*function(?:\s|\s*\/\*.*\*\/\s*)+([^(\s/]*)\s*/;function Mm(e){const t=`${e}`.match(mv);return t&&t[1]||""}function bm(e,t=""){return e.displayName||e.name||Mm(e)||t}function pf(e,t,n){const r=bm(t);return e.displayName||(r!==""?`${n}(${r})`:n)}function hv(e){if(e!=null){if(typeof e=="string")return e;if(typeof e=="function")return bm(e,"Component");if(typeof e=="object")switch(e.$$typeof){case df.ForwardRef:return pf(e,e.render,"ForwardRef");case df.Memo:return pf(e,e.type,"memo");default:return}}}const yv=Object.freeze(Object.defineProperty({__proto__:null,default:hv,getFunctionName:Mm},Symbol.toStringTag,{value:"Module"}));function Fi(e,t){const n=R({},t);return Object.keys(e).forEach(r=>{if(r.toString().match(/^(components|slots)$/))n[r]=R({},e[r],n[r]);else if(r.toString().match(/^(componentsProps|slotProps)$/)){const o=e[r]||{},i=t[r];n[r]={},!i||!Object.keys(i)?n[r]=o:!o||!Object.keys(o)?n[r]=i:(n[r]=R({},i),Object.keys(o).forEach(l=>{n[r][l]=Fi(o[l],i[l])}))}else n[r]===void 0&&(n[r]=e[r])}),n}const gv=typeof window<"u"?C.useLayoutEffect:C.useEffect,vv=gv;function wv(e,t=Number.MIN_SAFE_INTEGER,n=Number.MAX_SAFE_INTEGER){return Math.max(t,Math.min(e,n))}const xv=Object.freeze(Object.defineProperty({__proto__:null,default:wv},Symbol.toStringTag,{value:"Module"}));function Sv(e,t){typeof e=="function"?e(t):e&&(e.current=t)}function Qo(e){const t=C.useRef(e);return vv(()=>{t.current=e}),C.useRef((...n)=>(0,t.current)(...n)).current}function mf(...e){return C.useMemo(()=>e.every(t=>t==null)?null:t=>{e.forEach(n=>{Sv(n,t)})},e)}const hf={};function kv(e,t){const n=C.useRef(hf);return n.current===hf&&(n.current=e(t)),n}const _v=[];function Cv(e){C.useEffect(e,_v)}class Ll{constructor(){this.currentId=null,this.clear=()=>{this.currentId!==null&&(clearTimeout(this.currentId),this.currentId=null)},this.disposeEffect=()=>this.clear}static create(){return new Ll}start(t,n){this.clear(),this.currentId=setTimeout(()=>{this.currentId=null,n()},t)}}function Ev(){const e=kv(Ll.create).current;return Cv(e.disposeEffect),e}let Il=!0,ms=!1;const Pv=new Ll,$v={text:!0,search:!0,url:!0,tel:!0,email:!0,password:!0,number:!0,date:!0,month:!0,week:!0,time:!0,datetime:!0,"datetime-local":!0};function Tv(e){const{type:t,tagName:n}=e;return!!(n==="INPUT"&&$v[t]&&!e.readOnly||n==="TEXTAREA"&&!e.readOnly||e.isContentEditable)}function Rv(e){e.metaKey||e.altKey||e.ctrlKey||(Il=!0)}function ma(){Il=!1}function Ov(){this.visibilityState==="hidden"&&ms&&(Il=!0)}function Mv(e){e.addEventListener("keydown",Rv,!0),e.addEventListener("mousedown",ma,!0),e.addEventListener("pointerdown",ma,!0),e.addEventListener("touchstart",ma,!0),e.addEventListener("visibilitychange",Ov,!0)}function bv(e){const{target:t}=e;try{return t.matches(":focus-visible")}catch{}return Il||Tv(t)}function zv(){const e=C.useCallback(o=>{o!=null&&Mv(o.ownerDocument)},[]),t=C.useRef(!1);function n(){return t.current?(ms=!0,Pv.start(100,()=>{ms=!1}),t.current=!1,!0):!1}function r(o){return bv(o)?(t.current=!0,!0):!1}return{isFocusVisibleRef:t,onFocusLine truncated
0% {
transform: scale(0);
opacity: 0.1;
}
100% {
transform: scale(1);
opacity: 0.3;
}
`)),sx=$n($f||($f=Al`
0% {
opacity: 1;
}
100% {
opacity: 0;
}
`)),ux=$n(Tf||(Tf=Al`
0% {
transform: scale(1);
}
50% {
transform: scale(0.92);
}
100% {
transform: scale(1);
}
`)),cx=vt("span",{name:"MuiTouchRipple",slot:"Root"})({overflow:"hidden",pointerEvents:"none",position:"absolute",zIndex:0,top:0,right:0,bottom:0,left:0,borderRadius:"inherit"}),fx=vt(rx,{name:"MuiTouchRipple",slot:"Ripple"})(Rf||(Rf=Al`
opacity: 0;
position: absolute;
&.${0} {
opacity: 0.3;
transform: scale(1);
animation-name: ${0};
animation-duration: ${0}ms;
animation-timing-function: ${0};
}
&.${0} {
animation-duration: ${0}ms;
}
& .${0} {
opacity: 1;
display: block;
width: 100%;
height: 100%;
border-radius: 50%;
background-color: currentColor;
}
& .${0} {
opacity: 0;
animation-name: ${0};
animation-duration: ${0}ms;
animation-timing-function: ${0};
}
& .${0} {
position: absolute;
/* @noflip */
left: 0px;
top: 0;
animation-name: ${0};
animation-duration: 2500ms;
animation-timing-function: ${0};
animation-iteration-count: infinite;
animation-delay: 200ms;
}
`),Ze.rippleVisible,ax,gs,({theme:e})=>e.transitions.easing.easeInOut,Ze.ripplePulsate,({theme:e})=>e.transitions.duration.shorter,Ze.child,Ze.childLeaving,sx,gs,({theme:e})=>e.transitions.easing.easeInOut,Ze.childPulsate,ux,({theme:e})=>e.transitions.easing.easeInOut),dx=C.forwardRef(function(t,n){const r=vr({props:t,name:"MuiTouchRipple"}),{center:o=!1,classes:i={},className:l}=r,a=Fe(r,ix),[s,u]=C.useState([]),p=C.useRef(0),m=C.useRef(null);C.useEffect(()=>{m.current&&(m.current(),m.current=null)},[s]);const d=C.useRef(!1),v=Ev(),g=C.useRef(null),y=C.useRef(null),$=C.useCallback(w=>{const{pulsate:x,rippleX:k,rippleY:S,rippleSize:P,cb:I}=w;u(O=>[...O,b.jsx(fx,{classes:{ripple:Oe(i.ripple,Ze.ripple),rippleVisible:Oe(i.rippleVisible,Ze.rippleVisible),ripplePulsate:Oe(i.ripplePulsate,Ze.ripplePulsate),child:Oe(i.child,Ze.child),childLeaving:Oe(i.childLeaving,Ze.childLeaving),childPulsate:Oe(i.childPulsate,Ze.childPulsate)},timeout:gs,pulsate:x,rippleX:k,rippleY:S,rippleSize:P},p.current)]),p.current+=1,m.current=I},[i]),f=C.useCallback((w={},x={},k=()=>{})=>{const{pulsate:S=!1,center:P=o||x.pulsate,fakeElement:I=!1}=x;if((w==null?void 0:w.type)==="mousedown"&&d.current){d.current=!1;return}(w==null?void 0:w.type)==="touchstart"&&(d.current=!0);const O=I?null:y.current,W=O?O.getBoundingClientRect():{width:0,height:0,left:0,top:0};let H,se,Se;if(P||w===void 0||w.clientX===0&&w.clientY===0||!w.clientX&&!w.touches)H=Math.round(W.width/2),se=Math.round(W.height/2);else{const{clientX:ut,clientY:$e}=w.touches&&w.touches.length>0?w.touches[0]:w;H=Math.round(ut-W.left),se=Math.round($e-W.top)}if(P)Se=Math.sqrt((2*W.width**2+W.height**2)/3),Se%2===0&&(Se+=1);else{const ut=Math.max(Math.abs((O?O.clientWidth:0)-H),H)*2+2,$e=Math.max(Math.abs((O?O.clientHeight:0)-se),se)*2+2;Se=Math.sqrt(ut**2+$e**2)}w!=null&&w.touches?g.current===null&&(g.current=()=>{$({pulsate:S,rippleX:H,rippleY:se,rippleSize:Se,cb:k})},v.start(lx,()=>{g.current&&(g.current(),g.current=null)})):$({pulsate:S,rippleX:H,rippleY:se,rippleSize:Se,cb:k})},[o,$,v]),c=C.useCallback(()=>{f({},{pulsate:!0})},[f]),h=C.useCallback((w,x)=>{if(v.clear(),(w==null?void 0:w.type)==="touchend"&&g.current){g.current(),g.current=null,v.start(0,()=>{h(w,x)});return}g.current=null,u(k=>k.length>0?k.slice(1):k),m.current=x},[v]);return C.useImperativeHandle(n,()=>({pulsate:c,start:f,stop:h}),[c,f,h]),b.jsx(cx,R({className:Oe(Ze.root,i.root,l),ref:y},a,{children:b.jsx(nx,{component:null,exit:!0,children:s})}))}),px=dx;function mx(e){return Po("MuiButtonBase",e)}const hx=hr("MuiButtonBase",["root","disabled","focusVisible"]),yx=hx,gx=["action","centerRipple","children","className","component","disabled","disableRipple","disableTouchRipple","focusRipple","focusVisibleClassName","LinkComponent","onBlur","onClick","onContextMenu","onDragLeave","onFocus","onFocusVisible","onKeyDown","onKeyUp","onMouseDown","onMouseLeave","onMouseUp","onTouchEnd","onTouchMove","onTouchStart","tabIndex","TouchRippleProps","touchRippleRef","type"],vx=e=>{const{disabled:t,focusVisible:n,focusVisibleClassName:r,classes:o}=e,l=Dl({root:["root",t&&"disabled",n&&"focusVisible"]},mx,o);return n&&r&&(l.root+=` ${r}`),l},wx=vt("button",{name:"MuiButtonBase",slot:"Root",overridesResolver:(e,t)=>t.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"},[`&.${yx.disabled}`]:{pointerEvents:"none",cursor:"default"},"@media print":{colorAdjust:"exact"}}),xx=C.forwardRef(function(t,n){const r=vr({props:t,name:"MuiButtonBase"}),{action:o,centerRipple:i=!1,children:l,className:a,component:s="button",disabled:u=!1,disableRipple:p=!1,disableTouchRipple:m=!1,focusRipple:d=!1,LinkComponent:v="a",onBlur:g,onClick:y,onContextMenu:$,onDragLeave:f,onFocus:c,onFocusVisible:h,onKeyDown:w,onKeyUp:x,onMouseDown:k,onMouseLeave:S,onMouseUp:P,onTouchEnd:I,onTouchMove:O,onTouchStart:W,tabIndex:H=0,TouchRippleProps:se,touchRippleRef:Se,type:ut}=r,$e=Fe(r,gx),Tt=C.useRef(null),E=C.useRef(null),z=mf(E,Se),{isFocusVisibleRef:N,onFocus:Z,onBlur:ue,ref:Tn}=zv(),[Te,Bt]=C.useState(!1);u&&Te&&Bt(!1),C.useImperativeHandle(o,()=>({focusVisible:()=>{Bt(!0),Tt.current.focus()}}),[]);const[ct,Rn]=C.useState(!1);C.useEffect(()=>{Rn(!0)},[]);const Xm=ct&&!p&&!u;C.useEffect(()=>{Te&&d&&!p&&ct&&E.current.pulsate()},[p,d,Te,ct]);function Rt(L,Wu,fh=m){return Qo(Bu=>(Wu&&Wu(Bu),!fh&&E.current&&E.current[L](Bu),!0))}const qm=Rt("start",k),Zm=Rt("stop",$),Jm=Rt("stop",f),eh=Rt("stop",P),th=Rt("stop",L=>{Te&&L.preventDefault(),S&&S(L)}),nh=Rt("start",W),rh=Rt("stop",I),oh=Rt("stop",O),ih=Rt("stop",L=>{ue(L),N.current===!1&&Bt(!1),g&&g(L)},!1),lh=Qo(L=>{Tt.current||(Tt.current=L.currentTarget) Line truncated
0% {
left: -35%;
right: 100%;
}
60% {
left: 100%;
right: -90%;
}
100% {
left: 100%;
right: -90%;
}
`)),eS=$n(bf||(bf=wr`
0% {
left: -200%;
right: 100%;
}
60% {
left: 107%;
right: -8%;
}
100% {
left: 107%;
right: -8%;
}
`)),tS=$n(zf||(zf=wr`
0% {
opacity: 1;
background-position: 0 -23px;
}
60% {
opacity: 0;
background-position: 0 -23px;
}
100% {
opacity: 1;
background-position: -200px -23px;
}
`)),nS=e=>{const{classes:t,variant:n,color:r}=e,o={root:["root",`color${G(r)}`,n],dashed:["dashed",`dashedColor${G(r)}`],bar1:["bar",`barColor${G(r)}`,(n==="indeterminate"||n==="query")&&"bar1Indeterminate",n==="determinate"&&"bar1Determinate",n==="buffer"&&"bar1Buffer"],bar2:["bar",n!=="buffer"&&`barColor${G(r)}`,n==="buffer"&&`color${G(r)}`,(n==="indeterminate"||n==="query")&&"bar2Indeterminate",n==="buffer"&&"bar2Buffer"]};return Dl(o,qx,t)},ju=(e,t)=>t==="inherit"?"currentColor":e.vars?e.vars.palette.LinearProgress[`${t}Bg`]:e.palette.mode==="light"?Dm(e.palette[t].main,.62):Im(e.palette[t].main,.5),rS=vt("span",{name:"MuiLinearProgress",slot:"Root",overridesResolver:(e,t)=>{const{ownerState:n}=e;return[t.root,t[`color${G(n.color)}`],t[n.variant]]}})(({ownerState:e,theme:t})=>R({position:"relative",overflow:"hidden",display:"block",height:4,zIndex:0,"@media print":{colorAdjust:"exact"},backgroundColor:ju(t,e.color)},e.color==="inherit"&&e.variant!=="buffer"&&{backgroundColor:"none","&::before":{content:'""',position:"absolute",left:0,top:0,right:0,bottom:0,backgroundColor:"currentColor",opacity:.3}},e.variant==="buffer"&&{backgroundColor:"transparent"},e.variant==="query"&&{transform:"rotate(180deg)"})),oS=vt("span",{name:"MuiLinearProgress",slot:"Dashed",overridesResolver:(e,t)=>{const{ownerState:n}=e;return[t.dashed,t[`dashedColor${G(n.color)}`]]}})(({ownerState:e,theme:t})=>{const n=ju(t,e.color);return R({position:"absolute",marginTop:0,height:"100%",width:"100%"},e.color==="inherit"&&{opacity:.3},{backgroundImage:`radial-gradient(${n} 0%, ${n} 16%, transparent 42%)`,backgroundSize:"10px 10px",backgroundPosition:"0 -23px"})},ko(Nf||(Nf=wr`
animation: ${0} 3s infinite linear;
`),tS)),iS=vt("span",{name:"MuiLinearProgress",slot:"Bar1",overridesResolver:(e,t)=>{const{ownerState:n}=e;return[t.bar,t[`barColor${G(n.color)}`],(n.variant==="indeterminate"||n.variant==="query")&&t.bar1Indeterminate,n.variant==="determinate"&&t.bar1Determinate,n.variant==="buffer"&&t.bar1Buffer]}})(({ownerState:e,theme:t})=>R({width:"100%",position:"absolute",left:0,bottom:0,top:0,transition:"transform 0.2s linear",transformOrigin:"left",backgroundColor:e.color==="inherit"?"currentColor":(t.vars||t).palette[e.color].main},e.variant==="determinate"&&{transition:`transform .${vs}s linear`},e.variant==="buffer"&&{zIndex:1,transition:`transform .${vs}s linear`}),({ownerState:e})=>(e.variant==="indeterminate"||e.variant==="query")&&ko(Lf||(Lf=wr`
width: auto;
animation: ${0} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite;
`),Jx)),lS=vt("span",{name:"MuiLinearProgress",slot:"Bar2",overridesResolver:(e,t)=>{const{ownerState:n}=e;return[t.bar,t[`barColor${G(n.color)}`],(n.variant==="indeterminate"||n.variant==="query")&&t.bar2Indeterminate,n.variant==="buffer"&&t.bar2Buffer]}})(({ownerState:e,theme:t})=>R({width:"100%",position:"absolute",left:0,bottom:0,top:0,transition:"transform 0.2s linear",transformOrigin:"left"},e.variant!=="buffer"&&{backgroundColor:e.color==="inherit"?"currentColor":(t.vars||t).palette[e.color].main},e.color==="inherit"&&{opacity:.3},e.variant==="buffer"&&{backgroundColor:ju(t,e.color),transition:`transform .${vs}s linear`}),({ownerState:e})=>(e.variant==="indeterminate"||e.variant==="query")&&ko(If||(If=wr`
width: auto;
animation: ${0} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite;
`),eS)),aS=C.forwardRef(function(t,n){const r=vr({props:t,name:"MuiLinearProgress"}),{className:o,color:i="primary",value:l,valueBuffer:a,variant:s="indeterminate"}=r,u=Fe(r,Zx),p=R({},r,{color:i,variant:s}),m=nS(p),d=Lv(),v={},g={bar1:{},bar2:{}};if((s==="determinate"||s==="buffer")&&l!==void 0){v["aria-valuenow"]=Math.round(l),v["aria-valuemin"]=0,v["aria-valuemax"]=100;let y=l-100;d&&(y=-y),g.bar1.transform=`translateX(${y}%)`}if(s==="buffer"&&a!==void 0){let y=(a||0)-100;d&&(y=-y),g.bar2.transform=`translateX(${y}%)`}return b.jsxs(rS,R({className:Oe(m.root,o),ownerState:p,role:"progressbar"},v,{ref:n},u,{children:[s==="buffer"?b.jsx(oS,{className:m.dashed,ownerState:p}):null,b.jsx(iS,{className:m.bar1,ownerState:p,style:g.bar1}),s==="determinate"?null:b.jsx(lS,{className:m.bar2,ownerState:p,style:g.bar2})]}))}),sS=aS;function uS(){return window.crypto.getRandomValues(new Uint32Array(1))[0]}function ws(e,t=!1){const n=uS(),r=`_${n}`;return Object.defineProperty(window,r,{value:o=>(t&&Reflect.deleteProperty(window,r),e==null?void 0:e(o)),writable:!1,configurable:!0}),n}async function cS(e,t={}){return new Promise((n,r)=>{const o=ws(l=>{n(l),Reflect.deleteProperty(window,`_${i}`)},!0),i=ws(l=>{r(l),Reflect.deleteProperty(window,`_${o}`)},!0);window.__TAURI_IPC__({cmd:e,callback:o,error:i,...t})})}async function M(e){return cS("tauri",e)}async function Gm(e,t){return M({__tauriModule:"Event",message:{cmd:"unlisten",event:e,eventId:t}})}async function fS(e,t,n){await M({__tauriModule:"Event",message:{cmd:"emit",event:e,windowLabel:t,payload:n}})}async function Ym(e,t,n){return M({__tauriModule:"Event",message:{cmd:"listen",event:e,windowLabel:t,handler:ws(n)}}).then(r=>async()=>Gm(e,r))}async function dS(e,t,n){return Ym(e,t,r=>{n(r),Gm(e,r.id).catch(()=>{})})}var We;(function(e){e.WINDOW_RESIZED="tauri://resize",e.WINDOW_MOVED="tauri://move",e.WINDOW_CLOSE_REQUESTED="tauri://close-requested",e.WINDOW_CREATED="tauri://window-created",e.WINDOW_DESTROYED="tauri://destroyed",e.WINDOW_FOCUS="tauri://focus",e.WINDOW_BLUR="tauri://blur",e.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",e.WINDOW_THEME_CHANGED="tauri://theme-changed",e.WINDOW_FILE_DROP="tauri://file-drop",e.WINDOW_FILE_DROP_HOVER="tauri://file-drop-hover",e.WINDOW_FILE_DROP_CANCELLED="tauri://file-drop-cancelled",e.MENU="tauri://menu",e.CHECK_UPDATE="tauri://update",e.UPDATE_AVAILABLE="tauri://update-available",e.INSTALL_UPDATE="tauri://update-install",e.STATUS_UPDATE="tauri://update-status",e.DOWNLOAD_PROGRESS="tauri://update-download-progress"})(We||(We={}));class pS{constructor(t,n){this.type="Logical",this.width=t,this.height=n}}class xs{constructor(t,n){this.type="Physical",this.width=t,this.height=n}toLogical(t){return new pS(this.width/t,this.height/t)}}class mS{constructor(t,n){this.type="Logical",this.x=t,this.y=n}}class Ss{constructor(t,n){this.type="Physical",this.x=t,this.y=n}toLogical(t){return new mS(this.x/t,this.y/t)}}var ks;(function(e){e[e.Critical=1]="Critical",e[e.Informational=2]="Informational"})(ks||(ks={}));function Df(){return window.__TAURI_METADATA__.__windows.map(e=>new mo(e.label,{skip:!0}))}const Af=["tauri://created","tauri://error"];class hS{constructor(t){this.label=t,this.listeners=Object.create(null)}async listen(t,n){return this._handleTauriEvent(t,n)?Promise.resolve(()=>{const r=this.listeners[t];r.splice(r.indexOf(n),1)}):Ym(t,this.label,n)}async once(t,n){return this._handleTauriEvent(t,n)?Promise.resolve(()=>{const r=this.listeners[t];r.splice(r.indexOf(n),1)}):dS(t,this.label,n)}async emit(t,n){if(Af.includes(t)){for(const r of this.listeners[t]||[])r({event:t,id:-1,windowLabel:this.label,payload:n});return Promise.resolve()}return fS(t,this.label,n)}_handleTauriEvent(t,n){return Af.includes(t)?(t in this.listeners?this.listeners[t].push(n):this.listeners[t]=[n],!0):!1}}class yS extends hS{async scaleFactor(){return M({__tauriModule:"Window",message:{cmd:"manage",data:{label:this.label,cmd:{type:"scaleFactor"}}}})}async innerPosition(){return M({__tauriModule:"Window",message:{cmd:"manage",data:{label:this.label,cmd:{type:"innerPosition"}}}}).then(({x:t,y:n})=>new Ss(t,n))}async outerPosition(){return M({__tauriModule:"Window",message:{cmd:"manage",data:{label:this.label,cmd:{type:"outerPosition"}}}}).then(({x:t,y:n})=>new Ss(t,n))}async innerSize(){return M({__tauriModule:"Window",message:{cmd:"manage",data:{label:this.label,cmd:{type:"innerSize"}}}}).then(({width:t,height:n})=>new xs(t,n))}async outerSize(){return M({__tauriModule:"Window",message:{cmd:"manage",data:{label:this.label,cmd:{type:"outerSize"}}}}).then(({width:t,height:n})=>new xs(t,n))}async isFullscreen(){return M({__tauriModule:"Window",message:{cmd:"manage",data:{label:this.label,cmd:{type:"isFullscreen"}}}})}async isMinimized(){return M({__tauriModule:"Window",message:{cmd:"manage",data:{label:this.label,cmd:{type:"isMinimized"}}}})}async isMaximized(){return M({__tauriModule:"Window",message:{cmd:"manage",data:{label:this.label,cm Line truncated
Note that this is not an issue if running this frontend on a browser instead of a Tauri window.`),ho=new mo("main",{skip:!0}));function vS(e){return new Ss(e.x,e.y)}function wS(e){return new xs(e.width,e.height)}const xS="/assets/icon-674efcbe.svg";function SS(){const[e,t]=C.useState(null);return C.useEffect(()=>{const n=ho.listen("app://update-progress",r=>{t(r.payload)});return()=>{n.then(r=>r())}},[]),e}function kS(){const[e,t]=C.useState(!1);C.useEffect(()=>{const r=ho.listen("app://update-error",()=>{t(!0)});return()=>{r.then(o=>o())}},[]);const n=()=>{t(!1),ho.emit("app://update")};return b.jsxs(b.Fragment,{children:[b.jsx(Xx,{}),b.jsx(Nt,{sx:{position:"absolute",inset:0},display:"flex",alignItems:"center",px:2,"data-tauri-drag-region":!0,children:b.jsxs(Nt,{display:"flex",alignItems:"center",flex:"1","data-tauri-drag-region":!0,children:[b.jsx(Nt,{component:"img",src:xS,alt:"logo",sx:{width:"4rem",height:"4rem"},"data-tauri-drag-region":!0}),b.jsx(Nt,{flex:1,ml:2,children:e?b.jsx(CS,{onRetry:n}):b.jsx(_S,{})})]})})]})}function _S(){const e=SS();return b.jsxs(b.Fragment,{children:[b.jsx(Au,{variant:"h1",fontSize:"1rem","data-tauri-drag-region":!0,children:"Updating the GUI components..."}),b.jsx(Nt,{mt:1,children:b.jsx(ES,{value:e})})]})}function CS({onRetry:e}){return b.jsxs(b.Fragment,{children:[b.jsx(Au,{variant:"h1",fontSize:"1rem","data-tauri-drag-region":!0,children:"Failed to update the GUI components."}),b.jsx(Nt,{mt:1,"data-tauri-drag-region":!0,children:b.jsx(Kx,{variant:"contained",color:"primary",size:"small",onClick:e,sx:{textTransform:"none"},children:"Retry"})})]})}function ES(e){const{value:t}=e;return b.jsxs(Nt,{sx:{display:"flex",alignItems:"center"},children:[b.jsx(Nt,{flex:"1",children:b.jsx(sS,{variant:t===null?"indeterminate":"determinate",value:t??0,sx:{py:1.2,".MuiLinearProgress-bar":{transition:"none"}}})}),t!==null&&b.jsx(Nt,{sx:{minWidth:35,textAlign:"right",ml:1},children:b.jsx(Au,{variant:"body2",color:"text.secondary",children:`${Math.round(t)}%`})})]})}const PS=qp(document.getElementById("root"));PS.render(b.jsx(kS,{}));
+5 -4
View File
@@ -2,11 +2,11 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/assets/icon-small-BO4dlTNl.svg" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>GPGUI Downloader</title>
<script type="module" crossorigin src="/assets/main-B7u6_mhO.js"></script>
<link rel="stylesheet" crossorigin href="/assets/main-DiWGniCh.css">
<title>GlobalProtect</title>
<script type="module" crossorigin src="/assets/main-c159dd55.js"></script>
<link rel="stylesheet" href="/assets/index-11e7064a.css">
</head>
<body>
<script>
@@ -16,5 +16,6 @@
document.documentElement.style.fontSize = 16 / ratio + "px";
</script>
<div id="root" data-tauri-drag-region></div>
</body>
</html>
+6
View File
@@ -0,0 +1,6 @@
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

+2 -2
View File
@@ -2,9 +2,9 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/src/assets/icon-small.svg" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>GPGUI Downloader</title>
<title>GlobalProtect</title>
</head>
<body>
<script>
+22 -18
View File
@@ -9,25 +9,29 @@
"tauri": "tauri"
},
"dependencies": {
"@tauri-apps/api": "^2.12.1",
"react": "^19.3.0",
"react-dom": "^19.3.0"
"@emotion/react": "^11.13.0",
"@emotion/styled": "^11.13.0",
"@mui/icons-material": "^5.16.7",
"@mui/material": "^5.16.7",
"@tauri-apps/api": "^1.6.0",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@tauri-apps/cli": "^2.12.1",
"@types/node": "^26.6.4",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@typescript-eslint/eslint-plugin": "^8.71.1",
"@typescript-eslint/parser": "^8.71.1",
"@vitejs/plugin-react": "^6.1.2",
"eslint": "^9.39.5",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^7.1.1",
"prettier": "3.9.9",
"typescript": "^6.0.3",
"vite": "^8.3.3"
"@tauri-apps/cli": "^1.6.0",
"@types/node": "^20.14.15",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@typescript-eslint/eslint-plugin": "^6.21.0",
"@typescript-eslint/parser": "^6.21.0",
"@vitejs/plugin-react": "^4.3.1",
"eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-react": "^7.35.0",
"eslint-plugin-react-hooks": "^4.6.2",
"prettier": "3.1.0",
"typescript": "^5.5.4",
"vite": "^4.5.3"
},
"packageManager": "pnpm@9.15.1"
"packageManager": "pnpm@8.15.7"
}
+2476 -2712
View File
File diff suppressed because it is too large. Load diff
+6
View File
@@ -0,0 +1,6 @@
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

+4 -9
View File
@@ -1,18 +1,16 @@
[package]
name = "gpgui-helper"
rust-version.workspace = true
authors.workspace = true
version.workspace = true
edition.workspace = true
license.workspace = true
[build-dependencies]
tauri-build = { version = "2", features = [] }
tauri-build = { version = "1.5", features = [] }
[dependencies]
gpapi = { path = "../../../crates/gpapi", features = ["tauri", "clap"] }
tauri.workspace = true
gpapi = { path = "../../../crates/gpapi", features = ["tauri"] }
tauri = { workspace = true, features = ["window-start-dragging"] }
tokio.workspace = true
anyhow.workspace = true
log.workspace = true
@@ -20,11 +18,8 @@ clap.workspace = true
compile-time.workspace = true
env_logger.workspace = true
futures-util.workspace = true
uuid.workspace = true
zeroize.workspace = true
tokio-tungstenite = "0.30"
tempfile.workspace = true
reqwest = { workspace = true, features = ["stream"] }
[features]
default = ["tauri/custom-protocol"]
custom-protocol = ["tauri/custom-protocol"]
-59
View File
@@ -1,62 +1,3 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
println!("cargo:rerun-if-env-changed=GPGUI_HELPER_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
println!(
"cargo:rustc-env=GPGUI_HELPER_GIT_COMMIT={}",
resolve_commit(&repo_root, &source_commit)
);
tauri_build::build()
}
fn resolve_commit(repo_root: &PathBuf, source_commit: &PathBuf) -> String {
env_commit("GPGUI_HELPER_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(source_commit))
.or_else(|| git_commit(repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string())
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=9", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
@@ -1,12 +0,0 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": [
"core:window:allow-start-dragging",
"core:event:allow-listen",
"core:event:allow-emit",
"core:event:allow-unlisten"
]
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

After

Width:  |  Height:  |  Size: 83 KiB

+97 -49
View File
@@ -1,51 +1,99 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
<defs>
<linearGradient id="ocean" x1="245" y1="170" x2="770" y2="770" gradientUnits="userSpaceOnUse">
<stop stop-color="#579bc1"/>
<stop offset=".52" stop-color="#438fbd"/>
<stop offset="1" stop-color="#2f719e"/>
</linearGradient>
<linearGradient id="land" x1="260" y1="190" x2="750" y2="735" gradientUnits="userSpaceOnUse">
<stop stop-color="#56c78a"/>
<stop offset=".55" stop-color="#3bbf78"/>
<stop offset="1" stop-color="#279b5d"/>
</linearGradient>
<linearGradient id="lock" x1="385" y1="400" x2="650" y2="700" gradientUnits="userSpaceOnUse">
<stop stop-color="#f3b84c"/>
<stop offset=".55" stop-color="#e8a12f"/>
<stop offset="1" stop-color="#d4871e"/>
</linearGradient>
<clipPath id="globe-clip">
<circle cx="512" cy="455" r="315"/>
</clipPath>
<filter id="globe-shadow" x="150" y="90" width="730" height="760" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feDropShadow dx="0" dy="18" stdDeviation="22" flood-color="#174d6f" flood-opacity=".14"/>
</filter>
<filter id="lock-shadow" x="280" y="210" width="470" height="540" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feDropShadow dx="0" dy="18" stdDeviation="18" flood-color="#70430c" flood-opacity=".2"/>
</filter>
</defs>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<g transform="translate(512 512) scale(1.3) translate(-512 -455)">
<g filter="url(#globe-shadow)">
<circle cx="512" cy="455" r="315" fill="url(#ocean)"/>
<g clip-path="url(#globe-clip)" fill="url(#land)">
<path d="M177 326c74-121 177-185 302-190-13 51-49 84-105 98-4 45-32 79-86 101-37 17-75 14-111-9Z"/>
<path d="M564 135c129 18 229 103 273 220-69-3-121 15-157 54-51-14-83-50-95-107-38-36-45-92-21-167Z"/>
<path d="M189 467c63-39 125-34 187 16 57 25 73 73 48 144-45 90-108 146-189 166-58-88-73-197-46-326Z"/>
<path d="M612 572c78-38 157-18 238 59-45 89-122 144-231 164-20-67-22-122-7-165-22-17-22-36 0-58Z"/>
</g>
<circle cx="512" cy="455" r="308" fill="none" stroke="#9ccde2" stroke-width="11" stroke-opacity=".24"/>
</g>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
version="1.1"
id="Layer_1"
x="0px"
y="0px"
viewBox="0 0 96 96"
style="enable-background:new 0 0 96 96;"
xml:space="preserve"
sodipodi:docname="com.yuezk.qt.gpclient.svg"
inkscape:version="0.92.4 5da689c313, 2019-01-14"><metadata
id="metadata14"><rdf:RDF><cc:Work
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
id="defs12" /><sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="1920"
inkscape:window-height="1006"
id="namedview10"
showgrid="false"
inkscape:zoom="6.9532168"
inkscape:cx="7.9545315"
inkscape:cy="59.062386"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:current-layer="g8499" />
<style
type="text/css"
id="style2">
.st0{fill:#2980B9;}
.st1{fill:#3498DB;}
.st2{fill:#2ECC71;}
.st3{fill:#27AE60;}
</style>
<g transform="translate(512 490) scale(.82) translate(-512 -490)" filter="url(#lock-shadow)">
<path d="M405 429v-75c0-142 214-142 214 0v75" fill="none" stroke="#eef1f2" stroke-width="58" stroke-linecap="round"/>
<rect x="340" y="403" width="344" height="278" rx="62" fill="url(#lock)"/>
<rect x="346" y="409" width="332" height="266" rx="56" fill="none" stroke="#f7cb75" stroke-width="10" stroke-opacity=".3"/>
<g fill="#85500f" opacity=".78">
<path d="M501 538h22l16 69h-54Z"/>
<circle cx="512" cy="521" r="27"/>
</g>
</g>
</g>
</svg>
<g
id="g8499"
transform="matrix(1.3407388,0,0,1.3407388,-16.409202,-16.355463)"><g
id="XMLID_1_">
<circle
r="32.5"
cy="48"
cx="48"
class="st0"
id="XMLID_3_"
style="fill:#2980b9" />
<path
d="m 48,15.5 v 65 C 65.9,80.5 80.5,65.7 80.5,48 80.5,30 65.9,15.5 48,15.5 Z"
class="st1"
id="XMLID_4_"
inkscape:connector-curvature="0"
style="fill:#3498db" />
<path
d="m 48,15.5 v 0.6 l 1.2,-0.3 c 0.3,-0.3 0.4,-0.3 0.6,-0.3 h -1.1 z m 7.3,0.9 c -0.1,0 0.4,0.9 1.1,1.8 0.8,1.5 1.1,2.1 1.3,2.1 0.3,-0.3 1.9,-1.2 3,-2.1 -1.7,-0.9 -3.5,-1.5 -5.4,-1.8 z m 10.3,6.2 c -0.1,0 -0.4,0 -0.9,0.6 l -0.8,0.9 0.6,0.6 c 0.3,0.6 0.8,0.9 1,1.2 0.5,0.6 0.6,0.6 0.1,1.5 -0.2,0.6 -0.3,0.9 -0.3,0.9 0.1,0.3 0.3,0.3 1.4,0.3 h 1.6 c 0.1,0 0.3,-0.6 0.4,-1.2 l 0.1,-0.9 -1.1,-0.9 c -1,-0.9 -1,-0.9 -1.4,-1.8 -0.3,-0.6 -0.6,-1.2 -0.7,-1.2 z m -3,2.4 c -0.2,0 -1.3,2.1 -1.3,2.4 0,0 0.3,0.6 0.7,0.9 0.4,0.3 0.7,0.6 0.7,0.6 0.1,0 1.2,-1.2 1.4,-1.5 C 64.2,27.1 64,26.8 63.5,26.2 63.1,25.5 62.7,25 62.6,25 Z m 9.5,1.1 0.2,0.3 c 0,0.3 -0.7,0.9 -1.4,1.5 -1.2,0.9 -1.4,1.2 -2,1.2 -0.6,0 -0.9,0.3 -1.8,0.9 -0.6,0.6 -1.2,0.9 -1.2,1.2 0,0 0.2,0.3 0.6,0.9 0.7,0.6 0.7,0.9 0.2,1.8 l -0.4,0.3 h -1.1 c -0.6,0 -1.5,0 -1.8,-0.3 -0.9,0 -0.8,0 -0.1,2.1 1,3 1.1,3.2 1.3,3.2 0.1,0 1.3,-1.2 2.8,-2.4 1.5,-1.2 2.7,-2.4 2.8,-2.4 l 0.6,0.3 c 0.4,0.3 0.5,0 1.3,-0.6 l 0.8,-0.6 0.8,0.6 c 1.9,1.2 2.2,1.5 2.3,2.4 0.2,1.5 0.3,1.8 0.5,1.8 0.1,0 1.3,-1.5 1.6,-1.8 0.1,-0.3 -0.1,-0.6 -1.1,-2.1 -0.7,-0.9 -1.1,-1.8 -1.1,-2.1 0,0 0.1,0 0.3,-0.3 0.2,0 0.4,0.3 1,0.9 -1.6,-2.3 -3.2,-4.7 -5.1,-6.8 z m 2.8,10.7 c -0.2,0 -0.9,0.9 -0.8,1.2 l 0.5,0.3 H 75 c 0.2,0 0.3,0 0.2,-0.3 C 75.1,37.4 75,36.8 74.9,36.8 Z M 72.3,38 h -2.4 l -2.4,0.3 -4.5,3.5 -4.4,3.8 v 3.5 c 0,2.1 0,3.8 0.1,3.8 0.1,0 0.7,0.9 1.5,1.5 0.8,0.9 1.5,1.5 1.8,1.8 0.4,0.3 0.5,0.3 4,0.6 l 3.4,0.3 1.6,0.9 c 0.8,0.6 1.5,1.2 1.6,1.2 0.1,0 -0.3,0.3 -0.6,0.6 l -0.6,0.6 1,1.2 c 0.5,0.6 1.3,1.5 1.7,1.8 l 0.6,0.9 v 1.7 0.9 c 3.7,-5 5.9,-11.5 6.1,-18.3 0.1,-2.7 -0.3,-5.3 -0.8,-8 l -0.6,-0.3 c -0.1,0 -0.5,0.3 -1,0.6 -0.5,0.3 -1,0.9 -1.1,0.9 -0.1,0 -0.8,-0.3 -1.8,-0.6 l -1.8,-0.6 v -0.9 c 0,-0.6 0,-0.9 -0.6,-1.5 z M 48,63.7 V 64 h 0.2 z"
class="st2"
id="XMLID_13_"
inkscape:connector-curvature="0"
style="fill:#2ecc71" />
<path
d="m 48,15.5 c -3.1,0 -6.2,0.5 -9,1.3 0.3,0.4 0.3,0.4 0.6,0.9 1.5,2.5 1.7,2.8 2.1,2.9 0.3,0 0.9,0.1 1.6,0.1 h 1.2 l 0.9,-2 0.8,-1.9 1.8,-0.6 z m -16.9,4.7 c -2.8,1.7 -5.4,3.9 -7.6,6.4 -3.8,4.3 -6.3,9.6 -7.4,15.4 0.5,0 0.9,-0.1 1.8,-0.1 2.8,0.1 2.5,0 3.4,1.4 0.5,0.8 0.6,0.8 1.4,0.8 1,0.1 0.9,0 0.5,-1.6 -0.2,-0.6 -0.3,-1.2 -0.3,-1.4 0,-0.2 0.5,-0.7 1.7,-1.6 1.9,-1.5 1.8,-1.3 1.5,-2.9 -0.1,-0.3 0.1,-0.6 0.6,-1.2 0.7,-0.7 0.7,-0.6 1.4,-0.6 h 0.7 l 0.1,-1.2 c 0.1,-0.7 0.1,-1.3 0.2,-1.3 0,0 1.9,-1.1 4.1,-2.3 2.2,-1.2 4.1,-2.2 4.2,-2.3 0.2,-0.2 -0.3,-0.8 -2.7,-3.8 -1.5,-1.9 -2.8,-3.6 -2.9,-3.7 z m -5.8,23 c -0.1,0 -0.1,0.3 -0.1,0.6 0,0.6 0,0.7 0.6,1 0.8,0.4 0.9,0.5 0.8,0.2 -0.1,-0.4 -1.2,-1.9 -1.3,-1.8 z m -3.4,2.1 -0.5,1.8 c 0.1,0.1 0.9,0.3 1.8,0.5 1,0.2 1.6,0.4 1.8,0.3 l 0.5,-1.3 z m -3.8,1 -1.1,0.6 c -0.6,0.3 -1.2,0.6 -1.4,0.6 h -0.1 c 0,1.4 0.1,2.8 0.3,4.2 l 0.6,0.4 1,-0.1 h 1 l 0.6,1.4 c 0.3,0.7 0.7,1.4 0.8,1.5 0.1,0.1 1,0.1 1.8,0.1 h 1.5 L 23,56.2 c 0,1.2 0,1.3 -0.6,2.2 -0.4,0.5 -0.6,1.2 -0.6,1.4 0,0.2 0.7,2.1 1.6,4.3 l 1.5,4 1.6,0.8 c 1.2,0.6 1.5,0.8 1.5,1 0,0.1 -0.4,2.1 -0.6,3.1 3,2.5 6.4,4.5 10.2,5.8 3.5,-3.6 6.8,-7.1 7.3,-7.6 l 0.7,-0.7 0.2,-1.9 c 0.2,-1.1 0.4,-2.1 0.4,-2.2 0,-0.1 0.5,-0.6 1,-1.2 0.5,-0.5 0.8,-1 0.8,-1.1 v -0.2 c -0.1,-0.1 -1.4,-1.1 -3,-2.2 l -3.1,-2.1 -1.1,-0.1 c -0.8,0 -1.2,0 -1.3,-0.2 C 39.4,59.2 39.2,58.5 39.1,57.7 39,56.9 38.9,56.2 38.8,56.1 38.8,56 38,56 37.1,56 36.2,56 35.4,55.9 35.3,55.8 35.2,55.7 35.2,55.1 35.1,54.3 35,53.6 34.9,53 34.8,52.9 34.7,52.8 33.7,52.7 32.5,52.6 30.5,52.5 30.1,52.5 29.1,52 l -1.2,-0.6 -1.6,0.7 -1.7,0.9 -1.8,-0.1 c -2,0 -1.9,0.2 -2.1,-1.6 C 20.6,50.7 20.6,50.1 20.5,50.1 20.4,50 20,50 19.6,49.9 L 18.9,49.7 19,49.2 c 0,-0.3 0,-1 0.1,-1.4 L 19.2,47 18.7,46.5 Z m 9.1,1.1 C 27.1,47.5 27.1,47.8 27,48 l -0.1,0.5 2.9,1.2 c 2.9,1.1 3.4,1.2 3.9,0.7 0.2,-0.2 0.1,-0.2 -0.3,-0.4 -0.3,-0.1 -1.7,-0.9 -3.2,-1.6 -1.7,-0.7 -2.9,-1.1 -3,-1 z"
class="st3"
id="XMLID_20_"
inkscape:connector-curvature="0"
style="fill:#27ae60" />
</g><g
transform="matrix(1.458069,0,0,1.458069,-22.631538,-19.615144)"
id="g7664"><path
inkscape:connector-curvature="0"
id="XMLID_6_"
class="st3"
d="m 38.8,56.1 c 0,1.2 1,2.2 2.2,2.2 h 15.2 c 1.2,0 2.2,-1 2.2,-2.2 V 45.3 c 0,-1.2 -1,-2.2 -2.2,-2.2 H 40.9 c -1.2,0 -2.2,1 -2.2,2.2 v 10.8 z"
style="fill:#f1aa27;fill-opacity:1" /><path
style="fill:#e6e6e6"
inkscape:connector-curvature="0"
id="XMLID_7_"
class="st4"
d="m 55.5,43.1 h -3.3 v -3.7 c 0,-2.1 -1.7,-3.8 -3.8,-3.8 -2.1,0 -3.8,1.7 -3.8,3.8 v 3.8 h -3.1 v -3.8 c 0,-3.9 3.2,-7 7,-7 3.9,0 7,3.2 7,7 z" /><path
style="fill:#e6e6e6;fill-opacity:1"
inkscape:connector-curvature="0"
id="XMLID_8_"
class="st5"
d="m 50.35,48.2 c 0,-1 -0.8,-1.8 -1.8,-1.8 -1,0 -1.8,0.8 -1.8,1.8 0,0.7 0.4,1.3 1,1.6 l -1,5.2 h 3.6 l -1,-5.2 c 0.6,-0.3 1,-0.9 1,-1.6 z" /></g></g></svg>

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 6.7 KiB

+13 -32
View File
@@ -1,55 +1,39 @@
use std::sync::Arc;
use gpapi::service::transport::SessionCredential;
use gpapi::utils::window::WindowExt;
use log::info;
use tauri::{Listener, Manager};
use tokio::sync::watch;
use tauri::Manager;
use crate::updater::{GuiUpdater, Installer, ProgressNotifier};
pub struct App {
credential: Arc<SessionCredential>,
credential_lease: watch::Receiver<bool>,
api_key: Vec<u8>,
gui_version: String,
}
impl App {
pub fn new(credential: Arc<SessionCredential>, credential_lease: watch::Receiver<bool>, gui_version: &str) -> Self {
pub fn new(api_key: Vec<u8>, gui_version: &str) -> Self {
Self {
credential,
credential_lease,
api_key,
gui_version: gui_version.to_string(),
}
}
pub fn run(&self) -> anyhow::Result<()> {
let gui_version = self.gui_version.clone();
let credential = Arc::clone(&self.credential);
let credential_lease = self.credential_lease.clone();
let api_key = self.api_key.clone();
tauri::Builder::default()
.setup(move |app| {
let win = app.get_webview_window("main").expect("no main window");
let _ = win.hide_menu();
let win = app.get_window("main").expect("no main window");
win.hide_menu();
let notifier = ProgressNotifier::new(win.clone());
let installer = Installer::new(credential, credential_lease.clone());
let installer = Installer::new(api_key);
let updater = Arc::new(GuiUpdater::new(gui_version, notifier, installer));
let app_handle = app.handle().clone();
let mut app_credential_lease = credential_lease;
tokio::spawn(async move {
while *app_credential_lease.borrow() {
if app_credential_lease.changed().await.is_err() {
return;
}
}
info!("Service credential lease ended");
app_handle.exit(0);
});
let win_clone = win.clone();
app.listen_any("app://update-done", move |_event| {
app.listen_global("app://update-done", move |_event| {
info!("Update done");
let _ = win_clone.close();
});
@@ -57,15 +41,12 @@ impl App {
// Listen for the update event
win.listen("app://update", move |_event| {
let updater = Arc::clone(&updater);
if updater.is_in_progress() {
info!("Update already in progress");
updater.notify_progress();
return;
}
tokio::spawn(async move { updater.update().await });
});
// Update the GUI on startup
win.trigger("app://update", None);
Ok(())
})
.run(tauri::generate_context!())?;
+22 -85
View File
@@ -1,101 +1,52 @@
use clap::Parser;
use std::{io::Read, sync::Arc};
use anyhow::{Context, bail};
use gpapi::{
clap::InfoLevelVerbosity,
service::transport::{MAX_CREDENTIAL_FRAME, SessionCredential},
utils::env_utils,
};
use log::info;
use tokio::sync::watch;
use zeroize::Zeroizing;
use gpapi::utils::base64;
use log::{info, LevelFilter};
use crate::app::App;
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPGUI_HELPER_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
const GP_API_KEY: &[u8; 32] = &[0; 32];
#[derive(Parser)]
#[command(version = VERSION)]
struct Cli {
#[arg(long, help = "Read the service credential from stdin")]
service_credential_on_stdin: bool,
#[arg(long, help = "Read the API key from stdin")]
api_key_on_stdin: bool,
#[arg(long, default_value = env!("CARGO_PKG_VERSION"), help = "The version of the GUI")]
gui_version: String,
#[command(flatten)]
verbose: InfoLevelVerbosity,
}
impl Cli {
fn run(&self) -> anyhow::Result<()> {
let credential = self.read_credential()?;
let credential_lease = monitor_credential_lease().context("Failed to monitor service credential lifetime")?;
let app = App::new(Arc::new(credential), credential_lease, &self.gui_version);
env_utils::patch_gui_runtime_env(false);
let api_key = self.read_api_key()?;
let app = App::new(api_key, &self.gui_version);
app.run()
}
fn read_credential(&self) -> anyhow::Result<SessionCredential> {
if !self.service_credential_on_stdin {
bail!("Service credential must be provided via --service-credential-on-stdin");
fn read_api_key(&self) -> anyhow::Result<Vec<u8>> {
if self.api_key_on_stdin {
let mut api_key = String::new();
std::io::stdin().read_line(&mut api_key)?;
let api_key = base64::decode_to_vec(api_key.trim())?;
Ok(api_key)
} else {
Ok(GP_API_KEY.to_vec())
}
let stdin = std::io::stdin();
let mut input = stdin.lock();
let mut header = [0_u8; 2];
input
.read_exact(&mut header)
.context("Failed to read service credential header")?;
let payload_len = u16::from_be_bytes(header) as usize;
if payload_len == 0 || payload_len + header.len() > MAX_CREDENTIAL_FRAME {
bail!("Invalid service credential length");
}
let mut frame = Zeroizing::new(Vec::with_capacity(payload_len + header.len()));
frame.extend_from_slice(&header);
frame.resize(payload_len + header.len(), 0);
input
.read_exact(&mut frame[header.len()..])
.context("Failed to read service credential")?;
SessionCredential::decode_frame(&frame).context("Invalid service credential")
}
}
fn monitor_credential_lease() -> std::io::Result<watch::Receiver<bool>> {
let (lease_tx, lease_rx) = watch::channel(true);
std::thread::Builder::new()
.name("credential-lease".to_owned())
.spawn(move || {
let stdin = std::io::stdin();
close_credential_lease_at_eof(stdin.lock(), lease_tx);
})?;
Ok(lease_rx)
}
fn close_credential_lease_at_eof(mut input: impl Read, lease_tx: watch::Sender<bool>) {
let mut buffer = [0_u8; 256];
while matches!(input.read(&mut buffer), Ok(len) if len > 0) {}
let _ = lease_tx.send(false);
}
fn init_logger(cli: &Cli) {
env_logger::builder()
.filter_level(cli.verbose.log_level_filter())
.init();
fn init_logger() {
env_logger::builder().filter_level(LevelFilter::Info).init();
}
pub fn run() {
let cli = Cli::parse();
init_logger(&cli);
init_logger();
info!("gpgui-helper started: {}", VERSION);
if let Err(e) = cli.run() {
@@ -103,17 +54,3 @@ pub fn run() {
std::process::exit(1);
}
}
#[cfg(test)]
mod tests {
use std::io::Cursor;
use super::*;
#[test]
fn credential_lease_closes_at_eof() {
let (lease_tx, lease_rx) = watch::channel(true);
close_credential_lease_at_eof(Cursor::new(b"ignored lease bytes"), lease_tx);
assert!(!*lease_rx.borrow());
}
}
+40 -565
View File
@@ -1,363 +1,70 @@
use std::{
error::Error,
fmt::{self, Display, Formatter},
sync::{Arc, RwLock},
time::Duration,
};
use std::sync::Arc;
use anyhow::{Context, bail};
use futures_util::{SinkExt, StreamExt};
use gpapi::{
service::{
request::{UpdateGuiRequest, WsRequest},
transport::{
ClientMessage, ClientPrelude, MAX_WS_MESSAGE, NoiseInitiator, NoiseTransport, ServerMessage, ServerPrelude,
ServiceResult, SessionCredential,
},
},
utils::{checksum::verify_checksum, endpoint::ws_endpoint},
service::request::UpdateGuiRequest,
utils::{checksum::verify_checksum, crypto::Crypto, endpoint::http_endpoint},
};
use log::{info, warn};
use tauri::{Emitter, WebviewWindow};
use tokio::net::TcpStream;
use tokio::sync::{mpsc, oneshot, watch};
use tokio_tungstenite::{
MaybeTlsStream, WebSocketStream, connect_async_with_config,
tungstenite::{Message, protocol::WebSocketConfig},
};
use uuid::Uuid;
use tauri::{Manager, Window};
use crate::downloader::{ChecksumFetcher, FileDownloader};
#[cfg(not(debug_assertions))]
const SNAPSHOT: &str = match option_env!("SNAPSHOT") {
Some(val) => val,
None => "false",
Some(val) => val,
None => "false"
};
#[cfg(target_env = "musl")]
const GUI_LIBC_SUFFIX: &str = "-musl";
#[cfg(not(target_env = "musl"))]
const GUI_LIBC_SUFFIX: &str = "";
fn gui_asset_name() -> Option<String> {
gui_asset_name_for(std::env::consts::OS, std::env::consts::ARCH, GUI_LIBC_SUFFIX)
}
fn gui_asset_name_for(os: &str, arch: &str, libc_suffix: &str) -> Option<String> {
let name = match (os, arch) {
("linux", "x86_64" | "aarch64") => format!("gpgui_{arch}{libc_suffix}.bin.tar.xz"),
("freebsd", "x86_64") => "gpgui_freebsd_amd64.bin.tar.xz".to_owned(),
("freebsd", "aarch64") => "gpgui_freebsd_arm64.bin.tar.xz".to_owned(),
("openbsd", "x86_64") => "gpgui_openbsd_amd64.bin.tar.xz".to_owned(),
("openbsd", "aarch64") => "gpgui_openbsd_arm64.bin.tar.xz".to_owned(),
_ => return None,
};
Some(name)
}
pub struct ProgressNotifier {
win: WebviewWindow,
win: Window,
}
impl ProgressNotifier {
pub fn new(win: WebviewWindow) -> Self {
pub fn new(win: Window) -> Self {
Self { win }
}
fn notify(&self, progress: Option<f64>) {
let _ = self.win.emit("app://update-progress", progress);
let _ = self.win.emit_all("app://update-progress", progress);
}
fn notify_error(&self) {
let _ = self.win.emit("app://update-error", ());
let _ = self.win.emit_all("app://update-error", ());
}
fn notify_done(&self) {
let _ = self.win.emit("app://update-done", ());
let _ = self.win.emit_and_trigger("app://update-done", ());
}
}
pub struct Installer {
command_tx: mpsc::Sender<InstallCommand>,
}
struct InstallCommand {
request: UpdateGuiRequest,
reply: oneshot::Sender<anyhow::Result<()>>,
crypto: Crypto,
}
impl Installer {
pub fn new(credential: Arc<SessionCredential>, credential_lease: watch::Receiver<bool>) -> Self {
let (command_tx, command_rx) = mpsc::channel(1);
tokio::spawn(async move {
run_installer(credential, credential_lease, command_rx).await;
});
Self { command_tx }
pub fn new(api_key: Vec<u8>) -> Self {
Self {
crypto: Crypto::new(api_key),
}
}
async fn install(&self, path: &str, checksum: &str) -> anyhow::Result<()> {
let service_endpoint = http_endpoint().await?;
let request = UpdateGuiRequest {
path: path.to_string(),
checksum: checksum.to_string(),
};
let (reply, result) = oneshot::channel();
self
.command_tx
.send(InstallCommand { request, reply })
.await
.context("Authenticated GUI installer is unavailable")?;
tokio::time::timeout(Duration::from_secs(60), result)
.await
.context("Service update request timed out")?
.context("Authenticated GUI installer stopped before replying")?
}
}
let payload = self.crypto.encrypt(&request)?;
type Socket = WebSocketStream<MaybeTlsStream<TcpStream>>;
reqwest::Client::default()
.post(format!("{}/update-gui", service_endpoint))
.body(payload)
.send()
.await?
.error_for_status()?;
#[derive(Debug)]
struct TerminalConnectError(String);
impl Display for TerminalConnectError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
impl Error for TerminalConnectError {}
async fn run_installer(
credential: Arc<SessionCredential>,
mut credential_lease: watch::Receiver<bool>,
mut commands: mpsc::Receiver<InstallCommand>,
) {
let mut pending = None;
loop {
if !*credential_lease.borrow() {
return;
}
let connection = tokio::select! {
changed = credential_lease.changed() => {
if changed.is_err() || !*credential_lease.borrow() {
return;
}
continue;
}
result = tokio::time::timeout(Duration::from_secs(5), connect_installer(&credential)) => {
match result {
Ok(result) => result,
Err(_) => Err(anyhow::anyhow!("Authenticated GUI installer handshake timed out")),
}
}
};
match connection {
Ok((mut socket, mut noise)) => {
info!("Authenticated GUI installer connected");
match run_installer_connection(
&mut socket,
&mut noise,
&mut credential_lease,
&mut commands,
&mut pending,
)
.await
{
Ok(ConnectionEnd::CredentialLeaseEnded | ConnectionEnd::CommandsClosed) => return,
Err(err) => warn!("Authenticated GUI installer connection lost: {err}"),
}
}
Err(err) if err.is::<TerminalConnectError>() => {
warn!("Authenticated GUI installer stopped: {err}");
return;
}
Err(err) => warn!("Authenticated GUI installer connection failed: {err}"),
}
tokio::select! {
changed = credential_lease.changed() => {
if changed.is_err() || !*credential_lease.borrow() {
return;
}
}
_ = tokio::time::sleep(Duration::from_millis(100)) => {}
}
}
}
enum ConnectionEnd {
CredentialLeaseEnded,
CommandsClosed,
}
async fn run_installer_connection(
socket: &mut Socket,
noise: &mut NoiseTransport,
credential_lease: &mut watch::Receiver<bool>,
commands: &mut mpsc::Receiver<InstallCommand>,
pending: &mut Option<InstallCommand>,
) -> anyhow::Result<ConnectionEnd> {
if pending.as_ref().is_some_and(|command| command.reply.is_closed()) {
pending.take();
}
let mut pending_id = match pending.as_ref() {
Some(command) => Some(send_install_command(socket, noise, command).await?),
None => None,
};
loop {
tokio::select! {
changed = credential_lease.changed() => {
if changed.is_err() || !*credential_lease.borrow() {
return Ok(ConnectionEnd::CredentialLeaseEnded);
}
}
command = commands.recv() => {
let Some(command) = command else { return Ok(ConnectionEnd::CommandsClosed) };
if command.reply.is_closed() {
continue;
}
if pending.is_some() {
let _ = command.reply.send(Err(anyhow::anyhow!("GUI installation is already pending")));
continue;
}
*pending = Some(command);
pending_id = Some(send_install_command(socket, noise, pending.as_ref().unwrap()).await?);
}
frame = socket.next() => {
match frame.context("Service closed the authenticated GUI installer")?? {
Message::Binary(data) => match noise.decrypt::<ServerMessage>(&data)? {
ServerMessage::Reply { id, result } => {
if pending_id != Some(id) {
bail!("Service sent a mismatched GUI installation reply");
}
let Some(command) = pending.take() else {
bail!("Service sent an unexpected GUI installation reply");
};
pending_id = None;
let result = match result {
ServiceResult::Accepted => Ok(()),
ServiceResult::Rejected(rejection) => Err(anyhow::anyhow!(
"Service rejected GUI installation ({:?}): {}",
rejection.code(),
rejection.message()
)),
_ => Err(anyhow::anyhow!("Service sent an unexpected GUI installation reply")),
};
let _ = command.reply.send(result);
}
ServerMessage::Event { .. } | ServerMessage::Snapshot { .. } => {}
ServerMessage::Attached { .. } => bail!("Service sent a duplicate attach response"),
},
Message::Ping(data) => socket.send(Message::Pong(data)).await?,
Message::Pong(_) => {}
Message::Close(_) => bail!("Service closed the authenticated GUI installer"),
_ => bail!("Service sent an unexpected WebSocket frame"),
}
}
}
}
}
async fn send_install_command(
socket: &mut Socket,
noise: &mut NoiseTransport,
command: &InstallCommand,
) -> anyhow::Result<Uuid> {
let id = Uuid::new_v4();
send_client_message(
socket,
noise,
&ClientMessage::Request {
id,
request: WsRequest::UpdateGui(command.request.clone()),
},
)
.await?;
Ok(id)
}
async fn connect_installer(credential: &SessionCredential) -> anyhow::Result<(Socket, NoiseTransport)> {
let endpoint = ws_endpoint().await?;
connect_installer_at(credential, &endpoint).await
}
async fn connect_installer_at(
credential: &SessionCredential,
endpoint: &str,
) -> anyhow::Result<(Socket, NoiseTransport)> {
if credential.product_version() != env!("CARGO_PKG_VERSION") {
return Err(TerminalConnectError("Service credential version does not match gpgui-helper".to_owned()).into());
}
let config = WebSocketConfig::default()
.max_message_size(Some(MAX_WS_MESSAGE))
.max_frame_size(Some(MAX_WS_MESSAGE));
let (mut socket, _) = connect_async_with_config(endpoint, Some(config), false).await?;
let prelude = ClientPrelude {
product_version: credential.product_version().to_owned(),
hip_protocol_version: gpapi::service::transport::HIP_PROTOCOL_VERSION,
service_instance_id: credential.service_instance_id(),
session_id: credential.session_id(),
};
socket.send(Message::Binary(prelude.encode()?.into())).await?;
let server_prelude = ServerPrelude::decode(&receive_binary(&mut socket).await?)
.map_err(|err| TerminalConnectError(format!("Service sent an invalid update-session response: {err}")))?;
match server_prelude {
ServerPrelude::Ready => {}
ServerPrelude::Rejected(reason) => {
return Err(TerminalConnectError(format!("Service rejected the update session: {reason:?}")).into());
}
}
let mut initiator = NoiseInitiator::new(
credential.product_version(),
credential.service_instance_id(),
credential.session_id(),
credential.secret(),
)?;
socket.send(Message::Binary(initiator.write_first()?.into())).await?;
let mut noise = initiator.read_response(&receive_binary(&mut socket).await?)?;
send_client_message(
&mut socket,
&mut noise,
&ClientMessage::Attach {
last_event_revision: None,
},
)
.await?;
if !matches!(
receive_server_message(&mut socket, &mut noise).await?,
ServerMessage::Attached { .. }
) {
bail!("Service did not attach the update session");
}
Ok((socket, noise))
}
async fn send_client_message(
socket: &mut Socket,
noise: &mut NoiseTransport,
message: &ClientMessage,
) -> anyhow::Result<()> {
socket.send(Message::Binary(noise.encrypt(message)?.into())).await?;
Ok(())
}
async fn receive_server_message(socket: &mut Socket, noise: &mut NoiseTransport) -> anyhow::Result<ServerMessage> {
Ok(noise.decrypt(&receive_binary(socket).await?)?)
}
async fn receive_binary(socket: &mut Socket) -> anyhow::Result<Vec<u8>> {
match socket.next().await {
Some(Ok(Message::Binary(data))) => Ok(data.to_vec()),
Some(Ok(_)) => bail!("Service sent an unexpected handshake frame"),
Some(Err(err)) => Err(err.into()),
None => bail!("Service closed during handshake"),
Ok(())
}
}
@@ -365,8 +72,6 @@ pub struct GuiUpdater {
version: String,
notifier: Arc<ProgressNotifier>,
installer: Installer,
in_progress: RwLock<bool>,
progress: Arc<RwLock<Option<f64>>>,
}
impl GuiUpdater {
@@ -375,16 +80,10 @@ impl GuiUpdater {
version,
notifier: Arc::new(notifier),
installer,
in_progress: Default::default(),
progress: Default::default(),
}
}
pub async fn update(&self) {
let Some(asset_name) = gui_asset_name() else {
info!("GUI updates are not supported on this platform.");
return;
};
info!("Update GUI, version: {}", self.version);
#[cfg(debug_assertions)]
@@ -396,8 +95,15 @@ impl GuiUpdater {
format!("v{}", self.version)
};
let file_url =
format!("https://github.com/yuezk/GlobalProtect-openconnect/releases/download/{release_tag}/{asset_name}");
#[cfg(target_arch = "x86_64")]
let arch = "x86_64";
#[cfg(target_arch = "aarch64")]
let arch = "aarch64";
let file_url = format!(
"https://github.com/yuezk/GlobalProtect-openconnect/releases/download/{}/gpgui_{}.bin.tar.xz",
release_tag, arch
);
let checksum_url = format!("{}.sha256", file_url);
info!("Downloading file: {}", file_url);
@@ -406,23 +112,15 @@ impl GuiUpdater {
let cf = ChecksumFetcher::new(&checksum_url);
let notifier = Arc::clone(&self.notifier);
let progress_ref = Arc::clone(&self.progress);
dl.on_progress(move |progress| {
// Save progress to shared state so that it can be notified to the UI when needed
if let Ok(mut guard) = progress_ref.try_write() {
*guard = progress;
}
notifier.notify(progress);
});
dl.on_progress(move |progress| notifier.notify(progress));
self.set_in_progress(true);
let res = tokio::try_join!(dl.download(), cf.fetch());
let (file, checksum) = match res {
Ok((file, checksum)) => (file, checksum),
Err(err) => {
warn!("Download error: {}", err);
self.notify_error();
self.notifier.notify_error();
return;
}
};
@@ -432,7 +130,7 @@ impl GuiUpdater {
if let Err(err) = verify_checksum(&file_path, &checksum) {
warn!("Checksum error: {}", err);
self.notify_error();
self.notifier.notify_error();
return;
}
@@ -440,233 +138,10 @@ impl GuiUpdater {
if let Err(err) = self.installer.install(&file_path, &checksum).await {
warn!("Install error: {}", err);
self.notify_error();
self.notifier.notify_error();
} else {
info!("Install success");
self.notify_done();
self.notifier.notify_done();
}
}
pub fn is_in_progress(&self) -> bool {
if let Ok(guard) = self.in_progress.try_read() {
*guard
} else {
info!("Failed to acquire in_progress lock");
false
}
}
fn set_in_progress(&self, in_progress: bool) {
if let Ok(mut guard) = self.in_progress.try_write() {
*guard = in_progress;
} else {
info!("Failed to acquire in_progress lock");
}
}
fn notify_error(&self) {
self.set_in_progress(false);
self.notifier.notify_error();
}
fn notify_done(&self) {
self.set_in_progress(false);
self.notifier.notify_done();
}
pub fn notify_progress(&self) {
let progress = if let Ok(guard) = self.progress.try_read() {
*guard
} else {
info!("Failed to acquire progress lock");
None
};
self.notifier.notify(progress);
}
}
#[cfg(test)]
mod tests {
use gpapi::{
os_profile::HostIdentity,
service::{
transport::{ClientPrelude, NoiseResponder},
vpn_env::{HostInfo, VpnEnv},
vpn_state::VpnState,
},
};
use tokio::net::TcpListener;
use tokio_tungstenite::accept_async;
use super::*;
#[test]
fn selects_platform_specific_gui_assets() {
assert_eq!(
gui_asset_name_for("linux", "x86_64", ""),
Some("gpgui_x86_64.bin.tar.xz".to_owned())
);
assert_eq!(
gui_asset_name_for("linux", "aarch64", "-musl"),
Some("gpgui_aarch64-musl.bin.tar.xz".to_owned())
);
assert_eq!(
gui_asset_name_for("freebsd", "x86_64", ""),
Some("gpgui_freebsd_amd64.bin.tar.xz".to_owned())
);
assert_eq!(
gui_asset_name_for("openbsd", "aarch64", ""),
Some("gpgui_openbsd_arm64.bin.tar.xz".to_owned())
);
assert_eq!(gui_asset_name_for("macos", "aarch64", ""), None);
}
#[tokio::test]
async fn pending_install_reconnects_with_a_fresh_handshake() {
let credential = Arc::new(SessionCredential::generate(Uuid::new_v4(), env!("CARGO_PKG_VERSION")).unwrap());
let (command_tx, mut commands) = mpsc::channel(1);
let (reply_tx, reply_rx) = oneshot::channel();
command_tx
.send(InstallCommand {
request: UpdateGuiRequest {
path: "/tmp/gpgui-update".to_owned(),
checksum: "checksum".to_owned(),
},
reply: reply_tx,
})
.await
.unwrap();
let (_lease_tx, mut credential_lease) = watch::channel(true);
let mut pending = None;
let (first_endpoint, first_service) = spawn_test_service(Arc::clone(&credential), false).await;
let (mut socket, mut noise) = connect_installer_at(&credential, &first_endpoint).await.unwrap();
assert!(
run_installer_connection(
&mut socket,
&mut noise,
&mut credential_lease,
&mut commands,
&mut pending,
)
.await
.is_err()
);
first_service.await.unwrap();
assert!(pending.is_some());
let (second_endpoint, second_service) = spawn_test_service(Arc::clone(&credential), true).await;
let (mut socket, mut noise) = connect_installer_at(&credential, &second_endpoint).await.unwrap();
assert!(
run_installer_connection(
&mut socket,
&mut noise,
&mut credential_lease,
&mut commands,
&mut pending,
)
.await
.is_err()
);
second_service.await.unwrap();
assert!(pending.is_none());
assert!(reply_rx.await.unwrap().is_ok());
}
#[tokio::test]
async fn credential_version_mismatch_is_terminal() {
let credential = SessionCredential::generate(Uuid::new_v4(), "different-version").unwrap();
let Err(err) = connect_installer_at(&credential, "ws://127.0.0.1:1/ws").await else {
panic!("version mismatch should fail before connecting");
};
assert!(err.is::<TerminalConnectError>());
}
async fn spawn_test_service(
credential: Arc<SessionCredential>,
reply: bool,
) -> (String, tokio::task::JoinHandle<()>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let endpoint = format!("ws://{}/ws", listener.local_addr().unwrap());
let service = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let mut socket = accept_async(stream).await.unwrap();
let prelude = match socket.next().await.unwrap().unwrap() {
Message::Binary(data) => ClientPrelude::decode(&data).unwrap(),
frame => panic!("unexpected prelude frame: {frame:?}"),
};
assert_eq!(prelude.service_instance_id, credential.service_instance_id());
assert_eq!(prelude.session_id, credential.session_id());
socket
.send(Message::Binary(ServerPrelude::Ready.encode().unwrap().into()))
.await
.unwrap();
let mut responder = NoiseResponder::new(
credential.product_version(),
credential.service_instance_id(),
credential.session_id(),
credential.secret(),
)
.unwrap();
let first = match socket.next().await.unwrap().unwrap() {
Message::Binary(data) => data,
frame => panic!("unexpected handshake frame: {frame:?}"),
};
responder.read_first(&first).unwrap();
let (response, mut noise) = responder.write_response().unwrap();
socket.send(Message::Binary(response.into())).await.unwrap();
let attach = match socket.next().await.unwrap().unwrap() {
Message::Binary(data) => data,
frame => panic!("unexpected attach frame: {frame:?}"),
};
assert!(matches!(
noise.decrypt::<ClientMessage>(&attach).unwrap(),
ClientMessage::Attach { .. }
));
let attached = ServerMessage::Attached {
connection_id: Uuid::new_v4(),
current_revision: 0,
snapshot: VpnEnv {
vpn_state: VpnState::Disconnected,
vpnc_script: None,
auth_executable: String::new(),
host_info: HostInfo {
host_identity: HostIdentity::collect(),
},
},
};
socket
.send(Message::Binary(noise.encrypt(&attached).unwrap().into()))
.await
.unwrap();
let request = match socket.next().await.unwrap().unwrap() {
Message::Binary(data) => noise.decrypt::<ClientMessage>(&data).unwrap(),
frame => panic!("unexpected request frame: {frame:?}"),
};
let ClientMessage::Request {
id,
request: WsRequest::UpdateGui(update),
} = request
else {
panic!("unexpected installer request");
};
assert_eq!(update.path, "/tmp/gpgui-update");
if reply {
let message = ServerMessage::Reply {
id,
result: ServiceResult::Accepted,
};
socket
.send(Message::Binary(noise.encrypt(&message).unwrap().into()))
.await
.unwrap();
}
socket.close(None).await.unwrap();
});
(endpoint, service)
}
}
+34 -25
View File
@@ -1,43 +1,52 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"$schema": "../node_modules/@tauri-apps/cli/schema.json",
"build": {
"beforeDevCommand": "pnpm dev",
"beforeBuildCommand": "pnpm build",
"devUrl": "http://localhost:1421",
"frontendDist": "../dist"
"devPath": "http://localhost:1421",
"distDir": "../dist",
"withGlobalTauri": false
},
"identifier": "com.yuezk.gpgui-helper",
"productName": "gpgui-helper",
"app": {
"withGlobalTauri": false,
"package": {
"productName": "gpgui-helper"
},
"tauri": {
"allowlist": {
"all": false,
"window": {
"all": false,
"startDragging": true
}
},
"bundle": {
"active": false,
"targets": "deb",
"identifier": "com.yuezk.gpgui-helper",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/[email protected]",
"icons/icon.icns",
"icons/icon.ico"
]
},
"security": {
"csp": null
},
"windows": [
{
"title": "GPGUI Downloader",
"title": "GlobalProtect GUI Helper",
"center": true,
"resizable": true,
"width": 460,
"height": 104,
"minWidth": 460,
"minHeight": 104,
"maxWidth": 460,
"maxHeight": 104,
"width": 500,
"height": 100,
"minWidth": 500,
"minHeight": 100,
"maxWidth": 500,
"maxHeight": 100,
"label": "main",
"decorations": false
}
]
},
"bundle": {
"active": false,
"targets": "deb",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/[email protected]",
"icons/icon.icns",
"icons/icon.ico"
]
}
}
@@ -1,43 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
<defs>
<linearGradient id="ocean" x1="245" y1="170" x2="770" y2="770" gradientUnits="userSpaceOnUse">
<stop stop-color="#579bc1"/>
<stop offset=".52" stop-color="#438fbd"/>
<stop offset="1" stop-color="#2f719e"/>
</linearGradient>
<linearGradient id="land" x1="260" y1="190" x2="750" y2="735" gradientUnits="userSpaceOnUse">
<stop stop-color="#56c78a"/>
<stop offset=".55" stop-color="#3bbf78"/>
<stop offset="1" stop-color="#279b5d"/>
</linearGradient>
<linearGradient id="lock" x1="385" y1="400" x2="650" y2="700" gradientUnits="userSpaceOnUse">
<stop stop-color="#f3b84c"/>
<stop offset=".55" stop-color="#e8a12f"/>
<stop offset="1" stop-color="#d4871e"/>
</linearGradient>
<clipPath id="globe-clip">
<circle cx="512" cy="455" r="315"/>
</clipPath>
</defs>
<g transform="translate(512 512) scale(1.3) translate(-512 -455)">
<circle cx="512" cy="455" r="315" fill="url(#ocean)"/>
<g clip-path="url(#globe-clip)" fill="url(#land)">
<path d="M177 326c74-121 177-185 302-190-13 51-49 84-105 98-4 45-32 79-86 101-37 17-75 14-111-9Z"/>
<path d="M564 135c129 18 229 103 273 220-69-3-121 15-157 54-51-14-83-50-95-107-38-36-45-92-21-167Z"/>
<path d="M189 467c63-39 125-34 187 16 57 25 73 73 48 144-45 90-108 146-189 166-58-88-73-197-46-326Z"/>
<path d="M612 572c78-38 157-18 238 59-45 89-122 144-231 164-20-67-22-122-7-165-22-17-22-36 0-58Z"/>
</g>
<circle cx="512" cy="455" r="308" fill="none" stroke="#9ccde2" stroke-width="11" stroke-opacity=".4"/>
<g transform="translate(512 490) scale(.82) translate(-512 -490)">
<path d="M405 429v-75c0-142 214-142 214 0v75" fill="none" stroke="#eef1f2" stroke-width="58" stroke-linecap="round"/>
<rect x="340" y="403" width="344" height="278" rx="62" fill="url(#lock)"/>
<rect x="346" y="409" width="332" height="266" rx="56" fill="none" stroke="#f7cb75" stroke-width="10" stroke-opacity=".45"/>
<g fill="#85500f" opacity=".85">
<path d="M501 538h22l16 69h-54Z"/>
<circle cx="512" cy="521" r="27"/>
</g>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 2.2 KiB

+99
View File
@@ -0,0 +1,99 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
version="1.1"
id="Layer_1"
x="0px"
y="0px"
viewBox="0 0 96 96"
style="enable-background:new 0 0 96 96;"
xml:space="preserve"
sodipodi:docname="com.yuezk.qt.gpclient.svg"
inkscape:version="0.92.4 5da689c313, 2019-01-14"><metadata
id="metadata14"><rdf:RDF><cc:Work
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
id="defs12" /><sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="1920"
inkscape:window-height="1006"
id="namedview10"
showgrid="false"
inkscape:zoom="6.9532168"
inkscape:cx="7.9545315"
inkscape:cy="59.062386"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:current-layer="g8499" />
<style
type="text/css"
id="style2">
.st0{fill:#2980B9;}
.st1{fill:#3498DB;}
.st2{fill:#2ECC71;}
.st3{fill:#27AE60;}
</style>
<g
id="g8499"
transform="matrix(1.3407388,0,0,1.3407388,-16.409202,-16.355463)"><g
id="XMLID_1_">
<circle
r="32.5"
cy="48"
cx="48"
class="st0"
id="XMLID_3_"
style="fill:#2980b9" />
<path
d="m 48,15.5 v 65 C 65.9,80.5 80.5,65.7 80.5,48 80.5,30 65.9,15.5 48,15.5 Z"
class="st1"
id="XMLID_4_"
inkscape:connector-curvature="0"
style="fill:#3498db" />
<path
d="m 48,15.5 v 0.6 l 1.2,-0.3 c 0.3,-0.3 0.4,-0.3 0.6,-0.3 h -1.1 z m 7.3,0.9 c -0.1,0 0.4,0.9 1.1,1.8 0.8,1.5 1.1,2.1 1.3,2.1 0.3,-0.3 1.9,-1.2 3,-2.1 -1.7,-0.9 -3.5,-1.5 -5.4,-1.8 z m 10.3,6.2 c -0.1,0 -0.4,0 -0.9,0.6 l -0.8,0.9 0.6,0.6 c 0.3,0.6 0.8,0.9 1,1.2 0.5,0.6 0.6,0.6 0.1,1.5 -0.2,0.6 -0.3,0.9 -0.3,0.9 0.1,0.3 0.3,0.3 1.4,0.3 h 1.6 c 0.1,0 0.3,-0.6 0.4,-1.2 l 0.1,-0.9 -1.1,-0.9 c -1,-0.9 -1,-0.9 -1.4,-1.8 -0.3,-0.6 -0.6,-1.2 -0.7,-1.2 z m -3,2.4 c -0.2,0 -1.3,2.1 -1.3,2.4 0,0 0.3,0.6 0.7,0.9 0.4,0.3 0.7,0.6 0.7,0.6 0.1,0 1.2,-1.2 1.4,-1.5 C 64.2,27.1 64,26.8 63.5,26.2 63.1,25.5 62.7,25 62.6,25 Z m 9.5,1.1 0.2,0.3 c 0,0.3 -0.7,0.9 -1.4,1.5 -1.2,0.9 -1.4,1.2 -2,1.2 -0.6,0 -0.9,0.3 -1.8,0.9 -0.6,0.6 -1.2,0.9 -1.2,1.2 0,0 0.2,0.3 0.6,0.9 0.7,0.6 0.7,0.9 0.2,1.8 l -0.4,0.3 h -1.1 c -0.6,0 -1.5,0 -1.8,-0.3 -0.9,0 -0.8,0 -0.1,2.1 1,3 1.1,3.2 1.3,3.2 0.1,0 1.3,-1.2 2.8,-2.4 1.5,-1.2 2.7,-2.4 2.8,-2.4 l 0.6,0.3 c 0.4,0.3 0.5,0 1.3,-0.6 l 0.8,-0.6 0.8,0.6 c 1.9,1.2 2.2,1.5 2.3,2.4 0.2,1.5 0.3,1.8 0.5,1.8 0.1,0 1.3,-1.5 1.6,-1.8 0.1,-0.3 -0.1,-0.6 -1.1,-2.1 -0.7,-0.9 -1.1,-1.8 -1.1,-2.1 0,0 0.1,0 0.3,-0.3 0.2,0 0.4,0.3 1,0.9 -1.6,-2.3 -3.2,-4.7 -5.1,-6.8 z m 2.8,10.7 c -0.2,0 -0.9,0.9 -0.8,1.2 l 0.5,0.3 H 75 c 0.2,0 0.3,0 0.2,-0.3 C 75.1,37.4 75,36.8 74.9,36.8 Z M 72.3,38 h -2.4 l -2.4,0.3 -4.5,3.5 -4.4,3.8 v 3.5 c 0,2.1 0,3.8 0.1,3.8 0.1,0 0.7,0.9 1.5,1.5 0.8,0.9 1.5,1.5 1.8,1.8 0.4,0.3 0.5,0.3 4,0.6 l 3.4,0.3 1.6,0.9 c 0.8,0.6 1.5,1.2 1.6,1.2 0.1,0 -0.3,0.3 -0.6,0.6 l -0.6,0.6 1,1.2 c 0.5,0.6 1.3,1.5 1.7,1.8 l 0.6,0.9 v 1.7 0.9 c 3.7,-5 5.9,-11.5 6.1,-18.3 0.1,-2.7 -0.3,-5.3 -0.8,-8 l -0.6,-0.3 c -0.1,0 -0.5,0.3 -1,0.6 -0.5,0.3 -1,0.9 -1.1,0.9 -0.1,0 -0.8,-0.3 -1.8,-0.6 l -1.8,-0.6 v -0.9 c 0,-0.6 0,-0.9 -0.6,-1.5 z M 48,63.7 V 64 h 0.2 z"
class="st2"
id="XMLID_13_"
inkscape:connector-curvature="0"
style="fill:#2ecc71" />
<path
d="m 48,15.5 c -3.1,0 -6.2,0.5 -9,1.3 0.3,0.4 0.3,0.4 0.6,0.9 1.5,2.5 1.7,2.8 2.1,2.9 0.3,0 0.9,0.1 1.6,0.1 h 1.2 l 0.9,-2 0.8,-1.9 1.8,-0.6 z m -16.9,4.7 c -2.8,1.7 -5.4,3.9 -7.6,6.4 -3.8,4.3 -6.3,9.6 -7.4,15.4 0.5,0 0.9,-0.1 1.8,-0.1 2.8,0.1 2.5,0 3.4,1.4 0.5,0.8 0.6,0.8 1.4,0.8 1,0.1 0.9,0 0.5,-1.6 -0.2,-0.6 -0.3,-1.2 -0.3,-1.4 0,-0.2 0.5,-0.7 1.7,-1.6 1.9,-1.5 1.8,-1.3 1.5,-2.9 -0.1,-0.3 0.1,-0.6 0.6,-1.2 0.7,-0.7 0.7,-0.6 1.4,-0.6 h 0.7 l 0.1,-1.2 c 0.1,-0.7 0.1,-1.3 0.2,-1.3 0,0 1.9,-1.1 4.1,-2.3 2.2,-1.2 4.1,-2.2 4.2,-2.3 0.2,-0.2 -0.3,-0.8 -2.7,-3.8 -1.5,-1.9 -2.8,-3.6 -2.9,-3.7 z m -5.8,23 c -0.1,0 -0.1,0.3 -0.1,0.6 0,0.6 0,0.7 0.6,1 0.8,0.4 0.9,0.5 0.8,0.2 -0.1,-0.4 -1.2,-1.9 -1.3,-1.8 z m -3.4,2.1 -0.5,1.8 c 0.1,0.1 0.9,0.3 1.8,0.5 1,0.2 1.6,0.4 1.8,0.3 l 0.5,-1.3 z m -3.8,1 -1.1,0.6 c -0.6,0.3 -1.2,0.6 -1.4,0.6 h -0.1 c 0,1.4 0.1,2.8 0.3,4.2 l 0.6,0.4 1,-0.1 h 1 l 0.6,1.4 c 0.3,0.7 0.7,1.4 0.8,1.5 0.1,0.1 1,0.1 1.8,0.1 h 1.5 L 23,56.2 c 0,1.2 0,1.3 -0.6,2.2 -0.4,0.5 -0.6,1.2 -0.6,1.4 0,0.2 0.7,2.1 1.6,4.3 l 1.5,4 1.6,0.8 c 1.2,0.6 1.5,0.8 1.5,1 0,0.1 -0.4,2.1 -0.6,3.1 3,2.5 6.4,4.5 10.2,5.8 3.5,-3.6 6.8,-7.1 7.3,-7.6 l 0.7,-0.7 0.2,-1.9 c 0.2,-1.1 0.4,-2.1 0.4,-2.2 0,-0.1 0.5,-0.6 1,-1.2 0.5,-0.5 0.8,-1 0.8,-1.1 v -0.2 c -0.1,-0.1 -1.4,-1.1 -3,-2.2 l -3.1,-2.1 -1.1,-0.1 c -0.8,0 -1.2,0 -1.3,-0.2 C 39.4,59.2 39.2,58.5 39.1,57.7 39,56.9 38.9,56.2 38.8,56.1 38.8,56 38,56 37.1,56 36.2,56 35.4,55.9 35.3,55.8 35.2,55.7 35.2,55.1 35.1,54.3 35,53.6 34.9,53 34.8,52.9 34.7,52.8 33.7,52.7 32.5,52.6 30.5,52.5 30.1,52.5 29.1,52 l -1.2,-0.6 -1.6,0.7 -1.7,0.9 -1.8,-0.1 c -2,0 -1.9,0.2 -2.1,-1.6 C 20.6,50.7 20.6,50.1 20.5,50.1 20.4,50 20,50 19.6,49.9 L 18.9,49.7 19,49.2 c 0,-0.3 0,-1 0.1,-1.4 L 19.2,47 18.7,46.5 Z m 9.1,1.1 C 27.1,47.5 27.1,47.8 27,48 l -0.1,0.5 2.9,1.2 c 2.9,1.1 3.4,1.2 3.9,0.7 0.2,-0.2 0.1,-0.2 -0.3,-0.4 -0.3,-0.1 -1.7,-0.9 -3.2,-1.6 -1.7,-0.7 -2.9,-1.1 -3,-1 z"
class="st3"
id="XMLID_20_"
inkscape:connector-curvature="0"
style="fill:#27ae60" />
</g><g
transform="matrix(1.458069,0,0,1.458069,-22.631538,-19.615144)"
id="g7664"><path
inkscape:connector-curvature="0"
id="XMLID_6_"
class="st3"
d="m 38.8,56.1 c 0,1.2 1,2.2 2.2,2.2 h 15.2 c 1.2,0 2.2,-1 2.2,-2.2 V 45.3 c 0,-1.2 -1,-2.2 -2.2,-2.2 H 40.9 c -1.2,0 -2.2,1 -2.2,2.2 v 10.8 z"
style="fill:#f1aa27;fill-opacity:1" /><path
style="fill:#e6e6e6"
inkscape:connector-curvature="0"
id="XMLID_7_"
class="st4"
d="m 55.5,43.1 h -3.3 v -3.7 c 0,-2.1 -1.7,-3.8 -3.8,-3.8 -2.1,0 -3.8,1.7 -3.8,3.8 v 3.8 h -3.1 v -3.8 c 0,-3.9 3.2,-7 7,-7 3.9,0 7,3.2 7,7 z" /><path
style="fill:#e6e6e6;fill-opacity:1"
inkscape:connector-curvature="0"
id="XMLID_8_"
class="st5"
d="m 50.35,48.2 c 0,-1 -0.8,-1.8 -1.8,-1.8 -1,0 -1.8,0.8 -1.8,1.8 0,0.7 0.4,1.3 1,1.6 l -1,5.2 h 3.6 l -1,-5.2 c 0.6,-0.3 1,-0.9 1,-1.6 z" /></g></g></svg>

After

Width:  |  Height:  |  Size: 6.7 KiB

+100 -86
View File
@@ -1,117 +1,131 @@
import { getCurrentWindow } from "@tauri-apps/api/window";
import logo from "../../assets/icon-small.svg";
import { Box, Button, CssBaseline, LinearProgress, Typography } from "@mui/material";
import { appWindow } from "@tauri-apps/api/window";
import logo from "../../assets/icon.svg";
import { useEffect, useState } from "react";
import "./styles.css";
const appWindow = getCurrentWindow();
export default function App() {
const [error, setError] = useState(false);
function useUpdateProgress() {
const [progress, setProgress] = useState<number | null>(null);
useEffect(() => {
const unlisteners: Array<() => void> = [];
let disposed = false;
const startUpdate = async () => {
const progressUnlisten = await appWindow.listen("app://update-progress", (event) => {
setProgress(event.payload as number);
});
const errorUnlisten = await appWindow.listen("app://update-error", () => {
setError(true);
});
if (disposed) {
progressUnlisten();
errorUnlisten();
return;
}
unlisteners.push(progressUnlisten, errorUnlisten);
await appWindow.emit("app://update");
};
void startUpdate();
const unlisten = appWindow.listen("app://update-progress", (event) => {
setProgress(event.payload as number);
});
return () => {
disposed = true;
unlisteners.forEach((unlisten) => unlisten());
unlisten.then((unlisten) => unlisten());
};
}, []);
return progress;
}
export default function App() {
const [error, setError] = useState(false);
useEffect(() => {
const unlisten = appWindow.listen("app://update-error", () => {
setError(true);
});
return () => {
unlisten.then((unlisten) => unlisten());
};
}, []);
const handleRetry = () => {
setError(false);
setProgress(null);
appWindow.emit("app://update");
};
return (
<div className="update-window" data-tauri-drag-region>
<img src={logo} alt="" className="update-logo" data-tauri-drag-region />
<div className="update-content" data-tauri-drag-region>
{error ? (
<DownloadFailed onRetry={handleRetry} />
) : (
<DownloadIndicator progress={progress} />
)}
</div>
</div>
<>
<CssBaseline />
<Box
sx={{ position: "absolute", inset: 0 }}
display="flex"
alignItems="center"
px={2}
data-tauri-drag-region
>
<Box display="flex" alignItems="center" flex="1" data-tauri-drag-region>
<Box
component="img"
src={logo}
alt="logo"
sx={{ width: "4rem", height: "4rem" }}
data-tauri-drag-region
/>
<Box flex={1} ml={2}>
{error ? <DownloadFailed onRetry={handleRetry} /> : <DownloadIndicator />}
</Box>
</Box>
</Box>
</>
);
}
function DownloadIndicator({ progress }: { progress: number | null }) {
function DownloadIndicator() {
const progress = useUpdateProgress();
return (
<div className="update-status" data-tauri-drag-region>
<h1 className="update-title" data-tauri-drag-region>
Getting GP Connect ready
</h1>
<DownloadProgress value={progress} />
</div>
<>
<Typography variant="h1" fontSize="1rem" data-tauri-drag-region>
Updating the GUI components...
</Typography>
<Box mt={1}>
<LinearProgressWithLabel value={progress} />
</Box>
</>
);
}
function DownloadFailed({ onRetry }: { onRetry: () => void }) {
return (
<div className="update-status error-status" data-tauri-drag-region>
<div className="error-copy" role="alert" data-tauri-drag-region>
<h1 className="update-title" data-tauri-drag-region>
Couldn’t get GP Connect ready
</h1>
<p className="update-description" data-tauri-drag-region>
Please try again.
</p>
</div>
<button type="button" onClick={onRetry} className="retry-button">
Retry
</button>
</div>
);
}
function DownloadProgress({ value }: { value: number | null }) {
const isDeterminate = value !== null;
return (
<>
<div className="progress-summary" data-tauri-drag-region>
<p className="update-description" data-tauri-drag-region>
This should only take a moment.
</p>
<span className="progress-label" aria-hidden="true">
{isDeterminate ? `${Math.round(value)}%` : "In progress"}
</span>
</div>
<div
className={`progress-bar${isDeterminate ? "" : " progress-bar-indeterminate"}`}
role="progressbar"
aria-label="Update progress"
aria-valuemin={isDeterminate ? 0 : undefined}
aria-valuemax={isDeterminate ? 100 : undefined}
aria-valuenow={isDeterminate ? Math.round(value) : undefined}
>
<div className="progress-fill" style={isDeterminate ? { width: `${value}%` } : undefined} />
</div>
<Typography variant="h1" fontSize="1rem" data-tauri-drag-region>
Failed to update the GUI components.
</Typography>
<Box mt={1} data-tauri-drag-region>
<Button
variant="contained"
color="primary"
size="small"
onClick={onRetry}
sx={{
textTransform: "none",
}}
>
Retry
</Button>
</Box>
</>
);
}
function LinearProgressWithLabel(props: { value: number | null }) {
const { value } = props;
return (
<Box sx={{ display: "flex", alignItems: "center" }}>
<Box flex="1">
<LinearProgress
variant={value === null ? "indeterminate" : "determinate"}
value={value ?? 0}
sx={{
py: 1.2,
".MuiLinearProgress-bar": {
transition: "none",
},
}}
/>
</Box>
{value !== null && (
<Box sx={{ minWidth: 35, textAlign: "right", ml: 1 }}>
<Typography variant="body2" color="text.secondary">{`${Math.round(value)}%`}</Typography>
</Box>
)}
</Box>
);
}
@@ -1,173 +1,10 @@
html,
body,
#root {
box-sizing: border-box;
height: 100%;
margin: 0;
padding: 0;
overflow: hidden;
-webkit-user-select: none;
user-select: none;
cursor: default;
}
body {
background: #f6f5f4;
color: #2e3436;
font-family:
Inter,
ui-sans-serif,
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
sans-serif;
}
button {
font: inherit;
}
.update-window {
box-sizing: border-box;
display: flex;
align-items: center;
width: 100%;
height: 100%;
padding: 16px 18px;
gap: 15px;
background: #f6f5f4;
}
.update-logo {
flex: 0 0 auto;
width: 48px;
height: 48px;
}
.update-content,
.update-status {
min-width: 0;
width: 100%;
}
.update-title {
margin: 0;
color: #2e3436;
font-size: 16px;
font-weight: 600;
line-height: 1.25;
letter-spacing: -0.01em;
}
.update-description {
margin: 3px 0 0;
color: #5e5c64;
font-size: 12px;
line-height: 1.4;
}
.progress-summary {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-top: 3px;
}
.progress-summary .update-description {
margin: 0;
}
.progress-bar {
position: relative;
width: 100%;
height: 6px;
margin-top: 9px;
overflow: hidden;
border-radius: 3px;
background-color: #d5d3d1;
}
.progress-fill {
height: 100%;
border-radius: 3px;
background: #3584e4;
transition: width 180ms ease-out;
}
.progress-bar-indeterminate .progress-fill {
width: 35%;
animation: progress-indeterminate 1.4s ease-in-out infinite;
}
@keyframes progress-indeterminate {
from {
transform: translateX(-110%);
}
to {
transform: translateX(300%);
}
}
@media (prefers-reduced-motion: reduce) {
.progress-fill {
transition: none;
}
.progress-bar-indeterminate .progress-fill {
animation: none;
transform: translateX(90%);
}
}
.progress-label {
flex: 0 0 auto;
color: #3d3846;
font-size: 12px;
font-variant-numeric: tabular-nums;
font-weight: 500;
text-align: right;
white-space: nowrap;
}
.error-status {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
}
.error-status .update-title {
color: #9c2f2f;
}
.error-copy {
min-width: 0;
}
.retry-button {
min-width: 68px;
padding: 4px 14px;
border: 0;
border-radius: 8px;
background: #1c71d8;
color: #ffffff;
cursor: pointer;
font-size: 12px;
font-weight: 600;
line-height: 1.5;
}
.retry-button:hover {
background: #1a5fb4;
}
.retry-button:active {
background: #174a8b;
}
.retry-button:focus-visible {
outline: 2px solid #1a5fb4;
outline-offset: 2px;
}
+2 -2
View File
@@ -20,9 +20,9 @@ export default defineConfig(async () => {
// https://tauri.app/v1/api/config#buildconfig.beforedevcommand
envPrefix: ["VITE_", "TAURI_"],
build: {
rolldownOptions: {
rollupOptions: {
input: {
main: resolve(import.meta.dirname, "index.html"),
main: resolve(__dirname, "index.html"),
},
},
},
+1 -18
View File
@@ -5,11 +5,7 @@ edition.workspace = true
license.workspace = true
[dependencies]
common = { path = "../../crates/common" }
gpapi = { path = "../../crates/gpapi", features = ["clap", "logger"] }
gphip = { path = "../../crates/gphip" }
base64.workspace = true
sha256.workspace = true
gpapi = { path = "../../crates/gpapi" }
openconnect = { path = "../../crates/openconnect" }
clap.workspace = true
anyhow.workspace = true
@@ -24,16 +20,3 @@ log.workspace = true
compile-time.workspace = true
xz2 = "0.1"
tar = "0.4"
thiserror.workspace = true
uuid = { workspace = true, features = ["v4"] }
zeroize.workspace = true
tempfile.workspace = true
getrandom = "0.4"
mac_address = "1"
[target.'cfg(unix)'.dependencies]
nix = { version = "0.31", features = ["fs", "socket", "user"] }
[dev-dependencies]
openssl.workspace = true
tokio-tungstenite = "0.29"
-69
View File
@@ -1,69 +0,0 @@
use std::{env, fs, path::PathBuf, process::Command};
const UNKNOWN_COMMIT: &str = "unknown";
const DISPLAY_COMMIT_LEN: usize = 9;
fn main() {
// Installed OpenConnect lives in the private ../lib/gpclient directory.
// Build executables also locate their exact Cargo library; installers remove that rpath.
#[cfg(target_os = "macos")]
{
println!("cargo:rustc-link-arg=-Wl,-rpath,@executable_path/../lib/gpclient");
let library_dir = env::var("DEP_OPENCONNECT_LIB_DIR").expect("OpenConnect exports its build library directory");
println!("cargo:rustc-link-arg=-Wl,-rpath,{library_dir}");
}
println!("cargo:rerun-if-env-changed=GPSERVICE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=SOURCE_GIT_COMMIT");
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
let repo_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set")).join("../..");
let source_commit = repo_root.join("SOURCE_COMMIT");
println!("cargo:rerun-if-changed={}", source_commit.display());
println!(
"cargo:rustc-env=GPSERVICE_GIT_COMMIT={}",
resolve_commit(&repo_root, &source_commit)
);
}
fn resolve_commit(repo_root: &PathBuf, source_commit: &PathBuf) -> String {
env_commit("GPSERVICE_GIT_COMMIT")
.or_else(|| env_commit("SOURCE_GIT_COMMIT"))
.or_else(|| env_commit("GITHUB_SHA"))
.or_else(|| file_commit(source_commit))
.or_else(|| git_commit(repo_root))
.unwrap_or_else(|| UNKNOWN_COMMIT.to_string())
}
fn env_commit(key: &str) -> Option<String> {
env::var(key).ok().and_then(|value| normalize_commit(&value))
}
fn file_commit(path: &PathBuf) -> Option<String> {
fs::read_to_string(path).ok().and_then(|value| normalize_commit(&value))
}
fn git_commit(repo_root: &PathBuf) -> Option<String> {
let output = Command::new("git")
.args(["rev-parse", "--short=9", "HEAD"])
.current_dir(repo_root)
.output()
.ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout)
.ok()
.and_then(|value| normalize_commit(&value))
}
fn normalize_commit(value: &str) -> Option<String> {
let value = value.trim();
if value.is_empty() {
return None;
}
Some(value.chars().take(DISPLAY_COMMIT_LEN).collect())
}
@@ -1,10 +0,0 @@
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[path = "privileged_unix.rs"]
mod platform;
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
#[path = "unsupported.rs"]
mod platform;
fn main() {
platform::run();
}
@@ -1,56 +0,0 @@
use std::io::Read;
use anyhow::{Context, ensure};
use clap::{Parser, Subcommand};
use gpservice::hip_approval::{self, InstallRequest};
use nix::unistd::Uid;
const MAX_INSTALL_REQUEST_SIZE: u64 = 2 * 1024 * 1024;
#[derive(Parser)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
Install,
Revoke { approval_id: String },
}
fn try_run() -> anyhow::Result<()> {
ensure!(Uid::effective().is_root(), "HIP script installer must run as root");
let approving_uid = std::env::var("PKEXEC_UID")
.context("HIP script installer requires pkexec authorization")?
.parse::<u32>()
.context("Invalid pkexec user identity")?;
ensure!(approving_uid != 0, "HIP script installer requires a desktop user");
match Cli::parse().command {
Command::Install => {
let mut input = Vec::new();
std::io::stdin()
.lock()
.take(MAX_INSTALL_REQUEST_SIZE + 1)
.read_to_end(&mut input)?;
ensure!(
input.len() as u64 <= MAX_INSTALL_REQUEST_SIZE,
"HIP install request is too large"
);
let request: InstallRequest = serde_json::from_slice(&input).context("Invalid HIP install request")?;
let info = hip_approval::install(request, approving_uid)?;
serde_json::to_writer(std::io::stdout().lock(), &info)?;
println!();
}
Command::Revoke { approval_id } => hip_approval::revoke(&approval_id, approving_uid)?,
}
Ok(())
}
pub(super) fn run() {
if let Err(err) = try_run() {
eprintln!("HIP approval failed: {err:#}");
std::process::exit(1);
}
}
@@ -1,4 +0,0 @@
pub(super) fn run() {
eprintln!("Root HIP script approvals are unavailable on this platform");
std::process::exit(1);
}
@@ -1,10 +0,0 @@
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
#[path = "privileged_unix.rs"]
mod platform;
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))]
#[path = "unsupported.rs"]
mod platform;
fn main() {
platform::run();
}
@@ -1,42 +0,0 @@
use std::io::Read;
use anyhow::bail;
use clap::{Parser, Subcommand};
use gpapi::service::vpnc_script::InstallVpncScriptRequest;
use nix::unistd::Uid;
const MAX_INSTALL_REQUEST_SIZE: u64 = 2 * 1024 * 1024;
#[derive(Parser)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
Install,
Remove,
}
fn try_run() -> anyhow::Result<()> {
if !Uid::effective().is_root() {
bail!("The VPNC script installer must run as root");
}
match Cli::parse().command {
Command::Install => {
let input = std::io::stdin().lock().take(MAX_INSTALL_REQUEST_SIZE);
let request = serde_json::from_reader::<_, InstallVpncScriptRequest>(input)?;
gpservice::vpnc_script::install(request)
}
Command::Remove => gpservice::vpnc_script::remove(),
}
}
pub(super) fn run() {
if let Err(err) = try_run() {
eprintln!("Error: {err:#}");
std::process::exit(1);
}
}
@@ -1,4 +0,0 @@
pub(super) fn run() {
eprintln!("The VPNC script installer is only available on Linux, FreeBSD, and OpenBSD");
std::process::exit(1);
}
+102 -279
View File
@@ -1,227 +1,86 @@
use std::io::Write;
use std::path::PathBuf;
use std::sync::{Arc, atomic::AtomicBool};
#[cfg(target_os = "macos")]
use std::time::Duration;
use std::sync::Arc;
use std::{collections::HashMap, io::Write};
use anyhow::{Context, bail};
use anyhow::bail;
use clap::Parser;
use common::constants::GP_SERVICE_LOCK_FILE;
use gpapi::clap::InfoLevelVerbosity;
use gpapi::logger;
#[cfg(debug_assertions)]
use gpapi::utils::lock_file::dev_service_lock_file_path;
use gpapi::{
service::vpn_state::VpnState,
utils::{lock_file::LockFile, redact::Redaction, shutdown_signal},
process::gui_launcher::GuiLauncher,
service::{request::WsRequest, vpn_state::VpnState},
utils::{crypto::generate_key, env_file, lock_file::LockFile, redact::Redaction, shutdown_signal},
GP_SERVICE_LOCK_FILE,
};
#[cfg(target_os = "macos")]
use log::{Log, Metadata, Record};
use log::{info, warn};
use log::{info, warn, LevelFilter};
use tokio::sync::{mpsc, watch};
use uuid::Uuid;
use crate::{
request_dispatcher::RequestDispatcher, session_registry::SessionRegistry, vpn_task::VpnTask, ws_server::WsServer,
};
use crate::{vpn_task::VpnTask, ws_server::WsServer};
const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("GPSERVICE_GIT_COMMIT"),
" ",
compile_time::date_str!(),
")"
);
#[cfg(target_os = "macos")]
struct RedactingMacosLogger {
logger: logger::MacosLogger,
redaction: Arc<Redaction>,
}
#[cfg(target_os = "macos")]
impl Log for RedactingMacosLogger {
fn enabled(&self, metadata: &Metadata<'_>) -> bool {
self.logger.enabled(metadata)
}
fn log(&self, record: &Record<'_>) {
if self.enabled(record.metadata()) {
let message = self.redaction.redact_str(&record.args().to_string());
self.logger.write(record.level(), record.target(), &message);
}
}
fn flush(&self) {}
}
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
#[derive(Parser)]
#[command(version = VERSION)]
struct Cli {
#[clap(long)]
#[cfg_attr(debug_assertions, clap(conflicts_with = "dev_standalone"))]
#[cfg_attr(target_os = "macos", clap(conflicts_with = "macos_brokered"))]
desktop_credentials: bool,
minimized: bool,
#[clap(long)]
env_file: Option<String>,
#[cfg(debug_assertions)]
#[clap(long, requires_all = ["dev_uid", "dev_bootstrap_socket"])]
dev_standalone: bool,
#[cfg(debug_assertions)]
#[clap(long, requires = "dev_standalone")]
dev_uid: Option<u32>,
#[cfg(debug_assertions)]
#[clap(long, requires = "dev_standalone")]
dev_bootstrap_socket: Option<PathBuf>,
#[cfg(target_os = "macos")]
#[clap(long, conflicts_with = "dev_standalone")]
macos_brokered: bool,
#[command(flatten)]
verbose: InfoLevelVerbosity,
#[clap(long)]
no_gui: bool,
}
impl Cli {
async fn run(&mut self) -> anyhow::Result<()> {
let redaction = self.init_logger();
info!("gpservice started: {}", VERSION);
async fn run(&mut self, redaction: Arc<Redaction>) -> anyhow::Result<()> {
let pid = std::process::id();
let lock_file = Arc::new(LockFile::new(self.service_lock_file_path()?, pid));
let lock_file = Arc::new(LockFile::new(GP_SERVICE_LOCK_FILE, pid));
if lock_file.check_health().await {
bail!("Another instance of the service is already running");
}
// Channel for receiving VPN state from the lifecycle actor
let api_key = self.prepare_api_key();
// Channel for sending requests to the VPN task
let (ws_req_tx, ws_req_rx) = mpsc::channel::<WsRequest>(32);
// Channel for receiving the VPN state from the VPN task
let (vpn_state_tx, vpn_state_rx) = watch::channel(VpnState::Disconnected);
let gui_restart_requested = Arc::new(AtomicBool::new(false));
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
let externally_brokered = self.externally_brokered();
let desktop_uid = if self.desktop_credentials {
anyhow::ensure!(
nix::unistd::Uid::effective().is_root(),
"Desktop credentials require a privileged service"
);
let uid: u32 = std::env::var("PKEXEC_UID")
.context("Desktop credentials require a pkexec-authenticated user")?
.parse()
.context("Invalid pkexec user")?;
anyhow::ensure!(uid != 0, "Desktop credentials require a non-root user");
anyhow::ensure!(
nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))?.is_some(),
"Desktop user is unavailable"
);
Some(uid)
} else {
crate::runtime_user::desktop_uid()
};
let desktop_channel = if self.desktop_credentials {
Some(crate::desktop_client::DesktopClient::from_stdio()?)
} else {
None
};
let brokered_scripts_dir = if externally_brokered {
let executable = std::env::current_exe().context("Failed to locate the gpservice executable")?;
let contents_dir = executable
.parent()
.and_then(std::path::Path::parent)
.context("gpservice is not inside a macOS application bundle")?;
Some(contents_dir.join("Resources/Scripts"))
} else {
None
};
let (mut vpn_task, lifecycle) = VpnTask::new(vpn_state_tx, externally_brokered, Arc::clone(&registry));
let dispatcher = Arc::new(RequestDispatcher::new(
lifecycle.clone(),
Arc::clone(&gui_restart_requested),
Arc::clone(&redaction),
!externally_brokered,
brokered_scripts_dir,
));
#[cfg(target_os = "macos")]
let idle_vpn_state_rx = vpn_state_rx.clone();
let ws_server = WsServer::new(
env!("CARGO_PKG_VERSION"),
Arc::clone(&registry),
dispatcher,
vpn_state_rx,
lock_file.clone(),
);
let mut vpn_task = VpnTask::new(ws_req_rx, vpn_state_tx);
let ws_server = WsServer::new(api_key.clone(), ws_req_tx, vpn_state_rx, lock_file.clone(), redaction);
let (shutdown_tx, mut shutdown_rx) = mpsc::channel::<()>(4);
let shutdown_tx_clone = shutdown_tx.clone();
let vpn_task_cancel_token = vpn_task.cancel_token();
let server_token = ws_server.cancel_token();
#[cfg(target_os = "macos")]
if externally_brokered {
let credential_server = crate::macos_broker::CredentialServer::new(Arc::clone(&registry));
let credential_token = server_token.clone();
let credential_shutdown = shutdown_tx.clone();
tokio::spawn(async move {
if let Err(err) = credential_server.start(credential_token).await {
warn!("Broker credential server stopped: {err}");
let _ = credential_shutdown.send(()).await;
}
});
let idle_registry = Arc::clone(&registry);
let idle_shutdown = shutdown_tx.clone();
let idle_token = server_token.clone();
tokio::spawn(async move {
wait_for_brokered_idle(idle_vpn_state_rx, idle_registry, idle_token).await;
let _ = idle_shutdown.send(()).await;
});
}
#[cfg(debug_assertions)]
if self.dev_standalone {
let Some(dev_bootstrap_socket) = self.dev_bootstrap_socket.clone() else {
bail!("--dev-bootstrap-socket is required with --dev-standalone");
};
let Some(dev_uid) = self.dev_uid else {
bail!("--dev-uid is required with --dev-standalone");
};
let bootstrap = crate::dev_bootstrap::DevBootstrap::new(dev_bootstrap_socket, dev_uid, Arc::clone(&registry));
let bootstrap_token = server_token.clone();
let bootstrap_shutdown = shutdown_tx.clone();
tokio::spawn(async move {
if let Err(err) = bootstrap.start(bootstrap_token).await {
warn!("Debug bootstrap stopped: {err}");
let _ = bootstrap_shutdown.send(()).await;
}
});
}
#[cfg(unix)]
{
let lifecycle = lifecycle.clone();
let vpn_ctx = vpn_task.context();
let ws_ctx = ws_server.context();
tokio::spawn(async move { signals::handle_signals(lifecycle, ws_ctx).await });
tokio::spawn(async move { signals::handle_signals(vpn_ctx, ws_ctx).await });
}
let desktop_cancel = server_token.clone();
let shutdown_token = server_token.clone();
let vpn_task_handle = tokio::spawn(async move { vpn_task.start(server_token).await });
let (ws_ready_tx, ws_ready_rx) = tokio::sync::oneshot::channel();
let ws_server_handle = tokio::spawn(async move { ws_server.start(shutdown_tx_clone, ws_ready_tx).await });
let ws_server_handle = tokio::spawn(async move { ws_server.start(shutdown_tx_clone).await });
let desktop_client_handle = if let Some(channel) = desktop_channel {
ws_ready_rx.await.context("WebSocket server failed to start")?;
let desktop_uid = desktop_uid.context("Desktop user is unavailable")?;
Some(tokio::spawn(async move {
if let Err(err) = channel
.serve(registry, desktop_uid, gui_restart_requested, desktop_cancel)
.await
{
warn!("Desktop credential channel ended: {err}");
}
let _ = shutdown_tx.send(()).await;
}))
#[cfg(debug_assertions)]
let no_gui = self.no_gui;
#[cfg(not(debug_assertions))]
let no_gui = false;
if no_gui {
info!("GUI is disabled");
} else {
info!("Running with an externally launched GUI");
None
};
let envs = self.env_file.as_ref().map(env_file::load_env_vars).transpose()?;
let minimized = self.minimized;
tokio::spawn(async move {
launch_gui(envs, api_key, minimized).await;
let _ = shutdown_tx.send(()).await;
});
}
tokio::select! {
_ = shutdown_signal() => {
@@ -233,11 +92,7 @@ impl Cli {
}
vpn_task_cancel_token.cancel();
shutdown_token.cancel();
let _ = tokio::join!(vpn_task_handle, ws_server_handle);
if let Some(handle) = desktop_client_handle {
let _ = handle.await;
}
lock_file.unlock()?;
@@ -246,97 +101,37 @@ impl Cli {
Ok(())
}
fn externally_brokered(&self) -> bool {
#[cfg(target_os = "macos")]
return self.macos_brokered;
#[cfg(not(target_os = "macos"))]
false
}
fn service_lock_file_path(&self) -> anyhow::Result<PathBuf> {
fn prepare_api_key(&self) -> Vec<u8> {
#[cfg(debug_assertions)]
if self.dev_standalone {
let socket = self
.dev_bootstrap_socket
.as_ref()
.context("--dev-bootstrap-socket is required with --dev-standalone")?;
return Ok(dev_service_lock_file_path(socket));
if self.no_gui {
return gpapi::GP_API_KEY.to_vec();
}
Ok(PathBuf::from(GP_SERVICE_LOCK_FILE))
}
fn init_logger(&self) -> Arc<Redaction> {
let redaction = Arc::new(Redaction::new());
let level = self.verbose.log_level_filter().to_level().unwrap_or(log::Level::Info);
#[cfg(target_os = "macos")]
if logger::macos_unified_log_enabled() {
logger::init_with_logger(
level,
RedactingMacosLogger {
logger: logger::MacosLogger::new("com.yuezk.gpgui", "gpservice"),
redaction: Arc::clone(&redaction),
},
);
return redaction;
}
let redaction_clone = Arc::clone(&redaction);
let inner_logger = env_logger::builder()
// Set the log level to the Trace level, the logs will be filtered
.filter_level(log::LevelFilter::Trace)
.format(move |buf, record| {
let timestamp = buf.timestamp();
writeln!(
buf,
"[{} {:<5} {}] {}",
timestamp,
record.level(),
record.module_path().unwrap_or_default(),
redaction_clone.redact_str(&record.args().to_string())
)
})
.build();
logger::init_with_logger(level, inner_logger);
redaction
generate_key().to_vec()
}
}
#[cfg(target_os = "macos")]
async fn wait_for_brokered_idle(
mut vpn_state_rx: watch::Receiver<VpnState>,
registry: Arc<SessionRegistry>,
cancel: tokio_util::sync::CancellationToken,
) {
const IDLE_TIMEOUT: Duration = Duration::from_secs(60);
const CHECK_INTERVAL: Duration = Duration::from_secs(1);
fn init_logger() -> Arc<Redaction> {
let redaction = Arc::new(Redaction::new());
let redaction_clone = Arc::clone(&redaction);
// let target = Box::new(File::create("log.txt").expect("Can't create file"));
env_logger::builder()
.filter_level(LevelFilter::Info)
.format(move |buf, record| {
let timestamp = buf.timestamp();
writeln!(
buf,
"[{} {} {}] {}",
timestamp,
record.level(),
record.module_path().unwrap_or_default(),
redaction_clone.redact_str(&record.args().to_string())
)
})
// .target(env_logger::Target::Pipe(target))
.init();
let mut idle_since = None;
let mut interval = tokio::time::interval(CHECK_INTERVAL);
loop {
tokio::select! {
_ = cancel.cancelled() => return,
_ = vpn_state_rx.changed() => {},
_ = interval.tick() => {},
}
let idle = matches!(*vpn_state_rx.borrow(), VpnState::Disconnected | VpnState::Failed(_)) && registry.is_empty();
if !idle {
idle_since = None;
continue;
}
let started = idle_since.get_or_insert_with(tokio::time::Instant::now);
if started.elapsed() >= IDLE_TIMEOUT {
info!("Brokered service idle timeout reached");
return;
}
}
redaction
}
#[cfg(unix)]
@@ -345,14 +140,14 @@ mod signals {
use log::{info, warn};
use crate::vpn_task::LifecycleHandle;
use crate::vpn_task::VpnTaskContext;
use crate::ws_server::WsServerContext;
const DISCONNECTED_PID_FILE: &str = "/tmp/gpservice_disconnected.pid";
pub async fn handle_signals(lifecycle: LifecycleHandle, ws_ctx: Arc<WsServerContext>) {
pub(crate) async fn handle_signals(vpn_ctx: Arc<VpnTaskContext>, ws_ctx: Arc<WsServerContext>) {
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 user_sig1 = signal(SignalKind::user_defined1())?;
@@ -370,7 +165,7 @@ mod signals {
tokio::select! {
_ = user_sig1.recv() => {
info!("Received SIGUSR1 signal");
if lifecycle.disconnect_and_wait().await {
if vpn_ctx.disconnect().await {
// Write the PID to a dedicated file to indicate that the VPN task is disconnected via SIGUSR1
let pid = std::process::id();
if let Err(err) = tokio::fs::write(DISCONNECTED_PID_FILE, pid.to_string()).await {
@@ -387,10 +182,38 @@ mod signals {
}
}
async fn launch_gui(envs: Option<HashMap<String, String>>, api_key: Vec<u8>, mut minimized: bool) {
loop {
let gui_launcher = GuiLauncher::new(env!("CARGO_PKG_VERSION"), &api_key)
.envs(envs.clone())
.minimized(minimized);
match gui_launcher.launch().await {
Ok(exit_status) => {
// Exit code 99 means that the GUI needs to be restarted
if exit_status.code() != Some(99) {
info!("GUI exited with code {:?}", exit_status.code());
break;
}
info!("GUI exited with code 99, restarting");
minimized = false;
}
Err(err) => {
warn!("Failed to launch GUI: {}", err);
break;
}
}
}
}
pub async fn run() {
let mut cli = Cli::parse();
if let Err(e) = cli.run().await {
let redaction = init_logger();
info!("gpservice started: {}", VERSION);
if let Err(e) = cli.run(redaction).await {
eprintln!("Error: {}", e);
std::process::exit(1);
}
Loaded 100 of 332 files, more files were not shown because too many files have changed in this diff. Show more