diff --git a/lib/processMultipart.js b/lib/processMultipart.js index de61e1d..990639b 100644 --- a/lib/processMultipart.js +++ b/lib/processMultipart.js @@ -31,11 +31,23 @@ module.exports = (options, req, res, next) => { const busboyOptions = buildOptions(options, { headers: req.headers }); const busboy = Busboy(busboyOptions); - // Close connection with specified reason and http code, default: 400 Bad Request. + /** + * Closes connection with specified reason and http code. + * @param {number} code HTTP response code, default: 400. + * @param {*} reason Reason to close connection, default: 'Bad Request'. + */ const closeConnection = (code, reason) => { req.unpipe(busboy); - res.writeHead(code || 400, { Connection: 'close' }); - res.end(reason || 'Bad Request'); + req.resume(); + if (res.headersSent) { + debugLog(options, 'Headers already sent, can\'t close connection.'); + return; + } + const resCode = code || 400; + const resReason = reason || 'Bad Request'; + debugLog(options, `Closing connection with ${resCode}: ${resReason}`); + res.writeHead(resCode, { Connection: 'close' }); + res.end(resReason); }; // Express proxies sometimes attach multipart data to a buffer @@ -87,11 +99,13 @@ module.exports = (options, req, res, next) => { // Reset upload timer in case of file limit reached. uploadTimer.clear(); // Run a user defined limit handler if it has been set. - if (isFunc(options.limitHandler)) return options.limitHandler(req, res, next); + if (isFunc(options.limitHandler)) { + options.limitHandler(req, res, next); + } // Close connection with 413 code and do cleanup if abortOnLimit set(default: false). if (options.abortOnLimit) { debugLog(options, `Aborting upload because of size limit ${field}->${filename}.`); - !isFunc(options.limitHandler) ? closeConnection(413, options.responseOnLimit) : ''; + closeConnection(413, options.responseOnLimit); cleanup(); } });