• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

PowerDNS / pdns / 39223413174

19 Oct 2026 08:31AM UTC coverage: 72.19% (-0.002%) from 72.192%
39223413174

push

github

web-flow
Merge pull request #18189 from miodvallat/reglyss

auth: fix invalid regexp

47479 of 83414 branches covered (56.92%)

Branch coverage included in aggregate %.

1 of 1 new or added line in 1 file covered. (100.0%)

58 existing lines in 13 files now uncovered.

136282 of 171137 relevant lines covered (79.63%)

7312839.41 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

60.18
/pdns/misc.cc
1
/*
2
 * This file is part of PowerDNS or dnsdist.
3
 * Copyright -- PowerDNS.COM B.V. and its contributors
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of version 2 of the GNU General Public License as
7
 * published by the Free Software Foundation.
8
 *
9
 * In addition, for the avoidance of any doubt, permission is granted to
10
 * link this program with OpenSSL and to (re)distribute the binaries
11
 * produced as the result of such linking.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
 */
22

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
{
1,412,185 ✔
79
  const char* ptr = static_cast<const char*>(buf);
1,412,185 ✔
80
  const char* eptr = ptr + count;
1,412,185 ✔
81

82
  while (ptr != eptr) {
2,824,323 ✔
83
    auto res = ::write(fileDesc, ptr, eptr - ptr);
1,412,138 ✔
84
    if (res < 0) {
1,412,138 !
85
      if (errno == EAGAIN) {
×
86
        throw std::runtime_error("used writen2 on non-blocking socket, got EAGAIN");
×
87
      }
×
88
      unixDie("failed in writen2");
×
89
    }
×
90
    else if (res == 0) {
1,412,138 !
91
      throw std::runtime_error("could not write all bytes, got eof in writen2");
×
92
    }
×
93

94
    ptr += res;
1,412,138 ✔
95
  }
1,412,138 ✔
96

97
  return count;
1,412,185 ✔
98
}
1,412,185 ✔
99

100
size_t readn2(int fileDesc, void* buffer, size_t len)
101
{
1,424 ✔
102
  size_t pos = 0;
1,424 ✔
103

104
  for (;;) {
1,424 ✔
105
    auto res = read(fileDesc, static_cast<char*>(buffer) + pos, len - pos); // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic): it's the API
1,424 ✔
106
    if (res == 0) {
1,424 ✔
107
      throw runtime_error("EOF while reading message");
407 ✔
108
    }
407 ✔
109
    if (res < 0) {
1,017 !
110
      if (errno == EAGAIN) {
×
111
        throw std::runtime_error("used readn2 on non-blocking socket, got EAGAIN");
×
112
      }
×
113
      unixDie("failed in readn2");
×
114
    }
×
115

116
    pos += static_cast<size_t>(res);
1,017 ✔
117
    if (pos == len) {
1,017 !
118
      break;
1,017 ✔
119
    }
1,017 ✔
120
  }
1,017 ✔
121
  return len;
1,017 ✔
122
}
1,424 ✔
123

124
size_t readn2WithTimeout(int fileDesc, void* buffer, size_t len, const struct timeval& idleTimeout, const struct timeval& totalTimeout, bool allowIncomplete)
125
{
1,943 ✔
126
  size_t pos = 0;
1,943 ✔
127
  struct timeval start{0, 0};
1,943 ✔
128
  struct timeval remainingTime = totalTimeout;
1,943 ✔
129
  if (totalTimeout.tv_sec != 0 || totalTimeout.tv_usec != 0) {
1,943 !
130
    gettimeofday(&start, nullptr);
63 ✔
131
  }
63 ✔
132

133
  do {
2,998 ✔
134
    ssize_t got = read(fileDesc, static_cast<char*>(buffer) + pos, len - pos);
2,998 ✔
135
    if (got > 0) {
2,998 ✔
136
      pos += (size_t)got;
1,966 ✔
137
      if (allowIncomplete) {
1,966 !
138
        break;
×
139
      }
×
140
    }
1,966 ✔
141
    else if (got == 0) {
1,032 ✔
142
      throw runtime_error("EOF while reading message");
5 ✔
143
    }
5 ✔
144
    else {
1,027 ✔
145
      if (errno == EAGAIN) {
1,027 !
146
        struct timeval waitTime = ((totalTimeout.tv_sec == 0 && totalTimeout.tv_usec == 0) || idleTimeout <= remainingTime) ? idleTimeout : remainingTime;
1,027 !
147
        int res = waitForData(fileDesc, waitTime);
1,027 ✔
148
        if (res > 0) {
1,027 ✔
149
          /* there is data available */
150
        }
1,026 ✔
151
        else if (res == 0) {
1 !
152
          throw runtime_error("Timeout while waiting for data to read");
×
153
        }
×
154
        else {
1 ✔
155
          throw runtime_error("Error while waiting for data to read");
1 ✔
156
        }
1 ✔
157
      }
1,027 ✔
158
      else {
×
159
        unixDie("failed in readn2WithTimeout");
×
160
      }
×
161
    }
1,027 ✔
162

163
    if (totalTimeout.tv_sec != 0 || totalTimeout.tv_usec != 0) {
2,992 !
164
      struct timeval now{};
170 ✔
165
      gettimeofday(&now, nullptr);
170 ✔
166
      struct timeval elapsed = now - start;
170 ✔
167
      if (remainingTime < elapsed) {
170 !
168
        throw runtime_error("Timeout while reading data");
×
169
      }
×
170
      start = now;
170 ✔
171
      remainingTime = remainingTime - elapsed;
170 ✔
172
    }
170 ✔
173
  } while (pos < len);
2,992 ✔
174

175
  return len;
1,937 ✔
176
}
1,943 ✔
177

178
size_t writen2WithTimeout(int fileDesc, const void* buffer, size_t len, const struct timeval& timeout)
179
{
1,119 ✔
180
  size_t pos = 0;
1,119 ✔
181
  do {
1,119 ✔
182
    ssize_t written = write(fileDesc, reinterpret_cast<const char*>(buffer) + pos, len - pos);
1,119 ✔
183

184
    if (written > 0) {
1,119 !
185
      pos += (size_t)written;
1,119 ✔
186
    }
1,119 ✔
187
    else if (written == 0) {
×
188
      throw runtime_error("EOF while writing message");
×
189
    }
×
190
    else {
×
191
      if (errno == EAGAIN) {
×
192
        int res = waitForRWData(fileDesc, false, timeout);
×
193
        if (res > 0) {
×
194
          /* there is room available */
195
        }
×
196
        else if (res == 0) {
×
197
          throw runtime_error("Timeout while waiting to write data");
×
198
        }
×
199
        else {
×
200
          throw runtime_error("Error while waiting for room to write data");
×
201
        }
×
202
      }
×
203
      else {
×
204
        unixDie("failed in write2WithTimeout");
×
205
      }
×
206
    }
×
207
  } while (pos < len);
1,119 !
208

209
  return len;
1,119 ✔
210
}
1,119 ✔
211

212
auto pdns::getMessageFromErrno(const int errnum) -> std::string
213
{
2,490 ✔
214
  const size_t errLen = 2048;
2,490 ✔
215
  std::string errMsgData{};
2,490 ✔
216
  errMsgData.resize(errLen);
2,490 ✔
217

218
  const char* errMsg = nullptr;
2,490 ✔
219
#ifdef STRERROR_R_CHAR_P
2,490 ✔
220
  errMsg = strerror_r(errnum, errMsgData.data(), errMsgData.length());
2,490 ✔
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
  std::string message{errMsg};
2,490 ✔
235
  return message;
2,490 ✔
236
}
2,490 ✔
237

238
#if defined(HAVE_LIBCRYPTO)
239
auto pdns::OpenSSL::error(const std::string& errorMessage) -> std::runtime_error
240
{
×
241
  unsigned long errorCode = 0;
×
242
  auto fullErrorMessage{errorMessage};
×
243
#if OPENSSL_VERSION_MAJOR >= 3
×
244
  const char* filename = nullptr;
×
245
  const char* functionName = nullptr;
×
246
  int lineNumber = 0;
×
247
  while ((errorCode = ERR_get_error_all(&filename, &lineNumber, &functionName, nullptr, nullptr)) != 0) {
×
248
    fullErrorMessage += std::string(": ") + std::to_string(errorCode);
×
249

250
    const auto* lib = ERR_lib_error_string(errorCode);
×
251
    if (lib != nullptr) {
×
252
      fullErrorMessage += std::string(":") + lib;
×
253
    }
×
254

255
    const auto* reason = ERR_reason_error_string(errorCode);
×
256
    if (reason != nullptr) {
×
257
      fullErrorMessage += std::string("::") + reason;
×
258
    }
×
259

260
    if (filename != nullptr) {
×
261
      fullErrorMessage += std::string(" - ") + filename;
×
262
    }
×
263
    if (lineNumber != 0) {
×
264
      fullErrorMessage += std::string(":") + std::to_string(lineNumber);
×
265
    }
×
266
    if (functionName != nullptr) {
×
267
      fullErrorMessage += std::string(" - ") + functionName;
×
268
    }
×
269
  }
×
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
  return std::runtime_error{fullErrorMessage};
×
291
}
×
292

293
auto pdns::OpenSSL::error(const std::string& componentName, const std::string& errorMessage) -> std::runtime_error
294
{
×
295
  return pdns::OpenSSL::error(componentName + ": " + errorMessage);
×
296
}
×
297
#endif // HAVE_LIBCRYPTO
298

299
string nowTime()
300
{
2,823 ✔
301
  time_t now = time(nullptr);
2,823 ✔
302
  struct tm theTime{};
2,823 ✔
303
  localtime_r(&now, &theTime);
2,823 ✔
304
  std::array<char, 30> buffer{};
2,823 ✔
305
  // YYYY-mm-dd HH:MM:SS TZOFF
306
  size_t ret = strftime(buffer.data(), buffer.size(), "%F %T %z", &theTime);
2,823 ✔
307
  if (ret == 0) {
2,823 !
308
    buffer[0] = '\0';
×
309
  }
×
310
  return {buffer.data()};
2,823 ✔
311
}
2,823 ✔
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
{
3,567,116 ✔
316
  return waitForRWData(fileDesc, true, seconds, mseconds);
3,567,116 ✔
317
}
3,567,116 ✔
318

319
int waitForData(int fileDesc, struct timeval timeout)
320
{
16,512 ✔
321
  return waitForRWData(fileDesc, true, timeout);
16,512 ✔
322
}
16,512 ✔
323

