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 true if 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 oldTermiosPtr, err := unix.IoctlGetTermios(fd, unix.TCGETS)
82 oldTermios := *oldTermiosPtr
84 newTermios := oldTermios
85 newTermios.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK | syscall.ISTRIP | syscall.INLCR | syscall.IGNCR | syscall.ICRNL | syscall.IXON
86 newTermios.Oflag &^= syscall.OPOST
87 newTermios.Lflag &^= syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG | syscall.IEXTEN
88 newTermios.Cflag &^= syscall.CSIZE | syscall.PARENB
89 newTermios.Cflag |= syscall.CS8
90 newTermios.Cc[unix.VMIN] = 1
91 newTermios.Cc[unix.VTIME] = 0
93 if err := unix.IoctlSetTermios(fd, unix.TCSETS, &newTermios); err != nil {
102 // Restore restores the terminal connected to the given file descriptor to a
104 func Restore(fd int, oldState *State) error {
105 return unix.IoctlSetTermios(fd, unix.TCSETS, oldState.state)
108 // GetState returns the current state of a terminal which may be useful to
109 // restore the terminal after a signal.
110 func GetState(fd int) (*State, error) {
111 oldTermiosPtr, err := unix.IoctlGetTermios(fd, unix.TCGETS)
117 state: oldTermiosPtr,
121 // GetSize returns the dimensions of the given terminal.
122 func GetSize(fd int) (width, height int, err error) {
123 ws, err := unix.IoctlGetWinsize(fd, unix.TIOCGWINSZ)
127 return int(ws.Col), int(ws.Row), nil