forked from mushorg/glutton
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy_tcp.go
68 lines (54 loc) · 1.49 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
package glutton
import (
"context"
"fmt"
"io"
"net"
"net/url"
"time"
"github.com/kung-foo/freki"
)
func (g *Glutton) tcpProxy(ctx context.Context, conn net.Conn) (err error) {
defer func() {
err = conn.Close()
if err != nil {
g.logger.Error(fmt.Sprintf("[tcp.prxy] error: %v", err))
}
}()
host, port, _ := net.SplitHostPort(conn.RemoteAddr().String())
ck := freki.NewConnKeyByString(host, port)
md := g.processor.Connections.GetByFlow(ck)
if md == nil {
g.logger.Warn(fmt.Sprintf("[tcp.prxy] untracked connection: %s", conn.RemoteAddr().String()))
return
}
target := md.Rule.Target
fmt.Printf("Rule Traget: %+v\n", target)
dest, err := url.Parse(target)
if err != nil {
g.logger.Error("[tcp.prxy]failed to parse destination address, check rules file")
return err
}
if dest.Scheme != "tcp" && dest.Scheme != "docker" {
g.logger.Error(fmt.Sprintf("[tcp.prxy] unsuppported scheme: %s", dest.Scheme))
return
}
g.logger.Info(fmt.Sprintf("[prxy.tcp] %s -> %v to %s", host, md.TargetPort, dest.String()))
proxyConn, err := net.DialTimeout("tcp", dest.Host, time.Second*120)
if err != nil {
g.logger.Error(fmt.Sprintf("[prxy.tcp] %v", err))
return err
}
// TODO: Log traffic by wrapping connection with io.ReadClose
go func() {
_, err = io.Copy(proxyConn, conn)
if err != nil {
g.logger.Error(fmt.Sprintf("[prxy.tcp] %v", err))
}
}()
_, err = io.Copy(conn, proxyConn)
if err != nil {
g.logger.Error(fmt.Sprintf("[prxy.tcp] %v", err))
}
return err
}