324
int waitForRWData(int fileDesc, bool waitForRead, int seconds, int mseconds, bool* error, bool* disconnected)
325
{
3,589,576 ✔
326
  struct pollfd pfd{};
3,589,576 ✔
327
  memset(&pfd, 0, sizeof(pfd));
3,589,576 ✔
328
  pfd.fd = fileDesc;
3,589,576 ✔
329

330
  if (waitForRead) {
3,589,576 ✔
331
    pfd.events = POLLIN;
3,586,217 ✔
332
  }
3,586,217 ✔
333
  else {
3,359 ✔
334
    pfd.events = POLLOUT;
3,359 ✔
335
  }
3,359 ✔
336

337
  int ret = poll(&pfd, 1, (seconds * 1000) + mseconds);
3,589,576 ✔
338
  if (ret > 0) {
3,589,577 ✔
339
    if ((error != nullptr) && (pfd.revents & POLLERR) != 0) {
3,090,938 ✔
340
      *error = true;
37 ✔
341
    }
37 ✔
342
    if ((disconnected != nullptr) && (pfd.revents & POLLHUP) != 0) {
3,090,938 ✔
343
      *disconnected = true;
37 ✔
344
    }
37 ✔
345
  }
3,090,938 ✔
346

347
  return ret;
3,589,576 ✔
348
}
3,589,576 ✔
349

350
int waitForRWData(int fileDesc, bool waitForRead, struct timeval timeout, bool* error, bool* disconnected)
351
{
17,820 ✔
352
  return waitForRWData(fileDesc, waitForRead, static_cast<int>(timeout.tv_sec), static_cast<int>(timeout.tv_usec / 1000), error, disconnected);
17,820 ✔
353
}
17,820 ✔
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
{
2,293 ✔
358
  set<int> realFDs;
2,293 ✔
359
  for (const auto& anFd : fds) {
4,586 ✔
360
    if (anFd >= 0 && realFDs.count(anFd) == 0) {
4,586 !
361
      realFDs.insert(anFd);
4,560 ✔
362
    }
4,560 ✔
363
  }
4,586 ✔
364

365
  std::vector<struct pollfd> pfds(realFDs.size());
2,293 ✔
366
  memset(pfds.data(), 0, realFDs.size() * sizeof(struct pollfd));
2,293 ✔
367
  int ctr = 0;
2,293 ✔
368
  for (const auto& anFd : realFDs) {
4,560 ✔
369
    pfds[ctr].fd = anFd;
4,560 ✔
370
    pfds[ctr].events = POLLIN;
4,560 ✔
371
    ctr++;
4,560 ✔
372
  }
4,560 ✔
373

374
  int ret{};
2,293 ✔
375
  if (seconds >= 0) {
2,293 !
376
    ret = poll(pfds.data(), realFDs.size(), (seconds * 1000) + mseconds);
2,293 ✔
377
  }
2,293 ✔
378
  else {
×
379
    ret = poll(pfds.data(), realFDs.size(), -1);
×
380
  }
×
381
  if (ret <= 0) {
2,293 ✔
382
    return ret;
2,287 ✔
383
  }
2,287 ✔
384

385
  set<int> pollinFDs;
6 ✔
386
  for (const auto& pfd : pfds) {
6 ✔
387
    if ((pfd.revents & POLLIN) != 0) {
6 !
388
      pollinFDs.insert(pfd.fd);
6 ✔
389
    }
6 ✔
390
  }
6 ✔
391
  auto iter(pollinFDs.begin());
6 ✔
392
  advance(iter, dns_random(pollinFDs.size()));
6 ✔
393
  *fdOut = *iter;
6 ✔
394
  return 1;
6 ✔
395
}
2,293 ✔
396

397
string humanDuration(time_t passed)
398
{
4 ✔
399
  ostringstream ret;
4 ✔
400
  if (passed < 60) {
4 !
401
    ret << passed << " seconds";
4 ✔
402
  }
4 ✔
403
  else if (passed < 3600) {
×
404
    ret << std::setprecision(2) << static_cast<double>(passed) / 60.0 << " minutes";
×
405
  }
×
406
  else if (passed < 86400) {
×
407
    ret << std::setprecision(3) << static_cast<double>(passed) / 3600.0 << " hours";
×
408
  }
×
409
  else if (static_cast<double>(passed) < (86400 * 30.41)) {
×
410
    ret << std::setprecision(3) << static_cast<double>(passed) / 86400.0 << " days";
×
411
  }
×
412
  else {
×
413
    ret << std::setprecision(3) << static_cast<double>(passed) / (86400 * 30.41) << " months";
×
414
  }
×
415

416
  return ret.str();
4 ✔
417
}
4 ✔
418

419
string unquotify(const string& item)
420
{
11 ✔
421
  if (item.size() < 2) {
11 ✔
422
    return item;
2 ✔
423
  }
2 ✔
424

425
  string::size_type bpos = 0;
9 ✔
426
  string::size_type epos = item.size();
9 ✔
427

428
  if (item[0] == '"') {
9 !
429
    bpos = 1;
9 ✔
430
  }
9 ✔
431

432
  if (item[epos - 1] == '"') {
9 !
433
    epos -= 1;
9 ✔
434
  }
9 ✔
435

436
  return item.substr(bpos, epos - bpos);
9 ✔
437
}
11 ✔
438

439
void stripLine(string& line)
440
{
×
441
  string::size_type pos = line.find_first_of("\r\n");
×
442
  if (pos != string::npos) {
×
443
    line.resize(pos);
×
444
  }
×
445
}
×
446

447
string urlEncode(const string& text)
448
{
×
449
  string ret;
×
450
  for (char index : text) {
×
451
    if (index == ' ') {
×
452
      ret.append("%20");
×
453
    }
×
454
    else {
×
455
      ret.append(1, index);
×
456
    }
×
457
  }
×
458
  return ret;
×
459
}
×
460

461
static size_t getMaxHostNameSize()
462
{
2,452 ✔
463
#if defined(HOST_NAME_MAX)
2,452 ✔
464
  return HOST_NAME_MAX;
2,452 ✔
465
#endif
×
466

467
#if defined(_SC_HOST_NAME_MAX)
×
468
  auto tmp = sysconf(_SC_HOST_NAME_MAX);
×
469
  if (tmp != -1) {
×
470
    return tmp;
×
471
  }
×
472
#endif
×
473

474
  const size_t maxHostNameSize = 255;
×
475
  return maxHostNameSize;
×
476
}
×
477

478
std::optional<string> getHostname()
479
{
2,452 ✔
480
  const size_t maxHostNameBufSize = getMaxHostNameSize() + 1;
2,452 ✔
481
  std::string hostname;
2,452 ✔
482
  hostname.resize(maxHostNameBufSize, 0);
2,452 ✔
483

484
  if (gethostname(hostname.data(), maxHostNameBufSize) == -1) {
2,452 !
485
    return std::nullopt;
×
486
  }
×
487

488
  hostname.resize(strlen(hostname.c_str()));
2,452 ✔
489
  return std::make_optional(hostname);
2,452 ✔
490
}
2,452 ✔
491

492
std::string getCarbonHostName()
493
{
175 ✔
494
  auto hostname = getHostname();
175 ✔
495
  if (!hostname.has_value()) {
175 !
496
    throw std::runtime_error(stringerror());
×
497
  }
×
498

499
  std::replace(hostname->begin(), hostname->end(), '.', '_');
175 ✔
500
  return *hostname;
175 ✔
501
}
175 ✔
502

503
void cleanSlashes(string& str)
504
{
7,962 ✔
505
  string out;
7,962 ✔
506
  bool keepNextSlash = true;
7,962 ✔
507
  for (const auto& value : str) {
151,883 ✔
508
    if (value == '/') {
151,883 ✔
509
      if (keepNextSlash) {
10,045 ✔
510
        keepNextSlash = false;
9,838 ✔
511
      }
9,838 ✔
512
      else {
207 ✔
513
        continue;
207 ✔
514
      }
207 ✔
515
    }
10,045 ✔
516
    else {
141,838 ✔
517
      keepNextSlash = true;
141,838 ✔
518
    }
141,838 ✔
519
    out.append(1, value);
151,676 ✔
520
  }
151,676 ✔
521
  str = std::move(out);
7,962 ✔
522
}
7,962 ✔
523

524
bool IpToU32(const string& str, uint32_t* ptr)
525
{
×
526
  if (str.empty()) {
×
527
    *ptr = 0;
×
528
    return true;
×
529
  }
×
530

531
  struct in_addr inp{};
×
532
  if (inet_aton(str.c_str(), &inp) != 0) {
×
533
    *ptr = inp.s_addr;
×
534
    return true;
×
535
  }
×
536
  return false;
×
537
}
×
538

539
string U32ToIP(uint32_t val)
540
{
×
541
  std::array<char, 17> tmp{};
×
542
  snprintf(tmp.data(), tmp.size(), "%u.%u.%u.%u",
×
543
           (val >> 24) & 0xff,
×
544
           (val >> 16) & 0xff,
×
545
           (val >> 8) & 0xff,
×
546
           (val) & 0xff);
×
547
  return tmp.data();
×
548
}
×
549

550
string makeHexDump(const string& str, const string& sep)
551
{
2,116 ✔
552
  std::array<char, 5> tmp{};
2,116 ✔
553
  string ret;
2,116 ✔
554
  ret.reserve(static_cast<size_t>(str.size() * (2 + sep.size())));
2,116 ✔
555

556
  for (char index : str) {
91,234 ✔
557
    snprintf(tmp.data(), tmp.size(), "%02x", static_cast<unsigned char>(index));
91,234 ✔
558
    ret += tmp.data();
91,234 ✔
559
    ret += sep;
91,234 ✔
560
  }
91,234 ✔
561
  return ret;
2,116 ✔
562
}
2,116 ✔
563

564
string makeBytesFromHex(const string& str)
565
{
9 ✔
566
  if (str.size() % 2 != 0) {
9 ✔
567
    throw std::range_error("odd number of bytes in hex string");
3 ✔
568
  }
3 ✔
569
  string ret;
6 ✔
570
  ret.reserve(str.size() / 2);
6 ✔
571

572
  for (size_t i = 0; i < str.size(); i += 2) {
36 ✔
573
    const auto numStr = str.substr(i, 2);
33 ✔
574
    unsigned int num = 0;
33 ✔
575
    if (sscanf(numStr.c_str(), "%02x", &num) != 1) {
33 ✔
576
      throw std::range_error("Invalid value while parsing the hex string '" + str + "'");
3 ✔
577
    }
3 ✔
578
    ret.push_back(static_cast<char>(num));
30 ✔
579
  }
30 ✔
580

581
  return ret;
3 ✔
582
}
6 ✔
583

584
void normalizeTV(struct timeval& timeval)
585
{
304,892 ✔
586
  if (timeval.tv_usec > 1000000) {
304,892 ✔
587
    ++timeval.tv_sec;
5,622 ✔
588
    timeval.tv_usec -= 1000000;
5,622 ✔
589
  }
5,622 ✔
590
  else if (timeval.tv_usec < 0) {
299,270 ✔
591
    --timeval.tv_sec;
43,626 ✔
592
    timeval.tv_usec += 1000000;
43,626 ✔
593
  }
43,626 ✔
594
}
304,892 ✔
595

