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

PowerDNS / pdns / 17765900968

16 Sep 2025 12:33PM UTC coverage: 65.987% (-0.04%) from 66.029%
17765900968

Pull #16108

github

web-flow
Merge 4059c5fe8 into 2e297650d
Pull Request #16108: dnsdist: implement simple packet shuffle in cache

42424 of 93030 branches covered (45.6%)

Branch coverage included in aggregate %.

9 of 135 new or added lines in 6 files covered. (6.67%)

34 existing lines in 8 files now uncovered.

128910 of 166619 relevant lines covered (77.37%)

5500581.66 hits per line

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

61.76
/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
#ifdef HAVE_CONFIG_H
24
#include "config.h"
25
#endif
26

27
#include <sys/param.h>
28
#include <sys/socket.h>
29
#include <fcntl.h>
30
#include <netdb.h>
31
#include <sys/time.h>
32
#include <ctime>
33
#include <sys/resource.h>
34
#include <netinet/in.h>
35
#include <sys/un.h>
36
#include <unistd.h>
37
#include <fstream>
38
#include "misc.hh"
39
#include <vector>
40
#include <string>
41
#include <sstream>
42
#include <cerrno>
43
#include <cstring>
44
#include <iostream>
45
#include <sys/types.h>
46
#include <dirent.h>
47
#include <algorithm>
48
#include <poll.h>
49
#include <iomanip>
50
#include <netinet/tcp.h>
51
#include <optional>
52
#include <cstdlib>
53
#include <cstdio>
54
#include "pdnsexception.hh"
55
#include <boost/algorithm/string.hpp>
56
#include <boost/format.hpp>
57
#include "iputils.hh"
58
#include "dnsparser.hh"
59
#include "dns_random.hh"
60
#include <pwd.h>
61
#include <grp.h>
62
#include <climits>
63
#include <unordered_map>
64
#ifdef __FreeBSD__
65
#  include <pthread_np.h>
66
#endif
67
#ifdef __NetBSD__
68
#  include <pthread.h>
69
#  include <sched.h>
70
#endif
71

72
#if defined(HAVE_LIBCRYPTO)
73
#include <openssl/err.h>
74
#endif // HAVE_LIBCRYPTO
75

76
size_t writen2(int fileDesc, const void *buf, size_t count)
77
{
1,412,805✔
78
  const char *ptr = static_cast<const char*>(buf);
1,412,805✔
79
  const char *eptr = ptr + count;
1,412,805✔
80

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

93
    ptr += res;
1,412,812✔
94
  }
1,412,812✔
95

96
  return count;
1,412,805✔
97
}
1,412,805✔
98

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

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

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

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

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

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

174
  return len;
1,873✔
175
}
1,878✔
176

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

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

207
  return len;
1,022✔
208
}
1,022✔
209

210
auto pdns::getMessageFromErrno(const int errnum) -> std::string
211
{
1,586✔
212
  const size_t errLen = 2048;
1,586✔
213
  std::string errMsgData{};
1,586✔
214
  errMsgData.resize(errLen);
1,586✔
215

216
  const char* errMsg = nullptr;
1,586✔
217
#ifdef STRERROR_R_CHAR_P
1,586✔
218
  errMsg = strerror_r(errnum, errMsgData.data(), errMsgData.length());
1,586✔
219
#else
220
  // This can fail, and when it does, it sets errno. We ignore that and
221
  // set our own error message instead.
222
  int res = strerror_r(errnum, errMsgData.data(), errMsgData.length());
223
  errMsg = errMsgData.c_str();
224
  if (res != 0) {
225
    errMsg = "Unknown (the exact error could not be retrieved)";
226
  }
227
#endif
228

229
  // We make a copy here because `strerror_r()` might return a static
230
  // immutable buffer for an error message. The copy shouldn't be
231
  // critical though, we're on the bailout/error-handling path anyways.
232
  std::string message{errMsg};
1,586✔
233
  return message;
1,586✔
234
}
1,586✔
235

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

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

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

258
    if (filename != nullptr) {
×
259
      fullErrorMessage += std::string(" - ") + filename;
×
260
    }
×
261
    if (lineNumber != 0) {
×
262
      fullErrorMessage += std::string(":") + std::to_string(lineNumber);
×
263
    }
×
264
    if (functionName != nullptr) {
×
265
      fullErrorMessage += std::string(" - ") + functionName;
×
266
    }
×
267
  }
×
268
#else
269
  while ((errorCode = ERR_get_error()) != 0) {
270
    fullErrorMessage += std::string(": ") + std::to_string(errorCode);
271

272
    const auto* lib = ERR_lib_error_string(errorCode);
273
    if (lib != nullptr) {
274
      fullErrorMessage += std::string(":") + lib;
275
    }
276

277
    const auto* func = ERR_func_error_string(errorCode);
278
    if (func != nullptr) {
279
      fullErrorMessage += std::string(":") + func;
280
    }
281

282
    const auto* reason = ERR_reason_error_string(errorCode);
283
    if (reason != nullptr) {
284
      fullErrorMessage += std::string("::") + reason;
285
    }
286
  }
287
#endif
288
  return std::runtime_error{fullErrorMessage};
×
289
}
×
290

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

297
string nowTime()
298
{
2,811✔
299
  time_t now = time(nullptr);
2,811✔
300
  struct tm theTime{};
2,811✔
301
  localtime_r(&now, &theTime);
2,811✔
302
  std::array<char, 30> buffer{};
2,811✔
303
  // YYYY-mm-dd HH:MM:SS TZOFF
304
  size_t ret = strftime(buffer.data(), buffer.size(), "%F %T %z", &theTime);
2,811✔
305
  if (ret == 0) {
2,811!
306
    buffer[0] = '\0';
×
307
  }
×
308
  return {buffer.data()};
2,811✔
309
}
2,811✔
310

311
// returns -1 in case if error, 0 if no data is available, 1 if there is. In the first two cases, errno is set
312
int waitForData(int fileDesc, int seconds, int mseconds)
313
{
2,279,421✔
314
  return waitForRWData(fileDesc, true, seconds, mseconds);
2,279,421✔
315
}
2,279,421✔
316

317
int waitForData(int fileDesc, struct timeval timeout)
318
{
15,890✔
319
  return waitForRWData(fileDesc, true, timeout);
15,890✔
320
}
15,890✔
321

322
int waitForRWData(int fileDesc, bool waitForRead, int seconds, int mseconds, bool* error, bool* disconnected)
323
{
2,300,747✔
324
  struct pollfd pfd{};
2,300,747✔
325
  memset(&pfd, 0, sizeof(pfd));
2,300,747✔
326
  pfd.fd = fileDesc;
2,300,747✔
327

328
  if (waitForRead) {
2,300,747✔
329
    pfd.events = POLLIN;
2,297,677✔
330
  }
2,297,677✔
331
  else {
3,070✔
332
    pfd.events = POLLOUT;
3,070✔
333
  }
3,070✔
334

335
  int ret = poll(&pfd, 1, seconds * 1000 + mseconds);
2,300,747✔
336
  if (ret > 0) {
2,300,747✔
337
    if ((error != nullptr) && (pfd.revents & POLLERR) != 0) {
2,085,287✔
338
      *error = true;
33✔
339
    }
33✔
340
    if ((disconnected != nullptr) && (pfd.revents & POLLHUP) != 0) {
2,085,287✔
341
      *disconnected = true;
33✔
342
    }
33✔
343
  }
2,085,287✔
344

345
  return ret;
2,300,747✔
346
}
2,300,747✔
347

348
int waitForRWData(int fileDesc, bool waitForRead, struct timeval timeout, bool* error, bool* disconnected)
349
{
17,096✔
350
  return waitForRWData(fileDesc, waitForRead, static_cast<int>(timeout.tv_sec), static_cast<int>(timeout.tv_usec / 1000), error, disconnected);
17,096✔
351
}
17,096✔
352

353
// returns -1 in case of error, 0 if no data is available, 1 if there is. In the first two cases, errno is set
354
int waitForMultiData(const set<int>& fds, const int seconds, const int mseconds, int* fdOut) {
2,263✔
355
  set<int> realFDs;
2,263✔
356
  for (const auto& fd : fds) {
4,526✔
357
    if (fd >= 0 && realFDs.count(fd) == 0) {
4,526!
358
      realFDs.insert(fd);
4,502✔
359
    }
4,502✔
360
  }
4,526✔
361

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

371
  int ret;
2,263✔
372
  if(seconds >= 0)
2,263!
373
    ret = poll(pfds.data(), realFDs.size(), seconds * 1000 + mseconds);
2,263✔
374
  else
×
375
    ret = poll(pfds.data(), realFDs.size(), -1);
×
376
  if(ret <= 0)
2,263✔
377
    return ret;
2,257✔
378

379
  set<int> pollinFDs;
6✔
380
  for (const auto& pfd : pfds) {
6✔
381
    if (pfd.revents & POLLIN) {
6!
382
      pollinFDs.insert(pfd.fd);
6✔
383
    }
6✔
384
  }
6✔
385
  set<int>::const_iterator it(pollinFDs.begin());
6✔
386
  advance(it, dns_random(pollinFDs.size()));
6✔
387
  *fdOut = *it;
6✔
388
  return 1;
6✔
389
}
2,263✔
390

