portfinder.js 14 KB

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