Skip to content

Commit

Permalink
net: handle socket.write(cb) edge case
Browse files Browse the repository at this point in the history
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: #30841
  • Loading branch information
santigimeno committed Dec 20, 2022
1 parent 7738844 commit 3c5e0af
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/net.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
24 changes: 24 additions & 0 deletions test/parallel/test-net-write-cb-on-destroy.js
Original file line number Diff line number Diff line change
@@ -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();
}));

0 comments on commit 3c5e0af

Please sign in to comment.