Skip to content

Commit

Permalink
Include websocket non-upgrade response
Browse files Browse the repository at this point in the history
When the server do not accept the upgrade request for websockets the
response was previously not included and sent back. Now the proxy will
include the headers and the content from the server and the response in
these cases. Fixes http-party#890.

Change-Id: I6fc2745154e05585ca63309bb442afb60ee92082
  • Loading branch information
Tigge committed Jun 20, 2017
1 parent c979ba9 commit 087a8a6
Showing 1 changed file with 23 additions and 17 deletions.
40 changes: 23 additions & 17 deletions lib/http-proxy/passes/ws-incoming.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,24 @@ module.exports = {
* @api private
*/
stream : function stream(req, socket, options, head, server, clb) {

const 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);
Expand All @@ -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) {
Expand All @@ -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);

Expand Down

0 comments on commit 087a8a6

Please sign in to comment.