# Rouh on Windows, in one command (rouh-core task 186, step 186-04). In PowerShell: # # irm https://rouh.land/install.ps1 | iex # # A PREVIEW: it is built and checked on Linux and on GitHub's Windows machines, which cannot run # WSL2, and has not yet been run on a real Windows computer. INSTALL-WINDOWS.md in rouh-core says # exactly what has been proved and what has not. # # What it does, in order, and it can be run again at any time: # 1. checks this computer: Windows 10 2004 or Windows 11, a 64-bit Intel, AMD or Arm processor, # 8 GB of memory, 20 GB of free disk, and virtualisation switched on; # 2. switches WSL2 on (Windows' built-in Linux layer) when it is not: Windows asks for an # administrator's yes once, and may need one restart; # 3. gets Rouh's own Linux (Debian with Docker Engine, never Docker Desktop) and trusts nothing it # has not checked: rouh.land's record of it is signed with Rouh's release key, written below, and # the file must match the SHA-256 that record names, byte for byte, before WSL imports it; # 4. sets WSL up for a Linux that stays on: no shutting down when idle, and a memory cap so Windows # keeps enough (.wslconfig in your user folder; settings already there are kept); # 5. keeps Rouh running from sign-in (a task in Task Scheduler, for you only, no administrator); # 6. starts Rouh inside it with the same one command every Linux server runs # (https://rouh.land/install.sh: the signed release, the same containers as Mac and Linux); # 7. opens Rouh's setup in your browser, on this computer only (http://127.0.0.1:8420). # # After it, the same file is kept as %LOCALAPPDATA%\Rouh\rouh.ps1, Rouh's command on Windows: # powershell -ExecutionPolicy Bypass -File "$env:LOCALAPPDATA\Rouh\rouh.ps1" # open | status | update | back | compact | uninstall [-Keep | -Wipe] [-Yes] # Rouh for Windows (the tray app) runs the same commands from its menu. # # Settings, all optional, set before running it: # $env:ROUH_LAND = 'https://rouh.land' where the release, the record and install.sh come from # $env:ROUH_YES = '1' do not ask before installing # $env:ROUH_NO_OPEN = '1' do not open the browser at the end # $env:ROUH_WINDOWS_APP = '1' run by Rouh for Windows: it keeps Rouh running itself # $env:ROUH_DRY_RUN = '1' say each change it would make, and make none # Works in Windows PowerShell 5.1, which every Windows 10 and 11 has, and in PowerShell 7. # Everything runs inside a module of its own, so that run with irm ... | iex nothing of it (its # settings, its functions, a stop) leaks into, or closes, the PowerShell window it was typed in. $RouhPs1Path = $PSCommandPath New-Module -Name RouhInstall -ArgumentList $RouhPs1Path -ScriptBlock { param($ScriptPath) $ErrorActionPreference = 'Stop' Set-StrictMode -Version 2.0 # Windows PowerShell 5.1 on an older .NET may not offer TLS 1.2 by itself; rouh.land needs it. [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 # --- settings ------------------------------------------------------------------------------------ $script:RouhLand = if ($env:ROUH_LAND) { $env:ROUH_LAND.TrimEnd('/') } else { 'https://rouh.land' } $script:Distro = 'Rouh' $script:LinuxUser = 'rouh' $script:Port = 8420 $script:RouhHome = Join-Path $env:LOCALAPPDATA 'Rouh' $script:TaskName = 'Rouh keeps running' $script:DryRun = ($env:ROUH_DRY_RUN -eq '1') #: Rouh's release key: the public half of the Ed25519 key every release and record is signed with #: (rouh-core deploy/container/mac_release.py PUBLIC_KEYS, install.sh's KEY_RAW, Rouh for Mac's #: StackRelease.trustedKeys hold the same). $script:KeyId = 'rouh-mac-stack-1' $script:KeyRaw = 'XyU09FKab+ZrKEvIfHSaYvnLF3F8FSOnIdX8frWCjiA=' #: Cloudflare in front of rouh.land refuses some programs' own User-Agent; this one is Rouh's. $script:UserAgent = 'rouh-install-ps1/1 (Rouh for Windows; +https://rouh.land)' $script:MinBuild = 19041 $script:MinMemoryGB = 8 $script:MinDiskGB = 20 # --- Ed25519 signature check (RFC 8032, section 5.1.7), in plain PowerShell 5.1 --------------------- # Windows PowerShell has no Ed25519 of its own, and Windows ships no openssl, so the check that the # Linux installer does with openssl is done here with .NET's big integers and SHA-512. It only ever # verifies (no secret is involved), so being slow and simple is fine: about a second. Add-Type -AssemblyName System.Numerics $script:EdP = [System.Numerics.BigInteger]::Pow(2, 255) - 19 $script:EdL = [System.Numerics.BigInteger]::Pow(2, 252) + [System.Numerics.BigInteger]::Parse('27742317777372353535851937790883648493') function Get-EdMod([System.Numerics.BigInteger]$a, [System.Numerics.BigInteger]$m) { $r = [System.Numerics.BigInteger]::Remainder($a, $m) if ($r.Sign -lt 0) { $r = $r + $m } return $r } function Get-EdInv([System.Numerics.BigInteger]$a) { return [System.Numerics.BigInteger]::ModPow($a, $script:EdP - 2, $script:EdP) } function ConvertFrom-EdBytes([byte[]]$b) { # Little-endian, unsigned: .NET reads little-endian two's complement, so a zero byte is added. $u = New-Object byte[] ($b.Length + 1) [Array]::Copy($b, $u, $b.Length) return New-Object System.Numerics.BigInteger (, $u) } $script:EdD = Get-EdMod ((-121665) * (Get-EdInv 121666)) $script:EdP $script:EdI = [System.Numerics.BigInteger]::ModPow(2, ($script:EdP - 1) / 4, $script:EdP) # Points in extended coordinates (X, Y, Z, T), x = X/Z, y = Y/Z, x*y = T/Z. function Add-EdPoint($P, $Q) { $m = $script:EdP $A = Get-EdMod (($P[1] - $P[0]) * ($Q[1] - $Q[0])) $m $B = Get-EdMod (($P[1] + $P[0]) * ($Q[1] + $Q[0])) $m $C = Get-EdMod (2 * $P[3] * $Q[3] * $script:EdD) $m $D = Get-EdMod (2 * $P[2] * $Q[2]) $m $E = $B - $A; $F = $D - $C; $G = $D + $C; $H = $B + $A return @((Get-EdMod ($E * $F) $m), (Get-EdMod ($G * $H) $m), (Get-EdMod ($F * $G) $m), (Get-EdMod ($E * $H) $m)) } function Get-EdMultiple([System.Numerics.BigInteger]$s, $P) { $Q = @([System.Numerics.BigInteger]::Zero, [System.Numerics.BigInteger]::One, [System.Numerics.BigInteger]::One, [System.Numerics.BigInteger]::Zero) while ($s.Sign -gt 0) { if (-not $s.IsEven) { $Q = Add-EdPoint $Q $P } $P = Add-EdPoint $P $P $s = $s / 2 } return $Q } function ConvertFrom-EdPoint([byte[]]$b) { if ($b.Length -ne 32) { return $null } $m = $script:EdP $c = [byte[]]$b.Clone() $sign = ($c[31] -shr 7) -band 1 $c[31] = $c[31] -band 0x7f $y = ConvertFrom-EdBytes $c if ($y -ge $m) { return $null } $xx = Get-EdMod (($y * $y - 1) * (Get-EdInv ($script:EdD * $y * $y + 1))) $m if ($xx.IsZero) { if ($sign -eq 1) { return $null }; $x = [System.Numerics.BigInteger]::Zero } else { $x = [System.Numerics.BigInteger]::ModPow($xx, ($m + 3) / 8, $m) if (-not (Get-EdMod ($x * $x - $xx) $m).IsZero) { $x = Get-EdMod ($x * $script:EdI) $m } if (-not (Get-EdMod ($x * $x - $xx) $m).IsZero) { return $null } if ([int]($x % 2) -ne $sign) { $x = $m - $x } } return @($x, $y, [System.Numerics.BigInteger]::One, (Get-EdMod ($x * $y) $m)) } function Test-EdSamepoint($P, $Q) { $m = $script:EdP return ((Get-EdMod ($P[0] * $Q[2] - $Q[0] * $P[2]) $m).IsZero -and (Get-EdMod ($P[1] * $Q[2] - $Q[1] * $P[2]) $m).IsZero) } # Test-Ed25519 PUBLICKEY(32 bytes) MESSAGE(bytes) SIGNATURE(64 bytes): $true only for a good signature. function Test-Ed25519([byte[]]$PublicKey, [byte[]]$Message, [byte[]]$Signature) { if ($PublicKey.Length -ne 32 -or $Signature.Length -ne 64) { return $false } $A = ConvertFrom-EdPoint $PublicKey $Rb = [byte[]]$Signature[0..31] $R = ConvertFrom-EdPoint $Rb if ($null -eq $A -or $null -eq $R) { return $false } $S = ConvertFrom-EdBytes ([byte[]]$Signature[32..63]) if ($S -ge $script:EdL) { return $false } $sha = [System.Security.Cryptography.SHA512]::Create() $all = New-Object byte[] (64 + $Message.Length) [Array]::Copy($Rb, 0, $all, 0, 32); [Array]::Copy($PublicKey, 0, $all, 32, 32); [Array]::Copy($Message, 0, $all, 64, $Message.Length) $h = Get-EdMod (ConvertFrom-EdBytes $sha.ComputeHash($all)) $script:EdL $gy = Get-EdMod (4 * (Get-EdInv 5)) $script:EdP $gyBytes = $gy.ToByteArray() $g = New-Object byte[] 32 [Array]::Copy($gyBytes, $g, [Math]::Min(32, $gyBytes.Length)) $B = ConvertFrom-EdPoint $g $left = Get-EdMultiple $S $B $right = Add-EdPoint $R (Get-EdMultiple $h $A) return (Test-EdSamePoint $left $right) } # --- saying it ------------------------------------------------------------------------------------ function Write-Step([string]$Text) { Write-Host ''; Write-Host $Text -ForegroundColor White } function Write-Good([string]$Text) { Write-Host " [ok] $Text" -ForegroundColor Green } function Write-Note([string]$Text) { Write-Host " [!] $Text" -ForegroundColor Yellow } function Write-Line([string]$Text) { Write-Host " $Text" } # A stop: the one way anything here gives up, with the reason in plain words. function Stop-Rouh([string]$Why) { throw "ROUH-STOP:$Why" } # --- everything that touches Windows goes through these, so a dry run and a test can stand in ---- # wsl.exe, or (only for a test) the stand-in ROUH_WSL_EXE names. function Get-WslExe { if ($env:ROUH_WSL_EXE) { return $env:ROUH_WSL_EXE } return 'wsl.exe' } # Invoke-Wsl @(ARGS): wsl.exe, its words as UTF-8 (WSL_UTF8), and its exit code. Returns # @{ Code; Out } where Out is every line it printed. function Invoke-Wsl { param([string[]]$WslArgs, [switch]$Changes, [switch]$Live) if ($script:DryRun -and $Changes) { Write-Line "(dry run) wsl.exe $($WslArgs -join ' ')" return @{ Code = 0; Out = @() } } $env:WSL_UTF8 = '1' $exe = Get-WslExe $prev = $ErrorActionPreference; $ErrorActionPreference = 'Continue' # With WSL_UTF8 wsl.exe and the Linux inside both write UTF-8 (install.sh's marks, Docker's # progress); Windows PowerShell 5.1 would read it in the console's old code page. $enc = $null try { $enc = [Console]::OutputEncoding; [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false } catch { $enc = $null } try { if ($Live) { $out = New-Object System.Collections.Generic.List[string] & $exe @WslArgs 2>&1 | ForEach-Object { $s = "$_"; $out.Add($s); Write-Line $s } return @{ Code = $LASTEXITCODE; Out = $out.ToArray() } } $lines = & $exe @WslArgs 2>&1 | ForEach-Object { "$_" } return @{ Code = $LASTEXITCODE; Out = @($lines) } } catch { return @{ Code = 127; Out = @("$_") } } finally { $ErrorActionPreference = $prev if ($null -ne $enc) { try { [Console]::OutputEncoding = $enc } catch { $null = $_ } } } } # In Rouh's Linux, as its user: rouh-wsl COMMAND, the one contract with the Linux side. function Invoke-RouhWsl([string]$Command, [switch]$Changes, [switch]$Live) { return Invoke-Wsl @('-d', $script:Distro, '-u', $script:LinuxUser, '--cd', '~', '--', '/usr/local/bin/rouh-wsl', $Command) -Changes:$Changes -Live:$Live } function Get-SystemFacts { $os = Get-CimInstance Win32_OperatingSystem $cs = Get-CimInstance Win32_ComputerSystem $cpu = @(Get-CimInstance Win32_Processor)[0] $drive = Get-PSDrive -Name ($env:LOCALAPPDATA.Substring(0, 1)) $arch = $env:PROCESSOR_ARCHITEW6432 if (-not $arch) { $arch = $env:PROCESSOR_ARCHITECTURE } return @{ Caption = [string]$os.Caption; Build = [int]$os.BuildNumber; Arch = [string]$arch MemoryGB = [math]::Round($cs.TotalPhysicalMemory / 1GB); FreeDiskGB = [math]::Floor($drive.Free / 1GB) Hypervisor = [bool]$cs.HypervisorPresent; VirtFirmware = [bool]$cpu.VirtualizationFirmwareEnabled Cores = [int]$cs.NumberOfLogicalProcessors } } function Get-RouhJson([string]$Path) { return Invoke-RestMethod -UseBasicParsing -Uri "$script:RouhLand$Path" -TimeoutSec 60 -UserAgent $script:UserAgent } function Save-RouhDownload([string]$Url, [string]$To) { if (Get-Command curl.exe -ErrorAction SilentlyContinue) { & curl.exe -fL --retry 3 --progress-bar -o $To $Url if ($LASTEXITCODE -ne 0) { Stop-Rouh "the download of Rouh's Linux stopped (curl said $LASTEXITCODE). Run this again." } } else { $pp = $ProgressPreference; $ProgressPreference = 'SilentlyContinue' try { Invoke-WebRequest -UseBasicParsing -Uri $Url -OutFile $To } finally { $ProgressPreference = $pp } } } function Get-CurrentUserName { return [Security.Principal.WindowsIdentity]::GetCurrent().Name } function Start-Elevated([string]$File, [string[]]$Arguments) { if ($script:DryRun) { Write-Line "(dry run) as administrator: $File $($Arguments -join ' ')"; return 0 } $p = Start-Process -FilePath $File -ArgumentList $Arguments -Verb RunAs -Wait -PassThru return $p.ExitCode } function Open-Browser([string]$Url) { if ($script:DryRun) { Write-Line "(dry run) open $Url"; return } Start-Process $Url } function Test-RouhAnswers { try { $r = Invoke-WebRequest -UseBasicParsing -Uri "http://127.0.0.1:$script:Port/healthz" -TimeoutSec 10 return ($r.StatusCode -eq 200) } catch { return $false } } # --- 1. this computer --------------------------------------------------------------------------------- function Test-Computer { Write-Step 'Checking this computer' $f = Get-SystemFacts if ($f.Build -lt $script:MinBuild) { Stop-Rouh "Rouh needs Windows 10 version 2004 (build 19041) or Windows 11, and this is $($f.Caption), build $($f.Build). Update Windows, then run this again." } if ($f.Build -ge 22000) { Write-Good "$($f.Caption), build $($f.Build)" } else { Write-Note "$($f.Caption), build $($f.Build): Rouh is tested first on Windows 11; this may work" } switch ($f.Arch) { 'AMD64' { $script:Arch = 'x64'; Write-Good '64-bit Intel or AMD processor' } 'ARM64' { $script:Arch = 'arm64'; Write-Good '64-bit Arm processor (Rouh''s Arm build)' } default { Stop-Rouh "Rouh needs a 64-bit Intel, AMD or Arm processor, and this one is $($f.Arch)." } } if ($f.Cores -lt 2) { Stop-Rouh "Rouh needs at least 2 processor cores, and this computer has $($f.Cores)." } if ($f.MemoryGB -lt $script:MinMemoryGB) { Stop-Rouh "Rouh needs a computer with at least $($script:MinMemoryGB) GB of memory (4 for Rouh, the rest for Windows), and this one has $($f.MemoryGB) GB." } $script:MemoryCapGB = [int][math]::Min(16, [math]::Max(4, [math]::Floor($f.MemoryGB / 2))) Write-Good "$($f.MemoryGB) GB of memory; Rouh's Linux may use up to $($script:MemoryCapGB) GB" if ($f.FreeDiskGB -lt $script:MinDiskGB) { Stop-Rouh "Rouh needs at least $($script:MinDiskGB) GB of free disk on drive $($env:LOCALAPPDATA.Substring(0,2)), and there is $($f.FreeDiskGB) GB." } Write-Good "$($f.FreeDiskGB) GB of free disk" if (-not $f.Hypervisor -and -not $f.VirtFirmware) { Stop-Rouh 'virtualisation is switched off in this computer''s firmware (BIOS or UEFI), and WSL2 needs it. Restart into the firmware settings, switch on Intel VT-x or AMD-V (SVM), save, and run this again.' } Write-Good 'Virtualisation is on' return $f } # --- 2. WSL2 itself ----------------------------------------------------------------------------------- # Get-WslVersion: the WSL version as [version], or $null when WSL is not installed (or is the old # one built into Windows, which has no --version). function Get-WslVersion { if (-not (Get-Command (Get-WslExe) -ErrorAction SilentlyContinue)) { return $null } $r = Invoke-Wsl @('--version') if ($r.Code -ne 0) { return $null } foreach ($line in $r.Out) { if ($line -match '(\d+\.\d+\.\d+(\.\d+)?)') { return [version]$Matches[1] } } return $null } function Enable-Wsl { Write-Step 'WSL2, Windows'' built-in Linux layer' $v = Get-WslVersion if ($null -ne $v -and $v -ge [version]'2.0.0') { Write-Good "WSL $v"; return } if ($null -ne $v) { Write-Line "WSL $v is older than Rouh needs (2.0.0): updating it." $r = Invoke-Wsl @('--update') -Changes -Live if ($r.Code -ne 0) { Stop-Rouh 'WSL did not update. Run "wsl --update" yourself, then run this again.' } Write-Good 'WSL updated' return } Write-Line 'WSL is not switched on yet. Windows will ask for an administrator''s yes to switch it on.' $code = Start-Elevated 'wsl.exe' @('--install', '--no-distribution') if ($code -ne 0 -and $code -ne 3010) { Stop-Rouh "switching WSL on did not finish (it said $code). Run ""wsl --install --no-distribution"" as administrator, then run this again." } $v = Get-WslVersion if ($script:DryRun) { return } if ($null -eq $v -or $code -eq 3010) { Write-Note 'WSL is switched on, and Windows needs one restart to finish. Restart, then run the same command again: it carries on from here.' Stop-Rouh 'RESTART' } Write-Good "WSL $v" } # --- 3. Rouh's own Linux, checked --------------------------------------------------------------------- # Test-RouhRecord ENVELOPE: the record's payload, as an object, only when it is signed with Rouh's # release key and is a record of Rouh's WSL Linux; otherwise it stops. function Test-RouhRecord($Envelope) { if ($null -eq $Envelope -or $Envelope.format -ne 1 -or $Envelope.key -ne $script:KeyId) { Stop-Rouh 'rouh.land''s record of Rouh''s Linux is not signed with Rouh''s release key, so nothing of it was used.' } $message = [Text.Encoding]::UTF8.GetBytes([string]$Envelope.payload) $signature = [Convert]::FromBase64String([string]$Envelope.signature) if (-not (Test-Ed25519 ([Convert]::FromBase64String($script:KeyRaw)) $message $signature)) { Stop-Rouh 'the signature on rouh.land''s record of Rouh''s Linux does not match Rouh''s release key, so nothing of it was used.' } $r = $Envelope.payload | ConvertFrom-Json if ($r.kind -ne 'rouh-wsl-image' -or $r.format -ne 1) { Stop-Rouh 'rouh.land handed out something that is not a record of Rouh''s Linux.' } return $r } function Get-RouhLinux { Write-Step 'Getting Rouh''s own Linux, and checking it' try { $envelope = Get-RouhJson '/windows/wsl/stable.json' } catch { Stop-Rouh "rouh.land did not hand out its record of Rouh's Linux ($($_.Exception.Message)). Run this again in a minute." } $r = Test-RouhRecord $envelope Write-Good "rouh.land's record of Rouh's Linux $($r.version): signed with Rouh's key" $image = $r.images.PSObject.Properties[$script:Arch] if ($null -eq $image) { Stop-Rouh "there is no Rouh Linux for this processor ($script:Arch) yet." } $image = $image.Value if ([string]$image.url -notmatch '^https://' -or [string]$image.sha256 -notmatch '^[0-9a-f]{64}$') { Stop-Rouh 'the record names no https address or SHA-256 for this processor''s Linux.' } $dir = Join-Path $script:RouhHome 'download' New-Item -ItemType Directory -Force -Path $dir | Out-Null $file = Join-Path $dir ([IO.Path]::GetFileName(([uri]$image.url).AbsolutePath)) $have = (Test-Path $file) -and ((Get-FileHash -Algorithm SHA256 $file).Hash.ToLower() -eq $image.sha256) if (-not $have) { Write-Line "Downloading $([math]::Round($image.size / 1MB)) MB..." Save-RouhDownload $image.url $file } $len = (Get-Item $file).Length $sum = (Get-FileHash -Algorithm SHA256 $file).Hash.ToLower() if ($len -ne [long]$image.size -or $sum -ne $image.sha256) { Remove-Item -Force $file Stop-Rouh "the download did not match the SHA-256 rouh.land's signed record names ($($sum.Substring(0,16))... is not $($image.sha256.Substring(0,16))...), so it was deleted and not used. Run this again." } Write-Good "Rouh's Linux $($r.version) for $script:Arch, $([math]::Round($len / 1MB)) MB: every byte matches its SHA-256" return $file } function Test-DistroThere { $r = Invoke-Wsl @('--list', '--quiet') if ($r.Code -ne 0) { return $false } foreach ($line in $r.Out) { if (($line -replace "`0", '').Trim() -eq $script:Distro) { return $true } } return $false } function Get-KeptCopy { $kept = Join-Path $script:RouhHome 'Kept' if (-not (Test-Path $kept)) { return $null } return Get-ChildItem -Path $kept -Filter 'Rouh-kept-*.tar' | Sort-Object Name -Descending | Select-Object -First 1 } function Import-RouhLinux([string]$File) { $place = Join-Path $script:RouhHome 'wsl' New-Item -ItemType Directory -Force -Path $place | Out-Null $r = Invoke-Wsl @('--import', $script:Distro, $place, $File, '--version', '2') -Changes -Live if ($r.Code -ne 0) { Stop-Rouh "WSL did not import Rouh's Linux: $($r.Out -join ' ')" } # The disk is not made sparse (WSL calls that unsafe for the data in it); it only grows, and # rouh.ps1 compact (Compact disk in Rouh for Windows) gives the space back (186-02). Write-Good "Rouh's Linux is in WSL as ""$script:Distro"", in $place" } # --- 4. WSL's settings -------------------------------------------------------------------------------- # Set-IniValue TEXT SECTION KEY VALUE: TEXT with KEY in [SECTION] set, unless the person has set it # already (then their value stays, and $script:IniKept says so). Comments and order are kept. function Set-IniValue([string]$Text, [string]$Section, [string]$Key, [string]$Value) { $lines = New-Object System.Collections.Generic.List[string] if ($Text) { $lines.AddRange([string[]]($Text -split "`r?`n")) } $in = $false; $start = -1; $end = $lines.Count for ($i = 0; $i -lt $lines.Count; $i++) { $t = $lines[$i].Trim() if ($t -match '^\[(.+)\]$') { if ($in) { $end = $i; break } if ($Matches[1].Trim() -eq $Section) { $in = $true; $start = $i } continue } if ($in -and $t -match "^$([regex]::Escape($Key))\s*=\s*(.*)$") { $script:IniKept = "$Section.$Key=$($Matches[1].Trim())" return ($lines -join "`r`n") } } if ($start -lt 0) { while ($lines.Count -gt 0 -and $lines[$lines.Count - 1].Trim() -eq '') { $lines.RemoveAt($lines.Count - 1) } if ($lines.Count -gt 0) { $lines.Add('') } $lines.Add("[$Section]"); $lines.Add("$Key=$Value") } else { $at = $end while ($at -gt $start + 1 -and $lines[$at - 1].Trim() -eq '') { $at-- } $lines.Insert($at, "$Key=$Value") } $script:IniKept = $null return ($lines -join "`r`n") } function Set-WslConfig { Write-Step 'WSL''s settings, for a Linux that stays on' $file = Join-Path $env:USERPROFILE '.wslconfig' $before = '' if (Test-Path $file) { $before = [IO.File]::ReadAllText($file) } $text = $before $kept = @() $wanted = @( @('wsl2', 'memory', "$($script:MemoryCapGB)GB"), # WSL shuts a Linux down a while after the last Windows program using it stops (186-01, # microsoft/WSL #13416); Rouh's own Linux must stay up, so: never when idle. @('wsl2', 'vmIdleTimeout', '-1'), @('general', 'instanceIdleTimeout', '-1') ) foreach ($w in $wanted) { $text = Set-IniValue $text $w[0] $w[1] $w[2] if ($script:IniKept) { $kept += $script:IniKept } } foreach ($k in $kept) { Write-Note "kept your own setting $k" } if ($text -eq $before) { Write-Good '.wslconfig already says what Rouh needs'; return $false } if ($script:DryRun) { Write-Line "(dry run) would write $file"; Write-Line ($text -replace "`r`n", ' | '); return $true } $backup = "$file.before-rouh" if ($before -and -not (Test-Path $backup)) { [IO.File]::WriteAllText($backup, $before) } [IO.File]::WriteAllText($file, $text + "`r`n") Write-Good "${file}: memory up to $($script:MemoryCapGB) GB, and WSL stays up when idle (yours before is in .wslconfig.before-rouh)" return $true } # WSL reads .wslconfig only when it starts. Restart it now only when nothing else of the person's is # running in it; otherwise say it takes effect next time. function Restart-WslIfFree { $r = Invoke-Wsl @('--list', '--running', '--quiet') $others = @($r.Out | ForEach-Object { ($_ -replace "`0", '').Trim() } | Where-Object { $_ -and $_ -ne $script:Distro -and $_ -notmatch 'no running' }) if ($r.Code -eq 0 -and $others.Count -gt 0) { Write-Note "WSL's new settings take effect the next time WSL starts: your own Linux ($($others -join ', ')) is running, so it was not stopped." return } $null = Invoke-Wsl @('--shutdown') -Changes } # --- 5. running from sign-in -------------------------------------------------------------------------- # A task for this user alone, at sign-in, that holds one process open in Rouh's Linux: WSL keeps a # Linux up while a Windows program uses it. conhost --headless gives it no window. function Register-KeepRunning { Write-Step 'Keeping Rouh running from sign-in' if ($env:ROUH_WINDOWS_APP -eq '1') { Write-Good 'Rouh for Windows keeps it running, from sign-in'; return } $wsl = Join-Path $env:WINDIR 'System32\wsl.exe' $argsLine = "--headless `"$wsl`" -d $script:Distro -u $script:LinuxUser --exec /usr/local/bin/rouh-wsl keep-awake" if ($script:DryRun) { Write-Line "(dry run) task ""$script:TaskName"": at sign-in, conhost.exe $argsLine"; return } $me = Get-CurrentUserName $action = New-ScheduledTaskAction -Execute (Join-Path $env:WINDIR 'System32\conhost.exe') -Argument $argsLine $trigger = New-ScheduledTaskTrigger -AtLogOn -User $me $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable ` -ExecutionTimeLimit ([TimeSpan]::Zero) -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) -MultipleInstances IgnoreNew $principal = New-ScheduledTaskPrincipal -UserId $me -LogonType Interactive -RunLevel Limited Register-ScheduledTask -TaskName $script:TaskName -Action $action -Trigger $trigger -Settings $settings -Principal $principal ` -Description 'Holds Rouh''s Linux in WSL up while you are signed in (added by https://rouh.land/install.ps1).' -Force | Out-Null Start-ScheduledTask -TaskName $script:TaskName Write-Good "Task Scheduler: ""$script:TaskName"", at sign-in, for you only" } # --- 6 and 7. Rouh itself, then its setup ------------------------------------------------------------ function Get-RouhState { $r = Invoke-RouhWsl state $line = @($r.Out | Where-Object { $_ -match '^\{' } | Select-Object -Last 1) if ($r.Code -ne 0 -or $line.Count -eq 0) { return $null } return ($line[0] | ConvertFrom-Json) } function Start-Rouh { Write-Step 'Starting Rouh (the first time downloads about 2 GB, about 5 minutes)' $r = Invoke-RouhWsl first-start -Changes -Live if ($r.Code -ne 0) { Stop-Rouh 'Rouh did not start inside its Linux; the lines above say why. Run this again to carry on.' } } function Open-Rouh([switch]$Quiet) { $r = Invoke-RouhWsl link $url = @($r.Out | Where-Object { $_ -match '^http://127\.0\.0\.1:\d+/' } | Select-Object -Last 1) if ($r.Code -ne 0 -or $url.Count -eq 0) { Stop-Rouh "Rouh did not give an address to open: $($r.Out -join ' ')" } if (-not $script:DryRun -and -not (Test-RouhAnswers)) { Stop-Rouh "Rouh runs inside its Linux, but http://127.0.0.1:$script:Port does not answer from Windows. In .wslconfig, [wsl2] localhostForwarding must not be false; then: wsl --shutdown, and run this again." } if ($env:ROUH_NO_OPEN -eq '1') { Write-Line "Open Rouh: $($url[0])"; return } Open-Browser $url[0] if (-not $Quiet) { Write-Good 'Rouh opened in your browser. The address works once; open Rouh again with: rouh.ps1 open' } } function Save-Command { $to = Join-Path $script:RouhHome 'rouh.ps1' if ($script:DryRun) { Write-Line "(dry run) would keep this script as $to"; return } New-Item -ItemType Directory -Force -Path $script:RouhHome | Out-Null if ($ScriptPath -and (Test-Path $ScriptPath) -and ((Resolve-Path $ScriptPath).Path -ne $to)) { Copy-Item -Force $ScriptPath $to } elseif (-not $ScriptPath) { try { Invoke-WebRequest -UseBasicParsing -Uri "$script:RouhLand/install.ps1" -OutFile $to -UserAgent $script:UserAgent } catch { Write-Note "could not keep rouh.ps1: $($_.Exception.Message)" } } } # --- the commands ------------------------------------------------------------------------------------- function Confirm-Go { if ($env:ROUH_YES -eq '1' -or $script:DryRun -or $env:ROUH_WINDOWS_APP -eq '1') { return } if (-not [Environment]::UserInteractive) { return } $a = Read-Host "`nGo on? [Y/n]" if ($a -and $a -notmatch '^(y|yes)$') { Write-Line 'Nothing was changed.'; Stop-Rouh 'CANCELLED' } } function Invoke-Install { Write-Host 'Rouh on Windows: one command. It checks this computer, switches WSL2 on, and starts Rouh in its own Linux.' -ForegroundColor White Write-Note 'A preview: not yet run on a real Windows computer (INSTALL-WINDOWS.md says what is proved).' $null = Test-Computer $there = Test-DistroThere $kept = $null if (-not $there) { $kept = Get-KeptCopy } Write-Step 'What happens now' if ($null -eq (Get-WslVersion)) { Write-Line '- Switch WSL2 on (an administrator''s yes, perhaps one restart)' } if ($there) { Write-Line "- Rouh's Linux is here already: update Rouh in it" } elseif ($kept) { Write-Line "- Bring back your Rouh, kept when it was uninstalled: $($kept.Name)" } else { Write-Line "- Get Rouh's own Linux, about 400 MB, checked against rouh.land's signed record" } Write-Line '- Set WSL to stay up while you are signed in, with a memory cap' Write-Line '- Start Rouh: about 2 GB, about 5 minutes the first time' Write-Line '- Open Rouh''s setup in your browser, on this computer only' Write-Line 'Nothing of Rouh''s listens beyond this computer. Uninstall any time: rouh.ps1 uninstall' Confirm-Go Enable-Wsl if (-not $there) { if ($kept) { Write-Step 'Bringing back your Rouh'; Import-RouhLinux $kept.FullName } else { $file = Get-RouhLinux Import-RouhLinux $file if (-not $script:DryRun) { Remove-Item -Force $file -ErrorAction SilentlyContinue } } } if (Set-WslConfig) { Restart-WslIfFree } Register-KeepRunning Start-Rouh Save-Command Write-Step 'Rouh is running' Open-Rouh } function Invoke-Status { if (-not (Test-DistroThere)) { Write-Line 'Rouh is not installed on this computer. Install it: irm https://rouh.land/install.ps1 | iex'; return } $s = Get-RouhState if ($null -eq $s) { Write-Line 'Rouh''s Linux is here, and does not answer yet.'; return } if ($s.running) { Write-Good "Rouh is running, at http://127.0.0.1:$($s.port)" } else { Write-Note 'Rouh is not running' } if ($s.release) { Write-Line "Release $($s.release.version), base $($s.release.level) (signature checked)" } if ($s.running -and -not $s.owner) { Write-Note 'Not set up yet: rouh.ps1 open' } $t = Get-ScheduledTask -TaskName $script:TaskName -ErrorAction SilentlyContinue if ($t) { Write-Line "Keeps running from sign-in: $($t.State)" } } function Invoke-Uninstall([string]$How) { if (-not (Test-DistroThere)) { Write-Line 'Rouh is not installed on this computer.'; return } if (-not $How) { Write-Step 'What should happen to Rouh''s data?' Write-Line 'K Keep my data (recommended): a checked copy of your Rouh is kept on this computer, and installing again brings it back.' Write-Line 'W Wipe my data: Rouh and everything it knows is removed for good.' $a = Read-Host 'Keep or Wipe? [K/w]' $How = if ($a -match '^(w|wipe)$') { 'wipe' } else { 'keep' } } if ($How -eq 'wipe' -and $env:ROUH_YES -ne '1' -and -not $script:DryRun) { if ((Read-Host 'Type WIPE to remove Rouh and its data for good') -cne 'WIPE') { Write-Line 'Nothing was removed.'; return } } if ($How -eq 'keep') { Write-Step 'Keeping a checked copy of your Rouh' $r = Invoke-RouhWsl uninstall-keep -Changes -Live if ($r.Code -ne 0) { Stop-Rouh 'the copy did not check out, so nothing was removed and Rouh runs again.' } $keptDir = Join-Path $script:RouhHome 'Kept' New-Item -ItemType Directory -Force -Path $keptDir | Out-Null $to = Join-Path $keptDir ("Rouh-kept-{0}.tar" -f (Get-Date -Format 'yyyyMMdd-HHmmss')) $null = Invoke-Wsl @('--terminate', $script:Distro) -Changes $e = Invoke-Wsl @('--export', $script:Distro, $to) -Changes -Live if ($e.Code -ne 0) { Stop-Rouh "WSL did not save Rouh's Linux to $to, so it was not removed: $($e.Out -join ' ')" } Write-Good "Kept: $to" } Get-ScheduledTask -TaskName $script:TaskName -ErrorAction SilentlyContinue | ForEach-Object { if ($script:DryRun) { Write-Line "(dry run) remove task $script:TaskName" } else { Unregister-ScheduledTask -TaskName $script:TaskName -Confirm:$false } } $u = Invoke-Wsl @('--unregister', $script:Distro) -Changes if ($u.Code -ne 0) { Stop-Rouh "WSL did not remove Rouh's Linux: $($u.Out -join ' ')" } if (-not $script:DryRun) { Remove-Item -Recurse -Force (Join-Path $script:RouhHome 'wsl'), (Join-Path $script:RouhHome 'download') -ErrorAction SilentlyContinue } Write-Step 'Rouh is removed from this computer' if ($How -eq 'keep') { Write-Line 'Install it again with irm https://rouh.land/install.ps1 | iex, and it brings your Rouh back.' } else { Write-Line 'A Connected Rouh''s rouh.land account is still there; delete it on rouh.land if you want.' } Write-Line 'WSL itself, your own Linux and .wslconfig stay as they are.' } # Compact disk (186-02): WSL's disk file only grows as Rouh writes and deletes; this gives the space # back. Rouh stops for a minute or two, and Windows asks for an administrator's yes for diskpart. function Invoke-Compact { if (-not (Test-DistroThere)) { Write-Line 'Rouh is not installed on this computer.'; return } $vhd = Join-Path $script:RouhHome 'wsl\ext4.vhdx' if (-not $script:DryRun -and -not (Test-Path $vhd)) { Stop-Rouh "Rouh's disk is not at $vhd." } Write-Step 'Giving disk space back (Rouh stops for a minute or two)' $before = 0; if (Test-Path $vhd) { $before = (Get-Item $vhd).Length } $null = Invoke-Wsl @('-d', $script:Distro, '-u', 'root', '--', 'fstrim', '-av') -Changes -Live $r = Invoke-Wsl @('--list', '--running', '--quiet') $others = @($r.Out | ForEach-Object { ($_ -replace "`0", '').Trim() } | Where-Object { $_ -and $_ -ne $script:Distro -and $_ -notmatch 'no running' }) if ($others.Count -gt 0) { Stop-Rouh "compacting needs WSL stopped, and your own Linux ($($others -join ', ')) is running. Close it, then run this again." } $null = Invoke-Wsl @('--shutdown') -Changes $script = Join-Path $env:TEMP 'rouh-compact.txt' if (-not $script:DryRun) { [IO.File]::WriteAllText($script, "select vdisk file=`"$vhd`"`r`nattach vdisk readonly`r`ncompact vdisk`r`ndetach vdisk`r`n") } $code = Start-Elevated 'diskpart.exe' @('/s', $script) Remove-Item -Force $script -ErrorAction SilentlyContinue if ($code -ne 0) { Stop-Rouh "diskpart did not compact Rouh's disk (it said $code); Rouh starts again as it was." } $null = Get-RouhState if (Test-Path $vhd) { $after = (Get-Item $vhd).Length Write-Good ("Rouh's disk: {0:N1} GB, was {1:N1} GB" -f ($after / 1GB), ($before / 1GB)) } } function Invoke-RouhCommand([string[]]$Words) { $cmd = 'install'; $how = $null foreach ($w in $Words) { switch -Regex ($w) { '^-?-?keep$' { $how = 'keep'; continue } '^-?-?wipe$' { $how = 'wipe'; continue } '^-?-?yes$' { $env:ROUH_YES = '1'; continue } '^-?-?dry-?run$' { $script:DryRun = $true; continue } '^(install|open|status|update|back|compact|uninstall|help)$' { $cmd = $w; continue } default { Stop-Rouh "unknown word ""$w"". The commands are install, open, status, update, back, compact and uninstall." } } } switch ($cmd) { 'install' { Invoke-Install } 'open' { Open-Rouh } 'status' { Invoke-Status } 'update' { $r = Invoke-RouhWsl update -Changes -Live; if ($r.Code -ne 0) { Stop-Rouh 'the update did not go through; Rouh stays on the release before.' } } 'back' { $r = Invoke-RouhWsl back -Changes -Live; if ($r.Code -ne 0) { Stop-Rouh 'going back did not work; the lines above say why.' } } 'compact' { Invoke-Compact } 'uninstall' { Invoke-Uninstall $how } 'help' { if ($ScriptPath) { Get-Content -TotalCount 40 $ScriptPath | Write-Host } else { Write-Line 'Commands: install, open, status, update, back, compact, uninstall [-Keep|-Wipe]' } } } } # Invoke-RouhMain WORDS: the command, and its exit code; a stop is said here, never thrown on. function Invoke-RouhMain([string[]]$Words) { try { Invoke-RouhCommand $Words; return 0 } catch { $m = "$($_.Exception.Message)" if ($m -notlike 'ROUH-STOP:*') { Write-Host '' Write-Host "Rouh: something went wrong that this installer did not expect: $m" -ForegroundColor Red Write-Host " (at $($_.InvocationInfo.ScriptLineNumber): $($_.InvocationInfo.Line.Trim()))" Write-Host ' Nothing more was changed. Run it again; if it says the same, send these lines to Rouh''s makers.' return 1 } $why = $m.Substring(10) if ($why -in @('RESTART', 'CANCELLED')) { return 0 } Write-Host ''; Write-Host "Rouh: $why" -ForegroundColor Red return 1 } } Export-ModuleMember -Function * } | Import-Module -Force # Run with irm ... | iex there are no words, so it installs; as rouh.ps1 the words are the command. # A test sets ROUH_PS1_NO_MAIN, and calls the module's functions itself. if ($env:ROUH_PS1_NO_MAIN -ne '1') { $RouhCode = RouhInstall\Invoke-RouhMain ([string[]]@($args)) Remove-Module RouhInstall if ($RouhPs1Path) { exit $RouhCode } }