Coverage Report

Created: 2026-12-01 06:11

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/pdns/pdns/dnsdistdist/misc.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 "config.h"
24
25
#include <sys/param.h>
26
#include <sys/socket.h>
27
#include <sys/stat.h>
28
#include <fcntl.h>
29
#include <netdb.h>
30
#include <sys/time.h>
31
#include <ctime>
32
#include <sys/resource.h>
33
#include <netinet/in.h>
34
#include <sys/un.h>
35
#include <unistd.h>
36
#include <fstream>
37
#include "misc.hh"
38
#include <vector>
39
#include <string>
40
#include <sstream>
41
#include <cerrno>
42
#include <cstring>
43
#include <iostream>
44
#include <sys/types.h>
45
#include <dirent.h>
46
#include <algorithm>
47
#include <poll.h>
48
#include <iomanip>
49
#include <netinet/tcp.h>
50
#include <optional>
51
#include <cstdlib>
52
#include <cstdio>
53
#include "pdnsexception.hh"
54
#include <boost/algorithm/string.hpp>
55
#include <boost/format.hpp>
56
#include "iputils.hh"
57
#include "dns_random.hh"
58
#include "logger.hh"
59
#include "logging.hh"
60
#include <pwd.h>
61
#include <grp.h>
62
#include <unordered_map>
63
#ifdef __FreeBSD__
64
#include <pthread_np.h>
65
#endif
66
#ifdef __NetBSD__
67
#include <pthread.h>
68
#include <sched.h>
69
#endif
70
71
#if defined(HAVE_LIBCRYPTO)
72
#include <openssl/err.h>
73
#endif // HAVE_LIBCRYPTO
74
75
// NOLINTBEGIN(cppcoreguidelines-pro-bounds-pointer-arithmetic,cppcoreguidelines-pro-type-reinterpret-cast)
76
77
size_t writen2(int fileDesc, const void* buf, size_t count)
78
0
{
79
0
  const char* ptr = static_cast<const char*>(buf);
80
0
  const char* eptr = ptr + count;
81
82
0
  while (ptr != eptr) {
83
0
    auto res = ::write(fileDesc, ptr, eptr - ptr);
84
0
    if (res < 0) {
85
0
      if (errno == EAGAIN) {
86
0
        throw std::runtime_error("used writen2 on non-blocking socket, got EAGAIN");
87
0
      }
88
0
      unixDie("failed in writen2");
89
0
    }
90
0
    else if (res == 0) {
91
0
      throw std::runtime_error("could not write all bytes, got eof in writen2");
92
0
    }
93
94
0
    ptr += res;
95
0
  }
96
97
0
  return count;
98
0
}
99
100
size_t readn2(int fileDesc, void* buffer, size_t len)
101
0
{
102
0
  size_t pos = 0;
103
104
0
  for (;;) {
105
0
    auto res = read(fileDesc, static_cast<char*>(buffer) + pos, len - pos); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic): it's the API
106
0
    if (res == 0) {
107
0
      throw runtime_error("EOF while reading message");
108
0
    }
109
0
    if (res < 0) {
110
0
      if (errno == EAGAIN) {
111
0
        throw std::runtime_error("used readn2 on non-blocking socket, got EAGAIN");
112
0
      }
113
0
      unixDie("failed in readn2");
114
0
    }
115
116
0
    pos += static_cast<size_t>(res);
117
0
    if (pos == len) {
118
0
      break;
119
0
    }
120
0
  }
121
0
  return len;
