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