391
string humanDuration(time_t passed)
392
{
4✔
393
  ostringstream ret;
4✔
394
  if(passed<60)
4!
395
    ret<<passed<<" seconds";
4✔
396
  else if(passed<3600)
×
397
    ret<<std::setprecision(2)<<passed/60.0<<" minutes";
×
398
  else if(passed<86400)
×
399
    ret<<std::setprecision(3)<<passed/3600.0<<" hours";
×
400
  else if(passed<(86400*30.41))
×
401
    ret<<std::setprecision(3)<<passed/86400.0<<" days";
×
402
  else
×
403
    ret<<std::setprecision(3)<<passed/(86400*30.41)<<" months";
×
404

405
  return ret.str();
4✔
406
}
4✔
407

408
string unquotify(const string &item)
409
{
11✔
410
  if(item.size()<2)
11✔
411
    return item;
2✔
412

413
  string::size_type bpos=0, epos=item.size();
9✔
414

415
  if(item[0]=='"')
9!
416
    bpos=1;
9✔
417

418
  if(item[epos-1]=='"')
9!
419
    epos-=1;
9✔
420

421
  return item.substr(bpos,epos-bpos);
9✔
422
}
11✔
423

424
void stripLine(string &line)
425
{
×
426
  string::size_type pos=line.find_first_of("\r\n");
×
427
  if(pos!=string::npos) {
×
428
    line.resize(pos);
×
429
  }
×
430
}
×
431

432
string urlEncode(const string &text)
433
{
×
434
  string ret;
×
435
  for(char i : text)
×
436
    if(i==' ')ret.append("%20");
×
437
    else ret.append(1,i);
×
438
  return ret;
×
439
}
×
440

441
static size_t getMaxHostNameSize()
442
{
352✔
443
#if defined(HOST_NAME_MAX)
352✔
444
  return HOST_NAME_MAX;
352✔
445
#endif
×
446

447
#if defined(_SC_HOST_NAME_MAX)
×
448
  auto tmp = sysconf(_SC_HOST_NAME_MAX);
×
449
  if (tmp != -1) {
×
450
    return tmp;
×
451
  }
×
452
#endif
×
453

454
  const size_t maxHostNameSize = 255;
×
455
  return maxHostNameSize;
×
456
}
×
457

458
std::optional<string> getHostname()
459
{
352✔
460
  const size_t maxHostNameBufSize = getMaxHostNameSize() + 1;
352✔
461
  std::string hostname;
352✔
462
  hostname.resize(maxHostNameBufSize, 0);
352✔
463

464
  if (gethostname(hostname.data(), maxHostNameBufSize) == -1) {
352!
465
    return std::nullopt;
×
466
  }
×
467

468
  hostname.resize(strlen(hostname.c_str()));
352✔
469
  return std::make_optional(hostname);
352✔
470
}
352✔
471

472
std::string getCarbonHostName()
473
{
175✔
474
  auto hostname = getHostname();
175✔
475
  if (!hostname.has_value()) {
175!
476
    throw std::runtime_error(stringerror());
×
477
  }
×
478

479
  std::replace(hostname->begin(), hostname->end(), '.', '_');
175✔
480
  return *hostname;
175✔
481
}
175✔
482

483
void cleanSlashes(string &str)
484
{
7,377✔
485
  string out;
7,377✔
486
  bool keepNextSlash = true;
7,377✔
487
  for (const auto& value : str) {
138,957✔
488
    if (value == '/') {
138,957✔
489
      if (keepNextSlash) {
9,192✔
490
        keepNextSlash = false;
8,985✔
491
      }
8,985✔
492
      else {
207✔
493
        continue;
207✔
494
      }
207✔
495
    }
9,192✔
496
    else {
129,765✔
497
      keepNextSlash = true;
129,765✔
498
    }
129,765✔
499
    out.append(1, value);
138,750✔
500
  }
138,750✔
501
  str = std::move(out);
7,377✔
502
}
7,377✔
503

504
bool IpToU32(const string &str, uint32_t *ip)
505
{
×
506
  if(str.empty()) {
×
507
    *ip=0;
×
508
    return true;
×
509
  }
×
510

511
  struct in_addr inp;
×
512
  if(inet_aton(str.c_str(), &inp)) {
×
513
    *ip=inp.s_addr;
×
514
    return true;
×
515
  }
×
516
  return false;
×
517
}
×
518

519
string U32ToIP(uint32_t val)
520
{
×
521
  char tmp[17];
×
522
  snprintf(tmp, sizeof(tmp), "%u.%u.%u.%u",
×
523
           (val >> 24)&0xff,
×
524
           (val >> 16)&0xff,
×
525
           (val >>  8)&0xff,
×
526
           (val      )&0xff);
×
527
  return string(tmp);
×
528
}
×
529

530

531
string makeHexDump(const string& str, const string& sep)
532
{
1,630✔
533
  std::array<char, 5> tmp;
1,630✔
534
  string ret;
1,630✔
535
  ret.reserve(static_cast<size_t>(str.size() * (2 + sep.size())));
1,630✔
536

537
  for (char n : str) {
87,080✔
538
    snprintf(tmp.data(), tmp.size(), "%02x", static_cast<unsigned char>(n));
87,080✔
539
    ret += tmp.data();
87,080✔
540
    ret += sep;
87,080✔
541
  }
87,080✔
542
  return ret;
1,630✔
543
}
1,630✔
544

545
string makeBytesFromHex(const string &in) {
9✔
546
  if (in.size() % 2 != 0) {
9✔
547
    throw std::range_error("odd number of bytes in hex string");
3✔
548
  }
3✔
549
  string ret;
6✔
550
  ret.reserve(in.size() / 2);
6✔
551

552
  for (size_t i = 0; i < in.size(); i += 2) {
36✔
553
    const auto numStr = in.substr(i, 2);
33✔
554
    unsigned int num = 0;
33✔
555
    if (sscanf(numStr.c_str(), "%02x", &num) != 1) {
33✔
556
      throw std::range_error("Invalid value while parsing the hex string '" + in + "'");
3✔
557
    }
3✔
558
    ret.push_back(static_cast<uint8_t>(num));
30✔
559
  }
30✔
560

561
  return ret;
3✔
562
}
6✔
563

564
void normalizeTV(struct timeval& tv)
565
{
194,523✔
566
  if(tv.tv_usec > 1000000) {
194,523✔
567
    ++tv.tv_sec;
6,302✔
568
    tv.tv_usec-=1000000;
6,302✔
569
  }
6,302✔
570
  else if(tv.tv_usec < 0) {
188,221✔
571
    --tv.tv_sec;
47,409✔
572
    tv.tv_usec+=1000000;
47,409✔
573
  }
47,409✔
574
}
194,523✔
575

576
struct timeval operator+(const struct timeval& lhs, const struct timeval& rhs)
577
{
10,550✔
578
  struct timeval ret;
10,550✔
579
  ret.tv_sec=lhs.tv_sec + rhs.tv_sec;
10,550✔
580
  ret.tv_usec=lhs.tv_usec + rhs.tv_usec;
10,550✔
581
  normalizeTV(ret);
10,550✔
582
  return ret;
10,550✔
583
}
10,550✔
584

585
struct timeval operator-(const struct timeval& lhs, const struct timeval& rhs)
586
{
94,196✔
587
  struct timeval ret;
94,196✔
588
  ret.tv_sec=lhs.tv_sec - rhs.tv_sec;
94,196✔
589
  ret.tv_usec=lhs.tv_usec - rhs.tv_usec;
94,196✔
590
  normalizeTV(ret);
94,196✔
591
  return ret;
94,196✔
592
}
94,196✔
593

594
pair<string, string> splitField(const string& inp, char sepa)
595
{
737,427✔
596
  pair<string, string> ret;
737,427✔
597
  string::size_type cpos=inp.find(sepa);
737,427✔
598
  if(cpos==string::npos)
737,427✔
599
    ret.first=inp;
337,809✔
600
  else {
399,618✔
601
    ret.first=inp.substr(0, cpos);
399,618✔
602
    ret.second=inp.substr(cpos+1);
399,618✔
603
  }
399,618✔
604
  return ret;
737,427✔
605
}
737,427✔
606

607
int logFacilityToLOG(unsigned int facility)
608
{
×
609
  switch(facility) {
×
610
  case 0:
×
611
    return LOG_LOCAL0;
×
612
  case 1:
×
613
    return(LOG_LOCAL1);
×
614
  case 2:
×
615
    return(LOG_LOCAL2);
×
616
  case 3:
×
617
    return(LOG_LOCAL3);
×
618
  case 4:
×
619
    return(LOG_LOCAL4);
×
620
  case 5:
×
621
    return(LOG_LOCAL5);
×
622
  case 6:
×
623
    return(LOG_LOCAL6);
×
624
  case 7:
×
625
    return(LOG_LOCAL7);
×
626
  default:
×
627
    return -1;
×
628
  }
×
629
}
×
630