596
struct timeval operator+(const struct timeval& lhs, const struct timeval& rhs)
597
{
11,942 ✔
598
  struct timeval ret{};
11,942 ✔
599
  ret.tv_sec = lhs.tv_sec + rhs.tv_sec;
11,942 ✔
600
  ret.tv_usec = lhs.tv_usec + rhs.tv_usec;
11,942 ✔
601
  normalizeTV(ret);
11,942 ✔
602
  return ret;
11,942 ✔
603
}
11,942 ✔
604

605
struct timeval operator-(const struct timeval& lhs, const struct timeval& rhs)
606
{
158,836 ✔
607
  struct timeval ret{};
158,836 ✔
608
  ret.tv_sec = lhs.tv_sec - rhs.tv_sec;
158,836 ✔
609
  ret.tv_usec = lhs.tv_usec - rhs.tv_usec;
158,836 ✔
610
  normalizeTV(ret);
158,836 ✔
611
  return ret;
158,836 ✔
612
}
158,836 ✔
613

614
pair<string, string> splitField(const string& inp, char sepa)
615
{
879,018 ✔
616
  pair<string, string> ret;
879,018 ✔
617
  string::size_type cpos = inp.find(sepa);
879,018 ✔
618
  if (cpos == string::npos) {
879,018 ✔
619
    ret.first = inp;
404,962 ✔
620
  }
404,962 ✔
621
  else {
474,056 ✔
622
    ret.first = inp.substr(0, cpos);
474,056 ✔
623
    ret.second = inp.substr(cpos + 1);
474,056 ✔
624
  }
474,056 ✔
625
  return ret;
879,018 ✔
626
}
879,018 ✔
627

628
int logFacilityToLOG(unsigned int facility)
629
{
×
630
  switch (facility) {
×
631
  case 0:
×
632
    return LOG_LOCAL0;
×
633
  case 1:
×
634
    return (LOG_LOCAL1);
×
635
  case 2:
×
636
    return (LOG_LOCAL2);
×
637
  case 3:
×
638
    return (LOG_LOCAL3);
×
639
  case 4:
×
640
    return (LOG_LOCAL4);
×
641
  case 5:
×
642
    return (LOG_LOCAL5);
×
643
  case 6:
×
644
    return (LOG_LOCAL6);
×
645
  case 7:
×
646
    return (LOG_LOCAL7);
×
647
  default:
×
648
    return -1;
×
649
  }
×
650
}
×
651

652
std::optional<int> logFacilityFromString(std::string facilityStr)
653
{
×
654
  static std::unordered_map<std::string, int> const s_facilities = {
×
655
    {"local0", LOG_LOCAL0},
×
656
    {"log_local0", LOG_LOCAL0},
×
657
    {"local1", LOG_LOCAL1},
×
658
    {"log_local1", LOG_LOCAL1},
×
659
    {"local2", LOG_LOCAL2},
×
660
    {"log_local2", LOG_LOCAL2},
×
661
    {"local3", LOG_LOCAL3},
×
662
    {"log_local3", LOG_LOCAL3},
×
663
    {"local4", LOG_LOCAL4},
×
664
    {"log_local4", LOG_LOCAL4},
×
665
    {"local5", LOG_LOCAL5},
×
666
    {"log_local5", LOG_LOCAL5},
×
667
    {"local6", LOG_LOCAL6},
×
668
    {"log_local6", LOG_LOCAL6},
×
669
    {"local7", LOG_LOCAL7},
×
670
    {"log_local7", LOG_LOCAL7},
×
671
    /* most of these likely make very little sense
672
       for us, but why not? */
673
    {"kern", LOG_KERN},
×
674
    {"log_kern", LOG_KERN},
×
675
    {"user", LOG_USER},
×
676
    {"log_user", LOG_USER},
×
677
    {"mail", LOG_MAIL},
×
678
    {"log_mail", LOG_MAIL},
×
679
    {"daemon", LOG_DAEMON},
×
680
    {"log_daemon", LOG_DAEMON},
×
681
    {"auth", LOG_AUTH},
×
682
    {"log_auth", LOG_AUTH},
×
683
    {"syslog", LOG_SYSLOG},
×
684
    {"log_syslog", LOG_SYSLOG},
×
685
    {"lpr", LOG_LPR},
×
686
    {"log_lpr", LOG_LPR},
×
687
    {"news", LOG_NEWS},
×
688
    {"log_news", LOG_NEWS},
×
689
    {"uucp", LOG_UUCP},
×
690
    {"log_uucp", LOG_UUCP},
×
691
    {"cron", LOG_CRON},
×
692
    {"log_cron", LOG_CRON},
×
693
    {"authpriv", LOG_AUTHPRIV},
×
694
    {"log_authpriv", LOG_AUTHPRIV},
×
695
    {"ftp", LOG_FTP},
×
696
    {"log_ftp", LOG_FTP}};
×
697

698
  toLowerInPlace(facilityStr);
×
699
  auto facilityIt = s_facilities.find(facilityStr);
×
700
  if (facilityIt == s_facilities.end()) {
×
701
    return std::nullopt;
×
702
  }
×
703

704
  return facilityIt->second;
×
705
}
×
706

707
string stripDot(const string& dom)
708
{
671,626 ✔
709
  if (dom.empty()) {
671,626 ✔
710
    return dom;
3 ✔
711
  }
3 ✔
712

713
  if (dom[dom.size() - 1] != '.') {
671,623 ✔
714
    return dom;
671,176 ✔
715
  }
671,176 ✔
716

717
  return dom.substr(0, dom.size() - 1);
447 ✔
718
}
671,623 ✔
719

720
int makeIPv6sockaddr(const std::string& addr, struct sockaddr_in6* ret)
721
{
1,642,876 ✔
722
  if (addr.empty()) {
1,642,876 ✔
723
    return -1;
17 ✔
724
  }
17 ✔
725

726
  string ourAddr(addr);
1,642,859 ✔
727
  std::optional<uint16_t> port = std::nullopt;
1,642,859 ✔
728

729
  if (addr[0] == '[') { // [::]:53 style address
1,642,859 ✔
730
    string::size_type pos = addr.find(']');
131,597 ✔
731
    if (pos == string::npos) {
131,597 !
732
      return -1;
×
733
    }
×
734

735
    ourAddr.assign(addr.c_str() + 1, pos - 1);
131,597 ✔
736
    if (pos + 1 != addr.size()) { // complete after ], no port specified
131,597 ✔
737
      if (pos + 2 > addr.size() || addr[pos + 1] != ':') {
131,573 !
738
        return -1;
×
739
      }
×
740

741
      try {
131,573 ✔
742
        auto tmpPort = pdns::checked_stoi<uint16_t>(addr.substr(pos + 2));
131,573 ✔
743
        port = std::make_optional(tmpPort);
131,573 ✔
744
      }
131,573 ✔
745
      catch (const std::logic_error&) {
131,573 ✔
746
        return -1;
24 ✔
747
      }
24 ✔
748
    }
131,573 ✔
749
  }
131,597 ✔
750

751
  ret->sin6_scope_id = 0;
1,642,835 ✔
752
  ret->sin6_family = AF_INET6;
1,642,835 ✔
753

754
  if (inet_pton(AF_INET6, ourAddr.c_str(), (void*)&ret->sin6_addr) != 1) {
1,642,835 ✔
755
    struct addrinfo hints{};
458 ✔
756
    std::memset(&hints, 0, sizeof(struct addrinfo));
458 ✔
757
    hints.ai_flags = AI_NUMERICHOST;
458 ✔
758
    hints.ai_family = AF_INET6;
458 ✔
759

760
    struct addrinfo* res = nullptr;
458 ✔
761
    // getaddrinfo has anomalous return codes, anything nonzero is an error, positive or negative
762
    if (getaddrinfo(ourAddr.c_str(), nullptr, &hints, &res) != 0) {
458 !
763
      return -1;
458 ✔
764
    }
458 ✔
765

766
    memcpy(ret, res->ai_addr, res->ai_addrlen);
×
767
    freeaddrinfo(res);
×
768
  }
×
769

770
  if (port.has_value()) {
1,642,377 ✔
771
    ret->sin6_port = htons(*port);
131,549 ✔
772
  }
131,549 ✔
773

774
  return 0;
1,642,377 ✔
775
}
1,642,835 ✔
776

777
int makeIPv4sockaddr(const std::string& arg, struct sockaddr_in* ret)
778
{
3,556,875 ✔
779
  std::string str(arg);
3,556,875 ✔
780
  if (str.empty()) {
3,556,875 ✔
781
    return -1;
17 ✔
782
  }
17 ✔
783
  struct in_addr inp{};
3,556,858 ✔
784

785
  string::size_type pos = str.find(':');
3,556,858 ✔
786
  if (pos == string::npos) { // no port specified, not touching the port
3,556,858 ✔
787
    if (inet_aton(str.c_str(), &inp) != 0) {
1,504,929 ✔
788
      ret->sin_addr.s_addr = inp.s_addr;
1,504,505 ✔
789
      return 0;
1,504,505 ✔
790
    }
1,504,505 ✔
791
    return -1;
424 ✔
792
  }
1,504,929 ✔
793
  if (*(str.c_str() + pos + 1) == 0) { // trailing :
2,051,929 ✔
794
    return -1;
1 ✔
795
  }
1 ✔
796

797
  auto* eptr = str.data() + str.size();
2,051,928 ✔
798
  int port = static_cast<int>(strtol(str.c_str() + pos + 1, &eptr, 10));
2,051,928 ✔
799
  if (port < 0 || port > 65535) {
2,051,928 ✔
800
    return -1;
24 ✔
801
  }
24 ✔
802
  if (*eptr != 0) {
2,051,904 ✔
803
    return -1;
1,642,410 ✔
804
  }
1,642,410 ✔
805

806
  ret->sin_port = htons(port);
409,494 ✔
807
  if (inet_aton(str.substr(0, pos).c_str(), &inp) != 0) {
409,494 !
808
    ret->sin_addr.s_addr = inp.s_addr;
409,494 ✔
809
    return 0;
409,494 ✔
810
  }
409,494 ✔
811
  return -1;
×
812
}
409,494 ✔
813

814
int makeUNsockaddr(const std::string& path, struct sockaddr_un* ret)
815
{
1,562 ✔
816
  if (path.empty()) {
1,562 ✔
817
    return -1;
6 ✔
818
  }
6 ✔
819
  memset(ret, 0, sizeof(struct sockaddr_un));
1,556 ✔
820
  ret->sun_family = AF_UNIX;
1,556 ✔
821
  if (path.length() >= sizeof(ret->sun_path)) {
1,556 !
822
    return -1;
×
823
  }
×
824
  path.copy(&ret->sun_path[0], sizeof(ret->sun_path), 0);
1,556 ✔
825
  return 0;
1,556 ✔
826
}
1,556 ✔
827

