You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.0 KiB

4 years ago
  1. 'use strict'
  2. var os = require('os')
  3. var util = require('util')
  4. var EventEmitter = require('events').EventEmitter
  5. var serviceName = require('multicast-dns-service-types')
  6. var txt = require('dns-txt')()
  7. var TLD = '.local'
  8. module.exports = Service
  9. util.inherits(Service, EventEmitter)
  10. function Service (opts) {
  11. if (!opts.name) throw new Error('Required name not given')
  12. if (!opts.type) throw new Error('Required type not given')
  13. if (!opts.port) throw new Error('Required port not given')
  14. this.name = opts.name
  15. this.protocol = opts.protocol || 'tcp'
  16. this.type = serviceName.stringify(opts.type, this.protocol)
  17. this.host = opts.host || os.hostname()
  18. this.port = opts.port
  19. this.fqdn = this.name + '.' + this.type + TLD
  20. this.subtypes = opts.subtypes || null
  21. this.txt = opts.txt || null
  22. this.published = false
  23. this._activated = false // indicates intent - true: starting/started, false: stopping/stopped
  24. }
  25. Service.prototype._records = function () {
  26. var records = [rr_ptr(this), rr_srv(this), rr_txt(this)]
  27. var self = this
  28. var interfaces = os.networkInterfaces()
  29. Object.keys(interfaces).forEach(function (name) {
  30. interfaces[name].forEach(function (addr) {
  31. if (addr.internal) return
  32. if (addr.family === 'IPv4') {
  33. records.push(rr_a(self, addr.address))
  34. } else {
  35. records.push(rr_aaaa(self, addr.address))
  36. }
  37. })
  38. })
  39. return records
  40. }
  41. function rr_ptr (service) {
  42. return {
  43. name: service.type + TLD,
  44. type: 'PTR',
  45. ttl: 28800,
  46. data: service.fqdn
  47. }
  48. }
  49. function rr_srv (service) {
  50. return {
  51. name: service.fqdn,
  52. type: 'SRV',
  53. ttl: 120,
  54. data: {
  55. port: service.port,
  56. target: service.host
  57. }
  58. }
  59. }
  60. function rr_txt (service) {
  61. return {
  62. name: service.fqdn,
  63. type: 'TXT',
  64. ttl: 4500,
  65. data: txt.encode(service.txt)
  66. }
  67. }
  68. function rr_a (service, ip) {
  69. return {
  70. name: service.host,
  71. type: 'A',
  72. ttl: 120,
  73. data: ip
  74. }
  75. }
  76. function rr_aaaa (service, ip) {
  77. return {
  78. name: service.host,
  79. type: 'AAAA',
  80. ttl: 120,
  81. data: ip
  82. }
  83. }