631
std::optional<int> logFacilityFromString(std::string facilityStr)
632
{
×
633
  static std::unordered_map<std::string, int> const s_facilities = {
×
634
    {"local0", LOG_LOCAL0},
×
635
    {"log_local0", LOG_LOCAL0},
×
636
    {"local1", LOG_LOCAL1},
×
637
    {"log_local1", LOG_LOCAL1},
×
638
    {"local2", LOG_LOCAL2},
×
639
    {"log_local2", LOG_LOCAL2},
×
640
    {"local3", LOG_LOCAL3},
×
641
    {"log_local3", LOG_LOCAL3},
×
642
    {"local4", LOG_LOCAL4},
×
643
    {"log_local4", LOG_LOCAL4},
×
644
    {"local5", LOG_LOCAL5},
×
645
    {"log_local5", LOG_LOCAL5},
×
646
    {"local6", LOG_LOCAL6},
×
647
    {"log_local6", LOG_LOCAL6},
×
648
    {"local7", LOG_LOCAL7},
×
649
    {"log_local7", LOG_LOCAL7},
×
650
    /* most of these likely make very little sense
651
       for us, but why not? */
652
    {"kern", LOG_KERN},
×
653
    {"log_kern", LOG_KERN},
×
654
    {"user", LOG_USER},
×
655
    {"log_user", LOG_USER},
×
656
    {"mail", LOG_MAIL},
×
657
    {"log_mail", LOG_MAIL},
×
658
    {"daemon", LOG_DAEMON},
×
659
    {"log_daemon", LOG_DAEMON},
×
660
    {"auth", LOG_AUTH},
×
661
    {"log_auth", LOG_AUTH},
×
662
    {"syslog", LOG_SYSLOG},
×
663
    {"log_syslog", LOG_SYSLOG},
×
664
    {"lpr", LOG_LPR},
×
665
    {"log_lpr", LOG_LPR},
×
666
    {"news", LOG_NEWS},
×
667
    {"log_news", LOG_NEWS},
×
668
    {"uucp", LOG_UUCP},
×
669
    {"log_uucp", LOG_UUCP},
×
670
    {"cron", LOG_CRON},
×
671
    {"log_cron", LOG_CRON},
×
672
    {"authpriv", LOG_AUTHPRIV},
×
673
    {"log_authpriv", LOG_AUTHPRIV},
×
674
    {"ftp", LOG_FTP},
×
675
    {"log_ftp", LOG_FTP}
×
676
  };
×
677

678
  toLowerInPlace(facilityStr);
×
679
  auto facilityIt = s_facilities.find(facilityStr);
×
680
  if (facilityIt == s_facilities.end()) {
×
681
    return std::nullopt;
×
682
  }
×
683

684
  return facilityIt->second;
×
685
}
×
686

687
string stripDot(const string& dom)
688
{
671,527✔
689
  if(dom.empty())
671,527✔
690
    return dom;
3✔
691

692
  if(dom[dom.size()-1]!='.')
671,524✔
693
    return dom;
671,077✔
694

695
  return dom.substr(0,dom.size()-1);
447✔
696
}
671,524✔
697

698
int makeIPv6sockaddr(const std::string& addr, struct sockaddr_in6* ret)
699
{
1,277,427✔
700
  if (addr.empty()) {
1,277,427✔
701
    return -1;
16✔
702
  }
16✔
703

704
  string ourAddr(addr);
1,277,411✔
705
  std::optional<uint16_t> port = std::nullopt;
1,277,411✔
706

707
  if (addr[0] == '[') { // [::]:53 style address
1,277,411✔
708
    string::size_type pos = addr.find(']');
67,662✔
709
    if (pos == string::npos) {
67,662!
710
      return -1;
×
711
    }
×
712

713
    ourAddr.assign(addr.c_str() + 1, pos - 1);
67,662✔
714
    if (pos + 1 != addr.size()) { // complete after ], no port specified
67,662✔
715
      if (pos + 2 > addr.size() || addr[pos + 1] != ':') {
67,643!
716
        return -1;
×
717
      }
×
718

719
      try {
67,643✔
720
        auto tmpPort = pdns::checked_stoi<uint16_t>(addr.substr(pos + 2));
67,643✔
721
        port = std::make_optional(tmpPort);
67,643✔
722
      }
67,643✔
723
      catch (const std::out_of_range&) {
67,643✔
724
        return -1;
20✔
725
      }
20✔
726
    }
67,643✔
727
  }
67,662✔
728

729
  ret->sin6_scope_id = 0;
1,277,391✔
730
  ret->sin6_family = AF_INET6;
1,277,391✔
731

732
  if (inet_pton(AF_INET6, ourAddr.c_str(), (void*)&ret->sin6_addr) != 1) {
1,277,391✔
733
    struct addrinfo hints{};
453✔
734
    std::memset(&hints, 0, sizeof(struct addrinfo));
453✔
735
    hints.ai_flags = AI_NUMERICHOST;
453✔
736
    hints.ai_family = AF_INET6;
453✔
737

738
    struct addrinfo* res = nullptr;
453✔
739
    // getaddrinfo has anomalous return codes, anything nonzero is an error, positive or negative
740
    if (getaddrinfo(ourAddr.c_str(), nullptr, &hints, &res) != 0) {
453!
741
      return -1;
453✔
742
    }
453✔
743

744
    memcpy(ret, res->ai_addr, res->ai_addrlen);
×
745
    freeaddrinfo(res);
×
746
  }
×
747

748
  if (port.has_value()) {
1,276,938✔
749
    ret->sin6_port = htons(*port);
67,623✔
750
  }
67,623✔
751

752
  return 0;
1,276,938✔
753
}
1,277,391✔
754

755
int makeIPv4sockaddr(const std::string& str, struct sockaddr_in* ret)
756
{
2,005,455✔
757
  if(str.empty()) {
2,005,455✔
758
    return -1;
5✔
759
  }
5✔
760
  struct in_addr inp;
2,005,450✔
761

762
  string::size_type pos = str.find(':');
2,005,450✔
763
  if(pos == string::npos) { // no port specified, not touching the port
2,005,450✔
764
    if(inet_aton(str.c_str(), &inp)) {
860,319✔
765
      ret->sin_addr.s_addr=inp.s_addr;
860,237✔
766
      return 0;
860,237✔
767
    }
860,237✔
768
    return -1;
82✔
769
  }
860,319✔
770
  if(!*(str.c_str() + pos + 1)) // trailing :
1,145,131!
771
    return -1;
×
772

773
  char *eptr = const_cast<char*>(str.c_str()) + str.size();
1,145,131✔
774
  int port = strtol(str.c_str() + pos + 1, &eptr, 10);
1,145,131✔
775
  if (port < 0 || port > 65535)
1,145,131✔
776
    return -1;
20✔
777

778
  if(*eptr)
1,145,111✔
779
    return -1;
934,906✔
780

781
  ret->sin_port = htons(port);
210,205✔
782
  if(inet_aton(str.substr(0, pos).c_str(), &inp)) {
210,205✔
783
    ret->sin_addr.s_addr=inp.s_addr;
210,204✔
784
    return 0;
210,204✔
785
  }
210,204✔
786
  return -1;
1✔
787
}
210,205✔
788

789
int makeUNsockaddr(const std::string& path, struct sockaddr_un* ret)
790
{
1,394✔
791
  if (path.empty())
1,394✔
792
    return -1;
4✔
793

794
  memset(ret, 0, sizeof(struct sockaddr_un));
1,390✔
795
  ret->sun_family = AF_UNIX;
1,390✔
796
  if (path.length() >= sizeof(ret->sun_path))
1,390!
797
    return -1;
×
798

799
  path.copy(ret->sun_path, sizeof(ret->sun_path), 0);
1,390✔
800
  return 0;
1,390✔
801
}
1,390✔
802

803
//! read a line of text from a FILE* to a std::string, returns false on 'no data'
804
bool stringfgets(FILE* fp, std::string& line)
805
{
4,341,693✔
806
  char buffer[1024];
4,341,693✔
807
  line.clear();
4,341,693✔
808

809
  do {
4,341,954✔
810
    if(!fgets(buffer, sizeof(buffer), fp))
4,341,954✔
811
      return !line.empty();
4,274✔
812

813
    line.append(buffer);
4,337,680✔
814
  } while(!strchr(buffer, '\n'));
4,337,680✔
815
  return true;
4,337,419✔
816
}
4,341,693✔
817

