| 1 |
// Copyright 2017 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
//go:build (aix || darwin || dragonfly || freebsd || hurd || (linux && !android) || netbsd || openbsd || solaris) && cgo |
| 6 |
|
| 7 |
// Package pty is a simple pseudo-terminal package for Unix systems, |
| 8 |
// implemented by calling C functions via cgo. |
| 9 |
// This is only used for testing the os/signal package. |
| 10 |
package pty |
| 11 |
|
| 12 |
import ( |
| 13 |
"fmt" |
| 14 |
"os" |
| 15 |
"syscall" |
| 16 |
"unsafe" |
| 17 |
) |
| 18 |
|
| 19 |
//extern posix_openpt |
| 20 |
func posix_openpt(int32) int32 |
| 21 |
|
| 22 |
//extern grantpt |
| 23 |
func grantpt(int32) int32 |
| 24 |
|
| 25 |
//extern unlockpt |
| 26 |
func unlockpt(int32) int32 |
| 27 |
|
| 28 |
//extern ptsname |
| 29 |
func ptsname(int32) *byte |
| 30 |
|
| 31 |
//extern close |
| 32 |
func close(int32) int32 |
| 33 |
|
| 34 |
const _O_RDWR = 2 |
| 35 |
|
| 36 |
type PtyError struct { |
| 37 |
FuncName string |
| 38 |
ErrorString string |
| 39 |
Errno syscall.Errno |
| 40 |
} |
| 41 |
|
| 42 |
func ptyError(name string, err error) *PtyError { |
| 43 |
return &PtyError{name, err.Error(), err.(syscall.Errno)} |
| 44 |
} |
| 45 |
|
| 46 |
func (e *PtyError) Error() string { |
| 47 |
return fmt.Sprintf("%s: %s", e.FuncName, e.ErrorString) |
| 48 |
} |
| 49 |
|
| 50 |
func (e *PtyError) Unwrap() error { return e.Errno } |
| 51 |
|
| 52 |
// Open returns a control pty and the name of the linked process tty. |
| 53 |
func Open() (pty *os.File, processTTY string, err error) { |
| 54 |
m := posix_openpt(_O_RDWR) |
| 55 |
if m < 0 { |
| 56 |
return nil, "", ptyError("posix_openpt", syscall.GetErrno()) |
| 57 |
} |
| 58 |
if grantpt(m) < 0 { |
| 59 |
errno := syscall.GetErrno() |
| 60 |
close(m) |
| 61 |
return nil, "", ptyError("grantpt", errno) |
| 62 |
} |
| 63 |
if unlockpt(m) < 0 { |
| 64 |
errno := syscall.GetErrno() |
| 65 |
close(m) |
| 66 |
return nil, "", ptyError("unlockpt", errno) |
| 67 |
} |
| 68 |
p := ptsname(m) |
| 69 |
s := (*[32000]byte)(unsafe.Pointer(p))[:] |
| 70 |
for i, v := range s { |
| 71 |
if v == 0 { |
| 72 |
s = s[:i:i] |
| 73 |
break |
| 74 |
} |
| 75 |
} |
| 76 |
processTTY = string(s) |
| 77 |
return os.NewFile(uintptr(m), "pty"), processTTY, nil |
| 78 |
} |