1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | "use strict";
|
9 |
|
10 | var 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 |
|
18 | var debugTestPort = debug('portfinder:testPort'),
|
19 | debugGetPort = debug('portfinder:getPort'),
|
20 | debugDefaultHosts = debug('portfinder:defaultHosts');
|
21 |
|
22 | var internals = {};
|
23 |
|
24 | internals.testPort = function(options, callback) {
|
25 | if (!callback) {
|
26 | callback = options;
|
27 | options = {};
|
28 | }
|
29 |
|
30 | options.server = options.server || net.createServer(function () {
|
31 |
|
32 |
|
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 |
|
81 |
|
82 |
|
83 |
|
84 | options.server.listen(currentPort);
|
85 | }
|
86 | };
|
87 |
|
88 |
|
89 |
|
90 |
|
91 |
|
92 | exports.basePort = 8000;
|
93 |
|
94 |
|
95 |
|
96 |
|
97 |
|
98 |
|
99 |
|
100 |
|
101 |
|
102 | exports.highestPort = 40000;
|
103 | var _highestPort = 65535;
|
104 |
|
105 |
|
106 |
|
107 |
|
108 |
|
109 | exports.basePath = '/tmp/portfinder'
|
110 |
|
111 |
|
112 |
|
113 |
|
114 |
|
115 |
|
116 |
|
117 | exports.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 |
|
185 |
|
186 | if (err.code === 'EADDRNOTAVAIL' || err.code === 'EINVAL') {
|
187 | if (options.host === currentHost) {
|
188 |
|
189 |
|
190 |
|
191 |
|
192 |
|
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 |
|
202 | return callback(err);
|
203 | }
|
204 | }
|
205 |
|
206 |
|
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 |
|
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 |
|
224 | return exports.getPort({ port: openPorts.pop(), host: options.host, startPort: options.startPort, stopPort: options.stopPort }, callback);
|
225 | }
|
226 |
|
227 | });
|
228 | };
|
229 |
|
230 |
|
231 |
|
232 |
|
233 |
|
234 |
|
235 | exports.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 |
|
255 |
|
256 |
|
257 |
|
258 |
|
259 |
|
260 | exports.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 |
|
279 |
|
280 |
|
281 |
|
282 |
|
283 |
|
284 | exports.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 |
|
295 |
|
296 | function testSocket () {
|
297 | fs.stat(options.path, function (err) {
|
298 |
|
299 |
|
300 |
|
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 |
|
313 |
|
314 |
|
315 | options.path = exports.nextSocket(options.path);
|
316 | exports.getSocket(options, callback);
|
317 | }
|
318 | });
|
319 | }
|
320 |
|
321 |
|
322 |
|
323 |
|
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 |
|
338 |
|
339 |
|
340 |
|
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 |
|
357 |
|
358 |
|
359 |
|
360 | return options.exists
|
361 | ? testSocket()
|
362 | : checkAndTestSocket();
|
363 | };
|
364 |
|
365 |
|
366 |
|
367 |
|
368 |
|
369 |
|
370 |
|
371 | function 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 |
|
382 |
|
383 |
|
384 |
|
385 |
|
386 | exports.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 |
|
402 |
|
403 |
|
404 |
|
405 |
|
406 |
|
407 |
|
408 |
|
409 |
|
410 |
|
411 |
|
412 |
|
413 |
|
414 |
|
415 |
|
416 |
|
417 |
|
418 |
|
419 |
|
420 |
|
421 |
|
422 |
|
423 |
|
424 |
|
425 |
|
426 |
|
427 |
|
428 |
|
429 |
|
430 |
|
431 |
|
432 |
|
433 |
|
434 |
|
435 |
|
436 |
|
437 |
|
438 |
|
439 |
|
440 |
|
441 |
|
442 |
|
443 |
|
444 |
|
445 |
|
446 |
|
447 |
|
448 |
|
449 |
|
450 |
|
451 |
|
452 |
|
453 |
|
454 |
|
455 |
|
456 |
|
457 |
|
458 |
|
459 |
|
460 |
|
461 |
|
462 |
|
463 |
|
464 |
|
465 |
|
466 |
|
467 |
|
468 |
|
469 |
|
470 |
|
471 |
|
472 |
|
473 |
|
474 |
|
475 |
|
476 | exports._defaultHosts = (function() {
|
477 | var interfaces = {};
|
478 | try{
|
479 | interfaces = os.networkInterfaces();
|
480 | }
|
481 | catch(e) {
|
482 |
|
483 |
|
484 |
|
485 |
|
486 |
|
487 |
|
488 |
|
489 |
|
490 |
|
491 | if (e.syscall === 'uv_interface_addresses') {
|
492 |
|
493 |
|
494 | } else {
|
495 | throw e;
|
496 | }
|
497 | }
|
498 |
|
499 | var interfaceNames = Object.keys(interfaces),
|
500 | hiddenButImportantHost = '0.0.0.0',
|
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 |
|
511 | results.push(null);
|
512 |
|
513 | debugDefaultHosts("exports._defaultHosts is: %o", results);
|
514 |
|
515 | return results;
|
516 | }());
|