-
Notifications
You must be signed in to change notification settings - Fork 11
/
proxy_tcp.go
100 lines (79 loc) · 1.78 KB
/
proxy_tcp.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
package freki
import (
"fmt"
"io"
"net"
"time"
"github.com/pkg/errors"
)
type TCPProxy struct {
port uint
processor *Processor
listener net.Listener
}
func NewTCPProxy(port uint) *TCPProxy {
return &TCPProxy{
port: port,
}
}
func (p *TCPProxy) Port() uint {
return p.port
}
func (p *TCPProxy) Type() string {
return "proxy.tcp"
}
func (p *TCPProxy) Start(processor *Processor) error {
p.processor = processor
var err error
// TODO: can I be more specific with the bind addr?
p.listener, err = net.Listen("tcp", fmt.Sprintf(":%d", p.port))
if err != nil {
return err
}
for {
conn, err := p.listener.Accept()
if err != nil {
logger.Error(errors.Wrap(err, p.Type()))
continue
}
go p.handleConnection(conn)
}
}
func (p *TCPProxy) handleConnection(conn net.Conn) {
host, port, _ := net.SplitHostPort(conn.RemoteAddr().String())
ck := NewConnKeyByString(host, port)
md := p.processor.Connections.GetByFlow(ck)
if md == nil {
logger.Warnf("[prxy.tcp] untracked connection: %s", conn.RemoteAddr().String())
return
}
target := md.Rule.targetURL
if target.Scheme != "tcp" && target.Scheme != "docker" {
logger.Error(fmt.Errorf("unsuppported scheme: %s", target.Scheme))
return
}
logger.Infof("[prxy.tcp] %s -> %s to %s", host, md.TargetPort, target.String())
proxyConn, err := net.DialTimeout("tcp", target.Host, time.Second*5)
if err != nil {
logger.Error(errors.Wrap(err, p.Type()))
return
}
go func() {
_, err := io.Copy(proxyConn, conn)
if err != nil {
logger.Error(errors.Wrap(err, p.Type()))
}
}()
go func() {
_, err := io.Copy(conn, proxyConn)
if err != nil {
logger.Error(errors.Wrap(err, p.Type()))
}
}()
}
func (p *TCPProxy) Shutdown() error {
if p.listener != nil {
return p.listener.Close()
}
return nil
}