| 1 | # Shared verified package preparation for initial installation and maintenance. |
| 2 | function Get-PinnedPackage($Spec, [string]$Cache) { |
| 3 | $file = Join-Path $Cache $Spec.filename |
| 4 | $cached=Test-Path -LiteralPath $file |
| 5 | if ($cached) { |
| 6 | $item=Get-Item -LiteralPath $file -Force |
| 7 | if ($item -isnot [IO.FileInfo] -or $item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'The download cache contains an invalid file.' } |
| 8 | if ((Get-FileHash -LiteralPath $file).Hash -eq $Spec.sha256) { return $file } |
| 9 | # Keep the old cache entry until a complete replacement has passed verification. |
| 10 | } |
| 11 | $tmp = $file+'.'+[guid]::NewGuid()+'.download' |
| 12 | try { |
| 13 | Invoke-WebRequest -UseBasicParsing -Uri $Spec.url -OutFile $tmp |
| 14 | if ((Get-FileHash -LiteralPath $tmp).Hash -ne $Spec.sha256) { throw ('Package verification failed: '+$Spec.filename) } |
| 15 | if ($cached) { [IO.File]::Replace($tmp,$file,[Management.Automation.Language.NullString]::Value) } |
| 16 | else { [IO.File]::Move($tmp,$file) } |
| 17 | } finally { if ([IO.File]::Exists($tmp)) { [IO.File]::Delete($tmp) } } |
| 18 | return $file |
| 19 | } |
| 20 | |
| 21 | function Expand-PinnedTar([string]$File,[string]$Destination) { |
| 22 | $null=New-Item -ItemType Directory -Path $Destination -Force |
| 23 | & (Join-Path $env:SystemRoot 'System32/tar.exe') -xf $File -C $Destination --strip-components 1 |
| 24 | if ($LASTEXITCODE) { throw ('Package extraction failed: '+[IO.Path]::GetFileName($File)) } |
| 25 | } |