diff --git a/lib/sorting-hat.js b/lib/sorting-hat.js index 1f2c91d..436395b 100644 --- a/lib/sorting-hat.js +++ b/lib/sorting-hat.js @@ -141,6 +141,40 @@ module.exports.assign = function (state, tun, cb) { return conn; } + function errorTcp(conf, cb) { + var socketPair = require('socket-pair'); + var conn = socketPair.create(function (err, other) { + if (err) { cb(err); return; } + + cb(null, conn); + + other.write("\n" + + [ "[Telebit Error Server]" + , "Could not load '" + conf.handler + "' as a module, file, or directory." + ].join("\n") + "\n\n"); + other.end(); + }); + //if (tun.data) { conn.write(tun.data); } + return conn; + } + function fileDirTcp(conf, cb) { + var socketPair = require('socket-pair'); + var conn = socketPair.create(function (err, other) { + if (err) { cb(err); return; } + + if (conf._stat.isFile()) { + fs.createReadStream(conf.handler).pipe(other); + } else { + fs.readdir(conf.handler, function (err, nodes) { + other.write('\n' + nodes.join('\n') + '\n\n'); + other.end(); + }); + } + cb(null, conn); + }); + //if (tun.data) { conn.write(tun.data); } + return conn; + } function echoTcp(cb) { var socketPair = require('socket-pair'); var conn = socketPair.create(function (err, other) { @@ -228,16 +262,30 @@ module.exports.assign = function (state, tun, cb) { console.error("Failed to require('" + handlerpath + "'):", e1.message); console.error("Failed to require('" + path.join(localshare, handlerpath) + "'):", e2.message); console.warn("Trying static and index handlers for '" + handle + ":" + id + "'"); - echoTcp(cb); - return; + handler = null; + // fallthru } } - var socketPair = require('socket-pair'); - conn = socketPair.create(function (err, other) { - handler(other, tun, id); - cb(null, conn); + + if (handler) { + var socketPair = require('socket-pair'); + conn = socketPair.create(function (err, other) { + handler(other, tun, id); + cb(null, conn); + }); + return conn; + } + + fs.access(conf.handler, fs.constants.R_OK, function (err1) { + fs.stat(conf.handler, function (err2, stat) { + if (err1 || err2 && (stat.isFile() || stat.isDirectory())) { + errorTcp(conf, cb); + return; + } + conf._stat = stat; + fileDirTcp(conf, cb); + }); }); - return conn; } var handlerservers = {}; function invokeHandler(conf, tlsSocket, tun, id) { @@ -289,7 +337,7 @@ module.exports.assign = function (state, tun, cb) { } catch(e2) { console.error("Failed to require('" + handlerpath + "'):", e1.message); console.error("Failed to require('" + path.join(localshare, handlerpath) + "'):", e2.message); - console.warn("Using default handler for '" + handle + ":" + id + "'"); + console.warn("Trying static and index handlers for '" + handle + ":" + id + "'"); handler = null; // fallthru }