goldilocks.js/lib/socks5-server.js

78 lines
1.7 KiB
JavaScript
Raw Normal View History

'use strict';
2017-08-04 21:23:15 +00:00
module.exports.create = function (deps, config) {
var PromiseA = require('bluebird');
var server;
function curState() {
var addr = server && server.address();
if (!addr) {
return PromiseA.resolve({running: false});
}
return PromiseA.resolve({
running: true
, port: addr.port
});
}
2017-08-04 21:23:15 +00:00
function start(port) {
if (server) {
return curState();
}
server = require('socksv5').createServer(function (info, accept) {
accept();
});
// It would be nice if we could use `server-destroy` here, but we can't because
// the socksv5 library will not give us access to any sockets it actually
// handles, so we have no way of keeping track of them or closing them.
server.on('close', function () {
server = null;
});
server.useAuth(require('socksv5').auth.None());
return new PromiseA(function (resolve, reject) {
server.on('error', function (err) {
2017-08-04 21:23:15 +00:00
if (!port && err.code === 'EADDRINUSE') {
server.listen(0);
} else {
server = null;
reject(err);
}
});
2017-08-04 21:23:15 +00:00
server.listen(port || 1080, function () {
resolve(curState());
});
});
}
function stop() {
if (!server) {
return curState();
}
return new PromiseA(function (resolve, reject) {
server.close(function (err) {
if (err) {
reject(err);
} else {
2017-07-07 19:48:40 +00:00
resolve(curState());
}
});
});
}
2017-08-04 21:23:15 +00:00
if (config.socks5 && config.socks5.enabled) {
start(config.socks5.port).catch(function (err) {
console.error('failed to start Socks5 proxy', err);
});
}
return {
2017-07-07 19:48:40 +00:00
curState: curState
, start: start
, stop: stop
};
};