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
)
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("interface")) {
110 interface
= boost::get
<std::string
>((*vars
)["interface"]);
112 if (vars
->count("cpus")) {
113 for (const auto cpu
: boost::get
<std::vector
<std::pair
<int,int>>>((*vars
)["cpus"])) {
114 cpus
.insert(cpu
.second
);
120 #if defined(HAVE_DNS_OVER_TLS) || defined(HAVE_DNS_OVER_HTTPS)
121 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
)
123 if (certFiles
.type() == typeid(std::string
) && keyFiles
.type() == typeid(std::string
)) {
124 auto certFile
= boost::get
<std::string
>(certFiles
);
125 auto keyFile
= boost::get
<std::string
>(keyFiles
);
127 pairs
.push_back({certFile
, keyFile
});
129 else if (certFiles
.type() == typeid(std::vector
<std::pair
<int,std::string
>>) && keyFiles
.type() == typeid(std::vector
<std::pair
<int,std::string
>>))
131 auto certFilesVect
= boost::get
<std::vector
<std::pair
<int,std::string
>>>(certFiles
);
132 auto keyFilesVect
= boost::get
<std::vector
<std::pair
<int,std::string
>>>(keyFiles
);
133 if (certFilesVect
.size() == keyFilesVect
.size()) {
135 for (size_t idx
= 0; idx
< certFilesVect
.size(); idx
++) {
136 pairs
.push_back({certFilesVect
.at(idx
).second
, keyFilesVect
.at(idx
).second
});
140 errlog("Error, mismatching number of certificates and keys in call to %s()!", context
);
141 g_outputBuffer
="Error, mismatching number of certificates and keys in call to " + context
+ "()!";
146 errlog("Error, mismatching number of certificates and keys in call to %s()!", context
);
147 g_outputBuffer
="Error, mismatching number of certificates and keys in call to " + context
+ "()!";
154 static void parseTLSConfig(TLSConfig
& config
, const std::string
& context
, boost::optional
<localbind_t
> vars
)
156 if (vars
->count("ciphers")) {
157 config
.d_ciphers
= boost::get
<const string
>((*vars
)["ciphers"]);
160 if (vars
->count("ciphersTLS13")) {
161 config
.d_ciphers13
= boost::get
<const string
>((*vars
)["ciphersTLS13"]);
165 if (vars
->count("minTLSVersion")) {
166 config
.d_minTLSVersion
= libssl_tls_version_from_string(boost::get
<const string
>((*vars
)["minTLSVersion"]));
168 #endif /* HAVE_LIBSSL */
170 if (vars
->count("ticketKeyFile")) {
171 config
.d_ticketKeyFile
= boost::get
<const string
>((*vars
)["ticketKeyFile"]);
174 if (vars
->count("ticketsKeysRotationDelay")) {
175 config
.d_ticketsKeyRotationDelay
= boost::get
<int>((*vars
)["ticketsKeysRotationDelay"]);
178 if (vars
->count("numberOfTicketsKeys")) {
179 config
.d_numberOfTicketsKeys
= boost::get
<int>((*vars
)["numberOfTicketsKeys"]);
182 if (vars
->count("preferServerCiphers")) {
183 config
.d_preferServerCiphers
= boost::get
<bool>((*vars
)["preferServerCiphers"]);
186 if (vars
->count("sessionTimeout")) {
187 config
.d_sessionTimeout
= boost::get
<int>((*vars
)["sessionTimeout"]);
190 if (vars
->count("sessionTickets")) {
191 config
.d_enableTickets
= boost::get
<bool>((*vars
)["sessionTickets"]);
194 if (vars
->count("numberOfStoredSessions")) {
195 auto value
= boost::get
<int>((*vars
)["numberOfStoredSessions"]);
197 errlog("Invalid value '%d' for %s() parameter 'numberOfStoredSessions', should be >= 0, dismissing", value
, context
);
198 g_outputBuffer
="Invalid value '" + std::to_string(value
) + "' for " + context
+ "() parameter 'numberOfStoredSessions', should be >= 0, dimissing";
200 config
.d_maxStoredSessions
= value
;
203 if (vars
->count("ocspResponses")) {
204 auto files
= boost::get
<std::vector
<std::pair
<int, std::string
>>>((*vars
)["ocspResponses"]);
205 for (const auto& file
: files
) {
206 config
.d_ocspFiles
.push_back(file
.second
);
210 if (vars
->count("keyLogFile")) {
211 #ifdef HAVE_SSL_CTX_SET_KEYLOG_CALLBACK
212 config
.d_keyLogFile
= boost::get
<const string
>((*vars
)["keyLogFile"]);
214 errlog("TLS Key logging has been enabled using the 'keyLogFile' parameter to %s(), but this version of OpenSSL does not support it", context
);
215 g_outputBuffer
= "TLS Key logging has been enabled using the 'keyLogFile' parameter to " + context
+ "(), but this version of OpenSSL does not support it";
220 #endif // defined(HAVE_DNS_OVER_TLS) || defined(HAVE_DNS_OVER_HTTPS)
222 static void setupLuaConfig(bool client
, bool configCheck
)
224 typedef std::unordered_map
<std::string
, boost::variant
<bool, std::string
, vector
<pair
<int, std::string
> >, DownstreamState::checkfunc_t
> > newserver_t
;
225 g_lua
.writeFunction("inClientStartup", [client
]() {
226 return client
&& !g_configurationDone
;
229 g_lua
.writeFunction("inConfigCheck", [configCheck
]() {
233 g_lua
.writeFunction("newServer",
234 [client
, configCheck
](boost::variant
<string
,newserver_t
> pvars
, boost::optional
<int> qps
) {
237 std::shared_ptr
<DownstreamState
> ret
= std::make_shared
<DownstreamState
>(ComboAddress());
240 ComboAddress serverAddr
;
241 std::string serverAddressStr
;
242 if(auto addrStr
= boost::get
<string
>(&pvars
)) {
243 serverAddressStr
= *addrStr
;
245 vars
["qps"] = std::to_string(*qps
);
248 vars
= boost::get
<newserver_t
>(pvars
);
249 serverAddressStr
= boost::get
<string
>(vars
["address"]);
253 serverAddr
= ComboAddress(serverAddressStr
, 53);
255 catch(const PDNSException
& e
) {
256 g_outputBuffer
="Error creating new server: "+string(e
.reason
);
257 errlog("Error creating new server with address %s: %s", serverAddressStr
, e
.reason
);
260 catch(std::exception
& e
) {
261 g_outputBuffer
="Error creating new server: "+string(e
.what());
262 errlog("Error creating new server with address %s: %s", serverAddressStr
, e
.what());
266 if(IsAnyAddress(serverAddr
)) {
267 g_outputBuffer
="Error creating new server: invalid address for a downstream server.";
268 errlog("Error creating new server: %s is not a valid address for a downstream server", serverAddressStr
);
272 ComboAddress sourceAddr
;
273 std::string sourceItfName
;
274 unsigned int sourceItf
= 0;
275 size_t numberOfSockets
= 1;
278 if(vars
.count("source")) {
279 /* handle source in the following forms:
280 - v4 address ("192.0.2.1")
281 - v6 address ("2001:DB8::1")
282 - interface name ("eth0")
283 - v4 address and interface name ("192.0.2.1@eth0")
284 - v6 address and interface name ("2001:DB8::1@eth0")
286 const string source
= boost::get
<string
>(vars
["source"]);
288 std::string::size_type pos
= source
.find("@");
289 if (pos
== std::string::npos
) {
290 /* no '@', try to parse that as a valid v4/v6 address */
292 sourceAddr
= ComboAddress(source
);
302 /* try to parse as interface name, or v4/v6@itf */
303 sourceItfName
= source
.substr(pos
== std::string::npos
? 0 : pos
+ 1);
304 unsigned int itfIdx
= if_nametoindex(sourceItfName
.c_str());
307 if (pos
== 0 || pos
== std::string::npos
) {
308 /* "eth0" or "@eth0" */
312 /* "192.0.2.1@eth0" */
313 sourceAddr
= ComboAddress(source
.substr(0, pos
));
316 #ifdef SO_BINDTODEVICE
317 /* we need to retain CAP_NET_RAW to be able to set SO_BINDTODEVICE in the health checks */
318 g_capabilitiesToRetain
.insert("CAP_NET_RAW");
323 warnlog("Dismissing source %s because '%s' is not a valid interface name", source
, sourceItfName
);
328 if (vars
.count("sockets")) {
329 numberOfSockets
= std::stoul(boost::get
<string
>(vars
["sockets"]));
330 if (numberOfSockets
== 0) {
331 warnlog("Dismissing invalid number of sockets '%s', using 1 instead", boost::get
<string
>(vars
["sockets"]));
336 // create but don't connect the socket in client or check-config modes
337 ret
=std::make_shared
<DownstreamState
>(serverAddr
, sourceAddr
, sourceItf
, sourceItfName
, numberOfSockets
, !(client
|| configCheck
));
338 if (!(client
|| configCheck
)) {
339 infolog("Added downstream server %s", serverAddr
.toStringWithPort());
342 if(vars
.count("qps")) {
343 int qpsVal
=std::stoi(boost::get
<string
>(vars
["qps"]));
344 ret
->qps
=QPSLimiter(qpsVal
, qpsVal
);
347 if(vars
.count("order")) {
348 ret
->order
=std::stoi(boost::get
<string
>(vars
["order"]));
351 if(vars
.count("weight")) {
353 int weightVal
=std::stoi(boost::get
<string
>(vars
["weight"]));
356 errlog("Error creating new server: downstream weight value must be greater than 0.");
360 ret
->setWeight(weightVal
);
362 catch(std::exception
& e
) {
363 // std::stoi will throw an exception if the string isn't in a value int range
364 errlog("Error creating new server: downstream weight value must be between %s and %s", 1, std::numeric_limits
<int>::max());
369 if(vars
.count("retries")) {
370 ret
->retries
=std::stoi(boost::get
<string
>(vars
["retries"]));
373 if(vars
.count("checkInterval")) {
374 ret
->checkInterval
=static_cast<unsigned int>(std::stoul(boost::get
<string
>(vars
["checkInterval"])));
377 if(vars
.count("tcpConnectTimeout")) {
378 ret
->tcpConnectTimeout
=std::stoi(boost::get
<string
>(vars
["tcpConnectTimeout"]));
381 if(vars
.count("tcpSendTimeout")) {
382 ret
->tcpSendTimeout
=std::stoi(boost::get
<string
>(vars
["tcpSendTimeout"]));
385 if(vars
.count("tcpRecvTimeout")) {
386 ret
->tcpRecvTimeout
=std::stoi(boost::get
<string
>(vars
["tcpRecvTimeout"]));
389 if(vars
.count("tcpFastOpen")) {
390 bool fastOpen
= boost::get
<bool>(vars
["tcpFastOpen"]);
393 ret
->tcpFastOpen
=true;
395 warnlog("TCP Fast Open has been configured on downstream server %s but is not supported", boost::get
<string
>(vars
["address"]));
400 if(vars
.count("name")) {
401 ret
->setName(boost::get
<string
>(vars
["name"]));
404 if (vars
.count("id")) {
405 ret
->setId(boost::lexical_cast
<boost::uuids::uuid
>(boost::get
<string
>(vars
["id"])));
408 if(vars
.count("checkName")) {
409 ret
->checkName
=DNSName(boost::get
<string
>(vars
["checkName"]));
412 if(vars
.count("checkType")) {
413 ret
->checkType
=boost::get
<string
>(vars
["checkType"]);
416 if(vars
.count("checkClass")) {
417 ret
->checkClass
=std::stoi(boost::get
<string
>(vars
["checkClass"]));
420 if(vars
.count("checkFunction")) {
421 ret
->checkFunction
= boost::get
<DownstreamState::checkfunc_t
>(vars
["checkFunction"]);
424 if(vars
.count("checkTimeout")) {
425 ret
->checkTimeout
= std::stoi(boost::get
<string
>(vars
["checkTimeout"]));
428 if(vars
.count("setCD")) {
429 ret
->setCD
=boost::get
<bool>(vars
["setCD"]);
432 if(vars
.count("mustResolve")) {
433 ret
->mustResolve
=boost::get
<bool>(vars
["mustResolve"]);
436 if(vars
.count("useClientSubnet")) {
437 ret
->useECS
=boost::get
<bool>(vars
["useClientSubnet"]);
440 if(vars
.count("disableZeroScope")) {
441 ret
->disableZeroScope
=boost::get
<bool>(vars
["disableZeroScope"]);
444 if(vars
.count("ipBindAddrNoPort")) {
445 ret
->ipBindAddrNoPort
=boost::get
<bool>(vars
["ipBindAddrNoPort"]);
448 if(vars
.count("addXPF")) {
449 ret
->xpfRRCode
=std::stoi(boost::get
<string
>(vars
["addXPF"]));
452 if(vars
.count("maxCheckFailures")) {
453 ret
->maxCheckFailures
=std::stoi(boost::get
<string
>(vars
["maxCheckFailures"]));
456 if(vars
.count("rise")) {
457 ret
->minRiseSuccesses
=std::stoi(boost::get
<string
>(vars
["rise"]));
460 if(vars
.count("cpus")) {
461 for (const auto cpu
: boost::get
<vector
<pair
<int,string
>>>(vars
["cpus"])) {
462 cpus
.insert(std::stoi(cpu
.second
));
466 /* this needs to be done _AFTER_ the order has been set,
467 since the server are kept ordered inside the pool */
468 auto localPools
= g_pools
.getCopy();
469 if(vars
.count("pool")) {
470 if(auto* pool
= boost::get
<string
>(&vars
["pool"])) {
471 ret
->pools
.insert(*pool
);
474 auto pools
= boost::get
<vector
<pair
<int, string
> > >(vars
["pool"]);
475 for(auto& p
: pools
) {
476 ret
->pools
.insert(p
.second
);
479 for(const auto& poolName
: ret
->pools
) {
480 addServerToPool(localPools
, poolName
, ret
);
484 addServerToPool(localPools
, "", ret
);
486 g_pools
.setState(localPools
);
488 if (ret
->connected
) {
489 ret
->threadStarted
.test_and_set();
492 g_launchWork
->push_back([ret
,cpus
]() {
493 ret
->tid
= thread(responderThread
, ret
);
495 mapThreadToCPUList(ret
->tid
.native_handle(), cpus
);
500 ret
->tid
= thread(responderThread
, ret
);
502 mapThreadToCPUList(ret
->tid
.native_handle(), cpus
);
507 auto states
= g_dstates
.getCopy();
508 states
.push_back(ret
);
509 std::stable_sort(states
.begin(), states
.end(), [](const decltype(ret
)& a
, const decltype(ret
)& b
) {
510 return a
->order
< b
->order
;
512 g_dstates
.setState(states
);
516 g_lua
.writeFunction("rmServer",
517 [](boost::variant
<std::shared_ptr
<DownstreamState
>, int, std::string
> var
)
520 shared_ptr
<DownstreamState
> server
= nullptr;
521 auto states
= g_dstates
.getCopy();
522 if (auto* rem
= boost::get
<shared_ptr
<DownstreamState
>>(&var
)) {
525 else if (auto str
= boost::get
<std::string
>(&var
)) {
526 const auto uuid
= getUniqueID(*str
);
527 for (auto& state
: states
) {
528 if (state
->id
== uuid
) {
534 int idx
= boost::get
<int>(var
);
535 server
= states
.at(idx
);
538 throw std::runtime_error("unable to locate the requested server");
540 auto localPools
= g_pools
.getCopy();
541 for (const string
& poolName
: server
->pools
) {
542 removeServerFromPool(localPools
, poolName
, server
);
544 /* the server might also be in the default pool */
545 removeServerFromPool(localPools
, "", server
);
546 g_pools
.setState(localPools
);
547 states
.erase(remove(states
.begin(), states
.end(), server
), states
.end());
548 g_dstates
.setState(states
);
551 g_lua
.writeFunction("truncateTC", [](bool tc
) { setLuaSideEffect(); g_truncateTC
=tc
; });
552 g_lua
.writeFunction("fixupCase", [](bool fu
) { setLuaSideEffect(); g_fixupCase
=fu
; });
554 g_lua
.writeFunction("addACL", [](const std::string
& domain
) {
556 g_ACL
.modify([domain
](NetmaskGroup
& nmg
) { nmg
.addMask(domain
); });
559 g_lua
.writeFunction("rmACL", [](const std::string
& netmask
) {
561 g_ACL
.modify([netmask
](NetmaskGroup
& nmg
) { nmg
.deleteMask(netmask
); });
564 g_lua
.writeFunction("setLocal", [client
](const std::string
& addr
, boost::optional
<localbind_t
> vars
) {
568 if (g_configurationDone
) {
569 g_outputBuffer
="setLocal cannot be used at runtime!\n";
572 bool reusePort
= false;
573 int tcpFastOpenQueueSize
= 0;
574 std::string interface
;
577 parseLocalBindVars(vars
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
);
580 ComboAddress
loc(addr
, 53);
581 for (auto it
= g_frontends
.begin(); it
!= g_frontends
.end(); ) {
582 /* DoH, DoT and DNSCrypt frontends are separate */
583 if ((*it
)->tlsFrontend
== nullptr && (*it
)->dnscryptCtx
== nullptr && (*it
)->dohFrontend
== nullptr) {
584 it
= g_frontends
.erase(it
);
591 // only works pre-startup, so no sync necessary
592 g_frontends
.push_back(std::unique_ptr
<ClientState
>(new ClientState(loc
, false, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
)));
593 g_frontends
.push_back(std::unique_ptr
<ClientState
>(new ClientState(loc
, true, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
)));
595 catch(const std::exception
& e
) {
596 g_outputBuffer
="Error: "+string(e
.what())+"\n";
600 g_lua
.writeFunction("addLocal", [client
](const std::string
& addr
, boost::optional
<localbind_t
> vars
) {
604 if (g_configurationDone
) {
605 g_outputBuffer
="addLocal cannot be used at runtime!\n";
608 bool reusePort
= false;
609 int tcpFastOpenQueueSize
= 0;
610 std::string interface
;
613 parseLocalBindVars(vars
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
);
616 ComboAddress
loc(addr
, 53);
617 // only works pre-startup, so no sync necessary
618 g_frontends
.push_back(std::unique_ptr
<ClientState
>(new ClientState(loc
, false, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
)));
619 g_frontends
.push_back(std::unique_ptr
<ClientState
>(new ClientState(loc
, true, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
)));
621 catch(std::exception
& e
) {
622 g_outputBuffer
="Error: "+string(e
.what())+"\n";
623 errlog("Error while trying to listen on %s: %s\n", addr
, string(e
.what()));
627 g_lua
.writeFunction("setACL", [](boost::variant
<string
,vector
<pair
<int, string
>>> inp
) {
630 if(auto str
= boost::get
<string
>(&inp
)) {
633 else for(const auto& p
: boost::get
<vector
<pair
<int,string
>>>(inp
)) {
634 nmg
.addMask(p
.second
);
639 g_lua
.writeFunction("showACL", []() {
640 setLuaNoSideEffect();
643 g_ACL
.getLocal()->toStringVector(&vec
);
645 for(const auto& s
: vec
)
646 g_outputBuffer
+=s
+"\n";
650 g_lua
.writeFunction("shutdown", []() {
652 sd_notify(0, "STOPPING=1");
653 #endif /* HAVE_SYSTEMD */
655 // Useful for debugging leaks, but might lead to race under load
656 // since other threads are still runing.
657 for(auto& frontend
: g_tlslocals
) {
662 google::protobuf::ShutdownProtobufLibrary();
663 #endif /* HAVE_PROTOBUF */
668 typedef std::unordered_map
<std::string
, boost::variant
<bool, std::string
> > showserversopts_t
;
670 g_lua
.writeFunction("showServers", [](boost::optional
<showserversopts_t
> vars
) {
671 setLuaNoSideEffect();
672 bool showUUIDs
= false;
674 if (vars
->count("showUUIDs")) {
675 showUUIDs
= boost::get
<bool>((*vars
)["showUUIDs"]);
682 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%" );
683 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
684 ret
<< (fmt
% "#" % "Name" % "Address" % "State" % "Qps" % "Qlim" % "Ord" % "Wt" % "Queries" % "Drops" % "Drate" % "Lat" % "Outstanding" % "Pools" % "UUID") << endl
;
686 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%" );
687 ret
<< (fmt
% "#" % "Name" % "Address" % "State" % "Qps" % "Qlim" % "Ord" % "Wt" % "Queries" % "Drops" % "Drate" % "Lat" % "Outstanding" % "Pools") << endl
;
690 uint64_t totQPS
{0}, totQueries
{0}, totDrops
{0};
692 auto states
= g_dstates
.getLocal();
693 for(const auto& s
: *states
) {
694 string status
= s
->getStatus();
696 for(auto& p
: s
->pools
) {
702 ret
<< (fmt
% counter
% s
->getName() % s
->remote
.toStringWithPort() %
704 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
;
706 ret
<< (fmt
% counter
% s
->getName() % s
->remote
.toStringWithPort() %
708 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
;
710 totQPS
+= s
->queryLoad
;
711 totQueries
+= s
->queries
.load();
712 totDrops
+= s
->reuseds
.load();
716 ret
<< (fmt
% "All" % "" % "" % ""
718 (double)totQPS
% "" % "" % "" % totQueries
% totDrops
% "" % "" % "" % "" % "" ) << endl
;
720 ret
<< (fmt
% "All" % "" % "" % ""
722 (double)totQPS
% "" % "" % "" % totQueries
% totDrops
% "" % "" % "" % "" ) << endl
;
725 g_outputBuffer
=ret
.str();
726 } catch(std::exception
& e
) {
727 g_outputBuffer
=e
.what();
732 g_lua
.writeFunction("getServers", []() {
733 setLuaNoSideEffect();
734 vector
<pair
<int, std::shared_ptr
<DownstreamState
> > > ret
;
736 for(const auto& s
: g_dstates
.getCopy()) {
737 ret
.push_back(make_pair(count
++, s
));
742 g_lua
.writeFunction("getPoolServers", [](string pool
) {
743 return getDownstreamCandidates(g_pools
.getCopy(), pool
);
746 g_lua
.writeFunction("getServer", [client
](boost::variant
<unsigned int, std::string
> i
) {
748 return std::make_shared
<DownstreamState
>(ComboAddress());
750 auto states
= g_dstates
.getCopy();
751 if (auto str
= boost::get
<std::string
>(&i
)) {
752 const auto uuid
= getUniqueID(*str
);
753 for (auto& state
: states
) {
754 if (state
->id
== uuid
) {
759 else if (auto pos
= boost::get
<unsigned int>(&i
)) {
760 return states
.at(*pos
);
763 g_outputBuffer
= "Error: no rule matched\n";
764 return std::shared_ptr
<DownstreamState
>(nullptr);
767 g_lua
.writeFunction("carbonServer", [](const std::string
& address
, boost::optional
<string
> ourName
,
768 boost::optional
<unsigned int> interval
, boost::optional
<string
> namespace_name
,
769 boost::optional
<string
> instance_name
) {
771 auto ours
= g_carbon
.getCopy();
773 ComboAddress(address
, 2003),
774 (namespace_name
&& !namespace_name
->empty()) ? *namespace_name
: "dnsdist",
775 ourName
? *ourName
: "",
776 (instance_name
&& !instance_name
->empty()) ? *instance_name
: "main" ,
777 interval
? *interval
: 30
779 g_carbon
.setState(ours
);
782 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
) {
786 local
= ComboAddress(address
);
788 catch (const PDNSException
& e
) {
789 throw std::runtime_error(std::string("Error parsing the bind address for the webserver: ") + e
.reason
);
792 if (client
|| configCheck
) {
797 int sock
= SSocket(local
.sin4
.sin_family
, SOCK_STREAM
, 0);
798 SSetsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, 1);
801 auto launch
=[sock
, local
, password
, apiKey
, customHeaders
]() {
802 setWebserverPassword(password
);
803 setWebserverAPIKey(apiKey
);
804 setWebserverCustomHeaders(customHeaders
);
805 thread
t(dnsdistWebserverThread
, sock
, local
);
809 g_launchWork
->push_back(launch
);
813 catch(std::exception
& e
) {
814 g_outputBuffer
="Unable to bind to webserver socket on " + local
.toStringWithPort() + ": " + e
.what();
815 errlog("Unable to bind to webserver socket on %s: %s", local
.toStringWithPort(), e
.what());
820 typedef std::unordered_map
<std::string
, boost::variant
<std::string
, std::map
<std::string
, std::string
>> > webserveropts_t
;
822 g_lua
.writeFunction("setWebserverConfig", [](boost::optional
<webserveropts_t
> vars
) {
828 if(vars
->count("password")) {
829 const std::string password
= boost::get
<std::string
>(vars
->at("password"));
831 setWebserverPassword(password
);
833 if(vars
->count("apiKey")) {
834 const std::string apiKey
= boost::get
<std::string
>(vars
->at("apiKey"));
836 setWebserverAPIKey(apiKey
);
838 if(vars
->count("customHeaders")) {
839 const boost::optional
<std::map
<std::string
, std::string
> > headers
= boost::get
<std::map
<std::string
, std::string
> >(vars
->at("customHeaders"));
841 setWebserverCustomHeaders(headers
);
845 g_lua
.writeFunction("controlSocket", [client
,configCheck
](const std::string
& str
) {
847 ComboAddress
local(str
, 5199);
849 if(client
|| configCheck
) {
850 g_serverControl
= local
;
854 g_consoleEnabled
= true;
855 #ifdef HAVE_LIBSODIUM
856 if (g_configurationDone
&& g_consoleKey
.empty()) {
857 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");
862 int sock
= SSocket(local
.sin4
.sin_family
, SOCK_STREAM
, 0);
863 SSetsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, 1);
866 auto launch
=[sock
, local
]() {
867 thread
t(controlThread
, sock
, local
);
871 g_launchWork
->push_back(launch
);
876 catch(std::exception
& e
) {
877 g_outputBuffer
="Unable to bind to control socket on " + local
.toStringWithPort() + ": " + e
.what();
878 errlog("Unable to bind to control socket on %s: %s", local
.toStringWithPort(), e
.what());
882 g_lua
.writeFunction("addConsoleACL", [](const std::string
& netmask
) {
884 #ifndef HAVE_LIBSODIUM
885 warnlog("Allowing remote access to the console while libsodium support has not been enabled is not secure, and will result in cleartext communications");
888 g_consoleACL
.modify([netmask
](NetmaskGroup
& nmg
) { nmg
.addMask(netmask
); });
891 g_lua
.writeFunction("setConsoleACL", [](boost::variant
<string
,vector
<pair
<int, string
>>> inp
) {
894 #ifndef HAVE_LIBSODIUM
895 warnlog("Allowing remote access to the console while libsodium support has not been enabled is not secure, and will result in cleartext communications");
899 if(auto str
= boost::get
<string
>(&inp
)) {
902 else for(const auto& p
: boost::get
<vector
<pair
<int,string
>>>(inp
)) {
903 nmg
.addMask(p
.second
);
905 g_consoleACL
.setState(nmg
);
908 g_lua
.writeFunction("showConsoleACL", []() {
909 setLuaNoSideEffect();
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 g_consoleACL
.getLocal()->toStringVector(&vec
);
918 for(const auto& s
: vec
) {
919 g_outputBuffer
+= s
+ "\n";
923 g_lua
.writeFunction("clearQueryCounters", []() {
924 unsigned int size
{0};
926 WriteLock
wl(&g_qcount
.queryLock
);
927 size
= g_qcount
.records
.size();
928 g_qcount
.records
.clear();
931 boost::format
fmt("%d records cleared from query counter buffer\n");
932 g_outputBuffer
= (fmt
% size
).str();
935 g_lua
.writeFunction("getQueryCounters", [](boost::optional
<unsigned int> optMax
) {
936 setLuaNoSideEffect();
937 ReadLock
rl(&g_qcount
.queryLock
);
938 g_outputBuffer
= "query counting is currently: ";
939 g_outputBuffer
+= g_qcount
.enabled
? "enabled" : "disabled";
940 g_outputBuffer
+= (boost::format(" (%d records in buffer)\n") % g_qcount
.records
.size()).str();
942 boost::format
fmt("%-3d %s: %d request(s)\n");
943 QueryCountRecords::iterator it
;
944 unsigned int max
= optMax
? *optMax
: 10;
945 unsigned int index
{1};
946 for(it
= g_qcount
.records
.begin(); it
!= g_qcount
.records
.end() && index
<= max
; ++it
, ++index
) {
947 g_outputBuffer
+= (fmt
% index
% it
->first
% it
->second
).str();
951 g_lua
.writeFunction("setQueryCount", [](bool enabled
) { g_qcount
.enabled
=enabled
; });
953 g_lua
.writeFunction("setQueryCountFilter", [](QueryCountFilter func
) {
954 g_qcount
.filter
= func
;
957 g_lua
.writeFunction("makeKey", []() {
958 setLuaNoSideEffect();
959 g_outputBuffer
="setKey("+newKey()+")\n";
962 g_lua
.writeFunction("setKey", [](const std::string
& key
) {
963 if(!g_configurationDone
&& ! g_consoleKey
.empty()) { // this makes sure the commandline -k key prevails over dnsdist.conf
964 return; // but later setKeys() trump the -k value again
966 #ifndef HAVE_LIBSODIUM
967 warnlog("Calling setKey() while libsodium support has not been enabled is not secure, and will result in cleartext communications");
972 if(B64Decode(key
, newkey
) < 0) {
973 g_outputBuffer
=string("Unable to decode ")+key
+" as Base64";
974 errlog("%s", g_outputBuffer
);
980 g_lua
.writeFunction("testCrypto", [](boost::optional
<string
> optTestMsg
)
982 setLuaNoSideEffect();
983 #ifdef HAVE_LIBSODIUM
988 testmsg
= *optTestMsg
;
991 testmsg
= "testStringForCryptoTests";
997 string encrypted
= sodEncryptSym(testmsg
, g_consoleKey
, sn
);
998 string decrypted
= sodDecryptSym(encrypted
, g_consoleKey
, sn2
);
1003 encrypted
= sodEncryptSym(testmsg
, g_consoleKey
, sn
);
1004 decrypted
= sodDecryptSym(encrypted
, g_consoleKey
, sn2
);
1006 if(testmsg
== decrypted
)
1007 g_outputBuffer
="Everything is ok!\n";
1009 g_outputBuffer
="Crypto failed.. (the decoded value does not match the cleartext one)\n";
1011 catch(const std::exception
& e
) {
1012 g_outputBuffer
="Crypto failed: "+std::string(e
.what())+"\n";
1015 g_outputBuffer
="Crypto failed..\n";
1018 g_outputBuffer
="Crypto not available.\n";
1022 g_lua
.writeFunction("setTCPRecvTimeout", [](int timeout
) { g_tcpRecvTimeout
=timeout
; });
1024 g_lua
.writeFunction("setTCPSendTimeout", [](int timeout
) { g_tcpSendTimeout
=timeout
; });
1026 g_lua
.writeFunction("setUDPTimeout", [](int timeout
) { g_udpTimeout
=timeout
; });
1028 g_lua
.writeFunction("setMaxUDPOutstanding", [](uint16_t max
) {
1029 if (!g_configurationDone
) {
1030 g_maxOutstanding
= max
;
1032 g_outputBuffer
="Max UDP outstanding cannot be altered at runtime!\n";
1036 g_lua
.writeFunction("setMaxTCPClientThreads", [](uint64_t max
) {
1037 if (!g_configurationDone
) {
1038 g_maxTCPClientThreads
= max
;
1040 g_outputBuffer
="Maximum TCP client threads count cannot be altered at runtime!\n";
1044 g_lua
.writeFunction("setMaxTCPQueuedConnections", [](uint64_t max
) {
1045 if (!g_configurationDone
) {
1046 g_maxTCPQueuedConnections
= max
;
1048 g_outputBuffer
="The maximum number of queued TCP connections cannot be altered at runtime!\n";
1052 g_lua
.writeFunction("setMaxTCPQueriesPerConnection", [](size_t max
) {
1053 if (!g_configurationDone
) {
1054 g_maxTCPQueriesPerConn
= max
;
1056 g_outputBuffer
="The maximum number of queries per TCP connection cannot be altered at runtime!\n";
1060 g_lua
.writeFunction("setMaxTCPConnectionsPerClient", [](size_t max
) {
1061 if (!g_configurationDone
) {
1062 g_maxTCPConnectionsPerClient
= max
;
1064 g_outputBuffer
="The maximum number of TCP connection per client cannot be altered at runtime!\n";
1068 g_lua
.writeFunction("setMaxTCPConnectionDuration", [](size_t max
) {
1069 if (!g_configurationDone
) {
1070 g_maxTCPConnectionDuration
= max
;
1072 g_outputBuffer
="The maximum duration of a TCP connection cannot be altered at runtime!\n";
1076 g_lua
.writeFunction("setCacheCleaningDelay", [](uint32_t delay
) { g_cacheCleaningDelay
= delay
; });
1078 g_lua
.writeFunction("setCacheCleaningPercentage", [](uint16_t percentage
) { if (percentage
< 100) g_cacheCleaningPercentage
= percentage
; else g_cacheCleaningPercentage
= 100; });
1080 g_lua
.writeFunction("setECSSourcePrefixV4", [](uint16_t prefix
) { g_ECSSourcePrefixV4
=prefix
; });
1082 g_lua
.writeFunction("setECSSourcePrefixV6", [](uint16_t prefix
) { g_ECSSourcePrefixV6
=prefix
; });
1084 g_lua
.writeFunction("setECSOverride", [](bool override
) { g_ECSOverride
=override
; });
1086 g_lua
.writeFunction("setPreserveTrailingData", [](bool preserve
) { g_preserveTrailingData
= preserve
; });
1088 g_lua
.writeFunction("showDynBlocks", []() {
1089 setLuaNoSideEffect();
1090 auto slow
= g_dynblockNMG
.getCopy();
1091 struct timespec now
;
1093 boost::format
fmt("%-24s %8d %8d %-10s %-20s %s\n");
1094 g_outputBuffer
= (fmt
% "What" % "Seconds" % "Blocks" % "Warning" % "Action" % "Reason").str();
1095 for(const auto& e
: slow
) {
1096 if(now
< e
.second
.until
)
1097 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();
1099 auto slow2
= g_dynblockSMT
.getCopy();
1100 slow2
.visit([&now
, &fmt
](const SuffixMatchTree
<DynBlock
>& node
) {
1101 if(now
<node
.d_value
.until
) {
1102 string
dom("empty");
1103 if(!node
.d_value
.domain
.empty())
1104 dom
= node
.d_value
.domain
.toString();
1105 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();
1111 g_lua
.writeFunction("clearDynBlocks", []() {
1114 g_dynblockNMG
.setState(nmg
);
1115 SuffixMatchTree
<DynBlock
> smt
;
1116 g_dynblockSMT
.setState(smt
);
1119 g_lua
.writeFunction("addDynBlocks",
1120 [](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
) {
1125 auto slow
= g_dynblockNMG
.getCopy();
1126 struct timespec until
, now
;
1129 int actualSeconds
= seconds
? *seconds
: 10;
1130 until
.tv_sec
+= actualSeconds
;
1131 for(const auto& capair
: m
) {
1132 unsigned int count
= 0;
1133 auto got
= slow
.lookup(Netmask(capair
.first
));
1136 if(until
< got
->second
.until
) // had a longer policy
1138 if(now
< got
->second
.until
) // only inherit count on fresh query we are extending
1139 count
=got
->second
.blocks
;
1143 DynBlock db
{msg
,until
,DNSName(),(action
? *action
: DNSAction::Action::None
)};
1146 warnlog("Inserting dynamic block for %s for %d seconds: %s", capair
.first
.toString(), actualSeconds
, msg
);
1147 slow
.insert(Netmask(capair
.first
)).second
=db
;
1149 g_dynblockNMG
.setState(slow
);
1152 g_lua
.writeFunction("addDynBlockSMT",
1153 [](const vector
<pair
<unsigned int, string
> >&names
, const std::string
& msg
, boost::optional
<int> seconds
, boost::optional
<DNSAction::Action
> action
) {
1154 if (names
.empty()) {
1158 auto slow
= g_dynblockSMT
.getCopy();
1159 struct timespec until
, now
;
1162 int actualSeconds
= seconds
? *seconds
: 10;
1163 until
.tv_sec
+= actualSeconds
;
1165 for(const auto& capair
: names
) {
1166 unsigned int count
= 0;
1167 DNSName
domain(capair
.second
);
1168 domain
.makeUsLowerCase();
1169 auto got
= slow
.lookup(domain
);
1172 if(until
< got
->until
) // had a longer policy
1174 if(now
< got
->until
) // only inherit count on fresh query we are extending
1180 DynBlock db
{msg
,until
,domain
,(action
? *action
: DNSAction::Action::None
)};
1183 warnlog("Inserting dynamic block for %s for %d seconds: %s", domain
, actualSeconds
, msg
);
1184 slow
.add(domain
, db
);
1186 g_dynblockSMT
.setState(slow
);
1189 g_lua
.writeFunction("setDynBlocksAction", [](DNSAction::Action action
) {
1190 if (!g_configurationDone
) {
1191 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
) {
1192 g_dynBlockAction
= action
;
1195 errlog("Dynamic blocks action can only be Drop, NoOp, NXDomain, Refused, Truncate or NoRecurse!");
1196 g_outputBuffer
="Dynamic blocks action can only be Drop, NoOp, NXDomain, Refused, Truncate or NoRecurse!\n";
1199 g_outputBuffer
="Dynamic blocks action cannot be altered at runtime!\n";
1203 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
) {
1204 if (g_configurationDone
) {
1205 g_outputBuffer
="addDNSCryptBind cannot be used at runtime!\n";
1208 #ifdef HAVE_DNSCRYPT
1209 bool reusePort
= false;
1210 int tcpFastOpenQueueSize
= 0;
1211 std::string interface
;
1213 std::vector
<DNSCryptContext::CertKeyPaths
> certKeys
;
1215 parseLocalBindVars(vars
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
);
1217 if (certFiles
.type() == typeid(std::string
) && keyFiles
.type() == typeid(std::string
)) {
1218 auto certFile
= boost::get
<std::string
>(certFiles
);
1219 auto keyFile
= boost::get
<std::string
>(keyFiles
);
1220 certKeys
.push_back({certFile
, keyFile
});
1222 else if (certFiles
.type() == typeid(std::vector
<std::pair
<int,std::string
>>) && keyFiles
.type() == typeid(std::vector
<std::pair
<int,std::string
>>)) {
1223 auto certFilesVect
= boost::get
<std::vector
<std::pair
<int,std::string
>>>(certFiles
);
1224 auto keyFilesVect
= boost::get
<std::vector
<std::pair
<int,std::string
>>>(keyFiles
);
1225 if (certFilesVect
.size() == keyFilesVect
.size()) {
1226 for (size_t idx
= 0; idx
< certFilesVect
.size(); idx
++) {
1227 certKeys
.push_back({certFilesVect
.at(idx
).second
, keyFilesVect
.at(idx
).second
});
1231 errlog("Error, mismatching number of certificates and keys in call to addDNSCryptBind!");
1232 g_outputBuffer
="Error, mismatching number of certificates and keys in call to addDNSCryptBind()!";
1237 errlog("Error, mismatching number of certificates and keys in call to addDNSCryptBind()!");
1238 g_outputBuffer
="Error, mismatching number of certificates and keys in call to addDNSCryptBind()!";
1243 auto ctx
= std::make_shared
<DNSCryptContext
>(providerName
, certKeys
);
1246 auto cs
= std::unique_ptr
<ClientState
>(new ClientState(ComboAddress(addr
, 443), false, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
));
1247 cs
->dnscryptCtx
= ctx
;
1248 g_dnsCryptLocals
.push_back(ctx
);
1249 g_frontends
.push_back(std::move(cs
));
1252 cs
= std::unique_ptr
<ClientState
>(new ClientState(ComboAddress(addr
, 443), true, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
));
1253 cs
->dnscryptCtx
= ctx
;
1254 g_frontends
.push_back(std::move(cs
));
1256 catch(std::exception
& e
) {
1258 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1261 g_outputBuffer
="Error: DNSCrypt support is not enabled.\n";
1266 g_lua
.writeFunction("showDNSCryptBinds", []() {
1267 setLuaNoSideEffect();
1268 #ifdef HAVE_DNSCRYPT
1270 boost::format
fmt("%1$-3d %2% %|25t|%3$-20.20s");
1271 ret
<< (fmt
% "#" % "Address" % "Provider Name") << endl
;
1274 std::unordered_set
<std::shared_ptr
<DNSCryptContext
>> contexts
;
1275 for (const auto& frontend
: g_frontends
) {
1276 const std::shared_ptr
<DNSCryptContext
> ctx
= frontend
->dnscryptCtx
;
1277 if (!ctx
|| contexts
.count(ctx
) != 0) {
1280 contexts
.insert(ctx
);
1281 ret
<< (fmt
% idx
% frontend
->local
.toStringWithPort() % ctx
->getProviderName()) << endl
;
1285 g_outputBuffer
=ret
.str();
1287 g_outputBuffer
="Error: DNSCrypt support is not enabled.\n";
1291 g_lua
.writeFunction("getDNSCryptBind", [](size_t idx
) {
1292 setLuaNoSideEffect();
1293 #ifdef HAVE_DNSCRYPT
1294 std::shared_ptr
<DNSCryptContext
> ret
= nullptr;
1295 if (idx
< g_dnsCryptLocals
.size()) {
1296 ret
= g_dnsCryptLocals
.at(idx
);
1300 g_outputBuffer
="Error: DNSCrypt support is not enabled.\n";
1304 g_lua
.writeFunction("getDNSCryptBindCount", []() {
1305 setLuaNoSideEffect();
1306 return g_dnsCryptLocals
.size();
1309 g_lua
.writeFunction("generateDNSCryptProviderKeys", [client
](const std::string
& publicKeyFile
, const std::string privateKeyFile
) {
1310 setLuaNoSideEffect();
1311 #ifdef HAVE_DNSCRYPT
1315 unsigned char publicKey
[DNSCRYPT_PROVIDER_PUBLIC_KEY_SIZE
];
1316 unsigned char privateKey
[DNSCRYPT_PROVIDER_PRIVATE_KEY_SIZE
];
1317 sodium_mlock(privateKey
, sizeof(privateKey
));
1320 DNSCryptContext::generateProviderKeys(publicKey
, privateKey
);
1322 ofstream
pubKStream(publicKeyFile
);
1323 pubKStream
.write((char*) publicKey
, sizeof(publicKey
));
1326 ofstream
privKStream(privateKeyFile
);
1327 privKStream
.write((char*) privateKey
, sizeof(privateKey
));
1328 privKStream
.close();
1330 g_outputBuffer
="Provider fingerprint is: " + DNSCryptContext::getProviderFingerprint(publicKey
) + "\n";
1332 catch(std::exception
& e
) {
1334 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1337 sodium_memzero(privateKey
, sizeof(privateKey
));
1338 sodium_munlock(privateKey
, sizeof(privateKey
));
1340 g_outputBuffer
="Error: DNSCrypt support is not enabled.\n";
1344 g_lua
.writeFunction("printDNSCryptProviderFingerprint", [](const std::string
& publicKeyFile
) {
1345 setLuaNoSideEffect();
1346 #ifdef HAVE_DNSCRYPT
1347 unsigned char publicKey
[DNSCRYPT_PROVIDER_PUBLIC_KEY_SIZE
];
1350 ifstream
file(publicKeyFile
);
1351 file
.read((char *) &publicKey
, sizeof(publicKey
));
1354 throw std::runtime_error("Invalid dnscrypt provider public key file " + publicKeyFile
);
1357 g_outputBuffer
="Provider fingerprint is: " + DNSCryptContext::getProviderFingerprint(publicKey
) + "\n";
1359 catch(std::exception
& e
) {
1361 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1364 g_outputBuffer
="Error: DNSCrypt support is not enabled.\n";
1368 #ifdef HAVE_DNSCRYPT
1369 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
) {
1370 setLuaNoSideEffect();
1374 DNSCryptPrivateKey privateKey
;
1378 if (generateDNSCryptCertificate(providerPrivateKeyFile
, serial
, begin
, end
, version
? *version
: DNSCryptExchangeVersion::VERSION1
, cert
, privateKey
)) {
1379 privateKey
.saveToFile(privateKeyFile
);
1380 DNSCryptContext::saveCertFromFile(cert
, certificateFile
);
1383 catch(const std::exception
& e
) {
1385 g_outputBuffer
="Error: "+string(e
.what())+"\n";
1390 g_lua
.writeFunction("showPools", []() {
1391 setLuaNoSideEffect();
1394 boost::format
fmt("%1$-20.20s %|25t|%2$20s %|25t|%3$20s %|50t|%4%" );
1396 ret
<< (fmt
% "Name" % "Cache" % "ServerPolicy" % "Servers" ) << endl
;
1398 const auto localPools
= g_pools
.getCopy();
1399 for (const auto& entry
: localPools
) {
1400 const string
& name
= entry
.first
;
1401 const std::shared_ptr
<ServerPool
> pool
= entry
.second
;
1402 string cache
= pool
->packetCache
!= nullptr ? pool
->packetCache
->toString() : "";
1403 string policy
= g_policy
.getLocal()->name
;
1404 if (pool
->policy
!= nullptr) {
1405 policy
= pool
->policy
->name
;
1409 for (const auto& server
: pool
->getServers()) {
1410 if (!servers
.empty()) {
1413 if (!server
.second
->getName().empty()) {
1414 servers
+= server
.second
->getName();
1417 servers
+= server
.second
->remote
.toStringWithPort();
1420 ret
<< (fmt
% name
% cache
% policy
% servers
) << endl
;
1422 g_outputBuffer
=ret
.str();
1423 }catch(std::exception
& e
) { g_outputBuffer
=e
.what(); throw; }
1426 g_lua
.writeFunction("getPool", [client
](const string
& poolName
) {
1428 return std::make_shared
<ServerPool
>();
1430 auto localPools
= g_pools
.getCopy();
1431 std::shared_ptr
<ServerPool
> pool
= createPoolIfNotExists(localPools
, poolName
);
1432 g_pools
.setState(localPools
);
1436 g_lua
.writeFunction("setVerboseHealthChecks", [](bool verbose
) { g_verboseHealthChecks
=verbose
; });
1437 g_lua
.writeFunction("setStaleCacheEntriesTTL", [](uint32_t ttl
) { g_staleCacheEntriesTTL
= ttl
; });
1439 g_lua
.writeFunction("showBinds", []() {
1440 setLuaNoSideEffect();
1443 boost::format
fmt("%1$-3d %2$-20.20s %|35t|%3$-20.20s %|57t|%4%" );
1445 ret
<< (fmt
% "#" % "Address" % "Protocol" % "Queries" ) << endl
;
1448 for (const auto& front
: g_frontends
) {
1449 ret
<< (fmt
% counter
% front
->local
.toStringWithPort() % front
->getType() % front
->queries
) << endl
;
1452 g_outputBuffer
=ret
.str();
1453 }catch(std::exception
& e
) { g_outputBuffer
=e
.what(); throw; }
1456 g_lua
.writeFunction("getBind", [](size_t num
) {
1457 setLuaNoSideEffect();
1458 ClientState
* ret
= nullptr;
1459 if(num
< g_frontends
.size()) {
1460 ret
=g_frontends
[num
].get();
1465 g_lua
.writeFunction("getBindCount", []() {
1466 setLuaNoSideEffect();
1467 return g_frontends
.size();
1470 g_lua
.writeFunction("help", [](boost::optional
<std::string
> command
) {
1471 setLuaNoSideEffect();
1472 g_outputBuffer
= "";
1473 for (const auto& keyword
: g_consoleKeywords
) {
1475 g_outputBuffer
+= keyword
.toString() + "\n";
1477 else if (keyword
.name
== command
) {
1478 g_outputBuffer
= keyword
.toString() + "\n";
1483 g_outputBuffer
= "Nothing found for " + *command
+ "\n";
1487 g_lua
.writeFunction("showVersion", []() {
1488 setLuaNoSideEffect();
1489 g_outputBuffer
= "dnsdist " + std::string(VERSION
) + "\n";
1492 g_lua
.writeFunction("showSecurityStatus", []() {
1493 setLuaNoSideEffect();
1494 g_outputBuffer
= std::to_string(g_stats
.securityStatus
) + "\n";
1498 g_lua
.writeFunction("setDefaultBPFFilter", [](std::shared_ptr
<BPFFilter
> bpf
) {
1499 if (g_configurationDone
) {
1500 g_outputBuffer
="setDefaultBPFFilter() cannot be used at runtime!\n";
1503 g_defaultBPFFilter
= bpf
;
1506 g_lua
.writeFunction("registerDynBPFFilter", [](std::shared_ptr
<DynBPFFilter
> dbpf
) {
1508 g_dynBPFFilters
.push_back(dbpf
);
1512 g_lua
.writeFunction("unregisterDynBPFFilter", [](std::shared_ptr
<DynBPFFilter
> dbpf
) {
1514 for (auto it
= g_dynBPFFilters
.begin(); it
!= g_dynBPFFilters
.end(); it
++) {
1516 g_dynBPFFilters
.erase(it
);
1523 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
) {
1525 struct timespec until
, now
;
1526 clock_gettime(CLOCK_MONOTONIC
, &now
);
1528 int actualSeconds
= seconds
? *seconds
: 10;
1529 until
.tv_sec
+= actualSeconds
;
1530 for(const auto& capair
: m
) {
1531 if (dynbpf
->block(capair
.first
, until
)) {
1532 warnlog("Inserting eBPF dynamic block for %s for %d seconds: %s", capair
.first
.toString(), actualSeconds
, msg
? *msg
: "");
1537 #endif /* HAVE_EBPF */
1539 g_lua
.writeFunction
<std::unordered_map
<string
,uint64_t>()>("getStatisticsCounters", []() {
1540 setLuaNoSideEffect();
1541 std::unordered_map
<string
,uint64_t> res
;
1542 for(const auto& entry
: g_stats
.entries
) {
1543 if(const auto& val
= boost::get
<DNSDistStats::stat_t
*>(&entry
.second
))
1544 res
[entry
.first
] = (*val
)->load();
1549 g_lua
.writeFunction("includeDirectory", [](const std::string
& dirname
) {
1550 if (g_configurationDone
) {
1551 errlog("includeDirectory() cannot be used at runtime!");
1552 g_outputBuffer
="includeDirectory() cannot be used at runtime!\n";
1557 errlog("includeDirectory() cannot be used recursively!");
1558 g_outputBuffer
="includeDirectory() cannot be used recursively!\n";
1564 if (stat(dirname
.c_str(), &st
)) {
1565 errlog("The included directory %s does not exist!", dirname
.c_str());
1566 g_outputBuffer
="The included directory " + dirname
+ " does not exist!";
1570 if (!S_ISDIR(st
.st_mode
)) {
1571 errlog("The included directory %s is not a directory!", dirname
.c_str());
1572 g_outputBuffer
="The included directory " + dirname
+ " is not a directory!";
1578 std::list
<std::string
> files
;
1579 if (!(dirp
= opendir(dirname
.c_str()))) {
1580 errlog("Error opening the included directory %s!", dirname
.c_str());
1581 g_outputBuffer
="Error opening the included directory " + dirname
+ "!";
1585 while((ent
= readdir(dirp
)) != NULL
) {
1586 if (ent
->d_name
[0] == '.') {
1590 if (boost::ends_with(ent
->d_name
, ".conf")) {
1591 std::ostringstream namebuf
;
1592 namebuf
<< dirname
.c_str() << "/" << ent
->d_name
;
1594 if (stat(namebuf
.str().c_str(), &st
) || !S_ISREG(st
.st_mode
)) {
1598 files
.push_back(namebuf
.str());
1605 for (auto file
= files
.begin(); file
!= files
.end(); ++file
) {
1606 std::ifstream
ifs(*file
);
1608 warnlog("Unable to read configuration from '%s'", *file
);
1610 vinfolog("Read configuration from '%s'", *file
);
1613 g_lua
.executeCode(ifs
);
1619 g_lua
.writeFunction("setAPIWritable", [](bool writable
, boost::optional
<std::string
> apiConfigDir
) {
1621 g_apiReadWrite
= writable
;
1623 if (!(*apiConfigDir
).empty()) {
1624 g_apiConfigDirectory
= *apiConfigDir
;
1627 errlog("The API configuration directory value cannot be empty!");
1628 g_outputBuffer
="The API configuration directory value cannot be empty!";
1633 g_lua
.writeFunction("setServFailWhenNoServer", [](bool servfail
) {
1635 g_servFailOnNoPolicy
= servfail
;
1638 g_lua
.writeFunction("setRoundRobinFailOnNoServer", [](bool fail
) {
1640 g_roundrobinFailOnNoServer
= fail
;
1643 g_lua
.writeFunction("setConsistentHashingBalancingFactor", [](double factor
) {
1645 if (factor
>= 1.0) {
1646 g_consistentHashBalancingFactor
= factor
;
1649 errlog("Invalid value passed to setConsistentHashingBalancingFactor()!");
1650 g_outputBuffer
="Invalid value passed to setConsistentHashingBalancingFactor()!\n";
1655 g_lua
.writeFunction("setWeightedBalancingFactor", [](double factor
) {
1657 if (factor
>= 1.0) {
1658 g_weightedBalancingFactor
= factor
;
1661 errlog("Invalid value passed to setWeightedBalancingFactor()!");
1662 g_outputBuffer
="Invalid value passed to setWeightedBalancingFactor()!\n";
1667 g_lua
.writeFunction("setRingBuffersSize", [](size_t capacity
, boost::optional
<size_t> numberOfShards
) {
1669 if (g_configurationDone
) {
1670 errlog("setRingBuffersSize() cannot be used at runtime!");
1671 g_outputBuffer
="setRingBuffersSize() cannot be used at runtime!\n";
1674 g_rings
.setCapacity(capacity
, numberOfShards
? *numberOfShards
: 1);
1677 g_lua
.writeFunction("setRingBuffersLockRetries", [](size_t retries
) {
1679 g_rings
.setNumberOfLockRetries(retries
);
1682 g_lua
.writeFunction("setWHashedPertubation", [](uint32_t pertub
) {
1684 g_hashperturb
= pertub
;
1687 g_lua
.writeFunction("setTCPUseSinglePipe", [](bool flag
) {
1688 if (g_configurationDone
) {
1689 g_outputBuffer
="setTCPUseSinglePipe() cannot be used at runtime!\n";
1693 g_useTCPSinglePipe
= flag
;
1696 g_lua
.writeFunction("snmpAgent", [client
,configCheck
](bool enableTraps
, boost::optional
<std::string
> masterSocket
) {
1697 if(client
|| configCheck
)
1699 #ifdef HAVE_NET_SNMP
1700 if (g_configurationDone
) {
1701 errlog("snmpAgent() cannot be used at runtime!");
1702 g_outputBuffer
="snmpAgent() cannot be used at runtime!\n";
1706 if (g_snmpEnabled
) {
1707 errlog("snmpAgent() cannot be used twice!");
1708 g_outputBuffer
="snmpAgent() cannot be used twice!\n";
1712 g_snmpEnabled
= true;
1713 g_snmpTrapsEnabled
= enableTraps
;
1714 g_snmpAgent
= new DNSDistSNMPAgent("dnsdist", masterSocket
? *masterSocket
: std::string());
1716 errlog("NET SNMP support is required to use snmpAgent()");
1717 g_outputBuffer
="NET SNMP support is required to use snmpAgent()\n";
1718 #endif /* HAVE_NET_SNMP */
1721 g_lua
.writeFunction("sendCustomTrap", [](const std::string
& str
) {
1722 if (g_snmpAgent
&& g_snmpTrapsEnabled
) {
1723 g_snmpAgent
->sendCustomTrap(str
);
1727 g_lua
.writeFunction("setServerPolicy", [](ServerPolicy policy
) {
1729 g_policy
.setState(policy
);
1732 g_lua
.writeFunction("setServerPolicyLua", [](string name
, ServerPolicy::policyfunc_t policy
) {
1734 g_policy
.setState(ServerPolicy
{name
, policy
, true});
1737 g_lua
.writeFunction("setServerPolicyLuaFFI", [](string name
, ServerPolicy::ffipolicyfunc_t policy
) {
1739 auto pol
= ServerPolicy(name
, policy
);
1740 g_policy
.setState(std::move(pol
));
1743 g_lua
.writeFunction("showServerPolicy", []() {
1745 g_outputBuffer
=g_policy
.getLocal()->name
+"\n";
1748 g_lua
.writeFunction("setPoolServerPolicy", [](ServerPolicy policy
, string pool
) {
1750 auto localPools
= g_pools
.getCopy();
1751 setPoolPolicy(localPools
, pool
, std::make_shared
<ServerPolicy
>(policy
));
1752 g_pools
.setState(localPools
);
1755 g_lua
.writeFunction("setPoolServerPolicyLua", [](string name
, ServerPolicy::policyfunc_t policy
, string pool
) {
1757 auto localPools
= g_pools
.getCopy();
1758 setPoolPolicy(localPools
, pool
, std::make_shared
<ServerPolicy
>(ServerPolicy
{name
, policy
, true}));
1759 g_pools
.setState(localPools
);
1762 g_lua
.writeFunction("showPoolServerPolicy", [](string pool
) {
1764 auto localPools
= g_pools
.getCopy();
1765 auto poolObj
= getPool(localPools
, pool
);
1766 if (poolObj
->policy
== nullptr) {
1767 g_outputBuffer
=g_policy
.getLocal()->name
+"\n";
1769 g_outputBuffer
=poolObj
->policy
->name
+"\n";
1773 g_lua
.writeFunction("setTCPDownstreamCleanupInterval", [](uint16_t interval
) {
1775 g_downstreamTCPCleanupInterval
= interval
;
1778 g_lua
.writeFunction("setConsoleConnectionsLogging", [](bool enabled
) {
1779 g_logConsoleConnections
= enabled
;
1782 g_lua
.writeFunction("setConsoleOutputMaxMsgSize", [](uint32_t size
) {
1783 g_consoleOutputMsgMaxSize
= size
;
1786 g_lua
.writeFunction("setUDPMultipleMessagesVectorSize", [](size_t vSize
) {
1787 if (g_configurationDone
) {
1788 errlog("setUDPMultipleMessagesVectorSize() cannot be used at runtime!");
1789 g_outputBuffer
="setUDPMultipleMessagesVectorSize() cannot be used at runtime!\n";
1792 #if defined(HAVE_RECVMMSG) && defined(HAVE_SENDMMSG) && defined(MSG_WAITFORONE)
1794 g_udpVectorSize
= vSize
;
1796 errlog("recvmmsg() support is not available!");
1797 g_outputBuffer
="recvmmsg support is not available!\n";
1801 g_lua
.writeFunction("setAddEDNSToSelfGeneratedResponses", [](bool add
) {
1802 g_addEDNSToSelfGeneratedResponses
= add
;
1805 g_lua
.writeFunction("setPayloadSizeOnSelfGeneratedAnswers", [](uint16_t payloadSize
) {
1806 if (payloadSize
< 512) {
1807 warnlog("setPayloadSizeOnSelfGeneratedAnswers() is set too low, using 512 instead!");
1808 g_outputBuffer
="setPayloadSizeOnSelfGeneratedAnswers() is set too low, using 512 instead!";
1811 if (payloadSize
> s_udpIncomingBufferSize
) {
1812 warnlog("setPayloadSizeOnSelfGeneratedAnswers() is set too high, capping to %d instead!", s_udpIncomingBufferSize
);
1813 g_outputBuffer
="setPayloadSizeOnSelfGeneratedAnswers() is set too high, capping to " + std::to_string(s_udpIncomingBufferSize
) + " instead";
1814 payloadSize
= s_udpIncomingBufferSize
;
1816 g_PayloadSizeSelfGenAnswers
= payloadSize
;
1819 g_lua
.writeFunction("setSecurityPollSuffix", [](const std::string
& suffix
) {
1820 if (g_configurationDone
) {
1821 g_outputBuffer
="setSecurityPollSuffix() cannot be used at runtime!\n";
1825 g_secPollSuffix
= suffix
;
1828 g_lua
.writeFunction("setSecurityPollInterval", [](time_t newInterval
) {
1829 if (newInterval
<= 0) {
1830 warnlog("setSecurityPollInterval() should be > 0, skipping");
1831 g_outputBuffer
="setSecurityPollInterval() should be > 0, skipping";
1834 g_secPollInterval
= newInterval
;
1837 g_lua
.writeFunction("setSyslogFacility", [](int facility
) {
1839 if (g_configurationDone
) {
1840 g_outputBuffer
="setSyslogFacility cannot be used at runtime!\n";
1843 setSyslogFacility(facility
);
1846 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
) {
1850 #ifdef HAVE_DNS_OVER_HTTPS
1852 if (g_configurationDone
) {
1853 g_outputBuffer
="addDOHLocal cannot be used at runtime!\n";
1856 auto frontend
= std::make_shared
<DOHFrontend
>();
1858 if (certFiles
&& !certFiles
->empty() && keyFiles
&& !keyFiles
->empty()) {
1859 if (!loadTLSCertificateAndKeys("addDOHLocal", frontend
->d_tlsConfig
.d_certKeyPairs
, *certFiles
, *keyFiles
)) {
1863 frontend
->d_local
= ComboAddress(addr
, 443);
1866 frontend
->d_local
= ComboAddress(addr
, 80);
1867 infolog("No certificate provided for DoH endpoint %s, running in DNS over HTTP mode instead of DNS over HTTPS", frontend
->d_local
.toStringWithPort());
1871 if (urls
->type() == typeid(std::string
)) {
1872 frontend
->d_urls
.push_back(boost::get
<std::string
>(*urls
));
1874 else if (urls
->type() == typeid(std::vector
<std::pair
<int,std::string
>>)) {
1875 auto urlsVect
= boost::get
<std::vector
<std::pair
<int,std::string
>>>(*urls
);
1876 for(const auto& p
: urlsVect
) {
1877 frontend
->d_urls
.push_back(p
.second
);
1882 frontend
->d_urls
= {"/dns-query"};
1885 bool reusePort
= false;
1886 int tcpFastOpenQueueSize
= 0;
1887 std::string interface
;
1891 parseLocalBindVars(vars
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
);
1893 if (vars
->count("idleTimeout")) {
1894 frontend
->d_idleTimeout
= boost::get
<int>((*vars
)["idleTimeout"]);
1897 if (vars
->count("serverTokens")) {
1898 frontend
->d_serverTokens
= boost::get
<const string
>((*vars
)["serverTokens"]);
1901 if (vars
->count("customResponseHeaders")) {
1902 for (auto const& headerMap
: boost::get
<std::map
<std::string
,std::string
>>((*vars
)["customResponseHeaders"])) {
1903 std::pair
<std::string
,std::string
> headerResponse
= std::make_pair(boost::to_lower_copy(headerMap
.first
), headerMap
.second
);
1904 frontend
->d_customResponseHeaders
.push_back(headerResponse
);
1908 if (vars
->count("sendCacheControlHeaders")) {
1909 frontend
->d_sendCacheControlHeaders
= boost::get
<bool>((*vars
)["sendCacheControlHeaders"]);
1912 parseTLSConfig(frontend
->d_tlsConfig
, "addDOHLocal", vars
);
1914 g_dohlocals
.push_back(frontend
);
1915 auto cs
= std::unique_ptr
<ClientState
>(new ClientState(frontend
->d_local
, true, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
));
1916 cs
->dohFrontend
= frontend
;
1917 g_frontends
.push_back(std::move(cs
));
1919 throw std::runtime_error("addDOHLocal() called but DNS over HTTPS support is not present!");
1923 g_lua
.writeFunction("showDOHFrontends", []() {
1924 #ifdef HAVE_DNS_OVER_HTTPS
1925 setLuaNoSideEffect();
1928 boost::format
fmt("%-3d %-20.20s %-15d %-15d %-15d %-15d %-15d %-15d %-15d %-15d %-15d %-15d %-15d %-15d");
1929 ret
<< (fmt
% "#" % "Address" % "HTTP" % "HTTP/1" % "HTTP/2" % "GET" % "POST" % "Bad" % "Errors" % "Redirects" % "Valid" % "# ticket keys" % "Rotation delay" % "Next rotation") << endl
;
1931 for (const auto& ctx
: g_dohlocals
) {
1932 ret
<< (fmt
% counter
% ctx
->d_local
.toStringWithPort() % ctx
->d_httpconnects
% ctx
->d_http1Stats
.d_nbQueries
% ctx
->d_http1Stats
.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
;
1935 g_outputBuffer
= ret
.str();
1937 catch(const std::exception
& e
) {
1938 g_outputBuffer
= e
.what();
1942 g_outputBuffer
="DNS over HTTPS support is not present!\n";
1946 g_lua
.writeFunction("showDOHResponseCodes", []() {
1947 #ifdef HAVE_DNS_OVER_HTTPS
1948 setLuaNoSideEffect();
1951 boost::format
fmt("%-3d %-20.20s %-15d %-15d %-15d %-15d %-15d %-15d");
1952 g_outputBuffer
= "\n- HTTP/1:\n\n";
1953 ret
<< (fmt
% "#" % "Address" % "200" % "400" % "403" % "500" % "502" % "Others" ) << endl
;
1955 for (const auto& ctx
: g_dohlocals
) {
1956 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
;
1959 g_outputBuffer
+= ret
.str();
1962 g_outputBuffer
+= "\n- HTTP/2:\n\n";
1963 ret
<< (fmt
% "#" % "Address" % "200" % "400" % "403" % "500" % "502" % "Others" ) << endl
;
1965 for (const auto& ctx
: g_dohlocals
) {
1966 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
;
1969 g_outputBuffer
+= ret
.str();
1971 catch(const std::exception
& e
) {
1972 g_outputBuffer
= e
.what();
1976 g_outputBuffer
="DNS over HTTPS support is not present!\n";
1980 g_lua
.writeFunction("getDOHFrontend", [client
](size_t index
) {
1981 std::shared_ptr
<DOHFrontend
> result
= nullptr;
1985 #ifdef HAVE_DNS_OVER_HTTPS
1986 setLuaNoSideEffect();
1988 if (index
< g_dohlocals
.size()) {
1989 result
= g_dohlocals
.at(index
);
1992 errlog("Error: trying to get DOH frontend with index %zu but we only have %zu frontend(s)\n", index
, g_dohlocals
.size());
1993 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";
1996 catch(const std::exception
& e
) {
1997 g_outputBuffer
="Error while trying to get DOH frontend with index " + std::to_string(index
) + ": "+string(e
.what())+"\n";
1998 errlog("Error while trying to get DOH frontend with index %zu: %s\n", index
, string(e
.what()));
2001 g_outputBuffer
="DNS over HTTPS support is not present!\n";
2006 g_lua
.writeFunction("getDOHFrontendCount", []() {
2007 setLuaNoSideEffect();
2008 return g_dohlocals
.size();
2011 g_lua
.registerFunction
<void(std::shared_ptr
<DOHFrontend
>::*)()>("reloadCertificates", [](std::shared_ptr
<DOHFrontend
> frontend
) {
2012 if (frontend
!= nullptr) {
2013 frontend
->reloadCertificates();
2017 g_lua
.registerFunction
<void(std::shared_ptr
<DOHFrontend
>::*)()>("rotateTicketsKey", [](std::shared_ptr
<DOHFrontend
> frontend
) {
2018 if (frontend
!= nullptr) {
2019 frontend
->rotateTicketsKey(time(nullptr));
2023 g_lua
.registerFunction
<void(std::shared_ptr
<DOHFrontend
>::*)(const std::string
&)>("loadTicketsKeys", [](std::shared_ptr
<DOHFrontend
> frontend
, const std::string
& file
) {
2024 if (frontend
!= nullptr) {
2025 frontend
->loadTicketsKeys(file
);
2029 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
) {
2030 if (frontend
!= nullptr) {
2031 std::vector
<std::shared_ptr
<DOHResponseMapEntry
>> newMap
;
2032 newMap
.reserve(map
.size());
2034 for (const auto& entry
: map
) {
2035 newMap
.push_back(entry
.second
);
2038 frontend
->d_responsesMap
= std::move(newMap
);
2042 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
) {
2046 #ifdef HAVE_DNS_OVER_TLS
2048 if (g_configurationDone
) {
2049 g_outputBuffer
="addTLSLocal cannot be used at runtime!\n";
2052 shared_ptr
<TLSFrontend
> frontend
= std::make_shared
<TLSFrontend
>();
2054 if (!loadTLSCertificateAndKeys("addTLSLocal", frontend
->d_tlsConfig
.d_certKeyPairs
, certFiles
, keyFiles
)) {
2058 bool reusePort
= false;
2059 int tcpFastOpenQueueSize
= 0;
2060 std::string interface
;
2064 parseLocalBindVars(vars
, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
);
2066 if (vars
->count("provider")) {
2067 frontend
->d_provider
= boost::get
<const string
>((*vars
)["provider"]);
2068 boost::algorithm::to_lower(frontend
->d_provider
);
2071 parseTLSConfig(frontend
->d_tlsConfig
, "addTLSLocal", vars
);
2075 frontend
->d_addr
= ComboAddress(addr
, 853);
2076 if (!frontend
->d_provider
.empty()) {
2077 vinfolog("Loading TLS provider '%s'", frontend
->d_provider
);
2081 vinfolog("Loading default TLS provider 'openssl'");
2083 vinfolog("Loading default TLS provider 'gnutls'");
2086 // only works pre-startup, so no sync necessary
2087 auto cs
= std::unique_ptr
<ClientState
>(new ClientState(frontend
->d_addr
, true, reusePort
, tcpFastOpenQueueSize
, interface
, cpus
));
2088 cs
->tlsFrontend
= frontend
;
2089 g_tlslocals
.push_back(cs
->tlsFrontend
);
2090 g_frontends
.push_back(std::move(cs
));
2092 catch(const std::exception
& e
) {
2093 g_outputBuffer
="Error: "+string(e
.what())+"\n";
2096 throw std::runtime_error("addTLSLocal() called but DNS over TLS support is not present!");
2100 g_lua
.writeFunction("showTLSContexts", []() {
2101 #ifdef HAVE_DNS_OVER_TLS
2102 setLuaNoSideEffect();
2105 boost::format
fmt("%1$-3d %2$-20.20s %|25t|%3$-14d %|40t|%4$-14d %|54t|%5$-21.21s");
2107 ret
<< (fmt
% "#" % "Address" % "# ticket keys" % "Rotation delay" % "Next rotation" ) << endl
;
2109 for (const auto& ctx
: g_tlslocals
) {
2110 ret
<< (fmt
% counter
% ctx
->d_addr
.toStringWithPort() % ctx
->getTicketsKeysCount() % ctx
->getTicketsKeyRotationDelay() % ctx
->getNextTicketsKeyRotation()) << endl
;
2113 g_outputBuffer
= ret
.str();
2115 catch(const std::exception
& e
) {
2116 g_outputBuffer
= e
.what();
2120 g_outputBuffer
="DNS over TLS support is not present!\n";
2124 g_lua
.writeFunction("getTLSContext", [](size_t index
) {
2125 std::shared_ptr
<TLSCtx
> result
= nullptr;
2126 #ifdef HAVE_DNS_OVER_TLS
2127 setLuaNoSideEffect();
2129 if (index
< g_tlslocals
.size()) {
2130 result
= g_tlslocals
.at(index
)->getContext();
2133 errlog("Error: trying to get TLS context with index %zu but we only have %zu context(s)\n", index
, g_tlslocals
.size());
2134 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";
2137 catch(const std::exception
& e
) {
2138 g_outputBuffer
="Error while trying to get TLS context with index " + std::to_string(index
) + ": "+string(e
.what())+"\n";
2139 errlog("Error while trying to get TLS context with index %zu: %s\n", index
, string(e
.what()));
2142 g_outputBuffer
="DNS over TLS support is not present!\n";
2147 g_lua
.writeFunction("getTLSFrontend", [](size_t index
) {
2148 std::shared_ptr
<TLSFrontend
> result
= nullptr;
2149 #ifdef HAVE_DNS_OVER_TLS
2150 setLuaNoSideEffect();
2152 if (index
< g_tlslocals
.size()) {
2153 result
= g_tlslocals
.at(index
);
2156 errlog("Error: trying to get TLS frontend with index %zu but we only have %zu frontends\n", index
, g_tlslocals
.size());
2157 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";
2160 catch(const std::exception
& e
) {
2161 g_outputBuffer
="Error while trying to get TLS frontend with index " + std::to_string(index
) + ": "+string(e
.what())+"\n";
2162 errlog("Error while trying to get TLS frontend with index %zu: %s\n", index
, string(e
.what()));
2165 g_outputBuffer
="DNS over TLS support is not present!\n";
2170 g_lua
.writeFunction("getTLSFrontendCount", []() {
2171 setLuaNoSideEffect();
2172 return g_tlslocals
.size();
2175 g_lua
.registerFunction
<void(std::shared_ptr
<TLSCtx
>::*)()>("rotateTicketsKey", [](std::shared_ptr
<TLSCtx
> ctx
) {
2176 if (ctx
!= nullptr) {
2177 ctx
->rotateTicketsKey(time(nullptr));
2181 g_lua
.registerFunction
<void(std::shared_ptr
<TLSCtx
>::*)(const std::string
&)>("loadTicketsKeys", [](std::shared_ptr
<TLSCtx
> ctx
, const std::string
& file
) {
2182 if (ctx
!= nullptr) {
2183 ctx
->loadTicketsKeys(file
);
2187 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
) {
2188 #ifdef HAVE_DNS_OVER_TLS
2189 if (loadTLSCertificateAndKeys("loadNewCertificatesAndKeys", frontend
->d_tlsConfig
.d_certKeyPairs
, certFiles
, keyFiles
)) {
2190 frontend
->setupTLS();
2195 g_lua
.writeFunction("reloadAllCertificates", []() {
2196 for (auto& frontend
: g_frontends
) {
2201 #ifdef HAVE_DNSCRYPT
2202 if (frontend
->dnscryptCtx
) {
2203 frontend
->dnscryptCtx
->reloadCertificates();
2205 #endif /* HAVE_DNSCRYPT */
2206 #ifdef HAVE_DNS_OVER_TLS
2207 if (frontend
->tlsFrontend
) {
2208 frontend
->tlsFrontend
->setupTLS();
2210 #endif /* HAVE_DNS_OVER_TLS */
2211 #ifdef HAVE_DNS_OVER_HTTPS
2212 if (frontend
->dohFrontend
) {
2213 frontend
->dohFrontend
->reloadCertificates();
2215 #endif /* HAVE_DNS_OVER_HTTPS */
2217 catch(const std::exception
& e
) {
2218 errlog("Error reloading certificates for frontend %s: %s", frontend
->local
.toStringWithPort(), e
.what());
2223 g_lua
.writeFunction("setAllowEmptyResponse", [](bool allow
) { g_allowEmptyResponse
=allow
; });
2225 #if defined(HAVE_LIBSSL) && defined(HAVE_OCSP_BASIC_SIGN)
2226 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
) {
2231 libssl_generate_ocsp_response(certFile
, caCert
, caKey
, outFile
, ndays
, nmin
);
2233 #endif /* HAVE_LIBSSL && HAVE_OCSP_BASIC_SIGN*/
2236 vector
<std::function
<void(void)>> setupLua(bool client
, bool configCheck
, const std::string
& config
)
2238 g_launchWork
= new vector
<std::function
<void(void)>>();
2241 setupLuaConfig(client
, configCheck
);
2242 setupLuaBindings(client
);
2243 setupLuaBindingsDNSCrypt();
2244 setupLuaBindingsDNSQuestion();
2245 setupLuaBindingsKVS(client
);
2246 setupLuaBindingsPacketCache();
2247 setupLuaBindingsProtoBuf(client
, configCheck
);
2248 setupLuaInspection();
2252 #ifdef LUAJIT_VERSION
2253 g_lua
.executeCode(getLuaFFIWrappers());
2256 std::ifstream
ifs(config
);
2258 warnlog("Unable to read configuration from '%s'", config
);
2260 vinfolog("Read configuration from '%s'", config
);
2262 g_lua
.executeCode(ifs
);
2264 auto ret
= *g_launchWork
;
2265 delete g_launchWork
;
2266 g_launchWork
= nullptr;