]>
Commit | Line | Data |
---|---|---|
12c86877 | 1 | /* |
6edbf68a PL |
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 | */ | |
870a0fe4 AT |
22 | #ifdef HAVE_CONFIG_H |
23 | #include "config.h" | |
24 | #endif | |
9054d8a4 | 25 | #include "utility.hh" |
d267d1bf | 26 | #include "dynlistener.hh" |
2470b36e | 27 | #include "ws-auth.hh" |
e611a06c | 28 | #include "json.hh" |
12c86877 BH |
29 | #include "webserver.hh" |
30 | #include "logger.hh" | |
31 | #include "statbag.hh" | |
32 | #include "misc.hh" | |
6f16f97c | 33 | #include "base64.hh" |
12c86877 BH |
34 | #include "arguments.hh" |
35 | #include "dns.hh" | |
6cc98ddf | 36 | #include "comment.hh" |
e611a06c | 37 | #include "ueberbackend.hh" |
dcc65f25 | 38 | #include <boost/format.hpp> |
fa8fd4d2 | 39 | |
9ac4a7c6 | 40 | #include "namespaces.hh" |
6ec5e728 | 41 | #include "ws-api.hh" |
ba1a571d | 42 | #include "version.hh" |
d29d5db7 | 43 | #include "dnsseckeeper.hh" |
3c3c006b | 44 | #include <iomanip> |
0f0e73fe | 45 | #include "zoneparser-tng.hh" |
a426cb89 | 46 | #include "common_startup.hh" |
bf269e28 | 47 | #include "auth-caches.hh" |
8537b9f0 | 48 | |
24afabad | 49 | using json11::Json; |
12c86877 BH |
50 | |
51 | extern StatBag S; | |
52 | ||
f63168e6 | 53 | static void patchZone(HttpRequest* req, HttpResponse* resp); |
995473c8 | 54 | static void storeChangedPTRs(UeberBackend& B, vector<DNSResourceRecord>& new_ptrs); |
f63168e6 CH |
55 | static void makePtr(const DNSResourceRecord& rr, DNSResourceRecord* ptr); |
56 | ||
dea47634 | 57 | AuthWebServer::AuthWebServer() |
12c86877 BH |
58 | { |
59 | d_start=time(0); | |
96d299db | 60 | d_min10=d_min5=d_min1=0; |
c81c2ea8 | 61 | d_ws = 0; |
f17c93b4 | 62 | d_tid = 0; |
536ab56f | 63 | if(arg().mustDo("webserver") || arg().mustDo("api")) { |
bbef8f04 | 64 | d_ws = new WebServer(arg()["webserver-address"], arg().asNum("webserver-port")); |
825fa717 CH |
65 | d_ws->bind(); |
66 | } | |
12c86877 BH |
67 | } |
68 | ||
dea47634 | 69 | void AuthWebServer::go() |
12c86877 | 70 | { |
536ab56f CH |
71 | S.doRings(); |
72 | pthread_create(&d_tid, 0, webThreadHelper, this); | |
73 | pthread_create(&d_tid, 0, statThreadHelper, this); | |
12c86877 BH |
74 | } |
75 | ||
dea47634 | 76 | void AuthWebServer::statThread() |
12c86877 BH |
77 | { |
78 | try { | |
79 | for(;;) { | |
80 | d_queries.submit(S.read("udp-queries")); | |
81 | d_cachehits.submit(S.read("packetcache-hit")); | |
82 | d_cachemisses.submit(S.read("packetcache-miss")); | |
83 | d_qcachehits.submit(S.read("query-cache-hit")); | |
84 | d_qcachemisses.submit(S.read("query-cache-miss")); | |
85 | Utility::sleep(1); | |
86 | } | |
87 | } | |
88 | catch(...) { | |
e6a9dde5 | 89 | g_log<<Logger::Error<<"Webserver statThread caught an exception, dying"<<endl; |
5bd2ea7b | 90 | _exit(1); |
12c86877 BH |
91 | } |
92 | } | |
93 | ||
dea47634 | 94 | void *AuthWebServer::statThreadHelper(void *p) |
12c86877 | 95 | { |
dea47634 CH |
96 | AuthWebServer *self=static_cast<AuthWebServer *>(p); |
97 | self->statThread(); | |
12c86877 BH |
98 | return 0; // never reached |
99 | } | |
100 | ||
dea47634 | 101 | void *AuthWebServer::webThreadHelper(void *p) |
12c86877 | 102 | { |
dea47634 CH |
103 | AuthWebServer *self=static_cast<AuthWebServer *>(p); |
104 | self->webThread(); | |
12c86877 BH |
105 | return 0; // never reached |
106 | } | |
107 | ||
9f3fdaa0 CH |
108 | static string htmlescape(const string &s) { |
109 | string result; | |
110 | for(string::const_iterator it=s.begin(); it!=s.end(); ++it) { | |
111 | switch (*it) { | |
112 | case '&': | |
c86a96f9 | 113 | result += "&"; |
9f3fdaa0 CH |
114 | break; |
115 | case '<': | |
116 | result += "<"; | |
117 | break; | |
118 | case '>': | |
119 | result += ">"; | |
120 | break; | |
c7f59d62 PL |
121 | case '"': |
122 | result += """; | |
123 | break; | |
9f3fdaa0 CH |
124 | default: |
125 | result += *it; | |
126 | } | |
127 | } | |
128 | return result; | |
129 | } | |
130 | ||
12c86877 BH |
131 | void printtable(ostringstream &ret, const string &ringname, const string &title, int limit=10) |
132 | { | |
133 | int tot=0; | |
134 | int entries=0; | |
101b5d5d | 135 | vector<pair <string,unsigned int> >ring=S.getRing(ringname); |
12c86877 | 136 | |
1071abdd | 137 | for(vector<pair<string, unsigned int> >::const_iterator i=ring.begin(); i!=ring.end();++i) { |
12c86877 BH |
138 | tot+=i->second; |
139 | entries++; | |
140 | } | |
141 | ||
1071abdd | 142 | ret<<"<div class=\"panel\">"; |
c7f59d62 | 143 | ret<<"<span class=resetring><i></i><a href=\"?resetring="<<htmlescape(ringname)<<"\">Reset</a></span>"<<endl; |
1071abdd CH |
144 | ret<<"<h2>"<<title<<"</h2>"<<endl; |
145 | ret<<"<div class=ringmeta>"; | |
c7f59d62 | 146 | ret<<"<a class=topXofY href=\"?ring="<<htmlescape(ringname)<<"\">Showing: Top "<<limit<<" of "<<entries<<"</a>"<<endl; |
1071abdd | 147 | ret<<"<span class=resizering>Resize: "; |
bb3c3f50 | 148 | unsigned int sizes[]={10,100,500,1000,10000,500000,0}; |
12c86877 BH |
149 | for(int i=0;sizes[i];++i) { |
150 | if(S.getRingSize(ringname)!=sizes[i]) | |
c7f59d62 | 151 | ret<<"<a href=\"?resizering="<<htmlescape(ringname)<<"&size="<<sizes[i]<<"\">"<<sizes[i]<<"</a> "; |
12c86877 BH |
152 | else |
153 | ret<<"("<<sizes[i]<<") "; | |
154 | } | |
1071abdd | 155 | ret<<"</span></div>"; |
12c86877 | 156 | |
1071abdd | 157 | ret<<"<table class=\"data\">"; |
12c86877 | 158 | int printed=0; |
f5cb7e61 | 159 | int total=max(1,tot); |
bb3c3f50 | 160 | for(vector<pair<string,unsigned int> >::const_iterator i=ring.begin();limit && i!=ring.end();++i,--limit) { |
dea47634 | 161 | ret<<"<tr><td>"<<htmlescape(i->first)<<"</td><td>"<<i->second<<"</td><td align=right>"<< AuthWebServer::makePercentage(i->second*100.0/total)<<"</td>"<<endl; |
12c86877 BH |
162 | printed+=i->second; |
163 | } | |
164 | ret<<"<tr><td colspan=3></td></tr>"<<endl; | |
165 | if(printed!=tot) | |
dea47634 | 166 | ret<<"<tr><td><b>Rest:</b></td><td><b>"<<tot-printed<<"</b></td><td align=right><b>"<< AuthWebServer::makePercentage((tot-printed)*100.0/total)<<"</b></td>"<<endl; |
12c86877 | 167 | |
e2a77e08 | 168 | ret<<"<tr><td><b>Total:</b></td><td><b>"<<tot<<"</b></td><td align=right><b>100%</b></td>"; |
1071abdd | 169 | ret<<"</table></div>"<<endl; |
12c86877 BH |
170 | } |
171 | ||
dea47634 | 172 | void AuthWebServer::printvars(ostringstream &ret) |
12c86877 | 173 | { |
1071abdd | 174 | ret<<"<div class=panel><h2>Variables</h2><table class=\"data\">"<<endl; |
12c86877 BH |
175 | |
176 | vector<string>entries=S.getEntries(); | |
177 | for(vector<string>::const_iterator i=entries.begin();i!=entries.end();++i) { | |
178 | ret<<"<tr><td>"<<*i<<"</td><td>"<<S.read(*i)<<"</td><td>"<<S.getDescrip(*i)<<"</td>"<<endl; | |
179 | } | |
e2a77e08 | 180 | |
1071abdd | 181 | ret<<"</table></div>"<<endl; |
12c86877 BH |
182 | } |
183 | ||
dea47634 | 184 | void AuthWebServer::printargs(ostringstream &ret) |
12c86877 | 185 | { |
e2a77e08 | 186 | ret<<"<table border=1><tr><td colspan=3 bgcolor=\"#0000ff\"><font color=\"#ffffff\">Arguments</font></td>"<<endl; |
12c86877 BH |
187 | |
188 | vector<string>entries=arg().list(); | |
189 | for(vector<string>::const_iterator i=entries.begin();i!=entries.end();++i) { | |
190 | ret<<"<tr><td>"<<*i<<"</td><td>"<<arg()[*i]<<"</td><td>"<<arg().getHelp(*i)<<"</td>"<<endl; | |
191 | } | |
192 | } | |
193 | ||
dea47634 | 194 | string AuthWebServer::makePercentage(const double& val) |
b6f57093 BH |
195 | { |
196 | return (boost::format("%.01f%%") % val).str(); | |
197 | } | |
198 | ||
dea47634 | 199 | void AuthWebServer::indexfunction(HttpRequest* req, HttpResponse* resp) |
12c86877 | 200 | { |
583ea80d CH |
201 | if(!req->getvars["resetring"].empty()) { |
202 | if (S.ringExists(req->getvars["resetring"])) | |
203 | S.resetRing(req->getvars["resetring"]); | |
d7b8730e | 204 | resp->status = 302; |
0665b7e6 | 205 | resp->headers["Location"] = req->url.path; |
80d59cd1 | 206 | return; |
12c86877 | 207 | } |
583ea80d | 208 | if(!req->getvars["resizering"].empty()){ |
335da0ba | 209 | int size=std::stoi(req->getvars["size"]); |
583ea80d | 210 | if (S.ringExists(req->getvars["resizering"]) && size > 0 && size <= 500000) |
335da0ba | 211 | S.resizeRing(req->getvars["resizering"], std::stoi(req->getvars["size"])); |
d7b8730e | 212 | resp->status = 302; |
0665b7e6 | 213 | resp->headers["Location"] = req->url.path; |
80d59cd1 | 214 | return; |
12c86877 BH |
215 | } |
216 | ||
217 | ostringstream ret; | |
218 | ||
1071abdd CH |
219 | ret<<"<!DOCTYPE html>"<<endl; |
220 | ret<<"<html><head>"<<endl; | |
221 | ret<<"<title>PowerDNS Authoritative Server Monitor</title>"<<endl; | |
222 | ret<<"<link rel=\"stylesheet\" href=\"style.css\"/>"<<endl; | |
223 | ret<<"</head><body>"<<endl; | |
224 | ||
225 | ret<<"<div class=\"row\">"<<endl; | |
226 | ret<<"<div class=\"headl columns\">"; | |
a1caa8b8 | 227 | ret<<"<a href=\"/\" id=\"appname\">PowerDNS "<<htmlescape(VERSION); |
1071abdd | 228 | if(!arg()["config-name"].empty()) { |
a1caa8b8 | 229 | ret<<" ["<<htmlescape(arg()["config-name"])<<"]"; |
1071abdd CH |
230 | } |
231 | ret<<"</a></div>"<<endl; | |
232 | ret<<"<div class=\"headr columns\"></div></div>"; | |
233 | ret<<"<div class=\"row\"><div class=\"all columns\">"; | |
12c86877 BH |
234 | |
235 | time_t passed=time(0)-s_starttime; | |
236 | ||
e2a77e08 KM |
237 | ret<<"<p>Uptime: "<< |
238 | humanDuration(passed)<< | |
239 | "<br>"<<endl; | |
12c86877 | 240 | |
395b07ea | 241 | ret<<"Queries/second, 1, 5, 10 minute averages: "<<std::setprecision(3)<< |
3e1cd1f4 | 242 | (int)d_queries.get1()<<", "<< |
243 | (int)d_queries.get5()<<", "<< | |
244 | (int)d_queries.get10()<<". Max queries/second: "<<(int)d_queries.getMax()<< | |
12c86877 | 245 | "<br>"<<endl; |
1d6b70f9 | 246 | |
f6154a3b | 247 | if(d_cachemisses.get10()+d_cachehits.get10()>0) |
b6f57093 | 248 | ret<<"Cache hitrate, 1, 5, 10 minute averages: "<< |
f6154a3b CH |
249 | makePercentage((d_cachehits.get1()*100.0)/((d_cachehits.get1())+(d_cachemisses.get1())))<<", "<< |
250 | makePercentage((d_cachehits.get5()*100.0)/((d_cachehits.get5())+(d_cachemisses.get5())))<<", "<< | |
251 | makePercentage((d_cachehits.get10()*100.0)/((d_cachehits.get10())+(d_cachemisses.get10())))<< | |
b6f57093 | 252 | "<br>"<<endl; |
12c86877 | 253 | |
f6154a3b | 254 | if(d_qcachemisses.get10()+d_qcachehits.get10()>0) |
395b07ea | 255 | ret<<"Backend query cache hitrate, 1, 5, 10 minute averages: "<<std::setprecision(2)<< |
f6154a3b CH |
256 | makePercentage((d_qcachehits.get1()*100.0)/((d_qcachehits.get1())+(d_qcachemisses.get1())))<<", "<< |
257 | makePercentage((d_qcachehits.get5()*100.0)/((d_qcachehits.get5())+(d_qcachemisses.get5())))<<", "<< | |
258 | makePercentage((d_qcachehits.get10()*100.0)/((d_qcachehits.get10())+(d_qcachemisses.get10())))<< | |
b6f57093 | 259 | "<br>"<<endl; |
12c86877 | 260 | |
395b07ea | 261 | ret<<"Backend query load, 1, 5, 10 minute averages: "<<std::setprecision(3)<< |
3e1cd1f4 | 262 | (int)d_qcachemisses.get1()<<", "<< |
263 | (int)d_qcachemisses.get5()<<", "<< | |
264 | (int)d_qcachemisses.get10()<<". Max queries/second: "<<(int)d_qcachemisses.getMax()<< | |
12c86877 BH |
265 | "<br>"<<endl; |
266 | ||
1071abdd | 267 | ret<<"Total queries: "<<S.read("udp-queries")<<". Question/answer latency: "<<S.read("latency")/1000.0<<"ms</p><br>"<<endl; |
583ea80d | 268 | if(req->getvars["ring"].empty()) { |
12c86877 BH |
269 | vector<string>entries=S.listRings(); |
270 | for(vector<string>::const_iterator i=entries.begin();i!=entries.end();++i) | |
271 | printtable(ret,*i,S.getRingTitle(*i)); | |
272 | ||
f6154a3b | 273 | printvars(ret); |
12c86877 | 274 | if(arg().mustDo("webserver-print-arguments")) |
f6154a3b | 275 | printargs(ret); |
12c86877 | 276 | } |
bea69e32 | 277 | else if(S.ringExists(req->getvars["ring"])) |
583ea80d | 278 | printtable(ret,req->getvars["ring"],S.getRingTitle(req->getvars["ring"]),100); |
12c86877 | 279 | |
1071abdd | 280 | ret<<"</div></div>"<<endl; |
a4167e57 | 281 | ret<<"<footer class=\"row\">"<<fullVersionString()<<"<br>© 2013 - 2018 <a href=\"http://www.powerdns.com/\">PowerDNS.COM BV</a>.</footer>"<<endl; |
12c86877 BH |
282 | ret<<"</body></html>"<<endl; |
283 | ||
80d59cd1 | 284 | resp->body = ret.str(); |
61f5d289 | 285 | resp->status = 200; |
12c86877 BH |
286 | } |
287 | ||
1d6b70f9 CH |
288 | /** Helper to build a record content as needed. */ |
289 | static inline string makeRecordContent(const QType& qtype, const string& content, bool noDot) { | |
290 | // noDot: for backend storage, pass true. for API users, pass false. | |
9a2c1e06 | 291 | auto drc = DNSRecordContent::makeunique(qtype.getCode(), QClass::IN, content); |
7fe1a82b | 292 | return drc->getZoneRepresentation(noDot); |
1d6b70f9 CH |
293 | } |
294 | ||
295 | /** "Normalize" record content for API consumers. */ | |
296 | static inline string makeApiRecordContent(const QType& qtype, const string& content) { | |
297 | return makeRecordContent(qtype, content, false); | |
298 | } | |
299 | ||
300 | /** "Normalize" record content for backend storage. */ | |
301 | static inline string makeBackendRecordContent(const QType& qtype, const string& content) { | |
302 | return makeRecordContent(qtype, content, true); | |
303 | } | |
304 | ||
ce846be6 | 305 | static Json::object getZoneInfo(const DomainInfo& di, DNSSECKeeper *dk) { |
290a083d | 306 | string zoneId = apiZoneNameToId(di.zone); |
d622042f | 307 | vector<string> masters; |
308 | for(const auto& m : di.masters) | |
309 | masters.push_back(m.toStringWithPortExcept(53)); | |
24ded6cc | 310 | |
62a9a74c CH |
311 | return Json::object { |
312 | // id is the canonical lookup key, which doesn't actually match the name (in some cases) | |
313 | { "id", zoneId }, | |
16e25450 | 314 | { "url", "/api/v1/servers/localhost/zones/" + zoneId }, |
62a9a74c CH |
315 | { "name", di.zone.toString() }, |
316 | { "kind", di.getKindString() }, | |
ce846be6 | 317 | { "dnssec", dk->isSecuredZone(di.zone) }, |
62a9a74c | 318 | { "account", di.account }, |
d622042f | 319 | { "masters", masters }, |
62a9a74c CH |
320 | { "serial", (double)di.serial }, |
321 | { "notified_serial", (double)di.notified_serial }, | |
322 | { "last_check", (double)di.last_check } | |
323 | }; | |
c04b5870 CH |
324 | } |
325 | ||
986e4858 PL |
326 | static bool shouldDoRRSets(HttpRequest* req) { |
327 | if (req->getvars.count("rrsets") == 0 || req->getvars["rrsets"] == "true") | |
328 | return true; | |
329 | if (req->getvars["rrsets"] == "false") | |
330 | return false; | |
331 | throw ApiException("'rrsets' request parameter value '"+req->getvars["rrsets"]+"' is not supported"); | |
332 | } | |
333 | ||
334 | static void fillZone(const DNSName& zonename, HttpResponse* resp, bool doRRSets) { | |
1abb81f4 | 335 | UeberBackend B; |
1abb81f4 | 336 | DomainInfo di; |
77bfe8de PL |
337 | if(!B.getDomainInfo(zonename, di)) { |
338 | throw HttpNotFoundException(); | |
339 | } | |
1abb81f4 | 340 | |
adef67eb | 341 | DNSSECKeeper dk(&B); |
ce846be6 | 342 | Json::object doc = getZoneInfo(di, &dk); |
62a9a74c | 343 | // extra stuff getZoneInfo doesn't do for us (more expensive) |
d29d5db7 CH |
344 | string soa_edit_api; |
345 | di.backend->getDomainMetadataOne(zonename, "SOA-EDIT-API", soa_edit_api); | |
62a9a74c | 346 | doc["soa_edit_api"] = soa_edit_api; |
6bb25159 MS |
347 | string soa_edit; |
348 | di.backend->getDomainMetadataOne(zonename, "SOA-EDIT", soa_edit); | |
62a9a74c | 349 | doc["soa_edit"] = soa_edit; |
986e4858 PL |
350 | string nsec3param; |
351 | di.backend->getDomainMetadataOne(zonename, "NSEC3PARAM", nsec3param); | |
352 | doc["nsec3param"] = nsec3param; | |
353 | string nsec3narrow; | |
354 | bool nsec3narrowbool = false; | |
355 | di.backend->getDomainMetadataOne(zonename, "NSEC3NARROW", nsec3narrow); | |
356 | if (nsec3narrow == "1") | |
357 | nsec3narrowbool = true; | |
358 | doc["nsec3narrow"] = nsec3narrowbool; | |
359 | ||
360 | string api_rectify; | |
361 | di.backend->getDomainMetadataOne(zonename, "API-RECTIFY", api_rectify); | |
362 | doc["api_rectify"] = (api_rectify == "1"); | |
363 | ||
eecc9ed5 PL |
364 | // TSIG |
365 | vector<string> tsig_master, tsig_slave; | |
366 | di.backend->getDomainMetadata(zonename, "TSIG-ALLOW-AXFR", tsig_master); | |
367 | di.backend->getDomainMetadata(zonename, "AXFR-MASTER-TSIG", tsig_slave); | |
368 | ||
369 | Json::array tsig_master_keys; | |
370 | for (const auto& keyname : tsig_master) { | |
371 | tsig_master_keys.push_back(apiZoneNameToId(DNSName(keyname))); | |
372 | } | |
373 | doc["master_tsig_key_ids"] = tsig_master_keys; | |
374 | ||
375 | Json::array tsig_slave_keys; | |
376 | for (const auto& keyname : tsig_slave) { | |
377 | tsig_slave_keys.push_back(apiZoneNameToId(DNSName(keyname))); | |
378 | } | |
379 | doc["slave_tsig_key_ids"] = tsig_slave_keys; | |
380 | ||
986e4858 PL |
381 | if (doRRSets) { |
382 | vector<DNSResourceRecord> records; | |
383 | vector<Comment> comments; | |
384 | ||
385 | // load all records + sort | |
386 | { | |
387 | DNSResourceRecord rr; | |
388 | di.backend->list(zonename, di.id, true); // incl. disabled | |
389 | while(di.backend->get(rr)) { | |
390 | if (!rr.qtype.getCode()) | |
391 | continue; // skip empty non-terminals | |
392 | records.push_back(rr); | |
393 | } | |
394 | sort(records.begin(), records.end(), [](const DNSResourceRecord& a, const DNSResourceRecord& b) { | |
395 | if (a.qname == b.qname) { | |
396 | return b.qtype < a.qtype; | |
397 | } | |
398 | return b.qname < a.qname; | |
399 | }); | |
6754ef71 | 400 | } |
6754ef71 | 401 | |
986e4858 PL |
402 | // load all comments + sort |
403 | { | |
404 | Comment comment; | |
405 | di.backend->listComments(di.id); | |
406 | while(di.backend->getComment(comment)) { | |
407 | comments.push_back(comment); | |
408 | } | |
409 | sort(comments.begin(), comments.end(), [](const Comment& a, const Comment& b) { | |
410 | if (a.qname == b.qname) { | |
411 | return b.qtype < a.qtype; | |
412 | } | |
413 | return b.qname < a.qname; | |
414 | }); | |
6754ef71 | 415 | } |
6754ef71 | 416 | |
986e4858 PL |
417 | Json::array rrsets; |
418 | Json::object rrset; | |
419 | Json::array rrset_records; | |
420 | Json::array rrset_comments; | |
421 | DNSName current_qname; | |
422 | QType current_qtype; | |
423 | uint32_t ttl; | |
424 | auto rit = records.begin(); | |
425 | auto cit = comments.begin(); | |
426 | ||
427 | while (rit != records.end() || cit != comments.end()) { | |
428 | if (cit == comments.end() || (rit != records.end() && (cit->qname.toString() <= rit->qname.toString() || cit->qtype < rit->qtype || cit->qtype == rit->qtype))) { | |
429 | current_qname = rit->qname; | |
430 | current_qtype = rit->qtype; | |
431 | ttl = rit->ttl; | |
432 | } else { | |
433 | current_qname = cit->qname; | |
434 | current_qtype = cit->qtype; | |
435 | ttl = 0; | |
436 | } | |
6754ef71 | 437 | |
986e4858 PL |
438 | while(rit != records.end() && rit->qname == current_qname && rit->qtype == current_qtype) { |
439 | ttl = min(ttl, rit->ttl); | |
440 | rrset_records.push_back(Json::object { | |
441 | { "disabled", rit->disabled }, | |
442 | { "content", makeApiRecordContent(rit->qtype, rit->content) } | |
443 | }); | |
444 | rit++; | |
445 | } | |
446 | while (cit != comments.end() && cit->qname == current_qname && cit->qtype == current_qtype) { | |
447 | rrset_comments.push_back(Json::object { | |
448 | { "modified_at", (double)cit->modified_at }, | |
449 | { "account", cit->account }, | |
450 | { "content", cit->content } | |
451 | }); | |
452 | cit++; | |
453 | } | |
454 | ||
455 | rrset["name"] = current_qname.toString(); | |
456 | rrset["type"] = current_qtype.getName(); | |
457 | rrset["records"] = rrset_records; | |
458 | rrset["comments"] = rrset_comments; | |
459 | rrset["ttl"] = (double)ttl; | |
460 | rrsets.push_back(rrset); | |
461 | rrset.clear(); | |
462 | rrset_records.clear(); | |
463 | rrset_comments.clear(); | |
6754ef71 CH |
464 | } |
465 | ||
986e4858 | 466 | doc["rrsets"] = rrsets; |
6754ef71 CH |
467 | } |
468 | ||
669822d0 | 469 | resp->setBody(doc); |
1abb81f4 CH |
470 | } |
471 | ||
6ec5e728 CH |
472 | void productServerStatisticsFetch(map<string,string>& out) |
473 | { | |
a45303b8 | 474 | vector<string> items = S.getEntries(); |
ff05fd12 | 475 | for(const string& item : items) { |
335da0ba | 476 | out[item] = std::to_string(S.read(item)); |
a45303b8 CH |
477 | } |
478 | ||
479 | // add uptime | |
335da0ba | 480 | out["uptime"] = std::to_string(time(0) - s_starttime); |
c67bf8c5 CH |
481 | } |
482 | ||
24ded6cc CHB |
483 | static void validateGatheredRRType(const DNSResourceRecord& rr) { |
484 | if (rr.qtype.getCode() == QType::OPT || rr.qtype.getCode() == QType::TSIG) { | |
485 | throw ApiException("RRset "+rr.qname.toString()+" IN "+rr.qtype.getName()+": invalid type given"); | |
486 | } | |
487 | } | |
488 | ||
6754ef71 | 489 | static void gatherRecords(const Json container, const DNSName& qname, const QType qtype, const int ttl, vector<DNSResourceRecord>& new_records, vector<DNSResourceRecord>& new_ptrs) { |
f63168e6 CH |
490 | UeberBackend B; |
491 | DNSResourceRecord rr; | |
6754ef71 CH |
492 | rr.qname = qname; |
493 | rr.qtype = qtype; | |
494 | rr.auth = 1; | |
495 | rr.ttl = ttl; | |
24ded6cc CHB |
496 | |
497 | validateGatheredRRType(rr); | |
1f68b185 | 498 | for(auto record : container["records"].array_items()) { |
1f68b185 | 499 | string content = stringFromJson(record, "content"); |
1f68b185 CH |
500 | rr.disabled = boolFromJson(record, "disabled"); |
501 | ||
1f68b185 CH |
502 | // validate that the client sent something we can actually parse, and require that data to be dotted. |
503 | try { | |
504 | if (rr.qtype.getCode() != QType::AAAA) { | |
505 | string tmp = makeApiRecordContent(rr.qtype, content); | |
506 | if (!pdns_iequals(tmp, content)) { | |
507 | throw std::runtime_error("Not in expected format (parsed as '"+tmp+"')"); | |
508 | } | |
509 | } else { | |
510 | struct in6_addr tmpbuf; | |
511 | if (inet_pton(AF_INET6, content.c_str(), &tmpbuf) != 1 || content.find('.') != string::npos) { | |
512 | throw std::runtime_error("Invalid IPv6 address"); | |
1e5b9ab9 | 513 | } |
f63168e6 | 514 | } |
1f68b185 CH |
515 | rr.content = makeBackendRecordContent(rr.qtype, content); |
516 | } | |
517 | catch(std::exception& e) | |
518 | { | |
519 | throw ApiException("Record "+rr.qname.toString()+"/"+rr.qtype.getName()+" '"+content+"': "+e.what()); | |
520 | } | |
f63168e6 | 521 | |
1f68b185 CH |
522 | if ((rr.qtype.getCode() == QType::A || rr.qtype.getCode() == QType::AAAA) && |
523 | boolFromJson(record, "set-ptr", false) == true) { | |
524 | DNSResourceRecord ptr; | |
525 | makePtr(rr, &ptr); | |
f63168e6 | 526 | |
1f68b185 | 527 | // verify that there's a zone for the PTR |
1f68b185 | 528 | SOAData sd; |
cec52de6 | 529 | if (!B.getAuth(ptr.qname, QType(QType::PTR), &sd, false)) |
1f68b185 | 530 | throw ApiException("Could not find domain for PTR '"+ptr.qname.toString()+"' requested for '"+ptr.content+"'"); |
f63168e6 | 531 | |
1f68b185 CH |
532 | ptr.domain_id = sd.domain_id; |
533 | new_ptrs.push_back(ptr); | |
f63168e6 | 534 | } |
1f68b185 CH |
535 | |
536 | new_records.push_back(rr); | |
f63168e6 CH |
537 | } |
538 | } | |
539 | ||
6754ef71 | 540 | static void gatherComments(const Json container, const DNSName& qname, const QType qtype, vector<Comment>& new_comments) { |
f63168e6 | 541 | Comment c; |
6754ef71 CH |
542 | c.qname = qname; |
543 | c.qtype = qtype; | |
f63168e6 CH |
544 | |
545 | time_t now = time(0); | |
1f68b185 | 546 | for (auto comment : container["comments"].array_items()) { |
1f68b185 CH |
547 | c.modified_at = intFromJson(comment, "modified_at", now); |
548 | c.content = stringFromJson(comment, "content"); | |
549 | c.account = stringFromJson(comment, "account"); | |
550 | new_comments.push_back(c); | |
f63168e6 CH |
551 | } |
552 | } | |
6cc98ddf | 553 | |
986e4858 PL |
554 | static void checkDefaultDNSSECAlgos() { |
555 | int k_algo = DNSSECKeeper::shorthand2algorithm(::arg()["default-ksk-algorithm"]); | |
556 | int z_algo = DNSSECKeeper::shorthand2algorithm(::arg()["default-zsk-algorithm"]); | |
557 | int k_size = arg().asNum("default-ksk-size"); | |
558 | int z_size = arg().asNum("default-zsk-size"); | |
559 | ||
560 | // Sanity check DNSSEC parameters | |
561 | if (::arg()["default-zsk-algorithm"] != "") { | |
562 | if (k_algo == -1) | |
563 | throw ApiException("default-ksk-algorithm setting is set to unknown algorithm: " + ::arg()["default-ksk-algorithm"]); | |
564 | else if (k_algo <= 10 && k_size == 0) | |
565 | throw ApiException("default-ksk-algorithm is set to an algorithm("+::arg()["default-ksk-algorithm"]+") that requires a non-zero default-ksk-size!"); | |
566 | } | |
567 | ||
568 | if (::arg()["default-zsk-algorithm"] != "") { | |
569 | if (z_algo == -1) | |
570 | throw ApiException("default-zsk-algorithm setting is set to unknown algorithm: " + ::arg()["default-zsk-algorithm"]); | |
571 | else if (z_algo <= 10 && z_size == 0) | |
572 | throw ApiException("default-zsk-algorithm is set to an algorithm("+::arg()["default-zsk-algorithm"]+") that requires a non-zero default-zsk-size!"); | |
573 | } | |
574 | } | |
575 | ||
89a7e706 PL |
576 | static void throwUnableToSecure(const DNSName& zonename) { |
577 | throw ApiException("No backend was able to secure '" + zonename.toString() + "', most likely because no DNSSEC" | |
578 | + "capable backends are loaded, or because the backends have DNSSEC disabled. Check your configuration."); | |
579 | } | |
580 | ||
986e4858 | 581 | static void updateDomainSettingsFromDocument(UeberBackend& B, const DomainInfo& di, const DNSName& zonename, const Json document) { |
1f68b185 | 582 | string zonemaster; |
986e4858 | 583 | bool shouldRectify = false; |
1f68b185 CH |
584 | for(auto value : document["masters"].array_items()) { |
585 | string master = value.string_value(); | |
586 | if (master.empty()) | |
587 | throw ApiException("Master can not be an empty string"); | |
588 | zonemaster += master + " "; | |
bb9fd223 CH |
589 | } |
590 | ||
986e4858 PL |
591 | if (zonemaster != "") { |
592 | di.backend->setMaster(zonename, zonemaster); | |
593 | } | |
594 | if (document["kind"].is_string()) { | |
595 | di.backend->setKind(zonename, DomainInfo::stringToKind(stringFromJson(document, "kind"))); | |
596 | } | |
1f68b185 CH |
597 | if (document["soa_edit_api"].is_string()) { |
598 | di.backend->setDomainMetadataOne(zonename, "SOA-EDIT-API", document["soa_edit_api"].string_value()); | |
d29d5db7 | 599 | } |
1f68b185 CH |
600 | if (document["soa_edit"].is_string()) { |
601 | di.backend->setDomainMetadataOne(zonename, "SOA-EDIT", document["soa_edit"].string_value()); | |
6bb25159 | 602 | } |
c00908f1 PL |
603 | try { |
604 | bool api_rectify = boolFromJson(document, "api_rectify"); | |
605 | di.backend->setDomainMetadataOne(zonename, "API-RECTIFY", api_rectify ? "1" : "0"); | |
986e4858 | 606 | } |
819861fa | 607 | catch (const JsonException&) {} |
c00908f1 | 608 | |
1f68b185 CH |
609 | if (document["account"].is_string()) { |
610 | di.backend->setAccount(zonename, document["account"].string_value()); | |
79532aa7 | 611 | } |
986e4858 PL |
612 | |
613 | DNSSECKeeper dk(&B); | |
614 | bool dnssecInJSON = false; | |
615 | bool dnssecDocVal = false; | |
616 | ||
617 | try { | |
618 | dnssecDocVal = boolFromJson(document, "dnssec"); | |
619 | dnssecInJSON = true; | |
620 | } | |
819861fa | 621 | catch (const JsonException&) {} |
986e4858 PL |
622 | |
623 | bool isDNSSECZone = dk.isSecuredZone(zonename); | |
624 | ||
625 | if (dnssecInJSON) { | |
626 | if (dnssecDocVal) { | |
627 | if (!isDNSSECZone) { | |
628 | checkDefaultDNSSECAlgos(); | |
629 | ||
630 | int k_algo = DNSSECKeeper::shorthand2algorithm(::arg()["default-ksk-algorithm"]); | |
631 | int z_algo = DNSSECKeeper::shorthand2algorithm(::arg()["default-zsk-algorithm"]); | |
632 | int k_size = arg().asNum("default-ksk-size"); | |
633 | int z_size = arg().asNum("default-zsk-size"); | |
634 | ||
635 | if (k_algo != -1) { | |
636 | int64_t id; | |
637 | if (!dk.addKey(zonename, true, k_algo, id, k_size)) { | |
89a7e706 | 638 | throwUnableToSecure(zonename); |
986e4858 PL |
639 | } |
640 | } | |
641 | ||
642 | if (z_algo != -1) { | |
643 | int64_t id; | |
644 | if (!dk.addKey(zonename, false, z_algo, id, z_size)) { | |
89a7e706 | 645 | throwUnableToSecure(zonename); |
986e4858 PL |
646 | } |
647 | } | |
648 | ||
649 | // Used later for NSEC3PARAM | |
650 | isDNSSECZone = dk.isSecuredZone(zonename); | |
651 | ||
652 | if (!isDNSSECZone) { | |
89a7e706 | 653 | throwUnableToSecure(zonename); |
986e4858 PL |
654 | } |
655 | shouldRectify = true; | |
656 | } | |
657 | } else { | |
658 | // "dnssec": false in json | |
659 | if (isDNSSECZone) { | |
cbe8b186 PL |
660 | string info, error; |
661 | if (!dk.unSecureZone(zonename, error, info)) { | |
662 | throw ApiException("Error while un-securing zone '"+ zonename.toString()+"': " + error); | |
663 | } | |
664 | isDNSSECZone = dk.isSecuredZone(zonename); | |
665 | if (isDNSSECZone) { | |
666 | throw ApiException("Unable to un-secure zone '"+ zonename.toString()+"'"); | |
667 | } | |
668 | shouldRectify = true; | |
986e4858 PL |
669 | } |
670 | } | |
671 | } | |
672 | ||
673 | if(document["nsec3param"].string_value().length() > 0) { | |
674 | shouldRectify = true; | |
675 | NSEC3PARAMRecordContent ns3pr(document["nsec3param"].string_value()); | |
676 | string error_msg = ""; | |
677 | if (!isDNSSECZone) { | |
678 | throw ApiException("NSEC3PARAMs provided for zone '"+zonename.toString()+"', but zone is not DNSSEC secured."); | |
679 | } | |
680 | if (!dk.checkNSEC3PARAM(ns3pr, error_msg)) { | |
681 | throw ApiException("NSEC3PARAMs provided for zone '"+zonename.toString()+"' are invalid. " + error_msg); | |
682 | } | |
683 | if (!dk.setNSEC3PARAM(zonename, ns3pr, boolFromJson(document, "nsec3narrow", false))) { | |
684 | throw ApiException("NSEC3PARAMs provided for zone '" + zonename.toString() + | |
685 | "' passed our basic sanity checks, but cannot be used with the current backend."); | |
686 | } | |
687 | } | |
688 | ||
a843c67e KM |
689 | if (shouldRectify && !dk.isPresigned(zonename)) { |
690 | // Rectify | |
691 | string api_rectify; | |
692 | di.backend->getDomainMetadataOne(zonename, "API-RECTIFY", api_rectify); | |
693 | if (api_rectify == "1") { | |
694 | string info; | |
695 | string error_msg; | |
696 | if (!dk.rectifyZone(zonename, error_msg, info, true)) { | |
697 | throw ApiException("Failed to rectify '" + zonename.toString() + "' " + error_msg); | |
698 | } | |
699 | } | |
700 | ||
701 | // Increase serial | |
702 | string soa_edit_api_kind; | |
703 | di.backend->getDomainMetadataOne(zonename, "SOA-EDIT-API", soa_edit_api_kind); | |
704 | if (!soa_edit_api_kind.empty()) { | |
705 | SOAData sd; | |
706 | if (!B.getSOAUncached(zonename, sd, true)) | |
707 | return; | |
708 | ||
709 | string soa_edit_kind; | |
710 | di.backend->getDomainMetadataOne(zonename, "SOA-EDIT", soa_edit_kind); | |
711 | ||
712 | DNSResourceRecord rr; | |
713 | if (makeIncreasedSOARecord(sd, soa_edit_api_kind, soa_edit_kind, rr)) { | |
714 | if (!di.backend->replaceRRSet(di.id, rr.qname, rr.qtype, vector<DNSResourceRecord>(1, rr))) { | |
715 | throw ApiException("Hosting backend does not support editing records."); | |
716 | } | |
717 | } | |
a843c67e | 718 | } |
986e4858 | 719 | } |
1096d493 PL |
720 | |
721 | if (!document["master_tsig_key_ids"].is_null()) { | |
722 | vector<string> metadata; | |
723 | for(auto value : document["master_tsig_key_ids"].array_items()) { | |
724 | auto keyname(value.string_value()); | |
725 | // XXX test if the key actually exists? | |
726 | metadata.push_back(apiZoneIdToName(keyname).toString()); | |
727 | } | |
728 | if (!di.backend->setDomainMetadata(zonename, "TSIG-ALLOW-AXFR", metadata)) { | |
729 | throw ApiException("Unable to set new TSIG master keys for zone '" + zonename.toLogString() + "'"); | |
730 | } | |
731 | } | |
732 | if (!document["slave_tsig_key_ids"].is_null()) { | |
733 | vector<string> metadata; | |
734 | for(auto value : document["slave_tsig_key_ids"].array_items()) { | |
735 | auto keyname(value.string_value()); | |
736 | // XXX test if the key actually exists? | |
737 | metadata.push_back(apiZoneIdToName(keyname).toString()); | |
738 | } | |
739 | if (!di.backend->setDomainMetadata(zonename, "AXFR-MASTER-TSIG", metadata)) { | |
740 | throw ApiException("Unable to set new TSIG slave keys for zone '" + zonename.toLogString() + "'"); | |
741 | } | |
742 | } | |
bb9fd223 CH |
743 | } |
744 | ||
24e11043 CJ |
745 | static bool isValidMetadataKind(const string& kind, bool readonly) { |
746 | static vector<string> builtinOptions { | |
747 | "ALLOW-AXFR-FROM", | |
748 | "AXFR-SOURCE", | |
749 | "ALLOW-DNSUPDATE-FROM", | |
750 | "TSIG-ALLOW-DNSUPDATE", | |
751 | "FORWARD-DNSUPDATE", | |
752 | "SOA-EDIT-DNSUPDATE", | |
4c5b6925 | 753 | "NOTIFY-DNSUPDATE", |
24e11043 CJ |
754 | "ALSO-NOTIFY", |
755 | "AXFR-MASTER-TSIG", | |
756 | "GSS-ALLOW-AXFR-PRINCIPAL", | |
757 | "GSS-ACCEPTOR-PRINCIPAL", | |
758 | "IXFR", | |
759 | "LUA-AXFR-SCRIPT", | |
760 | "NSEC3NARROW", | |
761 | "NSEC3PARAM", | |
762 | "PRESIGNED", | |
763 | "PUBLISH-CDNSKEY", | |
764 | "PUBLISH-CDS", | |
765 | "SOA-EDIT", | |
766 | "TSIG-ALLOW-AXFR", | |
767 | "TSIG-ALLOW-DNSUPDATE" | |
768 | }; | |
769 | ||
770 | // the following options do not allow modifications via API | |
771 | static vector<string> protectedOptions { | |
986e4858 | 772 | "API-RECTIFY", |
2fabf5ce | 773 | "AXFR-MASTER-TSIG", |
24e11043 CJ |
774 | "NSEC3NARROW", |
775 | "NSEC3PARAM", | |
776 | "PRESIGNED", | |
2fabf5ce PL |
777 | "LUA-AXFR-SCRIPT", |
778 | "TSIG-ALLOW-AXFR" | |
24e11043 CJ |
779 | }; |
780 | ||
9ac4e6d5 PL |
781 | if (kind.find("X-") == 0) |
782 | return true; | |
783 | ||
24e11043 CJ |
784 | bool found = false; |
785 | ||
d8043c73 | 786 | for (const string& s : builtinOptions) { |
24e11043 | 787 | if (kind == s) { |
d8043c73 | 788 | for (const string& s2 : protectedOptions) { |
24e11043 CJ |
789 | if (!readonly && s == s2) |
790 | return false; | |
791 | } | |
792 | found = true; | |
793 | break; | |
794 | } | |
795 | } | |
796 | ||
797 | return found; | |
798 | } | |
799 | ||
800 | static void apiZoneMetadata(HttpRequest* req, HttpResponse *resp) { | |
801 | DNSName zonename = apiZoneIdToName(req->parameters["id"]); | |
d38e81e6 | 802 | |
24e11043 | 803 | UeberBackend B; |
d38e81e6 | 804 | DomainInfo di; |
77bfe8de PL |
805 | if (!B.getDomainInfo(zonename, di)) { |
806 | throw HttpNotFoundException(); | |
807 | } | |
24e11043 CJ |
808 | |
809 | if (req->method == "GET") { | |
810 | map<string, vector<string> > md; | |
811 | Json::array document; | |
812 | ||
813 | if (!B.getAllDomainMetadata(zonename, md)) | |
814 | throw HttpNotFoundException(); | |
815 | ||
816 | for (const auto& i : md) { | |
817 | Json::array entries; | |
818 | for (string j : i.second) | |
819 | entries.push_back(j); | |
820 | ||
821 | Json::object key { | |
822 | { "type", "Metadata" }, | |
823 | { "kind", i.first }, | |
824 | { "metadata", entries } | |
825 | }; | |
826 | ||
827 | document.push_back(key); | |
828 | } | |
829 | ||
830 | resp->setBody(document); | |
831 | } else if (req->method == "POST" && !::arg().mustDo("api-readonly")) { | |
832 | auto document = req->json(); | |
833 | string kind; | |
834 | vector<string> entries; | |
835 | ||
836 | try { | |
837 | kind = stringFromJson(document, "kind"); | |
819861fa | 838 | } catch (const JsonException&) { |
24e11043 CJ |
839 | throw ApiException("kind is not specified or not a string"); |
840 | } | |
841 | ||
842 | if (!isValidMetadataKind(kind, false)) | |
843 | throw ApiException("Unsupported metadata kind '" + kind + "'"); | |
844 | ||
845 | vector<string> vecMetadata; | |
c6720e79 CJ |
846 | |
847 | if (!B.getDomainMetadata(zonename, kind, vecMetadata)) | |
848 | throw ApiException("Could not retrieve metadata entries for domain '" + | |
849 | zonename.toString() + "'"); | |
850 | ||
24e11043 CJ |
851 | auto& metadata = document["metadata"]; |
852 | if (!metadata.is_array()) | |
853 | throw ApiException("metadata is not specified or not an array"); | |
854 | ||
855 | for (const auto& i : metadata.array_items()) { | |
856 | if (!i.is_string()) | |
857 | throw ApiException("metadata must be strings"); | |
c6720e79 CJ |
858 | else if (std::find(vecMetadata.cbegin(), |
859 | vecMetadata.cend(), | |
860 | i.string_value()) == vecMetadata.cend()) { | |
861 | vecMetadata.push_back(i.string_value()); | |
862 | } | |
24e11043 CJ |
863 | } |
864 | ||
865 | if (!B.setDomainMetadata(zonename, kind, vecMetadata)) | |
c6720e79 CJ |
866 | throw ApiException("Could not update metadata entries for domain '" + |
867 | zonename.toString() + "'"); | |
868 | ||
869 | Json::array respMetadata; | |
870 | for (const string& s : vecMetadata) | |
871 | respMetadata.push_back(s); | |
872 | ||
873 | Json::object key { | |
874 | { "type", "Metadata" }, | |
875 | { "kind", document["kind"] }, | |
876 | { "metadata", respMetadata } | |
877 | }; | |
24e11043 | 878 | |
24e11043 | 879 | resp->status = 201; |
c6720e79 | 880 | resp->setBody(key); |
24e11043 CJ |
881 | } else |
882 | throw HttpMethodNotAllowedException(); | |
883 | } | |
884 | ||
885 | static void apiZoneMetadataKind(HttpRequest* req, HttpResponse* resp) { | |
886 | DNSName zonename = apiZoneIdToName(req->parameters["id"]); | |
d38e81e6 | 887 | |
24e11043 | 888 | UeberBackend B; |
d38e81e6 | 889 | DomainInfo di; |
77bfe8de PL |
890 | if (!B.getDomainInfo(zonename, di)) { |
891 | throw HttpNotFoundException(); | |
892 | } | |
d38e81e6 PL |
893 | |
894 | string kind = req->parameters["kind"]; | |
24e11043 CJ |
895 | |
896 | if (req->method == "GET") { | |
897 | vector<string> metadata; | |
898 | Json::object document; | |
899 | Json::array entries; | |
900 | ||
901 | if (!B.getDomainMetadata(zonename, kind, metadata)) | |
902 | throw HttpNotFoundException(); | |
903 | else if (!isValidMetadataKind(kind, true)) | |
904 | throw ApiException("Unsupported metadata kind '" + kind + "'"); | |
905 | ||
906 | document["type"] = "Metadata"; | |
907 | document["kind"] = kind; | |
908 | ||
909 | for (const string& i : metadata) | |
910 | entries.push_back(i); | |
911 | ||
912 | document["metadata"] = entries; | |
913 | resp->setBody(document); | |
914 | } else if (req->method == "PUT" && !::arg().mustDo("api-readonly")) { | |
915 | auto document = req->json(); | |
916 | ||
917 | if (!isValidMetadataKind(kind, false)) | |
918 | throw ApiException("Unsupported metadata kind '" + kind + "'"); | |
919 | ||
920 | vector<string> vecMetadata; | |
921 | auto& metadata = document["metadata"]; | |
922 | if (!metadata.is_array()) | |
923 | throw ApiException("metadata is not specified or not an array"); | |
924 | ||
925 | for (const auto& i : metadata.array_items()) { | |
926 | if (!i.is_string()) | |
927 | throw ApiException("metadata must be strings"); | |
928 | vecMetadata.push_back(i.string_value()); | |
929 | } | |
930 | ||
931 | if (!B.setDomainMetadata(zonename, kind, vecMetadata)) | |
932 | throw ApiException("Could not update metadata entries for domain '" + zonename.toString() + "'"); | |
933 | ||
934 | Json::object key { | |
935 | { "type", "Metadata" }, | |
936 | { "kind", kind }, | |
937 | { "metadata", metadata } | |
938 | }; | |
939 | ||
940 | resp->setBody(key); | |
941 | } else if (req->method == "DELETE" && !::arg().mustDo("api-readonly")) { | |
942 | if (!isValidMetadataKind(kind, false)) | |
943 | throw ApiException("Unsupported metadata kind '" + kind + "'"); | |
944 | ||
945 | vector<string> md; // an empty vector will do it | |
946 | if (!B.setDomainMetadata(zonename, kind, md)) | |
947 | throw ApiException("Could not delete metadata for domain '" + zonename.toString() + "' (" + kind + ")"); | |
948 | } else | |
949 | throw HttpMethodNotAllowedException(); | |
950 | } | |
951 | ||
71de13d7 PL |
952 | // Throws 404 if the key with inquireKeyId does not exist |
953 | static void apiZoneCryptoKeysCheckKeyExists(DNSName zonename, int inquireKeyId, DNSSECKeeper *dk) { | |
954 | DNSSECKeeper::keyset_t keyset=dk->getKeys(zonename, false); | |
955 | bool found = false; | |
956 | for(const auto& value : keyset) { | |
957 | if (value.second.id == (unsigned) inquireKeyId) { | |
958 | found = true; | |
959 | break; | |
960 | } | |
961 | } | |
962 | if (!found) { | |
963 | throw HttpNotFoundException(); | |
964 | } | |
965 | } | |
966 | ||
60b0a236 BZ |
967 | static void apiZoneCryptokeysGET(DNSName zonename, int inquireKeyId, HttpResponse *resp, DNSSECKeeper *dk) { |
968 | DNSSECKeeper::keyset_t keyset=dk->getKeys(zonename, false); | |
4b7f120a | 969 | |
997cab68 BZ |
970 | bool inquireSingleKey = inquireKeyId >= 0; |
971 | ||
24afabad | 972 | Json::array doc; |
29704f66 | 973 | for(const auto& value : keyset) { |
997cab68 | 974 | if (inquireSingleKey && (unsigned)inquireKeyId != value.second.id) { |
29704f66 | 975 | continue; |
38809e97 | 976 | } |
24afabad | 977 | |
b6bd795c | 978 | string keyType; |
60b0a236 | 979 | switch (value.second.keyType) { |
b6bd795c PL |
980 | case DNSSECKeeper::KSK: keyType="ksk"; break; |
981 | case DNSSECKeeper::ZSK: keyType="zsk"; break; | |
982 | case DNSSECKeeper::CSK: keyType="csk"; break; | |
983 | } | |
984 | ||
24afabad | 985 | Json::object key { |
997cab68 BZ |
986 | { "type", "Cryptokey" }, |
987 | { "id", (int)value.second.id }, | |
988 | { "active", value.second.active }, | |
989 | { "keytype", keyType }, | |
990 | { "flags", (uint16_t)value.first.d_flags }, | |
5d9c6182 PL |
991 | { "dnskey", value.first.getDNSKEY().getZoneRepresentation() }, |
992 | { "algorithm", DNSSECKeeper::algorithm2name(value.first.d_algorithm) }, | |
993 | { "bits", value.first.getKey()->getBits() } | |
24afabad CH |
994 | }; |
995 | ||
b6bd795c | 996 | if (value.second.keyType == DNSSECKeeper::KSK || value.second.keyType == DNSSECKeeper::CSK) { |
24afabad | 997 | Json::array dses; |
8455425c | 998 | for(const uint8_t keyid : { DNSSECKeeper::SHA1, DNSSECKeeper::SHA256, DNSSECKeeper::GOST, DNSSECKeeper::SHA384 }) |
997cab68 BZ |
999 | try { |
1000 | dses.push_back(makeDSFromDNSKey(zonename, value.first.getDNSKEY(), keyid).getZoneRepresentation()); | |
1001 | } catch (...) {} | |
24afabad | 1002 | key["ds"] = dses; |
4b7f120a | 1003 | } |
29704f66 CH |
1004 | |
1005 | if (inquireSingleKey) { | |
1006 | key["privatekey"] = value.first.getKey()->convertToISC(); | |
1007 | resp->setBody(key); | |
1008 | return; | |
1009 | } | |
24afabad | 1010 | doc.push_back(key); |
4b7f120a MS |
1011 | } |
1012 | ||
29704f66 CH |
1013 | if (inquireSingleKey) { |
1014 | // we came here because we couldn't find the requested key. | |
1015 | throw HttpNotFoundException(); | |
1016 | } | |
4b7f120a | 1017 | resp->setBody(doc); |
997cab68 BZ |
1018 | |
1019 | } | |
1020 | ||
1021 | /* | |
1022 | * This method handles DELETE requests for URL /api/v1/servers/:server_id/zones/:zone_name/cryptokeys/:cryptokey_id . | |
1023 | * It deletes a key from :zone_name specified by :cryptokey_id. | |
1024 | * Server Answers: | |
60b0a236 | 1025 | * Case 1: the backend returns true on removal. This means the key is gone. |
75191dc4 | 1026 | * The server returns 204 No Content, no body. |
955cbfd0 | 1027 | * Case 2: the backend returns false on removal. An error occurred. |
75191dc4 PL |
1028 | * The server returns 422 Unprocessable Entity with message "Could not DELETE :cryptokey_id". |
1029 | * Case 3: the key or zone does not exist. | |
1030 | * The server returns 404 Not Found | |
997cab68 | 1031 | * */ |
60b0a236 BZ |
1032 | static void apiZoneCryptokeysDELETE(DNSName zonename, int inquireKeyId, HttpRequest *req, HttpResponse *resp, DNSSECKeeper *dk) { |
1033 | if (dk->removeKey(zonename, inquireKeyId)) { | |
1034 | resp->body = ""; | |
75191dc4 | 1035 | resp->status = 204; |
997cab68 BZ |
1036 | } else { |
1037 | resp->setErrorResult("Could not DELETE " + req->parameters["key_id"], 422); | |
1038 | } | |
1039 | } | |
1040 | ||
1041 | /* | |
1042 | * This method adds a key to a zone by generate it or content parameter. | |
1043 | * Parameter: | |
1044 | * { | |
5d9c6182 | 1045 | * "privatekey" : "key The format used is compatible with BIND and NSD/LDNS" <string> |
997cab68 BZ |
1046 | * "keytype" : "ksk|zsk" <string> |
1047 | * "active" : "true|false" <value> | |
5d9c6182 | 1048 | * "algorithm" : "key generation algorithm name as default"<string> https://doc.powerdns.com/md/authoritative/dnssec/#supported-algorithms |
997cab68 BZ |
1049 | * "bits" : number of bits <int> |
1050 | * } | |
1051 | * | |
1052 | * Response: | |
1053 | * Case 1: keytype isn't ksk|zsk | |
1054 | * The server returns 422 Unprocessable Entity {"error" : "Invalid keytype 'keytype'"} | |
60b0a236 BZ |
1055 | * Case 2: 'bits' must be a positive integer value. |
1056 | * The server returns 422 Unprocessable Entity {"error" : "'bits' must be a positive integer value."} | |
5d9c6182 | 1057 | * Case 3: The "algorithm" isn't supported |
997cab68 | 1058 | * The server returns 422 Unprocessable Entity {"error" : "Unknown algorithm: 'algo'"} |
60b0a236 | 1059 | * Case 4: Algorithm <= 10 and no bits were passed |
997cab68 | 1060 | * The server returns 422 Unprocessable Entity {"error" : "Creating an algorithm algo key requires the size (in bits) to be passed"} |
60b0a236 BZ |
1061 | * Case 5: The wrong keysize was passed |
1062 | * The server returns 422 Unprocessable Entity {"error" : "The algorithm does not support the given bit size."} | |
1063 | * Case 6: If the server cant guess the keysize | |
1064 | * The server returns 422 Unprocessable Entity {"error" : "Can not guess key size for algorithm"} | |
1065 | * Case 7: The key-creation failed | |
997cab68 | 1066 | * The server returns 422 Unprocessable Entity {"error" : "Adding key failed, perhaps DNSSEC not enabled in configuration?"} |
60b0a236 BZ |
1067 | * Case 8: The key in content has the wrong format |
1068 | * The server returns 422 Unprocessable Entity {"error" : "Key could not be parsed. Make sure your key format is correct."} | |
1069 | * Case 9: The wrong combination of fields is submitted | |
1070 | * The server returns 422 Unprocessable Entity {"error" : "Either you submit just the 'content' field or you leave 'content' empty and submit the other fields."} | |
1071 | * Case 10: No content and everything was fine | |
1072 | * The server returns 201 Created and all public data about the new cryptokey | |
1073 | * Case 11: With specified content | |
1074 | * The server returns 201 Created and all public data about the added cryptokey | |
997cab68 BZ |
1075 | */ |
1076 | ||
60b0a236 | 1077 | static void apiZoneCryptokeysPOST(DNSName zonename, HttpRequest *req, HttpResponse *resp, DNSSECKeeper *dk) { |
997cab68 | 1078 | auto document = req->json(); |
5d9c6182 PL |
1079 | string privatekey_fieldname = "privatekey"; |
1080 | auto privatekey = document["privatekey"]; | |
1081 | if (privatekey.is_null()) { | |
1082 | // Fallback to the old "content" behaviour | |
1083 | privatekey = document["content"]; | |
1084 | privatekey_fieldname = "content"; | |
1085 | } | |
997cab68 | 1086 | bool active = boolFromJson(document, "active", false); |
997cab68 | 1087 | bool keyOrZone; |
60b0a236 | 1088 | |
eefd15b3 | 1089 | if (stringFromJson(document, "keytype") == "ksk" || stringFromJson(document, "keytype") == "csk") { |
997cab68 BZ |
1090 | keyOrZone = true; |
1091 | } else if (stringFromJson(document, "keytype") == "zsk") { | |
1092 | keyOrZone = false; | |
1093 | } else { | |
1094 | throw ApiException("Invalid keytype " + stringFromJson(document, "keytype")); | |
1095 | } | |
1096 | ||
b727e19b | 1097 | int64_t insertedId = -1; |
997cab68 | 1098 | |
5d9c6182 | 1099 | if (privatekey.is_null()) { |
43215ca6 | 1100 | int bits = keyOrZone ? ::arg().asNum("default-ksk-size") : ::arg().asNum("default-zsk-size"); |
60b0a236 BZ |
1101 | auto docbits = document["bits"]; |
1102 | if (!docbits.is_null()) { | |
1103 | if (!docbits.is_number() || (fmod(docbits.number_value(), 1.0) != 0) || docbits.int_value() < 0) { | |
1104 | throw ApiException("'bits' must be a positive integer value"); | |
1105 | } else { | |
1106 | bits = docbits.int_value(); | |
1107 | } | |
1108 | } | |
43215ca6 | 1109 | int algorithm = DNSSECKeeper::shorthand2algorithm(keyOrZone ? ::arg()["default-ksk-algorithm"] : ::arg()["default-zsk-algorithm"]); |
5d9c6182 | 1110 | auto providedAlgo = document["algorithm"]; |
997cab68 | 1111 | if (providedAlgo.is_string()) { |
60b0a236 BZ |
1112 | algorithm = DNSSECKeeper::shorthand2algorithm(providedAlgo.string_value()); |
1113 | if (algorithm == -1) | |
997cab68 | 1114 | throw ApiException("Unknown algorithm: " + providedAlgo.string_value()); |
997cab68 BZ |
1115 | } else if (providedAlgo.is_number()) { |
1116 | algorithm = providedAlgo.int_value(); | |
60b0a236 BZ |
1117 | } else if (!providedAlgo.is_null()) { |
1118 | throw ApiException("Unknown algorithm: " + providedAlgo.string_value()); | |
997cab68 BZ |
1119 | } |
1120 | ||
60b0a236 | 1121 | try { |
b727e19b RG |
1122 | if (!dk->addKey(zonename, keyOrZone, algorithm, insertedId, bits, active)) { |
1123 | throw ApiException("Adding key failed, perhaps DNSSEC not enabled in configuration?"); | |
1124 | } | |
60b0a236 | 1125 | } catch (std::runtime_error& error) { |
997cab68 BZ |
1126 | throw ApiException(error.what()); |
1127 | } | |
997cab68 BZ |
1128 | if (insertedId < 0) |
1129 | throw ApiException("Adding key failed, perhaps DNSSEC not enabled in configuration?"); | |
5d9c6182 PL |
1130 | } else if (document["bits"].is_null() && document["algorithm"].is_null()) { |
1131 | auto keyData = stringFromJson(document, privatekey_fieldname); | |
997cab68 BZ |
1132 | DNSKEYRecordContent dkrc; |
1133 | DNSSECPrivateKey dpk; | |
60b0a236 | 1134 | try { |
997cab68 BZ |
1135 | shared_ptr<DNSCryptoKeyEngine> dke(DNSCryptoKeyEngine::makeFromISCString(dkrc, keyData)); |
1136 | dpk.d_algorithm = dkrc.d_algorithm; | |
5d9c6182 | 1137 | // TODO remove in 4.2.0 |
902c4e9c CH |
1138 | if(dpk.d_algorithm == DNSSECKeeper::RSASHA1NSEC3SHA1) |
1139 | dpk.d_algorithm = DNSSECKeeper::RSASHA1; | |
997cab68 BZ |
1140 | |
1141 | if (keyOrZone) | |
1142 | dpk.d_flags = 257; | |
1143 | else | |
1144 | dpk.d_flags = 256; | |
1145 | ||
1146 | dpk.setKey(dke); | |
997cab68 | 1147 | } |
60b0a236 BZ |
1148 | catch (std::runtime_error& error) { |
1149 | throw ApiException("Key could not be parsed. Make sure your key format is correct."); | |
1150 | } try { | |
b727e19b RG |
1151 | if (!dk->addKey(zonename, dpk,insertedId, active)) { |
1152 | throw ApiException("Adding key failed, perhaps DNSSEC not enabled in configuration?"); | |
1153 | } | |
60b0a236 | 1154 | } catch (std::runtime_error& error) { |
997cab68 BZ |
1155 | throw ApiException(error.what()); |
1156 | } | |
1157 | if (insertedId < 0) | |
1158 | throw ApiException("Adding key failed, perhaps DNSSEC not enabled in configuration?"); | |
60b0a236 | 1159 | } else { |
5d9c6182 | 1160 | throw ApiException("Either you submit just the 'privatekey' field or you leave 'privatekey' empty and submit the other fields."); |
997cab68 | 1161 | } |
60b0a236 | 1162 | apiZoneCryptokeysGET(zonename, insertedId, resp, dk); |
997cab68 | 1163 | resp->status = 201; |
60b0a236 | 1164 | } |
997cab68 BZ |
1165 | |
1166 | /* | |
1167 | * This method handles PUT (execute) requests for URL /api/v1/servers/:server_id/zones/:zone_name/cryptokeys/:cryptokey_id . | |
1168 | * It de/activates a key from :zone_name specified by :cryptokey_id. | |
1169 | * Server Answers: | |
60b0a236 | 1170 | * Case 1: invalid JSON data |
997cab68 | 1171 | * The server returns 400 Bad Request |
60b0a236 BZ |
1172 | * Case 2: the backend returns true on de/activation. This means the key is de/active. |
1173 | * The server returns 204 No Content | |
955cbfd0 | 1174 | * Case 3: the backend returns false on de/activation. An error occurred. |
997cab68 BZ |
1175 | * The sever returns 422 Unprocessable Entity with message "Could not de/activate Key: :cryptokey_id in Zone: :zone_name" |
1176 | * */ | |
60b0a236 | 1177 | static void apiZoneCryptokeysPUT(DNSName zonename, int inquireKeyId, HttpRequest *req, HttpResponse *resp, DNSSECKeeper *dk) { |
997cab68 BZ |
1178 | //throws an exception if the Body is empty |
1179 | auto document = req->json(); | |
1180 | //throws an exception if the key does not exist or is not a bool | |
1181 | bool active = boolFromJson(document, "active"); | |
60b0a236 BZ |
1182 | if (active) { |
1183 | if (!dk->activateKey(zonename, inquireKeyId)) { | |
997cab68 BZ |
1184 | resp->setErrorResult("Could not activate Key: " + req->parameters["key_id"] + " in Zone: " + zonename.toString(), 422); |
1185 | return; | |
1186 | } | |
1187 | } else { | |
60b0a236 | 1188 | if (!dk->deactivateKey(zonename, inquireKeyId)) { |
997cab68 BZ |
1189 | resp->setErrorResult("Could not deactivate Key: " + req->parameters["key_id"] + " in Zone: " + zonename.toString(), 422); |
1190 | return; | |
1191 | } | |
1192 | } | |
60b0a236 BZ |
1193 | resp->body = ""; |
1194 | resp->status = 204; | |
1195 | return; | |
997cab68 BZ |
1196 | } |
1197 | ||
1198 | /* | |
1199 | * This method chooses the right functionality for the request. It also checks for a cryptokey_id which has to be passed | |
1200 | * by URL /api/v1/servers/:server_id/zones/:zone_name/cryptokeys/:cryptokey_id . | |
1201 | * If the the HTTP-request-method isn't supported, the function returns a response with the 405 code (method not allowed). | |
1202 | * */ | |
1203 | static void apiZoneCryptokeys(HttpRequest *req, HttpResponse *resp) { | |
1204 | DNSName zonename = apiZoneIdToName(req->parameters["id"]); | |
1205 | ||
60b0a236 BZ |
1206 | UeberBackend B; |
1207 | DNSSECKeeper dk(&B); | |
1208 | DomainInfo di; | |
77bfe8de PL |
1209 | if (!B.getDomainInfo(zonename, di)) { |
1210 | throw HttpNotFoundException(); | |
1211 | } | |
60b0a236 | 1212 | |
997cab68 BZ |
1213 | int inquireKeyId = -1; |
1214 | if (req->parameters.count("key_id")) { | |
1215 | inquireKeyId = std::stoi(req->parameters["key_id"]); | |
71de13d7 | 1216 | apiZoneCryptoKeysCheckKeyExists(zonename, inquireKeyId, &dk); |
997cab68 BZ |
1217 | } |
1218 | ||
1219 | if (req->method == "GET") { | |
60b0a236 | 1220 | apiZoneCryptokeysGET(zonename, inquireKeyId, resp, &dk); |
1abc1df5 | 1221 | } else if (req->method == "DELETE" && !::arg().mustDo("api-readonly")) { |
60b0a236 BZ |
1222 | if (inquireKeyId == -1) |
1223 | throw HttpBadRequestException(); | |
1224 | apiZoneCryptokeysDELETE(zonename, inquireKeyId, req, resp, &dk); | |
1abc1df5 | 1225 | } else if (req->method == "POST" && !::arg().mustDo("api-readonly")) { |
60b0a236 | 1226 | apiZoneCryptokeysPOST(zonename, req, resp, &dk); |
1abc1df5 | 1227 | } else if (req->method == "PUT" && !::arg().mustDo("api-readonly")) { |
60b0a236 BZ |
1228 | if (inquireKeyId == -1) |
1229 | throw HttpBadRequestException(); | |
1230 | apiZoneCryptokeysPUT(zonename, inquireKeyId, req, resp, &dk); | |
997cab68 BZ |
1231 | } else { |
1232 | throw HttpMethodNotAllowedException(); //Returns method not allowed | |
1233 | } | |
4b7f120a MS |
1234 | } |
1235 | ||
1f68b185 | 1236 | static void gatherRecordsFromZone(const std::string& zonestring, vector<DNSResourceRecord>& new_records, DNSName zonename) { |
0f0e73fe MS |
1237 | DNSResourceRecord rr; |
1238 | vector<string> zonedata; | |
1f68b185 | 1239 | stringtok(zonedata, zonestring, "\r\n"); |
0f0e73fe MS |
1240 | |
1241 | ZoneParserTNG zpt(zonedata, zonename); | |
1242 | ||
1243 | bool seenSOA=false; | |
1244 | ||
1245 | string comment = "Imported via the API"; | |
1246 | ||
1247 | try { | |
1248 | while(zpt.get(rr, &comment)) { | |
1249 | if(seenSOA && rr.qtype.getCode() == QType::SOA) | |
1250 | continue; | |
1251 | if(rr.qtype.getCode() == QType::SOA) | |
1252 | seenSOA=true; | |
24ded6cc | 1253 | validateGatheredRRType(rr); |
0f0e73fe | 1254 | |
0f0e73fe MS |
1255 | new_records.push_back(rr); |
1256 | } | |
1257 | } | |
1258 | catch(std::exception& ae) { | |
1af62161 | 1259 | throw ApiException("An error occurred while parsing the zonedata: "+string(ae.what())); |
0f0e73fe MS |
1260 | } |
1261 | } | |
1262 | ||
e3675a8a CH |
1263 | /** Throws ApiException if records with duplicate name/type/content are present. |
1264 | * NOTE: sorts records in-place. | |
1265 | */ | |
1266 | static void checkDuplicateRecords(vector<DNSResourceRecord>& records) { | |
1267 | sort(records.begin(), records.end(), | |
1268 | [](const DNSResourceRecord& rec_a, const DNSResourceRecord& rec_b) -> bool { | |
1269 | return rec_a.qname.toString() > rec_b.qname.toString() || \ | |
1270 | rec_a.qtype.getCode() > rec_b.qtype.getCode() || \ | |
1271 | rec_a.content < rec_b.content; | |
1272 | } | |
1273 | ); | |
1274 | DNSResourceRecord previous; | |
1275 | for(const auto& rec : records) { | |
1276 | if (previous.qtype == rec.qtype && previous.qname == rec.qname && previous.content == rec.content) { | |
1277 | throw ApiException("Duplicate record in RRset " + rec.qname.toString() + " IN " + rec.qtype.getName() + " with content \"" + rec.content + "\""); | |
1278 | } | |
1279 | previous = rec; | |
1280 | } | |
1281 | } | |
1282 | ||
6f16f97c PL |
1283 | static void checkTSIGKey(UeberBackend& B, const DNSName& keyname, const DNSName& algo, const string& content) { |
1284 | DNSName algoFromDB; | |
1285 | string contentFromDB; | |
1286 | B.getTSIGKey(keyname, &algoFromDB, &contentFromDB); | |
1287 | if (!contentFromDB.empty() || !algoFromDB.empty()) { | |
1288 | throw ApiException("A TSIG key with the name '"+keyname.toLogString()+"' already exists"); | |
fa07a3cf PL |
1289 | } |
1290 | ||
6f16f97c PL |
1291 | TSIGHashEnum the; |
1292 | if (!getTSIGHashEnum(algo, the)) { | |
1293 | throw ApiException("Unknown TSIG algorithm: " + algo.toLogString()); | |
1294 | } | |
fa07a3cf | 1295 | |
6f16f97c PL |
1296 | string b64out; |
1297 | if (B64Decode(content, b64out) == -1) { | |
1298 | throw ApiException("TSIG content '" + content + "' cannot be base64-decoded"); | |
fa07a3cf | 1299 | } |
6f16f97c | 1300 | } |
fa07a3cf | 1301 | |
6f16f97c PL |
1302 | static Json::object makeJSONTSIGKey(const DNSName& keyname, const DNSName& algo, const string& content) { |
1303 | Json::object tsigkey = { | |
1304 | { "name", keyname.toStringNoDot() }, | |
1305 | { "id", apiZoneNameToId(keyname) }, | |
1306 | { "algorithm", algo.toStringNoDot() }, | |
1307 | { "key", content }, | |
1308 | { "type", "TSIGKey" } | |
1309 | }; | |
1310 | return tsigkey; | |
1311 | } | |
fa07a3cf | 1312 | |
6f16f97c PL |
1313 | static Json::object makeJSONTSIGKey(const struct TSIGKey& key) { |
1314 | return makeJSONTSIGKey(key.name, key.algorithm, key.key); | |
1315 | } | |
1316 | ||
1317 | static void apiServerTsigKeys(HttpRequest* req, HttpResponse* resp) { | |
1318 | UeberBackend B; | |
1319 | if (req->method == "GET") { | |
1320 | vector<struct TSIGKey> keys; | |
1321 | ||
1322 | if (!B.getTSIGKeys(keys)) { | |
1323 | throw ApiException("Unable to retrieve TSIG keys"); | |
1324 | } | |
1325 | ||
1326 | Json::array doc; | |
1327 | ||
1328 | for(const auto &key : keys) { | |
1329 | doc.push_back(makeJSONTSIGKey(key)); | |
1330 | } | |
1331 | resp->setBody(doc); | |
81c39bc6 | 1332 | } else if (req->method == "POST" && !::arg().mustDo("api-readonly")) { |
6f16f97c PL |
1333 | auto document = req->json(); |
1334 | DNSName keyname(stringFromJson(document, "name")); | |
1335 | DNSName algo(stringFromJson(document, "algorithm")); | |
1336 | string content(stringFromJson(document, "key")); | |
1337 | ||
1338 | if (content.empty()) { | |
1339 | size_t klen = 64; | |
1340 | if (algo.toStringNoDot() == "hmac-md5" | |
1341 | || algo.toStringNoDot() == "hmac-sha1" | |
1342 | || algo.toStringNoDot() == "hmac-sha224") { | |
1343 | klen = 32; | |
1344 | } | |
1345 | char tmpkey[64]; | |
1346 | for(size_t i = 0; i < klen; i+=4) { | |
1347 | *(unsigned int*)(tmpkey+i) = dns_random(0xffffffff); | |
1348 | } | |
1349 | content = Base64Encode(std::string(tmpkey, klen)); | |
1350 | } | |
1351 | ||
1352 | // Will throw and ApiException on error | |
1353 | checkTSIGKey(B, keyname, algo, content); | |
1354 | ||
1355 | if(!B.setTSIGKey(keyname, algo, content)) { | |
1356 | throw ApiException("Unable to add TSIG key"); | |
1357 | } | |
1358 | ||
1359 | resp->status = 201; | |
1360 | resp->setBody(makeJSONTSIGKey(keyname, algo, content)); | |
81c39bc6 PL |
1361 | } else { |
1362 | throw HttpMethodNotAllowedException(); | |
6f16f97c | 1363 | } |
fa07a3cf PL |
1364 | } |
1365 | ||
1366 | static void apiServerTsigKeyDetail(HttpRequest* req, HttpResponse* resp) { | |
fa07a3cf | 1367 | UeberBackend B; |
81c39bc6 | 1368 | DNSName keyname = apiZoneIdToName(req->parameters["id"]); |
fa07a3cf PL |
1369 | DNSName algo; |
1370 | string content; | |
1371 | ||
1372 | if (!B.getTSIGKey(keyname, &algo, &content)) { | |
1373 | throw ApiException("Unable to retrieve TSIG key with id '"+keyname.toLogString()+"'"); | |
1374 | } | |
1375 | ||
81c39bc6 PL |
1376 | json11::Json document; |
1377 | ||
1378 | if (!req->body.empty()) { | |
1379 | document = req->json(); | |
1380 | } | |
1381 | ||
1382 | struct TSIGKey tsk; | |
1383 | tsk.name = keyname; | |
1384 | tsk.algorithm = algo; | |
1385 | tsk.key = content; | |
1386 | ||
1387 | if (req->method == "GET") { | |
1388 | resp->setBody(makeJSONTSIGKey(tsk)); | |
1389 | } else if (req->method == "PUT" && !::arg().mustDo("api-readonly")) { | |
1390 | if (document["name"].is_string()) { | |
1391 | tsk.name = DNSName(document["name"].string_value()); | |
1392 | } | |
1393 | if (document["algorithm"].is_string()) { | |
1394 | tsk.algorithm = DNSName(document["algorithm"].string_value()); | |
1395 | ||
1396 | TSIGHashEnum the; | |
1397 | if (!getTSIGHashEnum(tsk.algorithm, the)) { | |
1398 | throw ApiException("Unknown TSIG algorithm: " + tsk.algorithm.toLogString()); | |
1399 | } | |
1400 | } | |
1401 | if (document["key"].is_string()) { | |
1402 | string new_content = document["key"].string_value(); | |
1403 | string decoded; | |
1404 | if (B64Decode(new_content, decoded) == -1) { | |
1405 | throw ApiException("Can not base64 decode key content '" + new_content + "'"); | |
1406 | } | |
1407 | tsk.key = new_content; | |
1408 | } | |
1409 | if (!B.setTSIGKey(tsk.name, tsk.algorithm, tsk.key)) { | |
1410 | throw ApiException("Unable to save TSIG Key"); | |
1411 | } | |
1412 | if (tsk.name != keyname) { | |
1413 | // Remove the old key | |
1414 | if (!B.deleteTSIGKey(keyname)) { | |
1415 | throw ApiException("Unable to remove TSIG key '" + keyname.toStringNoDot() + "'"); | |
1416 | } | |
1417 | } | |
1418 | resp->setBody(makeJSONTSIGKey(tsk)); | |
1419 | } else if (req->method == "DELETE" && !::arg().mustDo("api-readonly")) { | |
1420 | if (!B.deleteTSIGKey(keyname)) { | |
1421 | throw ApiException("Unable to remove TSIG key '" + keyname.toStringNoDot() + "'"); | |
1422 | } else { | |
1423 | resp->body = ""; | |
1424 | resp->status = 204; | |
1425 | } | |
1426 | } else { | |
1427 | throw HttpMethodNotAllowedException(); | |
1428 | } | |
fa07a3cf PL |
1429 | } |
1430 | ||
80d59cd1 | 1431 | static void apiServerZones(HttpRequest* req, HttpResponse* resp) { |
e2dba705 | 1432 | UeberBackend B; |
53942520 | 1433 | DNSSECKeeper dk(&B); |
d07bf7ff | 1434 | if (req->method == "POST" && !::arg().mustDo("api-readonly")) { |
e2dba705 | 1435 | DomainInfo di; |
1f68b185 | 1436 | auto document = req->json(); |
c576d0c5 | 1437 | DNSName zonename = apiNameToDNSName(stringFromJson(document, "name")); |
1d6b70f9 | 1438 | apiCheckNameAllowedCharacters(zonename.toString()); |
e3675a8a | 1439 | zonename.makeUsLowerCase(); |
4ebf78b1 | 1440 | |
1d6b70f9 | 1441 | bool exists = B.getDomainInfo(zonename, di); |
e2dba705 | 1442 | if(exists) |
331d3062 | 1443 | throw HttpConflictException(); |
e2dba705 | 1444 | |
bb9fd223 | 1445 | // validate 'kind' is set |
4bdff352 | 1446 | DomainInfo::DomainKind zonekind = DomainInfo::stringToKind(stringFromJson(document, "kind")); |
bb9fd223 | 1447 | |
6754ef71 CH |
1448 | string zonestring = document["zone"].string_value(); |
1449 | auto rrsets = document["rrsets"]; | |
1450 | if (rrsets.is_array() && zonestring != "") | |
1451 | throw ApiException("You cannot give rrsets AND zone data as text"); | |
0f0e73fe | 1452 | |
1f68b185 CH |
1453 | auto nameservers = document["nameservers"]; |
1454 | if (!nameservers.is_array() && zonekind != DomainInfo::Slave) | |
f63168e6 | 1455 | throw ApiException("Nameservers list must be given (but can be empty if NS records are supplied)"); |
e2dba705 | 1456 | |
f63168e6 | 1457 | string soa_edit_api_kind; |
1f68b185 CH |
1458 | if (document["soa_edit_api"].is_string()) { |
1459 | soa_edit_api_kind = document["soa_edit_api"].string_value(); | |
a6448d95 CH |
1460 | } |
1461 | else { | |
1462 | soa_edit_api_kind = "DEFAULT"; | |
1463 | } | |
1f68b185 | 1464 | string soa_edit_kind = document["soa_edit"].string_value(); |
e90b4e38 | 1465 | |
f63168e6 CH |
1466 | // if records/comments are given, load and check them |
1467 | bool have_soa = false; | |
33e6c3e9 | 1468 | bool have_zone_ns = false; |
f63168e6 CH |
1469 | vector<DNSResourceRecord> new_records; |
1470 | vector<Comment> new_comments; | |
1471 | vector<DNSResourceRecord> new_ptrs; | |
0f0e73fe | 1472 | |
6754ef71 CH |
1473 | if (rrsets.is_array()) { |
1474 | for (const auto& rrset : rrsets.array_items()) { | |
1475 | DNSName qname = apiNameToDNSName(stringFromJson(rrset, "name")); | |
1476 | apiCheckQNameAllowedCharacters(qname.toString()); | |
1477 | QType qtype; | |
1478 | qtype = stringFromJson(rrset, "type"); | |
1479 | if (qtype.getCode() == 0) { | |
1480 | throw ApiException("RRset "+qname.toString()+" IN "+stringFromJson(rrset, "type")+": unknown type given"); | |
1481 | } | |
1482 | if (rrset["records"].is_array()) { | |
1483 | int ttl = intFromJson(rrset, "ttl"); | |
1484 | gatherRecords(rrset, qname, qtype, ttl, new_records, new_ptrs); | |
1485 | } | |
1486 | if (rrset["comments"].is_array()) { | |
1487 | gatherComments(rrset, qname, qtype, new_comments); | |
1488 | } | |
1489 | } | |
0f0e73fe | 1490 | } else if (zonestring != "") { |
1f68b185 | 1491 | gatherRecordsFromZone(zonestring, new_records, zonename); |
0f0e73fe MS |
1492 | } |
1493 | ||
1f68b185 | 1494 | for(auto& rr : new_records) { |
e3675a8a | 1495 | rr.qname.makeUsLowerCase(); |
1d6b70f9 | 1496 | if (!rr.qname.isPartOf(zonename) && rr.qname != zonename) |
561434a6 | 1497 | throw ApiException("RRset "+rr.qname.toString()+" IN "+rr.qtype.getName()+": Name is out of zone"); |
cb9b5901 | 1498 | apiCheckQNameAllowedCharacters(rr.qname.toString()); |
f63168e6 | 1499 | |
1d6b70f9 | 1500 | if (rr.qtype.getCode() == QType::SOA && rr.qname==zonename) { |
f63168e6 | 1501 | have_soa = true; |
a6448d95 | 1502 | increaseSOARecord(rr, soa_edit_api_kind, soa_edit_kind); |
f63168e6 | 1503 | } |
33e6c3e9 CH |
1504 | if (rr.qtype.getCode() == QType::NS && rr.qname==zonename) { |
1505 | have_zone_ns = true; | |
1506 | } | |
f63168e6 | 1507 | } |
f7bfeb30 CH |
1508 | |
1509 | // synthesize RRs as needed | |
1510 | DNSResourceRecord autorr; | |
1d6b70f9 | 1511 | autorr.qname = zonename; |
f7bfeb30 CH |
1512 | autorr.auth = 1; |
1513 | autorr.ttl = ::arg().asNum("default-ttl"); | |
e2dba705 | 1514 | |
4de11a54 | 1515 | if (!have_soa && zonekind != DomainInfo::Slave) { |
f63168e6 | 1516 | // synthesize a SOA record so the zone "really" exists |
13f9e280 | 1517 | string soa = (boost::format("%s %s %ul") |
1d6b70f9 CH |
1518 | % ::arg()["default-soa-name"] |
1519 | % (::arg().isEmpty("default-soa-mail") ? (DNSName("hostmaster.") + zonename).toString() : ::arg()["default-soa-mail"]) | |
1f68b185 | 1520 | % document["serial"].int_value() |
1d6b70f9 | 1521 | ).str(); |
f63168e6 | 1522 | SOAData sd; |
1d6b70f9 | 1523 | fillSOAData(soa, sd); // fills out default values for us |
13f9e280 CH |
1524 | autorr.qtype = QType::SOA; |
1525 | autorr.content = makeSOAContent(sd)->getZoneRepresentation(true); | |
f7bfeb30 CH |
1526 | increaseSOARecord(autorr, soa_edit_api_kind, soa_edit_kind); |
1527 | new_records.push_back(autorr); | |
f63168e6 CH |
1528 | } |
1529 | ||
1530 | // create NS records if nameservers are given | |
1f68b185 CH |
1531 | for (auto value : nameservers.array_items()) { |
1532 | string nameserver = value.string_value(); | |
1533 | if (nameserver.empty()) | |
1534 | throw ApiException("Nameservers must be non-empty strings"); | |
1535 | if (!isCanonical(nameserver)) | |
1536 | throw ApiException("Nameserver is not canonical: '" + nameserver + "'"); | |
1537 | try { | |
1538 | // ensure the name parses | |
8f955653 | 1539 | autorr.content = DNSName(nameserver).toStringRootDot(); |
1f68b185 CH |
1540 | } catch (...) { |
1541 | throw ApiException("Unable to parse DNS Name for NS '" + nameserver + "'"); | |
4bdff352 | 1542 | } |
13f9e280 | 1543 | autorr.qtype = QType::NS; |
1f68b185 | 1544 | new_records.push_back(autorr); |
33e6c3e9 CH |
1545 | if (have_zone_ns) { |
1546 | throw ApiException("Nameservers list MUST NOT be mixed with zone-level NS in rrsets"); | |
1547 | } | |
e2dba705 CH |
1548 | } |
1549 | ||
e3675a8a CH |
1550 | checkDuplicateRecords(new_records); |
1551 | ||
986e4858 PL |
1552 | if (boolFromJson(document, "dnssec", false)) { |
1553 | checkDefaultDNSSECAlgos(); | |
1554 | ||
1555 | if(document["nsec3param"].string_value().length() > 0) { | |
1556 | NSEC3PARAMRecordContent ns3pr(document["nsec3param"].string_value()); | |
1557 | string error_msg = ""; | |
1558 | if (!dk.checkNSEC3PARAM(ns3pr, error_msg)) { | |
1559 | throw ApiException("NSEC3PARAMs provided for zone '"+zonename.toString()+"' are invalid. " + error_msg); | |
1560 | } | |
1561 | } | |
1562 | } | |
1563 | ||
f63168e6 | 1564 | // no going back after this |
1d6b70f9 CH |
1565 | if(!B.createDomain(zonename)) |
1566 | throw ApiException("Creating domain '"+zonename.toString()+"' failed"); | |
f63168e6 | 1567 | |
1d6b70f9 CH |
1568 | if(!B.getDomainInfo(zonename, di)) |
1569 | throw ApiException("Creating domain '"+zonename.toString()+"' failed: lookup of domain ID failed"); | |
f63168e6 | 1570 | |
9440a9f0 CH |
1571 | // updateDomainSettingsFromDocument does NOT fill out the default we've established above. |
1572 | if (!soa_edit_api_kind.empty()) { | |
1573 | di.backend->setDomainMetadataOne(zonename, "SOA-EDIT-API", soa_edit_api_kind); | |
1574 | } | |
1575 | ||
1d6b70f9 | 1576 | di.backend->startTransaction(zonename, di.id); |
f63168e6 | 1577 | |
abb873ee | 1578 | for(auto rr : new_records) { |
f63168e6 | 1579 | rr.domain_id = di.id; |
c9b43446 | 1580 | di.backend->feedRecord(rr, DNSName()); |
e2dba705 | 1581 | } |
1d6b70f9 | 1582 | for(Comment& c : new_comments) { |
f63168e6 CH |
1583 | c.domain_id = di.id; |
1584 | di.backend->feedComment(c); | |
1585 | } | |
e2dba705 | 1586 | |
986e4858 | 1587 | updateDomainSettingsFromDocument(B, di, zonename, document); |
e2dba705 | 1588 | |
f63168e6 CH |
1589 | di.backend->commitTransaction(); |
1590 | ||
3fe7c7d6 CH |
1591 | storeChangedPTRs(B, new_ptrs); |
1592 | ||
986e4858 | 1593 | fillZone(zonename, resp, shouldDoRRSets(req)); |
64a36f0d | 1594 | resp->status = 201; |
e2dba705 CH |
1595 | return; |
1596 | } | |
1597 | ||
c67bf8c5 CH |
1598 | if(req->method != "GET") |
1599 | throw HttpMethodNotAllowedException(); | |
1600 | ||
c67bf8c5 | 1601 | vector<DomainInfo> domains; |
cea26350 | 1602 | B.getAllDomains(&domains, true); // incl. disabled |
c67bf8c5 | 1603 | |
62a9a74c CH |
1604 | Json::array doc; |
1605 | for(const DomainInfo& di : domains) { | |
ce846be6 | 1606 | doc.push_back(getZoneInfo(di, &dk)); |
c67bf8c5 | 1607 | } |
669822d0 | 1608 | resp->setBody(doc); |
c67bf8c5 CH |
1609 | } |
1610 | ||
05776d2f | 1611 | static void apiServerZoneDetail(HttpRequest* req, HttpResponse* resp) { |
290a083d | 1612 | DNSName zonename = apiZoneIdToName(req->parameters["id"]); |
05776d2f | 1613 | |
77bfe8de PL |
1614 | UeberBackend B; |
1615 | DomainInfo di; | |
1616 | if (!B.getDomainInfo(zonename, di)) { | |
1617 | throw HttpNotFoundException(); | |
1618 | } | |
1619 | ||
d07bf7ff | 1620 | if(req->method == "PUT" && !::arg().mustDo("api-readonly")) { |
7c0ba3d2 | 1621 | // update domain settings |
7c0ba3d2 | 1622 | |
986e4858 | 1623 | updateDomainSettingsFromDocument(B, di, zonename, req->json()); |
7c0ba3d2 | 1624 | |
f0e76cee CH |
1625 | resp->body = ""; |
1626 | resp->status = 204; // No Content, but indicate success | |
7c0ba3d2 CH |
1627 | return; |
1628 | } | |
d07bf7ff | 1629 | else if(req->method == "DELETE" && !::arg().mustDo("api-readonly")) { |
a462a01d | 1630 | // delete domain |
a462a01d | 1631 | if(!di.backend->deleteDomain(zonename)) |
290a083d | 1632 | throw ApiException("Deleting domain '"+zonename.toString()+"' failed: backend delete failed/unsupported"); |
a462a01d CH |
1633 | |
1634 | // empty body on success | |
1635 | resp->body = ""; | |
37663c3b | 1636 | resp->status = 204; // No Content: declare that the zone is gone now |
a462a01d | 1637 | return; |
d07bf7ff | 1638 | } else if (req->method == "PATCH" && !::arg().mustDo("api-readonly")) { |
d708640f | 1639 | patchZone(req, resp); |
6cc98ddf CH |
1640 | return; |
1641 | } else if (req->method == "GET") { | |
986e4858 | 1642 | fillZone(zonename, resp, shouldDoRRSets(req)); |
6cc98ddf | 1643 | return; |
a462a01d | 1644 | } |
6cc98ddf | 1645 | throw HttpMethodNotAllowedException(); |
05776d2f CH |
1646 | } |
1647 | ||
a83004d3 | 1648 | static void apiServerZoneExport(HttpRequest* req, HttpResponse* resp) { |
290a083d | 1649 | DNSName zonename = apiZoneIdToName(req->parameters["id"]); |
a83004d3 CH |
1650 | |
1651 | if(req->method != "GET") | |
1652 | throw HttpMethodNotAllowedException(); | |
1653 | ||
1654 | ostringstream ss; | |
1655 | ||
1656 | UeberBackend B; | |
1657 | DomainInfo di; | |
77bfe8de PL |
1658 | if (!B.getDomainInfo(zonename, di)) { |
1659 | throw HttpNotFoundException(); | |
1660 | } | |
a83004d3 CH |
1661 | |
1662 | DNSResourceRecord rr; | |
1663 | SOAData sd; | |
1664 | di.backend->list(zonename, di.id); | |
1665 | while(di.backend->get(rr)) { | |
1666 | if (!rr.qtype.getCode()) | |
1667 | continue; // skip empty non-terminals | |
1668 | ||
a83004d3 | 1669 | ss << |
675fa24c | 1670 | rr.qname.toString() << "\t" << |
a83004d3 | 1671 | rr.ttl << "\t" << |
dc420da6 | 1672 | "IN" << "\t" << |
a83004d3 | 1673 | rr.qtype.getName() << "\t" << |
1d6b70f9 | 1674 | makeApiRecordContent(rr.qtype, rr.content) << |
a83004d3 CH |
1675 | endl; |
1676 | } | |
1677 | ||
1678 | if (req->accept_json) { | |
41873e7c | 1679 | resp->setBody(Json::object { { "zone", ss.str() } }); |
a83004d3 CH |
1680 | } else { |
1681 | resp->headers["Content-Type"] = "text/plain; charset=us-ascii"; | |
1682 | resp->body = ss.str(); | |
1683 | } | |
1684 | } | |
1685 | ||
a426cb89 | 1686 | static void apiServerZoneAxfrRetrieve(HttpRequest* req, HttpResponse* resp) { |
290a083d | 1687 | DNSName zonename = apiZoneIdToName(req->parameters["id"]); |
a426cb89 | 1688 | |
136965be | 1689 | if(req->method != "PUT" || ::arg().mustDo("api-readonly")) |
a426cb89 CH |
1690 | throw HttpMethodNotAllowedException(); |
1691 | ||
1692 | UeberBackend B; | |
1693 | DomainInfo di; | |
77bfe8de PL |
1694 | if (!B.getDomainInfo(zonename, di)) { |
1695 | throw HttpNotFoundException(); | |
1696 | } | |
a426cb89 CH |
1697 | |
1698 | if(di.masters.empty()) | |
290a083d | 1699 | throw ApiException("Domain '"+zonename.toString()+"' is not a slave domain (or has no master defined)"); |
a426cb89 CH |
1700 | |
1701 | random_shuffle(di.masters.begin(), di.masters.end()); | |
1702 | Communicator.addSuckRequest(zonename, di.masters.front()); | |
9b0f144f | 1703 | resp->setSuccessResult("Added retrieval request for '"+zonename.toString()+"' from master "+di.masters.front().toLogString()); |
a426cb89 CH |
1704 | } |
1705 | ||
1706 | static void apiServerZoneNotify(HttpRequest* req, HttpResponse* resp) { | |
290a083d | 1707 | DNSName zonename = apiZoneIdToName(req->parameters["id"]); |
a426cb89 | 1708 | |
136965be | 1709 | if(req->method != "PUT" || ::arg().mustDo("api-readonly")) |
a426cb89 CH |
1710 | throw HttpMethodNotAllowedException(); |
1711 | ||
1712 | UeberBackend B; | |
1713 | DomainInfo di; | |
77bfe8de PL |
1714 | if (!B.getDomainInfo(zonename, di)) { |
1715 | throw HttpNotFoundException(); | |
1716 | } | |
a426cb89 CH |
1717 | |
1718 | if(!Communicator.notifyDomain(zonename)) | |
1719 | throw ApiException("Failed to add to the queue - see server log"); | |
1720 | ||
692829aa | 1721 | resp->setSuccessResult("Notification queued"); |
a426cb89 CH |
1722 | } |
1723 | ||
4bc8379e PL |
1724 | static void apiServerZoneRectify(HttpRequest* req, HttpResponse* resp) { |
1725 | DNSName zonename = apiZoneIdToName(req->parameters["id"]); | |
1726 | ||
1727 | if(req->method != "PUT") | |
1728 | throw HttpMethodNotAllowedException(); | |
1729 | ||
1730 | UeberBackend B; | |
1731 | DomainInfo di; | |
77bfe8de PL |
1732 | if (!B.getDomainInfo(zonename, di)) { |
1733 | throw HttpNotFoundException(); | |
1734 | } | |
4bc8379e PL |
1735 | |
1736 | DNSSECKeeper dk(&B); | |
1737 | ||
1738 | if (!dk.isSecuredZone(zonename)) | |
1739 | throw ApiException("Zone '" + zonename.toString() + "' is not DNSSEC signed, not rectifying."); | |
1740 | ||
1741 | if (di.kind == DomainInfo::Slave) | |
1742 | throw ApiException("Zone '" + zonename.toString() + "' is a slave zone, not rectifying."); | |
1743 | ||
1744 | string error_msg = ""; | |
59102608 RG |
1745 | string info; |
1746 | if (!dk.rectifyZone(zonename, error_msg, info, true)) | |
4bc8379e PL |
1747 | throw ApiException("Failed to rectify '" + zonename.toString() + "' " + error_msg); |
1748 | ||
1749 | resp->setSuccessResult("Rectified"); | |
1750 | } | |
1751 | ||
d1587ceb CH |
1752 | static void makePtr(const DNSResourceRecord& rr, DNSResourceRecord* ptr) { |
1753 | if (rr.qtype.getCode() == QType::A) { | |
1754 | uint32_t ip; | |
1755 | if (!IpToU32(rr.content, &ip)) { | |
1756 | throw ApiException("PTR: Invalid IP address given"); | |
1757 | } | |
1d6b70f9 | 1758 | ptr->qname = DNSName((boost::format("%u.%u.%u.%u.in-addr.arpa.") |
d1587ceb CH |
1759 | % ((ip >> 24) & 0xff) |
1760 | % ((ip >> 16) & 0xff) | |
1761 | % ((ip >> 8) & 0xff) | |
1762 | % ((ip ) & 0xff) | |
1d6b70f9 | 1763 | ).str()); |
d1587ceb CH |
1764 | } else if (rr.qtype.getCode() == QType::AAAA) { |
1765 | ComboAddress ca(rr.content); | |
5fb3aa58 | 1766 | char buf[3]; |
d1587ceb | 1767 | ostringstream ss; |
5fb3aa58 CH |
1768 | for (int octet = 0; octet < 16; ++octet) { |
1769 | if (snprintf(buf, sizeof(buf), "%02x", ca.sin6.sin6_addr.s6_addr[octet]) != (sizeof(buf)-1)) { | |
1770 | // this should be impossible: no byte should give more than two digits in hex format | |
1771 | throw PDNSException("Formatting IPv6 address failed"); | |
1772 | } | |
1773 | ss << buf[0] << '.' << buf[1] << '.'; | |
d1587ceb | 1774 | } |
5fb3aa58 CH |
1775 | string tmp = ss.str(); |
1776 | tmp.resize(tmp.size()-1); // remove last dot | |
1777 | // reverse and append arpa domain | |
1d6b70f9 | 1778 | ptr->qname = DNSName(string(tmp.rbegin(), tmp.rend())) + DNSName("ip6.arpa."); |
d1587ceb | 1779 | } else { |
675fa24c | 1780 | throw ApiException("Unsupported PTR source '" + rr.qname.toString() + "' type '" + rr.qtype.getName() + "'"); |
d1587ceb CH |
1781 | } |
1782 | ||
1783 | ptr->qtype = "PTR"; | |
1784 | ptr->ttl = rr.ttl; | |
1785 | ptr->disabled = rr.disabled; | |
8f955653 | 1786 | ptr->content = rr.qname.toStringRootDot(); |
d1587ceb CH |
1787 | } |
1788 | ||
995473c8 CH |
1789 | static void storeChangedPTRs(UeberBackend& B, vector<DNSResourceRecord>& new_ptrs) { |
1790 | for(const DNSResourceRecord& rr : new_ptrs) { | |
995473c8 | 1791 | SOAData sd; |
cec52de6 | 1792 | if (!B.getAuth(rr.qname, QType(QType::PTR), &sd, false)) |
995473c8 CH |
1793 | throw ApiException("Could not find domain for PTR '"+rr.qname.toString()+"' requested for '"+rr.content+"' (while saving)"); |
1794 | ||
1795 | string soa_edit_api_kind; | |
1796 | string soa_edit_kind; | |
1797 | bool soa_changed = false; | |
1798 | DNSResourceRecord soarr; | |
1799 | sd.db->getDomainMetadataOne(sd.qname, "SOA-EDIT-API", soa_edit_api_kind); | |
1800 | sd.db->getDomainMetadataOne(sd.qname, "SOA-EDIT", soa_edit_kind); | |
1801 | if (!soa_edit_api_kind.empty()) { | |
13f9e280 | 1802 | soa_changed = makeIncreasedSOARecord(sd, soa_edit_api_kind, soa_edit_kind, soarr); |
995473c8 CH |
1803 | } |
1804 | ||
1805 | sd.db->startTransaction(sd.qname); | |
1806 | if (!sd.db->replaceRRSet(sd.domain_id, rr.qname, rr.qtype, vector<DNSResourceRecord>(1, rr))) { | |
1807 | sd.db->abortTransaction(); | |
1808 | throw ApiException("PTR-Hosting backend for "+rr.qname.toString()+"/"+rr.qtype.getName()+" does not support editing records."); | |
1809 | } | |
1810 | ||
1811 | if (soa_changed) { | |
1812 | sd.db->replaceRRSet(sd.domain_id, soarr.qname, soarr.qtype, vector<DNSResourceRecord>(1, soarr)); | |
1813 | } | |
1814 | ||
1815 | sd.db->commitTransaction(); | |
bf269e28 | 1816 | purgeAuthCachesExact(rr.qname); |
995473c8 CH |
1817 | } |
1818 | } | |
1819 | ||
d708640f | 1820 | static void patchZone(HttpRequest* req, HttpResponse* resp) { |
b3905a3d CH |
1821 | UeberBackend B; |
1822 | DomainInfo di; | |
290a083d | 1823 | DNSName zonename = apiZoneIdToName(req->parameters["id"]); |
77bfe8de PL |
1824 | if (!B.getDomainInfo(zonename, di)) { |
1825 | throw HttpNotFoundException(); | |
1826 | } | |
b3905a3d | 1827 | |
f63168e6 CH |
1828 | vector<DNSResourceRecord> new_records; |
1829 | vector<Comment> new_comments; | |
d708640f CH |
1830 | vector<DNSResourceRecord> new_ptrs; |
1831 | ||
1f68b185 | 1832 | Json document = req->json(); |
b3905a3d | 1833 | |
1f68b185 CH |
1834 | auto rrsets = document["rrsets"]; |
1835 | if (!rrsets.is_array()) | |
d708640f | 1836 | throw ApiException("No rrsets given in update request"); |
b3905a3d | 1837 | |
d708640f | 1838 | di.backend->startTransaction(zonename); |
6cc98ddf | 1839 | |
d708640f | 1840 | try { |
d29d5db7 | 1841 | string soa_edit_api_kind; |
a6448d95 | 1842 | string soa_edit_kind; |
d29d5db7 | 1843 | di.backend->getDomainMetadataOne(zonename, "SOA-EDIT-API", soa_edit_api_kind); |
a6448d95 | 1844 | di.backend->getDomainMetadataOne(zonename, "SOA-EDIT", soa_edit_kind); |
d29d5db7 CH |
1845 | bool soa_edit_done = false; |
1846 | ||
2b048cc7 PD |
1847 | set<pair<DNSName, QType>> seen; |
1848 | ||
6754ef71 CH |
1849 | for (const auto& rrset : rrsets.array_items()) { |
1850 | string changetype = toUpper(stringFromJson(rrset, "changetype")); | |
c576d0c5 | 1851 | DNSName qname = apiNameToDNSName(stringFromJson(rrset, "name")); |
cb9b5901 | 1852 | apiCheckQNameAllowedCharacters(qname.toString()); |
6754ef71 | 1853 | QType qtype; |
d708640f | 1854 | qtype = stringFromJson(rrset, "type"); |
6754ef71 CH |
1855 | if (qtype.getCode() == 0) { |
1856 | throw ApiException("RRset "+qname.toString()+" IN "+stringFromJson(rrset, "type")+": unknown type given"); | |
1857 | } | |
d708640f | 1858 | |
2b048cc7 PD |
1859 | if(seen.count({qname, qtype})) |
1860 | { | |
3216c7db | 1861 | throw ApiException("Duplicate RRset "+qname.toString()+" IN "+qtype.getName()); |
2b048cc7 PD |
1862 | } |
1863 | seen.insert({qname, qtype}); | |
d708640f | 1864 | |
d708640f | 1865 | if (changetype == "DELETE") { |
b7f21ab1 | 1866 | // delete all matching qname/qtype RRs (and, implicitly comments). |
d708640f CH |
1867 | if (!di.backend->replaceRRSet(di.id, qname, qtype, vector<DNSResourceRecord>())) { |
1868 | throw ApiException("Hosting backend does not support editing records."); | |
6cc98ddf | 1869 | } |
d708640f CH |
1870 | } |
1871 | else if (changetype == "REPLACE") { | |
1d6b70f9 | 1872 | // we only validate for REPLACE, as DELETE can be used to "fix" out of zone records. |
e325f20c | 1873 | if (!qname.isPartOf(zonename) && qname != zonename) |
edda67a2 | 1874 | throw ApiException("RRset "+qname.toString()+" IN "+qtype.getName()+": Name is out of zone"); |
34df6ecc | 1875 | |
6754ef71 CH |
1876 | bool replace_records = rrset["records"].is_array(); |
1877 | bool replace_comments = rrset["comments"].is_array(); | |
f63168e6 | 1878 | |
6754ef71 CH |
1879 | if (!replace_records && !replace_comments) { |
1880 | throw ApiException("No change for RRset " + qname.toString() + " IN " + qtype.getName()); | |
1881 | } | |
f63168e6 | 1882 | |
6754ef71 CH |
1883 | new_records.clear(); |
1884 | new_comments.clear(); | |
f63168e6 | 1885 | |
6754ef71 CH |
1886 | if (replace_records) { |
1887 | // ttl shouldn't be part of DELETE, and it shouldn't be required if we don't get new records. | |
1888 | int ttl = intFromJson(rrset, "ttl"); | |
1889 | // new_ptrs is merged. | |
1890 | gatherRecords(rrset, qname, qtype, ttl, new_records, new_ptrs); | |
1891 | ||
1892 | for(DNSResourceRecord& rr : new_records) { | |
1893 | rr.domain_id = di.id; | |
1894 | if (rr.qtype.getCode() == QType::SOA && rr.qname==zonename) { | |
1895 | soa_edit_done = increaseSOARecord(rr, soa_edit_api_kind, soa_edit_kind); | |
6754ef71 | 1896 | } |
d708640f | 1897 | } |
e3675a8a | 1898 | checkDuplicateRecords(new_records); |
6cc98ddf CH |
1899 | } |
1900 | ||
6754ef71 CH |
1901 | if (replace_comments) { |
1902 | gatherComments(rrset, qname, qtype, new_comments); | |
f63168e6 | 1903 | |
6754ef71 CH |
1904 | for(Comment& c : new_comments) { |
1905 | c.domain_id = di.id; | |
1906 | } | |
d708640f | 1907 | } |
b3905a3d | 1908 | |
d708640f | 1909 | if (replace_records) { |
03b1cc25 | 1910 | bool ent_present = false; |
8560f36a CH |
1911 | di.backend->lookup(QType(QType::ANY), qname); |
1912 | DNSResourceRecord rr; | |
1913 | while (di.backend->get(rr)) { | |
03b1cc25 CH |
1914 | if (qtype.getCode() == 0) { |
1915 | ent_present = true; | |
1916 | } | |
8560f36a CH |
1917 | if (qtype.getCode() == QType::CNAME && rr.qtype.getCode() != QType::CNAME) { |
1918 | throw ApiException("RRset "+qname.toString()+" IN "+qtype.getName()+": Conflicts with pre-existing non-CNAME RRset"); | |
1919 | } else if (qtype.getCode() != QType::CNAME && rr.qtype.getCode() == QType::CNAME) { | |
1920 | throw ApiException("RRset "+qname.toString()+" IN "+qtype.getName()+": Conflicts with pre-existing CNAME RRset"); | |
1921 | } | |
1922 | } | |
1923 | ||
03b1cc25 CH |
1924 | if (!new_records.empty() && ent_present) { |
1925 | QType qt_ent{0}; | |
1926 | if (!di.backend->replaceRRSet(di.id, qname, qt_ent, new_records)) { | |
1927 | throw ApiException("Hosting backend does not support editing records."); | |
1928 | } | |
1929 | } | |
d708640f CH |
1930 | if (!di.backend->replaceRRSet(di.id, qname, qtype, new_records)) { |
1931 | throw ApiException("Hosting backend does not support editing records."); | |
1932 | } | |
1933 | } | |
1934 | if (replace_comments) { | |
1935 | if (!di.backend->replaceComments(di.id, qname, qtype, new_comments)) { | |
1936 | throw ApiException("Hosting backend does not support editing comments."); | |
1937 | } | |
1938 | } | |
6cc98ddf | 1939 | } |
d708640f CH |
1940 | else |
1941 | throw ApiException("Changetype not understood"); | |
6cc98ddf | 1942 | } |
d29d5db7 CH |
1943 | |
1944 | // edit SOA (if needed) | |
1945 | if (!soa_edit_api_kind.empty() && !soa_edit_done) { | |
1946 | SOAData sd; | |
13f9e280 | 1947 | if (!B.getSOAUncached(zonename, sd, true)) |
290a083d | 1948 | throw ApiException("No SOA found for domain '"+zonename.toString()+"'"); |
d29d5db7 CH |
1949 | |
1950 | DNSResourceRecord rr; | |
13f9e280 CH |
1951 | if (makeIncreasedSOARecord(sd, soa_edit_api_kind, soa_edit_kind, rr)) { |
1952 | if (!di.backend->replaceRRSet(di.id, rr.qname, rr.qtype, vector<DNSResourceRecord>(1, rr))) { | |
1953 | throw ApiException("Hosting backend does not support editing records."); | |
1954 | } | |
d29d5db7 | 1955 | } |
3ae63ca8 | 1956 | |
478de03b KW |
1957 | // return old and new serials in headers |
1958 | resp->headers["X-PDNS-Old-Serial"] = std::to_string(sd.serial); | |
3ae63ca8 | 1959 | fillSOAData(rr.content, sd); |
478de03b | 1960 | resp->headers["X-PDNS-New-Serial"] = std::to_string(sd.serial); |
d29d5db7 CH |
1961 | } |
1962 | ||
d708640f CH |
1963 | } catch(...) { |
1964 | di.backend->abortTransaction(); | |
1965 | throw; | |
1966 | } | |
986e4858 | 1967 | |
b0486ea5 | 1968 | DNSSECKeeper dk(&B); |
986e4858 PL |
1969 | string api_rectify; |
1970 | di.backend->getDomainMetadataOne(zonename, "API-RECTIFY", api_rectify); | |
1971 | if (dk.isSecuredZone(zonename) && !dk.isPresigned(zonename) && api_rectify == "1") { | |
1972 | string error_msg = ""; | |
59102608 RG |
1973 | string info; |
1974 | if (!dk.rectifyZone(zonename, error_msg, info, false)) | |
986e4858 PL |
1975 | throw ApiException("Failed to rectify '" + zonename.toString() + "' " + error_msg); |
1976 | } | |
1977 | ||
d708640f | 1978 | di.backend->commitTransaction(); |
b3905a3d | 1979 | |
bf269e28 | 1980 | purgeAuthCachesExact(zonename); |
d1587ceb | 1981 | |
d708640f | 1982 | // now the PTRs |
995473c8 | 1983 | storeChangedPTRs(B, new_ptrs); |
b3905a3d | 1984 | |
f0e76cee CH |
1985 | resp->body = ""; |
1986 | resp->status = 204; // No Content, but indicate success | |
1987 | return; | |
b3905a3d CH |
1988 | } |
1989 | ||
b1902fab CH |
1990 | static void apiServerSearchData(HttpRequest* req, HttpResponse* resp) { |
1991 | if(req->method != "GET") | |
1992 | throw HttpMethodNotAllowedException(); | |
1993 | ||
583ea80d | 1994 | string q = req->getvars["q"]; |
720ed2bd AT |
1995 | string sMax = req->getvars["max"]; |
1996 | int maxEnts = 100; | |
1997 | int ents = 0; | |
1998 | ||
b1902fab CH |
1999 | if (q.empty()) |
2000 | throw ApiException("Query q can't be blank"); | |
606c8752 | 2001 | if (!sMax.empty()) |
335da0ba | 2002 | maxEnts = std::stoi(sMax); |
720ed2bd AT |
2003 | if (maxEnts < 1) |
2004 | throw ApiException("Maximum entries must be larger than 0"); | |
b1902fab | 2005 | |
720ed2bd | 2006 | SimpleMatch sm(q,true); |
b1902fab | 2007 | UeberBackend B; |
b1902fab | 2008 | vector<DomainInfo> domains; |
720ed2bd AT |
2009 | vector<DNSResourceRecord> result_rr; |
2010 | vector<Comment> result_c; | |
1d6b70f9 CH |
2011 | map<int,DomainInfo> zoneIdZone; |
2012 | map<int,DomainInfo>::iterator val; | |
00963dea | 2013 | Json::array doc; |
b1902fab | 2014 | |
720ed2bd | 2015 | B.getAllDomains(&domains, true); |
d2d194a9 | 2016 | |
720ed2bd | 2017 | for(const DomainInfo di: domains) |
1d6b70f9 | 2018 | { |
720ed2bd | 2019 | if (ents < maxEnts && sm.match(di.zone)) { |
00963dea CH |
2020 | doc.push_back(Json::object { |
2021 | { "object_type", "zone" }, | |
2022 | { "zone_id", apiZoneNameToId(di.zone) }, | |
2023 | { "name", di.zone.toString() } | |
2024 | }); | |
720ed2bd | 2025 | ents++; |
b1902fab | 2026 | } |
1d6b70f9 | 2027 | zoneIdZone[di.id] = di; // populate cache |
720ed2bd | 2028 | } |
b1902fab | 2029 | |
720ed2bd AT |
2030 | if (B.searchRecords(q, maxEnts, result_rr)) |
2031 | { | |
2032 | for(const DNSResourceRecord& rr: result_rr) | |
2033 | { | |
7cbc5255 CH |
2034 | if (!rr.qtype.getCode()) |
2035 | continue; // skip empty non-terminals | |
2036 | ||
00963dea CH |
2037 | auto object = Json::object { |
2038 | { "object_type", "record" }, | |
2039 | { "name", rr.qname.toString() }, | |
2040 | { "type", rr.qtype.getName() }, | |
2041 | { "ttl", (double)rr.ttl }, | |
2042 | { "disabled", rr.disabled }, | |
2043 | { "content", makeApiRecordContent(rr.qtype, rr.content) } | |
2044 | }; | |
720ed2bd | 2045 | if ((val = zoneIdZone.find(rr.domain_id)) != zoneIdZone.end()) { |
00963dea CH |
2046 | object["zone_id"] = apiZoneNameToId(val->second.zone); |
2047 | object["zone"] = val->second.zone.toString(); | |
720ed2bd | 2048 | } |
00963dea | 2049 | doc.push_back(object); |
b1902fab | 2050 | } |
720ed2bd | 2051 | } |
b1902fab | 2052 | |
720ed2bd AT |
2053 | if (B.searchComments(q, maxEnts, result_c)) |
2054 | { | |
2055 | for(const Comment &c: result_c) | |
2056 | { | |
00963dea CH |
2057 | auto object = Json::object { |
2058 | { "object_type", "comment" }, | |
25dcc05f | 2059 | { "name", c.qname.toString() }, |
00963dea CH |
2060 | { "content", c.content } |
2061 | }; | |
720ed2bd | 2062 | if ((val = zoneIdZone.find(c.domain_id)) != zoneIdZone.end()) { |
00963dea CH |
2063 | object["zone_id"] = apiZoneNameToId(val->second.zone); |
2064 | object["zone"] = val->second.zone.toString(); | |
720ed2bd | 2065 | } |
00963dea | 2066 | doc.push_back(object); |
b1902fab CH |
2067 | } |
2068 | } | |
4bd3d119 | 2069 | |
b1902fab CH |
2070 | resp->setBody(doc); |
2071 | } | |
2072 | ||
c0f6a1da | 2073 | void apiServerCacheFlush(HttpRequest* req, HttpResponse* resp) { |
136965be | 2074 | if(req->method != "PUT" || ::arg().mustDo("api-readonly")) |
a426cb89 | 2075 | throw HttpMethodNotAllowedException(); |
80d59cd1 | 2076 | |
c0f6a1da CH |
2077 | DNSName canon = apiNameToDNSName(req->getvars["domain"]); |
2078 | ||
bf269e28 | 2079 | uint64_t count = purgeAuthCachesExact(canon); |
f682752a | 2080 | resp->setBody(Json::object { |
bf269e28 RG |
2081 | { "count", (int) count }, |
2082 | { "result", "Flushed cache." } | |
f682752a | 2083 | }); |
ddc84d12 CH |
2084 | } |
2085 | ||
dea47634 | 2086 | void AuthWebServer::cssfunction(HttpRequest* req, HttpResponse* resp) |
c67bf8c5 | 2087 | { |
80d59cd1 CH |
2088 | resp->headers["Cache-Control"] = "max-age=86400"; |
2089 | resp->headers["Content-Type"] = "text/css"; | |
c67bf8c5 | 2090 | |
1071abdd | 2091 | ostringstream ret; |
1071abdd CH |
2092 | ret<<"* { box-sizing: border-box; margin: 0; padding: 0; }"<<endl; |
2093 | ret<<"body { color: black; background: white; margin-top: 1em; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 10pt; position: relative; }"<<endl; | |
2094 | ret<<"a { color: #0959c2; }"<<endl; | |
2095 | ret<<"a:hover { color: #3B8EC8; }"<<endl; | |
2096 | ret<<".row { width: 940px; max-width: 100%; min-width: 768px; margin: 0 auto; }"<<endl; | |
2097 | ret<<".row:before, .row:after { display: table; content:\" \"; }"<<endl; | |
2098 | ret<<".row:after { clear: both; }"<<endl; | |
2099 | ret<<".columns { position: relative; min-height: 1px; float: left; }"<<endl; | |
2100 | ret<<".all { width: 100%; }"<<endl; | |
2101 | ret<<".headl { width: 60%; }"<<endl; | |
2102 | ret<<".headr { width: 39.5%; float: right; background-repeat: no-repeat; margin-top: 7px; "; | |
2103 | ret<<"background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJoAAAAUCAYAAAB1RSS/AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAACtgAAArYBAHIqtQAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAABBTSURBVGiBtVp7cFRVmv9u3763b7/f9It00iFACBohgCEyQYgKI49CLV3cWaoEZBcfo2shu7KOtZbjrqOuVQtVWFuOrPqPRU3NgOIDlkgyJEYJwUAqjzEJedFJupN0p9/v+9o/mtve7r790HF+VbeSPue7555zz+98z4ucOXNmgWVZBH4AK5PJGIPBQBqNxpTNZkthGMZCCUxMTBCDg4PyiYkJWTQaRc1mc7Kuri7a1NQU4ssxDAOffPKJAQCynvnII494ESTddO3aNaXT6SS4TplMRj/44IM+7ndXV5dqfn5ewh9306ZNQZqmobu7W11qri0tLX6tVkv19vYqpqampPw+BEFYtVpNGQwG0mKxpJYsWUIKjTE6OiodGBhQ8NcgkUgYjUZDORyOhM1mSxV6fjAYFF+6dEnLb9NoNOR9990X4H53dHSovV4vzpfZvn27T6FQ0Py2sbExorOzU+N2uwmWZUGv15N33nlnuLGxMZy7byyVQEJ//nd9Yuz/lJR/HBdrHSlJ9baIuuV1L4LJ8/Y49pc/KcJX39WRC4MEgskY3Lourmn5rQdbckfe2ijfOBZo+40xNXtNysR9KLZkdVK+9oBf0fBkCABA3NraamTZwjxSKpXUAw884G1paQkUIty5c+f0Fy5cWMIfx+l0Snt6ejTt7e26AwcOuKxWawoAQCQSQW9vr3pxcTHrJTY3Nwe5Tb18+bJ2bGxMzvWhKMpu27bNj6IoCwDQ1tamd7lcRM79genpaaK1tdVQcDG3sXbt2rBWq6X6+/sV3d3d2mKyy5cvj+7cudO7atWqGL99bGxMWuxZOp0utX37du+9994b5A4Qh2AwiObei6Ioe/fdd4eVSiUNAHD16lX1+Pi4nC+zadOmIJ9oZ8+eNeTu3/T0tLSvr0/V3d0dPXr0qJNrZ+KL6MKpjZWUbyxzQMmFIYJcGCISw5+qjE9+M4UqLJmx/RdeWBK+elKfGTjuR+OhWSxx86JS/9D/zsrufDzMdSXGv5J5/vBYBZuKiLi25HS3LDndLUuMX1IYHjvtynQUQjgcFp89e9b8zjvv2BmGyepjWRbeffdd2/nz55cUIqvT6ZSeOHHC7vf7xVyb3W6P58rNzc1liOfxeLJISNM04na7Me63z+fD+P1SqZQupHn+Wty8eVN+4sSJyv7+fnlp6R/g8/nw06dPW0+ePLmUJEmklDxN08iVK1dU5Y7f0dGhvnjxYkElQVFU1jP9Xz5j4pMsSzYwifvPPWnhfsdHPpdnkYwHlk4ivi9/baFDM2IAACYZEi1++qSVTzI+YkN/VEe++726JNE4TE1Nyc6cOWPkt3322Wf6/v7+ki8nEAhgH3zwQWYhDoejINGSyaQoFAphuf2zs7MSAIBIJIImEgmU32ez2RLlruOngGVZ+Oijj6w+n09cWjobg4ODyg8//NBSWhLgu+++K4toJEkin376qancObBkFIl/f7bo2ImxC0om5kUBACK9pzTFZJlEAI0O/kEJABAf+UJOh115+8VH5MZHGkGimc3mRK66BwBoa2szBAIBMUB6w1tbW415QgUwOjqqGB4elgIA1NTU5BGN02IulwsXOqUul0sCADA/P5+3qIqKip+NaARBMBiGMbnt0Wg0z68qF729vepr164pS8k5nU7ZwsJC0U0DAOjp6VHGYjE0t10kEgmqt5TrOwIYqqRWTbmuSQAASM9fiFKy5Fx/Wnaur7Ss53tC8IQ+/fTTM/F4HH3rrbcc/E1nWRYmJyeJtWvXRr7++mt1rnoGANi6devipk2bgsePH7dHIpGs8Ts7O7W1tbXxqqqqJIZhLN+keDweDADA7XbjuWPebpcAACwsLOT1V1VVFSSayWRKvvLKK5P8tmLBTVNTk//hhx/2vv/++5aBgYEsLeB0OqWF7gMAsFqtiYqKivj169c1ueaytbVVv2HDhnChewHS7/fKlSuqPXv2LBaTyw1gAABqa2sjhw4dck1PT0vOnz9v4O+NWFNdlluBqispAABUYSEp/6TgPmRkVba0rGppybFRpZksaDodDkeioqIiT/M4nU4JAMDIyEiez1JTUxN9/PHHFyoqKpJbtmzx5faPj4/LANKOr9VqzRqbi7D4vhof8/PzOMAPhMyZa948OSAIAjiOs/xLSFvzIZFImO3bt+fNn9OqhaDRaMiDBw/Obd26NY8oTqdTWmhtfPT29paMmkOhUJ6CkEgkjFKppOvq6mIvvviis76+PkNqVF1BiQ21yWJjoiobiRlWpQAACMeWaKk5EMu2RQEAiOr7YyBCi2YliMrN0aI+Wjwez+vn/KOZmZk8lbl69eoI97+QeQwEAhgXFFRVVWX1+/1+nGVZyE1bcPB6vRKWZSE35JdKpbTJZCp4qiiKQmZmZnDuEiKqEITWTtN0SfMDALBjx45FiUSSZ35HRkaKakQAgPn5ecnU1FRRQuv1+rz0Qn9/v+ry5ctqgPTh2rFjR9ZB0e78Hzcgedb2NhDQ7vq9C24fQNXm3/gww8qCxJTX/4OfcGyJAwBgS+pSqo3/XFADo0oLqdn2lkeQaAzDIB0dHWqPx5O3YK1WSzIMA7lmEQDAaDSSQv/zEQwGUQCA6urqLKJRFIV4PB6MH3GqVCqS3z83N4cvLi5mEaVUIOD1evHXX399GXedOnXKWkweIJ3r++abb/IcYqPRWDA3xodUKmWEyMCZ/1IolQvMfXcAabN7+vRp68cff2wS8nElVVvihl99cQtV27PmhapspOHvzzmJ5Tsy6RtELGGX7G+7JV2xIysHiqAYq/rFv3h0e96f57drHnjTo2n57TwiJrIOl6SyOWo6cPmWiNAwgj7am2++6Ugmk4IkrK2tjUWjUVRoMXK5PJOHkclkdJ4AAESjURQAYPny5YKRJ59odXV1EX6ea2ZmRpKbf/s5AwEAgO+//17+8ssv1/j9/jzNt3HjxmC542g0GjI318etXQgoirKcxrx+/brKYDAUJPW6desiFy5ciM/MzORpyM7OTl04HEYPHz7synURiJpfxizPj4+T8/0S0jOEiw2rUrh5TRJE+TRAFWba+KvPZung9Hxy9iohwpUMvnRjQkSo8zQ1ICJQbX7Zp2h8LpCa7ZEwUY8Yt21IiHXLMopCkEyFSFZZWRmz2+0FVSqXUL39v6AM5yTr9XpKrVZnab2RkRFZKpXKPHvlypUxvuM+PT0tCQaDWW+lWCDwUzA3N0cIkay2tjbS0tLiL3ccoYNWzPRWVVXFcBxnAACCwSAmRCIOCILA/v373QqFghLqv3Hjhrq9vb1gioIFBNLFoLI8gbKBILdHRNi8ocvOC6nVavLw4cOzAAAKhYJGEARytRo/5A6Hw4JMk8lkmRNht9vjAwMDmU0dGhril3TAbDanDAZD0u12EwAAw8PDCoZhspZQLBD4KRBa17Zt27wPPfSQVyQqO+0IQumHQloeIB0Jr169Onzjxg01QOHDzqGioiJ55MiRW8ePH68UCg6+/PJLY0tLS4Cv1RJjF2W+z5+2UEFnxiqgKhup2/muW7pyV1YAQEfmUN9n/2SOj57PRN4IirHKphe86q2vLSIozktHMBDq+p0u3PkfRpZKZOYtqWyOavd86BZrlxWOOjMTQVH2jjvuCL/wwgtOvV5PAaQ3QyqV5r20SCSSebmhUEiQaCqVKnNfLkk4QnEwmUyk2WzOaNDp6emsU14qEABIO87Hjh2b5K79+/e7i8kLVS0UCgXF19blINfEAwCoVCpBDcShsbExVKw/FzabLXXs2LFJIT81Go2K+YFPYqpDuvDx7ko+yQAA6NAs5jn9sD1+84KMa2OpJLLw0X2VfJIBALA0iYS6/svoO/ePWcni4KWXjKH2V0x8kgEAJG99Lfd8uLmSSfiFj+j999/v3bt3r/vgwYMzb7zxxthzzz03w9UqOVit1rzFjY6OZiY7NDSUl/4gCIIxmUyZcZYtW1ZQG0mlUloul9Nmszkjn1sCK6cigGEY63A4EtxlsViKOvQOhyOm0WiyyNve3q4vN+IESKeAhKJnISeej/r6+ijfzy2Evr4+Oad19Xo9dejQoVkhbev1ejNE83/xjAXYfPcqDRZ8nz9lhdtjhjr/U0d6RwoGLtH+j7WJyctSAADSM4SHu/9bsFwFAECHXVjwq381ChKtubk50NLSEmhsbAxrNBrBU7hixYq8XMvg4KByamqKmJubw7799ts8H6GqqirGV+XV1dWJQppCq9WSAABWq7WgT/hzBwIAaW3d0NCQpVkCgQDW1dVVVnnI5XLhp06dsuW24zjO1NTUFJ0viqJsfX19Sa3W09Ojfu+996xcCkapVNIoiuaxyGAwkAAAdHBaXIw4AGnNRnqHcQCAxOTlknXdxHirHAAgOXFJBkzxQ5ic6pD/6Nodh9uRT1YxPRaLoW+//XaVWCxmhXyMe+65J8D/jeM4a7FYEkKOL5ceWLp0aUGiVVZWliSax+PBX3rppRp+27PPPjtdLKhpamoKtre3Z53Sr776yrB58+a8LzH4GB4eVr722muCpaaGhoYgQRCFVEoGGzduDF65cqVkqevGjRvqgYEBld1uj8/NzUlIMtsNwnGc4VJMlH+yrNwhFbglxoyrUnTEXVKeDs2K039nSstG5rDyvdscLF26NNnQ0JAX7tM0jQiRzGQyJdevXx/Jba+srBQ0J3q9ngRIBwRisVhQ65UTCNA0jQQCAYx/CZXO+LDb7UmLxZJFYo/Hg1+9erVovTLXtHMgCILevXt30bISh5UrV8ZzTXchUBSFTExMyIQCj7q6ugh3KHDbugSIhN8hHxLb+iQAAGasK+2SmOvTsuY1pWWNqxI/mWgAAI8++uiCTqcrmcTEMIzZt2+fW8hMFvJbuNMoEokEM+FSqZQ2m81/k0+DAADWr1+fZ8IuXrxY8lu3XKAoyu7bt8/NmbFSEDLdPxYSiYTZu3dvJqmKYHJWturhomNKa34ZFskMNACAYt2hQDFZEaGh5XfsDQMAECt2R1Glreja5GsOBP4qoul0Ouro0aO3TCZTQTOkUqnII0eO3FqxYoUgoYRKVQAA/ISl0Ph/60+Dmpqa8syky+Ui+vr6yv4uTavVks8///ytUsV0oWf/GHk+pFIp/cQTT8zqdLos31q36+S8WFcjuE9iTVVK99CpTDQuXbk7qmz8taAGRlAJq9t50o2qllIAACKJitHu+cCF4ApBdS5d/XdB+fqnguLq6upobm4Kx/GyQ3m9Xk+9+uqrk21tbZquri6t1+vFWZYFi8WSdDgcsV27di1qtdqCYb3ZbCZra2sjueaW/yl0XV1dNBwOZ/mT/KIxB6VSSTkcjlhuey44X8lkMqVy5TmC6/V6qrGx0Z8bPY6OjsrWrFkT1el0ec9CUZRVqVSUWq2mqqur4xs2bAgL+XQSiYTJvZcf9Njt9uRdd90Vys2PcQnd5ubmAMMwcPPmTXk0GhUDpCsRVVVVsccee2yBS0PxIZLqacszfZPBP7+qj4+1Kilf+lNuYtkDEU3La3mfcmsfPL4gqfxFrJxPuYll22Kmp/omgpf+zZia7ZEyCT+KGVcn5WsP+uUNh0IAAP8PaQRnE4MgdzkAAAAASUVORK5CYII=);"; | |
2104 | ret<<" width: 154px; height: 20px; }"<<endl; | |
2105 | ret<<"a#appname { margin: 0; font-size: 27px; color: #666; text-decoration: none; font-weight: bold; display: block; }"<<endl; | |
2106 | ret<<"footer { border-top: 1px solid #ddd; padding-top: 4px; font-size: 12px; }"<<endl; | |
2107 | ret<<"footer.row { margin-top: 1em; margin-bottom: 1em; }"<<endl; | |
2108 | ret<<".panel { background: #f2f2f2; border: 1px solid #e6e6e6; margin: 0 0 22px 0; padding: 20px; }"<<endl; | |
2109 | ret<<"table.data { width: 100%; border-spacing: 0; border-top: 1px solid #333; }"<<endl; | |
2110 | ret<<"table.data td { border-bottom: 1px solid #333; padding: 2px; }"<<endl; | |
2111 | ret<<"table.data tr:nth-child(2n) { background: #e2e2e2; }"<<endl; | |
2112 | ret<<"table.data tr:hover { background: white; }"<<endl; | |
2113 | ret<<".ringmeta { margin-bottom: 5px; }"<<endl; | |
2114 | ret<<".resetring {float: right; }"<<endl; | |
2115 | ret<<".resetring i { background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAA/klEQVQY01XPP04UUBgE8N/33vd2XZUWEuzYuMZEG4KFCQn2NhA4AIewAOMBPIG2xhNYeAcKGqkNCdmYlVBZGBIT4FHsbuE0U8xk/kAbqm9TOfI/nicfhmwgDNhvylUT58kxCp4l31L8SfH9IetJ2ev6PwyIwyZWsdb11/gbTK55Co+r8rmJaRPTFJcpZil+pTit7C5awMpA+Zpi1sRFE9MqflYOloYCjY2uP8EdYiGU4CVGUBubxKfOOLjrtOBmzvEilbVb/aQWvhRl0unBZVXe4XdnK+bprwqnhoyTsyZ+JG8Wk0apfExxlcp7PFruXH8gdxamWB4cyW2sIO4BG3czIp78jUIAAAAASUVORK5CYII=); width: 10px; height: 10px; margin-right: 2px; display: inline-block; background-repeat: no-repeat; }"<<endl; | |
2116 | ret<<".resetring:hover i { background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAA2ElEQVQY013PMUoDcRDF4c+kEzxCsNNCrBQvIGhnlcYm11EkBxAraw8gglgIoiJpAoKIYlBcgrgopsma3c3fwt1k9cHA480M8xvQp/nMjorOWY5ov7IAYlpjQk7aYxcuWBpwFQgJnUcaYk7GhEDIGL5w+MVpKLIRyR2b4JOjvGhUKzHTv2W7iuSN479Dvu9plf1awbQ6y3x1sU5tjpVJcMbakF6Ycoas8Dl5xEHJ160wRdfqzXfa6XQ4PLDlicWUjxHxZfndL/N+RhiwNzl/Q6PDhn/qsl76H7prcApk2B1aAAAAAElFTkSuQmCC);}"<<endl; | |
2117 | ret<<".resizering {float: right;}"<<endl; | |
80d59cd1 | 2118 | resp->body = ret.str(); |
c146576d | 2119 | resp->status = 200; |
1071abdd CH |
2120 | } |
2121 | ||
dea47634 | 2122 | void AuthWebServer::webThread() |
12c86877 BH |
2123 | { |
2124 | try { | |
479e0976 | 2125 | if(::arg().mustDo("api")) { |
c0f6a1da | 2126 | d_ws->registerApiHandler("/api/v1/servers/localhost/cache/flush", &apiServerCacheFlush); |
46d06a12 | 2127 | d_ws->registerApiHandler("/api/v1/servers/localhost/config", &apiServerConfig); |
46d06a12 PL |
2128 | d_ws->registerApiHandler("/api/v1/servers/localhost/search-log", &apiServerSearchLog); |
2129 | d_ws->registerApiHandler("/api/v1/servers/localhost/search-data", &apiServerSearchData); | |
2130 | d_ws->registerApiHandler("/api/v1/servers/localhost/statistics", &apiServerStatistics); | |
fa07a3cf PL |
2131 | d_ws->registerApiHandler("/api/v1/servers/localhost/tsigkeys/<id>", &apiServerTsigKeyDetail); |
2132 | d_ws->registerApiHandler("/api/v1/servers/localhost/tsigkeys", &apiServerTsigKeys); | |
46d06a12 PL |
2133 | d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/axfr-retrieve", &apiServerZoneAxfrRetrieve); |
2134 | d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/cryptokeys/<key_id>", &apiZoneCryptokeys); | |
2135 | d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/cryptokeys", &apiZoneCryptokeys); | |
2136 | d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/export", &apiServerZoneExport); | |
24e11043 CJ |
2137 | d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/metadata/<kind>", &apiZoneMetadataKind); |
2138 | d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/metadata", &apiZoneMetadata); | |
46d06a12 | 2139 | d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/notify", &apiServerZoneNotify); |
4bc8379e | 2140 | d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/rectify", &apiServerZoneRectify); |
46d06a12 PL |
2141 | d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>", &apiServerZoneDetail); |
2142 | d_ws->registerApiHandler("/api/v1/servers/localhost/zones", &apiServerZones); | |
2143 | d_ws->registerApiHandler("/api/v1/servers/localhost", &apiServerDetail); | |
2144 | d_ws->registerApiHandler("/api/v1/servers", &apiServer); | |
9e6d2033 | 2145 | d_ws->registerApiHandler("/api", &apiDiscovery); |
c67bf8c5 | 2146 | } |
536ab56f CH |
2147 | if (::arg().mustDo("webserver")) { |
2148 | d_ws->registerWebHandler("/style.css", boost::bind(&AuthWebServer::cssfunction, this, _1, _2)); | |
2149 | d_ws->registerWebHandler("/", boost::bind(&AuthWebServer::indexfunction, this, _1, _2)); | |
2150 | } | |
96d299db | 2151 | d_ws->go(); |
12c86877 BH |
2152 | } |
2153 | catch(...) { | |
e6a9dde5 | 2154 | g_log<<Logger::Error<<"AuthWebServer thread caught an exception, dying"<<endl; |
5bd2ea7b | 2155 | _exit(1); |
12c86877 BH |
2156 | } |
2157 | } |