aboutsummaryrefslogtreecommitdiff
path: root/vendor/github.com/chzyer/readline/remote.go
blob: 74dbf5690221f1a4ac77debd533ebc4aa837e8f3 (plain)
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
package readline

import (
	"bufio"
	"bytes"
	"encoding/binary"
	"fmt"
	"io"
	"net"
	"os"
	"sync"
	"sync/atomic"
)

type MsgType int16

const (
	T_DATA = MsgType(iota)
	T_WIDTH
	T_WIDTH_REPORT
	T_ISTTY_REPORT
	T_RAW
	T_ERAW // exit raw
	T_EOF
)

type RemoteSvr struct {
	eof           int32
	closed        int32
	width         int32
	reciveChan    chan struct{}
	writeChan     chan *writeCtx
	conn          net.Conn
	isTerminal    bool
	funcWidthChan func()
	stopChan      chan struct{}

	dataBufM sync.Mutex
	dataBuf  bytes.Buffer
}

type writeReply struct {
	n   int
	err error
}

type writeCtx struct {
	msg   *Message
	reply chan *writeReply
}

func newWriteCtx(msg *Message) *writeCtx {
	return &writeCtx{
		msg:   msg,
		reply: make(chan *writeReply),
	}
}

func NewRemoteSvr(conn net.Conn) (*RemoteSvr, error) {
	rs := &RemoteSvr{
		width:      -1,
		conn:       conn,
		writeChan:  make(chan *writeCtx),
		reciveChan: make(chan struct{}),
		stopChan:   make(chan struct{}),
	}
	buf := bufio.NewReader(rs.conn)

	if err := rs.init(buf); err != nil {
		return nil, err
	}

	go rs.readLoop(buf)
	go rs.writeLoop()
	return rs, nil
}

func (r *RemoteSvr) init(buf *bufio.Reader) error {
	m, err := ReadMessage(buf)
	if err != nil {
		return err
	}
	// receive isTerminal
	if m.Type != T_ISTTY_REPORT {
		return fmt.Errorf("unexpected init message")
	}
	r.GotIsTerminal(m.Data)

	// receive width
	m, err = ReadMessage(buf)
	if err != nil {
		return err
	}
	if m.Type != T_WIDTH_REPORT {
		return fmt.Errorf("unexpected init message")
	}
	r.GotReportWidth(m.Data)

	return nil
}

func (r *RemoteSvr) HandleConfig(cfg *Config) {
	cfg.Stderr = r
	cfg.Stdout = r
	cfg.Stdin = r
	cfg.FuncExitRaw = r.ExitRawMode
	cfg.FuncIsTerminal = r.IsTerminal
	cfg.FuncMakeRaw = r.EnterRawMode
	cfg.FuncExitRaw = r.ExitRawMode
	cfg.FuncGetWidth = r.GetWidth
	cfg.FuncOnWidthChanged = func(f func()) {
		r.funcWidthChan = f
	}
}

func (r *RemoteSvr) IsTerminal() bool {
	return r.isTerminal
}

func (r *RemoteSvr) checkEOF() error {
	if atomic.LoadInt32(&r.eof) == 1 {
		return io.EOF
	}
	return nil
}

func (r *RemoteSvr) Read(b []byte) (int, error) {
	r.dataBufM.Lock()
	n, err := r.dataBuf.Read(b)
	r.dataBufM.Unlock()
	if n == 0 {
		if err := r.checkEOF(); err != nil {
			return 0, err
		}
	}

	if n == 0 && err == io.EOF {
		<-r.reciveChan
		r.dataBufM.Lock()
		n, err = r.dataBuf.Read(b)
		r.dataBufM.Unlock()
	}
	if n == 0 {
		if err := r.checkEOF(); err != nil {
			return 0, err
		}
	}

	return n, err
}

func (r *RemoteSvr) writeMsg(m *Message) error {
	ctx := newWriteCtx(m)
	r.writeChan <- ctx
	reply := <-ctx.reply
	return reply.err
}

