2017-12-15 03:26:28 +00:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
module.exports.create = function (cli, dnsd) {
|
2017-12-15 04:20:16 +00:00
|
|
|
function runUdp() {
|
|
|
|
var server = require('dgram').createSocket({
|
|
|
|
type: cli.udp6 ? 'udp6' : 'udp4'
|
|
|
|
, reuseAddr: true
|
|
|
|
});
|
|
|
|
server.bind({
|
|
|
|
port: cli.port
|
|
|
|
, address: cli.address
|
2017-12-15 03:26:28 +00:00
|
|
|
});
|
|
|
|
|
2017-12-15 04:20:16 +00:00
|
|
|
var handlers = {};
|
|
|
|
handlers.onError = function (err) {
|
|
|
|
if ('EACCES' === err.code) {
|
|
|
|
console.error("");
|
|
|
|
console.error("EACCES: Couldn't bind to port. You probably need to use sudo, authbind, or setcap.");
|
|
|
|
console.error("");
|
|
|
|
process.exit(123);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
console.error("UDP Server Error:");
|
|
|
|
console.error(err.stack);
|
|
|
|
server.close(function () {
|
|
|
|
setTimeout(runUdp, 1000);
|
|
|
|
});
|
|
|
|
//throw new Error(err);
|
|
|
|
};
|
|
|
|
|
|
|
|
handlers.onMessage = function (nb, rinfo) {
|
|
|
|
//console.log('[DEBUG] got a UDP message', nb.length);
|
|
|
|
//console.log(nb.toString('hex'));
|
|
|
|
|
|
|
|
dnsd.onMessage(nb, function (err, newAb, dbgmsg) {
|
|
|
|
// TODO send legit error message
|
|
|
|
if (err) { server.send(Buffer.from([0x00]), rinfo.port, rinfo.address); return; }
|
|
|
|
server.send(newAb, rinfo.port, rinfo.address, function () {
|
|
|
|
console.log('[dnsd.onMessage] ' + dbgmsg, rinfo.port, rinfo.address);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
handlers.onListening = function () {
|
|
|
|
/*jshint validthis:true*/
|
|
|
|
var server = this;
|
|
|
|
|
|
|
|
if (cli.mdns || '224.0.0.251' === cli.nameserver) {
|
|
|
|
server.setBroadcast(true);
|
|
|
|
server.addMembership(cli.nameserver);
|
|
|
|
}
|
2017-12-15 03:26:28 +00:00
|
|
|
|
2017-12-15 04:20:16 +00:00
|
|
|
console.log('');
|
|
|
|
console.log('Bound and Listening:');
|
|
|
|
console.log(server.address().address + '#' + server.address().port + ' (' + server.type + ')');
|
|
|
|
};
|
2017-12-15 03:26:28 +00:00
|
|
|
|
2017-12-15 04:20:16 +00:00
|
|
|
server.on('error', handlers.onError);
|
|
|
|
server.on('message', handlers.onMessage);
|
|
|
|
server.on('listening', handlers.onListening);
|
2017-12-15 03:26:28 +00:00
|
|
|
|
2017-12-15 04:20:16 +00:00
|
|
|
return server;
|
|
|
|
}
|
2017-12-15 03:26:28 +00:00
|
|
|
|
2017-12-15 04:20:16 +00:00
|
|
|
return runUdp();
|
2017-12-15 03:26:28 +00:00
|
|
|
};
|