818
bool readFileIfThere(const char* fname, std::string* line)
819
{
356✔
820
  line->clear();
356✔
821
  auto filePtr = pdns::UniqueFilePtr(fopen(fname, "r"));
356✔
822
  if (!filePtr) {
356!
823
    return false;
×
824
  }
×
825
  return stringfgets(filePtr.get(), *line);
356✔
826
}
356✔
827

828
Regex::Regex(const string &expr)
829
{
59✔
830
  if(regcomp(&d_preg, expr.c_str(), REG_ICASE|REG_NOSUB|REG_EXTENDED))
59!
831
    throw PDNSException("Regular expression did not compile");
×
832
}
59✔
833

834
// if you end up here because valgrind told you were are doing something wrong
835
// with msgh->msg_controllen, please refer to https://github.com/PowerDNS/pdns/pull/3962
836
// first.
837
// Note that cmsgbuf should be aligned the same as a struct cmsghdr
838
void addCMsgSrcAddr(struct msghdr* msgh, cmsgbuf_aligned* cmsgbuf, const ComboAddress* source, int itfIndex)
839
{
28,433✔
840
  struct cmsghdr *cmsg = nullptr;
28,433✔
841

842
  if(source->sin4.sin_family == AF_INET6) {
28,433✔
843
    struct in6_pktinfo *pkt;
1✔
844

845
    msgh->msg_control = cmsgbuf;
1✔
846
#if !defined( __APPLE__ )
1✔
847
    /* CMSG_SPACE is not a constexpr on macOS */
848
    static_assert(CMSG_SPACE(sizeof(*pkt)) <= sizeof(*cmsgbuf), "Buffer is too small for in6_pktinfo");
1✔
849
#else /* __APPLE__ */
850
    if (CMSG_SPACE(sizeof(*pkt)) > sizeof(*cmsgbuf)) {
851
      throw std::runtime_error("Buffer is too small for in6_pktinfo");
852
    }
853
#endif /* __APPLE__ */
854
    msgh->msg_controllen = CMSG_SPACE(sizeof(*pkt));
1✔
855

856
    cmsg = CMSG_FIRSTHDR(msgh);
1!
857
    cmsg->cmsg_level = IPPROTO_IPV6;
1✔
858
    cmsg->cmsg_type = IPV6_PKTINFO;
1✔
859
    cmsg->cmsg_len = CMSG_LEN(sizeof(*pkt));
1✔
860

861
    pkt = (struct in6_pktinfo *) CMSG_DATA(cmsg);
1✔
862
    // Include the padding to stop valgrind complaining about passing uninitialized data
863
    memset(pkt, 0, CMSG_SPACE(sizeof(*pkt)));
1✔
864
    pkt->ipi6_addr = source->sin6.sin6_addr;
1✔
865
    pkt->ipi6_ifindex = itfIndex;
1✔
866
  }
1✔
867
  else {
28,432✔
868
#if defined(IP_PKTINFO)
28,432✔
869
    struct in_pktinfo *pkt;
28,432✔
870

871
    msgh->msg_control = cmsgbuf;
28,432✔
872
#if !defined( __APPLE__ )
28,432✔
873
    /* CMSG_SPACE is not a constexpr on macOS */
874
    static_assert(CMSG_SPACE(sizeof(*pkt)) <= sizeof(*cmsgbuf), "Buffer is too small for in_pktinfo");
28,432✔
875
#else /* __APPLE__ */
876
    if (CMSG_SPACE(sizeof(*pkt)) > sizeof(*cmsgbuf)) {
877
      throw std::runtime_error("Buffer is too small for in_pktinfo");
878
    }
879
#endif /* __APPLE__ */
880
    msgh->msg_controllen = CMSG_SPACE(sizeof(*pkt));
28,432✔
881

882
    cmsg = CMSG_FIRSTHDR(msgh);
28,432!
883
    cmsg->cmsg_level = IPPROTO_IP;
28,432✔
884
    cmsg->cmsg_type = IP_PKTINFO;
28,432✔
885
    cmsg->cmsg_len = CMSG_LEN(sizeof(*pkt));
28,432✔
886

887
    pkt = (struct in_pktinfo *) CMSG_DATA(cmsg);
28,432✔
888
    // Include the padding to stop valgrind complaining about passing uninitialized data
889
    memset(pkt, 0, CMSG_SPACE(sizeof(*pkt)));
28,432✔
890
    pkt->ipi_spec_dst = source->sin4.sin_addr;
28,432✔
891
    pkt->ipi_ifindex = itfIndex;
28,432✔
892
#elif defined(IP_SENDSRCADDR)
893
    struct in_addr *in;
894

895
    msgh->msg_control = cmsgbuf;
896
#if !defined( __APPLE__ )
897
    static_assert(CMSG_SPACE(sizeof(*in)) <= sizeof(*cmsgbuf), "Buffer is too small for in_addr");
898
#else /* __APPLE__ */
899
    if (CMSG_SPACE(sizeof(*in)) > sizeof(*cmsgbuf)) {
900
      throw std::runtime_error("Buffer is too small for in_addr");
901
    }
902
#endif /* __APPLE__ */
903
    msgh->msg_controllen = CMSG_SPACE(sizeof(*in));
904

905
    cmsg = CMSG_FIRSTHDR(msgh);
906
    cmsg->cmsg_level = IPPROTO_IP;
907
    cmsg->cmsg_type = IP_SENDSRCADDR;
908
    cmsg->cmsg_len = CMSG_LEN(sizeof(*in));
909

910
    // Include the padding to stop valgrind complaining about passing uninitialized data
911
    in = (struct in_addr *) CMSG_DATA(cmsg);
912
    memset(in, 0, CMSG_SPACE(sizeof(*in)));
913
    *in = source->sin4.sin_addr;
914
#endif
915
  }
28,432✔
916
}
28,433✔
917

918
unsigned int getFilenumLimit(bool hardOrSoft)
919
{
178✔
920
  struct rlimit rlim;
178✔
921
  if(getrlimit(RLIMIT_NOFILE, &rlim) < 0)
178!
922
    unixDie("Requesting number of available file descriptors");
×
923
  return hardOrSoft ? rlim.rlim_max : rlim.rlim_cur;
178!
924
}
178✔
925

926
void setFilenumLimit(unsigned int lim)
927
{
×
928
  struct rlimit rlim;
×
929

930
  if(getrlimit(RLIMIT_NOFILE, &rlim) < 0)
×
931
    unixDie("Requesting number of available file descriptors");
×
932
  rlim.rlim_cur=lim;
×
933
  if(setrlimit(RLIMIT_NOFILE, &rlim) < 0)
×
934
    unixDie("Setting number of available file descriptors");
×
935
}
×
936

937
bool setSocketTimestamps(int fd)
938
{
584✔
939
#ifdef SO_TIMESTAMP
584✔
940
  int on=1;
584✔
941
  return setsockopt(fd, SOL_SOCKET, SO_TIMESTAMP, (char*)&on, sizeof(on)) == 0;
584✔
942
#else
943
  return true; // we pretend this happened.
944
#endif
945
}
584✔
946

947
bool setTCPNoDelay(int sock)
948
{
6,880✔
949
  int flag = 1;
6,880✔
950
  return setsockopt(sock,            /* socket affected */
6,880✔
951
                    IPPROTO_TCP,     /* set option at TCP level */
6,880✔
952
                    TCP_NODELAY,     /* name of option */
6,880✔
953
                    (char *) &flag,  /* the cast is historical cruft */
6,880✔
954
                    sizeof(flag)) == 0;    /* length of option value */
6,880✔
955
}
6,880✔
956

957

958
bool setNonBlocking(int sock)
959
{
155,205✔
960
  int flags=fcntl(sock,F_GETFL,0);
155,205✔
961
  if(flags<0 || fcntl(sock, F_SETFL,flags|O_NONBLOCK) <0)
155,205✔
962
    return false;
×
963
  return true;
155,205✔
964
}
155,205✔
965

966
bool setBlocking(int sock)
967
{
89,269✔
968
  int flags=fcntl(sock,F_GETFL,0);
89,269✔
969
  if(flags<0 || fcntl(sock, F_SETFL,flags&(~O_NONBLOCK)) <0)
89,269✔
970
    return false;
×
971
  return true;
89,269✔
972
}
89,269✔
973

974
bool setReuseAddr(int sock)
975
{
34✔
976
  int tmp = 1;
34✔
977
  if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&tmp, static_cast<unsigned>(sizeof tmp))<0)
34!
978
    throw PDNSException(string("Setsockopt failed: ")+stringerror());
×
979
  return true;
34✔
980
}
34✔
981

