forked from yudai/gotty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webtty.go
219 lines (180 loc) · 4.53 KB
/
webtty.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
package webtty
import (
"context"
"encoding/base64"
"encoding/json"
"sync"
"github.com/pkg/errors"
)
// WebTTY bridges a PTY slave and its PTY master.
// To support text-based streams and side channel commands such as
// terminal resizing, WebTTY uses an original protocol.
type WebTTY struct {
// PTY Master, which probably a connection to browser
masterConn Master
// PTY Slave
slave Slave
windowTitle []byte
permitWrite bool
columns int
rows int
reconnect int // in seconds
masterPrefs []byte
bufferSize int
writeMutex sync.Mutex
}
// New creates a new instance of WebTTY.
// masterConn is a connection to the PTY master,
// typically it's a websocket connection to a client.
// slave is a PTY slave such as a local command with a PTY.
func New(masterConn Master, slave Slave, options ...Option) (*WebTTY, error) {
wt := &WebTTY{
masterConn: masterConn,
slave: slave,
permitWrite: false,
columns: 0,
rows: 0,
bufferSize: 1024,
}
for _, option := range options {
option(wt)
}
return wt, nil
}
// Run starts the main process of the WebTTY.
// This method blocks until the context is canceled.
// Note that the master and slave are left intact even
// after the context is canceled. Closing them is caller's
// responsibility.
// If the connection to one end gets closed, returns ErrSlaveClosed or ErrMasterClosed.
func (wt *WebTTY) Run(ctx context.Context) error {
err := wt.sendInitializeMessage()
if err != nil {
return errors.Wrapf(err, "failed to send initializing message")
}
errs := make(chan error, 2)
go func() {
errs <- func() error {
buffer := make([]byte, wt.bufferSize)
for {
n, err := wt.slave.Read(buffer)
if err != nil {
return ErrSlaveClosed
}
err = wt.handleSlaveReadEvent(buffer[:n])
if err != nil {
return err
}
}
}()
}()
go func() {
errs <- func() error {
buffer := make([]byte, wt.bufferSize)
for {
n, err := wt.masterConn.Read(buffer)
if err != nil {
return ErrMasterClosed
}
err = wt.handleMasterReadEvent(buffer[:n])
if err != nil {
return err
}
}
}()
}()
select {
case <-ctx.Done():
err = ctx.Err()
case err = <-errs:
}
return err
}
func (wt *WebTTY) sendInitializeMessage() error {
err := wt.masterWrite(append([]byte{SetWindowTitle}, wt.windowTitle...))
if err != nil {
return errors.Wrapf(err, "failed to send window title")
}
if wt.reconnect > 0 {
reconnect, _ := json.Marshal(wt.reconnect)
err := wt.masterWrite(append([]byte{SetReconnect}, reconnect...))
if err != nil {
return errors.Wrapf(err, "failed to set reconnect")
}
}
if wt.masterPrefs != nil {
err := wt.masterWrite(append([]byte{SetPreferences}, wt.masterPrefs...))
if err != nil {
return errors.Wrapf(err, "failed to set preferences")
}
}
return nil
}
func (wt *WebTTY) handleSlaveReadEvent(data []byte) error {
safeMessage := base64.StdEncoding.EncodeToString(data)
err := wt.masterWrite(append([]byte{Output}, []byte(safeMessage)...))
if err != nil {
return errors.Wrapf(err, "failed to send message to master")
}
return nil
}
func (wt *WebTTY) masterWrite(data []byte) error {
wt.writeMutex.Lock()
defer wt.writeMutex.Unlock()
_, err := wt.masterConn.Write(data)
if err != nil {
return errors.Wrapf(err, "failed to write to master")
}
return nil
}
func (wt *WebTTY) handleMasterReadEvent(data []byte) error {
if len(data) == 0 {
return errors.New("unexpected zero length read from master")
}
switch data[0] {
case Input:
if !wt.permitWrite {
return nil
}
if len(data) <= 1 {
return nil
}
_, err := wt.slave.Write(data[1:])
if err != nil {
return errors.Wrapf(err, "failed to write received data to slave")
}
case Ping:
err := wt.masterWrite([]byte{Pong})
if err != nil {
return errors.Wrapf(err, "failed to return Pong message to master")
}
case ResizeTerminal:
if wt.columns != 0 && wt.rows != 0 {
break
}
if len(data) <= 1 {
return errors.New("received malformed remote command for terminal resize: empty payload")
}
var args argResizeTerminal
err := json.Unmarshal(data[1:], &args)
if err != nil {
return errors.Wrapf(err, "received malformed data for terminal resize")
}
rows := wt.rows
if rows == 0 {
rows = int(args.Rows)
}
columns := wt.columns
if columns == 0 {
columns = int(args.Columns)
}
wt.slave.ResizeTerminal(columns, rows)
default:
return errors.Errorf("unknown message type `%c`", data[0])
}
return nil
}
type argResizeTerminal struct {
Columns float64
Rows float64
}