Coverage Report

Created: 2025-06-13 06:27

/src/pdns/pdns/misc.hh
Line
Count
Source (jump to first uncovered line)
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
#pragma once
23
#include <cinttypes>
24
#include <cstring>
25
#include <cstdio>
26
#include <regex.h>
27
#include <climits>
28
#include <type_traits>
29
30
#include <boost/algorithm/string.hpp>
31
32
#include "dns.hh"
33
#include <atomic>
34
#include <sys/time.h>
35
#include <sys/types.h>
36
#include <sys/socket.h>
37
#include <ctime>
38
#include <syslog.h>
39
#include <stdexcept>
40
#include <string>
41
#include <cctype>
42
#include <utility>
43
#include <vector>
44
45
#include "namespaces.hh"
46
47
class DNSName;
48
#if defined(PDNS_AUTH)
49
class ZoneName;
50
#else
51
using ZoneName = DNSName;
52
#endif
53
54
// Do not change to "using TSIGHashEnum ..." until you know CodeQL does not choke on it
55
typedef enum
56
{
57
  TSIG_MD5,
58
  TSIG_SHA1,
59
  TSIG_SHA224,
60
  TSIG_SHA256,
61
  TSIG_SHA384,
62
  TSIG_SHA512,
63
  TSIG_GSS,
64
} TSIGHashEnum;
65
66
namespace pdns
67
{
68
/**
69
 * \brief Retrieves the errno-based error message in a reentrant way.
70
 *
71
 * This internally handles the portability issues around using
72
 * `strerror_r` and returns a `std::string` that owns the error
73
 * message's contents.
74
 *
75
 * \param[in] errnum The errno value.
76
 *
77
 * \return The `std::string` error message.
78
 */
79
auto getMessageFromErrno(int errnum) -> std::string;
80
81
#if defined(HAVE_LIBCRYPTO)
82
namespace OpenSSL
83
{
84
  /**
85
   * \brief Throws a `std::runtime_error` with the current OpenSSL error.
86
   *
87
   * \param[in] errorMessage The message to attach in addition to the OpenSSL error.
88
   */
89
  [[nodiscard]] auto error(const std::string& errorMessage) -> std::runtime_error;
90
91
  /**
92
   * \brief Throws a `std::runtime_error` with a name and the current OpenSSL error.
93
   *
94
   * \param[in] componentName The name of the component to mark the error message with.
95
   * \param[in] errorMessage The message to attach in addition to the OpenSSL error.
96
   */
97
  [[nodiscard]] auto error(const std::string& componentName, const std::string& errorMessage) -> std::runtime_error;
98
}
99
#endif // HAVE_LIBCRYPTO
100
}
101
102
string nowTime();
103
string unquotify(const string &item);
104
string humanDuration(time_t passed);
105
bool stripDomainSuffix(string *qname, const string &domain);
106
void stripLine(string &line);
107
std::optional<string> getHostname();
108
std::string getCarbonHostName();
109
string urlEncode(const string &text);
110
int waitForData(int fileDesc, int seconds, int useconds = 0);
111
int waitFor2Data(int fd1, int fd2, int seconds, int useconds, int* fd);
112
int waitForMultiData(const set<int>& fds, const int seconds, const int useconds, int* fd);
113
int waitForRWData(int fileDesc, bool waitForRead, int seconds, int useconds, bool* error = nullptr, bool* disconnected = nullptr);
114
bool getTSIGHashEnum(const DNSName& algoName, TSIGHashEnum& algoEnum);
115
DNSName getTSIGAlgoName(TSIGHashEnum& algoEnum);
116
117
int logFacilityToLOG(unsigned int facility);
118
std::optional<int> logFacilityFromString(std::string facilityStr);
119
120
template<typename Container>
121
void
122
stringtok (Container &container, string const &in,
123
           const char * const delimiters = " \t\n")
