config-central/src/Adapters.psm1

230 lines
12 KiB
PowerShell

Set-StrictMode -Version Latest
function Get-TextHash {
param([AllowEmptyString()][string]$Text)
$bytes = [Text.Encoding]::UTF8.GetBytes($Text)
$hash = [Security.Cryptography.SHA256]::HashData($bytes)
[Convert]::ToHexString($hash).ToLowerInvariant()
}
function Get-ObjectHash {
param($Value)
Get-TextHash -Text ($Value | ConvertTo-Json -Depth 16 -Compress)
}
function Read-IniValues {
param([Parameter(Mandatory)][string]$Path)
$result = [ordered]@{}
$section = ''
foreach ($line in @(Get-Content -LiteralPath $Path -ErrorAction Stop)) {
$trimmed = $line.Trim()
if (-not $trimmed -or $trimmed.StartsWith(';') -or $trimmed.StartsWith('#')) { continue }
if ($trimmed -match '^\[(.+)\]$') {
$section = $Matches[1]
if (-not $result.Contains($section)) { $result[$section] = [ordered]@{} }
continue
}
$separator = $line.IndexOf('=')
if ($separator -lt 1) { throw "Invalid INI line in '$Path': $line" }
$key = $line.Substring(0, $separator).Trim()
$value = $line.Substring($separator + 1).Trim()
if (-not $result.Contains($section)) { $result[$section] = [ordered]@{} }
if ($result[$section].Contains($key)) { throw "Duplicate INI key '$section/$key' in '$Path'." }
$result[$section][$key] = $value
}
return $result
}
function Get-IniSnapshot {
param([string]$Path, $Desired)
$actual = if (Test-Path -LiteralPath $Path -PathType Leaf) { Read-IniValues -Path $Path } else { [ordered]@{} }
$snapshot = [ordered]@{}
$present = 0
foreach ($section in $Desired.Keys) {
$snapshot[$section] = [ordered]@{}
foreach ($key in $Desired[$section].Keys) {
if ($actual.Contains($section) -and $actual[$section].Contains($key)) {
$snapshot[$section][$key] = [string]$actual[$section][$key]
$present++
}
else { $snapshot[$section][$key] = $null }
}
}
[pscustomobject]@{ values = $snapshot; hash = Get-ObjectHash $snapshot; present = $present }
}
function Merge-IniFile {
param([string]$Target, $Desired)
$lines = [Collections.Generic.List[string]]::new()
if (Test-Path -LiteralPath $Target -PathType Leaf) {
foreach ($line in @(Get-Content -LiteralPath $Target)) { $lines.Add($line) }
}
$seen = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
$section = ''
for ($index = 0; $index -lt $lines.Count; $index++) {
$trimmed = $lines[$index].Trim()
if ($trimmed -match '^\[(.+)\]$') { $section = $Matches[1]; continue }
$separator = $lines[$index].IndexOf('=')
if ($separator -lt 1) { continue }
$key = $lines[$index].Substring(0, $separator).Trim()
if ($Desired.Contains($section) -and $Desired[$section].Contains($key)) {
$lines[$index] = "$key=$($Desired[$section][$key])"
[void]$seen.Add("$section`0$key")
}
}
foreach ($desiredSection in $Desired.Keys) {
$missing = @($Desired[$desiredSection].Keys | Where-Object { -not $seen.Contains("$desiredSection`0$_") })
if ($missing.Count -eq 0) { continue }
if ($lines.Count -gt 0 -and $lines[$lines.Count - 1] -ne '') { $lines.Add('') }
if ($desiredSection) { $lines.Add("[$desiredSection]") }
foreach ($key in $missing) { $lines.Add("$key=$($Desired[$desiredSection][$key])") }
}
return (($lines -join [Environment]::NewLine) + [Environment]::NewLine)
}
function Read-RegistryDeclaration {
param([string]$Path)
$declaration = Get-Content -LiteralPath $Path -Raw | ConvertFrom-Json -Depth 16
if ($declaration.schemaVersion -ne 1 -or $declaration.values -isnot [System.Array]) { throw "Invalid registry declaration '$Path'." }
$seen = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
foreach ($value in $declaration.values) {
foreach ($required in @('path', 'name', 'type', 'value')) {
if ($null -eq $value.PSObject.Properties[$required]) { throw "Registry declaration '$Path' is missing '$required'." }
}
if ($value.path -match '(^|\\)\.\.?($|\\)' -or [IO.Path]::IsPathFullyQualified([string]$value.path)) { throw "Unsafe registry subpath '$($value.path)'." }
if ($value.name -notmatch '^[^\\/]+$') { throw "Unsafe registry value name '$($value.name)'." }
if ($value.type -notin @('String', 'ExpandString', 'DWord', 'QWord', 'MultiString', 'Binary')) { throw "Unsupported registry type '$($value.type)'." }
if (-not $seen.Add("$($value.path)\$($value.name)")) { throw "Duplicate registry value '$($value.path)\$($value.name)'." }
}
return $declaration
}
function Get-RegistrySnapshot {
param([string]$Root, $Declaration)
$snapshot = [ordered]@{}
$present = 0
foreach ($entry in $Declaration.values) {
$key = "$($entry.path)\$($entry.name)"
$registryPath = if ([string]::IsNullOrWhiteSpace([string]$entry.path)) { $Root } else { Join-Path $Root $entry.path }
try {
$property = Get-ItemProperty -LiteralPath $registryPath -Name $entry.name -ErrorAction Stop
$snapshot[$key] = $property.($entry.name)
$present++
}
catch { $snapshot[$key] = $null }
}
[pscustomobject]@{ values = $snapshot; hash = Get-ObjectHash $snapshot; present = $present }
}
function Get-HostsDeclaration {
param([string]$Path)
$lines = [Collections.Generic.List[string]]::new()
foreach ($line in @(Get-Content -LiteralPath $Path)) {
$trimmed = $line.Trim()
if (-not $trimmed -or $trimmed.StartsWith('#')) { continue }
$parts = @($trimmed -split '\s+')
$address = $null
if ($parts.Count -lt 2 -or -not [Net.IPAddress]::TryParse($parts[0], [ref]$address)) { throw "Invalid hosts entry in '$Path': $line" }
foreach ($hostName in $parts[1..($parts.Count - 1)]) {
if ($hostName.StartsWith('#')) { break }
if ($hostName -notmatch '^[A-Za-z0-9._-]+$') { throw "Invalid host name '$hostName' in '$Path'." }
}
$lines.Add($trimmed)
}
return @($lines)
}
function Get-HostsBlock {
param([string]$Path, [string]$Name)
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return $null }
$begin = "# BEGIN CONFIG CENTRAL: $Name"
$end = "# END CONFIG CENTRAL: $Name"
$inside = $false
$found = $false
$lines = [Collections.Generic.List[string]]::new()
foreach ($line in @(Get-Content -LiteralPath $Path)) {
if ($line.Trim() -eq $begin) { if ($found -or $inside) { throw "Duplicate hosts block '$Name'." }; $inside = $true; $found = $true; continue }
if ($line.Trim() -eq $end) { if (-not $inside) { throw "Unmatched hosts block end '$Name'." }; $inside = $false; continue }
if ($inside) { $lines.Add($line.Trim()) }
}
if ($inside) { throw "Unclosed hosts block '$Name'." }
if (-not $found) { return $null }
return @($lines)
}
function Get-AdapterPlan {
param($Config, [string]$Source, [string]$Target, $Record)
if ($Config.mode -eq 'ini-overlay') {
$desired = Read-IniValues -Path $Source
$count = @($desired.Keys | ForEach-Object { $desired[$_].Count } | Measure-Object -Sum).Sum
if (-not $count) { return [pscustomobject]@{ action = 'None'; reason = 'INI overlay has no active keys'; desired = $desired; desiredHash = Get-ObjectHash $desired; currentHash = $null; requiresAdmin = $false } }
$current = Get-IniSnapshot -Path $Target -Desired $desired
$desiredHash = Get-ObjectHash $desired
}
elseif ($Config.mode -eq 'registry') {
if (-not $IsWindows) { throw 'Registry configs can only be planned on Windows.' }
if ($Target -notmatch '^HKCU:\\Software\\MPC-HC\\MPC-HC(?:\\.*)?$') { throw "Registry target is outside the allowed MPC-HC key: '$Target'." }
$desired = Read-RegistryDeclaration -Path $Source
if ($desired.values.Count -eq 0) { return [pscustomobject]@{ action = 'None'; reason = 'Registry declaration has no values'; desired = $desired; desiredHash = Get-ObjectHash $desired; currentHash = $null; requiresAdmin = $false } }
$current = Get-RegistrySnapshot -Root $Target -Declaration $desired
$desiredValues = [ordered]@{}
foreach ($entry in $desired.values) { $desiredValues["$($entry.path)\$($entry.name)"] = $entry.value }
$desiredHash = Get-ObjectHash $desiredValues
}
elseif ($Config.mode -eq 'hosts-block') {
$desired = @(Get-HostsDeclaration -Path $Source)
if ($desired.Count -eq 0) { return [pscustomobject]@{ action = 'None'; reason = 'Hosts declaration has no active entries'; desired = $desired; desiredHash = Get-ObjectHash $desired; currentHash = $null; requiresAdmin = $true } }
$currentBlock = Get-HostsBlock -Path $Target -Name $Config.name
$current = [pscustomobject]@{ values = $currentBlock; hash = if ($null -eq $currentBlock) { $null } else { Get-ObjectHash @($currentBlock) }; present = if ($null -eq $currentBlock) { 0 } else { @($currentBlock).Count } }
$desiredHash = Get-ObjectHash $desired
}
else { throw "Unknown adapter mode '$($Config.mode)'." }
$lastHash = if ($null -ne $Record -and $Record.Contains('deployedHash')) { [string]$Record.deployedHash } else { $null }
if ($null -eq $Record -and $current.present -eq 0) { $action = 'Create'; $reason = 'Managed values are absent' }
elseif ($null -eq $Record -and $current.hash -eq $desiredHash) { $action = 'Adopt'; $reason = 'Managed values already match' }
elseif ($null -eq $Record) { $action = 'Conflict'; $reason = 'Existing managed values are not owned by Config Central' }
elseif ($current.hash -ne $lastHash) { $action = 'Conflict'; $reason = 'Managed values were edited locally' }
elseif ($current.hash -eq $desiredHash) { $action = 'None'; $reason = 'Managed values are current' }
else { $action = 'Update'; $reason = 'Repository values changed' }
[pscustomobject]@{ action = $action; reason = $reason; desired = $desired; desiredHash = $desiredHash; currentHash = $current.hash; requiresAdmin = ($Config.mode -eq 'hosts-block') }
}
function Set-RegistryDeclaration {
param([string]$Root, $Declaration)
foreach ($entry in $Declaration.values) {
$path = if ([string]::IsNullOrWhiteSpace([string]$entry.path)) { $Root } else { Join-Path $Root $entry.path }
[void](New-Item -Path $path -Force)
$value = switch ($entry.type) {
'DWord' { [uint32]$entry.value }
'QWord' { [uint64]$entry.value }
'Binary' { [byte[]]@($entry.value) }
'MultiString' { [string[]]@($entry.value) }
default { [string]$entry.value }
}
[void](New-ItemProperty -LiteralPath $path -Name $entry.name -PropertyType $entry.type -Value $value -Force)
}
}
function Set-HostsBlockContent {
param([string]$Target, [string]$Name, [string[]]$Lines)
$begin = "# BEGIN CONFIG CENTRAL: $Name"
$end = "# END CONFIG CENTRAL: $Name"
$existing = if (Test-Path -LiteralPath $Target -PathType Leaf) { [Collections.Generic.List[string]]@(Get-Content -LiteralPath $Target) } else { [Collections.Generic.List[string]]::new() }
$output = [Collections.Generic.List[string]]::new()
$inside = $false
foreach ($line in $existing) {
if ($line.Trim() -eq $begin) { $inside = $true; continue }
if ($line.Trim() -eq $end) { $inside = $false; continue }
if (-not $inside) { $output.Add($line) }
}
while ($output.Count -gt 0 -and -not $output[$output.Count - 1].Trim()) { $output.RemoveAt($output.Count - 1) }
if ($output.Count -gt 0) { $output.Add('') }
$output.Add($begin)
foreach ($line in $Lines) { $output.Add($line) }
$output.Add($end)
(($output -join [Environment]::NewLine) + [Environment]::NewLine)
}
Export-ModuleMember -Function Get-ObjectHash, Read-IniValues, Get-IniSnapshot, Merge-IniFile, Read-RegistryDeclaration, Get-RegistrySnapshot, Get-HostsDeclaration, Get-HostsBlock, Get-AdapterPlan, Set-RegistryDeclaration, Set-HostsBlockContent