telebit.js/wsclient.js

254 lines
7.3 KiB
JavaScript
Raw Normal View History

2016-09-30 01:10:40 +00:00
(function () {
'use strict';
var WebSocket = require('ws');
var sni = require('sni');
2016-10-06 05:55:48 +00:00
var Packer = require('tunnel-packer');
2016-09-30 01:10:40 +00:00
2016-09-30 19:04:27 +00:00
function run(copts) {
2016-10-11 23:43:24 +00:00
var tunnelUrl = copts.stunneld.replace(/\/$/, '') + '/?access_token=' + copts.token;
2016-09-30 19:04:27 +00:00
var wstunneler;
2017-04-08 00:49:52 +00:00
var authenticated = false;
2016-09-30 19:04:27 +00:00
var localclients = {};
var clientHandlers = {
onClose: function (cid, opts, err) {
2017-04-08 00:49:52 +00:00
wsHandlers.sendMessage(Packer.pack(opts, null, err && 'error' || 'end'));
delete localclients[cid];
console.log('[local onClose] closed "' + cid + '" (' + clientHandlers.count() + ' clients)');
}
, onError: function(cid, opts, err) {
console.info("[local onError] closing '" + cid + "' because '" + err.message + "'");
clientHandlers.onClose(cid, opts, err);
}
, closeSingle: function (cid) {
if (!localclients[cid]) {
return;
}
console.log('[closeSingle]', cid);
try {
localclients[cid].end();
setTimeout(function () {
if (localclients[cid]) {
console.warn('[closeSingle]', cid, 'connection still present');
delete localclients[cid];
}
}, 500);
} catch (err) {
console.warn('[closeSingle] failed to close connection', cid, err);
delete localclients[cid];
}
}
, closeAll: function () {
console.log('[closeAll]');
Object.keys(localclients).forEach(function (cid) {
try {
localclients[cid].end();
} catch (err) {
console.warn('[closeAll] failed to close connection', cid, err);
}
});
setTimeout(function () {
Object.keys(localclients).forEach(function (cid) {
if (localclients[cid]) {
console.warn('[closeAll]', cid, 'connection still present');
delete localclients[cid];
}
});
}, 500);
}
, count: function () {
return Object.keys(localclients).length;
}
};
var packerHandlers = {
2016-09-30 19:04:27 +00:00
onmessage: function (opts) {
2016-10-06 05:02:28 +00:00
var net = copts.net || require('net');
2016-10-06 05:55:48 +00:00
var cid = Packer.addrToId(opts);
var service = opts.service.toLowerCase();
var portList = copts.services[service];
2016-09-30 19:04:27 +00:00
var servername;
var port;
2016-09-30 19:04:27 +00:00
var str;
var m;
authenticated = true;
if (localclients[cid]) {
//console.log("[=>] received data from '" + cid + "' =>", opts.data.byteLength);
localclients[cid].write(opts.data);
return;
}
if (!portList) {
packerHandlers._onConnectError(cid, opts, new Error("unsupported service '" + service + "'"));
return;
}
if ('http' === service) {
2016-09-30 19:04:27 +00:00
str = opts.data.toString();
m = str.match(/(?:^|[\r\n])Host: ([^\r\n]+)[\r\n]*/im);
servername = (m && m[1].toLowerCase() || '').split(':')[0];
}
else if ('https' === service) {
servername = sni(opts.data);
}
else {
servername = '*';
2016-09-30 19:04:27 +00:00
}
if (!servername) {
//console.warn(opts.data.toString());
packerHandlers._onConnectError(cid, opts, new Error("missing servername for '" + cid + "' " + opts.data.byteLength));
2016-09-30 19:04:27 +00:00
return;
}
port = portList[servername] || portList['*'];
2016-10-06 05:02:28 +00:00
localclients[cid] = net.createConnection({
2016-10-11 23:43:24 +00:00
port: port
2016-10-06 05:02:28 +00:00
, host: '127.0.0.1'
2016-10-11 23:43:24 +00:00
, servername: servername
2016-10-06 05:10:16 +00:00
, data: opts.data
2016-10-06 21:01:58 +00:00
, remoteFamily: opts.family
, remoteAddress: opts.address
, remotePort: opts.port
2016-10-06 05:02:28 +00:00
}, function () {
2016-09-30 19:04:27 +00:00
//console.log("[=>] first packet from tunneler to '" + cid + "' as '" + opts.service + "'", opts.data.byteLength);
2016-10-12 19:14:16 +00:00
// this will happen before 'data' is triggered
2016-10-12 18:59:13 +00:00
localclients[cid].write(opts.data);
2016-09-30 19:04:27 +00:00
});
console.info("[connect] new client '" + cid + "' for '" + servername + "' (" + clientHandlers.count() + " clients)");
2016-10-06 05:02:28 +00:00
localclients[cid].on('readable', function (size) {
var chunk;
2016-10-11 23:43:24 +00:00
if (!localclients[cid]) {
console.error("[error] localclients[cid]", cid);
return;
}
if (!localclients[cid].read) {
console.error("[error] localclients[cid].read", cid);
console.log(localclients[cid]);
return;
}
2016-10-06 05:02:28 +00:00
do {
chunk = localclients[cid].read(size);
2016-10-12 19:11:21 +00:00
if (chunk) {
2017-04-08 00:49:52 +00:00
wsHandlers.sendMessage(Packer.pack(opts, chunk));
2016-10-12 19:11:21 +00:00
}
2016-10-06 05:02:28 +00:00
} while (chunk);
2016-09-30 19:04:27 +00:00
});
localclients[cid].on('error', clientHandlers.onError.bind(null, cid, opts));
localclients[cid].on('end', clientHandlers.onClose.bind(null, cid, opts));
2016-09-30 19:04:27 +00:00
}
, onend: function (opts) {
2016-10-06 05:55:48 +00:00
var cid = Packer.addrToId(opts);
2016-09-30 19:04:27 +00:00
//console.log("[end] '" + cid + "'");
clientHandlers.closeSingle(cid);
2016-09-30 19:04:27 +00:00
}
, onerror: function (opts) {
2016-10-06 05:55:48 +00:00
var cid = Packer.addrToId(opts);
2016-09-30 19:04:27 +00:00
//console.log("[error] '" + cid + "'", opts.code || '', opts.message);
clientHandlers.closeSingle(cid);
2016-09-30 19:04:27 +00:00
}
, _onConnectError: function (cid, opts, err) {
console.info("[_onConnectError] opening '" + cid + "' failed because " + err.message);
2017-04-08 00:49:52 +00:00
wsHandlers.sendMessage(Packer.pack(opts, null, 'error'));
2016-09-30 19:04:27 +00:00
}
};
2017-04-08 00:49:52 +00:00
var retry = true;
var retryTimeout;
2016-09-30 19:04:27 +00:00
var wsHandlers = {
onOpen: function () {
console.info("[open] connected to '" + copts.stunneld + "'");
2016-09-30 01:10:40 +00:00
}
2016-09-30 19:04:27 +00:00
, onClose: function () {
console.log('ON CLOSE');
2017-04-08 00:49:52 +00:00
wstunneler = null;
clientHandlers.closeAll();
2016-09-30 19:04:27 +00:00
if (!authenticated) {
console.info('[close] failed on first attempt... check authentication.');
}
2017-04-08 00:49:52 +00:00
else if (retry) {
2016-09-30 19:04:27 +00:00
console.info('[retry] disconnected and waiting...');
2017-04-08 00:49:52 +00:00
retryTimeout = setTimeout(connect, 5000);
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) {
console.error("[tunnel error] " + err.message);
2016-09-30 05:23:03 +00:00
console.error(err);
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) {
if (wstunneler) {
try {
wstunneler.send(msg, {binary: true})
} catch (err) {
console.warn('[sendMessage] error sending websocket message', err);
}
}
}
};
function connect() {
if (!retry) {
return;
}
retryTimeout = null;
var machine = require('tunnel-packer').create(packerHandlers);
console.info("[connect] '" + copts.stunneld + "'");
wstunneler = new WebSocket(tunnelUrl, { rejectUnauthorized: !copts.insecure });
wstunneler.on('open', wsHandlers.onOpen);
wstunneler.on('close', wsHandlers.onClose);
wstunneler.on('error', wsHandlers.onError);
wstunneler.on('message', function (data, flags) {
if (data.error || '{' === data[0]) {
console.log(data);
return;
}
machine.fns.addChunk(data, flags);
});
}
connect();
function sigHandler() {
console.log('SIGINT');
// We want to handle cleanup properly unless something is broken in our cleanup process
// that prevents us from exitting, in which case we want the user to be able to send
// the signal again and exit the way it normally would.
process.removeListener('SIGINT', sigHandler);
2017-04-08 00:49:52 +00:00
retry = false;
if (retryTimeout) {
clearTimeout(retryTimeout);
retryTimeout = null;
}
if (wstunneler) {
2016-09-30 05:46:00 +00:00
try {
wstunneler.close();
} catch(e) {
2016-09-30 19:04:27 +00:00
console.error("[error] wstunneler.close()");
2016-09-30 05:46:00 +00:00
console.error(e);
}
}
2017-04-08 00:49:52 +00:00
}
process.on('SIGINT', sigHandler);
2016-09-30 19:04:27 +00:00
}
2016-09-30 05:46:00 +00:00
2016-09-30 19:04:27 +00:00
module.exports.connect = run;
2016-09-30 01:10:40 +00:00
}());