diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9e05b7d17..ef35d4c1b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -147,6 +147,32 @@ jobs: fi - run: go test ./... + # Die Medien-Tests laufen unter Windows, weil der Windows-Pfad (Laufwerke, + # WLAN, Imager, Helfer) sonst ungetestet bliebe. Tests, die Unix-Rechte, + # Symlinks oder ein Linux-Shellskript brauchen, überspringen sich dort selbst. + installer-windows: + name: Installer media tests (Windows) + needs: changes + if: needs.changes.outputs.installer_go == 'true' || github.event_name == 'push' + runs-on: windows-latest + defaults: + run: + working-directory: installer + env: + CGO_ENABLED: '0' + steps: + # Vor dem Checkout gibt es den Ordner installer noch nicht, daher hier + # den Arbeitsordner des Runners. Eingebettete Vorlagen und Fixtures + # sollen LF behalten. + - name: Keep LF line endings in the checkout + working-directory: ${{ github.workspace }} + run: git config --global core.autocrlf false + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: installer/go.mod + - run: go test ./internal/media/... ./internal/host/... ./cmd/installer/... + dashboard-js: name: Dashboard (JS) needs: changes @@ -291,6 +317,11 @@ jobs: TARGET: ${{ matrix.target }} CGO_ENABLED: '0' run: GOOS="${TARGET%/*}" GOARCH="${TARGET#*/}" go build -o "$RUNNER_TEMP/installer-build" ./cmd/installer + - name: Vet for ${{ matrix.target }} + env: + TARGET: ${{ matrix.target }} + CGO_ENABLED: '0' + run: GOOS="${TARGET%/*}" GOARCH="${TARGET#*/}" go vet ./... python-bridges: name: Python bridges @@ -500,6 +531,7 @@ jobs: - changes - dashboard-go - installer-go + - installer-windows - dashboard-js - dashboard-smoke - installer-webui-go diff --git a/changelog/highlights/298.json b/changelog/highlights/298.json new file mode 100644 index 000000000..7a28cd027 --- /dev/null +++ b/changelog/highlights/298.json @@ -0,0 +1,8 @@ +{ + "de": { + "*": "Der Installer bereitet Speichermedien jetzt auch unter Windows vor" + }, + "en": { + "*": "Prepare storage media on Windows" + } +} diff --git a/dashboard/CHANGELOG.md b/dashboard/CHANGELOG.md index c3446ba2c..ed8d31682 100644 --- a/dashboard/CHANGELOG.md +++ b/dashboard/CHANGELOG.md @@ -37,6 +37,7 @@ - **autolearn:** Learning functions can take minute values from Home Assistant (#294) (7aa657e) - **monitoring:** Monitoring shows the forecast check, a year comparison and the learned values as a usual day (#297) (4f93975) - **dashboard:** show system versions on the versions page (#299) (18a2b0b) +- **automations:** Monitoring checks the results of adopted suggestions and rules report a season drift (#300) (d9e023b) - **automations:** mark rules that came from a learned suggestion (f85130f) - **webui:** record which suggestion a saved rule came from (ae2baed) - **autolearn:** measure the effect of an adopted suggestion against the season (a1e9dc6) @@ -49,7 +50,6 @@ - **demo:** show every effect state and drift kind (c3e766b) - **webui:** let a tour expand the suggestions band (fa55c0a) - **monitoring:** check the results of adopted suggestions in Monitoring (f4755bb) -- **automations:** Monitoring checks the results of adopted suggestions and rules report a season drift (#300) - **dashboard:** read the system package versions (8d025b3) - **dashboard:** serve system versions to setup users (8e71270) - **dashboard:** show the kernel and the Debian point release (93d002d) @@ -367,6 +367,7 @@ - **storage:** wipe old file system signatures before formatting a stick (#245) (aeafa63) - **storage:** set up, back up and replug the additional drive reliably (#247) (b668394) - **automations:** correct the learning feature after the full review (#296) (88f3c75) +- **backup:** A restore stays in place even when the battery state cannot be written (#288) (e5c5437) - **webui:** mark rules adopted from the suggestions band (6e20041) - **autolearn:** accept baseline weeks with five days of data (fbbda8c) - **autolearn:** keep the comparison values when a drifted rule is replaced (a95dcb5) @@ -382,7 +383,6 @@ - **demo:** adopt the surplus window as a scenario and count one effect in hand switches (49a32f9) - **webui:** fit the effect axis on phones and say what a threshold fix does (0b4bef6) - **webui:** label only the ends of the before and since axis (222cf12) -- **backup:** A restore stays in place even when the battery state cannot be written (#288) (e5c5437) - **monitoring:** keep texts and locale out of the insight model (57e2a44) - **monitoring:** show the legend items for statistics weeks and gaps (82cde6e) - **monitoring:** route locale formatting through I18n (a664db2) diff --git a/docs/developing/installer-cli.md b/docs/developing/installer-cli.md index ad1ff6b48..26be733b8 100644 --- a/docs/developing/installer-cli.md +++ b/docs/developing/installer-cli.md @@ -262,6 +262,10 @@ Every failing check comes with a retry command you can copy, usually `installer deploy --only `. Run `diagnose` first when a node behaves oddly. +`media-helper` and `media-shim` are internal subcommands. The media mode of the +web UI uses them to write a storage medium, and they are not meant to be called +by hand. They are not part of `help`. + ## Common flags These apply to every subcommand: diff --git a/docs/installer-operating-system.md b/docs/installer-operating-system.md index e87a1cca0..c0d1baa2b 100644 --- a/docs/installer-operating-system.md +++ b/docs/installer-operating-system.md @@ -38,7 +38,9 @@ signature. Everything else in the package stays verified. ## Raspberry Pi with the Raspberry Pi Imager -- Pick the image from the table above. +- Pick the image from the table above. The installer's **Media** tab can also + write the card for you on Linux and Windows, see + [Preparing a storage medium](installer.md#preparing-a-storage-medium). - Set hostname, user, SSH, WiFi and timezone in the Imager before it writes the card. On a headless remote site you do not want to find out afterwards that SSH is off. diff --git a/docs/installer.md b/docs/installer.md index 0e2a2880e..7dfe01d81 100644 --- a/docs/installer.md +++ b/docs/installer.md @@ -84,9 +84,16 @@ such as a quicker package build for a first try. ## Preparing a storage medium The **Media** tab writes an SD card for a Raspberry Pi so that you do not need a -second tool for the image. It needs the Raspberry Pi Imager 2.0 or newer, as the -Flatpak or as a package. If it is missing, the tab links to Discover and to the -download page. For now the tab works on Linux only. Windows and macOS follow. +second tool for the image. The tab works on Linux and Windows. macOS follows. It +needs the Raspberry Pi Imager 2.0 or newer. + +On Linux that is the Flatpak or a package. If it is missing, the tab links to +Discover and to the download page. On Windows the tab links to the download page +and shows the command +`winget install -e --id RaspberryPiFoundation.RaspberryPiImager`. Run the +command or install the Imager from the page, then use **check again**. The Imager +setup also installs a USB driver (`rpiboot-winusb`) and may ask you to confirm +it. The same tab also builds a USB stick that installs Debian on other hardware, see [Other hardware (Debian)](#other-hardware-debian). @@ -105,7 +112,10 @@ The same tab also builds a USB stick that installs Debian on other hardware, see With **Connect to Wi-Fi** switched on, pick a network from the list of networks in range or choose **Other network** and type its name. The network - this computer is connected to is selected first. If this computer knows the + this computer is connected to is selected first. On Windows this needs + location access for desktop apps. Without it no networks are suggested, you + type the name yourself, and the password check still works. If this computer + knows the password of that network, or of the same network on the other band, the installer tells you whether yours matches, and otherwise says that it cannot check it. The Wi-Fi password only goes onto the card and the installer does @@ -119,7 +129,11 @@ The same tab also builds a USB stick that installs Debian on other hardware, see you tick a box, for an internal drive you type the drive's name. 4. **Write.** The installer downloads the image, checks its checksum, writes the card with the Imager and ejects it. The Imager asks for administrator rights - through the system's own dialog. + through the system's own dialog. On Windows the prompt names the Energy Node + installer, because only a small helper started from it runs with those + rights. If you refuse, the job ends without writing. Cancelling takes a few + seconds until the Imager has ended, and the card is then incomplete, so write + it again. 5. **Done.** Put the card into the Pi, connect it and switch it on. The installer waits for the Pi and then offers **Continue to setup**. diff --git a/installer/CHANGELOG.md b/installer/CHANGELOG.md index 627a7aab5..c16ee0942 100644 --- a/installer/CHANGELOG.md +++ b/installer/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## v0.3.4-pre.6 (2026-11-15) +## v0.3.4-pre.7 (2026-11-15) ### Features @@ -10,6 +10,17 @@ - **installer:** write a Debian install stick from the media mode (#255) (cb9e1aa) - **installer:** The configure screen of the installer shows its services and tuning as modules (#280) (f85e2a6) - **installer:** apply a changed service selection without a full update (#282) (ab11a7a) +- **installer:** check the target again before writing and read Windows imager output (c0a7cd7) +- **installer:** add the zone tables for the media defaults (d895abc) +- **installer:** add the media helper that runs the imager on behalf of the installer (b24ec8d) +- **installer:** run the imager in a pseudo console on Windows (6d84c06) +- **installer:** write media on Windows through an elevated helper (ec6df47) +- **installer:** find the Raspberry Pi Imager on Windows (917581f) +- **installer:** list Windows drives for the media mode (02a87d6) +- **installer:** take timezone, keyboard and country from Windows (d89dfb6) +- **installer:** read Wi-Fi networks and stored keys on Windows (f643b40) +- **installer:** eject the written medium on Windows (670a16f) +- **installer:** prepare storage media on Windows (#298) - **installer:** compute the steps an apply-selection run needs (c855116) - **installer:** prepare from the package stored on the node (f5b1c87) - **installer:** run only the changed services in apply-selection mode (7af7686) @@ -47,6 +58,13 @@ ### Fixes - **installer:** ask for the pinned host key type when probing and signing in (#241) (a5e2b38) +- **installer:** watch for cancel while the UAC prompt is open (ec65d4c) +- **installer:** hand the console pipe to the copy goroutine (527d98f) +- **installer:** match Windows volumes when PowerShell wraps the access paths (8e1ab65) +- **installer:** keep a cancelled write running until the imager has ended (693afe7) +- **installer:** show the whole imager error with correct characters (e9b2ed8) +- **installer:** keep recently seen Wi-Fi networks in the list (a2dbda5) +- **installer:** close the own console window once the app window is open (a56fbd1) - **installer:** skip the Debian release lookup for unsupported devices (4b53c16) - **installer:** install python3 on the Debian stick target (b007104) - **installer:** manage the Debian node network with NetworkManager (8034938) @@ -55,18 +73,30 @@ - **installer:** read the Wi-Fi name without a rescan and keep its band (092e503) - **installer:** unblock Wi-Fi on Raspberry Pi OS by setting its country (ffb360a) +### Refactors + +- **installer:** move the media platform choices behind one file per system (e77c96b) +- **installer:** share the Wi-Fi merge and add the Windows Wi-Fi parsers (8b1e9d2) + ### Documentation +- **installer:** describe what the log sink removes (8f5d163) - **installer:** record the QEMU matrix results and the emergency password run (ce5c7ab) ### Tests +- **installer:** add recorded Windows outputs for the media mode (55e7a70) +- **installer:** compare the state dirs with the system path separator (bc24cad) - **installer:** cover the ISO layout failures of isopatch (f52f4cc) - **installer:** pin the disk selection of the Debian install script (3a98409) - **installer:** keep the Debian stick QEMU matrix in the repo (d0433a1) - **installer:** let mediastick set the emergency password (052a7b8) - **installer:** add dev.sh to try the Debian stick in QEMU (#257) (8bb3a60) +### CI + +- run the installer media tests on Windows (c7d413f) + ## v0.3.3 (2026-11-16) ### Fixes diff --git a/installer/VERSION b/installer/VERSION index 44ed50712..1afca5d74 100644 --- a/installer/VERSION +++ b/installer/VERSION @@ -1 +1 @@ -v0.3.4-pre.6 +v0.3.4-pre.7 diff --git a/installer/cmd/installer/main.go b/installer/cmd/installer/main.go index 2bf04cd0d..5ffea2c47 100644 --- a/installer/cmd/installer/main.go +++ b/installer/cmd/installer/main.go @@ -13,6 +13,7 @@ import ( "strings" "github.com/Developer-Simon/energy-node-installer/internal/devcli" + "github.com/Developer-Simon/energy-node-installer/internal/media" "github.com/Developer-Simon/energy-node-installer/internal/transport" ) @@ -41,6 +42,10 @@ func main() { err = runDiagnoseCmd(os.Args[2:]) case "restart": err = runRestartCmd(os.Args[2:]) + case media.HelperName: + os.Exit(runMediaHelperCmd(os.Args[2:])) + case media.ShimName: + os.Exit(runMediaShimCmd(os.Args[2:])) case "-h", "--help", "help": printUsage() return diff --git a/installer/cmd/installer/mediahelper.go b/installer/cmd/installer/mediahelper.go new file mode 100644 index 000000000..aa3fe639d --- /dev/null +++ b/installer/cmd/installer/mediahelper.go @@ -0,0 +1,66 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "os" + + "github.com/Developer-Simon/energy-node-installer/internal/media" +) + +// runMediaHelperCmd ist der interne Unterbefehl media-helper. Er steht nicht in printUsage. +func runMediaHelperCmd(args []string) int { + files, name, rest, err := parseMediaHelperArgs(args) + if err != nil { + fmt.Fprintln(os.Stderr, "media-helper:", err) + return 125 + } + return media.RunHelper(context.Background(), files, name, rest) +} + +// runMediaShimCmd ist der interne Unterbefehl media-shim -- . +func runMediaShimCmd(args []string) int { + if len(args) < 2 || args[0] != "--" { + fmt.Fprintln(os.Stderr, "usage: media-shim -- ") + return 125 + } + return media.RunShim(args[1], args[2:]) +} + +// parseMediaHelperArgs liest --log, --cancel, optional --status und danach -- . +func parseMediaHelperArgs(args []string) (media.HelperFiles, string, []string, error) { + var files media.HelperFiles + sep := -1 + for i, a := range args { + if a == "--" { + sep = i + break + } + } + if sep < 0 { + return files, "", nil, errors.New("missing -- before the program") + } + rest := args[sep+1:] + if len(rest) == 0 { + return files, "", nil, errors.New("missing program name after --") + } + + fs := flag.NewFlagSet(media.HelperName, flag.ContinueOnError) + fs.SetOutput(io.Discard) + fs.StringVar(&files.Log, "log", "", "") + fs.StringVar(&files.Cancel, "cancel", "", "") + fs.StringVar(&files.Status, "status", "", "") + if err := fs.Parse(args[:sep]); err != nil { + return files, "", nil, err + } + if fs.NArg() != 0 { + return files, "", nil, fmt.Errorf("unexpected arguments before --: %v", fs.Args()) + } + if files.Log == "" || files.Cancel == "" { + return files, "", nil, errors.New("--log and --cancel are required") + } + return files, rest[0], rest[1:], nil +} diff --git a/installer/cmd/installer/mediahelper_test.go b/installer/cmd/installer/mediahelper_test.go new file mode 100644 index 000000000..88c04c9ce --- /dev/null +++ b/installer/cmd/installer/mediahelper_test.go @@ -0,0 +1,29 @@ +package main + +import ( + "reflect" + "testing" +) + +func TestMediaHelperParsesItsFlags(t *testing.T) { + files, name, rest, err := parseMediaHelperArgs([]string{"--log", "a", "--cancel", "b", "--", "x", "y", "z"}) + if err != nil { + t.Fatal(err) + } + if files.Log != "a" || files.Cancel != "b" || files.Status != "" { + t.Fatalf("files = %+v", files) + } + if name != "x" || !reflect.DeepEqual(rest, []string{"y", "z"}) { + t.Fatalf("name = %q, rest = %v", name, rest) + } + + if _, _, _, err := parseMediaHelperArgs([]string{"--log", "a", "--cancel", "b", "x"}); err == nil { + t.Fatal("missing -- must fail") + } + if _, _, _, err := parseMediaHelperArgs([]string{"--log", "a", "--cancel", "b", "--"}); err == nil { + t.Fatal("missing program name must fail") + } + if _, _, _, err := parseMediaHelperArgs([]string{"--cancel", "b", "--", "x"}); err == nil { + t.Fatal("missing --log must fail") + } +} diff --git a/installer/cmd/installer/mediashim_windows_test.go b/installer/cmd/installer/mediashim_windows_test.go new file mode 100644 index 000000000..b8f88e701 --- /dev/null +++ b/installer/cmd/installer/mediashim_windows_test.go @@ -0,0 +1,43 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" + "strconv" + "testing" +) + +// TestMain macht die Testdatei selbst zum Imager: mit gesetzter Variable endet der Prozess +// mit dem angegebenen Code. +func TestMain(m *testing.M) { + if code := os.Getenv("ENERGY_NODE_FAKE_IMAGER_EXIT"); code != "" { + n, err := strconv.Atoi(code) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(125) + } + os.Exit(n) + } + os.Exit(m.Run()) +} + +func TestMediaShimPassesTheExitCode(t *testing.T) { + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(exe) + if err != nil { + t.Fatal(err) + } + imager := filepath.Join(t.TempDir(), "rpi-imager.exe") + if err := os.WriteFile(imager, data, 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("ENERGY_NODE_FAKE_IMAGER_EXIT", "3") + + if got := runMediaShimCmd([]string{"--", imager}); got != 3 { + t.Fatalf("runMediaShimCmd = %d, want 3", got) + } +} diff --git a/installer/cmd/installer/savefile_test.go b/installer/cmd/installer/savefile_test.go index 021099174..66f9e6e26 100644 --- a/installer/cmd/installer/savefile_test.go +++ b/installer/cmd/installer/savefile_test.go @@ -3,11 +3,15 @@ package main import ( "os" "path/filepath" + "runtime" "strings" "testing" ) func TestSaveFileInWritesUnchangedName(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("checks Unix mode bits 0600, which Windows does not report") + } dir := t.TempDir() name := "energy-node-protokoll-20261031-120000.txt" content := []byte("inhalt") diff --git a/installer/cmd/installer/ui_test.go b/installer/cmd/installer/ui_test.go index e9e7aae4b..df61d14aa 100644 --- a/installer/cmd/installer/ui_test.go +++ b/installer/cmd/installer/ui_test.go @@ -1,6 +1,7 @@ package main import ( + "path/filepath" "strings" "testing" @@ -83,8 +84,11 @@ func TestDescribeShellModeStopsWaitingOnlyAfterAWebviewClosed(t *testing.T) { } func TestRunUIStateDirsLiveUnderTheEnergyNodeHome(t *testing.T) { - dirs := stateDirs("/home/dev") - if dirs.work != "/home/dev/.energy-node/work" || dirs.cache != "/home/dev/.energy-node/cache" { + home := filepath.FromSlash("/home/dev") + dirs := stateDirs(home) + wantWork := filepath.Join(home, ".energy-node", "work") + wantCache := filepath.Join(home, ".energy-node", "cache") + if dirs.work != wantWork || dirs.cache != wantCache { t.Errorf("stateDirs = %+v", dirs) } } diff --git a/installer/go.mod b/installer/go.mod index 39aa2e14b..ce9dd6c71 100644 --- a/installer/go.mod +++ b/installer/go.mod @@ -11,6 +11,7 @@ require ( github.com/pkg/sftp v1.13.11 github.com/zalando/go-keyring v0.2.8 golang.org/x/crypto v0.57.0 + golang.org/x/sys v0.48.0 golang.org/x/term v0.46.0 ) @@ -21,7 +22,6 @@ require ( github.com/godbus/dbus/v5 v5.2.2 // indirect github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 // indirect github.com/kr/fs v0.1.0 // indirect - golang.org/x/sys v0.48.0 // indirect ) replace github.com/Developer-Simon/energy-node-webui => ./webui diff --git a/installer/internal/host/elevate.go b/installer/internal/host/elevate.go new file mode 100644 index 000000000..0894f526e --- /dev/null +++ b/installer/internal/host/elevate.go @@ -0,0 +1,103 @@ +package host + +import ( + "context" + "io" + "os" + + "github.com/Developer-Simon/energy-node-installer/internal/media" +) + +// helperExe liefert den Pfad des eigenen Programms, das den erhoehten Helfer startet (Testnaht). +var helperExe = os.Executable + +// shellExecuteInfo entspricht SHELLEXECUTEINFOW auf 64 bit (112 Bytes). +type shellExecuteInfo struct { + cbSize uint32 + fMask uint32 + hwnd uintptr + lpVerb uintptr + lpFile uintptr + lpParameters uintptr + lpDirectory uintptr + nShow int32 + hInstApp uintptr + lpIDList uintptr + lpClass uintptr + hkeyClass uintptr + dwHotKey uint32 + hIconOrMon uintptr + hProcess uintptr +} + +const ( + seeMaskNoCloseProcess = 0x00000040 + seeMaskNoAsync = 0x00000100 + seeMaskFlagNoUI = 0x00000400 +) + +// launcher startet exe mit args erhoeht und liefert eine Wartefunktion fuer den Exit-Code. +type launcher func(exe string, args []string) (wait func() (int, error), err error) + +// helperArgs baut die Argumente fuer den Helfer: Dateien, dann der Imager nach dem Trenner. +func helperArgs(f media.HelperFiles, name string, args []string) []string { + out := []string{ + media.HelperName, + "--log", f.Log, + "--cancel", f.Cancel, + "--status", f.Status, + "--", name, + } + return append(out, args...) +} + +// runElevated startet den Imager ueber launch und liefert dessen Log und Exit-Code. +// Wird ctx abgebrochen, schreibt es die Abbruchdatei, auf die der Helfer den Imager beendet. +// Der Beobachter laeuft schon waehrend launch: der UAC-Dialog blockiert, eine Abbruch- +// Datei muss aber vor dem Start des Helfers liegen. +func runElevated(ctx context.Context, launch launcher, exe, dir, name string, args []string) (io.ReadCloser, func() (int, error), error) { + files, err := media.PrepareHelperFiles(dir) + if err != nil { + return nil, nil, err + } + done := make(chan struct{}) + watched := make(chan struct{}) + go func() { + defer close(watched) + select { + case <-ctx.Done(): + writeCancelFile(files.Cancel) + case <-done: + } + }() + + wait, err := launch(exe, helperArgs(files, name, args)) + if err != nil { + // Der Aufrufer loescht den Ordner: der Beobachter darf dann nicht mehr schreiben. + close(done) + <-watched + return nil, nil, err + } + if ctx.Err() != nil { + writeCancelFile(files.Cancel) + } + + var code int + var waitErr error + go func() { + code, waitErr = wait() + close(done) + }() + + return media.TailLog(files.Log, done), func() (int, error) { + <-done + return code, waitErr + }, nil +} + +// writeCancelFile legt die Abbruchdatei an. Fehler bleiben folgenlos, der Helfer endet ohnehin mit dem Imager. +func writeCancelFile(path string) { + if f, err := os.Create(path); err == nil { + _ = f.Close() + } +} diff --git a/installer/internal/host/elevate_script_test.go b/installer/internal/host/elevate_script_test.go new file mode 100644 index 000000000..8d3b28089 --- /dev/null +++ b/installer/internal/host/elevate_script_test.go @@ -0,0 +1,63 @@ +//go:build !windows + +package host + +import ( + "context" + "io" + "os" + "path/filepath" + "testing" + + "github.com/Developer-Simon/energy-node-installer/internal/media" +) + +// inProcessLauncher ersetzt den erhoehten Start: der Helfer laeuft als Goroutine im Testprozess. +func inProcessLauncher(t *testing.T) launcher { + return func(exe string, args []string) (func() (int, error), error) { + f, name, rest := splitHelperArgs(t, args) + done := make(chan int, 1) + go func() { done <- media.RunHelper(context.Background(), f, name, rest) }() + return func() (int, error) { return <-done, nil }, nil + } +} + +// splitHelperArgs zerlegt die Argumente aus helperArgs wieder. +func splitHelperArgs(t *testing.T, args []string) (media.HelperFiles, string, []string) { + t.Helper() + if len(args) < 9 || args[0] != media.HelperName || args[7] != "--" { + t.Fatalf("helper args: %q", args) + } + f := media.HelperFiles{Log: args[2], Cancel: args[4], Status: args[6]} + return f, args[8], args[9:] +} + +func TestRunElevatedTailsTheLogAndReturnsTheExitCode(t *testing.T) { + dir := t.TempDir() + script := filepath.Join(t.TempDir(), "rpi-imager") + body := "#!/bin/sh\necho line one\necho line two\nexit 3\n" + if err := os.WriteFile(script, []byte(body), 0o755); err != nil { + t.Fatal(err) + } + + out, wait, err := runElevated(context.Background(), inProcessLauncher(t), "installer", dir, script, nil) + if err != nil { + t.Fatalf("runElevated: %v", err) + } + defer out.Close() + + logged, err := io.ReadAll(out) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(logged) != "line one\nline two\n" { + t.Errorf("log = %q", logged) + } + code, err := wait() + if err != nil { + t.Fatalf("wait: %v", err) + } + if code != 3 { + t.Errorf("exit code = %d, want 3", code) + } +} diff --git a/installer/internal/host/elevate_test.go b/installer/internal/host/elevate_test.go new file mode 100644 index 000000000..947399de4 --- /dev/null +++ b/installer/internal/host/elevate_test.go @@ -0,0 +1,141 @@ +package host + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "testing" + "time" + "unsafe" + + "github.com/Developer-Simon/energy-node-installer/internal/media" +) + +func TestShellExecuteInfoLayout(t *testing.T) { + if unsafe.Sizeof(uintptr(0)) != 8 { + t.Skip("SHELLEXECUTEINFOW ist nur auf 64 bit festgelegt") + } + var info shellExecuteInfo + if got := unsafe.Sizeof(info); got != 112 { + t.Errorf("Sizeof = %d, want 112", got) + } + checks := []struct { + name string + got uintptr + want uintptr + }{ + {"lpVerb", unsafe.Offsetof(info.lpVerb), 16}, + {"nShow", unsafe.Offsetof(info.nShow), 48}, + {"dwHotKey", unsafe.Offsetof(info.dwHotKey), 88}, + {"hProcess", unsafe.Offsetof(info.hProcess), 104}, + } + for _, c := range checks { + if c.got != c.want { + t.Errorf("Offsetof(%s) = %d, want %d", c.name, c.got, c.want) + } + } +} + +func TestHelperArgsPutTheImagerAfterTheSeparator(t *testing.T) { + f := media.HelperFiles{Log: "/job/imager.log", Cancel: "/job/cancel", Status: "/job/status"} + got := helperArgs(f, `C:\job\rpi-imager.exe`, []string{"--foo", "bar"}) + want := []string{ + media.HelperName, + "--log", "/job/imager.log", + "--cancel", "/job/cancel", + "--status", "/job/status", + "--", `C:\job\rpi-imager.exe`, "--foo", "bar", + } + if !slices.Equal(got, want) { + t.Errorf("helperArgs = %q, want %q", got, want) + } +} + +func TestRunElevatedWritesTheCancelFileOnContextCancel(t *testing.T) { + dir := t.TempDir() + ctx, cancel := context.WithCancel(context.Background()) + release := make(chan struct{}) + launch := func(exe string, args []string) (func() (int, error), error) { + return func() (int, error) { + <-release + return 0, nil + }, nil + } + + out, wait, err := runElevated(ctx, launch, "installer", dir, "rpi-imager", nil) + if err != nil { + t.Fatalf("runElevated: %v", err) + } + cancel() + + cancelFile := filepath.Join(dir, "cancel") + deadline := time.Now().Add(2 * time.Second) + for { + if _, err := os.Stat(cancelFile); err == nil { + break + } + if time.Now().After(deadline) { + t.Fatal("cancel file was not written after ctx was cancelled") + } + time.Sleep(5 * time.Millisecond) + } + close(release) + if _, err := wait(); err != nil { + t.Errorf("wait: %v", err) + } + if err := out.Close(); err != nil { + t.Errorf("Close: %v", err) + } +} + +func TestElevatedRunnerMapsCancelledToRightsDenied(t *testing.T) { + launchErr := fmt.Errorf("uac: %w", media.ErrRightsDenied) + launch := func(exe string, args []string) (func() (int, error), error) { + return nil, launchErr + } + + _, _, err := runElevated(context.Background(), launch, "installer", t.TempDir(), "rpi-imager", nil) + if err != launchErr { + t.Fatalf("runElevated err = %v, want the launcher error unchanged", err) + } + if !errors.Is(err, media.ErrRightsDenied) { + t.Errorf("errors.Is(err, ErrRightsDenied) = false for %v", err) + } +} + +func TestRunElevatedWritesTheCancelFileWhileTheLauncherStillBlocks(t *testing.T) { + dir := t.TempDir() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + seen := false + launch := func(exe string, args []string) (func() (int, error), error) { + cancel() + cancelFile := filepath.Join(dir, "cancel") + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if _, err := os.Stat(cancelFile); err == nil { + seen = true + break + } + time.Sleep(5 * time.Millisecond) + } + return func() (int, error) { return 0, nil }, nil + } + + out, wait, err := runElevated(ctx, launch, "installer", dir, "rpi-imager", nil) + if err != nil { + t.Fatalf("runElevated: %v", err) + } + if !seen { + t.Error("cancel file did not appear while the launcher was still blocked") + } + if _, err := wait(); err != nil { + t.Errorf("wait: %v", err) + } + if err := out.Close(); err != nil { + t.Errorf("Close: %v", err) + } +} diff --git a/installer/internal/host/elevate_windows.go b/installer/internal/host/elevate_windows.go new file mode 100644 index 000000000..2ee259472 --- /dev/null +++ b/installer/internal/host/elevate_windows.go @@ -0,0 +1,93 @@ +//go:build windows + +package host + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "runtime" + "strings" + "unsafe" + + "github.com/Developer-Simon/energy-node-installer/internal/media" + "golang.org/x/sys/windows" +) + +var procShellExecuteExW = windows.NewLazySystemDLL("shell32.dll").NewProc("ShellExecuteExW") + +// shellExecuteRunas startet exe erhoeht (UAC) ohne Fenster und liefert eine Wartefunktion. +func shellExecuteRunas(exe string, args []string) (func() (int, error), error) { + quoted := make([]string, len(args)) + for i, a := range args { + quoted[i] = windows.EscapeArg(a) + } + verb, _ := windows.UTF16PtrFromString("runas") + file, _ := windows.UTF16PtrFromString(exe) + params, err := windows.UTF16PtrFromString(strings.Join(quoted, " ")) + if err != nil { + return nil, err + } + // Die Zeiger werden nur als uintptr gehalten, daher gepinnt. + var pin runtime.Pinner + defer pin.Unpin() + pin.Pin(verb) + pin.Pin(file) + pin.Pin(params) + info := &shellExecuteInfo{ + fMask: seeMaskNoCloseProcess | seeMaskNoAsync | seeMaskFlagNoUI, + lpVerb: uintptr(unsafe.Pointer(verb)), + lpFile: uintptr(unsafe.Pointer(file)), + lpParameters: uintptr(unsafe.Pointer(params)), + nShow: windows.SW_HIDE, + } + info.cbSize = uint32(unsafe.Sizeof(*info)) + r1, _, e1 := procShellExecuteExW.Call(uintptr(unsafe.Pointer(info))) + runtime.KeepAlive(verb) + runtime.KeepAlive(file) + runtime.KeepAlive(params) + if r1 == 0 { + if errors.Is(e1, windows.ERROR_CANCELLED) { + return nil, fmt.Errorf("uac: %w", media.ErrRightsDenied) + } + return nil, fmt.Errorf("ShellExecuteExW: %w", e1) + } + process := windows.Handle(info.hProcess) + return func() (int, error) { + defer windows.CloseHandle(process) + if _, err := windows.WaitForSingleObject(process, windows.INFINITE); err != nil { + return -1, err + } + var code uint32 + if err := windows.GetExitCodeProcess(process, &code); err != nil { + return -1, err + } + return int(code), nil + }, nil +} + +// elevatedRunner startet den Imager ueber den erhoehten Helfer des Installers. +// Der Job-Ordner wird nach dem Warten geloescht, Windows kann offene Dateien nicht loeschen. +func elevatedRunner(ctx context.Context, name string, args ...string) (io.ReadCloser, func() (int, error), error) { + dir, err := os.MkdirTemp("", "energy-node-media-") + if err != nil { + return nil, nil, err + } + exe, err := helperExe() + if err != nil { + _ = os.RemoveAll(dir) + return nil, nil, fmt.Errorf("own executable: %w", err) + } + out, wait, err := runElevated(ctx, shellExecuteRunas, exe, dir, name, args) + if err != nil { + _ = os.RemoveAll(dir) + return nil, nil, err + } + return out, func() (int, error) { + defer os.RemoveAll(dir) + defer out.Close() + return wait() + }, nil +} diff --git a/installer/internal/host/host.go b/installer/internal/host/host.go index ad87395ab..f0581fa26 100644 --- a/installer/internal/host/host.go +++ b/installer/internal/host/host.go @@ -97,6 +97,9 @@ type Host struct { mediaW *media.Writer mediaStart func(context.Context, media.WriteRequest) error + // wifiSeen sammelt die Netze in Reichweite ueber mehrere Abfragen. + wifiSeen media.WifiMemory + // mediaCache ersetzt den Zwischenspeicher des Katalogs. nil heisst der echte // Zwischenspeicher in MediaDir; Tests setzen ihn auf einen lokalen Stand. mediaCache *media.Cache diff --git a/installer/internal/host/keypair_test.go b/installer/internal/host/keypair_test.go index 971ad759e..9e251b77f 100644 --- a/installer/internal/host/keypair_test.go +++ b/installer/internal/host/keypair_test.go @@ -3,6 +3,7 @@ package host_test import ( "os" "path/filepath" + "runtime" "strings" "testing" @@ -10,6 +11,9 @@ import ( ) func TestGenerateEd25519WritesAKeyPairWithTightPermissions(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("checks Unix mode bits 0600, which Windows does not report") + } dir := t.TempDir() privatePath, publicLine, err := host.GenerateEd25519(dir) if err != nil { diff --git a/installer/internal/host/media.go b/installer/internal/host/media.go index 57c9d1cdc..7d68d53aa 100644 --- a/installer/internal/host/media.go +++ b/installer/internal/host/media.go @@ -25,11 +25,8 @@ const ( defaultMediaUser = "node" ) -// Die Quelle des Imagers und die Adressen zum Herunterladen. -const ( - mediaDiscoverURL = "appstream://" + media.FlatpakID - mediaWebsiteURL = "https://www.raspberrypi.com/software/" -) +// mediaWebsiteURL ist die Seite zum Herunterladen des Imagers. +const mediaWebsiteURL = "https://www.raspberrypi.com/software/" var _ hostapi.MediaProvider = (*Host)(nil) @@ -44,7 +41,7 @@ var imagerEnv = media.Env{ // mediaSupported liefert MEDIA_UNSUPPORTED, wenn der Rechner keine Medien // vorbereiten kann oder kein Medienverzeichnis gesetzt ist. func (h *Host) mediaSupported() error { - if runtime.GOOS != "linux" || h.cfg.MediaDir == "" { + if supported, _ := mediaPlatform(); !supported || h.cfg.MediaDir == "" { return apiError(hostapi.MediaErrUnsupported, http.StatusNotImplemented, runtime.GOOS) } return nil @@ -62,12 +59,11 @@ func (h *Host) writer() (*media.Writer, error) { return nil, err } h.mediaW = &media.Writer{ - Cache: h.mediaCacheOrDefault(), - Imager: func(ctx context.Context) (media.Imager, bool) { - return media.FindImager(ctx, imagerEnv) - }, + Cache: h.mediaCacheOrDefault(), + Imager: locateImager, Drives: media.ListDrives, - Run: execRunner, + Run: mediaRunner, + Eject: mediaEject, KnownHosts: h.cfg.KnownHostsPath, KeyPath: keyPath, WorkDir: filepath.Join(h.cfg.MediaDir, "jobs"), @@ -122,15 +118,13 @@ func execRunner(ctx context.Context, name string, args ...string) (io.ReadCloser func (h *Host) MediaStatus(ctx context.Context) (hostapi.MediaStatus, error) { status := hostapi.MediaStatus{Platform: runtime.GOOS, Links: []hostapi.MediaLink{}} - if runtime.GOOS != "linux" { + supported, links := mediaPlatform() + if !supported { return status, nil } status.Supported = true - status.Links = []hostapi.MediaLink{ - {Kind: "discover", URL: mediaDiscoverURL}, - {Kind: "website", URL: mediaWebsiteURL}, - } - im, ok := media.FindImager(ctx, imagerEnv) + status.Links = links + im, ok := locateImager(ctx) status.Imager = hostapi.MediaImagerStatus{Found: ok} if ok { status.Imager.Kind = string(im.Kind) @@ -150,7 +144,9 @@ func (h *Host) MediaCatalog(ctx context.Context) (hostapi.MediaCatalog, error) { // Ohne Liste und ohne gespeicherte Kopie bleibt nur die Geraeteliste ohne Images. list, offline = nil, true } - view := hostapi.MediaCatalog{Offline: offline, Defaults: mediaDefaults(media.HostDefaults())} + defaults := media.HostDefaults() + defaults.WifiNetworks = h.wifiSeen.Merge(defaults.WifiNetworks) + view := hostapi.MediaCatalog{Offline: offline, Defaults: mediaDefaults(defaults)} for _, d := range media.Devices() { device := hostapi.MediaDevice{ID: d.ID, Group: d.Group, Experimental: d.Experimental, Unsupported: d.Unsupported} if d.Kind == "debian" && !d.Unsupported { @@ -260,7 +256,7 @@ func (h *Host) MediaWifiNetworks(ctx context.Context) ([]hostapi.MediaWifiNetwor if err := h.mediaSupported(); err != nil { return nil, err } - return mediaWifiNetworks(media.WifiInRange(ctx)), nil + return mediaWifiNetworks(h.wifiSeen.Merge(media.WifiInRange(ctx))), nil } func (h *Host) MediaWrite(ctx context.Context, req hostapi.MediaWriteRequest) error { @@ -318,6 +314,7 @@ func (h *Host) MediaJob(ctx context.Context) (hostapi.MediaJob, error) { BytesDone: v.BytesDone, BytesTotal: v.BytesTotal, Rate: v.Rate, + Cancelling: v.Cancelling, Log: append([]string{}, v.Log...), } for _, s := range v.Steps { diff --git a/installer/internal/host/media_linux.go b/installer/internal/host/media_linux.go new file mode 100644 index 000000000..5153ed1f4 --- /dev/null +++ b/installer/internal/host/media_linux.go @@ -0,0 +1,31 @@ +//go:build linux + +package host + +import ( + "context" + + "github.com/Developer-Simon/energy-node-installer/internal/media" + "github.com/Developer-Simon/energy-node-webui/hostapi" +) + +// mediaDiscoverURL oeffnet den Imager im App-Store (Flatpak). +const mediaDiscoverURL = "appstream://" + media.FlatpakID + +// mediaPlatform meldet, dass dieser Rechner Medien vorbereiten kann. +func mediaPlatform() (supported bool, links []hostapi.MediaLink) { + return true, []hostapi.MediaLink{ + {Kind: "discover", URL: mediaDiscoverURL}, + {Kind: "website", URL: mediaWebsiteURL}, + } +} + +var mediaRunner media.Runner = execRunner + +// mediaEject ist nil: der Imager wirft das Medium selbst aus. +var mediaEject func(context.Context, media.Drive) error + +// locateImager sucht den Imager ueber Flatpak und den Systempfad. +func locateImager(ctx context.Context) (media.Imager, bool) { + return media.FindImager(ctx, imagerEnv) +} diff --git a/installer/internal/host/media_other.go b/installer/internal/host/media_other.go new file mode 100644 index 000000000..cfaff4bed --- /dev/null +++ b/installer/internal/host/media_other.go @@ -0,0 +1,25 @@ +//go:build !linux && !windows + +package host + +import ( + "context" + + "github.com/Developer-Simon/energy-node-installer/internal/media" + "github.com/Developer-Simon/energy-node-webui/hostapi" +) + +// mediaPlatform meldet, dass dieser Rechner keine Medien vorbereitet. +func mediaPlatform() (supported bool, links []hostapi.MediaLink) { + return false, []hostapi.MediaLink{} +} + +var mediaRunner media.Runner = execRunner + +// mediaEject ist nil: der Imager wirft das Medium selbst aus. +var mediaEject func(context.Context, media.Drive) error + +// locateImager findet auf diesem System keinen Imager. +func locateImager(ctx context.Context) (media.Imager, bool) { + return media.Imager{}, false +} diff --git a/installer/internal/host/media_test.go b/installer/internal/host/media_test.go index 83a69d8c9..80f07cd12 100644 --- a/installer/internal/host/media_test.go +++ b/installer/internal/host/media_test.go @@ -79,6 +79,9 @@ func TestMediaUnsupportedWithoutLinux(t *testing.T) { if runtime.GOOS == "linux" { t.Skip("checks the non-Linux answer") } + if runtime.GOOS == "windows" { + t.Skip("media mode is supported on Windows, so the unsupported answer does not apply") + } h := newMediaHost(t, t.TempDir()) _, err := h.MediaCatalog(context.Background()) assertAPIError(t, err, hostapi.MediaErrUnsupported, http.StatusNotImplemented) diff --git a/installer/internal/host/media_windows.go b/installer/internal/host/media_windows.go new file mode 100644 index 000000000..9668df0a9 --- /dev/null +++ b/installer/internal/host/media_windows.go @@ -0,0 +1,30 @@ +//go:build windows + +package host + +import ( + "context" + + "github.com/Developer-Simon/energy-node-installer/internal/media" + "github.com/Developer-Simon/energy-node-webui/hostapi" +) + +// mediaWingetCommand installiert den Imager ueber winget. +const mediaWingetCommand = "winget install -e --id RaspberryPiFoundation.RaspberryPiImager" + +// mediaPlatform meldet, dass dieser Rechner Medien vorbereiten kann. +func mediaPlatform() (supported bool, links []hostapi.MediaLink) { + return true, []hostapi.MediaLink{ + {Kind: "website", URL: mediaWebsiteURL}, + {Kind: "winget", Command: mediaWingetCommand}, + } +} + +var mediaRunner media.Runner = elevatedRunner + +var mediaEject = media.EjectDrive + +// locateImager sucht den installierten Imager an den bekannten Installationsorten. +func locateImager(ctx context.Context) (media.Imager, bool) { + return media.LocateWindowsImager() +} diff --git a/installer/internal/host/sudo_test.go b/installer/internal/host/sudo_test.go index 6537d5e81..0a3a9ebac 100644 --- a/installer/internal/host/sudo_test.go +++ b/installer/internal/host/sudo_test.go @@ -3,6 +3,7 @@ package host import ( "errors" "os/exec" + "runtime" "testing" "golang.org/x/crypto/ssh" @@ -42,6 +43,9 @@ func (e exitStatus) Error() string { return "exit" } func (e exitStatus) ExitStatus() int { return int(e) } func TestEnableSudoScriptIsValidShell(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("runs sh on the Linux sudo setup script") + } if out, err := exec.Command("sh", "-n", "-c", enableSudoScript).CombinedOutput(); err != nil { t.Fatalf("sh -n: %v\n%s", err, out) } diff --git a/installer/internal/media/conpty_windows.go b/installer/internal/media/conpty_windows.go new file mode 100644 index 000000000..1870c917d --- /dev/null +++ b/installer/internal/media/conpty_windows.go @@ -0,0 +1,183 @@ +package media + +import ( + "fmt" + "io" + "os" + "sync" + "time" + "unsafe" + + "golang.org/x/sys/windows" +) + +// Obergrenzen: alle Prozesse des Jobs muessen in dieser Zeit enden, die Konsolenausgabe in der zweiten. +// Ein beendeter Imager lebt, bis Windows seine gepufferten Schreibzugriffe abgearbeitet hat, bei +// langsamen Medien viele Minuten. Solange gilt der Auftrag als laufend. +const ( + jobWaitLimit = 30 * time.Minute + copyWaitLimit = 5 * time.Second +) + +// conptyImager ist der laufende Imager in der Pseudokonsole. Kill und Wait laufen in verschiedenen +// Goroutinen. mu schuetzt killed, closed und members sowie die Handles, die Kill liest. +type conptyImager struct { + log *os.File + + mu sync.Mutex + killed bool + closed bool + members []windows.Handle + job windows.Handle + proc windows.Handle + thread windows.Handle + hpc windows.Handle + inR, inW windows.Handle + outR windows.Handle + outW windows.Handle + out *os.File + copyDone chan struct{} +} + +// Kill beendet alle Prozesse des Jobs. Prozesse, die sich nicht mehr oeffnen lassen, verhindern das nicht. +func (w *conptyImager) Kill() error { + w.mu.Lock() + defer w.mu.Unlock() + if w.closed || w.killed { + return nil + } + w.killed = true + // Handles vor dem Beenden oeffnen: ein Handle ist erst signalisiert, wenn der Prozess weg ist. + members, err := openJobProcesses(w.job, w.log) + if err != nil { + fmt.Fprintln(w.log, "list job processes:", err) + } + w.members = members + if err := windows.TerminateJobObject(w.job, 1); err != nil { + return fmt.Errorf("TerminateJobObject: %w", err) + } + return nil +} + +// Wait wartet auf den Zwischenprozess, der den Imager-Exit-Code weitergibt, und raeumt alles auf. +func (w *conptyImager) Wait() (int, error) { + // Ohne Sperre warten, sonst blockiert Kill waehrend des Wartens. + var resErr error + rc, err := windows.WaitForSingleObject(w.proc, windows.INFINITE) + if err != nil { + resErr = fmt.Errorf("WaitForSingleObject: %w", err) + } else if rc != windows.WAIT_OBJECT_0 { + resErr = fmt.Errorf("WaitForSingleObject returned %#x", rc) + } + var exit uint32 + if err := windows.GetExitCodeProcess(w.proc, &exit); err != nil && resErr == nil { + resErr = fmt.Errorf("GetExitCodeProcess: %w", err) + } + + w.mu.Lock() + w.closed = true + members := w.members + w.members = nil + w.mu.Unlock() + + deadline := time.Now().Add(jobWaitLimit) + for _, m := range members { + left := max(time.Until(deadline), 0) + rc, err := windows.WaitForSingleObject(m, uint32(left/time.Millisecond)) + if (err != nil || rc != windows.WAIT_OBJECT_0) && resErr == nil { + resErr = fmt.Errorf("process still active: rc=%#x err=%v", rc, err) + } + _ = windows.CloseHandle(m) + } + + w.closePseudoConsole() + select { + case <-w.copyDone: + case <-time.After(copyWaitLimit): + } + w.closeAll() + + // Der Imager-Exit-Code kommt als uint32, Abstuerze wie 0xC0000005 werden so negativ. + return int(int32(exit)), resErr +} + +func (w *conptyImager) closePseudoConsole() { + if w.hpc != 0 { + windows.ClosePseudoConsole(w.hpc) + w.hpc = 0 + } +} + +// closeAll gibt alle noch offenen Handles frei. Doppeltes Schliessen ist sicher. +func (w *conptyImager) closeAll() { + w.closePseudoConsole() + closeHandle(&w.inR) + closeHandle(&w.outW) + closeHandle(&w.inW) + closeHandle(&w.outR) + if w.out != nil { + _ = w.out.Close() + w.out = nil + } + closeHandle(&w.thread) + closeHandle(&w.proc) + closeHandle(&w.job) +} + +func closeHandle(h *windows.Handle) { + if *h != 0 { + _ = windows.CloseHandle(*h) + *h = 0 + } +} + +// newKillOnCloseJob legt einen Job an, dessen Prozesse enden, sobald das letzte Handle schliesst. +func newKillOnCloseJob() (windows.Handle, error) { + job, err := windows.CreateJobObject(nil, nil) + if err != nil { + return 0, fmt.Errorf("CreateJobObject: %w", err) + } + var info windows.JOBOBJECT_EXTENDED_LIMIT_INFORMATION + info.BasicLimitInformation.LimitFlags = windows.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE + if _, err := windows.SetInformationJobObject(job, windows.JobObjectExtendedLimitInformation, + uintptr(unsafe.Pointer(&info)), uint32(unsafe.Sizeof(info))); err != nil { + _ = windows.CloseHandle(job) + return 0, fmt.Errorf("SetInformationJobObject: %w", err) + } + return job, nil +} + +// openJobProcesses liefert ein SYNCHRONIZE-Handle fuer jeden Prozess im Job und protokolliert jeden. +// Auch bei einem Fehler kommen die Handles zurueck, die sich oeffnen liessen. +func openJobProcesses(job windows.Handle, log io.Writer) ([]windows.Handle, error) { + // JOBOBJECT_BASIC_PROCESS_ID_LIST, Informationsklasse 3. + var list struct { + Assigned, InList uint32 + IDs [64]uintptr + } + if err := windows.QueryInformationJobObject(job, 3, + uintptr(unsafe.Pointer(&list)), uint32(unsafe.Sizeof(list)), nil); err != nil { + return nil, fmt.Errorf("QueryInformationJobObject: %w", err) + } + var handles []windows.Handle + var firstErr error + for _, id := range list.IDs[:min(int(list.InList), len(list.IDs))] { + h, err := windows.OpenProcess(windows.SYNCHRONIZE|windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(id)) + if err != nil { + fmt.Fprintf(log, "job process pid=%d: open error: %v\n", id, err) + if firstErr == nil { + firstErr = err + } + continue + } + name := make([]uint16, 1024) + n := uint32(len(name)) + if err := windows.QueryFullProcessImageName(h, 0, &name[0], &n); err != nil { + fmt.Fprintf(log, "job process pid=%d: name error: %v\n", id, err) + } else { + fmt.Fprintf(log, "job process pid=%d %s\n", id, windows.UTF16ToString(name[:n])) + } + handles = append(handles, h) + } + return handles, firstErr +} diff --git a/installer/internal/media/debianscript_test.go b/installer/internal/media/debianscript_test.go index 48aef500e..c1b90709d 100644 --- a/installer/internal/media/debianscript_test.go +++ b/installer/internal/media/debianscript_test.go @@ -6,6 +6,7 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "strings" "testing" ) @@ -67,6 +68,9 @@ db_get() { printf 'get|%s\n' "$1" >>"$REC_FILE"; RET=$FAKE_CONFIRM; } ` func TestEarlyScriptPicksOnlyAnInternalDisk(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("runs the Debian early script with sh on a Linux sysfs tree with symlinks") + } if _, err := exec.LookPath("sh"); err != nil { t.Skip("no sh on this host") } diff --git a/installer/internal/media/defaults.go b/installer/internal/media/defaults.go index 1d559e8f6..4d2d6489f 100644 --- a/installer/internal/media/defaults.go +++ b/installer/internal/media/defaults.go @@ -1,5 +1,7 @@ package media +import "strings" + // Defaults are the host values the installer form starts with. type Defaults struct { Timezone string @@ -16,6 +18,42 @@ type Defaults struct { // fixedKeyboards are the layouts offered in the form, in display order. var fixedKeyboards = []string{"de", "us", "gb", "fr", "ch", "it", "es", "nl", "se", "dk", "no", "fi", "pl", "cz"} +// klidLayouts ordnet die letzten vier Hex-Stellen einer Windows-KLID dem Layout zu. +var klidLayouts = map[string]string{ + "0407": "de", "0409": "us", "0809": "gb", "040c": "fr", "0807": "ch", "100c": "ch", + "0410": "it", "040a": "es", "0c0a": "es", "0413": "nl", "0813": "nl", "041d": "se", + "0406": "dk", "0414": "no", "040b": "fi", "0415": "pl", "0405": "cz", +} + +// keyboardFromKLID returns the layout of a Windows keyboard layout ID such as "00000407", or "". +func keyboardFromKLID(klid string) string { + if len(klid) < 4 { + return "" + } + return klidLayouts[strings.ToLower(klid[len(klid)-4:])] +} + +// countryFromLocale returns the upper-case country of a locale such as de_DE.UTF-8 or de-DE, or "". +func countryFromLocale(locale string) string { + if i := strings.IndexAny(locale, ".@"); i >= 0 { + locale = locale[:i] + } + parts := strings.FieldsFunc(locale, func(r rune) bool { return r == '_' || r == '-' }) + if len(parts) < 2 { + return "" + } + last := parts[len(parts)-1] + if len(last) != 2 { + return "" + } + for _, r := range last { + if (r < 'A' || r > 'Z') && (r < 'a' || r > 'z') { + return "" + } + } + return strings.ToUpper(last) +} + // keyboardChoices returns the fixed layouts with the detected one first when it is missing. func keyboardChoices(detected string) []string { for _, k := range fixedKeyboards { diff --git a/installer/internal/media/defaults_linux.go b/installer/internal/media/defaults_linux.go index 464e12f05..1177699fe 100644 --- a/installer/internal/media/defaults_linux.go +++ b/installer/internal/media/defaults_linux.go @@ -9,7 +9,6 @@ import ( "os" "os/exec" "path/filepath" - "sort" "strconv" "strings" "time" @@ -17,9 +16,6 @@ import ( const zone1970Path = "/usr/share/zoneinfo/zone1970.tab" -// maxWifiNetworks begrenzt die Netze in Reichweite. -const maxWifiNetworks = 10 - // HostDefaults reads timezone, keyboard, and WLAN country from this computer. func HostDefaults() Defaults { d := Defaults{Timezone: "UTC", Keyboard: "us"} @@ -69,10 +65,7 @@ func nmcliWifiList(parent context.Context, rescan string, timeout time.Duration) // and "\" as "\\" in the SSID. Hidden networks (empty SSID) are skipped, access // points with the same name are merged. func parseWifiList(data []byte) (string, int, []WifiNetwork) { - var active string - var activeFreq int - byName := map[string]*WifiNetwork{} - var order []*WifiNetwork + var samples []wifiSample sc := bufio.NewScanner(bytes.NewReader(data)) for sc.Scan() { line := strings.TrimRight(sc.Text(), "\r") @@ -96,69 +89,21 @@ func parseWifiList(data []byte) (string, int, []WifiNetwork) { if ssid == "" { continue } - if activeField == "yes" && active == "" { - active, activeFreq = ssid, freq - } - n := byName[ssid] - if n == nil { - n = &WifiNetwork{SSID: ssid} - byName[ssid] = n - order = append(order, n) - } - if signal > n.Signal { - n.Signal = signal - } - switch { - case freq >= 5000: - n.Band5 = true - case freq > 0: - n.Band24 = true - } + samples = append(samples, wifiSample{SSID: ssid, FreqMHz: freq, Signal: signal, Active: activeField == "yes"}) } - sort.SliceStable(order, func(a, b int) bool { - if order[a].Signal != order[b].Signal { - return order[a].Signal > order[b].Signal - } - return order[a].SSID < order[b].SSID - }) - if len(order) > maxWifiNetworks { - order = order[:maxWifiNetworks] - } - nets := make([]WifiNetwork, len(order)) - for k, n := range order { - nets[k] = *n - } - return active, activeFreq, nets + return mergeWifi(samples) } // zoneCountries maps each zone of zone1970.tab to its first country code. func zoneCountries() map[string]string { data, err := os.ReadFile(zone1970Path) if err != nil { - return map[string]string{} + _, countries := embeddedZones() + return countries } return parseZoneCountries(data) } -// parseZoneCountries returns zone -> first country code (first column, comma separated) of zone1970.tab. -func parseZoneCountries(data []byte) map[string]string { - out := map[string]string{} - sc := bufio.NewScanner(bytes.NewReader(data)) - for sc.Scan() { - line := strings.TrimSpace(sc.Text()) - if line == "" || strings.HasPrefix(line, "#") { - continue - } - fields := strings.Split(line, "\t") - if len(fields) < 3 { - continue - } - code, _, _ := strings.Cut(strings.TrimSpace(fields[0]), ",") - out[strings.TrimSpace(fields[2])] = code - } - return out -} - // unescapeTerse reverses the backslash escaping of nmcli terse output. func unescapeTerse(s string) string { var b strings.Builder @@ -188,40 +133,14 @@ func localTimezone() string { return target[i+len(marker):] } -// timezoneList returns the sorted zone names from zone1970.tab plus UTC. +// timezoneList returns the sorted zone names from zone1970.tab plus UTC, or the embedded table. func timezoneList() []string { data, err := os.ReadFile(zone1970Path) if err != nil { - return []string{"UTC"} + zones, _ := embeddedZones() + return zones } - zones := parseZoneTab(data) - for _, z := range zones { - if z == "UTC" { - return zones - } - } - zones = append(zones, "UTC") - sort.Strings(zones) - return zones -} - -// parseZoneTab returns the sorted zone names (third column) of a zone1970.tab file. -func parseZoneTab(data []byte) []string { - var zones []string - sc := bufio.NewScanner(bytes.NewReader(data)) - for sc.Scan() { - line := strings.TrimSpace(sc.Text()) - if line == "" || strings.HasPrefix(line, "#") { - continue - } - fields := strings.Split(line, "\t") - if len(fields) < 3 { - continue - } - zones = append(zones, strings.TrimSpace(fields[2])) - } - sort.Strings(zones) - return zones + return zonesWithUTC(parseZoneTab(data)) } // localKeyboard returns the X11 layout from localectl, falling back to the console keymap. @@ -262,15 +181,3 @@ func localeFromEnv() string { } return os.Getenv("LANG") } - -// countryFromLocale returns the upper-case country of a locale such as de_DE.UTF-8, or "". -func countryFromLocale(locale string) string { - if i := strings.IndexAny(locale, ".@"); i >= 0 { - locale = locale[:i] - } - parts := strings.Split(locale, "_") - if len(parts) != 2 { - return "" - } - return strings.ToUpper(parts[1]) -} diff --git a/installer/internal/media/defaults_other.go b/installer/internal/media/defaults_other.go index aaaf8744c..5ee3bfb54 100644 --- a/installer/internal/media/defaults_other.go +++ b/installer/internal/media/defaults_other.go @@ -1,4 +1,4 @@ -//go:build !linux +//go:build !linux && !windows package media diff --git a/installer/internal/media/defaults_windows.go b/installer/internal/media/defaults_windows.go new file mode 100644 index 000000000..cfba7fd6f --- /dev/null +++ b/installer/internal/media/defaults_windows.go @@ -0,0 +1,60 @@ +//go:build windows + +package media + +import ( + "context" + "syscall" + "unsafe" + + "golang.org/x/sys/windows/registry" +) + +// localeNameMaxLength entspricht LOCALE_NAME_MAX_LENGTH der Windows-API. +const localeNameMaxLength = 85 + +var procGetUserDefaultLocaleName = syscall.NewLazyDLL("kernel32.dll").NewProc("GetUserDefaultLocaleName") + +// HostDefaults reads timezone, keyboard and country from Windows. Missing values +// fall back to UTC, us and an empty country. +func HostDefaults() Defaults { + d := Defaults{Timezone: "UTC", Keyboard: "us"} + zone := windowsZoneToIANA(registryString(registry.LOCAL_MACHINE, `SYSTEM\CurrentControlSet\Control\TimeZoneInformation`, "TimeZoneKeyName")) + if zone != "" { + d.Timezone = zone + } + d.Timezones, d.ZoneCountries = embeddedZones() + if kb := keyboardFromKLID(registryString(registry.CURRENT_USER, `Keyboard Layout\Preload`, "1")); kb != "" { + d.Keyboard = kb + } + d.Keyboards = keyboardChoices(d.Keyboard) + d.WifiCountry = countryFromLocale(userLocaleName()) + ctx, cancel := context.WithTimeout(context.Background(), wlanCallTimeout) + defer cancel() + d.WifiSSID, d.WifiFreqMHz, d.WifiNetworks = windowsWifi(ctx, false) + return d +} + +// registryString returns a string value, or "" when the key or value cannot be read. +func registryString(root registry.Key, path, name string) string { + key, err := registry.OpenKey(root, path, registry.QUERY_VALUE) + if err != nil { + return "" + } + defer key.Close() + value, _, err := key.GetStringValue(name) + if err != nil { + return "" + } + return value +} + +// userLocaleName returns the user's default locale name such as de-DE, or "". +func userLocaleName() string { + buf := make([]uint16, localeNameMaxLength) + n, _, _ := procGetUserDefaultLocaleName.Call(uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf))) + if n == 0 { + return "" + } + return syscall.UTF16ToString(buf) +} diff --git a/installer/internal/media/drives_other.go b/installer/internal/media/drives_other.go index 19bb1aa5f..144e2a164 100644 --- a/installer/internal/media/drives_other.go +++ b/installer/internal/media/drives_other.go @@ -1,4 +1,4 @@ -//go:build !linux +//go:build !linux && !windows package media diff --git a/installer/internal/media/drives_windows.go b/installer/internal/media/drives_windows.go new file mode 100644 index 000000000..096309c12 --- /dev/null +++ b/installer/internal/media/drives_windows.go @@ -0,0 +1,28 @@ +//go:build windows + +package media + +import ( + "bytes" + "context" + "errors" + "fmt" + "os/exec" +) + +// ListDrives fragt Windows nach den Platten. Das Skript laeuft ohne Konsolenfenster +// und ohne erhoehte Rechte, weil Get-Disk und Get-Volume das fuer Lesezugriffe nicht brauchen. +func ListDrives(ctx context.Context) ([]Drive, error) { + cmd := exec.CommandContext(ctx, "powershell.exe", + "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", windowsDiskScript) + hideWindow(cmd) + out, err := cmd.Output() + if err != nil { + var exitErr *exec.ExitError + if errors.As(err, &exitErr) { + return nil, fmt.Errorf("media: powershell disk list: %w: %s", err, bytes.TrimSpace(exitErr.Stderr)) + } + return nil, fmt.Errorf("media: powershell disk list: %w", err) + } + return ParseWindowsDisks(out) +} diff --git a/installer/internal/media/drives_windowsparse.go b/installer/internal/media/drives_windowsparse.go new file mode 100644 index 000000000..105e8f5e5 --- /dev/null +++ b/installer/internal/media/drives_windowsparse.go @@ -0,0 +1,252 @@ +package media + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "sort" + "strconv" + "strings" +) + +// windowsDiskScript liefert Platten, Partitionen und Volumes als JSON. +// Die Ausgabe wird in ParseWindowsDisks ausgewertet. +const windowsDiskScript = `$ErrorActionPreference = 'Stop' +[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 +$d = @(Get-Disk | Select-Object Number, FriendlyName, Size, @{n='BusType';e={[string]$_.BusType}}, IsBoot, IsSystem) +$p = @(Get-Partition | Select-Object DiskNumber, PartitionNumber, @{n='DriveLetter';e={[string]$_.DriveLetter}}, Size, @{n='AccessPaths';e={@($_.AccessPaths)}}) +$v = @(Get-Volume | Select-Object Path, FileSystemLabel, FileSystem, Size, SizeRemaining) +@{ disks = $d; partitions = $p; volumes = $v; systemDrive = $env:SystemDrive } | ConvertTo-Json -Depth 4 -Compress` + +// windowsBusNames ist die Microsoft-Tabelle der BusType-Werte. +var windowsBusNames = []string{ + "Unknown", "SCSI", "ATAPI", "ATA", "1394", "SSA", "Fibre Channel", "USB", + "RAID", "iSCSI", "SAS", "SATA", "SD", "MMC", "Virtual", "FileBackedVirtual", + "Storage Spaces", "NVMe", "SCM", "UFS", +} + +type winDisk struct { + Number int `json:"Number"` + FriendlyName string `json:"FriendlyName"` + Size int64 `json:"Size"` + BusType json.RawMessage `json:"BusType"` + IsBoot *bool `json:"IsBoot"` + IsSystem *bool `json:"IsSystem"` +} + +type winPartition struct { + DiskNumber int `json:"DiskNumber"` + PartitionNumber int `json:"PartitionNumber"` + DriveLetter string `json:"DriveLetter"` + Size int64 `json:"Size"` + AccessPaths json.RawMessage `json:"AccessPaths"` +} + +type winVolume struct { + Path string `json:"Path"` + FileSystemLabel string `json:"FileSystemLabel"` + FileSystem string `json:"FileSystem"` + Size int64 `json:"Size"` + SizeRemaining int64 `json:"SizeRemaining"` +} + +type winDisksDoc struct { + Disks json.RawMessage `json:"disks"` + Partitions json.RawMessage `json:"partitions"` + Volumes json.RawMessage `json:"volumes"` + SystemDrive string `json:"systemDrive"` +} + +// ParseWindowsDisks liefert die Wechselmedien und internen Platten ohne das +// Systemlaufwerk. Fail closed: fehlt systemDrive, ist das ein Fehler. Platten +// mit fehlenden Boot- oder Systemflags werden ausgeblendet. +func ParseWindowsDisks(data []byte) ([]Drive, error) { + if len(bytes.TrimSpace(data)) == 0 { + return nil, errors.New("media: windows disk list: empty output") + } + var doc winDisksDoc + if err := json.Unmarshal(data, &doc); err != nil { + return nil, fmt.Errorf("media: windows disk list: %w", err) + } + sys := strings.TrimSpace(doc.SystemDrive) + if sys == "" { + return nil, errors.New("media: windows disk list: systemDrive fehlt") + } + sysLetter := strings.ToUpper(sys[:1]) + + disks, err := decodeWinList[winDisk](doc.Disks) + if err != nil { + return nil, fmt.Errorf("media: windows disk list: disks: %w", err) + } + parts, err := decodeWinList[winPartition](doc.Partitions) + if err != nil { + return nil, fmt.Errorf("media: windows disk list: partitions: %w", err) + } + vols, err := decodeWinList[winVolume](doc.Volumes) + if err != nil { + return nil, fmt.Errorf("media: windows disk list: volumes: %w", err) + } + + volByPath := make(map[string]winVolume, len(vols)) + for _, v := range vols { + volByPath[v.Path] = v + } + partsByDisk := make(map[int][]winPartition) + for _, p := range parts { + partsByDisk[p.DiskNumber] = append(partsByDisk[p.DiskNumber], p) + } + + sort.SliceStable(disks, func(i, j int) bool { return disks[i].Number < disks[j].Number }) + drives := make([]Drive, 0, len(disks)) + for _, d := range disks { + if d.Size <= 0 || d.IsBoot == nil || d.IsSystem == nil || *d.IsBoot || *d.IsSystem { + continue + } + dParts := partsByDisk[d.Number] + if holdsSystemLetter(dParts, sysLetter) { + continue + } + drives = append(drives, d.drive(dParts, volByPath)) + } + return drives, nil +} + +// holdsSystemLetter reports whether one partition has the system drive letter. +func holdsSystemLetter(parts []winPartition, sysLetter string) bool { + for _, p := range parts { + if letter := driveLetter(p.DriveLetter); letter != "" && strings.EqualFold(letter, sysLetter) { + return true + } + } + return false +} + +// driveLetter liefert den Laufwerksbuchstaben, NUL und Leerzeichen gelten als leer. +func driveLetter(raw string) string { + s := strings.Trim(raw, "\x00 \t\r\n") + if s == "" { + return "" + } + return s[:1] +} + +func (d winDisk) drive(parts []winPartition, vols map[string]winVolume) Drive { + model := strings.TrimSpace(d.FriendlyName) + if model == "" { + model = fmt.Sprintf("PhysicalDrive%d", d.Number) + } + bus := windowsBusName(d.BusType) + sort.SliceStable(parts, func(i, j int) bool { return parts[i].PartitionNumber < parts[j].PartitionNumber }) + partitions := make([]Partition, 0, len(parts)) + for _, p := range parts { + partitions = append(partitions, p.partition(vols)) + } + return Drive{ + Path: fmt.Sprintf(`\\.\PhysicalDrive%d`, d.Number), + Model: model, + Size: d.Size, + Transport: windowsTransport(bus), + Removable: isWindowsRemovableBus(bus), + Partitions: partitions, + } +} + +func (p winPartition) partition(vols map[string]winVolume) Partition { + out := Partition{Name: fmt.Sprintf("Partition %d", p.PartitionNumber)} + if letter := driveLetter(p.DriveLetter); letter != "" { + out.Name = letter + ":" + } + paths, err := decodeWinList[string](p.AccessPaths) + if err != nil { + return out + } + for _, path := range paths { + if v, ok := vols[path]; ok { + out.Label = v.FileSystemLabel + out.FSType = v.FileSystem + out.Used = v.Size - v.SizeRemaining + break + } + } + return out +} + +// windowsBusName liefert den Namen eines BusType, auch als Zahl oder Zahlentext. +func windowsBusName(raw json.RawMessage) string { + var s string + if json.Unmarshal(raw, &s) == nil { + if n, err := strconv.Atoi(s); err == nil { + return windowsBusByNumber(n) + } + return s + } + var n int + if json.Unmarshal(raw, &n) == nil { + return windowsBusByNumber(n) + } + return "" +} + +func windowsBusByNumber(n int) string { + if n < 0 || n >= len(windowsBusNames) { + return "" + } + return windowsBusNames[n] +} + +func windowsTransport(bus string) string { + switch strings.ToUpper(bus) { + case "USB": + return "usb" + case "SD", "MMC": + return "mmc" + case "SATA", "ATA": + return "sata" + case "NVME": + return "nvme" + } + return strings.ToLower(bus) +} + +func isWindowsRemovableBus(bus string) bool { + switch strings.ToUpper(bus) { + case "USB", "SD", "MMC": + return true + } + return false +} + +// decodeWinList liest eine JSON-Liste, die als Array, Einzelobjekt oder null +// kommen darf. Windows PowerShell 5.1 verpackt Arrays hinter berechneten +// Eigenschaften auch als {"value":[...],"Count":n}. +func decodeWinList[T any](raw json.RawMessage) ([]T, error) { + raw = bytes.TrimSpace(raw) + if len(raw) == 0 || string(raw) == "null" { + return nil, nil + } + if raw[0] == '{' { + var wrapped struct { + Value json.RawMessage `json:"value"` + Count *int `json:"Count"` + } + if err := json.Unmarshal(raw, &wrapped); err != nil { + return nil, err + } + if wrapped.Count != nil && wrapped.Value != nil { + return decodeWinList[T](wrapped.Value) + } + } + if raw[0] == '[' { + var out []T + if err := json.Unmarshal(raw, &out); err != nil { + return nil, err + } + return out, nil + } + var one T + if err := json.Unmarshal(raw, &one); err != nil { + return nil, err + } + return []T{one}, nil +} diff --git a/installer/internal/media/drives_windowsparse_test.go b/installer/internal/media/drives_windowsparse_test.go new file mode 100644 index 000000000..7bae73a3a --- /dev/null +++ b/installer/internal/media/drives_windowsparse_test.go @@ -0,0 +1,271 @@ +package media + +import ( + "os" + "testing" +) + +func loadWindowsDisks(t *testing.T, name string) []Drive { + t.Helper() + data, err := os.ReadFile("testdata/windows/" + name) + if err != nil { + t.Fatal(err) + } + drives, err := ParseWindowsDisks(data) + if err != nil { + t.Fatalf("ParseWindowsDisks(%s): %v", name, err) + } + return drives +} + +func mustParseWindowsDisks(t *testing.T, data string) []Drive { + t.Helper() + drives, err := ParseWindowsDisks([]byte(data)) + if err != nil { + t.Fatalf("ParseWindowsDisks: %v", err) + } + return drives +} + +func equalStrings(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +func TestWindowsDisksHideTheSystemDisk(t *testing.T) { + drives := mustParseWindowsDisks(t, `{ + "disks": [{"Number": 0, "FriendlyName": "CT2000P3SSD8", "Size": 2000398934016, "BusType": "NVMe", "IsSystem": true}], + "partitions": [], + "volumes": [], + "systemDrive": "C:" + }`) + if len(drives) != 0 { + t.Fatalf("got %d drives, want none: %v", len(drives), drivePaths(drives)) + } +} + +func TestWindowsDisksHideTheSystemDriveLetterDisk(t *testing.T) { + drives := mustParseWindowsDisks(t, `{ + "disks": [ + {"Number": 0, "FriendlyName": "SYS", "Size": 500000000000, "BusType": "NVMe", "IsBoot": false, "IsSystem": false}, + {"Number": 1, "FriendlyName": "Stick", "Size": 8000000000, "BusType": "USB", "IsBoot": false, "IsSystem": false} + ], + "partitions": [ + {"DiskNumber": 0, "PartitionNumber": 1, "DriveLetter": "C", "Size": 400000000000, "AccessPaths": []}, + {"DiskNumber": 1, "PartitionNumber": 1, "DriveLetter": "", "Size": 7000000000, "AccessPaths": []} + ], + "volumes": [], + "systemDrive": "c:" + }`) + if got, want := drivePaths(drives), []string{`\\.\PhysicalDrive1`}; !equalStrings(got, want) { + t.Fatalf("paths = %v, want %v", got, want) + } +} + +func TestWindowsDisksUsbStickIsRemovable(t *testing.T) { + drives := mustParseWindowsDisks(t, `{ + "disks": [{"Number": 2, "FriendlyName": " Kingston DataTraveler 3.0 ", "Size": 15931539456, "BusType": "USB", "IsBoot": false, "IsSystem": false}], + "partitions": [{"DiskNumber": 2, "PartitionNumber": 1, "DriveLetter": "E", "Size": 15931000000, "AccessPaths": ["E:\\", "\\\\?\\Volume{abc}\\"]}], + "volumes": [{"Path": "\\\\?\\Volume{abc}\\", "FileSystemLabel": "WERKSTATT", "FileSystem": "FAT32", "Size": 1000, "SizeRemaining": 400}], + "systemDrive": "C:" + }`) + if len(drives) != 1 { + t.Fatalf("got %d drives, want 1", len(drives)) + } + d := drives[0] + if d.Path != `\\.\PhysicalDrive2` { + t.Errorf("Path = %q", d.Path) + } + if d.Model != "Kingston DataTraveler 3.0" { + t.Errorf("Model = %q", d.Model) + } + if d.Size != 15931539456 { + t.Errorf("Size = %d", d.Size) + } + if d.Transport != "usb" || !d.Removable { + t.Errorf("Transport = %q, Removable = %v", d.Transport, d.Removable) + } + if len(d.Partitions) != 1 { + t.Fatalf("got %d partitions, want 1", len(d.Partitions)) + } + want := Partition{Name: "E:", Label: "WERKSTATT", FSType: "FAT32", Used: 600} + if d.Partitions[0] != want { + t.Errorf("partition = %+v, want %+v", d.Partitions[0], want) + } +} + +func TestWindowsDisksSdReaderIsRemovable(t *testing.T) { + drives := mustParseWindowsDisks(t, `{ + "disks": [{"Number": 4, "FriendlyName": "SD Reader", "Size": 64000000000, "BusType": "SD", "IsBoot": false, "IsSystem": false}], + "partitions": [], + "volumes": [], + "systemDrive": "C:" + }`) + if len(drives) != 1 { + t.Fatalf("got %d drives, want 1", len(drives)) + } + if drives[0].Transport != "mmc" || !drives[0].Removable { + t.Errorf("Transport = %q, Removable = %v", drives[0].Transport, drives[0].Removable) + } +} + +func TestWindowsDisksSataIsInternal(t *testing.T) { + drives := mustParseWindowsDisks(t, `{ + "disks": [{"Number": 1, "FriendlyName": "WD", "Size": 3000592982016, "BusType": "SATA", "IsBoot": false, "IsSystem": false}], + "partitions": [], + "volumes": [], + "systemDrive": "C:" + }`) + if len(drives) != 1 { + t.Fatalf("got %d drives, want 1", len(drives)) + } + if drives[0].Transport != "sata" || drives[0].Removable { + t.Errorf("Transport = %q, Removable = %v", drives[0].Transport, drives[0].Removable) + } +} + +func TestWindowsDisksAcceptsSingleObjectsAndNumericBusType(t *testing.T) { + drives := mustParseWindowsDisks(t, `{ + "disks": {"Number": 2, "FriendlyName": "", "Size": 8000000000, "BusType": 7, "IsBoot": false, "IsSystem": false}, + "partitions": {"DiskNumber": 2, "PartitionNumber": 1, "DriveLetter": "", "Size": 7900000000, "AccessPaths": null}, + "volumes": null, + "systemDrive": "C:" + }`) + if len(drives) != 1 { + t.Fatalf("got %d drives, want 1", len(drives)) + } + d := drives[0] + if d.Model != `PhysicalDrive2` { + t.Errorf("Model = %q, want the fallback name", d.Model) + } + if d.Transport != "usb" || !d.Removable { + t.Errorf("Transport = %q, Removable = %v", d.Transport, d.Removable) + } + if len(d.Partitions) != 1 || d.Partitions[0].Name != "Partition 1" { + t.Errorf("partitions = %+v", d.Partitions) + } +} + +func TestWindowsDisksRecordedOutput(t *testing.T) { + drives := loadWindowsDisks(t, "disks-usb.json") + if got, want := drivePaths(drives), []string{ + `\\.\PhysicalDrive0`, `\\.\PhysicalDrive1`, `\\.\PhysicalDrive2`, + `\\.\PhysicalDrive4`, `\\.\PhysicalDrive5`, + }; !equalStrings(got, want) { + t.Fatalf("paths = %v, want %v", got, want) + } + var removable []string + for _, d := range drives { + if d.Removable { + removable = append(removable, d.Path) + } + } + if want := []string{`\\.\PhysicalDrive4`, `\\.\PhysicalDrive5`}; !equalStrings(removable, want) { + t.Fatalf("removable = %v, want %v", removable, want) + } + reader := drives[3] + if reader.Removable != true || reader.Transport != "usb" { + t.Errorf("reader: Transport = %q, Removable = %v", reader.Transport, reader.Removable) + } + if len(reader.Partitions) != 2 { + t.Fatalf("reader partitions = %+v", reader.Partitions) + } + boot := reader.Partitions[0] + if boot.Name != "E:" || boot.Label != "bootfs" || boot.FSType != "FAT32" || boot.Used != 78434816 { + t.Errorf("boot partition = %+v", boot) + } + stick := drives[4] + if stick.Model != "TDK LoR Trans-It Drive" || stick.Size != 1992294400 { + t.Errorf("stick = %q, %d", stick.Model, stick.Size) + } + data := drives[0].Partitions + if len(data) != 2 || data[1].Name != "D:" || data[1].Label != "Data" || data[1].Used != 2742150529024 { + t.Errorf("data disk partitions = %+v", data) + } +} + +func TestWindowsDisksReadWrappedAccessPaths(t *testing.T) { + drives := mustParseWindowsDisks(t, `{ + "disks": [{"Number": 2, "FriendlyName": "Stick", "Size": 8000000000, "BusType": "USB", "IsBoot": false, "IsSystem": false}], + "partitions": [{"DiskNumber": 2, "PartitionNumber": 1, "DriveLetter": "E", "Size": 7000000000, "AccessPaths": {"value": ["E:\\", "\\\\?\\Volume{abc}\\"], "Count": 2}}], + "volumes": [{"Path": "\\\\?\\Volume{abc}\\", "FileSystemLabel": "Data", "FileSystem": "NTFS", "Size": 1000, "SizeRemaining": 400}], + "systemDrive": "C:" + }`) + if len(drives) != 1 || len(drives[0].Partitions) != 1 { + t.Fatalf("drives = %+v", drives) + } + want := Partition{Name: "E:", Label: "Data", FSType: "NTFS", Used: 600} + if drives[0].Partitions[0] != want { + t.Errorf("partition = %+v, want %+v", drives[0].Partitions[0], want) + } +} + +func TestWindowsDisksHideTheEmptyReader(t *testing.T) { + drives := loadWindowsDisks(t, "disks-empty-reader.json") + if got, want := drivePaths(drives), []string{ + `\\.\PhysicalDrive0`, `\\.\PhysicalDrive1`, `\\.\PhysicalDrive2`, `\\.\PhysicalDrive5`, + }; !equalStrings(got, want) { + t.Fatalf("paths = %v, want %v", got, want) + } +} + +func TestWindowsDisksWithoutRemovableMedia(t *testing.T) { + drives := loadWindowsDisks(t, "disks-none.json") + if got, want := drivePaths(drives), []string{ + `\\.\PhysicalDrive0`, `\\.\PhysicalDrive1`, `\\.\PhysicalDrive2`, + }; !equalStrings(got, want) { + t.Fatalf("paths = %v, want %v", got, want) + } + if got := Visible(drives, false); len(got) != 0 { + t.Fatalf("removable drives = %v, want none", drivePaths(got)) + } +} + +func TestWindowsDisksWithoutSystemDriveIsAnError(t *testing.T) { + for name, data := range map[string]string{ + "empty": `{"disks": [{"Number": 1, "Size": 8000000000, "BusType": "USB", "IsBoot": false, "IsSystem": false}], "partitions": [], "volumes": [], "systemDrive": ""}`, + "missing": `{"disks": [{"Number": 1, "Size": 8000000000, "BusType": "USB", "IsBoot": false, "IsSystem": false}], "partitions": [], "volumes": []}`, + } { + drives, err := ParseWindowsDisks([]byte(data)) + if err == nil { + t.Errorf("%s: no error", name) + } + if len(drives) != 0 { + t.Errorf("%s: got drives %v", name, drivePaths(drives)) + } + } +} + +func TestWindowsDisksHideDisksWithUnknownBootFlags(t *testing.T) { + drives := mustParseWindowsDisks(t, `{ + "disks": [ + {"Number": 1, "FriendlyName": "NullBoot", "Size": 8000000000, "BusType": "USB", "IsBoot": null, "IsSystem": false}, + {"Number": 2, "FriendlyName": "NoSystem", "Size": 8000000000, "BusType": "USB", "IsBoot": false}, + {"Number": 3, "FriendlyName": "Known", "Size": 8000000000, "BusType": "USB", "IsBoot": false, "IsSystem": false} + ], + "partitions": [], + "volumes": [], + "systemDrive": "C:" + }`) + if got, want := drivePaths(drives), []string{`\\.\PhysicalDrive3`}; !equalStrings(got, want) { + t.Fatalf("paths = %v, want %v", got, want) + } +} + +func TestWindowsDisksInvalidInputIsAnError(t *testing.T) { + for name, data := range map[string]string{ + "invalid json": `{"disks": [`, + "empty input": ``, + } { + if _, err := ParseWindowsDisks([]byte(data)); err == nil { + t.Errorf("%s: no error", name) + } + } +} diff --git a/installer/internal/media/eject.go b/installer/internal/media/eject.go new file mode 100644 index 000000000..a68e0795f --- /dev/null +++ b/installer/internal/media/eject.go @@ -0,0 +1,52 @@ +package media + +import ( + "context" + "fmt" + "regexp" +) + +var driveNameRe = regexp.MustCompile(`^[A-Z]:$`) + +// ejectScript returns the PowerShell script that ejects the volume with the +// drive letter name such as "E:", like "Eject" in the Explorer. ok is false for +// every other name. +func ejectScript(name string) (script string, ok bool) { + if !driveNameRe.MatchString(name) { + return "", false + } + return fmt.Sprintf(`$ErrorActionPreference = 'Stop' +$item = (New-Object -ComObject Shell.Application).Namespace(17).ParseName('%[1]s') +if ($null -eq $item) { exit 0 } +$item.InvokeVerb('Eject') +for ($i = 0; $i -lt 20; $i++) { if (-not (Test-Path '%[1]s\')) { exit 0 }; Start-Sleep -Milliseconds 250 } +[Console]::Error.WriteLine('%[1]s is still mounted') +exit 1`, name), true +} + +// ejectDrive lists the drives again, because the written medium has new drive +// letters, and runs the eject script for each letter of the same drive. +func ejectDrive(ctx context.Context, d Drive, + list func(context.Context) ([]Drive, error), + run func(ctx context.Context, script string) error) error { + drives, err := list(ctx) + if err != nil { + return err + } + for _, x := range drives { + if x.Path != d.Path || x.Model != d.Model || x.Size != d.Size { + continue + } + for _, p := range x.Partitions { + script, ok := ejectScript(p.Name) + if !ok { + continue + } + if err := run(ctx, script); err != nil { + return err + } + } + return nil + } + return ErrDriveGone +} diff --git a/installer/internal/media/eject_test.go b/installer/internal/media/eject_test.go new file mode 100644 index 000000000..135cdd26a --- /dev/null +++ b/installer/internal/media/eject_test.go @@ -0,0 +1,44 @@ +package media + +import ( + "context" + "errors" + "strings" + "testing" +) + +func TestEjectRunsOneScriptPerDriveLetterOfTheSameDrive(t *testing.T) { + written := Drive{Path: `\\.\PhysicalDrive4`, Model: "Reader", Size: 4000, Removable: true} + listed := written + listed.Partitions = []Partition{{Name: "E:"}, {Name: "Partition 2"}, {Name: "F:"}} + var scripts []string + err := ejectDrive(context.Background(), written, + func(context.Context) ([]Drive, error) { return []Drive{listed}, nil }, + func(_ context.Context, script string) error { scripts = append(scripts, script); return nil }) + if err != nil { + t.Fatal(err) + } + if len(scripts) != 2 || !strings.Contains(scripts[0], "ParseName('E:')") || !strings.Contains(scripts[1], "ParseName('F:')") { + t.Fatalf("scripts = %v", scripts) + } +} + +func TestEjectDoesNothingWhenTheDriveChanged(t *testing.T) { + written := Drive{Path: `\\.\PhysicalDrive4`, Model: "Reader", Size: 4000, Removable: true} + other := Drive{Path: written.Path, Model: "Other disk", Size: 9000, Partitions: []Partition{{Name: "D:"}}} + ran := false + err := ejectDrive(context.Background(), written, + func(context.Context) ([]Drive, error) { return []Drive{other}, nil }, + func(context.Context, string) error { ran = true; return nil }) + if !errors.Is(err, ErrDriveGone) || ran { + t.Fatalf("err = %v, ran = %v", err, ran) + } +} + +func TestEjectScriptRefusesAnythingButADriveLetter(t *testing.T) { + for _, name := range []string{"Partition 1", "E", "e:", "E:'; Remove-Item x; '", ""} { + if _, ok := ejectScript(name); ok { + t.Errorf("%q accepted", name) + } + } +} diff --git a/installer/internal/media/eject_windows.go b/installer/internal/media/eject_windows.go new file mode 100644 index 000000000..7b14de0c7 --- /dev/null +++ b/installer/internal/media/eject_windows.go @@ -0,0 +1,25 @@ +//go:build windows + +package media + +import ( + "bytes" + "context" + "fmt" + "os/exec" +) + +// EjectDrive ejects every volume of the drive d. It needs no administrator rights. +func EjectDrive(ctx context.Context, d Drive) error { + return ejectDrive(ctx, d, ListDrives, func(ctx context.Context, script string) error { + cmd := exec.CommandContext(ctx, "powershell.exe", + "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script) + hideWindow(cmd) + var stderr bytes.Buffer + cmd.Stderr = &stderr + if err := cmd.Run(); err != nil { + return fmt.Errorf("media: eject: %w: %s", err, bytes.TrimSpace(stderr.Bytes())) + } + return nil + }) +} diff --git a/installer/internal/media/helper.go b/installer/internal/media/helper.go new file mode 100644 index 000000000..81ddfe40c --- /dev/null +++ b/installer/internal/media/helper.go @@ -0,0 +1,308 @@ +package media + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "sync" + "time" +) + +// HelperName ist der Unterbefehl, der RunHelper im Installer-Binary startet. +const HelperName = "media-helper" + +// ShimName ist der Unterbefehl, der unter Windows den Imager in der Pseudokonsole startet. +const ShimName = "media-shim" + +// HelperFiles sind die Dateien, ueber die Installer und Helfer sprechen. Status ist optional. +type HelperFiles struct{ Log, Cancel, Status string } + +// imagerProcess ist der laufende Imager, plattformspezifisch erzeugt. +type imagerProcess interface { + Wait() (int, error) + Kill() error +} + +// PrepareHelperFiles legt Log und Status leer an, als aufrufender Benutzer. +// Die Abbruchdatei wird nicht angelegt. +func PrepareHelperFiles(dir string) (HelperFiles, error) { + f := HelperFiles{ + Log: filepath.Join(dir, "imager.log"), + Cancel: filepath.Join(dir, "cancel"), + Status: filepath.Join(dir, "status"), + } + for _, p := range []string{f.Log, f.Status} { + file, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600) + if err != nil { + return HelperFiles{}, err + } + if err := file.Close(); err != nil { + return HelperFiles{}, err + } + } + return f, nil +} + +// ReadHelperStatus liest den Exit-Code aus der Statusdatei. false bei leer oder kaputt. +func ReadHelperStatus(path string) (int, bool) { + data, err := os.ReadFile(path) + if err != nil { + return 0, false + } + code, err := strconv.Atoi(strings.TrimSpace(string(data))) + if err != nil { + return 0, false + } + return code, true +} + +// checkImagerName erlaubt nur den Imager selbst, nicht beliebige Programme. +func checkImagerName(name string) error { + base := filepath.Base(name) + if base != "rpi-imager.exe" && base != "rpi-imager" { + return fmt.Errorf("refusing to run %s", base) + } + return nil +} + +// RunHelper startet den Imager, schreibt seine Ausgabe ins Log und liefert den Exit-Code. +// Erscheint die Abbruchdatei, wird der Imager beendet. +func RunHelper(ctx context.Context, f HelperFiles, name string, args []string) int { + log, err := os.OpenFile(f.Log, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o600) + if err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + return finishHelper(f, 125) + } + defer log.Close() + + if err := checkImagerName(name); err != nil { + fmt.Fprintf(log, "Error: %v\n", err) + return finishHelper(f, 125) + } + if fileExists(f.Cancel) { + fmt.Fprintln(log, "Error: cancelled before start") + return finishHelper(f, 1) + } + + proc, err := startImager(log, name, args) + if err != nil { + fmt.Fprintf(log, "Error: %v\n", err) + return finishHelper(f, 125) + } + + type waitResult struct { + code int + err error + } + waited := make(chan waitResult, 1) + go func() { + code, err := proc.Wait() + waited <- waitResult{code, err} + }() + + killed := false + kill := func() { + if killed { + return + } + killed = true + if err := proc.Kill(); err != nil { + fmt.Fprintf(log, "Error: kill: %v\n", err) + } + } + + ticker := time.NewTicker(250 * time.Millisecond) + defer ticker.Stop() + cancelled := ctx.Done() + for { + select { + case r := <-waited: + if r.err != nil { + fmt.Fprintf(log, "Error: %v\n", r.err) + return finishHelper(f, 125) + } + code := r.code + if code < 0 { + // Durch Signal beendet: nie als Erfolg oder ungueltiger Code melden. + code = 1 + } + return finishHelper(f, code) + case <-ticker.C: + if fileExists(f.Cancel) { + kill() + } + case <-cancelled: + cancelled = nil + kill() + } + } +} + +// finishHelper schreibt den Exit-Code in die Statusdatei, falls eine gesetzt ist. +func finishHelper(f HelperFiles, code int) int { + if f.Status != "" { + if file, err := os.OpenFile(f.Status, os.O_WRONLY|os.O_TRUNC, 0); err == nil { + _, _ = fmt.Fprintf(file, "%d\n", code) + _ = file.Close() + } + } + return code +} + +// RunShim startet name mit den geerbten Standardkanaelen und liefert dessen Exit-Code. +// Die Kindprozesse erben bewusst die Konsole des Shims. +func RunShim(name string, args []string) int { + if err := checkImagerName(name); err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + return 125 + } + prepareShimConsole() + cmd := exec.Command(name, args...) + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + err := cmd.Run() + if err == nil { + return 0 + } + var ee *exec.ExitError + if errors.As(err, &ee) { + if code := ee.ExitCode(); code >= 0 { + return code + } + return 1 + } + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + return 125 +} + +// startExec startet name mit Ausgabe ins Log, ohne Pseudokonsole. +// Die Plattformdateien rufen es aus startImager auf. +func startExec(log *os.File, name string, args []string) (imagerProcess, error) { + cmd := exec.Command(name, args...) + cmd.Stdout = log + cmd.Stderr = log + hideWindow(cmd) + if err := cmd.Start(); err != nil { + return nil, err + } + return execImager{cmd}, nil +} + +type execImager struct{ cmd *exec.Cmd } + +func (e execImager) Wait() (int, error) { + err := e.cmd.Wait() + if err == nil { + return 0, nil + } + var ee *exec.ExitError + if errors.As(err, &ee) { + return ee.ExitCode(), nil + } + return 0, err +} + +func (e execImager) Kill() error { return e.cmd.Process.Kill() } + +// TailLog liefert alle Bytes, die in path geschrieben werden. Die Datei darf anfangs fehlen. +// Ist done geschlossen, liest es den Rest und liefert danach io.EOF. +// Close beendet das Folgen sofort und gibt die Datei frei. +func TailLog(path string, done <-chan struct{}) io.ReadCloser { + return &tailReader{ + path: path, + done: done, + stop: make(chan struct{}), + } +} + +const tailPoll = 100 * time.Millisecond + +type tailReader struct { + path string + done <-chan struct{} + stop chan struct{} + once sync.Once + + mu sync.Mutex + f *os.File +} + +func (t *tailReader) Read(p []byte) (int, error) { + for { + if isClosed(t.stop) { + return 0, io.EOF + } + // Erst pruefen, dann lesen: so geht kein Byte verloren, das vor done geschrieben wurde. + finished := isClosed(t.done) + n, err := t.readOnce(p) + if n > 0 { + return n, nil + } + if err != nil { + return 0, err + } + if finished { + _ = t.Close() + return 0, io.EOF + } + select { + case <-t.done: + case <-t.stop: + case <-time.After(tailPoll): + } + } +} + +func (t *tailReader) readOnce(p []byte) (int, error) { + t.mu.Lock() + defer t.mu.Unlock() + if isClosed(t.stop) { + return 0, io.EOF + } + if t.f == nil { + f, err := os.Open(t.path) + if err != nil { + return 0, nil // Datei fehlt noch + } + t.f = f + } + n, err := t.f.Read(p) + if errors.Is(err, io.EOF) { + // Noch kein neues Ende: der Aufrufer wartet auf weitere Bytes. + return n, nil + } + return n, err +} + +func (t *tailReader) Close() error { + t.once.Do(func() { close(t.stop) }) + t.mu.Lock() + defer t.mu.Unlock() + if t.f != nil { + err := t.f.Close() + t.f = nil + return err + } + return nil +} + +func isClosed(c <-chan struct{}) bool { + select { + case <-c: + return true + default: + return false + } +} + +func fileExists(path string) bool { + _, err := os.Stat(path) + return err == nil +} diff --git a/installer/internal/media/helper_other.go b/installer/internal/media/helper_other.go new file mode 100644 index 000000000..2dbb658f3 --- /dev/null +++ b/installer/internal/media/helper_other.go @@ -0,0 +1,18 @@ +//go:build !windows + +package media + +import ( + "os" + "os/exec" +) + +// hideWindow ist auf Nicht-Windows-Systemen ein No-op. +func hideWindow(cmd *exec.Cmd) {} + +// prepareShimConsole ist auf Nicht-Windows-Systemen ein No-op. +func prepareShimConsole() {} + +func startImager(log *os.File, name string, args []string) (imagerProcess, error) { + return startExec(log, name, args) +} diff --git a/installer/internal/media/helper_test.go b/installer/internal/media/helper_test.go new file mode 100644 index 000000000..cf7631a30 --- /dev/null +++ b/installer/internal/media/helper_test.go @@ -0,0 +1,176 @@ +//go:build !windows + +package media + +import ( + "context" + "io" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// writeImagerScript legt ein Shellskript namens rpi-imager an und liefert seinen Pfad. +func writeImagerScript(t *testing.T, dir, body string) string { + t.Helper() + path := filepath.Join(dir, "rpi-imager") + if err := os.WriteFile(path, []byte("#!/bin/sh\n"+body+"\n"), 0o755); err != nil { + t.Fatal(err) + } + return path +} + +func TestRunHelperWritesOutputAndExitCode(t *testing.T) { + dir := t.TempDir() + f, err := PrepareHelperFiles(dir) + if err != nil { + t.Fatal(err) + } + script := writeImagerScript(t, dir, `printf ' Writing: [>] 10 %%\r'; exit 3`) + + code := RunHelper(context.Background(), f, script, nil) + if code != 3 { + t.Fatalf("exit code = %d, want 3", code) + } + log, err := os.ReadFile(f.Log) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(log), " Writing: [>] 10 %") { + t.Fatalf("log = %q, want the writing line", log) + } + got, ok := ReadHelperStatus(f.Status) + if !ok || got != 3 { + t.Fatalf("ReadHelperStatus = %d, %v, want 3, true", got, ok) + } +} + +func TestPrepareHelperFilesCreatesLogAndStatusOnly(t *testing.T) { + dir := t.TempDir() + f, err := PrepareHelperFiles(dir) + if err != nil { + t.Fatal(err) + } + if f.Log != filepath.Join(dir, "imager.log") || f.Status != filepath.Join(dir, "status") || f.Cancel != filepath.Join(dir, "cancel") { + t.Fatalf("paths = %+v", f) + } + for _, p := range []string{f.Log, f.Status} { + info, err := os.Stat(p) + if err != nil { + t.Fatalf("%s not created: %v", p, err) + } + if info.Size() != 0 { + t.Fatalf("%s size = %d, want 0", p, info.Size()) + } + if info.Mode().Perm() != 0o600 { + t.Fatalf("%s mode = %v, want 0600", p, info.Mode().Perm()) + } + } + if _, err := os.Stat(f.Cancel); !os.IsNotExist(err) { + t.Fatalf("cancel file must not exist, stat err = %v", err) + } + if _, ok := ReadHelperStatus(f.Status); ok { + t.Fatal("empty status file must read as not ok") + } +} + +func TestRunHelperKillsOnCancelFile(t *testing.T) { + dir := t.TempDir() + f, err := PrepareHelperFiles(dir) + if err != nil { + t.Fatal(err) + } + script := writeImagerScript(t, dir, "exec sleep 30") + + go func() { + time.Sleep(300 * time.Millisecond) + _ = os.WriteFile(f.Cancel, nil, 0o600) + }() + + start := time.Now() + code := RunHelper(context.Background(), f, script, nil) + if code == 0 { + t.Fatal("killed imager must not return 0") + } + if elapsed := time.Since(start); elapsed > 2*time.Second { + t.Fatalf("RunHelper took %v after cancel", elapsed) + } +} + +func TestRunHelperDoesNotStartWhenAlreadyCancelled(t *testing.T) { + dir := t.TempDir() + f, err := PrepareHelperFiles(dir) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f.Cancel, nil, 0o600); err != nil { + t.Fatal(err) + } + marker := filepath.Join(dir, "started") + script := writeImagerScript(t, dir, "touch "+marker) + + code := RunHelper(context.Background(), f, script, nil) + if code == 0 { + t.Fatal("cancelled run must not return 0") + } + if _, err := os.Stat(marker); !os.IsNotExist(err) { + t.Fatalf("imager must not start, stat err = %v", err) + } + log, _ := os.ReadFile(f.Log) + if !strings.Contains(string(log), "Error: cancelled before start") { + t.Fatalf("log = %q", log) + } +} + +func TestRunHelperRefusesOtherPrograms(t *testing.T) { + dir := t.TempDir() + f, err := PrepareHelperFiles(dir) + if err != nil { + t.Fatal(err) + } + + code := RunHelper(context.Background(), f, "/bin/sh", nil) + if code != 125 { + t.Fatalf("exit code = %d, want 125", code) + } + log, _ := os.ReadFile(f.Log) + if !strings.HasPrefix(string(log), "Error: refusing to run sh") { + t.Fatalf("log = %q", log) + } +} + +func TestTailLogFollowsUntilDone(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "imager.log") + done := make(chan struct{}) + + go func() { + time.Sleep(150 * time.Millisecond) + _ = os.WriteFile(path, []byte("first\n"), 0o600) + time.Sleep(150 * time.Millisecond) + f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0) + if err == nil { + _, _ = f.WriteString("second\n") + _ = f.Close() + } + close(done) + }() + + rc := TailLog(path, done) + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatal(err) + } + if string(data) != "first\nsecond\n" { + t.Fatalf("tail = %q", data) + } +} + +func TestRunShimRefusesOtherPrograms(t *testing.T) { + if code := RunShim("/bin/sh", nil); code != 125 { + t.Fatalf("exit code = %d, want 125", code) + } +} diff --git a/installer/internal/media/helper_windows.go b/installer/internal/media/helper_windows.go new file mode 100644 index 000000000..93bcc3c4d --- /dev/null +++ b/installer/internal/media/helper_windows.go @@ -0,0 +1,121 @@ +package media + +import ( + "fmt" + "io" + "os" + "os/exec" + "syscall" + "unsafe" + + "golang.org/x/sys/windows" +) + +// createNoWindow ist CREATE_NO_WINDOW: Kindprozesse bekommen kein sichtbares Konsolenfenster. +const createNoWindow = 0x08000000 + +func hideWindow(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: createNoWindow} +} + +// utf8CodePage ist CP_UTF8. +const utf8CodePage = 65001 + +// prepareShimConsole stellt die Pseudokonsole auf UTF-8. Der Imager schreibt UTF-8, +// sonst liest die Konsole die Bytes in der OEM-Codepage. +func prepareShimConsole() { + _ = windows.SetConsoleCP(utf8CodePage) + _ = windows.SetConsoleOutputCP(utf8CodePage) +} + +// shimExe liefert den Pfad des eigenen Programms, das den Zwischenprozess startet. +var shimExe = os.Executable + +// startImager startet den Imager ueber den Shim in einer Pseudokonsole, siehe conpty_windows.go. +// Der Imager haengt sich an die Konsole seines Elternprozesses, deshalb ist die Pipe allein zu wenig. +func startImager(log *os.File, name string, args []string) (imagerProcess, error) { + exe, err := shimExe() + if err != nil { + return nil, fmt.Errorf("own executable: %w", err) + } + cmdLine, err := windows.UTF16PtrFromString(windows.ComposeCommandLine(append([]string{exe, ShimName, "--", name}, args...))) + if err != nil { + return nil, err + } + + w := &conptyImager{log: log} + ok := false + defer func() { + if !ok { + if w.proc != 0 { + // Gestartet, aber nicht zugeordnet oder nicht fortgesetzt: sofort beenden. + _ = windows.TerminateProcess(w.proc, 1) + } + w.closeAll() + } + }() + + // Pipes: der Installer schreibt nach inW, die Konsole liest inR; die Konsole schreibt nach outW, wir lesen outR. + if err := windows.CreatePipe(&w.inR, &w.inW, nil, 0); err != nil { + return nil, fmt.Errorf("CreatePipe in: %w", err) + } + if err := windows.CreatePipe(&w.outR, &w.outW, nil, 0); err != nil { + return nil, fmt.Errorf("CreatePipe out: %w", err) + } + if err := windows.CreatePseudoConsole(windows.Coord{X: 1000, Y: 30}, w.inR, w.outW, 0, &w.hpc); err != nil { + return nil, fmt.Errorf("CreatePseudoConsole: %w", err) + } + // Die Konsole besitzt diese Enden jetzt. + _ = windows.CloseHandle(w.inR) + _ = windows.CloseHandle(w.outW) + w.inR, w.outW = 0, 0 + + attrs, err := windows.NewProcThreadAttributeList(1) + if err != nil { + return nil, fmt.Errorf("NewProcThreadAttributeList: %w", err) + } + defer attrs.Delete() + + // Der PSEUDOCONSOLE-Attributwert ist der HPCON-Wert selbst, nicht ein Zeiger darauf. + hpcValue := *(*unsafe.Pointer)(unsafe.Pointer(&w.hpc)) + if err := attrs.Update(windows.PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, hpcValue, unsafe.Sizeof(w.hpc)); err != nil { + return nil, fmt.Errorf("UpdateProcThreadAttribute: %w", err) + } + + si := new(windows.StartupInfoEx) + si.Cb = uint32(unsafe.Sizeof(*si)) + si.ProcThreadAttributeList = attrs.List() + + w.job, err = newKillOnCloseJob() + if err != nil { + return nil, err + } + + // Gestartet wird angehalten: kein Kindprozess entsteht, bevor der Prozess im Job liegt. + var pi windows.ProcessInformation + flags := uint32(windows.EXTENDED_STARTUPINFO_PRESENT | windows.CREATE_SUSPENDED) + if err := windows.CreateProcess(nil, cmdLine, nil, nil, false, flags, nil, nil, &si.StartupInfo, &pi); err != nil { + return nil, fmt.Errorf("CreateProcess: %w", err) + } + w.proc, w.thread = pi.Process, pi.Thread + if err := windows.AssignProcessToJobObject(w.job, w.proc); err != nil { + return nil, fmt.Errorf("AssignProcessToJobObject: %w", err) + } + if _, err := windows.ResumeThread(w.thread); err != nil { + return nil, fmt.Errorf("ResumeThread: %w", err) + } + + // Die Konsolenausgabe laeuft ins Log, bis die Konsole geschlossen wird. + out := os.NewFile(uintptr(w.outR), "conpty-out") + w.out = out + w.outR = 0 + done := make(chan struct{}) + w.copyDone = done + go func() { + defer close(done) + _, _ = io.Copy(log, out) + }() + + ok = true + return w, nil +} diff --git a/installer/internal/media/imager.go b/installer/internal/media/imager.go index 053d9538c..fd7e751fc 100644 --- a/installer/internal/media/imager.go +++ b/installer/internal/media/imager.go @@ -13,6 +13,7 @@ type ImagerKind string const ( ImagerNative ImagerKind = "native" ImagerFlatpak ImagerKind = "flatpak" + ImagerWindows ImagerKind = "windows" ) // FlatpakID is the Flatpak application ID of the Raspberry Pi Imager. @@ -108,8 +109,59 @@ func (im Imager) Command(a WriteArgs) (name string, args []string) { return "flatpak", args } + if im.Kind == ImagerWindows { + args = []string{"--cli"} + args = append(args, flags...) + args = append(args, a.Image, a.Drive) + return im.Path, args + } + args = []string{im.Path, "--cli"} args = append(args, flags...) args = append(args, a.Image, a.Drive) return "pkexec", args } + +// WinEnv wraps the Windows system calls so tests can replace them. +type WinEnv struct { + Getenv func(string) string + Exists func(string) bool + FileVersion func(string) (string, error) +} + +// FindWindowsImager returns the first installed rpi-imager.exe from the known install +// locations. A location whose environment variable is empty is skipped. Its version comes +// from the file's version resource, trimmed to three parts. ok is false if none exists. +func FindWindowsImager(env WinEnv) (im Imager, ok bool) { + candidates := []struct{ variable, sub string }{ + {"ProgramFiles", `\Raspberry Pi Ltd\Imager\rpi-imager.exe`}, + {"ProgramFiles", `\Raspberry Pi Imager\rpi-imager.exe`}, + {"ProgramFiles(x86)", `\Raspberry Pi Imager\rpi-imager.exe`}, + {"LOCALAPPDATA", `\Programs\Raspberry Pi Imager\rpi-imager.exe`}, + } + for _, c := range candidates { + base := env.Getenv(c.variable) + if base == "" { + continue + } + path := base + c.sub + if !env.Exists(path) { + continue + } + version, err := env.FileVersion(path) + if err != nil { + version = "" + } + return Imager{Kind: ImagerWindows, Path: path, Version: trimVersion(version)}, true + } + return Imager{}, false +} + +// trimVersion cuts a four part file version such as "2.0.12.0" to "2.0.12". +func trimVersion(version string) string { + parts := strings.Split(version, ".") + if len(parts) > 3 { + parts = parts[:3] + } + return strings.Join(parts, ".") +} diff --git a/installer/internal/media/imager_otherwin.go b/installer/internal/media/imager_otherwin.go new file mode 100644 index 000000000..6ed274fb0 --- /dev/null +++ b/installer/internal/media/imager_otherwin.go @@ -0,0 +1,8 @@ +//go:build !windows + +package media + +// LocateWindowsImager reports no imager outside Windows. +func LocateWindowsImager() (Imager, bool) { + return Imager{}, false +} diff --git a/installer/internal/media/imager_test.go b/installer/internal/media/imager_test.go index eb27d3ccf..43969acb7 100644 --- a/installer/internal/media/imager_test.go +++ b/installer/internal/media/imager_test.go @@ -139,3 +139,102 @@ func indexOf(list []string, s string) int { } return -1 } + +func TestWindowsImagerCommandRunsTheExeDirectly(t *testing.T) { + im := Imager{Kind: ImagerWindows, Path: `C:\P\rpi-imager.exe`} + name, args := im.Command(WriteArgs{ + Image: `C:\c\img\os.img.xz`, + Drive: `\\.\PhysicalDrive1`, + UserData: `C:\c\job\user-data`, + SystemDrive: true, + }) + want := []string{"--cli", "--enable-writing-system-drives", "--cloudinit-userdata", `C:\c\job\user-data`, `C:\c\img\os.img.xz`, `\\.\PhysicalDrive1`} + if name != `C:\P\rpi-imager.exe` { + t.Errorf("name = %q, want the exe path", name) + } + if !reflect.DeepEqual(args, want) { + t.Errorf("args = %v\nwant %v", args, want) + } +} + +// fakeWinEnv answers the Windows lookups from fixed tables. +func fakeWinEnv(vars map[string]string, existing []string, version string, versionErr error) WinEnv { + exists := map[string]bool{} + for _, p := range existing { + exists[p] = true + } + return WinEnv{ + Getenv: func(name string) string { return vars[name] }, + Exists: func(path string) bool { return exists[path] }, + FileVersion: func(string) (string, error) { + return version, versionErr + }, + } +} + +var winVars = map[string]string{ + "ProgramFiles": `C:\Program Files`, + "ProgramFiles(x86)": `C:\Program Files (x86)`, + "LOCALAPPDATA": `C:\Users\simon\AppData\Local`, +} + +func TestFindWindowsImagerPrefersProgramFiles(t *testing.T) { + env := fakeWinEnv(winVars, []string{ + `C:\Program Files\Raspberry Pi Ltd\Imager\rpi-imager.exe`, + `C:\Program Files\Raspberry Pi Imager\rpi-imager.exe`, + `C:\Users\simon\AppData\Local\Programs\Raspberry Pi Imager\rpi-imager.exe`, + }, "2.0.12.0", nil) + im, ok := FindWindowsImager(env) + if !ok { + t.Fatal("imager not found") + } + want := Imager{Kind: ImagerWindows, Path: `C:\Program Files\Raspberry Pi Ltd\Imager\rpi-imager.exe`, Version: "2.0.12"} + if im != want { + t.Fatalf("got %+v, want %+v", im, want) + } +} + +func TestFindWindowsImagerFallsBackToLocalAppData(t *testing.T) { + env := fakeWinEnv(winVars, []string{ + `C:\Users\simon\AppData\Local\Programs\Raspberry Pi Imager\rpi-imager.exe`, + }, "2.0.12.0", nil) + im, ok := FindWindowsImager(env) + if !ok { + t.Fatal("imager not found") + } + if im.Path != `C:\Users\simon\AppData\Local\Programs\Raspberry Pi Imager\rpi-imager.exe` || im.Version != "2.0.12" { + t.Fatalf("got %+v", im) + } +} + +func TestFindWindowsImagerTrimsTheFourthVersionPart(t *testing.T) { + env := fakeWinEnv(winVars, []string{ + `C:\Program Files\Raspberry Pi Imager\rpi-imager.exe`, + }, "2.0.8.0", nil) + im, ok := FindWindowsImager(env) + if !ok { + t.Fatal("imager not found") + } + if im.Version != "2.0.8" { + t.Fatalf("Version = %q, want 2.0.8", im.Version) + } +} + +func TestFindWindowsImagerWithoutVersionIsTooOld(t *testing.T) { + env := fakeWinEnv(winVars, []string{ + `C:\Program Files\Raspberry Pi Imager\rpi-imager.exe`, + }, "", errors.New("no version info")) + im, ok := FindWindowsImager(env) + if !ok { + t.Fatal("imager not found") + } + if im.Version != "" || !im.TooOld() { + t.Fatalf("got %+v, want empty version that is too old", im) + } +} + +func TestFindWindowsImagerNotInstalled(t *testing.T) { + if _, ok := FindWindowsImager(fakeWinEnv(winVars, nil, "", nil)); ok { + t.Fatal("expected ok == false") + } +} diff --git a/installer/internal/media/imager_windows.go b/installer/internal/media/imager_windows.go new file mode 100644 index 000000000..eebcba602 --- /dev/null +++ b/installer/internal/media/imager_windows.go @@ -0,0 +1,41 @@ +//go:build windows + +package media + +import ( + "fmt" + "os" + "unsafe" + + "golang.org/x/sys/windows" +) + +// LocateWindowsImager finds the installed Raspberry Pi Imager. It reads the version from the +// file's version resource and never starts the imager, since that could trigger UAC. +func LocateWindowsImager() (Imager, bool) { + return FindWindowsImager(WinEnv{ + Getenv: os.Getenv, + Exists: fileExists, + FileVersion: fileVersion, + }) +} + +// fileVersion returns the four part file version of path, such as "2.0.12.0". +func fileVersion(path string) (string, error) { + size, err := windows.GetFileVersionInfoSize(path, nil) + if err != nil { + return "", err + } + buf := make([]byte, size) + if err := windows.GetFileVersionInfo(path, 0, size, unsafe.Pointer(&buf[0])); err != nil { + return "", err + } + var block unsafe.Pointer + var n uint32 + if err := windows.VerQueryValue(unsafe.Pointer(&buf[0]), `\`, unsafe.Pointer(&block), &n); err != nil { + return "", err + } + info := (*windows.VS_FIXEDFILEINFO)(block) + ms, ls := info.FileVersionMS, info.FileVersionLS + return fmt.Sprintf("%d.%d.%d.%d", ms>>16, ms&0xffff, ls>>16, ls&0xffff), nil +} diff --git a/installer/internal/media/job.go b/installer/internal/media/job.go index db39df9ac..946ea04da 100644 --- a/installer/internal/media/job.go +++ b/installer/internal/media/job.go @@ -70,7 +70,8 @@ type JobView struct { Percent int `json:"percent"` // des aktiven Schritts BytesDone int64 `json:"bytes_done"` BytesTotal int64 `json:"bytes_total"` - Rate int64 `json:"rate"` // Byte/s, gleitend ueber 3 s + Rate int64 `json:"rate"` // Byte/s, gleitend ueber 3 s + Cancelling bool `json:"cancelling"` // Abbruch verlangt, der Imager laeuft noch Error *JobError `json:"error"` Log []string `json:"log"` // letzte 200 Zeilen Target *Target `json:"target"` // erst bei done @@ -127,6 +128,7 @@ type Writer struct { WorkDir string // /jobs Debian func(ctx context.Context, arch string) (DebianRelease, error) // signierte Debian-Release-Suche PatchISO func(in, out string, o isopatch.Options) error // nil = isopatch.Patch + Eject func(ctx context.Context, d Drive) error // nil = der Imager wirft selbst aus mu sync.Mutex busy bool @@ -135,9 +137,11 @@ type Writer struct { } var ( - ErrBusy = errors.New("media: a write is already running") - ErrDriveGone = errors.New("media: drive is no longer listed") - ErrConfirm = errors.New("media: confirmation does not match the drive") + ErrBusy = errors.New("media: a write is already running") + ErrDriveGone = errors.New("media: drive is no longer listed") + ErrConfirm = errors.New("media: confirmation does not match the drive") + // ErrRightsDenied reports that the administrator prompt was refused or dismissed. + ErrRightsDenied = errors.New("media: administrator rights were refused") ErrSettings = errors.New("media: settings are invalid") ErrImagerMissing = errors.New("media: raspberry pi imager is missing or too old") ErrTooSmall = errors.New("media: drive is smaller than the image") @@ -151,14 +155,16 @@ const ( codeWriteFailed = "MEDIA_WRITE_FAILED" codeVerifyFailed = "MEDIA_VERIFY_FAILED" codeRightsDenied = "MEDIA_RIGHTS_DENIED" + codeDriveGone = "MEDIA_DRIVE_GONE" codeCancelled = "MEDIA_CANCELLED" codePatchFailed = "MEDIA_PATCH_FAILED" debianLabel = "ENERGY-NODE-LOESCHT" debianJolietName = "LÖSCHT PLATTE" - logLimit = 200 - rateWindow = 3 * time.Second + logLimit = 200 + rateWindow = 3 * time.Second + ejectTimeout = 30 * time.Second ) var wifiCountryPattern = regexp.MustCompile(`^[A-Z]{2}$`) @@ -347,6 +353,7 @@ func (w *Writer) execute(ctx context.Context, p *plan) (JobState, *JobError) { if err := os.MkdirAll(w.WorkDir, 0o700); err != nil { return r.fail(codeWriteFailed, err.Error()) } + removeStaleJobs(w.WorkDir, time.Now()) tmp, err := os.MkdirTemp(w.WorkDir, "job-") if err != nil { return r.fail(codeWriteFailed, err.Error()) @@ -364,6 +371,29 @@ func (w *Writer) execute(ctx context.Context, p *plan) (JobState, *JobError) { return r.runImager(r.withDrive(args, tmp, imgPath)) } +// staleJobAge is the age after which a left over job folder is removed. A +// second installer may be writing right now, so younger folders stay. +const staleJobAge = 24 * time.Hour + +// removeStaleJobs removes job folders that an earlier run could not delete, for +// example because the imager still held the stick image open. Errors are ignored. +func removeStaleJobs(dir string, now time.Time) { + entries, err := os.ReadDir(dir) + if err != nil { + return + } + for _, e := range entries { + if !e.IsDir() || !strings.HasPrefix(e.Name(), "job-") { + continue + } + info, err := e.Info() + if err != nil || now.Sub(info.ModTime()) < staleJobAge { + continue + } + _ = os.RemoveAll(filepath.Join(dir, e.Name())) + } +} + // withDrive adds the target drive and the read access of the imager to a. func (r *jobRun) withDrive(a WriteArgs, tmp, iso string) WriteArgs { a.Drive = r.p.drive.Path @@ -447,13 +477,23 @@ func (w *Writer) setStep(id StepID, state StepState) { }) } +// listedAs reports whether drives contain a drive with the path, model and size of d. +func listedAs(drives []Drive, d Drive) bool { + for _, x := range drives { + if x.Path == d.Path && x.Model == d.Model && x.Size == d.Size { + return true + } + } + return false +} + // fail marks the active step as failed. A cancelled context wins over the code. func (r *jobRun) fail(code, detail string) (JobState, *JobError) { if r.active != "" { r.w.setStep(r.active, StepFailed) } if r.ctx.Err() != nil { - return JobCancelled, &JobError{Code: codeCancelled, Detail: "cancelled by user"} + return JobCancelled, &JobError{Code: codeCancelled} } return JobFailed, &JobError{Code: code, Detail: detail} } @@ -604,8 +644,19 @@ func (r *jobRun) runImager(a WriteArgs) (JobState, *JobError) { name, args := r.p.imager.Command(a) r.move(StepRights) + drives, err := r.w.Drives(r.ctx) + if err != nil { + return r.fail(codeWriteFailed, err.Error()) + } + if !listedAs(drives, r.p.drive) { + return r.fail(codeDriveGone, "the drive changed after the start") + } + out, wait, err := r.w.Run(r.ctx, name, args...) if err != nil { + if errors.Is(err, ErrRightsDenied) { + return r.fail(codeRightsDenied, "") + } return r.fail(codeWriteFailed, err.Error()) } defer out.Close() @@ -617,7 +668,7 @@ func (r *jobRun) runImager(a WriteArgs) (JobState, *JobError) { code, werr := wait() if r.ctx.Err() != nil { - return r.fail(codeCancelled, "cancelled by user") + return r.fail(codeCancelled, "") } if perr != nil { return r.fail(codeWriteFailed, perr.Error()) @@ -630,7 +681,7 @@ func (r *jobRun) runImager(a WriteArgs) (JobState, *JobError) { return r.fail(code, r.errMsg) } if (code == 126 || code == 127) && name == "pkexec" && cr.n == 0 { - return r.fail(codeRightsDenied, "pkexec was dismissed or refused") + return r.fail(codeRightsDenied, "") } if werr != nil { return r.fail(codeWriteFailed, werr.Error()) @@ -646,6 +697,7 @@ func (r *jobRun) runImager(a WriteArgs) (JobState, *JobError) { if err := transport.PinHostKey(r.w.KnownHosts, host, r.hk.Public); err != nil { return r.fail(codeWriteFailed, "pin host key: "+err.Error()) } + r.eject() r.done(StepEject) r.w.update(func(v *JobView) { v.Target = &Target{Host: host, User: r.p.req.Settings.User, KeyPath: r.w.KeyPath} @@ -653,6 +705,21 @@ func (r *jobRun) runImager(a WriteArgs) (JobState, *JobError) { return JobDone, nil } +// eject removes a removable medium from the system. The medium is complete at +// this point, so a failure only goes into the log. +func (r *jobRun) eject() { + if r.w.Eject == nil || !r.p.drive.Removable { + return + } + ctx, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), ejectTimeout) + defer cancel() + if err := r.w.Eject(ctx, r.p.drive); err != nil { + logs := &logSink{w: r.w} + _, _ = logs.Write([]byte("eject: " + err.Error())) + logs.flush() + } +} + // onProgress maps one imager event to steps and percent. func (r *jobRun) onProgress(p Progress) { switch p.Phase { @@ -721,6 +788,7 @@ func (w *Writer) finish(state JobState, jobErr *JobError) { w.view.State = state w.view.Error = jobErr w.view.Rate = 0 + w.view.Cancelling = false if state != JobDone { w.view.Target = nil } @@ -757,9 +825,9 @@ func (s *logSink) Write(p []byte) (int, error) { return len(p), nil } -// flush appends the partial line to the view and clears the ESC[0K codes. +// flush appends the partial line to the view without terminal control sequences. func (s *logSink) flush() { - line := strings.ReplaceAll(string(s.partial), "\x1b[0K", "") + line := stripVT(string(s.partial)) s.partial = s.partial[:0] if strings.TrimSpace(line) == "" { return @@ -789,10 +857,14 @@ func (w *Writer) View() JobView { return v } -// Cancel stops the running job. It does nothing when no job runs. +// Cancel stops the running job. It does nothing when no job runs. The job stays +// running, marked as cancelling, until the imager has ended. func (w *Writer) Cancel() { w.mu.Lock() cancel := w.cancel + if cancel != nil { + w.view.Cancelling = true + } w.mu.Unlock() if cancel != nil { cancel() diff --git a/installer/internal/media/job_test.go b/installer/internal/media/job_test.go index 2ee2b57dc..dc14df96e 100644 --- a/installer/internal/media/job_test.go +++ b/installer/internal/media/job_test.go @@ -313,6 +313,9 @@ func TestPkexecDismissedMeansRightsDenied(t *testing.T) { if name, _ := fr.got(); name != "pkexec" { t.Fatalf("runner name = %q, want pkexec", name) } + if v.Error.Detail != "" { + t.Fatalf("detail = %q, want none", v.Error.Detail) + } } func TestTheEmergencyPasswordIsNeverInTheView(t *testing.T) { @@ -646,3 +649,161 @@ func TestDebianTooSmallDrive(t *testing.T) { t.Fatalf("Start error = %v, want ErrTooSmall", err) } } + +func TestRunImagerMapsErrRightsDeniedToRightsDenied(t *testing.T) { + w := newTestWriter(t, []Drive{sdb}, &fakeRun{}) + w.Run = func(context.Context, string, ...string) (io.ReadCloser, func() (int, error), error) { + return nil, nil, fmt.Errorf("x: %w", ErrRightsDenied) + } + if err := w.Start(context.Background(), okWrite); err != nil { + t.Fatal(err) + } + v := waitJob(t, w) + if v.State != JobFailed || v.Error == nil || v.Error.Code != codeRightsDenied { + t.Fatalf("state = %s, error = %+v, want %s", v.State, v.Error, codeRightsDenied) + } + if v.Error.Detail != "" { + t.Fatalf("detail = %q, want none", v.Error.Detail) + } +} + +func TestRunImagerRefusesADriveThatChangedSinceStart(t *testing.T) { + changed := Drive{Path: "/dev/sdb", Model: "Stick", Size: 16e9, Removable: true} + fr := &fakeRun{out: loadFixture(t, "imager-ok.txt")} + w := newTestWriter(t, []Drive{sdb}, fr) + calls := 0 + w.Drives = func(context.Context) ([]Drive, error) { + calls++ + if calls == 1 { + return []Drive{sdb}, nil + } + return []Drive{changed}, nil + } + if err := w.Start(context.Background(), okWrite); err != nil { + t.Fatal(err) + } + v := waitJob(t, w) + if v.State != JobFailed || v.Error == nil || v.Error.Code != codeDriveGone { + t.Fatalf("state = %s, error = %+v, want %s", v.State, v.Error, codeDriveGone) + } + if name, _ := fr.got(); name != "" { + t.Fatalf("imager was started with %q although the drive changed", name) + } +} + +func TestRunImagerRefusesWhenTheDriveIsGone(t *testing.T) { + fr := &fakeRun{out: loadFixture(t, "imager-ok.txt")} + w := newTestWriter(t, []Drive{sdb}, fr) + calls := 0 + w.Drives = func(context.Context) ([]Drive, error) { + calls++ + if calls == 1 { + return []Drive{sdb}, nil + } + return nil, nil + } + if err := w.Start(context.Background(), okWrite); err != nil { + t.Fatal(err) + } + v := waitJob(t, w) + if v.State != JobFailed || v.Error == nil || v.Error.Code != codeDriveGone { + t.Fatalf("state = %s, error = %+v, want %s", v.State, v.Error, codeDriveGone) + } +} + +func TestCancelShowsCancellingUntilTheImagerEnds(t *testing.T) { + w := newTestWriter(t, []Drive{sdb}, &fakeRun{}) + started := make(chan struct{}) + release := make(chan struct{}) + w.Run = func(context.Context, string, ...string) (io.ReadCloser, func() (int, error), error) { + close(started) + return io.NopCloser(strings.NewReader("")), func() (int, error) { <-release; return 1, nil }, nil + } + if err := w.Start(context.Background(), okWrite); err != nil { + t.Fatal(err) + } + <-started + if w.View().Cancelling { + t.Fatal("cancelling before Cancel") + } + w.Cancel() + if v := w.View(); v.State != JobRunning || !v.Cancelling { + t.Fatalf("state = %s, cancelling = %v, want running and cancelling", v.State, v.Cancelling) + } + close(release) + v := waitJob(t, w) + if v.State != JobCancelled || v.Cancelling { + t.Fatalf("state = %s, cancelling = %v, want cancelled", v.State, v.Cancelling) + } + if v.Error == nil || v.Error.Detail != "" { + t.Fatalf("error = %+v, want no detail", v.Error) + } +} + +func TestAJobRemovesOnlyOldJobFolders(t *testing.T) { + w := newTestWriter(t, []Drive{sdb}, &fakeRun{out: loadFixture(t, "imager-ok.txt")}) + old := filepath.Join(w.WorkDir, "job-old") + fresh := filepath.Join(w.WorkDir, "job-fresh") + other := filepath.Join(w.WorkDir, "keep") + for _, dir := range []string{old, fresh, other} { + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "stick.iso"), []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + } + past := time.Now().Add(-48 * time.Hour) + for _, dir := range []string{old, other} { + if err := os.Chtimes(dir, past, past); err != nil { + t.Fatal(err) + } + } + if err := w.Start(context.Background(), okWrite); err != nil { + t.Fatal(err) + } + waitJob(t, w) + if _, err := os.Stat(old); !os.IsNotExist(err) { + t.Errorf("old job folder still there: %v", err) + } + for _, dir := range []string{fresh, other} { + if _, err := os.Stat(dir); err != nil { + t.Errorf("%s was removed: %v", dir, err) + } + } +} + +func TestADoneJobEjectsARemovableDriveAndIgnoresTheError(t *testing.T) { + w := newTestWriter(t, []Drive{sdb}, &fakeRun{out: loadFixture(t, "imager-ok.txt")}) + var ejected []string + w.Eject = func(_ context.Context, d Drive) error { + ejected = append(ejected, d.Path) + return errors.New("still mounted") + } + if err := w.Start(context.Background(), okWrite); err != nil { + t.Fatal(err) + } + v := waitJob(t, w) + if v.State != JobDone { + t.Fatalf("state = %s, error = %+v", v.State, v.Error) + } + if len(ejected) != 1 || ejected[0] != "/dev/sdb" { + t.Fatalf("ejected = %v", ejected) + } + if len(v.Log) == 0 || v.Log[len(v.Log)-1] != "eject: still mounted" { + t.Fatalf("log = %v", v.Log) + } +} + +func TestAFailedJobEjectsNothing(t *testing.T) { + w := newTestWriter(t, []Drive{sdb}, &fakeRun{out: loadFixture(t, "imager-error.txt"), code: 1}) + ran := false + w.Eject = func(context.Context, Drive) error { ran = true; return nil } + if err := w.Start(context.Background(), okWrite); err != nil { + t.Fatal(err) + } + waitJob(t, w) + if ran { + t.Fatal("ejected after a failed write") + } +} diff --git a/installer/internal/media/progress.go b/installer/internal/media/progress.go index 35fa39199..8f79745f1 100644 --- a/installer/internal/media/progress.go +++ b/installer/internal/media/progress.go @@ -30,8 +30,21 @@ type Progress struct { var ( imagerProgressRe = regexp.MustCompile(`^(Writing|Verifying): \[[^\]]*\]\s+(\d+)\s*%`) imagerIgnored = []string{"Platform:", "Starting background", "CacheManager", "Optimal async", "FileOperations", "WARNING:"} + vtCSIRe = regexp.MustCompile(`\x1b\[[0-9;?]*[A-Za-z]`) + vtOSCRe = regexp.MustCompile(`\x1b\][^\x07]*\x07`) + gluedSentenceRe = regexp.MustCompile(`([.:!?])(\p{Lu}\p{Ll})`) + gluedPleaseRe = regexp.MustCompile(`(\p{Ll})(Please )`) ) +// maxErrorMessage begrenzt die Fehlermeldung in Zeichen. +const maxErrorMessage = 600 + +// stripVT removes the terminal control sequences (CSI and OSC) that the Windows +// console writes into the imager output. +func stripVT(s string) string { + return vtOSCRe.ReplaceAllString(vtCSIRe.ReplaceAllString(s, ""), "") +} + // splitLines splits on both \r and \n, so progress updates that overwrite a line count as lines. func splitLines(data []byte, atEOF bool) (advance int, token []byte, err error) { if i := bytes.IndexAny(data, "\r\n"); i >= 0 { @@ -44,22 +57,59 @@ func splitLines(data []byte, atEOF bool) (advance int, token []byte, err error) } // ParseImagerOutput reads the imager output line by line (\r and \n both separate lines, -// ESC[0K is removed) and calls emit for every recognized line. +// control sequences are removed) and calls emit for every recognized line. The lines +// after an error belong to its message: each of them emits the longer error again. func ParseImagerOutput(r io.Reader, emit func(Progress)) error { sc := bufio.NewScanner(r) sc.Split(splitLines) + message := "" for sc.Scan() { - raw := strings.ReplaceAll(sc.Text(), "\x1b[0K", "") + raw := stripVT(sc.Text()) if strings.TrimSpace(raw) == "" { continue } - if p, ok := parseImagerLine(raw); ok { + p, ok := parseImagerLine(raw) + if ok && (message == "" || p.Phase != PhasePrepare) { + if p.Phase == PhaseError { + message = tidyMessage(p.Message) + p.Message = message + } emit(p) + continue + } + if message != "" && continuesError(raw) { + message = tidyMessage(message + " " + strings.TrimSpace(raw)) + emit(Progress{Phase: PhaseError, Message: message}) } } return sc.Err() } +// continuesError reports whether a line after an error is part of its message. +func continuesError(raw string) bool { + line := strings.TrimSpace(raw) + if strings.HasPrefix(line, "job process") { + return false + } + for _, prefix := range imagerIgnored { + if strings.HasPrefix(line, prefix) { + return false + } + } + return true +} + +// tidyMessage puts back the spaces the imager drops between sentences and cuts +// the message to maxErrorMessage characters. +func tidyMessage(s string) string { + s = gluedSentenceRe.ReplaceAllString(s, "$1 $2") + s = gluedPleaseRe.ReplaceAllString(s, "$1 $2") + if r := []rune(s); len(r) > maxErrorMessage { + s = string(r[:maxErrorMessage]) + } + return s +} + // parseImagerLine classifies one output line. raw keeps its indentation, because // indented lines are the preparation steps. func parseImagerLine(raw string) (Progress, bool) { diff --git a/installer/internal/media/progress_test.go b/installer/internal/media/progress_test.go index e31687766..b6a92436a 100644 --- a/installer/internal/media/progress_test.go +++ b/installer/internal/media/progress_test.go @@ -3,6 +3,7 @@ package media import ( "os" "reflect" + "strings" "testing" ) @@ -50,3 +51,47 @@ func TestParseImagerOutputError(t *testing.T) { t.Errorf("first = %+v, want write 45", got[0]) } } + +func TestParseImagerOutputWindowsRecording(t *testing.T) { + counts := map[Phase]int{} + for _, p := range parseFile(t, "testdata/imager-win-ok.txt") { + counts[p.Phase]++ + } + if counts[PhaseWrite] == 0 || counts[PhaseVerify] == 0 || counts[PhaseDone] != 1 || counts[PhaseError] != 0 { + t.Fatalf("phase counts = %v, want write, verify, exactly one done and no error", counts) + } +} + +func TestParseImagerOutputCollectsAMultiLineError(t *testing.T) { + out := " Writing: [---> ] 45 %\r\n" + + "Error: Error writing to storage device.Some writes failed to complete. This could be caused by:\r\n" + + " • Bad sectors\r\n" + + "\r\n" + + "• A hardware failurePlease try again.\r\n" + + "job process pid=1 C:\\x.exe\r\n" + var got []Progress + if err := ParseImagerOutput(strings.NewReader(out), func(p Progress) { got = append(got, p) }); err != nil { + t.Fatal(err) + } + last := got[len(got)-1] + want := "Error writing to storage device. Some writes failed to complete. This could be caused by: • Bad sectors • A hardware failure Please try again." + if last.Phase != PhaseError || last.Message != want { + t.Errorf("last = %+v\nwant message %q", last, want) + } + for _, p := range got[1:] { + if p.Phase != PhaseError { + t.Errorf("unexpected phase after the error: %+v", p) + } + } +} + +func TestParseImagerOutputCutsALongError(t *testing.T) { + out := "Error: x\n" + strings.Repeat("more text\n", 200) + var last Progress + if err := ParseImagerOutput(strings.NewReader(out), func(p Progress) { last = p }); err != nil { + t.Fatal(err) + } + if n := len([]rune(last.Message)); n != maxErrorMessage { + t.Errorf("length = %d, want %d", n, maxErrorMessage) + } +} diff --git a/installer/internal/media/testdata/imager-win-ok.txt b/installer/internal/media/testdata/imager-win-ok.txt new file mode 100644 index 000000000..7a5a1c00b --- /dev/null +++ b/installer/internal/media/testdata/imager-win-ok.txt @@ -0,0 +1,13 @@ +helper-conpty started elevated=true pid=10380 +pipes created +pseudo console created hpc=0x205c35323f0 +imager pid=24152 +[?9001h[?1004h[?25lshim started, starting imager +]0;C:\spike-winmac\spikewin\spikewin-fix.exe[?25hCacheManager initialized with background thread +Optimal async queue depth: 256 (available: 16105 MB, budget: 2415 MB, block size: 1024 KB, baseline: 256 ) +FileOperations log callback installed +Starting background cache operations +Starting background drive list polling + Unmounting volumes...  Cleaning disk...  Zero'ing out first and last MB of drive...  Zero'ing out end of drive...  Starting download... Writing: [> ] 0 % Writing: [> ] 1 % Writing: [> ] 2 % Writing: [> ] 3 % Writing: [> ] 4 % Writing: [-> ] 5 % Writing: [-> ] 6 % Writing: [-> ] 7 % Writing: [-> ] 8 % Writing: [-> ] 9 % Writing: [--> ] 10 % Writing: [--> ] 11 % Writing: [--> ] 12 % Writing: [--> ] 13 % Writing: [--> ] 14 % Writing: [---> ] 15 % Writing: [---> ] 16 % Writing: [---> ] 17 % Writing: [---> ] 18 % Writing: [---> ] 19 % Writing: [----> ] 20 % Writing: [----> ] 21 % Writing: [----> ] 22 % Writing: [----> ] 23 % Writing: [----> ] 24 % Writing: [-----> ] 25 % Writing: [-----> ] 26 % Writing: [-----> ] 27 % Writing: [-----> ] 28 % Writing: [-----> ] 29 % Writing: [------> ] 30 % Writing: [------> ] 31 % Writing: [------> ] 32 % Writing: [------> ] 33 % Writing: [------> ] 34 % Writing: [-------> ] 35 % Writing: [-------> ] 36 % Writing: [-------> ] 37 % Writing: [-------> ] 38 % Writing: [-------> ] 39 % Writing: [--------> ] 40 % Writing: [--------> ] 41 % Writing: [--------> ] 42 % Writing: [--------> ] 43 % Writing: [--------> ] 44 % Writing: [---------> ] 45 % Writing: [---------> ] 46 % Writing: [---------> ] 47 % Writing: [---------> ] 48 % Writing: [---------> ] 49 % Writing: [----------> ] 50 % Writing: [----------> ] 51 % Writing: [----------> ] 52 % Writing: [----------> ] 53 % Writing: [----------> ] 54 % Writing: [-----------> ] 55 % Writing: [-----------> ] 56 % Writing: [-----------> ] 57 % Writing: [-----------> ] 58 % Writing: [-----------> ] 59 % Writing: [------------> ] 60 % Writing: [------------> ] 61 % Writing: [------------> ] 62 % Writing: [------------> ] 63 % Writing: [------------> ] 64 % Writing: [-------------> ] 65 % Writing: [-------------> ] 66 % Writing: [-------------> ] 67 % Writing: [-------------> ] 68 % Writing: [-------------> ] 69 % Writing: [--------------> ] 70 % Writing: [--------------> ] 71 % Writing: [--------------> ] 72 % Writing: [--------------> ] 73 % Writing: [--------------> ] 74 % Writing: [---------------> ] 75 % Writing: [---------------> ] 76 % Writing: [---------------> ] 77 % Writing: [---------------> ] 78 % Writing: [---------------> ] 79 % Writing: [----------------> ] 80 % Writing: [----------------> ] 81 % Writing: [----------------> ] 82 % Writing: [----------------> ] 83 % Writing: [----------------> ] 84 % Writing: [-----------------> ] 85 % Writing: [-----------------> ] 86 % Writing: [-----------------> ] 87 % Writing: [-----------------> ] 88 % Writing: [-----------------> ] 89 % Writing: [------------------> ] 90 % Writing: [------------------> ] 91 % Writing: [------------------> ] 92 % Writing: [------------------> ] 93 % Writing: [------------------> ] 94 % Writing: [-------------------> ] 95 % Writing: [-------------------> ] 96 % Writing: [-------------------> ] 97 % Writing: [-------------------> ] 98 % Writing: [-------------------> ] 99 % Writing: [-------------------->] 100 % Verifying: [> ] 0 % Verifying: [> ] 1 % Verifying: [> ] 2 % Verifying: [> ] 3 % Verifying: [> ] 4 % Verifying: [-> ] 5 % Verifying: [-> ] 6 % Verifying: [-> ] 7 % Verifying: [-> ] 8 % Verifying: [-> ] 9 % Verifying: [--> ] 10 % Verifying: [--> ] 11 % Verifying: [--> ] 12 % Verifying: [--> ] 13 % Verifying: [--> ] 14 % Verifying: [---> ] 15 % Verifying: [---> ] 16 % Verifying: [---> ] 17 % Verifying: [---> ] 18 % Verifying: [---> ] 19 % Verifying: [----> ] 20 % Verifying: [----> ] 21 % Verifying: [----> ] 22 % Verifying: [----> ] 23 % Verifying: [----> ] 24 % Verifying: [-----> ] 25 % Verifying: [-----> ] 26 % Verifying: [-----> ] 27 % Verifying: [-----> ] 28 % Verifying: [-----> ] 29 % Verifying: [------> ] 30 % Verifying: [------> ] 31 % Verifying: [------> ] 32 % Verifying: [------> ] 33 % Verifying: [------> ] 34 % Verifying: [-------> ] 35 % Verifying: [-------> ] 36 % Verifying: [-------> ] 37 % Verifying: [-------> ] 38 % Verifying: [-------> ] 39 % Verifying: [--------> ] 40 % Verifying: [--------> ] 41 % Verifying: [--------> ] 42 % Verifying: [--------> ] 43 % Verifying: [--------> ] 44 % Verifying: [---------> ] 45 % Verifying: [---------> ] 46 % Verifying: [---------> ] 47 % Verifying: [---------> ] 48 % Verifying: [---------> ] 49 % Verifying: [----------> ] 50 % Verifying: [----------> ] 51 % Verifying: [----------> ] 52 % Verifying: [----------> ] 53 % Verifying: [----------> ] 54 % Verifying: [-----------> ] 55 % Verifying: [-----------> ] 56 % Verifying: [-----------> ] 57 % Verifying: [-----------> ] 58 % Verifying: [-----------> ] 59 % Verifying: [------------> ] 60 % Verifying: [------------> ] 61 % Verifying: [------------> ] 62 % Verifying: [------------> ] 63 % Verifying: [------------> ] 64 % Verifying: [-------------> ] 65 % Verifying: [-------------> ] 66 % Verifying: [-------------> ] 67 % Verifying: [-------------> ] 68 % Verifying: [-------------> ] 69 % Verifying: [--------------> ] 70 % Verifying: [--------------> ] 71 % Verifying: [--------------> ] 72 % Verifying: [--------------> ] 73 % Verifying: [--------------> ] 74 % Verifying: [---------------> ] 75 % Verifying: [---------------> ] 76 % Verifying: [---------------> ] 77 % Verifying: [---------------> ] 78 % Verifying: [---------------> ] 79 % Verifying: [----------------> ] 80 % Verifying: [----------------> ] 81 % Verifying: [----------------> ] 82 % Verifying: [----------------> ] 83 % Verifying: [----------------> ] 84 % Verifying: [-----------------> ] 85 % Verifying: [-----------------> ] 86 % Verifying: [-----------------> ] 87 % Verifying: [-----------------> ] 88 % Verifying: [-----------------> ] 89 % Verifying: [------------------> ] 90 % Verifying: [------------------> ] 91 % Verifying: [------------------> ] 92 % Verifying: [------------------> ] 93 % Verifying: [------------------> ] 94 % Verifying: [-------------------> ] 95 % Verifying: [-------------------> ] 96 % Verifying: [-------------------> ] 97 % Verifying: [-------------------> ] 98 % Verifying: [-------------------> ] 99 %  Customising OS...  Verifying OS customisation... Write successful. +shim: imager finished, err: +[?9001l[?1004l \ No newline at end of file diff --git a/installer/internal/media/testdata/windows/disks-empty-reader.json b/installer/internal/media/testdata/windows/disks-empty-reader.json new file mode 100644 index 000000000..2fc89f05b --- /dev/null +++ b/installer/internal/media/testdata/windows/disks-empty-reader.json @@ -0,0 +1,175 @@ +{ + "disks": [ + { + "Number": 1, + "FriendlyName": "ST4000DM004-2CV104", + "Size": 4000787030016, + "BusType": "SATA", + "IsBoot": false, + "IsSystem": false + }, + { + "Number": 3, + "FriendlyName": "CT2000P3SSD8", + "Size": 2000398934016, + "BusType": "NVMe", + "IsBoot": true, + "IsSystem": true + }, + { + "Number": 2, + "FriendlyName": "Samsung SSD 850 EVO 250GB", + "Size": 250059350016, + "BusType": "SATA", + "IsBoot": false, + "IsSystem": false + }, + { + "Number": 0, + "FriendlyName": "WDC WD30EZRZ-00Z5HB0", + "Size": 3000592982016, + "BusType": "SATA", + "IsBoot": false, + "IsSystem": false + }, + { + "Number": 4, + "FriendlyName": "Mass Storage Device", + "Size": 0, + "BusType": "USB", + "IsBoot": false, + "IsSystem": false + }, + { + "Number": 5, + "FriendlyName": "TDK LoR Trans-It Drive", + "Size": 1992294400, + "BusType": "USB", + "IsBoot": false, + "IsSystem": false + } + ], + "partitions": [ + { + "DiskNumber": 1, + "PartitionNumber": 1, + "DriveLetter": "", + "Size": 4000785104896, + "AccessPaths": [] + }, + { + "DiskNumber": 3, + "PartitionNumber": 1, + "DriveLetter": "", + "Size": 104857600, + "AccessPaths": [] + }, + { + "DiskNumber": 3, + "PartitionNumber": 2, + "DriveLetter": "", + "Size": 16777216, + "AccessPaths": [] + }, + { + "DiskNumber": 3, + "PartitionNumber": 3, + "DriveLetter": "C", + "Size": 1515175542784, + "AccessPaths": [ + "C:\\", + "\\\\?\\Volume{00000000-0000-4000-8000-000000000005}\\" + ] + }, + { + "DiskNumber": 3, + "PartitionNumber": 4, + "DriveLetter": "", + "Size": 995098624, + "AccessPaths": [] + }, + { + "DiskNumber": 3, + "PartitionNumber": 5, + "DriveLetter": "", + "Size": 2147483648, + "AccessPaths": [] + }, + { + "DiskNumber": 3, + "PartitionNumber": 6, + "DriveLetter": "", + "Size": 481036337152, + "AccessPaths": [] + }, + { + "DiskNumber": 2, + "PartitionNumber": 1, + "DriveLetter": "", + "Size": 250058113024, + "AccessPaths": [] + }, + { + "DiskNumber": 0, + "PartitionNumber": 1, + "DriveLetter": "", + "Size": 16759808, + "AccessPaths": [] + }, + { + "DiskNumber": 0, + "PartitionNumber": 2, + "DriveLetter": "D", + "Size": 3000574672896, + "AccessPaths": [ + "D:\\", + "\\\\?\\Volume{00000000-0000-4000-8000-000000000004}\\" + ] + }, + { + "DiskNumber": 5, + "PartitionNumber": 1, + "DriveLetter": "", + "Size": 3768320, + "AccessPaths": [] + } + ], + "volumes": [ + { + "Path": "\\\\?\\Volume{00000000-0000-4000-8000-000000000001}\\", + "FileSystemLabel": "", + "FileSystem": "NTFS", + "Size": 995094528, + "SizeRemaining": 160161792 + }, + { + "Path": "\\\\?\\Volume{00000000-0000-4000-8000-000000000003}\\", + "FileSystemLabel": "", + "FileSystem": "FAT", + "Size": 3743744, + "SizeRemaining": 14336 + }, + { + "Path": "\\\\?\\Volume{00000000-0000-4000-8000-000000000004}\\", + "FileSystemLabel": "Data", + "FileSystem": "NTFS", + "Size": 3000574668800, + "SizeRemaining": 258564005888 + }, + { + "Path": "\\\\?\\Volume{00000000-0000-4000-8000-000000000005}\\", + "FileSystemLabel": "", + "FileSystem": "NTFS", + "Size": 1515175538688, + "SizeRemaining": 295196200960 + }, + { + "Path": "\\\\?\\Volume{00000000-0000-4000-8000-000000000006}\\", + "FileSystemLabel": "", + "FileSystem": "", + "Size": 0, + "SizeRemaining": 0 + } + ], + "systemDrive": "C:" +} diff --git a/installer/internal/media/testdata/windows/disks-none.json b/installer/internal/media/testdata/windows/disks-none.json new file mode 100644 index 000000000..29c97f6c6 --- /dev/null +++ b/installer/internal/media/testdata/windows/disks-none.json @@ -0,0 +1,138 @@ +{ + "disks": [ + { + "Number": 1, + "FriendlyName": "ST4000DM004-2CV104", + "Size": 4000787030016, + "BusType": "SATA", + "IsBoot": false, + "IsSystem": false + }, + { + "Number": 3, + "FriendlyName": "CT2000P3SSD8", + "Size": 2000398934016, + "BusType": "NVMe", + "IsBoot": true, + "IsSystem": true + }, + { + "Number": 2, + "FriendlyName": "Samsung SSD 850 EVO 250GB", + "Size": 250059350016, + "BusType": "SATA", + "IsBoot": false, + "IsSystem": false + }, + { + "Number": 0, + "FriendlyName": "WDC WD30EZRZ-00Z5HB0", + "Size": 3000592982016, + "BusType": "SATA", + "IsBoot": false, + "IsSystem": false + } + ], + "partitions": [ + { + "DiskNumber": 1, + "PartitionNumber": 1, + "DriveLetter": "", + "Size": 4000785104896, + "AccessPaths": [] + }, + { + "DiskNumber": 3, + "PartitionNumber": 1, + "DriveLetter": "", + "Size": 104857600, + "AccessPaths": [] + }, + { + "DiskNumber": 3, + "PartitionNumber": 2, + "DriveLetter": "", + "Size": 16777216, + "AccessPaths": [] + }, + { + "DiskNumber": 3, + "PartitionNumber": 3, + "DriveLetter": "C", + "Size": 1515175542784, + "AccessPaths": [ + "C:\\", + "\\\\?\\Volume{00000000-0000-4000-8000-000000000005}\\" + ] + }, + { + "DiskNumber": 3, + "PartitionNumber": 4, + "DriveLetter": "", + "Size": 995098624, + "AccessPaths": [] + }, + { + "DiskNumber": 3, + "PartitionNumber": 5, + "DriveLetter": "", + "Size": 2147483648, + "AccessPaths": [] + }, + { + "DiskNumber": 3, + "PartitionNumber": 6, + "DriveLetter": "", + "Size": 481036337152, + "AccessPaths": [] + }, + { + "DiskNumber": 2, + "PartitionNumber": 1, + "DriveLetter": "", + "Size": 250058113024, + "AccessPaths": [] + }, + { + "DiskNumber": 0, + "PartitionNumber": 1, + "DriveLetter": "", + "Size": 16759808, + "AccessPaths": [] + }, + { + "DiskNumber": 0, + "PartitionNumber": 2, + "DriveLetter": "D", + "Size": 3000574672896, + "AccessPaths": [ + "D:\\", + "\\\\?\\Volume{00000000-0000-4000-8000-000000000004}\\" + ] + } + ], + "volumes": [ + { + "Path": "\\\\?\\Volume{00000000-0000-4000-8000-000000000001}\\", + "FileSystemLabel": "", + "FileSystem": "NTFS", + "Size": 995094528, + "SizeRemaining": 120078336 + }, + { + "Path": "\\\\?\\Volume{00000000-0000-4000-8000-000000000004}\\", + "FileSystemLabel": "Data", + "FileSystem": "NTFS", + "Size": 3000574668800, + "SizeRemaining": 258766045184 + }, + { + "Path": "\\\\?\\Volume{00000000-0000-4000-8000-000000000005}\\", + "FileSystemLabel": "", + "FileSystem": "NTFS", + "Size": 1515175538688, + "SizeRemaining": 297555832832 + } + ], + "systemDrive": "C:" +} diff --git a/installer/internal/media/testdata/windows/disks-usb.json b/installer/internal/media/testdata/windows/disks-usb.json new file mode 100644 index 000000000..6af10ee5f --- /dev/null +++ b/installer/internal/media/testdata/windows/disks-usb.json @@ -0,0 +1 @@ +{"partitions":[{"DiskNumber":1,"PartitionNumber":1,"DriveLetter":"\u0000","Size":4000785104896,"AccessPaths":null},{"DiskNumber":3,"PartitionNumber":1,"DriveLetter":"\u0000","Size":104857600,"AccessPaths":"\\\\?\\Volume{00000000-0000-4000-8000-000000000001}\\"},{"DiskNumber":3,"PartitionNumber":2,"DriveLetter":"\u0000","Size":16777216,"AccessPaths":null},{"DiskNumber":3,"PartitionNumber":3,"DriveLetter":"C","Size":1515175542784,"AccessPaths":{"value":["C:\\","\\\\?\\Volume{00000000-0000-4000-8000-000000000002}\\"],"Count":2}},{"DiskNumber":3,"PartitionNumber":4,"DriveLetter":"\u0000","Size":995098624,"AccessPaths":"\\\\?\\Volume{00000000-0000-4000-8000-000000000003}\\"},{"DiskNumber":3,"PartitionNumber":5,"DriveLetter":"\u0000","Size":2147483648,"AccessPaths":null},{"DiskNumber":3,"PartitionNumber":6,"DriveLetter":"\u0000","Size":481036337152,"AccessPaths":null},{"DiskNumber":2,"PartitionNumber":1,"DriveLetter":"\u0000","Size":250058113024,"AccessPaths":null},{"DiskNumber":0,"PartitionNumber":1,"DriveLetter":"\u0000","Size":16759808,"AccessPaths":null},{"DiskNumber":0,"PartitionNumber":2,"DriveLetter":"D","Size":3000574672896,"AccessPaths":{"value":["D:\\","\\\\?\\Volume{00000000-0000-4000-8000-000000000004}\\"],"Count":2}},{"DiskNumber":4,"PartitionNumber":1,"DriveLetter":"E","Size":536870912,"AccessPaths":{"value":["E:\\","\\\\?\\Volume{00000000-0000-4000-8000-000000000005}\\"],"Count":2}},{"DiskNumber":4,"PartitionNumber":2,"DriveLetter":"\u0000","Size":3426746368,"AccessPaths":null},{"DiskNumber":5,"PartitionNumber":1,"DriveLetter":"\u0000","Size":3768320,"AccessPaths":"\\\\?\\Volume{00000000-0000-4000-8000-000000000006}\\"}],"volumes":[{"Path":"\\\\?\\Volume{00000000-0000-4000-8000-000000000003}\\","FileSystemLabel":"","FileSystem":"NTFS","Size":995094528,"SizeRemaining":160161792},{"Path":"\\\\?\\Volume{00000000-0000-4000-8000-000000000005}\\","FileSystemLabel":"bootfs","FileSystem":"FAT32","Size":528592896,"SizeRemaining":450158080},{"Path":"\\\\?\\Volume{00000000-0000-4000-8000-000000000006}\\","FileSystemLabel":"","FileSystem":"FAT","Size":3743744,"SizeRemaining":14336},{"Path":"\\\\?\\Volume{00000000-0000-4000-8000-000000000004}\\","FileSystemLabel":"Data","FileSystem":"NTFS","Size":3000574668800,"SizeRemaining":258424139776},{"Path":"\\\\?\\Volume{00000000-0000-4000-8000-000000000002}\\","FileSystemLabel":"","FileSystem":"NTFS","Size":1515175538688,"SizeRemaining":301933166592}],"disks":[{"Number":1,"FriendlyName":"ST4000DM004-2CV104","Size":4000787030016,"BusType":"SATA","IsBoot":false,"IsSystem":false},{"Number":3,"FriendlyName":"CT2000P3SSD8","Size":2000398934016,"BusType":"NVMe","IsBoot":true,"IsSystem":true},{"Number":2,"FriendlyName":"Samsung SSD 850 EVO 250GB","Size":250059350016,"BusType":"SATA","IsBoot":false,"IsSystem":false},{"Number":0,"FriendlyName":"WDC WD30EZRZ-00Z5HB0","Size":3000592982016,"BusType":"SATA","IsBoot":false,"IsSystem":false},{"Number":4,"FriendlyName":"Mass Storage Device","Size":3972005888,"BusType":"USB","IsBoot":false,"IsSystem":false},{"Number":5,"FriendlyName":"TDK LoR Trans-It Drive","Size":1992294400,"BusType":"USB","IsBoot":false,"IsSystem":false}],"systemDrive":"C:"} diff --git a/installer/internal/media/testdata/windows/wlan-profile-protected.xml b/installer/internal/media/testdata/windows/wlan-profile-protected.xml new file mode 100644 index 000000000..1694ed630 --- /dev/null +++ b/installer/internal/media/testdata/windows/wlan-profile-protected.xml @@ -0,0 +1,29 @@ + + + Beispielnetz1 + + + 426569737069656C6E65747A31 + Beispielnetz1 + + + ESS + auto + + + + WPA2PSK + AES + false + + + passPhrase + true + 01000000D08C9DDF0115D1118C7A00C04FC297EB + + + + + false + + diff --git a/installer/internal/media/testdata/windows/wlan-profile-psk.xml b/installer/internal/media/testdata/windows/wlan-profile-psk.xml new file mode 100644 index 000000000..f1dfbf040 --- /dev/null +++ b/installer/internal/media/testdata/windows/wlan-profile-psk.xml @@ -0,0 +1,29 @@ + + + Beispielnetz1 + + + 426569737069656C6E65747A31 + Beispielnetz1 + + + ESS + auto + + + + WPA2PSK + AES + false + + + passPhrase + false + beispielschluessel + + + + + false + + diff --git a/installer/internal/media/wifikey_other.go b/installer/internal/media/wifikey_other.go index d0894ec81..815831774 100644 --- a/installer/internal/media/wifikey_other.go +++ b/installer/internal/media/wifikey_other.go @@ -1,4 +1,4 @@ -//go:build !linux +//go:build !linux && !windows package media diff --git a/installer/internal/media/wifimemory.go b/installer/internal/media/wifimemory.go new file mode 100644 index 000000000..48f5476b3 --- /dev/null +++ b/installer/internal/media/wifimemory.go @@ -0,0 +1,65 @@ +package media + +import ( + "sort" + "sync" + "time" +) + +// wifiMemoryTTL ist die Zeit, die ein gesehenes Netz in der Liste bleibt. +const wifiMemoryTTL = 5 * time.Minute + +// WifiMemory sammelt die Netze mehrerer Abfragen. Windows haelt Scanergebnisse +// nur kurz, eine zweite Abfrage kann deshalb weniger Netze liefern. Der +// Nullwert ist benutzbar. +type WifiMemory struct { + Now func() time.Time // nil = time.Now + + mu sync.Mutex + seen map[string]rememberedWifi +} + +type rememberedWifi struct { + net WifiNetwork + at time.Time +} + +// Merge nimmt eine Abfrage auf und liefert alle noch gueltigen Netze, das +// staerkste zuerst. Ein einmal gesehenes Band bleibt dem Netz erhalten. +func (m *WifiMemory) Merge(nets []WifiNetwork) []WifiNetwork { + m.mu.Lock() + defer m.mu.Unlock() + now := time.Now() + if m.Now != nil { + now = m.Now() + } + if m.seen == nil { + m.seen = map[string]rememberedWifi{} + } + for ssid, r := range m.seen { + if now.Sub(r.at) > wifiMemoryTTL { + delete(m.seen, ssid) + } + } + for _, n := range nets { + if old, ok := m.seen[n.SSID]; ok { + n.Band24 = n.Band24 || old.net.Band24 + n.Band5 = n.Band5 || old.net.Band5 + } + m.seen[n.SSID] = rememberedWifi{net: n, at: now} + } + out := make([]WifiNetwork, 0, len(m.seen)) + for _, r := range m.seen { + out = append(out, r.net) + } + sort.Slice(out, func(a, b int) bool { + if out[a].Signal != out[b].Signal { + return out[a].Signal > out[b].Signal + } + return out[a].SSID < out[b].SSID + }) + if len(out) > maxWifiNetworks { + out = out[:maxWifiNetworks] + } + return out +} diff --git a/installer/internal/media/wifimemory_test.go b/installer/internal/media/wifimemory_test.go new file mode 100644 index 000000000..1ec18381e --- /dev/null +++ b/installer/internal/media/wifimemory_test.go @@ -0,0 +1,47 @@ +package media + +import ( + "reflect" + "testing" + "time" +) + +func TestWifiMemoryKeepsRecentNetworksAndBothBands(t *testing.T) { + now := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC) + m := &WifiMemory{Now: func() time.Time { return now }} + m.Merge([]WifiNetwork{ + {SSID: "Haus", Signal: 50, Band24: true}, + {SSID: "Nachbar", Signal: 30, Band24: true}, + }) + now = now.Add(time.Minute) + got := m.Merge([]WifiNetwork{{SSID: "Haus", Signal: 80, Band5: true}}) + want := []WifiNetwork{ + {SSID: "Haus", Signal: 80, Band24: true, Band5: true}, + {SSID: "Nachbar", Signal: 30, Band24: true}, + } + if !reflect.DeepEqual(got, want) { + t.Errorf("got %+v\nwant %+v", got, want) + } +} + +func TestWifiMemoryForgetsAfterFiveMinutes(t *testing.T) { + now := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC) + m := &WifiMemory{Now: func() time.Time { return now }} + m.Merge([]WifiNetwork{{SSID: "Alt", Signal: 50, Band24: true}}) + now = now.Add(6 * time.Minute) + if got := m.Merge(nil); len(got) != 0 { + t.Errorf("got %+v, want nothing", got) + } +} + +func TestWifiMemoryReturnsTheStrongestTen(t *testing.T) { + m := &WifiMemory{} + var nets []WifiNetwork + for i := 0; i < 12; i++ { + nets = append(nets, WifiNetwork{SSID: string(rune('a' + i)), Signal: i}) + } + got := m.Merge(nets) + if len(got) != 10 || got[0].SSID != "l" { + t.Errorf("got %+v", got) + } +} diff --git a/installer/internal/media/wlan_parse.go b/installer/internal/media/wlan_parse.go new file mode 100644 index 000000000..8626748d7 --- /dev/null +++ b/installer/internal/media/wlan_parse.go @@ -0,0 +1,88 @@ +package media + +import ( + "encoding/xml" + "sort" +) + +// maxWifiNetworks begrenzt die Netze in Reichweite. +const maxWifiNetworks = 10 + +// wifiSample ist ein Access Point aus einer Scanliste, vor dem Zusammenfassen. +type wifiSample struct { + SSID string + FreqMHz int + Signal int + Active bool +} + +// mergeWifi fasst Access Points mit gleichem Namen zu einem Netz zusammen. +// Leere Namen fallen weg, das staerkste Signal gewinnt, und das Band ergibt +// sich aus der Frequenz (ab 5000 MHz 5 GHz). Die Liste ist nach Signal und +// dann nach Name sortiert. +func mergeWifi(samples []wifiSample) (active string, activeFreq int, nets []WifiNetwork) { + byName := map[string]*WifiNetwork{} + var order []*WifiNetwork + for _, s := range samples { + if s.SSID == "" { + continue + } + if s.Active && active == "" { + active, activeFreq = s.SSID, s.FreqMHz + } + n := byName[s.SSID] + if n == nil { + n = &WifiNetwork{SSID: s.SSID} + byName[s.SSID] = n + order = append(order, n) + } + if s.Signal > n.Signal { + n.Signal = s.Signal + } + switch { + case s.FreqMHz >= 5000: + n.Band5 = true + case s.FreqMHz > 0: + n.Band24 = true + } + } + sort.SliceStable(order, func(a, b int) bool { + if order[a].Signal != order[b].Signal { + return order[a].Signal > order[b].Signal + } + return order[a].SSID < order[b].SSID + }) + if len(order) > maxWifiNetworks { + order = order[:maxWifiNetworks] + } + nets = make([]WifiNetwork, len(order)) + for k, n := range order { + nets[k] = *n + } + return active, activeFreq, nets +} + +// wlanProfileXML ist der Teil eines WLAN-Profils, den parseWlanProfile liest. +// Ohne Namensraum im Tag passt das Element unabhaengig von der Version des +// Profils. +type wlanProfileXML struct { + Name string `xml:"SSIDConfig>SSID>name"` + KeyType string `xml:"MSM>security>sharedKey>keyType"` + Protected string `xml:"MSM>security>sharedKey>protected"` + KeyMaterial string `xml:"MSM>security>sharedKey>keyMaterial"` +} + +// parseWlanProfile liest den Namen und, wenn er im Klartext vorliegt, das +// Passwort aus einem WLAN-Profil von WlanGetProfile. Verschluesselte Schluessel +// bleiben leer. ok ist false bei kaputtem XML oder ohne Namen. +func parseWlanProfile(data []byte) (storedWifi, bool) { + var p wlanProfileXML + if err := xml.Unmarshal(data, &p); err != nil || p.Name == "" { + return storedWifi{}, false + } + s := storedWifi{SSID: p.Name} + if p.KeyType == "passPhrase" && p.Protected == "false" { + s.PSK = p.KeyMaterial + } + return s, true +} diff --git a/installer/internal/media/wlan_parse_test.go b/installer/internal/media/wlan_parse_test.go new file mode 100644 index 000000000..5ed78a4ef --- /dev/null +++ b/installer/internal/media/wlan_parse_test.go @@ -0,0 +1,114 @@ +package media + +import ( + "os" + "reflect" + "strings" + "testing" + "unsafe" +) + +func TestWlanStructLayouts(t *testing.T) { + sizes := []struct { + name string + got, want uintptr + }{ + {"wlanInterfaceInfo", unsafe.Sizeof(wlanInterfaceInfo{}), 532}, + {"wlanBssEntry", unsafe.Sizeof(wlanBssEntry{}), 360}, + {"wlanProfileInfo", unsafe.Sizeof(wlanProfileInfo{}), 516}, + {"wlanBssEntry.BssType", unsafe.Offsetof(wlanBssEntry{}.BssType), 48}, + {"wlanBssEntry.Timestamp", unsafe.Offsetof(wlanBssEntry{}.Timestamp), 72}, + {"wlanBssEntry.ChCenterFrequency", unsafe.Offsetof(wlanBssEntry{}.ChCenterFrequency), 92}, + {"wlanBssEntry.IeSize", unsafe.Offsetof(wlanBssEntry{}.IeSize), 356}, + {"wlanConnectionHead.SSIDLen", unsafe.Offsetof(wlanConnectionHead{}.SSIDLen), 520}, + {"wlanConnectionHead.BSSID", unsafe.Offsetof(wlanConnectionHead{}.BSSID), 560}, + } + for _, s := range sizes { + if s.got != s.want { + t.Errorf("%s = %d, want %d", s.name, s.got, s.want) + } + } +} + +func TestMergeWifiMatchesTheNmcliBehaviour(t *testing.T) { + samples := []wifiSample{ + {SSID: "", FreqMHz: 2412, Signal: 90}, + {SSID: "WelcomeHome 5 GHz", FreqMHz: 5500, Signal: 64, Active: true}, + {SSID: "WelcomeHome", FreqMHz: 2437, Signal: 70}, + {SSID: "WelcomeHome", FreqMHz: 5180, Signal: 50}, + {SSID: "My:Net", FreqMHz: 2462, Signal: 30}, + {SSID: "Back\\slash", FreqMHz: 2412, Signal: 30}, + } + active, freq, nets := mergeWifi(samples) + if active != "WelcomeHome 5 GHz" || freq != 5500 { + t.Errorf("active = %q, %d", active, freq) + } + want := []WifiNetwork{ + {SSID: "WelcomeHome", Signal: 70, Band24: true, Band5: true}, + {SSID: "WelcomeHome 5 GHz", Signal: 64, Band5: true}, + {SSID: "Back\\slash", Signal: 30, Band24: true}, + {SSID: "My:Net", Signal: 30, Band24: true}, + } + if !reflect.DeepEqual(nets, want) { + t.Errorf("nets = %+v\nwant %+v", nets, want) + } +} + +func TestParseWlanProfileReadsThePassphrase(t *testing.T) { + data, err := os.ReadFile("testdata/windows/wlan-profile-psk.xml") + if err != nil { + t.Fatal(err) + } + got, ok := parseWlanProfile(data) + want := storedWifi{SSID: "Beispielnetz1", PSK: "beispielschluessel"} + if !ok || got != want { + t.Errorf("parseWlanProfile() = %+v, %v, want %+v, true", got, ok, want) + } +} + +func TestParseWlanProfileProtectedKeyIsUnknown(t *testing.T) { + data, err := os.ReadFile("testdata/windows/wlan-profile-protected.xml") + if err != nil { + t.Fatal(err) + } + got, ok := parseWlanProfile(data) + want := storedWifi{SSID: "Beispielnetz1", PSK: ""} + if !ok || got != want { + t.Errorf("parseWlanProfile() = %+v, %v, want %+v, true", got, ok, want) + } +} + +func TestParseWlanProfileUnescapesTheName(t *testing.T) { + data := ` + + Café & Co 5G +` + got, ok := parseWlanProfile([]byte(data)) + if !ok || got.SSID != "Café & Co 5G" { + t.Errorf("parseWlanProfile() = %+v, %v, want SSID %q", got, ok, "Café & Co 5G") + } +} + +func TestParseWlanProfileRejectsBrokenProfiles(t *testing.T) { + for name, data := range map[string]string{ + "broken xml": `Haus`, + "without ssid": `ESS`, + } { + t.Run(name, func(t *testing.T) { + if _, ok := parseWlanProfile([]byte(data)); ok { + t.Errorf("parseWlanProfile() ok = true, want false") + } + }) + } +} + +func TestParseWlanProfileKeepsSSIDAndKeyUntrimmed(t *testing.T) { + data := ` Haus ` + + `passPhrasefalse` + + ` geheim123 ` + got, ok := parseWlanProfile([]byte(strings.TrimSpace(data))) + want := storedWifi{SSID: " Haus ", PSK: " geheim123 "} + if !ok || got != want { + t.Errorf("parseWlanProfile() = %+v, %v, want %+v, true", got, ok, want) + } +} diff --git a/installer/internal/media/wlan_types.go b/installer/internal/media/wlan_types.go new file mode 100644 index 000000000..3b69efcff --- /dev/null +++ b/installer/internal/media/wlan_types.go @@ -0,0 +1,47 @@ +package media + +// wlanInterfaceInfo entspricht WLAN_INTERFACE_INFO (532 Bytes). +type wlanInterfaceInfo struct { + GUID [16]byte + Description [256]uint16 + State uint32 +} + +// wlanBssEntry entspricht WLAN_BSS_ENTRY (360 Bytes). +type wlanBssEntry struct { + SSIDLen uint32 + SSID [32]byte + PhyID uint32 + BSSID [6]byte + BssType uint32 + PhyType uint32 + RSSI int32 + LinkQuality uint32 + InRegDomain uint8 + BeaconPeriod uint16 + Timestamp uint64 + HostTimestamp uint64 + Capability uint16 + ChCenterFrequency uint32 // kHz + RateSetLen uint32 + RateSet [126]uint16 + IeOffset uint32 + IeSize uint32 +} + +// wlanConnectionHead ist der Anfang von WLAN_CONNECTION_ATTRIBUTES bis zur BSSID. +type wlanConnectionHead struct { + State uint32 + Mode uint32 + ProfileName [256]uint16 + SSIDLen uint32 + SSID [32]byte + BssType uint32 + BSSID [6]byte +} + +// wlanProfileInfo entspricht WLAN_PROFILE_INFO (516 Bytes). +type wlanProfileInfo struct { + Name [256]uint16 + Flags uint32 +} diff --git a/installer/internal/media/wlan_windows.go b/installer/internal/media/wlan_windows.go new file mode 100644 index 000000000..1e2ef42b4 --- /dev/null +++ b/installer/internal/media/wlan_windows.go @@ -0,0 +1,272 @@ +//go:build windows + +package media + +import ( + "context" + "time" + "unsafe" + + "golang.org/x/sys/windows" +) + +// wlanapi.dll wird erst beim Aufruf geladen. Fehlt sie, bleiben alle Ergebnisse leer. +var ( + wlanapi = windows.NewLazySystemDLL("wlanapi.dll") + procWlanOpenHandle = wlanapi.NewProc("WlanOpenHandle") + procWlanCloseHandle = wlanapi.NewProc("WlanCloseHandle") + procWlanEnumInterfaces = wlanapi.NewProc("WlanEnumInterfaces") + procWlanQueryInterface = wlanapi.NewProc("WlanQueryInterface") + procWlanScan = wlanapi.NewProc("WlanScan") + procWlanGetNetworkBssList = wlanapi.NewProc("WlanGetNetworkBssList") + procWlanGetProfileList = wlanapi.NewProc("WlanGetProfileList") + procWlanGetProfile = wlanapi.NewProc("WlanGetProfile") + procWlanFreeMemory = wlanapi.NewProc("WlanFreeMemory") +) + +const ( + wlanClientVersion = 2 + wlanOpcodeCurrentConn = 7 // wlan_intf_opcode_current_connection + wlanBssTypeAny = 3 // dot11_BSS_type_any + wlanProfileGetPlaintextKey = 4 // WLAN_PROFILE_GET_PLAINTEXT_KEY + wlanListHeader = 8 // Zaehler und Index bzw. Gesamtgroesse und Zaehler vor den Eintraegen + wlanMaxSSIDLen = 32 + wlanScanWait = 4 * time.Second + wlanCallTimeout = 3 * time.Second // HostDefaults und CheckWifiKey + wlanRangeTimeout = 15 * time.Second // WifiInRange +) + +// wlanReading ist das Ergebnis einer Abfrage der WLAN-Adapter. +type wlanReading struct { + active string + freq int + nets []WifiNetwork +} + +// wlanKeyResult ist das Ergebnis von CheckWifiKey. +type wlanKeyResult struct { + result, via string +} + +// CheckWifiKey vergleicht ssid und password mit den gespeicherten WLAN-Profilen +// dieses Rechners. Ohne Rechte, ohne Profile oder bei einem Fehler kommt +// WifiKeyUnknown heraus. +func CheckWifiKey(ctx context.Context, ssid, password string) (result, via string) { + if ssid == "" || password == "" { + return WifiKeyUnknown, "" + } + ctx, cancel := context.WithTimeout(ctx, wlanCallTimeout) + defer cancel() + res, ok := wlanRun(ctx, func() wlanKeyResult { + r, v := checkWlanKey(ssid, password) + return wlanKeyResult{r, v} + }) + if !ok { + return WifiKeyUnknown, "" + } + return res.result, res.via +} + +// WifiInRange scannt die WLAN-Adapter und liefert die Netze in Reichweite. +// Ohne Ortungsfreigabe oder Adapter kommt eine leere Liste heraus. +func WifiInRange(ctx context.Context) []WifiNetwork { + ctx, cancel := context.WithTimeout(ctx, wlanRangeTimeout) + defer cancel() + _, _, nets := windowsWifi(ctx, true) + return nets +} + +// windowsWifi liefert das aktive Netz, seine Frequenz und die Netze in Reichweite. +// Mit scan wird vorher ein Scan angestossen und kurz gewartet. +func windowsWifi(ctx context.Context, scan bool) (active string, freq int, nets []WifiNetwork) { + r, ok := wlanRun(ctx, func() wlanReading { return readWlan(ctx, scan) }) + if !ok { + return "", 0, nil + } + return r.active, r.freq, r.nets +} + +// wlanRun fuehrt work in einer eigenen Goroutine aus, die ihre Handles selbst +// schliesst. Endet ctx vorher, kommt ok false zurueck. Die Goroutine schreibt +// dann in einen gepufferten Kanal und blockiert nicht. +func wlanRun[T any](ctx context.Context, work func() T) (T, bool) { + done := make(chan T, 1) + go func() { done <- work() }() + var zero T + select { + case v := <-done: + return v, true + case <-ctx.Done(): + return zero, false + } +} + +// wlanReady laedt wlanapi.dll und alle benoetigten Funktionen. +func wlanReady() bool { + for _, p := range []*windows.LazyProc{ + procWlanOpenHandle, procWlanCloseHandle, procWlanEnumInterfaces, + procWlanQueryInterface, procWlanScan, procWlanGetNetworkBssList, + procWlanGetProfileList, procWlanGetProfile, procWlanFreeMemory, + } { + if p.Find() != nil { + return false + } + } + return true +} + +// wlanOpen oeffnet einen WLAN-Handle. Der Aufrufer schliesst ihn. +func wlanOpen() (uintptr, bool) { + var negotiated uint32 + var h uintptr + r, _, _ := procWlanOpenHandle.Call(wlanClientVersion, 0, + uintptr(unsafe.Pointer(&negotiated)), uintptr(unsafe.Pointer(&h))) + return h, r == 0 +} + +// readWlan liest Verbindung und Netze aller Adapter. Der Handle gehoert dieser Goroutine. +func readWlan(ctx context.Context, scan bool) wlanReading { + if !wlanReady() { + return wlanReading{} + } + h, ok := wlanOpen() + if !ok { + return wlanReading{} + } + defer procWlanCloseHandle.Call(h, 0) + + guids := wlanInterfaceGUIDs(h) + if scan { + for _, g := range guids { + procWlanScan.Call(h, uintptr(unsafe.Pointer(&g)), 0, 0, 0) + } + timer := time.NewTimer(wlanScanWait) + defer timer.Stop() + select { + case <-ctx.Done(): + return wlanReading{} + case <-timer.C: + } + } + + var samples []wifiSample + for _, g := range guids { + conn, connected := wlanConnection(h, &g) + for _, e := range wlanBssList(h, &g) { + n := min(int(e.SSIDLen), wlanMaxSSIDLen) + samples = append(samples, wifiSample{ + SSID: string(e.SSID[:n]), + FreqMHz: int(e.ChCenterFrequency / 1000), + Signal: int(e.LinkQuality), + Active: connected && e.BSSID == conn.BSSID, + }) + } + } + active, freq, nets := mergeWifi(samples) + return wlanReading{active: active, freq: freq, nets: nets} +} + +// checkWlanKey sammelt die Profile, die zu ssid passen, und vergleicht das Passwort. +func checkWlanKey(ssid, password string) (result, via string) { + if !wlanReady() { + return WifiKeyUnknown, "" + } + h, ok := wlanOpen() + if !ok { + return WifiKeyUnknown, "" + } + defer procWlanCloseHandle.Call(h, 0) + + var stored []storedWifi + for _, g := range wlanInterfaceGUIDs(h) { + for _, p := range wlanProfiles(h, &g) { + s, ok := wlanProfileData(h, &g, p) + if !ok || (s.SSID != ssid && !twins(ssid, s.SSID)) { + continue + } + stored = append(stored, s) + } + } + return matchWifiKey(stored, ssid, password) +} + +// wlanInterfaceGUIDs liest die GUIDs der WLAN-Adapter. Die Werte werden kopiert, +// bevor der Speicher der Liste frei geht. +func wlanInterfaceGUIDs(h uintptr) [][16]byte { + var list unsafe.Pointer + r, _, _ := procWlanEnumInterfaces.Call(h, 0, uintptr(unsafe.Pointer(&list))) + if r != 0 || list == nil { + return nil + } + defer procWlanFreeMemory.Call(uintptr(list)) + count := int(*(*uint32)(list)) + infos := unsafe.Slice((*wlanInterfaceInfo)(unsafe.Add(list, wlanListHeader)), count) + guids := make([][16]byte, 0, count) + for i := range infos { + guids = append(guids, infos[i].GUID) + } + return guids +} + +// wlanConnection liest die aktuelle Verbindung eines Adapters. ok ist false ohne +// Verbindung oder wenn Windows den Zugriff verweigert. +func wlanConnection(h uintptr, guid *[16]byte) (conn wlanConnectionHead, ok bool) { + var size uint32 + var data unsafe.Pointer + r, _, _ := procWlanQueryInterface.Call(h, uintptr(unsafe.Pointer(guid)), wlanOpcodeCurrentConn, 0, + uintptr(unsafe.Pointer(&size)), uintptr(unsafe.Pointer(&data)), 0) + if r != 0 || data == nil { + return wlanConnectionHead{}, false + } + defer procWlanFreeMemory.Call(uintptr(data)) + if size < uint32(unsafe.Sizeof(wlanConnectionHead{})) { + return wlanConnectionHead{}, false + } + return *(*wlanConnectionHead)(data), true +} + +// wlanBssList liest die Netze in Reichweite eines Adapters. Die Eintraege werden kopiert. +func wlanBssList(h uintptr, guid *[16]byte) []wlanBssEntry { + var list unsafe.Pointer + r, _, _ := procWlanGetNetworkBssList.Call(h, uintptr(unsafe.Pointer(guid)), 0, wlanBssTypeAny, 0, 0, + uintptr(unsafe.Pointer(&list))) + if r != 0 || list == nil { + return nil + } + defer procWlanFreeMemory.Call(uintptr(list)) + count := int(*(*uint32)(unsafe.Add(list, 4))) + entries := unsafe.Slice((*wlanBssEntry)(unsafe.Add(list, wlanListHeader)), count) + out := make([]wlanBssEntry, count) + copy(out, entries) + return out +} + +// wlanProfiles liest die gespeicherten Profile eines Adapters. Die Eintraege werden kopiert. +func wlanProfiles(h uintptr, guid *[16]byte) []wlanProfileInfo { + var list unsafe.Pointer + r, _, _ := procWlanGetProfileList.Call(h, uintptr(unsafe.Pointer(guid)), 0, uintptr(unsafe.Pointer(&list))) + if r != 0 || list == nil { + return nil + } + defer procWlanFreeMemory.Call(uintptr(list)) + count := int(*(*uint32)(list)) + entries := unsafe.Slice((*wlanProfileInfo)(unsafe.Add(list, wlanListHeader)), count) + out := make([]wlanProfileInfo, count) + copy(out, entries) + return out +} + +// wlanProfileData holt ein Profil mit Klartext-Schluessel und liest es aus. +// Das XML liegt in Speicher der Windows-API und wird danach frei gegeben. +func wlanProfileData(h uintptr, guid *[16]byte, info wlanProfileInfo) (storedWifi, bool) { + name := info.Name + flags := uint32(wlanProfileGetPlaintextKey) + var xml unsafe.Pointer + r, _, _ := procWlanGetProfile.Call(h, uintptr(unsafe.Pointer(guid)), uintptr(unsafe.Pointer(&name[0])), 0, + uintptr(unsafe.Pointer(&xml)), uintptr(unsafe.Pointer(&flags)), 0) + if r != 0 || xml == nil { + return storedWifi{}, false + } + defer procWlanFreeMemory.Call(uintptr(xml)) + return parseWlanProfile([]byte(windows.UTF16PtrToString((*uint16)(xml)))) +} diff --git a/installer/internal/media/zoneinfo.go b/installer/internal/media/zoneinfo.go new file mode 100644 index 000000000..8b17b0078 --- /dev/null +++ b/installer/internal/media/zoneinfo.go @@ -0,0 +1,100 @@ +package media + +import ( + "bufio" + "bytes" + "embed" + "sort" + "strings" +) + +// zoneinfoFS enthaelt die Zonentabelle (tzdata, gemeinfrei) und die Zuordnung der +// Windows-Zonen-IDs (CLDR, territory 001). Linux und Windows greifen darauf zurueck. +// +//go:embed zoneinfo/zone1970.tab zoneinfo/windowszones.txt +var zoneinfoFS embed.FS + +// windowsZonesData returns the embedded Windows-to-IANA table. +func windowsZonesData() []byte { + data, _ := zoneinfoFS.ReadFile("zoneinfo/windowszones.txt") + return data +} + +// embeddedZones returns the sorted zones of the embedded zone1970.tab plus UTC, +// and the zone -> country code map of the same table. +func embeddedZones() (zones []string, countries map[string]string) { + data, _ := zoneinfoFS.ReadFile("zoneinfo/zone1970.tab") + return zonesWithUTC(parseZoneTab(data)), parseZoneCountries(data) +} + +// zonesWithUTC adds UTC to a sorted zone list when it is missing. +func zonesWithUTC(zones []string) []string { + for _, z := range zones { + if z == "UTC" { + return zones + } + } + zones = append(zones, "UTC") + sort.Strings(zones) + return zones +} + +// windowsZoneToIANA maps a Windows time zone ID such as "W. Europe Standard Time" +// to its IANA zone. Etc/UTC and Etc/GMT both become "UTC", so the zone is part +// of the picker list. Unknown IDs return "". +func windowsZoneToIANA(id string) string { + scanner := bufio.NewScanner(bytes.NewReader(windowsZonesData())) + for scanner.Scan() { + line := scanner.Text() + if line == "" || strings.HasPrefix(line, "#") { + continue + } + winID, iana, ok := strings.Cut(line, "\t") + if !ok || winID != id { + continue + } + if iana == "Etc/UTC" || iana == "Etc/GMT" { + return "UTC" + } + return iana + } + return "" +} + +// parseZoneTab returns the sorted zone names (third column) of a zone1970.tab file. +func parseZoneTab(data []byte) []string { + var zones []string + sc := bufio.NewScanner(bytes.NewReader(data)) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + fields := strings.Split(line, "\t") + if len(fields) < 3 { + continue + } + zones = append(zones, strings.TrimSpace(fields[2])) + } + sort.Strings(zones) + return zones +} + +// parseZoneCountries returns zone -> first country code (first column, comma separated) of zone1970.tab. +func parseZoneCountries(data []byte) map[string]string { + out := map[string]string{} + sc := bufio.NewScanner(bytes.NewReader(data)) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + fields := strings.Split(line, "\t") + if len(fields) < 3 { + continue + } + code, _, _ := strings.Cut(strings.TrimSpace(fields[0]), ",") + out[strings.TrimSpace(fields[2])] = code + } + return out +} diff --git a/installer/internal/media/zoneinfo/windowszones.txt b/installer/internal/media/zoneinfo/windowszones.txt new file mode 100644 index 000000000..ab7d34a2d --- /dev/null +++ b/installer/internal/media/zoneinfo/windowszones.txt @@ -0,0 +1,133 @@ +# CLDR 48 windowsZones.xml territory 001, legacy names as in zone1970.tab (tzdata 2026f) +Aleutian Standard Time America/Adak +Hawaiian Standard Time Pacific/Honolulu +Marquesas Standard Time Pacific/Marquesas +Alaskan Standard Time America/Anchorage +Pacific Standard Time (Mexico) America/Tijuana +Pacific Standard Time America/Los_Angeles +US Mountain Standard Time America/Phoenix +Mountain Standard Time (Mexico) America/Mazatlan +Mountain Standard Time America/Denver +Yukon Standard Time America/Whitehorse +Central America Standard Time America/Guatemala +Central Standard Time America/Chicago +Easter Island Standard Time Pacific/Easter +Central Standard Time (Mexico) America/Mexico_City +Canada Central Standard Time America/Regina +SA Pacific Standard Time America/Bogota +Eastern Standard Time (Mexico) America/Cancun +Eastern Standard Time America/New_York +Haiti Standard Time America/Port-au-Prince +Cuba Standard Time America/Havana +US Eastern Standard Time America/Indiana/Indianapolis +Turks And Caicos Standard Time America/Grand_Turk +Paraguay Standard Time America/Asuncion +Atlantic Standard Time America/Halifax +Venezuela Standard Time America/Caracas +Central Brazilian Standard Time America/Cuiaba +SA Western Standard Time America/La_Paz +Pacific SA Standard Time America/Santiago +Newfoundland Standard Time America/St_Johns +Tocantins Standard Time America/Araguaina +E. South America Standard Time America/Sao_Paulo +SA Eastern Standard Time America/Cayenne +Argentina Standard Time America/Argentina/Buenos_Aires +Greenland Standard Time America/Nuuk +Montevideo Standard Time America/Montevideo +Magallanes Standard Time America/Punta_Arenas +Saint Pierre Standard Time America/Miquelon +Bahia Standard Time America/Bahia +Azores Standard Time Atlantic/Azores +Cape Verde Standard Time Atlantic/Cape_Verde +UTC Etc/UTC +GMT Standard Time Europe/London +Greenwich Standard Time Etc/UTC +Sao Tome Standard Time Africa/Sao_Tome +Morocco Standard Time Africa/Casablanca +W. Europe Standard Time Europe/Berlin +Central Europe Standard Time Europe/Budapest +Romance Standard Time Europe/Paris +Central European Standard Time Europe/Warsaw +W. Central Africa Standard Time Africa/Lagos +Jordan Standard Time Asia/Amman +GTB Standard Time Europe/Bucharest +Middle East Standard Time Asia/Beirut +Egypt Standard Time Africa/Cairo +E. Europe Standard Time Europe/Chisinau +Syria Standard Time Asia/Damascus +West Bank Standard Time Asia/Hebron +South Africa Standard Time Africa/Johannesburg +FLE Standard Time Europe/Kyiv +Israel Standard Time Asia/Jerusalem +South Sudan Standard Time Africa/Juba +Kaliningrad Standard Time Europe/Kaliningrad +Sudan Standard Time Africa/Khartoum +Libya Standard Time Africa/Tripoli +Namibia Standard Time Africa/Windhoek +Arabic Standard Time Asia/Baghdad +Turkey Standard Time Europe/Istanbul +Arab Standard Time Asia/Riyadh +Belarus Standard Time Europe/Minsk +Russian Standard Time Europe/Moscow +E. Africa Standard Time Africa/Nairobi +Iran Standard Time Asia/Tehran +Arabian Standard Time Asia/Dubai +Astrakhan Standard Time Europe/Astrakhan +Azerbaijan Standard Time Asia/Baku +Russia Time Zone 3 Europe/Samara +Mauritius Standard Time Indian/Mauritius +Saratov Standard Time Europe/Saratov +Georgian Standard Time Asia/Tbilisi +Volgograd Standard Time Europe/Volgograd +Caucasus Standard Time Asia/Yerevan +Afghanistan Standard Time Asia/Kabul +West Asia Standard Time Asia/Tashkent +Ekaterinburg Standard Time Asia/Yekaterinburg +Pakistan Standard Time Asia/Karachi +Qyzylorda Standard Time Asia/Qyzylorda +India Standard Time Asia/Kolkata +Sri Lanka Standard Time Asia/Colombo +Nepal Standard Time Asia/Kathmandu +Central Asia Standard Time Asia/Bishkek +Bangladesh Standard Time Asia/Dhaka +Omsk Standard Time Asia/Omsk +Myanmar Standard Time Asia/Yangon +SE Asia Standard Time Asia/Bangkok +Altai Standard Time Asia/Barnaul +W. Mongolia Standard Time Asia/Hovd +North Asia Standard Time Asia/Krasnoyarsk +N. Central Asia Standard Time Asia/Novosibirsk +Tomsk Standard Time Asia/Tomsk +China Standard Time Asia/Shanghai +North Asia East Standard Time Asia/Irkutsk +Singapore Standard Time Asia/Singapore +W. Australia Standard Time Australia/Perth +Taipei Standard Time Asia/Taipei +Ulaanbaatar Standard Time Asia/Ulaanbaatar +Aus Central W. Standard Time Australia/Eucla +Transbaikal Standard Time Asia/Chita +Tokyo Standard Time Asia/Tokyo +North Korea Standard Time Asia/Pyongyang +Korea Standard Time Asia/Seoul +Yakutsk Standard Time Asia/Yakutsk +Cen. Australia Standard Time Australia/Adelaide +AUS Central Standard Time Australia/Darwin +E. Australia Standard Time Australia/Brisbane +AUS Eastern Standard Time Australia/Sydney +West Pacific Standard Time Pacific/Port_Moresby +Tasmania Standard Time Australia/Hobart +Vladivostok Standard Time Asia/Vladivostok +Lord Howe Standard Time Australia/Lord_Howe +Bougainville Standard Time Pacific/Bougainville +Russia Time Zone 10 Asia/Srednekolymsk +Magadan Standard Time Asia/Magadan +Norfolk Standard Time Pacific/Norfolk +Sakhalin Standard Time Asia/Sakhalin +Central Pacific Standard Time Pacific/Guadalcanal +Russia Time Zone 11 Asia/Kamchatka +New Zealand Standard Time Pacific/Auckland +Fiji Standard Time Pacific/Fiji +Chatham Islands Standard Time Pacific/Chatham +Tonga Standard Time Pacific/Tongatapu +Samoa Standard Time Pacific/Apia +Line Islands Standard Time Pacific/Kiritimati diff --git a/installer/internal/media/zoneinfo/zone1970.tab b/installer/internal/media/zoneinfo/zone1970.tab new file mode 100644 index 000000000..1aed9b5e3 --- /dev/null +++ b/installer/internal/media/zoneinfo/zone1970.tab @@ -0,0 +1,375 @@ +# tzdb timezone descriptions +# +# This file is in the public domain. +# +# From Paul Eggert (2025-05-15): +# This file contains a table where each row stands for a timezone where +# civil timestamps have agreed since 1970. Columns are separated by +# a single tab. Lines beginning with ‘#’ are comments. All text uses +# UTF-8 encoding. The columns of the table are as follows: +# +# 1. The countries that overlap the timezone, as a comma-separated list +# of ISO 3166 2-character country codes. +# 2. Latitude and longitude of the timezone’s principal location +# in ISO 6709 sign-degrees-minutes-seconds format, +# either ±DDMM±DDDMM or ±DDMMSS±DDDMMSS, +# first latitude (+ is north), then longitude (+ is east). +# 3. Timezone name used in value of TZ environment variable. +# Please see the theory.html file for how these names are chosen. +# If multiple timezones overlap a country, each has a row in the +# table, with each column 1 containing the country code. +# 4. Comments; present if and only if countries have multiple timezones, +# and useful only for those countries. For example, the comments +# for the row with countries CH,DE,LI and name Europe/Zurich +# are useful only for DE, since CH and LI have no other timezones. +# +# If a timezone covers multiple countries, the most-populous city is used, +# and that country is listed first in column 1; any other countries +# are listed alphabetically by country code. The table is sorted +# first by country code, then (if possible) by an order within the +# country that (1) makes some geographical sense, and (2) puts the +# most populous timezones first, where that does not contradict (1). +# +# This table is intended as an aid for users, to help them select timezones +# appropriate for their practical needs. It is not intended to take or +# endorse any position on legal or territorial claims. +# +#country- +#codes coordinates TZ comments +AD +4230+00131 Europe/Andorra +AE,OM,RE,SC,TF +2518+05518 Asia/Dubai Crozet +AF +3431+06912 Asia/Kabul +AL +4120+01950 Europe/Tirane +AM +4011+04430 Asia/Yerevan +AQ -6617+11031 Antarctica/Casey Casey +AQ -6835+07758 Antarctica/Davis Davis +AQ -6736+06253 Antarctica/Mawson Mawson +AQ -6448-06406 Antarctica/Palmer Palmer +AQ -6734-06808 Antarctica/Rothera Rothera +AQ -720041+0023206 Antarctica/Troll Troll +AQ -7824+10654 Antarctica/Vostok Vostok +AR -3436-05827 America/Argentina/Buenos_Aires Buenos Aires (BA, CF) +AR -3124-06411 America/Argentina/Cordoba most areas: CB, CC, CN, ER, FM, MN, SE, SF +AR -2447-06525 America/Argentina/Salta Salta (SA, LP, NQ, RN) +AR -2411-06518 America/Argentina/Jujuy Jujuy (JY) +AR -2649-06513 America/Argentina/Tucuman Tucumán (TM) +AR -2828-06547 America/Argentina/Catamarca Catamarca (CT), Chubut (CH) +AR -2926-06651 America/Argentina/La_Rioja La Rioja (LR) +AR -3132-06831 America/Argentina/San_Juan San Juan (SJ) +AR -3253-06849 America/Argentina/Mendoza Mendoza (MZ) +AR -3319-06621 America/Argentina/San_Luis San Luis (SL) +AR -5138-06913 America/Argentina/Rio_Gallegos Santa Cruz (SC) +AR -5448-06818 America/Argentina/Ushuaia Tierra del Fuego (TF) +AS,UM -1416-17042 Pacific/Pago_Pago Midway +AT +4813+01620 Europe/Vienna +AU -3133+15905 Australia/Lord_Howe Lord Howe Island +AU -5430+15857 Antarctica/Macquarie Macquarie Island +AU -4253+14719 Australia/Hobart Tasmania +AU -3749+14458 Australia/Melbourne Victoria +AU -3352+15113 Australia/Sydney New South Wales (most areas) +AU -3157+14127 Australia/Broken_Hill New South Wales (Yancowinna) +AU -2728+15302 Australia/Brisbane Queensland (most areas) +AU -2016+14900 Australia/Lindeman Queensland (Whitsunday Islands) +AU -3455+13835 Australia/Adelaide South Australia +AU -1228+13050 Australia/Darwin Northern Territory +AU -3157+11551 Australia/Perth Western Australia (most areas) +AU -3143+12852 Australia/Eucla Western Australia (Eucla) +AZ +4023+04951 Asia/Baku +BB +1306-05937 America/Barbados +BD +2343+09025 Asia/Dhaka +BE,LU,NL +5050+00420 Europe/Brussels +BG +4241+02319 Europe/Sofia +BM +3217-06446 Atlantic/Bermuda +BO -1630-06809 America/La_Paz +BR -0351-03225 America/Noronha Atlantic islands +BR -0127-04829 America/Belem Pará (east), Amapá +BR -0343-03830 America/Fortaleza Brazil (northeast: MA, PI, CE, RN, PB) +BR -0803-03454 America/Recife Pernambuco +BR -0712-04812 America/Araguaina Tocantins +BR -0940-03543 America/Maceio Alagoas, Sergipe +BR -1259-03831 America/Bahia Bahia +BR -2332-04637 America/Sao_Paulo Brazil (southeast: GO, DF, MG, ES, RJ, SP, PR, SC, RS) +BR -2027-05437 America/Campo_Grande Mato Grosso do Sul +BR -1535-05605 America/Cuiaba Mato Grosso +BR -0226-05452 America/Santarem Pará (west) +BR -0846-06354 America/Porto_Velho Rondônia +BR +0249-06040 America/Boa_Vista Roraima +BR -0308-06001 America/Manaus Amazonas (east) +BR -0640-06952 America/Eirunepe Amazonas (west) +BR -0958-06748 America/Rio_Branco Acre +BT +2728+08939 Asia/Thimphu +BY +5354+02734 Europe/Minsk +BZ +1730-08812 America/Belize +CA +4734-05243 America/St_Johns Newfoundland, Labrador (SE) +CA +4439-06336 America/Halifax Atlantic - NS (most areas), PE +CA +4612-05957 America/Glace_Bay Atlantic - NS (Cape Breton) +CA +4606-06447 America/Moncton Atlantic - New Brunswick +CA +5320-06025 America/Goose_Bay Atlantic - Labrador (most areas) +CA,BS +4339-07923 America/Toronto Eastern - ON & QC (most areas) +CA +6344-06828 America/Iqaluit Eastern - NU (most areas) +CA +4953-09709 America/Winnipeg EST - Manitoba, ON (northwest) +CA +744144-0944945 America/Resolute Central - NU (Resolute) +CA +624900-0920459 America/Rankin_Inlet Central - NU (central) +CA +5024-10439 America/Regina CST - SK (most areas) +CA +5017-10750 America/Swift_Current CST - SK (midwest) +CA +5333-11328 America/Edmonton CST - AB, BC(E), NT(E), SK(W) +CA +690650-1050310 America/Cambridge_Bay Mountain - NU (west) +CA +682059-1334300 America/Inuvik CST - NT (west) +CA +4916-12307 America/Vancouver MST - BC (most areas) +CA +5546-12014 America/Dawson_Creek MST - BC (Dawson Cr, Ft St John) +CA +5848-12242 America/Fort_Nelson MST - BC (Ft Nelson) +CA +6043-13503 America/Whitehorse MST - Yukon (east) +CA +6404-13925 America/Dawson MST - Yukon (west) +CH,DE,LI +4723+00832 Europe/Zurich Büsingen +CI,BF,GH,GM,GN,IS,ML,MR,SH,SL,SN,TG +0519-00402 Africa/Abidjan +CK -2114-15946 Pacific/Rarotonga +CL -3327-07040 America/Santiago most of Chile +CL -4534-07204 America/Coyhaique Aysén Region +CL -5309-07055 America/Punta_Arenas Magallanes Region +CL -2709-10926 Pacific/Easter Easter Island +CN +3114+12128 Asia/Shanghai Beijing Time +CN +4348+08735 Asia/Urumqi Xinjiang Time +CO +0436-07405 America/Bogota +CR +0956-08405 America/Costa_Rica +CU +2308-08222 America/Havana +CV +1455-02331 Atlantic/Cape_Verde +CY +3510+03322 Asia/Nicosia most of Cyprus +CY +3507+03357 Asia/Famagusta Northern Cyprus +CZ,SK +5005+01426 Europe/Prague +DE,DK,NO,SE,SJ +5230+01322 Europe/Berlin most of Germany +DO +1828-06954 America/Santo_Domingo +DZ +3647+00303 Africa/Algiers +EC -0210-07950 America/Guayaquil Ecuador (mainland) +EC -0054-08936 Pacific/Galapagos Galápagos Islands +EE +5925+02445 Europe/Tallinn +EG +3003+03115 Africa/Cairo +EH +2709-01312 Africa/El_Aaiun +ES +4024-00341 Europe/Madrid Spain (mainland) +ES +3553-00519 Africa/Ceuta Ceuta, Melilla +ES +2806-01524 Atlantic/Canary Canary Islands +FI,AX +6010+02458 Europe/Helsinki +FJ -1808+17825 Pacific/Fiji +FK -5142-05751 Atlantic/Stanley +FM +0519+16259 Pacific/Kosrae Kosrae +FO +6201-00646 Atlantic/Faroe +FR,MC +4852+00220 Europe/Paris +GB,GG,IM,JE +513030-0000731 Europe/London +GE +4143+04449 Asia/Tbilisi +GF +0456-05220 America/Cayenne +GI +3608-00521 Europe/Gibraltar +GL +6411-05144 America/Nuuk most of Greenland +GL +7646-01840 America/Danmarkshavn National Park (east coast) +GL +7029-02158 America/Scoresbysund Scoresbysund/Ittoqqortoormiit +GL +7634-06847 America/Thule Thule/Pituffik +GR +3758+02343 Europe/Athens +GS -5416-03632 Atlantic/South_Georgia +GT +1438-09031 America/Guatemala +GU,MP +1328+14445 Pacific/Guam +GW +1151-01535 Africa/Bissau +GY +0648-05810 America/Guyana +HK +2217+11409 Asia/Hong_Kong +HN +1406-08713 America/Tegucigalpa +HT +1832-07220 America/Port-au-Prince +HU +4730+01905 Europe/Budapest +ID -0610+10648 Asia/Jakarta Java, Sumatra +ID -0002+10920 Asia/Pontianak Borneo (west, central) +ID -0507+11924 Asia/Makassar Borneo (east, south), Sulawesi/Celebes, Bali, Nusa Tengarra, Timor (west) +ID -0232+14042 Asia/Jayapura New Guinea (West Papua / Irian Jaya), Malukus/Moluccas +IE +5320-00615 Europe/Dublin +IL +314650+0351326 Asia/Jerusalem +IN +2232+08822 Asia/Kolkata +IO -0720+07225 Indian/Chagos +IQ +3321+04425 Asia/Baghdad +IR +3540+05126 Asia/Tehran +IT,SM,VA +4154+01229 Europe/Rome +JM +175805-0764736 America/Jamaica +JO +3157+03556 Asia/Amman +JP,AU +353916+1394441 Asia/Tokyo Eyre Bird Observatory +KE,DJ,ER,ET,KM,MG,SO,TZ,UG,YT -0117+03649 Africa/Nairobi +KG +4254+07436 Asia/Bishkek +KI,MH,TV,UM,WF +0125+17300 Pacific/Tarawa Gilberts, Marshalls, Wake +KI -0247-17143 Pacific/Kanton Phoenix Islands +KI +0152-15720 Pacific/Kiritimati Line Islands +KP +3901+12545 Asia/Pyongyang +KR +3733+12658 Asia/Seoul +KZ +4315+07657 Asia/Almaty most of Kazakhstan +KZ +4448+06528 Asia/Qyzylorda Qyzylorda/Kyzylorda/Kzyl-Orda +KZ +5312+06337 Asia/Qostanay Qostanay/Kostanay/Kustanay +KZ +5017+05710 Asia/Aqtobe Aqtöbe/Aktobe +KZ +4431+05016 Asia/Aqtau Mangghystaū/Mankistau +KZ +4707+05156 Asia/Atyrau Atyraū/Atirau/Gur’yev +KZ +5113+05121 Asia/Oral West Kazakhstan +LB +3353+03530 Asia/Beirut +LK +0656+07951 Asia/Colombo +LR +0618-01047 Africa/Monrovia +LT +5441+02519 Europe/Vilnius +LV +5657+02406 Europe/Riga +LY +3254+01311 Africa/Tripoli +MA +3339-00735 Africa/Casablanca +MD +4700+02850 Europe/Chisinau +MH +0905+16720 Pacific/Kwajalein Kwajalein +MM,CC +1647+09610 Asia/Yangon +MN +4755+10653 Asia/Ulaanbaatar most of Mongolia +MN +4801+09139 Asia/Hovd Bayan-Ölgii, Hovd, Uvs +MO +221150+1133230 Asia/Macau +MQ +1436-06105 America/Martinique +MT +3554+01431 Europe/Malta +MU -2010+05730 Indian/Mauritius +MV,TF +0410+07330 Indian/Maldives Kerguelen, St Paul I, Amsterdam I +MX +1924-09909 America/Mexico_City Central Mexico +MX +2105-08646 America/Cancun Quintana Roo +MX +2058-08937 America/Merida Campeche, Yucatán +MX +2540-10019 America/Monterrey Durango; Coahuila, Nuevo León, Tamaulipas (most areas) +MX +2550-09730 America/Matamoros Coahuila, Nuevo León, Tamaulipas (US border) +MX +2838-10605 America/Chihuahua Chihuahua (most areas) +MX +3144-10629 America/Ciudad_Juarez Chihuahua (US border - west) +MX +2934-10425 America/Ojinaga Chihuahua (US border - east) +MX +2313-10625 America/Mazatlan Baja California Sur, Nayarit (most areas), Sinaloa +MX +2048-10515 America/Bahia_Banderas Bahía de Banderas +MX +2904-11058 America/Hermosillo Sonora +MX +3232-11701 America/Tijuana Baja California +MY,BN +0133+11020 Asia/Kuching Sabah, Sarawak +MZ,BI,BW,CD,MW,RW,ZM,ZW -2558+03235 Africa/Maputo Central Africa Time +NA -2234+01706 Africa/Windhoek +NC -2216+16627 Pacific/Noumea +NF -2903+16758 Pacific/Norfolk +NG,AO,BJ,CD,CF,CG,CM,GA,GQ,NE +0627+00324 Africa/Lagos West Africa Time +NI +1209-08617 America/Managua +NP +2743+08519 Asia/Kathmandu +NR -0031+16655 Pacific/Nauru +NU -1901-16955 Pacific/Niue +NZ,AQ -3652+17446 Pacific/Auckland New Zealand time +NZ -4357-17633 Pacific/Chatham Chatham Islands +PA,CA,KY +0858-07932 America/Panama EST - ON (Atikokan), NU (Coral H) +PE -1203-07703 America/Lima +PF -1732-14934 Pacific/Tahiti Society Islands +PF -0900-13930 Pacific/Marquesas Marquesas Islands +PF -2308-13457 Pacific/Gambier Gambier Islands +PG,AQ,FM -0930+14710 Pacific/Port_Moresby Papua New Guinea (most areas), Chuuk, Yap, Dumont d’Urville +PG -0613+15534 Pacific/Bougainville Bougainville +PH +143512+1205804 Asia/Manila +PK +2452+06703 Asia/Karachi +PL +5215+02100 Europe/Warsaw +PM +4703-05620 America/Miquelon +PN -2504-13005 Pacific/Pitcairn +PR,AG,CA,AI,AW,BL,BQ,CW,DM,GD,GP,KN,LC,MF,MS,SX,TT,VC,VG,VI +182806-0660622 America/Puerto_Rico AST - QC (Lower North Shore) +PS +3130+03428 Asia/Gaza Gaza Strip +PS +313200+0350542 Asia/Hebron West Bank +PT +3843-00908 Europe/Lisbon Portugal (mainland) +PT +3238-01654 Atlantic/Madeira Madeira Islands +PT +3744-02540 Atlantic/Azores Azores +PW +0720+13429 Pacific/Palau +PY -2516-05740 America/Asuncion +QA,BH +2517+05132 Asia/Qatar +RO +4426+02606 Europe/Bucharest +RS,BA,HR,ME,MK,SI +4450+02030 Europe/Belgrade +RU +5443+02030 Europe/Kaliningrad MSK-01 - Kaliningrad +RU +554521+0373704 Europe/Moscow MSK+00 - Moscow area +# Mention RU and UA alphabetically. See “territorial claims” above. +RU,UA +4457+03406 Europe/Simferopol Crimea +RU +5836+04939 Europe/Kirov MSK+00 - Kirov +RU +4844+04425 Europe/Volgograd MSK+00 - Volgograd +RU +4621+04803 Europe/Astrakhan MSK+01 - Astrakhan +RU +5134+04602 Europe/Saratov MSK+01 - Saratov +RU +5420+04824 Europe/Ulyanovsk MSK+01 - Ulyanovsk +RU +5312+05009 Europe/Samara MSK+01 - Samara, Udmurtia +RU +5651+06036 Asia/Yekaterinburg MSK+02 - Urals +RU +5500+07324 Asia/Omsk MSK+03 - Omsk +RU +5502+08255 Asia/Novosibirsk MSK+04 - Novosibirsk +RU +5322+08345 Asia/Barnaul MSK+04 - Altai +RU +5630+08458 Asia/Tomsk MSK+04 - Tomsk +RU +5345+08707 Asia/Novokuznetsk MSK+04 - Kemerovo +RU +5601+09250 Asia/Krasnoyarsk MSK+04 - Krasnoyarsk area +RU +5216+10420 Asia/Irkutsk MSK+05 - Irkutsk, Buryatia +RU +5203+11328 Asia/Chita MSK+06 - Zabaykalsky +RU +6200+12940 Asia/Yakutsk MSK+06 - Lena River +RU +623923+1353314 Asia/Khandyga MSK+06 - Tomponsky, Ust-Maysky +RU +4310+13156 Asia/Vladivostok MSK+07 - Amur River +RU +643337+1431336 Asia/Ust-Nera MSK+07 - Oymyakonsky +RU +5934+15048 Asia/Magadan MSK+08 - Magadan +RU +4658+14242 Asia/Sakhalin MSK+08 - Sakhalin Island +RU +6728+15343 Asia/Srednekolymsk MSK+08 - Sakha (E), N Kuril Is +RU +5301+15839 Asia/Kamchatka MSK+09 - Kamchatka +RU +6445+17729 Asia/Anadyr MSK+09 - Bering Sea +SA,AQ,KW,YE +2438+04643 Asia/Riyadh Syowa +SB,FM -0932+16012 Pacific/Guadalcanal Pohnpei +SD +1536+03232 Africa/Khartoum +SG,AQ,MY +0117+10351 Asia/Singapore peninsular Malaysia, Concordia +SR +0550-05510 America/Paramaribo +SS +0451+03137 Africa/Juba +ST +0020+00644 Africa/Sao_Tome +SV +1342-08912 America/El_Salvador +SY +3330+03618 Asia/Damascus +TC +2128-07108 America/Grand_Turk +TD +1207+01503 Africa/Ndjamena +TH,CX,KH,LA,VN +1345+10031 Asia/Bangkok north Vietnam +TJ +3835+06848 Asia/Dushanbe +TK -0922-17114 Pacific/Fakaofo +TL -0833+12535 Asia/Dili +TM +3757+05823 Asia/Ashgabat +TN +3648+01011 Africa/Tunis +TO -210800-1751200 Pacific/Tongatapu +TR +4101+02858 Europe/Istanbul +TW +2503+12130 Asia/Taipei +UA +5026+03031 Europe/Kyiv most of Ukraine +US +404251-0740023 America/New_York Eastern (most areas) +US +421953-0830245 America/Detroit Eastern - MI (most areas) +US +381515-0854534 America/Kentucky/Louisville Eastern - KY (Louisville area) +US +364947-0845057 America/Kentucky/Monticello Eastern - KY (Wayne) +US +394606-0860929 America/Indiana/Indianapolis Eastern - IN (most areas) +US +384038-0873143 America/Indiana/Vincennes Eastern - IN (Da, Du, K, Mn) +US +410305-0863611 America/Indiana/Winamac Eastern - IN (Pulaski) +US +382232-0862041 America/Indiana/Marengo Eastern - IN (Crawford) +US +382931-0871643 America/Indiana/Petersburg Eastern - IN (Pike) +US +384452-0850402 America/Indiana/Vevay Eastern - IN (Switzerland) +US +415100-0873900 America/Chicago Central (most areas) +US +375711-0864541 America/Indiana/Tell_City Central - IN (Perry) +US +411745-0863730 America/Indiana/Knox Central - IN (Starke) +US +450628-0873651 America/Menominee Central - MI (Wisconsin border) +US +470659-1011757 America/North_Dakota/Center Central - ND (Oliver) +US +465042-1012439 America/North_Dakota/New_Salem Central - ND (Morton rural) +US +471551-1014640 America/North_Dakota/Beulah Central - ND (Mercer) +US +394421-1045903 America/Denver Mountain (most areas) +US +433649-1161209 America/Boise Mountain - ID (south), OR (east) +US,CA +332654-1120424 America/Phoenix MST - AZ (most areas), Creston BC +US +340308-1181434 America/Los_Angeles Pacific +US +611305-1495401 America/Anchorage Alaska (most areas) +US +581807-1342511 America/Juneau Alaska - Juneau area +US +571035-1351807 America/Sitka Alaska - Sitka area +US +550737-1313435 America/Metlakatla Alaska - Annette Island +US +593249-1394338 America/Yakutat Alaska - Yakutat +US +643004-1652423 America/Nome Alaska (west) +US +515248-1763929 America/Adak Alaska - western Aleutians +US +211825-1575130 Pacific/Honolulu Hawaii +UY -345433-0561245 America/Montevideo +UZ +3940+06648 Asia/Samarkand Uzbekistan (west) +UZ +4120+06918 Asia/Tashkent Uzbekistan (east) +VE +1030-06656 America/Caracas +VN +1045+10640 Asia/Ho_Chi_Minh south Vietnam +VU -1740+16825 Pacific/Efate +WS -1350-17144 Pacific/Apia +ZA,LS,SZ -2615+02800 Africa/Johannesburg +# +# The next section contains experimental tab-separated comments for +# use by user agents like tzselect that identify continents and oceans. +# +# For example, the comment ‘#@AQAntarctica/’ means the country code +# AQ is in the continent Antarctica regardless of the Zone name, +# so Pacific/Auckland should be listed under Antarctica as well as +# under the Pacific because its line’s country codes include AQ. +# +# If more than one country code is affected each is listed separated +# by commas, e.g., ‘#@IS,SHAtlantic/’. If a country code is in +# more than one continent or ocean, each is listed separated by +# commas, e.g., the second column of ‘#@CY,TRAsia/,Europe/’. +# +# These experimental comments are present only for country codes where +# the continent or ocean is not already obvious from the Zone name. +# For example, there is no such comment for RU since it already +# corresponds to Zone names starting with both ‘Europe/’ and ‘Asia/’. +# +#@AQ Antarctica/ +#@IS,SH Atlantic/ +#@CY,TR Asia/,Europe/ +#@SJ Arctic/ +#@CC,CX,KM,MG,YT Indian/ diff --git a/installer/internal/media/zoneinfo_test.go b/installer/internal/media/zoneinfo_test.go new file mode 100644 index 000000000..50152b7d2 --- /dev/null +++ b/installer/internal/media/zoneinfo_test.go @@ -0,0 +1,81 @@ +package media + +import ( + "strings" + "testing" +) + +func TestWindowsZoneToIANA(t *testing.T) { + cases := map[string]string{ + "W. Europe Standard Time": "Europe/Berlin", + "UTC": "UTC", + "Gibt es nicht": "", + } + for in, want := range cases { + if got := windowsZoneToIANA(in); got != want { + t.Errorf("windowsZoneToIANA(%q) = %q, want %q", in, got, want) + } + } +} + +func TestEveryWindowsZoneIsKnown(t *testing.T) { + zones, _ := embeddedZones() + known := map[string]bool{} + for _, z := range zones { + known[z] = true + } + for _, line := range strings.Split(string(windowsZonesData()), "\n") { + if line == "" || strings.HasPrefix(line, "#") { + continue + } + id, _, _ := strings.Cut(line, "\t") + iana := windowsZoneToIANA(id) + if !known[iana] { + t.Errorf("Windows zone %q maps to %q, which is not in embeddedZones()", id, iana) + } + } +} + +func TestEmbeddedZonesContainBerlinAndUTC(t *testing.T) { + zones, countries := embeddedZones() + var hasBerlin, hasUTC bool + for _, z := range zones { + hasBerlin = hasBerlin || z == "Europe/Berlin" + hasUTC = hasUTC || z == "UTC" + } + if !hasBerlin || !hasUTC { + t.Errorf("embeddedZones() lacks Berlin (%v) or UTC (%v)", hasBerlin, hasUTC) + } + if countries["Europe/Berlin"] != "DE" { + t.Errorf("countries[Europe/Berlin] = %q, want DE", countries["Europe/Berlin"]) + } +} + +func TestKeyboardFromKLID(t *testing.T) { + cases := map[string]string{ + "00000407": "de", + "0000100C": "ch", + "00010409": "us", + "00000419": "", + } + for in, want := range cases { + if got := keyboardFromKLID(in); got != want { + t.Errorf("keyboardFromKLID(%q) = %q, want %q", in, got, want) + } + } +} + +func TestCountryFromLocaleAcceptsDash(t *testing.T) { + cases := map[string]string{ + "de-DE": "DE", + "de_DE.UTF-8": "DE", + "en": "", + "en_001": "", + "sr-Latn-RS": "RS", + } + for in, want := range cases { + if got := countryFromLocale(in); got != want { + t.Errorf("countryFromLocale(%q) = %q, want %q", in, got, want) + } + } +} diff --git a/installer/internal/shell/shell.go b/installer/internal/shell/shell.go index 89ceb7c12..dbda47703 100644 --- a/installer/internal/shell/shell.go +++ b/installer/internal/shell/shell.go @@ -75,6 +75,9 @@ type embeddedWindow interface { // logic without a real display. var newWebview func(url string) (embeddedWindow, error) +// windowReady runs once an embedded window exists, before its event loop starts. +var windowReady = func() {} + // Open shows url in a window and reports which fallback stage answered // (see Mode). For ModeWebview it does not return until the window is // closed -- the caller must have started its HTTP server and be ready to @@ -87,6 +90,7 @@ func Open(url string) (Mode, error) { if newWebview != nil { win, err := newWebview(url) if err == nil { + windowReady() win.Run() win.Destroy() return ModeWebview, nil diff --git a/installer/internal/shell/shell_internal_test.go b/installer/internal/shell/shell_internal_test.go index d74577b96..427c15ee3 100644 --- a/installer/internal/shell/shell_internal_test.go +++ b/installer/internal/shell/shell_internal_test.go @@ -6,6 +6,7 @@ import ( "os" "path/filepath" "runtime" + "strings" "testing" ) @@ -107,3 +108,23 @@ func TestOpenFallsBackToStage4WhenNothingIsOnPath(t *testing.T) { t.Errorf("mode = %v, want ModeURLOnly", mode) } } + +type orderWindow struct{ calls *[]string } + +func (w orderWindow) Run() { *w.calls = append(*w.calls, "run") } +func (w orderWindow) Destroy() { *w.calls = append(*w.calls, "destroy") } + +func TestOpenReportsTheWindowBeforeItRuns(t *testing.T) { + var calls []string + prevWebview, prevReady := newWebview, windowReady + newWebview = func(url string) (embeddedWindow, error) { return orderWindow{&calls}, nil } + windowReady = func() { calls = append(calls, "ready") } + t.Cleanup(func() { newWebview, windowReady = prevWebview, prevReady }) + + if _, err := Open("http://127.0.0.1:1/"); err != nil { + t.Fatalf("Open: %v", err) + } + if got := strings.Join(calls, " "); got != "ready run destroy" { + t.Errorf("calls = %q", got) + } +} diff --git a/installer/internal/shell/webview_windows.go b/installer/internal/shell/webview_windows.go index 0b06ebdec..075eff47c 100644 --- a/installer/internal/shell/webview_windows.go +++ b/installer/internal/shell/webview_windows.go @@ -4,11 +4,16 @@ package shell import ( "errors" + "unsafe" webview2 "github.com/jchv/go-webview2" + "golang.org/x/sys/windows" ) -func init() { newWebview = newEdgeWebview } +func init() { + newWebview = newEdgeWebview + windowReady = releaseOwnConsole +} // newEdgeWebview backs Stufe 1 on Windows via go-webview2, a pure-Go // binding onto the Edge WebView2 runtime (E6). Unlike glaze, New does not @@ -32,3 +37,20 @@ func newEdgeWebview(url string) (embeddedWindow, error) { wv.Navigate(url) return wv, nil } + +var ( + kernel32 = windows.NewLazySystemDLL("kernel32.dll") + procGetConsoleProcessList = kernel32.NewProc("GetConsoleProcessList") + procFreeConsole = kernel32.NewProc("FreeConsole") +) + +// releaseOwnConsole schliesst das Konsolenfenster, das Windows beim Doppelklick nur +// fuer den Installer geoeffnet hat. Aus einer Shell gestartet teilt er sich die +// Konsole mit ihr und behaelt sie. +func releaseOwnConsole() { + var ids [2]uint32 + n, _, _ := procGetConsoleProcessList.Call(uintptr(unsafe.Pointer(&ids[0])), uintptr(len(ids))) + if n == 1 { + _, _, _ = procFreeConsole.Call() + } +} diff --git a/installer/webui/CHANGELOG.md b/installer/webui/CHANGELOG.md index 4dab154b7..e7d018a7d 100644 --- a/installer/webui/CHANGELOG.md +++ b/installer/webui/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## v0.3.4-pre.9 (2026-11-06) +## v0.3.4-pre.10 (2026-11-06) ### Features @@ -13,6 +13,10 @@ - **installer:** The configure screen of the installer shows its services and tuning as modules (#280) (f85e2a6) - **installer:** apply a changed service selection without a full update (#282) (ab11a7a) - **installer:** highlight that the Debian stick needs a network cable (#286) (01a23f2) +- **installer:** show the Windows install paths for the imager (4b4a5c1) +- **installer:** add texts for the running and cancelling write (2fb9672) +- **installer:** add the hint text for small media (b4d7e92) +- **installer:** prepare storage media on Windows (#298) - **installer:** prepare from the package stored on the node (f5b1c87) - **installer:** accept the apply-selection run mode (5dc8abe) - **installer:** offer the package stored on the node as a source (1ac4e7a) @@ -64,6 +68,9 @@ ### Fixes +- **installer:** keep a cancelled write running until the imager has ended (693afe7) +- **installer:** keep the write screen moving and show cancelling (cbfa3ce) +- **installer:** name only known used space and warn about small cards (b502ec8) - **installer:** keep the apply selection button while it runs (5281d56) - **installer:** translate the skip reasons of step 89 (23d333a) - **installer:** show the hotspot credentials after every successful run (bbeac07) @@ -73,8 +80,13 @@ - **webui:** leave space below the drive list and say SD-Karte (96e292e) - **webui:** keep the media hint above the page and the SD card name in one piece (d038b46) +### Refactors + +- **installer:** move the media platform choices behind one file per system (e77c96b) + ### Documentation +- **installer:** name the winget link kind (fe178db) - **installer:** draw the configure modules in the reference draft (ffb05a9) - **installer:** draw the update preview modules in the reference draft (505550a) - **installer:** tighten the media texts and describe the Wi-Fi list (553f296) diff --git a/installer/webui/VERSION b/installer/webui/VERSION index cc85b486c..1c0be1b6d 100644 --- a/installer/webui/VERSION +++ b/installer/webui/VERSION @@ -1 +1 @@ -v0.3.4-pre.9 +v0.3.4-pre.10 diff --git a/installer/webui/catalogs/de.json b/installer/webui/catalogs/de.json index fc69b27df..3b0bf4caf 100644 --- a/installer/webui/catalogs/de.json +++ b/installer/webui/catalogs/de.json @@ -400,9 +400,9 @@ "error.GITHUB_NO_RELEASE": "Es gibt kein veröffentlichtes Paket für die Architektur dieses Geräts.", "error.GITHUB_UNREACHABLE": "GitHub ist nicht erreichbar oder hat die Anfrage abgelehnt.", "error.HOSTKEY_CHANGED": "Das Gerät zeigt einen anderen Host-Schlüssel als beim letzten Mal. Genau davor schützt Trust On First Use. Nicht fortfahren, bevor der Grund geklärt ist.", + "error.HOSTKEY_UNKNOWN": "Der Host-Schlüssel des Geräts ist noch nicht bekannt.", "error.HOTSPOT_PASSWORD_INVALID": "Das Hotspot-Passwort ist ungültig.", "error.HOTSPOT_UNREADABLE": "Die Zugangsdaten des Notfall-Hotspots ließen sich nicht lesen. Das Ergebnis zeigt sie deshalb nicht.", - "error.HOSTKEY_UNKNOWN": "Der Host-Schlüssel des Geräts ist noch nicht bekannt.", "error.JOB_IN_PROGRESS": "Es läuft oder wartet bereits ein Update. Bitte warte, bis es fertig ist.", "error.JOB_STAGING_FAILED": "Der Update-Auftrag konnte nicht angelegt werden.", "error.KEYFILE_UNREADABLE": "Die Schlüsseldatei ließ sich nicht lesen.", @@ -610,35 +610,28 @@ "media.action.another": "Weiteres Medium", "media.action.erase_write": "Löschen und schreiben", "media.action.to_setup": "Weiter zum Einrichten", + "media.debian.class.abort": "Unter 3 GB: zu klein, die Installation bricht ab.", + "media.debian.class.large": "Mehr als 34 GB, groß: Swap-Datei so groß wie der Arbeitsspeicher, höchstens 4 GB.", + "media.debian.class.medium": "8 bis 34 GB, mittel: EFI 512 MB, Swap-Datei 1 GB, Journal 200 MB.", + "media.debian.class.small": "3 bis unter 8 GB, klein: EFI 256 MB oder BIOS-Boot, zram, Journal 50 MB.", + "media.debian.drive.explain": "Der Stick startet auf dem Zielgerät die Debian-Installation, sie schreibt auf die interne Platte des Zielgeräts.", + "media.debian.drive.recommend": "Vorsichtshalber am Zielgerät alle Laufwerke außer der internen Platte abziehen, zum Beispiel USB-Platten, Speicherkarten oder eine zweite Platte. Die Installation fasst nur die interne Platte an.", + "media.debian.drive.title": "USB-Stick für die Installation", + "media.debian.split.disk": "Auf der Platte des Zielgeräts", + "media.debian.split.multi": "Gibt es mehrere interne Platten, bricht die Installation ab, statt zu raten.", + "media.debian.split.stick": "Auf dem Stick", + "media.debian.split.stick_text": "Der Installer. Der Rest des Sticks bleibt ungenutzt.", "media.device.deb-amd64": "x86 64-bit", "media.device.deb-amd64.hint": "z. B. AMD GX-424CC, Intel N100", "media.device.deb-arm64": "ARM 64-bit", "media.device.deb-arm64.hint": "mit UEFI", "media.device.deb-i386": "x86 32-bit", - "media.debian.drive.title": "USB-Stick für die Installation", - "media.debian.drive.explain": "Der Stick startet auf dem Zielgerät die Debian-Installation, sie schreibt auf die interne Platte des Zielgeräts.", - "media.debian.drive.recommend": "Vorsichtshalber am Zielgerät alle Laufwerke außer der internen Platte abziehen, zum Beispiel USB-Platten, Speicherkarten oder eine zweite Platte. Die Installation fasst nur die interne Platte an.", - "media.debian.split.stick": "Auf dem Stick", - "media.debian.split.stick_text": "Der Installer. Der Rest des Sticks bleibt ungenutzt.", - "media.debian.split.disk": "Auf der Platte des Zielgeräts", - "media.debian.class.abort": "Unter 3 GB: zu klein, die Installation bricht ab.", - "media.debian.class.small": "3 bis unter 8 GB, klein: EFI 256 MB oder BIOS-Boot, zram, Journal 50 MB.", - "media.debian.class.medium": "8 bis 34 GB, mittel: EFI 512 MB, Swap-Datei 1 GB, Journal 200 MB.", - "media.debian.class.large": "Mehr als 34 GB, groß: Swap-Datei so groß wie der Arbeitsspeicher, höchstens 4 GB.", - "media.debian.split.multi": "Gibt es mehrere interne Platten, bricht die Installation ab, statt zu raten.", "media.device.pi1": "Pi 1, Zero, Zero W", "media.device.pi2": "Pi 2", "media.device.pi3": "Pi 3, 3+, Zero 2 W", "media.device.pi4": "Pi 4, 400", "media.device.pi5": "Pi 5, 500", "media.device.title": "Für welches Gerät ist die SD-Karte?", - "media.done.foreign": "Unter {host} antwortet ein anderes Gerät.", - "media.done.found": "{host} ist erreichbar.", - "media.done.ip": "IP-Adresse des Geräts", - "media.done.pi.1": "SD-Karte in den Pi stecken, Netzwerkkabel oder WLAN und Strom anschließen.", - "media.done.pi.2": "Der erste Start dauert einige Minuten.", - "media.done.pi.3": "Der Installer sucht {host} und meldet sich, sobald das Gerät erreichbar ist.", - "media.done.debian.title": "Der Stick ist fertig", "media.done.debian.1": "Vorsichtshalber alle Laufwerke außer der internen Platte vom Zielgerät abziehen (USB-Platten, Speicherkarten, zweite Platte). Die Installation fasst nur die interne Platte an.", "media.done.debian.2": "Stick einstecken, Netzwerkkabel anschließen.", "media.done.debian.3": "Vom USB-Stick starten. Das Bootmenü öffnet sich meist mit F12 oder F11.", @@ -648,10 +641,17 @@ "media.done.debian.5": "Danach schaltet sich das Gerät aus. Stick abziehen, bevor du es wieder einschaltest.", "media.done.debian.5.warn": "Bleibt der Stick stecken, startet die Installation erneut.", "media.done.debian.5.warn_noask": "Bleibt der Stick stecken, startet die Installation erneut und löscht die Platte noch einmal.", + "media.done.debian.title": "Der Stick ist fertig", + "media.done.foreign": "Unter {host} antwortet ein anderes Gerät.", + "media.done.found": "{host} ist erreichbar.", + "media.done.ip": "IP-Adresse des Geräts", + "media.done.pi.1": "SD-Karte in den Pi stecken, Netzwerkkabel oder WLAN und Strom anschließen.", + "media.done.pi.2": "Der erste Start dauert einige Minuten.", + "media.done.pi.3": "Der Installer sucht {host} und meldet sich, sobald das Gerät erreichbar ist.", "media.done.slow.boot": "Das Gerät hat den ersten Start noch nicht beendet. Warte noch etwas.", + "media.done.slow.dhcp": "Kein DHCP am Kabel: Das Gerät fragt dann nach Netzwerkeinstellungen.", "media.done.slow.mdns": "Das Netzwerk löst .local-Namen nicht auf. Gib unten die IP-Adresse ein.", "media.done.slow.network": "Das Gerät ist nicht im selben Netzwerk wie dieser Rechner.", - "media.done.slow.dhcp": "Kein DHCP am Kabel: Das Gerät fragt dann nach Netzwerkeinstellungen.", "media.done.slow.title": "Noch keine Antwort", "media.done.title": "Die SD-Karte ist fertig", "media.done.waiting": "Warte auf {host}", @@ -660,20 +660,26 @@ "media.drive.removable": "Wechselmedium", "media.drive.show_internal": "Auch interne Laufwerke anzeigen", "media.drive.show_internal_hint": "Zum Beispiel eine Festplatte, die per SATA angeschlossen ist. Das Laufwerk, von dem dieser Rechner läuft, steht nie in der Liste.", + "media.drive.small_for_setup": "Für die Einrichtung ist dieses Medium knapp. Empfohlen sind mindestens 8 GB.", "media.drive.title": "Welches Laufwerk soll beschrieben werden?", "media.drive.too_small": "zu klein", "media.group.debian": "Andere Hardware (Debian)", "media.group.pi": "Raspberry Pi", "media.imager.missing.text": "Der Installer beschreibt die SD-Karte mit dem Raspberry Pi Imager ab Version 2.0. Installiere ihn über Discover oder von der Webseite und prüfe dann erneut.", + "media.imager.missing.text.windows": "Der Installer beschreibt Speicherkarten und USB-Sticks mit dem Raspberry Pi Imager ab Version 2.0. Lade ihn von der Webseite oder installiere ihn mit winget und prüfe dann erneut.", "media.imager.missing.title": "Der Raspberry Pi Imager fehlt", "media.imager.old.text": "Nötig ist Version 2.0 oder neuer. Aktualisiere ihn über Discover oder von der Webseite und prüfe dann erneut.", + "media.imager.old.text.windows": "Nötig ist Version 2.0 oder neuer. Aktualisiere ihn von der Webseite oder mit winget und prüfe dann erneut.", "media.imager.old.title": "Der Raspberry Pi Imager ist zu alt", "media.layout.boot": "Boot", "media.layout.pi": "Die Systempartition wächst beim ersten Start auf die ganze SD-Karte.", "media.layout.system": "System", "media.layout.title": "So wird die SD-Karte aufgeteilt", + "media.link.copied": "Kopiert", + "media.link.copy": "Befehl kopieren", "media.link.discover": "In Discover öffnen", "media.link.website": "Webseite", + "media.link.winget": "Mit winget installieren", "media.name.invalid": "Nur Kleinbuchstaben, Ziffern und Bindestriche, höchstens 63 Zeichen.", "media.name.ok": "Gültig und im Netz frei", "media.name.taken": "Im Netz schon vergeben. Vorschlag: {name}", @@ -695,6 +701,7 @@ "media.result.download": "Wird geladen", "media.result.offline": "Die Liste der Images ist nicht erreichbar. Prüfe die Internetverbindung.", "media.result.package": "Paket {arch}", + "media.rights.windows": "Windows fragt gleich nach Administratorrechten, damit der Imager schreiben darf.", "media.settings.arm_serial": "ARM-Geräte zeigen die Installation oft nur über eine serielle Konsole und auf Englisch.", "media.settings.ask_erase": "Vor dem Löschen nachfragen", "media.settings.ask_erase_hint": "Das Zielgerät zeigt die gefundene Platte mit Modell und Größe und fragt, ob sie gelöscht werden darf. Ohne Nachfrage läuft die Installation ohne jede Eingabe durch.", @@ -718,9 +725,9 @@ "media.settings.password_mismatch": "Die Passwörter sind verschieden.", "media.settings.password_short": "Mindestens 8 Zeichen.", "media.settings.region": "Region", - "media.settings.ssid": "Netzwerkname", "media.settings.ssh_password": "Auch per SSH mit Passwort anmelden", "media.settings.ssh_password_hint": "Praktisch bei der Fehlersuche. Der Schlüssel des Installers bleibt hinterlegt.", + "media.settings.ssid": "Netzwerkname", "media.settings.system": "System", "media.settings.timezone": "Zeitzone", "media.settings.title": "Einstellungen für das Gerät", @@ -738,7 +745,7 @@ "media.step.write": "Schreiben", "media.tag.experimental": "experimentell", "media.tag.unsupported": "nicht unterstützt", - "media.unsupported.text": "Das Vorbereiten eines Mediums funktioniert vorerst unter Linux. Windows und macOS folgen. Die Anleitung beschreibt, wie sich eine SD-Karte von Hand vorbereiten lässt.", + "media.unsupported.text": "Das Vorbereiten eines Mediums funktioniert vorerst unter Linux und Windows. macOS folgt. Die Anleitung beschreibt, wie sich eine SD-Karte von Hand vorbereiten lässt.", "media.unsupported.title": "Auf diesem System noch nicht verfügbar", "media.warn.confirm_card": "Ich habe verstanden, dass die SD-Karte gelöscht wird.", "media.warn.confirm_debian": "Ich habe verstanden, dass der Stick beschrieben und die interne Platte des Zielgeräts gelöscht wird.", @@ -761,7 +768,9 @@ "media.wifi.scanning": "Suche Netze …", "media.wifi.signal": "Signalstärke {n} von 3", "media.wifi.unknown": "Dieser Rechner kennt kein Passwort für dieses Netz und kann deins deshalb nicht prüfen.", + "media.write.busy": "Läuft seit {time}. Auf langsamen Medien kann der Balken minutenlang stehen.", "media.write.cancel_hint": "Nach einem Abbruch muss das Medium neu geschrieben werden.", + "media.write.cancelling": "Wird abgebrochen. Das Medium wird noch beschrieben, das kann einige Minuten dauern. Bitte noch nicht abziehen.", "media.write.log": "Protokoll", "media.write.remaining": "noch etwa {time}, {rate}/s", "media.write.save_log": "Protokoll speichern", @@ -903,6 +912,10 @@ "result.fail.heading": "Der Lauf ist abgebrochen", "result.fail.summary": "Bei „{step}“ · nach {duration}", "result.fail.summary_nostep": "Nach {duration}", + "result.hotspot.heading": "Notfall-Hotspot", + "result.hotspot.name": "Name", + "result.hotspot.password": "Passwort", + "result.hotspot.text": "Schreib dir das auf. Findet der Node kein Netz, öffnet er nach 5 Minuten diesen Hotspot.", "result.lines.heading": "Letzte Protokollzeilen", "result.lines.text": "Aus dem Schritt, der fehlgeschlagen ist.", "result.ok.heading": "Der Node läuft", @@ -910,10 +923,6 @@ "result.ok.summary_short": "{duration} gebraucht · Paket {version} ({arch})", "result.reach.heading": "Dashboard erreichen", "result.reach.text": "Beide Adressen zeigen auf dasselbe Dashboard.", - "result.hotspot.heading": "Notfall-Hotspot", - "result.hotspot.text": "Schreib dir das auf. Findet der Node kein Netz, öffnet er nach 5 Minuten diesen Hotspot.", - "result.hotspot.name": "Name", - "result.hotspot.password": "Passwort", "result.redeploy.summary": "Paket {from} → {to} · {restarted} · {duration} gebraucht", "result.repair.summary": "{step} erneut ausgeführt · {duration} gebraucht", "result.restarted.one": "{n} Dienst neu gestartet", diff --git a/installer/webui/catalogs/en.json b/installer/webui/catalogs/en.json index f8022ab5c..e7ec02454 100644 --- a/installer/webui/catalogs/en.json +++ b/installer/webui/catalogs/en.json @@ -400,9 +400,9 @@ "error.GITHUB_NO_RELEASE": "There is no published package for this device's architecture.", "error.GITHUB_UNREACHABLE": "GitHub is unreachable or rejected the request.", "error.HOSTKEY_CHANGED": "The device presents a different host key than last time. Trust on first use protects against exactly this. Do not continue until you know why.", + "error.HOSTKEY_UNKNOWN": "The device's host key is not known yet.", "error.HOTSPOT_PASSWORD_INVALID": "The hotspot password is not valid.", "error.HOTSPOT_UNREADABLE": "The emergency hotspot credentials could not be read. The result therefore does not show them.", - "error.HOSTKEY_UNKNOWN": "The device's host key is not known yet.", "error.JOB_IN_PROGRESS": "An update is already running or queued. Please wait until it has finished.", "error.JOB_STAGING_FAILED": "The update job could not be created.", "error.KEYFILE_UNREADABLE": "The key file could not be read.", @@ -610,35 +610,28 @@ "media.action.another": "Another medium", "media.action.erase_write": "Erase and write", "media.action.to_setup": "Continue to setup", + "media.debian.class.abort": "Under 3 GB: too small, the installation stops.", + "media.debian.class.large": "More than 34 GB, large: swap file as large as the RAM, at most 4 GB.", + "media.debian.class.medium": "8 to 34 GB, medium: EFI 512 MB, swap file 1 GB, journal 200 MB.", + "media.debian.class.small": "3 to under 8 GB, small: EFI 256 MB or BIOS boot, zram, journal 50 MB.", + "media.debian.drive.explain": "The stick starts the Debian installation on the target device, which writes to the internal disk of the target device.", + "media.debian.drive.recommend": "Before you start, unplug all drives on the target device except the internal disk, for example USB disks, memory cards or a second disk. The installation only touches the internal disk.", + "media.debian.drive.title": "USB stick for the installation", + "media.debian.split.disk": "On the disk of the target device", + "media.debian.split.multi": "If there are several internal disks, the installation stops instead of guessing.", + "media.debian.split.stick": "On the stick", + "media.debian.split.stick_text": "The installer. The rest of the stick stays unused.", "media.device.deb-amd64": "x86 64-bit", "media.device.deb-amd64.hint": "e.g. AMD GX-424CC, Intel N100", "media.device.deb-arm64": "ARM 64-bit", "media.device.deb-arm64.hint": "with UEFI", "media.device.deb-i386": "x86 32-bit", - "media.debian.drive.title": "USB stick for the installation", - "media.debian.drive.explain": "The stick starts the Debian installation on the target device, which writes to the internal disk of the target device.", - "media.debian.drive.recommend": "Before you start, unplug all drives on the target device except the internal disk, for example USB disks, memory cards or a second disk. The installation only touches the internal disk.", - "media.debian.split.stick": "On the stick", - "media.debian.split.stick_text": "The installer. The rest of the stick stays unused.", - "media.debian.split.disk": "On the disk of the target device", - "media.debian.class.abort": "Under 3 GB: too small, the installation stops.", - "media.debian.class.small": "3 to under 8 GB, small: EFI 256 MB or BIOS boot, zram, journal 50 MB.", - "media.debian.class.medium": "8 to 34 GB, medium: EFI 512 MB, swap file 1 GB, journal 200 MB.", - "media.debian.class.large": "More than 34 GB, large: swap file as large as the RAM, at most 4 GB.", - "media.debian.split.multi": "If there are several internal disks, the installation stops instead of guessing.", "media.device.pi1": "Pi 1, Zero, Zero W", "media.device.pi2": "Pi 2", "media.device.pi3": "Pi 3, 3+, Zero 2 W", "media.device.pi4": "Pi 4, 400", "media.device.pi5": "Pi 5, 500", "media.device.title": "Which device is the card for?", - "media.done.foreign": "Another device answers at {host}.", - "media.done.found": "{host} is reachable.", - "media.done.ip": "IP address of the device", - "media.done.pi.1": "Put the card into the Pi and connect a network cable or Wi-Fi and power.", - "media.done.pi.2": "The first start takes a few minutes.", - "media.done.pi.3": "The installer looks for {host} and reports as soon as the device answers.", - "media.done.debian.title": "The stick is ready", "media.done.debian.1": "To be safe, unplug all drives from the target device except the internal disk (USB disks, memory cards, a second disk). The installation only touches the internal disk.", "media.done.debian.2": "Plug in the stick and connect the network cable.", "media.done.debian.3": "Boot from the USB stick. The boot menu usually opens with F12 or F11.", @@ -648,10 +641,17 @@ "media.done.debian.5": "Then the device switches off. Unplug the stick before you switch it on again.", "media.done.debian.5.warn": "If the stick stays plugged in, the installation starts again.", "media.done.debian.5.warn_noask": "If the stick stays plugged in, the installation starts again and erases the disk once more.", + "media.done.debian.title": "The stick is ready", + "media.done.foreign": "Another device answers at {host}.", + "media.done.found": "{host} is reachable.", + "media.done.ip": "IP address of the device", + "media.done.pi.1": "Put the card into the Pi and connect a network cable or Wi-Fi and power.", + "media.done.pi.2": "The first start takes a few minutes.", + "media.done.pi.3": "The installer looks for {host} and reports as soon as the device answers.", "media.done.slow.boot": "The device has not finished its first start yet. Wait a little longer.", + "media.done.slow.dhcp": "No DHCP on the cable: the device then asks for network settings.", "media.done.slow.mdns": "The network does not resolve .local names. Enter the IP address below.", "media.done.slow.network": "The device is not on the same network as this computer.", - "media.done.slow.dhcp": "No DHCP on the cable: the device then asks for network settings.", "media.done.slow.title": "Still no answer", "media.done.title": "The SD card is ready", "media.done.waiting": "Waiting for {host}", @@ -660,20 +660,26 @@ "media.drive.removable": "removable", "media.drive.show_internal": "Also show internal drives", "media.drive.show_internal_hint": "For example a disk connected by SATA. The drive this computer runs from is never listed.", + "media.drive.small_for_setup": "This medium is tight for the setup. At least 8 GB are recommended.", "media.drive.title": "Which drive should be written?", "media.drive.too_small": "too small", "media.group.debian": "Generic", "media.group.pi": "Raspberry Pi", "media.imager.missing.text": "The installer writes the card with the Raspberry Pi Imager 2.0 or newer. Install it from Discover or from the website, then check again.", + "media.imager.missing.text.windows": "The installer writes memory cards and USB sticks with Raspberry Pi Imager 2.0 or newer. Download it from the website or install it with winget, then check again.", "media.imager.missing.title": "The Raspberry Pi Imager is missing", "media.imager.old.text": "Version 2.0 or newer is needed. Update it from Discover or from the website, then check again.", + "media.imager.old.text.windows": "Version 2.0 or newer is needed. Update it from the website or with winget, then check again.", "media.imager.old.title": "The Raspberry Pi Imager is too old", "media.layout.boot": "Boot", "media.layout.pi": "The system partition grows to the whole card on first start.", "media.layout.system": "System", "media.layout.title": "How the card is divided", + "media.link.copied": "Copied", + "media.link.copy": "Copy command", "media.link.discover": "Open in Discover", "media.link.website": "Website", + "media.link.winget": "Install with winget", "media.name.invalid": "Use lowercase letters, digits and hyphens, up to 63 characters.", "media.name.ok": "Valid and free on the network", "media.name.taken": "Already taken on the network. Suggestion: {name}", @@ -695,6 +701,7 @@ "media.result.download": "Will be downloaded", "media.result.offline": "The list of images cannot be reached. Check the internet connection.", "media.result.package": "Package {arch}", + "media.rights.windows": "Windows will ask for administrator rights so the imager can write.", "media.settings.arm_serial": "ARM devices often show the installation only on a serial console, and in English.", "media.settings.ask_erase": "Ask before erasing", "media.settings.ask_erase_hint": "The target device shows the disk it found, with model and size, and asks whether it may be erased. Without this question, the installation runs through without any input.", @@ -718,9 +725,9 @@ "media.settings.password_mismatch": "The passwords differ.", "media.settings.password_short": "At least 8 characters.", "media.settings.region": "Region", - "media.settings.ssid": "Network name", "media.settings.ssh_password": "Also allow SSH login with the password", "media.settings.ssh_password_hint": "Handy for debugging. The installer's key stays in place.", + "media.settings.ssid": "Network name", "media.settings.system": "System", "media.settings.timezone": "Time zone", "media.settings.title": "Settings for the device", @@ -738,7 +745,7 @@ "media.step.write": "Write", "media.tag.experimental": "experimental", "media.tag.unsupported": "not supported", - "media.unsupported.text": "Preparing a medium works on Linux for now. Windows and macOS follow. The guide describes how to prepare a card by hand.", + "media.unsupported.text": "Preparing a medium works on Linux and Windows for now. macOS follows. The guide describes how to prepare a card by hand.", "media.unsupported.title": "Not available on this system yet", "media.warn.confirm_card": "I understand that the card will be erased.", "media.warn.confirm_debian": "I understand that the stick will be written and the internal disk of the target device erased.", @@ -761,7 +768,9 @@ "media.wifi.scanning": "Looking for networks …", "media.wifi.signal": "Signal strength {n} of 3", "media.wifi.unknown": "This computer knows no password for this network, so it cannot check yours.", + "media.write.busy": "Running for {time}. On slow media the bar can stand still for minutes.", "media.write.cancel_hint": "After cancelling, the medium has to be written again.", + "media.write.cancelling": "Cancelling. The medium is still being written, which can take a few minutes. Please do not remove it yet.", "media.write.log": "Log", "media.write.remaining": "about {time} left, {rate}/s", "media.write.save_log": "Save log", @@ -903,6 +912,10 @@ "result.fail.heading": "The run stopped", "result.fail.summary": "At “{step}” · after {duration}", "result.fail.summary_nostep": "After {duration}", + "result.hotspot.heading": "Emergency hotspot", + "result.hotspot.name": "Name", + "result.hotspot.password": "Password", + "result.hotspot.text": "Write this down. If the node finds no network, it opens this hotspot after 5 minutes.", "result.lines.heading": "Last log lines", "result.lines.text": "From the step that failed.", "result.ok.heading": "The node is running", @@ -910,10 +923,6 @@ "result.ok.summary_short": "{duration} taken · package {version} ({arch})", "result.reach.heading": "Reach the dashboard", "result.reach.text": "Both addresses lead to the same dashboard.", - "result.hotspot.heading": "Emergency hotspot", - "result.hotspot.text": "Write this down. If the node finds no network, it opens this hotspot after 5 minutes.", - "result.hotspot.name": "Name", - "result.hotspot.password": "Password", "result.redeploy.summary": "Package {from} → {to} · {restarted} · {duration} taken", "result.repair.summary": "{step} run again · {duration} taken", "result.restarted.one": "{n} service restarted", diff --git a/installer/webui/cmd/fakehost/main.go b/installer/webui/cmd/fakehost/main.go index fbc7fab02..39a96e8af 100644 --- a/installer/webui/cmd/fakehost/main.go +++ b/installer/webui/cmd/fakehost/main.go @@ -51,7 +51,12 @@ func main() { deltaFails := flag.Bool("delta-verify-fails", false, "die Teilübertragung besteht die Prüfung nicht: Vorbereiten scheitert, bis das ganze Paket neu übertragen wird") packageOffline := flag.String("package-offline", "", "diese Pakete lassen sich nicht herunterladen, Format caddy[,tailscale]: Vorbereiten fragt, bis je Paket geantwortet ist") diagnoseDelay := flag.Duration("diagnose-delay", 0, "Pause zwischen den Abschnitten der Diagnose im Strom, apt wartet das Achtfache (0: die Diagnose kommt auf einmal)") + mediaPlatform := flag.String("media-platform", "", "Plattform des Mediums: windows (Webseite und winget-Befehl) oder leer fuer Linux") + mediaImagerMissing := flag.Bool("media-imager-missing", false, "kein Raspberry Pi Imager gefunden: die Fehlerkarte erscheint") flag.Parse() + if *mediaPlatform != "" && *mediaPlatform != "windows" { + log.Fatalf("-media-platform: %q ist unbekannt, erlaubt sind windows oder leer", *mediaPlatform) + } // Den Updater gibt es nur im Dashboard: das Szenario bringt den Wirt mit. if *scenario == "updater" { *dashboard = true @@ -61,7 +66,7 @@ func main() { if err != nil { log.Fatal(err) } - opts := options{dashboard: *dashboard, trusted: *trusted, holdStep: *hold, stepDelay: *delay, systemUpdates: *systemUpdates, nodePackage: *nodePackage, abiMismatch: *abiMismatch, deltaVerifyFails: *deltaFails, packageOffline: splitPackageList(*packageOffline), english: *language == "en", diagnoseDelay: *diagnoseDelay} + opts := options{mediaPlatform: *mediaPlatform, mediaImagerMissing: *mediaImagerMissing, dashboard: *dashboard, trusted: *trusted, holdStep: *hold, stepDelay: *delay, systemUpdates: *systemUpdates, nodePackage: *nodePackage, abiMismatch: *abiMismatch, deltaVerifyFails: *deltaFails, packageOffline: splitPackageList(*packageOffline), english: *language == "en", diagnoseDelay: *diagnoseDelay} if *failStep != "" { opts.failStep, opts.failCode = splitFailSpec(*failStep) } diff --git a/installer/webui/cmd/fakehost/scenario.go b/installer/webui/cmd/fakehost/scenario.go index 04c5b5892..97a6fc838 100644 --- a/installer/webui/cmd/fakehost/scenario.go +++ b/installer/webui/cmd/fakehost/scenario.go @@ -20,11 +20,15 @@ const fingerprint = "SHA256:xK9v+Lm2Qd8pR4tN1wZa7YcB3fH6jE0sU5gV2nP8kQo" type options struct { dashboard bool - trusted bool - holdStep string - failStep string - failCode string - stepDelay time.Duration + // mediaPlatform: die Plattform des Mediums, "windows" oder leer (Linux). + mediaPlatform string + // mediaImagerMissing: kein Raspberry Pi Imager gefunden. + mediaImagerMissing bool + trusted bool + holdStep string + failStep string + failCode string + stepDelay time.Duration // english: die Log-Zeilen der Attrappe auf Englisch (--lang en). Ein // echter Node meldet sie aus den Skripten, deutsch; die Attrappe zeigt sie // fuer die Dokumentation in der Sprache des Fensters. @@ -371,6 +375,10 @@ func strptr(s string) *string { return &s } func newScenario(name string, opts options) *stagedBackend { fake := hostapitest.NewFake() + fake.MediaPlatform = opts.mediaPlatform + if opts.mediaImagerMissing { + fake.MediaStatusView.Imager = hostapi.MediaImagerStatus{} + } // updater ist vorlage-update so, wie der Updater des Dashboards // (dashboard/internal/updaterhost) den Lauf schreibt: nur gewaehlte // Schritte stehen im Auftrag. Abgewaehlte melden gar nichts, auch der diff --git a/installer/webui/hostapi/hostapitest/fake.go b/installer/webui/hostapi/hostapitest/fake.go index 3a344ec38..9bf3e42f8 100644 --- a/installer/webui/hostapi/hostapitest/fake.go +++ b/installer/webui/hostapi/hostapitest/fake.go @@ -108,7 +108,10 @@ type FakeBackend struct { // Rechnernamen, MediaWriteErr laesst den Start scheitern und // LastMediaWrite haelt den letzten Auftrag. Den Verlauf des Auftrags // steuern die unexportierten Felder (siehe fake_media.go). - MediaStatusView hostapi.MediaStatus + MediaStatusView hostapi.MediaStatus + // MediaPlatform waehlt die Plattform des Status: "windows" liefert die + // Links von Windows, leer oder "linux" die Vorgabe aus MediaStatusView. + MediaPlatform string MediaCatalogView hostapi.MediaCatalog MediaDriveList []hostapi.MediaDrive MediaTaken map[string]bool diff --git a/installer/webui/hostapi/hostapitest/fake_media.go b/installer/webui/hostapi/hostapitest/fake_media.go index f9e176506..215dd903a 100644 --- a/installer/webui/hostapi/hostapitest/fake_media.go +++ b/installer/webui/hostapi/hostapitest/fake_media.go @@ -190,11 +190,20 @@ func mediaDriveFixture() []hostapi.MediaDrive { } } -// MediaStatus liefert die Vorgaben der Attrappe. +// MediaStatus liefert die Vorgaben der Attrappe. Mit MediaPlatform "windows" +// stehen Webseite und winget-Befehl in den Links, wie auf dem echten Host. func (f *FakeBackend) MediaStatus(ctx context.Context) (hostapi.MediaStatus, error) { f.mu.Lock() defer f.mu.Unlock() - return f.MediaStatusView, nil + status := f.MediaStatusView + if f.MediaPlatform == "windows" { + status.Platform = "windows" + status.Links = []hostapi.MediaLink{ + {Kind: "website", URL: "https://www.raspberrypi.com/software/"}, + {Kind: "winget", Command: "winget install -e --id RaspberryPiFoundation.RaspberryPiImager"}, + } + } + return status, nil } // MediaCatalog liefert die Geraeteliste der Attrappe. diff --git a/installer/webui/hostapi/media.go b/installer/webui/hostapi/media.go index ae9286790..04b22e557 100644 --- a/installer/webui/hostapi/media.go +++ b/installer/webui/hostapi/media.go @@ -32,10 +32,11 @@ const ( const maxMediaBody = 64 << 10 // MediaLink ist ein Verweis auf den Imager: kind ist "discover" (der -// App-Store) oder "website". +// App-Store), "website" oder "winget" (nur Command, keine URL). type MediaLink struct { - Kind string `json:"kind"` - URL string `json:"url"` + Kind string `json:"kind"` + URL string `json:"url"` + Command string `json:"command,omitempty"` } // MediaImagerStatus beschreibt den gefundenen Raspberry Pi Imager. @@ -195,6 +196,7 @@ type MediaJob struct { BytesDone int64 `json:"bytes_done"` BytesTotal int64 `json:"bytes_total"` Rate int64 `json:"rate"` + Cancelling bool `json:"cancelling"` Error *ErrorView `json:"error"` Log []string `json:"log"` Target *MediaTarget `json:"target"` diff --git a/installer/webui/static/css/screens.css b/installer/webui/static/css/screens.css index 9db3dc130..4ed542488 100644 --- a/installer/webui/static/css/screens.css +++ b/installer/webui/static/css/screens.css @@ -551,6 +551,9 @@ .media-notice-t{font-size:.84rem;font-weight:600;color:var(--text-strong)} .media-notice-s{font-size:.78rem;line-height:1.45;color:var(--text-muted)} .media-notice-actions{display:flex;flex-wrap:wrap;gap:.5rem;margin-top:.5rem} +.media-link-cmd{display:flex;flex-wrap:wrap;align-items:center;gap:.4rem .6rem;margin-top:.2rem} +.media-link-cmd-t{flex:0 0 100%;font-size:.78rem;color:var(--text-muted)} +.media-cmd{flex:1 1 12rem;min-width:0;padding:.35rem .5rem;border-radius:var(--radius-sm);border:1px solid var(--border-soft);background:var(--sunken);font-size:.74rem;line-height:1.4;color:var(--text-strong);white-space:normal;overflow-wrap:anywhere;user-select:all} .media-cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(18rem,1fr));gap:1rem;align-items:start} .media-row2{display:grid;grid-template-columns:1fr 1fr;gap:.7rem} .media-field{margin-bottom:.8rem} @@ -659,6 +662,7 @@ button.media-erase:hover:not(:disabled){background:var(--bad-bg);border-color:va .media-steps{list-style:none;margin:.6rem 0 0;padding:0} .media-step{display:flex;align-items:center;gap:.6rem;padding:.35rem 0;font-size:.84rem;color:var(--text-muted)} .media-step--done{color:var(--text)} +.media-step-note{display:block;margin-top:.15rem;font-size:.74rem;line-height:1.4;color:var(--text-muted)} .media-step--active{color:var(--text-strong);font-weight:600} .media-step--failed{color:var(--bad)} .media-step-ic{flex:none;display:inline-flex;align-items:center;justify-content:center;width:1.1rem;height:1.1rem} @@ -673,6 +677,9 @@ button.media-erase:hover:not(:disabled){background:var(--bad-bg);border-color:va .media-bar{height:.5rem;margin-top:.9rem;border-radius:999px;background:var(--track);overflow:hidden} .media-bar-fill{display:block;height:100%;background:var(--accent);transition:width .4s var(--ease)} @media (prefers-reduced-motion:reduce){.media-bar-fill{transition:none}} +.media-bar--busy .media-bar-fill{background-image:linear-gradient(110deg,transparent 35%,rgba(255,255,255,.45) 50%,transparent 65%);background-size:200% 100%;animation:media-bar-busy 1.6s linear infinite} +@keyframes media-bar-busy{from{background-position:150% 0}to{background-position:-50% 0}} +@media (prefers-reduced-motion:reduce){.media-bar--busy .media-bar-fill{animation:none;background-image:none}} .media-log{margin-top:.9rem} .media-log summary{cursor:pointer;font-size:.8rem;color:var(--text-subtle)} .media-log-body{max-height:14rem;overflow:auto;margin:.5rem 0;padding:.5rem .6rem;border-radius:var(--radius-sm);background:var(--sunken);font-size:.72rem;line-height:1.45;white-space:pre-wrap;color:var(--text-muted)} diff --git a/installer/webui/static/js/media-model.js b/installer/webui/static/js/media-model.js index dea60425c..2ea4813de 100644 --- a/installer/webui/static/js/media-model.js +++ b/installer/webui/static/js/media-model.js @@ -65,6 +65,9 @@ var WAIT_PI = 10 * 60 * 1000; var WAIT_DEBIAN = 30 * 60 * 1000; + // Ohne neue Werte fuer diese Zeit gilt die Restzeit nicht mehr. + var STALL_MS = 15000; + // Die Ersatzschritte, wenn der Server keine schickt. Pi richtet die Einstellungen // mit dem Imager ein, Debian legt sie beim Umbau des Images ab (patch). var STEPS_PI = ['download', 'checksum', 'rights', 'write', 'verify', 'customize', 'eject']; @@ -371,6 +374,27 @@ return Math.max(0, Math.round((job.bytes_total - job.bytes_done) / job.rate)); }, + // writeStatus: die Zeile unter dem Balken beim Schreiben und Nachpruefen. + // sinceChange: Millisekunden seit sich Schritt oder Prozent geaendert + // haben, stepAge: seit Beginn des Schritts. Solange Werte kommen, zaehlt + // die Restzeit herunter, danach laeuft eine Uhr. null in anderen Schritten. + writeStatus: function (job, sinceChange, stepAge) { + var active = ((job && job.steps) || []).find(function (step) { + return step.state === 'active'; + }); + if (!active || (active.id !== 'write' && active.id !== 'verify')) { + return null; + } + var left = window.MediaModel.remaining(job); + if (left !== null && sinceChange < STALL_MS) { + var rest = left - Math.floor(sinceChange / 1000); + if (rest > 0) { + return { key: 'media.write.remaining', seconds: rest }; + } + } + return { key: 'media.write.busy', seconds: Math.floor(stepAge / 1000) }; + }, + // remembered: was der Rechner fuer das naechste Medium behaelt. Keine // Passwoerter und kein WLAN-Land, das folgt der Zeitzone. remembered: function (s) { diff --git a/installer/webui/static/js/screen-media.js b/installer/webui/static/js/screen-media.js index bdd6653e3..aaa5129da 100644 --- a/installer/webui/static/js/screen-media.js +++ b/installer/webui/static/js/screen-media.js @@ -10,6 +10,8 @@ var WRITE_POLL = 500; var DONE_CLOCK = 1000; var DONE_POLL = 5000; + // Unter dieser Groesse wird es beim Einrichten eines Pi eng (Karten "8 GB" haben gut 7,5 Milliarden Byte). + var SETUP_MIN_BYTES = 7e9; // DEVICE_HINTS: die Zeile unter dem Namen einer Debian-Zeile. var DEVICE_HINTS = { 'deb-amd64': 'media.device.deb-amd64.hint', 'deb-arm64': 'media.device.deb-arm64.hint' }; @@ -23,6 +25,11 @@ // alt, imagerKey ist 'missing' oder 'old'), 'failed' oder 'ready'. state: '', imagerKey: '', + // platform: 'linux' oder 'windows' aus dem Status. Bestimmt die Texte der Karte. + platform: 'linux', + // copied: die Art des Links, dessen Befehl eben kopiert wurde (2 s). + copied: '', + copyTimer: null, links: [], devices: [], groups: [], @@ -48,6 +55,8 @@ return; } this.links = status.links || []; + this.platform = status.platform || 'linux'; + this.shell.shared.mediaPlatform = this.platform; if (!status.supported) { this.state = 'unsupported'; return; @@ -73,6 +82,31 @@ return this.load(); }, + // imagerTextKey: der Text der Karte. Off Linux ein eigener Schluessel mit Plattformsuffix. + get imagerTextKey() { + return 'media.imager.' + this.imagerKey + '.text' + (this.platform === 'linux' ? '' : '.' + this.platform); + }, + + // copyCommand: den Befehl in die Zwischenablage. Ohne Zwischenablage oder + // bei Ablehnung bleibt der Befehl markierbar und es erscheint kein Kopiert. + async copyCommand(link) { + try { + if (!window.navigator.clipboard || !window.navigator.clipboard.writeText) { + return; + } + await window.navigator.clipboard.writeText(link.command); + } catch (err) { + return; + } + var self = this; + this.copied = link.kind; + window.clearTimeout(this.copyTimer); + this.copyTimer = window.setTimeout(function () { + self.copied = ''; + self.copyTimer = null; + }, 2000); + }, + get device() { var id = this.picked; return this.devices.find(function (item) { @@ -668,6 +702,11 @@ return this.group === 'pi' && !!this.selectedDrive; }, + get tightForSetup() { + var drive = this.selectedDrive; + return this.group === 'pi' && !!drive && drive.size < SETUP_MIN_BYTES; + }, + fits(drive) { return !this.limit || drive.size >= this.limit; }, @@ -689,8 +728,10 @@ }, partitionText(part) { - var used = window.Format.megabytes(part.used, this.shell.lang); - return [part.label || part.name, part.fstype, this.shell.t('media.warn.used', { size: used })].filter(Boolean).join(', '); + var used = part.used > 0 + ? this.shell.t('media.warn.used', { size: window.Format.megabytes(part.used, this.shell.lang) }) + : ''; + return [part.label || part.name, part.fstype, used].filter(Boolean).join(', '); }, pick(path) { @@ -761,6 +802,12 @@ timer: null, // group: 'pi' oder 'debian', bestimmt die Ersatzschritte. group: '', + // Zeitpunkte der letzten Aenderung, fuer die Zeile unter dem Balken. + now: 0, + changedAt: 0, + stepAt: 0, + mark: '', + stepId: '', get shell() { return window.Installer.shell; @@ -787,21 +834,58 @@ }); }, + // platform: 'linux' oder 'windows', vom Geraet-Bildschirm gemerkt. + get platform() { + return this.shell.shared.mediaPlatform || 'linux'; + }, + get percent() { return this.job ? Math.max(0, Math.min(100, this.job.percent || 0)) : 0; }, get remainingText() { - var seconds = window.MediaModel.remaining(this.job); - if (seconds === null) { + if (!this.running || this.cancelling) { + return ''; + } + var status = window.MediaModel.writeStatus(this.job, this.now - this.changedAt, this.now - this.stepAt); + if (!status) { return ''; } - return this.shell.t('media.write.remaining', { - time: window.Format.elapsed(seconds * 1000), + return this.shell.t(status.key, { + time: window.Format.elapsed(status.seconds * 1000), rate: window.Format.megabytes(this.job.rate, this.shell.lang), }); }, + // cancelling: der Abbruch ist verlangt, der Imager laeuft noch. + get cancelling() { + return this.running && !!(this.job && this.job.cancelling); + }, + + // rightsNote: der Hinweis auf die Abfrage von Windows, solange sie noch kommt oder offen ist. + rightsNote(row) { + return row.id === 'rights' && this.platform === 'windows' && (row.state === 'pending' || row.state === 'active'); + }, + + // track: merkt sich, wann sich Schritt und Prozent zuletzt geaendert haben. + track(job) { + var now = Date.now(); + var active = (job.steps || []).find(function (step) { + return step.state === 'active'; + }); + var stepId = active ? active.id : ''; + var mark = stepId + ':' + job.percent; + if (stepId !== this.stepId) { + this.stepId = stepId; + this.stepAt = now; + } + if (mark !== this.mark) { + this.mark = mark; + this.changedAt = now; + } + this.now = now; + }, + get log() { return this.job && this.job.log ? this.job.log : []; }, @@ -812,6 +896,8 @@ var media = this.shell.shared.media; this.failed = false; this.job = null; + this.mark = ''; + this.stepId = ''; try { await window.Api.post('/api/media/write', { device: media.device, @@ -846,6 +932,7 @@ return; } this.job = job; + this.track(job); if (job.state === 'idle' || job.state === 'running') { return; } diff --git a/installer/webui/templates/screen-media.html b/installer/webui/templates/screen-media.html index aad5e7089..b2f7900af 100644 --- a/installer/webui/templates/screen-media.html +++ b/installer/webui/templates/screen-media.html @@ -21,10 +21,21 @@ {{template "icon-warn"}} - + + @@ -395,6 +406,10 @@

+
+ +
-
+
-