forked from anacrolix/torrent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathut-holepunching_test.go
407 lines (382 loc) · 10.2 KB
/
ut-holepunching_test.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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
package torrent
import (
"context"
"errors"
"fmt"
"io"
"math/rand"
"net"
"os"
"sync"
"testing"
"testing/iotest"
"time"
"github.com/anacrolix/log"
"github.com/anacrolix/missinggo/v2/iter"
qt "github.com/frankban/quicktest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/time/rate"
"github.com/anacrolix/torrent/internal/testutil"
)
// Check that after completing leeching, a leecher transitions to a seeding
// correctly. Connected in a chain like so: Seeder <-> Leecher <-> LeecherLeecher.
func TestHolepunchConnect(t *testing.T) {
c := qt.New(t)
greetingTempDir, mi := testutil.GreetingTestTorrent()
defer os.RemoveAll(greetingTempDir)
cfg := TestingConfig(t)
cfg.Seed = true
cfg.MaxAllocPeerRequestDataPerConn = 4
cfg.DataDir = greetingTempDir
cfg.DisablePEX = true
cfg.Debug = true
cfg.AcceptPeerConnections = false
// Listening, even without accepting, still means the leecher-leecher completes the dial to the
// seeder, and so it won't attempt to holepunch.
cfg.DisableTCP = true
// Ensure that responding to holepunch connects don't wait around for the dial limit. We also
// have to allow the initial connection to the leecher though, so it can rendezvous for us.
cfg.DialRateLimiter = rate.NewLimiter(0, 1)
cfg.Logger = cfg.Logger.WithContextText("seeder")
seeder, err := NewClient(cfg)
require.NoError(t, err)
defer seeder.Close()
defer testutil.ExportStatusWriter(seeder, "s", t)()
seederTorrent, ok, err := seeder.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
require.NoError(t, err)
assert.True(t, ok)
seederTorrent.VerifyData()
cfg = TestingConfig(t)
cfg.Seed = true
cfg.DataDir = t.TempDir()
cfg.AlwaysWantConns = true
cfg.Logger = cfg.Logger.WithContextText("leecher")
// This way the leecher leecher will still try to use this peer as a relay, but won't be told
// about the seeder via PEX.
//cfg.DisablePEX = true
cfg.Debug = true
leecher, err := NewClient(cfg)
require.NoError(t, err)
defer leecher.Close()
defer testutil.ExportStatusWriter(leecher, "l", t)()
cfg = TestingConfig(t)
cfg.Seed = false
cfg.DataDir = t.TempDir()
cfg.MaxAllocPeerRequestDataPerConn = 4
cfg.Debug = true
cfg.NominalDialTimeout = time.Second
cfg.Logger = cfg.Logger.WithContextText("leecher-leecher")
//cfg.DisableUTP = true
leecherLeecher, _ := NewClient(cfg)
require.NoError(t, err)
defer leecherLeecher.Close()
defer testutil.ExportStatusWriter(leecherLeecher, "ll", t)()
leecherGreeting, ok, err := leecher.AddTorrentSpec(func() (ret *TorrentSpec) {
ret = TorrentSpecFromMetaInfo(mi)
ret.ChunkSize = 2
return
}())
_ = leecherGreeting
require.NoError(t, err)
assert.True(t, ok)
llg, ok, err := leecherLeecher.AddTorrentSpec(func() (ret *TorrentSpec) {
ret = TorrentSpecFromMetaInfo(mi)
ret.ChunkSize = 3
return
}())
require.NoError(t, err)
assert.True(t, ok)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
r := llg.NewReader()
defer r.Close()
qt.Check(t, iotest.TestReader(r, []byte(testutil.GreetingFileContents)), qt.IsNil)
}()
go seederTorrent.AddClientPeer(leecher)
waitForConns(seederTorrent)
go llg.AddClientPeer(leecher)
waitForConns(llg)
time.Sleep(time.Second)
llg.cl.lock()
targetAddr := seeder.ListenAddrs()[0]
log.Printf("trying to initiate to %v", targetAddr)
initiateConn(outgoingConnOpts{
peerInfo: PeerInfo{
Addr: targetAddr,
},
t: llg,
requireRendezvous: true,
skipHolepunchRendezvous: false,
HeaderObfuscationPolicy: llg.cl.config.HeaderObfuscationPolicy,
}, true)
llg.cl.unlock()
wg.Wait()
c.Check(seeder.dialedSuccessfullyAfterHolepunchConnect, qt.Not(qt.HasLen), 0)
c.Check(leecherLeecher.probablyOnlyConnectedDueToHolepunch, qt.Not(qt.HasLen), 0)
llClientStats := leecherLeecher.Stats()
c.Check(llClientStats.NumPeersUndialableWithoutHolepunch, qt.Not(qt.Equals), 0)
c.Check(llClientStats.NumPeersUndialableWithoutHolepunchDialedAfterHolepunchConnect, qt.Not(qt.Equals), 0)
c.Check(llClientStats.NumPeersProbablyOnlyConnectedDueToHolepunch, qt.Not(qt.Equals), 0)
}
func waitForConns(t *Torrent) {
t.cl.lock()
defer t.cl.unlock()
for {
for range t.conns {
return
}
t.cl.event.Wait()
}
}
// Show that dialling TCP will complete before the other side accepts.
func TestDialTcpNotAccepting(t *testing.T) {
l, err := net.Listen("tcp", "localhost:0")
c := qt.New(t)
c.Check(err, qt.IsNil)
defer l.Close()
dialedConn, err := net.Dial("tcp", l.Addr().String())
c.Assert(err, qt.IsNil)
dialedConn.Close()
}
func TestTcpSimultaneousOpen(t *testing.T) {
const network = "tcp"
ctx := context.Background()
makeDialer := func(localPort int, remoteAddr string) func() (net.Conn, error) {
dialer := net.Dialer{
LocalAddr: &net.TCPAddr{
//IP: net.IPv6loopback,
Port: localPort,
},
}
return func() (net.Conn, error) {
return dialer.DialContext(ctx, network, remoteAddr)
}
}
c := qt.New(t)
// I really hate doing this in unit tests, but we would need to pick apart Dialer to get
// perfectly synchronized simultaneous dials.
for range iter.N(10) {
first, second := randPortPair()
t.Logf("ports are %v and %v", first, second)
err := testSimultaneousOpen(
c.Cleanup,
makeDialer(first, fmt.Sprintf("localhost:%d", second)),
makeDialer(second, fmt.Sprintf("localhost:%d", first)),
)
if err == nil {
return
}
// This proves that the connections are not the same.
if errors.Is(err, errMsgNotReceived) {
t.Fatal(err)
}
// Could be a timing issue, so try again.
t.Log(err)
}
// If we weren't able to get a simultaneous dial to occur, then we can't call it a failure.
t.Skip("couldn't synchronize dials")
}
func randIntInRange(low, high int) int {
return rand.Intn(high-low+1) + low
}
func randDynamicPort() int {
return randIntInRange(49152, 65535)
}
func randPortPair() (first int, second int) {
first = randDynamicPort()
for {
second = randDynamicPort()
if second != first {
return
}
}
}
func writeMsg(conn net.Conn) {
conn.Write([]byte(defaultMsg))
// Writing must be closed so the reader will get EOF and stop reading.
conn.Close()
}
func readMsg(conn net.Conn) error {
msgBytes, err := io.ReadAll(conn)
if err != nil {
return err
}
msgStr := string(msgBytes)
if msgStr != defaultMsg {
return fmt.Errorf("read %q", msgStr)
}
return nil
}
var errMsgNotReceived = errors.New("msg not received in time")
// Runs two dialers simultaneously, then sends a message on one connection and check it reads from
// the other, thereby showing that both dials obtained endpoints to the same connection.
func testSimultaneousOpen(
cleanup func(func()),
firstDialer, secondDialer func() (net.Conn, error),
) error {
errs := make(chan error)
var dialsDone sync.WaitGroup
const numDials = 2
dialsDone.Add(numDials)
signal := make(chan struct{})
var dialersDone sync.WaitGroup
dialersDone.Add(numDials)
doDial := func(
dialer func() (net.Conn, error),
onSignal func(net.Conn),
) {
defer dialersDone.Done()
conn, err := dialer()
dialsDone.Done()
errs <- err
if err != nil {
return
}
cleanup(func() {
conn.Close()
})
<-signal
onSignal(conn)
//if err == nil {
// conn.Close()
//}
}
go doDial(
firstDialer,
func(conn net.Conn) {
writeMsg(conn)
errs <- nil
},
)
go doDial(
secondDialer,
func(conn net.Conn) {
gotMsg := make(chan error, 1)
go func() {
gotMsg <- readMsg(conn)
}()
select {
case err := <-gotMsg:
errs <- err
case <-time.After(time.Second):
errs <- errMsgNotReceived
}
},
)
dialsDone.Wait()
for range iter.N(numDials) {
err := <-errs
if err != nil {
return err
}
}
close(signal)
for range iter.N(numDials) {
err := <-errs
if err != nil {
return err
}
}
dialersDone.Wait()
return nil
}
const defaultMsg = "hello"
// Show that uTP doesn't implement simultaneous open. When two sockets dial each other, they both
// get separate connections. This means that holepunch connect may result in an accept (and dial)
// for one or both peers involved.
func TestUtpSimultaneousOpen(t *testing.T) {
t.Parallel()
c := qt.New(t)
const network = "udp"
ctx := context.Background()
newUtpSocket := func(addr string) utpSocket {
socket, err := NewUtpSocket(
network,
addr,
func(net.Addr) bool {
return false
},
log.Default,
)
c.Assert(err, qt.IsNil)
return socket
}
first := newUtpSocket("localhost:0")
defer first.Close()
second := newUtpSocket("localhost:0")
defer second.Close()
getDial := func(sock utpSocket, addr string) func() (net.Conn, error) {
return func() (net.Conn, error) {
return sock.DialContext(ctx, network, addr)
}
}
t.Logf("first addr is %v. second addr is %v", first.Addr().String(), second.Addr().String())
for range iter.N(10) {
err := testSimultaneousOpen(
c.Cleanup,
getDial(first, second.Addr().String()),
getDial(second, first.Addr().String()),
)
if err == nil {
t.Fatal("expected utp to fail simultaneous open")
}
if errors.Is(err, errMsgNotReceived) {
return
}
skipGoUtpDialIssue(t, err)
t.Log(err)
time.Sleep(time.Second)
}
t.FailNow()
}
func writeAndReadMsg(r, w net.Conn) error {
go writeMsg(w)
return readMsg(r)
}
func skipGoUtpDialIssue(t *testing.T, err error) {
if err.Error() == "timed out waiting for ack" {
t.Skip("anacrolix go utp implementation has issues. Use anacrolix/go-libutp by enabling CGO.")
}
}
// Show that dialling one socket and accepting from the other results in them having ends of the
// same connection.
func TestUtpDirectDialMsg(t *testing.T) {
t.Parallel()
c := qt.New(t)
const network = "udp4"
ctx := context.Background()
newUtpSocket := func(addr string) utpSocket {
socket, err := NewUtpSocket(network, addr, func(net.Addr) bool {
return false
}, log.Default)
c.Assert(err, qt.IsNil)
return socket
}
for range iter.N(10) {
err := func() error {
first := newUtpSocket("localhost:0")
defer first.Close()
second := newUtpSocket("localhost:0")
defer second.Close()
writer, err := first.DialContext(ctx, network, second.Addr().String())
if err != nil {
return err
}
defer writer.Close()
reader, err := second.Accept()
defer reader.Close()
c.Assert(err, qt.IsNil)
return writeAndReadMsg(reader, writer)
}()
if err == nil {
return
}
skipGoUtpDialIssue(t, err)
t.Log(err)
time.Sleep(time.Second)
}
t.FailNow()
}