tc_unix.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. //go:build darwin || freebsd || linux || netbsd || openbsd || zos
  2. // +build darwin freebsd linux netbsd openbsd zos
  3. /*
  4. Copyright The containerd Authors.
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. */
  15. package console
  16. import (
  17. "golang.org/x/sys/unix"
  18. )
  19. func tcget(fd uintptr, p *unix.Termios) error {
  20. termios, err := unix.IoctlGetTermios(int(fd), cmdTcGet)
  21. if err != nil {
  22. return err
  23. }
  24. *p = *termios
  25. return nil
  26. }
  27. func tcset(fd uintptr, p *unix.Termios) error {
  28. return unix.IoctlSetTermios(int(fd), cmdTcSet, p)
  29. }
  30. func tcgwinsz(fd uintptr) (WinSize, error) {
  31. var ws WinSize
  32. uws, err := unix.IoctlGetWinsize(int(fd), unix.TIOCGWINSZ)
  33. if err != nil {
  34. return ws, err
  35. }
  36. // Translate from unix.Winsize to console.WinSize
  37. ws.Height = uws.Row
  38. ws.Width = uws.Col
  39. ws.x = uws.Xpixel
  40. ws.y = uws.Ypixel
  41. return ws, nil
  42. }
  43. func tcswinsz(fd uintptr, ws WinSize) error {
  44. // Translate from console.WinSize to unix.Winsize
  45. var uws unix.Winsize
  46. uws.Row = ws.Height
  47. uws.Col = ws.Width
  48. uws.Xpixel = ws.x
  49. uws.Ypixel = ws.y
  50. return unix.IoctlSetWinsize(int(fd), unix.TIOCSWINSZ, &uws)
  51. }
  52. func setONLCR(fd uintptr, enable bool) error {
  53. var termios unix.Termios
  54. if err := tcget(fd, &termios); err != nil {
  55. return err
  56. }
  57. if enable {
  58. // Set +onlcr so we can act like a real terminal
  59. termios.Oflag |= unix.ONLCR
  60. } else {
  61. // Set -onlcr so we don't have to deal with \r.
  62. termios.Oflag &^= unix.ONLCR
  63. }
  64. return tcset(fd, &termios)
  65. }
  66. func cfmakeraw(t unix.Termios) unix.Termios {
  67. t.Iflag &^= (unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON)
  68. t.Oflag &^= unix.OPOST
  69. t.Lflag &^= (unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN)
  70. t.Cflag &^= (unix.CSIZE | unix.PARENB)
  71. t.Cflag |= unix.CS8
  72. t.Cc[unix.VMIN] = 1
  73. t.Cc[unix.VTIME] = 0
  74. return t
  75. }