diff --git a/lib/sorting-hat.js b/lib/sorting-hat.js index 502fd65..12827bb 100644 --- a/lib/sorting-hat.js +++ b/lib/sorting-hat.js @@ -100,7 +100,7 @@ module.exports.assign = function (state, tun, cb) { state.defaultHttpServer.emit('connection', tlsSocket); }; - function getNetConn(port) { + function getNetConn(port, cb) { var netOpts = { port: port , host: '127.0.0.1' @@ -117,8 +117,12 @@ module.exports.assign = function (state, tun, cb) { // this will happen before 'data' or 'readable' is triggered // We use the data from the netOpts object so that the createConnection function has // the oppurtunity of removing/changing it if it wants/needs to handle it differently. + cb(null, conn); + cb = function () {}; // for error events + }); + conn.on('error', function (err) { + cb(err); }); - return conn; } function redirectHttp(cb) { @@ -194,8 +198,7 @@ module.exports.assign = function (state, tun, cb) { function invokeTcpHandler(conf, socket, tun, id, cb) { var conn; if (parseInt(conf.handler, 10)) { - conn = getNetConn(conf.handler); - cb(null, conn); + getNetConn(conf.handler, cb); return conn; } @@ -232,13 +235,20 @@ module.exports.assign = function (state, tun, cb) { } var handlerservers = {}; function invokeHandler(conf, tlsSocket, tun, id) { - var conn; if (parseInt(conf.handler, 10)) { // TODO http-proxy with proper headers and ws support - conn = getNetConn(conf.handler); - console.info("Port-Forwarding '" + (tun.name || tun.serviceport) + "' to '" + conf.handler + "'"); - conn.pipe(tlsSocket); - tlsSocket.pipe(conn); + getNetConn(conf.handler, function (err, conn) { + if (err) { + // TODO direct to site with error page + console.error("probably couldn't connect to handler"); + tlsSocket.write("Couldn't connect to localhost:" + conf.handler); + tlsSocket.end(); + return; + } + console.info("Port-Forwarding '" + (tun.name || tun.serviceport) + "' to '" + conf.handler + "'"); + conn.pipe(tlsSocket); + tlsSocket.pipe(conn); + }); return; } var handle = tun.name || tun.port;