123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497 |
- "use strict";
- var fs = require('fs'),
- os = require('os'),
- net = require('net'),
- path = require('path'),
- _async = require('async'),
- debug = require('debug'),
- mkdirp = require('mkdirp').mkdirp;
- var debugTestPort = debug('portfinder:testPort'),
- debugGetPort = debug('portfinder:getPort'),
- debugDefaultHosts = debug('portfinder:defaultHosts');
- var internals = {};
- internals.testPort = function(options, callback) {
- if (!callback) {
- callback = options;
- options = {};
- }
- options.server = options.server || net.createServer(function () {
-
-
-
- });
- debugTestPort("entered testPort(): trying", options.host, "port", options.port);
- function onListen () {
- debugTestPort("done w/ testPort(): OK", options.host, "port", options.port);
- options.server.removeListener('error', onError);
- options.server.close();
- callback(null, options.port);
- }
- function onError (err) {
- debugTestPort("done w/ testPort(): failed", options.host, "w/ port", options.port, "with error", err.code);
- options.server.removeListener('listening', onListen);
- if (!(err.code == 'EADDRINUSE' || err.code == 'EACCES')) {
- return callback(err);
- }
- var nextPort = exports.nextPort(options.port);
- if (nextPort > exports.highestPort) {
- return callback(new Error('No open ports available'));
- }
- internals.testPort({
- port: nextPort,
- host: options.host,
- server: options.server
- }, callback);
- }
- options.server.once('error', onError);
- options.server.once('listening', onListen);
- if (options.host) {
- options.server.listen(options.port, options.host);
- } else {
-
- options.server.listen(options.port);
- }
- };
- exports.basePort = 8000;
- exports.highestPort = 65535;
- exports.basePath = '/tmp/portfinder'
- exports.getPort = function (options, callback) {
- if (!callback) {
- callback = options;
- options = {};
- }
- options.port = Number(options.port) || Number(exports.basePort);
- options.host = options.host || null;
- options.stopPort = Number(options.stopPort) || Number(exports.highestPort);
- if(!options.startPort) {
- options.startPort = Number(options.port);
- if(options.startPort < 0) {
- throw Error('Provided options.startPort(' + options.startPort + ') is less than 0, which are cannot be bound.');
- }
- if(options.stopPort < options.startPort) {
- throw Error('Provided options.stopPort(' + options.stopPort + 'is less than options.startPort (' + options.startPort + ')');
- }
- }
- if (options.host) {
- var hasUserGivenHost;
- for (var i = 0; i < exports._defaultHosts.length; i++) {
- if (exports._defaultHosts[i] === options.host) {
- hasUserGivenHost = true;
- break;
- }
- }
- if (!hasUserGivenHost) {
- exports._defaultHosts.push(options.host);
- }
- }
- var openPorts = [], currentHost;
- return _async.eachSeries(exports._defaultHosts, function(host, next) {
- debugGetPort("in eachSeries() iteration callback: host is", host);
- return internals.testPort({ host: host, port: options.port }, function(err, port) {
- if (err) {
- debugGetPort("in eachSeries() iteration callback testPort() callback", "with an err:", err.code);
- currentHost = host;
- return next(err);
- } else {
- debugGetPort("in eachSeries() iteration callback testPort() callback",
- "with a success for port", port);
- openPorts.push(port);
- return next();
- }
- });
- }, function(err) {
- if (err) {
- debugGetPort("in eachSeries() result callback: err is", err);
-
-
- if (err.code === 'EADDRNOTAVAIL' || err.code === 'EINVAL') {
- if (options.host === currentHost) {
-
-
-
-
-
- var msg = 'Provided host ' + options.host + ' could NOT be bound. Please provide a different host address or hostname';
- return callback(Error(msg));
- } else {
- var idx = exports._defaultHosts.indexOf(currentHost);
- exports._defaultHosts.splice(idx, 1);
- return exports.getPort(options, callback);
- }
- } else {
-
- return callback(err);
- }
- }
-
- openPorts.sort(function(a, b) {
- return a - b;
- });
- debugGetPort("in eachSeries() result callback: openPorts is", openPorts);
- if (openPorts[0] === openPorts[openPorts.length-1]) {
-
- if(openPorts[0] <= options.stopPort) {
- return callback(null, openPorts[0]);
- }
- else {
- var msg = 'No open ports found in between '+ options.startPort + ' and ' + options.stopPort;
- return callback(Error(msg));
- }
- } else {
-
- return exports.getPort({ port: openPorts.pop(), host: options.host, startPort: options.startPort, stopPort: options.stopPort }, callback);
- }
- });
- };
- exports.getPortPromise = function (options) {
- if (typeof Promise !== 'function') {
- throw Error('Native promise support is not available in this version of node.' +
- 'Please install a polyfill and assign Promise to global.Promise before calling this method');
- }
- if (!options) {
- options = {};
- }
- return new Promise(function(resolve, reject) {
- exports.getPort(options, function(err, port) {
- if (err) {
- return reject(err);
- }
- resolve(port);
- });
- });
- }
- exports.getPorts = function (count, options, callback) {
- if (!callback) {
- callback = options;
- options = {};
- }
- var lastPort = null;
- _async.timesSeries(count, function(index, asyncCallback) {
- if (lastPort) {
- options.port = exports.nextPort(lastPort);
- }
- exports.getPort(options, function (err, port) {
- if (err) {
- asyncCallback(err);
- } else {
- lastPort = port;
- asyncCallback(null, port);
- }
- });
- }, callback);
- };
- exports.getSocket = function (options, callback) {
- if (!callback) {
- callback = options;
- options = {};
- }
- options.mod = options.mod || parseInt(755, 8);
- options.path = options.path || exports.basePath + '.sock';
-
-
-
- function testSocket () {
- fs.stat(options.path, function (err) {
-
-
-
-
- if (err) {
- if (err.code == 'ENOENT') {
- callback(null, options.path);
- }
- else {
- callback(err);
- }
- }
- else {
-
-
-
-
- options.path = exports.nextSocket(options.path);
- exports.getSocket(options, callback);
- }
- });
- }
-
-
-
-
- function createAndTestSocket (dir) {
- mkdirp(dir, options.mod, function (err) {
- if (err) {
- return callback(err);
- }
- options.exists = true;
- testSocket();
- });
- }
-
-
-
-
-
-
- function checkAndTestSocket () {
- var dir = path.dirname(options.path);
- fs.stat(dir, function (err, stats) {
- if (err || !stats.isDirectory()) {
- return createAndTestSocket(dir);
- }
- options.exists = true;
- testSocket();
- });
- }
-
-
-
-
-
- return options.exists
- ? testSocket()
- : checkAndTestSocket();
- };
- exports.nextPort = function (port) {
- return port + 1;
- };
- exports.nextSocket = function (socketPath) {
- var dir = path.dirname(socketPath),
- name = path.basename(socketPath, '.sock'),
- match = name.match(/^([a-zA-z]+)(\d*)$/i),
- index = parseInt(match[2]),
- base = match[1];
- if (isNaN(index)) {
- index = 0;
- }
- index += 1;
- return path.join(dir, base + index + '.sock');
- };
- exports._defaultHosts = (function() {
- var interfaces = {};
- try{
- interfaces = os.networkInterfaces();
- }
- catch(e) {
-
-
-
-
-
-
-
-
-
- if (e.syscall === 'uv_interface_addresses') {
-
-
- } else {
- throw e;
- }
- }
- var interfaceNames = Object.keys(interfaces),
- hiddenButImportantHost = '0.0.0.0',
- results = [hiddenButImportantHost];
- for (var i = 0; i < interfaceNames.length; i++) {
- var _interface = interfaces[interfaceNames[i]];
- for (var j = 0; j < _interface.length; j++) {
- var curr = _interface[j];
- results.push(curr.address);
- }
- }
-
- results.push(null);
- debugDefaultHosts("exports._defaultHosts is: %o", results);
- return results;
- }());
|