-
Notifications
You must be signed in to change notification settings - Fork 9
/
forwarder.go
64 lines (59 loc) · 1.42 KB
/
forwarder.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
package main
import (
"fmt"
"io"
"net"
"strings"
"time"
)
type Forwarder struct {
src Address
dst Address
dialTimeout int
}
func NewForwarder(src Address, dst Address, dialTimeout int) *Forwarder {
return &Forwarder{
src: src,
dst: dst,
dialTimeout: dialTimeout,
}
}
func (f *Forwarder) Start() {
listener, err := net.Listen("tcp", f.src.String())
panicIfErr(err)
for {
srcConn, err := listener.Accept()
if err != nil {
println(err.Error())
continue
}
go func(srcConn net.Conn) {
dstConn, err := net.DialTimeout("tcp", f.dst.String(), time.Duration(f.dialTimeout)*time.Second)
if err != nil {
if strings.Contains(err.Error(), "i/o timeout") {
println(fmt.Sprintf(`%s -- %s >-< %s %s`, time.Now().Format(time.RFC3339), srcConn.RemoteAddr().String(), f.dst.String(), "dial timed out"))
} else {
println(err.Error())
}
_ = srcConn.Close()
return
}
println(fmt.Sprintf(`%s -- %s <-> %s`, time.Now().Format(time.RFC3339), srcConn.RemoteAddr().String(), f.dst.String()))
go func(srcConn, dstConn net.Conn) {
_, _ = io.Copy(srcConn, dstConn)
_ = srcConn.Close()
_ = dstConn.Close()
}(srcConn, dstConn)
go func(srcConn, dstConn net.Conn) {
_, _ = io.Copy(dstConn, srcConn)
_ = srcConn.Close()
_ = dstConn.Close()
}(srcConn, dstConn)
}(srcConn)
}
}
func panicIfErr(err error) {
if err != nil {
panic(err)
}
}