-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcpproxy.go
More file actions
104 lines (84 loc) · 1.87 KB
/
tcpproxy.go
File metadata and controls
104 lines (84 loc) · 1.87 KB
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
package main
import (
"fmt"
"io"
"log"
"net"
)
func NewSinglePortProxy(host string, port int) (*SinglePortProxy, error) {
portstr := fmt.Sprintf(":%d", port)
ln, err := net.Listen("tcp", portstr)
if err != nil {
log.Println(err)
return nil, err
}
log.Printf("New TCP Proxy on Port %s, for host %s", portstr, host)
spp := SinglePortProxy{
host: host,
port: port,
listener: ln,
}
go spp.listenForConnections()
return &spp, nil
}
type SinglePortProxy struct {
host string
port int
listener net.Listener
stopped bool
}
func (proxy *SinglePortProxy) listenForConnections() {
for {
defer func() {
if r := recover(); r != nil {
//it's ok, Accept probably stopped because port is closed
}
}()
conn, err := proxy.listener.Accept()
if err != nil {
if proxy.stopped {
break
} else {
panic(err)
}
}
pc := proxyConnection{
upstream: conn,
downstreamHost: proxy.host,
downstreamPort: proxy.port,
}
go pc.establish()
}
}
func (proxy SinglePortProxy) Stop() {
log.Printf("Stop listening to port %v\n", proxy.port)
proxy.stopped = true
proxy.listener.Close()
}
type proxyConnection struct {
upstream net.Conn
downstream net.Conn
downstreamHost string
downstreamPort int
}
func (pc *proxyConnection) establish() {
defer pc.upstream.Close()
var err error
pc.downstream, err = net.Dial("tcp", fmt.Sprintf("%s:%d", pc.downstreamHost, pc.downstreamPort))
if err != nil {
//TODO if it is connection refused pass this on to the client
log.Println(err)
return
}
defer pc.downstream.Close()
//in parallel copy responses back
done := make(chan bool)
go copyContent(pc.downstream, pc.upstream, done)
go copyContent(pc.upstream, pc.downstream, done)
//wait for one channel to finish
<-done
}
func copyContent(in net.Conn, out net.Conn, done chan bool) {
io.Copy(out, in)
done <- true
}