-
Notifications
You must be signed in to change notification settings - Fork 5
/
client.go
355 lines (320 loc) · 7.9 KB
/
client.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
package wsep
import (
"bytes"
"context"
"encoding/json"
"io"
"net"
"strings"
"cdr.dev/wsep/internal/proto"
"golang.org/x/xerrors"
"nhooyr.io/websocket"
)
const maxMessageSize = 64000
type remoteExec struct {
conn *websocket.Conn
}
// RemoteExecer creates an execution interface from a WebSocket connection.
func RemoteExecer(conn *websocket.Conn) Execer {
conn.SetReadLimit(maxMessageSize)
return remoteExec{conn: conn}
}
// Command represents an external command to be run
type Command struct {
// ID allows reconnecting commands that have a TTY.
ID string
Command string
Args []string
// Commands with a TTY also require Rows and Cols.
TTY bool
Rows uint16
Cols uint16
Stdin bool
UID uint32
GID uint32
Env []string
WorkingDir string
}
// Start runs the command on the remote. Once a command is started, callers should
// not read from, write to, or close the websocket. Closing the returned Process will
// also close the websocket.
func (r remoteExec) Start(ctx context.Context, c Command) (Process, error) {
header := proto.ClientStartHeader{
ID: c.ID,
Command: mapToProtoCmd(c),
Type: proto.TypeStart,
}
payload, err := json.Marshal(header)
if err != nil {
return nil, err
}
err = r.conn.Write(ctx, websocket.MessageBinary, payload)
if err != nil {
return nil, err
}
_, payload, err = r.conn.Read(ctx)
if err != nil {
return nil, xerrors.Errorf("read pid message: %w", err)
}
var pidHeader proto.ServerPidHeader
err = json.Unmarshal(payload, &pidHeader)
if err != nil {
return nil, xerrors.Errorf("failed to parse pid message: %w", err)
}
var stdin io.WriteCloser
if c.Stdin {
stdin = remoteStdin{
conn: websocket.NetConn(ctx, r.conn, websocket.MessageBinary),
}
} else {
stdin = disabledStdinWriter{}
}
listenCtx, cancelListen := context.WithCancel(ctx)
rp := &remoteProcess{
ctx: ctx,
conn: r.conn,
cmd: c,
pid: pidHeader.Pid,
done: make(chan struct{}),
stderr: newPipe(),
stderrData: make(chan []byte),
stdout: newPipe(),
stdoutData: make(chan []byte),
stdin: stdin,
cancelListen: cancelListen,
}
go rp.listen(listenCtx)
return rp, nil
}
type remoteProcess struct {
ctx context.Context
cancelListen func()
cmd Command
conn *websocket.Conn
pid int
done chan struct{}
closeErr error
exitMsg *proto.ServerExitCodeHeader
readErr error
stdin io.WriteCloser
stdout pipe
stdoutErr error
stdoutData chan []byte
stderr pipe
stderrErr error
stderrData chan []byte
}
type remoteStdin struct {
conn net.Conn
}
func (r remoteStdin) Write(b []byte) (int, error) {
stdinHeader := proto.Header{
Type: proto.TypeStdin,
}
headerByt, err := json.Marshal(stdinHeader)
if err != nil {
return 0, err
}
stdinWriter := proto.WithHeader(r.conn, headerByt)
maxBodySize := maxMessageSize - len(headerByt) - 1
var nn int
for len(b) > maxMessageSize {
n, err := stdinWriter.Write(b[:maxBodySize])
nn += n
if err != nil {
return nn, err
}
b = b[maxBodySize:]
}
n, err := stdinWriter.Write(b)
nn += n
return nn, err
}
func (r remoteStdin) Close() error {
closeHeader := proto.Header{
Type: proto.TypeCloseStdin,
}
headerByt, err := json.Marshal(closeHeader)
if err != nil {
return err
}
_, err = proto.WithHeader(r.conn, headerByt).Write(nil)
return err
}
type pipe struct {
r *io.PipeReader
w *io.PipeWriter
d chan []byte
e chan error
buf []byte
}
func newPipe() pipe {
pr, pw := io.Pipe()
return pipe{
r: pr,
w: pw,
d: make(chan []byte),
e: make(chan error),
buf: make([]byte, maxMessageSize),
}
}
// writeCtx writes data to the pipe, or returns if the context is canceled.
func (p *pipe) writeCtx(ctx context.Context, data []byte) error {
// actually do the copy on another goroutine so that we can return if context
// is canceled
go func() {
var err error
select {
case <-ctx.Done():
return
case body := <-p.d:
_, err = io.CopyBuffer(p.w, bytes.NewReader(body), p.buf)
}
select {
case <-ctx.Done():
return
case p.e <- err:
return
}
}()
select {
case <-ctx.Done():
return ctx.Err()
case p.d <- data:
// data being written.
}
select {
case <-ctx.Done():
return ctx.Err()
case err := <-p.e:
return err
}
}
func (r *remoteProcess) listen(ctx context.Context) {
defer func() {
r.stdoutErr = r.stdout.w.Close()
r.stderrErr = r.stderr.w.Close()
r.closeErr = r.conn.Close(websocket.StatusNormalClosure, "normal closure")
// If we were in r.conn.Read() we cancel the ctx, the websocket library closes
// the websocket before we have a chance to. Unfortunately there is a race in the
// the websocket library, where sometimes close frame has already been written before
// we even call r.conn.Close(), and sometimes it gets written during our call to
// r.conn.Close(), so we need to handle both those cases in examining the error that comes
// back. This is a normal closure, so report nil for the error.
readCtxCanceled := r.readErr != nil && strings.Contains(r.readErr.Error(), "context canceled")
alreadyClosed := r.closeErr != nil &&
(strings.Contains(r.closeErr.Error(), "already wrote close") ||
strings.Contains(r.closeErr.Error(), "WebSocket closed"))
if alreadyClosed && readCtxCanceled {
r.closeErr = nil
}
close(r.done)
}()
for ctx.Err() == nil {
_, payload, err := r.conn.Read(ctx)
if err != nil {
r.readErr = err
return
}
headerByt, body := proto.SplitMessage(payload)
var header proto.Header
err = json.Unmarshal(headerByt, &header)
if err != nil {
r.readErr = err
return
}
switch header.Type {
case proto.TypeStderr:
err = r.stderr.writeCtx(ctx, body)
if err != nil {
r.readErr = err
return
}
case proto.TypeStdout:
err = r.stdout.writeCtx(ctx, body)
if err != nil {
r.readErr = err
return
}
case proto.TypeExitCode:
var exitMsg proto.ServerExitCodeHeader
err = json.Unmarshal(headerByt, &exitMsg)
if err != nil {
r.readErr = err
return
}
r.exitMsg = &exitMsg
return
}
}
// if we get here, the context is done, so use that as the read error
r.readErr = ctx.Err()
}
func (r *remoteProcess) Pid() int {
return r.pid
}
func (r *remoteProcess) Stdin() io.WriteCloser {
if !r.cmd.Stdin {
return disabledStdinWriter{}
}
return r.stdin
}
// Stdout returns a reader for standard out from the process. You MUST read from
// this reader even if you don't care about the data to avoid blocking the
// websocket.
func (r *remoteProcess) Stdout() io.Reader {
return r.stdout.r
}
// Stdout returns a reader for standard error from the process. You MUST read from
// this reader even if you don't care about the data to avoid blocking the
// websocket.
func (r *remoteProcess) Stderr() io.Reader {
return r.stderr.r
}
func (r *remoteProcess) Resize(ctx context.Context, rows, cols uint16) error {
header := proto.ClientResizeHeader{
Type: proto.TypeResize,
Cols: cols,
Rows: rows,
}
payload, err := json.Marshal(header)
if err != nil {
return err
}
return r.conn.Write(ctx, websocket.MessageBinary, payload)
}
func (r *remoteProcess) Wait() error {
<-r.done
if r.readErr != nil {
return r.readErr
}
// when listen() closes r.done, either there must be a read error or exitMsg
// is set non-nil, so it's safe to access members here.
if r.exitMsg.ExitCode != 0 {
return ExitError{code: r.exitMsg.ExitCode, error: r.exitMsg.Error}
}
return nil
}
func (r *remoteProcess) Close() error {
r.cancelListen()
<-r.done
closeErr := r.closeErr
return joinErrs(closeErr, r.stdoutErr, r.stderrErr)
}
func joinErrs(errs ...error) error {
var str string
foundErr := false
for _, e := range errs {
if e != nil {
foundErr = true
if str != "" {
str += ", "
}
str += e.Error()
}
}
if foundErr {
return xerrors.New(str)
}
return nil
}