release: prepare GP Connect 3.5.0 with Windows support

This commit is contained in:
Kevin Yue committed 2026-11-19 01:40:22 +08:00
1 parent 6ffb1e8709
commit 43c20d0976
172 files changed
+9629 -1171

No files matched your search

-2
View File
@@ -10,7 +10,6 @@ license="GPL-3.0-only"
depends="
gmp
gnutls
libayatana-appindicator
libsecret
libxml2
lz4
@@ -30,7 +29,6 @@ makedepends="
gmp-dev
gnutls-dev
gtk+3.0-dev
libayatana-appindicator-dev
libsecret-dev
librsvg-dev
libtool
@@ -10,7 +10,7 @@ url="https://github.com/yuezk/GlobalProtect-openconnect"
license=('GPL3')
makedepends=(git pkg-config make autoconf automake gettext libtool patch curl wget file appmenu-gtk-module librsvg cargo)
depends=(webkit2gtk-4.1 libappindicator-gtk3 libsecret libxml2 zlib lz4 gnutls libp11-kit nettle libhogweed.so gmp shared-mime-info desktop-file-utils xdg-utils)
depends=(webkit2gtk-4.1 libsecret libxml2 zlib lz4 gnutls libp11-kit nettle libhogweed.so gmp shared-mime-info desktop-file-utils xdg-utils)
optdepends=('wmctrl: for window management')
conflicts=('globalprotect-openconnect')
-4
View File
@@ -23,10 +23,6 @@ deps: {
origin: "security/gnutls"
version: "*"
}
"libayatana-appindicator": {
origin: "devel/libayatana-appindicator"
version: "*"
}
"liblz4": {
origin: "archivers/liblz4"
version: "*"
-2
View File
@@ -19,7 +19,6 @@ Build-Depends: debhelper (>= 9),
nettle-dev,
libgmp-dev,
libsecret-1-0,
libayatana-appindicator3-1,
gnome-keyring,
libwebkit2gtk-4.1-dev,
cargo-@RUST_VERSION@,
@@ -33,7 +32,6 @@ Depends:
${misc:Depends},
${shlibs:Depends},
libsecret-1-0,
libayatana-appindicator3-1,
gnome-keyring,
xdg-utils,
Description: A GUI client for GlobalProtect VPN
+1 -1
View File
@@ -9,7 +9,7 @@ arch=('x86_64' 'aarch64')
url="https://github.com/yuezk/GlobalProtect-openconnect"
license=('GPL3')
makedepends=('make' 'pkg-config' 'cargo' 'file' 'autoconf' 'automake' 'gettext' 'libtool' 'patch')
depends=('webkit2gtk-4.1' 'libappindicator-gtk3' 'librsvg' 'libsecret' 'appmenu-gtk-module'
depends=('webkit2gtk-4.1' 'librsvg' 'libsecret' 'appmenu-gtk-module'
'gnutls' 'libxml2' 'zlib' 'lz4' 'libp11-kit' 'nettle' 'libhogweed.so' 'gmp' 'xdg-utils')
optdepends=('wmctrl: for window management')
@@ -28,15 +28,9 @@ BuildRequires: file
BuildRequires: perl
BuildRequires: pkgconfig(webkit2gtk-4.1)
BuildRequires: (pkgconfig(appindicator3-0.1) or pkgconfig(ayatana-appindicator3-0.1))
BuildRequires: (librsvg2-devel or librsvg-devel)
%if 0%{?suse_version}
Requires: (libappindicator3-1 or libayatana-appindicator3-1)
%else
Requires: (libappindicator-gtk3 or libayatana-appindicator-gtk3)
%endif
Requires: xdg-utils
Conflicts: globalprotect-openconnect-snapshot
+99
View File
@@ -0,0 +1,99 @@
# Windows installer
`installer.nsi` embeds a complete Windows payload and the canonical
`machine-install.ps1` installation implementation. Build it with NSIS 3 Unicode:
```powershell
& makensis /DTARGET_ARCH=x64 /DPAYLOAD_DIR=C:\build\payload /DOUTPUT_FILE=C:\build\GPConnect-Setup.exe /DPRODUCT_VERSION=3.4.0 /DBUILD_VERSION=3.4.0.0 /DDISPLAY_VERSION=3.4.0-snapshot.2026.1114.2 .\packaging\windows\installer.nsi
```
`TARGET_ARCH` is `x64` or `arm64` and must match every executable and DLL in
the payload. Each installer accepts only its native Windows architecture. ARM64
requires Windows 11; x64 requires Windows 10 build 19041 or newer.
The native library build accepts `scripts/build-openconnect-windows.ps1 -TunnelType 'GP Connect'`
(the default). This passes OpenConnect's `--with-wintun-tunnel-type` build option;
OpenConnect itself defaults to `OpenConnect`. Wintun appends ` Tunnel` to the
selected type. The gateway-based connection name is unchanged.
`BUILD_VERSION` must contain four numeric components. `PRODUCT_VERSION` must
match the payload's `build-info.json`. `DISPLAY_VERSION` is the full release
identity, including the snapshot build when applicable. The payload must contain matching
`gpgui.exe`, `gpauth.exe`, `gpservice.exe`, their DLL dependency closure, the
vendor-signed `wintun.dll`, `licenses`, and `build-info.json`. The NSIS compiler
adds the generated uninstaller; it is not a separately built executable.
The installer, extraction progress and uninstaller use the shared Windows icon
from `apps/gpauth/icons/windows/icon.ico`. The confirmation and Finish pages use `sidebar.bmp`,
derived from that same icon. After regenerating application icons, run
`powershell -NoProfile -File scripts/generate-windows-installer-artwork.ps1`
on Windows and retain the updated bitmap before building installers.
The development ZIP includes the same machine implementation as
`installer/machine-install.ps1`. Its install/uninstall entrypoints call that
implementation rather than maintaining a second file replacement algorithm.
Use the EXE installer to upgrade an installation that already has an NSIS
uninstaller; the development ZIP does not contain that generated executable.
Installation waits for the installed GUI/auth paths in all Windows sessions;
it does not stop arbitrary same-name processes. Service shutdown uses SCM,
checks the existing network-recovery criteria, and waits for file release.
Application files are staged under Program Files with protected ACLs. The old
directory is renamed to `GP Connect.previous` until the new service is Running.
Handled replacement/start failures restore old files and metadata and restart
the previous service. An interrupted installer with a retained backup requires
explicit repair; it is not automatically recovered.
Disk use includes the downloaded installer and one expanded new payload. NSIS
extracts into its temporary directory, then the machine implementation consumes
those disposable files into protected staging instead of copying the whole bundle.
When temp and Program Files use different volumes, file moves may temporarily
duplicate the file currently being moved. The old installation is renamed, not
copied. The machine implementation checks the installation volume before staging;
NSIS extraction errors must complete before service shutdown.
Successful installation removes the old copy and staging. Installer logs keep
the current and previous attempt in ProgramData. No updater cache is added.
The installer never launches the GUI as administrator. Users open GP Connect
from the Start menu after completion. User configuration and licensing state
are retained during upgrades and uninstall. Release builds use Azure Artifact
Signing with GitHub OIDC and RFC 3161 timestamps. Application executables,
the built OpenConnect DLL, and the generated NSIS uninstaller and installer
are signed before checksums and WinSparkle signatures are generated.
Vendor DLL signatures are preserved. WinSparkle independently verifies its
installer payload signature before handoff.
The GitHub `windows-signing` environment is trusted by the Entra application
`gp-connect-github-signing`. Its only Azure role is Artifact Signing Certificate
Profile Signer on `tangramly-signing/certificateProfiles/gp-connect`.
Environment deployment policies allow the `release/next` branch and `v*` tags.
Repository variables supply `AZURE_SIGNING_CLIENT_ID`, `AZURE_TENANT_ID`,
`AZURE_SUBSCRIPTION_ID`, `AZURE_SIGNING_ENDPOINT`, `AZURE_SIGNING_ACCOUNT`,
`AZURE_SIGNING_PROFILE`, and `WINDOWS_SIGNING_PUBLISHER`. No Azure client secret
or Authenticode private key is stored in GitHub. `build-windows.ps1 -Sign` requires
Microsoft's ArtifactSigning PowerShell module 0.1.20 and an Azure CLI login.
The build verifies the publisher, certificate trust and timestamp on each signed
file. The installer smoke test repeats those checks on the installed runtime
and uninstaller before testing removal.
The Start menu shortcut registers `System.AppUserModel.ID` as `com.yuezk.gpgui`,
matching the GUI and native toast sender. Windows uses the shortcut's name and
executable icon to identify GP Connect in Notification Center. Its identity is
part of the shortcut, so the existing shortcut rollback and uninstall own its cleanup.
Manual launches show an Install/Cancel confirmation page (Update/Cancel when
GP Connect is already installed). The update feed supplies `/UPDATE` through
WinSparkle's `sparkle:installerArguments` to skip that page after the user has
already confirmed the in-app update. This is not silent mode: elevation,
installation progress, errors, and the Finish page remain visible.
The service log rotates after 5 MiB and retains three numbered archives, keeping
each entry whole. The bundle includes `licenses/file-rotate.txt` for the Windows
service's rotation library.
On a disposable Windows installation, verify a normal A-to-B upgrade and a B
payload whose `gpservice.exe` is replaced with another valid PE executable that
cannot host a Windows service. The latter must fail service startup, restore A's
files and uninstall metadata, and leave A's service running. Also check held
runtime files, active GUI/auth windows, Wintun-signature failure, and concurrent
installer attempts. Do not run failure fixtures against a live company VPN.
+127
View File
@@ -0,0 +1,127 @@
Unicode true
RequestExecutionLevel admin
!include "MUI2.nsh"
!include "x64.nsh"
!include "FileFunc.nsh"
!ifndef PAYLOAD_DIR
!error "PAYLOAD_DIR is required"
!endif
!ifndef OUTPUT_FILE
!error "OUTPUT_FILE is required"
!endif
!ifndef PRODUCT_VERSION
!error "PRODUCT_VERSION is required"
!endif
!ifndef TARGET_ARCH
!define TARGET_ARCH "x64"
!endif
!ifndef BUILD_VERSION
!define BUILD_VERSION "${PRODUCT_VERSION}.0"
!endif
!ifndef DISPLAY_VERSION
!define DISPLAY_VERSION "${PRODUCT_VERSION}"
!endif
!ifdef SIGN_SCRIPT
!uninstfinalize 'pwsh -NoLogo -NoProfile -NonInteractive -File "${SIGN_SCRIPT}" -Files "%1"' = 0
!finalize 'pwsh -NoLogo -NoProfile -NonInteractive -File "${SIGN_SCRIPT}" -Files "%1"' = 0
!endif
Name "GP Connect"
OutFile "${OUTPUT_FILE}"
InstallDir "$PROGRAMFILES64\GP Connect"
VIProductVersion "${BUILD_VERSION}"
VIAddVersionKey "ProductName" "GP Connect"
VIAddVersionKey "FileDescription" "GP Connect Installer"
VIAddVersionKey "ProductVersion" "${DISPLAY_VERSION}"
VIAddVersionKey "FileVersion" "${BUILD_VERSION}"
VIAddVersionKey "LegalCopyright" "GP Connect contributors"
ShowInstDetails show
ShowUninstDetails show
Var InstallAction
!define MUI_ICON "${__FILEDIR__}\..\..\apps\gpauth\icons\windows\icon.ico"
!define MUI_UNICON "${MUI_ICON}"
!define MUI_WELCOMEFINISHPAGE_BITMAP "${__FILEDIR__}\sidebar.bmp"
!define MUI_ABORTWARNING
!define MUI_FINISHPAGE_TITLE "GP Connect is ready"
!define MUI_FINISHPAGE_TEXT "Open GP Connect from the Start menu."
!define MUI_WELCOMEPAGE_TITLE "$InstallAction GP Connect"
!define MUI_WELCOMEPAGE_TEXT "$InstallAction GP Connect for all users on this computer.$\r$\n$\r$\nClick $InstallAction to continue."
!define MUI_PAGE_CUSTOMFUNCTION_PRE ConfirmInstall
!define MUI_PAGE_CUSTOMFUNCTION_SHOW ShowInstallAction
!insertmacro MUI_PAGE_WELCOME
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_PAGE_FINISH
!insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_INSTFILES
!insertmacro MUI_LANGUAGE "English"
Function .onInit
!if "${TARGET_ARCH}" == "arm64"
${IfNot} ${IsNativeARM64}
MessageBox MB_OK|MB_ICONSTOP "This GP Connect installer requires Windows 11 on ARM64." /SD IDOK
SetErrorLevel 1
Abort
${EndIf}
!else if "${TARGET_ARCH}" == "x64"
${IfNot} ${IsNativeAMD64}
MessageBox MB_OK|MB_ICONSTOP "This GP Connect installer requires x64 Windows." /SD IDOK
SetErrorLevel 1
Abort
${EndIf}
!else
!error "Unsupported TARGET_ARCH"
!endif
SetRegView 64
StrCpy $InstallAction "Install"
ReadRegStr $0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\GPConnect" "DisplayVersion"
${If} $0 != ""
StrCpy $InstallAction "Update"
${EndIf}
FunctionEnd
Function ConfirmInstall
${GetParameters} $0
ClearErrors
${GetOptions} $0 "/UPDATE" $1
${IfNot} ${Errors}
Abort
${EndIf}
FunctionEnd
Function ShowInstallAction
GetDlgItem $0 $HWNDPARENT 1
SendMessage $0 ${WM_SETTEXT} 0 "STR:$InstallAction"
FunctionEnd
Section "Install"
InitPluginsDir
SetOutPath "$PLUGINSDIR\payload"
File /r "${PAYLOAD_DIR}\*"
WriteUninstaller "$PLUGINSDIR\payload\uninstall.exe"
SetOutPath "$PLUGINSDIR"
File "${__FILEDIR__}\machine-install.ps1"
DetailPrint "Preparing GP Connect and waiting for open windows to close..."
nsExec::ExecToLog '"$WINDIR\Sysnative\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$PLUGINSDIR\machine-install.ps1" -Action Install -SourceDirectory "$PLUGINSDIR\payload" -Version "${PRODUCT_VERSION}" -ConsumeSource'
Pop $0
${If} $0 != 0
MessageBox MB_OK|MB_ICONSTOP "GP Connect could not be installed. See the details below and try again." /SD IDOK
SetErrorLevel 1
Abort
${EndIf}
SectionEnd
Section "Uninstall"
SetRegView 64
InitPluginsDir
SetOutPath "$PLUGINSDIR"
File "${__FILEDIR__}\machine-install.ps1"
DetailPrint "Waiting for GP Connect and sign-in windows to close..."
nsExec::ExecToLog '"$WINDIR\Sysnative\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$PLUGINSDIR\machine-install.ps1" -Action Uninstall'
Pop $0
${If} $0 != 0
MessageBox MB_OK|MB_ICONSTOP "GP Connect could not be removed. See the details below and try again." /SD IDOK
SetErrorLevel 1
Abort
${EndIf}
SectionEnd
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 BourgondAries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+437
View File
@@ -0,0 +1,437 @@
#Requires -RunAsAdministrator
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)][ValidateSet('Install', 'Uninstall')][string]$Action,
[string]$SourceDirectory,
[string]$Version,
[switch]$ConsumeSource
)
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
if ($PSVersionTable.PSEdition -eq 'Desktop') {
# A PowerShell 7 caller can pass incompatible modules to Windows PowerShell.
$env:PSModulePath = Join-Path $PSHOME 'Modules'
}
if (![Environment]::Is64BitProcess) { throw 'Run the GP Connect installer with 64-bit PowerShell.' }
$destination = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) 'GP Connect'
$state = Join-Path $env:ProgramData 'GP Connect'
$serviceName = 'GPConnect'
$serviceBinary = Join-Path $destination 'gpservice.exe'
$shortcutPath = Join-Path $env:ProgramData 'Microsoft\Windows\Start Menu\Programs\GP Connect.lnk'
$uninstallKey = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\GPConnect'
$recoveryKey = 'HKLM:\SOFTWARE\GP Connect\NetworkRecovery'
$publicAcl = 'O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FRFX;;;BU)'
$privateAcl = 'O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)'
$backup = $destination + '.previous'
$stage = $null
$oldMoved = $false
$newMoved = $false
$serviceStopped = $false
$createdService = $false
$committed = $false
$oldMetadata = $null
$oldShortcut = $null
function Assert-RegularDirectory([string]$Path) {
if (Test-Path -LiteralPath $Path) {
$item = Get-Item -LiteralPath $Path -Force
if (!$item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
throw "The installation folder must be a regular directory: $Path"
}
}
}
function Set-DirectoryAcl([string]$Path, [string]$Descriptor) {
Assert-RegularDirectory $Path
if (!(Test-Path -LiteralPath $Path)) { New-Item -ItemType Directory -Path $Path | Out-Null }
$acl = Get-Acl -LiteralPath $Path
$acl.SetSecurityDescriptorSddlForm($Descriptor)
Set-Acl -LiteralPath $Path -AclObject $acl
}
function Wait-ForApplications {
$deadline = [DateTime]::UtcNow.AddSeconds(30)
do {
$running = @(Get-CimInstance Win32_Process -Filter "Name='gpgui.exe' OR Name='gpauth.exe'" |
Where-Object { $_.ExecutablePath -in @((Join-Path $destination 'gpgui.exe'), (Join-Path $destination 'gpauth.exe')) })
if (!$running.Count) { return }
if ([DateTime]::UtcNow -ge $deadline) {
throw 'Quit GP Connect and finish or cancel sign-in in all Windows sessions, then try again.'
}
Start-Sleep -Milliseconds 250
} while ($true)
}
function Wait-ServiceState([string]$Expected) {
$controller = Get-Service -Name $serviceName
try { $controller.WaitForStatus($Expected, [TimeSpan]::FromSeconds(30)) }
finally { $controller.Dispose() }
}
function Stop-InstalledService {
$service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if (!$service) { return }
try { $stopped = $service.Status -eq 'Stopped' } finally { $service.Dispose() }
if (!$stopped) { Stop-Service -Name $serviceName; Wait-ServiceState 'Stopped' }
}
function Start-InstalledService {
Start-Service -Name $serviceName
Wait-ServiceState 'Running'
}
function Move-InstalledDirectoryToBackup {
try { Move-Item -LiteralPath $destination -Destination $backup }
catch [IO.IOException] {
throw 'GP Connect files are in use. Close any GP Connect folders in File Explorer and try again.'
}
}
function Wait-ForRuntimeRelease {
$deadline = [DateTime]::UtcNow.AddSeconds(30)
do {
$locked = $false
foreach ($file in Get-ChildItem -LiteralPath $destination -File | Where-Object { $_.Extension -in @('.exe', '.dll') }) {
try {
$stream = [IO.File]::Open($file.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
$stream.Dispose()
} catch [IO.IOException] { $locked = $true; break }
}
if (!$locked) { return }
if ([DateTime]::UtcNow -ge $deadline) { throw 'An application file is still in use. Close GP Connect in all Windows sessions and try again.' }
Start-Sleep -Milliseconds 250
} while ($true)
}
function Assert-NetworkClean {
$records = @()
if (Test-Path $recoveryKey) { $records = @((Get-Item $recoveryKey).GetValueNames() | Where-Object { $_ -like 'Route-*' }) }
$policies = @(Get-DnsClientNrptRule | Where-Object { $_.Comment -like 'GPConnect:*' })
if ($records.Count -or $policies.Count) {
throw 'VPN network cleanup is incomplete. Restart GP Connect before trying again.'
}
}
function Invoke-ServiceCommand([string[]]$Arguments) {
& "$env:SystemRoot\System32\sc.exe" @Arguments | Out-Null
if ($LASTEXITCODE -ne 0) { throw "Windows service configuration failed ($LASTEXITCODE)." }
}
function Set-MachineState {
Set-DirectoryAcl $state $publicAcl
Set-DirectoryAcl (Join-Path $state 'Private') $privateAcl
foreach ($name in @('gpservice.lock', 'gpservice.log')) {
$path = Join-Path $state $name
if (Test-Path -LiteralPath $path) {
if ((Get-Item -LiteralPath $path -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) {
throw "Service state file must not be a link: $path"
}
$acl = Get-Acl -LiteralPath $path
$acl.SetSecurityDescriptorSddlForm($publicAcl)
Set-Acl -LiteralPath $path -AclObject $acl
}
}
$registry = [Microsoft.Win32.Registry]::LocalMachine.CreateSubKey('SOFTWARE\GP Connect')
try {
$recovery = $registry.CreateSubKey('NetworkRecovery', [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, [Microsoft.Win32.RegistryOptions]::Volatile)
try {
foreach ($key in @($registry, $recovery)) {
$acl = New-Object System.Security.AccessControl.RegistrySecurity
$acl.SetSecurityDescriptorSddlForm('O:BAG:BAD:P(A;CI;KA;;;SY)(A;CI;KA;;;BA)')
$key.SetAccessControl($acl)
}
} finally { $recovery.Dispose() }
} finally { $registry.Dispose() }
}
function Set-ShortcutAppUserModelId([string]$Path, [string]$ApplicationId) {
if (-not ('GPConnect.Installer.ShortcutIdentity' -as [type])) {
# NSIS also extracts a native System.dll; reference the loaded .NET assembly explicitly.
Add-Type -ReferencedAssemblies ([System.Uri].Assembly.Location) -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
namespace GPConnect.Installer {
public static class ShortcutIdentity {
[StructLayout(LayoutKind.Sequential)]
private struct PropertyKey { public Guid Format; public uint Id; }
// PROPVARIANT is 24 bytes in both supported 64-bit architectures.
[StructLayout(LayoutKind.Explicit, Size = 24)]
private struct PropVariant {
[FieldOffset(0)] public ushort Type;
[FieldOffset(8)] public IntPtr Value;
}
[ComImport, Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IPropertyStore {
void GetCount(out uint count);
void GetAt(uint index, out PropertyKey key);
void GetValue(ref PropertyKey key, out PropVariant value);
void SetValue(ref PropertyKey key, ref PropVariant value);
void Commit();
}
[DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
private static extern void SHGetPropertyStoreFromParsingName(
string path, IntPtr context, uint flags, ref Guid iid, out IPropertyStore store);
public static void Set(string path, string applicationId) {
var iid = typeof(IPropertyStore).GUID;
IPropertyStore store;
SHGetPropertyStoreFromParsingName(path, IntPtr.Zero, 2, ref iid, out store); // GPS_READWRITE
var value = new PropVariant { Type = 31, Value = Marshal.StringToCoTaskMemUni(applicationId) }; // VT_LPWSTR
try {
var key = new PropertyKey { Format = new Guid("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"), Id = 5 };
store.SetValue(ref key, ref value); // PKEY_AppUserModel_ID
store.Commit();
} finally {
Marshal.FreeCoTaskMem(value.Value);
Marshal.ReleaseComObject(store);
}
}
}
}
'@
}
[GPConnect.Installer.ShortcutIdentity]::Set($Path, $ApplicationId)
}
function Set-InstallationMetadata([string]$InstalledVersion) {
$shell = New-Object -ComObject WScript.Shell
$shortcut = $shell.CreateShortcut($shortcutPath)
$shortcut.TargetPath = Join-Path $destination 'gpgui.exe'
$shortcut.WorkingDirectory = $destination
$shortcut.Description = 'A GUI client for GlobalProtect VPN'
$shortcut.IconLocation = (Join-Path $destination 'gpgui.exe') + ',0'
$shortcut.Save()
Set-ShortcutAppUserModelId $shortcutPath 'com.yuezk.gpgui'
if (Test-Path -LiteralPath (Join-Path $destination 'uninstall.exe')) {
New-Item -Path $uninstallKey -Force | Out-Null
$values = @{
DisplayName = 'GP Connect'; DisplayVersion = $InstalledVersion; Publisher = 'GP Connect'
InstallLocation = $destination; DisplayIcon = (Join-Path $destination 'gpgui.exe')
UninstallString = '"' + (Join-Path $destination 'uninstall.exe') + '"'
}
foreach ($entry in $values.GetEnumerator()) {
New-ItemProperty -Path $uninstallKey -Name $entry.Key -Value $entry.Value -PropertyType String -Force | Out-Null
}
foreach ($name in @('NoModify', 'NoRepair')) {
New-ItemProperty -Path $uninstallKey -Name $name -Value 1 -PropertyType DWord -Force | Out-Null
}
}
}
function Restore-InstallationMetadata {
if (Test-Path $uninstallKey) { Remove-Item $uninstallKey -Recurse -Force }
if ($oldMetadata) {
New-Item -Path $uninstallKey -Force | Out-Null
foreach ($entry in $oldMetadata.GetEnumerator()) {
New-ItemProperty -Path $uninstallKey -Name $entry.Key -Value $entry.Value.Value -PropertyType $entry.Value.Kind -Force | Out-Null
}
}
if ($oldShortcut) { [IO.File]::WriteAllBytes($shortcutPath, $oldShortcut) }
elseif (Test-Path -LiteralPath $shortcutPath) { Remove-Item -LiteralPath $shortcutPath -Force }
}
function Remove-OwnedCallback {
$callback = 'HKCU:\Software\Classes\globalprotectcallback'
$commandKey = "$callback\shell\open\command"
if (Test-Path $commandKey) {
$command = (Get-Item $commandKey).GetValue('')
$authBinary = Join-Path $destination 'gpauth.exe'
$owned = @("`"$authBinary`" auth-callback `"%1`"", "`"\\?\$authBinary`" auth-callback `"%1`"")
if ($command -in $owned) { Remove-Item $callback -Recurse -Force }
}
}
$mutex = New-Object System.Threading.Mutex($false, 'Global\GPConnect.Installer')
$owned = $false
$transcript = $false
try {
try { $owned = $mutex.WaitOne(0) } catch [Threading.AbandonedMutexException] { $owned = $true }
if (!$owned) { throw 'Another GP Connect installation is running. Wait for it to finish.' }
Assert-RegularDirectory $destination
Assert-RegularDirectory $state
if (Test-Path -LiteralPath $backup) {
throw "A previous installation needs repair. The retained files are in $backup. Do not delete them before restoring GP Connect."
}
# Keep only this attempt and one previous diagnostic log.
Set-DirectoryAcl $state $publicAcl
$log = Join-Path $state 'installer.log'
$previousLog = Join-Path $state 'installer.previous.log'
foreach ($path in @($log, $previousLog)) {
if ((Test-Path -LiteralPath $path) -and ((Get-Item -LiteralPath $path -Force).Attributes -band [IO.FileAttributes]::ReparsePoint)) {
throw 'Installer log must not be a link.'
}
}
if (Test-Path -LiteralPath $previousLog) { Remove-Item -LiteralPath $previousLog -Force }
if (Test-Path -LiteralPath $log) { Move-Item -LiteralPath $log -Destination $previousLog }
Start-Transcript -Path $log -Force | Out-Null
$transcript = $true
$existing = Get-CimInstance Win32_Service -Filter "Name='$serviceName'"
if ($existing -and $existing.PathName -ne ('"' + $serviceBinary + '"')) {
throw 'The GPConnect service is registered to another installation.'
}
$wasRunning = $existing -and $existing.State -ne 'Stopped'
if ($Action -eq 'Install') {
if (!$SourceDirectory) { throw 'An installation source is required.' }
$source = (Resolve-Path -LiteralPath $SourceDirectory).Path.TrimEnd('\')
if ($source -eq $destination -or $source.StartsWith($destination + '\', [StringComparison]::OrdinalIgnoreCase)) {
throw 'Install from an extracted package outside the application folder.'
}
foreach ($name in @('gpservice.exe', 'gpauth.exe', 'gpgui.exe', 'gp-posture.exe', 'libopenconnect-5.dll', 'wintun.dll', 'build-info.json')) {
if (!(Test-Path -LiteralPath (Join-Path $source $name) -PathType Leaf)) { throw "Missing Windows package file: $name" }
}
$info = Get-Content -LiteralPath (Join-Path $source 'build-info.json') -Raw | ConvertFrom-Json
if ((Test-Path -LiteralPath (Join-Path $destination 'uninstall.exe')) -and
!(Test-Path -LiteralPath (Join-Path $source 'uninstall.exe'))) {
throw 'Use the Windows installer to update this installation.'
}
if (!$Version) { $Version = $info.version }
$architecture = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString().ToLowerInvariant()
if ($info.product -ne 'GP Connect' -or $info.architecture -notin @('x64','arm64') -or $info.architecture -ne $architecture -or !$Version -or $info.version -ne $Version) {
throw 'The package version or architecture does not match this installer.'
}
if (![Environment]::Is64BitProcess -or [Environment]::OSVersion.Version.Build -lt 19041) {
throw 'GP Connect requires Windows 10 build 19041 or newer.'
}
if ($architecture -eq 'arm64' -and [Environment]::OSVersion.Version.Build -lt 22000) {
throw 'GP Connect for ARM64 requires Windows 11.'
}
$payload = @(Get-ChildItem -LiteralPath $source -Force | Where-Object {
($_.PSIsContainer -and $_.Name -eq 'licenses') -or
(!$_.PSIsContainer -and ($_.Extension -eq '.dll' -or
$_.Name -in @('gpservice.exe', 'gpauth.exe', 'gpgui.exe', 'gp-posture.exe', 'uninstall.exe', 'build-info.json')))
})
foreach ($item in $payload) {
$items = @($item)
if ($item.PSIsContainer) { $items += @(Get-ChildItem -LiteralPath $item.FullName -Force -Recurse) }
if ($items | Where-Object { $_.Attributes -band [IO.FileAttributes]::ReparsePoint }) { throw 'The package must not contain file links.' }
}
$requiredBytes = [long]0
foreach ($item in $payload) {
if ($item.PSIsContainer) { $requiredBytes += [long](Get-ChildItem -LiteralPath $item.FullName -File -Recurse | Measure-Object -Property Length -Sum).Sum }
else { $requiredBytes += $item.Length }
}
$volume = New-Object IO.DriveInfo([IO.Path]::GetPathRoot($destination))
$additionalBytes = $requiredBytes + 16MB
if ($ConsumeSource -and [IO.Path]::GetPathRoot($source) -eq $volume.Name) {
# The extracted files already occupy this volume; renaming them adds no copy.
$additionalBytes = 16MB
}
if ($volume.AvailableFreeSpace -lt $additionalBytes) { throw 'There is not enough free space to install GP Connect.' }
$stage = $destination + '.stage-' + [Guid]::NewGuid().ToString('N')
Set-DirectoryAcl $stage $publicAcl
foreach ($item in $payload) {
if (!$ConsumeSource) {
Copy-Item -LiteralPath $item.FullName -Destination $stage -Recurse -Force
continue
}
# NSIS's extracted payload is disposable. Move files individually so temp
# and Program Files may be on different volumes without keeping two bundles.
$files = @($item)
if ($item.PSIsContainer) { $files = @(Get-ChildItem -LiteralPath $item.FullName -File -Recurse) }
foreach ($file in $files) {
$relative = $file.Name
if ($item.PSIsContainer) {
# Enumerated paths share the same expanded spelling, including 8.3 temp paths.
$child = $file.FullName.Substring($item.FullName.Length).TrimStart('\')
$relative = Join-Path $item.Name $child
}
$target = Join-Path $stage $relative
$parent = Split-Path $target -Parent
if (!(Test-Path -LiteralPath $parent)) { New-Item -ItemType Directory -Path $parent -Force | Out-Null }
Move-Item -LiteralPath $file.FullName -Destination $target
}
}
# Copies inherit the staging directory's protected policy, even when source ACLs differ.
foreach ($item in Get-ChildItem -LiteralPath $stage -Force -Recurse) {
$acl = Get-Acl -LiteralPath $item.FullName
$acl.SetSecurityDescriptorSddlForm($publicAcl)
Set-Acl -LiteralPath $item.FullName -AclObject $acl
}
$signature = Get-AuthenticodeSignature (Join-Path $stage 'wintun.dll')
if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch 'WireGuard LLC') {
throw 'The package requires the vendor-signed Wintun driver DLL.'
}
if ((Test-Path -LiteralPath $destination) -and !$existing) { throw 'The service is not registered. Repair the existing installation before updating.' }
if ($existing -and !(Test-Path -LiteralPath $destination)) { throw 'The registered installation is missing. Restore its files before updating.' }
if (Test-Path $uninstallKey) {
$key = Get-Item $uninstallKey
$oldMetadata = @{}
foreach ($name in $key.GetValueNames()) { $oldMetadata[$name] = @{ Value = $key.GetValue($name); Kind = $key.GetValueKind($name).ToString() } }
}
if (Test-Path -LiteralPath $shortcutPath) { $oldShortcut = [IO.File]::ReadAllBytes($shortcutPath) }
Wait-ForApplications
if ($existing) {
$serviceStopped = $true
Stop-InstalledService
Assert-NetworkClean
Wait-ForRuntimeRelease
}
if (Test-Path -LiteralPath $destination) { Move-InstalledDirectoryToBackup; $oldMoved = $true }
Move-Item -LiteralPath $stage -Destination $destination
$stage = $null
$newMoved = $true
Set-MachineState
if (!$existing) {
New-Service -Name $serviceName -DisplayName 'GP Connect' -BinaryPathName ('"' + $serviceBinary + '"') -StartupType Automatic -Description 'Connects GP Connect to your GlobalProtect VPN network.' | Out-Null
$createdService = $true
} else { Set-Service -Name $serviceName -StartupType Automatic }
Invoke-ServiceCommand @('failure', $serviceName, 'reset=', '86400', 'actions=', 'restart/3000/restart/10000/none/0')
Set-InstallationMetadata $Version
Start-InstalledService
$committed = $true
if ($oldMoved) { Remove-Item -LiteralPath $backup -Recurse -Force; $oldMoved = $false }
Write-Host "Installed GP Connect $Version. Open it from the Start menu."
} else {
if (!$existing) {
if (Test-Path -LiteralPath $destination) { throw 'The service is not registered. Review the installation folder before removing it.' }
Write-Host 'GP Connect is not installed.'
return
}
Wait-ForApplications
$serviceStopped = $true
Stop-InstalledService
Assert-NetworkClean
Wait-ForRuntimeRelease
# Move first: a locked runtime aborts while its registration and files are intact.
Move-InstalledDirectoryToBackup
$oldMoved = $true
Invoke-ServiceCommand @('delete', $serviceName)
$committed = $true
Remove-Item -LiteralPath $backup -Recurse -Force
$oldMoved = $false
if (Test-Path -LiteralPath $shortcutPath) { Remove-Item -LiteralPath $shortcutPath -Force }
if (Test-Path $uninstallKey) { Remove-Item $uninstallKey -Recurse -Force }
if (Test-Path $recoveryKey) { Remove-Item $recoveryKey -Force }
Remove-OwnedCallback
Write-Host 'Removed GP Connect. User settings and service logs are kept.'
}
} catch {
$failure = $_
if (!$committed) {
try {
if ($newMoved) { Stop-InstalledService; Remove-Item -LiteralPath $destination -Recurse -Force }
if ($oldMoved) { Move-Item -LiteralPath $backup -Destination $destination; $oldMoved = $false }
if ($createdService) { Invoke-ServiceCommand @('delete', $serviceName) }
if ($newMoved) { Restore-InstallationMetadata }
if ($existing -and $serviceStopped -and $wasRunning) { Start-InstalledService }
} catch {
Write-Host "Could not restore GP Connect: $($_.Exception.Message)"
Write-Host "Keep any retained files in $backup and run the installer again after restoring the installation."
}
}
Write-Host "Installation failed: $($failure.Exception.Message)"
Write-Host "Details: $(Join-Path $state 'installer.log')"
throw $failure
} finally {
if ($stage -and (Test-Path -LiteralPath $stage)) {
try { Remove-Item -LiteralPath $stage -Recurse -Force } catch { Write-Warning "Could not remove temporary files: $stage" }
}
if ($transcript) { Stop-Transcript | Out-Null }
if ($owned) { $mutex.ReleaseMutex() }
$mutex.Dispose()
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB