forked from coolaj86/goldilocks.js
74 lines
1.4 KiB
JavaScript
74 lines
1.4 KiB
JavaScript
'use strict';
|
|
|
|
module.exports.create = function () {
|
|
var PromiseA = require('bluebird');
|
|
var enableDestroy = require('server-destroy');
|
|
var server;
|
|
|
|
function curState() {
|
|
if (!server) {
|
|
return PromiseA.resolve({running: false});
|
|
}
|
|
return PromiseA.resolve({
|
|
running: true
|
|
, port: server.address().port
|
|
});
|
|
}
|
|
|
|
function start() {
|
|
if (server) {
|
|
return curState();
|
|
}
|
|
|
|
server = require('socksv5').createServer(function (info, accept) {
|
|
accept();
|
|
});
|
|
|
|
enableDestroy(server);
|
|
server.on('close', function () {
|
|
server = null;
|
|
});
|
|
|
|
server.useAuth(require('socksv5').auth.None());
|
|
|
|
return new PromiseA(function (resolve, reject) {
|
|
server.on('error', function (err) {
|
|
if (err.code === 'EADDRINUSE') {
|
|
server.listen(0);
|
|
} else {
|
|
server = null;
|
|
reject(err);
|
|
}
|
|
});
|
|
server.listen(1080, function () {
|
|
resolve(curState());
|
|
});
|
|
});
|
|
}
|
|
|
|
function stop() {
|
|
if (!server) {
|
|
return curState();
|
|
}
|
|
return new PromiseA(function (resolve, reject) {
|
|
var timeoutId = setTimeout(function () {
|
|
server.destroy();
|
|
}, 1000);
|
|
server.close(function (err) {
|
|
clearTimeout(timeoutId);
|
|
if (err) {
|
|
reject(err);
|
|
} else {
|
|
resolve();
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
return {
|
|
isRunning: curState
|
|
, start: start
|
|
, stop: stop
|
|
};
|
|
};
|