From 30655bb87fb0117f3b64c719393e0466f90519b6 Mon Sep 17 00:00:00 2001 From: Damien Arrachequesne Date: Thu, 8 Dec 2016 00:30:39 +0100 Subject: [PATCH 1/2] Add proper response when handleUpgrade fails When the `verify` method fails, the current implementation closes the connection immediately, which is understood by some proxy (such as nginx) as if the server was not available (resulting in "upstream prematurely closed connection while reading response header from upstream" error). That commit make sure a proper response is sent before closing the connection. --- lib/server.js | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/lib/server.js b/lib/server.js index e2f379f34..8f2e811cf 100644 --- a/lib/server.js +++ b/lib/server.js @@ -329,8 +329,8 @@ Server.prototype.handleUpgrade = function (req, socket, upgradeHead) { var self = this; this.verify(req, true, function (err, success) { - if (err) { - socket.end(); + if (!success) { + abortConnection(socket, err); return; } @@ -463,3 +463,27 @@ Server.prototype.attach = function (server, options) { }); } }; + +/** + * Close the connection + * + * @param {net.Socket} socket + * @param {code} error code + * @api private + */ + +function abortConnection (socket, code) { + if (socket.writable) { + var message = Server.errorMessages.hasOwnProperty(code) ? Server.errorMessages[code] : code; + var length = Buffer.byteLength(message); + socket.write( + 'HTTP/1.1 400 Bad Request\r\n' + + 'Connection: close\r\n' + + 'Content-type: text/html\r\n' + + 'Content-Length: ' + length + '\r\n' + + '\r\n' + + message + ); + } + socket.destroy(); +} From a6e9570db59352dffc1c6bb4e99ddf59f82896f6 Mon Sep 17 00:00:00 2001 From: Damien Arrachequesne Date: Thu, 8 Dec 2016 00:52:21 +0100 Subject: [PATCH 2/2] grammar --- lib/server.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/server.js b/lib/server.js index 8f2e811cf..791b80fe1 100644 --- a/lib/server.js +++ b/lib/server.js @@ -465,7 +465,7 @@ Server.prototype.attach = function (server, options) { }; /** - * Close the connection + * Closes the connection * * @param {net.Socket} socket * @param {code} error code