2016-09-27 21:56:06 +00:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
var sni = require('sni');
|
|
|
|
var url = require('url');
|
2017-09-08 17:24:30 +00:00
|
|
|
var PromiseA = require('bluebird');
|
2016-09-27 21:56:06 +00:00
|
|
|
var jwt = require('jsonwebtoken');
|
2016-09-28 05:26:16 +00:00
|
|
|
var packer = require('tunnel-packer');
|
|
|
|
|
2017-09-08 17:24:30 +00:00
|
|
|
function timeoutPromise(duration) {
|
|
|
|
return new PromiseA(function (resolve) {
|
|
|
|
setTimeout(resolve, duration);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-04-05 02:31:58 +00:00
|
|
|
var Devices = {};
|
2017-04-07 17:52:25 +00:00
|
|
|
Devices.add = function (store, servername, newDevice) {
|
2017-05-26 22:33:27 +00:00
|
|
|
var devices = store[servername] || [];
|
2017-04-07 17:52:25 +00:00
|
|
|
devices.push(newDevice);
|
|
|
|
store[servername] = devices;
|
2017-04-05 02:31:58 +00:00
|
|
|
};
|
2017-04-07 17:52:25 +00:00
|
|
|
Devices.remove = function (store, servername, device) {
|
2017-05-26 22:33:27 +00:00
|
|
|
var devices = store[servername] || [];
|
2017-04-07 17:52:25 +00:00
|
|
|
var index = devices.indexOf(device);
|
|
|
|
|
|
|
|
if (index < 0) {
|
2017-04-27 01:52:30 +00:00
|
|
|
console.warn('attempted to remove non-present device', device.deviceId, 'from', servername);
|
2017-04-07 17:52:25 +00:00
|
|
|
return null;
|
|
|
|
}
|
|
|
|
return devices.splice(index, 1)[0];
|
2017-04-05 02:31:58 +00:00
|
|
|
};
|
|
|
|
Devices.list = function (store, servername) {
|
2017-06-05 17:00:54 +00:00
|
|
|
if (store[servername] && store[servername].length) {
|
2017-05-26 22:33:27 +00:00
|
|
|
return store[servername];
|
|
|
|
}
|
|
|
|
// There wasn't an exact match so check any of the wildcard domains, sorted longest
|
|
|
|
// first so the one with the biggest natural match with be found first.
|
|
|
|
var deviceList = [];
|
|
|
|
Object.keys(store).filter(function (pattern) {
|
2017-05-27 00:18:06 +00:00
|
|
|
return pattern[0] === '*' && store[pattern].length;
|
2017-05-26 22:33:27 +00:00
|
|
|
}).sort(function (a, b) {
|
|
|
|
return b.length - a.length;
|
|
|
|
}).some(function (pattern) {
|
|
|
|
var subPiece = pattern.slice(1);
|
|
|
|
if (subPiece === servername.slice(-subPiece.length)) {
|
|
|
|
console.log('"'+servername+'" matches "'+pattern+'"');
|
|
|
|
deviceList = store[pattern];
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
return deviceList;
|
2017-04-05 02:31:58 +00:00
|
|
|
};
|
|
|
|
Devices.exist = function (store, servername) {
|
2017-05-26 22:33:27 +00:00
|
|
|
return !!(Devices.list(store, servername).length);
|
2017-04-05 02:31:58 +00:00
|
|
|
};
|
|
|
|
Devices.next = function (store, servername) {
|
|
|
|
var devices = Devices.list(store, servername);
|
2017-04-05 07:01:43 +00:00
|
|
|
var device;
|
2017-04-05 02:31:58 +00:00
|
|
|
|
|
|
|
if (devices._index >= devices.length) {
|
|
|
|
devices._index = 0;
|
|
|
|
}
|
2017-04-05 07:01:43 +00:00
|
|
|
device = devices[devices._index || 0];
|
2017-04-05 02:31:58 +00:00
|
|
|
devices._index = (devices._index || 0) + 1;
|
|
|
|
|
2017-04-05 07:01:43 +00:00
|
|
|
return device;
|
2017-04-05 02:31:58 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
module.exports.store = { Devices: Devices };
|
2016-10-13 00:16:14 +00:00
|
|
|
module.exports.create = function (copts) {
|
2017-04-05 02:31:58 +00:00
|
|
|
var deviceLists = {};
|
2017-04-07 21:46:00 +00:00
|
|
|
var activityTimeout = copts.activityTimeout || 2*60*1000;
|
|
|
|
var pongTimeout = copts.pongTimeout || 10*1000;
|
2016-09-27 21:56:06 +00:00
|
|
|
|
2018-04-24 16:34:20 +00:00
|
|
|
function onWsConnection(ws, upgradeReq) {
|
|
|
|
console.log(ws);
|
|
|
|
var socketId = packer.socketToId(upgradeReq.socket);
|
2017-04-27 01:52:30 +00:00
|
|
|
var remotes = {};
|
2017-04-05 02:31:58 +00:00
|
|
|
|
2017-04-27 01:52:30 +00:00
|
|
|
function logName() {
|
|
|
|
var result = Object.keys(remotes).map(function (jwtoken) {
|
|
|
|
return remotes[jwtoken].deviceId;
|
|
|
|
}).join(';');
|
2016-09-30 19:15:58 +00:00
|
|
|
|
2017-04-27 01:52:30 +00:00
|
|
|
return result || socketId;
|
2016-09-27 21:56:06 +00:00
|
|
|
}
|
2017-09-07 23:10:47 +00:00
|
|
|
function sendTunnelMsg(addr, data, service) {
|
|
|
|
ws.send(packer.pack(addr, data, service), {binary: true});
|
|
|
|
}
|
2016-09-27 21:56:06 +00:00
|
|
|
|
2017-09-07 00:43:34 +00:00
|
|
|
function getBrowserConn(cid) {
|
|
|
|
var browserConn;
|
2017-04-27 01:52:30 +00:00
|
|
|
Object.keys(remotes).some(function (jwtoken) {
|
|
|
|
if (remotes[jwtoken].clients[cid]) {
|
2017-09-07 00:43:34 +00:00
|
|
|
browserConn = remotes[jwtoken].clients[cid];
|
2017-04-27 01:52:30 +00:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
});
|
2017-04-26 18:05:44 +00:00
|
|
|
|
2017-09-07 00:43:34 +00:00
|
|
|
return browserConn;
|
2017-04-26 18:05:44 +00:00
|
|
|
}
|
2017-09-08 17:24:30 +00:00
|
|
|
function closeBrowserConn(cid) {
|
|
|
|
var remote;
|
|
|
|
Object.keys(remotes).some(function (jwtoken) {
|
|
|
|
if (remotes[jwtoken].clients[cid]) {
|
|
|
|
remote = remotes[jwtoken];
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
if (!remote) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
PromiseA.resolve().then(function () {
|
|
|
|
var conn = remote.clients[cid];
|
|
|
|
conn.tunnelClosing = true;
|
|
|
|
conn.end();
|
|
|
|
|
|
|
|
// If no data is buffered for writing then we don't need to wait for it to drain.
|
|
|
|
if (!conn.bufferSize) {
|
|
|
|
return timeoutPromise(500);
|
|
|
|
}
|
|
|
|
// Otherwise we want the connection to be able to finish, but we also want to impose
|
|
|
|
// a time limit for it to drain, since it shouldn't have more than 1MB buffered.
|
|
|
|
return new PromiseA(function (resolve) {
|
|
|
|
var timeoutId = setTimeout(resolve, 60*1000);
|
|
|
|
conn.once('drain', function () {
|
|
|
|
clearTimeout(timeoutId);
|
|
|
|
setTimeout(resolve, 500);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}).then(function () {
|
|
|
|
if (remote.clients[cid]) {
|
|
|
|
console.warn(cid, 'browser connection still present after calling `end`');
|
|
|
|
remote.clients[cid].destroy();
|
|
|
|
return timeoutPromise(500);
|
|
|
|
}
|
|
|
|
}).then(function () {
|
|
|
|
if (remote.clients[cid]) {
|
|
|
|
console.error(cid, 'browser connection still present after calling `destroy`');
|
|
|
|
delete remote.clients[cid];
|
|
|
|
}
|
|
|
|
}).catch(function (err) {
|
|
|
|
console.warn('failed to close browser connection', cid, err);
|
|
|
|
});
|
|
|
|
}
|
2017-04-26 18:05:44 +00:00
|
|
|
|
2017-04-27 01:52:30 +00:00
|
|
|
function addToken(jwtoken) {
|
|
|
|
if (remotes[jwtoken]) {
|
2017-04-28 01:36:28 +00:00
|
|
|
// return { message: "token sent multiple times", code: "E_TOKEN_REPEAT" };
|
|
|
|
return null;
|
2017-04-27 01:52:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var token;
|
|
|
|
try {
|
|
|
|
token = jwt.verify(jwtoken, copts.secret);
|
|
|
|
} catch (e) {
|
|
|
|
token = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!token) {
|
2017-04-28 01:36:28 +00:00
|
|
|
return { message: "invalid access token", code: "E_INVALID_TOKEN" };
|
2017-04-27 01:52:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (!Array.isArray(token.domains)) {
|
|
|
|
if ('string' === typeof token.name) {
|
|
|
|
token.domains = [ token.name ];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-05-26 22:33:27 +00:00
|
|
|
if (!Array.isArray(token.domains) || !token.domains.length) {
|
2017-04-28 01:36:28 +00:00
|
|
|
return { message: "invalid server name", code: "E_INVALID_NAME" };
|
2017-04-27 01:52:30 +00:00
|
|
|
}
|
|
|
|
if (token.domains.some(function (name) { return typeof name !== 'string'; })) {
|
2017-04-28 01:36:28 +00:00
|
|
|
return { message: "invalid server name", code: "E_INVALID_NAME" };
|
2017-04-27 01:52:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Add the custom properties we need to manage this remote, then add it to all the relevant
|
|
|
|
// domains and the list of all this websocket's remotes.
|
|
|
|
token.deviceId = (token.device && (token.device.id || token.device.hostname)) || token.domains.join(',');
|
|
|
|
token.ws = ws;
|
2018-04-24 16:34:20 +00:00
|
|
|
token.upgradeReq = upgradeReq;
|
2017-04-27 01:52:30 +00:00
|
|
|
token.clients = {};
|
|
|
|
|
2017-09-07 23:10:47 +00:00
|
|
|
token.pausedConns = [];
|
|
|
|
ws._socket.on('drain', function () {
|
2017-09-11 21:45:17 +00:00
|
|
|
// the websocket library has it's own buffer apart from node's socket buffer, but that one
|
|
|
|
// is much more difficult to watch, so we watch for the lower level buffer to drain and
|
|
|
|
// then check to see if the upper level buffer is still too full to write to. Note that
|
|
|
|
// the websocket library buffer has something to do with compression, so I'm not requiring
|
|
|
|
// that to be 0 before we start up again.
|
|
|
|
if (ws.bufferedAmount > 128*1024) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2017-09-07 23:10:47 +00:00
|
|
|
token.pausedConns.forEach(function (conn) {
|
|
|
|
if (!conn.manualPause) {
|
2017-09-11 21:45:17 +00:00
|
|
|
// console.log('resuming', conn.tunnelCid, 'now that the web socket has caught up');
|
2017-09-07 23:10:47 +00:00
|
|
|
conn.resume();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
token.pausedConns.length = 0;
|
|
|
|
});
|
|
|
|
|
2017-04-27 01:52:30 +00:00
|
|
|
token.domains.forEach(function (domainname) {
|
|
|
|
console.log('domainname', domainname);
|
|
|
|
Devices.add(deviceLists, domainname, token);
|
|
|
|
});
|
|
|
|
remotes[jwtoken] = token;
|
|
|
|
console.log("added token '" + token.deviceId + "' to websocket", socketId);
|
2017-04-28 01:36:28 +00:00
|
|
|
return null;
|
2017-04-27 01:52:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function removeToken(jwtoken) {
|
|
|
|
var remote = remotes[jwtoken];
|
|
|
|
if (!remote) {
|
2017-04-28 01:36:28 +00:00
|
|
|
return { message: 'specified token not present', code: 'E_INVALID_TOKEN'};
|
2017-04-27 01:52:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Prevent any more browser connections being sent to this remote, and any existing
|
|
|
|
// connections from trying to send more data across the connection.
|
|
|
|
remote.domains.forEach(function (domainname) {
|
|
|
|
Devices.remove(deviceLists, domainname, remote);
|
|
|
|
});
|
|
|
|
remote.ws = null;
|
2018-04-24 16:34:20 +00:00
|
|
|
remote.upgradeReq = null;
|
2017-04-27 01:52:30 +00:00
|
|
|
|
|
|
|
// Close all of the existing browser connections associated with this websocket connection.
|
|
|
|
Object.keys(remote.clients).forEach(function (cid) {
|
2017-09-08 17:24:30 +00:00
|
|
|
closeBrowserConn(cid);
|
2017-04-27 01:52:30 +00:00
|
|
|
});
|
|
|
|
delete remotes[jwtoken];
|
|
|
|
console.log("removed token '" + remote.deviceId + "' from websocket", socketId);
|
2017-04-28 01:36:28 +00:00
|
|
|
return null;
|
2017-04-27 01:52:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var firstToken;
|
2018-04-24 16:34:20 +00:00
|
|
|
var authn = (upgradeReq.headers.authorization||'').split(/\s+/);
|
2017-04-27 01:52:30 +00:00
|
|
|
if (authn[0] && 'basic' === authn[0].toLowerCase()) {
|
|
|
|
try {
|
|
|
|
authn = new Buffer(authn[1], 'base64').toString('ascii').split(':');
|
|
|
|
firstToken = authn[1];
|
|
|
|
} catch (err) { }
|
|
|
|
}
|
|
|
|
if (!firstToken) {
|
2018-04-24 16:34:20 +00:00
|
|
|
firstToken = url.parse(upgradeReq.url, true).query.access_token;
|
2017-04-27 01:52:30 +00:00
|
|
|
}
|
2017-04-28 01:36:28 +00:00
|
|
|
if (firstToken) {
|
|
|
|
var err = addToken(firstToken);
|
|
|
|
if (err) {
|
2017-09-07 23:10:47 +00:00
|
|
|
sendTunnelMsg(null, [0, err], 'control');
|
2017-04-28 01:36:28 +00:00
|
|
|
ws.close();
|
|
|
|
return;
|
|
|
|
}
|
2017-04-27 01:52:30 +00:00
|
|
|
}
|
|
|
|
|
2017-04-28 18:50:50 +00:00
|
|
|
var commandHandlers = {
|
|
|
|
add_token: addToken
|
|
|
|
, delete_token: function (token) {
|
|
|
|
if (token !== '*') {
|
|
|
|
return removeToken(token);
|
|
|
|
}
|
|
|
|
var err;
|
|
|
|
Object.keys(remotes).some(function (jwtoken) {
|
|
|
|
err = removeToken(jwtoken);
|
|
|
|
return err;
|
|
|
|
});
|
|
|
|
return err;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
var packerHandlers = {
|
2017-04-28 01:36:28 +00:00
|
|
|
oncontrol: function (opts) {
|
|
|
|
var cmd, err;
|
|
|
|
try {
|
|
|
|
cmd = JSON.parse(opts.data.toString());
|
|
|
|
} catch (err) {}
|
|
|
|
if (!Array.isArray(cmd) || typeof cmd[0] !== 'number') {
|
2017-04-28 20:19:56 +00:00
|
|
|
var msg = 'received bad command "' + opts.data.toString() + '"';
|
|
|
|
console.warn(msg, 'from websocket', socketId);
|
2017-09-07 23:10:47 +00:00
|
|
|
sendTunnelMsg(null, [0, {message: msg, code: 'E_BAD_COMMAND'}], 'control');
|
2017-04-28 01:36:28 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (cmd[0] < 0) {
|
2017-04-28 18:50:50 +00:00
|
|
|
// We only ever send one command and we send it once, so we just hard coded the ID as 1.
|
|
|
|
if (cmd[0] === -1) {
|
|
|
|
if (cmd[1]) {
|
|
|
|
console.log('received error response to hello from', socketId, cmd[1]);
|
|
|
|
}
|
2017-04-28 01:36:28 +00:00
|
|
|
}
|
|
|
|
else {
|
2017-04-28 18:50:50 +00:00
|
|
|
console.warn('received response to unknown command', cmd, 'from', socketId);
|
2017-04-28 01:36:28 +00:00
|
|
|
}
|
2017-04-28 18:50:50 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2017-04-28 20:19:56 +00:00
|
|
|
if (cmd[0] === 0) {
|
|
|
|
console.warn('received dis-associated error from', socketId, cmd[1]);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2017-04-28 18:50:50 +00:00
|
|
|
if (commandHandlers[cmd[1]]) {
|
|
|
|
err = commandHandlers[cmd[1]].apply(null, cmd.slice(2));
|
2017-04-28 01:36:28 +00:00
|
|
|
}
|
|
|
|
else {
|
2017-04-28 18:50:50 +00:00
|
|
|
err = { message: 'unknown command "'+cmd[1]+'"', code: 'E_UNKNOWN_COMMAND' };
|
2017-04-28 01:36:28 +00:00
|
|
|
}
|
|
|
|
|
2017-09-07 23:10:47 +00:00
|
|
|
sendTunnelMsg(null, [-cmd[0], err], 'control');
|
2017-04-28 01:36:28 +00:00
|
|
|
}
|
2017-09-07 23:10:47 +00:00
|
|
|
|
2017-04-28 01:36:28 +00:00
|
|
|
, onmessage: function (opts) {
|
2016-10-01 05:52:37 +00:00
|
|
|
var cid = packer.addrToId(opts);
|
2017-04-27 01:52:30 +00:00
|
|
|
console.log("remote '" + logName() + "' has data for '" + cid + "'", opts.data.byteLength);
|
2016-09-30 06:46:02 +00:00
|
|
|
|
2017-09-07 23:10:47 +00:00
|
|
|
var browserConn = getBrowserConn(cid);
|
|
|
|
if (!browserConn) {
|
|
|
|
sendTunnelMsg(opts, {message: 'no matching connection', code: 'E_NO_CONN'}, 'error');
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
browserConn.write(opts.data);
|
2017-09-11 21:45:17 +00:00
|
|
|
// tunnelRead is how many bytes we've read from the tunnel, and written to the browser.
|
|
|
|
browserConn.tunnelRead = (browserConn.tunnelRead || 0) + opts.data.byteLength;
|
2017-09-07 23:10:47 +00:00
|
|
|
// If we have more than 1MB buffered data we need to tell the other side to slow down.
|
|
|
|
// Once we've finished sending what we have we can tell the other side to keep going.
|
2017-09-08 17:24:30 +00:00
|
|
|
// If we've already sent the 'pause' message though don't send it again, because we're
|
|
|
|
// probably just dealing with data queued before our message got to them.
|
|
|
|
if (!browserConn.remotePaused && browserConn.bufferSize > 1024*1024) {
|
2017-09-11 21:45:17 +00:00
|
|
|
sendTunnelMsg(opts, browserConn.tunnelRead, 'pause');
|
2017-09-08 17:24:30 +00:00
|
|
|
browserConn.remotePaused = true;
|
|
|
|
|
2017-09-07 23:10:47 +00:00
|
|
|
browserConn.once('drain', function () {
|
2017-09-11 21:45:17 +00:00
|
|
|
sendTunnelMsg(opts, browserConn.tunnelRead, 'resume');
|
2017-09-08 17:24:30 +00:00
|
|
|
browserConn.remotePaused = false;
|
2017-09-07 23:10:47 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
, onpause: function (opts) {
|
|
|
|
var cid = packer.addrToId(opts);
|
|
|
|
console.log('[TunnelPause]', cid);
|
2017-09-07 00:43:34 +00:00
|
|
|
var browserConn = getBrowserConn(cid);
|
2017-04-27 01:52:30 +00:00
|
|
|
if (browserConn) {
|
2017-09-07 23:10:47 +00:00
|
|
|
browserConn.manualPause = true;
|
|
|
|
browserConn.pause();
|
2017-09-07 00:43:34 +00:00
|
|
|
} else {
|
2017-09-07 23:10:47 +00:00
|
|
|
sendTunnelMsg(opts, {message: 'no matching connection', code: 'E_NO_CONN'}, 'error');
|
2016-09-30 06:46:02 +00:00
|
|
|
}
|
|
|
|
}
|
2017-09-07 23:10:47 +00:00
|
|
|
, onresume: function (opts) {
|
|
|
|
var cid = packer.addrToId(opts);
|
|
|
|
console.log('[TunnelResume]', cid);
|
|
|
|
var browserConn = getBrowserConn(cid);
|
|
|
|
if (browserConn) {
|
|
|
|
browserConn.manualPause = false;
|
|
|
|
browserConn.resume();
|
|
|
|
} else {
|
|
|
|
sendTunnelMsg(opts, {message: 'no matching connection', code: 'E_NO_CONN'}, 'error');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-09-30 06:46:02 +00:00
|
|
|
, onend: function (opts) {
|
2016-10-01 05:52:37 +00:00
|
|
|
var cid = packer.addrToId(opts);
|
2016-09-30 06:46:02 +00:00
|
|
|
console.log('[TunnelEnd]', cid);
|
2017-09-08 17:24:30 +00:00
|
|
|
closeBrowserConn(cid);
|
2016-09-30 06:46:02 +00:00
|
|
|
}
|
|
|
|
, onerror: function (opts) {
|
2016-10-01 05:52:37 +00:00
|
|
|
var cid = packer.addrToId(opts);
|
2017-09-08 17:24:30 +00:00
|
|
|
console.log('[TunnelError]', cid, opts.message);
|
|
|
|
closeBrowserConn(cid);
|
2016-09-30 06:46:02 +00:00
|
|
|
}
|
|
|
|
};
|
2017-04-28 18:50:50 +00:00
|
|
|
var unpacker = packer.create(packerHandlers);
|
2017-04-05 02:31:58 +00:00
|
|
|
|
2017-04-07 21:46:00 +00:00
|
|
|
var lastActivity = Date.now();
|
|
|
|
var timeoutId;
|
|
|
|
function refreshTimeout() {
|
|
|
|
lastActivity = Date.now();
|
|
|
|
}
|
|
|
|
function checkTimeout() {
|
|
|
|
// Determine how long the connection has been "silent", ie no activity.
|
|
|
|
var silent = Date.now() - lastActivity;
|
|
|
|
|
|
|
|
// If we have had activity within the last activityTimeout then all we need to do is
|
|
|
|
// call this function again at the soonest time when the connection could be timed out.
|
|
|
|
if (silent < activityTimeout) {
|
|
|
|
timeoutId = setTimeout(checkTimeout, activityTimeout-silent);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise we check to see if the pong has also timed out, and if not we send a ping
|
|
|
|
// and call this function again when the pong will have timed out.
|
|
|
|
else if (silent < activityTimeout + pongTimeout) {
|
2017-04-27 01:52:30 +00:00
|
|
|
console.log('pinging', logName());
|
2017-04-07 21:46:00 +00:00
|
|
|
try {
|
2017-04-27 01:52:30 +00:00
|
|
|
ws.ping();
|
2017-04-07 21:46:00 +00:00
|
|
|
} catch (err) {
|
2017-04-27 01:52:30 +00:00
|
|
|
console.warn('failed to ping home cloud', logName());
|
2017-04-07 21:46:00 +00:00
|
|
|
}
|
|
|
|
timeoutId = setTimeout(checkTimeout, pongTimeout);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Last case means the ping we sent before didn't get a response soon enough, so we
|
|
|
|
// need to close the websocket connection.
|
|
|
|
else {
|
2017-04-27 01:52:30 +00:00
|
|
|
console.log('home cloud', logName(), 'connection timed out');
|
|
|
|
ws.close(1013, 'connection timeout');
|
2017-04-07 21:46:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
timeoutId = setTimeout(checkTimeout, activityTimeout);
|
|
|
|
|
|
|
|
// Note that our websocket library automatically handles pong responses on ping requests
|
|
|
|
// before it even emits the event.
|
|
|
|
ws.on('ping', refreshTimeout);
|
|
|
|
ws.on('pong', refreshTimeout);
|
|
|
|
ws.on('message', function forwardMessage(chunk) {
|
|
|
|
refreshTimeout();
|
2016-09-30 02:20:38 +00:00
|
|
|
console.log('message from home cloud to tunneler to browser', chunk.byteLength);
|
2016-09-30 07:11:24 +00:00
|
|
|
//console.log(chunk.toString());
|
2017-04-27 01:52:30 +00:00
|
|
|
unpacker.fns.addChunk(chunk);
|
2017-04-07 21:46:00 +00:00
|
|
|
});
|
|
|
|
|
2017-04-05 02:31:58 +00:00
|
|
|
function hangup() {
|
2017-04-07 21:46:00 +00:00
|
|
|
clearTimeout(timeoutId);
|
2017-04-27 01:52:30 +00:00
|
|
|
console.log('home cloud', logName(), 'connection closing');
|
|
|
|
Object.keys(remotes).forEach(function (jwtoken) {
|
|
|
|
removeToken(jwtoken);
|
2017-04-26 18:05:44 +00:00
|
|
|
});
|
2017-05-26 23:26:44 +00:00
|
|
|
ws.terminate();
|
2017-04-05 02:31:58 +00:00
|
|
|
}
|
2016-09-28 05:26:16 +00:00
|
|
|
|
2017-04-05 02:31:58 +00:00
|
|
|
ws.on('close', hangup);
|
2017-04-07 00:21:21 +00:00
|
|
|
ws.on('error', hangup);
|
2017-04-28 18:50:50 +00:00
|
|
|
|
|
|
|
// We only ever send one command and we send it once, so we just hard code the ID as 1
|
2017-09-07 23:10:47 +00:00
|
|
|
sendTunnelMsg(null, [1, 'hello', [unpacker._version], Object.keys(commandHandlers)], 'control');
|
2017-04-07 00:21:21 +00:00
|
|
|
}
|
2016-09-27 21:56:06 +00:00
|
|
|
|
2017-09-07 00:43:34 +00:00
|
|
|
function pipeWs(servername, service, conn, remote) {
|
2017-04-26 18:05:44 +00:00
|
|
|
console.log('[pipeWs] servername:', servername, 'service:', service);
|
|
|
|
|
2017-09-07 00:43:34 +00:00
|
|
|
var browserAddr = packer.socketToAddr(conn);
|
2017-04-26 18:05:44 +00:00
|
|
|
browserAddr.service = service;
|
|
|
|
var cid = packer.addrToId(browserAddr);
|
2017-09-08 17:24:30 +00:00
|
|
|
conn.tunnelCid = cid;
|
2018-04-24 16:34:20 +00:00
|
|
|
console.log('[pipeWs] browser is', cid, 'home-cloud is', packer.socketToId(remote.upgradeReq.socket));
|
2017-04-26 18:05:44 +00:00
|
|
|
|
|
|
|
function sendWs(data, serviceOverride) {
|
2017-09-11 21:45:17 +00:00
|
|
|
if (remote.ws && (!conn.tunnelClosing || serviceOverride)) {
|
2016-10-12 23:11:11 +00:00
|
|
|
try {
|
2017-04-26 18:05:44 +00:00
|
|
|
remote.ws.send(packer.pack(browserAddr, data, serviceOverride), { binary: true });
|
2017-09-07 23:10:47 +00:00
|
|
|
// If we can't send data over the websocket as fast as this connection can send it to us
|
|
|
|
// (or there are a lot of connections trying to send over the same websocket) then we
|
|
|
|
// need to pause the connection for a little. We pause all connections if any are paused
|
|
|
|
// to make things more fair so a connection doesn't get stuck waiting for everyone else
|
2017-09-08 17:24:30 +00:00
|
|
|
// to finish because it got caught on the boundary. Also if serviceOverride is set it
|
|
|
|
// means the connection is over, so no need to pause it.
|
2017-09-11 21:45:17 +00:00
|
|
|
if (!serviceOverride && (remote.pausedConns.length || remote.ws.bufferedAmount > 1024*1024)) {
|
|
|
|
// console.log('pausing', cid, 'to allow web socket to catch up');
|
2017-09-08 17:24:30 +00:00
|
|
|
conn.pause();
|
|
|
|
remote.pausedConns.push(conn);
|
2017-09-07 23:10:47 +00:00
|
|
|
}
|
2017-04-26 18:05:44 +00:00
|
|
|
} catch (err) {
|
|
|
|
console.warn('[pipeWs] error sending websocket message', err);
|
2016-10-12 23:11:11 +00:00
|
|
|
}
|
|
|
|
}
|
2017-04-26 18:05:44 +00:00
|
|
|
}
|
|
|
|
|
2017-09-07 00:43:34 +00:00
|
|
|
remote.clients[cid] = conn;
|
|
|
|
conn.on('data', function (chunk) {
|
2017-04-26 18:05:44 +00:00
|
|
|
console.log('[pipeWs] data from browser to tunneler', chunk.byteLength);
|
|
|
|
sendWs(chunk);
|
2016-09-30 02:20:38 +00:00
|
|
|
});
|
2017-09-07 00:43:34 +00:00
|
|
|
conn.on('error', function (err) {
|
2017-04-26 18:05:44 +00:00
|
|
|
console.warn('[pipeWs] browser connection error', err);
|
2016-09-30 02:20:38 +00:00
|
|
|
});
|
2017-09-07 00:43:34 +00:00
|
|
|
conn.on('close', function (hadErr) {
|
2017-04-26 18:05:44 +00:00
|
|
|
console.log('[pipeWs] browser connection closing');
|
2017-09-08 17:24:30 +00:00
|
|
|
sendWs(null, hadErr ? 'error': 'end');
|
2016-09-30 02:20:38 +00:00
|
|
|
delete remote.clients[cid];
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-09-07 00:43:34 +00:00
|
|
|
function onTcpConnection(conn) {
|
2016-09-27 21:56:06 +00:00
|
|
|
// this works when I put it here, but I don't know if it's tls yet here
|
|
|
|
// httpsServer.emit('connection', socket);
|
|
|
|
//tls3000.emit('connection', socket);
|
|
|
|
|
|
|
|
//var tlsSocket = new tls.TLSSocket(socket, { secureContext: tls.createSecureContext(tlsOpts) });
|
|
|
|
//tlsSocket.on('data', function (chunk) {
|
|
|
|
// console.log('dummy', chunk.byteLength);
|
|
|
|
//});
|
|
|
|
|
|
|
|
//return;
|
2017-09-07 00:43:34 +00:00
|
|
|
conn.once('data', function (firstChunk) {
|
2016-09-27 21:56:06 +00:00
|
|
|
// BUG XXX: this assumes that the packet won't be chunked smaller
|
|
|
|
// than the 'hello' or the point of the 'Host' header.
|
|
|
|
// This is fairly reasonable, but there are edge cases where
|
|
|
|
// it does not hold (such as manual debugging with telnet)
|
|
|
|
// and so it should be fixed at some point in the future
|
|
|
|
|
|
|
|
// defer after return (instead of being in many places)
|
|
|
|
process.nextTick(function () {
|
2017-09-07 00:43:34 +00:00
|
|
|
conn.unshift(firstChunk);
|
2016-09-27 21:56:06 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
var service = 'tcp';
|
|
|
|
var servername;
|
|
|
|
var str;
|
|
|
|
var m;
|
|
|
|
|
|
|
|
function tryTls() {
|
2017-04-05 02:31:58 +00:00
|
|
|
if (-1 !== copts.servernames.indexOf(servername)) {
|
2017-04-05 08:13:03 +00:00
|
|
|
console.log("Lock and load, admin interface time!");
|
2017-09-07 00:43:34 +00:00
|
|
|
copts.httpsTunnel(servername, conn);
|
2017-04-05 02:31:58 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2017-04-05 08:13:03 +00:00
|
|
|
if (!servername) {
|
|
|
|
console.log("No SNI was given, so there's nothing we can do here");
|
2017-09-07 00:43:34 +00:00
|
|
|
copts.httpsInvalid(servername, conn);
|
2017-04-05 08:13:03 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2017-04-07 00:21:21 +00:00
|
|
|
var nextDevice = Devices.next(deviceLists, servername);
|
2017-04-05 08:13:03 +00:00
|
|
|
if (!nextDevice) {
|
|
|
|
console.log("No devices match the given servername");
|
2017-09-07 00:43:34 +00:00
|
|
|
copts.httpsInvalid(servername, conn);
|
2016-09-27 21:56:06 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2017-04-05 02:31:58 +00:00
|
|
|
console.log("pipeWs(servername, service, socket, deviceLists['" + servername + "'])");
|
2017-09-07 00:43:34 +00:00
|
|
|
pipeWs(servername, service, conn, nextDevice);
|
2016-09-27 21:56:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// https://github.com/mscdex/httpolyglot/issues/3#issuecomment-173680155
|
|
|
|
if (22 === firstChunk[0]) {
|
|
|
|
// TLS
|
|
|
|
service = 'https';
|
|
|
|
servername = (sni(firstChunk)||'').toLowerCase();
|
2016-09-30 02:20:38 +00:00
|
|
|
console.log("tls hello servername:", servername);
|
2016-09-27 21:56:06 +00:00
|
|
|
tryTls();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (firstChunk[0] > 32 && firstChunk[0] < 127) {
|
|
|
|
str = firstChunk.toString();
|
2016-09-30 02:20:38 +00:00
|
|
|
m = str.match(/(?:^|[\r\n])Host: ([^\r\n]+)[\r\n]*/im);
|
|
|
|
servername = (m && m[1].toLowerCase() || '').split(':')[0];
|
|
|
|
console.log('servername', servername);
|
2016-09-27 21:56:06 +00:00
|
|
|
if (/HTTP\//i.test(str)) {
|
|
|
|
service = 'http';
|
2017-04-05 07:01:43 +00:00
|
|
|
// TODO disallow http entirely
|
|
|
|
// /^\/\.well-known\/acme-challenge\//.test(str)
|
2017-04-05 02:31:58 +00:00
|
|
|
if (/well-known/.test(str)) {
|
2016-09-27 21:56:06 +00:00
|
|
|
// HTTP
|
2017-04-05 02:31:58 +00:00
|
|
|
if (Devices.exist(deviceLists, servername)) {
|
2017-09-07 00:43:34 +00:00
|
|
|
pipeWs(servername, service, conn, Devices.next(deviceLists, servername));
|
2016-09-28 05:26:16 +00:00
|
|
|
return;
|
|
|
|
}
|
2017-09-07 00:43:34 +00:00
|
|
|
copts.handleHttp(servername, conn);
|
2016-09-27 21:56:06 +00:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
// redirect to https
|
2017-09-07 00:43:34 +00:00
|
|
|
copts.handleInsecureHttp(servername, conn);
|
2016-09-27 21:56:06 +00:00
|
|
|
}
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
console.error("Got unexpected connection", str);
|
2017-09-07 00:43:34 +00:00
|
|
|
conn.write(JSON.stringify({ error: {
|
2016-09-27 21:56:06 +00:00
|
|
|
message: "not sure what you were trying to do there..."
|
|
|
|
, code: 'E_INVALID_PROTOCOL' }
|
|
|
|
}));
|
2017-09-07 00:43:34 +00:00
|
|
|
conn.end();
|
2016-09-27 21:56:06 +00:00
|
|
|
});
|
2017-09-07 00:43:34 +00:00
|
|
|
conn.on('error', function (err) {
|
2016-09-30 07:11:24 +00:00
|
|
|
console.error('[error] tcp socket raw TODO forward and close');
|
|
|
|
console.error(err);
|
|
|
|
});
|
2016-10-01 05:52:37 +00:00
|
|
|
}
|
|
|
|
|
2017-06-22 00:55:24 +00:00
|
|
|
return {
|
|
|
|
tcp: onTcpConnection
|
|
|
|
, ws: onWsConnection
|
|
|
|
, isClientDomain: Devices.exist.bind(null, deviceLists)
|
|
|
|
};
|
2016-10-01 05:52:37 +00:00
|
|
|
};
|