Blame view

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