portfinder.js 14 KB

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