portfinder.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. /*
  2. * portfinder.js: A simple tool to find an open port on the current machine.
  3. *
  4. * (C) 2011, Charlie Robbins
  5. *
  6. */
  7. "use strict";
  8. var fs = require('fs'),
  9. os = require('os'),
  10. net = require('net'),
  11. path = require('path'),
  12. _async = require('async'),
  13. debug = require('debug'),
  14. mkdirp = require('mkdirp').mkdirp;
  15. var debugTestPort = debug('portfinder:testPort'),
  16. debugGetPort = debug('portfinder:getPort'),
  17. debugDefaultHosts = debug('portfinder:defaultHosts');
  18. var internals = {};
  19. internals.testPort = function(options, callback) {
  20. if (!callback) {
  21. callback = options;
  22. options = {};
  23. }
  24. options.server = options.server || net.createServer(function () {
  25. //
  26. // Create an empty listener for the port testing server.
  27. //
  28. });
  29. debugTestPort("entered testPort(): trying", options.host, "port", options.port);
  30. function onListen () {
  31. debugTestPort("done w/ testPort(): OK", options.host, "port", options.port);
  32. options.server.removeListener('error', onError);
  33. options.server.close();
  34. callback(null, options.port);
  35. }
  36. function onError (err) {
  37. debugTestPort("done w/ testPort(): failed", options.host, "w/ port", options.port, "with error", err.code);
  38. options.server.removeListener('listening', onListen);
  39. if (!(err.code == 'EADDRINUSE' || err.code == 'EACCES')) {
  40. return callback(err);
  41. }
  42. var nextPort = exports.nextPort(options.port);
  43. if (nextPort > exports.highestPort) {
  44. return callback(new Error('No open ports available'));
  45. }
  46. internals.testPort({
  47. port: nextPort,
  48. host: options.host,
  49. server: options.server
  50. }, callback);
  51. }
  52. options.server.once('error', onError);
  53. options.server.once('listening', onListen);
  54. if (options.host) {
  55. options.server.listen(options.port, options.host);
  56. } else {
  57. /*
  58. Judgement of service without host
  59. example:
  60. express().listen(options.port)
  61. */
  62. options.server.listen(options.port);
  63. }
  64. };
  65. //
  66. // ### @basePort {Number}
  67. // The lowest port to begin any port search from
  68. //
  69. exports.basePort = 8000;
  70. //
  71. // ### function setBasePort (port)
  72. // #### @port {Number} The new base port
  73. //
  74. exports.setBasePort = function (port) {
  75. exports.basePort = port;
  76. }
  77. //
  78. // ### @highestPort {Number}
  79. // Largest port number is an unsigned short 2**16 -1=65335
  80. //
  81. exports.highestPort = 65535;
  82. //
  83. // ### function setHighestPort (port)
  84. // #### @port {Number} The new highest port
  85. //
  86. exports.setHighestPort = function (port) {
  87. exports.highestPort = port;
  88. }
  89. //
  90. // ### @basePath {string}
  91. // Default path to begin any socket search from
  92. //
  93. exports.basePath = '/tmp/portfinder'
  94. //
  95. // ### function getPort (options, callback)
  96. // #### @options {Object} Settings to use when finding the necessary port
  97. // #### @callback {function} Continuation to respond to when complete.
  98. // Responds with a unbound port on the current machine.
  99. //
  100. exports.getPort = function (options, callback) {
  101. if (!callback) {
  102. callback = options;
  103. options = {};
  104. }
  105. options.port = Number(options.port) || Number(exports.basePort);
  106. options.host = options.host || null;
  107. options.stopPort = Number(options.stopPort) || Number(exports.highestPort);
  108. if(!options.startPort) {
  109. options.startPort = Number(options.port);
  110. if(options.startPort < 0) {
  111. throw Error('Provided options.startPort(' + options.startPort + ') is less than 0, which are cannot be bound.');
  112. }
  113. if(options.stopPort < options.startPort) {
  114. throw Error('Provided options.stopPort(' + options.stopPort + 'is less than options.startPort (' + options.startPort + ')');
  115. }
  116. }
  117. if (options.host) {
  118. if (exports._defaultHosts.indexOf(options.host) !== -1) {
  119. exports._defaultHosts.push(options.host)
  120. }
  121. }
  122. var openPorts = [], currentHost;
  123. return _async.eachSeries(exports._defaultHosts, function(host, next) {
  124. debugGetPort("in eachSeries() iteration callback: host is", host);
  125. return internals.testPort({ host: host, port: options.port }, function(err, port) {
  126. if (err) {
  127. debugGetPort("in eachSeries() iteration callback testPort() callback", "with an err:", err.code);
  128. currentHost = host;
  129. return next(err);
  130. } else {
  131. debugGetPort("in eachSeries() iteration callback testPort() callback",
  132. "with a success for port", port);
  133. openPorts.push(port);
  134. return next();
  135. }
  136. });
  137. }, function(err) {
  138. if (err) {
  139. debugGetPort("in eachSeries() result callback: err is", err);
  140. // If we get EADDRNOTAVAIL it means the host is not bindable, so remove it
  141. // from exports._defaultHosts and start over. For ubuntu, we use EINVAL for the same
  142. if (err.code === 'EADDRNOTAVAIL' || err.code === 'EINVAL') {
  143. if (options.host === currentHost) {
  144. // if bad address matches host given by user, tell them
  145. //
  146. // NOTE: We may need to one day handle `my-non-existent-host.local` if users
  147. // report frustration with passing in hostnames that DONT map to bindable
  148. // hosts, without showing them a good error.
  149. var msg = 'Provided host ' + options.host + ' could NOT be bound. Please provide a different host address or hostname';
  150. return callback(Error(msg));
  151. } else {
  152. var idx = exports._defaultHosts.indexOf(currentHost);
  153. exports._defaultHosts.splice(idx, 1);
  154. return exports.getPort(options, callback);
  155. }
  156. } else {
  157. // error is not accounted for, file ticket, handle special case
  158. return callback(err);
  159. }
  160. }
  161. // sort so we can compare first host to last host
  162. openPorts.sort(function(a, b) {
  163. return a - b;
  164. });
  165. debugGetPort("in eachSeries() result callback: openPorts is", openPorts);
  166. if (openPorts[0] === openPorts[openPorts.length-1]) {
  167. // if first === last, we found an open port
  168. if(openPorts[0] <= options.stopPort) {
  169. return callback(null, openPorts[0]);
  170. }
  171. else {
  172. var msg = 'No open ports found in between '+ options.startPort + ' and ' + options.stopPort;
  173. return callback(Error(msg));
  174. }
  175. } else {
  176. // otherwise, try again, using sorted port, aka, highest open for >= 1 host
  177. return exports.getPort({ port: openPorts.pop(), host: options.host, startPort: options.startPort, stopPort: options.stopPort }, callback);
  178. }
  179. });
  180. };
  181. //
  182. // ### function getPortPromise (options)
  183. // #### @options {Object} Settings to use when finding the necessary port
  184. // Responds a promise to an unbound port on the current machine.
  185. //
  186. exports.getPortPromise = function (options) {
  187. if (typeof Promise !== 'function') {
  188. throw Error('Native promise support is not available in this version of node.' +
  189. 'Please install a polyfill and assign Promise to global.Promise before calling this method');
  190. }
  191. if (!options) {
  192. options = {};
  193. }
  194. return new Promise(function(resolve, reject) {
  195. exports.getPort(options, function(err, port) {
  196. if (err) {
  197. return reject(err);
  198. }
  199. resolve(port);
  200. });
  201. });
  202. }
  203. //
  204. // ### function getPorts (count, options, callback)
  205. // #### @count {Number} The number of ports to find
  206. // #### @options {Object} Settings to use when finding the necessary port
  207. // #### @callback {function} Continuation to respond to when complete.
  208. // Responds with an array of unbound ports on the current machine.
  209. //
  210. exports.getPorts = function (count, options, callback) {
  211. if (!callback) {
  212. callback = options;
  213. options = {};
  214. }
  215. var lastPort = null;
  216. _async.timesSeries(count, function(index, asyncCallback) {
  217. if (lastPort) {
  218. options.port = exports.nextPort(lastPort);
  219. }
  220. exports.getPort(options, function (err, port) {
  221. if (err) {
  222. asyncCallback(err);
  223. } else {
  224. lastPort = port;
  225. asyncCallback(null, port);
  226. }
  227. });
  228. }, callback);
  229. };
  230. //
  231. // ### function getSocket (options, callback)
  232. // #### @options {Object} Settings to use when finding the necessary port
  233. // #### @callback {function} Continuation to respond to when complete.
  234. // Responds with a unbound socket using the specified directory and base
  235. // name on the current machine.
  236. //
  237. exports.getSocket = function (options, callback) {
  238. if (!callback) {
  239. callback = options;
  240. options = {};
  241. }
  242. options.mod = options.mod || parseInt(755, 8);
  243. options.path = options.path || exports.basePath + '.sock';
  244. //
  245. // Tests the specified socket
  246. //
  247. function testSocket () {
  248. fs.stat(options.path, function (err) {
  249. //
  250. // If file we're checking doesn't exist (thus, stating it emits ENOENT),
  251. // we should be OK with listening on this socket.
  252. //
  253. if (err) {
  254. if (err.code == 'ENOENT') {
  255. callback(null, options.path);
  256. }
  257. else {
  258. callback(err);
  259. }
  260. }
  261. else {
  262. //
  263. // This file exists, so it isn't possible to listen on it. Lets try
  264. // next socket.
  265. //
  266. options.path = exports.nextSocket(options.path);
  267. exports.getSocket(options, callback);
  268. }
  269. });
  270. }
  271. //
  272. // Create the target `dir` then test connection
  273. // against the socket.
  274. //
  275. function createAndTestSocket (dir) {
  276. mkdirp(dir, options.mod, function (err) {
  277. if (err) {
  278. return callback(err);
  279. }
  280. options.exists = true;
  281. testSocket();
  282. });
  283. }
  284. //
  285. // Check if the parent directory of the target
  286. // socket path exists. If it does, test connection
  287. // against the socket. Otherwise, create the directory
  288. // then test connection.
  289. //
  290. function checkAndTestSocket () {
  291. var dir = path.dirname(options.path);
  292. fs.stat(dir, function (err, stats) {
  293. if (err || !stats.isDirectory()) {
  294. return createAndTestSocket(dir);
  295. }
  296. options.exists = true;
  297. testSocket();
  298. });
  299. }
  300. //
  301. // If it has been explicitly stated that the
  302. // target `options.path` already exists, then
  303. // simply test the socket.
  304. //
  305. return options.exists
  306. ? testSocket()
  307. : checkAndTestSocket();
  308. };
  309. //
  310. // ### function nextPort (port)
  311. // #### @port {Number} Port to increment from.
  312. // Gets the next port in sequence from the
  313. // specified `port`.
  314. //
  315. exports.nextPort = function (port) {
  316. return port + 1;
  317. };
  318. //
  319. // ### function nextSocket (socketPath)
  320. // #### @socketPath {string} Path to increment from
  321. // Gets the next socket path in sequence from the
  322. // specified `socketPath`.
  323. //
  324. exports.nextSocket = function (socketPath) {
  325. var dir = path.dirname(socketPath),
  326. name = path.basename(socketPath, '.sock'),
  327. match = name.match(/^([a-zA-z]+)(\d*)$/i),
  328. index = parseInt(match[2]),
  329. base = match[1];
  330. if (isNaN(index)) {
  331. index = 0;
  332. }
  333. index += 1;
  334. return path.join(dir, base + index + '.sock');
  335. };
  336. /**
  337. * @desc List of internal hostnames provided by your machine. A user
  338. * provided hostname may also be provided when calling portfinder.getPort,
  339. * which would then be added to the default hosts we lookup and return here.
  340. *
  341. * @return {array}
  342. *
  343. * Long Form Explantion:
  344. *
  345. * - Input: (os.networkInterfaces() w/ MacOS 10.11.5+ and running a VM)
  346. *
  347. * { lo0:
  348. * [ { address: '::1',
  349. * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
  350. * family: 'IPv6',
  351. * mac: '00:00:00:00:00:00',
  352. * scopeid: 0,
  353. * internal: true },
  354. * { address: '127.0.0.1',
  355. * netmask: '255.0.0.0',
  356. * family: 'IPv4',
  357. * mac: '00:00:00:00:00:00',
  358. * internal: true },
  359. * { address: 'fe80::1',
  360. * netmask: 'ffff:ffff:ffff:ffff::',
  361. * family: 'IPv6',
  362. * mac: '00:00:00:00:00:00',
  363. * scopeid: 1,
  364. * internal: true } ],
  365. * en0:
  366. * [ { address: 'fe80::a299:9bff:fe17:766d',
  367. * netmask: 'ffff:ffff:ffff:ffff::',
  368. * family: 'IPv6',
  369. * mac: 'a0:99:9b:17:76:6d',
  370. * scopeid: 4,
  371. * internal: false },
  372. * { address: '10.0.1.22',
  373. * netmask: '255.255.255.0',
  374. * family: 'IPv4',
  375. * mac: 'a0:99:9b:17:76:6d',
  376. * internal: false } ],
  377. * awdl0:
  378. * [ { address: 'fe80::48a8:37ff:fe34:aaef',
  379. * netmask: 'ffff:ffff:ffff:ffff::',
  380. * family: 'IPv6',
  381. * mac: '4a:a8:37:34:aa:ef',
  382. * scopeid: 8,
  383. * internal: false } ],
  384. * vnic0:
  385. * [ { address: '10.211.55.2',
  386. * netmask: '255.255.255.0',
  387. * family: 'IPv4',
  388. * mac: '00:1c:42:00:00:08',
  389. * internal: false } ],
  390. * vnic1:
  391. * [ { address: '10.37.129.2',
  392. * netmask: '255.255.255.0',
  393. * family: 'IPv4',
  394. * mac: '00:1c:42:00:00:09',
  395. * internal: false } ] }
  396. *
  397. * - Output:
  398. *
  399. * [
  400. * '0.0.0.0',
  401. * '::1',
  402. * '127.0.0.1',
  403. * 'fe80::1',
  404. * '10.0.1.22',
  405. * 'fe80::48a8:37ff:fe34:aaef',
  406. * '10.211.55.2',
  407. * '10.37.129.2'
  408. * ]
  409. *
  410. * Note we export this so we can use it in our tests, otherwise this API is private
  411. */
  412. exports._defaultHosts = (function() {
  413. var interfaces = {};
  414. try{
  415. interfaces = os.networkInterfaces();
  416. }
  417. catch(e) {
  418. // As of October 2016, Windows Subsystem for Linux (WSL) does not support
  419. // the os.networkInterfaces() call and throws instead. For this platform,
  420. // assume 0.0.0.0 as the only address
  421. //
  422. // - https://github.com/Microsoft/BashOnWindows/issues/468
  423. //
  424. // - Workaround is a mix of good work from the community:
  425. // - https://github.com/http-party/node-portfinder/commit/8d7e30a648ff5034186551fa8a6652669dec2f2f
  426. // - https://github.com/yarnpkg/yarn/pull/772/files
  427. if (e.syscall === 'uv_interface_addresses') {
  428. // swallow error because we're just going to use defaults
  429. // documented @ https://github.com/nodejs/node/blob/4b65a65e75f48ff447cabd5500ce115fb5ad4c57/doc/api/net.md#L231
  430. } else {
  431. throw e;
  432. }
  433. }
  434. var interfaceNames = Object.keys(interfaces),
  435. hiddenButImportantHost = '0.0.0.0', // !important - dont remove, hence the naming :)
  436. results = [hiddenButImportantHost];
  437. for (var i = 0; i < interfaceNames.length; i++) {
  438. var _interface = interfaces[interfaceNames[i]];
  439. for (var j = 0; j < _interface.length; j++) {
  440. var curr = _interface[j];
  441. results.push(curr.address);
  442. }
  443. }
  444. // add null value, For createServer function, do not use host.
  445. results.push(null);
  446. debugDefaultHosts("exports._defaultHosts is: %o", results);
  447. return results;
  448. }());