net: fix invalid write after end error

Don't error if not ended.

Fixes: https://github.com/nodejs/node/issues/36029

PR-URL: https://github.com/nodejs/node/pull/36043
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
This commit is contained in:
Robert Nagy 2020-11-08 19:56:56 +01:00 committed by Antoine du Hamel
parent f5c508c805
commit f7f0a6aa5d
3 changed files with 25 additions and 3 deletions

View File

@ -30,6 +30,7 @@ const {
NumberParseInt,
ObjectDefineProperty,
ObjectSetPrototypeOf,
ReflectApply,
Symbol,
} = primordials;
@ -434,6 +435,11 @@ function afterShutdown() {
// of the other side sending a FIN. The standard 'write after end'
// is overly vague, and makes it seem like the user's code is to blame.
function writeAfterFIN(chunk, encoding, cb) {
if (!this.writableEnded) {
return ReflectApply(
stream.Duplex.prototype.write, this, [chunk, encoding, cb]);
}
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
@ -947,7 +953,6 @@ Socket.prototype.connect = function(...args) {
this._unrefTimer();
this.connecting = true;
this.writable = true;
if (pipe) {
validateString(path, 'options.path');

View File

@ -0,0 +1,15 @@
'use strict';
const common = require('../common');
const assert = require('assert');
const net = require('net');
const server = net.createServer(common.mustCall(function(s) {
server.close();
s.end();
})).listen(0, 'localhost', common.mustCall(function() {
const socket = net.connect(this.address().port, 'localhost');
socket.on('end', common.mustCall(() => {
assert.strictEqual(socket.writable, true);
socket.write('hello world');
}));
}));

View File

@ -26,8 +26,10 @@ const server = net.createServer(function(sock) {
});
sock.on('end', function() {
gotServerEnd = true;
sock.write(serverData);
sock.end();
setImmediate(() => {
sock.write(serverData);
sock.end();
});
});
server.close();
});