CaiWuXiTong/scripts/keep-upstream-tunnel.ps1

111 lines
2.9 KiB
PowerShell

#Requires -Version 5.1
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidatePattern('^[A-Za-z0-9._:-]+$')]
[string] $ServerHost,
[ValidateRange(1, 65535)]
[int] $ServerPort = 22,
[ValidatePattern('^[A-Za-z0-9._-]+$')]
[string] $RemoteUser = 'caiwu-tunnel',
[Parameter(Mandatory = $true)]
[string] $PrivateKeyPath,
[Parameter(Mandatory = $true)]
[ValidatePattern('^[A-Za-z0-9._:-]+$')]
[string] $RemoteBindAddress,
[Parameter(Mandatory = $true)]
[ValidateRange(1, 65535)]
[int] $RemoteBindPort,
[Parameter(Mandatory = $true)]
[ValidatePattern('^[A-Za-z0-9._:-]+$')]
[string] $UpstreamHost,
[ValidateRange(1, 65535)]
[int] $UpstreamPort = 1433,
[ValidateRange(10, 300)]
[int] $RetrySeconds = 30,
[switch] $Once
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$sshCommand = Get-Command 'ssh.exe' -ErrorAction Stop
$resolvedKeyPath = (Resolve-Path -LiteralPath $PrivateKeyPath -ErrorAction Stop).Path
$identity = '{0}|{1}|{2}|{3}' -f $ServerHost, $ServerPort, $RemoteBindAddress, $RemoteBindPort
$sha256 = [System.Security.Cryptography.SHA256]::Create()
try {
$identityBytes = [System.Text.Encoding]::UTF8.GetBytes($identity)
$identityHash = [System.BitConverter]::ToString($sha256.ComputeHash($identityBytes)).Replace('-', '')
}
finally {
$sha256.Dispose()
}
$mutex = New-Object System.Threading.Mutex($false, ('Local\CaiWuXiTong-UpstreamTunnel-{0}' -f $identityHash.Substring(0, 20)))
$ownsMutex = $false
try {
try {
$ownsMutex = $mutex.WaitOne(0)
}
catch [System.Threading.AbandonedMutexException] {
$ownsMutex = $true
}
if (-not $ownsMutex) {
Write-Output 'The read-only upstream tunnel is already managed by another local process.'
exit 0
}
$forward = '{0}:{1}:{2}:{3}' -f $RemoteBindAddress, $RemoteBindPort, $UpstreamHost, $UpstreamPort
$destination = '{0}@{1}' -f $RemoteUser, $ServerHost
$sshArguments = @(
'-N',
'-T',
'-i', $resolvedKeyPath,
'-p', $ServerPort,
'-o', 'BatchMode=yes',
'-o', 'ConnectTimeout=10',
'-o', 'ExitOnForwardFailure=yes',
'-o', 'ServerAliveInterval=20',
'-o', 'ServerAliveCountMax=3',
'-o', 'StrictHostKeyChecking=accept-new',
'-o', 'TCPKeepAlive=yes',
'-o', 'LogLevel=ERROR',
'-R', $forward,
$destination
)
do {
& $sshCommand.Source @sshArguments
$exitCode = $LASTEXITCODE
if ($Once) {
exit $exitCode
}
Write-Warning ('The read-only upstream tunnel disconnected (SSH exit code {0}); retrying shortly.' -f $exitCode)
$retryDelay = $RetrySeconds + (Get-Random -Minimum 0 -Maximum 6)
Start-Sleep -Seconds $retryDelay
}
while ($true)
}
finally {
if ($ownsMutex) {
$mutex.ReleaseMutex()
}
$mutex.Dispose()
}