windows: a terminal waits for magpie, through a magpie.com beside the app (#3737)

The Windows app is linked with -H windowsgui so a double click opens no
console, and PowerShell and cmd don't wait for a GUI program. The prompt
came back before magpie printed, and `magpie plugin login`'s password
keys went to the shell as well as to magpie (tom047784 / TomXPRIME on
Discord, 10-27; the handle error in the same report was 9298d2a).

A shell looks for `magpie` by PATHEXT, which lists .COM before .EXE. So
magpie now writes magpie.com beside the app. It is a 1.9MB console program
(internal/update/launcher), built and embedded by `make release-windows`
(the comlauncher tag). The shell waits for it. It runs the app with its own
std handles, passes MAGPIE_COM=1, waits, and exits with the app's code. The
app keeps those handles and borrows the console for the streams Windows
dropped (a GUI child gets no console handles), so redirection, pipes and
hidden prompts work. A command that opens the window (none, app, gui, tray,
panel, -Embedding, magpie: links) is started DETACHED, and the shell isn't
held. A double click and the Start menu still open magpie.exe.

Why this, and not a console-subsystem copy or a magpie-cli.exe: the
running process is still magpie.exe, so autostart, shortcuts, relaunch and
every os.Executable() use are unchanged. There is no new release asset (still
16), and magpie-releases needs no change. The trailer names the app, so a
download kept as magpie-windows-amd64.exe is run by its own name.

Where it is written:
- Settings › Command line's Add (cliPlace) writes it instead of magpie.cmd
  in a build that carries it.
- A terminal command run as magpie.exe writes it when the folder is on PATH
  or has a magpie.com or magpie.cmd, so existing users get it on their next
  `magpie <cmd>`.
- The app's start (placeExe) writes it again when the bytes differ, so an
  update brings it along.
- A running magpie.com is moved aside and cleared on the next run.
- A copy beside a magpie.exe leaves `magpie` to it (comOwner).
- The Command line row reads magpie.com as this app, with "(which runs
  magpie.exe)".

Run, at 2e165fe9d (main since then touches none of these files):
- gofmt -l: clean
- go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...
- go build for darwin, linux -tags nogui and windows
- make release-windows: amd64 and arm64 are PE subsystem 2 (GUI), as before
- go test -tags nogui -count=1 -timeout 45m ./internal/update/...
  ./internal/cli/ ./internal/gui/ ./internal/proc/: all ok
- cli-path.test.cjs in chromium and webkit (11 + 11 pass); i18n-keys,
  gui-zh-tw, gui-ja, gui-de pass
- The Windows box, with GOOS=windows test binaries: launcher's TestArgsOf,
  TestOpensWindow and TestTargetName pass; update's TestWriteCom,
  TestComOwner, TestEnsureCompanion, TestFindCLIPrefersCom and
  TestCLIShim pass. TestComMagicIsTheLaunchers reads the source, so it
  can't run from a copied binary there; it passes on macOS.
- The Windows box, sandbox HOME, release build, interactive ConPTY over
  ssh -tt with typed keys:
  - Old v0.1.1675 in PowerShell 7.5.4: the prompt comes back before
    "magpie 0.1.1675", $LASTEXITCODE is empty, `> out.txt` is empty, and
    backup's passphrase is split between the shell and magpie.
  - New build in PowerShell 7.5.4: the first `magpie` as magpie.exe wrote
    magpie.com, and Get-Command then resolves it. `magpie version` prints
    before the next line, with exit 0. A bad command gives 1. `> out.txt`
    holds the version. backup reads "Passphrase for the backup:" and
    "Again:" typed. restore reads "Passphrase:" typed. A piped passphrase
    is read (wrong passphrase, exit 1).
  - New build in cmd: `where` lists magpie.com first. The same version,
    ERRORLEVEL 0 and 1, and typed backup and restore passphrases work.
    Ctrl+C at a prompt ends it with 0xC000013A and leaves no magpie.exe.
  - The update: an older magpie.com in place was moved aside and rewritten
    by the first command of the new build, and the .old was gone after the
    next one.

Broken by hand, red:
- writeCom always rewriting: TestWriteCom
- EnsureCompanion ignoring PATH: TestEnsureCompanion
- comOwner always true: TestComOwner
- app.js's old shim-only condition: the "magpie.com is said to run the app"
  case in en and zh

Not tried:
- A real double click or the Start menu on the box. magpie.exe is still
  GUI-subsystem and is what they open, but no window was opened there. The
  sandbox app would share the gateway's port with the box's own magpie.
- Windows Terminal itself; the ConPTY ssh -tt gives is what it uses.
- The arm64 build on a real ARM machine.
- The full go test ./... at this head. Another session's agent and
  gateway suite was running on the machine (load ~115), so only the
  touched packages and internal/proc ran.
