Skip to content

Commit f6b6155

Browse files
committed
Handle invalid Windows console handles
1 parent 2b0f38f commit f6b6155

3 files changed

Lines changed: 26 additions & 12 deletions

File tree

go.mod

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
module UWP-TCP-Con
22

33
go 1.25
4+
5+
require golang.org/x/sys v0.30.0

internal/cli/terminal.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
//go:build !windows
2+
13
package cli
24

35
import (

internal/cli/terminal_windows.go

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,47 @@
1+
//go:build windows
2+
13
package cli
24

35
import (
4-
"syscall"
6+
"errors"
7+
8+
"golang.org/x/sys/windows"
59
)
610

711
type terminalState struct {
8-
mode uint32
12+
handle windows.Handle
13+
mode uint32
914
}
1015

1116
func makeRaw(fd int) (*terminalState, error) {
12-
handle := syscall.Handle(fd)
17+
handle, err := windows.GetStdHandle(windows.STD_INPUT_HANDLE)
18+
if err != nil {
19+
return nil, err
20+
}
1321
var original uint32
14-
if err := syscall.GetConsoleMode(handle, &original); err != nil {
22+
if err := windows.GetConsoleMode(handle, &original); err != nil {
23+
if errors.Is(err, windows.ERROR_INVALID_HANDLE) {
24+
return nil, nil
25+
}
1526
return nil, err
1627
}
1728

1829
raw := original
19-
raw &^= syscall.ENABLE_ECHO_INPUT
20-
raw &^= syscall.ENABLE_LINE_INPUT
21-
raw &^= syscall.ENABLE_PROCESSED_INPUT
22-
raw |= syscall.ENABLE_VIRTUAL_TERMINAL_INPUT
30+
raw &^= windows.ENABLE_ECHO_INPUT
31+
raw &^= windows.ENABLE_LINE_INPUT
32+
raw &^= windows.ENABLE_PROCESSED_INPUT
33+
raw |= windows.ENABLE_VIRTUAL_TERMINAL_INPUT
2334

24-
if err := syscall.SetConsoleMode(handle, raw); err != nil {
35+
if err := windows.SetConsoleMode(handle, raw); err != nil {
2536
return nil, err
2637
}
2738

28-
return &terminalState{mode: original}, nil
39+
return &terminalState{handle: handle, mode: original}, nil
2940
}
3041

3142
func restore(fd int, state *terminalState) {
3243
if state == nil {
3344
return
3445
}
35-
handle := syscall.Handle(fd)
36-
_ = syscall.SetConsoleMode(handle, state.mode)
46+
_ = windows.SetConsoleMode(state.handle, state.mode)
3747
}

0 commit comments

Comments
 (0)