Debian Codegraph @

portfinder/lib/portfinder.js

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