]> git.ipfire.org Git - thirdparty/pdns.git/blob - pdns/dnsdist-web.cc
00c6e36b1d610f35c48cbe160977c24a83c522f9
[thirdparty/pdns.git] / pdns / dnsdist-web.cc
1 /*
2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of version 2 of the GNU General Public License as
7 * published by the Free Software Foundation.
8 *
9 * In addition, for the avoidance of any doubt, permission is granted to
10 * link this program with OpenSSL and to (re)distribute the binaries
11 * produced as the result of such linking.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
22 #include "dnsdist.hh"
23 #include "sstuff.hh"
24 #include "ext/json11/json11.hpp"
25 #include "ext/incbin/incbin.h"
26 #include "dolog.hh"
27 #include <thread>
28 #include "threadname.hh"
29 #include <sstream>
30 #include <yahttp/yahttp.hpp>
31 #include "namespaces.hh"
32 #include <sys/time.h>
33 #include <sys/resource.h>
34 #include "ext/incbin/incbin.h"
35 #include "htmlfiles.h"
36 #include "base64.hh"
37 #include "gettime.hh"
38 #include <boost/format.hpp>
39
40 bool g_apiReadWrite{false};
41 WebserverConfig g_webserverConfig;
42 std::string g_apiConfigDirectory;
43
44 static bool apiWriteConfigFile(const string& filebasename, const string& content)
45 {
46 if (!g_apiReadWrite) {
47 errlog("Not writing content to %s since the API is read-only", filebasename);
48 return false;
49 }
50
51 if (g_apiConfigDirectory.empty()) {
52 vinfolog("Not writing content to %s since the API configuration directory is not set", filebasename);
53 return false;
54 }
55
56 string filename = g_apiConfigDirectory + "/" + filebasename + ".conf";
57 ofstream ofconf(filename.c_str());
58 if (!ofconf) {
59 errlog("Could not open configuration fragment file '%s' for writing: %s", filename, stringerror());
60 return false;
61 }
62 ofconf << "-- Generated by the REST API, DO NOT EDIT" << endl;
63 ofconf << content << endl;
64 ofconf.close();
65 return true;
66 }
67
68 static void apiSaveACL(const NetmaskGroup& nmg)
69 {
70 vector<string> vec;
71 nmg.toStringVector(&vec);
72
73 string acl;
74 for(const auto& s : vec) {
75 if (!acl.empty()) {
76 acl += ", ";
77 }
78 acl += "\"" + s + "\"";
79 }
80
81 string content = "setACL({" + acl + "})";
82 apiWriteConfigFile("acl", content);
83 }
84
85 static bool checkAPIKey(const YaHTTP::Request& req, const string& expectedApiKey)
86 {
87 if (expectedApiKey.empty()) {
88 return false;
89 }
90
91 const auto header = req.headers.find("x-api-key");
92 if (header != req.headers.end()) {
93 return (header->second == expectedApiKey);
94 }
95
96 return false;
97 }
98
99 static bool checkWebPassword(const YaHTTP::Request& req, const string &expected_password)
100 {
101 static const char basicStr[] = "basic ";
102
103 const auto header = req.headers.find("authorization");
104
105 if (header != req.headers.end() && toLower(header->second).find(basicStr) == 0) {
106 string cookie = header->second.substr(sizeof(basicStr) - 1);
107
108 string plain;
109 B64Decode(cookie, plain);
110
111 vector<string> cparts;
112 stringtok(cparts, plain, ":");
113
114 if (cparts.size() == 2) {
115 return cparts[1] == expected_password;
116 }
117 }
118
119 return false;
120 }
121
122 static bool isAnAPIRequest(const YaHTTP::Request& req)
123 {
124 return req.url.path.find("/api/") == 0;
125 }
126
127 static bool isAnAPIRequestAllowedWithWebAuth(const YaHTTP::Request& req)
128 {
129 return req.url.path == "/api/v1/servers/localhost";
130 }
131
132 static bool isAStatsRequest(const YaHTTP::Request& req)
133 {
134 return req.url.path == "/jsonstat" || req.url.path == "/metrics";
135 }
136
137 static bool compareAuthorization(const YaHTTP::Request& req)
138 {
139 std::lock_guard<std::mutex> lock(g_webserverConfig.lock);
140
141 if (isAnAPIRequest(req)) {
142 /* Access to the API requires a valid API key */
143 if (checkAPIKey(req, g_webserverConfig.apiKey)) {
144 return true;
145 }
146
147 return isAnAPIRequestAllowedWithWebAuth(req) && checkWebPassword(req, g_webserverConfig.password);
148 }
149
150 if (isAStatsRequest(req)) {
151 /* Access to the stats is allowed for both API and Web users */
152 return checkAPIKey(req, g_webserverConfig.apiKey) || checkWebPassword(req, g_webserverConfig.password);
153 }
154
155 return checkWebPassword(req, g_webserverConfig.password);
156 }
157
158 static bool isMethodAllowed(const YaHTTP::Request& req)
159 {
160 if (req.method == "GET") {
161 return true;
162 }
163 if (req.method == "PUT" && g_apiReadWrite) {
164 if (req.url.path == "/api/v1/servers/localhost/config/allow-from") {
165 return true;
166 }
167 }
168 return false;
169 }
170
171 static void handleCORS(const YaHTTP::Request& req, YaHTTP::Response& resp)
172 {
173 const auto origin = req.headers.find("Origin");
174 if (origin != req.headers.end()) {
175 if (req.method == "OPTIONS") {
176 /* Pre-flight request */
177 if (g_apiReadWrite) {
178 resp.headers["Access-Control-Allow-Methods"] = "GET, PUT";
179 }
180 else {
181 resp.headers["Access-Control-Allow-Methods"] = "GET";
182 }
183 resp.headers["Access-Control-Allow-Headers"] = "Authorization, X-API-Key";
184 }
185
186 resp.headers["Access-Control-Allow-Origin"] = origin->second;
187
188 if (isAStatsRequest(req) || isAnAPIRequestAllowedWithWebAuth(req)) {
189 resp.headers["Access-Control-Allow-Credentials"] = "true";
190 }
191 }
192 }
193
194 static void addSecurityHeaders(YaHTTP::Response& resp, const boost::optional<std::map<std::string, std::string> >& customHeaders)
195 {
196 static const std::vector<std::pair<std::string, std::string> > headers = {
197 { "X-Content-Type-Options", "nosniff" },
198 { "X-Frame-Options", "deny" },
199 { "X-Permitted-Cross-Domain-Policies", "none" },
200 { "X-XSS-Protection", "1; mode=block" },
201 { "Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'" },
202 };
203
204 for (const auto& h : headers) {
205 if (customHeaders) {
206 const auto& custom = customHeaders->find(h.first);
207 if (custom != customHeaders->end()) {
208 continue;
209 }
210 }
211 resp.headers[h.first] = h.second;
212 }
213 }
214
215 static void addCustomHeaders(YaHTTP::Response& resp, const boost::optional<std::map<std::string, std::string> >& customHeaders)
216 {
217 if (!customHeaders)
218 return;
219
220 for (const auto& c : *customHeaders) {
221 if (!c.second.empty()) {
222 resp.headers[c.first] = c.second;
223 }
224 }
225 }
226
227 template<typename T>
228 static json11::Json::array someResponseRulesToJson(GlobalStateHolder<vector<T>>* someResponseRules)
229 {
230 using namespace json11;
231 Json::array responseRules;
232 int num=0;
233 auto localResponseRules = someResponseRules->getLocal();
234 for(const auto& a : *localResponseRules) {
235 Json::object rule{
236 {"id", num++},
237 {"creationOrder", (double)a.d_creationOrder},
238 {"uuid", boost::uuids::to_string(a.d_id)},
239 {"matches", (double)a.d_rule->d_matches},
240 {"rule", a.d_rule->toString()},
241 {"action", a.d_action->toString()},
242 };
243 responseRules.push_back(rule);
244 }
245 return responseRules;
246 }
247
248 static void connectionThread(int sock, ComboAddress remote)
249 {
250 setThreadName("dnsdist/webConn");
251
252 using namespace json11;
253 vinfolog("Webserver handling connection from %s", remote.toStringWithPort());
254
255 try {
256 YaHTTP::AsyncRequestLoader yarl;
257 YaHTTP::Request req;
258 bool finished = false;
259
260 yarl.initialize(&req);
261 while(!finished) {
262 int bytes;
263 char buf[1024];
264 bytes = read(sock, buf, sizeof(buf));
265 if (bytes > 0) {
266 string data = string(buf, bytes);
267 finished = yarl.feed(data);
268 } else {
269 // read error OR EOF
270 break;
271 }
272 }
273 yarl.finalize();
274
275 string command=req.getvars["command"];
276
277 req.getvars.erase("_"); // jQuery cache buster
278
279 YaHTTP::Response resp;
280 resp.version = req.version;
281 const string charset = "; charset=utf-8";
282
283 {
284 std::lock_guard<std::mutex> lock(g_webserverConfig.lock);
285
286 addCustomHeaders(resp, g_webserverConfig.customHeaders);
287 addSecurityHeaders(resp, g_webserverConfig.customHeaders);
288 }
289 /* indicate that the connection will be closed after completion of the response */
290 resp.headers["Connection"] = "close";
291
292 /* no need to send back the API key if any */
293 resp.headers.erase("X-API-Key");
294
295 if(req.method == "OPTIONS") {
296 /* the OPTIONS method should not require auth, otherwise it breaks CORS */
297 handleCORS(req, resp);
298 resp.status=200;
299 }
300 else if (!compareAuthorization(req)) {
301 YaHTTP::strstr_map_t::iterator header = req.headers.find("authorization");
302 if (header != req.headers.end())
303 errlog("HTTP Request \"%s\" from %s: Web Authentication failed", req.url.path, remote.toStringWithPort());
304 resp.status=401;
305 resp.body="<h1>Unauthorized</h1>";
306 resp.headers["WWW-Authenticate"] = "basic realm=\"PowerDNS\"";
307
308 }
309 else if(!isMethodAllowed(req)) {
310 resp.status=405;
311 }
312 else if(req.url.path=="/jsonstat") {
313 handleCORS(req, resp);
314 resp.status=200;
315
316 if(command=="stats") {
317 auto obj=Json::object {
318 { "packetcache-hits", 0},
319 { "packetcache-misses", 0},
320 { "over-capacity-drops", 0 },
321 { "too-old-drops", 0 },
322 { "server-policy", g_policy.getLocal()->name}
323 };
324
325 for(const auto& e : g_stats.entries) {
326 if (e.first == "special-memory-usage")
327 continue; // Too expensive for get-all
328 if(const auto& val = boost::get<DNSDistStats::stat_t*>(&e.second))
329 obj.insert({e.first, (double)(*val)->load()});
330 else if (const auto& dval = boost::get<double*>(&e.second))
331 obj.insert({e.first, (**dval)});
332 else
333 obj.insert({e.first, (double)(*boost::get<DNSDistStats::statfunction_t>(&e.second))(e.first)});
334 }
335 Json my_json = obj;
336 resp.body=my_json.dump();
337 resp.headers["Content-Type"] = "application/json";
338 }
339 else if(command=="dynblocklist") {
340 Json::object obj;
341 auto nmg = g_dynblockNMG.getLocal();
342 struct timespec now;
343 gettime(&now);
344 for(const auto& e: *nmg) {
345 if(now < e->second.until ) {
346 Json::object thing{
347 {"reason", e->second.reason},
348 {"seconds", (double)(e->second.until.tv_sec - now.tv_sec)},
349 {"blocks", (double)e->second.blocks},
350 {"action", DNSAction::typeToString(e->second.action != DNSAction::Action::None ? e->second.action : g_dynBlockAction) },
351 {"warning", e->second.warning }
352 };
353 obj.insert({e->first.toString(), thing});
354 }
355 }
356
357 auto smt = g_dynblockSMT.getLocal();
358 smt->visit([&now,&obj](const SuffixMatchTree<DynBlock>& node) {
359 if(now <node.d_value.until) {
360 string dom("empty");
361 if(!node.d_value.domain.empty())
362 dom = node.d_value.domain.toString();
363 Json::object thing{
364 {"reason", node.d_value.reason},
365 {"seconds", (double)(node.d_value.until.tv_sec - now.tv_sec)},
366 {"blocks", (double)node.d_value.blocks},
367 {"action", DNSAction::typeToString(node.d_value.action != DNSAction::Action::None ? node.d_value.action : g_dynBlockAction) }
368 };
369 obj.insert({dom, thing});
370 }
371 });
372
373
374
375 Json my_json = obj;
376 resp.body=my_json.dump();
377 resp.headers["Content-Type"] = "application/json";
378 }
379 else if(command=="ebpfblocklist") {
380 Json::object obj;
381 #ifdef HAVE_EBPF
382 struct timespec now;
383 gettime(&now);
384 for (const auto& dynbpf : g_dynBPFFilters) {
385 std::vector<std::tuple<ComboAddress, uint64_t, struct timespec> > addrStats = dynbpf->getAddrStats();
386 for (const auto& entry : addrStats) {
387 Json::object thing
388 {
389 {"seconds", (double)(std::get<2>(entry).tv_sec - now.tv_sec)},
390 {"blocks", (double)(std::get<1>(entry))}
391 };
392 obj.insert({std::get<0>(entry).toString(), thing });
393 }
394 }
395 #endif /* HAVE_EBPF */
396 Json my_json = obj;
397 resp.body=my_json.dump();
398 resp.headers["Content-Type"] = "application/json";
399 }
400 else {
401 resp.status=404;
402 }
403 }
404 else if (req.url.path == "/metrics") {
405 handleCORS(req, resp);
406 resp.status = 200;
407
408 std::ostringstream output;
409 for (const auto& e : g_stats.entries) {
410 if (e.first == "special-memory-usage")
411 continue; // Too expensive for get-all
412 std::string metricName = std::get<0>(e);
413
414 // Prometheus suggest using '_' instead of '-'
415 std::string prometheusMetricName = "dnsdist_" + boost::replace_all_copy(metricName, "-", "_");
416
417 MetricDefinition metricDetails;
418
419 if (!g_metricDefinitions.getMetricDetails(metricName, metricDetails)) {
420 vinfolog("Do not have metric details for %s", metricName);
421 continue;
422 }
423
424 std::string prometheusTypeName = g_metricDefinitions.getPrometheusStringMetricType(metricDetails.prometheusType);
425
426 if (prometheusTypeName == "") {
427 vinfolog("Unknown Prometheus type for %s", metricName);
428 continue;
429 }
430
431 // for these we have the help and types encoded in the sources:
432 output << "# HELP " << prometheusMetricName << " " << metricDetails.description << "\n";
433 output << "# TYPE " << prometheusMetricName << " " << prometheusTypeName << "\n";
434 output << prometheusMetricName << " ";
435
436 if (const auto& val = boost::get<DNSDistStats::stat_t*>(&std::get<1>(e)))
437 output << (*val)->load();
438 else if (const auto& dval = boost::get<double*>(&std::get<1>(e)))
439 output << **dval;
440 else
441 output << (*boost::get<DNSDistStats::statfunction_t>(&std::get<1>(e)))(std::get<0>(e));
442
443 output << "\n";
444 }
445
446 // Latency histogram buckets
447 output << "# HELP dnsdist_latency Histogram of responses by latency\n";
448 output << "# TYPE dnsdist_latency histogram\n";
449 uint64_t latency_amounts = g_stats.latency0_1;
450 output << "dnsdist_latency_bucket{le=\"1\"} " << latency_amounts << "\n";
451 latency_amounts += g_stats.latency1_10;
452 output << "dnsdist_latency_bucket{le=\"10\"} " << latency_amounts << "\n";
453 latency_amounts += g_stats.latency10_50;
454 output << "dnsdist_latency_bucket{le=\"50\"} " << latency_amounts << "\n";
455 latency_amounts += g_stats.latency50_100;
456 output << "dnsdist_latency_bucket{le=\"100\"} " << latency_amounts << "\n";
457 latency_amounts += g_stats.latency100_1000;
458 output << "dnsdist_latency_bucket{le=\"1000\"} " << latency_amounts << "\n";
459 latency_amounts += g_stats.latencySlow; // Should be the same as latency_count
460 output << "dnsdist_latency_bucket{le=\"+Inf\"} " << latency_amounts << "\n";
461
462 auto states = g_dstates.getLocal();
463 const string statesbase = "dnsdist_server_";
464
465 output << "# HELP " << statesbase << "queries " << "Amount of queries relayed to server" << "\n";
466 output << "# TYPE " << statesbase << "queries " << "counter" << "\n";
467 output << "# HELP " << statesbase << "drops " << "Amount of queries not answered by server" << "\n";
468 output << "# TYPE " << statesbase << "drops " << "counter" << "\n";
469 output << "# HELP " << statesbase << "latency " << "Server's latency when answering questions in milliseconds" << "\n";
470 output << "# TYPE " << statesbase << "latency " << "gauge" << "\n";
471 output << "# HELP " << statesbase << "senderrors " << "Total number of OS snd errors while relaying queries" << "\n";
472 output << "# TYPE " << statesbase << "senderrors " << "counter" << "\n";
473 output << "# HELP " << statesbase << "outstanding " << "Current number of queries that are waiting for a backend response" << "\n";
474 output << "# TYPE " << statesbase << "outstanding " << "gauge" << "\n";
475 output << "# HELP " << statesbase << "order " << "The order in which this server is picked" << "\n";
476 output << "# TYPE " << statesbase << "order " << "gauge" << "\n";
477 output << "# HELP " << statesbase << "weight " << "The weight within the order in which this server is picked" << "\n";
478 output << "# TYPE " << statesbase << "weight " << "gauge" << "\n";
479 output << "# HELP " << statesbase << "tcpdiedsendingquery " << "The number of TCP I/O errors while sending the query" << "\n";
480 output << "# TYPE " << statesbase << "tcpdiedsendingquery " << "counter" << "\n";
481 output << "# HELP " << statesbase << "tcpdiedreadingresponse " << "The number of TCP I/O errors while reading the response" << "\n";
482 output << "# TYPE " << statesbase << "tcpdiedreadingresponse " << "counter" << "\n";
483 output << "# HELP " << statesbase << "tcpgaveup " << "The number of TCP connections failing after too many attempts" << "\n";
484 output << "# TYPE " << statesbase << "tcpgaveup " << "counter" << "\n";
485 output << "# HELP " << statesbase << "tcpreadtimeouts " << "The number of TCP read timeouts" << "\n";
486 output << "# TYPE " << statesbase << "tcpreadtimeouts " << "counter" << "\n";
487 output << "# HELP " << statesbase << "tcpwritetimeouts " << "The number of TCP write timeouts" << "\n";
488 output << "# TYPE " << statesbase << "tcpwritetimeouts " << "counter" << "\n";
489 output << "# HELP " << statesbase << "tcpcurrentconnections " << "The number of current TCP connections" << "\n";
490 output << "# TYPE " << statesbase << "tcpcurrentconnections " << "gauge" << "\n";
491 output << "# HELP " << statesbase << "tcpavgqueriesperconn " << "The average number of queries per TCP connection" << "\n";
492 output << "# TYPE " << statesbase << "tcpavgqueriesperconn " << "gauge" << "\n";
493 output << "# HELP " << statesbase << "tcpavgconnduration " << "The average duration of a TCP connection (ms)" << "\n";
494 output << "# TYPE " << statesbase << "tcpavgconnduration " << "gauge" << "\n";
495
496 for (const auto& state : *states) {
497 string serverName;
498
499 if (state->name.empty())
500 serverName = state->remote.toStringWithPort();
501 else
502 serverName = state->getName();
503
504 boost::replace_all(serverName, ".", "_");
505
506 const std::string label = boost::str(boost::format("{server=\"%1%\",address=\"%2%\"}")
507 % serverName % state->remote.toStringWithPort());
508
509 output << statesbase << "queries" << label << " " << state->queries.load() << "\n";
510 output << statesbase << "drops" << label << " " << state->reuseds.load() << "\n";
511 output << statesbase << "latency" << label << " " << state->latencyUsec/1000.0 << "\n";
512 output << statesbase << "senderrors" << label << " " << state->sendErrors.load() << "\n";
513 output << statesbase << "outstanding" << label << " " << state->outstanding.load() << "\n";
514 output << statesbase << "order" << label << " " << state->order << "\n";
515 output << statesbase << "weight" << label << " " << state->weight << "\n";
516 output << statesbase << "tcpdiedsendingquery" << label << " " << state->tcpDiedSendingQuery << "\n";
517 output << statesbase << "tcpdiedreadingresponse" << label << " " << state->tcpDiedReadingResponse << "\n";
518 output << statesbase << "tcpgaveup" << label << " " << state->tcpGaveUp << "\n";
519 output << statesbase << "tcpreadtimeouts" << label << " " << state->tcpReadTimeouts << "\n";
520 output << statesbase << "tcpwritetimeouts" << label << " " << state->tcpWriteTimeouts << "\n";
521 output << statesbase << "tcpcurrentconnections" << label << " " << state->tcpCurrentConnections << "\n";
522 output << statesbase << "tcpavgqueriesperconn" << label << " " << state->tcpAvgQueriesPerConnection << "\n";
523 output << statesbase << "tcpavgconnduration" << label << " " << state->tcpAvgConnectionDuration << "\n";
524 }
525
526 const string frontsbase = "dnsdist_frontend_";
527 output << "# HELP " << frontsbase << "queries " << "Amount of queries received by this frontend" << "\n";
528 output << "# TYPE " << frontsbase << "queries " << "counter" << "\n";
529 output << "# HELP " << frontsbase << "tcpdiedreadingquery " << "Amount of TCP connections terminated while reading the query from the client" << "\n";
530 output << "# TYPE " << frontsbase << "tcpdiedreadingquery " << "counter" << "\n";
531 output << "# HELP " << frontsbase << "tcpdiedsendingresponse " << "Amount of TCP connections terminated while sending a response to the client" << "\n";
532 output << "# TYPE " << frontsbase << "tcpdiedsendingresponse " << "counter" << "\n";
533 output << "# HELP " << frontsbase << "tcpgaveup " << "Amount of TCP connections terminated after too many attemps to get a connection to the backend" << "\n";
534 output << "# TYPE " << frontsbase << "tcpgaveup " << "counter" << "\n";
535 output << "# HELP " << frontsbase << "tcpclientimeouts " << "Amount of TCP connections terminated by a timeout while reading from the client" << "\n";
536 output << "# TYPE " << frontsbase << "tcpclientimeouts " << "counter" << "\n";
537 output << "# HELP " << frontsbase << "tcpdownstreamimeouts " << "Amount of TCP connections terminated by a timeout while reading from the backend" << "\n";
538 output << "# TYPE " << frontsbase << "tcpdownstreamimeouts " << "counter" << "\n";
539 output << "# HELP " << frontsbase << "tcpcurrentconnections " << "Amount of current incoming TCP connections from clients" << "\n";
540 output << "# TYPE " << frontsbase << "tcpcurrentconnections " << "gauge" << "\n";
541 output << "# HELP " << frontsbase << "tcpavgqueriesperconnection " << "The average number of queries per TCP connection" << "\n";
542 output << "# TYPE " << frontsbase << "tcpavgqueriesperconnection " << "gauge" << "\n";
543 output << "# HELP " << frontsbase << "tcpavgconnectionduration " << "The average duration of a TCP connection (ms)" << "\n";
544 output << "# TYPE " << frontsbase << "tcpavgconnectionduration " << "gauge" << "\n";
545
546 std::map<std::string,uint64_t> frontendDuplicates;
547 for (const auto& front : g_frontends) {
548 if (front->udpFD == -1 && front->tcpFD == -1)
549 continue;
550
551 string frontName = front->local.toString() + ":" + std::to_string(front->local.getPort());
552 const string proto = front->getType();
553 string fullName = frontName + "_" + proto;
554 auto dupPair = frontendDuplicates.insert({fullName, 1});
555 if (!dupPair.second) {
556 frontName = frontName + "_" + std::to_string(dupPair.first->second);
557 ++(dupPair.first->second);
558 }
559 const std::string label = boost::str(boost::format("{frontend=\"%1%\",proto=\"%2%\"} ")
560 % frontName % proto);
561
562 output << frontsbase << "queries" << label << front->queries.load() << "\n";
563 output << frontsbase << "tcpdiedreadingquery" << label << front->tcpDiedReadingQuery.load() << "\n";
564 output << frontsbase << "tcpdiedsendingresponse" << label << front->tcpDiedSendingResponse.load() << "\n";
565 output << frontsbase << "tcpgaveup" << label << front->tcpGaveUp.load() << "\n";
566 output << frontsbase << "tcpclientimeouts" << label << front->tcpClientTimeouts.load() << "\n";
567 output << frontsbase << "tcpdownstreamtimeouts" << label << front->tcpDownstreamTimeouts.load() << "\n";
568 output << frontsbase << "tcpcurrentconnections" << label << front->tcpCurrentConnections.load() << "\n";
569 output << frontsbase << "tcpavgqueriesperconnection" << label << front->tcpAvgQueriesPerConnection.load() << "\n";
570 output << frontsbase << "tcpavgconnectionduration" << label << front->tcpAvgConnectionDuration.load() << "\n";
571 }
572
573 const string dohfrontsbase = "dnsdist_doh_frontend_";
574 output << "# HELP " << dohfrontsbase << "http_connects " << "Number of TCP connections establoshed to this frontend" << "\n";
575 output << "# TYPE " << dohfrontsbase << "queries " << "counter" << "\n";
576 output << "# HELP " << dohfrontsbase << "tls10_queries " << "Number of valid DNS queries received via TLS 1.0" << "\n";
577 output << "# TYPE " << dohfrontsbase << "tls10_queries " << "counter" << "\n";
578 output << "# HELP " << dohfrontsbase << "tls11_queries " << "Number of valid DNS queries received via TLS 1.1" << "\n";
579 output << "# TYPE " << dohfrontsbase << "tls11_queries " << "counter" << "\n";
580 output << "# HELP " << dohfrontsbase << "tls12_queries " << "Number of valid DNS queries received via TLS 1.2" << "\n";
581 output << "# TYPE " << dohfrontsbase << "tls12_queries " << "counter" << "\n";
582 output << "# HELP " << dohfrontsbase << "tls13_queries " << "Number of valid DNS queries received via TLS 1.3" << "\n";
583 output << "# TYPE " << dohfrontsbase << "tls13_queries " << "counter" << "\n";
584 output << "# HELP " << dohfrontsbase << "tlsunknown_queries " << "Number of valid DNS queries received via an unknown TLS version" << "\n";
585 output << "# TYPE " << dohfrontsbase << "tlsunknown_queries " << "counter" << "\n";
586 output << "# HELP " << dohfrontsbase << "get_queries " << "Number of valid DNS queries received via GET" << "\n";
587 output << "# TYPE " << dohfrontsbase << "get_queries " << "counter" << "\n";
588 output << "# HELP " << dohfrontsbase << "post_queries " << "Number of valid DNS queries received via POST" << "\n";
589 output << "# TYPE " << dohfrontsbase << "post_queries " << "counter" << "\n";
590 output << "# HELP " << dohfrontsbase << "bad_requests " << "Number of requests that could not be converted to a DNS query" << "\n";
591 output << "# TYPE " << dohfrontsbase << "bad_requests " << "counter" << "\n";
592 output << "# HELP " << dohfrontsbase << "error_responses " << "Number of responses sent by dnsdist indicating an error" << "\n";
593 output << "# TYPE " << dohfrontsbase << "error_responses " << "counter" << "\n";
594 output << "# HELP " << dohfrontsbase << "valid_responses " << "Number of valid responses sent by dnsdist" << "\n";
595 output << "# TYPE " << dohfrontsbase << "valid_responses " << "counter" << "\n";
596 output << "# HELP " << dohfrontsbase << "http1_queries " << "Number of queries received over HTTP/1.x" << "\n";
597 output << "# TYPE " << dohfrontsbase << "http1_queries " << "counter" << "\n";
598 output << "# HELP " << dohfrontsbase << "http1_nb200responses " << "Number of responses with a 200 status code sent over HTTP/1.x" << "\n";
599 output << "# TYPE " << dohfrontsbase << "http1_nb200responses " << "counter" << "\n";
600 output << "# HELP " << dohfrontsbase << "http1_nb400responses " << "Number of responses with a 400 status code sent over HTTP/1.x" << "\n";
601 output << "# TYPE " << dohfrontsbase << "http1_nb400responses " << "counter" << "\n";
602 output << "# HELP " << dohfrontsbase << "http1_nb403responses " << "Number of responses with a 403 status code sent over HTTP/1.x" << "\n";
603 output << "# TYPE " << dohfrontsbase << "http1_nb403responses " << "counter" << "\n";
604 output << "# HELP " << dohfrontsbase << "http1_nb500responses " << "Number of responses with a 500 status code sent over HTTP/1.x" << "\n";
605 output << "# TYPE " << dohfrontsbase << "http1_nb500responses " << "counter" << "\n";
606 output << "# HELP " << dohfrontsbase << "http1_nb502responses " << "Number of responses with a 502 status code sent over HTTP/1.x" << "\n";
607 output << "# TYPE " << dohfrontsbase << "http1_nb502responses " << "counter" << "\n";
608 output << "# HELP " << dohfrontsbase << "http1_nbotherresponses " << "Number of responses with an other status code sent over HTTP/1.x" << "\n";
609 output << "# TYPE " << dohfrontsbase << "http1_nbotherresponses " << "counter" << "\n";
610 output << "# HELP " << dohfrontsbase << "http2_queries " << "Number of queries received over HTTP/2.x" << "\n";
611 output << "# TYPE " << dohfrontsbase << "http2_queries " << "counter" << "\n";
612 output << "# HELP " << dohfrontsbase << "http2_nb200responses " << "Number of responses with a 200 status code sent over HTTP/2.x" << "\n";
613 output << "# TYPE " << dohfrontsbase << "http2_nb200responses " << "counter" << "\n";
614 output << "# HELP " << dohfrontsbase << "http2_nb400responses " << "Number of responses with a 400 status code sent over HTTP/2.x" << "\n";
615 output << "# TYPE " << dohfrontsbase << "http2_nb400responses " << "counter" << "\n";
616 output << "# HELP " << dohfrontsbase << "http2_nb403responses " << "Number of responses with a 403 status code sent over HTTP/2.x" << "\n";
617 output << "# TYPE " << dohfrontsbase << "http2_nb403responses " << "counter" << "\n";
618 output << "# HELP " << dohfrontsbase << "http2_nb500responses " << "Number of responses with a 500 status code sent over HTTP/2.x" << "\n";
619 output << "# TYPE " << dohfrontsbase << "http2_nb500responses " << "counter" << "\n";
620 output << "# HELP " << dohfrontsbase << "http2_nb502responses " << "Number of responses with a 502 status code sent over HTTP/2.x" << "\n";
621 output << "# TYPE " << dohfrontsbase << "http2_nb502responses " << "counter" << "\n";
622 output << "# HELP " << dohfrontsbase << "http2_nbotherresponses " << "Number of responses with an other status code sent over HTTP/2.x" << "\n";
623 output << "# TYPE " << dohfrontsbase << "http2_nbotherresponses " << "counter" << "\n";
624
625 #ifdef HAVE_DNS_OVER_HTTPS
626 for(const auto& doh : g_dohlocals) {
627 const std::string label = boost::str(boost::format("{address=\"%1%\"} ") % doh->d_local.toStringWithPort());
628
629 output << dohfrontsbase << "http_connects" << label << doh->d_httpconnects << "\n";
630 output << dohfrontsbase << "tls10_queries" << label << doh->d_tls10queries << "\n";
631 output << dohfrontsbase << "tls11_queries" << label << doh->d_tls11queries << "\n";
632 output << dohfrontsbase << "tls12_queries" << label << doh->d_tls12queries << "\n";
633 output << dohfrontsbase << "tls13_queries" << label << doh->d_tls13queries << "\n";
634 output << dohfrontsbase << "tlsunknown_queries" << label << doh->d_tlsUnknownqueries << "\n";
635 output << dohfrontsbase << "get_queries" << label << doh->d_getqueries << "\n";
636 output << dohfrontsbase << "post_queries" << label << doh->d_postqueries << "\n";
637 output << dohfrontsbase << "bad_requests" << label << doh->d_badrequests << "\n";
638 output << dohfrontsbase << "error_responses" << label << doh->d_errorresponses << "\n";
639 output << dohfrontsbase << "valid_responses" << label << doh->d_validresponses << "\n";
640
641 output << dohfrontsbase << "http1_queries" << label << doh->d_http1Stats.d_nbQueries << "\n";
642 output << dohfrontsbase << "http1_nb200responses" << label << doh->d_http1Stats.d_nb200Responses << "\n";
643 output << dohfrontsbase << "http1_nb400responses" << label << doh->d_http1Stats.d_nb400Responses << "\n";
644 output << dohfrontsbase << "http1_nb403responses" << label << doh->d_http1Stats.d_nb403Responses << "\n";
645 output << dohfrontsbase << "http1_nb500responses" << label << doh->d_http1Stats.d_nb500Responses << "\n";
646 output << dohfrontsbase << "http1_nb502responses" << label << doh->d_http1Stats.d_nb502Responses << "\n";
647 output << dohfrontsbase << "http1_nbotherresponses" << label << doh->d_http1Stats.d_nbOtherResponses << "\n";
648 output << dohfrontsbase << "http2_queries" << label << doh->d_http2Stats.d_nbQueries << "\n";
649 output << dohfrontsbase << "http2_nb200responses" << label << doh->d_http2Stats.d_nb200Responses << "\n";
650 output << dohfrontsbase << "http2_nb400responses" << label << doh->d_http2Stats.d_nb400Responses << "\n";
651 output << dohfrontsbase << "http2_nb403responses" << label << doh->d_http2Stats.d_nb403Responses << "\n";
652 output << dohfrontsbase << "http2_nb500responses" << label << doh->d_http2Stats.d_nb500Responses << "\n";
653 output << dohfrontsbase << "http2_nb502responses" << label << doh->d_http2Stats.d_nb502Responses << "\n";
654 output << dohfrontsbase << "http2_nbotherresponses" << label << doh->d_http2Stats.d_nbOtherResponses << "\n";
655 }
656 #endif /* HAVE_DNS_OVER_HTTPS */
657
658 auto localPools = g_pools.getLocal();
659 const string cachebase = "dnsdist_pool_";
660
661 for (const auto& entry : *localPools) {
662 string poolName = entry.first;
663
664 if (poolName.empty()) {
665 poolName = "_default_";
666 }
667 const string label = "{pool=\"" + poolName + "\"}";
668 const std::shared_ptr<ServerPool> pool = entry.second;
669 output << "dnsdist_pool_servers" << label << " " << pool->countServers(false) << "\n";
670 output << "dnsdist_pool_active_servers" << label << " " << pool->countServers(true) << "\n";
671
672 if (pool->packetCache != nullptr) {
673 const auto& cache = pool->packetCache;
674
675 output << cachebase << "cache_size" <<label << " " << cache->getMaxEntries() << "\n";
676 output << cachebase << "cache_entries" <<label << " " << cache->getEntriesCount() << "\n";
677 output << cachebase << "cache_hits" <<label << " " << cache->getHits() << "\n";
678 output << cachebase << "cache_misses" <<label << " " << cache->getMisses() << "\n";
679 output << cachebase << "cache_deferred_inserts" <<label << " " << cache->getDeferredInserts() << "\n";
680 output << cachebase << "cache_deferred_lookups" <<label << " " << cache->getDeferredLookups() << "\n";
681 output << cachebase << "cache_lookup_collisions" <<label << " " << cache->getLookupCollisions() << "\n";
682 output << cachebase << "cache_insert_collisions" <<label << " " << cache->getInsertCollisions() << "\n";
683 output << cachebase << "cache_ttl_too_shorts" <<label << " " << cache->getTTLTooShorts() << "\n";
684 }
685 }
686
687 resp.body = output.str();
688 resp.headers["Content-Type"] = "text/plain";
689 }
690
691 else if(req.url.path=="/api/v1/servers/localhost") {
692 handleCORS(req, resp);
693 resp.status=200;
694
695 Json::array servers;
696 auto localServers = g_dstates.getLocal();
697 int num=0;
698 for(const auto& a : *localServers) {
699 string status;
700 if(a->availability == DownstreamState::Availability::Up)
701 status = "UP";
702 else if(a->availability == DownstreamState::Availability::Down)
703 status = "DOWN";
704 else
705 status = (a->upStatus ? "up" : "down");
706
707 Json::array pools;
708 for(const auto& p: a->pools)
709 pools.push_back(p);
710
711 Json::object server{
712 {"id", num++},
713 {"name", a->name},
714 {"address", a->remote.toStringWithPort()},
715 {"state", status},
716 {"qps", (double)a->queryLoad},
717 {"qpsLimit", (double)a->qps.getRate()},
718 {"outstanding", (double)a->outstanding},
719 {"reuseds", (double)a->reuseds},
720 {"weight", (double)a->weight},
721 {"order", (double)a->order},
722 {"pools", pools},
723 {"latency", (double)(a->latencyUsec/1000.0)},
724 {"queries", (double)a->queries},
725 {"sendErrors", (double)a->sendErrors},
726 {"tcpDiedSendingQuery", (double)a->tcpDiedSendingQuery},
727 {"tcpDiedReadingResponse", (double)a->tcpDiedReadingResponse},
728 {"tcpGaveUp", (double)a->tcpGaveUp},
729 {"tcpReadTimeouts", (double)a->tcpReadTimeouts},
730 {"tcpWriteTimeouts", (double)a->tcpWriteTimeouts},
731 {"tcpCurrentConnections", (double)a->tcpCurrentConnections},
732 {"tcpAvgQueriesPerConnection", (double)a->tcpAvgQueriesPerConnection},
733 {"tcpAvgConnectionDuration", (double)a->tcpAvgConnectionDuration},
734 {"dropRate", (double)a->dropRate}
735 };
736
737 /* sending a latency for a DOWN server doesn't make sense */
738 if (a->availability == DownstreamState::Availability::Down) {
739 server["latency"] = nullptr;
740 }
741
742 servers.push_back(server);
743 }
744
745 Json::array frontends;
746 num=0;
747 for(const auto& front : g_frontends) {
748 if (front->udpFD == -1 && front->tcpFD == -1)
749 continue;
750 Json::object frontend{
751 { "id", num++ },
752 { "address", front->local.toStringWithPort() },
753 { "udp", front->udpFD >= 0 },
754 { "tcp", front->tcpFD >= 0 },
755 { "type", front->getType() },
756 { "queries", (double) front->queries.load() },
757 { "tcpDiedReadingQuery", (double) front->tcpDiedReadingQuery.load() },
758 { "tcpDiedSendingResponse", (double) front->tcpDiedSendingResponse.load() },
759 { "tcpGaveUp", (double) front->tcpGaveUp.load() },
760 { "tcpClientTimeouts", (double) front->tcpClientTimeouts },
761 { "tcpDownstreamTimeouts", (double) front->tcpDownstreamTimeouts },
762 { "tcpCurrentConnections", (double) front->tcpCurrentConnections },
763 { "tcpAvgQueriesPerConnection", (double) front->tcpAvgQueriesPerConnection },
764 { "tcpAvgConnectionDuration", (double) front->tcpAvgConnectionDuration },
765 };
766 frontends.push_back(frontend);
767 }
768
769 Json::array dohs;
770 #ifdef HAVE_DNS_OVER_HTTPS
771 {
772 num = 0;
773 for(const auto& doh : g_dohlocals) {
774 Json::object obj{
775 { "id", num++ },
776 { "address", doh->d_local.toStringWithPort() },
777 { "http-connects", (double) doh->d_httpconnects },
778 { "http1-queries", (double) doh->d_http1Stats.d_nbQueries },
779 { "http2-queries", (double) doh->d_http2Stats.d_nbQueries },
780 { "http1-200-responses", (double) doh->d_http1Stats.d_nb200Responses },
781 { "http2-200-responses", (double) doh->d_http2Stats.d_nb200Responses },
782 { "http1-400-responses", (double) doh->d_http1Stats.d_nb400Responses },
783 { "http2-400-responses", (double) doh->d_http2Stats.d_nb400Responses },
784 { "http1-403-responses", (double) doh->d_http1Stats.d_nb403Responses },
785 { "http2-403-responses", (double) doh->d_http2Stats.d_nb403Responses },
786 { "http1-500-responses", (double) doh->d_http1Stats.d_nb500Responses },
787 { "http2-500-responses", (double) doh->d_http2Stats.d_nb500Responses },
788 { "http1-502-responses", (double) doh->d_http1Stats.d_nb502Responses },
789 { "http2-502-responses", (double) doh->d_http2Stats.d_nb502Responses },
790 { "http1-other-responses", (double) doh->d_http1Stats.d_nbOtherResponses },
791 { "http2-other-responses", (double) doh->d_http2Stats.d_nbOtherResponses },
792 { "tls10-queries", (double) doh->d_tls10queries },
793 { "tls11-queries", (double) doh->d_tls11queries },
794 { "tls12-queries", (double) doh->d_tls12queries },
795 { "tls13-queries", (double) doh->d_tls13queries },
796 { "tls-unknown-queries", (double) doh->d_tlsUnknownqueries },
797 { "get-queries", (double) doh->d_getqueries },
798 { "post-queries", (double) doh->d_postqueries },
799 { "bad-requests", (double) doh->d_badrequests },
800 { "error-responses", (double) doh->d_errorresponses },
801 { "valid-responses", (double) doh->d_validresponses }
802 };
803 dohs.push_back(obj);
804 }
805 }
806 #endif /* HAVE_DNS_OVER_HTTPS */
807
808 Json::array pools;
809 auto localPools = g_pools.getLocal();
810 num=0;
811 for(const auto& pool : *localPools) {
812 const auto& cache = pool.second->packetCache;
813 Json::object entry {
814 { "id", num++ },
815 { "name", pool.first },
816 { "serversCount", (double) pool.second->countServers(false) },
817 { "cacheSize", (double) (cache ? cache->getMaxEntries() : 0) },
818 { "cacheEntries", (double) (cache ? cache->getEntriesCount() : 0) },
819 { "cacheHits", (double) (cache ? cache->getHits() : 0) },
820 { "cacheMisses", (double) (cache ? cache->getMisses() : 0) },
821 { "cacheDeferredInserts", (double) (cache ? cache->getDeferredInserts() : 0) },
822 { "cacheDeferredLookups", (double) (cache ? cache->getDeferredLookups() : 0) },
823 { "cacheLookupCollisions", (double) (cache ? cache->getLookupCollisions() : 0) },
824 { "cacheInsertCollisions", (double) (cache ? cache->getInsertCollisions() : 0) },
825 { "cacheTTLTooShorts", (double) (cache ? cache->getTTLTooShorts() : 0) }
826 };
827 pools.push_back(entry);
828 }
829
830 Json::array rules;
831 auto localRules = g_rulactions.getLocal();
832 num=0;
833 for(const auto& a : *localRules) {
834 Json::object rule{
835 {"id", num++},
836 {"creationOrder", (double)a.d_creationOrder},
837 {"uuid", boost::uuids::to_string(a.d_id)},
838 {"matches", (double)a.d_rule->d_matches},
839 {"rule", a.d_rule->toString()},
840 {"action", a.d_action->toString()},
841 {"action-stats", a.d_action->getStats()}
842 };
843 rules.push_back(rule);
844 }
845
846 auto responseRules = someResponseRulesToJson(&g_resprulactions);
847 auto cacheHitResponseRules = someResponseRulesToJson(&g_cachehitresprulactions);
848 auto selfAnsweredResponseRules = someResponseRulesToJson(&g_selfansweredresprulactions);
849
850 string acl;
851
852 vector<string> vec;
853 g_ACL.getLocal()->toStringVector(&vec);
854
855 for(const auto& s : vec) {
856 if(!acl.empty()) acl += ", ";
857 acl+=s;
858 }
859 string localaddresses;
860 for(const auto& front : g_frontends) {
861 if (front->tcp) {
862 continue;
863 }
864 if (!localaddresses.empty()) {
865 localaddresses += ", ";
866 }
867 localaddresses += front->local.toStringWithPort();
868 }
869
870 Json my_json = Json::object {
871 { "daemon_type", "dnsdist" },
872 { "version", VERSION},
873 { "servers", servers},
874 { "frontends", frontends },
875 { "pools", pools },
876 { "rules", rules},
877 { "response-rules", responseRules},
878 { "cache-hit-response-rules", cacheHitResponseRules},
879 { "self-answered-response-rules", selfAnsweredResponseRules},
880 { "acl", acl},
881 { "local", localaddresses},
882 { "dohFrontends", dohs }
883 };
884 resp.headers["Content-Type"] = "application/json";
885 resp.body=my_json.dump();
886 }
887 else if(req.url.path=="/api/v1/servers/localhost/statistics") {
888 handleCORS(req, resp);
889 resp.status=200;
890
891 Json::array doc;
892 for(const auto& item : g_stats.entries) {
893 if (item.first == "special-memory-usage")
894 continue; // Too expensive for get-all
895
896 if(const auto& val = boost::get<DNSDistStats::stat_t*>(&item.second)) {
897 doc.push_back(Json::object {
898 { "type", "StatisticItem" },
899 { "name", item.first },
900 { "value", (double)(*val)->load() }
901 });
902 }
903 else if (const auto& dval = boost::get<double*>(&item.second)) {
904 doc.push_back(Json::object {
905 { "type", "StatisticItem" },
906 { "name", item.first },
907 { "value", (**dval) }
908 });
909 }
910 else {
911 doc.push_back(Json::object {
912 { "type", "StatisticItem" },
913 { "name", item.first },
914 { "value", (double)(*boost::get<DNSDistStats::statfunction_t>(&item.second))(item.first) }
915 });
916 }
917 }
918 Json my_json = doc;
919 resp.body=my_json.dump();
920 resp.headers["Content-Type"] = "application/json";
921 }
922 else if(req.url.path=="/api/v1/servers/localhost/config") {
923 handleCORS(req, resp);
924 resp.status=200;
925
926 Json::array doc;
927 typedef boost::variant<bool, double, std::string> configentry_t;
928 std::vector<std::pair<std::string, configentry_t> > configEntries {
929 { "acl", g_ACL.getLocal()->toString() },
930 { "allow-empty-response", g_allowEmptyResponse },
931 { "control-socket", g_serverControl.toStringWithPort() },
932 { "ecs-override", g_ECSOverride },
933 { "ecs-source-prefix-v4", (double) g_ECSSourcePrefixV4 },
934 { "ecs-source-prefix-v6", (double) g_ECSSourcePrefixV6 },
935 { "fixup-case", g_fixupCase },
936 { "max-outstanding", (double) g_maxOutstanding },
937 { "server-policy", g_policy.getLocal()->name },
938 { "stale-cache-entries-ttl", (double) g_staleCacheEntriesTTL },
939 { "tcp-recv-timeout", (double) g_tcpRecvTimeout },
940 { "tcp-send-timeout", (double) g_tcpSendTimeout },
941 { "truncate-tc", g_truncateTC },
942 { "verbose", g_verbose },
943 { "verbose-health-checks", g_verboseHealthChecks }
944 };
945 for(const auto& item : configEntries) {
946 if (const auto& bval = boost::get<bool>(&item.second)) {
947 doc.push_back(Json::object {
948 { "type", "ConfigSetting" },
949 { "name", item.first },
950 { "value", *bval }
951 });
952 }
953 else if (const auto& sval = boost::get<string>(&item.second)) {
954 doc.push_back(Json::object {
955 { "type", "ConfigSetting" },
956 { "name", item.first },
957 { "value", *sval }
958 });
959 }
960 else if (const auto& dval = boost::get<double>(&item.second)) {
961 doc.push_back(Json::object {
962 { "type", "ConfigSetting" },
963 { "name", item.first },
964 { "value", *dval }
965 });
966 }
967 }
968 Json my_json = doc;
969 resp.body=my_json.dump();
970 resp.headers["Content-Type"] = "application/json";
971 }
972 else if(req.url.path=="/api/v1/servers/localhost/config/allow-from") {
973 handleCORS(req, resp);
974
975 resp.headers["Content-Type"] = "application/json";
976 resp.status=200;
977
978 if (req.method == "PUT") {
979 std::string err;
980 Json doc = Json::parse(req.body, err);
981
982 if (!doc.is_null()) {
983 NetmaskGroup nmg;
984 auto aclList = doc["value"];
985 if (aclList.is_array()) {
986
987 for (auto value : aclList.array_items()) {
988 try {
989 nmg.addMask(value.string_value());
990 } catch (NetmaskException &e) {
991 resp.status = 400;
992 break;
993 }
994 }
995
996 if (resp.status == 200) {
997 infolog("Updating the ACL via the API to %s", nmg.toString());
998 g_ACL.setState(nmg);
999 apiSaveACL(nmg);
1000 }
1001 }
1002 else {
1003 resp.status = 400;
1004 }
1005 }
1006 else {
1007 resp.status = 400;
1008 }
1009 }
1010 if (resp.status == 200) {
1011 Json::array acl;
1012 vector<string> vec;
1013 g_ACL.getLocal()->toStringVector(&vec);
1014
1015 for(const auto& s : vec) {
1016 acl.push_back(s);
1017 }
1018
1019 Json::object obj{
1020 { "type", "ConfigSetting" },
1021 { "name", "allow-from" },
1022 { "value", acl }
1023 };
1024 Json my_json = obj;
1025 resp.body=my_json.dump();
1026 }
1027 }
1028 else if(!req.url.path.empty() && g_urlmap.count(req.url.path.c_str()+1)) {
1029 resp.body.assign(g_urlmap[req.url.path.c_str()+1]);
1030 vector<string> parts;
1031 stringtok(parts, req.url.path, ".");
1032 if(parts.back() == "html")
1033 resp.headers["Content-Type"] = "text/html" + charset;
1034 else if(parts.back() == "css")
1035 resp.headers["Content-Type"] = "text/css" + charset;
1036 else if(parts.back() == "js")
1037 resp.headers["Content-Type"] = "application/javascript" + charset;
1038 else if(parts.back() == "png")
1039 resp.headers["Content-Type"] = "image/png";
1040 resp.status=200;
1041 }
1042 else if(req.url.path=="/") {
1043 resp.body.assign(g_urlmap["index.html"]);
1044 resp.headers["Content-Type"] = "text/html" + charset;
1045 resp.status=200;
1046 }
1047 else {
1048 // cerr<<"404 for: "<<req.url.path<<endl;
1049 resp.status=404;
1050 }
1051
1052 std::ostringstream ofs;
1053 ofs << resp;
1054 string done;
1055 done=ofs.str();
1056 writen2(sock, done.c_str(), done.size());
1057
1058 close(sock);
1059 sock = -1;
1060 }
1061 catch(const YaHTTP::ParseError& e) {
1062 vinfolog("Webserver thread died with parse error exception while processing a request from %s: %s", remote.toStringWithPort(), e.what());
1063 close(sock);
1064 }
1065 catch(const std::exception& e) {
1066 errlog("Webserver thread died with exception while processing a request from %s: %s", remote.toStringWithPort(), e.what());
1067 close(sock);
1068 }
1069 catch(...) {
1070 errlog("Webserver thread died with exception while processing a request from %s", remote.toStringWithPort());
1071 close(sock);
1072 }
1073 }
1074
1075 void setWebserverAPIKey(const boost::optional<std::string> apiKey)
1076 {
1077 std::lock_guard<std::mutex> lock(g_webserverConfig.lock);
1078
1079 if (apiKey) {
1080 g_webserverConfig.apiKey = *apiKey;
1081 } else {
1082 g_webserverConfig.apiKey.clear();
1083 }
1084 }
1085
1086 void setWebserverPassword(const std::string& password)
1087 {
1088 std::lock_guard<std::mutex> lock(g_webserverConfig.lock);
1089
1090 g_webserverConfig.password = password;
1091 }
1092
1093 void setWebserverCustomHeaders(const boost::optional<std::map<std::string, std::string> > customHeaders)
1094 {
1095 std::lock_guard<std::mutex> lock(g_webserverConfig.lock);
1096
1097 g_webserverConfig.customHeaders = customHeaders;
1098 }
1099
1100 void dnsdistWebserverThread(int sock, const ComboAddress& local)
1101 {
1102 setThreadName("dnsdist/webserv");
1103 warnlog("Webserver launched on %s", local.toStringWithPort());
1104 for(;;) {
1105 try {
1106 ComboAddress remote(local);
1107 int fd = SAccept(sock, remote);
1108 vinfolog("Got connection from %s", remote.toStringWithPort());
1109 std::thread t(connectionThread, fd, remote);
1110 t.detach();
1111 }
1112 catch(std::exception& e) {
1113 errlog("Had an error accepting new webserver connection: %s", e.what());
1114 }
1115 }
1116 }