982
void setDscp(int sock, unsigned short family, uint8_t dscp)
983
{
2,938✔
984
  int val = 0;
2,938✔
985
  unsigned int len = 0;
2,938✔
986

987
  if (dscp == 0 || dscp > 63) {
2,938!
988
    // No DSCP marking
989
    return;
2,938✔
990
  }
2,938✔
991

992
  if (family == AF_INET) {
×
993
    if (getsockopt(sock, IPPROTO_IP, IP_TOS, &val, &len)<0) {
×
994
      throw std::runtime_error(string("Set DSCP failed: ")+stringerror());
×
995
    }
×
996
    val = (dscp<<2) | (val&0x3);
×
997
    if (setsockopt(sock, IPPROTO_IP, IP_TOS, &val, sizeof(val))<0) {
×
998
      throw std::runtime_error(string("Set DSCP failed: ")+stringerror());
×
999
    }
×
1000
  }
×
1001
  else if (family == AF_INET6) {
×
1002
    if (getsockopt(sock, IPPROTO_IPV6, IPV6_TCLASS, &val, &len)<0) {
×
1003
      throw std::runtime_error(string("Set DSCP failed: ")+stringerror());
×
1004
    }
×
1005
    val = (dscp<<2) | (val&0x3);
×
1006
    if (setsockopt(sock, IPPROTO_IPV6, IPV6_TCLASS, &val, sizeof(val))<0) {
×
1007
      throw std::runtime_error(string("Set DSCP failed: ")+stringerror());
×
1008
    }
×
1009
  }
×
1010
}
×
1011

1012
bool isNonBlocking(int sock)
1013
{
111,621✔
1014
  int flags=fcntl(sock,F_GETFL,0);
111,621✔
1015
  return flags & O_NONBLOCK;
111,621✔
1016
}
111,621✔
1017

1018
bool setReceiveSocketErrors([[maybe_unused]] int sock, [[maybe_unused]] int af)
1019
{
8,908✔
1020
#ifdef __linux__
8,908✔
1021
  int tmp = 1, ret;
8,908✔
1022
  if (af == AF_INET) {
8,909✔
1023
    ret = setsockopt(sock, IPPROTO_IP, IP_RECVERR, &tmp, sizeof(tmp));
8,895✔
1024
  } else {
2,147,485,395✔
1025
    ret = setsockopt(sock, IPPROTO_IPV6, IPV6_RECVERR, &tmp, sizeof(tmp));
2,147,483,655✔
1026
  }
2,147,483,655✔
1027
  if (ret < 0) {
8,908!
1028
    throw PDNSException(string("Setsockopt failed: ") + stringerror());
×
1029
  }
×
1030
#endif
8,908✔
1031
  return true;
8,908✔
1032
}
8,908✔
1033

1034
// Closes a socket.
1035
int closesocket(int socket)
1036
{
49,673✔
1037
  int ret = ::close(socket);
49,673✔
1038
  if(ret < 0 && errno == ECONNRESET) { // see ticket 192, odd BSD behaviour
49,673!
1039
    return 0;
×
1040
  }
×
1041
  if (ret < 0) {
49,673!
1042
    int err = errno;
×
1043
    throw PDNSException("Error closing socket: " + stringerror(err));
×
1044
  }
×
1045
  return ret;
49,673✔
1046
}
49,673✔
1047

1048
bool setCloseOnExec(int sock)
1049
{
46,271✔
1050
  int flags=fcntl(sock,F_GETFD,0);
46,271✔
1051
  if(flags<0 || fcntl(sock, F_SETFD,flags|FD_CLOEXEC) <0)
46,271!
1052
    return false;
×
1053
  return true;
46,271✔
1054
}
46,271✔
1055

1056
#ifdef __linux__
1057
#include <linux/rtnetlink.h>
1058

1059
int getMACAddress(const ComboAddress& ca, char* dest, size_t destLen)
1060
{
2✔
1061
  struct {
2✔
1062
    struct nlmsghdr headermsg;
2✔
1063
    struct ndmsg neighbormsg;
2✔
1064
  } request;
2✔
1065

1066
  std::array<char, 8192> buffer;
2✔
1067

1068
  auto sock = FDWrapper(socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_ROUTE));
2✔
1069
  if (sock.getHandle() == -1) {
2!
1070
    return errno;
×
1071
  }
×
1072

1073
  memset(&request, 0, sizeof(request));
2✔
1074
  request.headermsg.nlmsg_len = NLMSG_LENGTH(sizeof(struct ndmsg));
2✔
1075
  request.headermsg.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
2✔
1076
  request.headermsg.nlmsg_type = RTM_GETNEIGH;
2✔
1077
  request.neighbormsg.ndm_family = ca.sin4.sin_family;
2✔
1078

1079
  while (true) {
2✔
1080
    ssize_t sent = send(sock.getHandle(), &request, sizeof(request), 0);
2✔
1081
    if (sent == -1) {
2!
1082
      if (errno == EINTR) {
×
1083
        continue;
×
1084
      }
×
1085
      return errno;
×
1086
    }
×
1087
    else if (static_cast<size_t>(sent) != sizeof(request)) {
2!
1088
      return EIO;
×
1089
    }
×
1090
    break;
2✔
1091
  }
2✔
1092

1093
  bool done = false;
2✔
1094
  bool foundIP = false;
2✔
1095
  bool foundMAC = false;
2✔
1096
  do {
2✔
1097
    ssize_t got = recv(sock.getHandle(), buffer.data(), buffer.size(), 0);
2✔
1098

1099
    if (got < 0) {
2!
1100
      if (errno == EINTR) {
×
1101
        continue;
×
1102
      }
×
1103
      return errno;
×
1104
    }
×
1105

1106
    size_t remaining = static_cast<size_t>(got);
2✔
1107
    for (struct nlmsghdr* nlmsgheader = reinterpret_cast<struct nlmsghdr*>(buffer.data());
2✔
1108
         done == false && NLMSG_OK (nlmsgheader, remaining);
6!
1109
         nlmsgheader = reinterpret_cast<struct nlmsghdr*>(NLMSG_NEXT(nlmsgheader, remaining))) {
6✔
1110

1111
      if (nlmsgheader->nlmsg_type == NLMSG_DONE) {
6✔
1112
        done = true;
2✔
1113
        break;
2✔
1114
      }
2✔
1115

1116
      auto nd = reinterpret_cast<struct ndmsg*>(NLMSG_DATA(nlmsgheader));
4✔
1117
      auto rtatp = reinterpret_cast<struct rtattr*>(reinterpret_cast<char*>(nd) + NLMSG_ALIGN(sizeof(struct ndmsg)));
4✔
1118
      int rtattrlen = nlmsgheader->nlmsg_len - NLMSG_LENGTH(sizeof(struct ndmsg));
4✔
1119

1120
      if (nd->ndm_family != ca.sin4.sin_family) {
4!
1121
        continue;
×
1122
      }
×
1123

1124
      if (ca.sin4.sin_family == AF_INET6 && ca.sin6.sin6_scope_id != 0 && static_cast<int32_t>(ca.sin6.sin6_scope_id) != nd->ndm_ifindex) {
4!
1125
        continue;
×
1126
      }
×
1127

1128
      for (; done == false && RTA_OK(rtatp, rtattrlen); rtatp = RTA_NEXT(rtatp, rtattrlen)) {
20!
1129
        if (rtatp->rta_type == NDA_DST){
16✔
1130
          if (nd->ndm_family == AF_INET) {
4!
1131
            auto inp = reinterpret_cast<struct in_addr*>(RTA_DATA(rtatp));
4✔
1132
            if (inp->s_addr == ca.sin4.sin_addr.s_addr) {
4!
1133
              foundIP = true;
×
1134
            }
×
1135
          }
4✔
1136
          else if (nd->ndm_family == AF_INET6) {
×
1137
            auto inp = reinterpret_cast<struct in6_addr *>(RTA_DATA(rtatp));
×
1138
            if (memcmp(inp->s6_addr, ca.sin6.sin6_addr.s6_addr, sizeof(ca.sin6.sin6_addr.s6_addr)) == 0) {
×
1139
              foundIP = true;
×
1140
            }
×
1141
          }
×
1142
        }
4✔
1143
        else if (rtatp->rta_type == NDA_LLADDR) {
12✔
1144
          if (foundIP) {
4!
1145
            size_t addrLen = rtatp->rta_len - sizeof(struct rtattr);
×
1146
            if (addrLen > destLen) {
×
1147
              return ENOBUFS;
×
1148
            }
×
1149
            memcpy(dest, reinterpret_cast<const char*>(rtatp) + sizeof(struct rtattr), addrLen);
×
1150
            foundMAC = true;
×
1151
            done = true;
×
1152
            break;
×
1153
          }
×
1154
        }
4✔
1155
      }
16✔
1156
    }
4✔
1157
  }
2✔
1158
  while (done == false);
2!
1159

1160
  return foundMAC ? 0 : ENOENT;
2!
1161
}
2✔
1162
#else
1163
int getMACAddress(const ComboAddress& /* ca */, char* /* dest */, size_t /* len */)
1164
{
1165
  return ENOENT;
1166
}
1167
#endif /* __linux__ */
1168

1169
string getMACAddress(const ComboAddress& ca)
1170
{
×
1171
  string ret;
×
1172
  char tmp[6];
×
1173
  if (getMACAddress(ca, tmp, sizeof(tmp)) == 0) {
×
1174
    ret.append(tmp, sizeof(tmp));
×
1175
  }
×
1176
  return ret;
×
1177
}
×
1178