828
//! read a line of text from a FILE* to a std::string, returns false on 'no data'
829
bool stringfgets(FILE* file, std::string& line)
830
{
4,343,476 ✔
831
  std::array<char, 1024> buffer{};
4,343,476 ✔
832
  line.clear();
4,343,476 ✔
833

834
  do {
4,343,793 ✔
835
    if (fgets(buffer.data(), buffer.size(), file) == nullptr) {
4,343,793 ✔
836
      return !line.empty();
4,434 ✔
837
    }
4,434 ✔
838
    line.append(buffer.data());
4,339,359 ✔
839
  } while (strchr(buffer.data(), '\n') == nullptr);
4,339,359 ✔
840
  return true;
4,339,042 ✔
841
}
4,343,476 ✔
842

843
bool readFileIfThere(const char* fname, std::string* line)
844
{
406 ✔
845
  line->clear();
406 ✔
846
  auto filePtr = pdns::UniqueFilePtr(fopen(fname, "r"));
406 ✔
847
  if (!filePtr) {
406 !
848
    return false;
×
849
  }
×
850
  return stringfgets(filePtr.get(), *line);
406 ✔
851
}
406 ✔
852

853
Regex::Regex(const string& expr) :
854
  d_preg(new regex_t)
309 ✔
855
{
309 ✔
856
  if (auto ret = regcomp(d_preg.get(), expr.c_str(), REG_ICASE | REG_NOSUB | REG_EXTENDED); ret != 0) {
309 !
857
    std::array<char, 1024> errorBuffer{};
×
858
    if (regerror(ret, d_preg.get(), errorBuffer.data(), errorBuffer.size()) > 0) {
×
859
      throw PDNSException("Regular expression " + expr + " did not compile: " + errorBuffer.data());
×
860
    }
×
861
    throw PDNSException("Regular expression " + expr + " did not compile");
×
862
  }
×
863
}
309 ✔
864

865
/** call this to find out if 'line' matches your expression */
866
bool Regex::match(const string& line) const
867
{
1,694,609 ✔
868
  return regexec(d_preg.get(), line.c_str(), 0, nullptr, 0) == 0;
1,694,609 ✔
869
}
1,694,609 ✔
870

871
bool Regex::match(const DNSName& name) const
872
{
×
873
  return match(name.toStringNoDot());
×
874
}
×
875

876
// if you end up here because valgrind told you were are doing something wrong
877
// with msgh->msg_controllen, please refer to https://github.com/PowerDNS/pdns/pull/3962
878
// first.
879
// Note that cmsgbuf should be aligned the same as a struct cmsghdr
880
void addCMsgSrcAddr(struct msghdr* msgh, cmsgbuf_aligned* cmsgbuf, const ComboAddress* source, int itfIndex)
881
{
30,580 ✔
882
  struct cmsghdr* cmsg = nullptr;
30,580 ✔
883

884
  if (source->sin4.sin_family == AF_INET6) {
30,580 ✔
885
    struct in6_pktinfo* pkt{};
1 ✔
886

887
    msgh->msg_control = cmsgbuf;
1 ✔
888
#if !defined(__APPLE__)
1 ✔
889
    /* CMSG_SPACE is not a constexpr on macOS */
890
    static_assert(CMSG_SPACE(sizeof(*pkt)) <= sizeof(*cmsgbuf), "Buffer is too small for in6_pktinfo");
1 ✔
891
#else /* __APPLE__ */
892
    if (CMSG_SPACE(sizeof(*pkt)) > sizeof(*cmsgbuf)) {
893
      throw std::runtime_error("Buffer is too small for in6_pktinfo");
894
    }
895
#endif /* __APPLE__ */
896
    msgh->msg_controllen = CMSG_SPACE(sizeof(*pkt));
1 ✔
897

898
    cmsg = CMSG_FIRSTHDR(msgh);
1 !
899
    cmsg->cmsg_level = IPPROTO_IPV6;
1 ✔
900
    cmsg->cmsg_type = IPV6_PKTINFO;
1 ✔
901
    cmsg->cmsg_len = CMSG_LEN(sizeof(*pkt));
1 ✔
902

903
    pkt = reinterpret_cast<struct in6_pktinfo*>(CMSG_DATA(cmsg));
1 ✔
904
    // Include the padding to stop valgrind complaining about passing uninitialized data
905
    memset(pkt, 0, CMSG_SPACE(sizeof(*pkt)));
1 ✔
906
    pkt->ipi6_addr = source->sin6.sin6_addr;
1 ✔
907
    pkt->ipi6_ifindex = itfIndex;
1 ✔
908
  }
1 ✔
909
  else {
30,579 ✔
910
#if defined(IP_PKTINFO)
30,579 ✔
911
    struct in_pktinfo* pkt{};
30,579 ✔
912

913
    msgh->msg_control = cmsgbuf;
30,579 ✔
914
#if !defined(__APPLE__)
30,579 ✔
915
    /* CMSG_SPACE is not a constexpr on macOS */
916
    static_assert(CMSG_SPACE(sizeof(*pkt)) <= sizeof(*cmsgbuf), "Buffer is too small for in_pktinfo");
30,579 ✔
917
#else /* __APPLE__ */
918
    if (CMSG_SPACE(sizeof(*pkt)) > sizeof(*cmsgbuf)) {
919
      throw std::runtime_error("Buffer is too small for in_pktinfo");
920
    }
921
#endif /* __APPLE__ */
922
    msgh->msg_controllen = CMSG_SPACE(sizeof(*pkt));
30,579 ✔
923

924
    cmsg = CMSG_FIRSTHDR(msgh);
30,579 !
925
    cmsg->cmsg_level = IPPROTO_IP;
30,579 ✔
926
    cmsg->cmsg_type = IP_PKTINFO;
30,579 ✔
927
    cmsg->cmsg_len = CMSG_LEN(sizeof(*pkt));
30,579 ✔
928

929
    pkt = reinterpret_cast<struct in_pktinfo*>(CMSG_DATA(cmsg));
30,579 ✔
930
    // Include the padding to stop valgrind complaining about passing uninitialized data
931
    memset(pkt, 0, CMSG_SPACE(sizeof(*pkt)));
30,579 ✔
932
    pkt->ipi_spec_dst = source->sin4.sin_addr;
30,579 ✔
933
    pkt->ipi_ifindex = itfIndex;
30,579 ✔
934
#elif defined(IP_SENDSRCADDR)
935
    struct in_addr* in;
936

937
    msgh->msg_control = cmsgbuf;
938
#if !defined(__APPLE__)
939
    static_assert(CMSG_SPACE(sizeof(*in)) <= sizeof(*cmsgbuf), "Buffer is too small for in_addr");
940
#else /* __APPLE__ */
941
    if (CMSG_SPACE(sizeof(*in)) > sizeof(*cmsgbuf)) {
942
      throw std::runtime_error("Buffer is too small for in_addr");
943
    }
944
#endif /* __APPLE__ */
945
    msgh->msg_controllen = CMSG_SPACE(sizeof(*in));
946

947
    cmsg = CMSG_FIRSTHDR(msgh);
948
    cmsg->cmsg_level = IPPROTO_IP;
949
    cmsg->cmsg_type = IP_SENDSRCADDR;
950
    cmsg->cmsg_len = CMSG_LEN(sizeof(*in));
951

952
    // Include the padding to stop valgrind complaining about passing uninitialized data
953
    in = (struct in_addr*)CMSG_DATA(cmsg);
954
    memset(in, 0, CMSG_SPACE(sizeof(*in)));
955
    *in = source->sin4.sin_addr;
956
#endif
957
  }
30,579 ✔
958
}
30,580 ✔
959

960
unsigned int getFilenumLimit(bool hardOrSoft)
961
{
203 ✔
962
  struct rlimit rlim{};
203 ✔
963
  if (getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
203 !
964
    unixDie("Requesting number of available file descriptors");
×
965
  }
×
966
  return hardOrSoft ? rlim.rlim_max : rlim.rlim_cur;
203 !
967
}
203 ✔
968

969
void setFilenumLimit(unsigned int lim)
970
{
×
971
  struct rlimit rlim{};
×
972

973
  if (getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
×
974
    unixDie("Requesting number of available file descriptors");
×
975
  }
×
976
  rlim.rlim_cur = lim;
×
977
  if (setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
×
978
    unixDie("Setting number of available file descriptors");
×
979
  }
×
980
}
×
981

982
bool setSocketTimestamps(int fileDesc)
983
{
634 ✔
984
#ifdef SO_TIMESTAMP
634 ✔
985
  int one = 1;
634 ✔
986
  return setsockopt(fileDesc, SOL_SOCKET, SO_TIMESTAMP, &one, sizeof(one)) == 0;
634 ✔
987
#else
988
  return true; // we pretend this happened.
989
#endif
990
}
634 ✔
991

992
bool setTCPNoDelay(int sock)
993
{
8,972 ✔
994
  int flag = 1;
8,972 ✔
995
  return setsockopt(sock, /* socket affected */
8,972 ✔
996
                    IPPROTO_TCP, /* set option at TCP level */
8,972 ✔
997
                    TCP_NODELAY, /* name of option */
8,972 ✔
998
                    &flag,
8,972 ✔
999
                    sizeof(flag))
8,972 ✔
1000
    == 0; /* length of option value */
8,972 ✔
1001
}
8,972 ✔
1002

1003
bool setNonBlocking(int sock)
1004
{
168,062 ✔
1005
  int flags = fcntl(sock, F_GETFL, 0);
168,062 ✔
1006
  return flags >= 0 && fcntl(sock, F_SETFL, flags | O_NONBLOCK) >= 0;
168,063 ✔
1007
}
168,062 ✔
1008

1009
bool setBlocking(int sock)
1010
{
92,373 ✔
1011
  int flags = fcntl(sock, F_GETFL, 0);
92,373 ✔
1012
  return flags >= 0 && fcntl(sock, F_SETFL, flags & (~O_NONBLOCK)) >= 0;
92,373 !
1013
}
92,373 ✔
1014

1015
bool setReuseAddr(int sock)
1016
{
206 ✔
1017
  int tmp = 1;
206 ✔
1018
  if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &tmp, static_cast<unsigned>(sizeof tmp)) < 0) {
206 !
1019
    throw PDNSException(string("Setsockopt failed: ") + stringerror());
×
1020
  }
×
1021
  return true;
206 ✔
1022
}
206 ✔
1023

