fix(windows): start a responsive tray immediately after installation
This commit is contained in:
1 parent
14cb3570c1
commit
d59b2d5463
13 files changed
+850
-106
No files matched your search
@@ -0,0 +1,15 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
// Keep the original (normally unelevated) interactive process alive while its
|
||||||
|
// UAC child installs. Only successful installation may start the user frontend.
|
||||||
|
func runInstallerSteps(install func() error, startTray func() error) error {
|
||||||
|
if err := install(); err != nil {
|
||||||
|
return fmt.Errorf("install RVBox: %w", err)
|
||||||
|
}
|
||||||
|
if err := startTray(); err != nil {
|
||||||
|
return fmt.Errorf("RVBox is installed, but its notification-area icon could not start: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestInstallerStartsTrayOnlyAfterSuccessfulElevation_HP_WINCLI_06(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
installErr error
|
||||||
|
trayErr error
|
||||||
|
wantCalls []string
|
||||||
|
}{
|
||||||
|
{"success", nil, nil, []string{"install", "tray"}},
|
||||||
|
{"UAC cancelled", errors.New("cancelled"), nil, []string{"install"}},
|
||||||
|
{"installation failed", errors.New("copy failed"), nil, []string{"install"}},
|
||||||
|
{"tray failed", nil, errors.New("no desktop"), []string{"install", "tray"}},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
var calls []string
|
||||||
|
err := runInstallerSteps(func() error { calls = append(calls, "install"); return tc.installErr }, func() error { calls = append(calls, "tray"); return tc.trayErr })
|
||||||
|
if !reflect.DeepEqual(calls, tc.wantCalls) {
|
||||||
|
t.Fatalf("calls = %v, want %v", calls, tc.wantCalls)
|
||||||
|
}
|
||||||
|
if tc.installErr != nil && !errors.Is(err, tc.installErr) || tc.trayErr != nil && !errors.Is(err, tc.trayErr) {
|
||||||
|
t.Fatalf("error lost its cause: %v", err)
|
||||||
|
}
|
||||||
|
if tc.installErr == nil && tc.trayErr == nil && err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if tc.trayErr != nil && !strings.Contains(err.Error(), "RVBox is installed") {
|
||||||
|
t.Fatalf("partial success is not explicit: %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
+104
-20
@@ -3,16 +3,21 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
"time"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
"github.com/rvbox/rvbox/internal/client/windowsservice"
|
"github.com/rvbox/rvbox/internal/client/windowsservice"
|
||||||
|
"github.com/rvbox/rvbox/internal/client/windowstray"
|
||||||
"golang.org/x/sys/windows"
|
"golang.org/x/sys/windows"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -22,8 +27,11 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
installerUser32 = syscall.NewLazyDLL("user32.dll")
|
installerUser32 = syscall.NewLazyDLL("user32.dll")
|
||||||
installerMessageBox = installerUser32.NewProc("MessageBoxW")
|
installerMessageBox = installerUser32.NewProc("MessageBoxW")
|
||||||
|
installerShellExecute = windows.NewLazySystemDLL("shell32.dll").NewProc("ShellExecuteExW")
|
||||||
|
installerCOMInitialize = windows.NewLazySystemDLL("ole32.dll").NewProc("CoInitializeEx")
|
||||||
|
installerCOMUninitialize = windows.NewLazySystemDLL("ole32.dll").NewProc("CoUninitialize")
|
||||||
)
|
)
|
||||||
|
|
||||||
// runInteractiveInstaller is the double-click entry point. It does no
|
// runInteractiveInstaller is the double-click entry point. It does no
|
||||||
@@ -35,21 +43,101 @@ func runInteractiveInstaller(_ io.Writer, _ io.Writer) error {
|
|||||||
showInstallerMessage("RVBox setup could not locate its executable.", installerErrorIcon)
|
showInstallerMessage("RVBox setup could not locate its executable.", installerErrorIcon)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
err = runInstallerSteps(func() error { return runElevatedInstaller(executable) }, startInstalledTray)
|
||||||
|
if err != nil {
|
||||||
|
showInstallerMessage(err.Error(), installerErrorIcon)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
showInstallerMessage("RVBox is installed and its Windows service has started.\n\nThe notification-area icon is available now; no sign-out or reboot is needed. Windows may place it under the hidden-icons arrow.", installerInfoIcon)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// shellExecuteInfo matches SHELLEXECUTEINFOW, including pointer-sized fields
|
||||||
|
// and native alignment on the supported Windows amd64 build.
|
||||||
|
type shellExecuteInfo struct {
|
||||||
|
Size uint32
|
||||||
|
Mask uint32
|
||||||
|
Window uintptr
|
||||||
|
Verb *uint16
|
||||||
|
File *uint16
|
||||||
|
Parameters *uint16
|
||||||
|
Directory *uint16
|
||||||
|
Show int32
|
||||||
|
Instance uintptr
|
||||||
|
IDList uintptr
|
||||||
|
Class *uint16
|
||||||
|
ClassKey uintptr
|
||||||
|
HotKey uint32
|
||||||
|
Icon uintptr
|
||||||
|
Process windows.Handle
|
||||||
|
}
|
||||||
|
|
||||||
|
func runElevatedInstaller(executable string) error {
|
||||||
|
runtime.LockOSThread()
|
||||||
|
defer runtime.UnlockOSThread()
|
||||||
|
// Shell extensions may require COM. Balance both S_OK and S_FALSE, while
|
||||||
|
// allowing a caller whose thread is already initialized in another mode.
|
||||||
|
hr, _, _ := installerCOMInitialize.Call(0, 2|4) // STA, disable OLE1 DDE.
|
||||||
|
if int32(hr) >= 0 {
|
||||||
|
defer installerCOMUninitialize.Call()
|
||||||
|
} else if uint32(hr) != 0x80010106 { // RPC_E_CHANGED_MODE
|
||||||
|
return fmt.Errorf("initialize setup shell: HRESULT %#x", uint32(hr))
|
||||||
|
}
|
||||||
file, err := windows.UTF16PtrFromString(executable)
|
file, err := windows.UTF16PtrFromString(executable)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
arguments, err := windows.UTF16PtrFromString("--install-default")
|
info := shellExecuteInfo{
|
||||||
if err != nil {
|
Size: uint32(unsafe.Sizeof(shellExecuteInfo{})),
|
||||||
return err
|
Mask: 0x40 | 0x100, // SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC.
|
||||||
|
Verb: installerUTF16("runas"), File: file,
|
||||||
|
Parameters: installerUTF16("--install-default"), Show: windows.SW_SHOWNORMAL,
|
||||||
}
|
}
|
||||||
if err := windows.ShellExecute(0, installerUTF16("runas"), file, arguments, nil, windows.SW_SHOWNORMAL); err != nil {
|
result, _, callErr := installerShellExecute.Call(uintptr(unsafe.Pointer(&info)))
|
||||||
showInstallerMessage("RVBox setup was cancelled or could not obtain administrator approval.\n\nNo changes were made.", installerErrorIcon)
|
if result == 0 {
|
||||||
return fmt.Errorf("request installer elevation: %w", err)
|
return fmt.Errorf("request installer elevation: %w", callErr)
|
||||||
|
}
|
||||||
|
if info.Process == 0 {
|
||||||
|
return errors.New("elevated setup did not return a process handle")
|
||||||
|
}
|
||||||
|
defer windows.CloseHandle(info.Process)
|
||||||
|
if _, err := windows.WaitForSingleObject(info.Process, windows.INFINITE); err != nil {
|
||||||
|
return fmt.Errorf("wait for elevated setup: %w", err)
|
||||||
|
}
|
||||||
|
var exitCode uint32
|
||||||
|
if err := windows.GetExitCodeProcess(info.Process, &exitCode); err != nil {
|
||||||
|
return fmt.Errorf("read elevated setup result: %w", err)
|
||||||
|
}
|
||||||
|
if exitCode != 0 {
|
||||||
|
return fmt.Errorf("elevated setup failed (exit code %d)", exitCode)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func packagedInstallPaths() (string, string) {
|
||||||
|
programFiles := os.Getenv("ProgramFiles")
|
||||||
|
if programFiles == "" {
|
||||||
|
programFiles = `C:\Program Files`
|
||||||
|
}
|
||||||
|
programData := os.Getenv("ProgramData")
|
||||||
|
if programData == "" {
|
||||||
|
programData = `C:\ProgramData`
|
||||||
|
}
|
||||||
|
return filepath.Join(programFiles, "RVBox", "rvbox.exe"), filepath.Join(programData, "RVBox", "client.toml")
|
||||||
|
}
|
||||||
|
|
||||||
|
func startInstalledTray() error {
|
||||||
|
executable, configPath := packagedInstallPaths()
|
||||||
|
command := exec.Command(executable, "--tray", "--config", configPath)
|
||||||
|
if err := command.Start(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_ = command.Process.Release()
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
return windowstray.WaitReady(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
// installPackagedDefault executes only in the UAC-elevated child. It preserves
|
// installPackagedDefault executes only in the UAC-elevated child. It preserves
|
||||||
// a pre-existing operator configuration, atomically updates the executable,
|
// a pre-existing operator configuration, atomically updates the executable,
|
||||||
// installs/updates the SCM service, and starts it.
|
// installs/updates the SCM service, and starts it.
|
||||||
@@ -59,7 +147,8 @@ func installPackagedDefault(_ io.Writer) error {
|
|||||||
showInstallerMessage("RVBox could not be installed.\n\n"+err.Error()+"\n\nNo existing configuration was replaced.", installerErrorIcon)
|
showInstallerMessage("RVBox could not be installed.\n\n"+err.Error()+"\n\nNo existing configuration was replaced.", installerErrorIcon)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
showInstallerMessage("RVBox is installed and its Windows service is starting.\n\nThe notification-area icon starts automatically at the next sign-in.", installerInfoIcon)
|
// The original interactive process waits for this child to exit, starts the
|
||||||
|
// tray with its own user token, then shows the single success message.
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,18 +160,13 @@ func installPackagedDefaultFiles() error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("locate installer executable: %w", err)
|
return fmt.Errorf("locate installer executable: %w", err)
|
||||||
}
|
}
|
||||||
programFiles := os.Getenv("ProgramFiles")
|
targetExecutable, configPath := packagedInstallPaths()
|
||||||
if programFiles == "" {
|
targetDirectory, configDirectory := filepath.Dir(targetExecutable), filepath.Dir(configPath)
|
||||||
programFiles = `C:\Program Files`
|
trayCtx, cancelTray := context.WithTimeout(context.Background(), 3*time.Second)
|
||||||
|
defer cancelTray()
|
||||||
|
if err := windowstray.CloseCurrent(trayCtx); err != nil {
|
||||||
|
return fmt.Errorf("close existing notification-area frontend: %w", err)
|
||||||
}
|
}
|
||||||
programData := os.Getenv("ProgramData")
|
|
||||||
if programData == "" {
|
|
||||||
programData = `C:\ProgramData`
|
|
||||||
}
|
|
||||||
targetDirectory := filepath.Join(programFiles, "RVBox")
|
|
||||||
targetExecutable := filepath.Join(targetDirectory, "rvbox.exe")
|
|
||||||
configDirectory := filepath.Join(programData, "RVBox")
|
|
||||||
configPath := filepath.Join(configDirectory, "client.toml")
|
|
||||||
|
|
||||||
// A running service can keep the prior executable open. Stop it before the
|
// A running service can keep the prior executable open. Stop it before the
|
||||||
// atomic replacement; a missing service is already a successful first run.
|
// atomic replacement; a missing service is already a successful first run.
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"runtime"
|
||||||
|
"testing"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestInstallerShellExecuteInfoLayout_HP_WINCLI_07(t *testing.T) {
|
||||||
|
if runtime.GOARCH != "amd64" {
|
||||||
|
t.Skip("v1 Windows executable is amd64")
|
||||||
|
}
|
||||||
|
var info shellExecuteInfo
|
||||||
|
if unsafe.Sizeof(info) != 112 || unsafe.Offsetof(info.Instance) != 56 || unsafe.Offsetof(info.Process) != 104 {
|
||||||
|
t.Fatalf("SHELLEXECUTEINFOW layout mismatch: size=%d instance=%d process=%d", unsafe.Sizeof(info), unsafe.Offsetof(info.Instance), unsafe.Offsetof(info.Process))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2291,7 +2291,14 @@ service start.
|
|||||||
Register the tray with the machine-wide `Run` key, not Task Scheduler and not
|
Register the tray with the machine-wide `Run` key, not Task Scheduler and not
|
||||||
service-created cross-session injection. Use one ACL-protected mutex per WTS
|
service-created cross-session injection. Use one ACL-protected mutex per WTS
|
||||||
session so each logged-in user gets at most one tray while multiple RDP/console
|
session so each logged-in user gets at most one tray while multiple RDP/console
|
||||||
sessions remain independent. Run its Win32 message pump on one locked OS thread,
|
sessions remain independent. The double-click installer keeps its original
|
||||||
|
interactive process alive, waits for the UAC child process's successful exit,
|
||||||
|
starts the installed tray with the original user's token, and waits up to ten
|
||||||
|
seconds for `Shell_NotifyIconGetRect` to confirm the registered icon before
|
||||||
|
showing success. A failed/cancelled installation must not start a tray; failure
|
||||||
|
to start the tray must explicitly report the already-installed service rather
|
||||||
|
than claiming complete success. No sign-out or reboot is required.
|
||||||
|
Run its Win32 message pump on one locked OS thread,
|
||||||
recreate the icon after `TaskbarCreated`, and use bounded nonblocking IPC/UI
|
recreate the icon after `TaskbarCreated`, and use bounded nonblocking IPC/UI
|
||||||
channels. The tooltip shows connection/readiness/dirty state without payloads.
|
channels. The tooltip shows connection/readiness/dirty state without payloads.
|
||||||
`Exit` closes only that tray. The service continues through tray exit, user
|
`Exit` closes only that tray. The service continues through tray exit, user
|
||||||
@@ -2300,6 +2307,15 @@ logoff, Explorer restart, and periods with no interactive user.
|
|||||||
Expose a versioned, length-bounded local named-pipe tray protocol with
|
Expose a versioned, length-bounded local named-pipe tray protocol with
|
||||||
`PIPE_REJECT_REMOTE_CLIENTS`, explicit SYSTEM/Administrators/interactive-user
|
`PIPE_REJECT_REMOTE_CLIENTS`, explicit SYSTEM/Administrators/interactive-user
|
||||||
ACLs, peer PID/session/token inspection, deadlines, and no command payloads.
|
ACLs, peer PID/session/token inspection, deadlines, and no command payloads.
|
||||||
|
Check enabled, non-deny-only primary-token administrator groups rather than
|
||||||
|
passing a primary token to `CheckTokenMembership`. Use cancellable overlapped
|
||||||
|
connect/read/write operations, a three-second total client-request timeout,
|
||||||
|
five-second per-peer server deadline, and at most eight connected peers.
|
||||||
|
Drain cancelled I/O before releasing its OVERLAPPED/event/buffer. Do not use
|
||||||
|
`FlushFileBuffers` as a request/response acknowledgement: rejection before a
|
||||||
|
request read can deadlock both peers. Keep a response alive until client
|
||||||
|
disconnect or the peer deadline. Create the icon independently of IPC and
|
||||||
|
post bounded status/action responses back to the UI thread.
|
||||||
The tray never reads the spool/database. Read-only status may be served to a
|
The tray never reads the spool/database. Read-only status may be served to a
|
||||||
local interactive user. For a mutating service/config action, the tray launches
|
local interactive user. For a mutating service/config action, the tray launches
|
||||||
the narrow canonical `configure-service` mode with UAC; that helper sends one
|
the narrow canonical `configure-service` mode with UAC; that helper sends one
|
||||||
|
|||||||
@@ -83,7 +83,11 @@ The same signed `rvbox.exe` has explicit `service`, `tray`, `install-service`,
|
|||||||
`configure-service`, per-command launcher, and signal-
|
`configure-service`, per-command launcher, and signal-
|
||||||
helper modes. Internal modes require SCM state or a service-created launch
|
helper modes. Internal modes require SCM state or a service-created launch
|
||||||
proof. Task Scheduler is not used. The installer registers an unelevated per-
|
proof. Task Scheduler is not used. The installer registers an unelevated per-
|
||||||
user tray launch through the machine-wide `Run` key. One tray may run in each
|
user tray launch through the machine-wide `Run` key. The original interactive
|
||||||
|
installer waits for its UAC child to finish successfully, starts the installed
|
||||||
|
tray in its own desktop session, and verifies that Shell accepted the icon
|
||||||
|
before showing success. No sign-out or reboot is required. The service does
|
||||||
|
not inject a tray into another session. One tray may run in each
|
||||||
logged-in session; its exit, failure, disablement, or Explorer restart does not
|
logged-in session; its exit, failure, disablement, or Explorer restart does not
|
||||||
stop the service or commands.
|
stop the service or commands.
|
||||||
|
|
||||||
@@ -98,7 +102,12 @@ persistent executable or process.
|
|||||||
|
|
||||||
The tray is a thin frontend over a local-only named pipe. It never opens the
|
The tray is a thin frontend over a local-only named pipe. It never opens the
|
||||||
SQLite store/spool or owns a server connection. The pipe rejects remote clients,
|
SQLite store/spool or owns a server connection. The pipe rejects remote clients,
|
||||||
has explicit ACLs, and the service impersonates each caller for authorization.
|
has explicit ACLs, and the service verifies each caller's PID, session and
|
||||||
|
primary-token groups for authorization. Deny-only administrator membership in
|
||||||
|
a filtered token does not authorize mutations. Overlapped I/O has bounded
|
||||||
|
deadlines/cancellation; neither peer uses an unbounded pipe flush. The icon is
|
||||||
|
created before any IPC, with status/actions exchanged asynchronously so a
|
||||||
|
stopped or stalled service cannot hide the icon or freeze its message loop.
|
||||||
Read-only health/status is available to an interactive local user. Service
|
Read-only health/status is available to an interactive local user. Service
|
||||||
start/stop/restart, Automatic/Manual startup changes, config editing, incident
|
start/stop/restart, Automatic/Manual startup changes, config editing, incident
|
||||||
resolution, and other machine-wide mutations require a locally elevated
|
resolution, and other machine-wide mutations require a locally elevated
|
||||||
|
|||||||
@@ -170,6 +170,49 @@ The Windows artifact is linked with the GUI subsystem (`-H=windowsgui`) so
|
|||||||
service, launcher, and tray startup do not flash a console. Human-facing modes
|
service, launcher, and tray startup do not flash a console. Human-facing modes
|
||||||
still attach to a parent console explicitly when one exists.
|
still attach to a parent console explicitly when one exists.
|
||||||
|
|
||||||
|
### Focused native tray and installer regression checks
|
||||||
|
|
||||||
|
`internal/client/windowstray/native_windows_test.go` contains real Win32 tests,
|
||||||
|
not Linux stubs: enabled/deny-only primary-token peer checks, one-shot status,
|
||||||
|
rejection before reading a request, malformed responses, stalled-peer deadlines,
|
||||||
|
eight idle peers plus a bounded ninth request, shutdown cancellation, native
|
||||||
|
`NOTIFYICONDATAW` layout, and actual icon creation/message-loop/close under GC.
|
||||||
|
Build its executable in Docker:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose -f deploy/compose.yaml run --rm toolchain \
|
||||||
|
env CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go test -c \
|
||||||
|
-o .test-runs/RUN/windowstray.test.exe ./internal/client/windowstray
|
||||||
|
```
|
||||||
|
|
||||||
|
Use the checksum-verified fixture transfer route to place it at a **distinct
|
||||||
|
test-only path**, never the installed SCM service executable. On a prepared
|
||||||
|
interactive fixture, run it through the server control socket:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
rvc run --shell cmd CLIENT \
|
||||||
|
'@C:\Users\Public\RVBoxTrayTests.exe -test.v -test.run TestNativeTray -test.timeout 45s'
|
||||||
|
```
|
||||||
|
|
||||||
|
Require `PASS` and the durable command lifecycle
|
||||||
|
`COMMAND_SUCCEEDED`; the presence of a process or a successful RPC alone is not
|
||||||
|
test success. The UI case briefly creates/removes its own test icon. Session 0
|
||||||
|
runs verify rejection/transport but skip the actual desktop-window case, so
|
||||||
|
they do not substitute for the interactive run.
|
||||||
|
|
||||||
|
`cmd/rvbox/installer_flow_test.go` checks install-before-tray ordering, cancelled/
|
||||||
|
failed elevation, and explicit partial success when tray startup fails. The
|
||||||
|
native installer structure-layout test is in `installer_windows_test.go`.
|
||||||
|
For the real double-click acceptance route, preserve UAC policy: the unelevated
|
||||||
|
parent must wait for its elevated child to exit successfully, start the installed
|
||||||
|
tray with the original user's token, and confirm a registered icon before its
|
||||||
|
single success dialog. Verify both service and tray identities, current-session
|
||||||
|
startup without a reboot, Run-key sign-in startup, duplicate prevention, and
|
||||||
|
continued service operation when only the tray exits. The tray must remain
|
||||||
|
visible/responsive when its service is absent or its IPC peer stalls. Windows
|
||||||
|
may put a new application icon under its hidden-icons arrow; do not rewrite the
|
||||||
|
user's global notification-area preferences to force pinning.
|
||||||
|
|
||||||
Suite output is capped by the checked-in harness policy (10 MiB by default) and
|
Suite output is capped by the checked-in harness policy (10 MiB by default) and
|
||||||
stored as `artifacts/suite.log`. A failed run remains inspectable and can be
|
stored as `artifacts/suite.log`. A failed run remains inspectable and can be
|
||||||
moved back to `ready` with `recover`, then resumed with the same run ID and
|
moved back to `ready` with `recover`, then resumed with the same run ID and
|
||||||
|
|||||||
@@ -0,0 +1,242 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package windowstray
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
winapi "golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
func trayTestName() string {
|
||||||
|
return fmt.Sprintf(`\\.\pipe\rvbox-tray-test-%d-%d`, winapi.GetCurrentProcessId(), time.Now().UnixNano())
|
||||||
|
}
|
||||||
|
|
||||||
|
func trayTestServer(t *testing.T, handler func(context.Context, winapi.Handle)) string {
|
||||||
|
t.Helper()
|
||||||
|
name := trayTestName()
|
||||||
|
pipe, err := newTrayPipe(name)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
defer close(done)
|
||||||
|
defer winapi.CloseHandle(pipe)
|
||||||
|
if connectTrayPipe(ctx, pipe) == nil {
|
||||||
|
handler(ctx, pipe)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
t.Cleanup(func() {
|
||||||
|
cancel()
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Error("pipe server did not shut down")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNativeTrayRequestRoundTrip_HP_WINTRAY_02(t *testing.T) {
|
||||||
|
var session uint32
|
||||||
|
if err := winapi.ProcessIdToSessionId(winapi.GetCurrentProcessId(), &session); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
seen := make(chan Peer, 1)
|
||||||
|
name := trayTestServer(t, func(ctx context.Context, pipe winapi.Handle) {
|
||||||
|
// serveTrayPipe owns its handle; the test server owns the original.
|
||||||
|
var duplicate winapi.Handle
|
||||||
|
process := winapi.CurrentProcess()
|
||||||
|
if err := winapi.DuplicateHandle(process, pipe, process, &duplicate, 0, false, winapi.DUPLICATE_SAME_ACCESS); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
serveTrayPipe(ctx, duplicate, func(_ context.Context, peer Peer, _ Frame) (Frame, error) {
|
||||||
|
seen <- peer
|
||||||
|
return Frame{Action: ActionStatus, Payload: []byte("native status OK")}, nil
|
||||||
|
})
|
||||||
|
})
|
||||||
|
response, err := requestNamedTrayPipe(context.Background(), name, Frame{Action: ActionStatus})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if session == 0 {
|
||||||
|
if !strings.Contains(string(response.Payload), "not interactive") {
|
||||||
|
t.Fatalf("Session 0 rejection = %q", response.Payload)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if string(response.Payload) != "native status OK" {
|
||||||
|
t.Fatalf("response = %q", response.Payload)
|
||||||
|
}
|
||||||
|
peer := <-seen
|
||||||
|
if !peer.TokenVerified || !peer.Interactive || peer.SessionID != session || peer.PID != winapi.GetCurrentProcessId() {
|
||||||
|
t.Fatalf("peer = %#v", peer)
|
||||||
|
}
|
||||||
|
var token winapi.Token
|
||||||
|
if err := winapi.OpenProcessToken(winapi.CurrentProcess(), winapi.TOKEN_QUERY, &token); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer token.Close()
|
||||||
|
if peer.Administrator != token.IsElevated() {
|
||||||
|
t.Fatalf("enabled administrator membership=%t, elevated=%t", peer.Administrator, token.IsElevated())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNativeTrayStalledServerDeadline_BH_WINTRAY_02(t *testing.T) {
|
||||||
|
name := trayTestServer(t, func(ctx context.Context, _ winapi.Handle) { <-ctx.Done() })
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
|
||||||
|
defer cancel()
|
||||||
|
start := time.Now()
|
||||||
|
_, err := requestNamedTrayPipe(ctx, name, Frame{Action: ActionStatus})
|
||||||
|
if !errors.Is(err, context.DeadlineExceeded) || time.Since(start) > 2*time.Second {
|
||||||
|
t.Fatalf("stalled request = %v after %s", err, time.Since(start))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNativeTrayMalformedResponse_BH_WINTRAY_03(t *testing.T) {
|
||||||
|
name := trayTestServer(t, func(ctx context.Context, pipe winapi.Handle) {
|
||||||
|
if _, err := readTrayFrame(ctx, pipe); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, _ = transferTrayPipe(ctx, pipe, []byte("invalid frame"), true)
|
||||||
|
_, _ = transferTrayPipe(ctx, pipe, make([]byte, 1), false)
|
||||||
|
})
|
||||||
|
_, err := requestNamedTrayPipe(context.Background(), name, Frame{Action: ActionStatus})
|
||||||
|
if !errors.Is(err, ErrInvalidFrame) {
|
||||||
|
t.Fatalf("malformed response = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNativeTrayRejectionBeforeRead_BH_WINTRAY_05(t *testing.T) {
|
||||||
|
name := trayTestServer(t, func(ctx context.Context, pipe winapi.Handle) {
|
||||||
|
// Reproduce an identity rejection before reading the request. A client
|
||||||
|
// FlushFileBuffers here would wait forever for a server read, while the
|
||||||
|
// server's flush waits for a client response read.
|
||||||
|
writeTrayResponse(ctx, pipe, ErrInvalidPeer)
|
||||||
|
buffer := make([]byte, maxFrameBytes)
|
||||||
|
for {
|
||||||
|
if _, err := transferTrayPipe(ctx, pipe, buffer, false); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
response, err := requestNamedTrayPipe(context.Background(), name, Frame{Action: ActionStatus})
|
||||||
|
if err != nil || !strings.Contains(string(response.Payload), ErrInvalidPeer.Error()) {
|
||||||
|
t.Fatalf("pre-read rejection = %q, %v", response.Payload, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNativeTrayIdlePeersBoundedShutdown_BH_WINTRAY_04(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
name := trayTestName()
|
||||||
|
done := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
done <- serveNamedTrayPipe(ctx, name, func(context.Context, Peer, Frame) (Frame, error) { return Frame{Action: ActionStatus}, nil })
|
||||||
|
}()
|
||||||
|
var clients []winapi.Handle
|
||||||
|
t.Cleanup(func() {
|
||||||
|
cancel()
|
||||||
|
for _, handle := range clients {
|
||||||
|
_ = winapi.CloseHandle(handle)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
path, _ := winapi.UTF16PtrFromString(name)
|
||||||
|
for i := 0; i < pipeInstances; i++ {
|
||||||
|
deadline := time.Now().Add(2 * time.Second)
|
||||||
|
for {
|
||||||
|
handle, err := winapi.CreateFile(path, winapi.GENERIC_READ|winapi.GENERIC_WRITE, 0, nil, winapi.OPEN_EXISTING, winapi.FILE_FLAG_OVERLAPPED, 0)
|
||||||
|
if err == nil {
|
||||||
|
clients = append(clients, handle)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
time.Sleep(5 * time.Millisecond)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
requestCtx, requestCancel := context.WithTimeout(ctx, 150*time.Millisecond)
|
||||||
|
_, err := requestNamedTrayPipe(requestCtx, name, Frame{Action: ActionStatus})
|
||||||
|
requestCancel()
|
||||||
|
if !errors.Is(err, context.DeadlineExceeded) {
|
||||||
|
t.Fatalf("ninth stalled peer = %v", err)
|
||||||
|
}
|
||||||
|
cancel()
|
||||||
|
select {
|
||||||
|
case err := <-done:
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("service did not cancel its accept and idle reads")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNativeTrayIconLayout_HP_WINTRAY_03(t *testing.T) {
|
||||||
|
if runtime.GOARCH != "amd64" {
|
||||||
|
t.Skip("v1 Windows executable is amd64")
|
||||||
|
}
|
||||||
|
var icon trayIconData
|
||||||
|
if unsafe.Sizeof(icon) != 976 || unsafe.Offsetof(icon.InfoData) != 304 || unsafe.Offsetof(icon.TimeoutOrVersion) != 816 || unsafe.Offsetof(icon.InfoTitle) != 820 || unsafe.Offsetof(icon.InfoFlags) != 948 || unsafe.Offsetof(icon.Guid) != 952 {
|
||||||
|
t.Fatalf("NOTIFYICONDATAW layout mismatch: size=%d info=%d title=%d flags=%d", unsafe.Sizeof(icon), unsafe.Offsetof(icon.InfoData), unsafe.Offsetof(icon.InfoTitle), unsafe.Offsetof(icon.InfoFlags))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNativeTrayWindowLifecycle_HP_WINTRAY_04(t *testing.T) {
|
||||||
|
var session uint32
|
||||||
|
if err := winapi.ProcessIdToSessionId(winapi.GetCurrentProcessId(), &session); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if session == 0 {
|
||||||
|
t.Skip("requires the real interactive Windows fixture desktop")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
ready := make(chan *trayWindow, 1)
|
||||||
|
done := make(chan error, 1)
|
||||||
|
go runTrayMessageLoop(ctx, io.Discard, "RVBox native tray test", ready, done)
|
||||||
|
var window *trayWindow
|
||||||
|
select {
|
||||||
|
case window = <-ready:
|
||||||
|
case err := <-done:
|
||||||
|
t.Fatalf("tray startup failed: %v", err)
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("tray startup blocked before creating its icon")
|
||||||
|
}
|
||||||
|
defer procPostMessage.Call(window.hwnd, wmClose, 0, 0)
|
||||||
|
readyCtx, readyCancel := context.WithTimeout(ctx, time.Second)
|
||||||
|
defer readyCancel()
|
||||||
|
if err := WaitReady(readyCtx); err != nil {
|
||||||
|
t.Fatalf("Shell did not confirm its registered icon: %v", err)
|
||||||
|
}
|
||||||
|
send := user32Tray.NewProc("SendMessageTimeoutW")
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
runtime.GC()
|
||||||
|
var result uintptr
|
||||||
|
ok, _, err := send.Call(window.hwnd, 0, 0, 0, 2, 1000, uintptr(unsafe.Pointer(&result)))
|
||||||
|
if ok == 0 {
|
||||||
|
t.Fatalf("window message loop stopped responding after GC: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_, _, _ = procPostMessage.Call(window.hwnd, wmClose, 0, 0)
|
||||||
|
select {
|
||||||
|
case err := <-done:
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("tray did not process close on its owning thread")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package windowstray
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"runtime"
|
||||||
|
|
||||||
|
winapi "golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Each operation owns its OVERLAPPED/event until cancellation has actually
|
||||||
|
// completed. Closing a synchronous pipe from another goroutine does not provide
|
||||||
|
// the bounded shutdown/deadline contract needed by a desktop frontend.
|
||||||
|
func trayOverlapped(ctx context.Context, handle winapi.Handle, start func(*winapi.Overlapped, *uint32) error) (uint32, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
event, err := winapi.CreateEvent(nil, 1, 0, nil)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer winapi.CloseHandle(event)
|
||||||
|
overlapped := winapi.Overlapped{HEvent: event}
|
||||||
|
var transferred uint32
|
||||||
|
err = start(&overlapped, &transferred)
|
||||||
|
if !errors.Is(err, winapi.ERROR_IO_PENDING) {
|
||||||
|
return transferred, err
|
||||||
|
}
|
||||||
|
cancelled := make(chan struct{})
|
||||||
|
stop := context.AfterFunc(ctx, func() {
|
||||||
|
_ = winapi.CancelIoEx(handle, &overlapped)
|
||||||
|
close(cancelled)
|
||||||
|
})
|
||||||
|
err = winapi.GetOverlappedResult(handle, &overlapped, &transferred, true)
|
||||||
|
if !stop() {
|
||||||
|
<-cancelled
|
||||||
|
}
|
||||||
|
if err != nil && ctx.Err() != nil {
|
||||||
|
return transferred, ctx.Err()
|
||||||
|
}
|
||||||
|
return transferred, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func connectTrayPipe(ctx context.Context, handle winapi.Handle) error {
|
||||||
|
_, err := trayOverlapped(ctx, handle, func(overlapped *winapi.Overlapped, _ *uint32) error {
|
||||||
|
err := winapi.ConnectNamedPipe(handle, overlapped)
|
||||||
|
if errors.Is(err, winapi.ERROR_PIPE_CONNECTED) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func transferTrayPipe(ctx context.Context, handle winapi.Handle, buffer []byte, write bool) (uint32, error) {
|
||||||
|
n, err := trayOverlapped(ctx, handle, func(overlapped *winapi.Overlapped, transferred *uint32) error {
|
||||||
|
if write {
|
||||||
|
return winapi.WriteFile(handle, buffer, transferred, overlapped)
|
||||||
|
}
|
||||||
|
return winapi.ReadFile(handle, buffer, transferred, overlapped)
|
||||||
|
})
|
||||||
|
runtime.KeepAlive(buffer)
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
@@ -18,3 +18,7 @@ func Serve(context.Context, Handler) error { return ErrUnsupported }
|
|||||||
func Request(context.Context, Frame) (Frame, error) { return Frame{}, ErrUnsupported }
|
func Request(context.Context, Frame) (Frame, error) { return Frame{}, ErrUnsupported }
|
||||||
|
|
||||||
func Run(context.Context, io.Writer) error { return ErrUnsupported }
|
func Run(context.Context, io.Writer) error { return ErrUnsupported }
|
||||||
|
|
||||||
|
func WaitReady(context.Context) error { return ErrUnsupported }
|
||||||
|
|
||||||
|
func CloseCurrent(context.Context) error { return ErrUnsupported }
|
||||||
@@ -13,7 +13,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
@@ -23,6 +23,8 @@ import (
|
|||||||
const (
|
const (
|
||||||
pipeBufferBytes = 64 << 10
|
pipeBufferBytes = 64 << 10
|
||||||
pipeInstances = 8
|
pipeInstances = 8
|
||||||
|
requestTimeout = 3 * time.Second
|
||||||
|
peerTimeout = 5 * time.Second
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -34,41 +36,53 @@ var (
|
|||||||
// run before any interactive user logs in; in that state no client can pass
|
// run before any interactive user logs in; in that state no client can pass
|
||||||
// the interactive-peer authorization check.
|
// the interactive-peer authorization check.
|
||||||
func Serve(ctx context.Context, handler Handler) error {
|
func Serve(ctx context.Context, handler Handler) error {
|
||||||
|
return serveNamedTrayPipe(ctx, PipeName, handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
func serveNamedTrayPipe(ctx context.Context, name string, handler Handler) error {
|
||||||
if handler == nil {
|
if handler == nil {
|
||||||
return errors.New("tray handler is required")
|
return errors.New("tray handler is required")
|
||||||
}
|
}
|
||||||
|
ctx, cancel := context.WithCancel(ctx)
|
||||||
|
var workers sync.WaitGroup
|
||||||
|
defer func() { cancel(); workers.Wait() }()
|
||||||
|
active := make(chan struct{}, pipeInstances)
|
||||||
for {
|
for {
|
||||||
pipe, err := newTrayPipe()
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("create tray pipe: %w", err)
|
|
||||||
}
|
|
||||||
connected := make(chan error, 1)
|
|
||||||
go func() { connected <- winapi.ConnectNamedPipe(winapi.Handle(pipe.Fd()), nil) }()
|
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
_ = pipe.Close()
|
|
||||||
return nil
|
return nil
|
||||||
case err := <-connected:
|
case active <- struct{}{}:
|
||||||
if err != nil && !errors.Is(err, winapi.ERROR_PIPE_CONNECTED) {
|
|
||||||
_ = pipe.Close()
|
|
||||||
if ctx.Err() != nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
go serveTrayPipe(ctx, pipe, handler)
|
|
||||||
}
|
}
|
||||||
|
pipe, err := newTrayPipe(name)
|
||||||
|
if err != nil {
|
||||||
|
<-active
|
||||||
|
return fmt.Errorf("create tray pipe: %w", err)
|
||||||
|
}
|
||||||
|
if err := connectTrayPipe(ctx, pipe); err != nil {
|
||||||
|
_ = winapi.CloseHandle(pipe)
|
||||||
|
<-active
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
workers.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer workers.Done()
|
||||||
|
defer func() { <-active }()
|
||||||
|
serveTrayPipe(ctx, pipe, handler)
|
||||||
|
}()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func newTrayPipe() (*os.File, error) {
|
func newTrayPipe(pipeName string) (winapi.Handle, error) {
|
||||||
name, err := winapi.UTF16PtrFromString(PipeName)
|
name, err := winapi.UTF16PtrFromString(pipeName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return 0, err
|
||||||
}
|
}
|
||||||
descriptor, err := winapi.SecurityDescriptorFromString(pipeSDDL)
|
descriptor, err := winapi.SecurityDescriptorFromString(pipeSDDL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return 0, err
|
||||||
}
|
}
|
||||||
attributes := &winapi.SecurityAttributes{
|
attributes := &winapi.SecurityAttributes{
|
||||||
Length: uint32(unsafe.Sizeof(winapi.SecurityAttributes{})),
|
Length: uint32(unsafe.Sizeof(winapi.SecurityAttributes{})),
|
||||||
@@ -78,47 +92,49 @@ func newTrayPipe() (*os.File, error) {
|
|||||||
// client rejection belongs to the latter; placing it in open mode produces
|
// client rejection belongs to the latter; placing it in open mode produces
|
||||||
// ERROR_INVALID_PARAMETER on Windows. We inspect the client token directly
|
// ERROR_INVALID_PARAMETER on Windows. We inspect the client token directly
|
||||||
// and never impersonate it, so no SQOS/impersonation flag is needed here.
|
// and never impersonate it, so no SQOS/impersonation flag is needed here.
|
||||||
openMode := uint32(winapi.PIPE_ACCESS_DUPLEX)
|
openMode := uint32(winapi.PIPE_ACCESS_DUPLEX | winapi.FILE_FLAG_OVERLAPPED)
|
||||||
pipeMode := uint32(winapi.PIPE_TYPE_MESSAGE | winapi.PIPE_READMODE_MESSAGE | winapi.PIPE_WAIT | winapi.PIPE_REJECT_REMOTE_CLIENTS)
|
pipeMode := uint32(winapi.PIPE_TYPE_MESSAGE | winapi.PIPE_READMODE_MESSAGE | winapi.PIPE_WAIT | winapi.PIPE_REJECT_REMOTE_CLIENTS)
|
||||||
handle, err := winapi.CreateNamedPipe(name, openMode, pipeMode, pipeInstances, pipeBufferBytes, pipeBufferBytes, 0, attributes)
|
handle, err := winapi.CreateNamedPipe(name, openMode, pipeMode, pipeInstances, pipeBufferBytes, pipeBufferBytes, 0, attributes)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return 0, err
|
||||||
}
|
}
|
||||||
return os.NewFile(uintptr(handle), "rvbox-tray-pipe"), nil
|
return handle, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func serveTrayPipe(ctx context.Context, pipe *os.File, handler Handler) {
|
func serveTrayPipe(ctx context.Context, pipe winapi.Handle, handler Handler) {
|
||||||
if pipe == nil {
|
defer winapi.CloseHandle(pipe)
|
||||||
return
|
ctx, cancel := context.WithTimeout(ctx, peerTimeout)
|
||||||
}
|
defer cancel()
|
||||||
defer pipe.Close()
|
respond := func(value any) {
|
||||||
// A blocked Read must be interrupted when service shutdown cancels ctx.
|
writeTrayResponse(ctx, pipe, value)
|
||||||
readDone := make(chan struct{})
|
// Keep buffered response bytes alive until the one-shot client closes.
|
||||||
go func() {
|
// Unlike FlushFileBuffers this read is cancellable and deadline-bounded;
|
||||||
select {
|
// no additional acknowledgement frame is required on the wire.
|
||||||
case <-ctx.Done():
|
buffer := make([]byte, maxFrameBytes)
|
||||||
_ = pipe.Close()
|
for ctx.Err() == nil {
|
||||||
case <-readDone:
|
n, err := transferTrayPipe(ctx, pipe, buffer, false)
|
||||||
|
if err != nil && !errors.Is(err, winapi.ERROR_MORE_DATA) || n == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}()
|
}
|
||||||
defer close(readDone)
|
peer, err := peerFromPipe(pipe)
|
||||||
peer, err := peerFromPipe(winapi.Handle(pipe.Fd()))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeTrayResponse(pipe, err)
|
respond(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
request, err := readTrayFrame(pipe)
|
request, err := readTrayFrame(ctx, pipe)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeTrayResponse(pipe, err)
|
respond(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := Authorize(peer, request.Action); err != nil {
|
if err := Authorize(peer, request.Action); err != nil {
|
||||||
writeTrayResponse(pipe, err)
|
respond(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
response, err := handler(ctx, peer, request)
|
response, err := handler(ctx, peer, request)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeTrayResponse(pipe, err)
|
respond(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if response.Action == 0 {
|
if response.Action == 0 {
|
||||||
@@ -127,22 +143,25 @@ func serveTrayPipe(ctx context.Context, pipe *os.File, handler Handler) {
|
|||||||
if response.Action != ActionStatus {
|
if response.Action != ActionStatus {
|
||||||
response = Frame{Action: ActionStatus}
|
response = Frame{Action: ActionStatus}
|
||||||
}
|
}
|
||||||
writeTrayResponse(pipe, response)
|
respond(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
func readTrayFrame(reader io.Reader) (Frame, error) {
|
func readTrayFrame(ctx context.Context, pipe winapi.Handle) (Frame, error) {
|
||||||
buffer := make([]byte, maxFrameBytes)
|
buffer := make([]byte, maxFrameBytes)
|
||||||
count, err := reader.Read(buffer)
|
count, err := transferTrayPipe(ctx, pipe, buffer, false)
|
||||||
|
if errors.Is(err, winapi.ERROR_MORE_DATA) {
|
||||||
|
return Frame{}, ErrFrameTooLarge
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Frame{}, err
|
return Frame{}, err
|
||||||
}
|
}
|
||||||
if count == len(buffer) {
|
if int(count) == len(buffer) {
|
||||||
return Frame{}, ErrFrameTooLarge
|
return Frame{}, ErrFrameTooLarge
|
||||||
}
|
}
|
||||||
return Decode(buffer[:count])
|
return Decode(buffer[:count])
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeTrayResponse(writer *os.File, value any) {
|
func writeTrayResponse(ctx context.Context, pipe winapi.Handle, value any) {
|
||||||
frame := Frame{Action: ActionStatus}
|
frame := Frame{Action: ActionStatus}
|
||||||
switch response := value.(type) {
|
switch response := value.(type) {
|
||||||
case Frame:
|
case Frame:
|
||||||
@@ -158,8 +177,7 @@ func writeTrayResponse(writer *os.File, value any) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
_, _ = writer.Write(encoded)
|
_, _ = transferTrayPipe(ctx, pipe, encoded, true)
|
||||||
_ = winapi.FlushFileBuffers(winapi.Handle(writer.Fd()))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func peerFromPipe(pipe winapi.Handle) (Peer, error) {
|
func peerFromPipe(pipe winapi.Handle) (Peer, error) {
|
||||||
@@ -193,10 +211,19 @@ func peerFromPipe(pipe winapi.Handle) (Peer, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return Peer{}, ErrInvalidPeer
|
return Peer{}, ErrInvalidPeer
|
||||||
}
|
}
|
||||||
admin, err := token.IsMember(adminSID)
|
groups, err := token.GetTokenGroups()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Peer{}, ErrInvalidPeer
|
return Peer{}, ErrInvalidPeer
|
||||||
}
|
}
|
||||||
|
// OpenProcessToken returns a primary token; CheckTokenMembership requires
|
||||||
|
// an impersonation token. Inspect enabled groups directly, excluding the
|
||||||
|
// deny-only Administrators SID in a normal split-token user's token.
|
||||||
|
admin := false
|
||||||
|
for _, group := range groups.AllGroups() {
|
||||||
|
if group.Sid != nil && group.Sid.Equals(adminSID) && group.Attributes&winapi.SE_GROUP_ENABLED != 0 && group.Attributes&winapi.SE_GROUP_USE_FOR_DENY_ONLY == 0 {
|
||||||
|
admin = true
|
||||||
|
}
|
||||||
|
}
|
||||||
sid := user.User.Sid.String()
|
sid := user.User.Sid.String()
|
||||||
return Peer{PID: pid, SessionID: sessionID, SID: sid, TokenVerified: true, Interactive: sessionID != 0, Administrator: admin, System: sid == "S-1-5-18"}, nil
|
return Peer{PID: pid, SessionID: sessionID, SID: sid, TokenVerified: true, Interactive: sessionID != 0, Administrator: admin, System: sid == "S-1-5-18"}, nil
|
||||||
}
|
}
|
||||||
@@ -205,22 +232,28 @@ func peerFromPipe(pipe winapi.Handle) (Peer, error) {
|
|||||||
// It retries only the transient ERROR_PIPE_BUSY state and never falls back to
|
// It retries only the transient ERROR_PIPE_BUSY state and never falls back to
|
||||||
// an arbitrary filesystem/socket path.
|
// an arbitrary filesystem/socket path.
|
||||||
func Request(ctx context.Context, request Frame) (Frame, error) {
|
func Request(ctx context.Context, request Frame) (Frame, error) {
|
||||||
|
return requestNamedTrayPipe(ctx, PipeName, request)
|
||||||
|
}
|
||||||
|
|
||||||
|
func requestNamedTrayPipe(ctx context.Context, pipeName string, request Frame) (Frame, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, requestTimeout)
|
||||||
|
defer cancel()
|
||||||
encoded, err := Encode(request)
|
encoded, err := Encode(request)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Frame{}, err
|
return Frame{}, err
|
||||||
}
|
}
|
||||||
var pipe *os.File
|
var pipe winapi.Handle
|
||||||
for {
|
for {
|
||||||
if ctx.Err() != nil {
|
if ctx.Err() != nil {
|
||||||
return Frame{}, ctx.Err()
|
return Frame{}, ctx.Err()
|
||||||
}
|
}
|
||||||
name, nameErr := winapi.UTF16PtrFromString(PipeName)
|
name, nameErr := winapi.UTF16PtrFromString(pipeName)
|
||||||
if nameErr != nil {
|
if nameErr != nil {
|
||||||
return Frame{}, nameErr
|
return Frame{}, nameErr
|
||||||
}
|
}
|
||||||
handle, openErr := winapi.CreateFile(name, winapi.GENERIC_READ|winapi.GENERIC_WRITE, 0, nil, winapi.OPEN_EXISTING, 0, 0)
|
handle, openErr := winapi.CreateFile(name, winapi.GENERIC_READ|winapi.GENERIC_WRITE, 0, nil, winapi.OPEN_EXISTING, winapi.FILE_FLAG_OVERLAPPED, 0)
|
||||||
if openErr == nil {
|
if openErr == nil {
|
||||||
pipe = os.NewFile(uintptr(handle), "rvbox-tray-client")
|
pipe = handle
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
if !errors.Is(openErr, winapi.ERROR_PIPE_BUSY) {
|
if !errors.Is(openErr, winapi.ERROR_PIPE_BUSY) {
|
||||||
@@ -234,14 +267,15 @@ func Request(ctx context.Context, request Frame) (Frame, error) {
|
|||||||
case <-timer.C:
|
case <-timer.C:
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
defer pipe.Close()
|
defer winapi.CloseHandle(pipe)
|
||||||
state := uint32(winapi.PIPE_READMODE_MESSAGE)
|
state := uint32(winapi.PIPE_READMODE_MESSAGE)
|
||||||
_ = winapi.SetNamedPipeHandleState(winapi.Handle(pipe.Fd()), &state, nil, nil)
|
if err := winapi.SetNamedPipeHandleState(pipe, &state, nil, nil); err != nil {
|
||||||
if _, err := pipe.Write(encoded); err != nil {
|
|
||||||
return Frame{}, err
|
return Frame{}, err
|
||||||
}
|
}
|
||||||
if err := winapi.FlushFileBuffers(winapi.Handle(pipe.Fd())); err != nil {
|
if n, err := transferTrayPipe(ctx, pipe, encoded, true); err != nil {
|
||||||
return Frame{}, err
|
return Frame{}, err
|
||||||
|
} else if int(n) != len(encoded) {
|
||||||
|
return Frame{}, io.ErrShortWrite
|
||||||
}
|
}
|
||||||
return readTrayFrame(pipe)
|
return readTrayFrame(ctx, pipe)
|
||||||
}
|
}
|
||||||
@@ -15,9 +15,11 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
"time"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
@@ -32,6 +34,7 @@ const (
|
|||||||
wmLButtonDblClick = 0x0203
|
wmLButtonDblClick = 0x0203
|
||||||
wmApp = 0x8000
|
wmApp = 0x8000
|
||||||
trayMessage = wmApp + 1
|
trayMessage = wmApp + 1
|
||||||
|
trayResponse = wmApp + 2
|
||||||
trayIconID = 1
|
trayIconID = 1
|
||||||
trayNIMAdd = 0
|
trayNIMAdd = 0
|
||||||
trayNIMModify = 1
|
trayNIMModify = 1
|
||||||
@@ -50,6 +53,7 @@ const (
|
|||||||
var (
|
var (
|
||||||
ErrTrayAlreadyRunning = errors.New("RVBox tray is already running in this session")
|
ErrTrayAlreadyRunning = errors.New("RVBox tray is already running in this session")
|
||||||
user32Tray = syscall.NewLazyDLL("user32.dll")
|
user32Tray = syscall.NewLazyDLL("user32.dll")
|
||||||
|
kernel32Tray = syscall.NewLazyDLL("kernel32.dll")
|
||||||
shell32Tray = syscall.NewLazyDLL("shell32.dll")
|
shell32Tray = syscall.NewLazyDLL("shell32.dll")
|
||||||
procRegisterClassEx = user32Tray.NewProc("RegisterClassExW")
|
procRegisterClassEx = user32Tray.NewProc("RegisterClassExW")
|
||||||
procCreateWindowEx = user32Tray.NewProc("CreateWindowExW")
|
procCreateWindowEx = user32Tray.NewProc("CreateWindowExW")
|
||||||
@@ -69,9 +73,11 @@ var (
|
|||||||
procDestroyMenu = user32Tray.NewProc("DestroyMenu")
|
procDestroyMenu = user32Tray.NewProc("DestroyMenu")
|
||||||
procGetCursorPos = user32Tray.NewProc("GetCursorPos")
|
procGetCursorPos = user32Tray.NewProc("GetCursorPos")
|
||||||
procSetForeground = user32Tray.NewProc("SetForegroundWindow")
|
procSetForeground = user32Tray.NewProc("SetForegroundWindow")
|
||||||
procGetModuleHandle = user32Tray.NewProc("GetModuleHandleW")
|
procGetModuleHandle = kernel32Tray.NewProc("GetModuleHandleW")
|
||||||
procRegisterMessage = user32Tray.NewProc("RegisterWindowMessageW")
|
procRegisterMessage = user32Tray.NewProc("RegisterWindowMessageW")
|
||||||
procShellNotify = shell32Tray.NewProc("Shell_NotifyIconW")
|
procShellNotify = shell32Tray.NewProc("Shell_NotifyIconW")
|
||||||
|
procShellIconRect = shell32Tray.NewProc("Shell_NotifyIconGetRect")
|
||||||
|
procFindWindow = user32Tray.NewProc("FindWindowW")
|
||||||
trayCallback = syscall.NewCallback(trayWindowProc)
|
trayCallback = syscall.NewCallback(trayWindowProc)
|
||||||
trayWindows sync.Map // hwnd -> *trayWindow
|
trayWindows sync.Map // hwnd -> *trayWindow
|
||||||
taskbarCreatedMessage uint32
|
taskbarCreatedMessage uint32
|
||||||
@@ -113,9 +119,10 @@ type trayIconData struct {
|
|||||||
Tip [128]uint16
|
Tip [128]uint16
|
||||||
State uint32
|
State uint32
|
||||||
StateMask uint32
|
StateMask uint32
|
||||||
InfoFlags uint32
|
|
||||||
InfoTitle [64]uint16
|
|
||||||
InfoData [256]uint16
|
InfoData [256]uint16
|
||||||
|
TimeoutOrVersion uint32
|
||||||
|
InfoTitle [64]uint16
|
||||||
|
InfoFlags uint32
|
||||||
Guid [16]byte
|
Guid [16]byte
|
||||||
BalloonIcon uintptr
|
BalloonIcon uintptr
|
||||||
}
|
}
|
||||||
@@ -127,6 +134,15 @@ type trayWindow struct {
|
|||||||
tooltip string
|
tooltip string
|
||||||
output io.Writer
|
output io.Writer
|
||||||
closeOnce sync.Once
|
closeOnce sync.Once
|
||||||
|
ctx context.Context
|
||||||
|
responses chan trayActionResult
|
||||||
|
pending bool // UI-thread owned; at most one bounded request at a time.
|
||||||
|
}
|
||||||
|
|
||||||
|
type trayActionResult struct {
|
||||||
|
action Action
|
||||||
|
response Frame
|
||||||
|
err error
|
||||||
}
|
}
|
||||||
|
|
||||||
// Run starts one notification icon for the current logged-in session. It
|
// Run starts one notification icon for the current logged-in session. It
|
||||||
@@ -138,24 +154,27 @@ func Run(ctx context.Context, output io.Writer) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer winapi.CloseHandle(mutex)
|
defer winapi.CloseHandle(mutex)
|
||||||
response, err := Request(ctx, Frame{Action: ActionStatus})
|
ctx, cancel := context.WithCancel(ctx)
|
||||||
tooltip := "RVBox service unavailable"
|
defer cancel()
|
||||||
if err == nil {
|
|
||||||
tooltip = string(response.Payload)
|
|
||||||
}
|
|
||||||
if tooltip == "" {
|
|
||||||
tooltip = "RVBox service"
|
|
||||||
}
|
|
||||||
ready := make(chan *trayWindow, 1)
|
ready := make(chan *trayWindow, 1)
|
||||||
done := make(chan error, 1)
|
done := make(chan error, 1)
|
||||||
go runTrayMessageLoop(output, tooltip, ready, done)
|
// Icon creation never waits for the daemon or the network. Status refresh
|
||||||
|
// is asynchronous after the icon exists, including when the service is down.
|
||||||
|
go runTrayMessageLoop(ctx, output, "RVBox service", ready, done)
|
||||||
var window *trayWindow
|
var window *trayWindow
|
||||||
select {
|
select {
|
||||||
case window = <-ready:
|
case window = <-ready:
|
||||||
case err := <-done:
|
case err := <-done:
|
||||||
return err
|
return err
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
return nil
|
// Do not abandon an in-progress startup and leave an orphan icon.
|
||||||
|
select {
|
||||||
|
case window = <-ready:
|
||||||
|
_, _, _ = procPostMessage.Call(window.hwnd, wmClose, 0, 0)
|
||||||
|
return <-done
|
||||||
|
case err := <-done:
|
||||||
|
return err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
@@ -177,7 +196,7 @@ func acquireTrayMutex() (winapi.Handle, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
mutex, err := winapi.CreateMutex(nil, true, name)
|
mutex, err := winapi.CreateMutex(nil, false, name)
|
||||||
if errors.Is(err, winapi.ERROR_ALREADY_EXISTS) {
|
if errors.Is(err, winapi.ERROR_ALREADY_EXISTS) {
|
||||||
if mutex != 0 {
|
if mutex != 0 {
|
||||||
_ = winapi.CloseHandle(mutex)
|
_ = winapi.CloseHandle(mutex)
|
||||||
@@ -190,14 +209,25 @@ func acquireTrayMutex() (winapi.Handle, error) {
|
|||||||
return mutex, nil
|
return mutex, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func runTrayMessageLoop(output io.Writer, tooltip string, ready chan<- *trayWindow, done chan<- error) {
|
func runTrayMessageLoop(ctx context.Context, output io.Writer, tooltip string, ready chan<- *trayWindow, done chan<- error) {
|
||||||
|
runtime.LockOSThread()
|
||||||
|
defer runtime.UnlockOSThread()
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
done <- nil
|
||||||
|
return
|
||||||
|
}
|
||||||
className, err := winapi.UTF16PtrFromString("RVBoxTrayWindowV1")
|
className, err := winapi.UTF16PtrFromString("RVBoxTrayWindowV1")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
done <- err
|
done <- err
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
instance, _, _ := procGetModuleHandle.Call(0)
|
instance, _, _ := procGetModuleHandle.Call(0)
|
||||||
icon, _, _ := procLoadIcon.Call(0, uintptr(trayIDIApplication))
|
// Release builds embed the application's icon as resource 1. Unit-test
|
||||||
|
// binaries have no resource, so retain the standard icon as a fallback.
|
||||||
|
icon, _, _ := procLoadIcon.Call(instance, 1)
|
||||||
|
if icon == 0 {
|
||||||
|
icon, _, _ = procLoadIcon.Call(0, uintptr(trayIDIApplication))
|
||||||
|
}
|
||||||
cursor, _, _ := procLoadCursor.Call(0, uintptr(trayIDCArrow))
|
cursor, _, _ := procLoadCursor.Call(0, uintptr(trayIDCArrow))
|
||||||
class := trayClass{CbSize: uint32(unsafe.Sizeof(trayClass{})), WndProc: trayCallback, HInstance: instance, HIcon: icon, HCursor: cursor, ClassName: className, HIconSm: icon}
|
class := trayClass{CbSize: uint32(unsafe.Sizeof(trayClass{})), WndProc: trayCallback, HInstance: instance, HIcon: icon, HCursor: cursor, ClassName: className, HIconSm: icon}
|
||||||
if result, _, callErr := procRegisterClassEx.Call(uintptr(unsafe.Pointer(&class))); result == 0 && !errors.Is(callErr, winapi.ERROR_CLASS_ALREADY_EXISTS) {
|
if result, _, callErr := procRegisterClassEx.Call(uintptr(unsafe.Pointer(&class))); result == 0 && !errors.Is(callErr, winapi.ERROR_CLASS_ALREADY_EXISTS) {
|
||||||
@@ -210,9 +240,9 @@ func runTrayMessageLoop(output io.Writer, tooltip string, ready chan<- *trayWind
|
|||||||
done <- callErr
|
done <- callErr
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
window := &trayWindow{hwnd: hwnd, class: className, tooltip: tooltip, output: output}
|
window := &trayWindow{hwnd: hwnd, class: className, tooltip: tooltip, output: output, ctx: ctx, responses: make(chan trayActionResult, 1)}
|
||||||
window.icon = trayIconData{CbSize: uint32(unsafe.Sizeof(trayIconData{})), HWnd: hwnd, UID: trayIconID, UFlags: trayNIFMessage | trayNIFIcon | trayNIFTip, UCallbackMessage: trayMessage, HIcon: icon}
|
window.icon = trayIconData{CbSize: uint32(unsafe.Sizeof(trayIconData{})), HWnd: hwnd, UID: trayIconID, UFlags: trayNIFMessage | trayNIFIcon | trayNIFTip, UCallbackMessage: trayMessage, HIcon: icon}
|
||||||
copy(window.icon.Tip[:], winapi.StringToUTF16(tooltip))
|
copy(window.icon.Tip[:len(window.icon.Tip)-1], winapi.StringToUTF16(tooltip))
|
||||||
trayWindows.Store(hwnd, window)
|
trayWindows.Store(hwnd, window)
|
||||||
messageName, _ := winapi.UTF16PtrFromString("TaskbarCreated")
|
messageName, _ := winapi.UTF16PtrFromString("TaskbarCreated")
|
||||||
registeredMessage, _, _ := procRegisterMessage.Call(uintptr(unsafe.Pointer(messageName)))
|
registeredMessage, _, _ := procRegisterMessage.Call(uintptr(unsafe.Pointer(messageName)))
|
||||||
@@ -225,6 +255,7 @@ func runTrayMessageLoop(output io.Writer, tooltip string, ready chan<- *trayWind
|
|||||||
}
|
}
|
||||||
_, _, _ = procShowWindow.Call(hwnd, traySWHide)
|
_, _, _ = procShowWindow.Call(hwnd, traySWHide)
|
||||||
ready <- window
|
ready <- window
|
||||||
|
window.action(ActionStatus)
|
||||||
for {
|
for {
|
||||||
var message trayMessageRecord
|
var message trayMessageRecord
|
||||||
result, _, getErr := procGetMessage.Call(uintptr(unsafe.Pointer(&message)), 0, 0, 0)
|
result, _, getErr := procGetMessage.Call(uintptr(unsafe.Pointer(&message)), 0, 0, 0)
|
||||||
@@ -262,6 +293,11 @@ func trayWindowProc(hwnd uintptr, message uint32, wParam, lParam uintptr) uintpt
|
|||||||
window.action(Action(uint16(wParam)))
|
window.action(Action(uint16(wParam)))
|
||||||
}
|
}
|
||||||
return 0
|
return 0
|
||||||
|
case trayResponse:
|
||||||
|
if window != nil {
|
||||||
|
window.applyResponse()
|
||||||
|
}
|
||||||
|
return 0
|
||||||
case trayMessage:
|
case trayMessage:
|
||||||
if window != nil && (uint32(lParam) == wmRButtonUp || uint32(lParam) == wmLButtonDblClick) {
|
if window != nil && (uint32(lParam) == wmRButtonUp || uint32(lParam) == wmLButtonDblClick) {
|
||||||
window.showMenu()
|
window.showMenu()
|
||||||
@@ -283,7 +319,7 @@ func (window *trayWindow) addIcon() error {
|
|||||||
window.icon.UFlags = trayNIFMessage | trayNIFIcon | trayNIFTip
|
window.icon.UFlags = trayNIFMessage | trayNIFIcon | trayNIFTip
|
||||||
if result, _, err := procShellNotify.Call(uintptr(trayNIMAdd), uintptr(unsafe.Pointer(&window.icon))); result == 0 {
|
if result, _, err := procShellNotify.Call(uintptr(trayNIMAdd), uintptr(unsafe.Pointer(&window.icon))); result == 0 {
|
||||||
if err == syscall.Errno(0) {
|
if err == syscall.Errno(0) {
|
||||||
err = syscall.GetLastError()
|
err = errors.New("Shell_NotifyIconW did not accept the notification icon")
|
||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -329,8 +365,38 @@ func (window *trayWindow) action(action Action) {
|
|||||||
_, _, _ = procDestroyWindow.Call(window.hwnd)
|
_, _, _ = procDestroyWindow.Call(window.hwnd)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
response, err := Request(context.Background(), Frame{Action: action})
|
if window.pending {
|
||||||
if err != nil {
|
return
|
||||||
|
}
|
||||||
|
window.pending = true
|
||||||
|
go func() {
|
||||||
|
response, err := Request(window.ctx, Frame{Action: action})
|
||||||
|
select {
|
||||||
|
case window.responses <- trayActionResult{action: action, response: response, err: err}:
|
||||||
|
_, _, _ = procPostMessage.Call(window.hwnd, trayResponse, 0, 0)
|
||||||
|
case <-window.ctx.Done():
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (window *trayWindow) applyResponse() {
|
||||||
|
var result trayActionResult
|
||||||
|
select {
|
||||||
|
case result = <-window.responses:
|
||||||
|
default:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
window.pending = false
|
||||||
|
action, response := result.action, result.response
|
||||||
|
if result.err != nil {
|
||||||
|
if isServiceMutation(action) {
|
||||||
|
// A stopped service has no pipe to answer Start. The same narrow
|
||||||
|
// UAC helper is valid both for absent IPC and denied authorization.
|
||||||
|
if err := runElevatedServiceAction(action); err == nil {
|
||||||
|
window.setTooltip("RVBox elevation requested")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
window.setTooltip("RVBox service unavailable")
|
window.setTooltip("RVBox service unavailable")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -351,6 +417,59 @@ func (window *trayWindow) action(action Action) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WaitReady is used only by the interactive installer in the same desktop
|
||||||
|
// session. It confirms Shell has accepted an actual icon, not merely that a
|
||||||
|
// child process was spawned. It never opens daemon config or state.
|
||||||
|
func WaitReady(ctx context.Context) error {
|
||||||
|
class, _ := winapi.UTF16PtrFromString("RVBoxTrayWindowV1")
|
||||||
|
type identifier struct {
|
||||||
|
Size uint32
|
||||||
|
HWnd uintptr
|
||||||
|
UID uint32
|
||||||
|
GUID [16]byte
|
||||||
|
}
|
||||||
|
type rectangle struct{ Left, Top, Right, Bottom int32 }
|
||||||
|
timer := time.NewTicker(50 * time.Millisecond)
|
||||||
|
defer timer.Stop()
|
||||||
|
for {
|
||||||
|
hwnd, _, _ := procFindWindow.Call(uintptr(unsafe.Pointer(class)), 0)
|
||||||
|
if hwnd != 0 {
|
||||||
|
id := identifier{Size: uint32(unsafe.Sizeof(identifier{})), HWnd: hwnd, UID: trayIconID}
|
||||||
|
var rect rectangle
|
||||||
|
result, _, _ := procShellIconRect.Call(uintptr(unsafe.Pointer(&id)), uintptr(unsafe.Pointer(&rect)))
|
||||||
|
if int32(result) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
case <-timer.C:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CloseCurrent lets an elevated installer update the canonical executable
|
||||||
|
// without leaving this desktop's old frontend holding the image open. It is
|
||||||
|
// deliberately a same-session window message, not service session injection.
|
||||||
|
func CloseCurrent(ctx context.Context) error {
|
||||||
|
class, _ := winapi.UTF16PtrFromString("RVBoxTrayWindowV1")
|
||||||
|
timer := time.NewTicker(50 * time.Millisecond)
|
||||||
|
defer timer.Stop()
|
||||||
|
for {
|
||||||
|
hwnd, _, _ := procFindWindow.Call(uintptr(unsafe.Pointer(class)), 0)
|
||||||
|
if hwnd == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
_, _, _ = procPostMessage.Call(hwnd, wmClose, 0, 0)
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
case <-timer.C:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func isServiceMutation(action Action) bool {
|
func isServiceMutation(action Action) bool {
|
||||||
return action == ActionStartService || action == ActionStopService || action == ActionRestartService || action == ActionSetAutomatic || action == ActionSetManual
|
return action == ActionStartService || action == ActionStopService || action == ActionRestartService || action == ActionSetAutomatic || action == ActionSetManual
|
||||||
}
|
}
|
||||||
@@ -418,7 +537,7 @@ func (window *trayWindow) setTooltip(value string) {
|
|||||||
for index := range window.icon.Tip {
|
for index := range window.icon.Tip {
|
||||||
window.icon.Tip[index] = 0
|
window.icon.Tip[index] = 0
|
||||||
}
|
}
|
||||||
copy(window.icon.Tip[:], winapi.StringToUTF16(value))
|
copy(window.icon.Tip[:len(window.icon.Tip)-1], winapi.StringToUTF16(value))
|
||||||
_, _, _ = procShellNotify.Call(uintptr(trayNIMModify), uintptr(unsafe.Pointer(&window.icon)))
|
_, _, _ = procShellNotify.Call(uintptr(trayNIMModify), uintptr(unsafe.Pointer(&window.icon)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -269,6 +269,60 @@ layer = "unit"
|
|||||||
status = "implemented"
|
status = "implemented"
|
||||||
tests = ["internal/client/windowstray/protocol_test.go:TestTrayFrameRoundTripAndPayloadBounds_HP_WINTRAY_01"]
|
tests = ["internal/client/windowstray/protocol_test.go:TestTrayFrameRoundTripAndPayloadBounds_HP_WINTRAY_01"]
|
||||||
|
|
||||||
|
[[requirements]]
|
||||||
|
id = "HP-WINCLI-06"
|
||||||
|
layer = "unit"
|
||||||
|
status = "implemented"
|
||||||
|
tests = ["cmd/rvbox/installer_flow_test.go:TestInstallerStartsTrayOnlyAfterSuccessfulElevation_HP_WINCLI_06"]
|
||||||
|
|
||||||
|
[[requirements]]
|
||||||
|
id = "HP-WINCLI-07"
|
||||||
|
layer = "unit"
|
||||||
|
status = "implemented"
|
||||||
|
tests = ["cmd/rvbox/installer_windows_test.go:TestInstallerShellExecuteInfoLayout_HP_WINCLI_07"]
|
||||||
|
|
||||||
|
[[requirements]]
|
||||||
|
id = "HP-WINTRAY-02"
|
||||||
|
layer = "integration"
|
||||||
|
status = "implemented"
|
||||||
|
tests = ["internal/client/windowstray/native_windows_test.go:TestNativeTrayRequestRoundTrip_HP_WINTRAY_02"]
|
||||||
|
|
||||||
|
[[requirements]]
|
||||||
|
id = "HP-WINTRAY-03"
|
||||||
|
layer = "unit"
|
||||||
|
status = "implemented"
|
||||||
|
tests = ["internal/client/windowstray/native_windows_test.go:TestNativeTrayIconLayout_HP_WINTRAY_03"]
|
||||||
|
|
||||||
|
[[requirements]]
|
||||||
|
id = "HP-WINTRAY-04"
|
||||||
|
layer = "integration"
|
||||||
|
status = "implemented"
|
||||||
|
tests = ["internal/client/windowstray/native_windows_test.go:TestNativeTrayWindowLifecycle_HP_WINTRAY_04"]
|
||||||
|
|
||||||
|
[[requirements]]
|
||||||
|
id = "BH-WINTRAY-02"
|
||||||
|
layer = "integration"
|
||||||
|
status = "implemented"
|
||||||
|
tests = ["internal/client/windowstray/native_windows_test.go:TestNativeTrayStalledServerDeadline_BH_WINTRAY_02"]
|
||||||
|
|
||||||
|
[[requirements]]
|
||||||
|
id = "BH-WINTRAY-03"
|
||||||
|
layer = "integration"
|
||||||
|
status = "implemented"
|
||||||
|
tests = ["internal/client/windowstray/native_windows_test.go:TestNativeTrayMalformedResponse_BH_WINTRAY_03"]
|
||||||
|
|
||||||
|
[[requirements]]
|
||||||
|
id = "BH-WINTRAY-04"
|
||||||
|
layer = "integration"
|
||||||
|
status = "implemented"
|
||||||
|
tests = ["internal/client/windowstray/native_windows_test.go:TestNativeTrayIdlePeersBoundedShutdown_BH_WINTRAY_04"]
|
||||||
|
|
||||||
|
[[requirements]]
|
||||||
|
id = "BH-WINTRAY-05"
|
||||||
|
layer = "integration"
|
||||||
|
status = "implemented"
|
||||||
|
tests = ["internal/client/windowstray/native_windows_test.go:TestNativeTrayRejectionBeforeRead_BH_WINTRAY_05"]
|
||||||
|
|
||||||
[[requirements]]
|
[[requirements]]
|
||||||
id = "BH-WINTRAY-01"
|
id = "BH-WINTRAY-01"
|
||||||
layer = "unit"
|
layer = "unit"
|
||||||
|
|||||||
Reference in new issue
Block a user