sclient.js/index.js

79 lines
2.0 KiB
JavaScript

'use strict';
var PromiseA = global.Promise;
var net = require('net');
var tls = require('tls');
function listenForConns(emitter, opts) {
function pipeConn(c, out) {
var sclient = tls.connect({
servername: opts.remoteAddr, host: opts.remoteAddr, port: opts.remotePort
, rejectUnauthorized: opts.rejectUnauthorized
}, function () {
emitter.emit('connect', sclient);
c.pipe(sclient);
sclient.pipe(out || c);
});
sclient.on('error', function (err) {
emitter.emit('remote-error', err);
});
c.on('error', function (err) {
emitter.emit('local-error', err);
});
if (out) {
out.on('error', function (err) {
emitter.emit('local-error', err);
});
}
}
if ('-' === opts.localAddress || '|' === opts.localAddress) {
pipeConn(opts.stdin, opts.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 () {
opts.localPort = this.address().port;
opts.server = this;
emitter.emit('listening', opts);
});
}
function testConn(opts) {
return new PromiseA(function (resolve, reject) {
// Test connection first
var tlsOpts = {
host: opts.remoteAddr, port: opts.remotePort
, rejectUnauthorized: opts.rejectUnauthorized
};
if (opts.servername) {
tlsOpts.servername = opts.servername;
} 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 () {
tlsSock.end();
resolve();
});
tlsSock.on('error', function (err) {
reject(err);
});
});
}
// no public exports yet
// the API is for the commandline only
module.exports._test = testConn;
module.exports._listen = listenForConns;