Dmitriy Ryajov 9ddff85601 feat: filter IPFS addrs correctly (#62)
* feat: dns support for WS

* fix: address parsing

* feat: filter IPFS addrs correctly

* fix: remove lodash includes dependency

* feat: mafmt addrs now support /ipfs no need for ad-hoc filtering

* feat: skip p2p-circuit addresses

* chore: updating ci files

* chore: upgrading to new aegir

* test: pass the no-parallel flag to tests

* wip

* test: removing global timeout and setting it on a specific test

* feat: resolve 0 addresses (#64)

* feat: resolve 0 addresses

* chore: upgrading pull-ws

* chore: update circle CI

* chore: update gitignore

* chore: update deps

* chore: update CI again

* test: fix node.js tests

* test: fix browser tests

* chore
2017-10-20 12:12:35 +01:00

74 lines
1.9 KiB
JavaScript

'use strict'
const Connection = require('interface-connection').Connection
const includes = require('lodash.includes')
const multiaddr = require('multiaddr')
const os = require('os')
function noop () {}
const createServer = require('pull-ws/server') || noop
module.exports = (options, handler) => {
const listener = createServer((socket) => {
socket.getObservedAddrs = (callback) => {
// TODO research if we can reuse the address in anyway
return callback(null, [])
}
handler(new Connection(socket))
})
let listeningMultiaddr
listener._listen = listener.listen
listener.listen = (ma, callback) => {
callback = callback || noop
listeningMultiaddr = ma
if (includes(ma.protoNames(), 'ipfs')) {
ma = ma.decapsulate('ipfs')
}
listener._listen(ma.toOptions(), callback)
}
listener.getAddrs = (callback) => {
const multiaddrs = []
const address = listener.address()
if (!address) {
return callback(new Error('Listener is not ready yet'))
}
let ipfsId = listeningMultiaddr.getPeerId()
// Because TCP will only return the IPv6 version
// we need to capture from the passed multiaddr
if (listeningMultiaddr.toString().indexOf('ip4') !== -1) {
let m = listeningMultiaddr.decapsulate('tcp')
m = m.encapsulate('/tcp/' + address.port + '/ws')
if (listeningMultiaddr.getPeerId()) {
m = m.encapsulate('/ipfs/' + ipfsId)
}
if (m.toString().indexOf('0.0.0.0') !== -1) {
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)
}
}
callback(null, multiaddrs)
}
return listener
}