1179
uint64_t udpErrorStats([[maybe_unused]] const std::string& str)
1180
{
1,965✔
1181
#ifdef __linux__
1,965✔
1182
  ifstream ifs("/proc/net/snmp");
1,965✔
1183
  if (!ifs) {
1,965!
1184
    return 0;
×
1185
  }
×
1186

1187
  string line;
1,965✔
1188
  while (getline(ifs, line)) {
18,550!
1189
    if (boost::starts_with(line, "Udp: ") && isdigit(line.at(5))) {
18,550✔
1190
      vector<string> parts;
1,965✔
1191
      stringtok(parts, line, " \n\t\r");
1,965✔
1192

1193
      if (parts.size() < 7) {
1,965!
1194
        break;
×
1195
      }
×
1196

1197
      if (str == "udp-rcvbuf-errors") {
1,965!
1198
        return std::stoull(parts.at(5));
×
1199
      }
×
1200
      else if (str == "udp-sndbuf-errors") {
1,965✔
1201
        return std::stoull(parts.at(6));
393✔
1202
      }
393✔
1203
      else if (str == "udp-noport-errors") {
1,572✔
1204
        return std::stoull(parts.at(2));
393✔
1205
      }
393✔
1206
      else if (str == "udp-in-errors") {
1,179✔
1207
        return std::stoull(parts.at(3));
393✔
1208
      }
393✔
1209
      else if (parts.size() >= 8 && str == "udp-in-csum-errors") {
786!
1210
        return std::stoull(parts.at(7));
393✔
1211
      }
393✔
1212
      else {
393✔
1213
        return 0;
393✔
1214
      }
393✔
1215
    }
1,965✔
1216
  }
18,550✔
UNCOV
1217
#endif
×
UNCOV
1218
  return 0;
×
1219
}
1,965✔
1220

1221
uint64_t udp6ErrorStats([[maybe_unused]] const std::string& str)
1222
{
1,965✔
1223
#ifdef __linux__
1,965✔
1224
  const std::map<std::string, std::string> keys = {
1,965✔
1225
    { "udp6-in-errors", "Udp6InErrors" },
1,965✔
1226
    { "udp6-recvbuf-errors", "Udp6RcvbufErrors" },
1,965✔
1227
    { "udp6-sndbuf-errors", "Udp6SndbufErrors" },
1,965✔
1228
    { "udp6-noport-errors", "Udp6NoPorts" },
1,965✔
1229
    { "udp6-in-csum-errors", "Udp6InCsumErrors" }
1,965✔
1230
  };
1,965✔
1231

1232
  auto key = keys.find(str);
1,965✔
1233
  if (key == keys.end()) {
1,965!
1234
    return 0;
×
1235
  }
×
1236

1237
  ifstream ifs("/proc/net/snmp6");
1,965✔
1238
  if (!ifs) {
1,965!
1239
    return 0;
×
1240
  }
×
1241

1242
  std::string line;
1,965✔
1243
  while (getline(ifs, line)) {
144,954!
1244
    if (!boost::starts_with(line, key->second)) {
144,954✔
1245
      continue;
142,989✔
1246
    }
142,989✔
1247

1248
    std::vector<std::string> parts;
1,965✔
1249
    stringtok(parts, line, " \n\t\r");
1,965✔
1250

1251
    if (parts.size() != 2) {
1,965!
1252
      return 0;
×
1253
    }
×
1254

1255
    return std::stoull(parts.at(1));
1,965✔
1256
  }
1,965✔
UNCOV
1257
#endif
×
UNCOV
1258
  return 0;
×
1259
}
1,965✔
1260

1261
uint64_t tcpErrorStats(const std::string& /* str */)
1262
{
246✔
1263
#ifdef __linux__
246✔
1264
  ifstream ifs("/proc/net/netstat");
246✔
1265
  if (!ifs) {
246!
1266
    return 0;
×
1267
  }
×
1268

1269
  string line;
246✔
1270
  vector<string> parts;
246✔
1271
  while (getline(ifs,line)) {
492!
1272
    if (line.size() > 9 && boost::starts_with(line, "TcpExt: ") && isdigit(line.at(8))) {
492!
1273
      stringtok(parts, line, " \n\t\r");
246✔
1274

1275
      if (parts.size() < 21) {
246!
1276
        break;
×
1277
      }
×
1278

1279
      return std::stoull(parts.at(20));
246✔
1280
    }
246✔
1281
  }
492✔
1282
#endif
×
1283
  return 0;
×
1284
}
246✔
1285

1286
uint64_t getCPUIOWait(const std::string& /* str */)
1287
{
389✔
1288
#ifdef __linux__
389✔
1289
  ifstream ifs("/proc/stat");
389✔
1290
  if (!ifs) {
389!
1291
    return 0;
×
1292
  }
×
1293

1294
  string line;
389✔
1295
  vector<string> parts;
389✔
1296
  while (getline(ifs, line)) {
389!
1297
    if (boost::starts_with(line, "cpu ")) {
389!
1298
      stringtok(parts, line, " \n\t\r");
389✔
1299

1300
      if (parts.size() < 6) {
389!
1301
        break;
×
1302
      }
×
1303

1304
      return std::stoull(parts[5]);
389✔
1305
    }
389✔
1306
  }
389✔
1307
#endif
×
1308
  return 0;
×
1309
}
389✔
1310

1311
uint64_t getCPUSteal(const std::string& /* str */)
1312
{
389✔
1313
#ifdef __linux__
389✔
1314
  ifstream ifs("/proc/stat");
389✔
1315
  if (!ifs) {
389!
1316
    return 0;
×
1317
  }
×
1318

1319
  string line;
389✔
1320
  vector<string> parts;
389✔
1321
  while (getline(ifs, line)) {
389!
1322
    if (boost::starts_with(line, "cpu ")) {
389!
1323
      stringtok(parts, line, " \n\t\r");
389✔
1324

1325
      if (parts.size() < 9) {
389!
1326
        break;
×
1327
      }
×
1328

1329
      return std::stoull(parts[8]);
389✔
1330
    }
389✔
1331
  }
389✔
1332
#endif
×
1333
  return 0;
×
1334
}
389✔
1335

1336
bool getTSIGHashEnum(const DNSName& algoName, TSIGHashEnum& algoEnum)
1337
{
1,299✔
1338
  if (algoName == g_hmacmd5dnsname_long || algoName == g_hmacmd5dnsname) {
1,299✔
1339
    algoEnum = TSIG_MD5;
1,200✔
1340
  }
1,200✔
1341
  else if (algoName == g_hmacsha1dnsname) {
99✔
1342
    algoEnum = TSIG_SHA1;
76✔
1343
  }
76✔
1344
  else if (algoName == g_hmacsha224dnsname) {
23!
1345
    algoEnum = TSIG_SHA224;
×
1346
  }
×
1347
  else if (algoName == g_hmacsha256dnsname) {
23✔
1348
    algoEnum = TSIG_SHA256;
4✔
1349
  }
4✔
1350
  else if (algoName == g_hmacsha384dnsname) {
19!
1351
    algoEnum = TSIG_SHA384;
×
1352
  }
×
1353
  else if (algoName == g_hmacsha512dnsname) {
19✔
1354
    algoEnum = TSIG_SHA512;
11✔
1355
  }
11✔
1356
  else if (algoName == g_gsstsigdnsname) {
8!
1357
    algoEnum = TSIG_GSS;
×
1358
  }
×
1359
  else {
8✔
1360
     return false;
8✔
1361
  }
8✔
1362
  return true;
1,291✔
1363
}
1,299✔
1364

1365
DNSName getTSIGAlgoName(TSIGHashEnum& algoEnum)
1366
{
135✔
1367
  switch(algoEnum) {
135!
1368
  case TSIG_MD5: return g_hmacmd5dnsname_long;
135!
1369
  case TSIG_SHA1: return g_hmacsha1dnsname;
×
1370
  case TSIG_SHA224: return g_hmacsha224dnsname;
×
1371
  case TSIG_SHA256: return g_hmacsha256dnsname;
×
1372
  case TSIG_SHA384: return g_hmacsha384dnsname;
×
1373
  case TSIG_SHA512: return g_hmacsha512dnsname;
×
1374
  case TSIG_GSS: return g_gsstsigdnsname;
×
1375
  }
135✔
1376
  throw PDNSException("getTSIGAlgoName does not understand given algorithm, please fix!");
×
1377
}
135✔
1378

