From cf54b0a48a83383f1cc9770ca69d2df306e554e6 Mon Sep 17 00:00:00 2001 From: Gustav Tiger Date: Tue, 20 Jun 2017 13:38:28 +0200 Subject: [PATCH] Include websocket non-upgrade response When the server do not accept the upgrade request for websockets the server's response was previously not included and sent back. Now the proxy will include the response in these cases. Fixes #890. Change-Id: I142a15ee12603f54d611ae9362a94c62fb3c9f36 --- lib/http-proxy/passes/ws-incoming.js | 40 ++++++++++++++++------------ test/lib-http-proxy-test.js | 1 - 2 files changed, 23 insertions(+), 18 deletions(-) diff --git a/lib/http-proxy/passes/ws-incoming.js b/lib/http-proxy/passes/ws-incoming.js index cf3796cde..270f23f45 100644 --- a/lib/http-proxy/passes/ws-incoming.js +++ b/lib/http-proxy/passes/ws-incoming.js @@ -77,6 +77,24 @@ module.exports = { * @api private */ stream : function stream(req, socket, options, head, server, clb) { + + var createHttpHeader = function(line, headers) { + return Object.keys(headers).reduce(function (head, key) { + var value = headers[key]; + + if (!Array.isArray(value)) { + head.push(key + ': ' + value); + return head; + } + + for (var i = 0; i < value.length; i++) { + head.push(key + ': ' + value[i]); + } + return head; + }, [line]) + .join('\r\n') + '\r\n\r\n'; + } + common.setupSocket(socket); if (head && head.length) socket.unshift(head); @@ -93,7 +111,10 @@ module.exports = { proxyReq.on('error', onOutgoingError); proxyReq.on('response', function (res) { // if upgrade event isn't going to happen, close the socket - if (!res.upgrade) socket.end(); + if (!res.upgrade) { + socket.write(createHttpHeader('HTTP/' + res.httpVersion + ' ' + res.statusCode + ' ' + res.statusMessage, res.headers)); + res.pipe(socket); + } }); proxyReq.on('upgrade', function(proxyRes, proxySocket, proxyHead) { @@ -119,22 +140,7 @@ module.exports = { // Remark: Handle writing the headers to the socket when switching protocols // Also handles when a header is an array // - socket.write( - Object.keys(proxyRes.headers).reduce(function (head, key) { - var value = proxyRes.headers[key]; - - if (!Array.isArray(value)) { - head.push(key + ': ' + value); - return head; - } - - for (var i = 0; i < value.length; i++) { - head.push(key + ': ' + value[i]); - } - return head; - }, ['HTTP/1.1 101 Switching Protocols']) - .join('\r\n') + '\r\n\r\n' - ); + socket.write(createHttpHeader('HTTP/1.1 101 Switching Protocols', proxyRes.headers)); proxySocket.pipe(socket).pipe(proxySocket); diff --git a/test/lib-http-proxy-test.js b/test/lib-http-proxy-test.js index ec6273f94..b507a0052 100644 --- a/test/lib-http-proxy-test.js +++ b/test/lib-http-proxy-test.js @@ -415,7 +415,6 @@ describe('lib/http-proxy.js', function() { client.on('error', function (err) { expect(err).to.be.an(Error); - expect(err.code).to.be('ECONNRESET'); proxyServer.close(); done(); });