-
Notifications
You must be signed in to change notification settings - Fork 143
/
host.go
287 lines (258 loc) · 6.08 KB
/
host.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
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"log"
"os"
"os/exec"
"os/signal"
"time"
"github.com/kr/pty"
"github.com/maxmcd/webtty/pkg/sd"
"github.com/mitchellh/colorstring"
"github.com/pion/webrtc/v3"
)
type hostSession struct {
session
cmd []string
nonInteractive bool
oneWay bool
ptmx *os.File
ptmxReady bool
tmux bool
}
func (hs *hostSession) dataChannelOnOpen() func() {
return func() {
colorstring.Println("[bold]Terminal session started:")
cmd := exec.Command(hs.cmd[0], hs.cmd[1:]...)
var err error
hs.ptmx, err = pty.Start(cmd)
if err != nil {
log.Println(err)
hs.errChan <- err
return
}
hs.ptmxReady = true
if !hs.nonInteractive {
if err = hs.makeRawTerminal(); err != nil {
log.Println(err)
hs.errChan <- err
return
}
go func() {
if _, err = io.Copy(hs.ptmx, os.Stdin); err != nil {
log.Println(err)
}
}()
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for range c {
log.Println("Sigint")
hs.errChan <- errors.New("sigint")
}
}()
buf := make([]byte, 1024)
for {
nr, err := hs.ptmx.Read(buf)
if err != nil {
if err == io.EOF {
err = nil
} else {
log.Println(err)
}
hs.errChan <- err
return
}
if !hs.nonInteractive {
if _, err = os.Stdout.Write(buf[0:nr]); err != nil {
log.Println(err)
hs.errChan <- err
return
}
}
if err = hs.dc.Send(buf[0:nr]); err != nil {
log.Println(err)
hs.errChan <- err
return
}
}
}
}
func (hs *hostSession) dataChannelOnMessage() func(payload webrtc.DataChannelMessage) {
return func(p webrtc.DataChannelMessage) {
// OnMessage can fire before onOpen
// Let's wait for the pty session to be ready
for hs.ptmxReady != true {
time.Sleep(1 * time.Millisecond)
}
if p.IsString {
if len(p.Data) > 2 && p.Data[0] == '[' && p.Data[1] == '"' {
var msg []string
err := json.Unmarshal(p.Data, &msg)
if len(msg) == 0 {
log.Println(err)
hs.errChan <- err
}
if msg[0] == "stdin" {
toWrite := []byte(msg[1])
if len(toWrite) == 0 {
return
}
_, err := hs.ptmx.Write([]byte(msg[1]))
if err != nil {
log.Println(err)
hs.errChan <- err
}
return
}
if msg[0] == "set_size" {
var size []int
_ = json.Unmarshal(p.Data, &size)
ws, err := pty.GetsizeFull(hs.ptmx)
if err != nil {
log.Println(err)
hs.errChan <- err
return
}
ws.Rows = uint16(size[1])
ws.Cols = uint16(size[2])
if len(size) >= 5 {
ws.X = uint16(size[3])
ws.Y = uint16(size[4])
}
if err := pty.Setsize(hs.ptmx, ws); err != nil {
log.Println(err)
hs.errChan <- err
}
return
}
}
if string(p.Data) == "quit" {
hs.errChan <- nil
return
}
hs.errChan <- fmt.Errorf(
`Unmatched string message: "%s"`,
string(p.Data),
)
} else {
_, err := hs.ptmx.Write(p.Data)
if err != nil {
log.Println(err)
hs.errChan <- err
}
}
}
}
func (hs *hostSession) onDataChannel() func(dc *webrtc.DataChannel) {
return func(dc *webrtc.DataChannel) {
hs.dc = dc
dc.OnOpen(hs.dataChannelOnOpen())
dc.OnMessage(hs.dataChannelOnMessage())
}
}
func (hs *hostSession) mustReadStdin() (string, error) {
var input string
fmt.Scanln(&input)
sd, err := sd.Decode(input)
return sd.Sdp, err
}
func (hs *hostSession) createOffer() (err error) {
hs.pc.OnDataChannel(hs.onDataChannel())
// Create unused DataChannel, the offer doesn't implictly have
// any media sections otherwise
if _, err = hs.pc.CreateDataChannel("offerer-channel", nil); err != nil {
log.Println(err)
return
}
// Create an offer to send to the browser
offer, err := hs.pc.CreateOffer(nil)
if err != nil {
log.Println(err)
return
}
// Create channel that is blocked until ICE Gathering is complete
gatherComplete := webrtc.GatheringCompletePromise(hs.pc)
err = hs.pc.SetLocalDescription(offer)
if err != nil {
log.Println(err)
return
}
// Block until ICE Gathering is complete
<-gatherComplete
hs.offer = sd.SessionDescription{
Sdp: hs.pc.LocalDescription().SDP,
}
if hs.oneWay {
hs.offer.GenKeys()
hs.offer.Encrypt()
hs.offer.TenKbSiteLoc = randSeq(100)
}
return
}
func (hs *hostSession) run() (err error) {
if err = hs.init(); err != nil {
return
}
colorstring.Printf("[bold]Setting up a WebTTY connection.\n\n")
if hs.oneWay {
colorstring.Printf(
"Warning: One-way connections rely on a third party to connect. " +
"More info here: https://github.com/maxmcd/webtty#one-way-connections\n\n")
}
if err = hs.createOffer(); err != nil {
return
}
// Output the offer in base64 so we can paste it in browser
colorstring.Printf("[bold]Connection ready. Here is your connection data:\n\n")
fmt.Printf("%s\n\n", sd.Encode(hs.offer))
colorstring.Printf(`[bold]Paste it in the terminal after the webtty command` +
"\n[bold]Or in a browser: [reset]https://maxmcd.github.io/webtty/\n\n")
if hs.oneWay == false {
colorstring.Println("[bold]When you have the answer, paste it below and hit enter:")
// Wait for the answer to be pasted
hs.answer.Sdp, err = hs.mustReadStdin()
if err != nil {
log.Println(err)
return
}
fmt.Println("Answer received, connecting...")
} else {
body, err := pollForResponse(hs.offer.TenKbSiteLoc)
if err != nil {
log.Println(err)
return err
}
hs.answer, err = sd.Decode(body)
if err != nil {
log.Println(err)
return err
}
hs.answer.Key = hs.offer.Key
hs.answer.Nonce = hs.offer.Nonce
if err = hs.answer.Decrypt(); err != nil {
return err
}
}
return hs.setHostRemoteDescriptionAndWait()
}
func (hs *hostSession) setHostRemoteDescriptionAndWait() (err error) {
// Set the remote SessionDescription
answer := webrtc.SessionDescription{
Type: webrtc.SDPTypeAnswer,
SDP: hs.answer.Sdp,
}
// Apply the answer as the remote description
if err = hs.pc.SetRemoteDescription(answer); err != nil {
log.Println(err)
return
}
// Wait to quit
err = <-hs.errChan
hs.cleanup()
return
}