-
Notifications
You must be signed in to change notification settings - Fork 6
/
pty.go
134 lines (106 loc) · 2.32 KB
/
pty.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
// Create a pty for us
package main
import (
"io"
"os"
"sync"
"github.com/pkg/term/termios"
"golang.org/x/sys/unix"
)
type winsize struct {
Rows uint16 // ws_row: Number of rows (in cells)
Cols uint16 // ws_col: Number of columns (in cells)
X uint16 // ws_xpixel: Width in pixels
Y uint16 // ws_ypixel: Height in pixels
}
type pty struct {
wg sync.WaitGroup
signals chan os.Signal
previousStdinTermios unix.Termios
stdinIsatty bool
master *os.File
slave *os.File
}
func createPty() (*pty, error) {
master, slave, err := termios.Pty()
if err != nil {
return nil, err
}
return &pty{
master: master,
slave: slave,
signals: make(chan os.Signal, 1),
}, nil
}
func (p *pty) Stdin() *os.File {
return p.slave
}
func (p *pty) Stdout() *os.File {
return p.slave
}
func (p *pty) Stderr() *os.File {
return p.slave
}
func (p *pty) Start() error {
err := p.makeStdinRaw()
if err != nil {
return err
}
p.wg.Add(2)
go func() {
io.Copy(p.master, os.Stdin)
p.wg.Done()
}()
go func() {
io.Copy(os.Stdout, p.master)
p.wg.Done()
}()
p.inheritWindowSize()
return nil
}
func (p *pty) Terminate() {
p.restoreStdin()
p.master.Close()
p.slave.Close()
close(p.signals)
// TODO: somehow I can't figure out how to have the
// spawned process send an EOF when its fds are closed,
// so for this reason the io.Copy calls above never return.
//p.wg.Wait()
}
func (p *pty) inheritWindowSize() error {
winsz, err := unix.IoctlGetWinsize(int(os.Stdout.Fd()), unix.TIOCGWINSZ)
if err != nil {
return err
}
if err := unix.IoctlSetWinsize(int(p.master.Fd()), unix.TIOCSWINSZ, winsz); err != nil {
return err
}
return nil
}
func (p *pty) makeStdinRaw() error {
var stdinTermios unix.Termios
err := termios.Tcgetattr(os.Stdin.Fd(), &stdinTermios)
// We might get ENOTTY if stdin is redirected
if err != nil {
if errno, ok := err.(unix.Errno); ok {
if errno == unix.ENOTTY {
return nil
} else {
return err
}
}
}
p.previousStdinTermios = stdinTermios
p.stdinIsatty = true
termios.Cfmakeraw(&stdinTermios)
if err := termios.Tcsetattr(os.Stdin.Fd(), termios.TCSANOW, &stdinTermios); err != nil {
return err
}
return nil
}
func (p *pty) restoreStdin() {
if p.stdinIsatty {
_ = termios.Tcsetattr(os.Stdin.Fd(), termios.TCSANOW, &p.previousStdinTermios)
}
}