1024
void setDscp(int sock, unsigned short family, uint8_t dscp)
1025
{
3,461 ✔
1026
  int val = 0;
3,461 ✔
1027
  unsigned int len = 0;
3,461 ✔
1028

1029
  if (dscp == 0 || dscp > 63) {
3,461 !
1030
    // No DSCP marking
1031
    return;
3,461 ✔
1032
  }
3,461 ✔
1033

1034
  if (family == AF_INET) {
×
1035
    if (getsockopt(sock, IPPROTO_IP, IP_TOS, &val, &len) < 0) {
×
1036
      throw std::runtime_error(string("Set DSCP failed: ") + stringerror());
×
1037
    }
×
1038
    val = (dscp << 2) | (val & 0x3);
×
1039
    if (setsockopt(sock, IPPROTO_IP, IP_TOS, &val, sizeof(val)) < 0) {
×
1040
      throw std::runtime_error(string("Set DSCP failed: ") + stringerror());
×
1041
    }
×
1042
  }
×
1043
  else if (family == AF_INET6) {
×
1044
    if (getsockopt(sock, IPPROTO_IPV6, IPV6_TCLASS, &val, &len) < 0) {
×
1045
      throw std::runtime_error(string("Set DSCP failed: ") + stringerror());
×
1046
    }
×
1047
    val = (dscp << 2) | (val & 0x3);
×
1048
    if (setsockopt(sock, IPPROTO_IPV6, IPV6_TCLASS, &val, sizeof(val)) < 0) {
×
1049
      throw std::runtime_error(string("Set DSCP failed: ") + stringerror());
×
1050
    }
×
1051
  }
×
1052
}
×
1053

1054
bool isNonBlocking(int sock)
1055
{
115,807 ✔
1056
  int flags = fcntl(sock, F_GETFL, 0);
115,807 ✔
1057
  return (flags & O_NONBLOCK) != 0;
115,807 ✔
1058
}
115,807 ✔
1059

1060
bool setReceiveSocketErrors([[maybe_unused]] int sock, [[maybe_unused]] int family)
1061
{
10,115 ✔
1062
#ifdef __linux__
10,115 ✔
1063
  int tmp = 1;
10,115 ✔
1064
  int ret{};
10,115 ✔
1065
  if (family == AF_INET) {
10,116 ✔
1066
    ret = setsockopt(sock, IPPROTO_IP, IP_RECVERR, &tmp, sizeof(tmp));
10,098 ✔
1067
  }
10,098 ✔
1068
  else {
2,147,483,658 ✔
1069
    ret = setsockopt(sock, IPPROTO_IPV6, IPV6_RECVERR, &tmp, sizeof(tmp));
2,147,483,658 ✔
1070
  }
2,147,483,658 ✔
1071
  if (ret < 0) {
10,115 !
1072
    throw PDNSException(string("Setsockopt failed: ") + stringerror());
×
1073
  }
×
1074
#endif
10,115 ✔
1075
  return true;
10,115 ✔
1076
}
10,115 ✔
1077

1078
// Closes a socket.
1079
int closesocket(int socket)
1080
{
53,344 ✔
1081
  int ret = ::close(socket);
53,344 ✔
1082
  if (ret < 0 && errno == ECONNRESET) { // see ticket 192, odd BSD behaviour
53,344 !
1083
    return 0;
×
1084
  }
×
1085
  if (ret < 0) {
53,344 !
1086
    int err = errno;
×
1087
    throw PDNSException("Error closing socket: " + stringerror(err));
×
1088
  }
×
1089
  return ret;
53,344 ✔
1090
}
53,344 ✔
1091

1092
bool setCloseOnExec(int sock)
1093
{
49,027 ✔
1094
  int flags = fcntl(sock, F_GETFD, 0);
49,027 ✔
1095
  return flags >= 0 && fcntl(sock, F_SETFD, flags | FD_CLOEXEC) >= 0;
49,027 !
1096
}
49,027 ✔
1097

1098
#ifdef __linux__
1099
#include <linux/rtnetlink.h>
1100

1101
int getMACAddress(const ComboAddress& address, char* dest, size_t destLen)
1102
{
3 ✔
1103
  struct
3 ✔
1104
  {
3 ✔
1105
    struct nlmsghdr headermsg;
3 ✔
1106
    struct ndmsg neighbormsg;
3 ✔
1107
  } request{};
3 ✔
1108

1109
  std::array<char, 8192> buffer{};
3 ✔
1110

1111
  auto sock = FDWrapper(socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE));
3 ✔
1112
  if (sock.getHandle() == -1) {
3 !
1113
    return errno;
×
1114
  }
×
1115

1116
  memset(&request, 0, sizeof(request));
3 ✔
1117
  request.headermsg.nlmsg_len = NLMSG_LENGTH(sizeof(struct ndmsg));
3 ✔
1118
  request.headermsg.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
3 ✔
1119
  request.headermsg.nlmsg_type = RTM_GETNEIGH;
3 ✔
1120
  request.neighbormsg.ndm_family = address.sin4.sin_family;
3 ✔
1121

1122
  while (true) {
3 ✔
1123
    ssize_t sent = send(sock.getHandle(), &request, sizeof(request), 0);
3 ✔
1124
    if (sent == -1) {
3 !
1125
      if (errno == EINTR) {
×
1126
        continue;
×
1127
      }
×
1128
      return errno;
×
1129
    }
×
1130
    if (static_cast<size_t>(sent) != sizeof(request)) {
3 !
1131
      return EIO;
×
1132
    }
×
1133
    break;
3 ✔
1134
  }
3 ✔
1135

1136
  bool done = false;
3 ✔
1137
  bool foundIP = false;
3 ✔
1138
  bool foundMAC = false;
3 ✔
1139
  do {
3 ✔
1140
    ssize_t got = recv(sock.getHandle(), buffer.data(), buffer.size(), 0);
3 ✔
1141

1142
    if (got < 0) {
3 !
1143
      if (errno == EINTR) {
×
1144
        continue;
×
1145
      }
×
1146
      return errno;
×
1147
    }
×
1148

1149
    auto remaining = static_cast<size_t>(got);
3 ✔
1150
    for (auto* nlmsgheader = reinterpret_cast<struct nlmsghdr*>(buffer.data());
3 ✔
1151
         !done && NLMSG_OK(nlmsgheader, remaining);
9 !
1152
         nlmsgheader = reinterpret_cast<struct nlmsghdr*>(NLMSG_NEXT(nlmsgheader, remaining))) {
9 ✔
1153

1154
      if (nlmsgheader->nlmsg_type == NLMSG_DONE) {
9 ✔
1155
        done = true;
3 ✔
1156
        break;
3 ✔
1157
      }
3 ✔
1158

1159
      auto* ndmsg = reinterpret_cast<struct ndmsg*>(NLMSG_DATA(nlmsgheader));
6 ✔
1160
      auto* rtatp = reinterpret_cast<struct rtattr*>(reinterpret_cast<char*>(ndmsg) + NLMSG_ALIGN(sizeof(struct ndmsg)));
6 ✔
1161
      auto rtattrlen = nlmsgheader->nlmsg_len - NLMSG_LENGTH(sizeof(struct ndmsg));
6 ✔
1162

1163
      if (ndmsg->ndm_family != address.sin4.sin_family) {
6 !
1164
        continue;
×
1165
      }
×
1166

1167
      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) {
6 !
1168
        continue;
×
1169
      }
×
1170

1171
      for (; !done && RTA_OK(rtatp, rtattrlen); rtatp = RTA_NEXT(rtatp, rtattrlen)) {
30 !
1172
        if (rtatp->rta_type == NDA_DST) {
24 ✔
1173
          if (ndmsg->ndm_family == AF_INET) {
6 !
1174
            auto* inp = reinterpret_cast<struct in_addr*>(RTA_DATA(rtatp));
6 ✔
1175
            if (inp->s_addr == address.sin4.sin_addr.s_addr) {
6 !
1176
              foundIP = true;
×
1177
            }
×
1178
          }
6 ✔
1179
          else if (ndmsg->ndm_family == AF_INET6) {
×
1180
            auto* inp = reinterpret_cast<struct in6_addr*>(RTA_DATA(rtatp));
×
1181
            if (memcmp(&inp->s6_addr[0], &address.sin6.sin6_addr.s6_addr[0], sizeof(address.sin6.sin6_addr.s6_addr)) == 0) {
×
1182
              foundIP = true;
×
1183
            }
×
1184
          }
×
1185
        }
6 ✔
1186
        else if (rtatp->rta_type == NDA_LLADDR) {
18 ✔
1187
          if (foundIP) {
6 !
1188
            size_t addrLen = rtatp->rta_len - sizeof(struct rtattr);
×
1189
            if (addrLen > destLen) {
×
1190
              return ENOBUFS;
×
1191
            }
×
1192
            memcpy(dest, reinterpret_cast<const char*>(rtatp) + sizeof(struct rtattr), addrLen);
×
1193
            foundMAC = true;
×
1194
            done = true;
×
1195
            break;
×
1196
          }
×
1197
        }
6 ✔
1198
      }
24 ✔
1199
    }
6 ✔
1200
  } while (!done);
3 !
1201

1202
  return foundMAC ? 0 : ENOENT;
3 !
1203
}
3 ✔
1204
#else
1205
int getMACAddress(const ComboAddress& /* ca */, char* /* dest */, size_t /* len */)
1206
{
1207
  return ENOENT;
1208
}
1209
#endif /* __linux__ */
1210

1211
string getMACAddress(const ComboAddress& address)
1212
{
×
1213
  string ret;
×
1214
  std::array<char, 6> tmp{};
×
1215
  if (getMACAddress(address, tmp.data(), tmp.size()) == 0) {
×
1216
    ret.append(tmp.data(), tmp.size());
×
1217
  }
×
1218
  return ret;
×
1219
}
×
1220

1221
uint64_t udpErrorStats([[maybe_unused]] const std::string& str)
1222
{
2,185 ✔
1223
#ifdef __linux__
2,185 ✔
1224
  ifstream ifs("/proc/net/snmp");
2,185 ✔
1225
  if (!ifs) {
2,185 !
1226
    return 0;
×
1227
  }
×
1228

1229
  string line;
2,185 ✔
1230
  while (getline(ifs, line)) {
20,520 !
1231
    if (boost::starts_with(line, "Udp: ") && isdigit(line.at(5)) != 0) {
20,520 ✔
1232
      vector<string> parts;
2,185 ✔
1233
      stringtok(parts, line, " \n\t\r");
2,185 ✔
1234

1235
      if (parts.size() < 7) {
2,185 !
1236
        break;
×
1237
      }
×
1238

1239
      if (str == "udp-recvbuf-errors") {
2,185 ✔
1240
        return std::stoull(parts.at(5));
437 ✔
1241
      }
437 ✔
1242
      if (str == "udp-sndbuf-errors") {
1,748 ✔
1243
        return std::stoull(parts.at(6));
437 ✔
1244
      }
437 ✔
1245
      if (str == "udp-noport-errors") {
1,311 ✔
1246
        return std::stoull(parts.at(2));
437 ✔
1247
      }
437 ✔
1248
      if (str == "udp-in-errors") {
874 ✔
1249
        return std::stoull(parts.at(3));
437 ✔
1250
      }
437 ✔
1251
      if (parts.size() >= 8 && str == "udp-in-csum-errors") {
437 !
1252
        return std::stoull(parts.at(7));
437 ✔
1253
      }
437 ✔
UNCOV
1254
      return 0;
×
1255
    }
437 ✔
1256
  }
20,520 ✔
UNCOV
1257
#endif
×
UNCOV
1258
  return 0;
×
1259
}
2,185 ✔
1260

