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"
41 #include "dnswriter.hh"
44 #include "protobuf.hh"
45 #include "sodcrypto.hh"
47 #include <boost/logic/tribool.hpp>
48 #include <boost/lexical_cast.hpp>
51 #include <systemd/sd-daemon.h>
56 static vector
<std::function
<void(void)>>* g_launchWork
= nullptr;
58 boost::tribool g_noLuaSideEffect
;
59 static bool g_included
{false};
61 /* this is a best effort way to prevent logging calls with no side-effects in the output of delta()
62 Functions can declare setLuaNoSideEffect() and if nothing else does declare a side effect, or nothing
63 has done so before on this invocation, this call won't be part of delta() output */
64 void setLuaNoSideEffect()
66 if(g_noLuaSideEffect
==false) // there has been a side effect already
68 g_noLuaSideEffect
=true;
71 void setLuaSideEffect()
73 g_noLuaSideEffect
=false;
76 bool getLuaNoSideEffect()
78 if (g_noLuaSideEffect
) {
84 void resetLuaSideEffect()
86 g_noLuaSideEffect
= boost::logic::indeterminate
;
89 typedef std::unordered_map
<std::string
, boost::variant
<bool, int, std::string
, std::vector
<std::pair
<int,int> > > > localbind_t
;
91 static void parseLocalBindVars(boost::optional
<localbind_t
> vars
, bool& doTCP
, bool& reusePort
, int& tcpFastOpenQueueSize
, std::string
& interface
, std::set
<int>& cpus
)
94 if (vars
->count("doTCP")) {
95 doTCP
= boost::get
<bool>((*vars
)["doTCP"]);
97 if (vars
->count("reusePort")) {
98 reusePort
= boost::get
<bool>((*vars
)["reusePort"]);
100 if (vars
->count("tcpFastOpenQueueSize")) {
101 tcpFastOpenQueueSize
= boost::get
<int>((*vars
)["tcpFastOpenQueueSize"]);
103 if (vars
->count("interface")) {
104 interface
= boost::get
<std::string
>((*vars
)["interface"]);
106 if (vars
->count("cpus")) {
107 for (const auto cpu
: boost::get
<std::vector
<std::pair
<int,int>>>((*vars
)["cpus"])) {
108 cpus
.insert(cpu
.second
);
114 #ifdef HAVE_DNS_OVER_TLS
115 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
)
117 if (certFiles
.type() == typeid(std::string
) && keyFiles
.type() == typeid(std::string
)) {
118 auto certFile
= boost::get
<std::string
>(certFiles
);
119 auto keyFile
= boost::get
<std::string
>(keyFiles
);
120 frontend
->d_certKeyPairs
.clear();
121 frontend
->d_certKeyPairs
.push_back({certFile
, keyFile
});
123 else if (certFiles
.type() == typeid(std::vector
<std::pair
<int,std::string
>>) && keyFiles
.type() == typeid(std::vector
<std::pair
<int,std::string
>>))
125 auto certFilesVect
= boost::get
<std::vector
<std::pair
<int,std::string
>>>(certFiles
);
126 auto keyFilesVect
= boost::get
<std::vector
<std::pair
<int,std::string
>>>(keyFiles
);
127 if (certFilesVect
.size() == keyFilesVect
.size()) {
128 frontend
->d_certKeyPairs
.clear();
129 for (size_t idx
= 0; idx
< certFilesVect
.size(); idx
++) {
130 frontend
->d_certKeyPairs
.push_back({certFilesVect
.at(idx
).second
, keyFilesVect
.at(idx
).second
});
134 errlog("Error, mismatching number of certificates and keys in call to addTLSLocal()!");
135 g_outputBuffer
="Error, mismatching number of certificates and keys in call to addTLSLocal()!";
140 errlog("Error, mismatching number of certificates and keys in call to addTLSLocal()!");
141 g_outputBuffer
="Error, mismatching number of certificates and keys in call to addTLSLocal()!";
147 #endif /* HAVE_DNS_OVER_TLS */
149 void setupLuaConfig(bool client
)
151 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("tcpConnectTimeout")) {
293 ret
->tcpConnectTimeout
=std::stoi(boost::get
<string
>(vars
["tcpConnectTimeout"]));
296 if(vars
.count("tcpSendTimeout")) {
297 ret
->tcpSendTimeout
=std::stoi(boost::get
<string
>(vars
["tcpSendTimeout"]));
300 if(vars
.count("tcpRecvTimeout")) {
301 ret
->tcpRecvTimeout
=std::stoi(boost::get
<string
>(vars
["tcpRecvTimeout"]));
304 if(vars
.count("tcpFastOpen")) {
305 bool fastOpen
= boost::get
<bool>(vars
["tcpFastOpen"]);
308 ret
->tcpFastOpen
=true;
310 warnlog("TCP Fast Open has been configured on downstream server %s but is not supported", boost::get
<string
>(vars
["address"]));
315 if(vars
.count("name")) {
316 ret
->name
=boost::get
<string
>(vars
["name"]);
319 if (vars
.count("id")) {
320 ret
->setId(boost::lexical_cast
<boost::uuids::uuid
>(boost::get
<string
>(vars
["id"])));
323 if(vars
.count("checkName")) {
324 ret
->checkName
=DNSName(boost::get
<string
>(vars
["checkName"]));
327 if(vars
.count("checkType")) {
328 ret
->checkType
=boost::get
<string
>(vars
["checkType"]);
331 if(vars
.count("checkClass")) {
332 ret
->checkClass
=std::stoi(boost::get
<string
>(vars
["checkClass"]));
335 if(vars
.count("checkFunction")) {
336 ret
->checkFunction
= boost::get
<DownstreamState::checkfunc_t
>(vars
["checkFunction"]);
339 if(vars
.count("setCD")) {
340 ret
->setCD
=boost::get
<bool>(vars
["setCD"]);
343 if(vars
.count("mustResolve")) {
344 ret
->mustResolve
=boost::get
<bool>(vars
["mustResolve"]);
347 if(vars
.count("useClientSubnet")) {
348 ret
->useECS
=boost::get
<bool>(vars
["useClientSubnet"]);
351 if(vars
.count("ipBindAddrNoPort")) {
352 ret
->ipBindAddrNoPort
=boost::get
<bool>(vars
["ipBindAddrNoPort"]);
355 if(vars
.count("addXPF")) {
356 ret
->xpfRRCode
=std::stoi(boost::get
<string
>(vars
["addXPF"]));
359 if(vars
.count("maxCheckFailures")) {
360 ret
->maxCheckFailures
=std::stoi(boost::get
<string
>(vars
["maxCheckFailures"]));
363 if(vars
.count("cpus")) {
364 for (const auto cpu
: boost::get
<vector
<pair
<int,string
>>>(vars
["cpus"])) {
365 cpus
.insert(std::stoi(cpu
.second
));
369 /* this needs to be done _AFTER_ the order has been set,
370 since the server are kept ordered inside the pool */
371 auto localPools
= g_pools
.getCopy();
372 if(vars
.count("pool")) {
373 if(auto* pool
= boost::get
<string
>(&vars
["pool"])) {
374 ret
->pools
.insert(*pool
);
377 auto pools
= boost::get
<vector
<pair
<int, string
> > >(vars
["pool"]);
378 for(auto& p
: pools
) {
379 ret
->pools
.insert(p
.second
);
382 for(const auto& poolName
: ret
->pools
) {
383 addServerToPool(localPools
, poolName
, ret
);
387 addServerToPool(localPools
, "", ret
);
389 g_pools
.setState(localPools
);
391 if (ret
->connected
) {
392 ret
->threadStarted
.test_and_set();
395 g_launchWork
->push_back([ret
,cpus
]() {
396 ret
->tid
= thread(responderThread
, ret
);
398 mapThreadToCPUList(ret
->tid
.native_handle(), cpus
);
403 ret
->tid
= thread(responderThread
, ret
);
405 mapThreadToCPUList(ret
->tid
.native_handle(), cpus
);
410 auto states
= g_dstates
.getCopy();
411 states
.push_back(ret
);
412 std::stable_sort(states
.begin(), states
.end(), [](const decltype(ret
)& a
, const decltype(ret
)& b
) {
413 return a
->order
< b
->order
;
415 g_dstates
.setState(states
);
419 g_lua
.writeFunction("rmServer",
420 [](boost::variant
<std::shared_ptr
<DownstreamState
>, int> var
)
423 shared_ptr
<DownstreamState
> server
;
424 auto* rem
= boost::get
<shared_ptr
<DownstreamState
>>(&var
);
425 auto states
= g_dstates
.getCopy();
430 int idx
= boost::get
<int>(var
);
431 server
= states
.at(idx
);
433 auto localPools
= g_pools
.getCopy();
434 for (const string
& poolName
: server
->pools
) {
435 removeServerFromPool(localPools
, poolName
, server
);
437 /* the server might also be in the default pool */
438 removeServerFromPool(localPools
, "", server
);
439 g_pools
.setState(localPools
);
440 states
.erase(remove(states
.begin(), states
.end(), server
), states
.end());
441 g_dstates
.setState(states
);
444 g_lua
.writeFunction("setServerPolicy", [](ServerPolicy policy
) {
446 g_policy
.setState(policy
);
448 g_lua
.writeFunction("setServerPolicyLua", [](string name
, policyfunc_t policy
) {
450 g_policy
.setState(ServerPolicy
{name
, policy
, true});
453 g_lua
.writeFunction("showServerPolicy", []() {
455 g_outputBuffer
=g_policy
.getLocal()->name
+"\n";
458 g_lua
.writeFunction("truncateTC", [](bool tc
) { setLuaSideEffect(); g_truncateTC
=tc
; });
459 g_lua
.writeFunction("fixupCase", [](bool fu
) { setLuaSideEffect(); g_fixupCase
=fu
; });
461 g_lua
.writeFunction("addACL", [](const std::string
& domain
) {
463 g_ACL
.modify([domain
](NetmaskGroup
& nmg
) { nmg
.addMask(domain
); });
466 g_lua
.writeFunction("setLocal", [client
](const std::string
& addr
, boost::optional
<localbind_t
> vars
) {
470 if (g_configurationDone
) {
471 g_outputBuffer
="setLocal cannot be used at runtime!\n";
475 bool reusePort
= false;
476 int tcpFastOpenQueueSize
= 0;
477 std::string interface
;
480 parseLocalBindVars(vars
, doTCP
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
);
483 ComboAddress
loc(addr
, 53);
485 g_locals
.push_back(std::make_tuple(loc
, doTCP
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
)); /// only works pre-startup, so no sync necessary
487 catch(std::exception
& e
) {
488 g_outputBuffer
="Error: "+string(e
.what())+"\n";
492 g_lua
.writeFunction("addLocal", [client
](const std::string
& addr
, boost::optional
<localbind_t
> vars
) {
496 if (g_configurationDone
) {
497 g_outputBuffer
="addLocal cannot be used at runtime!\n";
501 bool reusePort
= false;
502 int tcpFastOpenQueueSize
= 0;
503 std::string interface
;
506 parseLocalBindVars(vars
, doTCP
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
);
509 ComboAddress
loc(addr
, 53);
510 g_locals
.push_back(std::make_tuple(loc
, doTCP
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
)); /// only works pre-startup, so no sync necessary
512 catch(std::exception
& e
) {
513 g_outputBuffer
="Error: "+string(e
.what())+"\n";
517 g_lua
.writeFunction("setACL", [](boost::variant
<string
,vector
<pair
<int, string
>>> inp
) {
520 if(auto str
= boost::get
<string
>(&inp
)) {
523 else for(const auto& p
: boost::get
<vector
<pair
<int,string
>>>(inp
)) {
524 nmg
.addMask(p
.second
);
529 g_lua
.writeFunction("showACL", []() {
530 setLuaNoSideEffect();
533 g_ACL
.getLocal()->toStringVector(&vec
);
535 for(const auto& s
: vec
)
536 g_outputBuffer
+=s
+"\n";
540 g_lua
.writeFunction("shutdown", []() {
542 sd_notify(0, "STOPPING=1");
543 #endif /* HAVE_SYSTEMD */
545 // Useful for debugging leaks, but might lead to race under load
546 // since other threads are still runing.
547 for(auto& frontend
: g_tlslocals
) {
552 google::protobuf::ShutdownProtobufLibrary();
553 #endif /* HAVE_PROTOBUF */
558 g_lua
.writeFunction("showServers", []() {
559 setLuaNoSideEffect();
562 boost::format
fmt("%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%" );
563 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14
564 ret
<< (fmt
% "#" % "Name" % "Address" % "State" % "Qps" % "Qlim" % "Ord" % "Wt" % "Queries" % "Drops" % "Drate" % "Lat" % "Outstanding" % "Pools") << endl
;
566 uint64_t totQPS
{0}, totQueries
{0}, totDrops
{0};
568 auto states
= g_dstates
.getLocal();
569 for(const auto& s
: *states
) {
570 string status
= s
->getStatus();
572 for(auto& p
: s
->pools
) {
578 ret
<< (fmt
% counter
% s
->name
% s
->remote
.toStringWithPort() %
580 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
;
582 totQPS
+= s
->queryLoad
;
583 totQueries
+= s
->queries
.load();
584 totDrops
+= s
->reuseds
.load();
587 ret
<< (fmt
% "All" % "" % "" % ""
589 (double)totQPS
% "" % "" % "" % totQueries
% totDrops
% "" % "" % "" % "" ) << endl
;
591 g_outputBuffer
=ret
.str();
592 }catch(std::exception
& e
) { g_outputBuffer
=e
.what(); throw; }
595 g_lua
.writeFunction("getServers", []() {
596 setLuaNoSideEffect();
597 vector
<pair
<int, std::shared_ptr
<DownstreamState
> > > ret
;
599 for(const auto& s
: g_dstates
.getCopy()) {
600 ret
.push_back(make_pair(count
++, s
));
605 g_lua
.writeFunction("getPoolServers", [](string pool
) {
606 return getDownstreamCandidates(g_pools
.getCopy(), pool
);
609 g_lua
.writeFunction("getServer", [client
](int i
) {
611 return std::make_shared
<DownstreamState
>(ComboAddress());
612 return g_dstates
.getCopy().at(i
);
615 g_lua
.writeFunction("carbonServer", [](const std::string
& address
, boost::optional
<string
> ourName
,
616 boost::optional
<unsigned int> interval
) {
618 auto ours
= g_carbon
.getCopy();
619 ours
.push_back({ComboAddress(address
, 2003), ourName
? *ourName
: "", interval
? *interval
: 30});
620 g_carbon
.setState(ours
);
623 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
) {
627 ComboAddress
local(address
);
629 int sock
= SSocket(local
.sin4
.sin_family
, SOCK_STREAM
, 0);
630 SSetsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, 1);
633 auto launch
=[sock
, local
, password
, apiKey
, customHeaders
]() {
634 thread
t(dnsdistWebserverThread
, sock
, local
, password
, apiKey
? *apiKey
: "", customHeaders
);
638 g_launchWork
->push_back(launch
);
642 catch(std::exception
& e
) {
643 g_outputBuffer
="Unable to bind to webserver socket on " + local
.toStringWithPort() + ": " + e
.what();
644 errlog("Unable to bind to webserver socket on %s: %s", local
.toStringWithPort(), e
.what());
649 g_lua
.writeFunction("controlSocket", [client
](const std::string
& str
) {
651 ComboAddress
local(str
, 5199);
654 g_serverControl
= local
;
658 g_consoleEnabled
= true;
659 #ifdef HAVE_LIBSODIUM
660 if (g_configurationDone
&& g_consoleKey
.empty()) {
661 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");
666 int sock
= SSocket(local
.sin4
.sin_family
, SOCK_STREAM
, 0);
667 SSetsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, 1);
670 auto launch
=[sock
, local
]() {
671 thread
t(controlThread
, sock
, local
);
675 g_launchWork
->push_back(launch
);
680 catch(std::exception
& e
) {
681 g_outputBuffer
="Unable to bind to control socket on " + local
.toStringWithPort() + ": " + e
.what();
682 errlog("Unable to bind to control socket on %s: %s", local
.toStringWithPort(), e
.what());
686 g_lua
.writeFunction("addConsoleACL", [](const std::string
& netmask
) {
688 #ifndef HAVE_LIBSODIUM
689 warnlog("Allowing remote access to the console while libsodium support has not been enabled is not secure, and will result in cleartext communications");
692 g_consoleACL
.modify([netmask
](NetmaskGroup
& nmg
) { nmg
.addMask(netmask
); });
695 g_lua
.writeFunction("setConsoleACL", [](boost::variant
<string
,vector
<pair
<int, string
>>> inp
) {
698 #ifndef HAVE_LIBSODIUM
699 warnlog("Allowing remote access to the console while libsodium support has not been enabled is not secure, and will result in cleartext communications");
703 if(auto str
= boost::get
<string
>(&inp
)) {
706 else for(const auto& p
: boost::get
<vector
<pair
<int,string
>>>(inp
)) {
707 nmg
.addMask(p
.second
);
709 g_consoleACL
.setState(nmg
);
712 g_lua
.writeFunction("showConsoleACL", []() {
713 setLuaNoSideEffect();
715 #ifndef HAVE_LIBSODIUM
716 warnlog("Allowing remote access to the console while libsodium support has not been enabled is not secure, and will result in cleartext communications");
720 g_consoleACL
.getLocal()->toStringVector(&vec
);
722 for(const auto& s
: vec
) {
723 g_outputBuffer
+= s
+ "\n";
727 g_lua
.writeFunction("clearQueryCounters", []() {
728 unsigned int size
{0};
730 WriteLock
wl(&g_qcount
.queryLock
);
731 size
= g_qcount
.records
.size();
732 g_qcount
.records
.clear();
735 boost::format
fmt("%d records cleared from query counter buffer\n");
736 g_outputBuffer
= (fmt
% size
).str();
739 g_lua
.writeFunction("getQueryCounters", [](boost::optional
<unsigned int> optMax
) {
740 setLuaNoSideEffect();
741 ReadLock
rl(&g_qcount
.queryLock
);
742 g_outputBuffer
= "query counting is currently: ";
743 g_outputBuffer
+= g_qcount
.enabled
? "enabled" : "disabled";
744 g_outputBuffer
+= (boost::format(" (%d records in buffer)\n") % g_qcount
.records
.size()).str();
746 boost::format
fmt("%-3d %s: %d request(s)\n");
747 QueryCountRecords::iterator it
;
748 unsigned int max
= optMax
? *optMax
: 10;
749 unsigned int index
{1};
750 for(it
= g_qcount
.records
.begin(); it
!= g_qcount
.records
.end() && index
<= max
; ++it
, ++index
) {
751 g_outputBuffer
+= (fmt
% index
% it
->first
% it
->second
).str();
755 g_lua
.writeFunction("setQueryCount", [](bool enabled
) { g_qcount
.enabled
=enabled
; });
757 g_lua
.writeFunction("setQueryCountFilter", [](QueryCountFilter func
) {
758 g_qcount
.filter
= func
;
761 g_lua
.writeFunction("makeKey", []() {
762 setLuaNoSideEffect();
763 g_outputBuffer
="setKey("+newKey()+")\n";
766 g_lua
.writeFunction("setKey", [](const std::string
& key
) {
767 if(!g_configurationDone
&& ! g_consoleKey
.empty()) { // this makes sure the commandline -k key prevails over dnsdist.conf
768 return; // but later setKeys() trump the -k value again
770 #ifndef HAVE_LIBSODIUM
771 warnlog("Calling setKey() while libsodium support has not been enabled is not secure, and will result in cleartext communications");
776 if(B64Decode(key
, newkey
) < 0) {
777 g_outputBuffer
=string("Unable to decode ")+key
+" as Base64";
778 errlog("%s", g_outputBuffer
);
784 g_lua
.writeFunction("testCrypto", [](boost::optional
<string
> optTestMsg
)
786 setLuaNoSideEffect();
787 #ifdef HAVE_LIBSODIUM
792 testmsg
= *optTestMsg
;
795 testmsg
= "testStringForCryptoTests";
801 string encrypted
= sodEncryptSym(testmsg
, g_consoleKey
, sn
);
802 string decrypted
= sodDecryptSym(encrypted
, g_consoleKey
, sn2
);
807 encrypted
= sodEncryptSym(testmsg
, g_consoleKey
, sn
);
808 decrypted
= sodDecryptSym(encrypted
, g_consoleKey
, sn2
);
810 if(testmsg
== decrypted
)
811 g_outputBuffer
="Everything is ok!\n";
813 g_outputBuffer
="Crypto failed..\n";
817 g_outputBuffer
="Crypto failed..\n";
820 g_outputBuffer
="Crypto not available.\n";
824 g_lua
.writeFunction("setTCPRecvTimeout", [](int timeout
) { g_tcpRecvTimeout
=timeout
; });
826 g_lua
.writeFunction("setTCPSendTimeout", [](int timeout
) { g_tcpSendTimeout
=timeout
; });
828 g_lua
.writeFunction("setUDPTimeout", [](int timeout
) { g_udpTimeout
=timeout
; });
830 g_lua
.writeFunction("setMaxUDPOutstanding", [](uint16_t max
) {
831 if (!g_configurationDone
) {
832 g_maxOutstanding
= max
;
834 g_outputBuffer
="Max UDP outstanding cannot be altered at runtime!\n";
838 g_lua
.writeFunction("setMaxTCPClientThreads", [](uint64_t max
) {
839 if (!g_configurationDone
) {
840 g_maxTCPClientThreads
= max
;
842 g_outputBuffer
="Maximum TCP client threads count cannot be altered at runtime!\n";
846 g_lua
.writeFunction("setMaxTCPQueuedConnections", [](uint64_t max
) {
847 if (!g_configurationDone
) {
848 g_maxTCPQueuedConnections
= max
;
850 g_outputBuffer
="The maximum number of queued TCP connections cannot be altered at runtime!\n";
854 g_lua
.writeFunction("setMaxTCPQueriesPerConnection", [](size_t max
) {
855 if (!g_configurationDone
) {
856 g_maxTCPQueriesPerConn
= max
;
858 g_outputBuffer
="The maximum number of queries per TCP connection cannot be altered at runtime!\n";
862 g_lua
.writeFunction("setMaxTCPConnectionsPerClient", [](size_t max
) {
863 if (!g_configurationDone
) {
864 g_maxTCPConnectionsPerClient
= max
;
866 g_outputBuffer
="The maximum number of TCP connection per client cannot be altered at runtime!\n";
870 g_lua
.writeFunction("setMaxTCPConnectionDuration", [](size_t max
) {
871 if (!g_configurationDone
) {
872 g_maxTCPConnectionDuration
= max
;
874 g_outputBuffer
="The maximum duration of a TCP connection cannot be altered at runtime!\n";
878 g_lua
.writeFunction("setCacheCleaningDelay", [](uint32_t delay
) { g_cacheCleaningDelay
= delay
; });
880 g_lua
.writeFunction("setCacheCleaningPercentage", [](uint16_t percentage
) { if (percentage
< 100) g_cacheCleaningPercentage
= percentage
; else g_cacheCleaningPercentage
= 100; });
882 g_lua
.writeFunction("setECSSourcePrefixV4", [](uint16_t prefix
) { g_ECSSourcePrefixV4
=prefix
; });
884 g_lua
.writeFunction("setECSSourcePrefixV6", [](uint16_t prefix
) { g_ECSSourcePrefixV6
=prefix
; });
886 g_lua
.writeFunction("setECSOverride", [](bool override
) { g_ECSOverride
=override
; });
888 g_lua
.writeFunction("showDynBlocks", []() {
889 setLuaNoSideEffect();
890 auto slow
= g_dynblockNMG
.getCopy();
893 boost::format
fmt("%-24s %8d %8d %-10s %-20s %s\n");
894 g_outputBuffer
= (fmt
% "What" % "Seconds" % "Blocks" % "Warning" % "Action" % "Reason").str();
895 for(const auto& e
: slow
) {
896 if(now
< e
->second
.until
)
897 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();
899 auto slow2
= g_dynblockSMT
.getCopy();
900 slow2
.visit([&now
, &fmt
](const SuffixMatchTree
<DynBlock
>& node
) {
901 if(now
<node
.d_value
.until
) {
903 if(!node
.d_value
.domain
.empty())
904 dom
= node
.d_value
.domain
.toString();
905 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();
911 g_lua
.writeFunction("clearDynBlocks", []() {
914 g_dynblockNMG
.setState(nmg
);
915 SuffixMatchTree
<DynBlock
> smt
;
916 g_dynblockSMT
.setState(smt
);
919 g_lua
.writeFunction("addDynBlocks",
920 [](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
) {
925 auto slow
= g_dynblockNMG
.getCopy();
926 struct timespec until
, now
;
929 int actualSeconds
= seconds
? *seconds
: 10;
930 until
.tv_sec
+= actualSeconds
;
931 for(const auto& capair
: m
) {
932 unsigned int count
= 0;
933 auto got
= slow
.lookup(Netmask(capair
.first
));
936 if(until
< got
->second
.until
) // had a longer policy
938 if(now
< got
->second
.until
) // only inherit count on fresh query we are extending
939 count
=got
->second
.blocks
;
943 DynBlock db
{msg
,until
,DNSName(),(action
? *action
: DNSAction::Action::None
)};
946 warnlog("Inserting dynamic block for %s for %d seconds: %s", capair
.first
.toString(), actualSeconds
, msg
);
947 slow
.insert(Netmask(capair
.first
)).second
=db
;
949 g_dynblockNMG
.setState(slow
);
952 g_lua
.writeFunction("addDynBlockSMT",
953 [](const vector
<pair
<unsigned int, string
> >&names
, const std::string
& msg
, boost::optional
<int> seconds
, boost::optional
<DNSAction::Action
> action
) {
958 auto slow
= g_dynblockSMT
.getCopy();
959 struct timespec until
, now
;
962 int actualSeconds
= seconds
? *seconds
: 10;
963 until
.tv_sec
+= actualSeconds
;
965 for(const auto& capair
: names
) {
966 unsigned int count
= 0;
967 DNSName
domain(capair
.second
);
968 auto got
= slow
.lookup(domain
);
971 if(until
< got
->until
) // had a longer policy
973 if(now
< got
->until
) // only inherit count on fresh query we are extending
979 DynBlock db
{msg
,until
,domain
,(action
? *action
: DNSAction::Action::None
)};
982 warnlog("Inserting dynamic block for %s for %d seconds: %s", domain
, actualSeconds
, msg
);
983 slow
.add(domain
, db
);
985 g_dynblockSMT
.setState(slow
);
988 g_lua
.writeFunction("setDynBlocksAction", [](DNSAction::Action action
) {
989 if (!g_configurationDone
) {
990 if (action
== DNSAction::Action::Drop
|| action
== DNSAction::Action::NoOp
|| action
== DNSAction::Action::Nxdomain
|| action
== DNSAction::Action::Refused
|| action
== DNSAction::Action::Truncate
) {
991 g_dynBlockAction
= action
;
994 errlog("Dynamic blocks action can only be Drop, NoOp, NXDomain, Refused or Truncate!");
995 g_outputBuffer
="Dynamic blocks action can only be Drop, NoOp, NXDomain, Refused or Truncate!\n";
998 g_outputBuffer
="Dynamic blocks action cannot be altered at runtime!\n";
1002 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
) {
1003 if (g_configurationDone
) {
1004 g_outputBuffer
="addDNSCryptBind cannot be used at runtime!\n";
1007 #ifdef HAVE_DNSCRYPT
1009 bool reusePort
= false;
1010 int tcpFastOpenQueueSize
= 0;
1011 std::string interface
;
1014 parseLocalBindVars(vars
, doTCP
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
);
1017 auto ctx
= std::make_shared
<DNSCryptContext
>(providerName
, certFile
, keyFile
);
1018 g_dnsCryptLocals
.push_back(std::make_tuple(ComboAddress(addr
, 443), ctx
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
));
1020 catch(std::exception
& e
) {
1022 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1025 g_outputBuffer
="Error: DNSCrypt support is not enabled.\n";
1030 g_lua
.writeFunction("showDNSCryptBinds", []() {
1031 setLuaNoSideEffect();
1032 #ifdef HAVE_DNSCRYPT
1034 boost::format
fmt("%1$-3d %2% %|25t|%3$-20.20s");
1035 ret
<< (fmt
% "#" % "Address" % "Provider Name") << endl
;
1038 for (const auto& local
: g_dnsCryptLocals
) {
1039 const std::shared_ptr
<DNSCryptContext
> ctx
= std::get
<1>(local
);
1040 ret
<< (fmt
% idx
% std::get
<0>(local
).toStringWithPort() % ctx
->getProviderName()) << endl
;
1044 g_outputBuffer
=ret
.str();
1046 g_outputBuffer
="Error: DNSCrypt support is not enabled.\n";
1050 g_lua
.writeFunction("getDNSCryptBind", [](size_t idx
) {
1051 setLuaNoSideEffect();
1052 #ifdef HAVE_DNSCRYPT
1053 std::shared_ptr
<DNSCryptContext
> ret
= nullptr;
1054 if (idx
< g_dnsCryptLocals
.size()) {
1055 ret
= std::get
<1>(g_dnsCryptLocals
.at(idx
));
1059 g_outputBuffer
="Error: DNSCrypt support is not enabled.\n";
1063 g_lua
.writeFunction("generateDNSCryptProviderKeys", [](const std::string
& publicKeyFile
, const std::string privateKeyFile
) {
1064 setLuaNoSideEffect();
1065 #ifdef HAVE_DNSCRYPT
1066 unsigned char publicKey
[DNSCRYPT_PROVIDER_PUBLIC_KEY_SIZE
];
1067 unsigned char privateKey
[DNSCRYPT_PROVIDER_PRIVATE_KEY_SIZE
];
1068 sodium_mlock(privateKey
, sizeof(privateKey
));
1071 DNSCryptContext::generateProviderKeys(publicKey
, privateKey
);
1073 ofstream
pubKStream(publicKeyFile
);
1074 pubKStream
.write((char*) publicKey
, sizeof(publicKey
));
1077 ofstream
privKStream(privateKeyFile
);
1078 privKStream
.write((char*) privateKey
, sizeof(privateKey
));
1079 privKStream
.close();
1081 g_outputBuffer
="Provider fingerprint is: " + DNSCryptContext::getProviderFingerprint(publicKey
) + "\n";
1083 catch(std::exception
& e
) {
1085 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1088 sodium_memzero(privateKey
, sizeof(privateKey
));
1089 sodium_munlock(privateKey
, sizeof(privateKey
));
1091 g_outputBuffer
="Error: DNSCrypt support is not enabled.\n";
1095 g_lua
.writeFunction("printDNSCryptProviderFingerprint", [](const std::string
& publicKeyFile
) {
1096 setLuaNoSideEffect();
1097 #ifdef HAVE_DNSCRYPT
1098 unsigned char publicKey
[DNSCRYPT_PROVIDER_PUBLIC_KEY_SIZE
];
1101 ifstream
file(publicKeyFile
);
1102 file
.read((char *) &publicKey
, sizeof(publicKey
));
1105 throw std::runtime_error("Invalid dnscrypt provider public key file " + publicKeyFile
);
1108 g_outputBuffer
="Provider fingerprint is: " + DNSCryptContext::getProviderFingerprint(publicKey
) + "\n";
1110 catch(std::exception
& e
) {
1112 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1115 g_outputBuffer
="Error: DNSCrypt support is not enabled.\n";
1119 #ifdef HAVE_DNSCRYPT
1120 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
) {
1121 setLuaNoSideEffect();
1122 DNSCryptPrivateKey privateKey
;
1126 if (generateDNSCryptCertificate(providerPrivateKeyFile
, serial
, begin
, end
, version
? *version
: DNSCryptExchangeVersion::VERSION1
, cert
, privateKey
)) {
1127 privateKey
.saveToFile(privateKeyFile
);
1128 DNSCryptContext::saveCertFromFile(cert
, certificateFile
);
1131 catch(const std::exception
& e
) {
1133 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1138 g_lua
.writeFunction("showPools", []() {
1139 setLuaNoSideEffect();
1142 boost::format
fmt("%1$-20.20s %|25t|%2$20s %|25t|%3$20s %|50t|%4%" );
1144 ret
<< (fmt
% "Name" % "Cache" % "ServerPolicy" % "Servers" ) << endl
;
1146 const auto localPools
= g_pools
.getCopy();
1147 for (const auto& entry
: localPools
) {
1148 const string
& name
= entry
.first
;
1149 const std::shared_ptr
<ServerPool
> pool
= entry
.second
;
1150 string cache
= pool
->packetCache
!= nullptr ? pool
->packetCache
->toString() : "";
1151 string policy
= g_policy
.getLocal()->name
;
1152 if (pool
->policy
!= nullptr) {
1153 policy
= pool
->policy
->name
;
1157 for (const auto& server
: pool
->getServers()) {
1158 if (!servers
.empty()) {
1161 if (!server
.second
->name
.empty()) {
1162 servers
+= server
.second
->name
;
1165 servers
+= server
.second
->remote
.toStringWithPort();
1168 ret
<< (fmt
% name
% cache
% policy
% servers
) << endl
;
1170 g_outputBuffer
=ret
.str();
1171 }catch(std::exception
& e
) { g_outputBuffer
=e
.what(); throw; }
1174 g_lua
.writeFunction("getPool", [client
](const string
& poolName
) {
1176 return std::make_shared
<ServerPool
>();
1178 auto localPools
= g_pools
.getCopy();
1179 std::shared_ptr
<ServerPool
> pool
= createPoolIfNotExists(localPools
, poolName
);
1180 g_pools
.setState(localPools
);
1184 g_lua
.writeFunction("setVerboseHealthChecks", [](bool verbose
) { g_verboseHealthChecks
=verbose
; });
1185 g_lua
.writeFunction("setStaleCacheEntriesTTL", [](uint32_t ttl
) { g_staleCacheEntriesTTL
= ttl
; });
1187 g_lua
.writeFunction("showBinds", []() {
1188 setLuaNoSideEffect();
1191 boost::format
fmt("%1$-3d %2$-20.20s %|25t|%3$-8.8s %|35t|%4%" );
1193 ret
<< (fmt
% "#" % "Address" % "Protocol" % "Queries" ) << endl
;
1196 for (const auto& front
: g_frontends
) {
1197 ret
<< (fmt
% counter
% front
->local
.toStringWithPort() % (front
->udpFD
!= -1 ? "UDP" : "TCP") % front
->queries
) << endl
;
1200 g_outputBuffer
=ret
.str();
1201 }catch(std::exception
& e
) { g_outputBuffer
=e
.what(); throw; }
1204 g_lua
.writeFunction("getBind", [](size_t num
) {
1205 setLuaNoSideEffect();
1206 ClientState
* ret
= nullptr;
1207 if(num
< g_frontends
.size()) {
1208 ret
=g_frontends
[num
];
1213 g_lua
.writeFunction("help", [](boost::optional
<std::string
> command
) {
1214 setLuaNoSideEffect();
1215 g_outputBuffer
= "";
1216 for (const auto& keyword
: g_consoleKeywords
) {
1218 g_outputBuffer
+= keyword
.toString() + "\n";
1220 else if (keyword
.name
== command
) {
1221 g_outputBuffer
= keyword
.toString() + "\n";
1226 g_outputBuffer
= "Nothing found for " + *command
+ "\n";
1230 g_lua
.writeFunction("showVersion", []() {
1231 setLuaNoSideEffect();
1232 g_outputBuffer
= "dnsdist " + std::string(VERSION
) + "\n";
1236 g_lua
.writeFunction("setDefaultBPFFilter", [](std::shared_ptr
<BPFFilter
> bpf
) {
1237 if (g_configurationDone
) {
1238 g_outputBuffer
="setDefaultBPFFilter() cannot be used at runtime!\n";
1241 g_defaultBPFFilter
= bpf
;
1244 g_lua
.writeFunction("registerDynBPFFilter", [](std::shared_ptr
<DynBPFFilter
> dbpf
) {
1246 g_dynBPFFilters
.push_back(dbpf
);
1250 g_lua
.writeFunction("unregisterDynBPFFilter", [](std::shared_ptr
<DynBPFFilter
> dbpf
) {
1252 for (auto it
= g_dynBPFFilters
.begin(); it
!= g_dynBPFFilters
.end(); it
++) {
1254 g_dynBPFFilters
.erase(it
);
1261 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
) {
1263 struct timespec until
, now
;
1264 clock_gettime(CLOCK_MONOTONIC
, &now
);
1266 int actualSeconds
= seconds
? *seconds
: 10;
1267 until
.tv_sec
+= actualSeconds
;
1268 for(const auto& capair
: m
) {
1269 if (dynbpf
->block(capair
.first
, until
)) {
1270 warnlog("Inserting eBPF dynamic block for %s for %d seconds: %s", capair
.first
.toString(), actualSeconds
, msg
? *msg
: "");
1275 #endif /* HAVE_EBPF */
1277 g_lua
.writeFunction
<std::unordered_map
<string
,uint64_t>()>("getStatisticsCounters", []() {
1278 setLuaNoSideEffect();
1279 std::unordered_map
<string
,uint64_t> res
;
1280 for(const auto& entry
: g_stats
.entries
) {
1281 if(const auto& val
= boost::get
<DNSDistStats::stat_t
*>(&entry
.second
))
1282 res
[entry
.first
] = (*val
)->load();
1287 g_lua
.writeFunction("includeDirectory", [](const std::string
& dirname
) {
1288 if (g_configurationDone
) {
1289 errlog("includeDirectory() cannot be used at runtime!");
1290 g_outputBuffer
="includeDirectory() cannot be used at runtime!\n";
1295 errlog("includeDirectory() cannot be used recursively!");
1296 g_outputBuffer
="includeDirectory() cannot be used recursively!\n";
1302 if (stat(dirname
.c_str(), &st
)) {
1303 errlog("The included directory %s does not exist!", dirname
.c_str());
1304 g_outputBuffer
="The included directory " + dirname
+ " does not exist!";
1308 if (!S_ISDIR(st
.st_mode
)) {
1309 errlog("The included directory %s is not a directory!", dirname
.c_str());
1310 g_outputBuffer
="The included directory " + dirname
+ " is not a directory!";
1316 std::list
<std::string
> files
;
1317 if (!(dirp
= opendir(dirname
.c_str()))) {
1318 errlog("Error opening the included directory %s!", dirname
.c_str());
1319 g_outputBuffer
="Error opening the included directory " + dirname
+ "!";
1323 while((ent
= readdir(dirp
)) != NULL
) {
1324 if (ent
->d_name
[0] == '.') {
1328 if (boost::ends_with(ent
->d_name
, ".conf")) {
1329 std::ostringstream namebuf
;
1330 namebuf
<< dirname
.c_str() << "/" << ent
->d_name
;
1332 if (stat(namebuf
.str().c_str(), &st
) || !S_ISREG(st
.st_mode
)) {
1336 files
.push_back(namebuf
.str());
1343 for (auto file
= files
.begin(); file
!= files
.end(); ++file
) {
1344 std::ifstream
ifs(*file
);
1346 warnlog("Unable to read configuration from '%s'", *file
);
1348 vinfolog("Read configuration from '%s'", *file
);
1351 g_lua
.executeCode(ifs
);
1357 g_lua
.writeFunction("setAPIWritable", [](bool writable
, boost::optional
<std::string
> apiConfigDir
) {
1359 g_apiReadWrite
= writable
;
1361 if (!(*apiConfigDir
).empty()) {
1362 g_apiConfigDirectory
= *apiConfigDir
;
1365 errlog("The API configuration directory value cannot be empty!");
1366 g_outputBuffer
="The API configuration directory value cannot be empty!";
1371 g_lua
.writeFunction("setServFailWhenNoServer", [](bool servfail
) {
1373 g_servFailOnNoPolicy
= servfail
;
1376 g_lua
.writeFunction("setRingBuffersSize", [](size_t capacity
, boost::optional
<size_t> numberOfShards
) {
1378 if (g_configurationDone
) {
1379 errlog("setRingBuffersSize() cannot be used at runtime!");
1380 g_outputBuffer
="setRingBuffersSize() cannot be used at runtime!\n";
1383 g_rings
.setCapacity(capacity
, numberOfShards
? *numberOfShards
: 1);
1386 g_lua
.writeFunction("setRingBuffersLockRetries", [](size_t retries
) {
1388 g_rings
.setNumberOfLockRetries(retries
);
1391 g_lua
.writeFunction("setWHashedPertubation", [](uint32_t pertub
) {
1393 g_hashperturb
= pertub
;
1396 g_lua
.writeFunction("setTCPUseSinglePipe", [](bool flag
) {
1397 if (g_configurationDone
) {
1398 g_outputBuffer
="setTCPUseSinglePipe() cannot be used at runtime!\n";
1402 g_useTCPSinglePipe
= flag
;
1405 g_lua
.writeFunction("snmpAgent", [client
](bool enableTraps
, boost::optional
<std::string
> masterSocket
) {
1408 #ifdef HAVE_NET_SNMP
1409 if (g_configurationDone
) {
1410 errlog("snmpAgent() cannot be used at runtime!");
1411 g_outputBuffer
="snmpAgent() cannot be used at runtime!\n";
1415 if (g_snmpEnabled
) {
1416 errlog("snmpAgent() cannot be used twice!");
1417 g_outputBuffer
="snmpAgent() cannot be used twice!\n";
1421 g_snmpEnabled
= true;
1422 g_snmpTrapsEnabled
= enableTraps
;
1423 g_snmpAgent
= new DNSDistSNMPAgent("dnsdist", masterSocket
? *masterSocket
: std::string());
1425 errlog("NET SNMP support is required to use snmpAgent()");
1426 g_outputBuffer
="NET SNMP support is required to use snmpAgent()\n";
1427 #endif /* HAVE_NET_SNMP */
1430 g_lua
.writeFunction("sendCustomTrap", [](const std::string
& str
) {
1431 #ifdef HAVE_NET_SNMP
1432 if (g_snmpAgent
&& g_snmpTrapsEnabled
) {
1433 g_snmpAgent
->sendCustomTrap(str
);
1435 #endif /* HAVE_NET_SNMP */
1438 g_lua
.writeFunction("setPoolServerPolicy", [](ServerPolicy policy
, string pool
) {
1440 auto localPools
= g_pools
.getCopy();
1441 setPoolPolicy(localPools
, pool
, std::make_shared
<ServerPolicy
>(policy
));
1442 g_pools
.setState(localPools
);
1445 g_lua
.writeFunction("setPoolServerPolicyLua", [](string name
, policyfunc_t policy
, string pool
) {
1447 auto localPools
= g_pools
.getCopy();
1448 setPoolPolicy(localPools
, pool
, std::make_shared
<ServerPolicy
>(ServerPolicy
{name
, policy
, true}));
1449 g_pools
.setState(localPools
);
1452 g_lua
.writeFunction("showPoolServerPolicy", [](string pool
) {
1454 auto localPools
= g_pools
.getCopy();
1455 auto poolObj
= getPool(localPools
, pool
);
1456 if (poolObj
->policy
== nullptr) {
1457 g_outputBuffer
=g_policy
.getLocal()->name
+"\n";
1459 g_outputBuffer
=poolObj
->policy
->name
+"\n";
1463 g_lua
.writeFunction("setTCPDownstreamCleanupInterval", [](uint16_t interval
) {
1465 g_downstreamTCPCleanupInterval
= interval
;
1468 g_lua
.writeFunction("setConsoleConnectionsLogging", [](bool enabled
) {
1469 g_logConsoleConnections
= enabled
;
1472 g_lua
.writeFunction("setUDPMultipleMessagesVectorSize", [](size_t vSize
) {
1473 if (g_configurationDone
) {
1474 errlog("setUDPMultipleMessagesVectorSize() cannot be used at runtime!");
1475 g_outputBuffer
="setUDPMultipleMessagesVectorSize() cannot be used at runtime!\n";
1478 #if defined(HAVE_RECVMMSG) && defined(HAVE_SENDMMSG) && defined(MSG_WAITFORONE)
1480 g_udpVectorSize
= vSize
;
1482 errlog("recvmmsg() support is not available!");
1483 g_outputBuffer
="recvmmsg support is not available!\n";
1487 g_lua
.writeFunction("setAddEDNSToSelfGeneratedResponses", [](bool add
) {
1488 g_addEDNSToSelfGeneratedResponses
= add
;
1491 g_lua
.writeFunction("setPayloadSizeOnSelfGeneratedAnswers", [](uint16_t payloadSize
) {
1492 if (payloadSize
< 512) {
1493 warnlog("setPayloadSizeOnSelfGeneratedAnswers() is set too low, using 512 instead!");
1494 g_outputBuffer
="setPayloadSizeOnSelfGeneratedAnswers() is set too low, using 512 instead!";
1497 if (payloadSize
> s_udpIncomingBufferSize
) {
1498 warnlog("setPayloadSizeOnSelfGeneratedAnswers() is set too high, capping to %d instead!", s_udpIncomingBufferSize
);
1499 g_outputBuffer
="setPayloadSizeOnSelfGeneratedAnswers() is set too high, capping to " + std::to_string(s_udpIncomingBufferSize
) + " instead";
1500 payloadSize
= s_udpIncomingBufferSize
;
1502 g_PayloadSizeSelfGenAnswers
= payloadSize
;
1505 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
) {
1508 #ifdef HAVE_DNS_OVER_TLS
1510 if (g_configurationDone
) {
1511 g_outputBuffer
="addTLSLocal cannot be used at runtime!\n";
1514 shared_ptr
<TLSFrontend
> frontend
= std::make_shared
<TLSFrontend
>();
1516 if (!loadTLSCertificateAndKeys(frontend
, certFiles
, keyFiles
)) {
1522 parseLocalBindVars(vars
, doTCP
, frontend
->d_reusePort
, frontend
->d_tcpFastOpenQueueSize
, frontend
->d_interface
, frontend
->d_cpus
);
1524 if (vars
->count("provider")) {
1525 frontend
->d_provider
= boost::get
<const string
>((*vars
)["provider"]);
1528 if (vars
->count("ciphers")) {
1529 frontend
->d_ciphers
= boost::get
<const string
>((*vars
)["ciphers"]);
1532 if (vars
->count("ticketKeyFile")) {
1533 frontend
->d_ticketKeyFile
= boost::get
<const string
>((*vars
)["ticketKeyFile"]);
1536 if (vars
->count("ticketsKeysRotationDelay")) {
1537 frontend
->d_ticketsKeyRotationDelay
= std::stoi(boost::get
<const string
>((*vars
)["ticketsKeysRotationDelay"]));
1540 if (vars
->count("numberOfTicketsKeys")) {
1541 frontend
->d_numberOfTicketsKeys
= std::stoi(boost::get
<const string
>((*vars
)["numberOfTicketsKeys"]));
1544 if (vars
->count("sessionTickets")) {
1545 frontend
->d_enableTickets
= boost::get
<bool>((*vars
)["sessionTickets"]);
1548 if (vars
->count("numberOfStoredSessions")) {
1549 auto value
= boost::get
<int>((*vars
)["numberOfStoredSessions"]);
1551 errlog("Invalid value '%d' for addTLSLocal() parameter 'numberOfStoredSessions', should be >= 0, dismissing", value
);
1552 g_outputBuffer
="Invalid value '" + std::to_string(value
) + "' for addTLSLocal() parameter 'numberOfStoredSessions', should be >= 0, dimissing";
1555 frontend
->d_maxStoredSessions
= value
;
1560 frontend
->d_addr
= ComboAddress(addr
, 853);
1561 vinfolog("Loading TLS provider %s", frontend
->d_provider
);
1562 g_tlslocals
.push_back(frontend
); /// only works pre-startup, so no sync necessary
1564 catch(const std::exception
& e
) {
1565 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1568 g_outputBuffer
="DNS over TLS support is not present!\n";
1572 g_lua
.writeFunction("showTLSContexts", []() {
1573 #ifdef HAVE_DNS_OVER_TLS
1574 setLuaNoSideEffect();
1577 boost::format
fmt("%1$-3d %2$-20.20s %|25t|%3$-14d %|40t|%4$-14d %|54t|%5$-21.21s");
1579 ret
<< (fmt
% "#" % "Address" % "# ticket keys" % "Rotation delay" % "Next rotation" ) << endl
;
1581 for (const auto& ctx
: g_tlslocals
) {
1582 ret
<< (fmt
% counter
% ctx
->d_addr
.toStringWithPort() % ctx
->getTicketsKeysCount() % ctx
->getTicketsKeyRotationDelay() % ctx
->getNextTicketsKeyRotation()) << endl
;
1585 g_outputBuffer
= ret
.str();
1587 catch(const std::exception
& e
) {
1588 g_outputBuffer
= e
.what();
1592 g_outputBuffer
="DNS over TLS support is not present!\n";
1596 g_lua
.writeFunction("getTLSContext", [](size_t index
) {
1597 std::shared_ptr
<TLSCtx
> result
= nullptr;
1598 #ifdef HAVE_DNS_OVER_TLS
1599 setLuaNoSideEffect();
1601 if (index
< g_tlslocals
.size()) {
1602 result
= g_tlslocals
.at(index
)->getContext();
1605 errlog("Error: trying to get TLS context with index %zu but we only have %zu\n", index
, g_tlslocals
.size());
1606 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";
1609 catch(const std::exception
& e
) {
1610 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1611 errlog("Error: %s\n", string(e
.what()));
1614 g_outputBuffer
="DNS over TLS support is not present!\n";
1619 g_lua
.writeFunction("getTLSFrontend", [](size_t index
) {
1620 std::shared_ptr
<TLSFrontend
> result
= nullptr;
1621 #ifdef HAVE_DNS_OVER_TLS
1622 setLuaNoSideEffect();
1624 if (index
< g_tlslocals
.size()) {
1625 result
= g_tlslocals
.at(index
);
1628 errlog("Error: trying to get TLS frontend with index %zu but we only have %zu\n", index
, g_tlslocals
.size());
1629 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";
1632 catch(const std::exception
& e
) {
1633 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1634 errlog("Error: %s\n", string(e
.what()));
1637 g_outputBuffer
="DNS over TLS support is not present!\n";
1642 g_lua
.registerFunction
<void(std::shared_ptr
<TLSCtx
>::*)()>("rotateTicketsKey", [](std::shared_ptr
<TLSCtx
> ctx
) {
1643 if (ctx
!= nullptr) {
1644 ctx
->rotateTicketsKey(time(nullptr));
1648 g_lua
.registerFunction
<void(std::shared_ptr
<TLSCtx
>::*)(const std::string
&)>("loadTicketsKeys", [](std::shared_ptr
<TLSCtx
> ctx
, const std::string
& file
) {
1649 if (ctx
!= nullptr) {
1650 ctx
->loadTicketsKeys(file
);
1654 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
) {
1655 #ifdef HAVE_DNS_OVER_TLS
1656 if (loadTLSCertificateAndKeys(frontend
, certFiles
, keyFiles
)) {
1657 frontend
->setupTLS();
1663 vector
<std::function
<void(void)>> setupLua(bool client
, const std::string
& config
)
1665 g_launchWork
= new vector
<std::function
<void(void)>>();
1668 setupLuaConfig(client
);
1669 setupLuaBindings(client
);
1670 setupLuaBindingsDNSQuestion();
1671 setupLuaInspection();
1675 std::ifstream
ifs(config
);
1677 warnlog("Unable to read configuration from '%s'", config
);
1679 vinfolog("Read configuration from '%s'", config
);
1681 g_lua
.executeCode(ifs
);
1683 auto ret
= *g_launchWork
;
1684 delete g_launchWork
;
1685 g_launchWork
= nullptr;