-
Notifications
You must be signed in to change notification settings - Fork 0
/
tunnel.go
72 lines (65 loc) · 1.71 KB
/
tunnel.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
package player
import (
"fmt"
"os"
"os/exec"
"os/signal"
"syscall"
"github.com/urfave/cli"
errors "golang.org/x/xerrors"
)
var tunnelCommand = cli.Command{
Name: "tunnel",
Usage: "tells xap to create a SSH based tunnel before to connect through, [user@]host:/path/to/socket",
Flags: []cli.Flag{
cli.StringFlag{
Name: "remote-socket, s",
Usage: "location of the remote socket",
},
cli.StringFlag{
Name: "destination, H",
Usage: "[user@]hostname[:port]",
},
},
Action: func(ctx *cli.Context) error {
localSocket := ctx.GlobalString("socket")
remoteSocket := ctx.String("remote-socket")
if remoteSocket == "" {
return errors.New("remote-socket can't be empty")
}
addr := ctx.String("destination")
if addr == "" {
return errors.New("destination can't be empty")
}
sigchan := make(chan os.Signal, 1)
signal.Notify(sigchan, syscall.SIGTERM, syscall.SIGHUP)
cmd := exec.Command("ssh", "-nNT", "-L", localSocket+":"+remoteSocket, addr)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Start()
if err != nil {
return errors.Errorf("failed to connect to %s: %w", addr, err)
}
done := make(chan error, 1)
go func() {
err := cmd.Wait()
done <- err
close(done)
}()
fmt.Fprintf(os.Stdout, "Starting SSH tunnel... connect to %s\n", localSocket)
select {
case <-sigchan:
fmt.Fprintf(os.Stdout, "Stopping tunnel...\n")
if err := cmd.Process.Kill(); err != nil {
return errors.Errorf("failed to kill ssh command: %w", err)
}
case err := <-done:
fmt.Fprintf(os.Stdout, "Tunnel stopped working...\n")
if err != nil {
return errors.Errorf("ssh command failed: %w", err)
}
}
return os.Remove(localSocket)
},
}