1379
uint64_t getOpenFileDescriptors(const std::string&)
1380
{
406✔
1381
#ifdef __linux__
406✔
1382
  uint64_t nbFileDescriptors = 0;
406✔
1383
  const auto dirName = "/proc/" + std::to_string(getpid()) + "/fd/";
406✔
1384
  auto directoryError = pdns::visit_directory(dirName, [&nbFileDescriptors]([[maybe_unused]] ino_t inodeNumber, const std::string_view& name) {
25,881✔
1385
    uint32_t num;
25,881✔
1386
    try {
25,881✔
1387
      pdns::checked_stoi_into(num, std::string(name));
25,881✔
1388
      if (std::to_string(num) == name) {
25,881✔
1389
        nbFileDescriptors++;
25,070✔
1390
      }
25,070✔
1391
    } catch (...) {
25,881✔
1392
      // was not a number.
1393
    }
812✔
1394
    return true;
25,882✔
1395
  });
25,881✔
1396
  if (directoryError) {
406!
1397
    return 0U;
×
1398
  }
×
1399
  return nbFileDescriptors;
406✔
1400
#elif defined(__OpenBSD__)
1401
  // FreeBSD also has this in libopenbsd, but I don't know if that's available always
1402
  return getdtablecount();
1403
#else
1404
  return 0U;
1405
#endif
1406
}
406✔
1407

1408
uint64_t getRealMemoryUsage(const std::string&)
1409
{
406✔
1410
#ifdef __linux__
406✔
1411
  ifstream ifs("/proc/self/statm");
406✔
1412
  if(!ifs)
406!
1413
    return 0;
×
1414

1415
  uint64_t size, resident, shared, text, lib, data;
406✔
1416
  ifs >> size >> resident >> shared >> text >> lib >> data;
406✔
1417

1418
  // We used to use "data" here, but it proves unreliable and even is marked "broken"
1419
  // in https://www.kernel.org/doc/html/latest/filesystems/proc.html
1420
  return resident * getpagesize();
406✔
1421
#else
1422
  struct rusage ru;
1423
  if (getrusage(RUSAGE_SELF, &ru) != 0)
1424
    return 0;
1425
  return ru.ru_maxrss * 1024;
1426
#endif
1427
}
406✔
1428

1429

1430
uint64_t getSpecialMemoryUsage(const std::string&)
1431
{
17✔
1432
#ifdef __linux__
17✔
1433
  ifstream ifs("/proc/self/smaps");
17✔
1434
  if(!ifs)
17!
1435
    return 0;
×
1436
  string line;
17✔
1437
  uint64_t bytes=0;
17✔
1438
  string header("Private_Dirty:");
17✔
1439
  while(getline(ifs, line)) {
231,186✔
1440
    if(boost::starts_with(line, header)) {
231,169✔
1441
      bytes += std::stoull(line.substr(header.length() + 1))*1024;
9,261✔
1442
    }
9,261✔
1443
  }
231,169✔
1444
  return bytes;
17✔
1445
#else
1446
  return 0;
1447
#endif
1448
}
17✔
1449

1450
uint64_t getCPUTimeUser(const std::string&)
1451
{
259✔
1452
  struct rusage ru;
259✔
1453
  getrusage(RUSAGE_SELF, &ru);
259✔
1454
  return (ru.ru_utime.tv_sec*1000ULL + ru.ru_utime.tv_usec/1000);
259✔
1455
}
259✔
1456

1457
uint64_t getCPUTimeSystem(const std::string&)
1458
{
259✔
1459
  struct rusage ru;
259✔
1460
  getrusage(RUSAGE_SELF, &ru);
259✔
1461
  return (ru.ru_stime.tv_sec*1000ULL + ru.ru_stime.tv_usec/1000);
259✔
1462
}
259✔
1463

1464
double DiffTime(const struct timespec& first, const struct timespec& second)
1465
{
122✔
1466
  auto seconds = second.tv_sec - first.tv_sec;
122✔
1467
  auto nseconds = second.tv_nsec - first.tv_nsec;
122✔
1468

1469
  if (nseconds < 0) {
122✔
1470
    seconds -= 1;
110✔
1471
    nseconds += 1000000000;
110✔
1472
  }
110✔
1473
  return static_cast<double>(seconds) + static_cast<double>(nseconds) / 1000000000.0;
122✔
1474
}
122✔
1475

1476
double DiffTime(const struct timeval& first, const struct timeval& second)
1477
{
×
1478
  int seconds=second.tv_sec - first.tv_sec;
×
1479
  int useconds=second.tv_usec - first.tv_usec;
×
1480

1481
  if(useconds < 0) {
×
1482
    seconds-=1;
×
1483
    useconds+=1000000;
×
1484
  }
×
1485
  return seconds + useconds/1000000.0;
×
1486
}
×
1487

1488
uid_t strToUID(const string &str)
1489
{
×
1490
  uid_t result = 0;
×
1491
  const char * cstr = str.c_str();
×
1492
  struct passwd * pwd = getpwnam(cstr);
×
1493

1494
  if (pwd == nullptr) {
×
1495
    long long val;
×
1496

1497
    try {
×
1498
      val = stoll(str);
×
1499
    }
×
1500
    catch(std::exception& e) {
×
1501
      throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr).str() );
×
1502
    }
×
1503

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

1508
    result = static_cast<uid_t>(val);
×
1509
  }
×
1510
  else {
×
1511
    result = pwd->pw_uid;
×
1512
  }
×
1513

1514
  return result;
×
1515
}
×
1516

1517
gid_t strToGID(const string &str)
1518
{
×
1519
  gid_t result = 0;
×
1520
  const char * cstr = str.c_str();
×
1521
  struct group * grp = getgrnam(cstr);
×
1522

1523
  if (grp == nullptr) {
×
1524
    long long val;
×
1525

1526
    try {
×
1527
      val = stoll(str);
×
1528
    }
×
1529
    catch(std::exception& e) {
×
1530
      throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr).str() );
×
1531
    }
×
1532

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

1537
    result = static_cast<gid_t>(val);
×
1538
  }
×
1539
  else {
×
1540
    result = grp->gr_gid;
×
1541
  }
×
1542

1543
  return result;
×
1544
}
×
1545

1546
bool isSettingThreadCPUAffinitySupported()
1547
{
×
1548
#ifdef HAVE_PTHREAD_SETAFFINITY_NP
1549
  return true;
1550
#else
1551
  return false;
1552
#endif
1553
}
×
1554

1555
int mapThreadToCPUList([[maybe_unused]] pthread_t tid, [[maybe_unused]] const std::set<int>& cpus)
1556
{
×
1557
#ifdef HAVE_PTHREAD_SETAFFINITY_NP
1558
#  ifdef __NetBSD__
1559
  cpuset_t *cpuset;
1560
  cpuset = cpuset_create();
1561
  for (const auto cpuID : cpus) {
1562
    cpuset_set(cpuID, cpuset);
1563
  }
1564

1565
  return pthread_setaffinity_np(tid,
1566
                                cpuset_size(cpuset),
1567
                                cpuset);
1568
#  else
1569
#    ifdef __FreeBSD__
1570
#      define cpu_set_t cpuset_t
1571
#    endif
1572
  cpu_set_t cpuset;
1573
  CPU_ZERO(&cpuset);
1574
  for (const auto cpuID : cpus) {
×
1575
    CPU_SET(cpuID, &cpuset);
×
1576
  }
1577

1578
  return pthread_setaffinity_np(tid,
1579
                                sizeof(cpuset),
1580
                                &cpuset);
1581
#  endif
1582
#else
1583
  return ENOSYS;
1584
#endif /* HAVE_PTHREAD_SETAFFINITY_NP */
1585
}
×
1586

1587
std::vector<ComboAddress> getResolvers(const std::string& resolvConfPath)
1588
{
90✔
1589
  std::vector<ComboAddress> results;
90✔
1590

1591
  ifstream ifs(resolvConfPath);
90✔
1592
  if (!ifs) {
90!
1593
    return results;
×
1594
  }
×
1595

1596
  string line;
90✔
1597
  while(std::getline(ifs, line)) {
1,166✔
1598
    boost::trim_right_if(line, boost::is_any_of(" \r\n\x1a"));
1,076✔
1599
    boost::trim_left(line); // leading spaces, let's be nice
1,076✔
1600

1601
    string::size_type tpos = line.find_first_of(";#");
1,076✔
1602
    if (tpos != string::npos) {
1,076✔
1603
      line.resize(tpos);
629✔
1604
    }
629✔
1605

1606
    if (boost::starts_with(line, "nameserver ") || boost::starts_with(line, "nameserver\t")) {
1,076✔
1607
      vector<string> parts;
91✔
1608
      stringtok(parts, line, " \t,"); // be REALLY nice
91✔
1609
      for (auto iter = parts.begin() + 1; iter != parts.end(); ++iter) {
182✔
1610
        try {
91✔
1611
          results.emplace_back(*iter, 53);
91✔
1612
        }
91✔
1613
        catch(...)
91✔
1614
        {
91✔
1615
        }
×
1616
      }
91✔
1617
    }
91✔
1618
  }
1,076✔
1619

1620
  return results;
90✔
1621
}
90✔
1622

