-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
288 lines (250 loc) · 6.05 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
package main
import (
"flag"
"fmt"
"io"
"log"
"net"
"strings"
"sync"
"time"
)
var (
confForward string
showHelp bool
)
func init() {
flag.StringVar(&confForward, "f", "", "forward ports eg. udp::53-8.8.8.8:53,tcp:0.0.0.0:80-x.x.x.x:80")
flag.BoolVar(&showHelp, "help", false, "show help")
flag.Parse()
log.SetFlags(log.Lshortfile | log.LstdFlags)
}
func parse(g string) (*Forward, error) {
tmp := strings.Split(strings.TrimSpace(g), "-")
if len(tmp) != 2 {
return nil, fmt.Errorf("invalid format")
}
// remote
remote := tmp[1]
if len(strings.Split(remote, ":")) != 2 {
return nil, fmt.Errorf("invalid format")
}
// protocol, local
left := strings.Split(tmp[0], ":")
if len(left) != 3 {
return nil, fmt.Errorf("invalid format")
}
protocol := left[0]
local := left[1]
port := left[2]
return &Forward{
LocalAddr: fmt.Sprintf("%s:%s", local, port),
RemoteAddr: remote,
Protocol: protocol,
udpRConnMap: make(map[string]*net.UDPConn),
}, nil
}
func main() {
if showHelp || confForward == "" {
flag.Usage()
return
}
var forwards []*Forward
gs := strings.Split(confForward, ",")
for _, g := range gs {
f, err := parse(g)
if err != nil {
log.Fatalf("'%s' %s", g, err)
}
forwards = append(forwards, f)
}
if len(forwards) == 0 {
log.Fatalf("forward is empty")
}
g := sync.WaitGroup{}
for _, f := range forwards {
g.Add(1)
go func(f *Forward) {
defer g.Done()
err := f.Serve()
if err != nil {
log.Printf("[%s] serve failed. err: %v\n", f, err)
}
}(f)
}
g.Wait()
}
type Forward struct {
LocalAddr string
RemoteAddr string
Protocol string
lock sync.Mutex
udpRConnMap map[string]*net.UDPConn // map[clientAddr]remoteConn
}
func (f *Forward) String() string {
return fmt.Sprintf("%s:%s-%s", f.Protocol, f.LocalAddr, f.RemoteAddr)
}
func (f *Forward) Serve() error {
if strings.HasPrefix(f.Protocol, "tcp") {
return f.serveTcp()
}
return f.serveUdp()
}
func (f *Forward) serveTcp() error {
ln, err := net.Listen(f.Protocol, f.LocalAddr)
if err != nil {
return err
}
defer ln.Close()
// test remote ?
rn, err := net.Dial(f.Protocol, f.RemoteAddr)
if err != nil {
return err
}
rn.Close()
log.Printf("[%s] listen on %s\n", f, ln.Addr().String())
var retryDelay time.Duration
maxDelay := 1 * time.Second
var id int
var lc net.Conn
for {
lc, err = ln.Accept()
if err != nil {
if retryDelay == 0 {
retryDelay = 50 * time.Millisecond
} else {
retryDelay *= 2
}
if retryDelay > maxDelay {
retryDelay = maxDelay
}
log.Printf("[%s] accept error: %v; retrying in %v\n", f, err, retryDelay)
time.Sleep(retryDelay)
continue
}
id++
log.Printf("[%s] [%d] [%s -> -] new conn\n", f, id, lc.RemoteAddr())
go f.forwardTcp(id, lc)
}
}
func (f *Forward) serveUdp() error {
localAddr, err := net.ResolveUDPAddr(f.Protocol, f.LocalAddr)
if err != nil {
return err
}
remoteAddr, err := net.ResolveUDPAddr(f.Protocol, f.RemoteAddr)
if err != nil {
return err
}
lc, err := net.ListenUDP(f.Protocol, localAddr)
if err != nil {
return err
}
defer lc.Close()
log.Printf("[%s] listen on %s\n", f, localAddr)
buf := make([]byte, 32*1024)
for {
n, clientAddr, err := lc.ReadFromUDP(buf)
if err != nil {
log.Printf("[%s] read err: %s\n", f, err)
continue
}
go f.forwardUdp(clientAddr, remoteAddr, lc, buf[:n])
}
}
func (f *Forward) forwardUdp(clientAddr *net.UDPAddr, remoteAddr *net.UDPAddr, lc *net.UDPConn, buf []byte) {
var rc *net.UDPConn
var err error
var isNewConn bool
const timeout = time.Second * 30
clientAddrStr := clientAddr.String()
f.lock.Lock()
if cacheRC, ok := f.udpRConnMap[clientAddrStr]; ok {
rc = cacheRC
} else {
rc, err = net.DialUDP(f.Protocol, nil, remoteAddr)
if err != nil {
log.Printf("[%s] dial remote failed. err:%v", f, err)
f.lock.Unlock()
return
}
f.udpRConnMap[clientAddr.String()] = rc
isNewConn = true
log.Printf("[%s] [%s <> %s] new remote conn", f, clientAddr, remoteAddr)
}
// delay deadLine
rc.SetDeadline(time.Now().Add(timeout))
f.lock.Unlock()
n, err := rc.Write(buf)
if err != nil {
log.Printf("[%s] Write remote failed. err:%v", f, err)
return
}
log.Printf("[%s] [%s -> %s] forward %d bytes", f, clientAddr, remoteAddr, n)
if !isNewConn {
return
}
go func() {
defer func() {
f.lock.Lock()
delete(f.udpRConnMap, clientAddrStr)
f.lock.Unlock()
rc.Close()
log.Printf("[%s] [%s <> %s] remote closed ", f, clientAddr, remoteAddr)
return
}()
buf = make([]byte, 32*1024)
for {
n, err := rc.Read(buf)
if err != nil {
if e, ok := err.(net.Error); ok && e.Timeout() {
return
}
log.Printf("[%s] [ <- %s] read remote err: %v", f, remoteAddr, err)
return
}
_, err = lc.WriteToUDP(buf[:n], clientAddr)
if err != nil {
log.Printf("[%s] [%s <- %s] write client err: %v", f, clientAddr, remoteAddr, err)
return
}
log.Printf("[%s] [%s <- %s] forward %d bytes", f, clientAddr, remoteAddr, n)
}
}()
}
func (f *Forward) forwardTcp(id int, lc net.Conn) {
var rc net.Conn
defer func() {
lc.Close()
if rc != nil {
rc.Close()
}
log.Printf("[%s] [%v] [%s <> %s] closed", f, id, lc.RemoteAddr().String(), rc.RemoteAddr().String())
}()
var err error
var retryDelay time.Duration // how long to sleep on accept failure
maxRetryTimes, retryTimes := 3, 0
for {
rc, err = net.Dial(f.Protocol, f.RemoteAddr)
if err != nil {
if ne, ok := err.(net.Error); ok && ne.Timeout() && retryTimes < maxRetryTimes {
if retryDelay == 0 {
retryDelay = 100 * time.Millisecond
} else {
retryDelay *= 2
}
log.Printf("[%s] [%d] [%s -> %s] conn remote failed. err:%v; retryTimes:%v, retrying in %v\n",
f, id, lc.RemoteAddr(), rc.RemoteAddr(), err, retryTimes, retryDelay)
time.Sleep(retryDelay)
retryTimes++
continue
}
log.Printf("[%s] [%d] [%s -> %s] conn remote failed. err:%v\n", f, id, lc.RemoteAddr(), rc.RemoteAddr(), err)
return
}
break
}
log.Printf("[%s] [%d] [%s -> %s] conn success", f, id, lc.RemoteAddr(), rc.RemoteAddr())
go io.Copy(lc, rc)
io.Copy(rc, lc)
}