-
Notifications
You must be signed in to change notification settings - Fork 88
/
index.ts
360 lines (297 loc) · 9.88 KB
/
index.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
import logger from '../../logger'
import { socketToMaConn } from './socket-to-conn'
import * as filters from './filters'
import { MultiaddrFilter, CreateListenerOptions, DialOptions } from '@libp2p/interface-transport'
import type { AbortOptions } from '@libp2p/interfaces'
import type { Multiaddr } from '@multiformats/multiaddr'
import type { ClientOptions, ErrorEvent } from 'ws'
import os from 'os'
import PeerId from 'peer-id'
import url from 'url'
import type { Server } from 'http'
import https from 'https'
import { EventEmitter } from 'events'
import { dumpPEM } from '../utils'
import pDefer from 'p-defer'
import { multiaddrToUri as toUri } from '@multiformats/multiaddr-to-uri'
import { AbortError } from '@libp2p/interfaces/errors'
import { connect } from 'it-ws'
import { ServerOptions, WebSocketServer as ItWsWebsocketServer } from 'it-ws/server'
import { multiaddr } from '@multiformats/multiaddr'
import { MultiaddrConnection, Connection } from '@libp2p/interface-connection'
const log = logger('libp2p:websockets')
const symbol = Symbol.for('@libp2p/transport')
export interface WebSocketServer extends ItWsWebsocketServer {
__connections?: MultiaddrConnection[]
}
export interface WebSocketsInit extends AbortOptions {
filter?: MultiaddrFilter
websocket: ClientOptions
server?: Server
localAddress: string
targetPort: number
createServer: (opts?: ServerOptions) => WebSocketServer
}
class Discovery extends EventEmitter {
tag: string
constructor() {
super()
this.tag = 'channel_18'
}
stop() { }
start() { }
end() { }
}
export class WebSockets extends EventEmitter {
private readonly init?: WebSocketsInit
_websocketOpts: ClientOptions
localAddress: string
discovery: Discovery
targetPort: number
createServer: (opts?: ServerOptions) => WebSocketServer
constructor({ websocket, localAddress, targetPort, createServer }: WebSocketsInit) {
super()
this._websocketOpts = websocket
this.localAddress = localAddress
this.discovery = new Discovery()
this.targetPort = targetPort
this.createServer = createServer
}
get [Symbol.toStringTag]() {
return '@libp2p/websockets'
}
get [symbol](): true {
return true
}
async dial(ma: Multiaddr, options: DialOptions) {
let conn: Connection
let socket
let maConn: MultiaddrConnection
try {
socket = await this._connect(ma, {
websocket: {
...this._websocketOpts,
...this.certData
}
})
} catch (e) {
log.error('error connecting to %s. Details: %s', ma, e.message)
throw e
}
try {
maConn = socketToMaConn(socket, ma, { signal: options.signal })
log('new outbound connection %s', maConn.remoteAddr)
} catch (e) {
log.error('error creating new outbound connection %s. Details: %s', ma, e.message)
throw e
}
try {
conn = await options.upgrader.upgradeOutbound(maConn)
log('outbound connection %s upgraded', maConn.remoteAddr)
return conn
} catch (e) {
log.error('error upgrading outbound connection %s. Details: %s', maConn.remoteAddr, e.message)
throw e
}
}
get certData() {
const { cert, key, ca } = this._websocketOpts
if (!cert || !key || !ca?.length || !ca[0]) {
throw new Error('No cert data in _websocketOpts')
}
let _ca: string | Buffer
if (Array.isArray(ca)) {
_ca = ca[0]
} else {
_ca = ca
}
return {
cert: dumpPEM('CERTIFICATE', cert.toString()),
key: dumpPEM('PRIVATE KEY', key.toString()),
ca: [dumpPEM('CERTIFICATE', _ca.toString())]
}
}
async _connect(ma: Multiaddr, options: any = {}) {
if (options.signal?.aborted) {
throw new AbortError()
}
const cOpts = ma.toOptions()
log('connect %s:%s', cOpts.host, cOpts.port)
const errorPromise = pDefer()
const errfn = (event: ErrorEvent) => {
log.error(`connection error: ${event.message}`)
errorPromise.reject(event)
}
const myUri = `${toUri(ma)}/?remoteAddress=${encodeURIComponent(
this.localAddress
)}`
const rawSocket = connect(myUri, Object.assign({ binary: true }, options))
if (rawSocket.socket.on) {
rawSocket.socket.on('error', errfn)
} else {
rawSocket.socket.onerror = errfn
}
if (!options.signal) {
await Promise.race([rawSocket.connected(), errorPromise.promise])
log(`${this.localAddress} connected %s`, ma)
return rawSocket
}
// Allow abort via signal during connect
let onAbort
// eslint-disable-next-line
const abort = new Promise((_resolve, reject) => {
onAbort = () => {
reject(new AbortError())
rawSocket.close().catch(err => {
log.error('error closing raw socket', err)
})
}
// Already aborted?
if (options.signal.aborted) return onAbort()
options.signal.addEventListener('abort', onAbort)
})
try {
await Promise.race([abort, errorPromise.promise, rawSocket.connected()])
} finally {
options.signal.removeEventListener('abort', onAbort)
}
log('connected %s', ma)
return rawSocket
}
/**
* Creates a Websockets listener. The provided `handler` function will be called
* anytime a new incoming Connection has been successfully upgraded via
* `upgrader.upgradeInbound`
*/
prepareListener = ({ handler, upgrader }: CreateListenerOptions): any => {
console.log('preparing listener')
log('prepareListener')
const listener: any = new EventEmitter()
const trackConn = (server: WebSocketServer, maConn: MultiaddrConnection) => {
server.__connections?.push(maConn)
}
const serverHttps = https.createServer({
...this.certData,
requestCert: true,
enableTrace: false
})
const optionsServ = {
server: serverHttps,
verifyClient: function (_info: any, done: (res: boolean) => void) {
done(true)
}
}
const server = this.createServer(optionsServ)
server.__connections = []
server.on('connection', async (stream, request) => {
let maConn: MultiaddrConnection
let conn: Connection
// eslint-disable-next-line
const query = url.parse(request.url, true).query
log('server connecting with', query.remoteAddress)
if (!query.remoteAddress) return
const remoteAddress = query.remoteAddress.toString()
try {
maConn = socketToMaConn(stream, multiaddr(remoteAddress))
const peer = {
id: PeerId.createFromB58String(remoteAddress.split('/p2p/')[1]),
multiaddrs: [maConn.remoteAddr]
}
this.discovery.emit('peer', peer)
log('new inbound connection %s', maConn.remoteAddr)
} catch (e) {
log.error(`Failed to convert stream into a MultiaddrConnection for ${remoteAddress}:`, e)
return
}
try {
conn = await upgrader.upgradeInbound(maConn)
} catch (err) {
log.error('inbound connection failed to upgrade', err)
return await maConn?.close()
}
log('inbound connection %s upgraded', maConn.remoteAddr)
trackConn(server, maConn)
if (handler) handler(conn)
listener.emit('connection', conn)
})
.on('listening', () => listener.emit('listening'))
.on('error', err => listener.emit('error', err))
.on('close', () => listener.emit('close'))
// Keep track of open connections to destroy in case of timeout
let listeningMultiaddr: Multiaddr
listener.close = async () => {
server.__connections?.forEach(async maConn => await maConn.close())
return await server.close()
}
listener.addEventListener = () => { }
listener.listen = async (ma: Multiaddr) => {
listeningMultiaddr = ma
const listenOptions = {
...ma.toOptions(),
port: this.targetPort
}
return await server.listen(listenOptions)
}
listener.getAddrs = () => {
const multiaddrs: Multiaddr[] = []
const address = server.address()
if (!address) {
throw new Error('Listener is not ready yet')
}
const ipfsId: string | null = listeningMultiaddr.getPeerId()
// Because TCP will only return the IPv6 version
// we need to capture from the passed multiaddr
if (listeningMultiaddr.toString().includes('ip4')) {
let m = listeningMultiaddr.decapsulate('tcp')
m = m.encapsulate('/tcp/443/wss')
if (ipfsId) {
m = m.encapsulate('/p2p/' + ipfsId)
}
if (m.toString().includes('0.0.0.0')) {
const netInterfaces = os.networkInterfaces()
Object.keys(netInterfaces).forEach(niKey => {
netInterfaces[niKey]?.forEach(ni => {
if (ni.family === 'IPv4') {
multiaddrs.push(multiaddr(m.toString().replace('0.0.0.0', ni.address)))
}
})
})
} else {
multiaddrs.push(m)
}
}
return multiaddrs
}
return listener
}
createListener(options: CreateListenerOptions) {
// if (typeof options === 'function') {
// // TODO: is it needed?
// handler = options
// options = {}
// }
return this.prepareListener(options)
}
/**
* Takes a list of `Multiaddr`s and returns only valid Websockets addresses.
* By default, in a browser environment only DNS+WSS multiaddr is accepted,
* while in a Node.js environment DNS+{WS, WSS} multiaddrs are accepted.
*/
filter(multiaddrs: Multiaddr[]) {
multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs]
if (this.init?.filter != null) {
return this.init?.filter(multiaddrs)
}
// Browser
// Probably we don't need browser atm
// if (isBrowser || isWebWorker) {
// return filters.dnsWss(multiaddrs)
// }
return filters.all(multiaddrs)
}
}
export function webSockets(init: WebSocketsInit): (components?: any) => WebSockets {
return () => {
return new WebSockets(init)
}
}