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