//go:build windows package windowstray // This file is the small native service endpoint. It intentionally uses one // request per pipe connection: the tray is a presentation client, not a // long-lived command channel, and a bounded connection makes cancellation and // peer verification straightforward. The service never hands the tray a // store handle or command payload. import ( "context" "errors" "fmt" "io" "sync" "time" "unsafe" winapi "golang.org/x/sys/windows" ) const ( pipeBufferBytes = 64 << 10 pipeInstances = 8 requestTimeout = 3 * time.Second peerTimeout = 5 * time.Second ) var ( ErrUnsupported = errors.New("Windows tray IPC is unavailable on this platform") pipeSDDL = "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GRGW;;;IU)" ) // Serve accepts bounded tray requests until ctx is cancelled. It is safe to // run before any interactive user logs in; in that state no client can pass // the interactive-peer authorization check. 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 { 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 { select { case <-ctx.Done(): return nil case active <- struct{}{}: } 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(pipeName string) (winapi.Handle, error) { name, err := winapi.UTF16PtrFromString(pipeName) if err != nil { return 0, err } descriptor, err := winapi.SecurityDescriptorFromString(pipeSDDL) if err != nil { return 0, err } attributes := &winapi.SecurityAttributes{ Length: uint32(unsafe.Sizeof(winapi.SecurityAttributes{})), SecurityDescriptor: descriptor, } // CreateNamedPipe has separate open-mode and pipe-mode arguments. Remote // client rejection belongs to the latter; placing it in open mode produces // ERROR_INVALID_PARAMETER on Windows. We inspect the client token directly // and never impersonate it, so no SQOS/impersonation flag is needed here. 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) handle, err := winapi.CreateNamedPipe(name, openMode, pipeMode, pipeInstances, pipeBufferBytes, pipeBufferBytes, 0, attributes) if err != nil { return 0, err } return handle, nil } func serveTrayPipe(ctx context.Context, pipe winapi.Handle, handler Handler) { defer winapi.CloseHandle(pipe) ctx, cancel := context.WithTimeout(ctx, peerTimeout) defer cancel() respond := func(value any) { writeTrayResponse(ctx, pipe, value) // Keep buffered response bytes alive until the one-shot client closes. // Unlike FlushFileBuffers this read is cancellable and deadline-bounded; // no additional acknowledgement frame is required on the wire. buffer := make([]byte, maxFrameBytes) for ctx.Err() == nil { n, err := transferTrayPipe(ctx, pipe, buffer, false) if err != nil && !errors.Is(err, winapi.ERROR_MORE_DATA) || n == 0 { break } } } peer, err := peerFromPipe(pipe) if err != nil { respond(err) return } request, err := readTrayFrame(ctx, pipe) if err != nil { respond(err) return } if err := Authorize(peer, request.Action); err != nil { respond(err) return } response, err := handler(ctx, peer, request) if err != nil { respond(err) return } if response.Action == 0 { response.Action = ActionStatus } if response.Action != ActionStatus { response = Frame{Action: ActionStatus} } respond(response) } func readTrayFrame(ctx context.Context, pipe winapi.Handle) (Frame, error) { buffer := make([]byte, maxFrameBytes) count, err := transferTrayPipe(ctx, pipe, buffer, false) if errors.Is(err, winapi.ERROR_MORE_DATA) { return Frame{}, ErrFrameTooLarge } if err != nil { return Frame{}, err } if int(count) == len(buffer) { return Frame{}, ErrFrameTooLarge } return Decode(buffer[:count]) } func writeTrayResponse(ctx context.Context, pipe winapi.Handle, value any) { frame := Frame{Action: ActionStatus} switch response := value.(type) { case Frame: frame = response case error: message := response.Error() if len(message) > maxPayloadBytes { message = message[:maxPayloadBytes] } frame.Payload = []byte("error: " + message) } encoded, err := Encode(frame) if err != nil { return } _, _ = transferTrayPipe(ctx, pipe, encoded, true) } func peerFromPipe(pipe winapi.Handle) (Peer, error) { if pipe == 0 || pipe == winapi.InvalidHandle { return Peer{}, ErrInvalidPeer } var pid uint32 if err := winapi.GetNamedPipeClientProcessId(pipe, &pid); err != nil || pid == 0 { return Peer{}, ErrInvalidPeer } process, err := winapi.OpenProcess(winapi.PROCESS_QUERY_LIMITED_INFORMATION, false, pid) if err != nil { return Peer{}, ErrInvalidPeer } defer winapi.CloseHandle(process) var token winapi.Token if err := winapi.OpenProcessToken(process, winapi.TOKEN_QUERY, &token); err != nil { return Peer{}, ErrInvalidPeer } defer token.Close() user, err := token.GetTokenUser() if err != nil || user.User.Sid == nil { return Peer{}, ErrInvalidPeer } var sessionID uint32 var returned uint32 if err := winapi.GetTokenInformation(token, winapi.TokenSessionId, (*byte)(unsafe.Pointer(&sessionID)), uint32(unsafe.Sizeof(sessionID)), &returned); err != nil || returned != uint32(unsafe.Sizeof(sessionID)) { return Peer{}, ErrInvalidPeer } adminSID, err := winapi.CreateWellKnownSid(winapi.WinBuiltinAdministratorsSid) if err != nil { return Peer{}, ErrInvalidPeer } groups, err := token.GetTokenGroups() if err != nil { 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() return Peer{PID: pid, SessionID: sessionID, SID: sid, TokenVerified: true, Interactive: sessionID != 0, Administrator: admin, System: sid == "S-1-5-18"}, nil } // Request opens exactly one local pipe connection and exchanges one frame. // It retries only the transient ERROR_PIPE_BUSY state and never falls back to // an arbitrary filesystem/socket path. 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) if err != nil { return Frame{}, err } var pipe winapi.Handle for { if ctx.Err() != nil { return Frame{}, ctx.Err() } name, nameErr := winapi.UTF16PtrFromString(pipeName) if nameErr != nil { return Frame{}, nameErr } handle, openErr := winapi.CreateFile(name, winapi.GENERIC_READ|winapi.GENERIC_WRITE, 0, nil, winapi.OPEN_EXISTING, winapi.FILE_FLAG_OVERLAPPED, 0) if openErr == nil { pipe = handle break } if !errors.Is(openErr, winapi.ERROR_PIPE_BUSY) { return Frame{}, openErr } timer := time.NewTimer(100 * time.Millisecond) select { case <-ctx.Done(): timer.Stop() return Frame{}, ctx.Err() case <-timer.C: } } defer winapi.CloseHandle(pipe) state := uint32(winapi.PIPE_READMODE_MESSAGE) if err := winapi.SetNamedPipeHandleState(pipe, &state, nil, nil); err != nil { return Frame{}, err } if n, err := transferTrayPipe(ctx, pipe, encoded, true); err != nil { return Frame{}, err } else if int(n) != len(encoded) { return Frame{}, io.ErrShortWrite } return readTrayFrame(ctx, pipe) }