]> git.ipfire.org Git - thirdparty/pdns.git/blame - pdns/ws-auth.cc
API: Add POST for TSIGKey endpoint
[thirdparty/pdns.git] / pdns / ws-auth.cc
CommitLineData
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 49using json11::Json;
12c86877
BH
50
51extern StatBag S;
52
f63168e6 53static void patchZone(HttpRequest* req, HttpResponse* resp);
995473c8 54static void storeChangedPTRs(UeberBackend& B, vector<DNSResourceRecord>& new_ptrs);
f63168e6
CH
55static void makePtr(const DNSResourceRecord& rr, DNSResourceRecord* ptr);
56
dea47634 57AuthWebServer::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 69void 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 76void 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 94void *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 101void *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
108static 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 += "&amp;";
9f3fdaa0
CH
114 break;
115 case '<':
116 result += "&lt;";
117 break;
118 case '>':
119 result += "&gt;";
120 break;
c7f59d62
PL
121 case '"':
122 result += "&quot;";
123 break;
9f3fdaa0
CH
124 default:
125 result += *it;
126 }
127 }
128 return result;
129}
130
12c86877
BH
131void 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)<<"&amp;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 172void 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 184void 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 194string AuthWebServer::makePercentage(const double& val)
b6f57093
BH
195{
196 return (boost::format("%.01f%%") % val).str();
197}
198
dea47634 199void 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>&copy; 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. */
289static 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. */
296static inline string makeApiRecordContent(const QType& qtype, const string& content) {
297 return makeRecordContent(qtype, content, false);
298}
299
300/** "Normalize" record content for backend storage. */
301static inline string makeBackendRecordContent(const QType& qtype, const string& content) {
302 return makeRecordContent(qtype, content, true);
303}
304
ce846be6 305static 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
326static 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
334static 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
364 if (doRRSets) {
365 vector<DNSResourceRecord> records;
366 vector<Comment> comments;
367
368 // load all records + sort
369 {
370 DNSResourceRecord rr;
371 di.backend->list(zonename, di.id, true); // incl. disabled
372 while(di.backend->get(rr)) {
373 if (!rr.qtype.getCode())
374 continue; // skip empty non-terminals
375 records.push_back(rr);
376 }
377 sort(records.begin(), records.end(), [](const DNSResourceRecord& a, const DNSResourceRecord& b) {
378 if (a.qname == b.qname) {
379 return b.qtype < a.qtype;
380 }
381 return b.qname < a.qname;
382 });
6754ef71 383 }
6754ef71 384
986e4858
PL
385 // load all comments + sort
386 {
387 Comment comment;
388 di.backend->listComments(di.id);
389 while(di.backend->getComment(comment)) {
390 comments.push_back(comment);
391 }
392 sort(comments.begin(), comments.end(), [](const Comment& a, const Comment& b) {
393 if (a.qname == b.qname) {
394 return b.qtype < a.qtype;
395 }
396 return b.qname < a.qname;
397 });
6754ef71 398 }
6754ef71 399
986e4858
PL
400 Json::array rrsets;
401 Json::object rrset;
402 Json::array rrset_records;
403 Json::array rrset_comments;
404 DNSName current_qname;
405 QType current_qtype;
406 uint32_t ttl;
407 auto rit = records.begin();
408 auto cit = comments.begin();
409
410 while (rit != records.end() || cit != comments.end()) {
411 if (cit == comments.end() || (rit != records.end() && (cit->qname.toString() <= rit->qname.toString() || cit->qtype < rit->qtype || cit->qtype == rit->qtype))) {
412 current_qname = rit->qname;
413 current_qtype = rit->qtype;
414 ttl = rit->ttl;
415 } else {
416 current_qname = cit->qname;
417 current_qtype = cit->qtype;
418 ttl = 0;
419 }
6754ef71 420
986e4858
PL
421 while(rit != records.end() && rit->qname == current_qname && rit->qtype == current_qtype) {
422 ttl = min(ttl, rit->ttl);
423 rrset_records.push_back(Json::object {
424 { "disabled", rit->disabled },
425 { "content", makeApiRecordContent(rit->qtype, rit->content) }
426 });
427 rit++;
428 }
429 while (cit != comments.end() && cit->qname == current_qname && cit->qtype == current_qtype) {
430 rrset_comments.push_back(Json::object {
431 { "modified_at", (double)cit->modified_at },
432 { "account", cit->account },
433 { "content", cit->content }
434 });
435 cit++;
436 }
437
438 rrset["name"] = current_qname.toString();
439 rrset["type"] = current_qtype.getName();
440 rrset["records"] = rrset_records;
441 rrset["comments"] = rrset_comments;
442 rrset["ttl"] = (double)ttl;
443 rrsets.push_back(rrset);
444 rrset.clear();
445 rrset_records.clear();
446 rrset_comments.clear();
6754ef71
CH
447 }
448
986e4858 449 doc["rrsets"] = rrsets;
6754ef71
CH
450 }
451
669822d0 452 resp->setBody(doc);
1abb81f4
CH
453}
454
6ec5e728
CH
455void productServerStatisticsFetch(map<string,string>& out)
456{
a45303b8 457 vector<string> items = S.getEntries();
ff05fd12 458 for(const string& item : items) {
335da0ba 459 out[item] = std::to_string(S.read(item));
a45303b8
CH
460 }
461
462 // add uptime
335da0ba 463 out["uptime"] = std::to_string(time(0) - s_starttime);
c67bf8c5
CH
464}
465
24ded6cc
CHB
466static void validateGatheredRRType(const DNSResourceRecord& rr) {
467 if (rr.qtype.getCode() == QType::OPT || rr.qtype.getCode() == QType::TSIG) {
468 throw ApiException("RRset "+rr.qname.toString()+" IN "+rr.qtype.getName()+": invalid type given");
469 }
470}
471
6754ef71 472static void gatherRecords(const Json container, const DNSName& qname, const QType qtype, const int ttl, vector<DNSResourceRecord>& new_records, vector<DNSResourceRecord>& new_ptrs) {
f63168e6
CH
473 UeberBackend B;
474 DNSResourceRecord rr;
6754ef71
CH
475 rr.qname = qname;
476 rr.qtype = qtype;
477 rr.auth = 1;
478 rr.ttl = ttl;
24ded6cc
CHB
479
480 validateGatheredRRType(rr);
1f68b185 481 for(auto record : container["records"].array_items()) {
1f68b185 482 string content = stringFromJson(record, "content");
1f68b185
CH
483 rr.disabled = boolFromJson(record, "disabled");
484
1f68b185
CH
485 // validate that the client sent something we can actually parse, and require that data to be dotted.
486 try {
487 if (rr.qtype.getCode() != QType::AAAA) {
488 string tmp = makeApiRecordContent(rr.qtype, content);
489 if (!pdns_iequals(tmp, content)) {
490 throw std::runtime_error("Not in expected format (parsed as '"+tmp+"')");
491 }
492 } else {
493 struct in6_addr tmpbuf;
494 if (inet_pton(AF_INET6, content.c_str(), &tmpbuf) != 1 || content.find('.') != string::npos) {
495 throw std::runtime_error("Invalid IPv6 address");
1e5b9ab9 496 }
f63168e6 497 }
1f68b185
CH
498 rr.content = makeBackendRecordContent(rr.qtype, content);
499 }
500 catch(std::exception& e)
501 {
502 throw ApiException("Record "+rr.qname.toString()+"/"+rr.qtype.getName()+" '"+content+"': "+e.what());
503 }
f63168e6 504
1f68b185
CH
505 if ((rr.qtype.getCode() == QType::A || rr.qtype.getCode() == QType::AAAA) &&
506 boolFromJson(record, "set-ptr", false) == true) {
507 DNSResourceRecord ptr;
508 makePtr(rr, &ptr);
f63168e6 509
1f68b185 510 // verify that there's a zone for the PTR
1f68b185 511 SOAData sd;
cec52de6 512 if (!B.getAuth(ptr.qname, QType(QType::PTR), &sd, false))
1f68b185 513 throw ApiException("Could not find domain for PTR '"+ptr.qname.toString()+"' requested for '"+ptr.content+"'");
f63168e6 514
1f68b185
CH
515 ptr.domain_id = sd.domain_id;
516 new_ptrs.push_back(ptr);
f63168e6 517 }
1f68b185
CH
518
519 new_records.push_back(rr);
f63168e6
CH
520 }
521}
522
6754ef71 523static void gatherComments(const Json container, const DNSName& qname, const QType qtype, vector<Comment>& new_comments) {
f63168e6 524 Comment c;
6754ef71
CH
525 c.qname = qname;
526 c.qtype = qtype;
f63168e6
CH
527
528 time_t now = time(0);
1f68b185 529 for (auto comment : container["comments"].array_items()) {
1f68b185
CH
530 c.modified_at = intFromJson(comment, "modified_at", now);
531 c.content = stringFromJson(comment, "content");
532 c.account = stringFromJson(comment, "account");
533 new_comments.push_back(c);
f63168e6
CH
534 }
535}
6cc98ddf 536
986e4858
PL
537static void checkDefaultDNSSECAlgos() {
538 int k_algo = DNSSECKeeper::shorthand2algorithm(::arg()["default-ksk-algorithm"]);
539 int z_algo = DNSSECKeeper::shorthand2algorithm(::arg()["default-zsk-algorithm"]);
540 int k_size = arg().asNum("default-ksk-size");
541 int z_size = arg().asNum("default-zsk-size");
542
543 // Sanity check DNSSEC parameters
544 if (::arg()["default-zsk-algorithm"] != "") {
545 if (k_algo == -1)
546 throw ApiException("default-ksk-algorithm setting is set to unknown algorithm: " + ::arg()["default-ksk-algorithm"]);
547 else if (k_algo <= 10 && k_size == 0)
548 throw ApiException("default-ksk-algorithm is set to an algorithm("+::arg()["default-ksk-algorithm"]+") that requires a non-zero default-ksk-size!");
549 }
550
551 if (::arg()["default-zsk-algorithm"] != "") {
552 if (z_algo == -1)
553 throw ApiException("default-zsk-algorithm setting is set to unknown algorithm: " + ::arg()["default-zsk-algorithm"]);
554 else if (z_algo <= 10 && z_size == 0)
555 throw ApiException("default-zsk-algorithm is set to an algorithm("+::arg()["default-zsk-algorithm"]+") that requires a non-zero default-zsk-size!");
556 }
557}
558
89a7e706
PL
559static void throwUnableToSecure(const DNSName& zonename) {
560 throw ApiException("No backend was able to secure '" + zonename.toString() + "', most likely because no DNSSEC"
561 + "capable backends are loaded, or because the backends have DNSSEC disabled. Check your configuration.");
562}
563
986e4858 564static void updateDomainSettingsFromDocument(UeberBackend& B, const DomainInfo& di, const DNSName& zonename, const Json document) {
1f68b185 565 string zonemaster;
986e4858 566 bool shouldRectify = false;
1f68b185
CH
567 for(auto value : document["masters"].array_items()) {
568 string master = value.string_value();
569 if (master.empty())
570 throw ApiException("Master can not be an empty string");
571 zonemaster += master + " ";
bb9fd223
CH
572 }
573
986e4858
PL
574 if (zonemaster != "") {
575 di.backend->setMaster(zonename, zonemaster);
576 }
577 if (document["kind"].is_string()) {
578 di.backend->setKind(zonename, DomainInfo::stringToKind(stringFromJson(document, "kind")));
579 }
1f68b185
CH
580 if (document["soa_edit_api"].is_string()) {
581 di.backend->setDomainMetadataOne(zonename, "SOA-EDIT-API", document["soa_edit_api"].string_value());
d29d5db7 582 }
1f68b185
CH
583 if (document["soa_edit"].is_string()) {
584 di.backend->setDomainMetadataOne(zonename, "SOA-EDIT", document["soa_edit"].string_value());
6bb25159 585 }
c00908f1
PL
586 try {
587 bool api_rectify = boolFromJson(document, "api_rectify");
588 di.backend->setDomainMetadataOne(zonename, "API-RECTIFY", api_rectify ? "1" : "0");
986e4858 589 }
819861fa 590 catch (const JsonException&) {}
c00908f1 591
1f68b185
CH
592 if (document["account"].is_string()) {
593 di.backend->setAccount(zonename, document["account"].string_value());
79532aa7 594 }
986e4858
PL
595
596 DNSSECKeeper dk(&B);
597 bool dnssecInJSON = false;
598 bool dnssecDocVal = false;
599
600 try {
601 dnssecDocVal = boolFromJson(document, "dnssec");
602 dnssecInJSON = true;
603 }
819861fa 604 catch (const JsonException&) {}
986e4858
PL
605
606 bool isDNSSECZone = dk.isSecuredZone(zonename);
607
608 if (dnssecInJSON) {
609 if (dnssecDocVal) {
610 if (!isDNSSECZone) {
611 checkDefaultDNSSECAlgos();
612
613 int k_algo = DNSSECKeeper::shorthand2algorithm(::arg()["default-ksk-algorithm"]);
614 int z_algo = DNSSECKeeper::shorthand2algorithm(::arg()["default-zsk-algorithm"]);
615 int k_size = arg().asNum("default-ksk-size");
616 int z_size = arg().asNum("default-zsk-size");
617
618 if (k_algo != -1) {
619 int64_t id;
620 if (!dk.addKey(zonename, true, k_algo, id, k_size)) {
89a7e706 621 throwUnableToSecure(zonename);
986e4858
PL
622 }
623 }
624
625 if (z_algo != -1) {
626 int64_t id;
627 if (!dk.addKey(zonename, false, z_algo, id, z_size)) {
89a7e706 628 throwUnableToSecure(zonename);
986e4858
PL
629 }
630 }
631
632 // Used later for NSEC3PARAM
633 isDNSSECZone = dk.isSecuredZone(zonename);
634
635 if (!isDNSSECZone) {
89a7e706 636 throwUnableToSecure(zonename);
986e4858
PL
637 }
638 shouldRectify = true;
639 }
640 } else {
641 // "dnssec": false in json
642 if (isDNSSECZone) {
cbe8b186
PL
643 string info, error;
644 if (!dk.unSecureZone(zonename, error, info)) {
645 throw ApiException("Error while un-securing zone '"+ zonename.toString()+"': " + error);
646 }
647 isDNSSECZone = dk.isSecuredZone(zonename);
648 if (isDNSSECZone) {
649 throw ApiException("Unable to un-secure zone '"+ zonename.toString()+"'");
650 }
651 shouldRectify = true;
986e4858
PL
652 }
653 }
654 }
655
656 if(document["nsec3param"].string_value().length() > 0) {
657 shouldRectify = true;
658 NSEC3PARAMRecordContent ns3pr(document["nsec3param"].string_value());
659 string error_msg = "";
660 if (!isDNSSECZone) {
661 throw ApiException("NSEC3PARAMs provided for zone '"+zonename.toString()+"', but zone is not DNSSEC secured.");
662 }
663 if (!dk.checkNSEC3PARAM(ns3pr, error_msg)) {
664 throw ApiException("NSEC3PARAMs provided for zone '"+zonename.toString()+"' are invalid. " + error_msg);
665 }
666 if (!dk.setNSEC3PARAM(zonename, ns3pr, boolFromJson(document, "nsec3narrow", false))) {
667 throw ApiException("NSEC3PARAMs provided for zone '" + zonename.toString() +
668 "' passed our basic sanity checks, but cannot be used with the current backend.");
669 }
670 }
671
a843c67e
KM
672 if (shouldRectify && !dk.isPresigned(zonename)) {
673 // Rectify
674 string api_rectify;
675 di.backend->getDomainMetadataOne(zonename, "API-RECTIFY", api_rectify);
676 if (api_rectify == "1") {
677 string info;
678 string error_msg;
679 if (!dk.rectifyZone(zonename, error_msg, info, true)) {
680 throw ApiException("Failed to rectify '" + zonename.toString() + "' " + error_msg);
681 }
682 }
683
684 // Increase serial
685 string soa_edit_api_kind;
686 di.backend->getDomainMetadataOne(zonename, "SOA-EDIT-API", soa_edit_api_kind);
687 if (!soa_edit_api_kind.empty()) {
688 SOAData sd;
689 if (!B.getSOAUncached(zonename, sd, true))
690 return;
691
692 string soa_edit_kind;
693 di.backend->getDomainMetadataOne(zonename, "SOA-EDIT", soa_edit_kind);
694
695 DNSResourceRecord rr;
696 if (makeIncreasedSOARecord(sd, soa_edit_api_kind, soa_edit_kind, rr)) {
697 if (!di.backend->replaceRRSet(di.id, rr.qname, rr.qtype, vector<DNSResourceRecord>(1, rr))) {
698 throw ApiException("Hosting backend does not support editing records.");
699 }
700 }
a843c67e 701 }
986e4858 702 }
bb9fd223
CH
703}
704
24e11043
CJ
705static bool isValidMetadataKind(const string& kind, bool readonly) {
706 static vector<string> builtinOptions {
707 "ALLOW-AXFR-FROM",
708 "AXFR-SOURCE",
709 "ALLOW-DNSUPDATE-FROM",
710 "TSIG-ALLOW-DNSUPDATE",
711 "FORWARD-DNSUPDATE",
712 "SOA-EDIT-DNSUPDATE",
4c5b6925 713 "NOTIFY-DNSUPDATE",
24e11043
CJ
714 "ALSO-NOTIFY",
715 "AXFR-MASTER-TSIG",
716 "GSS-ALLOW-AXFR-PRINCIPAL",
717 "GSS-ACCEPTOR-PRINCIPAL",
718 "IXFR",
719 "LUA-AXFR-SCRIPT",
720 "NSEC3NARROW",
721 "NSEC3PARAM",
722 "PRESIGNED",
723 "PUBLISH-CDNSKEY",
724 "PUBLISH-CDS",
725 "SOA-EDIT",
726 "TSIG-ALLOW-AXFR",
727 "TSIG-ALLOW-DNSUPDATE"
728 };
729
730 // the following options do not allow modifications via API
731 static vector<string> protectedOptions {
986e4858 732 "API-RECTIFY",
24e11043
CJ
733 "NSEC3NARROW",
734 "NSEC3PARAM",
735 "PRESIGNED",
736 "LUA-AXFR-SCRIPT"
737 };
738
9ac4e6d5
PL
739 if (kind.find("X-") == 0)
740 return true;
741
24e11043
CJ
742 bool found = false;
743
d8043c73 744 for (const string& s : builtinOptions) {
24e11043 745 if (kind == s) {
d8043c73 746 for (const string& s2 : protectedOptions) {
24e11043
CJ
747 if (!readonly && s == s2)
748 return false;
749 }
750 found = true;
751 break;
752 }
753 }
754
755 return found;
756}
757
758static void apiZoneMetadata(HttpRequest* req, HttpResponse *resp) {
759 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
d38e81e6 760
24e11043 761 UeberBackend B;
d38e81e6 762 DomainInfo di;
77bfe8de
PL
763 if (!B.getDomainInfo(zonename, di)) {
764 throw HttpNotFoundException();
765 }
24e11043
CJ
766
767 if (req->method == "GET") {
768 map<string, vector<string> > md;
769 Json::array document;
770
771 if (!B.getAllDomainMetadata(zonename, md))
772 throw HttpNotFoundException();
773
774 for (const auto& i : md) {
775 Json::array entries;
776 for (string j : i.second)
777 entries.push_back(j);
778
779 Json::object key {
780 { "type", "Metadata" },
781 { "kind", i.first },
782 { "metadata", entries }
783 };
784
785 document.push_back(key);
786 }
787
788 resp->setBody(document);
789 } else if (req->method == "POST" && !::arg().mustDo("api-readonly")) {
790 auto document = req->json();
791 string kind;
792 vector<string> entries;
793
794 try {
795 kind = stringFromJson(document, "kind");
819861fa 796 } catch (const JsonException&) {
24e11043
CJ
797 throw ApiException("kind is not specified or not a string");
798 }
799
800 if (!isValidMetadataKind(kind, false))
801 throw ApiException("Unsupported metadata kind '" + kind + "'");
802
803 vector<string> vecMetadata;
c6720e79
CJ
804
805 if (!B.getDomainMetadata(zonename, kind, vecMetadata))
806 throw ApiException("Could not retrieve metadata entries for domain '" +
807 zonename.toString() + "'");
808
24e11043
CJ
809 auto& metadata = document["metadata"];
810 if (!metadata.is_array())
811 throw ApiException("metadata is not specified or not an array");
812
813 for (const auto& i : metadata.array_items()) {
814 if (!i.is_string())
815 throw ApiException("metadata must be strings");
c6720e79
CJ
816 else if (std::find(vecMetadata.cbegin(),
817 vecMetadata.cend(),
818 i.string_value()) == vecMetadata.cend()) {
819 vecMetadata.push_back(i.string_value());
820 }
24e11043
CJ
821 }
822
823 if (!B.setDomainMetadata(zonename, kind, vecMetadata))
c6720e79
CJ
824 throw ApiException("Could not update metadata entries for domain '" +
825 zonename.toString() + "'");
826
827 Json::array respMetadata;
828 for (const string& s : vecMetadata)
829 respMetadata.push_back(s);
830
831 Json::object key {
832 { "type", "Metadata" },
833 { "kind", document["kind"] },
834 { "metadata", respMetadata }
835 };
24e11043 836
24e11043 837 resp->status = 201;
c6720e79 838 resp->setBody(key);
24e11043
CJ
839 } else
840 throw HttpMethodNotAllowedException();
841}
842
843static void apiZoneMetadataKind(HttpRequest* req, HttpResponse* resp) {
844 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
d38e81e6 845
24e11043 846 UeberBackend B;
d38e81e6 847 DomainInfo di;
77bfe8de
PL
848 if (!B.getDomainInfo(zonename, di)) {
849 throw HttpNotFoundException();
850 }
d38e81e6
PL
851
852 string kind = req->parameters["kind"];
24e11043
CJ
853
854 if (req->method == "GET") {
855 vector<string> metadata;
856 Json::object document;
857 Json::array entries;
858
859 if (!B.getDomainMetadata(zonename, kind, metadata))
860 throw HttpNotFoundException();
861 else if (!isValidMetadataKind(kind, true))
862 throw ApiException("Unsupported metadata kind '" + kind + "'");
863
864 document["type"] = "Metadata";
865 document["kind"] = kind;
866
867 for (const string& i : metadata)
868 entries.push_back(i);
869
870 document["metadata"] = entries;
871 resp->setBody(document);
872 } else if (req->method == "PUT" && !::arg().mustDo("api-readonly")) {
873 auto document = req->json();
874
875 if (!isValidMetadataKind(kind, false))
876 throw ApiException("Unsupported metadata kind '" + kind + "'");
877
878 vector<string> vecMetadata;
879 auto& metadata = document["metadata"];
880 if (!metadata.is_array())
881 throw ApiException("metadata is not specified or not an array");
882
883 for (const auto& i : metadata.array_items()) {
884 if (!i.is_string())
885 throw ApiException("metadata must be strings");
886 vecMetadata.push_back(i.string_value());
887 }
888
889 if (!B.setDomainMetadata(zonename, kind, vecMetadata))
890 throw ApiException("Could not update metadata entries for domain '" + zonename.toString() + "'");
891
892 Json::object key {
893 { "type", "Metadata" },
894 { "kind", kind },
895 { "metadata", metadata }
896 };
897
898 resp->setBody(key);
899 } else if (req->method == "DELETE" && !::arg().mustDo("api-readonly")) {
900 if (!isValidMetadataKind(kind, false))
901 throw ApiException("Unsupported metadata kind '" + kind + "'");
902
903 vector<string> md; // an empty vector will do it
904 if (!B.setDomainMetadata(zonename, kind, md))
905 throw ApiException("Could not delete metadata for domain '" + zonename.toString() + "' (" + kind + ")");
906 } else
907 throw HttpMethodNotAllowedException();
908}
909
71de13d7
PL
910// Throws 404 if the key with inquireKeyId does not exist
911static void apiZoneCryptoKeysCheckKeyExists(DNSName zonename, int inquireKeyId, DNSSECKeeper *dk) {
912 DNSSECKeeper::keyset_t keyset=dk->getKeys(zonename, false);
913 bool found = false;
914 for(const auto& value : keyset) {
915 if (value.second.id == (unsigned) inquireKeyId) {
916 found = true;
917 break;
918 }
919 }
920 if (!found) {
921 throw HttpNotFoundException();
922 }
923}
924
60b0a236
BZ
925static void apiZoneCryptokeysGET(DNSName zonename, int inquireKeyId, HttpResponse *resp, DNSSECKeeper *dk) {
926 DNSSECKeeper::keyset_t keyset=dk->getKeys(zonename, false);
4b7f120a 927
997cab68
BZ
928 bool inquireSingleKey = inquireKeyId >= 0;
929
24afabad 930 Json::array doc;
29704f66 931 for(const auto& value : keyset) {
997cab68 932 if (inquireSingleKey && (unsigned)inquireKeyId != value.second.id) {
29704f66 933 continue;
38809e97 934 }
24afabad 935
b6bd795c 936 string keyType;
60b0a236 937 switch (value.second.keyType) {
b6bd795c
PL
938 case DNSSECKeeper::KSK: keyType="ksk"; break;
939 case DNSSECKeeper::ZSK: keyType="zsk"; break;
940 case DNSSECKeeper::CSK: keyType="csk"; break;
941 }
942
24afabad 943 Json::object key {
997cab68
BZ
944 { "type", "Cryptokey" },
945 { "id", (int)value.second.id },
946 { "active", value.second.active },
947 { "keytype", keyType },
948 { "flags", (uint16_t)value.first.d_flags },
5d9c6182
PL
949 { "dnskey", value.first.getDNSKEY().getZoneRepresentation() },
950 { "algorithm", DNSSECKeeper::algorithm2name(value.first.d_algorithm) },
951 { "bits", value.first.getKey()->getBits() }
24afabad
CH
952 };
953
b6bd795c 954 if (value.second.keyType == DNSSECKeeper::KSK || value.second.keyType == DNSSECKeeper::CSK) {
24afabad 955 Json::array dses;
8455425c 956 for(const uint8_t keyid : { DNSSECKeeper::SHA1, DNSSECKeeper::SHA256, DNSSECKeeper::GOST, DNSSECKeeper::SHA384 })
997cab68
BZ
957 try {
958 dses.push_back(makeDSFromDNSKey(zonename, value.first.getDNSKEY(), keyid).getZoneRepresentation());
959 } catch (...) {}
24afabad 960 key["ds"] = dses;
4b7f120a 961 }
29704f66
CH
962
963 if (inquireSingleKey) {
964 key["privatekey"] = value.first.getKey()->convertToISC();
965 resp->setBody(key);
966 return;
967 }
24afabad 968 doc.push_back(key);
4b7f120a
MS
969 }
970
29704f66
CH
971 if (inquireSingleKey) {
972 // we came here because we couldn't find the requested key.
973 throw HttpNotFoundException();
974 }
4b7f120a 975 resp->setBody(doc);
997cab68
BZ
976
977}
978
979/*
980 * This method handles DELETE requests for URL /api/v1/servers/:server_id/zones/:zone_name/cryptokeys/:cryptokey_id .
981 * It deletes a key from :zone_name specified by :cryptokey_id.
982 * Server Answers:
60b0a236 983 * Case 1: the backend returns true on removal. This means the key is gone.
75191dc4 984 * The server returns 204 No Content, no body.
955cbfd0 985 * Case 2: the backend returns false on removal. An error occurred.
75191dc4
PL
986 * The server returns 422 Unprocessable Entity with message "Could not DELETE :cryptokey_id".
987 * Case 3: the key or zone does not exist.
988 * The server returns 404 Not Found
997cab68 989 * */
60b0a236
BZ
990static void apiZoneCryptokeysDELETE(DNSName zonename, int inquireKeyId, HttpRequest *req, HttpResponse *resp, DNSSECKeeper *dk) {
991 if (dk->removeKey(zonename, inquireKeyId)) {
992 resp->body = "";
75191dc4 993 resp->status = 204;
997cab68
BZ
994 } else {
995 resp->setErrorResult("Could not DELETE " + req->parameters["key_id"], 422);
996 }
997}
998
999/*
1000 * This method adds a key to a zone by generate it or content parameter.
1001 * Parameter:
1002 * {
5d9c6182 1003 * "privatekey" : "key The format used is compatible with BIND and NSD/LDNS" <string>
997cab68
BZ
1004 * "keytype" : "ksk|zsk" <string>
1005 * "active" : "true|false" <value>
5d9c6182 1006 * "algorithm" : "key generation algorithm name as default"<string> https://doc.powerdns.com/md/authoritative/dnssec/#supported-algorithms
997cab68
BZ
1007 * "bits" : number of bits <int>
1008 * }
1009 *
1010 * Response:
1011 * Case 1: keytype isn't ksk|zsk
1012 * The server returns 422 Unprocessable Entity {"error" : "Invalid keytype 'keytype'"}
60b0a236
BZ
1013 * Case 2: 'bits' must be a positive integer value.
1014 * The server returns 422 Unprocessable Entity {"error" : "'bits' must be a positive integer value."}
5d9c6182 1015 * Case 3: The "algorithm" isn't supported
997cab68 1016 * The server returns 422 Unprocessable Entity {"error" : "Unknown algorithm: 'algo'"}
60b0a236 1017 * Case 4: Algorithm <= 10 and no bits were passed
997cab68 1018 * The server returns 422 Unprocessable Entity {"error" : "Creating an algorithm algo key requires the size (in bits) to be passed"}
60b0a236
BZ
1019 * Case 5: The wrong keysize was passed
1020 * The server returns 422 Unprocessable Entity {"error" : "The algorithm does not support the given bit size."}
1021 * Case 6: If the server cant guess the keysize
1022 * The server returns 422 Unprocessable Entity {"error" : "Can not guess key size for algorithm"}
1023 * Case 7: The key-creation failed
997cab68 1024 * The server returns 422 Unprocessable Entity {"error" : "Adding key failed, perhaps DNSSEC not enabled in configuration?"}
60b0a236
BZ
1025 * Case 8: The key in content has the wrong format
1026 * The server returns 422 Unprocessable Entity {"error" : "Key could not be parsed. Make sure your key format is correct."}
1027 * Case 9: The wrong combination of fields is submitted
1028 * The server returns 422 Unprocessable Entity {"error" : "Either you submit just the 'content' field or you leave 'content' empty and submit the other fields."}
1029 * Case 10: No content and everything was fine
1030 * The server returns 201 Created and all public data about the new cryptokey
1031 * Case 11: With specified content
1032 * The server returns 201 Created and all public data about the added cryptokey
997cab68
BZ
1033 */
1034
60b0a236 1035static void apiZoneCryptokeysPOST(DNSName zonename, HttpRequest *req, HttpResponse *resp, DNSSECKeeper *dk) {
997cab68 1036 auto document = req->json();
5d9c6182
PL
1037 string privatekey_fieldname = "privatekey";
1038 auto privatekey = document["privatekey"];
1039 if (privatekey.is_null()) {
1040 // Fallback to the old "content" behaviour
1041 privatekey = document["content"];
1042 privatekey_fieldname = "content";
1043 }
997cab68 1044 bool active = boolFromJson(document, "active", false);
997cab68 1045 bool keyOrZone;
60b0a236 1046
eefd15b3 1047 if (stringFromJson(document, "keytype") == "ksk" || stringFromJson(document, "keytype") == "csk") {
997cab68
BZ
1048 keyOrZone = true;
1049 } else if (stringFromJson(document, "keytype") == "zsk") {
1050 keyOrZone = false;
1051 } else {
1052 throw ApiException("Invalid keytype " + stringFromJson(document, "keytype"));
1053 }
1054
b727e19b 1055 int64_t insertedId = -1;
997cab68 1056
5d9c6182 1057 if (privatekey.is_null()) {
43215ca6 1058 int bits = keyOrZone ? ::arg().asNum("default-ksk-size") : ::arg().asNum("default-zsk-size");
60b0a236
BZ
1059 auto docbits = document["bits"];
1060 if (!docbits.is_null()) {
1061 if (!docbits.is_number() || (fmod(docbits.number_value(), 1.0) != 0) || docbits.int_value() < 0) {
1062 throw ApiException("'bits' must be a positive integer value");
1063 } else {
1064 bits = docbits.int_value();
1065 }
1066 }
43215ca6 1067 int algorithm = DNSSECKeeper::shorthand2algorithm(keyOrZone ? ::arg()["default-ksk-algorithm"] : ::arg()["default-zsk-algorithm"]);
5d9c6182 1068 auto providedAlgo = document["algorithm"];
997cab68 1069 if (providedAlgo.is_string()) {
60b0a236
BZ
1070 algorithm = DNSSECKeeper::shorthand2algorithm(providedAlgo.string_value());
1071 if (algorithm == -1)
997cab68 1072 throw ApiException("Unknown algorithm: " + providedAlgo.string_value());
997cab68
BZ
1073 } else if (providedAlgo.is_number()) {
1074 algorithm = providedAlgo.int_value();
60b0a236
BZ
1075 } else if (!providedAlgo.is_null()) {
1076 throw ApiException("Unknown algorithm: " + providedAlgo.string_value());
997cab68
BZ
1077 }
1078
60b0a236 1079 try {
b727e19b
RG
1080 if (!dk->addKey(zonename, keyOrZone, algorithm, insertedId, bits, active)) {
1081 throw ApiException("Adding key failed, perhaps DNSSEC not enabled in configuration?");
1082 }
60b0a236 1083 } catch (std::runtime_error& error) {
997cab68
BZ
1084 throw ApiException(error.what());
1085 }
997cab68
BZ
1086 if (insertedId < 0)
1087 throw ApiException("Adding key failed, perhaps DNSSEC not enabled in configuration?");
5d9c6182
PL
1088 } else if (document["bits"].is_null() && document["algorithm"].is_null()) {
1089 auto keyData = stringFromJson(document, privatekey_fieldname);
997cab68
BZ
1090 DNSKEYRecordContent dkrc;
1091 DNSSECPrivateKey dpk;
60b0a236 1092 try {
997cab68
BZ
1093 shared_ptr<DNSCryptoKeyEngine> dke(DNSCryptoKeyEngine::makeFromISCString(dkrc, keyData));
1094 dpk.d_algorithm = dkrc.d_algorithm;
5d9c6182 1095 // TODO remove in 4.2.0
902c4e9c
CH
1096 if(dpk.d_algorithm == DNSSECKeeper::RSASHA1NSEC3SHA1)
1097 dpk.d_algorithm = DNSSECKeeper::RSASHA1;
997cab68
BZ
1098
1099 if (keyOrZone)
1100 dpk.d_flags = 257;
1101 else
1102 dpk.d_flags = 256;
1103
1104 dpk.setKey(dke);
997cab68 1105 }
60b0a236
BZ
1106 catch (std::runtime_error& error) {
1107 throw ApiException("Key could not be parsed. Make sure your key format is correct.");
1108 } try {
b727e19b
RG
1109 if (!dk->addKey(zonename, dpk,insertedId, active)) {
1110 throw ApiException("Adding key failed, perhaps DNSSEC not enabled in configuration?");
1111 }
60b0a236 1112 } catch (std::runtime_error& error) {
997cab68
BZ
1113 throw ApiException(error.what());
1114 }
1115 if (insertedId < 0)
1116 throw ApiException("Adding key failed, perhaps DNSSEC not enabled in configuration?");
60b0a236 1117 } else {
5d9c6182 1118 throw ApiException("Either you submit just the 'privatekey' field or you leave 'privatekey' empty and submit the other fields.");
997cab68 1119 }
60b0a236 1120 apiZoneCryptokeysGET(zonename, insertedId, resp, dk);
997cab68 1121 resp->status = 201;
60b0a236 1122}
997cab68
BZ
1123
1124/*
1125 * This method handles PUT (execute) requests for URL /api/v1/servers/:server_id/zones/:zone_name/cryptokeys/:cryptokey_id .
1126 * It de/activates a key from :zone_name specified by :cryptokey_id.
1127 * Server Answers:
60b0a236 1128 * Case 1: invalid JSON data
997cab68 1129 * The server returns 400 Bad Request
60b0a236
BZ
1130 * Case 2: the backend returns true on de/activation. This means the key is de/active.
1131 * The server returns 204 No Content
955cbfd0 1132 * Case 3: the backend returns false on de/activation. An error occurred.
997cab68
BZ
1133 * The sever returns 422 Unprocessable Entity with message "Could not de/activate Key: :cryptokey_id in Zone: :zone_name"
1134 * */
60b0a236 1135static void apiZoneCryptokeysPUT(DNSName zonename, int inquireKeyId, HttpRequest *req, HttpResponse *resp, DNSSECKeeper *dk) {
997cab68
BZ
1136 //throws an exception if the Body is empty
1137 auto document = req->json();
1138 //throws an exception if the key does not exist or is not a bool
1139 bool active = boolFromJson(document, "active");
60b0a236
BZ
1140 if (active) {
1141 if (!dk->activateKey(zonename, inquireKeyId)) {
997cab68
BZ
1142 resp->setErrorResult("Could not activate Key: " + req->parameters["key_id"] + " in Zone: " + zonename.toString(), 422);
1143 return;
1144 }
1145 } else {
60b0a236 1146 if (!dk->deactivateKey(zonename, inquireKeyId)) {
997cab68
BZ
1147 resp->setErrorResult("Could not deactivate Key: " + req->parameters["key_id"] + " in Zone: " + zonename.toString(), 422);
1148 return;
1149 }
1150 }
60b0a236
BZ
1151 resp->body = "";
1152 resp->status = 204;
1153 return;
997cab68
BZ
1154}
1155
1156/*
1157 * This method chooses the right functionality for the request. It also checks for a cryptokey_id which has to be passed
1158 * by URL /api/v1/servers/:server_id/zones/:zone_name/cryptokeys/:cryptokey_id .
1159 * If the the HTTP-request-method isn't supported, the function returns a response with the 405 code (method not allowed).
1160 * */
1161static void apiZoneCryptokeys(HttpRequest *req, HttpResponse *resp) {
1162 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
1163
60b0a236
BZ
1164 UeberBackend B;
1165 DNSSECKeeper dk(&B);
1166 DomainInfo di;
77bfe8de
PL
1167 if (!B.getDomainInfo(zonename, di)) {
1168 throw HttpNotFoundException();
1169 }
60b0a236 1170
997cab68
BZ
1171 int inquireKeyId = -1;
1172 if (req->parameters.count("key_id")) {
1173 inquireKeyId = std::stoi(req->parameters["key_id"]);
71de13d7 1174 apiZoneCryptoKeysCheckKeyExists(zonename, inquireKeyId, &dk);
997cab68
BZ
1175 }
1176
1177 if (req->method == "GET") {
60b0a236 1178 apiZoneCryptokeysGET(zonename, inquireKeyId, resp, &dk);
1abc1df5 1179 } else if (req->method == "DELETE" && !::arg().mustDo("api-readonly")) {
60b0a236
BZ
1180 if (inquireKeyId == -1)
1181 throw HttpBadRequestException();
1182 apiZoneCryptokeysDELETE(zonename, inquireKeyId, req, resp, &dk);
1abc1df5 1183 } else if (req->method == "POST" && !::arg().mustDo("api-readonly")) {
60b0a236 1184 apiZoneCryptokeysPOST(zonename, req, resp, &dk);
1abc1df5 1185 } else if (req->method == "PUT" && !::arg().mustDo("api-readonly")) {
60b0a236
BZ
1186 if (inquireKeyId == -1)
1187 throw HttpBadRequestException();
1188 apiZoneCryptokeysPUT(zonename, inquireKeyId, req, resp, &dk);
997cab68
BZ
1189 } else {
1190 throw HttpMethodNotAllowedException(); //Returns method not allowed
1191 }
4b7f120a
MS
1192}
1193
1f68b185 1194static void gatherRecordsFromZone(const std::string& zonestring, vector<DNSResourceRecord>& new_records, DNSName zonename) {
0f0e73fe
MS
1195 DNSResourceRecord rr;
1196 vector<string> zonedata;
1f68b185 1197 stringtok(zonedata, zonestring, "\r\n");
0f0e73fe
MS
1198
1199 ZoneParserTNG zpt(zonedata, zonename);
1200
1201 bool seenSOA=false;
1202
1203 string comment = "Imported via the API";
1204
1205 try {
1206 while(zpt.get(rr, &comment)) {
1207 if(seenSOA && rr.qtype.getCode() == QType::SOA)
1208 continue;
1209 if(rr.qtype.getCode() == QType::SOA)
1210 seenSOA=true;
24ded6cc 1211 validateGatheredRRType(rr);
0f0e73fe 1212
0f0e73fe
MS
1213 new_records.push_back(rr);
1214 }
1215 }
1216 catch(std::exception& ae) {
1af62161 1217 throw ApiException("An error occurred while parsing the zonedata: "+string(ae.what()));
0f0e73fe
MS
1218 }
1219}
1220
e3675a8a
CH
1221/** Throws ApiException if records with duplicate name/type/content are present.
1222 * NOTE: sorts records in-place.
1223 */
1224static void checkDuplicateRecords(vector<DNSResourceRecord>& records) {
1225 sort(records.begin(), records.end(),
1226 [](const DNSResourceRecord& rec_a, const DNSResourceRecord& rec_b) -> bool {
1227 return rec_a.qname.toString() > rec_b.qname.toString() || \
1228 rec_a.qtype.getCode() > rec_b.qtype.getCode() || \
1229 rec_a.content < rec_b.content;
1230 }
1231 );
1232 DNSResourceRecord previous;
1233 for(const auto& rec : records) {
1234 if (previous.qtype == rec.qtype && previous.qname == rec.qname && previous.content == rec.content) {
1235 throw ApiException("Duplicate record in RRset " + rec.qname.toString() + " IN " + rec.qtype.getName() + " with content \"" + rec.content + "\"");
1236 }
1237 previous = rec;
1238 }
1239}
1240
6f16f97c
PL
1241static void checkTSIGKey(UeberBackend& B, const DNSName& keyname, const DNSName& algo, const string& content) {
1242 DNSName algoFromDB;
1243 string contentFromDB;
1244 B.getTSIGKey(keyname, &algoFromDB, &contentFromDB);
1245 if (!contentFromDB.empty() || !algoFromDB.empty()) {
1246 throw ApiException("A TSIG key with the name '"+keyname.toLogString()+"' already exists");
fa07a3cf
PL
1247 }
1248
6f16f97c
PL
1249 TSIGHashEnum the;
1250 if (!getTSIGHashEnum(algo, the)) {
1251 throw ApiException("Unknown TSIG algorithm: " + algo.toLogString());
1252 }
fa07a3cf 1253
6f16f97c
PL
1254 string b64out;
1255 if (B64Decode(content, b64out) == -1) {
1256 throw ApiException("TSIG content '" + content + "' cannot be base64-decoded");
fa07a3cf 1257 }
6f16f97c 1258}
fa07a3cf 1259
6f16f97c
PL
1260static Json::object makeJSONTSIGKey(const DNSName& keyname, const DNSName& algo, const string& content) {
1261 Json::object tsigkey = {
1262 { "name", keyname.toStringNoDot() },
1263 { "id", apiZoneNameToId(keyname) },
1264 { "algorithm", algo.toStringNoDot() },
1265 { "key", content },
1266 { "type", "TSIGKey" }
1267 };
1268 return tsigkey;
1269}
fa07a3cf 1270
6f16f97c
PL
1271static Json::object makeJSONTSIGKey(const struct TSIGKey& key) {
1272 return makeJSONTSIGKey(key.name, key.algorithm, key.key);
1273}
1274
1275static void apiServerTsigKeys(HttpRequest* req, HttpResponse* resp) {
1276 UeberBackend B;
1277 if (req->method == "GET") {
1278 vector<struct TSIGKey> keys;
1279
1280 if (!B.getTSIGKeys(keys)) {
1281 throw ApiException("Unable to retrieve TSIG keys");
1282 }
1283
1284 Json::array doc;
1285
1286 for(const auto &key : keys) {
1287 doc.push_back(makeJSONTSIGKey(key));
1288 }
1289 resp->setBody(doc);
fa07a3cf
PL
1290 }
1291
6f16f97c
PL
1292 if (req->method != "GET" && ::arg().mustDo("api-readonly")) {
1293 throw HttpMethodNotAllowedException();
1294 }
1295
1296 if (req->method == "POST") {
1297 auto document = req->json();
1298 DNSName keyname(stringFromJson(document, "name"));
1299 DNSName algo(stringFromJson(document, "algorithm"));
1300 string content(stringFromJson(document, "key"));
1301
1302 if (content.empty()) {
1303 size_t klen = 64;
1304 if (algo.toStringNoDot() == "hmac-md5"
1305 || algo.toStringNoDot() == "hmac-sha1"
1306 || algo.toStringNoDot() == "hmac-sha224") {
1307 klen = 32;
1308 }
1309 char tmpkey[64];
1310 for(size_t i = 0; i < klen; i+=4) {
1311 *(unsigned int*)(tmpkey+i) = dns_random(0xffffffff);
1312 }
1313 content = Base64Encode(std::string(tmpkey, klen));
1314 }
1315
1316 // Will throw and ApiException on error
1317 checkTSIGKey(B, keyname, algo, content);
1318
1319 if(!B.setTSIGKey(keyname, algo, content)) {
1320 throw ApiException("Unable to add TSIG key");
1321 }
1322
1323 resp->status = 201;
1324 resp->setBody(makeJSONTSIGKey(keyname, algo, content));
1325 }
fa07a3cf
PL
1326}
1327
1328static void apiServerTsigKeyDetail(HttpRequest* req, HttpResponse* resp) {
1329 if (req->method != "GET") {
1330 throw HttpMethodNotAllowedException();
1331 }
1332
1333 DNSName keyname = apiZoneIdToName(req->parameters["id"]);
1334
1335 UeberBackend B;
1336 DNSName algo;
1337 string content;
1338
1339 if (!B.getTSIGKey(keyname, &algo, &content)) {
1340 throw ApiException("Unable to retrieve TSIG key with id '"+keyname.toLogString()+"'");
1341 }
1342
6f16f97c 1343 resp->setBody(makeJSONTSIGKey(keyname, algo, content));
fa07a3cf
PL
1344}
1345
80d59cd1 1346static void apiServerZones(HttpRequest* req, HttpResponse* resp) {
e2dba705 1347 UeberBackend B;
53942520 1348 DNSSECKeeper dk(&B);
d07bf7ff 1349 if (req->method == "POST" && !::arg().mustDo("api-readonly")) {
e2dba705 1350 DomainInfo di;
1f68b185 1351 auto document = req->json();
c576d0c5 1352 DNSName zonename = apiNameToDNSName(stringFromJson(document, "name"));
1d6b70f9 1353 apiCheckNameAllowedCharacters(zonename.toString());
e3675a8a 1354 zonename.makeUsLowerCase();
4ebf78b1 1355
1d6b70f9 1356 bool exists = B.getDomainInfo(zonename, di);
e2dba705 1357 if(exists)
331d3062 1358 throw HttpConflictException();
e2dba705 1359
bb9fd223 1360 // validate 'kind' is set
4bdff352 1361 DomainInfo::DomainKind zonekind = DomainInfo::stringToKind(stringFromJson(document, "kind"));
bb9fd223 1362
6754ef71
CH
1363 string zonestring = document["zone"].string_value();
1364 auto rrsets = document["rrsets"];
1365 if (rrsets.is_array() && zonestring != "")
1366 throw ApiException("You cannot give rrsets AND zone data as text");
0f0e73fe 1367
1f68b185
CH
1368 auto nameservers = document["nameservers"];
1369 if (!nameservers.is_array() && zonekind != DomainInfo::Slave)
f63168e6 1370 throw ApiException("Nameservers list must be given (but can be empty if NS records are supplied)");
e2dba705 1371
f63168e6 1372 string soa_edit_api_kind;
1f68b185
CH
1373 if (document["soa_edit_api"].is_string()) {
1374 soa_edit_api_kind = document["soa_edit_api"].string_value();
a6448d95
CH
1375 }
1376 else {
1377 soa_edit_api_kind = "DEFAULT";
1378 }
1f68b185 1379 string soa_edit_kind = document["soa_edit"].string_value();
e90b4e38 1380
f63168e6
CH
1381 // if records/comments are given, load and check them
1382 bool have_soa = false;
33e6c3e9 1383 bool have_zone_ns = false;
f63168e6
CH
1384 vector<DNSResourceRecord> new_records;
1385 vector<Comment> new_comments;
1386 vector<DNSResourceRecord> new_ptrs;
0f0e73fe 1387
6754ef71
CH
1388 if (rrsets.is_array()) {
1389 for (const auto& rrset : rrsets.array_items()) {
1390 DNSName qname = apiNameToDNSName(stringFromJson(rrset, "name"));
1391 apiCheckQNameAllowedCharacters(qname.toString());
1392 QType qtype;
1393 qtype = stringFromJson(rrset, "type");
1394 if (qtype.getCode() == 0) {
1395 throw ApiException("RRset "+qname.toString()+" IN "+stringFromJson(rrset, "type")+": unknown type given");
1396 }
1397 if (rrset["records"].is_array()) {
1398 int ttl = intFromJson(rrset, "ttl");
1399 gatherRecords(rrset, qname, qtype, ttl, new_records, new_ptrs);
1400 }
1401 if (rrset["comments"].is_array()) {
1402 gatherComments(rrset, qname, qtype, new_comments);
1403 }
1404 }
0f0e73fe 1405 } else if (zonestring != "") {
1f68b185 1406 gatherRecordsFromZone(zonestring, new_records, zonename);
0f0e73fe
MS
1407 }
1408
1f68b185 1409 for(auto& rr : new_records) {
e3675a8a 1410 rr.qname.makeUsLowerCase();
1d6b70f9 1411 if (!rr.qname.isPartOf(zonename) && rr.qname != zonename)
561434a6 1412 throw ApiException("RRset "+rr.qname.toString()+" IN "+rr.qtype.getName()+": Name is out of zone");
cb9b5901 1413 apiCheckQNameAllowedCharacters(rr.qname.toString());
f63168e6 1414
1d6b70f9 1415 if (rr.qtype.getCode() == QType::SOA && rr.qname==zonename) {
f63168e6 1416 have_soa = true;
a6448d95 1417 increaseSOARecord(rr, soa_edit_api_kind, soa_edit_kind);
f63168e6 1418 }
33e6c3e9
CH
1419 if (rr.qtype.getCode() == QType::NS && rr.qname==zonename) {
1420 have_zone_ns = true;
1421 }
f63168e6 1422 }
f7bfeb30
CH
1423
1424 // synthesize RRs as needed
1425 DNSResourceRecord autorr;
1d6b70f9 1426 autorr.qname = zonename;
f7bfeb30
CH
1427 autorr.auth = 1;
1428 autorr.ttl = ::arg().asNum("default-ttl");
e2dba705 1429
4de11a54 1430 if (!have_soa && zonekind != DomainInfo::Slave) {
f63168e6 1431 // synthesize a SOA record so the zone "really" exists
13f9e280 1432 string soa = (boost::format("%s %s %ul")
1d6b70f9
CH
1433 % ::arg()["default-soa-name"]
1434 % (::arg().isEmpty("default-soa-mail") ? (DNSName("hostmaster.") + zonename).toString() : ::arg()["default-soa-mail"])
1f68b185 1435 % document["serial"].int_value()
1d6b70f9 1436 ).str();
f63168e6 1437 SOAData sd;
1d6b70f9 1438 fillSOAData(soa, sd); // fills out default values for us
13f9e280
CH
1439 autorr.qtype = QType::SOA;
1440 autorr.content = makeSOAContent(sd)->getZoneRepresentation(true);
f7bfeb30
CH
1441 increaseSOARecord(autorr, soa_edit_api_kind, soa_edit_kind);
1442 new_records.push_back(autorr);
f63168e6
CH
1443 }
1444
1445 // create NS records if nameservers are given
1f68b185
CH
1446 for (auto value : nameservers.array_items()) {
1447 string nameserver = value.string_value();
1448 if (nameserver.empty())
1449 throw ApiException("Nameservers must be non-empty strings");
1450 if (!isCanonical(nameserver))
1451 throw ApiException("Nameserver is not canonical: '" + nameserver + "'");
1452 try {
1453 // ensure the name parses
8f955653 1454 autorr.content = DNSName(nameserver).toStringRootDot();
1f68b185
CH
1455 } catch (...) {
1456 throw ApiException("Unable to parse DNS Name for NS '" + nameserver + "'");
4bdff352 1457 }
13f9e280 1458 autorr.qtype = QType::NS;
1f68b185 1459 new_records.push_back(autorr);
33e6c3e9
CH
1460 if (have_zone_ns) {
1461 throw ApiException("Nameservers list MUST NOT be mixed with zone-level NS in rrsets");
1462 }
e2dba705
CH
1463 }
1464
e3675a8a
CH
1465 checkDuplicateRecords(new_records);
1466
986e4858
PL
1467 if (boolFromJson(document, "dnssec", false)) {
1468 checkDefaultDNSSECAlgos();
1469
1470 if(document["nsec3param"].string_value().length() > 0) {
1471 NSEC3PARAMRecordContent ns3pr(document["nsec3param"].string_value());
1472 string error_msg = "";
1473 if (!dk.checkNSEC3PARAM(ns3pr, error_msg)) {
1474 throw ApiException("NSEC3PARAMs provided for zone '"+zonename.toString()+"' are invalid. " + error_msg);
1475 }
1476 }
1477 }
1478
f63168e6 1479 // no going back after this
1d6b70f9
CH
1480 if(!B.createDomain(zonename))
1481 throw ApiException("Creating domain '"+zonename.toString()+"' failed");
f63168e6 1482
1d6b70f9
CH
1483 if(!B.getDomainInfo(zonename, di))
1484 throw ApiException("Creating domain '"+zonename.toString()+"' failed: lookup of domain ID failed");
f63168e6 1485
9440a9f0
CH
1486 // updateDomainSettingsFromDocument does NOT fill out the default we've established above.
1487 if (!soa_edit_api_kind.empty()) {
1488 di.backend->setDomainMetadataOne(zonename, "SOA-EDIT-API", soa_edit_api_kind);
1489 }
1490
1d6b70f9 1491 di.backend->startTransaction(zonename, di.id);
f63168e6 1492
abb873ee 1493 for(auto rr : new_records) {
f63168e6 1494 rr.domain_id = di.id;
c9b43446 1495 di.backend->feedRecord(rr, DNSName());
e2dba705 1496 }
1d6b70f9 1497 for(Comment& c : new_comments) {
f63168e6
CH
1498 c.domain_id = di.id;
1499 di.backend->feedComment(c);
1500 }
e2dba705 1501
986e4858 1502 updateDomainSettingsFromDocument(B, di, zonename, document);
e2dba705 1503
f63168e6
CH
1504 di.backend->commitTransaction();
1505
3fe7c7d6
CH
1506 storeChangedPTRs(B, new_ptrs);
1507
986e4858 1508 fillZone(zonename, resp, shouldDoRRSets(req));
64a36f0d 1509 resp->status = 201;
e2dba705
CH
1510 return;
1511 }
1512
c67bf8c5
CH
1513 if(req->method != "GET")
1514 throw HttpMethodNotAllowedException();
1515
c67bf8c5 1516 vector<DomainInfo> domains;
cea26350 1517 B.getAllDomains(&domains, true); // incl. disabled
c67bf8c5 1518
62a9a74c
CH
1519 Json::array doc;
1520 for(const DomainInfo& di : domains) {
ce846be6 1521 doc.push_back(getZoneInfo(di, &dk));
c67bf8c5 1522 }
669822d0 1523 resp->setBody(doc);
c67bf8c5
CH
1524}
1525
05776d2f 1526static void apiServerZoneDetail(HttpRequest* req, HttpResponse* resp) {
290a083d 1527 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
05776d2f 1528
77bfe8de
PL
1529 UeberBackend B;
1530 DomainInfo di;
1531 if (!B.getDomainInfo(zonename, di)) {
1532 throw HttpNotFoundException();
1533 }
1534
d07bf7ff 1535 if(req->method == "PUT" && !::arg().mustDo("api-readonly")) {
7c0ba3d2 1536 // update domain settings
7c0ba3d2 1537
986e4858 1538 updateDomainSettingsFromDocument(B, di, zonename, req->json());
7c0ba3d2 1539
f0e76cee
CH
1540 resp->body = "";
1541 resp->status = 204; // No Content, but indicate success
7c0ba3d2
CH
1542 return;
1543 }
d07bf7ff 1544 else if(req->method == "DELETE" && !::arg().mustDo("api-readonly")) {
a462a01d 1545 // delete domain
a462a01d 1546 if(!di.backend->deleteDomain(zonename))
290a083d 1547 throw ApiException("Deleting domain '"+zonename.toString()+"' failed: backend delete failed/unsupported");
a462a01d
CH
1548
1549 // empty body on success
1550 resp->body = "";
37663c3b 1551 resp->status = 204; // No Content: declare that the zone is gone now
a462a01d 1552 return;
d07bf7ff 1553 } else if (req->method == "PATCH" && !::arg().mustDo("api-readonly")) {
d708640f 1554 patchZone(req, resp);
6cc98ddf
CH
1555 return;
1556 } else if (req->method == "GET") {
986e4858 1557 fillZone(zonename, resp, shouldDoRRSets(req));
6cc98ddf 1558 return;
a462a01d 1559 }
6cc98ddf 1560 throw HttpMethodNotAllowedException();
05776d2f
CH
1561}
1562
a83004d3 1563static void apiServerZoneExport(HttpRequest* req, HttpResponse* resp) {
290a083d 1564 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
a83004d3
CH
1565
1566 if(req->method != "GET")
1567 throw HttpMethodNotAllowedException();
1568
1569 ostringstream ss;
1570
1571 UeberBackend B;
1572 DomainInfo di;
77bfe8de
PL
1573 if (!B.getDomainInfo(zonename, di)) {
1574 throw HttpNotFoundException();
1575 }
a83004d3
CH
1576
1577 DNSResourceRecord rr;
1578 SOAData sd;
1579 di.backend->list(zonename, di.id);
1580 while(di.backend->get(rr)) {
1581 if (!rr.qtype.getCode())
1582 continue; // skip empty non-terminals
1583
a83004d3 1584 ss <<
675fa24c 1585 rr.qname.toString() << "\t" <<
a83004d3 1586 rr.ttl << "\t" <<
dc420da6 1587 "IN" << "\t" <<
a83004d3 1588 rr.qtype.getName() << "\t" <<
1d6b70f9 1589 makeApiRecordContent(rr.qtype, rr.content) <<
a83004d3
CH
1590 endl;
1591 }
1592
1593 if (req->accept_json) {
41873e7c 1594 resp->setBody(Json::object { { "zone", ss.str() } });
a83004d3
CH
1595 } else {
1596 resp->headers["Content-Type"] = "text/plain; charset=us-ascii";
1597 resp->body = ss.str();
1598 }
1599}
1600
a426cb89 1601static void apiServerZoneAxfrRetrieve(HttpRequest* req, HttpResponse* resp) {
290a083d 1602 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
a426cb89 1603
136965be 1604 if(req->method != "PUT" || ::arg().mustDo("api-readonly"))
a426cb89
CH
1605 throw HttpMethodNotAllowedException();
1606
1607 UeberBackend B;
1608 DomainInfo di;
77bfe8de
PL
1609 if (!B.getDomainInfo(zonename, di)) {
1610 throw HttpNotFoundException();
1611 }
a426cb89
CH
1612
1613 if(di.masters.empty())
290a083d 1614 throw ApiException("Domain '"+zonename.toString()+"' is not a slave domain (or has no master defined)");
a426cb89
CH
1615
1616 random_shuffle(di.masters.begin(), di.masters.end());
1617 Communicator.addSuckRequest(zonename, di.masters.front());
9b0f144f 1618 resp->setSuccessResult("Added retrieval request for '"+zonename.toString()+"' from master "+di.masters.front().toLogString());
a426cb89
CH
1619}
1620
1621static void apiServerZoneNotify(HttpRequest* req, HttpResponse* resp) {
290a083d 1622 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
a426cb89 1623
136965be 1624 if(req->method != "PUT" || ::arg().mustDo("api-readonly"))
a426cb89
CH
1625 throw HttpMethodNotAllowedException();
1626
1627 UeberBackend B;
1628 DomainInfo di;
77bfe8de
PL
1629 if (!B.getDomainInfo(zonename, di)) {
1630 throw HttpNotFoundException();
1631 }
a426cb89
CH
1632
1633 if(!Communicator.notifyDomain(zonename))
1634 throw ApiException("Failed to add to the queue - see server log");
1635
692829aa 1636 resp->setSuccessResult("Notification queued");
a426cb89
CH
1637}
1638
4bc8379e
PL
1639static void apiServerZoneRectify(HttpRequest* req, HttpResponse* resp) {
1640 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
1641
1642 if(req->method != "PUT")
1643 throw HttpMethodNotAllowedException();
1644
1645 UeberBackend B;
1646 DomainInfo di;
77bfe8de
PL
1647 if (!B.getDomainInfo(zonename, di)) {
1648 throw HttpNotFoundException();
1649 }
4bc8379e
PL
1650
1651 DNSSECKeeper dk(&B);
1652
1653 if (!dk.isSecuredZone(zonename))
1654 throw ApiException("Zone '" + zonename.toString() + "' is not DNSSEC signed, not rectifying.");
1655
1656 if (di.kind == DomainInfo::Slave)
1657 throw ApiException("Zone '" + zonename.toString() + "' is a slave zone, not rectifying.");
1658
1659 string error_msg = "";
59102608
RG
1660 string info;
1661 if (!dk.rectifyZone(zonename, error_msg, info, true))
4bc8379e
PL
1662 throw ApiException("Failed to rectify '" + zonename.toString() + "' " + error_msg);
1663
1664 resp->setSuccessResult("Rectified");
1665}
1666
d1587ceb
CH
1667static void makePtr(const DNSResourceRecord& rr, DNSResourceRecord* ptr) {
1668 if (rr.qtype.getCode() == QType::A) {
1669 uint32_t ip;
1670 if (!IpToU32(rr.content, &ip)) {
1671 throw ApiException("PTR: Invalid IP address given");
1672 }
1d6b70f9 1673 ptr->qname = DNSName((boost::format("%u.%u.%u.%u.in-addr.arpa.")
d1587ceb
CH
1674 % ((ip >> 24) & 0xff)
1675 % ((ip >> 16) & 0xff)
1676 % ((ip >> 8) & 0xff)
1677 % ((ip ) & 0xff)
1d6b70f9 1678 ).str());
d1587ceb
CH
1679 } else if (rr.qtype.getCode() == QType::AAAA) {
1680 ComboAddress ca(rr.content);
5fb3aa58 1681 char buf[3];
d1587ceb 1682 ostringstream ss;
5fb3aa58
CH
1683 for (int octet = 0; octet < 16; ++octet) {
1684 if (snprintf(buf, sizeof(buf), "%02x", ca.sin6.sin6_addr.s6_addr[octet]) != (sizeof(buf)-1)) {
1685 // this should be impossible: no byte should give more than two digits in hex format
1686 throw PDNSException("Formatting IPv6 address failed");
1687 }
1688 ss << buf[0] << '.' << buf[1] << '.';
d1587ceb 1689 }
5fb3aa58
CH
1690 string tmp = ss.str();
1691 tmp.resize(tmp.size()-1); // remove last dot
1692 // reverse and append arpa domain
1d6b70f9 1693 ptr->qname = DNSName(string(tmp.rbegin(), tmp.rend())) + DNSName("ip6.arpa.");
d1587ceb 1694 } else {
675fa24c 1695 throw ApiException("Unsupported PTR source '" + rr.qname.toString() + "' type '" + rr.qtype.getName() + "'");
d1587ceb
CH
1696 }
1697
1698 ptr->qtype = "PTR";
1699 ptr->ttl = rr.ttl;
1700 ptr->disabled = rr.disabled;
8f955653 1701 ptr->content = rr.qname.toStringRootDot();
d1587ceb
CH
1702}
1703
995473c8
CH
1704static void storeChangedPTRs(UeberBackend& B, vector<DNSResourceRecord>& new_ptrs) {
1705 for(const DNSResourceRecord& rr : new_ptrs) {
995473c8 1706 SOAData sd;
cec52de6 1707 if (!B.getAuth(rr.qname, QType(QType::PTR), &sd, false))
995473c8
CH
1708 throw ApiException("Could not find domain for PTR '"+rr.qname.toString()+"' requested for '"+rr.content+"' (while saving)");
1709
1710 string soa_edit_api_kind;
1711 string soa_edit_kind;
1712 bool soa_changed = false;
1713 DNSResourceRecord soarr;
1714 sd.db->getDomainMetadataOne(sd.qname, "SOA-EDIT-API", soa_edit_api_kind);
1715 sd.db->getDomainMetadataOne(sd.qname, "SOA-EDIT", soa_edit_kind);
1716 if (!soa_edit_api_kind.empty()) {
13f9e280 1717 soa_changed = makeIncreasedSOARecord(sd, soa_edit_api_kind, soa_edit_kind, soarr);
995473c8
CH
1718 }
1719
1720 sd.db->startTransaction(sd.qname);
1721 if (!sd.db->replaceRRSet(sd.domain_id, rr.qname, rr.qtype, vector<DNSResourceRecord>(1, rr))) {
1722 sd.db->abortTransaction();
1723 throw ApiException("PTR-Hosting backend for "+rr.qname.toString()+"/"+rr.qtype.getName()+" does not support editing records.");
1724 }
1725
1726 if (soa_changed) {
1727 sd.db->replaceRRSet(sd.domain_id, soarr.qname, soarr.qtype, vector<DNSResourceRecord>(1, soarr));
1728 }
1729
1730 sd.db->commitTransaction();
bf269e28 1731 purgeAuthCachesExact(rr.qname);
995473c8
CH
1732 }
1733}
1734
d708640f 1735static void patchZone(HttpRequest* req, HttpResponse* resp) {
b3905a3d
CH
1736 UeberBackend B;
1737 DomainInfo di;
290a083d 1738 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
77bfe8de
PL
1739 if (!B.getDomainInfo(zonename, di)) {
1740 throw HttpNotFoundException();
1741 }
b3905a3d 1742
f63168e6
CH
1743 vector<DNSResourceRecord> new_records;
1744 vector<Comment> new_comments;
d708640f
CH
1745 vector<DNSResourceRecord> new_ptrs;
1746
1f68b185 1747 Json document = req->json();
b3905a3d 1748
1f68b185
CH
1749 auto rrsets = document["rrsets"];
1750 if (!rrsets.is_array())
d708640f 1751 throw ApiException("No rrsets given in update request");
b3905a3d 1752
d708640f 1753 di.backend->startTransaction(zonename);
6cc98ddf 1754
d708640f 1755 try {
d29d5db7 1756 string soa_edit_api_kind;
a6448d95 1757 string soa_edit_kind;
d29d5db7 1758 di.backend->getDomainMetadataOne(zonename, "SOA-EDIT-API", soa_edit_api_kind);
a6448d95 1759 di.backend->getDomainMetadataOne(zonename, "SOA-EDIT", soa_edit_kind);
d29d5db7
CH
1760 bool soa_edit_done = false;
1761
2b048cc7
PD
1762 set<pair<DNSName, QType>> seen;
1763
6754ef71
CH
1764 for (const auto& rrset : rrsets.array_items()) {
1765 string changetype = toUpper(stringFromJson(rrset, "changetype"));
c576d0c5 1766 DNSName qname = apiNameToDNSName(stringFromJson(rrset, "name"));
cb9b5901 1767 apiCheckQNameAllowedCharacters(qname.toString());
6754ef71 1768 QType qtype;
d708640f 1769 qtype = stringFromJson(rrset, "type");
6754ef71
CH
1770 if (qtype.getCode() == 0) {
1771 throw ApiException("RRset "+qname.toString()+" IN "+stringFromJson(rrset, "type")+": unknown type given");
1772 }
d708640f 1773
2b048cc7
PD
1774 if(seen.count({qname, qtype}))
1775 {
3216c7db 1776 throw ApiException("Duplicate RRset "+qname.toString()+" IN "+qtype.getName());
2b048cc7
PD
1777 }
1778 seen.insert({qname, qtype});
d708640f 1779
d708640f 1780 if (changetype == "DELETE") {
b7f21ab1 1781 // delete all matching qname/qtype RRs (and, implicitly comments).
d708640f
CH
1782 if (!di.backend->replaceRRSet(di.id, qname, qtype, vector<DNSResourceRecord>())) {
1783 throw ApiException("Hosting backend does not support editing records.");
6cc98ddf 1784 }
d708640f
CH
1785 }
1786 else if (changetype == "REPLACE") {
1d6b70f9 1787 // we only validate for REPLACE, as DELETE can be used to "fix" out of zone records.
e325f20c 1788 if (!qname.isPartOf(zonename) && qname != zonename)
edda67a2 1789 throw ApiException("RRset "+qname.toString()+" IN "+qtype.getName()+": Name is out of zone");
34df6ecc 1790
6754ef71
CH
1791 bool replace_records = rrset["records"].is_array();
1792 bool replace_comments = rrset["comments"].is_array();
f63168e6 1793
6754ef71
CH
1794 if (!replace_records && !replace_comments) {
1795 throw ApiException("No change for RRset " + qname.toString() + " IN " + qtype.getName());
1796 }
f63168e6 1797
6754ef71
CH
1798 new_records.clear();
1799 new_comments.clear();
f63168e6 1800
6754ef71
CH
1801 if (replace_records) {
1802 // ttl shouldn't be part of DELETE, and it shouldn't be required if we don't get new records.
1803 int ttl = intFromJson(rrset, "ttl");
1804 // new_ptrs is merged.
1805 gatherRecords(rrset, qname, qtype, ttl, new_records, new_ptrs);
1806
1807 for(DNSResourceRecord& rr : new_records) {
1808 rr.domain_id = di.id;
1809 if (rr.qtype.getCode() == QType::SOA && rr.qname==zonename) {
1810 soa_edit_done = increaseSOARecord(rr, soa_edit_api_kind, soa_edit_kind);
6754ef71 1811 }
d708640f 1812 }
e3675a8a 1813 checkDuplicateRecords(new_records);
6cc98ddf
CH
1814 }
1815
6754ef71
CH
1816 if (replace_comments) {
1817 gatherComments(rrset, qname, qtype, new_comments);
f63168e6 1818
6754ef71
CH
1819 for(Comment& c : new_comments) {
1820 c.domain_id = di.id;
1821 }
d708640f 1822 }
b3905a3d 1823
d708640f 1824 if (replace_records) {
03b1cc25 1825 bool ent_present = false;
8560f36a
CH
1826 di.backend->lookup(QType(QType::ANY), qname);
1827 DNSResourceRecord rr;
1828 while (di.backend->get(rr)) {
03b1cc25
CH
1829 if (qtype.getCode() == 0) {
1830 ent_present = true;
1831 }
8560f36a
CH
1832 if (qtype.getCode() == QType::CNAME && rr.qtype.getCode() != QType::CNAME) {
1833 throw ApiException("RRset "+qname.toString()+" IN "+qtype.getName()+": Conflicts with pre-existing non-CNAME RRset");
1834 } else if (qtype.getCode() != QType::CNAME && rr.qtype.getCode() == QType::CNAME) {
1835 throw ApiException("RRset "+qname.toString()+" IN "+qtype.getName()+": Conflicts with pre-existing CNAME RRset");
1836 }
1837 }
1838
03b1cc25
CH
1839 if (!new_records.empty() && ent_present) {
1840 QType qt_ent{0};
1841 if (!di.backend->replaceRRSet(di.id, qname, qt_ent, new_records)) {
1842 throw ApiException("Hosting backend does not support editing records.");
1843 }
1844 }
d708640f
CH
1845 if (!di.backend->replaceRRSet(di.id, qname, qtype, new_records)) {
1846 throw ApiException("Hosting backend does not support editing records.");
1847 }
1848 }
1849 if (replace_comments) {
1850 if (!di.backend->replaceComments(di.id, qname, qtype, new_comments)) {
1851 throw ApiException("Hosting backend does not support editing comments.");
1852 }
1853 }
6cc98ddf 1854 }
d708640f
CH
1855 else
1856 throw ApiException("Changetype not understood");
6cc98ddf 1857 }
d29d5db7
CH
1858
1859 // edit SOA (if needed)
1860 if (!soa_edit_api_kind.empty() && !soa_edit_done) {
1861 SOAData sd;
13f9e280 1862 if (!B.getSOAUncached(zonename, sd, true))
290a083d 1863 throw ApiException("No SOA found for domain '"+zonename.toString()+"'");
d29d5db7
CH
1864
1865 DNSResourceRecord rr;
13f9e280
CH
1866 if (makeIncreasedSOARecord(sd, soa_edit_api_kind, soa_edit_kind, rr)) {
1867 if (!di.backend->replaceRRSet(di.id, rr.qname, rr.qtype, vector<DNSResourceRecord>(1, rr))) {
1868 throw ApiException("Hosting backend does not support editing records.");
1869 }
d29d5db7 1870 }
3ae63ca8 1871
478de03b
KW
1872 // return old and new serials in headers
1873 resp->headers["X-PDNS-Old-Serial"] = std::to_string(sd.serial);
3ae63ca8 1874 fillSOAData(rr.content, sd);
478de03b 1875 resp->headers["X-PDNS-New-Serial"] = std::to_string(sd.serial);
d29d5db7
CH
1876 }
1877
d708640f
CH
1878 } catch(...) {
1879 di.backend->abortTransaction();
1880 throw;
1881 }
986e4858 1882
b0486ea5 1883 DNSSECKeeper dk(&B);
986e4858
PL
1884 string api_rectify;
1885 di.backend->getDomainMetadataOne(zonename, "API-RECTIFY", api_rectify);
1886 if (dk.isSecuredZone(zonename) && !dk.isPresigned(zonename) && api_rectify == "1") {
1887 string error_msg = "";
59102608
RG
1888 string info;
1889 if (!dk.rectifyZone(zonename, error_msg, info, false))
986e4858
PL
1890 throw ApiException("Failed to rectify '" + zonename.toString() + "' " + error_msg);
1891 }
1892
d708640f 1893 di.backend->commitTransaction();
b3905a3d 1894
bf269e28 1895 purgeAuthCachesExact(zonename);
d1587ceb 1896
d708640f 1897 // now the PTRs
995473c8 1898 storeChangedPTRs(B, new_ptrs);
b3905a3d 1899
f0e76cee
CH
1900 resp->body = "";
1901 resp->status = 204; // No Content, but indicate success
1902 return;
b3905a3d
CH
1903}
1904
b1902fab
CH
1905static void apiServerSearchData(HttpRequest* req, HttpResponse* resp) {
1906 if(req->method != "GET")
1907 throw HttpMethodNotAllowedException();
1908
583ea80d 1909 string q = req->getvars["q"];
720ed2bd
AT
1910 string sMax = req->getvars["max"];
1911 int maxEnts = 100;
1912 int ents = 0;
1913
b1902fab
CH
1914 if (q.empty())
1915 throw ApiException("Query q can't be blank");
606c8752 1916 if (!sMax.empty())
335da0ba 1917 maxEnts = std::stoi(sMax);
720ed2bd
AT
1918 if (maxEnts < 1)
1919 throw ApiException("Maximum entries must be larger than 0");
b1902fab 1920
720ed2bd 1921 SimpleMatch sm(q,true);
b1902fab 1922 UeberBackend B;
b1902fab 1923 vector<DomainInfo> domains;
720ed2bd
AT
1924 vector<DNSResourceRecord> result_rr;
1925 vector<Comment> result_c;
1d6b70f9
CH
1926 map<int,DomainInfo> zoneIdZone;
1927 map<int,DomainInfo>::iterator val;
00963dea 1928 Json::array doc;
b1902fab 1929
720ed2bd 1930 B.getAllDomains(&domains, true);
d2d194a9 1931
720ed2bd 1932 for(const DomainInfo di: domains)
1d6b70f9 1933 {
720ed2bd 1934 if (ents < maxEnts && sm.match(di.zone)) {
00963dea
CH
1935 doc.push_back(Json::object {
1936 { "object_type", "zone" },
1937 { "zone_id", apiZoneNameToId(di.zone) },
1938 { "name", di.zone.toString() }
1939 });
720ed2bd 1940 ents++;
b1902fab 1941 }
1d6b70f9 1942 zoneIdZone[di.id] = di; // populate cache
720ed2bd 1943 }
b1902fab 1944
720ed2bd
AT
1945 if (B.searchRecords(q, maxEnts, result_rr))
1946 {
1947 for(const DNSResourceRecord& rr: result_rr)
1948 {
7cbc5255
CH
1949 if (!rr.qtype.getCode())
1950 continue; // skip empty non-terminals
1951
00963dea
CH
1952 auto object = Json::object {
1953 { "object_type", "record" },
1954 { "name", rr.qname.toString() },
1955 { "type", rr.qtype.getName() },
1956 { "ttl", (double)rr.ttl },
1957 { "disabled", rr.disabled },
1958 { "content", makeApiRecordContent(rr.qtype, rr.content) }
1959 };
720ed2bd 1960 if ((val = zoneIdZone.find(rr.domain_id)) != zoneIdZone.end()) {
00963dea
CH
1961 object["zone_id"] = apiZoneNameToId(val->second.zone);
1962 object["zone"] = val->second.zone.toString();
720ed2bd 1963 }
00963dea 1964 doc.push_back(object);
b1902fab 1965 }
720ed2bd 1966 }
b1902fab 1967
720ed2bd
AT
1968 if (B.searchComments(q, maxEnts, result_c))
1969 {
1970 for(const Comment &c: result_c)
1971 {
00963dea
CH
1972 auto object = Json::object {
1973 { "object_type", "comment" },
25dcc05f 1974 { "name", c.qname.toString() },
00963dea
CH
1975 { "content", c.content }
1976 };
720ed2bd 1977 if ((val = zoneIdZone.find(c.domain_id)) != zoneIdZone.end()) {
00963dea
CH
1978 object["zone_id"] = apiZoneNameToId(val->second.zone);
1979 object["zone"] = val->second.zone.toString();
720ed2bd 1980 }
00963dea 1981 doc.push_back(object);
b1902fab
CH
1982 }
1983 }
4bd3d119 1984
b1902fab
CH
1985 resp->setBody(doc);
1986}
1987
c0f6a1da 1988void apiServerCacheFlush(HttpRequest* req, HttpResponse* resp) {
136965be 1989 if(req->method != "PUT" || ::arg().mustDo("api-readonly"))
a426cb89 1990 throw HttpMethodNotAllowedException();
80d59cd1 1991
c0f6a1da
CH
1992 DNSName canon = apiNameToDNSName(req->getvars["domain"]);
1993
bf269e28 1994 uint64_t count = purgeAuthCachesExact(canon);
f682752a 1995 resp->setBody(Json::object {
bf269e28
RG
1996 { "count", (int) count },
1997 { "result", "Flushed cache." }
f682752a 1998 });
ddc84d12
CH
1999}
2000
dea47634 2001void AuthWebServer::cssfunction(HttpRequest* req, HttpResponse* resp)
c67bf8c5 2002{
80d59cd1
CH
2003 resp->headers["Cache-Control"] = "max-age=86400";
2004 resp->headers["Content-Type"] = "text/css";
c67bf8c5 2005
1071abdd 2006 ostringstream ret;
1071abdd
CH
2007 ret<<"* { box-sizing: border-box; margin: 0; padding: 0; }"<<endl;
2008 ret<<"body { color: black; background: white; margin-top: 1em; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 10pt; position: relative; }"<<endl;
2009 ret<<"a { color: #0959c2; }"<<endl;
2010 ret<<"a:hover { color: #3B8EC8; }"<<endl;
2011 ret<<".row { width: 940px; max-width: 100%; min-width: 768px; margin: 0 auto; }"<<endl;
2012 ret<<".row:before, .row:after { display: table; content:\" \"; }"<<endl;
2013 ret<<".row:after { clear: both; }"<<endl;
2014 ret<<".columns { position: relative; min-height: 1px; float: left; }"<<endl;
2015 ret<<".all { width: 100%; }"<<endl;
2016 ret<<".headl { width: 60%; }"<<endl;
2017 ret<<".headr { width: 39.5%; float: right; background-repeat: no-repeat; margin-top: 7px; ";
2018 ret<<"background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJoAAAAUCAYAAAB1RSS/AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAACtgAAArYBAHIqtQAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAABBTSURBVGiBtVp7cFRVmv9u3763b7/f9It00iFACBohgCEyQYgKI49CLV3cW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5WsP+uUNh0IAAP8PaQRnE4MgdzkAAAAASUVORK5CYII=);";
2019 ret<<" width: 154px; height: 20px; }"<<endl;
2020 ret<<"a#appname { margin: 0; font-size: 27px; color: #666; text-decoration: none; font-weight: bold; display: block; }"<<endl;
2021 ret<<"footer { border-top: 1px solid #ddd; padding-top: 4px; font-size: 12px; }"<<endl;
2022 ret<<"footer.row { margin-top: 1em; margin-bottom: 1em; }"<<endl;
2023 ret<<".panel { background: #f2f2f2; border: 1px solid #e6e6e6; margin: 0 0 22px 0; padding: 20px; }"<<endl;
2024 ret<<"table.data { width: 100%; border-spacing: 0; border-top: 1px solid #333; }"<<endl;
2025 ret<<"table.data td { border-bottom: 1px solid #333; padding: 2px; }"<<endl;
2026 ret<<"table.data tr:nth-child(2n) { background: #e2e2e2; }"<<endl;
2027 ret<<"table.data tr:hover { background: white; }"<<endl;
2028 ret<<".ringmeta { margin-bottom: 5px; }"<<endl;
2029 ret<<".resetring {float: right; }"<<endl;
2030 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;
2031 ret<<".resetring:hover i { background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAA2ElEQVQY013PMUoDcRDF4c+kEzxCsNNCrBQvIGhnlcYm11EkBxAraw8gglgIoiJpAoKIYlBcgrgopsma3c3fwt1k9cHA480M8xvQp/nMjorOWY5ov7IAYlpjQk7aYxcuWBpwFQgJnUcaYk7GhEDIGL5w+MVpKLIRyR2b4JOjvGhUKzHTv2W7iuSN479Dvu9plf1awbQ6y3x1sU5tjpVJcMbakF6Ycoas8Dl5xEHJ160wRdfqzXfa6XQ4PLDlicWUjxHxZfndL/N+RhiwNzl/Q6PDhn/qsl76H7prcApk2B1aAAAAAElFTkSuQmCC);}"<<endl;
2032 ret<<".resizering {float: right;}"<<endl;
80d59cd1 2033 resp->body = ret.str();
c146576d 2034 resp->status = 200;
1071abdd
CH
2035}
2036
dea47634 2037void AuthWebServer::webThread()
12c86877
BH
2038{
2039 try {
479e0976 2040 if(::arg().mustDo("api")) {
c0f6a1da 2041 d_ws->registerApiHandler("/api/v1/servers/localhost/cache/flush", &apiServerCacheFlush);
46d06a12 2042 d_ws->registerApiHandler("/api/v1/servers/localhost/config", &apiServerConfig);
46d06a12
PL
2043 d_ws->registerApiHandler("/api/v1/servers/localhost/search-log", &apiServerSearchLog);
2044 d_ws->registerApiHandler("/api/v1/servers/localhost/search-data", &apiServerSearchData);
2045 d_ws->registerApiHandler("/api/v1/servers/localhost/statistics", &apiServerStatistics);
fa07a3cf
PL
2046 d_ws->registerApiHandler("/api/v1/servers/localhost/tsigkeys/<id>", &apiServerTsigKeyDetail);
2047 d_ws->registerApiHandler("/api/v1/servers/localhost/tsigkeys", &apiServerTsigKeys);
46d06a12
PL
2048 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/axfr-retrieve", &apiServerZoneAxfrRetrieve);
2049 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/cryptokeys/<key_id>", &apiZoneCryptokeys);
2050 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/cryptokeys", &apiZoneCryptokeys);
2051 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/export", &apiServerZoneExport);
24e11043
CJ
2052 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/metadata/<kind>", &apiZoneMetadataKind);
2053 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/metadata", &apiZoneMetadata);
46d06a12 2054 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/notify", &apiServerZoneNotify);
4bc8379e 2055 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/rectify", &apiServerZoneRectify);
46d06a12
PL
2056 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>", &apiServerZoneDetail);
2057 d_ws->registerApiHandler("/api/v1/servers/localhost/zones", &apiServerZones);
2058 d_ws->registerApiHandler("/api/v1/servers/localhost", &apiServerDetail);
2059 d_ws->registerApiHandler("/api/v1/servers", &apiServer);
9e6d2033 2060 d_ws->registerApiHandler("/api", &apiDiscovery);
c67bf8c5 2061 }
536ab56f
CH
2062 if (::arg().mustDo("webserver")) {
2063 d_ws->registerWebHandler("/style.css", boost::bind(&AuthWebServer::cssfunction, this, _1, _2));
2064 d_ws->registerWebHandler("/", boost::bind(&AuthWebServer::indexfunction, this, _1, _2));
2065 }
96d299db 2066 d_ws->go();
12c86877
BH
2067 }
2068 catch(...) {
e6a9dde5 2069 g_log<<Logger::Error<<"AuthWebServer thread caught an exception, dying"<<endl;
5bd2ea7b 2070 _exit(1);
12c86877
BH
2071 }
2072}