browser.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. 'use strict'
  2. var util = require('util')
  3. var EventEmitter = require('events').EventEmitter
  4. var serviceName = require('multicast-dns-service-types')
  5. var dnsEqual = require('dns-equal')
  6. var dnsTxt = require('dns-txt')
  7. var TLD = '.local'
  8. var WILDCARD = '_services._dns-sd._udp' + TLD
  9. module.exports = Browser
  10. util.inherits(Browser, EventEmitter)
  11. /**
  12. * Start a browser
  13. *
  14. * The browser listens for services by querying for PTR records of a given
  15. * type, protocol and domain, e.g. _http._tcp.local.
  16. *
  17. * If no type is given, a wild card search is performed.
  18. *
  19. * An internal list of online services is kept which starts out empty. When
  20. * ever a new service is discovered, it's added to the list and an "up" event
  21. * is emitted with that service. When it's discovered that the service is no
  22. * longer available, it is removed from the list and a "down" event is emitted
  23. * with that service.
  24. */
  25. function Browser (mdns, opts, onup) {
  26. if (typeof opts === 'function') return new Browser(mdns, null, opts)
  27. EventEmitter.call(this)
  28. this._mdns = mdns
  29. this._onresponse = null
  30. this._serviceMap = {}
  31. this._txt = dnsTxt(opts.txt)
  32. if (!opts || !opts.type) {
  33. this._name = WILDCARD
  34. this._wildcard = true
  35. } else {
  36. this._name = serviceName.stringify(opts.type, opts.protocol || 'tcp') + TLD
  37. if (opts.name) this._name = opts.name + '.' + this._name
  38. this._wildcard = false
  39. }
  40. this.services = []
  41. if (onup) this.on('up', onup)
  42. this.start()
  43. }
  44. Browser.prototype.start = function () {
  45. if (this._onresponse) return
  46. var self = this
  47. // List of names for the browser to listen for. In a normal search this will
  48. // be the primary name stored on the browser. In case of a wildcard search
  49. // the names will be determined at runtime as responses come in.
  50. var nameMap = {}
  51. if (!this._wildcard) nameMap[this._name] = true
  52. this._onresponse = function (packet, rinfo) {
  53. if (self._wildcard) {
  54. packet.answers.forEach(function (answer) {
  55. if (answer.type !== 'PTR' || answer.name !== self._name || answer.name in nameMap) return
  56. nameMap[answer.data] = true
  57. self._mdns.query(answer.data, 'PTR')
  58. })
  59. }
  60. Object.keys(nameMap).forEach(function (name) {
  61. // unregister all services shutting down
  62. goodbyes(name, packet).forEach(self._removeService.bind(self))
  63. // register all new services
  64. var matches = buildServicesFor(name, packet, self._txt, rinfo)
  65. if (matches.length === 0) return
  66. matches.forEach(function (service) {
  67. if (self._serviceMap[service.fqdn]) return // ignore already registered services
  68. self._addService(service)
  69. })
  70. })
  71. }
  72. this._mdns.on('response', this._onresponse)
  73. this.update()
  74. }
  75. Browser.prototype.stop = function () {
  76. if (!this._onresponse) return
  77. this._mdns.removeListener('response', this._onresponse)
  78. this._onresponse = null
  79. }
  80. Browser.prototype.update = function () {
  81. this._mdns.query(this._name, 'PTR')
  82. }
  83. Browser.prototype._addService = function (service) {
  84. this.services.push(service)
  85. this._serviceMap[service.fqdn] = true
  86. this.emit('up', service)
  87. }
  88. Browser.prototype._removeService = function (fqdn) {
  89. var service, index
  90. this.services.some(function (s, i) {
  91. if (dnsEqual(s.fqdn, fqdn)) {
  92. service = s
  93. index = i
  94. return true
  95. }
  96. })
  97. if (!service) return
  98. this.services.splice(index, 1)
  99. delete this._serviceMap[fqdn]
  100. this.emit('down', service)
  101. }
  102. // PTR records with a TTL of 0 is considered a "goodbye" announcement. I.e. a
  103. // DNS response broadcasted when a service shuts down in order to let the
  104. // network know that the service is no longer going to be available.
  105. //
  106. // For more info see:
  107. // https://tools.ietf.org/html/rfc6762#section-8.4
  108. //
  109. // This function returns an array of all resource records considered a goodbye
  110. // record
  111. function goodbyes (name, packet) {
  112. return packet.answers.concat(packet.additionals)
  113. .filter(function (rr) {
  114. return rr.type === 'PTR' && rr.ttl === 0 && dnsEqual(rr.name, name)
  115. })
  116. .map(function (rr) {
  117. return rr.data
  118. })
  119. }
  120. function buildServicesFor (name, packet, txt, referer) {
  121. var records = packet.answers.concat(packet.additionals).filter(function (rr) {
  122. return rr.ttl > 0 // ignore goodbye messages
  123. })
  124. return records
  125. .filter(function (rr) {
  126. return rr.type === 'PTR' && dnsEqual(rr.name, name)
  127. })
  128. .map(function (ptr) {
  129. var service = {
  130. addresses: []
  131. }
  132. records
  133. .filter(function (rr) {
  134. return (rr.type === 'SRV' || rr.type === 'TXT') && dnsEqual(rr.name, ptr.data)
  135. })
  136. .forEach(function (rr) {
  137. if (rr.type === 'SRV') {
  138. var parts = rr.name.split('.')
  139. var name = parts[0]
  140. var types = serviceName.parse(parts.slice(1, -1).join('.'))
  141. service.name = name
  142. service.fqdn = rr.name
  143. service.host = rr.data.target
  144. service.referer = referer
  145. service.port = rr.data.port
  146. service.type = types.name
  147. service.protocol = types.protocol
  148. service.subtypes = types.subtypes
  149. } else if (rr.type === 'TXT') {
  150. service.rawTxt = rr.data
  151. service.txt = txt.decode(rr.data)
  152. }
  153. })
  154. if (!service.name) return
  155. records
  156. .filter(function (rr) {
  157. return (rr.type === 'A' || rr.type === 'AAAA') && dnsEqual(rr.name, service.host)
  158. })
  159. .forEach(function (rr) {
  160. service.addresses.push(rr.data)
  161. })
  162. return service
  163. })
  164. .filter(function (rr) {
  165. return !!rr
  166. })
  167. }