124
0
{
125
0
  const string::size_type len = in.length();
126
0
  string::size_type i = 0;
127
128
0
  while (i<len) {
129
    // eat leading whitespace
130
0
    i = in.find_first_not_of (delimiters, i);
131
0
    if (i == string::npos)
132
0
      return;   // nothing left but white space
133
134
    // find the end of the token
135
0
    string::size_type j = in.find_first_of (delimiters, i);
136
137
    // push token
138
0
    if (j == string::npos) {
139
0
      container.push_back (in.substr(i));
140
0
      return;
141
0
    } else
142
0
      container.push_back (in.substr(i, j-i));
143
144
    // set up for next loop
145
0
    i = j + 1;
146
0
  }
147
0
}
148
149
template<typename T> bool rfc1982LessThan(T a, T b)
150
{
151
  static_assert(std::is_unsigned_v<T>, "rfc1982LessThan only works for unsigned types");
152
  return std::make_signed_t<T>(a - b) < 0;
153
}
154
155
// fills container with ranges, so {posbegin,posend}
156
template <typename Container>
157
void
158
vstringtok (Container &container, string const &in,
159
           const char * const delimiters = " \t\n")
160
0
{
161
0
  const string::size_type len = in.length();
162
0
  string::size_type i = 0;
163
164
0
  while (i<len) {
165
    // eat leading whitespace
166
0
    i = in.find_first_not_of (delimiters, i);
167
0
    if (i == string::npos)
168
0
      return;   // nothing left but white space
169
170
    // find the end of the token
171
0
    string::size_type j = in.find_first_of (delimiters, i);
172
173
    // push token
174
0
    if (j == string::npos) {
175
0
      container.emplace_back(i, len);
176
0
      return;
177
0
    } else
178
0
      container.emplace_back(i, j);
179
180
    // set up for next loop
181
0
    i = j + 1;
182
0
  }
183
0
}
184
185
size_t writen2(int fd, const void *buf, size_t count);
186
0
inline size_t writen2(int fd, const std::string &s) { return writen2(fd, s.data(), s.size()); }
187
size_t readn2(int fileDesc, void* buffer, size_t len);
188
size_t readn2WithTimeout(int fd, void* buffer, size_t len, const struct timeval& idleTimeout, const struct timeval& totalTimeout={0,0}, bool allowIncomplete=false);
189
size_t writen2WithTimeout(int fd, const void * buffer, size_t len, const struct timeval& timeout);
190
191
void toLowerInPlace(string& str);
192
const string toLower(const string &upper);
193
const string toLowerCanonic(const string &upper);
194
bool IpToU32(const string &str, uint32_t *ip);
195
string U32ToIP(uint32_t);
196
197
inline string stringerror(int err = errno)
198
0
{
199
0
  return pdns::getMessageFromErrno(err);
200
0
}
201
202
string bitFlip(const string &str);
203
204
void dropPrivs(int uid, int gid);
205
void cleanSlashes(string &str);
206
207
#if defined(_POSIX_THREAD_CPUTIME) && defined(CLOCK_THREAD_CPUTIME_ID)
208
/** CPUTime measurements */
209
class CPUTime
210
{
211
public:
212
  void start()
213
0
  {
214
0
    clock_gettime(CLOCK_THREAD_CPUTIME_ID, &d_start);
215
0
  }
216
  uint64_t ndiff()
217
0
  {
218
0
    struct timespec now;
219
0
    clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
220
0
    return 1000000000ULL*(now.tv_sec - d_start.tv_sec) + (now.tv_nsec - d_start.tv_nsec);
221
0
  }
222
private:
223
  struct timespec d_start;
224
};
225
#endif
226
227
/** The DTime class can be used for timing statistics with microsecond resolution.
228
On 32 bits systems this means that 2147 seconds is the longest time that can be measured. */
229
class DTime
230
{
231
public:
232
  //!< Does not set the timer for you! Saves lots of gettimeofday() calls
233
  DTime() = default;
234
  DTime(const DTime &dt) = default;
235
  DTime & operator=(const DTime &dt) = default;
236
  inline time_t time() const;
237
  inline void set();  //!< Reset the timer
238
  inline int udiff(bool reset = true); //!< Return the number of microseconds since the timer was last set.
239
240
  int udiffNoReset() //!< Return the number of microseconds since the timer was last set.
241
0
  {
242
0
    return udiff(false);
243
0
  }
244
  void setTimeval(const struct timeval& tv)
245
0
  {
246
0
    d_set=tv;
247
0
  }
248
  struct timeval getTimeval() const
249
0
  {
250
0
    return d_set;
251
0
  }
252
private:
253
struct timeval d_set{0, 0};
254
};
255
256
inline time_t DTime::time() const
257
0
{
258
0
  return d_set.tv_sec;
259
0
}
260
261
inline void DTime::set()
262
0
{
263
0
  gettimeofday(&d_set, nullptr);
264
0
}
265
266
inline int DTime::udiff(bool reset)
267
0
{
268
0
  struct timeval now;
269
0
  gettimeofday(&now, nullptr);
270
0
271
0
  int ret=1000000*(now.tv_sec-d_set.tv_sec)+(now.tv_usec-d_set.tv_usec);
272
0
273
0
  if (reset) {
274
0
    d_set = now;
275
0
  }
276
0
277
0
  return ret;
278
0
}
279
280
inline void toLowerInPlace(string& str)
281
0
{
282
0
  const size_t length = str.length();
283
0
  char c;
284
0
  for (size_t i = 0; i < length; ++i) {
285
0
    c = dns_tolower(str[i]);
286
0
    if (c != str[i]) {
287
0
      str[i] = c;
288
0
    }
289
0
  }
290
0
}
291
292
inline const string toLower(const string &upper)
293
0
{
294
0
  string reply(upper);
295
296
0
  toLowerInPlace(reply);
297
298
0
  return reply;
299
0
}
300
301
inline const string toLowerCanonic(const string &upper)
302
0
{
303
0
  string reply(upper);
304
0
  if(!upper.empty()) {
305
0
    unsigned int i, limit= ( unsigned int ) reply.length();
306
0
    unsigned char c;
307
0
    for(i = 0; i < limit ; i++) {
308
0
      c = dns_tolower(upper[i]);
309
0
      if(c != upper[i])
310
0
        reply[i] = c;
311
0
    }
312
0
    if(upper[i-1]=='.')
313
0
      reply.resize(i-1);
314
0
  }
315
0
316
0
  return reply;
317
0
}
318
319
320
321
// Make s uppercase:
322
inline string toUpper( const string& s )
323
0
{
324
0
        string r(s);
325
0
        for( unsigned int i = 0; i < s.length(); i++ ) {
326
0
          r[i] = dns_toupper(r[i]);
327
0
        }
328
0
        return r;
329
0
}
330
331
inline double getTime()
332
0
{
333
0
  struct timeval now;
334
0
  gettimeofday(&now,0);
335
0
336
0
  return now.tv_sec+now.tv_usec/1000000.0;
337
0
}
338
339
[[noreturn]] inline void unixDie(const string &why)
340
0
{
341
0
  throw runtime_error(why + ": " + stringerror(errno));
342
0
}
343
344
string makeHexDump(const string& str, const string& sep = " ");
345
//! Convert the hexstring in to a byte string
346
string makeBytesFromHex(const string &in);
347
348
void normalizeTV(struct timeval& tv);
349
struct timeval operator+(const struct timeval& lhs, const struct timeval& rhs);
350
struct timeval operator-(const struct timeval& lhs, const struct timeval& rhs);
351
352
inline float makeFloat(const struct timeval& tv)
353
0
{
354
0
  return tv.tv_sec + tv.tv_usec/1000000.0f;
355
0
}
356
inline uint64_t uSec(const struct timeval& tv)
357
0
{
358
0
  return tv.tv_sec * 1000000 + tv.tv_usec;
359
0
}
360
361
inline bool operator<(const struct timeval& lhs, const struct timeval& rhs)
362
0
{
363
0
  return std::tie(lhs.tv_sec, lhs.tv_usec) < std::tie(rhs.tv_sec, rhs.tv_usec);
364
0
}
365
inline bool operator<=(const struct timeval& lhs, const struct timeval& rhs)
366
0
{
367
0
  return std::tie(lhs.tv_sec, lhs.tv_usec) <= std::tie(rhs.tv_sec, rhs.tv_usec);
368
0
}
369
370
inline bool operator<(const struct timespec& lhs, const struct timespec& rhs)
371
0
{
372
0
  return std::tie(lhs.tv_sec, lhs.tv_nsec) < std::tie(rhs.tv_sec, rhs.tv_nsec);
373
0
}
374
375
376
inline bool pdns_ilexicographical_compare(const std::string& a, const std::string& b)  __attribute__((pure));
377
inline bool pdns_ilexicographical_compare(const std::string& a, const std::string& b)
378
0
{
379
0
  const unsigned char *aPtr = (const unsigned char*)a.c_str(), *bPtr = (const unsigned char*)b.c_str();
380
0
  const unsigned char *aEptr = aPtr + a.length(), *bEptr = bPtr + b.length();
381
0
  while(aPtr != aEptr && bPtr != bEptr) {
382
0
    if ((*aPtr != *bPtr) && (dns_tolower(*aPtr) - dns_tolower(*bPtr)))
383
0
      return (dns_tolower(*aPtr) - dns_tolower(*bPtr)) < 0;
384
0
    aPtr++;
385
0
    bPtr++;
386
0
  }
387
0
  if(aPtr == aEptr && bPtr == bEptr) // strings are equal (in length)
388
0
    return false;
389
0
  return aPtr == aEptr; // true if first string was shorter
390
0
}
391
392
inline bool pdns_iequals(const std::string& a, const std::string& b) __attribute__((pure));
393
inline bool pdns_iequals(const std::string& a, const std::string& b)
394
0
{
395
0
  if (a.length() != b.length())
396
0
    return false;
397
398
0
  const char *aPtr = a.c_str(), *bPtr = b.c_str();
399
0
  const char *aEptr = aPtr + a.length();
400
0
  while(aPtr != aEptr) {
401
0
    if((*aPtr != *bPtr) && (dns_tolower(*aPtr) != dns_tolower(*bPtr)))
402
0
      return false;
403
0
    aPtr++;
404
0
    bPtr++;
405
0
  }
406
0
  return true;
407
0
}
408
409
inline bool pdns_iequals_ch(const char a, const char b) __attribute__((pure));
410
inline bool pdns_iequals_ch(const char a, const char b)
411
0
{
412
0
  if ((a != b) && (dns_tolower(a) != dns_tolower(b)))
413
0
    return false;
414
0
415
0
  return true;
416
0
}
417
418
419
typedef unsigned long AtomicCounterInner;
420
typedef std::atomic<AtomicCounterInner> AtomicCounter ;
421
422
// FIXME400 this should probably go?
423
struct CIStringCompare
424
{
425
  bool operator()(const string& a, const string& b) const
426
0
  {
427
0
    return pdns_ilexicographical_compare(a, b);
428
0
  }
429
};
430
431
struct CIStringComparePOSIX
432
{
433
   bool operator() (const std::string& lhs, const std::string& rhs) const
434
0
   {
435
0
      const std::locale &loc = std::locale("POSIX");
436
0
      auto lhsIter = lhs.begin();
437
0
      auto rhsIter = rhs.begin();
438
0
      while (lhsIter != lhs.end()) {
439
0
        if (rhsIter == rhs.end() || std::tolower(*rhsIter,loc) < std::tolower(*lhsIter,loc)) {
440
0
          return false;
441
0
        }
442
0
        if (std::tolower(*lhsIter,loc) < std::tolower(*rhsIter,loc)) {
443
0
          return true;
444
0
        }
445
0
        ++lhsIter;++rhsIter;
446
0
      }
447
0
      return rhsIter != rhs.end();
448
0
   }
449
};
450
451
struct CIStringPairCompare
452
{
453
  bool operator()(const pair<string, uint16_t>& a, const pair<string, uint16_t>& b) const
454
0
  {
455
0
    if(pdns_ilexicographical_compare(a.first, b.first))
456
0
  return true;
457
0
    if(pdns_ilexicographical_compare(b.first, a.first))
458
0
  return false;
459
0
    return a.second < b.second;
460
0
  }
461
};
462
463
inline size_t pdns_ci_find(const string& haystack, const string& needle)
464
0
{
465
0
  string::const_iterator it = std::search(haystack.begin(), haystack.end(),
466
0
    needle.begin(), needle.end(), pdns_iequals_ch);
467
0
  if (it == haystack.end()) {
468
0
    // not found
469
0
    return string::npos;
470
0
  } else {
471
0
    return it - haystack.begin();
472
0
  }
473
0
}
474
475
pair<string, string> splitField(const string& inp, char sepa);
476
477
inline bool isCanonical(std::string_view qname)
478
0
{
479
0
  if(qname.empty())
480
0
    return false;
481
0
  return qname[qname.size()-1]=='.';
482
0
}
483
484
inline DNSName toCanonic(const ZoneName& zone, const string& qname)
485
0
{
486
0
  if(qname.size()==1 && qname[0]=='@')
487
0
    return DNSName(zone);
488
0
  if(isCanonical(qname))
489
0
    return DNSName(qname);
490
0
  return DNSName(qname) += DNSName(zone);
491
0
}
492
493
string stripDot(const string& dom);
494
495
int makeIPv6sockaddr(const std::string& addr, struct sockaddr_in6* ret);
496
int makeIPv4sockaddr(const std::string& str, struct sockaddr_in* ret);
497
int makeUNsockaddr(const std::string& path, struct sockaddr_un* ret);
498
bool stringfgets(FILE* fp, std::string& line);
499
500
template<typename Index>
501
std::pair<typename Index::iterator,bool>
502
replacing_insert(Index& i,const typename Index::value_type& x)
503
{
504
  std::pair<typename Index::iterator,bool> res=i.insert(x);
505
  if(!res.second)res.second=i.replace(res.first,x);
506
  return res;
507
}
508
509
/** very small regex wrapper */
510
class Regex
511
{
512
public:
513
  /** constructor that accepts the expression to regex */
514
  Regex(const string &expr);
515
516
  ~Regex()
517
0
  {
518
0
    regfree(&d_preg);
519
0
  }
520
  /** call this to find out if 'line' matches your expression */
521
  bool match(const string &line) const
522
0
  {
523
0
    return regexec(&d_preg,line.c_str(),0,0,0)==0;
524
0
  }
525
  bool match(const DNSName& name) const
526
0
  {
527
0
    return match(name.toStringNoDot());
528
0
  }
529
530
private:
531
  regex_t d_preg;
532
};
533
534
class SimpleMatch
535
{
536
public:
537
  SimpleMatch(string mask, bool caseFold = false) :
538
    d_mask(std::move(mask)), d_fold(caseFold)
539
0
  {
540
0
  }
541
542
  bool match(string::const_iterator mi, string::const_iterator mend, string::const_iterator vi, string::const_iterator vend) const
543
0
  {
544
0
    for(;;++mi) {
545
0
      if (mi == mend) {
546
0
        return vi == vend;
547
0
      } else if (*mi == '?') {
548
0
        if (vi == vend) return false;
549
0
        ++vi;
550
0
      } else if (*mi == '*') {
551
0
        while(mi != mend && *mi == '*') ++mi;
552
0
        if (mi == mend) return true;
553
0
        while(vi != vend) {
554
0
          if (match(mi,mend,vi,vend)) return true;
555
0
          ++vi;
556
0
        }
557
0
        return false;
558
0
      } else {
559
0
        if ((mi == mend && vi != vend)||
560
0
            (mi != mend && vi == vend)) return false;
561
0
        if (d_fold) {
562
0
          if (dns_tolower(*mi) != dns_tolower(*vi)) return false;
563
0
        } else {
564
0
          if (*mi != *vi) return false;
565
0
        }
566
0
        ++vi;
567
0
      }
568
0
    }
569
0
  }
570
571
0
  bool match(const string& value) const {
572
0
    return match(d_mask.begin(), d_mask.end(), value.begin(), value.end());
573
0
  }
574
575
0
  bool match(const DNSName& name) const {
576
0
    return match(name.toStringNoDot());
577
0
  }
578
579
#if defined(PDNS_AUTH) // [
580
0
  bool match(const ZoneName& name) const {
581
0
    return match(name.toStringNoDot());
582
0
  }
583
#endif // ]
584
585
private:
586
  const string d_mask;
587
  const bool d_fold;
588
};
589
590
union ComboAddress;
591
592
// An aligned type to hold cmsgbufs. See https://man.openbsd.org/CMSG_DATA
593
typedef union { struct cmsghdr hdr; char buf[256]; } cmsgbuf_aligned;
594
595
/* itfIndex is an interface index, as returned by if_nametoindex(). 0 means default. */
596
void addCMsgSrcAddr(struct msghdr* msgh, cmsgbuf_aligned* cbuf, const ComboAddress* source, int itfIndex);
597
598
unsigned int getFilenumLimit(bool hardOrSoft=0);
599
void setFilenumLimit(unsigned int lim);
600
bool readFileIfThere(const char* fname, std::string* line);
601
bool setSocketTimestamps(int fd);
602
603
//! Sets the socket into blocking mode.
604
bool setBlocking( int sock );
605
606
void setDscp(int sock, unsigned short family, uint8_t dscp);
607
608
//! Sets the socket into non-blocking mode.
609
bool setNonBlocking( int sock );
610
bool setTCPNoDelay(int sock);
611
bool setReuseAddr(int sock);
612
bool isNonBlocking(int sock);
613
bool setReceiveSocketErrors(int sock, int af);
614
int closesocket(int socket);
615
bool setCloseOnExec(int sock);
616
617
size_t getPipeBufferSize(int fd);
618
bool setPipeBufferSize(int fd, size_t size);
619
620
uint64_t udpErrorStats(const std::string& str);
621
uint64_t udp6ErrorStats(const std::string& str);
622
uint64_t tcpErrorStats(const std::string& str);
623
uint64_t getRealMemoryUsage(const std::string&);
624
uint64_t getSpecialMemoryUsage(const std::string&);
625
uint64_t getOpenFileDescriptors(const std::string&);
626
uint64_t getCPUTimeUser(const std::string&);
627
uint64_t getCPUTimeSystem(const std::string&);
628
uint64_t getCPUIOWait(const std::string&);
629
uint64_t getCPUSteal(const std::string&);
630
std::string getMACAddress(const ComboAddress& ca);
631
int getMACAddress(const ComboAddress& ca, char* dest, size_t len);
632
633
template<typename T>
634
const T& defTer(const T& a, const T& b)
635
{
636
  return a ? a : b;
637
}
638
639
template<typename P, typename T>
640
T valueOrEmpty(const P val) {
641
  if (!val) return T{};
642
  return T(val);
643
}
644
645
646
// I'm not very OCD, but I appreciate loglines like "processing 1 delta", "processing 2 deltas" :-)
647
template <typename Integer,
648
typename std::enable_if_t<std::is_integral_v<Integer>, bool> = true>
649
const char* addS(Integer siz, const char* singular = "", const char *plural = "s")
650
{
651
  if (siz == 1) {
652
    return singular;
653
  }
654
  return plural;
655
}
656
657
template <typename C,
658
typename std::enable_if_t<std::is_class_v<C>, bool> = true>
659
const char* addS(const C& c, const char* singular = "", const char *plural = "s")
660
{
661
  return addS(c.size(), singular, plural);
662
}
663
664
template<typename C>
665
const typename C::value_type::second_type* rplookup(const C& c, const typename C::value_type::first_type& key)
666
{
667
  auto fnd = c.find(key);
668
  if(fnd == c.end())
669
    return 0;
670
  return &fnd->second;
671
}
672
673
double DiffTime(const struct timespec& first, const struct timespec& second);
674
double DiffTime(const struct timeval& first, const struct timeval& second);
675
uid_t strToUID(const string &str);
676
gid_t strToGID(const string &str);
677
678
namespace pdns
679
{
680
/**
681
 * \brief Does a checked conversion from one integer type to another.
682
 *
683
 * \warning The source type `F` and target type `T` must have the same
684
 * signedness, otherwise a compilation error is thrown.
685
 *
686
 * \exception std::out_of_range Thrown if the source value does not fit
687
 * in the target type.
688
 *
689
 * \param[in] from The source value of type `F`.
690
 *
691
 * \return The target value of type `T`.
692
 */
693
template <typename T, typename F>
694
auto checked_conv(F from) -> T
695
0
{
696
0
  static_assert(std::numeric_limits<F>::is_integer, "checked_conv: The `F` type must be an integer");
697
0
  static_assert(std::numeric_limits<T>::is_integer, "checked_conv: The `T` type must be an integer");
698
0
  static_assert((std::numeric_limits<F>::is_signed && std::numeric_limits<T>::is_signed) || (!std::numeric_limits<F>::is_signed && !std::numeric_limits<T>::is_signed),
699
0
                "checked_conv: The `T` and `F` types must either both be signed or unsigned");
700
701
0
  constexpr auto tMin = std::numeric_limits<T>::min();
702
  if constexpr (std::numeric_limits<F>::min() != tMin) {
703
    if (from < tMin) {
704
      string s = "checked_conv: source value " + std::to_string(from) + " is smaller than target's minimum possible value " + std::to_string(tMin);
705
      throw std::out_of_range(s);
706
    }
707
  }
708
709
0
  constexpr auto tMax = std::numeric_limits<T>::max();
710
0
  if constexpr (std::numeric_limits<F>::max() != tMax) {
711
0
    if (from > tMax) {
712
0
      string s = "checked_conv: source value " + std::to_string(from) + " is larger than target's maximum possible value " + std::to_string(tMax);
713
0
      throw std::out_of_range(s);
714
0
    }
715
0
  }
716
717
0
  return static_cast<T>(from);
718
0
}
Unexecuted instantiation: unsigned char pdns::checked_conv<unsigned char, unsigned long long>(unsigned long long)
Unexecuted instantiation: unsigned int pdns::checked_conv<unsigned int, unsigned long long>(unsigned long long)
Unexecuted instantiation: unsigned short pdns::checked_conv<unsigned short, unsigned long long>(unsigned long long)
719
720
/**
721
 * \brief Performs a conversion from `std::string&` to integer.
722
 *
723
 * This function internally calls `std::stoll` and `std::stoull` to do
724
 * the conversion from `std::string&` and calls `pdns::checked_conv` to
725
 * do the checked conversion from `long long`/`unsigned long long` to
726
 * `T`.
727
 *
728
 * \warning The target type `T` must be an integer, otherwise a
729
 * compilation error is thrown.
730
 *
731
 * \exception std:stoll Throws what std::stoll throws.
732
 *
733
 * \exception std::stoull Throws what std::stoull throws.
734
 *
735
 * \exception pdns::checked_conv Throws what pdns::checked_conv throws.
736
 *
737
 * \param[in] str The input string to be converted.
738
 *
739
 * \param[in] idx Location to store the index at which processing
740
 * stopped. If the input `str` is empty, `*idx` shall be set to 0.
741
 *
742
 * \param[in] base The numerical base for conversion.
743
 *
744
 * \return `str` converted to integer `T`, or 0 if `str` is empty.
745
 */
746
template <typename T>
747
auto checked_stoi(const std::string& str, size_t* idx = nullptr, int base = 10) -> T
748
0
{
749
0
  static_assert(std::numeric_limits<T>::is_integer, "checked_stoi: The `T` type must be an integer");
750
751
0
  if (str.empty()) {
752
0
    if (idx != nullptr) {
753
0
      *idx = 0;
754
0
    }
755
756
0
    return 0; // compatibility
757
0
  }
758
759
0
  if constexpr (std::is_unsigned_v<T>) {
760
0
    return pdns::checked_conv<T>(std::stoull(str, idx, base));
761
  }
762
  else {
763
    return pdns::checked_conv<T>(std::stoll(str, idx, base));
764
  }
765
0
}
Unexecuted instantiation: unsigned char pdns::checked_stoi<unsigned char>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, unsigned long*, int)
Unexecuted instantiation: unsigned int pdns::checked_stoi<unsigned int>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, unsigned long*, int)
Unexecuted instantiation: unsigned short pdns::checked_stoi<unsigned short>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, unsigned long*, int)
766
767
/**
768
 * \brief Performs a conversion from `std::string&` to integer.
769
 *
770
 * This function internally calls `pdns::checked_stoi` and stores its
771
 * result in `out`.
772
 *
773
 * \exception pdns::checked_stoi Throws what pdns::checked_stoi throws.
774
 *
775
 * \param[out] out `str` converted to integer `T`, or 0 if `str` is
776
 * empty.
777
 *
778
 * \param[in] str The input string to be converted.
779
 *
780
 * \param[in] idx Location to store the index at which processing
781
 * stopped. If the input `str` is empty, `*idx` shall be set to 0.
782
 *
783
 * \param[in] base The numerical base for conversion.
784
 *
785
 * \return `str` converted to integer `T`, or 0 if `str` is empty.
786
 */
