]> git.ipfire.org Git - thirdparty/pdns.git/blame - pdns/dnsdist-console.cc
Merge pull request #6705 from ahupowerdns/recursor-tracelog-improv
[thirdparty/pdns.git] / pdns / dnsdist-console.cc
CommitLineData
12471842
PL
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 */
b5521206
RG
22
23#include <fstream>
24#include <pwd.h>
25#include <thread>
424bdfb1 26
4d39d7f3 27#if defined (__OpenBSD__) || defined(__NetBSD__)
424bdfb1
PD
28#include <readline/readline.h>
29#include <readline/history.h>
30#else
9c8aa826 31#include <editline/readline.h>
424bdfb1
PD
32#endif
33
7e7a5b71 34#include "ext/json11/json11.hpp"
ffb07158 35
b5521206
RG
36#include "dolog.hh"
37#include "dnsdist.hh"
38#include "dnsdist-console.hh"
39#include "sodcrypto.hh"
40
41GlobalStateHolder<NetmaskGroup> g_consoleACL;
f758857a 42vector<pair<struct timeval, string> > g_confDelta;
b5521206 43std::string g_consoleKey;
506bb661 44bool g_logConsoleConnections{true};
f758857a 45
46// MUST BE CALLED UNDER A LOCK - right now the LuaLock
b5521206 47static void feedConfigDelta(const std::string& line)
f758857a 48{
171fca9a 49 if(line.empty())
50 return;
f758857a 51 struct timeval now;
52 gettimeofday(&now, 0);
53 g_confDelta.push_back({now,line});
54}
55
b5521206 56static string historyFile(const bool &ignoreHOME = false)
93644039
PL
57{
58 string ret;
59
60 struct passwd pwd;
61 struct passwd *result;
62 char buf[16384];
63 getpwuid_r(geteuid(), &pwd, buf, sizeof(buf), &result);
64
65 const char *homedir = getenv("HOME");
66 if (result)
67 ret = string(pwd.pw_dir);
68 if (homedir && !ignoreHOME) // $HOME overrides what the OS tells us
69 ret = string(homedir);
70 if (ret.empty())
71 ret = "."; // CWD if nothing works..
72 ret.append("/.dnsdist_history");
73 return ret;
74}
75
ffb07158 76void doClient(ComboAddress server, const std::string& command)
77{
9c186303 78 if(g_verbose)
79 cout<<"Connecting to "<<server.toStringWithPort()<<endl;
b5521206 80
ffb07158 81 int fd=socket(server.sin4.sin_family, SOCK_STREAM, 0);
6a62c0e3
RG
82 if (fd < 0) {
83 cerr<<"Unable to connect to "<<server.toStringWithPort()<<endl;
84 return;
85 }
ffb07158 86 SConnect(fd, server);
9c186303 87 setTCPNoDelay(fd);
333ea16e 88 SodiumNonce theirs, ours, readingNonce, writingNonce;
ffb07158 89 ours.init();
90
91 writen2(fd, (const char*)ours.value, sizeof(ours.value));
92 readn2(fd, (char*)theirs.value, sizeof(theirs.value));
333ea16e
RG
93 readingNonce.merge(ours, theirs);
94 writingNonce.merge(theirs, ours);
ffb07158 95
96 if(!command.empty()) {
b5521206 97 string msg=sodEncryptSym(command, g_consoleKey, writingNonce);
a683e8bd 98 putMsgLen32(fd, (uint32_t) msg.length());
ffb07158 99 if(!msg.empty())
100 writen2(fd, msg);
101 uint32_t len;
e4ef64be
RG
102 if(getMsgLen32(fd, &len)) {
103 if (len > 0) {
104 boost::scoped_array<char> resp(new char[len]);
105 readn2(fd, resp.get(), len);
106 msg.assign(resp.get(), len);
b5521206 107 msg=sodDecryptSym(msg, g_consoleKey, readingNonce);
7e7a5b71 108 cout<<msg;
a43f9501 109 cout.flush();
e4ef64be
RG
110 }
111 }
112 else {
113 cout << "Connection closed by the server." << endl;
114 }
6a62c0e3 115 close(fd);
ffb07158 116 return;
117 }
118
93644039 119 string histfile = historyFile();
ffb07158 120 set<string> dupper;
121 {
93644039 122 ifstream history(histfile);
ffb07158 123 string line;
124 while(getline(history, line))
125 add_history(line.c_str());
126 }
93644039 127 ofstream history(histfile, std::ios_base::app);
ffb07158 128 string lastline;
129 for(;;) {
130 char* sline = readline("> ");
131 rl_bind_key('\t',rl_complete);
132 if(!sline)
133 break;
134
135 string line(sline);
136 if(!line.empty() && line != lastline) {
137 add_history(sline);
138 history << sline <<endl;
139 history.flush();
140 }
141 lastline=line;
142 free(sline);
143
144 if(line=="quit")
145 break;
f5c1ce10 146 if(line=="help" || line=="?")
5fbd6dda 147 line="help()";
ffb07158 148
0877da98
RG
149 /* no need to send an empty line to the server */
150 if(line.empty())
151 continue;
152
b5521206 153 string msg=sodEncryptSym(line, g_consoleKey, writingNonce);
a683e8bd 154 putMsgLen32(fd, (uint32_t) msg.length());
ffb07158 155 writen2(fd, msg);
156 uint32_t len;
ff16861c 157 if(!getMsgLen32(fd, &len)) {
ffb07158 158 cout << "Connection closed by the server." << endl;
159 break;
160 }
161
ff16861c
RG
162 if (len > 0) {
163 boost::scoped_array<char> resp(new char[len]);
164 readn2(fd, resp.get(), len);
165 msg.assign(resp.get(), len);
b5521206 166 msg=sodDecryptSym(msg, g_consoleKey, readingNonce);
7e7a5b71 167 cout<<msg;
168 cout.flush();
ff16861c
RG
169 }
170 else {
171 cout<<endl;
172 }
ffb07158 173 }
6c1ca990 174 close(fd);
ffb07158 175}
176
177void doConsole()
178{
93644039 179 string histfile = historyFile(true);
ffb07158 180 set<string> dupper;
181 {
93644039 182 ifstream history(histfile);
ffb07158 183 string line;
184 while(getline(history, line))
185 add_history(line.c_str());
186 }
93644039 187 ofstream history(histfile, std::ios_base::app);
ffb07158 188 string lastline;
189 for(;;) {
190 char* sline = readline("> ");
191 rl_bind_key('\t',rl_complete);
192 if(!sline)
193 break;
194
195 string line(sline);
196 if(!line.empty() && line != lastline) {
197 add_history(sline);
198 history << sline <<endl;
199 history.flush();
200 }
201 lastline=line;
202 free(sline);
203
204 if(line=="quit")
205 break;
f5c1ce10 206 if(line=="help" || line=="?")
5fbd6dda 207 line="help()";
ffb07158 208
209 string response;
210 try {
7e7a5b71 211 bool withReturn=true;
212 retry:;
213 try {
214 std::lock_guard<std::mutex> lock(g_luamutex);
215 g_outputBuffer.clear();
216 resetLuaSideEffect();
217 auto ret=g_lua.executeCode<
218 boost::optional<
219 boost::variant<
220 string,
221 shared_ptr<DownstreamState>,
630e3e0a 222 ClientState*,
7e7a5b71 223 std::unordered_map<string, double>
224 >
225 >
226 >(withReturn ? ("return "+line) : line);
7e7a5b71 227 if(ret) {
af619119 228 if (const auto dsValue = boost::get<shared_ptr<DownstreamState>>(&*ret)) {
6d54c50c
CH
229 if (*dsValue) {
230 cout<<(*dsValue)->getName()<<endl;
231 }
7e7a5b71 232 }
630e3e0a 233 else if (const auto csValue = boost::get<ClientState*>(&*ret)) {
6d54c50c
CH
234 if (*csValue) {
235 cout<<(*csValue)->local.toStringWithPort()<<endl;
236 }
630e3e0a 237 }
7e7a5b71 238 else if (const auto strValue = boost::get<string>(&*ret)) {
239 cout<<*strValue<<endl;
240 }
241 else if(const auto um = boost::get<std::unordered_map<string, double> >(&*ret)) {
242 using namespace json11;
243 Json::object o;
244 for(const auto& v : *um)
245 o[v.first]=v.second;
246 Json out = o;
247 cout<<out.dump()<<endl;
248 }
249 }
250 else
251 cout << g_outputBuffer;
252 if(!getLuaNoSideEffect())
253 feedConfigDelta(line);
ffb07158 254 }
7e7a5b71 255 catch(const LuaContext::SyntaxErrorException&) {
256 if(withReturn) {
257 withReturn=false;
258 goto retry;
259 }
260 throw;
261 }
262 }
263 catch(const LuaContext::WrongTypeException& e) {
e2323545 264 std::cerr<<"Command returned an object we can't print: "<<std::string(e.what())<<std::endl;
7e7a5b71 265 // tried to return something we don't understand
ffb07158 266 }
267 catch(const LuaContext::ExecutionErrorException& e) {
98bac6bc 268 if(!strcmp(e.what(),"invalid key to 'next'"))
269 std::cerr<<"Error parsing parameters, did you forget parameter name?";
270 else
271 std::cerr << e.what();
ffb07158 272 try {
273 std::rethrow_if_nested(e);
98bac6bc 274
d96df9ec 275 std::cerr << std::endl;
af619119
RG
276 } catch(const std::exception& ne) {
277 // ne is the exception that was thrown from inside the lambda
278 std::cerr << ": " << ne.what() << std::endl;
ffb07158 279 }
af619119
RG
280 catch(const PDNSException& ne) {
281 // ne is the exception that was thrown from inside the lambda
282 std::cerr << ": " << ne.reason << std::endl;
ffb07158 283 }
284 }
285 catch(const std::exception& e) {
ffb07158 286 std::cerr << e.what() << std::endl;
287 }
288 }
289}
290/**** CARGO CULT CODE AHEAD ****/
ca4252e0
RG
291const std::vector<ConsoleKeyword> g_consoleKeywords{
292 /* keyword, function, parameters, description */
293 { "addACL", true, "netmask", "add to the ACL set who can use this server" },
4d5959e6 294 { "addAction", true, "DNS rule, DNS action [, {uuid=\"UUID\"}]", "add a rule" },
b5521206 295 { "addConsoleACL", true, "netmask", "add a netmask to the console ACL" },
4bc167b8 296 { "addDNSCryptBind", true, "\"127.0.0.1:8443\", \"provider name\", \"/path/to/resolver.cert\", \"/path/to/resolver.key\", {reusePort=false, tcpFastOpenSize=0, interface=\"\", cpus={}}", "listen to incoming DNSCrypt queries on 127.0.0.1 port 8443, with a provider name of `provider name`, using a resolver certificate and associated key stored respectively in the `resolver.cert` and `resolver.key` files. The fifth optional parameter is a table of parameters" },
7b925432 297 { "addDynBlocks", true, "addresses, message[, seconds[, action]]", "block the set of addresses with message `msg`, for `seconds` seconds (10 by default), applying `action` (default to the one set with `setDynBlocksAction()`)" },
4bc167b8 298 { "addLocal", true, "addr [, {doTCP=true, reusePort=false, tcpFastOpenSize=0, interface=\"\", cpus={}}]", "add `addr` to the list of addresses we listen on" },
e33e53fc
CH
299 { "addLuaAction", true, "x, func [, {uuid=\"UUID\"}]", "where 'x' is all the combinations from `addAction`, and func is a function with the parameter `dq`, which returns an action to be taken on this packet. Good for rare packets but where you want to do a lot of processing" },
300 { "addLuaResponseAction", true, "x, func [, {uuid=\"UUID\"}]", "where 'x' is all the combinations from `addAction`, and func is a function with the parameter `dr`, which returns an action to be taken on this response packet. Good for rare packets but where you want to do a lot of processing" },
4d5959e6
RG
301 { "addCacheHitResponseAction", true, "DNS rule, DNS response action [, {uuid=\"UUID\"}]", "add a cache hit response rule" },
302 { "addResponseAction", true, "DNS rule, DNS response action [, {uuid=\"UUID\"}]", "add a response rule" },
2d4783a8 303 { "addSelfAnsweredResponseAction", true, "DNS rule, DNS response action [, {uuid=\"UUID\"}]", "add a self-answered response rule" },
fa974ada 304 { "addTLSLocal", true, "addr, certFile(s), keyFile(s) [,params]", "listen to incoming DNS over TLS queries on the specified address using the specified certificate (or list of) and key (or list of). The last parameter is a table" },
ca4252e0 305 { "AllowAction", true, "", "let these packets go through" },
788c3243 306 { "AllowResponseAction", true, "", "let these packets go through" },
ca4252e0
RG
307 { "AllRule", true, "", "matches all traffic" },
308 { "AndRule", true, "list of DNS rules", "matches if all sub-rules matches" },
309 { "benchRule", true, "DNS Rule [, iterations [, suffix]]", "bench the specified DNS rule" },
310 { "carbonServer", true, "serverIP, [ourname], [interval]", "report statistics to serverIP using our hostname, or 'ourname' if provided, every 'interval' seconds" },
311 { "controlSocket", true, "addr", "open a control socket on this address / connect to this address in client mode" },
312 { "clearDynBlocks", true, "", "clear all dynamic blocks" },
786e4d8c 313 { "clearQueryCounters", true, "", "clears the query counter buffer" },
ca4252e0
RG
314 { "clearRules", true, "", "remove all current rules" },
315 { "DelayAction", true, "milliseconds", "delay the response by the specified amount of milliseconds (UDP-only)" },
788c3243 316 { "DelayResponseAction", true, "milliseconds", "delay the response by the specified amount of milliseconds (UDP-only)" },
ca4252e0
RG
317 { "delta", true, "", "shows all commands entered that changed the configuration" },
318 { "DisableValidationAction", true, "", "set the CD bit in the question, let it go through" },
82a91ddf
CH
319 { "DnstapLogAction", true, "identity, FrameStreamLogger [, alterFunction]", "send the contents of this query to a FrameStreamLogger or RemoteLogger as dnstap. `alterFunction` is a callback, receiving a DNSQuestion and a DnstapMessage, that can be used to modify the dnstap message" },
320 { "DnstapLogResponseAction", true, "identity, FrameStreamLogger [, alterFunction]", "send the contents of this response to a remote or FrameStreamLogger or RemoteLogger as dnstap. `alterFunction` is a callback, receiving a DNSResponse and a DnstapMessage, that can be used to modify the dnstap message" },
ca4252e0 321 { "DropAction", true, "", "drop these packets" },
788c3243 322 { "DropResponseAction", true, "", "drop these packets" },
ca4252e0
RG
323 { "dumpStats", true, "", "print all statistics we gather" },
324 { "exceedNXDOMAINs", true, "rate, seconds", "get set of addresses that exceed `rate` NXDOMAIN/s over `seconds` seconds" },
dc2fd93a 325 { "dynBlockRulesGroup", true, "", "return a new DynBlockRulesGroup object" },
ca4252e0
RG
326 { "exceedQRate", true, "rate, seconds", "get set of address that exceed `rate` queries/s over `seconds` seconds" },
327 { "exceedQTypeRate", true, "type, rate, seconds", "get set of address that exceed `rate` queries/s for queries of type `type` over `seconds` seconds" },
55fcc3d7 328 { "exceedRespByterate", true, "rate, seconds", "get set of addresses that exceeded `rate` bytes/s answers over `seconds` seconds" },
82e55fbd 329 { "exceedServFails", true, "rate, seconds", "get set of addresses that exceed `rate` servfails/s over `seconds` seconds" },
ca4252e0
RG
330 { "firstAvailable", false, "", "picks the server with the lowest `order` that has not exceeded its QPS limit" },
331 { "fixupCase", true, "bool", "if set (default to no), rewrite the first qname of the question part of the answer to match the one from the query. It is only useful when you have a downstream server that messes up the case of the question qname in the answer" },
332 { "generateDNSCryptCertificate", true, "\"/path/to/providerPrivate.key\", \"/path/to/resolver.cert\", \"/path/to/resolver.key\", serial, validFrom, validUntil", "generate a new resolver private key and related certificate, valid from the `validFrom` timestamp until the `validUntil` one, signed with the provider private key" },
79500db5 333 { "generateDNSCryptProviderKeys", true, "\"/path/to/providerPublic.key\", \"/path/to/providerPrivate.key\"", "generate a new provider keypair" },
ca55cc52 334 { "getBind", true, "n", "returns the listener at index n" },
79500db5 335 { "getDNSCryptBind", true, "n", "return the `DNSCryptContext` object corresponding to the bind `n`" },
5d31a326 336 { "getPool", true, "name", "return the pool named `name`, or \"\" for the default pool" },
ca4252e0 337 { "getPoolServers", true, "pool", "return servers part of this pool" },
786e4d8c 338 { "getQueryCounters", true, "[max=10]", "show current buffer of query counters, limited by 'max' if provided" },
ca4252e0
RG
339 { "getResponseRing", true, "", "return the current content of the response ring" },
340 { "getServer", true, "n", "returns server with index n" },
341 { "getServers", true, "", "returns a table with all defined servers" },
a227f47d 342 { "getTLSContext", true, "n", "returns the TLS context with index n" },
6f2a4580 343 { "inClientStartup", true, "", "returns true during console client parsing of configuration" },
ca4252e0
RG
344 { "grepq", true, "Netmask|DNS Name|100ms|{\"::1\", \"powerdns.com\", \"100ms\"} [, n]", "shows the last n queries and responses matching the specified client address or range (Netmask), or the specified DNS Name, or slower than 100ms" },
345 { "leastOutstanding", false, "", "Send traffic to downstream server with least outstanding queries, with the lowest 'order', and within that the lowest recent latency"},
456fc645 346 { "LogAction", true, "[filename], [binary], [append], [buffered]", "Log a line for each query, to the specified file if any, to the console (require verbose) otherwise. When logging to a file, the `binary` optional parameter specifies whether we log in binary form (default) or in textual form, the `append` optional parameter specifies whether we open the file for appending or truncate each time (default), and the `buffered` optional parameter specifies whether writes to the file are buffered (default) or not." },
ca4252e0 347 { "makeKey", true, "", "generate a new server access key, emit configuration line ready for pasting" },
67ce0bdd 348 { "MaxQPSIPRule", true, "qps, [v4Mask=32 [, v6Mask=64 [, burst=qps [, expiration=300 [, cleanupDelay=60]]]]]", "matches traffic exceeding the qps limit per subnet" },
ca4252e0 349 { "MaxQPSRule", true, "qps", "matches traffic **not** exceeding this qps limit" },
cf48b0ce 350 { "mvCacheHitResponseRule", true, "from, to", "move cache hit response rule 'from' to a position where it is in front of 'to'. 'to' can be one larger than the largest rule" },
ca4252e0
RG
351 { "mvResponseRule", true, "from, to", "move response rule 'from' to a position where it is in front of 'to'. 'to' can be one larger than the largest rule" },
352 { "mvRule", true, "from, to", "move rule 'from' to a position where it is in front of 'to'. 'to' can be one larger than the largest rule, in which case the rule will be moved to the last position" },
2d4783a8 353 { "mvSelfAnsweredResponseRule", true, "from, to", "move self-answered response rule 'from' to a position where it is in front of 'to'. 'to' can be one larger than the largest rule" },
ca4252e0 354 { "newDNSName", true, "name", "make a DNSName based on this .-terminated name" },
82a91ddf
CH
355 { "newFrameStreamTcpLogger", true, "addr", "create a FrameStream logger object writing to a TCP address (addr should be ip:port), to use with `DnstapLogAction()` and `DnstapLogResponseAction()`" },
356 { "newFrameStreamUnixLogger", true, "socket", "create a FrameStream logger object writing to a local unix socket, to use with `DnstapLogAction()` and `DnstapLogResponseAction()`" },
4bc167b8 357 { "newPacketCache", true, "maxEntries[, maxTTL=86400, minTTL=0, temporaryFailureTTL=60, staleTTL=60, dontAge=false, numberOfShards=1, deferrableInsertLock=true]", "return a new Packet Cache" },
ca4252e0
RG
358 { "newQPSLimiter", true, "rate, burst", "configure a QPS limiter with that rate and that burst capacity" },
359 { "newRemoteLogger", true, "address:port [, timeout=2, maxQueuedEntries=100, reconnectWaitTime=1]", "create a Remote Logger object, to use with `RemoteLogAction()` and `RemoteLogResponseAction()`" },
4d5959e6 360 { "newRuleAction", true, "DNS rule, DNS action [, {uuid=\"UUID\"}]", "return a pair of DNS Rule and DNS Action, to be used with `setRules()`" },
150105a2 361 { "newServer", true, "{address=\"ip:port\", qps=1000, order=1, weight=10, pool=\"abuse\", retries=5, tcpConnectTimeout=5, tcpSendTimeout=30, tcpRecvTimeout=30, checkName=\"a.root-servers.net.\", checkType=\"A\", maxCheckFailures=1, mustResolve=false, useClientSubnet=true, source=\"address|interface name|address@interface\", sockets=1}", "instantiate a server" },
ca4252e0
RG
362 { "newServerPolicy", true, "name, function", "create a policy object from a Lua function" },
363 { "newSuffixMatchNode", true, "", "returns a new SuffixMatchNode" },
364 { "NoRecurseAction", true, "", "strip RD bit from the question, let it go through" },
365 { "PoolAction", true, "poolname", "set the packet into the specified pool" },
366 { "printDNSCryptProviderFingerprint", true, "\"/path/to/providerPublic.key\"", "display the fingerprint of the provided resolver public key" },
367 { "RegexRule", true, "regex", "matches the query name against the supplied regex" },
8429ad04 368 { "registerDynBPFFilter", true, "DynBPFFilter", "register this dynamic BPF filter into the web interface so that its counters are displayed" },
165c9030
RG
369 { "RemoteLogAction", true, "RemoteLogger [, alterFunction]", "send the content of this query to a remote logger via Protocol Buffer. `alterFunction` is a callback, receiving a DNSQuestion and a DNSDistProtoBufMessage, that can be used to modify the Protocol Buffer content, for example for anonymization purposes" },
370 { "RemoteLogResponseAction", true, "RemoteLogger [,alterFunction [,includeCNAME]]", "send the content of this response to a remote logger via Protocol Buffer. `alterFunction` is the same callback than the one in `RemoteLogAction` and `includeCNAME` indicates whether CNAME records inside the response should be parsed and exported. The default is to only exports A and AAAA records" },
4d5959e6
RG
371 { "rmCacheHitResponseRule", true, "id", "remove cache hit response rule in position 'id', or whose uuid matches if 'id' is an UUID string" },
372 { "rmResponseRule", true, "id", "remove response rule in position 'id', or whose uuid matches if 'id' is an UUID string" },
373 { "rmRule", true, "id", "remove rule in position 'id', or whose uuid matches if 'id' is an UUID string" },
2d4783a8 374 { "rmSelfAnsweredResponseRule", true, "id", "remove self-answered response rule in position 'id', or whose uuid matches if 'id' is an UUID string" },
ca4252e0
RG
375 { "rmServer", true, "n", "remove server with index n" },
376 { "roundrobin", false, "", "Simple round robin over available servers" },
377 { "QNameLabelsCountRule", true, "min, max", "matches if the qname has less than `min` or more than `max` labels" },
0f697c45 378 { "QNameRule", true, "qname", "matches queries with the specified qname" },
ca4252e0
RG
379 { "QNameWireLengthRule", true, "min, max", "matches if the qname's length on the wire is less than `min` or more than `max` bytes" },
380 { "QTypeRule", true, "qtype", "matches queries with the specified qtype" },
788c3243 381 { "RCodeRule", true, "rcode", "matches responses with the specified rcode" },
d83feb68 382 { "ERCodeRule", true, "rcode", "matches responses with the specified extended rcode (EDNS0)" },
9f4eb5cc 383 { "sendCustomTrap", true, "str", "send a custom `SNMP` trap from Lua, containing the `str` string"},
ca4252e0 384 { "setACL", true, "{netmask, netmask}", "replace the ACL set with these netmasks. Use `setACL({})` to reset the list, meaning no one can use us" },
56d68fad 385 { "setAPIWritable", true, "bool, dir", "allow modifications via the API. if `dir` is set, it must be a valid directory where the configuration files will be written by the API" },
b5521206 386 { "setConsoleACL", true, "{netmask, netmask}", "replace the console ACL set with these netmasks" },
506bb661 387 { "setConsoleConnectionsLogging", true, "enabled", "whether to log the opening and closing of console connections" },
ca4252e0 388 { "setDNSSECPool", true, "pool name", "move queries requesting DNSSEC processing to this pool" },
7b925432 389 { "setDynBlocksAction", true, "action", "set which action is performed when a query is blocked. Only DNSAction.Drop (the default) and DNSAction.Refused are supported" },
ca4252e0
RG
390 { "setECSOverride", true, "bool", "whether to override an existing EDNS Client Subnet value in the query" },
391 { "setECSSourcePrefixV4", true, "prefix-length", "the EDNS Client Subnet prefix-length used for IPv4 queries" },
392 { "setECSSourcePrefixV6", true, "prefix-length", "the EDNS Client Subnet prefix-length used for IPv6 queries" },
393 { "setKey", true, "key", "set access key to that key" },
4bc167b8 394 { "setLocal", true, "addr [, {doTCP=true, reusePort=false, tcpFastOpenSize=0, interface=\"\", cpus={}}]", "reset the list of addresses we listen on to this address" },
ca4252e0 395 { "setMaxTCPClientThreads", true, "n", "set the maximum of TCP client threads, handling TCP connections" },
9396d955
RG
396 { "setMaxTCPConnectionDuration", true, "n", "set the maximum duration of an incoming TCP connection, in seconds. 0 means unlimited" },
397 { "setMaxTCPConnectionsPerClient", true, "n", "set the maximum number of TCP connections per client. 0 means unlimited" },
398 { "setMaxTCPQueriesPerConnection", true, "n", "set the maximum number of queries in an incoming TCP connection. 0 means unlimited" },
ca4252e0
RG
399 { "setMaxTCPQueuedConnections", true, "n", "set the maximum number of TCP connections queued (waiting to be picked up by a client thread)" },
400 { "setMaxUDPOutstanding", true, "n", "set the maximum number of outstanding UDP queries to a given backend server. This can only be set at configuration time and defaults to 10240" },
742c079a
RG
401 { "setPoolServerPolicy", true, "policy, pool", "set the server selection policy for this pool to that policy" },
402 { "setPoolServerPolicy", true, "name, func, pool", "set the server selection policy for this pool to one named 'name' and provided by 'function'" },
786e4d8c
RS
403 { "setQueryCount", true, "bool", "set whether queries should be counted" },
404 { "setQueryCountFilter", true, "func", "filter queries that would be counted, where `func` is a function with parameter `dq` which decides whether a query should and how it should be counted" },
6d31c8b6 405 { "setRingBuffersLockRetries", true, "n", "set the number of attempts to get a non-blocking lock to a ringbuffer shard before blocking" },
a609acdb 406 { "setRingBuffersSize", true, "n [, numberOfShards]", "set the capacity of the ringbuffers used for live traffic inspection to `n`, and optionally the number of shards to use to `numberOfShards`" },
ca4252e0
RG
407 { "setRules", true, "list of rules", "replace the current rules with the supplied list of pairs of DNS Rules and DNS Actions (see `newRuleAction()`)" },
408 { "setServerPolicy", true, "policy", "set server selection policy to that policy" },
409 { "setServerPolicyLua", true, "name, function", "set server selection policy to one named 'name' and provided by 'function'" },
26a3cdb7 410 { "setServFailWhenNoServer", true, "bool", "if set, return a ServFail when no servers are available, instead of the default behaviour of dropping the query" },
9a32faa3 411 { "setStaleCacheEntriesTTL", true, "n", "allows using cache entries expired for at most n seconds when there is no backend available to answer for a query" },
840ed663 412 { "setTCPDownstreamCleanupInterval", true, "interval", "minimum interval in seconds between two cleanups of the idle TCP downstream connections" },
edbda1ad 413 { "setTCPUseSinglePipe", true, "bool", "whether the incoming TCP connections should be put into a single queue instead of using per-thread queues. Defaults to false" },
ca4252e0
RG
414 { "setTCPRecvTimeout", true, "n", "set the read timeout on TCP connections from the client, in seconds" },
415 { "setTCPSendTimeout", true, "n", "set the write timeout on TCP connections from the client, in seconds" },
0beaa5c8 416 { "setUDPMultipleMessagesVectorSize", true, "n", "set the size of the vector passed to recvmmsg() to receive UDP messages. Default to 1 which means that the feature is disabled and recvmsg() is used instead" },
e0b5e49d 417 { "setUDPTimeout", true, "n", "set the maximum time dnsdist will wait for a response from a backend over UDP, in seconds" },
ca4252e0
RG
418 { "setVerboseHealthChecks", true, "bool", "set whether health check errors will be logged" },
419 { "show", true, "string", "outputs `string`" },
420 { "showACL", true, "", "show our ACL set" },
ca55cc52 421 { "showBinds", true, "", "show listening addresses (frontends)" },
15bb664c 422 { "showCacheHitResponseRules", true, "[{showUUIDs=false, truncateRuleWidth=-1}]", "show all defined cache hit response rules, optionally with their UUIDs and optionally truncated to a given width" },
b5521206 423 { "showConsoleACL", true, "", "show our current console ACL set" },
ca4252e0
RG
424 { "showDNSCryptBinds", true, "", "display the currently configured DNSCrypt binds" },
425 { "showDynBlocks", true, "", "show dynamic blocks in force" },
5d31a326 426 { "showPools", true, "", "show the available pools" },
742c079a 427 { "showPoolServerPolicy", true, "pool", "show server selection policy for this pool" },
ca4252e0 428 { "showResponseLatency", true, "", "show a plot of the response time latency distribution" },
3a5a3376
CHB
429 { "showResponseRules", true, "[{showUUIDs=false, truncateRuleWidth=-1}]", "show all defined response rules, optionally with their UUIDs and optionally truncated to a given width" },
430 { "showRules", true, "[{showUUIDs=false, truncateRuleWidth=-1}]", "show all defined rules, optionally with their UUIDs and optionally truncated to a given width" },
431 { "showSelfAnsweredResponseRules", true, "[{showUUIDs=false, truncateRuleWidth=-1}]", "show all defined self-answered response rules, optionally with their UUIDs and optionally truncated to a given width" },
ca4252e0
RG
432 { "showServerPolicy", true, "", "show name of currently operational server selection policy" },
433 { "showServers", true, "", "output all servers" },
e65ae260 434 { "showTCPStats", true, "", "show some statistics regarding TCP" },
8b25405d 435 { "showTLSContexts", true, "", "list all the available TLS contexts" },
ca4252e0
RG
436 { "showVersion", true, "", "show the current version" },
437 { "shutdown", true, "", "shut down `dnsdist`" },
9f4eb5cc
RG
438 { "snmpAgent", true, "enableTraps [, masterSocket]", "enable `SNMP` support. `enableTraps` is a boolean indicating whether traps should be sent and `masterSocket` an optional string specifying how to connect to the master agent"},
439 { "SNMPTrapAction", true, "[reason]", "send an SNMP trap, adding the optional `reason` string as the query description"},
440 { "SNMPTrapResponseAction", true, "[reason]", "send an SNMP trap, adding the optional `reason` string as the response description"},
ca4252e0 441 { "SpoofAction", true, "{ip, ...} ", "forge a response with the specified IPv4 (for an A query) or IPv6 (for an AAAA). If you specify multiple addresses, all that match the query type (A, AAAA or ANY) will get spoofed in" },
a76b0d63
RG
442 { "TagAction", true, "name, value", "set the tag named 'name' to the given value" },
443 { "TagResponseAction", true, "name, value", "set the tag named 'name' to the given value" },
444 { "TagRule", true, "name [, value]", "matches if the tag named 'name' is present, with the given 'value' matching if any" },
ca4252e0 445 { "TCAction", true, "", "create answer to query with TC and RD bits set, to move to TCP" },
a2c4a339
CH
446 { "TeeAction", true, "remote [, addECS]", "send copy of query to remote, optionally adding ECS info" },
447 { "TempFailureCacheTTLAction", true, "ttl", "set packetcache TTL for temporary failure replies" },
ca4252e0 448 { "testCrypto", true, "", "test of the crypto all works" },
01b8149e 449 { "TimedIPSetRule", true, "", "Create a rule which matches a set of IP addresses which expire"},
ca4252e0 450 { "topBandwidth", true, "top", "show top-`top` clients that consume the most bandwidth over length of ringbuffer" },
cf48b0ce 451 { "topCacheHitResponseRule", true, "", "move the last cache hit response rule to the first position" },
ca4252e0
RG
452 { "topClients", true, "n", "show top-`n` clients sending the most queries over length of ringbuffer" },
453 { "topQueries", true, "n[, labels]", "show top 'n' queries, as grouped when optionally cut down to 'labels' labels" },
454 { "topResponses", true, "n, kind[, labels]", "show top 'n' responses with RCODE=kind (0=NO Error, 2=ServFail, 3=ServFail), as grouped when optionally cut down to 'labels' labels" },
2d4783a8 455 { "topCacheHitResponseRule", true, "", "move the last cache hit response rule to the first position" },
ca4252e0
RG
456 { "topResponseRule", true, "", "move the last response rule to the first position" },
457 { "topRule", true, "", "move the last rule to the first position" },
2d4783a8 458 { "topSelfAnsweredResponseRule", true, "", "move the last self-answered response rule to the first position" },
ca4252e0 459 { "topSlow", true, "[top][, limit][, labels]", "show `top` queries slower than `limit` milliseconds, grouped by last `labels` labels" },
e72fbfc4 460 { "truncateTC", true, "bool", "if set (defaults to no starting with dnsdist 1.2.0) truncate TC=1 answers so they are actually empty. Fixes an issue for PowerDNS Authoritative Server 2.9.22. Note: turning this on breaks compatibility with RFC 6891." },
8429ad04 461 { "unregisterDynBPFFilter", true, "DynBPFFilter", "unregister this dynamic BPF filter" },
ca4252e0
RG
462 { "webserver", true, "address:port, password [, apiKey [, customHeaders ]])", "launch a webserver with stats on that address with that password" },
463 { "whashed", false, "", "Weighted hashed ('sticky') distribution over available servers, based on the server 'weight' parameter" },
464 { "wrandom", false, "", "Weighted random over available servers, based on the server 'weight' parameter" },
465};
466
ffb07158 467extern "C" {
468char* my_generator(const char* text, int state)
469{
470 string t(text);
e8130431
RG
471 /* to keep it readable, we try to keep only 4 keywords per line
472 and to start a new line when the first letter changes */
ffb07158 473 static int s_counter=0;
474 int counter=0;
475 if(!state)
476 s_counter=0;
477
ca4252e0
RG
478 for(const auto& keyword : g_consoleKeywords) {
479 if(boost::starts_with(keyword.name, t) && counter++ == s_counter) {
480 std::string value(keyword.name);
ffb07158 481 s_counter++;
ca4252e0
RG
482 if (keyword.function) {
483 value += "(";
484 if (keyword.parameters.empty()) {
485 value += ")";
486 }
487 }
488 return strdup(value.c_str());
ffb07158 489 }
490 }
491 return 0;
492}
493
494char** my_completion( const char * text , int start, int end)
495{
496 char **matches=0;
497 if (start == 0)
498 matches = rl_completion_matches ((char*)text, &my_generator);
d9de8b61
CH
499
500 // skip default filename completion.
501 rl_attempted_completion_over = 1;
502
ffb07158 503 return matches;
504}
505}
506
b5521206 507static void controlClientThread(int fd, ComboAddress client)
ffb07158 508try
509{
9c186303 510 setTCPNoDelay(fd);
333ea16e 511 SodiumNonce theirs, ours, readingNonce, writingNonce;
ffb07158 512 ours.init();
333ea16e 513 readn2(fd, (char*)theirs.value, sizeof(theirs.value));
ffb07158 514 writen2(fd, (char*)ours.value, sizeof(ours.value));
333ea16e
RG
515 readingNonce.merge(ours, theirs);
516 writingNonce.merge(theirs, ours);
ffb07158 517
518 for(;;) {
519 uint32_t len;
520 if(!getMsgLen32(fd, &len))
521 break;
0877da98
RG
522
523 if (len == 0) {
524 /* just ACK an empty message
525 with an empty response */
526 putMsgLen32(fd, 0);
527 continue;
528 }
529
ffb07158 530 boost::scoped_array<char> msg(new char[len]);
531 readn2(fd, msg.get(), len);
532
533 string line(msg.get(), len);
b5521206 534 line = sodDecryptSym(line, g_consoleKey, readingNonce);
ffb07158 535 // cerr<<"Have decrypted line: "<<line<<endl;
536 string response;
537 try {
7e7a5b71 538 bool withReturn=true;
539 retry:;
540 try {
541 std::lock_guard<std::mutex> lock(g_luamutex);
542
543 g_outputBuffer.clear();
544 resetLuaSideEffect();
545 auto ret=g_lua.executeCode<
546 boost::optional<
547 boost::variant<
548 string,
549 shared_ptr<DownstreamState>,
630e3e0a 550 ClientState*,
7e7a5b71 551 std::unordered_map<string, double>
552 >
553 >
554 >(withReturn ? ("return "+line) : line);
ffb07158 555
556 if(ret) {
630e3e0a 557 if (const auto dsValue = boost::get<shared_ptr<DownstreamState>>(&*ret)) {
6d54c50c
CH
558 if (*dsValue) {
559 response=(*dsValue)->getName()+"\n";
560 } else {
561 response="";
562 }
630e3e0a
CH
563 }
564 else if (const auto csValue = boost::get<ClientState*>(&*ret)) {
6d54c50c
CH
565 if (*csValue) {
566 response=(*csValue)->local.toStringWithPort()+"\n";
567 } else {
568 response="";
569 }
630e3e0a
CH
570 }
571 else if (const auto strValue = boost::get<string>(&*ret)) {
572 response=*strValue+"\n";
573 }
7e7a5b71 574 else if(const auto um = boost::get<std::unordered_map<string, double> >(&*ret)) {
575 using namespace json11;
576 Json::object o;
577 for(const auto& v : *um)
578 o[v.first]=v.second;
579 Json out = o;
580 response=out.dump()+"\n";
581 }
ffb07158 582 }
583 else
584 response=g_outputBuffer;
f758857a 585 if(!getLuaNoSideEffect())
586 feedConfigDelta(line);
7e7a5b71 587 }
588 catch(const LuaContext::SyntaxErrorException&) {
589 if(withReturn) {
590 withReturn=false;
591 goto retry;
592 }
593 throw;
594 }
ffb07158 595 }
628377ec
RG
596 catch(const LuaContext::WrongTypeException& e) {
597 response = "Command returned an object we can't print: " +std::string(e.what()) + "\n";
598 // tried to return something we don't understand
599 }
ffb07158 600 catch(const LuaContext::ExecutionErrorException& e) {
98bac6bc 601 if(!strcmp(e.what(),"invalid key to 'next'"))
602 response = "Error: Parsing function parameters, did you forget parameter name?";
603 else
604 response = "Error: " + string(e.what());
ffb07158 605 try {
606 std::rethrow_if_nested(e);
af619119
RG
607 } catch(const std::exception& ne) {
608 // ne is the exception that was thrown from inside the lambda
609 response+= ": " + string(ne.what());
ffb07158 610 }
af619119
RG
611 catch(const PDNSException& ne) {
612 // ne is the exception that was thrown from inside the lambda
613 response += ": " + string(ne.reason);
ffb07158 614 }
615 }
616 catch(const LuaContext::SyntaxErrorException& e) {
617 response = "Error: " + string(e.what()) + ": ";
618 }
b5521206 619 response = sodEncryptSym(response, g_consoleKey, writingNonce);
ffb07158 620 putMsgLen32(fd, response.length());
621 writen2(fd, response.c_str(), response.length());
622 }
506bb661
RG
623 if (g_logConsoleConnections) {
624 infolog("Closed control connection from %s", client.toStringWithPort());
625 }
ffb07158 626 close(fd);
627 fd=-1;
628}
629catch(std::exception& e)
630{
631 errlog("Got an exception in client connection from %s: %s", client.toStringWithPort(), e.what());
632 if(fd >= 0)
633 close(fd);
634}
635
b5521206
RG
636void controlThread(int fd, ComboAddress local)
637try
638{
639 ComboAddress client;
640 int sock;
641 auto localACL = g_consoleACL.getLocal();
642 infolog("Accepting control connections on %s", local.toStringWithPort());
643
644 while ((sock = SAccept(fd, client)) >= 0) {
645
646 if (!localACL->match(client)) {
647 vinfolog("Control connection from %s dropped because of ACL", client.toStringWithPort());
648 close(sock);
649 continue;
650 }
651
652 if (g_logConsoleConnections) {
653 warnlog("Got control connection from %s", client.toStringWithPort());
654 }
655
656 std::thread t(controlClientThread, sock, client);
657 t.detach();
658 }
659}
660catch(const std::exception& e)
661{
662 close(fd);
663 errlog("Control connection died: %s", e.what());
664}