-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
109 lines (78 loc) · 2.34 KB
/
main.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
101
102
103
104
105
106
107
108
109
package main
import (
"errors"
"flag"
"io"
"net"
"os"
"time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
const (
bufSize = 1024
numRetries = 6
dialTimeOut = 6 * time.Second
)
func handler(conn net.Conn, outConn string) error {
numRetriesExceeded := errors.New("num retries exceeded")
for i := 0; i < numRetries; i++ {
log.Info().Int("attempt", i).Int("timeout", int(dialTimeOut.Seconds())).Msg("tcpforwarder - dial connection")
target, err := net.DialTimeout("tcp", outConn, dialTimeOut)
if err != nil {
log.Warn().Err(err).Msg("tcpforwarder - remote connection")
continue
}
log.Info().Str("outConn", outConn).Msg("tcpforwarder - connection established")
go func() {
defer target.Close()
outBuff := make([]byte, bufSize)
_, err := io.CopyBuffer(target, conn, outBuff)
if err != nil {
// TODO: fix to reuse connections
log.Error().Err(err).Msg("tcpforwarder - outbuff")
}
log.Info().Msg("tcpforwarder - end target connection")
}()
go func() {
defer conn.Close()
inBuff := make([]byte, bufSize)
_, err := io.CopyBuffer(conn, target, inBuff)
if err != nil {
// TODO: fix to reuse connections
log.Error().Err(err).Msg("tcpforwarder - inbuff")
}
log.Info().Msg("tcpforwarder - end main connection")
}()
return nil
}
log.Error().Err(numRetriesExceeded).Msg("tcpforwarder - handler")
return numRetriesExceeded
}
func main() {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
var inConn, outConn string
flag.StringVar(&inConn, "i", "", "incoming connecction -> host:port")
flag.StringVar(&outConn, "o", "", "output connection forwarded to -> host:port")
flag.Parse()
if len(inConn) == 0 || len(outConn) == 0 {
log.Warn().Str("inConn", inConn).Str("outConn", outConn).Msg("tcpforwarder - missing arg")
flag.PrintDefaults()
os.Exit(-1)
}
log.Info().Str("inConn", inConn).Str("outConn", outConn).Msg("tcpforwarder - args")
listener, err := net.Listen("tcp", inConn)
if err != nil {
log.Error().Err(err).Msg("tcpforwarder - create listener")
panic(err)
}
for {
conn, err := listener.Accept()
if err != nil {
log.Error().Err(err).Msg("tcpforwarder - accept incomin connection")
panic(err)
}
log.Info().Str("remote addr", conn.RemoteAddr().String()).Msg("tcpforwarder - accepted connection")
go handler(conn, outConn)
}
}