]> git.ipfire.org Git - thirdparty/pdns.git/blob - pdns/dnsdist-web.cc
Merge pull request #9114 from pieterlexis/rec-may-2020
[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 "dnsdist-healthchecks.hh"
24 #include "dnsdist-prometheus.hh"
25
26 #include "sstuff.hh"
27 #include "ext/json11/json11.hpp"
28 #include "ext/incbin/incbin.h"
29 #include "dolog.hh"
30 #include <thread>
31 #include "threadname.hh"
32 #include <sstream>
33 #include <yahttp/yahttp.hpp>
34 #include "namespaces.hh"
35 #include <sys/time.h>
36 #include <sys/resource.h>
37 #include "ext/incbin/incbin.h"
38 #include "htmlfiles.h"
39 #include "base64.hh"
40 #include "gettime.hh"
41 #include <boost/format.hpp>
42
43 bool g_apiReadWrite{false};
44 WebserverConfig g_webserverConfig;
45 std::string g_apiConfigDirectory;
46 static const MetricDefinitionStorage s_metricDefinitions;
47
48 const std::map<std::string, MetricDefinition> MetricDefinitionStorage::metrics{
49 { "responses", MetricDefinition(PrometheusMetricType::counter, "Number of responses received from backends") },
50 { "servfail-responses", MetricDefinition(PrometheusMetricType::counter, "Number of SERVFAIL answers received from backends") },
51 { "queries", MetricDefinition(PrometheusMetricType::counter, "Number of received queries")},
52 { "frontend-nxdomain", MetricDefinition(PrometheusMetricType::counter, "Number of NXDomain answers sent to clients")},
53 { "frontend-servfail", MetricDefinition(PrometheusMetricType::counter, "Number of SERVFAIL answers sent to clients")},
54 { "frontend-noerror", MetricDefinition(PrometheusMetricType::counter, "Number of NoError answers sent to clients")},
55 { "acl-drops", MetricDefinition(PrometheusMetricType::counter, "Number of packets dropped because of the ACL")},
56 { "rule-drop", MetricDefinition(PrometheusMetricType::counter, "Number of queries dropped because of a rule")},
57 { "rule-nxdomain", MetricDefinition(PrometheusMetricType::counter, "Number of NXDomain answers returned because of a rule")},
58 { "rule-refused", MetricDefinition(PrometheusMetricType::counter, "Number of Refused answers returned because of a rule")},
59 { "rule-servfail", MetricDefinition(PrometheusMetricType::counter, "Number of SERVFAIL answers received because of a rule")},
60 { "self-answered", MetricDefinition(PrometheusMetricType::counter, "Number of self-answered responses")},
61 { "downstream-timeouts", MetricDefinition(PrometheusMetricType::counter, "Number of queries not answered in time by a backend")},
62 { "downstream-send-errors", MetricDefinition(PrometheusMetricType::counter, "Number of errors when sending a query to a backend")},
63 { "trunc-failures", MetricDefinition(PrometheusMetricType::counter, "Number of errors encountered while truncating an answer")},
64 { "no-policy", MetricDefinition(PrometheusMetricType::counter, "Number of queries dropped because no server was available")},
65 { "latency0-1", MetricDefinition(PrometheusMetricType::counter, "Number of queries answered in less than 1ms")},
66 { "latency1-10", MetricDefinition(PrometheusMetricType::counter, "Number of queries answered in 1-10 ms")},
67 { "latency10-50", MetricDefinition(PrometheusMetricType::counter, "Number of queries answered in 10-50 ms")},
68 { "latency50-100", MetricDefinition(PrometheusMetricType::counter, "Number of queries answered in 50-100 ms")},
69 { "latency100-1000", MetricDefinition(PrometheusMetricType::counter, "Number of queries answered in 100-1000 ms")},
70 { "latency-slow", MetricDefinition(PrometheusMetricType::counter, "Number of queries answered in more than 1 second")},
71 { "latency-avg100", MetricDefinition(PrometheusMetricType::gauge, "Average response latency in microseconds of the last 100 packets")},
72 { "latency-avg1000", MetricDefinition(PrometheusMetricType::gauge, "Average response latency in microseconds of the last 1000 packets")},
73 { "latency-avg10000", MetricDefinition(PrometheusMetricType::gauge, "Average response latency in microseconds of the last 10000 packets")},
74 { "latency-avg1000000", MetricDefinition(PrometheusMetricType::gauge, "Average response latency in microseconds of the last 1000000 packets")},
75 { "uptime", MetricDefinition(PrometheusMetricType::gauge, "Uptime of the dnsdist process in seconds")},
76 { "real-memory-usage", MetricDefinition(PrometheusMetricType::gauge, "Current memory usage in bytes")},
77 { "noncompliant-queries", MetricDefinition(PrometheusMetricType::counter, "Number of queries dropped as non-compliant")},
78 { "noncompliant-responses", MetricDefinition(PrometheusMetricType::counter, "Number of answers from a backend dropped as non-compliant")},
79 { "rdqueries", MetricDefinition(PrometheusMetricType::counter, "Number of received queries with the recursion desired bit set")},
80 { "empty-queries", MetricDefinition(PrometheusMetricType::counter, "Number of empty queries received from clients")},
81 { "cache-hits", MetricDefinition(PrometheusMetricType::counter, "Number of times an answer was retrieved from cache")},
82 { "cache-misses", MetricDefinition(PrometheusMetricType::counter, "Number of times an answer not found in the cache")},
83 { "cpu-iowait", MetricDefinition(PrometheusMetricType::counter, "Time waiting for I/O to complete by the whole system, in units of USER_HZ")},
84 { "cpu-user-msec", MetricDefinition(PrometheusMetricType::counter, "Milliseconds spent by dnsdist in the user state")},
85 { "cpu-steal", MetricDefinition(PrometheusMetricType::counter, "Stolen time, which is the time spent by the whole system in other operating systems when running in a virtualized environment, in units of USER_HZ")},
86 { "cpu-sys-msec", MetricDefinition(PrometheusMetricType::counter, "Milliseconds spent by dnsdist in the system state")},
87 { "fd-usage", MetricDefinition(PrometheusMetricType::gauge, "Number of currently used file descriptors")},
88 { "dyn-blocked", MetricDefinition(PrometheusMetricType::counter, "Number of queries dropped because of a dynamic block")},
89 { "dyn-block-nmg-size", MetricDefinition(PrometheusMetricType::gauge, "Number of dynamic blocks entries") },
90 { "security-status", MetricDefinition(PrometheusMetricType::gauge, "Security status of this software. 0=unknown, 1=OK, 2=upgrade recommended, 3=upgrade mandatory") },
91 { "udp-in-errors", MetricDefinition(PrometheusMetricType::counter, "From /proc/net/snmp InErrors") },
92 { "udp-noport-errors", MetricDefinition(PrometheusMetricType::counter, "From /proc/net/snmp NoPorts") },
93 { "udp-recvbuf-errors", MetricDefinition(PrometheusMetricType::counter, "From /proc/net/snmp RcvbufErrors") },
94 { "udp-sndbuf-errors", MetricDefinition(PrometheusMetricType::counter, "From /proc/net/snmp SndbufErrors") },
95 };
96
97 static bool apiWriteConfigFile(const string& filebasename, const string& content)
98 {
99 if (!g_apiReadWrite) {
100 errlog("Not writing content to %s since the API is read-only", filebasename);
101 return false;
102 }
103
104 if (g_apiConfigDirectory.empty()) {
105 vinfolog("Not writing content to %s since the API configuration directory is not set", filebasename);
106 return false;
107 }
108
109 string filename = g_apiConfigDirectory + "/" + filebasename + ".conf";
110 ofstream ofconf(filename.c_str());
111 if (!ofconf) {
112 errlog("Could not open configuration fragment file '%s' for writing: %s", filename, stringerror());
113 return false;
114 }
115 ofconf << "-- Generated by the REST API, DO NOT EDIT" << endl;
116 ofconf << content << endl;
117 ofconf.close();
118 return true;
119 }
120
121 static void apiSaveACL(const NetmaskGroup& nmg)
122 {
123 vector<string> vec;
124 nmg.toStringVector(&vec);
125
126 string acl;
127 for(const auto& s : vec) {
128 if (!acl.empty()) {
129 acl += ", ";
130 }
131 acl += "\"" + s + "\"";
132 }
133
134 string content = "setACL({" + acl + "})";
135 apiWriteConfigFile("acl", content);
136 }
137
138 static bool checkAPIKey(const YaHTTP::Request& req, const string& expectedApiKey)
139 {
140 if (expectedApiKey.empty()) {
141 return false;
142 }
143
144 const auto header = req.headers.find("x-api-key");
145 if (header != req.headers.end()) {
146 return (header->second == expectedApiKey);
147 }
148
149 return false;
150 }
151
152 static bool checkWebPassword(const YaHTTP::Request& req, const string &expected_password)
153 {
154 static const char basicStr[] = "basic ";
155
156 const auto header = req.headers.find("authorization");
157
158 if (header != req.headers.end() && toLower(header->second).find(basicStr) == 0) {
159 string cookie = header->second.substr(sizeof(basicStr) - 1);
160
161 string plain;
162 B64Decode(cookie, plain);
163
164 vector<string> cparts;
165 stringtok(cparts, plain, ":");
166
167 if (cparts.size() == 2) {
168 return cparts[1] == expected_password;
169 }
170 }
171
172 return false;
173 }
174
175 static bool isAnAPIRequest(const YaHTTP::Request& req)
176 {
177 return req.url.path.find("/api/") == 0;
178 }
179
180 static bool isAnAPIRequestAllowedWithWebAuth(const YaHTTP::Request& req)
181 {
182 return req.url.path == "/api/v1/servers/localhost";
183 }
184
185 static bool isAStatsRequest(const YaHTTP::Request& req)
186 {
187 return req.url.path == "/jsonstat" || req.url.path == "/metrics";
188 }
189
190 static bool compareAuthorization(const YaHTTP::Request& req)
191 {
192 std::lock_guard<std::mutex> lock(g_webserverConfig.lock);
193
194 if (isAnAPIRequest(req)) {
195 /* Access to the API requires a valid API key */
196 if (checkAPIKey(req, g_webserverConfig.apiKey)) {
197 return true;
198 }
199
200 return isAnAPIRequestAllowedWithWebAuth(req) && checkWebPassword(req, g_webserverConfig.password);
201 }
202
203 if (isAStatsRequest(req)) {
204 /* Access to the stats is allowed for both API and Web users */
205 return checkAPIKey(req, g_webserverConfig.apiKey) || checkWebPassword(req, g_webserverConfig.password);
206 }
207
208 return checkWebPassword(req, g_webserverConfig.password);
209 }
210
211 static bool isMethodAllowed(const YaHTTP::Request& req)
212 {
213 if (req.method == "GET") {
214 return true;
215 }
216 if (req.method == "PUT" && g_apiReadWrite) {
217 if (req.url.path == "/api/v1/servers/localhost/config/allow-from") {
218 return true;
219 }
220 }
221 return false;
222 }
223
224 static void handleCORS(const YaHTTP::Request& req, YaHTTP::Response& resp)
225 {
226 const auto origin = req.headers.find("Origin");
227 if (origin != req.headers.end()) {
228 if (req.method == "OPTIONS") {
229 /* Pre-flight request */
230 if (g_apiReadWrite) {
231 resp.headers["Access-Control-Allow-Methods"] = "GET, PUT";
232 }
233 else {
234 resp.headers["Access-Control-Allow-Methods"] = "GET";
235 }
236 resp.headers["Access-Control-Allow-Headers"] = "Authorization, X-API-Key";
237 }
238
239 resp.headers["Access-Control-Allow-Origin"] = origin->second;
240
241 if (isAStatsRequest(req) || isAnAPIRequestAllowedWithWebAuth(req)) {
242 resp.headers["Access-Control-Allow-Credentials"] = "true";
243 }
244 }
245 }
246
247 static void addSecurityHeaders(YaHTTP::Response& resp, const boost::optional<std::map<std::string, std::string> >& customHeaders)
248 {
249 static const std::vector<std::pair<std::string, std::string> > headers = {
250 { "X-Content-Type-Options", "nosniff" },
251 { "X-Frame-Options", "deny" },
252 { "X-Permitted-Cross-Domain-Policies", "none" },
253 { "X-XSS-Protection", "1; mode=block" },
254 { "Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'" },
255 };
256
257 for (const auto& h : headers) {
258 if (customHeaders) {
259 const auto& custom = customHeaders->find(h.first);
260 if (custom != customHeaders->end()) {
261 continue;
262 }
263 }
264 resp.headers[h.first] = h.second;
265 }
266 }
267
268 static void addCustomHeaders(YaHTTP::Response& resp, const boost::optional<std::map<std::string, std::string> >& customHeaders)
269 {
270 if (!customHeaders)
271 return;
272
273 for (const auto& c : *customHeaders) {
274 if (!c.second.empty()) {
275 resp.headers[c.first] = c.second;
276 }
277 }
278 }
279
280 template<typename T>
281 static json11::Json::array someResponseRulesToJson(GlobalStateHolder<vector<T>>* someResponseRules)
282 {
283 using namespace json11;
284 Json::array responseRules;
285 int num=0;
286 auto localResponseRules = someResponseRules->getLocal();
287 for(const auto& a : *localResponseRules) {
288 Json::object rule{
289 {"id", num++},
290 {"creationOrder", (double)a.d_creationOrder},
291 {"uuid", boost::uuids::to_string(a.d_id)},
292 {"matches", (double)a.d_rule->d_matches},
293 {"rule", a.d_rule->toString()},
294 {"action", a.d_action->toString()},
295 };
296 responseRules.push_back(rule);
297 }
298 return responseRules;
299 }
300
301 static void connectionThread(int sock, ComboAddress remote)
302 {
303 setThreadName("dnsdist/webConn");
304
305 using namespace json11;
306 vinfolog("Webserver handling connection from %s", remote.toStringWithPort());
307
308 try {
309 YaHTTP::AsyncRequestLoader yarl;
310 YaHTTP::Request req;
311 bool finished = false;
312
313 yarl.initialize(&req);
314 while(!finished) {
315 int bytes;
316 char buf[1024];
317 bytes = read(sock, buf, sizeof(buf));
318 if (bytes > 0) {
319 string data = string(buf, bytes);
320 finished = yarl.feed(data);
321 } else {
322 // read error OR EOF
323 break;
324 }
325 }
326 yarl.finalize();
327
328 string command=req.getvars["command"];
329
330 req.getvars.erase("_"); // jQuery cache buster
331
332 YaHTTP::Response resp;
333 resp.version = req.version;
334 const string charset = "; charset=utf-8";
335
336 {
337 std::lock_guard<std::mutex> lock(g_webserverConfig.lock);
338
339 addCustomHeaders(resp, g_webserverConfig.customHeaders);
340 addSecurityHeaders(resp, g_webserverConfig.customHeaders);
341 }
342 /* indicate that the connection will be closed after completion of the response */
343 resp.headers["Connection"] = "close";
344
345 /* no need to send back the API key if any */
346 resp.headers.erase("X-API-Key");
347
348 if(req.method == "OPTIONS") {
349 /* the OPTIONS method should not require auth, otherwise it breaks CORS */
350 handleCORS(req, resp);
351 resp.status=200;
352 }
353 else if (!compareAuthorization(req)) {
354 YaHTTP::strstr_map_t::iterator header = req.headers.find("authorization");
355 if (header != req.headers.end())
356 errlog("HTTP Request \"%s\" from %s: Web Authentication failed", req.url.path, remote.toStringWithPort());
357 resp.status=401;
358 resp.body="<h1>Unauthorized</h1>";
359 resp.headers["WWW-Authenticate"] = "basic realm=\"PowerDNS\"";
360
361 }
362 else if(!isMethodAllowed(req)) {
363 resp.status=405;
364 }
365 else if(req.url.path=="/jsonstat") {
366 handleCORS(req, resp);
367 resp.status=200;
368
369 if(command=="stats") {
370 auto obj=Json::object {
371 { "packetcache-hits", 0},
372 { "packetcache-misses", 0},
373 { "over-capacity-drops", 0 },
374 { "too-old-drops", 0 },
375 { "server-policy", g_policy.getLocal()->name}
376 };
377
378 for(const auto& e : g_stats.entries) {
379 if (e.first == "special-memory-usage")
380 continue; // Too expensive for get-all
381 if(const auto& val = boost::get<DNSDistStats::stat_t*>(&e.second))
382 obj.insert({e.first, (double)(*val)->load()});
383 else if (const auto& dval = boost::get<double*>(&e.second))
384 obj.insert({e.first, (**dval)});
385 else
386 obj.insert({e.first, (double)(*boost::get<DNSDistStats::statfunction_t>(&e.second))(e.first)});
387 }
388 Json my_json = obj;
389 resp.body=my_json.dump();
390 resp.headers["Content-Type"] = "application/json";
391 }
392 else if(command=="dynblocklist") {
393 Json::object obj;
394 auto nmg = g_dynblockNMG.getLocal();
395 struct timespec now;
396 gettime(&now);
397 for(const auto& e: *nmg) {
398 if(now < e.second.until ) {
399 Json::object thing{
400 {"reason", e.second.reason},
401 {"seconds", (double)(e.second.until.tv_sec - now.tv_sec)},
402 {"blocks", (double)e.second.blocks},
403 {"action", DNSAction::typeToString(e.second.action != DNSAction::Action::None ? e.second.action : g_dynBlockAction) },
404 {"warning", e.second.warning }
405 };
406 obj.insert({e.first.toString(), thing});
407 }
408 }
409
410 auto smt = g_dynblockSMT.getLocal();
411 smt->visit([&now,&obj](const SuffixMatchTree<DynBlock>& node) {
412 if(now <node.d_value.until) {
413 string dom("empty");
414 if(!node.d_value.domain.empty())
415 dom = node.d_value.domain.toString();
416 Json::object thing{
417 {"reason", node.d_value.reason},
418 {"seconds", (double)(node.d_value.until.tv_sec - now.tv_sec)},
419 {"blocks", (double)node.d_value.blocks},
420 {"action", DNSAction::typeToString(node.d_value.action != DNSAction::Action::None ? node.d_value.action : g_dynBlockAction) }
421 };
422 obj.insert({dom, thing});
423 }
424 });
425
426
427
428 Json my_json = obj;
429 resp.body=my_json.dump();
430 resp.headers["Content-Type"] = "application/json";
431 }
432 else if(command=="ebpfblocklist") {
433 Json::object obj;
434 #ifdef HAVE_EBPF
435 struct timespec now;
436 gettime(&now);
437 for (const auto& dynbpf : g_dynBPFFilters) {
438 std::vector<std::tuple<ComboAddress, uint64_t, struct timespec> > addrStats = dynbpf->getAddrStats();
439 for (const auto& entry : addrStats) {
440 Json::object thing
441 {
442 {"seconds", (double)(std::get<2>(entry).tv_sec - now.tv_sec)},
443 {"blocks", (double)(std::get<1>(entry))}
444 };
445 obj.insert({std::get<0>(entry).toString(), thing });
446 }
447 }
448 #endif /* HAVE_EBPF */
449 Json my_json = obj;
450 resp.body=my_json.dump();
451 resp.headers["Content-Type"] = "application/json";
452 }
453 else {
454 resp.status=404;
455 }
456 }
457 else if (req.url.path == "/metrics") {
458 handleCORS(req, resp);
459 resp.status = 200;
460
461 std::ostringstream output;
462 static const std::set<std::string> metricBlacklist = { "latency-count", "latency-sum" };
463 for (const auto& e : g_stats.entries) {
464 if (e.first == "special-memory-usage")
465 continue; // Too expensive for get-all
466 std::string metricName = std::get<0>(e);
467
468 // Prometheus suggest using '_' instead of '-'
469 std::string prometheusMetricName = "dnsdist_" + boost::replace_all_copy(metricName, "-", "_");
470 if (metricBlacklist.count(metricName) != 0) {
471 continue;
472 }
473
474 MetricDefinition metricDetails;
475 if (!s_metricDefinitions.getMetricDetails(metricName, metricDetails)) {
476 vinfolog("Do not have metric details for %s", metricName);
477 continue;
478 }
479
480 std::string prometheusTypeName = s_metricDefinitions.getPrometheusStringMetricType(metricDetails.prometheusType);
481
482 if (prometheusTypeName == "") {
483 vinfolog("Unknown Prometheus type for %s", metricName);
484 continue;
485 }
486
487 // for these we have the help and types encoded in the sources:
488 output << "# HELP " << prometheusMetricName << " " << metricDetails.description << "\n";
489 output << "# TYPE " << prometheusMetricName << " " << prometheusTypeName << "\n";
490 output << prometheusMetricName << " ";
491
492 if (const auto& val = boost::get<DNSDistStats::stat_t*>(&std::get<1>(e)))
493 output << (*val)->load();
494 else if (const auto& dval = boost::get<double*>(&std::get<1>(e)))
495 output << **dval;
496 else
497 output << (*boost::get<DNSDistStats::statfunction_t>(&std::get<1>(e)))(std::get<0>(e));
498
499 output << "\n";
500 }
501
502 // Latency histogram buckets
503 output << "# HELP dnsdist_latency Histogram of responses by latency (in milliseconds)\n";
504 output << "# TYPE dnsdist_latency histogram\n";
505 uint64_t latency_amounts = g_stats.latency0_1;
506 output << "dnsdist_latency_bucket{le=\"1\"} " << latency_amounts << "\n";
507 latency_amounts += g_stats.latency1_10;
508 output << "dnsdist_latency_bucket{le=\"10\"} " << latency_amounts << "\n";
509 latency_amounts += g_stats.latency10_50;
510 output << "dnsdist_latency_bucket{le=\"50\"} " << latency_amounts << "\n";
511 latency_amounts += g_stats.latency50_100;
512 output << "dnsdist_latency_bucket{le=\"100\"} " << latency_amounts << "\n";
513 latency_amounts += g_stats.latency100_1000;
514 output << "dnsdist_latency_bucket{le=\"1000\"} " << latency_amounts << "\n";
515 latency_amounts += g_stats.latencySlow; // Should be the same as latency_count
516 output << "dnsdist_latency_bucket{le=\"+Inf\"} " << latency_amounts << "\n";
517 output << "dnsdist_latency_sum " << g_stats.latencySum << "\n";
518 output << "dnsdist_latency_count " << getLatencyCount(std::string()) << "\n";
519
520 auto states = g_dstates.getLocal();
521 const string statesbase = "dnsdist_server_";
522
523 output << "# HELP " << statesbase << "status " << "Whether this backend is up (1) or down (0)" << "\n";
524 output << "# TYPE " << statesbase << "status " << "gauge" << "\n";
525 output << "# HELP " << statesbase << "queries " << "Amount of queries relayed to server" << "\n";
526 output << "# TYPE " << statesbase << "queries " << "counter" << "\n";
527 output << "# HELP " << statesbase << "responses " << "Amount of responses received from this server" << "\n";
528 output << "# TYPE " << statesbase << "responses " << "counter" << "\n";
529 output << "# HELP " << statesbase << "drops " << "Amount of queries not answered by server" << "\n";
530 output << "# TYPE " << statesbase << "drops " << "counter" << "\n";
531 output << "# HELP " << statesbase << "latency " << "Server's latency when answering questions in milliseconds" << "\n";
532 output << "# TYPE " << statesbase << "latency " << "gauge" << "\n";
533 output << "# HELP " << statesbase << "senderrors " << "Total number of OS send errors while relaying queries" << "\n";
534 output << "# TYPE " << statesbase << "senderrors " << "counter" << "\n";
535 output << "# HELP " << statesbase << "outstanding " << "Current number of queries that are waiting for a backend response" << "\n";
536 output << "# TYPE " << statesbase << "outstanding " << "gauge" << "\n";
537 output << "# HELP " << statesbase << "order " << "The order in which this server is picked" << "\n";
538 output << "# TYPE " << statesbase << "order " << "gauge" << "\n";
539 output << "# HELP " << statesbase << "weight " << "The weight within the order in which this server is picked" << "\n";
540 output << "# TYPE " << statesbase << "weight " << "gauge" << "\n";
541 output << "# HELP " << statesbase << "tcpdiedsendingquery " << "The number of TCP I/O errors while sending the query" << "\n";
542 output << "# TYPE " << statesbase << "tcpdiedsendingquery " << "counter" << "\n";
543 output << "# HELP " << statesbase << "tcpdiedreadingresponse " << "The number of TCP I/O errors while reading the response" << "\n";
544 output << "# TYPE " << statesbase << "tcpdiedreadingresponse " << "counter" << "\n";
545 output << "# HELP " << statesbase << "tcpgaveup " << "The number of TCP connections failing after too many attempts" << "\n";
546 output << "# TYPE " << statesbase << "tcpgaveup " << "counter" << "\n";
547 output << "# HELP " << statesbase << "tcpreadtimeouts " << "The number of TCP read timeouts" << "\n";
548 output << "# TYPE " << statesbase << "tcpreadtimeouts " << "counter" << "\n";
549 output << "# HELP " << statesbase << "tcpwritetimeouts " << "The number of TCP write timeouts" << "\n";
550 output << "# TYPE " << statesbase << "tcpwritetimeouts " << "counter" << "\n";
551 output << "# HELP " << statesbase << "tcpcurrentconnections " << "The number of current TCP connections" << "\n";
552 output << "# TYPE " << statesbase << "tcpcurrentconnections " << "gauge" << "\n";
553 output << "# HELP " << statesbase << "tcpavgqueriesperconn " << "The average number of queries per TCP connection" << "\n";
554 output << "# TYPE " << statesbase << "tcpavgqueriesperconn " << "gauge" << "\n";
555 output << "# HELP " << statesbase << "tcpavgconnduration " << "The average duration of a TCP connection (ms)" << "\n";
556 output << "# TYPE " << statesbase << "tcpavgconnduration " << "gauge" << "\n";
557
558 for (const auto& state : *states) {
559 string serverName;
560
561 if (state->getName().empty())
562 serverName = state->remote.toStringWithPort();
563 else
564 serverName = state->getName();
565
566 boost::replace_all(serverName, ".", "_");
567
568 const std::string label = boost::str(boost::format("{server=\"%1%\",address=\"%2%\"}")
569 % serverName % state->remote.toStringWithPort());
570
571 output << statesbase << "status" << label << " " << (state->isUp() ? "1" : "0") << "\n";
572 output << statesbase << "queries" << label << " " << state->queries.load() << "\n";
573 output << statesbase << "responses" << label << " " << state->responses.load() << "\n";
574 output << statesbase << "drops" << label << " " << state->reuseds.load() << "\n";
575 output << statesbase << "latency" << label << " " << state->latencyUsec/1000.0 << "\n";
576 output << statesbase << "senderrors" << label << " " << state->sendErrors.load() << "\n";
577 output << statesbase << "outstanding" << label << " " << state->outstanding.load() << "\n";
578 output << statesbase << "order" << label << " " << state->order << "\n";
579 output << statesbase << "weight" << label << " " << state->weight << "\n";
580 output << statesbase << "tcpdiedsendingquery" << label << " " << state->tcpDiedSendingQuery << "\n";
581 output << statesbase << "tcpdiedreadingresponse" << label << " " << state->tcpDiedReadingResponse << "\n";
582 output << statesbase << "tcpgaveup" << label << " " << state->tcpGaveUp << "\n";
583 output << statesbase << "tcpreadtimeouts" << label << " " << state->tcpReadTimeouts << "\n";
584 output << statesbase << "tcpwritetimeouts" << label << " " << state->tcpWriteTimeouts << "\n";
585 output << statesbase << "tcpcurrentconnections" << label << " " << state->tcpCurrentConnections << "\n";
586 output << statesbase << "tcpavgqueriesperconn" << label << " " << state->tcpAvgQueriesPerConnection << "\n";
587 output << statesbase << "tcpavgconnduration" << label << " " << state->tcpAvgConnectionDuration << "\n";
588 }
589
590 const string frontsbase = "dnsdist_frontend_";
591 output << "# HELP " << frontsbase << "queries " << "Amount of queries received by this frontend" << "\n";
592 output << "# TYPE " << frontsbase << "queries " << "counter" << "\n";
593 output << "# HELP " << frontsbase << "responses " << "Amount of responses sent by this frontend" << "\n";
594 output << "# TYPE " << frontsbase << "responses " << "counter" << "\n";
595 output << "# HELP " << frontsbase << "tcpdiedreadingquery " << "Amount of TCP connections terminated while reading the query from the client" << "\n";
596 output << "# TYPE " << frontsbase << "tcpdiedreadingquery " << "counter" << "\n";
597 output << "# HELP " << frontsbase << "tcpdiedsendingresponse " << "Amount of TCP connections terminated while sending a response to the client" << "\n";
598 output << "# TYPE " << frontsbase << "tcpdiedsendingresponse " << "counter" << "\n";
599 output << "# HELP " << frontsbase << "tcpgaveup " << "Amount of TCP connections terminated after too many attempts to get a connection to the backend" << "\n";
600 output << "# TYPE " << frontsbase << "tcpgaveup " << "counter" << "\n";
601 output << "# HELP " << frontsbase << "tcpclientimeouts " << "Amount of TCP connections terminated by a timeout while reading from the client" << "\n";
602 output << "# TYPE " << frontsbase << "tcpclientimeouts " << "counter" << "\n";
603 output << "# HELP " << frontsbase << "tcpdownstreamtimeouts " << "Amount of TCP connections terminated by a timeout while reading from the backend" << "\n";
604 output << "# TYPE " << frontsbase << "tcpdownstreamtimeouts " << "counter" << "\n";
605 output << "# HELP " << frontsbase << "tcpcurrentconnections " << "Amount of current incoming TCP connections from clients" << "\n";
606 output << "# TYPE " << frontsbase << "tcpcurrentconnections " << "gauge" << "\n";
607 output << "# HELP " << frontsbase << "tcpavgqueriesperconnection " << "The average number of queries per TCP connection" << "\n";
608 output << "# TYPE " << frontsbase << "tcpavgqueriesperconnection " << "gauge" << "\n";
609 output << "# HELP " << frontsbase << "tcpavgconnectionduration " << "The average duration of a TCP connection (ms)" << "\n";
610 output << "# TYPE " << frontsbase << "tcpavgconnectionduration " << "gauge" << "\n";
611 output << "# HELP " << frontsbase << "tlsqueries " << "Number of queries received by dnsdist over TLS, by TLS version" << "\n";
612 output << "# TYPE " << frontsbase << "tlsqueries " << "counter" << "\n";
613 output << "# HELP " << frontsbase << "tlsnewsessions " << "Amount of new TLS sessions negotiated" << "\n";
614 output << "# TYPE " << frontsbase << "tlsnewsessions " << "counter" << "\n";
615 output << "# HELP " << frontsbase << "tlsresumptions " << "Amount of TLS sessions resumed" << "\n";
616 output << "# TYPE " << frontsbase << "tlsresumptions " << "counter" << "\n";
617 output << "# HELP " << frontsbase << "tlsunknownticketkeys " << "Amount of attempts to resume TLS session from an unknown key (possibly expired)" << "\n";
618 output << "# TYPE " << frontsbase << "tlsunknownticketkeys " << "counter" << "\n";
619 output << "# HELP " << frontsbase << "tlsinactiveticketkeys " << "Amount of TLS sessions resumed from an inactive key" << "\n";
620 output << "# TYPE " << frontsbase << "tlsinactiveticketkeys " << "counter" << "\n";
621
622 output << "# HELP " << frontsbase << "tlshandshakefailures " << "Amount of TLS handshake failures" << "\n";
623 output << "# TYPE " << frontsbase << "tlshandshakefailures " << "counter" << "\n";
624
625 std::map<std::string,uint64_t> frontendDuplicates;
626 for (const auto& front : g_frontends) {
627 if (front->udpFD == -1 && front->tcpFD == -1)
628 continue;
629
630 const string frontName = front->local.toString() + ":" + std::to_string(front->local.getPort());
631 const string proto = front->getType();
632 const string fullName = frontName + "_" + proto;
633 uint64_t threadNumber = 0;
634 auto dupPair = frontendDuplicates.insert({fullName, 1});
635 if (!dupPair.second) {
636 threadNumber = dupPair.first->second;
637 ++(dupPair.first->second);
638 }
639 const std::string label = boost::str(boost::format("{frontend=\"%1%\",proto=\"%2%\",thread=\"%3%\"} ")
640 % frontName % proto % threadNumber);
641
642 output << frontsbase << "queries" << label << front->queries.load() << "\n";
643 output << frontsbase << "responses" << label << front->responses.load() << "\n";
644 if (front->isTCP()) {
645 output << frontsbase << "tcpdiedreadingquery" << label << front->tcpDiedReadingQuery.load() << "\n";
646 output << frontsbase << "tcpdiedsendingresponse" << label << front->tcpDiedSendingResponse.load() << "\n";
647 output << frontsbase << "tcpgaveup" << label << front->tcpGaveUp.load() << "\n";
648 output << frontsbase << "tcpclientimeouts" << label << front->tcpClientTimeouts.load() << "\n";
649 output << frontsbase << "tcpdownstreamtimeouts" << label << front->tcpDownstreamTimeouts.load() << "\n";
650 output << frontsbase << "tcpcurrentconnections" << label << front->tcpCurrentConnections.load() << "\n";
651 output << frontsbase << "tcpavgqueriesperconnection" << label << front->tcpAvgQueriesPerConnection.load() << "\n";
652 output << frontsbase << "tcpavgconnectionduration" << label << front->tcpAvgConnectionDuration.load() << "\n";
653 if (front->hasTLS()) {
654 output << frontsbase << "tlsnewsessions" << label << front->tlsNewSessions.load() << "\n";
655 output << frontsbase << "tlsresumptions" << label << front->tlsResumptions.load() << "\n";
656 output << frontsbase << "tlsunknownticketkeys" << label << front->tlsUnknownTicketKey.load() << "\n";
657 output << frontsbase << "tlsinactiveticketkeys" << label << front->tlsInactiveTicketKey.load() << "\n";
658
659 output << frontsbase << "tlsqueries{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",tls=\"tls10\"} " << front->tls10queries.load() << "\n";
660 output << frontsbase << "tlsqueries{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",tls=\"tls11\"} " << front->tls11queries.load() << "\n";
661 output << frontsbase << "tlsqueries{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",tls=\"tls12\"} " << front->tls12queries.load() << "\n";
662 output << frontsbase << "tlsqueries{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",tls=\"tls13\"} " << front->tls13queries.load() << "\n";
663 output << frontsbase << "tlsqueries{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",tls=\"unknown\"} " << front->tlsUnknownqueries.load() << "\n";
664
665 const TLSErrorCounters* errorCounters = nullptr;
666 if (front->tlsFrontend != nullptr) {
667 errorCounters = &front->tlsFrontend->d_tlsCounters;
668 }
669 else if (front->dohFrontend != nullptr) {
670 errorCounters = &front->dohFrontend->d_tlsCounters;
671 }
672
673 if (errorCounters != nullptr) {
674 output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",error=\"dhKeyTooSmall\"} " << errorCounters->d_dhKeyTooSmall << "\n";
675 output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",error=\"inappropriateFallBack\"} " << errorCounters->d_inappropriateFallBack << "\n";
676 output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",error=\"noSharedCipher\"} " << errorCounters->d_noSharedCipher << "\n";
677 output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",error=\"unknownCipherType\"} " << errorCounters->d_unknownCipherType << "\n";
678 output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",error=\"unknownKeyExchangeType\"} " << errorCounters->d_unknownKeyExchangeType << "\n";
679 output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",error=\"unknownProtocol\"} " << errorCounters->d_unknownProtocol << "\n";
680 output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",error=\"unsupportedEC\"} " << errorCounters->d_unsupportedEC << "\n";
681 output << frontsbase << "tlshandshakefailures{frontend=\"" << frontName << "\",proto=\"" << proto << "\",thread=\"" << threadNumber << "\",error=\"unsupportedProtocol{\"} " << errorCounters->d_unsupportedProtocol << "\n";
682 }
683 }
684 }
685 }
686
687 output << "# HELP " << frontsbase << "http_connects " << "Number of DoH TCP connections established to this frontend" << "\n";
688 output << "# TYPE " << frontsbase << "http_connects " << "counter" << "\n";
689
690 output << "# HELP " << frontsbase << "doh_http_method_queries " << "Number of DoH queries received by dnsdist, by HTTP method" << "\n";
691 output << "# TYPE " << frontsbase << "doh_http_method_queries " << "counter" << "\n";
692
693 output << "# HELP " << frontsbase << "doh_http_version_queries " << "Number of DoH queries received by dnsdist, by HTTP version" << "\n";
694 output << "# TYPE " << frontsbase << "doh_http_version_queries " << "counter" << "\n";
695
696 output << "# HELP " << frontsbase << "doh_bad_requests " << "Number of requests that could not be converted to a DNS query" << "\n";
697 output << "# TYPE " << frontsbase << "doh_bad_requests " << "counter" << "\n";
698
699 output << "# HELP " << frontsbase << "doh_responses " << "Number of responses sent, by type" << "\n";
700 output << "# TYPE " << frontsbase << "doh_responses " << "counter" << "\n";
701
702 output << "# HELP " << frontsbase << "doh_version_status_responses " << "Number of requests that could not be converted to a DNS query" << "\n";
703 output << "# TYPE " << frontsbase << "doh_version_status_responses " << "counter" << "\n";
704
705 #ifdef HAVE_DNS_OVER_HTTPS
706 std::map<std::string,uint64_t> dohFrontendDuplicates;
707 for(const auto& doh : g_dohlocals) {
708 const string frontName = doh->d_local.toStringWithPort();
709 uint64_t threadNumber = 0;
710 auto dupPair = frontendDuplicates.insert({frontName, 1});
711 if (!dupPair.second) {
712 threadNumber = dupPair.first->second;
713 ++(dupPair.first->second);
714 }
715 const std::string addrlabel = boost::str(boost::format("frontend=\"%1%\",thread=\"%2%\"") % frontName % threadNumber);
716 const std::string label = "{" + addrlabel + "} ";
717
718 output << frontsbase << "http_connects" << label << doh->d_httpconnects << "\n";
719 output << frontsbase << "doh_http_method_queries{method=\"get\"," << addrlabel << "} " << doh->d_getqueries << "\n";
720 output << frontsbase << "doh_http_method_queries{method=\"post\"," << addrlabel << "} " << doh->d_postqueries << "\n";
721
722 output << frontsbase << "doh_http_version_queries{version=\"1\"," << addrlabel << "} " << doh->d_http1Stats.d_nbQueries << "\n";
723 output << frontsbase << "doh_http_version_queries{version=\"2\"," << addrlabel << "} " << doh->d_http2Stats.d_nbQueries << "\n";
724
725 output << frontsbase << "doh_bad_requests{" << addrlabel << "} " << doh->d_badrequests << "\n";
726
727 output << frontsbase << "doh_responses{type=\"error\"," << addrlabel << "} " << doh->d_errorresponses << "\n";
728 output << frontsbase << "doh_responses{type=\"redirect\"," << addrlabel << "} " << doh->d_redirectresponses << "\n";
729 output << frontsbase << "doh_responses{type=\"valid\"," << addrlabel << "} " << doh->d_validresponses << "\n";
730
731 output << frontsbase << "doh_version_status_responses{httpversion=\"1\",status=\"200\"," << addrlabel << "} " << doh->d_http1Stats.d_nb200Responses << "\n";
732 output << frontsbase << "doh_version_status_responses{httpversion=\"1\",status=\"400\"," << addrlabel << "} " << doh->d_http1Stats.d_nb400Responses << "\n";
733 output << frontsbase << "doh_version_status_responses{httpversion=\"1\",status=\"403\"," << addrlabel << "} " << doh->d_http1Stats.d_nb403Responses << "\n";
734 output << frontsbase << "doh_version_status_responses{httpversion=\"1\",status=\"500\"," << addrlabel << "} " << doh->d_http1Stats.d_nb500Responses << "\n";
735 output << frontsbase << "doh_version_status_responses{httpversion=\"1\",status=\"502\"," << addrlabel << "} " << doh->d_http1Stats.d_nb502Responses << "\n";
736 output << frontsbase << "doh_version_status_responses{httpversion=\"1\",status=\"other\"," << addrlabel << "} " << doh->d_http1Stats.d_nbOtherResponses << "\n";
737 output << frontsbase << "doh_version_status_responses{httpversion=\"2\",status=\"200\"," << addrlabel << "} " << doh->d_http2Stats.d_nb200Responses << "\n";
738 output << frontsbase << "doh_version_status_responses{httpversion=\"2\",status=\"400\"," << addrlabel << "} " << doh->d_http2Stats.d_nb400Responses << "\n";
739 output << frontsbase << "doh_version_status_responses{httpversion=\"2\",status=\"403\"," << addrlabel << "} " << doh->d_http2Stats.d_nb403Responses << "\n";
740 output << frontsbase << "doh_version_status_responses{httpversion=\"2\",status=\"500\"," << addrlabel << "} " << doh->d_http2Stats.d_nb500Responses << "\n";
741 output << frontsbase << "doh_version_status_responses{httpversion=\"2\",status=\"502\"," << addrlabel << "} " << doh->d_http2Stats.d_nb502Responses << "\n";
742 output << frontsbase << "doh_version_status_responses{httpversion=\"2\",status=\"other\"," << addrlabel << "} " << doh->d_http2Stats.d_nbOtherResponses << "\n";
743 }
744 #endif /* HAVE_DNS_OVER_HTTPS */
745
746 auto localPools = g_pools.getLocal();
747 const string cachebase = "dnsdist_pool_";
748 output << "# HELP dnsdist_pool_servers " << "Number of servers in that pool" << "\n";
749 output << "# TYPE dnsdist_pool_servers " << "gauge" << "\n";
750 output << "# HELP dnsdist_pool_active_servers " << "Number of available servers in that pool" << "\n";
751 output << "# TYPE dnsdist_pool_active_servers " << "gauge" << "\n";
752
753 output << "# HELP dnsdist_pool_cache_size " << "Maximum number of entries that this cache can hold" << "\n";
754 output << "# TYPE dnsdist_pool_cache_size " << "gauge" << "\n";
755 output << "# HELP dnsdist_pool_cache_entries " << "Number of entries currently present in that cache" << "\n";
756 output << "# TYPE dnsdist_pool_cache_entries " << "gauge" << "\n";
757 output << "# HELP dnsdist_pool_cache_hits " << "Number of hits from that cache" << "\n";
758 output << "# TYPE dnsdist_pool_cache_hits " << "counter" << "\n";
759 output << "# HELP dnsdist_pool_cache_misses " << "Number of misses from that cache" << "\n";
760 output << "# TYPE dnsdist_pool_cache_misses " << "counter" << "\n";
761 output << "# HELP dnsdist_pool_cache_deferred_inserts " << "Number of insertions into that cache skipped because it was already locked" << "\n";
762 output << "# TYPE dnsdist_pool_cache_deferred_inserts " << "counter" << "\n";
763 output << "# HELP dnsdist_pool_cache_deferred_lookups " << "Number of lookups into that cache skipped because it was already locked" << "\n";
764 output << "# TYPE dnsdist_pool_cache_deferred_lookups " << "counter" << "\n";
765 output << "# HELP dnsdist_pool_cache_lookup_collisions " << "Number of lookups into that cache that triggered a collision (same hash but different entry)" << "\n";
766 output << "# TYPE dnsdist_pool_cache_lookup_collisions " << "counter" << "\n";
767 output << "# HELP dnsdist_pool_cache_insert_collisions " << "Number of insertions into that cache that triggered a collision (same hash but different entry)" << "\n";
768 output << "# TYPE dnsdist_pool_cache_insert_collisions " << "counter" << "\n";
769 output << "# HELP dnsdist_pool_cache_ttl_too_shorts " << "Number of insertions into that cache skipped because the TTL of the answer was not long enough" << "\n";
770 output << "# TYPE dnsdist_pool_cache_ttl_too_shorts " << "counter" << "\n";
771
772 for (const auto& entry : *localPools) {
773 string poolName = entry.first;
774
775 if (poolName.empty()) {
776 poolName = "_default_";
777 }
778 const string label = "{pool=\"" + poolName + "\"}";
779 const std::shared_ptr<ServerPool> pool = entry.second;
780 output << "dnsdist_pool_servers" << label << " " << pool->countServers(false) << "\n";
781 output << "dnsdist_pool_active_servers" << label << " " << pool->countServers(true) << "\n";
782
783 if (pool->packetCache != nullptr) {
784 const auto& cache = pool->packetCache;
785
786 output << cachebase << "cache_size" <<label << " " << cache->getMaxEntries() << "\n";
787 output << cachebase << "cache_entries" <<label << " " << cache->getEntriesCount() << "\n";
788 output << cachebase << "cache_hits" <<label << " " << cache->getHits() << "\n";
789 output << cachebase << "cache_misses" <<label << " " << cache->getMisses() << "\n";
790 output << cachebase << "cache_deferred_inserts" <<label << " " << cache->getDeferredInserts() << "\n";
791 output << cachebase << "cache_deferred_lookups" <<label << " " << cache->getDeferredLookups() << "\n";
792 output << cachebase << "cache_lookup_collisions" <<label << " " << cache->getLookupCollisions() << "\n";
793 output << cachebase << "cache_insert_collisions" <<label << " " << cache->getInsertCollisions() << "\n";
794 output << cachebase << "cache_ttl_too_shorts" <<label << " " << cache->getTTLTooShorts() << "\n";
795 }
796 }
797
798 resp.body = output.str();
799 resp.headers["Content-Type"] = "text/plain";
800 }
801
802 else if(req.url.path=="/api/v1/servers/localhost") {
803 handleCORS(req, resp);
804 resp.status=200;
805
806 Json::array servers;
807 auto localServers = g_dstates.getLocal();
808 int num=0;
809 for(const auto& a : *localServers) {
810 string status;
811 if(a->availability == DownstreamState::Availability::Up)
812 status = "UP";
813 else if(a->availability == DownstreamState::Availability::Down)
814 status = "DOWN";
815 else
816 status = (a->upStatus ? "up" : "down");
817
818 Json::array pools;
819 for(const auto& p: a->pools)
820 pools.push_back(p);
821
822 Json::object server{
823 {"id", num++},
824 {"name", a->getName()},
825 {"address", a->remote.toStringWithPort()},
826 {"state", status},
827 {"qps", (double)a->queryLoad},
828 {"qpsLimit", (double)a->qps.getRate()},
829 {"outstanding", (double)a->outstanding},
830 {"reuseds", (double)a->reuseds},
831 {"weight", (double)a->weight},
832 {"order", (double)a->order},
833 {"pools", pools},
834 {"latency", (double)(a->latencyUsec/1000.0)},
835 {"queries", (double)a->queries},
836 {"responses", (double)a->responses},
837 {"sendErrors", (double)a->sendErrors},
838 {"tcpDiedSendingQuery", (double)a->tcpDiedSendingQuery},
839 {"tcpDiedReadingResponse", (double)a->tcpDiedReadingResponse},
840 {"tcpGaveUp", (double)a->tcpGaveUp},
841 {"tcpReadTimeouts", (double)a->tcpReadTimeouts},
842 {"tcpWriteTimeouts", (double)a->tcpWriteTimeouts},
843 {"tcpCurrentConnections", (double)a->tcpCurrentConnections},
844 {"tcpAvgQueriesPerConnection", (double)a->tcpAvgQueriesPerConnection},
845 {"tcpAvgConnectionDuration", (double)a->tcpAvgConnectionDuration},
846 {"dropRate", (double)a->dropRate}
847 };
848
849 /* sending a latency for a DOWN server doesn't make sense */
850 if (a->availability == DownstreamState::Availability::Down) {
851 server["latency"] = nullptr;
852 }
853
854 servers.push_back(server);
855 }
856
857 Json::array frontends;
858 num=0;
859 for(const auto& front : g_frontends) {
860 if (front->udpFD == -1 && front->tcpFD == -1)
861 continue;
862 Json::object frontend{
863 { "id", num++ },
864 { "address", front->local.toStringWithPort() },
865 { "udp", front->udpFD >= 0 },
866 { "tcp", front->tcpFD >= 0 },
867 { "type", front->getType() },
868 { "queries", (double) front->queries.load() },
869 { "responses", (double) front->responses.load() },
870 { "tcpDiedReadingQuery", (double) front->tcpDiedReadingQuery.load() },
871 { "tcpDiedSendingResponse", (double) front->tcpDiedSendingResponse.load() },
872 { "tcpGaveUp", (double) front->tcpGaveUp.load() },
873 { "tcpClientTimeouts", (double) front->tcpClientTimeouts },
874 { "tcpDownstreamTimeouts", (double) front->tcpDownstreamTimeouts },
875 { "tcpCurrentConnections", (double) front->tcpCurrentConnections },
876 { "tcpAvgQueriesPerConnection", (double) front->tcpAvgQueriesPerConnection },
877 { "tcpAvgConnectionDuration", (double) front->tcpAvgConnectionDuration },
878 { "tlsNewSessions", (double) front->tlsNewSessions },
879 { "tlsResumptions", (double) front->tlsResumptions },
880 { "tlsUnknownTicketKey", (double) front->tlsUnknownTicketKey },
881 { "tlsInactiveTicketKey", (double) front->tlsInactiveTicketKey },
882 { "tls10Queries", (double) front->tls10queries },
883 { "tls11Queries", (double) front->tls11queries },
884 { "tls12Queries", (double) front->tls12queries },
885 { "tls13Queries", (double) front->tls13queries },
886 { "tlsUnknownQueries", (double) front->tlsUnknownqueries },
887 };
888 const TLSErrorCounters* errorCounters = nullptr;
889 if (front->tlsFrontend != nullptr) {
890 errorCounters = &front->tlsFrontend->d_tlsCounters;
891 }
892 else if (front->dohFrontend != nullptr) {
893 errorCounters = &front->dohFrontend->d_tlsCounters;
894 }
895 if (errorCounters != nullptr) {
896 frontend["tlsHandshakeFailuresDHKeyTooSmall"] = (double)errorCounters->d_dhKeyTooSmall;
897 frontend["tlsHandshakeFailuresInappropriateFallBack"] = (double)errorCounters->d_inappropriateFallBack;
898 frontend["tlsHandshakeFailuresNoSharedCipher"] = (double)errorCounters->d_noSharedCipher;
899 frontend["tlsHandshakeFailuresUnknownCipher"] = (double)errorCounters->d_unknownCipherType;
900 frontend["tlsHandshakeFailuresUnknownKeyExchangeType"] = (double)errorCounters->d_unknownKeyExchangeType;
901 frontend["tlsHandshakeFailuresUnknownProtocol"] = (double)errorCounters->d_unknownProtocol;
902 frontend["tlsHandshakeFailuresUnsupportedEC"] = (double)errorCounters->d_unsupportedEC;
903 frontend["tlsHandshakeFailuresUnsupportedProtocol"] = (double)errorCounters->d_unsupportedProtocol;
904 }
905 frontends.push_back(frontend);
906 }
907
908 Json::array dohs;
909 #ifdef HAVE_DNS_OVER_HTTPS
910 {
911 num = 0;
912 for(const auto& doh : g_dohlocals) {
913 Json::object obj{
914 { "id", num++ },
915 { "address", doh->d_local.toStringWithPort() },
916 { "http-connects", (double) doh->d_httpconnects },
917 { "http1-queries", (double) doh->d_http1Stats.d_nbQueries },
918 { "http2-queries", (double) doh->d_http2Stats.d_nbQueries },
919 { "http1-200-responses", (double) doh->d_http1Stats.d_nb200Responses },
920 { "http2-200-responses", (double) doh->d_http2Stats.d_nb200Responses },
921 { "http1-400-responses", (double) doh->d_http1Stats.d_nb400Responses },
922 { "http2-400-responses", (double) doh->d_http2Stats.d_nb400Responses },
923 { "http1-403-responses", (double) doh->d_http1Stats.d_nb403Responses },
924 { "http2-403-responses", (double) doh->d_http2Stats.d_nb403Responses },
925 { "http1-500-responses", (double) doh->d_http1Stats.d_nb500Responses },
926 { "http2-500-responses", (double) doh->d_http2Stats.d_nb500Responses },
927 { "http1-502-responses", (double) doh->d_http1Stats.d_nb502Responses },
928 { "http2-502-responses", (double) doh->d_http2Stats.d_nb502Responses },
929 { "http1-other-responses", (double) doh->d_http1Stats.d_nbOtherResponses },
930 { "http2-other-responses", (double) doh->d_http2Stats.d_nbOtherResponses },
931 { "get-queries", (double) doh->d_getqueries },
932 { "post-queries", (double) doh->d_postqueries },
933 { "bad-requests", (double) doh->d_badrequests },
934 { "error-responses", (double) doh->d_errorresponses },
935 { "redirect-responses", (double) doh->d_redirectresponses },
936 { "valid-responses", (double) doh->d_validresponses }
937 };
938 dohs.push_back(obj);
939 }
940 }
941 #endif /* HAVE_DNS_OVER_HTTPS */
942
943 Json::array pools;
944 auto localPools = g_pools.getLocal();
945 num=0;
946 for(const auto& pool : *localPools) {
947 const auto& cache = pool.second->packetCache;
948 Json::object entry {
949 { "id", num++ },
950 { "name", pool.first },
951 { "serversCount", (double) pool.second->countServers(false) },
952 { "cacheSize", (double) (cache ? cache->getMaxEntries() : 0) },
953 { "cacheEntries", (double) (cache ? cache->getEntriesCount() : 0) },
954 { "cacheHits", (double) (cache ? cache->getHits() : 0) },
955 { "cacheMisses", (double) (cache ? cache->getMisses() : 0) },
956 { "cacheDeferredInserts", (double) (cache ? cache->getDeferredInserts() : 0) },
957 { "cacheDeferredLookups", (double) (cache ? cache->getDeferredLookups() : 0) },
958 { "cacheLookupCollisions", (double) (cache ? cache->getLookupCollisions() : 0) },
959 { "cacheInsertCollisions", (double) (cache ? cache->getInsertCollisions() : 0) },
960 { "cacheTTLTooShorts", (double) (cache ? cache->getTTLTooShorts() : 0) }
961 };
962 pools.push_back(entry);
963 }
964
965 Json::array rules;
966 auto localRules = g_rulactions.getLocal();
967 num=0;
968 for(const auto& a : *localRules) {
969 Json::object rule{
970 {"id", num++},
971 {"creationOrder", (double)a.d_creationOrder},
972 {"uuid", boost::uuids::to_string(a.d_id)},
973 {"matches", (double)a.d_rule->d_matches},
974 {"rule", a.d_rule->toString()},
975 {"action", a.d_action->toString()},
976 {"action-stats", a.d_action->getStats()}
977 };
978 rules.push_back(rule);
979 }
980
981 auto responseRules = someResponseRulesToJson(&g_resprulactions);
982 auto cacheHitResponseRules = someResponseRulesToJson(&g_cachehitresprulactions);
983 auto selfAnsweredResponseRules = someResponseRulesToJson(&g_selfansweredresprulactions);
984
985 string acl;
986
987 vector<string> vec;
988 g_ACL.getLocal()->toStringVector(&vec);
989
990 for(const auto& s : vec) {
991 if(!acl.empty()) acl += ", ";
992 acl+=s;
993 }
994 string localaddressesStr;
995 std::set<std::string> localaddresses;
996 for(const auto& front : g_frontends) {
997 localaddresses.insert(front->local.toStringWithPort());
998 }
999 for (const auto& addr : localaddresses) {
1000 if (!localaddressesStr.empty()) {
1001 localaddressesStr += ", ";
1002 }
1003 localaddressesStr += addr;
1004 }
1005
1006 Json my_json = Json::object {
1007 { "daemon_type", "dnsdist" },
1008 { "version", VERSION},
1009 { "servers", servers},
1010 { "frontends", frontends },
1011 { "pools", pools },
1012 { "rules", rules},
1013 { "response-rules", responseRules},
1014 { "cache-hit-response-rules", cacheHitResponseRules},
1015 { "self-answered-response-rules", selfAnsweredResponseRules},
1016 { "acl", acl},
1017 { "local", localaddressesStr},
1018 { "dohFrontends", dohs }
1019 };
1020 resp.headers["Content-Type"] = "application/json";
1021 resp.body=my_json.dump();
1022 }
1023 else if(req.url.path=="/api/v1/servers/localhost/statistics") {
1024 handleCORS(req, resp);
1025 resp.status=200;
1026
1027 Json::array doc;
1028 for(const auto& item : g_stats.entries) {
1029 if (item.first == "special-memory-usage")
1030 continue; // Too expensive for get-all
1031
1032 if(const auto& val = boost::get<DNSDistStats::stat_t*>(&item.second)) {
1033 doc.push_back(Json::object {
1034 { "type", "StatisticItem" },
1035 { "name", item.first },
1036 { "value", (double)(*val)->load() }
1037 });
1038 }
1039 else if (const auto& dval = boost::get<double*>(&item.second)) {
1040 doc.push_back(Json::object {
1041 { "type", "StatisticItem" },
1042 { "name", item.first },
1043 { "value", (**dval) }
1044 });
1045 }
1046 else {
1047 doc.push_back(Json::object {
1048 { "type", "StatisticItem" },
1049 { "name", item.first },
1050 { "value", (double)(*boost::get<DNSDistStats::statfunction_t>(&item.second))(item.first) }
1051 });
1052 }
1053 }
1054 Json my_json = doc;
1055 resp.body=my_json.dump();
1056 resp.headers["Content-Type"] = "application/json";
1057 }
1058 else if(req.url.path=="/api/v1/servers/localhost/config") {
1059 handleCORS(req, resp);
1060 resp.status=200;
1061
1062 Json::array doc;
1063 typedef boost::variant<bool, double, std::string> configentry_t;
1064 std::vector<std::pair<std::string, configentry_t> > configEntries {
1065 { "acl", g_ACL.getLocal()->toString() },
1066 { "allow-empty-response", g_allowEmptyResponse },
1067 { "control-socket", g_serverControl.toStringWithPort() },
1068 { "ecs-override", g_ECSOverride },
1069 { "ecs-source-prefix-v4", (double) g_ECSSourcePrefixV4 },
1070 { "ecs-source-prefix-v6", (double) g_ECSSourcePrefixV6 },
1071 { "fixup-case", g_fixupCase },
1072 { "max-outstanding", (double) g_maxOutstanding },
1073 { "server-policy", g_policy.getLocal()->name },
1074 { "stale-cache-entries-ttl", (double) g_staleCacheEntriesTTL },
1075 { "tcp-recv-timeout", (double) g_tcpRecvTimeout },
1076 { "tcp-send-timeout", (double) g_tcpSendTimeout },
1077 { "truncate-tc", g_truncateTC },
1078 { "verbose", g_verbose },
1079 { "verbose-health-checks", g_verboseHealthChecks }
1080 };
1081 for(const auto& item : configEntries) {
1082 if (const auto& bval = boost::get<bool>(&item.second)) {
1083 doc.push_back(Json::object {
1084 { "type", "ConfigSetting" },
1085 { "name", item.first },
1086 { "value", *bval }
1087 });
1088 }
1089 else if (const auto& sval = boost::get<string>(&item.second)) {
1090 doc.push_back(Json::object {
1091 { "type", "ConfigSetting" },
1092 { "name", item.first },
1093 { "value", *sval }
1094 });
1095 }
1096 else if (const auto& dval = boost::get<double>(&item.second)) {
1097 doc.push_back(Json::object {
1098 { "type", "ConfigSetting" },
1099 { "name", item.first },
1100 { "value", *dval }
1101 });
1102 }
1103 }
1104 Json my_json = doc;
1105 resp.body=my_json.dump();
1106 resp.headers["Content-Type"] = "application/json";
1107 }
1108 else if(req.url.path=="/api/v1/servers/localhost/config/allow-from") {
1109 handleCORS(req, resp);
1110
1111 resp.headers["Content-Type"] = "application/json";
1112 resp.status=200;
1113
1114 if (req.method == "PUT") {
1115 std::string err;
1116 Json doc = Json::parse(req.body, err);
1117
1118 if (!doc.is_null()) {
1119 NetmaskGroup nmg;
1120 auto aclList = doc["value"];
1121 if (aclList.is_array()) {
1122
1123 for (auto value : aclList.array_items()) {
1124 try {
1125 nmg.addMask(value.string_value());
1126 } catch (NetmaskException &e) {
1127 resp.status = 400;
1128 break;
1129 }
1130 }
1131
1132 if (resp.status == 200) {
1133 infolog("Updating the ACL via the API to %s", nmg.toString());
1134 g_ACL.setState(nmg);
1135 apiSaveACL(nmg);
1136 }
1137 }
1138 else {
1139 resp.status = 400;
1140 }
1141 }
1142 else {
1143 resp.status = 400;
1144 }
1145 }
1146 if (resp.status == 200) {
1147 Json::array acl;
1148 vector<string> vec;
1149 g_ACL.getLocal()->toStringVector(&vec);
1150
1151 for(const auto& s : vec) {
1152 acl.push_back(s);
1153 }
1154
1155 Json::object obj{
1156 { "type", "ConfigSetting" },
1157 { "name", "allow-from" },
1158 { "value", acl }
1159 };
1160 Json my_json = obj;
1161 resp.body=my_json.dump();
1162 }
1163 }
1164 else if(!req.url.path.empty() && g_urlmap.count(req.url.path.c_str()+1)) {
1165 resp.body.assign(g_urlmap[req.url.path.c_str()+1]);
1166 vector<string> parts;
1167 stringtok(parts, req.url.path, ".");
1168 if(parts.back() == "html")
1169 resp.headers["Content-Type"] = "text/html" + charset;
1170 else if(parts.back() == "css")
1171 resp.headers["Content-Type"] = "text/css" + charset;
1172 else if(parts.back() == "js")
1173 resp.headers["Content-Type"] = "application/javascript" + charset;
1174 else if(parts.back() == "png")
1175 resp.headers["Content-Type"] = "image/png";
1176 resp.status=200;
1177 }
1178 else if(req.url.path=="/") {
1179 resp.body.assign(g_urlmap["index.html"]);
1180 resp.headers["Content-Type"] = "text/html" + charset;
1181 resp.status=200;
1182 }
1183 else {
1184 // cerr<<"404 for: "<<req.url.path<<endl;
1185 resp.status=404;
1186 }
1187
1188 std::ostringstream ofs;
1189 ofs << resp;
1190 string done;
1191 done=ofs.str();
1192 writen2(sock, done.c_str(), done.size());
1193
1194 close(sock);
1195 sock = -1;
1196 }
1197 catch(const YaHTTP::ParseError& e) {
1198 vinfolog("Webserver thread died with parse error exception while processing a request from %s: %s", remote.toStringWithPort(), e.what());
1199 close(sock);
1200 }
1201 catch(const std::exception& e) {
1202 errlog("Webserver thread died with exception while processing a request from %s: %s", remote.toStringWithPort(), e.what());
1203 close(sock);
1204 }
1205 catch(...) {
1206 errlog("Webserver thread died with exception while processing a request from %s", remote.toStringWithPort());
1207 close(sock);
1208 }
1209 }
1210
1211 void setWebserverAPIKey(const boost::optional<std::string> apiKey)
1212 {
1213 std::lock_guard<std::mutex> lock(g_webserverConfig.lock);
1214
1215 if (apiKey) {
1216 g_webserverConfig.apiKey = *apiKey;
1217 } else {
1218 g_webserverConfig.apiKey.clear();
1219 }
1220 }
1221
1222 void setWebserverPassword(const std::string& password)
1223 {
1224 std::lock_guard<std::mutex> lock(g_webserverConfig.lock);
1225
1226 g_webserverConfig.password = password;
1227 }
1228
1229 void setWebserverCustomHeaders(const boost::optional<std::map<std::string, std::string> > customHeaders)
1230 {
1231 std::lock_guard<std::mutex> lock(g_webserverConfig.lock);
1232
1233 g_webserverConfig.customHeaders = customHeaders;
1234 }
1235
1236 void dnsdistWebserverThread(int sock, const ComboAddress& local)
1237 {
1238 setThreadName("dnsdist/webserv");
1239 warnlog("Webserver launched on %s", local.toStringWithPort());
1240 for(;;) {
1241 try {
1242 ComboAddress remote(local);
1243 int fd = SAccept(sock, remote);
1244 vinfolog("Got connection from %s", remote.toStringWithPort());
1245 std::thread t(connectionThread, fd, remote);
1246 t.detach();
1247 }
1248 catch(std::exception& e) {
1249 errlog("Had an error accepting new webserver connection: %s", e.what());
1250 }
1251 }
1252 }