portfinder.js 13 KB

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