sclient.js/index.js

68 lines
1.9 KiB
JavaScript

'use strict';
var net = require('net');
var tls = require('tls');
function listenForConns(opts) {
function pipeConn(c, out) {
var sclient = tls.connect({
servername: opts.remoteAddr, host: opts.remoteAddr, port: opts.remotePort
, rejectUnauthorized: opts.rejectUnauthorized
}, function () {
console.info('[connect] ' + sclient.localAddress.replace('::1', 'localhost') + ":" + sclient.localPort
+ " => " + opts.remoteAddr + ":" + opts.remotePort);
c.pipe(sclient);
sclient.pipe(out || c);
});
sclient.on('error', function (err) {
console.error('[error] (remote) ' + err.toString());
});
c.on('error', function (err) {
console.error('[error] (local) ' + err.toString());
});
if (out) {
out.on('error', function (err) {
console.error('[error] (local) ' + err.toString());
});
}
}
if ('-' === opts.localAddress || '|' === opts.localAddress) {
pipeConn(process.stdin, process.stdout);
return;
}
var server = net.createServer(pipeConn);
server.on('error', function (err) {
console.error('[error] ' + err.toString());
});
server.listen({
host: opts.localAddress
, port: opts.localPort
}, function () {
console.info('[listening] ' + opts.remoteAddr + ":" + opts.remotePort
+ " <= " + opts.localAddress + ":" + opts.localPort);
});
}
function testConn(opts) {
// Test connection first
var tlsOpts = {
host: opts.remoteAddr, port: opts.remotePort
, rejectUnauthorized: opts.rejectUnauthorized
};
if (opts.servername) {
tlsOpts.servername = opts.servername;
}
var tlsSock = tls.connect(tlsOpts, function () {
tlsSock.end();
listenForConns(opts);
});
tlsSock.on('error', function (err) {
console.warn("[warn] '" + opts.remoteAddr + ":" + opts.remotePort + "' may not be accepting connections: ", err.toString(), '\n');
listenForConns(opts);
});
}
module.exports = testConn;