-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
torrent.js
1835 lines (1493 loc) · 52.3 KB
/
torrent.js
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
/* global Blob */
const addrToIPPort = require('addr-to-ip-port')
const BitField = require('bitfield').default
const ChunkStoreWriteStream = require('chunk-store-stream/write')
const cpus = require('cpus')
const debug = require('debug')('webtorrent:torrent')
const Discovery = require('torrent-discovery')
const EventEmitter = require('events').EventEmitter
const fs = require('fs')
const FSChunkStore = require('fs-chunk-store') // browser: `memory-chunk-store`
const get = require('simple-get')
const ImmediateChunkStore = require('immediate-chunk-store')
const ltDontHave = require('lt_donthave')
const MultiStream = require('multistream')
const net = require('net') // browser exclude
const os = require('os') // browser exclude
const parallel = require('run-parallel')
const parallelLimit = require('run-parallel-limit')
const parseTorrent = require('parse-torrent')
const path = require('path')
const Piece = require('torrent-piece')
const pump = require('pump')
const queueMicrotask = require('queue-microtask')
const randomIterate = require('random-iterate')
const sha1 = require('simple-sha1')
const speedometer = require('speedometer')
const utMetadata = require('ut_metadata')
const utp = require('utp-native') // browser exclude
const utPex = require('ut_pex') // browser exclude
const File = require('./file')
const Peer = require('./peer')
const RarityMap = require('./rarity-map')
const Server = require('./server') // browser exclude
const WebConn = require('./webconn')
const MAX_BLOCK_LENGTH = 128 * 1024
const PIECE_TIMEOUT = 30000
const CHOKE_TIMEOUT = 5000
const SPEED_THRESHOLD = 3 * Piece.BLOCK_LENGTH
const PIPELINE_MIN_DURATION = 0.5
const PIPELINE_MAX_DURATION = 1
const RECHOKE_INTERVAL = 10000 // 10 seconds
const RECHOKE_OPTIMISTIC_DURATION = 2 // 30 seconds
// IndexedDB chunk stores used in the browser benefit from high concurrency
const FILESYSTEM_CONCURRENCY = process.browser ? cpus().length : 2
const RECONNECT_WAIT = [1000, 5000, 15000]
const VERSION = require('../package.json').version
const USER_AGENT = `WebTorrent/${VERSION} (https://webtorrent.io)`
let TMP
try {
TMP = path.join(fs.statSync('/tmp') && '/tmp', 'webtorrent')
} catch (err) {
TMP = path.join(typeof os.tmpdir === 'function' ? os.tmpdir() : '/', 'webtorrent')
}
class Torrent extends EventEmitter {
constructor (torrentId, client, opts) {
super()
this._debugId = 'unknown infohash'
this.client = client
this.announce = opts.announce
this.urlList = opts.urlList
this.path = opts.path
this.skipVerify = !!opts.skipVerify
this._store = opts.store || FSChunkStore
this._preloadedStore = opts.preloadedStore || null
this._destroyStoreOnDestroy = opts.destroyStoreOnDestroy || false
this._getAnnounceOpts = opts.getAnnounceOpts
// if defined, `opts.private` overrides default privacy of torrent
if (typeof opts.private === 'boolean') this.private = opts.private
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 = []
this._xsRequests = []
// 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)
this._debug('new torrent')
}
get timeRemaining () {
if (this.done) return 0
if (this.downloadSpeed === 0) return Infinity
return ((this.length - this.downloaded) / this.downloadSpeed) * 1000
}
get downloaded () {
if (!this.bitfield) return 0
let downloaded = 0
for (let 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
const 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
// }
// })
get downloadSpeed () { return this._downloadSpeed() }
get uploadSpeed () { return this._uploadSpeed() }
get progress () { return this.length ? this.downloaded / this.length : 0 }
get ratio () { return this.uploaded / (this.received || this.length) }
get numPeers () { return this.wires.length }
get torrentFileBlobURL () {
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' })
)
}
get _numQueued () {
return this._queue.length + (this._peersLength - this._numConns)
}
get _numConns () {
let numConns = 0
for (const id in this._peers) {
if (this._peers[id].connected) numConns += 1
}
return numConns
}
// TODO: remove in v1
get swarm () {
console.warn('WebTorrent: `torrent.swarm` is deprecated. Use `torrent` directly instead.')
return this
}
_onTorrentId (torrentId) {
if (this.destroyed) return
let parsedTorrent
try { parsedTorrent = parseTorrent(torrentId) } catch (err) {}
if (parsedTorrent) {
// Attempt to set infoHash property synchronously
this.infoHash = parsedTorrent.infoHash
this._debugId = parsedTorrent.infoHash.toString('hex').substring(0, 7)
queueMicrotask(() => {
if (this.destroyed) return
this._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, (err, parsedTorrent) => {
if (this.destroyed) return
if (err) return this._destroy(err)
this._onParsedTorrent(parsedTorrent)
})
}
}
_onParsedTorrent (parsedTorrent) {
if (this.destroyed) return
this._processParsedTorrent(parsedTorrent)
if (!this.infoHash) {
return this._destroy(new Error('Malformed torrent data: No info hash'))
}
if (!this.path) this.path = path.join(TMP, this.infoHash)
this._rechokeIntervalId = setInterval(() => {
this._rechoke()
}, RECHOKE_INTERVAL)
if (this._rechokeIntervalId.unref) this._rechokeIntervalId.unref()
// Private 'infoHash' event allows client.add to check for duplicate torrents and
// destroy them before the normal 'infoHash' event is emitted. Prevents user
// applications from needing to deal with duplicate 'infoHash' events.
this.emit('_infoHash', this.infoHash)
if (this.destroyed) return
this.emit('infoHash', this.infoHash)
if (this.destroyed) return // user might destroy torrent in event handler
if (this.client.listening) {
this._onListening()
} else {
this.client.once('listening', () => {
this._onListening()
})
}
}
_processParsedTorrent (parsedTorrent) {
this._debugId = parsedTorrent.infoHash.toString('hex').substring(0, 7)
if (typeof this.private !== 'undefined') {
// `private` option overrides default, only if it's defined
parsedTorrent.private = this.private
}
if (this.announce) {
// Allow specifying trackers via `opts` parameter
parsedTorrent.announce = parsedTorrent.announce.concat(this.announce)
}
if (this.client.tracker && global.WEBTORRENT_ANNOUNCE && !parsedTorrent.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)
}
// remove duplicates by converting to Set and back
parsedTorrent.announce = Array.from(new Set(parsedTorrent.announce))
parsedTorrent.urlList = Array.from(new Set(parsedTorrent.urlList))
Object.assign(this, parsedTorrent)
this.magnetURI = parseTorrent.toMagnetURI(parsedTorrent)
this.torrentFile = parseTorrent.toTorrentFile(parsedTorrent)
}
_onListening () {
if (this.destroyed) return
if (this.info) {
// 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.
this._onMetadata(this)
} else {
if (this.xs) this._getMetadataFromServer()
this._startDiscovery()
}
}
_startDiscovery () {
if (this.discovery || this.destroyed) return
let trackerOpts = this.client.tracker
if (trackerOpts) {
trackerOpts = Object.assign({}, this.client.tracker, {
getAnnounceOpts: () => {
if (this.destroyed) return
const opts = {
uploaded: this.uploaded,
downloaded: this.downloaded,
left: Math.max(this.length - this.downloaded, 0)
}
if (this.client.tracker.getAnnounceOpts) {
Object.assign(opts, this.client.tracker.getAnnounceOpts())
}
if (this._getAnnounceOpts) {
// TODO: consider deprecating this, as it's redundant with the former case
Object.assign(opts, this._getAnnounceOpts())
}
return opts
}
})
}
// add BEP09 peer-address
if (this.peerAddresses) {
this.peerAddresses.forEach(peer => this.addPeer(peer))
}
// begin discovering peers via DHT and trackers
this.discovery = new Discovery({
infoHash: this.infoHash,
announce: this.announce,
peerId: this.client.peerId,
dht: !this.private && this.client.dht,
tracker: trackerOpts,
port: this.client.torrentPort,
userAgent: USER_AGENT,
lsd: this.client.lsd
})
this.discovery.on('error', (err) => {
this._destroy(err)
})
this.discovery.on('peer', (peer, source) => {
this._debug('peer %s discovered via %s', peer, source)
// Don't create new outgoing TCP connections when torrent is done
if (typeof peer === 'string' && this.done) return
this.addPeer(peer)
})
this.discovery.on('trackerAnnounce', () => {
this.emit('trackerAnnounce')
if (this.numPeers === 0) this.emit('noPeers', 'tracker')
})
this.discovery.on('dhtAnnounce', () => {
this.emit('dhtAnnounce')
if (this.numPeers === 0) this.emit('noPeers', 'dht')
})
this.discovery.on('warning', (err) => {
this.emit('warning', err)
})
}
_getMetadataFromServer () {
// to allow function hoisting
const self = this
const urls = Array.isArray(this.xs) ? this.xs : [this.xs]
const tasks = urls.map(url => cb => {
getMetadataFromURL(url, cb)
})
parallel(tasks)
function getMetadataFromURL (url, cb) {
if (url.indexOf('http://') !== 0 && url.indexOf('https://') !== 0) {
self.emit('warning', new Error(`skipping non-http xs param: ${url}`))
return cb(null)
}
const opts = {
url,
method: 'GET',
headers: {
'user-agent': USER_AGENT
}
}
let req
try {
req = get.concat(opts, onResponse)
} catch (err) {
self.emit('warning', new Error(`skipping invalid url xs param: ${url}`))
return cb(null)
}
self._xsRequests.push(req)
function onResponse (err, res, torrent) {
if (self.destroyed) return cb(null)
if (self.metadata) return cb(null)
if (err) {
self.emit('warning', new Error(`http error from xs param: ${url}`))
return cb(null)
}
if (res.statusCode !== 200) {
self.emit('warning', new Error(`non-200 status code ${res.statusCode} from xs param: ${url}`))
return cb(null)
}
let parsedTorrent
try {
parsedTorrent = parseTorrent(torrent)
} catch (err) {}
if (!parsedTorrent) {
self.emit('warning', new Error(`got invalid torrent file from xs param: ${url}`))
return cb(null)
}
if (parsedTorrent.infoHash !== self.infoHash) {
self.emit('warning', new Error(`got torrent file with incorrect info hash from xs param: ${url}`))
return cb(null)
}
self._onMetadata(parsedTorrent)
cb(null)
}
}
}
/**
* Called when the full torrent metadata is received.
*/
_onMetadata (metadata) {
if (this.metadata || this.destroyed) return
this._debug('got metadata')
this._xsRequests.forEach(req => {
req.abort()
})
this._xsRequests = []
let parsedTorrent
if (metadata && metadata.infoHash) {
// `metadata` is a parsed torrent (from parse-torrent module)
parsedTorrent = metadata
} else {
try {
parsedTorrent = parseTorrent(metadata)
} catch (err) {
return this._destroy(err)
}
}
this._processParsedTorrent(parsedTorrent)
this.metadata = this.torrentFile
// add web seed urls (BEP19)
if (this.client.enableWebSeeds) {
this.urlList.forEach(url => {
this.addWebSeed(url)
})
}
this._rarityMap = new RarityMap(this)
this.store = new ImmediateChunkStore(
this._preloadedStore || new this._store(this.pieceLength, {
torrent: {
infoHash: this.infoHash
},
files: this.files.map(file => ({
path: path.join(this.path, file.path),
length: file.length,
offset: file.offset
})),
length: this.length,
name: this.infoHash
})
)
this.files = this.files.map(file => new File(this, file))
// Select only specified files (BEP53) http://www.bittorrent.org/beps/bep_0053.html
if (this.so) {
this.files.forEach((v, i) => {
if (this.so.includes(i)) {
this.files[i].select()
} else {
this.files[i].deselect()
}
})
} else {
// start off selecting the entire torrent with low priority
if (this.pieces.length !== 0) {
this.select(0, this.pieces.length - 1, false)
}
}
this._hashes = this.pieces
this.pieces = this.pieces.map((hash, i) => {
const pieceLength = (i === this.pieces.length - 1)
? this.lastPieceLength
: this.pieceLength
return new Piece(pieceLength)
})
this._reservations = this.pieces.map(() => [])
this.bitfield = new BitField(this.pieces.length)
this.wires.forEach(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(this.metadata)
this._onWireWithMetadata(wire)
})
// Emit 'metadata' before 'ready' and 'done'
this.emit('metadata')
// User might destroy torrent in response to 'metadata' event
if (this.destroyed) return
if (this.skipVerify) {
// Skip verifying exisitng data and just assume it's correct
this._markAllVerified()
this._onStore()
} else {
const onPiecesVerified = (err) => {
if (err) return this._destroy(err)
this._debug('done verifying')
this._onStore()
}
this._debug('verifying existing torrent data')
if (this._fileModtimes && this._store === FSChunkStore) {
// don't verify if the files haven't been modified since we last checked
this.getFileModtimes((err, fileModtimes) => {
if (err) return this._destroy(err)
const unchanged = this.files.map((_, index) => fileModtimes[index] === this._fileModtimes[index]).every(x => x)
if (unchanged) {
this._markAllVerified()
this._onStore()
} else {
this._verifyPieces(onPiecesVerified)
}
})
} else {
this._verifyPieces(onPiecesVerified)
}
}
}
/*
* TODO: remove this
* Gets the last modified time of every file on disk for this torrent.
* Only valid in Node, not in the browser.
*/
getFileModtimes (cb) {
const ret = []
parallelLimit(this.files.map((file, index) => cb => {
fs.stat(path.join(this.path, file.path), (err, stat) => {
if (err && err.code !== 'ENOENT') return cb(err)
ret[index] = stat && stat.mtime.getTime()
cb(null)
})
}), FILESYSTEM_CONCURRENCY, err => {
this._debug('done getting file modtimes')
cb(err, ret)
})
}
_verifyPieces (cb) {
parallelLimit(this.pieces.map((piece, index) => cb => {
if (this.destroyed) return cb(new Error('torrent is destroyed'))
const getOpts = {}
// Specify length for the last piece in case it is zero-padded
if (index === this.pieces.length - 1) {
getOpts.length = this.lastPieceLength
}
this.store.get(index, getOpts, (err, buf) => {
if (this.destroyed) return cb(new Error('torrent is destroyed'))
if (err) return queueMicrotask(() => cb(null)) // ignore error
sha1(buf, hash => {
if (this.destroyed) return cb(new Error('torrent is destroyed'))
if (hash === this._hashes[index]) {
this._debug('piece verified %s', index)
this._markVerified(index)
} else {
this._debug('piece invalid %s', index)
}
cb(null)
})
})
}), FILESYSTEM_CONCURRENCY, cb)
}
rescanFiles (cb) {
if (this.destroyed) throw new Error('torrent is destroyed')
if (!cb) cb = noop
this._verifyPieces((err) => {
if (err) {
this._destroy(err)
return cb(err)
}
this._checkDone()
cb(null)
})
}
_markAllVerified () {
for (let index = 0; index < this.pieces.length; index++) {
this._markVerified(index)
}
}
_markVerified (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.
*/
_onStore () {
if (this.destroyed) return
this._debug('on store')
// Start discovery before emitting 'ready'
this._startDiscovery()
this.ready = true
this.emit('ready')
// Files may start out done if the file was already in the store
this._checkDone()
// In case any selections were made before torrent was ready
this._updateSelections()
}
destroy (opts, cb) {
if (typeof opts === 'function') return this.destroy(null, opts)
this._destroy(null, opts, cb)
}
_destroy (err, opts, cb) {
if (typeof opts === 'function') return this._destroy(err, null, opts)
if (this.destroyed) return
this.destroyed = true
this._debug('destroy')
this.client._remove(this)
clearInterval(this._rechokeIntervalId)
this._xsRequests.forEach(req => {
req.abort()
})
if (this._rarityMap) {
this._rarityMap.destroy()
}
for (const id in this._peers) {
this.removePeer(id)
}
this.files.forEach(file => {
if (file instanceof File) file._destroy()
})
const tasks = this._servers.map(server => cb => {
server.destroy(cb)
})
if (this.discovery) {
tasks.push(cb => {
this.discovery.destroy(cb)
})
}
if (this.store) {
let destroyStore = this._destroyStoreOnDestroy
if (opts && opts.destroyStore !== undefined) {
destroyStore = opts.destroyStore
}
tasks.push(cb => {
if (destroyStore) {
this.store.destroy(cb)
} else {
this.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, then the error will be emitted at
// `client.on('error')`. This prevents throwing an uncaught exception
// (unhandled 'error' event), but it makes it impossible to distinguish client
// errors versus torrent errors. Torrent errors are not fatal, and the client
// is still usable afterwards. Therefore, always listen for errors in both
// places (`client.on('error')` and `torrent.on('error')`).
if (this.listenerCount('error') === 0) {
this.client.emit('error', err)
} else {
this.emit('error', err)
}
}
this.emit('close')
this.client = null
this.files = []
this.discovery = null
this.store = null
this._rarityMap = null
this._peers = null
this._servers = null
this._xsRequests = null
}
addPeer (peer) {
if (this.destroyed) throw new Error('torrent is destroyed')
if (!this.infoHash) throw new Error('addPeer() must not be called before the `infoHash` event')
if (this.client.blocked) {
let host
if (typeof peer === 'string') {
let parts
try {
parts = addrToIPPort(peer)
} catch (e) {
this._debug('ignoring peer: invalid %s', peer)
this.emit('invalidPeer', peer)
return false
}
host = parts[0]
} else if (typeof peer.remoteAddress === 'string') {
host = peer.remoteAddress
}
if (host && this.client.blocked.contains(host)) {
this._debug('ignoring peer: blocked %s', peer)
if (typeof peer !== 'string') peer.destroy()
this.emit('blockedPeer', peer)
return false
}
}
// if the utp connection fails to connect, then it is replaced with a tcp connection to the same ip:port
const wasAdded = !!this._addPeer(peer, this.client.utp ? 'utp' : 'tcp')
if (wasAdded) {
this.emit('peer', peer)
} else {
this.emit('invalidPeer', peer)
}
return wasAdded
}
_addPeer (peer, type) {
if (this.destroyed) {
if (typeof peer !== 'string') peer.destroy()
return null
}
if (typeof peer === 'string' && !this._validAddr(peer)) {
this._debug('ignoring peer: invalid %s', peer)
return null
}
const id = (peer && peer.id) || peer
if (this._peers[id]) {
this._debug('ignoring peer: duplicate (%s)', id)
if (typeof peer !== 'string') peer.destroy()
return null
}
if (this.paused) {
this._debug('ignoring peer: torrent is paused')
if (typeof peer !== 'string') peer.destroy()
return null
}
this._debug('add peer %s', id)
let newPeer
if (typeof peer === 'string') {
// `peer` is an addr ("ip:port" string)
newPeer = type === 'utp' ? Peer.createUTPOutgoingPeer(peer, this) : Peer.createTCPOutgoingPeer(peer, this)
} else {
// `peer` is a WebRTC connection (simple-peer)
newPeer = Peer.createWebRTCPeer(peer, this)
}
this._peers[newPeer.id] = newPeer
this._peersLength += 1
if (typeof peer === 'string') {
// `peer` is an addr ("ip:port" string)
this._queue.push(newPeer)
this._drain()
}
return newPeer
}
addWebSeed (urlOrConn) {
if (this.destroyed) throw new Error('torrent is destroyed')
let id
let conn
if (typeof urlOrConn === 'string') {
id = urlOrConn
if (!/^https?:\/\/.+/.test(id)) {
this.emit('warning', new Error(`ignoring invalid web seed: ${id}`))
this.emit('invalidPeer', id)
return
}
if (this._peers[id]) {
this.emit('warning', new Error(`ignoring duplicate web seed: ${id}`))
this.emit('invalidPeer', id)
return
}
conn = new WebConn(id, this)
} else if (urlOrConn && typeof urlOrConn.connId === 'string') {
conn = urlOrConn
id = conn.connId
if (this._peers[id]) {
this.emit('warning', new Error(`ignoring duplicate web seed: ${id}`))
this.emit('invalidPeer', id)
return
}
} else {
this.emit('warning', new Error('addWebSeed must be passed a string or connection object with id property'))
return
}
this._debug('add web seed %s', id)
const newPeer = Peer.createWebSeedPeer(conn, id, this)
this._peers[newPeer.id] = newPeer
this._peersLength += 1
this.emit('peer', id)
}
/**
* Called whenever a new incoming TCP peer connects to this torrent swarm. Called with a
* peer that has already sent a handshake.
*/
_addIncomingPeer (peer) {
if (this.destroyed) return peer.destroy(new Error('torrent is destroyed'))
if (this.paused) return peer.destroy(new Error('torrent is paused'))
this._debug('add incoming peer %s', peer.id)
this._peers[peer.id] = peer
this._peersLength += 1
}
removePeer (peer) {
const id = (peer && peer.id) || peer
peer = this._peers[id]
if (!peer) return
this._debug('removePeer %s', id)
delete this._peers[id]
this._peersLength -= 1
peer.destroy()
// If torrent swarm was at capacity before, try to open a new connection now
this._drain()
}
select (start, end, priority, notify) {
if (this.destroyed) throw new Error('torrent is destroyed')
if (start < 0 || end < start || this.pieces.length <= end) {
throw new Error(`invalid selection ${start} : ${end}`)
}
priority = Number(priority) || 0
this._debug('select %s-%s (priority %s)', start, end, priority)
this._selections.push({
from: start,
to: end,
offset: 0,
priority,
notify: notify || noop
})
this._selections.sort((a, b) => b.priority - a.priority)
this._updateSelections()
}
deselect (start, end, priority) {
if (this.destroyed) throw new Error('torrent is destroyed')
priority = Number(priority) || 0
this._debug('deselect %s-%s (priority %s)', start, end, priority)
for (let i = 0; i < this._selections.length; ++i) {
const s = this._selections[i]
if (s.from === start && s.to === end && s.priority === priority) {
this._selections.splice(i, 1)
break
}
}
this._updateSelections()
}
critical (start, end) {
if (this.destroyed) throw new Error('torrent is destroyed')
this._debug('critical %s-%s', start, end)
for (let i = start; i <= end; ++i) {
this._critical[i] = true
}
this._updateSelections()
}
_onWire (wire, addr) {
this._debug('got wire %s (%s)', wire._debugId, addr || 'Unknown')
wire.on('download', downloaded => {
if (this.destroyed) return
this.received += downloaded
this._downloadSpeed(downloaded)
this.client._downloadSpeed(downloaded)
this.emit('download', downloaded)
if (this.destroyed) return
this.client.emit('download', downloaded)
})
wire.on('upload', uploaded => {
if (this.destroyed) return
this.uploaded += uploaded
this._uploadSpeed(uploaded)
this.client._uploadSpeed(uploaded)
this.emit('upload', uploaded)
if (this.destroyed) return
this.client.emit('upload', uploaded)
})
this.wires.push(wire)
if (addr) {
// Sometimes RTCPeerConnection.getStats() doesn't return an ip:port for peers
const parts = addrToIPPort(addr)
wire.remoteAddress = parts[0]
wire.remotePort = parts[1]
}
// When peer sends PORT message, add that DHT node to routing table
if (this.client.dht && this.client.dht.listening) {
wire.on('port', port => {
if (this.destroyed || this.client.dht.destroyed) {
return
}
if (!wire.remoteAddress) {
return this._debug('ignoring PORT from peer with no address')