diff --git a/lib/_http_server.js b/lib/_http_server.js index 8ea7cfbace9df0..aafc1a84849470 100644 --- a/lib/_http_server.js +++ b/lib/_http_server.js @@ -36,6 +36,7 @@ const httpSocketSetup = common.httpSocketSetup; const OutgoingMessage = require('_http_outgoing').OutgoingMessage; const { outHeadersKey, ondrain } = require('internal/http'); const errors = require('internal/errors'); +const Buffer = require('buffer').Buffer; const STATUS_CODES = { 100: 'Continue', @@ -449,13 +450,21 @@ function onParserExecute(server, socket, parser, state, ret, d) { onParserExecuteCommon(server, socket, parser, state, ret, undefined); } +const badRequestResponse = Buffer.from( + 'HTTP/1.1 400 ' + STATUS_CODES[400] + CRLF + CRLF, 'ascii' +); function socketOnError(e) { // Ignore further errors this.removeListener('error', socketOnError); this.on('error', () => {}); - if (!this.server.emit('clientError', e, this)) + if (!this.server.emit('clientError', e, this)) { + if (this.writable) { + this.end(badRequestResponse); + return; + } this.destroy(e); + } } function onParserExecuteCommon(server, socket, parser, state, ret, d) { diff --git a/test/parallel/test-http-blank-header.js b/test/parallel/test-http-blank-header.js index ff86193a1bad4a..40377fb6684db4 100644 --- a/test/parallel/test-http-blank-header.js +++ b/test/parallel/test-http-blank-header.js @@ -38,6 +38,7 @@ const server = http.createServer(common.mustCall((req, res) => { server.listen(0, common.mustCall(() => { const c = net.createConnection(server.address().port); + let received = ''; c.on('connect', common.mustCall(() => { c.write('GET /blah HTTP/1.1\r\n' + @@ -47,7 +48,12 @@ server.listen(0, common.mustCall(() => { '\r\n\r\nhello world' ); })); - - c.on('end', common.mustCall(() => c.end())); + c.on('data', common.mustCall((data) => { + received += data.toString(); + })); + c.on('end', common.mustCall(() => { + assert.strictEqual('HTTP/1.1 400 Bad Request\r\n\r\n', received); + c.end(); + })); c.on('close', common.mustCall(() => server.close())); }));