Skip to content
This repository was archived by the owner on Aug 29, 2023. It is now read-only.

Commit 1ec7a4a

Browse files
committed
comply with the latest interface-transport and interface-connection spec
1 parent 730a477 commit 1ec7a4a

File tree

6 files changed

+676
-265
lines changed

6 files changed

+676
-265
lines changed

README.md

+10-25
Original file line numberDiff line numberDiff line change
@@ -24,18 +24,20 @@ transports.
2424
## Example
2525

2626
```js
27-
const Tcp = require('libp2p-tcp')
27+
const TCP = require('libp2p-tcp')
2828
const multiaddr = require('multiaddr')
2929

3030
const mh1 = multiaddr('/ip4/127.0.0.1/tcp/9090')
3131
const mh2 = multiaddr('/ip6/::/tcp/9092')
3232

3333
const tcp = new Tcp()
3434

35-
tcp.createListener([mh1, mh2], function handler (socket) {
35+
var listener = tcp.createListener(mh1, function handler (socket) {
3636
console.log('connection')
3737
socket.end('bye')
38-
}, function ready () {
38+
})
39+
40+
var listener.listen(function ready () {
3941
console.log('ready')
4042

4143
const client = tcp.dial(mh1)
@@ -65,31 +67,14 @@ bye
6567

6668
## API
6769

68-
```js
69-
const Tcp = require('libp2p-tcp')
70-
```
71-
72-
### var tcp = new Tcp()
73-
74-
Creates a new TCP object. This does nothing on its own, but provides access to
75-
`dial` and `createListener`.
76-
77-
### tcp.createListener(multiaddrs, handler, ready)
78-
79-
Creates TCP servers that listen on the addresses described in the array
80-
`multiaddrs`. Each connection will call `handler` with a connection stream.
81-
`ready` is called once all servers are listening.
82-
83-
### tcp.dial(multiaddr, options={})
70+
[![](https://raw.githubusercontent.com/diasdavid/interface-transport/master/img/badge.png)](https://github.com/diasdavid/interface-transport)
8471

85-
Connects to the multiaddress `multiaddr` using TCP, returning the socket stream.
86-
If `options.ready` is set to a function, it is called when a connection is
87-
established.
72+
`libp2p-tcp` accepts TCP addresses both IPFS and non IPFS encapsulated addresses, i.e:
8873

89-
### tcp.close(callback)
74+
`/ip4/127.0.0.1/tcp/4001`
75+
`/ip4/127.0.0.1/tcp/4001/ipfs/QmHash`
9076

91-
Closes all the listening TCP servers, calling `callback` once all of them have
92-
been shut down.
77+
Both for dialing and listening.
9378

9479
## License
9580

package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
"tape": "^4.5.1"
4141
},
4242
"dependencies": {
43+
"duplexify": "^3.4.3",
4344
"ip-address": "^5.8.0",
4445
"lodash.contains": "^2.4.3",
4546
"mafmt": "^2.1.0",
@@ -53,4 +54,4 @@
5354
"Stephen Whitmore <[email protected]>",
5455
"dignifiedquire <[email protected]>"
5556
]
56-
}
57+
}

src/connection.js

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
'use strict'
2+
3+
const util = require('util')
4+
const Duplexify = require('duplexify')
5+
6+
module.exports = Connection
7+
8+
util.inherits(Connection, Duplexify)
9+
10+
function Connection (conn) {
11+
if (!(this instanceof Connection)) {
12+
return new Connection(conn)
13+
}
14+
15+
Duplexify.call(this)
16+
17+
let peerInfo
18+
19+
this.getPeerInfo = (callback) => {
20+
if (conn.getPeerInfo) {
21+
return conn.getPeerInfo(callback)
22+
}
23+
24+
if (!peerInfo) {
25+
return callback(new Error('Peer Info not set yet'))
26+
}
27+
28+
callback(null, peerInfo)
29+
}
30+
31+
this.setPeerInfo = (_peerInfo) => {
32+
if (conn.setPeerInfo) {
33+
return conn.setPeerInfo(_peerInfo)
34+
}
35+
peerInfo = _peerInfo
36+
}
37+
38+
this.getObservedAddrs = (callback) => {
39+
if (conn.getObservedAddrs) {
40+
return conn.getObservedAddrs(callback)
41+
}
42+
callback(null, [])
43+
}
44+
45+
this.setInnerConn = (conn) => {
46+
this.setReadable(conn)
47+
this.setWritable(conn)
48+
}
49+
50+
if (conn) {
51+
this.setInnerConn(conn)
52+
}
53+
}

src/index.js

+137-57
Original file line numberDiff line numberDiff line change
@@ -6,68 +6,169 @@ const tcp = require('net')
66
const multiaddr = require('multiaddr')
77
const Address6 = require('ip-address').Address6
88
const mafmt = require('mafmt')
9-
const parallel = require('run-parallel')
9+
// const parallel = require('run-parallel')
1010
const contains = require('lodash.contains')
11+
const os = require('os')
12+
const Connection = require('./connection')
1113

1214
exports = module.exports = TCP
1315

1416
const IPFS_CODE = 421
15-
const CLOSE_TIMEOUT = 300
17+
const CLOSE_TIMEOUT = 2000
1618

1719
function TCP () {
1820
if (!(this instanceof TCP)) {
1921
return new TCP()
2022
}
2123

22-
const listeners = []
23-
24-
this.dial = function (multiaddr, options) {
25-
if (!options) {
24+
this.dial = function (ma, options, callback) {
25+
if (typeof options === 'function') {
26+
callback = options
2627
options = {}
2728
}
28-
options.ready = options.ready || function noop () {}
29-
const conn = tcp.connect(multiaddr.toOptions(), options.ready)
29+
30+
if (!callback) {
31+
callback = function noop () {}
32+
}
33+
34+
const socket = tcp.connect(ma.toOptions())
35+
const conn = new Connection(socket)
3036
conn.getObservedAddrs = () => {
3137
return [multiaddr]
3238
}
39+
40+
socket.on('timeout', () => {
41+
conn.emit('timeout')
42+
})
43+
44+
socket.on('error', (err) => {
45+
callback(err)
46+
conn.emit('error', err)
47+
})
48+
49+
socket.on('connect', () => {
50+
callback(null, conn)
51+
conn.emit('connect')
52+
})
53+
54+
conn.getObservedAddrs = (cb) => {
55+
return cb(null, [ma])
56+
}
57+
3358
return conn
3459
}
3560

36-
this.createListener = (multiaddrs, handler, callback) => {
37-
if (!Array.isArray(multiaddrs)) {
38-
multiaddrs = [multiaddrs]
61+
this.createListener = (options, handler) => {
62+
if (typeof options === 'function') {
63+
handler = options
64+
options = {}
3965
}
4066

41-
const freshMultiaddrs = []
67+
const listener = tcp.createServer((socket) => {
68+
const conn = new Connection(socket)
69+
70+
conn.getObservedAddrs = (cb) => {
71+
return cb(null, [getMultiaddr(socket)])
72+
}
73+
handler(conn)
74+
})
4275

43-
parallel(multiaddrs.map((m) => (cb) => {
44-
let ipfsHashId
45-
if (contains(m.protoNames(), 'ipfs')) {
46-
ipfsHashId = m.stringTuples().filter((tuple) => {
76+
let ipfsId
77+
let listeningMultiaddr
78+
79+
listener._listen = listener.listen
80+
listener.listen = (ma, callback) => {
81+
listeningMultiaddr = ma
82+
if (contains(ma.protoNames(), 'ipfs')) {
83+
ipfsId = ma.stringTuples().filter((tuple) => {
4784
if (tuple[0] === IPFS_CODE) {
4885
return true
4986
}
5087
})[0][1]
51-
m = m.decapsulate('ipfs')
88+
listeningMultiaddr = ma.decapsulate('ipfs')
5289
}
5390

54-
const listener = tcp.createServer((conn) => {
55-
conn.getObservedAddrs = () => {
56-
return [getMultiaddr(conn)]
57-
}
58-
handler(conn)
59-
})
91+
listener._listen(listeningMultiaddr.toOptions(), callback)
92+
}
6093

61-
listener.__connections = {}
62-
listener.on('connection', (conn) => {
63-
const key = `${conn.remoteAddress}:${conn.remotePort}`
64-
listener.__connections[key] = conn
94+
listener._close = listener.close
95+
listener.close = (options, callback) => {
96+
if (typeof options === 'function') {
97+
callback = options
98+
options = {}
99+
}
100+
if (!callback) { callback = function noop () {} }
101+
if (!options) { options = {} }
65102

66-
conn.on('close', () => {
67-
delete listener.__connections[key]
103+
let closed = false
104+
listener._close(callback)
105+
listener.once('close', () => {
106+
closed = true
107+
})
108+
setTimeout(() => {
109+
if (closed) {
110+
return
111+
}
112+
log('unable to close graciously, destroying conns')
113+
Object.keys(listener.__connections).forEach((key) => {
114+
log('destroying %s', key)
115+
listener.__connections[key].destroy()
68116
})
117+
}, options.timeout || CLOSE_TIMEOUT)
118+
}
119+
120+
// Keep track of open connections to destroy in case of timeout
121+
listener.__connections = {}
122+
listener.on('connection', (socket) => {
123+
const key = `${socket.remoteAddress}:${socket.remotePort}`
124+
listener.__connections[key] = socket
125+
126+
socket.on('close', () => {
127+
delete listener.__connections[key]
69128
})
129+
})
130+
131+
listener.getAddrs = (callback) => {
132+
const multiaddrs = []
133+
const address = listener.address()
134+
135+
// Because TCP will only return the IPv6 version
136+
// we need to capture from the passed multiaddr
137+
if (listeningMultiaddr.toString().indexOf('ip4') !== -1) {
138+
let m = listeningMultiaddr.decapsulate('tcp')
139+
m = m.encapsulate('/tcp/' + address.port)
140+
if (ipfsId) {
141+
m = m.encapsulate('/ipfs/' + ipfsId)
142+
}
143+
144+
if (m.toString().indexOf('0.0.0.0') !== -1) {
145+
const netInterfaces = os.networkInterfaces()
146+
Object.keys(netInterfaces).forEach((niKey) => {
147+
netInterfaces[niKey].forEach((ni) => {
148+
if (ni.family === 'IPv4') {
149+
multiaddrs.push(multiaddr(m.toString().replace('0.0.0.0', ni.address)))
150+
}
151+
})
152+
})
153+
} else {
154+
multiaddrs.push(m)
155+
}
156+
}
157+
158+
if (address.family === 'IPv6') {
159+
let ma = multiaddr('/ip6/' + address.address + '/tcp/' + address.port)
160+
if (ipfsId) {
161+
ma = ma.encapsulate('/ipfs/' + ipfsId)
162+
}
163+
164+
multiaddrs.push(ma)
165+
}
166+
167+
callback(null, multiaddrs)
168+
}
70169

170+
return listener
171+
/*
71172
listener.listen(m.toOptions(), () => {
72173
// Node.js likes to convert addr to IPv6 (when 0.0.0.0 for e.g)
73174
const address = listener.address()
@@ -92,28 +193,7 @@ function TCP () {
92193
cb()
93194
})
94195
listeners.push(listener)
95-
}), (err) => {
96-
callback(err, freshMultiaddrs)
97-
})
98-
}
99-
100-
this.close = (callback) => {
101-
log('closing')
102-
if (listeners.length === 0) {
103-
log('Called close with no active listeners')
104-
return callback()
105-
}
106-
107-
parallel(listeners.map((listener) => (cb) => {
108-
setTimeout(() => {
109-
Object.keys(listener.__connections).forEach((key) => {
110-
log('destroying %s', key)
111-
listener.__connections[key].destroy()
112-
})
113-
}, CLOSE_TIMEOUT)
114-
115-
listener.close(cb)
116-
}), callback)
196+
*/
117197
}
118198

119199
this.filter = (multiaddrs) => {
@@ -129,19 +209,19 @@ function TCP () {
129209
}
130210
}
131211

132-
function getMultiaddr (conn) {
212+
function getMultiaddr (socket) {
133213
var mh
134214

135-
if (conn.remoteFamily === 'IPv6') {
136-
var addr = new Address6(conn.remoteAddress)
215+
if (socket.remoteFamily === 'IPv6') {
216+
var addr = new Address6(socket.remoteAddress)
137217
if (addr.v4) {
138218
var ip4 = addr.to4().correctForm()
139-
mh = multiaddr('/ip4/' + ip4 + '/tcp/' + conn.remotePort)
219+
mh = multiaddr('/ip4/' + ip4 + '/tcp/' + socket.remotePort)
140220
} else {
141-
mh = multiaddr('/ip6/' + conn.remoteAddress + '/tcp/' + conn.remotePort)
221+
mh = multiaddr('/ip6/' + socket.remoteAddress + '/tcp/' + socket.remotePort)
142222
}
143223
} else {
144-
mh = multiaddr('/ip4/' + conn.remoteAddress + '/tcp/' + conn.remotePort)
224+
mh = multiaddr('/ip4/' + socket.remoteAddress + '/tcp/' + socket.remotePort)
145225
}
146226

147227
return mh

0 commit comments

Comments
 (0)