git ssb

15+

ansuz / dnssb



Tree: 8b277e861c3c9b30cb3e985a8b7fd3bdad237398

Files: 8b277e861c3c9b30cb3e985a8b7fd3bdad237398 / lib / server.js

2177 bytesRaw
1var Pull = require("pull-stream");
2var Ansuz = require("ansuz");
3var SsbDns = require("./ssb-dns");
4
5var Server = module.exports = {};
6
7var log = {
8 req: function (req, opt) {
9 if (!(opt && opt.verbose)) { return; }
10 var q = req.question[0];
11 console.log();
12 console.log({
13 name: q.name,
14 type: q.type,
15 class: q.class,
16 });
17 },
18};
19
20var answer = function (sbot, req, res, opt) {
21 log.req(req, opt);
22
23 var q = req.question;
24
25 // TODO validate queries more carefully
26 if (!q.length) {
27 console.error("invalid question");
28 res.end();
29 return;
30 }
31
32 var qMap = {}
33 q.forEach(function (q) {
34 qMap[q.name.toLowerCase() + ':' + q.type] = true;
35 });
36
37 Pull(sbot.messagesByType({
38 type: 'ssb-dns',
39 }),
40 Pull.filter(function (msg) {
41 var c = msg.value.content;
42 var record = c && c.record;
43 return record && qMap[record.name + ':' + record.type];
44 }),
45 SsbDns(function (err, records) {
46 if (opt && opt.verbose) {
47 var names = q.map(function (q) { return q.name }).join(', ');
48 var types = records.map(function (r) { return r.type }).join(', ');
49 var vals = records.map(function (r) { return r.value }).join(', ');
50 console.log("%s (%s) => %s", names, types, vals);
51 }
52 res.answer = records;
53 res.end();
54 }));
55};
56
57var createServer = Server.create = function (sbot, port, host, cb, opt) {
58 var Dnsd = require("dnsd");
59 return Dnsd.createServer(function(req, res) {
60 answer(sbot, req, res, opt);
61 }).listen(port, host, cb);
62};
63
64Server.listen = function (port, host, cb, opt) {
65 var Client = require("ssb-client");
66 Client(function (err, sbot) {
67 if (err) {
68 console.error(err);
69 return void process.exit(1);
70 }
71 var server = createServer(sbot, port, host, cb, opt);
72
73 var close = function () {
74 console.error("Server connection lost. Shutting down");
75 sbot.close();
76 server.close();
77 };
78
79 sbot.on('closed', close);
80 });
81};
82
83

Built with git-ssb-web