In Node.js, both http.Server
and https.Sever
emit the clientError
event, but with different arguments:
http.Server#clientError(exception, cocket)
https.Server#clientError(exception, securePair)
With securePair
being an instance of tls.SecurePair
, securePair.cleartext
a tls.CleartextStream
and securePair.encrypted
a tls.CryptoStream
.
The question is, how do I get the address and port of the client that caused the clientError
? In theory, this should work:
socket = securePair.cleartext.socket;
console.log(socket.remoteAddress + ':' + socket.remotePort);
In reality, when I try to connect to the HTTPS server using HTTP (pretending it were a HTTP server) and cancelling after a few seconds, I get a clientError
of type ECONNRESET
, but socket.remoteAddress
and socket.remotePort
are both undefined
(even though securePair.cleartext.socket
is indeed a net.Socket
and not undefined
).
Unfortunately, bounty did not seem to help much :-( I had to investigate this myself.
Apparently, a fix has been made (but is not yet in any released node.js) to be able to get these values even after socket has been closed: https://github.com/joyent/node/commit/8c38b07252d86f4eef91344f8df4f0c3e38bca35
A workaround is to store the address at connect time:
srv.on('connect', function (socket) {
socket.stored_remoteAddress = socket.remoteAddress;
});
srv.on('clientError', function (err, socket) {
console.log(socket.cleartext.socket.stored_remoteAddress);
}
This works, but is not pretty.
Apparently, even this does not work fully :-(
Node.js 0.11 does not emit the 'clientError' event on SSL errors (for example), so there's no way to catch the situation there.
Node.js 0.12 emits the 'clientError' event, but uses a new TLS implementation which does not have the 'cleartext' socket available anymore. I could not find any way to pass information from 'connect' event to 'clientError' event, or any way to find out that they are for the same socket (as the socket is already closed in the 'clientError' event).
So, it would seem that the only way is to wait for a new Node.js release (0.12.2 earliest, if they think this is worth a fix) and hope this gets fixed for real.