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