-
Notifications
You must be signed in to change notification settings - Fork 451
/
upgrader.ts
630 lines (529 loc) · 19.8 KB
/
upgrader.ts
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
import { logger } from '@libp2p/logger'
import errCode from 'err-code'
import { Dialer, Listener } from '@libp2p/multistream-select'
import { pipe } from 'it-pipe'
// @ts-expect-error mutable-proxy does not export types
import mutableProxy from 'mutable-proxy'
import { codes } from './errors.js'
import { createConnection } from '@libp2p/connection'
import { CustomEvent, EventEmitter } from '@libp2p/interfaces/events'
import { peerIdFromString } from '@libp2p/peer-id'
import type { MultiaddrConnection, Connection, Stream } from '@libp2p/interface-connection'
import type { ConnectionEncrypter, SecuredConnection } from '@libp2p/interface-connection-encrypter'
import type { StreamMuxer, StreamMuxerFactory } from '@libp2p/interface-stream-muxer'
import type { PeerId } from '@libp2p/interface-peer-id'
import type { Upgrader, UpgraderEvents } from '@libp2p/interface-transport'
import type { Duplex } from 'it-stream-types'
import { Components, isInitializable } from '@libp2p/components'
import type { AbortOptions } from '@libp2p/interfaces'
import type { Registrar } from '@libp2p/interface-registrar'
import { DEFAULT_MAX_INBOUND_STREAMS, DEFAULT_MAX_OUTBOUND_STREAMS } from './registrar.js'
import { TimeoutController } from 'timeout-abort-controller'
import { abortableDuplex } from 'abortable-iterator'
import { setMaxListeners } from 'events'
const log = logger('libp2p:upgrader')
interface CreateConectionOptions {
cryptoProtocol: string
direction: 'inbound' | 'outbound'
maConn: MultiaddrConnection
upgradedConn: Duplex<Uint8Array>
remotePeer: PeerId
muxerFactory?: StreamMuxerFactory
}
interface OnStreamOptions {
connection: Connection
stream: Stream
protocol: string
}
export interface CryptoResult extends SecuredConnection {
protocol: string
}
export interface UpgraderInit {
connectionEncryption: ConnectionEncrypter[]
muxers: StreamMuxerFactory[]
/**
* An amount of ms by which an inbound connection upgrade
* must complete
*/
inboundUpgradeTimeout: number
}
function findIncomingStreamLimit (protocol: string, registrar: Registrar) {
try {
const { options } = registrar.getHandler(protocol)
return options.maxInboundStreams
} catch (err: any) {
if (err.code !== codes.ERR_NO_HANDLER_FOR_PROTOCOL) {
throw err
}
}
return DEFAULT_MAX_INBOUND_STREAMS
}
function findOutgoingStreamLimit (protocol: string, registrar: Registrar) {
try {
const { options } = registrar.getHandler(protocol)
return options.maxOutboundStreams
} catch (err: any) {
if (err.code !== codes.ERR_NO_HANDLER_FOR_PROTOCOL) {
throw err
}
}
return DEFAULT_MAX_OUTBOUND_STREAMS
}
function countStreams (protocol: string, direction: 'inbound' | 'outbound', connection: Connection) {
let streamCount = 0
connection.streams.forEach(stream => {
if (stream.stat.direction === direction && stream.stat.protocol === protocol) {
streamCount++
}
})
return streamCount
}
export class DefaultUpgrader extends EventEmitter<UpgraderEvents> implements Upgrader {
private readonly components: Components
private readonly connectionEncryption: Map<string, ConnectionEncrypter>
private readonly muxers: Map<string, StreamMuxerFactory>
private readonly inboundUpgradeTimeout: number
constructor (components: Components, init: UpgraderInit) {
super()
this.components = components
this.connectionEncryption = new Map()
init.connectionEncryption.forEach(encrypter => {
this.connectionEncryption.set(encrypter.protocol, encrypter)
})
this.muxers = new Map()
init.muxers.forEach(muxer => {
this.muxers.set(muxer.protocol, muxer)
})
this.inboundUpgradeTimeout = init.inboundUpgradeTimeout
}
/**
* Upgrades an inbound connection
*/
async upgradeInbound (maConn: MultiaddrConnection): Promise<Connection> {
let encryptedConn
let remotePeer
let upgradedConn: Duplex<Uint8Array>
let muxerFactory: StreamMuxerFactory | undefined
let cryptoProtocol
let setPeer
let proxyPeer
const metrics = this.components.getMetrics()
const timeoutController = new TimeoutController(this.inboundUpgradeTimeout)
try {
// fails on node < 15.4
setMaxListeners?.(Infinity, timeoutController.signal)
} catch {}
try {
const abortableStream = abortableDuplex(maConn, timeoutController.signal)
maConn.source = abortableStream.source
maConn.sink = abortableStream.sink
if (await this.components.getConnectionGater().denyInboundConnection(maConn)) {
throw errCode(new Error('The multiaddr connection is blocked by gater.acceptConnection'), codes.ERR_CONNECTION_INTERCEPTED)
}
if (metrics != null) {
({ setTarget: setPeer, proxy: proxyPeer } = mutableProxy())
const idString = `${(Math.random() * 1e9).toString(36)}${Date.now()}`
setPeer({ toString: () => idString })
maConn = metrics.trackStream({ stream: maConn, remotePeer: proxyPeer })
}
log('starting the inbound connection upgrade')
// Protect
let protectedConn = maConn
const protector = this.components.getConnectionProtector()
if (protector != null) {
log('protecting the inbound connection')
protectedConn = await protector.protect(maConn)
}
try {
// Encrypt the connection
({
conn: encryptedConn,
remotePeer,
protocol: cryptoProtocol
} = await this._encryptInbound(protectedConn))
if (await this.components.getConnectionGater().denyInboundEncryptedConnection(remotePeer, {
...protectedConn,
...encryptedConn
})) {
throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)
}
// Multiplex the connection
if (this.muxers.size > 0) {
const multiplexed = await this._multiplexInbound({
...protectedConn,
...encryptedConn
}, this.muxers)
muxerFactory = multiplexed.muxerFactory
upgradedConn = multiplexed.stream
} else {
upgradedConn = encryptedConn
}
} catch (err: any) {
log.error('Failed to upgrade inbound connection', err)
await maConn.close(err)
throw err
}
if (await this.components.getConnectionGater().denyInboundUpgradedConnection(remotePeer, {
...protectedConn,
...encryptedConn
})) {
throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)
}
if (metrics != null) {
metrics.updatePlaceholder(proxyPeer, remotePeer)
setPeer(remotePeer)
}
log('Successfully upgraded inbound connection')
return this._createConnection({
cryptoProtocol,
direction: 'inbound',
maConn,
upgradedConn,
muxerFactory,
remotePeer
})
} finally {
timeoutController.clear()
}
}
/**
* Upgrades an outbound connection
*/
async upgradeOutbound (maConn: MultiaddrConnection): Promise<Connection> {
const idStr = maConn.remoteAddr.getPeerId()
if (idStr == null) {
throw errCode(new Error('outbound connection must have a peer id'), codes.ERR_INVALID_MULTIADDR)
}
const remotePeerId = peerIdFromString(idStr)
if (await this.components.getConnectionGater().denyOutboundConnection(remotePeerId, maConn)) {
throw errCode(new Error('The multiaddr connection is blocked by connectionGater.denyOutboundConnection'), codes.ERR_CONNECTION_INTERCEPTED)
}
let encryptedConn
let remotePeer
let upgradedConn
let cryptoProtocol
let muxerFactory
let setPeer
let proxyPeer
const metrics = this.components.getMetrics()
if (metrics != null) {
({ setTarget: setPeer, proxy: proxyPeer } = mutableProxy())
const idString = `${(Math.random() * 1e9).toString(36)}${Date.now()}`
setPeer({ toB58String: () => idString })
maConn = metrics.trackStream({ stream: maConn, remotePeer: proxyPeer })
}
log('Starting the outbound connection upgrade')
// Protect
let protectedConn = maConn
const protector = this.components.getConnectionProtector()
if (protector != null) {
protectedConn = await protector.protect(maConn)
}
try {
// Encrypt the connection
({
conn: encryptedConn,
remotePeer,
protocol: cryptoProtocol
} = await this._encryptOutbound(protectedConn, remotePeerId))
if (await this.components.getConnectionGater().denyOutboundEncryptedConnection(remotePeer, {
...protectedConn,
...encryptedConn
})) {
throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)
}
// Multiplex the connection
if (this.muxers.size > 0) {
const multiplexed = await this._multiplexOutbound({
...protectedConn,
...encryptedConn
}, this.muxers)
muxerFactory = multiplexed.muxerFactory
upgradedConn = multiplexed.stream
} else {
upgradedConn = encryptedConn
}
} catch (err: any) {
log.error('Failed to upgrade outbound connection', err)
await maConn.close(err)
throw err
}
if (await this.components.getConnectionGater().denyOutboundUpgradedConnection(remotePeer, {
...protectedConn,
...encryptedConn
})) {
throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED)
}
if (metrics != null) {
metrics.updatePlaceholder(proxyPeer, remotePeer)
setPeer(remotePeer)
}
log('Successfully upgraded outbound connection')
return this._createConnection({
cryptoProtocol,
direction: 'outbound',
maConn,
upgradedConn,
muxerFactory,
remotePeer
})
}
/**
* A convenience method for generating a new `Connection`
*/
_createConnection (opts: CreateConectionOptions): Connection {
const {
cryptoProtocol,
direction,
maConn,
upgradedConn,
remotePeer,
muxerFactory
} = opts
let muxer: StreamMuxer | undefined
let newStream: ((multicodecs: string[], options?: AbortOptions) => Promise<Stream>) | undefined
let connection: Connection // eslint-disable-line prefer-const
if (muxerFactory != null) {
// Create the muxer
muxer = muxerFactory.createStreamMuxer({
direction,
// Run anytime a remote stream is created
onIncomingStream: muxedStream => {
if (connection == null) {
return
}
void Promise.resolve()
.then(async () => {
const mss = new Listener(muxedStream)
const protocols = this.components.getRegistrar().getProtocols()
const { stream, protocol } = await mss.handle(protocols)
log('%s: incoming stream opened on %s', direction, protocol)
const metrics = this.components.getMetrics()
if (metrics != null) {
metrics.trackStream({ stream, remotePeer, protocol })
}
if (connection == null) {
return
}
const incomingLimit = findIncomingStreamLimit(protocol, this.components.getRegistrar())
const streamCount = countStreams(protocol, 'inbound', connection)
if (streamCount === incomingLimit) {
throw errCode(new Error('Too many incoming protocol streams'), codes.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS)
}
muxedStream.stat.protocol = protocol
connection.addStream(muxedStream)
this._onStream({ connection, stream: { ...muxedStream, ...stream }, protocol })
})
.catch(err => {
log.error(err)
if (muxedStream.stat.timeline.close == null) {
muxedStream.close()
}
})
},
// Run anytime a stream closes
onStreamEnd: muxedStream => {
connection?.removeStream(muxedStream.id)
}
})
if (isInitializable(muxer)) {
muxer.init(this.components)
}
newStream = async (protocols: string[], options: AbortOptions = {}): Promise<Stream> => {
if (muxer == null) {
throw errCode(new Error('Stream is not multiplexed'), codes.ERR_MUXER_UNAVAILABLE)
}
log('%s: starting new stream on %s', direction, protocols)
const muxedStream = muxer.newStream()
const mss = new Dialer(muxedStream)
const metrics = this.components.getMetrics()
let controller: TimeoutController | undefined
try {
if (options.signal == null) {
log('No abort signal was passed while trying to negotiate protocols %s falling back to default timeout', protocols)
controller = new TimeoutController(30000)
options.signal = controller.signal
try {
// fails on node < 15.4
setMaxListeners?.(Infinity, controller.signal)
} catch {}
}
let { stream, protocol } = await mss.select(protocols, options)
if (metrics != null) {
stream = metrics.trackStream({ stream, remotePeer, protocol })
}
const outgoingLimit = findOutgoingStreamLimit(protocol, this.components.getRegistrar())
const streamCount = countStreams(protocol, 'outbound', connection)
if (streamCount === outgoingLimit) {
throw errCode(new Error('Too many outgoing protocol streams'), codes.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS)
}
muxedStream.stat.protocol = protocol
return {
...muxedStream,
...stream,
stat: {
...muxedStream.stat,
protocol
}
}
} catch (err: any) {
log.error('could not create new stream', err)
if (muxedStream.stat.timeline.close == null) {
muxedStream.close()
}
if (err.code != null) {
throw err
}
throw errCode(err, codes.ERR_UNSUPPORTED_PROTOCOL)
} finally {
if (controller != null) {
controller.clear()
}
}
}
// Pipe all data through the muxer
pipe(upgradedConn, muxer, upgradedConn).catch(log.error)
}
const _timeline = maConn.timeline
maConn.timeline = new Proxy(_timeline, {
set: (...args) => {
if (connection != null && args[1] === 'close' && args[2] != null && _timeline.close == null) {
// Wait for close to finish before notifying of the closure
(async () => {
try {
if (connection.stat.status === 'OPEN') {
await connection.close()
}
} catch (err: any) {
log.error(err)
} finally {
this.dispatchEvent(new CustomEvent<Connection>('connectionEnd', {
detail: connection
}))
}
})().catch(err => {
log.error(err)
})
}
return Reflect.set(...args)
}
})
maConn.timeline.upgraded = Date.now()
const errConnectionNotMultiplexed = () => {
throw errCode(new Error('connection is not multiplexed'), codes.ERR_CONNECTION_NOT_MULTIPLEXED)
}
// Create the connection
connection = createConnection({
remoteAddr: maConn.remoteAddr,
remotePeer: remotePeer,
stat: {
status: 'OPEN',
direction,
timeline: maConn.timeline,
multiplexer: muxer?.protocol,
encryption: cryptoProtocol
},
newStream: newStream ?? errConnectionNotMultiplexed,
getStreams: () => muxer != null ? muxer.streams : errConnectionNotMultiplexed(),
close: async () => {
await maConn.close()
// Ensure remaining streams are closed
if (muxer != null) {
muxer.close()
}
}
})
this.dispatchEvent(new CustomEvent<Connection>('connection', {
detail: connection
}))
return connection
}
/**
* Routes incoming streams to the correct handler
*/
_onStream (opts: OnStreamOptions): void {
const { connection, stream, protocol } = opts
const { handler } = this.components.getRegistrar().getHandler(protocol)
handler({ connection, stream })
}
/**
* Attempts to encrypt the incoming `connection` with the provided `cryptos`
*/
async _encryptInbound (connection: Duplex<Uint8Array>): Promise<CryptoResult> {
const mss = new Listener(connection)
const protocols = Array.from(this.connectionEncryption.keys())
log('handling inbound crypto protocol selection', protocols)
try {
const { stream, protocol } = await mss.handle(protocols)
const encrypter = this.connectionEncryption.get(protocol)
if (encrypter == null) {
throw new Error(`no crypto module found for ${protocol}`)
}
log('encrypting inbound connection...')
return {
...await encrypter.secureInbound(this.components.getPeerId(), stream),
protocol
}
} catch (err: any) {
throw errCode(err, codes.ERR_ENCRYPTION_FAILED)
}
}
/**
* Attempts to encrypt the given `connection` with the provided connection encrypters.
* The first `ConnectionEncrypter` module to succeed will be used
*/
async _encryptOutbound (connection: MultiaddrConnection, remotePeerId: PeerId): Promise<CryptoResult> {
const mss = new Dialer(connection)
const protocols = Array.from(this.connectionEncryption.keys())
log('selecting outbound crypto protocol', protocols)
try {
const { stream, protocol } = await mss.select(protocols)
const encrypter = this.connectionEncryption.get(protocol)
if (encrypter == null) {
throw new Error(`no crypto module found for ${protocol}`)
}
log('encrypting outbound connection to %p', remotePeerId)
return {
...await encrypter.secureOutbound(this.components.getPeerId(), stream, remotePeerId),
protocol
}
} catch (err: any) {
throw errCode(err, codes.ERR_ENCRYPTION_FAILED)
}
}
/**
* Selects one of the given muxers via multistream-select. That
* muxer will be used for all future streams on the connection.
*/
async _multiplexOutbound (connection: MultiaddrConnection, muxers: Map<string, StreamMuxerFactory>): Promise<{ stream: Duplex<Uint8Array>, muxerFactory?: StreamMuxerFactory}> {
const dialer = new Dialer(connection)
const protocols = Array.from(muxers.keys())
log('outbound selecting muxer %s', protocols)
try {
const { stream, protocol } = await dialer.select(protocols)
log('%s selected as muxer protocol', protocol)
const muxerFactory = muxers.get(protocol)
return { stream, muxerFactory }
} catch (err: any) {
log.error('error multiplexing outbound stream', err)
throw errCode(err, codes.ERR_MUXER_UNAVAILABLE)
}
}
/**
* Registers support for one of the given muxers via multistream-select. The
* selected muxer will be used for all future streams on the connection.
*/
async _multiplexInbound (connection: MultiaddrConnection, muxers: Map<string, StreamMuxerFactory>): Promise<{ stream: Duplex<Uint8Array>, muxerFactory?: StreamMuxerFactory}> {
const listener = new Listener(connection)
const protocols = Array.from(muxers.keys())
log('inbound handling muxers %s', protocols)
try {
const { stream, protocol } = await listener.handle(protocols)
const muxerFactory = muxers.get(protocol)
return { stream, muxerFactory }
} catch (err: any) {
log.error('error multiplexing inbound stream', err)
throw errCode(err, codes.ERR_MUXER_UNAVAILABLE)
}
}
}