Coverage Report

Created: 2023-03-26 07:17

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