Coverage Report

Created: 2024-11-12 06:21

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