portfinder.js 16 KB

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