Skip to content

Commit 7995509

Browse files
[fix] Add proper response when handleUpgrade fails (#458)
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.
1 parent dd854a8 commit 7995509

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

lib/server.js

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -321,8 +321,8 @@ Server.prototype.handleUpgrade = function (req, socket, upgradeHead) {
321321

322322
var self = this;
323323
this.verify(req, true, function (err, success) {
324-
if (err) {
325-
socket.end();
324+
if (!success) {
325+
abortConnection(socket, err);
326326
return;
327327
}
328328

@@ -455,3 +455,27 @@ Server.prototype.attach = function (server, options) {
455455
});
456456
}
457457
};
458+
459+
/**
460+
* Closes the connection
461+
*
462+
* @param {net.Socket} socket
463+
* @param {code} error code
464+
* @api private
465+
*/
466+
467+
function abortConnection (socket, code) {
468+
if (socket.writable) {
469+
var message = Server.errorMessages.hasOwnProperty(code) ? Server.errorMessages[code] : code;
470+
var length = Buffer.byteLength(message);
471+
socket.write(
472+
'HTTP/1.1 400 Bad Request\r\n' +
473+
'Connection: close\r\n' +
474+
'Content-type: text/html\r\n' +
475+
'Content-Length: ' + length + '\r\n' +
476+
'\r\n' +
477+
message
478+
);
479+
}
480+
socket.destroy();
481+
}

0 commit comments

Comments
 (0)