pty_dragonfly.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. //go:build dragonfly
  2. // +build dragonfly
  3. package pty
  4. import (
  5. "errors"
  6. "os"
  7. "strings"
  8. "syscall"
  9. "unsafe"
  10. )
  11. // same code as pty_darwin.go
  12. func open() (pty, tty *os.File, err error) {
  13. p, err := os.OpenFile("/dev/ptmx", os.O_RDWR, 0)
  14. if err != nil {
  15. return nil, nil, err
  16. }
  17. // In case of error after this point, make sure we close the ptmx fd.
  18. defer func() {
  19. if err != nil {
  20. _ = p.Close() // Best effort.
  21. }
  22. }()
  23. sname, err := ptsname(p)
  24. if err != nil {
  25. return nil, nil, err
  26. }
  27. if err := grantpt(p); err != nil {
  28. return nil, nil, err
  29. }
  30. if err := unlockpt(p); err != nil {
  31. return nil, nil, err
  32. }
  33. t, err := os.OpenFile(sname, os.O_RDWR, 0)
  34. if err != nil {
  35. return nil, nil, err
  36. }
  37. return p, t, nil
  38. }
  39. func grantpt(f *os.File) error {
  40. _, err := isptmaster(f.Fd())
  41. return err
  42. }
  43. func unlockpt(f *os.File) error {
  44. _, err := isptmaster(f.Fd())
  45. return err
  46. }
  47. func isptmaster(fd uintptr) (bool, error) {
  48. err := ioctl(fd, syscall.TIOCISPTMASTER, 0)
  49. return err == nil, err
  50. }
  51. var (
  52. emptyFiodgnameArg fiodgnameArg
  53. ioctl_FIODNAME = _IOW('f', 120, unsafe.Sizeof(emptyFiodgnameArg))
  54. )
  55. func ptsname(f *os.File) (string, error) {
  56. name := make([]byte, _C_SPECNAMELEN)
  57. fa := fiodgnameArg{Name: (*byte)(unsafe.Pointer(&name[0])), Len: _C_SPECNAMELEN, Pad_cgo_0: [4]byte{0, 0, 0, 0}}
  58. err := ioctl(f.Fd(), ioctl_FIODNAME, uintptr(unsafe.Pointer(&fa)))
  59. if err != nil {
  60. return "", err
  61. }
  62. for i, c := range name {
  63. if c == 0 {
  64. s := "/dev/" + string(name[:i])
  65. return strings.Replace(s, "ptm", "pts", -1), nil
  66. }
  67. }
  68. return "", errors.New("TIOCPTYGNAME string not NUL-terminated")
  69. }