]> git.ipfire.org Git - thirdparty/pdns.git/blob - pdns/dnsdist-lua.cc
dnsdist: squelch unused function warning
[thirdparty/pdns.git] / pdns / dnsdist-lua.cc
1 /*
2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of version 2 of the GNU General Public License as
7 * published by the Free Software Foundation.
8 *
9 * In addition, for the avoidance of any doubt, permission is granted to
10 * link this program with OpenSSL and to (re)distribute the binaries
11 * produced as the result of such linking.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
22
23 #include <dirent.h>
24 #include <fstream>
25
26 // for OpenBSD, sys/socket.h needs to come before net/if.h
27 #include <sys/socket.h>
28 #include <net/if.h>
29
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <thread>
33
34 #include "dnsdist.hh"
35 #include "dnsdist-console.hh"
36 #include "dnsdist-ecs.hh"
37 #include "dnsdist-lua.hh"
38 #include "dnsdist-rings.hh"
39 #include "dnsdist-secpoll.hh"
40
41 #include "base64.hh"
42 #include "dnswriter.hh"
43 #include "dolog.hh"
44 #include "lock.hh"
45 #include "protobuf.hh"
46 #include "sodcrypto.hh"
47
48 #include <boost/logic/tribool.hpp>
49 #include <boost/lexical_cast.hpp>
50
51 #ifdef HAVE_SYSTEMD
52 #include <systemd/sd-daemon.h>
53 #endif
54
55 using std::thread;
56
57 static vector<std::function<void(void)>>* g_launchWork = nullptr;
58
59 boost::tribool g_noLuaSideEffect;
60 static bool g_included{false};
61
62 /* this is a best effort way to prevent logging calls with no side-effects in the output of delta()
63 Functions can declare setLuaNoSideEffect() and if nothing else does declare a side effect, or nothing
64 has done so before on this invocation, this call won't be part of delta() output */
65 void setLuaNoSideEffect()
66 {
67 if(g_noLuaSideEffect==false) // there has been a side effect already
68 return;
69 g_noLuaSideEffect=true;
70 }
71
72 void setLuaSideEffect()
73 {
74 g_noLuaSideEffect=false;
75 }
76
77 bool getLuaNoSideEffect()
78 {
79 if (g_noLuaSideEffect) {
80 return true;
81 }
82 return false;
83 }
84
85 void resetLuaSideEffect()
86 {
87 g_noLuaSideEffect = boost::logic::indeterminate;
88 }
89
90 typedef std::unordered_map<std::string, boost::variant<bool, int, std::string, std::vector<std::pair<int,int> > > > localbind_t;
91
92 static void parseLocalBindVars(boost::optional<localbind_t> vars, bool& reusePort, int& tcpFastOpenQueueSize, std::string& interface, std::set<int>& cpus)
93 {
94 if (vars) {
95 if (vars->count("reusePort")) {
96 reusePort = boost::get<bool>((*vars)["reusePort"]);
97 }
98 if (vars->count("tcpFastOpenQueueSize")) {
99 tcpFastOpenQueueSize = boost::get<int>((*vars)["tcpFastOpenQueueSize"]);
100 }
101 if (vars->count("interface")) {
102 interface = boost::get<std::string>((*vars)["interface"]);
103 }
104 if (vars->count("cpus")) {
105 for (const auto cpu : boost::get<std::vector<std::pair<int,int>>>((*vars)["cpus"])) {
106 cpus.insert(cpu.second);
107 }
108 }
109 }
110 }
111
112 #if defined(HAVE_DNS_OVER_TLS) || defined(HAVE_DNS_OVER_HTTPS)
113 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)
114 {
115 if (certFiles.type() == typeid(std::string) && keyFiles.type() == typeid(std::string)) {
116 auto certFile = boost::get<std::string>(certFiles);
117 auto keyFile = boost::get<std::string>(keyFiles);
118 pairs.clear();
119 pairs.push_back({certFile, keyFile});
120 }
121 else if (certFiles.type() == typeid(std::vector<std::pair<int,std::string>>) && keyFiles.type() == typeid(std::vector<std::pair<int,std::string>>))
122 {
123 auto certFilesVect = boost::get<std::vector<std::pair<int,std::string>>>(certFiles);
124 auto keyFilesVect = boost::get<std::vector<std::pair<int,std::string>>>(keyFiles);
125 if (certFilesVect.size() == keyFilesVect.size()) {
126 pairs.clear();
127 for (size_t idx = 0; idx < certFilesVect.size(); idx++) {
128 pairs.push_back({certFilesVect.at(idx).second, keyFilesVect.at(idx).second});
129 }
130 }
131 else {
132 errlog("Error, mismatching number of certificates and keys in call to %s()!", context);
133 g_outputBuffer="Error, mismatching number of certificates and keys in call to " + context + "()!";
134 return false;
135 }
136 }
137 else {
138 errlog("Error, mismatching number of certificates and keys in call to %s()!", context);
139 g_outputBuffer="Error, mismatching number of certificates and keys in call to " + context + "()!";
140 return false;
141 }
142
143 return true;
144 }
145 #endif // defined(HAVE_DNS_OVER_TLS) || defined(HAVE_DNS_OVER_HTTPS)
146
147 void setupLuaConfig(bool client)
148 {
149 typedef std::unordered_map<std::string, boost::variant<bool, std::string, vector<pair<int, std::string> >, DownstreamState::checkfunc_t > > newserver_t;
150 g_lua.writeFunction("inClientStartup", [client]() {
151 return client && !g_configurationDone;
152 });
153
154 g_lua.writeFunction("newServer",
155 [client](boost::variant<string,newserver_t> pvars, boost::optional<int> qps) {
156 setLuaSideEffect();
157
158 std::shared_ptr<DownstreamState> ret = std::make_shared<DownstreamState>(ComboAddress());
159 newserver_t vars;
160
161 ComboAddress serverAddr;
162 std::string serverAddressStr;
163 if(auto addrStr = boost::get<string>(&pvars)) {
164 serverAddressStr = *addrStr;
165 if(qps) {
166 vars["qps"] = std::to_string(*qps);
167 }
168 } else {
169 vars = boost::get<newserver_t>(pvars);
170 serverAddressStr = boost::get<string>(vars["address"]);
171 }
172
173 try {
174 serverAddr = ComboAddress(serverAddressStr, 53);
175 }
176 catch(const PDNSException& e) {
177 g_outputBuffer="Error creating new server: "+string(e.reason);
178 errlog("Error creating new server with address %s: %s", serverAddressStr, e.reason);
179 return ret;
180 }
181 catch(std::exception& e) {
182 g_outputBuffer="Error creating new server: "+string(e.what());
183 errlog("Error creating new server with address %s: %s", serverAddressStr, e.what());
184 return ret;
185 }
186
187 if(IsAnyAddress(serverAddr)) {
188 g_outputBuffer="Error creating new server: invalid address for a downstream server.";
189 errlog("Error creating new server: %s is not a valid address for a downstream server", serverAddressStr);
190 return ret;
191 }
192
193 ComboAddress sourceAddr;
194 unsigned int sourceItf = 0;
195 size_t numberOfSockets = 1;
196 std::set<int> cpus;
197
198 if(vars.count("source")) {
199 /* handle source in the following forms:
200 - v4 address ("192.0.2.1")
201 - v6 address ("2001:DB8::1")
202 - interface name ("eth0")
203 - v4 address and interface name ("192.0.2.1@eth0")
204 - v6 address and interface name ("2001:DB8::1@eth0")
205 */
206 const string source = boost::get<string>(vars["source"]);
207 bool parsed = false;
208 std::string::size_type pos = source.find("@");
209 if (pos == std::string::npos) {
210 /* no '@', try to parse that as a valid v4/v6 address */
211 try {
212 sourceAddr = ComboAddress(source);
213 parsed = true;
214 }
215 catch(...)
216 {
217 }
218 }
219
220 if (parsed == false)
221 {
222 /* try to parse as interface name, or v4/v6@itf */
223 string itfName = source.substr(pos == std::string::npos ? 0 : pos + 1);
224 unsigned int itfIdx = if_nametoindex(itfName.c_str());
225
226 if (itfIdx != 0) {
227 if (pos == 0 || pos == std::string::npos) {
228 /* "eth0" or "@eth0" */
229 sourceItf = itfIdx;
230 }
231 else {
232 /* "192.0.2.1@eth0" */
233 sourceAddr = ComboAddress(source.substr(0, pos));
234 sourceItf = itfIdx;
235 }
236 }
237 else
238 {
239 warnlog("Dismissing source %s because '%s' is not a valid interface name", source, itfName);
240 }
241 }
242 }
243
244 if (vars.count("sockets")) {
245 numberOfSockets = std::stoul(boost::get<string>(vars["sockets"]));
246 if (numberOfSockets == 0) {
247 warnlog("Dismissing invalid number of sockets '%s', using 1 instead", boost::get<string>(vars["sockets"]));
248 numberOfSockets = 1;
249 }
250 }
251
252 if(client) {
253 // do not construct DownstreamState now, it would try binding sockets.
254 return ret;
255 }
256 ret=std::make_shared<DownstreamState>(serverAddr, sourceAddr, sourceItf, numberOfSockets);
257
258 if(vars.count("qps")) {
259 int qpsVal=std::stoi(boost::get<string>(vars["qps"]));
260 ret->qps=QPSLimiter(qpsVal, qpsVal);
261 }
262
263 if(vars.count("order")) {
264 ret->order=std::stoi(boost::get<string>(vars["order"]));
265 }
266
267 if(vars.count("weight")) {
268 try {
269 int weightVal=std::stoi(boost::get<string>(vars["weight"]));
270
271 if(weightVal < 1) {
272 errlog("Error creating new server: downstream weight value must be greater than 0.");
273 return ret;
274 }
275
276 ret->setWeight(weightVal);
277 }
278 catch(std::exception& e) {
279 // std::stoi will throw an exception if the string isn't in a value int range
280 errlog("Error creating new server: downstream weight value must be between %s and %s", 1, std::numeric_limits<int>::max());
281 return ret;
282 }
283 }
284
285 if(vars.count("retries")) {
286 ret->retries=std::stoi(boost::get<string>(vars["retries"]));
287 }
288
289 if(vars.count("checkInterval")) {
290 ret->checkInterval=static_cast<unsigned int>(std::stoul(boost::get<string>(vars["checkInterval"])));
291 }
292
293 if(vars.count("tcpConnectTimeout")) {
294 ret->tcpConnectTimeout=std::stoi(boost::get<string>(vars["tcpConnectTimeout"]));
295 }
296
297 if(vars.count("tcpSendTimeout")) {
298 ret->tcpSendTimeout=std::stoi(boost::get<string>(vars["tcpSendTimeout"]));
299 }
300
301 if(vars.count("tcpRecvTimeout")) {
302 ret->tcpRecvTimeout=std::stoi(boost::get<string>(vars["tcpRecvTimeout"]));
303 }
304
305 if(vars.count("tcpFastOpen")) {
306 bool fastOpen = boost::get<bool>(vars["tcpFastOpen"]);
307 if (fastOpen) {
308 #ifdef MSG_FASTOPEN
309 ret->tcpFastOpen=true;
310 #else
311 warnlog("TCP Fast Open has been configured on downstream server %s but is not supported", boost::get<string>(vars["address"]));
312 #endif
313 }
314 }
315
316 if(vars.count("name")) {
317 ret->name=boost::get<string>(vars["name"]);
318 }
319
320 if (vars.count("id")) {
321 ret->setId(boost::lexical_cast<boost::uuids::uuid>(boost::get<string>(vars["id"])));
322 }
323
324 if(vars.count("checkName")) {
325 ret->checkName=DNSName(boost::get<string>(vars["checkName"]));
326 }
327
328 if(vars.count("checkType")) {
329 ret->checkType=boost::get<string>(vars["checkType"]);
330 }
331
332 if(vars.count("checkClass")) {
333 ret->checkClass=std::stoi(boost::get<string>(vars["checkClass"]));
334 }
335
336 if(vars.count("checkFunction")) {
337 ret->checkFunction= boost::get<DownstreamState::checkfunc_t>(vars["checkFunction"]);
338 }
339
340 if(vars.count("checkTimeout")) {
341 ret->checkTimeout = std::stoi(boost::get<string>(vars["checkTimeout"]));
342 }
343
344 if(vars.count("setCD")) {
345 ret->setCD=boost::get<bool>(vars["setCD"]);
346 }
347
348 if(vars.count("mustResolve")) {
349 ret->mustResolve=boost::get<bool>(vars["mustResolve"]);
350 }
351
352 if(vars.count("useClientSubnet")) {
353 ret->useECS=boost::get<bool>(vars["useClientSubnet"]);
354 }
355
356 if(vars.count("disableZeroScope")) {
357 ret->disableZeroScope=boost::get<bool>(vars["disableZeroScope"]);
358 }
359
360 if(vars.count("ipBindAddrNoPort")) {
361 ret->ipBindAddrNoPort=boost::get<bool>(vars["ipBindAddrNoPort"]);
362 }
363
364 if(vars.count("addXPF")) {
365 ret->xpfRRCode=std::stoi(boost::get<string>(vars["addXPF"]));
366 }
367
368 if(vars.count("maxCheckFailures")) {
369 ret->maxCheckFailures=std::stoi(boost::get<string>(vars["maxCheckFailures"]));
370 }
371
372 if(vars.count("rise")) {
373 ret->minRiseSuccesses=std::stoi(boost::get<string>(vars["rise"]));
374 }
375
376 if(vars.count("cpus")) {
377 for (const auto cpu : boost::get<vector<pair<int,string>>>(vars["cpus"])) {
378 cpus.insert(std::stoi(cpu.second));
379 }
380 }
381
382 /* this needs to be done _AFTER_ the order has been set,
383 since the server are kept ordered inside the pool */
384 auto localPools = g_pools.getCopy();
385 if(vars.count("pool")) {
386 if(auto* pool = boost::get<string>(&vars["pool"])) {
387 ret->pools.insert(*pool);
388 }
389 else {
390 auto pools = boost::get<vector<pair<int, string> > >(vars["pool"]);
391 for(auto& p : pools) {
392 ret->pools.insert(p.second);
393 }
394 }
395 for(const auto& poolName: ret->pools) {
396 addServerToPool(localPools, poolName, ret);
397 }
398 }
399 else {
400 addServerToPool(localPools, "", ret);
401 }
402 g_pools.setState(localPools);
403
404 if (ret->connected) {
405 ret->threadStarted.test_and_set();
406
407 if(g_launchWork) {
408 g_launchWork->push_back([ret,cpus]() {
409 ret->tid = thread(responderThread, ret);
410 if (!cpus.empty()) {
411 mapThreadToCPUList(ret->tid.native_handle(), cpus);
412 }
413 });
414 }
415 else {
416 ret->tid = thread(responderThread, ret);
417 if (!cpus.empty()) {
418 mapThreadToCPUList(ret->tid.native_handle(), cpus);
419 }
420 }
421 }
422
423 auto states = g_dstates.getCopy();
424 states.push_back(ret);
425 std::stable_sort(states.begin(), states.end(), [](const decltype(ret)& a, const decltype(ret)& b) {
426 return a->order < b->order;
427 });
428 g_dstates.setState(states);
429 return ret;
430 } );
431
432 g_lua.writeFunction("rmServer",
433 [](boost::variant<std::shared_ptr<DownstreamState>, int> var)
434 {
435 setLuaSideEffect();
436 shared_ptr<DownstreamState> server;
437 auto* rem = boost::get<shared_ptr<DownstreamState>>(&var);
438 auto states = g_dstates.getCopy();
439 if(rem) {
440 server = *rem;
441 }
442 else {
443 int idx = boost::get<int>(var);
444 server = states.at(idx);
445 }
446 auto localPools = g_pools.getCopy();
447 for (const string& poolName : server->pools) {
448 removeServerFromPool(localPools, poolName, server);
449 }
450 /* the server might also be in the default pool */
451 removeServerFromPool(localPools, "", server);
452 g_pools.setState(localPools);
453 states.erase(remove(states.begin(), states.end(), server), states.end());
454 g_dstates.setState(states);
455 } );
456
457 g_lua.writeFunction("setServerPolicy", [](ServerPolicy policy) {
458 setLuaSideEffect();
459 g_policy.setState(policy);
460 });
461 g_lua.writeFunction("setServerPolicyLua", [](string name, policyfunc_t policy) {
462 setLuaSideEffect();
463 g_policy.setState(ServerPolicy{name, policy, true});
464 });
465
466 g_lua.writeFunction("showServerPolicy", []() {
467 setLuaSideEffect();
468 g_outputBuffer=g_policy.getLocal()->name+"\n";
469 });
470
471 g_lua.writeFunction("truncateTC", [](bool tc) { setLuaSideEffect(); g_truncateTC=tc; });
472 g_lua.writeFunction("fixupCase", [](bool fu) { setLuaSideEffect(); g_fixupCase=fu; });
473
474 g_lua.writeFunction("addACL", [](const std::string& domain) {
475 setLuaSideEffect();
476 g_ACL.modify([domain](NetmaskGroup& nmg) { nmg.addMask(domain); });
477 });
478
479 g_lua.writeFunction("setLocal", [client](const std::string& addr, boost::optional<localbind_t> vars) {
480 setLuaSideEffect();
481 if(client)
482 return;
483 if (g_configurationDone) {
484 g_outputBuffer="setLocal cannot be used at runtime!\n";
485 return;
486 }
487 bool reusePort = false;
488 int tcpFastOpenQueueSize = 0;
489 std::string interface;
490 std::set<int> cpus;
491
492 parseLocalBindVars(vars, reusePort, tcpFastOpenQueueSize, interface, cpus);
493
494 try {
495 ComboAddress loc(addr, 53);
496 for (auto it = g_frontends.begin(); it != g_frontends.end(); ) {
497 /* TLS and DNSCrypt frontends are separate */
498 if ((*it)->tlsFrontend == nullptr && (*it)->dnscryptCtx == nullptr) {
499 it = g_frontends.erase(it);
500 }
501 else {
502 ++it;
503 }
504 }
505
506 // only works pre-startup, so no sync necessary
507 g_frontends.push_back(std::unique_ptr<ClientState>(new ClientState(loc, false, reusePort, tcpFastOpenQueueSize, interface, cpus)));
508 g_frontends.push_back(std::unique_ptr<ClientState>(new ClientState(loc, true, reusePort, tcpFastOpenQueueSize, interface, cpus)));
509 }
510 catch(const std::exception& e) {
511 g_outputBuffer="Error: "+string(e.what())+"\n";
512 }
513 });
514
515 g_lua.writeFunction("addLocal", [client](const std::string& addr, boost::optional<localbind_t> vars) {
516 setLuaSideEffect();
517 if(client)
518 return;
519 if (g_configurationDone) {
520 g_outputBuffer="addLocal cannot be used at runtime!\n";
521 return;
522 }
523 bool reusePort = false;
524 int tcpFastOpenQueueSize = 0;
525 std::string interface;
526 std::set<int> cpus;
527
528 parseLocalBindVars(vars, reusePort, tcpFastOpenQueueSize, interface, cpus);
529
530 try {
531 ComboAddress loc(addr, 53);
532 // only works pre-startup, so no sync necessary
533 g_frontends.push_back(std::unique_ptr<ClientState>(new ClientState(loc, false, reusePort, tcpFastOpenQueueSize, interface, cpus)));
534 g_frontends.push_back(std::unique_ptr<ClientState>(new ClientState(loc, true, reusePort, tcpFastOpenQueueSize, interface, cpus)));
535 }
536 catch(std::exception& e) {
537 g_outputBuffer="Error: "+string(e.what())+"\n";
538 errlog("Error while trying to listen on %s: %s\n", addr, string(e.what()));
539 }
540 });
541
542 g_lua.writeFunction("setACL", [](boost::variant<string,vector<pair<int, string>>> inp) {
543 setLuaSideEffect();
544 NetmaskGroup nmg;
545 if(auto str = boost::get<string>(&inp)) {
546 nmg.addMask(*str);
547 }
548 else for(const auto& p : boost::get<vector<pair<int,string>>>(inp)) {
549 nmg.addMask(p.second);
550 }
551 g_ACL.setState(nmg);
552 });
553
554 g_lua.writeFunction("showACL", []() {
555 setLuaNoSideEffect();
556 vector<string> vec;
557
558 g_ACL.getLocal()->toStringVector(&vec);
559
560 for(const auto& s : vec)
561 g_outputBuffer+=s+"\n";
562
563 });
564
565 g_lua.writeFunction("shutdown", []() {
566 #ifdef HAVE_SYSTEMD
567 sd_notify(0, "STOPPING=1");
568 #endif /* HAVE_SYSTEMD */
569 #if 0
570 // Useful for debugging leaks, but might lead to race under load
571 // since other threads are still runing.
572 for(auto& frontend : g_tlslocals) {
573 frontend->cleanup();
574 }
575 g_tlslocals.clear();
576 #ifdef HAVE_PROTOBUF
577 google::protobuf::ShutdownProtobufLibrary();
578 #endif /* HAVE_PROTOBUF */
579 #endif /* 0 */
580 _exit(0);
581 } );
582
583 typedef std::unordered_map<std::string, boost::variant<bool, std::string> > showserversopts_t;
584
585 g_lua.writeFunction("showServers", [](boost::optional<showserversopts_t> vars) {
586 setLuaNoSideEffect();
587 bool showUUIDs = false;
588 if (vars) {
589 if (vars->count("showUUIDs")) {
590 showUUIDs = boost::get<bool>((*vars)["showUUIDs"]);
591 }
592 }
593 try {
594 ostringstream ret;
595 boost::format fmt;
596 if (showUUIDs) {
597 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%" );
598 // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
599 ret << (fmt % "#" % "Name" % "Address" % "State" % "Qps" % "Qlim" % "Ord" % "Wt" % "Queries" % "Drops" % "Drate" % "Lat" % "Outstanding" % "Pools" % "UUID") << endl;
600 } else {
601 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%" );
602 ret << (fmt % "#" % "Name" % "Address" % "State" % "Qps" % "Qlim" % "Ord" % "Wt" % "Queries" % "Drops" % "Drate" % "Lat" % "Outstanding" % "Pools") << endl;
603 }
604
605 uint64_t totQPS{0}, totQueries{0}, totDrops{0};
606 int counter=0;
607 auto states = g_dstates.getLocal();
608 for(const auto& s : *states) {
609 string status = s->getStatus();
610 string pools;
611 for(auto& p : s->pools) {
612 if(!pools.empty())
613 pools+=" ";
614 pools+=p;
615 }
616 if (showUUIDs) {
617 ret << (fmt % counter % s->name % s->remote.toStringWithPort() %
618 status %
619 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;
620 } else {
621 ret << (fmt % counter % s->name % s->remote.toStringWithPort() %
622 status %
623 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;
624 }
625 totQPS += s->queryLoad;
626 totQueries += s->queries.load();
627 totDrops += s->reuseds.load();
628 ++counter;
629 }
630 if (showUUIDs) {
631 ret<< (fmt % "All" % "" % "" % ""
632 %
633 (double)totQPS % "" % "" % "" % totQueries % totDrops % "" % "" % "" % "" % "" ) << endl;
634 } else {
635 ret<< (fmt % "All" % "" % "" % ""
636 %
637 (double)totQPS % "" % "" % "" % totQueries % totDrops % "" % "" % "" % "" ) << endl;
638 }
639
640 g_outputBuffer=ret.str();
641 } catch(std::exception& e) {
642 g_outputBuffer=e.what();
643 throw;
644 }
645 });
646
647 g_lua.writeFunction("getServers", []() {
648 setLuaNoSideEffect();
649 vector<pair<int, std::shared_ptr<DownstreamState> > > ret;
650 int count=1;
651 for(const auto& s : g_dstates.getCopy()) {
652 ret.push_back(make_pair(count++, s));
653 }
654 return ret;
655 });
656
657 g_lua.writeFunction("getPoolServers", [](string pool) {
658 return getDownstreamCandidates(g_pools.getCopy(), pool);
659 });
660
661 g_lua.writeFunction("getServer", [client](int i) {
662 if (client)
663 return std::make_shared<DownstreamState>(ComboAddress());
664 return g_dstates.getCopy().at(i);
665 });
666
667 g_lua.writeFunction("carbonServer", [](const std::string& address, boost::optional<string> ourName,
668 boost::optional<unsigned int> interval, boost::optional<string> namespace_name,
669 boost::optional<string> instance_name) {
670 setLuaSideEffect();
671 auto ours = g_carbon.getCopy();
672 ours.push_back({
673 ComboAddress(address, 2003),
674 (namespace_name && !namespace_name->empty()) ? *namespace_name : "dnsdist",
675 ourName ? *ourName : "",
676 (instance_name && !instance_name->empty()) ? *instance_name : "main" ,
677 interval ? *interval : 30
678 });
679 g_carbon.setState(ours);
680 });
681
682 g_lua.writeFunction("webserver", [client](const std::string& address, const std::string& password, const boost::optional<std::string> apiKey, const boost::optional<std::map<std::string, std::string> > customHeaders) {
683 setLuaSideEffect();
684 if(client)
685 return;
686 ComboAddress local(address);
687 try {
688 int sock = SSocket(local.sin4.sin_family, SOCK_STREAM, 0);
689 SSetsockopt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
690 SBind(sock, local);
691 SListen(sock, 5);
692 auto launch=[sock, local, password, apiKey, customHeaders]() {
693 setWebserverPassword(password);
694 setWebserverAPIKey(apiKey);
695 setWebserverCustomHeaders(customHeaders);
696 thread t(dnsdistWebserverThread, sock, local);
697 t.detach();
698 };
699 if(g_launchWork)
700 g_launchWork->push_back(launch);
701 else
702 launch();
703 }
704 catch(std::exception& e) {
705 g_outputBuffer="Unable to bind to webserver socket on " + local.toStringWithPort() + ": " + e.what();
706 errlog("Unable to bind to webserver socket on %s: %s", local.toStringWithPort(), e.what());
707 }
708
709 });
710
711 typedef std::unordered_map<std::string, boost::variant<std::string, std::map<std::string, std::string>> > webserveropts_t;
712
713 g_lua.writeFunction("setWebserverConfig", [](boost::optional<webserveropts_t> vars) {
714 setLuaSideEffect();
715
716 if (!vars) {
717 return ;
718 }
719 if(vars->count("password")) {
720 const std::string password = boost::get<std::string>(vars->at("password"));
721
722 setWebserverPassword(password);
723 }
724 if(vars->count("apiKey")) {
725 const std::string apiKey = boost::get<std::string>(vars->at("apiKey"));
726
727 setWebserverAPIKey(apiKey);
728 }
729 if(vars->count("customHeaders")) {
730 const boost::optional<std::map<std::string, std::string> > headers = boost::get<std::map<std::string, std::string> >(vars->at("customHeaders"));
731
732 setWebserverCustomHeaders(headers);
733 }
734 });
735
736 g_lua.writeFunction("controlSocket", [client](const std::string& str) {
737 setLuaSideEffect();
738 ComboAddress local(str, 5199);
739
740 if(client) {
741 g_serverControl = local;
742 return;
743 }
744
745 g_consoleEnabled = true;
746 #ifdef HAVE_LIBSODIUM
747 if (g_configurationDone && g_consoleKey.empty()) {
748 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");
749 }
750 #endif
751
752 try {
753 int sock = SSocket(local.sin4.sin_family, SOCK_STREAM, 0);
754 SSetsockopt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
755 SBind(sock, local);
756 SListen(sock, 5);
757 auto launch=[sock, local]() {
758 thread t(controlThread, sock, local);
759 t.detach();
760 };
761 if(g_launchWork)
762 g_launchWork->push_back(launch);
763 else
764 launch();
765
766 }
767 catch(std::exception& e) {
768 g_outputBuffer="Unable to bind to control socket on " + local.toStringWithPort() + ": " + e.what();
769 errlog("Unable to bind to control socket on %s: %s", local.toStringWithPort(), e.what());
770 }
771 });
772
773 g_lua.writeFunction("addConsoleACL", [](const std::string& netmask) {
774 setLuaSideEffect();
775 #ifndef HAVE_LIBSODIUM
776 warnlog("Allowing remote access to the console while libsodium support has not been enabled is not secure, and will result in cleartext communications");
777 #endif
778
779 g_consoleACL.modify([netmask](NetmaskGroup& nmg) { nmg.addMask(netmask); });
780 });
781
782 g_lua.writeFunction("setConsoleACL", [](boost::variant<string,vector<pair<int, string>>> inp) {
783 setLuaSideEffect();
784
785 #ifndef HAVE_LIBSODIUM
786 warnlog("Allowing remote access to the console while libsodium support has not been enabled is not secure, and will result in cleartext communications");
787 #endif
788
789 NetmaskGroup nmg;
790 if(auto str = boost::get<string>(&inp)) {
791 nmg.addMask(*str);
792 }
793 else for(const auto& p : boost::get<vector<pair<int,string>>>(inp)) {
794 nmg.addMask(p.second);
795 }
796 g_consoleACL.setState(nmg);
797 });
798
799 g_lua.writeFunction("showConsoleACL", []() {
800 setLuaNoSideEffect();
801
802 #ifndef HAVE_LIBSODIUM
803 warnlog("Allowing remote access to the console while libsodium support has not been enabled is not secure, and will result in cleartext communications");
804 #endif
805
806 vector<string> vec;
807 g_consoleACL.getLocal()->toStringVector(&vec);
808
809 for(const auto& s : vec) {
810 g_outputBuffer += s + "\n";
811 }
812 });
813
814 g_lua.writeFunction("clearQueryCounters", []() {
815 unsigned int size{0};
816 {
817 WriteLock wl(&g_qcount.queryLock);
818 size = g_qcount.records.size();
819 g_qcount.records.clear();
820 }
821
822 boost::format fmt("%d records cleared from query counter buffer\n");
823 g_outputBuffer = (fmt % size).str();
824 });
825
826 g_lua.writeFunction("getQueryCounters", [](boost::optional<unsigned int> optMax) {
827 setLuaNoSideEffect();
828 ReadLock rl(&g_qcount.queryLock);
829 g_outputBuffer = "query counting is currently: ";
830 g_outputBuffer+= g_qcount.enabled ? "enabled" : "disabled";
831 g_outputBuffer+= (boost::format(" (%d records in buffer)\n") % g_qcount.records.size()).str();
832
833 boost::format fmt("%-3d %s: %d request(s)\n");
834 QueryCountRecords::iterator it;
835 unsigned int max = optMax ? *optMax : 10;
836 unsigned int index{1};
837 for(it = g_qcount.records.begin(); it != g_qcount.records.end() && index <= max; ++it, ++index) {
838 g_outputBuffer += (fmt % index % it->first % it->second).str();
839 }
840 });
841
842 g_lua.writeFunction("setQueryCount", [](bool enabled) { g_qcount.enabled=enabled; });
843
844 g_lua.writeFunction("setQueryCountFilter", [](QueryCountFilter func) {
845 g_qcount.filter = func;
846 });
847
848 g_lua.writeFunction("makeKey", []() {
849 setLuaNoSideEffect();
850 g_outputBuffer="setKey("+newKey()+")\n";
851 });
852
853 g_lua.writeFunction("setKey", [](const std::string& key) {
854 if(!g_configurationDone && ! g_consoleKey.empty()) { // this makes sure the commandline -k key prevails over dnsdist.conf
855 return; // but later setKeys() trump the -k value again
856 }
857 #ifndef HAVE_LIBSODIUM
858 warnlog("Calling setKey() while libsodium support has not been enabled is not secure, and will result in cleartext communications");
859 #endif
860
861 setLuaSideEffect();
862 string newkey;
863 if(B64Decode(key, newkey) < 0) {
864 g_outputBuffer=string("Unable to decode ")+key+" as Base64";
865 errlog("%s", g_outputBuffer);
866 }
867 else
868 g_consoleKey=newkey;
869 });
870
871 g_lua.writeFunction("testCrypto", [](boost::optional<string> optTestMsg)
872 {
873 setLuaNoSideEffect();
874 #ifdef HAVE_LIBSODIUM
875 try {
876 string testmsg;
877
878 if (optTestMsg) {
879 testmsg = *optTestMsg;
880 }
881 else {
882 testmsg = "testStringForCryptoTests";
883 }
884
885 SodiumNonce sn, sn2;
886 sn.init();
887 sn2=sn;
888 string encrypted = sodEncryptSym(testmsg, g_consoleKey, sn);
889 string decrypted = sodDecryptSym(encrypted, g_consoleKey, sn2);
890
891 sn.increment();
892 sn2.increment();
893
894 encrypted = sodEncryptSym(testmsg, g_consoleKey, sn);
895 decrypted = sodDecryptSym(encrypted, g_consoleKey, sn2);
896
897 if(testmsg == decrypted)
898 g_outputBuffer="Everything is ok!\n";
899 else
900 g_outputBuffer="Crypto failed..\n";
901
902 }
903 catch(...) {
904 g_outputBuffer="Crypto failed..\n";
905 }
906 #else
907 g_outputBuffer="Crypto not available.\n";
908 #endif
909 });
910
911 g_lua.writeFunction("setTCPRecvTimeout", [](int timeout) { g_tcpRecvTimeout=timeout; });
912
913 g_lua.writeFunction("setTCPSendTimeout", [](int timeout) { g_tcpSendTimeout=timeout; });
914
915 g_lua.writeFunction("setUDPTimeout", [](int timeout) { g_udpTimeout=timeout; });
916
917 g_lua.writeFunction("setMaxUDPOutstanding", [](uint16_t max) {
918 if (!g_configurationDone) {
919 g_maxOutstanding = max;
920 } else {
921 g_outputBuffer="Max UDP outstanding cannot be altered at runtime!\n";
922 }
923 });
924
925 g_lua.writeFunction("setMaxTCPClientThreads", [](uint64_t max) {
926 if (!g_configurationDone) {
927 g_maxTCPClientThreads = max;
928 } else {
929 g_outputBuffer="Maximum TCP client threads count cannot be altered at runtime!\n";
930 }
931 });
932
933 g_lua.writeFunction("setMaxTCPQueuedConnections", [](uint64_t max) {
934 if (!g_configurationDone) {
935 g_maxTCPQueuedConnections = max;
936 } else {
937 g_outputBuffer="The maximum number of queued TCP connections cannot be altered at runtime!\n";
938 }
939 });
940
941 g_lua.writeFunction("setMaxTCPQueriesPerConnection", [](size_t max) {
942 if (!g_configurationDone) {
943 g_maxTCPQueriesPerConn = max;
944 } else {
945 g_outputBuffer="The maximum number of queries per TCP connection cannot be altered at runtime!\n";
946 }
947 });
948
949 g_lua.writeFunction("setMaxTCPConnectionsPerClient", [](size_t max) {
950 if (!g_configurationDone) {
951 g_maxTCPConnectionsPerClient = max;
952 } else {
953 g_outputBuffer="The maximum number of TCP connection per client cannot be altered at runtime!\n";
954 }
955 });
956
957 g_lua.writeFunction("setMaxTCPConnectionDuration", [](size_t max) {
958 if (!g_configurationDone) {
959 g_maxTCPConnectionDuration = max;
960 } else {
961 g_outputBuffer="The maximum duration of a TCP connection cannot be altered at runtime!\n";
962 }
963 });
964
965 g_lua.writeFunction("setCacheCleaningDelay", [](uint32_t delay) { g_cacheCleaningDelay = delay; });
966
967 g_lua.writeFunction("setCacheCleaningPercentage", [](uint16_t percentage) { if (percentage < 100) g_cacheCleaningPercentage = percentage; else g_cacheCleaningPercentage = 100; });
968
969 g_lua.writeFunction("setECSSourcePrefixV4", [](uint16_t prefix) { g_ECSSourcePrefixV4=prefix; });
970
971 g_lua.writeFunction("setECSSourcePrefixV6", [](uint16_t prefix) { g_ECSSourcePrefixV6=prefix; });
972
973 g_lua.writeFunction("setECSOverride", [](bool override) { g_ECSOverride=override; });
974
975 g_lua.writeFunction("setPreserveTrailingData", [](bool preserve) { g_preserveTrailingData = preserve; });
976
977 g_lua.writeFunction("showDynBlocks", []() {
978 setLuaNoSideEffect();
979 auto slow = g_dynblockNMG.getCopy();
980 struct timespec now;
981 gettime(&now);
982 boost::format fmt("%-24s %8d %8d %-10s %-20s %s\n");
983 g_outputBuffer = (fmt % "What" % "Seconds" % "Blocks" % "Warning" % "Action" % "Reason").str();
984 for(const auto& e: slow) {
985 if(now < e->second.until)
986 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();
987 }
988 auto slow2 = g_dynblockSMT.getCopy();
989 slow2.visit([&now, &fmt](const SuffixMatchTree<DynBlock>& node) {
990 if(now <node.d_value.until) {
991 string dom("empty");
992 if(!node.d_value.domain.empty())
993 dom = node.d_value.domain.toString();
994 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();
995 }
996 });
997
998 });
999
1000 g_lua.writeFunction("clearDynBlocks", []() {
1001 setLuaSideEffect();
1002 nmts_t nmg;
1003 g_dynblockNMG.setState(nmg);
1004 SuffixMatchTree<DynBlock> smt;
1005 g_dynblockSMT.setState(smt);
1006 });
1007
1008 g_lua.writeFunction("addDynBlocks",
1009 [](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) {
1010 if (m.empty()) {
1011 return;
1012 }
1013 setLuaSideEffect();
1014 auto slow = g_dynblockNMG.getCopy();
1015 struct timespec until, now;
1016 gettime(&now);
1017 until=now;
1018 int actualSeconds = seconds ? *seconds : 10;
1019 until.tv_sec += actualSeconds;
1020 for(const auto& capair : m) {
1021 unsigned int count = 0;
1022 auto got = slow.lookup(Netmask(capair.first));
1023 bool expired=false;
1024 if(got) {
1025 if(until < got->second.until) // had a longer policy
1026 continue;
1027 if(now < got->second.until) // only inherit count on fresh query we are extending
1028 count=got->second.blocks;
1029 else
1030 expired=true;
1031 }
1032 DynBlock db{msg,until,DNSName(),(action ? *action : DNSAction::Action::None)};
1033 db.blocks=count;
1034 if(!got || expired)
1035 warnlog("Inserting dynamic block for %s for %d seconds: %s", capair.first.toString(), actualSeconds, msg);
1036 slow.insert(Netmask(capair.first)).second=db;
1037 }
1038 g_dynblockNMG.setState(slow);
1039 });
1040
1041 g_lua.writeFunction("addDynBlockSMT",
1042 [](const vector<pair<unsigned int, string> >&names, const std::string& msg, boost::optional<int> seconds, boost::optional<DNSAction::Action> action) {
1043 if (names.empty()) {
1044 return;
1045 }
1046 setLuaSideEffect();
1047 auto slow = g_dynblockSMT.getCopy();
1048 struct timespec until, now;
1049 gettime(&now);
1050 until=now;
1051 int actualSeconds = seconds ? *seconds : 10;
1052 until.tv_sec += actualSeconds;
1053
1054 for(const auto& capair : names) {
1055 unsigned int count = 0;
1056 DNSName domain(capair.second);
1057 auto got = slow.lookup(domain);
1058 bool expired=false;
1059 if(got) {
1060 if(until < got->until) // had a longer policy
1061 continue;
1062 if(now < got->until) // only inherit count on fresh query we are extending
1063 count=got->blocks;
1064 else
1065 expired=true;
1066 }
1067
1068 DynBlock db{msg,until,domain,(action ? *action : DNSAction::Action::None)};
1069 db.blocks=count;
1070 if(!got || expired)
1071 warnlog("Inserting dynamic block for %s for %d seconds: %s", domain, actualSeconds, msg);
1072 slow.add(domain, db);
1073 }
1074 g_dynblockSMT.setState(slow);
1075 });
1076
1077 g_lua.writeFunction("setDynBlocksAction", [](DNSAction::Action action) {
1078 if (!g_configurationDone) {
1079 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) {
1080 g_dynBlockAction = action;
1081 }
1082 else {
1083 errlog("Dynamic blocks action can only be Drop, NoOp, NXDomain, Refused, Truncate or NoRecurse!");
1084 g_outputBuffer="Dynamic blocks action can only be Drop, NoOp, NXDomain, Refused, Truncate or NoRecurse!\n";
1085 }
1086 } else {
1087 g_outputBuffer="Dynamic blocks action cannot be altered at runtime!\n";
1088 }
1089 });
1090
1091 g_lua.writeFunction("addDNSCryptBind", [](const std::string& addr, const std::string& providerName, const std::string& certFile, const std::string keyFile, boost::optional<localbind_t> vars) {
1092 if (g_configurationDone) {
1093 g_outputBuffer="addDNSCryptBind cannot be used at runtime!\n";
1094 return;
1095 }
1096 #ifdef HAVE_DNSCRYPT
1097 bool reusePort = false;
1098 int tcpFastOpenQueueSize = 0;
1099 std::string interface;
1100 std::set<int> cpus;
1101
1102 parseLocalBindVars(vars, reusePort, tcpFastOpenQueueSize, interface, cpus);
1103
1104 try {
1105 auto ctx = std::make_shared<DNSCryptContext>(providerName, certFile, keyFile);
1106
1107 /* UDP */
1108 auto cs = std::unique_ptr<ClientState>(new ClientState(ComboAddress(addr, 443), false, reusePort, tcpFastOpenQueueSize, interface, cpus));
1109 cs->dnscryptCtx = ctx;
1110 g_dnsCryptLocals.push_back(ctx);
1111 g_frontends.push_back(std::move(cs));
1112
1113 /* TCP */
1114 cs = std::unique_ptr<ClientState>(new ClientState(ComboAddress(addr, 443), true, reusePort, tcpFastOpenQueueSize, interface, cpus));
1115 cs->dnscryptCtx = ctx;
1116 g_frontends.push_back(std::move(cs));
1117 }
1118 catch(std::exception& e) {
1119 errlog(e.what());
1120 g_outputBuffer="Error: "+string(e.what())+"\n";
1121 }
1122 #else
1123 g_outputBuffer="Error: DNSCrypt support is not enabled.\n";
1124 #endif
1125
1126 });
1127
1128 g_lua.writeFunction("showDNSCryptBinds", []() {
1129 setLuaNoSideEffect();
1130 #ifdef HAVE_DNSCRYPT
1131 ostringstream ret;
1132 boost::format fmt("%1$-3d %2% %|25t|%3$-20.20s");
1133 ret << (fmt % "#" % "Address" % "Provider Name") << endl;
1134 size_t idx = 0;
1135
1136 for (const auto& frontend : g_frontends) {
1137 const std::shared_ptr<DNSCryptContext> ctx = frontend->dnscryptCtx;
1138 ret<< (fmt % idx % frontend->local.toStringWithPort() % ctx->getProviderName()) << endl;
1139 idx++;
1140 }
1141
1142 g_outputBuffer=ret.str();
1143 #else
1144 g_outputBuffer="Error: DNSCrypt support is not enabled.\n";
1145 #endif
1146 });
1147
1148 g_lua.writeFunction("getDNSCryptBind", [](size_t idx) {
1149 setLuaNoSideEffect();
1150 #ifdef HAVE_DNSCRYPT
1151 std::shared_ptr<DNSCryptContext> ret = nullptr;
1152 if (idx < g_dnsCryptLocals.size()) {
1153 ret = g_dnsCryptLocals.at(idx);
1154 }
1155 return ret;
1156 #else
1157 g_outputBuffer="Error: DNSCrypt support is not enabled.\n";
1158 #endif
1159 });
1160
1161 g_lua.writeFunction("generateDNSCryptProviderKeys", [](const std::string& publicKeyFile, const std::string privateKeyFile) {
1162 setLuaNoSideEffect();
1163 #ifdef HAVE_DNSCRYPT
1164 unsigned char publicKey[DNSCRYPT_PROVIDER_PUBLIC_KEY_SIZE];
1165 unsigned char privateKey[DNSCRYPT_PROVIDER_PRIVATE_KEY_SIZE];
1166 sodium_mlock(privateKey, sizeof(privateKey));
1167
1168 try {
1169 DNSCryptContext::generateProviderKeys(publicKey, privateKey);
1170
1171 ofstream pubKStream(publicKeyFile);
1172 pubKStream.write((char*) publicKey, sizeof(publicKey));
1173 pubKStream.close();
1174
1175 ofstream privKStream(privateKeyFile);
1176 privKStream.write((char*) privateKey, sizeof(privateKey));
1177 privKStream.close();
1178
1179 g_outputBuffer="Provider fingerprint is: " + DNSCryptContext::getProviderFingerprint(publicKey) + "\n";
1180 }
1181 catch(std::exception& e) {
1182 errlog(e.what());
1183 g_outputBuffer="Error: "+string(e.what())+"\n";
1184 }
1185
1186 sodium_memzero(privateKey, sizeof(privateKey));
1187 sodium_munlock(privateKey, sizeof(privateKey));
1188 #else
1189 g_outputBuffer="Error: DNSCrypt support is not enabled.\n";
1190 #endif
1191 });
1192
1193 g_lua.writeFunction("printDNSCryptProviderFingerprint", [](const std::string& publicKeyFile) {
1194 setLuaNoSideEffect();
1195 #ifdef HAVE_DNSCRYPT
1196 unsigned char publicKey[DNSCRYPT_PROVIDER_PUBLIC_KEY_SIZE];
1197
1198 try {
1199 ifstream file(publicKeyFile);
1200 file.read((char *) &publicKey, sizeof(publicKey));
1201
1202 if (file.fail())
1203 throw std::runtime_error("Invalid dnscrypt provider public key file " + publicKeyFile);
1204
1205 file.close();
1206 g_outputBuffer="Provider fingerprint is: " + DNSCryptContext::getProviderFingerprint(publicKey) + "\n";
1207 }
1208 catch(std::exception& e) {
1209 errlog(e.what());
1210 g_outputBuffer="Error: "+string(e.what())+"\n";
1211 }
1212 #else
1213 g_outputBuffer="Error: DNSCrypt support is not enabled.\n";
1214 #endif
1215 });
1216
1217 #ifdef HAVE_DNSCRYPT
1218 g_lua.writeFunction("generateDNSCryptCertificate", [](const std::string& providerPrivateKeyFile, const std::string& certificateFile, const std::string privateKeyFile, uint32_t serial, time_t begin, time_t end, boost::optional<DNSCryptExchangeVersion> version) {
1219 setLuaNoSideEffect();
1220 DNSCryptPrivateKey privateKey;
1221 DNSCryptCert cert;
1222
1223 try {
1224 if (generateDNSCryptCertificate(providerPrivateKeyFile, serial, begin, end, version ? *version : DNSCryptExchangeVersion::VERSION1, cert, privateKey)) {
1225 privateKey.saveToFile(privateKeyFile);
1226 DNSCryptContext::saveCertFromFile(cert, certificateFile);
1227 }
1228 }
1229 catch(const std::exception& e) {
1230 errlog(e.what());
1231 g_outputBuffer="Error: "+string(e.what())+"\n";
1232 }
1233 });
1234 #endif
1235
1236 g_lua.writeFunction("showPools", []() {
1237 setLuaNoSideEffect();
1238 try {
1239 ostringstream ret;
1240 boost::format fmt("%1$-20.20s %|25t|%2$20s %|25t|%3$20s %|50t|%4%" );
1241 // 1 2 3 4
1242 ret << (fmt % "Name" % "Cache" % "ServerPolicy" % "Servers" ) << endl;
1243
1244 const auto localPools = g_pools.getCopy();
1245 for (const auto& entry : localPools) {
1246 const string& name = entry.first;
1247 const std::shared_ptr<ServerPool> pool = entry.second;
1248 string cache = pool->packetCache != nullptr ? pool->packetCache->toString() : "";
1249 string policy = g_policy.getLocal()->name;
1250 if (pool->policy != nullptr) {
1251 policy = pool->policy->name;
1252 }
1253 string servers;
1254
1255 for (const auto& server: pool->getServers()) {
1256 if (!servers.empty()) {
1257 servers += ", ";
1258 }
1259 if (!server.second->name.empty()) {
1260 servers += server.second->name;
1261 servers += " ";
1262 }
1263 servers += server.second->remote.toStringWithPort();
1264 }
1265
1266 ret << (fmt % name % cache % policy % servers) << endl;
1267 }
1268 g_outputBuffer=ret.str();
1269 }catch(std::exception& e) { g_outputBuffer=e.what(); throw; }
1270 });
1271
1272 g_lua.writeFunction("getPool", [client](const string& poolName) {
1273 if (client) {
1274 return std::make_shared<ServerPool>();
1275 }
1276 auto localPools = g_pools.getCopy();
1277 std::shared_ptr<ServerPool> pool = createPoolIfNotExists(localPools, poolName);
1278 g_pools.setState(localPools);
1279 return pool;
1280 });
1281
1282 g_lua.writeFunction("setVerboseHealthChecks", [](bool verbose) { g_verboseHealthChecks=verbose; });
1283 g_lua.writeFunction("setStaleCacheEntriesTTL", [](uint32_t ttl) { g_staleCacheEntriesTTL = ttl; });
1284
1285 g_lua.writeFunction("showBinds", []() {
1286 setLuaNoSideEffect();
1287 try {
1288 ostringstream ret;
1289 boost::format fmt("%1$-3d %2$-20.20s %|35t|%3$-20.20s %|57t|%4%" );
1290 // 1 2 3 4
1291 ret << (fmt % "#" % "Address" % "Protocol" % "Queries" ) << endl;
1292
1293 size_t counter = 0;
1294 for (const auto& front : g_frontends) {
1295 ret << (fmt % counter % front->local.toStringWithPort() % front->getType() % front->queries) << endl;
1296 counter++;
1297 }
1298 g_outputBuffer=ret.str();
1299 }catch(std::exception& e) { g_outputBuffer=e.what(); throw; }
1300 });
1301
1302 g_lua.writeFunction("getBind", [](size_t num) {
1303 setLuaNoSideEffect();
1304 ClientState* ret = nullptr;
1305 if(num < g_frontends.size()) {
1306 ret=g_frontends[num].get();
1307 }
1308 return ret;
1309 });
1310
1311 g_lua.writeFunction("help", [](boost::optional<std::string> command) {
1312 setLuaNoSideEffect();
1313 g_outputBuffer = "";
1314 for (const auto& keyword : g_consoleKeywords) {
1315 if (!command) {
1316 g_outputBuffer += keyword.toString() + "\n";
1317 }
1318 else if (keyword.name == command) {
1319 g_outputBuffer = keyword.toString() + "\n";
1320 return;
1321 }
1322 }
1323 if (command) {
1324 g_outputBuffer = "Nothing found for " + *command + "\n";
1325 }
1326 });
1327
1328 g_lua.writeFunction("showVersion", []() {
1329 setLuaNoSideEffect();
1330 g_outputBuffer = "dnsdist " + std::string(VERSION) + "\n";
1331 });
1332
1333 g_lua.writeFunction("showSecurityStatus", []() {
1334 setLuaNoSideEffect();
1335 g_outputBuffer = std::to_string(g_stats.securityStatus) + "\n";
1336 });
1337
1338 #ifdef HAVE_EBPF
1339 g_lua.writeFunction("setDefaultBPFFilter", [](std::shared_ptr<BPFFilter> bpf) {
1340 if (g_configurationDone) {
1341 g_outputBuffer="setDefaultBPFFilter() cannot be used at runtime!\n";
1342 return;
1343 }
1344 g_defaultBPFFilter = bpf;
1345 });
1346
1347 g_lua.writeFunction("registerDynBPFFilter", [](std::shared_ptr<DynBPFFilter> dbpf) {
1348 if (dbpf) {
1349 g_dynBPFFilters.push_back(dbpf);
1350 }
1351 });
1352
1353 g_lua.writeFunction("unregisterDynBPFFilter", [](std::shared_ptr<DynBPFFilter> dbpf) {
1354 if (dbpf) {
1355 for (auto it = g_dynBPFFilters.begin(); it != g_dynBPFFilters.end(); it++) {
1356 if (*it == dbpf) {
1357 g_dynBPFFilters.erase(it);
1358 break;
1359 }
1360 }
1361 }
1362 });
1363
1364 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) {
1365 setLuaSideEffect();
1366 struct timespec until, now;
1367 clock_gettime(CLOCK_MONOTONIC, &now);
1368 until=now;
1369 int actualSeconds = seconds ? *seconds : 10;
1370 until.tv_sec += actualSeconds;
1371 for(const auto& capair : m) {
1372 if (dynbpf->block(capair.first, until)) {
1373 warnlog("Inserting eBPF dynamic block for %s for %d seconds: %s", capair.first.toString(), actualSeconds, msg ? *msg : "");
1374 }
1375 }
1376 });
1377
1378 #endif /* HAVE_EBPF */
1379
1380 g_lua.writeFunction<std::unordered_map<string,uint64_t>()>("getStatisticsCounters", []() {
1381 setLuaNoSideEffect();
1382 std::unordered_map<string,uint64_t> res;
1383 for(const auto& entry : g_stats.entries) {
1384 if(const auto& val = boost::get<DNSDistStats::stat_t*>(&entry.second))
1385 res[entry.first] = (*val)->load();
1386 }
1387 return res;
1388 });
1389
1390 g_lua.writeFunction("includeDirectory", [](const std::string& dirname) {
1391 if (g_configurationDone) {
1392 errlog("includeDirectory() cannot be used at runtime!");
1393 g_outputBuffer="includeDirectory() cannot be used at runtime!\n";
1394 return;
1395 }
1396
1397 if (g_included) {
1398 errlog("includeDirectory() cannot be used recursively!");
1399 g_outputBuffer="includeDirectory() cannot be used recursively!\n";
1400 return;
1401 }
1402
1403 g_included = true;
1404 struct stat st;
1405 if (stat(dirname.c_str(), &st)) {
1406 errlog("The included directory %s does not exist!", dirname.c_str());
1407 g_outputBuffer="The included directory " + dirname + " does not exist!";
1408 return;
1409 }
1410
1411 if (!S_ISDIR(st.st_mode)) {
1412 errlog("The included directory %s is not a directory!", dirname.c_str());
1413 g_outputBuffer="The included directory " + dirname + " is not a directory!";
1414 return;
1415 }
1416
1417 DIR *dirp;
1418 struct dirent *ent;
1419 std::list<std::string> files;
1420 if (!(dirp = opendir(dirname.c_str()))) {
1421 errlog("Error opening the included directory %s!", dirname.c_str());
1422 g_outputBuffer="Error opening the included directory " + dirname + "!";
1423 return;
1424 }
1425
1426 while((ent = readdir(dirp)) != NULL) {
1427 if (ent->d_name[0] == '.') {
1428 continue;
1429 }
1430
1431 if (boost::ends_with(ent->d_name, ".conf")) {
1432 std::ostringstream namebuf;
1433 namebuf << dirname.c_str() << "/" << ent->d_name;
1434
1435 if (stat(namebuf.str().c_str(), &st) || !S_ISREG(st.st_mode)) {
1436 continue;
1437 }
1438
1439 files.push_back(namebuf.str());
1440 }
1441 }
1442
1443 closedir(dirp);
1444 files.sort();
1445
1446 for (auto file = files.begin(); file != files.end(); ++file) {
1447 std::ifstream ifs(*file);
1448 if (!ifs) {
1449 warnlog("Unable to read configuration from '%s'", *file);
1450 } else {
1451 vinfolog("Read configuration from '%s'", *file);
1452 }
1453
1454 g_lua.executeCode(ifs);
1455 }
1456
1457 g_included = false;
1458 });
1459
1460 g_lua.writeFunction("setAPIWritable", [](bool writable, boost::optional<std::string> apiConfigDir) {
1461 setLuaSideEffect();
1462 g_apiReadWrite = writable;
1463 if (apiConfigDir) {
1464 if (!(*apiConfigDir).empty()) {
1465 g_apiConfigDirectory = *apiConfigDir;
1466 }
1467 else {
1468 errlog("The API configuration directory value cannot be empty!");
1469 g_outputBuffer="The API configuration directory value cannot be empty!";
1470 }
1471 }
1472 });
1473
1474 g_lua.writeFunction("setServFailWhenNoServer", [](bool servfail) {
1475 setLuaSideEffect();
1476 g_servFailOnNoPolicy = servfail;
1477 });
1478
1479 g_lua.writeFunction("setRoundRobinFailOnNoServer", [](bool fail) {
1480 setLuaSideEffect();
1481 g_roundrobinFailOnNoServer = fail;
1482 });
1483
1484 g_lua.writeFunction("setRingBuffersSize", [](size_t capacity, boost::optional<size_t> numberOfShards) {
1485 setLuaSideEffect();
1486 if (g_configurationDone) {
1487 errlog("setRingBuffersSize() cannot be used at runtime!");
1488 g_outputBuffer="setRingBuffersSize() cannot be used at runtime!\n";
1489 return;
1490 }
1491 g_rings.setCapacity(capacity, numberOfShards ? *numberOfShards : 1);
1492 });
1493
1494 g_lua.writeFunction("setRingBuffersLockRetries", [](size_t retries) {
1495 setLuaSideEffect();
1496 g_rings.setNumberOfLockRetries(retries);
1497 });
1498
1499 g_lua.writeFunction("setWHashedPertubation", [](uint32_t pertub) {
1500 setLuaSideEffect();
1501 g_hashperturb = pertub;
1502 });
1503
1504 g_lua.writeFunction("setTCPUseSinglePipe", [](bool flag) {
1505 if (g_configurationDone) {
1506 g_outputBuffer="setTCPUseSinglePipe() cannot be used at runtime!\n";
1507 return;
1508 }
1509 setLuaSideEffect();
1510 g_useTCPSinglePipe = flag;
1511 });
1512
1513 g_lua.writeFunction("snmpAgent", [client](bool enableTraps, boost::optional<std::string> masterSocket) {
1514 if(client)
1515 return;
1516 #ifdef HAVE_NET_SNMP
1517 if (g_configurationDone) {
1518 errlog("snmpAgent() cannot be used at runtime!");
1519 g_outputBuffer="snmpAgent() cannot be used at runtime!\n";
1520 return;
1521 }
1522
1523 if (g_snmpEnabled) {
1524 errlog("snmpAgent() cannot be used twice!");
1525 g_outputBuffer="snmpAgent() cannot be used twice!\n";
1526 return;
1527 }
1528
1529 g_snmpEnabled = true;
1530 g_snmpTrapsEnabled = enableTraps;
1531 g_snmpAgent = new DNSDistSNMPAgent("dnsdist", masterSocket ? *masterSocket : std::string());
1532 #else
1533 errlog("NET SNMP support is required to use snmpAgent()");
1534 g_outputBuffer="NET SNMP support is required to use snmpAgent()\n";
1535 #endif /* HAVE_NET_SNMP */
1536 });
1537
1538 g_lua.writeFunction("sendCustomTrap", [](const std::string& str) {
1539 #ifdef HAVE_NET_SNMP
1540 if (g_snmpAgent && g_snmpTrapsEnabled) {
1541 g_snmpAgent->sendCustomTrap(str);
1542 }
1543 #endif /* HAVE_NET_SNMP */
1544 });
1545
1546 g_lua.writeFunction("setPoolServerPolicy", [](ServerPolicy policy, string pool) {
1547 setLuaSideEffect();
1548 auto localPools = g_pools.getCopy();
1549 setPoolPolicy(localPools, pool, std::make_shared<ServerPolicy>(policy));
1550 g_pools.setState(localPools);
1551 });
1552
1553 g_lua.writeFunction("setPoolServerPolicyLua", [](string name, policyfunc_t policy, string pool) {
1554 setLuaSideEffect();
1555 auto localPools = g_pools.getCopy();
1556 setPoolPolicy(localPools, pool, std::make_shared<ServerPolicy>(ServerPolicy{name, policy, true}));
1557 g_pools.setState(localPools);
1558 });
1559
1560 g_lua.writeFunction("showPoolServerPolicy", [](string pool) {
1561 setLuaSideEffect();
1562 auto localPools = g_pools.getCopy();
1563 auto poolObj = getPool(localPools, pool);
1564 if (poolObj->policy == nullptr) {
1565 g_outputBuffer=g_policy.getLocal()->name+"\n";
1566 } else {
1567 g_outputBuffer=poolObj->policy->name+"\n";
1568 }
1569 });
1570
1571 g_lua.writeFunction("setTCPDownstreamCleanupInterval", [](uint16_t interval) {
1572 setLuaSideEffect();
1573 g_downstreamTCPCleanupInterval = interval;
1574 });
1575
1576 g_lua.writeFunction("setConsoleConnectionsLogging", [](bool enabled) {
1577 g_logConsoleConnections = enabled;
1578 });
1579
1580 g_lua.writeFunction("setConsoleOutputMaxMsgSize", [](uint32_t size) {
1581 g_consoleOutputMsgMaxSize = size;
1582 });
1583
1584 g_lua.writeFunction("setUDPMultipleMessagesVectorSize", [](size_t vSize) {
1585 if (g_configurationDone) {
1586 errlog("setUDPMultipleMessagesVectorSize() cannot be used at runtime!");
1587 g_outputBuffer="setUDPMultipleMessagesVectorSize() cannot be used at runtime!\n";
1588 return;
1589 }
1590 #if defined(HAVE_RECVMMSG) && defined(HAVE_SENDMMSG) && defined(MSG_WAITFORONE)
1591 setLuaSideEffect();
1592 g_udpVectorSize = vSize;
1593 #else
1594 errlog("recvmmsg() support is not available!");
1595 g_outputBuffer="recvmmsg support is not available!\n";
1596 #endif
1597 });
1598
1599 g_lua.writeFunction("setAddEDNSToSelfGeneratedResponses", [](bool add) {
1600 g_addEDNSToSelfGeneratedResponses = add;
1601 });
1602
1603 g_lua.writeFunction("setPayloadSizeOnSelfGeneratedAnswers", [](uint16_t payloadSize) {
1604 if (payloadSize < 512) {
1605 warnlog("setPayloadSizeOnSelfGeneratedAnswers() is set too low, using 512 instead!");
1606 g_outputBuffer="setPayloadSizeOnSelfGeneratedAnswers() is set too low, using 512 instead!";
1607 payloadSize = 512;
1608 }
1609 if (payloadSize > s_udpIncomingBufferSize) {
1610 warnlog("setPayloadSizeOnSelfGeneratedAnswers() is set too high, capping to %d instead!", s_udpIncomingBufferSize);
1611 g_outputBuffer="setPayloadSizeOnSelfGeneratedAnswers() is set too high, capping to " + std::to_string(s_udpIncomingBufferSize) + " instead";
1612 payloadSize = s_udpIncomingBufferSize;
1613 }
1614 g_PayloadSizeSelfGenAnswers = payloadSize;
1615 });
1616
1617 g_lua.writeFunction("setSecurityPollSuffix", [](const std::string& suffix) {
1618 if (g_configurationDone) {
1619 g_outputBuffer="setSecurityPollSuffix() cannot be used at runtime!\n";
1620 return;
1621 }
1622
1623 g_secPollSuffix = suffix;
1624 });
1625
1626 g_lua.writeFunction("setSecurityPollInterval", [](time_t newInterval) {
1627 if (newInterval <= 0) {
1628 warnlog("setSecurityPollInterval() should be > 0, skipping");
1629 g_outputBuffer="setSecurityPollInterval() should be > 0, skipping";
1630 }
1631
1632 g_secPollInterval = newInterval;
1633 });
1634
1635 g_lua.writeFunction("setSyslogFacility", [](int facility) {
1636 setLuaSideEffect();
1637 if (g_configurationDone) {
1638 g_outputBuffer="setSyslogFacility cannot be used at runtime!\n";
1639 return;
1640 }
1641 setSyslogFacility(facility);
1642 });
1643
1644 g_lua.writeFunction("addDOHLocal", [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<boost::variant<std::string, vector<pair<int, std::string> > > > urls, boost::optional<localbind_t> vars) {
1645 #ifdef HAVE_DNS_OVER_HTTPS
1646 if (client) {
1647 return;
1648 }
1649 setLuaSideEffect();
1650 if (g_configurationDone) {
1651 g_outputBuffer="addDOHLocal cannot be used at runtime!\n";
1652 return;
1653 }
1654 auto frontend = std::make_shared<DOHFrontend>();
1655
1656 if (!loadTLSCertificateAndKeys("addDOHLocal", frontend->d_certKeyPairs, certFiles, keyFiles)) {
1657 return;
1658 }
1659
1660 frontend->d_local = ComboAddress(addr, 443);
1661 if (urls) {
1662 if (urls->type() == typeid(std::string)) {
1663 frontend->d_urls.push_back(boost::get<std::string>(*urls));
1664 }
1665 else if (urls->type() == typeid(std::vector<std::pair<int,std::string>>)) {
1666 auto urlsVect = boost::get<std::vector<std::pair<int,std::string>>>(*urls);
1667 for(const auto& p : urlsVect) {
1668 frontend->d_urls.push_back(p.second);
1669 }
1670 }
1671 }
1672 else {
1673 frontend->d_urls = {"/"};
1674 }
1675
1676 bool reusePort = false;
1677 int tcpFastOpenQueueSize = 0;
1678 std::string interface;
1679 std::set<int> cpus;
1680
1681 if(vars) {
1682 parseLocalBindVars(vars, reusePort, tcpFastOpenQueueSize, interface, cpus);
1683
1684 if (vars->count("idleTimeout")) {
1685 frontend->d_idleTimeout = boost::get<int>((*vars)["idleTimeout"]);
1686 }
1687 if (vars->count("ciphers")) {
1688 frontend->d_ciphers = boost::get<const string>((*vars)["ciphers"]);
1689 }
1690 if (vars->count("ciphersTLS13")) {
1691 frontend->d_ciphers13 = boost::get<const string>((*vars)["ciphersTLS13"]);
1692 }
1693 if (vars->count("serverTokens")) {
1694 frontend->d_serverTokens = boost::get<const string>((*vars)["serverTokens"]);
1695 }
1696 }
1697 g_dohlocals.push_back(frontend);
1698 auto cs = std::unique_ptr<ClientState>(new ClientState(frontend->d_local, true, reusePort, tcpFastOpenQueueSize, interface, cpus));
1699 cs->dohFrontend = frontend;
1700 g_frontends.push_back(std::move(cs));
1701 #else
1702 throw std::runtime_error("addDOHLocal() called but DNS over HTTPS support is not present!");
1703 #endif
1704 });
1705
1706 g_lua.writeFunction("showDOHFrontends", []() {
1707 #ifdef HAVE_DNS_OVER_HTTPS
1708 setLuaNoSideEffect();
1709 try {
1710 ostringstream ret;
1711 boost::format fmt("%-3d %-20.20s %-15d %-15d %-15d %-15d %-15d %-15d %-15d %-15d %-15d %-15d %-15d %-15d %-15d");
1712 ret << (fmt % "#" % "Address" % "HTTP" % "HTTP/1" % "HTTP/2" % "TLS 1.0" % "TLS 1.1" % "TLS 1.2" % "TLS 1.3" % "TLS other" % "GET" % "POST" % "Bad" % "Errors" % "Valid") << endl;
1713 size_t counter = 0;
1714 for (const auto& ctx : g_dohlocals) {
1715 ret << (fmt % counter % ctx->d_local.toStringWithPort() % ctx->d_httpconnects % ctx->d_http1queries % ctx->d_http2queries % ctx->d_tls10queries % ctx->d_tls11queries % ctx->d_tls12queries % ctx->d_tls13queries % ctx->d_tlsUnknownqueries % ctx->d_getqueries % ctx->d_postqueries % ctx->d_badrequests % ctx->d_errorresponses % ctx->d_validresponses) << endl;
1716 counter++;
1717 }
1718 g_outputBuffer = ret.str();
1719 }
1720 catch(const std::exception& e) {
1721 g_outputBuffer = e.what();
1722 throw;
1723 }
1724 #else
1725 g_outputBuffer="DNS over HTTPS support is not present!\n";
1726 #endif
1727 });
1728
1729 g_lua.writeFunction("getDOHFrontend", [](size_t index) {
1730 std::shared_ptr<DOHFrontend> result = nullptr;
1731 #ifdef HAVE_DNS_OVER_HTTPS
1732 setLuaNoSideEffect();
1733 try {
1734 if (index < g_dohlocals.size()) {
1735 result = g_dohlocals.at(index);
1736 }
1737 else {
1738 errlog("Error: trying to get DOH frontend with index %zu but we only have %zu frontend(s)\n", index, g_dohlocals.size());
1739 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";
1740 }
1741 }
1742 catch(const std::exception& e) {
1743 g_outputBuffer="Error while trying to get DOH frontend with index " + std::to_string(index) + ": "+string(e.what())+"\n";
1744 errlog("Error while trying to get DOH frontend with index %zu: %s\n", index, string(e.what()));
1745 }
1746 #else
1747 g_outputBuffer="DNS over HTTPS support is not present!\n";
1748 #endif
1749 return result;
1750 });
1751
1752 g_lua.registerFunction<void(std::shared_ptr<DOHFrontend>::*)()>("reloadCertificates", [](std::shared_ptr<DOHFrontend> frontend) {
1753 if (frontend != nullptr) {
1754 frontend->reloadCertificates();
1755 }
1756 });
1757
1758 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) {
1759 #ifdef HAVE_DNS_OVER_TLS
1760 if (client)
1761 return;
1762 setLuaSideEffect();
1763 if (g_configurationDone) {
1764 g_outputBuffer="addTLSLocal cannot be used at runtime!\n";
1765 return;
1766 }
1767 shared_ptr<TLSFrontend> frontend = std::make_shared<TLSFrontend>();
1768
1769 if (!loadTLSCertificateAndKeys("addTLSLocal", frontend->d_certKeyPairs, certFiles, keyFiles)) {
1770 return;
1771 }
1772
1773 bool reusePort = false;
1774 int tcpFastOpenQueueSize = 0;
1775 std::string interface;
1776 std::set<int> cpus;
1777
1778 if (vars) {
1779 parseLocalBindVars(vars, reusePort, tcpFastOpenQueueSize, interface, cpus);
1780
1781 if (vars->count("provider")) {
1782 frontend->d_provider = boost::get<const string>((*vars)["provider"]);
1783 }
1784
1785 if (vars->count("ciphers")) {
1786 frontend->d_ciphers = boost::get<const string>((*vars)["ciphers"]);
1787 }
1788
1789 if (vars->count("ciphersTLS13")) {
1790 frontend->d_ciphers13 = boost::get<const string>((*vars)["ciphersTLS13"]);
1791 }
1792
1793 if (vars->count("ticketKeyFile")) {
1794 frontend->d_ticketKeyFile = boost::get<const string>((*vars)["ticketKeyFile"]);
1795 }
1796
1797 if (vars->count("ticketsKeysRotationDelay")) {
1798 frontend->d_ticketsKeyRotationDelay = boost::get<int>((*vars)["ticketsKeysRotationDelay"]);
1799 }
1800
1801 if (vars->count("numberOfTicketsKeys")) {
1802 frontend->d_numberOfTicketsKeys = boost::get<int>((*vars)["numberOfTicketsKeys"]);
1803 }
1804
1805 if (vars->count("sessionTickets")) {
1806 frontend->d_enableTickets = boost::get<bool>((*vars)["sessionTickets"]);
1807 }
1808
1809 if (vars->count("numberOfStoredSessions")) {
1810 auto value = boost::get<int>((*vars)["numberOfStoredSessions"]);
1811 if (value < 0) {
1812 errlog("Invalid value '%d' for addTLSLocal() parameter 'numberOfStoredSessions', should be >= 0, dismissing", value);
1813 g_outputBuffer="Invalid value '" + std::to_string(value) + "' for addTLSLocal() parameter 'numberOfStoredSessions', should be >= 0, dimissing";
1814 return;
1815 }
1816 frontend->d_maxStoredSessions = value;
1817 }
1818 }
1819
1820 try {
1821 frontend->d_addr = ComboAddress(addr, 853);
1822 vinfolog("Loading TLS provider %s", frontend->d_provider);
1823 // only works pre-startup, so no sync necessary
1824 auto cs = std::unique_ptr<ClientState>(new ClientState(frontend->d_addr, true, reusePort, tcpFastOpenQueueSize, interface, cpus));
1825 cs->tlsFrontend = frontend;
1826 g_tlslocals.push_back(cs->tlsFrontend);
1827 g_frontends.push_back(std::move(cs));
1828 }
1829 catch(const std::exception& e) {
1830 g_outputBuffer="Error: "+string(e.what())+"\n";
1831 }
1832 #else
1833 throw std::runtime_error("addTLSLocal() called but DNS over TLS support is not present!");
1834 #endif
1835 });
1836
1837 g_lua.writeFunction("showTLSContexts", []() {
1838 #ifdef HAVE_DNS_OVER_TLS
1839 setLuaNoSideEffect();
1840 try {
1841 ostringstream ret;
1842 boost::format fmt("%1$-3d %2$-20.20s %|25t|%3$-14d %|40t|%4$-14d %|54t|%5$-21.21s");
1843 // 1 2 3 4 5
1844 ret << (fmt % "#" % "Address" % "# ticket keys" % "Rotation delay" % "Next rotation" ) << endl;
1845 size_t counter = 0;
1846 for (const auto& ctx : g_tlslocals) {
1847 ret << (fmt % counter % ctx->d_addr.toStringWithPort() % ctx->getTicketsKeysCount() % ctx->getTicketsKeyRotationDelay() % ctx->getNextTicketsKeyRotation()) << endl;
1848 counter++;
1849 }
1850 g_outputBuffer = ret.str();
1851 }
1852 catch(const std::exception& e) {
1853 g_outputBuffer = e.what();
1854 throw;
1855 }
1856 #else
1857 g_outputBuffer="DNS over TLS support is not present!\n";
1858 #endif
1859 });
1860
1861 g_lua.writeFunction("getTLSContext", [](size_t index) {
1862 std::shared_ptr<TLSCtx> result = nullptr;
1863 #ifdef HAVE_DNS_OVER_TLS
1864 setLuaNoSideEffect();
1865 try {
1866 if (index < g_tlslocals.size()) {
1867 result = g_tlslocals.at(index)->getContext();
1868 }
1869 else {
1870 errlog("Error: trying to get TLS context with index %zu but we only have %zu context(s)\n", index, g_tlslocals.size());
1871 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";
1872 }
1873 }
1874 catch(const std::exception& e) {
1875 g_outputBuffer="Error while trying to get TLS context with index " + std::to_string(index) + ": "+string(e.what())+"\n";
1876 errlog("Error while trying to get TLS context with index %zu: %s\n", index, string(e.what()));
1877 }
1878 #else
1879 g_outputBuffer="DNS over TLS support is not present!\n";
1880 #endif
1881 return result;
1882 });
1883
1884 g_lua.writeFunction("getTLSFrontend", [](size_t index) {
1885 std::shared_ptr<TLSFrontend> result = nullptr;
1886 #ifdef HAVE_DNS_OVER_TLS
1887 setLuaNoSideEffect();
1888 try {
1889 if (index < g_tlslocals.size()) {
1890 result = g_tlslocals.at(index);
1891 }
1892 else {
1893 errlog("Error: trying to get TLS frontend with index %zu but we only have %zu frontends\n", index, g_tlslocals.size());
1894 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";
1895 }
1896 }
1897 catch(const std::exception& e) {
1898 g_outputBuffer="Error while trying to get TLS frontend with index " + std::to_string(index) + ": "+string(e.what())+"\n";
1899 errlog("Error while trying to get TLS frontend with index %zu: %s\n", index, string(e.what()));
1900 }
1901 #else
1902 g_outputBuffer="DNS over TLS support is not present!\n";
1903 #endif
1904 return result;
1905 });
1906
1907 g_lua.registerFunction<void(std::shared_ptr<TLSCtx>::*)()>("rotateTicketsKey", [](std::shared_ptr<TLSCtx> ctx) {
1908 if (ctx != nullptr) {
1909 ctx->rotateTicketsKey(time(nullptr));
1910 }
1911 });
1912
1913 g_lua.registerFunction<void(std::shared_ptr<TLSCtx>::*)(const std::string&)>("loadTicketsKeys", [](std::shared_ptr<TLSCtx> ctx, const std::string& file) {
1914 if (ctx != nullptr) {
1915 ctx->loadTicketsKeys(file);
1916 }
1917 });
1918
1919 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) {
1920 #ifdef HAVE_DNS_OVER_TLS
1921 if (loadTLSCertificateAndKeys("loadNewCertificatesAndKeys", frontend->d_certKeyPairs, certFiles, keyFiles)) {
1922 frontend->setupTLS();
1923 }
1924 #endif
1925 });
1926
1927 g_lua.writeFunction("reloadAllCertificates", []() {
1928 for (auto& frontend : g_frontends) {
1929 if (!frontend) {
1930 continue;
1931 }
1932 try {
1933 #ifdef HAVE_DNSCRYPT
1934 if (frontend->dnscryptCtx) {
1935 frontend->dnscryptCtx->reloadCertificate();
1936 }
1937 #endif /* HAVE_DNSCRYPT */
1938 #ifdef HAVE_DNS_OVER_TLS
1939 if (frontend->tlsFrontend) {
1940 frontend->tlsFrontend->setupTLS();
1941 }
1942 #endif /* HAVE_DNS_OVER_TLS */
1943 #ifdef HAVE_DNS_OVER_HTTPS
1944 if (frontend->dohFrontend) {
1945 frontend->dohFrontend->reloadCertificates();
1946 }
1947 #endif /* HAVE_DNS_OVER_HTTPS */
1948 }
1949 catch(const std::exception& e) {
1950 errlog("Error reloading certificates for frontend %s: %s", frontend->local.toStringWithPort(), e.what());
1951 }
1952 }
1953 });
1954
1955 g_lua.writeFunction("setAllowEmptyResponse", [](bool allow) { g_allowEmptyResponse=allow; });
1956 }
1957
1958 vector<std::function<void(void)>> setupLua(bool client, const std::string& config)
1959 {
1960 g_launchWork= new vector<std::function<void(void)>>();
1961
1962 setupLuaActions();
1963 setupLuaConfig(client);
1964 setupLuaBindings(client);
1965 setupLuaBindingsDNSQuestion();
1966 setupLuaInspection();
1967 setupLuaRules();
1968 setupLuaVars();
1969
1970 std::ifstream ifs(config);
1971 if(!ifs)
1972 warnlog("Unable to read configuration from '%s'", config);
1973 else
1974 vinfolog("Read configuration from '%s'", config);
1975
1976 g_lua.executeCode(ifs);
1977
1978 auto ret = *g_launchWork;
1979 delete g_launchWork;
1980 g_launchWork = nullptr;
1981 return ret;
1982 }