Debian Codegraph @

term/termios.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // Copyright 2015 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5
6 /*
7 Package term implements a subset of the C termios library to interface with Terminals.
8
9 This package allows the caller to get and set most Terminal capabilites
10 and sizes as well as create PTYs to enable writing things like script,
11 screen, tmux, and expect.
12
13 The Termios type is used for setting/getting Terminal capabilities while
14 the PTY type is used for handling virtual terminals.
15
16 Currently this part of this lib is Linux specific.
17
18 Also implements a simple version of readline in pure Go and some Stringers
19 for terminal colors and attributes.
20 */
21 package term
22
23 import (
24 "errors"
25 "os"
26 "strconv"
27 "strings"
28 "syscall"
29 "unsafe"
30 )
31
32 // IOCTL terminal stuff.
33 const (
34 TCGETS = 0x5401 // TCGETS get terminal attributes
35 TCSETS = 0x5402 // TCSETS set terminal attributes
36 TIOCGWINSZ = 0x5413 // TIOCGWINSZ used to get the terminal window size
37 TIOCSWINSZ = 0x5414 // TIOCSWINSZ used to set the terminal window size
38 TIOCGPTN = 0x80045430 // TIOCGPTN IOCTL used to get the PTY number
39 TIOCSPTLCK = 0x40045431 // TIOCSPTLCK IOCT used to lock/unlock PTY
40 CBAUD = 0010017 // CBAUD Serial speed settings
41 CBAUDEX = 0010000 // CBAUDX Serial speed settings
42 )
43
44 // INPUT handling terminal flags
45 // see 'man stty' for further info about most of the constants
46 const (
47 IGNBRK = 0000001 // IGNBRK ignore break characters
48 BRKINT = 0000002 // BRKINT Break genereates an interrupt signal
49 IGNPAR = 0000004 // IGNPAR Ignore characters with parity errors
50 PARMRK = 0000010 // PARMRK Mark parity errors byte{ff,0}
51 INPCK = 0000020 // INPCK enable parity checking
52 ISTRIP = 0000040 // ISTRIP Clear 8th bit of input characters
53 INLCR = 0000100 // INLCR Translate LF => CR
54 IGNCR = 0000200 // IGNCR Ignore Carriage Return
55 ICRNL = 0000400 // ICRNL Translate CR => NL
56 IUCLC = 0001000 // IUCLC Translate uppercase to lowercase
57 IXON = 0002000 // IXON Enable flow control
58 IXANY = 0004000 // IXANY let any char restart input
59 IXOFF = 0010000 // IXOFF start sending start/stop chars
60 IMAXBEL = 0020000 // IMAXBEL Sound the bell and skip flushing input buffer
61 IUTF8 = 0040000 // IUTF8 assume input being utf-8
62 )
63
64 // OUTPUT treatment terminal flags
65 const (
66 OPOST = 0000001 // OPOST post process output
67 OLCUC = 0000002 // OLCUC translate lower case to upper case
68 ONLCR = 0000004 // ONLCR Map NL -> CR-NL
69 OCRNL = 0000010 // OCRNL Map CR -> NL
70 ONOCR = 0000020 // ONOCR No CR at col 0
71 ONLRET = 0000040 // ONLRET NL also do CR
72 OFILL = 0000100 // OFILL Fillchar for delay
73 OFDEL = 0000200 // OFDEL use delete instead of null
74 )
75
76 // TERM control modes.
77 const (
78 CSIZE = 0000060 // CSIZE used as mask when setting character size
79 CS5 = 0000000 // CS5 char size 5bits
80 CS6 = 0000020 // CS6 char size 6bits
81 CS7 = 0000040 // CS7 char size 7bits
82 CS8 = 0000060 // CS8 char size 8bits
83 CSTOPB = 0000100 // CSTOPB two stop bits
84 CREAD = 0000200 // CREAD enable input
85 PARENB = 0000400 // PARENB generate and expect parity bit
86 PARODD = 0001000 // PARODD set odd parity
87 HUPCL = 0002000 // HUPCL send HUP when last process closes term
88 CLOCAL = 0004000 // CLOCAL no modem control signals
89 )
90
91 // TERM modes
92 const (
93 ISIG = 0000001 // ISIG enable Interrupt,quit and suspend chars
94 ICANON = 0000002 // ICANON enable erase,kill ,werase and rprnt chars
95 XCASE = 0000004 // XCASE preceedes all uppercase chars with '\'
96 ECHO = 0000010 // ECHO echo input characters
97 ECHOE = 0000020 // ECHOE erase => BS - SPACE - BS
98 ECHOK = 0000040 // ECHOK add newline after kill char
99 ECHONL = 0000100 // ECHONL echo NL even without other characters
100 NOFLSH = 0000200 // NOFLSH no flush after interrupt and kill characters
101 TOSTOP = 0000400 // TOSTOP stop BG jobs trying to write to term
102 ECHOCTL = 0001000 // ECHOCTL will echo control characters as ^c
103 ECHOPRT = 0002000 // ECHOPRT will print erased characters between \ /
104 ECHOKE = 0004000 // ECHOKE kill all line considering ECHOPRT and ECHOE flags
105 IEXTEN = 0100000 // IEXTEN enable non POSIX special characters
106 )
107
108 // Control characters
109 const (
110 VINTR = 0 // VINTR char will send an interrupt signal
111 VQUIT = 1 // VQUIT char will send a quit signal
112 VERASE = 2 // VEREASE char will erase last typed char
113 VKILL = 3 // VKILL char will erase current line
114 VEOF = 4 // VEOF char will send EOF
115 VTIME = 5 // VTIME set read timeout in tenths of seconds
116 VMIN = 6 // VMIN set min characters for a complete read
117 VSWTC = 7 // VSWTC char will switch to a different shell layer
118 VSTART = 8 // VSTART char will restart output after stopping it
119 VSTOP = 9 // VSTOP char will stop output
120 VSUSP = 10 // VSUSP char will send a stop signal
121 VEOL = 11 // VEOL char will end the line
122 VREPRINT = 12 // VREPRINT will redraw the current line
123 VDISCARD = 13 // VDISCARD
124 VWERASE = 14 // VWERASE char will erase last word typed
125 VLNEXT = 15 // VLNEXT char will enter the next char quoted
126 VEOL2 = 16 // VEOL2 char alternate to end line
127 tNCCS = 32 // tNCCS Termios CC size
128 )
129
130 // Termios merge of the C Terminal and Kernel termios structs.
131 type Termios struct {
132 Iflag uint32 // Iflag Handles the different Input modes
133 Oflag uint32 // Oflag For the different Output modes
134 Cflag uint32 // Cflag Control modes
135 Lflag uint32 // Lflag Local modes
136 Line byte // Line
137 Cc [tNCCS]byte // Cc Control characters. How to handle special Characters eg. Backspace being ^H or ^? and so on
138 Ispeed uint32 // Ispeed Hardly ever used speed of terminal
139 Ospeed uint32 // Ospeed "
140 Wz Winsize // Wz Terminal size information.
141 }
142
143 // Winsize handle the terminal window size.
144 type Winsize struct {
145 WsRow uint16 // WsRow Terminal number of rows
146 WsCol uint16 // WsCol Terminal number of columns
147 WsXpixel uint16 // WsXpixel Terminal width in pixels
148 WsYpixel uint16 // WsYpixel Terminal height in pixels
149 }
150
151 // PTY the PTY Master/Slave are always bundled together so makes sense to bundle here too.
152 //
153 // Slave - implements the virtual terminal functionality and the place you connect client applications
154 // Master - Things written to the Master are forwarded to the Slave terminal and the other way around.
155 // This gives reading from Master would give you nice line-by-line with no strange characters in
156 // Cooked() Mode and every char in Raw() mode.
157 //
158 // Since Slave is a virtual terminal it depends on the terminal settings ( in this lib the Termios ) what
159 // and when data is forwarded through the terminal.
160 //
161 // See 'man pty' for further info
162 type PTY struct {
163 Master *os.File // Master The Master part of the PTY
164 Slave *os.File // Slave The Slave part of the PTY
165 }
166
167 // Raw Sets terminal t to raw mode.
168 // This gives that the terminal will do the absolut minimal of processing, pretty much send everything through.
169 // This is normally what Shells and such want since they have their own readline and movement code.
170 func (t *Termios) Raw() {
171 t.Iflag &^= IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON
172 // t.Iflag &^= BRKINT | ISTRIP | ICRNL | IXON // Stevens RAW
173 t.Oflag &^= OPOST
174 t.Lflag &^= ECHO | ECHONL | ICANON | ISIG | IEXTEN
175 t.Cflag &^= CSIZE | PARENB
176 t.Cflag |= CS8
177 t.Cc[VMIN] = 1
178 t.Cc[VTIME] = 0
179 }
180
181 // Cook Set the Terminal to Cooked mode.
182 // In this mode the Terminal process the information before sending it on to the application.
183 func (t *Termios) Cook() {
184 t.Iflag |= BRKINT | IGNPAR | ISTRIP | ICRNL | IXON
185 t.Oflag |= OPOST
186 t.Lflag |= ISIG | ICANON
187 }
188
189 // Sane reset Term to sane values.
190 // Should be pretty much what the shell command "reset" does to the terminal.
191 func (t *Termios) Sane() {
192 t.Iflag &^= IGNBRK | INLCR | IGNCR | IUTF8 | IXOFF | IUCLC | IXANY
193 t.Iflag |= BRKINT | ICRNL | IMAXBEL
194 t.Oflag |= OPOST | ONLCR
195 t.Oflag &^= OLCUC | OCRNL | ONOCR | ONLRET
196 t.Cflag |= CREAD
197 }
198
199 // Set Sets terminal t attributes on file.
200 func (t *Termios) Set(file *os.File) error {
201 fd := file.Fd()
202 _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), uintptr(TCSETS), uintptr(unsafe.Pointer(t)))
203 if errno != 0 {
204 return errno
205 }
206 return nil
207 }
208
209 // Attr Gets (terminal related) attributes from file.
210 func Attr(file *os.File) (Termios, error) {
211 var t Termios
212 fd := file.Fd()
213 _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), uintptr(TCGETS), uintptr(unsafe.Pointer(&t)))
214 if errno != 0 {
215 return t, errno
216 }
217 t.Ispeed &= CBAUD | CBAUDEX
218 t.Ospeed &= CBAUD | CBAUDEX
219 return t, nil
220 }
221
222 // Isatty returns true if file is a tty.
223 func Isatty(file *os.File) bool {
224 _, err := Attr(file)
225 return err == nil
226 }
227
228 // GetPass reads password from a TTY with no echo.
229 func GetPass(prompt string, f *os.File, pbuf []byte) ([]byte, error) {
230 t, err := Attr(f)
231 if err != nil {
232 return nil, err
233 }
234 defer t.Set(f)
235 noecho := t
236 noecho.Lflag = noecho.Lflag &^ ECHO
237 if err := noecho.Set(f); err != nil {
238 return nil, err
239 }
240 b := make([]byte, 1, 1)
241 i := 0
242 if _, err := f.Write([]byte(prompt)); err != nil {
243 return nil, err
244 }
245 for ; i < len(pbuf); i++ {
246 if _, err := f.Read(b); err != nil {
247 b[0] = 0
248 clearbuf(pbuf[:i+1])
249 }
250 if b[0] == '\n' || b[0] == '\r' {
251 return pbuf[:i], nil
252 }
253 pbuf[i] = b[0]
254 b[0] = 0
255 }
256 clearbuf(pbuf[:i+1])
257 return nil, errors.New("ran out of bufferspace")
258 }
259
260 // clearbuf clears out the buffer incase we couldn't read the full password.
261 func clearbuf(b []byte) {
262 for i := range b {
263 b[i] = 0
264 }
265 }
266
267 // GetChar reads a single byte.
268 func GetChar(f *os.File) (b byte, err error) {
269 bs := make([]byte, 1, 1)
270 if _, err = f.Read(bs); err != nil {
271 return 0, err
272 }
273 return bs[0], err
274 }
275
276 // PTSName return the name of the pty.
277 func (p *PTY) PTSName() (string, error) {
278 n, err := p.PTSNumber()
279 if err != nil {
280 return "", err
281 }
282 return "/dev/pts/" + strconv.Itoa(int(n)), nil
283 }
284
285 // PTSNumber return the pty number.
286 func (p *PTY) PTSNumber() (uint, error) {
•287 var ptyno uint32
288 _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(p.Master.Fd()), uintptr(TIOCGPTN), uintptr(unsafe.Pointer(&ptyno)))
289 if errno != 0 {
290 return 0, errno
291 }
•292 return uint(ptyno), nil
293 }
294
295 // Winsz Fetches the current terminal windowsize.
296 // example handling changing window sizes with PTYs:
297 //
298 // import "os"
299 // import "os/signal"
300 //
301 // var sig = make(chan os.Signal,2) // Channel to listen for UNIX SIGNALS on
302 // signal.Notify(sig, syscall.SIGWINCH) // That'd be the window changing
303 //
304 // for {
305 // <-sig
306 // term.Winsz(os.Stdin) // We got signaled our terminal changed size so we read in the new value
307 // term.Setwinsz(pty.Slave) // Copy it to our virtual Terminal
308 // }
309 func (t *Termios) Winsz(file *os.File) error {
310 _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(file.Fd()), uintptr(TIOCGWINSZ), uintptr(unsafe.Pointer(&t.Wz)))
311 if errno != 0 {
312 return errno
313 }
314 return nil
315 }
316
317 // Setwinsz Sets the terminal window size.
318 func (t *Termios) Setwinsz(file *os.File) error {
319 _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(file.Fd()), uintptr(TIOCSWINSZ), uintptr(unsafe.Pointer(&t.Wz)))
320 if errno != 0 {
321 return errno
322 }
323 return nil
324 }
325
326 // OpenPTY Creates a new Master/Slave PTY pair.
327 func OpenPTY() (*PTY, error) {
328 // Opening ptmx gives you the FD of a brand new PTY
329 master, err := os.OpenFile("/dev/ptmx", os.O_RDWR, 0)
330 if err != nil {
331 return nil, err
332 }
333
334 // unlock pty slave
•335 var unlock int32 // 0 => Unlock
336 if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(master.Fd()), uintptr(TIOCSPTLCK), uintptr(unsafe.Pointer(&unlock))); errno != 0 {
337 master.Close()
338 return nil, errno
339 }
340
341 // get path of pts slave
342 pty := &PTY{Master: master}
343 slaveStr, err := pty.PTSName()
344 if err != nil {
345 master.Close()
346 return nil, err
347 }
348
349 // open pty slave
350 pty.Slave, err = os.OpenFile(slaveStr, os.O_RDWR|syscall.O_NOCTTY, 0)
351 if err != nil {
352 master.Close()
353 return nil, err
354 }
355
356 return pty, nil
357 }
358
359 // Close closes the PTYs that OpenPTY created.
360 func (p *PTY) Close() error {
361 slaveErr := errors.New("Slave FD nil")
362 if p.Slave != nil {
363 slaveErr = p.Slave.Close()
364 }
365 masterErr := errors.New("Master FD nil")
366 if p.Master != nil {
367 masterErr = p.Master.Close()
368 }
369 if slaveErr != nil || masterErr != nil {
370 var errs []string
371 if slaveErr != nil {
372 errs = append(errs, "Slave: "+slaveErr.Error())
373 }
374 if masterErr != nil {
375 errs = append(errs, "Master: "+masterErr.Error())
376 }
377 return errors.New(strings.Join(errs, " "))
378 }
379 return nil
380 }
381
382 // ReadByte implements the io.ByteReader interface to read single char from the PTY.
383 func (p *PTY) ReadByte() (byte, error) {
384 bs := make([]byte, 1, 1)
385 _, err := p.Master.Read(bs)
386 return bs[0], err
387 }
388
389 // GetChar fine old getchar() for a PTY.
390 func (p *PTY) GetChar() (byte, error) {
391 return p.ReadByte()
392 }