sterfive-bonjour-service
Version:
A Bonjour/Zeroconf implementation in TypeScript
187 lines • 7.48 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Browser = void 0;
const events_1 = require("events");
const service_types_1 = require("./service-types");
const dns_txt_1 = __importDefault(require("./dns-txt"));
const dnsEqual = require('dns-equal');
const TLD = '.local';
const WILDCARD = '_services._dns-sd._udp' + TLD;
/**
* Start a browser
*
* The browser listens for services by querying for PTR records of a given
* type, protocol and domain, e.g. _http._tcp.local.
*
* If no type is given, a wild card search is performed.
*
* An internal list of online services is kept which starts out empty. When
* ever a new service is discovered, it's added to the list and an "up" event
* is emitted with that service. When it's discovered that the service is no
* longer available, it is removed from the list and a "down" event is emitted
* with that service.
*/
class Browser extends events_1.EventEmitter {
constructor(mdns, opts, onup) {
super();
this.serviceMap = {};
this.wildcard = false;
this._services = [];
if (typeof opts === 'function')
return new Browser(mdns, null, opts);
this.mdns = mdns;
if (opts != null && opts.txt != null) {
this.txt = new dns_txt_1.default(opts.txt);
}
else {
this.txt = new dns_txt_1.default();
}
if (!opts || !opts.type) {
this.name = WILDCARD;
this.wildcard = true;
}
else {
this.name = (0, service_types_1.toString)({ name: opts.type, protocol: opts.protocol || 'tcp' }) + TLD;
if (opts.name)
this.name = opts.name + '.' + this.name;
this.wildcard = false;
}
if (onup)
this.on('up', onup);
this.start();
}
start() {
var _a;
if (this.onresponse || this.name === undefined)
return;
const self = this;
// List of names for the browser to listen for. In a normal search this will
// be the primary name stored on the browser. In case of a wildcard search
// the names will be determined at runtime as responses come in.
const nameMap = {};
if (!this.wildcard)
nameMap[this.name] = true;
this.onresponse = (packet, rinfo) => {
if (self.wildcard) {
packet.answers.forEach((answer) => {
var _a;
if (answer.type !== 'PTR' || answer.name !== self.name || answer.name in nameMap)
return;
nameMap[answer.data] = true;
(_a = self.mdns) === null || _a === void 0 ? void 0 : _a.query(answer.data, 'PTR');
});
}
Object.keys(nameMap).forEach((name) => {
// unregister all services shutting down
self.goodbyes(name, packet).forEach(self.removeService.bind(self));
// register all new services
const matches = self.buildServicesFor(name, packet, self.txt, rinfo);
if (matches.length === 0)
return;
matches.forEach((service) => {
if (self.serviceMap[service.fqdn])
return; // ignore already registered services
self.addService(service);
});
});
};
(_a = this.mdns) === null || _a === void 0 ? void 0 : _a.on('response', this.onresponse);
this.update();
}
stop() {
var _a;
if (!this.onresponse)
return;
(_a = this.mdns) === null || _a === void 0 ? void 0 : _a.removeListener('response', this.onresponse);
this.onresponse = undefined;
}
update() {
var _a;
(_a = this.mdns) === null || _a === void 0 ? void 0 : _a.query(this.name || '', 'PTR');
}
get services() {
return this._services;
}
addService(service) {
this._services.push(service);
this.serviceMap[service.fqdn] = true;
this.emit('up', service);
}
removeService(fqdn) {
let service, index;
this._services.some(function (s, i) {
if (dnsEqual(s.fqdn, fqdn)) {
service = s;
index = i;
return true;
}
});
if (!service || index === undefined)
return;
this._services.splice(index, 1);
delete this.serviceMap[fqdn];
this.emit('down', service);
}
// PTR records with a TTL of 0 is considered a "goodbye" announcement. I.e. a
// DNS response broadcasted when a service shuts down in order to let the
// network know that the service is no longer going to be available.
//
// For more info see:
// https://tools.ietf.org/html/rfc6762#section-8.4
//
// This function returns an array of all resource records considered a goodbye
// record
goodbyes(name, packet) {
return packet.answers
.concat(packet.additionals)
.filter((rr) => rr.type === 'PTR' && rr.ttl === 0 && dnsEqual(rr.name, name))
.map((rr) => rr.data);
}
buildServicesFor(name, packet, txt, referer) {
const records = packet.answers.concat(packet.additionals).filter((rr) => rr.ttl > 0); // ignore goodbye messages
return records
.filter((rr) => rr.type === 'PTR' && dnsEqual(rr.name, name))
.map((ptr) => {
const service = {
addresses: []
};
records
.filter((rr) => {
return (rr.type === 'SRV' || rr.type === 'TXT') && dnsEqual(rr.name, ptr.data);
})
.forEach((rr) => {
var _a;
if (rr.type === 'SRV') {
const parts = rr.name.split('.');
const name = parts[0];
const types = (0, service_types_1.toType)(parts.slice(1, -1).join('.'));
service.name = name;
service.fqdn = rr.name;
service.host = rr.data.target;
service.referer = referer;
service.port = rr.data.port;
service.type = types.name;
service.protocol = types.protocol;
service.subtypes = types.subtypes;
}
else if (rr.type === 'TXT') {
service.rawTxt = rr.data;
service.txt = (_a = this.txt) === null || _a === void 0 ? void 0 : _a.decodeAll(rr.data);
}
});
if (!service.name)
return;
records
.filter((rr) => (rr.type === 'A' || rr.type === 'AAAA') && dnsEqual(rr.name, service.host))
.forEach((rr) => service.addresses.push(rr.data));
return service;
})
.filter((rr) => !!rr);
}
}
exports.Browser = Browser;
exports.default = Browser;
//# sourceMappingURL=browser.js.map