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.
7 package terminal // import "golang.org/x/crypto/ssh/terminal"
10 "golang.org/x/sys/unix"
15 // State contains the state of a terminal.
20 // IsTerminal returns whether the given file descriptor is a terminal.
21 func IsTerminal(fd int) bool {
22 _, err := unix.IoctlGetTermio(fd, unix.TCGETA)
26 // ReadPassword reads a line of input from a terminal without local echo. This
27 // is commonly used for inputting passwords and other sensitive data. The slice
28 // returned does not include the \n.
29 func ReadPassword(fd int) ([]byte, error) {
30 // see also: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libast/common/uwin/getpass.c
31 val, err := unix.IoctlGetTermios(fd, unix.TCGETS)
38 newState.Lflag &^= syscall.ECHO
39 newState.Lflag |= syscall.ICANON | syscall.ISIG
40 newState.Iflag |= syscall.ICRNL
41 err = unix.IoctlSetTermios(fd, unix.TCSETS, &newState)
46 defer unix.IoctlSetTermios(fd, unix.TCSETS, &oldState)
51 n, err := syscall.Read(fd, buf[:])
64 ret = append(ret, buf[:n]...)
73 // MakeRaw puts the terminal connected to the given file descriptor into raw
74 // mode and returns the previous state of the terminal so that it can be
76 // see http://cr.illumos.org/~webrev/andy_js/1060/
77 func MakeRaw(fd int) (*State, error) {
78 termios, err := unix.IoctlGetTermios(fd, unix.TCGETS)
83 oldState := State{termios: *termios}
85 termios.Iflag &^= unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON
86 termios.Oflag &^= unix.OPOST
87 termios.Lflag &^= unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN
88 termios.Cflag &^= unix.CSIZE | unix.PARENB
89 termios.Cflag |= unix.CS8
90 termios.Cc[unix.VMIN] = 1
91 termios.Cc[unix.VTIME] = 0
93 if err := unix.IoctlSetTermios(fd, unix.TCSETS, termios); err != nil {
100 // Restore restores the terminal connected to the given file descriptor to a
102 func Restore(fd int, oldState *State) error {
103 return unix.IoctlSetTermios(fd, unix.TCSETS, &oldState.termios)
106 // GetState returns the current state of a terminal which may be useful to
107 // restore the terminal after a signal.
108 func GetState(fd int) (*State, error) {
109 termios, err := unix.IoctlGetTermios(fd, unix.TCGETS)
114 return &State{termios: *termios}, nil
117 // GetSize returns the dimensions of the given terminal.
118 func GetSize(fd int) (width, height int, err error) {
119 ws, err := unix.IoctlGetWinsize(fd, unix.TIOCGWINSZ)
123 return int(ws.Col), int(ws.Row), nil