portscanner.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. var net = require('net')
  2. var Socket = net.Socket
  3. var async = require('async')
  4. var isNumberLike = require('is-number-like')
  5. var promisify = require('./promisify')
  6. /**
  7. * Finds the first port with a status of 'open', implying the port is in use and
  8. * there is likely a service listening on it.
  9. */
  10. /**
  11. * @param {Number} startPort - Port to begin status check on (inclusive).
  12. * @param {Number} [endPort=65535] - Last port to check status on (inclusive).
  13. * @param {String} [host='127.0.0.1'] - Host of where to scan.
  14. * @param {findPortCallback} [callback] - Function to call back with error or results.
  15. * @returns {Promise}
  16. * @example
  17. * // scans through 3000 to 3002 (inclusive)
  18. * portscanner.findAPortInUse(3000, 3002, '127.0.0.1', console.log)
  19. * // returns a promise in the absence of a callback
  20. * portscanner.findAPortInUse(3000, 3002, '127.0.0.1').then(console.log)
  21. * @example
  22. * // scans through 3000 to 65535 on '127.0.0.1'
  23. * portscanner.findAPortInUse(3000, console.log)
  24. */
  25. /**
  26. * @param {Array} postList - Array of ports to check status on.
  27. * @param {String} [host='127.0.0.1'] - Host of where to scan.
  28. * @param {findPortCallback} [callback] - Function to call back with error or results.
  29. * @returns {Promise}
  30. * @example
  31. * // scans 3000 and 3002 only, not 3001.
  32. * portscanner.findAPortInUse([3000, 3002], console.log)
  33. */
  34. function findAPortInUse () {
  35. var params = [].slice.call(arguments)
  36. params.unshift('open')
  37. return findAPortWithStatus.apply(null, params)
  38. }
  39. /**
  40. * Finds the first port with a status of 'closed', implying the port is not in
  41. * use. Accepts identical parameters as {@link findAPortInUse}
  42. */
  43. function findAPortNotInUse () {
  44. var params = [].slice.call(arguments)
  45. params.unshift('closed')
  46. return findAPortWithStatus.apply(null, params)
  47. }
  48. /**
  49. * Checks the status of an individual port.
  50. */
  51. /**
  52. * @param {Number} port - Port to check status on.
  53. * @param {String} [host='127.0.0.1'] - Host of where to scan.
  54. * @param {checkPortCallback} [callback] - Function to call back with error or results.
  55. * @returns {Promise}
  56. */
  57. /**
  58. * @param {Number} port - Port to check status on.
  59. * @param {Object} [opts={}] - Options object.
  60. * @param {String} [opts.host='127.0.0.1'] - Host of where to scan.
  61. * @param {Number} [opts.timeout=400] - Connection timeout in ms.
  62. * @param {checkPortCallback} [callback] - Function to call back with error or results.
  63. * @returns {Promise}
  64. */
  65. function checkPortStatus (port) {
  66. var args, host, opts, callback
  67. args = [].slice.call(arguments, 1)
  68. if (typeof args[0] === 'string') {
  69. host = args[0]
  70. } else if (typeof args[0] === 'object') {
  71. opts = args[0]
  72. } else if (typeof args[0] === 'function') {
  73. callback = args[0]
  74. }
  75. if (typeof args[1] === 'object') {
  76. opts = args[1]
  77. } else if (typeof args[1] === 'function') {
  78. callback = args[1]
  79. }
  80. if (typeof args[2] === 'function') {
  81. callback = args[2]
  82. }
  83. if (!callback) return promisify(checkPortStatus, arguments)
  84. opts = opts || {}
  85. host = host || opts.host || '127.0.0.1'
  86. var timeout = opts.timeout || 400
  87. var connectionRefused = false
  88. var socket = new Socket()
  89. var status = null
  90. var error = null
  91. // Socket connection established, port is open
  92. socket.on('connect', function () {
  93. status = 'open'
  94. socket.destroy()
  95. })
  96. // If no response, assume port is not listening
  97. socket.setTimeout(timeout)
  98. socket.on('timeout', function () {
  99. status = 'closed'
  100. error = new Error('Timeout (' + timeout + 'ms) occurred waiting for ' + host + ':' + port + ' to be available')
  101. socket.destroy()
  102. })
  103. // Assuming the port is not open if an error. May need to refine based on
  104. // exception
  105. socket.on('error', function (exception) {
  106. if (exception.code !== 'ECONNREFUSED') {
  107. error = exception
  108. } else {
  109. connectionRefused = true
  110. }
  111. status = 'closed'
  112. })
  113. // Return after the socket has closed
  114. socket.on('close', function (exception) {
  115. if (exception && !connectionRefused) { error = error || exception } else { error = null }
  116. callback(error, status)
  117. })
  118. socket.connect(port, host)
  119. }
  120. /**
  121. * Callback for {@link checkPortStatus}
  122. * @callback checkPortCallback
  123. * @param {Error|null} error - Any error that occurred while port scanning, or null.
  124. * @param {String} status - Status: 'open' if the port is in use, 'closed' if the port is available.
  125. */
  126. /**
  127. * Internal helper function used by {@link findAPortInUse} and {@link findAPortNotInUse}
  128. * to find a port from a range or a list with a specific status.
  129. */
  130. /**
  131. * @param {String} status - Status to check.
  132. * @param {...params} params - Params as passed exactly to {@link findAPortInUse} and {@link findAPortNotInUse}.
  133. */
  134. function findAPortWithStatus (status) {
  135. var params, startPort, endPort, portList, host, callback
  136. params = [].slice.call(arguments, 1)
  137. if (params[0] instanceof Array) {
  138. portList = params[0]
  139. } else if (isNumberLike(params[0])) {
  140. startPort = parseInt(params[0], 10)
  141. }
  142. if (typeof params[1] === 'function') {
  143. callback = params[1]
  144. } else if (typeof params[1] === 'string') {
  145. host = params[1]
  146. } else if (isNumberLike(params[1])) {
  147. endPort = parseInt(params[1], 10)
  148. }
  149. if (typeof params[2] === 'string') {
  150. host = params[2]
  151. } else if (typeof params[2] === 'function') {
  152. callback = params[2]
  153. }
  154. if (typeof params[3] === 'function') {
  155. callback = params[3]
  156. }
  157. if (!callback) return promisify(findAPortWithStatus, arguments)
  158. if (startPort && endPort && endPort < startPort) {
  159. // WARNING: endPort less than startPort. Using endPort as startPort & vice versa.
  160. var tempStartPort = startPort
  161. startPort = endPort
  162. endPort = tempStartPort
  163. }
  164. endPort = endPort || 65535
  165. var foundPort = false
  166. var numberOfPortsChecked = 0
  167. var port = portList ? portList[0] : startPort
  168. // Returns true if a port with matching status has been found or if checked
  169. // the entire range of ports
  170. var hasFoundPort = function () {
  171. return foundPort || numberOfPortsChecked === (portList ? portList.length : endPort - startPort + 1)
  172. }
  173. // Checks the status of the port
  174. var checkNextPort = function (callback) {
  175. checkPortStatus(port, host, function (error, statusOfPort) {
  176. numberOfPortsChecked++
  177. if (statusOfPort === status) {
  178. foundPort = true
  179. callback(error)
  180. } else {
  181. port = portList ? portList[numberOfPortsChecked] : port + 1
  182. callback(null)
  183. }
  184. })
  185. }
  186. // Check the status of each port until one with a matching status has been
  187. // found or the range of ports has been exhausted
  188. async.until(hasFoundPort, checkNextPort, function (error) {
  189. if (error) {
  190. callback(error, port)
  191. } else if (foundPort) {
  192. callback(null, port)
  193. } else {
  194. callback(null, false)
  195. }
  196. })
  197. }
  198. /**
  199. * Callback for {@link findAPortWithStatus}, and by that extension, for {@link findAPortInUse} and {@link findAPortNotInUse}.
  200. * @callback findPortCallback
  201. * @param {Error|null} error - Any error that occurred while port scanning, or null.
  202. * @param {Number|Boolean} port - The first open port found. Note, this is the first port that returns status as 'open', not necessarily the first open port checked. If no open port is found, the value is false.
  203. */
  204. /**
  205. * @exports portscanner
  206. */
  207. module.exports = {
  208. findAPortInUse: findAPortInUse,
  209. findAPortNotInUse: findAPortNotInUse,
  210. checkPortStatus: checkPortStatus
  211. }