Skip to content

Commit

Permalink
Add headers on 'handshake'
Browse files Browse the repository at this point in the history
The headers in the 'handshake' event were not written to the socket, the client received data but not the headers.
  • Loading branch information
Ivan Jaramillo authored and indexzero committed Apr 21, 2013
1 parent 98f5c46 commit 985025c
Showing 1 changed file with 43 additions and 2 deletions.
45 changes: 43 additions & 2 deletions lib/node-http-proxy/http-proxy.js
Expand Up @@ -698,6 +698,15 @@ HttpProxy.prototype.proxyWebSocketRequest = function (req, socket, upgradeHead,
socket: socket,
head: head
};

//
// Here we set the handshake `headers` and `statusCode` data to the outgoing
// request so that we can reuse this data later.
//
reverseProxy.handshake = {
headers: {},
statusCode: null,
}

//
// If the agent for this particular `host` and `port` combination
Expand All @@ -707,7 +716,16 @@ HttpProxy.prototype.proxyWebSocketRequest = function (req, socket, upgradeHead,
// In addition, it's important to note the closure scope here. Since
// there is no mapping of the socket to the request bound to it.
//
reverseProxy.on('upgrade', function (_, remoteSocket, head) {
reverseProxy.on('upgrade', function ( res, remoteSocket, head) {

//
// Prepare handshake response 'headers' and 'statusCode'.
//
reverseProxy.handshake = {
headers: res.headers,
statusCode: res.statusCode,
}

//
// Prepare the socket for the reverseProxy request and begin to
// stream data between the two sockets. Here it is important to
Expand All @@ -723,6 +741,28 @@ HttpProxy.prototype.proxyWebSocketRequest = function (req, socket, upgradeHead,
//
reverseProxy.once('socket', function (revSocket) {
revSocket.on('data', function handshake (data) {

// Set empty headers
var headers = '';

//
// If the handshake statusCode 101, concat headers.
//
if(reverseProxy.handshake.statusCode && reverseProxy.handshake.statusCode == 101){

headers = [
'HTTP/1.1 101 Switching Protocols'
, 'Upgrade: websocket'
, 'Connection: Upgrade'
, 'Sec-WebSocket-Accept: ' + reverseProxy.handshake.headers['sec-websocket-accept']
];

headers = headers.concat('', '').join('\r\n');

}



//
// Ok, kind of harmfull part of code. Socket.IO sends a hash
// at the end of handshake if protocol === 76, but we need
Expand Down Expand Up @@ -752,7 +792,8 @@ HttpProxy.prototype.proxyWebSocketRequest = function (req, socket, upgradeHead,
// from the original incoming request.
//
self.emit('websocket:handshake', req, socket, head, sdata, data);
socket.write(sdata);
// add headers to the socket
socket.write(headers+sdata);
var flushed = socket.write(data);
if (!flushed) {
revSocket.pause();
Expand Down

0 comments on commit 985025c

Please sign in to comment.