-
Notifications
You must be signed in to change notification settings - Fork 3
/
port.go
375 lines (328 loc) · 6.92 KB
/
port.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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package libtorrent
import (
"bytes"
"math/rand"
"net"
"net/http"
"strconv"
"strings"
"time"
"github.com/anacrolix/missinggo"
"github.com/syncthing/syncthing/lib/nat"
"github.com/syncthing/syncthing/lib/upnp"
)
var tcpPort string
var udpPort string
var mappingAddr []string // clientAddr when mapping called
var clientPorts []string
var mappingClose missinggo.Event
var (
RefreshPort = (1 * time.Minute).Nanoseconds()
)
func localIP(gip net.IP) (ips []string) {
ifaces, err := net.Interfaces()
if err != nil {
return
}
for _, iface := range ifaces {
if iface.Flags&net.FlagUp == 0 {
continue // interface down
}
if iface.Flags&net.FlagLoopback != 0 {
continue // loopback interface
}
addrs, err := iface.Addrs()
if err != nil {
return
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if ip == nil || ip.IsLoopback() {
continue
}
ip = ip.To4()
if ip == nil {
continue // not an ipv4 address
}
if gip != nil && ip.Mask(ip.DefaultMask()).Equal(gip.Mask(gip.DefaultMask())) {
ips = append(ips, ip.String())
} else {
ips = append(ips, ip.String())
}
}
}
return
}
func PortCount() int {
mu.Lock()
defer mu.Unlock()
clientPorts = portList()
if udpPort != "" {
clientPorts = append(clientPorts, udpPort)
}
return len(clientPorts)
}
func portList() []string {
var ports []string
host, port, err := net.SplitHostPort(clientAddr)
if err != nil {
ports = append(ports, clientAddr)
} else {
if host == "" || host == "::" {
ips := localIP(nil)
if len(ips) == 0 {
ports = append(ports, net.JoinHostPort(host, port))
} else {
for _, v := range ips {
ports = append(ports, net.JoinHostPort(v, port))
}
}
} else {
ports = append(ports, net.JoinHostPort(host, port))
}
}
return ports
}
func Port(i int) string {
mu.Lock()
defer mu.Unlock()
return clientPorts[i]
}
func PortCheck() bool {
port := tcpPort
if port == "" {
// check does not perfome on UDP but what we can do?
port = udpPort
}
if port == "" {
// ports are not forwarded? using local socket port
_, port, err = net.SplitHostPort(clientAddr)
if err != nil {
return false
}
} else {
_, port, err = net.SplitHostPort(port)
if err != nil {
return false
}
}
url := "http://portcheck.transmissionbt.com/" + port
var resp *http.Response
resp, err = http.Get(url)
if err != nil {
return false
}
defer resp.Body.Close()
buf := new(bytes.Buffer)
buf.ReadFrom(resp.Body)
s := buf.String()
return s == "1"
}
func getPort(d nat.Device, proto nat.Protocol, port int, extPort string) (int, error) {
n := "libtorrent " + strings.ToLower(string(proto))
_, ep, err := net.SplitHostPort(extPort)
if err == nil && ep != "" {
extPort = ep
}
ext, err := net.LookupPort("tcp", extPort)
if err != nil || ext == 0 {
ext = port
}
lease := 2 * time.Duration(RefreshPort) * time.Nanosecond
// try specific port
p, err := d.AddPortMapping(proto, port, ext, n, lease)
if err == nil {
return p, nil
}
// try random port
p, err = d.AddPortMapping(proto, port, 0, n, lease)
if err == nil {
return p, nil
}
// try rand port
for i := 0; i < 10; i++ {
// Then try up to ten random ports.
extPort := 1024 + rand.Intn(65535-1024)
p, err = d.AddPortMapping(proto, port, extPort, n, lease)
if err == nil {
return p, nil
}
}
return 0, err
}
func mappingPort(timeout time.Duration) error {
mu.Lock()
_, pp, err := net.SplitHostPort(clientAddr)
mu.Unlock()
if err != nil {
return err
}
localport, err := net.LookupPort("tcp", pp)
if err != nil {
return err
}
dd := upnp.Discover(timeout, timeout)
u := func(d nat.Device) error {
ext, err := d.GetExternalIPAddress()
if err != nil {
return err
}
mu.Lock()
pp := udpPort // reuse old port
if pp == "" {
pp = tcpPort // reuse tcp port
}
mu.Unlock()
p, err := getPort(d, nat.UDP, localport, pp)
if err != nil {
return err
}
mu.Lock()
defer mu.Unlock()
udpPort = net.JoinHostPort(ext.String(), strconv.Itoa(p))
return nil
}
udp := u
t := func(d nat.Device) error {
ext, err := d.GetExternalIPAddress()
if err != nil {
return err
}
mu.Lock()
pp := tcpPort // reuse old port
if pp == "" {
pp = udpPort // reuse udp port
}
mu.Unlock()
p, err := getPort(d, nat.TCP, localport, pp)
if err != nil {
return err
}
mu.Lock()
defer mu.Unlock()
tcpPort = net.JoinHostPort(ext.String(), strconv.Itoa(p))
return nil
}
tcp := t
// start udp priority
for _, d := range dd {
if udp != nil {
if err := udp(d); err == nil {
udp = nil
}
}
if tcp != nil {
if err := tcp(d); err == nil {
tcp = nil
}
}
}
// start tcp priority
mu.Lock()
if udpPort != tcpPort { // ooops...
if tcpPort != "" { // tcp assigned, so UPnP/NAP-PMP working.
// did we miss udp port or tcp is different? which menas we unable to get tcp port number same as udp port.
// we need to reset udp port and try assign udp port number same as tcp port.
if udpPort != "" { // udp assgined so UPnP/NAP-PMP udp working.
udpPort = ""
mu.Unlock()
udp = u
for _, d := range dd {
if udp != nil {
if err := udp(d); err == nil {
udp = nil
}
}
}
mu.Lock()
if udpPort == "" { // unable to assign udp port reset booth
udpPort = ""
tcpPort = ""
}
}
}
}
mu.Unlock()
mu.Lock()
defer mu.Unlock()
if tcp != nil {
tcpPort = ""
}
if udp != nil {
udpPort = ""
}
// udp have priority we are using uTP
if udpPort == "" { // udp == tcp == ""
tcpPort = ""
updateClientAddr(clientAddr)
return nil
}
if tcpPort != udpPort {
// if we got different TCP port, reset it
tcpPort = ""
updateClientAddr(udpPort)
return nil
}
if tcpPort == udpPort { // finnely!
updateClientAddr(udpPort)
return nil
}
return nil // never here
}
func updateClientAddr(addr string) {
if client == nil { // already closed
return
}
old := client.ListenAddr().String()
if old == addr {
return
}
client.SetListenAddr(addr)
}
func mappingStart() {
mu.Lock()
mappingClose.Set()
mappingClose.Clear()
mu.Unlock()
refresh := RefreshPort
if udpPort == "" { // start from 1 second if previous mapping failed
refresh = (1 * time.Second).Nanoseconds()
}
for {
mu.Lock()
if client == nil { // client can be closed already
mu.Unlock()
return
}
clientClose := client.Wait()
mu.Unlock()
select {
case <-mappingClose.LockedChan(&mu):
return
case <-clientClose:
return
case <-time.After(time.Duration(refresh) * time.Nanosecond):
}
// in go routine do 1 seconds discovery
mappingPort(1 * time.Second)
if udpPort != "" { // on success, normal refresh rate
refresh = RefreshPort
} else {
refresh = refresh * 2
}
if refresh > RefreshPort {
refresh = RefreshPort
}
}
}
func mappingStop() {
mappingClose.Set()
mappingAddr = nil
updateClientAddr(clientAddr)
}