@@ -12,6 +12,7 @@ const toPull = require('stream-to-pull-stream')
12
12
const getMultiaddr = require ( './get-multiaddr' )
13
13
14
14
const IPFS_CODE = 421
15
+ const CLOSE_TIMEOUT = 2000
15
16
16
17
module . exports = ( handler ) => {
17
18
const listener = net . createServer ( ( socket ) => {
@@ -24,7 +25,41 @@ module.exports = (handler) => {
24
25
handler ( conn )
25
26
} )
26
27
28
+ // Keep track of open connections to destroy in case of timeout
27
29
listener . __connections = { }
30
+ listener . on ( 'connection' , ( socket ) => {
31
+ const key = `${ socket . remoteAddress } :${ socket . remotePort } `
32
+ listener . __connections [ key ] = socket
33
+
34
+ socket . on ( 'close' , ( ) => {
35
+ delete listener . __connections [ key ]
36
+ } )
37
+ } )
38
+
39
+ listener . _close = listener . close
40
+ listener . close = ( options , cb ) => {
41
+ if ( typeof options === 'function' ) {
42
+ cb = options
43
+ options = { }
44
+ }
45
+ cb = cb || ( ( ) => { } )
46
+ options = options || { }
47
+
48
+ let closed = false
49
+ listener . _close ( cb )
50
+ listener . once ( 'close' , ( ) => {
51
+ closed = true
52
+ } )
53
+ setTimeout ( ( ) => {
54
+ if ( closed ) return
55
+
56
+ log ( 'unable to close graciously, destroying conns' )
57
+ Object . keys ( listener . __connections ) . forEach ( ( key ) => {
58
+ log ( 'destroying %s' , key )
59
+ listener . __connections [ key ] . destroy ( )
60
+ } )
61
+ } , options . timeout || CLOSE_TIMEOUT )
62
+ }
28
63
let ipfsId
29
64
let listeningAddr
30
65
@@ -41,10 +76,14 @@ module.exports = (handler) => {
41
76
return listener . _listen ( lOpts . port , lOpts . host , cb )
42
77
}
43
78
44
- listener . getAddrs = ( callback ) => {
79
+ listener . getAddrs = ( cb ) => {
45
80
const multiaddrs = [ ]
46
81
const address = listener . address ( )
47
82
83
+ if ( ! address ) {
84
+ return cb ( new Error ( 'Listener is not ready yet' ) )
85
+ }
86
+
48
87
// Because TCP will only return the IPv6 version
49
88
// we need to capture from the passed multiaddr
50
89
if ( listeningAddr . toString ( ) . indexOf ( 'ip4' ) !== - 1 ) {
@@ -77,7 +116,7 @@ module.exports = (handler) => {
77
116
multiaddrs . push ( ma )
78
117
}
79
118
80
- callback ( null , multiaddrs )
119
+ cb ( null , multiaddrs )
81
120
}
82
121
83
122
return listener
0 commit comments