Files: aa8bdc9d1c7570e788c3416709fa6ef788024cec / lib / server.js
2177 bytesRaw
1 | var Pull = require("pull-stream"); |
2 | var Ansuz = require("ansuz"); |
3 | var SsbDns = require("./ssb-dns"); |
4 | |
5 | var Server = module.exports = {}; |
6 | |
7 | var 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 | |
20 | var 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 | |
57 | var 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 | |
64 | Server.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