From 3c5e0af0ce591719b5d3588a4edf570590f4fca7 Mon Sep 17 00:00:00 2001 From: Santiago Gimeno Date: Tue, 1 Nov 2022 11:20:11 +0100 Subject: [PATCH] net: handle socket.write(cb) edge case Make sure that when calling `write()` on a connecting socket, the callback is called if the socket is destroyed before the connection is established. Fixes: https://github.com/nodejs/node/issues/30841 --- lib/net.js | 5 ++++ test/parallel/test-net-write-cb-on-destroy.js | 24 +++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 test/parallel/test-net-write-cb-on-destroy.js diff --git a/lib/net.js b/lib/net.js index 9b0b1f87a636e5..cc80bb3a348da7 100644 --- a/lib/net.js +++ b/lib/net.js @@ -886,8 +886,13 @@ Socket.prototype._writeGeneric = function(writev, data, encoding, cb) { this._pendingData = data; this._pendingEncoding = encoding; this.once('connect', function connect() { + this.off('close', onClose); this._writeGeneric(writev, data, encoding, cb); }); + function onClose() { + cb(new ERR_SOCKET_CLOSED()); + } + this.once('close', onClose); return; } this._pendingData = null; diff --git a/test/parallel/test-net-write-cb-on-destroy.js b/test/parallel/test-net-write-cb-on-destroy.js new file mode 100644 index 00000000000000..92d1e58f3bfe8a --- /dev/null +++ b/test/parallel/test-net-write-cb-on-destroy.js @@ -0,0 +1,24 @@ +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); + +const server = net.createServer(); +server.listen(0, common.mustCall(() => { + const socket = new net.Socket(); + + socket.connect({ + port: server.address().port, + }); + + assert(socket.connecting); + + socket.write('foo', common.expectsError({ + code: 'ERR_SOCKET_CLOSED', + name: 'Error' + })); + + socket.destroy(); + server.close(); +}));