122
0
}
123
124
size_t readn2WithTimeout(int fileDesc, void* buffer, size_t len, const struct timeval& idleTimeout, const struct timeval& totalTimeout, bool allowIncomplete)
125
0
{
126
0
  size_t pos = 0;
127
0
  struct timeval start{0, 0};
128
0
  struct timeval remainingTime = totalTimeout;
129
0
  if (totalTimeout.tv_sec != 0 || totalTimeout.tv_usec != 0) {
130
0
    gettimeofday(&start, nullptr);
131
0
  }
132
133
0
  do {
134
0
    ssize_t got = read(fileDesc, static_cast<char*>(buffer) + pos, len - pos);
135
0
    if (got > 0) {
136
0
      pos += (size_t)got;
137
0
      if (allowIncomplete) {
138
0
        break;
139
0
      }
140
0
    }
141
0
    else if (got == 0) {
142
0
      throw runtime_error("EOF while reading message");
143
0
    }
144
0
    else {
145
0
      if (errno == EAGAIN) {
146
0
        struct timeval waitTime = ((totalTimeout.tv_sec == 0 && totalTimeout.tv_usec == 0) || idleTimeout <= remainingTime) ? idleTimeout : remainingTime;
147
0
        int res = waitForData(fileDesc, waitTime);
148
0
        if (res > 0) {
149
          /* there is data available */
150
0
        }
151
0
        else if (res == 0) {
152
0
          throw runtime_error("Timeout while waiting for data to read");
153
0
        }
154
0
        else {
155
0
          throw runtime_error("Error while waiting for data to read");
156
0
        }
157
0
      }
158
0
      else {
159
0
        unixDie("failed in readn2WithTimeout");
160
0
      }
161
0
    }
162
163
0
    if (totalTimeout.tv_sec != 0 || totalTimeout.tv_usec != 0) {
164
0
      struct timeval now{};
165
0
      gettimeofday(&now, nullptr);
166
0
      struct timeval elapsed = now - start;
167
0
      if (remainingTime < elapsed) {
168
0
        throw runtime_error("Timeout while reading data");
169
0
      }
170
0
      start = now;
171
0
      remainingTime = remainingTime - elapsed;
172
0
    }
173
0
  } while (pos < len);
174
175
0
  return len;
176
0
}
177
178
size_t writen2WithTimeout(int fileDesc, const void* buffer, size_t len, const struct timeval& timeout)
179
0
{
180
0
  size_t pos = 0;
181
0
  do {
182
0
    ssize_t written = write(fileDesc, reinterpret_cast<const char*>(buffer) + pos, len - pos);
183
184
0
    if (written > 0) {
185
0
      pos += (size_t)written;
186
0
    }
187
0
    else if (written == 0) {
188
0
      throw runtime_error("EOF while writing message");
189
0
    }
190
0
    else {
191
0
      if (errno == EAGAIN) {
192
0
        int res = waitForRWData(fileDesc, false, timeout);
193
0
        if (res > 0) {
194
          /* there is room available */
195
0
        }
196
0
        else if (res == 0) {
197
0
          throw runtime_error("Timeout while waiting to write data");
198
0
        }
199
0
        else {
200
0
          throw runtime_error("Error while waiting for room to write data");
201
0
        }
202
0
      }
203
0
      else {
204
0
        unixDie("failed in write2WithTimeout");
205
0
      }
206
0
    }
207
0
  } while (pos < len);
208
209
0
  return len;
210
0
}
211
212
auto pdns::getMessageFromErrno(const int errnum) -> std::string
213
0
{
214
0
  const size_t errLen = 2048;
215
0
  std::string errMsgData{};
216
0
  errMsgData.resize(errLen);
217
218
0
  const char* errMsg = nullptr;
219
0
#ifdef STRERROR_R_CHAR_P
220
0
  errMsg = strerror_r(errnum, errMsgData.data(), errMsgData.length());
221
#else
222
  // This can fail, and when it does, it sets errno. We ignore that and
223
  // set our own error message instead.
224
  int res = strerror_r(errnum, errMsgData.data(), errMsgData.length());
225
  errMsg = errMsgData.c_str();
226
  if (res != 0) {
227
    errMsg = "Unknown (the exact error could not be retrieved)";
228
  }
229
#endif
230
231
  // We make a copy here because `strerror_r()` might return a static
232
  // immutable buffer for an error message. The copy shouldn't be
233
  // critical though, we're on the bailout/error-handling path anyways.
234
0
  std::string message{errMsg};
235
0
  return message;
236
0
}
237
238
#if defined(HAVE_LIBCRYPTO)
239
auto pdns::OpenSSL::error(const std::string& errorMessage) -> std::runtime_error
240
0
{
241
0
  unsigned long errorCode = 0;
242
0
  auto fullErrorMessage{errorMessage};
243
0
#if OPENSSL_VERSION_MAJOR >= 3
244
0
  const char* filename = nullptr;
245
0
  const char* functionName = nullptr;
246
0
  int lineNumber = 0;
247
0
  while ((errorCode = ERR_get_error_all(&filename, &lineNumber, &functionName, nullptr, nullptr)) != 0) {
248
0
    fullErrorMessage += std::string(": ") + std::to_string(errorCode);
249
250
0
    const auto* lib = ERR_lib_error_string(errorCode);
251
0
    if (lib != nullptr) {
252
0
      fullErrorMessage += std::string(":") + lib;
253
0
    }
254
255
0
    const auto* reason = ERR_reason_error_string(errorCode);
256
0
    if (reason != nullptr) {
257
0
      fullErrorMessage += std::string("::") + reason;
258
0
    }
259
260
0
    if (filename != nullptr) {
261
0
      fullErrorMessage += std::string(" - ") + filename;
262
0
    }
263
0
    if (lineNumber != 0) {
264
0
      fullErrorMessage += std::string(":") + std::to_string(lineNumber);
265
0
    }
266
0
    if (functionName != nullptr) {
267
0
      fullErrorMessage += std::string(" - ") + functionName;
268
0
    }
269
0
  }
270
#else
271
  while ((errorCode = ERR_get_error()) != 0) {
272
    fullErrorMessage += std::string(": ") + std::to_string(errorCode);
273
274
    const auto* lib = ERR_lib_error_string(errorCode);
275
    if (lib != nullptr) {
276
      fullErrorMessage += std::string(":") + lib;
277
    }
278
279
    const auto* func = ERR_func_error_string(errorCode);
280
    if (func != nullptr) {
281
      fullErrorMessage += std::string(":") + func;
282
    }
283
284
    const auto* reason = ERR_reason_error_string(errorCode);
285
    if (reason != nullptr) {
286
      fullErrorMessage += std::string("::") + reason;
287
    }
288
  }
289
#endif
290
0
  return std::runtime_error{fullErrorMessage};
291
0
}
292
293
auto pdns::OpenSSL::error(const std::string& componentName, const std::string& errorMessage) -> std::runtime_error
294
0
{
295
0
  return pdns::OpenSSL::error(componentName + ": " + errorMessage);
296
0
}
297
#endif // HAVE_LIBCRYPTO
298
299
string nowTime()
300
0
{
301
0
  time_t now = time(nullptr);
302
0
  struct tm theTime{};
303
0
  localtime_r(&now, &theTime);
304
0
  std::array<char, 30> buffer{};
305
  // YYYY-mm-dd HH:MM:SS TZOFF
306
0
  size_t ret = strftime(buffer.data(), buffer.size(), "%F %T %z", &theTime);
307
0
  if (ret == 0) {
308
0
    buffer[0] = '\0';
309
0
  }
310
0
  return {buffer.data()};
311
0
}
312
313
// returns -1 in case if error, 0 if no data is available, 1 if there is. In the first two cases, errno is set
314
int waitForData(int fileDesc, int seconds, int mseconds)
315
0
{
316
0
  return waitForRWData(fileDesc, true, seconds, mseconds);
317
0
}
318
319
int waitForData(int fileDesc, struct timeval timeout)
320
0
{
321
0
  return waitForRWData(fileDesc, true, timeout);
322
0
}
323
324
int waitForRWData(int fileDesc, bool waitForRead, int seconds, int mseconds, bool* error, bool* disconnected)
325
0
{
326
0
  struct pollfd pfd{};
327
0
  memset(&pfd, 0, sizeof(pfd));
328
0
  pfd.fd = fileDesc;
329
330
0
  if (waitForRead) {
331
0
    pfd.events = POLLIN;
332
0
  }
333
0
  else {
334
0
    pfd.events = POLLOUT;
335
0
  }
336
337
0
  int ret = poll(&pfd, 1, (seconds * 1000) + mseconds);
338
0
  if (ret > 0) {
339
0
    if ((error != nullptr) && (pfd.revents & POLLERR) != 0) {
340
0
      *error = true;
341
0
    }
342
0
    if ((disconnected != nullptr) && (pfd.revents & POLLHUP) != 0) {
343
0
      *disconnected = true;
344
0
    }
345
0
  }
346
347
0
  return ret;
348
0
}
349
350
int waitForRWData(int fileDesc, bool waitForRead, struct timeval timeout, bool* error, bool* disconnected)
351
0
{
352
0
  return waitForRWData(fileDesc, waitForRead, static_cast<int>(timeout.tv_sec), static_cast<int>(timeout.tv_usec / 1000), error, disconnected);
353
0
}
354
355
// returns -1 in case of error, 0 if no data is available, 1 if there is. In the first two cases, errno is set
356
int waitForMultiData(const set<int>& fds, const int seconds, const int mseconds, int* fdOut)
357
0
{
358
0
  set<int> realFDs;
359
0
  for (const auto& anFd : fds) {
360
0
    if (anFd >= 0 && realFDs.count(anFd) == 0) {
361
0
      realFDs.insert(anFd);
362
0
    }
363
0
  }
364
365
0
  std::vector<struct pollfd> pfds(realFDs.size());
366
0
  memset(pfds.data(), 0, realFDs.size() * sizeof(struct pollfd));
367
0
  int ctr = 0;
368
0
  for (const auto& anFd : realFDs) {
369
0
    pfds[ctr].fd = anFd;
370
0
    pfds[ctr].events = POLLIN;
371
0
    ctr++;
372
0
  }
373
374
0
  int ret{};
375
0
  if (seconds >= 0) {
376
0
    ret = poll(pfds.data(), realFDs.size(), (seconds * 1000) + mseconds);
377
0
  }
378
0
  else {
379
0
    ret = poll(pfds.data(), realFDs.size(), -1);
380
0
  }
381
0
  if (ret <= 0) {
382
0
    return ret;
383
0
  }
384
385
0
  set<int> pollinFDs;
386
0
  for (const auto& pfd : pfds) {
387
0
    if ((pfd.revents & POLLIN) != 0) {
388
0
      pollinFDs.insert(pfd.fd);
389
0
    }
390
0
  }
391
0
  auto iter(pollinFDs.begin());
392
0
  advance(iter, dns_random(pollinFDs.size()));
393
0
  *fdOut = *iter;
394
0
  return 1;
395
0
}
396
397
string humanDuration(time_t passed)
398
0
{
399
0
  ostringstream ret;
400
0
  if (passed < 60) {
401
0
    ret << passed << " seconds";
402
0
  }
403
0
  else if (passed < 3600) {
404
0
    ret << std::setprecision(2) << static_cast<double>(passed) / 60.0 << " minutes";
405
0
  }
406
0
  else if (passed < 86400) {
407
0
    ret << std::setprecision(3) << static_cast<double>(passed) / 3600.0 << " hours";
408
0
  }
409
0
  else if (static_cast<double>(passed) < (86400 * 30.41)) {
410
0
    ret << std::setprecision(3) << static_cast<double>(passed) / 86400.0 << " days";
411
0
  }
412
0
  else {
413
0
    ret << std::setprecision(3) << static_cast<double>(passed) / (86400 * 30.41) << " months";
414
0
  }
415
416
0
  return ret.str();
417
0
}
418
419
string unquotify(const string& item)
420
0
{
421
0
  if (item.size() < 2) {
422
0
    return item;
423
0
  }
424
425
0
  string::size_type bpos = 0;
426
0
  string::size_type epos = item.size();
427
428
0
  if (item[0] == '"') {
429
0
    bpos = 1;
430
0
  }
431
432
0
  if (item[epos - 1] == '"') {
433
0
    epos -= 1;
434
0
  }
435
436
0
  return item.substr(bpos, epos - bpos);
437
0
}
438
439
void stripLine(string& line)
440
0
{
441
0
  string::size_type pos = line.find_first_of("\r\n");
442
0
  if (pos != string::npos) {
443
0
    line.resize(pos);
444
0
  }
445
0
}
446
447
string urlEncode(const string& text)
448
0
{
449
0
  string ret;
450
0
  for (char index : text) {
451
0
    if (index == ' ') {
452
0
      ret.append("%20");
453
0
    }
454
0
    else {
455
0
      ret.append(1, index);
456
0
    }
457
0
  }
458
0
  return ret;
459
0
}
460
461
static size_t getMaxHostNameSize()
462
6
{
463
6
#if defined(HOST_NAME_MAX)
464
6
  return HOST_NAME_MAX;
465
0
#endif
466
467
0
  const size_t maxHostNameSize = 255;
468
0
#if defined(_SC_HOST_NAME_MAX)
469
0
  return pdns::sysconf(_SC_HOST_NAME_MAX, maxHostNameSize);
470
0
#endif
471
472
0
  return maxHostNameSize;
473
6
}
474
475
std::optional<string> getHostname()
476
6
{
477
6
  const size_t maxHostNameBufSize = getMaxHostNameSize() + 1;
478
6
  std::string hostname;
479
6
  hostname.resize(maxHostNameBufSize, 0);
480
481
6
  if (gethostname(hostname.data(), maxHostNameBufSize) == -1) {
482
0
    return std::nullopt;
483
0
  }
484
485
6
  hostname.resize(strlen(hostname.c_str()));
486
6
  return std::make_optional(hostname);
487
6
}
488
489
std::string getCarbonHostName()
490
0
{
491
0
  auto hostname = getHostname();
492
0
  if (!hostname.has_value()) {
493
0
    throw std::runtime_error(stringerror());
494
0
  }
495
496
0
  std::replace(hostname->begin(), hostname->end(), '.', '_');
497
0
  return *hostname;
498
0
}
499
500
void cleanSlashes(string& str)
501
0
{
502
0
  string out;
503
0
  bool keepNextSlash = true;
504
0
  for (const auto& value : str) {
505
0
    if (value == '/') {
506
0
      if (keepNextSlash) {
507
0
        keepNextSlash = false;
508
0
      }
509
0
      else {
510
0
        continue;
511
0
      }
512
0
    }
513
0
    else {
514
0
      keepNextSlash = true;
515
0
    }
516
0
    out.append(1, value);
517
0
  }
518
0
  str = std::move(out);
519
0
}
520
521
bool IpToU32(const string& str, uint32_t* ptr)
522
0
{
523
0
  if (str.empty()) {
524
0
    *ptr = 0;
525
0
    return true;
526
0
  }
527
528
0
  struct in_addr inp{};
529
0
  if (inet_aton(str.c_str(), &inp) != 0) {
530
0
    *ptr = inp.s_addr;
531
0
    return true;
532
0
  }
533
0
  return false;
534
0
}
535
536
string U32ToIP(uint32_t val)
537
0
{
538
0
  std::array<char, 17> tmp{};
539
0
  snprintf(tmp.data(), tmp.size(), "%u.%u.%u.%u",
540
0
           (val >> 24) & 0xff,
541
0
           (val >> 16) & 0xff,
542
0
           (val >> 8) & 0xff,
543
0
           (val) & 0xff);
544
0
  return tmp.data();
545
0
}
546
547
string makeHexDump(const string& str, const string& sep)
548
1.08k
{
549
1.08k
  std::array<char, 5> tmp{};
550
1.08k
  string ret;
551
1.08k
  ret.reserve(static_cast<size_t>(str.size() * (2 + sep.size())));
552
553
4.81M
  for (char index : str) {
554
4.81M
    snprintf(tmp.data(), tmp.size(), "%02x", static_cast<unsigned char>(index));
555
4.81M
    ret += tmp.data();
556
4.81M
    ret += sep;
557
4.81M
  }
558
1.08k
  return ret;
559
1.08k
}
560
561
string makeBytesFromHex(const string& str)
562
0
{
563
0
  if (str.size() % 2 != 0) {
564
0
    throw std::range_error("odd number of bytes in hex string");
565
0
  }
566
0
  string ret;
567
0
  ret.reserve(str.size() / 2);
568
569
0
  for (size_t i = 0; i < str.size(); i += 2) {
570
0
    const auto numStr = str.substr(i, 2);
571
0
    unsigned int num = 0;
572
0
    if (sscanf(numStr.c_str(), "%02x", &num) != 1) {
573
0
      throw std::range_error("Invalid value while parsing the hex string '" + str + "'");
574
0
    }
575
0
    ret.push_back(static_cast<char>(num));
576
0
  }
577
578
0
  return ret;
579
0
}
580
581
void normalizeTV(struct timeval& timeval)
582
0
{
583
0
  if (timeval.tv_usec > 1000000) {
584
0
    ++timeval.tv_sec;
585
0
    timeval.tv_usec -= 1000000;
586
0
  }
587
0
  else if (timeval.tv_usec < 0) {
588
0
    --timeval.tv_sec;
589
0
    timeval.tv_usec += 1000000;
590
0
  }
591
0
}
592
593
struct timeval operator+(const struct timeval& lhs, const struct timeval& rhs)
594
0
{
595
0
  struct timeval ret{};
596
0
  ret.tv_sec = lhs.tv_sec + rhs.tv_sec;
597
0
  ret.tv_usec = lhs.tv_usec + rhs.tv_usec;
598
0
  normalizeTV(ret);
599
0
  return ret;
600
0
}
601
602
struct timeval operator-(const struct timeval& lhs, const struct timeval& rhs)
603
0
{
604
0
  struct timeval ret{};
605
0
  ret.tv_sec = lhs.tv_sec - rhs.tv_sec;
606
0
  ret.tv_usec = lhs.tv_usec - rhs.tv_usec;
607
0
  normalizeTV(ret);
608
0
  return ret;
609
0
}
610
611
pair<string, string> splitField(const string& inp, char sepa)
612
23.4k
{
613
23.4k
  pair<string, string> ret;
614
23.4k
  string::size_type cpos = inp.find(sepa);
615
23.4k
  if (cpos == string::npos) {
616
0
    ret.first = inp;
617
0
  }
618
23.4k
  else {
619
23.4k
    ret.first = inp.substr(0, cpos);
620
23.4k
    ret.second = inp.substr(cpos + 1);
621
23.4k
  }
622
23.4k
  return ret;
623
23.4k
}
624
625
int logFacilityToLOG(unsigned int facility)
626
0
{
627
0
  switch (facility) {
628
0
  case 0:
629
0
    return LOG_LOCAL0;
630
0
  case 1:
631
0
    return (LOG_LOCAL1);
632
0
  case 2:
633
0
    return (LOG_LOCAL2);
634
0
  case 3:
635
0
    return (LOG_LOCAL3);
636
0
  case 4:
637
0
    return (LOG_LOCAL4);
638
0
  case 5:
639
0
    return (LOG_LOCAL5);
640
0
  case 6:
641
0
    return (LOG_LOCAL6);
642
0
  case 7:
643
0
    return (LOG_LOCAL7);
644
0
  default:
645
0
    return -1;
646
0
  }
647
0
}
648
649
std::optional<int> logFacilityFromString(std::string facilityStr)
650
0
{
651
0
  static std::unordered_map<std::string, int> const s_facilities = {
652
0
    {"local0", LOG_LOCAL0},
653
0
    {"log_local0", LOG_LOCAL0},
654
0
    {"local1", LOG_LOCAL1},
655
0
    {"log_local1", LOG_LOCAL1},
656
0
    {"local2", LOG_LOCAL2},
657
0
    {"log_local2", LOG_LOCAL2},
658
0
    {"local3", LOG_LOCAL3},
659
0
    {"log_local3", LOG_LOCAL3},
660
0
    {"local4", LOG_LOCAL4},
661
0
    {"log_local4", LOG_LOCAL4},
662
0
    {"local5", LOG_LOCAL5},
663
0
    {"log_local5", LOG_LOCAL5},
664
0
    {"local6", LOG_LOCAL6},
665
0
    {"log_local6", LOG_LOCAL6},
666
0
    {"local7", LOG_LOCAL7},
667
0
    {"log_local7", LOG_LOCAL7},
668
    /* most of these likely make very little sense
669
       for us, but why not? */
670
0
    {"kern", LOG_KERN},
671
0
    {"log_kern", LOG_KERN},
672
0
    {"user", LOG_USER},
673
0
    {"log_user", LOG_USER},
674
0
    {"mail", LOG_MAIL},
675
0
    {"log_mail", LOG_MAIL},
676
0
    {"daemon", LOG_DAEMON},
677
0
    {"log_daemon", LOG_DAEMON},
678
0
    {"auth", LOG_AUTH},
679
0
    {"log_auth", LOG_AUTH},
680
0
    {"syslog", LOG_SYSLOG},
681
0
    {"log_syslog", LOG_SYSLOG},
682
0
    {"lpr", LOG_LPR},
683
0
    {"log_lpr", LOG_LPR},
684
0
    {"news", LOG_NEWS},
685
0
    {"log_news", LOG_NEWS},
686
0
    {"uucp", LOG_UUCP},
687
0
    {"log_uucp", LOG_UUCP},
688
0
    {"cron", LOG_CRON},
689
0
    {"log_cron", LOG_CRON},
690
0
    {"authpriv", LOG_AUTHPRIV},
691
0
    {"log_authpriv", LOG_AUTHPRIV},
692
0
    {"ftp", LOG_FTP},
693
0
    {"log_ftp", LOG_FTP}};
694
695
0
  toLowerInPlace(facilityStr);
696
0
  auto facilityIt = s_facilities.find(facilityStr);
697
0
  if (facilityIt == s_facilities.end()) {
698
0
    return std::nullopt;
699
0
  }
700
701
0
  return facilityIt->second;
702
0
}
703
704
string stripDot(const string& dom)
705
0
{
706
0
  if (dom.empty()) {
707
0
    return dom;
708
0
  }
709
710
0
  if (dom[dom.size() - 1] != '.') {
711
0
    return dom;
712
0
  }
713
714
0
  return dom.substr(0, dom.size() - 1);
715
0
}
716
717
int makeIPv6sockaddr(const std::string& addr, struct sockaddr_in6* ret)
718
141k
{
719
141k
  if (addr.empty()) {
720
43
    return -1;
721
43
  }
722
723
141k
  string ourAddr(addr);
724
141k
  std::optional<uint16_t> port = std::nullopt;
725
726
141k
  if (addr[0] == '[') { // [::]:53 style address
727
1.76k
    string::size_type pos = addr.find(']');
728
1.76k
    if (pos == string::npos) {
729
15
      return -1;
730
15
    }
731
732
1.74k
    ourAddr.assign(addr.c_str() + 1, pos - 1);
733
1.74k
    if (pos + 1 != addr.size()) { // complete after ], no port specified
734
1.54k
      if (pos + 2 > addr.size() || addr[pos + 1] != ':') {
735
38
        return -1;
736
38
      }
737
738
1.50k
      try {
739
1.50k
        auto tmpPort = pdns::checked_stoi<uint16_t>(addr.substr(pos + 2));
740
1.50k
        port = std::make_optional(tmpPort);
741
1.50k
      }
742
1.50k
      catch (const std::logic_error&) {
743
20
        return -1;
744
20
      }
745
1.50k
    }
746
1.74k
  }
747
748
141k
  ret->sin6_scope_id = 0;
749
141k
  ret->sin6_family = AF_INET6;
750
751
141k
  if (inet_pton(AF_INET6, ourAddr.c_str(), (void*)&ret->sin6_addr) != 1) {
752
4.00k
    struct addrinfo hints{};
753
4.00k
    std::memset(&hints, 0, sizeof(struct addrinfo));
754
4.00k
    hints.ai_flags = AI_NUMERICHOST;
755
4.00k
    hints.ai_family = AF_INET6;
756
757
4.00k
    struct addrinfo* res = nullptr;
758
    // getaddrinfo has anomalous return codes, anything nonzero is an error, positive or negative
759
4.00k
    if (getaddrinfo(ourAddr.c_str(), nullptr, &hints, &res) != 0) {
760
317
      return -1;
761
317
    }
762
763
3.68k
    memcpy(ret, res->ai_addr, res->ai_addrlen);
764
3.68k
    freeaddrinfo(res);
765
3.68k
  }
766
767
141k
  if (port.has_value()) {
768
1.42k
    ret->sin6_port = htons(*port);
769
1.42k
  }
770
771
141k
  return 0;
772
141k
}
773
774
int makeIPv4sockaddr(const std::string& arg, struct sockaddr_in* ret)
775
419k
{
776
419k
  std::string str(arg);
777
419k
  if (str.empty()) {
778
43
    return -1;
779
43
  }
780
419k
  struct in_addr inp{};
781
782
419k
  string::size_type pos = str.find(':');
783
419k
  if (pos == string::npos) { // no port specified, not touching the port
784
272k
    if (inet_aton(str.c_str(), &inp) != 0) {
785
272k
      ret->sin_addr.s_addr = inp.s_addr;
786
272k
      return 0;
787
272k
    }
788
73
    return -1;
789
272k
  }
790
147k
  if (*(str.c_str() + pos + 1) == 0) { // trailing :
791
18
    return -1;
792
18
  }
793
794
147k
  auto* eptr = str.data() + str.size();
795
147k
  int port = static_cast<int>(strtol(str.c_str() + pos + 1, &eptr, 10));
796
147k
  if (port < 0 || port > 65535) {
797
57
    return -1;
798
57
  }
799
147k
  if (*eptr != 0) {
800
141k
    return -1;
801
141k
  }
802
803
5.42k
  ret->sin_port = htons(port);
804
5.42k
  if (inet_aton(str.substr(0, pos).c_str(), &inp) != 0) {
805
5.29k
    ret->sin_addr.s_addr = inp.s_addr;
806
5.29k
    return 0;
807
5.29k
  }
808
130
  return -1;
809
5.42k
}
810
811
int makeUNsockaddr(const std::string& path, struct sockaddr_un* ret)
812
0
{
813
0
  if (path.empty()) {
814
0
    return -1;
815
0
  }
816
0
  memset(ret, 0, sizeof(struct sockaddr_un));
817
0
  ret->sun_family = AF_UNIX;
818
0
  if (path.length() >= sizeof(ret->sun_path)) {
819
0
    return -1;
820
0
  }
821
0
  path.copy(&ret->sun_path[0], sizeof(ret->sun_path), 0);
822
0
  return 0;
823
0
}
824
825
//! read a line of text from a FILE* to a std::string, returns false on 'no data'
826
bool stringfgets(FILE* file, std::string& line)
827
0
{
828
0
  std::array<char, 1024> buffer{};
829
0
  line.clear();
830
831
0
  do {
832
0
    if (fgets(buffer.data(), buffer.size(), file) == nullptr) {
833
0
      return !line.empty();
834
0
    }
835
0
    line.append(buffer.data());
836
0
  } while (strchr(buffer.data(), '\n') == nullptr);
837
0
  return true;
838
0
}
839
840
bool readFileIfThere(const char* fname, std::string* line)
841
0
{
842
0
  line->clear();
843
0
  auto filePtr = pdns::UniqueFilePtr(fopen(fname, "r"));
844
0
  if (!filePtr) {
845
0
    return false;
846
0
  }
847
0
  return stringfgets(filePtr.get(), *line);
848
0
}
849
850
Regex::Regex(const string& expr) :
851
0
  d_preg(new regex_t)
