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