func (r *RemoteSvr) Write(b []byte) (int, error) {
	ctx := newWriteCtx(NewMessage(T_DATA, b))
	r.writeChan <- ctx
	reply := <-ctx.reply
	return reply.n, reply.err
}

func (r *RemoteSvr) EnterRawMode() error {
	return r.writeMsg(NewMessage(T_RAW, nil))
}

func (r *RemoteSvr) ExitRawMode() error {
	return r.writeMsg(NewMessage(T_ERAW, nil))
}

func (r *RemoteSvr) writeLoop() {
	defer r.Close()

loop:
	for {
		select {
		case ctx, ok := <-r.writeChan:
			if !ok {
				break
			}
			n, err := ctx.msg.WriteTo(r.conn)
			ctx.reply <- &writeReply{n, err}
		case <-r.stopChan:
			break loop
		}
	}
}

func (r *RemoteSvr) Close() error {
	if atomic.CompareAndSwapInt32(&r.closed, 0, 1) {
		close(r.stopChan)
		r.conn.Close()
	}
	return nil
}

func (r *RemoteSvr) readLoop(buf *bufio.Reader) {
	defer r.Close()
	for {
		m, err := ReadMessage(buf)
		if err != nil {
			break
		}
		switch m.Type {
		case T_EOF:
			atomic.StoreInt32(&r.eof, 1)
			select {
			case r.reciveChan <- struct{}{}:
			default:
			}
		case T_DATA:
			r.dataBufM.Lock()
			r.dataBuf.Write(m.Data)
			r.dataBufM.Unlock()
			select {
			case r.reciveChan <- struct{}{}:
			default:
			}
		case T_WIDTH_REPORT:
			r.GotReportWidth(m.Data)
		case T_ISTTY_REPORT:
			r.GotIsTerminal(m.Data)
		}
	}
}

func (r *RemoteSvr) GotIsTerminal(data []byte) {
	if binary.BigEndian.Uint16(data) == 0 {
		r.isTerminal = false
	} else {
		r.isTerminal = true
	}
}

func (r *RemoteSvr) GotReportWidth(data []byte) {
	atomic.StoreInt32(&r.width, int32(binary.BigEndian.Uint16(data)))
	if r.funcWidthChan != nil {
		r.funcWidthChan()
	}
}

func (r *RemoteSvr) GetWidth() int {
	return int(atomic.LoadInt32(&r.width))
}

// -----------------------------------------------------------------------------

type Message struct {
	Type MsgType
	Data []byte
}

func ReadMessage(r io.Reader) (*Message, error) {
	m := new(Message)
	var length int32
	if err := binary.Read(r, binary.BigEndian, &length); err != nil {
		return nil, err
	}
	if err := binary.Read(r, binary.BigEndian, &m.Type); err != nil {
		return nil, err
	}
	m.Data = make([]byte, int(length)-2)
	if _, err := io.ReadFull(r, m.Data); err != nil {
		return nil, err
	}
	return m, nil
}

func NewMessage(t MsgType, data []byte) *Message {
	return &Message{t, data}
}

func (m *Message) WriteTo(w io.Writer) (int, error) {
	buf := bytes.NewBuffer(make([]byte, 0, len(m.Data)+2+4))
	binary.Write(buf, binary.BigEndian, int32(len(m.Data)+2))
	binary.Write(buf, binary.BigEndian, m.Type)
	buf.Write(m.Data)
	n, err := buf.WriteTo(w)
	return int(n), err
}

// -----------------------------------------------------------------------------

type RemoteCli struct {
	conn        net.Conn
	raw         RawMode
	receiveChan chan struct{}
	inited      int32
	isTerminal  *bool

	data  bytes.Buffer
	dataM sync.Mutex
}

func NewRemoteCli(conn net.Conn) (*RemoteCli, error) {
	r := &RemoteCli{
		conn:        conn,
		receiveChan: make(chan struct{}),
	}
	return r, nil
}

