-
-
Notifications
You must be signed in to change notification settings - Fork 13.1k
/
client.go
89 lines (76 loc) · 1.52 KB
/
client.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
package ssh
import (
"net"
libio "github.com/fatedier/golib/io"
"golang.org/x/crypto/ssh"
)
type TunnelClient struct {
localAddr string
sshServer string
commands string
sshConn *ssh.Client
ln net.Listener
}
func NewTunnelClient(localAddr string, sshServer string, commands string) *TunnelClient {
return &TunnelClient{
localAddr: localAddr,
sshServer: sshServer,
commands: commands,
}
}
func (c *TunnelClient) Start() error {
config := &ssh.ClientConfig{
User: "v0",
HostKeyCallback: func(string, net.Addr, ssh.PublicKey) error { return nil },
}
conn, err := ssh.Dial("tcp", c.sshServer, config)
if err != nil {
return err
}
c.sshConn = conn
l, err := conn.Listen("tcp", "0.0.0.0:80")
if err != nil {
return err
}
c.ln = l
ch, req, err := conn.OpenChannel("session", []byte(""))
if err != nil {
return err
}
defer ch.Close()
go ssh.DiscardRequests(req)
type command struct {
Cmd string
}
_, err = ch.SendRequest("exec", false, ssh.Marshal(command{Cmd: c.commands}))
if err != nil {
return err
}
go c.serveListener()
return nil
}
func (c *TunnelClient) Close() {
if c.sshConn != nil {
_ = c.sshConn.Close()
}
if c.ln != nil {
_ = c.ln.Close()
}
}
func (c *TunnelClient) serveListener() {
for {
conn, err := c.ln.Accept()
if err != nil {
return
}
go c.hanldeConn(conn)
}
}
func (c *TunnelClient) hanldeConn(conn net.Conn) {
defer conn.Close()
local, err := net.Dial("tcp", c.localAddr)
if err != nil {
return
}
_, _, _ = libio.Join(local, conn)
}