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