Skip to content

Commit

Permalink
[fix] Add proper response when handleUpgrade fails (#458)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
darrachequesne authored Dec 10, 2016
1 parent dd854a8 commit 7995509
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -321,8 +321,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;
}

Expand Down Expand Up @@ -455,3 +455,27 @@ Server.prototype.attach = function (server, options) {
});
}
};

/**
* Closes 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();
}

0 comments on commit 7995509

Please sign in to comment.