2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
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.
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.
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.
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.
26 // for OpenBSD, sys/socket.h needs to come before net/if.h
27 #include <sys/socket.h>
30 #include <sys/types.h>
35 #include "dnsdist-console.hh"
36 #include "dnsdist-ecs.hh"
37 #include "dnsdist-lua.hh"
38 #include "dnsdist-rings.hh"
39 #include "dnsdist-secpoll.hh"
42 #include "dnswriter.hh"
45 #include "protobuf.hh"
46 #include "sodcrypto.hh"
48 #include <boost/logic/tribool.hpp>
49 #include <boost/lexical_cast.hpp>
52 #include <systemd/sd-daemon.h>
57 static vector
<std::function
<void(void)>>* g_launchWork
= nullptr;
59 boost::tribool g_noLuaSideEffect
;
60 static bool g_included
{false};
62 /* this is a best effort way to prevent logging calls with no side-effects in the output of delta()
63 Functions can declare setLuaNoSideEffect() and if nothing else does declare a side effect, or nothing
64 has done so before on this invocation, this call won't be part of delta() output */
65 void setLuaNoSideEffect()
67 if(g_noLuaSideEffect
==false) // there has been a side effect already
69 g_noLuaSideEffect
=true;
72 void setLuaSideEffect()
74 g_noLuaSideEffect
=false;
77 bool getLuaNoSideEffect()
79 if (g_noLuaSideEffect
) {
85 void resetLuaSideEffect()
87 g_noLuaSideEffect
= boost::logic::indeterminate
;
90 typedef std::unordered_map
<std::string
, boost::variant
<bool, int, std::string
, std::vector
<std::pair
<int,int> > > > localbind_t
;
92 static void parseLocalBindVars(boost::optional
<localbind_t
> vars
, bool& doTCP
, bool& reusePort
, int& tcpFastOpenQueueSize
, std::string
& interface
, std::set
<int>& cpus
)
95 if (vars
->count("doTCP")) {
96 doTCP
= boost::get
<bool>((*vars
)["doTCP"]);
98 if (vars
->count("reusePort")) {
99 reusePort
= boost::get
<bool>((*vars
)["reusePort"]);
101 if (vars
->count("tcpFastOpenQueueSize")) {
102 tcpFastOpenQueueSize
= boost::get
<int>((*vars
)["tcpFastOpenQueueSize"]);
104 if (vars
->count("interface")) {
105 interface
= boost::get
<std::string
>((*vars
)["interface"]);
107 if (vars
->count("cpus")) {
108 for (const auto cpu
: boost::get
<std::vector
<std::pair
<int,int>>>((*vars
)["cpus"])) {
109 cpus
.insert(cpu
.second
);
115 #ifdef HAVE_DNS_OVER_TLS
116 static bool loadTLSCertificateAndKeys(shared_ptr
<TLSFrontend
>& frontend
, boost::variant
<std::string
, std::vector
<std::pair
<int,std::string
>>> certFiles
, boost::variant
<std::string
, std::vector
<std::pair
<int,std::string
>>> keyFiles
)
118 if (certFiles
.type() == typeid(std::string
) && keyFiles
.type() == typeid(std::string
)) {
119 auto certFile
= boost::get
<std::string
>(certFiles
);
120 auto keyFile
= boost::get
<std::string
>(keyFiles
);
121 frontend
->d_certKeyPairs
.clear();
122 frontend
->d_certKeyPairs
.push_back({certFile
, keyFile
});
124 else if (certFiles
.type() == typeid(std::vector
<std::pair
<int,std::string
>>) && keyFiles
.type() == typeid(std::vector
<std::pair
<int,std::string
>>))
126 auto certFilesVect
= boost::get
<std::vector
<std::pair
<int,std::string
>>>(certFiles
);
127 auto keyFilesVect
= boost::get
<std::vector
<std::pair
<int,std::string
>>>(keyFiles
);
128 if (certFilesVect
.size() == keyFilesVect
.size()) {
129 frontend
->d_certKeyPairs
.clear();
130 for (size_t idx
= 0; idx
< certFilesVect
.size(); idx
++) {
131 frontend
->d_certKeyPairs
.push_back({certFilesVect
.at(idx
).second
, keyFilesVect
.at(idx
).second
});
135 errlog("Error, mismatching number of certificates and keys in call to addTLSLocal()!");
136 g_outputBuffer
="Error, mismatching number of certificates and keys in call to addTLSLocal()!";
141 errlog("Error, mismatching number of certificates and keys in call to addTLSLocal()!");
142 g_outputBuffer
="Error, mismatching number of certificates and keys in call to addTLSLocal()!";
148 #endif /* HAVE_DNS_OVER_TLS */
150 void setupLuaConfig(bool client
)
152 typedef std::unordered_map
<std::string
, boost::variant
<bool, std::string
, vector
<pair
<int, std::string
> >, DownstreamState::checkfunc_t
> > newserver_t
;
153 g_lua
.writeFunction("inClientStartup", [client
]() {
154 return client
&& !g_configurationDone
;
157 g_lua
.writeFunction("newServer",
158 [client
](boost::variant
<string
,newserver_t
> pvars
, boost::optional
<int> qps
) {
161 std::shared_ptr
<DownstreamState
> ret
= std::make_shared
<DownstreamState
>(ComboAddress());
164 ComboAddress serverAddr
;
165 std::string serverAddressStr
;
166 if(auto addrStr
= boost::get
<string
>(&pvars
)) {
167 serverAddressStr
= *addrStr
;
169 vars
["qps"] = std::to_string(*qps
);
172 vars
= boost::get
<newserver_t
>(pvars
);
173 serverAddressStr
= boost::get
<string
>(vars
["address"]);
177 serverAddr
= ComboAddress(serverAddressStr
, 53);
179 catch(const PDNSException
& e
) {
180 g_outputBuffer
="Error creating new server: "+string(e
.reason
);
181 errlog("Error creating new server with address %s: %s", serverAddressStr
, e
.reason
);
184 catch(std::exception
& e
) {
185 g_outputBuffer
="Error creating new server: "+string(e
.what());
186 errlog("Error creating new server with address %s: %s", serverAddressStr
, e
.what());
190 if(IsAnyAddress(serverAddr
)) {
191 g_outputBuffer
="Error creating new server: invalid address for a downstream server.";
192 errlog("Error creating new server: %s is not a valid address for a downstream server", serverAddressStr
);
196 ComboAddress sourceAddr
;
197 unsigned int sourceItf
= 0;
198 size_t numberOfSockets
= 1;
201 if(vars
.count("source")) {
202 /* handle source in the following forms:
203 - v4 address ("192.0.2.1")
204 - v6 address ("2001:DB8::1")
205 - interface name ("eth0")
206 - v4 address and interface name ("192.0.2.1@eth0")
207 - v6 address and interface name ("2001:DB8::1@eth0")
209 const string source
= boost::get
<string
>(vars
["source"]);
211 std::string::size_type pos
= source
.find("@");
212 if (pos
== std::string::npos
) {
213 /* no '@', try to parse that as a valid v4/v6 address */
215 sourceAddr
= ComboAddress(source
);
225 /* try to parse as interface name, or v4/v6@itf */
226 string itfName
= source
.substr(pos
== std::string::npos
? 0 : pos
+ 1);
227 unsigned int itfIdx
= if_nametoindex(itfName
.c_str());
230 if (pos
== 0 || pos
== std::string::npos
) {
231 /* "eth0" or "@eth0" */
235 /* "192.0.2.1@eth0" */
236 sourceAddr
= ComboAddress(source
.substr(0, pos
));
242 warnlog("Dismissing source %s because '%s' is not a valid interface name", source
, itfName
);
247 if (vars
.count("sockets")) {
248 numberOfSockets
= std::stoul(boost::get
<string
>(vars
["sockets"]));
249 if (numberOfSockets
== 0) {
250 warnlog("Dismissing invalid number of sockets '%s', using 1 instead", boost::get
<string
>(vars
["sockets"]));
256 // do not construct DownstreamState now, it would try binding sockets.
259 ret
=std::make_shared
<DownstreamState
>(serverAddr
, sourceAddr
, sourceItf
, numberOfSockets
);
261 if(vars
.count("qps")) {
262 int qpsVal
=std::stoi(boost::get
<string
>(vars
["qps"]));
263 ret
->qps
=QPSLimiter(qpsVal
, qpsVal
);
266 if(vars
.count("order")) {
267 ret
->order
=std::stoi(boost::get
<string
>(vars
["order"]));
270 if(vars
.count("weight")) {
272 int weightVal
=std::stoi(boost::get
<string
>(vars
["weight"]));
275 errlog("Error creating new server: downstream weight value must be greater than 0.");
279 ret
->setWeight(weightVal
);
281 catch(std::exception
& e
) {
282 // std::stoi will throw an exception if the string isn't in a value int range
283 errlog("Error creating new server: downstream weight value must be between %s and %s", 1, std::numeric_limits
<int>::max());
288 if(vars
.count("retries")) {
289 ret
->retries
=std::stoi(boost::get
<string
>(vars
["retries"]));
292 if(vars
.count("checkInterval")) {
293 ret
->checkInterval
=static_cast<unsigned int>(std::stoul(boost::get
<string
>(vars
["checkInterval"])));
296 if(vars
.count("tcpConnectTimeout")) {
297 ret
->tcpConnectTimeout
=std::stoi(boost::get
<string
>(vars
["tcpConnectTimeout"]));
300 if(vars
.count("tcpSendTimeout")) {
301 ret
->tcpSendTimeout
=std::stoi(boost::get
<string
>(vars
["tcpSendTimeout"]));
304 if(vars
.count("tcpRecvTimeout")) {
305 ret
->tcpRecvTimeout
=std::stoi(boost::get
<string
>(vars
["tcpRecvTimeout"]));
308 if(vars
.count("tcpFastOpen")) {
309 bool fastOpen
= boost::get
<bool>(vars
["tcpFastOpen"]);
312 ret
->tcpFastOpen
=true;
314 warnlog("TCP Fast Open has been configured on downstream server %s but is not supported", boost::get
<string
>(vars
["address"]));
319 if(vars
.count("name")) {
320 ret
->name
=boost::get
<string
>(vars
["name"]);
323 if (vars
.count("id")) {
324 ret
->setId(boost::lexical_cast
<boost::uuids::uuid
>(boost::get
<string
>(vars
["id"])));
327 if(vars
.count("checkName")) {
328 ret
->checkName
=DNSName(boost::get
<string
>(vars
["checkName"]));
331 if(vars
.count("checkType")) {
332 ret
->checkType
=boost::get
<string
>(vars
["checkType"]);
335 if(vars
.count("checkClass")) {
336 ret
->checkClass
=std::stoi(boost::get
<string
>(vars
["checkClass"]));
339 if(vars
.count("checkFunction")) {
340 ret
->checkFunction
= boost::get
<DownstreamState::checkfunc_t
>(vars
["checkFunction"]);
343 if(vars
.count("checkTimeout")) {
344 ret
->checkTimeout
= std::stoi(boost::get
<string
>(vars
["checkTimeout"]));
347 if(vars
.count("setCD")) {
348 ret
->setCD
=boost::get
<bool>(vars
["setCD"]);
351 if(vars
.count("mustResolve")) {
352 ret
->mustResolve
=boost::get
<bool>(vars
["mustResolve"]);
355 if(vars
.count("useClientSubnet")) {
356 ret
->useECS
=boost::get
<bool>(vars
["useClientSubnet"]);
359 if(vars
.count("disableZeroScope")) {
360 ret
->disableZeroScope
=boost::get
<bool>(vars
["disableZeroScope"]);
363 if(vars
.count("ipBindAddrNoPort")) {
364 ret
->ipBindAddrNoPort
=boost::get
<bool>(vars
["ipBindAddrNoPort"]);
367 if(vars
.count("addXPF")) {
368 ret
->xpfRRCode
=std::stoi(boost::get
<string
>(vars
["addXPF"]));
371 if(vars
.count("maxCheckFailures")) {
372 ret
->maxCheckFailures
=std::stoi(boost::get
<string
>(vars
["maxCheckFailures"]));
375 if(vars
.count("rise")) {
376 ret
->minRiseSuccesses
=std::stoi(boost::get
<string
>(vars
["rise"]));
379 if(vars
.count("cpus")) {
380 for (const auto cpu
: boost::get
<vector
<pair
<int,string
>>>(vars
["cpus"])) {
381 cpus
.insert(std::stoi(cpu
.second
));
385 /* this needs to be done _AFTER_ the order has been set,
386 since the server are kept ordered inside the pool */
387 auto localPools
= g_pools
.getCopy();
388 if(vars
.count("pool")) {
389 if(auto* pool
= boost::get
<string
>(&vars
["pool"])) {
390 ret
->pools
.insert(*pool
);
393 auto pools
= boost::get
<vector
<pair
<int, string
> > >(vars
["pool"]);
394 for(auto& p
: pools
) {
395 ret
->pools
.insert(p
.second
);
398 for(const auto& poolName
: ret
->pools
) {
399 addServerToPool(localPools
, poolName
, ret
);
403 addServerToPool(localPools
, "", ret
);
405 g_pools
.setState(localPools
);
407 if (ret
->connected
) {
408 ret
->threadStarted
.test_and_set();
411 g_launchWork
->push_back([ret
,cpus
]() {
412 ret
->tid
= thread(responderThread
, ret
);
414 mapThreadToCPUList(ret
->tid
.native_handle(), cpus
);
419 ret
->tid
= thread(responderThread
, ret
);
421 mapThreadToCPUList(ret
->tid
.native_handle(), cpus
);
426 auto states
= g_dstates
.getCopy();
427 states
.push_back(ret
);
428 std::stable_sort(states
.begin(), states
.end(), [](const decltype(ret
)& a
, const decltype(ret
)& b
) {
429 return a
->order
< b
->order
;
431 g_dstates
.setState(states
);
435 g_lua
.writeFunction("rmServer",
436 [](boost::variant
<std::shared_ptr
<DownstreamState
>, int> var
)
439 shared_ptr
<DownstreamState
> server
;
440 auto* rem
= boost::get
<shared_ptr
<DownstreamState
>>(&var
);
441 auto states
= g_dstates
.getCopy();
446 int idx
= boost::get
<int>(var
);
447 server
= states
.at(idx
);
449 auto localPools
= g_pools
.getCopy();
450 for (const string
& poolName
: server
->pools
) {
451 removeServerFromPool(localPools
, poolName
, server
);
453 /* the server might also be in the default pool */
454 removeServerFromPool(localPools
, "", server
);
455 g_pools
.setState(localPools
);
456 states
.erase(remove(states
.begin(), states
.end(), server
), states
.end());
457 g_dstates
.setState(states
);
460 g_lua
.writeFunction("setServerPolicy", [](ServerPolicy policy
) {
462 g_policy
.setState(policy
);
464 g_lua
.writeFunction("setServerPolicyLua", [](string name
, policyfunc_t policy
) {
466 g_policy
.setState(ServerPolicy
{name
, policy
, true});
469 g_lua
.writeFunction("showServerPolicy", []() {
471 g_outputBuffer
=g_policy
.getLocal()->name
+"\n";
474 g_lua
.writeFunction("truncateTC", [](bool tc
) { setLuaSideEffect(); g_truncateTC
=tc
; });
475 g_lua
.writeFunction("fixupCase", [](bool fu
) { setLuaSideEffect(); g_fixupCase
=fu
; });
477 g_lua
.writeFunction("addACL", [](const std::string
& domain
) {
479 g_ACL
.modify([domain
](NetmaskGroup
& nmg
) { nmg
.addMask(domain
); });
482 g_lua
.writeFunction("setLocal", [client
](const std::string
& addr
, boost::optional
<localbind_t
> vars
) {
486 if (g_configurationDone
) {
487 g_outputBuffer
="setLocal cannot be used at runtime!\n";
491 bool reusePort
= false;
492 int tcpFastOpenQueueSize
= 0;
493 std::string interface
;
496 parseLocalBindVars(vars
, doTCP
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
);
499 ComboAddress
loc(addr
, 53);
501 g_locals
.push_back(std::make_tuple(loc
, doTCP
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
)); /// only works pre-startup, so no sync necessary
503 catch(std::exception
& e
) {
504 g_outputBuffer
="Error: "+string(e
.what())+"\n";
508 g_lua
.writeFunction("addLocal", [client
](const std::string
& addr
, boost::optional
<localbind_t
> vars
) {
512 if (g_configurationDone
) {
513 g_outputBuffer
="addLocal cannot be used at runtime!\n";
517 bool reusePort
= false;
518 int tcpFastOpenQueueSize
= 0;
519 std::string interface
;
522 parseLocalBindVars(vars
, doTCP
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
);
525 ComboAddress
loc(addr
, 53);
526 g_locals
.push_back(std::make_tuple(loc
, doTCP
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
)); /// only works pre-startup, so no sync necessary
528 catch(std::exception
& e
) {
529 g_outputBuffer
="Error: "+string(e
.what())+"\n";
533 g_lua
.writeFunction("setACL", [](boost::variant
<string
,vector
<pair
<int, string
>>> inp
) {
536 if(auto str
= boost::get
<string
>(&inp
)) {
539 else for(const auto& p
: boost::get
<vector
<pair
<int,string
>>>(inp
)) {
540 nmg
.addMask(p
.second
);
545 g_lua
.writeFunction("showACL", []() {
546 setLuaNoSideEffect();
549 g_ACL
.getLocal()->toStringVector(&vec
);
551 for(const auto& s
: vec
)
552 g_outputBuffer
+=s
+"\n";
556 g_lua
.writeFunction("shutdown", []() {
558 sd_notify(0, "STOPPING=1");
559 #endif /* HAVE_SYSTEMD */
561 // Useful for debugging leaks, but might lead to race under load
562 // since other threads are still runing.
563 for(auto& frontend
: g_tlslocals
) {
568 google::protobuf::ShutdownProtobufLibrary();
569 #endif /* HAVE_PROTOBUF */
574 typedef std::unordered_map
<std::string
, boost::variant
<bool, std::string
> > showserversopts_t
;
576 g_lua
.writeFunction("showServers", [](boost::optional
<showserversopts_t
> vars
) {
577 setLuaNoSideEffect();
578 bool showUUIDs
= false;
580 if (vars
->count("showUUIDs")) {
581 showUUIDs
= boost::get
<bool>((*vars
)["showUUIDs"]);
588 fmt
= boost::format("%1$-3d %15$-36s %2$-20.20s %|62t|%3% %|92t|%4$5s %|88t|%5$7.1f %|103t|%6$7d %|106t|%7$3d %|115t|%8$2d %|117t|%9$10d %|123t|%10$7d %|128t|%11$5.1f %|146t|%12$5.1f %|152t|%13$11d %14%" );
589 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
590 ret
<< (fmt
% "#" % "Name" % "Address" % "State" % "Qps" % "Qlim" % "Ord" % "Wt" % "Queries" % "Drops" % "Drate" % "Lat" % "Outstanding" % "Pools" % "UUID") << endl
;
592 fmt
= boost::format("%1$-3d %2$-20.20s %|25t|%3% %|55t|%4$5s %|51t|%5$7.1f %|66t|%6$7d %|69t|%7$3d %|78t|%8$2d %|80t|%9$10d %|86t|%10$7d %|91t|%11$5.1f %|109t|%12$5.1f %|115t|%13$11d %14%" );
593 ret
<< (fmt
% "#" % "Name" % "Address" % "State" % "Qps" % "Qlim" % "Ord" % "Wt" % "Queries" % "Drops" % "Drate" % "Lat" % "Outstanding" % "Pools") << endl
;
596 uint64_t totQPS
{0}, totQueries
{0}, totDrops
{0};
598 auto states
= g_dstates
.getLocal();
599 for(const auto& s
: *states
) {
600 string status
= s
->getStatus();
602 for(auto& p
: s
->pools
) {
608 ret
<< (fmt
% counter
% s
->name
% s
->remote
.toStringWithPort() %
610 s
->queryLoad
% s
->qps
.getRate() % s
->order
% s
->weight
% s
->queries
.load() % s
->reuseds
.load() % (s
->dropRate
) % (s
->latencyUsec
/1000.0) % s
->outstanding
.load() % pools
% s
->id
) << endl
;
612 ret
<< (fmt
% counter
% s
->name
% s
->remote
.toStringWithPort() %
614 s
->queryLoad
% s
->qps
.getRate() % s
->order
% s
->weight
% s
->queries
.load() % s
->reuseds
.load() % (s
->dropRate
) % (s
->latencyUsec
/1000.0) % s
->outstanding
.load() % pools
) << endl
;
616 totQPS
+= s
->queryLoad
;
617 totQueries
+= s
->queries
.load();
618 totDrops
+= s
->reuseds
.load();
622 ret
<< (fmt
% "All" % "" % "" % ""
624 (double)totQPS
% "" % "" % "" % totQueries
% totDrops
% "" % "" % "" % "" % "" ) << endl
;
626 ret
<< (fmt
% "All" % "" % "" % ""
628 (double)totQPS
% "" % "" % "" % totQueries
% totDrops
% "" % "" % "" % "" ) << endl
;
631 g_outputBuffer
=ret
.str();
632 } catch(std::exception
& e
) {
633 g_outputBuffer
=e
.what();
638 g_lua
.writeFunction("getServers", []() {
639 setLuaNoSideEffect();
640 vector
<pair
<int, std::shared_ptr
<DownstreamState
> > > ret
;
642 for(const auto& s
: g_dstates
.getCopy()) {
643 ret
.push_back(make_pair(count
++, s
));
648 g_lua
.writeFunction("getPoolServers", [](string pool
) {
649 return getDownstreamCandidates(g_pools
.getCopy(), pool
);
652 g_lua
.writeFunction("getServer", [client
](int i
) {
654 return std::make_shared
<DownstreamState
>(ComboAddress());
655 return g_dstates
.getCopy().at(i
);
658 g_lua
.writeFunction("carbonServer", [](const std::string
& address
, boost::optional
<string
> ourName
,
659 boost::optional
<unsigned int> interval
, boost::optional
<string
> namespace_name
,
660 boost::optional
<string
> instance_name
) {
662 auto ours
= g_carbon
.getCopy();
664 ComboAddress(address
, 2003),
665 (namespace_name
&& !namespace_name
->empty()) ? *namespace_name
: "dnsdist",
666 ourName
? *ourName
: "",
667 (instance_name
&& !instance_name
->empty()) ? *instance_name
: "main" ,
668 interval
? *interval
: 30
670 g_carbon
.setState(ours
);
673 g_lua
.writeFunction("webserver", [client
](const std::string
& address
, const std::string
& password
, const boost::optional
<std::string
> apiKey
, const boost::optional
<std::map
<std::string
, std::string
> > customHeaders
) {
677 ComboAddress
local(address
);
679 int sock
= SSocket(local
.sin4
.sin_family
, SOCK_STREAM
, 0);
680 SSetsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, 1);
683 auto launch
=[sock
, local
, password
, apiKey
, customHeaders
]() {
684 setWebserverPassword(password
);
685 setWebserverAPIKey(apiKey
);
686 setWebserverCustomHeaders(customHeaders
);
687 thread
t(dnsdistWebserverThread
, sock
, local
);
691 g_launchWork
->push_back(launch
);
695 catch(std::exception
& e
) {
696 g_outputBuffer
="Unable to bind to webserver socket on " + local
.toStringWithPort() + ": " + e
.what();
697 errlog("Unable to bind to webserver socket on %s: %s", local
.toStringWithPort(), e
.what());
702 typedef std::unordered_map
<std::string
, boost::variant
<std::string
, std::map
<std::string
, std::string
>> > webserveropts_t
;
704 g_lua
.writeFunction("setWebserverConfig", [](boost::optional
<webserveropts_t
> vars
) {
710 if(vars
->count("password")) {
711 const std::string password
= boost::get
<std::string
>(vars
->at("password"));
713 setWebserverPassword(password
);
715 if(vars
->count("apiKey")) {
716 const std::string apiKey
= boost::get
<std::string
>(vars
->at("apiKey"));
718 setWebserverAPIKey(apiKey
);
720 if(vars
->count("customHeaders")) {
721 const boost::optional
<std::map
<std::string
, std::string
> > headers
= boost::get
<std::map
<std::string
, std::string
> >(vars
->at("customHeaders"));
723 setWebserverCustomHeaders(headers
);
727 g_lua
.writeFunction("controlSocket", [client
](const std::string
& str
) {
729 ComboAddress
local(str
, 5199);
732 g_serverControl
= local
;
736 g_consoleEnabled
= true;
737 #ifdef HAVE_LIBSODIUM
738 if (g_configurationDone
&& g_consoleKey
.empty()) {
739 warnlog("Warning, the console has been enabled via 'controlSocket()' but no key has been set with 'setKey()' so all connections will fail until a key has been set");
744 int sock
= SSocket(local
.sin4
.sin_family
, SOCK_STREAM
, 0);
745 SSetsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, 1);
748 auto launch
=[sock
, local
]() {
749 thread
t(controlThread
, sock
, local
);
753 g_launchWork
->push_back(launch
);
758 catch(std::exception
& e
) {
759 g_outputBuffer
="Unable to bind to control socket on " + local
.toStringWithPort() + ": " + e
.what();
760 errlog("Unable to bind to control socket on %s: %s", local
.toStringWithPort(), e
.what());
764 g_lua
.writeFunction("addConsoleACL", [](const std::string
& netmask
) {
766 #ifndef HAVE_LIBSODIUM
767 warnlog("Allowing remote access to the console while libsodium support has not been enabled is not secure, and will result in cleartext communications");
770 g_consoleACL
.modify([netmask
](NetmaskGroup
& nmg
) { nmg
.addMask(netmask
); });
773 g_lua
.writeFunction("setConsoleACL", [](boost::variant
<string
,vector
<pair
<int, string
>>> inp
) {
776 #ifndef HAVE_LIBSODIUM
777 warnlog("Allowing remote access to the console while libsodium support has not been enabled is not secure, and will result in cleartext communications");
781 if(auto str
= boost::get
<string
>(&inp
)) {
784 else for(const auto& p
: boost::get
<vector
<pair
<int,string
>>>(inp
)) {
785 nmg
.addMask(p
.second
);
787 g_consoleACL
.setState(nmg
);
790 g_lua
.writeFunction("showConsoleACL", []() {
791 setLuaNoSideEffect();
793 #ifndef HAVE_LIBSODIUM
794 warnlog("Allowing remote access to the console while libsodium support has not been enabled is not secure, and will result in cleartext communications");
798 g_consoleACL
.getLocal()->toStringVector(&vec
);
800 for(const auto& s
: vec
) {
801 g_outputBuffer
+= s
+ "\n";
805 g_lua
.writeFunction("clearQueryCounters", []() {
806 unsigned int size
{0};
808 WriteLock
wl(&g_qcount
.queryLock
);
809 size
= g_qcount
.records
.size();
810 g_qcount
.records
.clear();
813 boost::format
fmt("%d records cleared from query counter buffer\n");
814 g_outputBuffer
= (fmt
% size
).str();
817 g_lua
.writeFunction("getQueryCounters", [](boost::optional
<unsigned int> optMax
) {
818 setLuaNoSideEffect();
819 ReadLock
rl(&g_qcount
.queryLock
);
820 g_outputBuffer
= "query counting is currently: ";
821 g_outputBuffer
+= g_qcount
.enabled
? "enabled" : "disabled";
822 g_outputBuffer
+= (boost::format(" (%d records in buffer)\n") % g_qcount
.records
.size()).str();
824 boost::format
fmt("%-3d %s: %d request(s)\n");
825 QueryCountRecords::iterator it
;
826 unsigned int max
= optMax
? *optMax
: 10;
827 unsigned int index
{1};
828 for(it
= g_qcount
.records
.begin(); it
!= g_qcount
.records
.end() && index
<= max
; ++it
, ++index
) {
829 g_outputBuffer
+= (fmt
% index
% it
->first
% it
->second
).str();
833 g_lua
.writeFunction("setQueryCount", [](bool enabled
) { g_qcount
.enabled
=enabled
; });
835 g_lua
.writeFunction("setQueryCountFilter", [](QueryCountFilter func
) {
836 g_qcount
.filter
= func
;
839 g_lua
.writeFunction("makeKey", []() {
840 setLuaNoSideEffect();
841 g_outputBuffer
="setKey("+newKey()+")\n";
844 g_lua
.writeFunction("setKey", [](const std::string
& key
) {
845 if(!g_configurationDone
&& ! g_consoleKey
.empty()) { // this makes sure the commandline -k key prevails over dnsdist.conf
846 return; // but later setKeys() trump the -k value again
848 #ifndef HAVE_LIBSODIUM
849 warnlog("Calling setKey() while libsodium support has not been enabled is not secure, and will result in cleartext communications");
854 if(B64Decode(key
, newkey
) < 0) {
855 g_outputBuffer
=string("Unable to decode ")+key
+" as Base64";
856 errlog("%s", g_outputBuffer
);
862 g_lua
.writeFunction("testCrypto", [](boost::optional
<string
> optTestMsg
)
864 setLuaNoSideEffect();
865 #ifdef HAVE_LIBSODIUM
870 testmsg
= *optTestMsg
;
873 testmsg
= "testStringForCryptoTests";
879 string encrypted
= sodEncryptSym(testmsg
, g_consoleKey
, sn
);
880 string decrypted
= sodDecryptSym(encrypted
, g_consoleKey
, sn2
);
885 encrypted
= sodEncryptSym(testmsg
, g_consoleKey
, sn
);
886 decrypted
= sodDecryptSym(encrypted
, g_consoleKey
, sn2
);
888 if(testmsg
== decrypted
)
889 g_outputBuffer
="Everything is ok!\n";
891 g_outputBuffer
="Crypto failed..\n";
895 g_outputBuffer
="Crypto failed..\n";
898 g_outputBuffer
="Crypto not available.\n";
902 g_lua
.writeFunction("setTCPRecvTimeout", [](int timeout
) { g_tcpRecvTimeout
=timeout
; });
904 g_lua
.writeFunction("setTCPSendTimeout", [](int timeout
) { g_tcpSendTimeout
=timeout
; });
906 g_lua
.writeFunction("setUDPTimeout", [](int timeout
) { g_udpTimeout
=timeout
; });
908 g_lua
.writeFunction("setMaxUDPOutstanding", [](uint16_t max
) {
909 if (!g_configurationDone
) {
910 g_maxOutstanding
= max
;
912 g_outputBuffer
="Max UDP outstanding cannot be altered at runtime!\n";
916 g_lua
.writeFunction("setMaxTCPClientThreads", [](uint64_t max
) {
917 if (!g_configurationDone
) {
918 g_maxTCPClientThreads
= max
;
920 g_outputBuffer
="Maximum TCP client threads count cannot be altered at runtime!\n";
924 g_lua
.writeFunction("setMaxTCPQueuedConnections", [](uint64_t max
) {
925 if (!g_configurationDone
) {
926 g_maxTCPQueuedConnections
= max
;
928 g_outputBuffer
="The maximum number of queued TCP connections cannot be altered at runtime!\n";
932 g_lua
.writeFunction("setMaxTCPQueriesPerConnection", [](size_t max
) {
933 if (!g_configurationDone
) {
934 g_maxTCPQueriesPerConn
= max
;
936 g_outputBuffer
="The maximum number of queries per TCP connection cannot be altered at runtime!\n";
940 g_lua
.writeFunction("setMaxTCPConnectionsPerClient", [](size_t max
) {
941 if (!g_configurationDone
) {
942 g_maxTCPConnectionsPerClient
= max
;
944 g_outputBuffer
="The maximum number of TCP connection per client cannot be altered at runtime!\n";
948 g_lua
.writeFunction("setMaxTCPConnectionDuration", [](size_t max
) {
949 if (!g_configurationDone
) {
950 g_maxTCPConnectionDuration
= max
;
952 g_outputBuffer
="The maximum duration of a TCP connection cannot be altered at runtime!\n";
956 g_lua
.writeFunction("setCacheCleaningDelay", [](uint32_t delay
) { g_cacheCleaningDelay
= delay
; });
958 g_lua
.writeFunction("setCacheCleaningPercentage", [](uint16_t percentage
) { if (percentage
< 100) g_cacheCleaningPercentage
= percentage
; else g_cacheCleaningPercentage
= 100; });
960 g_lua
.writeFunction("setECSSourcePrefixV4", [](uint16_t prefix
) { g_ECSSourcePrefixV4
=prefix
; });
962 g_lua
.writeFunction("setECSSourcePrefixV6", [](uint16_t prefix
) { g_ECSSourcePrefixV6
=prefix
; });
964 g_lua
.writeFunction("setECSOverride", [](bool override
) { g_ECSOverride
=override
; });
966 g_lua
.writeFunction("setPreserveTrailingData", [](bool preserve
) { g_preserveTrailingData
= preserve
; });
968 g_lua
.writeFunction("showDynBlocks", []() {
969 setLuaNoSideEffect();
970 auto slow
= g_dynblockNMG
.getCopy();
973 boost::format
fmt("%-24s %8d %8d %-10s %-20s %s\n");
974 g_outputBuffer
= (fmt
% "What" % "Seconds" % "Blocks" % "Warning" % "Action" % "Reason").str();
975 for(const auto& e
: slow
) {
976 if(now
< e
->second
.until
)
977 g_outputBuffer
+= (fmt
% e
->first
.toString() % (e
->second
.until
.tv_sec
- now
.tv_sec
) % e
->second
.blocks
% (e
->second
.warning
? "true" : "false") % DNSAction::typeToString(e
->second
.action
!= DNSAction::Action::None
? e
->second
.action
: g_dynBlockAction
) % e
->second
.reason
).str();
979 auto slow2
= g_dynblockSMT
.getCopy();
980 slow2
.visit([&now
, &fmt
](const SuffixMatchTree
<DynBlock
>& node
) {
981 if(now
<node
.d_value
.until
) {
983 if(!node
.d_value
.domain
.empty())
984 dom
= node
.d_value
.domain
.toString();
985 g_outputBuffer
+= (fmt
% dom
% (node
.d_value
.until
.tv_sec
- now
.tv_sec
) % node
.d_value
.blocks
% (node
.d_value
.warning
? "true" : "false") % DNSAction::typeToString(node
.d_value
.action
!= DNSAction::Action::None
? node
.d_value
.action
: g_dynBlockAction
) % node
.d_value
.reason
).str();
991 g_lua
.writeFunction("clearDynBlocks", []() {
994 g_dynblockNMG
.setState(nmg
);
995 SuffixMatchTree
<DynBlock
> smt
;
996 g_dynblockSMT
.setState(smt
);
999 g_lua
.writeFunction("addDynBlocks",
1000 [](const std::unordered_map
<ComboAddress
,unsigned int, ComboAddress::addressOnlyHash
, ComboAddress::addressOnlyEqual
>& m
, const std::string
& msg
, boost::optional
<int> seconds
, boost::optional
<DNSAction::Action
> action
) {
1005 auto slow
= g_dynblockNMG
.getCopy();
1006 struct timespec until
, now
;
1009 int actualSeconds
= seconds
? *seconds
: 10;
1010 until
.tv_sec
+= actualSeconds
;
1011 for(const auto& capair
: m
) {
1012 unsigned int count
= 0;
1013 auto got
= slow
.lookup(Netmask(capair
.first
));
1016 if(until
< got
->second
.until
) // had a longer policy
1018 if(now
< got
->second
.until
) // only inherit count on fresh query we are extending
1019 count
=got
->second
.blocks
;
1023 DynBlock db
{msg
,until
,DNSName(),(action
? *action
: DNSAction::Action::None
)};
1026 warnlog("Inserting dynamic block for %s for %d seconds: %s", capair
.first
.toString(), actualSeconds
, msg
);
1027 slow
.insert(Netmask(capair
.first
)).second
=db
;
1029 g_dynblockNMG
.setState(slow
);
1032 g_lua
.writeFunction("addDynBlockSMT",
1033 [](const vector
<pair
<unsigned int, string
> >&names
, const std::string
& msg
, boost::optional
<int> seconds
, boost::optional
<DNSAction::Action
> action
) {
1034 if (names
.empty()) {
1038 auto slow
= g_dynblockSMT
.getCopy();
1039 struct timespec until
, now
;
1042 int actualSeconds
= seconds
? *seconds
: 10;
1043 until
.tv_sec
+= actualSeconds
;
1045 for(const auto& capair
: names
) {
1046 unsigned int count
= 0;
1047 DNSName
domain(capair
.second
);
1048 auto got
= slow
.lookup(domain
);
1051 if(until
< got
->until
) // had a longer policy
1053 if(now
< got
->until
) // only inherit count on fresh query we are extending
1059 DynBlock db
{msg
,until
,domain
,(action
? *action
: DNSAction::Action::None
)};
1062 warnlog("Inserting dynamic block for %s for %d seconds: %s", domain
, actualSeconds
, msg
);
1063 slow
.add(domain
, db
);
1065 g_dynblockSMT
.setState(slow
);
1068 g_lua
.writeFunction("setDynBlocksAction", [](DNSAction::Action action
) {
1069 if (!g_configurationDone
) {
1070 if (action
== DNSAction::Action::Drop
|| action
== DNSAction::Action::NoOp
|| action
== DNSAction::Action::Nxdomain
|| action
== DNSAction::Action::Refused
|| action
== DNSAction::Action::Truncate
|| action
== DNSAction::Action::NoRecurse
) {
1071 g_dynBlockAction
= action
;
1074 errlog("Dynamic blocks action can only be Drop, NoOp, NXDomain, Refused, Truncate or NoRecurse!");
1075 g_outputBuffer
="Dynamic blocks action can only be Drop, NoOp, NXDomain, Refused, Truncate or NoRecurse!\n";
1078 g_outputBuffer
="Dynamic blocks action cannot be altered at runtime!\n";
1082 g_lua
.writeFunction("addDNSCryptBind", [](const std::string
& addr
, const std::string
& providerName
, const std::string
& certFile
, const std::string keyFile
, boost::optional
<localbind_t
> vars
) {
1083 if (g_configurationDone
) {
1084 g_outputBuffer
="addDNSCryptBind cannot be used at runtime!\n";
1087 #ifdef HAVE_DNSCRYPT
1089 bool reusePort
= false;
1090 int tcpFastOpenQueueSize
= 0;
1091 std::string interface
;
1094 parseLocalBindVars(vars
, doTCP
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
);
1097 auto ctx
= std::make_shared
<DNSCryptContext
>(providerName
, certFile
, keyFile
);
1098 g_dnsCryptLocals
.push_back(std::make_tuple(ComboAddress(addr
, 443), ctx
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
));
1100 catch(std::exception
& e
) {
1102 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1105 g_outputBuffer
="Error: DNSCrypt support is not enabled.\n";
1110 g_lua
.writeFunction("showDNSCryptBinds", []() {
1111 setLuaNoSideEffect();
1112 #ifdef HAVE_DNSCRYPT
1114 boost::format
fmt("%1$-3d %2% %|25t|%3$-20.20s");
1115 ret
<< (fmt
% "#" % "Address" % "Provider Name") << endl
;
1118 for (const auto& local
: g_dnsCryptLocals
) {
1119 const std::shared_ptr
<DNSCryptContext
> ctx
= std::get
<1>(local
);
1120 ret
<< (fmt
% idx
% std::get
<0>(local
).toStringWithPort() % ctx
->getProviderName()) << endl
;
1124 g_outputBuffer
=ret
.str();
1126 g_outputBuffer
="Error: DNSCrypt support is not enabled.\n";
1130 g_lua
.writeFunction("getDNSCryptBind", [](size_t idx
) {
1131 setLuaNoSideEffect();
1132 #ifdef HAVE_DNSCRYPT
1133 std::shared_ptr
<DNSCryptContext
> ret
= nullptr;
1134 if (idx
< g_dnsCryptLocals
.size()) {
1135 ret
= std::get
<1>(g_dnsCryptLocals
.at(idx
));
1139 g_outputBuffer
="Error: DNSCrypt support is not enabled.\n";
1143 g_lua
.writeFunction("generateDNSCryptProviderKeys", [](const std::string
& publicKeyFile
, const std::string privateKeyFile
) {
1144 setLuaNoSideEffect();
1145 #ifdef HAVE_DNSCRYPT
1146 unsigned char publicKey
[DNSCRYPT_PROVIDER_PUBLIC_KEY_SIZE
];
1147 unsigned char privateKey
[DNSCRYPT_PROVIDER_PRIVATE_KEY_SIZE
];
1148 sodium_mlock(privateKey
, sizeof(privateKey
));
1151 DNSCryptContext::generateProviderKeys(publicKey
, privateKey
);
1153 ofstream
pubKStream(publicKeyFile
);
1154 pubKStream
.write((char*) publicKey
, sizeof(publicKey
));
1157 ofstream
privKStream(privateKeyFile
);
1158 privKStream
.write((char*) privateKey
, sizeof(privateKey
));
1159 privKStream
.close();
1161 g_outputBuffer
="Provider fingerprint is: " + DNSCryptContext::getProviderFingerprint(publicKey
) + "\n";
1163 catch(std::exception
& e
) {
1165 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1168 sodium_memzero(privateKey
, sizeof(privateKey
));
1169 sodium_munlock(privateKey
, sizeof(privateKey
));
1171 g_outputBuffer
="Error: DNSCrypt support is not enabled.\n";
1175 g_lua
.writeFunction("printDNSCryptProviderFingerprint", [](const std::string
& publicKeyFile
) {
1176 setLuaNoSideEffect();
1177 #ifdef HAVE_DNSCRYPT
1178 unsigned char publicKey
[DNSCRYPT_PROVIDER_PUBLIC_KEY_SIZE
];
1181 ifstream
file(publicKeyFile
);
1182 file
.read((char *) &publicKey
, sizeof(publicKey
));
1185 throw std::runtime_error("Invalid dnscrypt provider public key file " + publicKeyFile
);
1188 g_outputBuffer
="Provider fingerprint is: " + DNSCryptContext::getProviderFingerprint(publicKey
) + "\n";
1190 catch(std::exception
& e
) {
1192 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1195 g_outputBuffer
="Error: DNSCrypt support is not enabled.\n";
1199 #ifdef HAVE_DNSCRYPT
1200 g_lua
.writeFunction("generateDNSCryptCertificate", [](const std::string
& providerPrivateKeyFile
, const std::string
& certificateFile
, const std::string privateKeyFile
, uint32_t serial
, time_t begin
, time_t end
, boost::optional
<DNSCryptExchangeVersion
> version
) {
1201 setLuaNoSideEffect();
1202 DNSCryptPrivateKey privateKey
;
1206 if (generateDNSCryptCertificate(providerPrivateKeyFile
, serial
, begin
, end
, version
? *version
: DNSCryptExchangeVersion::VERSION1
, cert
, privateKey
)) {
1207 privateKey
.saveToFile(privateKeyFile
);
1208 DNSCryptContext::saveCertFromFile(cert
, certificateFile
);
1211 catch(const std::exception
& e
) {
1213 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1218 g_lua
.writeFunction("showPools", []() {
1219 setLuaNoSideEffect();
1222 boost::format
fmt("%1$-20.20s %|25t|%2$20s %|25t|%3$20s %|50t|%4%" );
1224 ret
<< (fmt
% "Name" % "Cache" % "ServerPolicy" % "Servers" ) << endl
;
1226 const auto localPools
= g_pools
.getCopy();
1227 for (const auto& entry
: localPools
) {
1228 const string
& name
= entry
.first
;
1229 const std::shared_ptr
<ServerPool
> pool
= entry
.second
;
1230 string cache
= pool
->packetCache
!= nullptr ? pool
->packetCache
->toString() : "";
1231 string policy
= g_policy
.getLocal()->name
;
1232 if (pool
->policy
!= nullptr) {
1233 policy
= pool
->policy
->name
;
1237 for (const auto& server
: pool
->getServers()) {
1238 if (!servers
.empty()) {
1241 if (!server
.second
->name
.empty()) {
1242 servers
+= server
.second
->name
;
1245 servers
+= server
.second
->remote
.toStringWithPort();
1248 ret
<< (fmt
% name
% cache
% policy
% servers
) << endl
;
1250 g_outputBuffer
=ret
.str();
1251 }catch(std::exception
& e
) { g_outputBuffer
=e
.what(); throw; }
1254 g_lua
.writeFunction("getPool", [client
](const string
& poolName
) {
1256 return std::make_shared
<ServerPool
>();
1258 auto localPools
= g_pools
.getCopy();
1259 std::shared_ptr
<ServerPool
> pool
= createPoolIfNotExists(localPools
, poolName
);
1260 g_pools
.setState(localPools
);
1264 g_lua
.writeFunction("setVerboseHealthChecks", [](bool verbose
) { g_verboseHealthChecks
=verbose
; });
1265 g_lua
.writeFunction("setStaleCacheEntriesTTL", [](uint32_t ttl
) { g_staleCacheEntriesTTL
= ttl
; });
1267 g_lua
.writeFunction("showBinds", []() {
1268 setLuaNoSideEffect();
1271 boost::format
fmt("%1$-3d %2$-20.20s %|35t|%3$-20.20s %|57t|%4%" );
1273 ret
<< (fmt
% "#" % "Address" % "Protocol" % "Queries" ) << endl
;
1276 for (const auto& front
: g_frontends
) {
1277 ret
<< (fmt
% counter
% front
->local
.toStringWithPort() % front
->getType() % front
->queries
) << endl
;
1280 g_outputBuffer
=ret
.str();
1281 }catch(std::exception
& e
) { g_outputBuffer
=e
.what(); throw; }
1284 g_lua
.writeFunction("getBind", [](size_t num
) {
1285 setLuaNoSideEffect();
1286 ClientState
* ret
= nullptr;
1287 if(num
< g_frontends
.size()) {
1288 ret
=g_frontends
[num
];
1293 g_lua
.writeFunction("help", [](boost::optional
<std::string
> command
) {
1294 setLuaNoSideEffect();
1295 g_outputBuffer
= "";
1296 for (const auto& keyword
: g_consoleKeywords
) {
1298 g_outputBuffer
+= keyword
.toString() + "\n";
1300 else if (keyword
.name
== command
) {
1301 g_outputBuffer
= keyword
.toString() + "\n";
1306 g_outputBuffer
= "Nothing found for " + *command
+ "\n";
1310 g_lua
.writeFunction("showVersion", []() {
1311 setLuaNoSideEffect();
1312 g_outputBuffer
= "dnsdist " + std::string(VERSION
) + "\n";
1315 g_lua
.writeFunction("showSecurityStatus", []() {
1316 setLuaNoSideEffect();
1317 g_outputBuffer
= std::to_string(g_stats
.securityStatus
) + "\n";
1321 g_lua
.writeFunction("setDefaultBPFFilter", [](std::shared_ptr
<BPFFilter
> bpf
) {
1322 if (g_configurationDone
) {
1323 g_outputBuffer
="setDefaultBPFFilter() cannot be used at runtime!\n";
1326 g_defaultBPFFilter
= bpf
;
1329 g_lua
.writeFunction("registerDynBPFFilter", [](std::shared_ptr
<DynBPFFilter
> dbpf
) {
1331 g_dynBPFFilters
.push_back(dbpf
);
1335 g_lua
.writeFunction("unregisterDynBPFFilter", [](std::shared_ptr
<DynBPFFilter
> dbpf
) {
1337 for (auto it
= g_dynBPFFilters
.begin(); it
!= g_dynBPFFilters
.end(); it
++) {
1339 g_dynBPFFilters
.erase(it
);
1346 g_lua
.writeFunction("addBPFFilterDynBlocks", [](const std::unordered_map
<ComboAddress
,unsigned int, ComboAddress::addressOnlyHash
, ComboAddress::addressOnlyEqual
>& m
, std::shared_ptr
<DynBPFFilter
> dynbpf
, boost::optional
<int> seconds
, boost::optional
<std::string
> msg
) {
1348 struct timespec until
, now
;
1349 clock_gettime(CLOCK_MONOTONIC
, &now
);
1351 int actualSeconds
= seconds
? *seconds
: 10;
1352 until
.tv_sec
+= actualSeconds
;
1353 for(const auto& capair
: m
) {
1354 if (dynbpf
->block(capair
.first
, until
)) {
1355 warnlog("Inserting eBPF dynamic block for %s for %d seconds: %s", capair
.first
.toString(), actualSeconds
, msg
? *msg
: "");
1360 #endif /* HAVE_EBPF */
1362 g_lua
.writeFunction
<std::unordered_map
<string
,uint64_t>()>("getStatisticsCounters", []() {
1363 setLuaNoSideEffect();
1364 std::unordered_map
<string
,uint64_t> res
;
1365 for(const auto& entry
: g_stats
.entries
) {
1366 if(const auto& val
= boost::get
<DNSDistStats::stat_t
*>(&entry
.second
))
1367 res
[entry
.first
] = (*val
)->load();
1372 g_lua
.writeFunction("includeDirectory", [](const std::string
& dirname
) {
1373 if (g_configurationDone
) {
1374 errlog("includeDirectory() cannot be used at runtime!");
1375 g_outputBuffer
="includeDirectory() cannot be used at runtime!\n";
1380 errlog("includeDirectory() cannot be used recursively!");
1381 g_outputBuffer
="includeDirectory() cannot be used recursively!\n";
1387 if (stat(dirname
.c_str(), &st
)) {
1388 errlog("The included directory %s does not exist!", dirname
.c_str());
1389 g_outputBuffer
="The included directory " + dirname
+ " does not exist!";
1393 if (!S_ISDIR(st
.st_mode
)) {
1394 errlog("The included directory %s is not a directory!", dirname
.c_str());
1395 g_outputBuffer
="The included directory " + dirname
+ " is not a directory!";
1401 std::list
<std::string
> files
;
1402 if (!(dirp
= opendir(dirname
.c_str()))) {
1403 errlog("Error opening the included directory %s!", dirname
.c_str());
1404 g_outputBuffer
="Error opening the included directory " + dirname
+ "!";
1408 while((ent
= readdir(dirp
)) != NULL
) {
1409 if (ent
->d_name
[0] == '.') {
1413 if (boost::ends_with(ent
->d_name
, ".conf")) {
1414 std::ostringstream namebuf
;
1415 namebuf
<< dirname
.c_str() << "/" << ent
->d_name
;
1417 if (stat(namebuf
.str().c_str(), &st
) || !S_ISREG(st
.st_mode
)) {
1421 files
.push_back(namebuf
.str());
1428 for (auto file
= files
.begin(); file
!= files
.end(); ++file
) {
1429 std::ifstream
ifs(*file
);
1431 warnlog("Unable to read configuration from '%s'", *file
);
1433 vinfolog("Read configuration from '%s'", *file
);
1436 g_lua
.executeCode(ifs
);
1442 g_lua
.writeFunction("setAPIWritable", [](bool writable
, boost::optional
<std::string
> apiConfigDir
) {
1444 g_apiReadWrite
= writable
;
1446 if (!(*apiConfigDir
).empty()) {
1447 g_apiConfigDirectory
= *apiConfigDir
;
1450 errlog("The API configuration directory value cannot be empty!");
1451 g_outputBuffer
="The API configuration directory value cannot be empty!";
1456 g_lua
.writeFunction("setServFailWhenNoServer", [](bool servfail
) {
1458 g_servFailOnNoPolicy
= servfail
;
1461 g_lua
.writeFunction("setRingBuffersSize", [](size_t capacity
, boost::optional
<size_t> numberOfShards
) {
1463 if (g_configurationDone
) {
1464 errlog("setRingBuffersSize() cannot be used at runtime!");
1465 g_outputBuffer
="setRingBuffersSize() cannot be used at runtime!\n";
1468 g_rings
.setCapacity(capacity
, numberOfShards
? *numberOfShards
: 1);
1471 g_lua
.writeFunction("setRingBuffersLockRetries", [](size_t retries
) {
1473 g_rings
.setNumberOfLockRetries(retries
);
1476 g_lua
.writeFunction("setWHashedPertubation", [](uint32_t pertub
) {
1478 g_hashperturb
= pertub
;
1481 g_lua
.writeFunction("setTCPUseSinglePipe", [](bool flag
) {
1482 if (g_configurationDone
) {
1483 g_outputBuffer
="setTCPUseSinglePipe() cannot be used at runtime!\n";
1487 g_useTCPSinglePipe
= flag
;
1490 g_lua
.writeFunction("snmpAgent", [client
](bool enableTraps
, boost::optional
<std::string
> masterSocket
) {
1493 #ifdef HAVE_NET_SNMP
1494 if (g_configurationDone
) {
1495 errlog("snmpAgent() cannot be used at runtime!");
1496 g_outputBuffer
="snmpAgent() cannot be used at runtime!\n";
1500 if (g_snmpEnabled
) {
1501 errlog("snmpAgent() cannot be used twice!");
1502 g_outputBuffer
="snmpAgent() cannot be used twice!\n";
1506 g_snmpEnabled
= true;
1507 g_snmpTrapsEnabled
= enableTraps
;
1508 g_snmpAgent
= new DNSDistSNMPAgent("dnsdist", masterSocket
? *masterSocket
: std::string());
1510 errlog("NET SNMP support is required to use snmpAgent()");
1511 g_outputBuffer
="NET SNMP support is required to use snmpAgent()\n";
1512 #endif /* HAVE_NET_SNMP */
1515 g_lua
.writeFunction("sendCustomTrap", [](const std::string
& str
) {
1516 #ifdef HAVE_NET_SNMP
1517 if (g_snmpAgent
&& g_snmpTrapsEnabled
) {
1518 g_snmpAgent
->sendCustomTrap(str
);
1520 #endif /* HAVE_NET_SNMP */
1523 g_lua
.writeFunction("setPoolServerPolicy", [](ServerPolicy policy
, string pool
) {
1525 auto localPools
= g_pools
.getCopy();
1526 setPoolPolicy(localPools
, pool
, std::make_shared
<ServerPolicy
>(policy
));
1527 g_pools
.setState(localPools
);
1530 g_lua
.writeFunction("setPoolServerPolicyLua", [](string name
, policyfunc_t policy
, string pool
) {
1532 auto localPools
= g_pools
.getCopy();
1533 setPoolPolicy(localPools
, pool
, std::make_shared
<ServerPolicy
>(ServerPolicy
{name
, policy
, true}));
1534 g_pools
.setState(localPools
);
1537 g_lua
.writeFunction("showPoolServerPolicy", [](string pool
) {
1539 auto localPools
= g_pools
.getCopy();
1540 auto poolObj
= getPool(localPools
, pool
);
1541 if (poolObj
->policy
== nullptr) {
1542 g_outputBuffer
=g_policy
.getLocal()->name
+"\n";
1544 g_outputBuffer
=poolObj
->policy
->name
+"\n";
1548 g_lua
.writeFunction("setTCPDownstreamCleanupInterval", [](uint16_t interval
) {
1550 g_downstreamTCPCleanupInterval
= interval
;
1553 g_lua
.writeFunction("setConsoleConnectionsLogging", [](bool enabled
) {
1554 g_logConsoleConnections
= enabled
;
1557 g_lua
.writeFunction("setConsoleOutputMaxMsgSize", [](uint32_t size
) {
1558 g_consoleOutputMsgMaxSize
= size
;
1561 g_lua
.writeFunction("setUDPMultipleMessagesVectorSize", [](size_t vSize
) {
1562 if (g_configurationDone
) {
1563 errlog("setUDPMultipleMessagesVectorSize() cannot be used at runtime!");
1564 g_outputBuffer
="setUDPMultipleMessagesVectorSize() cannot be used at runtime!\n";
1567 #if defined(HAVE_RECVMMSG) && defined(HAVE_SENDMMSG) && defined(MSG_WAITFORONE)
1569 g_udpVectorSize
= vSize
;
1571 errlog("recvmmsg() support is not available!");
1572 g_outputBuffer
="recvmmsg support is not available!\n";
1576 g_lua
.writeFunction("setAddEDNSToSelfGeneratedResponses", [](bool add
) {
1577 g_addEDNSToSelfGeneratedResponses
= add
;
1580 g_lua
.writeFunction("setPayloadSizeOnSelfGeneratedAnswers", [](uint16_t payloadSize
) {
1581 if (payloadSize
< 512) {
1582 warnlog("setPayloadSizeOnSelfGeneratedAnswers() is set too low, using 512 instead!");
1583 g_outputBuffer
="setPayloadSizeOnSelfGeneratedAnswers() is set too low, using 512 instead!";
1586 if (payloadSize
> s_udpIncomingBufferSize
) {
1587 warnlog("setPayloadSizeOnSelfGeneratedAnswers() is set too high, capping to %d instead!", s_udpIncomingBufferSize
);
1588 g_outputBuffer
="setPayloadSizeOnSelfGeneratedAnswers() is set too high, capping to " + std::to_string(s_udpIncomingBufferSize
) + " instead";
1589 payloadSize
= s_udpIncomingBufferSize
;
1591 g_PayloadSizeSelfGenAnswers
= payloadSize
;
1594 g_lua
.writeFunction("setSecurityPollSuffix", [](const std::string
& suffix
) {
1595 if (g_configurationDone
) {
1596 g_outputBuffer
="setSecurityPollSuffix() cannot be used at runtime!\n";
1600 g_secPollSuffix
= suffix
;
1603 g_lua
.writeFunction("setSecurityPollInterval", [](time_t newInterval
) {
1604 if (newInterval
<= 0) {
1605 warnlog("setSecurityPollInterval() should be > 0, skipping");
1606 g_outputBuffer
="setSecurityPollInterval() should be > 0, skipping";
1609 g_secPollInterval
= newInterval
;
1612 g_lua
.writeFunction("setSyslogFacility", [](int facility
) {
1614 if (g_configurationDone
) {
1615 g_outputBuffer
="setSyslogFacility cannot be used at runtime!\n";
1618 setSyslogFacility(facility
);
1621 g_lua
.writeFunction("addTLSLocal", [client
](const std::string
& addr
, boost::variant
<std::string
, std::vector
<std::pair
<int,std::string
>>> certFiles
, boost::variant
<std::string
, std::vector
<std::pair
<int,std::string
>>> keyFiles
, boost::optional
<localbind_t
> vars
) {
1624 #ifdef HAVE_DNS_OVER_TLS
1626 if (g_configurationDone
) {
1627 g_outputBuffer
="addTLSLocal cannot be used at runtime!\n";
1630 shared_ptr
<TLSFrontend
> frontend
= std::make_shared
<TLSFrontend
>();
1632 if (!loadTLSCertificateAndKeys(frontend
, certFiles
, keyFiles
)) {
1638 parseLocalBindVars(vars
, doTCP
, frontend
->d_reusePort
, frontend
->d_tcpFastOpenQueueSize
, frontend
->d_interface
, frontend
->d_cpus
);
1640 if (vars
->count("provider")) {
1641 frontend
->d_provider
= boost::get
<const string
>((*vars
)["provider"]);
1644 if (vars
->count("ciphers")) {
1645 frontend
->d_ciphers
= boost::get
<const string
>((*vars
)["ciphers"]);
1648 if (vars
->count("ticketKeyFile")) {
1649 frontend
->d_ticketKeyFile
= boost::get
<const string
>((*vars
)["ticketKeyFile"]);
1652 if (vars
->count("ticketsKeysRotationDelay")) {
1653 frontend
->d_ticketsKeyRotationDelay
= boost::get
<int>((*vars
)["ticketsKeysRotationDelay"]);
1656 if (vars
->count("numberOfTicketsKeys")) {
1657 frontend
->d_numberOfTicketsKeys
= boost::get
<int>((*vars
)["numberOfTicketsKeys"]);
1660 if (vars
->count("sessionTickets")) {
1661 frontend
->d_enableTickets
= boost::get
<bool>((*vars
)["sessionTickets"]);
1664 if (vars
->count("numberOfStoredSessions")) {
1665 auto value
= boost::get
<int>((*vars
)["numberOfStoredSessions"]);
1667 errlog("Invalid value '%d' for addTLSLocal() parameter 'numberOfStoredSessions', should be >= 0, dismissing", value
);
1668 g_outputBuffer
="Invalid value '" + std::to_string(value
) + "' for addTLSLocal() parameter 'numberOfStoredSessions', should be >= 0, dimissing";
1671 frontend
->d_maxStoredSessions
= value
;
1676 frontend
->d_addr
= ComboAddress(addr
, 853);
1677 vinfolog("Loading TLS provider %s", frontend
->d_provider
);
1678 g_tlslocals
.push_back(frontend
); /// only works pre-startup, so no sync necessary
1680 catch(const std::exception
& e
) {
1681 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1684 g_outputBuffer
="DNS over TLS support is not present!\n";
1688 g_lua
.writeFunction("showTLSContexts", []() {
1689 #ifdef HAVE_DNS_OVER_TLS
1690 setLuaNoSideEffect();
1693 boost::format
fmt("%1$-3d %2$-20.20s %|25t|%3$-14d %|40t|%4$-14d %|54t|%5$-21.21s");
1695 ret
<< (fmt
% "#" % "Address" % "# ticket keys" % "Rotation delay" % "Next rotation" ) << endl
;
1697 for (const auto& ctx
: g_tlslocals
) {
1698 ret
<< (fmt
% counter
% ctx
->d_addr
.toStringWithPort() % ctx
->getTicketsKeysCount() % ctx
->getTicketsKeyRotationDelay() % ctx
->getNextTicketsKeyRotation()) << endl
;
1701 g_outputBuffer
= ret
.str();
1703 catch(const std::exception
& e
) {
1704 g_outputBuffer
= e
.what();
1708 g_outputBuffer
="DNS over TLS support is not present!\n";
1712 g_lua
.writeFunction("getTLSContext", [](size_t index
) {
1713 std::shared_ptr
<TLSCtx
> result
= nullptr;
1714 #ifdef HAVE_DNS_OVER_TLS
1715 setLuaNoSideEffect();
1717 if (index
< g_tlslocals
.size()) {
1718 result
= g_tlslocals
.at(index
)->getContext();
1721 errlog("Error: trying to get TLS context with index %zu but we only have %zu\n", index
, g_tlslocals
.size());
1722 g_outputBuffer
="Error: trying to get TLS context with index " + std::to_string(index
) + " but we only have " + std::to_string(g_tlslocals
.size()) + "\n";
1725 catch(const std::exception
& e
) {
1726 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1727 errlog("Error: %s\n", string(e
.what()));
1730 g_outputBuffer
="DNS over TLS support is not present!\n";
1735 g_lua
.writeFunction("getTLSFrontend", [](size_t index
) {
1736 std::shared_ptr
<TLSFrontend
> result
= nullptr;
1737 #ifdef HAVE_DNS_OVER_TLS
1738 setLuaNoSideEffect();
1740 if (index
< g_tlslocals
.size()) {
1741 result
= g_tlslocals
.at(index
);
1744 errlog("Error: trying to get TLS frontend with index %zu but we only have %zu\n", index
, g_tlslocals
.size());
1745 g_outputBuffer
="Error: trying to get TLS frontend with index " + std::to_string(index
) + " but we only have " + std::to_string(g_tlslocals
.size()) + "\n";
1748 catch(const std::exception
& e
) {
1749 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1750 errlog("Error: %s\n", string(e
.what()));
1753 g_outputBuffer
="DNS over TLS support is not present!\n";
1758 g_lua
.registerFunction
<void(std::shared_ptr
<TLSCtx
>::*)()>("rotateTicketsKey", [](std::shared_ptr
<TLSCtx
> ctx
) {
1759 if (ctx
!= nullptr) {
1760 ctx
->rotateTicketsKey(time(nullptr));
1764 g_lua
.registerFunction
<void(std::shared_ptr
<TLSCtx
>::*)(const std::string
&)>("loadTicketsKeys", [](std::shared_ptr
<TLSCtx
> ctx
, const std::string
& file
) {
1765 if (ctx
!= nullptr) {
1766 ctx
->loadTicketsKeys(file
);
1770 g_lua
.registerFunction
<void(std::shared_ptr
<TLSFrontend
>::*)(boost::variant
<std::string
, std::vector
<std::pair
<int,std::string
>>> certFiles
, boost::variant
<std::string
, std::vector
<std::pair
<int,std::string
>>> keyFiles
)>("loadNewCertificatesAndKeys", [](std::shared_ptr
<TLSFrontend
>& frontend
, boost::variant
<std::string
, std::vector
<std::pair
<int,std::string
>>> certFiles
, boost::variant
<std::string
, std::vector
<std::pair
<int,std::string
>>> keyFiles
) {
1771 #ifdef HAVE_DNS_OVER_TLS
1772 if (loadTLSCertificateAndKeys(frontend
, certFiles
, keyFiles
)) {
1773 frontend
->setupTLS();
1778 g_lua
.writeFunction("setAllowEmptyResponse", [](bool allow
) { g_allowEmptyResponse
=allow
; });
1781 vector
<std::function
<void(void)>> setupLua(bool client
, const std::string
& config
)
1783 g_launchWork
= new vector
<std::function
<void(void)>>();
1786 setupLuaConfig(client
);
1787 setupLuaBindings(client
);
1788 setupLuaBindingsDNSQuestion();
1789 setupLuaInspection();
1793 std::ifstream
ifs(config
);
1795 warnlog("Unable to read configuration from '%s'", config
);
1797 vinfolog("Read configuration from '%s'", config
);
1799 g_lua
.executeCode(ifs
);
1801 auto ret
= *g_launchWork
;
1802 delete g_launchWork
;
1803 g_launchWork
= nullptr;