pty_dragonfly.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package pty
  2. import (
  3. "errors"
  4. "os"
  5. "strings"
  6. "syscall"
  7. "unsafe"
  8. )
  9. // same code as pty_darwin.go
  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 := grantpt(p); err != nil {
  26. return nil, nil, err
  27. }
  28. if err := unlockpt(p); err != nil {
  29. return nil, nil, err
  30. }
  31. t, err := os.OpenFile(sname, os.O_RDWR, 0)
  32. if err != nil {
  33. return nil, nil, err
  34. }
  35. return p, t, nil
  36. }
  37. func grantpt(f *os.File) error {
  38. _, err := isptmaster(f.Fd())
  39. return err
  40. }
  41. func unlockpt(f *os.File) error {
  42. _, err := isptmaster(f.Fd())
  43. return err
  44. }
  45. func isptmaster(fd uintptr) (bool, error) {
  46. err := ioctl(fd, syscall.TIOCISPTMASTER, 0)
  47. return err == nil, err
  48. }
  49. var (
  50. emptyFiodgnameArg fiodgnameArg
  51. ioctl_FIODNAME = _IOW('f', 120, unsafe.Sizeof(emptyFiodgnameArg))
  52. )
  53. func ptsname(f *os.File) (string, error) {
  54. name := make([]byte, _C_SPECNAMELEN)
  55. fa := fiodgnameArg{Name: (*byte)(unsafe.Pointer(&name[0])), Len: _C_SPECNAMELEN, Pad_cgo_0: [4]byte{0, 0, 0, 0}}
  56. err := ioctl(f.Fd(), ioctl_FIODNAME, uintptr(unsafe.Pointer(&fa)))
  57. if err != nil {
  58. return "", err
  59. }
  60. for i, c := range name {
  61. if c == 0 {
  62. s := "/dev/" + string(name[:i])
  63. return strings.Replace(s, "ptm", "pts", -1), nil
  64. }
  65. }
  66. return "", errors.New("TIOCPTYGNAME string not NUL-terminated")
  67. }