/
impl.go
306 lines (275 loc) · 8.11 KB
/
impl.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
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"github.com/kr/pty"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/exec"
"sync"
"syscall"
"time"
"v.io/v23/context"
"v.io/v23/rpc"
"v.io/v23/security"
"v.io/x/ref/examples/tunnel"
"v.io/x/ref/examples/tunnel/internal"
)
// T implements tunnel.TunnelServerMethods
type T struct {
}
// Use the same exit code as SSH when a non-shell error occurs.
const nonShellErrorCode int32 = 255
func (t *T) Forward(ctx *context.T, call tunnel.TunnelForwardServerCall, network, address string) error {
conn, err := net.Dial(network, address)
if err != nil {
return err
}
b, _ := security.RemoteBlessingNames(ctx, call.Security())
name := fmt.Sprintf("RemoteBlessings:%v LocalAddr:%v RemoteAddr:%v", b, conn.LocalAddr(), conn.RemoteAddr())
ctx.Infof("TUNNEL START: %v", name)
err = internal.Forward(conn, call.SendStream(), call.RecvStream())
ctx.Infof("TUNNEL END : %v (%v)", name, err)
return err
}
func (t *T) ReverseForward(ctx *context.T, call rpc.ServerCall, network, address string) error {
ln, err := net.Listen(network, address)
if err != nil {
return err
}
defer ln.Close()
ctx.Infof("Listening on %q", ln.Addr())
remoteEP := call.RemoteEndpoint().Name()
go func() {
for {
conn, err := ln.Accept()
if err != nil {
ctx.Infof("Accept failed: %v", err)
if oErr, ok := err.(*net.OpError); ok && oErr.Temporary() {
continue
}
return
}
go func(c net.Conn) {
defer c.Close()
stream, err := tunnel.ForwarderClient(remoteEP).Forward(ctx)
if err != nil {
ctx.Infof("Forward failed: %v", err)
return
}
name := fmt.Sprintf("%v-->%v-->(%v)", c.RemoteAddr(), c.LocalAddr(), remoteEP)
ctx.Infof("TUNNEL START: %v", name)
errf := internal.Forward(c, stream.SendStream(), stream.RecvStream())
err = stream.Finish()
ctx.Infof("TUNNEL END : %v (%v, %v)", name, errf, err)
}(conn)
}
}()
<-ctx.Done()
return nil
}
func (t *T) Shell(ctx *context.T, call tunnel.TunnelShellServerCall, command string, shellOpts tunnel.ShellOpts) (int32, string, error) {
b, _ := security.RemoteBlessingNames(ctx, call.Security())
ctx.Infof("SHELL START for %v: %q", b, command)
shell, err := findShell()
if err != nil {
return nonShellErrorCode, "", err
}
var c *exec.Cmd
// An empty command means that we need an interactive shell.
if len(command) == 0 {
c = exec.Command(shell, "-i")
sendMotd(ctx, call)
} else {
c = exec.Command(shell, "-c", command)
}
c.SysProcAttr = &syscall.SysProcAttr{
// Create a new process group for the child process. After the
// child exits, we'll use it to clean up processes left behind.
Setpgid: true,
}
c.Env = []string{
fmt.Sprintf("HOME=%s", os.Getenv("HOME")),
fmt.Sprintf("PATH=%s", os.Getenv("PATH")),
}
c.Env = append(c.Env, shellOpts.Environment...)
ctx.Infof("Shell environment: %v", c.Env)
c.Dir = os.Getenv("HOME")
ctx.Infof("Shell CWD: %v", c.Dir)
var (
stdin io.WriteCloser // We write to stdin.
stdout, stderr io.ReadCloser // We read from stdout and stderr.
ptyFd uintptr // File descriptor for pty.
)
if shellOpts.UsePty {
f, err := pty.Start(c)
if err != nil {
return nonShellErrorCode, "", err
}
defer f.Close()
stdin, stdout, stderr = f, f, nil
ptyFd = f.Fd()
setWindowSize(ctx, ptyFd, shellOpts.WinSize.Rows, shellOpts.WinSize.Cols)
} else {
var err error
if stdin, err = c.StdinPipe(); err != nil {
return nonShellErrorCode, "", err
}
defer stdin.Close()
if stdout, err = c.StdoutPipe(); err != nil {
return nonShellErrorCode, "", err
}
defer stdout.Close()
if stderr, err = c.StderrPipe(); err != nil {
return nonShellErrorCode, "", err
}
defer stderr.Close()
if err = c.Start(); err != nil {
ctx.Infof("Cmd.Start failed: %v", err)
return nonShellErrorCode, "", err
}
}
// Read loop for STDIN
// This loop reads from the RPC stream and writes to STDIN of the child
// process.
go func() {
stream := call.RecvStream()
for stream.Advance() {
packet := stream.Value()
switch v := packet.(type) {
case tunnel.ClientShellPacketStdin:
if n, err := stdin.Write(v.Value); n != len(v.Value) || err != nil {
ctx.VI(3).Infof("Write failed: %v", err)
}
case tunnel.ClientShellPacketEndOfFile:
if err := stdin.Close(); err != nil {
ctx.VI(3).Infof("Close failed: %v", err)
}
case tunnel.ClientShellPacketWinSize:
size := v.Value
if size.Rows > 0 && size.Cols > 0 && ptyFd != 0 {
setWindowSize(ctx, ptyFd, size.Rows, size.Cols)
}
default:
ctx.Infof("unexpected message type: %T", packet)
}
}
ctx.VI(3).Infof("Read loop STDIN: %v", stream.Err())
if err := stdin.Close(); err != nil {
ctx.VI(3).Infof("stdin.Close failed: %v", err)
}
}()
var (
// wg is used to make sure the STDOUT and STDERR read loops exit
// before the RPC ends.
wg sync.WaitGroup
// STDOUT and STDERR are sent on the same stream, which is not
// thread-safe.
sendMutex sync.Mutex
// The read loop reads from STDOUT or STDOUT of the child
// process and writes to the RPC stream.
readLoop = func(r io.Reader, stderr bool) {
defer wg.Done()
buf := make([]byte, 2048)
var pkt tunnel.ServerShellPacket
for {
n, err := r.Read(buf[:])
if err != nil {
ctx.VI(3).Infof("Read failed: %v", err)
return
}
if stderr {
pkt = tunnel.ServerShellPacketStderr{buf[:n]}
} else {
pkt = tunnel.ServerShellPacketStdout{buf[:n]}
}
sendMutex.Lock()
err = call.SendStream().Send(pkt)
sendMutex.Unlock()
if err != nil {
ctx.VI(3).Infof("send failed: %v", err)
return
}
}
}
)
wg.Add(1)
go readLoop(stdout, false)
if stderr != nil {
wg.Add(1)
go readLoop(stderr, true)
}
defer wg.Wait()
// When the RPC is terminated, we need to kill the child process, if
// it is still running, and any other processes left behind in the same
// process group.
go func(p *os.Process) {
if pid := p.Pid; pid > 0 {
defer syscall.Kill(-pid, syscall.SIGKILL)
}
<-ctx.Done()
if err := p.Signal(syscall.SIGHUP); err != nil {
// The process has already exited, or we somehow don't
// have permission to send a signal to that process.
ctx.Infof("[%d].Signal(SIGHUP): %v", p.Pid, err)
return
}
time.Sleep(time.Second)
if err := p.Kill(); err != nil {
ctx.Infof("[%d].Kill(): %v", p.Pid, err)
}
}(c.Process)
// Wait for the child process to exit.
// If the exit status is 0, return nil error. Otherwise, return an error
// that describes how the process exited.
state, err := c.Process.Wait()
if err != nil {
ctx.Infof("Process.Wait failed: %v", err)
return nonShellErrorCode, "", err
}
ctx.Infof("SHELL END for %v: %s", b, state)
if state.Success() {
return 0, "", nil
}
status, ok := state.Sys().(syscall.WaitStatus)
if !ok {
return nonShellErrorCode, state.String(), nil
}
if status.Signaled() {
return nonShellErrorCode, fmt.Sprintf("process killed by signal %d (%v)", status.Signal(), status.Signal()), nil
}
return int32(status.ExitStatus()), fmt.Sprintf("process exited with exit status %d", status.ExitStatus()), nil
}
// findShell returns the path to the first usable shell binary.
func findShell() (string, error) {
shells := []string{"/bin/bash", "/bin/sh", "/system/bin/sh"}
for _, s := range shells {
if _, err := os.Stat(s); err == nil {
return s, nil
}
}
return "", errors.New("could not find any shell binary")
}
// sendMotd sends the content of the MOTD file to the stream, if it exists.
func sendMotd(ctx *context.T, s tunnel.TunnelShellServerStream) {
data, err := ioutil.ReadFile("/etc/motd")
if err != nil {
// No MOTD. That's OK.
return
}
packet := tunnel.ServerShellPacketStdout{[]byte(data)}
if err = s.SendStream().Send(packet); err != nil {
ctx.Infof("Send failed: %v", err)
}
}
func setWindowSize(ctx *context.T, fd uintptr, row, col uint16) {
ws := internal.Winsize{Row: row, Col: col}
if err := internal.SetWindowSize(fd, ws); err != nil {
ctx.Infof("Failed to set window size: %v", err)
}
}