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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
|
/* global URL, Blob */
module.exports = Torrent
var addrToIPPort = require('addr-to-ip-port')
var BitField = require('bitfield')
var ChunkStoreWriteStream = require('chunk-store-stream/write')
var debug = require('debug')('webtorrent:torrent')
var Discovery = require('torrent-discovery')
var EventEmitter = require('events').EventEmitter
var extend = require('xtend')
var extendMutable = require('xtend/mutable')
var fs = require('fs')
var FSChunkStore = require('fs-chunk-store') // browser: `memory-chunk-store`
var ImmediateChunkStore = require('immediate-chunk-store')
var inherits = require('inherits')
var MultiStream = require('multistream')
var net = require('net') // browser exclude
var os = require('os') // browser exclude
var parallel = require('run-parallel')
var parallelLimit = require('run-parallel-limit')
var parseTorrent = require('parse-torrent')
var path = require('path')
var pathExists = require('path-exists') // browser exclude
var Piece = require('torrent-piece')
var pump = require('pump')
var randomIterate = require('random-iterate')
var sha1 = require('simple-sha1')
var speedometer = require('speedometer')
var uniq = require('uniq')
var utMetadata = require('ut_metadata')
var utPex = require('ut_pex') // browser exclude
var File = require('./file')
var Peer = require('./peer')
var RarityMap = require('./rarity-map')
var Server = require('./server') // browser exclude
var MAX_BLOCK_LENGTH = 128 * 1024
var PIECE_TIMEOUT = 30000
var CHOKE_TIMEOUT = 5000
var SPEED_THRESHOLD = 3 * Piece.BLOCK_LENGTH
var PIPELINE_MIN_DURATION = 0.5
var PIPELINE_MAX_DURATION = 1
var RECHOKE_INTERVAL = 10000 // 10 seconds
var RECHOKE_OPTIMISTIC_DURATION = 2 // 30 seconds
var FILESYSTEM_CONCURRENCY = 2
var RECONNECT_WAIT = [ 1000, 5000, 15000 ]
var TMP = typeof pathExists.sync === 'function'
? path.join(pathExists.sync('/tmp') ? '/tmp' : os.tmpDir(), 'webtorrent')
: '/tmp/webtorrent'
inherits(Torrent, EventEmitter)
function Torrent (torrentId, client, opts) {
EventEmitter.call(this)
this.client = client
this._debugId = this.client.peerId.slice(32)
this._debug('new torrent')
this.announce = opts.announce
this.urlList = opts.urlList
this.path = opts.path
this._store = opts.store || FSChunkStore
this._getAnnounceOpts = opts.getAnnounceOpts
this.strategy = opts.strategy || 'sequential'
this.maxWebConns = opts.maxWebConns || 4
this._rechokeNumSlots = (opts.uploads === false || opts.uploads === 0)
? 0
: (+opts.uploads || 10)
this._rechokeOptimisticWire = null
this._rechokeOptimisticTime = 0
this._rechokeIntervalId = null
this.ready = false
this.destroyed = false
this.paused = false
this.done = false
this.metadata = null
this.store = null
this.files = []
this.pieces = []
this._amInterested = false
this._selections = []
this._critical = []
this.wires = [] // open wires (added *after* handshake)
this._queue = [] // queue of outgoing tcp peers to connect to
this._peers = {} // connected peers (addr/peerId -> Peer)
this._peersLength = 0 // number of elements in `this._peers` (cache, for perf)
// stats
this.received = 0
this.uploaded = 0
this._downloadSpeed = speedometer()
this._uploadSpeed = speedometer()
// for cleanup
this._servers = []
// TODO: remove this and expose a hook instead
// optimization: don't recheck every file if it hasn't changed
this._fileModtimes = opts.fileModtimes
if (torrentId !== null) this._onTorrentId(torrentId)
}
Object.defineProperty(Torrent.prototype, 'timeRemaining', {
get: function () {
if (this.done) return 0
if (this.downloadSpeed === 0) return Infinity
return ((this.length - this.downloaded) / this.downloadSpeed) * 1000
}
})
Object.defineProperty(Torrent.prototype, 'downloaded', {
get: function () {
if (!this.bitfield) return 0
var downloaded = 0
for (var index = 0, len = this.pieces.length; index < len; ++index) {
if (this.bitfield.get(index)) { // verified data
downloaded += (index === len - 1) ? this.lastPieceLength : this.pieceLength
} else { // "in progress" data
var piece = this.pieces[index]
downloaded += (piece.length - piece.missing)
}
}
return downloaded
}
})
// TODO: re-enable this. The number of missing pieces. Used to implement 'end game' mode.
// Object.defineProperty(Storage.prototype, 'numMissing', {
// get: function () {
// var self = this
// var numMissing = self.pieces.length
// for (var index = 0, len = self.pieces.length; index < len; index++) {
// numMissing -= self.bitfield.get(index)
// }
// return numMissing
// }
// })
Object.defineProperty(Torrent.prototype, 'downloadSpeed', {
get: function () { return this._downloadSpeed() }
})
Object.defineProperty(Torrent.prototype, 'uploadSpeed', {
get: function () { return this._uploadSpeed() }
})
Object.defineProperty(Torrent.prototype, 'progress', {
get: function () { return this.length ? this.downloaded / this.length : 0 }
})
Object.defineProperty(Torrent.prototype, 'ratio', {
get: function () { return this.uploaded / (this.received || 1) }
})
Object.defineProperty(Torrent.prototype, 'numPeers', {
get: function () { return this.wires.length }
})
Object.defineProperty(Torrent.prototype, 'torrentFileBlobURL', {
get: function () {
if (typeof window === 'undefined') throw new Error('browser-only property')
if (!this.torrentFile) return null
return URL.createObjectURL(
new Blob([ this.torrentFile ], { type: 'application/x-bittorrent' })
)
}
})
Object.defineProperty(Torrent.prototype, '_numQueued', {
get: function () {
return this._queue.length + (this._peersLength - this._numConns)
}
})
Object.defineProperty(Torrent.prototype, '_numConns', {
get: function () {
var self = this
var numConns = 0
for (var id in self._peers) {
if (self._peers[id].connected) numConns += 1
}
return numConns
}
})
// TODO: remove in v2
Object.defineProperty(Torrent.prototype, 'swarm', {
get: function () {
console.log('WebTorrent: `torrent.swarm` is deprecated. Use `torrent` directly instead.')
return this
}
})
Torrent.prototype._onTorrentId = function (torrentId) {
var self = this
if (self.destroyed) return
var parsedTorrent
try { parsedTorrent = parseTorrent(torrentId) } catch (err) {}
if (parsedTorrent) {
// Attempt to set infoHash property synchronously
self.infoHash = parsedTorrent.infoHash
process.nextTick(function () {
if (self.destroyed) return
self._onParsedTorrent(parsedTorrent)
})
} else {
// If torrentId failed to parse, it could be in a form that requires an async
// operation, i.e. http/https link, filesystem path, or Blob.
parseTorrent.remote(torrentId, function (err, parsedTorrent) {
if (self.destroyed) return
if (err) return self._destroy(err)
self._onParsedTorrent(parsedTorrent)
})
}
}
Torrent.prototype._onParsedTorrent = function (parsedTorrent) {
var self = this
if (self.destroyed) return
self._processParsedTorrent(parsedTorrent)
if (!self.infoHash) {
return self._destroy(new Error('Malformed torrent data: No info hash'))
}
if (!self.path) self.path = path.join(TMP, self.infoHash)
self._rechokeIntervalId = setInterval(function () {
self._rechoke()
}, RECHOKE_INTERVAL)
if (self._rechokeIntervalId.unref) self._rechokeIntervalId.unref()
self.emit('infoHash', self.infoHash)
if (self.destroyed) return // user might destroy torrent in `infoHash` event handler
if (self.client.listening) {
self._onListening()
} else {
self.client.once('listening', function () {
self._onListening()
})
}
}
Torrent.prototype._processParsedTorrent = function (parsedTorrent) {
if (this.announce) {
// Allow specifying trackers via `opts` parameter
parsedTorrent.announce = parsedTorrent.announce.concat(this.announce)
}
if (this.client.tracker && global.WEBTORRENT_ANNOUNCE && !this.private) {
// So `webtorrent-hybrid` can force specific trackers to be used
parsedTorrent.announce = parsedTorrent.announce.concat(global.WEBTORRENT_ANNOUNCE)
}
if (this.urlList) {
// Allow specifying web seeds via `opts` parameter
parsedTorrent.urlList = parsedTorrent.urlList.concat(this.urlList)
}
uniq(parsedTorrent.announce)
uniq(parsedTorrent.urlList)
extendMutable(this, parsedTorrent)
this.magnetURI = parseTorrent.toMagnetURI(parsedTorrent)
this.torrentFile = parseTorrent.toTorrentFile(parsedTorrent)
}
Torrent.prototype._onListening = function () {
var self = this
if (self.discovery || self.destroyed) return
var trackerOpts = {
rtcConfig: self.client._rtcConfig,
wrtc: self.client._wrtc,
getAnnounceOpts: function () {
var opts = {
uploaded: self.uploaded,
downloaded: self.downloaded,
left: Math.max(self.length - self.downloaded, 0)
}
if (self._getAnnounceOpts) opts = extend(opts, self._getAnnounceOpts())
return opts
}
}
// begin discovering peers via DHT and trackers
self.discovery = new Discovery({
infoHash: self.infoHash,
announce: self.announce,
peerId: self.client.peerId,
dht: !self.private && self.client.dht,
tracker: self.client.tracker && trackerOpts,
port: self.client.torrentPort
})
self.discovery.on('error', onError)
self.discovery.on('peer', onPeer)
self.discovery.on('trackerAnnounce', onTrackerAnnounce)
self.discovery.on('dhtAnnounce', onDHTAnnounce)
self.discovery.on('warning', onWarning)
function onError (err) {
self._destroy(err)
}
function onPeer (peer) {
// Don't create new outgoing TCP connections when torrent is done
if (typeof peer === 'string' && self.done) return
self.addPeer(peer)
}
function onTrackerAnnounce () {
self.emit('trackerAnnounce')
if (self.numPeers === 0) self.emit('noPeers', 'tracker')
}
function onDHTAnnounce () {
self.emit('dhtAnnounce')
if (self.numPeers === 0) self.emit('noPeers', 'dht')
}
function onWarning (err) {
self.emit('warning', err)
}
// if full metadata was included in initial torrent id, use it immediately. Otherwise,
// wait for torrent-discovery to find peers and ut_metadata to get the metadata.
if (self.info) self._onMetadata(self)
}
/**
* Called when the full torrent metadata is received.
*/
Torrent.prototype._onMetadata = function (metadata) {
var self = this
if (self.metadata || self.destroyed) return
self._debug('got metadata')
var parsedTorrent
if (metadata && metadata.infoHash) {
// `metadata` is a parsed torrent (from parse-torrent module)
parsedTorrent = metadata
} else {
try {
parsedTorrent = parseTorrent(metadata)
} catch (err) {
return self._destroy(err)
}
}
self._processParsedTorrent(parsedTorrent)
self.metadata = self.torrentFile
// add web seed urls (BEP19)
self.urlList.forEach(function (url) {
self.addWebSeed(url)
})
self._rarityMap = new RarityMap(self)
self.store = new ImmediateChunkStore(
new self._store(self.pieceLength, {
torrent: {
infoHash: self.infoHash
},
files: self.files.map(function (file) {
return {
path: path.join(self.path, file.path),
length: file.length,
offset: file.offset
}
}),
length: self.length
})
)
self.files = self.files.map(function (file) {
return new File(self, file)
})
self._hashes = self.pieces
self.pieces = self.pieces.map(function (hash, i) {
var pieceLength = (i === self.pieces.length - 1)
? self.lastPieceLength
: self.pieceLength
return new Piece(pieceLength)
})
self._reservations = self.pieces.map(function () {
return []
})
self.bitfield = new BitField(self.pieces.length)
self.wires.forEach(function (wire) {
// If we didn't have the metadata at the time ut_metadata was initialized for this
// wire, we still want to make it available to the peer in case they request it.
if (wire.ut_metadata) wire.ut_metadata.setMetadata(self.metadata)
self._onWireWithMetadata(wire)
})
self._debug('verifying existing torrent data')
if (self._fileModtimes && self._store === FSChunkStore) {
// don't verify if the files haven't been modified since we last checked
self.getFileModtimes(function (err, fileModtimes) {
if (err) return self._destroy(err)
var unchanged = self.files.map(function (_, index) {
return fileModtimes[index] === self._fileModtimes[index]
}).every(function (x) {
return x
})
if (unchanged) {
for (var index = 0; index < self.pieces.length; index++) {
self._markVerified(index)
}
self._onStore()
} else {
self._verifyPieces()
}
})
} else {
self._verifyPieces()
}
self.emit('metadata')
}
/*
* TODO: remove this
* Gets the last modified time of every file on disk for this torrent.
* Only valid in Node, not in the browser.
*/
Torrent.prototype.getFileModtimes = function (cb) {
var self = this
var ret = []
parallelLimit(self.files.map(function (file, index) {
return function (cb) {
fs.stat(path.join(self.path, file.path), function (err, stat) {
if (err && err.code !== 'ENOENT') return cb(err)
ret[index] = stat && stat.mtime.getTime()
cb(null)
})
}
}), FILESYSTEM_CONCURRENCY, function (err) {
self._debug('done getting file modtimes')
cb(err, ret)
})
}
Torrent.prototype._verifyPieces = function () {
var self = this
parallelLimit(self.pieces.map(function (_, index) {
return function (cb) {
if (self.destroyed) return cb(new Error('torrent is destroyed'))
self.store.get(index, function (err, buf) {
if (err) return cb(null) // ignore error
sha1(buf, function (hash) {
if (hash === self._hashes[index]) {
if (!self.pieces[index]) return
self._debug('piece verified %s', index)
self._markVerified(index)
} else {
self._debug('piece invalid %s', index)
}
cb(null)
})
})
}
}), FILESYSTEM_CONCURRENCY, function (err) {
if (err) return self._destroy(err)
self._debug('done verifying')
self._onStore()
})
}
Torrent.prototype._markVerified = function (index) {
this.pieces[index] = null
this._reservations[index] = null
this.bitfield.set(index, true)
}
/**
* Called when the metadata, listening server, and underlying chunk store is initialized.
*/
Torrent.prototype._onStore = function () {
var self = this
if (self.destroyed) return
self._debug('on store')
// start off selecting the entire torrent with low priority
self.select(0, self.pieces.length - 1, false)
self.ready = true
self.emit('ready')
// Files may start out done if the file was already in the store
self._checkDone()
// In case any selections were made before torrent was ready
self._updateSelections()
}
Torrent.prototype.destroy = function (cb) {
var self = this
self._destroy(null, cb)
}
Torrent.prototype._destroy = function (err, cb) {
var self = this
if (self.destroyed) return
self.destroyed = true
self._debug('destroy')
self.client._remove(self)
clearInterval(self._rechokeIntervalId)
if (self._rarityMap) {
self._rarityMap.destroy()
}
for (var id in self._peers) {
self.removePeer(id)
}
self.files.forEach(function (file) {
if (file instanceof File) file._destroy()
})
var tasks = self._servers.map(function (server) {
return function (cb) {
server.destroy(cb)
}
})
if (self.discovery) {
tasks.push(function (cb) {
self.discovery.destroy(cb)
})
}
if (self.store) {
tasks.push(function (cb) {
self.store.close(cb)
})
}
parallel(tasks, cb)
if (err) {
// Torrent errors are emitted at `torrent.on('error')`. If there are no 'error' event
// handlers on the torrent instance, the error will be emitted at
// `client.on('error')`. This prevents crashing the user's program, but it makes it
// impossible to determine a client error versus a torrent error (where the client
// is still usable afterwards). Users are recommended for errors in both places
// to distinguish between the error types.
if (self.listenerCount('error') === 0) {
self.client.emit('error', err)
} else {
self.emit('error', err)
}
}
self.emit('close')
self.client = null
self.files = []
self.discovery = null
self.store = null
self._rarityMap = null
self._peers = null
self._servers = null
}
Torrent.prototype.addPeer = function (peer) {
var self = this
if (self.destroyed) throw new Error('torrent is destroyed')
if (!self.infoHash) throw new Error('addPeer() must not be called before the `infoHash` event')
if (self.client.blocked) {
var host
if (typeof peer === 'string') {
var parts
try {
parts = addrToIPPort(peer)
} catch (e) {
self._debug('ignoring peer: invalid %s', peer)
self.emit('invalidPeer', peer)
return false
}
host = parts[0]
} else if (typeof peer.remoteAddress === 'string') {
host = peer.remoteAddress
}
if (host && self.client.blocked.contains(host)) {
self._debug('ignoring peer: blocked %s', peer)
if (typeof peer !== 'string') peer.destroy()
self.emit('blockedPeer', peer)
return false
}
}
var wasAdded = !!self._addPeer(peer)
if (wasAdded) {
self.emit('peer', peer)
} else {
self.emit('invalidPeer', peer)
}
return wasAdded
}
Torrent.prototype._addPeer = function (peer) {
var self = this
if (self.destroyed) {
self._debug('ignoring peer: torrent is destroyed')
if (typeof peer !== 'string') peer.destroy()
return null
}
if (typeof peer === 'string' && !self._validAddr(peer)) {
self._debug('ignoring peer: invalid %s', peer)
return null
}
var id = (peer && peer.id) || peer
if (self._peers[id]) {
self._debug('ignoring peer: duplicate (%s)', id)
if (typeof peer !== 'string') peer.destroy()
return null
}
if (self.paused) {
self._debug('ignoring peer: torrent is paused')
if (typeof peer !== 'string') peer.destroy()
return null
}
self._debug('add peer %s', id)
var newPeer
if (typeof peer === 'string') {
// `peer` is an addr ("ip:port" string)
newPeer = Peer.createTCPOutgoingPeer(peer, self)
} else {
// `peer` is a WebRTC connection (simple-peer)
newPeer = Peer.createWebRTCPeer(peer, self)
}
self._peers[newPeer.id] = newPeer
self._peersLength += 1
if (typeof peer === 'string') {
// `peer` is an addr ("ip:port" string)
self._queue.push(newPeer)
self._drain()
}
return newPeer
}
Torrent.prototype.addWebSeed = function (url) {
if (this.destroyed) throw new Error('torrent is destroyed')
if (!/^https?:\/\/.+/.test(url)) {
this._debug('ignoring invalid web seed %s', url)
this.emit('invalidPeer', url)
return
}
if (this._peers[url]) {
this._debug('ignoring duplicate web seed %s', url)
this.emit('invalidPeer', url)
return
}
this._debug('add web seed %s', url)
var newPeer = Peer.createWebSeedPeer(url, this)
this._peers[newPeer.id] = newPeer
this._peersLength += 1
this.emit('peer', url)
}
/**
* Called whenever a new incoming TCP peer connects to this torrent swarm. Called with a
* peer that has already sent a handshake.
*/
Torrent.prototype._addIncomingPeer = function (peer) {
var self = this
if (self.destroyed) return peer.destroy(new Error('torrent is destroyed'))
if (self.paused) return peer.destroy(new Error('torrent is paused'))
this._debug('add incoming peer %s', peer.id)
self._peers[peer.id] = peer
self._peersLength += 1
}
Torrent.prototype.removePeer = function (peer) {
var self = this
var id = (peer && peer.id) || peer
peer = self._peers[id]
if (!peer) return
this._debug('removePeer %s', id)
delete self._peers[id]
self._peersLength -= 1
peer.destroy()
// If torrent swarm was at capacity before, try to open a new connection now
self._drain()
}
Torrent.prototype.select = function (start, end, priority, notify) {
var self = this
if (self.destroyed) throw new Error('torrent is destroyed')
if (start > end || start < 0 || end >= self.pieces.length) {
throw new Error('invalid selection ', start, ':', end)
}
priority = Number(priority) || 0
self._debug('select %s-%s (priority %s)', start, end, priority)
self._selections.push({
from: start,
to: end,
offset: 0,
priority: priority,
notify: notify || noop
})
self._selections.sort(function (a, b) {
return b.priority - a.priority
})
self._updateSelections()
}
Torrent.prototype.deselect = function (start, end, priority) {
var self = this
if (self.destroyed) throw new Error('torrent is destroyed')
priority = Number(priority) || 0
self._debug('deselect %s-%s (priority %s)', start, end, priority)
for (var i = 0; i < self._selections.length; ++i) {
var s = self._selections[i]
if (s.from === start && s.to === end && s.priority === priority) {
self._selections.splice(i--, 1)
break
}
}
self._updateSelections()
}
Torrent.prototype.critical = function (start, end) {
var self = this
if (self.destroyed) throw new Error('torrent is destroyed')
self._debug('critical %s-%s', start, end)
for (var i = start; i <= end; ++i) {
self._critical[i] = true
}
self._updateSelections()
}
Torrent.prototype._onWire = function (wire, addr) {
var self = this
self._debug('got wire %s (%s)', wire._debugId, addr || 'Unknown')
wire.on('download', function (downloaded) {
if (self.destroyed) return
self.received += downloaded
self._downloadSpeed(downloaded)
self.client._downloadSpeed(downloaded)
self.emit('download', downloaded)
self.client.emit('download', downloaded)
})
wire.on('upload', function (uploaded) {
if (self.destroyed) return
self.uploaded += uploaded
self._uploadSpeed(uploaded)
self.client._uploadSpeed(uploaded)
self.emit('upload', uploaded)
self.client.emit('upload', uploaded)
})
self.wires.push(wire)
if (addr) {
// Sometimes RTCPeerConnection.getStats() doesn't return an ip:port for peers
var parts = addrToIPPort(addr)
wire.remoteAddress = parts[0]
wire.remotePort = parts[1]
}
// When peer sends PORT message, add that DHT node to routing table
if (self.client.dht && self.client.dht.listening) {
wire.on('port', function (port) {
if (self.destroyed || self.client.dht.destroyed) {
return
}
if (!wire.remoteAddress) {
return self._debug('ignoring PORT from peer with no address')
}
if (port === 0 || port > 65536) {
return self._debug('ignoring invalid PORT from peer')
}
self._debug('port: %s (from %s)', port, addr)
self.client.dht.addNode({ host: wire.remoteAddress, port: port })
})
}
wire.on('timeout', function () {
self._debug('wire timeout (%s)', addr)
// TODO: this might be destroying wires too eagerly
wire.destroy()
})
// Timeout for piece requests to this peer
wire.setTimeout(PIECE_TIMEOUT, true)
// Send KEEP-ALIVE (every 60s) so peers will not disconnect the wire
wire.setKeepAlive(true)
// use ut_metadata extension
wire.use(utMetadata(self.metadata))
wire.ut_metadata.on('warning', function (err) {
self._debug('ut_metadata warning: %s', err.message)
})
if (!self.metadata) {
wire.ut_metadata.on('metadata', function (metadata) {
self._debug('got metadata via ut_metadata')
self._onMetadata(metadata)
})
wire.ut_metadata.fetch()
}
// use ut_pex extension if the torrent is not flagged as private
if (typeof utPex === 'function' && !self.private) {
wire.use(utPex())
wire.ut_pex.on('peer', function (peer) {
// Only add potential new peers when we're not seeding
if (self.done) return
self._debug('ut_pex: got peer: %s (from %s)', peer, addr)
self.addPeer(peer)
})
wire.ut_pex.on('dropped', function (peer) {
// the remote peer believes a given peer has been dropped from the torrent swarm.
// if we're not currently connected to it, then remove it from the queue.
var peerObj = self._peers[peer]
if (peerObj && !peerObj.connected) {
self._debug('ut_pex: dropped peer: %s (from %s)', peer, addr)
self.removePeer(peer)
}
})
wire.once('close', function () {
// Stop sending updates to remote peer
wire.ut_pex.reset()
})
}
// Hook to allow user-defined `bittorrent-protocol` extensions
// More info: https://github.com/feross/bittorrent-protocol#extension-api
self.emit('wire', wire, addr)
if (self.metadata) {
process.nextTick(function () {
// This allows wire.handshake() to be called (by Peer.onHandshake) before any
// messages get sent on the wire
self._onWireWithMetadata(wire)
})
}
}
Torrent.prototype._onWireWithMetadata = function (wire) {
var self = this
var timeoutId = null
function onChokeTimeout () {
if (self.destroyed || wire.destroyed) return
if (self._numQueued > 2 * (self._numConns - self.numPeers) &&
wire.amInterested) {
wire.destroy()
} else {
timeoutId = setTimeout(onChokeTimeout, CHOKE_TIMEOUT)
if (timeoutId.unref) timeoutId.unref()
}
}
var i = 0
function updateSeedStatus () {
if (wire.peerPieces.length !== self.pieces.length) return
for (; i < self.pieces.length; ++i) {
if (!wire.peerPieces.get(i)) return
}
wire.isSeeder = true
wire.choke() // always choke seeders
}
wire.on('bitfield', function () {
updateSeedStatus()
self._update()
})
wire.on('have', function () {
updateSeedStatus()
self._update()
})
wire.once('interested', function () {
wire.unchoke()
})
wire.once('close', function () {
clearTimeout(timeoutId)
})
wire.on('choke', function () {
clearTimeout(timeoutId)
timeoutId = setTimeout(onChokeTimeout, CHOKE_TIMEOUT)
if (timeoutId.unref) timeoutId.unref()
})
wire.on('unchoke', function () {
clearTimeout(timeoutId)
self._update()
})
wire.on('request', function (index, offset, length, cb) {
if (length > MAX_BLOCK_LENGTH) {
// Per spec, disconnect from peers that request >128KB
return wire.destroy()
}
if (self.pieces[index]) return
self.store.get(index, { offset: offset, length: length }, cb)
})
wire.bitfield(self.bitfield) // always send bitfield (required)
wire.interested() // always start out interested
// Send PORT message to peers that support DHT
if (wire.peerExtensions.dht && self.client.dht && self.client.dht.listening) {
wire.port(self.client.dht.address().port)
}
timeoutId = setTimeout(onChokeTimeout, CHOKE_TIMEOUT)
if (timeoutId.unref) timeoutId.unref()
wire.isSeeder = false
updateSeedStatus()
}
/**
* Called on selection changes.
*/
Torrent.prototype._updateSelections = function () {
var self = this
if (!self.ready || self.destroyed) return
process.nextTick(function () {
self._gcSelections()
})
self._updateInterest()
self._update()
}
/**
* Garbage collect selections with respect to the store's current state.
*/
Torrent.prototype._gcSelections = function () {
var self = this
for (var i = 0; i < self._selections.length; i++) {
var s = self._selections[i]
var oldOffset = s.offset
// check for newly downloaded pieces in selection
while (self.bitfield.get(s.from + s.offset) && s.from + s.offset < s.to) {
s.offset++
}
if (oldOffset !== s.offset) s.notify()
if (s.to !== s.from + s.offset) continue
if (!self.bitfield.get(s.from + s.offset)) continue
// remove fully downloaded selection
self._selections.splice(i--, 1) // decrement i to offset splice
s.notify() // TODO: this may notify twice in a row. is this a problem?
self._updateInterest()
}
if (!self._selections.length) self.emit('idle')
}
/**
* Update interested status for all peers.
*/
Torrent.prototype._updateInterest = function () {
var self = this
var prev = self._amInterested
self._amInterested = !!self._selections.length
self.wires.forEach(function (wire) {
// TODO: only call wire.interested if the wire has at least one piece we need
if (self._amInterested) wire.interested()
else wire.uninterested()
})
if (prev === self._amInterested) return
if (self._amInterested) self.emit('interested')
else self.emit('uninterested')
}
/**
* Heartbeat to update all peers and their requests.
*/
Torrent.prototype._update = function () {
var self = this
if (self.destroyed) return
// update wires in random order for better request distribution
var ite = randomIterate(self.wires)
var wire
while ((wire = ite())) {
self._updateWire(wire)
}
}
/**
* Attempts to update a peer's requests
*/
Torrent.prototype._updateWire = function (wire) {
var self = this
if (wire.peerChoking) return
if (!wire.downloaded) return validateWire()
var minOutstandingRequests = getBlockPipelineLength(wire, PIPELINE_MIN_DURATION)
if (wire.requests.length >= minOutstandingRequests) return
var maxOutstandingRequests = getBlockPipelineLength(wire, PIPELINE_MAX_DURATION)
trySelectWire(false) || trySelectWire(true)
function genPieceFilterFunc (start, end, tried, rank) {
return function (i) {
return i >= start && i <= end && !(i in tried) && wire.peerPieces.get(i) && (!rank || rank(i))
}
}
// TODO: Do we need both validateWire and trySelectWire?
function validateWire () {
if (wire.requests.length) return
var i = self._selections.length
while (i--) {
var next = self._selections[i]
var piece
if (self.strategy === 'rarest') {
var start = next.from + next.offset
var end = next.to
var len = end - start + 1
var tried = {}
var tries = 0
var filter = genPieceFilterFunc(start, end, tried)
while (tries < len) {
piece = self._rarityMap.getRarestPiece(filter)
if (piece < 0) break
if (self._request(wire, piece, false)) return
tried[piece] = true
tries += 1
}
} else {
for (piece = next.to; piece >= next.from + next.offset; --piece) {
if (!wire.peerPieces.get(piece)) continue
if (self._request(wire, piece, false)) return
}
}
}
// TODO: wire failed to validate as useful; should we close it?
// probably not, since 'have' and 'bitfield' messages might be coming
}
function speedRanker () {
var speed = wire.downloadSpeed() || 1
if (speed > SPEED_THRESHOLD) return function () { return true }
var secs = Math.max(1, wire.requests.length) * Piece.BLOCK_LENGTH / speed
var tries = 10
var ptr = 0
return function (index) {
if (!tries || self.bitfield.get(index)) return true
var missing = self.pieces[index].missing
for (; ptr < self.wires.length; ptr++) {
var otherWire = self.wires[ptr]
var otherSpeed = otherWire.downloadSpeed()
if (otherSpeed < SPEED_THRESHOLD) continue
if (otherSpeed <= speed) continue
if (!otherWire.peerPieces.get(index)) continue
if ((missing -= otherSpeed * secs) > 0) continue
tries--
return false
}
return true
}
}
function shufflePriority (i) {
var last = i
for (var j = i; j < self._selections.length && self._selections[j].priority; j++) {
last = j
}
var tmp = self._selections[i]
self._selections[i] = self._selections[last]
self._selections[last] = tmp
}
function trySelectWire (hotswap) {
if (wire.requests.length >= maxOutstandingRequests) return true
var rank = speedRanker()
for (var i = 0; i < self._selections.length; i++) {
var next = self._selections[i]
var piece
if (self.strategy === 'rarest') {
var start = next.from + next.offset
var end = next.to
var len = end - start + 1
var tried = {}
var tries = 0
var filter = genPieceFilterFunc(start, end, tried, rank)
while (tries < len) {
piece = self._rarityMap.getRarestPiece(filter)
if (piece < 0) break
// request all non-reserved blocks in this piece
while (self._request(wire, piece, self._critical[piece] || hotswap)) {}
if (wire.requests.length < maxOutstandingRequests) {
tried[piece] = true
tries++
continue
}
if (next.priority) shufflePriority(i)
return true
}
} else {
for (piece = next.from + next.offset; piece <= next.to; piece++) {
if (!wire.peerPieces.get(piece) || !rank(piece)) continue
// request all non-reserved blocks in piece
while (self._request(wire, piece, self._critical[piece] || hotswap)) {}
if (wire.requests.length < maxOutstandingRequests) continue
if (next.priority) shufflePriority(i)
return true
}
}
}
return false
}
}
/**
* Called periodically to update the choked status of all peers, handling optimistic
* unchoking as described in BEP3.
*/
Torrent.prototype._rechoke = function () {
var self = this
if (!self.ready) return
if (self._rechokeOptimisticTime > 0) self._rechokeOptimisticTime -= 1
else self._rechokeOptimisticWire = null
var peers = []
self.wires.forEach(function (wire) {
if (!wire.isSeeder && wire !== self._rechokeOptimisticWire) {
peers.push({
wire: wire,
downloadSpeed: wire.downloadSpeed(),
uploadSpeed: wire.uploadSpeed(),
salt: Math.random(),
isChoked: true
})
}
})
peers.sort(rechokeSort)
var unchokeInterested = 0
var i = 0
for (; i < peers.length && unchokeInterested < self._rechokeNumSlots; ++i) {
peers[i].isChoked = false
if (peers[i].wire.peerInterested) unchokeInterested += 1
}
// Optimistically unchoke a peer
if (!self._rechokeOptimisticWire && i < peers.length && self._rechokeNumSlots) {
var candidates = peers.slice(i).filter(function (peer) { return peer.wire.peerInterested })
var optimistic = candidates[randomInt(candidates.length)]
if (optimistic) {
optimistic.isChoked = false
self._rechokeOptimisticWire = optimistic.wire
self._rechokeOptimisticTime = RECHOKE_OPTIMISTIC_DURATION
}
}
// Unchoke best peers
peers.forEach(function (peer) {
if (peer.wire.amChoking !== peer.isChoked) {
if (peer.isChoked) peer.wire.choke()
else peer.wire.unchoke()
}
})
function rechokeSort (peerA, peerB) {
// Prefer higher download speed
if (peerA.downloadSpeed !== peerB.downloadSpeed) {
return peerB.downloadSpeed - peerA.downloadSpeed
}
// Prefer higher upload speed
if (peerA.uploadSpeed !== peerB.uploadSpeed) {
return peerB.uploadSpeed - peerA.uploadSpeed
}
// Prefer unchoked
if (peerA.wire.amChoking !== peerB.wire.amChoking) {
return peerA.wire.amChoking ? 1 : -1
}
// Random order
return peerA.salt - peerB.salt
}
}
/**
* Attempts to cancel a slow block request from another wire such that the
* given wire may effectively swap out the request for one of its own.
*/
Torrent.prototype._hotswap = function (wire, index) {
var self = this
var speed = wire.downloadSpeed()
if (speed < Piece.BLOCK_LENGTH) return false
if (!self._reservations[index]) return false
var r = self._reservations[index]
if (!r) {
return false
}
var minSpeed = Infinity
var minWire
var i
for (i = 0; i < r.length; i++) {
var otherWire = r[i]
if (!otherWire || otherWire === wire) continue
var otherSpeed = otherWire.downloadSpeed()
if (otherSpeed >= SPEED_THRESHOLD) continue
if (2 * otherSpeed > speed || otherSpeed > minSpeed) continue
minWire = otherWire
minSpeed = otherSpeed
}
if (!minWire) return false
for (i = 0; i < r.length; i++) {
if (r[i] === minWire) r[i] = null
}
for (i = 0; i < minWire.requests.length; i++) {
var req = minWire.requests[i]
if (req.piece !== index) continue
self.pieces[index].cancel((req.offset / Piece.BLOCK_LENGTH) | 0)
}
self.emit('hotswap', minWire, wire, index)
return true
}
/**
* Attempts to request a block from the given wire.
*/
Torrent.prototype._request = function (wire, index, hotswap) {
var self = this
var numRequests = wire.requests.length
var isWebSeed = wire.type === 'webSeed'
if (self.bitfield.get(index)) return false
var maxOutstandingRequests = isWebSeed
? Math.min(
getPiecePipelineLength(wire, PIPELINE_MAX_DURATION, self.pieceLength),
self.maxWebConns
)
: getBlockPipelineLength(wire, PIPELINE_MAX_DURATION)
if (numRequests >= maxOutstandingRequests) return false
// var endGame = (wire.requests.length === 0 && self.store.numMissing < 30)
var piece = self.pieces[index]
var reservation = isWebSeed ? piece.reserveRemaining() : piece.reserve()
if (reservation === -1 && hotswap && self._hotswap(wire, index)) {
reservation = isWebSeed ? piece.reserveRemaining() : piece.reserve()
}
if (reservation === -1) return false
var r = self._reservations[index]
if (!r) r = self._reservations[index] = []
var i = r.indexOf(null)
if (i === -1) i = r.length
r[i] = wire
var chunkOffset = piece.chunkOffset(reservation)
var chunkLength = isWebSeed ? piece.chunkLengthRemaining(reservation) : piece.chunkLength(reservation)
wire.request(index, chunkOffset, chunkLength, function onChunk (err, chunk) {
// TODO: what is this for?
if (!self.ready) return self.once('ready', function () { onChunk(err, chunk) })
if (r[i] === wire) r[i] = null
if (piece !== self.pieces[index]) return onUpdateTick()
if (err) {
self._debug(
'error getting piece %s (offset: %s length: %s) from %s: %s',
index, chunkOffset, chunkLength, wire.remoteAddress + ':' + wire.remotePort,
err.message
)
isWebSeed ? piece.cancelRemaining(reservation) : piece.cancel(reservation)
onUpdateTick()
return
}
self._debug(
'got piece %s (offset: %s length: %s) from %s',
index, chunkOffset, chunkLength, wire.remoteAddress + ':' + wire.remotePort
)
if (!piece.set(reservation, chunk, wire)) return onUpdateTick()
var buf = piece.flush()
// TODO: might need to set self.pieces[index] = null here since sha1 is async
sha1(buf, function (hash) {
if (hash === self._hashes[index]) {
if (!self.pieces[index]) return
self._debug('piece verified %s', index)
self.pieces[index] = null
self._reservations[index] = null
self.bitfield.set(index, true)
self.store.put(index, buf)
self.wires.forEach(function (wire) {
wire.have(index)
})
self._checkDone()
} else {
self.pieces[index] = new Piece(piece.length)
self.emit('warning', new Error('Piece ' + index + ' failed verification'))
}
onUpdateTick()
})
})
function onUpdateTick () {
process.nextTick(function () { self._update() })
}
return true
}
Torrent.prototype._checkDone = function () {
var self = this
if (self.destroyed) return
// are any new files done?
self.files.forEach(function (file) {
if (file.done) return
for (var i = file._startPiece; i <= file._endPiece; ++i) {
if (!self.bitfield.get(i)) return
}
file.done = true
file.emit('done')
self._debug('file done: ' + file.name)
})
// is the torrent done? (if all current selections are satisfied, or there are
// no selections, then torrent is done)
var done = true
for (var i = 0; i < self._selections.length; i++) {
var selection = self._selections[i]
for (var piece = selection.from; piece <= selection.to; piece++) {
if (!self.bitfield.get(piece)) {
done = false
break
}
}
if (!done) break
}
if (!self.done && done) {
self.done = true
self._debug('torrent done: ' + self.infoHash)
if (self.discovery.tracker) {
self.discovery.tracker.complete()
}
self.emit('done')
}
self._gcSelections()
}
Torrent.prototype.load = function (streams, cb) {
var self = this
if (self.destroyed) throw new Error('torrent is destroyed')
if (!self.ready) return self.once('ready', function () { self.load(streams, cb) })
if (!Array.isArray(streams)) streams = [ streams ]
if (!cb) cb = noop
var readable = new MultiStream(streams)
var writable = new ChunkStoreWriteStream(self.store, self.pieceLength)
pump(readable, writable, function (err) {
if (err) return cb(err)
self.pieces.forEach(function (piece, index) {
self.pieces[index] = null
self._reservations[index] = null
self.bitfield.set(index, true)
})
self._checkDone()
cb(null)
})
}
Torrent.prototype.createServer = function (opts) {
if (typeof Server !== 'function') throw new Error('node.js-only method')
if (this.destroyed) throw new Error('torrent is destroyed')
var server = new Server(this, opts)
this._servers.push(server)
return server
}
Torrent.prototype.pause = function () {
if (this.destroyed) return
this._debug('pause')
this.paused = true
}
Torrent.prototype.resume = function () {
if (this.destroyed) return
this._debug('resume')
this.paused = false
this._drain()
}
Torrent.prototype._debug = function () {
var args = [].slice.call(arguments)
args[0] = '[' + this._debugId + '] ' + args[0]
debug.apply(null, args)
}
/**
* Pop a peer off the FIFO queue and connect to it. When _drain() gets called,
* the queue will usually have only one peer in it, except when there are too
* many peers (over `this.maxConns`) in which case they will just sit in the
* queue until another connection closes.
*/
Torrent.prototype._drain = function () {
var self = this
this._debug('_drain numConns %s maxConns %s', self._numConns, self.client.maxConns)
if (typeof net.connect !== 'function' || self.destroyed || self.paused ||
self._numConns >= self.client.maxConns) {
return
}
this._debug('drain (%s queued, %s/%s peers)', self._numQueued, self.numPeers, self.client.maxConns)
var peer = self._queue.shift()
if (!peer) return // queue could be empty
this._debug('tcp connect attempt to %s', peer.addr)
var parts = addrToIPPort(peer.addr)
var opts = {
host: parts[0],
port: parts[1]
}
var conn = peer.conn = net.connect(opts)
conn.once('connect', function () { peer.onConnect() })
conn.once('error', function (err) { peer.destroy(err) })
peer.startConnectTimeout()
// When connection closes, attempt reconnect after timeout (with exponential backoff)
conn.on('close', function () {
if (self.destroyed) return
// TODO: If torrent is done, do not try to reconnect after a timeout
if (peer.retries >= RECONNECT_WAIT.length) {
self._debug(
'conn %s closed: will not re-add (max %s attempts)',
peer.addr, RECONNECT_WAIT.length
)
return
}
var ms = RECONNECT_WAIT[peer.retries]
self._debug(
'conn %s closed: will re-add to queue in %sms (attempt %s)',
peer.addr, ms, peer.retries + 1
)
var reconnectTimeout = setTimeout(function reconnectTimeout () {
var newPeer = self._addPeer(peer.addr)
if (newPeer) newPeer.retries = peer.retries + 1
}, ms)
if (reconnectTimeout.unref) reconnectTimeout.unref()
})
}
/**
* Returns `true` if string is valid IPv4/6 address.
* @param {string} addr
* @return {boolean}
*/
Torrent.prototype._validAddr = function (addr) {
var parts
try {
parts = addrToIPPort(addr)
} catch (e) {
return false
}
var host = parts[0]
var port = parts[1]
return port > 0 && port < 65535 &&
!(host === '127.0.0.1' && port === this.client.torrentPort)
}
function getBlockPipelineLength (wire, duration) {
return 2 + Math.ceil(duration * wire.downloadSpeed() / Piece.BLOCK_LENGTH)
}
function getPiecePipelineLength (wire, duration, pieceLength) {
return 1 + Math.ceil(duration * wire.downloadSpeed() / pieceLength)
}
/**
* Returns a random integer in [0,high)
*/
function randomInt (high) {
return Math.random() * high | 0
}
function noop () {}
|