852
0
{
853
0
  if (auto ret = regcomp(d_preg.get(), expr.c_str(), REG_ICASE | REG_NOSUB | REG_EXTENDED); ret != 0) {
854
0
    std::array<char, 1024> errorBuffer{};
855
0
    if (regerror(ret, d_preg.get(), errorBuffer.data(), errorBuffer.size()) > 0) {
856
0
      throw PDNSException("Regular expression " + expr + " did not compile: " + errorBuffer.data());
857
0
    }
858
0
    throw PDNSException("Regular expression " + expr + " did not compile");
859
0
  }
860
0
}
861
862
/** call this to find out if 'line' matches your expression */
863
bool Regex::match(const string& line) const
864
0
{
865
0
  return regexec(d_preg.get(), line.c_str(), 0, nullptr, 0) == 0;
866
0
}
867
868
bool Regex::match(const DNSName& name) const
869
0
{
870
0
  return match(name.toStringNoDot());
871
0
}
872
873
// if you end up here because valgrind told you were are doing something wrong
874
// with msgh->msg_controllen, please refer to https://github.com/PowerDNS/pdns/pull/3962
875
// first.
876
// Note that cmsgbuf should be aligned the same as a struct cmsghdr
877
void addCMsgSrcAddr(struct msghdr* msgh, cmsgbuf_aligned* cmsgbuf, const ComboAddress* source, int itfIndex)
878
0
{
879
0
  struct cmsghdr* cmsg = nullptr;
880
881
0
  if (source->sin4.sin_family == AF_INET6) {
882
0
    struct in6_pktinfo* pkt{};
883
884
0
    msgh->msg_control = cmsgbuf;
885
0
#if !defined(__APPLE__)
886
    /* CMSG_SPACE is not a constexpr on macOS */
887
0
    static_assert(CMSG_SPACE(sizeof(*pkt)) <= sizeof(*cmsgbuf), "Buffer is too small for in6_pktinfo");
888
#else /* __APPLE__ */
889
    if (CMSG_SPACE(sizeof(*pkt)) > sizeof(*cmsgbuf)) {
890
      throw std::runtime_error("Buffer is too small for in6_pktinfo");
891
    }
892
#endif /* __APPLE__ */
893
0
    msgh->msg_controllen = CMSG_SPACE(sizeof(*pkt));
894
895
0
    cmsg = CMSG_FIRSTHDR(msgh);
896
0
    cmsg->cmsg_level = IPPROTO_IPV6;
897
0
    cmsg->cmsg_type = IPV6_PKTINFO;
898
0
    cmsg->cmsg_len = CMSG_LEN(sizeof(*pkt));
899
900
0
    pkt = reinterpret_cast<struct in6_pktinfo*>(CMSG_DATA(cmsg));
901
    // Include the padding to stop valgrind complaining about passing uninitialized data
902
0
    memset(pkt, 0, CMSG_SPACE(sizeof(*pkt)));
903
0
    pkt->ipi6_addr = source->sin6.sin6_addr;
904
0
    pkt->ipi6_ifindex = itfIndex;
905
0
  }
906
0
  else {
907
0
#if defined(IP_PKTINFO)
908
0
    struct in_pktinfo* pkt{};
909
910
0
    msgh->msg_control = cmsgbuf;
911
0
#if !defined(__APPLE__)
912
    /* CMSG_SPACE is not a constexpr on macOS */
913
0
    static_assert(CMSG_SPACE(sizeof(*pkt)) <= sizeof(*cmsgbuf), "Buffer is too small for in_pktinfo");
914
#else /* __APPLE__ */
915
    if (CMSG_SPACE(sizeof(*pkt)) > sizeof(*cmsgbuf)) {
916
      throw std::runtime_error("Buffer is too small for in_pktinfo");
917
    }
918
#endif /* __APPLE__ */
919
0
    msgh->msg_controllen = CMSG_SPACE(sizeof(*pkt));
920
921
0
    cmsg = CMSG_FIRSTHDR(msgh);
922
0
    cmsg->cmsg_level = IPPROTO_IP;
923
0
    cmsg->cmsg_type = IP_PKTINFO;
924
0
    cmsg->cmsg_len = CMSG_LEN(sizeof(*pkt));
925
926
0
    pkt = reinterpret_cast<struct in_pktinfo*>(CMSG_DATA(cmsg));
927
    // Include the padding to stop valgrind complaining about passing uninitialized data
928
0
    memset(pkt, 0, CMSG_SPACE(sizeof(*pkt)));
929
0
    pkt->ipi_spec_dst = source->sin4.sin_addr;
930
0
    pkt->ipi_ifindex = itfIndex;
931
#elif defined(IP_SENDSRCADDR)
932
    struct in_addr* in;
933
934
    msgh->msg_control = cmsgbuf;
935
#if !defined(__APPLE__)
936
    static_assert(CMSG_SPACE(sizeof(*in)) <= sizeof(*cmsgbuf), "Buffer is too small for in_addr");
937
#else /* __APPLE__ */
938
    if (CMSG_SPACE(sizeof(*in)) > sizeof(*cmsgbuf)) {
939
      throw std::runtime_error("Buffer is too small for in_addr");
940
    }
941
#endif /* __APPLE__ */
942
    msgh->msg_controllen = CMSG_SPACE(sizeof(*in));
943
944
    cmsg = CMSG_FIRSTHDR(msgh);
945
    cmsg->cmsg_level = IPPROTO_IP;
946
    cmsg->cmsg_type = IP_SENDSRCADDR;
947
    cmsg->cmsg_len = CMSG_LEN(sizeof(*in));
948
949
    // Include the padding to stop valgrind complaining about passing uninitialized data
950
    in = (struct in_addr*)CMSG_DATA(cmsg);
951
    memset(in, 0, CMSG_SPACE(sizeof(*in)));
952
    *in = source->sin4.sin_addr;
953
#endif
954
0
  }
955
0
}
956
957
unsigned int getFilenumLimit(bool hardOrSoft)
958
0
{
959
0
  struct rlimit rlim{};
960
0
  if (getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
961
0
    unixDie("Requesting number of available file descriptors");
962
0
  }
963
0
  return hardOrSoft ? rlim.rlim_max : rlim.rlim_cur;
964
0
}
965
966
void setFilenumLimit(unsigned int lim)
967
0
{
968
0
  struct rlimit rlim{};
969
970
0
  if (getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
971
0
    unixDie("Requesting number of available file descriptors");
972
0
  }
973
0
  rlim.rlim_cur = lim;
974
0
  if (setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
975
0
    unixDie("Setting number of available file descriptors");
976
0
  }
977
0
}
978
979
bool setSocketTimestamps(int fileDesc)
980
0
{
981
0
#ifdef SO_TIMESTAMP
982
0
  int one = 1;
983
0
  return setsockopt(fileDesc, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) == 0;
984
#else
985
  return true; // we pretend this happened.
986
#endif
987
0
}
988
989
bool setTCPNoDelay(int sock)
990
0
{
991
0
  int flag = 1;
992
0
  return setsockopt(sock, /* socket affected */
993
0
                    IPPROTO_TCP, /* set option at TCP level */
994
0
                    TCP_NODELAY, /* name of option */
995
0
                    &flag,
996
0
                    sizeof(flag))
997
0
    == 0; /* length of option value */
998
0
}
999
1000
bool setNonBlocking(int sock)
1001
0
{
1002
0
  int flags = fcntl(sock, F_GETFL, 0);
1003
0
  return flags >= 0 && fcntl(sock, F_SETFL, flags | O_NONBLOCK) >= 0;
1004
0
}
1005
1006
bool setBlocking(int sock)
1007
0
{
1008
0
  int flags = fcntl(sock, F_GETFL, 0);
1009
0
  return flags >= 0 && fcntl(sock, F_SETFL, flags & (~O_NONBLOCK)) >= 0;
1010
0
}
1011
1012
bool setReuseAddr(int sock)
1013
0
{
1014
0
  int tmp = 1;
1015
0
  if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &tmp, static_cast<unsigned>(sizeof tmp)) < 0) {
1016
0
    throw PDNSException(string("Setsockopt failed: ") + stringerror());
1017
0
  }
