-
Notifications
You must be signed in to change notification settings - Fork 0
/
mux.go
344 lines (313 loc) · 7.48 KB
/
mux.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
// Copyright 2018 Marco Pfatschbacher. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sshctl
import (
"encoding/binary"
"fmt"
"github.com/ftrvxmtrx/fd"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/terminal"
"io"
"net"
"os"
)
// ssh mux protocol messages
// cf: https://github.com/openbsd/src/blob/master/usr.bin/ssh/mux.c
const (
muxVersion = 4
muxMsgHello = 1
muxNewSession = 0x10000002
muxAliveCheck = 0x10000004
muxIsAlive = 0x80000005
muxSessionOpened = 0x80000006
muxTtyAllocFail = 0x80000008
muxExitMessage = 0x80000004
)
type muxNewSessionMsg struct {
Request uint32
RequestId uint32
ReservedStr string
TtyFlags uint32
ForwardX11 uint32
ForwardAgent uint32
SubSystemFlag uint32
EscapeChar uint32
Term string
Command string
}
type muxMsg struct {
Request uint32
Param uint32
}
func (s *Session) readPacket() ([]byte, error) {
lenbuf := make([]byte, 4)
_, err := io.ReadAtLeast(s.ctrlconn, lenbuf, 4)
if err != nil {
return nil, fmt.Errorf("Unable to read from control socket: %v", err)
}
len := binary.BigEndian.Uint32(lenbuf)
packet := make([]byte, len)
_, err = io.ReadAtLeast(s.ctrlconn, packet, int(len))
if err != nil {
return nil, fmt.Errorf("Unable to read from control socket: %v", err)
}
return packet, nil
}
func (s *Session) writePacket(req []byte) (err error) {
msg := make([]byte, 4+len(req))
binary.BigEndian.PutUint32(msg, uint32(len(req)))
copy(msg[4:], req)
if _, err = s.ctrlconn.Write(msg); err != nil {
return err
}
return nil
}
func packetPopInt(buf *[]byte) (int, error) {
if len(*buf) < 4 {
return -1, fmt.Errorf("buffer too short")
}
res := binary.BigEndian.Uint32(*buf)
*buf = (*buf)[4:]
return int(res), nil
}
func (s *Session) recvInts(count int) ([]int, error) {
var packet []byte
var err error
msgs := make([]int, 0)
if packet, err = s.readPacket(); err != nil {
return nil, err
}
var msg int
for ; count > 0; count-- {
if msg, err = packetPopInt(&packet); err != nil {
return nil, err
}
msgs = append(msgs, msg)
}
return msgs, nil
}
func (s *Session) openCtrlConn() error {
var raddr *net.UnixAddr
var err error
if raddr, err = net.ResolveUnixAddr("unix", s.sshctlpath); err != nil {
return err
}
if s.ctrlconn, err = net.DialUnix("unix", nil, raddr); err != nil {
return err
}
return nil
}
func (s *Session) sshMuxHello() error {
var msgs []int
var err error
if msgs, err = s.recvInts(2); err != nil {
return err
}
if msgs[0] != muxMsgHello || msgs[1] != muxVersion {
return fmt.Errorf("Incompatible Hello packet received")
}
m := &muxMsg{}
m.Request = muxMsgHello
m.Param = muxVersion
buf := ssh.Marshal(m)
if err = s.writePacket(buf); err != nil {
return err
}
return nil
}
func (s *Session) sshMuxAliveCheck() error {
var msgs []int
var err error
m := &muxMsg{}
m.Request = muxAliveCheck
m.Param = uint32(s.ctrlReqid)
buf := ssh.Marshal(m)
if err = s.writePacket(buf); err != nil {
return err
}
if msgs, err = s.recvInts(3); err != nil {
return err
}
if msgs[0] != muxIsAlive {
return fmt.Errorf("Expected ALIVE, got: 0x%x", msgs[0])
}
if msgs[1] != s.ctrlReqid {
return fmt.Errorf("out of sequence reply: 0x%x", msgs[0])
}
//sshpid = msgs[2]
s.ctrlReqid++
return nil
}
func (s *Session) sshMuxNewSession(cmd string) error {
nms := &muxNewSessionMsg{}
nms.Request = uint32(muxNewSession)
nms.RequestId = uint32(s.ctrlReqid)
nms.ReservedStr = ""
nms.EscapeChar = uint32(0xffffffff) // disable escape char
nms.Term = ""
nms.TtyFlags = uint32(0)
if s.term != "" {
nms.Term = s.term
nms.TtyFlags = uint32(1)
}
nms.Command = cmd
buf := ssh.Marshal(nms)
if err := s.writePacket(buf); err != nil {
return err
}
return nil
}
func (s *Session) sshMuxPassFileDescriptors() error {
var msgs []int
var err error
// SSH expects us to pass file descriptors.
// If the the user did provide an os.File, use it directly.
// Otherwise create a Pipe() and pass one end.
if sf, ok := s.Stdin.(*os.File); ok {
s.rmuxStdin = sf
s.stdinpipe = true
} else if s.lmuxStdin == nil {
// r, w, err = os.Pipe
if s.rmuxStdin, s.lmuxStdin, err = os.Pipe(); err != nil {
return err
}
}
if sf, ok := s.Stdout.(*os.File); ok {
s.rmuxStdout = sf
s.stdoutpipe = true
} else if s.lmuxStdout == nil {
if s.lmuxStdout, s.rmuxStdout, err = os.Pipe(); err != nil {
return err
}
}
if sf, ok := s.Stderr.(*os.File); ok {
s.rmuxStderr = sf
s.stderrpipe = true
} else if s.lmuxStderr == nil {
if s.lmuxStderr, s.rmuxStderr, err = os.Pipe(); err != nil {
return err
}
}
fd.Put(s.ctrlconn, s.rmuxStdin) //stdin
fd.Put(s.ctrlconn, s.rmuxStdout) //stdout
fd.Put(s.ctrlconn, s.rmuxStderr) //stderr
if msgs, err = s.recvInts(3); err != nil {
return err
}
if msgs[0] != muxSessionOpened {
return fmt.Errorf("Expected muxSessionOpened, got: 0x%x", msgs[0])
}
if msgs[1] != s.ctrlReqid {
return fmt.Errorf("out of sequence reply: 0x%x", msgs[0])
}
s.ctrlSessid = msgs[2]
s.ctrlReqid++
return nil
}
func (s *Session) makeRawTerm() error {
fd := int(s.rmuxStdin.Fd())
st, err := terminal.GetState(fd)
// Restore has to be done by the user
raw, err := terminal.MakeRaw(fd)
if err != nil {
return fmt.Errorf("MakeRaw err: %v", err)
}
if *st != *raw {
return fmt.Errorf("MakeRaw state was %v expected %v", *raw, *st)
}
return nil
}
func (s *Session) requestMuxSession(cmd string) error {
var err error
s.ctrlReqid = 0
if err = s.sshMuxHello(); err != nil {
return err
}
if err = s.sshMuxAliveCheck(); err != nil {
return err
}
if err = s.sshMuxNewSession(cmd); err != nil {
return err
}
if err = s.sshMuxPassFileDescriptors(); err != nil {
return err
}
if s.term != "" {
if err = s.makeRawTerm(); err != nil {
return err
}
}
// On created pipes, close the remote end from our side.
// This needs to happen after makeRawTerm()
if s.lmuxStdin != nil {
s.rmuxStdin.Close()
}
if s.lmuxStdout != nil {
s.rmuxStdout.Close()
}
if s.lmuxStderr != nil {
s.rmuxStderr.Close()
}
return nil
}
func (s *Session) wait() error {
wm := Waitmsg{status: -1}
var buf []byte
var err error
var mtype, sid int
exit_seen := false
for {
if buf, err = s.readPacket(); err != nil {
break
}
if mtype, err = packetPopInt(&buf); err != nil {
break
}
switch mtype {
case muxTtyAllocFail:
if sid, err = packetPopInt(&buf); err != nil {
break
}
if sid != s.ctrlSessid {
wm.msg = fmt.Sprintf("unknown session id: myid %d theirs %d", s.ctrlSessid, sid)
break
}
case muxExitMessage:
if sid, err = packetPopInt(&buf); err != nil {
break
}
if sid != s.ctrlSessid {
wm.msg = fmt.Sprintf("unknown session id: myid %d theirs %d", s.ctrlSessid, sid)
break
}
if exit_seen {
wm.msg = "exit seen twice"
break
}
if wm.status, err = packetPopInt(&buf); err != nil {
break
}
exit_seen = true
default:
// XXX read error string from packet
//checkErr(fmt.Errorf("master returned error: XXX"))
break
}
}
if wm.status == 0 {
return nil
}
if wm.status == -1 {
// exit-status was never sent from server
return &ExitMissingError{}
}
s.ctrlconn.Close()
return &ExitError{wm}
}
// ExitMissingError is returned if a session is torn down cleanly, but
// the server sends no confirmation of the exit status.
type ExitMissingError struct{}
func (e *ExitMissingError) Error() string {
return "wait: remote command exited without exit status or exit signal"
}