term_unix.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright 2019 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. //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos
  5. package term
  6. import (
  7. "golang.org/x/sys/unix"
  8. )
  9. type state struct {
  10. termios unix.Termios
  11. }
  12. func isTerminal(fd int) bool {
  13. _, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
  14. return err == nil
  15. }
  16. func makeRaw(fd int) (*State, error) {
  17. termios, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
  18. if err != nil {
  19. return nil, err
  20. }
  21. oldState := State{state{termios: *termios}}
  22. // This attempts to replicate the behaviour documented for cfmakeraw in
  23. // the termios(3) manpage.
  24. termios.Iflag &^= unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON
  25. termios.Oflag &^= unix.OPOST
  26. termios.Lflag &^= unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN
  27. termios.Cflag &^= unix.CSIZE | unix.PARENB
  28. termios.Cflag |= unix.CS8
  29. termios.Cc[unix.VMIN] = 1
  30. termios.Cc[unix.VTIME] = 0
  31. if err := unix.IoctlSetTermios(fd, ioctlWriteTermios, termios); err != nil {
  32. return nil, err
  33. }
  34. return &oldState, nil
  35. }
  36. func getState(fd int) (*State, error) {
  37. termios, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
  38. if err != nil {
  39. return nil, err
  40. }
  41. return &State{state{termios: *termios}}, nil
  42. }
  43. func restore(fd int, state *State) error {
  44. return unix.IoctlSetTermios(fd, ioctlWriteTermios, &state.termios)
  45. }
  46. func getSize(fd int) (width, height int, err error) {
  47. ws, err := unix.IoctlGetWinsize(fd, unix.TIOCGWINSZ)
  48. if err != nil {
  49. return 0, 0, err
  50. }
  51. return int(ws.Col), int(ws.Row), nil
  52. }
  53. // passwordReader is an io.Reader that reads from a specific file descriptor.
  54. type passwordReader int
  55. func (r passwordReader) Read(buf []byte) (int, error) {
  56. return unix.Read(int(r), buf)
  57. }
  58. func readPassword(fd int) ([]byte, error) {
  59. termios, err := unix.IoctlGetTermios(fd, ioctlReadTermios)
  60. if err != nil {
  61. return nil, err
  62. }
  63. newState := *termios
  64. newState.Lflag &^= unix.ECHO
  65. newState.Lflag |= unix.ICANON | unix.ISIG
  66. newState.Iflag |= unix.ICRNL
  67. if err := unix.IoctlSetTermios(fd, ioctlWriteTermios, &newState); err != nil {
  68. return nil, err
  69. }
  70. defer unix.IoctlSetTermios(fd, ioctlWriteTermios, termios)
  71. return readPasswordLine(passwordReader(fd))
  72. }