1261
uint64_t udp6ErrorStats([[maybe_unused]] const std::string& str)
1262
{
2,185 ✔
1263
#ifdef __linux__
2,185 ✔
1264
  const std::map<std::string, std::string> keys = {
2,185 ✔
1265
    {"udp6-in-errors", "Udp6InErrors"},
2,185 ✔
1266
    {"udp6-recvbuf-errors", "Udp6RcvbufErrors"},
2,185 ✔
1267
    {"udp6-sndbuf-errors", "Udp6SndbufErrors"},
2,185 ✔
1268
    {"udp6-noport-errors", "Udp6NoPorts"},
2,185 ✔
1269
    {"udp6-in-csum-errors", "Udp6InCsumErrors"}};
2,185 ✔
1270

1271
  auto key = keys.find(str);
2,185 ✔
1272
  if (key == keys.end()) {
2,185 !
1273
    return 0;
×
1274
  }
×
1275

1276
  ifstream ifs("/proc/net/snmp6");
2,185 ✔
1277
  if (!ifs) {
2,185 !
1278
    return 0;
×
1279
  }
×
1280

1281
  std::string line;
2,185 ✔
1282
  while (getline(ifs, line)) {
160,816 !
1283
    if (!boost::starts_with(line, key->second)) {
160,816 ✔
1284
      continue;
158,631 ✔
1285
    }
158,631 ✔
1286

1287
    std::vector<std::string> parts;
2,185 ✔
1288
    stringtok(parts, line, " \n\t\r");
2,185 ✔
1289

1290
    if (parts.size() != 2) {
2,185 !
1291
      return 0;
×
1292
    }
×
1293

1294
    return std::stoull(parts.at(1));
2,185 ✔
1295
  }
2,185 ✔
UNCOV
1296
#endif
×
UNCOV
1297
  return 0;
×
1298
}
2,185 ✔
1299

1300
uint64_t tcpErrorStats([[maybe_unused]] const std::string& label)
1301
{
272 ✔
1302
#ifdef __linux__
272 ✔
1303
  ifstream ifs("/proc/net/netstat");
272 ✔
1304
  if (!ifs) {
272 !
1305
    return 0U;
×
1306
  }
×
1307

1308
  string line;
272 ✔
1309
  std::vector<string> parts;
272 ✔
1310
  std::optional<size_t> position{std::nullopt};
272 ✔
1311
  while (getline(ifs, line)) {
544 !
1312
    if (line.size() <= 9 || !boost::starts_with(line, "TcpExt: ")) {
544 !
1313
      continue;
×
1314
    }
×
1315

1316
    if (!position.has_value() && isdigit(line.at(8)) == 0) {
544 !
1317
      // this is the line with the labels, let's try to find ours
1318
      parts.clear();
272 ✔
1319
      stringtok(parts, line, " \n\t\r");
272 ✔
1320
      size_t currentPosition = 0;
272 ✔
1321
      for (const auto& tentativeLabel : parts) {
6,528 !
1322
        if (tentativeLabel == label) {
6,528 ✔
1323
          position = currentPosition;
272 ✔
1324
          break;
272 ✔
1325
        }
272 ✔
1326
        ++currentPosition;
6,256 ✔
1327
      }
6,256 ✔
1328
      if (!position.has_value()) {
272 !
1329
        // label not found, bye
1330
        return 0U;
×
1331
      }
×
1332
      continue;
272 ✔
1333
    }
272 ✔
1334

1335
    if (position.has_value() && isdigit(line.at(8)) != 0) {
272 !
1336
      // this is the line with the values
1337
      parts.clear();
272 ✔
1338
      stringtok(parts, line, " \n\t\r");
272 ✔
1339
      if (parts.size() < *position) {
272 !
1340
        return 0U;
×
1341
      }
×
1342
      return std::stoull(parts.at(*position));
272 ✔
1343
    }
272 ✔
1344
  }
272 ✔
UNCOV
1345
#endif
×
UNCOV
1346
  return 0U;
×
1347
}
272 ✔
1348

1349
uint64_t getCPUIOWait(const std::string& /* str */)
1350
{
433 ✔
1351
#ifdef __linux__
433 ✔
1352
  ifstream ifs("/proc/stat");
433 ✔
1353
  if (!ifs) {
433 !
1354
    return 0;
×
1355
  }
×
1356

1357
  string line;
433 ✔
1358
  vector<string> parts;
433 ✔
1359
  while (getline(ifs, line)) {
433 !
1360
    if (boost::starts_with(line, "cpu ")) {
433 !
1361
      stringtok(parts, line, " \n\t\r");
433 ✔
1362

1363
      if (parts.size() < 6) {
433 !
1364
        break;
×
1365
      }
×
1366

1367
      return std::stoull(parts[5]);
433 ✔
1368
    }
433 ✔
1369
  }
433 ✔
UNCOV
1370
#endif
×
UNCOV
1371
  return 0;
×
1372
}
433 ✔
1373

1374
uint64_t getCPUSteal(const std::string& /* str */)
1375
{
433 ✔
1376
#ifdef __linux__
433 ✔
1377
  ifstream ifs("/proc/stat");
433 ✔
1378
  if (!ifs) {
433 !
1379
    return 0;
×
1380
  }
×
1381

1382
  string line;
433 ✔
1383
  vector<string> parts;
433 ✔
1384
  while (getline(ifs, line)) {
433 !
1385
    if (boost::starts_with(line, "cpu ")) {
433 !
1386
      stringtok(parts, line, " \n\t\r");
433 ✔
1387

1388
      if (parts.size() < 9) {
433 !
1389
        break;
×
1390
      }
×
1391

1392
      return std::stoull(parts[8]);
433 ✔
1393
    }
433 ✔
1394
  }
433 ✔
1395
#endif
×
1396
  return 0;
×
1397
}
433 ✔
1398

1399
bool getTSIGHashEnum(const DNSName& algoName, TSIGHashEnum& algoEnum)
1400
{
1,304 ✔
1401
  if (algoName == g_hmacmd5dnsname_long || algoName == g_hmacmd5dnsname) {
1,304 ✔
1402
    algoEnum = TSIG_MD5;
1,205 ✔
1403
  }
1,205 ✔
1404
  else if (algoName == g_hmacsha1dnsname) {
99 ✔
1405
    algoEnum = TSIG_SHA1;
76 ✔
1406
  }
76 ✔
1407
  else if (algoName == g_hmacsha224dnsname) {
23 !
1408
    algoEnum = TSIG_SHA224;
×
1409
  }
×
1410
  else if (algoName == g_hmacsha256dnsname) {
23 ✔
1411
    algoEnum = TSIG_SHA256;
4 ✔
1412
  }
4 ✔
1413
  else if (algoName == g_hmacsha384dnsname) {
19 !
1414
    algoEnum = TSIG_SHA384;
×
1415
  }
×
1416
  else if (algoName == g_hmacsha512dnsname) {
19 ✔
1417
    algoEnum = TSIG_SHA512;
11 ✔
1418
  }
11 ✔
1419
  else if (algoName == g_gsstsigdnsname) {
8 !
1420
    algoEnum = TSIG_GSS;
×
1421
  }
×
1422
  else {
8 ✔
1423
    return false;
8 ✔
1424
  }
8 ✔
1425
  return true;
1,296 ✔
1426
}
1,304 ✔
1427

1428
DNSName getTSIGAlgoName(TSIGHashEnum& algoEnum)
1429
{
135 ✔
1430
  switch (algoEnum) {
135 !
1431
  case TSIG_MD5:
135 !
1432
    return g_hmacmd5dnsname_long;
135 ✔
1433
  case TSIG_SHA1:
×
1434
    return g_hmacsha1dnsname;
×
1435
  case TSIG_SHA224:
×
1436
    return g_hmacsha224dnsname;
×
1437
  case TSIG_SHA256:
×
1438
    return g_hmacsha256dnsname;
×
1439
  case TSIG_SHA384:
×
1440
    return g_hmacsha384dnsname;
×
1441
  case TSIG_SHA512:
×
1442
    return g_hmacsha512dnsname;
×
1443
  case TSIG_GSS:
×
1444
    return g_gsstsigdnsname;
×
1445
  }
135 ✔
1446
  throw PDNSException("getTSIGAlgoName does not understand given algorithm, please fix!");
×
1447
}
135 ✔
1448

1449
uint64_t getOpenFileDescriptors(const std::string& /* unused */)
1450
{
450 ✔
1451
#ifdef __linux__
450 ✔
1452
  const auto* const dirName = "/proc/self/fd";
450 ✔
1453
  struct stat status; // NOLINT(cppcoreguidelines-pro-type-member-init)
450 ✔
1454
  auto ret = stat(dirName, &status);
450 ✔
1455
  if (ret != 0) {
450 !
1456
    return 0;
×
1457
  }
×
1458
  if (status.st_size != 0) { // Until linux 6.1, this would return 0
450 !
1459
    return status.st_size;
450 ✔
1460
  }
450 ✔
1461

1462
  // This can lead to performance issues with *many* open fds
UNCOV
1463
  uint64_t nbFileDescriptors = 0;
×
UNCOV
1464
  auto directoryError = pdns::visit_directory(dirName, [&nbFileDescriptors]([[maybe_unused]] ino_t inodeNumber, const std::string_view& name) {
×
1465
    uint32_t num{};
×
1466
    try {
×
1467
      pdns::checked_stoi_into(num, std::string(name));
×
1468
      if (std::to_string(num) == name) {
×
1469
        nbFileDescriptors++;
×
1470
      }
×
1471
    }
×
1472
    catch (...) {
×
1473
      // was not a number.
1474
      ;
×
1475
    }
×
1476
    return true;
×
1477
  });
×
UNCOV
1478
  if (directoryError) {
×
1479
    return 0U;
×
1480
  }
×
UNCOV
1481
  return nbFileDescriptors;
×
1482
#elif defined(__OpenBSD__)
1483
  // FreeBSD also has this in libopenbsd, but I don't know if that's available always
1484
  return getdtablecount();
1485
#else
1486
  return 0U;
1487
#endif
UNCOV
1488
}
×
1489

1490
uint64_t getRealMemoryUsage(const std::string& /* unused */)
1491
{
450 ✔
1492
#ifdef __linux__
450 ✔
1493
  ifstream ifs("/proc/self/statm");
450 ✔
1494
  if (!ifs) {
450 !
1495
    return 0;
×
1496
  }
×
1497
  uint64_t size{};
450 ✔
1498
  uint64_t resident{};
450 ✔
1499
  uint64_t shared{};
450 ✔
1500
  uint64_t text{};
450 ✔
1501
  uint64_t lib{};
450 ✔
1502
  uint64_t data{};
450 ✔
1503
  ifs >> size >> resident >> shared >> text >> lib >> data;
450 ✔
1504

1505
  // We used to use "data" here, but it proves unreliable and even is marked "broken"
1506
  // in https://www.kernel.org/doc/html/latest/filesystems/proc.html
1507
  return resident * getpagesize();
450 ✔
1508
#else
1509
  struct rusage rusage{};
1510
  if (getrusage(RUSAGE_SELF, &rusage) != 0) {
1511
    return 0;
1512
  }
1513
  return rusage.ru_maxrss * 1024;
1514
#endif
1515
}
450 ✔
1516

