UNPKG

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