2016-08-11 14:50:44 +02:00
|
|
|
'use strict'
|
|
|
|
|
|
|
|
const Connection = require('interface-connection').Connection
|
2016-12-15 21:06:54 -08:00
|
|
|
const includes = require('lodash.includes')
|
2017-10-20 04:12:35 -07:00
|
|
|
const multiaddr = require('multiaddr')
|
|
|
|
const os = require('os')
|
|
|
|
|
2017-03-23 15:09:06 +00:00
|
|
|
function noop () {}
|
2017-10-20 04:12:35 -07:00
|
|
|
|
2017-03-23 15:09:06 +00:00
|
|
|
const createServer = require('pull-ws/server') || noop
|
2016-08-11 14:50:44 +02:00
|
|
|
|
|
|
|
module.exports = (options, handler) => {
|
|
|
|
const listener = createServer((socket) => {
|
2017-03-23 15:09:06 +00:00
|
|
|
socket.getObservedAddrs = (callback) => {
|
2016-08-11 14:50:44 +02:00
|
|
|
// TODO research if we can reuse the address in anyway
|
2017-03-23 15:09:06 +00:00
|
|
|
return callback(null, [])
|
2016-08-11 14:50:44 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
handler(new Connection(socket))
|
|
|
|
})
|
|
|
|
|
|
|
|
let listeningMultiaddr
|
|
|
|
|
|
|
|
listener._listen = listener.listen
|
2017-03-23 15:09:06 +00:00
|
|
|
listener.listen = (ma, callback) => {
|
|
|
|
callback = callback || noop
|
2016-08-11 14:50:44 +02:00
|
|
|
listeningMultiaddr = ma
|
|
|
|
|
2016-12-15 21:06:54 -08:00
|
|
|
if (includes(ma.protoNames(), 'ipfs')) {
|
2016-08-11 14:50:44 +02:00
|
|
|
ma = ma.decapsulate('ipfs')
|
|
|
|
}
|
|
|
|
|
2017-03-23 15:09:06 +00:00
|
|
|
listener._listen(ma.toOptions(), callback)
|
2016-08-11 14:50:44 +02:00
|
|
|
}
|
|
|
|
|
2017-03-23 15:09:06 +00:00
|
|
|
listener.getAddrs = (callback) => {
|
2017-10-20 04:12:35 -07:00
|
|
|
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)
|
2016-08-11 14:50:44 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return listener
|
|
|
|
}
|