-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
430 lines (394 loc) · 12.7 KB
/
index.js
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
const dgram = require('dgram');
const packet = require('dns-packet');
const events = require('events');
const os = require('os');
const MDNS_IPV4 = '224.0.0.251';
const MDNS_IPV6 = 'FF02::FB';
const MDNS_PORT = 5353;
const ErrorMessages = {
NO_INTERFACES: 'No available interfaces.'
};
function familyIsIPV4(family) {
// string check for Node.js <= 17, number for >= 18
return family === 'IPv4' || family === 4;
}
module.exports = function (options) {
options = options || {};
var emitter = new events.EventEmitter();
var mDNS = {
config: {
reuseAddr: typeof options.reuseAddr === 'undefined' ? true : options.reuseAddr,
interfaces: options.interfaces || options.interface || null,
ttl: options.ttl || 255,
loopback: typeof options.loopback === 'undefined' ? true : options.loopback,
noInit: !!options.noInit,
srcPort: options.srcPort || 0
},
destroyed: false,
interfaces: [],
init: function () {
// build the list of network interfaces
if (!mDNS.config.interfaces) {
mDNS.config.interfaces = mDNS.getInterfaces();
} else if (mDNS.interfacesIsStrings(mDNS.config.interfaces)) {
mDNS.config.interfaces = mDNS.interfacesFromStrings(mDNS.config.interfaces);
}
if (!mDNS.config.interfaces || !mDNS.config.interfaces.length) {
emitter.emit('error', new Error(ErrorMessages.NO_INTERFACES));
}
// create sockets on interfaces
mDNS.interfaces = mDNS.config.interfaces.slice();
mDNS.createSockets()
.then(() => {
emitter.emit('ready');
})
.catch((err) => {
emitter.emit('error', err);
});
},
// create socket for each interface
createSockets: function () {
return new Promise((resolve, reject) => {
var processInterface = function (i) {
// check if complete
if (i >= mDNS.interfaces.length) {
if (mDNS.countListeningSockets()) {
resolve();
} else {
reject(new Error('No sockets created.'));
}
} else {
// process this interface
mDNS.createNewSockets(mDNS.interfaces[i])
.then((listening) => {
if (listening) {
mDNS.interfaces[i].listening = true;
}
// process next interface
processInterface(i + 1);
});
}
};
// start processing
processInterface(0);
});
},
// create new socket for an interface
createNewSockets: function (iface) {
return new Promise((resolve, reject) => {
mDNS.createSendSocket(iface)
.then(function () {
return mDNS.createReceiveSocket(iface);
})
.then(function () {
resolve(true);
})
.catch(function (err) {
iface.socketRecv = null;
iface.socketSend = null;
// socket failure, continue to next interface
resolve(false);
return err; // really only doing this to pass semistandard
});
});
},
createReceiveSocket: function (iface) {
return new Promise((resolve, reject) => {
iface.bindStatus = {
listening: false,
catchAll: false
};
mDNS.getReceiveSocket(iface)
.then(success => {
if (!success) {
// try again with catch-all address
iface.bindStatus.catchAll = true;
}
return success || mDNS.getReceiveSocket(iface);
})
.then(success => {
if (!success) {
reject(new Error('Failed to get receive socket'));
} else {
resolve();
}
})
.catch(err => { reject(err); });
});
},
// get a receive socket for the given interface
getReceiveSocket: function (iface) {
const isIPV4 = familyIsIPV4(iface.family);
return new Promise((resolve, reject) => {
iface.socketRecv = dgram.createSocket({
type: (isIPV4 ? 'udp4' : 'udp6'),
reuseAddr: mDNS.config.reuseAddr
})
.on('error', (err) => {
if (iface.bindStatus.listening) {
mDNS.socketError(err);
} else {
iface.socketRecv.close();
resolve(false);
}
})
.on('listening', () => {
iface.bindStatus.listening = true;
iface.socketRecv.setMulticastTTL(mDNS.config.ttl);
iface.socketRecv.setMulticastLoopback(mDNS.config.loopback);
try {
iface.socketRecv.addMembership(
(isIPV4 ? MDNS_IPV4 : MDNS_IPV6),
iface.bindStatus.address + (isIPV4 ? '' : '%' + iface.name)
);
resolve(true);
} catch (e) {
iface.socketRecv.close();
iface.bindStatus.listening = false;
resolve(false);
}
})
.on('message', (msg, rinfo) => {
// include interface name so we know where the message came in
rinfo.interface = iface.name;
mDNS.socketOnMessage(msg, rinfo);
});
if (iface.bindStatus.catchAll) {
iface.bindStatus.address = isIPV4 ? '0.0.0.0' : '::';
} else {
iface.bindStatus.address = (isIPV4 ? MDNS_IPV4 : MDNS_IPV6);
}
iface.socketRecv.bind(MDNS_PORT, iface.bindStatus.address + (isIPV4 ? '' : '%' + iface.name));
});
},
createSendSocket: function (iface) {
const isIPV4 = familyIsIPV4(iface.family);
return new Promise((resolve, reject) => {
iface.socketSend = dgram.createSocket({
type: (isIPV4 ? 'udp4' : 'udp6'),
reuseAddr: mDNS.config.reuseAddr
})
.once('error', (err) => {
reject(new Error(err.message));
})
.on('error', mDNS.socketError)
.on('listening', () => {
iface.socketSend.setMulticastTTL(mDNS.config.ttl);
resolve();
})
.on('message', (msg, rinfo) => {
// include interface name so we know where the message came in
rinfo.interface = iface.name;
mDNS.socketOnMessage(msg, rinfo);
})
.bind(mDNS.config.srcPort, iface.address + (isIPV4 ? '' : '%' + iface.name));
});
},
// process socket error
socketError: function (err) {
if (err.code === 'EACCES' || err.code === 'EADDRINUSE' || err.code === 'EADDRNOTAVAIL') {
emitter.emit('error', err);
} else {
emitter.emit('warning', err);
}
},
// event handler for incoming mDNS packets
socketOnMessage: function (message, rinfo) {
try {
message = packet.decode(message);
} catch (err) {
emitter.emit('warning', err);
return;
}
emitter.emit('packet', message, rinfo);
switch (message.type) {
case 'query':
emitter.emit('query', message, rinfo);
break;
case 'response':
emitter.emit('response', message, rinfo);
break;
}
},
// count the number of interface sockets that are listening
countListeningSockets: function () {
var ic = 0;
mDNS.interfaces.forEach((iface) => {
ic += iface.listening ? 1 : 0;
});
return ic;
},
// discover all non-internal network interfaces
getInterfaces: function () {
var interfaces = [];
var names = [];
var osInterfaces = os.networkInterfaces();
Object.keys(osInterfaces).forEach(function (iface) {
if (names.includes(iface)) {
return;
}
names.push(iface);
osInterfaces[iface].forEach(function (assignment) {
if (
assignment.internal ||
(assignment.family !== 'IPv4' && assignment.family !== 4 && assignment.family !== 'IPv6' && assignment.family !== 6) ||
/^(2002|2001):/ig.exec(assignment.address)
) {
// unsupported family, internal interface, or special IPv6 prefix
return;
}
interfaces.push({ name: iface, address: assignment.address, family: assignment.family });
});
});
return interfaces;
},
// check to see if the provided interfaces is made up of strings
interfacesIsStrings: function (interfaces) {
return (
typeof mDNS.config.interfaces === 'string' ||
(
Array.isArray(mDNS.config.interfaces) &&
mDNS.config.interfaces.length &&
typeof mDNS.config.interfaces[0] === 'string'
)
);
},
// convert interfaces specified by address string or name string into os interface objects
interfacesFromStrings: function (strings) {
strings = Array.isArray(strings) ? strings : [strings];
var interfaces = [];
var osInterfaces = mDNS.getInterfaces();
var ii;
strings.forEach((str) => {
for (ii = 0; ii < osInterfaces.length; ii++) {
if (str.toUpperCase() === osInterfaces[ii].address.toUpperCase() || str === osInterfaces[ii].name) {
// include interface that was specified by address or name
interfaces.push(osInterfaces[ii]);
}
}
});
return interfaces;
},
// find the interfaces that match the provided rinfo
getInterfaceMatches: function (rinfo) {
var interfaces = [];
mDNS.interfaces.forEach((iface) => {
if (!rinfo.interface || (rinfo.interface === iface.name && rinfo.family === iface.family)) {
interfaces.push(iface);
}
});
return interfaces;
},
// no operation
noop: function () {},
// send an mDNS packet
send: function (value, rinfo, cb) {
if (typeof rinfo === 'function') {
return mDNS.send(value, null, rinfo);
}
if (!cb) {
cb = mDNS.noop;
}
if (mDNS.destroyed) {
return cb();
}
// determine which intefaces to use for send
var interfaces;
if (!rinfo) {
interfaces = mDNS.interfaces;
} else {
interfaces = mDNS.getInterfaceMatches(rinfo);
}
// send message on each interface
var message = packet.encode(value);
var processInterface = function (ii) {
if (ii >= interfaces.length || mDNS.destroyed) {
return cb();
} else if (interfaces[ii].socketSend) {
interfaces[ii].socketSend.send(
message,
0,
message.length,
MDNS_PORT,
(familyIsIPV4(interfaces[ii].family) ? MDNS_IPV4 : MDNS_IPV6 + '%' + interfaces[ii].name),
function () {
processInterface(ii + 1);
}
);
} else {
// interface did not have socket
processInterface(ii + 1);
}
};
processInterface(0);
},
// send an mDNS query
query: function (q, type, rinfo, cb) {
if (typeof type === 'function') {
return mDNS.query(q, null, null, type);
}
if (typeof type === 'object' && type && type.port) {
return mDNS.query(q, null, type, rinfo);
}
if (typeof rinfo === 'function') {
return mDNS.query(q, type, null, rinfo);
}
if (!cb) {
cb = mDNS.noop;
}
if (typeof q === 'string') {
q = [{name: q, type: type || 'ANY'}];
}
if (Array.isArray(q)) {
q = {type: 'query', questions: q};
}
q.type = 'query';
mDNS.send(q, rinfo, cb);
},
// send an mDNS response
respond: function (res, rinfo, cb) {
if (Array.isArray(res)) {
res = {answers: res};
}
res.type = 'response';
mDNS.send(res, rinfo, cb);
},
// destroy the multicast server
destroy: function (cb) {
if (!cb) {
cb = mDNS.noop;
}
if (mDNS.destroyed) {
return process.nextTick(cb);
}
mDNS.destroyed = true;
var processInterface = function (i) {
if (i >= mDNS.interfaces.length) {
emitter.emit('destroyed');
cb();
} else {
if (mDNS.interfaces[i].socketSend) {
mDNS.interfaces[i].socketSend.close();
}
if (mDNS.interfaces[i].socketRecv) {
mDNS.interfaces[i].socketRecv.close();
}
processInterface(i + 1);
}
};
processInterface(0);
}
};
if (!mDNS.config.noInit) {
mDNS.init();
}
// expose mDNS methods
emitter.initServer = mDNS.init;
emitter.query = mDNS.query;
emitter.respond = mDNS.respond;
emitter.destroy = mDNS.destroy;
emitter.getInterfaces = mDNS.getInterfaces;
emitter.errorMessages = mDNS.errorMessages;
return emitter;
};
module.exports.ErrorMessages = ErrorMessages;