1018
0
  return true;
1019
0
}
1020
1021
void setDscp(int sock, unsigned short family, uint8_t dscp)
1022
0
{
1023
0
  int val = 0;
1024
0
  unsigned int len = 0;
1025
1026
0
  if (dscp == 0 || dscp > 63) {
1027
    // No DSCP marking
1028
0
    return;
1029
0
  }
1030
1031
0
  if (family == AF_INET) {
1032
0
    if (getsockopt(sock, IPPROTO_IP, IP_TOS, &val, &len) < 0) {
1033
0
      throw std::runtime_error(string("Set DSCP failed: ") + stringerror());
1034
0
    }
1035
0
    val = (dscp << 2) | (val & 0x3);
1036
0
    if (setsockopt(sock, IPPROTO_IP, IP_TOS, &val, sizeof(val)) < 0) {
1037
0
      throw std::runtime_error(string("Set DSCP failed: ") + stringerror());
1038
0
    }
1039
0
  }
1040
0
  else if (family == AF_INET6) {
1041
0
    if (getsockopt(sock, IPPROTO_IPV6, IPV6_TCLASS, &val, &len) < 0) {
1042
0
      throw std::runtime_error(string("Set DSCP failed: ") + stringerror());
1043
0
    }
1044
0
    val = (dscp << 2) | (val & 0x3);
1045
0
    if (setsockopt(sock, IPPROTO_IPV6, IPV6_TCLASS, &val, sizeof(val)) < 0) {
1046
0
      throw std::runtime_error(string("Set DSCP failed: ") + stringerror());
1047
0
    }
1048
0
  }
1049
0
}
1050
1051
bool isNonBlocking(int sock)
1052
0
{
1053
0
  int flags = fcntl(sock, F_GETFL, 0);
1054
0
  return (flags & O_NONBLOCK) != 0;
1055
0
}
1056
1057
bool setReceiveSocketErrors([[maybe_unused]] int sock, [[maybe_unused]] int family)
1058
0
{
1059
0
#ifdef __linux__
1060
0
  int tmp = 1;
1061
0
  int ret{};
1062
0
  if (family == AF_INET) {
1063
0
    ret = setsockopt(sock, IPPROTO_IP, IP_RECVERR, &tmp, sizeof(tmp));
1064
0
  }
1065
0
  else {
1066
0
    ret = setsockopt(sock, IPPROTO_IPV6, IPV6_RECVERR, &tmp, sizeof(tmp));
1067
0
  }
1068
0
  if (ret < 0) {
1069
0
    throw PDNSException(string("Setsockopt failed: ") + stringerror());
1070
0
  }
1071
0
#endif
1072
0
  return true;
1073
0
}
1074
1075
// Closes a socket.
1076
int closesocket(int socket)
1077
0
{
1078
0
  int ret = ::close(socket);
1079
0
  if (ret < 0 && errno == ECONNRESET) { // see ticket 192, odd BSD behaviour
1080
0
    return 0;
1081
0
  }
1082
0
  if (ret < 0) {
1083
0
    int err = errno;
1084
0
    throw PDNSException("Error closing socket: " + stringerror(err));
1085
0
  }
1086
0
  return ret;
1087
0
}
1088
1089
bool setCloseOnExec(int sock)
1090
0
{
1091
0
  int flags = fcntl(sock, F_GETFD, 0);
1092
0
  return flags >= 0 && fcntl(sock, F_SETFD, flags | FD_CLOEXEC) >= 0;
1093
0
}
1094
1095
#ifdef __linux__
1096
#include <linux/rtnetlink.h>
1097
1098
int getMACAddress(const ComboAddress& address, char* dest, size_t destLen)
1099
0
{
1100
0
  struct
1101
0
  {
1102
0
    struct nlmsghdr headermsg;
1103
0
    struct ndmsg neighbormsg;
1104
0
  } request{};
1105
1106
0
  std::array<char, 8192> buffer{};
1107
1108
0
  auto sock = FDWrapper(socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE));
