-
-
Notifications
You must be signed in to change notification settings - Fork 71
/
index.js
1348 lines (1172 loc) · 40.5 KB
/
index.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
/*! bittorrent-protocol. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */
import bencode from 'bencode'
import BitField from 'bitfield'
import crypto from 'crypto'
import Debug from 'debug'
import RC4 from 'rc4'
import { Duplex } from 'streamx'
import { hash, concat, equal, hex2arr, arr2hex, text2arr, arr2text, randomBytes } from 'uint8-util'
import throughput from 'throughput'
import arrayRemove from 'unordered-array-remove'
const debug = Debug('bittorrent-protocol')
const BITFIELD_GROW = 400000
const KEEP_ALIVE_TIMEOUT = 55000
const ALLOWED_FAST_SET_MAX_LENGTH = 100
const MESSAGE_PROTOCOL = text2arr('\u0013BitTorrent protocol')
const MESSAGE_KEEP_ALIVE = new Uint8Array([0x00, 0x00, 0x00, 0x00])
const MESSAGE_CHOKE = new Uint8Array([0x00, 0x00, 0x00, 0x01, 0x00])
const MESSAGE_UNCHOKE = new Uint8Array([0x00, 0x00, 0x00, 0x01, 0x01])
const MESSAGE_INTERESTED = new Uint8Array([0x00, 0x00, 0x00, 0x01, 0x02])
const MESSAGE_UNINTERESTED = new Uint8Array([0x00, 0x00, 0x00, 0x01, 0x03])
const MESSAGE_RESERVED = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
const MESSAGE_PORT = [0x00, 0x00, 0x00, 0x03, 0x09, 0x00, 0x00]
// BEP6 Fast Extension
const MESSAGE_HAVE_ALL = new Uint8Array([0x00, 0x00, 0x00, 0x01, 0x0E])
const MESSAGE_HAVE_NONE = new Uint8Array([0x00, 0x00, 0x00, 0x01, 0x0F])
const DH_PRIME = 'ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a36210000000000090563'
const DH_GENERATOR = 2
const VC = new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
const CRYPTO_PROVIDE = new Uint8Array([0x00, 0x00, 0x01, 0x02])
const CRYPTO_SELECT = new Uint8Array([0x00, 0x00, 0x00, 0x02]) // always try to choose RC4 encryption instead of plaintext
function xor (a, b) {
for (let len = a.length; len--;) a[len] ^= b[len]
return a
}
class Request {
constructor (piece, offset, length, callback) {
this.piece = piece
this.offset = offset
this.length = length
this.callback = callback
}
}
class HaveAllBitField {
constructor () {
this.buffer = new Uint8Array() // dummy
}
get (index) {
return true
}
set (index) {}
}
class Wire extends Duplex {
constructor (type = null, retries = 0, peEnabled = false) {
super()
this._debugId = arr2hex(randomBytes(4))
this._debug('new wire')
this.peerId = null // remote peer id (hex string)
this.peerIdBuffer = null // remote peer id (buffer)
this.type = type // connection type ('webrtc', 'tcpIncoming', 'tcpOutgoing', 'webSeed')
this.amChoking = true // are we choking the peer?
this.amInterested = false // are we interested in the peer?
this.peerChoking = true // is the peer choking us?
this.peerInterested = false // is the peer interested in us?
// The largest torrent that I know of (the Geocities archive) is ~641 GB and has
// ~41,000 pieces. Therefore, cap bitfield to 10x larger (400,000 bits) to support all
// possible torrents but prevent malicious peers from growing bitfield to fill memory.
this.peerPieces = new BitField(0, { grow: BITFIELD_GROW })
this.extensions = {}
this.peerExtensions = {}
this.requests = [] // outgoing
this.peerRequests = [] // incoming
this.extendedMapping = {} // number -> string, ex: 1 -> 'ut_metadata'
this.peerExtendedMapping = {} // string -> number, ex: 9 -> 'ut_metadata'
// The extended handshake to send, minus the "m" field, which gets automatically
// filled from `this.extendedMapping`
this.extendedHandshake = {}
this.peerExtendedHandshake = {} // remote peer's extended handshake
// BEP6 Fast Estension
this.hasFast = false // is fast extension enabled?
this.allowedFastSet = [] // allowed fast set
this.peerAllowedFastSet = [] // peer's allowed fast set
this._ext = {} // string -> function, ex 'ut_metadata' -> ut_metadata()
this._nextExt = 1
this.uploaded = 0
this.downloaded = 0
this.uploadSpeed = throughput()
this.downloadSpeed = throughput()
this._keepAliveInterval = null
this._timeout = null
this._timeoutMs = 0
this._timeoutExpiresAt = null
this._finished = false
this._parserSize = 0 // number of needed bytes to parse next message from remote peer
this._parser = null // function to call once `this._parserSize` bytes are available
this._buffer = [] // incomplete message data
this._bufferSize = 0 // cached total length of buffers in `this._buffer`
this._peEnabled = peEnabled
if (peEnabled) {
this._dh = crypto.createDiffieHellman(DH_PRIME, 'hex', DH_GENERATOR) // crypto object used to generate keys/secret
this._myPubKey = this._dh.generateKeys('hex') // my DH public key
} else {
this._myPubKey = null
}
this._peerPubKey = null // peer's DH public key
this._sharedSecret = null // shared DH secret
this._peerCryptoProvide = [] // encryption methods provided by peer; we expect this to always contain 0x02
this._cryptoHandshakeDone = false
this._cryptoSyncPattern = null // the pattern to search for when resynchronizing after receiving pe1/pe2
this._waitMaxBytes = null // the maximum number of bytes resynchronization must occur within
this._encryptionMethod = null // 1 for plaintext, 2 for RC4
this._encryptGenerator = null // RC4 keystream generator for encryption
this._decryptGenerator = null // RC4 keystream generator for decryption
this._setGenerators = false // a flag for whether setEncrypt() has successfully completed
this.once('finish', () => this._onFinish())
this.on('finish', this._onFinish)
this._debug('type:', this.type)
if (this.type === 'tcpIncoming' && this._peEnabled) {
// If we are not the initiator, we should wait to see if the client begins
// with PE/MSE handshake or the standard bittorrent handshake.
this._determineHandshakeType()
} else if (this.type === 'tcpOutgoing' && this._peEnabled && retries === 0) {
this._parsePe2()
} else {
this._parseHandshake(null)
}
}
/**
* Set whether to send a "keep-alive" ping (sent every 55s)
* @param {boolean} enable
*/
setKeepAlive (enable) {
this._debug('setKeepAlive %s', enable)
clearInterval(this._keepAliveInterval)
if (enable === false) return
this._keepAliveInterval = setInterval(() => {
this.keepAlive()
}, KEEP_ALIVE_TIMEOUT)
}
/**
* Set the amount of time to wait before considering a request to be "timed out"
* @param {number} ms
* @param {boolean=} unref (should the timer be unref'd? default: false)
*/
setTimeout (ms, unref) {
this._debug('setTimeout ms=%d unref=%s', ms, unref)
this._timeoutMs = ms
this._timeoutUnref = !!unref
this._resetTimeout(true)
}
destroy () {
if (this.destroyed) return
this._debug('destroy')
this.end()
return this
}
end (data) {
if (this.destroyed || this.destroying) return
this._debug('end')
this._onUninterested()
this._onChoke()
return super.end(data)
}
/**
* Use the specified protocol extension.
* @param {function} Extension
*/
use (Extension) {
const name = Extension.prototype.name
if (!name) {
throw new Error('Extension class requires a "name" property on the prototype')
}
this._debug('use extension.name=%s', name)
const ext = this._nextExt
const handler = new Extension(this)
function noop () {}
if (typeof handler.onHandshake !== 'function') {
handler.onHandshake = noop
}
if (typeof handler.onExtendedHandshake !== 'function') {
handler.onExtendedHandshake = noop
}
if (typeof handler.onMessage !== 'function') {
handler.onMessage = noop
}
this.extendedMapping[ext] = name
this._ext[name] = handler
this[name] = handler
this._nextExt += 1
}
//
// OUTGOING MESSAGES
//
/**
* Message "keep-alive": <len=0000>
*/
keepAlive () {
this._debug('keep-alive')
this._push(MESSAGE_KEEP_ALIVE)
}
sendPe1 () {
if (this._peEnabled) {
const padALen = Math.floor(Math.random() * 513)
const padA = randomBytes(padALen)
this._push(concat([hex2arr(this._myPubKey), padA]))
}
}
sendPe2 () {
const padBLen = Math.floor(Math.random() * 513)
const padB = randomBytes(padBLen)
this._push(concat([hex2arr(this._myPubKey), padB]))
}
async sendPe3 (infoHash) {
await this.setEncrypt(this._sharedSecret, infoHash)
const hash1Buffer = await hash(hex2arr(this._utfToHex('req1') + this._sharedSecret))
const hash2Buffer = await hash(hex2arr(this._utfToHex('req2') + infoHash))
const hash3Buffer = await hash(hex2arr(this._utfToHex('req3') + this._sharedSecret))
const hashesXorBuffer = xor(hash2Buffer, hash3Buffer)
const padCLen = new DataView(randomBytes(2).buffer).getUint16(0) % 512
const padCBuffer = randomBytes(padCLen)
let vcAndProvideBuffer = new Uint8Array(8 + 4 + 2 + padCLen + 2)
vcAndProvideBuffer.set(VC)
vcAndProvideBuffer.set(CRYPTO_PROVIDE, 8)
const view = new DataView(vcAndProvideBuffer.buffer)
view.setInt16(12, padCLen) // pad C length
padCBuffer.copy(vcAndProvideBuffer, 14)
view.setInt16(14 + padCLen, 0) // IA length
vcAndProvideBuffer = this._encryptHandshake(vcAndProvideBuffer)
this._push(concat([hash1Buffer, hashesXorBuffer, vcAndProvideBuffer]))
}
async sendPe4 (infoHash) {
await this.setEncrypt(this._sharedSecret, infoHash)
const padDLen = new DataView(randomBytes(2).buffer).getUint16(0) % 512
const padDBuffer = randomBytes(padDLen)
let vcAndSelectBuffer = new Uint8Array(8 + 4 + 2 + padDLen)
const view = new DataView(vcAndSelectBuffer.buffer)
vcAndSelectBuffer.set(VC)
vcAndSelectBuffer.set(CRYPTO_SELECT, 8)
view.setInt16(12, padDLen) // lenD?
vcAndSelectBuffer.set(padDBuffer, 14)
vcAndSelectBuffer = this._encryptHandshake(vcAndSelectBuffer)
this._push(vcAndSelectBuffer)
this._cryptoHandshakeDone = true
this._debug('completed crypto handshake')
}
/**
* Message: "handshake" <pstrlen><pstr><reserved><info_hash><peer_id>
* @param {Uint8Array|string} infoHash (as Buffer or *hex* string)
* @param {Uint8Array|string} peerId
* @param {Object} extensions
*/
handshake (infoHash, peerId, extensions) {
let infoHashBuffer
let peerIdBuffer
if (typeof infoHash === 'string') {
infoHash = infoHash.toLowerCase()
infoHashBuffer = hex2arr(infoHash)
} else {
infoHashBuffer = infoHash
infoHash = arr2hex(infoHashBuffer)
}
if (typeof peerId === 'string') {
peerIdBuffer = hex2arr(peerId)
} else {
peerIdBuffer = peerId
peerId = arr2hex(peerIdBuffer)
}
this._infoHash = infoHashBuffer
if (infoHashBuffer.length !== 20 || peerIdBuffer.length !== 20) {
throw new Error('infoHash and peerId MUST have length 20')
}
this._debug('handshake i=%s p=%s exts=%o', infoHash, peerId, extensions)
const reserved = new Uint8Array(MESSAGE_RESERVED)
this.extensions = {
extended: true,
dht: !!(extensions && extensions.dht),
fast: !!(extensions && extensions.fast)
}
reserved[5] |= 0x10 // enable extended message
if (this.extensions.dht) reserved[7] |= 0x01
if (this.extensions.fast) reserved[7] |= 0x04
// BEP6 Fast Extension: The extension is enabled only if both ends of the connection set this bit.
if (this.extensions.fast && this.peerExtensions.fast) {
this._debug('fast extension is enabled')
this.hasFast = true
}
this._push(concat([MESSAGE_PROTOCOL, reserved, infoHashBuffer, peerIdBuffer]))
this._handshakeSent = true
if (this.peerExtensions.extended && !this._extendedHandshakeSent) {
// Peer's handshake indicated support already
// (incoming connection)
this._sendExtendedHandshake()
}
}
/* Peer supports BEP-0010, send extended handshake.
*
* This comes after the 'handshake' event to give the user a chance to populate
* `this.extendedHandshake` and `this.extendedMapping` before the extended handshake
* is sent to the remote peer.
*/
_sendExtendedHandshake () {
// Create extended message object from registered extensions
const msg = Object.assign({}, this.extendedHandshake)
msg.m = {}
for (const ext in this.extendedMapping) {
const name = this.extendedMapping[ext]
msg.m[name] = Number(ext)
}
// Send extended handshake
this.extended(0, bencode.encode(msg))
this._extendedHandshakeSent = true
}
/**
* Message "choke": <len=0001><id=0>
*/
choke () {
if (this.amChoking) return
this.amChoking = true
this._debug('choke')
this._push(MESSAGE_CHOKE)
if (this.hasFast) {
// BEP6: If a peer sends a choke, it MUST reject all requests from the peer to whom the choke
// was sent except it SHOULD NOT reject requests for pieces that are in the allowed fast set.
let allowedCount = 0
while (this.peerRequests.length > allowedCount) { // until only allowed requests are left
const request = this.peerRequests[allowedCount] // first non-allowed request
if (this.allowedFastSet.includes(request.piece)) {
++allowedCount // count request as allowed
} else {
this.reject(request.piece, request.offset, request.length) // removes from this.peerRequests
}
}
} else {
while (this.peerRequests.length) {
this.peerRequests.pop()
}
}
}
/**
* Message "unchoke": <len=0001><id=1>
*/
unchoke () {
if (!this.amChoking) return
this.amChoking = false
this._debug('unchoke')
this._push(MESSAGE_UNCHOKE)
}
/**
* Message "interested": <len=0001><id=2>
*/
interested () {
if (this.amInterested) return
this.amInterested = true
this._debug('interested')
this._push(MESSAGE_INTERESTED)
}
/**
* Message "uninterested": <len=0001><id=3>
*/
uninterested () {
if (!this.amInterested) return
this.amInterested = false
this._debug('uninterested')
this._push(MESSAGE_UNINTERESTED)
}
/**
* Message "have": <len=0005><id=4><piece index>
* @param {number} index
*/
have (index) {
this._debug('have %d', index)
this._message(4, [index], null)
}
/**
* Message "bitfield": <len=0001+X><id=5><bitfield>
* @param {BitField|Buffer} bitfield
*/
bitfield (bitfield) {
this._debug('bitfield')
if (!ArrayBuffer.isView(bitfield)) bitfield = bitfield.buffer
this._message(5, [], bitfield)
}
/**
* Message "request": <len=0013><id=6><index><begin><length>
* @param {number} index
* @param {number} offset
* @param {number} length
* @param {function} cb
*/
request (index, offset, length, cb) {
if (!cb) cb = () => {}
if (this._finished) return cb(new Error('wire is closed'))
if (this.peerChoking && !(this.hasFast && this.peerAllowedFastSet.includes(index))) {
return cb(new Error('peer is choking'))
}
this._debug('request index=%d offset=%d length=%d', index, offset, length)
this.requests.push(new Request(index, offset, length, cb))
if (!this._timeout) {
this._resetTimeout(true)
}
this._message(6, [index, offset, length], null)
}
/**
* Message "piece": <len=0009+X><id=7><index><begin><block>
* @param {number} index
* @param {number} offset
* @param {Uint8Array} buffer
*/
piece (index, offset, buffer) {
this._debug('piece index=%d offset=%d', index, offset)
this._message(7, [index, offset], buffer)
this.uploaded += buffer.length
this.uploadSpeed(buffer.length)
this.emit('upload', buffer.length)
}
/**
* Message "cancel": <len=0013><id=8><index><begin><length>
* @param {number} index
* @param {number} offset
* @param {number} length
*/
cancel (index, offset, length) {
this._debug('cancel index=%d offset=%d length=%d', index, offset, length)
this._callback(
this._pull(this.requests, index, offset, length),
new Error('request was cancelled'),
null
)
this._message(8, [index, offset, length], null)
}
/**
* Message: "port" <len=0003><id=9><listen-port>
* @param {Number} port
*/
port (port) {
this._debug('port %d', port)
const message = new Uint8Array(MESSAGE_PORT)
const view = new DataView(message.buffer)
view.setUint16(5, port)
this._push(message)
}
/**
* Message: "suggest" <len=0x0005><id=0x0D><piece index> (BEP6)
* @param {number} index
*/
suggest (index) {
if (!this.hasFast) throw Error('fast extension is disabled')
this._debug('suggest %d', index)
this._message(0x0D, [index], null)
}
/**
* Message: "have-all" <len=0x0001><id=0x0E> (BEP6)
*/
haveAll () {
if (!this.hasFast) throw Error('fast extension is disabled')
this._debug('have-all')
this._push(MESSAGE_HAVE_ALL)
}
/**
* Message: "have-none" <len=0x0001><id=0x0F> (BEP6)
*/
haveNone () {
if (!this.hasFast) throw Error('fast extension is disabled')
this._debug('have-none')
this._push(MESSAGE_HAVE_NONE)
}
/**
* Message "reject": <len=0x000D><id=0x10><index><offset><length> (BEP6)
* @param {number} index
* @param {number} offset
* @param {number} length
*/
reject (index, offset, length) {
if (!this.hasFast) throw Error('fast extension is disabled')
this._debug('reject index=%d offset=%d length=%d', index, offset, length)
this._pull(this.peerRequests, index, offset, length)
this._message(0x10, [index, offset, length], null)
}
/**
* Message: "allowed-fast" <len=0x0005><id=0x11><piece index> (BEP6)
* @param {number} index
*/
allowedFast (index) {
if (!this.hasFast) throw Error('fast extension is disabled')
this._debug('allowed-fast %d', index)
if (!this.allowedFastSet.includes(index)) this.allowedFastSet.push(index)
this._message(0x11, [index], null)
}
/**
* Message: "extended" <len=0005+X><id=20><ext-number><payload>
* @param {number|string} ext
* @param {Object} obj
*/
extended (ext, obj) {
this._debug('extended ext=%s', ext)
if (typeof ext === 'string' && this.peerExtendedMapping[ext]) {
ext = this.peerExtendedMapping[ext]
}
if (typeof ext === 'number') {
const extId = new Uint8Array([ext])
const buf = ArrayBuffer.isView(obj) ? obj : bencode.encode(obj)
this._message(20, [], concat([extId, buf]))
} else {
throw new Error(`Unrecognized extension: ${ext}`)
}
}
/**
* Sets the encryption method for this wire, as per PSE/ME specification
*
* @param {string} sharedSecret: A hex-encoded string, which is the shared secret agreed
* upon from DH key exchange
* @param {string} infoHash: A hex-encoded info hash
* @returns boolean, true if encryption setting succeeds, false if it fails.
*/
async setEncrypt (sharedSecret, infoHash) {
let encryptKeyBuf
let encryptKeyIntArray
let decryptKeyBuf
let decryptKeyIntArray
switch (this.type) {
case 'tcpIncoming':
encryptKeyBuf = await hash(hex2arr(this._utfToHex('keyB') + sharedSecret + infoHash))
decryptKeyBuf = await hash(hex2arr(this._utfToHex('keyA') + sharedSecret + infoHash))
encryptKeyIntArray = []
for (const value of encryptKeyBuf.values()) {
encryptKeyIntArray.push(value)
}
decryptKeyIntArray = []
for (const value of decryptKeyBuf.values()) {
decryptKeyIntArray.push(value)
}
this._encryptGenerator = new RC4(encryptKeyIntArray)
this._decryptGenerator = new RC4(decryptKeyIntArray)
break
case 'tcpOutgoing':
encryptKeyBuf = await hash(hex2arr(this._utfToHex('keyA') + sharedSecret + infoHash))
decryptKeyBuf = await hash(hex2arr(this._utfToHex('keyB') + sharedSecret + infoHash))
encryptKeyIntArray = []
for (const value of encryptKeyBuf.values()) {
encryptKeyIntArray.push(value)
}
decryptKeyIntArray = []
for (const value of decryptKeyBuf.values()) {
decryptKeyIntArray.push(value)
}
this._encryptGenerator = new RC4(encryptKeyIntArray)
this._decryptGenerator = new RC4(decryptKeyIntArray)
break
default:
return false
}
// Discard the first 1024 bytes, as per MSE/PE implementation
for (let i = 0; i < 1024; i++) {
this._encryptGenerator.randomByte()
this._decryptGenerator.randomByte()
}
this._setGenerators = true
return true
}
/**
* Send a message to the remote peer.
*/
_message (id, numbers, data) {
const dataLength = data ? data.length : 0
const buffer = new Uint8Array(5 + (4 * numbers.length))
const view = new DataView(buffer.buffer)
view.setUint32(0, buffer.length + dataLength - 4)
buffer[4] = id
for (let i = 0; i < numbers.length; i++) {
view.setUint32(5 + (4 * i), numbers[i])
}
this._push(buffer)
if (data) this._push(data)
}
_push (data) {
if (this._finished) return
if (this._encryptionMethod === 2 && this._cryptoHandshakeDone) {
data = this._encrypt(data)
}
return this.push(data)
}
//
// INCOMING MESSAGES
//
_onKeepAlive () {
this._debug('got keep-alive')
this.emit('keep-alive')
}
_onPe1 (pubKeyBuffer) {
this._peerPubKey = arr2hex(pubKeyBuffer)
this._sharedSecret = this._dh.computeSecret(this._peerPubKey, 'hex', 'hex')
this.emit('pe1')
}
_onPe2 (pubKeyBuffer) {
this._peerPubKey = arr2hex(pubKeyBuffer)
this._sharedSecret = this._dh.computeSecret(this._peerPubKey, 'hex', 'hex')
this.emit('pe2')
}
async _onPe3 (hashesXorBuffer) {
const hash3 = await (arr2hex(this._utfToHex('req3') + this._sharedSecret))
const sKeyHash = arr2hex(xor(hash3, hashesXorBuffer))
this.emit('pe3', sKeyHash)
}
_onPe3Encrypted (vcBuffer, peerProvideBuffer) {
if (!equal(vcBuffer, VC)) {
this._debug('Error: verification constant did not match')
this.destroy()
return
}
for (const provideByte of peerProvideBuffer.values()) {
if (provideByte !== 0) {
this._peerCryptoProvide.push(provideByte)
}
}
if (this._peerCryptoProvide.includes(2)) {
this._encryptionMethod = 2
} else {
this._debug('Error: RC4 encryption method not provided by peer')
this.destroy()
}
}
_onPe4 (peerSelectBuffer) {
this._encryptionMethod = peerSelectBuffer[3]
if (!CRYPTO_PROVIDE.includes(this._encryptionMethod)) {
this._debug('Error: peer selected invalid crypto method')
this.destroy()
}
this._cryptoHandshakeDone = true
this._debug('crypto handshake done')
this.emit('pe4')
}
_onHandshake (infoHashBuffer, peerIdBuffer, extensions) {
const infoHash = arr2hex(infoHashBuffer)
const peerId = arr2hex(peerIdBuffer)
this._debug('got handshake i=%s p=%s exts=%o', infoHash, peerId, extensions)
this.peerId = peerId
this.peerIdBuffer = peerIdBuffer
this.peerExtensions = extensions
// BEP6 Fast Extension: The extension is enabled only if both ends of the connection set this bit.
if (this.extensions.fast && this.peerExtensions.fast) {
this._debug('fast extension is enabled')
this.hasFast = true
}
this.emit('handshake', infoHash, peerId, extensions)
for (const name in this._ext) {
this._ext[name].onHandshake(infoHash, peerId, extensions)
}
if (extensions.extended && this._handshakeSent &&
!this._extendedHandshakeSent) {
// outgoing connection
this._sendExtendedHandshake()
}
}
_onChoke () {
this.peerChoking = true
this._debug('got choke')
this.emit('choke')
if (!this.hasFast) {
// BEP6 Fast Extension: Choke no longer implicitly rejects all pending requests
while (this.requests.length) {
this._callback(this.requests.pop(), new Error('peer is choking'), null)
}
}
}
_onUnchoke () {
this.peerChoking = false
this._debug('got unchoke')
this.emit('unchoke')
}
_onInterested () {
this.peerInterested = true
this._debug('got interested')
this.emit('interested')
}
_onUninterested () {
this.peerInterested = false
this._debug('got uninterested')
this.emit('uninterested')
}
_onHave (index) {
if (this.peerPieces.get(index)) return
this._debug('got have %d', index)
this.peerPieces.set(index, true)
this.emit('have', index)
}
_onBitField (buffer) {
this.peerPieces = new BitField(buffer)
this._debug('got bitfield')
this.emit('bitfield', this.peerPieces)
}
_onRequest (index, offset, length) {
if (this.amChoking && !(this.hasFast && this.allowedFastSet.includes(index))) {
// BEP6: If a peer receives a request from a peer its choking, the peer receiving
// the request SHOULD send a reject unless the piece is in the allowed fast set.
if (this.hasFast) this.reject(index, offset, length)
return
}
this._debug('got request index=%d offset=%d length=%d', index, offset, length)
const respond = (err, buffer) => {
if (request !== this._pull(this.peerRequests, index, offset, length)) return
if (err) {
this._debug('error satisfying request index=%d offset=%d length=%d (%s)', index, offset, length, err.message)
if (this.hasFast) this.reject(index, offset, length)
return
}
this.piece(index, offset, buffer)
}
const request = new Request(index, offset, length, respond)
this.peerRequests.push(request)
this.emit('request', index, offset, length, respond)
}
_onPiece (index, offset, buffer) {
this._debug('got piece index=%d offset=%d', index, offset)
this._callback(this._pull(this.requests, index, offset, buffer.length), null, buffer)
this.downloaded += buffer.length
this.downloadSpeed(buffer.length)
this.emit('download', buffer.length)
this.emit('piece', index, offset, buffer)
}
_onCancel (index, offset, length) {
this._debug('got cancel index=%d offset=%d length=%d', index, offset, length)
this._pull(this.peerRequests, index, offset, length)
this.emit('cancel', index, offset, length)
}
_onPort (port) {
this._debug('got port %d', port)
this.emit('port', port)
}
_onSuggest (index) {
if (!this.hasFast) {
// BEP6: the peer MUST close the connection
this._debug('Error: got suggest whereas fast extension is disabled')
this.destroy()
return
}
this._debug('got suggest %d', index)
this.emit('suggest', index)
}
_onHaveAll () {
if (!this.hasFast) {
// BEP6: the peer MUST close the connection
this._debug('Error: got have-all whereas fast extension is disabled')
this.destroy()
return
}
this._debug('got have-all')
this.peerPieces = new HaveAllBitField()
this.emit('have-all')
}
_onHaveNone () {
if (!this.hasFast) {
// BEP6: the peer MUST close the connection
this._debug('Error: got have-none whereas fast extension is disabled')
this.destroy()
return
}
this._debug('got have-none')
this.emit('have-none')
}
_onReject (index, offset, length) {
if (!this.hasFast) {
// BEP6: the peer MUST close the connection
this._debug('Error: got reject whereas fast extension is disabled')
this.destroy()
return
}
this._debug('got reject index=%d offset=%d length=%d', index, offset, length)
this._callback(
this._pull(this.requests, index, offset, length),
new Error('request was rejected'),
null
)
this.emit('reject', index, offset, length)
}
_onAllowedFast (index) {
if (!this.hasFast) {
// BEP6: the peer MUST close the connection
this._debug('Error: got allowed-fast whereas fast extension is disabled')
this.destroy()
return
}
this._debug('got allowed-fast %d', index)
if (!this.peerAllowedFastSet.includes(index)) this.peerAllowedFastSet.push(index)
if (this.peerAllowedFastSet.length > ALLOWED_FAST_SET_MAX_LENGTH) this.peerAllowedFastSet.shift()
this.emit('allowed-fast', index)
}
_onExtended (ext, buf) {
if (ext === 0) {
let info
try {
info = bencode.decode(buf)
} catch (err) {
this._debug('ignoring invalid extended handshake: %s', err.message || err)
}
if (!info) return
this.peerExtendedHandshake = info
if (typeof info.m === 'object') {
for (const name in info.m) {
this.peerExtendedMapping[name] = Number(info.m[name].toString())
}
}
for (const name in this._ext) {
if (this.peerExtendedMapping[name]) {
this._ext[name].onExtendedHandshake(this.peerExtendedHandshake)
}
}
this._debug('got extended handshake')
this.emit('extended', 'handshake', this.peerExtendedHandshake)
} else {
if (this.extendedMapping[ext]) {
ext = this.extendedMapping[ext] // friendly name for extension
if (this._ext[ext]) {
// there is an registered extension handler, so call it
this._ext[ext].onMessage(buf)
}
}
this._debug('got extended message ext=%s', ext)
this.emit('extended', ext, buf)
}
}
_onTimeout () {
this._debug('request timed out')
this._callback(this.requests.shift(), new Error('request has timed out'), null)
this.emit('timeout')
}
/**
* Duplex stream method. Called whenever the remote peer has data for us. Data that the
* remote peer sends gets buffered (i.e. not actually processed) until the right number
* of bytes have arrived, determined by the last call to `this._parse(number, callback)`.
* Once enough bytes have arrived to process the message, the callback function
* (i.e. `this._parser`) gets called with the full buffer of data.
* @param {Uint8Array} data
* @param {function} cb
*/
_write (data, cb) {
if (this._encryptionMethod === 2 && this._cryptoHandshakeDone) {
data = this._decrypt(data)
}
this._bufferSize += data.length
this._buffer.push(data)
if (this._buffer.length > 1) {
this._buffer = [concat(this._buffer, this._bufferSize)]
}
// now this._buffer is an array containing a single Buffer
if (this._cryptoSyncPattern) {
const index = this._buffer[0].indexOf(this._cryptoSyncPattern)
if (index !== -1) {
this._buffer[0] = this._buffer[0].slice(index + this._cryptoSyncPattern.length)
this._bufferSize -= (index + this._cryptoSyncPattern.length)
this._cryptoSyncPattern = null
} else if (this._bufferSize + data.length > this._waitMaxBytes + this._cryptoSyncPattern.length) {
this._debug('Error: could not resynchronize')
this.destroy()
return
}
}
while (this._bufferSize >= this._parserSize && !this._cryptoSyncPattern) {
if (this._parserSize === 0) {
this._parser(new Uint8Array())
} else {
const buffer = this._buffer[0]
// console.log('buffer:', this._buffer)
this._bufferSize -= this._parserSize
this._buffer = this._bufferSize