]>
Commit | Line | Data |
---|---|---|
12471842 PL |
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 | */ | |
50bed881 | 22 | #include "dnsdist.hh" |
dd9c8246 | 23 | #include "dnsdist-healthchecks.hh" |
0d394f35 | 24 | #include "dnsdist-prometheus.hh" |
dd9c8246 | 25 | |
50bed881 | 26 | #include "sstuff.hh" |
27 | #include "ext/json11/json11.hpp" | |
28 | #include "ext/incbin/incbin.h" | |
29 | #include "dolog.hh" | |
30 | #include <thread> | |
519f5484 | 31 | #include "threadname.hh" |
50bed881 | 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" | |
85c7ca75 | 40 | #include "gettime.hh" |
76025fec | 41 | #include <boost/format.hpp> |
50bed881 | 42 | |
56d68fad | 43 | bool g_apiReadWrite{false}; |
80dbd7d2 | 44 | WebserverConfig g_webserverConfig; |
56d68fad | 45 | std::string g_apiConfigDirectory; |
0d394f35 RG |
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")}, | |
c46df0ca | 83 | { "cpu-iowait", MetricDefinition(PrometheusMetricType::counter, "Time waiting for I/O to complete by the whole system, in units of USER_HZ")}, |
0d394f35 | 84 | { "cpu-user-msec", MetricDefinition(PrometheusMetricType::counter, "Milliseconds spent by dnsdist in the user state")}, |
c46df0ca | 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")}, |
0d394f35 RG |
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 | }; | |
56d68fad RG |
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; | |
2d29e6b7 | 124 | nmg.toStringVector(&vec); |
56d68fad RG |
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 | } | |
50bed881 | 137 | |
55afa518 | 138 | static bool checkAPIKey(const YaHTTP::Request& req, const string& expectedApiKey) |
50bed881 | 139 | { |
55afa518 RG |
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); | |
50bed881 | 160 | |
161 | string plain; | |
162 | B64Decode(cookie, plain); | |
163 | ||
164 | vector<string> cparts; | |
165 | stringtok(cparts, plain, ":"); | |
166 | ||
55afa518 RG |
167 | if (cparts.size() == 2) { |
168 | return cparts[1] == expected_password; | |
169 | } | |
50bed881 | 170 | } |
55afa518 RG |
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 | { | |
37a5c2d5 | 187 | return req.url.path == "/jsonstat" || req.url.path == "/metrics"; |
55afa518 RG |
188 | } |
189 | ||
80dbd7d2 | 190 | static bool compareAuthorization(const YaHTTP::Request& req) |
55afa518 | 191 | { |
80dbd7d2 CHB |
192 | std::lock_guard<std::mutex> lock(g_webserverConfig.lock); |
193 | ||
55afa518 RG |
194 | if (isAnAPIRequest(req)) { |
195 | /* Access to the API requires a valid API key */ | |
80dbd7d2 | 196 | if (checkAPIKey(req, g_webserverConfig.apiKey)) { |
55afa518 | 197 | return true; |
87893e08 | 198 | } |
55afa518 | 199 | |
80dbd7d2 | 200 | return isAnAPIRequestAllowedWithWebAuth(req) && checkWebPassword(req, g_webserverConfig.password); |
55afa518 RG |
201 | } |
202 | ||
203 | if (isAStatsRequest(req)) { | |
204 | /* Access to the stats is allowed for both API and Web users */ | |
80dbd7d2 | 205 | return checkAPIKey(req, g_webserverConfig.apiKey) || checkWebPassword(req, g_webserverConfig.password); |
87893e08 | 206 | } |
55afa518 | 207 | |
80dbd7d2 | 208 | return checkWebPassword(req, g_webserverConfig.password); |
50bed881 | 209 | } |
210 | ||
56d68fad RG |
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 | ||
55afa518 | 224 | static void handleCORS(const YaHTTP::Request& req, YaHTTP::Response& resp) |
5387cc78 | 225 | { |
55afa518 | 226 | const auto origin = req.headers.find("Origin"); |
5387cc78 RG |
227 | if (origin != req.headers.end()) { |
228 | if (req.method == "OPTIONS") { | |
229 | /* Pre-flight request */ | |
56d68fad RG |
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 | } | |
87893e08 | 236 | resp.headers["Access-Control-Allow-Headers"] = "Authorization, X-API-Key"; |
5387cc78 RG |
237 | } |
238 | ||
239 | resp.headers["Access-Control-Allow-Origin"] = origin->second; | |
55afa518 RG |
240 | |
241 | if (isAStatsRequest(req) || isAnAPIRequestAllowedWithWebAuth(req)) { | |
242 | resp.headers["Access-Control-Allow-Credentials"] = "true"; | |
243 | } | |
5387cc78 RG |
244 | } |
245 | } | |
50bed881 | 246 | |
002decab RG |
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 | ||
d18eab67 CH |
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; | |
a9c2e4ab RG |
286 | auto localResponseRules = someResponseRules->getLocal(); |
287 | for(const auto& a : *localResponseRules) { | |
d18eab67 CH |
288 | Json::object rule{ |
289 | {"id", num++}, | |
f8a222ac | 290 | {"creationOrder", (double)a.d_creationOrder}, |
d18eab67 CH |
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 | ||
80dbd7d2 | 301 | static void connectionThread(int sock, ComboAddress remote) |
50bed881 | 302 | { |
519f5484 | 303 | setThreadName("dnsdist/webConn"); |
77c9bc9a | 304 | |
50bed881 | 305 | using namespace json11; |
fb7f8ec3 | 306 | vinfolog("Webserver handling connection from %s", remote.toStringWithPort()); |
56d68fad | 307 | |
438a189b | 308 | try { |
56d68fad | 309 | YaHTTP::AsyncRequestLoader yarl; |
438a189b | 310 | YaHTTP::Request req; |
56d68fad RG |
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(); | |
50bed881 | 327 | |
438a189b | 328 | string command=req.getvars["command"]; |
50bed881 | 329 | |
438a189b | 330 | req.getvars.erase("_"); // jQuery cache buster |
50bed881 | 331 | |
e3d76be2 RG |
332 | YaHTTP::Response resp; |
333 | resp.version = req.version; | |
c8c1a4fc | 334 | const string charset = "; charset=utf-8"; |
002decab | 335 | |
80dbd7d2 CHB |
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 | } | |
00b29455 CHB |
342 | /* indicate that the connection will be closed after completion of the response */ |
343 | resp.headers["Connection"] = "close"; | |
002decab | 344 | |
87893e08 RG |
345 | /* no need to send back the API key if any */ |
346 | resp.headers.erase("X-API-Key"); | |
50bed881 | 347 | |
5387cc78 RG |
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 | } | |
80dbd7d2 | 353 | else if (!compareAuthorization(req)) { |
cc55a8f2 JB |
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()); | |
438a189b | 357 | resp.status=401; |
358 | resp.body="<h1>Unauthorized</h1>"; | |
359 | resp.headers["WWW-Authenticate"] = "basic realm=\"PowerDNS\""; | |
50bed881 | 360 | |
50bed881 | 361 | } |
56d68fad | 362 | else if(!isMethodAllowed(req)) { |
5387cc78 RG |
363 | resp.status=405; |
364 | } | |
365 | else if(req.url.path=="/jsonstat") { | |
366 | handleCORS(req, resp); | |
438a189b | 367 | resp.status=200; |
d745cd6f | 368 | |
5387cc78 RG |
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) { | |
330dcb5c OM |
379 | if (e.first == "special-memory-usage") |
380 | continue; // Too expensive for get-all | |
5387cc78 | 381 | if(const auto& val = boost::get<DNSDistStats::stat_t*>(&e.second)) |
ca12836d | 382 | obj.insert({e.first, (double)(*val)->load()}); |
af619119 RG |
383 | else if (const auto& dval = boost::get<double*>(&e.second)) |
384 | obj.insert({e.first, (**dval)}); | |
5387cc78 | 385 | else |
778fe0a8 | 386 | obj.insert({e.first, (double)(*boost::get<DNSDistStats::statfunction_t>(&e.second))(e.first)}); |
5387cc78 RG |
387 | } |
388 | Json my_json = obj; | |
389 | resp.body=my_json.dump(); | |
5d1c98df | 390 | resp.headers["Content-Type"] = "application/json"; |
d745cd6f | 391 | } |
5387cc78 RG |
392 | else if(command=="dynblocklist") { |
393 | Json::object obj; | |
a9c2e4ab | 394 | auto nmg = g_dynblockNMG.getLocal(); |
5387cc78 | 395 | struct timespec now; |
85c7ca75 | 396 | gettime(&now); |
a9c2e4ab | 397 | for(const auto& e: *nmg) { |
7c888097 | 398 | if(now < e.second.until ) { |
8429ad04 | 399 | Json::object thing{ |
7c888097 SB |
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 } | |
8429ad04 | 405 | }; |
7c888097 | 406 | obj.insert({e.first.toString(), thing}); |
5387cc78 RG |
407 | } |
408 | } | |
0b71b874 | 409 | |
a9c2e4ab RG |
410 | auto smt = g_dynblockSMT.getLocal(); |
411 | smt->visit([&now,&obj](const SuffixMatchTree<DynBlock>& node) { | |
0b71b874 | 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(); | |
477c86a0 RG |
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}, | |
693f7eba | 420 | {"action", DNSAction::typeToString(node.d_value.action != DNSAction::Action::None ? node.d_value.action : g_dynBlockAction) } |
477c86a0 | 421 | }; |
0b71b874 | 422 | obj.insert({dom, thing}); |
423 | } | |
424 | }); | |
425 | ||
426 | ||
427 | ||
8429ad04 RG |
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 */ | |
5387cc78 RG |
449 | Json my_json = obj; |
450 | resp.body=my_json.dump(); | |
5d1c98df | 451 | resp.headers["Content-Type"] = "application/json"; |
5387cc78 RG |
452 | } |
453 | else { | |
454 | resp.status=404; | |
7be71139 | 455 | } |
7be71139 | 456 | } |
37a5c2d5 | 457 | else if (req.url.path == "/metrics") { |
d18e3070 | 458 | handleCORS(req, resp); |
37a5c2d5 | 459 | resp.status = 200; |
d18e3070 | 460 | |
37a5c2d5 | 461 | std::ostringstream output; |
d8923d3b | 462 | static const std::set<std::string> metricBlacklist = { "latency-count", "latency-sum" }; |
37a5c2d5 | 463 | for (const auto& e : g_stats.entries) { |
330dcb5c OM |
464 | if (e.first == "special-memory-usage") |
465 | continue; // Too expensive for get-all | |
37a5c2d5 PO |
466 | std::string metricName = std::get<0>(e); |
467 | ||
468 | // Prometheus suggest using '_' instead of '-' | |
bead1c22 | 469 | std::string prometheusMetricName = "dnsdist_" + boost::replace_all_copy(metricName, "-", "_"); |
d8923d3b RG |
470 | if (metricBlacklist.count(metricName) != 0) { |
471 | continue; | |
472 | } | |
37a5c2d5 | 473 | |
80dbd7d2 | 474 | MetricDefinition metricDetails; |
0d394f35 | 475 | if (!s_metricDefinitions.getMetricDetails(metricName, metricDetails)) { |
b5e27ae4 | 476 | vinfolog("Do not have metric details for %s", metricName); |
37a5c2d5 PO |
477 | continue; |
478 | } | |
d18e3070 | 479 | |
0d394f35 | 480 | std::string prometheusTypeName = s_metricDefinitions.getPrometheusStringMetricType(metricDetails.prometheusType); |
2e567c94 PO |
481 | |
482 | if (prometheusTypeName == "") { | |
483 | vinfolog("Unknown Prometheus type for %s", metricName); | |
484 | continue; | |
485 | } | |
486 | ||
d18e3070 | 487 | // for these we have the help and types encoded in the sources: |
37a5c2d5 | 488 | output << "# HELP " << prometheusMetricName << " " << metricDetails.description << "\n"; |
2e567c94 | 489 | output << "# TYPE " << prometheusMetricName << " " << prometheusTypeName << "\n"; |
37a5c2d5 PO |
490 | output << prometheusMetricName << " "; |
491 | ||
492 | if (const auto& val = boost::get<DNSDistStats::stat_t*>(&std::get<1>(e))) | |
493 | output << (*val)->load(); | |
d18e3070 | 494 | else if (const auto& dval = boost::get<double*>(&std::get<1>(e))) |
37a5c2d5 | 495 | output << **dval; |
d18e3070 | 496 | else |
37a5c2d5 | 497 | output << (*boost::get<DNSDistStats::statfunction_t>(&std::get<1>(e)))(std::get<0>(e)); |
80dbd7d2 | 498 | |
37a5c2d5 | 499 | output << "\n"; |
d18e3070 | 500 | } |
37a5c2d5 | 501 | |
eb0335ff MC |
502 | // Latency histogram buckets |
503 | output << "# HELP dnsdist_latency Histogram of responses by latency\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"; | |
d8923d3b RG |
517 | output << "dnsdist_latency_sum " << g_stats.latencySum << "\n"; |
518 | output << "dnsdist_latency_count " << getLatencyCount(std::string()) << "\n"; | |
eb0335ff | 519 | |
6141572b | 520 | auto states = g_dstates.getLocal(); |
d37db88f | 521 | const string statesbase = "dnsdist_server_"; |
e7fe227b | 522 | |
c41bc4e9 RG |
523 | output << "# HELP " << statesbase << "status " << "Whether this backend is up (1) or down (0)" << "\n"; |
524 | output << "# TYPE " << statesbase << "status " << "gauge" << "\n"; | |
a6e9e107 RG |
525 | output << "# HELP " << statesbase << "queries " << "Amount of queries relayed to server" << "\n"; |
526 | output << "# TYPE " << statesbase << "queries " << "counter" << "\n"; | |
7fc95193 RG |
527 | output << "# HELP " << statesbase << "responses " << "Amount of responses received from this server" << "\n"; |
528 | output << "# TYPE " << statesbase << "responses " << "counter" << "\n"; | |
a6e9e107 RG |
529 | output << "# HELP " << statesbase << "drops " << "Amount of queries not answered by server" << "\n"; |
530 | output << "# TYPE " << statesbase << "drops " << "counter" << "\n"; | |
c8464367 | 531 | output << "# HELP " << statesbase << "latency " << "Server's latency when answering questions in milliseconds" << "\n"; |
a6e9e107 | 532 | output << "# TYPE " << statesbase << "latency " << "gauge" << "\n"; |
c41bc4e9 | 533 | output << "# HELP " << statesbase << "senderrors " << "Total number of OS send errors while relaying queries" << "\n"; |
a6e9e107 RG |
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"; | |
cff9aa03 RG |
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"; | |
80dbd7d2 | 557 | |
6141572b | 558 | for (const auto& state : *states) { |
37a5c2d5 | 559 | string serverName; |
80dbd7d2 | 560 | |
be05aa91 | 561 | if (state->getName().empty()) |
47be7d7c | 562 | serverName = state->remote.toStringWithPort(); |
37a5c2d5 PO |
563 | else |
564 | serverName = state->getName(); | |
565 | ||
d18e3070 | 566 | boost::replace_all(serverName, ".", "_"); |
37a5c2d5 | 567 | |
76025fec PO |
568 | const std::string label = boost::str(boost::format("{server=\"%1%\",address=\"%2%\"}") |
569 | % serverName % state->remote.toStringWithPort()); | |
570 | ||
c41bc4e9 | 571 | output << statesbase << "status" << label << " " << (state->isUp() ? "1" : "0") << "\n"; |
cff9aa03 | 572 | output << statesbase << "queries" << label << " " << state->queries.load() << "\n"; |
7fc95193 | 573 | output << statesbase << "responses" << label << " " << state->responses.load() << "\n"; |
cff9aa03 RG |
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"; | |
d18e3070 | 588 | } |
37a5c2d5 | 589 | |
5bbcbea0 RG |
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"; | |
7fc95193 RG |
593 | output << "# HELP " << frontsbase << "responses " << "Amount of responses sent by this frontend" << "\n"; |
594 | output << "# TYPE " << frontsbase << "responses " << "counter" << "\n"; | |
5bbcbea0 RG |
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"; | |
c72ddfcf | 599 | output << "# HELP " << frontsbase << "tcpgaveup " << "Amount of TCP connections terminated after too many attempts to get a connection to the backend" << "\n"; |
5bbcbea0 RG |
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"; | |
b53e1663 RG |
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"; | |
5bbcbea0 RG |
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"; | |
b608e6c6 RG |
611 | output << "# HELP " << frontsbase << "tlsqueries " << "Number of queries received by dnsdist over TLS, by TLS version" << "\n"; |
612 | output << "# TYPE " << frontsbase << "tlsqueries " << "counter" << "\n"; | |
846b63bb RG |
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"; | |
b608e6c6 RG |
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"; | |
5bbcbea0 | 621 | |
f34fdcc5 RG |
622 | output << "# HELP " << frontsbase << "tlshandshakefailures " << "Amount of TLS handshake failures" << "\n"; |
623 | output << "# TYPE " << frontsbase << "tlshandshakefailures " << "counter" << "\n"; | |
624 | ||
a8b5b7a7 | 625 | std::map<std::string,uint64_t> frontendDuplicates; |
37a5c2d5 | 626 | for (const auto& front : g_frontends) { |
d18e3070 PO |
627 | if (front->udpFD == -1 && front->tcpFD == -1) |
628 | continue; | |
629 | ||
58aa4bc7 | 630 | const string frontName = front->local.toString() + ":" + std::to_string(front->local.getPort()); |
5bbcbea0 | 631 | const string proto = front->getType(); |
58aa4bc7 RG |
632 | const string fullName = frontName + "_" + proto; |
633 | uint64_t threadNumber = 0; | |
a8b5b7a7 | 634 | auto dupPair = frontendDuplicates.insert({fullName, 1}); |
131df256 | 635 | if (!dupPair.second) { |
58aa4bc7 | 636 | threadNumber = dupPair.first->second; |
131df256 | 637 | ++(dupPair.first->second); |
a8b5b7a7 | 638 | } |
58aa4bc7 RG |
639 | const std::string label = boost::str(boost::format("{frontend=\"%1%\",proto=\"%2%\",thread=\"%3%\"} ") |
640 | % frontName % proto % threadNumber); | |
5bbcbea0 RG |
641 | |
642 | output << frontsbase << "queries" << label << front->queries.load() << "\n"; | |
7fc95193 | 643 | output << frontsbase << "responses" << label << front->responses.load() << "\n"; |
3a2ca389 RG |
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"; | |
f34fdcc5 RG |
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 | ||
dce48f34 RG |
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"; | |
f34fdcc5 RG |
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) { | |
dce48f34 RG |
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"; | |
f34fdcc5 RG |
682 | } |
683 | } | |
3a2ca389 | 684 | } |
5bbcbea0 | 685 | } |
37a5c2d5 | 686 | |
846b63bb RG |
687 | output << "# HELP " << frontsbase << "http_connects " << "Number of DoH TCP connections established to this frontend" << "\n"; |
688 | output << "# TYPE " << frontsbase << "http_connects " << "counter" << "\n"; | |
7fa07d7c | 689 | |
7fa07d7c RG |
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"; | |
846b63bb | 700 | output << "# TYPE " << frontsbase << "doh_responses " << "counter" << "\n"; |
5bbcbea0 | 701 | |
7fa07d7c RG |
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 | ||
5bbcbea0 | 705 | #ifdef HAVE_DNS_OVER_HTTPS |
f24bcf93 | 706 | std::map<std::string,uint64_t> dohFrontendDuplicates; |
5bbcbea0 | 707 | for(const auto& doh : g_dohlocals) { |
58aa4bc7 RG |
708 | const string frontName = doh->d_local.toStringWithPort(); |
709 | uint64_t threadNumber = 0; | |
f24bcf93 RG |
710 | auto dupPair = frontendDuplicates.insert({frontName, 1}); |
711 | if (!dupPair.second) { | |
58aa4bc7 | 712 | threadNumber = dupPair.first->second; |
f24bcf93 RG |
713 | ++(dupPair.first->second); |
714 | } | |
e3f3828b | 715 | const std::string addrlabel = boost::str(boost::format("frontend=\"%1%\",thread=\"%2%\"") % frontName % threadNumber); |
846b63bb RG |
716 | const std::string label = "{" + addrlabel + "} "; |
717 | ||
718 | output << frontsbase << "http_connects" << label << doh->d_httpconnects << "\n"; | |
7fa07d7c RG |
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"; | |
846b63bb RG |
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 | ||
7fa07d7c RG |
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"; | |
d18e3070 | 743 | } |
5bbcbea0 | 744 | #endif /* HAVE_DNS_OVER_HTTPS */ |
37a5c2d5 | 745 | |
6141572b | 746 | auto localPools = g_pools.getLocal(); |
d18e3070 | 747 | const string cachebase = "dnsdist_pool_"; |
6fe2e748 RG |
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"; | |
80dbd7d2 | 752 | |
b0ae99b9 RG |
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 | ||
6141572b | 772 | for (const auto& entry : *localPools) { |
d18e3070 | 773 | string poolName = entry.first; |
80dbd7d2 | 774 | |
d18e3070 PO |
775 | if (poolName.empty()) { |
776 | poolName = "_default_"; | |
777 | } | |
778 | const string label = "{pool=\"" + poolName + "\"}"; | |
779 | const std::shared_ptr<ServerPool> pool = entry.second; | |
3004c35b | 780 | output << "dnsdist_pool_servers" << label << " " << pool->countServers(false) << "\n"; |
5040e507 | 781 | output << "dnsdist_pool_active_servers" << label << " " << pool->countServers(true) << "\n"; |
37a5c2d5 | 782 | |
d18e3070 PO |
783 | if (pool->packetCache != nullptr) { |
784 | const auto& cache = pool->packetCache; | |
37a5c2d5 PO |
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"; | |
d18e3070 PO |
795 | } |
796 | } | |
797 | ||
37a5c2d5 | 798 | resp.body = output.str(); |
d18e3070 PO |
799 | resp.headers["Content-Type"] = "text/plain"; |
800 | } | |
801 | ||
46d06a12 | 802 | else if(req.url.path=="/api/v1/servers/localhost") { |
5387cc78 | 803 | handleCORS(req, resp); |
438a189b | 804 | resp.status=200; |
805 | ||
806 | Json::array servers; | |
a9c2e4ab | 807 | auto localServers = g_dstates.getLocal(); |
438a189b | 808 | int num=0; |
a9c2e4ab | 809 | for(const auto& a : *localServers) { |
438a189b | 810 | string status; |
80dbd7d2 | 811 | if(a->availability == DownstreamState::Availability::Up) |
438a189b | 812 | status = "UP"; |
80dbd7d2 | 813 | else if(a->availability == DownstreamState::Availability::Down) |
438a189b | 814 | status = "DOWN"; |
80dbd7d2 | 815 | else |
438a189b | 816 | status = (a->upStatus ? "up" : "down"); |
4ace9fe8 | 817 | |
357c22dd | 818 | Json::array pools; |
438a189b | 819 | for(const auto& p: a->pools) |
357c22dd RG |
820 | pools.push_back(p); |
821 | ||
80dbd7d2 | 822 | Json::object server{ |
357c22dd | 823 | {"id", num++}, |
be05aa91 | 824 | {"name", a->getName()}, |
357c22dd RG |
825 | {"address", a->remote.toStringWithPort()}, |
826 | {"state", status}, | |
778fe0a8 RG |
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}, | |
357c22dd | 833 | {"pools", pools}, |
778fe0a8 | 834 | {"latency", (double)(a->latencyUsec/1000.0)}, |
4ace9fe8 | 835 | {"queries", (double)a->queries}, |
7fc95193 | 836 | {"responses", (double)a->responses}, |
684f332e | 837 | {"sendErrors", (double)a->sendErrors}, |
a6e9e107 RG |
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}, | |
cff9aa03 RG |
843 | {"tcpCurrentConnections", (double)a->tcpCurrentConnections}, |
844 | {"tcpAvgQueriesPerConnection", (double)a->tcpAvgQueriesPerConnection}, | |
845 | {"tcpAvgConnectionDuration", (double)a->tcpAvgConnectionDuration}, | |
684f332e | 846 | {"dropRate", (double)a->dropRate} |
4ace9fe8 | 847 | }; |
357c22dd | 848 | |
36927800 RG |
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 | ||
438a189b | 854 | servers.push_back(server); |
855 | } | |
856 | ||
65dec2a3 RG |
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 }, | |
ba7ec340 | 867 | { "type", front->getType() }, |
a6e9e107 | 868 | { "queries", (double) front->queries.load() }, |
7fc95193 | 869 | { "responses", (double) front->responses.load() }, |
a6e9e107 RG |
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 }, | |
cff9aa03 RG |
875 | { "tcpCurrentConnections", (double) front->tcpCurrentConnections }, |
876 | { "tcpAvgQueriesPerConnection", (double) front->tcpAvgQueriesPerConnection }, | |
877 | { "tcpAvgConnectionDuration", (double) front->tcpAvgConnectionDuration }, | |
846b63bb RG |
878 | { "tlsNewSessions", (double) front->tlsNewSessions }, |
879 | { "tlsResumptions", (double) front->tlsResumptions }, | |
b608e6c6 RG |
880 | { "tlsUnknownTicketKey", (double) front->tlsUnknownTicketKey }, |
881 | { "tlsInactiveTicketKey", (double) front->tlsInactiveTicketKey }, | |
f78aaaba RG |
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 }, | |
65dec2a3 | 887 | }; |
f34fdcc5 RG |
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 | } | |
65dec2a3 RG |
905 | frontends.push_back(frontend); |
906 | } | |
907 | ||
5bbcbea0 RG |
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 }, | |
5bbcbea0 RG |
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 }, | |
1ddac024 | 935 | { "redirect-responses", (double) doh->d_redirectresponses }, |
5bbcbea0 RG |
936 | { "valid-responses", (double) doh->d_validresponses } |
937 | }; | |
938 | dohs.push_back(obj); | |
939 | } | |
940 | } | |
941 | #endif /* HAVE_DNS_OVER_HTTPS */ | |
942 | ||
4ace9fe8 | 943 | Json::array pools; |
a9c2e4ab | 944 | auto localPools = g_pools.getLocal(); |
4ace9fe8 | 945 | num=0; |
a9c2e4ab | 946 | for(const auto& pool : *localPools) { |
4ace9fe8 RG |
947 | const auto& cache = pool.second->packetCache; |
948 | Json::object entry { | |
949 | { "id", num++ }, | |
950 | { "name", pool.first }, | |
778fe0a8 | 951 | { "serversCount", (double) pool.second->countServers(false) }, |
4ace9fe8 RG |
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 | ||
438a189b | 965 | Json::array rules; |
a9c2e4ab | 966 | auto localRules = g_rulactions.getLocal(); |
438a189b | 967 | num=0; |
a9c2e4ab | 968 | for(const auto& a : *localRules) { |
438a189b | 969 | Json::object rule{ |
4ace9fe8 | 970 | {"id", num++}, |
f8a222ac | 971 | {"creationOrder", (double)a.d_creationOrder}, |
4d5959e6 RG |
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()} | |
1f4059be | 977 | }; |
438a189b | 978 | rules.push_back(rule); |
979 | } | |
80dbd7d2 | 980 | |
d18eab67 CH |
981 | auto responseRules = someResponseRulesToJson(&g_resprulactions); |
982 | auto cacheHitResponseRules = someResponseRulesToJson(&g_cachehitresprulactions); | |
2d4783a8 | 983 | auto selfAnsweredResponseRules = someResponseRulesToJson(&g_selfansweredresprulactions); |
4ace9fe8 | 984 | |
da5d4999 | 985 | string acl; |
986 | ||
987 | vector<string> vec; | |
a9c2e4ab | 988 | g_ACL.getLocal()->toStringVector(&vec); |
da5d4999 | 989 | |
990 | for(const auto& s : vec) { | |
991 | if(!acl.empty()) acl += ", "; | |
4ace9fe8 | 992 | acl+=s; |
da5d4999 | 993 | } |
50a80098 RG |
994 | string localaddressesStr; |
995 | std::set<std::string> localaddresses; | |
6e9fd124 | 996 | for(const auto& front : g_frontends) { |
50a80098 RG |
997 | localaddresses.insert(front->local.toStringWithPort()); |
998 | } | |
999 | for (const auto& addr : localaddresses) { | |
1000 | if (!localaddressesStr.empty()) { | |
1001 | localaddressesStr += ", "; | |
6e9fd124 | 1002 | } |
50a80098 | 1003 | localaddressesStr += addr; |
da5d4999 | 1004 | } |
80dbd7d2 | 1005 | |
438a189b | 1006 | Json my_json = Json::object { |
4ace9fe8 RG |
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}, | |
2d4783a8 | 1015 | { "self-answered-response-rules", selfAnsweredResponseRules}, |
4ace9fe8 | 1016 | { "acl", acl}, |
50a80098 | 1017 | { "local", localaddressesStr}, |
5bbcbea0 | 1018 | { "dohFrontends", dohs } |
438a189b | 1019 | }; |
5d1c98df | 1020 | resp.headers["Content-Type"] = "application/json"; |
438a189b | 1021 | resp.body=my_json.dump(); |
c8adc34c RG |
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) { | |
330dcb5c OM |
1029 | if (item.first == "special-memory-usage") |
1030 | continue; // Too expensive for get-all | |
1031 | ||
c8adc34c RG |
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 | } | |
af619119 | 1039 | else if (const auto& dval = boost::get<double*>(&item.second)) { |
c8adc34c RG |
1040 | doc.push_back(Json::object { |
1041 | { "type", "StatisticItem" }, | |
1042 | { "name", item.first }, | |
af619119 | 1043 | { "value", (**dval) } |
c8adc34c RG |
1044 | }); |
1045 | } | |
1046 | else { | |
1047 | doc.push_back(Json::object { | |
1048 | { "type", "StatisticItem" }, | |
1049 | { "name", item.first }, | |
778fe0a8 | 1050 | { "value", (double)(*boost::get<DNSDistStats::statfunction_t>(&item.second))(item.first) } |
c8adc34c RG |
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; | |
50bed881 | 1061 | |
c8adc34c RG |
1062 | Json::array doc; |
1063 | typedef boost::variant<bool, double, std::string> configentry_t; | |
1064 | std::vector<std::pair<std::string, configentry_t> > configEntries { | |
a9c2e4ab | 1065 | { "acl", g_ACL.getLocal()->toString() }, |
0dffe9e3 | 1066 | { "allow-empty-response", g_allowEmptyResponse }, |
c8adc34c RG |
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) { | |
af619119 | 1082 | if (const auto& bval = boost::get<bool>(&item.second)) { |
c8adc34c RG |
1083 | doc.push_back(Json::object { |
1084 | { "type", "ConfigSetting" }, | |
1085 | { "name", item.first }, | |
af619119 | 1086 | { "value", *bval } |
c8adc34c RG |
1087 | }); |
1088 | } | |
af619119 | 1089 | else if (const auto& sval = boost::get<string>(&item.second)) { |
c8adc34c RG |
1090 | doc.push_back(Json::object { |
1091 | { "type", "ConfigSetting" }, | |
1092 | { "name", item.first }, | |
af619119 | 1093 | { "value", *sval } |
c8adc34c RG |
1094 | }); |
1095 | } | |
af619119 | 1096 | else if (const auto& dval = boost::get<double>(&item.second)) { |
c8adc34c RG |
1097 | doc.push_back(Json::object { |
1098 | { "type", "ConfigSetting" }, | |
1099 | { "name", item.first }, | |
af619119 | 1100 | { "value", *dval } |
c8adc34c RG |
1101 | }); |
1102 | } | |
1103 | } | |
1104 | Json my_json = doc; | |
1105 | resp.body=my_json.dump(); | |
1106 | resp.headers["Content-Type"] = "application/json"; | |
438a189b | 1107 | } |
56d68fad RG |
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; | |
a9c2e4ab | 1149 | g_ACL.getLocal()->toStringVector(&vec); |
56d68fad RG |
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 | } | |
e3d76be2 RG |
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]); | |
fe20a1c1 | 1166 | vector<string> parts; |
e3d76be2 | 1167 | stringtok(parts, req.url.path, "."); |
fe20a1c1 | 1168 | if(parts.back() == "html") |
c8c1a4fc | 1169 | resp.headers["Content-Type"] = "text/html" + charset; |
fe20a1c1 | 1170 | else if(parts.back() == "css") |
c8c1a4fc | 1171 | resp.headers["Content-Type"] = "text/css" + charset; |
fe20a1c1 | 1172 | else if(parts.back() == "js") |
c8c1a4fc | 1173 | resp.headers["Content-Type"] = "application/javascript" + charset; |
864a6641 RG |
1174 | else if(parts.back() == "png") |
1175 | resp.headers["Content-Type"] = "image/png"; | |
438a189b | 1176 | resp.status=200; |
1177 | } | |
e3d76be2 | 1178 | else if(req.url.path=="/") { |
438a189b | 1179 | resp.body.assign(g_urlmap["index.html"]); |
c8c1a4fc | 1180 | resp.headers["Content-Type"] = "text/html" + charset; |
438a189b | 1181 | resp.status=200; |
1182 | } | |
1183 | else { | |
e3d76be2 | 1184 | // cerr<<"404 for: "<<req.url.path<<endl; |
438a189b | 1185 | resp.status=404; |
1186 | } | |
50bed881 | 1187 | |
438a189b | 1188 | std::ostringstream ofs; |
1189 | ofs << resp; | |
1190 | string done; | |
1191 | done=ofs.str(); | |
1192 | writen2(sock, done.c_str(), done.size()); | |
50bed881 | 1193 | |
56d68fad RG |
1194 | close(sock); |
1195 | sock = -1; | |
438a189b | 1196 | } |
59e9504e RG |
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()); | |
56d68fad | 1199 | close(sock); |
59e9504e | 1200 | } |
34a6dd76 | 1201 | catch(const std::exception& e) { |
59e9504e | 1202 | errlog("Webserver thread died with exception while processing a request from %s: %s", remote.toStringWithPort(), e.what()); |
56d68fad | 1203 | close(sock); |
34a6dd76 RG |
1204 | } |
1205 | catch(...) { | |
59e9504e | 1206 | errlog("Webserver thread died with exception while processing a request from %s", remote.toStringWithPort()); |
56d68fad | 1207 | close(sock); |
34a6dd76 | 1208 | } |
50bed881 | 1209 | } |
32c97b56 CHB |
1210 | |
1211 | void setWebserverAPIKey(const boost::optional<std::string> apiKey) | |
80dbd7d2 CHB |
1212 | { |
1213 | std::lock_guard<std::mutex> lock(g_webserverConfig.lock); | |
1214 | ||
80dbd7d2 CHB |
1215 | if (apiKey) { |
1216 | g_webserverConfig.apiKey = *apiKey; | |
1217 | } else { | |
1218 | g_webserverConfig.apiKey.clear(); | |
1219 | } | |
32c97b56 CHB |
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 | ||
80dbd7d2 CHB |
1233 | g_webserverConfig.customHeaders = customHeaders; |
1234 | } | |
1235 | ||
1236 | void dnsdistWebserverThread(int sock, const ComboAddress& local) | |
50bed881 | 1237 | { |
519f5484 | 1238 | setThreadName("dnsdist/webserv"); |
d745cd6f | 1239 | warnlog("Webserver launched on %s", local.toStringWithPort()); |
50bed881 | 1240 | for(;;) { |
1241 | try { | |
1242 | ComboAddress remote(local); | |
1243 | int fd = SAccept(sock, remote); | |
1244 | vinfolog("Got connection from %s", remote.toStringWithPort()); | |
80dbd7d2 | 1245 | std::thread t(connectionThread, fd, remote); |
50bed881 | 1246 | t.detach(); |
1247 | } | |
1248 | catch(std::exception& e) { | |
1249 | errlog("Had an error accepting new webserver connection: %s", e.what()); | |
1250 | } | |
1251 | } | |
1252 | } |