1109
0
  if (sock.getHandle() == -1) {
1110
0
    return errno;
1111
0
  }
1112
1113
0
  memset(&request, 0, sizeof(request));
1114
0
  request.headermsg.nlmsg_len = NLMSG_LENGTH(sizeof(struct ndmsg));
1115
0
  request.headermsg.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
1116
0
  request.headermsg.nlmsg_type = RTM_GETNEIGH;
1117
0
  request.neighbormsg.ndm_family = address.sin4.sin_family;
1118
1119
0
  while (true) {
1120
0
    ssize_t sent = send(sock.getHandle(), &request, sizeof(request), 0);
1121
0
    if (sent == -1) {
1122
0
      if (errno == EINTR) {
1123
0
        continue;
1124
0
      }
1125
0
      return errno;
1126
0
    }
1127
0
    if (static_cast<size_t>(sent) != sizeof(request)) {
1128
0
      return EIO;
1129
0
    }
1130
0
    break;
1131
0
  }
1132
1133
0
  bool done = false;
1134
0
  bool foundIP = false;
1135
0
  bool foundMAC = false;
1136
0
  do {
1137
0
    ssize_t got = recv(sock.getHandle(), buffer.data(), buffer.size(), 0);
1138
1139
0
    if (got < 0) {
1140
0
      if (errno == EINTR) {
1141
0
        continue;
1142
0
      }
1143
0
      return errno;
1144
0
    }
1145
1146
0
    auto remaining = static_cast<size_t>(got);
1147
0
    for (auto* nlmsgheader = reinterpret_cast<struct nlmsghdr*>(buffer.data());
1148
0
         !done && NLMSG_OK(nlmsgheader, remaining);
1149
0
         nlmsgheader = reinterpret_cast<struct nlmsghdr*>(NLMSG_NEXT(nlmsgheader, remaining))) {
1150
1151
0
      if (nlmsgheader->nlmsg_type == NLMSG_DONE) {
1152
0
        done = true;
1153
0
        break;
1154
0
      }
1155
1156
0
      auto* ndmsg = reinterpret_cast<struct ndmsg*>(NLMSG_DATA(nlmsgheader));
1157
0
      auto* rtatp = reinterpret_cast<struct rtattr*>(reinterpret_cast<char*>(ndmsg) + NLMSG_ALIGN(sizeof(struct ndmsg)));
1158
0
      auto rtattrlen = nlmsgheader->nlmsg_len - NLMSG_LENGTH(sizeof(struct ndmsg));
1159
1160
0
      if (ndmsg->ndm_family != address.sin4.sin_family) {
1161
0
        continue;
1162
0
      }
1163
1164
0
      if (address.sin4.sin_family == AF_INET6 && address.sin6.sin6_scope_id != 0 && static_cast<int32_t>(address.sin6.sin6_scope_id) != ndmsg->ndm_ifindex) {
1165
0
        continue;
1166
0
      }
1167
1168
0
      for (; !done && RTA_OK(rtatp, rtattrlen); rtatp = RTA_NEXT(rtatp, rtattrlen)) {
1169
0
        if (rtatp->rta_type == NDA_DST) {
1170
0
          if (ndmsg->ndm_family == AF_INET) {
1171
0
            auto* inp = reinterpret_cast<struct in_addr*>(RTA_DATA(rtatp));
1172
0
            if (inp->s_addr == address.sin4.sin_addr.s_addr) {
1173
0
              foundIP = true;
1174
0
            }
1175
0
          }
1176
0
          else if (ndmsg->ndm_family == AF_INET6) {
1177
0
            auto* inp = reinterpret_cast<struct in6_addr*>(RTA_DATA(rtatp));
1178
0
            if (memcmp(&inp->s6_addr[0], &address.sin6.sin6_addr.s6_addr[0], sizeof(address.sin6.sin6_addr.s6_addr)) == 0) {
1179
0
              foundIP = true;
1180
0
            }
1181
0
          }
1182
0
        }
1183
0
        else if (rtatp->rta_type == NDA_LLADDR) {
1184
0
          if (foundIP) {
1185
0
            size_t addrLen = rtatp->rta_len - sizeof(struct rtattr);
1186
0
            if (addrLen > destLen) {
1187
0
              return ENOBUFS;
1188
0
            }
1189
0
            memcpy(dest, reinterpret_cast<const char*>(rtatp) + sizeof(struct rtattr), addrLen);
1190
0
            foundMAC = true;
1191
0
            done = true;
1192
0
            break;
1193
0
          }
1194
0
        }
1195
0
      }
1196
0
    }
1197
0
  } while (!done);
1198
1199
0
  return foundMAC ? 0 : ENOENT;