787
template <typename T>
788
auto checked_stoi_into(T& out, const std::string& str, size_t* idx = nullptr, int base = 10)
789
0
{
790
0
  out = checked_stoi<T>(str, idx, base);
791
0
}
Unexecuted instantiation: auto pdns::checked_stoi_into<unsigned int>(unsigned int&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, unsigned long*, int)
Unexecuted instantiation: auto pdns::checked_stoi_into<unsigned short>(unsigned short&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, unsigned long*, int)
792
}
793
794
bool isSettingThreadCPUAffinitySupported();
795
int mapThreadToCPUList(pthread_t tid, const std::set<int>& cpus);
796
797
std::vector<ComboAddress> getResolvers(const std::string& resolvConfPath);
798
799
DNSName reverseNameFromIP(const ComboAddress& ip);
800
801
size_t parseRFC1035CharString(const std::string &in, std::string &val); // from ragel
802
size_t parseSVCBValueListFromParsedRFC1035CharString(const std::string &in, vector<std::string> &val); // from ragel
803
size_t parseSVCBValueList(const std::string &in, vector<std::string> &val);
804
805
std::string makeLuaString(const std::string& in);
806
807
bool constantTimeStringEquals(const std::string& a, const std::string& b);
808
809
// Used in NID and L64 records
810
struct NodeOrLocatorID { uint8_t content[8]; };
811
812
struct FDWrapper
813
{
814
  FDWrapper() = default;
815
0
  FDWrapper(int desc): d_fd(desc) {}
816
  FDWrapper(const FDWrapper&) = delete;
817
  FDWrapper& operator=(const FDWrapper& rhs) = delete;
818
819
820
  ~FDWrapper()
821
0
  {
822
0
    reset();
823
0
  }
824
825
  FDWrapper(FDWrapper&& rhs) noexcept : d_fd(rhs.d_fd)
826
0
  {
827
0
    rhs.d_fd = -1;
828
0
  }
829
830
  FDWrapper& operator=(FDWrapper&& rhs) noexcept
831
0
  {
832
0
    if (d_fd >= 0) {
833
0
      close(d_fd);
834
0
    }
835
0
    d_fd = rhs.d_fd;
836
0
    rhs.d_fd = -1;
837
0
    return *this;
838
0
  }
839
840
  [[nodiscard]] int getHandle() const
841
0
  {
842
0
    return d_fd;
843
0
  }
844
845
  operator int() const
846
0
  {
847
0
    return d_fd;
848
0
  }
849
850
  int reset()
851
0
  {
852
0
    int ret = 0;
853
0
    if (d_fd >= 0) {
854
0
      ret = close(d_fd);
855
0
    }
856
0
    d_fd = -1;
857
0
    return ret;
858
0
  }
859
860
private:
861
  int d_fd{-1};
862
};
863
864
namespace pdns
865
{
866
[[nodiscard]] std::optional<std::string> visit_directory(const std::string& directory, const std::function<bool(ino_t inodeNumber, const std::string_view& name)>& visitor);
867
868
struct FilePtrDeleter
869
{
870
  /* using a deleter instead of decltype(&fclose) has two big advantages:
871
     - the deleter is included in the type and does not have to be passed
872
       when creating a new object (easier to use, less memory usage, in theory
873
       better inlining)
874
     - we avoid the annoying "ignoring attributes on template argument ‘int (*)(FILE*)’"
875
       warning from the compiler, which is there because fclose is tagged as __nonnull((1))
876
  */
877
0
  void operator()(FILE* filePtr) const noexcept {
878
0
    fclose(filePtr);
879
0
  }
880
};
881
882
using UniqueFilePtr = std::unique_ptr<FILE, FilePtrDeleter>;
883
884
UniqueFilePtr openFileForWriting(const std::string& filePath, mode_t permissions, bool mustNotExist = true, bool appendIfExists = false);
885
}