From 0161031c3e77574820e1246b020b96ddd2f7e0d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Jos=C3=A9=20Arboleda?= Date: Tue, 25 Oct 2022 10:44:08 -0500 Subject: [PATCH] lib: throws when invalid hex string in http request MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Juan José Arboleda --- lib/_http_outgoing.js | 6 ++++++ test/parallel/test-http-hex-write.js | 14 ++++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/_http_outgoing.js b/lib/_http_outgoing.js index a5b3863abaeebb..a2d5723a71c19f 100644 --- a/lib/_http_outgoing.js +++ b/lib/_http_outgoing.js @@ -334,6 +334,12 @@ OutgoingMessage.prototype.destroy = function destroy(error) { // This abstract either writing directly to the socket or buffering it. OutgoingMessage.prototype._send = function _send(data, encoding, callback) { + if (typeof data === 'string' && encoding === 'hex') { + if (data.length % 2 !== 0) { + throw new ERR_INVALID_ARG_VALUE('data', data, 'is invalid hex string'); + } + } + // This is a shameful hack to get the headers and first body chunk onto // the same packet. Future versions of Node are going to take care of // this at a lower level and in a more general way. diff --git a/test/parallel/test-http-hex-write.js b/test/parallel/test-http-hex-write.js index a3cbec6b36c0ad..363fbe0538edc2 100644 --- a/test/parallel/test-http-hex-write.js +++ b/test/parallel/test-http-hex-write.js @@ -27,12 +27,11 @@ const http = require('http'); const expect = 'hex\nutf8\n'; -http.createServer(function(q, s) { +const server = http.createServer(function(q, s) { s.setHeader('content-length', expect.length); s.write('6865780a', 'hex'); s.write('utf8\n'); s.end(); - this.close(); }).listen(0, common.mustCall(function() { http.request({ port: this.address().port }) .on('response', common.mustCall(function(res) { @@ -46,4 +45,15 @@ http.createServer(function(q, s) { assert.strictEqual(data, expect); })); })).end(); + + // Refs: https://github.com/nodejs/node/issues/45150 + const invalidReq = http.request({ port: this.address().port }); + assert.throws( + () => { invalidReq.write('boom!', 'hex'); }, + { + code: 'ERR_INVALID_ARG_VALUE', + message: 'The argument \'data\' is invalid hex string. Received \'boom!\'' + } + ); + invalidReq.end(() => server.close()); }));