2016-09-30 01:10:40 +00:00
|
|
|
(function () {
|
|
|
|
'use strict';
|
|
|
|
|
2018-09-04 00:57:38 +00:00
|
|
|
// TODO use stream-based ws
|
|
|
|
// https://github.com/websockets/ws/issues/596
|
|
|
|
|
2018-06-29 10:15:23 +00:00
|
|
|
var PromiseA;
|
|
|
|
try {
|
|
|
|
PromiseA = require('bluebird');
|
|
|
|
} catch(e) {
|
|
|
|
PromiseA = global.Promise;
|
|
|
|
}
|
2016-09-30 01:10:40 +00:00
|
|
|
var WebSocket = require('ws');
|
2018-05-31 06:19:53 +00:00
|
|
|
var Packer = require('proxy-packer');
|
2018-06-06 09:24:14 +00:00
|
|
|
var os = require('os');
|
2016-09-30 01:10:40 +00:00
|
|
|
|
2017-06-05 17:28:53 +00:00
|
|
|
function timeoutPromise(duration) {
|
|
|
|
return new PromiseA(function (resolve) {
|
|
|
|
setTimeout(resolve, duration);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2018-06-05 08:21:12 +00:00
|
|
|
function _connect(state) {
|
2017-05-25 19:46:09 +00:00
|
|
|
// Allow the tunnel client to be created with no token. This will prevent the connection from
|
|
|
|
// being established initialy and allows the caller to use `.append` for the first token so
|
|
|
|
// they can get a promise that will provide feedback about invalid tokens.
|
2018-06-13 21:00:08 +00:00
|
|
|
if(!state.sortingHat) {
|
|
|
|
state.sortingHat = "./sorting-hat.js";
|
|
|
|
}
|
2018-09-04 00:57:38 +00:00
|
|
|
|
|
|
|
var sharedPausedClients = [];
|
|
|
|
var sharedTimeoutId;
|
|
|
|
var client = require('./client').create({});
|
|
|
|
// client.wstunneler = null;
|
|
|
|
// client.pendingCommands = {};
|
|
|
|
// client.machine = machine<Packer>
|
|
|
|
// client.auth = null;
|
|
|
|
// client.sharedTokens = [];
|
|
|
|
// client.localclients = {};
|
|
|
|
// client.authenticated = false;
|
|
|
|
client._state = state;
|
|
|
|
|
2018-05-31 06:19:53 +00:00
|
|
|
if (state.token) {
|
2018-06-29 20:51:56 +00:00
|
|
|
if ('undefined' === state.token) {
|
|
|
|
throw new Error("passed string 'undefined' as token");
|
|
|
|
}
|
2018-09-04 00:57:38 +00:00
|
|
|
client.sharedTokens.push(state.token);
|
2017-05-25 19:46:09 +00:00
|
|
|
}
|
2017-04-10 17:39:27 +00:00
|
|
|
|
2017-04-07 23:38:55 +00:00
|
|
|
var clientHandlers = {
|
2018-09-04 00:57:38 +00:00
|
|
|
_initialConnect: true
|
|
|
|
, add: function (conn, cid, tun) {
|
|
|
|
client.localclients[cid] = conn;
|
2018-05-31 06:19:53 +00:00
|
|
|
console.info("[connect] new client '" + cid + "' for '" + tun.name + ":" + tun.serviceport + "' "
|
|
|
|
+ "(" + clientHandlers.count() + " clients)");
|
2017-09-08 16:54:47 +00:00
|
|
|
|
2017-09-11 20:52:49 +00:00
|
|
|
conn.tunnelCid = cid;
|
2018-08-08 09:14:40 +00:00
|
|
|
if (tun.data) {
|
|
|
|
conn.tunnelRead = tun.data.byteLength;
|
|
|
|
} else {
|
|
|
|
conn.tunnelRead = 0;
|
|
|
|
}
|
|
|
|
conn.tunnelWritten = 0;
|
2017-09-11 20:52:49 +00:00
|
|
|
|
2018-09-04 00:57:38 +00:00
|
|
|
// TODO use readable
|
2017-09-08 16:54:47 +00:00
|
|
|
conn.on('data', function onLocalData(chunk) {
|
2018-08-08 06:51:16 +00:00
|
|
|
//var chunk = conn.read();
|
2017-09-08 16:54:47 +00:00
|
|
|
if (conn.tunnelClosing) {
|
|
|
|
console.warn("[onLocalData] received data for '"+cid+"' over socket after connection was ended");
|
|
|
|
return;
|
|
|
|
}
|
2017-09-11 20:52:49 +00:00
|
|
|
// This value is bytes written to the tunnel (ie read from the local connection)
|
|
|
|
conn.tunnelWritten += chunk.byteLength;
|
2017-09-08 16:54:47 +00:00
|
|
|
|
|
|
|
// If we have a lot of buffered data waiting to be sent over the websocket we want to slow
|
|
|
|
// down the data we are getting to send over. We also want to pause all active connections
|
|
|
|
// if any connections are paused to make things more fair so one connection doesn't get
|
|
|
|
// stuff waiting for all other connections to finish because it tried writing near the border.
|
2018-09-04 00:57:38 +00:00
|
|
|
var bufSize = wsTunnelRemote.sendMessage(Packer.packHeader(tun, chunk));
|
2018-08-08 06:51:16 +00:00
|
|
|
// Sending 2 messages instead of copying the buffer
|
2018-09-04 00:57:38 +00:00
|
|
|
var bufSize2 = wsTunnelRemote.sendMessage(chunk);
|
|
|
|
if (sharedPausedClients.length || (bufSize + bufSize2) > 1024*1024) {
|
2017-09-11 21:35:03 +00:00
|
|
|
// console.log('[onLocalData] paused connection', cid, 'to allow websocket to catch up');
|
2017-09-08 16:54:47 +00:00
|
|
|
conn.pause();
|
2018-09-04 00:57:38 +00:00
|
|
|
sharedPausedClients.push(conn);
|
2017-09-08 16:54:47 +00:00
|
|
|
}
|
|
|
|
});
|
2017-09-11 20:52:49 +00:00
|
|
|
|
|
|
|
var sentEnd = false;
|
|
|
|
conn.on('end', function onLocalEnd() {
|
|
|
|
console.info("[onLocalEnd] connection '" + cid + "' ended, will probably close soon");
|
|
|
|
conn.tunnelClosing = true;
|
|
|
|
if (!sentEnd) {
|
2018-09-04 00:57:38 +00:00
|
|
|
wsTunnelRemote.sendMessage(Packer.packHeader(tun, null, 'end'));
|
2017-09-11 20:52:49 +00:00
|
|
|
sentEnd = true;
|
|
|
|
}
|
|
|
|
});
|
2017-09-08 16:54:47 +00:00
|
|
|
conn.on('error', function onLocalError(err) {
|
|
|
|
console.info("[onLocalError] connection '" + cid + "' errored:", err);
|
2017-09-11 20:52:49 +00:00
|
|
|
if (!sentEnd) {
|
2018-08-08 06:51:16 +00:00
|
|
|
var packBody = true;
|
2018-09-04 00:57:38 +00:00
|
|
|
wsTunnelRemote.sendMessage(Packer.packHeader(tun, {message: err.message, code: err.code}, 'error', packBody));
|
2017-09-11 20:52:49 +00:00
|
|
|
sentEnd = true;
|
|
|
|
}
|
2017-09-08 16:54:47 +00:00
|
|
|
});
|
|
|
|
conn.on('close', function onLocalClose(hadErr) {
|
2018-09-04 00:57:38 +00:00
|
|
|
delete client.localclients[cid];
|
2017-09-11 20:52:49 +00:00
|
|
|
console.log('[onLocalClose] closed "' + cid + '" read:'+conn.tunnelRead+', wrote:'+conn.tunnelWritten+' (' + clientHandlers.count() + ' clients)');
|
|
|
|
if (!sentEnd) {
|
2018-09-04 00:57:38 +00:00
|
|
|
wsTunnelRemote.sendMessage(Packer.packHeader(tun, null, hadErr && 'error' || 'end'));
|
2017-09-11 20:52:49 +00:00
|
|
|
sentEnd = true;
|
|
|
|
}
|
2017-09-08 16:54:47 +00:00
|
|
|
});
|
2017-04-07 23:38:55 +00:00
|
|
|
}
|
2017-09-08 16:54:47 +00:00
|
|
|
|
|
|
|
, write: function (cid, opts) {
|
2018-09-04 00:57:38 +00:00
|
|
|
var conn = client.localclients[cid];
|
2017-09-08 16:54:47 +00:00
|
|
|
if (!conn) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
//console.log("[=>] received data from '" + cid + "' =>", opts.data.byteLength);
|
|
|
|
|
|
|
|
if (conn.tunnelClosing) {
|
|
|
|
console.warn("[onmessage] received data for '"+cid+"' over socket after connection was ended");
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
conn.write(opts.data);
|
2017-09-11 20:52:49 +00:00
|
|
|
// It might seem weird to increase the "read" value in a function named `write`, but this
|
|
|
|
// is bytes read from the tunnel and written to the local connection.
|
|
|
|
conn.tunnelRead += opts.data.byteLength;
|
2017-09-11 21:35:03 +00:00
|
|
|
|
|
|
|
if (!conn.remotePaused && conn.bufferSize > 1024*1024) {
|
2018-08-08 06:51:16 +00:00
|
|
|
var packBody = true;
|
2018-09-04 00:57:38 +00:00
|
|
|
wsTunnelRemote.sendMessage(Packer.packHeader(opts, conn.tunnelRead, 'pause', packBody));
|
2017-09-11 21:35:03 +00:00
|
|
|
conn.remotePaused = true;
|
|
|
|
|
|
|
|
conn.once('drain', function () {
|
2018-08-08 06:51:16 +00:00
|
|
|
var packBody = true;
|
2018-09-04 00:57:38 +00:00
|
|
|
wsTunnelRemote.sendMessage(Packer.packHeader(opts, conn.tunnelRead, 'resume', packBody));
|
2017-09-11 21:35:03 +00:00
|
|
|
conn.remotePaused = false;
|
|
|
|
});
|
|
|
|
}
|
2017-09-08 16:54:47 +00:00
|
|
|
return true;
|
2017-04-07 23:38:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
, closeSingle: function (cid) {
|
2018-09-04 00:57:38 +00:00
|
|
|
if (!client.localclients[cid]) {
|
2017-04-07 23:38:55 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2017-04-08 00:01:47 +00:00
|
|
|
console.log('[closeSingle]', cid);
|
2017-09-08 16:54:47 +00:00
|
|
|
PromiseA.resolve().then(function () {
|
2018-09-04 00:57:38 +00:00
|
|
|
var conn = client.localclients[cid];
|
2017-09-08 16:54:47 +00:00
|
|
|
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) {
|
2017-06-05 17:28:53 +00:00
|
|
|
return timeoutPromise(500);
|
2017-09-08 16:54:47 +00:00
|
|
|
}
|
|
|
|
// 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) {
|
2018-09-04 00:57:38 +00:00
|
|
|
var myTimeoutId = setTimeout(resolve, 60*1000);
|
2017-09-08 16:54:47 +00:00
|
|
|
conn.once('drain', function () {
|
2018-09-04 00:57:38 +00:00
|
|
|
clearTimeout(myTimeoutId);
|
2017-09-08 16:54:47 +00:00
|
|
|
setTimeout(resolve, 500);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}).then(function () {
|
2018-09-04 00:57:38 +00:00
|
|
|
if (client.localclients[cid]) {
|
2017-09-08 16:54:47 +00:00
|
|
|
console.warn('[closeSingle]', cid, 'connection still present after calling `end`');
|
2018-09-04 00:57:38 +00:00
|
|
|
client.localclients[cid].destroy();
|
2017-09-08 16:54:47 +00:00
|
|
|
return timeoutPromise(500);
|
|
|
|
}
|
|
|
|
}).then(function () {
|
2018-09-04 00:57:38 +00:00
|
|
|
if (client.localclients[cid]) {
|
2017-09-08 16:54:47 +00:00
|
|
|
console.error('[closeSingle]', cid, 'connection still present after calling `destroy`');
|
2018-09-04 00:57:38 +00:00
|
|
|
delete client.localclients[cid];
|
2017-09-08 16:54:47 +00:00
|
|
|
}
|
|
|
|
}).catch(function (err) {
|
|
|
|
console.error('[closeSingle] failed to close connection', cid, err.toString());
|
2018-09-04 00:57:38 +00:00
|
|
|
delete client.localclients[cid];
|
2017-09-08 16:54:47 +00:00
|
|
|
});
|
2017-04-07 23:38:55 +00:00
|
|
|
}
|
|
|
|
, closeAll: function () {
|
2017-04-08 00:01:47 +00:00
|
|
|
console.log('[closeAll]');
|
2018-09-04 00:57:38 +00:00
|
|
|
Object.keys(client.localclients).forEach(function (cid) {
|
2017-06-05 17:28:53 +00:00
|
|
|
clientHandlers.closeSingle(cid);
|
2017-04-07 23:38:55 +00:00
|
|
|
});
|
|
|
|
}
|
2017-04-08 00:01:47 +00:00
|
|
|
|
2017-04-07 23:38:55 +00:00
|
|
|
, count: function () {
|
2018-09-04 00:57:38 +00:00
|
|
|
return Object.keys(client.localclients).length;
|
2017-04-07 23:38:55 +00:00
|
|
|
}
|
|
|
|
};
|
2017-04-08 00:01:47 +00:00
|
|
|
|
2018-09-04 00:57:38 +00:00
|
|
|
var DEFAULT_HTTP_TIMEOUT = (2 * 60);
|
|
|
|
var wsTunnelRemote = {
|
|
|
|
_activityTimeout: state.activityTimeout || (DEFAULT_HTTP_TIMEOUT - 5) * 1000
|
|
|
|
, _pongTimeout: state.pongTimeout || 10*1000
|
|
|
|
, _lastActivity: 0
|
|
|
|
, _sendCommand: function (name) {
|
|
|
|
var id = Math.ceil(1e9 * Math.random());
|
|
|
|
var cmd = [id, name].concat(Array.prototype.slice.call(arguments, 1));
|
|
|
|
if (state.debug) { console.log('[DEBUG] command sending', cmd); }
|
2018-06-01 09:13:04 +00:00
|
|
|
|
2018-08-08 06:51:16 +00:00
|
|
|
var packBody = true;
|
2018-09-04 00:57:38 +00:00
|
|
|
wsTunnelRemote.sendMessage(Packer.packHeader(null, cmd, 'control', packBody));
|
|
|
|
setTimeout(function () {
|
|
|
|
if (client.pendingCommands[id]) {
|
|
|
|
console.warn('command', name, id, 'timed out');
|
|
|
|
client.pendingCommands[id]({
|
|
|
|
message: 'response not received in time'
|
|
|
|
, code: 'E_TIMEOUT'
|
|
|
|
});
|
2017-04-28 00:38:01 +00:00
|
|
|
}
|
2018-09-04 00:57:38 +00:00
|
|
|
}, wsTunnelRemote._pongTimeout);
|
|
|
|
|
|
|
|
return new PromiseA(function (resolve, reject) {
|
|
|
|
client.pendingCommands[id] = function (err, result) {
|
|
|
|
delete client.pendingCommands[id];
|
|
|
|
if (err) {
|
|
|
|
reject(err);
|
|
|
|
} else {
|
|
|
|
resolve(result);
|
|
|
|
}
|
|
|
|
};
|
2018-05-31 06:19:53 +00:00
|
|
|
});
|
2017-09-08 16:54:47 +00:00
|
|
|
}
|
2018-09-04 00:57:38 +00:00
|
|
|
, refreshTimeout: function () {
|
|
|
|
wsTunnelRemote._lastActivity = Date.now();
|
2017-04-10 17:39:27 +00:00
|
|
|
}
|
|
|
|
, checkTimeout: function () {
|
2018-09-04 00:57:38 +00:00
|
|
|
if (!client.wstunneler) {
|
2017-04-10 17:39:27 +00:00
|
|
|
console.warn('checkTimeout called when websocket already closed');
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
// Determine how long the connection has been "silent", ie no activity.
|
2018-09-04 00:57:38 +00:00
|
|
|
var silent = Date.now() - wsTunnelRemote._lastActivity;
|
2017-04-10 17:39:27 +00:00
|
|
|
|
|
|
|
// 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.
|
2018-09-04 00:57:38 +00:00
|
|
|
if (silent < wsTunnelRemote._activityTimeout) {
|
|
|
|
sharedTimeoutId = setTimeout(wsTunnelRemote.checkTimeout, wsTunnelRemote._activityTimeout-silent);
|
2017-04-10 17:39:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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.
|
2018-09-04 00:57:38 +00:00
|
|
|
else if (silent < wsTunnelRemote._activityTimeout + wsTunnelRemote._pongTimeout) {
|
2017-04-10 17:39:27 +00:00
|
|
|
console.log('pinging tunnel server');
|
|
|
|
try {
|
2018-09-04 00:57:38 +00:00
|
|
|
client.wstunneler.ping();
|
2017-04-10 17:39:27 +00:00
|
|
|
} catch (err) {
|
|
|
|
console.warn('failed to ping tunnel server', err);
|
|
|
|
}
|
2018-09-04 00:57:38 +00:00
|
|
|
sharedTimeoutId = setTimeout(wsTunnelRemote.checkTimeout, wsTunnelRemote._pongTimeout);
|
2017-04-10 17:39:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Last case means the ping we sent before didn't get a response soon enough, so we
|
|
|
|
// need to close the websocket connection.
|
|
|
|
else {
|
|
|
|
console.log('connection timed out');
|
2018-09-04 00:57:38 +00:00
|
|
|
client.wstunneler.close(1000, 'connection timeout');
|
2017-04-10 17:39:27 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
, onOpen: function () {
|
2018-06-16 01:11:02 +00:00
|
|
|
console.info("[open] connected to '" + (state.wss || state.relay) + "'");
|
2018-09-04 00:57:38 +00:00
|
|
|
wsTunnelRemote.refreshTimeout();
|
2018-06-14 21:57:09 +00:00
|
|
|
|
2018-09-04 00:57:38 +00:00
|
|
|
sharedTimeoutId = setTimeout(wsTunnelRemote.checkTimeout, wsTunnelRemote._activityTimeout);
|
2017-09-08 16:54:47 +00:00
|
|
|
|
2018-09-04 00:57:38 +00:00
|
|
|
client.wstunneler._socket.on('drain', function () {
|
2017-09-11 21:35:03 +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.
|
2018-09-04 00:57:38 +00:00
|
|
|
if (client.wstunneler.bufferedAmount > 128*1024) {
|
2017-09-11 21:35:03 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2018-09-04 00:57:38 +00:00
|
|
|
sharedPausedClients.forEach(function (conn) {
|
2017-09-08 16:54:47 +00:00
|
|
|
if (!conn.manualPause) {
|
2017-09-11 21:35:03 +00:00
|
|
|
// console.log('resuming connection', conn.tunnelCid, 'now the websocket has caught up');
|
2017-09-08 16:54:47 +00:00
|
|
|
conn.resume();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2018-09-04 00:57:38 +00:00
|
|
|
sharedPausedClients.length = 0;
|
2017-09-08 16:54:47 +00:00
|
|
|
});
|
2018-06-14 21:57:09 +00:00
|
|
|
|
|
|
|
//Call either Open or Reconnect handlers.
|
2018-09-04 00:57:38 +00:00
|
|
|
if(state.handlers.onOpen && clientHandlers._initialConnect) {
|
2018-06-14 21:57:09 +00:00
|
|
|
state.handlers.onOpen();
|
2018-09-04 00:57:38 +00:00
|
|
|
} else if (state.handlers.onReconnect && !clientHandlers._initialConnect) {
|
2018-06-14 21:57:09 +00:00
|
|
|
state.handlers.onReconnect();
|
|
|
|
}
|
2018-09-04 00:57:38 +00:00
|
|
|
clientHandlers._initialConnect = false;
|
2016-09-30 01:10:40 +00:00
|
|
|
}
|
|
|
|
|
2016-09-30 19:04:27 +00:00
|
|
|
, onClose: function () {
|
2018-09-04 00:57:38 +00:00
|
|
|
clearTimeout(sharedTimeoutId);
|
|
|
|
client.wstunneler = null;
|
2017-04-07 23:38:55 +00:00
|
|
|
clientHandlers.closeAll();
|
2017-10-03 00:29:00 +00:00
|
|
|
|
|
|
|
var error = new Error('websocket connection closed before response');
|
|
|
|
error.code = 'E_CONN_CLOSED';
|
2018-09-04 00:57:38 +00:00
|
|
|
Object.keys(client.pendingCommands).forEach(function (id) {
|
|
|
|
client.pendingCommands[id](error);
|
2017-04-28 01:29:16 +00:00
|
|
|
});
|
2018-09-04 00:57:38 +00:00
|
|
|
if (client.connCallback) {
|
|
|
|
client.connCallback(error);
|
2017-10-03 00:29:00 +00:00
|
|
|
}
|
2017-04-07 23:38:55 +00:00
|
|
|
|
2018-09-04 00:57:38 +00:00
|
|
|
if (!client.authenticated) {
|
2018-06-14 21:57:09 +00:00
|
|
|
if(state.handlers.onError) {
|
2018-06-29 10:15:23 +00:00
|
|
|
var err = new Error('Failed to connect on first attempt... check authentication');
|
2018-06-14 21:57:09 +00:00
|
|
|
state.handlers.onError(err);
|
|
|
|
}
|
|
|
|
if(state.handlers.onClose) {
|
2018-06-29 10:15:23 +00:00
|
|
|
state.handlers.onClose();
|
2018-06-14 21:57:09 +00:00
|
|
|
}
|
2016-09-30 19:04:27 +00:00
|
|
|
console.info('[close] failed on first attempt... check authentication.');
|
2018-09-04 00:57:38 +00:00
|
|
|
sharedTimeoutId = null;
|
2016-09-30 19:04:27 +00:00
|
|
|
}
|
2018-09-04 00:57:38 +00:00
|
|
|
else if (client.sharedTokens.length) {
|
2018-06-14 21:57:09 +00:00
|
|
|
if(state.handlers.onDisconnect) {
|
|
|
|
state.handlers.onDisconnect();
|
|
|
|
}
|
2016-09-30 19:04:27 +00:00
|
|
|
console.info('[retry] disconnected and waiting...');
|
2018-09-04 00:57:38 +00:00
|
|
|
sharedTimeoutId = setTimeout(connect, 5000);
|
2018-06-14 21:57:09 +00:00
|
|
|
} else {
|
|
|
|
if(state.handlers.onClose) {
|
2018-06-29 10:15:23 +00:00
|
|
|
state.handlers.onClose();
|
2018-06-14 21:57:09 +00:00
|
|
|
}
|
2016-09-30 19:04:27 +00:00
|
|
|
}
|
|
|
|
}
|
2016-09-30 05:46:00 +00:00
|
|
|
|
2016-09-30 19:04:27 +00:00
|
|
|
, onError: function (err) {
|
2018-07-03 09:42:17 +00:00
|
|
|
if ('ENOTFOUND' === err.code) {
|
|
|
|
// DNS issue, probably network is disconnected
|
2018-09-04 00:57:38 +00:00
|
|
|
sharedTimeoutId = setTimeout(connect, 90 * 1000);
|
2018-07-03 09:42:17 +00:00
|
|
|
return;
|
|
|
|
}
|
2018-06-18 18:01:12 +00:00
|
|
|
console.error("[tunnel error] " + err.message);
|
|
|
|
console.error(err);
|
2018-09-04 00:57:38 +00:00
|
|
|
if (client.connCallback) {
|
|
|
|
client.connCallback(err);
|
2018-06-18 18:01:12 +00:00
|
|
|
}
|
2016-09-30 19:04:27 +00:00
|
|
|
}
|
2016-09-30 05:46:00 +00:00
|
|
|
|
2017-04-08 00:49:52 +00:00
|
|
|
, sendMessage: function (msg) {
|
2018-09-04 00:57:38 +00:00
|
|
|
if (client.wstunneler) {
|
2017-04-08 00:49:52 +00:00
|
|
|
try {
|
2018-09-04 00:57:38 +00:00
|
|
|
client.wstunneler.send(msg, {binary: true});
|
|
|
|
return client.wstunneler.bufferedAmount;
|
2017-04-08 00:49:52 +00:00
|
|
|
} catch (err) {
|
2017-04-26 23:37:52 +00:00
|
|
|
// There is a chance that this occurred after the websocket was told to close
|
|
|
|
// and before it finished, in which case we don't need to log the error.
|
2018-09-04 00:57:38 +00:00
|
|
|
if (client.wstunneler.readyState !== client.wstunneler.CLOSING) {
|
2017-04-26 23:37:52 +00:00
|
|
|
console.warn('[sendMessage] error sending websocket message', err);
|
|
|
|
}
|
2017-04-08 00:49:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
function connect() {
|
2018-09-04 00:57:38 +00:00
|
|
|
if (client.wstunneler) {
|
2017-04-28 21:28:21 +00:00
|
|
|
console.warn('attempted to connect with connection already active');
|
|
|
|
return;
|
|
|
|
}
|
2018-09-04 00:57:38 +00:00
|
|
|
if (!client.sharedTokens.length) {
|
2018-06-06 07:01:56 +00:00
|
|
|
if (state.config.email) {
|
2018-09-04 00:57:38 +00:00
|
|
|
client.auth = {
|
2018-06-06 07:01:56 +00:00
|
|
|
subject: state.config.email
|
|
|
|
, subject_scheme: 'mailto'
|
|
|
|
// TODO create domains list earlier
|
|
|
|
, scope: Object.keys(state.config.servernames || {}).join(',')
|
2018-06-13 20:40:44 +00:00
|
|
|
, otp: state.otp
|
2018-06-06 09:24:14 +00:00
|
|
|
, hostname: os.hostname()
|
|
|
|
// Used for User-Agent
|
|
|
|
, os_type: os.type()
|
|
|
|
, os_platform: os.platform()
|
|
|
|
, os_release: os.release()
|
|
|
|
, os_arch: os.arch()
|
2018-06-06 07:01:56 +00:00
|
|
|
};
|
|
|
|
}
|
2018-06-05 08:21:12 +00:00
|
|
|
}
|
2018-09-04 00:57:38 +00:00
|
|
|
sharedTimeoutId = null;
|
2017-04-08 00:49:52 +00:00
|
|
|
|
2018-06-16 01:11:02 +00:00
|
|
|
console.info("[connect] '" + (state.wss || state.relay) + "'");
|
2018-09-04 00:57:38 +00:00
|
|
|
var tunnelUrl = (state.wss || state.relay).replace(/\/$/, '') + '/'; // + client.auth;
|
|
|
|
var wsOpts = { binary: true, rejectUnauthorized: !state.insecure };
|
|
|
|
client.wstunneler = new WebSocket(tunnelUrl, wsOpts);
|
|
|
|
client.wsreader = require('./ws-readable').create(client.wstunneler);
|
|
|
|
client.wstunneler.on('open', wsTunnelRemote.onOpen);
|
|
|
|
client.wstunneler.on('close', wsTunnelRemote.onClose);
|
|
|
|
client.wstunneler.on('error', wsTunnelRemote.onError);
|
2017-04-10 17:39:27 +00:00
|
|
|
|
|
|
|
// Our library will automatically handle sending the pong respose to ping requests.
|
2018-09-04 00:57:38 +00:00
|
|
|
client.wstunneler.on('ping', wsTunnelRemote.refreshTimeout);
|
|
|
|
client.wstunneler.on('pong', wsTunnelRemote.refreshTimeout);
|
|
|
|
client.wstunneler.on('message', function (data, flags) {
|
|
|
|
wsTunnelRemote.refreshTimeout();
|
2017-04-08 00:49:52 +00:00
|
|
|
if (data.error || '{' === data[0]) {
|
|
|
|
console.log(data);
|
|
|
|
return;
|
|
|
|
}
|
2018-09-04 00:57:38 +00:00
|
|
|
client.machine.fns.addChunk(data, flags);
|
2017-04-08 00:49:52 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2018-09-04 00:57:38 +00:00
|
|
|
var xyzHandlers = {
|
|
|
|
_connPromise: null
|
|
|
|
, end: function(cb) {
|
|
|
|
client.sharedTokens.length = 0;
|
|
|
|
if (sharedTimeoutId) {
|
|
|
|
clearTimeout(sharedTimeoutId);
|
|
|
|
sharedTimeoutId = null;
|
2017-04-14 22:27:25 +00:00
|
|
|
}
|
2017-04-08 00:49:52 +00:00
|
|
|
|
2018-09-04 00:57:38 +00:00
|
|
|
if (client.wstunneler) {
|
2017-04-14 22:27:25 +00:00
|
|
|
try {
|
2018-09-04 00:57:38 +00:00
|
|
|
client.wstunneler.close(cb);
|
2017-04-14 22:27:25 +00:00
|
|
|
} catch(e) {
|
2018-09-04 00:57:38 +00:00
|
|
|
console.error("[error] client.wstunneler.close()");
|
2017-04-14 22:27:25 +00:00
|
|
|
console.error(e);
|
|
|
|
}
|
2016-09-30 05:46:00 +00:00
|
|
|
}
|
|
|
|
}
|
2017-04-28 01:29:16 +00:00
|
|
|
, append: function (token) {
|
2018-06-29 20:51:56 +00:00
|
|
|
if (!token) {
|
|
|
|
throw new Error("attempted to append empty token");
|
|
|
|
}
|
|
|
|
if ('undefined' === token) {
|
|
|
|
throw new Error("attempted to append token as the string 'undefined'");
|
|
|
|
}
|
2018-09-04 00:57:38 +00:00
|
|
|
if (client.sharedTokens.indexOf(token) >= 0) {
|
2017-04-28 16:57:48 +00:00
|
|
|
return PromiseA.resolve();
|
|
|
|
}
|
2018-09-04 00:57:38 +00:00
|
|
|
client.sharedTokens.push(token);
|
2017-04-28 21:28:21 +00:00
|
|
|
var prom;
|
2018-09-04 00:57:38 +00:00
|
|
|
if (client.sharedTokens.length === 1 && !client.wstunneler) {
|
2017-04-28 21:28:21 +00:00
|
|
|
// We just added the only token in the list, and the websocket connection isn't up
|
|
|
|
// so we need to restart the connection.
|
2018-09-04 00:57:38 +00:00
|
|
|
if (sharedTimeoutId) {
|
2017-04-28 21:28:21 +00:00
|
|
|
// Handle the case were the last token was removed and this token added between
|
|
|
|
// reconnect attempts to make sure we don't try openning multiple connections.
|
2018-09-04 00:57:38 +00:00
|
|
|
clearTimeout(sharedTimeoutId);
|
|
|
|
sharedTimeoutId = null;
|
2017-04-28 21:28:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// We want this case to behave as much like the other case as we can, but we don't have
|
|
|
|
// the same kind of reponses when we open brand new connections, so we have to rely on
|
|
|
|
// the 'hello' and the 'un-associated' error commands to determine if the token is good.
|
2018-09-04 00:57:38 +00:00
|
|
|
prom = xyzHandlers._connPromise = new PromiseA(function (resolve, reject) {
|
|
|
|
client.connCallback = function (err) {
|
|
|
|
client.connCallback = null;
|
|
|
|
xyzHandlers._connPromise = null;
|
2017-04-28 21:28:21 +00:00
|
|
|
if (err) {
|
|
|
|
reject(err);
|
|
|
|
} else {
|
|
|
|
resolve();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
});
|
|
|
|
connect();
|
|
|
|
}
|
2018-09-04 00:57:38 +00:00
|
|
|
else if (xyzHandlers._connPromise) {
|
|
|
|
prom = xyzHandlers._connPromise.then(function () {
|
|
|
|
return wsTunnelRemote._sendCommand('add_token', token);
|
2017-06-15 20:49:50 +00:00
|
|
|
});
|
|
|
|
}
|
2017-04-28 21:28:21 +00:00
|
|
|
else {
|
2018-09-04 00:57:38 +00:00
|
|
|
prom = wsTunnelRemote._sendCommand('add_token', token);
|
2017-04-28 21:28:21 +00:00
|
|
|
}
|
2017-04-28 16:57:48 +00:00
|
|
|
|
|
|
|
prom.catch(function (err) {
|
|
|
|
console.error('adding token', token, 'failed:', err);
|
|
|
|
// Most probably an invalid token of some kind, so we don't really want to keep it.
|
2018-09-04 00:57:38 +00:00
|
|
|
client.sharedTokens.splice(client.sharedTokens.indexOf(token), 1);
|
2017-04-28 16:57:48 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
return prom;
|
2017-04-28 01:29:16 +00:00
|
|
|
}
|
|
|
|
, clear: function (token) {
|
2017-04-28 16:57:48 +00:00
|
|
|
if (typeof token === 'undefined') {
|
|
|
|
token = '*';
|
|
|
|
}
|
|
|
|
|
|
|
|
if (token === '*') {
|
2018-09-04 00:57:38 +00:00
|
|
|
client.sharedTokens.length = 0;
|
2017-04-28 16:57:48 +00:00
|
|
|
} else {
|
2018-09-04 00:57:38 +00:00
|
|
|
var index = client.sharedTokens.indexOf(token);
|
2017-04-28 16:57:48 +00:00
|
|
|
if (index < 0) {
|
|
|
|
return PromiseA.resolve();
|
|
|
|
}
|
2018-09-04 00:57:38 +00:00
|
|
|
client.sharedTokens.splice(index);
|
2017-04-28 16:57:48 +00:00
|
|
|
}
|
|
|
|
|
2018-09-04 00:57:38 +00:00
|
|
|
var prom = wsTunnelRemote._sendCommand('delete_token', token);
|
2017-04-28 16:57:48 +00:00
|
|
|
prom.catch(function (err) {
|
|
|
|
console.error('clearing token', token, 'failed:', err);
|
|
|
|
});
|
|
|
|
|
|
|
|
return prom;
|
2017-04-28 01:29:16 +00:00
|
|
|
}
|
2017-04-14 22:27:25 +00:00
|
|
|
};
|
2018-09-04 00:57:38 +00:00
|
|
|
|
|
|
|
client._wsTunnelRemote = wsTunnelRemote;
|
|
|
|
client.clientHandlers = clientHandlers;
|
|
|
|
connect();
|
|
|
|
return xyzHandlers;
|
2016-09-30 19:04:27 +00:00
|
|
|
}
|
2016-09-30 05:46:00 +00:00
|
|
|
|
2018-06-05 08:21:12 +00:00
|
|
|
module.exports.connect = _connect;
|
|
|
|
module.exports.createConnection = _connect;
|
2016-09-30 01:10:40 +00:00
|
|
|
|
|
|
|
}());
|