index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. /**
  2. * @fileOverview
  3. * A simple promises-based check to see if a TCP port is already in use.
  4. */
  5. 'use strict';
  6. // define the exports first to avoid cyclic dependencies.
  7. exports.check = check;
  8. exports.waitUntilFreeOnHost = waitUntilFreeOnHost;
  9. exports.waitUntilFree = waitUntilFree;
  10. exports.waitUntilUsedOnHost = waitUntilUsedOnHost;
  11. exports.waitUntilUsed = waitUntilUsed;
  12. exports.waitForStatus = waitForStatus;
  13. var is = require('is2');
  14. var net = require('net');
  15. var util = require('util');
  16. var debug = require('debug')('tcp-port-used');
  17. // Global Values
  18. var TIMEOUT = 2000;
  19. var RETRYTIME = 250;
  20. function getDeferred() {
  21. var resolve, reject, promise = new Promise(function(res, rej) {
  22. resolve = res;
  23. reject = rej;
  24. });
  25. return {
  26. resolve: resolve,
  27. reject: reject,
  28. promise: promise
  29. };
  30. }
  31. /**
  32. * Creates an options object from all the possible arguments
  33. * @private
  34. * @param {Number} port a valid TCP port number
  35. * @param {String} host The DNS name or IP address.
  36. * @param {Boolean} status The desired in use status to wait for: false === not in use, true === in use
  37. * @param {Number} retryTimeMs the retry interval in milliseconds - defaultis is 200ms
  38. * @param {Number} timeOutMs the amount of time to wait until port is free default is 1000ms
  39. * @return {Object} An options object with all the above parameters as properties.
  40. */
  41. function makeOptionsObj(port, host, inUse, retryTimeMs, timeOutMs) {
  42. var opts = {};
  43. opts.port = port;
  44. opts.host = host;
  45. opts.inUse = inUse;
  46. opts.retryTimeMs = retryTimeMs;
  47. opts.timeOutMs = timeOutMs;
  48. return opts;
  49. }
  50. /**
  51. * Checks if a TCP port is in use by creating the socket and binding it to the
  52. * target port. Once bound, successfully, it's assume the port is availble.
  53. * After the socket is closed or in error, the promise is resolved.
  54. * Note: you have to be super user to correctly test system ports (0-1023).
  55. * @param {Number|Object} port The port you are curious to see if available. If an object, must have the parameters as properties.
  56. * @param {String} [host] May be a DNS name or IP address. Default '127.0.0.1'
  57. * @return {Object} A deferred Q promise.
  58. *
  59. * Example usage:
  60. *
  61. * var tcpPortUsed = require('tcp-port-used');
  62. * tcpPortUsed.check(22, '127.0.0.1')
  63. * .then(function(inUse) {
  64. * debug('Port 22 usage: '+inUse);
  65. * }, function(err) {
  66. * console.error('Error on check: '+util.inspect(err));
  67. * });
  68. */
  69. function check(port, host) {
  70. var deferred = getDeferred();
  71. var inUse = true;
  72. var client;
  73. var opts;
  74. if (!is.obj(port)) {
  75. opts = makeOptionsObj(port, host);
  76. } else {
  77. opts = port;
  78. }
  79. if (!is.port(opts.port)) {
  80. debug('Error invalid port: '+util.inspect(opts.port));
  81. deferred.reject(new Error('invalid port: '+util.inspect(opts.port)));
  82. return deferred.promise;
  83. }
  84. if (is.nullOrUndefined(opts.host)) {
  85. debug('set host address to default 127.0.0.1');
  86. opts.host = '127.0.0.1';
  87. }
  88. function cleanUp() {
  89. if (client) {
  90. client.removeAllListeners('connect');
  91. client.removeAllListeners('error');
  92. client.end();
  93. client.destroy();
  94. client.unref();
  95. }
  96. //debug('listeners removed from client socket');
  97. }
  98. function onConnectCb() {
  99. //debug('check - promise resolved - in use');
  100. deferred.resolve(inUse);
  101. cleanUp();
  102. }
  103. function onErrorCb(err) {
  104. if (err.code !== 'ECONNREFUSED') {
  105. //debug('check - promise rejected, error: '+err.message);
  106. deferred.reject(err);
  107. } else {
  108. //debug('ECONNREFUSED');
  109. inUse = false;
  110. //debug('check - promise resolved - not in use');
  111. deferred.resolve(inUse);
  112. }
  113. cleanUp();
  114. }
  115. client = new net.Socket();
  116. client.once('connect', onConnectCb);
  117. client.once('error', onErrorCb);
  118. client.connect({port: opts.port, host: opts.host}, function() {});
  119. return deferred.promise;
  120. }
  121. /**
  122. * Creates a deferred promise and fulfills it only when the socket's usage
  123. * equals status in terms of 'in use' (false === not in use, true === in use).
  124. * Will retry on an interval specified in retryTimeMs. Note: you have to be
  125. * super user to correctly test system ports (0-1023).
  126. * @param {Number|Object} port a valid TCP port number, if an object, has all the parameters described as properties.
  127. * @param {String} host The DNS name or IP address.
  128. * @param {Boolean} status The desired in use status to wait for false === not in use, true === in use
  129. * @param {Number} [retryTimeMs] the retry interval in milliseconds - defaultis is 200ms
  130. * @param {Number} [timeOutMs] the amount of time to wait until port is free default is 1000ms
  131. * @return {Object} A deferred promise from the Q library.
  132. *
  133. * Example usage:
  134. *
  135. * var tcpPortUsed = require('tcp-port-used');
  136. * tcpPortUsed.waitForStatus(44204, 'some.host.com', true, 500, 4000)
  137. * .then(function() {
  138. * console.log('Port 44204 is now in use.');
  139. * }, function(err) {
  140. * console.log('Error: ', error.message);
  141. * });
  142. */
  143. function waitForStatus(port, host, inUse, retryTimeMs, timeOutMs) {
  144. var deferred = getDeferred();
  145. var timeoutId;
  146. var timedout = false;
  147. var retryId;
  148. // the first arument may be an object, if it is not, make an object
  149. var opts;
  150. if (is.obj(port)) {
  151. opts = port;
  152. } else {
  153. opts = makeOptionsObj(port, host, inUse, retryTimeMs, timeOutMs);
  154. }
  155. //debug('opts:'+util.inspect(opts);
  156. if (!is.bool(opts.inUse)) {
  157. deferred.reject(new Error('inUse must be a boolean'));
  158. return deferred.promise;
  159. }
  160. if (!is.positiveInt(opts.retryTimeMs)) {
  161. opts.retryTimeMs = RETRYTIME;
  162. debug('set retryTime to default '+RETRYTIME+'ms');
  163. }
  164. if (!is.positiveInt(opts.timeOutMs)) {
  165. opts.timeOutMs = TIMEOUT;
  166. debug('set timeOutMs to default '+TIMEOUT+'ms');
  167. }
  168. function cleanUp() {
  169. if (timeoutId) {
  170. clearTimeout(timeoutId);
  171. }
  172. if (retryId) {
  173. clearTimeout(retryId);
  174. }
  175. }
  176. function timeoutFunc() {
  177. timedout = true;
  178. cleanUp();
  179. deferred.reject(new Error('timeout'));
  180. }
  181. timeoutId = setTimeout(timeoutFunc, opts.timeOutMs);
  182. function doCheck() {
  183. check(opts.port, opts.host)
  184. .then(function(inUse) {
  185. if (timedout) {
  186. return;
  187. }
  188. //debug('doCheck inUse: '+inUse);
  189. //debug('doCheck opts.inUse: '+opts.inUse);
  190. if (inUse === opts.inUse) {
  191. deferred.resolve();
  192. cleanUp();
  193. return;
  194. } else {
  195. retryId = setTimeout(function() { doCheck(); }, opts.retryTimeMs);
  196. return;
  197. }
  198. }, function(err) {
  199. if (timedout) {
  200. return;
  201. }
  202. deferred.reject(err);
  203. cleanUp();
  204. });
  205. }
  206. doCheck();
  207. return deferred.promise;
  208. }
  209. /**
  210. * Creates a deferred promise and fulfills it only when the socket is free.
  211. * Will retry on an interval specified in retryTimeMs.
  212. * Note: you have to be super user to correctly test system ports (0-1023).
  213. * @param {Number} port a valid TCP port number
  214. * @param {String} [host] The hostname or IP address of where the socket is.
  215. * @param {Number} [retryTimeMs] the retry interval in milliseconds - defaultis is 100ms.
  216. * @param {Number} [timeOutMs] the amount of time to wait until port is free. Default 300ms.
  217. * @return {Object} A deferred promise from the q library.
  218. *
  219. * Example usage:
  220. *
  221. * var tcpPortUsed = require('tcp-port-used');
  222. * tcpPortUsed.waitUntilFreeOnHost(44203, 'some.host.com', 500, 4000)
  223. * .then(function() {
  224. * console.log('Port 44203 is now free.');
  225. * }, function(err) {
  226. * console.loh('Error: ', error.message);
  227. * });
  228. */
  229. function waitUntilFreeOnHost(port, host, retryTimeMs, timeOutMs) {
  230. // the first arument may be an object, if it is not, make an object
  231. var opts;
  232. if (is.obj(port)) {
  233. opts = port;
  234. opts.inUse = false;
  235. } else {
  236. opts = makeOptionsObj(port, host, false, retryTimeMs, timeOutMs);
  237. }
  238. return waitForStatus(opts);
  239. }
  240. /**
  241. * For compatibility with previous version of the module, that did not provide
  242. * arguements for hostnames. The host is set to the localhost '127.0.0.1'.
  243. * @param {Number|Object} port a valid TCP port number. If an object, must contain all the parameters as properties.
  244. * @param {Number} [retryTimeMs] the retry interval in milliseconds - defaultis is 100ms.
  245. * @param {Number} [timeOutMs] the amount of time to wait until port is free. Default 300ms.
  246. * @return {Object} A deferred promise from the q library.
  247. *
  248. * Example usage:
  249. *
  250. * var tcpPortUsed = require('tcp-port-used');
  251. * tcpPortUsed.waitUntilFree(44203, 500, 4000)
  252. * .then(function() {
  253. * console.log('Port 44203 is now free.');
  254. * }, function(err) {
  255. * console.loh('Error: ', error.message);
  256. * });
  257. */
  258. function waitUntilFree(port, retryTimeMs, timeOutMs) {
  259. // the first arument may be an object, if it is not, make an object
  260. var opts;
  261. if (is.obj(port)) {
  262. opts = port;
  263. opts.host = '127.0.0.1';
  264. opts.inUse = false;
  265. } else {
  266. opts = makeOptionsObj(port, '127.0.0.1', false, retryTimeMs, timeOutMs);
  267. }
  268. return waitForStatus(opts);
  269. }
  270. /**
  271. * Creates a deferred promise and fulfills it only when the socket is used.
  272. * Will retry on an interval specified in retryTimeMs.
  273. * Note: you have to be super user to correctly test system ports (0-1023).
  274. * @param {Number|Object} port a valid TCP port number. If an object, must contain all the parameters as properties.
  275. * @param {Number} [retryTimeMs] the retry interval in milliseconds - defaultis is 500ms
  276. * @param {Number} [timeOutMs] the amount of time to wait until port is free
  277. * @return {Object} A deferred promise from the q library.
  278. *
  279. * Example usage:
  280. *
  281. * var tcpPortUsed = require('tcp-port-used');
  282. * tcpPortUsed.waitUntilUsedOnHost(44204, 'some.host.com', 500, 4000)
  283. * .then(function() {
  284. * console.log('Port 44204 is now in use.');
  285. * }, function(err) {
  286. * console.log('Error: ', error.message);
  287. * });
  288. */
  289. function waitUntilUsedOnHost(port, host, retryTimeMs, timeOutMs) {
  290. // the first arument may be an object, if it is not, make an object
  291. var opts;
  292. if (is.obj(port)) {
  293. opts = port;
  294. opts.inUse = true;
  295. } else {
  296. opts = makeOptionsObj(port, host, true, retryTimeMs, timeOutMs);
  297. }
  298. return waitForStatus(opts);
  299. }
  300. /**
  301. * For compatibility to previous version of module which did not have support
  302. * for host addresses. This function works only for localhost.
  303. * @param {Number} port a valid TCP port number. If an Object, must contain all the parameters as properties.
  304. * @param {Number} [retryTimeMs] the retry interval in milliseconds - defaultis is 500ms
  305. * @param {Number} [timeOutMs] the amount of time to wait until port is free
  306. * @return {Object} A deferred promise from the q library.
  307. *
  308. * Example usage:
  309. *
  310. * var tcpPortUsed = require('tcp-port-used');
  311. * tcpPortUsed.waitUntilUsed(44204, 500, 4000)
  312. * .then(function() {
  313. * console.log('Port 44204 is now in use.');
  314. * }, function(err) {
  315. * console.log('Error: ', error.message);
  316. * });
  317. */
  318. function waitUntilUsed(port, retryTimeMs, timeOutMs) {
  319. // the first arument may be an object, if it is not, make an object
  320. var opts;
  321. if (is.obj(port)) {
  322. opts = port;
  323. opts.host = '127.0.0.1';
  324. opts.inUse = true;
  325. } else {
  326. opts = makeOptionsObj(port, '127.0.0.1', true, retryTimeMs, timeOutMs);
  327. }
  328. return waitUntilUsedOnHost(opts);
  329. }