-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathserver.js
More file actions
699 lines (563 loc) · 19.7 KB
/
server.js
File metadata and controls
699 lines (563 loc) · 19.7 KB
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
const { EventEmitter } = require('events')
const safetyCatch = require('safety-catch')
const NoiseSecretStream = require('@hyperswarm/secret-stream')
const b4a = require('b4a')
const relay = require('blind-relay')
const NoiseWrap = require('./noise-wrap')
const Announcer = require('./announcer')
const { FIREWALL, ERROR } = require('./constants')
const { unslabbedHash } = require('./crypto')
const SecurePayload = require('./secure-payload')
const Holepuncher = require('./holepuncher')
const { isPrivate } = require('bogon')
const { ALREADY_LISTENING, NODE_DESTROYED, KEYPAIR_ALREADY_USED } = require('./errors')
const HANDSHAKE_CLEAR_WAIT = 10000
const HANDSHAKE_INITIAL_TIMEOUT = 10000
module.exports = class Server extends EventEmitter {
constructor (dht, opts = {}) {
super()
this.dht = dht
this.target = null
this.closed = false
this.firewall = opts.firewall || (() => false)
this.holepunch = opts.holepunch || (() => true)
this.relayThrough = opts.relayThrough || null
this.relayKeepAlive = opts.relayKeepAlive || 5000
this.pool = opts.pool || null
this.createHandshake = opts.createHandshake || defaultCreateHandshake
this.createSecretStream = opts.createSecretStream || defaultCreateSecretStream
this.suspended = false
this.handshakeClearWait = opts.handshakeClearWait || HANDSHAKE_CLEAR_WAIT
this._shareLocalAddress = opts.shareLocalAddress !== false
this._reusableSocket = !!opts.reusableSocket
this._neverPunch = opts.holepunch === false // useful for fully disabling punching
this._keyPair = null
this._announcer = null
this._connects = new Map()
this._holepunches = []
this._listening = null
this._closing = null
}
get listening () {
return this._listening !== null
}
get publicKey () {
return this._keyPair && this._keyPair.publicKey
}
get relayAddresses () {
return this._announcer ? this._announcer.relayAddresses : []
}
onconnection (encryptedSocket) {
this.emit('connection', encryptedSocket)
}
async suspend ({ log = noop } = {}) {
log('Suspending hyperdht server')
if (this._listening !== null) await this._listening
log('Suspending hyperdht server (post listening)')
this.suspended = true
this._clearAll()
return this._announcer ? this._announcer.suspend({ log }) : Promise.resolve()
}
async resume () {
if (this._listening !== null) await this._listening
this.suspended = false
return this._announcer ? this._announcer.resume() : Promise.resolve()
}
address () {
if (!this._keyPair) return null
return {
publicKey: this._keyPair.publicKey,
host: this.dht.host,
port: this.dht.port
}
}
close () {
if (this._closing) return this._closing
this._closing = this._close()
return this._closing
}
_gc () {
this.dht.listening.delete(this)
if (this.target) this.dht._router.delete(this.target)
}
async _stopListening () {
try {
if (this._announcer) await this._announcer.stop()
} catch {
// ignore
}
this._announcer = null
this._listening = null
this._keyPair = null
}
async _close () {
if (this._listening === null) {
this.closed = true
this.emit('close')
return
}
try {
await this._listening
} catch {}
this._gc()
this._clearAll()
await this._stopListening()
this.closed = true
this.emit('close')
}
_clearAll () {
while (this._holepunches.length > 0) {
const h = this._holepunches.pop()
if (h && h.puncher) h.puncher.destroy()
if (h && h.clearing) clearTimeout(h.clearing)
if (h && h.prepunching) clearTimeout(h.prepunching)
if (h && h.rawStream) h.rawStream.destroy()
}
this._connects.clear()
}
async listen (keyPair = this.dht.defaultKeyPair, opts = {}) {
if (this._listening !== null) throw ALREADY_LISTENING()
if (this.dht.destroyed) throw NODE_DESTROYED()
this._listening = this._listen(keyPair, opts)
await this._listening
return this
}
async _listen (keyPair, opts) {
// From now on, the DHT object which created me is responsible for closing me
this.dht.listening.add(this)
try {
await this.dht.bind()
if (this._closing) return
for (const s of this.dht.listening) {
if (s._keyPair && b4a.equals(s._keyPair.publicKey, keyPair.publicKey)) {
throw KEYPAIR_ALREADY_USED()
}
}
this.target = unslabbedHash(keyPair.publicKey)
this._keyPair = keyPair
this._announcer = new Announcer(this.dht, keyPair, this.target, opts)
this.dht._router.set(this.target, {
relay: null,
record: this._announcer.record,
onpeerhandshake: this._onpeerhandshake.bind(this),
onpeerholepunch: this._onpeerholepunch.bind(this)
})
// warm it up for now
this._localAddresses().catch(safetyCatch)
await this._announcer.start()
} catch (err) {
await this._stopListening()
this._gc()
throw err
}
if (this._closing) return
if (this.suspended) await this._announcer.suspend()
if (this._closing) return
if (this.dht.destroyed) throw NODE_DESTROYED()
if (this.pool) this.pool._attachServer(this)
this.emit('listening')
}
refresh () {
if (this._announcer) this._announcer.refresh()
}
notifyOnline () {
if (this._announcer) this._announcer.online.notify()
}
_localAddresses () {
return this.dht.validateLocalAddresses(Holepuncher.localAddresses(this.dht.io.serverSocket))
}
async _addHandshake (k, noise, clientAddress, { from, to: serverAddress, socket }, direct) {
let id = this._holepunches.indexOf(null)
if (id === -1) id = this._holepunches.push(null) - 1
const hs = {
round: 0,
reply: null,
puncher: null,
payload: null,
rawStream: null,
encryptedSocket: null,
prepunching: null,
firewalled: true,
clearing: null,
onsocket: null,
// Relay state
relayTimeout: null,
relayToken: null,
relaySocket: null,
relayClient: null,
relayPaired: false
}
this._holepunches[id] = hs
const handshake = this.createHandshake(this._keyPair, null)
let remotePayload
try {
remotePayload = await handshake.recv(noise)
} catch (err) {
safetyCatch(err)
this._clearLater(hs, id, k)
return null
}
if (this._closing || this.suspended) return null
try {
hs.firewalled = await this.firewall(handshake.remotePublicKey, remotePayload, clientAddress)
} catch (err) {
safetyCatch(err)
}
if (this._closing || this.suspended) return null
if (hs.firewalled) {
this._clearLater(hs, id, k)
return null
}
const error = remotePayload.version === 1
? (remotePayload.udx ? ERROR.NONE : ERROR.ABORTED)
: ERROR.VERSION_MISMATCH
const addresses = []
const ourRemoteAddr = this.dht.remoteAddress()
const ourLocalAddrs = this._shareLocalAddress ? await this._localAddresses() : null
if (this._closing || this.suspended) return null
if (ourRemoteAddr) addresses.push(ourRemoteAddr)
if (ourLocalAddrs) addresses.push(...ourLocalAddrs)
if (error === ERROR.NONE) {
hs.rawStream = this.dht.createRawStream({
framed: true,
firewall (socket, port, host) {
// Check if the traffic originated from the socket on which we're expecting relay traffic. If so,
// we haven't hole punched yet and the other side is just sending us traffic through the relay.
if (hs.relaySocket && isRelay(hs.relaySocket, socket, port, host)) {
return false
}
hs.onsocket(socket, port, host)
return false
}
})
hs.rawStream.on('error', autoDestroy)
hs.onsocket = (socket, port, host) => {
if (hs.rawStream === null) return // Already hole punched
this._clearLater(hs, id, k)
if (hs.prepunching) {
clearTimeout(hs.prepunching)
hs.prepunching = null
}
if (this._reusableSocket && remotePayload.udx.reusableSocket) {
this.dht._socketPool.routes.add(handshake.remotePublicKey, hs.rawStream)
}
hs.rawStream.removeListener('error', autoDestroy)
if (hs.rawStream.connected) {
const remoteChanging = hs.rawStream.changeRemote(socket, remotePayload.udx.id, port, host)
if (remoteChanging) remoteChanging.catch(safetyCatch)
} else {
hs.rawStream.connect(socket, remotePayload.udx.id, port, host)
hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, {
handshake: h,
keepAlive: this.dht.connectionKeepAlive
})
this.onconnection(hs.encryptedSocket)
}
if (hs.puncher) {
hs.puncher.onabort = noop
hs.puncher.destroy()
}
hs.rawStream = null
}
function autoDestroy () {
if (hs.puncher) hs.puncher.destroy()
}
}
const relayThrough = selectRelay(this.relayThrough)
if (relayThrough) hs.relayToken = relay.token()
try {
hs.reply = await handshake.send({
error,
firewall: ourRemoteAddr ? FIREWALL.OPEN : FIREWALL.UNKNOWN,
holepunch: ourRemoteAddr ? null : { id, relays: this._announcer.relays },
addresses4: addresses,
addresses6: null,
udx: {
reusableSocket: this._reusableSocket,
id: hs.rawStream ? hs.rawStream.id : 0,
seq: 0
},
secretStream: {},
relayThrough: relayThrough
? { publicKey: relayThrough, token: hs.relayToken }
: null
})
} catch (err) {
safetyCatch(err)
hs.rawStream.destroy()
this._clearLater(hs, id, k)
return null
}
if (this._closing || this.suspended) {
hs.rawStream.destroy()
return null
}
const h = handshake.final()
if (error !== ERROR.NONE) {
hs.rawStream.destroy()
this._clearLater(hs, id, k)
return hs
}
if (relayThrough || remotePayload.relayThrough) {
this._relayConnection(hs, relayThrough, remotePayload, h)
}
if (remotePayload.firewall === FIREWALL.OPEN || direct) {
const sock = direct ? socket : this.dht.socket
this.dht.stats.punches.open++
hs.onsocket(sock, clientAddress.port, clientAddress.host)
return hs
}
const onabort = () => {
if (hs.prepunching) clearTimeout(hs.prepunching)
hs.prepunching = null
hs.rawStream.on('close', () => this._clearLater(hs, id, k))
if (hs.relayToken === null) hs.rawStream.destroy()
}
if (!direct && clientAddress.host === serverAddress.host) {
const clientAddresses = remotePayload.addresses4.filter(onlyPrivateHosts)
if (clientAddresses.length > 0 && this._shareLocalAddress) {
const myAddresses = await this._localAddresses()
const addr = Holepuncher.matchAddress(myAddresses, clientAddresses)
if (addr) {
hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
return hs
}
}
}
if (this._closing || this.suspended) return null
if (ourRemoteAddr || this._neverPunch) {
hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT)
return hs
}
hs.payload = new SecurePayload(h.holepunchSecret)
hs.puncher = new Holepuncher(this.dht, this.dht.session(), false, remotePayload.firewall)
hs.puncher.onconnect = hs.onsocket
hs.puncher.onabort = onabort
hs.prepunching = setTimeout(hs.puncher.destroy.bind(hs.puncher), HANDSHAKE_INITIAL_TIMEOUT)
return hs
}
_clearLater (hs, id, k) {
if (hs.clearing) return
hs.clearing = setTimeout(() => this._clear(hs, id, k), this.handshakeClearWait)
}
_clear (hs, id, k) {
if (id >= this._holepunches.length || this._holepunches[id] !== hs) return
if (hs.clearing) clearTimeout(hs.clearing)
this._holepunches[id] = null
while (this._holepunches.length > 0 && this._holepunches[this._holepunches.length - 1] === null) {
this._holepunches.pop()
}
this._connects.delete(k)
}
async _onpeerhandshake ({ noise, peerAddress }, req) {
const k = b4a.toString(noise, 'hex')
// The next couple of statements MUST run within the same tick to prevent
// a malicious peer from flooding us with handshakes.
let p = this._connects.get(k)
if (!p) {
p = this._addHandshake(k, noise, peerAddress || req.from, req, !peerAddress)
this._connects.set(k, p)
}
const h = await p
if (!h) return null
if (this._closing !== null || this.suspended) return null
return { socket: h.puncher && h.puncher.socket, noise: h.reply }
}
async _onpeerholepunch ({ id, peerAddress, payload }, req) {
const h = id < this._holepunches.length ? this._holepunches[id] : null
if (!h) return null
if (!peerAddress || this._closing !== null || this.suspended) return null
const p = h.puncher
if (!p || !p.socket) return this._abort(h) // not opened
const remotePayload = h.payload.decrypt(payload)
if (!remotePayload) return null
const isServerRelay = this._announcer.isRelay(req.from)
const { error, firewall, round, punching, addresses, remoteAddress, remoteToken } = remotePayload
if (error !== ERROR.NONE) {
// We actually do not need to set the round here, but just do it for consistency.
if (round >= h.round) h.round = round
return this._abort(h)
}
const token = h.payload.token(peerAddress)
const echoed = isServerRelay && !!remoteToken && b4a.equals(token, remoteToken)
// Update our heuristics here
if (req.socket === p.socket) {
p.nat.add(req.to, req.from)
}
if (round >= h.round) {
h.round = round
p.updateRemote({ punching, firewall, addresses, verified: echoed ? peerAddress.host : null })
}
// Wait for the analyzer to reach a conclusion...
let stable = await p.analyze(false)
if (p.destroyed) return null
if (!p.remoteHolepunching && !stable) {
stable = await p.analyze(true)
if (p.destroyed) return null
if (!stable) return this._abort(h)
}
// Fast mode! If we are consistent and the remote has opened a session to us (remoteAddress)
// then fire a quick punch back. Note the await here just waits for the udp socket to flush.
if (isConsistent(p.nat.firewall) && remoteAddress && hasSameAddr(p.nat.addresses, remoteAddress)) {
await p.ping(peerAddress)
if (p.destroyed) return null
}
// Remote said they are punching (or willing to), so we will punch as well.
// Note that this returns when the punching has STARTED, so no guarantee
// we will have a connection after this promise etc.
if (p.remoteHolepunching) {
// TODO: still continue here if a local connection might work, but then do not holepunch...
if (!this.holepunch(p.remoteFirewall, p.nat.firewall, p.remoteAddresses, p.nat.addresses)) {
return p.destroyed ? null : this._abort(h)
}
if (h.prepunching) {
clearTimeout(h.prepunching)
h.prepunching = null
}
if (p.remoteFirewall >= FIREWALL.RANDOM || p.nat.firewall >= FIREWALL.RANDOM) {
if (this.dht._randomPunches >= this.dht._randomPunchLimit || (Date.now() - this.dht._lastRandomPunch) < this.dht._randomPunchInterval) {
if (!h.relayToken) return this._abort(h, ERROR.TRY_LATER)
return {
socket: p.socket,
payload: h.payload.encrypt({
error: ERROR.TRY_LATER,
firewall: p.nat.firewall,
round: h.round,
connected: p.connected,
punching: p.punching,
addresses: p.nat.addresses,
remoteAddress: null,
token: isServerRelay ? token : null,
remoteToken: remotePayload.token
})
}
}
}
const punching = await p.punch()
if (p.destroyed) return null
if (!punching) return this._abort(h)
}
// Freeze that analysis as soon as we have a result we are giving to the other peer
if (p.nat.firewall !== FIREWALL.UNKNOWN) {
p.nat.freeze()
}
return {
socket: p.socket,
payload: h.payload.encrypt({
error: ERROR.NONE,
firewall: p.nat.firewall,
round: h.round,
connected: p.connected,
punching: p.punching,
addresses: p.nat.addresses,
remoteAddress: null,
token: isServerRelay ? token : null,
remoteToken: remotePayload.token
})
}
}
_abort (h, error = ERROR.ABORTED) {
if (!h.payload) {
if (h.puncher) h.puncher.destroy()
return null
}
const payload = h.payload.encrypt({
error,
firewall: FIREWALL.UNKNOWN,
round: h.round,
connected: false,
punching: false,
addresses: null,
remoteAddress: null,
token: null,
remoteToken: null
})
h.puncher.destroy()
return { socket: this.dht.socket, payload }
}
_relayConnection (hs, relayThrough, remotePayload, h) {
let isInitiator
let publicKey
let token
if (relayThrough) {
isInitiator = true
publicKey = relayThrough
token = hs.relayToken
} else {
isInitiator = false
publicKey = remotePayload.relayThrough.publicKey
token = remotePayload.relayThrough.token
}
hs.relayToken = token
hs.relaySocket = this.dht.connect(publicKey)
hs.relaySocket.setKeepAlive(this.relayKeepAlive)
hs.relayClient = relay.Client.from(hs.relaySocket, { id: hs.relaySocket.publicKey })
hs.relayTimeout = setTimeout(onabort, 15000)
hs.relayClient
.pair(isInitiator, token, hs.rawStream)
.on('error', onabort)
.on('data', (remoteId) => {
if (hs.relayTimeout) clearRelayTimeout(hs)
if (hs.rawStream === null) {
onabort(null)
return
}
hs.relayPaired = true
if (hs.prepunching) clearTimeout(hs.prepunching)
hs.prepunching = null
const {
remotePort,
remoteHost,
socket
} = hs.relaySocket.rawStream
hs.rawStream
.on('close', () => hs.relaySocket.destroy())
.connect(socket, remoteId, remotePort, remoteHost)
hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, { handshake: h })
this.onconnection(hs.encryptedSocket)
})
function onabort () {
if (hs.relayTimeout) clearRelayTimeout(hs)
const socket = hs.relaySocket
hs.relayToken = null
hs.relaySocket = null
if (socket) socket.destroy()
}
}
}
function clearRelayTimeout (hs) {
clearTimeout(hs.relayTimeout)
hs.relayTimeout = null
}
function isConsistent (fw) {
return fw === FIREWALL.OPEN || fw === FIREWALL.CONSISTENT
}
function hasSameAddr (addrs, other) {
if (addrs === null) return false
for (const addr of addrs) {
if (addr.port === other.port && addr.host === other.host) return true
}
return false
}
function defaultCreateHandshake (keyPair, remotePublicKey) {
return new NoiseWrap(keyPair, remotePublicKey)
}
function defaultCreateSecretStream (isInitiator, rawStream, opts) {
return new NoiseSecretStream(isInitiator, rawStream, opts)
}
function onlyPrivateHosts (addr) {
return isPrivate(addr.host)
}
function isRelay (relaySocket, socket, port, host) {
const stream = relaySocket.rawStream
if (!stream) return false
if (stream.socket !== socket) return false
return port === stream.remotePort && host === stream.remoteHost
}
function selectRelay (relayThrough) {
if (typeof relayThrough === 'function') relayThrough = relayThrough()
if (relayThrough === null) return null
if (Array.isArray(relayThrough)) return relayThrough[Math.floor(Math.random() * relayThrough.length)]
return relayThrough
}
function noop () {}