From 58d2cc66d72e74ea4950f87939d8b1d08a12d002 Mon Sep 17 00:00:00 2001 From: Matteo Collina Date: Tue, 28 Sep 2021 16:55:10 +0200 Subject: [PATCH] http: remove 'data' and 'end' listener if client parser error There might be the case of some more data coming through after the parser has returned an error and we have destroyed the socket. We should also be removing the 'data' event handler. Fixes: https://github.com/nodejs/node/issues/40242 --- lib/_http_client.js | 2 ++ test/parallel/test-http-client-parse-error.js | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/_http_client.js b/lib/_http_client.js index 280c6ebab76073..273460693b4561 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -489,6 +489,8 @@ function socketOnData(d) { prepareError(ret, parser, d); debug('parse error', ret); freeParser(parser, req, socket); + socket.removeListener('data', socketOnData); + socket.removeListener('end', socketOnEnd); socket.destroy(); req.socket._hadError = true; req.emit('error', ret); diff --git a/test/parallel/test-http-client-parse-error.js b/test/parallel/test-http-client-parse-error.js index 2c18bdbede0139..5d0ad4b1463ed5 100644 --- a/test/parallel/test-http-client-parse-error.js +++ b/test/parallel/test-http-client-parse-error.js @@ -23,6 +23,7 @@ const common = require('../common'); const http = require('http'); const net = require('net'); +const assert = require('assert'); const Countdown = require('../common/countdown'); const countdown = new Countdown(2, () => server.close()); @@ -38,10 +39,12 @@ const server = server.listen(0, common.mustCall(() => { for (let i = 0; i < 2; i++) { - http.get({ + const req = http.get({ port: server.address().port, path: '/' }).on('error', common.mustCall((e) => { + assert.strictEqual(req.socket.listenerCount('data'), 0); + assert.strictEqual(req.socket.listenerCount('end'), 1); common.expectsError({ code: 'HPE_INVALID_CONSTANT', message: 'Parse Error: Expected HTTP/'