]> git.ipfire.org Git - thirdparty/pdns.git/blame - pdns/lua-recursor4.cc
Merge pull request #8245 from Habbie/dns_random_testing
[thirdparty/pdns.git] / pdns / lua-recursor4.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 */
808c5ef7 22#include "lua-recursor4.hh"
23#include <fstream>
808c5ef7 24#include "logger.hh"
a3e7b735 25#include "dnsparser.hh"
26#include "syncres.hh"
dd39e2dc 27#include "namespaces.hh"
b40562da
RG
28#include "rec_channel.hh"
29#include "ednsoptions.hh"
5ecf1d7e 30#include "ednssubnet.hh"
db486de5 31#include "filterpo.hh"
d705aad9 32#include "rec-snmp.hh"
08dcccd6 33#include <unordered_set>
410d750c 34
9694e14f 35RecursorLua4::RecursorLua4() { prepareContext(); }
70c21c40 36
a3e7b735 37static int getFakeAAAARecords(const DNSName& qname, const std::string& prefix, vector<DNSRecord>& ret)
38{
39 int rcode=directResolve(qname, QType(QType::A), 1, ret);
40
41 ComboAddress prefixAddress(prefix);
42
9fc9be6a
PL
43 // Remove double CNAME records
44 std::set<DNSName> seenCNAMEs;
45 ret.erase(std::remove_if(
46 ret.begin(),
47 ret.end(),
48 [&seenCNAMEs](DNSRecord& rr) {
49 if (rr.d_type == QType::CNAME) {
50 auto target = getRR<CNAMERecordContent>(rr);
51 if (target == nullptr) {
52 return false;
53 }
54 if (seenCNAMEs.count(target->getTarget()) > 0) {
55 // We've had this CNAME before, remove it
56 return true;
57 }
58 seenCNAMEs.insert(target->getTarget());
59 }
60 return false;
61 }),
62 ret.end());
63
8c0f5e09 64 bool seenA = false;
a3e7b735 65 for(DNSRecord& rr : ret)
66 {
67 if(rr.d_type == QType::A && rr.d_place==DNSResourceRecord::ANSWER) {
ba3c54cb
RG
68 if(auto rec = getRR<ARecordContent>(rr)) {
69 ComboAddress ipv4(rec->getCA());
70 uint32_t tmp;
71 memcpy((void*)&tmp, &ipv4.sin4.sin_addr.s_addr, 4);
72 // tmp=htonl(tmp);
73 memcpy(((char*)&prefixAddress.sin6.sin6_addr.s6_addr)+12, &tmp, 4);
74 rr.d_content = std::make_shared<AAAARecordContent>(prefixAddress);
75 rr.d_type = QType::AAAA;
76 }
8c0f5e09 77 seenA = true;
a3e7b735 78 }
79 }
8c0f5e09
PL
80
81 if (seenA) {
82 // We've seen an A in the ANSWER section, so there is no need to keep any
83 // SOA in the AUTHORITY section as this is not a NODATA response.
84 ret.erase(std::remove_if(
85 ret.begin(),
86 ret.end(),
87 [](DNSRecord& rr) {
88 return (rr.d_type == QType::SOA && rr.d_place==DNSResourceRecord::AUTHORITY);
89 }),
90 ret.end());
91 }
a3e7b735 92 return rcode;
93}
94
95static int getFakePTRRecords(const DNSName& qname, const std::string& prefix, vector<DNSRecord>& ret)
96{
97 /* qname has a reverse ordered IPv6 address, need to extract the underlying IPv4 address from it
98 and turn it into an IPv4 in-addr.arpa query */
99 ret.clear();
100 vector<string> parts = qname.getRawLabels();
101
102 if(parts.size() < 8)
103 return -1;
104
105 string newquery;
106 for(int n = 0; n < 4; ++n) {
107 newquery +=
926ccaca 108 std::to_string(stoll(parts[n*2], 0, 16) + 16*stoll(parts[n*2+1], 0, 16));
a3e7b735 109 newquery.append(1,'.');
110 }
111 newquery += "in-addr.arpa.";
112
113
114 int rcode = directResolve(DNSName(newquery), QType(QType::PTR), 1, ret);
115 for(DNSRecord& rr : ret)
116 {
117 if(rr.d_type == QType::PTR && rr.d_place==DNSResourceRecord::ANSWER) {
118 rr.d_name = qname;
119 }
120 }
121 return rcode;
122
123}
124
621e4e59
PL
125boost::optional<dnsheader> RecursorLua4::DNSQuestion::getDH() const
126{
127 if (dh)
128 return *dh;
129 return boost::optional<dnsheader>();
130}
131
e2fb3504
PL
132vector<string> RecursorLua4::DNSQuestion::getEDNSFlags() const
133{
134 vector<string> ret;
135 if (ednsFlags) {
136 if (*ednsFlags & EDNSOpts::DNSSECOK)
137 ret.push_back("DO");
138 }
139 return ret;
140}
141
142bool RecursorLua4::DNSQuestion::getEDNSFlag(string flag) const
143{
144 if (ednsFlags) {
145 if (flag == "DO" && (*ednsFlags & EDNSOpts::DNSSECOK))
146 return true;
147 }
148 return false;
149}
150
ba21fcfe 151vector<pair<uint16_t, string> > RecursorLua4::DNSQuestion::getEDNSOptions() const
e8340d27 152{
153 if(ednsOptions)
154 return *ednsOptions;
155 else
156 return vector<pair<uint16_t,string>>();
157}
158
ba21fcfe 159boost::optional<string> RecursorLua4::DNSQuestion::getEDNSOption(uint16_t code) const
e8340d27 160{
161 if(ednsOptions)
162 for(const auto& o : *ednsOptions)
163 if(o.first==code)
164 return o.second;
165
166 return boost::optional<string>();
167}
168
ba21fcfe 169boost::optional<Netmask> RecursorLua4::DNSQuestion::getEDNSSubnet() const
5ecf1d7e 170{
5ecf1d7e 171 if(ednsOptions) {
172 for(const auto& o : *ednsOptions) {
b40562da 173 if(o.first==EDNSOptionCode::ECS) {
5ecf1d7e 174 EDNSSubnetOpts eso;
175 if(getEDNSSubnetOptsFromString(o.second, &eso))
176 return eso.source;
177 else
178 break;
179 }
180 }
181 }
182 return boost::optional<Netmask>();
183}
184
e8340d27 185
ba21fcfe 186vector<pair<int, DNSRecord> > RecursorLua4::DNSQuestion::getRecords() const
a3e7b735 187{
188 vector<pair<int, DNSRecord> > ret;
189 int num=1;
190 for(const auto& r : records) {
191 ret.push_back({num++, r});
192 }
193 return ret;
194}
195void RecursorLua4::DNSQuestion::setRecords(const vector<pair<int, DNSRecord> >& recs)
196{
197 records.clear();
198 for(const auto& p : recs) {
199 records.push_back(p.second);
a3e7b735 200 }
201}
202
aee72a7b 203void RecursorLua4::DNSQuestion::addRecord(uint16_t type, const std::string& content, DNSResourceRecord::Place place, boost::optional<int> ttl, boost::optional<string> name)
a3e7b735 204{
205 DNSRecord dr;
aee72a7b 206 dr.d_name=name ? DNSName(*name) : qname;
a3e7b735 207 dr.d_ttl=ttl.get_value_or(3600);
208 dr.d_type = type;
209 dr.d_place = place;
6177a176 210 dr.d_content = DNSRecordContent::mastermake(type, 1, content);
a3e7b735 211 records.push_back(dr);
212}
213
aee72a7b 214void RecursorLua4::DNSQuestion::addAnswer(uint16_t type, const std::string& content, boost::optional<int> ttl, boost::optional<string> name)
a3e7b735 215{
aee72a7b 216 addRecord(type, content, DNSResourceRecord::ANSWER, ttl, name);
a3e7b735 217}
9f89a5f1 218
219struct DynMetric
220{
221 std::atomic<unsigned long>* ptr;
222 void inc() { (*ptr)++; }
223 void incBy(unsigned int by) { (*ptr)+= by; }
224 unsigned long get() { return *ptr; }
225 void set(unsigned long val) { *ptr =val; }
226};
227
70c21c40 228void RecursorLua4::postPrepareContext()
808c5ef7 229{
ba21fcfe
RG
230 d_lw->registerMember<const DNSName (DNSQuestion::*)>("qname", [](const DNSQuestion& dq) -> const DNSName& { return dq.qname; }, [](DNSQuestion& dq, const DNSName& newName) { (void) newName; });
231 d_lw->registerMember<uint16_t (DNSQuestion::*)>("qtype", [](const DNSQuestion& dq) -> uint16_t { return dq.qtype; }, [](DNSQuestion& dq, uint16_t newType) { (void) newType; });
232 d_lw->registerMember<bool (DNSQuestion::*)>("isTcp", [](const DNSQuestion& dq) -> bool { return dq.isTcp; }, [](DNSQuestion& dq, bool newTcp) { (void) newTcp; });
233 d_lw->registerMember<const ComboAddress (DNSQuestion::*)>("localaddr", [](const DNSQuestion& dq) -> const ComboAddress& { return dq.local; }, [](DNSQuestion& dq, const ComboAddress& newLocal) { (void) newLocal; });
234 d_lw->registerMember<const ComboAddress (DNSQuestion::*)>("remoteaddr", [](const DNSQuestion& dq) -> const ComboAddress& { return dq.remote; }, [](DNSQuestion& dq, const ComboAddress& newRemote) { (void) newRemote; });
1921a4c2 235 d_lw->registerMember<vState (DNSQuestion::*)>("validationState", [](const DNSQuestion& dq) -> vState { return dq.validationState; }, [](DNSQuestion& dq, vState newState) { (void) newState; });
ba21fcfe
RG
236
237 d_lw->registerMember<bool (DNSQuestion::*)>("variable", [](const DNSQuestion& dq) -> bool { return dq.variable; }, [](DNSQuestion& dq, bool newVariable) { dq.variable = newVariable; });
238 d_lw->registerMember<bool (DNSQuestion::*)>("wantsRPZ", [](const DNSQuestion& dq) -> bool { return dq.wantsRPZ; }, [](DNSQuestion& dq, bool newWantsRPZ) { dq.wantsRPZ = newWantsRPZ; });
f1c7929a 239 d_lw->registerMember<bool (DNSQuestion::*)>("logResponse", [](const DNSQuestion& dq) -> bool { return dq.logResponse; }, [](DNSQuestion& dq, bool newLogResponse) { dq.logResponse = newLogResponse; });
ba21fcfe 240
a3e7b735 241 d_lw->registerMember("rcode", &DNSQuestion::rcode);
ba461517 242 d_lw->registerMember("tag", &DNSQuestion::tag);
67e31ebe 243 d_lw->registerMember("requestorId", &DNSQuestion::requestorId);
e92fb64f
CHB
244 d_lw->registerMember("deviceId", &DNSQuestion::deviceId);
245 d_lw->registerMember("deviceName", &DNSQuestion::deviceName);
a3e7b735 246 d_lw->registerMember("followupFunction", &DNSQuestion::followupFunction);
247 d_lw->registerMember("followupPrefix", &DNSQuestion::followupPrefix);
248 d_lw->registerMember("followupName", &DNSQuestion::followupName);
6b8b26c8 249 d_lw->registerMember("data", &DNSQuestion::data);
250 d_lw->registerMember("udpQuery", &DNSQuestion::udpQuery);
251 d_lw->registerMember("udpAnswer", &DNSQuestion::udpAnswer);
252 d_lw->registerMember("udpQueryDest", &DNSQuestion::udpQueryDest);
253 d_lw->registerMember("udpCallback", &DNSQuestion::udpCallback);
667f6c7c 254 d_lw->registerMember("appliedPolicy", &DNSQuestion::appliedPolicy);
98c28a68
RG
255 d_lw->registerMember<DNSFilterEngine::Policy, std::string>("policyName",
256 [](const DNSFilterEngine::Policy& pol) -> std::string {
257 if(pol.d_name)
258 return *pol.d_name;
259 return std::string();
260 },
261 [](DNSFilterEngine::Policy& pol, const std::string& name) {
262 pol.d_name = std::make_shared<std::string>(name);
263 });
db486de5
PL
264 d_lw->registerMember("policyKind", &DNSFilterEngine::Policy::d_kind);
265 d_lw->registerMember("policyTTL", &DNSFilterEngine::Policy::d_ttl);
98c28a68
RG
266 d_lw->registerMember<DNSFilterEngine::Policy, std::string>("policyCustom",
267 [](const DNSFilterEngine::Policy& pol) -> std::string {
6da513b2
RG
268 std::string result;
269 if (pol.d_kind != DNSFilterEngine::PolicyKind::Custom) {
270 return result;
271 }
272
273 for (const auto& dr : pol.d_custom) {
274 if (!result.empty()) {
275 result += "\n";
276 }
277 result += dr->getZoneRepresentation();
278 }
279
280 return result;
db486de5 281 },
98c28a68 282 [](DNSFilterEngine::Policy& pol, const std::string& content) {
db486de5 283 // Only CNAMES for now, when we ever add a d_custom_type, there will be pain
6da513b2
RG
284 pol.d_custom.clear();
285 pol.d_custom.push_back(DNSRecordContent::mastermake(QType::CNAME, QClass::IN, content));
db486de5
PL
286 }
287 );
621e4e59 288 d_lw->registerFunction("getDH", &DNSQuestion::getDH);
e8340d27 289 d_lw->registerFunction("getEDNSOptions", &DNSQuestion::getEDNSOptions);
290 d_lw->registerFunction("getEDNSOption", &DNSQuestion::getEDNSOption);
5ecf1d7e 291 d_lw->registerFunction("getEDNSSubnet", &DNSQuestion::getEDNSSubnet);
e2fb3504
PL
292 d_lw->registerFunction("getEDNSFlags", &DNSQuestion::getEDNSFlags);
293 d_lw->registerFunction("getEDNSFlag", &DNSQuestion::getEDNSFlag);
a3e7b735 294 d_lw->registerMember("name", &DNSRecord::d_name);
295 d_lw->registerMember("type", &DNSRecord::d_type);
296 d_lw->registerMember("ttl", &DNSRecord::d_ttl);
57d0c73b 297 d_lw->registerMember("place", &DNSRecord::d_place);
00b8cadc 298
29e6303a
RG
299 d_lw->registerMember("size", &EDNSOptionViewValue::size);
300 d_lw->registerFunction<std::string(EDNSOptionViewValue::*)()>("getContent", [](const EDNSOptionViewValue& value) { return std::string(value.content, value.size); });
301 d_lw->registerFunction<size_t(EDNSOptionView::*)()>("count", [](const EDNSOptionView& option) { return option.values.size(); });
6158a3b3
PD
302 d_lw->registerFunction<std::vector<string>(EDNSOptionView::*)()>("getValues", [] (const EDNSOptionView& option) {
303 std::vector<string> values;
29e6303a 304 for (const auto& value : option.values) {
6158a3b3 305 values.push_back(std::string(value.content, value.size));
29e6303a
RG
306 }
307 return values;
308 });
309
310 /* pre 4.2 API compatibility, when we had only one value for a given EDNS option */
311 d_lw->registerMember<uint16_t(EDNSOptionView::*)>("size", [](const EDNSOptionView& option) -> uint16_t {
312 uint16_t result = 0;
313
314 if (!option.values.empty()) {
315 result = option.values.at(0).size;
316 }
317 return result;
318 },
319 [](EDNSOptionView& option, uint16_t newSize) { (void) newSize; });
320 d_lw->registerFunction<std::string(EDNSOptionView::*)()>("getContent", [](const EDNSOptionView& option) {
321 if (option.values.empty()) {
322 return std::string();
323 }
324 return std::string(option.values.at(0).content, option.values.at(0).size); });
00b8cadc 325
a3e7b735 326 d_lw->registerFunction<string(DNSRecord::*)()>("getContent", [](const DNSRecord& dr) { return dr.d_content->getZoneRepresentation(); });
7d5f094a 327 d_lw->registerFunction<boost::optional<ComboAddress>(DNSRecord::*)()>("getCA", [](const DNSRecord& dr) {
328 boost::optional<ComboAddress> ret;
329
330 if(auto rec = std::dynamic_pointer_cast<ARecordContent>(dr.d_content))
331 ret=rec->getCA(53);
dd079764
RG
332 else if(auto aaaarec = std::dynamic_pointer_cast<AAAARecordContent>(dr.d_content))
333 ret=aaaarec->getCA(53);
7d5f094a 334 return ret;
335 });
a3e7b735 336
337
6177a176 338 d_lw->registerFunction<void(DNSRecord::*)(const std::string&)>("changeContent", [](DNSRecord& dr, const std::string& newContent) { dr.d_content = DNSRecordContent::mastermake(dr.d_type, 1, newContent); });
a3e7b735 339 d_lw->registerFunction("addAnswer", &DNSQuestion::addAnswer);
08dcccd6 340 d_lw->registerFunction("addRecord", &DNSQuestion::addRecord);
a3e7b735 341 d_lw->registerFunction("getRecords", &DNSQuestion::getRecords);
342 d_lw->registerFunction("setRecords", &DNSQuestion::setRecords);
343
48096cf0 344 d_lw->registerFunction<void(DNSQuestion::*)(const std::string&)>("addPolicyTag", [](DNSQuestion& dq, const std::string& tag) { if (dq.policyTags) { dq.policyTags->push_back(tag); } });
667f6c7c 345 d_lw->registerFunction<void(DNSQuestion::*)(const std::vector<std::pair<int, std::string> >&)>("setPolicyTags", [](DNSQuestion& dq, const std::vector<std::pair<int, std::string> >& tags) {
48096cf0
RG
346 if (dq.policyTags) {
347 dq.policyTags->clear();
348 for (const auto& tag : tags) {
349 dq.policyTags->push_back(tag.second);
350 }
667f6c7c
RG
351 }
352 });
353 d_lw->registerFunction<std::vector<std::pair<int, std::string> >(DNSQuestion::*)()>("getPolicyTags", [](const DNSQuestion& dq) {
354 std::vector<std::pair<int, std::string> > ret;
48096cf0
RG
355 if (dq.policyTags) {
356 int count = 1;
357 for (const auto& tag : *dq.policyTags) {
358 ret.push_back({count++, tag});
359 }
667f6c7c
RG
360 }
361 return ret;
362 });
363
0a273054
RG
364 d_lw->registerFunction<void(DNSQuestion::*)(const std::string&)>("discardPolicy", [](DNSQuestion& dq, const std::string& policy) {
365 if (dq.discardedPolicies) {
366 (*dq.discardedPolicies)[policy] = true;
367 }
368 });
369
a3e7b735 370 d_lw->writeFunction("newDS", []() { return SuffixMatchNode(); });
805f3e03
PL
371 d_lw->registerFunction<void(SuffixMatchNode::*)(boost::variant<string,DNSName, vector<pair<unsigned int,string> > >)>(
372 "add",
373 [](SuffixMatchNode&smn, const boost::variant<string,DNSName,vector<pair<unsigned int,string> > >& in){
374 try {
375 if(auto s = boost::get<string>(&in)) {
376 smn.add(DNSName(*s));
377 }
378 else if(auto v = boost::get<vector<pair<unsigned int, string> > >(&in)) {
dd079764
RG
379 for(const auto& entry : *v)
380 smn.add(DNSName(entry.second));
805f3e03
PL
381 }
382 else {
383 smn.add(boost::get<DNSName>(in));
384 }
385 }
386 catch(std::exception& e) {
e6a9dde5 387 g_log <<Logger::Error<<e.what()<<endl;
805f3e03
PL
388 }
389 }
390 );
391
a3e7b735 392 d_lw->registerFunction("check",(bool (SuffixMatchNode::*)(const DNSName&) const) &SuffixMatchNode::check);
c6b99fc1 393 d_lw->registerFunction("toString",(string (SuffixMatchNode::*)() const) &SuffixMatchNode::toString);
a3e7b735 394
70c21c40 395 d_pd.push_back({"policykinds", in_t {
db486de5
PL
396 {"NoAction", (int)DNSFilterEngine::PolicyKind::NoAction},
397 {"Drop", (int)DNSFilterEngine::PolicyKind::Drop },
398 {"NXDOMAIN", (int)DNSFilterEngine::PolicyKind::NXDOMAIN},
399 {"NODATA", (int)DNSFilterEngine::PolicyKind::NODATA },
400 {"Truncate", (int)DNSFilterEngine::PolicyKind::Truncate},
401 {"Custom", (int)DNSFilterEngine::PolicyKind::Custom }
402 }});
403
a3e7b735 404 for(const auto& n : QType::names)
70c21c40 405 d_pd.push_back({n.first, n.second});
1921a4c2 406
70c21c40 407 d_pd.push_back({"validationstates", in_t{
1921a4c2
RG
408 {"Indeterminate", Indeterminate },
409 {"Bogus", Bogus },
410 {"Insecure", Insecure },
411 {"Secure", Secure },
412 }});
413
70c21c40 414 d_pd.push_back({"now", &g_now});
9f89a5f1 415
416 d_lw->writeFunction("getMetric", [](const std::string& str) {
417 return DynMetric{getDynMetric(str)};
418 });
419
420 d_lw->registerFunction("inc", &DynMetric::inc);
421 d_lw->registerFunction("incBy", &DynMetric::incBy);
422 d_lw->registerFunction("set", &DynMetric::set);
423 d_lw->registerFunction("get", &DynMetric::get);
b4015453 424
b0b37121
RG
425 d_lw->writeFunction("getStat", [](const std::string& str) {
426 uint64_t result = 0;
427 optional<uint64_t> value = getStatByName(str);
428 if (value) {
429 result = *value;
430 }
431 return result;
432 });
433
b4015453
RG
434 d_lw->writeFunction("getRecursorThreadId", []() {
435 return getRecursorThreadId();
436 });
437
d705aad9
RG
438 d_lw->writeFunction("sendCustomSNMPTrap", [](const std::string& str) {
439 if (g_snmpAgent) {
440 g_snmpAgent->sendCustomTrap(str);
441 }
442 });
c2d0a26f
AT
443
444 d_lw->writeFunction("getregisteredname", [](const DNSName &dname) {
445 return getRegisteredName(dname);
446 });
70c21c40 447}
a3e7b735 448
70c21c40 449void RecursorLua4::postLoad() {
0a273054 450 d_prerpz = d_lw->readVariable<boost::optional<luacall_t>>("prerpz").get_value_or(0);
a3e7b735 451 d_preresolve = d_lw->readVariable<boost::optional<luacall_t>>("preresolve").get_value_or(0);
452 d_nodata = d_lw->readVariable<boost::optional<luacall_t>>("nodata").get_value_or(0);
453 d_nxdomain = d_lw->readVariable<boost::optional<luacall_t>>("nxdomain").get_value_or(0);
454 d_postresolve = d_lw->readVariable<boost::optional<luacall_t>>("postresolve").get_value_or(0);
f90c7544 455 d_preoutquery = d_lw->readVariable<boost::optional<luacall_t>>("preoutquery").get_value_or(0);
a2f87dd1 456 d_maintenance = d_lw->readVariable<boost::optional<luamaintenance_t>>("maintenance").get_value_or(0);
f90c7544 457
458 d_ipfilter = d_lw->readVariable<boost::optional<ipfilter_t>>("ipfilter").get_value_or(0);
81c0afd8 459 d_gettag = d_lw->readVariable<boost::optional<gettag_t>>("gettag").get_value_or(0);
70fb28d9 460 d_gettag_ffi = d_lw->readVariable<boost::optional<gettag_ffi_t>>("gettag_ffi").get_value_or(0);
808c5ef7 461}
462
c4e71b7c
OM
463void RecursorLua4::getFeatures(Features & features) {
464 // Add key-values pairs below.
465 // Make sure you add string values explicity converted to string.
466 // e.g. features.push_back(make_pair("somekey", string("stringvalue"));
467 // Both int and double end up as a lua number type.
468 features.push_back(make_pair("PR8001_devicename", true));
469}
470
a2f87dd1
CHB
471void RecursorLua4::maintenance() const
472{
473 if (d_maintenance) {
474 d_maintenance();
475 }
476}
477
5899ee54 478bool RecursorLua4::prerpz(DNSQuestion& dq, int& ret) const
0a273054 479{
ba21fcfe 480 return genhook(d_prerpz, dq, ret);
0a273054
RG
481}
482
5899ee54 483bool RecursorLua4::preresolve(DNSQuestion& dq, int& ret) const
808c5ef7 484{
ba21fcfe 485 return genhook(d_preresolve, dq, ret);
a3e7b735 486}
487
5899ee54 488bool RecursorLua4::nxdomain(DNSQuestion& dq, int& ret) const
a3e7b735 489{
ba21fcfe 490 return genhook(d_nxdomain, dq, ret);
a3e7b735 491}
492
5899ee54 493bool RecursorLua4::nodata(DNSQuestion& dq, int& ret) const
a3e7b735 494{
ba21fcfe 495 return genhook(d_nodata, dq, ret);
a3e7b735 496}
497
5899ee54 498bool RecursorLua4::postresolve(DNSQuestion& dq, int& ret) const
a3e7b735 499{
ba21fcfe 500 return genhook(d_postresolve, dq, ret);
a3e7b735 501}
502
5899ee54 503bool RecursorLua4::preoutquery(const ComboAddress& ns, const ComboAddress& requestor, const DNSName& query, const QType& qtype, bool isTcp, vector<DNSRecord>& res, int& ret) const
a3e7b735 504{
ba21fcfe
RG
505 bool variableAnswer = false;
506 bool wantsRPZ = false;
f1c7929a
RG
507 bool logQuery = false;
508 RecursorLua4::DNSQuestion dq(ns, requestor, query, qtype.getCode(), isTcp, variableAnswer, wantsRPZ, logQuery);
6e505c5e 509 dq.currentRecords = &res;
ba21fcfe
RG
510
511 return genhook(d_preoutquery, dq, ret);
a3e7b735 512}
513
5899ee54 514bool RecursorLua4::ipfilter(const ComboAddress& remote, const ComboAddress& local, const struct dnsheader& dh) const
a3e7b735 515{
516 if(d_ipfilter)
f5062066 517 return d_ipfilter(remote, local, dh);
f90c7544 518 return false; // don't block
a3e7b735 519}
520
0a6a45c8 521unsigned int RecursorLua4::gettag(const ComboAddress& remote, const Netmask& ednssubnet, const ComboAddress& local, const DNSName& qname, uint16_t qtype, std::vector<std::string>* policyTags, LuaContext::LuaObject& data, const EDNSOptionViewMap& ednsOptions, bool tcp, std::string& requestorId, std::string& deviceId, std::string& deviceName) const
81c0afd8 522{
02b47f43 523 if(d_gettag) {
dff843b2 524 auto ret = d_gettag(remote, ednssubnet, local, qname, qtype, ednsOptions, tcp);
02b47f43
RG
525
526 if (policyTags) {
527 const auto& tags = std::get<1>(ret);
528 if (tags) {
529 for (const auto& tag : *tags) {
530 policyTags->push_back(tag.second);
531 }
532 }
533 }
5fd2577f 534 const auto dataret = std::get<2>(ret);
05c74122
RG
535 if (dataret) {
536 data = *dataret;
537 }
67e31ebe
RG
538 const auto reqIdret = std::get<3>(ret);
539 if (reqIdret) {
540 requestorId = *reqIdret;
541 }
590388d2
NC
542 const auto deviceIdret = std::get<4>(ret);
543 if (deviceIdret) {
544 deviceId = *deviceIdret;
545 }
0a6a45c8
CHB
546
547 const auto deviceNameret = std::get<5>(ret);
548 if (deviceNameret) {
549 deviceName = *deviceNameret;
550 }
02b47f43
RG
551 return std::get<0>(ret);
552 }
81c0afd8 553 return 0;
554}
555
70fb28d9
RG
556struct pdns_ffi_param
557{
558public:
406b722e 559 pdns_ffi_param(const DNSName& qname_, uint16_t qtype_, const ComboAddress& local_, const ComboAddress& remote_, const Netmask& ednssubnet_, std::vector<std::string>& policyTags_, std::vector<DNSRecord>& records_, const EDNSOptionViewMap& ednsOptions_, std::string& requestorId_, std::string& deviceId_, std::string& deviceName_, boost::optional<int>& rcode_, uint32_t& ttlCap_, bool& variable_, bool tcp_, bool& logQuery_, bool& logResponse_, bool& followCNAMERecords_): qname(qname_), local(local_), remote(remote_), ednssubnet(ednssubnet_), policyTags(policyTags_), records(records_), ednsOptions(ednsOptions_), requestorId(requestorId_), deviceId(deviceId_), deviceName(deviceName_), rcode(rcode_), ttlCap(ttlCap_), variable(variable_), logQuery(logQuery_), logResponse(logResponse_), followCNAMERecords(followCNAMERecords_), qtype(qtype_), tcp(tcp_)
70fb28d9
RG
560 {
561 }
562
563 std::unique_ptr<std::string> qnameStr{nullptr};
564 std::unique_ptr<std::string> localStr{nullptr};
565 std::unique_ptr<std::string> remoteStr{nullptr};
566 std::unique_ptr<std::string> ednssubnetStr{nullptr};
567 std::vector<pdns_ednsoption_t> ednsOptionsVect;
568
569 const DNSName& qname;
570 const ComboAddress& local;
571 const ComboAddress& remote;
572 const Netmask& ednssubnet;
573 std::vector<std::string>& policyTags;
37a919d4 574 std::vector<DNSRecord>& records;
29e6303a 575 const EDNSOptionViewMap& ednsOptions;
70fb28d9
RG
576 std::string& requestorId;
577 std::string& deviceId;
0a6a45c8 578 std::string& deviceName;
37a919d4 579 boost::optional<int>& rcode;
70fb28d9
RG
580 uint32_t& ttlCap;
581 bool& variable;
f1c7929a 582 bool& logQuery;
406b722e 583 bool& logResponse;
37a919d4 584 bool& followCNAMERecords;
70fb28d9
RG
585
586 unsigned int tag{0};
587 uint16_t qtype;
588 bool tcp;
589};
590
406b722e 591unsigned int RecursorLua4::gettag_ffi(const ComboAddress& remote, const Netmask& ednssubnet, const ComboAddress& local, const DNSName& qname, uint16_t qtype, std::vector<std::string>* policyTags, std::vector<DNSRecord>& records, LuaContext::LuaObject& data, const EDNSOptionViewMap& ednsOptions, bool tcp, std::string& requestorId, std::string& deviceId, std::string& deviceName, boost::optional<int>& rcode, uint32_t& ttlCap, bool& variable, bool& logQuery, bool& logResponse, bool& followCNAMERecords) const
70fb28d9
RG
592{
593 if (d_gettag_ffi) {
406b722e 594 pdns_ffi_param_t param(qname, qtype, local, remote, ednssubnet, *policyTags, records, ednsOptions, requestorId, deviceId, deviceName, rcode, ttlCap, variable, tcp, logQuery, logResponse, followCNAMERecords);
70fb28d9
RG
595
596 auto ret = d_gettag_ffi(&param);
597 if (ret) {
598 data = *ret;
599 }
600
601 return param.tag;
602 }
603 return 0;
604}
605
5899ee54 606bool RecursorLua4::genhook(const luacall_t& func, DNSQuestion& dq, int& ret) const
a3e7b735 607{
608 if(!func)
808c5ef7 609 return false;
a3e7b735 610
6e505c5e
RG
611 if (dq.currentRecords) {
612 dq.records = *dq.currentRecords;
ba21fcfe 613 } else {
6e505c5e 614 dq.records.clear();
ba21fcfe
RG
615 }
616
6e505c5e
RG
617 dq.followupFunction.clear();
618 dq.followupPrefix.clear();
619 dq.followupName.clear();
620 dq.udpQuery.clear();
621 dq.udpAnswer.clear();
622 dq.udpCallback.clear();
ba21fcfe 623
6e505c5e 624 dq.rcode = ret;
1c567515 625 bool handled=func(&dq);
2205c52b 626
a3e7b735 627 if(handled) {
f9e5e573 628loop:;
6e505c5e 629 ret=dq.rcode;
d2f97f2a 630
6e505c5e
RG
631 if(!dq.followupFunction.empty()) {
632 if(dq.followupFunction=="followCNAMERecords") {
633 ret = followCNAMERecords(dq.records, QType(dq.qtype));
a3e7b735 634 }
6e505c5e
RG
635 else if(dq.followupFunction=="getFakeAAAARecords") {
636 ret=getFakeAAAARecords(dq.followupName, dq.followupPrefix, dq.records);
a3e7b735 637 }
6e505c5e
RG
638 else if(dq.followupFunction=="getFakePTRRecords") {
639 ret=getFakePTRRecords(dq.followupName, dq.followupPrefix, dq.records);
a3e7b735 640 }
6e505c5e
RG
641 else if(dq.followupFunction=="udpQueryResponse") {
642 dq.udpAnswer = GenUDPQueryResponse(dq.udpQueryDest, dq.udpQuery);
dd079764
RG
643 auto cbFunc = d_lw->readVariable<boost::optional<luacall_t>>(dq.udpCallback).get_value_or(0);
644 if(!cbFunc) {
e6a9dde5 645 g_log<<Logger::Error<<"Attempted callback for Lua UDP Query/Response which could not be found"<<endl;
6b8b26c8 646 return false;
d2f97f2a 647 }
dd079764 648 bool result=cbFunc(&dq);
ba21fcfe 649 if(!result) {
d2f97f2a 650 return false;
651 }
652 goto loop;
f90c7544 653 }
a3e7b735 654 }
6e505c5e
RG
655 if (dq.currentRecords) {
656 *dq.currentRecords = dq.records;
ba21fcfe 657 }
a3e7b735 658 }
659
a3e7b735 660 // see if they added followup work for us too
661 return handled;
662}
3dcc3fde 663
3dcc3fde 664RecursorLua4::~RecursorLua4(){}
70fb28d9
RG
665
666const char* pdns_ffi_param_get_qname(pdns_ffi_param_t* ref)
667{
668 if (!ref->qnameStr) {
669 ref->qnameStr = std::unique_ptr<std::string>(new std::string(ref->qname.toStringNoDot()));
670 }
671
672 return ref->qnameStr->c_str();
673}
674
aedec560
RG
675void pdns_ffi_param_get_qname_raw(pdns_ffi_param_t* ref, const char** qname, size_t* qnameSize)
676{
677 const auto& storage = ref->qname.getStorage();
678 *qname = storage.data();
679 *qnameSize = storage.size();
680}
681
70fb28d9
RG
682uint16_t pdns_ffi_param_get_qtype(const pdns_ffi_param_t* ref)
683{
684 return ref->qtype;
685}
686
687const char* pdns_ffi_param_get_remote(pdns_ffi_param_t* ref)
688{
689 if (!ref->remoteStr) {
690 ref->remoteStr = std::unique_ptr<std::string>(new std::string(ref->remote.toString()));
691 }
692
693 return ref->remoteStr->c_str();
694}
695
aedec560
RG
696static void pdns_ffi_comboaddress_to_raw(const ComboAddress& ca, const void** addr, size_t* addrSize)
697{
698 if (ca.isIPv4()) {
699 *addr = &ca.sin4.sin_addr.s_addr;
700 *addrSize = sizeof(ca.sin4.sin_addr.s_addr);
701 }
702 else {
703 *addr = &ca.sin6.sin6_addr.s6_addr;
704 *addrSize = sizeof(ca.sin6.sin6_addr.s6_addr);
705 }
706}
707
708void pdns_ffi_param_get_remote_raw(pdns_ffi_param_t* ref, const void** addr, size_t* addrSize)
709{
710 pdns_ffi_comboaddress_to_raw(ref->remote, addr, addrSize);
711}
712
70fb28d9
RG
713uint16_t pdns_ffi_param_get_remote_port(const pdns_ffi_param_t* ref)
714{
715 return ref->remote.getPort();
716}
717
718const char* pdns_ffi_param_get_local(pdns_ffi_param_t* ref)
719{
720 if (!ref->localStr) {
721 ref->localStr = std::unique_ptr<std::string>(new std::string(ref->local.toString()));
722 }
723
724 return ref->localStr->c_str();
725}
726
aedec560
RG
727void pdns_ffi_param_get_local_raw(pdns_ffi_param_t* ref, const void** addr, size_t* addrSize)
728{
729 pdns_ffi_comboaddress_to_raw(ref->local, addr, addrSize);
730}
731
70fb28d9
RG
732uint16_t pdns_ffi_param_get_local_port(const pdns_ffi_param_t* ref)
733{
734 return ref->local.getPort();
735}
736
737const char* pdns_ffi_param_get_edns_cs(pdns_ffi_param_t* ref)
738{
739 if (ref->ednssubnet.empty()) {
740 return nullptr;
741 }
742
743 if (!ref->ednssubnetStr) {
744 ref->ednssubnetStr = std::unique_ptr<std::string>(new std::string(ref->ednssubnet.toStringNoMask()));
745 }
746
747 return ref->ednssubnetStr->c_str();
748}
749
aedec560
RG
750void pdns_ffi_param_get_edns_cs_raw(pdns_ffi_param_t* ref, const void** net, size_t* netSize)
751{
752 if (ref->ednssubnet.empty()) {
753 *net = nullptr;
754 *netSize = 0;
755 return;
756 }
757
758 pdns_ffi_comboaddress_to_raw(ref->ednssubnet.getNetwork(), net, netSize);
759}
760
70fb28d9
RG
761uint8_t pdns_ffi_param_get_edns_cs_source_mask(const pdns_ffi_param_t* ref)
762{
763 return ref->ednssubnet.getBits();
764}
765
29e6303a 766static void fill_edns_option(const EDNSOptionViewValue& value, pdns_ednsoption_t& option)
70fb28d9 767{
29e6303a 768 option.len = value.size;
70fb28d9
RG
769 option.data = nullptr;
770
29e6303a
RG
771 if (value.size > 0) {
772 option.data = value.content;
70fb28d9
RG
773 }
774}
775
776size_t pdns_ffi_param_get_edns_options(pdns_ffi_param_t* ref, const pdns_ednsoption_t** out)
777{
778 if (ref->ednsOptions.empty()) {
779 return 0;
780 }
781
29e6303a
RG
782 size_t totalCount = 0;
783 for (const auto& option : ref->ednsOptions) {
784 totalCount += option.second.values.size();
785 }
786
787 ref->ednsOptionsVect.resize(totalCount);
70fb28d9
RG
788
789 size_t pos = 0;
29e6303a
RG
790 for (const auto& option : ref->ednsOptions) {
791 for (const auto& entry : option.second.values) {
792 fill_edns_option(entry, ref->ednsOptionsVect.at(pos));
793 ref->ednsOptionsVect.at(pos).optionCode = option.first;
794 pos++;
795 }
70fb28d9
RG
796 }
797
798 *out = ref->ednsOptionsVect.data();
799
29e6303a 800 return totalCount;
70fb28d9
RG
801}
802
803size_t pdns_ffi_param_get_edns_options_by_code(pdns_ffi_param_t* ref, uint16_t optionCode, const pdns_ednsoption_t** out)
804{
805 const auto& it = ref->ednsOptions.find(optionCode);
29e6303a 806 if (it == ref->ednsOptions.cend() || it->second.values.empty()) {
70fb28d9
RG
807 return 0;
808 }
809
29e6303a
RG
810 ref->ednsOptionsVect.resize(it->second.values.size());
811
812 size_t pos = 0;
813 for (const auto& entry : it->second.values) {
814 fill_edns_option(entry, ref->ednsOptionsVect.at(pos));
815 ref->ednsOptionsVect.at(pos).optionCode = optionCode;
816 pos++;
817 }
70fb28d9
RG
818
819 *out = ref->ednsOptionsVect.data();
820
29e6303a 821 return pos;
70fb28d9
RG
822}
823
824void pdns_ffi_param_set_tag(pdns_ffi_param_t* ref, unsigned int tag)
825{
826 ref->tag = tag;
827}
828
829void pdns_ffi_param_add_policytag(pdns_ffi_param_t *ref, const char* name)
830{
831 ref->policyTags.push_back(std::string(name));
832}
833
834void pdns_ffi_param_set_requestorid(pdns_ffi_param_t* ref, const char* name)
835{
836 ref->requestorId = std::string(name);
837}
838
839void pdns_ffi_param_set_devicename(pdns_ffi_param_t* ref, const char* name)
840{
0a6a45c8 841 ref->deviceName = std::string(name);
70fb28d9
RG
842}
843
844void pdns_ffi_param_set_deviceid(pdns_ffi_param_t* ref, size_t len, const void* name)
845{
846 ref->deviceId = std::string(reinterpret_cast<const char*>(name), len);
847}
848
849void pdns_ffi_param_set_variable(pdns_ffi_param_t* ref, bool variable)
850{
851 ref->variable = variable;
852}
853
854void pdns_ffi_param_set_ttl_cap(pdns_ffi_param_t* ref, uint32_t ttl)
855{
856 ref->ttlCap = ttl;
857}
f1c7929a
RG
858
859void pdns_ffi_param_set_log_query(pdns_ffi_param_t* ref, bool logQuery)
860{
861 ref->logQuery = logQuery;
862}
37a919d4 863
406b722e
RG
864void pdns_ffi_param_set_log_response(pdns_ffi_param_t* ref, bool logResponse)
865{
866 ref->logResponse = logResponse;
867}
868
37a919d4
RG
869void pdns_ffi_param_set_rcode(pdns_ffi_param_t* ref, int rcode)
870{
871 ref->rcode = rcode;
872}
873
874void pdns_ffi_param_set_follow_cname_records(pdns_ffi_param_t* ref, bool follow)
875{
876 ref->followCNAMERecords = follow;
877}
878
879bool pdns_ffi_param_add_record(pdns_ffi_param_t *ref, const char* name, uint16_t type, uint32_t ttl, const char* content, size_t contentSize, pdns_record_place_t place)
880{
881 try {
882 DNSRecord dr;
32aa5e9b 883 dr.d_name = name != nullptr ? DNSName(name) : ref->qname;
37a919d4
RG
884 dr.d_ttl = ttl;
885 dr.d_type = type;
886 dr.d_class = QClass::IN;
887 dr.d_place = DNSResourceRecord::Place(place);
888 dr.d_content = DNSRecordContent::mastermake(type, QClass::IN, std::string(content, contentSize));
889 ref->records.push_back(std::move(dr));
890
891 return true;
892 }
893 catch (const std::exception& e) {
894 g_log<<Logger::Error<<"Error attempting to add a record from Lua via pdns_ffi_param_add_record(): "<<e.what()<<endl;
895 return false;
896 }
897}