sclient.js/index.js

80 lines
2.2 KiB
JavaScript
Raw Normal View History

2018-08-06 18:27:33 +00:00
'use strict';
var net = require('net');
var tls = require('tls');
2018-09-11 07:51:42 +00:00
function listenForConns(emitter, opts) {
function pipeConn(c, out) {
2018-08-06 18:27:33 +00:00
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);
2018-08-06 18:27:33 +00:00
});
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) {
2018-09-11 07:51:42 +00:00
pipeConn(opts.stdin, opts.stdout);
return;
}
var server = net.createServer(pipeConn);
2018-08-06 18:27:33 +00:00
server.on('error', function (err) {
console.error('[error] ' + err.toString());
});
server.listen({
host: opts.localAddress
, port: opts.localPort
}, function () {
2018-09-11 07:51:42 +00:00
opts.localPort = this.address().port;
opts.server = this;
emitter.emit('listening', opts);
2018-08-06 18:27:33 +00:00
});
}
function testConn(opts) {
2018-09-11 07:51:42 +00:00
var emitter = new (require('events').EventEmitter)();
2018-08-06 18:27:33 +00:00
// Test connection first
var tlsOpts = {
host: opts.remoteAddr, port: opts.remotePort
2018-08-06 18:27:33 +00:00
, rejectUnauthorized: opts.rejectUnauthorized
};
if (opts.servername) {
tlsOpts.servername = opts.servername;
2018-09-11 07:51:42 +00:00
} else if (/^[\w\.\-]+\.[a-z]{2,}$/i.test(opts.remoteAddr)) {
tlsOpts.servername = opts.remoteAddr.toLowerCase();
}
if (opts.alpn) {
tlsOpts.ALPNProtocols = [ 'http', 'h2' ];
}
var tlsSock = tls.connect(tlsOpts, function () {
2018-09-11 07:51:42 +00:00
setTimeout(function () {
tlsSock.end();
listenForConns(emitter, opts);
}, 200);
2018-08-06 18:27:33 +00:00
});
tlsSock.on('error', function (err) {
console.warn("[warn] '" + opts.remoteAddr + ":" + opts.remotePort + "' may not be accepting connections: ", err.toString(), '\n');
2018-09-11 07:51:42 +00:00
listenForConns(emitter, opts);
2018-08-06 18:27:33 +00:00
});
2018-09-11 07:51:42 +00:00
return emitter;
2018-08-06 18:27:33 +00:00
}
module.exports = testConn;