Documentation
¶
Overview ¶
Package pty provides pseudo-terminal support for Unix-like systems and for Windows console pseudo-terminals (ConPTY).
Unix pseudo-terminals ¶
On Unix-like systems a pseudo-terminal is a pair of devices: a master (commonly called the ptmx) and a slave (the pty, or tty). The master end is driven by the program that owns the terminal, the slave end is used by the program that believes it is talking to a real terminal.
This package covers the whole life cycle of such a pair:
- Open allocates a master/slave pair.
- Start, StartWithSize and StartWithAttr run an os/exec.Cmd on a fresh pair, optionally in a new session with the slave as its controlling terminal.
- GetSize, GetFullSize and SetSize query and change the terminal size, and InheritSize keeps one terminal in sync with another (typically from a SIGWINCH handler).
- ErrUnsupported is returned by every function that the current system cannot implement.
Windows pseudo-terminals ¶
Windows has no pseudo-terminal device, but its console host provides ConPTY: a pseudo-console that a child process can be attached to and that is driven through a pair of pipes. Use NewConPTY (or NewConPTYWithPipes to supply the pipes yourself) to create one, ConPTY.Spawn to start a process inside it and ConPTY.Read/ConPTY.Write to exchange data with that process.
Platform support ¶
Unix pseudo-terminals are implemented on Darwin, DragonFly BSD, FreeBSD, Linux, NetBSD, OpenBSD, Solaris/illumos and z/OS. ConPTY is implemented on Windows 10 1809 and later.
On every other system (AIX, Plan 9 and the WebAssembly targets among them) the package still compiles and the same API stays available, but terminal operations fail with ErrUnsupported.
Blocking operations ¶
The files returned by this package are ordinary *os.File values owned by the caller. Making Close interrupt a concurrent Read, or making deadlines work, requires non-blocking I/O: call syscall.SetNonblock on the file descriptor first. See the examples in the repository README.
Index ¶
- Constants
- Variables
- func ApplyTerminalModes(fd int, width, height int, modes map[uint8]uint32) error
- func CreatePipes() (inPipeRead, inPipeWrite, outPipeRead, outPipeWrite uintptr, err error)
- func GetSize(tty *os.File) (rows, cols int, err error)
- func InheritSize(from, to *os.File) error
- func Open() (ptmx, tty *os.File, err error)
- func SetSize(tty *os.File, size *Winsize) error
- func Start(cmd *exec.Cmd) (*os.File, error)
- func StartWithAttr(cmd *exec.Cmd, size *Winsize, attrs *syscall.SysProcAttr) (*os.File, error)
- func StartWithSize(cmd *exec.Cmd, size *Winsize) (*os.File, error)
- type Cmd
- type ConPTY
- func (*ConPTY) Close() error
- func (c *ConPTY) Command(name string, args ...string) *Cmd
- func (c *ConPTY) CommandContext(ctx context.Context, name string, args ...string) *Cmd
- func (*ConPTY) Fd() uintptr
- func (*ConPTY) InPipeReadFd() uintptr
- func (*ConPTY) InPipeWriteFd() uintptr
- func (*ConPTY) OutPipeReadFd() uintptr
- func (*ConPTY) OutPipeWriteFd() uintptr
- func (*ConPTY) Read([]byte) (int, error)
- func (*ConPTY) Resize(width, height int) error
- func (*ConPTY) Size() (int, int, error)
- func (*ConPTY) Spawn(name string, args []string, attr *syscall.ProcAttr) (pid int, handle uintptr, err error)
- func (*ConPTY) Write([]byte) (int, error)
- type Terminal
- type VirtualPTY
- func (v *VirtualPTY) Close() error
- func (v *VirtualPTY) Command(name string, args ...string) *Cmd
- func (v *VirtualPTY) CommandContext(ctx context.Context, name string, args ...string) *Cmd
- func (v *VirtualPTY) OnInterrupt(handler func())
- func (v *VirtualPTY) Read(p []byte) (int, error)
- func (v *VirtualPTY) Resize(width, height int) error
- func (v *VirtualPTY) SetRaw(raw bool)
- func (v *VirtualPTY) Size() (width, height int, err error)
- func (v *VirtualPTY) Slave() io.ReadWriteCloser
- func (v *VirtualPTY) Write(p []byte) (int, error)
- type Winsize
Examples ¶
Constants ¶
const ( DefaultWidth = 80 DefaultHeight = 25 )
Default size requested by NewConPTY and NewConPTYWithPipes when they are asked for a non-positive width or height.
const ( ModeVINTR = 1 ModeVQUIT = 2 ModeVERASE = 3 ModeVKILL = 4 ModeVEOF = 5 ModeVEOL = 6 ModeVEOL2 = 7 ModeVSTART = 8 ModeVSTOP = 9 ModeVSUSP = 10 ModeVDSUSP = 11 ModeVREPRINT = 12 ModeVWERASE = 13 ModeVLNEXT = 14 ModeVFLUSH = 15 ModeVSWTCH = 16 ModeVSTATUS = 17 ModeVDISCARD = 18 ModeVMIN = 19 ModeVTIME = 20 ModeIGNPAR = 30 ModePARMRK = 31 ModeINPCK = 32 ModeISTRIP = 33 ModeINLCR = 34 ModeIGNCR = 35 ModeICRNL = 36 ModeIUCLC = 37 ModeIXON = 38 ModeIXANY = 39 ModeIXOFF = 40 ModeIMAXBEL = 41 ModeIUTF8 = 42 ModeISIG = 50 ModeICANON = 51 ModeXCASE = 52 ModeECHO = 53 ModeECHOE = 54 ModeECHOK = 55 ModeECHONL = 56 ModeNOFLSH = 57 ModeTOSTOP = 58 ModeIEXTEN = 59 ModeECHOCTL = 60 ModeECHOKE = 61 ModePENDIN = 62 ModeOPOST = 70 ModeOLCUC = 71 ModeONLCR = 72 ModeOCRNL = 73 ModeONOCR = 74 ModeONLRET = 75 ModeCS7 = 90 ModeCS8 = 91 ModePARENB = 92 ModePARODD = 93 ModeTTYOpISpeed = 128 ModeTTYOpOSpeed = 129 )
Terminal mode opcodes of RFC 4254 section 8, the modes an SSH client sends in its pseudo-terminal request. They are the keys of the modes an SSH client asks for, and the values are the settings themselves: the value of a control character opcode is the character, the value of a flag opcode is 1 to set the flag and 0 to clear it, and the value of a speed opcode is a baud rate.
A client that uses golang.org/x/crypto/ssh passes ssh.TerminalModes, which is the same map, to ApplyTerminalModes.
Variables ¶
var ( // ErrInvalidCommand is returned by [Cmd.Start] when the command does not // come from a terminal that can start processes. ErrInvalidCommand = errors.New("pty: invalid command") // ErrNilContext is returned by [Cmd.Start] when the command was created // with [Terminal.CommandContext] and a nil context, rather than starting a // process that nothing can stop. ErrNilContext = errors.New("pty: nil context") )
var ErrUnsupported = errors.New("pty: unsupported")
ErrUnsupported is returned by functions that have no implementation on the current platform. Use errors.Is to test for it.
Functions ¶
func ApplyTerminalModes ¶
ApplyTerminalModes applies the terminal modes of an SSH pseudo-terminal request to the terminal with the given file descriptor, and resizes it to width by height character cells unless both are zero.
modes holds the opcodes of RFC 4254 section 8, the [Mode] constants of this package; ssh.TerminalModes is the same map and can be passed as it is. A mode the system does not have is ignored: a client asks for its terminal settings, it does not demand them.
The file descriptor comes from a terminal of this package, either the master end returned by Open and Start or the end returned by VirtualPTY.Slave, and it must be a terminal.
Systems without terminal settings support report ErrUnsupported.
func CreatePipes ¶
CreatePipes creates the pair of pipes a pseudo-console is driven through. It always fails with ErrUnsupported outside Windows.
func GetSize ¶
GetSize returns the number of rows and the number of columns of the terminal backed by tty.
func InheritSize ¶
InheritSize reads the terminal size of from and applies it to to.
It is commonly used in a SIGWINCH handler to keep a pseudo-terminal in step with the terminal the user is actually looking at:
winch := make(chan os.Signal, 1)
signal.Notify(winch, syscall.SIGWINCH)
for range winch {
if err := InheritSize(os.Stdin, ptmx); err != nil {
log.Printf("resizing pty: %v", err)
}
}
Example ¶
ExampleInheritSize keeps the size of a pseudo-terminal in step with the terminal the program is using, which is what an interactive shell needs.
package main
import (
"io"
"log"
"os"
"os/exec"
"os/signal"
"syscall"
"github.com/malivvan/pty"
)
func main() {
cmd := exec.Command("bash")
ptmx, err := pty.Start(cmd)
if err != nil {
log.Fatal(err)
}
defer func() { _ = ptmx.Close() }() // Best effort.
winch := make(chan os.Signal, 1)
signal.Notify(winch, syscall.SIGWINCH)
defer func() { signal.Stop(winch); close(winch) }() // Best effort.
go func() {
for range winch {
if err := pty.InheritSize(os.Stdin, ptmx); err != nil {
log.Printf("resizing pty: %v", err)
}
}
}()
winch <- syscall.SIGWINCH // Resize once, to match the current terminal.
_, _ = io.Copy(ptmx, os.Stdin)
}
Output:
func Open ¶
Open allocates a pseudo-terminal pair and returns its master end (the ptmx) and its slave end (the tty).
Both files belong to the caller, which must close them. Systems without pseudo-terminal support return ErrUnsupported.
func Start ¶
Start starts cmd with its standard input, output and error connected to a freshly allocated pseudo-terminal, and returns the master end of that terminal.
It is equivalent to StartWithSize(cmd, nil): the command is started in a new session with the slave end of the pseudo-terminal as its controlling terminal, so it behaves like a program started from an interactive shell.
The returned file belongs to the caller, which must close it. Systems without pseudo-terminal support return ErrUnsupported.
Example ¶
ExampleStart runs a command on a pseudo-terminal and echoes what it prints, the way a terminal emulator would.
package main
import (
"io"
"log"
"os"
"os/exec"
"github.com/malivvan/pty"
)
func main() {
cmd := exec.Command("grep", "--color=always", "pty")
ptmx, err := pty.Start(cmd)
if err != nil {
log.Fatal(err)
}
defer func() { _ = ptmx.Close() }() // Best effort.
go func() {
_, _ = ptmx.Write([]byte("pty\n"))
_, _ = ptmx.Write([]byte{4}) // EOT, which ends the input of grep.
}()
_, _ = io.Copy(os.Stdout, ptmx)
}
Output:
func StartWithAttr ¶
StartWithAttr starts cmd on a freshly allocated pseudo-terminal, resizing the terminal to size first when size is not nil, and returns the master end of that terminal.
attrs is assigned to cmd.SysProcAttr and replaces whatever the caller had put there, which is how the platform specific StartWithSize arranges for cmd to become the session leader that owns the slave end.
Most callers want Start or StartWithSize instead; this variant exists for the rare cases that need a different process setup, such as a command that must not receive a controlling terminal.
func StartWithSize ¶
StartWithSize is like Start but resizes the pseudo-terminal to size before starting cmd; a nil size keeps the default size of a new pseudo-terminal.
cmd is put in a new session (setsid) and the slave end of the terminal is made its controlling terminal (TIOCSCTTY), which is what interactive programs and job control expect.
Types ¶
type Cmd ¶
type Cmd struct {
// Path is the path of the program to run.
Path string
// Args holds the command line arguments, [Cmd.Path] being Args[0].
Args []string
// Env is the environment of the process. A nil Env means the environment
// of the current process.
Env []string
// Dir is the working directory of the process. An empty Dir means the
// current directory.
Dir string
// SysProcAttr holds the operating system specific settings of the process.
SysProcAttr *syscall.SysProcAttr
// Process is the process, once it has been started.
Process *os.Process
// ProcessState describes the process once it has exited.
ProcessState *os.ProcessState
// Cancel stops the process when the context of the command is done. It
// defaults to killing the process with [os.Process.Kill], and has to be
// set before the command is started.
Cancel func() error
// contains filtered or unexported fields
}
Cmd is a command that runs on a pseudo-terminal.
Its fields are the ones of os/exec.Cmd that every terminal can honour. A command always comes from the terminal it runs on, which is what decides how a process is attached to it:
shell := vt.Command("bash") // a terminal in this process
shell := console.Command("cmd.exe") // the Windows console host
The command is started with Cmd.Start, waited for with Cmd.Wait, and Cmd.Run does both. A command is started and waited for once: the fields below, Cmd.Cancel included, have to be set before Cmd.Start is called, and only one goroutine may do it.
func (*Cmd) Start ¶
Start starts the command on the terminal it came from.
A command that was created with Terminal.CommandContext is stopped with Cmd.Cancel when its context is done, in the same way os/exec stops a command created with os/exec.CommandContext.
func (*Cmd) Wait ¶
Wait waits for the command to exit and releases what the terminal held for it. It returns an error when the command has not been started, or has already been waited for.
A command whose context is done while it is being waited for is stopped, and reports the error of the context, so that errors.Is(err, context.Canceled) holds on every system, whether the process ends with a signal or with an exit code. A command that had already finished when it was stopped is not blamed on the context, and a command that could not be stopped reports that failure.
type ConPTY ¶
type ConPTY struct{}
ConPTY is the stand-in for the Windows pseudo-console on systems that have no ConPTY: it keeps programs that mention the type compiling, and every operation fails with ErrUnsupported. On Windows it is implemented by conpty_windows.go and fully functional.
func NewConPTY ¶
NewConPTY creates a pseudo-console of the requested size. It always fails with ErrUnsupported outside Windows.
func NewConPTYWithPipes ¶
func NewConPTYWithPipes(inPipeRead, inPipeWrite, outPipeRead, outPipeWrite uintptr, width, height, flags int) (*ConPTY, error)
NewConPTYWithPipes creates a pseudo-console that uses the given pipe handles. It always fails with ErrUnsupported outside Windows.
func (*ConPTY) CommandContext ¶
CommandContext returns a command that runs on the terminal and is stopped when ctx is done. A nil context is a mistake, which Cmd.Start reports as ErrNilContext.
func (*ConPTY) InPipeWriteFd ¶
InPipeWriteFd always returns 0.
func (*ConPTY) OutPipeReadFd ¶
OutPipeReadFd always returns 0.
func (*ConPTY) OutPipeWriteFd ¶
OutPipeWriteFd always returns 0.
func (*ConPTY) Read ¶
Read always fails with ErrUnsupported.
func (*ConPTY) Resize ¶
Resize always fails with ErrUnsupported.
func (*ConPTY) Size ¶
Size always fails with ErrUnsupported.
type Terminal ¶
type Terminal interface {
io.ReadWriteCloser
// Resize changes the size of the terminal.
Resize(width, height int) error
// Size returns the current size of the terminal.
Size() (width, height int, err error)
// Command returns a command that runs on the terminal; see [Cmd].
Command(name string, args ...string) *Cmd
// CommandContext returns a command that runs on the terminal and is stopped
// when ctx is done; see [Cmd].
CommandContext(ctx context.Context, name string, args ...string) *Cmd
}
Terminal is the behaviour of a pseudo-terminal that is driven through a single object rather than through a pair of files.
It is implemented by ConPTY, the real Windows pseudo-console, and by VirtualPTY, the in-memory terminal that works everywhere. A pseudo-terminal created by Open or Start is a pair of *os.File values instead, driven with Read, Write, SetSize and GetSize.
type VirtualPTY ¶
type VirtualPTY struct {
// contains filtered or unexported fields
}
VirtualPTY is a pseudo-terminal whose two ends live in the same process: it needs neither operating system support nor a child process, so it is available on every system this package builds on, and it lets a program that expects to run on a terminal run inside the process that drives it.
The terminal starts in canonical (cooked) mode and behaves like a real one: the input written with Write is echoed back, it only reaches the hosted program one complete line at a time, the erase and end-of-file characters are processed, and the line feeds the program writes are expanded to carriage return plus line feed on the way back, so a program that writes a carriage return of its own, as Windows programs do, gets two of them. Each of those is what a terminal does; VirtualPTY.SetRaw turns all of it off.
Like a real terminal, it holds a bounded amount of data: a program that writes more than the terminal can hold waits until the terminal is read, and so does a terminal that is typed into faster than the program reads.
Driving a program that runs in the same process ¶
VirtualPTY.Slave returns the end of the terminal the hosted program uses. Handing it to a program that only needs a reader for its input and writers for its output is enough to give that program a terminal, without starting another process. A shell interpreter, such as the one in mvdan.cc/sh/v3, is the classic example:
vt := pty.NewVirtualPTY(80, 24)
defer vt.Close()
runner, err := interp.New(interp.StdIO(vt.Slave(), vt.Slave(), vt.Slave()))
if err != nil {
return err
}
go runner.Run(ctx, file)
// Type a command on the terminal and read what the shell answers.
vt.Write([]byte("echo hello\n"))
io.Copy(os.Stdout, vt)
The same value can be used as the standard streams of a child process with os/exec, but note that such a process does not get a controlling terminal: it cannot open /dev/tty, read terminal attributes or receive signals from the terminal. Use Open or Start when that matters.
A VirtualPTY is safe for concurrent use by multiple goroutines.
func NewVirtualPTY ¶
func NewVirtualPTY(width, height int) *VirtualPTY
NewVirtualPTY returns a new in-memory pseudo-terminal of the given size. A width or height that is zero or negative is replaced by DefaultWidth or DefaultHeight, as NewConPTY does.
The terminal must be closed with VirtualPTY.Close when it is no longer needed.
func (*VirtualPTY) Close ¶
func (v *VirtualPTY) Close() error
Close ends the terminal: the hosted program still reads the input the terminal had set aside for it and then sees the end of its input, and the terminal still reads the output the program had written; after that, reads of the terminal report io.EOF and writes fail with os.ErrClosed. Closing a terminal more than once is safe.
func (*VirtualPTY) Command ¶
func (v *VirtualPTY) Command(name string, args ...string) *Cmd
Command returns a command that runs on the terminal; see Cmd.
The input of the terminal is shared with the other readers of its program end, so what is typed reaches the command in turn, as it does when several processes read the same terminal. Waiting for the command gives the input back: see Cmd.Wait.
func (*VirtualPTY) CommandContext ¶
CommandContext returns a command that runs on the terminal and is stopped when ctx is done. A nil context is a mistake, which Cmd.Start reports as ErrNilContext.
func (*VirtualPTY) OnInterrupt ¶
func (v *VirtualPTY) OnInterrupt(handler func())
OnInterrupt registers a handler that is called, in its own goroutine, when the interrupt character (^C) is typed on the terminal. A nil handler removes the current one.
A real terminal delivers a signal to the programs running on it instead; since a virtual terminal hosts no processes, the program driving it is told about the interruption here. Cancelling the context of a shell interpreter, for instance, is what makes it stop the command it is running. Interrupt characters typed in the same call to VirtualPTY.Write are reported as a single interruption.
func (*VirtualPTY) Read ¶
func (v *VirtualPTY) Read(p []byte) (int, error)
Read reads what the hosted program wrote, with the translation a terminal applies to its output: each line feed becomes a carriage return followed by a line feed, unless the terminal is in raw mode.
Read blocks until the program writes something, and returns io.EOF once the program has closed its end of the terminal or the terminal itself is closed.
func (*VirtualPTY) Resize ¶
func (v *VirtualPTY) Resize(width, height int) error
Resize changes the size of the terminal. The size is stored as given, so that a program that asks for a size of zero, which some do to mean "unknown", gets exactly that.
func (*VirtualPTY) SetRaw ¶
func (v *VirtualPTY) SetRaw(raw bool)
SetRaw switches the terminal between raw mode and canonical (cooked) mode, the mode it starts in. In raw mode input is handed to the hosted program byte by byte, without echo, without line buffering and without any translation of the input or the output, which is what a full screen program expects.
What a terminal has typed but not handed over yet when it stops assembling lines is handed to the program right away.
func (*VirtualPTY) Size ¶
func (v *VirtualPTY) Size() (width, height int, err error)
Size returns the size the terminal was created with or last resized to.
The error result is always nil; the method returns one so that its signature matches the other terminals of this package.
func (*VirtualPTY) Slave ¶
func (v *VirtualPTY) Slave() io.ReadWriteCloser
Slave returns the end of the terminal the hosted program uses: what is typed with VirtualPTY.Write is read from it, line by line, and what is written to it is read from the terminal with VirtualPTY.Read.
Like the slave device of a real terminal it is a single end, so closing it ends the input and the output of the program at once. The value belongs to the terminal and stays valid until then; it reports io.EOF for both reads and writes afterwards.
func (*VirtualPTY) Write ¶
func (v *VirtualPTY) Write(p []byte) (int, error)
Write sends input to the terminal, as a user typing on it would. In canonical mode the input is echoed back and only a complete line reaches the hosted program; see VirtualPTY and VirtualPTY.SetRaw.
Write waits while the program has not read the input the terminal holds for it, and while the echo and the output of the program have not been read. It returns os.ErrClosed once the terminal is closed, or once the program has closed its end of it.
type Winsize ¶
type Winsize struct {
Rows uint16 // Number of rows, in cells (ws_row).
Cols uint16 // Number of columns, in cells (ws_col).
X uint16 // Width in pixels (ws_xpixel).
Y uint16 // Height in pixels (ws_ypixel).
}
Winsize describes the size of a terminal, in character cells and in pixels.
Rows and Cols are what terminal applications care about; X and Y are the pixel size and stay zero on terminals that do not report it.