feat: build and publish Windows NSH packages with verified updates

This commit is contained in:
Kevin Yue committed 2026-11-14 23:10:21 +08:00
1 parent 2c9d227f02
commit 560d2b2de7
113 files changed
+7264 -801

No files matched your search

+62
View File
@@ -0,0 +1,62 @@
# 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 /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
```
`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 Finish page uses `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. Authenticode setup is separate;
WinSparkle must still verify the installer payload signature before handoff.
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.
+83
View File
@@ -0,0 +1,83 @@
Unicode true
RequestExecutionLevel admin
!include "MUI2.nsh"
!include "x64.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 BUILD_VERSION
!define BUILD_VERSION "${PRODUCT_VERSION}.0"
!endif
!ifndef DISPLAY_VERSION
!define DISPLAY_VERSION "${PRODUCT_VERSION}"
!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
!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."
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_PAGE_FINISH
!insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_INSTFILES
!insertmacro MUI_LANGUAGE "English"
Function .onInit
${IfNot} ${RunningX64}
MessageBox MB_OK|MB_ICONSTOP "GP Connect requires 64-bit Windows."
Abort
${EndIf}
SetRegView 64
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.
+370
View File
@@ -0,0 +1,370 @@
#Requires -RunAsAdministrator
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)][ValidateSet('Install', 'Uninstall')][string]$Action,
[string]$SourceDirectory,
[string]$Version,
[switch]$ConsumeSource
)
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
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-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 = 'GP Connect'
$shortcut.IconLocation = (Join-Path $destination 'gpgui.exe') + ',0'
$shortcut.Save()
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', '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 }
if ($info.product -ne 'GP Connect' -or $info.architecture -ne 'x64' -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, x64.'
}
$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', '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.FullName.Substring($source.Length).TrimStart('\')
$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