Skip to content

Commit

Permalink
http: do not leak error listeners
Browse files Browse the repository at this point in the history
PR-URL: #43587
Fixes: #43548
Reviewed-By: Matteo Collina <[email protected]>
Reviewed-By: Luigi Pinca <[email protected]>
Reviewed-By: Ricky Zhou <[email protected]>
Reviewed-By: Mohammed Keyvanzadeh <[email protected]>
  • Loading branch information
ShogunPanda authored and ruyadorno committed Aug 22, 2022
1 parent 68ee8e9 commit 8c2d19b
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/_http_server.js
Original file line number Diff line number Diff line change
Expand Up @@ -766,7 +766,10 @@ const requestHeaderFieldsTooLargeResponse = Buffer.from(
function socketOnError(e) {
// Ignore further errors
this.removeListener('error', socketOnError);
this.on('error', noop);

if (this.listenerCount('error') === 0) {
this.on('error', noop);
}

if (!this.server.emit('clientError', e, this)) {
if (this.writable && this.bytesWritten === 0) {
Expand Down
44 changes: 44 additions & 0 deletions test/parallel/test-http-socket-listeners.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
'use strict';

const common = require('../common');
const assert = require('assert');
const http = require('http');
const net = require('net');

// This test sends an invalid character to a HTTP server and purposely
// does not handle clientError (even if it sets an event handler).
//
// The idea is to let the server emit multiple errors on the socket,
// mostly due to parsing error, and make sure they don't result
// in leaking event listeners.

let i = 0;
let socket;

process.on('warning', common.mustNotCall());

const server = http.createServer(common.mustNotCall());

server.on('clientError', common.mustCallAtLeast((err) => {
assert.strictEqual(err.code, 'HPE_INVALID_METHOD');
assert.strictEqual(err.rawPacket.toString(), '*');

if (i === 20) {
socket.end();
} else {
socket.write('*');
i++;
}
}, 1));

server.listen(0, () => {
socket = net.createConnection({ port: server.address().port });

socket.on('connect', () => {
socket.write('*');
});

socket.on('close', () => {
server.close();
});
});

0 comments on commit 8c2d19b

Please sign in to comment.