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-healthchecks.hh"
38 #include "dnsdist-lua.hh"
40 #include "dnsdist-lua-ffi.hh"
41 #endif /* LUAJIT_VERSION */
42 #include "dnsdist-rings.hh"
43 #include "dnsdist-secpoll.hh"
46 #include "dnswriter.hh"
49 #include "protobuf.hh"
50 #include "sodcrypto.hh"
56 #include <boost/logic/tribool.hpp>
57 #include <boost/lexical_cast.hpp>
60 #include <systemd/sd-daemon.h>
65 static vector
<std::function
<void(void)>>* g_launchWork
= nullptr;
67 boost::tribool g_noLuaSideEffect
;
68 static bool g_included
{false};
70 /* this is a best effort way to prevent logging calls with no side-effects in the output of delta()
71 Functions can declare setLuaNoSideEffect() and if nothing else does declare a side effect, or nothing
72 has done so before on this invocation, this call won't be part of delta() output */
73 void setLuaNoSideEffect()
75 if(g_noLuaSideEffect
==false) // there has been a side effect already
77 g_noLuaSideEffect
=true;
80 void setLuaSideEffect()
82 g_noLuaSideEffect
=false;
85 bool getLuaNoSideEffect()
87 if (g_noLuaSideEffect
) {
93 void resetLuaSideEffect()
95 g_noLuaSideEffect
= boost::logic::indeterminate
;
98 typedef std::unordered_map
<std::string
, boost::variant
<bool, int, std::string
, std::vector
<std::pair
<int,int> >, std::vector
<std::pair
<int, std::string
> >, std::map
<std::string
,std::string
> > > localbind_t
;
100 static void parseLocalBindVars(boost::optional
<localbind_t
> vars
, bool& reusePort
, int& tcpFastOpenQueueSize
, std::string
& interface
, std::set
<int>& cpus
, int& tcpListenQueueSize
)
103 if (vars
->count("reusePort")) {
104 reusePort
= boost::get
<bool>((*vars
)["reusePort"]);
106 if (vars
->count("tcpFastOpenQueueSize")) {
107 tcpFastOpenQueueSize
= boost::get
<int>((*vars
)["tcpFastOpenQueueSize"]);
109 if (vars
->count("tcpListenQueueSize")) {
110 tcpListenQueueSize
= boost::get
<int>((*vars
)["tcpListenQueueSize"]);
112 if (vars
->count("interface")) {
113 interface
= boost::get
<std::string
>((*vars
)["interface"]);
115 if (vars
->count("cpus")) {
116 for (const auto& cpu
: boost::get
<std::vector
<std::pair
<int,int>>>((*vars
)["cpus"])) {
117 cpus
.insert(cpu
.second
);
123 #if defined(HAVE_DNS_OVER_TLS) || defined(HAVE_DNS_OVER_HTTPS)
124 static bool loadTLSCertificateAndKeys(const std::string
& context
, std::vector
<std::pair
<std::string
, std::string
>>& pairs
, boost::variant
<std::string
, std::vector
<std::pair
<int,std::string
>>> certFiles
, boost::variant
<std::string
, std::vector
<std::pair
<int,std::string
>>> keyFiles
)
126 if (certFiles
.type() == typeid(std::string
) && keyFiles
.type() == typeid(std::string
)) {
127 auto certFile
= boost::get
<std::string
>(certFiles
);
128 auto keyFile
= boost::get
<std::string
>(keyFiles
);
130 pairs
.push_back({certFile
, keyFile
});
132 else if (certFiles
.type() == typeid(std::vector
<std::pair
<int,std::string
>>) && keyFiles
.type() == typeid(std::vector
<std::pair
<int,std::string
>>))
134 auto certFilesVect
= boost::get
<std::vector
<std::pair
<int,std::string
>>>(certFiles
);
135 auto keyFilesVect
= boost::get
<std::vector
<std::pair
<int,std::string
>>>(keyFiles
);
136 if (certFilesVect
.size() == keyFilesVect
.size()) {
138 for (size_t idx
= 0; idx
< certFilesVect
.size(); idx
++) {
139 pairs
.push_back({certFilesVect
.at(idx
).second
, keyFilesVect
.at(idx
).second
});
143 errlog("Error, mismatching number of certificates and keys in call to %s()!", context
);
144 g_outputBuffer
="Error, mismatching number of certificates and keys in call to " + context
+ "()!";
149 errlog("Error, mismatching number of certificates and keys in call to %s()!", context
);
150 g_outputBuffer
="Error, mismatching number of certificates and keys in call to " + context
+ "()!";
157 static void parseTLSConfig(TLSConfig
& config
, const std::string
& context
, boost::optional
<localbind_t
> vars
)
159 if (vars
->count("ciphers")) {
160 config
.d_ciphers
= boost::get
<const string
>((*vars
)["ciphers"]);
163 if (vars
->count("ciphersTLS13")) {
164 config
.d_ciphers13
= boost::get
<const string
>((*vars
)["ciphersTLS13"]);
168 if (vars
->count("minTLSVersion")) {
169 config
.d_minTLSVersion
= libssl_tls_version_from_string(boost::get
<const string
>((*vars
)["minTLSVersion"]));
171 #endif /* HAVE_LIBSSL */
173 if (vars
->count("ticketKeyFile")) {
174 config
.d_ticketKeyFile
= boost::get
<const string
>((*vars
)["ticketKeyFile"]);
177 if (vars
->count("ticketsKeysRotationDelay")) {
178 config
.d_ticketsKeyRotationDelay
= boost::get
<int>((*vars
)["ticketsKeysRotationDelay"]);
181 if (vars
->count("numberOfTicketsKeys")) {
182 config
.d_numberOfTicketsKeys
= boost::get
<int>((*vars
)["numberOfTicketsKeys"]);
185 if (vars
->count("preferServerCiphers")) {
186 config
.d_preferServerCiphers
= boost::get
<bool>((*vars
)["preferServerCiphers"]);
189 if (vars
->count("sessionTimeout")) {
190 config
.d_sessionTimeout
= boost::get
<int>((*vars
)["sessionTimeout"]);
193 if (vars
->count("sessionTickets")) {
194 config
.d_enableTickets
= boost::get
<bool>((*vars
)["sessionTickets"]);
197 if (vars
->count("numberOfStoredSessions")) {
198 auto value
= boost::get
<int>((*vars
)["numberOfStoredSessions"]);
200 errlog("Invalid value '%d' for %s() parameter 'numberOfStoredSessions', should be >= 0, dismissing", value
, context
);
201 g_outputBuffer
="Invalid value '" + std::to_string(value
) + "' for " + context
+ "() parameter 'numberOfStoredSessions', should be >= 0, dimissing";
203 config
.d_maxStoredSessions
= value
;
206 if (vars
->count("ocspResponses")) {
207 auto files
= boost::get
<std::vector
<std::pair
<int, std::string
>>>((*vars
)["ocspResponses"]);
208 for (const auto& file
: files
) {
209 config
.d_ocspFiles
.push_back(file
.second
);
213 if (vars
->count("keyLogFile")) {
214 #ifdef HAVE_SSL_CTX_SET_KEYLOG_CALLBACK
215 config
.d_keyLogFile
= boost::get
<const string
>((*vars
)["keyLogFile"]);
217 errlog("TLS Key logging has been enabled using the 'keyLogFile' parameter to %s(), but this version of OpenSSL does not support it", context
);
218 g_outputBuffer
= "TLS Key logging has been enabled using the 'keyLogFile' parameter to " + context
+ "(), but this version of OpenSSL does not support it";
223 #endif // defined(HAVE_DNS_OVER_TLS) || defined(HAVE_DNS_OVER_HTTPS)
225 static void setupLuaConfig(bool client
, bool configCheck
)
227 typedef std::unordered_map
<std::string
, boost::variant
<bool, std::string
, vector
<pair
<int, std::string
> >, DownstreamState::checkfunc_t
> > newserver_t
;
228 g_lua
.writeFunction("inClientStartup", [client
]() {
229 return client
&& !g_configurationDone
;
232 g_lua
.writeFunction("inConfigCheck", [configCheck
]() {
236 g_lua
.writeFunction("newServer",
237 [client
, configCheck
](boost::variant
<string
,newserver_t
> pvars
, boost::optional
<int> qps
) {
240 std::shared_ptr
<DownstreamState
> ret
= std::make_shared
<DownstreamState
>(ComboAddress());
243 ComboAddress serverAddr
;
244 std::string serverAddressStr
;
245 if(auto addrStr
= boost::get
<string
>(&pvars
)) {
246 serverAddressStr
= *addrStr
;
248 vars
["qps"] = std::to_string(*qps
);
251 vars
= boost::get
<newserver_t
>(pvars
);
252 serverAddressStr
= boost::get
<string
>(vars
["address"]);
256 serverAddr
= ComboAddress(serverAddressStr
, 53);
258 catch(const PDNSException
& e
) {
259 g_outputBuffer
="Error creating new server: "+string(e
.reason
);
260 errlog("Error creating new server with address %s: %s", serverAddressStr
, e
.reason
);
263 catch(std::exception
& e
) {
264 g_outputBuffer
="Error creating new server: "+string(e
.what());
265 errlog("Error creating new server with address %s: %s", serverAddressStr
, e
.what());
269 if(IsAnyAddress(serverAddr
)) {
270 g_outputBuffer
="Error creating new server: invalid address for a downstream server.";
271 errlog("Error creating new server: %s is not a valid address for a downstream server", serverAddressStr
);
275 ComboAddress sourceAddr
;
276 std::string sourceItfName
;
277 unsigned int sourceItf
= 0;
278 size_t numberOfSockets
= 1;
281 if(vars
.count("source")) {
282 /* handle source in the following forms:
283 - v4 address ("192.0.2.1")
284 - v6 address ("2001:DB8::1")
285 - interface name ("eth0")
286 - v4 address and interface name ("192.0.2.1@eth0")
287 - v6 address and interface name ("2001:DB8::1@eth0")
289 const string source
= boost::get
<string
>(vars
["source"]);
291 std::string::size_type pos
= source
.find("@");
292 if (pos
== std::string::npos
) {
293 /* no '@', try to parse that as a valid v4/v6 address */
295 sourceAddr
= ComboAddress(source
);
305 /* try to parse as interface name, or v4/v6@itf */
306 sourceItfName
= source
.substr(pos
== std::string::npos
? 0 : pos
+ 1);
307 unsigned int itfIdx
= if_nametoindex(sourceItfName
.c_str());
310 if (pos
== 0 || pos
== std::string::npos
) {
311 /* "eth0" or "@eth0" */
315 /* "192.0.2.1@eth0" */
316 sourceAddr
= ComboAddress(source
.substr(0, pos
));
319 #ifdef SO_BINDTODEVICE
320 /* we need to retain CAP_NET_RAW to be able to set SO_BINDTODEVICE in the health checks */
321 g_capabilitiesToRetain
.insert("CAP_NET_RAW");
326 warnlog("Dismissing source %s because '%s' is not a valid interface name", source
, sourceItfName
);
331 if (vars
.count("sockets")) {
332 numberOfSockets
= std::stoul(boost::get
<string
>(vars
["sockets"]));
333 if (numberOfSockets
== 0) {
334 warnlog("Dismissing invalid number of sockets '%s', using 1 instead", boost::get
<string
>(vars
["sockets"]));
339 // create but don't connect the socket in client or check-config modes
340 ret
=std::make_shared
<DownstreamState
>(serverAddr
, sourceAddr
, sourceItf
, sourceItfName
, numberOfSockets
, !(client
|| configCheck
));
341 if (!(client
|| configCheck
)) {
342 infolog("Added downstream server %s", serverAddr
.toStringWithPort());
345 if(vars
.count("qps")) {
346 int qpsVal
=std::stoi(boost::get
<string
>(vars
["qps"]));
347 ret
->qps
=QPSLimiter(qpsVal
, qpsVal
);
350 if(vars
.count("order")) {
351 ret
->order
=std::stoi(boost::get
<string
>(vars
["order"]));
354 if(vars
.count("weight")) {
356 int weightVal
=std::stoi(boost::get
<string
>(vars
["weight"]));
359 errlog("Error creating new server: downstream weight value must be greater than 0.");
363 ret
->setWeight(weightVal
);
365 catch(std::exception
& e
) {
366 // std::stoi will throw an exception if the string isn't in a value int range
367 errlog("Error creating new server: downstream weight value must be between %s and %s", 1, std::numeric_limits
<int>::max());
372 if(vars
.count("retries")) {
373 ret
->retries
=std::stoi(boost::get
<string
>(vars
["retries"]));
376 if(vars
.count("checkInterval")) {
377 ret
->checkInterval
=static_cast<unsigned int>(std::stoul(boost::get
<string
>(vars
["checkInterval"])));
380 if(vars
.count("tcpConnectTimeout")) {
381 ret
->tcpConnectTimeout
=std::stoi(boost::get
<string
>(vars
["tcpConnectTimeout"]));
384 if(vars
.count("tcpSendTimeout")) {
385 ret
->tcpSendTimeout
=std::stoi(boost::get
<string
>(vars
["tcpSendTimeout"]));
388 if(vars
.count("tcpRecvTimeout")) {
389 ret
->tcpRecvTimeout
=std::stoi(boost::get
<string
>(vars
["tcpRecvTimeout"]));
392 if(vars
.count("tcpFastOpen")) {
393 bool fastOpen
= boost::get
<bool>(vars
["tcpFastOpen"]);
396 ret
->tcpFastOpen
=true;
398 warnlog("TCP Fast Open has been configured on downstream server %s but is not supported", boost::get
<string
>(vars
["address"]));
403 if(vars
.count("name")) {
404 ret
->setName(boost::get
<string
>(vars
["name"]));
407 if (vars
.count("id")) {
408 ret
->setId(boost::lexical_cast
<boost::uuids::uuid
>(boost::get
<string
>(vars
["id"])));
411 if(vars
.count("checkName")) {
412 ret
->checkName
=DNSName(boost::get
<string
>(vars
["checkName"]));
415 if(vars
.count("checkType")) {
416 ret
->checkType
=boost::get
<string
>(vars
["checkType"]);
419 if(vars
.count("checkClass")) {
420 ret
->checkClass
=std::stoi(boost::get
<string
>(vars
["checkClass"]));
423 if(vars
.count("checkFunction")) {
424 ret
->checkFunction
= boost::get
<DownstreamState::checkfunc_t
>(vars
["checkFunction"]);
427 if(vars
.count("checkTimeout")) {
428 ret
->checkTimeout
= std::stoi(boost::get
<string
>(vars
["checkTimeout"]));
431 if(vars
.count("setCD")) {
432 ret
->setCD
=boost::get
<bool>(vars
["setCD"]);
435 if(vars
.count("mustResolve")) {
436 ret
->mustResolve
=boost::get
<bool>(vars
["mustResolve"]);
439 if(vars
.count("useClientSubnet")) {
440 ret
->useECS
=boost::get
<bool>(vars
["useClientSubnet"]);
443 if(vars
.count("useProxyProtocol")) {
444 ret
->useProxyProtocol
= boost::get
<bool>(vars
["useProxyProtocol"]);
447 if(vars
.count("disableZeroScope")) {
448 ret
->disableZeroScope
=boost::get
<bool>(vars
["disableZeroScope"]);
451 if(vars
.count("ipBindAddrNoPort")) {
452 ret
->ipBindAddrNoPort
=boost::get
<bool>(vars
["ipBindAddrNoPort"]);
455 if(vars
.count("addXPF")) {
456 ret
->xpfRRCode
=std::stoi(boost::get
<string
>(vars
["addXPF"]));
459 if(vars
.count("maxCheckFailures")) {
460 ret
->maxCheckFailures
=std::stoi(boost::get
<string
>(vars
["maxCheckFailures"]));
463 if(vars
.count("rise")) {
464 ret
->minRiseSuccesses
=std::stoi(boost::get
<string
>(vars
["rise"]));
467 if(vars
.count("cpus")) {
468 for (const auto& cpu
: boost::get
<vector
<pair
<int,string
>>>(vars
["cpus"])) {
469 cpus
.insert(std::stoi(cpu
.second
));
473 /* this needs to be done _AFTER_ the order has been set,
474 since the server are kept ordered inside the pool */
475 auto localPools
= g_pools
.getCopy();
476 if(vars
.count("pool")) {
477 if(auto* pool
= boost::get
<string
>(&vars
["pool"])) {
478 ret
->pools
.insert(*pool
);
481 auto pools
= boost::get
<vector
<pair
<int, string
> > >(vars
["pool"]);
482 for(auto& p
: pools
) {
483 ret
->pools
.insert(p
.second
);
486 for(const auto& poolName
: ret
->pools
) {
487 addServerToPool(localPools
, poolName
, ret
);
491 addServerToPool(localPools
, "", ret
);
493 g_pools
.setState(localPools
);
495 if (ret
->connected
) {
496 ret
->threadStarted
.test_and_set();
499 g_launchWork
->push_back([ret
,cpus
]() {
500 ret
->tid
= thread(responderThread
, ret
);
502 mapThreadToCPUList(ret
->tid
.native_handle(), cpus
);
507 ret
->tid
= thread(responderThread
, ret
);
509 mapThreadToCPUList(ret
->tid
.native_handle(), cpus
);
514 auto states
= g_dstates
.getCopy();
515 states
.push_back(ret
);
516 std::stable_sort(states
.begin(), states
.end(), [](const decltype(ret
)& a
, const decltype(ret
)& b
) {
517 return a
->order
< b
->order
;
519 g_dstates
.setState(states
);
523 g_lua
.writeFunction("rmServer",
524 [](boost::variant
<std::shared_ptr
<DownstreamState
>, int, std::string
> var
)
527 shared_ptr
<DownstreamState
> server
= nullptr;
528 auto states
= g_dstates
.getCopy();
529 if (auto* rem
= boost::get
<shared_ptr
<DownstreamState
>>(&var
)) {
532 else if (auto str
= boost::get
<std::string
>(&var
)) {
533 const auto uuid
= getUniqueID(*str
);
534 for (auto& state
: states
) {
535 if (state
->id
== uuid
) {
541 int idx
= boost::get
<int>(var
);
542 server
= states
.at(idx
);
545 throw std::runtime_error("unable to locate the requested server");
547 auto localPools
= g_pools
.getCopy();
548 for (const string
& poolName
: server
->pools
) {
549 removeServerFromPool(localPools
, poolName
, server
);
551 /* the server might also be in the default pool */
552 removeServerFromPool(localPools
, "", server
);
553 g_pools
.setState(localPools
);
554 states
.erase(remove(states
.begin(), states
.end(), server
), states
.end());
555 g_dstates
.setState(states
);
558 g_lua
.writeFunction("truncateTC", [](bool tc
) { setLuaSideEffect(); g_truncateTC
=tc
; });
559 g_lua
.writeFunction("fixupCase", [](bool fu
) { setLuaSideEffect(); g_fixupCase
=fu
; });
561 g_lua
.writeFunction("addACL", [](const std::string
& domain
) {
563 g_ACL
.modify([domain
](NetmaskGroup
& nmg
) { nmg
.addMask(domain
); });
566 g_lua
.writeFunction("rmACL", [](const std::string
& netmask
) {
568 g_ACL
.modify([netmask
](NetmaskGroup
& nmg
) { nmg
.deleteMask(netmask
); });
571 g_lua
.writeFunction("setLocal", [client
](const std::string
& addr
, boost::optional
<localbind_t
> vars
) {
575 if (g_configurationDone
) {
576 g_outputBuffer
="setLocal cannot be used at runtime!\n";
579 bool reusePort
= false;
580 int tcpFastOpenQueueSize
= 0;
581 int tcpListenQueueSize
= 0;
582 std::string interface
;
585 parseLocalBindVars(vars
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
, tcpListenQueueSize
);
588 ComboAddress
loc(addr
, 53);
589 for (auto it
= g_frontends
.begin(); it
!= g_frontends
.end(); ) {
590 /* DoH, DoT and DNSCrypt frontends are separate */
591 if ((*it
)->tlsFrontend
== nullptr && (*it
)->dnscryptCtx
== nullptr && (*it
)->dohFrontend
== nullptr) {
592 it
= g_frontends
.erase(it
);
599 // only works pre-startup, so no sync necessary
600 g_frontends
.push_back(std::unique_ptr
<ClientState
>(new ClientState(loc
, false, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
)));
601 auto tcpCS
= std::unique_ptr
<ClientState
>(new ClientState(loc
, true, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
));
602 if (tcpListenQueueSize
> 0) {
603 tcpCS
->tcpListenQueueSize
= tcpListenQueueSize
;
605 g_frontends
.push_back(std::move(tcpCS
));
607 catch(const std::exception
& e
) {
608 g_outputBuffer
="Error: "+string(e
.what())+"\n";
612 g_lua
.writeFunction("addLocal", [client
](const std::string
& addr
, boost::optional
<localbind_t
> vars
) {
616 if (g_configurationDone
) {
617 g_outputBuffer
="addLocal cannot be used at runtime!\n";
620 bool reusePort
= false;
621 int tcpFastOpenQueueSize
= 0;
622 int tcpListenQueueSize
= 0;
623 std::string interface
;
626 parseLocalBindVars(vars
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
, tcpListenQueueSize
);
629 ComboAddress
loc(addr
, 53);
630 // only works pre-startup, so no sync necessary
631 g_frontends
.push_back(std::unique_ptr
<ClientState
>(new ClientState(loc
, false, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
)));
632 auto tcpCS
= std::unique_ptr
<ClientState
>(new ClientState(loc
, true, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
));
633 if (tcpListenQueueSize
> 0) {
634 tcpCS
->tcpListenQueueSize
= tcpListenQueueSize
;
636 g_frontends
.push_back(std::move(tcpCS
));
638 catch(std::exception
& e
) {
639 g_outputBuffer
="Error: "+string(e
.what())+"\n";
640 errlog("Error while trying to listen on %s: %s\n", addr
, string(e
.what()));
644 g_lua
.writeFunction("setACL", [](boost::variant
<string
,vector
<pair
<int, string
>>> inp
) {
647 if(auto str
= boost::get
<string
>(&inp
)) {
650 else for(const auto& p
: boost::get
<vector
<pair
<int,string
>>>(inp
)) {
651 nmg
.addMask(p
.second
);
656 g_lua
.writeFunction("showACL", []() {
657 setLuaNoSideEffect();
660 g_ACL
.getLocal()->toStringVector(&vec
);
662 for(const auto& s
: vec
)
663 g_outputBuffer
+=s
+"\n";
667 g_lua
.writeFunction("shutdown", []() {
669 sd_notify(0, "STOPPING=1");
670 #endif /* HAVE_SYSTEMD */
672 // Useful for debugging leaks, but might lead to race under load
673 // since other threads are still runing.
674 for(auto& frontend
: g_tlslocals
) {
679 google::protobuf::ShutdownProtobufLibrary();
680 #endif /* HAVE_PROTOBUF */
685 typedef std::unordered_map
<std::string
, boost::variant
<bool, std::string
> > showserversopts_t
;
687 g_lua
.writeFunction("showServers", [](boost::optional
<showserversopts_t
> vars
) {
688 setLuaNoSideEffect();
689 bool showUUIDs
= false;
691 if (vars
->count("showUUIDs")) {
692 showUUIDs
= boost::get
<bool>((*vars
)["showUUIDs"]);
699 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%" );
700 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
701 ret
<< (fmt
% "#" % "Name" % "Address" % "State" % "Qps" % "Qlim" % "Ord" % "Wt" % "Queries" % "Drops" % "Drate" % "Lat" % "Outstanding" % "Pools" % "UUID") << endl
;
703 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%" );
704 ret
<< (fmt
% "#" % "Name" % "Address" % "State" % "Qps" % "Qlim" % "Ord" % "Wt" % "Queries" % "Drops" % "Drate" % "Lat" % "Outstanding" % "Pools") << endl
;
707 uint64_t totQPS
{0}, totQueries
{0}, totDrops
{0};
709 auto states
= g_dstates
.getLocal();
710 for(const auto& s
: *states
) {
711 string status
= s
->getStatus();
713 for(auto& p
: s
->pools
) {
719 ret
<< (fmt
% counter
% s
->getName() % s
->remote
.toStringWithPort() %
721 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
;
723 ret
<< (fmt
% counter
% s
->getName() % s
->remote
.toStringWithPort() %
725 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
;
727 totQPS
+= s
->queryLoad
;
728 totQueries
+= s
->queries
.load();
729 totDrops
+= s
->reuseds
.load();
733 ret
<< (fmt
% "All" % "" % "" % ""
735 (double)totQPS
% "" % "" % "" % totQueries
% totDrops
% "" % "" % "" % "" % "" ) << endl
;
737 ret
<< (fmt
% "All" % "" % "" % ""
739 (double)totQPS
% "" % "" % "" % totQueries
% totDrops
% "" % "" % "" % "" ) << endl
;
742 g_outputBuffer
=ret
.str();
743 } catch(std::exception
& e
) {
744 g_outputBuffer
=e
.what();
749 g_lua
.writeFunction("getServers", []() {
750 setLuaNoSideEffect();
751 vector
<pair
<int, std::shared_ptr
<DownstreamState
> > > ret
;
753 for(const auto& s
: g_dstates
.getCopy()) {
754 ret
.push_back(make_pair(count
++, s
));
759 g_lua
.writeFunction("getPoolServers", [](string pool
) {
760 return getDownstreamCandidates(g_pools
.getCopy(), pool
);
763 g_lua
.writeFunction("getServer", [client
](boost::variant
<unsigned int, std::string
> i
) {
765 return std::make_shared
<DownstreamState
>(ComboAddress());
767 auto states
= g_dstates
.getCopy();
768 if (auto str
= boost::get
<std::string
>(&i
)) {
769 const auto uuid
= getUniqueID(*str
);
770 for (auto& state
: states
) {
771 if (state
->id
== uuid
) {
776 else if (auto pos
= boost::get
<unsigned int>(&i
)) {
777 return states
.at(*pos
);
780 g_outputBuffer
= "Error: no rule matched\n";
781 return std::shared_ptr
<DownstreamState
>(nullptr);
784 g_lua
.writeFunction("carbonServer", [](const std::string
& address
, boost::optional
<string
> ourName
,
785 boost::optional
<unsigned int> interval
, boost::optional
<string
> namespace_name
,
786 boost::optional
<string
> instance_name
) {
788 auto ours
= g_carbon
.getCopy();
790 ComboAddress(address
, 2003),
791 (namespace_name
&& !namespace_name
->empty()) ? *namespace_name
: "dnsdist",
792 ourName
? *ourName
: "",
793 (instance_name
&& !instance_name
->empty()) ? *instance_name
: "main" ,
794 interval
? *interval
: 30
796 g_carbon
.setState(ours
);
799 g_lua
.writeFunction("webserver", [client
,configCheck
](const std::string
& address
, const std::string
& password
, const boost::optional
<std::string
> apiKey
, const boost::optional
<std::map
<std::string
, std::string
> > customHeaders
) {
803 local
= ComboAddress(address
);
805 catch (const PDNSException
& e
) {
806 throw std::runtime_error(std::string("Error parsing the bind address for the webserver: ") + e
.reason
);
809 if (client
|| configCheck
) {
814 int sock
= SSocket(local
.sin4
.sin_family
, SOCK_STREAM
, 0);
815 SSetsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, 1);
818 auto launch
=[sock
, local
, password
, apiKey
, customHeaders
]() {
819 setWebserverPassword(password
);
820 setWebserverAPIKey(apiKey
);
821 setWebserverCustomHeaders(customHeaders
);
822 thread
t(dnsdistWebserverThread
, sock
, local
);
826 g_launchWork
->push_back(launch
);
830 catch(std::exception
& e
) {
831 g_outputBuffer
="Unable to bind to webserver socket on " + local
.toStringWithPort() + ": " + e
.what();
832 errlog("Unable to bind to webserver socket on %s: %s", local
.toStringWithPort(), e
.what());
837 typedef std::unordered_map
<std::string
, boost::variant
<std::string
, std::map
<std::string
, std::string
>> > webserveropts_t
;
839 g_lua
.writeFunction("setWebserverConfig", [](boost::optional
<webserveropts_t
> vars
) {
845 if(vars
->count("password")) {
846 const std::string password
= boost::get
<std::string
>(vars
->at("password"));
848 setWebserverPassword(password
);
850 if(vars
->count("apiKey")) {
851 const std::string apiKey
= boost::get
<std::string
>(vars
->at("apiKey"));
853 setWebserverAPIKey(apiKey
);
855 if(vars
->count("customHeaders")) {
856 const boost::optional
<std::map
<std::string
, std::string
> > headers
= boost::get
<std::map
<std::string
, std::string
> >(vars
->at("customHeaders"));
858 setWebserverCustomHeaders(headers
);
862 g_lua
.writeFunction("controlSocket", [client
,configCheck
](const std::string
& str
) {
864 ComboAddress
local(str
, 5199);
866 if(client
|| configCheck
) {
867 g_serverControl
= local
;
871 g_consoleEnabled
= true;
872 #ifdef HAVE_LIBSODIUM
873 if (g_configurationDone
&& g_consoleKey
.empty()) {
874 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");
879 int sock
= SSocket(local
.sin4
.sin_family
, SOCK_STREAM
, 0);
880 SSetsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, 1);
883 auto launch
=[sock
, local
]() {
884 thread
t(controlThread
, sock
, local
);
888 g_launchWork
->push_back(launch
);
893 catch(std::exception
& e
) {
894 g_outputBuffer
="Unable to bind to control socket on " + local
.toStringWithPort() + ": " + e
.what();
895 errlog("Unable to bind to control socket on %s: %s", local
.toStringWithPort(), e
.what());
899 g_lua
.writeFunction("addConsoleACL", [](const std::string
& netmask
) {
901 #ifndef HAVE_LIBSODIUM
902 warnlog("Allowing remote access to the console while libsodium support has not been enabled is not secure, and will result in cleartext communications");
905 g_consoleACL
.modify([netmask
](NetmaskGroup
& nmg
) { nmg
.addMask(netmask
); });
908 g_lua
.writeFunction("setConsoleACL", [](boost::variant
<string
,vector
<pair
<int, string
>>> inp
) {
911 #ifndef HAVE_LIBSODIUM
912 warnlog("Allowing remote access to the console while libsodium support has not been enabled is not secure, and will result in cleartext communications");
916 if(auto str
= boost::get
<string
>(&inp
)) {
919 else for(const auto& p
: boost::get
<vector
<pair
<int,string
>>>(inp
)) {
920 nmg
.addMask(p
.second
);
922 g_consoleACL
.setState(nmg
);
925 g_lua
.writeFunction("showConsoleACL", []() {
926 setLuaNoSideEffect();
928 #ifndef HAVE_LIBSODIUM
929 warnlog("Allowing remote access to the console while libsodium support has not been enabled is not secure, and will result in cleartext communications");
933 g_consoleACL
.getLocal()->toStringVector(&vec
);
935 for(const auto& s
: vec
) {
936 g_outputBuffer
+= s
+ "\n";
940 g_lua
.writeFunction("clearQueryCounters", []() {
941 unsigned int size
{0};
943 WriteLock
wl(&g_qcount
.queryLock
);
944 size
= g_qcount
.records
.size();
945 g_qcount
.records
.clear();
948 boost::format
fmt("%d records cleared from query counter buffer\n");
949 g_outputBuffer
= (fmt
% size
).str();
952 g_lua
.writeFunction("getQueryCounters", [](boost::optional
<unsigned int> optMax
) {
953 setLuaNoSideEffect();
954 ReadLock
rl(&g_qcount
.queryLock
);
955 g_outputBuffer
= "query counting is currently: ";
956 g_outputBuffer
+= g_qcount
.enabled
? "enabled" : "disabled";
957 g_outputBuffer
+= (boost::format(" (%d records in buffer)\n") % g_qcount
.records
.size()).str();
959 boost::format
fmt("%-3d %s: %d request(s)\n");
960 QueryCountRecords::iterator it
;
961 unsigned int max
= optMax
? *optMax
: 10;
962 unsigned int index
{1};
963 for(it
= g_qcount
.records
.begin(); it
!= g_qcount
.records
.end() && index
<= max
; ++it
, ++index
) {
964 g_outputBuffer
+= (fmt
% index
% it
->first
% it
->second
).str();
968 g_lua
.writeFunction("setQueryCount", [](bool enabled
) { g_qcount
.enabled
=enabled
; });
970 g_lua
.writeFunction("setQueryCountFilter", [](QueryCountFilter func
) {
971 g_qcount
.filter
= func
;
974 g_lua
.writeFunction("makeKey", []() {
975 setLuaNoSideEffect();
976 g_outputBuffer
="setKey("+newKey()+")\n";
979 g_lua
.writeFunction("setKey", [](const std::string
& key
) {
980 if(!g_configurationDone
&& ! g_consoleKey
.empty()) { // this makes sure the commandline -k key prevails over dnsdist.conf
981 return; // but later setKeys() trump the -k value again
983 #ifndef HAVE_LIBSODIUM
984 warnlog("Calling setKey() while libsodium support has not been enabled is not secure, and will result in cleartext communications");
989 if(B64Decode(key
, newkey
) < 0) {
990 g_outputBuffer
=string("Unable to decode ")+key
+" as Base64";
991 errlog("%s", g_outputBuffer
);
997 g_lua
.writeFunction("testCrypto", [](boost::optional
<string
> optTestMsg
)
999 setLuaNoSideEffect();
1000 #ifdef HAVE_LIBSODIUM
1005 testmsg
= *optTestMsg
;
1008 testmsg
= "testStringForCryptoTests";
1011 SodiumNonce sn
, sn2
;
1014 string encrypted
= sodEncryptSym(testmsg
, g_consoleKey
, sn
);
1015 string decrypted
= sodDecryptSym(encrypted
, g_consoleKey
, sn2
);
1020 encrypted
= sodEncryptSym(testmsg
, g_consoleKey
, sn
);
1021 decrypted
= sodDecryptSym(encrypted
, g_consoleKey
, sn2
);
1023 if(testmsg
== decrypted
)
1024 g_outputBuffer
="Everything is ok!\n";
1026 g_outputBuffer
="Crypto failed.. (the decoded value does not match the cleartext one)\n";
1028 catch(const std::exception
& e
) {
1029 g_outputBuffer
="Crypto failed: "+std::string(e
.what())+"\n";
1032 g_outputBuffer
="Crypto failed..\n";
1035 g_outputBuffer
="Crypto not available.\n";
1039 g_lua
.writeFunction("setTCPRecvTimeout", [](int timeout
) { g_tcpRecvTimeout
=timeout
; });
1041 g_lua
.writeFunction("setTCPSendTimeout", [](int timeout
) { g_tcpSendTimeout
=timeout
; });
1043 g_lua
.writeFunction("setUDPTimeout", [](int timeout
) { g_udpTimeout
=timeout
; });
1045 g_lua
.writeFunction("setMaxUDPOutstanding", [](uint16_t max
) {
1046 if (!g_configurationDone
) {
1047 g_maxOutstanding
= max
;
1049 g_outputBuffer
="Max UDP outstanding cannot be altered at runtime!\n";
1053 g_lua
.writeFunction("setMaxTCPClientThreads", [](uint64_t max
) {
1054 if (!g_configurationDone
) {
1055 g_maxTCPClientThreads
= max
;
1057 g_outputBuffer
="Maximum TCP client threads count cannot be altered at runtime!\n";
1061 g_lua
.writeFunction("setMaxTCPQueuedConnections", [](uint64_t max
) {
1062 if (!g_configurationDone
) {
1063 g_maxTCPQueuedConnections
= max
;
1065 g_outputBuffer
="The maximum number of queued TCP connections cannot be altered at runtime!\n";
1069 g_lua
.writeFunction("setMaxTCPQueriesPerConnection", [](size_t max
) {
1070 if (!g_configurationDone
) {
1071 g_maxTCPQueriesPerConn
= max
;
1073 g_outputBuffer
="The maximum number of queries per TCP connection cannot be altered at runtime!\n";
1077 g_lua
.writeFunction("setMaxTCPConnectionsPerClient", [](size_t max
) {
1078 if (!g_configurationDone
) {
1079 g_maxTCPConnectionsPerClient
= max
;
1081 g_outputBuffer
="The maximum number of TCP connection per client cannot be altered at runtime!\n";
1085 g_lua
.writeFunction("setMaxTCPConnectionDuration", [](size_t max
) {
1086 if (!g_configurationDone
) {
1087 g_maxTCPConnectionDuration
= max
;
1089 g_outputBuffer
="The maximum duration of a TCP connection cannot be altered at runtime!\n";
1093 g_lua
.writeFunction("setCacheCleaningDelay", [](uint32_t delay
) { g_cacheCleaningDelay
= delay
; });
1095 g_lua
.writeFunction("setCacheCleaningPercentage", [](uint16_t percentage
) { if (percentage
< 100) g_cacheCleaningPercentage
= percentage
; else g_cacheCleaningPercentage
= 100; });
1097 g_lua
.writeFunction("setECSSourcePrefixV4", [](uint16_t prefix
) { g_ECSSourcePrefixV4
=prefix
; });
1099 g_lua
.writeFunction("setECSSourcePrefixV6", [](uint16_t prefix
) { g_ECSSourcePrefixV6
=prefix
; });
1101 g_lua
.writeFunction("setECSOverride", [](bool override
) { g_ECSOverride
=override
; });
1103 g_lua
.writeFunction("setPreserveTrailingData", [](bool preserve
) { g_preserveTrailingData
= preserve
; });
1105 g_lua
.writeFunction("showDynBlocks", []() {
1106 setLuaNoSideEffect();
1107 auto slow
= g_dynblockNMG
.getCopy();
1108 struct timespec now
;
1110 boost::format
fmt("%-24s %8d %8d %-10s %-20s %s\n");
1111 g_outputBuffer
= (fmt
% "What" % "Seconds" % "Blocks" % "Warning" % "Action" % "Reason").str();
1112 for(const auto& e
: slow
) {
1113 if(now
< e
.second
.until
)
1114 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();
1116 auto slow2
= g_dynblockSMT
.getCopy();
1117 slow2
.visit([&now
, &fmt
](const SuffixMatchTree
<DynBlock
>& node
) {
1118 if(now
<node
.d_value
.until
) {
1119 string
dom("empty");
1120 if(!node
.d_value
.domain
.empty())
1121 dom
= node
.d_value
.domain
.toString();
1122 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();
1128 g_lua
.writeFunction("clearDynBlocks", []() {
1131 g_dynblockNMG
.setState(nmg
);
1132 SuffixMatchTree
<DynBlock
> smt
;
1133 g_dynblockSMT
.setState(smt
);
1136 g_lua
.writeFunction("addDynBlocks",
1137 [](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
) {
1142 auto slow
= g_dynblockNMG
.getCopy();
1143 struct timespec until
, now
;
1146 int actualSeconds
= seconds
? *seconds
: 10;
1147 until
.tv_sec
+= actualSeconds
;
1148 for(const auto& capair
: m
) {
1149 unsigned int count
= 0;
1150 auto got
= slow
.lookup(Netmask(capair
.first
));
1153 if(until
< got
->second
.until
) // had a longer policy
1155 if(now
< got
->second
.until
) // only inherit count on fresh query we are extending
1156 count
=got
->second
.blocks
;
1160 DynBlock db
{msg
,until
,DNSName(),(action
? *action
: DNSAction::Action::None
)};
1163 warnlog("Inserting dynamic block for %s for %d seconds: %s", capair
.first
.toString(), actualSeconds
, msg
);
1164 slow
.insert(Netmask(capair
.first
)).second
=db
;
1166 g_dynblockNMG
.setState(slow
);
1169 g_lua
.writeFunction("addDynBlockSMT",
1170 [](const vector
<pair
<unsigned int, string
> >&names
, const std::string
& msg
, boost::optional
<int> seconds
, boost::optional
<DNSAction::Action
> action
) {
1171 if (names
.empty()) {
1175 auto slow
= g_dynblockSMT
.getCopy();
1176 struct timespec until
, now
;
1179 int actualSeconds
= seconds
? *seconds
: 10;
1180 until
.tv_sec
+= actualSeconds
;
1182 for(const auto& capair
: names
) {
1183 unsigned int count
= 0;
1184 DNSName
domain(capair
.second
);
1185 domain
.makeUsLowerCase();
1186 auto got
= slow
.lookup(domain
);
1189 if(until
< got
->until
) // had a longer policy
1191 if(now
< got
->until
) // only inherit count on fresh query we are extending
1197 DynBlock db
{msg
,until
,domain
,(action
? *action
: DNSAction::Action::None
)};
1200 warnlog("Inserting dynamic block for %s for %d seconds: %s", domain
, actualSeconds
, msg
);
1201 slow
.add(domain
, db
);
1203 g_dynblockSMT
.setState(slow
);
1206 g_lua
.writeFunction("setDynBlocksAction", [](DNSAction::Action action
) {
1207 if (!g_configurationDone
) {
1208 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
) {
1209 g_dynBlockAction
= action
;
1212 errlog("Dynamic blocks action can only be Drop, NoOp, NXDomain, Refused, Truncate or NoRecurse!");
1213 g_outputBuffer
="Dynamic blocks action can only be Drop, NoOp, NXDomain, Refused, Truncate or NoRecurse!\n";
1216 g_outputBuffer
="Dynamic blocks action cannot be altered at runtime!\n";
1220 g_lua
.writeFunction("addDNSCryptBind", [](const std::string
& addr
, const std::string
& providerName
, 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
) {
1221 if (g_configurationDone
) {
1222 g_outputBuffer
="addDNSCryptBind cannot be used at runtime!\n";
1225 #ifdef HAVE_DNSCRYPT
1226 bool reusePort
= false;
1227 int tcpFastOpenQueueSize
= 0;
1228 int tcpListenQueueSize
= 0;
1229 std::string interface
;
1231 std::vector
<DNSCryptContext::CertKeyPaths
> certKeys
;
1233 parseLocalBindVars(vars
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
, tcpListenQueueSize
);
1235 if (certFiles
.type() == typeid(std::string
) && keyFiles
.type() == typeid(std::string
)) {
1236 auto certFile
= boost::get
<std::string
>(certFiles
);
1237 auto keyFile
= boost::get
<std::string
>(keyFiles
);
1238 certKeys
.push_back({certFile
, keyFile
});
1240 else if (certFiles
.type() == typeid(std::vector
<std::pair
<int,std::string
>>) && keyFiles
.type() == typeid(std::vector
<std::pair
<int,std::string
>>)) {
1241 auto certFilesVect
= boost::get
<std::vector
<std::pair
<int,std::string
>>>(certFiles
);
1242 auto keyFilesVect
= boost::get
<std::vector
<std::pair
<int,std::string
>>>(keyFiles
);
1243 if (certFilesVect
.size() == keyFilesVect
.size()) {
1244 for (size_t idx
= 0; idx
< certFilesVect
.size(); idx
++) {
1245 certKeys
.push_back({certFilesVect
.at(idx
).second
, keyFilesVect
.at(idx
).second
});
1249 errlog("Error, mismatching number of certificates and keys in call to addDNSCryptBind!");
1250 g_outputBuffer
="Error, mismatching number of certificates and keys in call to addDNSCryptBind()!";
1255 errlog("Error, mismatching number of certificates and keys in call to addDNSCryptBind()!");
1256 g_outputBuffer
="Error, mismatching number of certificates and keys in call to addDNSCryptBind()!";
1261 auto ctx
= std::make_shared
<DNSCryptContext
>(providerName
, certKeys
);
1264 auto cs
= std::unique_ptr
<ClientState
>(new ClientState(ComboAddress(addr
, 443), false, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
));
1265 cs
->dnscryptCtx
= ctx
;
1266 g_dnsCryptLocals
.push_back(ctx
);
1267 g_frontends
.push_back(std::move(cs
));
1270 cs
= std::unique_ptr
<ClientState
>(new ClientState(ComboAddress(addr
, 443), true, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
));
1271 cs
->dnscryptCtx
= ctx
;
1272 if (tcpListenQueueSize
> 0) {
1273 cs
->tcpListenQueueSize
= tcpListenQueueSize
;
1276 g_frontends
.push_back(std::move(cs
));
1278 catch(std::exception
& e
) {
1280 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1283 g_outputBuffer
="Error: DNSCrypt support is not enabled.\n";
1288 g_lua
.writeFunction("showDNSCryptBinds", []() {
1289 setLuaNoSideEffect();
1290 #ifdef HAVE_DNSCRYPT
1292 boost::format
fmt("%1$-3d %2% %|25t|%3$-20.20s");
1293 ret
<< (fmt
% "#" % "Address" % "Provider Name") << endl
;
1296 std::unordered_set
<std::shared_ptr
<DNSCryptContext
>> contexts
;
1297 for (const auto& frontend
: g_frontends
) {
1298 const std::shared_ptr
<DNSCryptContext
> ctx
= frontend
->dnscryptCtx
;
1299 if (!ctx
|| contexts
.count(ctx
) != 0) {
1302 contexts
.insert(ctx
);
1303 ret
<< (fmt
% idx
% frontend
->local
.toStringWithPort() % ctx
->getProviderName()) << endl
;
1307 g_outputBuffer
=ret
.str();
1309 g_outputBuffer
="Error: DNSCrypt support is not enabled.\n";
1313 g_lua
.writeFunction("getDNSCryptBind", [](size_t idx
) {
1314 setLuaNoSideEffect();
1315 #ifdef HAVE_DNSCRYPT
1316 std::shared_ptr
<DNSCryptContext
> ret
= nullptr;
1317 if (idx
< g_dnsCryptLocals
.size()) {
1318 ret
= g_dnsCryptLocals
.at(idx
);
1322 g_outputBuffer
="Error: DNSCrypt support is not enabled.\n";
1326 g_lua
.writeFunction("getDNSCryptBindCount", []() {
1327 setLuaNoSideEffect();
1328 return g_dnsCryptLocals
.size();
1331 g_lua
.writeFunction("generateDNSCryptProviderKeys", [client
](const std::string
& publicKeyFile
, const std::string privateKeyFile
) {
1332 setLuaNoSideEffect();
1333 #ifdef HAVE_DNSCRYPT
1337 unsigned char publicKey
[DNSCRYPT_PROVIDER_PUBLIC_KEY_SIZE
];
1338 unsigned char privateKey
[DNSCRYPT_PROVIDER_PRIVATE_KEY_SIZE
];
1339 sodium_mlock(privateKey
, sizeof(privateKey
));
1342 DNSCryptContext::generateProviderKeys(publicKey
, privateKey
);
1344 ofstream
pubKStream(publicKeyFile
);
1345 pubKStream
.write((char*) publicKey
, sizeof(publicKey
));
1348 ofstream
privKStream(privateKeyFile
);
1349 privKStream
.write((char*) privateKey
, sizeof(privateKey
));
1350 privKStream
.close();
1352 g_outputBuffer
="Provider fingerprint is: " + DNSCryptContext::getProviderFingerprint(publicKey
) + "\n";
1354 catch(std::exception
& e
) {
1356 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1359 sodium_memzero(privateKey
, sizeof(privateKey
));
1360 sodium_munlock(privateKey
, sizeof(privateKey
));
1362 g_outputBuffer
="Error: DNSCrypt support is not enabled.\n";
1366 g_lua
.writeFunction("printDNSCryptProviderFingerprint", [](const std::string
& publicKeyFile
) {
1367 setLuaNoSideEffect();
1368 #ifdef HAVE_DNSCRYPT
1369 unsigned char publicKey
[DNSCRYPT_PROVIDER_PUBLIC_KEY_SIZE
];
1372 ifstream
file(publicKeyFile
);
1373 file
.read((char *) &publicKey
, sizeof(publicKey
));
1376 throw std::runtime_error("Invalid dnscrypt provider public key file " + publicKeyFile
);
1379 g_outputBuffer
="Provider fingerprint is: " + DNSCryptContext::getProviderFingerprint(publicKey
) + "\n";
1381 catch(std::exception
& e
) {
1383 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1386 g_outputBuffer
="Error: DNSCrypt support is not enabled.\n";
1390 #ifdef HAVE_DNSCRYPT
1391 g_lua
.writeFunction("generateDNSCryptCertificate", [client
](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
) {
1392 setLuaNoSideEffect();
1396 DNSCryptPrivateKey privateKey
;
1400 if (generateDNSCryptCertificate(providerPrivateKeyFile
, serial
, begin
, end
, version
? *version
: DNSCryptExchangeVersion::VERSION1
, cert
, privateKey
)) {
1401 privateKey
.saveToFile(privateKeyFile
);
1402 DNSCryptContext::saveCertFromFile(cert
, certificateFile
);
1405 catch(const std::exception
& e
) {
1407 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1412 g_lua
.writeFunction("showPools", []() {
1413 setLuaNoSideEffect();
1416 boost::format
fmt("%1$-20.20s %|25t|%2$20s %|25t|%3$20s %|50t|%4%" );
1418 ret
<< (fmt
% "Name" % "Cache" % "ServerPolicy" % "Servers" ) << endl
;
1420 const auto localPools
= g_pools
.getCopy();
1421 for (const auto& entry
: localPools
) {
1422 const string
& name
= entry
.first
;
1423 const std::shared_ptr
<ServerPool
> pool
= entry
.second
;
1424 string cache
= pool
->packetCache
!= nullptr ? pool
->packetCache
->toString() : "";
1425 string policy
= g_policy
.getLocal()->name
;
1426 if (pool
->policy
!= nullptr) {
1427 policy
= pool
->policy
->name
;
1431 for (const auto& server
: pool
->getServers()) {
1432 if (!servers
.empty()) {
1435 if (!server
.second
->getName().empty()) {
1436 servers
+= server
.second
->getName();
1439 servers
+= server
.second
->remote
.toStringWithPort();
1442 ret
<< (fmt
% name
% cache
% policy
% servers
) << endl
;
1444 g_outputBuffer
=ret
.str();
1445 }catch(std::exception
& e
) { g_outputBuffer
=e
.what(); throw; }
1448 g_lua
.writeFunction("getPool", [client
](const string
& poolName
) {
1450 return std::make_shared
<ServerPool
>();
1452 auto localPools
= g_pools
.getCopy();
1453 std::shared_ptr
<ServerPool
> pool
= createPoolIfNotExists(localPools
, poolName
);
1454 g_pools
.setState(localPools
);
1458 g_lua
.writeFunction("setVerboseHealthChecks", [](bool verbose
) { g_verboseHealthChecks
=verbose
; });
1459 g_lua
.writeFunction("setStaleCacheEntriesTTL", [](uint32_t ttl
) { g_staleCacheEntriesTTL
= ttl
; });
1461 g_lua
.writeFunction("showBinds", []() {
1462 setLuaNoSideEffect();
1465 boost::format
fmt("%1$-3d %2$-20.20s %|35t|%3$-20.20s %|57t|%4%" );
1467 ret
<< (fmt
% "#" % "Address" % "Protocol" % "Queries" ) << endl
;
1470 for (const auto& front
: g_frontends
) {
1471 ret
<< (fmt
% counter
% front
->local
.toStringWithPort() % front
->getType() % front
->queries
) << endl
;
1474 g_outputBuffer
=ret
.str();
1475 }catch(std::exception
& e
) { g_outputBuffer
=e
.what(); throw; }
1478 g_lua
.writeFunction("getBind", [](size_t num
) {
1479 setLuaNoSideEffect();
1480 ClientState
* ret
= nullptr;
1481 if(num
< g_frontends
.size()) {
1482 ret
=g_frontends
[num
].get();
1487 g_lua
.writeFunction("getBindCount", []() {
1488 setLuaNoSideEffect();
1489 return g_frontends
.size();
1492 g_lua
.writeFunction("help", [](boost::optional
<std::string
> command
) {
1493 setLuaNoSideEffect();
1494 g_outputBuffer
= "";
1495 for (const auto& keyword
: g_consoleKeywords
) {
1497 g_outputBuffer
+= keyword
.toString() + "\n";
1499 else if (keyword
.name
== command
) {
1500 g_outputBuffer
= keyword
.toString() + "\n";
1505 g_outputBuffer
= "Nothing found for " + *command
+ "\n";
1509 g_lua
.writeFunction("showVersion", []() {
1510 setLuaNoSideEffect();
1511 g_outputBuffer
= "dnsdist " + std::string(VERSION
) + "\n";
1514 g_lua
.writeFunction("showSecurityStatus", []() {
1515 setLuaNoSideEffect();
1516 g_outputBuffer
= std::to_string(g_stats
.securityStatus
) + "\n";
1520 g_lua
.writeFunction("setDefaultBPFFilter", [](std::shared_ptr
<BPFFilter
> bpf
) {
1521 if (g_configurationDone
) {
1522 g_outputBuffer
="setDefaultBPFFilter() cannot be used at runtime!\n";
1525 g_defaultBPFFilter
= bpf
;
1528 g_lua
.writeFunction("registerDynBPFFilter", [](std::shared_ptr
<DynBPFFilter
> dbpf
) {
1530 g_dynBPFFilters
.push_back(dbpf
);
1534 g_lua
.writeFunction("unregisterDynBPFFilter", [](std::shared_ptr
<DynBPFFilter
> dbpf
) {
1536 for (auto it
= g_dynBPFFilters
.begin(); it
!= g_dynBPFFilters
.end(); it
++) {
1538 g_dynBPFFilters
.erase(it
);
1545 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
) {
1547 struct timespec until
, now
;
1548 clock_gettime(CLOCK_MONOTONIC
, &now
);
1550 int actualSeconds
= seconds
? *seconds
: 10;
1551 until
.tv_sec
+= actualSeconds
;
1552 for(const auto& capair
: m
) {
1553 if (dynbpf
->block(capair
.first
, until
)) {
1554 warnlog("Inserting eBPF dynamic block for %s for %d seconds: %s", capair
.first
.toString(), actualSeconds
, msg
? *msg
: "");
1559 #endif /* HAVE_EBPF */
1561 g_lua
.writeFunction
<std::unordered_map
<string
,uint64_t>()>("getStatisticsCounters", []() {
1562 setLuaNoSideEffect();
1563 std::unordered_map
<string
,uint64_t> res
;
1564 for(const auto& entry
: g_stats
.entries
) {
1565 if(const auto& val
= boost::get
<DNSDistStats::stat_t
*>(&entry
.second
))
1566 res
[entry
.first
] = (*val
)->load();
1571 g_lua
.writeFunction("includeDirectory", [](const std::string
& dirname
) {
1572 if (g_configurationDone
) {
1573 errlog("includeDirectory() cannot be used at runtime!");
1574 g_outputBuffer
="includeDirectory() cannot be used at runtime!\n";
1579 errlog("includeDirectory() cannot be used recursively!");
1580 g_outputBuffer
="includeDirectory() cannot be used recursively!\n";
1586 if (stat(dirname
.c_str(), &st
)) {
1587 errlog("The included directory %s does not exist!", dirname
.c_str());
1588 g_outputBuffer
="The included directory " + dirname
+ " does not exist!";
1592 if (!S_ISDIR(st
.st_mode
)) {
1593 errlog("The included directory %s is not a directory!", dirname
.c_str());
1594 g_outputBuffer
="The included directory " + dirname
+ " is not a directory!";
1600 std::list
<std::string
> files
;
1601 if (!(dirp
= opendir(dirname
.c_str()))) {
1602 errlog("Error opening the included directory %s!", dirname
.c_str());
1603 g_outputBuffer
="Error opening the included directory " + dirname
+ "!";
1607 while((ent
= readdir(dirp
)) != NULL
) {
1608 if (ent
->d_name
[0] == '.') {
1612 if (boost::ends_with(ent
->d_name
, ".conf")) {
1613 std::ostringstream namebuf
;
1614 namebuf
<< dirname
.c_str() << "/" << ent
->d_name
;
1616 if (stat(namebuf
.str().c_str(), &st
) || !S_ISREG(st
.st_mode
)) {
1620 files
.push_back(namebuf
.str());
1627 for (auto file
= files
.begin(); file
!= files
.end(); ++file
) {
1628 std::ifstream
ifs(*file
);
1630 warnlog("Unable to read configuration from '%s'", *file
);
1632 vinfolog("Read configuration from '%s'", *file
);
1635 g_lua
.executeCode(ifs
);
1641 g_lua
.writeFunction("setAPIWritable", [](bool writable
, boost::optional
<std::string
> apiConfigDir
) {
1643 g_apiReadWrite
= writable
;
1645 if (!(*apiConfigDir
).empty()) {
1646 g_apiConfigDirectory
= *apiConfigDir
;
1649 errlog("The API configuration directory value cannot be empty!");
1650 g_outputBuffer
="The API configuration directory value cannot be empty!";
1655 g_lua
.writeFunction("setServFailWhenNoServer", [](bool servfail
) {
1657 g_servFailOnNoPolicy
= servfail
;
1660 g_lua
.writeFunction("setRoundRobinFailOnNoServer", [](bool fail
) {
1662 g_roundrobinFailOnNoServer
= fail
;
1665 g_lua
.writeFunction("setConsistentHashingBalancingFactor", [](double factor
) {
1667 if (factor
>= 1.0) {
1668 g_consistentHashBalancingFactor
= factor
;
1671 errlog("Invalid value passed to setConsistentHashingBalancingFactor()!");
1672 g_outputBuffer
="Invalid value passed to setConsistentHashingBalancingFactor()!\n";
1677 g_lua
.writeFunction("setWeightedBalancingFactor", [](double factor
) {
1679 if (factor
>= 1.0) {
1680 g_weightedBalancingFactor
= factor
;
1683 errlog("Invalid value passed to setWeightedBalancingFactor()!");
1684 g_outputBuffer
="Invalid value passed to setWeightedBalancingFactor()!\n";
1689 g_lua
.writeFunction("setRingBuffersSize", [](size_t capacity
, boost::optional
<size_t> numberOfShards
) {
1691 if (g_configurationDone
) {
1692 errlog("setRingBuffersSize() cannot be used at runtime!");
1693 g_outputBuffer
="setRingBuffersSize() cannot be used at runtime!\n";
1696 g_rings
.setCapacity(capacity
, numberOfShards
? *numberOfShards
: 1);
1699 g_lua
.writeFunction("setRingBuffersLockRetries", [](size_t retries
) {
1701 g_rings
.setNumberOfLockRetries(retries
);
1704 g_lua
.writeFunction("setWHashedPertubation", [](uint32_t pertub
) {
1706 g_hashperturb
= pertub
;
1709 g_lua
.writeFunction("setTCPUseSinglePipe", [](bool flag
) {
1710 if (g_configurationDone
) {
1711 g_outputBuffer
="setTCPUseSinglePipe() cannot be used at runtime!\n";
1715 g_useTCPSinglePipe
= flag
;
1718 g_lua
.writeFunction("snmpAgent", [client
,configCheck
](bool enableTraps
, boost::optional
<std::string
> masterSocket
) {
1719 if(client
|| configCheck
)
1721 #ifdef HAVE_NET_SNMP
1722 if (g_configurationDone
) {
1723 errlog("snmpAgent() cannot be used at runtime!");
1724 g_outputBuffer
="snmpAgent() cannot be used at runtime!\n";
1728 if (g_snmpEnabled
) {
1729 errlog("snmpAgent() cannot be used twice!");
1730 g_outputBuffer
="snmpAgent() cannot be used twice!\n";
1734 g_snmpEnabled
= true;
1735 g_snmpTrapsEnabled
= enableTraps
;
1736 g_snmpAgent
= new DNSDistSNMPAgent("dnsdist", masterSocket
? *masterSocket
: std::string());
1738 errlog("NET SNMP support is required to use snmpAgent()");
1739 g_outputBuffer
="NET SNMP support is required to use snmpAgent()\n";
1740 #endif /* HAVE_NET_SNMP */
1743 g_lua
.writeFunction("sendCustomTrap", [](const std::string
& str
) {
1744 if (g_snmpAgent
&& g_snmpTrapsEnabled
) {
1745 g_snmpAgent
->sendCustomTrap(str
);
1749 g_lua
.writeFunction("setServerPolicy", [](ServerPolicy policy
) {
1751 g_policy
.setState(policy
);
1754 g_lua
.writeFunction("setServerPolicyLua", [](string name
, ServerPolicy::policyfunc_t policy
) {
1756 g_policy
.setState(ServerPolicy
{name
, policy
, true});
1759 g_lua
.writeFunction("setServerPolicyLuaFFI", [](string name
, ServerPolicy::ffipolicyfunc_t policy
) {
1761 auto pol
= ServerPolicy(name
, policy
);
1762 g_policy
.setState(std::move(pol
));
1765 g_lua
.writeFunction("showServerPolicy", []() {
1767 g_outputBuffer
=g_policy
.getLocal()->name
+"\n";
1770 g_lua
.writeFunction("setPoolServerPolicy", [](ServerPolicy policy
, string pool
) {
1772 auto localPools
= g_pools
.getCopy();
1773 setPoolPolicy(localPools
, pool
, std::make_shared
<ServerPolicy
>(policy
));
1774 g_pools
.setState(localPools
);
1777 g_lua
.writeFunction("setPoolServerPolicyLua", [](string name
, ServerPolicy::policyfunc_t policy
, string pool
) {
1779 auto localPools
= g_pools
.getCopy();
1780 setPoolPolicy(localPools
, pool
, std::make_shared
<ServerPolicy
>(ServerPolicy
{name
, policy
, true}));
1781 g_pools
.setState(localPools
);
1784 g_lua
.writeFunction("showPoolServerPolicy", [](string pool
) {
1786 auto localPools
= g_pools
.getCopy();
1787 auto poolObj
= getPool(localPools
, pool
);
1788 if (poolObj
->policy
== nullptr) {
1789 g_outputBuffer
=g_policy
.getLocal()->name
+"\n";
1791 g_outputBuffer
=poolObj
->policy
->name
+"\n";
1795 g_lua
.writeFunction("setTCPDownstreamCleanupInterval", [](uint16_t interval
) {
1797 g_downstreamTCPCleanupInterval
= interval
;
1800 g_lua
.writeFunction("setConsoleConnectionsLogging", [](bool enabled
) {
1801 g_logConsoleConnections
= enabled
;
1804 g_lua
.writeFunction("setConsoleOutputMaxMsgSize", [](uint32_t size
) {
1805 g_consoleOutputMsgMaxSize
= size
;
1808 g_lua
.writeFunction("setUDPMultipleMessagesVectorSize", [](size_t vSize
) {
1809 if (g_configurationDone
) {
1810 errlog("setUDPMultipleMessagesVectorSize() cannot be used at runtime!");
1811 g_outputBuffer
="setUDPMultipleMessagesVectorSize() cannot be used at runtime!\n";
1814 #if defined(HAVE_RECVMMSG) && defined(HAVE_SENDMMSG) && defined(MSG_WAITFORONE)
1816 g_udpVectorSize
= vSize
;
1818 errlog("recvmmsg() support is not available!");
1819 g_outputBuffer
="recvmmsg support is not available!\n";
1823 g_lua
.writeFunction("setAddEDNSToSelfGeneratedResponses", [](bool add
) {
1824 g_addEDNSToSelfGeneratedResponses
= add
;
1827 g_lua
.writeFunction("setPayloadSizeOnSelfGeneratedAnswers", [](uint16_t payloadSize
) {
1828 if (payloadSize
< 512) {
1829 warnlog("setPayloadSizeOnSelfGeneratedAnswers() is set too low, using 512 instead!");
1830 g_outputBuffer
="setPayloadSizeOnSelfGeneratedAnswers() is set too low, using 512 instead!";
1833 if (payloadSize
> s_udpIncomingBufferSize
) {
1834 warnlog("setPayloadSizeOnSelfGeneratedAnswers() is set too high, capping to %d instead!", s_udpIncomingBufferSize
);
1835 g_outputBuffer
="setPayloadSizeOnSelfGeneratedAnswers() is set too high, capping to " + std::to_string(s_udpIncomingBufferSize
) + " instead";
1836 payloadSize
= s_udpIncomingBufferSize
;
1838 g_PayloadSizeSelfGenAnswers
= payloadSize
;
1841 g_lua
.writeFunction("setSecurityPollSuffix", [](const std::string
& suffix
) {
1842 if (g_configurationDone
) {
1843 g_outputBuffer
="setSecurityPollSuffix() cannot be used at runtime!\n";
1847 g_secPollSuffix
= suffix
;
1850 g_lua
.writeFunction("setSecurityPollInterval", [](time_t newInterval
) {
1851 if (newInterval
<= 0) {
1852 warnlog("setSecurityPollInterval() should be > 0, skipping");
1853 g_outputBuffer
="setSecurityPollInterval() should be > 0, skipping";
1856 g_secPollInterval
= newInterval
;
1859 g_lua
.writeFunction("setSyslogFacility", [](int facility
) {
1861 if (g_configurationDone
) {
1862 g_outputBuffer
="setSyslogFacility cannot be used at runtime!\n";
1865 setSyslogFacility(facility
);
1868 g_lua
.writeFunction("addDOHLocal", [client
](const std::string
& addr
, boost::optional
<boost::variant
<std::string
, std::vector
<std::pair
<int,std::string
>>>> certFiles
, boost::optional
<boost::variant
<std::string
, std::vector
<std::pair
<int,std::string
>>>> keyFiles
, boost::optional
<boost::variant
<std::string
, vector
<pair
<int, std::string
> > > > urls
, boost::optional
<localbind_t
> vars
) {
1872 #ifdef HAVE_DNS_OVER_HTTPS
1874 if (g_configurationDone
) {
1875 g_outputBuffer
="addDOHLocal cannot be used at runtime!\n";
1878 auto frontend
= std::make_shared
<DOHFrontend
>();
1880 if (certFiles
&& !certFiles
->empty() && keyFiles
&& !keyFiles
->empty()) {
1881 if (!loadTLSCertificateAndKeys("addDOHLocal", frontend
->d_tlsConfig
.d_certKeyPairs
, *certFiles
, *keyFiles
)) {
1885 frontend
->d_local
= ComboAddress(addr
, 443);
1888 frontend
->d_local
= ComboAddress(addr
, 80);
1889 infolog("No certificate provided for DoH endpoint %s, running in DNS over HTTP mode instead of DNS over HTTPS", frontend
->d_local
.toStringWithPort());
1893 if (urls
->type() == typeid(std::string
)) {
1894 frontend
->d_urls
.push_back(boost::get
<std::string
>(*urls
));
1896 else if (urls
->type() == typeid(std::vector
<std::pair
<int,std::string
>>)) {
1897 auto urlsVect
= boost::get
<std::vector
<std::pair
<int,std::string
>>>(*urls
);
1898 for(const auto& p
: urlsVect
) {
1899 frontend
->d_urls
.push_back(p
.second
);
1904 frontend
->d_urls
= {"/dns-query"};
1907 bool reusePort
= false;
1908 int tcpFastOpenQueueSize
= 0;
1909 int tcpListenQueueSize
= 0;
1910 std::string interface
;
1914 parseLocalBindVars(vars
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
, tcpListenQueueSize
);
1916 if (vars
->count("idleTimeout")) {
1917 frontend
->d_idleTimeout
= boost::get
<int>((*vars
)["idleTimeout"]);
1920 if (vars
->count("serverTokens")) {
1921 frontend
->d_serverTokens
= boost::get
<const string
>((*vars
)["serverTokens"]);
1924 if (vars
->count("customResponseHeaders")) {
1925 for (auto const& headerMap
: boost::get
<std::map
<std::string
,std::string
>>((*vars
)["customResponseHeaders"])) {
1926 std::pair
<std::string
,std::string
> headerResponse
= std::make_pair(boost::to_lower_copy(headerMap
.first
), headerMap
.second
);
1927 frontend
->d_customResponseHeaders
.push_back(headerResponse
);
1931 if (vars
->count("sendCacheControlHeaders")) {
1932 frontend
->d_sendCacheControlHeaders
= boost::get
<bool>((*vars
)["sendCacheControlHeaders"]);
1935 if (vars
->count("trustForwardedForHeader")) {
1936 frontend
->d_trustForwardedForHeader
= boost::get
<bool>((*vars
)["trustForwardedForHeader"]);
1939 parseTLSConfig(frontend
->d_tlsConfig
, "addDOHLocal", vars
);
1941 g_dohlocals
.push_back(frontend
);
1942 auto cs
= std::unique_ptr
<ClientState
>(new ClientState(frontend
->d_local
, true, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
));
1943 cs
->dohFrontend
= frontend
;
1944 if (tcpListenQueueSize
> 0) {
1945 cs
->tcpListenQueueSize
= tcpListenQueueSize
;
1948 g_frontends
.push_back(std::move(cs
));
1950 throw std::runtime_error("addDOHLocal() called but DNS over HTTPS support is not present!");
1954 g_lua
.writeFunction("showDOHFrontends", []() {
1955 #ifdef HAVE_DNS_OVER_HTTPS
1956 setLuaNoSideEffect();
1959 boost::format
fmt("%-3d %-20.20s %-15d %-15d %-15d %-15d %-15d %-15d %-15d %-15d %-15d %-15d %-15d %-15d");
1960 ret
<< (fmt
% "#" % "Address" % "HTTP" % "HTTP/1" % "HTTP/2" % "GET" % "POST" % "Bad" % "Errors" % "Redirects" % "Valid" % "# ticket keys" % "Rotation delay" % "Next rotation") << endl
;
1962 for (const auto& ctx
: g_dohlocals
) {
1963 ret
<< (fmt
% counter
% ctx
->d_local
.toStringWithPort() % ctx
->d_httpconnects
% ctx
->d_http1Stats
.d_nbQueries
% ctx
->d_http2Stats
.d_nbQueries
% ctx
->d_getqueries
% ctx
->d_postqueries
% ctx
->d_badrequests
% ctx
->d_errorresponses
% ctx
->d_redirectresponses
% ctx
->d_validresponses
% ctx
->getTicketsKeysCount() % ctx
->getTicketsKeyRotationDelay() % ctx
->getNextTicketsKeyRotation()) << endl
;
1966 g_outputBuffer
= ret
.str();
1968 catch(const std::exception
& e
) {
1969 g_outputBuffer
= e
.what();
1973 g_outputBuffer
="DNS over HTTPS support is not present!\n";
1977 g_lua
.writeFunction("showDOHResponseCodes", []() {
1978 #ifdef HAVE_DNS_OVER_HTTPS
1979 setLuaNoSideEffect();
1982 boost::format
fmt("%-3d %-20.20s %-15d %-15d %-15d %-15d %-15d %-15d");
1983 g_outputBuffer
= "\n- HTTP/1:\n\n";
1984 ret
<< (fmt
% "#" % "Address" % "200" % "400" % "403" % "500" % "502" % "Others" ) << endl
;
1986 for (const auto& ctx
: g_dohlocals
) {
1987 ret
<< (fmt
% counter
% ctx
->d_local
.toStringWithPort() % ctx
->d_http1Stats
.d_nb200Responses
% ctx
->d_http1Stats
.d_nb400Responses
% ctx
->d_http1Stats
.d_nb403Responses
% ctx
->d_http1Stats
.d_nb500Responses
% ctx
->d_http1Stats
.d_nb502Responses
% ctx
->d_http1Stats
.d_nbOtherResponses
) << endl
;
1990 g_outputBuffer
+= ret
.str();
1993 g_outputBuffer
+= "\n- HTTP/2:\n\n";
1994 ret
<< (fmt
% "#" % "Address" % "200" % "400" % "403" % "500" % "502" % "Others" ) << endl
;
1996 for (const auto& ctx
: g_dohlocals
) {
1997 ret
<< (fmt
% counter
% ctx
->d_local
.toStringWithPort() % ctx
->d_http2Stats
.d_nb200Responses
% ctx
->d_http2Stats
.d_nb400Responses
% ctx
->d_http2Stats
.d_nb403Responses
% ctx
->d_http2Stats
.d_nb500Responses
% ctx
->d_http2Stats
.d_nb502Responses
% ctx
->d_http2Stats
.d_nbOtherResponses
) << endl
;
2000 g_outputBuffer
+= ret
.str();
2002 catch(const std::exception
& e
) {
2003 g_outputBuffer
= e
.what();
2007 g_outputBuffer
="DNS over HTTPS support is not present!\n";
2011 g_lua
.writeFunction("getDOHFrontend", [client
](size_t index
) {
2012 std::shared_ptr
<DOHFrontend
> result
= nullptr;
2016 #ifdef HAVE_DNS_OVER_HTTPS
2017 setLuaNoSideEffect();
2019 if (index
< g_dohlocals
.size()) {
2020 result
= g_dohlocals
.at(index
);
2023 errlog("Error: trying to get DOH frontend with index %zu but we only have %zu frontend(s)\n", index
, g_dohlocals
.size());
2024 g_outputBuffer
="Error: trying to get DOH frontend with index " + std::to_string(index
) + " but we only have " + std::to_string(g_dohlocals
.size()) + " frontend(s)\n";
2027 catch(const std::exception
& e
) {
2028 g_outputBuffer
="Error while trying to get DOH frontend with index " + std::to_string(index
) + ": "+string(e
.what())+"\n";
2029 errlog("Error while trying to get DOH frontend with index %zu: %s\n", index
, string(e
.what()));
2032 g_outputBuffer
="DNS over HTTPS support is not present!\n";
2037 g_lua
.writeFunction("getDOHFrontendCount", []() {
2038 setLuaNoSideEffect();
2039 return g_dohlocals
.size();
2042 g_lua
.registerFunction
<void(std::shared_ptr
<DOHFrontend
>::*)()>("reloadCertificates", [](std::shared_ptr
<DOHFrontend
> frontend
) {
2043 if (frontend
!= nullptr) {
2044 frontend
->reloadCertificates();
2048 g_lua
.registerFunction
<void(std::shared_ptr
<DOHFrontend
>::*)()>("rotateTicketsKey", [](std::shared_ptr
<DOHFrontend
> frontend
) {
2049 if (frontend
!= nullptr) {
2050 frontend
->rotateTicketsKey(time(nullptr));
2054 g_lua
.registerFunction
<void(std::shared_ptr
<DOHFrontend
>::*)(const std::string
&)>("loadTicketsKeys", [](std::shared_ptr
<DOHFrontend
> frontend
, const std::string
& file
) {
2055 if (frontend
!= nullptr) {
2056 frontend
->loadTicketsKeys(file
);
2060 g_lua
.registerFunction
<void(std::shared_ptr
<DOHFrontend
>::*)(const std::map
<int, std::shared_ptr
<DOHResponseMapEntry
>>&)>("setResponsesMap", [](std::shared_ptr
<DOHFrontend
> frontend
, const std::map
<int, std::shared_ptr
<DOHResponseMapEntry
>>& map
) {
2061 if (frontend
!= nullptr) {
2062 std::vector
<std::shared_ptr
<DOHResponseMapEntry
>> newMap
;
2063 newMap
.reserve(map
.size());
2065 for (const auto& entry
: map
) {
2066 newMap
.push_back(entry
.second
);
2069 frontend
->d_responsesMap
= std::move(newMap
);
2073 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
) {
2077 #ifdef HAVE_DNS_OVER_TLS
2079 if (g_configurationDone
) {
2080 g_outputBuffer
="addTLSLocal cannot be used at runtime!\n";
2083 shared_ptr
<TLSFrontend
> frontend
= std::make_shared
<TLSFrontend
>();
2085 if (!loadTLSCertificateAndKeys("addTLSLocal", frontend
->d_tlsConfig
.d_certKeyPairs
, certFiles
, keyFiles
)) {
2089 bool reusePort
= false;
2090 int tcpFastOpenQueueSize
= 0;
2091 int tcpListenQueueSize
= 0;
2092 std::string interface
;
2096 parseLocalBindVars(vars
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
, tcpListenQueueSize
);
2098 if (vars
->count("provider")) {
2099 frontend
->d_provider
= boost::get
<const string
>((*vars
)["provider"]);
2100 boost::algorithm::to_lower(frontend
->d_provider
);
2103 parseTLSConfig(frontend
->d_tlsConfig
, "addTLSLocal", vars
);
2107 frontend
->d_addr
= ComboAddress(addr
, 853);
2108 if (!frontend
->d_provider
.empty()) {
2109 vinfolog("Loading TLS provider '%s'", frontend
->d_provider
);
2113 vinfolog("Loading default TLS provider 'openssl'");
2115 vinfolog("Loading default TLS provider 'gnutls'");
2118 // only works pre-startup, so no sync necessary
2119 auto cs
= std::unique_ptr
<ClientState
>(new ClientState(frontend
->d_addr
, true, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
));
2120 cs
->tlsFrontend
= frontend
;
2121 if (tcpListenQueueSize
> 0) {
2122 cs
->tcpListenQueueSize
= tcpListenQueueSize
;
2124 g_tlslocals
.push_back(cs
->tlsFrontend
);
2125 g_frontends
.push_back(std::move(cs
));
2127 catch(const std::exception
& e
) {
2128 g_outputBuffer
="Error: "+string(e
.what())+"\n";
2131 throw std::runtime_error("addTLSLocal() called but DNS over TLS support is not present!");
2135 g_lua
.writeFunction("showTLSContexts", []() {
2136 #ifdef HAVE_DNS_OVER_TLS
2137 setLuaNoSideEffect();
2140 boost::format
fmt("%1$-3d %2$-20.20s %|25t|%3$-14d %|40t|%4$-14d %|54t|%5$-21.21s");
2142 ret
<< (fmt
% "#" % "Address" % "# ticket keys" % "Rotation delay" % "Next rotation" ) << endl
;
2144 for (const auto& ctx
: g_tlslocals
) {
2145 ret
<< (fmt
% counter
% ctx
->d_addr
.toStringWithPort() % ctx
->getTicketsKeysCount() % ctx
->getTicketsKeyRotationDelay() % ctx
->getNextTicketsKeyRotation()) << endl
;
2148 g_outputBuffer
= ret
.str();
2150 catch(const std::exception
& e
) {
2151 g_outputBuffer
= e
.what();
2155 g_outputBuffer
="DNS over TLS support is not present!\n";
2159 g_lua
.writeFunction("getTLSContext", [](size_t index
) {
2160 std::shared_ptr
<TLSCtx
> result
= nullptr;
2161 #ifdef HAVE_DNS_OVER_TLS
2162 setLuaNoSideEffect();
2164 if (index
< g_tlslocals
.size()) {
2165 result
= g_tlslocals
.at(index
)->getContext();
2168 errlog("Error: trying to get TLS context with index %zu but we only have %zu context(s)\n", index
, g_tlslocals
.size());
2169 g_outputBuffer
="Error: trying to get TLS context with index " + std::to_string(index
) + " but we only have " + std::to_string(g_tlslocals
.size()) + " context(s)\n";
2172 catch(const std::exception
& e
) {
2173 g_outputBuffer
="Error while trying to get TLS context with index " + std::to_string(index
) + ": "+string(e
.what())+"\n";
2174 errlog("Error while trying to get TLS context with index %zu: %s\n", index
, string(e
.what()));
2177 g_outputBuffer
="DNS over TLS support is not present!\n";
2182 g_lua
.writeFunction("getTLSFrontend", [](size_t index
) {
2183 std::shared_ptr
<TLSFrontend
> result
= nullptr;
2184 #ifdef HAVE_DNS_OVER_TLS
2185 setLuaNoSideEffect();
2187 if (index
< g_tlslocals
.size()) {
2188 result
= g_tlslocals
.at(index
);
2191 errlog("Error: trying to get TLS frontend with index %zu but we only have %zu frontends\n", index
, g_tlslocals
.size());
2192 g_outputBuffer
="Error: trying to get TLS frontend with index " + std::to_string(index
) + " but we only have " + std::to_string(g_tlslocals
.size()) + " frontend(s)\n";
2195 catch(const std::exception
& e
) {
2196 g_outputBuffer
="Error while trying to get TLS frontend with index " + std::to_string(index
) + ": "+string(e
.what())+"\n";
2197 errlog("Error while trying to get TLS frontend with index %zu: %s\n", index
, string(e
.what()));
2200 g_outputBuffer
="DNS over TLS support is not present!\n";
2205 g_lua
.writeFunction("getTLSFrontendCount", []() {
2206 setLuaNoSideEffect();
2207 return g_tlslocals
.size();
2210 g_lua
.registerFunction
<void(std::shared_ptr
<TLSCtx
>::*)()>("rotateTicketsKey", [](std::shared_ptr
<TLSCtx
> ctx
) {
2211 if (ctx
!= nullptr) {
2212 ctx
->rotateTicketsKey(time(nullptr));
2216 g_lua
.registerFunction
<void(std::shared_ptr
<TLSCtx
>::*)(const std::string
&)>("loadTicketsKeys", [](std::shared_ptr
<TLSCtx
> ctx
, const std::string
& file
) {
2217 if (ctx
!= nullptr) {
2218 ctx
->loadTicketsKeys(file
);
2222 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
) {
2223 #ifdef HAVE_DNS_OVER_TLS
2224 if (loadTLSCertificateAndKeys("loadNewCertificatesAndKeys", frontend
->d_tlsConfig
.d_certKeyPairs
, certFiles
, keyFiles
)) {
2225 frontend
->setupTLS();
2230 g_lua
.writeFunction("reloadAllCertificates", []() {
2231 for (auto& frontend
: g_frontends
) {
2236 #ifdef HAVE_DNSCRYPT
2237 if (frontend
->dnscryptCtx
) {
2238 frontend
->dnscryptCtx
->reloadCertificates();
2240 #endif /* HAVE_DNSCRYPT */
2241 #ifdef HAVE_DNS_OVER_TLS
2242 if (frontend
->tlsFrontend
) {
2243 frontend
->tlsFrontend
->setupTLS();
2245 #endif /* HAVE_DNS_OVER_TLS */
2246 #ifdef HAVE_DNS_OVER_HTTPS
2247 if (frontend
->dohFrontend
) {
2248 frontend
->dohFrontend
->reloadCertificates();
2250 #endif /* HAVE_DNS_OVER_HTTPS */
2252 catch(const std::exception
& e
) {
2253 errlog("Error reloading certificates for frontend %s: %s", frontend
->local
.toStringWithPort(), e
.what());
2258 g_lua
.writeFunction("setAllowEmptyResponse", [](bool allow
) { g_allowEmptyResponse
=allow
; });
2260 #if defined(HAVE_LIBSSL) && defined(HAVE_OCSP_BASIC_SIGN)
2261 g_lua
.writeFunction("generateOCSPResponse", [client
](const std::string
& certFile
, const std::string
& caCert
, const std::string
& caKey
, const std::string
& outFile
, int ndays
, int nmin
) {
2266 libssl_generate_ocsp_response(certFile
, caCert
, caKey
, outFile
, ndays
, nmin
);
2268 #endif /* HAVE_LIBSSL && HAVE_OCSP_BASIC_SIGN*/
2271 vector
<std::function
<void(void)>> setupLua(bool client
, bool configCheck
, const std::string
& config
)
2273 g_launchWork
= new vector
<std::function
<void(void)>>();
2276 setupLuaConfig(client
, configCheck
);
2277 setupLuaBindings(client
);
2278 setupLuaBindingsDNSCrypt();
2279 setupLuaBindingsDNSQuestion();
2280 setupLuaBindingsKVS(client
);
2281 setupLuaBindingsPacketCache();
2282 setupLuaBindingsProtoBuf(client
, configCheck
);
2283 setupLuaInspection();
2287 #ifdef LUAJIT_VERSION
2288 g_lua
.executeCode(getLuaFFIWrappers());
2291 std::ifstream
ifs(config
);
2293 warnlog("Unable to read configuration from '%s'", config
);
2295 vinfolog("Read configuration from '%s'", config
);
2297 g_lua
.executeCode(ifs
);
2299 auto ret
= *g_launchWork
;
2300 delete g_launchWork
;
2301 g_launchWork
= nullptr;