From 539904741bec4ef0763b8bfb7c4bdbd3ba36c8a6 Mon Sep 17 00:00:00 2001 From: Oliver Moran Date: Thu, 22 Apr 2021 22:22:48 +0100 Subject: [PATCH] Add error handling when parsing headers --- cgi.js | 15 +++++++++++++++ parser.js | 5 +++++ 2 files changed, 20 insertions(+) diff --git a/cgi.js b/cgi.js index 411cd50..63e03bf 100644 --- a/cgi.js +++ b/cgi.js @@ -122,9 +122,24 @@ function cgi(cgiBin, options) { if (!options.nph) { cgiResult = new CGIParser(cgiSpawn.stdout); + // When the parser encounters an error parsing the headers, then + // the 'error' event is emitted with an Error instance. + var headersHaveError = false; + cgiResult.on('error', function(err){ + headersHaveError = true; + if (options.stderr) { + options.stderr.write(err.toString()); + } else { + throw(err); + } + }); + // When the blank line after the headers has been parsed, then // the 'headers' event is emitted with a Headers instance. cgiResult.on('headers', function(headers) { + // Prevent sending anything if there was an error parsing the headers + if (headersHaveError) return; + headers.forEach(function(header) { // Don't set the 'Status' header. It's special, and should be // used to set the HTTP response code below. diff --git a/parser.js b/parser.js index aa4f662..1f4de6b 100644 --- a/parser.js +++ b/parser.js @@ -19,6 +19,7 @@ function Parser(stream) { allowFoldedHeaders: false }); this._headerParser.on('headers', this._onHeadersComplete.bind(this)); + this._headerParser.on('error', this._onHeadersError.bind(this)); } require('util').inherits(Parser, StreamStack); module.exports = Parser; @@ -38,3 +39,7 @@ Parser.prototype._onHeadersComplete = function(headers, leftover) { this._onData(leftover); } } + +Parser.prototype._onHeadersError = function(err) { + this.emit('error', err); +}