Coverage Report

Created: 2026-11-20 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/pdns/pdns/dnsdistdist/dnsdist-lua-ffi.cc
Line
Count
Source
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
23
#include "dnsdist-async.hh"
24
#include "dnsdist-cache.hh"
25
#include "dnsdist-dnsparser.hh"
26
#include "dnsdist-dynblocks.hh"
27
#include "dnsdist-ebpf.hh"
28
#include "dnsdist-ecs.hh"
29
#include "dnsdist-lua-ffi.hh"
30
#include "dnsdist-edns.hh"
31
#include "dnsdist-mac-address.hh"
32
#include "dnsdist-metrics.hh"
33
#include "dnsdist-lua-network.hh"
34
#include "dnsdist-lua.hh"
35
#include "dnsdist-rings.hh"
36
#include "dnsdist-self-answers.hh"
37
#include "dnsdist-svc.hh"
38
#include "dnsdist-snmp.hh"
39
#include "dolog.hh"
40
#include "svc-records.hh"
41
42
static std::shared_ptr<const Logr::Logger> getLogger(const std::string_view fromFunction)
43
0
{
44
0
  return dnsdist::logging::getTopLogger("lua-ffi-script")->withValues("lua.ffi.function", Logging::Loggable(fromFunction));
45
0
}
46
47
uint16_t dnsdist_ffi_dnsquestion_get_qtype(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
48
0
{
49
0
  return dnsQuestion->dq->ids.qtype;
50
0
}
51
52
uint16_t dnsdist_ffi_dnsquestion_get_qclass(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
53
0
{
54
0
  return dnsQuestion->dq->ids.qclass;
55
0
}
56
57
uint16_t dnsdist_ffi_dnsquestion_get_id(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
58
0
{
59
0
  if (dnsQuestion == nullptr) {
60
0
    return 0;
61
0
  }
62
0
  try {
63
0
    return ntohs(dnsQuestion->dq->getHeader()->id);
64
0
  }
65
0
  catch (const std::exception& e) {
66
0
    VERBOSESLOG(infolog("Error getting ID from packet: %s", e.what()),
67
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error getting ID from packet"));
68
0
    return 0;
69
0
  }
70
0
}
71
72
static void dnsdist_ffi_comboaddress_to_raw(const ComboAddress& caAddr, const void** addr, size_t* addrSize)
73
0
{
74
0
  if (caAddr.isIPv4()) {
75
0
    *addr = &caAddr.sin4.sin_addr.s_addr;
76
0
    *addrSize = sizeof(caAddr.sin4.sin_addr.s_addr);
77
0
  }
78
0
  else {
79
0
    *addr = &caAddr.sin6.sin6_addr.s6_addr;
80
0
    *addrSize = sizeof(caAddr.sin6.sin6_addr.s6_addr);
81
0
  }
82
0
}
83
84
void dnsdist_ffi_dnsquestion_get_localaddr(const dnsdist_ffi_dnsquestion_t* dnsQuestion, const void** addr, size_t* addrSize)
85
0
{
86
0
  dnsdist_ffi_comboaddress_to_raw(dnsQuestion->dq->ids.origDest, addr, addrSize);
87
0
}
88
89
bool dnsdist_ffi_dnsquestion_is_remote_v6(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
90
0
{
91
0
  if (dnsQuestion == nullptr || dnsQuestion->dq == nullptr) {
92
0
    return false;
93
0
  }
94
95
0
  return dnsQuestion->dq->ids.origRemote.isIPv6();
96
0
}
97
98
void dnsdist_ffi_dnsquestion_get_remoteaddr(const dnsdist_ffi_dnsquestion_t* dnsQuestion, const void** addr, size_t* addrSize)
99
0
{
100
0
  dnsdist_ffi_comboaddress_to_raw(dnsQuestion->dq->ids.origRemote, addr, addrSize);
101
0
}
102
103
size_t dnsdist_ffi_dnsquestion_get_mac_addr(const dnsdist_ffi_dnsquestion_t* dnsQuestion, void* buffer, size_t bufferSize)
104
0
{
105
0
  if (dnsQuestion == nullptr) {
106
0
    return 0;
107
0
  }
108
109
0
  try {
110
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
111
0
    auto ret = dnsdist::MacAddressesCache::get(dnsQuestion->dq->ids.origRemote, reinterpret_cast<unsigned char*>(buffer), bufferSize);
112
0
    if (ret != 0) {
113
0
      return 0;
114
0
    }
115
116
0
    return 6;
117
0
  }
118
0
  catch (const std::exception& e) {
119
0
    VERBOSESLOG(infolog("Error getting MAC address: %s", e.what()),
120
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error getting MAC address"));
121
0
    return 0;
122
0
  }
123
0
}
124
125
uint64_t dnsdist_ffi_dnsquestion_get_elapsed_us(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
126
0
{
127
0
  if (dnsQuestion == nullptr) {
128
0
    return 0;
129
0
  }
130
131
0
  return static_cast<uint64_t>(std::round(dnsQuestion->dq->ids.queryRealTime.udiff()));
132
0
}
133
134
static bool checkDNSQuestionType(const char* functionName, const dnsdist_ffi_dnsquestion_t* dnsQuestion)
135
0
{
136
0
  if (dnsQuestion->objectType != dnsdist::lua::ffi::ObjectType::Question) {
137
0
    VERBOSESLOG(infolog("Error: calling FFI function %s with a wrong type", functionName),
138
0
                getLogger(functionName)->info(Logr::Info, "Error: calling FFI function with a wrong type"));
139
0
    return false;
140
0
  }
141
0
  return true;
142
0
}
143
144
static bool checkDNSResponseType(const char* functionName, const dnsdist_ffi_dnsresponse_t* dnsResponse)
145
0
{
146
0
  if (dnsResponse->objectType != dnsdist::lua::ffi::ObjectType::Response) {
147
0
    VERBOSESLOG(infolog("Error: calling FFI function %s with a wrong type", functionName),
148
0
                getLogger(functionName)->info(Logr::Info, "Error: calling FFI function with a wrong type"));
149
0
    return false;
150
0
  }
151
0
  return true;
152
0
}
153
154
void dnsdist_ffi_dnsquestion_get_masked_remoteaddr(dnsdist_ffi_dnsquestion_t* dnsQuestion, const void** addr, size_t* addrSize, uint8_t bits)
155
0
{
156
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
157
0
  if (!checkDNSQuestionType(__func__, dnsQuestion)) {
158
0
    return;
159
0
  }
160
161
0
  dnsQuestion->maskedRemote = Netmask(dnsQuestion->dq->ids.origRemote, bits).getMaskedNetwork();
162
0
  dnsdist_ffi_comboaddress_to_raw(dnsQuestion->maskedRemote, addr, addrSize);
163
0
}
164
165
uint16_t dnsdist_ffi_dnsquestion_get_local_port(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
166
0
{
167
0
  return dnsQuestion->dq->ids.origDest.getPort();
168
0
}
169
170
uint16_t dnsdist_ffi_dnsquestion_get_remote_port(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
171
0
{
172
0
  return dnsQuestion->dq->ids.origRemote.getPort();
173
0
}
174
175
const char* dnsdist_ffi_dnsquestion_get_incoming_interface(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
176
0
{
177
0
  if (dnsQuestion == nullptr || dnsQuestion->dq == nullptr || dnsQuestion->dq->ids.cs == nullptr) {
178
0
    return nullptr;
179
0
  }
180
0
  return dnsQuestion->dq->ids.cs->interface.c_str();
181
0
}
182
183
void dnsdist_ffi_dnsquestion_get_qname_raw(const dnsdist_ffi_dnsquestion_t* dnsQuestion, const char** qname, size_t* qnameSize)
184
0
{
185
0
  const auto& storage = dnsQuestion->dq->ids.qname.getStorage();
186
0
  *qname = storage.data();
187
0
  *qnameSize = storage.size();
188
0
}
189
190
size_t dnsdist_ffi_dnsquestion_get_qname_hash(const dnsdist_ffi_dnsquestion_t* dnsQuestion, size_t init)
191
0
{
192
0
  return dnsQuestion->dq->ids.qname.hash(init);
193
0
}
194
195
int dnsdist_ffi_dnsquestion_get_rcode(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
196
0
{
197
0
  try {
198
0
    return dnsQuestion->dq->getHeader()->rcode;
199
0
  }
200
0
  catch (const std::exception& e) {
201
0
    VERBOSESLOG(infolog("Error getting rcode from packet: %s", e.what()),
202
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error getting rcode from packet"));
203
0
    return 0;
204
0
  }
205
0
}
206
207
const unsigned char* dnsdist_ffi_dnsquestion_get_data(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
208
0
{
209
0
  return dnsQuestion->dq->getData().data();
210
0
}
211
212
bool dnsdist_ffi_dnsquestion_get_header_copy(const dnsdist_ffi_dnsquestion_t* dnsQuestion, char* buffer, size_t buffer_size)
213
0
{
214
0
  if (dnsQuestion == nullptr || dnsQuestion->dq == nullptr || buffer == nullptr || buffer_size < sizeof(dnsheader)) {
215
0
    return false;
216
0
  }
217
218
0
  try {
219
0
    const auto aligned = dnsQuestion->dq->getHeader();
220
0
    memcpy(buffer, aligned.get(), sizeof(dnsheader));
221
0
    return true;
222
0
  }
223
0
  catch (const std::exception& e) {
224
0
    VERBOSESLOG(infolog("Error getting header from packet: %s", e.what()),
225
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error getting header from packet"));
226
0
    return false;
227
0
  }
228
0
}
229
230
bool dnsdist_ffi_dnsquestion_set_header(const dnsdist_ffi_dnsquestion_t* dnsQuestion, const char* buffer)
231
0
{
232
0
  if (dnsQuestion == nullptr || dnsQuestion->dq == nullptr || buffer == nullptr) {
233
0
    return false;
234
0
  }
235
236
0
  try {
237
0
    dnsQuestion->dq->editHeader([&buffer](dnsheader& header) -> bool {
238
0
      memcpy(&header, buffer, sizeof(dnsheader));
239
0
      return true;
240
0
    });
241
0
    return true;
242
0
  }
243
0
  catch (const std::exception& e) {
244
0
    VERBOSESLOG(infolog("Error setting header in packet: %s", e.what()),
245
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error setting header in packet"));
246
0
    return false;
247
0
  }
248
0
}
249
250
uint16_t dnsdist_ffi_dnsquestion_get_len(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
251
0
{
252
0
  return dnsQuestion->dq->getData().size();
253
0
}
254
255
size_t dnsdist_ffi_dnsquestion_get_size(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
256
0
{
257
0
  return dnsQuestion->dq->getData().size();
258
0
}
259
260
bool dnsdist_ffi_dnsquestion_set_size(dnsdist_ffi_dnsquestion_t* dnsQuestion, size_t newSize)
261
0
{
262
0
  try {
263
0
    if (newSize > std::numeric_limits<uint16_t>::max()) {
264
0
      return false;
265
0
    }
266
0
    dnsQuestion->dq->getMutableData().resize(newSize);
267
0
    return true;
268
0
  }
269
0
  catch (const std::exception& e) {
270
0
    VERBOSESLOG(infolog("Error setting packet size to %d: %s", newSize, e.what()),
271
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error setting header in packet", "size", Logging::Loggable(newSize)));
272
0
    return false;
273
0
  }
274
0
}
275
276
uint8_t dnsdist_ffi_dnsquestion_get_opcode(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
277
0
{
278
0
  try {
279
0
    return dnsQuestion->dq->getHeader()->opcode;
280
0
  }
281
0
  catch (const std::exception& e) {
282
0
    VERBOSESLOG(infolog("Error getting opcode from packet: %s", e.what()),
283
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error setting opcode from packet"));
284
0
    return 0;
285
0
  }
286
0
}
287
288
bool dnsdist_ffi_dnsquestion_get_tcp(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
289
0
{
290
0
  return dnsQuestion->dq->overTCP();
291
0
}
292
293
dnsdist_ffi_protocol_type dnsdist_ffi_dnsquestion_get_protocol(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
294
0
{
295
0
  if (dnsQuestion != nullptr) {
296
0
    auto proto = dnsQuestion->dq->getProtocol();
297
0
    if (proto == dnsdist::Protocol::DoUDP) {
298
0
      return dnsdist_ffi_protocol_type_doudp;
299
0
    }
300
0
    if (proto == dnsdist::Protocol::DoTCP) {
301
0
      return dnsdist_ffi_protocol_type_dotcp;
302
0
    }
303
0
    if (proto == dnsdist::Protocol::DNSCryptUDP) {
304
0
      return dnsdist_ffi_protocol_type_dnscryptudp;
305
0
    }
306
0
    if (proto == dnsdist::Protocol::DNSCryptTCP) {
307
0
      return dnsdist_ffi_protocol_type_dnscrypttcp;
308
0
    }
309
0
    if (proto == dnsdist::Protocol::DoT) {
310
0
      return dnsdist_ffi_protocol_type_dot;
311
0
    }
312
0
    if (proto == dnsdist::Protocol::DoH) {
313
0
      return dnsdist_ffi_protocol_type_doh;
314
0
    }
315
0
  }
316
0
  return dnsdist_ffi_protocol_type_doudp;
317
0
}
318
319
bool dnsdist_ffi_dnsquestion_get_skip_cache(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
320
0
{
321
0
  return dnsQuestion->dq->ids.skipCache;
322
0
}
323
324
bool dnsdist_ffi_dnsquestion_get_use_ecs(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
325
0
{
326
0
  return dnsQuestion->dq->useECS;
327
0
}
328
329
bool dnsdist_ffi_dnsquestion_get_ecs_override(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
330
0
{
331
0
  return dnsQuestion->dq->ecsOverride;
332
0
}
333
334
uint16_t dnsdist_ffi_dnsquestion_get_ecs_prefix_length(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
335
0
{
336
0
  return dnsQuestion->dq->ecsPrefixLength;
337
0
}
338
339
bool dnsdist_ffi_dnsquestion_is_temp_failure_ttl_set(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
340
0
{
341
0
  return dnsQuestion->dq->ids.tempFailureTTL != std::nullopt;
342
0
}
343
344
uint32_t dnsdist_ffi_dnsquestion_get_temp_failure_ttl(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
345
0
{
346
0
  if (dnsQuestion->dq->ids.tempFailureTTL) {
347
0
    return *dnsQuestion->dq->ids.tempFailureTTL;
348
0
  }
349
0
  return 0;
350
0
}
351
352
bool dnsdist_ffi_dnsquestion_get_do(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
353
0
{
354
0
  try {
355
0
    return (dnsdist::getEDNSZ(*dnsQuestion->dq) & EDNS_HEADER_FLAG_DO) != 0;
356
0
  }
357
0
  catch (const std::exception& e) {
358
0
    VERBOSESLOG(infolog("Error getting DNSSEC OK from packet: %s", e.what()),
359
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error setting DNSSEC OK from packet"));
360
0
    return false;
361
0
  }
362
0
}
363
364
uint8_t dnsdist_ffi_dnsquestion_get_edns_version(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
365
0
{
366
0
  auto version = dnsdist::getEDNSVersion(*dnsQuestion->dq);
367
0
  return version ? *version : 0U;
368
0
}
369
370
uint8_t dnsdist_ffi_dnsquestion_get_edns_extended_rcode(const dnsdist_ffi_dnsquestion_t* dnsQuestion)
371
0
{
372
0
  auto rcode = dnsdist::getEDNSExtendedRCode(*dnsQuestion->dq);
373
0
  return rcode ? *rcode : 0U;
374
0
}
375
376
void dnsdist_ffi_dnsquestion_get_sni(const dnsdist_ffi_dnsquestion_t* dnsQuestion, const char** sni, size_t* sniSize)
377
0
{
378
0
  *sniSize = dnsQuestion->dq->sni.size();
379
0
  *sni = dnsQuestion->dq->sni.c_str();
380
0
}
381
382
const char* dnsdist_ffi_dnsquestion_get_tag(const dnsdist_ffi_dnsquestion_t* dnsQuestion, const char* label)
383
0
{
384
0
  const char* result = nullptr;
385
386
0
  if (dnsQuestion != nullptr && dnsQuestion->dq != nullptr && dnsQuestion->dq->ids.qTag != nullptr) {
387
0
    const auto tagIt = dnsQuestion->dq->ids.qTag->find(label);
388
0
    if (tagIt != dnsQuestion->dq->ids.qTag->cend()) {
389
0
      result = tagIt->second.c_str();
390
0
    }
391
0
  }
392
393
0
  return result;
394
0
}
395
396
size_t dnsdist_ffi_dnsquestion_get_tag_raw(const dnsdist_ffi_dnsquestion_t* dnsQuestion, const char* label, char* buffer, size_t bufferSize)
397
0
{
398
0
  if (dnsQuestion == nullptr || dnsQuestion->dq == nullptr || dnsQuestion->dq->ids.qTag == nullptr || label == nullptr || buffer == nullptr || bufferSize == 0) {
399
0
    return 0;
400
0
  }
401
402
0
  const auto tagIt = dnsQuestion->dq->ids.qTag->find(label);
403
0
  if (tagIt == dnsQuestion->dq->ids.qTag->cend()) {
404
0
    return 0;
405
0
  }
406
407
0
  if (tagIt->second.size() > bufferSize) {
408
0
    return 0;
409
0
  }
410
411
0
  memcpy(buffer, tagIt->second.c_str(), tagIt->second.size());
412
0
  return tagIt->second.size();
413
0
}
414
415
const char* dnsdist_ffi_dnsquestion_get_http_path(dnsdist_ffi_dnsquestion_t* dnsQuestion)
416
0
{
417
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
418
0
  if (!checkDNSQuestionType(__func__, dnsQuestion)) {
419
0
    return nullptr;
420
0
  }
421
422
0
  if (!dnsQuestion->httpPath) {
423
0
    if (dnsQuestion->dq->ids.du) {
424
#if defined(HAVE_DNS_OVER_HTTPS)
425
      dnsQuestion->httpPath = dnsQuestion->dq->ids.du->getHTTPPath();
426
#endif /* HAVE_DNS_OVER_HTTPS */
427
0
    }
428
0
    else if (dnsQuestion->dq->ids.doh3u) {
429
#if defined(HAVE_DNS_OVER_HTTP3)
430
      dnsQuestion->httpPath = dnsQuestion->dq->ids.doh3u->getHTTPPath();
431
#endif /* HAVE_DNS_OVER_HTTP3 */
432
0
    }
433
0
  }
434
0
  if (dnsQuestion->httpPath) {
435
0
    return dnsQuestion->httpPath->c_str();
436
0
  }
437
0
  return nullptr;
438
0
}
439
440
const char* dnsdist_ffi_dnsquestion_get_http_query_string(dnsdist_ffi_dnsquestion_t* dnsQuestion)
441
0
{
442
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
443
0
  if (!checkDNSQuestionType(__func__, dnsQuestion)) {
444
0
    return nullptr;
445
0
  }
446
447
0
  if (!dnsQuestion->httpQueryString) {
448
0
    if (dnsQuestion->dq->ids.du) {
449
#ifdef HAVE_DNS_OVER_HTTPS
450
      dnsQuestion->httpQueryString = dnsQuestion->dq->ids.du->getHTTPQueryString();
451
#endif /* HAVE_DNS_OVER_HTTPS */
452
0
    }
453
0
    else if (dnsQuestion->dq->ids.doh3u) {
454
#if defined(HAVE_DNS_OVER_HTTP3)
455
      dnsQuestion->httpQueryString = dnsQuestion->dq->ids.doh3u->getHTTPQueryString();
456
#endif /* HAVE_DNS_OVER_HTTP3 */
457
0
    }
458
0
  }
459
0
  if (dnsQuestion->httpQueryString) {
460
0
    return dnsQuestion->httpQueryString->c_str();
461
0
  }
462
0
  return nullptr;
463
0
}
464
465
const char* dnsdist_ffi_dnsquestion_get_http_host(dnsdist_ffi_dnsquestion_t* dnsQuestion)
466
0
{
467
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
468
0
  if (!checkDNSQuestionType(__func__, dnsQuestion)) {
469
0
    return nullptr;
470
0
  }
471
472
0
  if (!dnsQuestion->httpHost) {
473
0
    if (dnsQuestion->dq->ids.du) {
474
#ifdef HAVE_DNS_OVER_HTTPS
475
      dnsQuestion->httpHost = dnsQuestion->dq->ids.du->getHTTPHost();
476
#endif /* HAVE_DNS_OVER_HTTPS */
477
0
    }
478
0
    else if (dnsQuestion->dq->ids.doh3u) {
479
#if defined(HAVE_DNS_OVER_HTTP3)
480
      dnsQuestion->httpHost = dnsQuestion->dq->ids.doh3u->getHTTPHost();
481
#endif /* HAVE_DNS_OVER_HTTP3 */
482
0
    }
483
0
  }
484
0
  if (dnsQuestion->httpHost) {
485
0
    return dnsQuestion->httpHost->c_str();
486
0
  }
487
0
  return nullptr;
488
0
}
489
490
const char* dnsdist_ffi_dnsquestion_get_http_scheme(dnsdist_ffi_dnsquestion_t* dnsQuestion)
491
0
{
492
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
493
0
  if (!checkDNSQuestionType(__func__, dnsQuestion)) {
494
0
    return nullptr;
495
0
  }
496
497
0
  if (!dnsQuestion->httpScheme) {
498
0
    if (dnsQuestion->dq->ids.du) {
499
#ifdef HAVE_DNS_OVER_HTTPS
500
      dnsQuestion->httpScheme = dnsQuestion->dq->ids.du->getHTTPScheme();
501
#endif /* HAVE_DNS_OVER_HTTPS */
502
0
    }
503
0
    else if (dnsQuestion->dq->ids.doh3u) {
504
#if defined(HAVE_DNS_OVER_HTTP3)
505
      dnsQuestion->httpScheme = dnsQuestion->dq->ids.doh3u->getHTTPScheme();
506
#endif /* HAVE_DNS_OVER_HTTP3 */
507
0
    }
508
0
  }
509
0
  if (dnsQuestion->httpScheme) {
510
0
    return dnsQuestion->httpScheme->c_str();
511
0
  }
512
0
  return nullptr;
513
0
}
514
515
static void fill_edns_option(const EDNSOptionViewValue& value, dnsdist_ffi_ednsoption_t& option)
516
0
{
517
0
  option.len = value.size;
518
0
  option.data = nullptr;
519
520
0
  if (value.size > 0) {
521
0
    option.data = value.content;
522
0
  }
523
0
}
524
525
// returns the length of the resulting 'out' array. 'out' is not set if the length is 0
526
size_t dnsdist_ffi_dnsquestion_get_edns_options(dnsdist_ffi_dnsquestion_t* dnsQuestion, const dnsdist_ffi_ednsoption_t** out)
527
0
{
528
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
529
0
  if (!checkDNSQuestionType(__func__, dnsQuestion)) {
530
0
    return 0U;
531
0
  }
532
533
0
  try {
534
0
    auto ednsOptions = parseEDNSOptions(*(dnsQuestion->dq));
535
0
    if (!ednsOptions) {
536
0
      return 0;
537
0
    }
538
539
0
    size_t totalCount = 0;
540
0
    for (const auto& option : *ednsOptions) {
541
0
      totalCount += option.second.values.size();
542
0
    }
543
544
0
    if (!dnsQuestion->ednsOptionsVect) {
545
0
      dnsQuestion->ednsOptionsVect = std::make_unique<std::vector<dnsdist_ffi_ednsoption_t>>();
546
0
    }
547
0
    dnsQuestion->ednsOptionsVect->clear();
548
0
    dnsQuestion->ednsOptionsVect->resize(totalCount);
549
0
    size_t pos = 0;
550
0
    for (const auto& option : *ednsOptions) {
551
0
      for (const auto& entry : option.second.values) {
552
0
        fill_edns_option(entry, dnsQuestion->ednsOptionsVect->at(pos));
553
0
        dnsQuestion->ednsOptionsVect->at(pos).optionCode = option.first;
554
0
        pos++;
555
0
      }
556
0
    }
557
558
0
    if (totalCount > 0) {
559
0
      *out = dnsQuestion->ednsOptionsVect->data();
560
0
    }
561
562
0
    return totalCount;
563
0
  }
564
0
  catch (const std::exception& e) {
565
0
    VERBOSESLOG(infolog("Error getting EDNS options from packet: %s", e.what()),
566
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error getting EDNS options from packet"));
567
0
    return 0U;
568
0
  }
569
0
  catch (...) {
570
0
    return 0U;
571
0
  }
572
0
}
573
574
size_t dnsdist_ffi_dnsquestion_get_http_headers([[maybe_unused]] dnsdist_ffi_dnsquestion_t* dnsQuestion, [[maybe_unused]] const dnsdist_ffi_http_header_t** out)
575
0
{
576
#if defined(HAVE_DNS_OVER_HTTPS) || defined(HAVE_DNS_OVER_HTTP3)
577
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
578
  if (!checkDNSQuestionType(__func__, dnsQuestion)) {
579
    return 0U;
580
  }
581
582
  try {
583
    const auto processHeaders = [&dnsQuestion](const std::unordered_map<std::string, std::string>& headers) {
584
      if (headers.empty()) {
585
        return;
586
      }
587
      dnsQuestion->httpHeaders = std::make_unique<std::unordered_map<std::string, std::string>>(headers);
588
      if (!dnsQuestion->httpHeadersVect) {
589
        dnsQuestion->httpHeadersVect = std::make_unique<std::vector<dnsdist_ffi_http_header_t>>();
590
      }
591
      dnsQuestion->httpHeadersVect->clear();
592
      dnsQuestion->httpHeadersVect->resize(dnsQuestion->httpHeaders->size());
593
      size_t pos = 0;
594
      for (const auto& header : *dnsQuestion->httpHeaders) {
595
        dnsQuestion->httpHeadersVect->at(pos).name = header.first.c_str();
596
        dnsQuestion->httpHeadersVect->at(pos).value = header.second.c_str();
597
        ++pos;
598
      }
599
    };
600
601
#if defined(HAVE_DNS_OVER_HTTPS)
602
    if (dnsQuestion->dq->ids.du) {
603
      const auto& headers = dnsQuestion->dq->ids.du->getHTTPHeaders();
604
      processHeaders(headers);
605
    }
606
#endif /* HAVE_DNS_OVER_HTTPS */
607
#if defined(HAVE_DNS_OVER_HTTP3)
608
    if (dnsQuestion->dq->ids.doh3u) {
609
      const auto& headers = dnsQuestion->dq->ids.doh3u->getHTTPHeaders();
610
      processHeaders(headers);
611
    }
612
#endif /* HAVE_DNS_OVER_HTTP3 */
613
614
    if (!dnsQuestion->httpHeadersVect) {
615
      return 0U;
616
    }
617
618
    if (!dnsQuestion->httpHeadersVect->empty()) {
619
      *out = dnsQuestion->httpHeadersVect->data();
620
    }
621
    return dnsQuestion->httpHeadersVect->size();
622
  }
623
  catch (...) {
624
    return 0U;
625
  }
626
#else /* HAVE_DNS_OVER_HTTPS || HAVE_DNS_OVER_HTTP3 */
627
0
  return 0U;
628
0
#endif /* HAVE_DNS_OVER_HTTPS || HAVE_DNS_OVER_HTTP3 */
629
0
}
630
631
size_t dnsdist_ffi_dnsquestion_get_tag_array(dnsdist_ffi_dnsquestion_t* dnsQuestion, const dnsdist_ffi_tag_t** out)
632
0
{
633
0
  if (dnsQuestion == nullptr || dnsQuestion->dq == nullptr || dnsQuestion->dq->ids.qTag == nullptr || dnsQuestion->dq->ids.qTag->empty()) {
634
0
    return 0;
635
0
  }
636
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
637
0
  if (!checkDNSQuestionType(__func__, dnsQuestion)) {
638
0
    return 0U;
639
0
  }
640
641
0
  if (!dnsQuestion->tagsVect) {
642
0
    dnsQuestion->tagsVect = std::make_unique<std::vector<dnsdist_ffi_tag_t>>();
643
0
  }
644
0
  dnsQuestion->tagsVect->clear();
645
0
  dnsQuestion->tagsVect->resize(dnsQuestion->dq->ids.qTag->size());
646
0
  size_t pos = 0;
647
648
0
  for (const auto& tag : *dnsQuestion->dq->ids.qTag) {
649
0
    auto& entry = dnsQuestion->tagsVect->at(pos);
650
0
    entry.name = tag.first.c_str();
651
0
    entry.value = tag.second.c_str();
652
0
    ++pos;
653
0
  }
654
655
0
  if (!dnsQuestion->tagsVect->empty()) {
656
0
    *out = dnsQuestion->tagsVect->data();
657
0
  }
658
659
0
  return dnsQuestion->tagsVect->size();
660
0
}
661
662
void dnsdist_ffi_dnsquestion_set_result(dnsdist_ffi_dnsquestion_t* dnsQuestion, const char* str, size_t strSize)
663
0
{
664
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
665
0
  if (!checkDNSQuestionType(__func__, dnsQuestion)) {
666
0
    return;
667
0
  }
668
0
  dnsQuestion->result = std::string(str, strSize);
669
0
}
670
671
void dnsdist_ffi_dnsquestion_set_http_response([[maybe_unused]] dnsdist_ffi_dnsquestion_t* dnsQuestion, [[maybe_unused]] uint16_t statusCode, [[maybe_unused]] const char* body, [[maybe_unused]] size_t bodyLen, [[maybe_unused]] const char* contentType)
672
0
{
673
#if defined(HAVE_DNS_OVER_HTTPS)
674
  if (dnsQuestion->dq->ids.du) {
675
    // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic): C API
676
    PacketBuffer bodyVect(body, body + bodyLen);
677
    dnsQuestion->dq->ids.du->setHTTPResponse(statusCode, std::move(bodyVect), contentType);
678
    dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion->dq->getMutableData(), [](dnsheader& header) {
679
      header.qr = true;
680
      return true;
681
    });
682
  }
683
#endif
684
#if defined(HAVE_DNS_OVER_HTTP3)
685
  if (dnsQuestion->dq->ids.doh3u) {
686
    // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic): C API
687
    PacketBuffer bodyVect(body, body + bodyLen);
688
    dnsQuestion->dq->ids.doh3u->setHTTPResponse(statusCode, std::move(bodyVect), contentType);
689
    dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion->dq->getMutableData(), [](dnsheader& header) {
690
      header.qr = true;
691
      return true;
692
    });
693
  }
694
#endif
695
0
}
696
697
void dnsdist_ffi_dnsquestion_set_extended_dns_error(dnsdist_ffi_dnsquestion_t* dnsQuestion, uint16_t infoCode, const char* extraText, size_t extraTextSize)
698
0
{
699
0
  dnsdist::edns::SetExtendedDNSErrorOperation ede;
700
0
  ede.error.infoCode = infoCode;
701
0
  if (extraText != nullptr && extraTextSize > 0) {
702
0
    ede.error.extraText = std::string(extraText, extraTextSize);
703
0
  }
704
0
  ede.clearExisting = true;
705
0
  dnsQuestion->dq->ids.d_extendedErrors = std::make_unique<std::vector<dnsdist::edns::SetExtendedDNSErrorOperation>>(std::initializer_list<dnsdist::edns::SetExtendedDNSErrorOperation>({std::move(ede)}));
706
0
}
707
708
void dnsdist_ffi_dnsquestion_add_extended_dns_error(dnsdist_ffi_dnsquestion_t* dnsQuestion, uint16_t infoCode, const char* extraText, size_t extraTextSize)
709
0
{
710
0
  dnsdist::edns::SetExtendedDNSErrorOperation ede;
711
0
  ede.error.infoCode = infoCode;
712
0
  if (extraText != nullptr && extraTextSize > 0) {
713
0
    ede.error.extraText = std::string(extraText, extraTextSize);
714
0
  }
715
0
  ede.clearExisting = false;
716
0
  if (!dnsQuestion->dq->ids.d_extendedErrors) {
717
0
    dnsQuestion->dq->ids.d_extendedErrors = std::make_unique<std::vector<dnsdist::edns::SetExtendedDNSErrorOperation>>(std::initializer_list<dnsdist::edns::SetExtendedDNSErrorOperation>({std::move(ede)}));
718
0
  }
719
0
  else {
720
0
    dnsQuestion->dq->ids.d_extendedErrors->emplace_back(ede);
721
0
  }
722
0
}
723
724
void dnsdist_ffi_dnsquestion_set_rcode(dnsdist_ffi_dnsquestion_t* dnsQuestion, int rcode)
725
0
{
726
0
  try {
727
0
    dnsdist::PacketMangling::editDNSHeaderFromPacket(dnsQuestion->dq->getMutableData(), [rcode](dnsheader& header) {
728
0
      header.rcode = rcode;
729
0
      header.qr = true;
730
0
      return true;
731
0
    });
732
0
  }
733
0
  catch (const std::exception& e) {
734
0
    VERBOSESLOG(infolog("Error setting rcode in packet: %s", e.what()),
735
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error setting rcode in packet"));
736
0
  }
737
0
}
738
739
void dnsdist_ffi_dnsquestion_set_len(dnsdist_ffi_dnsquestion_t* dnsQuestion, uint16_t len)
740
0
{
741
0
  try {
742
0
    dnsQuestion->dq->getMutableData().resize(len);
743
0
  }
744
0
  catch (const std::exception& e) {
745
0
    VERBOSESLOG(infolog("Error setting packet size to %d: %s", len, e.what()),
746
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error setting packet size", "size", Logging::Loggable(len)));
747
0
  }
748
0
}
749
750
void dnsdist_ffi_dnsquestion_set_skip_cache(dnsdist_ffi_dnsquestion_t* dnsQuestion, bool skipCache)
751
0
{
752
0
  dnsQuestion->dq->ids.skipCache = skipCache;
753
0
}
754
755
void dnsdist_ffi_dnsquestion_set_use_ecs(dnsdist_ffi_dnsquestion_t* dnsQuestion, bool useECS)
756
0
{
757
0
  dnsQuestion->dq->useECS = useECS;
758
0
}
759
760
void dnsdist_ffi_dnsquestion_set_ecs_override(dnsdist_ffi_dnsquestion_t* dnsQuestion, bool ecsOverride)
761
0
{
762
0
  dnsQuestion->dq->ecsOverride = ecsOverride;
763
0
}
764
765
void dnsdist_ffi_dnsquestion_set_ecs_prefix_length(dnsdist_ffi_dnsquestion_t* dnsQuestion, uint16_t ecsPrefixLength)
766
0
{
767
0
  dnsQuestion->dq->ecsPrefixLength = ecsPrefixLength;
768
0
}
769
770
void dnsdist_ffi_dnsquestion_set_temp_failure_ttl(dnsdist_ffi_dnsquestion_t* dnsQuestion, uint32_t tempFailureTTL)
771
0
{
772
0
  dnsQuestion->dq->ids.tempFailureTTL = tempFailureTTL;
773
0
}
774
775
void dnsdist_ffi_dnsquestion_unset_temp_failure_ttl(dnsdist_ffi_dnsquestion_t* dnsQuestion)
776
0
{
777
0
  dnsQuestion->dq->ids.tempFailureTTL = std::nullopt;
778
0
}
779
780
void dnsdist_ffi_dnsquestion_set_tag(dnsdist_ffi_dnsquestion_t* dnsQuestion, const char* label, const char* value)
781
0
{
782
0
  dnsQuestion->dq->setTag(label, value);
783
0
}
784
785
void dnsdist_ffi_dnsquestion_unset_tag(dnsdist_ffi_dnsquestion_t* dnsQuestion, const char* label)
786
0
{
787
0
  dnsQuestion->dq->unsetTag(label);
788
0
}
789
790
void dnsdist_ffi_dnsquestion_set_tag_raw(dnsdist_ffi_dnsquestion_t* dnsQuestion, const char* label, const char* value, size_t valueSize)
791
0
{
792
0
  dnsQuestion->dq->setTag(label, std::string(value, valueSize));
793
0
}
794
795
void dnsdist_ffi_dnsquestion_set_requestor_id(dnsdist_ffi_dnsquestion_t* dnsQuestion, const char* value, size_t valueSize)
796
0
{
797
0
  if (dnsQuestion == nullptr || dnsQuestion->dq == nullptr || value == nullptr) {
798
0
    return;
799
0
  }
800
0
  if (!dnsQuestion->dq->ids.d_protoBufData) {
801
0
    dnsQuestion->dq->ids.d_protoBufData = std::make_unique<InternalQueryState::ProtoBufData>();
802
0
  }
803
0
  dnsQuestion->dq->ids.d_protoBufData->d_requestorID = std::string(value, valueSize);
804
0
}
805
806
void dnsdist_ffi_dnsquestion_set_device_id(dnsdist_ffi_dnsquestion_t* dnsQuestion, const char* value, size_t valueSize)
807
0
{
808
0
  if (dnsQuestion == nullptr || dnsQuestion->dq == nullptr || value == nullptr) {
809
0
    return;
810
0
  }
811
0
  if (!dnsQuestion->dq->ids.d_protoBufData) {
812
0
    dnsQuestion->dq->ids.d_protoBufData = std::make_unique<InternalQueryState::ProtoBufData>();
813
0
  }
814
0
  dnsQuestion->dq->ids.d_protoBufData->d_deviceID = std::string(value, valueSize);
815
0
}
816
817
void dnsdist_ffi_dnsquestion_set_device_name(dnsdist_ffi_dnsquestion_t* dnsQuestion, const char* value, size_t valueSize)
818
0
{
819
0
  if (dnsQuestion == nullptr || dnsQuestion->dq == nullptr || value == nullptr) {
820
0
    return;
821
0
  }
822
0
  if (!dnsQuestion->dq->ids.d_protoBufData) {
823
0
    dnsQuestion->dq->ids.d_protoBufData = std::make_unique<InternalQueryState::ProtoBufData>();
824
0
  }
825
0
  dnsQuestion->dq->ids.d_protoBufData->d_deviceName = std::string(value, valueSize);
826
0
}
827
828
size_t dnsdist_ffi_dnsquestion_get_trailing_data(dnsdist_ffi_dnsquestion_t* dnsQuestion, const char** out)
829
0
{
830
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
831
0
  if (!checkDNSQuestionType(__func__, dnsQuestion)) {
832
0
    return 0U;
833
0
  }
834
0
  dnsQuestion->trailingData = dnsQuestion->dq->getTrailingData();
835
0
  if (!dnsQuestion->trailingData.empty()) {
836
0
    *out = dnsQuestion->trailingData.data();
837
0
  }
838
839
0
  return dnsQuestion->trailingData.size();
840
0
}
841
842
bool dnsdist_ffi_dnsquestion_set_trailing_data(dnsdist_ffi_dnsquestion_t* dnsQuestion, const char* data, size_t dataLen)
843
0
{
844
0
  return dnsQuestion->dq->setTrailingData(std::string(data, dataLen));
845
0
}
846
847
void dnsdist_ffi_dnsquestion_send_trap(dnsdist_ffi_dnsquestion_t* dnsQuestion, const char* reason, size_t reasonLen)
848
0
{
849
0
  if (g_snmpAgent != nullptr && dnsdist::configuration::getImmutableConfiguration().d_snmpTrapsEnabled) {
850
0
    g_snmpAgent->sendDNSTrap(*dnsQuestion->dq, std::string(reason, reasonLen));
851
0
  }
852
0
}
853
854
void dnsdist_ffi_dnsquestion_spoof_packet(dnsdist_ffi_dnsquestion_t* dnsQuestion, const char* raw, size_t len)
855
0
{
856
0
  if (len < sizeof(dnsheader)) {
857
0
    return;
858
0
  }
859
860
0
  try {
861
    // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
862
0
    dnsdist::self_answers::generateAnswerFromRawPacket(*dnsQuestion->dq, PacketBuffer(raw, raw + len));
863
0
  }
864
0
  catch (const std::exception& e) {
865
0
    VERBOSESLOG(infolog("Error generating answer from packet", len, e.what()),
866
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error generating answer from packet"));
867
0
  }
868
0
}
869
870
void dnsdist_ffi_dnsquestion_spoof_raw(dnsdist_ffi_dnsquestion_t* dnsQuestion, const dnsdist_ffi_raw_value_t* values, size_t valuesCount)
871
0
{
872
0
  std::vector<std::string> data;
873
0
  data.reserve(valuesCount);
874
875
0
  for (size_t idx = 0; idx < valuesCount; idx++) {
876
    // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
877
0
    data.emplace_back(values[idx].value, values[idx].size);
878
0
  }
879
880
0
  dnsdist::ResponseConfig config{};
881
0
  dnsdist::self_answers::generateAnswerFromRDataEntries(*dnsQuestion->dq, data, std::nullopt, config);
882
0
}
883
884
void dnsdist_ffi_dnsquestion_spoof_addrs(dnsdist_ffi_dnsquestion_t* dnsQuestion, const dnsdist_ffi_raw_value_t* values, size_t valuesCount)
885
0
{
886
0
  std::vector<ComboAddress> data;
887
0
  data.reserve(valuesCount);
888
889
0
  for (size_t idx = 0; idx < valuesCount; idx++) {
890
    // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
891
0
    if (values[idx].size == 4) {
892
0
      sockaddr_in sin{};
893
0
      sin.sin_family = AF_INET;
894
0
      sin.sin_port = 0;
895
      // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
896
0
      memcpy(&sin.sin_addr.s_addr, values[idx].value, sizeof(sin.sin_addr.s_addr));
897
0
      data.emplace_back(&sin);
898
0
    }
899
    // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
900
0
    else if (values[idx].size == 16) {
901
0
      sockaddr_in6 sin6{};
902
0
      sin6.sin6_family = AF_INET6;
903
0
      sin6.sin6_port = 0;
904
0
      sin6.sin6_scope_id = 0;
905
0
      sin6.sin6_flowinfo = 0;
906
      // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
907
0
      memcpy(&sin6.sin6_addr.s6_addr, values[idx].value, sizeof(sin6.sin6_addr.s6_addr));
908
0
      data.emplace_back(&sin6);
909
0
    }
910
0
  }
911
912
0
  dnsdist::ResponseConfig config{};
913
0
  dnsdist::self_answers::generateAnswerFromIPAddresses(*dnsQuestion->dq, data, config);
914
0
}
915
916
void dnsdist_ffi_dnsquestion_set_max_returned_ttl(dnsdist_ffi_dnsquestion_t* dnsQuestion, uint32_t max)
917
0
{
918
0
  if (dnsQuestion != nullptr && dnsQuestion->dq != nullptr) {
919
0
    dnsQuestion->dq->ids.ttlCap = max;
920
0
  }
921
0
}
922
923
bool dnsdist_ffi_dnsquestion_set_restartable(dnsdist_ffi_dnsquestion_t* dnsQuestion)
924
0
{
925
0
  if (dnsQuestion == nullptr || dnsQuestion->dq == nullptr) {
926
    // NOLINTNEXTLINE(readability-simplify-boolean-expr)
927
0
    return false;
928
0
  }
929
930
0
  dnsQuestion->dq->ids.d_packet = std::make_unique<PacketBuffer>(dnsQuestion->dq->getData());
931
0
  return true;
932
0
}
933
934
size_t dnsdist_ffi_servers_list_get_count(const dnsdist_ffi_servers_list_t* list)
935
0
{
936
0
  return list->ffiServers.size();
937
0
}
938
939
void dnsdist_ffi_servers_list_get_server(const dnsdist_ffi_servers_list_t* list, size_t idx, const dnsdist_ffi_server_t** out)
940
0
{
941
0
  try {
942
0
    *out = &list->ffiServers.at(idx);
943
0
  }
944
0
  catch (...) {
945
0
    *out = nullptr;
946
0
  }
947
0
}
948
949
size_t dnsdist_ffi_servers_list_chashed(const dnsdist_ffi_servers_list_t* list, const dnsdist_ffi_dnsquestion_t* dnsQuestion, size_t hash)
950
0
{
951
0
  (void)dnsQuestion;
952
0
  auto serverPosition = chashedFromHash(list->servers, hash);
953
0
  if (!serverPosition) {
954
0
    VERBOSESLOG(infolog("Unable to get a server in dnsdist_ffi_servers_list_chashed"),
955
0
                getLogger(__func__)->info(Logr::Info, "Unable to get a server in dnsdist_ffi_servers_list_chashed"));
956
0
    return std::numeric_limits<size_t>::max();
957
0
  }
958
0
  return *serverPosition;
959
0
}
960
961
size_t dnsdist_ffi_servers_list_whashed(const dnsdist_ffi_servers_list_t* list, const dnsdist_ffi_dnsquestion_t* dnsQuestion, size_t hash)
962
0
{
963
0
  (void)dnsQuestion;
964
0
  auto serverPosition = whashedFromHash(list->servers, hash);
965
0
  if (!serverPosition) {
966
0
    VERBOSESLOG(infolog("Unable to get a server in dnsdist_ffi_servers_list_whashed"),
967
0
                getLogger(__func__)->info(Logr::Info, "Unable to get a server in dnsdist_ffi_servers_list_whashed"));
968
0
    return std::numeric_limits<size_t>::max();
969
0
  }
970
0
  return *serverPosition;
971
0
}
972
973
uint64_t dnsdist_ffi_server_get_outstanding(const dnsdist_ffi_server_t* server)
974
0
{
975
0
  return server->server->outstanding;
976
0
}
977
978
int dnsdist_ffi_server_get_weight(const dnsdist_ffi_server_t* server)
979
0
{
980
0
  return server->server->d_config.d_weight;
981
0
}
982
983
int dnsdist_ffi_server_get_order(const dnsdist_ffi_server_t* server)
984
0
{
985
0
  return server->server->d_config.order;
986
0
}
987
988
double dnsdist_ffi_server_get_latency(const dnsdist_ffi_server_t* server)
989
0
{
990
0
  return server->server->getRelevantLatencyUsec();
991
0
}
992
993
bool dnsdist_ffi_server_is_up(const dnsdist_ffi_server_t* server)
994
0
{
995
0
  return server->server->isUp();
996
0
}
997
998
const char* dnsdist_ffi_server_get_name(const dnsdist_ffi_server_t* server)
999
0
{
1000
0
  return server->server->getName().c_str();
1001
0
}
1002
1003
const char* dnsdist_ffi_server_get_name_with_addr(const dnsdist_ffi_server_t* server)
1004
0
{
1005
0
  return server->server->getNameWithAddr().c_str();
1006
0
}
1007
1008
void dnsdist_ffi_dnsresponse_set_min_ttl(dnsdist_ffi_dnsresponse_t* dnsResponse, uint32_t min)
1009
0
{
1010
0
  dnsdist_ffi_dnsresponse_limit_ttl(dnsResponse, min, std::numeric_limits<uint32_t>::max());
1011
0
}
1012
1013
void dnsdist_ffi_dnsresponse_set_max_ttl(dnsdist_ffi_dnsresponse_t* dnsResponse, uint32_t max)
1014
0
{
1015
0
  dnsdist_ffi_dnsresponse_limit_ttl(dnsResponse, 0, max);
1016
0
}
1017
1018
void dnsdist_ffi_dnsresponse_limit_ttl(dnsdist_ffi_dnsresponse_t* dnsResponse, uint32_t min, uint32_t max)
1019
0
{
1020
0
  if (dnsResponse != nullptr && dnsResponse->dr != nullptr) {
1021
    // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
1022
0
    if (!checkDNSResponseType(__func__, dnsResponse)) {
1023
0
      return;
1024
0
    }
1025
1026
0
    dnsdist::PacketMangling::restrictDNSPacketTTLs(dnsResponse->dr->getMutableData(), min, max);
1027
0
  }
1028
0
}
1029
1030
void dnsdist_ffi_dnsresponse_set_max_returned_ttl(dnsdist_ffi_dnsresponse_t* dnsResponse, uint32_t max)
1031
0
{
1032
0
  if (dnsResponse != nullptr && dnsResponse->dr != nullptr) {
1033
    // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
1034
0
    if (!checkDNSResponseType(__func__, dnsResponse)) {
1035
0
      return;
1036
0
    }
1037
0
    dnsResponse->dr->ids.ttlCap = max;
1038
0
  }
1039
0
}
1040
1041
void dnsdist_ffi_dnsresponse_clear_records_type(dnsdist_ffi_dnsresponse_t* dnsResponse, uint16_t qtype)
1042
0
{
1043
0
  if (dnsResponse != nullptr && dnsResponse->dr != nullptr) {
1044
    // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
1045
0
    if (!checkDNSResponseType(__func__, dnsResponse)) {
1046
0
      return;
1047
0
    }
1048
0
    clearDNSPacketRecordTypes(dnsResponse->dr->getMutableData(), std::unordered_set<QType>{qtype});
1049
0
  }
1050
0
}
1051
1052
bool dnsdist_ffi_dnsresponse_rebase(dnsdist_ffi_dnsresponse_t* dnsResponse, const char* initialName, size_t initialNameSize)
1053
0
{
1054
0
  if (dnsResponse == nullptr || dnsResponse->dr == nullptr || initialName == nullptr || initialNameSize == 0) {
1055
0
    return false;
1056
0
  }
1057
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
1058
0
  if (!checkDNSResponseType(__func__, dnsResponse)) {
1059
0
    return false;
1060
0
  }
1061
1062
0
  try {
1063
0
    DNSName parsed(initialName, initialNameSize, 0, false);
1064
1065
0
    if (!dnsdist::changeNameInDNSPacket(dnsResponse->dr->getMutableData(), dnsResponse->dr->ids.qname, parsed)) {
1066
0
      return false;
1067
0
    }
1068
1069
    // set qname to new one
1070
0
    dnsResponse->dr->ids.qname = std::move(parsed);
1071
0
    dnsResponse->dr->ids.skipCache = true;
1072
0
  }
1073
0
  catch (const std::exception& e) {
1074
0
    VERBOSESLOG(infolog("Error rebasing packet on a new DNSName: %s", e.what()),
1075
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error rebasing packet on a new DNSName"));
1076
0
    return false;
1077
0
  }
1078
1079
0
  return true;
1080
0
}
1081
1082
bool dnsdist_ffi_dnsresponse_get_stale_cache_hit(const dnsdist_ffi_dnsresponse_t* dnsResponse)
1083
0
{
1084
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
1085
0
  if (!checkDNSResponseType(__func__, dnsResponse)) {
1086
0
    return false;
1087
0
  }
1088
0
  return dnsResponse->dr->ids.staleCacheHit;
1089
0
}
1090
1091
uint8_t dnsdist_ffi_dnsresponse_get_restart_count(const dnsdist_ffi_dnsresponse_t* dnsResponse)
1092
0
{
1093
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
1094
0
  if (!checkDNSResponseType(__func__, dnsResponse)) {
1095
0
    return 0U;
1096
0
  }
1097
0
  return dnsResponse->dr->ids.restartCount;
1098
0
}
1099
1100
bool dnsdist_ffi_dnsquestion_set_async(dnsdist_ffi_dnsquestion_t* dnsQuestion, uint16_t asyncID, uint16_t queryID, uint32_t timeoutMs)
1101
0
{
1102
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
1103
0
  if (!checkDNSQuestionType(__func__, dnsQuestion)) {
1104
0
    return false;
1105
0
  }
1106
0
  try {
1107
0
    dnsQuestion->dq->asynchronous = true;
1108
0
    return dnsdist::suspendQuery(*dnsQuestion->dq, asyncID, queryID, timeoutMs);
1109
0
  }
1110
0
  catch (const std::exception& e) {
1111
0
    VERBOSESLOG(infolog("Error in dnsdist_ffi_dnsquestion_set_async: %s", e.what()),
1112
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error turning query asynchronous"));
1113
0
  }
1114
0
  catch (...) {
1115
0
    VERBOSESLOG(infolog("Exception in dnsdist_ffi_dnsquestion_set_async"),
1116
0
                getLogger(__func__)->info(Logr::Info, "Unknown error turning query asynchronous"));
1117
0
  }
1118
1119
0
  return false;
1120
0
}
1121
1122
bool dnsdist_ffi_dnsresponse_set_async(dnsdist_ffi_dnsresponse_t* dnsResponse, uint16_t asyncID, uint16_t queryID, uint32_t timeoutMs)
1123
0
{
1124
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
1125
0
  if (!checkDNSResponseType(__func__, dnsResponse)) {
1126
0
    return false;
1127
0
  }
1128
1129
0
  try {
1130
0
    dnsResponse->dr->asynchronous = true;
1131
0
    auto* drPtr = dnsResponse->dr;
1132
0
    if (drPtr == nullptr) {
1133
0
      VERBOSESLOG(infolog("Passed a DNSQuestion instead of a DNSResponse to dnsdist_ffi_dnsresponse_set_async"),
1134
0
                  getLogger(__func__)->info(Logr::Info, "Passed a DNSQuestion instead of a DNSResponse"));
1135
0
      return false;
1136
0
    }
1137
1138
0
    return dnsdist::suspendResponse(*drPtr, asyncID, queryID, timeoutMs);
1139
0
  }
1140
0
  catch (const std::exception& e) {
1141
0
    VERBOSESLOG(infolog("Error in dnsdist_ffi_dnsresponse_set_async: %s", e.what()),
1142
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error turning response asynchronous"));
1143
0
  }
1144
0
  catch (...) {
1145
0
    VERBOSESLOG(infolog("Exception in dnsdist_ffi_dnsresponse_set_async"),
1146
0
                getLogger(__func__)->info(Logr::Info, "Unknown error turning response asynchronous"));
1147
0
  }
1148
0
  return false;
1149
0
}
1150
1151
bool dnsdist_ffi_resume_from_async(uint16_t asyncID, uint16_t queryID, const char* tag, size_t tagSize, const char* tagValue, size_t tagValueSize, bool useCache)
1152
0
{
1153
0
  if (!dnsdist::g_asyncHolder) {
1154
0
    VERBOSESLOG(infolog("Unable to resume, no asynchronous holder"),
1155
0
                getLogger(__func__)->info(Logr::Info, "Unable to resume, no asynchronous holder"));
1156
0
    return false;
1157
0
  }
1158
1159
0
  auto query = dnsdist::g_asyncHolder->get(asyncID, queryID);
1160
0
  if (!query) {
1161
0
    VERBOSESLOG(infolog("Unable to resume, no object found for asynchronous ID %d and query ID %d", asyncID, queryID),
1162
0
                getLogger(__func__)->info(Logr::Info, "Unable to resume, no object found for the supplied asynchronous and query IDs", "dnsdist.async.id", Logging::Loggable(asyncID), "dns.query.id", Logging::Loggable(queryID)));
1163
0
    return false;
1164
0
  }
1165
1166
0
  auto& ids = query->query.d_idstate;
1167
0
  if (tag != nullptr && tagSize > 0) {
1168
0
    if (!ids.qTag) {
1169
0
      ids.qTag = std::make_unique<QTag>();
1170
0
    }
1171
0
    (*ids.qTag)[std::string(tag, tagSize)] = std::string(tagValue, tagValueSize);
1172
0
  }
1173
1174
0
  ids.skipCache = !useCache;
1175
1176
0
  return dnsdist::queueQueryResumptionEvent(std::move(query));
1177
0
}
1178
1179
bool dnsdist_ffi_set_rcode_from_async(uint16_t asyncID, uint16_t queryID, uint8_t rcode, bool clearAnswers)
1180
0
{
1181
0
  if (!dnsdist::g_asyncHolder) {
1182
0
    VERBOSESLOG(infolog("Unable to resume and set rcode async, no asynchronous holder"),
1183
0
                getLogger(__func__)->info(Logr::Info, "Unable to resume and set rcode, no asynchronous holder"));
1184
0
    return false;
1185
0
  }
1186
1187
0
  auto query = dnsdist::g_asyncHolder->get(asyncID, queryID);
1188
0
  if (!query) {
1189
0
    VERBOSESLOG(infolog("Unable to resume with a custom response code, no object found for asynchronous ID %d and query ID %d", asyncID, queryID),
1190
0
                getLogger(__func__)->info(Logr::Info, "Unable to resume, no object found for the supplied asynchronous and query IDs", "dnsdist.async.id", Logging::Loggable(asyncID), "dns.query.id", Logging::Loggable(queryID)));
1191
0
    return false;
1192
0
  }
1193
1194
0
  if (!dnsdist::setInternalQueryRCode(query->query.d_idstate, query->query.d_buffer, rcode, clearAnswers)) {
1195
0
    return false;
1196
0
  }
1197
1198
0
  query->query.d_idstate.skipCache = true;
1199
1200
0
  return dnsdist::queueQueryResumptionEvent(std::move(query));
1201
0
}
1202
1203
static bool setAlternateName(PacketBuffer& packet, InternalQueryState& ids, std::string_view alternateName, std::string_view tag, std::string_view tagValue, std::string_view formerNameTagName)
1204
0
{
1205
0
  const DNSName originalName = ids.qname;
1206
0
  try {
1207
0
    DNSName parsed(alternateName.data(), alternateName.size(), 0, false);
1208
1209
    // edit qname in query packet
1210
0
    if (!dnsdist::changeNameInDNSPacket(packet, originalName, parsed)) {
1211
0
      return false;
1212
0
    }
1213
0
    if (ids.d_packet) {
1214
0
      *ids.d_packet = packet;
1215
0
    }
1216
    // set qname to new one
1217
0
    ids.qname = std::move(parsed);
1218
0
  }
1219
0
  catch (const std::exception& e) {
1220
0
    VERBOSESLOG(infolog("Error rebasing packet on a new DNSName: %s", e.what()),
1221
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error rebasing packet on a new DNSName"));
1222
0
    return false;
1223
0
  }
1224
1225
  // save existing qname in tag
1226
0
  if (!formerNameTagName.empty()) {
1227
0
    if (!ids.qTag) {
1228
0
      ids.qTag = std::make_unique<QTag>();
1229
0
    }
1230
0
    (*ids.qTag)[std::string(formerNameTagName)] = originalName.getStorage();
1231
0
  }
1232
1233
0
  if (!tag.empty()) {
1234
0
    if (!ids.qTag) {
1235
0
      ids.qTag = std::make_unique<QTag>();
1236
0
    }
1237
0
    (*ids.qTag)[std::string(tag)] = tagValue;
1238
0
  }
1239
1240
0
  ids.skipCache = true;
1241
0
  return true;
1242
0
}
1243
1244
bool dnsdist_ffi_resume_from_async_with_alternate_name(uint16_t asyncID, uint16_t queryID, const char* alternateName, size_t alternateNameSize, const char* tag, size_t tagSize, const char* tagValue, size_t tagValueSize, const char* formerNameTagName, size_t formerNameTagSize)
1245
0
{
1246
0
  if (!dnsdist::g_asyncHolder) {
1247
0
    return false;
1248
0
  }
1249
1250
0
  auto query = dnsdist::g_asyncHolder->get(asyncID, queryID);
1251
0
  if (!query) {
1252
0
    VERBOSESLOG(infolog("Unable to resume with an alternate name, no object found for asynchronous ID %d and query ID %d", asyncID, queryID),
1253
0
                getLogger(__func__)->info(Logr::Info, "Unable to resume, no object found for the supplied asynchronous and query IDs", "dnsdist.async.id", Logging::Loggable(asyncID), "dns.query.id", Logging::Loggable(queryID)));
1254
0
    return false;
1255
0
  }
1256
1257
0
  auto& ids = query->query.d_idstate;
1258
0
  PacketBuffer packet;
1259
0
  if (query->d_isResponse) {
1260
0
    if (!ids.d_packet) {
1261
0
      return false;
1262
0
    }
1263
0
    packet = std::move(*ids.d_packet);
1264
0
  }
1265
0
  else {
1266
0
    packet = std::move(query->query.d_buffer);
1267
0
  }
1268
1269
0
  auto wasOK = setAlternateName(packet, ids, std::string_view(alternateName, alternateNameSize), std::string_view(tag, tagSize), std::string_view(tagValue, tagValueSize), std::string_view(formerNameTagName, formerNameTagSize));
1270
0
  if (!wasOK) {
1271
0
    return false;
1272
0
  }
1273
1274
0
  if (query->d_isResponse) {
1275
0
    query->d_isResponse = false;
1276
0
  }
1277
0
  query->query.d_buffer = std::move(packet);
1278
1279
  // resume as query
1280
0
  return dnsdist::queueQueryResumptionEvent(std::move(query));
1281
0
}
1282
1283
bool dnsdist_ffi_dnsquestion_set_alternate_name(dnsdist_ffi_dnsquestion_t* dnsQuestion, const char* alternateName, size_t alternateNameSize, const char* tag, size_t tagSize, const char* tagValue, size_t tagValueSize, const char* formerNameTagName, size_t formerNameTagSize)
1284
0
{
1285
0
  if (dnsQuestion == nullptr || dnsQuestion->dq == nullptr || alternateName == nullptr || alternateNameSize == 0) {
1286
0
    return false;
1287
0
  }
1288
1289
0
  auto& ids = dnsQuestion->dq->ids;
1290
0
  auto& packet = dnsQuestion->dq->getMutableData();
1291
0
  return setAlternateName(packet, ids, std::string_view(alternateName, alternateNameSize), std::string_view(tag, tagSize), std::string_view(tagValue, tagValueSize), std::string_view(formerNameTagName, formerNameTagSize));
1292
0
}
1293
1294
bool dnsdist_ffi_drop_from_async(uint16_t asyncID, uint16_t queryID)
1295
0
{
1296
0
  if (!dnsdist::g_asyncHolder) {
1297
0
    return false;
1298
0
  }
1299
1300
0
  auto query = dnsdist::g_asyncHolder->get(asyncID, queryID);
1301
0
  if (!query) {
1302
0
    VERBOSESLOG(infolog("Unable to drop, no object found for asynchronous ID %d and query ID %d", asyncID, queryID),
1303
0
                getLogger(__func__)->info(Logr::Info, "Unable to drop, no object found for the supplied asynchronous and query IDs", "dnsdist.async.id", Logging::Loggable(asyncID), "dns.query.id", Logging::Loggable(queryID)));
1304
0
    return false;
1305
0
  }
1306
1307
0
  auto sender = query->getTCPQuerySender();
1308
0
  if (!sender) {
1309
0
    return false;
1310
0
  }
1311
1312
0
  timeval now{};
1313
0
  gettimeofday(&now, nullptr);
1314
0
  TCPResponse tresponse(std::move(query->query));
1315
0
  sender->notifyIOError(now, std::move(tresponse));
1316
1317
0
  return true;
1318
0
}
1319
1320
bool dnsdist_ffi_set_answer_from_async(uint16_t asyncID, uint16_t queryID, const char* raw, size_t rawSize)
1321
0
{
1322
0
  if (rawSize < sizeof(dnsheader)) {
1323
0
    return false;
1324
0
  }
1325
0
  if (!dnsdist::g_asyncHolder) {
1326
0
    return false;
1327
0
  }
1328
1329
0
  auto query = dnsdist::g_asyncHolder->get(asyncID, queryID);
1330
0
  if (!query) {
1331
0
    VERBOSESLOG(infolog("Unable to resume with a custom answer, no object found for asynchronous ID %d and query ID %d", asyncID, queryID),
1332
0
                getLogger(__func__)->info(Logr::Info, "Unable to resume with a custom answer, no object found for the supplied asynchronous and query IDs", "dnsdist.async.id", Logging::Loggable(asyncID), "dns.query.id", Logging::Loggable(queryID)));
1333
0
    return false;
1334
0
  }
1335
1336
0
  dnsheader_aligned alignedHeader(query->query.d_buffer.data());
1337
0
  auto oldID = alignedHeader->id;
1338
0
  query->query.d_buffer.clear();
1339
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay,cppcoreguidelines-pro-bounds-pointer-arithmetic)
1340
0
  query->query.d_buffer.insert(query->query.d_buffer.begin(), raw, raw + rawSize);
1341
1342
0
  dnsdist::PacketMangling::editDNSHeaderFromPacket(query->query.d_buffer, [oldID](dnsheader& header) {
1343
0
    header.id = oldID;
1344
0
    return true;
1345
0
  });
1346
0
  query->query.d_idstate.skipCache = true;
1347
1348
0
  return dnsdist::queueQueryResumptionEvent(std::move(query));
1349
0
}
1350
1351
// NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays)
1352
static constexpr char s_lua_ffi_code[] = R"FFICodeContent(
1353
  local ffi = require("ffi")
1354
  local C = ffi.C
1355
1356
  ffi.cdef[[
1357
)FFICodeContent"
1358
#include "dnsdist-lua-ffi-interface.inc"
1359
                                         R"FFICodeContent(
1360
  ]]
1361
1362
)FFICodeContent";
1363
1364
const char* getLuaFFIWrappers()
1365
0
{
1366
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
1367
0
  return s_lua_ffi_code;
1368
0
}
1369
1370
void setupLuaLoadBalancingContext(LuaContext& luaCtx)
1371
0
{
1372
0
  setupLuaBindings(luaCtx, true, false);
1373
0
  setupLuaBindingsDNSQuestion(luaCtx);
1374
0
  setupLuaBindingsLogging(luaCtx);
1375
0
  setupLuaBindingsKVS(luaCtx, true);
1376
0
  setupLuaVars(luaCtx);
1377
1378
0
#ifdef LUAJIT_VERSION
1379
0
  luaCtx.executeCode(getLuaFFIWrappers());
1380
0
#endif
1381
0
}
1382
1383
void setupLuaFFIPerThreadContext(LuaContext& luaCtx)
1384
0
{
1385
0
  setupLuaVars(luaCtx);
1386
0
  setupLuaBindingsLogging(luaCtx);
1387
1388
0
#ifdef LUAJIT_VERSION
1389
0
  luaCtx.executeCode(getLuaFFIWrappers());
1390
0
#endif
1391
0
}
1392
1393
size_t dnsdist_ffi_generate_proxy_protocol_payload(const size_t addrSize, const void* srcAddr, const void* dstAddr, const uint16_t srcPort, const uint16_t dstPort, const bool tcp, const size_t valuesCount, const dnsdist_ffi_proxy_protocol_value* values, void* out, const size_t outSize)
1394
0
{
1395
0
  try {
1396
0
    ComboAddress src;
1397
0
    ComboAddress dst;
1398
0
    if (addrSize != sizeof(src.sin4.sin_addr) && addrSize != sizeof(src.sin6.sin6_addr.s6_addr)) {
1399
0
      return 0;
1400
0
    }
1401
1402
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
1403
0
    src = makeComboAddressFromRaw(addrSize == sizeof(src.sin4.sin_addr) ? 4 : 6, reinterpret_cast<const char*>(srcAddr), addrSize);
1404
0
    src.sin4.sin_port = htons(srcPort);
1405
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
1406
0
    dst = makeComboAddressFromRaw(addrSize == sizeof(dst.sin4.sin_addr) ? 4 : 6, reinterpret_cast<const char*>(dstAddr), addrSize);
1407
0
    dst.sin4.sin_port = htons(dstPort);
1408
1409
0
    std::vector<ProxyProtocolValue> valuesVect;
1410
0
    if (valuesCount > 0) {
1411
0
      valuesVect.reserve(valuesCount);
1412
0
      for (size_t idx = 0; idx < valuesCount; idx++) {
1413
        // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
1414
0
        valuesVect.push_back({std::string(values[idx].value, values[idx].size), values[idx].type});
1415
0
      }
1416
0
    }
1417
1418
0
    std::string payload = makeProxyHeader(tcp, src, dst, valuesVect);
1419
0
    if (payload.size() > outSize) {
1420
0
      return 0;
1421
0
    }
1422
1423
0
    memcpy(out, payload.c_str(), payload.size());
1424
1425
0
    return payload.size();
1426
0
  }
1427
0
  catch (const std::exception& e) {
1428
0
    VERBOSESLOG(infolog("Exception in dnsdist_ffi_generate_proxy_protocol_payload: %s", e.what()),
1429
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Exception while generating proxy protocol payload"));
1430
0
    return 0;
1431
0
  }
1432
0
  catch (...) {
1433
0
    VERBOSESLOG(infolog("Unhandled exception in dnsdist_ffi_generate_proxy_protocol_payload"),
1434
0
                getLogger(__func__)->info(Logr::Info, "Unknown exception while generating proxy protocol payload"));
1435
0
    return 0;
1436
0
  }
1437
0
}
1438
1439
size_t dnsdist_ffi_dnsquestion_generate_proxy_protocol_payload(const dnsdist_ffi_dnsquestion_t* dnsQuestion, const size_t valuesCount, const dnsdist_ffi_proxy_protocol_value* values, void* out, const size_t outSize)
1440
0
{
1441
0
  try {
1442
0
    std::vector<ProxyProtocolValue> valuesVect;
1443
0
    if (valuesCount > 0) {
1444
0
      valuesVect.reserve(valuesCount);
1445
0
      for (size_t idx = 0; idx < valuesCount; idx++) {
1446
        // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
1447
0
        valuesVect.push_back({std::string(values[idx].value, values[idx].size), values[idx].type});
1448
0
      }
1449
0
    }
1450
1451
0
    std::string payload = makeProxyHeader(dnsQuestion->dq->overTCP(), dnsQuestion->dq->ids.origRemote, dnsQuestion->dq->ids.origDest, valuesVect);
1452
0
    if (payload.size() > outSize) {
1453
0
      return 0;
1454
0
    }
1455
1456
0
    memcpy(out, payload.c_str(), payload.size());
1457
1458
0
    return payload.size();
1459
0
  }
1460
0
  catch (const std::exception& e) {
1461
0
    VERBOSESLOG(infolog("Exception in dnsdist_ffi_dnsquestion_generate_proxy_protocol_payload: %s", e.what()),
1462
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Exception while generating proxy protocol payload"));
1463
0
    return 0;
1464
0
  }
1465
0
  catch (...) {
1466
0
    VERBOSESLOG(infolog("Unhandled exception in dnsdist_ffi_dnsquestion_generate_proxy_protocol_payload"),
1467
0
                getLogger(__func__)->info(Logr::Info, "Unknown exception while generating proxy protocol payload"));
1468
0
    return 0;
1469
0
  }
1470
0
}
1471
1472
bool dnsdist_ffi_dnsquestion_add_proxy_protocol_values(dnsdist_ffi_dnsquestion_t* dnsQuestion, const size_t valuesCount, const dnsdist_ffi_proxy_protocol_value_t* values)
1473
0
{
1474
0
  if (dnsQuestion == nullptr || dnsQuestion->dq == nullptr || values == nullptr || valuesCount == 0) {
1475
0
    return false;
1476
0
  }
1477
1478
0
  if (!dnsQuestion->dq->proxyProtocolValues) {
1479
0
    dnsQuestion->dq->proxyProtocolValues = make_unique<std::vector<ProxyProtocolValue>>();
1480
0
  }
1481
1482
0
  dnsQuestion->dq->proxyProtocolValues->reserve(dnsQuestion->dq->proxyProtocolValues->size() + valuesCount);
1483
0
  for (size_t idx = 0; idx < valuesCount; idx++) {
1484
    // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic): the Lua FFI API is a C API..
1485
0
    dnsQuestion->dq->proxyProtocolValues->push_back({std::string(values[idx].value, values[idx].size), values[idx].type});
1486
0
  }
1487
1488
0
  return true;
1489
0
}
1490
1491
size_t dnsdist_ffi_dnsquestion_get_proxy_protocol_values(dnsdist_ffi_dnsquestion_t* dnsQuestion, const dnsdist_ffi_proxy_protocol_value_t** out)
1492
0
{
1493
0
  if (dnsQuestion == nullptr || dnsQuestion->dq == nullptr || !dnsQuestion->dq->proxyProtocolValues || out == nullptr) {
1494
0
    return 0;
1495
0
  }
1496
1497
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
1498
0
  if (!checkDNSQuestionType(__func__, dnsQuestion)) {
1499
0
    return 0U;
1500
0
  }
1501
1502
0
  dnsQuestion->proxyProtocolValuesVect = std::make_unique<std::vector<dnsdist_ffi_proxy_protocol_value_t>>(dnsQuestion->dq->proxyProtocolValues->size());
1503
0
  for (size_t counter = 0; counter < dnsQuestion->dq->proxyProtocolValues->size(); ++counter) {
1504
0
    const auto& entry = dnsQuestion->dq->proxyProtocolValues->at(counter);
1505
0
    auto& targetEntry = dnsQuestion->proxyProtocolValuesVect->at(counter);
1506
0
    targetEntry.size = entry.content.size();
1507
0
    targetEntry.value = entry.content.data();
1508
0
    targetEntry.type = entry.type;
1509
0
  }
1510
1511
0
  *out = dnsQuestion->proxyProtocolValuesVect->data();
1512
0
  return dnsQuestion->proxyProtocolValuesVect->size();
1513
0
}
1514
1515
struct dnsdist_ffi_domain_list_t
1516
{
1517
  std::vector<std::string> d_domains;
1518
};
1519
struct dnsdist_ffi_address_list_t
1520
{
1521
  std::vector<std::string> d_addresses;
1522
};
1523
1524
const char* dnsdist_ffi_domain_list_get(const dnsdist_ffi_domain_list_t* list, size_t idx)
1525
0
{
1526
0
  if (list == nullptr || idx >= list->d_domains.size()) {
1527
0
    return nullptr;
1528
0
  }
1529
1530
0
  return list->d_domains.at(idx).c_str();
1531
0
}
1532
1533
void dnsdist_ffi_domain_list_free(dnsdist_ffi_domain_list_t* list)
1534
0
{
1535
  // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
1536
0
  delete list;
1537
0
}
1538
1539
const char* dnsdist_ffi_address_list_get(const dnsdist_ffi_address_list_t* list, size_t idx)
1540
0
{
1541
0
  if (list == nullptr || idx >= list->d_addresses.size()) {
1542
0
    return nullptr;
1543
0
  }
1544
1545
0
  return list->d_addresses.at(idx).c_str();
1546
0
}
1547
1548
void dnsdist_ffi_address_list_free(dnsdist_ffi_address_list_t* list)
1549
0
{
1550
  // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
1551
0
  delete list;
1552
0
}
1553
1554
size_t dnsdist_ffi_packetcache_get_domain_list_by_addr(const char* poolName, const char* addr, dnsdist_ffi_domain_list_t** out)
1555
0
{
1556
0
  if (poolName == nullptr || addr == nullptr || out == nullptr) {
1557
0
    return 0;
1558
0
  }
1559
1560
0
  ComboAddress caAddr;
1561
0
  try {
1562
0
    caAddr = ComboAddress(addr);
1563
0
  }
1564
0
  catch (const std::exception& e) {
1565
0
    VERBOSESLOG(infolog("Error parsing address passed to dnsdist_ffi_packetcache_get_domain_list_by_addr: %s", e.what()),
1566
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error parsing address"));
1567
0
    return 0;
1568
0
  }
1569
1570
0
  const auto& pools = dnsdist::configuration::getCurrentRuntimeConfiguration().d_pools;
1571
0
  auto poolIt = pools.find(poolName);
1572
0
  if (poolIt == pools.end()) {
1573
0
    return 0;
1574
0
  }
1575
1576
0
  const auto& pool = poolIt->second;
1577
0
  if (!pool.packetCache) {
1578
0
    return 0;
1579
0
  }
1580
1581
0
  auto domains = pool.packetCache->getDomainsContainingRecords(caAddr);
1582
0
  if (domains.empty()) {
1583
0
    return 0;
1584
0
  }
1585
1586
0
  auto list = std::make_unique<dnsdist_ffi_domain_list_t>();
1587
0
  list->d_domains.reserve(domains.size());
1588
0
  for (const auto& domain : domains) {
1589
0
    try {
1590
0
      list->d_domains.push_back(domain.toString());
1591
0
    }
1592
0
    catch (const std::exception& e) {
1593
0
      VERBOSESLOG(infolog("Error converting domain to string in dnsdist_ffi_packetcache_get_domain_list_by_addr: %s", e.what()),
1594
0
                  getLogger(__func__)->error(Logr::Info, e.what(), "Error converting domain to string", "domain", Logging::Loggable(domain)));
1595
0
    }
1596
0
  }
1597
1598
0
  size_t count = list->d_domains.size();
1599
0
  if (count > 0) {
1600
0
    *out = list.release();
1601
0
  }
1602
0
  return count;
1603
0
}
1604
1605
size_t dnsdist_ffi_packetcache_get_address_list_by_domain(const char* poolName, const char* domain, dnsdist_ffi_address_list_t** out)
1606
0
{
1607
0
  if (poolName == nullptr || domain == nullptr || out == nullptr) {
1608
0
    return 0;
1609
0
  }
1610
1611
0
  DNSName name;
1612
0
  try {
1613
0
    name = DNSName(domain);
1614
0
  }
1615
0
  catch (const std::exception& e) {
1616
0
    VERBOSESLOG(infolog("Error parsing domain passed to dnsdist_ffi_packetcache_get_address_list_by_domain: %s", e.what()),
1617
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error parsing domain parameter", "domain", Logging::Loggable(domain)));
1618
0
    return 0;
1619
0
  }
1620
1621
0
  const auto& pools = dnsdist::configuration::getCurrentRuntimeConfiguration().d_pools;
1622
0
  auto poolIt = pools.find(poolName);
1623
0
  if (poolIt == pools.end()) {
1624
0
    return 0;
1625
0
  }
1626
1627
0
  const auto& pool = poolIt->second;
1628
0
  if (!pool.packetCache) {
1629
0
    return 0;
1630
0
  }
1631
1632
0
  auto addresses = pool.packetCache->getRecordsForDomain(name);
1633
0
  if (addresses.empty()) {
1634
0
    return 0;
1635
0
  }
1636
1637
0
  auto list = std::make_unique<dnsdist_ffi_address_list_t>();
1638
0
  list->d_addresses.reserve(addresses.size());
1639
0
  for (const auto& addr : addresses) {
1640
0
    try {
1641
0
      list->d_addresses.push_back(addr.toString());
1642
0
    }
1643
0
    catch (const std::exception& e) {
1644
0
      VERBOSESLOG(infolog("Error converting address to string in dnsdist_ffi_packetcache_get_address_list_by_domain: %s", e.what()),
1645
0
                  getLogger(__func__)->error(Logr::Info, e.what(), "Error parsing address to string", "address", Logging::Loggable(addr)));
1646
0
    }
1647
0
  }
1648
1649
0
  size_t count = list->d_addresses.size();
1650
0
  if (count > 0) {
1651
0
    *out = list.release();
1652
0
  }
1653
0
  return count;
1654
0
}
1655
1656
struct dnsdist_ffi_ring_entry_list_t
1657
{
1658
  struct entry
1659
  {
1660
    std::string qname;
1661
    std::string requestor;
1662
    std::string macAddr;
1663
    std::string ds;
1664
    dnsheader dh;
1665
    double age;
1666
    unsigned int latency;
1667
    uint16_t size;
1668
    uint16_t qtype;
1669
    dnsdist::Protocol protocol;
1670
    bool isResponse;
1671
  };
1672
1673
  std::vector<entry> d_entries;
1674
};
1675
1676
bool dnsdist_ffi_ring_entry_is_response(const dnsdist_ffi_ring_entry_list_t* list, size_t idx)
1677
0
{
1678
0
  if (list == nullptr || idx >= list->d_entries.size()) {
1679
0
    return false;
1680
0
  }
1681
1682
0
  return list->d_entries.at(idx).isResponse;
1683
0
}
1684
1685
double dnsdist_ffi_ring_entry_get_age(const dnsdist_ffi_ring_entry_list_t* list, size_t idx)
1686
0
{
1687
0
  if (list == nullptr || idx >= list->d_entries.size()) {
1688
0
    return 0;
1689
0
  }
1690
1691
0
  return list->d_entries.at(idx).age;
1692
0
}
1693
1694
const char* dnsdist_ffi_ring_entry_get_name(const dnsdist_ffi_ring_entry_list_t* list, size_t idx)
1695
0
{
1696
0
  if (list == nullptr || idx >= list->d_entries.size()) {
1697
0
    return nullptr;
1698
0
  }
1699
1700
0
  return list->d_entries.at(idx).qname.c_str();
1701
0
}
1702
1703
uint16_t dnsdist_ffi_ring_entry_get_type(const dnsdist_ffi_ring_entry_list_t* list, size_t idx)
1704
0
{
1705
0
  if (list == nullptr || idx >= list->d_entries.size()) {
1706
0
    return 0;
1707
0
  }
1708
1709
0
  return list->d_entries.at(idx).qtype;
1710
0
}
1711
1712
const char* dnsdist_ffi_ring_entry_get_requestor(const dnsdist_ffi_ring_entry_list_t* list, size_t idx)
1713
0
{
1714
0
  if (list == nullptr || idx >= list->d_entries.size()) {
1715
0
    return nullptr;
1716
0
  }
1717
1718
0
  return list->d_entries.at(idx).requestor.c_str();
1719
0
}
1720
1721
const char* dnsdist_ffi_ring_entry_get_backend(const dnsdist_ffi_ring_entry_list_t* list, size_t idx)
1722
0
{
1723
0
  if (list == nullptr || idx >= list->d_entries.size()) {
1724
0
    return nullptr;
1725
0
  }
1726
1727
0
  return list->d_entries.at(idx).ds.c_str();
1728
0
}
1729
1730
uint8_t dnsdist_ffi_ring_entry_get_protocol(const dnsdist_ffi_ring_entry_list_t* list, size_t idx)
1731
0
{
1732
0
  if (list == nullptr || idx >= list->d_entries.size()) {
1733
0
    return 0;
1734
0
  }
1735
1736
0
  return list->d_entries.at(idx).protocol.toNumber();
1737
0
}
1738
1739
uint16_t dnsdist_ffi_ring_entry_get_size(const dnsdist_ffi_ring_entry_list_t* list, size_t idx)
1740
0
{
1741
0
  if (list == nullptr || idx >= list->d_entries.size()) {
1742
0
    return 0;
1743
0
  }
1744
1745
0
  return list->d_entries.at(idx).size;
1746
0
}
1747
1748
uint16_t dnsdist_ffi_ring_entry_get_latency(const dnsdist_ffi_ring_entry_list_t* list, size_t idx)
1749
0
{
1750
0
  if (list == nullptr || idx >= list->d_entries.size()) {
1751
0
    return 0;
1752
0
  }
1753
1754
0
  return list->d_entries.at(idx).latency;
1755
0
}
1756
1757
uint16_t dnsdist_ffi_ring_entry_get_id(const dnsdist_ffi_ring_entry_list_t* list, size_t idx)
1758
0
{
1759
0
  if (list == nullptr || idx >= list->d_entries.size()) {
1760
0
    return 0;
1761
0
  }
1762
1763
0
  return ntohs(list->d_entries.at(idx).dh.id);
1764
0
}
1765
1766
uint8_t dnsdist_ffi_ring_entry_get_rcode(const dnsdist_ffi_ring_entry_list_t* list, size_t idx)
1767
0
{
1768
0
  if (list == nullptr || idx >= list->d_entries.size()) {
1769
0
    return 0;
1770
0
  }
1771
1772
0
  return list->d_entries.at(idx).dh.rcode;
1773
0
}
1774
1775
bool dnsdist_ffi_ring_entry_get_aa(const dnsdist_ffi_ring_entry_list_t* list, size_t idx)
1776
0
{
1777
0
  if (list == nullptr || idx >= list->d_entries.size()) {
1778
0
    return false;
1779
0
  }
1780
1781
0
  return list->d_entries.at(idx).dh.aa == 1;
1782
0
}
1783
1784
bool dnsdist_ffi_ring_entry_get_rd(const dnsdist_ffi_ring_entry_list_t* list, size_t idx)
1785
0
{
1786
0
  if (list == nullptr || idx >= list->d_entries.size()) {
1787
0
    return false;
1788
0
  }
1789
1790
0
  return list->d_entries.at(idx).dh.rd == 1;
1791
0
}
1792
1793
bool dnsdist_ffi_ring_entry_get_tc(const dnsdist_ffi_ring_entry_list_t* list, size_t idx)
1794
0
{
1795
0
  if (list == nullptr || idx >= list->d_entries.size()) {
1796
0
    return false;
1797
0
  }
1798
1799
0
  return list->d_entries.at(idx).dh.tc == 1;
1800
0
}
1801
1802
uint16_t dnsdist_ffi_ring_entry_get_ancount(const dnsdist_ffi_ring_entry_list_t* list, size_t idx)
1803
0
{
1804
0
  if (list == nullptr || idx >= list->d_entries.size()) {
1805
0
    return 0;
1806
0
  }
1807
1808
0
  return ntohs(list->d_entries.at(idx).dh.ancount);
1809
0
}
1810
1811
uint16_t dnsdist_ffi_ring_entry_get_nscount(const dnsdist_ffi_ring_entry_list_t* list, size_t idx)
1812
0
{
1813
0
  if (list == nullptr || idx >= list->d_entries.size()) {
1814
0
    return 0;
1815
0
  }
1816
1817
0
  return ntohs(list->d_entries.at(idx).dh.nscount);
1818
0
}
1819
1820
uint16_t dnsdist_ffi_ring_entry_get_arcount(const dnsdist_ffi_ring_entry_list_t* list, size_t idx)
1821
0
{
1822
0
  if (list == nullptr || idx >= list->d_entries.size()) {
1823
0
    return 0;
1824
0
  }
1825
1826
0
  return ntohs(list->d_entries.at(idx).dh.arcount);
1827
0
}
1828
1829
bool dnsdist_ffi_ring_entry_has_mac_address(const dnsdist_ffi_ring_entry_list_t* list, size_t idx)
1830
0
{
1831
0
  if (list == nullptr || idx >= list->d_entries.size()) {
1832
0
    return false;
1833
0
  }
1834
1835
0
  return !list->d_entries.at(idx).macAddr.empty();
1836
0
}
1837
1838
const char* dnsdist_ffi_ring_entry_get_mac_address(const dnsdist_ffi_ring_entry_list_t* list, size_t idx)
1839
0
{
1840
0
  if (list == nullptr || idx >= list->d_entries.size()) {
1841
0
    return nullptr;
1842
0
  }
1843
1844
0
  return list->d_entries.at(idx).macAddr.data();
1845
0
}
1846
1847
void dnsdist_ffi_ring_entry_list_free(dnsdist_ffi_ring_entry_list_t* list)
1848
0
{
1849
  // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
1850
0
  delete list;
1851
0
}
1852
1853
template <typename T>
1854
static void addRingEntryToList(std::unique_ptr<dnsdist_ffi_ring_entry_list_t>& list, const struct timespec& now, const T& entry)
1855
0
{
1856
0
  auto age = DiffTime(entry.when, now);
1857
1858
0
  constexpr bool response = std::is_same_v<T, Rings::Response>;
1859
0
  if constexpr (!response) {
1860
#if defined(DNSDIST_RINGS_WITH_MACADDRESS)
1861
    dnsdist_ffi_ring_entry_list_t::entry tmp{entry.name.toString(), entry.requestor.toStringWithPort(), entry.hasmac ? std::string(reinterpret_cast<const char*>(entry.macaddress.data()), entry.macaddress.size()) : std::string(), std::string(), entry.dh, age, 0, entry.size, entry.qtype, entry.protocol, response};
1862
#else
1863
0
    dnsdist_ffi_ring_entry_list_t::entry tmp{entry.name.toString(), entry.requestor.toStringWithPort(), std::string(), std::string(), entry.dh, age, 0, entry.size, entry.qtype, entry.protocol, response};
1864
0
#endif
1865
0
    list->d_entries.push_back(std::move(tmp));
1866
  }
1867
0
  else {
1868
0
    dnsdist_ffi_ring_entry_list_t::entry tmp{entry.name.toString(), entry.requestor.toStringWithPort(), std::string(), entry.ds.toStringWithPort(), entry.dh, age, entry.usec, entry.size, entry.qtype, entry.protocol, response};
1869
0
    list->d_entries.push_back(std::move(tmp));
1870
0
  }
1871
0
}
Unexecuted instantiation: dnsdist-lua-ffi.cc:void addRingEntryToList<Rings::Query>(std::__1::unique_ptr<dnsdist_ffi_ring_entry_list_t, std::__1::default_delete<dnsdist_ffi_ring_entry_list_t> >&, timespec const&, Rings::Query const&)
Unexecuted instantiation: dnsdist-lua-ffi.cc:void addRingEntryToList<Rings::Response>(std::__1::unique_ptr<dnsdist_ffi_ring_entry_list_t, std::__1::default_delete<dnsdist_ffi_ring_entry_list_t> >&, timespec const&, Rings::Response const&)
1872
1873
size_t dnsdist_ffi_ring_get_entries(dnsdist_ffi_ring_entry_list_t** out)
1874
0
{
1875
0
  if (out == nullptr) {
1876
0
    return 0;
1877
0
  }
1878
0
  auto list = std::make_unique<dnsdist_ffi_ring_entry_list_t>();
1879
0
  struct timespec now{};
1880
0
  gettime(&now);
1881
1882
0
  for (const auto& shard : g_rings.d_shards) {
1883
0
    {
1884
0
      auto queryRingLock = shard->queryRing.lock();
1885
0
      for (const auto& entry : *queryRingLock) {
1886
0
        addRingEntryToList(list, now, entry);
1887
0
      }
1888
0
    }
1889
0
    {
1890
0
      auto responseRingLock = shard->respRing.lock();
1891
0
      for (const auto& entry : *responseRingLock) {
1892
0
        addRingEntryToList(list, now, entry);
1893
0
      }
1894
0
    }
1895
0
  }
1896
1897
0
  auto count = list->d_entries.size();
1898
0
  if (count > 0) {
1899
0
    *out = list.release();
1900
0
  }
1901
0
  return count;
1902
0
}
1903
1904
size_t dnsdist_ffi_ring_get_entries_by_addr(const char* addr, dnsdist_ffi_ring_entry_list_t** out)
1905
0
{
1906
0
  if (out == nullptr || addr == nullptr) {
1907
0
    return 0;
1908
0
  }
1909
0
  ComboAddress caAddr;
1910
0
  try {
1911
0
    caAddr = ComboAddress(addr);
1912
0
  }
1913
0
  catch (const std::exception& e) {
1914
0
    VERBOSESLOG(infolog("Unable to convert address in dnsdist_ffi_ring_get_entries_by_addr: %s", e.what()),
1915
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Unable to parse address", "address", Logging::Loggable(addr)));
1916
0
    return 0;
1917
0
  }
1918
1919
0
  auto list = std::make_unique<dnsdist_ffi_ring_entry_list_t>();
1920
0
  timespec now{};
1921
0
  gettime(&now);
1922
1923
0
  auto compare = ComboAddress::addressOnlyEqual();
1924
0
  for (const auto& shard : g_rings.d_shards) {
1925
0
    {
1926
0
      auto queryRingLock = shard->queryRing.lock();
1927
0
      for (const auto& entry : *queryRingLock) {
1928
0
        if (!compare(entry.requestor, caAddr)) {
1929
0
          continue;
1930
0
        }
1931
1932
0
        addRingEntryToList(list, now, entry);
1933
0
      }
1934
0
    }
1935
0
    {
1936
0
      auto responseRingLock = shard->respRing.lock();
1937
0
      for (const auto& entry : *responseRingLock) {
1938
0
        if (!compare(entry.requestor, caAddr)) {
1939
0
          continue;
1940
0
        }
1941
1942
0
        addRingEntryToList(list, now, entry);
1943
0
      }
1944
0
    }
1945
0
  }
1946
1947
0
  auto count = list->d_entries.size();
1948
0
  if (count > 0) {
1949
0
    *out = list.release();
1950
0
  }
1951
0
  return count;
1952
0
}
1953
1954
size_t dnsdist_ffi_ring_get_entries_by_mac(const char* addr, dnsdist_ffi_ring_entry_list_t** out)
1955
0
{
1956
0
  if (out == nullptr || addr == nullptr) {
1957
0
    return 0;
1958
0
  }
1959
1960
0
#if !defined(DNSDIST_RINGS_WITH_MACADDRESS)
1961
0
  return 0;
1962
#else
1963
  auto list = std::make_unique<dnsdist_ffi_ring_entry_list_t>();
1964
  timespec now{};
1965
  gettime(&now);
1966
1967
  for (const auto& shard : g_rings.d_shards) {
1968
    auto queryRingLock = shard->queryRing.lock();
1969
    for (const auto& entry : *queryRingLock) {
1970
      if (memcmp(addr, entry.macaddress.data(), entry.macaddress.size()) != 0) {
1971
        continue;
1972
      }
1973
1974
      addRingEntryToList(list, now, entry);
1975
    }
1976
  }
1977
1978
  auto count = list->d_entries.size();
1979
  if (count > 0) {
1980
    *out = list.release();
1981
  }
1982
  return count;
1983
#endif
1984
0
}
1985
1986
struct dnsdist_ffi_network_endpoint_t
1987
{
1988
  dnsdist::NetworkEndpoint d_endpoint;
1989
};
1990
1991
bool dnsdist_ffi_network_endpoint_new(const char* path, size_t pathSize, dnsdist_ffi_network_endpoint_t** out)
1992
0
{
1993
0
  if (path == nullptr || pathSize == 0 || out == nullptr) {
1994
0
    return false;
1995
0
  }
1996
0
  try {
1997
0
    dnsdist::NetworkEndpoint endpoint(std::string(path, pathSize));
1998
    // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
1999
0
    *out = new dnsdist_ffi_network_endpoint_t{std::move(endpoint)};
2000
0
    return true;
2001
0
  }
2002
0
  catch (const std::exception& e) {
2003
0
    VERBOSESLOG(infolog("Error creating a new network endpoint: %s", e.what()),
2004
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error creating a new network endpoint", "path", Logging::Loggable(path)));
2005
0
    return false;
2006
0
  }
2007
0
}
2008
2009
bool dnsdist_ffi_network_endpoint_is_valid(const dnsdist_ffi_network_endpoint_t* endpoint)
2010
0
{
2011
0
  return endpoint != nullptr;
2012
0
}
2013
2014
bool dnsdist_ffi_network_endpoint_send(const dnsdist_ffi_network_endpoint_t* endpoint, const char* payload, size_t payloadSize)
2015
0
{
2016
0
  if (endpoint != nullptr && payload != nullptr && payloadSize != 0) {
2017
0
    return endpoint->d_endpoint.send(std::string_view(payload, payloadSize));
2018
0
  }
2019
0
  return false;
2020
0
}
2021
2022
void dnsdist_ffi_network_endpoint_free(dnsdist_ffi_network_endpoint_t* endpoint)
2023
0
{
2024
  // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
2025
0
  delete endpoint;
2026
0
}
2027
2028
struct dnsdist_ffi_dnspacket_t
2029
{
2030
  dnsdist::DNSPacketOverlay overlay;
2031
};
2032
2033
bool dnsdist_ffi_dnspacket_parse(const char* packet, size_t packetSize, dnsdist_ffi_dnspacket_t** out)
2034
0
{
2035
0
  if (packet == nullptr || out == nullptr || packetSize < sizeof(dnsheader)) {
2036
0
    return false;
2037
0
  }
2038
2039
0
  try {
2040
0
    dnsdist::DNSPacketOverlay overlay(std::string_view(packet, packetSize));
2041
    // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
2042
0
    *out = new dnsdist_ffi_dnspacket_t{std::move(overlay)};
2043
0
    return true;
2044
0
  }
2045
0
  catch (const std::exception& e) {
2046
0
    VERBOSESLOG(vinfolog("Error in dnsdist_ffi_dnspacket_parse: %s", e.what()),
2047
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error parsing DNS packet", "packet_size", Logging::Loggable(packetSize)));
2048
0
  }
2049
0
  catch (...) {
2050
0
    VERBOSESLOG(infolog("Error in dnsdist_ffi_dnspacket_parse"),
2051
0
                getLogger(__func__)->info(Logr::Info, "Error parsing DNS packet", "packet_size", Logging::Loggable(packetSize)));
2052
0
  }
2053
0
  return false;
2054
0
}
2055
2056
void dnsdist_ffi_dnspacket_get_qname_raw(const dnsdist_ffi_dnspacket_t* packet, const char** qname, size_t* qnameSize)
2057
0
{
2058
0
  if (packet == nullptr || qname == nullptr || qnameSize == nullptr) {
2059
0
    return;
2060
0
  }
2061
0
  const auto& storage = packet->overlay.d_qname.getStorage();
2062
0
  *qname = storage.data();
2063
0
  *qnameSize = storage.size();
2064
0
}
2065
2066
uint16_t dnsdist_ffi_dnspacket_get_qtype(const dnsdist_ffi_dnspacket_t* packet)
2067
0
{
2068
0
  if (packet != nullptr) {
2069
0
    return packet->overlay.d_qtype;
2070
0
  }
2071
0
  return 0;
2072
0
}
2073
2074
uint16_t dnsdist_ffi_dnspacket_get_qclass(const dnsdist_ffi_dnspacket_t* packet)
2075
0
{
2076
0
  if (packet != nullptr) {
2077
0
    return packet->overlay.d_qclass;
2078
0
  }
2079
0
  return 0;
2080
0
}
2081
2082
uint16_t dnsdist_ffi_dnspacket_get_records_count_in_section(const dnsdist_ffi_dnspacket_t* packet, uint8_t section)
2083
0
{
2084
0
  if (packet == nullptr || section > DNSResourceRecord::ADDITIONAL) {
2085
0
    return 0;
2086
0
  }
2087
2088
0
  uint16_t count = 0;
2089
0
  for (const auto& record : packet->overlay.d_records) {
2090
0
    if (record.d_place == section) {
2091
0
      count++;
2092
0
    }
2093
0
  }
2094
2095
0
  return count;
2096
0
}
2097
2098
void dnsdist_ffi_dnspacket_get_record_name_raw(const dnsdist_ffi_dnspacket_t* packet, size_t idx, const char** name, size_t* nameSize)
2099
0
{
2100
0
  if (packet == nullptr || name == nullptr || nameSize == nullptr || idx >= packet->overlay.d_records.size()) {
2101
0
    return;
2102
0
  }
2103
0
  const auto& storage = packet->overlay.d_records.at(idx).d_name.getStorage();
2104
0
  *name = storage.data();
2105
0
  *nameSize = storage.size();
2106
0
}
2107
2108
uint16_t dnsdist_ffi_dnspacket_get_record_type(const dnsdist_ffi_dnspacket_t* packet, size_t idx)
2109
0
{
2110
0
  if (packet == nullptr || idx >= packet->overlay.d_records.size()) {
2111
0
    return 0;
2112
0
  }
2113
0
  return packet->overlay.d_records.at(idx).d_type;
2114
0
}
2115
2116
uint16_t dnsdist_ffi_dnspacket_get_record_class(const dnsdist_ffi_dnspacket_t* packet, size_t idx)
2117
0
{
2118
0
  if (packet == nullptr || idx >= packet->overlay.d_records.size()) {
2119
0
    return 0;
2120
0
  }
2121
0
  return packet->overlay.d_records.at(idx).d_class;
2122
0
}
2123
2124
uint32_t dnsdist_ffi_dnspacket_get_record_ttl(const dnsdist_ffi_dnspacket_t* packet, size_t idx)
2125
0
{
2126
0
  if (packet == nullptr || idx >= packet->overlay.d_records.size()) {
2127
0
    return 0;
2128
0
  }
2129
0
  return packet->overlay.d_records.at(idx).d_ttl;
2130
0
}
2131
2132
uint16_t dnsdist_ffi_dnspacket_get_record_content_length(const dnsdist_ffi_dnspacket_t* packet, size_t idx)
2133
0
{
2134
0
  if (packet == nullptr || idx >= packet->overlay.d_records.size()) {
2135
0
    return 0;
2136
0
  }
2137
0
  return packet->overlay.d_records.at(idx).d_contentLength;
2138
0
}
2139
2140
uint16_t dnsdist_ffi_dnspacket_get_record_content_offset(const dnsdist_ffi_dnspacket_t* packet, size_t idx)
2141
0
{
2142
0
  if (packet == nullptr || idx >= packet->overlay.d_records.size()) {
2143
0
    return 0;
2144
0
  }
2145
0
  return packet->overlay.d_records.at(idx).d_contentOffset;
2146
0
}
2147
2148
size_t dnsdist_ffi_dnspacket_get_name_at_offset_raw(const char* packet, size_t packetSize, size_t offset, char* name, size_t nameSize)
2149
0
{
2150
0
  if (packet == nullptr || name == nullptr || nameSize == 0 || offset >= packetSize) {
2151
0
    return 0;
2152
0
  }
2153
0
  try {
2154
0
    DNSName parsed(packet, packetSize, offset, true);
2155
0
    const auto& storage = parsed.getStorage();
2156
0
    if (nameSize < storage.size()) {
2157
0
      return 0;
2158
0
    }
2159
0
    memcpy(name, storage.data(), storage.size());
2160
0
    return storage.size();
2161
0
  }
2162
0
  catch (const std::exception& e) {
2163
0
    VERBOSESLOG(infolog("Error parsing DNSName from packet (%s) via dnsdist_ffi_dnspacket_get_name_at_offset_raw: %s", makeHexDump(std::string(packet, packetSize)), e.what()),
2164
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error parsing DNS name", "packet_size", Logging::Loggable(packetSize), "offset", Logging::Loggable(offset), "packet_bytes", Logging::Loggable(makeHexDump(std::string(packet, packetSize)))));
2165
0
  }
2166
0
  return 0;
2167
0
}
2168
2169
bool dnsdist_ffi_dnspacket_parse_a_record(const char* raw, const dnsdist_ffi_dnspacket_t* packet, size_t idx, char* addr, size_t* addrSize)
2170
0
{
2171
0
  if (raw == nullptr || packet == nullptr || addr == nullptr || addrSize == nullptr || *addrSize < 4 || idx >= packet->overlay.d_records.size()) {
2172
0
    return false;
2173
0
  }
2174
2175
0
  const auto& record = packet->overlay.d_records.at(idx);
2176
0
  if (record.d_type != QType::A || record.d_contentLength != 4) {
2177
0
    return false;
2178
0
  }
2179
2180
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic): this is a C API
2181
0
  memcpy(addr, &raw[record.d_contentOffset], 4);
2182
0
  *addrSize = record.d_contentLength;
2183
2184
0
  return true;
2185
0
}
2186
2187
bool dnsdist_ffi_dnspacket_parse_aaaa_record(const char* raw, const dnsdist_ffi_dnspacket_t* packet, size_t idx, char* addr, size_t* addrSize)
2188
0
{
2189
0
  if (raw == nullptr || packet == nullptr || addr == nullptr || addrSize == nullptr || *addrSize < 16 || idx >= packet->overlay.d_records.size()) {
2190
0
    return false;
2191
0
  }
2192
2193
0
  const auto& record = packet->overlay.d_records.at(idx);
2194
0
  if (record.d_type != QType::AAAA || record.d_contentLength != 16) {
2195
0
    return false;
2196
0
  }
2197
2198
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic): this is a C API
2199
0
  memcpy(addr, &raw[record.d_contentOffset], 16);
2200
0
  *addrSize = record.d_contentLength;
2201
2202
0
  return true;
2203
0
}
2204
2205
bool dnsdist_ffi_dnspacket_parse_address_record(const char* raw, const dnsdist_ffi_dnspacket_t* packet, size_t idx, char* addr, size_t* addrSize)
2206
0
{
2207
0
  if (raw == nullptr || packet == nullptr || addr == nullptr || addrSize == nullptr || idx >= packet->overlay.d_records.size()) {
2208
0
    return false;
2209
0
  }
2210
2211
0
  const auto& record = packet->overlay.d_records.at(idx);
2212
0
  if (record.d_type == QType::A && record.d_contentLength == 4) {
2213
0
    if (*addrSize < 4) {
2214
0
      return false;
2215
0
    }
2216
    // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic): this is a C API
2217
0
    memcpy(addr, &raw[record.d_contentOffset], 4);
2218
0
    *addrSize = record.d_contentLength;
2219
2220
0
    return true;
2221
0
  }
2222
2223
0
  if (record.d_type == QType::AAAA && record.d_contentLength == 16) {
2224
0
    if (*addrSize < 16) {
2225
0
      return false;
2226
0
    }
2227
    // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic): this is a C API
2228
0
    memcpy(addr, &raw[record.d_contentOffset], 16);
2229
0
    *addrSize = record.d_contentLength;
2230
2231
0
    return true;
2232
0
  }
2233
2234
0
  return false;
2235
0
}
2236
2237
bool dnsdist_ffi_dnspacket_parse_cname_record(const char* raw, const dnsdist_ffi_dnspacket_t* packet, size_t idx, char* name, size_t* nameSize)
2238
0
{
2239
0
  if (raw == nullptr || packet == nullptr || name == nullptr || nameSize == nullptr || *nameSize == 0 || idx >= packet->overlay.d_records.size()) {
2240
0
    return false;
2241
0
  }
2242
2243
0
  const auto& record = packet->overlay.d_records.at(idx);
2244
0
  if (record.d_type != QType::CNAME) {
2245
0
    return false;
2246
0
  }
2247
2248
0
  try {
2249
0
    DNSName parsed(raw, record.d_contentOffset + record.d_contentLength, record.d_contentOffset, true);
2250
0
    const auto& storage = parsed.getStorage();
2251
0
    if (*nameSize < storage.size()) {
2252
0
      return false;
2253
0
    }
2254
2255
0
    memcpy(name, storage.data(), storage.size());
2256
0
    *nameSize = storage.size();
2257
2258
0
    return true;
2259
0
  }
2260
0
  catch (const std::exception& e) {
2261
0
    VERBOSESLOG(infolog("Error parsing CNAME record: %s", e.what()),
2262
0
                getLogger(__func__)->error(Logr::Info, e.what(), "Error parsing CNAME record"));
2263
0
    return false;
2264
0
  }
2265
0
}
2266
2267
void dnsdist_ffi_dnspacket_free(dnsdist_ffi_dnspacket_t* packet)
2268
0
{
2269
  // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
2270
0
  delete packet;
2271
0
}
2272
2273
bool dnsdist_ffi_metric_declare(const char* name, size_t nameLen, const char* type, const char* description, const char* customName)
2274
0
{
2275
0
  if (name == nullptr || nameLen == 0 || type == nullptr || description == nullptr) {
2276
0
    return false;
2277
0
  }
2278
0
  auto result = dnsdist::metrics::declareCustomMetric(name, type, description, customName != nullptr ? std::optional<std::string>(customName) : std::nullopt, false);
2279
0
  return !result;
2280
0
}
2281
2282
void dnsdist_ffi_metric_inc(const char* metricName, size_t metricNameLen)
2283
0
{
2284
0
  auto result = dnsdist::metrics::incrementCustomCounter(std::string_view(metricName, metricNameLen), 1U, std::nullopt);
2285
0
  if (std::get_if<dnsdist::metrics::Error>(&result) != nullptr) {
2286
0
    return;
2287
0
  }
2288
0
}
2289
2290
void dnsdist_ffi_metric_inc_by(const char* metricName, size_t metricNameLen, uint64_t value)
2291
0
{
2292
0
  auto result = dnsdist::metrics::incrementCustomCounter(std::string_view(metricName, metricNameLen), value, std::nullopt);
2293
0
  if (std::get_if<dnsdist::metrics::Error>(&result) != nullptr) {
2294
0
    return;
2295
0
  }
2296
0
}
2297
2298
void dnsdist_ffi_metric_dec(const char* metricName, size_t metricNameLen)
2299
0
{
2300
0
  auto result = dnsdist::metrics::decrementCustomCounter(std::string_view(metricName, metricNameLen), 1U, std::nullopt);
2301
0
  if (std::get_if<dnsdist::metrics::Error>(&result) != nullptr) {
2302
0
    return;
2303
0
  }
2304
0
}
2305
2306
void dnsdist_ffi_metric_set(const char* metricName, size_t metricNameLen, double value)
2307
0
{
2308
0
  auto result = dnsdist::metrics::setCustomGauge(std::string_view(metricName, metricNameLen), value, std::nullopt);
2309
0
  if (std::get_if<dnsdist::metrics::Error>(&result) != nullptr) {
2310
0
    return;
2311
0
  }
2312
0
}
2313
2314
double dnsdist_ffi_metric_get(const char* metricName, size_t metricNameLen, bool isCounter)
2315
0
{
2316
0
  (void)isCounter;
2317
0
  auto result = dnsdist::metrics::getCustomMetric(std::string_view(metricName, metricNameLen), {});
2318
0
  if (std::get_if<dnsdist::metrics::Error>(&result) != nullptr) {
2319
0
    return 0.;
2320
0
  }
2321
0
  return std::get<double>(result);
2322
0
}
2323
2324
const char* dnsdist_ffi_network_message_get_payload(const dnsdist_ffi_network_message_t* msg)
2325
0
{
2326
0
  if (msg != nullptr) {
2327
0
    return msg->payload.c_str();
2328
0
  }
2329
0
  return nullptr;
2330
0
}
2331
2332
size_t dnsdist_ffi_network_message_get_payload_size(const dnsdist_ffi_network_message_t* msg)
2333
0
{
2334
0
  if (msg != nullptr) {
2335
0
    return msg->payload.size();
2336
0
  }
2337
0
  return 0;
2338
0
}
2339
2340
uint16_t dnsdist_ffi_network_message_get_endpoint_id(const dnsdist_ffi_network_message_t* msg)
2341
0
{
2342
0
  if (msg != nullptr) {
2343
0
    return msg->endpointID;
2344
0
  }
2345
0
  return 0;
2346
0
}
2347
2348
#ifndef DISABLE_DYNBLOCKS
2349
bool dnsdist_ffi_dynamic_blocks_add(const char* address, const char* message, uint8_t action, unsigned int duration, uint8_t clientIPMask, uint8_t clientIPPortMask, const char* tagKey, const char* tagValue)
2350
0
{
2351
0
  try {
2352
0
    ComboAddress clientIPCA;
2353
0
    try {
2354
0
      clientIPCA = ComboAddress(address);
2355
0
    }
2356
0
    catch (const std::exception& exp) {
2357
0
      SLOG(errlog("dnsdist_ffi_dynamic_blocks_add: Unable to parse '%s': %s", address, exp.what()),
2358
0
           getLogger(__func__)->error(Logr::Error, exp.what(), "Error parsing IP address", "address", Logging::Loggable(address)));
2359
0
      return false;
2360
0
    }
2361
2362
0
    AddressAndPortRange target(clientIPCA, clientIPMask, clientIPPortMask);
2363
2364
0
    timespec now{};
2365
0
    gettime(&now);
2366
0
    timespec until{now};
2367
0
    until.tv_sec += duration;
2368
0
    DynBlock dblock{message, until, DNSName(), static_cast<DNSAction::Action>(action)};
2369
2370
0
    auto dynamicRules = dnsdist::DynamicBlocks::getClientAddressDynamicRulesCopy();
2371
0
    if (dblock.action == DNSAction::Action::SetTag && tagKey != nullptr) {
2372
0
      dblock.tagSettings = std::make_shared<DynBlock::TagSettings>();
2373
0
      dblock.tagSettings->d_name = tagKey;
2374
0
      if (tagValue != nullptr) {
2375
0
        dblock.tagSettings->d_value = tagValue;
2376
0
      }
2377
0
    }
2378
0
    if (dnsdist::DynamicBlocks::addOrRefreshBlock(dynamicRules, now, target, std::move(dblock), false)) {
2379
0
      dnsdist::DynamicBlocks::setClientAddressDynamicRules(std::move(dynamicRules));
2380
0
      return true;
2381
0
    }
2382
0
  }
2383
0
  catch (const std::exception& exp) {
2384
0
    SLOG(errlog("Exception in dnsdist_ffi_dynamic_blocks_add: %s", exp.what()),
2385
0
         getLogger(__func__)->error(Logr::Error, exp.what(), "Exception adding a dynamic rule", "address", Logging::Loggable(address)));
2386
0
  }
2387
0
  catch (...) {
2388
0
    SLOG(errlog("Exception in dnsdist_ffi_dynamic_blocks_add"),
2389
0
         getLogger(__func__)->info(Logr::Error, "Unknown exception adding a dynamic rule", "address", Logging::Loggable(address)));
2390
0
  }
2391
0
  return false;
2392
0
}
2393
2394
bool dnsdist_ffi_dynamic_blocks_smt_add(const char* suffix, const char* message, uint8_t action, unsigned int duration, const char* tagKey, const char* tagValue)
2395
0
{
2396
0
  try {
2397
0
    DNSName domain;
2398
0
    try {
2399
0
      domain = DNSName(suffix);
2400
0
      domain.makeUsLowerCase();
2401
0
    }
2402
0
    catch (const std::exception& exp) {
2403
0
      SLOG(errlog("dnsdist_ffi_dynamic_blocks_smt_add: Unable to parse '%s': %s", suffix, exp.what()),
2404
0
           getLogger(__func__)->error(Logr::Error, exp.what(), "Error parsing suffix", "suffix", Logging::Loggable(suffix)));
2405
0
      return false;
2406
0
    }
2407
2408
0
    timespec now{};
2409
0
    gettime(&now);
2410
0
    timespec until{now};
2411
0
    until.tv_sec += duration;
2412
0
    DynBlock dblock{message, until, domain, static_cast<DNSAction::Action>(action)};
2413
0
    auto smtBlocks = dnsdist::DynamicBlocks::getSuffixDynamicRulesCopy();
2414
0
    if (dblock.action == DNSAction::Action::SetTag && tagKey != nullptr) {
2415
0
      dblock.tagSettings = std::make_shared<DynBlock::TagSettings>();
2416
0
      dblock.tagSettings->d_name = tagKey;
2417
0
      if (tagValue != nullptr) {
2418
0
        dblock.tagSettings->d_value = tagValue;
2419
0
      }
2420
0
    }
2421
0
    if (dnsdist::DynamicBlocks::addOrRefreshBlockSMT(smtBlocks, now, std::move(dblock), false)) {
2422
0
      dnsdist::DynamicBlocks::setSuffixDynamicRules(std::move(smtBlocks));
2423
0
      return true;
2424
0
    }
2425
0
  }
2426
0
  catch (const std::exception& exp) {
2427
0
    SLOG(errlog("Exception in dnsdist_ffi_dynamic_blocks_smt_add: %s", exp.what()),
2428
0
         getLogger(__func__)->error(Logr::Error, exp.what(), "Exception adding a dynamic SMT rule", "suffix", Logging::Loggable(suffix)));
2429
0
  }
2430
0
  catch (...) {
2431
0
    SLOG(errlog("Exception in dnsdist_ffi_dynamic_blocks_smt_add"),
2432
0
         getLogger(__func__)->info(Logr::Error, "Unknown exception adding a dynamic SMT rule", "suffix", Logging::Loggable(suffix)));
2433
0
  }
2434
0
  return false;
2435
0
}
2436
2437
struct dnsdist_ffi_dynamic_blocks_list_t
2438
{
2439
  std::vector<dnsdist_ffi_dynamic_block_entry_t> d_entries;
2440
};
2441
2442
size_t dnsdist_ffi_dynamic_blocks_get_entries(dnsdist_ffi_dynamic_blocks_list_t** out)
2443
0
{
2444
0
  if (out == nullptr) {
2445
0
    return 0;
2446
0
  }
2447
2448
0
  auto list = std::make_unique<dnsdist_ffi_dynamic_blocks_list_t>();
2449
2450
0
  timespec now{};
2451
0
  gettime(&now);
2452
2453
0
  const auto& dynamicRules = dnsdist::DynamicBlocks::getClientAddressDynamicRules();
2454
0
  for (const auto& entry : dynamicRules) {
2455
0
    const auto& client = entry.first;
2456
0
    const auto& details = entry.second;
2457
0
    if (!(now < details.until)) {
2458
0
      continue;
2459
0
    }
2460
2461
0
    uint64_t counter = details.blocks;
2462
0
    if (g_defaultBPFFilter && details.bpf) {
2463
0
      counter += g_defaultBPFFilter->getHits(client.getNetwork());
2464
0
    }
2465
0
    list->d_entries.push_back({strdup(client.toString().c_str()), strdup(details.reason.c_str()), counter, static_cast<uint64_t>(details.until.tv_sec - now.tv_sec), static_cast<uint8_t>(details.action != DNSAction::Action::None ? details.action : dnsdist::configuration::getCurrentRuntimeConfiguration().d_dynBlockAction), g_defaultBPFFilter && details.bpf, details.warning});
2466
0
  }
2467
2468
0
  auto count = list->d_entries.size();
2469
0
  *out = list.release();
2470
0
  return count;
2471
0
}
2472
2473
size_t dnsdist_ffi_dynamic_blocks_smt_get_entries(dnsdist_ffi_dynamic_blocks_list_t** out)
2474
0
{
2475
0
  if (out == nullptr) {
2476
0
    return 0;
2477
0
  }
2478
2479
0
  auto list = std::make_unique<dnsdist_ffi_dynamic_blocks_list_t>();
2480
2481
0
  timespec now{};
2482
0
  gettime(&now);
2483
2484
0
  const auto defaultAction = dnsdist::configuration::getCurrentRuntimeConfiguration().d_dynBlockAction;
2485
0
  const auto& smtBlocks = dnsdist::DynamicBlocks::getSuffixDynamicRules();
2486
0
  smtBlocks.visit([&now, &list, defaultAction](const SuffixMatchTree<DynBlock>& node) {
2487
0
    if (!(now < node.d_value.until)) {
2488
0
      return;
2489
0
    }
2490
0
    auto entry = node.d_value;
2491
0
    string key("empty");
2492
0
    if (!entry.domain.empty()) {
2493
0
      key = entry.domain.toString();
2494
0
    }
2495
0
    if (entry.action == DNSAction::Action::None) {
2496
0
      entry.action = defaultAction;
2497
0
    }
2498
0
    list->d_entries.push_back({strdup(key.c_str()), strdup(entry.reason.c_str()), entry.blocks, static_cast<uint64_t>(entry.until.tv_sec - now.tv_sec), static_cast<uint8_t>(entry.action), entry.bpf, entry.warning});
2499
0
  });
2500
2501
0
  auto count = list->d_entries.size();
2502
0
  *out = list.release();
2503
0
  return count;
2504
0
}
2505
2506
const dnsdist_ffi_dynamic_block_entry_t* dnsdist_ffi_dynamic_blocks_list_get(const dnsdist_ffi_dynamic_blocks_list_t* list, size_t idx)
2507
0
{
2508
0
  if (list == nullptr) {
2509
0
    return nullptr;
2510
0
  }
2511
2512
0
  if (idx >= list->d_entries.size()) {
2513
0
    return nullptr;
2514
0
  }
2515
2516
0
  return &list->d_entries.at(idx);
2517
0
}
2518
2519
void dnsdist_ffi_dynamic_blocks_list_free(dnsdist_ffi_dynamic_blocks_list_t* list)
2520
0
{
2521
0
  if (list == nullptr) {
2522
0
    return;
2523
0
  }
2524
2525
0
  for (auto& entry : list->d_entries) {
2526
    // NOLINTNEXTLINE(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc): this is a C API, RAII is not an option
2527
0
    free(entry.key);
2528
    // NOLINTNEXTLINE(cppcoreguidelines-owning-memory,cppcoreguidelines-no-malloc): this is a C API, RAII is not an option
2529
0
    free(entry.reason);
2530
0
  }
2531
2532
  // NOLINTNEXTLINE(cppcoreguidelines-owning-memory): this is a C API, RAII is not an option
2533
0
  delete list;
2534
0
}
2535
2536
#endif /* DISABLE_DYNBLOCKS */
2537
2538
uint32_t dnsdist_ffi_hash(uint32_t seed, const unsigned char* data, size_t dataSize, bool caseInsensitive)
2539
0
{
2540
0
  if (data == nullptr || dataSize == 0) {
2541
0
    return seed;
2542
0
  }
2543
2544
0
  if (caseInsensitive) {
2545
0
    return burtleCI(data, dataSize, seed);
2546
0
  }
2547
2548
0
  return burtle(data, dataSize, seed);
2549
0
}
2550
2551
struct dnsdist_ffi_svc_record_parameters
2552
{
2553
  SVCRecordParameters parameters;
2554
};
2555
2556
bool dnsdist_ffi_svc_record_parameters_new(const char* targetName, uint16_t priority, bool noDefaultALPN, dnsdist_ffi_svc_record_parameters** out)
2557
0
{
2558
0
  if (targetName == nullptr || out == nullptr) {
2559
0
    return false;
2560
0
  }
2561
0
  try {
2562
0
    auto parameters = std::make_unique<dnsdist_ffi_svc_record_parameters>();
2563
0
    parameters->parameters.target = DNSName(targetName);
2564
0
    parameters->parameters.priority = priority;
2565
0
    parameters->parameters.noDefaultAlpn = noDefaultALPN;
2566
0
    *out = parameters.release();
2567
0
    return true;
2568
0
  }
2569
0
  catch (const std::exception& exp) {
2570
0
    SLOG(errlog("Exception in dnsdist_ffi_svc_record_parameters_new: %s", exp.what()),
2571
0
         getLogger(__func__)->error(Logr::Error, exp.what(), "Exception creating SVC record parameter", "target_name", Logging::Loggable(targetName)));
2572
0
  }
2573
0
  catch (...) {
2574
0
    SLOG(errlog("Exception in dnsdist_ffi_svc_record_parameters_new"),
2575
0
         getLogger(__func__)->info(Logr::Error, "Exception creating SVC record parameter", "target_name", Logging::Loggable(targetName)));
2576
0
  }
2577
2578
0
  return false;
2579
0
}
2580
2581
void dnsdist_ffi_svc_record_parameters_set_port(dnsdist_ffi_svc_record_parameters* parameters, uint16_t port)
2582
0
{
2583
0
  if (parameters == nullptr) {
2584
0
    return;
2585
0
  }
2586
0
  parameters->parameters.port = port;
2587
0
}
2588
2589
void dnsdist_ffi_svc_record_parameters_set_ech(dnsdist_ffi_svc_record_parameters* parameters, const char* ech, size_t echLen)
2590
0
{
2591
0
  if (parameters == nullptr || ech == nullptr || echLen == 0) {
2592
0
    return;
2593
0
  }
2594
0
  parameters->parameters.ech = std::string(ech, echLen);
2595
0
}
2596
2597
void dnsdist_ffi_svc_record_parameters_set_additional_param(dnsdist_ffi_svc_record_parameters* parameters, const char* key, const char* value, size_t valueLen)
2598
0
{
2599
0
  if (parameters == nullptr || (value == nullptr && valueLen != 0)) {
2600
0
    return;
2601
0
  }
2602
0
  parameters->parameters.additionalParams.emplace_back(SvcParam::keyFromString(key), std::string(value, valueLen));
2603
0
}
2604
2605
void dnsdist_ffi_svc_record_parameters_add_mandatory_param(dnsdist_ffi_svc_record_parameters* parameters, uint16_t key)
2606
0
{
2607
0
  if (parameters == nullptr) {
2608
0
    return;
2609
0
  }
2610
0
  parameters->parameters.mandatoryParams.insert(key);
2611
0
}
2612
2613
void dnsdist_ffi_svc_record_parameters_add_alpn(dnsdist_ffi_svc_record_parameters* parameters, const char* value, size_t valueLen)
2614
0
{
2615
0
  if (parameters == nullptr || value == nullptr || valueLen == 0) {
2616
0
    return;
2617
0
  }
2618
0
  parameters->parameters.alpns.emplace_back(value, valueLen);
2619
0
}
2620
2621
void dnsdist_ffi_svc_record_parameters_add_ipv4_hint(dnsdist_ffi_svc_record_parameters* parameters, const char* value, size_t valueLen)
2622
0
{
2623
0
  if (parameters == nullptr || value == nullptr || valueLen == 0) {
2624
0
    return;
2625
0
  }
2626
0
  try {
2627
0
    parameters->parameters.ipv4hints.emplace_back(std::string(value, valueLen));
2628
0
  }
2629
0
  catch (const std::exception& exp) {
2630
0
    SLOG(errlog("Exception in dnsdist_ffi_svc_record_parameters_add_ipv4_hint: %s", exp.what()),
2631
0
         getLogger(__func__)->error(Logr::Error, exp.what(), "Exception adding IPv4 hint to SVC record"));
2632
0
  }
2633
0
  catch (...) {
2634
0
    SLOG(errlog("Exception in dnsdist_ffi_svc_record_parameters_add_ipv4_hint"),
2635
0
         getLogger(__func__)->info(Logr::Error, "Exception adding IPv4 hint to SVC record"));
2636
0
  }
2637
0
}
2638
2639
void dnsdist_ffi_svc_record_parameters_add_ipv6_hint(dnsdist_ffi_svc_record_parameters* parameters, const char* value, size_t valueLen)
2640
0
{
2641
0
  if (parameters == nullptr || value == nullptr || valueLen == 0) {
2642
0
    return;
2643
0
  }
2644
0
  try {
2645
0
    parameters->parameters.ipv6hints.emplace_back(std::string(value, valueLen));
2646
0
  }
2647
0
  catch (const std::exception& exp) {
2648
0
    SLOG(errlog("Exception in dnsdist_ffi_svc_record_parameters_add_ipv6_hint: %s", exp.what()),
2649
0
         getLogger(__func__)->error(Logr::Error, exp.what(), "Exception adding IPv6 hint to SVC record"));
2650
0
  }
2651
0
  catch (...) {
2652
0
    SLOG(errlog("Exception in dnsdist_ffi_svc_record_parameters_add_ipv6_hint"),
2653
0
         getLogger(__func__)->info(Logr::Error, "Exception adding IPv6 hint to SVC record"));
2654
0
  }
2655
0
}
2656
2657
bool dnsdist_ffi_dnsquestion_generate_svc_response(dnsdist_ffi_dnsquestion_t* dnsQuestion, const dnsdist_ffi_svc_record_parameters** parametersList, size_t parametersListSize, uint32_t ttl)
2658
0
{
2659
0
  if (dnsQuestion == nullptr || parametersList == nullptr || parametersListSize == 0) {
2660
0
    return false;
2661
0
  }
2662
0
  std::vector<SVCRecordParameters> parameters;
2663
0
  parameters.reserve(parametersListSize);
2664
0
  for (size_t idx = 0; idx < parametersListSize; idx++) {
2665
    // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic): this is a C API
2666
0
    const auto* parameter = parametersList[idx];
2667
0
    if (parameter == nullptr) {
2668
0
      return false;
2669
0
    }
2670
0
    parameters.push_back(parameter->parameters);
2671
0
  }
2672
0
  return dnsdist::svc::generateSVCResponse(*dnsQuestion->dq, ttl, parameters);
2673
0
}
2674
2675
void dnsdist_ffi_svc_record_parameters_free(dnsdist_ffi_svc_record_parameters* parameters)
2676
0
{
2677
  // NOLINTNEXTLINE(cppcoreguidelines-owning-memory): this is a C API, RAII is not an option
2678
0
  delete parameters;
2679
0
}
2680
2681
void dnsdist_ffi_dnsquestion_meta_begin_key([[maybe_unused]] dnsdist_ffi_dnsquestion_t* dnsQuestion, [[maybe_unused]] const char* key, [[maybe_unused]] size_t keyLen)
2682
0
{
2683
0
#if !defined(DISABLE_PROTOBUF)
2684
0
  if (dnsQuestion == nullptr || key == nullptr || keyLen == 0) {
2685
0
    return;
2686
0
  }
2687
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
2688
0
  if (!checkDNSQuestionType(__func__, dnsQuestion)) {
2689
0
    return;
2690
0
  }
2691
2692
0
  if (dnsQuestion->pbfWriter.valid()) {
2693
0
    VERBOSESLOG(infolog("Error in dnsdist_ffi_dnsquestion_meta_begin_key: the previous key has not been ended"),
2694
0
                getLogger(__func__)->info(Logr::Info, "Error beginning a new meta key: the previous key has not been ended"));
2695
0
    return;
2696
0
  }
2697
2698
0
  dnsQuestion->pbfWriter = protozero::pbf_writer{dnsQuestion->dq->ids.d_rawProtobufContent};
2699
0
  dnsQuestion->pbfMetaWriter = protozero::pbf_writer{dnsQuestion->pbfWriter, static_cast<protozero::pbf_tag_type>(pdns::ProtoZero::Message::Field::meta)};
2700
0
  dnsQuestion->pbfMetaWriter.add_string(static_cast<protozero::pbf_tag_type>(pdns::ProtoZero::Message::MetaField::key), protozero::data_view(key, keyLen));
2701
0
  dnsQuestion->pbfMetaValueWriter = protozero::pbf_writer{dnsQuestion->pbfMetaWriter, static_cast<protozero::pbf_tag_type>(pdns::ProtoZero::Message::MetaField::value)};
2702
0
#endif /* DISABLE_PROTOBUF */
2703
0
}
2704
2705
void dnsdist_ffi_dnsquestion_meta_add_str_value_to_key([[maybe_unused]] dnsdist_ffi_dnsquestion_t* dnsQuestion, [[maybe_unused]] const char* value, [[maybe_unused]] size_t valueLen)
2706
0
{
2707
0
#if !defined(DISABLE_PROTOBUF)
2708
0
  if (dnsQuestion == nullptr || value == nullptr || valueLen == 0) {
2709
0
    return;
2710
0
  }
2711
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
2712
0
  if (!checkDNSQuestionType(__func__, dnsQuestion)) {
2713
0
    return;
2714
0
  }
2715
2716
0
  if (!dnsQuestion->pbfMetaValueWriter.valid()) {
2717
0
    VERBOSESLOG(infolog("Error in dnsdist_ffi_dnsquestion_meta_add_str_value_to_key: trying to add a value without starting a key"),
2718
0
                getLogger(__func__)->info(Logr::Info, "Error adding a new meta value: the key has not been started"));
2719
0
    return;
2720
0
  }
2721
2722
0
  dnsQuestion->pbfMetaValueWriter.add_string(static_cast<protozero::pbf_tag_type>(pdns::ProtoZero::Message::MetaValueField::stringVal), protozero::data_view(value, valueLen));
2723
0
#endif /* DISABLE_PROTOBUF */
2724
0
}
2725
2726
void dnsdist_ffi_dnsquestion_meta_add_int64_value_to_key([[maybe_unused]] dnsdist_ffi_dnsquestion_t* dnsQuestion, [[maybe_unused]] int64_t value)
2727
0
{
2728
0
#if !defined(DISABLE_PROTOBUF)
2729
0
  if (dnsQuestion == nullptr) {
2730
0
    return;
2731
0
  }
2732
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
2733
0
  if (!checkDNSQuestionType(__func__, dnsQuestion)) {
2734
0
    return;
2735
0
  }
2736
2737
0
  if (!dnsQuestion->pbfMetaValueWriter.valid()) {
2738
0
    VERBOSESLOG(infolog("Error in dnsdist_ffi_dnsquestion_meta_add_int64_value_to_key: trying to add a value without starting a key"),
2739
0
                getLogger(__func__)->info(Logr::Info, "Error adding a new meta value: the key has not been started"));
2740
0
    return;
2741
0
  }
2742
2743
0
  dnsQuestion->pbfMetaValueWriter.add_uint64(static_cast<protozero::pbf_tag_type>(pdns::ProtoZero::Message::MetaValueField::intVal), value);
2744
0
#endif /* DISABLE_PROTOBUF */
2745
0
}
2746
2747
void dnsdist_ffi_dnsquestion_meta_end_key([[maybe_unused]] dnsdist_ffi_dnsquestion_t* dnsQuestion)
2748
0
{
2749
0
#if !defined(DISABLE_PROTOBUF)
2750
0
  if (dnsQuestion == nullptr) {
2751
0
    return;
2752
0
  }
2753
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
2754
0
  if (!checkDNSQuestionType(__func__, dnsQuestion)) {
2755
0
    return;
2756
0
  }
2757
2758
0
  if (!dnsQuestion->pbfWriter.valid()) {
2759
0
    VERBOSESLOG(infolog("Error in dnsdist_ffi_dnsquestion_meta_end_key: trying to end a key that has not been started"),
2760
0
                getLogger(__func__)->info(Logr::Info, "Error ending meta key: the key has not been started"));
2761
0
    return;
2762
0
  }
2763
2764
0
  try {
2765
    /* reset the pbf writer so that the sizes are properly updated */
2766
0
    dnsQuestion->pbfMetaValueWriter.commit();
2767
0
    dnsQuestion->pbfMetaWriter.commit();
2768
0
    dnsQuestion->pbfWriter = protozero::pbf_writer();
2769
0
  }
2770
0
  catch (const std::exception& exp) {
2771
0
    VERBOSESLOG(infolog("Error in dnsdist_ffi_dnsquestion_meta_end_key: %s", exp.what()),
2772
0
                getLogger(__func__)->error(Logr::Error, exp.what(), "Exception while ending meta key"));
2773
0
  }
2774
0
#endif /* DISABLE_PROTOBUF */
2775
0
}
2776
2777
void dnsdist_ffi_dnsresponse_meta_begin_key([[maybe_unused]] dnsdist_ffi_dnsresponse_t* dnsResponse, [[maybe_unused]] const char* key, [[maybe_unused]] size_t keyLen)
2778
0
{
2779
0
#if !defined(DISABLE_PROTOBUF)
2780
0
  if (dnsResponse == nullptr || key == nullptr || keyLen == 0) {
2781
0
    return;
2782
0
  }
2783
2784
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
2785
0
  if (!checkDNSResponseType(__func__, dnsResponse)) {
2786
0
    return;
2787
0
  }
2788
2789
0
  if (dnsResponse->pbfWriter.valid()) {
2790
0
    VERBOSESLOG(infolog("Error in dnsdist_ffi_dnsresponse_meta_begin_key: the previous key has not been ended"),
2791
0
                getLogger(__func__)->info(Logr::Info, "Error ending meta key for response : the previous key has not been ended"));
2792
0
    return;
2793
0
  }
2794
2795
0
  dnsResponse->pbfWriter = protozero::pbf_writer{dnsResponse->dr->ids.d_rawProtobufContent};
2796
0
  dnsResponse->pbfMetaWriter = protozero::pbf_writer{dnsResponse->pbfWriter, static_cast<protozero::pbf_tag_type>(pdns::ProtoZero::Message::Field::meta)};
2797
0
  dnsResponse->pbfMetaWriter.add_string(static_cast<protozero::pbf_tag_type>(pdns::ProtoZero::Message::MetaField::key), protozero::data_view(key, keyLen));
2798
0
  dnsResponse->pbfMetaValueWriter = protozero::pbf_writer{dnsResponse->pbfMetaWriter, static_cast<protozero::pbf_tag_type>(pdns::ProtoZero::Message::MetaField::value)};
2799
0
#endif /* DISABLE_PROTOBUF */
2800
0
}
2801
2802
void dnsdist_ffi_dnsresponse_meta_add_str_value_to_key([[maybe_unused]] dnsdist_ffi_dnsresponse_t* dnsResponse, [[maybe_unused]] const char* value, [[maybe_unused]] size_t valueLen)
2803
0
{
2804
0
#if !defined(DISABLE_PROTOBUF)
2805
0
  if (dnsResponse == nullptr || value == nullptr || valueLen == 0) {
2806
0
    return;
2807
0
  }
2808
2809
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
2810
0
  if (!checkDNSResponseType(__func__, dnsResponse)) {
2811
0
    return;
2812
0
  }
2813
2814
0
  if (!dnsResponse->pbfMetaValueWriter.valid()) {
2815
0
    VERBOSESLOG(infolog("Error in dnsdist_ffi_dnsresponse_meta_add_str_value_to_key: trying to add a value without starting a key"),
2816
0
                getLogger(__func__)->info(Logr::Info, "Error adding meta value: the key has not been started"));
2817
0
    return;
2818
0
  }
2819
2820
0
  dnsResponse->pbfMetaValueWriter.add_string(static_cast<protozero::pbf_tag_type>(pdns::ProtoZero::Message::MetaValueField::stringVal), protozero::data_view(value, valueLen));
2821
0
#endif /* DISABLE_PROTOBUF */
2822
0
}
2823
2824
void dnsdist_ffi_dnsresponse_meta_add_int64_value_to_key([[maybe_unused]] dnsdist_ffi_dnsresponse_t* dnsResponse, [[maybe_unused]] int64_t value)
2825
0
{
2826
0
#if !defined(DISABLE_PROTOBUF)
2827
0
  if (dnsResponse == nullptr) {
2828
0
    return;
2829
0
  }
2830
2831
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
2832
0
  if (!checkDNSResponseType(__func__, dnsResponse)) {
2833
0
    return;
2834
0
  }
2835
2836
0
  if (!dnsResponse->pbfMetaValueWriter.valid()) {
2837
0
    VERBOSESLOG(infolog("Error in dnsdist_ffi_dnsresponse_meta_add_int64_value_to_key: trying to add a value without starting a key"),
2838
0
                getLogger(__func__)->info(Logr::Info, "Error adding meta value: the key has not been started"));
2839
0
    return;
2840
0
  }
2841
2842
0
  dnsResponse->pbfMetaValueWriter.add_uint64(static_cast<protozero::pbf_tag_type>(pdns::ProtoZero::Message::MetaValueField::intVal), value);
2843
0
#endif /* DISABLE_PROTOBUF */
2844
0
}
2845
2846
void dnsdist_ffi_dnsresponse_meta_end_key([[maybe_unused]] dnsdist_ffi_dnsresponse_t* dnsResponse)
2847
0
{
2848
0
#if !defined(DISABLE_PROTOBUF)
2849
0
  if (dnsResponse == nullptr) {
2850
0
    return;
2851
0
  }
2852
2853
  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
2854
0
  if (!checkDNSResponseType(__func__, dnsResponse)) {
2855
0
    return;
2856
0
  }
2857
2858
0
  if (!dnsResponse->pbfWriter.valid()) {
2859
0
    VERBOSESLOG(infolog("Error in dnsdist_ffi_dnsresponse_meta_end_key: trying to end a key that has not been started"),
2860
0
                getLogger(__func__)->info(Logr::Info, "Error ending meta key: the key has not been started"));
2861
0
    return;
2862
0
  }
2863
2864
0
  try {
2865
    /* reset the pbf writer so that the sizes are properly updated */
2866
0
    dnsResponse->pbfMetaValueWriter.commit();
2867
0
    dnsResponse->pbfMetaWriter.commit();
2868
0
    dnsResponse->pbfWriter = protozero::pbf_writer();
2869
0
  }
2870
0
  catch (const std::exception& exp) {
2871
0
    VERBOSESLOG(infolog("Error in dnsdist_ffi_dnsresponse_meta_end_key: %s", exp.what()),
2872
0
                getLogger(__func__)->error(Logr::Error, exp.what(), "Exception while ending meta key"));
2873
0
  }
2874
0
#endif /* DISABLE_PROTOBUF */
2875
0
}