UNPKG

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