]> git.ipfire.org Git - thirdparty/pdns.git/blob - pdns/lua-recursor4.cc
Merge pull request #8352 from mnordhoff/chmod-chown-pdns.conf
[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 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
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
64 bool seenA = false;
65 for(DNSRecord& rr : ret)
66 {
67 if(rr.d_type == QType::A && rr.d_place==DNSResourceRecord::ANSWER) {
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 }
77 seenA = true;
78 }
79 }
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 }
92 return rcode;
93 }
94
95 static 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 +=
108 std::to_string(stoll(parts[n*2], 0, 16) + 16*stoll(parts[n*2+1], 0, 16));
109 newquery.append(1,'.');
110 }
111 newquery += "in-addr.arpa.";
112
113
114 DNSRecord rr;
115 rr.d_name = qname;
116 rr.d_type = QType::CNAME;
117 rr.d_content = std::make_shared<CNAMERecordContent>(newquery);
118 ret.push_back(rr);
119
120 int rcode = directResolve(DNSName(newquery), QType(QType::PTR), 1, ret);
121
122 return rcode;
123
124 }
125
126 boost::optional<dnsheader> RecursorLua4::DNSQuestion::getDH() const
127 {
128 if (dh)
129 return *dh;
130 return boost::optional<dnsheader>();
131 }
132
133 vector<string> RecursorLua4::DNSQuestion::getEDNSFlags() const
134 {
135 vector<string> ret;
136 if (ednsFlags) {
137 if (*ednsFlags & EDNSOpts::DNSSECOK)
138 ret.push_back("DO");
139 }
140 return ret;
141 }
142
143 bool RecursorLua4::DNSQuestion::getEDNSFlag(string flag) const
144 {
145 if (ednsFlags) {
146 if (flag == "DO" && (*ednsFlags & EDNSOpts::DNSSECOK))
147 return true;
148 }
149 return false;
150 }
151
152 vector<pair<uint16_t, string> > RecursorLua4::DNSQuestion::getEDNSOptions() const
153 {
154 if(ednsOptions)
155 return *ednsOptions;
156 else
157 return vector<pair<uint16_t,string>>();
158 }
159
160 boost::optional<string> RecursorLua4::DNSQuestion::getEDNSOption(uint16_t code) const
161 {
162 if(ednsOptions)
163 for(const auto& o : *ednsOptions)
164 if(o.first==code)
165 return o.second;
166
167 return boost::optional<string>();
168 }
169
170 boost::optional<Netmask> RecursorLua4::DNSQuestion::getEDNSSubnet() const
171 {
172 if(ednsOptions) {
173 for(const auto& o : *ednsOptions) {
174 if(o.first==EDNSOptionCode::ECS) {
175 EDNSSubnetOpts eso;
176 if(getEDNSSubnetOptsFromString(o.second, &eso))
177 return eso.source;
178 else
179 break;
180 }
181 }
182 }
183 return boost::optional<Netmask>();
184 }
185
186
187 vector<pair<int, DNSRecord> > RecursorLua4::DNSQuestion::getRecords() const
188 {
189 vector<pair<int, DNSRecord> > ret;
190 int num=1;
191 for(const auto& r : records) {
192 ret.push_back({num++, r});
193 }
194 return ret;
195 }
196 void RecursorLua4::DNSQuestion::setRecords(const vector<pair<int, DNSRecord> >& recs)
197 {
198 records.clear();
199 for(const auto& p : recs) {
200 records.push_back(p.second);
201 }
202 }
203
204 void RecursorLua4::DNSQuestion::addRecord(uint16_t type, const std::string& content, DNSResourceRecord::Place place, boost::optional<int> ttl, boost::optional<string> name)
205 {
206 DNSRecord dr;
207 dr.d_name=name ? DNSName(*name) : qname;
208 dr.d_ttl=ttl.get_value_or(3600);
209 dr.d_type = type;
210 dr.d_place = place;
211 dr.d_content = DNSRecordContent::mastermake(type, 1, content);
212 records.push_back(dr);
213 }
214
215 void RecursorLua4::DNSQuestion::addAnswer(uint16_t type, const std::string& content, boost::optional<int> ttl, boost::optional<string> name)
216 {
217 addRecord(type, content, DNSResourceRecord::ANSWER, ttl, name);
218 }
219
220 struct DynMetric
221 {
222 std::atomic<unsigned long>* ptr;
223 void inc() { (*ptr)++; }
224 void incBy(unsigned int by) { (*ptr)+= by; }
225 unsigned long get() { return *ptr; }
226 void set(unsigned long val) { *ptr =val; }
227 };
228
229 void RecursorLua4::postPrepareContext()
230 {
231 d_lw->registerMember<const DNSName (DNSQuestion::*)>("qname", [](const DNSQuestion& dq) -> const DNSName& { return dq.qname; }, [](DNSQuestion& dq, const DNSName& newName) { (void) newName; });
232 d_lw->registerMember<uint16_t (DNSQuestion::*)>("qtype", [](const DNSQuestion& dq) -> uint16_t { return dq.qtype; }, [](DNSQuestion& dq, uint16_t newType) { (void) newType; });
233 d_lw->registerMember<bool (DNSQuestion::*)>("isTcp", [](const DNSQuestion& dq) -> bool { return dq.isTcp; }, [](DNSQuestion& dq, bool newTcp) { (void) newTcp; });
234 d_lw->registerMember<const ComboAddress (DNSQuestion::*)>("localaddr", [](const DNSQuestion& dq) -> const ComboAddress& { return dq.local; }, [](DNSQuestion& dq, const ComboAddress& newLocal) { (void) newLocal; });
235 d_lw->registerMember<const ComboAddress (DNSQuestion::*)>("remoteaddr", [](const DNSQuestion& dq) -> const ComboAddress& { return dq.remote; }, [](DNSQuestion& dq, const ComboAddress& newRemote) { (void) newRemote; });
236 d_lw->registerMember<vState (DNSQuestion::*)>("validationState", [](const DNSQuestion& dq) -> vState { return dq.validationState; }, [](DNSQuestion& dq, vState newState) { (void) newState; });
237
238 d_lw->registerMember<bool (DNSQuestion::*)>("variable", [](const DNSQuestion& dq) -> bool { return dq.variable; }, [](DNSQuestion& dq, bool newVariable) { dq.variable = newVariable; });
239 d_lw->registerMember<bool (DNSQuestion::*)>("wantsRPZ", [](const DNSQuestion& dq) -> bool { return dq.wantsRPZ; }, [](DNSQuestion& dq, bool newWantsRPZ) { dq.wantsRPZ = newWantsRPZ; });
240 d_lw->registerMember<bool (DNSQuestion::*)>("logResponse", [](const DNSQuestion& dq) -> bool { return dq.logResponse; }, [](DNSQuestion& dq, bool newLogResponse) { dq.logResponse = newLogResponse; });
241
242 d_lw->registerMember("rcode", &DNSQuestion::rcode);
243 d_lw->registerMember("tag", &DNSQuestion::tag);
244 d_lw->registerMember("requestorId", &DNSQuestion::requestorId);
245 d_lw->registerMember("deviceId", &DNSQuestion::deviceId);
246 d_lw->registerMember("deviceName", &DNSQuestion::deviceName);
247 d_lw->registerMember("followupFunction", &DNSQuestion::followupFunction);
248 d_lw->registerMember("followupPrefix", &DNSQuestion::followupPrefix);
249 d_lw->registerMember("followupName", &DNSQuestion::followupName);
250 d_lw->registerMember("data", &DNSQuestion::data);
251 d_lw->registerMember("udpQuery", &DNSQuestion::udpQuery);
252 d_lw->registerMember("udpAnswer", &DNSQuestion::udpAnswer);
253 d_lw->registerMember("udpQueryDest", &DNSQuestion::udpQueryDest);
254 d_lw->registerMember("udpCallback", &DNSQuestion::udpCallback);
255 d_lw->registerMember("appliedPolicy", &DNSQuestion::appliedPolicy);
256 d_lw->registerMember<DNSFilterEngine::Policy, std::string>("policyName",
257 [](const DNSFilterEngine::Policy& pol) -> std::string {
258 if(pol.d_name)
259 return *pol.d_name;
260 return std::string();
261 },
262 [](DNSFilterEngine::Policy& pol, const std::string& name) {
263 pol.d_name = std::make_shared<std::string>(name);
264 });
265 d_lw->registerMember("policyKind", &DNSFilterEngine::Policy::d_kind);
266 d_lw->registerMember("policyTTL", &DNSFilterEngine::Policy::d_ttl);
267 d_lw->registerMember<DNSFilterEngine::Policy, std::string>("policyCustom",
268 [](const DNSFilterEngine::Policy& pol) -> std::string {
269 std::string result;
270 if (pol.d_kind != DNSFilterEngine::PolicyKind::Custom) {
271 return result;
272 }
273
274 for (const auto& dr : pol.d_custom) {
275 if (!result.empty()) {
276 result += "\n";
277 }
278 result += dr->getZoneRepresentation();
279 }
280
281 return result;
282 },
283 [](DNSFilterEngine::Policy& pol, const std::string& content) {
284 // Only CNAMES for now, when we ever add a d_custom_type, there will be pain
285 pol.d_custom.clear();
286 pol.d_custom.push_back(DNSRecordContent::mastermake(QType::CNAME, QClass::IN, content));
287 }
288 );
289 d_lw->registerFunction("getDH", &DNSQuestion::getDH);
290 d_lw->registerFunction("getEDNSOptions", &DNSQuestion::getEDNSOptions);
291 d_lw->registerFunction("getEDNSOption", &DNSQuestion::getEDNSOption);
292 d_lw->registerFunction("getEDNSSubnet", &DNSQuestion::getEDNSSubnet);
293 d_lw->registerFunction("getEDNSFlags", &DNSQuestion::getEDNSFlags);
294 d_lw->registerFunction("getEDNSFlag", &DNSQuestion::getEDNSFlag);
295 d_lw->registerMember("name", &DNSRecord::d_name);
296 d_lw->registerMember("type", &DNSRecord::d_type);
297 d_lw->registerMember("ttl", &DNSRecord::d_ttl);
298 d_lw->registerMember("place", &DNSRecord::d_place);
299
300 d_lw->registerMember("size", &EDNSOptionViewValue::size);
301 d_lw->registerFunction<std::string(EDNSOptionViewValue::*)()>("getContent", [](const EDNSOptionViewValue& value) { return std::string(value.content, value.size); });
302 d_lw->registerFunction<size_t(EDNSOptionView::*)()>("count", [](const EDNSOptionView& option) { return option.values.size(); });
303 d_lw->registerFunction<std::vector<string>(EDNSOptionView::*)()>("getValues", [] (const EDNSOptionView& option) {
304 std::vector<string> values;
305 for (const auto& value : option.values) {
306 values.push_back(std::string(value.content, value.size));
307 }
308 return values;
309 });
310
311 /* pre 4.2 API compatibility, when we had only one value for a given EDNS option */
312 d_lw->registerMember<uint16_t(EDNSOptionView::*)>("size", [](const EDNSOptionView& option) -> uint16_t {
313 uint16_t result = 0;
314
315 if (!option.values.empty()) {
316 result = option.values.at(0).size;
317 }
318 return result;
319 },
320 [](EDNSOptionView& option, uint16_t newSize) { (void) newSize; });
321 d_lw->registerFunction<std::string(EDNSOptionView::*)()>("getContent", [](const EDNSOptionView& option) {
322 if (option.values.empty()) {
323 return std::string();
324 }
325 return std::string(option.values.at(0).content, option.values.at(0).size); });
326
327 d_lw->registerFunction<string(DNSRecord::*)()>("getContent", [](const DNSRecord& dr) { return dr.d_content->getZoneRepresentation(); });
328 d_lw->registerFunction<boost::optional<ComboAddress>(DNSRecord::*)()>("getCA", [](const DNSRecord& dr) {
329 boost::optional<ComboAddress> ret;
330
331 if(auto rec = std::dynamic_pointer_cast<ARecordContent>(dr.d_content))
332 ret=rec->getCA(53);
333 else if(auto aaaarec = std::dynamic_pointer_cast<AAAARecordContent>(dr.d_content))
334 ret=aaaarec->getCA(53);
335 return ret;
336 });
337
338
339 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); });
340 d_lw->registerFunction("addAnswer", &DNSQuestion::addAnswer);
341 d_lw->registerFunction("addRecord", &DNSQuestion::addRecord);
342 d_lw->registerFunction("getRecords", &DNSQuestion::getRecords);
343 d_lw->registerFunction("setRecords", &DNSQuestion::setRecords);
344
345 d_lw->registerFunction<void(DNSQuestion::*)(const std::string&)>("addPolicyTag", [](DNSQuestion& dq, const std::string& tag) { if (dq.policyTags) { dq.policyTags->push_back(tag); } });
346 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) {
347 if (dq.policyTags) {
348 dq.policyTags->clear();
349 for (const auto& tag : tags) {
350 dq.policyTags->push_back(tag.second);
351 }
352 }
353 });
354 d_lw->registerFunction<std::vector<std::pair<int, std::string> >(DNSQuestion::*)()>("getPolicyTags", [](const DNSQuestion& dq) {
355 std::vector<std::pair<int, std::string> > ret;
356 if (dq.policyTags) {
357 int count = 1;
358 for (const auto& tag : *dq.policyTags) {
359 ret.push_back({count++, tag});
360 }
361 }
362 return ret;
363 });
364
365 d_lw->registerFunction<void(DNSQuestion::*)(const std::string&)>("discardPolicy", [](DNSQuestion& dq, const std::string& policy) {
366 if (dq.discardedPolicies) {
367 (*dq.discardedPolicies)[policy] = true;
368 }
369 });
370
371 d_lw->writeFunction("newDS", []() { return SuffixMatchNode(); });
372 d_lw->registerFunction<void(SuffixMatchNode::*)(boost::variant<string,DNSName, vector<pair<unsigned int,string> > >)>(
373 "add",
374 [](SuffixMatchNode&smn, const boost::variant<string,DNSName,vector<pair<unsigned int,string> > >& in){
375 try {
376 if(auto s = boost::get<string>(&in)) {
377 smn.add(DNSName(*s));
378 }
379 else if(auto v = boost::get<vector<pair<unsigned int, string> > >(&in)) {
380 for(const auto& entry : *v)
381 smn.add(DNSName(entry.second));
382 }
383 else {
384 smn.add(boost::get<DNSName>(in));
385 }
386 }
387 catch(std::exception& e) {
388 g_log <<Logger::Error<<e.what()<<endl;
389 }
390 }
391 );
392
393 d_lw->registerFunction("check",(bool (SuffixMatchNode::*)(const DNSName&) const) &SuffixMatchNode::check);
394 d_lw->registerFunction("toString",(string (SuffixMatchNode::*)() const) &SuffixMatchNode::toString);
395
396 d_pd.push_back({"policykinds", in_t {
397 {"NoAction", (int)DNSFilterEngine::PolicyKind::NoAction},
398 {"Drop", (int)DNSFilterEngine::PolicyKind::Drop },
399 {"NXDOMAIN", (int)DNSFilterEngine::PolicyKind::NXDOMAIN},
400 {"NODATA", (int)DNSFilterEngine::PolicyKind::NODATA },
401 {"Truncate", (int)DNSFilterEngine::PolicyKind::Truncate},
402 {"Custom", (int)DNSFilterEngine::PolicyKind::Custom }
403 }});
404
405 for(const auto& n : QType::names)
406 d_pd.push_back({n.first, n.second});
407
408 d_pd.push_back({"validationstates", in_t{
409 {"Indeterminate", Indeterminate },
410 {"Bogus", Bogus },
411 {"Insecure", Insecure },
412 {"Secure", Secure },
413 }});
414
415 d_pd.push_back({"now", &g_now});
416
417 d_lw->writeFunction("getMetric", [](const std::string& str) {
418 return DynMetric{getDynMetric(str)};
419 });
420
421 d_lw->registerFunction("inc", &DynMetric::inc);
422 d_lw->registerFunction("incBy", &DynMetric::incBy);
423 d_lw->registerFunction("set", &DynMetric::set);
424 d_lw->registerFunction("get", &DynMetric::get);
425
426 d_lw->writeFunction("getStat", [](const std::string& str) {
427 uint64_t result = 0;
428 optional<uint64_t> value = getStatByName(str);
429 if (value) {
430 result = *value;
431 }
432 return result;
433 });
434
435 d_lw->writeFunction("getRecursorThreadId", []() {
436 return getRecursorThreadId();
437 });
438
439 d_lw->writeFunction("sendCustomSNMPTrap", [](const std::string& str) {
440 if (g_snmpAgent) {
441 g_snmpAgent->sendCustomTrap(str);
442 }
443 });
444
445 d_lw->writeFunction("getregisteredname", [](const DNSName &dname) {
446 return getRegisteredName(dname);
447 });
448 }
449
450 void RecursorLua4::postLoad() {
451 d_prerpz = d_lw->readVariable<boost::optional<luacall_t>>("prerpz").get_value_or(0);
452 d_preresolve = d_lw->readVariable<boost::optional<luacall_t>>("preresolve").get_value_or(0);
453 d_nodata = d_lw->readVariable<boost::optional<luacall_t>>("nodata").get_value_or(0);
454 d_nxdomain = d_lw->readVariable<boost::optional<luacall_t>>("nxdomain").get_value_or(0);
455 d_postresolve = d_lw->readVariable<boost::optional<luacall_t>>("postresolve").get_value_or(0);
456 d_preoutquery = d_lw->readVariable<boost::optional<luacall_t>>("preoutquery").get_value_or(0);
457 d_maintenance = d_lw->readVariable<boost::optional<luamaintenance_t>>("maintenance").get_value_or(0);
458
459 d_ipfilter = d_lw->readVariable<boost::optional<ipfilter_t>>("ipfilter").get_value_or(0);
460 d_gettag = d_lw->readVariable<boost::optional<gettag_t>>("gettag").get_value_or(0);
461 d_gettag_ffi = d_lw->readVariable<boost::optional<gettag_ffi_t>>("gettag_ffi").get_value_or(0);
462 }
463
464 void RecursorLua4::getFeatures(Features & features) {
465 // Add key-values pairs below.
466 // Make sure you add string values explicity converted to string.
467 // e.g. features.push_back(make_pair("somekey", string("stringvalue"));
468 // Both int and double end up as a lua number type.
469 features.push_back(make_pair("PR8001_devicename", true));
470 }
471
472 void RecursorLua4::maintenance() const
473 {
474 if (d_maintenance) {
475 d_maintenance();
476 }
477 }
478
479 bool RecursorLua4::prerpz(DNSQuestion& dq, int& ret) const
480 {
481 return genhook(d_prerpz, dq, ret);
482 }
483
484 bool RecursorLua4::preresolve(DNSQuestion& dq, int& ret) const
485 {
486 return genhook(d_preresolve, dq, ret);
487 }
488
489 bool RecursorLua4::nxdomain(DNSQuestion& dq, int& ret) const
490 {
491 return genhook(d_nxdomain, dq, ret);
492 }
493
494 bool RecursorLua4::nodata(DNSQuestion& dq, int& ret) const
495 {
496 return genhook(d_nodata, dq, ret);
497 }
498
499 bool RecursorLua4::postresolve(DNSQuestion& dq, int& ret) const
500 {
501 return genhook(d_postresolve, dq, ret);
502 }
503
504 bool RecursorLua4::preoutquery(const ComboAddress& ns, const ComboAddress& requestor, const DNSName& query, const QType& qtype, bool isTcp, vector<DNSRecord>& res, int& ret) const
505 {
506 bool variableAnswer = false;
507 bool wantsRPZ = false;
508 bool logQuery = false;
509 RecursorLua4::DNSQuestion dq(ns, requestor, query, qtype.getCode(), isTcp, variableAnswer, wantsRPZ, logQuery);
510 dq.currentRecords = &res;
511
512 return genhook(d_preoutquery, dq, ret);
513 }
514
515 bool RecursorLua4::ipfilter(const ComboAddress& remote, const ComboAddress& local, const struct dnsheader& dh) const
516 {
517 if(d_ipfilter)
518 return d_ipfilter(remote, local, dh);
519 return false; // don't block
520 }
521
522 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, std::string& deviceName) const
523 {
524 if(d_gettag) {
525 auto ret = d_gettag(remote, ednssubnet, local, qname, qtype, ednsOptions, tcp);
526
527 if (policyTags) {
528 const auto& tags = std::get<1>(ret);
529 if (tags) {
530 for (const auto& tag : *tags) {
531 policyTags->push_back(tag.second);
532 }
533 }
534 }
535 const auto dataret = std::get<2>(ret);
536 if (dataret) {
537 data = *dataret;
538 }
539 const auto reqIdret = std::get<3>(ret);
540 if (reqIdret) {
541 requestorId = *reqIdret;
542 }
543 const auto deviceIdret = std::get<4>(ret);
544 if (deviceIdret) {
545 deviceId = *deviceIdret;
546 }
547
548 const auto deviceNameret = std::get<5>(ret);
549 if (deviceNameret) {
550 deviceName = *deviceNameret;
551 }
552 return std::get<0>(ret);
553 }
554 return 0;
555 }
556
557 struct pdns_ffi_param
558 {
559 public:
560 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_)
561 {
562 }
563
564 std::unique_ptr<std::string> qnameStr{nullptr};
565 std::unique_ptr<std::string> localStr{nullptr};
566 std::unique_ptr<std::string> remoteStr{nullptr};
567 std::unique_ptr<std::string> ednssubnetStr{nullptr};
568 std::vector<pdns_ednsoption_t> ednsOptionsVect;
569
570 const DNSName& qname;
571 const ComboAddress& local;
572 const ComboAddress& remote;
573 const Netmask& ednssubnet;
574 std::vector<std::string>& policyTags;
575 std::vector<DNSRecord>& records;
576 const EDNSOptionViewMap& ednsOptions;
577 std::string& requestorId;
578 std::string& deviceId;
579 std::string& deviceName;
580 boost::optional<int>& rcode;
581 uint32_t& ttlCap;
582 bool& variable;
583 bool& logQuery;
584 bool& logResponse;
585 bool& followCNAMERecords;
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, 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
593 {
594 if (d_gettag_ffi) {
595 pdns_ffi_param_t param(qname, qtype, local, remote, ednssubnet, *policyTags, records, ednsOptions, requestorId, deviceId, deviceName, rcode, ttlCap, variable, tcp, logQuery, logResponse, followCNAMERecords);
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->deviceName = 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 }
864
865 void pdns_ffi_param_set_log_response(pdns_ffi_param_t* ref, bool logResponse)
866 {
867 ref->logResponse = logResponse;
868 }
869
870 void pdns_ffi_param_set_rcode(pdns_ffi_param_t* ref, int rcode)
871 {
872 ref->rcode = rcode;
873 }
874
875 void pdns_ffi_param_set_follow_cname_records(pdns_ffi_param_t* ref, bool follow)
876 {
877 ref->followCNAMERecords = follow;
878 }
879
880 bool 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)
881 {
882 try {
883 DNSRecord dr;
884 dr.d_name = name != nullptr ? DNSName(name) : ref->qname;
885 dr.d_ttl = ttl;
886 dr.d_type = type;
887 dr.d_class = QClass::IN;
888 dr.d_place = DNSResourceRecord::Place(place);
889 dr.d_content = DNSRecordContent::mastermake(type, QClass::IN, std::string(content, contentSize));
890 ref->records.push_back(std::move(dr));
891
892 return true;
893 }
894 catch (const std::exception& e) {
895 g_log<<Logger::Error<<"Error attempting to add a record from Lua via pdns_ffi_param_add_record(): "<<e.what()<<endl;
896 return false;
897 }
898 }