1517
uint64_t getSpecialMemoryUsage(const std::string& /* unused */)
1518
{
17 ✔
1519
#ifdef __linux__
17 ✔
1520
  ifstream ifs("/proc/self/smaps");
17 ✔
1521
  if (!ifs) {
17 !
1522
    return 0;
×
1523
  }
×
1524
  string line;
17 ✔
1525
  uint64_t bytes = 0;
17 ✔
1526
  string header("Private_Dirty:");
17 ✔
1527
  while (getline(ifs, line)) {
312,507 ✔
1528
    if (boost::starts_with(line, header)) {
312,490 ✔
1529
      bytes += std::stoull(line.substr(header.length() + 1)) * 1024;
12,518 ✔
1530
    }
12,518 ✔
1531
  }
312,490 ✔
1532
  return bytes;
17 ✔
1533
#else
1534
  return 0;
1535
#endif
1536
}
17 ✔
1537

1538
uint64_t getCPUTimeUser(const std::string& /* unused */)
1539
{
285 ✔
1540
  struct rusage rusagew{};
285 ✔
1541
  getrusage(RUSAGE_SELF, &rusagew);
285 ✔
1542
  return (rusagew.ru_utime.tv_sec * 1000ULL) + (rusagew.ru_utime.tv_usec / 1000);
285 ✔
1543
}
285 ✔
1544

1545
uint64_t getCPUTimeSystem(const std::string& /* unused */)
1546
{
285 ✔
1547
  struct rusage rusage{};
285 ✔
1548
  getrusage(RUSAGE_SELF, &rusage);
285 ✔
1549
  return (rusage.ru_stime.tv_sec * 1000ULL) + (rusage.ru_stime.tv_usec / 1000);
285 ✔
1550
}
285 ✔
1551

1552
double DiffTime(const struct timespec& first, const struct timespec& second)
1553
{
126 ✔
1554
  auto seconds = second.tv_sec - first.tv_sec;
126 ✔
1555
  auto nseconds = second.tv_nsec - first.tv_nsec;
126 ✔
1556

1557
  if (nseconds < 0) {
126 ✔
1558
    seconds -= 1;
110 ✔
1559
    nseconds += 1000000000;
110 ✔
1560
  }
110 ✔
1561
  return static_cast<double>(seconds) + (static_cast<double>(nseconds) / 1000000000.0);
126 ✔
1562
}
126 ✔
1563

1564
double DiffTime(const struct timeval& first, const struct timeval& second)
1565
{
×
1566
  auto seconds = second.tv_sec - first.tv_sec;
×
1567
  auto useconds = second.tv_usec - first.tv_usec;
×
1568

1569
  if (useconds < 0) {
×
1570
    seconds -= 1;
×
1571
    useconds += 1000000;
×
1572
  }
×
1573
  return static_cast<double>(seconds) + (static_cast<double>(useconds) / 1000000.0);
×
1574
}
×
1575

1576
uid_t strToUID(const string& str)
1577
{
×
1578
  uid_t result = 0;
×
1579
  const char* cstr = str.c_str();
×
1580
  auto bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
×
1581
  if (bufsize == -1) {
×
1582
    throw runtime_error("cannot retrieve buffer size for passwd entry");
×
1583
  }
×
1584
  std::string buffer;
×
1585
  buffer.resize(bufsize);
×
1586
  struct passwd pwd{};
×
1587
  struct passwd* pwdPtr = nullptr;
×
1588
  if (getpwnam_r(cstr, &pwd, buffer.data(), buffer.size(), &pwdPtr) != 0) {
×
1589
    throw runtime_error("cannot retrieve uid");
×
1590
  }
×
1591

1592
  if (pwdPtr == nullptr) {
×
1593
    long long val{};
×
1594

1595
    try {
×
1596
      val = stoll(str);
×
1597
    }
×
1598
    catch (std::exception& e) {
×
1599
      throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr).str());
×
1600
    }
×
1601

1602
    if (val < std::numeric_limits<uid_t>::min() || val > std::numeric_limits<uid_t>::max()) {
×
1603
      throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr).str());
×
1604
    }
×
1605

1606
    result = static_cast<uid_t>(val);
×
1607
  }
×
1608
  else {
×
1609
    result = pwdPtr->pw_uid;
×
1610
  }
×
1611

1612
  return result;
×
1613
}
×
1614

1615
gid_t strToGID(const string& str)
1616
{
×
1617
  gid_t result = 0;
×
1618
  const char* cstr = str.c_str();
×
1619
  auto bufsize = sysconf(_SC_GETGR_R_SIZE_MAX);
×
1620
  if (bufsize == -1) {
×
1621
    throw runtime_error("cannot retrieve buffer size for group entry");
×
1622
  }
×
1623
  std::string buffer;
×
1624
  buffer.resize(bufsize);
×
1625
  struct group grp{};
×
1626
  struct group* grpPtr = nullptr;
×
1627
  if (getgrnam_r(cstr, &grp, buffer.data(), buffer.size(), &grpPtr) != 0) {
×
1628
    throw runtime_error("cannot retrieve gid");
×
1629
  }
×
1630

1631
  if (grpPtr == nullptr) {
×
1632
    long long val{};
×
1633

1634
    try {
×
1635
      val = stoll(str);
×
1636
    }
×
1637
    catch (std::exception& e) {
×
1638
      throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr).str());
×
1639
    }
×
1640

1641
    if (val < std::numeric_limits<gid_t>::min() || val > std::numeric_limits<gid_t>::max()) {
×
1642
      throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr).str());
×
1643
    }
×
1644

1645
    result = static_cast<gid_t>(val);
×
1646
  }
×
1647
  else {
×
1648
    result = grpPtr->gr_gid;
×
1649
  }
×
1650

1651
  return result;
×
1652
}
×
1653

1654
bool isSettingThreadCPUAffinitySupported()
1655
{
×
1656
#ifdef HAVE_PTHREAD_SETAFFINITY_NP
1657
  return true;
1658
#else
1659
  return false;
1660
#endif
1661
}
×
1662

1663
int mapThreadToCPUList([[maybe_unused]] pthread_t tid, [[maybe_unused]] const std::set<int>& cpus)
1664
{
×
1665
#ifdef HAVE_PTHREAD_SETAFFINITY_NP
1666
#ifdef __NetBSD__
1667
  cpuset_t* cpuset;
1668
  cpuset = cpuset_create();
1669
  for (const auto cpuID : cpus) {
1670
    cpuset_set(cpuID, cpuset);
1671
  }
1672

1673
  return pthread_setaffinity_np(tid,
1674
                                cpuset_size(cpuset),
1675
                                cpuset);
1676
#else
1677
#ifdef __FreeBSD__
1678
#define cpu_set_t cpuset_t
1679
#endif
1680
  cpu_set_t cpuset;
1681
  CPU_ZERO(&cpuset);
1682
  for (const auto cpuID : cpus) {
×
1683
    CPU_SET(cpuID, &cpuset);
×
1684
  }
1685

1686
  return pthread_setaffinity_np(tid,
1687
                                sizeof(cpuset),
1688
                                &cpuset);
1689
#endif
1690
#else
1691
  return ENOSYS;
1692
#endif /* HAVE_PTHREAD_SETAFFINITY_NP */
1693
}
×
1694

1695
std::vector<ComboAddress> getResolvers(const std::string& resolvConfPath)
1696
{
90 ✔
1697
  // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive in some boost versions
1698
  std::vector<ComboAddress> results;
90 ✔
1699

1700
  std::ifstream ifs(resolvConfPath);
90 ✔
1701
  if (!ifs) {
90 !
1702
    return results;
×
1703
  }
×
1704

1705
  string line;
90 ✔
1706
  while (std::getline(ifs, line)) {
1,166 ✔
1707
    boost::trim_right_if(line, boost::is_any_of(" \r\n\x1a"));
1,076 ✔
1708
    boost::trim_left(line); // leading spaces, let's be nice
1,076 ✔
1709

1710
    string::size_type tpos = line.find_first_of(";#");
1,076 ✔
1711
    if (tpos != string::npos) {
1,076 ✔
1712
      line.resize(tpos);
629 ✔
1713
    }
629 ✔
1714

1715
    if (boost::starts_with(line, "nameserver ") || boost::starts_with(line, "nameserver\t")) {
1,076 ✔
1716
      vector<string> parts;
91 ✔
1717
      stringtok(parts, line, " \t,"); // be REALLY nice
91 ✔
1718
      for (auto iter = parts.begin() + 1; iter != parts.end(); ++iter) {
182 ✔
1719
        try {
91 ✔
1720
          results.emplace_back(*iter, 53);
91 ✔
1721
        }
91 ✔
1722
        catch (...) {
91 ✔
1723
          ; // ignored
×
1724
        }
×
1725
      }
91 ✔
1726
    }
91 ✔
1727
  }
1,076 ✔
1728

1729
  return results;
90 ✔
1730
  // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
1731
}
90 ✔
1732

1733
size_t getPipeBufferSize([[maybe_unused]] int fileDesc)
1734
{
14,026 ✔
1735
#ifdef F_GETPIPE_SZ
14,026 ✔
1736
  int res = fcntl(fileDesc, F_GETPIPE_SZ);
14,026 ✔
1737
  if (res == -1) {
14,026 !
1738
    return 0;
×
1739
  }
×
1740
  return res;
14,026 ✔
1741
#else
1742
  errno = ENOSYS;
1743
  return 0;
1744
#endif /* F_GETPIPE_SZ */
1745
}
14,026 ✔
1746

1747
bool setPipeBufferSize([[maybe_unused]] int fileDesc, [[maybe_unused]] size_t size)
1748
{
14,026 ✔
1749
#ifdef F_SETPIPE_SZ
14,026 ✔
1750
  if (size > static_cast<size_t>(std::numeric_limits<int>::max())) {
14,026 !
1751
    errno = EINVAL;
×
1752
    return false;
×
1753
  }
×
1754
  int newSize = static_cast<int>(size);
14,026 ✔
1755
  int res = fcntl(fileDesc, F_SETPIPE_SZ, newSize);
14,026 ✔
1756
  return res != -1;
14,026 ✔
1757
#else
1758
  errno = ENOSYS;
1759
  return false;
1760
#endif /* F_SETPIPE_SZ */
1761
}
14,026 ✔
1762

