]> git.ipfire.org Git - thirdparty/pdns.git/blob - pdns/common_startup.cc
Merge pull request #9070 from rgacogne/boost-173
[thirdparty/pdns.git] / pdns / common_startup.cc
1 /*
2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of version 2 of the GNU General Public License as
7 * published by the Free Software Foundation.
8 *
9 * In addition, for the avoidance of any doubt, permission is granted to
10 * link this program with OpenSSL and to (re)distribute the binaries
11 * produced as the result of such linking.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
25 #include "common_startup.hh"
26 #include "ws-auth.hh"
27 #include "secpoll-auth.hh"
28 #include <sys/time.h>
29 #include <sys/resource.h>
30 #include "dynhandler.hh"
31 #include "dnsseckeeper.hh"
32 #include "threadname.hh"
33 #include "misc.hh"
34
35 #include <thread>
36
37 #ifdef HAVE_SYSTEMD
38 #include <systemd/sd-daemon.h>
39 #endif
40
41 bool g_anyToTcp;
42 bool g_8bitDNS;
43 #ifdef HAVE_LUA_RECORDS
44 bool g_doLuaRecord;
45 int g_luaRecordExecLimit;
46 time_t g_luaHealthChecksInterval{5};
47 time_t g_luaHealthChecksExpireDelay{3600};
48 #endif
49 typedef Distributor<DNSPacket,DNSPacket,PacketHandler> DNSDistributor;
50
51 ArgvMap theArg;
52 StatBag S; //!< Statistics are gathered across PDNS via the StatBag class S
53 AuthPacketCache PC; //!< This is the main PacketCache, shared across all threads
54 AuthQueryCache QC;
55 std::unique_ptr<DNSProxy> DP{nullptr};
56 std::unique_ptr<DynListener> dl{nullptr};
57 CommunicatorClass Communicator;
58 shared_ptr<UDPNameserver> N;
59 int avg_latency;
60 unique_ptr<TCPNameserver> TN;
61 static vector<DNSDistributor*> g_distributors;
62 vector<std::shared_ptr<UDPNameserver> > g_udpReceivers;
63
64 ArgvMap &arg()
65 {
66 return theArg;
67 }
68
69 void declareArguments()
70 {
71 ::arg().set("config-dir","Location of configuration directory (pdns.conf)")=SYSCONFDIR;
72 ::arg().set("config-name","Name of this virtual configuration - will rename the binary image")="";
73 ::arg().set("socket-dir",string("Where the controlsocket will live, ")+LOCALSTATEDIR+"/pdns when unset and not chrooted" )="";
74 ::arg().set("module-dir","Default directory for modules")=PKGLIBDIR;
75 ::arg().set("chroot","If set, chroot to this directory for more security")="";
76 ::arg().set("logging-facility","Log under a specific facility")="";
77 ::arg().set("daemon","Operate as a daemon")="no";
78
79 ::arg().set("local-port","The port on which we listen")="53";
80 ::arg().setSwitch("dnsupdate","Enable/Disable DNS update (RFC2136) support. Default is no.")="no";
81 ::arg().setSwitch("write-pid","Write a PID file")="yes";
82 ::arg().set("allow-dnsupdate-from","A global setting to allow DNS updates from these IP ranges.")="127.0.0.0/8,::1";
83 ::arg().setSwitch("send-signed-notify","Send TSIG secured NOTIFY if TSIG key is configured for a domain")="yes";
84 ::arg().set("allow-unsigned-notify","Allow unsigned notifications for TSIG secured domains")="yes"; //FIXME: change to 'no' later
85 ::arg().set("allow-unsigned-supermaster", "Allow supermasters to create zones without TSIG signed NOTIFY")="yes";
86 ::arg().setSwitch("forward-dnsupdate","A global setting to allow DNS update packages that are for a Slave domain, to be forwarded to the master.")="yes";
87 ::arg().setSwitch("log-dns-details","If PDNS should log DNS non-erroneous details")="no";
88 ::arg().setSwitch("log-dns-queries","If PDNS should log all incoming DNS queries")="no";
89 ::arg().set("local-address","Local IP addresses to which we bind")="0.0.0.0, ::";
90 ::arg().set("local-ipv6","DEPRECATED, will be removed, move your IPs to local-address")="";
91 ::arg().setSwitch("local-address-nonexist-fail","Fail to start if one or more of the local-address's do not exist on this server")="yes";
92 ::arg().setSwitch("non-local-bind", "Enable binding to non-local addresses by using FREEBIND / BINDANY socket options")="no";
93 ::arg().setSwitch("reuseport","Enable higher performance on compliant kernels by using SO_REUSEPORT allowing each receiver thread to open its own socket")="no";
94 ::arg().set("query-local-address","Source IP address for sending queries")="0.0.0.0";
95 ::arg().set("query-local-address6","Source IPv6 address for sending queries")="::";
96 ::arg().set("overload-queue-length","Maximum queuelength moving to packetcache only")="0";
97 ::arg().set("max-queue-length","Maximum queuelength before considering situation lost")="5000";
98
99 ::arg().set("retrieval-threads", "Number of AXFR-retrieval threads for slave operation")="2";
100 ::arg().setSwitch("api", "Enable/disable the REST API (including HTTP listener)")="no";
101 ::arg().set("api-key", "Static pre-shared authentication key for access to the REST API")="";
102 ::arg().setSwitch("default-api-rectify","Default API-RECTIFY value for zones")="yes";
103 ::arg().setSwitch("dname-processing", "If we should support DNAME records")="no";
104
105 ::arg().setCmd("help","Provide a helpful message");
106 ::arg().setCmd("version","Output version and compilation date");
107 ::arg().setCmd("config","Provide configuration file on standard output");
108 ::arg().setCmd("list-modules","Lists all modules available");
109 ::arg().setCmd("no-config","Don't parse configuration file");
110
111 ::arg().set("version-string","PowerDNS version in packets - full, anonymous, powerdns or custom")="full";
112 ::arg().set("control-console","Debugging switch - don't use")="no"; // but I know you will!
113 ::arg().set("loglevel","Amount of logging. Higher is more. Do not set below 3")="4";
114 ::arg().set("disable-syslog","Disable logging to syslog, useful when running inside a supervisor that logs stdout")="no";
115 ::arg().set("log-timestamp","Print timestamps in log lines")="yes";
116 ::arg().set("default-soa-name","name to insert in the SOA record if none set in the backend")="a.misconfigured.powerdns.server";
117 ::arg().set("default-soa-mail","mail address to insert in the SOA record if none set in the backend")="";
118 ::arg().set("distributor-threads","Default number of Distributor (backend) threads to start")="3";
119 ::arg().set("signing-threads","Default number of signer threads to start")="3";
120 ::arg().set("receiver-threads","Default number of receiver threads to start")="1";
121 ::arg().set("queue-limit","Maximum number of milliseconds to queue a query")="1500";
122 ::arg().set("resolver","Use this resolver for ALIAS and the internal stub resolver")="no";
123 ::arg().set("udp-truncation-threshold", "Maximum UDP response size before we truncate")="1232";
124
125 ::arg().set("config-name","Name of this virtual configuration - will rename the binary image")="";
126
127 ::arg().set("load-modules","Load this module - supply absolute or relative path")="";
128 ::arg().set("launch","Which backends to launch and order to query them in")="";
129 ::arg().setSwitch("disable-axfr","Disable zonetransfers but do allow TCP queries")="no";
130 ::arg().set("allow-axfr-ips","Allow zonetransfers only to these subnets")="127.0.0.0/8,::1";
131 ::arg().set("only-notify", "Only send AXFR NOTIFY to these IP addresses or netmasks")="0.0.0.0/0,::/0";
132 ::arg().set("also-notify", "When notifying a domain, also notify these nameservers")="";
133 ::arg().set("allow-notify-from","Allow AXFR NOTIFY from these IP ranges. If empty, drop all incoming notifies.")="0.0.0.0/0,::/0";
134 ::arg().set("slave-cycle-interval","Schedule slave freshness checks once every .. seconds")="60";
135
136 ::arg().set("tcp-control-address","If set, PowerDNS can be controlled over TCP on this address")="";
137 ::arg().set("tcp-control-port","If set, PowerDNS can be controlled over TCP on this address")="53000";
138 ::arg().set("tcp-control-secret","If set, PowerDNS can be controlled over TCP after passing this secret")="";
139 ::arg().set("tcp-control-range","If set, remote control of PowerDNS is possible over these networks only")="127.0.0.0/8, 10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12, ::1/128, fe80::/10";
140
141 ::arg().setSwitch("slave","Act as a slave")="no";
142 ::arg().setSwitch("master","Act as a master")="no";
143 ::arg().setSwitch("superslave", "Act as a superslave")="no";
144 ::arg().setSwitch("disable-axfr-rectify","Disable the rectify step during an outgoing AXFR. Only required for regression testing.")="no";
145 ::arg().setSwitch("guardian","Run within a guardian process")="no";
146 ::arg().setSwitch("prevent-self-notification","Don't send notifications to what we think is ourself")="yes";
147 ::arg().setSwitch("any-to-tcp","Answer ANY queries with tc=1, shunting to TCP")="yes";
148 ::arg().setSwitch("edns-subnet-processing","If we should act on EDNS Subnet options")="no";
149
150 ::arg().setSwitch("webserver","Start a webserver for monitoring (api=yes also enables the HTTP listener)")="no";
151 ::arg().setSwitch("webserver-print-arguments","If the webserver should print arguments")="no";
152 ::arg().set("webserver-address","IP Address of webserver/API to listen on")="127.0.0.1";
153 ::arg().set("webserver-port","Port of webserver/API to listen on")="8081";
154 ::arg().set("webserver-password","Password required for accessing the webserver")="";
155 ::arg().set("webserver-allow-from","Webserver/API access is only allowed from these subnets")="127.0.0.1,::1";
156 ::arg().set("webserver-loglevel", "Amount of logging in the webserver (none, normal, detailed)") = "normal";
157 ::arg().set("webserver-max-bodysize","Webserver/API maximum request/response body size in megabytes")="2";
158
159 ::arg().setSwitch("do-ipv6-additional-processing", "Do AAAA additional processing")="yes";
160 ::arg().setSwitch("query-logging","Hint backends that queries should be logged")="no";
161
162 ::arg().set("carbon-namespace", "If set overwrites the first part of the carbon string")="pdns";
163 ::arg().set("carbon-ourname", "If set, overrides our reported hostname for carbon stats")="";
164 ::arg().set("carbon-instance", "If set overwrites the the instance name default")="auth";
165 ::arg().set("carbon-server", "If set, send metrics in carbon (graphite) format to this server IP address")="";
166 ::arg().set("carbon-interval", "Number of seconds between carbon (graphite) updates")="30";
167
168 ::arg().set("cache-ttl","Seconds to store packets in the PacketCache")="20";
169 ::arg().set("negquery-cache-ttl","Seconds to store negative query results in the QueryCache")="60";
170 ::arg().set("query-cache-ttl","Seconds to store query results in the QueryCache")="20";
171 ::arg().set("soa-minimum-ttl","Default SOA minimum ttl")="3600";
172 ::arg().set("server-id", "Returned when queried for 'id.server' TXT or NSID, defaults to hostname - disabled or custom")="";
173 ::arg().set("soa-refresh-default","Default SOA refresh")="10800";
174 ::arg().set("soa-retry-default","Default SOA retry")="3600";
175 ::arg().set("soa-expire-default","Default SOA expire")="604800";
176 ::arg().set("default-soa-edit","Default SOA-EDIT value")="";
177 ::arg().set("default-soa-edit-signed","Default SOA-EDIT value for signed zones")="";
178 ::arg().set("dnssec-key-cache-ttl","Seconds to cache DNSSEC keys from the database")="30";
179 ::arg().set("domain-metadata-cache-ttl","Seconds to cache domain metadata from the database")="60";
180
181 ::arg().set("trusted-notification-proxy", "IP address of incoming notification proxy")="";
182 ::arg().set("slave-renotify", "If we should send out notifications for slaved updates")="no";
183 ::arg().set("forward-notify", "IP addresses to forward received notifications to regardless of master or slave settings")="";
184
185 ::arg().set("default-ttl","Seconds a result is valid if not set otherwise")="3600";
186 ::arg().set("max-tcp-connections","Maximum number of TCP connections")="20";
187 ::arg().set("max-tcp-connections-per-client","Maximum number of simultaneous TCP connections per client")="0";
188 ::arg().set("max-tcp-transactions-per-conn","Maximum number of subsequent queries per TCP connection")="0";
189 ::arg().set("max-tcp-connection-duration","Maximum time in seconds that a TCP DNS connection is allowed to stay open.")="0";
190 ::arg().set("tcp-idle-timeout","Maximum time in seconds that a TCP DNS connection is allowed to stay open while being idle")="5";
191
192 ::arg().setSwitch("no-shuffle","Set this to prevent random shuffling of answers - for regression testing")="off";
193
194 ::arg().set("setuid","If set, change user id to this uid for more security")="";
195 ::arg().set("setgid","If set, change group id to this gid for more security")="";
196
197 ::arg().set("max-cache-entries", "Maximum number of entries in the query cache")="1000000";
198 ::arg().set("max-packet-cache-entries", "Maximum number of entries in the packet cache")="1000000";
199 ::arg().set("max-signature-cache-entries", "Maximum number of signatures cache entries")="";
200 ::arg().set("max-ent-entries", "Maximum number of empty non-terminals in a zone")="100000";
201 ::arg().set("entropy-source", "If set, read entropy from this file")="/dev/urandom";
202
203 ::arg().set("lua-prequery-script", "Lua script with prequery handler (DO NOT USE)")="";
204 ::arg().set("lua-dnsupdate-policy-script", "Lua script with DNS update policy handler")="";
205
206 ::arg().setSwitch("traceback-handler","Enable the traceback handler (Linux only)")="yes";
207 ::arg().setSwitch("direct-dnskey","Fetch DNSKEY, CDS and CDNSKEY RRs from backend during DNSKEY or CDS/CDNSKEY synthesis")="no";
208 ::arg().set("default-ksk-algorithm","Default KSK algorithm")="ecdsa256";
209 ::arg().set("default-ksk-size","Default KSK size (0 means default)")="0";
210 ::arg().set("default-zsk-algorithm","Default ZSK algorithm")="";
211 ::arg().set("default-zsk-size","Default ZSK size (0 means default)")="0";
212 ::arg().set("max-nsec3-iterations","Limit the number of NSEC3 hash iterations")="500"; // RFC5155 10.3
213 ::arg().set("default-publish-cdnskey","Default value for PUBLISH-CDNSKEY")="";
214 ::arg().set("default-publish-cds","Default value for PUBLISH-CDS")="";
215
216 ::arg().set("include-dir","Include *.conf files from this directory");
217 ::arg().set("security-poll-suffix","Domain name from which to query security update notifications")="secpoll.powerdns.com.";
218
219 ::arg().setSwitch("expand-alias", "Expand ALIAS records")="no";
220 ::arg().setSwitch("outgoing-axfr-expand-alias", "Expand ALIAS records during outgoing AXFR")="no";
221 ::arg().setSwitch("8bit-dns", "Allow 8bit dns queries")="no";
222 #ifdef HAVE_LUA_RECORDS
223 ::arg().setSwitch("enable-lua-records", "Process LUA records for all zones (metadata overrides this)")="no";
224 ::arg().set("lua-records-exec-limit", "LUA records scripts execution limit (instructions count). Values <= 0 mean no limit")="1000";
225 ::arg().set("lua-health-checks-expire-delay", "Stops doing health checks after the record hasn't been used for that delay (in seconds)")="3600";
226 ::arg().set("lua-health-checks-interval", "LUA records health checks monitoring interval in seconds")="5";
227 #endif
228 ::arg().setSwitch("axfr-lower-serial", "Also AXFR a zone from a master with a lower serial")="no";
229
230 ::arg().set("lua-axfr-script", "Script to be used to edit incoming AXFRs")="";
231 ::arg().set("xfr-max-received-mbytes", "Maximum number of megabytes received from an incoming XFR")="100";
232 ::arg().set("axfr-fetch-timeout", "Maximum time in seconds for inbound AXFR to start or be idle after starting")="10";
233
234 ::arg().set("tcp-fast-open", "Enable TCP Fast Open support on the listening sockets, using the supplied numerical value as the queue size")="0";
235
236 ::arg().set("max-generate-steps", "Maximum number of $GENERATE steps when loading a zone from a file")="0";
237
238 ::arg().set("rng", "Specify the random number generator to use. Valid values are auto,sodium,openssl,getrandom,arc4random,urandom.")="auto";
239 ::arg().setDefaults();
240 }
241
242 static time_t s_start=time(0);
243 static uint64_t uptimeOfProcess(const std::string& str)
244 {
245 return time(0) - s_start;
246 }
247
248 static uint64_t getSysUserTimeMsec(const std::string& str)
249 {
250 struct rusage ru;
251 getrusage(RUSAGE_SELF, &ru);
252
253 if(str=="sys-msec") {
254 return (ru.ru_stime.tv_sec*1000ULL + ru.ru_stime.tv_usec/1000);
255 }
256 else
257 return (ru.ru_utime.tv_sec*1000ULL + ru.ru_utime.tv_usec/1000);
258
259 }
260
261 static uint64_t getTCPConnectionCount(const std::string& str)
262 {
263 return TN->numTCPConnections();
264 }
265
266 static uint64_t getQCount(const std::string& str)
267 try
268 {
269 int totcount=0;
270 for(const auto& d : g_distributors) {
271 if(!d)
272 continue;
273 totcount += d->getQueueSize(); // this does locking and other things, so don't get smart
274 }
275 return totcount;
276 }
277 catch(std::exception& e)
278 {
279 g_log<<Logger::Error<<"Had error retrieving queue sizes: "<<e.what()<<endl;
280 return 0;
281 }
282 catch(PDNSException& e)
283 {
284 g_log<<Logger::Error<<"Had error retrieving queue sizes: "<<e.reason<<endl;
285 return 0;
286 }
287
288 static uint64_t getLatency(const std::string& str)
289 {
290 return avg_latency;
291 }
292
293 void declareStats(void)
294 {
295 S.declare("udp-queries","Number of UDP queries received");
296 S.declare("udp-do-queries","Number of UDP queries received with DO bit");
297 S.declare("udp-answers","Number of answers sent out over UDP");
298 S.declare("udp-answers-bytes","Total size of answers sent out over UDP");
299 S.declare("udp4-answers-bytes","Total size of answers sent out over UDPv4");
300 S.declare("udp6-answers-bytes","Total size of answers sent out over UDPv6");
301
302 S.declare("udp4-answers","Number of IPv4 answers sent out over UDP");
303 S.declare("udp4-queries","Number of IPv4 UDP queries received");
304 S.declare("udp6-answers","Number of IPv6 answers sent out over UDP");
305 S.declare("udp6-queries","Number of IPv6 UDP queries received");
306 S.declare("overload-drops","Queries dropped because backends overloaded");
307
308 S.declare("rd-queries", "Number of recursion desired questions");
309 S.declare("recursion-unanswered", "Number of packets unanswered by configured recursor");
310 S.declare("recursing-answers","Number of recursive answers sent out");
311 S.declare("recursing-questions","Number of questions sent to recursor");
312 S.declare("corrupt-packets","Number of corrupt packets received");
313 S.declare("signatures", "Number of DNSSEC signatures made");
314 S.declare("tcp-queries","Number of TCP queries received");
315 S.declare("tcp-answers","Number of answers sent out over TCP");
316 S.declare("tcp-answers-bytes","Total size of answers sent out over TCP");
317 S.declare("tcp4-answers-bytes","Total size of answers sent out over TCPv4");
318 S.declare("tcp6-answers-bytes","Total size of answers sent out over TCPv6");
319
320 S.declare("tcp4-queries","Number of IPv4 TCP queries received");
321 S.declare("tcp4-answers","Number of IPv4 answers sent out over TCP");
322
323 S.declare("tcp6-queries","Number of IPv6 TCP queries received");
324 S.declare("tcp6-answers","Number of IPv6 answers sent out over TCP");
325
326 S.declare("open-tcp-connections","Number of currently open TCP connections", getTCPConnectionCount);;
327
328 S.declare("qsize-q","Number of questions waiting for database attention", getQCount);
329
330 S.declare("dnsupdate-queries", "DNS update packets received.");
331 S.declare("dnsupdate-answers", "DNS update packets successfully answered.");
332 S.declare("dnsupdate-refused", "DNS update packets that are refused.");
333 S.declare("dnsupdate-changes", "DNS update changes to records in total.");
334
335 S.declare("incoming-notifications", "NOTIFY packets received.");
336
337 S.declare("uptime", "Uptime of process in seconds", uptimeOfProcess);
338 S.declare("real-memory-usage", "Actual unique use of memory in bytes (approx)", getRealMemoryUsage);
339 S.declare("special-memory-usage", "Actual unique use of memory in bytes (approx)", getSpecialMemoryUsage);
340 S.declare("fd-usage", "Number of open filedescriptors", getOpenFileDescriptors);
341 #ifdef __linux__
342 S.declare("udp-recvbuf-errors", "UDP 'recvbuf' errors", udpErrorStats);
343 S.declare("udp-sndbuf-errors", "UDP 'sndbuf' errors", udpErrorStats);
344 S.declare("udp-noport-errors", "UDP 'noport' errors", udpErrorStats);
345 S.declare("udp-in-errors", "UDP 'in' errors", udpErrorStats);
346 #endif
347
348 S.declare("sys-msec", "Number of msec spent in system time", getSysUserTimeMsec);
349 S.declare("user-msec", "Number of msec spent in user time", getSysUserTimeMsec);
350
351 #ifdef __linux__
352 S.declare("cpu-iowait", "Time spent waiting for I/O to complete by the whole system, in units of USER_HZ", getCPUIOWait);
353 S.declare("cpu-steal", "Stolen time, which is the time spent by the whole system in other operating systems when running in a virtualized environment, in units of USER_HZ", getCPUSteal);
354 #endif
355
356 S.declare("meta-cache-size", "Number of entries in the metadata cache", DNSSECKeeper::dbdnssecCacheSizes);
357 S.declare("key-cache-size", "Number of entries in the key cache", DNSSECKeeper::dbdnssecCacheSizes);
358 S.declare("signature-cache-size", "Number of entries in the signature cache", signatureCacheSize);
359
360 S.declare("servfail-packets","Number of times a server-failed packet was sent out");
361 S.declare("latency","Average number of microseconds needed to answer a question", getLatency);
362 S.declare("timedout-packets","Number of packets which weren't answered within timeout set");
363 S.declare("security-status", "Security status based on regular polling");
364 S.declareDNSNameQTypeRing("queries","UDP Queries Received");
365 S.declareDNSNameQTypeRing("nxdomain-queries","Queries for non-existent records within existent domains");
366 S.declareDNSNameQTypeRing("noerror-queries","Queries for existing records, but for type we don't have");
367 S.declareDNSNameQTypeRing("servfail-queries","Queries that could not be answered due to backend errors");
368 S.declareDNSNameQTypeRing("unauth-queries","Queries for domains that we are not authoritative for");
369 S.declareRing("logmessages","Log Messages");
370 S.declareComboRing("remotes","Remote server IP addresses");
371 S.declareComboRing("remotes-unauth","Remote hosts querying domains for which we are not auth");
372 S.declareComboRing("remotes-corrupt","Remote hosts sending corrupt packets");
373 }
374
375 int isGuarded(char **argv)
376 {
377 char *p=strstr(argv[0],"-instance");
378
379 return !!p;
380 }
381
382 static void sendout(std::unique_ptr<DNSPacket>& a)
383 {
384 if(!a)
385 return;
386
387 N->send(*a);
388
389 int diff=a->d_dt.udiff();
390 avg_latency=(int)(0.999*avg_latency+0.001*diff);
391 }
392
393 //! The qthread receives questions over the internet via the Nameserver class, and hands them to the Distributor for further processing
394 static void qthread(unsigned int num)
395 try
396 {
397 setThreadName("pdns/receiver");
398
399 g_distributors[num] = DNSDistributor::Create(::arg().asNum("distributor-threads", 1));
400 DNSDistributor* distributor = g_distributors[num]; // the big dispatcher!
401 DNSPacket question(true);
402 DNSPacket cached(false);
403
404 AtomicCounter &numreceived=*S.getPointer("udp-queries");
405 AtomicCounter &numreceiveddo=*S.getPointer("udp-do-queries");
406
407 AtomicCounter &numreceived4=*S.getPointer("udp4-queries");
408
409 AtomicCounter &numreceived6=*S.getPointer("udp6-queries");
410 AtomicCounter &overloadDrops=*S.getPointer("overload-drops");
411
412 int diff;
413 bool logDNSQueries = ::arg().mustDo("log-dns-queries");
414 shared_ptr<UDPNameserver> NS;
415 std::string buffer;
416 buffer.resize(DNSPacket::s_udpTruncationThreshold);
417
418 // If we have SO_REUSEPORT then create a new port for all receiver threads
419 // other than the first one.
420 if(N->canReusePort() ) {
421 NS = g_udpReceivers[num];
422 if (NS == nullptr) {
423 NS = N;
424 }
425 } else {
426 NS = N;
427 }
428
429 for(;;) {
430 if(!NS->receive(question, buffer)) { // receive a packet inline
431 continue; // packet was broken, try again
432 }
433
434 numreceived++;
435
436 if(question.d_remote.getSocklen()==sizeof(sockaddr_in))
437 numreceived4++;
438 else
439 numreceived6++;
440
441 if(question.d_dnssecOk)
442 numreceiveddo++;
443
444 if(question.d.qr)
445 continue;
446
447 S.ringAccount("queries", question.qdomain, question.qtype);
448 S.ringAccount("remotes", question.d_remote);
449 if(logDNSQueries) {
450 string remote;
451 if(question.hasEDNSSubnet())
452 remote = question.getRemote().toString() + "<-" + question.getRealRemote().toString();
453 else
454 remote = question.getRemote().toString();
455 g_log << Logger::Notice<<"Remote "<< remote <<" wants '" << question.qdomain<<"|"<<question.qtype.getName() <<
456 "', do = " <<question.d_dnssecOk <<", bufsize = "<< question.getMaxReplyLen();
457 if(question.d_ednsRawPacketSizeLimit > 0 && question.getMaxReplyLen() != (unsigned int)question.d_ednsRawPacketSizeLimit)
458 g_log<<" ("<<question.d_ednsRawPacketSizeLimit<<")";
459 }
460
461 if(PC.enabled() && (question.d.opcode != Opcode::Notify && question.d.opcode != Opcode::Update) && question.couldBeCached()) {
462 bool haveSomething=PC.get(question, cached); // does the PacketCache recognize this question?
463 if (haveSomething) {
464 if(logDNSQueries)
465 g_log<<": packetcache HIT"<<endl;
466 cached.setRemote(&question.d_remote); // inlined
467 cached.setSocket(question.getSocket()); // inlined
468 cached.d_anyLocal = question.d_anyLocal;
469 cached.setMaxReplyLen(question.getMaxReplyLen());
470 cached.d.rd=question.d.rd; // copy in recursion desired bit
471 cached.d.id=question.d.id;
472 cached.commitD(); // commit d to the packet inlined
473 NS->send(cached); // answer it then inlined
474 diff=question.d_dt.udiff();
475 avg_latency=(int)(0.999*avg_latency+0.001*diff); // 'EWMA'
476 continue;
477 }
478 }
479
480 if(distributor->isOverloaded()) {
481 if(logDNSQueries)
482 g_log<<": Dropped query, backends are overloaded"<<endl;
483 overloadDrops++;
484 continue;
485 }
486
487 if (logDNSQueries) {
488 if (PC.enabled()) {
489 g_log<<": packetcache MISS"<<endl;
490 } else {
491 g_log<<endl;
492 }
493 }
494
495 try {
496 distributor->question(question, &sendout); // otherwise, give to the distributor
497 }
498 catch(DistributorFatal& df) { // when this happens, we have leaked loads of memory. Bailing out time.
499 _exit(1);
500 }
501 }
502 }
503 catch(PDNSException& pe)
504 {
505 g_log<<Logger::Error<<"Fatal error in question thread: "<<pe.reason<<endl;
506 _exit(1);
507 }
508
509 static void dummyThread()
510 {
511 }
512
513 static void triggerLoadOfLibraries()
514 {
515 std::thread dummy(dummyThread);
516 dummy.join();
517 }
518
519 void mainthread()
520 {
521 Utility::srandom();
522
523 gid_t newgid = 0;
524 if(!::arg()["setgid"].empty())
525 newgid = strToGID(::arg()["setgid"]);
526 uid_t newuid = 0;
527 if(!::arg()["setuid"].empty())
528 newuid = strToUID(::arg()["setuid"]);
529
530 g_anyToTcp = ::arg().mustDo("any-to-tcp");
531 g_8bitDNS = ::arg().mustDo("8bit-dns");
532 #ifdef HAVE_LUA_RECORDS
533 g_doLuaRecord = ::arg().mustDo("enable-lua-records");
534 g_LuaRecordSharedState = (::arg()["enable-lua-records"] == "shared");
535 g_luaRecordExecLimit = ::arg().asNum("lua-records-exec-limit");
536 g_luaHealthChecksInterval = ::arg().asNum("lua-health-checks-interval");
537 g_luaHealthChecksExpireDelay = ::arg().asNum("lua-health-checks-expire-delay");
538 #endif
539
540 DNSPacket::s_udpTruncationThreshold = std::max(512, ::arg().asNum("udp-truncation-threshold"));
541 DNSPacket::s_doEDNSSubnetProcessing = ::arg().mustDo("edns-subnet-processing");
542
543 PC.setTTL(::arg().asNum("cache-ttl"));
544 PC.setMaxEntries(::arg().asNum("max-packet-cache-entries"));
545 QC.setMaxEntries(::arg().asNum("max-cache-entries"));
546 DNSSECKeeper::setMaxEntries(::arg().asNum("max-cache-entries"));
547
548 if (!PC.enabled() && ::arg().mustDo("log-dns-queries")) {
549 g_log<<Logger::Warning<<"Packet cache disabled, logging queries without HIT/MISS"<<endl;
550 }
551
552 stubParseResolveConf();
553
554 if(!::arg()["chroot"].empty()) {
555 #ifdef HAVE_SYSTEMD
556 char *ns;
557 ns = getenv("NOTIFY_SOCKET");
558 if (ns != nullptr) {
559 g_log<<Logger::Error<<"Unable to chroot when running from systemd. Please disable chroot= or set the 'Type' for this service to 'simple'"<<endl;
560 exit(1);
561 }
562 #endif
563 triggerLoadOfLibraries();
564 if(::arg().mustDo("master") || ::arg().mustDo("slave"))
565 gethostbyname("a.root-servers.net"); // this forces all lookup libraries to be loaded
566 Utility::dropGroupPrivs(newuid, newgid);
567 if(chroot(::arg()["chroot"].c_str())<0 || chdir("/")<0) {
568 g_log<<Logger::Error<<"Unable to chroot to '"+::arg()["chroot"]+"': "<<stringerror()<<", exiting"<<endl;
569 exit(1);
570 }
571 else
572 g_log<<Logger::Error<<"Chrooted to '"<<::arg()["chroot"]<<"'"<<endl;
573 } else {
574 Utility::dropGroupPrivs(newuid, newgid);
575 }
576
577 AuthWebServer webserver;
578 Utility::dropUserPrivs(newuid);
579
580 if(::arg().mustDo("resolver")){
581 DP=std::unique_ptr<DNSProxy>(new DNSProxy(::arg()["resolver"]));
582 DP->go();
583 }
584
585 try {
586 doSecPoll(true);
587 }
588 catch(...) {}
589
590 {
591 // Some sanity checking on default key settings
592 bool hadKeyError = false;
593 int kskAlgo{0}, zskAlgo{0};
594 for (const string& algotype : {"ksk", "zsk"}) {
595 int algo, size;
596 if (::arg()["default-"+algotype+"-algorithm"].empty())
597 continue;
598 algo = DNSSECKeeper::shorthand2algorithm(::arg()["default-"+algotype+"-algorithm"]);
599 size = ::arg().asNum("default-"+algotype+"-size");
600 if (algo == -1) {
601 g_log<<Logger::Error<<"Error: default-"<<algotype<<"-algorithm set to unknown algorithm: "<<::arg()["default-"+algotype+"-algorithm"]<<endl;
602 hadKeyError = true;
603 }
604 else if (algo <= 10 && size == 0) {
605 g_log<<Logger::Error<<"Error: default-"<<algotype<<"-algorithm is set to an algorithm ("<<::arg()["default-"+algotype+"-algorithm"]<<") that requires a non-zero default-"<<algotype<<"-size!"<<endl;
606 hadKeyError = true;
607 }
608 if (algotype == "ksk") {
609 kskAlgo = algo;
610 } else {
611 zskAlgo = algo;
612 }
613 }
614 if (hadKeyError) {
615 exit(1);
616 }
617 if (kskAlgo == 0 && zskAlgo != 0) {
618 g_log<<Logger::Error<<"Error: default-zsk-algorithm is set, but default-ksk-algorithm is not set."<<endl;
619 exit(1);
620 }
621 if (zskAlgo != 0 && zskAlgo != kskAlgo) {
622 g_log<<Logger::Error<<"Error: default-zsk-algorithm ("<<::arg()["default-zsk-algorithm"]<<"), when set, can not be different from default-ksk-algorithm ("<<::arg()["default-ksk-algorithm"]<<")."<<endl;
623 exit(1);
624 }
625 }
626
627 // NOW SAFE TO CREATE THREADS!
628 dl->go();
629
630 if(::arg().mustDo("webserver") || ::arg().mustDo("api"))
631 webserver.go();
632
633 if(::arg().mustDo("slave") || ::arg().mustDo("master") || !::arg()["forward-notify"].empty())
634 Communicator.go();
635
636 TN->go(); // tcp nameserver launch
637
638 unsigned int max_rthreads= ::arg().asNum("receiver-threads", 1);
639 g_distributors.resize(max_rthreads);
640 for(unsigned int n=0; n < max_rthreads; ++n) {
641 std::thread t(qthread, n);
642 t.detach();
643 }
644
645 std::thread carbonThread(carbonDumpThread); // runs even w/o carbon, might change @ runtime
646
647 #ifdef HAVE_SYSTEMD
648 /* If we are here, notify systemd that we are ay-ok! This might have some
649 * timing issues with the backend-threads. e.g. if the initial MySQL connection
650 * is slow and times out (leading to process termination through the backend)
651 * We probably have told systemd already that we have started correctly.
652 */
653 sd_notify(0, "READY=1");
654 #endif
655
656 for(;;) {
657 sleep(1800);
658 try {
659 doSecPoll(false);
660 }
661 catch(...){}
662 }
663
664 g_log<<Logger::Error<<"Mainthread exiting - should never happen"<<endl;
665 }