1623
size_t getPipeBufferSize([[maybe_unused]] int fd)
1624
{
11,203✔
1625
#ifdef F_GETPIPE_SZ
11,203✔
1626
  int res = fcntl(fd, F_GETPIPE_SZ);
11,203✔
1627
  if (res == -1) {
11,203!
1628
    return 0;
×
1629
  }
×
1630
  return res;
11,203✔
1631
#else
1632
  errno = ENOSYS;
1633
  return 0;
1634
#endif /* F_GETPIPE_SZ */
1635
}
11,203✔
1636

1637
bool setPipeBufferSize([[maybe_unused]] int fd, [[maybe_unused]] size_t size)
1638
{
11,203✔
1639
#ifdef F_SETPIPE_SZ
11,203✔
1640
  if (size > static_cast<size_t>(std::numeric_limits<int>::max())) {
11,203!
1641
    errno = EINVAL;
×
1642
    return false;
×
1643
  }
×
1644
  int newSize = static_cast<int>(size);
11,203✔
1645
  int res = fcntl(fd, F_SETPIPE_SZ, newSize);
11,203✔
1646
  if (res == -1) {
11,203✔
1647
    return false;
6,231✔
1648
  }
6,231✔
1649
  return true;
4,972✔
1650
#else
1651
  errno = ENOSYS;
1652
  return false;
1653
#endif /* F_SETPIPE_SZ */
1654
}
11,203✔
1655

1656
DNSName reverseNameFromIP(const ComboAddress& ip)
1657
{
9✔
1658
  if (ip.isIPv4()) {
9✔
1659
    std::string result("in-addr.arpa.");
3✔
1660
    auto ptr = reinterpret_cast<const uint8_t*>(&ip.sin4.sin_addr.s_addr);
3✔
1661
    for (size_t idx = 0; idx < sizeof(ip.sin4.sin_addr.s_addr); idx++) {
15✔
1662
      result = std::to_string(ptr[idx]) + "." + result;
12✔
1663
    }
12✔
1664
    return DNSName(result);
3✔
1665
  }
3✔
1666
  else if (ip.isIPv6()) {
6!
1667
    std::string result("ip6.arpa.");
6✔
1668
    auto ptr = reinterpret_cast<const uint8_t*>(&ip.sin6.sin6_addr.s6_addr[0]);
6✔
1669
    for (size_t idx = 0; idx < sizeof(ip.sin6.sin6_addr.s6_addr); idx++) {
102✔
1670
      std::stringstream stream;
96✔
1671
      stream << std::hex << (ptr[idx] & 0x0F);
96✔
1672
      stream << '.';
96✔
1673
      stream << std::hex << (((ptr[idx]) >> 4) & 0x0F);
96✔
1674
      stream << '.';
96✔
1675
      result = stream.str() + result;
96✔
1676
    }
96✔
1677
    return DNSName(result);
6✔
1678
  }
6✔
1679

1680
  throw std::runtime_error("Calling reverseNameFromIP() for an address which is neither an IPv4 nor an IPv6");
×
1681
}
9✔
1682

1683
std::string makeLuaString(const std::string& in)
1684
{
×
1685
  ostringstream str;
×
1686

1687
  str<<'"';
×
1688

1689
  char item[5];
×
1690
  for (unsigned char n : in) {
×
1691
    if (islower(n) || isupper(n)) {
×
1692
      item[0] = n;
×
1693
      item[1] = 0;
×
1694
    }
×
1695
    else {
×
1696
      snprintf(item, sizeof(item), "\\%03d", n);
×
1697
    }
×
1698
    str << item;
×
1699
  }
×
1700

1701
  str<<'"';
×
1702

1703
  return str.str();
×
1704
}
×
1705

1706
size_t parseSVCBValueList(const std::string &in, vector<std::string> &val) {
733✔
1707
  std::string parsed;
733✔
1708
  auto ret = parseRFC1035CharString(in, parsed);
733✔
1709
  parseSVCBValueListFromParsedRFC1035CharString(parsed, val);
733✔
1710
  return ret;
733✔
1711
};
733✔
1712

1713
#ifdef HAVE_CRYPTO_MEMCMP
1714
#include <openssl/crypto.h>
1715
#else /* HAVE_CRYPTO_MEMCMP */
1716
#ifdef HAVE_SODIUM_MEMCMP
1717
#include <sodium.h>
1718
#endif /* HAVE_SODIUM_MEMCMP */
1719
#endif /* HAVE_CRYPTO_MEMCMP */
1720

1721
bool constantTimeStringEquals(const std::string& a, const std::string& b)
1722
{
2,337✔
1723
  if (a.size() != b.size()) {
2,337✔
1724
    return false;
5✔
1725
  }
5✔
1726
  const size_t size = a.size();
2,332✔
1727
#ifdef HAVE_CRYPTO_MEMCMP
2,332✔
1728
  return CRYPTO_memcmp(a.c_str(), b.c_str(), size) == 0;
2,332✔
1729
#else /* HAVE_CRYPTO_MEMCMP */
1730
#ifdef HAVE_SODIUM_MEMCMP
1731
  return sodium_memcmp(a.c_str(), b.c_str(), size) == 0;
1732
#else /* HAVE_SODIUM_MEMCMP */
1733
  const volatile unsigned char *_a = (const volatile unsigned char *) a.c_str();
1734
  const volatile unsigned char *_b = (const volatile unsigned char *) b.c_str();
1735
  unsigned char res = 0;
1736

1737
  for (size_t idx = 0; idx < size; idx++) {
1738
    res |= _a[idx] ^ _b[idx];
1739
  }
1740

1741
  return res == 0;
1742
#endif /* !HAVE_SODIUM_MEMCMP */
1743
#endif /* !HAVE_CRYPTO_MEMCMP */
1744
}
2,337✔
1745

1746
namespace pdns
1747
{
1748
struct CloseDirDeleter
1749
{
1750
  void operator()(DIR* dir) const noexcept {
490✔
1751
    closedir(dir);
490✔
1752
  }
490✔
1753
};
1754

1755
std::optional<std::string> visit_directory(const std::string& directory, const std::function<bool(ino_t inodeNumber, const std::string_view& name)>& visitor)
1756
{
604✔
1757
  auto dirHandle = std::unique_ptr<DIR, CloseDirDeleter>(opendir(directory.c_str()));
604✔
1758
  if (!dirHandle) {
604✔
1759
    auto err = errno;
114✔
1760
    return std::string("Error opening directory '" + directory + "': " + stringerror(err));
114✔
1761
  }
114✔
1762

1763
  bool keepGoing = true;
490✔
1764
  struct dirent* ent = nullptr;
490✔
1765
  // NOLINTNEXTLINE(concurrency-mt-unsafe): readdir is thread-safe nowadays and readdir_r is deprecated
1766
  while (keepGoing && (ent = readdir(dirHandle.get())) != nullptr) {
30,796!
1767
    // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay: dirent API
1768
    auto name = std::string_view(ent->d_name, strlen(ent->d_name));
30,306✔
1769
    keepGoing = visitor(ent->d_ino, name);
30,306✔
1770
  }
30,306✔
1771

1772
  return std::nullopt;
490✔
1773
}
604✔
1774

1775
UniqueFilePtr openFileForWriting(const std::string& filePath, mode_t permissions, bool mustNotExist, bool appendIfExists)
1776
{
4✔
1777
  int flags = O_WRONLY | O_CREAT;
4✔
1778
  if (mustNotExist) {
4!
1779
    flags |= O_EXCL;
×
1780
  }
×
1781
  else if (appendIfExists) {
4!
1782
    flags |= O_APPEND;
4✔
1783
  }
4✔
1784
  int fileDesc = open(filePath.c_str(), flags, permissions);
4✔
1785
  if (fileDesc == -1) {
4!
1786
    return {};
×
1787
  }
×
1788
  auto filePtr = pdns::UniqueFilePtr(fdopen(fileDesc, appendIfExists ? "a" : "w"));
4!
1789
  if (!filePtr) {
4!
1790
    auto error = errno;
×
1791
    close(fileDesc);
×
1792
    errno = error;
×
1793
    return {};
×
1794
  }
×
1795
  return filePtr;
4✔
1796
}
4✔
1797

1798
}
1799

1800
const char* timestamp(time_t arg, timebuf_t& buf)
1801
{
85✔
1802
  const std::string s_timestampFormat = "%Y-%m-%dT%T";
85✔
1803
  struct tm tmval{};
85✔
1804
  size_t len = strftime(buf.data(), buf.size(), s_timestampFormat.c_str(), localtime_r(&arg, &tmval));
85✔
1805
  if (len == 0) {
85!
1806
    int ret = snprintf(buf.data(), buf.size(), "%lld", static_cast<long long>(arg));
×
1807
    if (ret < 0 || static_cast<size_t>(ret) >= buf.size()) {
×
1808
      buf[0] = '\0';
×
1809
    }
×
1810
  }
×
1811
  return buf.data();
85✔
1812
}
85✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc