2017-06-21 00:16:11 +00:00
|
|
|
'use strict';
|
|
|
|
|
2017-08-04 21:23:15 +00:00
|
|
|
module.exports.create = function (deps, config) {
|
2017-06-21 00:16:11 +00:00
|
|
|
var PromiseA = require('bluebird');
|
|
|
|
var server;
|
|
|
|
|
|
|
|
function curState() {
|
2017-07-11 00:24:59 +00:00
|
|
|
var addr = server && server.address();
|
|
|
|
if (!addr) {
|
2017-06-21 00:16:11 +00:00
|
|
|
return PromiseA.resolve({running: false});
|
|
|
|
}
|
|
|
|
return PromiseA.resolve({
|
|
|
|
running: true
|
2017-07-11 00:24:59 +00:00
|
|
|
, port: addr.port
|
2017-06-21 00:16:11 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-08-04 21:23:15 +00:00
|
|
|
function start(port) {
|
2017-06-21 00:16:11 +00:00
|
|
|
if (server) {
|
|
|
|
return curState();
|
|
|
|
}
|
|
|
|
|
|
|
|
server = require('socksv5').createServer(function (info, accept) {
|
|
|
|
accept();
|
|
|
|
});
|
|
|
|
|
2017-07-11 00:24:59 +00:00
|
|
|
// 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.
|
2017-06-21 00:16:11 +00:00
|
|
|
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') {
|
2017-06-21 00:16:11 +00:00
|
|
|
server.listen(0);
|
|
|
|
} else {
|
|
|
|
server = null;
|
|
|
|
reject(err);
|
|
|
|
}
|
|
|
|
});
|
2017-08-04 21:23:15 +00:00
|
|
|
server.listen(port || 1080, function () {
|
2017-06-21 00:16:11 +00:00
|
|
|
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-06-21 00:16:11 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
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);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-06-21 00:16:11 +00:00
|
|
|
return {
|
2017-07-07 19:48:40 +00:00
|
|
|
curState: curState
|
2017-06-21 00:16:11 +00:00
|
|
|
, start: start
|
|
|
|
, stop: stop
|
|
|
|
};
|
|
|
|
};
|