-
Notifications
You must be signed in to change notification settings - Fork 2
/
shell.go
291 lines (228 loc) · 5.26 KB
/
shell.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package main
import (
"fmt"
"io"
"log"
"os"
"os/exec"
"os/signal"
"syscall"
"github.com/creack/pty"
"golang.org/x/crypto/ssh/terminal"
)
const bufferSize = 8 * 1024
type shell struct {
cmdLine []string
stdin io.ReadCloser
stdout io.WriteCloser
interceptor shellInterceptor
command *exec.Cmd
ptmx *os.File
cleanups []func(*shell)
}
func (s *shell) Open(options shellOptions) (returnedErr error) {
options.Sanitize()
s.cmdLine = options.CmdLine
s.stdin = options.Stdin
s.stdout = options.Stdout
defer func() {
if returnedErr != nil {
s.stdin.Close()
s.stdout.Close()
}
}()
if err := s.createShellInterceptor(options.ShellInterceptorFactory); err != nil {
return err
}
defer func() {
if returnedErr != nil {
s.Close()
}
}()
if err := s.startPTY(); err != nil {
return err
}
if err := s.makeTerminalRaw(); err != nil {
return err
}
s.resizePTY()
s.pipeStdin()
s.pipeStdout()
return nil
}
func (s *shell) Close() {
for _, cleanup := range s.cleanups {
cleanup(s)
}
s.cleanups = nil
}
func (s *shell) Wait() (_ int, returnedErr error) {
defer func() {
if returnedErr != nil {
s.stdin.Close()
}
}()
if err := s.command.Wait(); err != nil {
if exitError, ok := err.(*exec.ExitError); ok {
return exitError.ExitCode(), nil
}
return 0, fmt.Errorf("wait shell failed: %v", err)
}
return 0, nil
}
func (s *shell) createShellInterceptor(shellInterceptorFactory shellInterceptorFactory) error {
inputDataSender := func(data []byte) bool {
if _, err := s.ptmx.Write(data); err != nil {
log.Printf("write ptmx failed: %v", err)
return false
}
return true
}
outputDataSender := func(data []byte) bool {
if _, err := s.stdout.Write(data); err != nil {
log.Printf("write stdout failed: %v", err)
return false
}
return true
}
shellInterceptor, err := shellInterceptorFactory(inputDataSender, outputDataSender)
if err != nil {
log.Printf("create shell interceptor failed: %v", err)
return err
}
s.interceptor = shellInterceptor
return nil
}
func (s *shell) startPTY() error {
s.command = exec.Command(s.cmdLine[0], s.cmdLine[1:]...)
var err error
s.ptmx, err = pty.Start(s.command)
if err != nil {
return fmt.Errorf("start pty failed: %v", err)
}
s.cleanups = append(s.cleanups, func(s *shell) { s.ptmx.Close() })
return nil
}
func (s *shell) makeTerminalRaw() error {
stdin, ok := s.stdin.(*os.File)
if !ok {
return nil
}
oldState, err := terminal.MakeRaw(int(stdin.Fd()))
if err != nil {
return fmt.Errorf("make terminal raw failed: %v", err)
}
s.cleanups = append(s.cleanups, func(*shell) { terminal.Restore(int(stdin.Fd()), oldState) })
return nil
}
func (s *shell) resizePTY() {
stdin, ok := s.stdin.(*os.File)
if !ok {
return
}
signals := make(chan os.Signal, 1)
s.cleanups = append(s.cleanups, func(*shell) { close(signals) })
signal.Notify(signals, syscall.SIGWINCH)
go func() {
for range signals {
if err := pty.InheritSize(stdin, s.ptmx); err != nil {
log.Printf("resize pty failed: %s", err)
}
}
}()
signals <- syscall.SIGWINCH
}
func (s *shell) pipeStdin() {
go func() {
buffer := make([]byte, bufferSize)
for {
n, err := s.stdin.Read(buffer)
if err != nil {
if err == io.EOF {
return
}
log.Printf("read stdin failed: %v", err)
return
}
data := buffer[:n]
if !s.interceptor.HandleInputData(data) {
return
}
}
}()
}
func (s *shell) pipeStdout() {
go func() {
defer s.stdout.Close()
buffer := make([]byte, bufferSize)
for {
n, err := s.ptmx.Read(buffer)
if err != nil {
if err == io.EOF {
return
}
log.Printf("read ptmx failed: %v", err)
return
}
data := buffer[:n]
if !s.interceptor.HandleOutputData(data) {
return
}
}
}()
}
type shellOptions struct {
CmdLine []string
Stdin io.ReadCloser
Stdout io.WriteCloser
ShellInterceptorFactory shellInterceptorFactory
}
func (so *shellOptions) Sanitize() {
if len(so.CmdLine) == 0 {
if len(os.Args) < 2 {
so.CmdLine = []string{getShellName()}
} else {
so.CmdLine = os.Args[1:]
}
}
if so.Stdin == nil {
so.Stdin = os.Stdin
}
if so.Stdout == nil {
so.Stdout = os.Stdout
}
if so.ShellInterceptorFactory == nil {
so.ShellInterceptorFactory = dummyShellInterceptorFactory
}
}
type (
shellInterceptorFactory func(inputDataSender, outputDataSender dataSender) (shellInterceptor shellInterceptor, ok error)
dataSender func(data []byte) (ok bool)
shellInterceptor interface {
HandleInputData([]byte) (ok bool)
HandleOutputData([]byte) (ok bool)
}
)
type dummyShellInterceptor struct {
InputDataSender dataSender
OutputDataSender dataSender
}
func (dsi *dummyShellInterceptor) HandleInputData(data []byte) bool {
return dsi.InputDataSender(data)
}
func (dsi *dummyShellInterceptor) HandleOutputData(data []byte) bool {
return dsi.OutputDataSender(data)
}
func dummyShellInterceptorFactory(inputDataSender, outputDataSender dataSender) (shellInterceptor, error) {
return &dummyShellInterceptor{
InputDataSender: inputDataSender,
OutputDataSender: outputDataSender,
}, nil
}
func getShellName() string {
shellName, ok := os.LookupEnv("SHELL")
if !ok {
shellName = "sh"
}
return shellName
}