diff --git a/lib/net.js b/lib/net.js index 5cf28556778..6802b66a980 100644 --- a/lib/net.js +++ b/lib/net.js @@ -1198,8 +1198,11 @@ Socket.prototype._destroy = function(exception, cb) { debug('emit close'); this.emit('close', isException); }); - if (err) + if (err) { + // The handle is still open: close it normally. + closeSocketHandle(this, isException); this.emit('error', new ErrnoException(err, 'reset')); + } } else if (this._closeAfterHandlingError) { // Enqueue closing the socket as a microtask, so that the socket can be // accessible when an `error` event is handled in the `next tick queue`. diff --git a/src/tcp_wrap.cc b/src/tcp_wrap.cc index 68439487700..2ab2630d1e3 100644 --- a/src/tcp_wrap.cc +++ b/src/tcp_wrap.cc @@ -624,8 +624,11 @@ int TCPWrap::Reset(Local close_callback) { if (state_ != kInitialized) return 0; int err = uv_tcp_close_reset(&handle_, OnClose); + // The handle is not closing on failure. + if (err != 0) return err; + state_ = kClosing; - if (!err & !close_callback.IsEmpty() && close_callback->IsFunction() && + if (!close_callback.IsEmpty() && close_callback->IsFunction() && !persistent().IsEmpty()) { object() ->Set(env()->context(), env()->handle_onclose_symbol(), close_callback) diff --git a/test/parallel/test-net-socket-reset-after-end.js b/test/parallel/test-net-socket-reset-after-end.js new file mode 100644 index 00000000000..7a91b6d9e34 --- /dev/null +++ b/test/parallel/test-net-socket-reset-after-end.js @@ -0,0 +1,28 @@ +'use strict'; + +// resetAndDestroy() right after end() fails with EINVAL. The socket must +// still close. + +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); + +const server = net.createServer(common.mustCall((socket) => { + socket.on('error', common.mustCall((err) => { + assert.strictEqual(err.code, 'EINVAL'); + assert.strictEqual(err.syscall, 'reset'); + })); + socket.on('close', common.mustCall(() => { + assert.strictEqual(socket.destroyed, true); + })); + + socket.end('bye'); + socket.resetAndDestroy(); + server.close(); +})); + +server.listen(0, common.mustCall(() => { + const client = net.connect(server.address().port); + client.resume(); + client.on('close', common.mustCall()); +}));