1763
DNSName reverseNameFromIP(const ComboAddress& address)
1764
{
9 ✔
1765
  if (address.isIPv4()) {
9 ✔
1766
    std::string result("in-addr.arpa.");
3 ✔
1767
    const auto* ptr = reinterpret_cast<const uint8_t*>(&address.sin4.sin_addr.s_addr);
3 ✔
1768
    for (size_t idx = 0; idx < sizeof(address.sin4.sin_addr.s_addr); idx++) {
15 ✔
1769
      auto tmp{result};
12 ✔
1770
      result = std::to_string(ptr[idx]);
12 ✔
1771
      result += ".";
12 ✔
1772
      result += tmp;
12 ✔
1773
    }
12 ✔
1774
    return DNSName(result);
3 ✔
1775
  }
3 ✔
1776
  if (address.isIPv6()) {
6 !
1777
    std::string result("ip6.arpa.");
6 ✔
1778
    const auto* ptr = &address.sin6.sin6_addr.s6_addr[0];
6 ✔
1779
    for (size_t idx = 0; idx < sizeof(address.sin6.sin6_addr.s6_addr); idx++) {
102 ✔
1780
      std::stringstream stream;
96 ✔
1781
      stream << std::hex << (ptr[idx] & 0x0F);
96 ✔
1782
      stream << '.';
96 ✔
1783
      stream << std::hex << (((ptr[idx]) >> 4) & 0x0F);
96 ✔
1784
      stream << '.';
96 ✔
1785
      auto tmp{result};
96 ✔
1786
      result = stream.str();
96 ✔
1787
      result += tmp;
96 ✔
1788
    }
96 ✔
1789
    return DNSName(result);
6 ✔
1790
  }
6 ✔
1791

1792
  throw std::runtime_error("Calling reverseNameFromIP() for an address which is neither an IPv4 nor an IPv6");
×
1793
}
6 ✔
1794

1795
std::string makeLuaString(const std::string& input)
1796
{
×
1797
  ostringstream str;
×
1798

1799
  str << '"';
×
1800

1801
  std::array<char, 5> item{};
×
1802
  for (unsigned char character : input) {
×
1803
    if ((islower(character) != 0) || (isupper(character) != 0)) {
×
1804
      item[0] = static_cast<char>(character);
×
1805
      item[1] = 0;
×
1806
    }
×
1807
    else {
×
1808
      snprintf(item.data(), item.size(), "\\%03d", character);
×
1809
    }
×
1810
    str << item.data();
×
1811
  }
×
1812

1813
  str << '"';
×
1814

1815
  return str.str();
×
1816
}
×
1817

1818
size_t parseSVCBValueList(const std::string& str, vector<std::string>& val)
1819
{
754 ✔
1820
  std::string parsed;
754 ✔
1821
  auto ret = parseRFC1035CharString(str, parsed);
754 ✔
1822
  parseSVCBValueListFromParsedRFC1035CharString(parsed, val);
754 ✔
1823
  return ret;
754 ✔
1824
};
754 ✔
1825

1826
#ifdef HAVE_CRYPTO_MEMCMP
1827
#include <openssl/crypto.h>
1828
#else /* HAVE_CRYPTO_MEMCMP */
1829
#ifdef HAVE_SODIUM_MEMCMP
1830
#include <sodium.h>
1831
#endif /* HAVE_SODIUM_MEMCMP */
1832
#endif /* HAVE_CRYPTO_MEMCMP */
1833

1834
bool constantTimeStringEquals(const std::string& lhs, const std::string& rhs)
1835
{
2,691 ✔
1836
  if (lhs.size() != rhs.size()) {
2,691 ✔
1837
    return false;
5 ✔
1838
  }
5 ✔
1839
  const size_t size = lhs.size();
2,686 ✔
1840
#ifdef HAVE_CRYPTO_MEMCMP
2,686 ✔
1841
  return CRYPTO_memcmp(lhs.c_str(), rhs.c_str(), size) == 0;
2,686 ✔
1842
#else /* HAVE_CRYPTO_MEMCMP */
1843
#ifdef HAVE_SODIUM_MEMCMP
1844
  return sodium_memcmp(lhs.c_str(), rhs.c_str(), size) == 0;
1845
#else /* HAVE_SODIUM_MEMCMP */
1846
  const volatile unsigned char* _a = (const volatile unsigned char*)lhs.c_str();
1847
  const volatile unsigned char* _b = (const volatile unsigned char*)rhs.c_str();
1848
  unsigned char res = 0;
1849

1850
  for (size_t idx = 0; idx < size; idx++) {
1851
    res |= _a[idx] ^ _b[idx];
1852
  }
1853

1854
  return res == 0;
1855
#endif /* !HAVE_SODIUM_MEMCMP */
1856
#endif /* !HAVE_CRYPTO_MEMCMP */
1857
}
2,691 ✔
1858

1859
namespace pdns
1860
{
1861
struct CloseDirDeleter
1862
{
1863
  void operator()(DIR* dir) const noexcept
1864
  {
241 ✔
1865
    closedir(dir);
241 ✔
1866
  }
241 ✔
1867
};
1868

1869
std::optional<std::string> visit_directory(const std::string& directory, const std::function<bool(ino_t inodeNumber, const std::string_view& name)>& visitor)
1870
{
355 ✔
1871
  auto dirHandle = std::unique_ptr<DIR, CloseDirDeleter>(opendir(directory.c_str()));
355 ✔
1872
  if (!dirHandle) {
355 ✔
1873
    auto err = errno;
114 ✔
1874
    return std::string("Error opening directory '" + directory + "': " + stringerror(err));
114 ✔
1875
  }
114 ✔
1876

1877
  bool keepGoing = true;
241 ✔
1878
  struct dirent* ent = nullptr;
241 ✔
1879
  // NOLINTNEXTLINE(concurrency-mt-unsafe): readdir is thread-safe nowadays and readdir_r is deprecated
1880
  while (keepGoing && (ent = readdir(dirHandle.get())) != nullptr) {
9,370 !
1881
    // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay: dirent API
1882
    auto name = std::string_view(ent->d_name, strlen(ent->d_name));
9,129 ✔
1883
    keepGoing = visitor(ent->d_ino, name);
9,129 ✔
1884
  }
9,129 ✔
1885

1886
  return std::nullopt;
241 ✔
1887
}
355 ✔
1888

1889
#ifndef DNSDIST
1890
std::vector<std::string> list_directory(const std::string& directory, const std::string& suffix, Logr::log_t d_log)
1891
{
230 ✔
1892
  std::vector<std::string> results;
230 ✔
1893

1894
  auto directoryError = pdns::visit_directory(directory,
230 ✔
1895
                                              [&directory, &suffix, &results, d_log]([[maybe_unused]] ino_t inodeNumber, const std::string_view& name) {
9,074 ✔
1896
                                                if (boost::starts_with(name, ".")) {
9,074 ✔
1897
                                                  return true; // skip any dots
460 ✔
1898
                                                }
460 ✔
1899
                                                if (boost::ends_with(name, suffix)) {
8,614 ✔
1900
                                                  // build name
1901
                                                  string fullName = directory + "/" + std::string(name);
1,803 ✔
1902
                                                  // ensure it's a readable file
1903
                                                  struct stat statInfo{};
1,803 ✔
1904
                                                  if (stat(fullName.c_str(), &statInfo) != 0) {
1,803 !
1905
                                                    int err = errno;
1906
                                                    string msg = "Unable to stat file '" + fullName + "': " + stringerror(err);
1907
                                                    SLOG(g_log << Logger::Error << msg << std::endl,
×
1908
                                                         d_log->error(Logr::Error, err, "Unable to stat file", "name", Logging::Loggable(fullName)));
1909
                                                    throw PDNSException(std::move(msg));
1910
                                                  }
1911
                                                  if (!S_ISREG(statInfo.st_mode)) {
1,803 !
1912
                                                    string msg = "File '" + fullName + "' is not a regular file";
1913
                                                    SLOG(g_log << Logger::Error << msg << std::endl,
×
1914
                                                         d_log->info(Logr::Error, "File is not a regular file", "name", Logging::Loggable(fullName)));
1915
                                                    throw PDNSException(std::move(msg));
1916
                                                  }
1917
                                                  results.emplace_back(fullName);
1,803 ✔
1918
                                                }
1,803 ✔
1919
                                                return true;
8,614 ✔
1920
                                              });
8,614 ✔
1921

1922
  if (directoryError) {
230 !
1923
    int err = errno;
1924
    string msg = directory + " is not accessible: " + stringerror(err);
1925
    SLOG(g_log << Logger::Error << msg << std::endl,
×
1926
         d_log->error(Logr::Error, err, "Directory is not accessible", "name", Logging::Loggable(directory)));
1927
    throw PDNSException(std::move(msg));
1928
  }
1929

1930
  return results;
230 ✔
1931
}
230 ✔
1932
#endif
1933

1934
UniqueFilePtr openFileForWriting(const std::string& filePath, mode_t permissions, bool mustNotExist, bool appendIfExists)
1935
{
5 ✔
1936
  int flags = O_WRONLY | O_CREAT;
5 ✔
1937
  if (mustNotExist) {
5 ✔
1938
    flags |= O_EXCL;
1 ✔
1939
  }
1 ✔
1940
  else if (appendIfExists) {
4 !
1941
    flags |= O_APPEND;
4 ✔
1942
  }
4 ✔
1943
  int fileDesc = open(filePath.c_str(), flags, permissions);
5 ✔
1944
  if (fileDesc == -1) {
5 !
1945
    return {};
×
1946
  }
×
1947
  auto filePtr = pdns::UniqueFilePtr(fdopen(fileDesc, appendIfExists ? "a" : "w"));
5 ✔
1948
  if (!filePtr) {
5 !
1949
    auto error = errno;
×
1950
    close(fileDesc);
×
1951
    errno = error;
×
1952
    return {};
×
1953
  }
×
1954
  return filePtr;
5 ✔
1955
}
5 ✔
1956

1957
}
1958

1959
const char* timestamp(time_t arg, timebuf_t& buf)
1960
{
161 ✔
1961
  const std::string s_timestampFormat = "%Y-%m-%dT%T";
161 ✔
1962
  struct tm tmval{};
161 ✔
1963
  size_t len = strftime(buf.data(), buf.size(), s_timestampFormat.c_str(), localtime_r(&arg, &tmval));
161 ✔
1964
  if (len == 0) {
161 !
1965
    int ret = snprintf(buf.data(), buf.size(), "%lld", static_cast<long long>(arg));
×
1966
    if (ret < 0 || static_cast<size_t>(ret) >= buf.size()) {
×
1967
      buf[0] = '\0';
×
1968
    }
×
1969
  }
×
1970
  return buf.data();
161 ✔
1971
}
161 ✔
1972
// NOLINTEND(cppcoreguidelines-pro-bounds-pointer-arithmetic,cppcoreguidelines-pro-type-reinterpret-cast)
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc