mirror of
				https://github.com/yuezk/GlobalProtect-openconnect.git
				synced 2025-05-20 07:26:58 -04:00 
			
		
		
		
	Compare commits
	
		
			42 Commits
		
	
	
		
			v2.0.0-bet
			...
			c4fa91f6ea
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
|  | c4fa91f6ea | ||
|  | 69502b22a9 | ||
|  | 356946e635 | ||
|  | 3674a28dee | ||
|  | 3098d1170f | ||
|  | acf7ef28ab | ||
|  | 11a374765c | ||
|  | f6ceb5ac0a | ||
|  | 94a2cd2886 | ||
|  | 867ea71144 | ||
|  | c9484248a5 | ||
|  | a10539e9c3 | ||
|  | 601f422863 | ||
|  | bf96a88e21 | ||
|  | 963b7d5407 | ||
|  | f91f0bcd17 | ||
|  | 5603157679 | ||
|  | 4191e9a19f | ||
|  | 5bc3da99ac | ||
|  | e8db014336 | ||
|  | e5fd2ba280 | ||
|  | 15e798c1e7 | ||
|  | 1af21432d4 | ||
|  | c07e232ec2 | ||
|  | d975f981cc | ||
|  | c74ce52c2d | ||
|  | da3dc10569 | ||
|  | 75db9e162f | ||
|  | 89eb42ceac | ||
|  | 54d3bb8a92 | ||
|  | a1b49fde47 | ||
|  | f42f0d248e | ||
|  | ec0bff1e36 | ||
|  | 77fda0f527 | ||
|  | 8de183a53d | ||
|  | 462428f99a | ||
|  | cbd8b0f144 | ||
|  | 5a84c99cd9 | ||
|  | d5af0e58c2 | ||
|  | 16696e3840 | ||
|  | 6df9877895 | ||
|  | 19b9b757f4 | 
| @@ -1,62 +0,0 @@ | ||||
| FROM ubuntu:18.04 | ||||
|  | ||||
| ARG USERNAME=vscode | ||||
| ARG USER_UID=1000 | ||||
| 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.75.0 | ||||
|  | ||||
| RUN set -eux; \ | ||||
|   apt-get update; \ | ||||
|   apt-get install -y --no-install-recommends \ | ||||
|     sudo \ | ||||
|     ca-certificates \ | ||||
|     curl \ | ||||
|     gnupg \ | ||||
|     git \ | ||||
|     less \ | ||||
|     software-properties-common \ | ||||
|     # Tauri dependencies | ||||
|     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 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 | ||||
|  | ||||
| USER $USERNAME | ||||
|  | ||||
| # Install Oh My Zsh | ||||
| RUN sh -c "$(wget -O- https://github.com/deluan/zsh-in-docker/releases/download/v1.1.5/zsh-in-docker.sh)" -- \ | ||||
|     -t https://github.com/denysdovhan/spaceship-prompt \ | ||||
|     -a 'SPACESHIP_PROMPT_ADD_NEWLINE="false"' \ | ||||
|     -a 'SPACESHIP_PROMPT_SEPARATE_LINE="false"' \ | ||||
|     -p git \ | ||||
|     -p https://github.com/zsh-users/zsh-autosuggestions \ | ||||
|     -p https://github.com/zsh-users/zsh-completions; \ | ||||
|     # Change the default shell | ||||
|     sudo chsh -s /bin/zsh $USERNAME; \ | ||||
|     # Change the XTERM to xterm-256color | ||||
|     sed -i 's/TERM=xterm/TERM=xterm-256color/g' $HOME/.zshrc; | ||||
| @@ -1,10 +0,0 @@ | ||||
| { | ||||
|   "build": { | ||||
|     "dockerfile": "Dockerfile" | ||||
|   }, | ||||
|   "runArgs": [ | ||||
|     "--privileged", | ||||
|     "--cap-add=NET_ADMIN", | ||||
|     "--device=/dev/net/tun" | ||||
|   ] | ||||
| } | ||||
| @@ -7,3 +7,15 @@ indent_size = 2 | ||||
| end_of_line = lf | ||||
| insert_final_newline = true | ||||
| trim_trailing_whitespace = true | ||||
|  | ||||
| [*.{rs,toml}] | ||||
| indent_size = 4 | ||||
|  | ||||
| [*.{c,h}] | ||||
| indent_size = 4 | ||||
|  | ||||
| [*.{js,jsx,ts,tsx}] | ||||
| indent_size = 2 | ||||
|  | ||||
| [*.md] | ||||
| trim_trailing_whitespace = false | ||||
|   | ||||
							
								
								
									
										2
									
								
								.github/FUNDING.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										2
									
								
								.github/FUNDING.yml
									
									
									
									
										vendored
									
									
								
							| @@ -1,2 +0,0 @@ | ||||
| ko_fi: yuezk | ||||
| custom: ["https://buymeacoffee.com/yuezk", "https://paypal.me/zongkun"] | ||||
							
								
								
									
										116
									
								
								.github/workflows/build.yaml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										116
									
								
								.github/workflows/build.yaml
									
									
									
									
										vendored
									
									
								
							| @@ -1,116 +0,0 @@ | ||||
| name: Build GPGUI | ||||
| on: | ||||
|   push: | ||||
|     paths-ignore: | ||||
|       - LICENSE | ||||
|       - "*.md" | ||||
|       - .vscode | ||||
|       - .devcontainer | ||||
|     branches: | ||||
|       - main | ||||
|     # tags: | ||||
|     #   - v*.*.* | ||||
| jobs: | ||||
|   # Include arm64 if ref is a tag | ||||
|   setup-matrix: | ||||
|     runs-on: ubuntu-latest | ||||
|     outputs: | ||||
|       matrix: ${{ steps.set-matrix.outputs.matrix }} | ||||
|     steps: | ||||
|       - name: Set up matrix | ||||
|         id: set-matrix | ||||
|         run: | | ||||
|           if [[ "${{ github.ref }}" == "refs/tags/"* ]]; then | ||||
|             echo "matrix=[\"amd64\", \"arm64\"]" >> $GITHUB_OUTPUT | ||||
|           else | ||||
|             echo "matrix=[\"amd64\"]" >> $GITHUB_OUTPUT | ||||
|           fi | ||||
|  | ||||
|   build-fe: | ||||
|     runs-on: ubuntu-latest | ||||
|     steps: | ||||
|       - name: Checkout gpgui repo | ||||
|         uses: actions/checkout@v4 | ||||
|         with: | ||||
|           token: ${{ secrets.GH_PAT }} | ||||
|           repository: yuezk/gpgui | ||||
|  | ||||
|       - name: Install Node.js | ||||
|         uses: actions/setup-node@v4 | ||||
|         with: | ||||
|           node-version: 18 | ||||
|  | ||||
|       - uses: pnpm/action-setup@v2 | ||||
|         with: | ||||
|           version: 8 | ||||
|  | ||||
|       - name: Install dependencies | ||||
|         run: | | ||||
|           cd app | ||||
|           pnpm install | ||||
|       - name: Build | ||||
|         run: | | ||||
|           cd app | ||||
|           pnpm run build | ||||
|  | ||||
|       - name: Upload artifacts | ||||
|         uses: actions/upload-artifact@v4 | ||||
|         with: | ||||
|           name: gpgui-fe | ||||
|           path: app/dist | ||||
|  | ||||
|   build-tauri: | ||||
|     needs: [setup-matrix, build-fe] | ||||
|     runs-on: ubuntu-latest | ||||
|     strategy: | ||||
|       matrix: | ||||
|         arch: ${{ fromJson(needs.setup-matrix.outputs.matrix) }} | ||||
|     steps: | ||||
|       - name: Checkout gpgui repo | ||||
|         uses: actions/checkout@v4 | ||||
|         with: | ||||
|           token: ${{ secrets.GH_PAT }} | ||||
|           repository: yuezk/gpgui | ||||
|           path: gpgui | ||||
|  | ||||
|       - name: Checkout gp repo | ||||
|         uses: actions/checkout@v4 | ||||
|         with: | ||||
|           token: ${{ secrets.GH_PAT }} | ||||
|           repository: yuezk/GlobalProtect-openconnect | ||||
|           path: gp | ||||
|  | ||||
|       - name: Download gpgui-fe artifact | ||||
|         uses: actions/download-artifact@v4 | ||||
|         with: | ||||
|           name: gpgui-fe | ||||
|           path: gpgui/app/dist | ||||
|  | ||||
|       - name: Set up QEMU | ||||
|         uses: docker/setup-qemu-action@v3 | ||||
|         with: | ||||
|           platforms: ${{ matrix.arch }} | ||||
|  | ||||
|       - name: Login to Docker Hub | ||||
|         uses: docker/login-action@v3 | ||||
|         with: | ||||
|           username: ${{ secrets.DOCKER_HUB_USERNAME }} | ||||
|           password: ${{ secrets.DOCKER_HUB_TOKEN }} | ||||
|  | ||||
|       - name: Build Tauri in Docker | ||||
|         run: | | ||||
|           docker run \ | ||||
|             --rm \ | ||||
|             -v $(pwd):/${{ github.workspace }} \ | ||||
|             -w ${{ github.workspace }} \ | ||||
|             -e CI=true \ | ||||
|             --platform linux/${{ matrix.arch }} \ | ||||
|             yuezk/gpdev:main \ | ||||
|             "./gpgui/scripts/build.sh" | ||||
|  | ||||
|       - name: Upload artifacts | ||||
|         uses: actions/upload-artifact@v4 | ||||
|         with: | ||||
|           name: artifact-${{ matrix.arch }}-tauri | ||||
|           path: | | ||||
|             gpgui/.tmp/artifact | ||||
							
								
								
									
										39
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										39
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							| @@ -1,4 +1,35 @@ | ||||
| .idea | ||||
| /target | ||||
| .pnpm-store | ||||
| .env | ||||
| # Created by https://www.toptal.com/developers/gitignore/api/rust,visualstudiocode | ||||
| # Edit at https://www.toptal.com/developers/gitignore?templates=rust,visualstudiocode | ||||
|  | ||||
| ### Rust ### | ||||
| # Generated by Cargo | ||||
| # will have compiled files and executables | ||||
| debug/ | ||||
| target/ | ||||
|  | ||||
| # These are backup files generated by rustfmt | ||||
| **/*.rs.bk | ||||
|  | ||||
| # MSVC Windows builds of rustc generate these, which store debugging information | ||||
| *.pdb | ||||
|  | ||||
| ### VisualStudioCode ### | ||||
| .vscode/* | ||||
| !.vscode/settings.json | ||||
| !.vscode/tasks.json | ||||
| !.vscode/launch.json | ||||
| !.vscode/extensions.json | ||||
| !.vscode/*.code-snippets | ||||
|  | ||||
| # Local History for Visual Studio Code | ||||
| .history/ | ||||
|  | ||||
| # Built Visual Studio Code Extensions | ||||
| *.vsix | ||||
|  | ||||
| ### VisualStudioCode Patch ### | ||||
| # Ignore all local history of files | ||||
| .history | ||||
| .ionide | ||||
|  | ||||
| # End of https://www.toptal.com/developers/gitignore/api/rust,visualstudiocode | ||||
|   | ||||
							
								
								
									
										9
									
								
								.vscode/extensions.json
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										9
									
								
								.vscode/extensions.json
									
									
									
									
										vendored
									
									
								
							| @@ -1,9 +0,0 @@ | ||||
| { | ||||
|     "recommendations": [ | ||||
|         "rust-lang.rust-analyzer", | ||||
|         "tamasfe.even-better-toml", | ||||
|         "eamodio.gitlens", | ||||
|         "EditorConfig.EditorConfig", | ||||
|         "streetsidesoftware.code-spell-checker", | ||||
|     ] | ||||
| } | ||||
							
								
								
									
										60
									
								
								.vscode/settings.json
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										60
									
								
								.vscode/settings.json
									
									
									
									
										vendored
									
									
								
							| @@ -1,54 +1,52 @@ | ||||
| { | ||||
|   "cSpell.words": [ | ||||
|     "authcookie", | ||||
|         "bincode", | ||||
|         "chacha", | ||||
|     "bindgen", | ||||
|     "clickaway", | ||||
|     "clientgpversion", | ||||
|     "clientos", | ||||
|         "datetime", | ||||
|         "disconnectable", | ||||
|     "configparser", | ||||
|     "consts", | ||||
|     "devicename", | ||||
|     "distro", | ||||
|         "dotenv", | ||||
|         "dotenvy", | ||||
|         "getconfig", | ||||
|         "globalprotect", | ||||
|         "gpapi", | ||||
|         "gpauth", | ||||
|         "gpclient", | ||||
|     "gpcommon", | ||||
|     "gpconf", | ||||
|     "gpgui", | ||||
|     "gpservice", | ||||
|         "hidpi", | ||||
|     "humantime", | ||||
|     "Immer", | ||||
|     "jnlp", | ||||
|         "LOGNAME", | ||||
|     "lexopt", | ||||
|     "notistack", | ||||
|     "oneshot", | ||||
|     "openconnect", | ||||
|     "pkexec", | ||||
|         "Prelogin", | ||||
|     "prelogin", | ||||
|     "prelogon", | ||||
|     "prelogonuserauthcookie", | ||||
|     "repr", | ||||
|         "reqwest", | ||||
|         "roxmltree", | ||||
|         "rspc", | ||||
|     "rustc", | ||||
|     "servercert", | ||||
|         "specta", | ||||
|         "sysinfo", | ||||
|         "tanstack", | ||||
|     "shlex", | ||||
|     "tauri", | ||||
|     "tempdir", | ||||
|     "tempfile", | ||||
|     "thiserror", | ||||
|         "tungstenite", | ||||
|         "unistd", | ||||
|     "unlisten", | ||||
|         "urlencoding", | ||||
|     "userauthcookie", | ||||
|         "utsbuf", | ||||
|         "uzers", | ||||
|         "Vite", | ||||
|     "vpnc", | ||||
|         "vpninfo", | ||||
|         "wmctrl", | ||||
|         "XAUTHORITY", | ||||
|         "yuezk" | ||||
|     ] | ||||
|     "vpninfo" | ||||
|   ], | ||||
|   "files.associations": { | ||||
|     "*.css": "css", | ||||
|     "errno.h": "c", | ||||
|     "stdarg.h": "c", | ||||
|     "wrapper.h": "c", | ||||
|     "cstdlib": "c", | ||||
|     "stdio.h": "c", | ||||
|     "openconnect.h": "c", | ||||
|     "compare": "c", | ||||
|     "stdlib.h": "c", | ||||
|     "vpn.h": "c" | ||||
|   } | ||||
| } | ||||
|   | ||||
							
								
								
									
										3214
									
								
								Cargo.lock
									
									
									
										generated
									
									
									
								
							
							
						
						
									
										3214
									
								
								Cargo.lock
									
									
									
										generated
									
									
									
								
							
										
											
												File diff suppressed because it is too large
												Load Diff
											
										
									
								
							
							
								
								
									
										56
									
								
								Cargo.toml
									
									
									
									
									
								
							
							
						
						
									
										56
									
								
								Cargo.toml
									
									
									
									
									
								
							| @@ -1,52 +1,12 @@ | ||||
| [workspace] | ||||
| resolver = "2" | ||||
|  | ||||
| members = ["crates/*", "apps/gpclient", "apps/gpservice", "apps/gpauth"] | ||||
|  | ||||
| [workspace.package] | ||||
| version = "2.0.0-beta4" | ||||
| authors = ["Kevin Yue <k3vinyue@gmail.com>"] | ||||
| homepage = "https://github.com/yuezk/GlobalProtect-openconnect" | ||||
| edition = "2021" | ||||
| license = "GPL-3.0" | ||||
|  | ||||
| [workspace.dependencies] | ||||
| anyhow = "1.0" | ||||
| base64 = "0.21" | ||||
| clap = { version = "4.4.2", features = ["derive"] } | ||||
| ctrlc = "3.4" | ||||
| directories = "5.0" | ||||
| env_logger = "0.10" | ||||
| is_executable = "1.0" | ||||
| log = "0.4" | ||||
| regex = "1" | ||||
| reqwest = { version = "0.11", features = ["native-tls-vendored", "json"] } | ||||
| roxmltree = "0.18" | ||||
| serde = { version = "1.0", features = ["derive"] } | ||||
| serde_json = "1.0" | ||||
| sysinfo = "0.29" | ||||
| tempfile = "3.8" | ||||
| tokio = { version = "1", features = ["full"] } | ||||
| tokio-util = "0.7" | ||||
| url = "2.4" | ||||
| urlencoding = "2.1.3" | ||||
| axum = "0.7" | ||||
| futures = "0.3" | ||||
| futures-util = "0.3" | ||||
| tokio-tungstenite = "0.20.1" | ||||
| specta = "=2.0.0-rc.1" | ||||
| specta-macros = "=2.0.0-rc.1" | ||||
| uzers = "0.11" | ||||
| whoami = "1" | ||||
| tauri = { version = "1.5" } | ||||
| thiserror = "1" | ||||
| redact-engine = "0.1" | ||||
| dotenvy_macro = "0.15" | ||||
| compile-time = "0.2" | ||||
| members = [ | ||||
|     "gpcommon", | ||||
|     "gpclient", | ||||
|     "gpservice", | ||||
|     "gpgui/src-tauri" | ||||
| ] | ||||
|  | ||||
| [profile.release] | ||||
| opt-level = 'z'   # Optimize for size | ||||
| lto = true        # Enable link-time optimization | ||||
| codegen-units = 1 # Reduce number of codegen units to increase optimizations | ||||
| panic = 'abort'   # Abort on panic | ||||
| strip = true      # Strip symbols from binary* | ||||
| strip = true | ||||
| opt-level = "z" | ||||
|   | ||||
							
								
								
									
										674
									
								
								LICENSE
									
									
									
									
									
								
							
							
						
						
									
										674
									
								
								LICENSE
									
									
									
									
									
								
							| @@ -1,674 +0,0 @@ | ||||
|                     GNU GENERAL PUBLIC LICENSE | ||||
|                        Version 3, 29 June 2007 | ||||
|  | ||||
|  Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> | ||||
|  Everyone is permitted to copy and distribute verbatim copies | ||||
|  of this license document, but changing it is not allowed. | ||||
|  | ||||
|                             Preamble | ||||
|  | ||||
|   The GNU General Public License is a free, copyleft license for | ||||
| software and other kinds of works. | ||||
|  | ||||
|   The licenses for most software and other practical works are designed | ||||
| to take away your freedom to share and change the works.  By contrast, | ||||
| the GNU General Public License is intended to guarantee your freedom to | ||||
| share and change all versions of a program--to make sure it remains free | ||||
| software for all its users.  We, the Free Software Foundation, use the | ||||
| GNU General Public License for most of our software; it applies also to | ||||
| any other work released this way by its authors.  You can apply it to | ||||
| your programs, too. | ||||
|  | ||||
|   When we speak of free software, we are referring to freedom, not | ||||
| price.  Our General Public Licenses are designed to make sure that you | ||||
| have the freedom to distribute copies of free software (and charge for | ||||
| them if you wish), that you receive source code or can get it if you | ||||
| want it, that you can change the software or use pieces of it in new | ||||
| free programs, and that you know you can do these things. | ||||
|  | ||||
|   To protect your rights, we need to prevent others from denying you | ||||
| these rights or asking you to surrender the rights.  Therefore, you have | ||||
| certain responsibilities if you distribute copies of the software, or if | ||||
| you modify it: responsibilities to respect the freedom of others. | ||||
|  | ||||
|   For example, if you distribute copies of such a program, whether | ||||
| gratis or for a fee, you must pass on to the recipients the same | ||||
| freedoms that you received.  You must make sure that they, too, receive | ||||
| or can get the source code.  And you must show them these terms so they | ||||
| know their rights. | ||||
|  | ||||
|   Developers that use the GNU GPL protect your rights with two steps: | ||||
| (1) assert copyright on the software, and (2) offer you this License | ||||
| giving you legal permission to copy, distribute and/or modify it. | ||||
|  | ||||
|   For the developers' and authors' protection, the GPL clearly explains | ||||
| that there is no warranty for this free software.  For both users' and | ||||
| authors' sake, the GPL requires that modified versions be marked as | ||||
| changed, so that their problems will not be attributed erroneously to | ||||
| authors of previous versions. | ||||
|  | ||||
|   Some devices are designed to deny users access to install or run | ||||
| modified versions of the software inside them, although the manufacturer | ||||
| can do so.  This is fundamentally incompatible with the aim of | ||||
| protecting users' freedom to change the software.  The systematic | ||||
| pattern of such abuse occurs in the area of products for individuals to | ||||
| use, which is precisely where it is most unacceptable.  Therefore, we | ||||
| have designed this version of the GPL to prohibit the practice for those | ||||
| products.  If such problems arise substantially in other domains, we | ||||
| stand ready to extend this provision to those domains in future versions | ||||
| of the GPL, as needed to protect the freedom of users. | ||||
|  | ||||
|   Finally, every program is threatened constantly by software patents. | ||||
| States should not allow patents to restrict development and use of | ||||
| software on general-purpose computers, but in those that do, we wish to | ||||
| avoid the special danger that patents applied to a free program could | ||||
| make it effectively proprietary.  To prevent this, the GPL assures that | ||||
| patents cannot be used to render the program non-free. | ||||
|  | ||||
|   The precise terms and conditions for copying, distribution and | ||||
| modification follow. | ||||
|  | ||||
|                        TERMS AND CONDITIONS | ||||
|  | ||||
|   0. Definitions. | ||||
|  | ||||
|   "This License" refers to version 3 of the GNU General Public License. | ||||
|  | ||||
|   "Copyright" also means copyright-like laws that apply to other kinds of | ||||
| works, such as semiconductor masks. | ||||
|  | ||||
|   "The Program" refers to any copyrightable work licensed under this | ||||
| License.  Each licensee is addressed as "you".  "Licensees" and | ||||
| "recipients" may be individuals or organizations. | ||||
|  | ||||
|   To "modify" a work means to copy from or adapt all or part of the work | ||||
| in a fashion requiring copyright permission, other than the making of an | ||||
| exact copy.  The resulting work is called a "modified version" of the | ||||
| earlier work or a work "based on" the earlier work. | ||||
|  | ||||
|   A "covered work" means either the unmodified Program or a work based | ||||
| on the Program. | ||||
|  | ||||
|   To "propagate" a work means to do anything with it that, without | ||||
| permission, would make you directly or secondarily liable for | ||||
| infringement under applicable copyright law, except executing it on a | ||||
| computer or modifying a private copy.  Propagation includes copying, | ||||
| distribution (with or without modification), making available to the | ||||
| public, and in some countries other activities as well. | ||||
|  | ||||
|   To "convey" a work means any kind of propagation that enables other | ||||
| parties to make or receive copies.  Mere interaction with a user through | ||||
| a computer network, with no transfer of a copy, is not conveying. | ||||
|  | ||||
|   An interactive user interface displays "Appropriate Legal Notices" | ||||
| to the extent that it includes a convenient and prominently visible | ||||
| feature that (1) displays an appropriate copyright notice, and (2) | ||||
| tells the user that there is no warranty for the work (except to the | ||||
| extent that warranties are provided), that licensees may convey the | ||||
| work under this License, and how to view a copy of this License.  If | ||||
| the interface presents a list of user commands or options, such as a | ||||
| menu, a prominent item in the list meets this criterion. | ||||
|  | ||||
|   1. Source Code. | ||||
|  | ||||
|   The "source code" for a work means the preferred form of the work | ||||
| for making modifications to it.  "Object code" means any non-source | ||||
| form of a work. | ||||
|  | ||||
|   A "Standard Interface" means an interface that either is an official | ||||
| standard defined by a recognized standards body, or, in the case of | ||||
| interfaces specified for a particular programming language, one that | ||||
| is widely used among developers working in that language. | ||||
|  | ||||
|   The "System Libraries" of an executable work include anything, other | ||||
| than the work as a whole, that (a) is included in the normal form of | ||||
| packaging a Major Component, but which is not part of that Major | ||||
| Component, and (b) serves only to enable use of the work with that | ||||
| Major Component, or to implement a Standard Interface for which an | ||||
| implementation is available to the public in source code form.  A | ||||
| "Major Component", in this context, means a major essential component | ||||
| (kernel, window system, and so on) of the specific operating system | ||||
| (if any) on which the executable work runs, or a compiler used to | ||||
| produce the work, or an object code interpreter used to run it. | ||||
|  | ||||
|   The "Corresponding Source" for a work in object code form means all | ||||
| the source code needed to generate, install, and (for an executable | ||||
| work) run the object code and to modify the work, including scripts to | ||||
| control those activities.  However, it does not include the work's | ||||
| System Libraries, or general-purpose tools or generally available free | ||||
| programs which are used unmodified in performing those activities but | ||||
| which are not part of the work.  For example, Corresponding Source | ||||
| includes interface definition files associated with source files for | ||||
| the work, and the source code for shared libraries and dynamically | ||||
| linked subprograms that the work is specifically designed to require, | ||||
| such as by intimate data communication or control flow between those | ||||
| subprograms and other parts of the work. | ||||
|  | ||||
|   The Corresponding Source need not include anything that users | ||||
| can regenerate automatically from other parts of the Corresponding | ||||
| Source. | ||||
|  | ||||
|   The Corresponding Source for a work in source code form is that | ||||
| same work. | ||||
|  | ||||
|   2. Basic Permissions. | ||||
|  | ||||
|   All rights granted under this License are granted for the term of | ||||
| copyright on the Program, and are irrevocable provided the stated | ||||
| conditions are met.  This License explicitly affirms your unlimited | ||||
| permission to run the unmodified Program.  The output from running a | ||||
| covered work is covered by this License only if the output, given its | ||||
| content, constitutes a covered work.  This License acknowledges your | ||||
| rights of fair use or other equivalent, as provided by copyright law. | ||||
|  | ||||
|   You may make, run and propagate covered works that you do not | ||||
| convey, without conditions so long as your license otherwise remains | ||||
| in force.  You may convey covered works to others for the sole purpose | ||||
| of having them make modifications exclusively for you, or provide you | ||||
| with facilities for running those works, provided that you comply with | ||||
| the terms of this License in conveying all material for which you do | ||||
| not control copyright.  Those thus making or running the covered works | ||||
| for you must do so exclusively on your behalf, under your direction | ||||
| and control, on terms that prohibit them from making any copies of | ||||
| your copyrighted material outside their relationship with you. | ||||
|  | ||||
|   Conveying under any other circumstances is permitted solely under | ||||
| the conditions stated below.  Sublicensing is not allowed; section 10 | ||||
| makes it unnecessary. | ||||
|  | ||||
|   3. Protecting Users' Legal Rights From Anti-Circumvention Law. | ||||
|  | ||||
|   No covered work shall be deemed part of an effective technological | ||||
| measure under any applicable law fulfilling obligations under article | ||||
| 11 of the WIPO copyright treaty adopted on 20 December 1996, or | ||||
| similar laws prohibiting or restricting circumvention of such | ||||
| measures. | ||||
|  | ||||
|   When you convey a covered work, you waive any legal power to forbid | ||||
| circumvention of technological measures to the extent such circumvention | ||||
| is effected by exercising rights under this License with respect to | ||||
| the covered work, and you disclaim any intention to limit operation or | ||||
| modification of the work as a means of enforcing, against the work's | ||||
| users, your or third parties' legal rights to forbid circumvention of | ||||
| technological measures. | ||||
|  | ||||
|   4. Conveying Verbatim Copies. | ||||
|  | ||||
|   You may convey verbatim copies of the Program's source code as you | ||||
| receive it, in any medium, provided that you conspicuously and | ||||
| appropriately publish on each copy an appropriate copyright notice; | ||||
| keep intact all notices stating that this License and any | ||||
| non-permissive terms added in accord with section 7 apply to the code; | ||||
| keep intact all notices of the absence of any warranty; and give all | ||||
| recipients a copy of this License along with the Program. | ||||
|  | ||||
|   You may charge any price or no price for each copy that you convey, | ||||
| and you may offer support or warranty protection for a fee. | ||||
|  | ||||
|   5. Conveying Modified Source Versions. | ||||
|  | ||||
|   You may convey a work based on the Program, or the modifications to | ||||
| produce it from the Program, in the form of source code under the | ||||
| terms of section 4, provided that you also meet all of these conditions: | ||||
|  | ||||
|     a) The work must carry prominent notices stating that you modified | ||||
|     it, and giving a relevant date. | ||||
|  | ||||
|     b) The work must carry prominent notices stating that it is | ||||
|     released under this License and any conditions added under section | ||||
|     7.  This requirement modifies the requirement in section 4 to | ||||
|     "keep intact all notices". | ||||
|  | ||||
|     c) You must license the entire work, as a whole, under this | ||||
|     License to anyone who comes into possession of a copy.  This | ||||
|     License will therefore apply, along with any applicable section 7 | ||||
|     additional terms, to the whole of the work, and all its parts, | ||||
|     regardless of how they are packaged.  This License gives no | ||||
|     permission to license the work in any other way, but it does not | ||||
|     invalidate such permission if you have separately received it. | ||||
|  | ||||
|     d) If the work has interactive user interfaces, each must display | ||||
|     Appropriate Legal Notices; however, if the Program has interactive | ||||
|     interfaces that do not display Appropriate Legal Notices, your | ||||
|     work need not make them do so. | ||||
|  | ||||
|   A compilation of a covered work with other separate and independent | ||||
| works, which are not by their nature extensions of the covered work, | ||||
| and which are not combined with it such as to form a larger program, | ||||
| in or on a volume of a storage or distribution medium, is called an | ||||
| "aggregate" if the compilation and its resulting copyright are not | ||||
| used to limit the access or legal rights of the compilation's users | ||||
| beyond what the individual works permit.  Inclusion of a covered work | ||||
| in an aggregate does not cause this License to apply to the other | ||||
| parts of the aggregate. | ||||
|  | ||||
|   6. Conveying Non-Source Forms. | ||||
|  | ||||
|   You may convey a covered work in object code form under the terms | ||||
| of sections 4 and 5, provided that you also convey the | ||||
| machine-readable Corresponding Source under the terms of this License, | ||||
| in one of these ways: | ||||
|  | ||||
|     a) Convey the object code in, or embodied in, a physical product | ||||
|     (including a physical distribution medium), accompanied by the | ||||
|     Corresponding Source fixed on a durable physical medium | ||||
|     customarily used for software interchange. | ||||
|  | ||||
|     b) Convey the object code in, or embodied in, a physical product | ||||
|     (including a physical distribution medium), accompanied by a | ||||
|     written offer, valid for at least three years and valid for as | ||||
|     long as you offer spare parts or customer support for that product | ||||
|     model, to give anyone who possesses the object code either (1) a | ||||
|     copy of the Corresponding Source for all the software in the | ||||
|     product that is covered by this License, on a durable physical | ||||
|     medium customarily used for software interchange, for a price no | ||||
|     more than your reasonable cost of physically performing this | ||||
|     conveying of source, or (2) access to copy the | ||||
|     Corresponding Source from a network server at no charge. | ||||
|  | ||||
|     c) Convey individual copies of the object code with a copy of the | ||||
|     written offer to provide the Corresponding Source.  This | ||||
|     alternative is allowed only occasionally and noncommercially, and | ||||
|     only if you received the object code with such an offer, in accord | ||||
|     with subsection 6b. | ||||
|  | ||||
|     d) Convey the object code by offering access from a designated | ||||
|     place (gratis or for a charge), and offer equivalent access to the | ||||
|     Corresponding Source in the same way through the same place at no | ||||
|     further charge.  You need not require recipients to copy the | ||||
|     Corresponding Source along with the object code.  If the place to | ||||
|     copy the object code is a network server, the Corresponding Source | ||||
|     may be on a different server (operated by you or a third party) | ||||
|     that supports equivalent copying facilities, provided you maintain | ||||
|     clear directions next to the object code saying where to find the | ||||
|     Corresponding Source.  Regardless of what server hosts the | ||||
|     Corresponding Source, you remain obligated to ensure that it is | ||||
|     available for as long as needed to satisfy these requirements. | ||||
|  | ||||
|     e) Convey the object code using peer-to-peer transmission, provided | ||||
|     you inform other peers where the object code and Corresponding | ||||
|     Source of the work are being offered to the general public at no | ||||
|     charge under subsection 6d. | ||||
|  | ||||
|   A separable portion of the object code, whose source code is excluded | ||||
| from the Corresponding Source as a System Library, need not be | ||||
| included in conveying the object code work. | ||||
|  | ||||
|   A "User Product" is either (1) a "consumer product", which means any | ||||
| tangible personal property which is normally used for personal, family, | ||||
| or household purposes, or (2) anything designed or sold for incorporation | ||||
| into a dwelling.  In determining whether a product is a consumer product, | ||||
| doubtful cases shall be resolved in favor of coverage.  For a particular | ||||
| product received by a particular user, "normally used" refers to a | ||||
| typical or common use of that class of product, regardless of the status | ||||
| of the particular user or of the way in which the particular user | ||||
| actually uses, or expects or is expected to use, the product.  A product | ||||
| is a consumer product regardless of whether the product has substantial | ||||
| commercial, industrial or non-consumer uses, unless such uses represent | ||||
| the only significant mode of use of the product. | ||||
|  | ||||
|   "Installation Information" for a User Product means any methods, | ||||
| procedures, authorization keys, or other information required to install | ||||
| and execute modified versions of a covered work in that User Product from | ||||
| a modified version of its Corresponding Source.  The information must | ||||
| suffice to ensure that the continued functioning of the modified object | ||||
| code is in no case prevented or interfered with solely because | ||||
| modification has been made. | ||||
|  | ||||
|   If you convey an object code work under this section in, or with, or | ||||
| specifically for use in, a User Product, and the conveying occurs as | ||||
| part of a transaction in which the right of possession and use of the | ||||
| User Product is transferred to the recipient in perpetuity or for a | ||||
| fixed term (regardless of how the transaction is characterized), the | ||||
| Corresponding Source conveyed under this section must be accompanied | ||||
| by the Installation Information.  But this requirement does not apply | ||||
| if neither you nor any third party retains the ability to install | ||||
| modified object code on the User Product (for example, the work has | ||||
| been installed in ROM). | ||||
|  | ||||
|   The requirement to provide Installation Information does not include a | ||||
| requirement to continue to provide support service, warranty, or updates | ||||
| for a work that has been modified or installed by the recipient, or for | ||||
| the User Product in which it has been modified or installed.  Access to a | ||||
| network may be denied when the modification itself materially and | ||||
| adversely affects the operation of the network or violates the rules and | ||||
| protocols for communication across the network. | ||||
|  | ||||
|   Corresponding Source conveyed, and Installation Information provided, | ||||
| in accord with this section must be in a format that is publicly | ||||
| documented (and with an implementation available to the public in | ||||
| source code form), and must require no special password or key for | ||||
| unpacking, reading or copying. | ||||
|  | ||||
|   7. Additional Terms. | ||||
|  | ||||
|   "Additional permissions" are terms that supplement the terms of this | ||||
| License by making exceptions from one or more of its conditions. | ||||
| Additional permissions that are applicable to the entire Program shall | ||||
| be treated as though they were included in this License, to the extent | ||||
| that they are valid under applicable law.  If additional permissions | ||||
| apply only to part of the Program, that part may be used separately | ||||
| under those permissions, but the entire Program remains governed by | ||||
| this License without regard to the additional permissions. | ||||
|  | ||||
|   When you convey a copy of a covered work, you may at your option | ||||
| remove any additional permissions from that copy, or from any part of | ||||
| it.  (Additional permissions may be written to require their own | ||||
| removal in certain cases when you modify the work.)  You may place | ||||
| additional permissions on material, added by you to a covered work, | ||||
| for which you have or can give appropriate copyright permission. | ||||
|  | ||||
|   Notwithstanding any other provision of this License, for material you | ||||
| add to a covered work, you may (if authorized by the copyright holders of | ||||
| that material) supplement the terms of this License with terms: | ||||
|  | ||||
|     a) Disclaiming warranty or limiting liability differently from the | ||||
|     terms of sections 15 and 16 of this License; or | ||||
|  | ||||
|     b) Requiring preservation of specified reasonable legal notices or | ||||
|     author attributions in that material or in the Appropriate Legal | ||||
|     Notices displayed by works containing it; or | ||||
|  | ||||
|     c) Prohibiting misrepresentation of the origin of that material, or | ||||
|     requiring that modified versions of such material be marked in | ||||
|     reasonable ways as different from the original version; or | ||||
|  | ||||
|     d) Limiting the use for publicity purposes of names of licensors or | ||||
|     authors of the material; or | ||||
|  | ||||
|     e) Declining to grant rights under trademark law for use of some | ||||
|     trade names, trademarks, or service marks; or | ||||
|  | ||||
|     f) Requiring indemnification of licensors and authors of that | ||||
|     material by anyone who conveys the material (or modified versions of | ||||
|     it) with contractual assumptions of liability to the recipient, for | ||||
|     any liability that these contractual assumptions directly impose on | ||||
|     those licensors and authors. | ||||
|  | ||||
|   All other non-permissive additional terms are considered "further | ||||
| restrictions" within the meaning of section 10.  If the Program as you | ||||
| received it, or any part of it, contains a notice stating that it is | ||||
| governed by this License along with a term that is a further | ||||
| restriction, you may remove that term.  If a license document contains | ||||
| a further restriction but permits relicensing or conveying under this | ||||
| License, you may add to a covered work material governed by the terms | ||||
| of that license document, provided that the further restriction does | ||||
| not survive such relicensing or conveying. | ||||
|  | ||||
|   If you add terms to a covered work in accord with this section, you | ||||
| must place, in the relevant source files, a statement of the | ||||
| additional terms that apply to those files, or a notice indicating | ||||
| where to find the applicable terms. | ||||
|  | ||||
|   Additional terms, permissive or non-permissive, may be stated in the | ||||
| form of a separately written license, or stated as exceptions; | ||||
| the above requirements apply either way. | ||||
|  | ||||
|   8. Termination. | ||||
|  | ||||
|   You may not propagate or modify a covered work except as expressly | ||||
| provided under this License.  Any attempt otherwise to propagate or | ||||
| modify it is void, and will automatically terminate your rights under | ||||
| this License (including any patent licenses granted under the third | ||||
| paragraph of section 11). | ||||
|  | ||||
|   However, if you cease all violation of this License, then your | ||||
| license from a particular copyright holder is reinstated (a) | ||||
| provisionally, unless and until the copyright holder explicitly and | ||||
| finally terminates your license, and (b) permanently, if the copyright | ||||
| holder fails to notify you of the violation by some reasonable means | ||||
| prior to 60 days after the cessation. | ||||
|  | ||||
|   Moreover, your license from a particular copyright holder is | ||||
| reinstated permanently if the copyright holder notifies you of the | ||||
| violation by some reasonable means, this is the first time you have | ||||
| received notice of violation of this License (for any work) from that | ||||
| copyright holder, and you cure the violation prior to 30 days after | ||||
| your receipt of the notice. | ||||
|  | ||||
|   Termination of your rights under this section does not terminate the | ||||
| licenses of parties who have received copies or rights from you under | ||||
| this License.  If your rights have been terminated and not permanently | ||||
| reinstated, you do not qualify to receive new licenses for the same | ||||
| material under section 10. | ||||
|  | ||||
|   9. Acceptance Not Required for Having Copies. | ||||
|  | ||||
|   You are not required to accept this License in order to receive or | ||||
| run a copy of the Program.  Ancillary propagation of a covered work | ||||
| occurring solely as a consequence of using peer-to-peer transmission | ||||
| to receive a copy likewise does not require acceptance.  However, | ||||
| nothing other than this License grants you permission to propagate or | ||||
| modify any covered work.  These actions infringe copyright if you do | ||||
| not accept this License.  Therefore, by modifying or propagating a | ||||
| covered work, you indicate your acceptance of this License to do so. | ||||
|  | ||||
|   10. Automatic Licensing of Downstream Recipients. | ||||
|  | ||||
|   Each time you convey a covered work, the recipient automatically | ||||
| receives a license from the original licensors, to run, modify and | ||||
| propagate that work, subject to this License.  You are not responsible | ||||
| for enforcing compliance by third parties with this License. | ||||
|  | ||||
|   An "entity transaction" is a transaction transferring control of an | ||||
| organization, or substantially all assets of one, or subdividing an | ||||
| organization, or merging organizations.  If propagation of a covered | ||||
| work results from an entity transaction, each party to that | ||||
| transaction who receives a copy of the work also receives whatever | ||||
| licenses to the work the party's predecessor in interest had or could | ||||
| give under the previous paragraph, plus a right to possession of the | ||||
| Corresponding Source of the work from the predecessor in interest, if | ||||
| the predecessor has it or can get it with reasonable efforts. | ||||
|  | ||||
|   You may not impose any further restrictions on the exercise of the | ||||
| rights granted or affirmed under this License.  For example, you may | ||||
| not impose a license fee, royalty, or other charge for exercise of | ||||
| rights granted under this License, and you may not initiate litigation | ||||
| (including a cross-claim or counterclaim in a lawsuit) alleging that | ||||
| any patent claim is infringed by making, using, selling, offering for | ||||
| sale, or importing the Program or any portion of it. | ||||
|  | ||||
|   11. Patents. | ||||
|  | ||||
|   A "contributor" is a copyright holder who authorizes use under this | ||||
| License of the Program or a work on which the Program is based.  The | ||||
| work thus licensed is called the contributor's "contributor version". | ||||
|  | ||||
|   A contributor's "essential patent claims" are all patent claims | ||||
| owned or controlled by the contributor, whether already acquired or | ||||
| hereafter acquired, that would be infringed by some manner, permitted | ||||
| by this License, of making, using, or selling its contributor version, | ||||
| but do not include claims that would be infringed only as a | ||||
| consequence of further modification of the contributor version.  For | ||||
| purposes of this definition, "control" includes the right to grant | ||||
| patent sublicenses in a manner consistent with the requirements of | ||||
| this License. | ||||
|  | ||||
|   Each contributor grants you a non-exclusive, worldwide, royalty-free | ||||
| patent license under the contributor's essential patent claims, to | ||||
| make, use, sell, offer for sale, import and otherwise run, modify and | ||||
| propagate the contents of its contributor version. | ||||
|  | ||||
|   In the following three paragraphs, a "patent license" is any express | ||||
| agreement or commitment, however denominated, not to enforce a patent | ||||
| (such as an express permission to practice a patent or covenant not to | ||||
| sue for patent infringement).  To "grant" such a patent license to a | ||||
| party means to make such an agreement or commitment not to enforce a | ||||
| patent against the party. | ||||
|  | ||||
|   If you convey a covered work, knowingly relying on a patent license, | ||||
| and the Corresponding Source of the work is not available for anyone | ||||
| to copy, free of charge and under the terms of this License, through a | ||||
| publicly available network server or other readily accessible means, | ||||
| then you must either (1) cause the Corresponding Source to be so | ||||
| available, or (2) arrange to deprive yourself of the benefit of the | ||||
| patent license for this particular work, or (3) arrange, in a manner | ||||
| consistent with the requirements of this License, to extend the patent | ||||
| license to downstream recipients.  "Knowingly relying" means you have | ||||
| actual knowledge that, but for the patent license, your conveying the | ||||
| covered work in a country, or your recipient's use of the covered work | ||||
| in a country, would infringe one or more identifiable patents in that | ||||
| country that you have reason to believe are valid. | ||||
|  | ||||
|   If, pursuant to or in connection with a single transaction or | ||||
| arrangement, you convey, or propagate by procuring conveyance of, a | ||||
| covered work, and grant a patent license to some of the parties | ||||
| receiving the covered work authorizing them to use, propagate, modify | ||||
| or convey a specific copy of the covered work, then the patent license | ||||
| you grant is automatically extended to all recipients of the covered | ||||
| work and works based on it. | ||||
|  | ||||
|   A patent license is "discriminatory" if it does not include within | ||||
| the scope of its coverage, prohibits the exercise of, or is | ||||
| conditioned on the non-exercise of one or more of the rights that are | ||||
| specifically granted under this License.  You may not convey a covered | ||||
| work if you are a party to an arrangement with a third party that is | ||||
| in the business of distributing software, under which you make payment | ||||
| to the third party based on the extent of your activity of conveying | ||||
| the work, and under which the third party grants, to any of the | ||||
| parties who would receive the covered work from you, a discriminatory | ||||
| patent license (a) in connection with copies of the covered work | ||||
| conveyed by you (or copies made from those copies), or (b) primarily | ||||
| for and in connection with specific products or compilations that | ||||
| contain the covered work, unless you entered into that arrangement, | ||||
| or that patent license was granted, prior to 28 March 2007. | ||||
|  | ||||
|   Nothing in this License shall be construed as excluding or limiting | ||||
| any implied license or other defenses to infringement that may | ||||
| otherwise be available to you under applicable patent law. | ||||
|  | ||||
|   12. No Surrender of Others' Freedom. | ||||
|  | ||||
|   If conditions are imposed on you (whether by court order, agreement or | ||||
| otherwise) that contradict the conditions of this License, they do not | ||||
| excuse you from the conditions of this License.  If you cannot convey a | ||||
| covered work so as to satisfy simultaneously your obligations under this | ||||
| License and any other pertinent obligations, then as a consequence you may | ||||
| not convey it at all.  For example, if you agree to terms that obligate you | ||||
| to collect a royalty for further conveying from those to whom you convey | ||||
| the Program, the only way you could satisfy both those terms and this | ||||
| License would be to refrain entirely from conveying the Program. | ||||
|  | ||||
|   13. Use with the GNU Affero General Public License. | ||||
|  | ||||
|   Notwithstanding any other provision of this License, you have | ||||
| permission to link or combine any covered work with a work licensed | ||||
| under version 3 of the GNU Affero General Public License into a single | ||||
| combined work, and to convey the resulting work.  The terms of this | ||||
| License will continue to apply to the part which is the covered work, | ||||
| but the special requirements of the GNU Affero General Public License, | ||||
| section 13, concerning interaction through a network will apply to the | ||||
| combination as such. | ||||
|  | ||||
|   14. Revised Versions of this License. | ||||
|  | ||||
|   The Free Software Foundation may publish revised and/or new versions of | ||||
| the GNU General Public License from time to time.  Such new versions will | ||||
| be similar in spirit to the present version, but may differ in detail to | ||||
| address new problems or concerns. | ||||
|  | ||||
|   Each version is given a distinguishing version number.  If the | ||||
| Program specifies that a certain numbered version of the GNU General | ||||
| Public License "or any later version" applies to it, you have the | ||||
| option of following the terms and conditions either of that numbered | ||||
| version or of any later version published by the Free Software | ||||
| Foundation.  If the Program does not specify a version number of the | ||||
| GNU General Public License, you may choose any version ever published | ||||
| by the Free Software Foundation. | ||||
|  | ||||
|   If the Program specifies that a proxy can decide which future | ||||
| versions of the GNU General Public License can be used, that proxy's | ||||
| public statement of acceptance of a version permanently authorizes you | ||||
| to choose that version for the Program. | ||||
|  | ||||
|   Later license versions may give you additional or different | ||||
| permissions.  However, no additional obligations are imposed on any | ||||
| author or copyright holder as a result of your choosing to follow a | ||||
| later version. | ||||
|  | ||||
|   15. Disclaimer of Warranty. | ||||
|  | ||||
|   THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY | ||||
| APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT | ||||
| HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY | ||||
| OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, | ||||
| THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR | ||||
| PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM | ||||
| IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF | ||||
| ALL NECESSARY SERVICING, REPAIR OR CORRECTION. | ||||
|  | ||||
|   16. Limitation of Liability. | ||||
|  | ||||
|   IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING | ||||
| WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS | ||||
| THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY | ||||
| GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE | ||||
| USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF | ||||
| DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD | ||||
| PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), | ||||
| EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF | ||||
| SUCH DAMAGES. | ||||
|  | ||||
|   17. Interpretation of Sections 15 and 16. | ||||
|  | ||||
|   If the disclaimer of warranty and limitation of liability provided | ||||
| above cannot be given local legal effect according to their terms, | ||||
| reviewing courts shall apply local law that most closely approximates | ||||
| an absolute waiver of all civil liability in connection with the | ||||
| Program, unless a warranty or assumption of liability accompanies a | ||||
| copy of the Program in return for a fee. | ||||
|  | ||||
|                      END OF TERMS AND CONDITIONS | ||||
|  | ||||
|             How to Apply These Terms to Your New Programs | ||||
|  | ||||
|   If you develop a new program, and you want it to be of the greatest | ||||
| possible use to the public, the best way to achieve this is to make it | ||||
| free software which everyone can redistribute and change under these terms. | ||||
|  | ||||
|   To do so, attach the following notices to the program.  It is safest | ||||
| to attach them to the start of each source file to most effectively | ||||
| state the exclusion of warranty; and each file should have at least | ||||
| the "copyright" line and a pointer to where the full notice is found. | ||||
|  | ||||
|     <one line to give the program's name and a brief idea of what it does.> | ||||
|     Copyright (C) <year>  <name of author> | ||||
|  | ||||
|     This program is free software: you can redistribute it and/or modify | ||||
|     it under the terms of the GNU General Public License as published by | ||||
|     the Free Software Foundation, either version 3 of the License, or | ||||
|     (at your option) any later version. | ||||
|  | ||||
|     This program is distributed in the hope that it will be useful, | ||||
|     but WITHOUT ANY WARRANTY; without even the implied warranty of | ||||
|     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the | ||||
|     GNU General Public License for more details. | ||||
|  | ||||
|     You should have received a copy of the GNU General Public License | ||||
|     along with this program.  If not, see <https://www.gnu.org/licenses/>. | ||||
|  | ||||
| Also add information on how to contact you by electronic and paper mail. | ||||
|  | ||||
|   If the program does terminal interaction, make it output a short | ||||
| notice like this when it starts in an interactive mode: | ||||
|  | ||||
|     <program>  Copyright (C) <year>  <name of author> | ||||
|     This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. | ||||
|     This is free software, and you are welcome to redistribute it | ||||
|     under certain conditions; type `show c' for details. | ||||
|  | ||||
| The hypothetical commands `show w' and `show c' should show the appropriate | ||||
| parts of the General Public License.  Of course, your program's commands | ||||
| might be different; for a GUI interface, you would use an "about box". | ||||
|  | ||||
|   You should also get your employer (if you work as a programmer) or school, | ||||
| if any, to sign a "copyright disclaimer" for the program, if necessary. | ||||
| For more information on this, and how to apply and follow the GNU GPL, see | ||||
| <https://www.gnu.org/licenses/>. | ||||
|  | ||||
|   The GNU General Public License does not permit incorporating your program | ||||
| into proprietary programs.  If your program is a subroutine library, you | ||||
| may consider it more useful to permit linking proprietary applications with | ||||
| the library.  If this is what you want to do, use the GNU Lesser General | ||||
| Public License instead of this License.  But first, please read | ||||
| <https://www.gnu.org/licenses/why-not-lgpl.html>. | ||||
							
								
								
									
										131
									
								
								README.md
									
									
									
									
									
								
							
							
						
						
									
										131
									
								
								README.md
									
									
									
									
									
								
							| @@ -1,127 +1,42 @@ | ||||
| # GlobalProtect-openconnect | ||||
|  | ||||
| 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/yuezk/GlobalProtect-openconnect/assets/3297602/9242df9c-217d-42ab-8c21-8f9f69cd4eb5"> | ||||
| </p> | ||||
|  | ||||
| ## Features | ||||
| ## Development | ||||
|  | ||||
| - [x] Better Linux support | ||||
| - [x] Support both CLI and GUI | ||||
| - [x] Support both SSO and non-SSO authentication | ||||
| - [x] Support multiple portals | ||||
| - [x] Support gateway selection | ||||
| - [x] Support auto-connect on startup | ||||
| - [x] Support system tray icon | ||||
| ### Dependencies | ||||
|  | ||||
| ## Usage | ||||
| The following packages will be required to build depending on your environment: | ||||
|  | ||||
| ### CLI | ||||
| - [Cargo](https://doc.rust-lang.org/cargo/getting-started/installation.html) | ||||
| - [pnpm](https://pnpm.io/installation) | ||||
| - openconnect-devel (containing `openconnect.h`): `sudo apt install libopenconnect-dev` or `sudo yum install openconnect-devel` | ||||
| - GDK dependencies `sudo apt install libgdk3.0-cil-dev libcairo2-dev libsoup2.4-dev libgdk-pixbuf-2.0-dev libjavascriptcoregtk-4.0-dev libatk1.0-dev libpango1.0-dev libwebkit2gtk-4.0-dev` | ||||
|  | ||||
| The CLI version is always free and open source in this repo. It has almost the same features as the GUI version. | ||||
| ### Build the service | ||||
|  | ||||
| ``` | ||||
| Usage: gpclient [OPTIONS] <COMMAND> | ||||
| ```sh | ||||
| # Build the client first | ||||
| cargo build -p gpclient | ||||
|  | ||||
| Commands: | ||||
|   connect     Connect to a portal server | ||||
|   disconnect  Disconnect from the server | ||||
|   launch-gui  Launch the GUI | ||||
|   help        Print this message or the help of the given subcommand(s) | ||||
|  | ||||
| Options: | ||||
|       --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. | ||||
| # Build the service | ||||
| cargo build -p gpservice | ||||
| ``` | ||||
|  | ||||
| ### GUI | ||||
| ### Start the service | ||||
|  | ||||
| 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. 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] | ||||
| > | ||||
| > This instruction is for the 2.x version. The 1.x version is still available on the [1.x](https://github.com/yuezk/GlobalProtect-openconnect/tree/1.x) branch, you can build it from the source code by following the instructions in the `README.md` file. | ||||
|  | ||||
| > [!Warning] | ||||
| > | ||||
| > The client requires `openconnect >= 8.20`, please make sure you have it installed, you can check it with `openconnect --version`. | ||||
| > Installing the client from PPA will automatically install the required version of `openconnect`. | ||||
|  | ||||
| ### Debian/Ubuntu based distributions | ||||
|  | ||||
| #### Install from PPA | ||||
|  | ||||
| ``` | ||||
| sudo add-apt-repository ppa:yuezk/globalprotect-openconnect | ||||
| sudo apt-get update | ||||
| sudo apt-get install globalprotect-openconnect | ||||
| ```sh | ||||
| sudo ./target/debug/gpservice | ||||
| ``` | ||||
|  | ||||
| > [!Note] | ||||
| > | ||||
| > 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`. | ||||
| ### Start the GUI | ||||
|  | ||||
| #### Install from deb package | ||||
|  | ||||
| Download the latest deb package from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page. Then install it with `dpkg`: | ||||
|  | ||||
| ```bash | ||||
| sudo dpkg -i globalprotect-openconnect_*.deb | ||||
| ```sh | ||||
| cd gpgui | ||||
| pnpm install | ||||
| pnpm tauri dev | ||||
| ``` | ||||
|  | ||||
| ### Arch Linux / Manjaro | ||||
| ### Open the DevTools | ||||
|  | ||||
| #### Install from AUR | ||||
|  | ||||
| Install from AUR: [globalprotect-openconnect-git](https://aur.archlinux.org/packages/globalprotect-openconnect-git/) | ||||
|  | ||||
| ``` | ||||
| yay -S globalprotect-openconnect-git | ||||
| ``` | ||||
|  | ||||
| #### Install from package | ||||
|  | ||||
| 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/OpenSUSE/CentOS/RHEL | ||||
|  | ||||
| #### Install from COPR | ||||
|  | ||||
| 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: | ||||
|  | ||||
| ``` | ||||
| sudo dnf copr enable yuezk/globalprotect-openconnect | ||||
| sudo dnf install globalprotect-openconnect | ||||
| ``` | ||||
|  | ||||
| #### Install from OBS | ||||
|  | ||||
| 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. | ||||
|  | ||||
| #### Install from RPM package | ||||
|  | ||||
| Download the latest RPM package from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page. | ||||
|  | ||||
| ### Other distributions | ||||
|  | ||||
| The project depends on `openconnect >= 8.20`, `webkit2gtk`, `libsecret`, `libayatana-appindicator` or `libappindicator-gtk3`. You can install them first and then download the latest binary release (i.e., `*.bin.tar.gz`) from [releases](https://github.com/yuezk/GlobalProtect-openconnect/releases) page. | ||||
|  | ||||
| ## [License](./LICENSE) | ||||
|  | ||||
| GPLv3 | ||||
| Right-click on the GUI window and select "Inspect Element". | ||||
|   | ||||
| @@ -1,23 +0,0 @@ | ||||
| [package] | ||||
| name = "gpauth" | ||||
| version.workspace = true | ||||
| edition.workspace = true | ||||
| license.workspace = true | ||||
|  | ||||
| [build-dependencies] | ||||
| tauri-build = { version = "1.5", features = [] } | ||||
|  | ||||
| [dependencies] | ||||
| gpapi = { path = "../../crates/gpapi", features = ["tauri", "clap"] } | ||||
| anyhow.workspace = true | ||||
| clap.workspace = true | ||||
| env_logger.workspace = true | ||||
| log.workspace = true | ||||
| regex.workspace = true | ||||
| serde_json.workspace = true | ||||
| tokio.workspace = true | ||||
| tokio-util.workspace = true | ||||
| tempfile.workspace = true | ||||
| webkit2gtk = "0.18.2" | ||||
| tauri = { workspace = true, features = ["http-all"] } | ||||
| compile-time.workspace = true | ||||
										
											Binary file not shown.
										
									
								
							| Before Width: | Height: | Size: 3.4 KiB | 
										
											Binary file not shown.
										
									
								
							| Before Width: | Height: | Size: 6.8 KiB | 
										
											Binary file not shown.
										
									
								
							| Before Width: | Height: | Size: 974 B | 
										
											Binary file not shown.
										
									
								
							
										
											Binary file not shown.
										
									
								
							| Before Width: | Height: | Size: 85 KiB | 
										
											Binary file not shown.
										
									
								
							| Before Width: | Height: | Size: 14 KiB | 
| @@ -1,11 +0,0 @@ | ||||
| <!DOCTYPE html> | ||||
| <html lang="en"> | ||||
| <head> | ||||
|   <meta charset="UTF-8"> | ||||
|   <meta name="viewport" content="width=device-width, initial-scale=1.0"> | ||||
|   <title>GlobalProtect Login</title> | ||||
| </head> | ||||
| <body> | ||||
|   <p>Redirecting to GlobalProtect Login...</p> | ||||
| </body> | ||||
| </html> | ||||
| @@ -1,486 +0,0 @@ | ||||
| use std::{ | ||||
|   rc::Rc, | ||||
|   sync::Arc, | ||||
|   time::{Duration, Instant}, | ||||
| }; | ||||
|  | ||||
| use anyhow::bail; | ||||
| use gpapi::{ | ||||
|   auth::SamlAuthData, | ||||
|   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)); | ||||
|           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); | ||||
|         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) => { | ||||
|             return Err(anyhow::anyhow!("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(crate) async fn portal_prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result<String> { | ||||
|   info!("Portal prelogin..."); | ||||
|  | ||||
|   match prelogin(portal, gp_params).await? { | ||||
|     Prelogin::Saml(prelogin) => Ok(prelogin.saml_request().to_string()), | ||||
|     Prelogin::Standard(_) => Err(anyhow::anyhow!("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(AuthResult) + 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(AuthDataError::Invalid)) | ||||
|     } | ||||
|   }); | ||||
| } | ||||
|  | ||||
| fn read_auth_data_from_html(html: &str) -> AuthResult { | ||||
|   if html.contains("Temporarily Unavailable") { | ||||
|     info!("Found 'Temporarily Unavailable' in HTML, auth failed"); | ||||
|     return Err(AuthDataError::Invalid); | ||||
|   } | ||||
|  | ||||
|   match parse_xml_tag(html, "saml-auth-status") { | ||||
|     Some(saml_status) if saml_status == "1" => { | ||||
|       let username = parse_xml_tag(html, "saml-username"); | ||||
|       let prelogin_cookie = parse_xml_tag(html, "prelogin-cookie"); | ||||
|       let portal_userauthcookie = parse_xml_tag(html, "portal-userauthcookie"); | ||||
|  | ||||
|       if SamlAuthData::check(&username, &prelogin_cookie, &portal_userauthcookie) { | ||||
|         return Ok(SamlAuthData::new( | ||||
|           username.unwrap(), | ||||
|           prelogin_cookie, | ||||
|           portal_userauthcookie, | ||||
|         )); | ||||
|       } | ||||
|  | ||||
|       info!("Found invalid auth data in HTML"); | ||||
|       Err(AuthDataError::Invalid) | ||||
|     } | ||||
|     Some(status) => { | ||||
|       info!("Found invalid SAML status {} in HTML", status); | ||||
|       Err(AuthDataError::Invalid) | ||||
|     } | ||||
|     None => { | ||||
|       info!("No auth data found in HTML"); | ||||
|       Err(AuthDataError::NotFound) | ||||
|     } | ||||
|   } | ||||
| } | ||||
|  | ||||
| fn read_auth_data(main_resource: &WebResource, auth_result_tx: mpsc::UnboundedSender<AuthResult>) { | ||||
|   if main_resource.response().is_none() { | ||||
|     info!("No response found in main resource"); | ||||
|     send_auth_result(&auth_result_tx, Err(AuthDataError::Invalid)); | ||||
|     return; | ||||
|   } | ||||
|  | ||||
|   let response = main_resource.response().unwrap(); | ||||
|   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(|_| 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..."); | ||||
|       read_auth_data_from_body(main_resource, move |auth_result| { | ||||
|         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)); | ||||
|     } | ||||
|   } | ||||
| } | ||||
|  | ||||
| fn parse_xml_tag(html: &str, tag: &str) -> Option<String> { | ||||
|   let re = Regex::new(&format!("<{}>(.*)</{}>", tag, tag)).unwrap(); | ||||
|   re.captures(html) | ||||
|     .and_then(|captures| captures.get(1)) | ||||
|     .map(|m| m.as_str().to_string()) | ||||
| } | ||||
|  | ||||
| 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)) | ||||
| } | ||||
| @@ -1,164 +0,0 @@ | ||||
| use clap::Parser; | ||||
| use gpapi::{ | ||||
|   auth::{SamlAuthData, SamlAuthResult}, | ||||
|   clap::args::Os, | ||||
|   gp_params::{ClientOs, GpParams}, | ||||
|   utils::{normalize_server, openssl}, | ||||
|   GP_USER_AGENT, | ||||
| }; | ||||
| use log::{info, LevelFilter}; | ||||
| use serde_json::json; | ||||
| use tauri::{App, AppHandle, RunEvent}; | ||||
| use tempfile::NamedTempFile; | ||||
|  | ||||
| use crate::auth_window::{portal_prelogin, AuthWindow}; | ||||
|  | ||||
| const VERSION: &str = concat!( | ||||
|   env!("CARGO_PKG_VERSION"), | ||||
|   " (", | ||||
|   compile_time::date_str!(), | ||||
|   ")" | ||||
| ); | ||||
|  | ||||
| #[derive(Parser, Clone)] | ||||
| #[command(version = VERSION)] | ||||
| struct Cli { | ||||
|   server: String, | ||||
|   #[arg(long)] | ||||
|   saml_request: Option<String>, | ||||
|   #[arg(long, default_value = GP_USER_AGENT)] | ||||
|   user_agent: String, | ||||
|   #[arg(long, default_value = "Linux")] | ||||
|   os: Os, | ||||
|   #[arg(long)] | ||||
|   os_version: Option<String>, | ||||
|   #[arg(long)] | ||||
|   hidpi: bool, | ||||
|   #[arg(long)] | ||||
|   fix_openssl: bool, | ||||
|   #[arg(long)] | ||||
|   ignore_tls_errors: bool, | ||||
|   #[arg(long)] | ||||
|   clean: bool, | ||||
| } | ||||
|  | ||||
| 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?, | ||||
|     }; | ||||
|  | ||||
|     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>> { | ||||
|     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"); | ||||
|       let file = openssl::fix_openssl_env()?; | ||||
|  | ||||
|       return Ok(Some(file)); | ||||
|     } | ||||
|  | ||||
|     Ok(None) | ||||
|   } | ||||
|  | ||||
|   fn build_gp_params(&self) -> GpParams { | ||||
|     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) | ||||
|       .build(); | ||||
|  | ||||
|     gp_params | ||||
|   } | ||||
|  | ||||
|   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); | ||||
|  | ||||
|     auth_window.open().await | ||||
|   } | ||||
| } | ||||
|  | ||||
| fn create_app(cli: Cli) -> anyhow::Result<App> { | ||||
|   let app = tauri::Builder::default() | ||||
|     .setup(|app| { | ||||
|       let app_handle = app.handle(); | ||||
|  | ||||
|       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 mut cli = Cli::parse(); | ||||
|  | ||||
|   init_logger(); | ||||
|   info!("gpauth started: {}", VERSION); | ||||
|  | ||||
|   if let Err(err) = cli.run().await { | ||||
|     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); | ||||
|   } | ||||
| } | ||||
| @@ -1,9 +0,0 @@ | ||||
| #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] | ||||
|  | ||||
| mod auth_window; | ||||
| mod cli; | ||||
|  | ||||
| #[tokio::main] | ||||
| async fn main() { | ||||
|   cli::run().await; | ||||
| } | ||||
| @@ -1,47 +0,0 @@ | ||||
| { | ||||
|   "$schema": "https://cdn.jsdelivr.net/gh/tauri-apps/tauri@tauri-v1.5.0/tooling/cli/schema.json", | ||||
|   "build": { | ||||
|     "distDir": [ | ||||
|       "index.html" | ||||
|     ], | ||||
|     "devPath": [ | ||||
|       "index.html" | ||||
|     ], | ||||
|     "beforeDevCommand": "", | ||||
|     "beforeBuildCommand": "", | ||||
|     "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/128x128@2x.png", | ||||
|         "icons/icon.icns", | ||||
|         "icons/icon.ico" | ||||
|       ] | ||||
|     }, | ||||
|     "security": { | ||||
|       "csp": null | ||||
|     }, | ||||
|     "windows": [] | ||||
|   } | ||||
| } | ||||
| @@ -1,23 +0,0 @@ | ||||
| [package] | ||||
| name = "gpclient" | ||||
| authors.workspace = true | ||||
| version.workspace = true | ||||
| edition.workspace = true | ||||
| license.workspace = true | ||||
|  | ||||
| [dependencies] | ||||
| gpapi = { path = "../../crates/gpapi", features = ["clap"] } | ||||
| openconnect = { path = "../../crates/openconnect" } | ||||
| anyhow.workspace = true | ||||
| clap.workspace = true | ||||
| env_logger.workspace = true | ||||
| inquire = "0.6.2" | ||||
| log.workspace = true | ||||
| tokio.workspace = true | ||||
| sysinfo.workspace = true | ||||
| serde_json.workspace = true | ||||
| whoami.workspace = true | ||||
| tempfile.workspace = true | ||||
| reqwest.workspace = true | ||||
| directories = "5.0" | ||||
| compile-time.workspace = true | ||||
| @@ -1,129 +0,0 @@ | ||||
| use clap::{Parser, Subcommand}; | ||||
| use gpapi::utils::openssl; | ||||
| use log::{info, LevelFilter}; | ||||
| use tempfile::NamedTempFile; | ||||
|  | ||||
| use crate::{ | ||||
|   connect::{ConnectArgs, ConnectHandler}, | ||||
|   disconnect::DisconnectHandler, | ||||
|   launch_gui::{LaunchGuiArgs, LaunchGuiHandler}, | ||||
| }; | ||||
|  | ||||
| const VERSION: &str = concat!( | ||||
|   env!("CARGO_PKG_VERSION"), | ||||
|   " (", | ||||
|   compile_time::date_str!(), | ||||
|   ")" | ||||
| ); | ||||
|  | ||||
| pub(crate) struct SharedArgs { | ||||
|   pub(crate) fix_openssl: bool, | ||||
|   pub(crate) ignore_tls_errors: bool, | ||||
| } | ||||
|  | ||||
| #[derive(Subcommand)] | ||||
| enum CliCommand { | ||||
|   #[command(about = "Connect to a portal server")] | ||||
|   Connect(ConnectArgs), | ||||
|   #[command(about = "Disconnect from the server")] | ||||
|   Disconnect, | ||||
|   #[command(about = "Launch the GUI")] | ||||
|   LaunchGui(LaunchGuiArgs), | ||||
| } | ||||
|  | ||||
| #[derive(Parser)] | ||||
| #[command( | ||||
|   version = VERSION, | ||||
|   author, | ||||
|   about = "The GlobalProtect VPN client, based on OpenConnect, supports the SSO authentication method.", | ||||
|   help_template = "\ | ||||
| {before-help}{name} {version} | ||||
| {author} | ||||
|  | ||||
| {about} | ||||
|  | ||||
| {usage-heading} {usage} | ||||
|  | ||||
| {all-args}{after-help} | ||||
|  | ||||
| See 'gpclient help <command>' for more information on a specific command. | ||||
| " | ||||
| )] | ||||
| struct Cli { | ||||
|   #[command(subcommand)] | ||||
|   command: CliCommand, | ||||
|  | ||||
|   #[arg( | ||||
|     long, | ||||
|     help = "Get around the OpenSSL `unsafe legacy renegotiation` error" | ||||
|   )] | ||||
|   fix_openssl: bool, | ||||
|   #[arg(long, help = "Ignore the TLS errors")] | ||||
|   ignore_tls_errors: bool, | ||||
| } | ||||
|  | ||||
| impl Cli { | ||||
|   fn fix_openssl(&self) -> anyhow::Result<Option<NamedTempFile>> { | ||||
|     if self.fix_openssl { | ||||
|       let file = openssl::fix_openssl_env()?; | ||||
|       return Ok(Some(file)); | ||||
|     } | ||||
|  | ||||
|     Ok(None) | ||||
|   } | ||||
|  | ||||
|   async fn run(&self) -> anyhow::Result<()> { | ||||
|     // 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, | ||||
|     }; | ||||
|  | ||||
|     if self.ignore_tls_errors { | ||||
|       info!("TLS errors will be ignored"); | ||||
|     } | ||||
|  | ||||
|     match &self.command { | ||||
|       CliCommand::Connect(args) => ConnectHandler::new(args, &shared_args).handle().await, | ||||
|       CliCommand::Disconnect => DisconnectHandler::new().handle(), | ||||
|       CliCommand::LaunchGui(args) => LaunchGuiHandler::new(args).handle().await, | ||||
|     } | ||||
|   } | ||||
| } | ||||
|  | ||||
| fn init_logger() { | ||||
|   env_logger::builder().filter_level(LevelFilter::Info).init(); | ||||
| } | ||||
|  | ||||
| pub(crate) async fn run() { | ||||
|   let cli = Cli::parse(); | ||||
|  | ||||
|   init_logger(); | ||||
|   info!("gpclient started: {}", VERSION); | ||||
|  | ||||
|   if let Err(err) = cli.run().await { | ||||
|     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") { | ||||
|       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); | ||||
|   } | ||||
| } | ||||
| @@ -1,175 +0,0 @@ | ||||
| use std::{fs, sync::Arc}; | ||||
|  | ||||
| use clap::Args; | ||||
| use gpapi::{ | ||||
|   clap::args::Os, | ||||
|   credential::{Credential, PasswordCredential}, | ||||
|   gateway::gateway_login, | ||||
|   gp_params::{ClientOs, GpParams}, | ||||
|   portal::{prelogin, retrieve_config, Prelogin}, | ||||
|   process::auth_launcher::SamlAuthLauncher, | ||||
|   utils::{self, 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, short, help = "The VPNC script to use")] | ||||
|   script: Option<String>, | ||||
|   #[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)] | ||||
|   os_version: Option<String>, | ||||
|   #[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, | ||||
| } | ||||
|  | ||||
| impl ConnectArgs { | ||||
|   fn os_version(&self) -> String { | ||||
|     if let Some(os_version) = &self.os_version { | ||||
|       return os_version.to_owned(); | ||||
|     } | ||||
|  | ||||
|     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, | ||||
| } | ||||
|  | ||||
| impl<'a> ConnectHandler<'a> { | ||||
|   pub(crate) fn new(args: &'a ConnectArgs, shared_args: &'a SharedArgs) -> Self { | ||||
|     Self { args, shared_args } | ||||
|   } | ||||
|  | ||||
|   pub(crate) async fn handle(&self) -> anyhow::Result<()> { | ||||
|     let portal = utils::normalize_server(self.args.server.as_str())?; | ||||
|  | ||||
|     let gp_params = 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) | ||||
|       .build(); | ||||
|  | ||||
|     let prelogin = prelogin(&portal, &gp_params).await?; | ||||
|     let portal_credential = self.obtain_portal_credential(&prelogin).await?; | ||||
|     let mut portal_config = retrieve_config(&portal, &portal_credential, &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 {}", gateway))?, | ||||
|       None => { | ||||
|         portal_config.sort_gateways(prelogin.region()); | ||||
|         let gateways = portal_config.gateways(); | ||||
|  | ||||
|         if gateways.len() > 1 { | ||||
|           Select::new("Which gateway do you want to connect to?", gateways) | ||||
|             .with_vim_mode(true) | ||||
|             .prompt()? | ||||
|         } else { | ||||
|           gateways[0] | ||||
|         } | ||||
|       } | ||||
|     }; | ||||
|  | ||||
|     let gateway = selected_gateway.server(); | ||||
|     let cred = portal_config.auth_cookie().into(); | ||||
|     let token = gateway_login(gateway, &cred, &gp_params).await?; | ||||
|  | ||||
|     let vpn = Vpn::builder(gateway, &token) | ||||
|       .user_agent(self.args.user_agent.clone()) | ||||
|       .script(self.args.script.clone()) | ||||
|       .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_portal_credential(&self, prelogin: &Prelogin) -> anyhow::Result<Credential> { | ||||
|     match prelogin { | ||||
|       Prelogin::Saml(prelogin) => { | ||||
|         SamlAuthLauncher::new(&self.args.server) | ||||
|           .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) | ||||
|           .launch() | ||||
|           .await | ||||
|       } | ||||
|       Prelogin::Standard(prelogin) => { | ||||
|         println!("{}", prelogin.auth_message()); | ||||
|  | ||||
|         let user = self.args.user.as_ref().map_or_else( | ||||
|           || Text::new(&format!("{}:", prelogin.label_username())).prompt(), | ||||
|           |user| Ok(user.to_owned()), | ||||
|         )?; | ||||
|         let password = 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 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); | ||||
| } | ||||
| @@ -1,31 +0,0 @@ | ||||
| use crate::GP_CLIENT_LOCK_FILE; | ||||
| use log::{info, warn}; | ||||
| use std::fs; | ||||
| use sysinfo::{Pid, ProcessExt, Signal, System, SystemExt}; | ||||
|  | ||||
| pub(crate) struct DisconnectHandler; | ||||
|  | ||||
| impl DisconnectHandler { | ||||
|   pub(crate) fn new() -> Self { | ||||
|     Self | ||||
|   } | ||||
|  | ||||
|   pub(crate) fn handle(&self) -> anyhow::Result<()> { | ||||
|     if fs::metadata(GP_CLIENT_LOCK_FILE).is_err() { | ||||
|       warn!("PID file not found, maybe the client is not running"); | ||||
|       return Ok(()); | ||||
|     } | ||||
|  | ||||
|     let pid = fs::read_to_string(GP_CLIENT_LOCK_FILE)?; | ||||
|     let pid = pid.trim().parse::<usize>()?; | ||||
|     let s = System::new_all(); | ||||
|  | ||||
|     if let Some(process) = s.process(Pid::from(pid)) { | ||||
|       info!("Found process {}, killing...", pid); | ||||
|       if process.kill_with(Signal::Interrupt).is_none() { | ||||
|         warn!("Failed to kill process {}", pid); | ||||
|       } | ||||
|     } | ||||
|     Ok(()) | ||||
|   } | ||||
| } | ||||
| @@ -1,88 +0,0 @@ | ||||
| use std::{collections::HashMap, fs, path::PathBuf}; | ||||
|  | ||||
| use clap::Args; | ||||
| use directories::ProjectDirs; | ||||
| use gpapi::{ | ||||
|   process::service_launcher::ServiceLauncher, | ||||
|   utils::{endpoint::http_endpoint, env_file, shutdown_signal}, | ||||
| }; | ||||
| use log::info; | ||||
|  | ||||
| #[derive(Args)] | ||||
| pub(crate) struct LaunchGuiArgs { | ||||
|   #[clap(long, help = "Launch the GUI minimized")] | ||||
|   minimized: bool, | ||||
| } | ||||
|  | ||||
| pub(crate) struct LaunchGuiHandler<'a> { | ||||
|   args: &'a LaunchGuiArgs, | ||||
| } | ||||
|  | ||||
| impl<'a> LaunchGuiHandler<'a> { | ||||
|   pub(crate) fn new(args: &'a LaunchGuiArgs) -> Self { | ||||
|     Self { args } | ||||
|   } | ||||
|  | ||||
|   pub(crate) async fn handle(&self) -> anyhow::Result<()> { | ||||
|     // `launch-gui`cannot be run as root | ||||
|     let user = whoami::username(); | ||||
|     if user == "root" { | ||||
|       anyhow::bail!("`launch-gui` cannot be run as root"); | ||||
|     } | ||||
|  | ||||
|     if try_active_gui().await.is_ok() { | ||||
|       info!("The GUI is already running"); | ||||
|       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 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?; | ||||
|  | ||||
|     info!("Service exited with status: {}", exit_status); | ||||
|  | ||||
|     Ok(()) | ||||
|   } | ||||
| } | ||||
|  | ||||
| async fn try_active_gui() -> anyhow::Result<()> { | ||||
|   let service_endpoint = http_endpoint().await?; | ||||
|  | ||||
|   reqwest::Client::default() | ||||
|     .post(format!("{}/active-gui", service_endpoint)) | ||||
|     .send() | ||||
|     .await? | ||||
|     .error_for_status()?; | ||||
|  | ||||
|   Ok(()) | ||||
| } | ||||
|  | ||||
| pub fn get_log_file() -> anyhow::Result<PathBuf> { | ||||
|   let dirs = ProjectDirs::from("com.yuezk", "GlobalProtect-openconnect", "gpclient") | ||||
|     .ok_or_else(|| anyhow::anyhow!("Failed to get project dirs"))?; | ||||
|  | ||||
|   fs::create_dir_all(dirs.data_dir())?; | ||||
|  | ||||
|   Ok(dirs.data_dir().join("gpclient.log")) | ||||
| } | ||||
| @@ -1,11 +0,0 @@ | ||||
| mod cli; | ||||
| mod connect; | ||||
| mod disconnect; | ||||
| mod launch_gui; | ||||
|  | ||||
| pub(crate) const GP_CLIENT_LOCK_FILE: &str = "/var/run/gpclient.lock"; | ||||
|  | ||||
| #[tokio::main] | ||||
| async fn main() { | ||||
|   cli::run().await; | ||||
| } | ||||
| @@ -1,19 +0,0 @@ | ||||
| [package] | ||||
| name = "gpservice" | ||||
| version.workspace = true | ||||
| edition.workspace = true | ||||
| license.workspace = true | ||||
|  | ||||
| [dependencies] | ||||
| gpapi = { path = "../../crates/gpapi" } | ||||
| openconnect = { path = "../../crates/openconnect" } | ||||
| clap.workspace = true | ||||
| anyhow.workspace = true | ||||
| tokio.workspace = true | ||||
| tokio-util.workspace = true | ||||
| axum = { workspace = true, features = ["ws"] } | ||||
| futures.workspace = true | ||||
| serde_json.workspace = true | ||||
| env_logger.workspace = true | ||||
| log.workspace = true | ||||
| compile-time.workspace = true | ||||
| @@ -1,19 +0,0 @@ | ||||
| <?xml version="1.0" encoding="UTF-8"?> | ||||
| <!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN" "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd"> | ||||
| <policyconfig> | ||||
|   <vendor>GlobalProtect-openconnect</vendor> | ||||
|   <vendor_url>https://github.com/yuezk/GlobalProtect-openconnect</vendor_url> | ||||
|   <icon_name>gpgui</icon_name> | ||||
|   <action id="com.yuezk.gpservice"> | ||||
|     <description>Run GPService as root</description> | ||||
|     <message>Authentication is required to run the GPService as root</message> | ||||
|     <defaults> | ||||
|       <allow_any>yes</allow_any> | ||||
|       <allow_inactive>yes</allow_inactive> | ||||
|       <allow_active>yes</allow_active> | ||||
|     </defaults> | ||||
|     <annotate key="org.freedesktop.policykit.exec.path">/home/kevin/Documents/repos/gp/target/debug/gpservice</annotate> | ||||
|     <annotate key="org.freedesktop.policykit.exec.argv1">--with-gui</annotate> | ||||
|     <annotate key="org.freedesktop.policykit.exec.allow_gui">true</annotate> | ||||
|   </action> | ||||
| </policyconfig> | ||||
| @@ -1,182 +0,0 @@ | ||||
| use std::sync::Arc; | ||||
| use std::{collections::HashMap, io::Write}; | ||||
|  | ||||
| use anyhow::bail; | ||||
| use clap::Parser; | ||||
| use gpapi::{ | ||||
|   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, | ||||
| }; | ||||
| use log::{info, warn, LevelFilter}; | ||||
| use tokio::sync::{mpsc, watch}; | ||||
|  | ||||
| use crate::{vpn_task::VpnTask, ws_server::WsServer}; | ||||
|  | ||||
| const VERSION: &str = concat!( | ||||
|   env!("CARGO_PKG_VERSION"), | ||||
|   " (", | ||||
|   compile_time::date_str!(), | ||||
|   ")" | ||||
| ); | ||||
|  | ||||
| #[derive(Parser)] | ||||
| #[command(version = VERSION)] | ||||
| struct Cli { | ||||
|   #[clap(long)] | ||||
|   minimized: bool, | ||||
|   #[clap(long)] | ||||
|   env_file: Option<String>, | ||||
|   #[cfg(debug_assertions)] | ||||
|   #[clap(long)] | ||||
|   no_gui: bool, | ||||
| } | ||||
|  | ||||
| impl Cli { | ||||
|   async fn run(&mut self, redaction: Arc<Redaction>) -> anyhow::Result<()> { | ||||
|     let lock_file = Arc::new(LockFile::new(GP_SERVICE_LOCK_FILE)); | ||||
|  | ||||
|     if lock_file.check_health().await { | ||||
|       bail!("Another instance of the service is already running"); | ||||
|     } | ||||
|  | ||||
|     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 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_token = vpn_task.cancel_token(); | ||||
|     let server_token = ws_server.cancel_token(); | ||||
|  | ||||
|     let vpn_task_handle = tokio::spawn(async move { vpn_task.start(server_token).await }); | ||||
|     let ws_server_handle = tokio::spawn(async move { ws_server.start(shutdown_tx_clone).await }); | ||||
|  | ||||
|     #[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 { | ||||
|       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() => { | ||||
|             info!("Shutdown signal received"); | ||||
|         } | ||||
|         _ = shutdown_rx.recv() => { | ||||
|             info!("Shutdown request received, shutting down"); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     vpn_task_token.cancel(); | ||||
|     let _ = tokio::join!(vpn_task_handle, ws_server_handle); | ||||
|  | ||||
|     lock_file.unlock()?; | ||||
|  | ||||
|     info!("gpservice stopped"); | ||||
|  | ||||
|     Ok(()) | ||||
|   } | ||||
|  | ||||
|   fn prepare_api_key(&self) -> Vec<u8> { | ||||
|     #[cfg(debug_assertions)] | ||||
|     if self.no_gui { | ||||
|       return gpapi::GP_API_KEY.to_vec(); | ||||
|     } | ||||
|  | ||||
|     generate_key().to_vec() | ||||
|   } | ||||
| } | ||||
|  | ||||
| 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(); | ||||
|  | ||||
|   redaction | ||||
| } | ||||
|  | ||||
| async fn launch_gui(envs: Option<HashMap<String, String>>, api_key: Vec<u8>, mut minimized: bool) { | ||||
|   loop { | ||||
|     let api_key_clone = api_key.clone(); | ||||
|     let gui_launcher = GuiLauncher::new() | ||||
|       .envs(envs.clone()) | ||||
|       .api_key(api_key_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(); | ||||
|  | ||||
|   let redaction = init_logger(); | ||||
|   info!("gpservice started: {}", VERSION); | ||||
|  | ||||
|   if let Err(e) = cli.run(redaction).await { | ||||
|     eprintln!("Error: {}", e); | ||||
|     std::process::exit(1); | ||||
|   } | ||||
| } | ||||
| @@ -1,94 +0,0 @@ | ||||
| use std::{borrow::Cow, ops::ControlFlow, sync::Arc}; | ||||
|  | ||||
| use axum::{ | ||||
|   extract::{ | ||||
|     ws::{self, CloseFrame, Message, WebSocket}, | ||||
|     State, WebSocketUpgrade, | ||||
|   }, | ||||
|   response::IntoResponse, | ||||
| }; | ||||
| use futures::{SinkExt, StreamExt}; | ||||
| use gpapi::service::event::WsEvent; | ||||
| use log::{info, warn}; | ||||
|  | ||||
| use crate::ws_server::WsServerContext; | ||||
|  | ||||
| pub(crate) async fn health() -> impl IntoResponse { | ||||
|   "OK" | ||||
| } | ||||
|  | ||||
| pub(crate) async fn active_gui(State(ctx): State<Arc<WsServerContext>>) -> impl IntoResponse { | ||||
|   ctx.send_event(WsEvent::ActiveGui).await; | ||||
| } | ||||
|  | ||||
| pub(crate) async fn ws_handler( | ||||
|   ws: WebSocketUpgrade, | ||||
|   State(ctx): State<Arc<WsServerContext>>, | ||||
| ) -> impl IntoResponse { | ||||
|   ws.on_upgrade(move |socket| handle_socket(socket, ctx)) | ||||
| } | ||||
|  | ||||
| async fn handle_socket(mut socket: WebSocket, ctx: Arc<WsServerContext>) { | ||||
|   // Send ping message | ||||
|   if let Err(err) = socket.send(Message::Ping("Hi".into())).await { | ||||
|     warn!("Failed to send ping: {}", err); | ||||
|     return; | ||||
|   } | ||||
|  | ||||
|   // Wait for pong message | ||||
|   if socket.recv().await.is_none() { | ||||
|     warn!("Failed to receive pong"); | ||||
|     return; | ||||
|   } | ||||
|  | ||||
|   info!("New client connected"); | ||||
|  | ||||
|   let (mut sender, mut receiver) = socket.split(); | ||||
|   let (connection, mut msg_rx) = ctx.add_connection().await; | ||||
|  | ||||
|   let send_task = tokio::spawn(async move { | ||||
|     while let Some(msg) = msg_rx.recv().await { | ||||
|       if let Err(err) = sender.send(msg).await { | ||||
|         info!("Failed to send message: {}", err); | ||||
|         break; | ||||
|       } | ||||
|     } | ||||
|  | ||||
|     let close_msg = Message::Close(Some(CloseFrame { | ||||
|       code: ws::close_code::NORMAL, | ||||
|       reason: Cow::from("Goodbye"), | ||||
|     })); | ||||
|  | ||||
|     if let Err(err) = sender.send(close_msg).await { | ||||
|       warn!("Failed to close socket: {}", err); | ||||
|     } | ||||
|   }); | ||||
|  | ||||
|   let conn = Arc::clone(&connection); | ||||
|   let ctx_clone = Arc::clone(&ctx); | ||||
|   let recv_task = tokio::spawn(async move { | ||||
|     while let Some(Ok(msg)) = receiver.next().await { | ||||
|       let ControlFlow::Continue(ws_req) = conn.recv_msg(msg) else { | ||||
|         break; | ||||
|       }; | ||||
|  | ||||
|       if let Err(err) = ctx_clone.forward_req(ws_req).await { | ||||
|         info!("Failed to forward request: {}", err); | ||||
|         break; | ||||
|       } | ||||
|     } | ||||
|   }); | ||||
|  | ||||
|   tokio::select! { | ||||
|     _ = send_task => { | ||||
|         info!("WS server send task completed"); | ||||
|     }, | ||||
|     _ = recv_task => { | ||||
|         info!("WS server recv task completed"); | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   info!("Client disconnected"); | ||||
|  | ||||
|   ctx.remove_connection(connection).await; | ||||
| } | ||||
| @@ -1,11 +0,0 @@ | ||||
| mod cli; | ||||
| mod handlers; | ||||
| mod routes; | ||||
| mod vpn_task; | ||||
| mod ws_server; | ||||
| mod ws_connection; | ||||
|  | ||||
| #[tokio::main] | ||||
| async fn main() { | ||||
|   cli::run().await; | ||||
| } | ||||
| @@ -1,13 +0,0 @@ | ||||
| use std::sync::Arc; | ||||
|  | ||||
| use axum::{routing::{get, post}, Router}; | ||||
|  | ||||
| use crate::{handlers, ws_server::WsServerContext}; | ||||
|  | ||||
| pub(crate) fn routes(ctx: Arc<WsServerContext>) -> Router { | ||||
|   Router::new() | ||||
|     .route("/health", get(handlers::health)) | ||||
|     .route("/active-gui", post(handlers::active_gui)) | ||||
|     .route("/ws", get(handlers::ws_handler)) | ||||
|     .with_state(ctx) | ||||
| } | ||||
| @@ -1,144 +0,0 @@ | ||||
| use std::{sync::Arc, thread}; | ||||
|  | ||||
| use gpapi::service::{ | ||||
|   request::{ConnectRequest, WsRequest}, | ||||
|   vpn_state::VpnState, | ||||
| }; | ||||
| use log::info; | ||||
| use openconnect::Vpn; | ||||
| use tokio::sync::{mpsc, oneshot, watch, RwLock}; | ||||
| use tokio_util::sync::CancellationToken; | ||||
|  | ||||
| pub(crate) struct VpnTaskContext { | ||||
|   vpn_handle: Arc<RwLock<Option<Vpn>>>, | ||||
|   vpn_state_tx: Arc<watch::Sender<VpnState>>, | ||||
|   disconnect_rx: RwLock<Option<oneshot::Receiver<()>>>, | ||||
| } | ||||
|  | ||||
| impl VpnTaskContext { | ||||
|   pub fn new(vpn_state_tx: watch::Sender<VpnState>) -> Self { | ||||
|     Self { | ||||
|       vpn_handle: Default::default(), | ||||
|       vpn_state_tx: Arc::new(vpn_state_tx), | ||||
|       disconnect_rx: Default::default(), | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub async fn connect(&self, req: ConnectRequest) { | ||||
|     let vpn_state = self.vpn_state_tx.borrow().clone(); | ||||
|     if !matches!(vpn_state, VpnState::Disconnected) { | ||||
|       info!("VPN is not disconnected, ignore the request"); | ||||
|       return; | ||||
|     } | ||||
|  | ||||
|     let info = req.info().clone(); | ||||
|     let vpn_handle = self.vpn_handle.clone(); | ||||
|     let args = req.args(); | ||||
|     let vpn = Vpn::builder(req.gateway().server(), args.cookie()) | ||||
|       .user_agent(args.user_agent()) | ||||
|       .script(args.vpnc_script()) | ||||
|       .os(args.openconnect_os()) | ||||
|       .build(); | ||||
|  | ||||
|     // Save the VPN handle | ||||
|     vpn_handle.write().await.replace(vpn); | ||||
|  | ||||
|     let vpn_state_tx = self.vpn_state_tx.clone(); | ||||
|     let connect_info = Box::new(info.clone()); | ||||
|     vpn_state_tx.send(VpnState::Connecting(connect_info)).ok(); | ||||
|  | ||||
|     let (disconnect_tx, disconnect_rx) = oneshot::channel::<()>(); | ||||
|     self.disconnect_rx.write().await.replace(disconnect_rx); | ||||
|  | ||||
|     // Spawn a new thread to process the VPN connection, cannot use tokio::spawn here. | ||||
|     // Otherwise, it will block the tokio runtime and cannot send the VPN state to the channel | ||||
|     thread::spawn(move || { | ||||
|       let vpn_state_tx_clone = vpn_state_tx.clone(); | ||||
|  | ||||
|       vpn_handle.blocking_read().as_ref().map(|vpn| { | ||||
|         vpn.connect(move || { | ||||
|           let connect_info = Box::new(info.clone()); | ||||
|           vpn_state_tx.send(VpnState::Connected(connect_info)).ok(); | ||||
|         }) | ||||
|       }); | ||||
|  | ||||
|       // Notify the VPN is disconnected | ||||
|       vpn_state_tx_clone.send(VpnState::Disconnected).ok(); | ||||
|       // Remove the VPN handle | ||||
|       vpn_handle.blocking_write().take(); | ||||
|  | ||||
|       disconnect_tx.send(()).ok(); | ||||
|     }); | ||||
|   } | ||||
|  | ||||
|   pub async fn disconnect(&self) { | ||||
|     if let Some(disconnect_rx) = self.disconnect_rx.write().await.take() { | ||||
|       if let Some(vpn) = self.vpn_handle.read().await.as_ref() { | ||||
|         self.vpn_state_tx.send(VpnState::Disconnecting).ok(); | ||||
|         vpn.disconnect() | ||||
|       } | ||||
|       // Wait for the VPN to be disconnected | ||||
|       disconnect_rx.await.ok(); | ||||
|       info!("VPN disconnected"); | ||||
|     } else { | ||||
|       info!("VPN is not connected, skip disconnect"); | ||||
|       self.vpn_state_tx.send(VpnState::Disconnected).ok(); | ||||
|     } | ||||
|   } | ||||
| } | ||||
|  | ||||
| pub(crate) struct VpnTask { | ||||
|   ws_req_rx: mpsc::Receiver<WsRequest>, | ||||
|   ctx: Arc<VpnTaskContext>, | ||||
|   cancel_token: CancellationToken, | ||||
| } | ||||
|  | ||||
| impl VpnTask { | ||||
|   pub fn new(ws_req_rx: mpsc::Receiver<WsRequest>, vpn_state_tx: watch::Sender<VpnState>) -> Self { | ||||
|     let ctx = Arc::new(VpnTaskContext::new(vpn_state_tx)); | ||||
|     let cancel_token = CancellationToken::new(); | ||||
|  | ||||
|     Self { | ||||
|       ws_req_rx, | ||||
|       ctx, | ||||
|       cancel_token, | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub fn cancel_token(&self) -> CancellationToken { | ||||
|     self.cancel_token.clone() | ||||
|   } | ||||
|  | ||||
|   pub async fn start(&mut self, server_cancel_token: CancellationToken) { | ||||
|     let cancel_token = self.cancel_token.clone(); | ||||
|  | ||||
|     tokio::select! { | ||||
|         _ = self.recv() => { | ||||
|             info!("VPN task stopped"); | ||||
|         } | ||||
|         _ = cancel_token.cancelled() => { | ||||
|             info!("VPN task cancelled"); | ||||
|             self.ctx.disconnect().await; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     server_cancel_token.cancel(); | ||||
|   } | ||||
|  | ||||
|   async fn recv(&mut self) { | ||||
|     while let Some(req) = self.ws_req_rx.recv().await { | ||||
|       tokio::spawn(process_ws_req(req, self.ctx.clone())); | ||||
|     } | ||||
|   } | ||||
| } | ||||
|  | ||||
| async fn process_ws_req(req: WsRequest, ctx: Arc<VpnTaskContext>) { | ||||
|   match req { | ||||
|     WsRequest::Connect(req) => { | ||||
|       ctx.connect(*req).await; | ||||
|     } | ||||
|     WsRequest::Disconnect(_) => { | ||||
|       ctx.disconnect().await; | ||||
|     } | ||||
|   } | ||||
| } | ||||
| @@ -1,53 +0,0 @@ | ||||
| use std::{ops::ControlFlow, sync::Arc}; | ||||
|  | ||||
| use axum::extract::ws::{CloseFrame, Message}; | ||||
| use gpapi::{ | ||||
|   service::{event::WsEvent, request::WsRequest}, | ||||
|   utils::crypto::Crypto, | ||||
| }; | ||||
| use log::{info, warn}; | ||||
| use tokio::sync::mpsc; | ||||
|  | ||||
| pub(crate) struct WsConnection { | ||||
|   crypto: Arc<Crypto>, | ||||
|   tx: mpsc::Sender<Message>, | ||||
| } | ||||
|  | ||||
| impl WsConnection { | ||||
|   pub fn new(crypto: Arc<Crypto>, tx: mpsc::Sender<Message>) -> Self { | ||||
|     Self { crypto, tx } | ||||
|   } | ||||
|  | ||||
|   pub async fn send_event(&self, event: &WsEvent) -> anyhow::Result<()> { | ||||
|     let encrypted = self.crypto.encrypt(event)?; | ||||
|     let msg = Message::Binary(encrypted); | ||||
|  | ||||
|     self.tx.send(msg).await?; | ||||
|  | ||||
|     Ok(()) | ||||
|   } | ||||
|  | ||||
|   pub fn recv_msg(&self, msg: Message) -> ControlFlow<(), WsRequest> { | ||||
|     match msg { | ||||
|       Message::Binary(data) => match self.crypto.decrypt(data) { | ||||
|         Ok(ws_req) => ControlFlow::Continue(ws_req), | ||||
|         Err(err) => { | ||||
|           info!("Failed to decrypt message: {}", err); | ||||
|           ControlFlow::Break(()) | ||||
|         } | ||||
|       }, | ||||
|       Message::Close(cf) => { | ||||
|         if let Some(CloseFrame { code, reason }) = cf { | ||||
|           info!("Client sent close, code {} and reason `{}`", code, reason); | ||||
|         } else { | ||||
|           info!("Client somehow sent close message without CloseFrame"); | ||||
|         } | ||||
|         ControlFlow::Break(()) | ||||
|       } | ||||
|       _ => { | ||||
|         warn!("WS server received unexpected message: {:?}", msg); | ||||
|         ControlFlow::Break(()) | ||||
|       } | ||||
|     } | ||||
|   } | ||||
| } | ||||
| @@ -1,158 +0,0 @@ | ||||
| use std::sync::Arc; | ||||
|  | ||||
| use axum::extract::ws::Message; | ||||
| use gpapi::{ | ||||
|   service::{event::WsEvent, request::WsRequest, vpn_state::VpnState}, | ||||
|   utils::{crypto::Crypto, lock_file::LockFile, redact::Redaction}, | ||||
| }; | ||||
| use log::{info, warn}; | ||||
| use tokio::{ | ||||
|   net::TcpListener, | ||||
|   sync::{mpsc, watch, RwLock}, | ||||
| }; | ||||
| use tokio_util::sync::CancellationToken; | ||||
|  | ||||
| use crate::{routes, ws_connection::WsConnection}; | ||||
|  | ||||
| pub(crate) struct WsServerContext { | ||||
|   crypto: Arc<Crypto>, | ||||
|   ws_req_tx: mpsc::Sender<WsRequest>, | ||||
|   vpn_state_rx: watch::Receiver<VpnState>, | ||||
|   redaction: Arc<Redaction>, | ||||
|   connections: RwLock<Vec<Arc<WsConnection>>>, | ||||
| } | ||||
|  | ||||
| impl WsServerContext { | ||||
|   pub fn new( | ||||
|     api_key: Vec<u8>, | ||||
|     ws_req_tx: mpsc::Sender<WsRequest>, | ||||
|     vpn_state_rx: watch::Receiver<VpnState>, | ||||
|     redaction: Arc<Redaction>, | ||||
|   ) -> Self { | ||||
|     Self { | ||||
|       crypto: Arc::new(Crypto::new(api_key)), | ||||
|       ws_req_tx, | ||||
|       vpn_state_rx, | ||||
|       redaction, | ||||
|       connections: Default::default(), | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub async fn send_event(&self, event: WsEvent) { | ||||
|     let connections = self.connections.read().await; | ||||
|  | ||||
|     for conn in connections.iter() { | ||||
|       let _ = conn.send_event(&event).await; | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub async fn add_connection(&self) -> (Arc<WsConnection>, mpsc::Receiver<Message>) { | ||||
|     let (tx, rx) = mpsc::channel::<Message>(32); | ||||
|     let conn = Arc::new(WsConnection::new(Arc::clone(&self.crypto), tx)); | ||||
|  | ||||
|     // Send current VPN state to new client | ||||
|     info!("Sending current VPN state to new client"); | ||||
|     let vpn_state = self.vpn_state_rx.borrow().clone(); | ||||
|     if let Err(err) = conn.send_event(&WsEvent::VpnState(vpn_state)).await { | ||||
|       warn!("Failed to send VPN state to new client: {}", err); | ||||
|     } | ||||
|  | ||||
|     self.connections.write().await.push(Arc::clone(&conn)); | ||||
|  | ||||
|     (conn, rx) | ||||
|   } | ||||
|  | ||||
|   pub async fn remove_connection(&self, conn: Arc<WsConnection>) { | ||||
|     let mut connections = self.connections.write().await; | ||||
|     connections.retain(|c| !Arc::ptr_eq(c, &conn)); | ||||
|   } | ||||
|  | ||||
|   fn vpn_state_rx(&self) -> watch::Receiver<VpnState> { | ||||
|     self.vpn_state_rx.clone() | ||||
|   } | ||||
|  | ||||
|   pub async fn forward_req(&self, req: WsRequest) -> anyhow::Result<()> { | ||||
|     if let WsRequest::Connect(ref req) = req { | ||||
|       self | ||||
|         .redaction | ||||
|         .add_values(&[req.gateway().server(), req.args().cookie()])? | ||||
|     } | ||||
|  | ||||
|     self.ws_req_tx.send(req).await?; | ||||
|  | ||||
|     Ok(()) | ||||
|   } | ||||
| } | ||||
|  | ||||
| pub(crate) struct WsServer { | ||||
|   ctx: Arc<WsServerContext>, | ||||
|   cancel_token: CancellationToken, | ||||
|   lock_file: Arc<LockFile>, | ||||
| } | ||||
|  | ||||
| impl WsServer { | ||||
|   pub fn new( | ||||
|     api_key: Vec<u8>, | ||||
|     ws_req_tx: mpsc::Sender<WsRequest>, | ||||
|     vpn_state_rx: watch::Receiver<VpnState>, | ||||
|     lock_file: Arc<LockFile>, | ||||
|     redaction: Arc<Redaction>, | ||||
|   ) -> Self { | ||||
|     let ctx = Arc::new(WsServerContext::new( | ||||
|       api_key, | ||||
|       ws_req_tx, | ||||
|       vpn_state_rx, | ||||
|       redaction, | ||||
|     )); | ||||
|     let cancel_token = CancellationToken::new(); | ||||
|  | ||||
|     Self { | ||||
|       ctx, | ||||
|       cancel_token, | ||||
|       lock_file, | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub fn cancel_token(&self) -> CancellationToken { | ||||
|     self.cancel_token.clone() | ||||
|   } | ||||
|  | ||||
|   pub async fn start(&self, shutdown_tx: mpsc::Sender<()>) { | ||||
|     if let Ok(listener) = TcpListener::bind("127.0.0.1:0").await { | ||||
|       let local_addr = listener.local_addr().unwrap(); | ||||
|  | ||||
|       self.lock_file.lock(local_addr.port().to_string()).unwrap(); | ||||
|  | ||||
|       info!("WS server listening on port: {}", local_addr.port()); | ||||
|  | ||||
|       tokio::select! { | ||||
|         _ = watch_vpn_state(self.ctx.vpn_state_rx(), Arc::clone(&self.ctx)) => { | ||||
|           info!("VPN state watch task completed"); | ||||
|         } | ||||
|         _ = start_server(listener, self.ctx.clone()) => { | ||||
|             info!("WS server stopped"); | ||||
|         } | ||||
|         _ = self.cancel_token.cancelled() => { | ||||
|           info!("WS server cancelled"); | ||||
|         } | ||||
|       } | ||||
|     } | ||||
|  | ||||
|     let _ = shutdown_tx.send(()).await; | ||||
|   } | ||||
| } | ||||
|  | ||||
| async fn watch_vpn_state(mut vpn_state_rx: watch::Receiver<VpnState>, ctx: Arc<WsServerContext>) { | ||||
|   while vpn_state_rx.changed().await.is_ok() { | ||||
|     let vpn_state = vpn_state_rx.borrow().clone(); | ||||
|     ctx.send_event(WsEvent::VpnState(vpn_state)).await; | ||||
|   } | ||||
| } | ||||
|  | ||||
| async fn start_server(listener: TcpListener, ctx: Arc<WsServerContext>) -> anyhow::Result<()> { | ||||
|   let routes = routes::routes(ctx); | ||||
|  | ||||
|   axum::serve(listener, routes).await?; | ||||
|  | ||||
|   Ok(()) | ||||
| } | ||||
							
								
								
									
										19
									
								
								com.yuezk.gp.policy
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										19
									
								
								com.yuezk.gp.policy
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,19 @@ | ||||
| <?xml version="1.0" encoding="UTF-8"?> | ||||
| <!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN" "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd"> | ||||
| <policyconfig> | ||||
|   <vendor>The GlobalProtect-openconnect Project</vendor> | ||||
|   <vendor_url>https://github.com/yuezk/GlobalProtect-openconnect</vendor_url> | ||||
|   <icon_name>gpgui</icon_name> | ||||
|   <action id="com.yuezk.gp.update-gpconf"> | ||||
|     <description>Update the /etc/gpservice/gp.conf</description> | ||||
|     <message>Authentication is required to update the GlobalProtect service configuration</message> | ||||
|     <defaults> | ||||
|       <allow_any>auth_admin</allow_any> | ||||
|       <allow_inactive>auth_admin</allow_inactive> | ||||
|       <allow_active>auth_admin</allow_active> | ||||
|     </defaults> | ||||
|     <annotate key="org.freedesktop.policykit.exec.path">/usr/bin/tee</annotate> | ||||
|     <annotate key="org.freedesktop.policykit.exec.argv1">/etc/gpservice/gp.conf</annotate> | ||||
|     <annotate key="org.freedesktop.policykit.exec.allow_gui">true</annotate> | ||||
|   </action> | ||||
| </policyconfig> | ||||
| @@ -1,34 +0,0 @@ | ||||
| [package] | ||||
| name = "gpapi" | ||||
| version.workspace = true | ||||
| edition.workspace = true | ||||
| license = "MIT" | ||||
|  | ||||
| [dependencies] | ||||
| anyhow.workspace = true | ||||
| base64.workspace = true | ||||
| log.workspace = true | ||||
| reqwest.workspace = true | ||||
| roxmltree.workspace = true | ||||
| serde.workspace = true | ||||
| specta.workspace = true | ||||
| specta-macros.workspace = true | ||||
| urlencoding.workspace = true | ||||
| tokio.workspace = true | ||||
| serde_json.workspace = true | ||||
| whoami.workspace = true | ||||
| tempfile.workspace = true | ||||
| thiserror.workspace = true | ||||
| chacha20poly1305 = { version = "0.10", features = ["std"] } | ||||
| redact-engine.workspace = true | ||||
| url.workspace = true | ||||
| regex.workspace = true | ||||
| dotenvy_macro.workspace = true | ||||
| uzers.workspace = true | ||||
|  | ||||
| tauri = { workspace = true, optional = true } | ||||
| clap = { workspace = true, optional = true } | ||||
|  | ||||
| [features] | ||||
| tauri = ["dep:tauri"] | ||||
| clap = ["dep:clap"] | ||||
| @@ -1,63 +0,0 @@ | ||||
| use serde::{Deserialize, Serialize}; | ||||
|  | ||||
| #[derive(Debug, Serialize, Deserialize)] | ||||
| #[serde(rename_all = "camelCase")] | ||||
| pub struct SamlAuthData { | ||||
|   username: String, | ||||
|   prelogin_cookie: Option<String>, | ||||
|   portal_userauthcookie: Option<String>, | ||||
| } | ||||
|  | ||||
| #[derive(Debug, Serialize, Deserialize)] | ||||
| #[serde(rename_all = "camelCase")] | ||||
| pub enum SamlAuthResult { | ||||
|   Success(SamlAuthData), | ||||
|   Failure(String), | ||||
| } | ||||
|  | ||||
| impl SamlAuthResult { | ||||
|   pub fn is_success(&self) -> bool { | ||||
|     match self { | ||||
|       SamlAuthResult::Success(_) => true, | ||||
|       SamlAuthResult::Failure(_) => false, | ||||
|     } | ||||
|   } | ||||
| } | ||||
|  | ||||
| impl SamlAuthData { | ||||
|   pub fn new( | ||||
|     username: String, | ||||
|     prelogin_cookie: Option<String>, | ||||
|     portal_userauthcookie: Option<String>, | ||||
|   ) -> Self { | ||||
|     Self { | ||||
|       username, | ||||
|       prelogin_cookie, | ||||
|       portal_userauthcookie, | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub fn username(&self) -> &str { | ||||
|     &self.username | ||||
|   } | ||||
|  | ||||
|   pub fn prelogin_cookie(&self) -> Option<&str> { | ||||
|     self.prelogin_cookie.as_deref() | ||||
|   } | ||||
|  | ||||
|   pub fn check( | ||||
|     username: &Option<String>, | ||||
|     prelogin_cookie: &Option<String>, | ||||
|     portal_userauthcookie: &Option<String>, | ||||
|   ) -> bool { | ||||
|     let username_valid = username | ||||
|       .as_ref() | ||||
|       .is_some_and(|username| !username.is_empty()); | ||||
|     let prelogin_cookie_valid = prelogin_cookie.as_ref().is_some_and(|val| val.len() > 5); | ||||
|     let portal_userauthcookie_valid = portal_userauthcookie | ||||
|       .as_ref() | ||||
|       .is_some_and(|val| val.len() > 5); | ||||
|  | ||||
|     username_valid && (prelogin_cookie_valid || portal_userauthcookie_valid) | ||||
|   } | ||||
| } | ||||
| @@ -1,64 +0,0 @@ | ||||
| use clap::{builder::PossibleValue, ValueEnum}; | ||||
|  | ||||
| use crate::gp_params::ClientOs; | ||||
|  | ||||
| #[derive(Debug, Clone)] | ||||
| pub enum Os { | ||||
|   Linux, | ||||
|   Windows, | ||||
|   Mac, | ||||
| } | ||||
|  | ||||
| impl Os { | ||||
|   pub fn as_str(&self) -> &'static str { | ||||
|     match self { | ||||
|       Os::Linux => "Linux", | ||||
|       Os::Windows => "Windows", | ||||
|       Os::Mac => "Mac", | ||||
|     } | ||||
|   } | ||||
| } | ||||
|  | ||||
| impl From<&str> for Os { | ||||
|   fn from(os: &str) -> Self { | ||||
|     match os.to_lowercase().as_str() { | ||||
|       "linux" => Os::Linux, | ||||
|       "windows" => Os::Windows, | ||||
|       "mac" => Os::Mac, | ||||
|       _ => Os::Linux, | ||||
|     } | ||||
|   } | ||||
| } | ||||
|  | ||||
| impl From<&Os> for ClientOs { | ||||
|   fn from(value: &Os) -> Self { | ||||
|     match value { | ||||
|       Os::Linux => ClientOs::Linux, | ||||
|       Os::Windows => ClientOs::Windows, | ||||
|       Os::Mac => ClientOs::Mac, | ||||
|     } | ||||
|   } | ||||
| } | ||||
|  | ||||
| impl ValueEnum for Os { | ||||
|   fn value_variants<'a>() -> &'a [Self] { | ||||
|     &[Os::Linux, Os::Windows, Os::Mac] | ||||
|   } | ||||
|  | ||||
|   fn to_possible_value(&self) -> Option<clap::builder::PossibleValue> { | ||||
|     match self { | ||||
|       Os::Linux => Some(PossibleValue::new("Linux")), | ||||
|       Os::Windows => Some(PossibleValue::new("Windows")), | ||||
|       Os::Mac => Some(PossibleValue::new("Mac")), | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   fn from_str(input: &str, _: bool) -> Result<Self, String> { | ||||
|     match input.to_lowercase().as_str() { | ||||
|       "linux" => Ok(Os::Linux), | ||||
|       "windows" => Ok(Os::Windows), | ||||
|       "mac" => Ok(Os::Mac), | ||||
|       _ => Err(format!("Invalid OS: {}", input)), | ||||
|     } | ||||
|   } | ||||
| } | ||||
| @@ -1 +0,0 @@ | ||||
| pub mod args; | ||||
| @@ -1,226 +0,0 @@ | ||||
| use std::collections::HashMap; | ||||
|  | ||||
| use serde::{Deserialize, Serialize}; | ||||
| use specta::Type; | ||||
|  | ||||
| use crate::auth::SamlAuthData; | ||||
|  | ||||
| #[derive(Debug, Serialize, Deserialize, Type, Clone)] | ||||
| #[serde(rename_all = "camelCase")] | ||||
| pub struct PasswordCredential { | ||||
|   username: String, | ||||
|   password: String, | ||||
| } | ||||
|  | ||||
| impl PasswordCredential { | ||||
|   pub fn new(username: &str, password: &str) -> Self { | ||||
|     Self { | ||||
|       username: username.to_string(), | ||||
|       password: password.to_string(), | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub fn username(&self) -> &str { | ||||
|     &self.username | ||||
|   } | ||||
|  | ||||
|   pub fn password(&self) -> &str { | ||||
|     &self.password | ||||
|   } | ||||
| } | ||||
|  | ||||
| impl From<&CachedCredential> for PasswordCredential { | ||||
|   fn from(value: &CachedCredential) -> Self { | ||||
|     Self::new(value.username(), value.password().unwrap_or_default()) | ||||
|   } | ||||
| } | ||||
|  | ||||
| #[derive(Debug, Serialize, Deserialize, Type, Clone)] | ||||
| #[serde(rename_all = "camelCase")] | ||||
| pub struct PreloginCookieCredential { | ||||
|   username: String, | ||||
|   prelogin_cookie: String, | ||||
| } | ||||
|  | ||||
| impl PreloginCookieCredential { | ||||
|   pub fn new(username: &str, prelogin_cookie: &str) -> Self { | ||||
|     Self { | ||||
|       username: username.to_string(), | ||||
|       prelogin_cookie: prelogin_cookie.to_string(), | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub fn username(&self) -> &str { | ||||
|     &self.username | ||||
|   } | ||||
|  | ||||
|   pub fn prelogin_cookie(&self) -> &str { | ||||
|     &self.prelogin_cookie | ||||
|   } | ||||
| } | ||||
|  | ||||
| impl TryFrom<SamlAuthData> for PreloginCookieCredential { | ||||
|   type Error = anyhow::Error; | ||||
|  | ||||
|   fn try_from(value: SamlAuthData) -> Result<Self, Self::Error> { | ||||
|     let username = value.username().to_string(); | ||||
|     let prelogin_cookie = value | ||||
|       .prelogin_cookie() | ||||
|       .ok_or_else(|| anyhow::anyhow!("Missing prelogin cookie"))? | ||||
|       .to_string(); | ||||
|  | ||||
|     Ok(Self::new(&username, &prelogin_cookie)) | ||||
|   } | ||||
| } | ||||
|  | ||||
| #[derive(Debug, Serialize, Deserialize, Type, Clone)] | ||||
| #[serde(rename_all = "camelCase")] | ||||
| pub struct AuthCookieCredential { | ||||
|   username: String, | ||||
|   user_auth_cookie: String, | ||||
|   prelogon_user_auth_cookie: String, | ||||
| } | ||||
|  | ||||
| impl AuthCookieCredential { | ||||
|   pub fn new(username: &str, user_auth_cookie: &str, prelogon_user_auth_cookie: &str) -> Self { | ||||
|     Self { | ||||
|       username: username.to_string(), | ||||
|       user_auth_cookie: user_auth_cookie.to_string(), | ||||
|       prelogon_user_auth_cookie: prelogon_user_auth_cookie.to_string(), | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub fn username(&self) -> &str { | ||||
|     &self.username | ||||
|   } | ||||
|  | ||||
|   pub fn user_auth_cookie(&self) -> &str { | ||||
|     &self.user_auth_cookie | ||||
|   } | ||||
|  | ||||
|   pub fn prelogon_user_auth_cookie(&self) -> &str { | ||||
|     &self.prelogon_user_auth_cookie | ||||
|   } | ||||
| } | ||||
|  | ||||
| #[derive(Debug, Serialize, Deserialize, Type, Clone)] | ||||
| #[serde(rename_all = "camelCase")] | ||||
| pub struct CachedCredential { | ||||
|   username: String, | ||||
|   password: Option<String>, | ||||
|   auth_cookie: AuthCookieCredential, | ||||
| } | ||||
|  | ||||
| impl CachedCredential { | ||||
|   pub fn new( | ||||
|     username: String, | ||||
|     password: Option<String>, | ||||
|     auth_cookie: AuthCookieCredential, | ||||
|   ) -> Self { | ||||
|     Self { | ||||
|       username, | ||||
|       password, | ||||
|       auth_cookie, | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub fn username(&self) -> &str { | ||||
|     &self.username | ||||
|   } | ||||
|  | ||||
|   pub fn password(&self) -> Option<&str> { | ||||
|     self.password.as_deref() | ||||
|   } | ||||
|  | ||||
|   pub fn auth_cookie(&self) -> &AuthCookieCredential { | ||||
|     &self.auth_cookie | ||||
|   } | ||||
|  | ||||
|   pub fn set_auth_cookie(&mut self, auth_cookie: AuthCookieCredential) { | ||||
|     self.auth_cookie = auth_cookie; | ||||
|   } | ||||
| } | ||||
|  | ||||
| #[derive(Debug, Serialize, Deserialize, Type, Clone)] | ||||
| #[serde(tag = "type", rename_all = "camelCase")] | ||||
| pub enum Credential { | ||||
|   Password(PasswordCredential), | ||||
|   PreloginCookie(PreloginCookieCredential), | ||||
|   AuthCookie(AuthCookieCredential), | ||||
|   CachedCredential(CachedCredential), | ||||
| } | ||||
|  | ||||
| impl Credential { | ||||
|   pub fn username(&self) -> &str { | ||||
|     match self { | ||||
|       Credential::Password(cred) => cred.username(), | ||||
|       Credential::PreloginCookie(cred) => cred.username(), | ||||
|       Credential::AuthCookie(cred) => cred.username(), | ||||
|       Credential::CachedCredential(cred) => cred.username(), | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub fn to_params(&self) -> HashMap<&str, &str> { | ||||
|     let mut params = HashMap::new(); | ||||
|     params.insert("user", self.username()); | ||||
|  | ||||
|     let (passwd, prelogin_cookie, portal_userauthcookie, portal_prelogonuserauthcookie) = match self | ||||
|     { | ||||
|       Credential::Password(cred) => (Some(cred.password()), None, None, None), | ||||
|       Credential::PreloginCookie(cred) => (None, Some(cred.prelogin_cookie()), None, None), | ||||
|       Credential::AuthCookie(cred) => ( | ||||
|         None, | ||||
|         None, | ||||
|         Some(cred.user_auth_cookie()), | ||||
|         Some(cred.prelogon_user_auth_cookie()), | ||||
|       ), | ||||
|       Credential::CachedCredential(cred) => ( | ||||
|         cred.password(), | ||||
|         None, | ||||
|         Some(cred.auth_cookie.user_auth_cookie()), | ||||
|         Some(cred.auth_cookie.prelogon_user_auth_cookie()), | ||||
|       ), | ||||
|     }; | ||||
|  | ||||
|     params.insert("passwd", passwd.unwrap_or_default()); | ||||
|     params.insert("prelogin-cookie", prelogin_cookie.unwrap_or_default()); | ||||
|     params.insert( | ||||
|       "portal-userauthcookie", | ||||
|       portal_userauthcookie.unwrap_or_default(), | ||||
|     ); | ||||
|     params.insert( | ||||
|       "portal-prelogonuserauthcookie", | ||||
|       portal_prelogonuserauthcookie.unwrap_or_default(), | ||||
|     ); | ||||
|  | ||||
|     params | ||||
|   } | ||||
| } | ||||
|  | ||||
| impl TryFrom<SamlAuthData> for Credential { | ||||
|   type Error = anyhow::Error; | ||||
|  | ||||
|   fn try_from(value: SamlAuthData) -> Result<Self, Self::Error> { | ||||
|     let prelogin_cookie = PreloginCookieCredential::try_from(value)?; | ||||
|  | ||||
|     Ok(Self::PreloginCookie(prelogin_cookie)) | ||||
|   } | ||||
| } | ||||
|  | ||||
| impl From<PasswordCredential> for Credential { | ||||
|   fn from(value: PasswordCredential) -> Self { | ||||
|     Self::Password(value) | ||||
|   } | ||||
| } | ||||
|  | ||||
| impl From<&AuthCookieCredential> for Credential { | ||||
|   fn from(value: &AuthCookieCredential) -> Self { | ||||
|     Self::AuthCookie(value.clone()) | ||||
|   } | ||||
| } | ||||
|  | ||||
| impl From<&CachedCredential> for Credential { | ||||
|   fn from(value: &CachedCredential) -> Self { | ||||
|     Self::CachedCredential(value.clone()) | ||||
|   } | ||||
| } | ||||
| @@ -1,68 +0,0 @@ | ||||
| use log::info; | ||||
| use reqwest::Client; | ||||
| use roxmltree::Document; | ||||
| use urlencoding::encode; | ||||
|  | ||||
| use crate::{credential::Credential, gp_params::GpParams}; | ||||
|  | ||||
| pub async fn gateway_login( | ||||
|   gateway: &str, | ||||
|   cred: &Credential, | ||||
|   gp_params: &GpParams, | ||||
| ) -> anyhow::Result<String> { | ||||
|   let login_url = format!("https://{}/ssl-vpn/login.esp", gateway); | ||||
|   let client = Client::builder() | ||||
|     .user_agent(gp_params.user_agent()) | ||||
|     .build()?; | ||||
|  | ||||
|   let mut params = cred.to_params(); | ||||
|   let extra_params = gp_params.to_params(); | ||||
|  | ||||
|   params.extend(extra_params); | ||||
|   params.insert("server", gateway); | ||||
|  | ||||
|   info!("Gateway login, user_agent: {}", gp_params.user_agent()); | ||||
|  | ||||
|   let res = client.post(&login_url).form(¶ms).send().await?; | ||||
|   let res_xml = res.error_for_status()?.text().await?; | ||||
|  | ||||
|   let doc = Document::parse(&res_xml)?; | ||||
|  | ||||
|   build_gateway_token(&doc, gp_params.computer()) | ||||
| } | ||||
|  | ||||
| fn build_gateway_token(doc: &Document, computer: &str) -> anyhow::Result<String> { | ||||
|   let args = doc | ||||
|     .descendants() | ||||
|     .filter(|n| n.has_tag_name("argument")) | ||||
|     .map(|n| n.text().unwrap_or("").to_string()) | ||||
|     .collect::<Vec<_>>(); | ||||
|  | ||||
|   let params = [ | ||||
|     read_args(&args, 1, "authcookie")?, | ||||
|     read_args(&args, 3, "portal")?, | ||||
|     read_args(&args, 4, "user")?, | ||||
|     read_args(&args, 7, "domain")?, | ||||
|     read_args(&args, 15, "preferred-ip")?, | ||||
|     ("computer", computer), | ||||
|   ]; | ||||
|  | ||||
|   let token = params | ||||
|     .iter() | ||||
|     .map(|(k, v)| format!("{}={}", k, encode(v))) | ||||
|     .collect::<Vec<_>>() | ||||
|     .join("&"); | ||||
|  | ||||
|   Ok(token) | ||||
| } | ||||
|  | ||||
| fn read_args<'a>( | ||||
|   args: &'a [String], | ||||
|   index: usize, | ||||
|   key: &'a str, | ||||
| ) -> anyhow::Result<(&'a str, &'a str)> { | ||||
|   args | ||||
|     .get(index) | ||||
|     .ok_or_else(|| anyhow::anyhow!("Failed to read {key} from args")) | ||||
|     .map(|s| (key, s.as_ref())) | ||||
| } | ||||
| @@ -1,41 +0,0 @@ | ||||
| mod login; | ||||
| mod parse_gateways; | ||||
|  | ||||
| pub use login::*; | ||||
| pub(crate) use parse_gateways::*; | ||||
|  | ||||
| use serde::{Deserialize, Serialize}; | ||||
| use specta::Type; | ||||
|  | ||||
| use std::fmt::Display; | ||||
|  | ||||
| #[derive(Debug, Serialize, Deserialize, Type, Clone)] | ||||
| pub(crate) struct PriorityRule { | ||||
|   pub(crate) name: String, | ||||
|   pub(crate) priority: u32, | ||||
| } | ||||
|  | ||||
| #[derive(Debug, Serialize, Deserialize, Type, Clone)] | ||||
| #[serde(rename_all = "camelCase")] | ||||
| pub struct Gateway { | ||||
|   pub(crate) name: String, | ||||
|   pub(crate) address: String, | ||||
|   pub(crate) priority: u32, | ||||
|   pub(crate) priority_rules: Vec<PriorityRule>, | ||||
| } | ||||
|  | ||||
| impl Display for Gateway { | ||||
|   fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||||
|     write!(f, "{} ({})", self.name, self.address) | ||||
|   } | ||||
| } | ||||
|  | ||||
| impl Gateway { | ||||
|   pub fn name(&self) -> &str { | ||||
|     &self.name | ||||
|   } | ||||
|  | ||||
|   pub fn server(&self) -> &str { | ||||
|     &self.address | ||||
|   } | ||||
| } | ||||
| @@ -1,63 +0,0 @@ | ||||
| use roxmltree::Document; | ||||
|  | ||||
| use super::{Gateway, PriorityRule}; | ||||
|  | ||||
| pub(crate) fn parse_gateways(doc: &Document) -> Option<Vec<Gateway>> { | ||||
|   let node_gateways = doc.descendants().find(|n| n.has_tag_name("gateways"))?; | ||||
|   let list_gateway = node_gateways | ||||
|     .descendants() | ||||
|     .find(|n| n.has_tag_name("list"))?; | ||||
|  | ||||
|   let gateways = list_gateway | ||||
|     .children() | ||||
|     .filter_map(|gateway_item| { | ||||
|       if !gateway_item.has_tag_name("entry") { | ||||
|         return None; | ||||
|       } | ||||
|       let address = gateway_item.attribute("name").unwrap_or("").to_string(); | ||||
|       let name = gateway_item | ||||
|         .children() | ||||
|         .find(|n| n.has_tag_name("description")) | ||||
|         .and_then(|n| n.text()) | ||||
|         .unwrap_or("") | ||||
|         .to_string(); | ||||
|       let priority = gateway_item | ||||
|         .children() | ||||
|         .find(|n| n.has_tag_name("priority")) | ||||
|         .and_then(|n| n.text()) | ||||
|         .and_then(|s| s.parse().ok()) | ||||
|         .unwrap_or(u32::MAX); | ||||
|       let priority_rules = gateway_item | ||||
|         .children() | ||||
|         .find(|n| n.has_tag_name("priority-rule")) | ||||
|         .map(|n| { | ||||
|           n.children() | ||||
|             .filter_map(|n| { | ||||
|               if !n.has_tag_name("entry") { | ||||
|                 return None; | ||||
|               } | ||||
|               let name = n.attribute("name").unwrap_or("").to_string(); | ||||
|               let priority: u32 = n | ||||
|                 .children() | ||||
|                 .find(|n| n.has_tag_name("priority")) | ||||
|                 .and_then(|n| n.text()) | ||||
|                 .and_then(|s| s.parse().ok()) | ||||
|                 .unwrap_or(u32::MAX); | ||||
|  | ||||
|               Some(PriorityRule { name, priority }) | ||||
|             }) | ||||
|             .collect() | ||||
|         }) | ||||
|         .unwrap_or_default(); | ||||
|  | ||||
|       Some(Gateway { | ||||
|         name, | ||||
|         address, | ||||
|         priority, | ||||
|         priority_rules, | ||||
|       }) | ||||
|     }) | ||||
|     .collect(); | ||||
|  | ||||
|   Some(gateways) | ||||
| } | ||||
| @@ -1,166 +0,0 @@ | ||||
| use std::collections::HashMap; | ||||
|  | ||||
| use serde::{Deserialize, Serialize}; | ||||
| use specta::Type; | ||||
|  | ||||
| use crate::GP_USER_AGENT; | ||||
|  | ||||
| #[derive(Debug, Serialize, Deserialize, Clone, Type, Default)] | ||||
| pub enum ClientOs { | ||||
|   #[default] | ||||
|   Linux, | ||||
|   Windows, | ||||
|   Mac, | ||||
| } | ||||
|  | ||||
| impl From<&str> for ClientOs { | ||||
|   fn from(os: &str) -> Self { | ||||
|     match os { | ||||
|       "Linux" => ClientOs::Linux, | ||||
|       "Windows" => ClientOs::Windows, | ||||
|       "Mac" => ClientOs::Mac, | ||||
|       _ => ClientOs::Linux, | ||||
|     } | ||||
|   } | ||||
| } | ||||
|  | ||||
| impl ClientOs { | ||||
|   pub fn as_str(&self) -> &str { | ||||
|     match self { | ||||
|       ClientOs::Linux => "Linux", | ||||
|       ClientOs::Windows => "Windows", | ||||
|       ClientOs::Mac => "Mac", | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub fn to_openconnect_os(&self) -> &str { | ||||
|     match self { | ||||
|       ClientOs::Linux => "linux", | ||||
|       ClientOs::Windows => "win", | ||||
|       ClientOs::Mac => "mac-intel", | ||||
|     } | ||||
|   } | ||||
| } | ||||
|  | ||||
| #[derive(Debug, Serialize, Deserialize, Type, Default)] | ||||
| pub struct GpParams { | ||||
|   user_agent: String, | ||||
|   client_os: ClientOs, | ||||
|   os_version: Option<String>, | ||||
|   client_version: Option<String>, | ||||
|   computer: String, | ||||
|   ignore_tls_errors: bool, | ||||
| } | ||||
|  | ||||
| impl GpParams { | ||||
|   pub fn builder() -> GpParamsBuilder { | ||||
|     GpParamsBuilder::new() | ||||
|   } | ||||
|  | ||||
|   pub(crate) fn user_agent(&self) -> &str { | ||||
|     &self.user_agent | ||||
|   } | ||||
|  | ||||
|   pub(crate) fn computer(&self) -> &str { | ||||
|     &self.computer | ||||
|   } | ||||
|  | ||||
|   pub fn ignore_tls_errors(&self) -> bool { | ||||
|     self.ignore_tls_errors | ||||
|   } | ||||
|  | ||||
|   pub(crate) fn to_params(&self) -> HashMap<&str, &str> { | ||||
|     let mut params: HashMap<&str, &str> = HashMap::new(); | ||||
|     let client_os = self.client_os.as_str(); | ||||
|  | ||||
|     // Common params | ||||
|     params.insert("prot", "https:"); | ||||
|     params.insert("jnlpReady", "jnlpReady"); | ||||
|     params.insert("ok", "Login"); | ||||
|     params.insert("direct", "yes"); | ||||
|     params.insert("ipv6-support", "yes"); | ||||
|     params.insert("inputStr", ""); | ||||
|     params.insert("clientVer", "4100"); | ||||
|     params.insert("clientos", client_os); | ||||
|     params.insert("computer", &self.computer); | ||||
|  | ||||
|     if let Some(os_version) = &self.os_version { | ||||
|       params.insert("os-version", os_version); | ||||
|     } | ||||
|  | ||||
|     if let Some(client_version) = &self.client_version { | ||||
|       params.insert("clientgpversion", client_version); | ||||
|     } | ||||
|  | ||||
|     params | ||||
|   } | ||||
| } | ||||
|  | ||||
| pub struct GpParamsBuilder { | ||||
|   user_agent: String, | ||||
|   client_os: ClientOs, | ||||
|   os_version: Option<String>, | ||||
|   client_version: Option<String>, | ||||
|   computer: String, | ||||
|   ignore_tls_errors: bool, | ||||
| } | ||||
|  | ||||
| impl GpParamsBuilder { | ||||
|   pub fn new() -> Self { | ||||
|     Self { | ||||
|       user_agent: GP_USER_AGENT.to_string(), | ||||
|       client_os: ClientOs::Linux, | ||||
|       os_version: Default::default(), | ||||
|       client_version: Default::default(), | ||||
|       computer: whoami::hostname(), | ||||
|       ignore_tls_errors: false, | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub fn user_agent(&mut self, user_agent: &str) -> &mut Self { | ||||
|     self.user_agent = user_agent.to_string(); | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn client_os(&mut self, client_os: ClientOs) -> &mut Self { | ||||
|     self.client_os = client_os; | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn os_version<T: Into<Option<String>>>(&mut self, os_version: T) -> &mut Self { | ||||
|     self.os_version = os_version.into(); | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn client_version<T: Into<Option<String>>>(&mut self, client_version: T) -> &mut Self { | ||||
|     self.client_version = client_version.into(); | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn computer(&mut self, computer: &str) -> &mut Self { | ||||
|     self.computer = computer.to_string(); | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn ignore_tls_errors(&mut self, ignore_tls_errors: bool) -> &mut Self { | ||||
|     self.ignore_tls_errors = ignore_tls_errors; | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn build(&self) -> GpParams { | ||||
|     GpParams { | ||||
|       user_agent: self.user_agent.clone(), | ||||
|       client_os: self.client_os.clone(), | ||||
|       os_version: self.os_version.clone(), | ||||
|       client_version: self.client_version.clone(), | ||||
|       computer: self.computer.clone(), | ||||
|       ignore_tls_errors: self.ignore_tls_errors, | ||||
|     } | ||||
|   } | ||||
| } | ||||
|  | ||||
| impl Default for GpParamsBuilder { | ||||
|   fn default() -> Self { | ||||
|     Self::new() | ||||
|   } | ||||
| } | ||||
| @@ -1,35 +0,0 @@ | ||||
| pub mod auth; | ||||
| pub mod credential; | ||||
| pub mod gateway; | ||||
| pub mod gp_params; | ||||
| pub mod portal; | ||||
| pub mod process; | ||||
| pub mod service; | ||||
| pub mod utils; | ||||
|  | ||||
| #[cfg(feature = "clap")] | ||||
| pub mod clap; | ||||
|  | ||||
| #[cfg(debug_assertions)] | ||||
| pub const GP_API_KEY: &[u8; 32] = &[0; 32]; | ||||
|  | ||||
| pub const GP_USER_AGENT: &str = "PAN GlobalProtect"; | ||||
| pub const GP_SERVICE_LOCK_FILE: &str = "/var/run/gpservice.lock"; | ||||
|  | ||||
| #[cfg(not(debug_assertions))] | ||||
| pub const GP_CLIENT_BINARY: &str = "/usr/bin/gpclient"; | ||||
| #[cfg(not(debug_assertions))] | ||||
| pub const GP_SERVICE_BINARY: &str = "/usr/bin/gpservice"; | ||||
| #[cfg(not(debug_assertions))] | ||||
| pub const GP_GUI_BINARY: &str = "/usr/bin/gpgui"; | ||||
| #[cfg(not(debug_assertions))] | ||||
| pub(crate) const GP_AUTH_BINARY: &str = "/usr/bin/gpauth"; | ||||
|  | ||||
| #[cfg(debug_assertions)] | ||||
| pub const GP_CLIENT_BINARY: &str = dotenvy_macro::dotenv!("GP_CLIENT_BINARY"); | ||||
| #[cfg(debug_assertions)] | ||||
| pub const GP_SERVICE_BINARY: &str = dotenvy_macro::dotenv!("GP_SERVICE_BINARY"); | ||||
| #[cfg(debug_assertions)] | ||||
| pub const GP_GUI_BINARY: &str = dotenvy_macro::dotenv!("GP_GUI_BINARY"); | ||||
| #[cfg(debug_assertions)] | ||||
| pub(crate) const GP_AUTH_BINARY: &str = dotenvy_macro::dotenv!("GP_AUTH_BINARY"); | ||||
| @@ -1,174 +0,0 @@ | ||||
| use anyhow::ensure; | ||||
| use log::info; | ||||
| use reqwest::Client; | ||||
| use roxmltree::Document; | ||||
| use serde::Serialize; | ||||
| use specta::Type; | ||||
| use thiserror::Error; | ||||
|  | ||||
| use crate::{ | ||||
|   credential::{AuthCookieCredential, Credential}, | ||||
|   gateway::{parse_gateways, Gateway}, | ||||
|   gp_params::GpParams, | ||||
|   utils::{normalize_server, xml}, | ||||
| }; | ||||
|  | ||||
| #[derive(Debug, Serialize, Type)] | ||||
| #[serde(rename_all = "camelCase")] | ||||
| pub struct PortalConfig { | ||||
|   portal: String, | ||||
|   auth_cookie: AuthCookieCredential, | ||||
|   gateways: Vec<Gateway>, | ||||
|   config_digest: Option<String>, | ||||
| } | ||||
|  | ||||
| impl PortalConfig { | ||||
|   pub fn new( | ||||
|     portal: String, | ||||
|     auth_cookie: AuthCookieCredential, | ||||
|     gateways: Vec<Gateway>, | ||||
|     config_digest: Option<String>, | ||||
|   ) -> Self { | ||||
|     Self { | ||||
|       portal, | ||||
|       auth_cookie, | ||||
|       gateways, | ||||
|       config_digest, | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub fn portal(&self) -> &str { | ||||
|     &self.portal | ||||
|   } | ||||
|  | ||||
|   pub fn gateways(&self) -> Vec<&Gateway> { | ||||
|     self.gateways.iter().collect() | ||||
|   } | ||||
|  | ||||
|   pub fn auth_cookie(&self) -> &AuthCookieCredential { | ||||
|     &self.auth_cookie | ||||
|   } | ||||
|  | ||||
|   /// In-place sort the gateways by region | ||||
|   pub fn sort_gateways(&mut self, region: &str) { | ||||
|     let preferred_gateway = self.find_preferred_gateway(region); | ||||
|     let preferred_gateway_index = self | ||||
|       .gateways() | ||||
|       .iter() | ||||
|       .position(|gateway| gateway.name == preferred_gateway.name) | ||||
|       .unwrap(); | ||||
|  | ||||
|     // Move the preferred gateway to the front of the list | ||||
|     self.gateways.swap(0, preferred_gateway_index); | ||||
|   } | ||||
|  | ||||
|   /// Find a gateway by name or address | ||||
|   pub fn find_gateway(&self, name_or_address: &str) -> Option<&Gateway> { | ||||
|     self | ||||
|       .gateways | ||||
|       .iter() | ||||
|       .find(|gateway| gateway.name == name_or_address || gateway.address == name_or_address) | ||||
|   } | ||||
|  | ||||
|   /// Find the preferred gateway for the given region | ||||
|   /// Iterates over the gateways and find the first one that | ||||
|   /// has the lowest priority for the given region. | ||||
|   /// If no gateway is found, returns the gateway with the lowest priority. | ||||
|   pub fn find_preferred_gateway(&self, region: &str) -> &Gateway { | ||||
|     let mut preferred_gateway: Option<&Gateway> = None; | ||||
|     let mut lowest_region_priority = u32::MAX; | ||||
|  | ||||
|     for gateway in &self.gateways { | ||||
|       for rule in &gateway.priority_rules { | ||||
|         if (rule.name == region || rule.name == "Any") && rule.priority < lowest_region_priority { | ||||
|           preferred_gateway = Some(gateway); | ||||
|           lowest_region_priority = rule.priority; | ||||
|         } | ||||
|       } | ||||
|     } | ||||
|  | ||||
|     // If no gateway is found, return the gateway with the lowest priority | ||||
|     preferred_gateway.unwrap_or_else(|| { | ||||
|       self | ||||
|         .gateways | ||||
|         .iter() | ||||
|         .min_by_key(|gateway| gateway.priority) | ||||
|         .unwrap() | ||||
|     }) | ||||
|   } | ||||
| } | ||||
|  | ||||
| #[derive(Error, Debug)] | ||||
| pub enum PortalConfigError { | ||||
|   #[error("Empty response, retrying can help")] | ||||
|   EmptyResponse, | ||||
|   #[error("Empty auth cookie, retrying can help")] | ||||
|   EmptyAuthCookie, | ||||
|   #[error("Invalid auth cookie, retrying can help")] | ||||
|   InvalidAuthCookie, | ||||
|   #[error("Empty gateways, retrying can help")] | ||||
|   EmptyGateways, | ||||
| } | ||||
|  | ||||
| pub async fn retrieve_config( | ||||
|   portal: &str, | ||||
|   cred: &Credential, | ||||
|   gp_params: &GpParams, | ||||
| ) -> anyhow::Result<PortalConfig> { | ||||
|   let portal = normalize_server(portal)?; | ||||
|   let server = remove_url_scheme(&portal); | ||||
|  | ||||
|   let url = format!("{}/global-protect/getconfig.esp", portal); | ||||
|   let client = Client::builder() | ||||
|     .user_agent(gp_params.user_agent()) | ||||
|     .build()?; | ||||
|  | ||||
|   let mut params = cred.to_params(); | ||||
|   let extra_params = gp_params.to_params(); | ||||
|  | ||||
|   params.extend(extra_params); | ||||
|   params.insert("server", &server); | ||||
|   params.insert("host", &server); | ||||
|  | ||||
|   info!("Portal config, user_agent: {}", gp_params.user_agent()); | ||||
|  | ||||
|   let res = client.post(&url).form(¶ms).send().await?; | ||||
|   let res_xml = res.error_for_status()?.text().await?; | ||||
|  | ||||
|   ensure!(!res_xml.is_empty(), PortalConfigError::EmptyResponse); | ||||
|  | ||||
|   let doc = Document::parse(&res_xml)?; | ||||
|   let gateways = parse_gateways(&doc).ok_or_else(|| anyhow::anyhow!("Failed to parse gateways"))?; | ||||
|  | ||||
|   let user_auth_cookie = xml::get_child_text(&doc, "portal-userauthcookie").unwrap_or_default(); | ||||
|   let prelogon_user_auth_cookie = | ||||
|     xml::get_child_text(&doc, "portal-prelogonuserauthcookie").unwrap_or_default(); | ||||
|   let config_digest = xml::get_child_text(&doc, "config-digest"); | ||||
|  | ||||
|   ensure!( | ||||
|     !user_auth_cookie.is_empty() && !prelogon_user_auth_cookie.is_empty(), | ||||
|     PortalConfigError::EmptyAuthCookie | ||||
|   ); | ||||
|  | ||||
|   ensure!( | ||||
|     user_auth_cookie != "empty" && prelogon_user_auth_cookie != "empty", | ||||
|     PortalConfigError::InvalidAuthCookie | ||||
|   ); | ||||
|  | ||||
|   ensure!(!gateways.is_empty(), PortalConfigError::EmptyGateways); | ||||
|  | ||||
|   Ok(PortalConfig::new( | ||||
|     server.to_string(), | ||||
|     AuthCookieCredential::new( | ||||
|       cred.username(), | ||||
|       &user_auth_cookie, | ||||
|       &prelogon_user_auth_cookie, | ||||
|     ), | ||||
|     gateways, | ||||
|     config_digest, | ||||
|   )) | ||||
| } | ||||
|  | ||||
| fn remove_url_scheme(s: &str) -> String { | ||||
|   s.replace("http://", "").replace("https://", "") | ||||
| } | ||||
| @@ -1,5 +0,0 @@ | ||||
| mod config; | ||||
| mod prelogin; | ||||
|  | ||||
| pub use config::*; | ||||
| pub use prelogin::*; | ||||
| @@ -1,156 +0,0 @@ | ||||
| use anyhow::bail; | ||||
| use log::{info, trace}; | ||||
| use reqwest::Client; | ||||
| use roxmltree::Document; | ||||
| use serde::Serialize; | ||||
| use specta::Type; | ||||
|  | ||||
| use crate::{ | ||||
|   gp_params::GpParams, | ||||
|   utils::{base64, normalize_server, xml}, | ||||
| }; | ||||
|  | ||||
| const REQUIRED_PARAMS: [&str; 8] = [ | ||||
|   "tmp", | ||||
|   "clientVer", | ||||
|   "clientos", | ||||
|   "os-version", | ||||
|   "host-id", | ||||
|   "ipv6-support", | ||||
|   "default-browser", | ||||
|   "cas-support", | ||||
| ]; | ||||
|  | ||||
| #[derive(Debug, Serialize, Type, Clone)] | ||||
| #[serde(rename_all = "camelCase")] | ||||
| pub struct SamlPrelogin { | ||||
|   region: String, | ||||
|   saml_request: String, | ||||
| } | ||||
|  | ||||
| impl SamlPrelogin { | ||||
|   pub fn region(&self) -> &str { | ||||
|     &self.region | ||||
|   } | ||||
|  | ||||
|   pub fn saml_request(&self) -> &str { | ||||
|     &self.saml_request | ||||
|   } | ||||
| } | ||||
|  | ||||
| #[derive(Debug, Serialize, Type, Clone)] | ||||
| #[serde(rename_all = "camelCase")] | ||||
| pub struct StandardPrelogin { | ||||
|   region: String, | ||||
|   auth_message: String, | ||||
|   label_username: String, | ||||
|   label_password: String, | ||||
| } | ||||
|  | ||||
| impl StandardPrelogin { | ||||
|   pub fn region(&self) -> &str { | ||||
|     &self.region | ||||
|   } | ||||
|  | ||||
|   pub fn auth_message(&self) -> &str { | ||||
|     &self.auth_message | ||||
|   } | ||||
|  | ||||
|   pub fn label_username(&self) -> &str { | ||||
|     &self.label_username | ||||
|   } | ||||
|  | ||||
|   pub fn label_password(&self) -> &str { | ||||
|     &self.label_password | ||||
|   } | ||||
| } | ||||
|  | ||||
| #[derive(Debug, Serialize, Type, Clone)] | ||||
| #[serde(tag = "type", rename_all = "camelCase")] | ||||
| pub enum Prelogin { | ||||
|   Saml(SamlPrelogin), | ||||
|   Standard(StandardPrelogin), | ||||
| } | ||||
|  | ||||
| impl Prelogin { | ||||
|   pub fn region(&self) -> &str { | ||||
|     match self { | ||||
|       Prelogin::Saml(saml) => saml.region(), | ||||
|       Prelogin::Standard(standard) => standard.region(), | ||||
|     } | ||||
|   } | ||||
| } | ||||
|  | ||||
| pub async fn prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result<Prelogin> { | ||||
|   let user_agent = gp_params.user_agent(); | ||||
|   info!("Portal prelogin, user_agent: {}", user_agent); | ||||
|  | ||||
|   let portal = normalize_server(portal)?; | ||||
|   let prelogin_url = format!( | ||||
|     "{}/global-protect/prelogin.esp?kerberos-support=yes", | ||||
|     portal | ||||
|   ); | ||||
|   let mut params = gp_params.to_params(); | ||||
|   params.insert("tmp", "tmp"); | ||||
|   params.insert("default-browser", "0"); | ||||
|   params.insert("cas-support", "yes"); | ||||
|  | ||||
|   params.retain(|k, _| { | ||||
|     REQUIRED_PARAMS | ||||
|       .iter() | ||||
|       .any(|required_param| required_param == k) | ||||
|   }); | ||||
|  | ||||
|   let client = Client::builder() | ||||
|     .danger_accept_invalid_certs(gp_params.ignore_tls_errors()) | ||||
|     .user_agent(user_agent) | ||||
|     .build()?; | ||||
|  | ||||
|   let res = client.post(&prelogin_url).form(¶ms).send().await?; | ||||
|   let res_xml = res.error_for_status()?.text().await?; | ||||
|  | ||||
|   trace!("Prelogin response: {}", res_xml); | ||||
|   let doc = Document::parse(&res_xml)?; | ||||
|  | ||||
|   let status = xml::get_child_text(&doc, "status") | ||||
|     .ok_or_else(|| anyhow::anyhow!("Prelogin response does not contain status element"))?; | ||||
|   // Check the status of the prelogin response | ||||
|   if status.to_uppercase() != "SUCCESS" { | ||||
|     let msg = xml::get_child_text(&doc, "msg").unwrap_or(String::from("Unknown error")); | ||||
|     bail!("Prelogin failed: {}", msg) | ||||
|   } | ||||
|  | ||||
|   let region = xml::get_child_text(&doc, "region") | ||||
|     .ok_or_else(|| anyhow::anyhow!("Prelogin response does not contain region element"))?; | ||||
|  | ||||
|   let saml_method = xml::get_child_text(&doc, "saml-auth-method"); | ||||
|   let saml_request = xml::get_child_text(&doc, "saml-request"); | ||||
|   // Check if the prelogin response is SAML | ||||
|   if saml_method.is_some() && saml_request.is_some() { | ||||
|     let saml_request = base64::decode_to_string(&saml_request.unwrap())?; | ||||
|     let saml_prelogin = SamlPrelogin { | ||||
|       region, | ||||
|       saml_request, | ||||
|     }; | ||||
|  | ||||
|     return Ok(Prelogin::Saml(saml_prelogin)); | ||||
|   } | ||||
|  | ||||
|   let label_username = xml::get_child_text(&doc, "username-label"); | ||||
|   let label_password = xml::get_child_text(&doc, "password-label"); | ||||
|   // Check if the prelogin response is standard login | ||||
|   if label_username.is_some() && label_password.is_some() { | ||||
|     let auth_message = xml::get_child_text(&doc, "authentication-message") | ||||
|       .unwrap_or(String::from("Please enter the login credentials")); | ||||
|     let standard_prelogin = StandardPrelogin { | ||||
|       region, | ||||
|       auth_message, | ||||
|       label_username: label_username.unwrap(), | ||||
|       label_password: label_password.unwrap(), | ||||
|     }; | ||||
|  | ||||
|     return Ok(Prelogin::Standard(standard_prelogin)); | ||||
|   } | ||||
|  | ||||
|   bail!("Invalid prelogin response"); | ||||
| } | ||||
| @@ -1,129 +0,0 @@ | ||||
| use std::process::Stdio; | ||||
|  | ||||
| use tokio::process::Command; | ||||
|  | ||||
| use crate::{auth::SamlAuthResult, credential::Credential, GP_AUTH_BINARY}; | ||||
|  | ||||
| use super::command_traits::CommandExt; | ||||
|  | ||||
| pub struct SamlAuthLauncher<'a> { | ||||
|   server: &'a str, | ||||
|   saml_request: Option<&'a str>, | ||||
|   user_agent: Option<&'a str>, | ||||
|   os: Option<&'a str>, | ||||
|   os_version: Option<&'a str>, | ||||
|   hidpi: bool, | ||||
|   fix_openssl: bool, | ||||
|   ignore_tls_errors: bool, | ||||
|   clean: bool, | ||||
| } | ||||
|  | ||||
| impl<'a> SamlAuthLauncher<'a> { | ||||
|   pub fn new(server: &'a str) -> Self { | ||||
|     Self { | ||||
|       server, | ||||
|       saml_request: None, | ||||
|       user_agent: None, | ||||
|       os: None, | ||||
|       os_version: None, | ||||
|       hidpi: false, | ||||
|       fix_openssl: false, | ||||
|       ignore_tls_errors: false, | ||||
|       clean: false, | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub fn saml_request(mut self, saml_request: &'a str) -> Self { | ||||
|     self.saml_request = Some(saml_request); | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn user_agent(mut self, user_agent: &'a str) -> Self { | ||||
|     self.user_agent = Some(user_agent); | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn os(mut self, os: &'a str) -> Self { | ||||
|     self.os = Some(os); | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn os_version(mut self, os_version: Option<&'a str>) -> Self { | ||||
|     self.os_version = os_version; | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn hidpi(mut self, hidpi: bool) -> Self { | ||||
|     self.hidpi = hidpi; | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn fix_openssl(mut self, fix_openssl: bool) -> Self { | ||||
|     self.fix_openssl = fix_openssl; | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn ignore_tls_errors(mut self, ignore_tls_errors: bool) -> Self { | ||||
|     self.ignore_tls_errors = ignore_tls_errors; | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn clean(mut self, clean: bool) -> Self { | ||||
|     self.clean = clean; | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   /// Launch the authenticator binary as the current user or SUDO_USER if available. | ||||
|   pub async fn launch(self) -> anyhow::Result<Credential> { | ||||
|     let mut auth_cmd = Command::new(GP_AUTH_BINARY); | ||||
|     auth_cmd.arg(self.server); | ||||
|  | ||||
|     if let Some(saml_request) = self.saml_request { | ||||
|       auth_cmd.arg("--saml-request").arg(saml_request); | ||||
|     } | ||||
|  | ||||
|     if let Some(user_agent) = self.user_agent { | ||||
|       auth_cmd.arg("--user-agent").arg(user_agent); | ||||
|     } | ||||
|  | ||||
|     if let Some(os) = self.os { | ||||
|       auth_cmd.arg("--os").arg(os); | ||||
|     } | ||||
|  | ||||
|     if let Some(os_version) = self.os_version { | ||||
|       auth_cmd.arg("--os-version").arg(os_version); | ||||
|     } | ||||
|  | ||||
|     if self.hidpi { | ||||
|       auth_cmd.arg("--hidpi"); | ||||
|     } | ||||
|  | ||||
|     if self.fix_openssl { | ||||
|       auth_cmd.arg("--fix-openssl"); | ||||
|     } | ||||
|  | ||||
|     if self.ignore_tls_errors { | ||||
|       auth_cmd.arg("--ignore-tls-errors"); | ||||
|     } | ||||
|  | ||||
|     if self.clean { | ||||
|       auth_cmd.arg("--clean"); | ||||
|     } | ||||
|  | ||||
|     let mut non_root_cmd = auth_cmd.into_non_root()?; | ||||
|     let output = non_root_cmd | ||||
|       .kill_on_drop(true) | ||||
|       .stdout(Stdio::piped()) | ||||
|       .spawn()? | ||||
|       .wait_with_output() | ||||
|       .await?; | ||||
|  | ||||
|     let auth_result: SamlAuthResult = serde_json::from_slice(&output.stdout) | ||||
|       .map_err(|_| anyhow::anyhow!("Failed to parse auth data"))?; | ||||
|  | ||||
|     match auth_result { | ||||
|       SamlAuthResult::Success(auth_data) => Credential::try_from(auth_data), | ||||
|       SamlAuthResult::Failure(msg) => Err(anyhow::anyhow!(msg)), | ||||
|     } | ||||
|   } | ||||
| } | ||||
| @@ -1,64 +0,0 @@ | ||||
| use anyhow::bail; | ||||
| use std::{env, ffi::OsStr}; | ||||
| use tokio::process::Command; | ||||
| use uzers::{os::unix::UserExt, User}; | ||||
|  | ||||
| pub trait CommandExt { | ||||
|   fn new_pkexec<S: AsRef<OsStr>>(program: S) -> Command; | ||||
|   fn into_non_root(self) -> anyhow::Result<Command>; | ||||
| } | ||||
|  | ||||
| impl CommandExt for Command { | ||||
|   fn new_pkexec<S: AsRef<OsStr>>(program: S) -> Command { | ||||
|     let mut cmd = Command::new("pkexec"); | ||||
|     cmd | ||||
|       .arg("--disable-internal-agent") | ||||
|       .arg("--user") | ||||
|       .arg("root") | ||||
|       .arg(program); | ||||
|  | ||||
|     cmd | ||||
|   } | ||||
|  | ||||
|   fn into_non_root(mut self) -> anyhow::Result<Command> { | ||||
|     let user = | ||||
|       get_non_root_user().map_err(|_| anyhow::anyhow!("{:?} cannot be run as root", self))?; | ||||
|  | ||||
|     self | ||||
|       .env("HOME", user.home_dir()) | ||||
|       .env("USER", user.name()) | ||||
|       .env("LOGNAME", user.name()) | ||||
|       .env("USERNAME", user.name()) | ||||
|       .uid(user.uid()) | ||||
|       .gid(user.primary_group_id()); | ||||
|  | ||||
|     Ok(self) | ||||
|   } | ||||
| } | ||||
|  | ||||
| fn get_non_root_user() -> anyhow::Result<User> { | ||||
|   let current_user = whoami::username(); | ||||
|  | ||||
|   let user = if current_user == "root" { | ||||
|     get_real_user()? | ||||
|   } else { | ||||
|     uzers::get_user_by_name(¤t_user) | ||||
|       .ok_or_else(|| anyhow::anyhow!("User ({}) not found", current_user))? | ||||
|   }; | ||||
|  | ||||
|   if user.uid() == 0 { | ||||
|     bail!("Non-root user not found") | ||||
|   } | ||||
|  | ||||
|   Ok(user) | ||||
| } | ||||
|  | ||||
| fn get_real_user() -> anyhow::Result<User> { | ||||
|   // Read the UID from SUDO_UID or PKEXEC_UID environment variable if available. | ||||
|   let uid = match env::var("SUDO_UID") { | ||||
|     Ok(uid) => uid.parse::<u32>()?, | ||||
|     _ => env::var("PKEXEC_UID")?.parse::<u32>()?, | ||||
|   }; | ||||
|  | ||||
|   uzers::get_user_by_uid(uid).ok_or_else(|| anyhow::anyhow!("User not found")) | ||||
| } | ||||
| @@ -1,91 +0,0 @@ | ||||
| use std::{ | ||||
|   collections::HashMap, | ||||
|   path::PathBuf, | ||||
|   process::{ExitStatus, Stdio}, | ||||
| }; | ||||
|  | ||||
| use tokio::{io::AsyncWriteExt, process::Command}; | ||||
|  | ||||
| use crate::{utils::base64, GP_GUI_BINARY}; | ||||
|  | ||||
| use super::command_traits::CommandExt; | ||||
|  | ||||
| pub struct GuiLauncher { | ||||
|   program: PathBuf, | ||||
|   api_key: Option<Vec<u8>>, | ||||
|   minimized: bool, | ||||
|   envs: Option<HashMap<String, String>>, | ||||
| } | ||||
|  | ||||
| impl Default for GuiLauncher { | ||||
|   fn default() -> Self { | ||||
|     Self::new() | ||||
|   } | ||||
| } | ||||
|  | ||||
| impl GuiLauncher { | ||||
|   pub fn new() -> Self { | ||||
|     Self { | ||||
|       program: GP_GUI_BINARY.into(), | ||||
|       api_key: None, | ||||
|       minimized: false, | ||||
|       envs: None, | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub fn envs<T: Into<Option<HashMap<String, String>>>>(mut self, envs: T) -> Self { | ||||
|     self.envs = envs.into(); | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn api_key(mut self, api_key: Vec<u8>) -> Self { | ||||
|     self.api_key = Some(api_key); | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn minimized(mut self, minimized: bool) -> Self { | ||||
|     self.minimized = minimized; | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub async fn launch(&self) -> anyhow::Result<ExitStatus> { | ||||
|     let mut cmd = Command::new(&self.program); | ||||
|  | ||||
|     if let Some(envs) = &self.envs { | ||||
|       cmd.env_clear(); | ||||
|       cmd.envs(envs); | ||||
|     } | ||||
|  | ||||
|     if self.api_key.is_some() { | ||||
|       cmd.arg("--api-key-on-stdin"); | ||||
|     } | ||||
|  | ||||
|     if self.minimized { | ||||
|       cmd.arg("--minimized"); | ||||
|     } | ||||
|  | ||||
|     let mut non_root_cmd = cmd.into_non_root()?; | ||||
|  | ||||
|     let mut child = non_root_cmd | ||||
|       .kill_on_drop(true) | ||||
|       .stdin(Stdio::piped()) | ||||
|       .spawn()?; | ||||
|  | ||||
|     let mut stdin = child | ||||
|       .stdin | ||||
|       .take() | ||||
|       .ok_or_else(|| anyhow::anyhow!("Failed to open stdin"))?; | ||||
|  | ||||
|     if let Some(api_key) = &self.api_key { | ||||
|       let api_key = base64::encode(api_key); | ||||
|       tokio::spawn(async move { | ||||
|         stdin.write_all(api_key.as_bytes()).await.unwrap(); | ||||
|         drop(stdin); | ||||
|       }); | ||||
|     } | ||||
|  | ||||
|     let exit_status = child.wait().await?; | ||||
|  | ||||
|     Ok(exit_status) | ||||
|   } | ||||
| } | ||||
| @@ -1,5 +0,0 @@ | ||||
| pub(crate) mod command_traits; | ||||
|  | ||||
| pub mod auth_launcher; | ||||
| pub mod gui_launcher; | ||||
| pub mod service_launcher; | ||||
| @@ -1,72 +0,0 @@ | ||||
| use std::{ | ||||
|   fs::File, | ||||
|   path::PathBuf, | ||||
|   process::{ExitStatus, Stdio}, | ||||
| }; | ||||
|  | ||||
| use tokio::process::Command; | ||||
|  | ||||
| use crate::GP_SERVICE_BINARY; | ||||
|  | ||||
| use super::command_traits::CommandExt; | ||||
|  | ||||
| pub struct ServiceLauncher { | ||||
|   program: PathBuf, | ||||
|   minimized: bool, | ||||
|   env_file: Option<String>, | ||||
|   log_file: Option<String>, | ||||
| } | ||||
|  | ||||
| impl Default for ServiceLauncher { | ||||
|   fn default() -> Self { | ||||
|     Self::new() | ||||
|   } | ||||
| } | ||||
|  | ||||
| impl ServiceLauncher { | ||||
|   pub fn new() -> Self { | ||||
|     Self { | ||||
|       program: GP_SERVICE_BINARY.into(), | ||||
|       minimized: false, | ||||
|       env_file: None, | ||||
|       log_file: None, | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub fn minimized(mut self, minimized: bool) -> Self { | ||||
|     self.minimized = minimized; | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn env_file(mut self, env_file: &str) -> Self { | ||||
|     self.env_file = Some(env_file.to_string()); | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn log_file(mut self, log_file: &str) -> Self { | ||||
|     self.log_file = Some(log_file.to_string()); | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub async fn launch(&self) -> anyhow::Result<ExitStatus> { | ||||
|     let mut cmd = Command::new_pkexec(&self.program); | ||||
|  | ||||
|     if self.minimized { | ||||
|       cmd.arg("--minimized"); | ||||
|     } | ||||
|  | ||||
|     if let Some(env_file) = &self.env_file { | ||||
|       cmd.arg("--env-file").arg(env_file); | ||||
|     } | ||||
|  | ||||
|     if let Some(log_file) = &self.log_file { | ||||
|       let log_file = File::create(log_file)?; | ||||
|       let stdio = Stdio::from(log_file); | ||||
|       cmd.stderr(stdio); | ||||
|     } | ||||
|  | ||||
|     let exit_status = cmd.kill_on_drop(true).spawn()?.wait().await?; | ||||
|  | ||||
|     Ok(exit_status) | ||||
|   } | ||||
| } | ||||
| @@ -1,10 +0,0 @@ | ||||
| use serde::{Deserialize, Serialize}; | ||||
|  | ||||
| use super::vpn_state::VpnState; | ||||
|  | ||||
| /// Events that can be emitted by the service | ||||
| #[derive(Debug, Serialize, Deserialize, Clone)] | ||||
| pub enum WsEvent { | ||||
|   VpnState(VpnState), | ||||
|   ActiveGui, | ||||
| } | ||||
| @@ -1,3 +0,0 @@ | ||||
| pub mod event; | ||||
| pub mod request; | ||||
| pub mod vpn_state; | ||||
| @@ -1,118 +0,0 @@ | ||||
| use std::collections::HashMap; | ||||
|  | ||||
| use serde::{Deserialize, Serialize}; | ||||
| use specta::Type; | ||||
|  | ||||
| use crate::{gateway::Gateway, gp_params::ClientOs}; | ||||
|  | ||||
| use super::vpn_state::ConnectInfo; | ||||
|  | ||||
| #[derive(Debug, Deserialize, Serialize)] | ||||
| pub struct LaunchGuiRequest { | ||||
|   user: String, | ||||
|   envs: HashMap<String, String>, | ||||
| } | ||||
|  | ||||
| impl LaunchGuiRequest { | ||||
|   pub fn new(user: String, envs: HashMap<String, String>) -> Self { | ||||
|     Self { user, envs } | ||||
|   } | ||||
|  | ||||
|   pub fn user(&self) -> &str { | ||||
|     &self.user | ||||
|   } | ||||
|  | ||||
|   pub fn envs(&self) -> &HashMap<String, String> { | ||||
|     &self.envs | ||||
|   } | ||||
| } | ||||
|  | ||||
| #[derive(Debug, Deserialize, Serialize, Type)] | ||||
| pub struct ConnectArgs { | ||||
|   cookie: String, | ||||
|   vpnc_script: Option<String>, | ||||
|   user_agent: Option<String>, | ||||
|   os: Option<ClientOs>, | ||||
| } | ||||
|  | ||||
| impl ConnectArgs { | ||||
|   pub fn new(cookie: String) -> Self { | ||||
|     Self { | ||||
|       cookie, | ||||
|       vpnc_script: None, | ||||
|       user_agent: None, | ||||
|       os: None, | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub fn cookie(&self) -> &str { | ||||
|     &self.cookie | ||||
|   } | ||||
|  | ||||
|   pub fn vpnc_script(&self) -> Option<String> { | ||||
|     self.vpnc_script.clone() | ||||
|   } | ||||
|  | ||||
|   pub fn user_agent(&self) -> Option<String> { | ||||
|     self.user_agent.clone() | ||||
|   } | ||||
|  | ||||
|   pub fn openconnect_os(&self) -> Option<String> { | ||||
|     self | ||||
|       .os | ||||
|       .as_ref() | ||||
|       .map(|os| os.to_openconnect_os().to_string()) | ||||
|   } | ||||
| } | ||||
|  | ||||
| #[derive(Debug, Deserialize, Serialize, Type)] | ||||
| pub struct ConnectRequest { | ||||
|   info: ConnectInfo, | ||||
|   args: ConnectArgs, | ||||
| } | ||||
|  | ||||
| impl ConnectRequest { | ||||
|   pub fn new(info: ConnectInfo, cookie: String) -> Self { | ||||
|     Self { | ||||
|       info, | ||||
|       args: ConnectArgs::new(cookie), | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub fn with_vpnc_script<T: Into<Option<String>>>(mut self, vpnc_script: T) -> Self { | ||||
|     self.args.vpnc_script = vpnc_script.into(); | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn with_user_agent<T: Into<Option<String>>>(mut self, user_agent: T) -> Self { | ||||
|     self.args.user_agent = user_agent.into(); | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn with_os<T: Into<Option<ClientOs>>>(mut self, os: T) -> Self { | ||||
|     self.args.os = os.into(); | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn gateway(&self) -> &Gateway { | ||||
|     self.info.gateway() | ||||
|   } | ||||
|  | ||||
|   pub fn info(&self) -> &ConnectInfo { | ||||
|     &self.info | ||||
|   } | ||||
|  | ||||
|   pub fn args(&self) -> &ConnectArgs { | ||||
|     &self.args | ||||
|   } | ||||
| } | ||||
|  | ||||
| #[derive(Debug, Deserialize, Serialize, Type)] | ||||
| pub struct DisconnectRequest; | ||||
|  | ||||
| /// Requests that can be sent to the service | ||||
| #[derive(Debug, Deserialize, Serialize)] | ||||
| pub enum WsRequest { | ||||
|   Connect(Box<ConnectRequest>), | ||||
|   Disconnect(DisconnectRequest), | ||||
| } | ||||
| @@ -1,34 +0,0 @@ | ||||
| use serde::{Deserialize, Serialize}; | ||||
| use specta::Type; | ||||
|  | ||||
| use crate::gateway::Gateway; | ||||
|  | ||||
| #[derive(Debug, Deserialize, Serialize, Type, Clone)] | ||||
| pub struct ConnectInfo { | ||||
|   portal: String, | ||||
|   gateway: Gateway, | ||||
|   gateways: Vec<Gateway>, | ||||
| } | ||||
|  | ||||
| impl ConnectInfo { | ||||
|   pub fn new(portal: String, gateway: Gateway, gateways: Vec<Gateway>) -> Self { | ||||
|     Self { | ||||
|       portal, | ||||
|       gateway, | ||||
|       gateways, | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub fn gateway(&self) -> &Gateway { | ||||
|     &self.gateway | ||||
|   } | ||||
| } | ||||
|  | ||||
| #[derive(Debug, Serialize, Deserialize, Clone)] | ||||
| #[serde(rename_all = "camelCase")] | ||||
| pub enum VpnState { | ||||
|   Disconnected, | ||||
|   Connecting(Box<ConnectInfo>), | ||||
|   Connected(Box<ConnectInfo>), | ||||
|   Disconnecting, | ||||
| } | ||||
| @@ -1,21 +0,0 @@ | ||||
| use base64::{engine::general_purpose, Engine}; | ||||
|  | ||||
| pub fn encode(data: &[u8]) -> String { | ||||
|   let engine = general_purpose::STANDARD; | ||||
|  | ||||
|   engine.encode(data) | ||||
| } | ||||
|  | ||||
| pub fn decode_to_vec(s: &str) -> anyhow::Result<Vec<u8>> { | ||||
|   let engine = general_purpose::STANDARD; | ||||
|   let decoded = engine.decode(s)?; | ||||
|  | ||||
|   Ok(decoded) | ||||
| } | ||||
|  | ||||
| pub(crate) fn decode_to_string(s: &str) -> anyhow::Result<String> { | ||||
|   let decoded = decode_to_vec(s)?; | ||||
|   let decoded = String::from_utf8(decoded)?; | ||||
|  | ||||
|   Ok(decoded) | ||||
| } | ||||
| @@ -1,108 +0,0 @@ | ||||
| use chacha20poly1305::{ | ||||
|   aead::{Aead, OsRng}, | ||||
|   AeadCore, ChaCha20Poly1305, Key, KeyInit, Nonce, | ||||
| }; | ||||
| use serde::{de::DeserializeOwned, Serialize}; | ||||
|  | ||||
| pub fn generate_key() -> Key { | ||||
|   ChaCha20Poly1305::generate_key(&mut OsRng) | ||||
| } | ||||
|  | ||||
| pub fn encrypt<T>(key: &Key, value: &T) -> anyhow::Result<Vec<u8>> | ||||
| where | ||||
|   T: Serialize, | ||||
| { | ||||
|   let cipher = ChaCha20Poly1305::new(key); | ||||
|   let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng); | ||||
|  | ||||
|   let data = serde_json::to_vec(value)?; | ||||
|   let cipher_text = cipher.encrypt(&nonce, data.as_ref())?; | ||||
|  | ||||
|   let mut encrypted = Vec::new(); | ||||
|   encrypted.extend_from_slice(&nonce); | ||||
|   encrypted.extend_from_slice(&cipher_text); | ||||
|  | ||||
|   Ok(encrypted) | ||||
| } | ||||
|  | ||||
| pub fn decrypt<T>(key: &Key, encrypted: Vec<u8>) -> anyhow::Result<T> | ||||
| where | ||||
|   T: DeserializeOwned, | ||||
| { | ||||
|   let cipher = ChaCha20Poly1305::new(key); | ||||
|  | ||||
|   let nonce = Nonce::from_slice(&encrypted[..12]); | ||||
|   let cipher_text = &encrypted[12..]; | ||||
|  | ||||
|   let plaintext = cipher.decrypt(nonce, cipher_text)?; | ||||
|  | ||||
|   let value = serde_json::from_slice(&plaintext)?; | ||||
|  | ||||
|   Ok(value) | ||||
| } | ||||
|  | ||||
| pub struct Crypto { | ||||
|   key: Vec<u8>, | ||||
| } | ||||
|  | ||||
| impl Crypto { | ||||
|   pub fn new(key: Vec<u8>) -> Self { | ||||
|     Self { key } | ||||
|   } | ||||
|  | ||||
|   pub fn encrypt<T: Serialize>(&self, plain: T) -> anyhow::Result<Vec<u8>> { | ||||
|     let key: &[u8] = &self.key; | ||||
|     let encrypted_data = encrypt(key.into(), &plain)?; | ||||
|  | ||||
|     Ok(encrypted_data) | ||||
|   } | ||||
|  | ||||
|   pub fn decrypt<T: DeserializeOwned>(&self, encrypted: Vec<u8>) -> anyhow::Result<T> { | ||||
|     let key: &[u8] = &self.key; | ||||
|     decrypt(key.into(), encrypted) | ||||
|   } | ||||
|  | ||||
|   pub fn encrypt_to<T: Serialize>(&self, path: &std::path::Path, plain: T) -> anyhow::Result<()> { | ||||
|     let encrypted_data = self.encrypt(plain)?; | ||||
|     std::fs::write(path, encrypted_data)?; | ||||
|  | ||||
|     Ok(()) | ||||
|   } | ||||
|  | ||||
|   pub fn decrypt_from<T: DeserializeOwned>(&self, path: &std::path::Path) -> anyhow::Result<T> { | ||||
|     let encrypted_data = std::fs::read(path)?; | ||||
|     self.decrypt(encrypted_data) | ||||
|   } | ||||
| } | ||||
|  | ||||
| #[cfg(test)] | ||||
| mod tests { | ||||
|   use serde::Deserialize; | ||||
|  | ||||
|   use super::*; | ||||
|  | ||||
|   #[derive(Serialize, Deserialize)] | ||||
|   struct User { | ||||
|     name: String, | ||||
|     age: u8, | ||||
|   } | ||||
|  | ||||
|   #[test] | ||||
|   fn it_works() -> anyhow::Result<()> { | ||||
|     let key = generate_key(); | ||||
|  | ||||
|     let user = User { | ||||
|       name: "test".to_string(), | ||||
|       age: 18, | ||||
|     }; | ||||
|  | ||||
|     let encrypted = encrypt(&key, &user)?; | ||||
|  | ||||
|     let decrypted_user = decrypt::<User>(&key, encrypted)?; | ||||
|  | ||||
|     assert_eq!(user.name, decrypted_user.name); | ||||
|     assert_eq!(user.age, decrypted_user.age); | ||||
|  | ||||
|     Ok(()) | ||||
|   } | ||||
| } | ||||
| @@ -1,20 +0,0 @@ | ||||
| use tokio::fs; | ||||
|  | ||||
| use crate::GP_SERVICE_LOCK_FILE; | ||||
|  | ||||
| async fn read_port() -> anyhow::Result<String> { | ||||
|   let port = fs::read_to_string(GP_SERVICE_LOCK_FILE).await?; | ||||
|   Ok(port.trim().to_string()) | ||||
| } | ||||
|  | ||||
| pub async fn http_endpoint() -> anyhow::Result<String> { | ||||
|   let port = read_port().await?; | ||||
|  | ||||
|   Ok(format!("http://127.0.0.1:{}", port)) | ||||
| } | ||||
|  | ||||
| pub async fn ws_endpoint() -> anyhow::Result<String> { | ||||
|   let port = read_port().await?; | ||||
|  | ||||
|   Ok(format!("ws://127.0.0.1:{}/ws", port)) | ||||
| } | ||||
| @@ -1,37 +0,0 @@ | ||||
| use std::collections::HashMap; | ||||
| use std::env; | ||||
| use std::io::Write; | ||||
| use std::path::Path; | ||||
|  | ||||
| use tempfile::NamedTempFile; | ||||
|  | ||||
| pub fn persist_env_vars(extra: Option<HashMap<String, String>>) -> anyhow::Result<NamedTempFile> { | ||||
|   let mut env_file = NamedTempFile::new()?; | ||||
|   let content = env::vars() | ||||
|     .map(|(key, value)| format!("{}={}", key, value)) | ||||
|     .chain( | ||||
|       extra | ||||
|         .unwrap_or_default() | ||||
|         .into_iter() | ||||
|         .map(|(key, value)| format!("{}={}", key, value)), | ||||
|     ) | ||||
|     .collect::<Vec<String>>() | ||||
|     .join("\n"); | ||||
|  | ||||
|   writeln!(env_file, "{}", content)?; | ||||
|  | ||||
|   Ok(env_file) | ||||
| } | ||||
|  | ||||
| pub fn load_env_vars<T: AsRef<Path>>(env_file: T) -> anyhow::Result<HashMap<String, String>> { | ||||
|   let content = std::fs::read_to_string(env_file)?; | ||||
|   let mut env_vars: HashMap<String, String> = HashMap::new(); | ||||
|  | ||||
|   for line in content.lines() { | ||||
|     if let Some((key, value)) = line.split_once('=') { | ||||
|       env_vars.insert(key.to_string(), value.to_string()); | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   Ok(env_vars) | ||||
| } | ||||
| @@ -1,39 +0,0 @@ | ||||
| use std::path::PathBuf; | ||||
|  | ||||
| pub struct LockFile { | ||||
|   path: PathBuf, | ||||
| } | ||||
|  | ||||
| impl LockFile { | ||||
|   pub fn new<P: Into<PathBuf>>(path: P) -> Self { | ||||
|     Self { path: path.into() } | ||||
|   } | ||||
|  | ||||
|   pub fn exists(&self) -> bool { | ||||
|     self.path.exists() | ||||
|   } | ||||
|  | ||||
|   pub fn lock(&self, content: impl AsRef<[u8]>) -> anyhow::Result<()> { | ||||
|     std::fs::write(&self.path, content)?; | ||||
|     Ok(()) | ||||
|   } | ||||
|  | ||||
|   pub fn unlock(&self) -> anyhow::Result<()> { | ||||
|     std::fs::remove_file(&self.path)?; | ||||
|     Ok(()) | ||||
|   } | ||||
|  | ||||
|   pub async fn check_health(&self) -> bool { | ||||
|     match std::fs::read_to_string(&self.path) { | ||||
|       Ok(content) => { | ||||
|         let url = format!("http://127.0.0.1:{}/health", content.trim()); | ||||
|  | ||||
|         match reqwest::get(&url).await { | ||||
|           Ok(resp) => resp.status().is_success(), | ||||
|           Err(_) => false, | ||||
|         } | ||||
|       } | ||||
|       Err(_) => false, | ||||
|     } | ||||
|   } | ||||
| } | ||||
| @@ -1,40 +0,0 @@ | ||||
| use reqwest::Url; | ||||
|  | ||||
| pub(crate) mod xml; | ||||
|  | ||||
| pub mod base64; | ||||
| pub mod crypto; | ||||
| pub mod endpoint; | ||||
| pub mod env_file; | ||||
| pub mod lock_file; | ||||
| pub mod openssl; | ||||
| pub mod redact; | ||||
| #[cfg(feature = "tauri")] | ||||
| pub mod window; | ||||
|  | ||||
| mod shutdown_signal; | ||||
|  | ||||
| pub use shutdown_signal::shutdown_signal; | ||||
|  | ||||
| /// Normalize the server URL to the format `https://<host>:<port>` | ||||
| pub fn normalize_server(server: &str) -> anyhow::Result<String> { | ||||
|   let server = if server.starts_with("https://") || server.starts_with("http://") { | ||||
|     server.to_string() | ||||
|   } else { | ||||
|     format!("https://{}", server) | ||||
|   }; | ||||
|  | ||||
|   let normalized_url = Url::parse(&server)?; | ||||
|   let scheme = normalized_url.scheme(); | ||||
|   let host = normalized_url | ||||
|     .host_str() | ||||
|     .ok_or(anyhow::anyhow!("Invalid server URL: missing host"))?; | ||||
|  | ||||
|   let port: String = normalized_url | ||||
|     .port() | ||||
|     .map_or("".into(), |port| format!(":{}", port)); | ||||
|  | ||||
|   let normalized_url = format!("{}://{}{}", scheme, host, port); | ||||
|  | ||||
|   Ok(normalized_url) | ||||
| } | ||||
| @@ -1,37 +0,0 @@ | ||||
| use std::path::Path; | ||||
|  | ||||
| use tempfile::NamedTempFile; | ||||
|  | ||||
| pub fn openssl_conf() -> String { | ||||
|   let option = "UnsafeLegacyServerConnect"; | ||||
|  | ||||
|   format!( | ||||
|     "openssl_conf = openssl_init | ||||
|  | ||||
| [openssl_init] | ||||
| ssl_conf = ssl_sect | ||||
|  | ||||
| [ssl_sect] | ||||
| system_default = system_default_sect | ||||
|  | ||||
| [system_default_sect] | ||||
| Options = {}", | ||||
|     option | ||||
|   ) | ||||
| } | ||||
|  | ||||
| pub fn fix_openssl<P: AsRef<Path>>(path: P) -> anyhow::Result<()> { | ||||
|   let content = openssl_conf(); | ||||
|   std::fs::write(path, content)?; | ||||
|   Ok(()) | ||||
| } | ||||
|  | ||||
| pub fn fix_openssl_env() -> anyhow::Result<NamedTempFile> { | ||||
|   let openssl_conf = NamedTempFile::new()?; | ||||
|   let openssl_conf_path = openssl_conf.path(); | ||||
|  | ||||
|   fix_openssl(openssl_conf_path)?; | ||||
|   std::env::set_var("OPENSSL_CONF", openssl_conf_path); | ||||
|  | ||||
|   Ok(openssl_conf) | ||||
| } | ||||
| @@ -1,227 +0,0 @@ | ||||
| use std::sync::RwLock; | ||||
|  | ||||
| use redact_engine::{Pattern, Redaction as RedactEngine}; | ||||
| use regex::Regex; | ||||
| use url::{form_urlencoded, Url}; | ||||
|  | ||||
| pub struct Redaction { | ||||
|   redact_engine: RwLock<Option<RedactEngine>>, | ||||
| } | ||||
|  | ||||
| impl Default for Redaction { | ||||
|   fn default() -> Self { | ||||
|     Self::new() | ||||
|   } | ||||
| } | ||||
|  | ||||
| impl Redaction { | ||||
|   pub fn new() -> Self { | ||||
|     let redact_engine = RedactEngine::custom("[**********]").add_pattern(Pattern { | ||||
|       test: Regex::new("(((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4})").unwrap(), | ||||
|       group: 1, | ||||
|     }); | ||||
|  | ||||
|     Self { | ||||
|       redact_engine: RwLock::new(Some(redact_engine)), | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub fn add_value(&self, text: &str) -> anyhow::Result<()> { | ||||
|     let mut redact_engine = self | ||||
|       .redact_engine | ||||
|       .write() | ||||
|       .map_err(|_| anyhow::anyhow!("Failed to acquire write lock on redact engine"))?; | ||||
|  | ||||
|     *redact_engine = Some( | ||||
|       redact_engine | ||||
|         .take() | ||||
|         .ok_or_else(|| anyhow::anyhow!("Failed to take redact engine"))? | ||||
|         .add_value(text)?, | ||||
|     ); | ||||
|  | ||||
|     Ok(()) | ||||
|   } | ||||
|  | ||||
|   pub fn add_values(&self, texts: &[&str]) -> anyhow::Result<()> { | ||||
|     let mut redact_engine = self | ||||
|       .redact_engine | ||||
|       .write() | ||||
|       .map_err(|_| anyhow::anyhow!("Failed to acquire write lock on redact engine"))?; | ||||
|  | ||||
|     *redact_engine = Some( | ||||
|       redact_engine | ||||
|         .take() | ||||
|         .ok_or_else(|| anyhow::anyhow!("Failed to take redact engine"))? | ||||
|         .add_values(texts.to_vec())?, | ||||
|     ); | ||||
|  | ||||
|     Ok(()) | ||||
|   } | ||||
|  | ||||
|   pub fn redact_str(&self, text: &str) -> String { | ||||
|     self | ||||
|       .redact_engine | ||||
|       .read() | ||||
|       .expect("Failed to acquire read lock on redact engine") | ||||
|       .as_ref() | ||||
|       .expect("Failed to get redact engine") | ||||
|       .redact_str(text) | ||||
|   } | ||||
| } | ||||
|  | ||||
| /// Redact a value by replacing all but the first and last character with asterisks, | ||||
| /// The length of the value to be redacted must be at least 3 characters. | ||||
| /// e.g. "foo" -> "f**********o" | ||||
| pub fn redact_value(text: &str) -> String { | ||||
|   if text.len() < 3 { | ||||
|     return text.to_string(); | ||||
|   } | ||||
|  | ||||
|   let mut redacted = String::new(); | ||||
|   redacted.push_str(&text[0..1]); | ||||
|   redacted.push_str(&"*".repeat(10)); | ||||
|   redacted.push_str(&text[text.len() - 1..]); | ||||
|  | ||||
|   redacted | ||||
| } | ||||
|  | ||||
| pub fn redact_uri(uri: &str) -> String { | ||||
|   let Ok(mut url) = Url::parse(uri) else { | ||||
|     return uri.to_string(); | ||||
|   }; | ||||
|  | ||||
|   // Could be a data: URI | ||||
|   if url.cannot_be_a_base() { | ||||
|     if url.scheme() == "about" { | ||||
|       return uri.to_string(); | ||||
|     } | ||||
|  | ||||
|     if url.path().len() > 15 { | ||||
|       return format!( | ||||
|         "{}:{}{}", | ||||
|         url.scheme(), | ||||
|         &url.path()[0..10], | ||||
|         redact_value(&url.path()[10..]) | ||||
|       ); | ||||
|     } | ||||
|  | ||||
|     return format!("{}:{}", url.scheme(), redact_value(url.path())); | ||||
|   } | ||||
|  | ||||
|   let host = url.host_str().unwrap_or_default(); | ||||
|   if url.set_host(Some(&redact_value(host))).is_err() { | ||||
|     let redacted_query = redact_query(url.query()) | ||||
|       .as_deref() | ||||
|       .map(|query| format!("?{}", query)) | ||||
|       .unwrap_or_default(); | ||||
|  | ||||
|     return format!( | ||||
|       "{}://[**********]{}{}", | ||||
|       url.scheme(), | ||||
|       url.path(), | ||||
|       redacted_query | ||||
|     ); | ||||
|   } | ||||
|  | ||||
|   let redacted_query = redact_query(url.query()); | ||||
|   url.set_query(redacted_query.as_deref()); | ||||
|   url.to_string() | ||||
| } | ||||
|  | ||||
| fn redact_query(query: Option<&str>) -> Option<String> { | ||||
|   let query = query?; | ||||
|  | ||||
|   let query_pairs = form_urlencoded::parse(query.as_bytes()); | ||||
|   let mut redacted_pairs = query_pairs.map(|(key, value)| (key, redact_value(&value))); | ||||
|  | ||||
|   let query = form_urlencoded::Serializer::new(String::new()) | ||||
|     .extend_pairs(redacted_pairs.by_ref()) | ||||
|     .finish(); | ||||
|  | ||||
|   Some(query) | ||||
| } | ||||
|  | ||||
| #[cfg(test)] | ||||
| mod tests { | ||||
|   use super::*; | ||||
|  | ||||
|   #[test] | ||||
|   fn it_should_not_redact_value() { | ||||
|     let text = "fo"; | ||||
|  | ||||
|     assert_eq!(redact_value(text), "fo"); | ||||
|   } | ||||
|  | ||||
|   #[test] | ||||
|   fn it_should_redact_value() { | ||||
|     let text = "foo"; | ||||
|  | ||||
|     assert_eq!(redact_value(text), "f**********o"); | ||||
|   } | ||||
|  | ||||
|   #[test] | ||||
|   fn it_should_redact_dynamic_value() { | ||||
|     let redaction = Redaction::new(); | ||||
|  | ||||
|     redaction.add_value("foo").unwrap(); | ||||
|  | ||||
|     assert_eq!( | ||||
|       redaction.redact_str("hello, foo, bar"), | ||||
|       "hello, [**********], bar" | ||||
|     ); | ||||
|   } | ||||
|  | ||||
|   #[test] | ||||
|   fn it_should_redact_dynamic_values() { | ||||
|     let redaction = Redaction::new(); | ||||
|  | ||||
|     redaction.add_values(&["foo", "bar"]).unwrap(); | ||||
|  | ||||
|     assert_eq!( | ||||
|       redaction.redact_str("hello, foo, bar"), | ||||
|       "hello, [**********], [**********]" | ||||
|     ); | ||||
|   } | ||||
|  | ||||
|   #[test] | ||||
|   fn it_should_redact_uri() { | ||||
|     let uri = "https://foo.bar"; | ||||
|     assert_eq!(redact_uri(uri), "https://f**********r/"); | ||||
|  | ||||
|     let uri = "https://foo.bar/"; | ||||
|     assert_eq!(redact_uri(uri), "https://f**********r/"); | ||||
|  | ||||
|     let uri = "https://foo.bar/baz"; | ||||
|     assert_eq!(redact_uri(uri), "https://f**********r/baz"); | ||||
|  | ||||
|     let uri = "https://foo.bar/baz?qux=quux"; | ||||
|     assert_eq!(redact_uri(uri), "https://f**********r/baz?qux=q**********x"); | ||||
|   } | ||||
|  | ||||
|   #[test] | ||||
|   fn it_should_redact_data_uri() { | ||||
|     let uri = "data:text/plain;a"; | ||||
|     assert_eq!(redact_uri(uri), "data:t**********a"); | ||||
|  | ||||
|     let uri = "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ=="; | ||||
|     assert_eq!(redact_uri(uri), "data:text/plain;**********="); | ||||
|  | ||||
|     let uri = "about:blank"; | ||||
|     assert_eq!(redact_uri(uri), "about:blank"); | ||||
|   } | ||||
|  | ||||
|   #[test] | ||||
|   fn it_should_redact_ipv6() { | ||||
|     let uri = "https://[2001:db8::1]:8080"; | ||||
|     assert_eq!(redact_uri(uri), "https://[**********]/"); | ||||
|  | ||||
|     let uri = "https://[2001:db8::1]:8080/"; | ||||
|     assert_eq!(redact_uri(uri), "https://[**********]/"); | ||||
|  | ||||
|     let uri = "https://[2001:db8::1]:8080/baz"; | ||||
|     assert_eq!(redact_uri(uri), "https://[**********]/baz"); | ||||
|  | ||||
|     let uri = "https://[2001:db8::1]:8080/baz?qux=quux"; | ||||
|     assert_eq!(redact_uri(uri), "https://[**********]/baz?qux=q**********x"); | ||||
|   } | ||||
| } | ||||
| @@ -1,22 +0,0 @@ | ||||
| use tokio::signal; | ||||
|  | ||||
| pub async fn shutdown_signal() { | ||||
|   let ctrl_c = async { | ||||
|     signal::ctrl_c() | ||||
|       .await | ||||
|       .expect("failed to install Ctrl+C handler"); | ||||
|   }; | ||||
|  | ||||
|   #[cfg(unix)] | ||||
|   let terminate = async { | ||||
|     signal::unix::signal(signal::unix::SignalKind::terminate()) | ||||
|       .expect("failed to install signal handler") | ||||
|       .recv() | ||||
|       .await; | ||||
|   }; | ||||
|  | ||||
|   tokio::select! { | ||||
|       _ = ctrl_c => {}, | ||||
|       _ = terminate => {}, | ||||
|   } | ||||
| } | ||||
| @@ -1,89 +0,0 @@ | ||||
| use std::{process::ExitStatus, time::Duration}; | ||||
|  | ||||
| use anyhow::bail; | ||||
| use log::{info, warn}; | ||||
| use tauri::{window::MenuHandle, Window}; | ||||
| use tokio::process::Command; | ||||
|  | ||||
| pub trait WindowExt { | ||||
|   fn raise(&self) -> anyhow::Result<()>; | ||||
| } | ||||
|  | ||||
| impl WindowExt for Window { | ||||
|   fn raise(&self) -> anyhow::Result<()> { | ||||
|     raise_window(self) | ||||
|   } | ||||
| } | ||||
|  | ||||
| pub fn raise_window(win: &Window) -> anyhow::Result<()> { | ||||
|   let is_wayland = std::env::var("XDG_SESSION_TYPE").unwrap_or_default() == "wayland"; | ||||
|  | ||||
|   if is_wayland { | ||||
|     win.hide()?; | ||||
|     win.show()?; | ||||
|   } else { | ||||
|     if !win.is_visible()? { | ||||
|       win.show()?; | ||||
|     } | ||||
|     let title = win.title()?; | ||||
|     tokio::spawn(async move { | ||||
|       if let Err(err) = wmctrl_raise_window(&title).await { | ||||
|         warn!("Failed to raise window: {}", err); | ||||
|       } | ||||
|     }); | ||||
|   } | ||||
|  | ||||
|   // Calling window.show() on Windows will cause the menu to be shown. | ||||
|   hide_menu(win.menu_handle()); | ||||
|  | ||||
|   Ok(()) | ||||
| } | ||||
|  | ||||
| async fn wmctrl_raise_window(title: &str) -> anyhow::Result<()> { | ||||
|   let mut counter = 0; | ||||
|  | ||||
|   loop { | ||||
|     if let Ok(exit_status) = wmctrl_try_raise_window(title).await { | ||||
|       if exit_status.success() { | ||||
|         info!("Window raised after {} attempts", counter + 1); | ||||
|         return Ok(()); | ||||
|       } | ||||
|     } | ||||
|  | ||||
|     if counter >= 10 { | ||||
|       bail!("Failed to raise window: {}", title) | ||||
|     } | ||||
|  | ||||
|     counter += 1; | ||||
|     tokio::time::sleep(Duration::from_millis(100)).await; | ||||
|   } | ||||
| } | ||||
|  | ||||
| async fn wmctrl_try_raise_window(title: &str) -> anyhow::Result<ExitStatus> { | ||||
|   let exit_status = Command::new("wmctrl") | ||||
|     .arg("-F") | ||||
|     .arg("-a") | ||||
|     .arg(title) | ||||
|     .spawn()? | ||||
|     .wait() | ||||
|     .await?; | ||||
|  | ||||
|   Ok(exit_status) | ||||
| } | ||||
|  | ||||
| fn hide_menu(menu_handle: MenuHandle) { | ||||
|   tokio::spawn(async move { | ||||
|     loop { | ||||
|       let menu_visible = menu_handle.is_visible().unwrap_or(false); | ||||
|  | ||||
|       if !menu_visible { | ||||
|         break; | ||||
|       } | ||||
|  | ||||
|       if menu_visible { | ||||
|         let _ = menu_handle.hide(); | ||||
|         tokio::time::sleep(Duration::from_millis(10)).await; | ||||
|       } | ||||
|     } | ||||
|   }); | ||||
| } | ||||
| @@ -1,6 +0,0 @@ | ||||
| use roxmltree::Document; | ||||
|  | ||||
| pub(crate) fn get_child_text(doc: &Document, name: &str) -> Option<String> { | ||||
|   let node = doc.descendants().find(|n| n.has_tag_name(name))?; | ||||
|   node.text().map(|s| s.to_string()) | ||||
| } | ||||
| @@ -1,22 +0,0 @@ | ||||
| <?xml version="1.0" encoding="UTF-8"?> | ||||
| <prelogin-response> | ||||
|     <status>Success</status> | ||||
|     <ccusername></ccusername> | ||||
|     <autosubmit>false</autosubmit> | ||||
|     <msg></msg> | ||||
|     <newmsg></newmsg> | ||||
|     <authentication-message>Enter login credentials</authentication-message> | ||||
|     <username-label>Username</username-label> | ||||
|     <password-label>Password</password-label> | ||||
|     <panos-version>1</panos-version> | ||||
|     <saml-default-browser>yes</saml-default-browser> | ||||
|  | ||||
|     <cas-auth></cas-auth> | ||||
|     <saml-auth-status>0</saml-auth-status> | ||||
|     <saml-auth-method>REDIRECT</saml-auth-method> | ||||
|     <saml-request-timeout>600</saml-request-timeout> | ||||
|     <saml-request-id>0</saml-request-id> | ||||
|     <saml-request>U0FNTFJlcXVlc3Q9eHh4</saml-request> | ||||
|     <auth-api>no</auth-api> | ||||
|     <region>CN</region> | ||||
| </prelogin-response> | ||||
| @@ -1,15 +0,0 @@ | ||||
| <?xml version="1.0" encoding="UTF-8"?> | ||||
| <prelogin-response> | ||||
|     <status>Success</status> | ||||
|     <ccusername></ccusername> | ||||
|     <autosubmit>false</autosubmit> | ||||
|     <msg></msg> | ||||
|     <newmsg></newmsg> | ||||
|     <authentication-message>Enter login credentials</authentication-message> | ||||
|     <username-label>Username</username-label> | ||||
|     <password-label>Password</password-label> | ||||
|     <panos-version>1</panos-version> | ||||
|     <saml-default-browser>yes</saml-default-browser> | ||||
|     <auth-api>no</auth-api> | ||||
|     <region>US</region> | ||||
| </prelogin-response> | ||||
| @@ -1,13 +0,0 @@ | ||||
| [package] | ||||
| name = "openconnect" | ||||
| version.workspace = true | ||||
| edition.workspace = true | ||||
| license.workspace = true | ||||
| links = "openconnect" | ||||
|  | ||||
| [dependencies] | ||||
| log.workspace = true | ||||
| is_executable.workspace = true | ||||
|  | ||||
| [build-dependencies] | ||||
| cc = "1" | ||||
| @@ -1,12 +0,0 @@ | ||||
| fn main() { | ||||
|   // Link to the native openconnect library | ||||
|   println!("cargo:rustc-link-lib=openconnect"); | ||||
|   println!("cargo:rerun-if-changed=src/ffi/vpn.c"); | ||||
|   println!("cargo:rerun-if-changed=src/ffi/vpn.h"); | ||||
|  | ||||
|   // Compile the vpn.c file | ||||
|   cc::Build::new() | ||||
|     .file("src/ffi/vpn.c") | ||||
|     .include("src/ffi") | ||||
|     .compile("vpn"); | ||||
| } | ||||
| @@ -1,71 +0,0 @@ | ||||
| use crate::Vpn; | ||||
| use log::{debug, info, trace, warn}; | ||||
| use std::ffi::{c_char, c_int, c_void}; | ||||
|  | ||||
| #[repr(C)] | ||||
| #[derive(Debug)] | ||||
| pub(crate) struct ConnectOptions { | ||||
|   pub user_data: *mut c_void, | ||||
|  | ||||
|   pub server: *const c_char, | ||||
|   pub cookie: *const c_char, | ||||
|   pub user_agent: *const c_char, | ||||
|  | ||||
|   pub script: *const c_char, | ||||
|   pub os: *const c_char, | ||||
|   pub certificate: *const c_char, | ||||
|   pub servercert: *const c_char, | ||||
| } | ||||
|  | ||||
| #[link(name = "vpn")] | ||||
| extern "C" { | ||||
|   #[link_name = "vpn_connect"] | ||||
|   fn vpn_connect( | ||||
|     options: *const ConnectOptions, | ||||
|     callback: extern "C" fn(i32, *mut c_void), | ||||
|   ) -> c_int; | ||||
|  | ||||
|   #[link_name = "vpn_disconnect"] | ||||
|   fn vpn_disconnect(); | ||||
| } | ||||
|  | ||||
| pub(crate) fn connect(options: &ConnectOptions) -> i32 { | ||||
|   unsafe { vpn_connect(options, on_vpn_connected) } | ||||
| } | ||||
|  | ||||
| pub(crate) fn disconnect() { | ||||
|   unsafe { vpn_disconnect() } | ||||
| } | ||||
|  | ||||
| #[no_mangle] | ||||
| extern "C" fn on_vpn_connected(pipe_fd: i32, vpn: *mut c_void) { | ||||
|   let vpn = unsafe { &*(vpn as *const Vpn) }; | ||||
|   vpn.on_connected(pipe_fd); | ||||
| } | ||||
|  | ||||
| // Logger used in the C code. | ||||
| // level: 0 = error, 1 = info, 2 = debug, 3 = trace | ||||
| // map the error level log in openconnect to the warning level | ||||
| #[no_mangle] | ||||
| extern "C" fn vpn_log(level: i32, message: *const c_char) { | ||||
|   let message = unsafe { std::ffi::CStr::from_ptr(message) }; | ||||
|   let message = message.to_str().unwrap_or("Invalid log message"); | ||||
|   // Strip the trailing newline | ||||
|   let message = message.trim_end_matches('\n'); | ||||
|  | ||||
|   if level == 0 { | ||||
|     warn!("{}", message); | ||||
|   } else if level == 1 { | ||||
|     info!("{}", message); | ||||
|   } else if level == 2 { | ||||
|     debug!("{}", message); | ||||
|   } else if level == 3 { | ||||
|     trace!("{}", message); | ||||
|   } else { | ||||
|     warn!( | ||||
|       "Unknown log level: {}, enable DEBUG log level to see more details", | ||||
|       level | ||||
|     ); | ||||
|     debug!("{}", message); | ||||
|   } | ||||
| } | ||||
| @@ -1,5 +0,0 @@ | ||||
| mod ffi; | ||||
| mod vpn; | ||||
| mod vpnc_script; | ||||
|  | ||||
| pub use vpn::*; | ||||
| @@ -1,131 +0,0 @@ | ||||
| use std::{ | ||||
|   ffi::{c_char, CString}, | ||||
|   sync::{Arc, RwLock}, | ||||
| }; | ||||
|  | ||||
| use log::info; | ||||
|  | ||||
| use crate::{ffi, vpnc_script::find_default_vpnc_script}; | ||||
|  | ||||
| type OnConnectedCallback = Arc<RwLock<Option<Box<dyn FnOnce() + 'static + Send + Sync>>>>; | ||||
|  | ||||
| pub struct Vpn { | ||||
|   server: CString, | ||||
|   cookie: CString, | ||||
|   user_agent: CString, | ||||
|   script: CString, | ||||
|   os: CString, | ||||
|   certificate: Option<CString>, | ||||
|   servercert: Option<CString>, | ||||
|  | ||||
|   callback: OnConnectedCallback, | ||||
| } | ||||
|  | ||||
| impl Vpn { | ||||
|   pub fn builder(server: &str, cookie: &str) -> VpnBuilder { | ||||
|     VpnBuilder::new(server, cookie) | ||||
|   } | ||||
|  | ||||
|   pub fn connect(&self, on_connected: impl FnOnce() + 'static + Send + Sync) -> i32 { | ||||
|     self | ||||
|       .callback | ||||
|       .write() | ||||
|       .unwrap() | ||||
|       .replace(Box::new(on_connected)); | ||||
|     let options = self.build_connect_options(); | ||||
|  | ||||
|     ffi::connect(&options) | ||||
|   } | ||||
|  | ||||
|   pub(crate) fn on_connected(&self, pipe_fd: i32) { | ||||
|     info!("Connected to VPN, pipe_fd: {}", pipe_fd); | ||||
|  | ||||
|     if let Some(callback) = self.callback.write().unwrap().take() { | ||||
|       callback(); | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub fn disconnect(&self) { | ||||
|     ffi::disconnect(); | ||||
|   } | ||||
|  | ||||
|   fn build_connect_options(&self) -> ffi::ConnectOptions { | ||||
|     ffi::ConnectOptions { | ||||
|       user_data: self as *const _ as *mut _, | ||||
|  | ||||
|       server: self.server.as_ptr(), | ||||
|       cookie: self.cookie.as_ptr(), | ||||
|       user_agent: self.user_agent.as_ptr(), | ||||
|       script: self.script.as_ptr(), | ||||
|       os: self.os.as_ptr(), | ||||
|       certificate: Self::option_to_ptr(&self.certificate), | ||||
|       servercert: Self::option_to_ptr(&self.servercert), | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   fn option_to_ptr(option: &Option<CString>) -> *const c_char { | ||||
|     match option { | ||||
|       Some(value) => value.as_ptr(), | ||||
|       None => std::ptr::null(), | ||||
|     } | ||||
|   } | ||||
| } | ||||
|  | ||||
| pub struct VpnBuilder { | ||||
|   server: String, | ||||
|   cookie: String, | ||||
|   user_agent: Option<String>, | ||||
|   script: Option<String>, | ||||
|   os: Option<String>, | ||||
| } | ||||
|  | ||||
| impl VpnBuilder { | ||||
|   fn new(server: &str, cookie: &str) -> Self { | ||||
|     Self { | ||||
|       server: server.to_string(), | ||||
|       cookie: cookie.to_string(), | ||||
|       user_agent: None, | ||||
|       script: None, | ||||
|       os: None, | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   pub fn user_agent<T: Into<Option<String>>>(mut self, user_agent: T) -> Self { | ||||
|     self.user_agent = user_agent.into(); | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn script<T: Into<Option<String>>>(mut self, script: T) -> Self { | ||||
|     self.script = script.into(); | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn os<T: Into<Option<String>>>(mut self, os: T) -> Self { | ||||
|     self.os = os.into(); | ||||
|     self | ||||
|   } | ||||
|  | ||||
|   pub fn build(self) -> Vpn { | ||||
|     let user_agent = self.user_agent.unwrap_or_default(); | ||||
|     let script = self | ||||
|       .script | ||||
|       .or_else(find_default_vpnc_script) | ||||
|       .unwrap_or_default(); | ||||
|     let os = self.os.unwrap_or("linux".to_string()); | ||||
|  | ||||
|     Vpn { | ||||
|       server: Self::to_cstring(&self.server), | ||||
|       cookie: Self::to_cstring(&self.cookie), | ||||
|       user_agent: Self::to_cstring(&user_agent), | ||||
|       script: Self::to_cstring(&script), | ||||
|       os: Self::to_cstring(&os), | ||||
|       certificate: None, | ||||
|       servercert: None, | ||||
|       callback: Default::default(), | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   fn to_cstring(value: &str) -> CString { | ||||
|     CString::new(value.to_string()).expect("Failed to convert to CString") | ||||
|   } | ||||
| } | ||||
| @@ -1,23 +0,0 @@ | ||||
| use is_executable::IsExecutable; | ||||
| use std::path::Path; | ||||
|  | ||||
| const VPNC_SCRIPT_LOCATIONS: [&str; 5] = [ | ||||
|   "/usr/local/share/vpnc-scripts/vpnc-script", | ||||
|   "/usr/local/sbin/vpnc-script", | ||||
|   "/usr/share/vpnc-scripts/vpnc-script", | ||||
|   "/usr/sbin/vpnc-script", | ||||
|   "/etc/vpnc/vpnc-script", | ||||
| ]; | ||||
|  | ||||
| pub(crate) fn find_default_vpnc_script() -> Option<String> { | ||||
|   for location in VPNC_SCRIPT_LOCATIONS.iter() { | ||||
|     let path = Path::new(location); | ||||
|     if path.is_executable() { | ||||
|       return Some(location.to_string()); | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   log::warn!("vpnc-script not found"); | ||||
|  | ||||
|   None | ||||
| } | ||||
							
								
								
									
										1
									
								
								gpclient/.gitignore
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										1
									
								
								gpclient/.gitignore
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @@ -0,0 +1 @@ | ||||
| /target | ||||
							
								
								
									
										10
									
								
								gpclient/Cargo.toml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										10
									
								
								gpclient/Cargo.toml
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,10 @@ | ||||
| [package] | ||||
| name = "gpclient" | ||||
| version = "0.1.0" | ||||
| edition = "2021" | ||||
|  | ||||
| # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | ||||
|  | ||||
| [dependencies] | ||||
| gpcommon = { path = "../gpcommon" } | ||||
| tokio = { version = "1.0", features = ["full"] } | ||||
							
								
								
									
										25
									
								
								gpclient/src/main.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										25
									
								
								gpclient/src/main.rs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,25 @@ | ||||
| use gpcommon::{Client, SOCKET_PATH}; | ||||
| use tokio::{io::AsyncReadExt, net::UnixStream, sync::mpsc}; | ||||
|  | ||||
| #[tokio::main] | ||||
| async fn main() { | ||||
|     // let mut stream = UnixStream::connect(SOCKET_PATH).await.unwrap(); | ||||
|  | ||||
|     // let mut buf = [0u8; 34]; | ||||
|     // let _ = stream.read(&mut buf).await.unwrap(); | ||||
|  | ||||
|     // // The first two bytes are the port number, the rest is the AES key | ||||
|     // let http_port = u16::from_be_bytes([buf[0], buf[1]]); | ||||
|     // let aes_key = &buf[2..]; | ||||
|  | ||||
|     // println!("http_port: {http_port}"); | ||||
|     // println!("aes_key: {aes_key:?}"); | ||||
|     let (output_tx, mut output_rx) = mpsc::channel::<String>(32); | ||||
|     let client = Client::default(); | ||||
|  | ||||
|     tokio::select! { | ||||
|         _ = client.run() => { | ||||
|             println!("Client finished"); | ||||
|         } | ||||
|     } | ||||
| } | ||||
							
								
								
									
										2
									
								
								gpcommon/.gitignore
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										2
									
								
								gpcommon/.gitignore
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @@ -0,0 +1,2 @@ | ||||
| /target | ||||
| /Cargo.lock | ||||
							
								
								
									
										27
									
								
								gpcommon/Cargo.toml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										27
									
								
								gpcommon/Cargo.toml
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,27 @@ | ||||
| [package] | ||||
| name = "gpcommon" | ||||
| version = "0.1.0" | ||||
| edition = "2021" | ||||
|  | ||||
| # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | ||||
|  | ||||
| [dependencies] | ||||
| tokio = { version = "1.14", features = ["full"] } | ||||
| tokio-util = "0.7" | ||||
| thiserror = "1.0" | ||||
| serde = { version = "1.0", features = ["derive"] } | ||||
| bytes = "1.0" | ||||
| serde_json = "1.0" | ||||
| async-trait = "0.1" | ||||
| ring = "0.16" | ||||
| data-encoding = "2.3" | ||||
| log = "0.4" | ||||
| is_executable = "1.0" | ||||
| configparser = "3.0" | ||||
| shlex = "1.0" | ||||
| anyhow = "1.0" | ||||
| tempfile = "3.8" | ||||
| lexopt = "0.3.0" | ||||
|  | ||||
| [build-dependencies] | ||||
| cc = "1.0" | ||||
							
								
								
									
										12
									
								
								gpcommon/build.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										12
									
								
								gpcommon/build.rs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,12 @@ | ||||
| fn main() { | ||||
|     // Link to the native openconnect library | ||||
|     println!("cargo:rustc-link-lib=openconnect"); | ||||
|     println!("cargo:rerun-if-changed=src/vpn/vpn.c"); | ||||
|     println!("cargo:rerun-if-changed=src/vpn/vpn.h"); | ||||
|  | ||||
|     // Compile the vpn.c file | ||||
|     cc::Build::new() | ||||
|         .file("src/vpn/vpn.c") | ||||
|         .include("src/vpn") | ||||
|         .compile("vpn"); | ||||
| } | ||||
							
								
								
									
										286
									
								
								gpcommon/src/client.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										286
									
								
								gpcommon/src/client.rs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,286 @@ | ||||
| use crate::cmd::{Connect, Disconnect, GetStatus}; | ||||
| use crate::reader::Reader; | ||||
| use crate::request::CommandPayload; | ||||
| use crate::response::ResponseData; | ||||
| use crate::writer::Writer; | ||||
| use crate::RequestPool; | ||||
| use crate::Response; | ||||
| use crate::SOCKET_PATH; | ||||
| use crate::{Request, VpnStatus}; | ||||
| use log::{debug, info, warn}; | ||||
| use serde::{Deserialize, Serialize}; | ||||
| use std::fmt::Display; | ||||
| use std::sync::Arc; | ||||
| use tokio::io::{self, ReadHalf, WriteHalf}; | ||||
| use tokio::net::UnixStream; | ||||
| use tokio::sync::{mpsc, Mutex, RwLock}; | ||||
| use tokio_util::sync::CancellationToken; | ||||
|  | ||||
| #[derive(Debug)] | ||||
| enum ServiceEvent { | ||||
|     Online, | ||||
|     Response(Response), | ||||
|     Offline, | ||||
| } | ||||
|  | ||||
| impl From<Response> for ServiceEvent { | ||||
|     fn from(response: Response) -> Self { | ||||
|         Self::Response(response) | ||||
|     } | ||||
| } | ||||
|  | ||||
| #[derive(Debug)] | ||||
| pub enum ClientStatus { | ||||
|     Vpn(VpnStatus), | ||||
|     Service(bool), | ||||
| } | ||||
|  | ||||
| #[derive(Debug)] | ||||
| pub struct Client { | ||||
|     // pool of requests that are waiting for responses | ||||
|     request_pool: Arc<RequestPool>, | ||||
|     // tx for sending requests to the channel | ||||
|     request_tx: mpsc::Sender<Request>, | ||||
|     // rx for receiving requests from the channel | ||||
|     request_rx: Arc<Mutex<mpsc::Receiver<Request>>>, | ||||
|     // tx for sending responses to the channel | ||||
|     service_event_tx: mpsc::Sender<ServiceEvent>, | ||||
|     // rx for receiving responses from the channel | ||||
|     service_event_rx: Arc<Mutex<mpsc::Receiver<ServiceEvent>>>, | ||||
|     is_online: Arc<RwLock<bool>>, | ||||
| } | ||||
|  | ||||
| #[derive(Debug, Serialize, Deserialize)] | ||||
| pub struct ServerApiError { | ||||
|     pub message: String, | ||||
| } | ||||
|  | ||||
| impl Display for ServerApiError { | ||||
|     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||||
|         write!(f, "{message}", message = self.message) | ||||
|     } | ||||
| } | ||||
|  | ||||
| impl From<String> for ServerApiError { | ||||
|     fn from(message: String) -> Self { | ||||
|         Self { message } | ||||
|     } | ||||
| } | ||||
|  | ||||
| impl From<&str> for ServerApiError { | ||||
|     fn from(message: &str) -> Self { | ||||
|         Self { | ||||
|             message: message.to_string(), | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
| impl Default for Client { | ||||
|     fn default() -> Self { | ||||
|         let (request_tx, request_rx) = mpsc::channel::<Request>(32); | ||||
|         let (service_event_tx, server_event_rx) = mpsc::channel::<ServiceEvent>(32); | ||||
|  | ||||
|         Self { | ||||
|             request_pool: Default::default(), | ||||
|             request_tx, | ||||
|             request_rx: Arc::new(Mutex::new(request_rx)), | ||||
|             service_event_tx, | ||||
|             service_event_rx: Arc::new(Mutex::new(server_event_rx)), | ||||
|             is_online: Default::default(), | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
| impl Client { | ||||
|     pub async fn is_online(&self) -> bool { | ||||
|         *self.is_online.read().await | ||||
|     } | ||||
|  | ||||
|     pub fn subscribe_status(&self, callback: impl Fn(ClientStatus) + Send + Sync + 'static) { | ||||
|         let service_event_rx = self.service_event_rx.clone(); | ||||
|  | ||||
|         tokio::spawn(async move { | ||||
|             loop { | ||||
|                 let mut server_event_rx = service_event_rx.lock().await; | ||||
|                 if let Some(server_event) = server_event_rx.recv().await { | ||||
|                     match server_event { | ||||
|                         ServiceEvent::Online => { | ||||
|                             callback(ClientStatus::Service(true)); | ||||
|                         } | ||||
|                         ServiceEvent::Offline => { | ||||
|                             callback(ClientStatus::Service(false)); | ||||
|                         } | ||||
|                         ServiceEvent::Response(response) => { | ||||
|                             if let ResponseData::Status(vpn_status) = response.data() { | ||||
|                                 callback(ClientStatus::Vpn(vpn_status)); | ||||
|                             } | ||||
|                         } | ||||
|                     } | ||||
|                 } | ||||
|             } | ||||
|         }); | ||||
|     } | ||||
|  | ||||
|     pub async fn run(&self) { | ||||
|         info!("Connecting to the background service..."); | ||||
|  | ||||
|         // TODO exit the loop properly | ||||
|         loop { | ||||
|             match self.connect_to_server().await { | ||||
|                 Ok(_) => { | ||||
|                     debug!("Disconnected from server, reconnecting..."); | ||||
|                 } | ||||
|                 Err(err) => { | ||||
|                     debug!("Error connecting to server, retrying, error: {:?}", err) | ||||
|                 } | ||||
|             } | ||||
|  | ||||
|             // wait for a second before trying to reconnect | ||||
|             tokio::time::sleep(std::time::Duration::from_secs(1)).await; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     async fn connect_to_server(&self) -> Result<(), Box<dyn std::error::Error>> { | ||||
|         let stream = UnixStream::connect(SOCKET_PATH).await?; | ||||
|         let (read_stream, write_stream) = io::split(stream); | ||||
|         let cancel_token = CancellationToken::new(); | ||||
|  | ||||
|         let read_handle = tokio::spawn(handle_read( | ||||
|             read_stream, | ||||
|             self.request_pool.clone(), | ||||
|             self.service_event_tx.clone(), | ||||
|             cancel_token.clone(), | ||||
|         )); | ||||
|  | ||||
|         let write_handle = tokio::spawn(handle_write( | ||||
|             write_stream, | ||||
|             self.request_rx.clone(), | ||||
|             cancel_token, | ||||
|         )); | ||||
|  | ||||
|         *self.is_online.write().await = true; | ||||
|         info!("Connected to the background service"); | ||||
|         if let Err(err) = self.service_event_tx.send(ServiceEvent::Online).await { | ||||
|             warn!("Error sending online event to the channel: {}", err); | ||||
|         } | ||||
|  | ||||
|         let _ = tokio::join!(read_handle, write_handle); | ||||
|         *self.is_online.write().await = false; | ||||
|  | ||||
|         // TODO connection was lost, cleanup the request pool | ||||
|  | ||||
|         Ok(()) | ||||
|     } | ||||
|  | ||||
|     async fn send_command<T: TryFrom<ResponseData>>( | ||||
|         &self, | ||||
|         payload: CommandPayload, | ||||
|     ) -> Result<T, ServerApiError> { | ||||
|         if !*self.is_online.read().await { | ||||
|             return Err("Background service is not running".into()); | ||||
|         } | ||||
|  | ||||
|         let (request, response_rx) = self.request_pool.create_request(payload).await; | ||||
|  | ||||
|         if let Err(err) = self.request_tx.send(request).await { | ||||
|             return Err(format!("Error sending request to the channel: {}", err).into()); | ||||
|         } | ||||
|  | ||||
|         response_rx | ||||
|             .await | ||||
|             .map_err(|_| "Error receiving response from the channel".into()) | ||||
|             .and_then(|response| { | ||||
|                 if response.success() { | ||||
|                     response | ||||
|                         .data() | ||||
|                         .try_into() | ||||
|                         .map_err(|_| "Error parsing response data".into()) | ||||
|                 } else { | ||||
|                     Err(response.message().into()) | ||||
|                 } | ||||
|             }) | ||||
|     } | ||||
|  | ||||
|     pub async fn connect( | ||||
|         &self, | ||||
|         server: String, | ||||
|         cookie: String, | ||||
|         user_agent: String, | ||||
|     ) -> Result<(), ServerApiError> { | ||||
|         self.send_command(Connect::new(server, cookie, user_agent).into()) | ||||
|             .await | ||||
|     } | ||||
|  | ||||
|     pub async fn disconnect(&self) -> Result<(), ServerApiError> { | ||||
|         self.send_command(Disconnect.into()).await | ||||
|     } | ||||
|  | ||||
|     pub async fn status(&self) -> Result<VpnStatus, ServerApiError> { | ||||
|         self.send_command(GetStatus.into()).await | ||||
|     } | ||||
| } | ||||
|  | ||||
| async fn handle_read( | ||||
|     read_stream: ReadHalf<UnixStream>, | ||||
|     request_pool: Arc<RequestPool>, | ||||
|     service_event_tx: mpsc::Sender<ServiceEvent>, | ||||
|     cancel_token: CancellationToken, | ||||
| ) { | ||||
|     let mut reader: Reader = read_stream.into(); | ||||
|  | ||||
|     loop { | ||||
|         match reader.read_multiple::<Response>().await { | ||||
|             Ok(responses) => { | ||||
|                 for response in responses { | ||||
|                     match response.request_id() { | ||||
|                         Some(id) => request_pool.complete_request(id, response).await, | ||||
|                         None => { | ||||
|                             if let Err(err) = service_event_tx.send(response.into()).await { | ||||
|                                 warn!("Error sending response to output channel: {}", err); | ||||
|                             } | ||||
|                         } | ||||
|                     } | ||||
|                 } | ||||
|             } | ||||
|             Err(err) if err.kind() == io::ErrorKind::ConnectionAborted => { | ||||
|                 warn!("Disconnected from the background service"); | ||||
|                 if let Err(err) = service_event_tx.send(ServiceEvent::Offline).await { | ||||
|                     warn!( | ||||
|                         "Error sending server disconnected event to channel: {}", | ||||
|                         err | ||||
|                     ); | ||||
|                 } | ||||
|                 cancel_token.cancel(); | ||||
|                 break; | ||||
|             } | ||||
|             Err(err) => { | ||||
|                 warn!("Error reading from server: {}", err); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
| async fn handle_write( | ||||
|     write_stream: WriteHalf<UnixStream>, | ||||
|     request_rx: Arc<Mutex<mpsc::Receiver<Request>>>, | ||||
|     cancel_token: CancellationToken, | ||||
| ) { | ||||
|     let mut writer: Writer = write_stream.into(); | ||||
|     loop { | ||||
|         let mut request_rx = request_rx.lock().await; | ||||
|         tokio::select! { | ||||
|             Some(request) = request_rx.recv() => { | ||||
|                 if let Err(err) = writer.write(&request).await { | ||||
|                     warn!("Error writing to server: {}", err); | ||||
|                 } | ||||
|             } | ||||
|             _ = cancel_token.cancelled() => { | ||||
|                 info!("The read loop has been cancelled, exiting the write loop"); | ||||
|                 break; | ||||
|             } | ||||
|             else => { | ||||
|                 warn!("Error reading command from channel"); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| } | ||||
							
								
								
									
										39
									
								
								gpcommon/src/cmd/connect.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										39
									
								
								gpcommon/src/cmd/connect.rs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,39 @@ | ||||
| use super::{Command, CommandContext, CommandError}; | ||||
| use crate::{ResponseData, VpnStatus}; | ||||
| use async_trait::async_trait; | ||||
| use serde::{Deserialize, Serialize}; | ||||
|  | ||||
| #[derive(Debug, Serialize, Deserialize, Clone)] | ||||
| pub struct Connect { | ||||
|     server: String, | ||||
|     cookie: String, | ||||
|     user_agent: String, | ||||
| } | ||||
|  | ||||
| impl Connect { | ||||
|     pub fn new(server: String, cookie: String, user_agent: String) -> Self { | ||||
|         Self { | ||||
|             server, | ||||
|             cookie, | ||||
|             user_agent, | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
| #[async_trait] | ||||
| impl Command for Connect { | ||||
|     async fn handle(&self, context: CommandContext) -> Result<ResponseData, CommandError> { | ||||
|         let vpn = context.server_context.vpn(); | ||||
|         let status = vpn.status().await; | ||||
|  | ||||
|         if status != VpnStatus::Disconnected { | ||||
|             return Err(format!("VPN is already in state: {:?}", status).into()); | ||||
|         } | ||||
|  | ||||
|         if let Err(err) = vpn.connect(&self.server, &self.cookie, &self.user_agent).await { | ||||
|             return Err(err.to_string().into()); | ||||
|         } | ||||
|  | ||||
|         Ok(ResponseData::Empty) | ||||
|     } | ||||
| } | ||||
							
								
								
									
										15
									
								
								gpcommon/src/cmd/disconnect.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										15
									
								
								gpcommon/src/cmd/disconnect.rs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,15 @@ | ||||
| use super::{Command, CommandContext, CommandError}; | ||||
| use crate::ResponseData; | ||||
| use async_trait::async_trait; | ||||
| use serde::{Deserialize, Serialize}; | ||||
|  | ||||
| #[derive(Debug, Serialize, Deserialize, Clone)] | ||||
| pub struct Disconnect; | ||||
|  | ||||
| #[async_trait] | ||||
| impl Command for Disconnect { | ||||
|     async fn handle(&self, context: CommandContext) -> Result<ResponseData, CommandError> { | ||||
|         context.server_context.vpn().disconnect().await; | ||||
|         Ok(ResponseData::Empty) | ||||
|     } | ||||
| } | ||||
							
								
								
									
										54
									
								
								gpcommon/src/cmd/mod.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										54
									
								
								gpcommon/src/cmd/mod.rs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,54 @@ | ||||
| use crate::{response::ResponseData, server::ServerContext}; | ||||
| use async_trait::async_trait; | ||||
| use core::fmt::Debug; | ||||
| use std::{ | ||||
|     fmt::{self, Display}, | ||||
|     sync::Arc, | ||||
| }; | ||||
|  | ||||
| mod connect; | ||||
| mod disconnect; | ||||
| mod status; | ||||
|  | ||||
| pub use connect::Connect; | ||||
| pub use disconnect::Disconnect; | ||||
| pub use status::GetStatus; | ||||
|  | ||||
| #[derive(Debug)] | ||||
| pub(crate) struct CommandContext { | ||||
|     server_context: Arc<ServerContext>, | ||||
| } | ||||
|  | ||||
| impl From<Arc<ServerContext>> for CommandContext { | ||||
|     fn from(server_context: Arc<ServerContext>) -> Self { | ||||
|         Self { server_context } | ||||
|     } | ||||
| } | ||||
|  | ||||
| #[derive(Debug)] | ||||
| pub(crate) struct CommandError { | ||||
|     message: String, | ||||
| } | ||||
|  | ||||
| impl From<String> for CommandError { | ||||
|     fn from(message: String) -> Self { | ||||
|         Self { message } | ||||
|     } | ||||
| } | ||||
|  | ||||
| impl Display for CommandError { | ||||
|     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||||
|         write!(f, "CommandError {:#?}", self.message) | ||||
|     } | ||||
| } | ||||
|  | ||||
| #[async_trait] | ||||
| pub(crate) trait Command: Send + Sync { | ||||
|     async fn handle(&self, context: CommandContext) -> Result<ResponseData, CommandError>; | ||||
| } | ||||
|  | ||||
| impl Debug for dyn Command { | ||||
|     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||||
|         write!(f, "Command") | ||||
|     } | ||||
| } | ||||
							
								
								
									
										16
									
								
								gpcommon/src/cmd/status.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										16
									
								
								gpcommon/src/cmd/status.rs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,16 @@ | ||||
| use super::{Command, CommandContext, CommandError}; | ||||
| use crate::ResponseData; | ||||
| use async_trait::async_trait; | ||||
| use serde::{Deserialize, Serialize}; | ||||
|  | ||||
| #[derive(Debug, Serialize, Deserialize, Clone)] | ||||
| pub struct GetStatus; | ||||
|  | ||||
| #[async_trait] | ||||
| impl Command for GetStatus { | ||||
|     async fn handle(&self, context: CommandContext) -> Result<ResponseData, CommandError> { | ||||
|         let status = context.server_context.vpn().status().await; | ||||
|  | ||||
|         Ok(ResponseData::Status(status)) | ||||
|     } | ||||
| } | ||||
							
								
								
									
										179
									
								
								gpcommon/src/connection.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										179
									
								
								gpcommon/src/connection.rs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,179 @@ | ||||
| use crate::request::Request; | ||||
| use crate::server::ServerContext; | ||||
| use crate::Reader; | ||||
| use crate::Response; | ||||
| use crate::ResponseData; | ||||
| use crate::VpnStatus; | ||||
| use crate::Writer; | ||||
| use log::{debug, info, warn}; | ||||
| use std::sync::Arc; | ||||
| use tokio::io::{self, ReadHalf, WriteHalf}; | ||||
| use tokio::net::UnixStream; | ||||
| use tokio::sync::{mpsc, watch}; | ||||
| use tokio_util::sync::CancellationToken; | ||||
|  | ||||
| async fn handle_read( | ||||
|     read_stream: ReadHalf<UnixStream>, | ||||
|     server_context: Arc<ServerContext>, | ||||
|     response_tx: mpsc::Sender<Response>, | ||||
|     peer_pid: Option<i32>, | ||||
|     cancel_token: CancellationToken, | ||||
| ) { | ||||
|     let mut reader: Reader = read_stream.into(); | ||||
|     let mut authenticated: Option<bool> = None; | ||||
|  | ||||
|     loop { | ||||
|         match reader.read_multiple::<Request>().await { | ||||
|             Ok(requests) => { | ||||
|                 if authenticated.is_none() { | ||||
|                     authenticated = Some(authenticate(peer_pid)); | ||||
|                 } | ||||
|                 if !authenticated.unwrap_or(false) { | ||||
|                     warn!("Client not authenticated, closing connection"); | ||||
|                     cancel_token.cancel(); | ||||
|                     break; | ||||
|                 } | ||||
|  | ||||
|                 for request in requests { | ||||
|                     debug!("Received client request: {:?}", request); | ||||
|  | ||||
|                     let command = request.command(); | ||||
|                     let context = server_context.clone().into(); | ||||
|  | ||||
|                     let mut response = match command.handle(context).await { | ||||
|                         Ok(data) => Response::from(data), | ||||
|                         Err(err) => Response::from(err.to_string()), | ||||
|                     }; | ||||
|                     response.set_request_id(request.id()); | ||||
|  | ||||
|                     let _ = response_tx.send(response).await; | ||||
|                 } | ||||
|             } | ||||
|  | ||||
|             Err(err) if err.kind() == io::ErrorKind::ConnectionAborted => { | ||||
|                 info!("Client disconnected"); | ||||
|                 cancel_token.cancel(); | ||||
|                 break; | ||||
|             } | ||||
|  | ||||
|             Err(err) => { | ||||
|                 warn!("Error receiving request: {:?}", err); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
| async fn handle_write( | ||||
|     write_stream: WriteHalf<UnixStream>, | ||||
|     mut response_rx: mpsc::Receiver<Response>, | ||||
|     cancel_token: CancellationToken, | ||||
| ) { | ||||
|     let mut writer: Writer = write_stream.into(); | ||||
|  | ||||
|     loop { | ||||
|         tokio::select! { | ||||
|             Some(response) = response_rx.recv() => { | ||||
|                 debug!("Sending response: {:?}", response); | ||||
|                 if let Err(err) = writer.write(&response).await { | ||||
|                     warn!("Error sending response: {:?}", err); | ||||
|                 } | ||||
|             } | ||||
|             _ = cancel_token.cancelled() => { | ||||
|                 info!("Exiting the write loop"); | ||||
|                 break; | ||||
|             } | ||||
|             else => { | ||||
|                 warn!("Error receiving response from channel"); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
| async fn handle_status_change( | ||||
|     mut status_rx: watch::Receiver<VpnStatus>, | ||||
|     response_tx: mpsc::Sender<Response>, | ||||
|     cancel_token: CancellationToken, | ||||
| ) { | ||||
|     // Send the initial status | ||||
|     send_status(&status_rx, &response_tx).await; | ||||
|     debug!("Waiting for status change"); | ||||
|     let start_time = std::time::Instant::now(); | ||||
|  | ||||
|     loop { | ||||
|         tokio::select! { | ||||
|             _ = status_rx.changed() => { | ||||
|                 debug!("Status changed: {:?}", start_time.elapsed()); | ||||
|                 send_status(&status_rx, &response_tx).await; | ||||
|             } | ||||
|             _ = cancel_token.cancelled() => { | ||||
|                 info!("Exiting the status loop"); | ||||
|                 break; | ||||
|             } | ||||
|             else => { | ||||
|                 warn!("Error receiving status from channel"); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
| async fn send_status(status_rx: &watch::Receiver<VpnStatus>, response_tx: &mpsc::Sender<Response>) { | ||||
|     let status = *status_rx.borrow(); | ||||
|     if let Err(err) = response_tx | ||||
|         .send(Response::from(ResponseData::Status(status))) | ||||
|         .await | ||||
|     { | ||||
|         warn!("Error sending status: {:?}", err); | ||||
|     } | ||||
| } | ||||
|  | ||||
| pub(crate) async fn handle_connection(socket: UnixStream, context: Arc<ServerContext>) { | ||||
|     let peer_pid = peer_pid(&socket); | ||||
|     let (read_stream, write_stream) = io::split(socket); | ||||
|     let (response_tx, response_rx) = mpsc::channel::<Response>(32); | ||||
|     let cancel_token = CancellationToken::new(); | ||||
|     let status_rx = context.vpn().status_rx().await; | ||||
|  | ||||
|     // Read requests from the client | ||||
|     let read_handle = tokio::spawn(handle_read( | ||||
|         read_stream, | ||||
|         context.clone(), | ||||
|         response_tx.clone(), | ||||
|         peer_pid, | ||||
|         cancel_token.clone(), | ||||
|     )); | ||||
|  | ||||
|     // Write responses to the client | ||||
|     let write_handle = tokio::spawn(handle_write( | ||||
|         write_stream, | ||||
|         response_rx, | ||||
|         cancel_token.clone(), | ||||
|     )); | ||||
|  | ||||
|     // Watch for status changes | ||||
|     let status_handle = tokio::spawn(handle_status_change( | ||||
|         status_rx, | ||||
|         response_tx.clone(), | ||||
|         cancel_token, | ||||
|     )); | ||||
|  | ||||
|     let _ = tokio::join!(read_handle, write_handle, status_handle); | ||||
|  | ||||
|     debug!("Client connection closed"); | ||||
| } | ||||
|  | ||||
| fn peer_pid(socket: &UnixStream) -> Option<i32> { | ||||
|     match socket.peer_cred() { | ||||
|         Ok(ucred) => ucred.pid(), | ||||
|         Err(_) => None, | ||||
|     } | ||||
| } | ||||
|  | ||||
| // TODO - Implement authentication | ||||
| fn authenticate(peer_pid: Option<i32>) -> bool { | ||||
|     if let Some(pid) = peer_pid { | ||||
|         info!("Peer PID: {}", pid); | ||||
|         true | ||||
|     } else { | ||||
|         false | ||||
|     } | ||||
| } | ||||
							
								
								
									
										51
									
								
								gpcommon/src/lib.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										51
									
								
								gpcommon/src/lib.rs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,51 @@ | ||||
| use data_encoding::HEXUPPER; | ||||
| use ring::digest::{Context, SHA256}; | ||||
| use std::{ | ||||
|     fs::File, | ||||
|     io::{BufReader, Read}, | ||||
|     path::Path, | ||||
| }; | ||||
|  | ||||
| pub const SOCKET_PATH: &str = "/tmp/gpservice.sock"; | ||||
|  | ||||
| mod client; | ||||
| mod cmd; | ||||
| mod connection; | ||||
| mod reader; | ||||
| mod request; | ||||
| mod response; | ||||
| pub mod server; | ||||
| mod vpn; | ||||
| mod writer; | ||||
|  | ||||
| pub(crate) use request::Request; | ||||
| pub(crate) use request::RequestPool; | ||||
|  | ||||
| pub use response::Response; | ||||
| pub use response::ResponseData; | ||||
| pub use response::TryFromResponseDataError; | ||||
|  | ||||
| pub(crate) use reader::Reader; | ||||
| pub(crate) use writer::Writer; | ||||
|  | ||||
| pub use client::Client; | ||||
| pub use client::ServerApiError; | ||||
| pub use client::ClientStatus; | ||||
| pub use vpn::VpnStatus; | ||||
|  | ||||
| pub fn sha256_digest<P: AsRef<Path>>(file_path: P) -> Result<String, std::io::Error> { | ||||
|     let input = File::open(file_path)?; | ||||
|     let mut reader = BufReader::new(input); | ||||
|  | ||||
|     let mut context = Context::new(&SHA256); | ||||
|     let mut buffer = [0; 1024]; | ||||
|  | ||||
|     loop { | ||||
|         let count = reader.read(&mut buffer)?; | ||||
|         if count == 0 { | ||||
|             break; | ||||
|         } | ||||
|         context.update(&buffer[..count]); | ||||
|     } | ||||
|     Ok(HEXUPPER.encode(context.finish().as_ref())) | ||||
| } | ||||
							
								
								
									
										43
									
								
								gpcommon/src/reader.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										43
									
								
								gpcommon/src/reader.rs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,43 @@ | ||||
| use serde::Deserialize; | ||||
| use tokio::io::{self, AsyncReadExt, ReadHalf}; | ||||
| use tokio::net::UnixStream; | ||||
|  | ||||
| pub(crate) struct Reader { | ||||
|     stream: ReadHalf<UnixStream>, | ||||
| } | ||||
|  | ||||
| impl From<ReadHalf<UnixStream>> for Reader { | ||||
|     fn from(stream: ReadHalf<UnixStream>) -> Self { | ||||
|         Self { stream } | ||||
|     } | ||||
| } | ||||
|  | ||||
| impl Reader { | ||||
|     pub async fn read_multiple<T: for<'a> Deserialize<'a>>(&mut self) -> Result<Vec<T>, io::Error> { | ||||
|         let mut buffer = [0; 2048]; | ||||
|  | ||||
|         match self.stream.read(&mut buffer).await { | ||||
|             Ok(0) => Err(io::Error::new( | ||||
|                 io::ErrorKind::ConnectionAborted, | ||||
|                 "Peer disconnected", | ||||
|             )), | ||||
|             Ok(bytes_read) => { | ||||
|                 let response_str = String::from_utf8_lossy(&buffer[..bytes_read]); | ||||
|                 let responses: Vec<&str> = response_str.split("\n\n").collect(); | ||||
|                 let responses = responses | ||||
|                     .iter() | ||||
|                     .filter_map(|r| { | ||||
|                         if !r.is_empty() { | ||||
|                             serde_json::from_str(r).ok() | ||||
|                         } else { | ||||
|                             None | ||||
|                         } | ||||
|                     }) | ||||
|                     .collect::<Vec<T>>(); | ||||
|  | ||||
|                 Ok(responses) | ||||
|             } | ||||
|             Err(err) => Err(err), | ||||
|         } | ||||
|     } | ||||
| } | ||||
							
								
								
									
										105
									
								
								gpcommon/src/request.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										105
									
								
								gpcommon/src/request.rs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,105 @@ | ||||
| use crate::cmd::{Command, Connect, Disconnect, GetStatus}; | ||||
| use crate::Response; | ||||
| use serde::{Deserialize, Serialize}; | ||||
| use std::sync::Arc; | ||||
| use tokio::sync::{oneshot, RwLock}; | ||||
|  | ||||
| #[derive(Debug, Serialize, Deserialize)] | ||||
| pub(crate) struct Request { | ||||
|     id: u64, | ||||
|     payload: CommandPayload, | ||||
| } | ||||
|  | ||||
| impl Request { | ||||
|     fn new(id: u64, payload: CommandPayload) -> Self { | ||||
|         Self { id, payload } | ||||
|     } | ||||
|  | ||||
|     pub fn id(&self) -> u64 { | ||||
|         self.id | ||||
|     } | ||||
|  | ||||
|     pub fn command(&self) -> Box<dyn Command> { | ||||
|         match &self.payload { | ||||
|             CommandPayload::GetStatus(status) => Box::new(status.clone()), | ||||
|             CommandPayload::Connect(connect) => Box::new(connect.clone()), | ||||
|             CommandPayload::Disconnect(disconnect) => Box::new(disconnect.clone()), | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
| #[derive(Debug, Serialize, Deserialize)] | ||||
| pub(crate) enum CommandPayload { | ||||
|     GetStatus(GetStatus), | ||||
|     Connect(Connect), | ||||
|     Disconnect(Disconnect), | ||||
| } | ||||
|  | ||||
| impl From<GetStatus> for CommandPayload { | ||||
|     fn from(status: GetStatus) -> Self { | ||||
|         Self::GetStatus(status) | ||||
|     } | ||||
| } | ||||
|  | ||||
| impl From<Connect> for CommandPayload { | ||||
|     fn from(connect: Connect) -> Self { | ||||
|         Self::Connect(connect) | ||||
|     } | ||||
| } | ||||
|  | ||||
| impl From<Disconnect> for CommandPayload { | ||||
|     fn from(disconnect: Disconnect) -> Self { | ||||
|         Self::Disconnect(disconnect) | ||||
|     } | ||||
| } | ||||
|  | ||||
| #[derive(Debug)] | ||||
| struct RequestHandle { | ||||
|     id: u64, | ||||
|     response_tx: oneshot::Sender<Response>, | ||||
| } | ||||
|  | ||||
| #[derive(Debug, Default)] | ||||
| struct IdGenerator { | ||||
|     current_id: u64, | ||||
| } | ||||
|  | ||||
| impl IdGenerator { | ||||
|     fn next(&mut self) -> u64 { | ||||
|         let current_id = self.current_id; | ||||
|         self.current_id = self.current_id.wrapping_add(1); | ||||
|         current_id | ||||
|     } | ||||
| } | ||||
|  | ||||
| #[derive(Debug, Default)] | ||||
| pub(crate) struct RequestPool { | ||||
|     id_generator: Arc<RwLock<IdGenerator>>, | ||||
|     request_handles: Arc<RwLock<Vec<RequestHandle>>>, | ||||
| } | ||||
|  | ||||
| impl RequestPool { | ||||
|     pub async fn create_request( | ||||
|         &self, | ||||
|         payload: CommandPayload, | ||||
|     ) -> (Request, oneshot::Receiver<Response>) { | ||||
|         let id = self.id_generator.write().await.next(); | ||||
|         let (response_tx, response_rx) = oneshot::channel(); | ||||
|         let request_handle = RequestHandle { id, response_tx }; | ||||
|  | ||||
|         self.request_handles.write().await.push(request_handle); | ||||
|         (Request::new(id, payload), response_rx) | ||||
|     } | ||||
|  | ||||
|     pub async fn complete_request(&self, id: u64, response: Response) { | ||||
|         let mut request_handles = self.request_handles.write().await; | ||||
|         let request_handle = request_handles | ||||
|             .iter() | ||||
|             .position(|handle| handle.id == id) | ||||
|             .map(|index| request_handles.remove(index)); | ||||
|  | ||||
|         if let Some(request_handle) = request_handle { | ||||
|             let _ = request_handle.response_tx.send(response); | ||||
|         } | ||||
|     } | ||||
| } | ||||
							
								
								
									
										113
									
								
								gpcommon/src/response.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										113
									
								
								gpcommon/src/response.rs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,113 @@ | ||||
| use crate::vpn::VpnStatus; | ||||
| use serde::{Deserialize, Serialize}; | ||||
|  | ||||
| #[derive(Debug, Serialize, Deserialize, Clone)] | ||||
| pub struct Response { | ||||
|     request_id: Option<u64>, | ||||
|     success: bool, | ||||
|     message: String, | ||||
|     data: ResponseData, | ||||
| } | ||||
|  | ||||
| impl From<ResponseData> for Response { | ||||
|     fn from(data: ResponseData) -> Self { | ||||
|         Self { | ||||
|             request_id: None, | ||||
|             success: true, | ||||
|             message: String::from("Success"), | ||||
|             data, | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
| impl From<String> for Response { | ||||
|     fn from(message: String) -> Self { | ||||
|         Self { | ||||
|             request_id: None, | ||||
|             success: false, | ||||
|             message, | ||||
|             data: ResponseData::Empty, | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
| impl Response { | ||||
|     pub fn success(&self) -> bool { | ||||
|         self.success | ||||
|     } | ||||
|  | ||||
|     pub fn message(&self) -> &str { | ||||
|         &self.message | ||||
|     } | ||||
|  | ||||
|     pub fn set_request_id(&mut self, command_id: u64) { | ||||
|         self.request_id = Some(command_id); | ||||
|     } | ||||
|  | ||||
|     pub fn request_id(&self) -> Option<u64> { | ||||
|         self.request_id | ||||
|     } | ||||
|  | ||||
|     pub fn data(&self) -> ResponseData { | ||||
|         self.data | ||||
|     } | ||||
| } | ||||
|  | ||||
| #[derive(Debug, Serialize, Deserialize, Clone, Copy)] | ||||
| pub enum ResponseData { | ||||
|     Status(VpnStatus), | ||||
|     Empty, | ||||
| } | ||||
|  | ||||
| impl From<VpnStatus> for ResponseData { | ||||
|     fn from(status: VpnStatus) -> Self { | ||||
|         Self::Status(status) | ||||
|     } | ||||
| } | ||||
|  | ||||
| impl From<()> for ResponseData { | ||||
|     fn from(_: ()) -> Self { | ||||
|         Self::Empty | ||||
|     } | ||||
| } | ||||
|  | ||||
| #[derive(Debug)] | ||||
| pub struct TryFromResponseDataError { | ||||
|     message: String, | ||||
| } | ||||
|  | ||||
| impl std::fmt::Display for TryFromResponseDataError { | ||||
|     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||||
|         write!(f, "Invalid ResponseData: {}", self.message) | ||||
|     } | ||||
| } | ||||
|  | ||||
| impl From<&str> for TryFromResponseDataError { | ||||
|     fn from(message: &str) -> Self { | ||||
|         Self { | ||||
|             message: message.into(), | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
| impl TryFrom<ResponseData> for VpnStatus { | ||||
|     type Error = TryFromResponseDataError; | ||||
|  | ||||
|     fn try_from(value: ResponseData) -> Result<Self, Self::Error> { | ||||
|         match value { | ||||
|             ResponseData::Status(status) => Ok(status), | ||||
|             _ => Err("ResponseData is not a VpnStatus".into()), | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
| impl TryFrom<ResponseData> for () { | ||||
|     type Error = TryFromResponseDataError; | ||||
|  | ||||
|     fn try_from(value: ResponseData) -> Result<Self, Self::Error> { | ||||
|         match value { | ||||
|             ResponseData::Empty => Ok(()), | ||||
|             _ => Err("ResponseData is not empty".into()), | ||||
|         } | ||||
|     } | ||||
| } | ||||
							
								
								
									
										91
									
								
								gpcommon/src/server.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										91
									
								
								gpcommon/src/server.rs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,91 @@ | ||||
| use crate::{connection::handle_connection, vpn::Vpn}; | ||||
| use log::{warn, info}; | ||||
| use std::{future::Future, os::unix::prelude::PermissionsExt, path::Path, sync::Arc}; | ||||
| use tokio::fs; | ||||
| use tokio::net::{UnixListener, UnixStream}; | ||||
|  | ||||
| #[derive(Debug, Default)] | ||||
| pub(crate) struct ServerContext { | ||||
|     vpn: Arc<Vpn>, | ||||
| } | ||||
|  | ||||
| struct Server { | ||||
|     socket_path: String, | ||||
|     context: Arc<ServerContext>, | ||||
| } | ||||
|  | ||||
| impl ServerContext { | ||||
|     pub fn vpn(&self) -> Arc<Vpn> { | ||||
|         self.vpn.clone() | ||||
|     } | ||||
| } | ||||
|  | ||||
| impl Server { | ||||
|     fn new(socket_path: String) -> Self { | ||||
|         Self { | ||||
|             socket_path, | ||||
|             context: Default::default(), | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     // Check if an instance of the server is already running. | ||||
|     // by trying to connect to the socket. | ||||
|     async fn is_running(&self) -> bool { | ||||
|         UnixStream::connect(&self.socket_path).await.is_ok() | ||||
|     } | ||||
|  | ||||
|     async fn start(&self) -> Result<(), Box<dyn std::error::Error>> { | ||||
|         if Path::new(&self.socket_path).exists() { | ||||
|             fs::remove_file(&self.socket_path).await?; | ||||
|         } | ||||
|  | ||||
|         let listener = UnixListener::bind(&self.socket_path)?; | ||||
|         info!("Listening on socket: {:?}", listener.local_addr()?); | ||||
|  | ||||
|         let metadata = fs::metadata(&self.socket_path).await?; | ||||
|         let mut permissions = metadata.permissions(); | ||||
|         permissions.set_mode(0o666); | ||||
|         fs::set_permissions(&self.socket_path, permissions).await?; | ||||
|  | ||||
|         loop { | ||||
|             match listener.accept().await { | ||||
|                 Ok((socket, _)) => { | ||||
|                     info!("Accepted connection: {:?}", socket.peer_addr()?); | ||||
|                     tokio::spawn(handle_connection(socket, self.context.clone())); | ||||
|                 } | ||||
|                 Err(err) => { | ||||
|                     warn!("Error accepting connection: {:?}", err); | ||||
|                 } | ||||
|             } | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     async fn stop(&self) -> Result<(), Box<dyn std::error::Error>> { | ||||
|         self.context.vpn().disconnect().await; | ||||
|         fs::remove_file(&self.socket_path).await?; | ||||
|         Ok(()) | ||||
|     } | ||||
| } | ||||
|  | ||||
| pub async fn run( | ||||
|     socket_path: &str, | ||||
|     shutdown: impl Future, | ||||
| ) -> Result<(), Box<dyn std::error::Error>> { | ||||
|     let server = Server::new(socket_path.to_string()); | ||||
|  | ||||
|     if server.is_running().await { | ||||
|         return Err("Another instance of the server is already running".into()); | ||||
|     } | ||||
|  | ||||
|     tokio::select! { | ||||
|         res = server.start() => { | ||||
|             res? | ||||
|         }, | ||||
|         _ = shutdown => { | ||||
|             info!("Shutting down the server..."); | ||||
|             server.stop().await?; | ||||
|         }, | ||||
|     } | ||||
|  | ||||
|     Ok(()) | ||||
| } | ||||
							
								
								
									
										60
									
								
								gpcommon/src/vpn/ffi.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										60
									
								
								gpcommon/src/vpn/ffi.rs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,60 @@ | ||||
| use log::{debug, info, trace, warn}; | ||||
| use std::ffi::{c_char, c_int, c_void}; | ||||
| use tokio::sync::mpsc; | ||||
|  | ||||
| #[repr(C)] | ||||
| #[derive(Debug, Copy, Clone)] | ||||
| pub(crate) struct Options { | ||||
|     pub server: *const c_char, | ||||
|     pub cookie: *const c_char, | ||||
|     pub user_agent: *const c_char, | ||||
|     pub user_data: *mut c_void, | ||||
|  | ||||
|     pub script: *const c_char, | ||||
|     pub certificate: *const c_char, | ||||
|     pub servercert: *const c_char, | ||||
| } | ||||
|  | ||||
| #[link(name = "vpn")] | ||||
| extern "C" { | ||||
|     #[link_name = "vpn_connect"] | ||||
|     pub(crate) fn connect(options: *const Options) -> c_int; | ||||
|  | ||||
|     #[link_name = "vpn_disconnect"] | ||||
|     pub(crate) fn disconnect(); | ||||
| } | ||||
|  | ||||
| #[no_mangle] | ||||
| extern "C" fn on_vpn_connected(value: i32, sender: *mut c_void) { | ||||
|     let sender = unsafe { &*(sender as *const mpsc::Sender<i32>) }; | ||||
|     sender | ||||
|         .blocking_send(value) | ||||
|         .expect("Failed to send VPN connection code"); | ||||
| } | ||||
|  | ||||
| // Logger used in the C code. | ||||
| // level: 0 = error, 1 = info, 2 = debug, 3 = trace | ||||
| // map the error level log in openconnect to the warning level | ||||
| #[no_mangle] | ||||
| extern "C" fn vpn_log(level: i32, message: *const c_char) { | ||||
|     let message = unsafe { std::ffi::CStr::from_ptr(message) }; | ||||
|     let message = message.to_str().unwrap_or("Invalid log message"); | ||||
|     // Strip the trailing newline | ||||
|     let message = message.trim_end_matches('\n'); | ||||
|  | ||||
|     if level == 0 { | ||||
|         warn!("{}", message); | ||||
|     } else if level == 1 { | ||||
|         info!("{}", message); | ||||
|     } else if level == 2 { | ||||
|         debug!("{}", message); | ||||
|     } else if level == 3 { | ||||
|         trace!("{}", message); | ||||
|     } else { | ||||
|         warn!( | ||||
|             "Unknown log level: {}, enable DEBUG log level to see more details", | ||||
|             level | ||||
|         ); | ||||
|         debug!("{}", message); | ||||
|     } | ||||
| } | ||||
							
								
								
									
										164
									
								
								gpcommon/src/vpn/gpconf.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										164
									
								
								gpcommon/src/vpn/gpconf.rs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,164 @@ | ||||
| use anyhow::{Error, Ok, Result}; | ||||
| use configparser::ini::Ini; | ||||
| use lexopt::Parser; | ||||
| use log::warn; | ||||
|  | ||||
| const GPCONF_PATH: &str = "/etc/gpservice/gp.conf"; | ||||
| const DEFAULT_SECTION: &str = "*"; | ||||
| const PROP_OPENCONNECT_ARGS: &str = "openconnect-args"; | ||||
|  | ||||
| /// A struct representing the CLI arguments for the `openconnect` command. | ||||
| /// Supports most of the options from the `openconnect` command line. | ||||
| #[derive(Debug, Default)] | ||||
| pub(crate) struct OpenconnectArgs { | ||||
|     script: Option<String>, | ||||
|     certificate: Option<String>, | ||||
|     servercert: Option<String>, | ||||
| } | ||||
|  | ||||
| impl OpenconnectArgs { | ||||
|     pub fn script(&self) -> Option<String> { | ||||
|         self.script.to_owned() | ||||
|     } | ||||
|  | ||||
|     pub fn certificate(&self) -> Option<String> { | ||||
|         self.certificate.to_owned() | ||||
|     } | ||||
|  | ||||
|     pub fn servercert(&self) -> Option<String> { | ||||
|         self.servercert.to_owned() | ||||
|     } | ||||
| } | ||||
|  | ||||
| /// Read the `gp.conf` file and return the `openconnect` arguments for the given server. | ||||
| /// If the server is not found, the default section is used. | ||||
| pub(crate) fn read_conf(server: &str) -> Result<OpenconnectArgs> { | ||||
|     read_conf_from(GPCONF_PATH, server) | ||||
| } | ||||
|  | ||||
| /// Private function to read the `openconnect` arguments for the given server from a given path. | ||||
| /// Make it easy to write tests. | ||||
| fn read_conf_from(path: &str, server: &str) -> Result<OpenconnectArgs> { | ||||
|     let mut config = Ini::new(); | ||||
|  | ||||
|     config.set_default_section(DEFAULT_SECTION); | ||||
|     config.set_multiline(true); | ||||
|  | ||||
|     config.load(path).map_err(Error::msg)?; | ||||
|  | ||||
|     let default_openconnect_config = config | ||||
|         .get(DEFAULT_SECTION, PROP_OPENCONNECT_ARGS) | ||||
|         .unwrap_or_default(); | ||||
|     let server_openconnect_config = config | ||||
|         .get(server, PROP_OPENCONNECT_ARGS) | ||||
|         .unwrap_or(default_openconnect_config); | ||||
|  | ||||
|     let args = shlex::split(&server_openconnect_config).unwrap_or_default(); | ||||
|     parse_args(&args) | ||||
| } | ||||
|  | ||||
| fn parse_args(args: &Vec<String>) -> Result<OpenconnectArgs> { | ||||
|     use lexopt::prelude::*; | ||||
|  | ||||
|     let mut parser = Parser::from_args(args); | ||||
|  | ||||
|     let mut script: Option<String> = None; | ||||
|     let mut certificate: Option<String> = None; | ||||
|     let mut servercert: Option<String> = None; | ||||
|     while let Some(arg) = parser.next()? { | ||||
|         match arg { | ||||
|             Long("script") | Short('s') => { | ||||
|                 script = Some(parser.value()?.parse()?); | ||||
|             } | ||||
|             Long("certificate") | Short('c') => { | ||||
|                 certificate = Some(parser.value()?.parse()?); | ||||
|             } | ||||
|             Long("servercert") => { | ||||
|                 servercert = Some(parser.value()?.parse()?); | ||||
|             } | ||||
|             _ => { | ||||
|                 warn!("Ignoring unknown argument: {}", arg.unexpected()); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     Ok(OpenconnectArgs { | ||||
|         script, | ||||
|         certificate, | ||||
|         servercert, | ||||
|     }) | ||||
| } | ||||
|  | ||||
| #[cfg(test)] | ||||
| mod tests { | ||||
|     use std::io::Write; | ||||
|     use tempfile::NamedTempFile; | ||||
|  | ||||
|     use super::*; | ||||
|  | ||||
|     // Macro to create a temporary file with the given content. | ||||
|     macro_rules! tempfile { | ||||
|         ($content:expr) => {{ | ||||
|             let mut file = NamedTempFile::new().unwrap(); | ||||
|             write!(file, $content).unwrap(); | ||||
|             file | ||||
|         }}; | ||||
|     } | ||||
|  | ||||
|     #[test] | ||||
|     fn test_config_not_found() { | ||||
|         let args = read_conf_from("non-existent-file", "server"); | ||||
|         assert!(args.is_err()); | ||||
|     } | ||||
|  | ||||
|     #[test] | ||||
|     fn test_default_config() { | ||||
|         let file = tempfile!( | ||||
|             r#" | ||||
| [*] | ||||
| openconnect-args=--script=/script.sh | ||||
| "# | ||||
|         ); | ||||
|         let path = file.path().to_str().unwrap(); | ||||
|         let args = read_conf_from(path, "any server").unwrap(); | ||||
|  | ||||
|         assert_eq!(args.script, Some("/script.sh".to_string())); | ||||
|         assert_eq!(args.certificate, None); | ||||
|         assert_eq!(args.servercert, None); | ||||
|     } | ||||
|  | ||||
|     #[test] | ||||
|     fn test_server_config() { | ||||
|         let file = tempfile!( | ||||
|             r#" | ||||
| [*] | ||||
| openconnect-args=--script=/script.sh | ||||
|  | ||||
| [server] | ||||
| openconnect-args=--certificate=/cert.pem | ||||
| "# | ||||
|         ); | ||||
|         let path = file.path().to_str().unwrap(); | ||||
|         let args = read_conf_from(path, "server").unwrap(); | ||||
|  | ||||
|         assert_eq!(args.script, None); | ||||
|         assert_eq!(args.certificate, Some("/cert.pem".to_string())); | ||||
|         assert_eq!(args.servercert, None); | ||||
|     } | ||||
|  | ||||
|     #[test] | ||||
|     fn test_ignore_unknown_args() { | ||||
|         let file = tempfile!( | ||||
|             r#" | ||||
| [*] | ||||
| openconnect-args=--script=/script.sh --unknown-arg -c /cert.pem | ||||
| "# | ||||
|         ); | ||||
|         let path = file.path().to_str().unwrap(); | ||||
|         let args = read_conf_from(path, "server").unwrap(); | ||||
|  | ||||
|         assert_eq!(args.script, Some("/script.sh".to_string())); | ||||
|         assert_eq!(args.certificate, Some("/cert.pem".to_string())); | ||||
|         assert_eq!(args.servercert, None); | ||||
|     } | ||||
| } | ||||
Some files were not shown because too many files have changed in this diff Show More
		Reference in New Issue
	
	Block a user