-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.js
263 lines (225 loc) · 8.03 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
/*! ut_pex. MIT License. WebTorrent LLC <https://webtorrent.io/opensource> */
import { EventEmitter } from 'events'
import compact2string from 'compact2string'
import string2compact from 'string2compact'
import bencode from 'bencode'
const PEX_INTERVAL = 65000 // just over one minute
const PEX_MAX_PEERS = 50 // max number of peers to advertise per PEX message
const PEX_MIN_ALLOWED_INTERVAL = 60000 // should not receive messages below this interval
const FLAGS = {
prefersEncryption: 0x01,
isSender: 0x02,
supportsUtp: 0x04,
supportsUtHolepunch: 0x08,
isReachable: 0x10
}
export default () => {
class utPex extends EventEmitter {
constructor (wire) {
super()
this._wire = wire
this._intervalId = null
this._lastMessageTimestamp = 0
this.reset()
}
/**
* Start sending regular PEX updates to remote peer.
*/
start () {
clearInterval(this._intervalId)
this._intervalId = setInterval(() => this._sendMessage(), PEX_INTERVAL)
if (this._intervalId.unref) this._intervalId.unref()
}
/**
* Stop sending PEX updates to the remote peer.
*/
stop () {
clearInterval(this._intervalId)
this._intervalId = null
}
/**
* Stops sending updates to the remote peer and resets internal state of peers seen.
*/
reset () {
this._remoteAddedPeers = {}
this._remoteDroppedPeers = {}
this._localAddedPeers = {}
this._localDroppedPeers = {}
this.stop()
}
/**
* Adds a IPv4 peer to the locally discovered peer list for the next PEX message.
*/
addPeer (peer, flags = {}) {
this._addPeer(peer, this._encodeFlags(flags), 4)
}
/**
* Adds a IPv6 peer to the locally discovered peer list for the next PEX message.
*/
addPeer6 (peer, flags = {}) {
this._addPeer(peer, this._encodeFlags(flags), 6)
}
_addPeer (peer, flags, version) {
if (!peer.includes(':')) return // disregard invalid peers
if (peer in this._remoteAddedPeers) return // never advertise peer the remote wire already sent us
if (peer in this._localDroppedPeers) delete this._localDroppedPeers[peer]
this._localAddedPeers[peer] = { ip: version, flags }
}
/**
* Adds a IPv4 peer to the locally dropped peer list for the next PEX message.
*/
dropPeer (peer) {
this._dropPeer(peer, 4)
}
/**
* Adds a IPv6 peer to the locally dropped peer list for the next PEX message.
*/
dropPeer6 (peer) {
this._dropPeer(peer, 6)
}
_dropPeer (peer, version) {
if (!peer.includes(':')) return // disregard invalid peers
if (peer in this._remoteDroppedPeers) return // never advertise peer the remote wire already sent us
if (peer in this._localAddedPeers) delete this._localAddedPeers[peer]
this._localDroppedPeers[peer] = { ip: version }
}
onExtendedHandshake (handshake) {
if (!handshake.m || !handshake.m.ut_pex) {
return this.emit('warning', new Error('Peer does not support ut_pex'))
}
}
/**
* PEX messages are bencoded dictionaries with the following keys:
* 'added' : array of peers met since last PEX message
* 'added.f' : array of flags per peer
* 'dropped' : array of peers locally dropped from swarm since last PEX message
* 'added6' : ipv6 version of 'added'
* 'added6.f' : ipv6 version of 'added.f'
* 'dropped6' : ipv6 version of 'dropped'
*
* @param {Buffer} buf bencoded PEX dictionary
*/
onMessage (buf) {
// check message rate
const currentMessageTimestamp = Date.now()
if (currentMessageTimestamp - this._lastMessageTimestamp < PEX_MIN_ALLOWED_INTERVAL) {
this.reset()
this._wire.destroy()
return this.emit('warning', new Error('Peer disconnected for sending PEX messages too frequently'))
} else {
this._lastMessageTimestamp = currentMessageTimestamp
}
let message
try {
message = bencode.decode(buf)
if (message.added) {
compact2string.multi(Buffer.from(message.added)).forEach((peer, idx) => {
delete this._remoteDroppedPeers[peer]
if (!(peer in this._remoteAddedPeers)) {
const flags = message['added.f'][idx]
this._remoteAddedPeers[peer] = { ip: 4, flags }
this.emit('peer', peer, this._decodeFlags(flags))
}
})
}
if (message.added6) {
compact2string.multi6(Buffer.from(message.added6)).forEach((peer, idx) => {
delete this._remoteDroppedPeers[peer]
if (!(peer in this._remoteAddedPeers)) {
const flags = message['added6.f'][idx]
this._remoteAddedPeers[peer] = { ip: 6, flags }
this.emit('peer', peer, this._decodeFlags(flags))
}
})
}
if (message.dropped) {
compact2string.multi(Buffer.from(message.dropped)).forEach(peer => {
delete this._remoteAddedPeers[peer]
if (!(peer in this._remoteDroppedPeers)) {
this._remoteDroppedPeers[peer] = { ip: 4 }
this.emit('dropped', peer)
}
})
}
if (message.dropped6) {
compact2string.multi6(Buffer.from(message.dropped6)).forEach(peer => {
delete this._remoteAddedPeers[peer]
if (!(peer in this._remoteDroppedPeers)) {
this._remoteDroppedPeers[peer] = { ip: 6 }
this.emit('dropped', peer)
}
})
}
} catch (err) {
// drop invalid messages
}
}
/**
* Decode PEX bit-flags
* @param {Number} flags one byte number
* @returns {Object} based on boolean properties
*/
_decodeFlags (flags) {
return {
prefersEncryption: !!(flags & FLAGS.prefersEncryption),
isSender: !!(flags & FLAGS.isSender),
supportsUtp: !!(flags & FLAGS.supportsUtp),
supportsUtHolepunch: !!(flags & FLAGS.supportsUtHolepunch),
isReachable: !!(flags & FLAGS.isReachable)
}
}
/**
* Emcode PEX bit-flags
* @param {Object} flags based on boolean properties
* @returns {Number} one byte number
*/
_encodeFlags (flags) {
return Object.keys(flags).reduce((acc, cur) => (flags[cur] === true)
? acc | FLAGS[cur]
: acc, 0x00)
}
/**
* Sends a PEX message to the remote peer including information about any locally
* added / dropped peers.
*/
_sendMessage () {
const localAdded = Object.keys(this._localAddedPeers).slice(0, PEX_MAX_PEERS)
const localDropped = Object.keys(this._localDroppedPeers).slice(0, PEX_MAX_PEERS)
const _isIPv4 = (peers, addr) => peers[addr].ip === 4
const _isIPv6 = (peers, addr) => peers[addr].ip === 6
const _flags = (peers, addr) => peers[addr].flags
const added = string2compact(
localAdded.filter(k => _isIPv4(this._localAddedPeers, k))
)
const added6 = string2compact(
localAdded.filter(k => _isIPv6(this._localAddedPeers, k))
)
const dropped = string2compact(
localDropped.filter(k => _isIPv4(this._localDroppedPeers, k))
)
const dropped6 = string2compact(
localDropped.filter(k => _isIPv6(this._localDroppedPeers, k))
)
const addedFlags = Buffer.from(
localAdded.filter(k => _isIPv4(this._localAddedPeers, k)).map(k => _flags(this._localAddedPeers, k))
)
const added6Flags = Buffer.from(
localAdded.filter(k => _isIPv6(this._localAddedPeers, k)).map(k => _flags(this._localAddedPeers, k))
)
// update local deltas
localAdded.forEach(peer => delete this._localAddedPeers[peer])
localDropped.forEach(peer => delete this._localDroppedPeers[peer])
// send PEX message
this._wire.extended('ut_pex', {
added,
'added.f': addedFlags,
dropped,
added6,
'added6.f': added6Flags,
dropped6
})
}
}
utPex.prototype.name = 'ut_pex'
return utPex
}