...
Source file src/pkg/cmd/vendor/golang.org/x/crypto/ssh/terminal/util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package terminal
18
19 import (
20 "golang.org/x/sys/unix"
21 )
22
23
24 type State struct {
25 termios unix.Termios
26 }
27
28
29 func IsTerminal(fd int) bool {
30 _, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
31 return err == nil
32 }
33
34
35
36
37 func MakeRaw(fd int) (*State, error) {
38 termios, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
39 if err != nil {
40 return nil, err
41 }
42
43 oldState := State{termios: *termios}
44
45
46
47 termios.Iflag &^= unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON
48 termios.Oflag &^= unix.OPOST
49 termios.Lflag &^= unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN
50 termios.Cflag &^= unix.CSIZE | unix.PARENB
51 termios.Cflag |= unix.CS8
52 termios.Cc[unix.VMIN] = 1
53 termios.Cc[unix.VTIME] = 0
54 if err := unix.IoctlSetTermios(fd, ioctlWriteTermios, termios); err != nil {
55 return nil, err
56 }
57
58 return &oldState, nil
59 }
60
61
62
63 func GetState(fd int) (*State, error) {
64 termios, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
65 if err != nil {
66 return nil, err
67 }
68
69 return &State{termios: *termios}, nil
70 }
71
72
73
74 func Restore(fd int, state *State) error {
75 return unix.IoctlSetTermios(fd, ioctlWriteTermios, &state.termios)
76 }
77
78
79 func GetSize(fd int) (width, height int, err error) {
80 ws, err := unix.IoctlGetWinsize(fd, unix.TIOCGWINSZ)
81 if err != nil {
82 return -1, -1, err
83 }
84 return int(ws.Col), int(ws.Row), nil
85 }
86
87
88 type passwordReader int
89
90 func (r passwordReader) Read(buf []byte) (int, error) {
91 return unix.Read(int(r), buf)
92 }
93
94
95
96
97 func ReadPassword(fd int) ([]byte, error) {
98 termios, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
99 if err != nil {
100 return nil, err
101 }
102
103 newState := *termios
104 newState.Lflag &^= unix.ECHO
105 newState.Lflag |= unix.ICANON | unix.ISIG
106 newState.Iflag |= unix.ICRNL
107 if err := unix.IoctlSetTermios(fd, ioctlWriteTermios, &newState); err != nil {
108 return nil, err
109 }
110
111 defer unix.IoctlSetTermios(fd, ioctlWriteTermios, termios)
112
113 return readPasswordLine(passwordReader(fd))
114 }
115
View as plain text