fix(windows): launch commands on the interactive desktop

This commit is contained in:
cabbage committed 2026-10-27 18:35:29 +00:00
1 parent 30e7bb8545
commit 8d28925e44
20 files changed
+1036 -28

No files matched your search

@@ -0,0 +1,43 @@
package windows
import (
"fmt"
"strings"
"github.com/rvbox/rvbox/internal/client/supervisor"
)
const interactiveDesktop = `winsta0\default`
// Desktop placement follows the selected identity, never a caller-supplied
// desktop name. Session 0 contexts keep their noninteractive desktop.
func desktopForIdentity(identity supervisor.EffectiveIdentity) (string, error) {
switch ExecutionContext(identity.Context) {
case ContextActiveUser, ContextActiveUserElevated, ContextActiveSystem:
if identity.SessionID == 0 {
return "", fmt.Errorf("active execution context has no interactive session")
}
return interactiveDesktop, nil
case ContextLocalService, ContextLocalSystem:
if identity.SessionID != 0 {
return "", fmt.Errorf("local execution context unexpectedly targets session %d", identity.SessionID)
}
return "", nil
default:
return "", fmt.Errorf("unknown Windows execution context %q", identity.Context)
}
}
func validateInteractiveDesktop(desktop string) error {
if !strings.EqualFold(desktop, interactiveDesktop) {
return fmt.Errorf("interactive desktop mismatch: got %q, want %q", desktop, interactiveDesktop)
}
return nil
}
func launcherAbortError(payload []byte) error {
if len(payload) == 0 || len(payload) > 4096 {
return fmt.Errorf("launcher preparation failed without a valid diagnostic")
}
return fmt.Errorf("launcher preparation failed: %s", payload)
}
@@ -0,0 +1,55 @@
package windows
import (
"strings"
"testing"
"github.com/rvbox/rvbox/internal/client/supervisor"
)
func TestDesktopPlacementFollowsSelectedIdentity_HP_DESKTOP_01(t *testing.T) {
for _, context := range []ExecutionContext{ContextActiveUser, ContextActiveUserElevated, ContextActiveSystem} {
for _, sessionID := range []uint32{1, 7, 42} {
desktop, err := desktopForIdentity(supervisor.EffectiveIdentity{Context: string(context), SessionID: sessionID})
if err != nil || desktop != interactiveDesktop {
t.Fatalf("%s/%d: desktop=%q err=%v", context, sessionID, desktop, err)
}
}
}
for _, context := range []ExecutionContext{ContextLocalService, ContextLocalSystem} {
desktop, err := desktopForIdentity(supervisor.EffectiveIdentity{Context: string(context)})
if err != nil || desktop != "" {
t.Fatalf("%s: desktop=%q err=%v", context, desktop, err)
}
}
}
func TestDesktopRejectsWrongSessionAndSecureTargets_BH_DESKTOP_01(t *testing.T) {
for _, identity := range []supervisor.EffectiveIdentity{
{Context: string(ContextActiveUser)}, {Context: string(ContextActiveUserElevated)}, {Context: string(ContextActiveSystem)},
{Context: string(ContextLocalService), SessionID: 1}, {Context: string(ContextLocalSystem), SessionID: 1}, {Context: "unknown", SessionID: 1},
} {
if _, err := desktopForIdentity(identity); err == nil {
t.Fatalf("invalid identity accepted: %+v", identity)
}
}
for _, target := range []string{"", `winsta0\winlogon`, `winsta0\screensaver`, `Service-0x0-3e7$\default`, `winsta0\other`, `winsta0\default\extra`} {
if err := validateInteractiveDesktop(target); err == nil {
t.Fatalf("wrong desktop accepted: %q", target)
}
}
if err := validateInteractiveDesktop(`WinSta0\Default`); err != nil {
t.Fatal(err)
}
}
func TestDesktopFailureDiagnosticIsBounded_BH_DESKTOP_02(t *testing.T) {
if err := launcherAbortError([]byte("interactive desktop access: Access is denied.")); !strings.Contains(err.Error(), "Access is denied") {
t.Fatal(err)
}
for _, payload := range [][]byte{nil, make([]byte, 4097)} {
if err := launcherAbortError(payload); !strings.Contains(err.Error(), "without a valid diagnostic") {
t.Fatal(err)
}
}
}
@@ -0,0 +1,98 @@
//go:build windows
package windows
import (
"fmt"
"unsafe"
winapi "golang.org/x/sys/windows"
)
var (
desktopUser32 = winapi.NewLazySystemDLL("user32.dll")
procProcessWindowStation = desktopUser32.NewProc("GetProcessWindowStation")
procThreadDesktop = desktopUser32.NewProc("GetThreadDesktop")
procUserObjectInformation = desktopUser32.NewProc("GetUserObjectInformationW")
procOpenWindowStation = desktopUser32.NewProc("OpenWindowStationW")
procCloseWindowStation = desktopUser32.NewProc("CloseWindowStation")
procOpenDesktop = desktopUser32.NewProc("OpenDesktopW")
procCloseDesktop = desktopUser32.NewProc("CloseDesktop")
)
func desktopPointer(desktop string) *uint16 {
if desktop == "" {
return nil
}
value, _ := winapi.UTF16PtrFromString(desktop)
return value
}
func userObjectName(handle uintptr) (string, error) {
var name [256]uint16
var needed uint32
result, _, err := procUserObjectInformation.Call(handle, 2 /* UOI_NAME */, uintptr(unsafe.Pointer(&name[0])), unsafe.Sizeof(name), uintptr(unsafe.Pointer(&needed)))
if result == 0 {
return "", fmt.Errorf("read window station/desktop name: %w", err)
}
if needed < 2 || needed > uint32(unsafe.Sizeof(name)) {
return "", fmt.Errorf("invalid window station/desktop name size %d", needed)
}
return winapi.UTF16ToString(name[:]), nil
}
// Check access in the selected-session helper, not Session 0's service. Never
// broaden desktop ACLs or switch to Winlogon/the secure input desktop. A locked
// session can open Default now and display its UI when the user unlocks.
func verifyCurrentInteractiveDesktop(sessionID uint32) (string, error) {
if sessionID == 0 {
return "", nil
}
station, _, err := procProcessWindowStation.Call()
if station == 0 {
return "", fmt.Errorf("get process window station: %w", err)
}
desktop, _, err := procThreadDesktop.Call(uintptr(winapi.GetCurrentThreadId()))
if desktop == 0 {
return "", fmt.Errorf("get thread desktop: %w", err)
}
stationName, err := userObjectName(station)
if err != nil {
return "", err
}
desktopName, err := userObjectName(desktop)
if err != nil {
return "", err
}
path := stationName + `\` + desktopName
if err := validateInteractiveDesktop(path); err != nil {
return "", err
}
// Open non-inheritable handles to check existing logon-token access. The
// handles returned by GetProcessWindowStation/GetThreadDesktop are borrowed.
stationHandle, _, err := procOpenWindowStation.Call(uintptr(unsafe.Pointer(desktopPointer("winsta0"))), 0,
0x0002|0x0020 /* READATTRIBUTES | ACCESSGLOBALATOMS */)
if stationHandle == 0 {
return "", fmt.Errorf("interactive window station access: %w", err)
}
defer procCloseWindowStation.Call(stationHandle)
desktopHandle, _, err := procOpenDesktop.Call(uintptr(unsafe.Pointer(desktopPointer("default"))), 0, 0,
0x0001|0x0002|0x0004|0x0080 /* READOBJECTS | CREATEWINDOW | CREATEMENU | WRITEOBJECTS */)
if desktopHandle == 0 {
return "", fmt.Errorf("interactive desktop access: %w", err)
}
defer procCloseDesktop.Call(desktopHandle)
return path, nil
}
func commandStartup(stdin, stdout, stderr winapi.Handle, desktop string) (winapi.StartupInfoEx, uint32) {
startup := winapi.StartupInfoEx{StartupInfo: winapi.StartupInfo{
Cb: uint32(unsafe.Sizeof(winapi.StartupInfoEx{})), Desktop: desktopPointer(desktop),
Flags: winapi.STARTF_USESTDHANDLES | winapi.STARTF_USESHOWWINDOW, ShowWindow: winapi.SW_SHOWNORMAL,
StdInput: stdin, StdOutput: stdout, StdErr: stderr,
}}
// A private headless console does not ask GUI descendants to hide. Keep
// this distinct from DETACHED_PROCESS so the TERM helper can still attach.
flags := uint32(winapi.CREATE_NO_WINDOW | winapi.CREATE_SUSPENDED | winapi.CREATE_UNICODE_ENVIRONMENT | winapi.EXTENDED_STARTUPINFO_PRESENT)
return startup, flags
}
@@ -0,0 +1,253 @@
//go:build windows
package windows
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
rvboxv1 "github.com/rvbox/rvbox/gen/go/rvbox/v1"
"github.com/rvbox/rvbox/internal/client/supervisor"
"github.com/rvbox/rvbox/internal/domain"
winapi "golang.org/x/sys/windows"
)
// Native fixture children execute the production launcher/helper entrypoints.
// This dispatcher exists only in the test executable, never the release image.
func TestMain(m *testing.M) {
if len(os.Args) == 4 && os.Args[2] == "--channel" {
var err error
switch os.Args[1] {
case "--launcher":
err = RunLauncher(context.Background(), os.Args[3])
case "--signal-helper":
err = RunSignalHelper(context.Background(), os.Args[3])
default:
os.Exit(m.Run())
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
os.Exit(0)
}
os.Exit(m.Run())
}
func TestNativeDesktopAccessOnActualThread_HP_DESKTOP_02(t *testing.T) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
var sessionID uint32
if err := winapi.ProcessIdToSessionId(winapi.GetCurrentProcessId(), &sessionID); err != nil {
t.Fatal(err)
}
if sessionID == 0 {
t.Skip("requires an interactive desktop; Session 0 is a separate route")
}
path, err := verifyCurrentInteractiveDesktop(sessionID)
if err != nil {
t.Fatal(err)
}
if err := validateInteractiveDesktop(path); err != nil {
t.Fatal(err)
}
}
// This fixture lane requires LocalSystem (SCM/service route), one usable active
// desktop, and the bundled PowerShell probe readable by that user. Run it in the
// disposable native fixture, not by changing an ordinary user's service state.
func desktopFixture(t *testing.T, elevated bool) (*execSupervisor, string, string) {
t.Helper()
var token winapi.Token
if err := winapi.OpenProcessToken(winapi.CurrentProcess(), winapi.TOKEN_QUERY, &token); err != nil {
t.Fatal(err)
}
user, err := token.GetTokenUser()
_ = token.Close()
if err != nil {
t.Fatal(err)
}
if user.User.Sid.String() != securitySystemRID {
t.Skip("requires LocalSystem native fixture process")
}
probe := os.Getenv("RVBOX_NATIVE_GUI_PROBE")
if probe == "" {
t.Skip("set RVBOX_NATIVE_GUI_PROBE to the bundled windows_gui_probe.ps1")
}
if !filepath.IsAbs(probe) {
t.Fatal("GUI probe path must be absolute")
}
if info, err := os.Lstat(probe); err != nil || !info.Mode().IsRegular() {
t.Fatalf("GUI probe must be a readable regular file: %v", err)
}
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
root := os.Getenv("SystemRoot")
if root == "" {
root = `C:\Windows`
}
manager := newExecSupervisor(NativeOptions{ExecutablePath: executable, Shells: ShellPaths{CMD: filepath.Join(root, "System32", "cmd.exe"), PowerShell: filepath.Join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")}, WindowsTermGrace: 3 * time.Second})
selected, identity, err := manager.selectToken(elevated)
if err != nil {
t.Fatal(err)
}
_ = selected.Close()
if identity.SessionID == 0 {
t.Skip("requires one usable active session, not a Session 0 fallback")
}
directory := t.TempDir()
// Both levels are owned by this t.TempDir fixture. Only SYSTEM and the
// selected effective SID receive access, including wrapper-file traversal.
for _, path := range []string{filepath.Dir(directory), directory} {
sd, err := winapi.SecurityDescriptorFromString(fmt.Sprintf("D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;%s)", identity.UserSID))
if err != nil {
t.Fatal(err)
}
dacl, _, err := sd.DACL()
if err != nil {
t.Fatal(err)
}
if err := winapi.SetNamedSecurityInfo(path, winapi.SE_FILE_OBJECT, winapi.DACL_SECURITY_INFORMATION|winapi.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, dacl, nil); err != nil {
t.Fatal(err)
}
}
t.Cleanup(func() { _ = manager.StopAll(context.Background()) })
return manager, directory, probe
}
func desktopProbeProcess(t *testing.T, manager *execSupervisor, directory, probe string, elevated, consoleOnly bool) (supervisor.Process, context.Context) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
t.Cleanup(cancel)
args := []string{manager.options.Shells.PowerShell, "-NoLogo", "-NoProfile", "-STA", "-ExecutionPolicy", "Bypass", "-File", probe, "-Seconds", "2"}
if consoleOnly {
args[len(args)-1] = "25"
args = append(args, "-ConsoleOnly")
}
command, err := BuildCommandLine(args)
if err != nil {
t.Fatal(err)
}
issue, err := domain.NewUUIDv7()
if err != nil {
t.Fatal(err)
}
spec := supervisor.StartSpec{IssueUUID: issue, CommandRevision: 1, WorkingDirectory: directory, Execution: &rvboxv1.ExecutionSpec{ShellType: rvboxv1.ShellType_SHELL_CMD, Elevated: elevated, Source: &rvboxv1.ExecutionSpec_CommandText{CommandText: "@" + command}}}
var process supervisor.Process
if consoleOnly {
// Isolate console-event delivery from cmd's own batch-abort behavior.
// The actual launcher still prepares this root shell suspended, puts it
// in the Job, and uses the production authenticated TERM helper.
token, identity, tokenErr := manager.selectToken(elevated)
if tokenErr != nil {
t.Fatal(tokenErr)
}
defer token.Close()
base, envErr := token.Environ(false)
if envErr != nil {
t.Fatal(envErr)
}
environment, envErr := BuildEnvironmentBlock(parseEnvironment(base), nil)
if envErr != nil {
t.Fatal(envErr)
}
process, err = manager.startViaLauncher(ctx, spec, token, identity, LaunchPlan{ApplicationName: args[0], CommandLine: command, WorkingDirectory: directory, Environment: environment}, nil)
} else {
process, err = manager.Start(ctx, spec)
}
if err != nil {
t.Fatal(err)
}
if process.Identity().SessionID == 0 {
t.Fatal("native GUI route unexpectedly fell back to Session 0")
}
if err := process.Release(ctx); err != nil {
t.Fatal(err)
}
return process, ctx
}
func TestNativeLauncherShowsGUIOnSelectedDesktop_HP_DESKTOP_03(t *testing.T) {
for _, elevated := range []bool{false, true} {
t.Run(fmt.Sprintf("elevated=%v", elevated), func(t *testing.T) {
manager, directory, probe := desktopFixture(t, elevated)
process, ctx := desktopProbeProcess(t, manager, directory, probe, elevated, false)
var output strings.Builder
for {
chunk, err := process.ReadOutput(ctx)
if errors.Is(err, io.EOF) {
break
}
if err != nil {
t.Fatal(err)
}
output.Write(chunk.Data)
}
status, err := process.Wait(ctx)
if err != nil || status.Code != 0 {
t.Fatalf("probe exit=%v err=%v output=%s", status, err, output.String())
}
var report struct {
SessionID uint32 `json:"session_id"`
Station string `json:"window_station"`
Desktop string `json:"desktop"`
Input string `json:"input_desktop"`
Visible bool `json:"window_observed"`
ConsoleVisible bool `json:"console_window_visible"`
}
found := false
for _, line := range strings.Split(output.String(), "\n") {
if strings.HasPrefix(strings.TrimSpace(line), "{") {
if err := json.Unmarshal([]byte(line), &report); err != nil {
t.Fatal(err)
}
found = true
}
}
if !found || !report.Visible || report.ConsoleVisible || report.SessionID != process.Identity().SessionID || !strings.EqualFold(report.Station+`\`+report.Desktop, interactiveDesktop) || !strings.EqualFold(report.Input, "default") {
t.Fatalf("GUI probe did not observe an interactive window: %+v output=%s", report, output.String())
}
})
}
}
func TestNativeHeadlessConsoleStillReceivesTERM_HP_DESKTOP_04(t *testing.T) {
manager, directory, probe := desktopFixture(t, false)
process, ctx := desktopProbeProcess(t, manager, directory, probe, false, true)
var output strings.Builder
for !strings.Contains(output.String(), "RVBOX_CONSOLE_READY") {
chunk, err := process.ReadOutput(ctx)
if err != nil {
t.Fatalf("console never became ready: %v %s", err, output.String())
}
output.Write(chunk.Data)
}
outcome, err := manager.Signal(ctx, process, supervisor.SignalTerm)
if err != nil || !outcome.Delivered || outcome.Escalated {
t.Fatalf("TERM lost native console delivery: %+v err=%v", outcome, err)
}
for {
chunk, err := process.ReadOutput(ctx)
if errors.Is(err, io.EOF) {
break
}
if err != nil {
t.Fatal(err)
}
output.Write(chunk.Data)
}
if !strings.Contains(output.String(), "RVBOX_CTRL_BREAK_OBSERVED") {
t.Fatalf("TERM never reached the registered handler: %s", output.String())
}
}
@@ -11,6 +11,7 @@ import (
"io"
"os"
"os/exec"
"runtime"
"strings"
"sync"
"syscall"
@@ -242,6 +243,13 @@ func openLauncherPipe(channel, suffix string, access uint32) (*os.File, error) {
}
func (manager *execSupervisor) startViaLauncher(ctx context.Context, spec supervisor.StartSpec, token winapi.Token, identity supervisor.EffectiveIdentity, launch LaunchPlan, cleanup func()) (supervisor.Process, error) {
desktop, err := desktopForIdentity(identity)
if err != nil {
if cleanup != nil {
cleanup()
}
return nil, err
}
pipes, err := newLauncherPipes(identity.UserSID)
if err != nil {
if cleanup != nil {
@@ -299,6 +307,7 @@ func (manager *execSupervisor) startViaLauncher(ctx context.Context, spec superv
return nil, err
}
startup := winapi.StartupInfoEx{StartupInfo: winapi.StartupInfo{Cb: uint32(unsafe.Sizeof(winapi.StartupInfoEx{}))}}
startup.Desktop = desktopPointer(desktop)
var launcherInfo winapi.ProcessInformation
flags := uint32(winapi.CREATE_SUSPENDED | winapi.CREATE_UNICODE_ENVIRONMENT | winapi.EXTENDED_STARTUPINFO_PRESENT | winapi.CREATE_NO_WINDOW)
if err := winapi.CreateProcessAsUser(token, launcherApplication, &launcherCommandUTF16[0], nil, nil, false, flags, nil, nil, &startup.StartupInfo, &launcherInfo); err != nil {
@@ -334,6 +343,9 @@ func (manager *execSupervisor) startViaLauncher(ctx context.Context, spec superv
return nil, fmt.Errorf("read launcher hello: %w", err)
}
if frame.Kind != launcherFrameHello {
if frame.Kind == launcherFrameAbort {
return nil, launcherAbortError(frame.Payload)
}
return nil, errors.New("launcher did not send hello first")
}
var hello launcherHello
@@ -343,6 +355,11 @@ func (manager *execSupervisor) startViaLauncher(ctx context.Context, spec superv
if hello.PID != expected.PID || hello.Creation != expected.Creation || hello.SessionID != expected.SessionID || hello.Effective != expected.UserSID {
return nil, errors.New("launcher hello identity mismatch")
}
if desktop != "" {
if err := validateInteractiveDesktop(hello.Desktop); err != nil {
return nil, err
}
}
requestPayload, err := marshalLauncherPayload(launcherRequest{ApplicationName: launch.ApplicationName, CommandLine: launch.CommandLine, WorkingDirectory: launch.WorkingDirectory, Environment: launch.Environment})
if err != nil {
return nil, err
@@ -355,6 +372,9 @@ func (manager *execSupervisor) startViaLauncher(ctx context.Context, spec superv
return nil, fmt.Errorf("read shell preparation: %w", err)
}
if frame.Kind != launcherFrameShellPrepared {
if frame.Kind == launcherFrameAbort {
return nil, launcherAbortError(frame.Payload)
}
return nil, errors.New("launcher did not prepare a shell")
}
var prepared launcherShellPrepared
@@ -457,7 +477,9 @@ func (manager *execSupervisor) startViaLauncher(ctx context.Context, spec superv
// private pipes, reports its immutable identity, creates the requested shell
// suspended, and waits for the service's durable release frame before running
// any command code.
func RunLauncher(_ context.Context, channel string) error {
func RunLauncher(_ context.Context, channel string) (resultErr error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
generation, err := launcherGeneration(channel)
if err != nil {
return err
@@ -467,6 +489,15 @@ func RunLauncher(_ context.Context, channel string) error {
return err
}
defer control.Close()
defer func() {
if resultErr != nil {
detail := resultErr.Error()
if len(detail) > 4096 {
detail = detail[:4096]
}
_ = writeLauncherFrame(control, launcherFrame{Kind: launcherFrameAbort, Generation: generation, Payload: []byte(detail)})
}
}()
stdin, err := openLauncherPipe(channel, "stdin", winapi.GENERIC_READ)
if err != nil {
return err
@@ -496,11 +527,15 @@ func RunLauncher(_ context.Context, channel string) error {
if err != nil {
return err
}
desktop, err := verifyCurrentInteractiveDesktop(sessionID)
if err != nil {
return err
}
creation, err := processCreation(winapi.CurrentProcess())
if err != nil {
return err
}
helloPayload, err := marshalLauncherPayload(launcherHello{PID: winapi.GetCurrentProcessId(), Creation: creation, SessionID: sessionID, Effective: user.User.Sid.String()})
helloPayload, err := marshalLauncherPayload(launcherHello{PID: winapi.GetCurrentProcessId(), Creation: creation, SessionID: sessionID, Effective: user.User.Sid.String(), Desktop: desktop})
if err != nil {
return err
}
@@ -550,14 +585,13 @@ func RunLauncher(_ context.Context, channel string) error {
if err := attributes.Update(winapi.PROC_THREAD_ATTRIBUTE_HANDLE_LIST, unsafe.Pointer(&childHandles[0]), uintptr(len(childHandles))*unsafe.Sizeof(childHandles[0])); err != nil {
return err
}
startup := winapi.StartupInfoEx{StartupInfo: winapi.StartupInfo{Cb: uint32(unsafe.Sizeof(winapi.StartupInfoEx{})), Flags: winapi.STARTF_USESTDHANDLES | winapi.STARTF_USESHOWWINDOW, ShowWindow: winapi.SW_HIDE, StdInput: childHandles[0], StdOutput: childHandles[1], StdErr: childHandles[2]}}
startup, flags := commandStartup(childHandles[0], childHandles[1], childHandles[2], desktop)
startup.ProcThreadAttributeList = attributes.List()
var shellInfo winapi.ProcessInformation
var environment *uint16
if len(request.Environment) > 0 {
environment = &request.Environment[0]
}
flags := uint32(winapi.CREATE_NEW_CONSOLE | winapi.CREATE_SUSPENDED | winapi.CREATE_UNICODE_ENVIRONMENT | winapi.EXTENDED_STARTUPINFO_PRESENT)
if err := winapi.CreateProcess(application, &commandLine[0], nil, nil, true, flags, environment, workingDirectory, &startup.StartupInfo, &shellInfo); err != nil {
return fmt.Errorf("create suspended shell: %w", err)
}
@@ -664,6 +698,10 @@ func openSignalPipe(channel string) (*os.File, error) {
}
func runSignalHelper(ctx context.Context, executable string, token winapi.Token, identity supervisor.EffectiveIdentity, targetPID uint32, targetCreation uint64) (bool, error) {
desktop, err := desktopForIdentity(identity)
if err != nil {
return false, err
}
if executable == "" {
var err error
executable, err = os.Executable()
@@ -695,6 +733,7 @@ func runSignalHelper(ctx context.Context, executable string, token winapi.Token,
return false, err
}
startup := winapi.StartupInfo{Cb: uint32(unsafe.Sizeof(winapi.StartupInfo{}))}
startup.Desktop = desktopPointer(desktop)
var info winapi.ProcessInformation
flags := uint32(winapi.CREATE_NO_WINDOW | winapi.CREATE_UNICODE_ENVIRONMENT)
if err := winapi.CreateProcessAsUser(token, application, &commandUTF16[0], nil, nil, false, flags, nil, nil, &startup, &info); err != nil {
@@ -14,6 +14,7 @@ type launcherHello struct {
Creation uint64 `json:"creation"`
SessionID uint32 `json:"session_id"`
Effective string `json:"effective_sid"`
Desktop string `json:"desktop,omitempty"`
}
type launcherRequest struct {
@@ -13,6 +13,7 @@ import (
"fmt"
"os"
"strings"
"sync"
"syscall"
"time"
"unsafe"
@@ -41,6 +42,13 @@ var (
procFreeConsole = kernel32.NewProc("FreeConsole")
procGenerateCtrlEvent = kernel32.NewProc("GenerateConsoleCtrlEvent")
procSetCtrlHandler = kernel32.NewProc("SetConsoleCtrlHandler")
consoleControlMu sync.Mutex
ignoreOwnConsoleEvent = winapi.NewCallback(func(event uint32) uintptr {
if event == 0 || event == 1 {
return 1
} // CTRL_C_EVENT / CTRL_BREAK_EVENT.
return 0
})
)
func stdinLineEnding() []byte { return []byte{'\r', '\n'} }
@@ -851,16 +859,30 @@ func sendControlBreak(pid uint32) (bool, error) {
if pid == 0 {
return false, errors.New("command has no verified console PID")
}
// Console attachment is process-wide. The service fallback must serialize
// concurrent requests; the normal route uses a separate helper process.
consoleControlMu.Lock()
defer consoleControlMu.Unlock()
// A console-subsystem test/helper may have its own headless console. It
// must detach before attaching to the verified command's private console.
procFreeConsole.Call()
if result, _, err := procAttachConsole.Call(uintptr(pid)); result == 0 {
if err == syscall.Errno(0) {
err = syscall.GetLastError()
}
return false, err
}
defer procFreeConsole.Call()
// Prevent the service/helper itself from acting on the generated event.
procSetCtrlHandler.Call(0, 1)
defer procSetCtrlHandler.Call(0, 0)
// NULL/TRUE ignores only Ctrl+C, not the Ctrl+Break sent below. Install a
// real handler after attachment (which resets the handler table), then
// detach before removing it so our own broadcast cannot terminate us.
if result, _, err := procSetCtrlHandler.Call(ignoreOwnConsoleEvent, 1); result == 0 {
procFreeConsole.Call()
return false, fmt.Errorf("protect console signal helper: %w", err)
}
defer func() {
procFreeConsole.Call()
procSetCtrlHandler.Call(ignoreOwnConsoleEvent, 0)
}()
result, _, err := procGenerateCtrlEvent.Call(1 /* CTRL_BREAK_EVENT */, 0)
if result == 0 {
if err == syscall.Errno(0) {