1200
0
}
1201
#else
1202
int getMACAddress(const ComboAddress& /* ca */, char* /* dest */, size_t /* len */)
1203
{
1204
  return ENOENT;
1205
}
1206
#endif /* __linux__ */
1207
1208
string getMACAddress(const ComboAddress& address)
1209
0
{
1210
0
  string ret;
1211
0
  std::array<char, 6> tmp{};
1212
0
  if (getMACAddress(address, tmp.data(), tmp.size()) == 0) {
1213
0
    ret.append(tmp.data(), tmp.size());
1214
0
  }
1215
0
  return ret;
1216
0
}
1217
1218
uint64_t udpErrorStats([[maybe_unused]] const std::string& str)
1219
0
{
1220
0
#ifdef __linux__
1221
0
  ifstream ifs("/proc/net/snmp");
1222
0
  if (!ifs) {
1223
0
    return 0;
1224
0
  }
1225
1226
0
  string line;
1227
0
  while (getline(ifs, line)) {
1228
0
    if (boost::starts_with(line, "Udp: ") && isdigit(line.at(5)) != 0) {
1229
0
      vector<string> parts;
1230
0
      stringtok(parts, line, " \n\t\r");
1231
1232
0
      if (parts.size() < 7) {
1233
0
        break;
1234
0
      }
1235
1236
0
      if (str == "udp-recvbuf-errors") {
1237
0
        return std::stoull(parts.at(5));
1238
0
      }
1239
0
      if (str == "udp-sndbuf-errors") {
1240
0
        return std::stoull(parts.at(6));
1241
0
      }
1242
0
      if (str == "udp-noport-errors") {
1243
0
        return std::stoull(parts.at(2));
1244
0
      }
1245
0
      if (str == "udp-in-errors") {
1246
0
        return std::stoull(parts.at(3));
1247
0
      }
1248
0
      if (parts.size() >= 8 && str == "udp-in-csum-errors") {
1249
0
        return std::stoull(parts.at(7));
1250
0
      }
1251
0
      return 0;
1252
0
    }
1253
0
  }
1254
0
#endif
1255
0
  return 0;
1256
0
}
1257
1258
uint64_t udp6ErrorStats([[maybe_unused]] const std::string& str)
1259
0
{
1260
0
#ifdef __linux__
1261
0
  const std::map<std::string, std::string> keys = {
1262
0
    {"udp6-in-errors", "Udp6InErrors"},
1263
0
    {"udp6-recvbuf-errors", "Udp6RcvbufErrors"},
1264
0
    {"udp6-sndbuf-errors", "Udp6SndbufErrors"},
1265
0
    {"udp6-noport-errors", "Udp6NoPorts"},
1266
0
    {"udp6-in-csum-errors", "Udp6InCsumErrors"}};
1267
1268
0
  auto key = keys.find(str);
1269
0
  if (key == keys.end()) {
1270
0
    return 0;
1271
0
  }
1272
1273
0
  ifstream ifs("/proc/net/snmp6");
1274
0
  if (!ifs) {
1275
0
    return 0;
1276
0
  }
1277
1278
0
  std::string line;
1279
0
  while (getline(ifs, line)) {
1280
0
    if (!boost::starts_with(line, key->second)) {
1281
0
      continue;
1282
0
    }
1283
1284
0
    std::vector<std::string> parts;
1285
0
    stringtok(parts, line, " \n\t\r");
1286
1287
0
    if (parts.size() != 2) {
1288
0
      return 0;
1289
0
    }
1290
1291
0
    return std::stoull(parts.at(1));
1292
0
  }
1293
0
#endif
1294
0
  return 0;
1295
0
}
1296
1297
uint64_t tcpErrorStats([[maybe_unused]] const std::string& label)
1298
0
{
1299
0
#ifdef __linux__
1300
0
  ifstream ifs("/proc/net/netstat");
1301
0
  if (!ifs) {
1302
0
    return 0U;
1303
0
  }
1304
1305
0
  string line;
1306
0
  std::vector<string> parts;
1307
0
  std::optional<size_t> position{std::nullopt};
1308
0
  while (getline(ifs, line)) {
1309
0
    if (line.size() <= 9 || !boost::starts_with(line, "TcpExt: ")) {
1310
0
      continue;
1311
0
    }
1312
1313
0
    if (!position.has_value() && isdigit(line.at(8)) == 0) {
1314
      // this is the line with the labels, let's try to find ours
1315
0
      parts.clear();
1316
0
      stringtok(parts, line, " \n\t\r");
1317
0
      size_t currentPosition = 0;
1318
0
      for (const auto& tentativeLabel : parts) {
1319
0
        if (tentativeLabel == label) {
1320
0
          position = currentPosition;
1321
0
          break;
1322
0
        }
1323
0
        ++currentPosition;
1324
0
      }
1325
0
      if (!position.has_value()) {
1326
        // label not found, bye
1327
0
        return 0U;
1328
0
      }
1329
0
      continue;
1330
0
    }
1331
1332
0
    if (position.has_value() && isdigit(line.at(8)) != 0) {
1333
      // this is the line with the values
1334
0
      parts.clear();
1335
0
      stringtok(parts, line, " \n\t\r");
1336
0
      if (parts.size() < *position) {
1337
0
        return 0U;
1338
0
      }
1339
0
      return std::stoull(parts.at(*position));
1340
0
    }
1341
0
  }
1342
0
#endif
1343
0
  return 0U;
1344
0
}
1345
1346
uint64_t getCPUIOWait(const std::string& /* str */)
1347
0
{
1348
0
#ifdef __linux__
1349
0
  ifstream ifs("/proc/stat");
1350
0
  if (!ifs) {
1351
0
    return 0;
1352
0
  }
1353
1354
0
  string line;
1355
0
  vector<string> parts;
1356
0
  while (getline(ifs, line)) {
1357
0
    if (boost::starts_with(line, "cpu ")) {
1358
0
      stringtok(parts, line, " \n\t\r");
1359
1360
0
      if (parts.size() < 6) {
1361
0
        break;
1362
0
      }
1363
1364
0
      return std::stoull(parts[5]);
1365
0
    }
1366
0
  }
1367
0
#endif
1368
0
  return 0;
1369
0
}
1370
1371
uint64_t getCPUSteal(const std::string& /* str */)
1372
0
{
1373
0
#ifdef __linux__
1374
0
  ifstream ifs("/proc/stat");
1375
0
  if (!ifs) {
1376
0
    return 0;
1377
0
  }
1378
1379
0
  string line;
1380
0
  vector<string> parts;
1381
0
  while (getline(ifs, line)) {
1382
0
    if (boost::starts_with(line, "cpu ")) {
1383
0
      stringtok(parts, line, " \n\t\r");
1384
1385
0
      if (parts.size() < 9) {
1386
0
        break;
1387
0
      }
1388
1389
0
      return std::stoull(parts[8]);
1390
0
    }
1391
0
  }
1392
0
#endif
1393
0
  return 0;
1394
0
}
1395
1396
bool getTSIGHashEnum(const DNSName& algoName, TSIGHashEnum& algoEnum)
1397
0
{
1398
0
  if (algoName == g_hmacmd5dnsname_long || algoName == g_hmacmd5dnsname) {
1399
0
    algoEnum = TSIG_MD5;
1400
0
  }
1401
0
  else if (algoName == g_hmacsha1dnsname) {
1402
0
    algoEnum = TSIG_SHA1;
1403
0
  }
1404
0
  else if (algoName == g_hmacsha224dnsname) {
1405
0
    algoEnum = TSIG_SHA224;
1406
0
  }
1407
0
  else if (algoName == g_hmacsha256dnsname) {
1408
0
    algoEnum = TSIG_SHA256;
1409
0
  }
1410
0
  else if (algoName == g_hmacsha384dnsname) {
1411
0
    algoEnum = TSIG_SHA384;
1412
0
  }
1413
0
  else if (algoName == g_hmacsha512dnsname) {
1414
0
    algoEnum = TSIG_SHA512;
1415
0
  }
1416
0
  else if (algoName == g_gsstsigdnsname) {
1417
0
    algoEnum = TSIG_GSS;
1418
0
  }
1419
0
  else {
1420
0
    return false;
1421
0
  }
1422
0
  return true;
1423
0
}
1424
1425
DNSName getTSIGAlgoName(TSIGHashEnum& algoEnum)
1426
0
{
1427
0
  switch (algoEnum) {
1428
0
  case TSIG_MD5:
1429
0
    return g_hmacmd5dnsname_long;
1430
0
  case TSIG_SHA1:
1431
0
    return g_hmacsha1dnsname;
1432
0
  case TSIG_SHA224:
1433
0
    return g_hmacsha224dnsname;
1434
0
  case TSIG_SHA256:
1435
0
    return g_hmacsha256dnsname;
1436
0
  case TSIG_SHA384:
1437
0
    return g_hmacsha384dnsname;
1438
0
  case TSIG_SHA512:
1439
0
    return g_hmacsha512dnsname;
1440
0
  case TSIG_GSS:
1441
0
    return g_gsstsigdnsname;
1442
0
  }
1443
0
  throw PDNSException("getTSIGAlgoName does not understand given algorithm, please fix!");
1444
0
}
1445
1446
uint64_t getOpenFileDescriptors(const std::string& /* unused */)
1447
0
{
1448
0
#ifdef __linux__
1449
0
  const auto* const dirName = "/proc/self/fd";
1450
0
  struct stat status; // NOLINT(cppcoreguidelines-pro-type-member-init)
1451
0
  auto ret = stat(dirName, &status);
1452
0
  if (ret != 0) {
1453
0
    return 0;
1454
0
  }
1455
0
  if (status.st_size != 0) { // Until linux 6.1, this would return 0
1456
0
    return status.st_size;
1457
0
  }
1458
1459
  // This can lead to performance issues with *many* open fds
1460
0
  uint64_t nbFileDescriptors = 0;
1461
0
  auto directoryError = pdns::visit_directory(dirName, [&nbFileDescriptors]([[maybe_unused]] ino_t inodeNumber, const std::string_view& name) {
1462
0
    uint32_t num{};
1463
0
    try {
1464
0
      pdns::checked_stoi_into(num, std::string(name));
1465
0
      if (std::to_string(num) == name) {
1466
0
        nbFileDescriptors++;
1467
0
      }
1468
0
    }
1469
0
    catch (...) {
1470
      // was not a number.
1471
0
      ;
1472
0
    }
1473
0
    return true;
1474
0
  });
1475
0
  if (directoryError) {
1476
0
    return 0U;
1477
0
  }
1478
0
  return nbFileDescriptors;
1479
#elif defined(__OpenBSD__)
1480
  // FreeBSD also has this in libopenbsd, but I don't know if that's available always
1481
  return getdtablecount();
1482
#else
1483
  return 0U;
1484
#endif
1485
0
}
1486
1487
uint64_t getRealMemoryUsage(const std::string& /* unused */)
1488
0
{
1489
0
#ifdef __linux__
1490
0
  ifstream ifs("/proc/self/statm");
1491
0
  if (!ifs) {
1492
0
    return 0;
1493
0
  }
1494
0
  uint64_t size{};
1495
0
  uint64_t resident{};
1496
0
  uint64_t shared{};
1497
0
  uint64_t text{};
1498
0
  uint64_t lib{};
1499
0
  uint64_t data{};
1500
0
  ifs >> size >> resident >> shared >> text >> lib >> data;
1501
1502
  // We used to use "data" here, but it proves unreliable and even is marked "broken"
1503
  // in https://www.kernel.org/doc/html/latest/filesystems/proc.html
1504
0
  return resident * getpagesize();
1505
#else
1506
  struct rusage rusage{};
1507
  if (getrusage(RUSAGE_SELF, &rusage) != 0) {
1508
    return 0;
1509
  }
1510
  return rusage.ru_maxrss * 1024;
1511
#endif
1512
0
}
1513
1514
uint64_t getSpecialMemoryUsage(const std::string& /* unused */)
1515
0
{
1516
0
#ifdef __linux__
1517
0
  ifstream ifs("/proc/self/smaps");
1518
0
  if (!ifs) {
1519
0
    return 0;
1520
0
  }
1521
0
  string line;
1522
0
  uint64_t bytes = 0;
1523
0
  string header("Private_Dirty:");
1524
0
  while (getline(ifs, line)) {
1525
0
    if (boost::starts_with(line, header)) {
1526
0
      bytes += std::stoull(line.substr(header.length() + 1)) * 1024;
1527
0
    }
1528
0
  }
1529
0
  return bytes;
1530
#else
1531
  return 0;
1532
#endif
1533
0
}
1534
1535
uint64_t getCPUTimeUser(const std::string& /* unused */)
1536
0
{
1537
0
  struct rusage rusagew{};
1538
0
  getrusage(RUSAGE_SELF, &rusagew);
1539
0
  return (rusagew.ru_utime.tv_sec * 1000ULL) + (rusagew.ru_utime.tv_usec / 1000);
1540
0
}
1541
1542
uint64_t getCPUTimeSystem(const std::string& /* unused */)
1543
0
{
1544
0
  struct rusage rusage{};
1545
0
  getrusage(RUSAGE_SELF, &rusage);
1546
0
  return (rusage.ru_stime.tv_sec * 1000ULL) + (rusage.ru_stime.tv_usec / 1000);
1547
0
}
1548
1549
double DiffTime(const struct timespec& first, const struct timespec& second)
1550
0
{
1551
0
  auto seconds = second.tv_sec - first.tv_sec;
1552
0
  auto nseconds = second.tv_nsec - first.tv_nsec;
1553
1554
0
  if (nseconds < 0) {
1555
0
    seconds -= 1;
1556
0
    nseconds += 1000000000;
1557
0
  }
1558
0
  return static_cast<double>(seconds) + (static_cast<double>(nseconds) / 1000000000.0);
1559
0
}
1560
1561
double DiffTime(const struct timeval& first, const struct timeval& second)
1562
0
{
1563
0
  auto seconds = second.tv_sec - first.tv_sec;
1564
0
  auto useconds = second.tv_usec - first.tv_usec;
1565
1566
0
  if (useconds < 0) {
1567
0
    seconds -= 1;
1568
0
    useconds += 1000000;
1569
0
  }
1570
0
  return static_cast<double>(seconds) + (static_cast<double>(useconds) / 1000000.0);
1571
0
}
1572
1573
uid_t strToUID(const string& str)
1574
0
{
1575
0
  uid_t result = 0;
1576
0
  const char* cstr = str.c_str();
1577
0
  auto bufsize = pdns::sysconf(_SC_GETPW_R_SIZE_MAX, 1024);
1578
0
  std::string buffer;
1579
0
  buffer.resize(bufsize);
1580
0
  struct passwd pwd{};
1581
0
  struct passwd* pwdPtr = nullptr;
1582
0
  if (getpwnam_r(cstr, &pwd, buffer.data(), buffer.size(), &pwdPtr) != 0) {
1583
0
    throw runtime_error("cannot retrieve uid");
1584
0
  }
1585
1586
0
  if (pwdPtr == nullptr) {
1587
0
    long long val{};
1588
1589
0
    try {
1590
0
      val = stoll(str);
1591
0
    }
1592
0
    catch (std::exception& e) {
1593
0
      throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr).str());
1594
0
    }
