]> git.ipfire.org Git - thirdparty/pdns.git/blame - pdns/ws-auth.cc
Merge pull request #5113 from RobinGeuze/addPerPoolPolicy
[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"
e611a06c 31#include "packetcache.hh"
12c86877
BH
32#include "statbag.hh"
33#include "misc.hh"
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"
3c3c006b 47
8537b9f0 48
24afabad 49using json11::Json;
12c86877
BH
50
51extern StatBag S;
995473c8 52extern PacketCache PC;
12c86877 53
f63168e6 54static void patchZone(HttpRequest* req, HttpResponse* resp);
995473c8 55static void storeChangedPTRs(UeberBackend& B, vector<DNSResourceRecord>& new_ptrs);
f63168e6
CH
56static void makePtr(const DNSResourceRecord& rr, DNSResourceRecord* ptr);
57
dea47634 58AuthWebServer::AuthWebServer()
12c86877
BH
59{
60 d_start=time(0);
96d299db 61 d_min10=d_min5=d_min1=0;
c81c2ea8 62 d_ws = 0;
f17c93b4 63 d_tid = 0;
536ab56f 64 if(arg().mustDo("webserver") || arg().mustDo("api")) {
bbef8f04 65 d_ws = new WebServer(arg()["webserver-address"], arg().asNum("webserver-port"));
825fa717
CH
66 d_ws->bind();
67 }
12c86877
BH
68}
69
dea47634 70void AuthWebServer::go()
12c86877 71{
536ab56f
CH
72 S.doRings();
73 pthread_create(&d_tid, 0, webThreadHelper, this);
74 pthread_create(&d_tid, 0, statThreadHelper, this);
12c86877
BH
75}
76
dea47634 77void AuthWebServer::statThread()
12c86877
BH
78{
79 try {
80 for(;;) {
81 d_queries.submit(S.read("udp-queries"));
82 d_cachehits.submit(S.read("packetcache-hit"));
83 d_cachemisses.submit(S.read("packetcache-miss"));
84 d_qcachehits.submit(S.read("query-cache-hit"));
85 d_qcachemisses.submit(S.read("query-cache-miss"));
86 Utility::sleep(1);
87 }
88 }
89 catch(...) {
90 L<<Logger::Error<<"Webserver statThread caught an exception, dying"<<endl;
91 exit(1);
92 }
93}
94
dea47634 95void *AuthWebServer::statThreadHelper(void *p)
12c86877 96{
dea47634
CH
97 AuthWebServer *self=static_cast<AuthWebServer *>(p);
98 self->statThread();
12c86877
BH
99 return 0; // never reached
100}
101
dea47634 102void *AuthWebServer::webThreadHelper(void *p)
12c86877 103{
dea47634
CH
104 AuthWebServer *self=static_cast<AuthWebServer *>(p);
105 self->webThread();
12c86877
BH
106 return 0; // never reached
107}
108
9f3fdaa0
CH
109static string htmlescape(const string &s) {
110 string result;
111 for(string::const_iterator it=s.begin(); it!=s.end(); ++it) {
112 switch (*it) {
113 case '&':
c86a96f9 114 result += "&amp;";
9f3fdaa0
CH
115 break;
116 case '<':
117 result += "&lt;";
118 break;
119 case '>':
120 result += "&gt;";
121 break;
c7f59d62
PL
122 case '"':
123 result += "&quot;";
124 break;
9f3fdaa0
CH
125 default:
126 result += *it;
127 }
128 }
129 return result;
130}
131
12c86877
BH
132void printtable(ostringstream &ret, const string &ringname, const string &title, int limit=10)
133{
134 int tot=0;
135 int entries=0;
101b5d5d 136 vector<pair <string,unsigned int> >ring=S.getRing(ringname);
12c86877 137
1071abdd 138 for(vector<pair<string, unsigned int> >::const_iterator i=ring.begin(); i!=ring.end();++i) {
12c86877
BH
139 tot+=i->second;
140 entries++;
141 }
142
1071abdd 143 ret<<"<div class=\"panel\">";
c7f59d62 144 ret<<"<span class=resetring><i></i><a href=\"?resetring="<<htmlescape(ringname)<<"\">Reset</a></span>"<<endl;
1071abdd
CH
145 ret<<"<h2>"<<title<<"</h2>"<<endl;
146 ret<<"<div class=ringmeta>";
c7f59d62 147 ret<<"<a class=topXofY href=\"?ring="<<htmlescape(ringname)<<"\">Showing: Top "<<limit<<" of "<<entries<<"</a>"<<endl;
1071abdd 148 ret<<"<span class=resizering>Resize: ";
bb3c3f50 149 unsigned int sizes[]={10,100,500,1000,10000,500000,0};
12c86877
BH
150 for(int i=0;sizes[i];++i) {
151 if(S.getRingSize(ringname)!=sizes[i])
c7f59d62 152 ret<<"<a href=\"?resizering="<<htmlescape(ringname)<<"&amp;size="<<sizes[i]<<"\">"<<sizes[i]<<"</a> ";
12c86877
BH
153 else
154 ret<<"("<<sizes[i]<<") ";
155 }
1071abdd 156 ret<<"</span></div>";
12c86877 157
1071abdd 158 ret<<"<table class=\"data\">";
12c86877 159 int printed=0;
f5cb7e61 160 int total=max(1,tot);
bb3c3f50 161 for(vector<pair<string,unsigned int> >::const_iterator i=ring.begin();limit && i!=ring.end();++i,--limit) {
dea47634 162 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
163 printed+=i->second;
164 }
165 ret<<"<tr><td colspan=3></td></tr>"<<endl;
166 if(printed!=tot)
dea47634 167 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 168
e2a77e08 169 ret<<"<tr><td><b>Total:</b></td><td><b>"<<tot<<"</b></td><td align=right><b>100%</b></td>";
1071abdd 170 ret<<"</table></div>"<<endl;
12c86877
BH
171}
172
dea47634 173void AuthWebServer::printvars(ostringstream &ret)
12c86877 174{
1071abdd 175 ret<<"<div class=panel><h2>Variables</h2><table class=\"data\">"<<endl;
12c86877
BH
176
177 vector<string>entries=S.getEntries();
178 for(vector<string>::const_iterator i=entries.begin();i!=entries.end();++i) {
179 ret<<"<tr><td>"<<*i<<"</td><td>"<<S.read(*i)<<"</td><td>"<<S.getDescrip(*i)<<"</td>"<<endl;
180 }
e2a77e08 181
1071abdd 182 ret<<"</table></div>"<<endl;
12c86877
BH
183}
184
dea47634 185void AuthWebServer::printargs(ostringstream &ret)
12c86877 186{
e2a77e08 187 ret<<"<table border=1><tr><td colspan=3 bgcolor=\"#0000ff\"><font color=\"#ffffff\">Arguments</font></td>"<<endl;
12c86877
BH
188
189 vector<string>entries=arg().list();
190 for(vector<string>::const_iterator i=entries.begin();i!=entries.end();++i) {
191 ret<<"<tr><td>"<<*i<<"</td><td>"<<arg()[*i]<<"</td><td>"<<arg().getHelp(*i)<<"</td>"<<endl;
192 }
193}
194
dea47634 195string AuthWebServer::makePercentage(const double& val)
b6f57093
BH
196{
197 return (boost::format("%.01f%%") % val).str();
198}
199
dea47634 200void AuthWebServer::indexfunction(HttpRequest* req, HttpResponse* resp)
12c86877 201{
583ea80d
CH
202 if(!req->getvars["resetring"].empty()) {
203 if (S.ringExists(req->getvars["resetring"]))
204 S.resetRing(req->getvars["resetring"]);
80d59cd1 205 resp->status = 301;
0665b7e6 206 resp->headers["Location"] = req->url.path;
80d59cd1 207 return;
12c86877 208 }
583ea80d 209 if(!req->getvars["resizering"].empty()){
335da0ba 210 int size=std::stoi(req->getvars["size"]);
583ea80d 211 if (S.ringExists(req->getvars["resizering"]) && size > 0 && size <= 500000)
335da0ba 212 S.resizeRing(req->getvars["resizering"], std::stoi(req->getvars["size"]));
80d59cd1 213 resp->status = 301;
0665b7e6 214 resp->headers["Location"] = req->url.path;
80d59cd1 215 return;
12c86877
BH
216 }
217
218 ostringstream ret;
219
1071abdd
CH
220 ret<<"<!DOCTYPE html>"<<endl;
221 ret<<"<html><head>"<<endl;
222 ret<<"<title>PowerDNS Authoritative Server Monitor</title>"<<endl;
223 ret<<"<link rel=\"stylesheet\" href=\"style.css\"/>"<<endl;
224 ret<<"</head><body>"<<endl;
225
226 ret<<"<div class=\"row\">"<<endl;
227 ret<<"<div class=\"headl columns\">";
a1caa8b8 228 ret<<"<a href=\"/\" id=\"appname\">PowerDNS "<<htmlescape(VERSION);
1071abdd 229 if(!arg()["config-name"].empty()) {
a1caa8b8 230 ret<<" ["<<htmlescape(arg()["config-name"])<<"]";
1071abdd
CH
231 }
232 ret<<"</a></div>"<<endl;
233 ret<<"<div class=\"headr columns\"></div></div>";
234 ret<<"<div class=\"row\"><div class=\"all columns\">";
12c86877
BH
235
236 time_t passed=time(0)-s_starttime;
237
e2a77e08
KM
238 ret<<"<p>Uptime: "<<
239 humanDuration(passed)<<
240 "<br>"<<endl;
12c86877 241
395b07ea 242 ret<<"Queries/second, 1, 5, 10 minute averages: "<<std::setprecision(3)<<
f6154a3b
CH
243 d_queries.get1()<<", "<<
244 d_queries.get5()<<", "<<
245 d_queries.get10()<<". Max queries/second: "<<d_queries.getMax()<<
12c86877 246 "<br>"<<endl;
1d6b70f9 247
f6154a3b 248 if(d_cachemisses.get10()+d_cachehits.get10()>0)
b6f57093 249 ret<<"Cache hitrate, 1, 5, 10 minute averages: "<<
f6154a3b
CH
250 makePercentage((d_cachehits.get1()*100.0)/((d_cachehits.get1())+(d_cachemisses.get1())))<<", "<<
251 makePercentage((d_cachehits.get5()*100.0)/((d_cachehits.get5())+(d_cachemisses.get5())))<<", "<<
252 makePercentage((d_cachehits.get10()*100.0)/((d_cachehits.get10())+(d_cachemisses.get10())))<<
b6f57093 253 "<br>"<<endl;
12c86877 254
f6154a3b 255 if(d_qcachemisses.get10()+d_qcachehits.get10()>0)
395b07ea 256 ret<<"Backend query cache hitrate, 1, 5, 10 minute averages: "<<std::setprecision(2)<<
f6154a3b
CH
257 makePercentage((d_qcachehits.get1()*100.0)/((d_qcachehits.get1())+(d_qcachemisses.get1())))<<", "<<
258 makePercentage((d_qcachehits.get5()*100.0)/((d_qcachehits.get5())+(d_qcachemisses.get5())))<<", "<<
259 makePercentage((d_qcachehits.get10()*100.0)/((d_qcachehits.get10())+(d_qcachemisses.get10())))<<
b6f57093 260 "<br>"<<endl;
12c86877 261
395b07ea 262 ret<<"Backend query load, 1, 5, 10 minute averages: "<<std::setprecision(3)<<
f6154a3b
CH
263 d_qcachemisses.get1()<<", "<<
264 d_qcachemisses.get5()<<", "<<
265 d_qcachemisses.get10()<<". Max queries/second: "<<d_qcachemisses.getMax()<<
12c86877
BH
266 "<br>"<<endl;
267
1071abdd 268 ret<<"Total queries: "<<S.read("udp-queries")<<". Question/answer latency: "<<S.read("latency")/1000.0<<"ms</p><br>"<<endl;
583ea80d 269 if(req->getvars["ring"].empty()) {
12c86877
BH
270 vector<string>entries=S.listRings();
271 for(vector<string>::const_iterator i=entries.begin();i!=entries.end();++i)
272 printtable(ret,*i,S.getRingTitle(*i));
273
f6154a3b 274 printvars(ret);
12c86877 275 if(arg().mustDo("webserver-print-arguments"))
f6154a3b 276 printargs(ret);
12c86877 277 }
bea69e32 278 else if(S.ringExists(req->getvars["ring"]))
583ea80d 279 printtable(ret,req->getvars["ring"],S.getRingTitle(req->getvars["ring"]),100);
12c86877 280
1071abdd 281 ret<<"</div></div>"<<endl;
ff8f70b8 282 ret<<"<footer class=\"row\">"<<fullVersionString()<<"<br>&copy; 2013 - 2017 <a href=\"http://www.powerdns.com/\">PowerDNS.COM BV</a>.</footer>"<<endl;
12c86877
BH
283 ret<<"</body></html>"<<endl;
284
80d59cd1 285 resp->body = ret.str();
61f5d289 286 resp->status = 200;
12c86877
BH
287}
288
1d6b70f9
CH
289/** Helper to build a record content as needed. */
290static inline string makeRecordContent(const QType& qtype, const string& content, bool noDot) {
291 // noDot: for backend storage, pass true. for API users, pass false.
7fe1a82b 292 std::unique_ptr<DNSRecordContent> drc(DNSRecordContent::mastermake(qtype.getCode(), 1, content));
293 return drc->getZoneRepresentation(noDot);
1d6b70f9
CH
294}
295
296/** "Normalize" record content for API consumers. */
297static inline string makeApiRecordContent(const QType& qtype, const string& content) {
298 return makeRecordContent(qtype, content, false);
299}
300
301/** "Normalize" record content for backend storage. */
302static inline string makeBackendRecordContent(const QType& qtype, const string& content) {
303 return makeRecordContent(qtype, content, true);
304}
305
ce846be6 306static Json::object getZoneInfo(const DomainInfo& di, DNSSECKeeper *dk) {
290a083d 307 string zoneId = apiZoneNameToId(di.zone);
62a9a74c
CH
308 return Json::object {
309 // id is the canonical lookup key, which doesn't actually match the name (in some cases)
310 { "id", zoneId },
16e25450 311 { "url", "/api/v1/servers/localhost/zones/" + zoneId },
62a9a74c
CH
312 { "name", di.zone.toString() },
313 { "kind", di.getKindString() },
ce846be6 314 { "dnssec", dk->isSecuredZone(di.zone) },
62a9a74c
CH
315 { "account", di.account },
316 { "masters", di.masters },
317 { "serial", (double)di.serial },
318 { "notified_serial", (double)di.notified_serial },
319 { "last_check", (double)di.last_check }
320 };
c04b5870
CH
321}
322
290a083d 323static void fillZone(const DNSName& zonename, HttpResponse* resp) {
1abb81f4 324 UeberBackend B;
1abb81f4 325 DomainInfo di;
73301d73 326 if(!B.getDomainInfo(zonename, di))
290a083d 327 throw ApiException("Could not find domain '"+zonename.toString()+"'");
1abb81f4 328
adef67eb 329 DNSSECKeeper dk(&B);
ce846be6 330 Json::object doc = getZoneInfo(di, &dk);
62a9a74c 331 // extra stuff getZoneInfo doesn't do for us (more expensive)
d29d5db7
CH
332 string soa_edit_api;
333 di.backend->getDomainMetadataOne(zonename, "SOA-EDIT-API", soa_edit_api);
62a9a74c 334 doc["soa_edit_api"] = soa_edit_api;
6bb25159
MS
335 string soa_edit;
336 di.backend->getDomainMetadataOne(zonename, "SOA-EDIT", soa_edit);
62a9a74c 337 doc["soa_edit"] = soa_edit;
1abb81f4 338
6754ef71
CH
339 vector<DNSResourceRecord> records;
340 vector<Comment> comments;
1abb81f4 341
6754ef71
CH
342 // load all records + sort
343 {
344 DNSResourceRecord rr;
345 di.backend->list(zonename, di.id, true); // incl. disabled
346 while(di.backend->get(rr)) {
347 if (!rr.qtype.getCode())
348 continue; // skip empty non-terminals
349 records.push_back(rr);
350 }
351 sort(records.begin(), records.end(), [](const DNSResourceRecord& a, const DNSResourceRecord& b) {
352 if (a.qname == b.qname) {
353 return b.qtype < a.qtype;
354 }
355 return b.qname < a.qname;
356 });
357 }
358
359 // load all comments + sort
360 {
361 Comment comment;
362 di.backend->listComments(di.id);
363 while(di.backend->getComment(comment)) {
364 comments.push_back(comment);
365 }
366 sort(comments.begin(), comments.end(), [](const Comment& a, const Comment& b) {
367 if (a.qname == b.qname) {
368 return b.qtype < a.qtype;
369 }
370 return b.qname < a.qname;
371 });
372 }
373
374 Json::array rrsets;
375 Json::object rrset;
376 Json::array rrset_records;
377 Json::array rrset_comments;
378 DNSName current_qname;
379 QType current_qtype;
380 uint32_t ttl;
381 auto rit = records.begin();
382 auto cit = comments.begin();
383
384 while (rit != records.end() || cit != comments.end()) {
b43f5903 385 if (cit == comments.end() || (rit != records.end() && (cit->qname.toString() <= rit->qname.toString() || cit->qtype < rit->qtype || cit->qtype == rit->qtype))) {
6754ef71
CH
386 current_qname = rit->qname;
387 current_qtype = rit->qtype;
388 ttl = rit->ttl;
389 } else {
390 current_qname = cit->qname;
391 current_qtype = cit->qtype;
392 ttl = 0;
393 }
394
395 while(rit != records.end() && rit->qname == current_qname && rit->qtype == current_qtype) {
396 ttl = min(ttl, rit->ttl);
397 rrset_records.push_back(Json::object {
398 { "disabled", rit->disabled },
399 { "content", makeApiRecordContent(rit->qtype, rit->content) }
400 });
401 rit++;
402 }
403 while (cit != comments.end() && cit->qname == current_qname && cit->qtype == current_qtype) {
404 rrset_comments.push_back(Json::object {
405 { "modified_at", (double)cit->modified_at },
406 { "account", cit->account },
407 { "content", cit->content }
408 });
409 cit++;
410 }
411
412 rrset["name"] = current_qname.toString();
413 rrset["type"] = current_qtype.getName();
414 rrset["records"] = rrset_records;
415 rrset["comments"] = rrset_comments;
416 rrset["ttl"] = (double)ttl;
417 rrsets.push_back(rrset);
418 rrset.clear();
419 rrset_records.clear();
420 rrset_comments.clear();
421 }
422
423 doc["rrsets"] = rrsets;
6cc98ddf 424
669822d0 425 resp->setBody(doc);
1abb81f4
CH
426}
427
6ec5e728
CH
428void productServerStatisticsFetch(map<string,string>& out)
429{
a45303b8 430 vector<string> items = S.getEntries();
ff05fd12 431 for(const string& item : items) {
335da0ba 432 out[item] = std::to_string(S.read(item));
a45303b8
CH
433 }
434
435 // add uptime
335da0ba 436 out["uptime"] = std::to_string(time(0) - s_starttime);
c67bf8c5
CH
437}
438
6754ef71 439static void gatherRecords(const Json container, const DNSName& qname, const QType qtype, const int ttl, vector<DNSResourceRecord>& new_records, vector<DNSResourceRecord>& new_ptrs) {
f63168e6
CH
440 UeberBackend B;
441 DNSResourceRecord rr;
6754ef71
CH
442 rr.qname = qname;
443 rr.qtype = qtype;
444 rr.auth = 1;
445 rr.ttl = ttl;
1f68b185 446 for(auto record : container["records"].array_items()) {
1f68b185 447 string content = stringFromJson(record, "content");
1f68b185
CH
448 rr.disabled = boolFromJson(record, "disabled");
449
1f68b185
CH
450 // validate that the client sent something we can actually parse, and require that data to be dotted.
451 try {
452 if (rr.qtype.getCode() != QType::AAAA) {
453 string tmp = makeApiRecordContent(rr.qtype, content);
454 if (!pdns_iequals(tmp, content)) {
455 throw std::runtime_error("Not in expected format (parsed as '"+tmp+"')");
456 }
457 } else {
458 struct in6_addr tmpbuf;
459 if (inet_pton(AF_INET6, content.c_str(), &tmpbuf) != 1 || content.find('.') != string::npos) {
460 throw std::runtime_error("Invalid IPv6 address");
1e5b9ab9 461 }
f63168e6 462 }
1f68b185
CH
463 rr.content = makeBackendRecordContent(rr.qtype, content);
464 }
465 catch(std::exception& e)
466 {
467 throw ApiException("Record "+rr.qname.toString()+"/"+rr.qtype.getName()+" '"+content+"': "+e.what());
468 }
f63168e6 469
1f68b185
CH
470 if ((rr.qtype.getCode() == QType::A || rr.qtype.getCode() == QType::AAAA) &&
471 boolFromJson(record, "set-ptr", false) == true) {
472 DNSResourceRecord ptr;
473 makePtr(rr, &ptr);
f63168e6 474
1f68b185 475 // verify that there's a zone for the PTR
27c0050c 476 DNSPacket fakePacket(false);
1f68b185
CH
477 SOAData sd;
478 fakePacket.qtype = QType::PTR;
479 if (!B.getAuth(&fakePacket, &sd, ptr.qname))
480 throw ApiException("Could not find domain for PTR '"+ptr.qname.toString()+"' requested for '"+ptr.content+"'");
f63168e6 481
1f68b185
CH
482 ptr.domain_id = sd.domain_id;
483 new_ptrs.push_back(ptr);
f63168e6 484 }
1f68b185
CH
485
486 new_records.push_back(rr);
f63168e6
CH
487 }
488}
489
6754ef71 490static void gatherComments(const Json container, const DNSName& qname, const QType qtype, vector<Comment>& new_comments) {
f63168e6 491 Comment c;
6754ef71
CH
492 c.qname = qname;
493 c.qtype = qtype;
f63168e6
CH
494
495 time_t now = time(0);
1f68b185 496 for (auto comment : container["comments"].array_items()) {
1f68b185
CH
497 c.modified_at = intFromJson(comment, "modified_at", now);
498 c.content = stringFromJson(comment, "content");
499 c.account = stringFromJson(comment, "account");
500 new_comments.push_back(c);
f63168e6
CH
501 }
502}
6cc98ddf 503
1f68b185
CH
504static void updateDomainSettingsFromDocument(const DomainInfo& di, const DNSName& zonename, const Json document) {
505 string zonemaster;
506 for(auto value : document["masters"].array_items()) {
507 string master = value.string_value();
508 if (master.empty())
509 throw ApiException("Master can not be an empty string");
510 zonemaster += master + " ";
bb9fd223
CH
511 }
512
513 di.backend->setKind(zonename, DomainInfo::stringToKind(stringFromJson(document, "kind")));
1f68b185 514 di.backend->setMaster(zonename, zonemaster);
d29d5db7 515
1f68b185
CH
516 if (document["soa_edit_api"].is_string()) {
517 di.backend->setDomainMetadataOne(zonename, "SOA-EDIT-API", document["soa_edit_api"].string_value());
d29d5db7 518 }
1f68b185
CH
519 if (document["soa_edit"].is_string()) {
520 di.backend->setDomainMetadataOne(zonename, "SOA-EDIT", document["soa_edit"].string_value());
6bb25159 521 }
1f68b185
CH
522 if (document["account"].is_string()) {
523 di.backend->setAccount(zonename, document["account"].string_value());
79532aa7 524 }
bb9fd223
CH
525}
526
24e11043
CJ
527static bool isValidMetadataKind(const string& kind, bool readonly) {
528 static vector<string> builtinOptions {
529 "ALLOW-AXFR-FROM",
530 "AXFR-SOURCE",
531 "ALLOW-DNSUPDATE-FROM",
532 "TSIG-ALLOW-DNSUPDATE",
533 "FORWARD-DNSUPDATE",
534 "SOA-EDIT-DNSUPDATE",
535 "ALSO-NOTIFY",
536 "AXFR-MASTER-TSIG",
537 "GSS-ALLOW-AXFR-PRINCIPAL",
538 "GSS-ACCEPTOR-PRINCIPAL",
539 "IXFR",
540 "LUA-AXFR-SCRIPT",
541 "NSEC3NARROW",
542 "NSEC3PARAM",
543 "PRESIGNED",
544 "PUBLISH-CDNSKEY",
545 "PUBLISH-CDS",
546 "SOA-EDIT",
547 "TSIG-ALLOW-AXFR",
548 "TSIG-ALLOW-DNSUPDATE"
549 };
550
551 // the following options do not allow modifications via API
552 static vector<string> protectedOptions {
553 "NSEC3NARROW",
554 "NSEC3PARAM",
555 "PRESIGNED",
556 "LUA-AXFR-SCRIPT"
557 };
558
9ac4e6d5
PL
559 if (kind.find("X-") == 0)
560 return true;
561
24e11043
CJ
562 bool found = false;
563
d8043c73 564 for (const string& s : builtinOptions) {
24e11043 565 if (kind == s) {
d8043c73 566 for (const string& s2 : protectedOptions) {
24e11043
CJ
567 if (!readonly && s == s2)
568 return false;
569 }
570 found = true;
571 break;
572 }
573 }
574
575 return found;
576}
577
578static void apiZoneMetadata(HttpRequest* req, HttpResponse *resp) {
579 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
580 UeberBackend B;
581
582 if (req->method == "GET") {
583 map<string, vector<string> > md;
584 Json::array document;
585
586 if (!B.getAllDomainMetadata(zonename, md))
587 throw HttpNotFoundException();
588
589 for (const auto& i : md) {
590 Json::array entries;
591 for (string j : i.second)
592 entries.push_back(j);
593
594 Json::object key {
595 { "type", "Metadata" },
596 { "kind", i.first },
597 { "metadata", entries }
598 };
599
600 document.push_back(key);
601 }
602
603 resp->setBody(document);
604 } else if (req->method == "POST" && !::arg().mustDo("api-readonly")) {
605 auto document = req->json();
606 string kind;
607 vector<string> entries;
608
609 try {
610 kind = stringFromJson(document, "kind");
611 } catch (JsonException) {
612 throw ApiException("kind is not specified or not a string");
613 }
614
615 if (!isValidMetadataKind(kind, false))
616 throw ApiException("Unsupported metadata kind '" + kind + "'");
617
618 vector<string> vecMetadata;
c6720e79
CJ
619
620 if (!B.getDomainMetadata(zonename, kind, vecMetadata))
621 throw ApiException("Could not retrieve metadata entries for domain '" +
622 zonename.toString() + "'");
623
24e11043
CJ
624 auto& metadata = document["metadata"];
625 if (!metadata.is_array())
626 throw ApiException("metadata is not specified or not an array");
627
628 for (const auto& i : metadata.array_items()) {
629 if (!i.is_string())
630 throw ApiException("metadata must be strings");
c6720e79
CJ
631 else if (std::find(vecMetadata.cbegin(),
632 vecMetadata.cend(),
633 i.string_value()) == vecMetadata.cend()) {
634 vecMetadata.push_back(i.string_value());
635 }
24e11043
CJ
636 }
637
638 if (!B.setDomainMetadata(zonename, kind, vecMetadata))
c6720e79
CJ
639 throw ApiException("Could not update metadata entries for domain '" +
640 zonename.toString() + "'");
641
642 Json::array respMetadata;
643 for (const string& s : vecMetadata)
644 respMetadata.push_back(s);
645
646 Json::object key {
647 { "type", "Metadata" },
648 { "kind", document["kind"] },
649 { "metadata", respMetadata }
650 };
24e11043 651
24e11043 652 resp->status = 201;
c6720e79 653 resp->setBody(key);
24e11043
CJ
654 } else
655 throw HttpMethodNotAllowedException();
656}
657
658static void apiZoneMetadataKind(HttpRequest* req, HttpResponse* resp) {
659 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
660 string kind = req->parameters["kind"];
661 UeberBackend B;
662
663 if (req->method == "GET") {
664 vector<string> metadata;
665 Json::object document;
666 Json::array entries;
667
668 if (!B.getDomainMetadata(zonename, kind, metadata))
669 throw HttpNotFoundException();
670 else if (!isValidMetadataKind(kind, true))
671 throw ApiException("Unsupported metadata kind '" + kind + "'");
672
673 document["type"] = "Metadata";
674 document["kind"] = kind;
675
676 for (const string& i : metadata)
677 entries.push_back(i);
678
679 document["metadata"] = entries;
680 resp->setBody(document);
681 } else if (req->method == "PUT" && !::arg().mustDo("api-readonly")) {
682 auto document = req->json();
683
684 if (!isValidMetadataKind(kind, false))
685 throw ApiException("Unsupported metadata kind '" + kind + "'");
686
687 vector<string> vecMetadata;
688 auto& metadata = document["metadata"];
689 if (!metadata.is_array())
690 throw ApiException("metadata is not specified or not an array");
691
692 for (const auto& i : metadata.array_items()) {
693 if (!i.is_string())
694 throw ApiException("metadata must be strings");
695 vecMetadata.push_back(i.string_value());
696 }
697
698 if (!B.setDomainMetadata(zonename, kind, vecMetadata))
699 throw ApiException("Could not update metadata entries for domain '" + zonename.toString() + "'");
700
701 Json::object key {
702 { "type", "Metadata" },
703 { "kind", kind },
704 { "metadata", metadata }
705 };
706
707 resp->setBody(key);
708 } else if (req->method == "DELETE" && !::arg().mustDo("api-readonly")) {
709 if (!isValidMetadataKind(kind, false))
710 throw ApiException("Unsupported metadata kind '" + kind + "'");
711
712 vector<string> md; // an empty vector will do it
713 if (!B.setDomainMetadata(zonename, kind, md))
714 throw ApiException("Could not delete metadata for domain '" + zonename.toString() + "' (" + kind + ")");
715 } else
716 throw HttpMethodNotAllowedException();
717}
718
60b0a236
BZ
719static void apiZoneCryptokeysGET(DNSName zonename, int inquireKeyId, HttpResponse *resp, DNSSECKeeper *dk) {
720 DNSSECKeeper::keyset_t keyset=dk->getKeys(zonename, false);
4b7f120a 721
997cab68
BZ
722 bool inquireSingleKey = inquireKeyId >= 0;
723
24afabad 724 Json::array doc;
29704f66 725 for(const auto& value : keyset) {
997cab68 726 if (inquireSingleKey && (unsigned)inquireKeyId != value.second.id) {
29704f66 727 continue;
38809e97 728 }
24afabad 729
b6bd795c 730 string keyType;
60b0a236 731 switch (value.second.keyType) {
b6bd795c
PL
732 case DNSSECKeeper::KSK: keyType="ksk"; break;
733 case DNSSECKeeper::ZSK: keyType="zsk"; break;
734 case DNSSECKeeper::CSK: keyType="csk"; break;
735 }
736
24afabad 737 Json::object key {
997cab68
BZ
738 { "type", "Cryptokey" },
739 { "id", (int)value.second.id },
740 { "active", value.second.active },
741 { "keytype", keyType },
742 { "flags", (uint16_t)value.first.d_flags },
743 { "dnskey", value.first.getDNSKEY().getZoneRepresentation() }
24afabad
CH
744 };
745
b6bd795c 746 if (value.second.keyType == DNSSECKeeper::KSK || value.second.keyType == DNSSECKeeper::CSK) {
24afabad
CH
747 Json::array dses;
748 for(const int keyid : { 1, 2, 3, 4 })
997cab68
BZ
749 try {
750 dses.push_back(makeDSFromDNSKey(zonename, value.first.getDNSKEY(), keyid).getZoneRepresentation());
751 } catch (...) {}
24afabad 752 key["ds"] = dses;
4b7f120a 753 }
29704f66
CH
754
755 if (inquireSingleKey) {
756 key["privatekey"] = value.first.getKey()->convertToISC();
757 resp->setBody(key);
758 return;
759 }
24afabad 760 doc.push_back(key);
4b7f120a
MS
761 }
762
29704f66
CH
763 if (inquireSingleKey) {
764 // we came here because we couldn't find the requested key.
765 throw HttpNotFoundException();
766 }
4b7f120a 767 resp->setBody(doc);
997cab68
BZ
768
769}
770
771/*
772 * This method handles DELETE requests for URL /api/v1/servers/:server_id/zones/:zone_name/cryptokeys/:cryptokey_id .
773 * It deletes a key from :zone_name specified by :cryptokey_id.
774 * Server Answers:
60b0a236
BZ
775 * Case 1: the backend returns true on removal. This means the key is gone.
776 * The server returns 200 OK, no body.
955cbfd0 777 * Case 2: the backend returns false on removal. An error occurred.
60b0a236 778 * The sever returns 422 Unprocessable Entity with message "Could not DELETE :cryptokey_id".
997cab68 779 * */
60b0a236
BZ
780static void apiZoneCryptokeysDELETE(DNSName zonename, int inquireKeyId, HttpRequest *req, HttpResponse *resp, DNSSECKeeper *dk) {
781 if (dk->removeKey(zonename, inquireKeyId)) {
782 resp->body = "";
783 resp->status = 200;
997cab68
BZ
784 } else {
785 resp->setErrorResult("Could not DELETE " + req->parameters["key_id"], 422);
786 }
787}
788
789/*
790 * This method adds a key to a zone by generate it or content parameter.
791 * Parameter:
792 * {
793 * "content" : "key The format used is compatible with BIND and NSD/LDNS" <string>
794 * "keytype" : "ksk|zsk" <string>
795 * "active" : "true|false" <value>
1ec08a2b 796 * "algo" : "key generation algorithm "name|number" as default"<string> https://doc.powerdns.com/md/authoritative/dnssec/#supported-algorithms
997cab68
BZ
797 * "bits" : number of bits <int>
798 * }
799 *
800 * Response:
801 * Case 1: keytype isn't ksk|zsk
802 * The server returns 422 Unprocessable Entity {"error" : "Invalid keytype 'keytype'"}
60b0a236
BZ
803 * Case 2: 'bits' must be a positive integer value.
804 * The server returns 422 Unprocessable Entity {"error" : "'bits' must be a positive integer value."}
805 * Case 3: The "algo" isn't supported
997cab68 806 * The server returns 422 Unprocessable Entity {"error" : "Unknown algorithm: 'algo'"}
60b0a236 807 * Case 4: Algorithm <= 10 and no bits were passed
997cab68 808 * The server returns 422 Unprocessable Entity {"error" : "Creating an algorithm algo key requires the size (in bits) to be passed"}
60b0a236
BZ
809 * Case 5: The wrong keysize was passed
810 * The server returns 422 Unprocessable Entity {"error" : "The algorithm does not support the given bit size."}
811 * Case 6: If the server cant guess the keysize
812 * The server returns 422 Unprocessable Entity {"error" : "Can not guess key size for algorithm"}
813 * Case 7: The key-creation failed
997cab68 814 * The server returns 422 Unprocessable Entity {"error" : "Adding key failed, perhaps DNSSEC not enabled in configuration?"}
60b0a236
BZ
815 * Case 8: The key in content has the wrong format
816 * The server returns 422 Unprocessable Entity {"error" : "Key could not be parsed. Make sure your key format is correct."}
817 * Case 9: The wrong combination of fields is submitted
818 * The server returns 422 Unprocessable Entity {"error" : "Either you submit just the 'content' field or you leave 'content' empty and submit the other fields."}
819 * Case 10: No content and everything was fine
820 * The server returns 201 Created and all public data about the new cryptokey
821 * Case 11: With specified content
822 * The server returns 201 Created and all public data about the added cryptokey
997cab68
BZ
823 */
824
60b0a236 825static void apiZoneCryptokeysPOST(DNSName zonename, HttpRequest *req, HttpResponse *resp, DNSSECKeeper *dk) {
997cab68
BZ
826 auto document = req->json();
827 auto content = document["content"];
997cab68 828 bool active = boolFromJson(document, "active", false);
997cab68 829 bool keyOrZone;
60b0a236 830
997cab68
BZ
831 if (stringFromJson(document, "keytype") == "ksk") {
832 keyOrZone = true;
833 } else if (stringFromJson(document, "keytype") == "zsk") {
834 keyOrZone = false;
835 } else {
836 throw ApiException("Invalid keytype " + stringFromJson(document, "keytype"));
837 }
838
60b0a236 839 int64_t insertedId;
997cab68 840
997cab68 841 if (content.is_null()) {
60b0a236
BZ
842 int bits = 0;
843 auto docbits = document["bits"];
844 if (!docbits.is_null()) {
845 if (!docbits.is_number() || (fmod(docbits.number_value(), 1.0) != 0) || docbits.int_value() < 0) {
846 throw ApiException("'bits' must be a positive integer value");
847 } else {
848 bits = docbits.int_value();
849 }
850 }
997cab68
BZ
851 int algorithm = 13; // ecdsa256
852 auto providedAlgo = document["algo"];
853 if (providedAlgo.is_string()) {
60b0a236
BZ
854 algorithm = DNSSECKeeper::shorthand2algorithm(providedAlgo.string_value());
855 if (algorithm == -1)
997cab68 856 throw ApiException("Unknown algorithm: " + providedAlgo.string_value());
997cab68
BZ
857 } else if (providedAlgo.is_number()) {
858 algorithm = providedAlgo.int_value();
60b0a236
BZ
859 } else if (!providedAlgo.is_null()) {
860 throw ApiException("Unknown algorithm: " + providedAlgo.string_value());
997cab68
BZ
861 }
862
60b0a236
BZ
863 try {
864 dk->addKey(zonename, keyOrZone, algorithm, insertedId, bits, active);
865 } catch (std::runtime_error& error) {
997cab68
BZ
866 throw ApiException(error.what());
867 }
997cab68
BZ
868 if (insertedId < 0)
869 throw ApiException("Adding key failed, perhaps DNSSEC not enabled in configuration?");
60b0a236 870 } else if (document["bits"].is_null() && document["algo"].is_null()) {
997cab68
BZ
871 auto keyData = stringFromJson(document, "content");
872 DNSKEYRecordContent dkrc;
873 DNSSECPrivateKey dpk;
60b0a236 874 try {
997cab68
BZ
875 shared_ptr<DNSCryptoKeyEngine> dke(DNSCryptoKeyEngine::makeFromISCString(dkrc, keyData));
876 dpk.d_algorithm = dkrc.d_algorithm;
877 if(dpk.d_algorithm == 7)
878 dpk.d_algorithm = 5;
879
880 if (keyOrZone)
881 dpk.d_flags = 257;
882 else
883 dpk.d_flags = 256;
884
885 dpk.setKey(dke);
997cab68 886 }
60b0a236
BZ
887 catch (std::runtime_error& error) {
888 throw ApiException("Key could not be parsed. Make sure your key format is correct.");
889 } try {
890 dk->addKey(zonename, dpk,insertedId, active);
891 } catch (std::runtime_error& error) {
997cab68
BZ
892 throw ApiException(error.what());
893 }
894 if (insertedId < 0)
895 throw ApiException("Adding key failed, perhaps DNSSEC not enabled in configuration?");
60b0a236
BZ
896 } else {
897 throw ApiException("Either you submit just the 'content' field or you leave 'content' empty and submit the other fields.");
997cab68 898 }
60b0a236 899 apiZoneCryptokeysGET(zonename, insertedId, resp, dk);
997cab68 900 resp->status = 201;
60b0a236 901}
997cab68
BZ
902
903/*
904 * This method handles PUT (execute) requests for URL /api/v1/servers/:server_id/zones/:zone_name/cryptokeys/:cryptokey_id .
905 * It de/activates a key from :zone_name specified by :cryptokey_id.
906 * Server Answers:
60b0a236 907 * Case 1: invalid JSON data
997cab68 908 * The server returns 400 Bad Request
60b0a236
BZ
909 * Case 2: the backend returns true on de/activation. This means the key is de/active.
910 * The server returns 204 No Content
955cbfd0 911 * Case 3: the backend returns false on de/activation. An error occurred.
997cab68
BZ
912 * The sever returns 422 Unprocessable Entity with message "Could not de/activate Key: :cryptokey_id in Zone: :zone_name"
913 * */
60b0a236 914static void apiZoneCryptokeysPUT(DNSName zonename, int inquireKeyId, HttpRequest *req, HttpResponse *resp, DNSSECKeeper *dk) {
997cab68
BZ
915 //throws an exception if the Body is empty
916 auto document = req->json();
917 //throws an exception if the key does not exist or is not a bool
918 bool active = boolFromJson(document, "active");
60b0a236
BZ
919 if (active) {
920 if (!dk->activateKey(zonename, inquireKeyId)) {
997cab68
BZ
921 resp->setErrorResult("Could not activate Key: " + req->parameters["key_id"] + " in Zone: " + zonename.toString(), 422);
922 return;
923 }
924 } else {
60b0a236 925 if (!dk->deactivateKey(zonename, inquireKeyId)) {
997cab68
BZ
926 resp->setErrorResult("Could not deactivate Key: " + req->parameters["key_id"] + " in Zone: " + zonename.toString(), 422);
927 return;
928 }
929 }
60b0a236
BZ
930 resp->body = "";
931 resp->status = 204;
932 return;
997cab68
BZ
933}
934
935/*
936 * This method chooses the right functionality for the request. It also checks for a cryptokey_id which has to be passed
937 * by URL /api/v1/servers/:server_id/zones/:zone_name/cryptokeys/:cryptokey_id .
938 * If the the HTTP-request-method isn't supported, the function returns a response with the 405 code (method not allowed).
939 * */
940static void apiZoneCryptokeys(HttpRequest *req, HttpResponse *resp) {
941 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
942
60b0a236
BZ
943 UeberBackend B;
944 DNSSECKeeper dk(&B);
945 DomainInfo di;
946 if (!B.getDomainInfo(zonename, di))
947 throw HttpBadRequestException();
948
997cab68
BZ
949 int inquireKeyId = -1;
950 if (req->parameters.count("key_id")) {
951 inquireKeyId = std::stoi(req->parameters["key_id"]);
952 }
953
954 if (req->method == "GET") {
60b0a236 955 apiZoneCryptokeysGET(zonename, inquireKeyId, resp, &dk);
997cab68 956 } else if (req->method == "DELETE") {
60b0a236
BZ
957 if (inquireKeyId == -1)
958 throw HttpBadRequestException();
959 apiZoneCryptokeysDELETE(zonename, inquireKeyId, req, resp, &dk);
997cab68 960 } else if (req->method == "POST") {
60b0a236
BZ
961 apiZoneCryptokeysPOST(zonename, req, resp, &dk);
962 } else if (req->method == "PUT") {
963 if (inquireKeyId == -1)
964 throw HttpBadRequestException();
965 apiZoneCryptokeysPUT(zonename, inquireKeyId, req, resp, &dk);
997cab68
BZ
966 } else {
967 throw HttpMethodNotAllowedException(); //Returns method not allowed
968 }
4b7f120a
MS
969}
970
1f68b185 971static void gatherRecordsFromZone(const std::string& zonestring, vector<DNSResourceRecord>& new_records, DNSName zonename) {
0f0e73fe
MS
972 DNSResourceRecord rr;
973 vector<string> zonedata;
1f68b185 974 stringtok(zonedata, zonestring, "\r\n");
0f0e73fe
MS
975
976 ZoneParserTNG zpt(zonedata, zonename);
977
978 bool seenSOA=false;
979
980 string comment = "Imported via the API";
981
982 try {
983 while(zpt.get(rr, &comment)) {
984 if(seenSOA && rr.qtype.getCode() == QType::SOA)
985 continue;
986 if(rr.qtype.getCode() == QType::SOA)
987 seenSOA=true;
988
0f0e73fe
MS
989 new_records.push_back(rr);
990 }
991 }
992 catch(std::exception& ae) {
1af62161 993 throw ApiException("An error occurred while parsing the zonedata: "+string(ae.what()));
0f0e73fe
MS
994 }
995}
996
80d59cd1 997static void apiServerZones(HttpRequest* req, HttpResponse* resp) {
e2dba705 998 UeberBackend B;
53942520 999 DNSSECKeeper dk(&B);
d07bf7ff 1000 if (req->method == "POST" && !::arg().mustDo("api-readonly")) {
e2dba705 1001 DomainInfo di;
1f68b185 1002 auto document = req->json();
c576d0c5 1003 DNSName zonename = apiNameToDNSName(stringFromJson(document, "name"));
1d6b70f9 1004 apiCheckNameAllowedCharacters(zonename.toString());
4ebf78b1 1005
1d6b70f9 1006 bool exists = B.getDomainInfo(zonename, di);
e2dba705 1007 if(exists)
1d6b70f9 1008 throw ApiException("Domain '"+zonename.toString()+"' already exists");
e2dba705 1009
bb9fd223 1010 // validate 'kind' is set
4bdff352 1011 DomainInfo::DomainKind zonekind = DomainInfo::stringToKind(stringFromJson(document, "kind"));
bb9fd223 1012
6754ef71
CH
1013 string zonestring = document["zone"].string_value();
1014 auto rrsets = document["rrsets"];
1015 if (rrsets.is_array() && zonestring != "")
1016 throw ApiException("You cannot give rrsets AND zone data as text");
0f0e73fe 1017
1f68b185
CH
1018 auto nameservers = document["nameservers"];
1019 if (!nameservers.is_array() && zonekind != DomainInfo::Slave)
f63168e6 1020 throw ApiException("Nameservers list must be given (but can be empty if NS records are supplied)");
e2dba705 1021
f63168e6 1022 string soa_edit_api_kind;
1f68b185
CH
1023 if (document["soa_edit_api"].is_string()) {
1024 soa_edit_api_kind = document["soa_edit_api"].string_value();
a6448d95
CH
1025 }
1026 else {
1027 soa_edit_api_kind = "DEFAULT";
1028 }
1f68b185 1029 string soa_edit_kind = document["soa_edit"].string_value();
e90b4e38 1030
f63168e6
CH
1031 // if records/comments are given, load and check them
1032 bool have_soa = false;
33e6c3e9 1033 bool have_zone_ns = false;
f63168e6
CH
1034 vector<DNSResourceRecord> new_records;
1035 vector<Comment> new_comments;
1036 vector<DNSResourceRecord> new_ptrs;
0f0e73fe 1037
6754ef71
CH
1038 if (rrsets.is_array()) {
1039 for (const auto& rrset : rrsets.array_items()) {
1040 DNSName qname = apiNameToDNSName(stringFromJson(rrset, "name"));
1041 apiCheckQNameAllowedCharacters(qname.toString());
1042 QType qtype;
1043 qtype = stringFromJson(rrset, "type");
1044 if (qtype.getCode() == 0) {
1045 throw ApiException("RRset "+qname.toString()+" IN "+stringFromJson(rrset, "type")+": unknown type given");
1046 }
1047 if (rrset["records"].is_array()) {
1048 int ttl = intFromJson(rrset, "ttl");
1049 gatherRecords(rrset, qname, qtype, ttl, new_records, new_ptrs);
1050 }
1051 if (rrset["comments"].is_array()) {
1052 gatherComments(rrset, qname, qtype, new_comments);
1053 }
1054 }
0f0e73fe 1055 } else if (zonestring != "") {
1f68b185 1056 gatherRecordsFromZone(zonestring, new_records, zonename);
0f0e73fe
MS
1057 }
1058
1f68b185 1059 for(auto& rr : new_records) {
1d6b70f9 1060 if (!rr.qname.isPartOf(zonename) && rr.qname != zonename)
561434a6 1061 throw ApiException("RRset "+rr.qname.toString()+" IN "+rr.qtype.getName()+": Name is out of zone");
cb9b5901 1062 apiCheckQNameAllowedCharacters(rr.qname.toString());
f63168e6 1063
1d6b70f9 1064 if (rr.qtype.getCode() == QType::SOA && rr.qname==zonename) {
f63168e6 1065 have_soa = true;
a6448d95 1066 increaseSOARecord(rr, soa_edit_api_kind, soa_edit_kind);
1d6b70f9
CH
1067 // fixup dots after serializeSOAData/increaseSOARecord
1068 rr.content = makeBackendRecordContent(rr.qtype, rr.content);
f63168e6 1069 }
33e6c3e9
CH
1070 if (rr.qtype.getCode() == QType::NS && rr.qname==zonename) {
1071 have_zone_ns = true;
1072 }
f63168e6 1073 }
f7bfeb30
CH
1074
1075 // synthesize RRs as needed
1076 DNSResourceRecord autorr;
1d6b70f9 1077 autorr.qname = zonename;
f7bfeb30
CH
1078 autorr.auth = 1;
1079 autorr.ttl = ::arg().asNum("default-ttl");
e2dba705 1080
4de11a54 1081 if (!have_soa && zonekind != DomainInfo::Slave) {
f63168e6 1082 // synthesize a SOA record so the zone "really" exists
1d6b70f9
CH
1083 string soa = (boost::format("%s %s %lu")
1084 % ::arg()["default-soa-name"]
1085 % (::arg().isEmpty("default-soa-mail") ? (DNSName("hostmaster.") + zonename).toString() : ::arg()["default-soa-mail"])
1f68b185 1086 % document["serial"].int_value()
1d6b70f9 1087 ).str();
f63168e6 1088 SOAData sd;
1d6b70f9 1089 fillSOAData(soa, sd); // fills out default values for us
f7bfeb30 1090 autorr.qtype = "SOA";
1d6b70f9 1091 autorr.content = serializeSOAData(sd);
f7bfeb30 1092 increaseSOARecord(autorr, soa_edit_api_kind, soa_edit_kind);
1d6b70f9
CH
1093 // fixup dots after serializeSOAData/increaseSOARecord
1094 autorr.content = makeBackendRecordContent(autorr.qtype, autorr.content);
f7bfeb30 1095 new_records.push_back(autorr);
f63168e6
CH
1096 }
1097
1098 // create NS records if nameservers are given
1f68b185
CH
1099 for (auto value : nameservers.array_items()) {
1100 string nameserver = value.string_value();
1101 if (nameserver.empty())
1102 throw ApiException("Nameservers must be non-empty strings");
1103 if (!isCanonical(nameserver))
1104 throw ApiException("Nameserver is not canonical: '" + nameserver + "'");
1105 try {
1106 // ensure the name parses
8f955653 1107 autorr.content = DNSName(nameserver).toStringRootDot();
1f68b185
CH
1108 } catch (...) {
1109 throw ApiException("Unable to parse DNS Name for NS '" + nameserver + "'");
4bdff352 1110 }
1f68b185
CH
1111 autorr.qtype = "NS";
1112 new_records.push_back(autorr);
33e6c3e9
CH
1113 if (have_zone_ns) {
1114 throw ApiException("Nameservers list MUST NOT be mixed with zone-level NS in rrsets");
1115 }
e2dba705
CH
1116 }
1117
f63168e6 1118 // no going back after this
1d6b70f9
CH
1119 if(!B.createDomain(zonename))
1120 throw ApiException("Creating domain '"+zonename.toString()+"' failed");
f63168e6 1121
1d6b70f9
CH
1122 if(!B.getDomainInfo(zonename, di))
1123 throw ApiException("Creating domain '"+zonename.toString()+"' failed: lookup of domain ID failed");
f63168e6 1124
9440a9f0
CH
1125 // updateDomainSettingsFromDocument does NOT fill out the default we've established above.
1126 if (!soa_edit_api_kind.empty()) {
1127 di.backend->setDomainMetadataOne(zonename, "SOA-EDIT-API", soa_edit_api_kind);
1128 }
1129
1d6b70f9 1130 di.backend->startTransaction(zonename, di.id);
f63168e6 1131
abb873ee 1132 for(auto rr : new_records) {
f63168e6 1133 rr.domain_id = di.id;
e2dba705
CH
1134 di.backend->feedRecord(rr);
1135 }
1d6b70f9 1136 for(Comment& c : new_comments) {
f63168e6
CH
1137 c.domain_id = di.id;
1138 di.backend->feedComment(c);
1139 }
e2dba705 1140
1d6b70f9 1141 updateDomainSettingsFromDocument(di, zonename, document);
e2dba705 1142
f63168e6
CH
1143 di.backend->commitTransaction();
1144
3fe7c7d6
CH
1145 storeChangedPTRs(B, new_ptrs);
1146
1d6b70f9 1147 fillZone(zonename, resp);
64a36f0d 1148 resp->status = 201;
e2dba705
CH
1149 return;
1150 }
1151
c67bf8c5
CH
1152 if(req->method != "GET")
1153 throw HttpMethodNotAllowedException();
1154
c67bf8c5 1155 vector<DomainInfo> domains;
cea26350 1156 B.getAllDomains(&domains, true); // incl. disabled
c67bf8c5 1157
62a9a74c
CH
1158 Json::array doc;
1159 for(const DomainInfo& di : domains) {
ce846be6 1160 doc.push_back(getZoneInfo(di, &dk));
c67bf8c5 1161 }
669822d0 1162 resp->setBody(doc);
c67bf8c5
CH
1163}
1164
05776d2f 1165static void apiServerZoneDetail(HttpRequest* req, HttpResponse* resp) {
290a083d 1166 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
05776d2f 1167
d07bf7ff 1168 if(req->method == "PUT" && !::arg().mustDo("api-readonly")) {
7c0ba3d2
CH
1169 // update domain settings
1170 UeberBackend B;
1171 DomainInfo di;
1172 if(!B.getDomainInfo(zonename, di))
290a083d 1173 throw ApiException("Could not find domain '"+zonename.toString()+"'");
7c0ba3d2 1174
1f68b185 1175 updateDomainSettingsFromDocument(di, zonename, req->json());
7c0ba3d2 1176
f0e76cee
CH
1177 resp->body = "";
1178 resp->status = 204; // No Content, but indicate success
7c0ba3d2
CH
1179 return;
1180 }
d07bf7ff 1181 else if(req->method == "DELETE" && !::arg().mustDo("api-readonly")) {
a462a01d
CH
1182 // delete domain
1183 UeberBackend B;
1184 DomainInfo di;
1185 if(!B.getDomainInfo(zonename, di))
290a083d 1186 throw ApiException("Could not find domain '"+zonename.toString()+"'");
a462a01d
CH
1187
1188 if(!di.backend->deleteDomain(zonename))
290a083d 1189 throw ApiException("Deleting domain '"+zonename.toString()+"' failed: backend delete failed/unsupported");
a462a01d
CH
1190
1191 // empty body on success
1192 resp->body = "";
37663c3b 1193 resp->status = 204; // No Content: declare that the zone is gone now
a462a01d 1194 return;
d07bf7ff 1195 } else if (req->method == "PATCH" && !::arg().mustDo("api-readonly")) {
d708640f 1196 patchZone(req, resp);
6cc98ddf
CH
1197 return;
1198 } else if (req->method == "GET") {
1199 fillZone(zonename, resp);
1200 return;
a462a01d 1201 }
7c0ba3d2 1202
6cc98ddf 1203 throw HttpMethodNotAllowedException();
05776d2f
CH
1204}
1205
a83004d3 1206static void apiServerZoneExport(HttpRequest* req, HttpResponse* resp) {
290a083d 1207 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
a83004d3
CH
1208
1209 if(req->method != "GET")
1210 throw HttpMethodNotAllowedException();
1211
1212 ostringstream ss;
1213
1214 UeberBackend B;
1215 DomainInfo di;
1216 if(!B.getDomainInfo(zonename, di))
290a083d 1217 throw ApiException("Could not find domain '"+zonename.toString()+"'");
a83004d3
CH
1218
1219 DNSResourceRecord rr;
1220 SOAData sd;
1221 di.backend->list(zonename, di.id);
1222 while(di.backend->get(rr)) {
1223 if (!rr.qtype.getCode())
1224 continue; // skip empty non-terminals
1225
a83004d3 1226 ss <<
675fa24c 1227 rr.qname.toString() << "\t" <<
a83004d3
CH
1228 rr.ttl << "\t" <<
1229 rr.qtype.getName() << "\t" <<
1d6b70f9 1230 makeApiRecordContent(rr.qtype, rr.content) <<
a83004d3
CH
1231 endl;
1232 }
1233
1234 if (req->accept_json) {
41873e7c 1235 resp->setBody(Json::object { { "zone", ss.str() } });
a83004d3
CH
1236 } else {
1237 resp->headers["Content-Type"] = "text/plain; charset=us-ascii";
1238 resp->body = ss.str();
1239 }
1240}
1241
a426cb89 1242static void apiServerZoneAxfrRetrieve(HttpRequest* req, HttpResponse* resp) {
290a083d 1243 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
a426cb89
CH
1244
1245 if(req->method != "PUT")
1246 throw HttpMethodNotAllowedException();
1247
1248 UeberBackend B;
1249 DomainInfo di;
1250 if(!B.getDomainInfo(zonename, di))
290a083d 1251 throw ApiException("Could not find domain '"+zonename.toString()+"'");
a426cb89
CH
1252
1253 if(di.masters.empty())
290a083d 1254 throw ApiException("Domain '"+zonename.toString()+"' is not a slave domain (or has no master defined)");
a426cb89
CH
1255
1256 random_shuffle(di.masters.begin(), di.masters.end());
1257 Communicator.addSuckRequest(zonename, di.masters.front());
692829aa 1258 resp->setSuccessResult("Added retrieval request for '"+zonename.toString()+"' from master "+di.masters.front());
a426cb89
CH
1259}
1260
1261static void apiServerZoneNotify(HttpRequest* req, HttpResponse* resp) {
290a083d 1262 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
a426cb89
CH
1263
1264 if(req->method != "PUT")
1265 throw HttpMethodNotAllowedException();
1266
1267 UeberBackend B;
1268 DomainInfo di;
1269 if(!B.getDomainInfo(zonename, di))
290a083d 1270 throw ApiException("Could not find domain '"+zonename.toString()+"'");
a426cb89
CH
1271
1272 if(!Communicator.notifyDomain(zonename))
1273 throw ApiException("Failed to add to the queue - see server log");
1274
692829aa 1275 resp->setSuccessResult("Notification queued");
a426cb89
CH
1276}
1277
d1587ceb
CH
1278static void makePtr(const DNSResourceRecord& rr, DNSResourceRecord* ptr) {
1279 if (rr.qtype.getCode() == QType::A) {
1280 uint32_t ip;
1281 if (!IpToU32(rr.content, &ip)) {
1282 throw ApiException("PTR: Invalid IP address given");
1283 }
1d6b70f9 1284 ptr->qname = DNSName((boost::format("%u.%u.%u.%u.in-addr.arpa.")
d1587ceb
CH
1285 % ((ip >> 24) & 0xff)
1286 % ((ip >> 16) & 0xff)
1287 % ((ip >> 8) & 0xff)
1288 % ((ip ) & 0xff)
1d6b70f9 1289 ).str());
d1587ceb
CH
1290 } else if (rr.qtype.getCode() == QType::AAAA) {
1291 ComboAddress ca(rr.content);
5fb3aa58 1292 char buf[3];
d1587ceb 1293 ostringstream ss;
5fb3aa58
CH
1294 for (int octet = 0; octet < 16; ++octet) {
1295 if (snprintf(buf, sizeof(buf), "%02x", ca.sin6.sin6_addr.s6_addr[octet]) != (sizeof(buf)-1)) {
1296 // this should be impossible: no byte should give more than two digits in hex format
1297 throw PDNSException("Formatting IPv6 address failed");
1298 }
1299 ss << buf[0] << '.' << buf[1] << '.';
d1587ceb 1300 }
5fb3aa58
CH
1301 string tmp = ss.str();
1302 tmp.resize(tmp.size()-1); // remove last dot
1303 // reverse and append arpa domain
1d6b70f9 1304 ptr->qname = DNSName(string(tmp.rbegin(), tmp.rend())) + DNSName("ip6.arpa.");
d1587ceb 1305 } else {
675fa24c 1306 throw ApiException("Unsupported PTR source '" + rr.qname.toString() + "' type '" + rr.qtype.getName() + "'");
d1587ceb
CH
1307 }
1308
1309 ptr->qtype = "PTR";
1310 ptr->ttl = rr.ttl;
1311 ptr->disabled = rr.disabled;
8f955653 1312 ptr->content = rr.qname.toStringRootDot();
d1587ceb
CH
1313}
1314
995473c8
CH
1315static void storeChangedPTRs(UeberBackend& B, vector<DNSResourceRecord>& new_ptrs) {
1316 for(const DNSResourceRecord& rr : new_ptrs) {
27c0050c 1317 DNSPacket fakePacket(false);
995473c8
CH
1318 SOAData sd;
1319 sd.db = (DNSBackend *)-1; // getAuth() cache bypass
1320 fakePacket.qtype = QType::PTR;
1321
1322 if (!B.getAuth(&fakePacket, &sd, rr.qname))
1323 throw ApiException("Could not find domain for PTR '"+rr.qname.toString()+"' requested for '"+rr.content+"' (while saving)");
1324
1325 string soa_edit_api_kind;
1326 string soa_edit_kind;
1327 bool soa_changed = false;
1328 DNSResourceRecord soarr;
1329 sd.db->getDomainMetadataOne(sd.qname, "SOA-EDIT-API", soa_edit_api_kind);
1330 sd.db->getDomainMetadataOne(sd.qname, "SOA-EDIT", soa_edit_kind);
1331 if (!soa_edit_api_kind.empty()) {
1332 soarr.qname = sd.qname;
1333 soarr.content = serializeSOAData(sd);
1334 soarr.qtype = "SOA";
1335 soarr.domain_id = sd.domain_id;
1336 soarr.auth = 1;
1337 soarr.ttl = sd.ttl;
1338 increaseSOARecord(soarr, soa_edit_api_kind, soa_edit_kind);
1339 // fixup dots after serializeSOAData/increaseSOARecord
1340 soarr.content = makeBackendRecordContent(soarr.qtype, soarr.content);
1341 soa_changed = true;
1342 }
1343
1344 sd.db->startTransaction(sd.qname);
1345 if (!sd.db->replaceRRSet(sd.domain_id, rr.qname, rr.qtype, vector<DNSResourceRecord>(1, rr))) {
1346 sd.db->abortTransaction();
1347 throw ApiException("PTR-Hosting backend for "+rr.qname.toString()+"/"+rr.qtype.getName()+" does not support editing records.");
1348 }
1349
1350 if (soa_changed) {
1351 sd.db->replaceRRSet(sd.domain_id, soarr.qname, soarr.qtype, vector<DNSResourceRecord>(1, soarr));
1352 }
1353
1354 sd.db->commitTransaction();
1355 PC.purgeExact(rr.qname);
1356 }
1357}
1358
d708640f 1359static void patchZone(HttpRequest* req, HttpResponse* resp) {
b3905a3d
CH
1360 UeberBackend B;
1361 DomainInfo di;
290a083d 1362 DNSName zonename = apiZoneIdToName(req->parameters["id"]);
d708640f 1363 if (!B.getDomainInfo(zonename, di))
290a083d 1364 throw ApiException("Could not find domain '"+zonename.toString()+"'");
b3905a3d 1365
f63168e6
CH
1366 vector<DNSResourceRecord> new_records;
1367 vector<Comment> new_comments;
d708640f
CH
1368 vector<DNSResourceRecord> new_ptrs;
1369
1f68b185 1370 Json document = req->json();
b3905a3d 1371
1f68b185
CH
1372 auto rrsets = document["rrsets"];
1373 if (!rrsets.is_array())
d708640f 1374 throw ApiException("No rrsets given in update request");
b3905a3d 1375
d708640f 1376 di.backend->startTransaction(zonename);
6cc98ddf 1377
d708640f 1378 try {
d29d5db7 1379 string soa_edit_api_kind;
a6448d95 1380 string soa_edit_kind;
d29d5db7 1381 di.backend->getDomainMetadataOne(zonename, "SOA-EDIT-API", soa_edit_api_kind);
a6448d95 1382 di.backend->getDomainMetadataOne(zonename, "SOA-EDIT", soa_edit_kind);
d29d5db7
CH
1383 bool soa_edit_done = false;
1384
6754ef71
CH
1385 for (const auto& rrset : rrsets.array_items()) {
1386 string changetype = toUpper(stringFromJson(rrset, "changetype"));
c576d0c5 1387 DNSName qname = apiNameToDNSName(stringFromJson(rrset, "name"));
cb9b5901 1388 apiCheckQNameAllowedCharacters(qname.toString());
6754ef71 1389 QType qtype;
d708640f 1390 qtype = stringFromJson(rrset, "type");
6754ef71
CH
1391 if (qtype.getCode() == 0) {
1392 throw ApiException("RRset "+qname.toString()+" IN "+stringFromJson(rrset, "type")+": unknown type given");
1393 }
d708640f 1394
d708640f 1395 if (changetype == "DELETE") {
b7f21ab1 1396 // delete all matching qname/qtype RRs (and, implicitly comments).
d708640f
CH
1397 if (!di.backend->replaceRRSet(di.id, qname, qtype, vector<DNSResourceRecord>())) {
1398 throw ApiException("Hosting backend does not support editing records.");
6cc98ddf 1399 }
d708640f
CH
1400 }
1401 else if (changetype == "REPLACE") {
1d6b70f9 1402 // we only validate for REPLACE, as DELETE can be used to "fix" out of zone records.
e325f20c 1403 if (!qname.isPartOf(zonename) && qname != zonename)
edda67a2 1404 throw ApiException("RRset "+qname.toString()+" IN "+qtype.getName()+": Name is out of zone");
34df6ecc 1405
6754ef71
CH
1406 bool replace_records = rrset["records"].is_array();
1407 bool replace_comments = rrset["comments"].is_array();
f63168e6 1408
6754ef71
CH
1409 if (!replace_records && !replace_comments) {
1410 throw ApiException("No change for RRset " + qname.toString() + " IN " + qtype.getName());
1411 }
f63168e6 1412
6754ef71
CH
1413 new_records.clear();
1414 new_comments.clear();
f63168e6 1415
6754ef71
CH
1416 if (replace_records) {
1417 // ttl shouldn't be part of DELETE, and it shouldn't be required if we don't get new records.
1418 int ttl = intFromJson(rrset, "ttl");
1419 // new_ptrs is merged.
1420 gatherRecords(rrset, qname, qtype, ttl, new_records, new_ptrs);
1421
1422 for(DNSResourceRecord& rr : new_records) {
1423 rr.domain_id = di.id;
1424 if (rr.qtype.getCode() == QType::SOA && rr.qname==zonename) {
1425 soa_edit_done = increaseSOARecord(rr, soa_edit_api_kind, soa_edit_kind);
1426 rr.content = makeBackendRecordContent(rr.qtype, rr.content);
1427 }
d708640f 1428 }
6cc98ddf
CH
1429 }
1430
6754ef71
CH
1431 if (replace_comments) {
1432 gatherComments(rrset, qname, qtype, new_comments);
f63168e6 1433
6754ef71
CH
1434 for(Comment& c : new_comments) {
1435 c.domain_id = di.id;
1436 }
d708640f 1437 }
b3905a3d 1438
d708640f
CH
1439 if (replace_records) {
1440 if (!di.backend->replaceRRSet(di.id, qname, qtype, new_records)) {
1441 throw ApiException("Hosting backend does not support editing records.");
1442 }
1443 }
1444 if (replace_comments) {
1445 if (!di.backend->replaceComments(di.id, qname, qtype, new_comments)) {
1446 throw ApiException("Hosting backend does not support editing comments.");
1447 }
1448 }
6cc98ddf 1449 }
d708640f
CH
1450 else
1451 throw ApiException("Changetype not understood");
6cc98ddf 1452 }
d29d5db7
CH
1453
1454 // edit SOA (if needed)
1455 if (!soa_edit_api_kind.empty() && !soa_edit_done) {
1456 SOAData sd;
1457 if (!B.getSOA(zonename, sd))
290a083d 1458 throw ApiException("No SOA found for domain '"+zonename.toString()+"'");
d29d5db7
CH
1459
1460 DNSResourceRecord rr;
1461 rr.qname = zonename;
1462 rr.content = serializeSOAData(sd);
1463 rr.qtype = "SOA";
1464 rr.domain_id = di.id;
1465 rr.auth = 1;
1466 rr.ttl = sd.ttl;
a6448d95 1467 increaseSOARecord(rr, soa_edit_api_kind, soa_edit_kind);
1d6b70f9
CH
1468 // fixup dots after serializeSOAData/increaseSOARecord
1469 rr.content = makeBackendRecordContent(rr.qtype, rr.content);
d29d5db7
CH
1470
1471 if (!di.backend->replaceRRSet(di.id, rr.qname, rr.qtype, vector<DNSResourceRecord>(1, rr))) {
1472 throw ApiException("Hosting backend does not support editing records.");
1473 }
1474 }
1475
d708640f
CH
1476 } catch(...) {
1477 di.backend->abortTransaction();
1478 throw;
1479 }
1480 di.backend->commitTransaction();
b3905a3d 1481
be9d7339 1482 PC.purgeExact(zonename);
d1587ceb 1483
d708640f 1484 // now the PTRs
995473c8 1485 storeChangedPTRs(B, new_ptrs);
b3905a3d 1486
f0e76cee
CH
1487 resp->body = "";
1488 resp->status = 204; // No Content, but indicate success
1489 return;
b3905a3d
CH
1490}
1491
b1902fab
CH
1492static void apiServerSearchData(HttpRequest* req, HttpResponse* resp) {
1493 if(req->method != "GET")
1494 throw HttpMethodNotAllowedException();
1495
583ea80d 1496 string q = req->getvars["q"];
720ed2bd
AT
1497 string sMax = req->getvars["max"];
1498 int maxEnts = 100;
1499 int ents = 0;
1500
b1902fab
CH
1501 if (q.empty())
1502 throw ApiException("Query q can't be blank");
606c8752 1503 if (!sMax.empty())
335da0ba 1504 maxEnts = std::stoi(sMax);
720ed2bd
AT
1505 if (maxEnts < 1)
1506 throw ApiException("Maximum entries must be larger than 0");
b1902fab 1507
720ed2bd 1508 SimpleMatch sm(q,true);
b1902fab 1509 UeberBackend B;
b1902fab 1510 vector<DomainInfo> domains;
720ed2bd
AT
1511 vector<DNSResourceRecord> result_rr;
1512 vector<Comment> result_c;
1d6b70f9
CH
1513 map<int,DomainInfo> zoneIdZone;
1514 map<int,DomainInfo>::iterator val;
00963dea 1515 Json::array doc;
b1902fab 1516
720ed2bd 1517 B.getAllDomains(&domains, true);
d2d194a9 1518
720ed2bd 1519 for(const DomainInfo di: domains)
1d6b70f9 1520 {
720ed2bd 1521 if (ents < maxEnts && sm.match(di.zone)) {
00963dea
CH
1522 doc.push_back(Json::object {
1523 { "object_type", "zone" },
1524 { "zone_id", apiZoneNameToId(di.zone) },
1525 { "name", di.zone.toString() }
1526 });
720ed2bd 1527 ents++;
b1902fab 1528 }
1d6b70f9 1529 zoneIdZone[di.id] = di; // populate cache
720ed2bd 1530 }
b1902fab 1531
720ed2bd
AT
1532 if (B.searchRecords(q, maxEnts, result_rr))
1533 {
1534 for(const DNSResourceRecord& rr: result_rr)
1535 {
7cbc5255
CH
1536 if (!rr.qtype.getCode())
1537 continue; // skip empty non-terminals
1538
00963dea
CH
1539 auto object = Json::object {
1540 { "object_type", "record" },
1541 { "name", rr.qname.toString() },
1542 { "type", rr.qtype.getName() },
1543 { "ttl", (double)rr.ttl },
1544 { "disabled", rr.disabled },
1545 { "content", makeApiRecordContent(rr.qtype, rr.content) }
1546 };
720ed2bd 1547 if ((val = zoneIdZone.find(rr.domain_id)) != zoneIdZone.end()) {
00963dea
CH
1548 object["zone_id"] = apiZoneNameToId(val->second.zone);
1549 object["zone"] = val->second.zone.toString();
720ed2bd 1550 }
00963dea 1551 doc.push_back(object);
b1902fab 1552 }
720ed2bd 1553 }
b1902fab 1554
720ed2bd
AT
1555 if (B.searchComments(q, maxEnts, result_c))
1556 {
1557 for(const Comment &c: result_c)
1558 {
00963dea
CH
1559 auto object = Json::object {
1560 { "object_type", "comment" },
25dcc05f 1561 { "name", c.qname.toString() },
00963dea
CH
1562 { "content", c.content }
1563 };
720ed2bd 1564 if ((val = zoneIdZone.find(c.domain_id)) != zoneIdZone.end()) {
00963dea
CH
1565 object["zone_id"] = apiZoneNameToId(val->second.zone);
1566 object["zone"] = val->second.zone.toString();
720ed2bd 1567 }
00963dea 1568 doc.push_back(object);
b1902fab
CH
1569 }
1570 }
4bd3d119 1571
b1902fab
CH
1572 resp->setBody(doc);
1573}
1574
c0f6a1da 1575void apiServerCacheFlush(HttpRequest* req, HttpResponse* resp) {
a426cb89
CH
1576 if(req->method != "PUT")
1577 throw HttpMethodNotAllowedException();
80d59cd1 1578
c0f6a1da
CH
1579 DNSName canon = apiNameToDNSName(req->getvars["domain"]);
1580
c0f6a1da 1581 int count = PC.purgeExact(canon);
f682752a
CH
1582 resp->setBody(Json::object {
1583 { "count", count },
1584 { "result", "Flushed cache." }
1585 });
ddc84d12
CH
1586}
1587
dea47634 1588void AuthWebServer::cssfunction(HttpRequest* req, HttpResponse* resp)
c67bf8c5 1589{
80d59cd1
CH
1590 resp->headers["Cache-Control"] = "max-age=86400";
1591 resp->headers["Content-Type"] = "text/css";
c67bf8c5 1592
1071abdd 1593 ostringstream ret;
1071abdd
CH
1594 ret<<"* { box-sizing: border-box; margin: 0; padding: 0; }"<<endl;
1595 ret<<"body { color: black; background: white; margin-top: 1em; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 10pt; position: relative; }"<<endl;
1596 ret<<"a { color: #0959c2; }"<<endl;
1597 ret<<"a:hover { color: #3B8EC8; }"<<endl;
1598 ret<<".row { width: 940px; max-width: 100%; min-width: 768px; margin: 0 auto; }"<<endl;
1599 ret<<".row:before, .row:after { display: table; content:\" \"; }"<<endl;
1600 ret<<".row:after { clear: both; }"<<endl;
1601 ret<<".columns { position: relative; min-height: 1px; float: left; }"<<endl;
1602 ret<<".all { width: 100%; }"<<endl;
1603 ret<<".headl { width: 60%; }"<<endl;
1604 ret<<".headr { width: 39.5%; float: right; background-repeat: no-repeat; margin-top: 7px; ";
1605 ret<<"background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJoAAAAUCAYAAAB1RSS/AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAACtgAAArYBAHIqtQAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAABBTSURBVGiBtVp7cFRVmv9u3763b7/f9It00iFACBohgCEyQYgKI49CLV3cWaoEZBcfo2shu7KOtZbjrqOuVQtVWFuOrPqPRU3NgOIDlkgyJEYJwUAqjzEJedFJupN0p9/v+9o/mtve7r790HF+VbeSPue7555zz+98z4ucOXNmgWVZBH4AK5PJGIPBQBqNxpTNZkthGMZCCUxMTBCDg4PyiYkJWTQaRc1mc7Kuri7a1NQU4ssxDAOffPKJAQCynvnII494ESTddO3aNaXT6SS4TplMRj/44IM+7ndXV5dqfn5ewh9306ZNQZqmobu7W11qri0tLX6tVkv19vYqpqampPw+BEFYtVpNGQwG0mKxpJYsWUIKjTE6OiodGBhQ8NcgkUgYjUZDORyOhM1mSxV6fjAYFF+6dEnLb9NoNOR9990X4H53dHSovV4vzpfZvn27T6FQ0Py2sbExorOzU+N2uwmWZUGv15N33nlnuLGxMZy7byyVQEJ//nd9Yuz/lJR/HBdrHSlJ9baIuuV1L4LJ8/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u3dvJqmKYHJWturhomNKa34ZFskMNACAYt2hQDFZEaGh5XfsDQMAECt2R1Glreja5GsOBP4qoul0Ouro0aO3TCZTQTOkUqnII0eO3FqxYoUgoYRKVQAA/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=);";
1606 ret<<" width: 154px; height: 20px; }"<<endl;
1607 ret<<"a#appname { margin: 0; font-size: 27px; color: #666; text-decoration: none; font-weight: bold; display: block; }"<<endl;
1608 ret<<"footer { border-top: 1px solid #ddd; padding-top: 4px; font-size: 12px; }"<<endl;
1609 ret<<"footer.row { margin-top: 1em; margin-bottom: 1em; }"<<endl;
1610 ret<<".panel { background: #f2f2f2; border: 1px solid #e6e6e6; margin: 0 0 22px 0; padding: 20px; }"<<endl;
1611 ret<<"table.data { width: 100%; border-spacing: 0; border-top: 1px solid #333; }"<<endl;
1612 ret<<"table.data td { border-bottom: 1px solid #333; padding: 2px; }"<<endl;
1613 ret<<"table.data tr:nth-child(2n) { background: #e2e2e2; }"<<endl;
1614 ret<<"table.data tr:hover { background: white; }"<<endl;
1615 ret<<".ringmeta { margin-bottom: 5px; }"<<endl;
1616 ret<<".resetring {float: right; }"<<endl;
1617 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;
1618 ret<<".resetring:hover i { background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAA2ElEQVQY013PMUoDcRDF4c+kEzxCsNNCrBQvIGhnlcYm11EkBxAraw8gglgIoiJpAoKIYlBcgrgopsma3c3fwt1k9cHA480M8xvQp/nMjorOWY5ov7IAYlpjQk7aYxcuWBpwFQgJnUcaYk7GhEDIGL5w+MVpKLIRyR2b4JOjvGhUKzHTv2W7iuSN479Dvu9plf1awbQ6y3x1sU5tjpVJcMbakF6Ycoas8Dl5xEHJ160wRdfqzXfa6XQ4PLDlicWUjxHxZfndL/N+RhiwNzl/Q6PDhn/qsl76H7prcApk2B1aAAAAAElFTkSuQmCC);}"<<endl;
1619 ret<<".resizering {float: right;}"<<endl;
80d59cd1 1620 resp->body = ret.str();
c146576d 1621 resp->status = 200;
1071abdd
CH
1622}
1623
dea47634 1624void AuthWebServer::webThread()
12c86877
BH
1625{
1626 try {
479e0976 1627 if(::arg().mustDo("api")) {
c0f6a1da 1628 d_ws->registerApiHandler("/api/v1/servers/localhost/cache/flush", &apiServerCacheFlush);
46d06a12 1629 d_ws->registerApiHandler("/api/v1/servers/localhost/config", &apiServerConfig);
46d06a12
PL
1630 d_ws->registerApiHandler("/api/v1/servers/localhost/search-log", &apiServerSearchLog);
1631 d_ws->registerApiHandler("/api/v1/servers/localhost/search-data", &apiServerSearchData);
1632 d_ws->registerApiHandler("/api/v1/servers/localhost/statistics", &apiServerStatistics);
1633 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/axfr-retrieve", &apiServerZoneAxfrRetrieve);
1634 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/cryptokeys/<key_id>", &apiZoneCryptokeys);
1635 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/cryptokeys", &apiZoneCryptokeys);
1636 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/export", &apiServerZoneExport);
24e11043
CJ
1637 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/metadata/<kind>", &apiZoneMetadataKind);
1638 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/metadata", &apiZoneMetadata);
46d06a12
PL
1639 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>/notify", &apiServerZoneNotify);
1640 d_ws->registerApiHandler("/api/v1/servers/localhost/zones/<id>", &apiServerZoneDetail);
1641 d_ws->registerApiHandler("/api/v1/servers/localhost/zones", &apiServerZones);
1642 d_ws->registerApiHandler("/api/v1/servers/localhost", &apiServerDetail);
1643 d_ws->registerApiHandler("/api/v1/servers", &apiServer);
9e6d2033 1644 d_ws->registerApiHandler("/api", &apiDiscovery);
c67bf8c5 1645 }
536ab56f
CH
1646 if (::arg().mustDo("webserver")) {
1647 d_ws->registerWebHandler("/style.css", boost::bind(&AuthWebServer::cssfunction, this, _1, _2));
1648 d_ws->registerWebHandler("/", boost::bind(&AuthWebServer::indexfunction, this, _1, _2));
1649 }
96d299db 1650 d_ws->go();
12c86877
BH
1651 }
1652 catch(...) {
dea47634 1653 L<<Logger::Error<<"AuthWebServer thread caught an exception, dying"<<endl;
12c86877
BH
1654 exit(1);
1655 }
1656}