This commit is contained in:
yetone
2026-10-27 12:08:16 +08:00
parent 19dc5b9252
commit 2afacd7d18
16 changed files with 658 additions and 28 deletions
+1
View File
@@ -6,3 +6,4 @@
/rsrc_windows_*.syso
/magpie-dev-backend
/magpie-dev.new
/internal/update/launcher-*.com
+7 -4
View File
@@ -101,7 +101,9 @@ release-cli:
# The desktop app for Windows: the system WebView2 needs no cgo, so both
# arches cross-compile. Linked as a GUI program (no console window), with
# the icon, version and a DPI-aware manifest from build/windows.
# the icon, version and a DPI-aware manifest from build/windows. It carries
# magpie.com, the console program a terminal runs for `magpie` and waits
# for, which it writes beside itself (internal/update/com.go, #3737).
WINVER = $(shell echo $(VERSION) | sed -E 's/^v//; s/[^0-9.].*//')
release-windows:
@mkdir -p dist
@@ -109,8 +111,9 @@ release-windows:
--file-version "$(or $(WINVER),0.0.0)" --product-version "$(or $(WINVER),0.0.0)"
@for arch in amd64 arm64; do \
echo " windows/$$arch (app)"; \
CGO_ENABLED=0 GOOS=windows GOARCH=$$arch go build -tags production -trimpath -ldflags="$(LDFLAGS) -H windowsgui" -o dist/magpie-windows-$$arch.exe . || exit 1; \
done; rm -f rsrc_windows_*.syso
CGO_ENABLED=0 GOOS=windows GOARCH=$$arch go build -trimpath -ldflags="-s -w" -o internal/update/launcher-$$arch.com ./internal/update/launcher || exit 1; \
CGO_ENABLED=0 GOOS=windows GOARCH=$$arch go build -tags production,comlauncher -trimpath -ldflags="$(LDFLAGS) -H windowsgui" -o dist/magpie-windows-$$arch.exe . || exit 1; \
done; rm -f rsrc_windows_*.syso internal/update/launcher-*.com
# The desktop app for Linux links GTK 3 and WebKitGTK 4.1 through cgo, so it
# is built natively, one arch per machine.
@@ -120,7 +123,7 @@ release-linux:
@go build -tags "$(TAGS)" -trimpath -ldflags="$(LDFLAGS)" -o dist/magpie-linux-$(shell go env GOARCH) .
clean:
rm -rf magpie magpie.exe magpie.app dist rsrc_windows_*.syso
rm -rf magpie magpie.exe magpie.app dist rsrc_windows_*.syso internal/update/launcher-*.com
# Development: the UI is served from internal/gui/assets and the window
# reloads itself when a file there is saved. With fswatch installed, the
+64 -10
View File
@@ -5,6 +5,7 @@ import (
"syscall"
"github.com/charmbracelet/lipgloss"
"github.com/yetone/magpie/internal/update"
)
// The desktop build is linked as a GUI program so double-clicking it opens
@@ -12,29 +13,82 @@ import (
// is run from a terminal with a command, borrow that terminal's console so
// `magpie ls` and friends still print. Output that is redirected already has
// somewhere to go and is left alone.
//
// magpie.com, the console program a terminal runs for `magpie` (#3737,
// update.EnsureCompanion), hands over its own standard handles, redirected
// or the terminal's, and says so in update.ComEnv: they are kept, and its
// console is borrowed too, so Ctrl+C, a hidden prompt and the programs
// magpie starts have it. The variable is taken out of the environment, so
// what magpie starts doesn't read it as its own.
func init() {
fromCom := os.Getenv(update.ComEnv) != ""
if fromCom {
os.Unsetenv(update.ComEnv)
}
if len(os.Args) < 2 {
return
}
attach := syscall.NewLazyDLL("kernel32.dll").NewProc("AttachConsole")
const attachParentProcess = ^uintptr(0) // (DWORD)-1
if fromCom {
if r, _, _ := attach.Call(attachParentProcess); r != 0 {
// Windows doesn't give a GUI program the console handles
// it was started with, only the redirected ones: those
// left out are the console's own, set as it is attached
for _, std := range []struct {
f **os.File
n int
was syscall.Handle
name string
}{
{&os.Stdin, syscall.STD_INPUT_HANDLE, syscall.Stdin, "/dev/stdin"},
{&os.Stdout, syscall.STD_OUTPUT_HANDLE, syscall.Stdout, "/dev/stdout"},
{&os.Stderr, syscall.STD_ERROR_HANDLE, syscall.Stderr, "/dev/stderr"},
} {
if t, err := syscall.GetFileType(std.was); err == nil && t != 0 {
continue
}
if h, err := syscall.GetStdHandle(std.n); err == nil && h != 0 && h != syscall.InvalidHandle {
*std.f = os.NewFile(uintptr(h), std.name)
}
}
pointStyles(os.Stdout)
}
companion()
return
}
if t, err := syscall.GetFileType(syscall.Stdout); err == nil && t != 0 {
return // FILE_TYPE_UNKNOWN is 0: nothing attached
}
const attachParentProcess = ^uintptr(0) // (DWORD)-1
r, _, _ := syscall.NewLazyDLL("kernel32.dll").NewProc("AttachConsole").Call(attachParentProcess)
if r == 0 {
if r, _, _ := attach.Call(attachParentProcess); r == 0 {
return
}
if out, err := os.OpenFile("CONOUT$", os.O_RDWR, 0); err == nil {
os.Stdout, os.Stderr = out, out
// lipgloss's default renderer was made over the os.Stdout before
// this, a handle that is no terminal, so every style would print
// without colour. The styles made at package init hold that
// renderer, so it is pointed at the console in place. Anything
// else that reads or writes the standard streams takes os.Stdin,
// os.Stdout or os.Stderr when it runs, never in a package variable.
lipgloss.DefaultRenderer().SetOutput(lipgloss.NewRenderer(out).Output())
pointStyles(out)
}
if in, err := os.OpenFile("CONIN$", os.O_RDWR, 0); err == nil {
os.Stdin = in
}
companion()
}
// companion has a command run in a terminal bring the magpie.com beside
// this app up, or write it there when the folder is on PATH: run as
// magpie.exe, the first command after an update to this version, the next
// `magpie` is waited for (update.EnsureCompanion).
func companion() {
if exe, err := update.Executable(); err == nil {
update.EnsureCompanion(exe)
}
}
// pointStyles points lipgloss at out: its default renderer was made over
// the os.Stdout before this, a handle that was no terminal then, so every
// style would print without colour. The styles made at package init hold
// that renderer, so it is pointed at the console in place. Anything else
// that reads or writes the standard streams takes os.Stdin, os.Stdout or
// os.Stderr when it runs, never in a package variable.
func pointStyles(out *os.File) {
lipgloss.DefaultRenderer().SetOutput(lipgloss.NewRenderer(out).Output())
}
+1 -1
View File
@@ -19285,7 +19285,7 @@ function renderCLI(r) {
const paint = (v) => {
sub.textContent = v.stuck === "translocated" ? t("macOS runs magpie from a temporary copy until it is moved to Applications: move it there first")
: v.stuck === "read-only" ? t("magpie runs from its disk image: copy it to Applications first")
: v.ours ? t("In a new terminal, magpie runs this app: {path}", { path: v.command }) + (v.shim && v.command === v.shim ? " (" + t("which runs {name}", { name: exeName(v.exe) }) + ")" : "")
: v.ours ? t("In a new terminal, magpie runs this app: {path}", { path: v.command }) + (/\.(cmd|com)$/i.test(v.command || "") ? " (" + t("which runs {name}", { name: exeName(v.exe) }) + ")" : "")
: v.command ? t("In a new terminal, magpie runs another copy: {path}", { path: v.command }) + (v.version ? " (" + v.version + ")" : "")
: t("A new terminal can't find the magpie command");
add.hidden = v.ours || !v.dir || !!v.stuck;
+18 -4
View File
@@ -3,7 +3,8 @@
// terminal opened now runs this app, said for each shell (a dot, no left
// border), and Add to PATH, which posts /api/cli and shows the answer. On
// Windows a program not named magpie.exe (the site's portable download,
// #942) is said to get a magpie.cmd that runs it. A
// #942) is said to get a magpie.cmd that runs it, and a magpie.com that
// runs the app is said to run it (#3737). A
// shell whose PATH lacks the folder has its own button naming its profile,
// and only that button posts that shell. On Windows PowerShell and cmd are
// listed, with no profile to write; a translocated app gets no button. No
@@ -21,10 +22,10 @@ const assets = path.resolve(__dirname, "../assets");
const words = {
en: { row: "Command line", add: "Add to PATH", none: "can't find the magpie command", ours: "runs this app", fish: "Add to ~/.config/fish/config.fish",
added: "open a new terminal window", ps: "PowerShell and cmd take up a change in new windows", moved: "moved to Applications",
shimTitle: "writes magpie.cmd there, which runs magpie-windows-amd64.exe", shimAdded: "magpie.cmd beside magpie-windows-amd64.exe runs it as magpie", shimRuns: "which runs magpie-windows-amd64.exe" },
shimTitle: "writes magpie.cmd there, which runs magpie-windows-amd64.exe", shimAdded: "magpie.cmd beside magpie-windows-amd64.exe runs it as magpie", shimRuns: "which runs magpie-windows-amd64.exe", comRuns: "which runs magpie.exe" },
zh: { row: "命令行", add: "添加到 PATH", none: "新终端里找不到 magpie 命令", ours: "运行这个 app", fish: "添加到 ~/.config/fish/config.fish",
added: "新开一个终端窗口", ps: "PowerShell 和 cmd 在新窗口里生效", moved: "移到「应用程序」",
shimTitle: "写一个 magpie.cmd 来运行 magpie-windows-amd64.exe", shimAdded: "magpie-windows-amd64.exe 旁边的 magpie.cmd", shimRuns: "它运行 magpie-windows-amd64.exe" },
shimTitle: "写一个 magpie.cmd 来运行 magpie-windows-amd64.exe", shimAdded: "magpie-windows-amd64.exe 旁边的 magpie.cmd", shimRuns: "它运行 magpie-windows-amd64.exe", comRuns: "它运行 magpie.exe" },
};
const EXE = "/Applications/magpie.app/Contents/MacOS/magpie";
@@ -35,7 +36,9 @@ function view(ctl) {
// magpie.cmd Add writes beside it
const dir = ctl.portable ? "D:\\portable_app" : "C:\\Users\\u\\AppData\\Local\\magpie";
const exe = dir + (ctl.portable ? "\\magpie-windows-amd64.exe" : "\\magpie.exe"), shim = ctl.portable ? dir + "\\magpie.cmd" : "";
const cmd = ctl.added ? shim || exe : "";
// a release build runs as magpie through the magpie.com it writes
// beside the app, which a shell waits for (#3737)
const cmd = ctl.added ? shim || (ctl.com ? dir + "\\magpie.com" : exe) : "";
return { exe, ours: ctl.added, command: cmd, dir, windows: true, shim,
shells: ["PowerShell", "cmd"].map((name, i) => ({ name, default: i === 0, known: true, ours: ctl.added, command: cmd })) };
}
@@ -180,6 +183,17 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await page.context().close();
});
await t.test(lang + ": Windows' magpie.com is said to run the app (#3737)", async () => {
const ctl = { posts: [], gets: 0, windows: true, com: true };
const errors = [];
const { page, row } = await open(browser, lang, ctl, errors);
await row.locator("button.cli-add").click();
await row.locator(".sub", { hasText: "AppData\\Local\\magpie\\magpie.com" }).waitFor();
assert.match(await row.locator(".sub").innerText(), new RegExp(w.comRuns));
assert.deepEqual(errors, []);
await page.context().close();
});
await t.test(lang + ": a translocated app gets no button", async () => {
const ctl = { posts: [], gets: 0, stuck: "translocated" };
const errors = [];
+3 -2
View File
@@ -176,8 +176,9 @@ func (u *updater) placeExe(exe string) {
}
u.exe = exe
u.self, _ = os.Stat(exe)
update.RemoveOld(exe) // what the last updates on Windows moved aside
update.RemoveStaleNew(exe) // what a magpie left running downloaded again
update.RemoveOld(exe) // what the last updates on Windows moved aside
update.RemoveStaleNew(exe) // what a magpie left running downloaded again
update.EnsureCompanion(exe) // Windows: the magpie.com a terminal runs, of this version (#3737)
u.blocked = update.ReadBlocked(Version)
}
+6 -4
View File
@@ -50,7 +50,7 @@ type CLI struct {
Stuck string `json:"stuck,omitempty"` // translocated, read-only: why it can't be linked from where it is
Shells []CLIShell `json:"shells"`
Windows bool `json:"windows,omitempty"`
Shim string `json:"shim,omitempty"` // Windows: the magpie.cmd Add writes beside an app not named magpie.exe, which runs it
Shim string `json:"shim,omitempty"` // Windows: the magpie.cmd Add writes beside an app not named magpie.exe, which runs it, in a build with no magpie.com (com.go)
}
// cliShell is a shell installed here.
@@ -77,7 +77,7 @@ func ReadCLI() *CLI {
return v
}
v.Exe, v.Stuck = exe, cliStuck()
if v.Windows && needsShim(exe) {
if v.Windows && comLauncher == nil && needsShim(exe) {
v.Shim = filepath.Join(filepath.Dir(exe), shimName)
}
shells := cliShells()
@@ -94,7 +94,7 @@ func ReadCLI() *CLI {
var def []string
for i, sh := range shells {
s := CLIShell{Name: sh.Name, Default: sh.Default, Known: paths[i] != nil, Command: findCLI(paths[i])}
s.Ours = s.Command != "" && (sameFile(s.Command, exe) || shimRuns(s.Command, exe))
s.Ours = s.Command != "" && (sameFile(s.Command, exe) || shimRuns(s.Command, exe) || comRuns(s.Command, exe))
if p := cliProfile(sh.Name); p != "" {
s.Profile = tildeHome(p)
}
@@ -209,7 +209,9 @@ var cliStuck = func() string {
func cliNames() []string {
if runtime.GOOS == "windows" {
return []string{"magpie.exe", "magpie.cmd", "magpie.bat"}
// PATHEXT's order: magpie.com, the console program magpie writes
// beside the app (com.go), runs before magpie.exe
return []string{"magpie.com", "magpie.exe", "magpie.cmd", "magpie.bat"}
}
return []string{"magpie"}
}
+11 -3
View File
@@ -22,10 +22,18 @@ func installedShells() []cliShell {
func cliDir(exe string, _ []string, _ string) string { return filepath.Dir(exe) }
// cliPlace puts dir first in the user's PATH in the registry, where a
// terminal opened from now on takes it up, and tells Explorer; an app not
// named magpie.exe gets its magpie.cmd there first (writeShim).
// terminal opened from now on takes it up, and tells Explorer. The app's
// magpie.com goes there first (com.go), which a terminal waits for; a
// build without it gives an app not named magpie.exe a magpie.cmd
// (writeShim).
func cliPlace(exe, dir string) error {
if _, err := writeShim(exe); err != nil {
if comLauncher != nil {
if comOwner(exe) {
if _, err := writeCom(comLauncher, exe); err != nil {
return err
}
}
} else if _, err := writeShim(exe); err != nil {
return err
}
k, err := registry.OpenKey(registry.CURRENT_USER, `Environment`, registry.QUERY_VALUE|registry.SET_VALUE)
+161
View File
@@ -0,0 +1,161 @@
package update
import (
"bytes"
"fmt"
"os"
"path/filepath"
"strings"
)
// The Windows app is linked as a GUI program, so a double click opens no
// console window; but a shell doesn't wait for a GUI program either. In
// PowerShell or cmd, `magpie plugin login` gave the prompt back at once,
// printed after it, and the shell and magpie both read the keys typed:
// a hidden password never reached magpie (TomXPRIME, #3737). A shell looks
// for `magpie` by PATHEXT, which lists .COM before .EXE, so magpie writes
// magpie.com beside the app: a small console program (./launcher) that
// the shell waits for, which runs the app with its console and exits with
// the app's code. Double clicks and the Start menu still open magpie.exe.
//
// It is written wherever a terminal runs magpie from: when the app's
// folder is on PATH, where Settings › Command line puts it, or a magpie.com
// or magpie.cmd is there already. The app writes it again as it starts
// when its bytes differ, so an update brings it along.
// ComEnv is set by magpie.com for the app it runs: the standard handles it
// hands over are the terminal's console or a redirection, and its console
// is the one to borrow (cli's console_windows.go).
const ComEnv = "MAGPIE_COM"
// comName is the companion's file name; it runs as `magpie`.
const comName = "magpie.com"
// comMagic ends magpie.com; the app it runs is named just before it,
// after a NUL (launcher's targetName).
const comMagic = "\x00magpie-com-target"
// comLauncher is the launcher program, built for this system and put in
// the Windows app by `make release-windows` (com_embed_windows_*.go); nil
// in any other build, which writes no magpie.com.
var comLauncher []byte
// comText is the magpie.com that runs the program exe in its folder.
func comText(launcher []byte, exe string) []byte {
name := filepath.Base(strings.ReplaceAll(exe, `\`, "/"))
out := make([]byte, 0, len(launcher)+1+len(name)+len(comMagic))
out = append(out, launcher...)
out = append(out, 0)
out = append(out, name...)
return append(out, comMagic...)
}
// comTarget is the program name in a magpie.com's last bytes, "" when it
// has none.
func comTarget(b []byte) string {
if !bytes.HasSuffix(b, []byte(comMagic)) {
return ""
}
b = b[:len(b)-len(comMagic)]
return string(b[bytes.LastIndexByte(b, 0)+1:])
}
// comRuns says whether cmd is a magpie.com beside exe that runs it.
func comRuns(cmd, exe string) bool {
if !strings.EqualFold(filepath.Base(cmd), comName) || !strings.EqualFold(filepath.Dir(cmd), filepath.Dir(exe)) {
return false
}
f, err := os.Open(cmd)
if err != nil {
return false
}
defer f.Close()
st, err := f.Stat()
if err != nil || st.Size() < int64(len(comMagic)) {
return false
}
n := min(st.Size(), 1024)
b := make([]byte, n)
if _, err := f.ReadAt(b, st.Size()-n); err != nil {
return false
}
return strings.EqualFold(comTarget(b), filepath.Base(exe))
}
// comOwner says whether exe is the program a magpie.com in its folder
// should run: a magpie.exe there is what `magpie` ran before, so another
// copy beside it (magpie-windows-amd64 (1).exe) leaves it be.
func comOwner(exe string) bool {
if strings.EqualFold(filepath.Base(exe), "magpie.exe") {
return true
}
st, err := os.Stat(filepath.Join(filepath.Dir(exe), "magpie.exe"))
return err != nil || st.IsDir()
}
// EnsureCompanion writes the magpie.com that runs exe beside it when a
// terminal runs magpie from that folder (on PATH, or a magpie.com or
// magpie.cmd there), or brings one there up to this version. Nothing in
// a build without the launcher, or when it is as it should be already.
func EnsureCompanion(exe string) error {
if comLauncher == nil || !comOwner(exe) {
return nil
}
dir := filepath.Dir(exe)
if !onPath(dir, os.Getenv("PATH")) && !exists(filepath.Join(dir, comName)) && !exists(filepath.Join(dir, shimName)) {
return nil
}
_, err := writeCom(comLauncher, exe)
return err
}
// writeCom writes the magpie.com that runs exe beside it, unless it is
// there already, and is its path. A magpie.com running now (a `magpie
// serve` in a terminal) can't be written over, but can be moved aside,
// as an update moves the running app; the next run clears it.
func writeCom(launcher []byte, exe string) (string, error) {
p := filepath.Join(filepath.Dir(exe), comName)
want := comText(launcher, exe)
// the one moved aside last time, running then, is let go of now
RemoveOld(p)
if b, err := os.ReadFile(p); err == nil && bytes.Equal(b, want) {
return p, nil
}
f, err := os.CreateTemp(filepath.Dir(p), ".magpie-com-*")
if err != nil {
return "", fmt.Errorf("writing %s, which runs %s as magpie: %w", p, filepath.Base(exe), err)
}
tmp := f.Name()
_, err = f.Write(want)
if cerr := f.Close(); err == nil {
err = cerr
}
if err == nil {
if err = os.Rename(tmp, p); err != nil && exists(p) {
if aerr := os.Rename(p, oldName(p)); aerr == nil {
err = os.Rename(tmp, p)
}
}
}
if err != nil {
os.Remove(tmp)
return "", fmt.Errorf("writing %s, which runs %s as magpie: %w", p, filepath.Base(exe), err)
}
return p, nil
}
// onPath is whether dir is one of path's (Windows', ;-separated) folders.
func onPath(dir, path string) bool {
dir = strings.TrimRight(dir, `\/`)
for _, d := range strings.Split(path, string(os.PathListSeparator)) {
if d = strings.TrimRight(strings.TrimSpace(d), `\/`); d != "" && strings.EqualFold(d, dir) {
return true
}
}
return false
}
func exists(p string) bool {
_, err := os.Stat(p)
return err == nil
}
@@ -0,0 +1,13 @@
//go:build comlauncher
package update
import _ "embed"
// The launcher magpie.com is made of (com.go), built for windows/amd64 by
// `make release-windows` before the app; not kept in git.
//
//go:embed launcher-amd64.com
var launcheramd64 []byte
func init() { comLauncher = launcheramd64 }
@@ -0,0 +1,13 @@
//go:build comlauncher
package update
import _ "embed"
// The launcher magpie.com is made of (com.go), built for windows/arm64 by
// `make release-windows` before the app; not kept in git.
//
//go:embed launcher-arm64.com
var launcherarm64 []byte
func init() { comLauncher = launcherarm64 }
+139
View File
@@ -0,0 +1,139 @@
package update
import (
"bytes"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
)
// The launcher reads the name comText writes with its own copy of the
// marker (launcher/args.go): the two are one.
func TestComMagicIsTheLaunchers(t *testing.T) {
b, err := os.ReadFile(filepath.Join("launcher", "args.go"))
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(b), `const magic = "\x00magpie-com-target"`) || comMagic != "\x00magpie-com-target" {
t.Fatal("magpie.com's marker differs between the app and the launcher")
}
}
// #3737: a shell doesn't wait for the GUI-linked magpie.exe, so magpie
// writes magpie.com (run first by PATHEXT) beside it, naming the app it
// runs; written once, again only when its bytes differ (an update).
func TestWriteCom(t *testing.T) {
dir := t.TempDir()
exe := filepath.Join(dir, "magpie-windows-amd64.exe")
if err := os.WriteFile(exe, []byte("MZ"), 0o755); err != nil {
t.Fatal(err)
}
launcher := []byte("MZ launcher v1")
p, err := writeCom(launcher, exe)
if err != nil || p != filepath.Join(dir, "magpie.com") {
t.Fatalf("writeCom: %q, %v", p, err)
}
b, _ := os.ReadFile(p)
if !bytes.HasPrefix(b, launcher) || comTarget(b) != "magpie-windows-amd64.exe" {
t.Fatalf("magpie.com: %q", b)
}
if !comRuns(p, exe) || comRuns(p, filepath.Join(dir, "magpie.exe")) {
t.Fatal("magpie.com not read as running this app alone")
}
st1, _ := os.Stat(p)
if _, err := writeCom(launcher, exe); err != nil {
t.Fatal(err)
}
if st2, _ := os.Stat(p); !os.SameFile(st1, st2) {
t.Fatal("an up-to-date magpie.com written again")
}
// the next version's launcher
if _, err := writeCom([]byte("MZ launcher v2"), exe); err != nil {
t.Fatal(err)
}
if b, _ := os.ReadFile(p); !bytes.HasPrefix(b, []byte("MZ launcher v2")) {
t.Fatalf("magpie.com not brought up to date: %q", b)
}
// one moved aside while it ran goes on the next run
if err := os.WriteFile(p+".old", []byte("MZ launcher v1"), 0o755); err != nil {
t.Fatal(err)
}
if _, err := writeCom([]byte("MZ launcher v2"), exe); err != nil || exists(p+".old") {
t.Fatalf("magpie.com.old left: %v", err)
}
if left, _ := filepath.Glob(filepath.Join(dir, ".magpie-com-*")); len(left) > 0 {
t.Fatalf("temp files left: %q", left)
}
}
func TestComOwner(t *testing.T) {
dir := t.TempDir()
dl := filepath.Join(dir, "magpie-windows-amd64.exe")
if !comOwner(dl) {
t.Fatal("a lone download doesn't own magpie.com")
}
if err := os.WriteFile(filepath.Join(dir, "magpie.exe"), []byte("MZ"), 0o755); err != nil {
t.Fatal(err)
}
if comOwner(dl) {
t.Fatal("a copy beside magpie.exe takes `magpie` from it")
}
if !comOwner(filepath.Join(dir, "Magpie.exe")) {
t.Fatal("magpie.exe doesn't own its magpie.com")
}
}
// EnsureCompanion writes where a terminal runs magpie from, and nowhere
// else: a downloads folder off PATH gets nothing.
func TestEnsureCompanion(t *testing.T) {
old := comLauncher
t.Cleanup(func() { comLauncher = old })
sep := string(os.PathListSeparator)
comLauncher = nil
dir := t.TempDir()
exe := filepath.Join(dir, "magpie.exe")
t.Setenv("PATH", dir)
if err := EnsureCompanion(exe); err != nil || exists(filepath.Join(dir, comName)) {
t.Fatalf("a build with no launcher wrote magpie.com: %v", err)
}
comLauncher = []byte("MZ launcher")
off := t.TempDir()
t.Setenv("PATH", "/x"+sep+dir+string(filepath.Separator))
if err := EnsureCompanion(filepath.Join(off, "magpie.exe")); err != nil || exists(filepath.Join(off, comName)) {
t.Fatalf("magpie.com written off PATH: %v", err)
}
if err := EnsureCompanion(exe); err != nil || !comRuns(filepath.Join(dir, comName), exe) {
t.Fatalf("magpie.com not written in a folder on PATH: %v", err)
}
// off PATH, but a magpie.cmd says a terminal runs it from there
shim := t.TempDir()
dl := filepath.Join(shim, "magpie-windows-arm64.exe")
if err := os.WriteFile(filepath.Join(shim, shimName), []byte("@echo off\r\n"), 0o644); err != nil {
t.Fatal(err)
}
if err := EnsureCompanion(dl); err != nil || !comRuns(filepath.Join(shim, comName), dl) {
t.Fatalf("magpie.com not written beside a magpie.cmd: %v", err)
}
}
// findCLI names the program a shell runs: magpie.com, before magpie.exe
// in the same folder.
func TestFindCLIPrefersCom(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("PATHEXT is Windows'")
}
dir := t.TempDir()
for _, n := range []string{"magpie.exe", "magpie.com"} {
if err := os.WriteFile(filepath.Join(dir, n), []byte("MZ"), 0o755); err != nil {
t.Fatal(err)
}
}
if got := findCLI([]string{dir}); !strings.EqualFold(got, filepath.Join(dir, "magpie.com")) {
t.Fatalf("findCLI: %q", got)
}
}
+66
View File
@@ -0,0 +1,66 @@
package main
import (
"bytes"
"os"
"path/filepath"
"strings"
)
// magic ends the file; the app's name is just before it, after a NUL.
const magic = "\x00magpie-com-target"
// tail is how much of the file's end is read for the name: a file name
// of 255 UTF-16 units is at most 765 bytes of UTF-8.
const tail = 1024
// targetName is the app this runs: the name in its trailer, else the
// file's own name with .exe.
func targetName(self string) string {
if f, err := os.Open(self); err == nil {
defer f.Close()
if st, err := f.Stat(); err == nil && st.Size() > tail {
b := make([]byte, tail)
if _, err := f.ReadAt(b, st.Size()-tail); err == nil && bytes.HasSuffix(b, []byte(magic)) {
b = b[:len(b)-len(magic)]
if name := string(b[bytes.LastIndexByte(b, 0)+1:]); name != "" && filepath.Base(name) == name {
return name
}
}
}
}
return strings.TrimSuffix(filepath.Base(self), filepath.Ext(self)) + ".exe"
}
// argsOf is the command line after the program's name, as typed: the
// app gets the arguments byte for byte, parsed by its own rules. The name
// ends at the closing quote, or unquoted at a space or tab.
func argsOf(line string) string {
i := 0
if strings.HasPrefix(line, `"`) {
if j := strings.IndexByte(line[1:], '"'); j >= 0 {
i = j + 2
} else {
i = len(line)
}
} else {
for i < len(line) && line[i] != ' ' && line[i] != '\t' {
i++
}
}
return strings.TrimLeft(line[i:], " \t")
}
// opensWindow is whether args are a command the app answers with its
// window (cli.run): none, app, gui, tray, panel, -Embedding or a magpie://
// link.
func opensWindow(args []string) bool {
if len(args) == 0 {
return true
}
switch args[0] {
case "app", "gui", "tray", "panel", "-Embedding":
return true
}
return strings.HasPrefix(strings.ToLower(args[0]), "magpie:")
}
+64
View File
@@ -0,0 +1,64 @@
package main
import (
"os"
"path/filepath"
"testing"
)
// #3737: magpie.com hands the app what was typed after `magpie` as it
// was typed, runs the program its trailer names, and leaves a command that
// opens the window to run on its own.
func TestArgsOf(t *testing.T) {
for line, want := range map[string]string{
`magpie`: ``,
`magpie plugin login`: `plugin login`,
`magpie version`: `version`,
`"C:\Program Files\m\magpie.com" "a b" c`: `"a b" c`,
`"C:\m\magpie" x`: `x`,
`C:\m\magpie.com -v`: `-v`,
`"unclosed`: ``,
} {
if got := argsOf(line); got != want {
t.Errorf("argsOf(%q) = %q, want %q", line, got, want)
}
}
}
func TestOpensWindow(t *testing.T) {
for _, a := range [][]string{nil, {"app"}, {"gui"}, {"tray"}, {"panel"}, {"-Embedding"}, {"MAGPIE://open"}} {
if !opensWindow(a) {
t.Errorf("%q waited for as a terminal command", a)
}
}
for _, a := range [][]string{{"version"}, {"plugin", "login"}, {"serve"}, {"backup", "app"}} {
if opensWindow(a) {
t.Errorf("%q not waited for", a)
}
}
}
func TestTargetName(t *testing.T) {
dir := t.TempDir()
com := filepath.Join(dir, "magpie.com")
body := make([]byte, 4096)
write := func(b []byte) {
t.Helper()
if err := os.WriteFile(com, b, 0o755); err != nil {
t.Fatal(err)
}
}
write(append(append(append(body, 0), "magpie-windows-amd64 (1).exe"...), magic...))
if got := targetName(com); got != "magpie-windows-amd64 (1).exe" {
t.Fatalf("trailer's name: %q", got)
}
// no trailer, or one naming a path: its own name with .exe
write(body)
if got := targetName(com); got != "magpie.exe" {
t.Fatalf("no trailer: %q", got)
}
write(append(append(append(body, 0), "../evil.exe"...), magic...))
if got := targetName(com); got != "magpie.exe" {
t.Fatalf("a path in the trailer: %q", got)
}
}
+6
View File
@@ -0,0 +1,6 @@
//go:build !windows
// magpie.com runs on Windows only (main_windows.go).
package main
func main() {}
+85
View File
@@ -0,0 +1,85 @@
// Command launcher is magpie.com, the console program magpie writes
// beside the Windows app (update.EnsureCompanion, #3737).
//
// The app is linked with -H windowsgui so that a double click opens no
// console window, and a shell doesn't wait for such a program: `magpie
// plugin login` in PowerShell or cmd gave the prompt back at once, printed
// after it, and the shell and magpie read the same keys. A shell looks for
// `magpie` by PATHEXT, which lists .COM before .EXE, so it runs this
// instead: a console program, which the shell waits for. It runs the app
// with this console's standard handles, waits for it and exits with its
// code. A command that opens the app's window (none, app, gui, tray,
// panel, a magpie:// link) is started and left to run, as it was.
//
// The app it runs is named in this file's last bytes (update.comText),
// so a download kept as magpie-windows-amd64.exe is run by its own name.
package main
import (
"os"
"os/signal"
"path/filepath"
"syscall"
"unsafe"
"golang.org/x/sys/windows"
)
func main() {
self, err := os.Executable()
if err != nil {
fail(err)
}
target := filepath.Join(filepath.Dir(self), targetName(self))
line := windows.UTF16PtrToString(windows.GetCommandLine())
cmdline := `"` + target + `"`
if rest := argsOf(line); rest != "" {
cmdline += " " + rest
}
if opensWindow(os.Args[1:]) {
// the app's window, which outlives the terminal: started on its
// own, with no console, as a double click starts it
var si windows.StartupInfo
si.Cb = uint32(unsafe.Sizeof(si))
var pi windows.ProcessInformation
t, _ := windows.UTF16PtrFromString(target)
c, _ := windows.UTF16PtrFromString(cmdline)
if err := windows.CreateProcess(t, c, nil, nil, false, windows.DETACHED_PROCESS|windows.CREATE_NEW_PROCESS_GROUP, nil, nil, &si, &pi); err != nil {
fail(err)
}
windows.CloseHandle(pi.Thread)
windows.CloseHandle(pi.Process)
return
}
// Ctrl+C reaches every program on this console, the app too, which
// ends as it chooses; this one waits for it. A handler, not ignoring
// the signal: that would be inherited, and the app would never see it.
signal.Notify(make(chan os.Signal, 1), os.Interrupt)
files := []*os.File{os.Stdin, os.Stdout, os.Stderr}
for i, f := range files {
if f == nil { // started with no such stream: the app gets NUL
if files[i], err = os.OpenFile(os.DevNull, os.O_RDWR, 0); err != nil {
fail(err)
}
}
}
// update.ComEnv: the app keeps these handles and borrows this console
p, err := os.StartProcess(target, nil, &os.ProcAttr{
Files: files,
Env: append(os.Environ(), "MAGPIE_COM=1"),
Sys: &syscall.SysProcAttr{CmdLine: cmdline},
})
if err != nil {
fail(err)
}
st, err := p.Wait()
if err != nil {
fail(err)
}
os.Exit(st.ExitCode())
}
func fail(err error) {
os.Stderr.WriteString("magpie: " + err.Error() + "\n")
os.Exit(1)
}