1595
1596
0
    if (val < std::numeric_limits<uid_t>::min() || val > std::numeric_limits<uid_t>::max()) {
1597
0
      throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr).str());
1598
0
    }
1599
1600
0
    result = static_cast<uid_t>(val);
1601
0
  }
1602
0
  else {
1603
0
    result = pwdPtr->pw_uid;
1604
0
  }
1605
1606
0
  return result;
1607
0
}
1608
1609
gid_t strToGID(const string& str)
1610
0
{
1611
0
  gid_t result = 0;
1612
0
  const char* cstr = str.c_str();
1613
0
  auto bufsize = pdns::sysconf(_SC_GETGR_R_SIZE_MAX, 1024);
1614
0
  std::string buffer;
1615
0
  buffer.resize(bufsize);
1616
0
  struct group grp{};
1617
0
  struct group* grpPtr = nullptr;
1618
0
  if (getgrnam_r(cstr, &grp, buffer.data(), buffer.size(), &grpPtr) != 0) {
1619
0
    throw runtime_error("cannot retrieve gid");
1620
0
  }
1621
1622
0
  if (grpPtr == nullptr) {
1623
0
    long long val{};
1624
1625
0
    try {
1626
0
      val = stoll(str);
1627
0
    }
1628
0
    catch (std::exception& e) {
1629
0
      throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr).str());
1630
0
    }
1631
1632
0
    if (val < std::numeric_limits<gid_t>::min() || val > std::numeric_limits<gid_t>::max()) {
1633
0
      throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr).str());
1634
0
    }
1635
1636
0
    result = static_cast<gid_t>(val);
1637
0
  }
1638
0
  else {
1639
0
    result = grpPtr->gr_gid;
1640
0
  }
1641
1642
0
  return result;
