2014-03-10 16:21:30 -04:00
|
|
|
package pty
|
|
|
|
|
|
|
|
import (
|
2014-05-20 17:18:52 -04:00
|
|
|
"errors"
|
2014-03-10 16:21:30 -04:00
|
|
|
"os"
|
|
|
|
"syscall"
|
|
|
|
"unsafe"
|
|
|
|
)
|
|
|
|
|
2014-05-20 17:18:52 -04:00
|
|
|
func posix_openpt(oflag int) (fd int, err error) {
|
|
|
|
r0, _, e1 := syscall.Syscall(syscall.SYS_POSIX_OPENPT, uintptr(oflag), 0, 0)
|
|
|
|
fd = int(r0)
|
|
|
|
if e1 != 0 {
|
|
|
|
err = e1
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
2014-03-10 16:21:30 -04:00
|
|
|
|
|
|
|
func open() (pty, tty *os.File, err error) {
|
2014-05-20 17:18:52 -04:00
|
|
|
fd, err := posix_openpt(syscall.O_RDWR | syscall.O_CLOEXEC)
|
2014-03-10 16:21:30 -04:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
2014-05-20 17:18:52 -04:00
|
|
|
p := os.NewFile(uintptr(fd), "/dev/pts")
|
2014-03-10 16:21:30 -04:00
|
|
|
sname, err := ptsname(p)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
2014-05-20 17:18:52 -04:00
|
|
|
t, err := os.OpenFile("/dev/"+sname, os.O_RDWR, 0)
|
2014-03-10 16:21:30 -04:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
return p, t, nil
|
|
|
|
}
|
|
|
|
|
2014-05-20 17:18:52 -04:00
|
|
|
func isptmaster(fd uintptr) (bool, error) {
|
|
|
|
err := ioctl(fd, syscall.TIOCPTMASTER, 0)
|
|
|
|
return err == nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
|
|
|
emptyFiodgnameArg fiodgnameArg
|
|
|
|
ioctl_FIODGNAME = _IOW('f', 120, unsafe.Sizeof(emptyFiodgnameArg))
|
|
|
|
)
|
|
|
|
|
2014-03-10 16:21:30 -04:00
|
|
|
func ptsname(f *os.File) (string, error) {
|
2014-05-20 17:18:52 -04:00
|
|
|
master, err := isptmaster(f.Fd())
|
2014-03-10 16:21:30 -04:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2014-05-20 17:18:52 -04:00
|
|
|
if !master {
|
|
|
|
return "", syscall.EINVAL
|
|
|
|
}
|
2014-03-10 16:21:30 -04:00
|
|
|
|
2014-05-20 17:18:52 -04:00
|
|
|
const n = _C_SPECNAMELEN + 1
|
|
|
|
var (
|
|
|
|
buf = make([]byte, n)
|
|
|
|
arg = fiodgnameArg{Len: n, Buf: (*byte)(unsafe.Pointer(&buf[0]))}
|
2014-03-10 16:21:30 -04:00
|
|
|
)
|
2014-05-20 17:18:52 -04:00
|
|
|
err = ioctl(f.Fd(), ioctl_FIODGNAME, uintptr(unsafe.Pointer(&arg)))
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
for i, c := range buf {
|
|
|
|
if c == 0 {
|
|
|
|
return string(buf[:i]), nil
|
|
|
|
}
|
2014-03-10 16:21:30 -04:00
|
|
|
}
|
2014-05-20 17:18:52 -04:00
|
|
|
return "", errors.New("FIODGNAME string not NUL-terminated")
|
2014-03-10 16:21:30 -04:00
|
|
|
}
|