-
Notifications
You must be signed in to change notification settings - Fork 0
/
tunnel.go
74 lines (63 loc) · 1.3 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
73
74
package main
import (
"log"
"net"
"strconv"
"sync"
"golang.org/x/crypto/ssh"
)
func setupTunnel(quit <-chan struct{}, client *ssh.Client, lport, rport int) error {
listener, err := net.Listen("tcp", ":"+strconv.Itoa(lport))
if err != nil {
return err
}
go func() {
defer listener.Close()
connChan := make(chan net.Conn)
errChan := make(chan error)
go func() {
for {
conn, err := listener.Accept()
if err != nil {
errChan <- err
return
}
connChan <- conn
}
}()
for {
select {
case conn := <-connChan:
go tunnelConnectionToPortUsingClient(conn, rport, client)
case err := <-errChan:
log.Println("Listener failed", err)
case <-quit:
return
}
}
}()
return nil
}
func tunnelConnectionToPortUsingClient(localConn net.Conn, rport int, client *ssh.Client) {
addr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:"+strconv.Itoa(rport))
if err != nil {
panic(err)
}
remoteConn, err := client.DialTCP("tcp", nil, addr)
if err != nil {
panic(err)
}
wg := sync.WaitGroup{}
wg.Add(2)
copyConn := func(writer, reader net.Conn) {
defer wg.Done()
CopyAndMeasureThroughput(writer, reader)
}
go copyConn(localConn, remoteConn)
go copyConn(remoteConn, localConn)
go func() {
wg.Wait()
localConn.Close()
remoteConn.Close()
}()
}