1643
0
}
1644
1645
bool isSettingThreadCPUAffinitySupported()
1646
0
{
1647
0
#ifdef HAVE_PTHREAD_SETAFFINITY_NP
1648
0
  return true;
1649
#else
1650
  return false;
1651
#endif
1652
0
}
1653
1654
int mapThreadToCPUList([[maybe_unused]] pthread_t tid, [[maybe_unused]] const std::set<int>& cpus)
1655
0
{
1656
0
#ifdef HAVE_PTHREAD_SETAFFINITY_NP
1657
#ifdef __NetBSD__
1658
  cpuset_t* cpuset;
1659
  cpuset = cpuset_create();
1660
  for (const auto cpuID : cpus) {
1661
    cpuset_set(cpuID, cpuset);
1662
  }
1663
1664
  return pthread_setaffinity_np(tid,
1665
                                cpuset_size(cpuset),
1666
                                cpuset);
1667
#else
1668
#ifdef __FreeBSD__
1669
#define cpu_set_t cpuset_t
1670
#endif
1671
0
  cpu_set_t cpuset;
1672
0
  CPU_ZERO(&cpuset);
1673
0
  for (const auto cpuID : cpus) {
1674
0
    CPU_SET(cpuID, &cpuset);
1675
0
  }
1676
1677
0
  return pthread_setaffinity_np(tid,
1678
0
                                sizeof(cpuset),
1679
0
                                &cpuset);
1680
0
#endif
1681
#else
1682
  return ENOSYS;
1683
#endif /* HAVE_PTHREAD_SETAFFINITY_NP */
1684
0
}
1685
1686
std::vector<ComboAddress> getResolvers(const std::string& resolvConfPath)
1687
0
{
1688
  // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive in some boost versions
1689
0
  std::vector<ComboAddress> results;
1690
1691
0
  std::ifstream ifs(resolvConfPath);
1692
0
  if (!ifs) {
1693
0
    return results;
1694
0
  }
1695
1696
0
  string line;
1697
0
  while (std::getline(ifs, line)) {
1698
0
    boost::trim_right_if(line, boost::is_any_of(" \r\n\x1a"));
1699
0
    boost::trim_left(line); // leading spaces, let's be nice
1700
1701
0
    string::size_type tpos = line.find_first_of(";#");
1702
0
    if (tpos != string::npos) {
1703
0
      line.resize(tpos);
1704
0
    }
1705
1706
0
    if (boost::starts_with(line, "nameserver ") || boost::starts_with(line, "nameserver\t")) {
1707
0
      vector<string> parts;
1708
0
      stringtok(parts, line, " \t,"); // be REALLY nice
1709
0
      for (auto iter = parts.begin() + 1; iter != parts.end(); ++iter) {
1710
0
        try {
1711
0
          results.emplace_back(*iter, 53);
1712
0
        }
1713
0
        catch (...) {
1714
0
          ; // ignored
1715
0
        }
1716
0
      }
1717
0
    }
1718
0
  }
1719
1720
0
  return results;
1721
  // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
1722
0
}
1723
1724
size_t getPipeBufferSize([[maybe_unused]] int fileDesc)
1725
0
{
1726
0
#ifdef F_GETPIPE_SZ
1727
0
  int res = fcntl(fileDesc, F_GETPIPE_SZ);
1728
0
  if (res == -1) {
1729
0
    return 0;
1730
0
  }
1731
0
  return res;
1732
#else
1733
  errno = ENOSYS;
1734
  return 0;
1735
#endif /* F_GETPIPE_SZ */
1736
0
}
1737
1738
bool setPipeBufferSize([[maybe_unused]] int fileDesc, [[maybe_unused]] size_t size)
1739
0
{
1740
0
#ifdef F_SETPIPE_SZ
1741
0
  if (size > static_cast<size_t>(std::numeric_limits<int>::max())) {
1742
0
    errno = EINVAL;
1743
0
    return false;
1744
0
  }
1745
0
  int newSize = static_cast<int>(size);
1746
0
  int res = fcntl(fileDesc, F_SETPIPE_SZ, newSize);
1747
0
  return res != -1;
1748
#else
1749
  errno = ENOSYS;
1750
  return false;
1751
#endif /* F_SETPIPE_SZ */
1752
0
}
1753
1754
DNSName reverseNameFromIP(const ComboAddress& address)
1755
0
{
1756
0
  if (address.isIPv4()) {
1757
0
    std::string result("in-addr.arpa.");
1758
0
    const auto* ptr = reinterpret_cast<const uint8_t*>(&address.sin4.sin_addr.s_addr);
1759
0
    for (size_t idx = 0; idx < sizeof(address.sin4.sin_addr.s_addr); idx++) {
1760
0
      auto tmp{result};
1761
0
      result = std::to_string(ptr[idx]);
1762
0
      result += ".";
1763
0
      result += tmp;
1764
0
    }
1765
0
    return DNSName(result);
1766
0
  }
1767
0
  if (address.isIPv6()) {
1768
0
    std::string result("ip6.arpa.");
1769
0
    const auto* ptr = &address.sin6.sin6_addr.s6_addr[0];
1770
0
    for (size_t idx = 0; idx < sizeof(address.sin6.sin6_addr.s6_addr); idx++) {
1771
0
      std::stringstream stream;
1772
0
      stream << std::hex << (ptr[idx] & 0x0F);
1773
0
      stream << '.';
1774
0
      stream << std::hex << (((ptr[idx]) >> 4) & 0x0F);
1775
0
      stream << '.';
1776
0
      auto tmp{result};
1777
0
      result = stream.str();
1778
0
      result += tmp;
1779
0
    }
1780
0
    return DNSName(result);
1781
0
  }
1782
1783
0
  throw std::runtime_error("Calling reverseNameFromIP() for an address which is neither an IPv4 nor an IPv6");
1784
0
}
1785
1786
std::string makeLuaString(const std::string& input)
1787
0
{
1788
0
  ostringstream str;
1789
1790
0
  str << '"';
1791
1792
0
  std::array<char, 5> item{};
1793
0
  for (unsigned char character : input) {
1794
0
    if ((islower(character) != 0) || (isupper(character) != 0)) {
1795
0
      item[0] = static_cast<char>(character);
1796
0
      item[1] = 0;
1797
0
    }
1798
0
    else {
1799
0
      snprintf(item.data(), item.size(), "\\%03d", character);
1800
0
    }
1801
0
    str << item.data();
1802
0
  }
1803
1804
0
  str << '"';
1805
1806
0
  return str.str();
1807
0
}
1808
1809
size_t parseSVCBValueList(const std::string& str, vector<std::string>& val)
1810
1.11k
{
1811
1.11k
  std::string parsed;
1812
1.11k
  auto ret = parseRFC1035CharString(str, parsed);
1813
1.11k
  parseSVCBValueListFromParsedRFC1035CharString(parsed, val);
1814
1.11k
  return ret;
1815
1.11k
};
1816
1817
#ifdef HAVE_CRYPTO_MEMCMP
1818
#include <openssl/crypto.h>
1819
#else /* HAVE_CRYPTO_MEMCMP */
1820
#ifdef HAVE_SODIUM_MEMCMP
1821
#include <sodium.h>
1822
#endif /* HAVE_SODIUM_MEMCMP */
1823
#endif /* HAVE_CRYPTO_MEMCMP */
1824
1825
bool constantTimeStringEquals(const std::string& lhs, const std::string& rhs)
1826
0
{
1827
0
  if (lhs.size() != rhs.size()) {
1828
0
    return false;
1829
0
  }
1830
0
  const size_t size = lhs.size();
1831
0
#ifdef HAVE_CRYPTO_MEMCMP
1832
0
  return CRYPTO_memcmp(lhs.c_str(), rhs.c_str(), size) == 0;
1833
#else /* HAVE_CRYPTO_MEMCMP */
1834
#ifdef HAVE_SODIUM_MEMCMP
1835
  return sodium_memcmp(lhs.c_str(), rhs.c_str(), size) == 0;
1836
#else /* HAVE_SODIUM_MEMCMP */
1837
  const volatile unsigned char* _a = (const volatile unsigned char*)lhs.c_str();
1838
  const volatile unsigned char* _b = (const volatile unsigned char*)rhs.c_str();
1839
  unsigned char res = 0;
1840
1841
  for (size_t idx = 0; idx < size; idx++) {
1842
    res |= _a[idx] ^ _b[idx];
1843
  }
1844
1845
  return res == 0;
1846
#endif /* !HAVE_SODIUM_MEMCMP */
1847
#endif /* !HAVE_CRYPTO_MEMCMP */
1848
0
}
1849
1850
namespace pdns
1851
{
1852
struct CloseDirDeleter
1853
{
1854
  void operator()(DIR* dir) const noexcept
1855
0
  {
1856
0
    closedir(dir);
1857
0
  }
1858
};
1859
1860
std::optional<std::string> visit_directory(const std::string& directory, const std::function<bool(ino_t inodeNumber, const std::string_view& name)>& visitor)
1861
0
{
1862
0
  auto dirHandle = std::unique_ptr<DIR, CloseDirDeleter>(opendir(directory.c_str()));
1863
0
  if (!dirHandle) {
1864
0
    auto err = errno;
1865
0
    return std::string("Error opening directory '" + directory + "': " + stringerror(err));
1866
0
  }
1867
1868
0
  bool keepGoing = true;
1869
0
  struct dirent* ent = nullptr;
1870
  // NOLINTNEXTLINE(concurrency-mt-unsafe): readdir is thread-safe nowadays and readdir_r is deprecated
1871
0
  while (keepGoing && (ent = readdir(dirHandle.get())) != nullptr) {
1872
    // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay: dirent API
1873
0
    auto name = std::string_view(ent->d_name, strlen(ent->d_name));
1874
0
    keepGoing = visitor(ent->d_ino, name);
1875
0
  }
1876
1877
0
  return std::nullopt;
1878
0
}
1879
1880
#ifndef DNSDIST
1881
std::vector<std::string> list_directory(const std::string& directory, const std::string& suffix, Logr::log_t d_log)
1882
{
1883
  std::vector<std::string> results;
1884
1885
  auto directoryError = pdns::visit_directory(directory,
1886
                                              [&directory, &suffix, &results, d_log]([[maybe_unused]] ino_t inodeNumber, const std::string_view& name) {
1887
                                                if (boost::starts_with(name, ".")) {
1888
                                                  return true; // skip any dots
1889
                                                }
1890
                                                if (boost::ends_with(name, suffix)) {
1891
                                                  // build name
1892
                                                  string fullName = directory + "/" + std::string(name);
1893
                                                  // ensure it's a readable file
1894
                                                  struct stat statInfo{};
1895
                                                  if (stat(fullName.c_str(), &statInfo) != 0) {
1896
                                                    int err = errno;
1897
                                                    string msg = "Unable to stat file '" + fullName + "': " + stringerror(err);
1898
                                                    SLOG(g_log << Logger::Error << msg << std::endl,
1899
                                                         d_log->error(Logr::Error, err, "Unable to stat file", "name", Logging::Loggable(fullName)));
1900
                                                    throw PDNSException(std::move(msg));
1901
                                                  }
1902
                                                  if (!S_ISREG(statInfo.st_mode)) {
1903
                                                    string msg = "File '" + fullName + "' is not a regular file";
1904
                                                    SLOG(g_log << Logger::Error << msg << std::endl,
1905
                                                         d_log->info(Logr::Error, "File is not a regular file", "name", Logging::Loggable(fullName)));
1906
                                                    throw PDNSException(std::move(msg));
1907
                                                  }
1908
                                                  results.emplace_back(fullName);
1909
                                                }
1910
                                                return true;
1911
                                              });
1912
1913
  if (directoryError) {
1914
    int err = errno;
1915
    string msg = directory + " is not accessible: " + stringerror(err);
1916
    SLOG(g_log << Logger::Error << msg << std::endl,
1917
         d_log->error(Logr::Error, err, "Directory is not accessible", "name", Logging::Loggable(directory)));
1918
    throw PDNSException(std::move(msg));
1919
  }
1920
1921
  return results;
1922
}
1923
#endif
1924
1925
UniqueFilePtr openFileForWriting(const std::string& filePath, mode_t permissions, bool mustNotExist, bool appendIfExists)
1926
0
{
1927
0
  int flags = O_WRONLY | O_CREAT;
1928
0
  if (mustNotExist) {
1929
0
    flags |= O_EXCL;
1930
0
  }
1931
0
  else if (appendIfExists) {
1932
0
    flags |= O_APPEND;
1933
0
  }
1934
0
  int fileDesc = open(filePath.c_str(), flags, permissions);
1935
0
  if (fileDesc == -1) {
1936
0
    return {};
1937
0
  }
1938
0
  auto filePtr = pdns::UniqueFilePtr(fdopen(fileDesc, appendIfExists ? "a" : "w"));
1939
0
  if (!filePtr) {
1940
0
    auto error = errno;
1941
0
    close(fileDesc);
1942
0
    errno = error;
1943
0
    return {};
1944
0
  }
1945
0
  return filePtr;
1946
0
}
1947
1948
}
1949
1950
const char* timestamp(time_t arg, timebuf_t& buf)
1951
0
{
1952
0
  const std::string s_timestampFormat = "%Y-%m-%dT%T";
1953
0
  struct tm tmval{};
1954
0
  size_t len = strftime(buf.data(), buf.size(), s_timestampFormat.c_str(), localtime_r(&arg, &tmval));
1955
0
  if (len == 0) {
1956
0
    int ret = snprintf(buf.data(), buf.size(), "%lld", static_cast<long long>(arg));
1957
0
    if (ret < 0 || static_cast<size_t>(ret) >= buf.size()) {
1958
0
      buf[0] = '\0';
1959
0
    }
1960
0
  }
1961
0
  return buf.data();
1962
0
}
1963
// NOLINTEND(cppcoreguidelines-pro-bounds-pointer-arithmetic,cppcoreguidelines-pro-type-reinterpret-cast)
1964
1965
long pdns::sysconf(int key, long default_value)
1966
0
{
1967
0
  auto ret = ::sysconf(key);
1968
0
  if (ret == -1) {
1969
0
    ret = default_value;
1970
0
  }
1971
0
  return ret;
1972
0
}