ruen-ui/Tools/Resolve-RuenDependencies.ps1

147 lines
7.2 KiB
PowerShell

function Assert-RuenSpace([string]$Path, [long]$Required) {
$item = Get-Item -LiteralPath $Path
$free = $item.PSDrive.Free
if ($null -ne $free -and $free -lt $Required) { throw ('Not enough disk space at ' + $Path + ' for download, extraction and backups.') }
}
# Download directly from addon authors. Called only after package verification.
function Get-RuenDependencyList([string]$Bundle, [string]$Voices) {
$lock = Get-Content -LiteralPath (Join-Path $Bundle 'dependencies.lock.json') -Raw | ConvertFrom-Json
if ($lock.format -ne 1 -or $lock.interface -ne 16001) { throw 'Unsupported dependency lock.' }
$groups = @('base')
if ($Voices -ne 'none') { $groups += 'en' }
if ($Voices -eq 'enru') { $groups += 'ru' }
$names = @{}
foreach ($p in @($lock.packages | Where-Object { $_.group -in $groups })) {
if ($p.id -notmatch '^[A-Za-z0-9_]+$' -or $p.sha256 -notmatch '^[0-9a-f]{64}$' -or
([uri]$p.url).Scheme -ne 'https' -or $p.bytes -le 0 -or $p.bytes -gt 2000000000) {
throw 'Invalid pinned dependency.'
}
foreach ($name in $p.folders) {
if ($name -notmatch '^[A-Za-z0-9_]+$' -or $names.ContainsKey($name) -or $name -eq 'RuenUI') { throw 'Invalid addon folder.' }
$names[$name] = $true
}
$p
}
}
function Test-RuenDependency([string]$Folder) {
$toc = Join-Path $Folder ((Split-Path -Leaf $Folder) + '.toc')
return (Test-Path -LiteralPath $toc -PathType Leaf) -and
[bool](Select-String -LiteralPath $toc -Pattern '^## Interface:.*\b16001\b' -Quiet)
}
function Get-RuenArchive($Package, [string]$Cache) {
$file = Join-Path $Cache ($Package.id + '-' + $Package.sha256.Substring(0, 12) + '.zip')
Assert-NoLinks $file
if (Test-Path -LiteralPath $file -PathType Leaf) {
if ((Get-Item -LiteralPath $file).Length -eq $Package.bytes -and
(Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -eq $Package.sha256) { return $file }
}
Assert-RuenSpace $Cache ($Package.bytes + $Package.max_unpacked_bytes + 134217728)
$part = [IO.Path]::ChangeExtension($file, '.part')
Assert-NoLinks $part
Write-Host ("Downloading {0} ({1} MB)..." -f $Package.id, [math]::Round($Package.bytes / 1000000))
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$request = [Net.HttpWebRequest]::Create($Package.url)
$request.UserAgent = 'RuenUI-Installer/1'
$request.Timeout = 60000
$request.ReadWriteTimeout = 60000
$response = $null; $inputStream = $null; $outputStream = $null
try {
$response = $request.GetResponse()
if ($response.ResponseUri.Scheme -ne 'https') { throw 'Refusing a non-HTTPS download redirect.' }
$inputStream = $response.GetResponseStream()
$outputStream = [IO.File]::Create($part)
$buffer = New-Object byte[] 1048576
[long]$total = 0
while (($n = $inputStream.Read($buffer, 0, $buffer.Length)) -gt 0) {
$total += $n
if ($total -gt $Package.bytes) { throw 'Download exceeds pinned size.' }
$outputStream.Write($buffer, 0, $n)
}
$outputStream.Dispose(); $outputStream = $null
if ($total -ne $Package.bytes -or (Get-FileHash -LiteralPath $part -Algorithm SHA256).Hash -ne $Package.sha256) {
throw ('Dependency checksum mismatch: ' + $Package.id)
}
Move-Item -LiteralPath $part -Destination $file -Force
# Bound this cache to one archive per locked addon package.
foreach ($old in @(Get-ChildItem -LiteralPath $Cache -File)) {
if ($old.FullName -ne $file -and $old.Name -match ('^' + [regex]::Escape($Package.id) + '-[0-9a-f]{12}\.zip$')) {
Assert-NoLinks $old.FullName
Remove-Item -LiteralPath $old.FullName
}
}
return $file
} finally {
if ($outputStream) { $outputStream.Dispose() }
if ($inputStream) { $inputStream.Dispose() }
if ($response) { $response.Dispose() }
if (Test-Path -LiteralPath $part) { Remove-Item -LiteralPath $part }
}
}
function Get-RuenArchivePath([string]$Name) {
if (-not $Name -or $Name.Contains('\') -or $Name.Contains(':') -or $Name.StartsWith('/')) { throw 'Unsafe archive filename.' }
$parts = $Name.TrimEnd('/').Split('/')
foreach ($part in $parts) {
if (-not $part -or $part -in @('.', '..') -or $part -match '[\x00-\x1f<>"|?*]' -or
$part -match '[ .]$' -or $part -match '^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\..*)?$') {
throw ('Unsafe archive filename: ' + $Name)
}
}
return $Name.TrimEnd('/')
}
function Expand-RuenArchive($Package, [string]$Archive, [string]$Stage) {
Add-Type -AssemblyName System.IO.Compression.FileSystem
$zip = [IO.Compression.ZipFile]::OpenRead($Archive)
try {
if ($zip.Entries.Count -gt 100000) { throw 'Archive has too many entries.' }
$seen = @{}; [long]$total = 0
foreach ($entry in $zip.Entries) {
$rel = Get-RuenArchivePath $entry.FullName
if ($seen.ContainsKey($rel)) { throw ('Duplicate archive filename: ' + $rel) }
$seen[$rel] = $true
if ((($entry.ExternalAttributes -shr 16) -band 61440) -eq 40960) { throw 'Archive links are not allowed.' }
$total += $entry.Length
if ($total -gt $Package.max_unpacked_bytes) { throw 'Archive expands beyond its limit.' }
}
Assert-RuenSpace $Stage ($total + 134217728)
foreach ($entry in $zip.Entries) {
$rel = Get-RuenArchivePath $entry.FullName
if ($rel.Split('/')[0] -notin $Package.folders) { continue }
$target = Safe-RelativePath $Stage $rel
if ($entry.FullName.EndsWith('/')) { [void][IO.Directory]::CreateDirectory($target); continue }
[void][IO.Directory]::CreateDirectory((Split-Path -Parent $target))
[IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $target, $false)
}
} finally { $zip.Dispose() }
foreach ($folder in $Package.folders) {
if (-not (Test-RuenDependency (Join-Path $Stage $folder))) { throw ('Missing Forever TOC: ' + $folder) }
}
}
function Prepare-RuenDependencies([string]$Bundle, [string]$Game, [string]$Stage, [string]$Voices, [string]$Cache) {
$sources = @{ RuenUI = (Join-Path $Bundle 'RuenUI') }
$enabled = @('RuenUI')
foreach ($package in @(Get-RuenDependencyList $Bundle $Voices)) {
$missing = @()
foreach ($folder in $package.folders) {
$target = Join-Path $Game ('Interface/AddOns/' + $folder)
Assert-NoNestedLinks $target
if (Test-Path -LiteralPath $target) {
if (-not (Test-RuenDependency $target)) { throw ("Existing $folder is not marked compatible with Forever. Update it from its author first.") }
Write-Host ("Keeping existing $folder")
} else { $missing += $folder }
$enabled += $folder
}
if ($missing.Count) {
$archive = Get-RuenArchive $package $Cache
Expand-RuenArchive $package $archive $Stage
foreach ($folder in $missing) { $sources[$folder] = Join-Path $Stage $folder }
}
}
return @{ Sources = $sources; Enabled = $enabled }
}