func (r *RemoteCli) MarkIsTerminal(is bool) {
	r.isTerminal = &is
}

func (r *RemoteCli) init() error {
	if !atomic.CompareAndSwapInt32(&r.inited, 0, 1) {
		return nil
	}

	if err := r.reportIsTerminal(); err != nil {
		return err
	}

	if err := r.reportWidth(); err != nil {
		return err
	}

	// register sig for width changed
	DefaultOnWidthChanged(func() {
		r.reportWidth()
	})
	return nil
}

func (r *RemoteCli) writeMsg(m *Message) error {
	r.dataM.Lock()
	_, err := m.WriteTo(r.conn)
	r.dataM.Unlock()
	return err
}

func (r *RemoteCli) Write(b []byte) (int, error) {
	m := NewMessage(T_DATA, b)
	r.dataM.Lock()
	_, err := m.WriteTo(r.conn)
	r.dataM.Unlock()
	return len(b), err
}

func (r *RemoteCli) reportWidth() error {
	screenWidth := GetScreenWidth()
	data := make([]byte, 2)
	binary.BigEndian.PutUint16(data, uint16(screenWidth))
	msg := NewMessage(T_WIDTH_REPORT, data)

	if err := r.writeMsg(msg); err != nil {
		return err
	}
	return nil
}

func (r *RemoteCli) reportIsTerminal() error {
	var isTerminal bool
	if r.isTerminal != nil {
		isTerminal = *r.isTerminal
	} else {
		isTerminal = DefaultIsTerminal()
	}
	data := make([]byte, 2)
	if isTerminal {
		binary.BigEndian.PutUint16(data, 1)
	} else {
		binary.BigEndian.PutUint16(data, 0)
	}
	msg := NewMessage(T_ISTTY_REPORT, data)
	if err := r.writeMsg(msg); err != nil {
		return err
	}
	return nil
}

func (r *RemoteCli) readLoop() {
	buf := bufio.NewReader(r.conn)
	for {
		msg, err := ReadMessage(buf)
		if err != nil {
			break
		}
		switch msg.Type {
		case T_ERAW:
			r.raw.Exit()
		case T_RAW:
			r.raw.Enter()
		case T_DATA:
			os.Stdout.Write(msg.Data)
		}
	}
}

func (r *RemoteCli) ServeBy(source io.Reader) error {
	if err := r.init(); err != nil {
		return err
	}

	go func() {
		defer r.Close()
		for {
			n, _ := io.Copy(r, source)
			if n == 0 {
				break
			}
		}
	}()
	defer r.raw.Exit()
	r.readLoop()
	return nil
}

func (r *RemoteCli) Close() {
	r.writeMsg(NewMessage(T_EOF, nil))
}

func (r *RemoteCli) Serve() error {
	return r.ServeBy(os.Stdin)
}

func ListenRemote(n, addr string, cfg *Config, h func(*Instance), onListen ...func(net.Listener) error) error {
	ln, err := net.Listen(n, addr)
	if err != nil {
		return err
	}
	if len(onListen) > 0 {
		if err := onListen[0](ln); err != nil {
			return err
		}
	}
	for {
		conn, err := ln.Accept()
		if err != nil {
			break
		}
		go func() {
			defer conn.Close()
			rl, err := HandleConn(*cfg, conn)
			if err != nil {
				return
			}
			h(rl)
		}()
	}
	return nil
}

func HandleConn(cfg Config, conn net.Conn) (*Instance, error) {
	r, err := NewRemoteSvr(conn)
	if err != nil {
		return nil, err
	}
	r.HandleConfig(&cfg)

	rl, err := NewEx(&cfg)
	if err != nil {
		return nil, err
	}
	return rl, nil
}

func DialRemote(n, addr string) error {
	conn, err := net.Dial(n, addr)
	if err != nil {
		return err
	}
	defer conn.Close()

	cli, err := NewRemoteCli(conn)
	if err != nil {
		return err
	}
	return cli.Serve()
}