portfinder.js 14 KB

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