pty_linux.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //go:build linux
  2. // +build linux
  3. package pty
  4. import (
  5. "os"
  6. "strconv"
  7. "syscall"
  8. "unsafe"
  9. )
  10. func open() (pty, tty *os.File, err error) {
  11. p, err := os.OpenFile("/dev/ptmx", os.O_RDWR, 0)
  12. if err != nil {
  13. return nil, nil, err
  14. }
  15. // In case of error after this point, make sure we close the ptmx fd.
  16. defer func() {
  17. if err != nil {
  18. _ = p.Close() // Best effort.
  19. }
  20. }()
  21. sname, err := ptsname(p)
  22. if err != nil {
  23. return nil, nil, err
  24. }
  25. if err := unlockpt(p); err != nil {
  26. return nil, nil, err
  27. }
  28. t, err := os.OpenFile(sname, os.O_RDWR|syscall.O_NOCTTY, 0) //nolint:gosec // Expected Open from a variable.
  29. if err != nil {
  30. return nil, nil, err
  31. }
  32. return p, t, nil
  33. }
  34. func ptsname(f *os.File) (string, error) {
  35. var n _C_uint
  36. err := ioctl(f.Fd(), syscall.TIOCGPTN, uintptr(unsafe.Pointer(&n))) //nolint:gosec // Expected unsafe pointer for Syscall call.
  37. if err != nil {
  38. return "", err
  39. }
  40. return "/dev/pts/" + strconv.Itoa(int(n)), nil
  41. }
  42. func unlockpt(f *os.File) error {
  43. var u _C_int
  44. // use TIOCSPTLCK with a pointer to zero to clear the lock
  45. return ioctl(f.Fd(), syscall.TIOCSPTLCK, uintptr(unsafe.Pointer(&u))) //nolint:gosec // Expected unsafe pointer for Syscall call.
  46. }